@bugb-technologies/bravos 1.24.0 → 1.26.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 (51) hide show
  1. package/dist/bin.js +12 -0
  2. package/dist/cli.js +222 -16
  3. package/dist/context.js +4 -4
  4. package/dist/cursor.js +24 -5
  5. package/dist/dashboard-sast.js +113 -0
  6. package/dist/dashboard.js +22 -11
  7. package/dist/doctor.js +29 -2
  8. package/dist/graphbin.js +2 -2
  9. package/dist/guide.js +4 -2
  10. package/dist/hook-launcher.js +92 -0
  11. package/dist/hooks.js +56 -3
  12. package/dist/plugin-release.js +38 -12
  13. package/dist/prefs.js +13 -3
  14. package/dist/principles.js +1 -1
  15. package/dist/records-conflicts.js +128 -0
  16. package/dist/records-drafts.js +106 -0
  17. package/dist/records-ledger.js +103 -0
  18. package/dist/records-team.js +398 -0
  19. package/dist/records.js +158 -0
  20. package/dist/review-server.js +3 -1
  21. package/dist/review.js +16 -1
  22. package/dist/rules.js +97 -4
  23. package/dist/setup.js +6 -6
  24. package/dist/uninstall.js +1 -1
  25. package/dist/upkeep.js +3 -0
  26. package/docs/GUIDE.md +11 -1
  27. package/docs/UPGRADING.md +56 -0
  28. package/hooks/cards.mjs +63 -14
  29. package/hooks/coach.mjs +3 -1
  30. package/hooks/lib/agent-io.mjs +118 -0
  31. package/hooks/lib/briefing.mjs +94 -3
  32. package/hooks/lib/cards.mjs +8 -1
  33. package/hooks/lib/draft-check.mjs +104 -0
  34. package/hooks/lib/drafts.mjs +121 -0
  35. package/hooks/lib/ledger.mjs +270 -0
  36. package/hooks/lib/pre-pr.mjs +74 -0
  37. package/hooks/lib/prefs.mjs +7 -3
  38. package/hooks/lib/record-guard.mjs +272 -0
  39. package/hooks/lib/records.mjs +581 -0
  40. package/hooks/lib/replay.mjs +2 -1
  41. package/hooks/lib/sast.mjs +3 -1
  42. package/hooks/record-guard.mjs +62 -0
  43. package/hooks/session-start.mjs +4 -3
  44. package/package.json +2 -2
  45. package/skills/bravos/SKILL.md +1 -0
  46. package/skills/bravos-records/SKILL.md +57 -0
  47. package/templates/dashboard/dashboard.html +198 -1
  48. package/templates/omp/bravos.js +85 -1
  49. package/templates/opencode/bravos.js +84 -1
  50. package/templates/plugin/workspace-hook.mjs +37 -0
  51. package/templates/workflows/bravos-pr-gate.yml +23 -0
@@ -5,6 +5,9 @@ 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 { adoptedPrinciples } from './principles.mjs';
8
+ import { draftQueue } from './drafts.mjs';
9
+ import { ledgerBrief } from './ledger.mjs';
10
+ import { allRecords } from './records.mjs';
8
11
  import { legacySkills, legacySkillsLine } from './legacy-skills.mjs';
9
12
  import { deadHooksLine, deadUserHooks } from './dead-hooks.mjs';
10
13
  import { THEMES } from './palette.mjs';
@@ -158,6 +161,53 @@ export function principlesLine(p) {
158
161
  return `Security design principles: ${p.count} adopted in .guardlink/principles.md${enforced}${scoped}. Read the file before changing code here and follow each one; when a change would break one, say so and ask the person first. Never edit the file, its adoptions or its exceptions.`;
159
162
  }
160
163
 
164
+ // @comment -- "The security decision records as the briefing needs them: the adopted ones by id and module, and how many are drafts or were changed after adoption (those bind nobody). Only records that parse count, and a record's own text never reaches the briefing: the module name is cleaned to one short line."
165
+ export function readRecordsBrief(root) {
166
+ const all = allRecords(root);
167
+ let ledger = { exists: false };
168
+ try {
169
+ ledger = ledgerBrief(root);
170
+ } catch {
171
+ /* no ledger line */
172
+ }
173
+ if (!all.length) return { adopted: [], drafts: [], changed: [], proposed: [], named: [], ledger };
174
+ const adopted = all.filter((r) => r.state === 'adopted');
175
+ return { adopted: adopted.map((r) => ({ id: r.id, module: String(r.module).replace(/[^\p{L}\p{N} &_\-./]/gu, '').slice(0, 40) })), drafts: all.filter((r) => r.state === 'draft').map((r) => r.id), changed: all.filter((r) => r.state === 'changed' || r.state === 'disputed').map((r) => r.id), proposed: all.filter((r) => r.state === 'proposed').map((r) => r.id), named: adopted.filter((r) => r.approval?.via === 'name').map((r) => r.id), ledger };
176
+ }
177
+
178
+ // @comment -- "The briefing's line about security decision records, when the repository has any: which modules have an adopted record, that the agent asks which record covers a file before changing it (bravos records for <file>) and follows it, that what a record lists as not a bug is intended, and that a change against a rule is raised with the person first. Drafts and records changed after adoption are counted and said to bind nobody. Ids and module names only; the rules stay in the records, which the agent reads itself."
179
+ // @comment -- "The briefing's line about the module ledger, from the first session: how many modules it lists, how many need a record and how many have one, which still need one, and whether a person reviewed the list; with no ledger yet, one offer to map the modules (the agent runs bravos records ledger propose and a person reviews the result). Unless the person switched the nudge off, in which case it only counts. Names only; never enforced."
180
+ export function ledgerLine(l, prefs = null) {
181
+ if (!l || typeof l !== 'object') return null;
182
+ const quiet = prefs?.nudge?.value === 'off';
183
+ if (!l.exists) return quiet ? null : 'Module ledger: none yet. Offer the person once this session to map which modules of this application make security decisions (bravos records ledger propose; you review its proposal and a person reviews it in a pull request; it is never enforced, and the company principles apply everywhere either way).';
184
+ const n = (x, w) => `${x} ${w}${x === 1 ? '' : 's'}`;
185
+ const missing = Array.isArray(l.missing) && l.missing.length ? `; no record yet: ${l.missing.slice(0, 6).join(', ')}${l.missing.length > 6 ? ` and ${l.missing.length - 6} more` : ''}` : '';
186
+ const review = l.review === 'reviewed' ? 'reviewed' : l.review === 'proposed' ? 'proposed, not reviewed yet' : 'not reviewed';
187
+ const ask = missing && !quiet ? ' When you first edit one of those this session, offer to draft its record (the after-edit hook reminds you once per module).' : '';
188
+ return `Module ledger (.guardlink/records/README.md, ${review}): ${n(l.count, 'module')}, ${l.withRecords} with records; ${l.needs} need one${missing}.${ask}${l.problems ? ` ${n(l.problems, 'row')} do not parse (bravos records ledger).` : ''}`;
189
+ }
190
+
191
+ export function recordsLine(r) {
192
+ if (!r || typeof r !== 'object') return null;
193
+ const adopted = Array.isArray(r.adopted) ? r.adopted : [];
194
+ const drafts = Array.isArray(r.drafts) ? r.drafts : [];
195
+ const changed = Array.isArray(r.changed) ? r.changed : [];
196
+ const proposed = Array.isArray(r.proposed) ? r.proposed : [];
197
+ const named = Array.isArray(r.named) ? r.named : [];
198
+ if (!adopted.length && !drafts.length && !changed.length && !proposed.length) return null;
199
+ const list = (xs, show) => (xs.length > 8 ? `${xs.slice(0, 8).map(show).join(', ')} and ${xs.length - 8} more` : xs.map(show).join(', '));
200
+ const rest = [
201
+ drafts.length ? `${list(drafts, (x) => x)} ${drafts.length === 1 ? 'is a draft' : 'are drafts'} nobody has adopted` : '',
202
+ changed.length ? `${list(changed, (x) => x)} ${changed.length === 1 ? 'was' : 'were'} changed after adoption (bravos records check)` : '',
203
+ ].filter(Boolean).join('; ');
204
+ const unbound = (rest ? ` ${rest}: ${drafts.length + changed.length === 1 ? 'it binds' : 'they bind'} nobody until a person adopts ${drafts.length + changed.length === 1 ? 'it' : 'them'}, so tell the person.` : '')
205
+ + (proposed.length ? ` ${list(proposed, (x) => x)} ${proposed.length === 1 ? 'is a proposed change' : 'are proposed changes'} on this branch: the default branch's text binds until a code owner approves the pull request that changes ${proposed.length === 1 ? 'it' : 'them'}.` : '')
206
+ + (named.length ? ` ${list(named, (x) => x)} ${named.length === 1 ? 'is' : 'are'} adopted by a typed name only, not verified.` : '');
207
+ if (!adopted.length) return `Security decision records: none adopted yet in .guardlink/records/.${unbound}`;
208
+ return `Security decision records: ${adopted.length} adopted in .guardlink/records/ (${list(adopted, (x) => `${x.id} ${x.module}`)}), each the team's standard for the code its paths name. Before changing a file, run bravos records for <file> and read the record it names; follow its rules and treat what it lists as not a bug as intended. When a change would break a rule, say so and ask the person first. Change a record only when the person asks: the new text binds once its pull request is approved and merges (or, the fallback, a person adopts it with bravos records adopt <id> at their own terminal).${unbound}`;
209
+ }
210
+
161
211
  // @comment -- "The briefing's Intent line. Until a named person confirms what the product is for, it tells the agent to keep annotating against its own draft (drafting one first when there is none, without waiting for answers) and to ask the person once each session to confirm it on the intake page. Right after setup (a fresh hand-off marker) it says to begin in the first reply. A recorded decline is shown with its name and date, and ends the asking."
162
212
  function intentLine(intent, harness, gate, handoff = false) {
163
213
  const run = harness === 'claude' ? '/bravos-context' : 'the bravos-context skill';
@@ -177,6 +227,30 @@ function intentLine(intent, harness, gate, handoff = false) {
177
227
  const SKILL_SIGIL = { claude: '/', codex: '$', omp: '/skill:', opencode: '/' };
178
228
 
179
229
  // @comment -- "The background annotation pass: while coverage is under 100%, the briefing asks the agent to start one bravos-annotate slice in a subagent in its first reply, beside whatever the person asked, and to say so. Not on resume or compact (the session already had its pass), not in CI (the nightly is the annotator there), not when the person switched it off (bravos prefs set annotate off) or BRAVOS_AUTO_ANNOTATE=off is set, and not when coverage is unknown. With no intent yet the pass starts after the draft is written, so two agents never draft it at once. A harness without subagents offers the pass instead."
230
+ // @comment -- "What the briefing needs to say about background drafting, without network: the state of the drafting queue (the reviewed ledger's modules needing a record, minus those with a draft branch), by module name only. Never throws."
231
+ export function readDraftsBrief(root) {
232
+ try {
233
+ const q = draftQueue(root);
234
+ const name = (m) => String(m.name).replace(/[^\p{L}\p{N} &_\-./]/gu, '').slice(0, 40);
235
+ return { state: q.state, queue: q.queue.map(name), waiting: q.waiting.length, open: q.open.map(name) };
236
+ } catch {
237
+ return null;
238
+ }
239
+ }
240
+
241
+ // @comment -- "The briefing's Background drafting line: once per session (not on resume or compact, not in CI), when the reviewed ledger has modules that need a record and have none. On the Team plan the agent starts one background subagent that drafts up to the run's limit, each on its own branch and worktree, holds every line to its source, pushes nothing, and asks the person before opening each pull request. On Free it says once that drafting is Team, with the trial command. The person switches it off with bravos prefs set drafts off."
242
+ export function draftsLine(i) {
243
+ const d = i.drafts;
244
+ if (!d || d.state !== 'ok' || !Array.isArray(d.queue) || !d.queue.length) return null;
245
+ if (i.autoDraft === false || i.prefs?.drafts?.value === 'off') return null;
246
+ if (i.source === 'resume' || i.source === 'compact') return null;
247
+ const all = [...d.queue, ...(d.waiting ? [`${d.waiting} more`] : [])].join(', ');
248
+ if (i.licence?.licensed === false) return `Background drafting: ${all} in the reviewed module ledger need a security decision record. Drafting them is on the Team plan: tell the person once, in plain words, that ${TRIAL}; they can still ask you to help write one from what they say.`;
249
+ const skill = i.harness === 'claude' ? '/bravos-records' : 'the bravos-records skill';
250
+ const where = i.harness === 'claude' ? '' : '; where this harness has no subagents, offer it once instead';
251
+ return `Background drafting: ${all} in the reviewed module ledger need a security decision record and have none. In your first reply, start one background subagent alongside the person's request${where}: it runs bravos records drafts and drafts the modules it lists (${d.queue.length} now; one per module, each on its own branch and worktree through bravos records draft "<module>"), following ${skill}: only what documents, confirmed intent rules and people stated, cited; code as observed, never a decision; Not a bug left for the person. It pushes nothing: when it ends, tell the person in one line which drafts are ready and ask whether to open their pull requests, which a code owner then reviews.${d.open?.length ? ` Already waiting for review: ${d.open.join(', ')}.` : ''} The person switches this off with bravos prefs set drafts off --by "<their name>".`;
252
+ }
253
+
180
254
  export function backgroundLine(i) {
181
255
  const coverage = Number(i.guardlink?.ci?.summary?.coverage?.percent);
182
256
  if (!Number.isFinite(coverage) || coverage >= 100) return null;
@@ -285,9 +359,15 @@ export function buildBriefing(inputs) {
285
359
  if (documents) tail.push(documents);
286
360
  const principles = principlesLine(i.principles);
287
361
  if (principles) tail.push(principles);
362
+ const records = recordsLine(i.records);
363
+ if (records) tail.push(records);
364
+ const ledger = ledgerLine(i.records?.ledger, i.prefs);
365
+ if (ledger) tail.push(ledger);
288
366
  // The person's standing answer about commits, when they gave one (hooks/lib/prefs.mjs).
289
367
  const commits = commitsLine(i.prefs);
290
368
  if (commits) tail.push(commits);
369
+ const drafting = draftsLine(i);
370
+ if (drafting) tail.push(drafting);
291
371
  const background = backgroundLine(i);
292
372
  if (background) tail.push(background);
293
373
  if (i.proving && typeof i.proving === 'object') {
@@ -614,6 +694,10 @@ export async function collect(root, env, { deadlineMs = 20000, nextCount = 3 } =
614
694
  intent: readIntent(root),
615
695
  context: readContext(root),
616
696
  principles: readPrinciples(root),
697
+ records: readRecordsBrief(root),
698
+ drafts: readDraftsBrief(root),
699
+ // The background drafting pass is off for this run (BRAVOS_AUTO_DRAFT=off) or in CI.
700
+ autoDraft: env.BRAVOS_AUTO_DRAFT !== 'off' && !env.CI && !env.GITHUB_ACTIONS,
617
701
  gate: contextGate(root),
618
702
  prefs: readPrefs(facts.commonDir),
619
703
  // The background annotation pass is off for this run (BRAVOS_AUTO_ANNOTATE=off) or in CI, where the nightly annotates.
@@ -704,12 +788,17 @@ const TEAM_ADDS = 'autopilot, PR gate, SAST, code graph';
704
788
  export const fit = (s, w) => (s.length <= w ? s : s.slice(0, Math.max(0, w - 1)) + '…');
705
789
 
706
790
  // @comment -- "True when the project registers its own Bravos session-start hook for this harness (Claude Code: .claude/settings.json, Codex: .codex/hooks.json), so another copy of the hook, the plugin's, can stay quiet and the banner and briefing arrive once. A file that is missing or unreadable reads as not registered, and so does any other harness. Read-only."
791
+ // @comment -- "Whether a registered hook command runs one of bravos's hook scripts: the repository's copy (.bravos/hooks/<name>.mjs) or the installed CLI's (bravos hook <name>), so a repository whose registrations point at the CLI reads the same."
792
+ export function runsHook(command, name) {
793
+ return typeof command === 'string' && (command.includes(`.bravos/hooks/${name}.mjs`) || new RegExp(`\\bbravos hook ${name}(?![\\w-])`).test(command));
794
+ }
795
+
707
796
  export function sessionHookRegistered(root, harness) {
708
797
  const rel = harness === 'claude' ? '.claude/settings.json' : harness === 'codex' ? '.codex/hooks.json' : null;
709
798
  if (!rel) return false;
710
799
  try {
711
800
  const groups = JSON.parse(readFileSync(join(root, rel), 'utf8'))?.hooks?.SessionStart;
712
- return Array.isArray(groups) && groups.some((g) => arr(g?.hooks).some((h) => typeof h?.command === 'string' && h.command.includes('.bravos/hooks/session-start.mjs')));
801
+ return Array.isArray(groups) && groups.some((g) => arr(g?.hooks).some((h) => typeof h?.command === 'string' && runsHook(h.command, 'session-start')));
713
802
  } catch {
714
803
  return false;
715
804
  }
@@ -720,7 +809,7 @@ export function prePrRegistered(root) {
720
809
  for (const rel of ['.claude/settings.json', '.codex/hooks.json']) {
721
810
  try {
722
811
  const groups = JSON.parse(readFileSync(join(root, rel), 'utf8'))?.hooks?.PreToolUse;
723
- if (Array.isArray(groups) && groups.some((g) => arr(g?.hooks).some((h) => typeof h?.command === 'string' && h.command.includes('.bravos/hooks/pre-pr.mjs')))) return true;
812
+ if (Array.isArray(groups) && groups.some((g) => arr(g?.hooks).some((h) => typeof h?.command === 'string' && runsHook(h.command, 'pre-pr')))) return true;
724
813
  } catch {
725
814
  /* not registered here */
726
815
  }
@@ -733,7 +822,7 @@ export function autopilotRegistered(root) {
733
822
  for (const rel of ['.claude/settings.json', '.codex/hooks.json']) {
734
823
  try {
735
824
  const groups = JSON.parse(readFileSync(join(root, rel), 'utf8'))?.hooks?.Stop;
736
- if (Array.isArray(groups) && groups.some((g) => arr(g?.hooks).some((h) => typeof h?.command === 'string' && h.command.includes('.bravos/hooks/autopilot.mjs')))) return true;
825
+ if (Array.isArray(groups) && groups.some((g) => arr(g?.hooks).some((h) => typeof h?.command === 'string' && runsHook(h.command, 'autopilot')))) return true;
737
826
  } catch {
738
827
  /* not registered here */
739
828
  }
@@ -774,6 +863,8 @@ export function readVersion(hooksDir) {
774
863
  [join(dirname(hooksDir), 'skills.lock'), (j) => j.bravos_version],
775
864
  [join(dirname(hooksDir), '.claude-plugin', 'plugin.json'), (j) => j.version],
776
865
  [join(dirname(hooksDir), 'plugin.json'), (j) => j.version],
866
+ // This install's own copy, run by the hook launcher: the package it ships in.
867
+ [join(dirname(hooksDir), 'package.json'), (j) => (j.name === '@bugb-technologies/bravos' ? j.version : null)],
777
868
  ];
778
869
  for (const [file, pick] of tries) {
779
870
  try {
@@ -16,7 +16,7 @@ const EXPOSES = /@exposes\s+(\S+)\s+to\s+(#[\w.-]+)\s*\[(critical|high|p0|p1)\](
16
16
 
17
17
  export const cardsFile = (commonDir) => join(commonDir, 'bravos', 'cards.json');
18
18
 
19
- // @comment -- "The repository files an edit touched: file_path or notebook_path in the tool input, and every path an apply_patch text names (*** Add File / *** Update File / *** Move to). Paths outside the repository are dropped, so a payload cannot point the hook at other files."
19
+ // @comment -- "The repository files an edit touched: file_path or notebook_path in the tool input (and the names other agents use: filePath, path, Path, target_file, TargetFile, a paths list), and every path an apply_patch text names (*** Add File / *** Update File / *** Move to). Paths outside the repository are dropped, so a payload cannot point the hook at other files."
20
20
  // @mitigates #threat-cards against #out-of-repo-read using #repo-bound-paths -- "touchedFiles() keeps only paths that resolve inside the repository root and outside .git, so a crafted tool payload cannot make the hook read other files"
21
21
  export function touchedFiles(root, toolInput) {
22
22
  const out = new Set();
@@ -30,6 +30,13 @@ export function touchedFiles(root, toolInput) {
30
30
  const input = toolInput && typeof toolInput === 'object' ? toolInput : {};
31
31
  add(input.file_path);
32
32
  add(input.notebook_path);
33
+ // Other agents name the file differently: opencode filePath, omp and Antigravity path, Cursor target_file; a multi-file edit lists paths.
34
+ add(input.filePath);
35
+ add(input.path);
36
+ add(input.target_file);
37
+ add(input.TargetFile);
38
+ add(input.Path);
39
+ for (const p of Array.isArray(input.paths) ? input.paths.slice(0, MAX_FILES) : []) add(p);
33
40
  for (const v of Object.values(input)) {
34
41
  if (typeof v !== 'string') continue;
35
42
  for (const m of v.matchAll(/^\*\*\* (?:Add File|Update File|Move to): (.+)$/gm)) add(m[1]);
@@ -0,0 +1,104 @@
1
+ // @comment -- "The check a drafted security decision record must pass (a record whose header says drafted:, written by a coding agent for the team's review). Every rule says where it comes from: a stored document's section (SRC-n § Section), an intent rule a person confirmed (intent: INV-n), a person's own words (said by <name>), or the code (observed: <file>:<line>), which is what the code does today and not a decision, so it may only be guidance. Each citation is checked against the repository: the document and its section exist, the intent rule is confirmed, the file and line exist. Not a bug is never filled from code: each line there must cite a document, a confirmed intent rule or a person. A decision with no source stays the team's placeholder. Read-only; returns problems and notes, never throws."
2
+ import { findSection } from './context.mjs';
3
+ import { oneLine } from './principles.mjs';
4
+
5
+ export const DECISION_PLACEHOLDER = 'The team writes the decision here: no stored document, confirmed intent rule or person has stated it yet.';
6
+ const SOURCES_DIR = '.bravos/context/sources';
7
+
8
+ const OBSERVED = /\(observed:\s*([A-Za-z0-9_.\-/]+):(\d{1,6})(?:-(\d{1,6}))?\)/g;
9
+ const DOC = /\((SRC-[1-9][0-9]{0,4})\s*§\s*([^)]{1,120})\)/g;
10
+ const INTENT = /\(intent:\s*(INV-[0-9]{1,4})\)/gi;
11
+ const SAID = /\(said by\s+([^)]{2,80})\)/gi;
12
+
13
+ /** The sources a line of a drafted record cites. */
14
+ export function sourcesOf(text) {
15
+ const t = String(text ?? '');
16
+ return {
17
+ observed: [...t.matchAll(OBSERVED)].map((m) => ({ file: m[1], line: Number(m[2]), end: m[3] ? Number(m[3]) : Number(m[2]) })),
18
+ docs: [...t.matchAll(DOC)].map((m) => ({ id: m[1], section: m[2].trim() })),
19
+ intent: [...t.matchAll(INTENT)].map((m) => m[1].toUpperCase()),
20
+ said: [...t.matchAll(SAID)].map((m) => oneLine(m[1], 80)),
21
+ };
22
+ }
23
+
24
+ // @comment -- "The INV ids in .guardlink/intent.md a named person confirmed: an INV-n bullet whose attribution after the last ' — ' is present and does not start with draft (the reading bravos rules and the pre-PR gate use)."
25
+ export function confirmedIntent(text) {
26
+ const ok = new Set();
27
+ for (const line of String(text ?? '').split(/\r?\n/)) {
28
+ const m = /^\s*[-*]\s+(INV-\d+)\s*:\s*(.+)$/.exec(line);
29
+ if (!m) continue;
30
+ const dash = m[2].lastIndexOf(' — ');
31
+ if (dash >= 0 && !/^draft\b/i.test(m[2].slice(dash + 3).trim())) ok.add(m[1]);
32
+ }
33
+ return ok;
34
+ }
35
+
36
+ // @comment -- "Checks the citations of one drafted record against the repository through the reader (regular files inside it only). Problems fail bravos records check, so a draft whose sources do not hold cannot go out for review; notes tell the reviewer what is left for them: observed rules to confirm or remove, an empty Not a bug to fill from their own words, a decision left to write."
37
+ export function draftProblems(record, reader) {
38
+ const problems = [];
39
+ const notes = [];
40
+ const id = record.id;
41
+ let names = [];
42
+ try {
43
+ names = reader.list(SOURCES_DIR);
44
+ } catch {
45
+ names = [];
46
+ }
47
+ const docText = new Map();
48
+ const doc = (srcId) => {
49
+ if (!docText.has(srcId)) {
50
+ const name = names.find((n) => n === `${srcId}.md` || (n.startsWith(`${srcId}-`) && n.endsWith('.md')));
51
+ docText.set(srcId, name ? reader.read(`${SOURCES_DIR}/${name}`) : null);
52
+ }
53
+ return docText.get(srcId);
54
+ };
55
+ const intent = confirmedIntent(reader.read('.guardlink/intent.md') ?? '');
56
+ const lines = new Map();
57
+ const lineCount = (file) => {
58
+ if (!lines.has(file)) {
59
+ const t = reader.read(file);
60
+ lines.set(file, t === null ? -1 : String(t).split('\n').length);
61
+ }
62
+ return lines.get(file);
63
+ };
64
+ const verify = (where, s) => {
65
+ for (const d of s.docs) {
66
+ const text = doc(d.id);
67
+ if (text === null) problems.push(`${id} ${where} cites ${d.id}, which is not a stored document (bravos context list)`);
68
+ else if (!findSection(String(text), d.section)) problems.push(`${id} ${where} cites ${d.id} § ${d.section}, and that document has no such section`);
69
+ }
70
+ for (const i of s.intent) if (!intent.has(i)) problems.push(`${id} ${where} cites ${i}, which no person has confirmed in .guardlink/intent.md; cite it once it is confirmed, or leave it out`);
71
+ for (const o of s.observed) {
72
+ const n = lineCount(o.file);
73
+ if (n < 0) problems.push(`${id} ${where} cites ${o.file}, which is not a file in this repository`);
74
+ else if (o.line < 1 || o.end < o.line || o.end > n) problems.push(`${id} ${where} cites ${o.file}:${o.line}${o.end !== o.line ? `-${o.end}` : ''}, past the end of the file (${n} lines)`);
75
+ }
76
+ };
77
+ const decided = (s) => s.docs.length + s.intent.length + s.said.length > 0;
78
+
79
+ const ds = sourcesOf(record.decision);
80
+ verify('Decision', ds);
81
+ if (record.decision === DECISION_PLACEHOLDER) notes.push(`${id}: the decision is left for the team to write; no document, confirmed rule or person stated it`);
82
+ else if (!decided(ds)) problems.push(`${id} Decision cites no document, confirmed intent rule or person: a draft states only what the team decided. Cite the source, or leave the team's placeholder ("${DECISION_PLACEHOLDER}")`);
83
+
84
+ const observed = [];
85
+ for (const r of record.rules) {
86
+ const s = sourcesOf(r.text);
87
+ verify(r.id, s);
88
+ if (!decided(s) && !s.observed.length) problems.push(`${id} ${r.id} says nowhere where it comes from: cite (SRC-n § Section), (intent: INV-n), (said by <name>) or, for what the code does today, (observed: <file>:<line>)`);
89
+ else if (!decided(s)) {
90
+ observed.push(r.id);
91
+ if (r.kind === 'enforced') problems.push(`${id} ${r.id} is observed from the code only, so it is what the code does today, not a decision: make it guidance until the team confirms it`);
92
+ }
93
+ }
94
+ if (observed.length) notes.push(`${id}: ${observed.join(', ')} ${observed.length === 1 ? 'is' : 'are'} observed from the code, not decided; the reviewer confirms (cite who decided it) or removes ${observed.length === 1 ? 'it' : 'them'}`);
95
+
96
+ record.notABug.forEach((line, n) => {
97
+ const s = sourcesOf(line);
98
+ verify(`Not a bug ${n + 1}`, s);
99
+ if (s.observed.length) problems.push(`${id} Not a bug ${n + 1} cites the code: Not a bug is never filled from code alone, because it can make a real vulnerability look intended. Take it out, or cite a document, a confirmed intent rule or the person who said it`);
100
+ else if (!decided(s)) problems.push(`${id} Not a bug ${n + 1} cites no document, confirmed intent rule or person; in a draft every Not a bug line says who decided it`);
101
+ });
102
+ if (!record.notABug.length) notes.push(`${id}: Not a bug is empty, as a draft leaves it: ask the person what looks wrong in this module and is intended, and add only what they say (said by <name>)`);
103
+ return { problems, notes };
104
+ }
@@ -0,0 +1,121 @@
1
+ // @comment -- "Background drafting of security decision records (records round two, PR 3): which modules of the reviewed ledger need a record and have none, which already have a draft waiting (a bravos/record-<module> branch, or its open pull request), and how many may be drafted now. At most a few per run and a few waiting at once, so a large repository is not flooded, and never two drafts for one module. Bravos runs no model: a coding agent writes each draft in a subagent from the stored documents, confirmed intent rules and the code, and draft-check.mjs holds it to its sources. Reads git and the repository only; never throws to a hook."
2
+ import { spawnSync } from 'node:child_process';
3
+ import { readdirSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { DECISION_PLACEHOLDER, confirmedIntent } from './draft-check.mjs';
6
+ import { documentSections, moduleFiles, readLedger, repoFiles } from './ledger.mjs';
7
+ import { oneLine, treeReader } from './principles.mjs';
8
+ import { allRecords, approvalContext, ID } from './records.mjs';
9
+
10
+ export const DRAFT_PREFIX = 'bravos/record-';
11
+ /** Drafts started in one run (one background pass per session). */
12
+ export const DRAFT_LIMIT = 2;
13
+ /** Drafts waiting for review at once, across the repository. */
14
+ export const MAX_OPEN = 3;
15
+ export const draftBranch = (key) => `${DRAFT_PREFIX}${key}`;
16
+
17
+ const git = (root, args) => {
18
+ const r = spawnSync('git', args, { cwd: root, encoding: 'utf8', timeout: 8000, maxBuffer: 16 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] });
19
+ return r.status === 0 ? r.stdout : null;
20
+ };
21
+
22
+ // @comment -- "The draft branches this clone knows, local and on its remotes (bravos/record-<module>), by module key. Read with for-each-ref; nothing is fetched."
23
+ export function draftRefs(root) {
24
+ const out = new Map();
25
+ const text = git(root, ['for-each-ref', '--format=%(refname)', `refs/heads/${DRAFT_PREFIX}*`, `refs/remotes/*/${DRAFT_PREFIX}*`]) ?? '';
26
+ for (const ref of text.split('\n').map((l) => l.trim()).filter(Boolean)) {
27
+ const key = ref.slice(ref.indexOf(DRAFT_PREFIX) + DRAFT_PREFIX.length);
28
+ if (!/^[a-z0-9][a-z0-9-]{0,60}$/.test(key)) continue;
29
+ out.set(key, [...(out.get(key) ?? []), ref]);
30
+ }
31
+ return out;
32
+ }
33
+
34
+ // @comment -- "The highest record id used anywhere a new draft could collide: this checkout's records, the default branch's, every draft branch's, and the files in every worktree of this clone (a draft just started is not committed yet). A draft takes the next one, so two drafts started in parallel never share an id."
35
+ export function nextDraftId(root, records = allRecords(root)) {
36
+ let max = 0;
37
+ const take = (id) => {
38
+ if (ID.test(id)) max = Math.max(max, Number(id.slice(4)));
39
+ };
40
+ for (const r of records) take(r.id);
41
+ const refs = [...[...draftRefs(root).values()].flat()];
42
+ const ctx = approvalContext(root);
43
+ if (ctx?.ref) refs.push(ctx.ref);
44
+ for (const ref of refs) {
45
+ for (const name of (git(root, ['ls-tree', '--name-only', `${ref}:.guardlink/records`]) ?? '').split('\n')) {
46
+ const m = /^(SDR-[1-9][0-9]{0,3})[-.]/.exec(name.trim());
47
+ if (m) take(m[1]);
48
+ }
49
+ }
50
+ for (const line of (git(root, ['worktree', 'list', '--porcelain']) ?? '').split('\n')) {
51
+ if (!line.startsWith('worktree ')) continue;
52
+ try {
53
+ for (const name of readdirSync(join(line.slice(9).trim(), '.guardlink', 'records'))) {
54
+ const m = /^(SDR-[1-9][0-9]{0,3})[-.]/.exec(name);
55
+ if (m) take(m[1]);
56
+ }
57
+ } catch {
58
+ /* a worktree with no records folder */
59
+ }
60
+ }
61
+ return `SDR-${max + 1}`;
62
+ }
63
+
64
+ // @comment -- "What may be drafted now. Only from a ledger a person reviewed (its module list on the default branch): an unreviewed ledger could make the agent draft for a boundary nobody agreed. A module needs a draft when the ledger marks it as needing a record and it has none; one with a draft branch or an open draft pull request (openPrs, when the CLI could ask GitHub) already has its draft and is never drafted twice. A draft branch for a module that has since got a record no longer counts as waiting. The queue holds at most limit modules and never lets more than maxOpen drafts wait at once."
65
+ export function draftQueue(root, opts = {}) {
66
+ const limit = Math.max(0, opts.limit ?? DRAFT_LIMIT);
67
+ const maxOpen = Math.max(0, opts.maxOpen ?? MAX_OPEN);
68
+ const ledger = opts.ledger ?? readLedger(root, { files: opts.files });
69
+ if (!ledger.exists) return { state: 'no-ledger', queue: [], waiting: [], open: [], candidates: [] };
70
+ if (ledger.review?.state !== 'reviewed') return { state: 'unreviewed', queue: [], waiting: [], open: [], candidates: [], review: ledger.review };
71
+ const refs = draftRefs(root);
72
+ const prs = new Set((opts.openPrs ?? []).map((p) => String(p.headRefName ?? '')).filter((h) => h.startsWith(DRAFT_PREFIX)).map((h) => h.slice(DRAFT_PREFIX.length)));
73
+ const needs = ledger.modules.filter((m) => m.needs === 'yes');
74
+ const candidates = needs.filter((m) => !m.records.length);
75
+ const open = needs.filter((m) => !m.records.length && (refs.has(m.key) || prs.has(m.key))).map((m) => ({ name: m.name, key: m.key, branch: draftBranch(m.key), refs: refs.get(m.key) ?? [], pr: prs.has(m.key) }));
76
+ const free = candidates.filter((m) => !open.some((o) => o.key === m.key));
77
+ const slots = Math.max(0, Math.min(limit, maxOpen - open.length));
78
+ return { state: free.length ? 'ok' : 'none', queue: free.slice(0, slots), waiting: free.slice(slots), open, candidates, slots, limit, maxOpen };
79
+ }
80
+
81
+ // @comment -- "What the drafting agent is handed for one module: its code (a bounded list of files), the stored documents' sections that name it, already in the citation form a draft must use, and the intent rules a person confirmed (ids and a short line each). The documents and intent are cited, never copied into the brief beyond their headings and a line."
82
+ export function draftBrief(root, m, opts = {}) {
83
+ const files = moduleFiles(m, opts.files ?? repoFiles(root));
84
+ const key = m.key;
85
+ const sections = (opts.sections ?? documentSections(root)).filter((s) => s.key === key || s.key.split('-').includes(key) || key.split('-').every((w) => s.key.split('-').includes(w)));
86
+ const intentText = treeReader(root).read('.guardlink/intent.md') ?? '';
87
+ const ok = confirmedIntent(intentText);
88
+ const intent = [];
89
+ for (const line of String(intentText).split(/\r?\n/)) {
90
+ const x = /^\s*[-*]\s+(INV-\d+)\s*:\s*(.+)$/.exec(line);
91
+ if (x && ok.has(x[1]) && !intent.some((i) => i.id === x[1])) intent.push({ id: x[1], text: oneLine(x[2], 140) });
92
+ }
93
+ return { name: m.name, key, paths: m.paths, branch: draftBranch(key), evidence: m.evidence, why: m.why, files: files.slice(0, 40), moreFiles: Math.max(0, files.length - 40), documents: sections.map((s) => `${s.id} § ${s.heading}`), intent: intent.slice(0, 30) };
94
+ }
95
+
96
+ // @comment -- "The file a draft starts from: a drafted: header saying who drafted it and that it binds nobody until approved, the decision left as the team's placeholder, the rules and Not a bug sections empty with the drafting rules beside them in comments. The agent fills it in; bravos records check then holds every line to its source."
97
+ export function draftSkeleton(id, module, paths, today) {
98
+ return [
99
+ '---',
100
+ `record: ${id}`,
101
+ `module: ${module}`,
102
+ `paths: [${paths.join(', ')}]`,
103
+ `drafted: by a coding agent on ${today}, for the team's review; binds nobody until approved`,
104
+ '---',
105
+ `# ${module}: what was decided here`,
106
+ '',
107
+ '## Decision',
108
+ DECISION_PLACEHOLDER,
109
+ '<!-- Replace the line above only with what a stored document, a confirmed intent rule or a person stated, citing it: (SRC-n § Section), (intent: INV-n) or (said by <name>). Never a decision the team did not make. -->',
110
+ '',
111
+ '## Rules',
112
+ '<!-- One rule per line: "- R1 (enforced): <text> (SRC-n § Section)". Every rule cites its source. What the code does today is "(observed: <file>:<line>)": it is not a decision, so it is guidance until the team confirms it. -->',
113
+ '',
114
+ '## Why',
115
+ '<!-- From the documents, cited; otherwise leave it for the team. -->',
116
+ '',
117
+ '## Not a bug',
118
+ '<!-- Left for the team. Filled only from a stored document, a confirmed intent rule or a person\'s own words (said by <name>), never from the code: a line here makes behaviour look intended. Ask the person what looks wrong in this module and is intended. -->',
119
+ '',
120
+ ].join('\n');
121
+ }