@bugb-technologies/bravos 1.24.0 → 1.25.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 (45) hide show
  1. package/dist/bin.js +12 -0
  2. package/dist/cli.js +189 -15
  3. package/dist/context.js +4 -4
  4. package/dist/cursor.js +24 -5
  5. package/dist/dashboard.js +6 -0
  6. package/dist/doctor.js +29 -2
  7. package/dist/graphbin.js +2 -2
  8. package/dist/guide.js +3 -1
  9. package/dist/hook-launcher.js +92 -0
  10. package/dist/hooks.js +56 -3
  11. package/dist/prefs.js +13 -3
  12. package/dist/principles.js +1 -1
  13. package/dist/records-drafts.js +106 -0
  14. package/dist/records-ledger.js +103 -0
  15. package/dist/records-team.js +398 -0
  16. package/dist/records.js +158 -0
  17. package/dist/review-server.js +3 -1
  18. package/dist/review.js +16 -1
  19. package/dist/rules.js +48 -4
  20. package/dist/uninstall.js +1 -1
  21. package/dist/upkeep.js +3 -0
  22. package/docs/GUIDE.md +10 -0
  23. package/docs/UPGRADING.md +40 -0
  24. package/hooks/cards.mjs +62 -13
  25. package/hooks/coach.mjs +3 -1
  26. package/hooks/lib/agent-io.mjs +105 -0
  27. package/hooks/lib/briefing.mjs +94 -3
  28. package/hooks/lib/cards.mjs +8 -1
  29. package/hooks/lib/draft-check.mjs +104 -0
  30. package/hooks/lib/drafts.mjs +121 -0
  31. package/hooks/lib/ledger.mjs +270 -0
  32. package/hooks/lib/pre-pr.mjs +74 -0
  33. package/hooks/lib/prefs.mjs +7 -3
  34. package/hooks/lib/record-guard.mjs +272 -0
  35. package/hooks/lib/records.mjs +581 -0
  36. package/hooks/lib/replay.mjs +2 -1
  37. package/hooks/record-guard.mjs +60 -0
  38. package/hooks/session-start.mjs +4 -3
  39. package/package.json +2 -2
  40. package/skills/bravos/SKILL.md +1 -0
  41. package/skills/bravos-records/SKILL.md +57 -0
  42. package/templates/dashboard/dashboard.html +53 -0
  43. package/templates/omp/bravos.js +85 -1
  44. package/templates/opencode/bravos.js +84 -1
  45. package/templates/workflows/bravos-pr-gate.yml +23 -0
@@ -0,0 +1,92 @@
1
+ // @comment -- "The hook launcher: runs one of the hook scripts this installed bravos ships, by name, in this same Node process, so a hook registered as `bravos hook <name>` behaves byte for byte like `node .bravos/hooks/<name>.mjs` (same stdin, stdout, stderr and exit code) without a repository copy. It imports nothing of bravos's own beyond node built-ins, so the bin shim can reach it without loading the CLI's commands. Only names in the fixed table run; any other name, or none, exits 0 with no output, so a pointer to a hook a later or earlier bravos does not ship never breaks an agent's turn."
2
+ import { spawnSync } from 'node:child_process';
3
+ import { existsSync, realpathSync } from 'node:fs';
4
+ import { homedir } from 'node:os';
5
+ import { dirname, join, resolve } from 'node:path';
6
+ import { fileURLToPath, pathToFileURL } from 'node:url';
7
+ // @comment -- "Every script a repository copy of the hooks can be run as today: the agent hooks the harnesses register, the invitation snooze, the library commands the skills, git hooks and CI workflows call, and the nightly tools bootstrap. A name maps to a path inside this package's hooks/ folder; nothing a caller passes becomes part of a path."
8
+ export const HOOKS = Object.freeze({
9
+ 'session-start': 'session-start.mjs',
10
+ coach: 'coach.mjs',
11
+ cards: 'cards.mjs',
12
+ autopilot: 'autopilot.mjs',
13
+ 'pre-pr': 'pre-pr.mjs',
14
+ invite: 'invite.mjs',
15
+ replay: 'lib/replay.mjs',
16
+ context: 'lib/context.mjs',
17
+ principles: 'lib/principles.mjs',
18
+ 'threat-issues': 'lib/threat-issues.mjs',
19
+ 'nightly-stage': 'lib/nightly-stage.mjs',
20
+ 'nightly-tools': 'lib/nightly-tools.sh',
21
+ 'record-guard': 'record-guard.mjs',
22
+ records: 'lib/records.mjs',
23
+ });
24
+ // @comment -- "The hooks a harness runs on its own events (session start, each prompt, each edit, end of turn, before a pull request). As a pointer they may run in a repository Bravos is not set up in; there they do nothing, as no repository copy would exist to run. An explicit `session-start --briefing` is a request, not an event, and always answers."
25
+ export const AGENT_EVENTS = new Set(['session-start', 'coach', 'cards', 'autopilot', 'pre-pr', 'record-guard']);
26
+ // @comment -- "Hook scripts that run only through the installed CLI (bravos hook <name>) and are never copied into a repository's .bravos/hooks/, so moving the hooks out of repositories has nothing more to migrate."
27
+ export const CLI_ONLY_HOOKS = Object.freeze(['record-guard.mjs']);
28
+ // @comment -- "Whether the repository a hook event is about is set up with Bravos or GuardLink: the folder the harness names (CLAUDE_PROJECT_DIR) or the working folder, walked up to the top of its git checkout, holds GuardLink's .guardlink/config.json, or a repository's own Bravos marker (.bravos/skills.lock or .bravos/setup.json). The machine's own Bravos folder never counts: the home folder's .bravos/ and BRAVOS_HOME hold this machine's configuration and its user-level install, not a repository, so an agent opened in the home folder is not briefed. An empty .bravos/ is not a set-up repository either. File-system checks only: the event's stdin payload is left unread for the hook itself."
29
+ // @mitigates #hook-launcher against #home-folder-briefing using #repository-marker -- "A harness event counts as being in a Bravos repository only on a repository marker (.guardlink/config.json, .bravos/skills.lock, .bravos/setup.json), and never on the home folder's or BRAVOS_HOME's own .bravos/"
30
+ export function repoHasBravos(env = process.env, cwd = process.cwd()) {
31
+ const real = (p) => {
32
+ try {
33
+ return realpathSync(p);
34
+ }
35
+ catch {
36
+ return resolve(p);
37
+ }
38
+ };
39
+ const start = real(env.CLAUDE_PROJECT_DIR || cwd);
40
+ let dir = start;
41
+ for (;;) {
42
+ if (existsSync(join(dir, '.git')))
43
+ break;
44
+ const up = dirname(dir);
45
+ if (up === dir) {
46
+ dir = start;
47
+ break;
48
+ }
49
+ dir = up;
50
+ }
51
+ if (existsSync(join(dir, '.guardlink', 'config.json')))
52
+ return true;
53
+ const own = real(join(dir, '.bravos'));
54
+ const machine = [env.BRAVOS_HOME, env.HOME ? join(env.HOME, '.bravos') : null, join(homedir(), '.bravos')].filter((p) => !!p).map(real);
55
+ if (machine.includes(own))
56
+ return false;
57
+ return existsSync(join(dir, '.bravos', 'skills.lock')) || existsSync(join(dir, '.bravos', 'setup.json'));
58
+ }
59
+ /** The marker a hook reads to know it runs as the repository's registered hook, not as a plugin's or a user-level copy. Set in this process only, never in the environment, so a child process or a caller cannot fake it. */
60
+ export const LAUNCHER_MARK = Symbol.for('bravos.hook-launcher');
61
+ /** This package's hooks/ folder: beside dist/ in an install, beside src/ in a checkout. */
62
+ export function launcherHooksDir() {
63
+ return join(dirname(dirname(fileURLToPath(import.meta.url))), 'hooks');
64
+ }
65
+ // @comment -- "Runs the named hook with the given arguments. A known .mjs hook is imported in this process after process.argv is set to exactly what `node <script> <args>` would give it (the script's real path first), so its own entry guard, its argument parsing and its reading of stdin are unchanged, and it sets the exit code or exits itself as it does today. The nightly tools script runs under bash with stdin, stdout and stderr passed straight through and its exit code kept. An unknown name, no name, a script missing from this install, or a harness event in a folder not set up with Bravos or GuardLink exits 0 with no output, so a pointer never blocks an agent. A script that throws ends the process with code 1, as it does when run directly."
66
+ // @mitigates #hook-launcher against #hook-name-injection using #fixed-hook-table -- "Only names in the fixed table run, each mapped to a constant path inside this package; an unknown or crafted name runs nothing and prints nothing"
67
+ export async function launch(name, args) {
68
+ const rel = typeof name === 'string' && Object.prototype.hasOwnProperty.call(HOOKS, name) ? HOOKS[name] : null;
69
+ if (!rel) {
70
+ process.exitCode = 0;
71
+ return;
72
+ }
73
+ if (AGENT_EVENTS.has(name) && !(name === 'session-start' && args.includes('--briefing')) && !repoHasBravos()) {
74
+ process.exitCode = 0;
75
+ return;
76
+ }
77
+ const file = join(launcherHooksDir(), rel);
78
+ if (!existsSync(file)) {
79
+ process.exitCode = 0;
80
+ return;
81
+ }
82
+ const real = realpathSync(file);
83
+ if (rel.endsWith('.sh')) {
84
+ const r = spawnSync('bash', [real, ...args], { stdio: 'inherit' });
85
+ process.exitCode = r.status ?? 1;
86
+ return;
87
+ }
88
+ process.argv = [process.argv[0], real, ...args];
89
+ globalThis[LAUNCHER_MARK] = true;
90
+ // A script that throws while it runs ends this process with Node's own uncaught-error exit (code 1), as it would run directly.
91
+ await import(pathToFileURL(real).href);
92
+ }
package/dist/hooks.js CHANGED
@@ -3,6 +3,7 @@ import { dirname, join, relative } from 'node:path';
3
3
  import { hooksDir as packageHooksDir } from './paths.js';
4
4
  import { OLD_HOOK_COMMANDS, OLD_NAME, oldGlobalHookCommand } from './migrate.js';
5
5
  import { BravosError } from './types.js';
6
+ import { CLI_ONLY_HOOKS } from './hook-launcher.js';
6
7
  // @comment -- "The SessionStart command before 0.5.0; init and sync replace it with the per-harness form, and doctor still accepts it."
7
8
  export const LEGACY_HOOK_COMMAND = 'node .bravos/hooks/session-start.mjs';
8
9
  // @comment -- "Where a hook command finds the repository's .bravos/hooks. Until 1.8 the commands were relative (node .bravos/hooks/x.mjs), and a harness runs a hook in the session's current folder: once the agent changed folder (cd ios/Runner), every hook failed with 'Cannot find module', autopilot stopped running and the pre-PR gate let gh pr create through unchecked. Claude Code gives the project root as ${CLAUDE_PROJECT_DIR}; Codex documents resolving from the git top level. Both are quoted, so a path with a space works. Antigravity runs its hook in the workspace and keeps the relative form."
@@ -79,6 +80,20 @@ const cards = (h) => ({
79
80
  ? { matcher: 'Edit|Write|MultiEdit|NotebookEdit', hooks: [{ type: 'command', command: CARDS_COMMANDS[h], timeout: 10 }] }
80
81
  : { hooks: [{ type: 'command', command: CARDS_COMMANDS[h], timeout: 10 }] },
81
82
  });
83
+ // @comment -- "The record guard: a PreToolUse hook on Claude Code's file-edit tools and Codex's apply_patch that refuses the first edit in a session to a file an adopted security decision record covers, once, with the record in full (hooks/record-guard.mjs). It runs only through the installed CLI (bravos hook record-guard), and the command checks first that the repository keeps records and that bravos is on PATH, so a repository without records, or a teammate without Bravos, pays nothing and is never blocked."
84
+ export const RECORD_GUARD_COMMANDS = {
85
+ claude: 'if [ -d "${CLAUDE_PROJECT_DIR}/.guardlink/records" ] && command -v bravos >/dev/null 2>&1; then bravos hook record-guard --harness claude; fi',
86
+ agents: 'r="$(git rev-parse --show-toplevel 2>/dev/null)"; if [ -n "$r" ] && [ -d "$r/.guardlink/records" ] && command -v bravos >/dev/null 2>&1; then bravos hook record-guard --harness codex; fi',
87
+ };
88
+ // Claude Code's file-edit tools; Codex edits through apply_patch (its patch text names the files).
89
+ const RECORD_GUARD_MATCHER = { claude: 'Edit|Write|MultiEdit|NotebookEdit', agents: 'apply_patch|Edit|Write' };
90
+ export const ALL_RECORD_GUARD_COMMANDS = Object.values(RECORD_GUARD_COMMANDS).filter((c) => !!c);
91
+ const recordGuard = (h) => {
92
+ const command = RECORD_GUARD_COMMANDS[h];
93
+ if (!command)
94
+ return [];
95
+ return [{ event: 'PreToolUse', command, group: { matcher: RECORD_GUARD_MATCHER[h], hooks: [{ type: 'command', command, timeout: 10 }] } }];
96
+ };
82
97
  // The hook script itself only acts on commands that run gh pr create or gh pr ready.
83
98
  const prePr = (h) => ({
84
99
  event: 'PreToolUse',
@@ -190,9 +205,44 @@ export function installedOptIns(root) {
190
205
  prePr: files.some((f) => hookRegistered(f, 'PreToolUse', ALL_PRE_PR_COMMANDS)),
191
206
  };
192
207
  }
193
- export const AGY_HOOK_COMMAND = `${LEGACY_HOOK_COMMAND} --harness agy`;
208
+ // @comment -- "The edit hooks for agents whose hooks file Bravos writes as shell commands (Cursor, Antigravity): the record guard and the cards run only through the installed CLI (bravos hook <name>), never a repository copy, so the hooks migration has nothing to move. The guard runs only where the repository keeps records and bravos is on PATH; otherwise, like any failure, it answers {} and the edit goes ahead (Cursor blocks an edit on output that is not JSON)."
209
+ export const editGuardCommand = (harness) => `r="$(git rev-parse --show-toplevel 2>/dev/null)"; if [ -n "$r" ] && [ -d "$r/.guardlink/records" ] && command -v bravos >/dev/null 2>&1; then bravos hook record-guard --harness ${harness}; else echo '{}'; fi`;
210
+ export const editCardsCommand = (harness, args = '') => `if command -v bravos >/dev/null 2>&1; then bravos hook cards --harness ${harness}${args ? ` ${args}` : ''}; else echo '{}'; fi`;
211
+ // @comment -- "Antigravity runs a hook with its working directory set to the folder holding hooks.json (.agents/), so the session-start path is found from the git top level; the relative form 1.24 and earlier wrote never resolved there."
212
+ export const AGY_HOOK_COMMAND = `node "$(git rev-parse --show-toplevel)/.bravos/hooks/session-start.mjs" --harness agy`;
213
+ /** The relative form 1.24 and earlier registered; doctor still recognises it, setup replaces it. */
214
+ export const AGY_LEGACY_HOOK_COMMAND = `${LEGACY_HOOK_COMMAND} --harness agy`;
194
215
  export const AGY_HOOKS_FILE = '.agents/hooks.json';
195
- const AGY_GROUP = { SessionStart: [{ type: 'command', command: AGY_HOOK_COMMAND, timeout: 30 }] };
216
+ // @comment -- "Antigravity's edit tools: the agy CLI's write_file and edit_file (args Path), and the names its web docs list for the app and IDE (write_to_file, replace_file_content, multi_replace_file_content; args TargetFile). Anchored, since how its RE2 matcher anchors is not documented."
217
+ export const AGY_EDIT_MATCHER = '^(write_file|edit_file|write_to_file|replace_file_content|multi_replace_file_content)$';
218
+ // @comment -- "Bravos's named hook in .agents/hooks.json: the briefing at SessionStart; the record guard before an edit (PreToolUse, decision deny); after an edit the cards and the no-record nudge, which PostToolUse cannot hand the model, so they wait for the next model call (PreInvocation, injectSteps)."
219
+ export const AGY_GROUP = {
220
+ SessionStart: [{ type: 'command', command: AGY_HOOK_COMMAND, timeout: 30 }],
221
+ PreToolUse: [{ matcher: AGY_EDIT_MATCHER, hooks: [{ type: 'command', command: editGuardCommand('agy'), timeout: 10 }] }],
222
+ PostToolUse: [{ matcher: AGY_EDIT_MATCHER, hooks: [{ type: 'command', command: editCardsCommand('agy'), timeout: 10 }] }],
223
+ PreInvocation: [{ type: 'command', command: editCardsCommand('agy', '--deliver'), timeout: 5 }],
224
+ };
225
+ /** What .agents/hooks.json registers for Bravos: the session start, and the before- and after-edit hooks. */
226
+ export function agyRegistered(root) {
227
+ try {
228
+ const b = JSON.parse(readFileSync(join(root, AGY_HOOKS_FILE), 'utf8')).bravos;
229
+ // Every command in the group, whether listed flat (SessionStart, PreInvocation) or under a matcher (the tool events).
230
+ const commands = [];
231
+ for (const list of Object.values(b ?? {})) {
232
+ for (const e of Array.isArray(list) ? list : []) {
233
+ const entries = isObject(e) && Array.isArray(e.hooks) ? e.hooks : [e];
234
+ for (const h of entries)
235
+ if (isObject(h) && typeof h.command === 'string')
236
+ commands.push(h.command);
237
+ }
238
+ }
239
+ const any = (re) => commands.some((c) => re.test(c));
240
+ return { session: any(/session-start\.mjs"? --harness agy/), guard: any(/\bbravos hook record-guard --harness agy\b/), cards: any(/\bbravos hook cards --harness agy --deliver\b/) && any(/\bbravos hook cards --harness agy;/) };
241
+ }
242
+ catch {
243
+ return { session: false, guard: false, cards: false };
244
+ }
245
+ }
196
246
  // @comment -- "Plans bravos's entry in Antigravity's workspace hooks file, whose top-level keys are named hook groups; only the 'bravos' key is bravos's, every other key is kept, and a malformed file is refused before anything is written."
197
247
  function planAgy(root) {
198
248
  const abs = join(root, AGY_HOOKS_FILE);
@@ -218,7 +268,8 @@ function planAgy(root) {
218
268
  // @comment -- "Copies the hook scripts into <root>/.bravos/hooks and registers the SessionStart briefing, the UserPromptSubmit coach and the PostToolUse threat cards, plus the PreToolUse pre-PR gate when prePr is set, for Claude Code (.claude/settings.json), Codex (.codex/hooks.json) and Antigravity (.agents/hooks.json); settings files are validated before anything is written and existing keys and groups are preserved."
219
269
  export function installHook(root, harnesses, opts = {}) {
220
270
  const src = opts.hooksDir ?? packageHooksDir();
221
- const files = listFiles(src).map((abs) => relative(src, abs).split('\\').join('/')).sort();
271
+ // A hook that runs only through the installed CLI (record-guard) is never copied into the repository.
272
+ const files = listFiles(src).map((abs) => relative(src, abs).split('\\').join('/')).filter((f) => !CLI_ONLY_HOOKS.includes(f)).sort();
222
273
  const copied = files.map((f) => `.bravos/hooks/${f}`);
223
274
  const withPrePr = (opts.prePr || opts.autopilot) && !opts.globalHome;
224
275
  const withAutopilot = opts.autopilot && !opts.globalHome;
@@ -227,6 +278,8 @@ export function installHook(root, harnesses, opts = {}) {
227
278
  ...(opts.globalHome ? [] : [coach(h), cards(h)]),
228
279
  ...(withPrePr ? [prePr(h)] : []),
229
280
  ...(withAutopilot ? [autopilot(h)] : []),
281
+ // After the opt-in gate, so an existing PreToolUse list keeps the gate first.
282
+ ...(opts.globalHome ? [] : recordGuard(h)),
230
283
  ], [
231
284
  ...(withPrePr ? [] : [{ event: 'PreToolUse', commands: [OLD_HOOK_COMMANDS.prePr] }]),
232
285
  ...(withAutopilot ? [] : [{ event: 'Stop', commands: [OLD_HOOK_COMMANDS.autopilot] }]),
package/dist/prefs.js CHANGED
@@ -24,6 +24,14 @@ const NOTIFY_WHAT = {
24
24
  on: 'also send a desktop notification for each threat card',
25
25
  off: 'send no desktop notifications',
26
26
  };
27
+ const NUDGE_WHAT = {
28
+ on: 'say once per module per session, at the first edit, when a module the ledger marks as needing a security decision record has none',
29
+ off: 'say nothing about modules without a record; the briefing still counts them',
30
+ };
31
+ const DRAFTS_WHAT = {
32
+ background: 'let one background pass each session draft security decision records for the reviewed ledger\'s modules that need one (Team plan), pushing nothing without asking',
33
+ off: 'draft no records in the background; the agent drafts one when asked',
34
+ };
27
35
  const ANNOTATE_WHAT = {
28
36
  background: 'start one background annotation pass each session while coverage is incomplete',
29
37
  off: 'start no background annotation pass; annotate when asked and after your edits',
@@ -44,6 +52,8 @@ export async function getPrefs(root, env, json = false) {
44
52
  a ? `annotate: ${a.value} — ${ANNOTATE_WHAT[a.value]} (${a.by}, ${a.at})` : `annotate: not recorded — ${ANNOTATE_WHAT.background} (the default)`,
45
53
  prefs.cards ? `cards: ${prefs.cards.value} — ${CARDS_WHAT[prefs.cards.value]} (${prefs.cards.by}, ${prefs.cards.at})` : `cards: not recorded — ${CARDS_WHAT.on} (the default)`,
46
54
  prefs.notify ? `notify: ${prefs.notify.value} — ${NOTIFY_WHAT[prefs.notify.value]} (${prefs.notify.by}, ${prefs.notify.at})` : `notify: not recorded — ${NOTIFY_WHAT.off} (the default)`,
55
+ prefs.nudge ? `nudge: ${prefs.nudge.value} — ${NUDGE_WHAT[prefs.nudge.value]} (${prefs.nudge.by}, ${prefs.nudge.at})` : `nudge: not recorded — ${NUDGE_WHAT.on} (the default)`,
56
+ prefs.drafts ? `drafts: ${prefs.drafts.value} — ${DRAFTS_WHAT[prefs.drafts.value]} (${prefs.drafts.by}, ${prefs.drafts.at})` : `drafts: not recorded — ${DRAFTS_WHAT.background} (the default)`,
47
57
  prefs.coach ? `coach: ${prefs.coach.value} — ${COACH_WHAT[prefs.coach.value]} (${prefs.coach.by}, ${prefs.coach.at})` : `coach: not recorded — ${COACH_WHAT.on} (the default)`,
48
58
  `kept in ${L.prefsFile(dir)} (this clone only; never committed)`,
49
59
  ];
@@ -57,9 +67,9 @@ export async function setCommits(root, value, by, env, now = new Date()) {
57
67
  // @mitigates #person-prefs against #governance-forgery using #prefs-outside-tree -- "Every answer is written under the git directory with the name of the person who gave it."
58
68
  export async function setPref(root, key, value, by, env, now = new Date()) {
59
69
  const L = await prefsLib();
60
- const choices = key === 'commits' || key === 'annotate' || key === 'coach' || key === 'cards' || key === 'notify' ? L.PREF_CHOICES[key] : null;
70
+ const choices = key === 'commits' || key === 'annotate' || key === 'coach' || key === 'cards' || key === 'notify' || key === 'nudge' || key === 'drafts' ? L.PREF_CHOICES[key] : null;
61
71
  if (!choices)
62
- throw new BravosError('usage: bravos prefs set commits <commit|leave|ask> --by "<your name>" | bravos prefs set annotate <background|off> --by "<your name>" | bravos prefs set coach|cards|notify <on|off> --by "<your name>"');
72
+ throw new BravosError('usage: bravos prefs set commits <commit|leave|ask> --by "<your name>" | bravos prefs set annotate|drafts <background|off> --by "<your name>" | bravos prefs set coach|cards|notify|nudge <on|off> --by "<your name>"');
63
73
  if (!choices.includes(value))
64
74
  throw new BravosError(`usage: bravos prefs set ${key} <${choices.join('|')}> --by "<your name>"`);
65
75
  if (!by?.trim())
@@ -74,7 +84,7 @@ export async function setPref(root, key, value, by, env, now = new Date()) {
74
84
  catch (e) {
75
85
  throw new BravosError(e instanceof Error ? e.message : String(e));
76
86
  }
77
- const what = key === 'commits' ? WHAT[value] : key === 'coach' ? COACH_WHAT[value] : key === 'cards' ? CARDS_WHAT[value] : key === 'notify' ? NOTIFY_WHAT[value] : ANNOTATE_WHAT[value];
87
+ const what = key === 'commits' ? WHAT[value] : key === 'coach' ? COACH_WHAT[value] : key === 'cards' ? CARDS_WHAT[value] : key === 'notify' ? NOTIFY_WHAT[value] : key === 'nudge' ? NUDGE_WHAT[value] : key === 'drafts' ? DRAFTS_WHAT[value] : ANNOTATE_WHAT[value];
78
88
  const lines = [`${key}: ${value} — from now on the agent will ${what}`, `recorded in ${file} (this clone only; never committed)`];
79
89
  // On macOS the notifications come through osascript (shown as Script Editor) until the Bravos notifier app is staged.
80
90
  if (key === 'notify' && value === 'on' && process.platform === 'darwin')
@@ -11,7 +11,7 @@ let cached = null;
11
11
  export const principlesLib = () => (cached ??= import(pathToFileURL(join(hooksDir(), 'lib', 'principles.mjs')).href));
12
12
  const today = (now) => now.toISOString().slice(0, 10);
13
13
  // @comment -- "Writes one file inside the repository: every folder on the way must be a real folder (no link), and the file is replaced atomically through a temporary name, so a planted link cannot redirect the write."
14
- function writeInRepo(root, rel, data) {
14
+ export function writeInRepo(root, rel, data) {
15
15
  let dir = realpathSync(root);
16
16
  for (const part of dirname(rel).split(/[\\/]/).filter((p) => p && p !== '.')) {
17
17
  dir = join(dir, part);
@@ -0,0 +1,106 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
3
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { hooksDir } from './paths.js';
6
+ import { BravosError } from './types.js';
7
+ const lib = (name) => import(pathToFileURL(join(hooksDir(), 'lib', name)).href);
8
+ const git = (root, args, env = process.env) => execFileSync('git', args, { cwd: root, env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 30000 }).trim();
9
+ // @comment -- "The open pull requests whose head is a draft branch, asked of GitHub with gh as the person when gh is there and signed in; null when it cannot say, so the branches alone decide. Read-only."
10
+ // @flows #records -> GitHub.API via gh -- "bravos records drafts lists open pull requests (head branch names only) to keep one draft per module"
11
+ export function openDraftPrs(root, env = process.env) {
12
+ try {
13
+ const out = execFileSync('gh', ['pr', 'list', '--state', 'open', '--limit', '200', '--json', 'headRefName,number,url'], { cwd: root, env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 15000 });
14
+ const j = JSON.parse(out);
15
+ return Array.isArray(j) ? j.filter((p) => typeof p?.headRefName === 'string' && p.headRefName.startsWith('bravos/record-')) : null;
16
+ }
17
+ catch {
18
+ return null;
19
+ }
20
+ }
21
+ const RULES = [
22
+ 'How to draft (bravos-records): state only what a stored document, a confirmed intent rule or a person said, and cite it on the line: (SRC-n § Section), (intent: INV-n), (said by <name>).',
23
+ ' What the code does today is (observed: <file>:<line>): not a decision, so it is guidance until the team confirms it.',
24
+ ' Leave "Not a bug" empty unless a document, a confirmed rule or the person says it; never fill it from the code. Leave the decision as the team\'s placeholder when nobody stated one.',
25
+ ' Then bravos records check -C <worktree> until it passes, commit in the worktree, and tell the person. Push and open the pull request only after they say yes.',
26
+ ];
27
+ /** `bravos records drafts [--limit n] [--json]`: what to draft now. */
28
+ export async function draftsList(root, env, limit) {
29
+ const D = await lib('drafts.mjs');
30
+ const prs = openDraftPrs(root, env);
31
+ const q = D.draftQueue(root, { limit, openPrs: prs ?? [] });
32
+ const json = { schema: 'bravos.records-drafts/v1', ...q, github: prs === null ? 'did not answer (gh missing, signed out, or not a GitHub repository): draft branches decide' : 'asked', briefs: q.queue.map((m) => D.draftBrief(root, m)) };
33
+ if (q.state === 'no-ledger')
34
+ return { json, lines: ['records drafts: no module ledger yet. Map the modules first (bravos records ledger propose); drafting works from a ledger a person reviewed.'] };
35
+ if (q.state === 'unreviewed')
36
+ return { json, lines: [`records drafts: the module ledger is ${q.review?.words ?? 'not reviewed'}. Drafting waits until a person has reviewed it in its pull request, so no draft is written for a boundary nobody agreed.`] };
37
+ const lines = [];
38
+ if (q.open.length)
39
+ lines.push(`Waiting for review (one draft per module, never two): ${q.open.map((o) => `${o.name} on ${o.branch}${o.pr ? ' (pull request open)' : ''}`).join('; ')}`);
40
+ if (q.state === 'none') {
41
+ lines.unshift(`records drafts: nothing to draft now: every module the ledger says needs a record has one${q.open.length ? ' or a draft waiting' : ''}.`);
42
+ return { json, lines };
43
+ }
44
+ if (!q.queue.length) {
45
+ lines.unshift(`records drafts: ${q.waiting.length} module${q.waiting.length === 1 ? '' : 's'} need${q.waiting.length === 1 ? 's' : ''} a record, but ${q.open.length} draft${q.open.length === 1 ? '' : 's'} already wait for review (at most ${q.maxOpen} at once). Draft more once those are reviewed.`);
46
+ return { json, lines };
47
+ }
48
+ lines.unshift(`records drafts: draft ${q.queue.length} now (at most ${q.limit} per run, ${q.maxOpen} waiting at once)${q.waiting.length ? `; ${q.waiting.length} more after these: ${q.waiting.map((m) => m.name).join(', ')}` : ''}${prs === null ? '. GitHub did not answer (gh missing, signed out, or not a GitHub repository), so draft branches alone show what waits.' : '.'}`);
49
+ for (const b of json.briefs) {
50
+ lines.push(` ${b.name} (${b.paths.join(', ')}): bravos records draft "${b.name}" → branch ${b.branch}`, ` code: ${b.files.slice(0, 12).join(', ') || 'no files yet'}${b.files.length + b.moreFiles > 12 ? ` and ${b.files.length + b.moreFiles - 12} more` : ''}`, ` cite from the documents: ${b.documents.length ? b.documents.join('; ') : 'no stored document names this module (bravos context list)'}`, ` confirmed intent rules: ${b.intent.length ? b.intent.map((i) => i.id).join(', ') : 'none confirmed yet'}`, ` the ledger says: ${b.why}`);
51
+ }
52
+ lines.push(...RULES);
53
+ return { json, lines };
54
+ }
55
+ /** `bravos records draft "<module>" [--worktree <dir>]`: a branch, a worktree and a skeleton for one module. */
56
+ export async function draftStart(root, module, env, opts = {}) {
57
+ const D = await lib('drafts.mjs');
58
+ const Lg = await lib('ledger.mjs');
59
+ const l = Lg.readLedger(root);
60
+ const want = module.trim().toLowerCase();
61
+ const m = l.modules.find((x) => x.name.toLowerCase() === want || x.key === want);
62
+ if (!l.exists || !m)
63
+ throw new BravosError(`no module "${module}" in the ledger (bravos records ledger)`);
64
+ if (m.needs !== 'yes' || m.records.length)
65
+ throw new BravosError(`${m.name} ${m.records.length ? 'already has a record' : 'is optional in the ledger'}; drafting is for modules that need a record and have none`);
66
+ const prs = openDraftPrs(root, env);
67
+ const q = D.draftQueue(root, { limit: 1000, openPrs: prs ?? [] });
68
+ if (q.state === 'unreviewed')
69
+ throw new BravosError(`the module ledger is ${q.review?.words ?? 'not reviewed'}; drafting waits until a person has reviewed it`);
70
+ const mine = q.open.find((o) => o.key === m.key);
71
+ // @comment -- "One draft per module: a module with a draft branch or an open draft pull request is never drafted again, and no new draft starts while the most allowed already wait for review"
72
+ if (mine)
73
+ throw new BravosError(`${m.name} already has a draft waiting (${mine.branch}${mine.pr ? ', pull request open' : ''}); there is never more than one per module`);
74
+ if (q.open.length >= D.MAX_OPEN)
75
+ throw new BravosError(`${q.open.length} drafts already wait for review (at most ${D.MAX_OPEN} at once): ${q.open.map((o) => o.name).join(', ')}. Draft more once those are reviewed.`);
76
+ const branch = D.draftBranch(m.key);
77
+ const common = git(root, ['rev-parse', '--path-format=absolute', '--git-common-dir'], env);
78
+ const dir = opts.worktree ? (isAbsolute(opts.worktree) ? opts.worktree : resolve(root, opts.worktree)) : join(common, 'bravos', 'drafts', m.key);
79
+ if (existsSync(dir))
80
+ throw new BravosError(`${dir} already exists; remove it (git worktree remove) or pass --worktree <another dir>`);
81
+ let base = 'HEAD';
82
+ try {
83
+ base = git(root, ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'], env);
84
+ }
85
+ catch {
86
+ /* no default branch known: draft from this commit */
87
+ }
88
+ const id = D.nextDraftId(root);
89
+ mkdirSync(dirname(dir), { recursive: true });
90
+ git(root, ['worktree', 'add', '-q', '-b', branch, dir, base], env);
91
+ const rel = `.guardlink/records/${id}-${m.key}.md`;
92
+ const today = (opts.now ?? new Date()).toISOString().slice(0, 10);
93
+ mkdirSync(join(dir, '.guardlink', 'records'), { recursive: true });
94
+ writeFileSync(join(dir, rel), D.draftSkeleton(id, m.name, m.paths, today));
95
+ const brief = D.draftBrief(root, m);
96
+ return [
97
+ `Started ${id} for ${m.name}: ${join(dir, rel)}`,
98
+ ` branch ${branch} off ${base}, in its own worktree (${dir}); this checkout and its branch are untouched.`,
99
+ ` code: ${brief.files.slice(0, 12).join(', ')}${brief.files.length > 12 ? ', …' : ''}`,
100
+ ` cite from the documents: ${brief.documents.length ? brief.documents.join('; ') : 'no stored document names this module'}`,
101
+ ` confirmed intent rules: ${brief.intent.length ? brief.intent.map((i) => `${i.id} ${i.text}`).join('; ') : 'none confirmed yet'}`,
102
+ ...RULES.map((r) => r.replace('<worktree>', dir)),
103
+ ` Before committing, run bravos records ledger refresh -C ${dir} so the ledger's Record column says ${id} draft.`,
104
+ ` On the person's yes: git -C ${dir} push -u origin ${branch}, then gh pr create --head ${branch} --title "${id}: security decision record for ${m.name} (draft for review)". It binds nobody until a code owner approves the pull request.`,
105
+ ];
106
+ }
@@ -0,0 +1,103 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { BravosError } from './types.js';
5
+ import { hooksDir } from './paths.js';
6
+ let cached;
7
+ const lib = () => (cached ??= import(pathToFileURL(join(hooksDir(), 'lib', 'ledger.mjs')).href));
8
+ const GRAPH_NOTE = [
9
+ 'Code graph: this command reads the stored documents, the threat model and the folders, not the routes.',
10
+ ' With the code graph (Team plan), ask codegraph_routes, codegraph_auth_boundary and codegraph_attack_surface in the session and adjust the modules: merge folders that serve one feature, split one that holds two, and add the routes each module answers to its evidence.',
11
+ ' Without it (Free), modules come from folder names and what the documents and annotations say. A feature spread over folders with different names can show as two modules, and code with no annotations yet can be marked optional when it is not: review each boundary before a person does.',
12
+ ];
13
+ function write(root, file, text) {
14
+ const abs = join(root, file);
15
+ mkdirSync(dirname(abs), { recursive: true });
16
+ writeFileSync(abs, text);
17
+ }
18
+ const row = (m) => ` ${m.name} ${m.needs === 'yes' ? 'needs a record' : 'optional'} ${m.status ?? m.record ?? ''} (${m.paths.join(', ')})${m.owner && m.owner !== '—' ? ` owner ${m.owner}` : ''}`;
19
+ /** `bravos records ledger` (list). */
20
+ export async function ledgerList(root) {
21
+ const L = await lib();
22
+ const l = L.readLedger(root);
23
+ if (!l.exists)
24
+ return { lines: [`records ledger: no ${L.LEDGER_FILE} yet. bravos records ledger propose shows a first pass at the modules; --write adds them for review.`], json: { schema: 'bravos.records-ledger/v1', exists: false } };
25
+ const needs = l.modules.filter((m) => m.needs === 'yes');
26
+ return {
27
+ json: { schema: 'bravos.records-ledger/v1', exists: true, review: l.review, problems: l.problems, modules: l.modules },
28
+ lines: [
29
+ `records ledger: ${l.modules.length} module${l.modules.length === 1 ? '' : 's'}, ${l.modules.filter((m) => m.records?.length).length} with records, ${needs.length} need${needs.length === 1 ? 's' : ''} one — ${l.review?.words ?? 'not reviewed'}`,
30
+ ...l.modules.map(row),
31
+ ...l.problems.map((p) => `✗ ${p}`),
32
+ 'Proposed and reviewed by people, never enforced: the ledger holds no pull request.',
33
+ ],
34
+ };
35
+ }
36
+ /** `bravos records ledger propose [--write]`. */
37
+ export async function ledgerPropose(root, writeIt) {
38
+ const L = await lib();
39
+ const p = L.proposeModules(root);
40
+ const lines = [`records ledger propose: ${p.modules.length} candidate module${p.modules.length === 1 ? '' : 's'} from ${p.files} files (features, not one per folder):`];
41
+ for (const m of p.modules)
42
+ lines.push(` ${m.name} ${m.needs === 'yes' ? 'needs a record' : 'optional'} (${m.paths.join(', ')})`, ` why: ${m.why}`, ` evidence: ${m.evidence}`);
43
+ if (p.documentedOnly.length)
44
+ lines.push(`Sections of the stored documents that match no code (a feature not built yet, or named differently in the code; say which): ${p.documentedOnly.map((d) => `${d.id} § ${d.heading}`).join('; ')}`);
45
+ lines.push(...GRAPH_NOTE);
46
+ if (!writeIt) {
47
+ lines.push('Nothing written. Review the list, then run this again with --write; adjust rows with bravos records ledger add / remove.');
48
+ return lines;
49
+ }
50
+ const abs = join(root, L.LEDGER_FILE);
51
+ const before = existsSync(abs) ? readFileSync(abs, 'utf8') : null;
52
+ const merged = L.mergeProposal(before, p.modules);
53
+ write(root, L.LEDGER_FILE, merged.text);
54
+ const r = L.refreshLedger(root);
55
+ if (r)
56
+ write(root, L.LEDGER_FILE, r.text);
57
+ lines.push(before === null ? `Wrote ${L.LEDGER_FILE} with ${merged.added.length} modules.` : `Added ${merged.added.length} module${merged.added.length === 1 ? '' : 's'} to ${L.LEDGER_FILE}; the team's rows are as they were.`, 'It is a proposal: tell the person, and have them review it in a pull request (the same review as a record). Rewrite the Why of each row in their words when they correct it.');
58
+ return lines;
59
+ }
60
+ /** `bravos records ledger add "<Module>" --paths … --needs yes|optional [--why …] [--evidence …]`: adds the row, or replaces the one with that name. */
61
+ export async function ledgerAdd(root, name, o) {
62
+ const L = await lib();
63
+ const paths = (o.paths ?? '').split(',').map((s) => s.trim()).filter(Boolean);
64
+ if (!name || !paths.length || !['yes', 'optional'].includes(o.needs ?? ''))
65
+ throw new BravosError('usage: bravos records ledger add "<module>" --paths "<glob>,<glob>" --needs yes|optional [--why "<what it decides>"] [--evidence "<SRC-n § section; routes>"]');
66
+ const abs = join(root, L.LEDGER_FILE);
67
+ const parsed = L.parseLedger(existsSync(abs) ? readFileSync(abs, 'utf8') : '');
68
+ const probe = L.parseLedger(L.renderLedger([{ name, key: '', paths, needs: o.needs, why: o.why ?? '', owner: '', record: '', evidence: o.evidence ?? '' }]));
69
+ if (probe.problems.length || !probe.modules.length)
70
+ throw new BravosError(probe.problems[0] ?? 'that module does not make a ledger row');
71
+ const m = probe.modules[0];
72
+ const i = parsed.modules.findIndex((x) => x.key === m.key);
73
+ const next = i >= 0 ? parsed.modules.map((x, j) => (j === i ? { ...m, owner: x.owner } : x)) : [...parsed.modules, m];
74
+ write(root, L.LEDGER_FILE, L.renderLedger(next));
75
+ const r = L.refreshLedger(root);
76
+ if (r)
77
+ write(root, L.LEDGER_FILE, r.text);
78
+ return [`${i >= 0 ? 'Updated' : 'Added'} ${m.name} in ${L.LEDGER_FILE}. A person reviews the change in its pull request.`];
79
+ }
80
+ /** `bravos records ledger remove "<Module>"`. */
81
+ export async function ledgerRemove(root, name) {
82
+ const L = await lib();
83
+ const abs = join(root, L.LEDGER_FILE);
84
+ if (!existsSync(abs))
85
+ throw new BravosError(`no ${L.LEDGER_FILE} here`);
86
+ const parsed = L.parseLedger(readFileSync(abs, 'utf8'));
87
+ const key = L.parseLedger(L.renderLedger([{ name, key: '', paths: ['x/**'], needs: 'optional', why: '', owner: '', record: '', evidence: '' }])).modules[0]?.key;
88
+ const next = parsed.modules.filter((m) => m.key !== key);
89
+ if (next.length === parsed.modules.length)
90
+ throw new BravosError(`no module named "${name}" in ${L.LEDGER_FILE}`);
91
+ write(root, L.LEDGER_FILE, L.renderLedger(next));
92
+ return [`Removed ${name} from ${L.LEDGER_FILE}.`];
93
+ }
94
+ /** `bravos records ledger refresh`: the Record and Owner columns, from the records and CODEOWNERS. */
95
+ export async function ledgerRefresh(root) {
96
+ const L = await lib();
97
+ const r = L.refreshLedger(root);
98
+ if (!r)
99
+ return [`records ledger: no ${L.LEDGER_FILE} yet (bravos records ledger propose)`];
100
+ if (r.changed)
101
+ write(root, L.LEDGER_FILE, r.text);
102
+ return [r.changed ? `Refreshed ${L.LEDGER_FILE}: the Record and Owner columns now match the records and CODEOWNERS.` : `${L.LEDGER_FILE} is current.`, ...r.problems.map((p) => `✗ ${p}`)];
103
+ }