@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
@@ -0,0 +1,62 @@
1
+ // @comment -- "bravos record guard, the before-edit hook (Claude Code PreToolUse on Edit, Write, MultiEdit and NotebookEdit; Codex PreToolUse on apply_patch; Cursor preToolUse on Write and Delete; Antigravity PreToolUse on its file tools; opencode and omp through their plugins, which call it before an edit tool): the first edit in a session to a file an adopted security decision record covers is refused once, with the record in full, so the agent reads the team's decision before changing that code; the next attempt goes through. It is run only through the installed CLI (bravos hook record-guard), never from a repository copy. Each agent gets its own answer shape (hooks/lib/agent-io.mjs). Started with --plugin (a plugin's registration), it stays quiet where the repository registers its own guard. Any error, no session id, no adopted record, or a machine without Bravos: the edit goes ahead, with nothing printed or the agent's empty answer."
2
+ import { spawnSync } from 'node:child_process';
3
+ import { cursorRunsOwn, guardAnswer, harnessArg, normalize, repoRunsOwn } from './lib/agent-io.mjs';
4
+ import { audience } from './lib/audience.mjs';
5
+ import { gitCommonDir } from './lib/prefs.mjs';
6
+ import { guardDecision, readSession, writeSession } from './lib/record-guard.mjs';
7
+ import { logWatchEvent } from './lib/snapshot.mjs';
8
+
9
+ const STDIN_WAIT_MS = 3000;
10
+
11
+ async function readPayload() {
12
+ if (process.stdin.isTTY) return {};
13
+ const read = (async () => {
14
+ const chunks = [];
15
+ for await (const c of process.stdin) chunks.push(c);
16
+ return Buffer.concat(chunks).toString('utf8');
17
+ })().catch(() => '');
18
+ const raw = await Promise.race([read, new Promise((r) => setTimeout(() => r(''), STDIN_WAIT_MS).unref())]);
19
+ try {
20
+ const p = JSON.parse(raw);
21
+ return p && typeof p === 'object' ? p : {};
22
+ } catch {
23
+ return {};
24
+ }
25
+ }
26
+
27
+ async function main() {
28
+ const asked = harnessArg(process.argv);
29
+ let harness = asked;
30
+ let out = null;
31
+ try {
32
+ if (process.env.BRAVOS_RECORD_GUARD === 'off') throw new Error('off');
33
+ if (audience(process.env).kind === 'none') throw new Error('off');
34
+ const n = normalize(asked, await readPayload(), process.env);
35
+ harness = n.harness;
36
+ const cwd = n.cwd || process.cwd();
37
+ const top = spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8', timeout: 3000, stdio: ['ignore', 'pipe', 'ignore'] });
38
+ if (top.status !== 0) throw new Error('not a repository');
39
+ const root = top.stdout.trim();
40
+ if (!n.sessionId) throw new Error('no session');
41
+ // Cursor also runs the Claude Code registration; where it has its own, that one answers.
42
+ if (n.viaCursor && cursorRunsOwn(root, 'record-guard')) throw new Error('cursor runs its own');
43
+ // A plugin's registration stays quiet where the repository registers its own guard for this agent, so the record is shown once.
44
+ if (process.argv.includes('--plugin') && repoRunsOwn(root, harness)) throw new Error('the repository runs its own');
45
+ const commonDir = gitCommonDir(root);
46
+ const { refuse, state } = guardDecision({ root, toolInput: n.toolInput, state: readSession(commonDir, n.sessionId) });
47
+ if (refuse) {
48
+ // The refusal counts only once it is recorded: if the state cannot be written, the edit goes ahead rather than being refused for good.
49
+ if (!writeSession(commonDir, n.sessionId, state)) throw new Error('state not written');
50
+ out = guardAnswer(harness, refuse);
51
+ logWatchEvent(root, { summary: `record: first edit of a covered file stopped once so the record is read`, keys: ['bravos-record:read'] });
52
+ }
53
+ } catch {
54
+ out = null;
55
+ }
56
+ // Allowing: the agent's empty answer where it needs one (Cursor blocks an edit on output that is not JSON).
57
+ out ??= guardAnswer(harness, null);
58
+ if (out) process.stdout.write(JSON.stringify(out) + '\n');
59
+ process.exit(0);
60
+ }
61
+
62
+ main();
@@ -39,8 +39,9 @@ function harnessArg(argv, env) {
39
39
  return env.CLAUDE_PROJECT_DIR ? 'claude' : 'other';
40
40
  }
41
41
 
42
- // @comment -- "Whether the script running is the project's own .bravos/hooks/session-start.mjs (compared by real path, so a symlinked checkout still matches); false for the plugin's copy, the user-level copy and this repository's source."
42
+ // @comment -- "Whether the script running is the project's own hook: its .bravos/hooks/session-start.mjs (compared by real path, so a symlinked checkout still matches), or this install's copy run by the hook launcher (bravos hook session-start), which a repository registers in its place. False for the plugin's copy, the user-level copy and this repository's source. The launcher's mark is set in its own process, never read from the environment."
43
43
  function ownCopy(root) {
44
+ if (globalThis[Symbol.for('bravos.hook-launcher')] === true) return true;
44
45
  try {
45
46
  return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(join(root, '.bravos', 'hooks', 'session-start.mjs'));
46
47
  } catch {
@@ -164,8 +165,8 @@ function emit(harness, out, text) {
164
165
  process.exit(0);
165
166
  }
166
167
  if (harness === 'agy') {
167
- // Antigravity's SessionStart output: steps injected before the first model call.
168
- process.stdout.write(JSON.stringify({ injectSteps: [{ systemMessage: text, metadata: { source: 'bravos' } }] }) + '\n');
168
+ // Antigravity's SessionStart output: steps injected before the first model call. Its hooks contract (and the HookSystemMessage proto) wants systemMessage as a nested object; a plain string does not parse and the step is dropped.
169
+ process.stdout.write(JSON.stringify({ injectSteps: [{ systemMessage: { systemMessage: text, metadata: { source: 'bravos' } } }] }) + '\n');
169
170
  process.exit(0);
170
171
  }
171
172
  out.hookSpecificOutput = { hookEventName: 'SessionStart', additionalContext: text };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bugb-technologies/bravos",
3
- "version": "1.24.0",
3
+ "version": "1.26.0",
4
4
  "description": "Skills pack and installer that make Claude Code and Codex power users of guardlink (threat-model-as-code) and cert-x-gen (pentest-as-code).",
5
5
  "keywords": [
6
6
  "security",
@@ -16,7 +16,7 @@
16
16
  "license": "SEE LICENSE IN LICENSE",
17
17
  "type": "module",
18
18
  "bin": {
19
- "bravos": "dist/cli.js"
19
+ "bravos": "dist/bin.js"
20
20
  },
21
21
  "files": [
22
22
  "dist",
@@ -21,6 +21,7 @@ description: "Start here in any repo bravos is installed in: reads the security
21
21
  no `.guardlink/intent.md` yet, business logic, "what matters here", "is this intended?", learning the app → bravos-context (with no intent it drafts one and opens the intake page without waiting; annotation goes on against the draft, and each session asks once until a named person confirms it or declines).
22
22
  "identify / find / list all the threats or vulnerabilities", a security review or audit, "threat-model this codebase", "what could an attacker do here" → bravos-threat-hunt: the code graph and SAST first, every finding recorded in the threat model, then the dashboard and a report drawn from what was recorded. Never answer such a request from reading alone.
23
23
  security design principles, standards or secure coding rules for the team or company, making a repository's rules hold across repositories, a failing `bravos principles check` → bravos-principles (it proposes from the team's documents and confirmed rules; named people adopt each one).
24
+ a security decision, rule or standard for one module or feature, code that carries a comment naming a record (`SDR-n`), a request that goes against a module's adopted rule, something reported as a bug that a record lists as intended, a failing `bravos records check` → bravos-records (before changing a file it asks `bravos records for <file>`; a person adopts a record at their own terminal).
24
25
  coverage, annotating, a worklist in the briefing → bravos-annotate.
25
26
  reachability, blast radius, "is this live", tracing a handler to sinks → bravos-codegraph.
26
27
  before a PR, push for review, or marking a draft ready → bravos-ship.
@@ -0,0 +1,57 @@
1
+ ---
2
+ name: bravos-records
3
+ description: "Map which modules of an application make security decisions (the module ledger), draft records for them in the background for a code owner to review, and read, follow and help write security decision records: one document per module or feature (.guardlink/records/SDR-n-<module>.md) that says what was decided for that code, the rules that follow, why, and what looks like a bug but is not, binding once its text is on the default branch, approved through a code owner's pull-request review (a name typed at the person's own terminal is the weaker fallback). Use before changing code a record covers, when a request goes against a record's rule, when someone says a module's access or security behaviour is a bug, when asked to write down a security decision or standard for one module, when the briefing says there is no module ledger or the after-edit hook says a module has no record, and when `bravos records check` fails."
4
+ ---
5
+ # Bravos records: what was decided for this module, approved by a person
6
+
7
+ A record is the standard for the code it covers. Follow an approved record exactly; help write one only from what the team says; a person, never you, makes it binding: a code owner approving the pull request that brings it to the default branch, or, as the weaker fallback, a person typing their name.
8
+
9
+ ## When
10
+
11
+ - You are about to change code and the briefing lists security decision records, or a file carries a comment naming one (`SDR-n`).
12
+ - The person asks for something a record's rule forbids, or reports as a bug something a record lists under "Not a bug".
13
+ - The person asks to write down a security decision, rule or standard for one module or feature, or `bravos records check` fails.
14
+ - Reading and following records is on every plan. Writing a new one and adopting it are on the Team plan (the briefing's `Plan:` line); on Free say so with the trial command, `bravos account activate`. Rules for the whole company are bravos-principles; rules for the whole application are bravos-context.
15
+
16
+ ## Do
17
+
18
+ 1. Before changing a file, ask which record covers it: `bravos records for <file>`. In Claude Code, Codex, Cursor, Antigravity, opencode and omp the first edit in a session to a covered file is refused once with the record in full: that is Bravos, not an error. Read the record, then make the edit again, and it goes through. Read each record it names in full (the file under `.guardlink/records/`) and follow it: every rule, and everything under "Not a bug" is intended behaviour, not a defect to fix. Only an approved record binds; for a draft, tell the person it binds nobody yet and ask how they want to proceed. A record this branch edits is a proposal: the default branch's text still binds until the pull request is approved and merged.
19
+ 2. When what you are asked to do would break a rule, stop before editing. Tell the person which rule (its id and its words), how it was approved (`bravos records show SDR-n`), and that the change goes against it; ask whether they want to change the decision. Do not make the change on your own reading of the request.
20
+ 3. If they still want the change and the record stays as it is, make it and record the break where it happens: an `@exposes` of the rule's threat on that code, its description starting with the rule ("SDR-3 R1 broken: sales can open the margin report, asked for by <their name>"), with `@audit` beside it. Tell them `bravos rules` now shows the rule as unguarded and that it stays open until the code is fixed or the record is changed and adopted again. When asked to link a possible conflict (`bravos records conflicts`, or the dashboard's Decision records view, gives its key), read it with `bravos records conflicts --json`, check in the code that it really goes against that rule, and if it does record it the same way: an `@exposes` of the rule's threat at that place, with `@audit`, keeping the original claim as it is; if it does not, tell the person, who may dismiss it at their own terminal. Never dismiss one yourself.
21
+ 4. Map the modules once per repository. When the briefing says there is no module ledger, offer once to map them; on a yes run `bravos records ledger propose`, check each proposed module against the code and what the person tells you (on the Team plan also ask the code graph: `codegraph_routes`, `codegraph_auth_boundary`, `codegraph_attack_surface`, and merge or split modules by feature; without the graph, say that boundaries come from folders, documents and annotations only), then `--write`, fix rows with `bravos records ledger add` or `remove`, and rewrite each Why in their words. Tell them it is a proposal a person reviews in its pull request, never enforced. When the after-edit hook says a module needs a record and has none, or no record covers security-relevant code you are changing, look for a decision already written down (`bravos context list`, `docs/`, the README, `.guardlink/intent.md`), tell the person in one line, say the company principles and the application's rules still apply, and offer to draft one. Never copy principles into a record. Carry on with their request; a missing record never blocks it.
22
+ 5. To draft a record, gather what was decided from exactly three places and nothing else: what the person tells you in this conversation, a document that says it (`SRC-n` and the section), and rules people confirmed in `.guardlink/intent.md`. Cite each on its line: `(said by <name>)`, `(SRC-n § Section)`, `(intent: INV-n)`. When the decision is unclear, ask one question; never fill a gap with your own view of good practice. In the background (the briefing's Background drafting line, Team plan), the code is a fourth source, as observation only: run `bravos records drafts`, draft only the modules it lists, each with `bravos records draft "<module>"`, which starts its own branch and worktree (never switch the person's branch). A rule read from the code is `(observed: <file>:<line>)`, what the code does today and not a decision, so it is guidance; Not a bug stays empty unless a document, a confirmed rule or the person says it, never from code; the decision stays the team's placeholder when nobody stated one. Then `bravos records check -C <worktree>` until it passes and `bravos records ledger refresh -C <worktree>`, commit there, push nothing, and in one line ask the person whether to open each draft's pull request.
23
+ 6. In the foreground, run `bravos records new "<module>" --paths "<glob>,<glob>"` (the code the record covers); it writes the skeleton with the next free id. Fill it in, in the person's words: the decision in two or three sentences; each rule as one sentence someone can check, marked `enforced` when a test could show it broken at a place in the code and `guidance` otherwise; why; and under "Not a bug" each behaviour that looks wrong and is the decision.
24
+ 7. Run `bravos records check` and fix what it reports in the record you wrote.
25
+ 8. Tell the person: "This is a draft and binds nobody yet. Its observed rules are what the code does today: confirm or remove each, and tell me what looks wrong here and is intended, for Not a bug." On their yes, open its pull request (`git push -u origin <branch>`, then `gh pr create`), and say: "It is approved when it reaches the default branch through a pull request that a code owner reviews." `bravos records check` prints a `review:` line saying whether the default branch requires a code owner's review (it asks GitHub with `gh` when it is signed in). When that line says not enforced or unknown, offer once to add CODEOWNERS lines for the records: show them with `bravos records codeowners --owner <@user or @org/team>`, and write them with `--yes` only after the person says yes and names the owner; never write CODEOWNERS unasked. Requiring that review on the branch is a repository setting only an admin changes; say so, do not change it. Where there is no GitHub review, the fallback is a typed name: `bravos review records` (Team plan) or `bravos records adopt SDR-n` in their own terminal; say it is weaker, since a typed name shows who said so, not that anyone reviewed it. Do not wait: carry on with what else was asked.
26
+ 9. For each enforced rule, put it in the threat model, then give it a test. In `.guardlink/definitions.*`, reusing ids and never redefining one: one `@threat` carrying the reference `record:SDR-n` and a description that starts with the rule's id, e.g. `@threat Sales opens the margin report (#sdr-margin-report-admin-only) [high] cwe:CWE-862 record:SDR-3 -- "SDR-3 R1: only admins open the margin report"`. Then follow `{{SKILLS_ROOT}}/bravos-annotate/SKILL.md` over the record's paths: `@mitigates` where the code upholds the rule, `@exposes` where it does not. When adoption reports that a rule's threat has no replay test, follow `{{SKILLS_ROOT}}/bravos-templatize/SKILL.md` to write one bound to that threat, so bravos-prove can confirm a break.
27
+ 10. Point the code at its record. On each file the record covers that makes the decisions it describes, add `@comment -- "Security decision record SDR-n governs this file: .guardlink/records/SDR-n-<module>.md. Read it before changing access here."` where the briefing's `Annotations:` line says annotations go.
28
+ 11. Run `guardlink validate .` and `bravos rules`, which lists each rule of each record with its status. Ask before committing: "Commit the record, the definitions and the annotations now, or leave them for you to review?" (a `Commits:` line in the briefing is their standing answer). A person's adoption file under `.guardlink/records-answers/`, CODEOWNERS lines they said yes to, and the ledger (`bravos records ledger refresh` first, so its Record column is current) are committed with the record.
29
+ 12. When the pre-PR gate holds a pull request for a record rule, tell the person the three ways it clears: fix the code; a person approves a dated exception for that rule and place at their own terminal (`bravos records except SDR-n R1 --where "<glob>" --reason "<why>" --until YYYY-MM-DD`); or they change the record (edit it in their words, run `bravos records check`) and the new text is approved. An edited record holds only the branch that edits it: when the default branch requires a code owner's review, the gate notes it and GitHub holds the merge until a code owner approves; otherwise that branch waits until a person adopts the new text by name. Other branches keep following the default branch's text. `bravos records gaps` lists modules with security claims and no record.
30
+
31
+ ## Never
32
+
33
+ - Adopt or approve a record, approve a pull request, approve an exception, change branch protection, write CODEOWNERS without the person's yes, write or edit a file under `.guardlink/records-answers/` or `.guardlink/records-exceptions.json`, answer the review page for a person, or fake a terminal to run `bravos records adopt` or `bravos records except`.
34
+ - Write the ledger's Record or Owner column by hand (Bravos writes them), call a module reviewed, or mark one optional to stop the nudge.
35
+ - Write a decision, a rule or a "Not a bug" line the team did not state, or present your own view of good practice as their decision.
36
+ - Fill "Not a bug" from the code, mark an observed rule enforced, start more drafts than `bravos records drafts` lists, or push a draft or open its pull request before the person says yes.
37
+ - Change an adopted record without being asked, or weaken a rule or narrow its paths to make a change pass.
38
+ - Treat a draft as binding, or "fix" behaviour an adopted record lists under "Not a bug".
39
+ - Write `@accepts`, `@entitles` or `@confirmed` for a record's rule.
40
+ - Put a secret, a token or a path on someone's machine in a record.
41
+
42
+ ## Done when
43
+
44
+ - Every file you changed was checked with `bravos records for`, and you followed each adopted record it named or raised the conflict with the person before editing.
45
+ - A record you drafted passes `bravos records check`, says only what the team stated, and the person was told it is a draft and how to adopt it.
46
+ - Each enforced rule has a threat carrying `record:SDR-n`, `guardlink validate .` exits 0, and a break you were told to make is recorded as an open exposure with `@audit`.
47
+
48
+ ## What it leaves for the next skill
49
+
50
+ - The rule threat ids, for bravos-annotate (where each can break) and bravos-templatize (a test for each enforced rule). After an edit, a new exposure of a rule's threat or a removed check of one shows as a decision-record card; code with security claims that no record covers gets one line per file per session.
51
+ - `bravos rules` shows each record rule's status: holds, unguarded, broken, or not placed.
52
+
53
+ ## Go deeper
54
+
55
+ - `{{SKILLS_ROOT}}/bravos-annotate/SKILL.md` — recording where a threat can break.
56
+ - `{{SKILLS_ROOT}}/bravos-principles/SKILL.md` — rules for every repository, not one module.
57
+ - `{{SKILLS_ROOT}}/bravos-context/SKILL.md` — the application's intent and the stored design documents.
@@ -94,6 +94,19 @@ code { font: 12.5px var(--mono); background: var(--raised); border: 1px solid va
94
94
  .sites .state.broken { color: var(--sev-critical); }
95
95
  .sites .state.retest { color: var(--review); }
96
96
  .sites .state.held { color: var(--resolved); }
97
+ .findings { width: 100%; border-collapse: collapse; margin: 6px 0 18px; font-size: 12.5px; background: var(--panel); border: 1px solid var(--border); border-radius: var(--radius); }
98
+ .findings th { text-align: left; font: 600 11px/1.2 var(--mono); text-transform: uppercase; letter-spacing: .05em; color: var(--fg-muted); padding: 8px 10px; border-bottom: 1px solid var(--border); }
99
+ .findings td { padding: 7px 10px; border-bottom: 1px solid var(--border); vertical-align: top; }
100
+ .findings tr:last-child td { border-bottom: 0; }
101
+ .findings .where { font-family: var(--mono); overflow-wrap: anywhere; }
102
+ .findings .muted, .sast-h .muted { color: var(--fg-muted); }
103
+ .sev { font: 600 11px/1 var(--mono); text-transform: uppercase; }
104
+ .sev.error, .sev.critical, .sev.high { color: var(--sev-critical); }
105
+ .sev.warning, .sev.medium { color: var(--sev-medium); }
106
+ .reach.yes { color: var(--sev-critical); font-weight: 600; }
107
+ .sast-h { margin: 18px 0 4px; font-size: 14px; }
108
+ .sites li.conflict { margin-top: 10px; padding-top: 8px; border-top: 1px dashed var(--border); }
109
+ .sites li.conflict:first-child { margin-top: 0; padding-top: 0; border-top: 0; }
97
110
  </style>
98
111
  </head>
99
112
  <body>
@@ -110,6 +123,7 @@ code { font: 12.5px var(--mono); background: var(--raised); border: 1px solid va
110
123
  <script type="application/json" id="bravos-pages-css">__BRAVOS_PAGES_CSS__</script>
111
124
  <script type="application/json" id="bravos-pages-js">__BRAVOS_PAGES_JS__</script>
112
125
  <script type="application/json" id="bravos-rules">__BRAVOS_RULES__</script>
126
+ <script type="application/json" id="bravos-sast">__BRAVOS_SAST__</script>
113
127
  <script>
114
128
  (() => {
115
129
  const DATA = JSON.parse(document.getElementById('bravos-data').textContent);
@@ -120,7 +134,7 @@ code { font: 12.5px var(--mono); background: var(--raised); border: 1px solid va
120
134
  return n;
121
135
  };
122
136
  // Commands inside a note are shown as code; everything is set as text, never as markup.
123
- const COMMAND = /(bravos setup --tools -y|bravos setup --codegraph|bravos graph build \.|bravos account activate|bravos dashboard|guardlink validate \.|\/bravos-[a-z]+)/g;
137
+ const COMMAND = /(bravos setup --tools -y|bravos setup --codegraph|bravos graph build \.|bravos account activate|bravos sast run|bravos sast status|bravos sast candidates|bravos records conflicts(?: dismiss)?|bravos dashboard|guardlink validate \.|\/bravos-[a-z]+)/g;
124
138
  const prose = (text) => {
125
139
  const p = el('p');
126
140
  String(text).split(COMMAND).forEach((part, k) => p.append(k % 2 ? el('code', {}, part) : part));
@@ -606,6 +620,189 @@ code { font: 12.5px var(--mono); background: var(--raised); border: 1px solid va
606
620
  },
607
621
  });
608
622
 
623
+ // Decision records: each module's security decision record (.guardlink/records/), rule by rule, with its state, who
624
+ // adopted it, where the code enforces each enforced rule and what testing has shown. Bravos computes this (src/rules.ts
625
+ // records) and it is drawn here as text. Shown only when the repository has records or something to say about them.
626
+ // @comment -- "The Decision records view: one card per record rule with its status (broken, unguarded, holds, guidance…), the record and module, the rule's words, whether the record is adopted and by whom, and each place the rule is enforced or has no control, a place under a person's exception marked with its end day. All text comes from the rules document and is set as text, never as markup."
627
+ if (RULES && ((Array.isArray(RULES.records) && RULES.records.length) || RULES.recordsNote)) views.push({
628
+ id: 'decision-records',
629
+ label: 'Decision records',
630
+ build(section) {
631
+ const LABEL = { broken: 'broken', 'retest-due': 'retest due', holds: 'holds', unguarded: 'unguarded', 'guarded-untested': 'guarded, untested', 'not-placed': 'not placed', guidance: 'guidance' };
632
+ const SITE = { check: 'enforced at', gap: 'no control at', grant: 'granted in' };
633
+ const STATE = { broken: 'a test got through', retest: 'the code changed since it was tested', held: 'a test was refused', untested: 'not tested' };
634
+ const wrap = el('div', { class: 'rules' });
635
+ const inner = el('div', { class: 'rules-inner' });
636
+ const lead = prose(RULES.recordsNote || '');
637
+ lead.className = 'rules-lead';
638
+ inner.append(lead, prose('Each module\'s security decision record, adopted by named people with bravos records adopt or on bravos review records and kept in .guardlink/records/. Coding agents read the record before they change the code it covers; an enforced rule is tested, and the pre-PR gate holds a change that breaks it unless a person approved an exception.'));
639
+ for (const r of RULES.records || []) {
640
+ const status = LABEL[r.status] ? r.status : 'not-placed';
641
+ const card = el('article', { class: 'rule ' + status });
642
+ const head = el('div', { class: 'rule-head' });
643
+ head.append(el('span', { class: 'pill ' + status }, LABEL[status]), el('span', { class: 'rule-id' }, r.id));
644
+ if (r.recordState !== 'adopted') head.append(el('span', { class: 'pill' }, r.recordState));
645
+ card.append(head, el('p', { class: 'rule-text' }, r.text || ''), el('p', { class: 'rule-why' }, r.why || ''));
646
+ const meta = el('ul', { class: 'rule-meta' });
647
+ const fact = (label, value) => {
648
+ if (!value) return;
649
+ const li = el('li');
650
+ li.append(el('b', {}, label + ' '), value);
651
+ meta.append(li);
652
+ };
653
+ fact('module', r.module);
654
+ fact('adopted by', (r.adoptedBy || []).map((a) => a.by + ' (' + a.date + ')').join(', '));
655
+ fact('threat', r.threat || '');
656
+ card.append(meta);
657
+ if (Array.isArray(r.sites) && r.sites.length) {
658
+ const sites = el('ul', { class: 'sites' });
659
+ for (const st of r.sites) {
660
+ const li = el('li');
661
+ li.append(el('span', {}, SITE[st.kind] || 'at'), el('span', { class: 'where' }, String(st.file) + (st.line ? ':' + st.line : '')));
662
+ if (st.exception) li.append(el('span', { class: 'state retest' }, 'under an exception until ' + st.exception.until + (st.exception.by ? ', approved by ' + st.exception.by : '')));
663
+ else if (st.state) li.append(el('span', { class: 'state ' + st.state }, STATE[st.state] || st.state));
664
+ if (st.control) li.append(el('span', {}, 'by #' + st.control));
665
+ sites.append(li);
666
+ }
667
+ card.append(sites);
668
+ }
669
+ inner.append(card);
670
+ }
671
+ // @comment -- "Possible conflicts, per record: open exposures and SAST findings in the record's paths whose weakness bears on one of its rules, each with the reason it was matched and the two ways to act on it. They are suggestions for a person: drawn apart from the rule cards, they never change a rule's status. Dismissed ones are folded below, with who dismissed them and why. All text is set as text."
672
+ const conflicts = Array.isArray(RULES.conflicts) ? RULES.conflicts : [];
673
+ if (conflicts.length) {
674
+ inner.append(el('h3', { class: 'sast-h' }, 'Possible conflicts'));
675
+ inner.append(prose((RULES.conflictsNote || '') + ' Each is a suggestion for a person, matched by the kind of weakness and the record\'s paths; it never marks a rule broken or unguarded and never holds a pull request. A rule is broken only when a test got through.'));
676
+ const byRecord = new Map();
677
+ for (const c of conflicts) {
678
+ if (!byRecord.has(c.record)) byRecord.set(c.record, []);
679
+ byRecord.get(c.record).push(c);
680
+ }
681
+ for (const [record, list] of byRecord) {
682
+ const open = list.filter((c) => !c.dismissed);
683
+ const card = el('article', { class: 'rule unguarded' });
684
+ const head = el('div', { class: 'rule-head' });
685
+ head.append(el('span', { class: 'pill unguarded' }, open.length + ' possible'), el('span', { class: 'rule-id' }, record));
686
+ card.append(head);
687
+ const items = el('ul', { class: 'sites' });
688
+ for (const c of open) {
689
+ const li = el('li', { class: 'conflict' });
690
+ li.append(el('span', { class: 'pill' }, c.source === 'sast' ? 'SAST' : 'exposure'), el('span', { class: 'rule-id' }, c.record + ' ' + c.rule), el('span', {}, c.what), el('span', { class: 'where' }, c.file + (c.line ? ':' + c.line : '')));
691
+ items.append(li);
692
+ const why = el('li');
693
+ why.append(el('span', {}, 'why: ' + c.reason));
694
+ items.append(why);
695
+ const act = el('li');
696
+ act.append(el('span', {}, 'link it: ask your agent to "link records conflict ' + c.key + '" · not a conflict:'), el('code', {}, 'bravos records conflicts dismiss ' + c.key + ' --reason "<why>"'));
697
+ items.append(act);
698
+ }
699
+ card.append(items);
700
+ const gone = list.filter((c) => c.dismissed);
701
+ if (gone.length) {
702
+ const d = el('details');
703
+ d.append(el('summary', {}, gone.length + ' dismissed'));
704
+ const ul = el('ul', { class: 'sites' });
705
+ for (const c of gone) {
706
+ const li = el('li');
707
+ li.append(el('span', { class: 'rule-id' }, c.record + ' ' + c.rule), el('span', {}, c.what), el('span', { class: 'where' }, c.file + (c.line ? ':' + c.line : '')), el('span', {}, 'dismissed by ' + c.dismissed.by + ' on ' + c.dismissed.at + ': ' + c.dismissed.reason));
708
+ ul.append(li);
709
+ }
710
+ d.append(ul);
711
+ card.append(d);
712
+ }
713
+ inner.append(card);
714
+ }
715
+ }
716
+ wrap.append(inner);
717
+ section.append(wrap);
718
+ },
719
+ });
720
+
721
+ // SAST: the newest bravos-sast run, finding by finding, so a person who ran it can read it here. Bravos copies only
722
+ // named fields onto the page (src/dashboard-sast.ts) and withholds anything that looks like a credential; a secret is
723
+ // shown by its type and place, never its value. On the Free plan, or with no run yet, the view is one note.
724
+ // @comment -- "The SAST view: the run's age and commit, counts by class and severity, then the findings joined to a GuardLink claim, those not in the threat model yet, dependencies and secrets, reached ones first, each with severity, rule, title, file:line, whether it is reached (with the analyzer's reason) and the claim it joins; agent-configuration findings in one line. Every value is set as text, never as markup."
725
+ const SAST = JSON.parse(document.getElementById('bravos-sast').textContent);
726
+ if (SAST || (DATA.sast && DATA.sast.note)) views.push({
727
+ id: 'sast',
728
+ label: 'SAST',
729
+ build(section) {
730
+ const st = DATA.sast || {};
731
+ if (!SAST) {
732
+ section.append(note(st.state === 'locked' ? 'SAST is on the Team plan' : 'No SAST run yet', st.note || 'bravos sast run analyzes the repository; then run bravos dashboard again.'));
733
+ return;
734
+ }
735
+ const wrap = el('div', { class: 'rules' });
736
+ const inner = el('div', { class: 'rules-inner' });
737
+ const lead = prose(st.note || '');
738
+ lead.className = 'rules-lead';
739
+ inner.append(lead);
740
+ const facts = el('ul', { class: 'rule-meta' });
741
+ const fact = (label, value) => {
742
+ if (value === null || value === undefined || value === '') return;
743
+ const li = el('li');
744
+ li.append(el('b', {}, label + ' '), String(value));
745
+ facts.append(li);
746
+ };
747
+ fact('run', SAST.run);
748
+ fact('commit', SAST.sha);
749
+ fact('behind HEAD', SAST.staleCommits === null ? 'not known' : SAST.staleCommits + ' commit' + (SAST.staleCommits === 1 ? '' : 's'));
750
+ fact('analyzer', SAST.analyzer);
751
+ fact('code graph', SAST.graph);
752
+ fact('by class', Object.entries(SAST.byClass || {}).map(([k, v]) => k.replace(/_/g, ' ') + ' ' + v).join(', '));
753
+ fact('by severity', Object.entries(SAST.bySeverity || {}).map(([k, v]) => k + ' ' + v).join(', '));
754
+ if (SAST.suppressed) fact('suppressed', SAST.suppressed);
755
+ inner.append(facts);
756
+ const reachWord = (r) => (r.reachable === true ? 'reached' : r.reachable === false ? 'not reached' : 'not known');
757
+ const table = (title, rows, extra) => {
758
+ inner.append(el('h3', { class: 'sast-h' }, title + ' (' + rows.length + ')'));
759
+ if (!rows.length) {
760
+ inner.append(el('p', { class: 'muted' }, 'None in this run.'));
761
+ return;
762
+ }
763
+ const t = el('table', { class: 'findings' });
764
+ const head = el('tr');
765
+ for (const h of ['severity', 'finding', 'where', 'reached', extra.label]) head.append(el('th', {}, h));
766
+ t.append(head);
767
+ for (const r of rows) {
768
+ const tr = el('tr');
769
+ tr.append(el('td', { class: 'sev ' + String(r.severity || '') }, r.severity || ''));
770
+ const what = el('td');
771
+ what.append(el('div', {}, r.title || r.rule || ''), el('div', { class: 'muted' }, r.rule || ''));
772
+ tr.append(what);
773
+ const where = el('td', { class: 'where' }, (r.file || '') + (r.line ? ':' + r.line : ''));
774
+ if (r.function) where.append(el('div', { class: 'muted' }, r.function));
775
+ tr.append(where);
776
+ const reach = el('td');
777
+ reach.append(el('div', { class: 'reach ' + (r.reachable === true ? 'yes' : '') }, reachWord(r)), el('div', { class: 'muted' }, r.reach || ''));
778
+ tr.append(reach, el('td', {}, extra.value(r)));
779
+ t.append(tr);
780
+ }
781
+ inner.append(t);
782
+ };
783
+ table('Joined to the threat model', SAST.joined || [], { label: 'claim', value: (r) => r.claim || '' });
784
+ table('Not in the threat model yet', SAST.unjoined || [], { label: 'next', value: () => 'annotate it (/bravos-annotate)' });
785
+ table('Dependencies', SAST.dependencies || [], { label: 'vulnerable function', value: (r) => r.vulnerableFunction + (r.devOnly ? ' (dev only)' : '') });
786
+ inner.append(el('h3', { class: 'sast-h' }, 'Secrets (' + (SAST.secrets || []).length + ')'));
787
+ if ((SAST.secrets || []).length) {
788
+ inner.append(el('p', { class: 'muted' }, 'Shown by type and place only; the value never reaches this page.'));
789
+ const t = el('table', { class: 'findings' });
790
+ const head = el('tr');
791
+ for (const h of ['type', 'where', 'in git history', 'what to do']) head.append(el('th', {}, h));
792
+ t.append(head);
793
+ for (const s of SAST.secrets) {
794
+ const tr = el('tr');
795
+ tr.append(el('td', {}, s.type || s.rule || ''), el('td', { class: 'where' }, (s.file || '') + (s.line ? ':' + s.line : '')), el('td', {}, s.inHistory ? 'yes' : 'no'), el('td', {}, s.remediation || ''));
796
+ t.append(tr);
797
+ }
798
+ inner.append(t);
799
+ } else inner.append(el('p', { class: 'muted' }, 'None in this run.'));
800
+ if (SAST.agentConfig && SAST.agentConfig.count) inner.append(el('p', { class: 'muted' }, SAST.agentConfig.count + ' agent-configuration finding' + (SAST.agentConfig.count === 1 ? '' : 's') + ' (' + SAST.agentConfig.rules.join(', ') + '): bravos sast candidates --all lists them.'));
801
+ wrap.append(inner);
802
+ section.append(wrap);
803
+ },
804
+ });
805
+
609
806
  // Code graph: the seven pages the Bravos VS Code extension draws (Map, Owners & History, Coupling, Trust,
610
807
  // Attack surface, Entry points, Links), vendored unchanged and run in their own sandboxed frame. In the editor
611
808
  // a page asks its host for data; here the host is the small script below, which answers from the graph's
@@ -1,8 +1,55 @@
1
1
  // bravos (managed by bravos init/sync; edits are kept, bravos sync --force replaces them)
2
2
  // @comment -- "omp extension: omp runs no Claude Code or Codex hooks, so this does bravos's session start itself. On session_start it runs the repo's .bravos/hooks briefing code in-process (read-only guardlink, git and gh facts), shows the banner as a widget above the editor, and on the first prompt removes the widget and hands the briefing to the model as a hidden custom message. On a machine without Bravos (hooks/lib/audience.mjs) it shows the invitation instead, and hands over only the invitation's instruction. Never throws into omp."
3
- import { join } from 'node:path';
3
+ import { execFile } from 'node:child_process';
4
+ import { existsSync } from 'node:fs';
5
+ import { homedir } from 'node:os';
6
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
4
7
  import { pathToFileURL } from 'node:url';
5
8
 
9
+ // @comment -- "Asks the installed CLI (bravos hook <name>, never a repository copy) about one edit, with the payload on stdin; its last output line is the answer. Bounded to 8 seconds and fail-open: no bravos on PATH, an error, a timeout or output that is not JSON all read as no answer, so the edit goes ahead."
10
+ // @flows #records -> #hook-launcher via stdin -- "The omp plugin hands each edit tool's input to bravos hook record-guard or cards: a fixed argv (no shell), the payload only on stdin, the answer read as JSON"
11
+ const askBravos = (name, harness, payload, cwd) =>
12
+ new Promise((done) => {
13
+ try {
14
+ const child = execFile('bravos', ['hook', name, '--harness', harness], { cwd, timeout: 8000, maxBuffer: 1024 * 1024 }, (err, stdout) => {
15
+ try {
16
+ done(err ? null : JSON.parse(String(stdout).trim().split('\n').pop() || '{}'));
17
+ } catch {
18
+ done(null);
19
+ }
20
+ });
21
+ child.on('error', () => done(null));
22
+ child.stdin?.on('error', () => {});
23
+ child.stdin?.end(JSON.stringify(payload));
24
+ } catch {
25
+ done(null);
26
+ }
27
+ });
28
+
29
+ // The repository root above a folder (the first with .git), so the checks below work from a subfolder too.
30
+ const repoRoot = (dir) => {
31
+ let d = resolve(dir);
32
+ for (;;) {
33
+ if (existsSync(join(d, '.git'))) return d;
34
+ const up = dirname(d);
35
+ if (up === d) return null;
36
+ d = up;
37
+ }
38
+ };
39
+
40
+ // Paths an edit tool names, made absolute against the folder it ran in (omp also allows ~).
41
+ const absolute = (input, cwd) => {
42
+ if (!input || typeof input !== 'object') return {};
43
+ const fix = (p) => (typeof p !== 'string' || !p ? p : p.startsWith('~/') ? join(homedir(), p.slice(2)) : isAbsolute(p) ? p : resolve(cwd, p));
44
+ const out = { ...input };
45
+ for (const k of ['path', 'filePath', 'file_path']) if (k in out) out[k] = fix(out[k]);
46
+ if (Array.isArray(out.paths)) out.paths = out.paths.map(fix);
47
+ return out;
48
+ };
49
+
50
+ // omp 18's file tools: edit (path or paths; in its patch modes the patch text in input), write { path }, ast_edit { paths }.
51
+ const EDIT_TOOLS = new Set(['edit', 'write', 'ast_edit']);
52
+
6
53
  export default function bravos(pi) {
7
54
  let pending = null;
8
55
  let delivered = false;
@@ -65,6 +112,43 @@ export default function bravos(pi) {
65
112
  pi.on('session_start', start);
66
113
  pi.on('session_switch', start);
67
114
 
115
+ // @comment -- "The same protection as Claude Code and Codex around each edit (records round two): before an edit tool runs, the record guard (bravos hook record-guard) may refuse the first edit in a session to a file a security decision record covers, once, with the record; omp blocks the call on { block: true, reason } and gives the model the reason as the tool's error. After it runs, the cards and the no-record nudge (bravos hook cards) are appended to the tool result. omp blocks a tool whose tool_call handler throws or takes over 30 seconds, so every step is caught and bounded to 8 seconds: any error and the edit goes ahead."
116
+ const payload = (event, ctx, sessionId) => ({ session_id: sessionId, cwd: ctx?.cwd ?? process.cwd(), tool_name: String(event?.toolName ?? ''), tool_input: absolute(event?.input, ctx?.cwd ?? process.cwd()) });
117
+ const sessionOf = (ctx) => {
118
+ try {
119
+ return ctx?.sessionManager?.getSessionId?.() ?? null;
120
+ } catch {
121
+ return null;
122
+ }
123
+ };
124
+ pi.on('tool_call', async (event, ctx) => {
125
+ try {
126
+ const sessionId = sessionOf(ctx);
127
+ if (!EDIT_TOOLS.has(String(event?.toolName))) return undefined;
128
+ const root = repoRoot(ctx?.cwd ?? process.cwd());
129
+ if (!root || !existsSync(join(root, '.guardlink', 'records'))) return undefined;
130
+ const a = await askBravos('record-guard', 'omp', payload(event, ctx, sessionId), root);
131
+ if (a?.decision === 'deny' && typeof a.reason === 'string' && a.reason) return { block: true, reason: a.reason };
132
+ } catch {
133
+ /* fail open */
134
+ }
135
+ return undefined;
136
+ });
137
+ pi.on('tool_result', async (event, ctx) => {
138
+ try {
139
+ const sessionId = sessionOf(ctx);
140
+ if (event?.isError || !EDIT_TOOLS.has(String(event?.toolName))) return undefined;
141
+ const root = repoRoot(ctx?.cwd ?? process.cwd());
142
+ if (!root || !existsSync(join(root, '.guardlink'))) return undefined;
143
+ const a = await askBravos('cards', 'omp', payload(event, ctx, sessionId), root);
144
+ const note = typeof a?.additionalContext === 'string' ? a.additionalContext : '';
145
+ if (!note) return undefined;
146
+ return { content: [...(Array.isArray(event.content) ? event.content : []), { type: 'text', text: note }] };
147
+ } catch {
148
+ return undefined;
149
+ }
150
+ });
151
+
68
152
  pi.on('before_agent_start', async (_event, ctx) => {
69
153
  if (delivered) return undefined;
70
154
  delivered = true;
@@ -1,8 +1,55 @@
1
1
  // bravos (managed by bravos init/sync; edits are kept, bravos sync --force replaces them)
2
2
  // @comment -- "opencode 2.x plugin (default export { id, setup }): opencode runs no Claude Code or Codex hooks, so this does bravos's session start itself. setup() runs the repo's .bravos/hooks briefing code in-process (read-only guardlink, git and gh facts) and registers session hooks that append the briefing to the system prompt of each model request and of compaction. Each model request also carries the Bravos card with the instruction to open the agent's first reply with it, once (opencode's plugin can draw nothing in the transcript itself); compaction gets the briefing only. On a machine without Bravos (hooks/lib/audience.mjs) the requests carry only the invitation and its instruction, and compaction nothing. Never throws into opencode."
3
- import { join } from 'node:path';
3
+ import { execFile } from 'node:child_process';
4
+ import { existsSync } from 'node:fs';
5
+ import { homedir } from 'node:os';
6
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
4
7
  import { pathToFileURL } from 'node:url';
5
8
 
9
+ // @comment -- "Asks the installed CLI (bravos hook <name>, never a repository copy) about one edit, with the payload on stdin; its last output line is the answer. Bounded to 8 seconds and fail-open: no bravos on PATH, an error, a timeout or output that is not JSON all read as no answer, so the edit goes ahead."
10
+ // @flows #records -> #hook-launcher via stdin -- "The opencode plugin hands each edit tool's input to bravos hook record-guard or cards: a fixed argv (no shell), the payload only on stdin, the answer read as JSON"
11
+ const askBravos = (name, harness, payload, cwd) =>
12
+ new Promise((done) => {
13
+ try {
14
+ const child = execFile('bravos', ['hook', name, '--harness', harness], { cwd, timeout: 8000, maxBuffer: 1024 * 1024 }, (err, stdout) => {
15
+ try {
16
+ done(err ? null : JSON.parse(String(stdout).trim().split('\n').pop() || '{}'));
17
+ } catch {
18
+ done(null);
19
+ }
20
+ });
21
+ child.on('error', () => done(null));
22
+ child.stdin?.on('error', () => {});
23
+ child.stdin?.end(JSON.stringify(payload));
24
+ } catch {
25
+ done(null);
26
+ }
27
+ });
28
+
29
+ // The repository root above a folder (the first with .git), so the checks below work from a subfolder too.
30
+ const repoRoot = (dir) => {
31
+ let d = resolve(dir);
32
+ for (;;) {
33
+ if (existsSync(join(d, '.git'))) return d;
34
+ const up = dirname(d);
35
+ if (up === d) return null;
36
+ d = up;
37
+ }
38
+ };
39
+
40
+ // Paths an edit tool names, made absolute against the folder it ran in (omp also allows ~).
41
+ const absolute = (input, cwd) => {
42
+ if (!input || typeof input !== 'object') return {};
43
+ const fix = (p) => (typeof p !== 'string' || !p ? p : p.startsWith('~/') ? join(homedir(), p.slice(2)) : isAbsolute(p) ? p : resolve(cwd, p));
44
+ const out = { ...input };
45
+ for (const k of ['path', 'filePath', 'file_path']) if (k in out) out[k] = fix(out[k]);
46
+ if (Array.isArray(out.paths)) out.paths = out.paths.map(fix);
47
+ return out;
48
+ };
49
+
50
+ // opencode 2.2's edit tools: edit and write take { path }, patch takes { patchText } (apply_patch is its alias).
51
+ const EDIT_TOOLS = new Set(['edit', 'write', 'patch', 'apply_patch']);
52
+
6
53
  export default {
7
54
  id: 'bravos',
8
55
  setup: async (api) => {
@@ -41,6 +88,42 @@ export default {
41
88
  /* this opencode has no such hook */
42
89
  }
43
90
  }
91
+ // @comment -- "The same protection as Claude Code and Codex around each edit (records round two): before an edit tool runs, the record guard (bravos hook record-guard) may refuse the first edit in a session to a file a security decision record covers, once, with the record; opencode 2.2 blocks a tool whose execute.before hook throws, and hands the model the error's message. After it runs, the cards and the no-record nudge (bravos hook cards) are added to the tool result the model reads. opencode also fails a tool when such a hook throws by accident, so everything but the deliberate refusal is caught: any error and the edit goes ahead."
92
+ const gitRoot = repoRoot(root);
93
+ const payload = (e) => ({ session_id: typeof e?.sessionID === 'string' ? e.sessionID : null, cwd: root, tool_name: String(e?.tool ?? ''), tool_input: absolute(e?.input, root) });
94
+ try {
95
+ handles.push(
96
+ await api.tool.hook('execute.before', async (e) => {
97
+ let reason = null;
98
+ try {
99
+ if (gitRoot && EDIT_TOOLS.has(String(e?.tool)) && existsSync(join(gitRoot, '.guardlink', 'records'))) {
100
+ const a = await askBravos('record-guard', 'opencode', payload(e), root);
101
+ if (a?.decision === 'deny' && typeof a.reason === 'string' && a.reason) reason = a.reason;
102
+ }
103
+ } catch {
104
+ reason = null;
105
+ }
106
+ if (reason) throw new Error(reason);
107
+ }),
108
+ );
109
+ handles.push(
110
+ await api.tool.hook('execute.after', async (e) => {
111
+ try {
112
+ if (!gitRoot || e?.status !== 'completed' || !EDIT_TOOLS.has(String(e?.tool)) || !existsSync(join(gitRoot, '.guardlink'))) return;
113
+ const a = await askBravos('cards', 'opencode', payload(e), root);
114
+ const note = typeof a?.additionalContext === 'string' ? a.additionalContext : '';
115
+ if (!note || !e.result) return;
116
+ const c = e.result.content;
117
+ const base = typeof c === 'string' ? [{ type: 'text', text: c }] : Array.isArray(c) ? c : [];
118
+ e.result = { ...e.result, content: [...base, { type: 'text', text: note }] };
119
+ } catch {
120
+ /* the result stays as it was */
121
+ }
122
+ }),
123
+ );
124
+ } catch {
125
+ /* this opencode has no tool hooks */
126
+ }
44
127
  return () => Promise.all(handles.map((h) => h?.dispose?.())).then(() => undefined);
45
128
  },
46
129
  };