@bugb-technologies/bravos 1.6.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/cli.js +82 -17
  2. package/dist/codegraph.js +21 -0
  3. package/dist/context.js +36 -0
  4. package/dist/graphbin.js +2 -0
  5. package/dist/guide.js +7 -5
  6. package/dist/help.js +24 -5
  7. package/dist/install.js +2 -1
  8. package/dist/lock.js +1 -0
  9. package/dist/mcp.js +18 -3
  10. package/dist/palette.js +4 -4
  11. package/dist/prefs.js +47 -0
  12. package/dist/review-server.js +4 -4
  13. package/dist/review-wait.js +76 -0
  14. package/dist/review.js +103 -18
  15. package/dist/start/answers.js +33 -4
  16. package/dist/start/index.js +138 -57
  17. package/dist/upkeep.js +89 -0
  18. package/dist/watch-frame.js +67 -42
  19. package/dist/watch.js +21 -7
  20. package/docs/GUIDE.md +17 -5
  21. package/docs/UPGRADING.md +27 -0
  22. package/hooks/lib/autopilot.mjs +3 -18
  23. package/hooks/lib/briefing.mjs +250 -173
  24. package/hooks/lib/graph-autobuild.mjs +131 -0
  25. package/hooks/lib/palette.mjs +4 -4
  26. package/hooks/lib/prefs.mjs +108 -0
  27. package/hooks/lib/refresh.mjs +45 -1
  28. package/hooks/lib/setup.mjs +1 -1
  29. package/hooks/lib/snapshot.mjs +19 -1
  30. package/hooks/session-start.mjs +29 -2
  31. package/package.json +1 -1
  32. package/skills/bravos/SKILL.md +4 -3
  33. package/skills/bravos-annotate/SKILL.md +2 -2
  34. package/skills/bravos-context/SKILL.md +7 -6
  35. package/skills/bravos-env/SKILL.md +2 -2
  36. package/skills/bravos-env/scope.example.yaml +2 -1
  37. package/skills/bravos-prove/SKILL.md +2 -2
  38. package/skills/bravos-recheck/SKILL.md +1 -1
  39. package/skills/bravos-resync/SKILL.md +1 -1
  40. package/skills/bravos-ship/SKILL.md +1 -1
  41. package/skills/bravos-templatize/SKILL.md +1 -1
  42. package/templates/review/review.html +369 -124
package/dist/cli.js CHANGED
@@ -11,7 +11,7 @@ import { writeCursorPointer } from './cursor.js';
11
11
  import { writeOmpExtension } from './omp.js';
12
12
  import { homeOf, installGlobal } from './global.js';
13
13
  import { uninstall } from './uninstall.js';
14
- import { checkKind, newToken, readAllAnswers, readDraft, renderReview, summarize, writePage } from './review.js';
14
+ import { checkKind, newToken, prepareReview, readAllAnswers, readDraft, renderReview, summarize, writePage } from './review.js';
15
15
  import { addSource, checkSources, declineContext, gateFor, installPrePush, listSources, updateSource } from './context.js';
16
16
  import { formatRules, gatherRules } from './rules.js';
17
17
  import { spawn as spawnChild, spawnSync } from 'node:child_process';
@@ -538,7 +538,7 @@ export function buildProgram(io, result) {
538
538
  }));
539
539
  program
540
540
  .command('graph [question] [args...]')
541
- .description('Ask the code graph (Team plan): `graph build [DIR] [--scip MODE]` indexes a repository; `graph <question> [args] --json` asks it (attack-surface, entry-points, callers <file::symbol>, reachable-sinks, call-chain, …; the same answers as the codegraph_ MCP tools); `graph --json` lists every question this machine\'s binary answers.')
541
+ .description('Ask the code graph (Team plan): `graph build [DIR] [--scip MODE]` indexes a repository; `graph <question> [args] --json` asks it (attack-surface, entry-points, callers <file::symbol>, reachable-sinks, call-chain, …; the same answers as the codegraph_ MCP tools); `graph mcp` serves those tools over MCP on stdio (what .mcp.json registers); `graph --json` lists every question this machine\'s binary answers.')
542
542
  .option('-C, --dir <dir>', 'the repository (default: the current directory)')
543
543
  .option('--json', 'print the answer as JSON')
544
544
  .option('--scip <mode>', 'build: how the type checkers run — no-exec (default), auto, trusted, isolate, off')
@@ -557,6 +557,11 @@ export function buildProgram(io, result) {
557
557
  throw new BravosError(L.refusal(lic, 'codegraph', `bravos graph ${question ?? ''}`.trim()));
558
558
  }
559
559
  const root = dirArg(opts.dir ?? (question === 'build' && args[0] && !args[0].startsWith('--') ? args.shift() : undefined));
560
+ // The server .mcp.json registers: stdio is the agent's, so nothing else is written to stdout.
561
+ if (question === 'mcp') {
562
+ result.code = await graph.serveMcp(root, io.env);
563
+ return;
564
+ }
560
565
  if (question === 'build') {
561
566
  const r = graph.build(root, io.env, { scip: opts.scip, mode: opts.mode, json: opts.json });
562
567
  lines.push((r.stdout || r.stderr).trim());
@@ -751,6 +756,33 @@ export function buildProgram(io, result) {
751
756
  else
752
757
  throw new BravosError(`unknown context action '${action}'; use add, update, list, check, gate or decline`);
753
758
  }));
759
+ // @comment -- "bravos upkeep: what has fallen behind the installed bravos, here and on this machine: the repository's copies of the skills and hooks (bravos sync), and staged bundles older than this version pins (bravos setup). Read-only, no network, free; the session hook asks it at every start so the agent can run those two commands itself."
760
+ program
761
+ .command('upkeep [dir]')
762
+ .description('Say what is behind the installed bravos: this repository\'s copies of the skills and hooks (fixed by bravos sync) and staged bundles older than this version pins (fixed by bravos setup). Read-only; no network; free; runs no model.')
763
+ .option('--json', 'print bravos.upkeep/v1')
764
+ .action((dir, opts) => guardedAsync(async (lines) => {
765
+ const { gatherUpkeep, formatUpkeep } = await import('./upkeep.js');
766
+ const u = await gatherUpkeep(dirArg(dir), io.env);
767
+ lines.push(...(opts.json ? [JSON.stringify(u)] : formatUpkeep(u)));
768
+ }));
769
+ // @comment -- "bravos prefs: what this person told Bravos once so no session asks again. `prefs get` shows it; `prefs set commits <commit|leave|ask> --by <name>` records the answer about committing Bravos's own files. Kept under the git directory of this clone, never committed."
770
+ program
771
+ .command('prefs <action> [args...]')
772
+ .description('Your standing answers for this clone, kept under its git directory and never committed: `prefs get` shows them; `prefs set commits <commit|leave|ask> --by "<your name>"` says whether your agent commits Bravos\'s own files (annotations, intent, definitions, tests) without asking, always leaves them for you, or asks each session. Free; runs no model.')
773
+ .option('-C, --dir <dir>', 'the repository (default: the current directory)')
774
+ .option('--by <name>', 'set: whose answer this is')
775
+ .option('--json', 'get: print JSON')
776
+ .action((action, args, opts) => guardedAsync(async (lines) => {
777
+ const { getPrefs, setCommits } = await import('./prefs.js');
778
+ const dir = dirArg(opts.dir);
779
+ if (action === 'get' && args.length === 0)
780
+ lines.push(...(await getPrefs(dir, io.env, !!opts.json)));
781
+ else if (action === 'set' && args[0] === 'commits' && args.length === 2)
782
+ lines.push(...(await setCommits(dir, args[1], opts.by, io.env)));
783
+ else
784
+ throw new BravosError('usage: bravos prefs get [--json] | bravos prefs set commits <commit|leave|ask> --by "<your name>"');
785
+ }));
754
786
  // @comment -- "bravos rules: the design rules (INV-n in the intent, each a #inv- threat) with where the code enforces each and what testing has shown. Read-only and free; runs guardlink parse and hypothesis list, no model."
755
787
  program
756
788
  .command('rules [dir]')
@@ -767,6 +799,7 @@ export function buildProgram(io, result) {
767
799
  .option('--no-serve', 'write the page as a file instead of serving it; Save then downloads the answers')
768
800
  .option('--no-open', 'do not open a browser, only print the URL')
769
801
  .option('--share', 'render the page for a shared claude.ai artifact (Claude Code only; the agent publishes it)')
802
+ .option('--wait [seconds]', 'serve the page, then wait until the person presses Done and print everyone\'s answers; after the wait (default 90 seconds) it says "review: waiting" and exits 0, and running it again keeps waiting on the same page')
770
803
  .action((kind, dir, opts) => guardedAsync(async (lines) => {
771
804
  const root = dirArg(dir);
772
805
  checkKind(kind);
@@ -777,7 +810,7 @@ export function buildProgram(io, result) {
777
810
  return;
778
811
  }
779
812
  if (opts.share) {
780
- const rel = writePage(root, `${kind}-share`, await renderReview(draft, { kind: 'artifact' }));
813
+ const rel = writePage(root, `${kind}-share`, await renderReview(await prepareReview(root, draft), { kind: 'artifact' }));
781
814
  lines.push(`Share page: ${rel}`);
782
815
  lines.push('Sharing publishes your security intent to claude.ai, private until you share the link; teammates need access there.');
783
816
  lines.push('In Claude Code: publish that file with the Artifact tool and capabilities {db: {}}; share the link with the team.');
@@ -786,24 +819,56 @@ export function buildProgram(io, result) {
786
819
  return;
787
820
  }
788
821
  if (opts.serve === false) {
789
- const rel = writePage(root, kind, await renderReview(draft, { kind: 'file' }));
790
- lines.push(`Review page: ${rel} (Save downloads your answers; put them in .guardlink/${kind}-answers/ and commit)`);
822
+ const rel = writePage(root, kind, await renderReview(await prepareReview(root, draft), { kind: 'file' }));
823
+ lines.push(`Review page: ${rel} (includes available cited document text; Save downloads your answers; put them in .guardlink/${kind}-answers/ and commit)`);
791
824
  if (opts.open !== false)
792
825
  openInBrowser(pathJoin(root, rel), io.env);
793
826
  return;
794
827
  }
795
- const port = await freePort();
796
- const token = newToken();
797
- const child = spawnChild(process.execPath, [pathJoin(pathDirname(fileURLToPath(import.meta.url)), 'review-server.js'), root, kind, token, String(port)], { detached: true, stdio: 'ignore' });
798
- child.unref();
799
- const url = `http://127.0.0.1:${port}/?t=${token}`;
800
- if (!(await waitUp(url)))
801
- throw new BravosError('the review server did not start; try bravos review --no-serve');
802
- lines.push(`Review page: ${url}`);
803
- lines.push(`Answers save to .guardlink/${kind}-answers/<name>.json. Teammates run bravos review ${kind} after pulling. The page stops on Done or after 30 minutes idle.`);
804
- lines.push(`When everyone is done: bravos review ${kind} --summary`);
805
- if (opts.open !== false)
806
- openInBrowser(url, io.env);
828
+ // @comment -- "With --wait the command stays until the person presses Done (the page's server exits), then prints the answers, so an agent continues without anyone typing 'done'. What it prints before waiting goes out at once, because the agent's shell shows nothing until the command ends otherwise. A page already open for this review is waited on, never opened twice."
829
+ const RW = await import('./review-wait.js');
830
+ let waitFor = null;
831
+ if (opts.wait !== undefined) {
832
+ try {
833
+ waitFor = RW.waitSeconds(opts.wait);
834
+ }
835
+ catch (e) {
836
+ throw new BravosError(e instanceof Error ? e.message : String(e));
837
+ }
838
+ }
839
+ const commonDir = (await (await import('./prefs.js')).prefsLib()).gitCommonDir(root, io.env);
840
+ const say = (l) => (waitFor === null ? lines.push(l) : io.stdout(l));
841
+ let live = waitFor === null ? null : RW.readLive(commonDir, kind);
842
+ if (live)
843
+ say(`Review page: ${live.url} (already open; waiting for Done)`);
844
+ else {
845
+ const port = await freePort();
846
+ const token = newToken();
847
+ const child = spawnChild(process.execPath, [pathJoin(pathDirname(fileURLToPath(import.meta.url)), 'review-server.js'), root, kind, token, String(port)], { detached: true, stdio: 'ignore' });
848
+ child.unref();
849
+ const url = `http://127.0.0.1:${port}/?t=${token}`;
850
+ if (!(await waitUp(url)))
851
+ throw new BravosError('the review server did not start; try bravos review --no-serve');
852
+ if (child.pid) {
853
+ live = { pid: child.pid, port, url };
854
+ RW.writeLive(commonDir, kind, live);
855
+ }
856
+ say(`Review page: ${url}`);
857
+ say(`Answers save to .guardlink/${kind}-answers/<name>.json. Teammates run bravos review ${kind} after pulling. The page stops on Done or after 30 minutes idle.`);
858
+ if (waitFor === null)
859
+ lines.push(`When everyone is done: bravos review ${kind} --summary`);
860
+ if (opts.open !== false)
861
+ openInBrowser(url, io.env);
862
+ }
863
+ if (waitFor === null || !live)
864
+ return;
865
+ if (!(await RW.waitGone(live.pid, waitFor * 1000))) {
866
+ lines.push(`review: waiting — the page is still open. Run bravos review ${kind} --wait again to keep waiting; it will not open a second page.`);
867
+ return;
868
+ }
869
+ RW.clearLive(commonDir, kind);
870
+ const { files, skipped } = readAllAnswers(root, draft);
871
+ lines.push(files.length ? 'review: done' : 'review: closed with no answers saved', summarize(draft, files, skipped));
807
872
  }));
808
873
  program
809
874
  .command('next [dir]')
package/dist/codegraph.js CHANGED
@@ -52,6 +52,27 @@ export function build(root, env, opts = {}) {
52
52
  const r = spawnSync(bin, args, { cwd: root, env: graphEnv(env), encoding: 'utf8', timeout: opts.timeoutMs ?? 3 * 600 * 1000, maxBuffer: 64 * 1024 * 1024 });
53
53
  return { status: r.status, stdout: r.stdout ?? '', stderr: r.stderr ?? '' };
54
54
  }
55
+ // @comment -- "bravos graph mcp: runs codegraph-mcp for this repository with the terminal's own stdin, stdout and stderr and the graph store in its environment, and resolves with its exit code. This is what .mcp.json registers, so an agent's MCP client talks to the server through this CLI and the entry holds no path. Nothing is printed here: stdout belongs to the protocol. A signal to this process is passed on, and the server also stops when its stdin closes."
56
+ export function serveMcp(root, env) {
57
+ const bin = graphBin('codegraph-mcp', env);
58
+ if (!bin)
59
+ throw new BravosError('codegraph-mcp is not installed: bravos setup --codegraph fetches it (on the Team plan)');
60
+ return new Promise((done) => {
61
+ const child = spawn(bin, ['--project-path', root], { cwd: root, env: graphEnv(env), stdio: 'inherit' });
62
+ const pass = (sig) => () => child.kill(sig);
63
+ const onInt = pass('SIGINT');
64
+ const onTerm = pass('SIGTERM');
65
+ process.on('SIGINT', onInt);
66
+ process.on('SIGTERM', onTerm);
67
+ const finish = (code) => {
68
+ process.off('SIGINT', onInt);
69
+ process.off('SIGTERM', onTerm);
70
+ done(code);
71
+ };
72
+ child.on('error', () => finish(1));
73
+ child.on('exit', (code, sig) => finish(code ?? (sig ? 1 : 0)));
74
+ });
75
+ }
55
76
  export class GraphUnavailable extends BravosError {
56
77
  constructor(message) {
57
78
  super(message);
package/dist/context.js CHANGED
@@ -80,6 +80,42 @@ function loadIndex(root, L) {
80
80
  throw new BravosError([`${L.INDEX_PATH} needs fixing before anything is added to it:`, ...parsed.problems.map((p) => ` ${p.message}`), 'bravos context check shows the same list.'].join('\n'));
81
81
  return parsed.sources;
82
82
  }
83
+ // @comment -- "Only the local review includes document bodies. Use the context store's regular-file reader, match the recorded hash and recheck the exact bytes before displaying them. The draft can cite an id, never choose a path. Keep the total payload bounded even in a large store."
84
+ // @mitigates #context-sources against #untrusted-index-path using #derived-source-path -- "A citation selects an indexed source by id. Its Markdown file must resolve to its own location under the store and match the recorded digest."
85
+ export async function reviewSources(root, cited) {
86
+ if (!cited.size)
87
+ return [];
88
+ const lib = await contextLib();
89
+ const reader = lib.treeReader(root);
90
+ const index = reader.read(lib.INDEX_PATH);
91
+ if (!index)
92
+ return [];
93
+ const parsed = lib.parseIndex(index.toString('utf8'));
94
+ if (parsed.problems.length)
95
+ return [];
96
+ const names = reader.list(lib.SOURCES_DIR).map((entry) => entry.name);
97
+ const who = whoAmI(process.env);
98
+ const docs = [];
99
+ let remaining = 8 * 1024 * 1024;
100
+ for (const { id, title, kind, bytes, sha256 } of parsed.sources) {
101
+ if (!cited.has(id) || bytes > Math.min(remaining, lib.MAX_SOURCE_BYTES))
102
+ continue;
103
+ const name = lib.fileFor(id, names);
104
+ const data = name ? reader.read(`${lib.SOURCES_DIR}/${name}`) : null;
105
+ if (!data || data.length !== bytes || lib.sha256(data) !== sha256)
106
+ continue;
107
+ try {
108
+ vet(Buffer.from(title), lib, who, id);
109
+ const text = vet(data, lib, who, id);
110
+ docs.push({ id, title, kind, sha256, text });
111
+ remaining -= bytes;
112
+ }
113
+ catch {
114
+ // The review still shows the citation. Only verified, safe text may accompany it.
115
+ }
116
+ }
117
+ return docs;
118
+ }
83
119
  function writeAtomic(abs, data) {
84
120
  const tmp = `${abs}.writing-${process.pid}`;
85
121
  writeFileSync(tmp, data, { mode: 0o644 });
package/dist/graphbin.js CHANGED
@@ -132,5 +132,7 @@ export function graphStoreDir(env = process.env) {
132
132
  return null;
133
133
  }
134
134
  }
135
+ // @comment -- "True for a codegraph-mcp entry written by full path into this CLI's staged bundle ($BRAVOS_HOME/codegraph/<version>/<target>/codegraph-mcp). Such a path exists only on the machine that wrote it and changes with every bundle upgrade, so in a committed file it is both a local path and a broken entry for everyone else."
136
+ export const isStagedGraphCommand = (command) => typeof command === 'string' && /^(?:\/|[A-Za-z]:[\\/]).*[\\/]codegraph[\\/][^\\/]+[\\/][^\\/]+[\\/]codegraph-mcp$/.test(command);
135
137
  /** True for a codegraph-mcp entry bravos registers by full path into a bravos install, which goes stale when that install is replaced. */
136
138
  export const isInstallGraphCommand = (command) => typeof command === 'string' && /[\\/]bravos[\\/]_graph[\\/]bin[\\/]codegraph-mcp$/.test(command);
package/dist/guide.js CHANGED
@@ -37,7 +37,7 @@ export const GUIDE_TOPICS = [
37
37
  {
38
38
  name: 'Installing',
39
39
  body: [
40
- 'npm install -g @bugb-technologies/bravos (Node 20 or newer), then bravos start: a guided setup that asks one question at a time (colours, licence, tools, repository, AI tools, PR checks, a scheduled run, how testing is allowed), shows every change, and writes nothing until you choose Apply. It ends with the one thing to type in your agent.', 'By hand instead: bravos account activate signs you in once in the browser and writes the licence — a 30-day Team trial when the account has no plan; skip it to stay on Free — bravos init in a repository writes the skills, hooks and MCP wiring, and bravos setup puts the analyzer and the code graph on the machine (Team plan). guardlink and cxg come from bravos setup --tools -y, or npm and cargo by hand. If you used the Python bravos, rename its command so bravos means this one: mv ~/.local/bin/bravos ~/.local/bin/bravos-py (this CLI still finds its code graph and analyzer), or remove it with pipx or uv.',
40
+ 'npm install -g @bugb-technologies/bravos (Node 20 or newer), then bravos start: a guided setup that asks one question at a time (colours, licence, tools, repository, AI tools, PR checks, a scheduled run, how testing is allowed), shows every change, and writes nothing until you choose Apply. Then open your agent and say anything: Bravos begins with what the app is for and goes on to your code once you confirm (where the agent runs no hooks, it tells you the one thing to type).', 'By hand instead: bravos account activate signs you in once in the browser and writes the licence — a 30-day Team trial when the account has no plan; skip it to stay on Free — bravos init in a repository writes the skills, hooks and MCP wiring, and bravos setup puts the analyzer and the code graph on the machine (Team plan). guardlink and cxg come from bravos setup --tools -y, or npm and cargo by hand. If you used the Python bravos, rename its command so bravos means this one: mv ~/.local/bin/bravos ~/.local/bin/bravos-py (this CLI still finds its code graph and analyzer), or remove it with pipx or uv.',
41
41
  ],
42
42
  },
43
43
  {
@@ -45,7 +45,7 @@ export const GUIDE_TOPICS = [
45
45
  body: [
46
46
  'Run bravos next in a shell (free): it shows which of the nine steps are done here, in the order they build on each other — the code graph first (a machine step every later skill reads), then what the app intends, annotation coverage, SAST (which reads the annotations), how findings are proven and a test target, then the gates (autopilot, the pre-PR gate, CI, cheap to switch on any time) — what each unlocks, and the exact command for the next one. The banner shows the next step too, and every harness gives it to the agent, which offers a few starts the first time and suggests the next step at natural moments.',
47
47
  'Or just ask the agent "help me get started" (or run /bravos, $bravos in Codex): it gives a short tour fitted to this repo. BRAVOS_COACH=off stops the coaching; the Setup line stays.',
48
- 'Keep bravos watch running in a second terminal pane beside your agent (free, read-only, no model): the setup score, open and confirmed exposures, what to test next, stale claims and autopilot nudges, redrawn within seconds of a change. It also shows the hypothesis ledger, boundaries, the model\'s size, the code graph\'s call resolution and entry points, and the branch\'s commits. Keys: n copies the next command, r opens the intent review, d the dashboard (bravos dashboard), g asks the code graph, t shows test-next, i shows the recorded intent, u refreshes now, j and k scroll, q quits. Three columns from 150 wide, two from 110, one in an 80-column split.',
48
+ 'Keep bravos watch running in a second terminal pane beside your agent (free, read-only, no model): the setup score, open and confirmed exposures, what to test next, stale claims and autopilot nudges, redrawn within seconds of a change. It also shows the hypothesis ledger, boundaries, the model\'s size, the code graph\'s call resolution and entry points, and the branch\'s commits. Keys: n copies the next command, r opens the intent review, d the dashboard (bravos dashboard), g asks the code graph, t shows test-next, i shows the recorded intent, a opens the full text of retained activity, u refreshes now, j and k scroll, q quits. Three columns from 150 wide, two from 110, one in an 80-column split.',
49
49
  ],
50
50
  },
51
51
  {
@@ -117,19 +117,21 @@ export const GUIDE_TOPICS = [
117
117
  { name: 'See which design rules hold', skills: ['bravos', 'bravos-recheck'], body: ['bravos rules lists every rule your design states (INV-n in the intent) with its status: broken (a test got through), retest due (the code under it changed since it was tested), unguarded (it can break somewhere and nothing stops it), guarded but untested, not placed (no code is tied to it yet), or holds (a test tried and was refused everywhere it is enforced). Each line names the document the rule came from and the places it is enforced. bravos dashboard shows the same as its Design rules tab, worst first, beside GuardLink\'s threat model. Free, read-only, no model; --json prints bravos.rules/v1. On the Team plan the pre-PR check and the PR workflow hold a pull request that changes a file a holding rule is enforced in (the check, or the role table that grants the permission) after that rule was last tested, until its test is replayed or the PR body names the rule; the after-edit note says the same while you work.'] },
118
118
  { name: 'Context comes first', skills: ['bravos-context', 'bravos-annotate'], body: ['Threat-modelling starts only when a named person has confirmed what the product intends: bravos-annotate, campaigns and the nightly workflows wait until at least one item in .guardlink/intent.md is confirmed (run bravos-context; it asks for your design documents and a few decisions). A team that chooses to go without records that under a name, bravos context decline --by "<name>", which is committed like the intent; a coding agent is told never to decline for you. bravos context gate says which state a repository is in. Rechecks, retests and the ship check are not held back: they maintain a model that already exists.'] },
119
119
  { name: 'Threat-model someone else\'s project', skills: ['bravos-context', 'bravos-annotate'], body: ['bravos-context assumes you are researching software you do not own (an open-source project, a vendor\'s code): it drafts the intent from upstream\'s own docs with links and asks only the scope decisions — which configuration to rate against (shipped defaults or the hardened setup upstream recommends), single organisation or multi-tenant, which attackers are in scope, and the intended-looking behaviours upstream does not document. intent.md records them as Assumptions, and severities are rated against them. Say "this is our product" for the owner interview instead.'] },
120
- { name: 'Answer bravos\'s questions as a team', skills: ['bravos-context'], body: ['bravos-context opens its questions as a bravos page (bravos review intent): pre-filled with bravos\'s suggestions and their sources; change what is wrong, make the calls marked \'needs your call\' (Confirm stays off until you do), and the facts bravos drafted stay folded unless you open one to object. Each person\'s answers save to .guardlink/intent-answers/<name>.json; teammates run bravos review intent after pulling and commit theirs. bravos review intent --summary shows where people agree and disagree; only what a named person agreed to is marked confirmed. On Claude Code, --share puts the same page on a private claude.ai link instead.'] },
120
+ { name: 'Answer bravos\'s questions as a team', skills: ['bravos-context'], body: ['bravos-context opens its questions as a bravos page (bravos review intent): pre-filled with bravos\'s suggestions and their sources; change what is wrong, make the calls marked \'needs your call\' (Confirm stays off until you do), and the facts bravos drafted stay folded unless you open one to object. The role-by-action matrix links each documented permission to its question. In local reviews, open a cited SRC document to read its verified text. The saved HTML can contain these documents. Each person\'s answers save to .guardlink/intent-answers/<name>.json; teammates run bravos review intent after pulling and commit theirs. Press Done when you are finished: the agent runs bravos review intent --wait and carries on by itself. bravos review intent --summary shows where people agree and disagree; only what a named person agreed to is marked confirmed. On Claude Code, --share prepares an artifact with the draft and its citations. Publish that artifact to share it.'] },
121
121
  { name: 'I wrote security-relevant code', skills: ['bravos-annotate'], body: ['Annotates what you changed to guardlink\'s evidence bar and runs the lint gate until clean.'] },
122
122
  { name: 'Cover the whole repo', skills: ['bravos-campaign'], body: ['Rounds of batches with subagents and rests, until the coverage goal or until you stop it.'] },
123
123
  { name: 'Is this exposure real?', skills: ['bravos-templatize', 'bravos-env', 'bravos-prove'], body: ['Template → authorized target → run. Only a reproduced run confirms; reading code never does.'] },
124
124
  { name: 'My branch moved, or I found old annotation work', skills: ['bravos-resync'], body: ['When the briefing says this checkout is far behind its base, or lists idle branches with annotation work the base lacks: saves uncommitted work in a commit, starts a branch from the base, carries the sidecars and definitions with bravos resync, maps ids that duplicate the base\'s, and re-reads every carried claim on code that changed since. Old annotations are leads until re-read.'] },
125
125
  { name: 'I fixed a finding', skills: ['bravos-recheck'], body: ['Re-verifies stale claims, replays the retest kit, and checks the fix added no new exposure.'] },
126
126
  { name: 'I am about to open a PR', skills: ['bravos-ship'], body: ['The no-mistakes gate: validate, lint since the merge base, disclose new exposure, block confirmed exploits on changed paths.'] },
127
- { name: 'Find the routes, callers or blast radius', skills: ['bravos-codegraph'], body: ['One bounded question to the code graph instead of grepping. Team plan: bravos setup --codegraph stages codegraph-mcp, then bravos graph build . indexes the repository. With it, other skills get sharper on their own: bravos-templatize targets the route and auth that actually reach each sink, bravos-recheck follows a fix\'s callers and blast radius into other files, bravos-context drafts the real public surface, and bravos-prove tests the most reachable exposures first. Without it they read the code and say so.'] },
127
+ { name: 'Find the routes, callers or blast radius', skills: ['bravos-codegraph'], body: ['One bounded question to the code graph instead of grepping. Team plan: bravos setup --codegraph stages codegraph-mcp, then bravos graph build . indexes the repository. With it, other skills get sharper on their own: bravos-templatize targets the route and auth that actually reach each sink, bravos-recheck follows a fix\'s callers and blast radius into other files, bravos-context drafts the real public surface, and bravos-prove tests the most reachable exposures first. After each commit the graph is rebuilt for you: when a session starts and the commit has none, the session hook starts one quiet background build (no tokens; one at a time; never in CI; BRAVOS_GRAPH_AUTOBUILD=off turns it off). Without it they read the code and say so.'] },
128
128
  { name: 'Scan for dependency CVEs, secrets, IaC', skills: ['bravos-sast'], body: ['Licensed bravos-cli: Semgrep rules, request-to-sink taint over the code graph, dependency CVEs with whether the vulnerable function is reached, secrets (git history too) and IaC. It reads the GuardLink threat model as input, so annotate first. Says plainly when it is unavailable.'] },
129
129
  { name: 'What did SAST find, and what happens to it', skills: ['bravos-sast', 'bravos-annotate', 'bravos-templatize', 'bravos-prove', 'bravos-recheck'], body: ['bravos sast candidates (free, no model) reads the newest run in .bravos/sast/: reachable findings joined to a claim feed bravos-templatize and bravos-prove (the route and taint path to target, tested first); reachable findings not in the threat model are leads for bravos-annotate; bravos-recheck rescans the changed files after a fix. A static finding is a lead, never a confirmation; only a run confirms. The briefing\'s SAST line shows the latest run, or that SAST is unavailable.'] },
130
130
  { name: 'Keep it fresh while I work, or nightly', skills: ['bravos-schedule'], body: ['An in-session /loop from .claude/loop.md, the nightly workflow, or a cloud task you create. Loops never send test traffic.'] },
131
131
  { name: 'Add or fix security CI', skills: ['bravos-cicd'], body: ['PR gate, nightly annotation, SARIF to code scanning, script-injection fixes.'] },
132
132
  { name: 'An app made of several repositories (microservices)', skills: ['bravos-annotate', 'bravos-codegraph', 'bravos-prove'], body: ['Clone the services side by side in one folder, then run bravos workspace create NAME --member ./gateway=gateway@http://127.0.0.1:8080 --member ./orders=orders@http://127.0.0.1:8081 (bravos workspace plus guardlink link-project plus bravos in each repo and in the shared folder). Work on a service from its own repo; ask questions that cross services from the shared folder, where the briefing and bravos watch show every service. Declare each call to another service as @flows #<this>-<x> -> #<other>-<y> via http (plain ids, not #repo.tag). Build the code graph over the shared folder so it links one service\'s client calls to another\'s handlers. bravos report data --workspace writes one report across the services.'] },
133
+ { name: 'After updating bravos', skills: ['bravos'], body: ['Nothing to run by hand in a repository you work in with an agent: at the start of a session bravos upkeep (read-only, no network) tells the agent what is behind the installed version, and the agent runs bravos sync for the repository\'s skills and hooks, or bravos setup for Bravos\'s own bundles, without asking. If a teammate synced the repository with a newer bravos than yours, the agent syncs nothing and tells you to update. Installing guardlink and cxg (bravos setup --tools) still waits for your go-ahead.'] },
134
+ { name: 'Stop being asked about commits', skills: ['bravos'], body: ['Say once whether your agent commits the files Bravos writes (annotations, intent, definitions, tests): bravos prefs set commits commit|leave|ask --by "<your name>". bravos start asks it too. The answer is kept in this clone\'s git directory, never committed, and your own code is never part of such a commit. bravos prefs get shows it.'] },
133
135
  { name: 'See the findings on one page', skills: ['bravos'], body: ['Run bravos dashboard (free, no model): it writes one self-contained page under .bravos/dashboard/ (git-ignored) and opens it in your browser. It is GuardLink\'s threat model with who introduced and fixed each exposure and what changed since the default branch; on the Team plan, with the code graph built, a second tab shows the code graph: a map of where the risk sits, owners and history, coupling, trust, the attack surface, entry points and links. Run it again whenever you want the picture: it rebuilds from the code as it stands, rebuilding a code graph that is missing or behind first, and a saved page says when it is more than half a day old. --no-blame leaves git names out of a page you will share; --no-open only prints the path. Or ask your agent "show me the findings".'] },
134
136
  { name: 'Write up the assessment, a finding or a retest', skills: ['bravos-report'], body: ['Ask "write the assessment report" (or a finding, a retest, an executive brief). bravos report data gathers the evidence; the agent writes report.md in the eight-section reading order, with every proof claim citing its evidence; bravos report check refuses a finding labelled reproduced without a run or ledger record; bravos report export writes md, txt, html and pdf. bravos watch shows the newest report (p to read it, o to open the pdf or html).'] },
135
137
  ],
@@ -176,7 +178,7 @@ export const GUIDE_TOPICS = [
176
178
  { name: 'Authorization', body: ['No request goes to a host other than loopback without a committed, reviewed scope.yaml and your own typed authorization naming the target.'] },
177
179
  { name: 'Destructive tests', body: ['DoS and other destructive classes run only against a disposable loopback target.'] },
178
180
  { name: 'Credentials', body: ['Never invented. Test users and sessions are seeded or captured for real, or the run waits for you.'] },
179
- { name: 'No hidden agents', body: ['The agent in your session does the work; bravos never spawns another agent CLI. Model-API probe generation in cxg runs only after you agree to the spend.'] },
181
+ { name: 'No hidden agents', body: ['The agent in your session does the work; bravos never spawns another agent CLI, and never uses cxg\'s model-API probe generation: the tests it runs are the ones written and reviewed in your session.'] },
180
182
  { name: 'Governance', body: ['Agents never write @accepts or @entitles (a human\'s decision) and never write @confirmed without reproduction evidence in hand.'] },
181
183
  ],
182
184
  },
package/dist/help.js CHANGED
@@ -136,6 +136,25 @@ Design rules
136
136
  unguarded, guarded but untested, not placed, holds), the document it came from and where the
137
137
  code enforces it. bravos dashboard shows them as its Design rules tab. Read-only; no model.
138
138
 
139
+ Commits
140
+ Your agent asks before it commits the files Bravos writes. Say it once and it stops asking:
141
+ bravos prefs set commits commit|leave|ask --by "<your name>" (bravos start asks it too).
142
+ The answer is kept under this clone's git directory, never committed; your own code is
143
+ never part of such a commit. bravos prefs get shows it.
144
+
145
+ Upkeep
146
+ After you update bravos, each repository's copies of the skills and hooks are behind it,
147
+ and a staged bundle may be older than the new version pins. bravos upkeep says so; your
148
+ agent's session briefing reads it and the agent runs bravos sync or bravos setup itself.
149
+ When the repository is the newer side, it tells you to update bravos and syncs nothing.
150
+ BRAVOS_UPKEEP_PROBE=off stops the check.
151
+
152
+ The code graph is rebuilt for you too (Team plan): a graph belongs to the commit it was
153
+ built at, so when a session starts and the commit has none, the session hook starts one
154
+ quiet background build (bravos graph build . --scip no-exec: no tokens, no network, and the
155
+ repository's own build scripts are not run). One build per repository at a time; never in
156
+ CI; BRAVOS_GRAPH_AUTOBUILD=off turns it off.
157
+
139
158
  Context comes first
140
159
  bravos-annotate, campaigns and the nightly workflows start only when a named person has
141
160
  confirmed at least one item of .guardlink/intent.md, or has recorded that the team goes
@@ -243,10 +262,10 @@ What it writes (repository-relative)
243
262
  .claude/settings.json SessionStart hook, --harness claude (+ PreToolUse gate
244
263
  with --pre-pr-hook)
245
264
  .codex/hooks.json the same for Codex, --harness codex
246
- .mcp.json, .codex/config.toml MCP servers: guardlink always; cxg when on PATH; codegraph-mcp
247
- when on PATH or inside the bravos install (by full path, with
248
- the launcher's graph store as BRAVOS_CODEGRAPH_DIR; sync
249
- refreshes that entry when bravos is replaced)
265
+ .mcp.json, .codex/config.toml MCP servers: guardlink always; cxg when on PATH; the code graph
266
+ as "bravos graph mcp" when its bundle is staged (no path, so
267
+ the entry works for every teammate; sync rewrites an older
268
+ entry that held a full path), else codegraph-mcp from PATH
250
269
  .cursor/rules/bravos.mdc pointer to the skills, only if .cursor/ exists
251
270
  .omp/extensions/bravos.js omp session start, only if .omp/ exists or omp is on PATH
252
271
  Every merge keeps entries bravos did not write. A file it cannot parse is refused with
@@ -277,7 +296,7 @@ Flags in depth
277
296
  for testing. Also registers the pre-PR gate (implies --pre-pr-hook), which also lints. New
278
297
  exposures are handled as you choose: the first time proving comes up the agent asks
279
298
  you once (prove automatically on your loopback target, ask each time, on a schedule,
280
- or not now; and whether cxg may generate probes through a model API) and records your
299
+ or not now) and records your
281
300
  words in .guardlink/proving.md, which a PR that changes it must mention. It uses only
282
301
  guardlink's fast calls (a few seconds); a missing tool or timeout lets the turn finish.
283
302
  BRAVOS_AUTOPILOT=off pauses the check.
package/dist/install.js CHANGED
@@ -68,7 +68,8 @@ export function installSkills(root, harnesses, opts = {}) {
68
68
  // The lock claims this version only when every file was written; a skipped or failed file keeps
69
69
  // the old version, so a stale copy stays visible to the shadow check and the next sync retries it.
70
70
  const complete = report.skipped.length === 0;
71
- writeLock(root, { ...lock, bravos_version: complete ? version() : lock.bravos_version, files: { ...lock.files, ...record } });
71
+ // synced_with records which bravos ran this sync whatever was skipped, so bravos upkeep can tell an older bravos from a newer one.
72
+ writeLock(root, { schema: lock.schema, bravos_version: complete ? version() : lock.bravos_version, synced_with: version(), files: { ...lock.files, ...record } });
72
73
  }
73
74
  return report;
74
75
  }
package/dist/lock.js CHANGED
@@ -39,6 +39,7 @@ export function readLock(root) {
39
39
  return {
40
40
  schema: LOCK_SCHEMA,
41
41
  bravos_version: typeof p.bravos_version === 'string' ? p.bravos_version : version(),
42
+ ...(typeof p.synced_with === 'string' && p.synced_with ? { synced_with: p.synced_with } : {}),
42
43
  files,
43
44
  };
44
45
  }
package/dist/mcp.js CHANGED
@@ -3,7 +3,8 @@ import { dirname, join } from 'node:path';
3
3
  import { parse as parseToml } from 'smol-toml';
4
4
  import { whichBin } from './guardlink.js';
5
5
  import { graphBin, graphStore } from './codegraph.js';
6
- import { isInstallGraphCommand } from './graphbin.js';
6
+ import { staged } from './artifacts.js';
7
+ import { isInstallGraphCommand, isStagedGraphCommand, pythonBravos } from './graphbin.js';
7
8
  import { BravosError } from './types.js';
8
9
  // @comment -- "The launch argv (command and args) for each of the three MCP servers bravos knows: guardlink, cxg and codegraph; frozen so no caller can mutate a shared entry."
9
10
  export const SERVERS = Object.freeze({
@@ -12,6 +13,13 @@ export const SERVERS = Object.freeze({
12
13
  codegraph: Object.freeze({ command: 'codegraph-mcp', args: ['--project-path', '.'] }),
13
14
  });
14
15
  const BIN = { cxg: 'cxg', codegraph: 'codegraph-mcp' };
16
+ // @comment -- "The code graph server reached through this CLI (bravos graph mcp), not by the path of the binary. The entry is the same on every machine and after every bundle upgrade, so a committed .mcp.json carries no local path and works for each teammate who has Bravos installed."
17
+ export const GRAPH_LAUNCHER = Object.freeze({ command: 'bravos', args: ['graph', 'mcp'] });
18
+ /** Whether `bravos` on PATH is this CLI (and not the older Python one, which has no `graph mcp`). */
19
+ const thisBravosOnPath = (env) => {
20
+ const onPath = whichBin('bravos', env);
21
+ return !!onPath && pythonBravos(env) !== onPath;
22
+ };
15
23
  // @comment -- "Picks the servers to register: guardlink always, cxg when on PATH, codegraph when codegraph-mcp is on PATH or inside the bravos install (registered by full path, with the graph store the bravos launcher uses as BRAVOS_CODEGRAPH_DIR so the MCP route reads the graphs bravos graph build writes); the rest are reported as deferred."
16
24
  export function selectServers(env = process.env) {
17
25
  const selected = { guardlink: SERVERS.guardlink };
@@ -24,6 +32,9 @@ export function selectServers(env = process.env) {
24
32
  const mcpBin = graphBin('codegraph-mcp', env);
25
33
  if (mcpBin && mcpBin === whichBin('codegraph-mcp', env))
26
34
  selected.codegraph = SERVERS.codegraph;
35
+ // The staged bundle is registered through the launcher wherever this CLI is on PATH; the full path is the fallback (bravos run by path, or the older Python install).
36
+ else if (mcpBin && staged(env, 'codegraph') && thisBravosOnPath(env))
37
+ selected.codegraph = { command: GRAPH_LAUNCHER.command, args: [...GRAPH_LAUNCHER.args] };
27
38
  else if (mcpBin) {
28
39
  const store = graphStore(env);
29
40
  selected.codegraph = { command: mcpBin, args: [...SERVERS.codegraph.args], ...(store ? { env: { BRAVOS_CODEGRAPH_DIR: store } } : {}) };
@@ -33,9 +44,13 @@ export function selectServers(env = process.env) {
33
44
  return { selected, deferred };
34
45
  }
35
46
  const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
36
- // @comment -- "Whether an existing entry is bravos's own codegraph registration into a bravos install that no longer matches what bravos would write now (a replaced install, or a graph store it lacks); such an entry is refreshed, every other existing entry is kept as it is."
47
+ // @comment -- "Whether an existing entry is bravos's own codegraph registration that no longer matches what bravos would write now: one into a replaced Python install (or a graph store it lacks), or one by full path into a staged bundle on some machine when the portable launcher entry is available. Such an entry is refreshed; every other existing entry, a hand-written one included, is kept as it is."
37
48
  export function staleGraphEntry(name, existing, next) {
38
- if (name !== 'codegraph' || !next || !isObject(existing) || !isInstallGraphCommand(existing.command))
49
+ if (name !== 'codegraph' || !next || !isObject(existing))
50
+ return false;
51
+ // A full path into a staged bundle is replaced only by the launcher entry, which is the same everywhere: two machines never rewrite the file back and forth.
52
+ const stagedPath = isStagedGraphCommand(existing.command) && next.command === GRAPH_LAUNCHER.command;
53
+ if (!isInstallGraphCommand(existing.command) && !stagedPath)
39
54
  return false;
40
55
  return JSON.stringify({ c: existing.command, a: existing.args, e: existing.env ?? null }) !== JSON.stringify({ c: next.command, a: next.args, e: next.env ?? null });
41
56
  }
package/dist/palette.js CHANGED
@@ -5,20 +5,20 @@ import { join } from 'node:path';
5
5
  export const THEMES = {
6
6
  dark: {
7
7
  green: '#33d49d', blue: '#0360a2', light: '#f0f0f0', steel: '#55899e', red: '#ea1d1d',
8
- slate: '#3b6779', amber: '#f0b429', line: '#2b4f5c',
8
+ slate: '#3b6779', amber: '#f0b429', line: '#2b4f5c', warm: '#ff9f5b', cool: '#51b2a9',
9
9
  },
10
10
  light: {
11
11
  green: '#0f7a55', blue: '#0360a2', light: null, steel: '#3f6576', red: '#c41616',
12
- slate: '#4d6b78', amber: '#9a6400', line: '#7d98a3',
12
+ slate: '#4d6b78', amber: '#9a6400', line: '#7d98a3', warm: '#88441d', cool: '#006c67',
13
13
  },
14
14
  neutral: {
15
15
  green: '#1e9a6c', blue: '#2f7fc1', light: null, steel: '#4f8296', red: '#e02424',
16
- slate: '#5a7d8b', amber: '#b07a00', line: '#5a7d8b',
16
+ slate: '#5a7d8b', amber: '#b07a00', line: '#5a7d8b', warm: '#ad6131', cool: '#2c8980',
17
17
  },
18
18
  };
19
19
  export const FIXED = {
20
20
  green: '#33d49d', blue: '#0360a2', light: '#f0f0f0', steel: '#55899e', red: '#dc1f1f',
21
- slate: '#3b6779', amber: '#f0b429', line: '#2b4f5c', ink: '#0e1b21', deep: '#1f3943', white: '#ffffff',
21
+ slate: '#3b6779', amber: '#f0b429', line: '#2b4f5c', warm: '#ff9f5b', cool: '#51b2a9', ink: '#0e1b21', deep: '#1f3943', white: '#ffffff',
22
22
  };
23
23
  export const THEME_NAMES = ['dark', 'light', 'neutral'];
24
24
  export const isTheme = (t) => THEME_NAMES.includes(t);
package/dist/prefs.js ADDED
@@ -0,0 +1,47 @@
1
+ // @comment -- "bravos prefs: a person's standing answers for one clone, read and written through hooks/lib/prefs.mjs so the CLI and the session hook agree on the file and its shape. `prefs get` prints what is recorded; `prefs set commits <commit|leave|ask> --by <name>` records what a named person said about committing Bravos's own files. The file is under the git directory, never in the working tree."
2
+ import { pathToFileURL } from 'node:url';
3
+ import { join } from 'node:path';
4
+ import { hooksDir } from './paths.js';
5
+ import { BravosError } from './types.js';
6
+ let cached;
7
+ export const prefsLib = () => (cached ??= import(pathToFileURL(join(hooksDir(), 'lib', 'prefs.mjs')).href));
8
+ const WHAT = {
9
+ commit: "commit Bravos's own files without asking",
10
+ leave: "leave Bravos's own files uncommitted and list them",
11
+ ask: 'ask before the first commit of each session',
12
+ };
13
+ /** What is recorded for this clone, as text or JSON. */
14
+ export async function getPrefs(root, env, json = false) {
15
+ const L = await prefsLib();
16
+ const dir = L.gitCommonDir(root, env);
17
+ if (!dir)
18
+ throw new BravosError(`${root} is not a git repository: preferences are kept under its git directory`);
19
+ const prefs = L.readPrefs(dir);
20
+ if (json)
21
+ return [JSON.stringify({ schema: L.PREFS_SCHEMA, file: L.prefsFile(dir), ...prefs }, null, 2)];
22
+ const c = prefs.commits;
23
+ return [
24
+ c ? `commits: ${c.value} — ${WHAT[c.value]} (${c.by}, ${c.at})` : `commits: not recorded — the agent asks before the first commit of each session`,
25
+ `kept in ${L.prefsFile(dir)} (this clone only; never committed)`,
26
+ ];
27
+ }
28
+ // @comment -- "Records what a named person said about commits. --by is required and never taken from git: the name is the person's own, given when they answered, so an agent cannot record an answer nobody gave without also inventing a name (the skills forbid both)."
29
+ // @mitigates #person-prefs against #governance-forgery using #prefs-outside-tree -- "The answer is written under the git directory with the name of the person who gave it; nothing in a repository's tree can set it."
30
+ export async function setCommits(root, value, by, env, now = new Date()) {
31
+ const L = await prefsLib();
32
+ if (!L.COMMIT_CHOICES.includes(value))
33
+ throw new BravosError(`usage: bravos prefs set commits <${L.COMMIT_CHOICES.join('|')}> --by "<your name>"`);
34
+ if (!by?.trim())
35
+ throw new BravosError('say whose answer this is: --by "<your name>" (it is a person\'s decision; an agent never records one nobody gave)');
36
+ const dir = L.gitCommonDir(root, env);
37
+ if (!dir)
38
+ throw new BravosError(`${root} is not a git repository: preferences are kept under its git directory`);
39
+ let file;
40
+ try {
41
+ file = L.writeCommits(dir, value, by, now.toISOString().slice(0, 10));
42
+ }
43
+ catch (e) {
44
+ throw new BravosError(e instanceof Error ? e.message : String(e));
45
+ }
46
+ return [`commits: ${value} — from now on the agent will ${WHAT[value]}`, `recorded in ${file} (this clone only; never committed)`];
47
+ }
@@ -1,7 +1,7 @@
1
1
  // @comment -- "Detached child that serves one review: argv root, kind, token, port. Started by bravos review so the command can return at once in any harness; it exits on Done or after 30 minutes idle."
2
- import { readDraft, renderReview, startReviewServer } from './review.js';
2
+ import { prepareReview, readDraft, renderReview, startReviewServer } from './review.js';
3
3
  const [root, kind, token, port] = process.argv.slice(2);
4
- const draft = readDraft(root, kind);
5
- const page = await renderReview(draft, { kind: 'serve', token });
6
- const { server } = await startReviewServer(root, draft, page, token, Number(port));
4
+ const review = await prepareReview(root, readDraft(root, kind));
5
+ const page = await renderReview(review, { kind: 'serve', token });
6
+ const { server } = await startReviewServer(root, review.draft, page, token, Number(port));
7
7
  server.on('close', () => process.exit(0));
@@ -0,0 +1,76 @@
1
+ // @comment -- "bravos review --wait: lets an agent's command return when the person presses Done on the review page, so nobody has to type 'done' in chat. The page's server is the detached process bravos review already starts; this only remembers which process serves which review (its pid, port and URL, in a 0600 file under the clone's git directory, never in the working tree) and watches for that process to exit. A harness whose commands time out runs the command again: it finds the same server and keeps waiting, so a second page never opens."
2
+ import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ /** How long one --wait call holds on before it says "still waiting" and returns: under the two-minute limit most agent shells put on a command. */
5
+ export const DEFAULT_WAIT_SECONDS = 90;
6
+ export const MAX_WAIT_SECONDS = 1800;
7
+ // @comment -- "The --wait value: bare --wait is the default, a number is that many seconds within 1 second and the server's own 30-minute idle limit; anything else is refused."
8
+ export function waitSeconds(value) {
9
+ if (value === true || value === undefined)
10
+ return DEFAULT_WAIT_SECONDS;
11
+ const n = Number(value);
12
+ if (!Number.isFinite(n) || n < 1 || n > MAX_WAIT_SECONDS)
13
+ throw new Error(`--wait takes a number of seconds from 1 to ${MAX_WAIT_SECONDS}`);
14
+ return Math.floor(n);
15
+ }
16
+ /** Whether a process with this id is running (signal 0 asks without sending anything). */
17
+ export function alive(pid) {
18
+ if (!Number.isInteger(pid) || pid <= 1)
19
+ return false;
20
+ try {
21
+ process.kill(pid, 0);
22
+ return true;
23
+ }
24
+ catch (e) {
25
+ // EPERM means it exists but is someone else's: not our server.
26
+ return false;
27
+ }
28
+ }
29
+ export const reviewStateFile = (commonDir, kind) => join(commonDir, 'bravos', `review-${kind}.json`);
30
+ // @comment -- "Reads which server is showing this review, and only believes it while that process is running; a record left by a server that has gone is removed."
31
+ export function readLive(commonDir, kind) {
32
+ if (!commonDir)
33
+ return null;
34
+ const file = reviewStateFile(commonDir, kind);
35
+ try {
36
+ const j = JSON.parse(readFileSync(file, 'utf8'));
37
+ if (typeof j.pid === 'number' && typeof j.port === 'number' && typeof j.url === 'string' && /^http:\/\/127\.0\.0\.1:\d+\/\?t=[a-f0-9]+$/.test(j.url) && alive(j.pid))
38
+ return { pid: j.pid, port: j.port, url: j.url };
39
+ }
40
+ catch {
41
+ return null;
42
+ }
43
+ clearLive(commonDir, kind);
44
+ return null;
45
+ }
46
+ export function writeLive(commonDir, kind, live) {
47
+ if (!commonDir)
48
+ return;
49
+ const file = reviewStateFile(commonDir, kind);
50
+ mkdirSync(join(file, '..'), { recursive: true, mode: 0o700 });
51
+ const tmp = `${file}.tmp-${process.pid}`;
52
+ writeFileSync(tmp, JSON.stringify(live) + '\n', { mode: 0o600 });
53
+ try {
54
+ chmodSync(tmp, 0o600);
55
+ }
56
+ catch {
57
+ /* best effort on platforms without modes */
58
+ }
59
+ renameSync(tmp, file);
60
+ }
61
+ export function clearLive(commonDir, kind) {
62
+ if (!commonDir)
63
+ return;
64
+ rmSync(reviewStateFile(commonDir, kind), { force: true });
65
+ }
66
+ /** Resolves true when the process has exited, false when `ms` passed first. Asks the process table only, so the page's idle clock is never reset by the waiting. */
67
+ export async function waitGone(pid, ms, everyMs = 300) {
68
+ const until = Date.now() + ms;
69
+ for (;;) {
70
+ if (!alive(pid))
71
+ return true;
72
+ if (Date.now() >= until)
73
+ return false;
74
+ await new Promise((r) => setTimeout(r, Math.min(everyMs, Math.max(1, until - Date.now()))));
75
+ }
76
+ }