@bugb-technologies/bravos 1.2.1 → 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/README.md CHANGED
@@ -45,6 +45,7 @@ Or remove it (`pipx uninstall bravos` or `uv tool uninstall bravos`). `which -a
45
45
  | `bravos-env` | Brings up a target the user owns: loopback by default, a reviewed `scope.yaml`, the human's typed authorization, a real session. |
46
46
  | `bravos-prove` | Runs the authorized test and writes outcomes back only through guardlink's hypothesis ledger. |
47
47
  | `bravos-recheck` | After a fix: re-verifies stale claims, replays retest kits, checks the fix added no exposure. |
48
+ | `bravos-resync` | When a checkout is far behind its base or a branch with annotations was left behind: carries the sidecars and definitions onto the base with `bravos resync`, maps duplicate ids, and re-reads every carried claim on code that changed since. |
48
49
  | `bravos-sast` | Licensed static analysis (bravos-cli: Semgrep, request-to-sink taint, dependency CVEs, secrets, IaC) joined to the threat model and the code graph; says plainly when it is unavailable. Its runs land in `.bravos/sast/` (not committed), and `bravos sast candidates` hands them on: reachable findings joined to a claim give bravos-templatize and bravos-prove the route to target, findings not in the threat model are leads for bravos-annotate, and bravos-recheck rescans after a fix. A static finding is a lead; only a run confirms. |
49
50
  | `bravos-schedule` | Recurring upkeep: an in-session `/loop`, the nightly workflow, or a cloud task you create. Never live tests. |
50
51
  | `bravos-cicd` | Audits and writes the security workflows; fixes broken guardlink calls and script-injection risks. |
package/dist/cli.js CHANGED
@@ -19,7 +19,7 @@ import { GUIDE_TOPIC_IDS, renderGuide, renderGuideMarkdown } from './guide.js';
19
19
  import { detectHarnesses } from './detect.js';
20
20
  import { formatDoctor, runDoctor, withLicence } from './doctor.js';
21
21
  import { ensureGuardlink, registerPrePr, whichBin, writeScope } from './guardlink.js';
22
- import { installHook } from './hooks.js';
22
+ import { installHook, installedOptIns } from './hooks.js';
23
23
  import { activate, importLicence } from './account.js';
24
24
  import { listDevices, logout, refresh as refreshDevice, revokeDevice } from './device.js';
25
25
  import * as graph from './codegraph.js';
@@ -185,6 +185,15 @@ function pipeline(root, io, opts, withGuardlink, lines) {
185
185
  lines.push(`omp: skipped ${omp.path} — ${omp.reason}`);
186
186
  else if (omp.status !== 'absent')
187
187
  lines.push(`omp: ${omp.path} ${omp.status} (banner and briefing at session start)`);
188
+ // A hook the repo already registers stays registered: sync re-applies what is installed, so an
189
+ // opt-in is given once, not on every sync (removing one is bravos uninstall, or editing the settings).
190
+ const installed = installedOptIns(root);
191
+ const autopilotKept = !opts.autopilot && installed.autopilot;
192
+ const prePrKept = !opts.prePrHook && !opts.autopilot && installed.prePr && !installed.autopilot;
193
+ if (autopilotKept)
194
+ opts.autopilot = true;
195
+ if (prePrKept)
196
+ opts.prePrHook = true;
188
197
  // Autopilot is the pre-PR gate plus the end-of-turn check.
189
198
  if (opts.autopilot)
190
199
  opts.prePrHook = true;
@@ -255,7 +264,11 @@ function pipeline(root, io, opts, withGuardlink, lines) {
255
264
  const ocWritten = oc.status === 'done' ? [...oc.written, ...(oc.mcpAdded.length ? [OPENCODE_CONFIG] : [])] : [];
256
265
  const written = [...skills.written, ...skills.updated, ...mirror.written, ...mirror.updated, ...cursorWritten, ...ompWritten, ...ocWritten, ...workflowWritten, ...hook.copied, ...hook.registered.map((r) => r.file), ...guardlinkWritten];
257
266
  lines.push(...gitignoreWarnings(root, written, io.env));
258
- if (opts.autopilot) {
267
+ if (autopilotKept)
268
+ lines.push('autopilot: kept (already installed); BRAVOS_AUTOPILOT=off pauses the check.');
269
+ else if (prePrKept)
270
+ lines.push('pre-PR gate: kept (already installed).');
271
+ if (opts.autopilot && !autopilotKept) {
259
272
  lines.push('autopilot on: an end-of-turn check (Stop hook) sends the agent back once when changed code lacks annotations, sits under a confirmed or stale claim, or adds exposures; the pre-PR gate checks every gh pr create / gh pr ready.');
260
273
  lines.push('autopilot: the first time proving comes up, the agent asks you once how you want it handled and records your answer in .guardlink/proving.md. BRAVOS_AUTOPILOT=off pauses the check.');
261
274
  }
@@ -706,6 +719,25 @@ export function buildProgram(io, result) {
706
719
  }
707
720
  lines.push('', s.next ? `Next: ${s.next.label} — ${s.next.how}` : 'Everything bravos can use here is on.', 'More: bravos guide · bravos guide roles · bravos guide tasks', 'Live view: bravos watch (in a second terminal pane)');
708
721
  }));
722
+ program
723
+ .command('resync [dir]')
724
+ .description('Carry GuardLink annotation work from another branch or commit onto this checkout (external mode sidecars and the definitions they need): a dry run unless --apply; then reanchors, validates and lists what to re-read. --list shows idle branches with annotation work the base lacks. Runs no model.')
725
+ .option('--from <ref>', 'the branch or commit whose annotation work to carry here')
726
+ .option('--apply', 'write the sidecars and definitions, then reanchor and validate')
727
+ .option('--list', 'show this checkout\'s staleness and the idle branches with annotation work not on the base')
728
+ .option('--json', 'print the report as JSON (bravos.resync/v1)')
729
+ .action((dir, opts) => guardedAsync(async (lines) => {
730
+ const root = dirArg(dir);
731
+ const r = await import('./resync.js');
732
+ if (opts.list) {
733
+ lines.push(...(await r.listStranded(root, io.env)));
734
+ return;
735
+ }
736
+ if (!opts.from)
737
+ throw new BravosError('bravos resync: name the work to carry with --from <branch or commit>, or use --list to find it');
738
+ const report = r.resync(root, opts.from, { apply: !!opts.apply, env: io.env });
739
+ lines.push(...(opts.json ? [JSON.stringify(report, null, 2)] : r.formatReport(report)));
740
+ }));
709
741
  program
710
742
  .command('watch [dir]')
711
743
  .description('A live, read-only view of the repository\'s security work for a second terminal pane beside any agent: setup, open and confirmed exposures, what to test next, stale claims, the code graph, SAST, teammates\' PRs and autopilot nudges. Redraws when files change. Runs no model.')
package/dist/doctor.js CHANGED
@@ -1,10 +1,10 @@
1
- import { existsSync, readdirSync, readFileSync } from 'node:fs';
1
+ import { existsSync, readdirSync } from 'node:fs';
2
2
  import { homedir } from 'node:os';
3
3
  import { join } from 'node:path';
4
4
  import { installedGuardlinkSkills, whichBin } from './guardlink.js';
5
5
  import { graphBin } from './codegraph.js';
6
6
  import { findAnalyzer, findLicence } from './graphbin.js';
7
- import { AUTOPILOT_COMMAND, HOOK_COMMANDS, LEGACY_HOOK_COMMAND, PRE_PR_COMMAND } from './hooks.js';
7
+ import { AUTOPILOT_COMMAND, HOOK_COMMANDS, LEGACY_HOOK_COMMAND, PRE_PR_COMMAND, hookRegistered } from './hooks.js';
8
8
  import { skillsRoot } from './skills.js';
9
9
  import { resolveTheme } from './palette.js';
10
10
  const TOOLS = [
@@ -37,18 +37,6 @@ function guardlinkSkills(root, harness) {
37
37
  }
38
38
  }
39
39
  // @comment -- "True when a harness settings file registers one of bravos's commands under the given hook event (the per-harness SessionStart command or its pre-0.5.0 form); unreadable or malformed files read as not registered."
40
- function hookRegistered(file, event, commands) {
41
- try {
42
- const json = JSON.parse(readFileSync(file, 'utf8'));
43
- const groups = json?.hooks?.[event];
44
- if (!Array.isArray(groups))
45
- return false;
46
- return groups.some((g) => Array.isArray(g?.hooks) && g.hooks.some((h) => typeof h?.command === 'string' && commands.includes(h.command)));
47
- }
48
- catch {
49
- return false;
50
- }
51
- }
52
40
  /** Read-only environment check: PATH lookups and file reads only. */
53
41
  // @comment -- "Read-only environment check: looks up guardlink, cxg, codegraph-mcp and bravos-cli on PATH, the optional licence, guardlink initialisation, installed bravos and guardlink playbook skills per root, and hook registration; runs nothing."
54
42
  export function runDoctor(root, env = process.env) {
package/dist/guide.js CHANGED
@@ -118,6 +118,7 @@ export const GUIDE_TOPICS = [
118
118
  { 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.'] },
119
119
  { 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.'] },
120
120
  { 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.'] },
121
+ { 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.'] },
121
122
  { 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.'] },
122
123
  { 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.'] },
123
124
  { 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.'] },
@@ -132,7 +133,7 @@ export const GUIDE_TOPICS = [
132
133
  {
133
134
  id: 'skills',
134
135
  title: 'Every skill',
135
- summary: 'all fourteen skills, what each does and leaves for the next',
136
+ summary: 'all fifteen skills, what each does and leaves for the next',
136
137
  items: [
137
138
  { name: 'bravos', body: ['Front door: reads the security picture, explains the evidence loop, routes to the right skill.'] },
138
139
  { name: 'bravos-context', body: ['Learns what the product intends from the repo and a short interview; records invariants, intended behaviour, actors, assets and boundaries.'] },
@@ -143,6 +144,7 @@ export const GUIDE_TOPICS = [
143
144
  { name: 'bravos-env', body: ['Brings up a target you own: loopback by default, a committed reviewed scope.yaml, your typed authorization, a real session captured or imported.'] },
144
145
  { name: 'bravos-prove', body: ['Runs the authorized test, reads cxg\'s report and exit code, writes outcomes only through guardlink\'s hypothesis ledger.'] },
145
146
  { name: 'bravos-recheck', body: ['After a fix: stale claims, retest-kit replay, no new exposure, what to test next.'] },
147
+ { name: 'bravos-resync', body: ['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.'] },
146
148
  { name: 'bravos-sast', body: ['Licensed static analysis joined to guardlink claims and reachability; gates on findings new since the base.'] },
147
149
  { name: 'bravos-campaign', body: ['A goal over many rounds: disjoint batches, one subagent each, a gate per batch, rests, a final before-and-after.'] },
148
150
  { name: 'bravos-schedule', body: ['Recurring upkeep with each harness\'s own mechanism; never live tests from a loop.'] },
package/dist/help.js CHANGED
@@ -11,9 +11,11 @@ What bravos is
11
11
  Commands
12
12
  init [dir] First install in a repository. Runs guardlink init if .guardlink/ is absent.
13
13
  sync [dir] Re-apply bravos to a repository that already has it (after upgrading bravos,
14
- or to add --ci / --pre-pr-hook / --scope / --autopilot later). Never runs
15
- guardlink init. init and sync take --global for a user-level install.
14
+ or to add --ci / --pre-pr-hook / --scope / --autopilot later; hooks already
15
+ installed stay installed). Never runs guardlink init. init and sync take --global for a user-level install.
16
16
  doctor [dir] Read-only check of tools, licence, installed skills and hooks.
17
+ resync [dir] Carry annotation work from another branch onto this checkout: --from <ref>
18
+ (a dry run; --apply writes, reanchors and validates), or --list to find it.
17
19
  uninstall [dir]
18
20
  Remove bravos from a repository (--global: from your user), keeping
19
21
  anything you edited unless --force; --dry-run lists it first.
@@ -87,6 +89,8 @@ The skills it installs (one folder each in .claude/skills/ and .agents/skills/)
87
89
  bravos-prove Runs the authorized test, reads cxg's verdicts, writes outcomes back
88
90
  only through guardlink's hypothesis ledger.
89
91
  bravos-recheck After a fix: re-verifies stale claims, replays retest kits.
92
+ bravos-resync Carries annotation work a stale or abandoned branch holds onto the base,
93
+ then re-reads every carried claim on code that changed since.
90
94
  bravos-sast Licensed static analysis; says plainly when it is unavailable.
91
95
  bravos-schedule /loop while you work, the nightly workflow, or a cloud task you create.
92
96
  bravos-cicd Writes and audits the security GitHub Actions workflows.
package/dist/hooks.js CHANGED
@@ -111,6 +111,27 @@ function planRegistration(root, rel, regs) {
111
111
  return { file: rel, changed, doc };
112
112
  }
113
113
  // @comment -- "The command Antigravity runs from .agents/hooks.json; --harness agy makes the hook print Antigravity's injectSteps."
114
+ // @comment -- "True when a harness settings file registers one of the given commands under the event; read-only, an unreadable or malformed file reads as not registered. Doctor and sync share it."
115
+ export function hookRegistered(file, event, commands) {
116
+ try {
117
+ const json = JSON.parse(readFileSync(file, 'utf8'));
118
+ const groups = json?.hooks?.[event];
119
+ if (!Array.isArray(groups))
120
+ return false;
121
+ return groups.some((g) => Array.isArray(g?.hooks) && g.hooks.some((h) => typeof h?.command === 'string' && commands.includes(h.command)));
122
+ }
123
+ catch {
124
+ return false;
125
+ }
126
+ }
127
+ // @comment -- "Which opt-in hooks a repository already registers for Claude Code or Codex, so sync re-applies them without the flag being given again."
128
+ export function installedOptIns(root) {
129
+ const files = [join(root, '.claude', 'settings.json'), join(root, '.codex', 'hooks.json')];
130
+ return {
131
+ autopilot: files.some((f) => hookRegistered(f, 'Stop', [AUTOPILOT_COMMAND])),
132
+ prePr: files.some((f) => hookRegistered(f, 'PreToolUse', [PRE_PR_COMMAND])),
133
+ };
134
+ }
114
135
  export const AGY_HOOK_COMMAND = `${LEGACY_HOOK_COMMAND} --harness agy`;
115
136
  export const AGY_HOOKS_FILE = '.agents/hooks.json';
116
137
  const AGY_GROUP = { SessionStart: [{ type: 'command', command: AGY_HOOK_COMMAND, timeout: 30 }] };
package/dist/resync.js ADDED
@@ -0,0 +1,272 @@
1
+ // @comment -- "bravos resync: carries GuardLink annotation work from another branch or commit (sidecars, external mode) onto this checkout, mechanically and with no model: copies the sidecars whose source file still exists and that this checkout lacks, appends the definitions they reference and this checkout does not define (flagging ones that look like an existing id under another name), then with --apply reanchors and validates, and reports what moved, what lost its symbol and which files changed since the claims were written. A dry run unless --apply; never merges two sidecars, never deletes, never touches the source branch. Inline mode copies nothing and points at merge or cherry-pick. --list prints local branches carrying annotation work their base lacks."
2
+ import { spawnSync } from 'node:child_process';
3
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
4
+ import { dirname, join } from 'node:path';
5
+ import { pathToFileURL } from 'node:url';
6
+ import { hooksDir } from './paths.js';
7
+ import { BravosError } from './types.js';
8
+ export const SIDECAR_DIR = '.guardlink/annotations/';
9
+ export const RESYNC_RECORD = '.bravos/resync/last.json';
10
+ // @comment -- "Read-only git over argv (no shell): stdout, or null on any failure or non-zero exit. Output is capped generously because ls-tree and show of a large definitions file can be big."
11
+ function gitIn(root, env) {
12
+ return (args) => {
13
+ const r = spawnSync('git', args, { cwd: root, env, encoding: 'utf8', timeout: 30000, maxBuffer: 256 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] });
14
+ return r.error || r.status !== 0 ? null : r.stdout;
15
+ };
16
+ }
17
+ // @comment -- "Runs guardlink over argv with a long timeout and returns its exit status and combined output; a missing guardlink reads as status null, which the report states rather than failing."
18
+ function guardlink(root, env, args) {
19
+ const r = spawnSync('guardlink', args, { cwd: root, env, encoding: 'utf8', timeout: 300000, maxBuffer: 256 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
20
+ if (r.error)
21
+ return { status: null, out: '' };
22
+ return { status: r.status, out: `${r.stdout ?? ''}\n${r.stderr ?? ''}` };
23
+ }
24
+ // @comment -- "Option-injection guard: --from reaches git as an argument, so a value beginning with '-' (e.g. --output=…) is refused before any git call, and the ref must resolve to a commit."
25
+ export function assertRef(ref) {
26
+ if (typeof ref !== 'string' || ref.length === 0 || ref.startsWith('-') || /[\0\n]/.test(ref)) {
27
+ throw new BravosError(`bravos resync: --from needs a branch or commit name (got "${ref}")`);
28
+ }
29
+ }
30
+ /** Definitions declared on lines of a definitions file: `@asset Name (#id)`, `@threat …`, `@control …`, `@actor …`. */
31
+ // @comment -- "Pure parser for one-line GuardLink declarations (@asset, @threat, @control, @actor with a (#id)), keeping the raw line so it can be carried verbatim; the CWE is read from a cwe:CWE-n token when present."
32
+ export function parseDefinitions(text) {
33
+ const out = [];
34
+ for (const line of text.split('\n')) {
35
+ const m = /@(asset|threat|control|actor)\s+(\S+)\s*\(#([A-Za-z0-9][\w.-]*)\)/.exec(line);
36
+ if (!m)
37
+ continue;
38
+ const cwe = /cwe:(CWE-\d+)/i.exec(line);
39
+ out.push({ kind: m[1], name: m[2], id: m[3], cwe: cwe ? cwe[1].toUpperCase() : null, line: line.trimEnd() });
40
+ }
41
+ return out;
42
+ }
43
+ /** The #ids a sidecar's annotation lines reference, outside their quoted descriptions. */
44
+ // @comment -- "Pure extractor: for each @ line other than @source and @comment, the #ids before its ` -- \"` description, so a # inside prose is never mistaken for a reference; a parenthesised (#id), which names the annotation itself, is skipped."
45
+ export function referencedIds(sidecar) {
46
+ const ids = new Set();
47
+ for (const raw of sidecar.split('\n')) {
48
+ const line = raw.trim();
49
+ if (!line.startsWith('@') || line.startsWith('@source') || line.startsWith('@comment'))
50
+ continue;
51
+ // A parenthesised (#id) names the annotation itself (a @boundary's own id): a declaration, not a reference.
52
+ const head = line.split(' -- "')[0].replace(/\(#[A-Za-z0-9][\w.-]*\)/g, '');
53
+ for (const m of head.matchAll(/#([A-Za-z0-9][\w.-]*)/g))
54
+ ids.add(m[1]);
55
+ }
56
+ return ids;
57
+ }
58
+ const norm = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, '');
59
+ /** Existing definitions that look like the same thing as `d`: same kind, and the same CWE or the same normalized name. */
60
+ // @comment -- "Pure duplicate heuristic for a carried definition: an existing one of the same kind with the same CWE, or whose name or id normalizes the same; only ever a suggestion for a person or agent to map."
61
+ export function duplicatesOf(d, existing) {
62
+ return existing
63
+ .filter((e) => e.kind === d.kind && e.id !== d.id && ((d.cwe && e.cwe === d.cwe) || norm(e.name) === norm(d.name) || norm(e.id) === norm(d.id)))
64
+ .map((e) => e.id);
65
+ }
66
+ function readConfig(root) {
67
+ try {
68
+ const c = JSON.parse(readFileSync(join(root, '.guardlink', 'config.json'), 'utf8'));
69
+ return { mode: c?.annotation_mode === 'external' ? 'external' : 'inline', definitions: typeof c?.definitions === 'string' ? c.definitions : 'definitions.ts' };
70
+ }
71
+ catch {
72
+ return { mode: 'inline', definitions: 'definitions.ts' };
73
+ }
74
+ }
75
+ function coverage(root, env) {
76
+ const r = guardlink(root, env, ['ci', '-f', 'json']);
77
+ try {
78
+ const c = JSON.parse(r.out.slice(r.out.indexOf('{'), r.out.lastIndexOf('}') + 1))?.summary?.coverage;
79
+ return c ? { annotated_files: c.annotated_files, source_files: c.source_files, annotations: c.annotations } : null;
80
+ }
81
+ catch {
82
+ return null;
83
+ }
84
+ }
85
+ /** Sidecars `guardlink reanchor` reports by kind: { moved: [...], symbol_gone: [...] }. */
86
+ // @comment -- "Pure parser for guardlink reanchor's text report: each [kind] `sidecar` line, grouped by kind."
87
+ export function parseReanchor(out) {
88
+ const by = {};
89
+ for (const m of out.matchAll(/\[(moved|symbol_gone|line_gone|file_gone)\] `([^`]+)`/g))
90
+ (by[m[1]] ??= []).push(m[2]);
91
+ return by;
92
+ }
93
+ /**
94
+ * Plans (and with apply, performs) carrying annotation work from `from` onto the checkout at `root`.
95
+ */
96
+ // @comment -- "The resync pipeline: resolve the ref, classify its sidecars against this checkout, gather missing definitions and duplicate suggestions, then with apply write sidecars and a marked definitions block, reanchor, validate and measure coverage; the report is also saved to .bravos/resync/last.json (ignored scratch) for the bravos-resync skill. Writes only under .guardlink/ and .bravos/resync/, and only with apply."
97
+ export function resync(root, from, opts = {}) {
98
+ const env = opts.env ?? process.env;
99
+ assertRef(from);
100
+ const git = gitIn(root, env);
101
+ const sha = git(['rev-parse', '--verify', '--quiet', `${from}^{commit}`])?.trim();
102
+ if (!sha)
103
+ throw new BravosError(`bravos resync: ${from} is not a branch or commit in this repository`);
104
+ const head = git(['rev-parse', 'HEAD'])?.trim();
105
+ if (head === sha)
106
+ throw new BravosError(`bravos resync: ${from} is this checkout's own commit; check out the branch you want to carry the work onto first`);
107
+ const { mode, definitions } = readConfig(root);
108
+ const commitsNotHere = Number(git(['rev-list', '--count', `HEAD..${sha}`])?.trim() ?? 0);
109
+ const report = {
110
+ schema: 'bravos.resync/v1', from, sha, mode, applied: false,
111
+ copied: [], both: [], same: 0, sourceGone: [],
112
+ definitionsCarried: [], definitionsMissing: [], possibleDuplicates: [], changedSince: [],
113
+ reanchored: null, symbolGone: [], validate: null, coverage: { before: null, after: null },
114
+ commitsNotHere, note: null,
115
+ };
116
+ if (mode === 'inline') {
117
+ report.note = `inline mode: annotations live in source comments, so they travel with code. Bring the ${commitsNotHere} commit(s) on ${from} over with git merge or git cherry-pick, then run guardlink validate and bravos-resync's re-read step.`;
118
+ return save(root, report, false);
119
+ }
120
+ const listed = (git(['ls-tree', '-r', '--name-only', sha, '--', SIDECAR_DIR]) ?? '').split('\n').filter((f) => f.endsWith('.gal'));
121
+ const carried = new Map();
122
+ for (const f of listed) {
123
+ const src = f.slice(SIDECAR_DIR.length, -'.gal'.length);
124
+ if (!existsSync(join(root, src))) {
125
+ report.sourceGone.push(src);
126
+ continue;
127
+ }
128
+ const theirs = git(['show', `${sha}:${f}`]);
129
+ if (theirs === null)
130
+ continue;
131
+ if (existsSync(join(root, f))) {
132
+ if (readFileSync(join(root, f), 'utf8') === theirs)
133
+ report.same++;
134
+ else
135
+ report.both.push(f);
136
+ continue;
137
+ }
138
+ carried.set(f, theirs);
139
+ report.copied.push(f);
140
+ // Changed since: the source file here differs from the one the claims were written against.
141
+ const diff = spawnSync('git', ['diff', '--quiet', sha, '--', src], { cwd: root, env, stdio: 'ignore', timeout: 30000 });
142
+ if (diff.status === 1)
143
+ report.changedSince.push(src);
144
+ }
145
+ const defsRel = join('.guardlink', definitions);
146
+ const ours = existsSync(join(root, defsRel)) ? parseDefinitions(readFileSync(join(root, defsRel), 'utf8')) : [];
147
+ const theirsDefs = parseDefinitions(git(['show', `${sha}:${defsRel}`]) ?? '');
148
+ const known = new Set(ours.map((d) => d.id));
149
+ const needed = new Set();
150
+ for (const text of carried.values())
151
+ for (const id of referencedIds(text))
152
+ if (!known.has(id))
153
+ needed.add(id);
154
+ const carriedDefs = [];
155
+ for (const id of [...needed].sort()) {
156
+ const d = theirsDefs.find((x) => x.id === id);
157
+ if (!d) {
158
+ report.definitionsMissing.push(id);
159
+ continue;
160
+ }
161
+ carriedDefs.push(d);
162
+ report.definitionsCarried.push(id);
163
+ const dup = duplicatesOf(d, ours);
164
+ if (dup.length)
165
+ report.possibleDuplicates.push({ id, kind: d.kind, candidates: dup });
166
+ }
167
+ if (!opts.apply)
168
+ return save(root, report, false);
169
+ report.coverage.before = coverage(root, env);
170
+ const before = parseReanchor(guardlink(root, env, ['reanchor', '.']).out);
171
+ for (const [f, text] of carried) {
172
+ mkdirSync(dirname(join(root, f)), { recursive: true });
173
+ writeFileSync(join(root, f), text);
174
+ }
175
+ if (carriedDefs.length) {
176
+ const block = ['', `// ─── carried from ${from}@${sha.slice(0, 12)} by bravos resync (map possible duplicates, then drop them here) ───`, ...carriedDefs.map((d) => d.line), ''].join('\n');
177
+ const path = join(root, defsRel);
178
+ const existing = existsSync(path) ? readFileSync(path, 'utf8') : '';
179
+ writeFileSync(path, existing.replace(/\n*$/, '\n') + block);
180
+ }
181
+ const moved = parseReanchor(guardlink(root, env, ['reanchor', '.']).out).moved ?? [];
182
+ const apply = guardlink(root, env, ['reanchor', '.', '--apply']);
183
+ if (apply.status !== null) {
184
+ const copiedSet = new Set(report.copied);
185
+ const existingMoved = new Set(before.moved ?? []);
186
+ report.reanchored = { carried: moved.filter((f) => copiedSet.has(f)).length, existing: moved.filter((f) => existingMoved.has(f)).length };
187
+ report.symbolGone = [...new Set(parseReanchor(guardlink(root, env, ['reanchor', '.']).out).symbol_gone ?? [])].filter((f) => copiedSet.has(f));
188
+ const v = guardlink(root, env, ['validate', '.']);
189
+ const counts = /(\d+) error\(s\), (\d+) warning\(s\)/.exec(v.out);
190
+ report.validate = counts ? { errors: Number(counts[1]), warnings: Number(counts[2]) } : null;
191
+ report.coverage.after = coverage(root, env);
192
+ }
193
+ else {
194
+ report.note = 'guardlink not found on PATH: sidecars and definitions were written, but nothing was reanchored or validated; install guardlink and run guardlink reanchor . --apply';
195
+ }
196
+ report.applied = true;
197
+ return save(root, report, true);
198
+ }
199
+ // @comment -- "Saves the report to .bravos/resync/last.json, with a .gitignore of * beside it so the scratch never reaches git; a failure to save never fails the resync."
200
+ function save(root, report, _applied) {
201
+ try {
202
+ const dir = join(root, dirname(RESYNC_RECORD));
203
+ mkdirSync(dir, { recursive: true });
204
+ if (!existsSync(join(dir, '.gitignore')))
205
+ writeFileSync(join(dir, '.gitignore'), '*\n');
206
+ writeFileSync(join(root, RESYNC_RECORD), JSON.stringify(report, null, 2) + '\n');
207
+ }
208
+ catch {
209
+ /* the record is a convenience for the skill */
210
+ }
211
+ return report;
212
+ }
213
+ /** Report lines for a person. */
214
+ // @comment -- "Formats a ResyncReport as plain lines: what would be (or was) carried, what needs a person, and the next step."
215
+ export function formatReport(r) {
216
+ const verb = r.applied ? 'carried' : 'would carry';
217
+ const lines = [`bravos resync from ${r.from} (${r.sha.slice(0, 12)}), ${r.mode} mode${r.applied ? '' : ' — dry run, nothing written'}`];
218
+ if (r.note)
219
+ lines.push(r.note);
220
+ if (r.mode === 'inline')
221
+ return lines;
222
+ lines.push(`Sidecars: ${verb} ${r.copied.length} · already here ${r.same} · both have differing sidecars ${r.both.length} · source file gone ${r.sourceGone.length}`);
223
+ lines.push(`Definitions: ${verb} ${r.definitionsCarried.length}${r.definitionsMissing.length ? ` · referenced but defined nowhere ${r.definitionsMissing.length} (${r.definitionsMissing.slice(0, 5).join(', ')})` : ''}`);
224
+ if (r.possibleDuplicates.length) {
225
+ lines.push(`Possible duplicates to map onto this checkout's ids (${r.possibleDuplicates.length}):`);
226
+ for (const d of r.possibleDuplicates.slice(0, 10))
227
+ lines.push(` #${d.id} (${d.kind}) ~ ${d.candidates.map((c) => `#${c}`).join(', ')}`);
228
+ if (r.possibleDuplicates.length > 10)
229
+ lines.push(` … and ${r.possibleDuplicates.length - 10} more (in ${RESYNC_RECORD})`);
230
+ }
231
+ lines.push(`Changed since the claims were written: ${r.changedSince.length} file(s); re-read their annotations against today's code`);
232
+ if (r.both.length)
233
+ lines.push(`Both sides annotate ${r.both.length} file(s); not merged: ${r.both.slice(0, 3).join(', ')}${r.both.length > 3 ? ' …' : ''}`);
234
+ if (r.applied) {
235
+ if (r.reanchored)
236
+ lines.push(`Reanchored: ${r.reanchored.carried} carried sidecar(s), plus ${r.reanchored.existing} that had already drifted here`);
237
+ if (r.symbolGone.length)
238
+ lines.push(`Symbol gone (rewrite or drop): ${r.symbolGone.length} — ${r.symbolGone.slice(0, 3).join(', ')}${r.symbolGone.length > 3 ? ' …' : ''}`);
239
+ if (r.validate)
240
+ lines.push(`guardlink validate: ${r.validate.errors} error(s), ${r.validate.warnings} warning(s)`);
241
+ const c = (x) => (x ? `${x.annotated_files}/${x.source_files} files, ${x.annotations} annotations` : 'unknown');
242
+ lines.push(`Coverage: ${c(r.coverage.before)} → ${c(r.coverage.after)}`);
243
+ lines.push('Next: bravos-resync maps the duplicates, re-reads the changed files and drops what lost its code; nothing here is verified.');
244
+ }
245
+ else {
246
+ lines.push(`Next: bravos resync --from ${r.from} --apply`);
247
+ }
248
+ lines.push(`Details: ${RESYNC_RECORD}`);
249
+ return lines;
250
+ }
251
+ /** Stranded annotation work and the checkout's own staleness, from the hooks' shared helper. */
252
+ // @comment -- "bravos resync --list: the checkout's staleness against its base and the idle local branches carrying .guardlink/ work the base lacks, using hooks/lib/resync.mjs (the same answer the session briefing gives)."
253
+ export async function listStranded(root, env = process.env) {
254
+ const lib = await import(pathToFileURL(join(hooksDir(), 'lib', 'resync.mjs')).href);
255
+ const g = gitIn(root, env);
256
+ const git = async (args) => g(args)?.trim() ?? null;
257
+ const base = (await git(['symbolic-ref', '-q', '--short', 'refs/remotes/origin/HEAD'])) || 'origin/main';
258
+ const branchRef = await git(['rev-parse', '--abbrev-ref', 'HEAD']);
259
+ const branch = branchRef && branchRef !== 'HEAD' ? branchRef : null;
260
+ const stale = lib.staleness({ ...(await lib.gitStaleness(git, base)), branch, base });
261
+ const stranded = await lib.strandedBranches(git, base, { current: branch });
262
+ const lines = [];
263
+ lines.push(stale ? lib.staleLine(stale, { branch, base }) : `This checkout${branch ? ` (${branch})` : ''} is current with ${base} (as of last fetch).`);
264
+ if (stranded.length === 0)
265
+ lines.push(`No idle local branch carries annotation work that ${base} lacks.`);
266
+ else {
267
+ lines.push(`Idle branches with annotation work not on ${base}:`);
268
+ for (const s of stranded)
269
+ lines.push(` ${s.branch}: ${s.files} .guardlink/ file(s) — bravos resync --from ${s.branch}`);
270
+ }
271
+ return lines;
272
+ }
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.1",
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.
@@ -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.