@bugb-technologies/bravos 1.5.3 → 1.7.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/cli.js +81 -9
  2. package/dist/context.js +387 -0
  3. package/dist/dashboard.js +19 -5
  4. package/dist/guide.js +5 -2
  5. package/dist/help.js +19 -0
  6. package/dist/palette.js +4 -4
  7. package/dist/review-server.js +4 -4
  8. package/dist/review.js +103 -18
  9. package/dist/rules.js +218 -0
  10. package/dist/uninstall.js +6 -0
  11. package/dist/watch-frame.js +67 -42
  12. package/dist/watch.js +21 -7
  13. package/docs/GUIDE.md +20 -2
  14. package/docs/UPGRADING.md +28 -0
  15. package/hooks/lib/autopilot.mjs +29 -7
  16. package/hooks/lib/briefing.mjs +214 -171
  17. package/hooks/lib/context.mjs +522 -0
  18. package/hooks/lib/palette.mjs +4 -4
  19. package/hooks/lib/pre-pr.mjs +70 -0
  20. package/hooks/lib/setup.mjs +5 -2
  21. package/hooks/session-start.mjs +24 -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-context/SKILL.md +17 -10
  29. package/skills/bravos-context/intent.example.md +14 -1
  30. package/skills/bravos-recheck/SKILL.md +1 -1
  31. package/skills/bravos-ship/SKILL.md +2 -1
  32. package/skills/bravos-templatize/SKILL.md +1 -1
  33. package/templates/dashboard/dashboard.html +97 -0
  34. package/templates/review/review.html +368 -123
  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/guide.js CHANGED
@@ -45,7 +45,7 @@ export const GUIDE_TOPICS = [
45
45
  body: [
46
46
  'Run bravos next in a shell (free): it shows which of the nine steps are done here, in the order they build on each other — the code graph first (a machine step every later skill reads), then what the app intends, annotation coverage, SAST (which reads the annotations), how findings are proven and a test target, then the gates (autopilot, the pre-PR gate, CI, cheap to switch on any time) — what each unlocks, and the exact command for the next one. The banner shows the next step too, and every harness gives it to the agent, which offers a few starts the first time and suggests the next step at natural moments.',
47
47
  'Or just ask the agent "help me get started" (or run /bravos, $bravos in Codex): it gives a short tour fitted to this repo. BRAVOS_COACH=off stops the coaching; the Setup line stays.',
48
- 'Keep bravos watch running in a second terminal pane beside your agent (free, read-only, no model): the setup score, open and confirmed exposures, what to test next, stale claims and autopilot nudges, redrawn within seconds of a change. It also shows the hypothesis ledger, boundaries, the model\'s size, the code graph\'s call resolution and entry points, and the branch\'s commits. Keys: n copies the next command, r opens the intent review, d the dashboard (bravos dashboard), g asks the code graph, t shows test-next, i shows the recorded intent, u refreshes now, j and k scroll, q quits. Three columns from 150 wide, two from 110, one in an 80-column split.',
48
+ 'Keep bravos watch running in a second terminal pane beside your agent (free, read-only, no model): the setup score, open and confirmed exposures, what to test next, stale claims and autopilot nudges, redrawn within seconds of a change. It also shows the hypothesis ledger, boundaries, the model\'s size, the code graph\'s call resolution and entry points, and the branch\'s commits. Keys: n copies the next command, r opens the intent review, d the dashboard (bravos dashboard), g asks the code graph, t shows test-next, i shows the recorded intent, a opens the full text of retained activity, u refreshes now, j and k scroll, q quits. Three columns from 150 wide, two from 110, one in an 80-column split.',
49
49
  ],
50
50
  },
51
51
  {
@@ -113,8 +113,11 @@ 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
- { 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.'] },
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. The role-by-action matrix links each documented permission to its question. In local reviews, open a cited SRC document to read its verified text. The saved HTML can contain these documents. 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 prepares an artifact with the draft and its citations. Publish that artifact to share it.'] },
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.'] },
119
122
  { name: 'Cover the whole repo', skills: ['bravos-campaign'], body: ['Rounds of batches with subagents and rests, until the coverage goal or until you stop it.'] },
120
123
  { name: 'Is this exposure real?', skills: ['bravos-templatize', 'bravos-env', 'bravos-prove'], body: ['Template → authorized target → run. Only a reproduced run confirms; reading code never does.'] },
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
package/dist/palette.js CHANGED
@@ -5,20 +5,20 @@ import { join } from 'node:path';
5
5
  export const THEMES = {
6
6
  dark: {
7
7
  green: '#33d49d', blue: '#0360a2', light: '#f0f0f0', steel: '#55899e', red: '#ea1d1d',
8
- slate: '#3b6779', amber: '#f0b429', line: '#2b4f5c',
8
+ slate: '#3b6779', amber: '#f0b429', line: '#2b4f5c', warm: '#ff9f5b', cool: '#51b2a9',
9
9
  },
10
10
  light: {
11
11
  green: '#0f7a55', blue: '#0360a2', light: null, steel: '#3f6576', red: '#c41616',
12
- slate: '#4d6b78', amber: '#9a6400', line: '#7d98a3',
12
+ slate: '#4d6b78', amber: '#9a6400', line: '#7d98a3', warm: '#88441d', cool: '#006c67',
13
13
  },
14
14
  neutral: {
15
15
  green: '#1e9a6c', blue: '#2f7fc1', light: null, steel: '#4f8296', red: '#e02424',
16
- slate: '#5a7d8b', amber: '#b07a00', line: '#5a7d8b',
16
+ slate: '#5a7d8b', amber: '#b07a00', line: '#5a7d8b', warm: '#ad6131', cool: '#2c8980',
17
17
  },
18
18
  };
19
19
  export const FIXED = {
20
20
  green: '#33d49d', blue: '#0360a2', light: '#f0f0f0', steel: '#55899e', red: '#dc1f1f',
21
- slate: '#3b6779', amber: '#f0b429', line: '#2b4f5c', ink: '#0e1b21', deep: '#1f3943', white: '#ffffff',
21
+ slate: '#3b6779', amber: '#f0b429', line: '#2b4f5c', warm: '#ff9f5b', cool: '#51b2a9', ink: '#0e1b21', deep: '#1f3943', white: '#ffffff',
22
22
  };
23
23
  export const THEME_NAMES = ['dark', 'light', 'neutral'];
24
24
  export const isTheme = (t) => THEME_NAMES.includes(t);
@@ -1,7 +1,7 @@
1
1
  // @comment -- "Detached child that serves one review: argv root, kind, token, port. Started by bravos review so the command can return at once in any harness; it exits on Done or after 30 minutes idle."
2
- import { readDraft, renderReview, startReviewServer } from './review.js';
2
+ import { prepareReview, readDraft, renderReview, startReviewServer } from './review.js';
3
3
  const [root, kind, token, port] = process.argv.slice(2);
4
- const draft = readDraft(root, kind);
5
- const page = await renderReview(draft, { kind: 'serve', token });
6
- const { server } = await startReviewServer(root, draft, page, token, Number(port));
4
+ const review = await prepareReview(root, readDraft(root, kind));
5
+ const page = await renderReview(review, { kind: 'serve', token });
6
+ const { server } = await startReviewServer(root, review.draft, page, token, Number(port));
7
7
  server.on('close', () => process.exit(0));
package/dist/review.js CHANGED
@@ -1,9 +1,10 @@
1
+ import { execFileSync } from 'node:child_process';
1
2
  import { randomBytes } from 'node:crypto';
2
- import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
3
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
4
  import { createServer } from 'node:http';
4
5
  import { dirname, join } from 'node:path';
5
- import { pathToFileURL } from 'node:url';
6
- import { hooksDir, templatesDir } from './paths.js';
6
+ import { reviewSources } from './context.js';
7
+ import { templatesDir } from './paths.js';
7
8
  import { BravosError } from './types.js';
8
9
  // @comment -- "bravos review: the drafts an agent wrote (.guardlink/<kind>-draft.json) rendered as a bravos-branded page people answer in, a loopback-only server that saves each person's answers to .guardlink/<kind>-answers/<name>.json, and a plain-text summary of agreement and disagreement for the agent. Draft text comes from repo files and is untrusted: it travels as JSON and the page renders it with textContent."
9
10
  export const REVIEW_SCHEMA = 'bravos.review/v1';
@@ -32,9 +33,12 @@ export function validateDraft(value, kind) {
32
33
  throw bad(`kind must be '${kind}'`);
33
34
  if (!Array.isArray(value.questions) || value.questions.length === 0 || value.questions.length > 300)
34
35
  throw bad('needs 1 to 300 questions');
36
+ if (value.repo !== undefined && !str(value.repo))
37
+ throw bad('repo must be a string');
35
38
  if (value.perspective !== undefined && value.perspective !== 'researcher' && value.perspective !== 'owner')
36
39
  throw bad('perspective must be researcher or owner');
37
40
  const seen = new Set();
41
+ const cells = new Set();
38
42
  for (const [n, q] of value.questions.entries()) {
39
43
  if (!isObject(q))
40
44
  throw bad(`question ${n + 1} is not an object`);
@@ -69,6 +73,22 @@ export function validateDraft(value, kind) {
69
73
  throw bad(`${q.id}: an item needs its text`);
70
74
  if (q.sources !== undefined && !(Array.isArray(q.sources) && q.sources.every((s) => str(s, 400))))
71
75
  throw bad(`${q.id}: sources must be strings`);
76
+ if (q.permission !== undefined) {
77
+ const p = q.permission;
78
+ const label = (v) => typeof v === 'string' && v.trim().length > 0 && v.length <= 160;
79
+ if (!isObject(p) || !label(p.role) || !label(p.action) || (p.group !== undefined && !label(p.group)) || (p.effect !== 'allow' && p.effect !== 'deny')) {
80
+ throw bad(`${q.id}: permission needs a role, action and allow or deny effect`);
81
+ }
82
+ if (q.type !== 'item' || q.suggested !== 'agree' || !Array.isArray(q.sources) || !q.sources.some((s) => /\bSRC-[1-9][0-9]{0,4}\b/.test(s))) {
83
+ throw bad(`${q.id}: a permission must be an item with suggested agree and a stored source citation`);
84
+ }
85
+ if ((p.effect === 'deny' || q.confidence === 'low') && q.mustTouch !== true)
86
+ throw bad(`${q.id}: a denied or uncertain permission needs mustTouch`);
87
+ const key = JSON.stringify([p.group ?? (q.section || 'Permissions'), p.role, p.action]);
88
+ if (cells.has(key))
89
+ throw bad(`${q.id}: duplicate permission cell; combine its evidence in one question`);
90
+ cells.add(key);
91
+ }
72
92
  }
73
93
  return value;
74
94
  }
@@ -81,7 +101,7 @@ export function validateAnswers(value, draft) {
81
101
  if (!isObject(value.answers))
82
102
  throw new BravosError('answers must be an object keyed by question id');
83
103
  const ids = new Set(draft.questions.map((q) => q.id));
84
- const answers = {};
104
+ const answers = Object.create(null);
85
105
  for (const [id, a] of Object.entries(value.answers)) {
86
106
  if (!ids.has(id) || !isObject(a))
87
107
  continue;
@@ -125,9 +145,17 @@ export function readAllAnswers(root, draft) {
125
145
  const skipped = [];
126
146
  if (!existsSync(dir))
127
147
  return { files, skipped };
148
+ const base = join(realpathSync(root), answersDir(draft.kind));
149
+ if (realpathSync(dir) !== base || !lstatSync(dir).isDirectory())
150
+ return { files, skipped: [answersDir(draft.kind)] };
128
151
  for (const f of readdirSync(dir).filter((n) => n.endsWith('.json')).sort()) {
129
152
  try {
130
- files.push(validateAnswers(JSON.parse(readFileSync(join(dir, f), 'utf8')), draft));
153
+ const abs = join(base, f);
154
+ if (!lstatSync(abs).isFile() || realpathSync(abs) !== abs) {
155
+ skipped.push(f);
156
+ continue;
157
+ }
158
+ files.push(validateAnswers(JSON.parse(readFileSync(abs, 'utf8')), draft));
131
159
  }
132
160
  catch {
133
161
  skipped.push(f);
@@ -135,17 +163,76 @@ export function readAllAnswers(root, draft) {
135
163
  }
136
164
  return { files, skipped };
137
165
  }
138
- /** The brand art for the page header, from the hook's own constants (one source for banner and page). */
139
- async function brandArt() {
140
- const lib = await import(pathToFileURL(join(hooksDir(), 'lib', 'briefing.mjs')).href);
141
- return { mascot: lib.MASCOT, logo: lib.LOGO };
166
+ // @comment -- "Review pages may contain a team's design documents and answers may contain names or comments. Write only below real repository directories, then atomically replace the destination so a pre-existing link cannot redirect the write."
167
+ function writeReviewFile(root, rel, data) {
168
+ let dir = realpathSync(root);
169
+ for (const part of dirname(rel).split(/[\\/]/)) {
170
+ dir = join(dir, part);
171
+ try {
172
+ mkdirSync(dir, { mode: 0o700 });
173
+ }
174
+ catch (e) {
175
+ if (e.code !== 'EEXIST')
176
+ throw e;
177
+ }
178
+ if (!lstatSync(dir).isDirectory() || realpathSync(dir) !== dir)
179
+ throw new BravosError(`refusing to write through a link in ${rel}`);
180
+ }
181
+ const temp = join(dir, `.bravos-${randomBytes(16).toString('hex')}.tmp`);
182
+ try {
183
+ writeFileSync(temp, data, { flag: 'wx', mode: 0o600 });
184
+ renameSync(temp, join(root, rel));
185
+ }
186
+ finally {
187
+ rmSync(temp, { force: true });
188
+ }
189
+ }
190
+ // @comment -- "Make the repository label a link only when the draft names the same project as this checkout's GitHub origin. Reconstruct a public HTTPS path so credentials, local paths and URL parameters never enter the page."
191
+ function reviewRepoUrl(root, label) {
192
+ if (!label)
193
+ return;
194
+ try {
195
+ const origin = execFileSync('git', ['config', '--get', 'remote.origin.url'], {
196
+ cwd: root, encoding: 'utf8', timeout: 1500, stdio: ['ignore', 'pipe', 'ignore'],
197
+ }).trim();
198
+ const match = /^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([a-z0-9-]+)\/([a-z0-9_.-]+?)\/?$/i.exec(origin);
199
+ if (!match)
200
+ return;
201
+ const owner = match[1], repo = match[2].replace(/\.git$/i, '');
202
+ if (!repo || repo === '.' || repo === '..')
203
+ return;
204
+ if (![repo, `${owner}/${repo}`].some((name) => name.toLowerCase() === label.toLowerCase()))
205
+ return;
206
+ return `https://github.com/${owner}/${repo}`;
207
+ }
208
+ catch {
209
+ return;
210
+ }
211
+ }
212
+ const citedIds = (q) => (q.sources ?? []).flatMap((s) => s.match(/\bSRC-[1-9][0-9]{0,4}\b/g) ?? []);
213
+ // @comment -- "Take one local evidence snapshot for both the page and the server that accepts answers. A permission whose citations cannot all be verified needs an explicit decision, even when the draft suggested accepting it."
214
+ export async function prepareReview(root, draft) {
215
+ const sources = await reviewSources(root, new Set(draft.questions.flatMap(citedIds)));
216
+ const verified = new Set(sources.map((s) => s.id));
217
+ const questions = draft.questions.map((q) => {
218
+ if (!q.permission)
219
+ return q;
220
+ const missing = [...new Set(citedIds(q).filter((id) => !verified.has(id)))];
221
+ if (!missing.length)
222
+ return q;
223
+ return { ...q, mustTouch: true, confidence: 'low',
224
+ reason: [q.reason, `Check ${missing.join(', ')} before deciding. Its source text could not be included and verified for this review.`].filter(Boolean).join(' ') };
225
+ });
226
+ return { draft: { ...draft, questions }, sources, repoUrl: reviewRepoUrl(root, draft.repo) };
142
227
  }
143
- // @comment -- "Renders the self-contained review page: the template with the draft, mode and brand art embedded as JSON in a non-executing script tag, every '<' escaped so draft text cannot close the tag."
144
- export async function renderReview(draft, mode) {
228
+ // @comment -- "Embed the draft as inert JSON with escaped tag delimiters. Only a local review may add verified document bodies. Shared artifacts carry the citations and excerpts already present in the draft."
229
+ export async function renderReview(review, mode) {
145
230
  const template = readFileSync(join(templatesDir(), 'review', 'review.html'), 'utf8');
146
- const art = await brandArt();
231
+ const prepared = 'schema' in review ? { draft: review, sources: [], repoUrl: undefined } : review;
232
+ const { draft, repoUrl } = prepared;
233
+ const sources = mode.kind === 'artifact' ? [] : prepared.sources;
147
234
  const heading = draft.kind !== 'intent' ? `bravos asks: ${draft.kind}` : draft.perspective === 'owner' ? 'What does this product intend?' : `How should bravos judge ${draft.repo ?? 'this project'}?`;
148
- const data = JSON.stringify({ draft, mode, heading, ...art }).replace(/</g, '\\u003c').replace(/[\u2028\u2029]/g, (c) => `\\u${c.charCodeAt(0).toString(16)}`);
235
+ const data = JSON.stringify({ draft, mode, heading, sources, repoUrl }).replace(/</g, '\\u003c').replace(/[\u2028\u2029]/g, (c) => `\\u${c.charCodeAt(0).toString(16)}`);
149
236
  const page = template.replace('__BRAVOS_DATA__', () => data);
150
237
  // On claude.ai the runtime bridge supplies the shared database, so the page drops its own CSP there.
151
238
  return mode.kind === 'artifact' ? page.replace(/<meta http-equiv="Content-Security-Policy"[^>]*>\n?/, '') : page;
@@ -166,7 +253,7 @@ export function summarize(draft, files, skipped = []) {
166
253
  if (skipped.length)
167
254
  out.push(`skipped unreadable answer files: ${skipped.join(', ')}`);
168
255
  const groups = { DISAGREE: [], EDITED: [], DECIDED: [], 'NO ANSWER': [] };
169
- const accepted = {};
256
+ const accepted = Object.create(null);
170
257
  let acceptedCount = 0;
171
258
  for (const q of draft.questions) {
172
259
  const rows = files.map((f) => ({ by: f.by, a: f.answers[q.id] })).filter((r) => !!r.a);
@@ -243,8 +330,7 @@ export function startReviewServer(root, draft, page, token, port = 0) {
243
330
  if (missing.length)
244
331
  return send(400, `these decisions still need your call: ${missing.join(', ')}`);
245
332
  const rel = `${answersDir(draft.kind)}/${slug(a.by)}.json`;
246
- mkdirSync(dirname(join(root, rel)), { recursive: true });
247
- writeFileSync(join(root, rel), JSON.stringify(a, null, 2) + '\n');
333
+ writeReviewFile(root, rel, JSON.stringify(a, null, 2) + '\n');
248
334
  send(200, JSON.stringify({ saved: rel }), 'application/json');
249
335
  }
250
336
  catch (e) {
@@ -268,7 +354,6 @@ export const newToken = () => randomBytes(16).toString('hex');
268
354
  // @comment -- "Writes the rendered page for file mode (no server) to .bravos/review/<kind>.html and returns its path."
269
355
  export function writePage(root, kind, page) {
270
356
  const rel = `.bravos/review/${checkKind(kind)}.html`;
271
- mkdirSync(dirname(join(root, rel)), { recursive: true });
272
- writeFileSync(join(root, rel), page);
357
+ writeReviewFile(root, rel, page);
273
358
  return rel;
274
359
  }
package/dist/rules.js ADDED
@@ -0,0 +1,218 @@
1
+ // @comment -- "Design rules: the business-logic rules a team's design states (INV-n in .guardlink/intent.md, each a GuardLink threat #inv-…), joined to where the code enforces them and to what testing has shown. One row per rule with a status: broken, retest due, holds, unguarded, guarded but untested, or not placed. Read-only: it reads intent.md, the sources index, `guardlink parse .` and `guardlink hypothesis list --json .`, and runs no model. bravos rules prints it; bravos dashboard draws it as the Design rules view."
2
+ import { execFileSync } from 'node:child_process';
3
+ import { existsSync, readFileSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { contextLib } from './context.js';
6
+ import { parseJson, runner } from './watch.js';
7
+ export const STATUS_ORDER = ['broken', 'retest-due', 'unguarded', 'guarded-untested', 'not-placed', 'holds'];
8
+ export const STATUS_LABEL = {
9
+ broken: 'broken',
10
+ 'retest-due': 'retest due',
11
+ holds: 'holds',
12
+ unguarded: 'unguarded',
13
+ 'guarded-untested': 'guarded, untested',
14
+ 'not-placed': 'not placed',
15
+ };
16
+ const arr = (v) => (Array.isArray(v) ? v : []);
17
+ const bare = (id) => String(id ?? '').replace(/^#/, '');
18
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
19
+ // @comment -- "Reads the rules out of intent.md: every bullet that starts INV-n. What follows the last ' — ' is how it was decided (draft, or who agreed), a '(source: SRC-2 \"Report access\")' names the documents it came from, and the rest is the rule's text. Table rows and prose that mention a rule are not rules."
20
+ export function parseIntentRules(text) {
21
+ const out = [];
22
+ const seen = new Set();
23
+ for (const line of text.split('\n')) {
24
+ const m = /^\s*[-*]\s+(INV-\d+)\s*:\s*(.+)$/.exec(line);
25
+ if (!m || seen.has(m[1]))
26
+ continue;
27
+ seen.add(m[1]);
28
+ let rest = m[2].trim();
29
+ let attribution = '';
30
+ const dash = rest.lastIndexOf(' — ');
31
+ if (dash >= 0) {
32
+ attribution = rest.slice(dash + 3).trim();
33
+ rest = rest.slice(0, dash).trim();
34
+ }
35
+ const sources = [];
36
+ rest = rest
37
+ .replace(/\(source:\s*([^)]*)\)/gi, (_all, inner) => {
38
+ for (const s of inner.matchAll(/\b(SRC-[1-9][0-9]{0,4})\b(?:\s*"([^"]{0,120})")?/g))
39
+ sources.push({ id: s[1], section: s[2]?.trim() || null });
40
+ return '';
41
+ })
42
+ .replace(/\s+/g, ' ')
43
+ .trim();
44
+ const draft = /^draft\b/i.test(attribution) || attribution === '';
45
+ const by = /\b(?:accepted|edited|chosen|set|confirmed) by\s+(.+)$/i.exec(attribution)?.[1]?.trim() ?? null;
46
+ out.push({ id: m[1], text: rest.slice(0, 600), decided: draft ? 'draft' : 'confirmed', decidedBy: draft ? null : by, sources });
47
+ }
48
+ return out;
49
+ }
50
+ const SITE_WORD = { broken: 'a test got through', retest: 'the code changed since it was tested', held: 'a test was refused', untested: 'not tested' };
51
+ // @comment -- "A site's tested state from its ledger record: a confirmed outcome is broken; a record waiting for a retest, or one whose code changed since the test, is retest; a refuted outcome that still stands is held (the test tried and was refused); anything else is untested."
52
+ function siteState(rec) {
53
+ if (!rec)
54
+ return 'untested';
55
+ const state = String(rec.state ?? '');
56
+ if (state === 'confirmed')
57
+ return 'broken';
58
+ if (state === 'retest' || rec.expired === true)
59
+ return 'retest';
60
+ if (state === 'refuted')
61
+ return 'held';
62
+ return 'untested';
63
+ }
64
+ // @comment -- "A rule's status from its sites. Broken wins, then retest due. It holds only when every place it can break has been tested and refused. A place with no control at all makes it unguarded; checks that exist but have not all been tested make it guarded, untested; a rule tied to no code is not placed. The sentence beside the status says which of these it is and what would change it."
65
+ export function ruleStatus(sites) {
66
+ const testable = sites.filter((s) => s.kind !== 'grant');
67
+ const at = (s) => `${s.file}${s.line ? `:${s.line}` : ''}`;
68
+ const broken = testable.filter((s) => s.state === 'broken');
69
+ if (broken.length)
70
+ return { status: 'broken', why: `A test got through at ${broken.map(at).join(', ')}: the rule does not hold there.` };
71
+ const retest = testable.filter((s) => s.state === 'retest');
72
+ if (retest.length)
73
+ return { status: 'retest-due', why: `The code at ${retest.map(at).join(', ')} changed since it was last tested: replay its test.` };
74
+ const gaps = testable.filter((s) => s.kind === 'gap');
75
+ if (gaps.length)
76
+ return { status: 'unguarded', why: `Nothing enforces it at ${gaps.map(at).join(', ')}: an exposure is recorded there with no control.` };
77
+ if (testable.length && testable.every((s) => s.state === 'held'))
78
+ return { status: 'holds', why: `Tested at ${testable.length === 1 ? 'the one place' : `all ${testable.length} places`} it is enforced, and refused each time.` };
79
+ if (testable.length) {
80
+ const held = testable.filter((s) => s.state === 'held').length;
81
+ return { status: 'guarded-untested', why: held ? `Tested at ${held} of ${testable.length} places it is enforced; the others have a check that no test has tried.` : 'A check is annotated where it is enforced, but no test has tried it yet.' };
82
+ }
83
+ if (sites.length)
84
+ return { status: 'guarded-untested', why: 'It is recorded only as a control, which cannot be tested: the next annotation pass writes where it could break beside the check.' };
85
+ return { status: 'not-placed', why: 'No code is tied to this rule yet: the next annotation pass looks for where it is enforced.' };
86
+ }
87
+ // @comment -- "The files among a rule's places that changed after the rule was last tested: a later commit touches them, or they have uncommitted edits. GuardLink's test record lapses only when the code under the tested claim changes; a permission flipped in a role table, in another file, lapses nothing there, so the time of the change is what tells. Read-only git (argv, no shell); outside a repository nothing is reported."
88
+ export function changedSinceTest(root, env, files, testedMs) {
89
+ const git = (args) => {
90
+ try {
91
+ return execFileSync('git', args, { cwd: root, env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 10000 }).trim();
92
+ }
93
+ catch {
94
+ return null;
95
+ }
96
+ };
97
+ const out = [];
98
+ for (const file of [...new Set(files)].sort()) {
99
+ const committed = Number(git(['log', '-1', '--format=%ct', '--', file]));
100
+ const dirty = git(['status', '--porcelain', '--', file]);
101
+ if ((Number.isFinite(committed) && committed > 0 && committed * 1000 > testedMs) || (dirty !== null && dirty !== ''))
102
+ out.push(file);
103
+ }
104
+ return out;
105
+ }
106
+ // @comment -- "Builds the rules document. Each INV item in intent.md is matched to its threat by the threat's intent:INV-n reference, or for older repositories by a description that starts 'INV-n:'. A site is every @exposes of that threat (a check when a @mitigates covers the same asset and threat, a gap when none does) and every @mitigates in a file that has no @exposes of it (a grant). Each exposure's tested state comes from its one ledger record, matched by asset, threat and location. A threat named #inv-… that no intent item claims is listed too, so nothing an agent added stays out of sight."
107
+ export async function gatherRules(root, env, opts = {}) {
108
+ const names = opts.names !== false;
109
+ const intentFile = join(root, '.guardlink', 'intent.md');
110
+ const intentRules = existsSync(intentFile) ? parseIntentRules(readFileSync(intentFile, 'utf8')) : [];
111
+ const titles = new Map();
112
+ try {
113
+ const L = await contextLib();
114
+ const index = join(root, L.INDEX_PATH);
115
+ if (existsSync(index))
116
+ for (const s of L.parseIndex(readFileSync(index, 'utf8')).sources)
117
+ titles.set(s.id, { title: s.title, kind: s.kind });
118
+ }
119
+ catch {
120
+ /* sources are named by id alone */
121
+ }
122
+ const source = (s) => ({ id: s.id, section: s.section, title: titles.get(s.id)?.title ?? null, kind: titles.get(s.id)?.kind ?? null });
123
+ const run = await runner();
124
+ const [parsed, listed] = await Promise.all([
125
+ run('guardlink', ['parse', '.'], { cwd: root, env, timeoutMs: 120000 }),
126
+ run('guardlink', ['hypothesis', 'list', '--json', '.'], { cwd: root, env, timeoutMs: 60000 }),
127
+ ]);
128
+ const model = parsed.missing ? null : parseJson(parsed);
129
+ const records = arr(parseJson(listed)?.records);
130
+ const threats = arr(model?.threats).map((t) => ({ id: bare(t.id), severity: t.severity ?? null, refs: arr(t.external_refs).map(String), description: String(t.description ?? ''), name: String(t.name ?? t.canonical_name ?? '') }));
131
+ const threatFor = (inv) => threats.find((t) => t.refs.some((r) => r.toLowerCase() === `intent:${inv.toLowerCase()}`)) ?? threats.find((t) => new RegExp(`^${inv}\\b\\s*:`, 'i').test(t.description.trim())) ?? null;
132
+ const exposures = arr(model?.exposures);
133
+ const mitigations = arr(model?.mitigations);
134
+ const sitesFor = (threat) => {
135
+ const mine = (x) => bare(x.threat) === threat;
136
+ const sites = [];
137
+ const exposed = new Set();
138
+ for (const e of exposures.filter(mine)) {
139
+ const file = String(e.location?.file ?? '?');
140
+ const line = num(e.location?.line);
141
+ const asset = bare(e.asset);
142
+ exposed.add(file);
143
+ const control = mitigations.find((m) => mine(m) && bare(m.asset) === asset);
144
+ const origin = e.location?.origin_file ? { file: String(e.location.origin_file), line: num(e.location.origin_line) } : { file, line };
145
+ // The exposure's one ledger record: at its exact location (a sidecar's own line, or the code line), else the
146
+ // only record for this asset and threat in the file. Two candidates are no match: a wrong one would be a wrong verdict.
147
+ const same = records.filter((r) => bare(r.threat) === threat && bare(r.asset) === asset);
148
+ const exact = same.filter((r) => (r.file === origin.file && r.line === origin.line) || (r.file === file && r.line === line));
149
+ const inFile = same.filter((r) => r.file === origin.file || r.file === file);
150
+ const rec = exact.length === 1 ? exact[0] : exact.length === 0 && inFile.length === 1 ? inFile[0] : undefined;
151
+ const state = siteState(rec);
152
+ sites.push({ kind: control ? 'check' : 'gap', file, line, asset, control: control ? bare(control.control) : null, state, testedAt: rec?.outcome?.at ?? null, evidence: rec?.outcome?.evidence ? String(rec.outcome.evidence).slice(0, 300) : null });
153
+ }
154
+ for (const m of mitigations.filter(mine)) {
155
+ const file = String(m.location?.file ?? '?');
156
+ if (exposed.has(file))
157
+ continue;
158
+ sites.push({ kind: 'grant', file, line: num(m.location?.line), asset: bare(m.asset), control: bare(m.control), state: null, testedAt: null, evidence: null });
159
+ }
160
+ return sites;
161
+ };
162
+ // A rule that reads as holding is checked once more against git: a file it is enforced or granted in that changed
163
+ // after its oldest refused test makes the result stale, whatever the ledger still says.
164
+ const afterChanges = (verdict, sites) => {
165
+ if (verdict.status !== 'holds')
166
+ return verdict;
167
+ const tested = sites.map((s) => Date.parse(s.testedAt ?? '')).filter(Number.isFinite);
168
+ if (!tested.length)
169
+ return verdict;
170
+ const oldest = Math.min(...tested);
171
+ const moved = changedSinceTest(root, env, sites.map((s) => s.file), oldest);
172
+ if (!moved.length)
173
+ return verdict;
174
+ return { status: 'retest-due', why: `${moved.join(', ')} changed after the rule was last tested (${new Date(oldest).toISOString().slice(0, 10)}): the refused test no longer describes this code. Replay it.` };
175
+ };
176
+ const rules = [];
177
+ const claimed = new Set();
178
+ for (const r of intentRules) {
179
+ const t = threatFor(r.id);
180
+ if (t)
181
+ claimed.add(t.id);
182
+ const sites = t ? sitesFor(t.id) : [];
183
+ const verdict = !model
184
+ ? { status: 'not-placed', why: 'GuardLink is not installed here, so where this rule is enforced is not known.' }
185
+ : !t
186
+ ? { status: 'not-placed', why: 'No threat in the model stands for this rule yet: the context step adds one (#inv-…) with the reference intent:' + r.id + '.' }
187
+ : afterChanges(ruleStatus(sites), sites);
188
+ rules.push({ id: r.id, text: r.text, decided: r.decided, decidedBy: names ? r.decidedBy : null, sources: r.sources.map(source), threat: t ? `#${t.id}` : null, severity: t?.severity ?? null, refs: t?.refs ?? [], ...verdict, sites });
189
+ }
190
+ // A rule threat with no intent item behind it: written by an annotation pass, or left from an edited intent.
191
+ for (const t of threats.filter((x) => /^inv-/i.test(x.id) && !claimed.has(x.id))) {
192
+ const sites = sitesFor(t.id);
193
+ const verdict = afterChanges(ruleStatus(sites), sites);
194
+ rules.push({ id: null, text: t.description || t.name || `#${t.id}`, decided: null, decidedBy: null, sources: t.refs.filter((r) => /^design:SRC-/i.test(r)).map((r) => source({ id: r.slice(7), section: null })), threat: `#${t.id}`, severity: t.severity, refs: t.refs, status: verdict.status, why: `${verdict.why} No item in intent.md stands behind this threat: confirm it there, or remove it.`, sites });
195
+ }
196
+ rules.sort((a, b) => STATUS_ORDER.indexOf(a.status) - STATUS_ORDER.indexOf(b.status) || String(a.id ?? '~').localeCompare(String(b.id ?? '~'), undefined, { numeric: true }));
197
+ const summary = { total: rules.length, draft: rules.filter((r) => r.decided === 'draft').length, broken: 0, 'retest-due': 0, holds: 0, unguarded: 0, 'guarded-untested': 0, 'not-placed': 0 };
198
+ for (const r of rules)
199
+ summary[r.status] += 1;
200
+ if (!rules.length) {
201
+ return { schema: 'bravos.rules/v1', state: 'none', note: 'No design rules are recorded yet. Run /bravos-context: it asks for your design documents and writes the rules they state (who may do what, what must never happen) into .guardlink/intent.md.', summary, rules };
202
+ }
203
+ if (!model)
204
+ return { schema: 'bravos.rules/v1', state: 'no-guardlink', note: 'GuardLink is not installed on this machine, so the rules are listed without where the code enforces them: run bravos setup --tools -y, then bravos dashboard again.', summary, rules };
205
+ const said = STATUS_ORDER.filter((s) => summary[s]).map((s) => `${summary[s]} ${STATUS_LABEL[s]}`);
206
+ return { schema: 'bravos.rules/v1', state: 'present', note: `${rules.length} design rule${rules.length === 1 ? '' : 's'} from the intent: ${said.join(', ')}${summary.draft ? `; ${summary.draft} still a draft nobody has confirmed` : ''}.`, summary, rules };
207
+ }
208
+ // @comment -- "bravos rules as lines: the note, then one line per rule with its status, id, text, sources and the places it is enforced."
209
+ export function formatRules(doc) {
210
+ const lines = [doc.note];
211
+ for (const r of doc.rules) {
212
+ const src = r.sources.length ? ` (${r.sources.map((s) => s.id).join(', ')})` : '';
213
+ lines.push(`${STATUS_LABEL[r.status].padEnd(18)} ${(r.id ?? r.threat ?? '?').padEnd(7)} ${r.text}${r.decided === 'draft' ? ' [draft]' : ''}${src}`);
214
+ for (const s of r.sites)
215
+ lines.push(`${' '.repeat(19)}${s.kind === 'grant' ? 'granted in' : s.kind === 'gap' ? 'no control at' : 'enforced at'} ${s.file}${s.line ? `:${s.line}` : ''}${s.state ? ` — ${SITE_WORD[s.state]}` : ''}`);
216
+ }
217
+ return lines;
218
+ }
package/dist/uninstall.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { existsSync, lstatSync, readFileSync, readdirSync, readlinkSync, rmdirSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
2
2
  import { dirname, join } from 'node:path';
3
3
  import { LOCK_PATH, readLock, sha256 } from './lock.js';
4
+ import { removePrePush } from './context.js';
4
5
  import { BravosError } from './types.js';
5
6
  const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
6
7
  // Any command bravos registers: the per-repo relative forms and the user-level absolute one.
@@ -176,6 +177,11 @@ export function uninstall(root, opts = {}) {
176
177
  const leftover = ['reports', 'sast', 'watch', 'workspace', 'review'].filter((d) => existsSync(join(root, '.bravos', d)));
177
178
  if (leftover.length)
178
179
  report.notes.push(`.bravos/{${leftover.join(',')}} kept: reports, runs and snapshots are yours, not the install's`);
180
+ // The design documents are the team's, committed and cited by the threat model: an uninstall never touches them.
181
+ if (existsSync(join(root, '.bravos', 'context')))
182
+ report.notes.push('.bravos/context kept: the design documents and their index are yours, and the intent cites them');
183
+ if (!opts.home && removePrePush(root, process.env, dryRun))
184
+ report.notes.push('the pre-push check for design documents was removed from this clone\'s git hooks');
179
185
  try {
180
186
  if (!opts.home && lstatSync(join(root, '.agents', 'skills')).isSymbolicLink()) {
181
187
  report.notes.push('.agents/skills is still a link to .claude/skills (from --link-skills); remove it if no other agent needs it');