/** * The per-thread approval record (lib/approval-record.ts, bin/gstack-approvals): * branch-keyed storage, the secret refusal, the escaped ## Approvals table that * the ship receipt never reads as a citation, idempotent autoplan import, and * the Capy Drive mirror with its "unavailable" state. */ import { afterEach, describe, expect, test } from 'bun:test'; import { spawnSync } from 'node:child_process'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { parseCitations } from '../lib/approval-citations'; import { APPROVALS_TABLE_HEADER, branchKey, buildRow, cell, importAutoplan, pathLabels, readRecord, renderRecord, type StoreLocation } from '../lib/approval-record'; const ROOT = path.resolve(import.meta.dir, '..'); const dirs: string[] = []; const tmp = (prefix: string) => { const d = fs.mkdtempSync(path.join(os.tmpdir(), prefix)); dirs.push(d); return d; }; afterEach(() => { while (dirs.length) fs.rmSync(dirs.pop()!, { recursive: true, force: true }); }); function repo(branch = 'feature/capy-asks'): string { const d = tmp('appr-repo-'); spawnSync('git', ['init', '-q', '-b', branch], { cwd: d, timeout: 30_000 }); return d; } function bin(args: string[], o: { cwd: string; env?: Record }) { const r = spawnSync('bun', [path.join(ROOT, 'bin', 'gstack-approvals'), ...args], { cwd: o.cwd, encoding: 'utf8', timeout: 60_000, env: { ...process.env, GSTACK_CAPY: '', GSTACK_EPHEMERAL: '', GSTACK_APPROVALS_DIR: '', GSTACK_PROJECT_SLUG: 'acme-widgets', ...o.env }, }); return { status: r.status ?? -1, out: r.stdout ?? '', err: r.stderr ?? '' }; } const ADD = ['add', '--ask', 'Approve the plan for the widget fix', '--words', 'rec', '--by', 'Garry (via GStack Minder)', '--scope', 'the reviewed plan, every recommendation']; describe('branch keys', () => { test('one contained segment per exact ref, no collisions between sanitized look-alikes', () => { for (const b of ['feature/x', '../../etc', 'a b', '.hidden', 'x'.repeat(300)]) { const k = branchKey(b); expect(k).not.toContain('/'); expect(k.startsWith('.')).toBe(false); expect(k.length).toBeLessThanOrEqual(71); } expect(branchKey('feature/x')).not.toBe(branchKey('feature-x')); }); }); describe('gstack-approvals add and render', () => { test('a row round-trips into an ## Approvals table under the state root', () => { const cwd = repo(); const state = tmp('appr-state-'); const add = bin(ADD, { cwd, env: { GSTACK_STATE_ROOT: state } }); expect(add.status).toBe(0); expect(add.out).toMatch(/^APPROVAL_RECORDED: a-[0-9a-f]{12} .*\/projects\/acme-widgets\/approvals\/feature-capy-asks-[0-9a-f]{10}\.jsonl$/m); expect(bin(ADD, { cwd, env: { GSTACK_STATE_ROOT: state } }).out).toContain('(already present)'); const r = bin(['render', '--full'], { cwd, env: { GSTACK_STATE_ROOT: state } }); expect(r.status).toBe(0); expect(r.out).toContain('## Approvals'); expect(r.out).toContain('| Date | Asked | Exact words | Outcome | Covers | Still pending |'); expect(r.out.match(/^\| \d{4}-\d{2}-\d{2} \|/gm)?.length).toBe(1); expect(r.out).toContain('“rec” (Garry (via GStack Minder)) | approved |'); }); test('an empty record says so, and the branch flag selects another record', () => { const cwd = repo(); const state = tmp('appr-state-'); expect(bin(['render', '--branch', 'other'], { cwd, env: { GSTACK_STATE_ROOT: state } }).out).toContain('No approvals recorded for branch other.'); }); test('a secret refuses the row, names field and rule, never echoes the text, and writes nothing', () => { const cwd = repo(); const state = tmp('appr-state-'); const secret = 'AKIA' + 'IOSFODNN7EXAMPLQ'; const r = bin(['add', '--ask', 'ok', '--words', `use ${secret} for it ghp_${'a'.repeat(36)}`, '--by', 'g', '--scope', 's'], { cwd, env: { GSTACK_STATE_ROOT: state } }); expect(r.status).toBe(3); expect(r.err).toContain('(APPROVAL_RECORD_SECRET)'); expect(r.err).toContain('field words'); expect(r.err + r.out).not.toContain(secret); expect(fs.existsSync(path.join(state, 'projects'))).toBe(false); }); test('a GitHub Actions run id after a run word is not a phone number, and the record keeps it (GSTA-121)', () => { const cwd = repo(); const state = tmp('appr-state-'); const words = 'Rule-19 grant: re-READY with --no-screen citing screen 40477638211 GREEN at 5619199800a2; gate=40477638210 passed'; const r = bin(['add', '--ask', 'Third rule 19 grant on the GREEN screen', '--words', words, '--by', 'GStack Minder', '--scope', 'one merge'], { cwd, env: { GSTACK_STATE_ROOT: state } }); expect(r.status, r.err).toBe(0); const file = /^APPROVAL_RECORDED: a-[0-9a-f]{12} (.*\.jsonl)$/m.exec(r.out)![1]!; expect(fs.readFileSync(file, 'utf8')).toContain('screen 40477638211 GREEN'); const control = bin(['add', '--ask', 'ok', '--words', 'call me on 40477638211 or +14155550123', '--by', 'g', '--scope', 's'], { cwd, env: { GSTACK_STATE_ROOT: state } }); expect(control.status).toBe(3); expect(control.err).toContain('pii.phone.e164'); }); test("the owner's grant for a stop head whose short sha is all digits records (Free Tests 41667825418, 41766865679)", () => { const cwd = repo(); const state = tmp('appr-state-'); const ask = 'Owner grant: one scoped fix-check after round 2 (review_loop_grant 367120488513)'; const r = bin(['add', '--ask', ask, '--words', 'do it', '--by', 'GStack Minder', '--scope', 'this /ship invocation'], { cwd, env: { GSTACK_STATE_ROOT: state } }); expect(r.status, r.err).toBe(0); const file = /^APPROVAL_RECORDED: a-[0-9a-f]{12} (.*\.jsonl)$/m.exec(r.out)![1]!; expect(fs.readFileSync(file, 'utf8')).toContain('review_loop_grant 367120488513'); const control = bin(['add', '--ask', 'Owner grant (review_loop_grant 367120488513), call 367120488513 first', '--words', 'do it', '--by', 'g', '--scope', 's'], { cwd, env: { GSTACK_STATE_ROOT: state } }); expect(control.status).toBe(3); expect(control.err).toContain('field ask: pii.phone.e164'); }); test('missing fields, bad outcomes and impossible dates are usage errors', () => { const cwd = repo(); const state = tmp('appr-state-'); expect(bin(['add', '--ask', 'x'], { cwd, env: { GSTACK_STATE_ROOT: state } }).err).toContain('APPROVAL_RECORD_INVALID'); expect(bin([...ADD, '--outcome', 'maybe'], { cwd, env: { GSTACK_STATE_ROOT: state } }).status).toBe(2); expect(bin([...ADD, '--date', '2026-02-30'], { cwd, env: { GSTACK_STATE_ROOT: state } }).status).toBe(2); }); test('outside a repository there is no branch to key by', () => { const r = bin(['render'], { cwd: tmp('appr-norepo-'), env: { GSTACK_STATE_ROOT: tmp('appr-state-'), GIT_CEILING_DIRECTORIES: os.tmpdir() } }); expect(r.status).toBe(3); expect(r.err).toContain('(APPROVAL_RECORD_NO_BRANCH)'); }); }); describe('public repositories get no identifying approval text (GST-1160)', () => { const fakeGh = (out: string, code = 0) => { const d = tmp('appr-gh-'); fs.writeFileSync(path.join(d, 'gh'), `#!/bin/sh\nprintf '%s\\n' '${out}'\nexit ${code}\n`, { mode: 0o755 }); return { PATH: `${d}:${process.env.PATH}` }; }; const QUOTE = ['add', '--ask', 'Approve the plan "Qm leak fix" (autoplan run 20261102-qm-77, 4 decisions)', '--words', 'do it, ship the leak fix', '--by', 'Garry (via QM Minder)', '--scope', 'the reviewed plan (sha256 9f2c1e0b7a6d5c4b3a29180716f5e4d3c2b1a0f9e8d7c6b5a4938271605f4e3d)']; const leaks = (out: string) => ['do it, ship the leak fix', '20261102-qm-77', '9f2c1e0b7a6d', 'Garry', 'Qm leak fix'].filter(s => out.includes(s)); for (const [label, env] of [['public', () => fakeGh('PUBLIC')], ['unknown (gh fails)', () => fakeGh('', 1)]] as const) { test(`a ${label} repository renders only that it was approved and an opaque record id`, () => { const cwd = repo(); const state = tmp('appr-state-'); expect(bin(QUOTE, { cwd, env: { GSTACK_STATE_ROOT: state } }).status).toBe(0); const r = bin(['render'], { cwd, env: { GSTACK_STATE_ROOT: state, ...env() } }); expect(r.status, r.err).toBe(0); expect(leaks(r.out)).toEqual([]); expect(r.out).toContain('## Approvals'); expect(r.out).toMatch(/^Approved: yes \(record r-[0-9a-f]{12}\)/m); expect(r.out).not.toContain(APPROVALS_TABLE_HEADER); expect(r.err).toContain('APPROVALS_RENDER: redacted'); }); } test('a private repository keeps the full table, and --full is the explicit override when visibility is unknown', () => { const cwd = repo(); const state = tmp('appr-state-'); expect(bin(QUOTE, { cwd, env: { GSTACK_STATE_ROOT: state } }).status).toBe(0); const priv = bin(['render'], { cwd, env: { GSTACK_STATE_ROOT: state, ...fakeGh('PRIVATE') } }); expect(priv.out).toContain(APPROVALS_TABLE_HEADER); expect(priv.out).toContain('do it, ship the leak fix'); const forced = bin(['render', '--full'], { cwd, env: { GSTACK_STATE_ROOT: state, ...fakeGh('', 1) } }); expect(forced.out).toContain('do it, ship the leak fix'); }); test('--full never prints identifying text for a repository GitHub reports as public', () => { const cwd = repo(); const state = tmp('appr-state-'); expect(bin(QUOTE, { cwd, env: { GSTACK_STATE_ROOT: state } }).status).toBe(0); const r = bin(['render', '--full'], { cwd, env: { GSTACK_STATE_ROOT: state, ...fakeGh('PUBLIC') } }); expect(leaks(r.out)).toEqual([]); expect(r.err).toContain('public'); }); test('a private repository gh picks by default does not unlock the table for a public origin', () => { const cwd = repo(); const state = tmp('appr-state-'); const d = tmp('appr-gh-'); spawnSync('git', ['remote', 'add', 'origin', 'https://github.com/acme/public-widgets.git'], { cwd, timeout: 30_000 }); fs.writeFileSync(path.join(d, 'gh'), '#!/bin/sh\ncase " $* " in *" acme/public-widgets "*) echo PUBLIC ;; *) echo PRIVATE ;; esac\n', { mode: 0o755 }); expect(bin(QUOTE, { cwd, env: { GSTACK_STATE_ROOT: state } }).status).toBe(0); const r = bin(['render'], { cwd, env: { GSTACK_STATE_ROOT: state, GH_REPO: 'acme/private-upstream', PATH: `${d}:${process.env.PATH}` } }); expect(leaks(r.out)).toEqual([]); expect(r.err).toContain('APPROVALS_RENDER: redacted (repository visibility public'); }); test('the redacted record id is stable for the same rows and changes when a row is added', () => { const cwd = repo(); const state = tmp('appr-state-'); const id = () => /record (r-[0-9a-f]{12})/.exec(bin(['render'], { cwd, env: { GSTACK_STATE_ROOT: state, ...fakeGh('PUBLIC') } }).out)![1]; bin(QUOTE, { cwd, env: { GSTACK_STATE_ROOT: state } }); const first = id(); expect(id()).toBe(first); bin(ADD, { cwd, env: { GSTACK_STATE_ROOT: state } }); expect(id()).not.toBe(first); }); describe('full rows never carry a local path in Covers (GST-2048)', () => { const LEDGER = '/home/user/.capy/drive/project-user-gstack-garry-tan/ship-budget/ledger.jsonl'; const SCOPES = [ `spend cap 25000 credits, counted in ${LEDGER}`, 'the plan at ~/.gstack/projects/acme-widgets/plans/fix.md, and /Users/dana/work/widgets/notes.txt', 'the checkout /workspace/gstack/lib/approval-record.ts; C:\\Users\\dana\\gstack\\plan.md', ]; const pathLike = /(?:^|[\s(])(?:~[\\/]|\/[^\s/|]+\/|[A-Za-z]:[\\/])/; const addScoped = (cwd: string, state: string) => SCOPES.forEach((scope, i) => expect(bin(['add', '--ask', `Spend cap ${i}`, '--words', 'do it', '--by', 'Garry (via GStack Minder)', '--scope', scope], { cwd, env: { GSTACK_STATE_ROOT: state } }).status).toBe(0)); const post = (body: string) => { const d = tmp('appr-post-'); const stubs = tmp('appr-post-gh-'); fs.writeFileSync(path.join(stubs, 'gitconfig'), ''); const gitEnv = { ...process.env, GIT_CONFIG_GLOBAL: path.join(stubs, 'gitconfig'), GIT_CONFIG_NOSYSTEM: '1' }; spawnSync('git', ['init', '-q'], { cwd: d, timeout: 30_000, env: gitEnv }); spawnSync('git', ['remote', 'add', 'origin', 'git@github.com:acme/widget.git'], { cwd: d, timeout: 30_000, env: gitEnv }); fs.writeFileSync(path.join(stubs, 'gh'), '#!/bin/sh\ncat >/dev/null\nexit 0\n', { mode: 0o755 }); const file = path.join(d, 'body.md'); fs.writeFileSync(file, body); const r = spawnSync('bun', [path.join(ROOT, 'bin', 'gstack-post'), 'pr-body', '7', '--replace', '--repo-visibility', 'private', '--body-file', file], { cwd: d, encoding: 'utf8', timeout: 60_000, env: { ...gitEnv, PATH: `${stubs}:${process.env.PATH}`, GSTACK_STATE_ROOT: tmp('appr-post-state-') }, }); return { status: r.status ?? -1, err: r.stderr ?? '' }; }; test('a private render labels each path by its file name, and gstack-post finds no internal.user_path in it', () => { const cwd = repo(); const state = tmp('appr-state-'); addScoped(cwd, state); const r = bin(['render'], { cwd, env: { GSTACK_STATE_ROOT: state, ...fakeGh('PRIVATE') } }); expect(r.status, r.err).toBe(0); expect(r.out).toContain(APPROVALS_TABLE_HEADER); const control = post(`## Approvals\n\nCovers ${LEDGER}\n`); expect(control.status, control.err).toBe(0); expect(control.err).toContain('internal.user_path'); const posted = post(r.out); expect(posted.status, posted.err).toBe(0); expect(posted.err).not.toContain('internal.user_path'); const covers = r.out.split('\n').filter(l => /^\| \d{4}-/.test(l)).map(l => l.split(' | ')[4]!); expect(covers).toHaveLength(3); for (const c of covers) expect(c).not.toMatch(pathLike); expect(r.out).toContain('ledger.jsonl'); expect(r.out).toContain('fix.md'); expect(r.out).not.toContain('garry-tan'); expect(r.out).not.toContain('dana'); const list = bin(['list', '--json'], { cwd, env: { GSTACK_STATE_ROOT: state } }); expect(JSON.parse(list.out).rows.map((row: { scope: string }) => row.scope).sort()).toEqual([...SCOPES].sort()); }); test('--redacted on a private repository prints the same bytes as the public render', () => { const cwd = repo(); const state = tmp('appr-state-'); addScoped(cwd, state); const pub = bin(['render'], { cwd, env: { GSTACK_STATE_ROOT: state, ...fakeGh('PUBLIC') } }); const forced = bin(['render', '--redacted'], { cwd, env: { GSTACK_STATE_ROOT: state, ...fakeGh('PRIVATE') } }); expect(forced.status, forced.err).toBe(0); expect(forced.out).toBe(pub.out); expect(forced.out).not.toContain(APPROVALS_TABLE_HEADER); expect(forced.err).toContain('APPROVALS_RENDER: redacted (--redacted'); }); test('--redacted with --full refuses and prints nothing', () => { const cwd = repo(); const state = tmp('appr-state-'); addScoped(cwd, state); for (const args of [['render', '--redacted', '--full'], ['render', '--full', '--redacted']]) { const r = bin(args, { cwd, env: { GSTACK_STATE_ROOT: state, ...fakeGh('PRIVATE') } }); expect(r.status).toBe(2); expect(r.out).toBe(''); expect(r.err).toContain('--redacted and --full conflict'); } }); test('Asked and Still pending get the same labels as Covers; Exact words stays verbatim', () => { const cwd = repo(); const state = tmp('appr-state-'); expect(bin(['add', '--ask', `Raise the cap in ${LEDGER}?`, '--words', 'do it', '--by', 'Garry', '--scope', 'spend cap', '--pending', `settle file:///home/dana/ledger.json`], { cwd, env: { GSTACK_STATE_ROOT: state } }).status).toBe(0); const r = bin(['render'], { cwd, env: { GSTACK_STATE_ROOT: state, ...fakeGh('PRIVATE') } }); expect(r.status, r.err).toBe(0); expect(r.out).toContain('Raise the cap in …/ledger.jsonl?'); expect(r.out).toContain('settle …/ledger.json'); expect(r.out).not.toContain('garry-tan'); expect(r.out).not.toContain('dana'); }); test('paths glued onto a colon or dash and file: in any case are labelled, and gstack-post finds no internal.user_path', () => { const GLUED = ['ledger:/home/u/.capy/drive/project-user-x-y/x.md', 'garry@host:/home/u/x.md', 'file:/home/u/x', 'FILE:///home/u/a/b', 'run-/home/u/a.md']; const cwd = repo(); const state = tmp('appr-state-'); for (const [i, scope] of [...GLUED, 'see https://github.com/o/r'].entries()) expect(bin(['add', '--ask', `Glued path ${i}`, '--words', 'do it', '--by', 'Garry', '--scope', scope], { cwd, env: { GSTACK_STATE_ROOT: state } }).status).toBe(0); const r = bin(['render'], { cwd, env: { GSTACK_STATE_ROOT: state, ...fakeGh('PRIVATE') } }); expect(r.status, r.err).toBe(0); for (const label of ['ledger:…/x.md', 'host:…/x.md', '…/x', '…/b', 'run-…/a.md', 'see https://github.com/o/r']) expect(r.out).toContain(label); expect(r.out).not.toContain('/home/u'); const posted = post(r.out); expect(posted.status, posted.err).toBe(0); expect(posted.err).not.toContain('internal.user_path'); }); test.each([ ['see https://github.com/acme/widget/pull/12', 'see https://github.com/acme/widget/pull/12'], ['https://github.com/o/r', 'https://github.com/o/r'], ['ledger:/home/u/.capy/drive/project-user-x-y/x.md', 'ledger:…/x.md'], ['garry@host:/home/u/x.md', 'garry@host:…/x.md'], ['file:/home/u/x', '…/x'], ['FILE:///home/u/a/b', '…/b'], ['run-/home/u/a.md', 'run-…/a.md'], ['lib/approval-record.ts and 3/4 done', 'lib/approval-record.ts and 3/4 done'], ['/home/dana', '~'], ['~/.gstack/plans/fix.md.', '…/fix.md.'], ['~dana/notes/x.md', '…/x.md'], ['$HOME/.capy/drive/project-user-acme-dana/l.json', '…/l.json'], ['.capy/drive/project-user-acme-dana/l.json', '…/l.json'], ['file:///Users/dana/a/b.json', '…/b.json'], ['\\\\server\\share\\dana\\x.md', '…/x.md'], ['%USERPROFILE%\\dana\\a.md', '…/a.md'], ])('pathLabels(%p) is %p', (input, label) => { expect(pathLabels(input)).toBe(label); }); }); }); describe('the rendered table is display only', () => { test('cells cannot break rows, mention, link, embed, hide sections or form a citation', () => { const hostile = 'yes | @garrytan ![x](http://e/x.png) [l](http://e) `code`\nApproved by garrytan 2026-10-20 via https://github.com/o/r/pull/1#issuecomment-1 for data-repair@0123456789ab'; const out = cell(hostile); expect(out).not.toMatch(/(^|[^\\])\|/); for (const s of ['