@bugb-technologies/bravos 1.5.3 → 1.6.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/dist/rules.js ADDED
@@ -0,0 +1,218 @@
1
+ // @comment -- "Design rules: the business-logic rules a team's design states (INV-n in .guardlink/intent.md, each a GuardLink threat #inv-…), joined to where the code enforces them and to what testing has shown. One row per rule with a status: broken, retest due, holds, unguarded, guarded but untested, or not placed. Read-only: it reads intent.md, the sources index, `guardlink parse .` and `guardlink hypothesis list --json .`, and runs no model. bravos rules prints it; bravos dashboard draws it as the Design rules view."
2
+ import { execFileSync } from 'node:child_process';
3
+ import { existsSync, readFileSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { contextLib } from './context.js';
6
+ import { parseJson, runner } from './watch.js';
7
+ export const STATUS_ORDER = ['broken', 'retest-due', 'unguarded', 'guarded-untested', 'not-placed', 'holds'];
8
+ export const STATUS_LABEL = {
9
+ broken: 'broken',
10
+ 'retest-due': 'retest due',
11
+ holds: 'holds',
12
+ unguarded: 'unguarded',
13
+ 'guarded-untested': 'guarded, untested',
14
+ 'not-placed': 'not placed',
15
+ };
16
+ const arr = (v) => (Array.isArray(v) ? v : []);
17
+ const bare = (id) => String(id ?? '').replace(/^#/, '');
18
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
19
+ // @comment -- "Reads the rules out of intent.md: every bullet that starts INV-n. What follows the last ' — ' is how it was decided (draft, or who agreed), a '(source: SRC-2 \"Report access\")' names the documents it came from, and the rest is the rule's text. Table rows and prose that mention a rule are not rules."
20
+ export function parseIntentRules(text) {
21
+ const out = [];
22
+ const seen = new Set();
23
+ for (const line of text.split('\n')) {
24
+ const m = /^\s*[-*]\s+(INV-\d+)\s*:\s*(.+)$/.exec(line);
25
+ if (!m || seen.has(m[1]))
26
+ continue;
27
+ seen.add(m[1]);
28
+ let rest = m[2].trim();
29
+ let attribution = '';
30
+ const dash = rest.lastIndexOf(' — ');
31
+ if (dash >= 0) {
32
+ attribution = rest.slice(dash + 3).trim();
33
+ rest = rest.slice(0, dash).trim();
34
+ }
35
+ const sources = [];
36
+ rest = rest
37
+ .replace(/\(source:\s*([^)]*)\)/gi, (_all, inner) => {
38
+ for (const s of inner.matchAll(/\b(SRC-[1-9][0-9]{0,4})\b(?:\s*"([^"]{0,120})")?/g))
39
+ sources.push({ id: s[1], section: s[2]?.trim() || null });
40
+ return '';
41
+ })
42
+ .replace(/\s+/g, ' ')
43
+ .trim();
44
+ const draft = /^draft\b/i.test(attribution) || attribution === '';
45
+ const by = /\b(?:accepted|edited|chosen|set|confirmed) by\s+(.+)$/i.exec(attribution)?.[1]?.trim() ?? null;
46
+ out.push({ id: m[1], text: rest.slice(0, 600), decided: draft ? 'draft' : 'confirmed', decidedBy: draft ? null : by, sources });
47
+ }
48
+ return out;
49
+ }
50
+ const SITE_WORD = { broken: 'a test got through', retest: 'the code changed since it was tested', held: 'a test was refused', untested: 'not tested' };
51
+ // @comment -- "A site's tested state from its ledger record: a confirmed outcome is broken; a record waiting for a retest, or one whose code changed since the test, is retest; a refuted outcome that still stands is held (the test tried and was refused); anything else is untested."
52
+ function siteState(rec) {
53
+ if (!rec)
54
+ return 'untested';
55
+ const state = String(rec.state ?? '');
56
+ if (state === 'confirmed')
57
+ return 'broken';
58
+ if (state === 'retest' || rec.expired === true)
59
+ return 'retest';
60
+ if (state === 'refuted')
61
+ return 'held';
62
+ return 'untested';
63
+ }
64
+ // @comment -- "A rule's status from its sites. Broken wins, then retest due. It holds only when every place it can break has been tested and refused. A place with no control at all makes it unguarded; checks that exist but have not all been tested make it guarded, untested; a rule tied to no code is not placed. The sentence beside the status says which of these it is and what would change it."
65
+ export function ruleStatus(sites) {
66
+ const testable = sites.filter((s) => s.kind !== 'grant');
67
+ const at = (s) => `${s.file}${s.line ? `:${s.line}` : ''}`;
68
+ const broken = testable.filter((s) => s.state === 'broken');
69
+ if (broken.length)
70
+ return { status: 'broken', why: `A test got through at ${broken.map(at).join(', ')}: the rule does not hold there.` };
71
+ const retest = testable.filter((s) => s.state === 'retest');
72
+ if (retest.length)
73
+ return { status: 'retest-due', why: `The code at ${retest.map(at).join(', ')} changed since it was last tested: replay its test.` };
74
+ const gaps = testable.filter((s) => s.kind === 'gap');
75
+ if (gaps.length)
76
+ return { status: 'unguarded', why: `Nothing enforces it at ${gaps.map(at).join(', ')}: an exposure is recorded there with no control.` };
77
+ if (testable.length && testable.every((s) => s.state === 'held'))
78
+ return { status: 'holds', why: `Tested at ${testable.length === 1 ? 'the one place' : `all ${testable.length} places`} it is enforced, and refused each time.` };
79
+ if (testable.length) {
80
+ const held = testable.filter((s) => s.state === 'held').length;
81
+ return { status: 'guarded-untested', why: held ? `Tested at ${held} of ${testable.length} places it is enforced; the others have a check that no test has tried.` : 'A check is annotated where it is enforced, but no test has tried it yet.' };
82
+ }
83
+ if (sites.length)
84
+ return { status: 'guarded-untested', why: 'It is recorded only as a control, which cannot be tested: the next annotation pass writes where it could break beside the check.' };
85
+ return { status: 'not-placed', why: 'No code is tied to this rule yet: the next annotation pass looks for where it is enforced.' };
86
+ }
87
+ // @comment -- "The files among a rule's places that changed after the rule was last tested: a later commit touches them, or they have uncommitted edits. GuardLink's test record lapses only when the code under the tested claim changes; a permission flipped in a role table, in another file, lapses nothing there, so the time of the change is what tells. Read-only git (argv, no shell); outside a repository nothing is reported."
88
+ export function changedSinceTest(root, env, files, testedMs) {
89
+ const git = (args) => {
90
+ try {
91
+ return execFileSync('git', args, { cwd: root, env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 10000 }).trim();
92
+ }
93
+ catch {
94
+ return null;
95
+ }
96
+ };
97
+ const out = [];
98
+ for (const file of [...new Set(files)].sort()) {
99
+ const committed = Number(git(['log', '-1', '--format=%ct', '--', file]));
100
+ const dirty = git(['status', '--porcelain', '--', file]);
101
+ if ((Number.isFinite(committed) && committed > 0 && committed * 1000 > testedMs) || (dirty !== null && dirty !== ''))
102
+ out.push(file);
103
+ }
104
+ return out;
105
+ }
106
+ // @comment -- "Builds the rules document. Each INV item in intent.md is matched to its threat by the threat's intent:INV-n reference, or for older repositories by a description that starts 'INV-n:'. A site is every @exposes of that threat (a check when a @mitigates covers the same asset and threat, a gap when none does) and every @mitigates in a file that has no @exposes of it (a grant). Each exposure's tested state comes from its one ledger record, matched by asset, threat and location. A threat named #inv-… that no intent item claims is listed too, so nothing an agent added stays out of sight."
107
+ export async function gatherRules(root, env, opts = {}) {
108
+ const names = opts.names !== false;
109
+ const intentFile = join(root, '.guardlink', 'intent.md');
110
+ const intentRules = existsSync(intentFile) ? parseIntentRules(readFileSync(intentFile, 'utf8')) : [];
111
+ const titles = new Map();
112
+ try {
113
+ const L = await contextLib();
114
+ const index = join(root, L.INDEX_PATH);
115
+ if (existsSync(index))
116
+ for (const s of L.parseIndex(readFileSync(index, 'utf8')).sources)
117
+ titles.set(s.id, { title: s.title, kind: s.kind });
118
+ }
119
+ catch {
120
+ /* sources are named by id alone */
121
+ }
122
+ const source = (s) => ({ id: s.id, section: s.section, title: titles.get(s.id)?.title ?? null, kind: titles.get(s.id)?.kind ?? null });
123
+ const run = await runner();
124
+ const [parsed, listed] = await Promise.all([
125
+ run('guardlink', ['parse', '.'], { cwd: root, env, timeoutMs: 120000 }),
126
+ run('guardlink', ['hypothesis', 'list', '--json', '.'], { cwd: root, env, timeoutMs: 60000 }),
127
+ ]);
128
+ const model = parsed.missing ? null : parseJson(parsed);
129
+ const records = arr(parseJson(listed)?.records);
130
+ const threats = arr(model?.threats).map((t) => ({ id: bare(t.id), severity: t.severity ?? null, refs: arr(t.external_refs).map(String), description: String(t.description ?? ''), name: String(t.name ?? t.canonical_name ?? '') }));
131
+ const threatFor = (inv) => threats.find((t) => t.refs.some((r) => r.toLowerCase() === `intent:${inv.toLowerCase()}`)) ?? threats.find((t) => new RegExp(`^${inv}\\b\\s*:`, 'i').test(t.description.trim())) ?? null;
132
+ const exposures = arr(model?.exposures);
133
+ const mitigations = arr(model?.mitigations);
134
+ const sitesFor = (threat) => {
135
+ const mine = (x) => bare(x.threat) === threat;
136
+ const sites = [];
137
+ const exposed = new Set();
138
+ for (const e of exposures.filter(mine)) {
139
+ const file = String(e.location?.file ?? '?');
140
+ const line = num(e.location?.line);
141
+ const asset = bare(e.asset);
142
+ exposed.add(file);
143
+ const control = mitigations.find((m) => mine(m) && bare(m.asset) === asset);
144
+ const origin = e.location?.origin_file ? { file: String(e.location.origin_file), line: num(e.location.origin_line) } : { file, line };
145
+ // The exposure's one ledger record: at its exact location (a sidecar's own line, or the code line), else the
146
+ // only record for this asset and threat in the file. Two candidates are no match: a wrong one would be a wrong verdict.
147
+ const same = records.filter((r) => bare(r.threat) === threat && bare(r.asset) === asset);
148
+ const exact = same.filter((r) => (r.file === origin.file && r.line === origin.line) || (r.file === file && r.line === line));
149
+ const inFile = same.filter((r) => r.file === origin.file || r.file === file);
150
+ const rec = exact.length === 1 ? exact[0] : exact.length === 0 && inFile.length === 1 ? inFile[0] : undefined;
151
+ const state = siteState(rec);
152
+ sites.push({ kind: control ? 'check' : 'gap', file, line, asset, control: control ? bare(control.control) : null, state, testedAt: rec?.outcome?.at ?? null, evidence: rec?.outcome?.evidence ? String(rec.outcome.evidence).slice(0, 300) : null });
153
+ }
154
+ for (const m of mitigations.filter(mine)) {
155
+ const file = String(m.location?.file ?? '?');
156
+ if (exposed.has(file))
157
+ continue;
158
+ sites.push({ kind: 'grant', file, line: num(m.location?.line), asset: bare(m.asset), control: bare(m.control), state: null, testedAt: null, evidence: null });
159
+ }
160
+ return sites;
161
+ };
162
+ // A rule that reads as holding is checked once more against git: a file it is enforced or granted in that changed
163
+ // after its oldest refused test makes the result stale, whatever the ledger still says.
164
+ const afterChanges = (verdict, sites) => {
165
+ if (verdict.status !== 'holds')
166
+ return verdict;
167
+ const tested = sites.map((s) => Date.parse(s.testedAt ?? '')).filter(Number.isFinite);
168
+ if (!tested.length)
169
+ return verdict;
170
+ const oldest = Math.min(...tested);
171
+ const moved = changedSinceTest(root, env, sites.map((s) => s.file), oldest);
172
+ if (!moved.length)
173
+ return verdict;
174
+ return { status: 'retest-due', why: `${moved.join(', ')} changed after the rule was last tested (${new Date(oldest).toISOString().slice(0, 10)}): the refused test no longer describes this code. Replay it.` };
175
+ };
176
+ const rules = [];
177
+ const claimed = new Set();
178
+ for (const r of intentRules) {
179
+ const t = threatFor(r.id);
180
+ if (t)
181
+ claimed.add(t.id);
182
+ const sites = t ? sitesFor(t.id) : [];
183
+ const verdict = !model
184
+ ? { status: 'not-placed', why: 'GuardLink is not installed here, so where this rule is enforced is not known.' }
185
+ : !t
186
+ ? { status: 'not-placed', why: 'No threat in the model stands for this rule yet: the context step adds one (#inv-…) with the reference intent:' + r.id + '.' }
187
+ : afterChanges(ruleStatus(sites), sites);
188
+ rules.push({ id: r.id, text: r.text, decided: r.decided, decidedBy: names ? r.decidedBy : null, sources: r.sources.map(source), threat: t ? `#${t.id}` : null, severity: t?.severity ?? null, refs: t?.refs ?? [], ...verdict, sites });
189
+ }
190
+ // A rule threat with no intent item behind it: written by an annotation pass, or left from an edited intent.
191
+ for (const t of threats.filter((x) => /^inv-/i.test(x.id) && !claimed.has(x.id))) {
192
+ const sites = sitesFor(t.id);
193
+ const verdict = afterChanges(ruleStatus(sites), sites);
194
+ rules.push({ id: null, text: t.description || t.name || `#${t.id}`, decided: null, decidedBy: null, sources: t.refs.filter((r) => /^design:SRC-/i.test(r)).map((r) => source({ id: r.slice(7), section: null })), threat: `#${t.id}`, severity: t.severity, refs: t.refs, status: verdict.status, why: `${verdict.why} No item in intent.md stands behind this threat: confirm it there, or remove it.`, sites });
195
+ }
196
+ rules.sort((a, b) => STATUS_ORDER.indexOf(a.status) - STATUS_ORDER.indexOf(b.status) || String(a.id ?? '~').localeCompare(String(b.id ?? '~'), undefined, { numeric: true }));
197
+ const summary = { total: rules.length, draft: rules.filter((r) => r.decided === 'draft').length, broken: 0, 'retest-due': 0, holds: 0, unguarded: 0, 'guarded-untested': 0, 'not-placed': 0 };
198
+ for (const r of rules)
199
+ summary[r.status] += 1;
200
+ if (!rules.length) {
201
+ return { schema: 'bravos.rules/v1', state: 'none', note: 'No design rules are recorded yet. Run /bravos-context: it asks for your design documents and writes the rules they state (who may do what, what must never happen) into .guardlink/intent.md.', summary, rules };
202
+ }
203
+ if (!model)
204
+ return { schema: 'bravos.rules/v1', state: 'no-guardlink', note: 'GuardLink is not installed on this machine, so the rules are listed without where the code enforces them: run bravos setup --tools -y, then bravos dashboard again.', summary, rules };
205
+ const said = STATUS_ORDER.filter((s) => summary[s]).map((s) => `${summary[s]} ${STATUS_LABEL[s]}`);
206
+ return { schema: 'bravos.rules/v1', state: 'present', note: `${rules.length} design rule${rules.length === 1 ? '' : 's'} from the intent: ${said.join(', ')}${summary.draft ? `; ${summary.draft} still a draft nobody has confirmed` : ''}.`, summary, rules };
207
+ }
208
+ // @comment -- "bravos rules as lines: the note, then one line per rule with its status, id, text, sources and the places it is enforced."
209
+ export function formatRules(doc) {
210
+ const lines = [doc.note];
211
+ for (const r of doc.rules) {
212
+ const src = r.sources.length ? ` (${r.sources.map((s) => s.id).join(', ')})` : '';
213
+ lines.push(`${STATUS_LABEL[r.status].padEnd(18)} ${(r.id ?? r.threat ?? '?').padEnd(7)} ${r.text}${r.decided === 'draft' ? ' [draft]' : ''}${src}`);
214
+ for (const s of r.sites)
215
+ lines.push(`${' '.repeat(19)}${s.kind === 'grant' ? 'granted in' : s.kind === 'gap' ? 'no control at' : 'enforced at'} ${s.file}${s.line ? `:${s.line}` : ''}${s.state ? ` — ${SITE_WORD[s.state]}` : ''}`);
216
+ }
217
+ return lines;
218
+ }
package/dist/uninstall.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { existsSync, lstatSync, readFileSync, readdirSync, readlinkSync, rmdirSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
2
2
  import { dirname, join } from 'node:path';
3
3
  import { LOCK_PATH, readLock, sha256 } from './lock.js';
4
+ import { removePrePush } from './context.js';
4
5
  import { BravosError } from './types.js';
5
6
  const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
6
7
  // Any command bravos registers: the per-repo relative forms and the user-level absolute one.
@@ -176,6 +177,11 @@ export function uninstall(root, opts = {}) {
176
177
  const leftover = ['reports', 'sast', 'watch', 'workspace', 'review'].filter((d) => existsSync(join(root, '.bravos', d)));
177
178
  if (leftover.length)
178
179
  report.notes.push(`.bravos/{${leftover.join(',')}} kept: reports, runs and snapshots are yours, not the install's`);
180
+ // The design documents are the team's, committed and cited by the threat model: an uninstall never touches them.
181
+ if (existsSync(join(root, '.bravos', 'context')))
182
+ report.notes.push('.bravos/context kept: the design documents and their index are yours, and the intent cites them');
183
+ if (!opts.home && removePrePush(root, process.env, dryRun))
184
+ report.notes.push('the pre-push check for design documents was removed from this clone\'s git hooks');
179
185
  try {
180
186
  if (!opts.home && lstatSync(join(root, '.agents', 'skills')).isSymbolicLink()) {
181
187
  report.notes.push('.agents/skills is still a link to .claude/skills (from --link-skills); remove it if no other agent needs it');
package/docs/GUIDE.md CHANGED
@@ -100,6 +100,24 @@ Skills: `/bravos-context`
100
100
 
101
101
  Writes .guardlink/intent.md: invariants (INV-n) that become threats, and intended-by-design items (INT-n) that get an "intended?" audit instead of a high rating.
102
102
 
103
+ ### Start from your design documents
104
+
105
+ Skills: `/bravos-context`
106
+
107
+ Give bravos-context your PRDs, design documents or an earlier threat model, as files or links. Each is kept in the repository as Markdown under .bravos/context/ (bravos context add; committed, so the team can keep it current) after a check for secrets and local paths; a link is kept beside its snapshot. Every rule then names the document it came from (INV-4, source: SRC-2), including who may do what: "sales may see every report except the revenue report" becomes a rule that can be tested, where a scan would see nothing wrong. bravos context list shows the documents, bravos context check re-checks them, and a pre-push check stops a push that would send a secret in one. Free; the CLI runs no model and fetches nothing: your agent converts and fetches with your own access.
108
+
109
+ ### See which design rules hold
110
+
111
+ Skills: `/bravos` · `/bravos-recheck`
112
+
113
+ bravos rules lists every rule your design states (INV-n in the intent) with its status: broken (a test got through), retest due (the code under it changed since it was tested), unguarded (it can break somewhere and nothing stops it), guarded but untested, not placed (no code is tied to it yet), or holds (a test tried and was refused everywhere it is enforced). Each line names the document the rule came from and the places it is enforced. bravos dashboard shows the same as its Design rules tab, worst first, beside GuardLink's threat model. Free, read-only, no model; --json prints bravos.rules/v1. On the Team plan the pre-PR check and the PR workflow hold a pull request that changes a file a holding rule is enforced in (the check, or the role table that grants the permission) after that rule was last tested, until its test is replayed or the PR body names the rule; the after-edit note says the same while you work.
114
+
115
+ ### Context comes first
116
+
117
+ Skills: `/bravos-context` · `/bravos-annotate`
118
+
119
+ Threat-modelling starts only when a named person has confirmed what the product intends: bravos-annotate, campaigns and the nightly workflows wait until at least one item in .guardlink/intent.md is confirmed (run bravos-context; it asks for your design documents and a few decisions). A team that chooses to go without records that under a name, bravos context decline --by "<name>", which is committed like the intent; a coding agent is told never to decline for you. bravos context gate says which state a repository is in. Rechecks, retests and the ship check are not held back: they maintain a model that already exists.
120
+
103
121
  ### Threat-model someone else's project
104
122
 
105
123
  Skills: `/bravos-context` · `/bravos-annotate`
package/docs/UPGRADING.md CHANGED
@@ -2,6 +2,26 @@
2
2
 
3
3
  After `npm install -g @bugb-technologies/bravos`, run **`bravos setup --tools -y`** once on each machine and **`bravos sync`** in each repository. The notes below say what else changes, newest first.
4
4
 
5
+ ## 1.6.0
6
+
7
+ 1.6 makes threat modelling start from your design. Bravos now asks for your design documents, keeps them in the repository, turns what they state into rules it can test, and shows which rules hold.
8
+
9
+ - **Context now comes first. This changes what happens after `bravos sync`.** The annotate skill, campaigns, the after-edit notes that ask for annotation and the nightly annotate job all wait until a named person has confirmed at least one item of `.guardlink/intent.md`. A repository with no intent, or with a draft nobody confirmed, stops annotating until one of two things happens:
10
+ - you run the context step (ask your agent to "learn what this app intends"), or
11
+ - a named person records that the team goes without: `bravos context decline --by "<name>"`, then commit `.bravos/context/status.json`.
12
+
13
+ `bravos context gate` says which state a repository is in. Rechecks, retests and the ship check are not held back.
14
+ - **Design documents live in the repository.** Give the context step your PRDs, design documents or an earlier threat model, as files or links. Each is stored as Markdown under `.bravos/context/` and committed, so the team can keep it current; a link is kept beside its snapshot. `bravos context add | update | list | check`.
15
+ - A document carrying a secret, a local path or an embedded image is refused, by line number.
16
+ - A git pre-push check stops a push that would send one. It is installed in a clone only when that clone has no pre-push hook; otherwise Bravos prints the one line to add.
17
+ - Everyone with access to the repository can read these documents.
18
+ - **Rules name where they came from.** `intent.md` gains a Sources section and a "Who may do what" table, and each rule cites its document (`INV-4 … (source: SRC-2 "Report access")`).
19
+ - **A rule that holds can be tested.** The annotate skill now writes where a rule could break beside the check that stops it. Checks recorded before 1.6 show as "guarded, untested" until the next annotation pass rewrites them.
20
+ - **`bravos rules` and a Design rules tab in `bravos dashboard`** list every rule with its status: broken, retest due, unguarded, guarded but untested, not placed, or holds.
21
+ - **A change under a rule is noticed (Team plan).** The pre-PR check and the PR workflow hold a pull request that changes a file a holding rule is enforced or granted in, after that rule was last tested, until its test is replayed or the PR body names the rule (its INV id). This is conservative: an unrelated edit to such a file asks for the same.
22
+ - **For scripts:** the annotate skill's `slice.mjs` exits 3 with only `gate` and `notes` in its JSON while the gate is closed; `bravos dashboard --json` and the page's data gain a `rules` field.
23
+ - Run `bravos sync` in each repository to get the updated skills, hooks and workflows.
24
+
5
25
  ## 1.5.3
6
26
 
7
27
  1.5.3 ships with code graph 0.1.1 (Team plan), which fixes the fault 1.5.2 worked around.
@@ -2,6 +2,7 @@
2
2
  import { createHash } from 'node:crypto';
3
3
  import { appendFileSync, existsSync, mkdirSync, openSync, readFileSync, readSync, closeSync, fstatSync, writeFileSync } from 'node:fs';
4
4
  import { join } from 'node:path';
5
+ import { contextGate } from './context.mjs';
5
6
  import { gitStaleness, staleness } from './resync.mjs';
6
7
  import { asyncRunner, changedHunks, fingerprint, readSnapshot, workingChanges } from './snapshot.mjs';
7
8
 
@@ -180,12 +181,20 @@ export async function runAutopilot({ root, env = process.env, payload = {}, run
180
181
  }
181
182
  const paths = rows => arr(rows).map(w => typeof w === 'string' ? w : w?.file ?? w?.path)
182
183
  .filter(path => changedSource(path) && !isGenerated(path) && !configFiles.has(path));
183
- for (const path of paths(wl?.worklist)) {
184
- add(`unannotated:${path}`, `${path} has no GuardLink annotation: review the change with bravos-annotate; record any security-relevant behavior.`);
185
- }
186
- for (const path of paths(wl?.annotated)) {
187
- const ranges = hunks.get(path)?.map(h => h.start === h.end ? h.start : `${h.start}-${h.end}`).join(', ');
188
- add(`review:${path}`, `review changed code in ${path}${ranges ? ` (lines ${ranges})` : ''} with bravos-annotate. Check new behavior and guards even when another symbol in this file already has an annotation.`);
184
+ // Context first. While nobody has confirmed what the product intends (or declined), changed files are not put
185
+ // forward for annotation: one note says why and what to do, in place of a note per file. Notes about claims that
186
+ // already exist (stale, to retest, removed) still follow: they maintain the model, they do not start one.
187
+ const gate = contextGate(root);
188
+ if (!gate.open) {
189
+ if (paths(wl?.worklist).length || paths(wl?.annotated).length) add(`context:${gate.state}`, `${gate.message} The files changed this turn are not being put forward for annotation until then.`);
190
+ } else {
191
+ for (const path of paths(wl?.worklist)) {
192
+ add(`unannotated:${path}`, `${path} has no GuardLink annotation: review the change with bravos-annotate; record any security-relevant behavior.`);
193
+ }
194
+ for (const path of paths(wl?.annotated)) {
195
+ const ranges = hunks.get(path)?.map(h => h.start === h.end ? h.start : `${h.start}-${h.end}`).join(', ');
196
+ add(`review:${path}`, `review changed code in ${path}${ranges ? ` (lines ${ranges})` : ''} with bravos-annotate. Check new behavior and guards even when another symbol in this file already has an annotation.`);
197
+ }
189
198
  }
190
199
 
191
200
  const excluded = new Set(arr(wl?.excluded).map(e => e?.path ?? e?.file));
@@ -228,6 +237,18 @@ export async function runAutopilot({ root, env = process.env, payload = {}, run
228
237
  if (!controls.has(pair)) controls.set(pair, []);
229
238
  controls.get(pair).push(m.location);
230
239
  }
240
+ // A claim against a design rule (a threat the team's intent states, #inv-…) is named as one, with its INV id when
241
+ // the threat carries it, so the agent knows a rule from the design is what the edit sits under.
242
+ const ruleIds = new Map();
243
+ for (const t of arr(model?.threats)) {
244
+ const id = String(t?.id ?? '').replace(/^#/, '');
245
+ if (/^inv-/i.test(id)) ruleIds.set(id, arr(t.external_refs).map(r => /^intent:(INV-\d+)$/i.exec(String(r))?.[1]).find(Boolean) ?? null);
246
+ }
247
+ const ruleOf = (threat) => {
248
+ const id = String(threat ?? '').replace(/^#/, '');
249
+ if (!/^inv-/i.test(id)) return '';
250
+ return `design rule ${ruleIds.get(id) ? `${ruleIds.get(id)} ` : ''}`;
251
+ };
231
252
  const pref = readProving(root);
232
253
  if (ledger?.ledger === 'corrupt') {
233
254
  add('ledger:corrupt', 'GuardLink could not read the hypothesis ledger. Restore its evidence before treating any claim as untested or running a retest.');
@@ -247,7 +268,8 @@ export async function runAutopilot({ root, env = process.env, payload = {}, run
247
268
  // A current refutation holds until its anchor or a separate control changes.
248
269
  if (record.state === 'refuted' && !affectedControls.length) continue;
249
270
  const retest = record.state === 'retest' || record.state === 'confirmed' || record.expired || record.state === 'refuted';
250
- add(`proof:${record.key}:${record.state}`, `${retest ? 'Retest' : 'Untested'} ${record.threat} on ${record.asset} at ${loc.file}:${loc.line} (claim ${record.key}): ${proofInstruction(pref, retest)}.`);
271
+ const rule = ruleOf(record.threat);
272
+ add(`proof:${record.key}:${record.state}`, `${retest ? 'Retest' : 'Untested'} ${rule}${record.threat} on ${record.asset} at ${loc.file}:${loc.line} (claim ${record.key}): ${proofInstruction(pref, retest)}.${rule && retest ? ' If a PR is opened before it is retested, name the rule in the PR body.' : ''}`);
251
273
  }
252
274
  } else {
253
275
  // A legacy/unavailable ledger cannot report coverage of mitigated claims.
@@ -2,6 +2,7 @@
2
2
  import { spawn, spawnSync } from 'node:child_process';
3
3
  import { accessSync, constants, readFileSync } from 'node:fs';
4
4
  import { basename, delimiter, dirname, join } from 'node:path';
5
+ import { contextGate, readContext } from './context.mjs';
5
6
  import { THEMES } from './palette.mjs';
6
7
  import { readProving } from './proving.mjs';
7
8
  import { planLabel, planLine, status as licenceStatus } from './licence.mjs';
@@ -115,10 +116,28 @@ export function readIntent(root) {
115
116
  return { status: drafts > 0 ? 'draft' : 'confirmed', invariants, drafts };
116
117
  }
117
118
 
118
- function intentLine(intent, harness) {
119
+ // @comment -- "The briefing's line about the team's design documents, when there are any: how many, by id, that the rules cite them and that only the context skill opens them; and when the intent has fallen behind a document (edited, or added since), which ones and how to refresh. Ids only, never a title or any text from a document."
120
+ export function contextLine(context, harness) {
121
+ if (!context || typeof context !== 'object' || !context.count) return null;
119
122
  const run = harness === 'claude' ? '/bravos-context' : 'the bravos-context skill';
120
- if (intent.status === 'none') return `Intent: none — severities are not calibrated to the product; run ${run}`;
121
- if (intent.status === 'draft') return `Intent: draft (${intent.invariants} invariants, ${intent.drafts} items unconfirmed) — confirm with ${run}`;
123
+ const list = (ids) => (ids.length > 6 ? `${ids.slice(0, 6).join(', ')} and ${ids.length - 6} more` : ids.join(', '));
124
+ const behind = [
125
+ context.changed?.length ? `${list(context.changed)} changed since the rules were written` : '',
126
+ context.unread?.length ? `${list(context.unread)} not read into the intent yet` : '',
127
+ ].filter(Boolean);
128
+ const head = `Design documents: ${context.count} in .bravos/context/ (${list(context.ids ?? [])})`;
129
+ return behind.length
130
+ ? `${head} — ${behind.join('; ')}: refresh the intent with ${run}`
131
+ : `${head} — intent.md's rules cite them by id; only ${run} opens the documents themselves`;
132
+ }
133
+
134
+ // @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."
135
+ function intentLine(intent, harness, gate) {
136
+ const run = harness === 'claude' ? '/bravos-context' : 'the bravos-context skill';
137
+ 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).` : '';
138
+ const declined = gate?.state === 'declined' ? `declined by ${gate.by} on ${gate.at}` : '';
139
+ 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}`;
140
+ if (intent.status === 'draft') return `Intent: draft (${intent.invariants} invariants, ${intent.drafts} items unconfirmed${declined ? `; context ${declined}` : ''}) — confirm with ${run}${closed}`;
122
141
  return `Intent: confirmed (${intent.invariants} invariants)`;
123
142
  }
124
143
 
@@ -213,7 +232,9 @@ export function buildBriefing(inputs) {
213
232
  else if (i.inFlight.prs > 0 || i.inFlight.files > 0) {
214
233
  tail.push(`In flight by teammates: ${i.inFlight.files} files in ${i.inFlight.prs} open PRs`);
215
234
  }
216
- if (i.intent && typeof i.intent === 'object') tail.push(intentLine(i.intent, i.harness));
235
+ if (i.intent && typeof i.intent === 'object') tail.push(intentLine(i.intent, i.harness, i.gate));
236
+ const documents = contextLine(i.context, i.harness);
237
+ if (documents) tail.push(documents);
217
238
  if (i.proving && typeof i.proving === 'object') {
218
239
  const p = i.proving;
219
240
  tail.push(p.status === 'set'
@@ -462,6 +483,8 @@ export async function collect(root, env, { deadlineMs = 20000, nextCount = 3 } =
462
483
  dashboard: facts.dashboard,
463
484
  inFlight,
464
485
  intent: readIntent(root),
486
+ context: readContext(root),
487
+ gate: contextGate(root),
465
488
  annotationMode: readAnnotationMode(root),
466
489
  // bravos on PATH: what its probe says (a graph for this commit or not); else codegraph-mcp on PATH means the MCP route.
467
490
  codegraph: graphState ?? (whichOnPath('codegraph-mcp', env) ? 'unknown' : 'unavailable'),
@@ -635,7 +658,8 @@ export function quickStart(inputs, harness) {
635
658
  const picks = [];
636
659
  if (inputs?.stale || arr(inputs?.stranded).length > 0) picks.push('bravos-resync');
637
660
  if (arr(ci?.confirmed).length > 0) picks.push('bravos-recheck');
638
- if (inputs?.intent?.status === 'none') picks.push('bravos-context');
661
+ // Context first: with no intent, or one nobody has confirmed, the context skill is the start, ahead of everything else.
662
+ if (inputs?.intent?.status === 'none' || inputs?.gate?.open === false) picks.push('bravos-context');
639
663
  const cov = ci?.summary?.coverage;
640
664
  if (cov && num(cov.source_files) > num(cov.annotated_files)) picks.push('bravos-annotate');
641
665
  if (arr(g.next?.queue).some((q) => q?.state === 'untested')) picks.push('bravos-templatize');