@bugb-technologies/bravos 1.9.2 → 1.11.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.
@@ -133,22 +133,40 @@ export function contextLine(context, harness) {
133
133
  : `${head} — intent.md's rules cite them by id; only ${run} opens the documents themselves`;
134
134
  }
135
135
 
136
- // @comment -- "The briefing's Intent line. While the context gate is closed it also says so in words an agent acts on: do not start threat-modelling, run the context skill first, and how a person declines. A recorded decline is shown with the name and date of the person who made it."
136
+ // @comment -- "The briefing's Intent line. Until a named person confirms what the product is for, it tells the agent to keep annotating against its own draft (drafting one first when there is none, without waiting for answers) and to ask the person once each session to confirm it on the intake page. Right after setup (a fresh hand-off marker) it says to begin in the first reply. A recorded decline is shown with its name and date, and ends the asking."
137
137
  function intentLine(intent, harness, gate, handoff = false) {
138
138
  const run = harness === 'claude' ? '/bravos-context' : 'the bravos-context skill';
139
- // Right after bravos setup (a fresh hand-off marker), the person expects Bravos to begin: the agent starts the context step itself and goes on to annotation, unless their first message asks for something else.
140
- const begin = handoff && intent.status === 'none' ? ` Setup just finished here and the person expects Bravos to begin: start ${run} in your first reply without being asked, and go on to annotation once they have confirmed. If their first message asks for something else, do that and offer this once after.` : '';
141
- const closed = gate && gate.open === false ? `. Context comes first: do not annotate or start a campaign until a named person has confirmed it (or run bravos context decline --by "<name>" themselves).${begin}` : '';
139
+ const open = !gate || gate.open !== false;
140
+ const ask = ' Ask the person once this session to confirm it on the intake page (bravos review intent, a few minutes); keep working meanwhile, and never confirm anything for them.';
141
+ const begin = handoff && !open ? ` Setup just finished here and the person expects Bravos to begin: in your first reply, draft the context (${run}, without waiting for answers), start annotating, and show them the intake page. If their first message asks for something else, do that and start this alongside.` : '';
142
142
  const declined = gate?.state === 'declined' ? `declined by ${gate.by} on ${gate.at}` : '';
143
- if (intent.status === 'none') return declined ? `Intent: ${declined} — severities are not calibrated to the product; ${run} when the team is ready` : `Intent: none — severities are not calibrated to the product; run ${run}${closed}`;
144
- if (intent.status === 'draft') return `Intent: draft (${intent.invariants} invariants, ${intent.drafts} items unconfirmed${declined ? `; context ${declined}` : ''}) — confirm with ${run}${closed}`;
143
+ if (intent.status === 'none') {
144
+ if (declined) return `Intent: ${declined} — severities are not calibrated to the product; ${run} when the team is ready`;
145
+ return `Intent: none yet — draft it with ${run} (without waiting for answers) and annotate against that draft.${open ? '' : ask}${begin}`;
146
+ }
147
+ if (intent.status === 'draft') return `Intent: draft (${intent.invariants} invariants, ${intent.drafts} items unconfirmed${declined ? `; context ${declined}` : ''}) — annotate against this draft; its design rules are tested and can block pull requests, labelled as drafts.${open ? '' : ask}`;
145
148
  return `Intent: confirmed (${intent.invariants} invariants)`;
146
149
  }
147
150
 
148
151
 
149
152
  const SKILL_SIGIL = { claude: '/', codex: '$', omp: '/skill:', opencode: '/' };
150
153
 
151
- // @comment -- "The coaching block the briefing gives the agent in every harness: the Setup line (score and next unlock with its command) and, unless BRAVOS_COACH=off, a few rules for guiding a person who is not a power user — offer once, suggest at natural moments, plain words first, never lecture; shrinks to one rule once most of setup is on."
154
+ // @comment -- "The background annotation pass: while coverage is under 100%, the briefing asks the agent to start one bravos-annotate slice in a subagent in its first reply, beside whatever the person asked, and to say so. Not on resume or compact (the session already had its pass), not in CI (the nightly is the annotator there), not when the person switched it off (bravos prefs set annotate off) or BRAVOS_AUTO_ANNOTATE=off is set, and not when coverage is unknown. With no intent yet the pass starts after the draft is written, so two agents never draft it at once. A harness without subagents offers the pass instead."
155
+ export function backgroundLine(i) {
156
+ const coverage = Number(i.guardlink?.ci?.summary?.coverage?.percent);
157
+ if (!Number.isFinite(coverage) || coverage >= 100) return null;
158
+ if (i.autoAnnotate === false || i.prefs?.annotate?.value === 'off') return null;
159
+ if (i.source === 'resume' || i.source === 'compact') return null;
160
+ const skill = i.harness === 'claude' ? '/bravos-annotate' : 'the bravos-annotate skill';
161
+ const when = i.intent?.status === 'none' ? 'once the draft intent is written' : 'in your first reply';
162
+ const how = i.harness === 'claude'
163
+ ? `start one background annotation pass in a subagent (${skill}, one slice at its default budget) alongside the person's request, and say so in one line`
164
+ : `start one background annotation pass in a subagent (${skill}, one slice at its default budget) alongside the person's request and say so in one line; where this harness has no subagents, offer it once instead`;
165
+ const commits = i.prefs?.commits?.value === 'commit' ? 'it commits only Bravos\'s own files, as the Commits line allows' : 'it commits nothing; it leaves its files for the person';
166
+ return `Background annotation: coverage is ${coverage}% — ${when}, ${how}. It never edits the person's code; ${commits}; when it ends, report in one line what it covered. The person switches this off with bravos prefs set annotate off --by "<their name>".`;
167
+ }
168
+
169
+ // @comment -- "The coaching block the briefing gives the agent in every harness: the Setup line (score and next unlock with its command) and, unless BRAVOS_COACH=off, a few rules for guiding a person who is not a power user — step up rather than stay silent: every security-relevant reply ends with one concrete next step, a question about issues builds and opens the dashboard, each reminder once per topic per session, plain words first, never lecture; shrinks to one rule once most of setup is on."
152
170
  function coachLines(i) {
153
171
  if (!i.root || i.guardlink === 'missing') return [];
154
172
  const s = readSetup(i.root, i, i.harness);
@@ -156,13 +174,13 @@ function coachLines(i) {
156
174
  if (i.env?.BRAVOS_COACH === 'off' || process.env.BRAVOS_COACH === 'off') return out;
157
175
  const k = (n) => (SKILL_SIGIL[i.harness] ? `${SKILL_SIGIL[i.harness]}${n}` : n);
158
176
  if (s.done > 7) {
159
- out.push(`How to help: at natural moments suggest the next bravos step in one plain line (annotate after security edits, ${k('bravos-ship')} before a PR, ${k('bravos-recheck')} after a fix); never nag.`);
177
+ out.push(`How to help: step up, never stay silent — end every security-relevant reply with one concrete next step in one plain line (annotate after security edits, confirm untested exposures with ${k('bravos-prove')}, ${k('bravos-ship')} before a PR, ${k('bravos-recheck')} after a fix); once per topic per session, never nag.`);
160
178
  return out;
161
179
  }
162
180
  out.push(
163
- 'How to help this person (offer, never lecture; one offer per topic per session):',
181
+ 'How to help this person (step up, never stay silent, never lecture; one reminder per topic per session):',
164
182
  `- In your first reply, if setup is under 5 or intent is none, offer once in plain words three starts that fit this repo, in setup order (${i.licence?.licensed === false ? 'on the Free plan: learn what the app intends, annotate the uncovered files, prove the top threats; never lead with a Team-plan step' : 'build the code graph first if it is off, then learn what the app intends, annotate the uncovered files, run SAST, prove the top threats; or check this branch before a PR'}) and \`bravos guide\` for more; then follow their lead.`,
165
- `- After you edit security-relevant code, offer to record what it exposes (${k('bravos-annotate')}); before a PR, run the ship check (${k('bravos-ship')}); after a fix, offer a recheck (${k('bravos-recheck')}).`,
183
+ `- End every security-relevant reply with one concrete next step, said as a recommendation: after you edit security-relevant code, record what it exposes (${k('bravos-annotate')}); with untested exposures, confirm the top three (${k('bravos-prove')}, or ${k('bravos-env')} first when no target is recorded); before a PR, the ship check (${k('bravos-ship')}); after a fix, a recheck (${k('bravos-recheck')}). When they ask about issues, threats or vulnerabilities, build the dashboard while you answer, without waiting on it (\`bravos dashboard\`: it opens in their browser the first time this session, then \`--no-open\` with the path).`,
166
184
  // A standing answer is the briefing's Commits line; with none, ask once and (unless they chose to be asked each time) record it so no later session asks.
167
185
  ...(commitsLine(i.prefs) ? [] : [`- Commits are the person's call: before the first commit of a session ask once (commit now, or leave the files for them to review), even where a skill says to commit; skip the question only when they already asked for commits (a campaign, a schedule).${i.prefs?.commits?.value === 'ask' ? '' : ' Then ask whether that is their answer from now on, and if so record it with `bravos prefs set commits commit|leave --by "<their name>"`: their answer and their name, never yours.'}`]),
168
186
  '- When a request would go better with the next unlock above, say what it would add, once. Plain words first, skill name second. Never send test traffic without the authorization bravos-env asks for.',
@@ -243,6 +261,8 @@ export function buildBriefing(inputs) {
243
261
  // The person's standing answer about commits, when they gave one (hooks/lib/prefs.mjs).
244
262
  const commits = commitsLine(i.prefs);
245
263
  if (commits) tail.push(commits);
264
+ const background = backgroundLine(i);
265
+ if (background) tail.push(background);
246
266
  if (i.proving && typeof i.proving === 'object') {
247
267
  const p = i.proving;
248
268
  tail.push(p.status === 'set'
@@ -556,6 +576,8 @@ export async function collect(root, env, { deadlineMs = 20000, nextCount = 3 } =
556
576
  context: readContext(root),
557
577
  gate: contextGate(root),
558
578
  prefs: readPrefs(facts.commonDir),
579
+ // The background annotation pass is off for this run (BRAVOS_AUTO_ANNOTATE=off) or in CI, where the nightly annotates.
580
+ autoAnnotate: env.BRAVOS_AUTO_ANNOTATE !== 'off' && !env.CI && !env.GITHUB_ACTIONS,
559
581
  handoff: readHandoff(facts.commonDir),
560
582
  upkeep,
561
583
  // Read after the renewal above has run, so a refusal that just arrived is in it.
@@ -0,0 +1,153 @@
1
+ // @comment -- "bravos's coach: before each prompt, at most one dashboard instruction and one reminder for the agent, so Bravos steps up at the moments no skill is loaded. Facts come from a small per-session record the session hook writes under the clone's git directory (<git-common-dir>/bravos/coach/<session>.json), never from guardlink or the network, so the hook stays fast. Each topic is raised once per session; the first prompt gets no reminder (the briefing covers it). Dependency-free."
2
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+
5
+ export const COACH_SCHEMA = 'bravos.coach/v1';
6
+ /** The reminders, in the order they are given when several apply. */
7
+ export const REMINDERS = ['confirm', 'coverage', 'dashboard-stale'];
8
+
9
+ const SESSION_ID = /^[A-Za-z0-9._-]{1,128}$/;
10
+
11
+ // @comment -- "Where a session's coach record lives: under the git directory, like the preferences, so nothing a repository ships can set it; null for a session id that is not a plain token, so a payload cannot point the path elsewhere."
12
+ // @mitigates #person-prefs against #governance-forgery using #prefs-outside-tree -- "The coach record is written under the git directory, never in the working tree."
13
+ export function coachFile(commonDir, sessionId) {
14
+ if (!commonDir || typeof sessionId !== 'string' || !SESSION_ID.test(sessionId) || sessionId.startsWith('.')) return null;
15
+ return join(commonDir, 'bravos', 'coach', `${sessionId}.json`);
16
+ }
17
+
18
+ // @comment -- "Reads a session's coach record; anything that is not exactly the recorded shape reads as none, so a damaged file only means no reminders, never an error."
19
+ export function readCoach(commonDir, sessionId) {
20
+ const file = coachFile(commonDir, sessionId);
21
+ if (!file) return null;
22
+ try {
23
+ const d = JSON.parse(readFileSync(file, 'utf8'));
24
+ if (!d || typeof d !== 'object' || d.schema !== COACH_SCHEMA || !d.facts || typeof d.facts !== 'object') return null;
25
+ return { facts: d.facts, raised: Array.isArray(d.raised) ? d.raised.filter((t) => typeof t === 'string') : [], prompts: Number.isInteger(d.prompts) && d.prompts >= 0 ? d.prompts : 0, opened: d.opened === true };
26
+ } catch {
27
+ return null;
28
+ }
29
+ }
30
+
31
+ // @comment -- "Writes a session's coach record through a temporary file and a rename, 0600. Best effort: a failure only means no reminders this session."
32
+ export function writeCoach(commonDir, sessionId, record) {
33
+ const file = coachFile(commonDir, sessionId);
34
+ if (!file) return null;
35
+ try {
36
+ mkdirSync(join(file, '..'), { recursive: true, mode: 0o700 });
37
+ const tmp = `${file}.tmp-${process.pid}`;
38
+ writeFileSync(tmp, JSON.stringify({ schema: COACH_SCHEMA, ...record }) + '\n', { mode: 0o600 });
39
+ renameSync(tmp, file);
40
+ return file;
41
+ } catch {
42
+ return null;
43
+ }
44
+ }
45
+
46
+ // @comment -- "The facts the coach needs, taken from what the session hook already collected (BriefingInputs): coverage, how many claims guardlink queues to test or fix and the top three, whether a test target is recorded, the plan and the intake state. Pure."
47
+ export function coachFacts(i) {
48
+ const cov = i?.guardlink?.ci?.summary?.coverage;
49
+ const next = i?.guardlink?.next;
50
+ const queue = Array.isArray(next?.queue) ? next.queue : [];
51
+ const num = (v) => (Number.isFinite(Number(v)) ? Number(v) : null);
52
+ return {
53
+ coverage: cov ? { percent: num(cov.percent), annotated: num(cov.annotated_files), source: num(cov.source_files) } : null,
54
+ queued: num(next?.total) ?? queue.length,
55
+ top: queue.slice(0, 3).map((q) => ({ threat: String(q?.threat ?? ''), asset: String(q?.asset ?? ''), file: String(q?.file ?? ''), line: num(q?.line), state: String(q?.state ?? '') })),
56
+ target: i?.proving?.status === 'set' && !!i?.proving?.target,
57
+ licensed: i?.licence?.licensed === true ? true : i?.licence?.licensed === false ? false : null,
58
+ harness: i?.harness === 'claude' ? 'claude' : 'other',
59
+ };
60
+ }
61
+
62
+ // @comment -- "Records the session's facts when it starts. A resume or compact of the same session keeps what was already raised, so a reminder is never given twice in one session."
63
+ export function startCoach(commonDir, sessionId, inputs) {
64
+ const old = readCoach(commonDir, sessionId);
65
+ return writeCoach(commonDir, sessionId, { facts: coachFacts(inputs), raised: old?.raised ?? [], prompts: old?.prompts ?? 0, opened: old?.opened ?? false });
66
+ }
67
+
68
+ // The questions that mean "show me the security picture". Plain "issue" or "bug" counts only with a word that makes it about findings, so "fix this issue" does not open a dashboard.
69
+ const STRONG = /\b(threats?|vulns?|vulnerab\w*|findings?|exposures?|cves?|exploitable|attack surface|threat model|security (?:posture|picture|status|issues?|problems?|risks?)|risks?|risky|dashboard)\b/i;
70
+ const SOFT = /\b(?:what|which|show|list|any|identified|found|open|known|all|remaining|outstanding)\b[^.?!\n]{0,40}\b(?:issues|bugs|problems)\b|\bwhat(?:'s| is) open\b/i;
71
+
72
+ // @comment -- "Whether the person's prompt asks about the security picture: issues, threats, vulnerabilities, findings, risks, exposures, the dashboard. Pure."
73
+ export function asksAboutIssues(prompt) {
74
+ const p = String(prompt ?? '').slice(0, 4000);
75
+ return STRONG.test(p) || SOFT.test(p);
76
+ }
77
+
78
+ // @comment -- "The newest modification time under .guardlink/ (sidecars, definitions, intent, the ledger), bounded to a few thousand entries so the hook stays fast; 0 when there is none. Inline annotations in source files are not seen: the session's own commits are caught by the dashboard's commit."
79
+ export function newestModelChange(root, limit = 4000) {
80
+ let newest = 0;
81
+ let seen = 0;
82
+ const walk = (dir) => {
83
+ let entries;
84
+ try {
85
+ entries = readdirSync(dir, { withFileTypes: true });
86
+ } catch {
87
+ return;
88
+ }
89
+ for (const e of entries) {
90
+ if (++seen > limit) return;
91
+ const p = join(dir, e.name);
92
+ if (e.isDirectory()) walk(p);
93
+ else if (e.isFile()) {
94
+ try {
95
+ newest = Math.max(newest, statSync(p).mtimeMs);
96
+ } catch {
97
+ /* gone */
98
+ }
99
+ }
100
+ }
101
+ };
102
+ if (existsSync(join(root, '.guardlink'))) walk(join(root, '.guardlink'));
103
+ return newest;
104
+ }
105
+
106
+ const where = (t) => `${t.threat}${t.asset ? ` on ${t.asset}` : ''}${t.file ? ` (${t.file}${t.line ? `:${t.line}` : ''})` : ''}`;
107
+
108
+ // @comment -- "Decides what the coach says before one prompt. Returns the text for the agent (or '') and the record to keep. The dashboard instruction comes whenever the prompt asks about the security picture, opening the page only the first time in the session; then at most one reminder, never on the first prompt and never a topic already raised. Free-plan text names no Team step. Pure: the caller supplies the dashboard record and the newest model change."
109
+ export function coachTurn({ record, prompt, dashboard = null, modelChangedAt = 0, head = null }) {
110
+ if (!record?.facts) return { text: '', record, topics: [] };
111
+ const f = record.facts;
112
+ const k = (n) => (f.harness === 'claude' ? `/${n}` : n);
113
+ const raised = new Set(record.raised);
114
+ const lines = [];
115
+ const topics = [];
116
+ let opened = record.opened;
117
+
118
+ if (asksAboutIssues(prompt)) {
119
+ lines.push(opened
120
+ ? 'Bravos: they are asking about the security picture. As you answer, rebuild the dashboard without waiting on it (`bravos dashboard --no-open`, as a background job or subagent) and give its path in one line.'
121
+ : 'Bravos: they are asking about the security picture. As you answer, build the dashboard without waiting on it (`bravos dashboard`, as a background job or subagent): it rebuilds from the code and opens in their browser. Say in one line that it is opening.');
122
+ topics.push(opened ? 'dashboard' : 'dashboard-open');
123
+ opened = true;
124
+ }
125
+
126
+ if (record.prompts > 0) {
127
+ const cov = f.coverage;
128
+ const stale = dashboard && Number.isFinite(dashboard.generatedAt) && (modelChangedAt > dashboard.generatedAt || (head && dashboard.commit && !head.startsWith(dashboard.commit) && !dashboard.commit.startsWith(head)));
129
+ const due = {
130
+ confirm: f.queued > 0,
131
+ coverage: !!cov && Number.isFinite(cov.percent) && cov.percent < 100,
132
+ 'dashboard-stale': !!stale && !topics.length,
133
+ };
134
+ const pick = REMINDERS.find((t) => due[t] && !raised.has(t));
135
+ if (pick === 'confirm') {
136
+ const top = f.top.filter((t) => t.threat).map(where);
137
+ const how = f.target
138
+ ? `${k('bravos-prove')} can test them now on the recorded target`
139
+ : `none has a test target yet, so offer to set one up now with ${k('bravos-env')} (the person types their own authorization), then ${k('bravos-prove')}`;
140
+ lines.push(`Bravos reminder (once this session): ${f.queued} claim${f.queued === 1 ? '' : 's'} wait${f.queued === 1 ? 's' : ''} to be tested or fixed${top.length ? `, starting with ${top.join('; ')}` : ''}. After answering, recommend confirming the top three now: ${how}.`);
141
+ } else if (pick === 'coverage') {
142
+ const files = Number.isFinite(cov.annotated) && Number.isFinite(cov.source) ? ` (${cov.annotated} of ${cov.source} files)` : '';
143
+ const more = f.licensed === false ? `the next round (${k('bravos-annotate')})` : `the next round (${k('bravos-annotate')}), or a campaign to a coverage goal (${k('bravos-campaign')})`;
144
+ lines.push(`Bravos reminder (once this session): the threat model covers ${cov.percent}% of the code${files}. After answering, say so in one line and offer ${more}.`);
145
+ } else if (pick === 'dashboard-stale') {
146
+ lines.push('Bravos reminder (once this session): the threat model changed after the dashboard was built. After answering, offer to rebuild it (`bravos dashboard --no-open`).');
147
+ }
148
+ if (pick) topics.push(pick);
149
+ }
150
+
151
+ const next = { facts: f, raised: [...raised, ...topics.filter((t) => REMINDERS.includes(t))], prompts: record.prompts + 1, opened };
152
+ return { text: lines.join('\n'), record: next, topics };
153
+ }
@@ -400,7 +400,7 @@ export function readContext(root) {
400
400
  export const STATUS_PATH = `${CONTEXT_DIR}/status.json`;
401
401
  export const STATUS_SCHEMA = 'bravos.context-status/v1';
402
402
 
403
- // @comment -- "Whether threat-modelling may start here. Open when .guardlink/intent.md has at least one line a named person agreed to, or when a named person recorded that the team goes without context (.bravos/context/status.json); closed, with what to do, when there is no intent or only an unconfirmed draft. Reads two files and never throws; the same function, byte for byte, ships with the annotate skill."
403
+ // @comment -- "Whether a named person has settled the intake here. Open when .guardlink/intent.md has at least one line a named person agreed to, or when a named person recorded that the team goes without context (.bravos/context/status.json); closed, with a message asking for the intake, when there is no intent or only the agent's draft. Nothing refuses on it any more: annotation, autopilot and the nightlies go on, and the briefing asks once a session while it is closed. Reads two files and never throws; the same function, byte for byte, ships with the annotate skill."
404
404
  // gate:begin — kept identical, between these two markers, in skills/bravos-annotate/scripts/lib/gate.mjs (the copy the
405
405
  // annotate script runs, which cannot import from the hook scripts); tests/context-gate.test.ts holds the two together.
406
406
  const GATE_INTENT = '.guardlink/intent.md';
@@ -435,10 +435,11 @@ export function contextGate(root, fs = { readFileSync, join }) {
435
435
  state,
436
436
  message:
437
437
  (state === 'none'
438
- ? 'Context first: nobody has told bravos what this product is meant to do, so there is nothing to judge its code against.'
439
- : 'Context first: the intent here is still a draft that no named person has confirmed.') +
440
- ' Run the bravos-context skill (it asks for design documents and a few decisions) before threat-modelling.' +
441
- ' If the team chooses to go without, a named person records that: bravos context decline --by "<name>".',
438
+ ? 'Context not recorded yet: nobody has said what this product is meant to do.'
439
+ : 'Context not confirmed yet: the intent here is the agent\'s draft, and no named person has confirmed it.') +
440
+ ' Annotation goes on regardless, judged against the draft (with no intent yet, the bravos-context skill drafts one first, without waiting for answers).' +
441
+ ' Ask the person once this session to confirm it on the intake page: bravos review intent.' +
442
+ ' A team that chooses to go without records that by a named person: bravos context decline --by "<name>".',
442
443
  };
443
444
  }
444
445
  // gate:end
@@ -137,6 +137,26 @@ function ledgerGateClaims(root, run, options) {
137
137
  }
138
138
 
139
139
  // @comment -- "Design rules this branch may have disturbed. A design rule is a threat whose id starts inv- (written by bravos-context from the team's design). For each one, the files that hold a place it is enforced (its @exposes and @mitigates, by logical file and by sidecar) are intersected with the files this branch changed. A rule whose test was last refused (it held) and whose file changed in a commit made after that test is `lapsed`: the result no longer describes the code. A rule no test has tried is only `untested`. File level on purpose: the workflow mirrors this with git and jq, and the two must agree; and a permission flipped in a role table, in another file from the check, lapses nothing in GuardLink's ledger, so the time of the change is what tells."
140
+ // @comment -- "The INV ids in .guardlink/intent.md that no named person has confirmed: an INV-n bullet whose text after the last ' — ' starts with draft, or that has no attribution at all (the same reading as bravos rules). A draft rule blocks like a confirmed one; this only labels it, so the person sees the rule came from the agent's draft."
141
+ function draftRuleIds(root) {
142
+ const ids = new Set();
143
+ const seen = new Set();
144
+ let text = '';
145
+ try {
146
+ text = readFileSync(join(root, '.guardlink', 'intent.md'), 'utf8');
147
+ } catch {
148
+ return ids;
149
+ }
150
+ for (const line of text.split(/\r?\n/)) {
151
+ const m = /^\s*[-*]\s+(INV-\d+)\s*:\s*(.+)$/.exec(line);
152
+ if (!m || seen.has(m[1])) continue;
153
+ seen.add(m[1]);
154
+ const dash = m[2].lastIndexOf(' — ');
155
+ if (dash < 0 || /^draft\b/i.test(m[2].slice(dash + 3).trim())) ids.add(m[1]);
156
+ }
157
+ return ids;
158
+ }
159
+
140
160
  function designRuleChanges(root, base, run, options) {
141
161
  if (!existsSync(join(root, '.guardlink', 'intent.md'))) return { lapsed: [], untested: [] };
142
162
  const model = runJson(run, 'guardlink parse', 'guardlink', ['parse', '.'], options);
@@ -157,13 +177,14 @@ function designRuleChanges(root, base, run, options) {
157
177
  const sites = [...(Array.isArray(model.json.exposures) ? model.json.exposures : []), ...(Array.isArray(model.json.mitigations) ? model.json.mitigations : [])];
158
178
  const lapsed = [];
159
179
  const untested = [];
180
+ const drafts = draftRuleIds(root);
160
181
  for (const t of rules) {
161
182
  const id = bare(t.id);
162
183
  const files = [...new Set(sites.filter(x => bare(x?.threat) === id).flatMap(x => [x.location?.file, x.location?.origin_file]).filter(f => typeof f === 'string' && changed.has(f)))].sort();
163
184
  if (!files.length) continue;
164
185
  const inv = (Array.isArray(t.external_refs) ? t.external_refs : []).map(r => /^intent:(INV-\d+)$/i.exec(String(r))?.[1]).find(Boolean) ?? null;
165
186
  const held = records.filter(r => bare(r?.threat) === id && r.outcome?.outcome === 'refuted' && Number.isFinite(Date.parse(r.outcome?.at)));
166
- const row = { threat: `#${id}`, inv, files };
187
+ const row = { threat: `#${id}`, inv, files, draft: !!inv && drafts.has(inv.toUpperCase()) };
167
188
  if (!held.length) {
168
189
  untested.push(row);
169
190
  continue;
@@ -324,7 +345,7 @@ export function runGate({ root, action, command, cwd = root, env = process.env,
324
345
  const design = designRuleChanges(root, base, run, o);
325
346
  if (design.error) unknown(design);
326
347
  else {
327
- const line = (r) => ` - ${r.inv ? `${r.inv} ` : ''}${r.threat} — ${r.files.join(', ')}${r.tested ? ` (last tested ${r.tested})` : ''}`;
348
+ const line = (r) => ` - ${r.inv ? `${r.inv} ` : ''}${r.draft ? '(draft: not yet confirmed by a person) ' : ''}${r.threat} — ${r.files.join(', ')}${r.tested ? ` (last tested ${r.tested})` : ''}`;
328
349
  if (design.lapsed.length) {
329
350
  let body = null;
330
351
  if (action === 'create') body = commandBody(command, cwd);
@@ -1,4 +1,4 @@
1
- // @comment -- "A person's standing answers to questions Bravos would otherwise ask every session, kept per clone and never committed. Today there is one: what to do with Bravos's own files (annotations, intent, definitions, tests, the ledger) once they are written: commit them, leave them for the person, or keep asking. The file lives under the git directory (<git-common-dir>/bravos/prefs.json), which no commit, clone or pull can write, so a repository cannot ship an answer and grant itself silent commits, and every worktree of a clone shares it. Dependency-free: the session hook reads it, the CLI writes it."
1
+ // @comment -- "A person's standing answers to questions Bravos would otherwise ask every session, kept per clone and never committed. Two today: what to do with Bravos's own files (annotations, intent, definitions, tests, the ledger) once they are written: commit them, leave them for the person, or keep asking; whether the agent starts one background annotation pass each session while coverage is incomplete (background, the default) or not (off); and whether the coach adds reminders before prompts (on, the default) or not (off). The file lives under the git directory (<git-common-dir>/bravos/prefs.json), which no commit, clone or pull can write, so a repository cannot ship an answer and grant itself silent commits, and every worktree of a clone shares it. Dependency-free: the session hook reads it, the CLI writes it."
2
2
  import { spawnSync } from 'node:child_process';
3
3
  import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
4
4
  import { isAbsolute, join, resolve } from 'node:path';
@@ -6,6 +6,12 @@ import { isAbsolute, join, resolve } from 'node:path';
6
6
  export const PREFS_SCHEMA = 'bravos.prefs/v1';
7
7
  /** commit: commit Bravos's own files without asking. leave: never commit them, list them. ask: ask each session (the default when nothing is recorded). */
8
8
  export const COMMIT_CHOICES = ['commit', 'leave', 'ask'];
9
+ /** background: one annotation pass in a subagent each session while coverage is incomplete (the default when nothing is recorded). off: none. */
10
+ export const ANNOTATE_CHOICES = ['background', 'off'];
11
+ /** on: the coach adds a reminder before a prompt when one is due (the default when nothing is recorded). off: none. */
12
+ export const COACH_CHOICES = ['on', 'off'];
13
+ /** Each recorded answer and the choices it may hold. */
14
+ export const PREF_CHOICES = { commits: COMMIT_CHOICES, annotate: ANNOTATE_CHOICES, coach: COACH_CHOICES };
9
15
 
10
16
  // One line of visible text: a name goes into the briefing, so control and invisible characters never do.
11
17
  const clean = (v, max) => String(v ?? '').replace(/[\u0000-\u001F\u007F-\u009F​-‏‪-‮⁠-⁤⁦-⁩]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, max);
@@ -26,10 +32,10 @@ export function commonDirFrom(root, printed) {
26
32
 
27
33
  export const prefsFile = (commonDir) => join(commonDir, 'bravos', 'prefs.json');
28
34
 
29
- // @comment -- "Reads the preferences for a clone. Anything that is not exactly the recorded shape (another schema, an unknown choice, no name, a date that is not a date) reads as nothing recorded, so a damaged or hand-made file can only make Bravos ask again, never commit."
35
+ // @comment -- "Reads the preferences for a clone, each answer on its own. An answer that is not exactly the recorded shape (another schema, an unknown choice, no name, a date that is not a date) reads as nothing recorded, so a damaged or hand-made file can only make Bravos ask again or fall back to its default, never commit."
30
36
  // @mitigates #person-prefs against #governance-forgery using #prefs-outside-tree -- "Only a well-formed record under the git directory counts as the person's answer."
31
37
  export function readPrefs(commonDir) {
32
- const none = { commits: null };
38
+ const none = { commits: null, annotate: null, coach: null };
33
39
  if (!commonDir) return none;
34
40
  let doc;
35
41
  try {
@@ -38,17 +44,27 @@ export function readPrefs(commonDir) {
38
44
  return none;
39
45
  }
40
46
  if (!doc || typeof doc !== 'object' || doc.schema !== PREFS_SCHEMA) return none;
41
- const c = doc.commits;
42
- if (!c || typeof c !== 'object' || !COMMIT_CHOICES.includes(c.value)) return none;
43
- const by = clean(c.by, 80);
44
- if (!by || by.startsWith('<') || typeof c.at !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(c.at)) return none;
45
- return { commits: { value: c.value, by, at: c.at } };
47
+ const one = (key) => {
48
+ const c = doc[key];
49
+ if (!c || typeof c !== 'object' || !PREF_CHOICES[key].includes(c.value)) return null;
50
+ const by = clean(c.by, 80);
51
+ if (!by || by.startsWith('<') || typeof c.at !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(c.at)) return null;
52
+ return { value: c.value, by, at: c.at };
53
+ };
54
+ return { commits: one('commits'), annotate: one('annotate'), coach: one('coach') };
46
55
  }
47
56
 
48
- // @comment -- "Records the answer a named person gave: the choice, their name and the date, written 0600 through a temporary file and a rename. Refuses an unknown choice and an empty or placeholder name; other keys already in the file are kept."
57
+ // @comment -- "Records the commits answer a named person gave (writePref does the work)."
49
58
  export function writeCommits(commonDir, value, by, at) {
59
+ return writePref(commonDir, 'commits', value, by, at);
60
+ }
61
+
62
+ // @comment -- "Records one answer a named person gave: the choice, their name and the date, written 0600 through a temporary file and a rename. Refuses an unknown key or choice and an empty or placeholder name; other keys already in the file are kept."
63
+ export function writePref(commonDir, key, value, by, at) {
50
64
  if (!commonDir) throw new Error('this is not a git repository: preferences are kept under its git directory');
51
- if (!COMMIT_CHOICES.includes(value)) throw new Error(`the choice must be one of ${COMMIT_CHOICES.join(', ')}`);
65
+ if (!Object.hasOwn(PREF_CHOICES, key)) throw new Error(`no such preference: ${key} (one of ${Object.keys(PREF_CHOICES).join(', ')})`);
66
+ const choices = PREF_CHOICES[key];
67
+ if (!choices.includes(value)) throw new Error(`the choice must be one of ${choices.join(', ')}`);
52
68
  const name = clean(by, 80);
53
69
  if (!name || name.startsWith('<')) throw new Error('say whose answer this is: --by "<their name>"');
54
70
  if (!/^\d{4}-\d{2}-\d{2}$/.test(String(at))) throw new Error('the date must be YYYY-MM-DD');
@@ -62,7 +78,7 @@ export function writeCommits(commonDir, value, by, at) {
62
78
  }
63
79
  mkdirSync(join(file, '..'), { recursive: true, mode: 0o700 });
64
80
  const tmp = `${file}.tmp-${process.pid}`;
65
- writeFileSync(tmp, JSON.stringify({ ...doc, schema: PREFS_SCHEMA, commits: { value, by: name, at } }, null, 2) + '\n', { mode: 0o600 });
81
+ writeFileSync(tmp, JSON.stringify({ ...doc, schema: PREFS_SCHEMA, [key]: { value, by: name, at } }, null, 2) + '\n', { mode: 0o600 });
66
82
  try {
67
83
  chmodSync(tmp, 0o600);
68
84
  } catch {
@@ -82,7 +98,7 @@ export function commitsLine(prefs) {
82
98
  : `Commits: leave Bravos's own files uncommitted and list them; do not ask (${whose}).`;
83
99
  }
84
100
 
85
- // @comment -- "The hand-off from bravos setup to the first agent session: a dated marker in this clone's git directory saying setup just finished here and the person expects Bravos to begin. While it is fresh and the context gate is still closed, the briefing tells the agent to start the context step in its first reply; without it, or after a few days, the briefing only offers, so a session opened for something else is never taken over. Like the preferences, nothing in a repository's tree can write it."
101
+ // @comment -- "The hand-off from bravos setup to the first agent session: a dated marker in this clone's git directory saying setup just finished here and the person expects Bravos to begin. While it is fresh and there is no intent yet, the briefing tells the agent, in its first reply, to draft the context, start annotating and show the intake page; without it, or after a few days, the briefing only offers, so a session opened for something else is never taken over. Like the preferences, nothing in a repository's tree can write it."
86
102
  export const HANDOFF_DAYS = 3;
87
103
  export const handoffFile = (commonDir) => join(commonDir, 'bravos', 'handoff.json');
88
104
 
@@ -30,9 +30,9 @@ export function readSetup(root, i = {}, harness = 'other') {
30
30
  },
31
31
  {
32
32
  id: 'intent',
33
- // Done when the context gate is open: a named person confirmed the intent, or declined. A draft nobody confirmed
34
- // is not done, or setup would send people on to annotation while the gate still refuses it. Callers that do
35
- // not pass the gate (older ones) keep the earlier reading: any intent at all.
33
+ // Done when a named person confirmed the intent, or declined. A draft nobody confirmed is not done: annotation
34
+ // goes on against the draft meanwhile, and this item keeps asking a person to confirm it. Callers that do not
35
+ // pass the gate (older ones) keep the earlier reading: any intent at all.
36
36
  on: i.gate && typeof i.gate.open === 'boolean' ? i.gate.open : !!(i.intent?.status && i.intent.status !== 'none'),
37
37
  label: i.intent?.status === 'draft' ? 'confirm what the app intends' : 'record what the app intends',
38
38
  cta: skill('bravos-context', harness),
@@ -7,6 +7,8 @@ import { autopilotRegistered, buildBanner, buildBriefing, buildSummary, collect,
7
7
  import { resolveTheme } from './lib/palette.mjs';
8
8
  import { startGraphBuild } from './lib/graph-autobuild.mjs';
9
9
  import { takeSnapshot } from './lib/snapshot.mjs';
10
+ import { startCoach } from './lib/coach.mjs';
11
+ import { gitCommonDir } from './lib/prefs.mjs';
10
12
 
11
13
  const STDIN_WAIT_MS = 1000;
12
14
 
@@ -102,6 +104,10 @@ async function main() {
102
104
  if (!process.argv.includes('--global') && ownCopy(root)) {
103
105
  inputs.graphBuild = startGraphBuild({ root, env, codegraph: inputs.codegraph, licensed: inputs.licence?.licensed === true, sha: inputs.sha, installed: true });
104
106
  }
107
+ // Resume and compact carry on a session that already had its background annotation pass.
108
+ inputs.source = source;
109
+ // @comment -- "Leaves the facts the coach hook needs for this session (coverage, what waits to be tested, the target, the plan) under the git directory, so the per-prompt hook never runs guardlink. Skipped when the coach is switched off for the run; a resume or compact keeps what was already raised."
110
+ if (env.BRAVOS_COACH !== 'off' && typeof payload.session_id === 'string') startCoach(gitCommonDir(root, env), payload.session_id, inputs);
105
111
  text = buildBriefing(inputs);
106
112
  if (env.BRAVOS_BANNER !== 'off' && (source === null || source === 'startup') && harness !== 'agy') {
107
113
  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.9.2",
3
+ "version": "1.11.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",
@@ -18,7 +18,7 @@ description: "Start here in any repo bravos is installed in: reads the security
18
18
  claim (an annotation says code is exposed or mitigated) → testable template → authorized run against a target the user owns → verified outcome → recheck when the code changes.
19
19
  Three states are independent of each other: open / mitigated / accepted · untested / confirmed / refuted · verified / stale. A mitigated claim can still be untested; a confirmed one can go stale.
20
20
  3. Route the request:
21
- no `.guardlink/intent.md` yet, business logic, "what matters here", "is this intended?", learning the app → bravos-context (it comes before a first annotation pass: bravos-annotate and campaigns wait until a named person has confirmed the intent, or declined with `bravos context decline`).
21
+ no `.guardlink/intent.md` yet, business logic, "what matters here", "is this intended?", learning the app → bravos-context (with no intent it drafts one and opens the intake page without waiting; annotation goes on against the draft, and each session asks once until a named person confirms it or declines).
22
22
  coverage, annotating, "threat-model this", a worklist in the briefing → bravos-annotate.
23
23
  reachability, blast radius, "is this live", tracing a handler to sinks → bravos-codegraph.
24
24
  before a PR, push for review, or marking a draft ready → bravos-ship.
@@ -27,16 +27,17 @@ description: "Start here in any repo bravos is installed in: reads the security
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
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.
30
- "what is open?", "show me the findings", "is there a dashboard?" → answer in two or three lines from the briefing, then build the page without asking and give its path: `bravos dashboard --no-open` writes one self-contained HTML page (GuardLink's threat model, who introduced and fixed each exposure, what changed since the default branch; on the Team plan with the code graph built, also a Code graph tab: a map of where the risk sits, owners and history, coupling, the attack surface and entry points) under `.bravos/dashboard/`, git-ignored. Drop `--no-open`, so it opens in their browser, only when they asked to see it; add `--no-blame` when they will share the page. Always run the command: it rebuilds the page from the code as it stands, and on the Team plan rebuilds a code graph that is missing or behind first. Never open or point to a saved page instead, and when the briefing's `Dashboard:` line says the saved page is out of date, say so.
30
+ "what is open?", "what are the issues?", threats, vulnerabilities, risks, "show me the findings", "is there a dashboard?" → answer in two or three lines from the briefing, and at the same time build the page without asking, in the background (a background shell or a subagent), saying in one line that it is opening: `bravos dashboard` writes one self-contained HTML page (GuardLink's threat model, who introduced and fixed each exposure, what changed since the default branch; on the Team plan with the code graph built, also a Code graph tab: a map of where the risk sits, owners and history, coupling, the attack surface and entry points) under `.bravos/dashboard/`, git-ignored. The first time this session it opens in their browser; after that run it with `--no-open` and give the path, so tabs do not pile up. Add `--no-blame` when they will share the page. End with one recommended next step: confirm the top untested exposures (bravos-prove, or bravos-env first when no target is recorded), or annotate the next files when coverage is low. Always run the command: it rebuilds the page from the code as it stands, and on the Team plan rebuilds a code graph that is missing or behind first. Never open or point to a saved page instead, and when the briefing's `Dashboard:` line says the saved page is out of date, say so.
31
31
  write up the assessment, a finding, a retest or a brief for leadership → bravos-report.
32
32
  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).
33
33
  keep annotating while I work, nightly or periodic runs → bravos-schedule.
34
34
  security CI, a PR check, code-scanning upload → bravos-cicd.
35
35
  reach a goal over many rounds ("100% coverage", "test every exposure", "until done", autopilot, a campaign) → bravos-campaign.
36
36
  The briefing's `Plan:` line says which tier this machine is on. On Free, the research loop (context, annotate, templatize, env, prove, recheck, report, watch) is all there; the pre-PR gate, CI and nightly, schedule, workspaces, campaign, SAST and the code graph are on Team. When the request needs one of those, still name the right skill, say in one sentence that it is on the Team plan (`bravos account activate` starts a 30-day trial, no card), and offer the nearest free step instead; never pretend the feature ran.
37
- 4. bravos adds method and memory to what you can already do; it never caps it. Budgets in the skills are defaults: exceed them when the work calls for it and say why. Effort (low, medium, high, max) comes from the user's words, else a `bravos effort: <level>` line in `AGENTS.md` / `CLAUDE.md`, else medium. Only the safety rules under each skill's Never are hard. Two of them hold in every skill: before the first commit of a session ask the person once (commit now, or leave the files for them to review), even where a skill says to commit, unless they already asked for commits (a campaign, a schedule) or the briefing has a `Commits:` line, which is their standing answer for Bravos's own files: follow it without asking, and never fold their own code into such a commit. When you do ask, also ask whether that is their answer from now on and, if it is, record it with `bravos prefs set commits commit|leave --by "<their name>"`; and write annotations where the briefing's `Annotations:` line says, a `.gal` sidecar in external mode and a comment above the code in inline mode.
38
- 5. Name the next step in one line, taken from the briefing: a `FIX NOW` item first, then a stale claim in a file the user changed, then the top `guardlink hypothesis next` item, then coverage.
39
- 6. When the user takes an item to work on and it already has a ticket in their tracker, record the pick-up beside its claim so the hive can see it: write `@ticket #<threat> on #<asset> <ticket-ref> sla "<label>" by <assignee> until <YYYY-MM-DD>` directly beside the claim's `@exposes`, clauses in that order, dropping `sla "<label>"` and `until <YYYY-MM-DD>` unless the user gives them, then run `guardlink validate .`. The briefing's `Open tickets` line and `guardlink lookup tickets` show it to teammates; removing the line is how the ticket leaves the model.
37
+ 4. When the briefing has a `Background annotation:` line, start that pass in your first reply as bravos-annotate's `When` section says, beside whatever the person asked; say so in one line, and pass on its one-line report when it ends.
38
+ 5. bravos adds method and memory to what you can already do; it never caps it. Budgets in the skills are defaults: exceed them when the work calls for it and say why. Effort (low, medium, high, max) comes from the user's words, else a `bravos effort: <level>` line in `AGENTS.md` / `CLAUDE.md`, else medium. Only the safety rules under each skill's Never are hard. Two of them hold in every skill: before the first commit of a session ask the person once (commit now, or leave the files for them to review), even where a skill says to commit, unless they already asked for commits (a campaign, a schedule) or the briefing has a `Commits:` line, which is their standing answer for Bravos's own files: follow it without asking, and never fold their own code into such a commit. When you do ask, also ask whether that is their answer from now on and, if it is, record it with `bravos prefs set commits commit|leave --by "<their name>"`; and write annotations where the briefing's `Annotations:` line says, a `.gal` sidecar in external mode and a comment above the code in inline mode.
39
+ 6. Name the next step in one line, taken from the briefing: a `FIX NOW` item first, then a stale claim in a file the user changed, then the top `guardlink hypothesis next` item, then coverage.
40
+ 7. When the user takes an item to work on and it already has a ticket in their tracker, record the pick-up beside its claim so the hive can see it: write `@ticket #<threat> on #<asset> <ticket-ref> sla "<label>" by <assignee> until <YYYY-MM-DD>` directly beside the claim's `@exposes`, clauses in that order, dropping `sla "<label>"` and `until <YYYY-MM-DD>` unless the user gives them, then run `guardlink validate .`. The briefing's `Open tickets` line and `guardlink lookup tickets` show it to teammates; removing the line is how the ticket leaves the model.
40
41
 
41
42
  ## Never
42
43
 
@@ -10,13 +10,14 @@ description: "Keep the GuardLink threat model correct and growing, in this sessi
10
10
  - You just wrote or changed security-relevant code and its claims are missing or stale.
11
11
  - The briefing's `Open exposures:` line shows low coverage or a non-empty worklist.
12
12
  - bravos-ship or bravos-codegraph handed you gaps to annotate.
13
+ - The briefing has a `Background annotation:` line: one background pass this session. In Claude Code, start it with the Agent tool in the background (`run_in_background`), told to follow this skill for one slice at the default budget and report in one line; in a harness without subagents, offer it once instead. Tell the person in one line that it is running and go on with their request. The pass takes one slice (step 4 skips the person's current change) and writes annotations only, never code; it commits only as the briefing's `Commits:` line allows, and with no such line commits nothing and leaves its files for the person; when it ends, pass on its `+<files>, <p0>% → <p1>%` line. One per session: not again after a resume or compact, and none when the briefing has no such line (the person switched it off with `bravos prefs set annotate off`, or `BRAVOS_AUTO_ANNOTATE=off` is set).
13
14
 
14
15
  ## Do
15
16
 
16
- 1. Set up. You annotate in this session: guardlink supplies the method (its playbook skills), you supply the edits. `<base>` below is the base branch name, e.g. `main`; the briefing prints it as `base origin/<base>`, and without a briefing `git symbolic-ref -q --short refs/remotes/origin/HEAD` prints `origin/<base>` (if it prints nothing, use `main`). Run `git fetch origin <base>` before you use `origin/<base>`, so it is current; if the fetch fails (offline, no `origin`), say so and continue with the local ref. Record `git rev-parse HEAD` now as `<start>`: the lint gate judges only what this session writes. Definitions (`@asset`, `@threat`, `@control` with `#id`) live in `.guardlink/definitions.*`; reuse those ids and never redefine one. Read `.guardlink/intent.md`: its invariants (`INV-n`), intended-by-design items (`INT-n`), actors and crown jewels shape every claim below. Context comes first: threat-modelling starts only when a named person has confirmed the intent, or declined. If intent.md is missing, or the briefing's `Intent:` line says nobody has confirmed it, run bravos-context before anything else here. If the person would rather go without, tell them what that costs (severities are not calibrated to the product, and a rule only a design states will not be found) and that they record it themselves with `bravos context decline --by "<their name>"`; then carry on.
17
+ 1. Set up. You annotate in this session: guardlink supplies the method (its playbook skills), you supply the edits. `<base>` below is the base branch name, e.g. `main`; the briefing prints it as `base origin/<base>`, and without a briefing `git symbolic-ref -q --short refs/remotes/origin/HEAD` prints `origin/<base>` (if it prints nothing, use `main`). Run `git fetch origin <base>` before you use `origin/<base>`, so it is current; if the fetch fails (offline, no `origin`), say so and continue with the local ref. Record `git rev-parse HEAD` now as `<start>`: the lint gate judges only what this session writes. Definitions (`@asset`, `@threat`, `@control` with `#id`) live in `.guardlink/definitions.*`; reuse those ids and never redefine one. Read `.guardlink/intent.md`: its invariants (`INV-n`), intended-by-design items (`INT-n`), actors and crown jewels shape every claim below. Annotation never waits for the intake. If intent.md is missing, run bravos-context's draft first (its steps 2–4: it writes a draft intent.md and opens the intake page without waiting), then annotate against that draft. If the briefing's `Intent:` line says nobody has confirmed it, annotate against the draft and ask the person once this session to confirm it on the intake page (`bravos review intent`); never confirm anything for them. If the person would rather go without, tell them what that costs (severities are not calibrated to the product, and a rule only a design states will not be found) and that they record it themselves with `bravos context decline --by "<their name>"`.
17
18
  2. Run `guardlink ci -f json`. Note `summary.coverage.percent` as p0 and the worklist size from the briefing or `guardlink unannotated --json` (`summary.worklist`).
18
19
  3. Read the effort: the user's words ("at high"), else a `bravos effort: <level>` line in `AGENTS.md` / `CLAUDE.md`, else medium. Starting budgets — low: the changed files only; medium: changed plus 5 from the worklist; high: 25 per round, then the `chains` playbook; max: rounds until the worklist is empty (bravos-campaign runs those with subagents). These are defaults, not limits: take more or fewer when the code calls for it, and say why in one line ("12 files, not 5: the auth path spans them"). For a large pick, tell the user the files and rounds before you start.
19
- 4. Run `node {{SKILL_DIR}}/scripts/slice.mjs --base origin/<base> --n <budget>` (`--deep` for no limit, `--batches <k>` to split the pick for parallel work, `--prefer <file>` for entry points `codegraph_entry_points` found). It prints one JSON object: `diff` (files changed from the merge base to disk, including staged, unstaged and untracked source), `coverage` (unannotated files to cover, entry points and trust code first, generated, test and CI files last), `coverage_detail` (`{path, tier, why}`), `batches`, `skipped` (`{path, reason}`), `coverage_before`, `notes`. The order is advice: if your reading of the code says a different file matters more, take it and say why. Tell the user which `skipped` files teammates have in flight. Report every `notes` entry to the user; if one says gh was unavailable, say in-flight PRs were not checked before you take the `coverage` files. Exit 1 means `guardlink unannotated --json` failed: report it and stop. Exit 3 means the context gate is closed (its JSON carries `gate` and nothing to pick): report its note, run bravos-context, and annotate nothing until it is done or the person has declined. When the briefing's `SAST:` line shows a run, `bravos sast candidates` lists reachable findings not in the threat model yet: add their files to the pick as leads, open each, and annotate only what meets the evidence bar, as `@exposes` + `@audit` citing the rule and route, or an `@audit` naming a false positive. A static finding is never `@confirmed`. With SAST unavailable or no report, pick as usual.
20
+ 4. Run `node {{SKILL_DIR}}/scripts/slice.mjs --base origin/<base> --n <budget>` (`--deep` for no limit, `--batches <k>` to split the pick for parallel work, `--prefer <file>` for entry points `codegraph_entry_points` found). It prints one JSON object: `diff` (files changed from the merge base to disk, including staged, unstaged and untracked source), `coverage` (unannotated files to cover, entry points and trust code first, generated, test and CI files last), `coverage_detail` (`{path, tier, why}`), `batches`, `skipped` (`{path, reason}`), `coverage_before`, `notes`. The order is advice: if your reading of the code says a different file matters more, take it and say why. Tell the user which `skipped` files teammates have in flight. Report every `notes` entry to the user; if one says gh was unavailable, say in-flight PRs were not checked before you take the `coverage` files. Exit 1 means `guardlink unannotated --json` failed: report it and stop. Its `context` field says the intake's state (`none`, `draft`, `confirmed`, `declined`); while it is not confirmed, say once that severities are judged against the draft, and annotate the pick as usual. When the briefing's `SAST:` line shows a run, `bravos sast candidates` lists reachable findings not in the threat model yet: add their files to the pick as leads, open each, and annotate only what meets the evidence bar, as `@exposes` + `@audit` citing the rule and route, or an `@audit` naming a false positive. A static finding is never `@confirmed`. With SAST unavailable or no report, pick as usual.
20
21
  5. When a Stop hook names files or lines, review those changes first, including already annotated files. Read the actual patch and both sides of a move or deletion. Open each affected handler, guard and caller. With a current graph, ask `codegraph_annotation_gaps` with explicit new-side file ranges for working edits or the merge base for committed changes. Inspect stale and unindexed files and read unsupported routes from source. An existing annotation in the file does not establish that it describes the new behavior. Record the changed threat, guard, or flow, recheck an affected existing claim, or finish the review quietly when the change has no security consequence. Keep ordinary turn-end review to the changed code. Pick the playbook: `diff` files → `diff`; `coverage` files → `coverage`. Deep rounds run `exploitable`, then `chains`, then `coverage`, then `verify`. Add a logic pass when intent.md lists invariants (always at high and max, or when guardlink offers a `logic` playbook use it): walk each user journey that touches an invariant — signup, invite, role change, checkout, refund, export — and at each step ask what it assumes about the caller and the step before: ownership, tenant, state, amount, rate. The sink of a logic claim is the state change (the write, the transfer, the grant); the absent control is the missing ownership or state check. Claim it against the invariant's threat, and make a rule that holds testable. At each place a rule is enforced write the pair: `@exposes <Asset> to #inv-…` and `@mitigates <Asset> against #inv-… using #<control>`. A replay kit binds to an `@exposes`, so a check recorded only as `@mitigates` can never be tested or shown to hold; the pair says where the rule could break and what stops it there (for an `#inv-` rule this is the one `@exposes` written beside a check that is present). Where the permission itself is granted in another file (a role table, a policy file), write a `@mitigates` there too, so a change to it is noticed. A check that is missing and meets the evidence bar is an `@exposes` with an `@audit` and no `@mitigates`; a doubt is an `@audit`. Keep `intent:` and `design:` references on the `@threat` definition only.
21
22
  6. Open `{{SKILLS_ROOT}}/guardlink-annotate-<id>/SKILL.md` (guardlink writes it under `.claude/skills/`, and `bravos setup` mirrors it into `.agents/skills/` for Codex) and follow it. Otherwise call the MCP tool `guardlink_annotate` (server `guardlink`) with `prompt: "<scope>"` and `playbook: "<id>"`, or run `guardlink annotate --stdout --playbook <id> "<scope>"` (for the `diff` playbook, `guardlink annotate --stdout --playbook diff --since origin/<base> "<scope>"`, since `--since` defaults to HEAD and would list no changed files), and follow the prompt it returns.
22
23
  7. Read the repository's annotation mode in `.guardlink/README.md` and its configuration. In inline mode write annotations in the file's comment syntax directly above the code. In external mode update its `.guardlink/annotations/<source-path>.gal` sidecar and anchor the block to the logical source line and symbol using the local GuardLink playbook. Couple the claims: every `@exposes` with its `@mitigates` or `@audit`, the `@flows` the data takes, and a `@comment` on what the code does. Each claim meets the evidence bar: it names the code, the threat and the control by id, and you could point at the line that makes it true.
@@ -25,7 +26,7 @@ description: "Keep the GuardLink threat model correct and growing, in this sessi
25
26
  If a patch changes a caller, destination, trust boundary or security control, trace who can reach it, the data crossing it, the guard and where it is enforced. Reconcile the specific `@flows`, `@boundary` and control claims with the new behavior. For tools the application gives an agent, review `@agents` or `@reaches` at registration, `@effects` where the action occurs and `@gates` where approval is enforced. For coding-agent configuration, run `guardlink lookup "unentitled coding-agent reach"` and inspect the changed configuration lines. GuardLink derives the agent's reach from those files. Propose a missing entitlement for the human's decision; report an unapproved capability and the evidence separately from an exploitable finding.
26
27
  8. Gate: run `guardlink lint . --since <start> --json`. For each entry in `violations[]`, apply its `fix`. Repeat until `summary.errors` is 0. A violation on a line you did not write this session is not yours: leave the line as it is and report it to the user.
27
28
  9. Run `guardlink validate .` and fix what it reports in the lines you wrote.
28
- 10. Run `guardlink ci -f json` again and report `+<files>, <p0>% → <p1>%, <errors> lint errors`. Deep only: repeat steps 4–10 once per round, and stop when `coverage` comes back empty or a round adds no claims.
29
+ 10. Run `guardlink ci -f json` again and report `+<files>, <p0>% → <p1>% (<annotated> of <source> files annotated), <errors> lint errors`. Deep only: repeat steps 4–10 once per round, and stop when `coverage` comes back empty or a round adds no claims.
29
30
  11. On a normal coding turn keep annotations with the code change and preserve the user's staged and uncommitted edits. For a requested standalone coverage slice, with the person's go-ahead (the briefing's `Commits:` line is their standing answer; with no such line, ask once per session unless they already asked for commits), commit the slice on its own: `git add` only the annotated files, message `annotate: <n> files, <playbook>`. Ship it as a small PR or on the feature branch, whichever the team does.
30
31
  12. Read `guardlink hypothesis list --json`. Keep each changed exposure's stable key, source location, sidecar location when applicable, and tested state. Include untested claims with a declared mitigation. Hand new claims to bravos-templatize for a concrete kit; expired or previously tested claims go to bravos-recheck. Apply the recorded proving choice before execution: auto follows bravos-env and bravos-prove in its authorized scope; ask seeks a decision; schedule leaves the claim queued; none records that it was not tested. Evidence from a real run is required before marking a claim confirmed or refuted. Hand the change to bravos-ship before a PR.
31
32
 
@@ -36,7 +37,7 @@ description: "Keep the GuardLink threat model correct and growing, in this sessi
36
37
  - Apply a lint `fix` to a line this session did not write. For `accepts-written`, `entitles-written` or `confirmed-without-evidence` on someone else's line, never remove or downgrade it: stop and report it to the user.
37
38
  - Edit or delete an existing claim. If one looks wrong, write an `@audit` beside it saying why.
38
39
  - Treat an intended-by-design match as an accepted risk, or drop an existing claim because intent.md covers it.
39
- - Annotate while the context gate is closed, work around it (picking files by hand, another tool's annotate command), or run `bravos context decline` for the person: going without context is theirs to decide and to record.
40
+ - Mark a draft intent item confirmed, or run `bravos context decline` for the person: confirming the intent, or going without it, is theirs to decide and to record.
40
41
  - Open the design documents under `.bravos/context/sources/`. The rules they hold are in intent.md; only bravos-context reads the documents, with a person present.
41
42
  - Annotate a file `guardlink unannotated` lists under `excluded`.
42
43
  - Pad coverage with claims that fail the evidence bar. An honest `@exposes` plus `@audit` beats a guessed `@mitigates`.
@@ -47,7 +48,8 @@ description: "Keep the GuardLink threat model correct and growing, in this sessi
47
48
  - You reported the delta line from step 10, the files left in `skipped`, and any lint violation on a line you did not write.
48
49
  - Each new `@exposes` carries a severity with its reason, and every "intended?" `@audit` is listed for the user.
49
50
  - Each new claim's state is clear: open or mitigated (none accepted by you), untested (an annotation alone confirms or refutes nothing), and verified or stale per `guardlink ci`. Say what was not tested. Do not call the code clean; the lint gate judges annotations, not code.
50
- - If a dashboard was built earlier (the briefing's `Dashboard:` line, or one you opened this session), you rebuilt it with `bravos dashboard --no-open` and gave the path.
51
+ - You rebuilt the dashboard from the code (`bravos dashboard`, run in the background): opened in their browser if it has not been opened this session, else with `--no-open` and its path given. A background pass only reports its line; the main agent does this and the next step.
52
+ - You ended with one recommended next step, said as a recommendation and not as a list of what testing needs: with untested exposures, "let's confirm the top three now", naming them, through bravos-prove on the recorded target, or, with none recorded, "let's set up a target first" through bravos-env (the person types their own authorization); then the next round, or a campaign on the Team plan.
51
53
 
52
54
  ## What it leaves for the next skill
53
55