@bugb-technologies/bravos 1.5.2 → 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.
Files changed (38) hide show
  1. package/dist/artifacts.js +31 -1
  2. package/dist/cli.js +78 -5
  3. package/dist/codegraph.js +32 -4
  4. package/dist/context.js +351 -0
  5. package/dist/dashboard.js +35 -10
  6. package/dist/guide.js +3 -0
  7. package/dist/help.js +19 -0
  8. package/dist/report/data.js +2 -1
  9. package/dist/rules.js +218 -0
  10. package/dist/setup.js +33 -7
  11. package/dist/uninstall.js +6 -0
  12. package/dist/versions.js +1 -1
  13. package/dist/watch-frame.js +8 -1
  14. package/dist/watch.js +11 -2
  15. package/docs/GUIDE.md +18 -0
  16. package/docs/UPGRADING.md +30 -0
  17. package/hooks/lib/autopilot.mjs +29 -7
  18. package/hooks/lib/briefing.mjs +29 -5
  19. package/hooks/lib/context.mjs +522 -0
  20. package/hooks/lib/pre-pr.mjs +70 -0
  21. package/hooks/lib/setup.mjs +5 -2
  22. package/package.json +1 -1
  23. package/skills/bravos/SKILL.md +1 -1
  24. package/skills/bravos-annotate/SKILL.md +5 -3
  25. package/skills/bravos-annotate/scripts/lib/gate.mjs +45 -0
  26. package/skills/bravos-annotate/scripts/slice.mjs +10 -0
  27. package/skills/bravos-campaign/SKILL.md +1 -1
  28. package/skills/bravos-codegraph/SKILL.md +1 -1
  29. package/skills/bravos-context/SKILL.md +16 -10
  30. package/skills/bravos-context/intent.example.md +14 -1
  31. package/skills/bravos-recheck/SKILL.md +1 -1
  32. package/skills/bravos-ship/SKILL.md +2 -1
  33. package/skills/bravos-templatize/SKILL.md +1 -1
  34. package/templates/dashboard/dashboard.html +97 -0
  35. package/templates/workflows/bravos-nightly-claude.yml +36 -2
  36. package/templates/workflows/bravos-nightly-codex.yml +36 -2
  37. package/templates/workflows/bravos-nightly-copilot.yml +23 -0
  38. package/templates/workflows/bravos-pr-gate.yml +76 -0
package/dist/dashboard.js CHANGED
@@ -6,6 +6,7 @@ import * as graph from './codegraph.js';
6
6
  import { featureState, licenceLib } from './licence.js';
7
7
  import { templatesDir, version } from './paths.js';
8
8
  import { BravosError } from './types.js';
9
+ import { gatherRules } from './rules.js';
9
10
  export const DASHBOARD_DIR = '.bravos/dashboard';
10
11
  export const DASHBOARD_PATH = `${DASHBOARD_DIR}/index.html`;
11
12
  /** What the saved page was built from, for the session briefing to tell a current page from an old one. */
@@ -138,12 +139,14 @@ export function codeGraphStore(answers) {
138
139
  };
139
140
  }
140
141
  const NOT_BUILT = /no graph|No CodeGraph|codegraph_unavailable|not built|nothing is there|not available for project/i;
141
- // @comment -- "What the code graph says about itself for this checkout, from one cheap question: current, not-built (no graph for this commit), diverged (the working tree has moved since it was built), or unknown when it cannot say. Read-only."
142
+ // @comment -- "What the code graph says about itself for this checkout, from one cheap question: current, not-built (no graph for this commit), diverged (the working tree has moved since it was built), busy (it is there and another session or a build holds it), or unknown when it cannot say. Busy is tested before not-built and is never a reason to build. Read-only."
142
143
  export async function graphState(root, env) {
143
144
  try {
144
145
  const a = (await graph.askMany(root, env, [{ tool: 'codegraph_entry_points', args: { limit: 1 } }], 60000)).answers.codegraph_entry_points;
145
146
  if (!a)
146
147
  return 'unknown';
148
+ if ('error' in a && (a.busy || graph.isGraphBusy(a.error)))
149
+ return 'busy';
147
150
  if ('error' in a)
148
151
  return NOT_BUILT.test(a.error) ? 'not-built' : 'unknown';
149
152
  const state = text(obj(obj(a.result).graph_currency).state);
@@ -154,8 +157,8 @@ export async function graphState(root, env) {
154
157
  }
155
158
  }
156
159
  // @comment -- "Makes the code graph match the code before the dashboard draws from it, so a fresh page is never drawn from an old graph: no graph for this commit is built, and one the working tree has moved away from is rebuilt for the tree as it stands (--mode build; the default mode would reuse the commit's graph). Always --scip no-exec, which runs none of the repository's code, and no model. Returns a sentence for the page, empty when nothing was needed; a failed build is said, never thrown."
157
- export async function refreshGraph(root, env, onProgress) {
158
- const state = await graphState(root, env);
160
+ export async function refreshGraph(root, env, onProgress, known) {
161
+ const state = known ?? (await graphState(root, env));
159
162
  if (state !== 'not-built' && state !== 'diverged')
160
163
  return '';
161
164
  onProgress?.(state === 'not-built' ? 'Building the code graph for this commit first (no repository code runs; minutes on a large repository)…' : 'The code has moved since the code graph was built: rebuilding it first…');
@@ -185,8 +188,13 @@ export async function buildCodeGraph(root, env, opts = {}) {
185
188
  return note('locked', 'The code graph is on the Team plan: bravos account activate starts a 30-day trial, no card. The threat model tab is complete without it.');
186
189
  if (!graph.graphBin('codegraph-mcp', env))
187
190
  return note('missing', 'The code graph is not installed on this machine: run bravos setup --codegraph, then bravos graph build . and bravos dashboard again.');
188
- // The licence and the binary are settled, so a missing or behind graph is rebuilt before it is asked.
189
- const rebuilt = opts.refresh === false ? '' : await refreshGraph(root, env, opts.onProgress);
191
+ const BUSY = 'The code graph is busy: another session or a build is using it. Nothing needs rebuilding; run bravos dashboard again in a moment.';
192
+ // The licence and the binary are settled, so a missing or behind graph is rebuilt before it is asked. A busy one
193
+ // is neither: the server already waited for it, so the page says so now and nothing is built or asked again.
194
+ const state = opts.refresh === false ? null : await graphState(root, env);
195
+ if (state === 'busy')
196
+ return note('failed', BUSY);
197
+ const rebuilt = state ? await refreshGraph(root, env, opts.onProgress, state) : '';
190
198
  let answered;
191
199
  try {
192
200
  answered = await graph.askMany(root, env, Object.values(QUESTIONS).map((q) => ({ tool: q.tool, args: { ...q.args } })), 300000);
@@ -194,6 +202,10 @@ export async function buildCodeGraph(root, env, opts = {}) {
194
202
  catch (e) {
195
203
  return note('failed', `The code graph could not be asked (${e.message.slice(0, 200)}).`);
196
204
  }
205
+ // Asked and busy: the graph is there and another session or a build holds it. Said as that, never as "not built".
206
+ if (Object.values(answered.answers).some((a) => 'error' in a && (a.busy || graph.isGraphBusy(a.error)))) {
207
+ return note('failed', `${BUSY}${rebuilt}`);
208
+ }
197
209
  const errors = Object.values(answered.answers).map((a) => ('error' in a ? a.error : ''));
198
210
  if (errors.some((m) => NOT_BUILT.test(m))) {
199
211
  return note('not-built', `No code graph is built for this repository at this commit: run bravos graph build . (a few minutes, no tokens), then bravos dashboard again.${rebuilt}`);
@@ -219,7 +231,7 @@ export function shareCodeMap(store) {
219
231
  return { codemap: shared, pages };
220
232
  }
221
233
  // @comment -- "Renders the one-file dashboard: the page template with its facts and GuardLink's page each embedded as JSON in a non-executing script tag, every '<' escaped so none can close its tag. When there are code graph answers, they and the vendored Code graph pages (script and stylesheet) are embedded the same way; the page assembles them into a second sandboxed frame. Both go in through one pass with a function replacer, so nothing in either is read as a placeholder or a replacement pattern."
222
- export function renderDashboard(data, threatModelHtml, store = null) {
234
+ export function renderDashboard(data, threatModelHtml, store = null, rules = null) {
223
235
  const template = readFileSync(join(templatesDir(), 'dashboard', 'dashboard.html'), 'utf8');
224
236
  // One pass over the template, so text inside either value that looks like a placeholder is never filled in turn.
225
237
  // The pages' script and stylesheet travel only with a page that has graph answers to draw.
@@ -230,8 +242,9 @@ export function renderDashboard(data, threatModelHtml, store = null) {
230
242
  CODEGRAPH: () => (store ? shareCodeMap(store) : null),
231
243
  PAGES_JS: () => asset('codegraph-pages.js'),
232
244
  PAGES_CSS: () => asset('codegraph-pages.css'),
245
+ RULES: () => rules,
233
246
  };
234
- return template.replace(/__BRAVOS_(DATA|THREAT_MODEL|CODEGRAPH|PAGES_JS|PAGES_CSS)__/g, (_m, which) => inert(fill[which]()));
247
+ return template.replace(/__BRAVOS_(DATA|THREAT_MODEL|CODEGRAPH|PAGES_JS|PAGES_CSS|RULES)__/g, (_m, which) => inert(fill[which]()));
235
248
  }
236
249
  // @comment -- "bravos dashboard: gathers the repository's facts (read-only git, this machine's plan label), builds GuardLink's page and, on the Team plan, the Code graph pages from the graph's answers, and writes one self-contained HTML file. By default that is .bravos/dashboard/index.html beside a .gitignore of '*', since the page can carry git identities and findings; with `out` nothing is written inside the repository. A page is written even when GuardLink has nothing to show, so the person always gets a file that says what to do next."
237
250
  export async function buildDashboard(root, env, opts = {}) {
@@ -242,6 +255,17 @@ export async function buildDashboard(root, env, opts = {}) {
242
255
  const base = opts.since ?? baseRef(root, env);
243
256
  const tm = buildThreatModel(root, env, { base, blame: opts.blame !== false });
244
257
  const cg = await buildCodeGraph(root, env, { names: opts.blame !== false, refresh: opts.graphBuild !== false, onProgress: opts.onProgress });
258
+ // The design rules: free on every plan, read from the intent, GuardLink's model and its test ledger. A failure
259
+ // here is a note on that view, never a failed page.
260
+ let rules = null;
261
+ let rulesPart;
262
+ try {
263
+ rules = await gatherRules(root, env, { names: opts.blame !== false });
264
+ rulesPart = { state: rules.state === 'none' ? 'missing' : 'present', note: rules.note };
265
+ }
266
+ catch (e) {
267
+ rulesPart = { state: 'failed', note: `The design rules could not be read (${e.message.split('\n')[0].slice(0, 200)}).` };
268
+ }
245
269
  let plan = null;
246
270
  try {
247
271
  const L = (await licenceLib());
@@ -260,8 +284,9 @@ export async function buildDashboard(root, env, opts = {}) {
260
284
  plan,
261
285
  threatModel: { state: tm.state, note: tm.note, blame: tm.blame, since: tm.since },
262
286
  codeGraph: { state: cg.state, note: cg.note },
287
+ rules: rulesPart,
263
288
  };
264
- const page = renderDashboard(data, tm.html, cg.store);
289
+ const page = renderDashboard(data, tm.html, cg.store, rules);
265
290
  let path;
266
291
  if (opts.out) {
267
292
  path = resolve(opts.out);
@@ -275,9 +300,9 @@ export async function buildDashboard(root, env, opts = {}) {
275
300
  writeFileSync(ignore, '*\n');
276
301
  path = join(root, DASHBOARD_PATH);
277
302
  // Beside the page: what it was built from, so the session briefing can say when it has fallen behind.
278
- const meta = { schema: 'bravos.dashboard-meta/v1', generatedAt: data.generatedAt, commit: git(root, env, ['rev-parse', 'HEAD']), branch: data.branch, threatModel: tm.state, codeGraph: cg.state };
303
+ const meta = { schema: 'bravos.dashboard-meta/v1', generatedAt: data.generatedAt, commit: git(root, env, ['rev-parse', 'HEAD']), branch: data.branch, threatModel: tm.state, codeGraph: cg.state, rules: rulesPart.state };
279
304
  writeFileSync(join(root, DASHBOARD_META), `${JSON.stringify(meta, null, 2)}\n`);
280
305
  }
281
306
  writeFileSync(path, page);
282
- return { path, threatModel: { state: tm.state, note: tm.note }, codeGraph: { state: cg.state, note: cg.note } };
307
+ return { path, threatModel: { state: tm.state, note: tm.note }, codeGraph: { state: cg.state, note: cg.note }, rules: rulesPart };
283
308
  }
package/dist/guide.js CHANGED
@@ -113,6 +113,9 @@ export const GUIDE_TOPICS = [
113
113
  items: [
114
114
  { name: 'Where do I start? What is open?', skills: ['bravos'], body: ['Reads the briefing and names the one next step, with the reason.'] },
115
115
  { name: 'Teach bravos what the app is for', skills: ['bravos-context'], body: ['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.'] },
116
+ { name: 'Start from your design documents', skills: ['bravos-context'], body: ['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.'] },
117
+ { name: 'See which design rules hold', skills: ['bravos', 'bravos-recheck'], body: ['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.'] },
118
+ { name: 'Context comes first', skills: ['bravos-context', 'bravos-annotate'], body: ['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.'] },
116
119
  { name: 'Threat-model someone else\'s project', skills: ['bravos-context', 'bravos-annotate'], body: ['bravos-context assumes you are researching software you do not own (an open-source project, a vendor\'s code): it drafts the intent from upstream\'s own docs with links and asks only the scope decisions — which configuration to rate against (shipped defaults or the hardened setup upstream recommends), single organisation or multi-tenant, which attackers are in scope, and the intended-looking behaviours upstream does not document. intent.md records them as Assumptions, and severities are rated against them. Say "this is our product" for the owner interview instead.'] },
117
120
  { name: 'Answer bravos\'s questions as a team', skills: ['bravos-context'], body: ['bravos-context opens its questions as a bravos page (bravos review intent): pre-filled with bravos\'s suggestions and their sources; change what is wrong, make the calls marked \'needs your call\' (Confirm stays off until you do), and the facts bravos drafted stay folded unless you open one to object. Each person\'s answers save to .guardlink/intent-answers/<name>.json; teammates run bravos review intent after pulling and commit theirs. bravos review intent --summary shows where people agree and disagree; only what a named person agreed to is marked confirmed. On Claude Code, --share puts the same page on a private claude.ai link instead.'] },
118
121
  { name: 'I wrote security-relevant code', skills: ['bravos-annotate'], body: ['Annotates what you changed to guardlink\'s evidence bar and runs the lint gate until clean.'] },
package/dist/help.js CHANGED
@@ -123,6 +123,25 @@ Intent-aware annotation
123
123
  answer, never an automatic acceptance. The briefing's Intent line says whether intent is
124
124
  recorded, still draft, or missing.
125
125
 
126
+ Design documents
127
+ bravos-context starts from your own design: PRDs, design documents, an earlier threat model,
128
+ as files or links. bravos context add keeps each one in the repository as Markdown under
129
+ .bravos/context/ (committed; a link is kept beside its snapshot) after refusing secrets and
130
+ local paths, and each rule in intent.md names the document it came from (source: SRC-2).
131
+ bravos context list | check | update SRC-n. The CLI takes text only and runs no model: the
132
+ agent in your session converts a PDF or fetches a link with your own access.
133
+
134
+ Design rules
135
+ bravos rules lists each rule your design states with its status (broken, retest due,
136
+ unguarded, guarded but untested, not placed, holds), the document it came from and where the
137
+ code enforces it. bravos dashboard shows them as its Design rules tab. Read-only; no model.
138
+
139
+ Context comes first
140
+ bravos-annotate, campaigns and the nightly workflows start only when a named person has
141
+ confirmed at least one item of .guardlink/intent.md, or has recorded that the team goes
142
+ without: bravos context decline --by "<name>". bravos context gate says which it is.
143
+ Rechecks, retests and the ship check are never held back.
144
+
126
145
  Session start
127
146
  One hook run returns two things. The briefing (counts, FIX NOW, what to test next, stale
128
147
  claims, tickets, intent) goes to the model on every start, resume, clear and compact. On a
@@ -244,7 +244,8 @@ export async function gatherEvidence(root, env, opts) {
244
244
  items,
245
245
  runs,
246
246
  sast: sastSummary,
247
- graph: graph && 'notBuilt' in graph ? 'not-built' : graph,
247
+ // A graph in use by another session says nothing this time: the report leaves its graph facts out, as when it is not installed.
248
+ graph: graph && 'notBuilt' in graph ? 'not-built' : graph && 'busy' in graph ? null : graph,
248
249
  gaps,
249
250
  };
250
251
  }
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/setup.js CHANGED
@@ -3,7 +3,7 @@ import { checkProofTool, formatProofTool } from './proof-tools.js';
3
3
  import { spawnSync } from 'node:child_process';
4
4
  import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
5
5
  import { isAbsolute, join } from 'node:path';
6
- import { bundleEnvironment, hostTarget, install, missingPaths, staged, VERSIONS } from './artifacts.js';
6
+ import { bundleEnvironment, hostTarget, install, missingPaths, olderThan, staged, stagedVersion, VERSIONS } from './artifacts.js';
7
7
  import { graphBin, graphEnv } from './codegraph.js';
8
8
  import { whichBin } from './guardlink.js';
9
9
  import { findAnalyzer } from './graphbin.js';
@@ -11,6 +11,12 @@ import { licenceLib, requireFeature } from './licence.js';
11
11
  import { BravosError } from './types.js';
12
12
  import { PROOF_TOOL_PINS } from './versions.js';
13
13
  import { installProofTool, proofToolAction } from './install-proof-tool.js';
14
+ // @comment -- "The version of a staged bundle when it is older than the one this bravos pins, else null. An existing install keeps working on the old bundle until setup runs; this is how setup, and its --check, know there is a newer one to fetch. Read-only."
15
+ export function behindPin(env, kind) {
16
+ const dir = staged(env, kind);
17
+ const have = dir ? stagedVersion(dir) : null;
18
+ return have && olderThan(have, VERSIONS[kind]) ? have : null;
19
+ }
14
20
  // @comment -- "What is here and what setup would do, read-only: for each piece its path when present, the pinned version, whether the licence covers it, and the one action."
15
21
  export async function plan(env) {
16
22
  const L = await licenceLib();
@@ -18,9 +24,13 @@ export async function plan(env) {
18
24
  const sast = L.entitled(v, 'sast');
19
25
  const graph = L.entitled(v, 'codegraph');
20
26
  const t = hostTarget();
27
+ const behind = (kind) => {
28
+ const have = behindPin(env, kind);
29
+ return have ? { behind: have } : {};
30
+ };
21
31
  const items = [
22
- { id: 'analyzer', present: staged(env, 'analyzer') ?? findAnalyzer(env), wanted: VERSIONS.analyzer, licensed: sast, action: !t ? 'no build for this platform' : sast ? 'fetch, verify and stage the analyzer bundle' : 'on the Team plan: bravos account activate' },
23
- { id: 'codegraph', present: staged(env, 'codegraph') ?? graphBin('codegraph-build', env), wanted: VERSIONS.codegraph, licensed: graph, action: !t ? 'no build for this platform' : graph ? 'fetch, verify and stage codegraph-build and codegraph-mcp' : 'on the Team plan: bravos account activate' },
32
+ { id: 'analyzer', present: staged(env, 'analyzer') ?? findAnalyzer(env), wanted: VERSIONS.analyzer, licensed: sast, action: !t ? 'no build for this platform' : sast ? 'fetch, verify and stage the analyzer bundle' : 'on the Team plan: bravos account activate', ...behind('analyzer') },
33
+ { id: 'codegraph', present: staged(env, 'codegraph') ?? graphBin('codegraph-build', env), wanted: VERSIONS.codegraph, licensed: graph, action: !t ? 'no build for this platform' : graph ? 'fetch, verify and stage codegraph-build and codegraph-mcp' : 'on the Team plan: bravos account activate', ...behind('codegraph') },
24
34
  ...['guardlink', 'cxg'].map(id => ({
25
35
  id, present: whichBin(id, env), wanted: PROOF_TOOL_PINS[id].revision ?? PROOF_TOOL_PINS[id].version,
26
36
  licensed: null, action: proofToolAction(id), proofTool: checkProofTool(id, env),
@@ -33,7 +43,8 @@ export const formatPlan = (items) => items.map(i => {
33
43
  return '✘ ' + i.id.padEnd(10) + ' ' + i.present + ' (' + i.proofTool.status + ') — ' + i.action;
34
44
  }
35
45
  const status = i.present ? i.present : 'absent — ' + i.action;
36
- return (i.present ? '✔ ' : '✘ ') + i.id.padEnd(10) + ' ' + status + (i.present && i.licensed === false ? ' (licence does not cover it now)' : '');
46
+ const older = i.present && i.behind ? ` (${i.behind}; this bravos pins ${i.wanted}: bravos setup fetches it)` : '';
47
+ return (i.present ? '✔ ' : '✘ ') + i.id.padEnd(10) + ' ' + status + older + (i.present && i.licensed === false ? ' (licence does not cover it now)' : '');
37
48
  });
38
49
  // @comment -- "The setup itself. Default: the two licensed bundles for a licensed machine; --tools adds guardlink and cxg; --analyzer/--codegraph narrow it. Each licensed piece passes the gate before the first request. --dry-run prints the actions; -y is required for the package-manager installs because they run other people's installers."
39
50
  export async function runSetup(env, opts, io) {
@@ -52,15 +63,30 @@ export async function runSetup(env, opts, io) {
52
63
  const what = `bravos setup --${kind}`;
53
64
  await requireFeature(env, kind === 'analyzer' ? 'sast' : 'codegraph', what, { fetch: io.fetch });
54
65
  const have = staged(env, kind);
55
- if (have && !opts.yes) {
66
+ // A bundle older than the pin is fetched without -y: the pin is what this bravos was tested with, and
67
+ // "already staged" would leave an existing install on the old one for good.
68
+ const older = behindPin(env, kind);
69
+ if (have && !opts.yes && !older) {
56
70
  lines.push(`${kind}: already staged at ${have} (add -y to fetch ${VERSIONS[kind]} again)`);
57
71
  continue;
58
72
  }
59
73
  if (opts.dryRun) {
60
- lines.push(`dry-run: would fetch ${kind} ${VERSIONS[kind]} for ${hostTarget() ?? 'this platform'} through the account portal, verify its signature and stage it under $BRAVOS_HOME/${kind}/`);
74
+ lines.push(`dry-run: would fetch ${kind} ${VERSIONS[kind]} for ${hostTarget() ?? 'this platform'} through the account portal, verify its signature and stage it under $BRAVOS_HOME/${kind}/${older ? ` (replacing ${older})` : ''}`);
75
+ continue;
76
+ }
77
+ let r;
78
+ try {
79
+ r = await install(kind, { env, fetch: io.fetch, keys: io.keys, echo: io.echo });
80
+ }
81
+ catch (e) {
82
+ // The older bundle is complete and still the one in use, so a failed upgrade is said, not thrown.
83
+ if (!older || opts.yes)
84
+ throw e;
85
+ lines.push(`${kind}: ${older} stays staged at ${have}; ${VERSIONS[kind]} could not be fetched (${e.message.split('\n')[0].slice(0, 200)}). Run bravos setup again later.`);
61
86
  continue;
62
87
  }
63
- const r = await install(kind, { env, fetch: io.fetch, keys: io.keys, echo: io.echo });
88
+ if (older)
89
+ lines.push(`${kind}: ${older} was staged; this bravos pins ${VERSIONS[kind]}`);
64
90
  const missing = missingPaths(kind, r.dir);
65
91
  lines.push(`${kind}: ${r.version} staged at ${r.dir}${missing.length ? ` — missing ${missing.join(', ')}` : ''}`);
66
92
  lines.push(...selfTest(kind, r.dir, env));
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/dist/versions.js CHANGED
@@ -5,5 +5,5 @@ import { hooksDir } from './paths.js';
5
5
  /** The licensed analyzer bundle (bravos-cli plus gitleaks, osv-scanner, kics, zizmor and the rules), published by specter-v1's analyzer-release workflow. */
6
6
  export const ANALYZER_VERSION = '0.6.2';
7
7
  /** The code graph binaries (codegraph-build, codegraph-mcp), published by specter-v1's codegraph-release workflow. */
8
- export const CODEGRAPH_VERSION = '0.1.0';
8
+ export const CODEGRAPH_VERSION = '0.1.1';
9
9
  export const PROOF_TOOL_PINS = JSON.parse(readFileSync(join(hooksDir(), 'lib', 'proof-tool-pins.json'), 'utf8'));
@@ -268,6 +268,13 @@ function graphPanel(sn, inner) {
268
268
  body: [[s(`no graph for this commit (${sn.sha})`, C.amber)], [s('bravos keys the graph to the commit: rebuild after you commit', C.steel)], [s('→ bravos graph build . --scip no-exec', C.green)]],
269
269
  };
270
270
  }
271
+ if (g.state === 'busy') {
272
+ return {
273
+ title: 'CODE GRAPH',
274
+ right: 'busy',
275
+ body: [[s('in use by another session or a build', C.steel)], [s('nothing to do: watch asks again on the next refresh', C.steel)]],
276
+ };
277
+ }
271
278
  if (!d) {
272
279
  const body = g.entryPoints !== null ? [[s(`${g.entryPoints} entry points`)]] : [[s('askable: bravos graph <question>', C.steel)]];
273
280
  return { title: 'CODE GRAPH', right: 'asking…', body };
@@ -520,7 +527,7 @@ function tileItems(sn) {
520
527
  { label: 'COVERAGE', value: sn.coverage ? `${sn.coverage.percent}%` : '?', c: (sn.coverage?.percent ?? 0) >= 80 ? C.green : C.amber },
521
528
  { label: 'STALE', value: c ? String(c.stale) : '?', c: c?.stale ? C.amber : C.green },
522
529
  { label: 'SETUP', value: `${sn.setup.done}/${sn.setup.total}`, c: C.green },
523
- { label: 'GRAPH', value: worst ? `${Math.round(worst.ratio * 100)}%` : sn.graph.state === 'not-built' ? 'none' : sn.graph.state === 'unavailable' ? 'off' : '—', c: worst ? (worst.sufficient ? C.green : C.amber) : C.steel, sub: worst ? worst.language : undefined },
530
+ { label: 'GRAPH', value: worst ? `${Math.round(worst.ratio * 100)}%` : sn.graph.state === 'not-built' ? 'none' : sn.graph.state === 'unavailable' ? 'off' : sn.graph.state === 'busy' ? 'busy' : '—', c: worst ? (worst.sufficient ? C.green : C.amber) : C.steel, sub: worst ? worst.language : undefined },
524
531
  { label: 'SAST', value: sn.sast ? String(sn.sast.total) : sn.sastAvailable ? 'ready' : 'off', c: sn.sast?.unjoinedReachable ? C.red : C.steel },
525
532
  ];
526
533
  }
package/dist/watch.js CHANGED
@@ -57,7 +57,7 @@ const fileOf = (c) => String(c.location?.file ?? c.file ?? '?');
57
57
  const lineOf = (c) => num(c.location?.line ?? c.line);
58
58
  const keyOf = (c) => `${c.threat ?? '?'}|${c.asset ?? '?'}|${fileOf(c)}`;
59
59
  const sevRank = (s) => ['critical', 'high', 'medium', 'low'].indexOf(s) >>> 0;
60
- // @comment -- "One graph question in the shape the Python CLI's `bravos graph --json` printed ({result} or {error: codegraph_unavailable}), so summarizeGraph and graphAnswer read both the old transcript fixtures and the live MCP answers alike."
60
+ // @comment -- "One graph question in the shape the Python CLI's `bravos graph --json` printed ({result} or {error: codegraph_unavailable}), so summarizeGraph and graphAnswer read both the old transcript fixtures and the live MCP answers alike. A graph another process holds is {error: graph_busy} with an ask-again remedy, never codegraph_unavailable."
61
61
  export async function askGraph(root, env, question, args = [], timeoutMs = 60000) {
62
62
  if (!graph.graphBin('codegraph-mcp', env))
63
63
  return null;
@@ -66,6 +66,9 @@ export async function askGraph(root, env, question, args = [], timeoutMs = 60000
66
66
  }
67
67
  catch (e) {
68
68
  const m = e.message ?? '';
69
+ // Before the "not built" test, and never that: a busy graph must not send anyone to rebuild it.
70
+ if (graph.isGraphBusy(e))
71
+ return { error: 'graph_busy', message: m, remedy: graph.GRAPH_BUSY_REMEDY };
69
72
  if (/no graph|No CodeGraph|codegraph_unavailable|not built/i.test(m))
70
73
  return { error: 'codegraph_unavailable', message: m, remedy: '`bravos graph build .` indexes this repository' };
71
74
  return { error: 'graph_error', message: m };
@@ -112,6 +115,9 @@ export async function graphDetail(root, env) {
112
115
  return null;
113
116
  }
114
117
  const entry = got.answers[QUESTIONS.entry];
118
+ // Busy first: the graph is there and in use, so the panel keeps what it knew and asks again on the next refresh.
119
+ if (Object.values(got.answers).some((a) => 'error' in a && (a.busy || graph.isGraphBusy(a.error))))
120
+ return { busy: true };
115
121
  if (entry && 'error' in entry && /no graph|No CodeGraph|codegraph_unavailable|not built/i.test(entry.error))
116
122
  return { notBuilt: true };
117
123
  const ok = (tool) => {
@@ -177,7 +183,7 @@ export async function snapshot(root, env, opts = {}) {
177
183
  const i = collected;
178
184
  // The graph's own answers outrank the probe: a graph that just answered five questions is there, whatever a
179
185
  // probe that collided with another session said. Set before the setup score reads it.
180
- if (graphR && !('notBuilt' in graphR) && (i.codegraph === 'not-built' || i.codegraph === 'unknown'))
186
+ if (graphR && !('notBuilt' in graphR) && !('busy' in graphR) && (i.codegraph === 'not-built' || i.codegraph === 'unknown'))
181
187
  i.codegraph = 'current';
182
188
  const g = i.guardlink === 'missing' ? null : (i.guardlink ?? {});
183
189
  const ci = g?.ci ?? null;
@@ -228,6 +234,9 @@ export async function snapshot(root, env, opts = {}) {
228
234
  graph = { state: 'unavailable', entryPoints: null, byKind: null, detail: null };
229
235
  else if (graphR && 'notBuilt' in graphR)
230
236
  graph = { state: 'not-built', entryPoints: null, byKind: null, detail: null };
237
+ // In use by another session or a build: what the last refresh read still stands; with nothing read yet, say busy.
238
+ else if (graphR && 'busy' in graphR)
239
+ graph = prev?.graph?.detail ? prev.graph : { state: 'busy', entryPoints: null, byKind: null, detail: null };
231
240
  else
232
241
  graph = { state: String(i.codegraph ?? 'unavailable'), entryPoints: graphR?.entry?.total ?? null, byKind: graphR?.entry?.byKind ?? null, detail: graphR ?? null };
233
242
  }
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`