@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,60 @@
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). 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 } 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
+ const commonDir = gitCommonDir(root);
44
+ const { refuse, state } = guardDecision({ root, toolInput: n.toolInput, state: readSession(commonDir, n.sessionId) });
45
+ if (refuse) {
46
+ // The refusal counts only once it is recorded: if the state cannot be written, the edit goes ahead rather than being refused for good.
47
+ if (!writeSession(commonDir, n.sessionId, state)) throw new Error('state not written');
48
+ out = guardAnswer(harness, refuse);
49
+ logWatchEvent(root, { summary: `record: first edit of a covered file stopped once so the record is read`, keys: ['bravos-record:read'] });
50
+ }
51
+ } catch {
52
+ out = null;
53
+ }
54
+ // Allowing: the agent's empty answer where it needs one (Cursor blocks an edit on output that is not JSON).
55
+ out ??= guardAnswer(harness, null);
56
+ if (out) process.stdout.write(JSON.stringify(out) + '\n');
57
+ process.exit(0);
58
+ }
59
+
60
+ 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.25.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.
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.
@@ -606,6 +606,59 @@ code { font: 12.5px var(--mono); background: var(--raised); border: 1px solid va
606
606
  },
607
607
  });
608
608
 
609
+ // Decision records: each module's security decision record (.guardlink/records/), rule by rule, with its state, who
610
+ // adopted it, where the code enforces each enforced rule and what testing has shown. Bravos computes this (src/rules.ts
611
+ // records) and it is drawn here as text. Shown only when the repository has records or something to say about them.
612
+ // @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."
613
+ if (RULES && ((Array.isArray(RULES.records) && RULES.records.length) || RULES.recordsNote)) views.push({
614
+ id: 'decision-records',
615
+ label: 'Decision records',
616
+ build(section) {
617
+ const LABEL = { broken: 'broken', 'retest-due': 'retest due', holds: 'holds', unguarded: 'unguarded', 'guarded-untested': 'guarded, untested', 'not-placed': 'not placed', guidance: 'guidance' };
618
+ const SITE = { check: 'enforced at', gap: 'no control at', grant: 'granted in' };
619
+ const STATE = { broken: 'a test got through', retest: 'the code changed since it was tested', held: 'a test was refused', untested: 'not tested' };
620
+ const wrap = el('div', { class: 'rules' });
621
+ const inner = el('div', { class: 'rules-inner' });
622
+ const lead = prose(RULES.recordsNote || '');
623
+ lead.className = 'rules-lead';
624
+ 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.'));
625
+ for (const r of RULES.records || []) {
626
+ const status = LABEL[r.status] ? r.status : 'not-placed';
627
+ const card = el('article', { class: 'rule ' + status });
628
+ const head = el('div', { class: 'rule-head' });
629
+ head.append(el('span', { class: 'pill ' + status }, LABEL[status]), el('span', { class: 'rule-id' }, r.id));
630
+ if (r.recordState !== 'adopted') head.append(el('span', { class: 'pill' }, r.recordState));
631
+ card.append(head, el('p', { class: 'rule-text' }, r.text || ''), el('p', { class: 'rule-why' }, r.why || ''));
632
+ const meta = el('ul', { class: 'rule-meta' });
633
+ const fact = (label, value) => {
634
+ if (!value) return;
635
+ const li = el('li');
636
+ li.append(el('b', {}, label + ' '), value);
637
+ meta.append(li);
638
+ };
639
+ fact('module', r.module);
640
+ fact('adopted by', (r.adoptedBy || []).map((a) => a.by + ' (' + a.date + ')').join(', '));
641
+ fact('threat', r.threat || '');
642
+ card.append(meta);
643
+ if (Array.isArray(r.sites) && r.sites.length) {
644
+ const sites = el('ul', { class: 'sites' });
645
+ for (const st of r.sites) {
646
+ const li = el('li');
647
+ li.append(el('span', {}, SITE[st.kind] || 'at'), el('span', { class: 'where' }, String(st.file) + (st.line ? ':' + st.line : '')));
648
+ 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 : '')));
649
+ else if (st.state) li.append(el('span', { class: 'state ' + st.state }, STATE[st.state] || st.state));
650
+ if (st.control) li.append(el('span', {}, 'by #' + st.control));
651
+ sites.append(li);
652
+ }
653
+ card.append(sites);
654
+ }
655
+ inner.append(card);
656
+ }
657
+ wrap.append(inner);
658
+ section.append(wrap);
659
+ },
660
+ });
661
+
609
662
  // Code graph: the seven pages the Bravos VS Code extension draws (Map, Owners & History, Coupling, Trust,
610
663
  // Attack surface, Entry points, Links), vendored unchanged and run in their own sandboxed frame. In the editor
611
664
  // 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
  };
@@ -13,6 +13,8 @@ on:
13
13
 
14
14
  permissions:
15
15
  contents: read
16
+ # The records review check reads this PR's reviews and the reviews of the PR that last changed each record.
17
+ pull-requests: read
16
18
  security-events: write
17
19
  # upload-sarif reads the run's metadata; private repositories need this to upload.
18
20
  actions: read
@@ -247,6 +249,27 @@ jobs:
247
249
  git show "$BASE_SHA:.bravos/hooks/lib/context.mjs" > "$RUNNER_TEMP/bravos-context.mjs"
248
250
  node "$RUNNER_TEMP/bravos-context.mjs" check .
249
251
 
252
+ # Security decision records: whether a CODEOWNERS owner approved each record's last change on the base branch, and
253
+ # this PR's changes to records, read with the job's own token. It reports and never fails the job: the base
254
+ # branch's protection is what makes a PR wait for that review. A team owner the token may not read is said, not
255
+ # guessed. As with the design documents, the base branch's copy of the script runs, never this PR's.
256
+ - name: Security decision records reviewed by their code owners
257
+ env:
258
+ BASE_SHA: ${{ steps.base.outputs.sha }}
259
+ GITHUB_TOKEN: ${{ github.token }}
260
+ run: |
261
+ [[ -d .guardlink/records ]] || exit 0
262
+ lib="$RUNNER_TEMP/bravos-records-lib"
263
+ mkdir -p "$lib"
264
+ for f in records principles context; do
265
+ if ! git show "$BASE_SHA:.bravos/hooks/lib/$f.mjs" > "$lib/$f.mjs" 2> /dev/null; then
266
+ echo "The base branch's Bravos has no records review check yet (bravos sync adds it); records were not checked here." >> "$GITHUB_STEP_SUMMARY"
267
+ exit 0
268
+ fi
269
+ done
270
+ grep -q verify-github "$lib/records.mjs" || { echo "The base branch's Bravos predates the records review check (bravos sync adds it)." >> "$GITHUB_STEP_SUMMARY"; exit 0; }
271
+ node "$lib/records.mjs" verify-github
272
+
250
273
  - name: Changed source to review
251
274
  if: always() && steps.base.outcome == 'success'
252
275
  continue-on-error: true