@bugb-technologies/bravos 1.2.0 → 1.3.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.
package/docs/GUIDE.md CHANGED
@@ -130,6 +130,12 @@ Skills: `/bravos-templatize` · `/bravos-env` · `/bravos-prove`
130
130
 
131
131
  Template → authorized target → run. Only a reproduced run confirms; reading code never does.
132
132
 
133
+ ### My branch moved, or I found old annotation work
134
+
135
+ Skills: `/bravos-resync`
136
+
137
+ 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.
138
+
133
139
  ### I fixed a finding
134
140
 
135
141
  Skills: `/bravos-recheck`
@@ -222,6 +228,10 @@ Runs the authorized test, reads cxg's report and exit code, writes outcomes only
222
228
 
223
229
  After a fix: stale claims, retest-kit replay, no new exposure, what to test next.
224
230
 
231
+ ### bravos-resync
232
+
233
+ A stale checkout or a left-behind branch: carries its annotation work onto the base with bravos resync, maps duplicate ids, re-reads every carried claim on changed code.
234
+
225
235
  ### bravos-sast
226
236
 
227
237
  Licensed static analysis joined to guardlink claims and reachability; gates on findings new since the base.
@@ -1,47 +1,18 @@
1
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."
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, fingerprint, readSnapshot, workingChanges } from './snapshot.mjs';
7
+
8
+ export { asyncRunner, readSnapshot, safeSessionId, takeSnapshot } from './snapshot.mjs';
6
9
 
7
10
  export const AUTOPILOT_DEADLINE_MS = 20000;
8
- const OUTPUT_CAP = 64 * 1024 * 1024;
9
11
  const TRANSCRIPT_TAIL = 4 * 1024 * 1024;
10
12
  const MAX_LIST = 5;
11
13
 
12
14
  const arr = (v) => (Array.isArray(v) ? v : []);
13
15
 
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
16
 
46
17
  async function json(run, args, o) {
47
18
  const r = await run('guardlink', args, o);
@@ -57,13 +28,44 @@ async function json(run, args, o) {
57
28
  import { readProving } from './proving.mjs';
58
29
  export { readProving };
59
30
 
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 };
31
+ /** Paths bravos itself writes: never "changed code" for the check, whatever git says about them. */
32
+ const GENERATED_PREFIXES = ['.bravos/', '.claude/skills/', '.agents/skills/', '.opencode/', '.omp/'];
33
+ // Hook settings: bravos's own entries live here, and agent configuration is reported by guardlink diff, not annotations.
34
+ const GENERATED_FILES = new Set(['.claude/settings.json', '.codex/hooks.json', '.agents/hooks.json', 'opencode.json']);
35
+
36
+ // @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."
37
+ function lockedFiles(root) {
38
+ try {
39
+ const files = JSON.parse(readFileSync(join(root, '.bravos', 'skills.lock'), 'utf8'))?.files;
40
+ return new Set(files && typeof files === 'object' ? Object.keys(files) : []);
41
+ } catch {
42
+ return new Set();
43
+ }
44
+ }
45
+
46
+ // @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."
47
+ export function isGenerated(path, locked = new Set()) {
48
+ return GENERATED_FILES.has(path) || locked.has(path) || GENERATED_PREFIXES.some((p) => path.startsWith(p));
49
+ }
50
+
51
+ /**
52
+ * Files this session changed: with a start snapshot, working-tree files whose content differs from what
53
+ * the snapshot recorded plus files touched by commits made since it; without one, every working-tree
54
+ * change since HEAD. Bravos's own generated files are never included.
55
+ */
56
+ // @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."
57
+ export async function changedFiles(root, env, run, snapshot = null) {
58
+ const now = await workingChanges(root, env, run);
63
59
  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());
60
+ if (snapshot) {
61
+ for (const rel of now) if (snapshot.files[rel] === undefined || snapshot.files[rel] !== fingerprint(root, rel)) out.add(rel);
62
+ const committed = await run('git', ['diff', '--name-only', `${snapshot.head}..HEAD`], { cwd: root, env });
63
+ if (committed.status === 0) for (const l of committed.stdout.split('\n')) if (l.trim()) out.add(l.trim());
64
+ } else {
65
+ for (const rel of now) out.add(rel);
66
+ }
67
+ const locked = lockedFiles(root);
68
+ for (const rel of [...out]) if (isGenerated(rel, locked)) out.delete(rel);
67
69
  return out;
68
70
  }
69
71
 
@@ -100,9 +102,17 @@ export async function runAutopilot({ root, env = process.env, payload = {}, run
100
102
  if (!existsSync(join(root, '.guardlink'))) return { decision: 'allow' };
101
103
  const o = { cwd: root, env, timeoutMs: deadlineMs };
102
104
 
103
- const changed = await changedFiles(root, env, run);
105
+ const snapshot = readSnapshot(root, payload?.session_id);
106
+ const changed = await changedFiles(root, env, run, snapshot);
104
107
  if (changed.size === 0) return { decision: 'allow' };
105
108
 
109
+ // A checkout far behind its base: its model describes older code, so say that before anything else.
110
+ const git = (args) => run('git', args, o).then((r) => (r.status === 0 ? r.stdout.trim() : null));
111
+ const [baseRef, branchRef] = await Promise.all([git(['symbolic-ref', '-q', '--short', 'refs/remotes/origin/HEAD']), git(['rev-parse', '--abbrev-ref', 'HEAD'])]);
112
+ const base = baseRef || 'origin/main';
113
+ const branch = branchRef && branchRef !== 'HEAD' ? branchRef : null;
114
+ const behind = staleness({ ...(await gitStaleness(git, base)), branch, base });
115
+
106
116
  // The two fast guardlink calls, side by side; a missing guardlink or a timeout reads as nothing found.
107
117
  const [wl, ci] = await Promise.all([json(run, ['unannotated', '--json'], o), json(run, ['ci', '-f', 'json'], o)]);
108
118
 
@@ -110,6 +120,12 @@ export async function runAutopilot({ root, env = process.env, payload = {}, run
110
120
  // A short, stable key per finding: the same finding is raised once per session, a changed one again.
111
121
  const add = (key, line) => findings.push({ key: `[bravos-autopilot:${key.split(':')[0]}:${createHash('sha256').update(key).digest('hex').slice(0, 10)}]`, line });
112
122
 
123
+ if (behind) {
124
+ 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.`);
125
+ // Without a snapshot the changed set may be someone else's old edits; the stale line is the whole answer.
126
+ if (!snapshot) return finish(findings, payload);
127
+ }
128
+
113
129
  const worklist = arr(wl?.worklist).map((w) => (typeof w === 'string' ? w : w?.file ?? w?.path)).filter((f) => changed.has(f));
114
130
  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
131
 
@@ -139,6 +155,11 @@ export async function runAutopilot({ root, env = process.env, payload = {}, run
139
155
  add(`prove:${ids.sort().join(',')}`, `${open.length} open exposure(s) sit on files this turn changed (${listOf(ids)}): ${next}.`);
140
156
  }
141
157
 
158
+ return finish(findings, payload);
159
+ }
160
+
161
+ // @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."
162
+ function finish(findings, payload) {
142
163
  if (findings.length === 0) return { decision: 'allow' };
143
164
  const seen = transcriptTail(payload?.transcript_path);
144
165
  const fresh2 = findings.filter((f) => !seen.includes(f.key));
@@ -6,6 +6,7 @@ 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
11
  import { readSetup, setupLine } from './setup.mjs';
11
12
  import { memberCounts, readWorkspace, workspaceLines } from './workspace.mjs';
@@ -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));
@@ -323,8 +329,21 @@ export async function collect(root, env, { deadlineMs = 20000, nextCount = 3 } =
323
329
  git(['rev-parse', '--abbrev-ref', 'HEAD']),
324
330
  ]);
325
331
  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) : [] };
332
+ const name = branch && branch !== 'HEAD' ? branch : null;
333
+ const later = (args) => git(args, budget());
334
+ const [diff, behind, stranded] = await Promise.all([
335
+ later(['diff', '--name-only', `${base}...HEAD`]),
336
+ gitStaleness(later, base),
337
+ strandedBranches(later, base, { current: name }),
338
+ ]);
339
+ return {
340
+ sha: sha ?? 'unknown',
341
+ base,
342
+ branch: name,
343
+ changedFiles: diff ? diff.split('\n').filter(Boolean) : [],
344
+ stale: staleness({ ...behind, branch: name, base }),
345
+ stranded,
346
+ };
328
347
  })();
329
348
 
330
349
  const hasGuardlink = whichOnPath('guardlink', env);
@@ -373,6 +392,8 @@ export async function collect(root, env, { deadlineMs = 20000, nextCount = 3 } =
373
392
  sha: facts.sha,
374
393
  base: facts.base,
375
394
  branch: facts.branch,
395
+ stale: facts.stale,
396
+ stranded: facts.stranded,
376
397
  guardlink,
377
398
  changedFiles: facts.changedFiles,
378
399
  inFlight,
@@ -519,6 +540,7 @@ export function topThreats(exposures, n = 3) {
519
540
  }
520
541
 
521
542
  const SKILL_HINT = {
543
+ 'bravos-resync': 'carry old work',
522
544
  'bravos-recheck': 'recheck a fix',
523
545
  'bravos-context': 'record intent',
524
546
  'bravos-annotate': 'cover unannotated',
@@ -532,6 +554,7 @@ export function quickStart(inputs, harness) {
532
554
  const g = inputs?.guardlink && typeof inputs.guardlink === 'object' ? inputs.guardlink : {};
533
555
  const ci = g.ci;
534
556
  const picks = [];
557
+ if (inputs?.stale || arr(inputs?.stranded).length > 0) picks.push('bravos-resync');
535
558
  if (arr(ci?.confirmed).length > 0) picks.push('bravos-recheck');
536
559
  if (inputs?.intent?.status === 'none') picks.push('bravos-context');
537
560
  const cov = ci?.summary?.coverage;
@@ -609,6 +632,8 @@ export function buildBanner(inputs, opts = {}) {
609
632
  }
610
633
  const g = i.guardlink ?? {};
611
634
  lines.push('', countsLine(g), statusLine(i));
635
+ if (i.stale) lines.push(`! ${i.branch ?? 'this checkout'} is ${i.stale.behind} behind ${i.base} · findings describe older code · bravos-resync`);
636
+ else if (arr(i.stranded).length > 0) lines.push(`~ annotation work on ${i.stranded[0].branch} is not on ${i.base} · bravos-resync`);
612
637
  if (i.shadow) {
613
638
  lines.push(i.shadow.userNewer
614
639
  ? `~ repo bravos ${i.shadow.repo} is behind your ${i.shadow.user} · run: bravos sync`
@@ -0,0 +1,78 @@
1
+ // @comment -- "Staleness and stranded-work facts shared by the session briefing, the autopilot Stop hook and bravos resync: how far the checkout's branch is behind its base (as of the last fetch, never fetching), and which local branches carry .guardlink/ work their base does not have. Read-only git calls through a runner the caller supplies (argv, no shell); every failure reads as nothing to report."
2
+
3
+ /** A branch this many commits behind its base is stale whatever its age. */
4
+ export const STALE_BEHIND = 20;
5
+ /** A branch any number of commits behind is stale once its shared base is older than this. */
6
+ export const STALE_DAYS = 7;
7
+ /** How many local branches, most recently committed first, are looked at for stranded annotation work. */
8
+ export const STRANDED_SCAN = 10;
9
+
10
+ const DAY_MS = 86400000;
11
+
12
+ /**
13
+ * Decides whether a checkout is stale. `behind` is commits on the base not on HEAD; `baseAge` is the
14
+ * shared base's commit time in seconds. Returns { behind, baseDate } or null when nothing is worth saying.
15
+ */
16
+ // @comment -- "Pure threshold: stale at STALE_BEHIND commits behind, or any commits behind with a shared base older than STALE_DAYS; never stale on the base branch itself or with unreadable inputs."
17
+ export function staleness({ behind, baseAge, branch, base, now = Date.now() } = {}) {
18
+ const n = Number(behind);
19
+ if (!Number.isFinite(n) || n <= 0) return null;
20
+ if (branch && base && (base === branch || base.endsWith(`/${branch}`))) return null;
21
+ const at = Number(baseAge) * 1000;
22
+ const old = Number.isFinite(at) && at > 0 && now - at > STALE_DAYS * DAY_MS;
23
+ if (n < STALE_BEHIND && !old) return null;
24
+ return { behind: n, baseDate: Number.isFinite(at) && at > 0 ? new Date(at).toISOString().slice(0, 10) : null };
25
+ }
26
+
27
+ /**
28
+ * Reads behind-count and shared-base time for HEAD against `base`. `git(args)` resolves to trimmed
29
+ * stdout or null. Resolves { behind, baseAge } with nulls where git could not answer.
30
+ */
31
+ // @comment -- "Two read-only git calls against the last-fetched base ref: rev-list --count HEAD..base and the merge-base's commit time."
32
+ export async function gitStaleness(git, base) {
33
+ const [behind, mb] = await Promise.all([git(['rev-list', '--count', `HEAD..${base}`]), git(['merge-base', 'HEAD', base])]);
34
+ const baseAge = mb ? await git(['log', '-1', '--format=%ct', mb]) : null;
35
+ return { behind: behind === null ? null : Number(behind), baseAge: baseAge === null ? null : Number(baseAge) };
36
+ }
37
+
38
+ /**
39
+ * Local branches that look left behind (no commit for STALE_DAYS) yet carry `.guardlink/` changes their
40
+ * base does not have: [{ branch, files }], most recently committed first. A branch being worked on is a
41
+ * feature branch, not stranded work, so it is never listed; nor is `current` (the stale line covers it).
42
+ */
43
+ // @comment -- "Lists up to STRANDED_SCAN local branches by recency, keeps those idle for STALE_DAYS other than the base and the current branch, and counts the .guardlink/ files each changed since it left base (base...branch); branches with nothing there are dropped."
44
+ export async function strandedBranches(git, base, { scan = STRANDED_SCAN, current = null, now = Date.now() } = {}) {
45
+ const refs = await git(['for-each-ref', '--sort=-committerdate', `--count=${scan}`, '--format=%(refname:short) %(committerdate:unix)', 'refs/heads']);
46
+ if (!refs) return [];
47
+ const short = base.replace(/^origin\//, '');
48
+ const names = refs
49
+ .split('\n')
50
+ .map((l) => l.trim().split(' '))
51
+ .filter(([name, at]) => name && name !== short && name !== current && now - Number(at) * 1000 > STALE_DAYS * DAY_MS)
52
+ .map(([name]) => name);
53
+ const found = await Promise.all(
54
+ names.map(async (branch) => {
55
+ const out = await git(['diff', '--name-only', `${base}...${branch}`, '--', '.guardlink/']);
56
+ const files = out ? out.split('\n').filter(Boolean).length : 0;
57
+ return files > 0 ? { branch, files } : null;
58
+ }),
59
+ );
60
+ return found.filter(Boolean);
61
+ }
62
+
63
+ /** The briefing line for a stale checkout, or null. */
64
+ // @comment -- "Formats the stale-checkout line the agent reads: how far behind, since when, and the two ways out (update the branch, or carry its annotations with bravos-resync)."
65
+ export function staleLine(s, { branch, base }) {
66
+ if (!s) return null;
67
+ const since = s.baseDate ? ` (shared base ${s.baseDate}, as of last fetch)` : ' (as of last fetch)';
68
+ return `Branch: ${branch ?? 'this checkout'} is ${s.behind} commits behind ${base}${since}. The model below describes that older code: update the branch, or carry its annotation work to ${base} with bravos-resync.`;
69
+ }
70
+
71
+ /** The briefing line for stranded annotation work, or null. */
72
+ // @comment -- "Formats the stranded-work line: up to three branches with their .guardlink/ file counts, then a count of the rest."
73
+ export function strandedLine(list, base) {
74
+ if (!Array.isArray(list) || list.length === 0) return null;
75
+ const shown = list.slice(0, 3).map((b) => `${b.branch} (${b.files} files)`).join(', ');
76
+ const more = list.length > 3 ? ` and ${list.length - 3} more` : '';
77
+ return `Annotation work not on ${base}: ${shown}${more}; bravos-resync carries it.`;
78
+ }
@@ -0,0 +1,123 @@
1
+ // @comment -- "The session-start snapshot autopilot compares against: the working-tree changes present when a session began (path to content fingerprint) and HEAD at that moment, written to .bravos/watch/turn-base/<session_id>.json (the watch folder ignores itself), plus the read-only spawn runner both hooks use. Kept apart from autopilot.mjs because the session-start hook imports it and plugin hook bundles ship without the autopilot module."
2
+ import { createHash } from 'node:crypto';
3
+ import { spawn } from 'node:child_process';
4
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
5
+ import { join } from 'node:path';
6
+
7
+ const OUTPUT_CAP = 64 * 1024 * 1024;
8
+
9
+ // @comment -- "Async spawn with the pre-PR runner's result shape: argv array, no shell, stdin closed, output capped, killed at timeoutMs; never rejects."
10
+ export function asyncRunner(cmd, args, { cwd, env, timeoutMs = 20000 }) {
11
+ return new Promise((resolve) => {
12
+ let child;
13
+ try {
14
+ child = spawn(cmd, args, { cwd, env, stdio: ['ignore', 'pipe', 'ignore'] });
15
+ } catch (e) {
16
+ resolve({ missing: e?.code === 'ENOENT', error: e?.code ?? String(e), status: null, stdout: '' });
17
+ return;
18
+ }
19
+ const chunks = [];
20
+ let size = 0;
21
+ let done = false;
22
+ const finish = (r) => {
23
+ if (done) return;
24
+ done = true;
25
+ clearTimeout(timer);
26
+ resolve(r);
27
+ };
28
+ child.stdout.on('data', (b) => {
29
+ if (size < OUTPUT_CAP) chunks.push(b);
30
+ size += b.length;
31
+ });
32
+ const timer = setTimeout(() => {
33
+ child.kill('SIGKILL');
34
+ finish({ status: null, error: 'ETIMEDOUT', stdout: '' });
35
+ }, timeoutMs);
36
+ child.on('error', (e) => finish({ missing: e.code === 'ENOENT', error: e.code ?? e.message, status: null, stdout: '' }));
37
+ child.on('close', (status) => finish({ status, stdout: Buffer.concat(chunks).toString('utf8') }));
38
+ });
39
+ }
40
+
41
+ /** Files changed in the working tree since HEAD, tracked or not (bravos's own files included). */
42
+ // @comment -- "Lists working-tree changes since HEAD (git diff --name-only HEAD) plus untracked files (ls-files --others --exclude-standard); read-only argv spawns."
43
+ export async function workingChanges(root, env, run) {
44
+ const o = { cwd: root, env };
45
+ const out = new Set();
46
+ const [diff, untracked] = await Promise.all([run('git', ['diff', '--name-only', 'HEAD'], o), run('git', ['ls-files', '--others', '--exclude-standard'], o)]);
47
+ if (diff.status === 0) for (const l of diff.stdout.split('\n')) if (l.trim()) out.add(l.trim());
48
+ if (untracked.status === 0) for (const l of untracked.stdout.split('\n')) if (l.trim()) out.add(l.trim());
49
+ return out;
50
+ }
51
+
52
+ /** A session id safe to use as a file name, or null. */
53
+ // @comment -- "Path-traversal guard: the Stop and SessionStart payloads' session_id becomes a file name only when it is 1-128 characters of [A-Za-z0-9_-]; anything else (a slash, dots, empty) means no snapshot, never a path outside .bravos/watch/turn-base"
54
+ export function safeSessionId(id) {
55
+ return typeof id === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(id) ? id : null;
56
+ }
57
+
58
+ export const SNAPSHOT_MAX_FILES = 2000;
59
+ const SNAPSHOT_MAX_BYTES = 2 * 1024 * 1024;
60
+ const SNAPSHOT_KEEP_MS = 7 * 86400000;
61
+ const snapshotDir = (root) => join(root, '.bravos', 'watch', 'turn-base');
62
+
63
+ // @comment -- "A cheap fingerprint of one working-tree file: sha1 of its content, size and mtime for a file over 2 MB, 'absent' when it cannot be read (deleted counts as a state too)."
64
+ export function fingerprint(root, rel) {
65
+ try {
66
+ const st = statSync(join(root, rel));
67
+ if (st.size > SNAPSHOT_MAX_BYTES) return `size:${st.size}:${st.mtimeMs}`;
68
+ return 'sha1:' + createHash('sha1').update(readFileSync(join(root, rel))).digest('hex');
69
+ } catch {
70
+ return 'absent';
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Records what the working tree already held when a session started, so the end-of-turn check can
76
+ * tell this session's changes from edits that were there before it. Never throws.
77
+ */
78
+ // @comment -- "Writes .bravos/watch/turn-base/<session_id>.json = {head, files: {path: fingerprint}} for the working-tree changes present at session start (at most SNAPSHOT_MAX_FILES), keeps an existing snapshot for the same session (a resume or compact keeps the session's own start), and prunes snapshots older than seven days; the watch folder ignores itself in git."
79
+ export async function takeSnapshot(root, sessionId, { env = process.env, run = asyncRunner, now = Date.now() } = {}) {
80
+ const id = safeSessionId(sessionId);
81
+ if (!id) return null;
82
+ try {
83
+ const dir = snapshotDir(root);
84
+ const file = join(dir, `${id}.json`);
85
+ if (existsSync(file)) return file;
86
+ const o = { cwd: root, env, timeoutMs: 5000 };
87
+ const head = await run('git', ['rev-parse', 'HEAD'], o);
88
+ if (head.status !== 0) return null;
89
+ const files = {};
90
+ let n = 0;
91
+ for (const rel of await workingChanges(root, env, run)) {
92
+ if (n++ >= SNAPSHOT_MAX_FILES) break;
93
+ files[rel] = fingerprint(root, rel);
94
+ }
95
+ mkdirSync(dir, { recursive: true });
96
+ const ignore = join(root, '.bravos', 'watch', '.gitignore');
97
+ if (!existsSync(ignore)) writeFileSync(ignore, '*\n');
98
+ writeFileSync(file, JSON.stringify({ at: new Date(now).toISOString(), head: head.stdout.trim(), files, truncated: n > SNAPSHOT_MAX_FILES }));
99
+ for (const f of readdirSync(dir)) {
100
+ try {
101
+ if (f.endsWith('.json') && now - statSync(join(dir, f)).mtimeMs > SNAPSHOT_KEEP_MS) rmSync(join(dir, f));
102
+ } catch {
103
+ /* a snapshot that cannot be pruned is harmless */
104
+ }
105
+ }
106
+ return file;
107
+ } catch {
108
+ return null;
109
+ }
110
+ }
111
+
112
+ // @comment -- "Reads a session's start snapshot; a missing, unreadable or malformed one is null, which keeps the pre-snapshot behaviour."
113
+ export function readSnapshot(root, sessionId) {
114
+ const id = safeSessionId(sessionId);
115
+ if (!id) return null;
116
+ try {
117
+ const s = JSON.parse(readFileSync(join(snapshotDir(root), `${id}.json`), 'utf8'));
118
+ return s && typeof s.head === 'string' && s.files && typeof s.files === 'object' ? s : null;
119
+ } catch {
120
+ return null;
121
+ }
122
+ }
123
+
@@ -1,9 +1,10 @@
1
- // @comment -- "SessionStart hook entry (--global: the user-level copy, silent where the repo has its own bravos hook or no .guardlink/; --briefing prints only the briefing text, for a skill that runs it by hand): reads the hook payload from stdin (bounded wait, bad input ignored; source, and Antigravity's workspacePaths), awaits collect() (read-only guardlink, git and gh facts under a shared 20 s deadline), and prints one JSON envelope: the briefing as additionalContext for the model, plus on a fresh start a banner as systemMessage for the human (brand-coloured; a three-line summary for Codex). With --harness agy it prints Antigravity's injectSteps instead. Always exits 0 so a session never fails to start."
1
+ // @comment -- "SessionStart hook entry (--global: the user-level copy, silent where the repo has its own bravos hook or no .guardlink/; --briefing prints only the briefing text, for a skill that runs it by hand): reads the hook payload from stdin (bounded wait, bad input ignored; source, and Antigravity's workspacePaths), awaits collect() (read-only guardlink, git and gh facts under a shared 20 s deadline) and, where autopilot is registered, the session-start snapshot of the working tree (.bravos/watch/turn-base), and prints one JSON envelope: the briefing as additionalContext for the model, plus on a fresh start a banner as systemMessage for the human (brand-coloured; a three-line summary for Codex). With --harness agy it prints Antigravity's injectSteps instead. Always exits 0 so a session never fails to start."
2
2
  import { existsSync } from 'node:fs';
3
3
  import { dirname, join } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
- import { buildBanner, buildBriefing, buildSummary, collect, readVersion } from './lib/briefing.mjs';
5
+ import { autopilotRegistered, buildBanner, buildBriefing, buildSummary, collect, readVersion } from './lib/briefing.mjs';
6
6
  import { resolveTheme } from './lib/palette.mjs';
7
+ import { takeSnapshot } from './lib/snapshot.mjs';
7
8
 
8
9
  const STDIN_WAIT_MS = 1000;
9
10
 
@@ -58,7 +59,10 @@ async function main() {
58
59
  if (process.argv.includes('--global') && (existsSync(join(root, '.bravos', 'hooks', 'session-start.mjs')) || !existsSync(join(root, '.guardlink')))) {
59
60
  process.exit(0);
60
61
  }
61
- const inputs = await collect(root, env);
62
+ // Where autopilot is on, record what the working tree held at the start, beside the briefing, so its
63
+ // end-of-turn check judges only this session's changes (no autopilot, nothing written).
64
+ const snap = autopilotRegistered(root) ? takeSnapshot(root, payload.session_id, { env }) : null;
65
+ const [inputs] = await Promise.all([collect(root, env), snap]);
62
66
  text = buildBriefing(inputs);
63
67
  if (env.BRAVOS_BANNER !== 'off' && (source === null || source === 'startup') && harness !== 'agy') {
64
68
  const version = readVersion(dirname(fileURLToPath(import.meta.url)));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bugb-technologies/bravos",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "description": "Skills pack and installer that make Claude Code and Codex power users of guardlink (threat-model-as-code) and cert-x-gen (pentest-as-code).",
5
5
  "keywords": [
6
6
  "security",
@@ -26,6 +26,7 @@ description: "Start here in any repo bravos is installed in: reads the security
26
26
  standing up a test target, seeding test users, capturing a session → bravos-env.
27
27
  proving a finding, testing whether an exposure is exploitable → bravos-prove (after bravos-env).
28
28
  a fix landed, stale claims, closing a security ticket → bravos-recheck.
29
+ the briefing says the branch is far behind its base, annotation work sits on an idle branch, a branch was moved or abandoned → bravos-resync.
29
30
  write up the assessment, a finding, a retest or a brief for leadership → bravos-report.
30
31
  static analysis, dependency, secret or IaC findings → bravos-sast; "what did SAST find" → `bravos sast candidates` (the briefing's `SAST:` line says whether a run exists, or that SAST is unavailable).
31
32
  keep annotating while I work, nightly or periodic runs → bravos-schedule.
@@ -20,7 +20,7 @@ description: "Audit and write the repo's security CI: the bravos PR gate (valida
20
20
  4. Fix what the audit found in workflows bravos did not write: replace a broken guardlink call with the form above, and pass event text through `env:` and quote it in the shell. Show each change to the user before committing it.
21
21
  5. SAST in CI, only when the team has a bravos licence: add a step running `bravos-cli analyze . --ci --fail-on error -f sarif,json -o sast` with the licence from a repo secret, and upload `sast.sarif` under its own code-scanning category.
22
22
  6. Validate the workflows: run `actionlint` on them if it is installed; otherwise parse each as YAML. Fix every error.
23
- 7. Name the secrets and settings the user must add (`ANTHROPIC_API_KEY` or `OPENAI_API_KEY` for the nightly job, the bravos licence for SAST, permission for Actions to create pull requests) without writing any value.
23
+ 7. Name the secrets and settings the user must add (`CLAUDE_CODE_OAUTH_TOKEN` for the Claude nightly, which runs on the user's Claude plan and comes from `claude setup-token`, or `OPENAI_API_KEY` for the Codex one, or for the Copilot nightly `COPILOT_ASSIGN_TOKEN` plus `BRAVOS_LICENCE` as an Agents secret; the bravos licence for SAST, permission for Actions to create pull requests) without writing any value.
24
24
  8. Ship the workflow changes as a pull request through bravos-ship.
25
25
 
26
26
  ## Never
@@ -0,0 +1,52 @@
1
+ ---
2
+ name: bravos-resync
3
+ description: "Carry annotation work that never reached the base branch onto it, and keep it true: when the briefing or autopilot says this checkout is far behind its base or lists idle branches with annotation work, or the user moved, rebased or abandoned a branch with annotations on it. Saves uncommitted work first, runs `bravos resync` to copy the sidecars and definitions and reanchor them, maps ids that duplicate the base's, re-reads every carried claim on code that changed since it was written, drops what lost its code, and opens a PR. Use before annotating or proving on a stale checkout, and before running `bravos resync`."
4
+ ---
5
+ # Bravos resync: old annotation work is a lead, not a fact
6
+
7
+ ## When
8
+
9
+ - The briefing says `Branch: … is N commits behind`, or lists `Annotation work not on <base>`.
10
+ - Autopilot says this checkout is behind its base.
11
+ - The user switched, rebased or abandoned a branch that carried annotations, or found old annotation work and asks whether it is still useful.
12
+
13
+ ## Do
14
+
15
+ 1. Find the base: `git symbolic-ref -q --short refs/remotes/origin/HEAD` prints `origin/<base>` (if empty, use `origin/main`). Run `bravos resync --list` to see how far this checkout is behind and which idle branches carry `.guardlink/` work the base lacks. Tell the user what you found in two lines and ask before you move their checkout.
16
+ 2. Make uncommitted work safe before anything else: on the old branch, commit it as it is with a message that says it is unreviewed work in progress (`git add -A` then `git commit -m "wip: unreviewed annotation drafts, kept for bravos resync"`). That commit is the only copy; a stash can be popped by another session, so never stash.
17
+ 3. Start fresh from the base: `git fetch origin`, then `git switch -c resync/<old-branch> origin/<base>` (in a worktree when this checkout is shared with another session).
18
+ 4. Preview: `bravos resync --from <old-branch>`. Read the counts: sidecars to carry, sidecars both sides have, definitions to carry, possible duplicates, and files changed since the claims were written. With inline annotations it copies nothing and says to bring the commits over with `git cherry-pick` or `git merge` instead; do that, then continue at step 7.
19
+ 5. Apply: `bravos resync --from <old-branch> --apply`. It writes the sidecars and a marked block of carried definitions, runs `guardlink reanchor . --apply`, validates, and saves the full lists to `.bravos/resync/last.json`.
20
+ 6. Map each possible duplicate: read both definitions. When they name the same thing, replace the carried id with the base's in the carried sidecars and delete its line from the carried block. When you are not sure, keep both and list the pair for the user.
21
+ 7. Re-read every annotation in each file on the changed-since list against today's code, with bravos-annotate's rules: a claim that no longer says what the code does is corrected, or removed when its code is gone. Do the same for each sidecar on the symbol-gone list. Use the code graph (bravos-codegraph) to find where moved code went.
22
+ 8. For a file both sides annotate (`both` in the report), compare the two sidecars and carry over only the claims the base's lacks, by hand.
23
+ 9. Check the result: `guardlink validate .`, then `guardlink lint . --since origin/<base>` and fix each finding on lines you carried, then `guardlink diff origin/<base>` to list the exposures this brings back.
24
+ 10. Open a PR from the resync branch. The body says which branch and commit the work came from, how many sidecars and definitions were carried, which ids were mapped, how many files were re-read, what was dropped, and every exposure it reopens, each marked unverified.
25
+
26
+ ## Never
27
+
28
+ - Delete, reset or force-push the old branch or its uncommitted work; that is the user's call, after the PR merges.
29
+ - Stash work to move a checkout, or switch a checkout another session is using.
30
+ - Re-lock a carried claim with `guardlink verify` unless you re-read its code in this session.
31
+ - Write `@accepts`, `@entitles` or `@confirmed` for carried work, or keep an old `@confirmed` line without a replay that reproduces it today.
32
+ - Merge two ids because their names look alike; map only what you read and know is the same.
33
+ - Call carried exposures findings: they are claims about older code until re-read and proven.
34
+
35
+ ## Done when
36
+
37
+ - The old work is in a commit on its branch, and the resync branch starts from the current base.
38
+ - Every possible duplicate is mapped or listed for the user.
39
+ - Every changed-since file and every symbol-gone sidecar was re-read, and each claim corrected, kept or removed.
40
+ - `guardlink validate .` reports no errors, and the PR lists what was carried, mapped, dropped and reopened.
41
+
42
+ ## What it leaves for the next skill
43
+
44
+ - Exposures the carried work reopens, for bravos-prove or bravos-templatize to test.
45
+ - Confirmed claims that came with it, for bravos-recheck to replay.
46
+ - Files still without annotations, for bravos-annotate.
47
+
48
+ ## Go deeper
49
+
50
+ - `{{SKILLS_ROOT}}/bravos-annotate/SKILL.md` — the rules for correcting or removing a claim.
51
+ - `{{SKILLS_ROOT}}/bravos-recheck/SKILL.md` — re-verifying claims after code changes.
52
+ - `{{SKILLS_ROOT}}/bravos-codegraph/SKILL.md` — finding where moved code went.
@@ -16,7 +16,7 @@ description: "Set up recurring security upkeep with each harness's own mechanism
16
16
 
17
17
  1. If the user wants a goal reached in rounds with rests ("100% coverage", "every exposure", subagents per round), that is bravos-campaign; hand it over. Otherwise map the intent to one mechanism and say which: while this session is open → an in-session loop; while the laptop is closed, any harness → the nightly GitHub Actions workflow; while the laptop is closed, Claude Code with a cloud account → a cloud scheduled task the user creates.
18
18
  2. In-session loop (Claude Code only): copy `{{SKILL_DIR}}/loop.md` to `.claude/loop.md`, adjust the steps to the user's request, and commit it. Tell the user to start it with a bare `/loop`, which reads that file; it runs only while the session is open, stops when it exits, and expires after seven days. Codex has no equivalent; offer the nightly workflow instead.
19
- 3. Nightly workflow: run `bravos init --ci` (or `bravos sync --ci` in a repo bravos already set up), keep the variant for the team's harness (`bravos-nightly-claude.yml` or `bravos-nightly-codex.yml`) and delete the other. Tell the user the secret it needs (`ANTHROPIC_API_KEY` or `OPENAI_API_KEY`) and to allow GitHub Actions to create pull requests in the repo settings.
19
+ 3. Nightly workflow: run `bravos init --ci` (or `bravos sync --ci` in a repo bravos already set up), keep the variant for the team's harness (`bravos-nightly-claude.yml` or `bravos-nightly-codex.yml`) and delete the other. A team on GitHub Copilot uses `bravos init --workflows nightly-copilot` instead: it opens an issue each night and assigns it to Copilot's cloud agent, which needs the secret `COPILOT_ASSIGN_TOKEN` (a Copilot user's personal access token) and `BRAVOS_LICENCE` as an Agents secret. Tell the user the secret it needs (`CLAUDE_CODE_OAUTH_TOKEN` for Claude Code, made once with `claude setup-token` so the run uses their Claude plan, or `OPENAI_API_KEY` for Codex) and to allow GitHub Actions to create pull requests in the repo settings.
20
20
  4. Cloud scheduled task: a skill cannot create one. Give the user the prompt to paste into `/schedule`: follow bravos-annotate in slice mode on the next unannotated files, run its lint gate, and open one pull request whose body carries bravos-ship's Security gate section. Tell them the task clones the default branch and runs at most hourly.
21
21
  5. State the spend before the user starts any of them: files per run (the default slice is five) times runs per day, and that each run spends model tokens.
22
22
  6. Nightly scan, opt-in: it replays the kits in `.guardlink/cxg-replay/` and records outcomes through `guardlink hypothesis confirm --from-scan`, and it runs only when `.guardlink/scope.yaml` is committed with an `authorization_attestation` a human typed and reviewed in a PR, and the repo variable `BRAVOS_SCAN_TARGET` is a loopback URL the job starts (repo variable `BRAVOS_APP_START`) or a host in that scope's `host_allowlist`. Otherwise the step prints why it skipped. Tell the user which variables to set and that the scope file is their standing authorization.
@@ -6,9 +6,12 @@
6
6
  # file's human-written attestation the scan step skips and the job annotates only.
7
7
  # The nightly is on the Team plan: add the repo secret BRAVOS_LICENCE (the token from
8
8
  # account.bugb.io/dashboard/license) so the agent's paid skills run; without it they say so and stop.
9
- # Needs the repo secret ANTHROPIC_API_KEY, and Settings > Actions > General > "Allow GitHub
10
- # Actions to create and approve pull requests". Pin the actions to commit SHAs if your
11
- # organisation requires it.
9
+ # Claude Code here signs in with your Claude plan, so the run uses that plan like a session would:
10
+ # run `claude setup-token` once on your machine and store what it prints as the repo secret
11
+ # CLAUDE_CODE_OAUTH_TOKEN. A repo that already set ANTHROPIC_API_KEY keeps working on that key;
12
+ # delete that secret to run on your plan instead. Also enable Settings > Actions > General >
13
+ # "Allow GitHub Actions to create and approve pull requests". Pin the actions to commit SHAs if
14
+ # your organisation requires it.
12
15
  name: bravos nightly (Claude Code)
13
16
 
14
17
  on:
@@ -57,6 +60,7 @@ jobs:
57
60
  - name: Annotate the next slice
58
61
  uses: anthropics/claude-code-action@v1
59
62
  with:
63
+ claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
60
64
  anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
61
65
  prompt: |
62
66
  Follow .claude/skills/bravos-annotate/SKILL.md in slice mode (the default) to cover the