@bugb-technologies/bravos 1.23.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.
- package/dist/artifacts.js +23 -8
- package/dist/bin.js +12 -0
- package/dist/cli.js +203 -21
- package/dist/context.js +4 -4
- package/dist/cursor.js +24 -5
- package/dist/dashboard.js +6 -0
- package/dist/doctor.js +29 -2
- package/dist/graphbin.js +2 -2
- package/dist/guide.js +4 -2
- package/dist/hook-launcher.js +92 -0
- package/dist/hooks.js +56 -3
- package/dist/prefs.js +18 -4
- package/dist/principles.js +1 -1
- package/dist/records-drafts.js +106 -0
- package/dist/records-ledger.js +103 -0
- package/dist/records-team.js +398 -0
- package/dist/records.js +158 -0
- package/dist/review-server.js +3 -1
- package/dist/review.js +16 -1
- package/dist/rules.js +48 -4
- package/dist/setup-route.js +1 -1
- package/dist/setup.js +57 -2
- package/dist/uninstall.js +1 -1
- package/dist/upkeep.js +3 -0
- package/dist/versions.js +3 -0
- package/docs/GUIDE.md +11 -1
- package/docs/UPGRADING.md +48 -0
- package/hooks/cards.mjs +62 -13
- package/hooks/coach.mjs +3 -1
- package/hooks/lib/agent-io.mjs +105 -0
- package/hooks/lib/briefing.mjs +94 -3
- package/hooks/lib/cards.mjs +49 -10
- package/hooks/lib/draft-check.mjs +104 -0
- package/hooks/lib/drafts.mjs +121 -0
- package/hooks/lib/ledger.mjs +270 -0
- package/hooks/lib/pre-pr.mjs +74 -0
- package/hooks/lib/prefs.mjs +7 -3
- package/hooks/lib/record-guard.mjs +272 -0
- package/hooks/lib/records.mjs +581 -0
- package/hooks/lib/replay.mjs +2 -1
- package/hooks/record-guard.mjs +60 -0
- package/hooks/session-start.mjs +4 -3
- package/package.json +2 -2
- package/skills/bravos/SKILL.md +1 -0
- package/skills/bravos-records/SKILL.md +57 -0
- package/templates/dashboard/dashboard.html +53 -0
- package/templates/omp/bravos.js +85 -1
- package/templates/opencode/bravos.js +84 -1
- package/templates/workflows/bravos-pr-gate.yml +23 -0
package/dist/graphbin.js
CHANGED
|
@@ -19,8 +19,8 @@ export function pythonBravos(env = process.env) {
|
|
|
19
19
|
const real = realpathSync(file);
|
|
20
20
|
if (real.startsWith(self + '/'))
|
|
21
21
|
continue;
|
|
22
|
-
// An npm shim (a shell script that execs node on this package's dist/cli.js) is not the Python CLI either.
|
|
23
|
-
if (readFileSync(real, 'utf8')
|
|
22
|
+
// An npm shim (a shell script that execs node on this package's dist/bin.js, or dist/cli.js before 1.25) is not the Python CLI either.
|
|
23
|
+
if (/dist\/(?:bin|cli)\.js/.test(readFileSync(real, 'utf8')))
|
|
24
24
|
continue;
|
|
25
25
|
return file;
|
|
26
26
|
}
|
package/dist/guide.js
CHANGED
|
@@ -117,10 +117,11 @@ export const GUIDE_TOPICS = [
|
|
|
117
117
|
{ name: 'Teach bravos what the app is for', skills: ['bravos-context'], body: ['Writes .guardlink/intent.md: invariants (INV-n) that become threats, and intended-by-design items (INT-n) that get an "intended?" audit instead of a high rating.'] },
|
|
118
118
|
{ name: 'Start from your design documents', skills: ['bravos-context'], body: ['Give bravos-context your PRDs, design documents or an earlier threat model, as files or links. Each is kept in the repository as Markdown under .bravos/context/ (bravos context add; committed, so the team can keep it current) after a check for secrets and local paths; a link is kept beside its snapshot. Every rule then names the document it came from (INV-4, source: SRC-2), including who may do what: "sales may see every report except the revenue report" becomes a rule that can be tested, where a scan would see nothing wrong. bravos context list shows the documents, bravos context check re-checks them, and a pre-push check stops a push that would send a secret in one. Free; the CLI runs no model and fetches nothing: your agent converts and fetches with your own access.'] },
|
|
119
119
|
{ name: 'Write down your company\'s security design principles', skills: ['bravos-principles'], body: ['Ask for "our security design principles". bravos-principles proposes candidates only from your stored documents (cited by section, checked against the text), INV rules a person already confirmed in this or another repository, or an optional starter list mapped to OWASP ASVS 4.0.3, which is never pre-selected; bravos review principles refuses anything else. On the page each principle is its own decision (Agree, Change the wording, or No); there is no adopt-all. Confirm records your adoption with the exact wording and a fingerprint, and bravos writes .guardlink/principles.md from the adoptions: committed, so every developer who pulls gets it, and the Bravos block in AGENTS.md and CLAUDE.md tells every coding agent to read and follow it and never edit it. A principle is enforced (it becomes a threat with principle:SDP-n, is tested, and the pre-PR gate stops a change that breaks it, whatever the PR body says) or guidance (followed, not tested). bravos principles check (free; the pre-push hook and the gate run it) fails a hand-edited line, an adoption nobody made, or an exception past its date. An exception is approved by a person at their own terminal: bravos principles except SDP-n --where "<glob>" --reason "<why>" --until <date>, at most a year, never extended; a coding agent cannot run it. bravos principles copy --from <repository> takes the same set into another repository, and check says when the source changes. The dashboard\'s Security design view shows each principle, where it is enforced, its exceptions, and what it caught or stopped in the last 30 and 90 days. Team plan for authoring, the gate and the view; adopted principles are followed on every plan.'] },
|
|
120
|
+
{ name: 'Write down what was decided for one module', skills: ['bravos-records'], body: ['Ask for "a security decision record for <module>". bravos-records drafts one document for that module (.guardlink/records/SDR-n-<module>.md) from what you tell it, your documents and confirmed rules: the decision, the rules that follow, why, and what looks like a bug but is not. It is a draft until its text reaches the default branch: approved when a code owner reviews the pull request that merges it (bravos records check asks GitHub with gh whether the branch requires that review, and offers CODEOWNERS lines for .guardlink/records/ that it writes only after you say yes: bravos records codeowners --owner @you). Without that review, a record on the default branch reads \'on main, review not enforced\'; the weaker fallback is a person running bravos records adopt SDR-n at their own terminal and typing their name, which shows who said so, not that anyone reviewed it. An agent cannot approve or adopt one. From then on every coding agent asks bravos records for <file> before changing covered code and follows the record; in Claude Code, Codex, Cursor, Antigravity, opencode and omp the first edit of a covered file in a session is refused once with the record in full (each in its own hook shape, through the installed CLI; any hook error lets the edit through), so it is read before anything changes. A change that goes against a rule is raised with you first and shows as a decision-record card after the edit, as does a removed check, and a record edited on a branch is a proposal: the default branch\'s text binds until the edit is approved, and only the branch that edits it waits (bravos records check). In CI, the PR gate checks with the workflow\'s GITHUB_TOKEN that a code owner approved the last change to each record and reports what it could not prove. A module ledger, .guardlink/records/README.md, lists which modules of the application make security decisions: the agent proposes it (bravos records ledger propose: features found from the stored documents, the threat model and the folders, with the code graph\'s routes on the Team plan; without the graph a feature split over folders with different names can show as two modules, so the boundaries are for a person to review), a person reviews it in its pull request, and Bravos keeps its Record and Owner columns (bravos records ledger refresh, owners from CODEOWNERS). It is never enforced. From the first session the briefing counts it ("9 modules, 2 with records"), and the first edit in a session to a module it says needs a record, and has none, gets one line offering to draft one, never a block; the company principles apply either way (bravos prefs set nudge off silences it). On the Team plan, once a person has reviewed the ledger, the agent drafts records for the modules that need one in the background: a subagent runs bravos records drafts (at most 2 a run, 3 waiting for review at once, never two for one module) and bravos records draft "<module>", which starts each draft on its own branch and worktree so your checkout is never touched. A draft states only what your documents (SRC-n § Section), confirmed intent rules or people said, cited on the line; what the code does today is marked observed and kept as guidance; Not a bug is never filled from code. bravos records check holds every citation to the repository. The agent pushes nothing and asks you before opening each draft\'s pull request; it binds nobody until a code owner approves it, and only that branch waits. bravos prefs set drafts off stops it. bravos rules lists each rule with its status. On the Team plan the pre-PR gate holds a change that breaks an adopted enforced rule whatever the PR body says, until the code is fixed, a person approves a dated exception (bravos records except SDR-n R1, at their own terminal), or the record is changed and the new text approved; people can adopt on a page with bravos review records (Agree, Change or No per rule); bravos records gaps lists modules no record covers; and the dashboard has a Decision records view. Reading and following records is free; writing, adopting, exceptions, the gate, gaps and the view are on the Team plan.'] },
|
|
120
121
|
{ name: 'See which design rules hold', skills: ['bravos', 'bravos-recheck'], body: ['bravos rules lists every rule your design states (INV-n in the intent) with its status: broken (a test got through), retest due (the code under it changed since it was tested), unguarded (it can break somewhere and nothing stops it), guarded but untested, not placed (no code is tied to it yet), or holds (a test tried and was refused everywhere it is enforced). Each line names the document the rule came from and the places it is enforced. bravos dashboard shows the same under Threat model, as Design rules in GuardLink\'s sidebar beside Exposures, worst first. Free, read-only, no model; --json prints bravos.rules/v1. On the Team plan the pre-PR check and the PR workflow hold a pull request that changes a file a holding rule is enforced in (the check, or the role table that grants the permission) after that rule was last tested, until its test is replayed or the PR body names the rule; the after-edit note says the same while you work.'] },
|
|
121
122
|
{ name: 'The intake asks, it never blocks', skills: ['bravos-context', 'bravos-annotate'], body: ['Annotation starts in the first session. With no confirmed intent, the agent drafts what the product is for from the README, docs and code (.guardlink/intent.md, every item marked draft), annotates against that draft, and opens the intake page without waiting. Each session asks once for a person to confirm it (bravos review intent, a few minutes) until someone confirms or declines; the agent never confirms for you. Rules drafted from the design are tested and can block a pull request right away; bravos rules and the block message label them draft until a person confirms them. When the answers arrive, the agent re-judges what they changed: an item you mark intended by design is annotated as intended, not as a finding. The intake page brings back the answers each person gave when they reopen it, and saves them as they go; only Confirm makes them count, and it records who and when. Design documents (a PRD, a design document, an earlier threat model) can be added on the page itself: Markdown and text are stored with the usual checks, and a PDF, Word file, slides or link waits for the agent to convert. Every rule cites the section of the document it came from, the page shows that passage under the question, and bravos context check refuses a section the document does not have. The intake and the documents are committed so the team gets them on their next pull; bravos doctor warns when a .gitignore rule keeps them on one machine, and bravos context share --yes narrows a blanket .bravos/ rule. A team that chooses to go without records that under a name, bravos context decline --by "<name>", which is committed like the intent and ends the asking; a coding agent is told never to decline for you. bravos context gate says which state a repository is in.'] },
|
|
122
123
|
{ name: 'Updates', skills: ['bravos'], body: ['Bravos tells you when it is updated. At most once a day a session start asks the npm registry, in a background process the session never waits on, for the latest published version: the same request npm install makes, with only the package name. A newer version shows in the banner and the briefing, and the coach tells a session that is already running, once. Installing it is yours to do (npm install -g @bugb-technologies/bravos); once it is installed the coach has the agent run bravos setup in the repository, which brings its Bravos files up to date. bravos doctor shows the last check. BRAVOS_UPDATE_CHECK=off stops the check, and it never runs in CI.'] },
|
|
123
|
-
{ name: 'Threat cards', skills: ['bravos-prove', 'bravos-env'], body: ['When an edit adds a critical or high threat to the threat model (an @exposes claim) that no test has confirmed or refuted, a hook that runs after the edit shows you a card in the terminal straight away: the severity, what the threat is, the claim and where it is, its state, and one next step (bravos-env to set up a test target, where you type the authorization, then bravos-prove). The agent is told to raise it in the same reply and recommend confirming it; it never confirms, refutes or accepts a threat itself. Only lines that are not in the last commit count, so existing claims never raise a card, and each threat raises one card per clone. The hook reads the edited files, their committed copy and the local ledger; it runs no guardlink, no test and no network. bravos watch lists every card. BRAVOS_THREAT_CARDS=off turns cards off for a run and bravos prefs set cards off --by "<your name>" for the clone; bravos prefs set notify on --by "<your name>" adds a desktop notification (macOS and Linux).'] },
|
|
124
|
+
{ name: 'Threat cards', skills: ['bravos-prove', 'bravos-env'], body: ['When an edit adds a critical or high threat to the threat model (an @exposes claim) that no test has confirmed or refuted, a hook that runs after the edit shows you a card in the terminal straight away: the severity, what the threat is, the claim and where it is, its state, and one next step (bravos-env to set up a test target, where you type the authorization, then bravos-prove). The agent is told to raise it in the same reply and recommend confirming it; it never confirms, refutes or accepts a threat itself. Only lines that are not in the last commit count, so existing claims never raise a card, and each threat raises one card per clone. The hook reads the edited files, their committed copy and the local ledger; it runs no guardlink, no test and no network. bravos watch lists every card. BRAVOS_THREAT_CARDS=off turns cards off for a run and bravos prefs set cards off --by "<your name>" for the clone; bravos prefs set notify on --by "<your name>" adds a desktop notification (macOS and Linux). On macOS, bravos setup --notifier then installs the small Bravos notifier app (signed and notarized by Bugb), so the notification shows as Bravos with its icon and a click opens the dashboard; until it is installed, notifications come through osascript and show as Script Editor.'] },
|
|
124
125
|
{ name: 'The coach', skills: ['bravos'], body: ['Bravos does not wait to be asked. Before each prompt a fast hook (it runs no guardlink and no network) may add one line for the agent. A question about issues, threats, vulnerabilities, findings or risks builds the dashboard while the agent answers, and opens it in your browser the first time in a session; later questions rebuild it and give the path. From the second prompt on it reminds, each topic once a session and at most one per prompt: claims waiting to be confirmed, with the next step (bravos-env to set up a target, where you type the authorization, then bravos-prove); how much of the code the threat model covers, with the next round; and a dashboard that is older than the model. Skills end every round the same way. bravos watch lists each reminder. BRAVOS_COACH=off turns it off for one run, and bravos prefs set coach off --by "<your name>" for this clone.'] },
|
|
125
126
|
{ name: 'Background annotation', skills: ['bravos-annotate'], body: ['While coverage is under 100%, each new session asks the agent to start one annotation pass in a background subagent (one slice at the default budget) beside whatever you asked, and to tell you in one line. It writes annotations only, never code; it commits only as your commits answer allows (bravos prefs set commits), and otherwise leaves its files for you; it reports the files it covered and the coverage change in one line. It does not run again on resume or compact, nor in CI, where the nightly annotates. bravos prefs set annotate off --by "<your name>" switches it off for this clone (background turns it back on), and BRAVOS_AUTO_ANNOTATE=off for one run. In a harness without subagents the agent offers the pass instead.'] },
|
|
126
127
|
{ name: 'Threat-model someone else\'s project', skills: ['bravos-context', 'bravos-annotate'], body: ['bravos-context assumes you are researching software you do not own (an open-source project, a vendor\'s code): it drafts the intent from upstream\'s own docs with links and asks only the scope decisions — which configuration to rate against (shipped defaults or the hardened setup upstream recommends), single organisation or multi-tenant, which attackers are in scope, and the intended-looking behaviours upstream does not document. intent.md records them as Assumptions, and severities are rated against them. Say "this is our product" for the owner interview instead.'] },
|
|
@@ -146,7 +147,7 @@ export const GUIDE_TOPICS = [
|
|
|
146
147
|
{
|
|
147
148
|
id: 'skills',
|
|
148
149
|
title: 'Every skill',
|
|
149
|
-
summary: 'all
|
|
150
|
+
summary: 'all eighteen skills, what each does and leaves for the next',
|
|
150
151
|
items: [
|
|
151
152
|
{ name: 'bravos', body: ['Front door: reads the security picture, explains the evidence loop, routes to the right skill.'] },
|
|
152
153
|
{ name: 'bravos-context', body: ['Learns what the product intends from the repo and a short interview; records invariants, intended behaviour, actors, assets and boundaries.'] },
|
|
@@ -161,6 +162,7 @@ export const GUIDE_TOPICS = [
|
|
|
161
162
|
{ name: 'bravos-sast', body: ['Licensed static analysis joined to guardlink claims and reachability; gates on findings new since the base.'] },
|
|
162
163
|
{ name: 'bravos-threat-hunt', body: ['"Identify all the threats": maps the attack surface with the code graph, runs SAST, records every finding in the threat model with bravos-annotate, rebuilds the dashboard and reports from what was recorded, then recommends confirming the top three.'] },
|
|
163
164
|
{ name: 'bravos-principles', body: ['Your company\'s security design principles, from your own documents and confirmed rules (or an optional starter list mapped to OWASP ASVS): proposed on the review page, adopted one by one by named people, written by bravos to .guardlink/principles.md, followed by every coding agent, and enforced ones tested and held to by the pre-PR gate.'] },
|
|
165
|
+
{ name: 'bravos-records', body: ['Security decision records, one document per module or feature: what was decided there, the rules that follow, why, and what looks like a bug but is not. Drafted from what the team states, approved through a code owner\'s pull-request review (or, weaker, a name typed at a person\'s own terminal), read by every coding agent before it changes covered code, and listed rule by rule in bravos rules.'] },
|
|
164
166
|
{ name: 'bravos-campaign', body: ['A goal over many rounds: disjoint batches, one subagent each, a gate per batch, rests, a final before-and-after.'] },
|
|
165
167
|
{ name: 'bravos-schedule', body: ['Recurring upkeep with each harness\'s own mechanism; never live tests from a loop.'] },
|
|
166
168
|
{ name: 'bravos-cicd', body: ['Audits and writes the security workflows.'] },
|
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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,8 +84,12 @@ 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];
|
|
78
|
-
|
|
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];
|
|
88
|
+
const lines = [`${key}: ${value} — from now on the agent will ${what}`, `recorded in ${file} (this clone only; never committed)`];
|
|
89
|
+
// On macOS the notifications come through osascript (shown as Script Editor) until the Bravos notifier app is staged.
|
|
90
|
+
if (key === 'notify' && value === 'on' && process.platform === 'darwin')
|
|
91
|
+
lines.push('on macOS, bravos setup --notifier installs the Bravos notifier app so these show as Bravos (until then they come through osascript, shown as Script Editor)');
|
|
92
|
+
return lines;
|
|
79
93
|
}
|
|
80
94
|
// @comment -- "Leaves the hand-off marker after a first install, from the install pipeline itself (which is synchronous, so it cannot load the hook library): the same file and shape hooks/lib/prefs.mjs writeHandoff writes and readHandoff reads, under the clone's git directory. It is what makes the next agent session begin the context step by itself, whichever way Bravos was installed: the guided setup, flags from a script, or the website's setup skill. Returns whether it was written; a folder that is not a git repository, or git not answering, only means the person types the first command."
|
|
81
95
|
// @mitigates #person-prefs against #governance-forgery using #prefs-outside-tree -- "The marker is written under the git directory, where no commit, clone or pull can put one."
|
package/dist/principles.js
CHANGED
|
@@ -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
|
+
}
|