@bugb-technologies/bravos 1.14.1 → 1.16.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/cli.js CHANGED
@@ -787,9 +787,22 @@ export function buildProgram(io, result) {
787
787
  }));
788
788
  program
789
789
  .command('doctor [dir]')
790
- .description('Read-only check of the tools, licence, skills and hooks bravos relies on.')
790
+ .description('Read-only check of the tools, licence, skills and hooks bravos relies on. --fix-hooks removes Bravos\'s or Joseph\'s user-level hooks whose script is gone, after a backup.')
791
791
  .addHelpText('after', DOCTOR_HELP)
792
- .action((dir) => guardedAsync(async (lines) => {
792
+ .option('--fix-hooks', 'remove Bravos\'s or Joseph\'s own user-level hooks whose script no longer exists (each settings file is backed up first; nothing else is changed)')
793
+ .action((dir, opts) => guardedAsync(async (lines) => {
794
+ // @comment -- "bravos doctor --fix-hooks: the person's own command for removing dead Bravos or Joseph hooks from their user settings (hooks/lib/dead-hooks.mjs fixDeadHooks): it says each entry it removes and where the backup is. An agent is told to name the command, never to run it."
795
+ if (opts.fixHooks) {
796
+ const D = (await import(pathToFileURL(join(hooksDir(), 'lib', 'dead-hooks.mjs')).href));
797
+ const r = D.fixDeadHooks({ ...io.env, HOME: homeOf(io.env) });
798
+ if (!r.removed.length)
799
+ lines.push('No dead user-level hooks: nothing to remove.');
800
+ for (const d of r.removed)
801
+ lines.push(`removed from ${d.file} (${d.event}): ${d.script} no longer exists`);
802
+ if (r.backups.length)
803
+ lines.push(`backup${r.backups.length === 1 ? '' : 's'}: ${r.backups.join(', ')}`, 'Start a new session: the "hook error" line is gone.');
804
+ return;
805
+ }
793
806
  const L = await licenceLib();
794
807
  const v = L.status(io.env);
795
808
  lines.push(formatDoctor(await withLegacySkills(withLicence(runDoctor(dirArg(dir), io.env), L.planLine(v), v.licensed), io.env)));
package/dist/dashboard.js CHANGED
@@ -260,7 +260,7 @@ export async function buildDashboard(root, env, opts = {}) {
260
260
  let rules = null;
261
261
  let rulesPart;
262
262
  try {
263
- rules = await gatherRules(root, env, { names: opts.blame !== false });
263
+ rules = await gatherRules(root, env, { names: opts.blame !== false, details: true });
264
264
  rulesPart = { state: rules.state === 'none' ? 'missing' : 'present', note: rules.note };
265
265
  }
266
266
  catch (e) {
package/dist/doctor.js CHANGED
@@ -132,7 +132,9 @@ export function withLicence(r, plan, licensed) {
132
132
  export async function withLegacySkills(r, env) {
133
133
  const L = (await import(pathToFileURL(join(hooksDir(), 'lib', 'legacy-skills.mjs')).href));
134
134
  const found = L.legacySkills({ ...env, HOME: env.HOME ?? homedir() });
135
- return { ...r, legacy_skills: found, ...(found.length ? { legacy_command: L.retireCommand(found) } : {}) };
135
+ const D = (await import(pathToFileURL(join(hooksDir(), 'lib', 'dead-hooks.mjs')).href));
136
+ const dead = D.deadUserHooks({ ...env, HOME: env.HOME ?? homedir() });
137
+ return { ...r, legacy_skills: found, ...(found.length ? { legacy_command: L.retireCommand(found) } : {}), dead_hooks: dead };
136
138
  }
137
139
  export function formatDoctor(r) {
138
140
  const yn = (b) => (b ? 'yes' : 'no');
@@ -148,6 +150,7 @@ export function formatDoctor(r) {
148
150
  `autopilot claude: ${yn(r.autopilot.claude)} codex: ${yn(r.autopilot.codex)}${r.autopilot.claude || r.autopilot.codex ? '' : ' (opt-in: bravos setup --autopilot)'}`,
149
151
  `cards claude: ${yn(r.cards.claude)} codex: ${yn(r.cards.codex)}${r.cards.claude || r.cards.codex ? (process.env.BRAVOS_THREAT_CARDS === 'off' ? ' (off for this run: BRAVOS_THREAT_CARDS=off)' : '') : ' (bravos setup adds it)'}`,
150
152
  `coach claude: ${yn(r.coach.claude)} codex: ${yn(r.coach.codex)}${r.coach.claude || r.coach.codex ? (process.env.BRAVOS_COACH === 'off' ? ' (off for this run: BRAVOS_COACH=off)' : '') : ' (bravos setup adds it)'}`,
153
+ ...(r.dead_hooks?.length ? [`✘ dead user-level hooks ${r.dead_hooks.map((d) => `${d.file} ${d.event}: ${d.script} is gone`).join('; ')} — every session shows "hook error". Remove them (a backup is kept): bravos doctor --fix-hooks`] : r.dead_hooks ? ['✔ no dead user-level hooks'] : []),
151
154
  ...(r.legacy_skills?.length ? [`✘ old Python bravos skills ${r.legacy_skills.map((f) => `${f.root}: ${f.names.join(', ')}`).join('; ')} — your agent may load them instead of this repository's. Move them aside (reversible): ${r.legacy_command}`] : r.legacy_skills ? ['✔ no old Python bravos skills at user level'] : []),
152
155
  ...(r.updates ? [updatesLine(r.updates)] : []),
153
156
  ...(r.theme ? [`colours ${r.theme.theme} (${r.theme.source})${r.theme.source.startsWith('default') ? ' — pick yours: BRAVOS_THEME=light or dark, or bravos setup' : ''}`] : []),
package/dist/guide.js CHANGED
@@ -157,6 +157,7 @@ export const GUIDE_TOPICS = [
157
157
  { name: 'bravos-recheck', body: ['After a fix: stale claims, retest-kit replay, no new exposure, what to test next.'] },
158
158
  { name: 'bravos-resync', body: ['A stale checkout or a left-behind branch: carries its annotation work onto the base with bravos resync, maps duplicate ids, re-reads every carried claim on changed code.'] },
159
159
  { name: 'bravos-sast', body: ['Licensed static analysis joined to guardlink claims and reachability; gates on findings new since the base.'] },
160
+ { name: 'bravos-threat-hunt', body: ['"Identify all the threats": maps the attack surface with the code graph, runs SAST, records every finding in the threat model with bravos-annotate, rebuilds the dashboard and reports from what was recorded, then recommends confirming the top three.'] },
160
161
  { name: 'bravos-campaign', body: ['A goal over many rounds: disjoint batches, one subagent each, a gate per batch, rests, a final before-and-after.'] },
161
162
  { name: 'bravos-schedule', body: ['Recurring upkeep with each harness\'s own mechanism; never live tests from a loop.'] },
162
163
  { name: 'bravos-cicd', body: ['Audits and writes the security workflows.'] },
package/dist/rules.js CHANGED
@@ -1,7 +1,7 @@
1
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
2
  import { execFileSync } from 'node:child_process';
3
- import { existsSync, readFileSync } from 'node:fs';
4
- import { join } from 'node:path';
3
+ import { existsSync, readFileSync, statSync } from 'node:fs';
4
+ import { isAbsolute, join, resolve, sep } from 'node:path';
5
5
  import { contextLib } from './context.js';
6
6
  import { parseJson, runner } from './watch.js';
7
7
  export const STATUS_ORDER = ['broken', 'retest-due', 'unguarded', 'guarded-untested', 'not-placed', 'holds'];
@@ -103,6 +103,61 @@ export function changedSinceTest(root, env, files, testedMs) {
103
103
  }
104
104
  return out;
105
105
  }
106
+ const SNIPPET_RADIUS = 3;
107
+ const MAX_DETAILED_SITES = 60;
108
+ // @comment -- "The code around one place, for the dashboard: up to three lines either side of it, read from the working tree. The path comes from GuardLink's model, so it is kept inside the repository (no absolute path, no '..', not under .git) and a file over 1 MB, or one that looks binary, gives nothing."
109
+ // @exposes #dashboard-rules to #rules-path-escape [low] cwe:CWE-22 -- "snippetAt() reads the file named by a GuardLink model location, which an annotation in the repository controls, and embeds its lines in the dashboard page"
110
+ // @mitigates #dashboard-rules against #rules-path-escape using #repo-relative-read -- "snippetAt() reads only repository-relative paths without '..' segments, outside .git, and at most 1 MB, so a crafted model location cannot make the dashboard embed another file"
111
+ export function snippetAt(root, file, line) {
112
+ if (!line || !file || isAbsolute(file) || file.split(/[\\/]/).some((p) => p === '..' || p === '.git'))
113
+ return null;
114
+ const abs = resolve(root, file);
115
+ if (!abs.startsWith(resolve(root) + sep))
116
+ return null;
117
+ try {
118
+ if (statSync(abs).size > 1024 * 1024)
119
+ return null;
120
+ const text = readFileSync(abs, 'utf8');
121
+ if (text.includes('\u0000'))
122
+ return null;
123
+ const lines = text.split('\n');
124
+ const from = Math.max(1, line - SNIPPET_RADIUS);
125
+ const to = Math.min(lines.length, line + SNIPPET_RADIUS);
126
+ const out = [];
127
+ for (let n = from; n <= to; n++)
128
+ out.push({ n, text: lines[n - 1].replace(/\t/g, ' ').slice(0, 240), hit: n === line });
129
+ return out.length ? out : null;
130
+ }
131
+ catch {
132
+ return null;
133
+ }
134
+ }
135
+ // @comment -- "The day text first appeared in a file's history (git log -S, oldest first), or null: when a claim or a rule was first committed. Read-only git, argv only, bounded."
136
+ export function firstSeen(root, env, file, needle) {
137
+ if (!needle.trim() || /[\0\n]/.test(needle) || file.startsWith('-'))
138
+ return null;
139
+ try {
140
+ const out = execFileSync('git', ['log', '--format=%cs', '--reverse', `-S${needle}`, '--', file], { cwd: root, env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 15000 }).trim();
141
+ const day = out.split('\n')[0]?.trim();
142
+ return /^\d{4}-\d{2}-\d{2}$/.test(day ?? '') ? day : null;
143
+ }
144
+ catch {
145
+ return null;
146
+ }
147
+ }
148
+ // @comment -- "The text to look for in history for a claim: the longest stretch of its description with no quote or backslash (a sidecar writes a quote in a description as \\\", so the plain text would not match), at most 60 characters and at least 12, else nothing."
149
+ export function claimNeedle(description) {
150
+ const best = description.split(/["\\]/).reduce((a, b) => (b.trim().length > a.trim().length ? b : a), '').trim();
151
+ return best.length >= 12 ? best.slice(0, 60) : '';
152
+ }
153
+ // @comment -- "Who reaches an asset according to the threat model's own @flows: each flow into it, and each flow into those sources, two hops at most and at most six links, so the dashboard can draw 'LAN host -> HTTP -> Appium' from what was annotated."
154
+ export function flowsInto(flows, asset) {
155
+ const id = (v) => String(v ?? '').replace(/^#/, '');
156
+ const into = (target) => flows.filter((f) => id(f.target) === target).map((f) => ({ from: id(f.source), to: target, via: f.mechanism ? String(f.mechanism).slice(0, 80) : null }));
157
+ const first = into(asset).slice(0, 3);
158
+ const second = first.flatMap((f) => into(f.from)).filter((f) => f.from !== asset).slice(0, 3);
159
+ return [...second, ...first];
160
+ }
106
161
  // @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
162
  export async function gatherRules(root, env, opts = {}) {
108
163
  const names = opts.names !== false;
@@ -131,6 +186,27 @@ export async function gatherRules(root, env, opts = {}) {
131
186
  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
187
  const exposures = arr(model?.exposures);
133
188
  const mitigations = arr(model?.mitigations);
189
+ const flows = arr(model?.flows);
190
+ let detailed = 0;
191
+ // A place's details, for the dashboard: what its claim says, the code around it, who reaches it, and when it
192
+ // appeared. Bounded, so a repository with many places still builds its page quickly.
193
+ const detailsFor = (x, verb, file, line, written, rec) => {
194
+ if (detailed >= MAX_DETAILED_SITES)
195
+ return undefined;
196
+ detailed++;
197
+ const description = String(x.description ?? '').slice(0, 1200);
198
+ const needle = claimNeedle(description);
199
+ return {
200
+ verb,
201
+ severity: typeof x.severity === 'string' ? x.severity : null,
202
+ description,
203
+ written,
204
+ snippet: snippetAt(root, file, line),
205
+ flows: verb === 'exposes' ? flowsInto(flows, bare(x.asset)) : [],
206
+ firstSeen: needle ? firstSeen(root, env, written.file, needle) : null,
207
+ outcome: rec?.outcome?.outcome ? String(rec.outcome.outcome) : null,
208
+ };
209
+ };
134
210
  const sitesFor = (threat) => {
135
211
  const mine = (x) => bare(x.threat) === threat;
136
212
  const sites = [];
@@ -149,13 +225,15 @@ export async function gatherRules(root, env, opts = {}) {
149
225
  const inFile = same.filter((r) => r.file === origin.file || r.file === file);
150
226
  const rec = exact.length === 1 ? exact[0] : exact.length === 0 && inFile.length === 1 ? inFile[0] : undefined;
151
227
  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 });
228
+ 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, ...(opts.details ? { details: detailsFor(e, 'exposes', file, line, origin, rec) } : {}) });
153
229
  }
154
230
  for (const m of mitigations.filter(mine)) {
155
231
  const file = String(m.location?.file ?? '?');
156
232
  if (exposed.has(file))
157
233
  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 });
234
+ const line = num(m.location?.line);
235
+ const origin = m.location?.origin_file ? { file: String(m.location.origin_file), line: num(m.location.origin_line) } : { file, line };
236
+ sites.push({ kind: 'grant', file, line, asset: bare(m.asset), control: bare(m.control), state: null, testedAt: null, evidence: null, ...(opts.details ? { details: detailsFor(m, 'mitigates', file, line, origin, undefined) } : {}) });
159
237
  }
160
238
  return sites;
161
239
  };
@@ -185,7 +263,7 @@ export async function gatherRules(root, env, opts = {}) {
185
263
  : !t
186
264
  ? { 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
265
  : 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 });
266
+ 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, ...(opts.details ? { addedAt: firstSeen(root, env, '.guardlink/intent.md', `${r.id}:`) } : {}) });
189
267
  }
190
268
  // A rule threat with no intent item behind it: written by an annotation pass, or left from an edited intent.
191
269
  for (const t of threats.filter((x) => /^inv-/i.test(x.id) && !claimed.has(x.id))) {
package/docs/GUIDE.md CHANGED
@@ -298,6 +298,10 @@ A stale checkout or a left-behind branch: carries its annotation work onto the b
298
298
 
299
299
  Licensed static analysis joined to guardlink claims and reachability; gates on findings new since the base.
300
300
 
301
+ ### bravos-threat-hunt
302
+
303
+ "Identify all the threats": maps the attack surface with the code graph, runs SAST, records every finding in the threat model with bravos-annotate, rebuilds the dashboard and reports from what was recorded, then recommends confirming the top three.
304
+
301
305
  ### bravos-campaign
302
306
 
303
307
  A goal over many rounds: disjoint batches, one subagent each, a gate per batch, rests, a final before-and-after.
package/docs/UPGRADING.md CHANGED
@@ -2,6 +2,36 @@
2
2
 
3
3
  After `npm install -g @bugb-technologies/bravos`, run **`bravos setup`** in a repository you work in: it brings this machine and that repository up to date. In repositories you work in with an agent you can skip even that: the agent runs it at the start of a session. From 1.12 on you do not have to watch for releases: Bravos tells you when a newer version is out, and after you install it the agent brings each repository up to date. The notes below say what else changes, newest first. (Before 1.9 the same was `bravos setup --tools -y` per machine and `bravos sync` per repository; both still work.)
4
4
 
5
+ ## 1.16.0
6
+
7
+ - **"Identify all the threats" uses everything Bravos has.** A new skill, `bravos-threat-hunt`, runs when you ask to identify, find or list threats or vulnerabilities, for a security review or audit, or to threat-model the codebase:
8
+ - **Maps the attack surface** with the code graph (Team).
9
+ - **Runs SAST** (Team, with bravos-cli).
10
+ - **Records every finding** in the threat model with a deep annotation pass. A repository of up to 200 files is covered in full, in parallel batches; a larger one gets the most exposed parts first, then an offer to continue.
11
+ - **Rebuilds the dashboard,** then **reports from what was recorded,** with where each finding came from.
12
+ - **Recommends confirming** the top three.
13
+ - **Free plan, or no graph or SAST:** it reads the code and says plainly what was unavailable.
14
+ - **It is reached two ways.** The front-door skill routes these requests to it, and the coach tells the agent "this is a threat hunt" every time you ask. Questions about what is already recorded ("what are the issues?") still get the quick answer and the dashboard.
15
+ - **Dead hooks are named.** If your user settings (`~/.claude/settings.json`, `~/.codex/hooks.json`) still run an old Bravos or Joseph hook whose script is gone, every session prints "hook error". Bravos now says so in the banner, the briefing and `bravos doctor`.
16
+ - **The fix:** run `bravos doctor --fix-hooks` yourself. It removes only those entries and keeps a backup; your other hooks are left alone.
17
+
18
+ ## 1.15.0
19
+
20
+ - **Click a design rule to see it in full.** In `bravos dashboard`, Threat model → Design rules is now a list beside a detail pane. The pane shows:
21
+ - **The rule:** its status, threat and severity, who confirmed it and its source.
22
+ - **Four counts:** places it can break, places with a control, places tested, and open places.
23
+ - **Why it has its status.**
24
+ - **Each place it can break,** which you open for detail:
25
+ - the `@exposes` or `@mitigates` written there;
26
+ - the code around it with the claim's line marked;
27
+ - who reaches it, from the threat model's `@flows`;
28
+ - its last test;
29
+ - buttons to copy the path or the test command.
30
+ - **History:** when the rule and each claim were first committed, and each test.
31
+ - **One next step,** with its command.
32
+ - **The page now carries code.** It includes a few lines around each rule's places (up to 60 places, three lines either side). Keep that in mind when you share a dashboard file.
33
+ - **Rebuild to see it:** run `bravos dashboard` again. `bravos rules --json` is unchanged.
34
+
5
35
  ## 1.14.1
6
36
 
7
37
  - **Design rules are under Threat model in `bravos dashboard`.** They sit in GuardLink's sidebar, right after Exposures, in the same look as the rest of the threat model.
@@ -5,6 +5,7 @@ import { homedir } from 'node:os';
5
5
  import { basename, delimiter, dirname, join } from 'node:path';
6
6
  import { contextGate, readContext } from './context.mjs';
7
7
  import { legacySkills, legacySkillsLine } from './legacy-skills.mjs';
8
+ import { deadHooksLine, deadUserHooks } from './dead-hooks.mjs';
8
9
  import { THEMES } from './palette.mjs';
9
10
  import { commitsLine, commonDirFrom, readHandoff, readPrefs } from './prefs.mjs';
10
11
  import { cliVersion, newer, readUpdate, updateLine } from './update-check.mjs';
@@ -290,6 +291,9 @@ export function buildBriefing(inputs) {
290
291
  // Skills the retired Python bravos left at user level: the agent must not follow them (hooks/lib/legacy-skills.mjs).
291
292
  const legacy = legacySkillsLine(i.legacy);
292
293
  if (legacy) tail.push(legacy);
294
+ // Bravos's or Joseph's own user-level hooks whose script is gone: they fail at every session start (hooks/lib/dead-hooks.mjs).
295
+ const deadHooks = deadHooksLine(i.deadHooks);
296
+ if (deadHooks) tail.push(deadHooks);
293
297
  if ((i.autopilot || i.prePr) && hooksLocked(i)) {
294
298
  // The repo registers the hooks for everyone; this person's copy answers nothing until they have a licence.
295
299
  const which = i.autopilot ? 'Autopilot (the end-of-turn check and the pre-PR gate)' : 'The pre-PR gate';
@@ -604,6 +608,7 @@ export async function collect(root, env, { deadlineMs = 20000, nextCount = 3 } =
604
608
  prePr: prePrRegistered(root),
605
609
  shadow: userSkillsShadow(root, env),
606
610
  legacy: legacySkills(env),
611
+ deadHooks: deadUserHooks({ ...env, HOME: env.HOME || homedir() }),
607
612
  autopilot: autopilotRegistered(root),
608
613
  proving: readProving(root),
609
614
  workspace,
@@ -880,6 +885,7 @@ function bannerWarnings(i, plan) {
880
885
  // One line for old Python skills at user level; bravos doctor prints the command that moves them aside.
881
886
  const old = arr(i.legacy).reduce((n, f) => n + arr(f?.names).length, 0);
882
887
  if (old > 0) lines.push(`! ${old} old Python bravos skill${old === 1 ? '' : 's'} in your user folder · bravos doctor`);
888
+ if (arr(i.deadHooks).length) lines.push(`! a user-level hook runs a script that is gone (${i.deadHooks[0].script}) · bravos doctor --fix-hooks`);
883
889
  if (i.update?.latest && i.cli && newer(i.update.latest, i.cli)) lines.push(`~ Update available: bravos ${i.update.latest} (you have ${i.cli}) · npm install -g @bugb-technologies/bravos`);
884
890
  return lines;
885
891
  }
@@ -70,6 +70,17 @@ export function startCoach(commonDir, sessionId, inputs) {
70
70
  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;
71
71
  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;
72
72
 
73
+ // A request to find the threats rather than read what is recorded: a finding verb with a threat word, or the names of the exercise.
74
+ const HUNT_VERB = /\b(?:identify|find|list|enumerate|scan|audit|review|hunt|discover|map|look for|check for|search for|detect|spot)\b/i;
75
+ const HUNT_NOUN = /\b(?:threats?|vulns?|vulnerab\w*|security (?:issues?|problems?|holes?|bugs?|flaws?|risks?)|risks?|attack surface|weakness\w*|exploits?)\b/i;
76
+ const HUNT_NAME = /\b(?:threat[- ]model(?:ling|ing)? (?:this|the|my|our)|security (?:review|audit|assessment)|pen ?test (?:this|the)|what (?:could|can) an attacker)\b/i;
77
+
78
+ // @comment -- "Whether the person asks Bravos to find the threats (identify, find, list, scan, audit or review them; a security review or audit; threat-model this) rather than to read what is already recorded. Pure."
79
+ export function asksForHunt(prompt) {
80
+ const p = String(prompt ?? '').slice(0, 4000);
81
+ return HUNT_NAME.test(p) || (HUNT_VERB.test(p) && HUNT_NOUN.test(p));
82
+ }
83
+
73
84
  // @comment -- "Whether the person's prompt asks about the security picture: issues, threats, vulnerabilities, findings, risks, exposures, the dashboard. Pure."
74
85
  export function asksAboutIssues(prompt) {
75
86
  const p = String(prompt ?? '').slice(0, 4000);
@@ -116,7 +127,12 @@ export function coachTurn({ record, prompt, dashboard = null, modelChangedAt = 0
116
127
  const topics = [];
117
128
  let opened = record.opened;
118
129
 
119
- if (asksAboutIssues(prompt)) {
130
+ if (asksForHunt(prompt)) {
131
+ // A hunt every time it is asked: each is a request, and the skill rebuilds the dashboard itself.
132
+ lines.push(`Bravos: this is a threat hunt. Follow ${k('bravos-threat-hunt')}: ask the code graph for the attack surface and run SAST first (where available), record each finding in the threat model with ${k('bravos-annotate')}, then rebuild the dashboard and report from what was recorded. Do not answer from reading the code alone.`);
133
+ topics.push('hunt');
134
+ opened = true;
135
+ } else if (asksAboutIssues(prompt)) {
120
136
  lines.push(opened
121
137
  ? '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.'
122
138
  : '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.');
@@ -0,0 +1,79 @@
1
+ // @comment -- "Finds Bravos's own user-level hooks that point at a script which no longer exists: an entry in ~/.claude/settings.json or ~/.codex/hooks.json that runs node on an .mjs under ~/.joseph, ~/.bravos or a .bravos/hooks folder that is gone (an old Joseph install, a removed user-level setup). Such an entry fails at every session start, in every project, as 'hook error'. Reading is file reads only; removing is fixDeadHooks(), which a person runs through bravos doctor --fix-hooks, never an agent. Dependency-free."
2
+ import { copyFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { isAbsolute, join } from 'node:path';
4
+
5
+ export const USER_HOOK_FILES = ['.claude/settings.json', '.codex/hooks.json'];
6
+ // node "<path>.mjs" or node <path>.mjs, with the path's home written as ~, $HOME or ${HOME}.
7
+ const NODE_SCRIPT = /\bnode\s+"?((?:~|\$\{?HOME\}?|\/)[^"\s]*\.mjs)"?/;
8
+ const OURS = /\/\.(?:joseph|bravos)\/|\/\.bravos\/hooks\//;
9
+
10
+ const expand = (p, home) => p.replace(/^~(?=\/)/, home).replace(/^\$\{?HOME\}?(?=\/)/, home);
11
+
12
+ // @comment -- "The dead entries: [{ file, event, command, script }] for each hook command in the user's settings files that runs one of Bravos's or Joseph's scripts and whose script is missing. A command that is not ours, or whose script exists, is never listed; an unreadable settings file lists nothing."
13
+ export function deadUserHooks(env = process.env) {
14
+ const home = env?.HOME;
15
+ if (!home) return [];
16
+ const out = [];
17
+ for (const rel of USER_HOOK_FILES) {
18
+ const file = join(home, rel);
19
+ let doc;
20
+ try {
21
+ doc = JSON.parse(readFileSync(file, 'utf8'));
22
+ } catch {
23
+ continue;
24
+ }
25
+ for (const [event, groups] of Object.entries(doc?.hooks ?? {})) {
26
+ if (!Array.isArray(groups)) continue;
27
+ for (const g of groups) {
28
+ for (const h of Array.isArray(g?.hooks) ? g.hooks : []) {
29
+ const command = typeof h?.command === 'string' ? h.command : '';
30
+ const m = NODE_SCRIPT.exec(command);
31
+ if (!m) continue;
32
+ const script = expand(m[1], home);
33
+ if (!isAbsolute(script) || !OURS.test(script) || existsSync(script)) continue;
34
+ out.push({ file: join('~', rel), event, command, script: script.replace(home, '~') });
35
+ }
36
+ }
37
+ }
38
+ }
39
+ return out;
40
+ }
41
+
42
+ // @comment -- "The briefing's and banner's line for dead user-level hooks: what fails and the one command that removes them, which the person runs. Null when there are none."
43
+ export function deadHooksLine(dead) {
44
+ if (!Array.isArray(dead) || !dead.length) return null;
45
+ const scripts = [...new Set(dead.map((d) => d.script))];
46
+ return `Dead hook: your user settings run ${scripts.length === 1 ? 'a script that no longer exists' : `${scripts.length} scripts that no longer exist`} (${scripts.join(', ')}), so every session in every project shows "hook error". Tell the person once: bravos doctor --fix-hooks, in their own terminal, removes ${dead.length === 1 ? 'it' : 'them'} and keeps a backup. Never edit their settings yourself.`;
47
+ }
48
+
49
+ // @comment -- "Removes the dead entries from the user's settings files, and nothing else: each file is backed up beside itself first (<file>.bravos-backup-<time>), a group left with no hooks is dropped, an event left with no groups is dropped, and every other key and hook is kept. Returns what was removed and where the backups are."
50
+ export function fixDeadHooks(env = process.env, now = new Date()) {
51
+ const home = env?.HOME;
52
+ const dead = deadUserHooks(env);
53
+ if (!home || !dead.length) return { removed: [], backups: [] };
54
+ const removed = [];
55
+ const backups = [];
56
+ for (const rel of USER_HOOK_FILES) {
57
+ const mine = dead.filter((d) => d.file === join('~', rel));
58
+ if (!mine.length) continue;
59
+ const file = join(home, rel);
60
+ const doc = JSON.parse(readFileSync(file, 'utf8'));
61
+ const gone = new Set(mine.map((d) => d.command));
62
+ for (const [event, groups] of Object.entries(doc.hooks ?? {})) {
63
+ if (!Array.isArray(groups)) continue;
64
+ const kept = groups
65
+ .map((g) => (Array.isArray(g?.hooks) ? { ...g, hooks: g.hooks.filter((h) => !(typeof h?.command === 'string' && gone.has(h.command))) } : g))
66
+ .filter((g) => !(Array.isArray(g?.hooks) && g.hooks.length === 0));
67
+ if (kept.length) doc.hooks[event] = kept;
68
+ else delete doc.hooks[event];
69
+ }
70
+ if (doc.hooks && !Object.keys(doc.hooks).length) delete doc.hooks;
71
+ const backup = `${file}.bravos-backup-${now.toISOString().replace(/[:.]/g, '-')}`;
72
+ copyFileSync(file, backup);
73
+ writeFileSync(file, JSON.stringify(doc, null, 2) + '\n');
74
+ backups.push(backup.replace(home, '~'));
75
+ removed.push(...mine);
76
+ }
77
+ return { removed, backups };
78
+ }
79
+
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bugb-technologies/bravos",
3
- "version": "1.14.1",
3
+ "version": "1.16.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",
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: bravos
3
- description: "Start here in any repo bravos is installed in: reads the security picture, explains the evidence loop in five lines, and routes to bravos-annotate, bravos-codegraph or bravos-ship. Use when asked where to start on security, what is open or confirmed, what to fix next, or whenever a task touches security-relevant code."
3
+ description: "Start here in any repo bravos is installed in: reads the security picture, explains the evidence loop in five lines, and routes to bravos-threat-hunt, bravos-annotate, bravos-codegraph or bravos-ship. Use when asked where to start on security, what is open or confirmed, what to fix next, or whenever a task touches security-relevant code."
4
4
  ---
5
5
  # Bravos: where this repo stands and what to do next
6
6
 
@@ -19,7 +19,8 @@ description: "Start here in any repo bravos is installed in: reads the security
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
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
- coverage, annotating, "threat-model this", a worklist in the briefing → bravos-annotate.
22
+ "identify / find / list all the threats or vulnerabilities", a security review or audit, "threat-model this codebase", "what could an attacker do here" → bravos-threat-hunt: the code graph and SAST first, every finding recorded in the threat model, then the dashboard and a report drawn from what was recorded. Never answer such a request from reading alone.
23
+ coverage, annotating, a worklist in the briefing → bravos-annotate.
23
24
  reachability, blast radius, "is this live", tracing a handler to sinks → bravos-codegraph.
24
25
  before a PR, push for review, or marking a draft ready → bravos-ship.
25
26
  pentest templates, a retest kit, making a claim testable → bravos-templatize.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: bravos-annotate
3
- description: "Keep the GuardLink threat model correct and growing, in this session: pick a budgeted slice of files (or go deep on request), follow guardlink's own playbook skill, write annotations that meet the evidence bar, run the lint gate until clean, and report the coverage delta. Use when asked to annotate, threat-model or cover code, after writing security-relevant code, when the briefing shows coverage or a worklist, and when asked to annotate deeply or run multiple rounds."
3
+ description: "Keep the GuardLink threat model correct and growing, in this session: pick a budgeted slice of files (or go deep on request), follow guardlink's own playbook skill, write annotations that meet the evidence bar, run the lint gate until clean, and report the coverage delta. Use when asked to annotate, threat-model or cover code, after writing security-relevant code, when the briefing shows coverage or a worklist, and when asked to annotate deeply or run multiple rounds. A request to identify or find all the threats is bravos-threat-hunt, which runs this skill after the code graph and SAST."
4
4
  ---
5
5
  # Bravos annotate: a budgeted slice of the threat model, gated
6
6
 
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: bravos-codegraph
3
- description: "Ask the repo's code graph (codegraph-mcp) one bounded question — routes, attack surface, sinks a symbol reaches, whether code is live, blast radius, annotation gaps in a change — instead of grepping. Use before editing security-relevant code, when judging a finding's reachability, when tracing a handler to its sinks, and when bravos-annotate or bravos-ship needs targets."
3
+ description: "Ask the repo's code graph (codegraph-mcp) one bounded question — routes, attack surface, sinks a symbol reaches, whether code is live, blast radius, annotation gaps in a change — instead of grepping. Use before editing security-relevant code, when judging a finding's reachability, when tracing a handler to its sinks, and when bravos-annotate or bravos-ship needs targets. A request to identify or find all the threats is bravos-threat-hunt, which asks this graph first."
4
4
  ---
5
5
  # Bravos codegraph: one question, one tool, one verdict
6
6
 
@@ -0,0 +1,51 @@
1
+ ---
2
+ name: bravos-threat-hunt
3
+ description: "Find every threat in the codebase with everything Bravos has, and record them: the code graph's attack surface and entry points first, then SAST, then each finding written into the GuardLink threat model as a claim (annotate), the dashboard rebuilt, and a report drawn from what was recorded, never from reading alone. Use when asked to identify, find, list or enumerate the threats or vulnerabilities, to do a security review or audit, to threat-model the codebase, to scan for security issues, or what an attacker could do here."
4
+ ---
5
+ # Bravos threat hunt: map, scan, record, report
6
+
7
+ ## When
8
+
9
+ - The person asks to identify, find, list or enumerate the threats, vulnerabilities, security issues, risks or weaknesses in the codebase (or a part of it).
10
+ - The person asks for a security review, a security audit, or to threat-model the codebase, or what an attacker could do here.
11
+ - The coach line says "this is a threat hunt".
12
+
13
+ A question about what is already recorded ("what is open?", "what are the issues?") is not a hunt: answer it from the briefing and the dashboard, as the bravos skill says.
14
+
15
+ ## Do
16
+
17
+ 1. Say in one line what you are about to do: map the attack surface, run the scanner, record each finding in the threat model, then report from it. Read the briefing's `Plan:`, `Code graph:`, `SAST:` and `Intent:` lines (without a briefing, `node .bravos/hooks/session-start.mjs --briefing`). With no `.guardlink/intent.md`, run bravos-context's draft first (it writes a draft and opens the intake page without waiting), so severities are judged against what the app is for.
18
+ 2. Map the attack surface. On the Team plan with the code graph current: ask `codegraph_attack_surface`, `codegraph_entry_points`, `codegraph_auth_boundary` and `codegraph_routes` (or `bravos graph <question> --json`; bravos-codegraph says how). With no graph built, build it first (`bravos graph build . --scip no-exec`, no tokens, a few minutes). On the Free plan, or when the graph is unavailable, read the route table, the IPC or command handlers and the auth code instead, and say "code graph unavailable; surface read from the code". Keep the list of entry points and the routes that answer unauthenticated callers: they are the leads for step 4.
19
+ 3. Scan. On the Team plan with bravos-cli present (`bravos doctor`): run `bravos sast run`, read its exit code as bravos-sast says (3 or 4 means incomplete, never clean), then `bravos sast candidates --json`. Keep the reachable findings, especially those not in the threat model yet. When SAST is unavailable (no licence, no bravos-cli, or no SAST report), say so in one line and carry on: the hunt does not wait for it.
20
+ 4. Record. Run bravos-annotate in deep mode with the `exploitable` playbook, taking as leads the entry points from step 2, the SAST findings from step 3, and the code that handles input from those entry points. Every finding that meets the evidence bar becomes a claim where the repository keeps annotations: `@exposes` with a severity and its reason, paired with `@mitigates` where a control exists or `@audit` where none does, the `@flows` the data takes, and a `@comment`. A doubt is an `@audit`, not a finding. Scope: the whole repository when `guardlink unannotated --json` lists 200 source files or fewer, split into batches of about 25 files run in parallel subagents (as bravos-campaign does, each told to follow bravos-annotate on its own files only); a larger repository gets the top of the attack surface (about 100 files, entry points and the code they reach first) in this session, then an offer of bravos-campaign for the rest.
21
+ 5. Gate it: `guardlink lint . --since <start> --json` until `summary.errors` is 0, then `guardlink validate .`. A violation on a line this session did not write is reported, not fixed.
22
+ 6. Rebuild the dashboard in the background (`bravos dashboard`, opened in the browser the first time this session, else `--no-open` with the path).
23
+ 7. Report from the threat model, not from memory: read `guardlink ci -f json` (or `guardlink parse .`) after recording, and give one table of the claims this hunt wrote, most severe first, with severity, the claim (asset and threat), `file:line`, where it came from (code graph, SAST or reading) and its state, which is untested until a test says otherwise. Then the coverage line (`<annotated> of <source> files annotated`, before → after) and `N recorded as claims`. List anything below the evidence bar separately, as the `@audit` questions it was recorded as.
24
+ 8. For committing Bravos's own files, follow the briefing's `Commits:` line; with no such line, ask once (commit now, or leave them for the person to review).
25
+ 9. End with one recommended next step: confirm the top three untested exposures now (bravos-prove on the recorded target, or bravos-env first to set one up, where the person types their own authorization), or the next files with bravos-campaign when the repository was larger than one hunt.
26
+
27
+ ## Never
28
+
29
+ - Report a threat that is not in the threat model after this hunt: every finding in the report is a claim this session recorded, or an `@audit` question it recorded.
30
+ - Answer a hunt from reading alone when the code graph or SAST is available, or call the code clean: the lint gate judges annotations, and an empty scan with exit 3 or 4 is incomplete.
31
+ - Write `@accepts`, `@entitles` or `@confirmed`: accepting a risk is a named person's decision, and confirming one needs a real test.
32
+ - Send any test traffic: a hunt reads and records; proving is bravos-prove, with the person's authorization.
33
+ - Commit or push without the person's go-ahead, or stash at all (another session can pop it).
34
+
35
+ ## Done when
36
+
37
+ - The code graph and SAST were used where available, and the report says plainly which were unavailable.
38
+ - Every finding in the report is a claim in the threat model (or an `@audit` question), `guardlink lint . --since <start>` reports 0 errors and `guardlink validate .` exits 0.
39
+ - The report table, the coverage line and the count of recorded claims were given, drawn from the model after recording.
40
+ - 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.
41
+ - You ended with one recommended next step.
42
+
43
+ ## What it leaves for the next skill
44
+
45
+ - The recorded claims, all untested, for bravos-templatize and bravos-prove; the files left over, for bravos-campaign.
46
+
47
+ ## Go deeper
48
+
49
+ - `{{SKILLS_ROOT}}/bravos-annotate/SKILL.md` — the evidence bar, placement and the lint gate.
50
+ - `{{SKILLS_ROOT}}/bravos-codegraph/SKILL.md` — asking the graph one bounded question at a time.
51
+ - `{{SKILLS_ROOT}}/bravos-sast/SKILL.md` — reading the scanner's exit code and candidates.
@@ -183,7 +183,7 @@ code { font: 12.5px var(--mono); background: var(--raised); border: 1px solid va
183
183
  // own style, so the rules sit beside the exposures they guard. Everything goes into the frame's srcdoc, where
184
184
  // the frame's own script builds it from inert JSON as text, never as markup. When GuardLink's page has no
185
185
  // sidebar to add to, the frame tells this page, which shows the rules on their own tab instead.
186
- // @comment -- "Runs inside GuardLink's sandboxed frame: adds a Design rules item after Exposures in its sidebar and a section after its exposures, built from inert JSON whose '<' is escaped, with every rule's text set as textContent (the only markup is a fixed icon). With no sidebar it places nothing and posts rules-not-placed to the dashboard, which then shows its fallback tab."
186
+ // @comment -- "Runs inside GuardLink's sandboxed frame: adds a Design rules item after Exposures in its sidebar and a section after its exposures: the rules as a list to pick from, and the picked rule in full (its places with their claim, the code around each, who reaches it per the model's @flows, its history and one next step). Built from inert JSON whose '<' is escaped, with every value set as textContent (the only markup is a fixed icon). With no sidebar it places nothing and posts rules-not-placed to the dashboard, which then shows its fallback tab."
187
187
  const frameRules = () => {
188
188
  var doc = JSON.parse(document.getElementById('bravos-rules-data').textContent);
189
189
  var nav = document.querySelector('.rail-nav');
@@ -237,34 +237,148 @@ code { font: 12.5px var(--mono); background: var(--raised); border: 1px solid va
237
237
  chips.append(d);
238
238
  }
239
239
  sec.append(chips);
240
- rules.forEach(function (r) {
240
+ // Two panes: the rules as a list to pick from, and the picked rule in full beside it.
241
+ var panes = mk('div', 'rpanes');
242
+ var listPane = mk('div', 'rlist');
243
+ var detail = mk('div', 'rdetail');
244
+ detail.setAttribute('aria-live', 'polite');
245
+ panes.append(listPane, detail);
246
+ sec.append(panes);
247
+ var SEV = { critical: 4, high: 3, medium: 2, low: 1 };
248
+ var where = function (s) { return String(s.file) + (s.line ? ':' + s.line : ''); };
249
+ var sevOf = function (s) { return (s.details && s.details.severity) || ''; };
250
+ // One recommended next step per rule, from its status and its worst place.
251
+ var nextStep = function (r) {
252
+ var sites = Array.isArray(r.sites) ? r.sites : [];
253
+ var worst = function (pred) { return sites.filter(pred).sort(function (a, b) { return (SEV[sevOf(b)] || 0) - (SEV[sevOf(a)] || 0); })[0]; };
254
+ if (r.status === 'broken') { var b = worst(function (s) { return s.state === 'broken'; }) || sites[0]; return { text: 'A test got through at ' + where(b) + '. Fix the code there, then replay its test to show the rule holds again.', cmd: '/bravos-recheck ' + b.file }; }
255
+ if (r.status === 'retest-due') { var t = worst(function (s) { return s.state === 'retest'; }) || sites[0]; return { text: 'The code at ' + where(t) + ' changed after the rule was last tested, so that result no longer describes it. Replay the test.', cmd: '/bravos-recheck ' + t.file }; }
256
+ if (r.status === 'unguarded') { var g = worst(function (s) { return s.kind === 'gap'; }) || sites[0]; return { text: 'Nothing enforces it at ' + where(g) + (sevOf(g) ? ' (' + sevOf(g) + ')' : '') + '. Add a check there and record it with @mitigates, or confirm first that it can be broken.', cmd: '/bravos-prove ' + where(g) }; }
257
+ if (r.status === 'guarded-untested') { var u = worst(function (s) { return s.kind === 'check' && s.state !== 'held'; }) || sites[0]; return { text: 'A check exists at ' + where(u) + ', but no test has tried it. Test it, so the rule can be shown to hold.', cmd: '/bravos-prove ' + where(u) }; }
258
+ if (r.status === 'not-placed') return { text: 'No code is tied to this rule yet. Annotate where it is enforced, so it has places to check.', cmd: '/bravos-annotate' };
259
+ return { text: 'It holds at every place it is enforced: each test there was refused. Nothing to do until the code changes.', cmd: '' };
260
+ };
261
+ // Copying from a sandboxed frame may be refused: then the command is selected for the reader to copy.
262
+ var copyButton = function (label, text, primary) {
263
+ var wrap = mk('span', 'rcopy');
264
+ var b = mk('button', 'rbtn' + (primary ? ' primary' : ''), label);
265
+ b.type = 'button';
266
+ var shown = mk('code', 'rcmd', text);
267
+ b.addEventListener('click', function () {
268
+ var select = function () {
269
+ try { var range = document.createRange(); range.selectNodeContents(shown); var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); b.textContent = 'Selected: copy it'; } catch (e) { /* nothing more to do */ }
270
+ };
271
+ try {
272
+ navigator.clipboard.writeText(text).then(function () { b.textContent = 'Copied'; }, select);
273
+ } catch (e) { select(); }
274
+ setTimeout(function () { b.textContent = label; }, 1800);
275
+ });
276
+ wrap.append(b, shown);
277
+ return wrap;
278
+ };
279
+ var cards = [];
280
+ var show = function (r, card) {
281
+ cards.forEach(function (c) { c.setAttribute('aria-pressed', String(c === card)); });
282
+ while (detail.firstChild) detail.removeChild(detail.firstChild);
241
283
  var status = LABEL[r.status] ? r.status : 'not-placed';
242
- var card = mk('article', 'rule ' + status);
243
284
  var top = mk('div', 'rule-head');
244
285
  top.append(mk('span', 'rpill ' + status, LABEL[status]), mk('span', 'rule-id', r.id || r.threat || 'rule'));
245
286
  if (r.decided === 'draft') top.append(mk('span', 'rpill', 'draft'));
246
287
  if (r.threat) top.append(mk('span', 'rule-threat', [r.threat, r.severity].filter(Boolean).join(' · ')));
247
- card.append(top, mk('p', 'rule-text', r.text || ''));
248
- if (r.why) card.append(mk('p', 'rule-why', r.why));
288
+ detail.append(top, mk('p', 'rd-title', r.text || ''));
249
289
  var meta = [];
250
- if (Array.isArray(r.sources) && r.sources.length) meta.push('from ' + r.sources.map(function (s) { return s.id + (s.section ? ' "' + s.section + '"' : ''); }).join('; '));
251
- meta.push(r.decided === 'draft' ? 'nobody has confirmed it yet' : r.decidedBy ? 'confirmed by ' + r.decidedBy : r.decided === 'confirmed' ? 'confirmed' : '');
252
- var m = meta.filter(Boolean).join(' · ');
253
- if (m) card.append(mk('p', 'rule-meta', m));
254
- if (Array.isArray(r.sites) && r.sites.length) {
255
- var sites = mk('ul', 'rule-sites');
256
- r.sites.forEach(function (s) {
257
- var li = mk('li');
258
- li.append(mk('span', 'site-kind', SITE[s.kind] || 'at'), mk('span', 'site-where', String(s.file) + (s.line ? ':' + s.line : '')));
259
- if (s.state) li.append(mk('span', 'site-state ' + s.state, STATE[s.state] || s.state));
260
- if (s.control) li.append(mk('span', 'site-extra', 'by #' + s.control));
261
- if (s.testedAt) li.append(mk('span', 'site-extra', String(s.testedAt).slice(0, 10)));
262
- sites.append(li);
263
- });
264
- card.append(sites);
290
+ meta.push(r.decided === 'draft' ? 'Nobody has confirmed it yet' : r.decidedBy ? 'Confirmed by ' + r.decidedBy : r.decided === 'confirmed' ? 'Confirmed' : 'No intent item stands behind it');
291
+ if (Array.isArray(r.sources) && r.sources.length) meta.push('from ' + r.sources.map(function (s) { return s.id + (s.section ? ' "' + s.section + '"' : '') + (s.title ? ' (' + s.title + ')' : ''); }).join('; '));
292
+ detail.append(mk('p', 'rule-meta', meta.join(' · ')));
293
+ var sites = Array.isArray(r.sites) ? r.sites : [];
294
+ var stats = mk('div', 'rstats');
295
+ [[sites.length, 'places it can break', false], [sites.filter(function (s) { return s.kind !== 'gap'; }).length, 'with a control', false], [sites.filter(function (s) { return s.testedAt; }).length, 'tested', false], [sites.filter(function (s) { return s.kind === 'gap' || s.state === 'broken'; }).length, 'open', true]].forEach(function (x) {
296
+ var box = mk('div', 'rstat' + (x[2] && x[0] ? ' bad' : ''));
297
+ box.append(mk('b', '', x[0]), mk('span', '', x[1]));
298
+ stats.append(box);
299
+ });
300
+ detail.append(stats);
301
+ detail.append(mk('h3', 'rh', 'Why it has this status'), mk('div', 'rwhy ' + status, r.why || ''));
302
+ detail.append(mk('h3', 'rh', 'Where it can break'));
303
+ if (!sites.length) detail.append(mk('p', 'rule-meta', 'Nothing in the code is tied to this rule yet.'));
304
+ sites.forEach(function (s, i) {
305
+ var d = s.details || null;
306
+ var box = mk('div', 'rsite');
307
+ var head = mk('button', 'rsite-head');
308
+ head.type = 'button';
309
+ var body = mk('div', 'rsite-body');
310
+ var open = i === 0;
311
+ body.hidden = !open;
312
+ head.setAttribute('aria-expanded', String(open));
313
+ head.append(mk('span', 'site-kind ' + s.kind, SITE[s.kind] || 'at'), mk('span', 'site-where', where(s)), mk('span', 'site-state ' + (s.state || ''), [sevOf(s), s.state ? STATE[s.state] || s.state : s.kind === 'grant' ? 'watched, not tested' : ''].filter(Boolean).join(' · ')));
314
+ head.addEventListener('click', function () { body.hidden = !body.hidden; head.setAttribute('aria-expanded', String(!body.hidden)); });
315
+ if (d) {
316
+ var claim = mk('div', 'rclaim');
317
+ claim.append(mk('b', '', '@' + d.verb + ' '), (d.verb === 'exposes' ? '#' + s.asset + ' to ' + r.threat : '#' + s.asset + ' against ' + r.threat + (s.control ? ' using #' + s.control : '')) + (d.severity ? ' [' + d.severity + ']' : ''));
318
+ if (d.description) claim.append(mk('span', 'rclaim-d', d.description));
319
+ body.append(claim);
320
+ if (d.written && d.written.file !== s.file) body.append(mk('p', 'rule-meta', 'Written in ' + d.written.file + (d.written.line ? ':' + d.written.line : '')));
321
+ if (Array.isArray(d.snippet) && d.snippet.length) {
322
+ var pre = mk('pre', 'rcode');
323
+ d.snippet.forEach(function (l) { var line = mk('span', l.hit ? 'hit' : ''); line.append(mk('i', '', l.n), l.text); pre.append(line); });
324
+ body.append(pre);
325
+ }
326
+ if (Array.isArray(d.flows) && d.flows.length) {
327
+ var reach = mk('div', 'rreach');
328
+ reach.append(mk('span', 'rule-meta', 'Who reaches it (the model’s @flows):'));
329
+ d.flows.forEach(function (f) {
330
+ var row = mk('span', 'rflow');
331
+ row.append(mk('span', 'rnode', '#' + f.from), mk('span', 'rarrow', '→' + (f.via ? ' ' + f.via + ' →' : '')), mk('span', 'rnode' + (f.to === s.asset ? ' sink' : ''), '#' + f.to));
332
+ reach.append(row);
333
+ });
334
+ body.append(reach);
335
+ }
336
+ if (s.testedAt) body.append(mk('p', 'rule-meta', 'Last test ' + String(s.testedAt).slice(0, 10) + (d.outcome ? ': ' + d.outcome : '') + (s.evidence ? ' · ' + s.evidence : '')));
337
+ }
338
+ var acts = mk('div', 'racts');
339
+ acts.append(copyButton('Copy path', where(s)));
340
+ if (s.kind !== 'grant') acts.append(copyButton('Copy test command', '/bravos-prove ' + where(s)));
341
+ body.append(acts);
342
+ box.append(head, body);
343
+ detail.append(box);
344
+ });
345
+ // History: when the rule and each claim appeared, and each test result, oldest first.
346
+ var events = [];
347
+ if (r.addedAt) events.push([r.addedAt, 'Rule added to .guardlink/intent.md' + (r.decidedBy ? '; confirmed by ' + r.decidedBy : r.decided === 'draft' ? ' as a draft' : '') + '.', '']);
348
+ sites.forEach(function (s) {
349
+ if (s.details && s.details.firstSeen) events.push([s.details.firstSeen, 'Claim recorded at ' + where(s) + (sevOf(s) ? ' (' + sevOf(s) + ')' : '') + '.', s.kind === 'gap' ? 'warn' : '']);
350
+ if (s.testedAt) events.push([String(s.testedAt).slice(0, 10), 'Tested at ' + where(s) + ': ' + ((s.details && s.details.outcome) || s.state || 'recorded') + '.', s.state === 'broken' ? 'bad' : s.state === 'held' ? 'ok' : '']);
351
+ });
352
+ events.sort(function (a, b) { return a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0; });
353
+ if (events.length) {
354
+ detail.append(mk('h3', 'rh', 'History'));
355
+ var tl = mk('ol', 'rtimeline');
356
+ events.forEach(function (e) { var li = mk('li', e[2]); li.append(mk('time', '', e[0]), e[1]); tl.append(li); });
357
+ detail.append(tl);
265
358
  }
266
- sec.append(card);
359
+ var n = nextStep(r);
360
+ detail.append(mk('h3', 'rh', 'Next step'));
361
+ var nb = mk('div', 'rnext');
362
+ nb.append(mk('p', '', n.text));
363
+ if (n.cmd) nb.append(copyButton('Copy command', n.cmd, true));
364
+ detail.append(nb);
365
+ };
366
+ rules.forEach(function (r, i) {
367
+ var status = LABEL[r.status] ? r.status : 'not-placed';
368
+ var card = mk('button', 'rule ' + status);
369
+ card.type = 'button';
370
+ var top = mk('span', 'rule-head');
371
+ top.append(mk('span', 'rpill ' + status, LABEL[status]), mk('span', 'rule-id', r.id || r.threat || 'rule'));
372
+ if (r.decided === 'draft') top.append(mk('span', 'rpill', 'draft'));
373
+ if (r.threat) top.append(mk('span', 'rule-threat', [r.threat, r.severity].filter(Boolean).join(' · ')));
374
+ var sites = Array.isArray(r.sites) ? r.sites : [];
375
+ card.append(top, mk('span', 'rule-text', r.text || ''), mk('span', 'rule-meta', sites.length ? sites.length + ' place' + (sites.length === 1 ? '' : 's') + ' · ' + sites.filter(function (s) { return s.testedAt; }).length + ' tested' : 'not tied to any code yet'));
376
+ card.addEventListener('click', function () { show(r, card); if (window.innerWidth < 1100) detail.scrollIntoView({ block: 'start' }); });
377
+ cards.push(card);
378
+ listPane.append(card);
267
379
  });
380
+ if (rules.length) show(rules[0], cards[0]);
381
+ else detail.append(mk('p', 'rule-meta', doc.note || ''));
268
382
  var exp = document.getElementById('sec-exposures');
269
383
  if (exp && exp.parentNode === main && exp.nextSibling) main.insertBefore(sec, exp.nextSibling);
270
384
  else main.append(sec);
@@ -274,20 +388,43 @@ code { font: 12.5px var(--mono); background: var(--raised); border: 1px solid va
274
388
  '#sec-rules .rchip{display:inline-flex;align-items:baseline;gap:5px;padding:2px 9px;border:1px solid var(--border);border-radius:999px;background:var(--raised);font-size:12px;color:var(--fg-muted)}',
275
389
  '#sec-rules .rchip b{font-weight:650;color:var(--fg);font-variant-numeric:tabular-nums}',
276
390
  '#sec-rules .rchip.broken{border-color:var(--sev-critical)}#sec-rules .rchip.retest-due,#sec-rules .rchip.unguarded{border-color:var(--review)}#sec-rules .rchip.holds{border-color:var(--resolved)}',
277
- '#sec-rules .rule{background:var(--panel);border:1px solid var(--border);border-left:3px solid var(--border-strong);border-radius:10px;padding:12px 14px;margin:0 0 10px;max-width:1100px}',
391
+ '#sec-rules .rpanes{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1.35fr);gap:16px;align-items:start}',
392
+ '@media (max-width:1100px){#sec-rules .rpanes{grid-template-columns:minmax(0,1fr)}}',
393
+ '#sec-rules .rule{display:block;width:100%;text-align:left;font:inherit;color:inherit;cursor:pointer;background:var(--panel);border:1px solid var(--border);border-left:3px solid var(--border-strong);border-radius:10px;padding:11px 13px;margin:0 0 8px}',
394
+ '#sec-rules .rule:hover{background:var(--hover)}#sec-rules .rule[aria-pressed="true"]{border-color:var(--accent);box-shadow:0 0 0 1px var(--accent)}',
395
+ '#sec-rules .rule:focus-visible,#sec-rules .rsite-head:focus-visible,#sec-rules .rbtn:focus-visible{outline:2px solid var(--accent);outline-offset:2px}',
278
396
  '#sec-rules .rule.broken{border-left-color:var(--sev-critical)}#sec-rules .rule.retest-due,#sec-rules .rule.unguarded{border-left-color:var(--review)}#sec-rules .rule.holds{border-left-color:var(--resolved)}',
279
397
  '#sec-rules .rule-head{display:flex;flex-wrap:wrap;align-items:center;gap:6px 10px}',
280
398
  '#sec-rules .rpill{font-size:10.5px;font-weight:650;text-transform:uppercase;letter-spacing:.05em;padding:2px 6px;border-radius:4px;border:1px solid var(--border-strong);color:var(--fg-muted);white-space:nowrap}',
281
399
  '#sec-rules .rpill.broken{color:var(--sev-critical);border-color:var(--sev-critical)}#sec-rules .rpill.retest-due,#sec-rules .rpill.unguarded{color:var(--review);border-color:var(--review)}#sec-rules .rpill.holds{color:var(--resolved);border-color:var(--resolved)}',
282
400
  '#sec-rules .rule-id{font-weight:650;font-family:var(--font-mono,ui-monospace,monospace);font-size:12.5px}',
283
401
  '#sec-rules .rule-threat{margin-left:auto;font-family:var(--font-mono,ui-monospace,monospace);font-size:11.5px;color:var(--fg-subtle)}',
284
- '#sec-rules .rule-text{margin:8px 0 4px;font-size:13.5px;color:var(--fg);line-height:1.45}',
285
- '#sec-rules .rule-why{margin:0 0 6px;font-size:12.5px;color:var(--fg-muted)}',
286
- '#sec-rules .rule-meta{margin:0;font-size:12px;color:var(--fg-subtle)}',
287
- '#sec-rules .rule-sites{list-style:none;margin:10px 0 0;padding:8px 0 0;border-top:1px solid var(--border-muted,var(--border));font-size:12px;display:grid;gap:3px}',
288
- '#sec-rules .rule-sites li{display:flex;flex-wrap:wrap;gap:4px 10px;color:var(--fg-muted)}',
289
- '#sec-rules .site-kind{min-width:92px;color:var(--fg-subtle)}#sec-rules .site-where{font-family:var(--font-mono,ui-monospace,monospace);color:var(--fg);overflow-wrap:anywhere}',
290
- '#sec-rules .site-state.broken{color:var(--sev-critical)}#sec-rules .site-state.retest{color:var(--review)}#sec-rules .site-state.held{color:var(--resolved)}',
402
+ '#sec-rules .rule-text{display:block;margin:7px 0 3px;font-size:13px;color:var(--fg);line-height:1.45}',
403
+ '#sec-rules .rule-meta{display:block;margin:0;font-size:12px;color:var(--fg-subtle)}',
404
+ '#sec-rules .rdetail{background:var(--panel);border:1px solid var(--border);border-radius:10px;padding:16px 18px;position:sticky;top:12px;max-height:calc(100vh - 24px);overflow:auto}',
405
+ '#sec-rules .rd-title{font-size:15px;line-height:1.45;margin:10px 0 6px;color:var(--fg)}',
406
+ '#sec-rules .rstats{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:8px;margin:14px 0 4px}',
407
+ '#sec-rules .rstat{background:var(--raised);border:1px solid var(--border);border-radius:8px;padding:8px 10px}#sec-rules .rstat b{display:block;font-size:19px;font-variant-numeric:tabular-nums}#sec-rules .rstat span{font-size:11px;color:var(--fg-subtle)}#sec-rules .rstat.bad b{color:var(--review)}',
408
+ '#sec-rules .rh{font-size:11px;text-transform:uppercase;letter-spacing:.08em;color:var(--fg-subtle);margin:18px 0 8px;font-weight:650}',
409
+ '#sec-rules .rwhy{border-left:3px solid var(--border-strong);padding:6px 10px;font-size:12.5px;color:var(--fg-muted);background:var(--raised);border-radius:6px}#sec-rules .rwhy.broken{border-left-color:var(--sev-critical)}#sec-rules .rwhy.unguarded,#sec-rules .rwhy.retest-due{border-left-color:var(--review)}#sec-rules .rwhy.holds{border-left-color:var(--resolved)}',
410
+ '#sec-rules .rsite{border:1px solid var(--border);border-radius:8px;margin:0 0 8px;overflow:hidden}',
411
+ '#sec-rules .rsite-head{display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:10px;align-items:center;width:100%;text-align:left;font:inherit;color:inherit;background:none;border:0;padding:8px 11px;cursor:pointer}#sec-rules .rsite-head:hover{background:var(--hover)}',
412
+ '#sec-rules .site-kind{font-size:10.5px;font-weight:650;text-transform:uppercase;letter-spacing:.04em;color:var(--review);white-space:nowrap}#sec-rules .site-kind.check,#sec-rules .site-kind.grant{color:var(--accent)}',
413
+ '#sec-rules .site-where{font-family:var(--font-mono,ui-monospace,monospace);font-size:12px;color:var(--fg);overflow-wrap:anywhere}',
414
+ '#sec-rules .site-state{font-size:11.5px;color:var(--fg-subtle);white-space:nowrap}#sec-rules .site-state.broken{color:var(--sev-critical)}#sec-rules .site-state.retest{color:var(--review)}#sec-rules .site-state.held{color:var(--resolved)}',
415
+ '#sec-rules .rsite-body{border-top:1px solid var(--border);padding:10px 11px 12px;display:grid;gap:8px}#sec-rules .rsite-body[hidden]{display:none}',
416
+ '#sec-rules .rclaim{font-family:var(--font-mono,ui-monospace,monospace);font-size:11.5px;line-height:1.55;color:var(--fg-muted);background:var(--sunken,var(--raised));border-radius:6px;padding:8px 10px;overflow-wrap:anywhere}#sec-rules .rclaim b{color:var(--sev-high)}#sec-rules .rclaim-d{display:block;margin-top:4px;color:var(--fg)}',
417
+ '#sec-rules .rcode{margin:0;font-family:var(--font-mono,ui-monospace,monospace);font-size:11.5px;line-height:1.6;background:var(--sunken,var(--raised));border:1px solid var(--border);border-radius:6px;padding:6px 0;overflow-x:auto}',
418
+ '#sec-rules .rcode span{display:block;padding:0 10px;white-space:pre}#sec-rules .rcode span.hit{background:color-mix(in srgb,var(--review) 18%,transparent);box-shadow:inset 3px 0 0 var(--review)}#sec-rules .rcode i{font-style:normal;color:var(--fg-subtle);display:inline-block;width:3.4em}',
419
+ '#sec-rules .rreach{display:grid;gap:4px}#sec-rules .rflow{display:flex;flex-wrap:wrap;align-items:center;gap:6px;font-family:var(--font-mono,ui-monospace,monospace);font-size:11.5px}',
420
+ '#sec-rules .rnode{border:1px solid var(--border-strong);border-radius:5px;padding:1px 7px;background:var(--raised)}#sec-rules .rnode.sink{border-color:var(--review);color:var(--review)}#sec-rules .rarrow{color:var(--fg-subtle)}',
421
+ '#sec-rules .racts{display:flex;flex-wrap:wrap;gap:8px}#sec-rules .rcopy{display:inline-flex;align-items:center;gap:8px;min-width:0}',
422
+ '#sec-rules .rbtn{font:inherit;font-size:12px;color:var(--fg);background:var(--panel);border:1px solid var(--border-strong);border-radius:6px;padding:3px 9px;cursor:pointer;white-space:nowrap}#sec-rules .rbtn:hover{background:var(--hover)}#sec-rules .rbtn.primary{background:var(--accent);border-color:var(--accent);color:var(--on-accent,#fff)}',
423
+ '#sec-rules .rcmd{font-family:var(--font-mono,ui-monospace,monospace);font-size:11.5px;color:var(--fg-muted);overflow-wrap:anywhere}',
424
+ '#sec-rules .rtimeline{list-style:none;margin:0;padding:0 0 0 14px;border-left:2px solid var(--border);display:grid;gap:7px}',
425
+ '#sec-rules .rtimeline li{position:relative;font-size:12px;color:var(--fg-muted)}#sec-rules .rtimeline li::before{content:"";position:absolute;left:-20px;top:5px;width:9px;height:9px;border-radius:50%;background:var(--panel);border:2px solid var(--border-strong)}',
426
+ '#sec-rules .rtimeline li.warn::before{border-color:var(--review)}#sec-rules .rtimeline li.bad::before{border-color:var(--sev-critical)}#sec-rules .rtimeline li.ok::before{border-color:var(--resolved)}#sec-rules .rtimeline time{font-family:var(--font-mono,ui-monospace,monospace);font-size:11px;color:var(--fg-subtle);margin-right:8px}',
427
+ '#sec-rules .rnext{border:1px solid var(--accent);border-radius:8px;padding:10px 12px;display:grid;gap:8px;font-size:12.5px;background:color-mix(in srgb,var(--accent) 8%,var(--panel))}#sec-rules .rnext p{margin:0;color:var(--fg)}',
291
428
  ].join('');
292
429
  const rulesForFrame = () => {
293
430
  // With no rules yet, the sidebar item still appears, saying how to get them.