@bugb-technologies/bravos 1.2.1 → 1.4.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 (47) hide show
  1. package/README.md +17 -10
  2. package/dist/ci.js +11 -3
  3. package/dist/cli.js +50 -8
  4. package/dist/doctor.js +4 -16
  5. package/dist/guide.js +5 -3
  6. package/dist/help.js +16 -16
  7. package/dist/hooks.js +21 -0
  8. package/dist/install-proof-tool.js +117 -0
  9. package/dist/proof-tools.js +29 -0
  10. package/dist/report/check.js +4 -1
  11. package/dist/report/data.js +81 -149
  12. package/dist/report/markdown.js +1 -1
  13. package/dist/report/redact.js +16 -0
  14. package/dist/report/runs.js +169 -0
  15. package/dist/resync.js +272 -0
  16. package/dist/setup.js +31 -16
  17. package/dist/start/answers.js +5 -3
  18. package/dist/start/index.js +28 -14
  19. package/dist/versions.js +4 -3
  20. package/docs/GUIDE.md +12 -2
  21. package/hooks/lib/autopilot.mjs +216 -77
  22. package/hooks/lib/briefing.mjs +36 -5
  23. package/hooks/lib/nightly-stage.mjs +66 -0
  24. package/hooks/lib/nightly-tools.sh +45 -0
  25. package/hooks/lib/pre-pr.mjs +88 -17
  26. package/hooks/lib/proof-tool-pins.json +12 -0
  27. package/hooks/lib/replay.mjs +579 -0
  28. package/hooks/lib/resync.mjs +78 -0
  29. package/hooks/lib/setup.mjs +15 -6
  30. package/hooks/lib/snapshot.mjs +189 -0
  31. package/hooks/session-start.mjs +7 -3
  32. package/package.json +1 -1
  33. package/skills/bravos/SKILL.md +2 -1
  34. package/skills/bravos-annotate/SKILL.md +6 -5
  35. package/skills/bravos-annotate/scripts/slice.mjs +15 -8
  36. package/skills/bravos-cicd/SKILL.md +1 -1
  37. package/skills/bravos-env/SKILL.md +3 -3
  38. package/skills/bravos-prove/SKILL.md +11 -15
  39. package/skills/bravos-recheck/SKILL.md +3 -3
  40. package/skills/bravos-report/SKILL.md +1 -1
  41. package/skills/bravos-resync/SKILL.md +52 -0
  42. package/skills/bravos-schedule/SKILL.md +1 -1
  43. package/skills/bravos-ship/SKILL.md +1 -1
  44. package/skills/bravos-templatize/SKILL.md +3 -3
  45. package/templates/workflows/bravos-nightly-claude.yml +131 -74
  46. package/templates/workflows/bravos-nightly-codex.yml +130 -73
  47. package/templates/workflows/bravos-pr-gate.yml +88 -14
@@ -1,47 +1,19 @@
1
- // @comment -- "bravos autopilot's end-of-turn check (Claude Code and Codex Stop hooks): from the working-tree changes since HEAD it finds changed files with no GuardLink annotation, confirmed or stale claims on changed files, and open exposures on changed files, using only the two fast guardlink calls (unannotated and ci, run concurrently; lint and diff are left to the pre-PR gate because they take a minute on a large repo), and returns block with a short reason naming the skill to run, or allow. A nudge, not a gate: a missing tool, a timeout or bad input allows. Each finding is raised once per session (its key is looked up in the harness's transcript, which bravos only reads). Read-only: argv spawns, no shell."
1
+ // @comment -- "bravos autopilot's end-of-turn check (Claude Code and Codex Stop hooks): reads session changes, the annotation worklist, current model and tested states; reports changes to review and affected claim keys, scoped to code and sidecar locations, and returns block with a short reason naming the skill to run, or allow. A nudge, not a gate: a missing tool, a timeout or bad input allows. Each finding is raised once per session, per file or claim rather than per edit (its key is looked up in the harness's transcript, which bravos only reads), and the guardlink calls share one time budget under the hook's 30 s limit. Read-only: argv spawns, no shell."
2
2
  import { createHash } from 'node:crypto';
3
- import { spawn } from 'node:child_process';
4
3
  import { appendFileSync, existsSync, mkdirSync, openSync, readFileSync, readSync, closeSync, fstatSync, writeFileSync } from 'node:fs';
5
4
  import { join } from 'node:path';
5
+ import { gitStaleness, staleness } from './resync.mjs';
6
+ import { asyncRunner, changedHunks, fingerprint, readSnapshot, workingChanges } from './snapshot.mjs';
6
7
 
7
- export const AUTOPILOT_DEADLINE_MS = 20000;
8
- const OUTPUT_CAP = 64 * 1024 * 1024;
8
+ export { asyncRunner, readSnapshot, safeSessionId, takeSnapshot } from './snapshot.mjs';
9
+
10
+ // One budget for the whole check, under the harness's 30 s hook limit.
11
+ export const AUTOPILOT_DEADLINE_MS = 24000;
9
12
  const TRANSCRIPT_TAIL = 4 * 1024 * 1024;
10
13
  const MAX_LIST = 5;
11
14
 
12
15
  const arr = (v) => (Array.isArray(v) ? v : []);
13
16
 
14
- // @comment -- "Async spawn with the pre-PR runner's result shape: argv array, no shell, stdin closed, output capped, killed at timeoutMs; never rejects."
15
- export function asyncRunner(cmd, args, { cwd, env, timeoutMs = AUTOPILOT_DEADLINE_MS }) {
16
- return new Promise((resolve) => {
17
- let child;
18
- try {
19
- child = spawn(cmd, args, { cwd, env, stdio: ['ignore', 'pipe', 'ignore'] });
20
- } catch (e) {
21
- resolve({ missing: e?.code === 'ENOENT', error: e?.code ?? String(e), status: null, stdout: '' });
22
- return;
23
- }
24
- const chunks = [];
25
- let size = 0;
26
- let done = false;
27
- const finish = (r) => {
28
- if (done) return;
29
- done = true;
30
- clearTimeout(timer);
31
- resolve(r);
32
- };
33
- child.stdout.on('data', (b) => {
34
- if (size < OUTPUT_CAP) chunks.push(b);
35
- size += b.length;
36
- });
37
- const timer = setTimeout(() => {
38
- child.kill('SIGKILL');
39
- finish({ status: null, error: 'ETIMEDOUT', stdout: '' });
40
- }, timeoutMs);
41
- child.on('error', (e) => finish({ missing: e.code === 'ENOENT', error: e.code ?? e.message, status: null, stdout: '' }));
42
- child.on('close', (status) => finish({ status, stdout: Buffer.concat(chunks).toString('utf8') }));
43
- });
44
- }
45
17
 
46
18
  async function json(run, args, o) {
47
19
  const r = await run('guardlink', args, o);
@@ -57,13 +29,48 @@ async function json(run, args, o) {
57
29
  import { readProving } from './proving.mjs';
58
30
  export { readProving };
59
31
 
60
- /** Files changed in the working tree since HEAD, tracked or not. */
61
- export async function changedFiles(root, env, run) {
62
- const o = { cwd: root, env };
32
+ /** Paths bravos itself writes: never "changed code" for the check, whatever git says about them. */
33
+ const GENERATED_PREFIXES = ['.bravos/', '.claude/skills/', '.agents/skills/', '.opencode/', '.omp/'];
34
+ // Hook settings: bravos's own entries live here, and agent configuration is reported by guardlink diff, not annotations.
35
+ const GENERATED_FILES = new Set(['.claude/settings.json', '.codex/hooks.json', '.agents/hooks.json', 'opencode.json']);
36
+
37
+ // @comment -- "The paths the repo's skills lock says bravos wrote (.bravos/skills.lock files), so a generated file outside the fixed prefixes is still recognised; an unreadable lock is an empty set."
38
+ function lockedFiles(root) {
39
+ try {
40
+ const files = JSON.parse(readFileSync(join(root, '.bravos', 'skills.lock'), 'utf8'))?.files;
41
+ return new Set(files && typeof files === 'object' ? Object.keys(files) : []);
42
+ } catch {
43
+ return new Set();
44
+ }
45
+ }
46
+
47
+ // @comment -- "True for a path bravos generated (fixed prefixes, hook settings files, or listed in the skills lock): such a file is setup, not code the agent wrote, so the check never asks for it to be annotated."
48
+ export function isGenerated(path, locked = new Set()) {
49
+ return GENERATED_FILES.has(path) || locked.has(path) || GENERATED_PREFIXES.some((p) => path.startsWith(p));
50
+ }
51
+
52
+ /**
53
+ * Files this session changed: with a start snapshot, working-tree files whose content differs from what
54
+ * the snapshot recorded plus files touched by commits made since it; without one, every working-tree
55
+ * change since HEAD. Bravos's own generated files are never included.
56
+ */
57
+ // @comment -- "The set the check runs on: snapshot-relative when the session has one (so edits that predate the session, and commits made during it, are judged correctly), HEAD-relative otherwise; generated setup files are filtered out either way."
58
+ export async function changedFiles(root, env, run, snapshot = null) {
59
+ const now = await workingChanges(root, env, run);
63
60
  const out = new Set();
64
- const [diff, untracked] = await Promise.all([run('git', ['diff', '--name-only', 'HEAD'], o), run('git', ['ls-files', '--others', '--exclude-standard'], o)]);
65
- if (diff.status === 0) for (const l of diff.stdout.split('\n')) if (l.trim()) out.add(l.trim());
66
- if (untracked.status === 0) for (const l of untracked.stdout.split('\n')) if (l.trim()) out.add(l.trim());
61
+ if (snapshot) {
62
+ for (const rel of now) if (!Object.hasOwn(snapshot.files, rel) || snapshot.files[rel] !== fingerprint(root, rel)) out.add(rel);
63
+ // Also catch a previously dirty file restored to HEAD during the session.
64
+ for (const path of Object.keys(snapshot.files)) if (!now.has(path) && snapshot.files[path] !== fingerprint(root, path)) out.add(path);
65
+ const committed = await run('git', ['diff', '--name-only', `${snapshot.head}..HEAD`, '-z', '--no-renames', '--'], { cwd: root, env });
66
+ if (committed.status === 0) for (const path of committed.stdout.split('\0')) if (path) out.add(path);
67
+ } else {
68
+ for (const rel of now) out.add(rel);
69
+ }
70
+ const locked = lockedFiles(root);
71
+ // Shared agent settings also carry operator-authored permissions and hooks; review
72
+ // those through GuardLink's config model instead of treating them as source.
73
+ for (const rel of [...out]) if (rel.startsWith('.bravos/') || locked.has(rel)) out.delete(rel);
67
74
  return out;
68
75
  }
69
76
 
@@ -86,67 +93,199 @@ function transcriptTail(path) {
86
93
  }
87
94
  }
88
95
 
89
- const listOf = (all) => { const xs = [...new Set(all)]; return xs.slice(0, MAX_LIST).join(', ') + (xs.length > MAX_LIST ? ` and ${xs.length - MAX_LIST} more` : ''); };
90
96
  const fileOf = (c) => c?.location?.file ?? c?.file;
91
97
 
98
+ function proofInstruction(pref, retest) {
99
+ const skill = retest ? 'bravos-recheck' : 'bravos-prove';
100
+ if (pref.status !== 'set') return 'ask the person once how they want findings proven (bravos-prove); retain these claim keys for that decision';
101
+ if (pref.choice === 'ask') return `ask the person before testing with ${skill}`;
102
+ if (pref.choice === 'schedule') return 'leave the keys for the authorized scheduled run and report that they await testing';
103
+ if (pref.choice === 'none') return 'report the outstanding claims; the person chose not to run tests';
104
+ return `use bravos-templatize for missing kits and ${skill} on ${pref.target ?? 'the recorded loopback target'} under the recorded scope and generation choice`;
105
+ }
106
+
107
+ // @comment -- "GuardLink hypothesis list names the authored row (a .gal line in external mode). Join the exact authored line, asset and threat to parse's current exposure or confirmation to get its logical source span. Never identify an individual claim by threat and file alone."
108
+ function authoredKey(file, line, asset, threat) {
109
+ return JSON.stringify([file, line, asset, threat]);
110
+ }
111
+
112
+ function overlaps(hunks, file, start, end = start) {
113
+ if (!hunks.has(file)) return true; // Untracked file, binary, or no patch available: review the file.
114
+ if (!Number.isInteger(start) || !Number.isInteger(end)) return hunks.get(file).length > 0;
115
+ return hunks.get(file).some(h => h.start <= end && start <= h.end);
116
+ }
117
+
118
+ function touches(location, changed, hunks) {
119
+ if (!location) return false;
120
+ if (changed.has(location.origin_file) && overlaps(hunks, location.origin_file, location.origin_line)) return true;
121
+ if (!changed.has(location.file)) return false;
122
+ const anchor = location.anchor;
123
+ return overlaps(hunks, location.file, anchor?.start_line ?? location.line, anchor?.end_line ?? location.line);
124
+ }
125
+
92
126
  /**
93
127
  * Runs the end-of-turn check. `payload` is the Stop hook's stdin (stop_hook_active, transcript_path).
94
128
  * Returns { decision: 'allow' } or { decision: 'block', reason }.
95
129
  */
96
130
  // @comment -- "Decides the Stop hook's answer: allow when autopilot is off, the turn was already continued by a Stop hook, guardlink is absent, nothing changed or nothing new is found; otherwise block once with one line per finding and the skill that handles it, and for new exposures the next step the recorded proving preference implies."
97
131
  export async function runAutopilot({ root, env = process.env, payload = {}, run = asyncRunner, deadlineMs = AUTOPILOT_DEADLINE_MS }) {
132
+ const started = Date.now();
98
133
  if (env.BRAVOS_AUTOPILOT === 'off') return { decision: 'allow' };
99
134
  if (payload?.stop_hook_active === true) return { decision: 'allow' };
100
135
  if (!existsSync(join(root, '.guardlink'))) return { decision: 'allow' };
101
136
  const o = { cwd: root, env, timeoutMs: deadlineMs };
102
137
 
103
- const changed = await changedFiles(root, env, run);
138
+ const snapshot = readSnapshot(root, payload?.session_id);
139
+ const changed = await changedFiles(root, env, run, snapshot);
104
140
  if (changed.size === 0) return { decision: 'allow' };
105
141
 
106
- // The two fast guardlink calls, side by side; a missing guardlink or a timeout reads as nothing found.
107
- const [wl, ci] = await Promise.all([json(run, ['unannotated', '--json'], o), json(run, ['ci', '-f', 'json'], o)]);
142
+ // A checkout far behind its base: its model describes older code, so say that before anything else.
143
+ const git = (args) => run('git', args, o).then((r) => (r.status === 0 ? r.stdout.trim() : null));
144
+ const [baseRef, branchRef] = await Promise.all([git(['symbolic-ref', '-q', '--short', 'refs/remotes/origin/HEAD']), git(['rev-parse', '--abbrev-ref', 'HEAD'])]);
145
+ const base = baseRef || 'origin/main';
146
+ const branch = branchRef && branchRef !== 'HEAD' ? branchRef : null;
147
+ const behind = staleness({ ...(await gitStaleness(git, base)), branch, base });
148
+
149
+ // The hook runs under a 30 s harness limit: the guardlink calls share what is left of one budget, not 20 s each.
150
+ const left = Math.max(2000, deadlineMs - (Date.now() - started));
151
+ const og = { ...o, timeoutMs: left };
152
+ const [wl, ci, ledger, model, patch] = await Promise.all([
153
+ json(run, ['unannotated', '--json'], og), json(run, ['ci', '-f', 'json'], og),
154
+ json(run, ['hypothesis', 'list', '--json'], og), json(run, ['parse', '.', '--no-pretty'], og),
155
+ changedHunks(root, env, run, snapshot?.head ?? 'HEAD', left),
156
+ ]);
157
+ const hunks = new Map();
158
+ for (const path of changed) {
159
+ if (!patch.has(path)) continue;
160
+ const baseline = snapshot?.hunks?.[path];
161
+ const prior = new Set(Array.isArray(baseline) ? baseline : []);
162
+ hunks.set(path, patch.get(path).filter(h => !prior.has(h.hash)));
163
+ }
108
164
 
109
165
  const findings = [];
110
- // A short, stable key per finding: the same finding is raised once per session, a changed one again.
111
- const add = (key, line) => findings.push({ key: `[bravos-autopilot:${key.split(':')[0]}:${createHash('sha256').update(key).digest('hex').slice(0, 10)}]`, line });
112
-
113
- const worklist = arr(wl?.worklist).map((w) => (typeof w === 'string' ? w : w?.file ?? w?.path)).filter((f) => changed.has(f));
114
- if (worklist.length) add(`unannotated:${worklist.sort().join(',')}`, `${worklist.length} changed file(s) have no GuardLink annotation (${listOf(worklist)}): annotate the security-relevant code in them with bravos-annotate, or say why none is needed.`);
115
-
116
- const confirmed = arr(ci?.confirmed).filter((c) => changed.has(fileOf(c)));
117
- if (confirmed.length) {
118
- const ids = confirmed.map((c) => `${c.threat ?? '?'} at ${fileOf(c)}:${c?.location?.line ?? c?.line ?? '?'}`);
119
- add(`recheck:${ids.sort().join(',')}`, `you changed code under a confirmed exploit (${listOf(ids)}): run bravos-recheck to see whether the change fixed it, before finishing.`);
120
- }
121
- const stale = arr(ci?.stale).filter((c) => changed.has(fileOf(c)));
122
- if (stale.length) {
123
- const ids = stale.map((c) => `${fileOf(c)}:${c?.line ?? c?.location?.line ?? '?'}`);
124
- add(`stale:${ids.sort().join(',')}`, `${stale.length} claim(s) went stale in files you changed (${listOf(ids)}): re-read and re-verify them with bravos-recheck.`);
125
- }
126
-
127
- // Open exposures on the files this turn changed: what a proving decision is about.
128
- const confirmedKeys = new Set(confirmed.map((c) => `${c.threat}|${fileOf(c)}`));
129
- const open = arr(ci?.exposures).filter((e) => changed.has(fileOf(e)) && !confirmedKeys.has(`${e.threat}|${fileOf(e)}`));
130
- if (open.length) {
131
- const ids = open.map((e) => `${e?.threat ?? '?'} on ${e?.asset ?? '?'}`);
132
- const p = readProving(root);
133
- let next;
134
- if (p.status !== 'set') next = 'ask the person once how they want findings proven (automatically on their loopback target, each time you ask, on a schedule, or not now), and record their answer with bravos-prove';
135
- else if (p.choice === 'auto') next = `prove the untested ones with bravos-prove on ${p.target ?? 'the recorded loopback target'}, as .guardlink/proving.md records (${p.by}, ${p.date})`;
136
- else if (p.choice === 'ask') next = 'ask the person whether to prove them now (bravos-prove), as .guardlink/proving.md asks';
137
- else if (p.choice === 'schedule') next = 'leave them for the scheduled run .guardlink/proving.md names, and say so';
138
- else next = 'note them for the person; .guardlink/proving.md says not to prove for now';
139
- add(`prove:${ids.sort().join(',')}`, `${open.length} open exposure(s) sit on files this turn changed (${listOf(ids)}): ${next}.`);
166
+ const add = (key, line) => findings.push({ key: `[bravos-autopilot:${key.split(':')[0]}:${createHash('sha256').update(key).digest('hex').slice(0, 12)}]`, line });
167
+ const changedSource = path => changed.has(path) && (!hunks.has(path) || hunks.get(path).length > 0);
168
+
169
+ if (behind) {
170
+ add(`behind:${base}:${behind.behind}`, `this checkout is ${behind.behind} commits behind ${base}${behind.baseDate ? ` (shared base ${behind.baseDate})` : ''}, so its threat model describes older code${snapshot ? '' : ' and the changes here may predate this session'}: update the branch, or carry its annotation work to ${base} with bravos-resync, before annotating or proving here.`);
171
+ // Without a snapshot the changed set may be someone else's old edits; the stale line is the whole answer.
172
+ if (!snapshot) return finish(findings, payload);
173
+ }
174
+
175
+ const configFiles = new Set(arr(model?.agent_config?.files).map(f => f.path));
176
+ for (const path of changed) {
177
+ if (changedSource(path) && (configFiles.has(path) || (GENERATED_FILES.has(path) && hunks.has(path)))) {
178
+ add('config:' + path, 'Review changed coding-agent capabilities in ' + path + ' with bravos-annotate and GuardLink’s unentitled coding-agent reach lookup. Check the capability, affected asset and approval before proposing an entitlement.');
179
+ }
180
+ }
181
+ const paths = rows => arr(rows).map(w => typeof w === 'string' ? w : w?.file ?? w?.path)
182
+ .filter(path => changedSource(path) && !isGenerated(path) && !configFiles.has(path));
183
+ for (const path of paths(wl?.worklist)) {
184
+ add(`unannotated:${path}`, `${path} has no GuardLink annotation: review the change with bravos-annotate; record any security-relevant behavior.`);
185
+ }
186
+ for (const path of paths(wl?.annotated)) {
187
+ const ranges = hunks.get(path)?.map(h => h.start === h.end ? h.start : `${h.start}-${h.end}`).join(', ');
188
+ add(`review:${path}`, `review changed code in ${path}${ranges ? ` (lines ${ranges})` : ''} with bravos-annotate. Check new behavior and guards even when another symbol in this file already has an annotation.`);
189
+ }
190
+
191
+ const excluded = new Set(arr(wl?.excluded).map(e => e?.path ?? e?.file));
192
+ for (const path of changed) {
193
+ if (path.endsWith('.gal') && changedSource(path)) {
194
+ add('sidecar:' + path, 'Review changed claims in ' + path + ' with bravos-annotate. Read the logical source named by each affected block; reconcile retired claims and their replay kits.');
195
+ } else if (hunks.get(path)?.some(h => h.deleted) && !excluded.has(path) && !/\.(?:md|txt|rst)$/i.test(path)) {
196
+ add('removed:' + path, 'Review the deletion or move of ' + path + ' with bravos-annotate. Check its previous guards, current callers and any sidecars that still describe it.');
197
+ }
198
+ }
199
+
200
+ // ci.stale gives logical file/line, but not the whole source span. Use the
201
+ // parse location so a stale claim in an untouched sibling is not requeued.
202
+ const staleLocations = new Map();
203
+ for (const [verb, rows] of Object.entries({ exposes: model?.exposures, mitigates: model?.mitigations, boundary: model?.boundaries, flows: model?.flows, confirmed: model?.confirmed })) {
204
+ for (const { location } of arr(rows)) {
205
+ if (!location) continue;
206
+ const key = JSON.stringify([verb, location.file, location.line]);
207
+ if (!staleLocations.has(key)) staleLocations.set(key, []);
208
+ staleLocations.get(key).push(location);
209
+ }
210
+ }
211
+ for (const c of arr(ci?.stale)) {
212
+ const file = fileOf(c);
213
+ const locations = staleLocations.get(JSON.stringify([c.verb, file, c.line]));
214
+ if (locations ? !locations.some(l => touches(l, changed, hunks)) : !changedSource(file)) continue;
215
+ add('stale:' + (c.key ?? authoredKey(file, c.line)), (c.verb ?? 'guard') + ' claim at ' + file + ':' + (c.line ?? c.location?.line ?? '?') + ' went stale: re-read and re-verify it with bravos-recheck.');
140
216
  }
141
217
 
218
+ const byAuthored = new Map();
219
+ for (const entry of [...arr(model?.exposures), ...arr(model?.confirmed)]) {
220
+ const loc = entry.location;
221
+ if (!loc) continue;
222
+ byAuthored.set(authoredKey(loc.origin_file ?? loc.file, loc.origin_line ?? loc.line, entry.asset, entry.threat), loc);
223
+ }
224
+ const controls = new Map();
225
+ for (const m of arr(model?.mitigations)) {
226
+ if (!touches(m.location, changed, hunks)) continue;
227
+ const pair = JSON.stringify([m.asset, m.threat]);
228
+ if (!controls.has(pair)) controls.set(pair, []);
229
+ controls.get(pair).push(m.location);
230
+ }
231
+ const pref = readProving(root);
232
+ if (ledger?.ledger === 'corrupt') {
233
+ add('ledger:corrupt', 'GuardLink could not read the hypothesis ledger. Restore its evidence before treating any claim as untested or running a retest.');
234
+ } else if (Array.isArray(ledger?.records)) {
235
+ if (!Array.isArray(model?.exposures) && ledger.records.some(r => !r.location && r.file?.endsWith('.gal'))) {
236
+ add('ledger:locations', 'GuardLink source locations are unavailable for sidecar claims. Read their source blocks before selecting tests; the set of affected claims is unknown.');
237
+ }
238
+ for (const record of ledger.records) {
239
+ if (!record?.key) continue;
240
+ const loc = record.location ?? byAuthored.get(authoredKey(record.file, record.line, record.asset, record.threat));
241
+ if (!loc) {
242
+ if (changed.has(record.file)) add('unresolved:' + record.key, 'Resolve the logical source location for claim ' + record.key + ' in ' + record.file + ' before choosing a kit.');
243
+ continue;
244
+ }
245
+ const affectedControls = controls.get(JSON.stringify([record.asset, record.threat])) ?? [];
246
+ if (!touches(loc, changed, hunks) && !affectedControls.length) continue;
247
+ // A current refutation holds until its anchor or a separate control changes.
248
+ if (record.state === 'refuted' && !affectedControls.length) continue;
249
+ const retest = record.state === 'retest' || record.state === 'confirmed' || record.expired || record.state === 'refuted';
250
+ add(`proof:${record.key}:${record.state}`, `${retest ? 'Retest' : 'Untested'} ${record.threat} on ${record.asset} at ${loc.file}:${loc.line} (claim ${record.key}): ${proofInstruction(pref, retest)}.`);
251
+ }
252
+ } else {
253
+ // A legacy/unavailable ledger cannot report coverage of mitigated claims.
254
+ for (const c of arr(ci?.confirmed).filter(c => changedSource(fileOf(c)))) {
255
+ const file = fileOf(c);
256
+ add(`recheck:${authoredKey(file, c.location?.line, c.asset, c.threat)}`, `confirmed ${c.threat} at ${file}:${c.location?.line ?? '?'}: review with bravos-recheck; ${proofInstruction(pref, true)}.`);
257
+ }
258
+ for (const e of arr(ci?.exposures).filter(c => changedSource(fileOf(c)))) {
259
+ const file = fileOf(e);
260
+ add(`prove:${authoredKey(file, e.location?.line, e.asset, e.threat)}`, `open exposure ${e.threat} on ${e.asset} in ${file}: ${proofInstruction(pref, false)}. The hypothesis ledger was unavailable; tested state is unknown.`);
261
+ }
262
+ }
263
+
264
+ return finish(findings, payload);
265
+ }
266
+
267
+ // @comment -- "Turns the findings into the hook's answer: allow when there are none or every one was already raised this session (its key is in the transcript), else block once with one line per new finding."
268
+ function finish(findings, payload) {
142
269
  if (findings.length === 0) return { decision: 'allow' };
143
270
  const seen = transcriptTail(payload?.transcript_path);
144
271
  const fresh2 = findings.filter((f) => !seen.includes(f.key));
145
272
  if (fresh2.length === 0) return { decision: 'allow' };
273
+ // Keep large changes readable while preserving one deduplication key per distinct finding.
274
+ const groups = new Map();
275
+ for (const f of fresh2) {
276
+ const kind = f.key.split(':')[1];
277
+ if (!groups.has(kind)) groups.set(kind, []);
278
+ groups.get(kind).push(f);
279
+ }
280
+ const lines = [];
281
+ for (const [kind, group] of groups) {
282
+ for (const item of group.slice(0, MAX_LIST)) lines.push('- ' + item.line);
283
+ if (group.length > MAX_LIST) lines.push('- ' + (group.length - MAX_LIST) + ' more ' + kind + ' items: inspect the rest with the changed-file diff and guardlink hypothesis list --json.');
284
+ }
146
285
  const reason = [
147
286
  'bravos autopilot, before you finish:',
148
- ...fresh2.map((f) => `- ${f.line}`),
149
- 'If something here does not apply, say why in one line and finish.',
287
+ ...lines,
288
+ 'Finish quietly when the review finds no security change. Surface a finding, an untested claim that needs attention, or a decision the person must make.',
150
289
  fresh2.map((f) => f.key).join(' '),
151
290
  ].join('\n');
152
291
  const summary = `sent the agent back once: ${fresh2[0].line}${fresh2.length > 1 ? ` (+${fresh2.length - 1} more)` : ''}`;
@@ -6,8 +6,9 @@ import { THEMES } from './palette.mjs';
6
6
  import { readProving } from './proving.mjs';
7
7
  import { planLine, status as licenceStatus } from './licence.mjs';
8
8
  import { refreshIfDue } from './refresh.mjs';
9
+ import { gitStaleness, staleLine, staleness, strandedBranches, strandedLine } from './resync.mjs';
9
10
  import { readSast, sastAvailable, sastLine } from './sast.mjs';
10
- import { readSetup, setupLine } from './setup.mjs';
11
+ import { hooksLocked, readSetup, setupLine, TRIAL } from './setup.mjs';
11
12
  import { memberCounts, readWorkspace, workspaceLines } from './workspace.mjs';
12
13
 
13
14
  const SEVERITIES = ['critical', 'high', 'medium', 'low'];
@@ -125,7 +126,12 @@ export function buildBriefing(inputs) {
125
126
 
126
127
  const g = i.guardlink ?? {};
127
128
  const head = [];
129
+ // A stale checkout qualifies everything below it, so it comes first.
130
+ const staleText = staleLine(i.stale, { branch: i.branch, base: i.base });
131
+ if (staleText) head.push(staleText);
128
132
  head.push(exposuresLine(g));
133
+ const strandedText = strandedLine(i.stranded, i.base);
134
+ if (strandedText) head.push(strandedText);
129
135
 
130
136
  // Truncatable sections: { header, items }; the cap drops tickets first, then stale, FIX NOW, next.
131
137
  const confirmed = arr(g.ci?.confirmed).slice().sort((a, b) => sevRank(a.severity) - sevRank(b.severity));
@@ -170,7 +176,11 @@ export function buildBriefing(inputs) {
170
176
  ? `Note: this repo's bravos (${i.shadow.repo}) is behind the person's user-level copy (${i.shadow.user}), which Claude Code uses; suggest they run bravos sync in this repo from their own terminal`
171
177
  : `Note: the person's user-level bravos skills (~/.claude/skills, ${i.shadow.user}) are used instead of this repo's (${i.shadow.repo}); tell them to run bravos sync --global from their own terminal, then start a new session`);
172
178
  }
173
- if (i.autopilot) tail.push('Autopilot: on — an end-of-turn check sends you back once if changed code lacks annotations, sits under a confirmed or stale claim, or adds exposures to prove');
179
+ if ((i.autopilot || i.prePr) && hooksLocked(i)) {
180
+ // The repo registers the hooks for everyone; this person's copy answers nothing until they have a licence.
181
+ const which = i.autopilot ? 'Autopilot (the end-of-turn check and the pre-PR gate)' : 'The pre-PR gate';
182
+ tail.push(`${which}: installed in this repo but inactive for this person — it is on the Team plan and they have no licence, so nothing checks their work automatically. Tell them once, in plain words, and that ${TRIAL}; never say autopilot checked anything.`);
183
+ } else if (i.autopilot) tail.push('Autopilot: on — at turn end, review changed behavior in new and annotated files and follow the proving choice for affected claims');
174
184
  if (i.codegraph === 'current') tail.push('Code graph: current');
175
185
  else if (i.codegraph === 'cli') tail.push('Code graph: ask it with `bravos graph <question> --json` (same answers as the codegraph_ tools; e.g. attack-surface, entry-points, callers, reachable-sinks, call-chain); if it says no graph, build it: bravos graph build . (bravos-codegraph)');
176
186
  else if (i.codegraph === 'not-built') tail.push('Code graph: none for this commit — bravos keys a graph to the commit it was built at, so a new commit needs a rebuild: bravos graph build . --scip no-exec (bravos-codegraph; no tokens, a few minutes). Until then skills trace routes by reading.');
@@ -323,8 +333,21 @@ export async function collect(root, env, { deadlineMs = 20000, nextCount = 3 } =
323
333
  git(['rev-parse', '--abbrev-ref', 'HEAD']),
324
334
  ]);
325
335
  const base = ref || 'origin/main';
326
- const diff = await git(['diff', '--name-only', `${base}...HEAD`], budget());
327
- return { sha: sha ?? 'unknown', base, branch: branch && branch !== 'HEAD' ? branch : null, changedFiles: diff ? diff.split('\n').filter(Boolean) : [] };
336
+ const name = branch && branch !== 'HEAD' ? branch : null;
337
+ const later = (args) => git(args, budget());
338
+ const [diff, behind, stranded] = await Promise.all([
339
+ later(['diff', '--name-only', `${base}...HEAD`]),
340
+ gitStaleness(later, base),
341
+ strandedBranches(later, base, { current: name }),
342
+ ]);
343
+ return {
344
+ sha: sha ?? 'unknown',
345
+ base,
346
+ branch: name,
347
+ changedFiles: diff ? diff.split('\n').filter(Boolean) : [],
348
+ stale: staleness({ ...behind, branch: name, base }),
349
+ stranded,
350
+ };
328
351
  })();
329
352
 
330
353
  const hasGuardlink = whichOnPath('guardlink', env);
@@ -373,6 +396,8 @@ export async function collect(root, env, { deadlineMs = 20000, nextCount = 3 } =
373
396
  sha: facts.sha,
374
397
  base: facts.base,
375
398
  branch: facts.branch,
399
+ stale: facts.stale,
400
+ stranded: facts.stranded,
376
401
  guardlink,
377
402
  changedFiles: facts.changedFiles,
378
403
  inFlight,
@@ -519,6 +544,7 @@ export function topThreats(exposures, n = 3) {
519
544
  }
520
545
 
521
546
  const SKILL_HINT = {
547
+ 'bravos-resync': 'carry old work',
522
548
  'bravos-recheck': 'recheck a fix',
523
549
  'bravos-context': 'record intent',
524
550
  'bravos-annotate': 'cover unannotated',
@@ -532,6 +558,7 @@ export function quickStart(inputs, harness) {
532
558
  const g = inputs?.guardlink && typeof inputs.guardlink === 'object' ? inputs.guardlink : {};
533
559
  const ci = g.ci;
534
560
  const picks = [];
561
+ if (inputs?.stale || arr(inputs?.stranded).length > 0) picks.push('bravos-resync');
535
562
  if (arr(ci?.confirmed).length > 0) picks.push('bravos-recheck');
536
563
  if (inputs?.intent?.status === 'none') picks.push('bravos-context');
537
564
  const cov = ci?.summary?.coverage;
@@ -581,7 +608,8 @@ function statusLine(i) {
581
608
  const graph = i.codegraph === 'unavailable' ? 'graph off' : i.codegraph === 'not-built' ? 'graph none' : i.codegraph === 'diverged' ? 'graph stale' : 'graph on';
582
609
  const sast = i.sast?.summary ? `sast ${i.sast.summary.reachable} reachable` : i.sast?.available?.ok ? 'sast not run' : 'sast off';
583
610
  const setup = i.root ? readSetup(i.root, i, i.harness) : null;
584
- return `intent ${intent} · ${graph} · pre-PR ${i.prePr ? 'on' : 'off'} · auto ${i.autopilot ? 'on' : 'off'} · ${sast}${setup ? ` · setup ${setup.done}/${setup.total}` : ''}`;
611
+ const hook = (on) => (!on ? 'off' : hooksLocked(i) ? 'locked' : 'on');
612
+ return `intent ${intent} · ${graph} · pre-PR ${hook(i.prePr)} · auto ${hook(i.autopilot)} · ${sast}${setup ? ` · setup ${setup.done}/${setup.total}` : ''}`;
585
613
  }
586
614
 
587
615
  /**
@@ -609,6 +637,9 @@ export function buildBanner(inputs, opts = {}) {
609
637
  }
610
638
  const g = i.guardlink ?? {};
611
639
  lines.push('', countsLine(g), statusLine(i));
640
+ if ((i.autopilot || i.prePr) && hooksLocked(i)) lines.push(`~ ${i.autopilot ? 'autopilot' : 'the pre-PR gate'} is set up here, on the Team plan for you · bravos account activate`);
641
+ if (i.stale) lines.push(`! ${i.branch ?? 'this checkout'} is ${i.stale.behind} behind ${i.base} · findings describe older code · bravos-resync`);
642
+ else if (arr(i.stranded).length > 0) lines.push(`~ annotation work on ${i.stranded[0].branch} is not on ${i.base} · bravos-resync`);
612
643
  if (i.shadow) {
613
644
  lines.push(i.shadow.userNewer
614
645
  ? `~ repo bravos ${i.shadow.repo} is behind your ${i.shadow.user} · run: bravos sync`
@@ -0,0 +1,66 @@
1
+ // @comment -- "Stage only annotation changes, bound JS kits for review and the verified ledger from the separate runner. The authoring agent cannot stage arbitrary files, credentials, reports, policies, workflow edits or its own ledger."
2
+ import { execFileSync } from 'node:child_process';
3
+ import { copyFileSync, existsSync, lstatSync, readFileSync, realpathSync } from 'node:fs';
4
+ import { join, resolve, sep } from 'node:path';
5
+
6
+ const git = (...args) => execFileSync('git', args, { encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 });
7
+ const root = realpathSync(git('rev-parse', '--show-toplevel').trim());
8
+ process.chdir(root);
9
+ if (!process.env.START || git('rev-parse', 'HEAD').trim() !== process.env.START) throw new Error('The author changed HEAD; only changes against the reviewed start commit may be staged.');
10
+ git('restore', '--staged', '--', '.');
11
+ const names = new Set([...git('diff', '--name-only', '-z').split('\0'), ...git('ls-files', '--others', '--exclude-standard', '-z').split('\0')]);
12
+ function regular(path) {
13
+ return existsSync(path) && resolve(path) === realpathSync(path) && lstatSync(path).isFile();
14
+ }
15
+ // @mitigates #replay-ledger against #governance-forgery using #annotation-only-staging -- "a changed line counts as an annotation only when the whole line is a comment that carries one (no code after a closing */ or -->), an agent may never add @accepts, @entitles or @confirmed, and may never remove a line carrying @accepts or @entitles; a file that breaks any of this is left unstaged and named."
16
+ const GOVERNANCE_ADD = /@(?:accepts|entitles|confirmed)\b/;
17
+ const GOVERNANCE_KEEP = /@(?:accepts|entitles)\b/;
18
+ // A whole comment line holding an annotation, in the comment syntaxes annotations are written in.
19
+ const ANNOTATION_LINE = /^(?:\/\/+|#+|--|;+|\*|\/\*+|<!--)\s*@[a-z][\w-]*\b/;
20
+ const COMMENT_ONLY = /^(?:\/\*\*?|\*\/|\*|\/\/+|#+|--)$/;
21
+ function codeAfterClose(line) {
22
+ const close = Math.max(line.lastIndexOf('*/'), line.lastIndexOf('-->'));
23
+ if (close < 0) return false;
24
+ return line.slice(close + (line.startsWith('-->', close) ? 3 : 2)).trim().length > 0;
25
+ }
26
+ function changedLines(name, tracked) {
27
+ if (!tracked) return { added: readFileSync(name, 'utf8').split('\n').map((s) => s.trim()), removed: [] };
28
+ const diff = git('diff', '--no-ext-diff', '--unified=0', '--', name);
29
+ const rows = diff.split('\n').filter((line) => /^[+-]/.test(line) && !/^(--- a\/|\+\+\+ b\/|--- \/dev\/null)/.test(line));
30
+ return { added: rows.filter((l) => l[0] === '+').map((l) => l.slice(1).trim()), removed: rows.filter((l) => l[0] === '-').map((l) => l.slice(1).trim()) };
31
+ }
32
+ const untrackedSet = new Set(git('ls-files', '--others', '--exclude-standard', '-z').split('\0').filter(Boolean));
33
+ const refused = [];
34
+ for (const name of names) {
35
+ if (!name || !regular(name) || /[\x00-\x1f]/.test(name)) continue;
36
+ const isSidecar = /^\.guardlink\/annotations\/.+\.gal$/.test(name);
37
+ const isDefinitions = /^\.guardlink\/definitions\.[a-z]+$/.test(name);
38
+ const isKit = /^\.guardlink\/cxg-replay\/.+\.js$/.test(name) &&
39
+ /^\/\/\s*@(bravos_claim_key|exposure_claim_key):\s*[0-9a-f]{64}:\d+\s*$/m.test(readFileSync(name, 'utf8'));
40
+ if (!(isSidecar || isDefinitions || isKit) && name.split('/').some((part) => part.startsWith('.'))) continue;
41
+ const { added, removed } = changedLines(name, !untrackedSet.has(name));
42
+ // Human decisions and confirmations are never the agent's to add, and acceptances never its to remove.
43
+ if (!isKit && (added.some((l) => GOVERNANCE_ADD.test(l)) || removed.some((l) => GOVERNANCE_KEEP.test(l)))) {
44
+ refused.push(`${name}: adds @accepts/@entitles/@confirmed or removes an @accepts/@entitles line`);
45
+ continue;
46
+ }
47
+ if (!(isSidecar || isDefinitions || isKit)) {
48
+ // Inline annotation edits may change a tracked source file, but only whole annotation or comment lines.
49
+ const changes = [...added, ...removed].filter(Boolean);
50
+ const ok = changes.some((l) => ANNOTATION_LINE.test(l)) &&
51
+ changes.every((l) => (COMMENT_ONLY.test(l) || ANNOTATION_LINE.test(l)) && !codeAfterClose(l));
52
+ if (!ok) { refused.push(`${name}: changes lines that are not whole annotation comments`); continue; }
53
+ }
54
+ git('add', '--', name);
55
+ }
56
+ for (const r of refused) console.log(`Not staged: ${r}`);
57
+ if (process.env.LEDGER === 'yes') {
58
+ const ledger = join(root, '.guardlink', 'hypotheses.json');
59
+ if (realpathSync(join(root, '.guardlink')) !== join(root, '.guardlink') || (lstatSync(ledger, { throwIfNoEntry: false }) && !regular(ledger))) {
60
+ throw new Error('Unsafe destination for verified GuardLink ledger.');
61
+ }
62
+ const incoming = join(process.env.RUNNER_TEMP, 'bravos-verified-ledger', 'hypotheses.json');
63
+ if (!regular(incoming) || !realpathSync(incoming).startsWith(realpathSync(process.env.RUNNER_TEMP) + sep)) throw new Error('Missing verified ledger artifact.');
64
+ copyFileSync(incoming, ledger);
65
+ git('add', '--', '.guardlink/hypotheses.json');
66
+ }
@@ -0,0 +1,45 @@
1
+ #!/usr/bin/env bash
2
+ # @comment -- "Bootstrap the pinned upstream tools on a fresh Actions runner: the released npm and crates.io versions, or, when a pin names a revision, that commit built from source."
3
+ set -euo pipefail
4
+ role=${1:?choose author or replay}
5
+ case "$role" in author|replay|annotate) ;; *) exit 2 ;; esac
6
+ pins="$(dirname "$0")/proof-tool-pins.json"
7
+ guardlink_version=$(jq -er '.guardlink.version' "$pins")
8
+ guardlink_revision=$(jq -r '.guardlink.revision // empty' "$pins")
9
+ guardlink_repo=$(jq -er '.guardlink.repository' "$pins")
10
+ cxg_version=$(jq -er '.cxg.version' "$pins")
11
+ cxg_revision=$(jq -r '.cxg.revision // empty' "$pins")
12
+ cxg_repo=$(jq -er '.cxg.repository' "$pins")
13
+ # Every job uses the same GuardLink: the replay and annotate jobs read the model the author wrote against.
14
+ if test -n "$guardlink_revision"; then
15
+ source_dir=$(mktemp -d "$RUNNER_TEMP/bravos-guardlink-XXXXXX")
16
+ git init -q "$source_dir"
17
+ git -C "$source_dir" fetch --quiet --depth=1 "$guardlink_repo" "$guardlink_revision"
18
+ git -C "$source_dir" checkout --quiet --detach FETCH_HEAD
19
+ test "$(git -C "$source_dir" rev-parse HEAD)" = "$guardlink_revision"
20
+ (
21
+ cd "$source_dir"
22
+ npm ci --include=dev --no-audit --no-fund
23
+ npm run build
24
+ tarball=$(npm pack --ignore-scripts --json | jq -re '.[0].filename')
25
+ npm install -g "./$tarball"
26
+ )
27
+ else
28
+ npm install -g "guardlink@$guardlink_version"
29
+ fi
30
+ test "$role" != annotate || exit 0
31
+ install_root="$RUNNER_TEMP/bravos-cxg"
32
+ if ! test -x "$install_root/bin/cxg"; then
33
+ if test -n "$cxg_revision"; then
34
+ cargo install --locked --root "$install_root" --git "$cxg_repo" --rev "$cxg_revision" cert-x-gen
35
+ else
36
+ cargo install --locked --root "$install_root" "cert-x-gen@$cxg_version"
37
+ fi
38
+ fi
39
+ export PATH="$install_root/bin:$PATH"
40
+ echo "$install_root/bin" >> "$GITHUB_PATH"
41
+ cxg pentest install
42
+ if test "$role" = replay; then
43
+ "$CXG_PYTHON" -m pip install -r "$HOME/.cert-x-gen/pentest/requirements.txt"
44
+ "$CXG_PYTHON" -m playwright install --with-deps chromium
45
+ fi