@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/rules.js
CHANGED
|
@@ -322,16 +322,53 @@ export async function gatherRules(root, env, opts = {}) {
|
|
|
322
322
|
const principlesNote = !principles.length
|
|
323
323
|
? checked.ok ? '' : `principles.md does not match what people adopted (${checked.problems.length} problem${checked.problems.length === 1 ? '' : 's'}): bravos principles check.`
|
|
324
324
|
: `${principles.length} security design principle${principles.length === 1 ? '' : 's'} adopted (${enforcedCount} enforced)${principles.filter((p) => p.status === 'broken').length ? `, ${principles.filter((p) => p.status === 'broken').length} broken` : ''}${checked.ok ? '' : `; principles.md does not match the adoptions: bravos principles check`}.`;
|
|
325
|
+
// THE MODULES' DECISION RECORDS: each rule of each record joined to the threat that stands for it. A record's threat
|
|
326
|
+
// carries the reference record:SDR-n and a description that starts "SDR-n Rk:"; a record with one enforced rule and
|
|
327
|
+
// one such threat is matched without the prefix.
|
|
328
|
+
// @comment -- "Joins each rule of each security decision record to its threat (reference record:SDR-n, description starting 'SDR-n Rk:') and gives it the same status a design rule gets. A rule of a record nobody has adopted, or one changed after adoption, is listed with that said, since it binds nobody; a guidance rule is followed, not tested."
|
|
329
|
+
const RL = await (await import('./records.js')).recordsLib();
|
|
330
|
+
const recordCheck = RL.checkRecords(P.treeReader(root), { root });
|
|
331
|
+
const recordRules = [];
|
|
332
|
+
for (const rec of recordCheck.records) {
|
|
333
|
+
const mine = threats.filter((t) => t.refs.some((r) => r.toLowerCase() === `record:${rec.id.toLowerCase()}`));
|
|
334
|
+
const enforcedRules = rec.rules.filter((x) => x.kind === 'enforced');
|
|
335
|
+
for (const rule of rec.rules) {
|
|
336
|
+
const t = rule.kind !== 'enforced' ? null : mine.find((x) => new RegExp(`^${rec.id}\\s+${rule.id}\\b`, 'i').test(x.description.trim())) ?? (enforcedRules.length === 1 && mine.length === 1 ? mine[0] : null);
|
|
337
|
+
// A place under a live exception a person approved for this rule is set aside, as for a principle.
|
|
338
|
+
const exceptions = recordCheck.exceptions ?? [];
|
|
339
|
+
const sites = (t ? sitesFor(t.id) : []).map((site) => {
|
|
340
|
+
const e = exceptions.find((x) => x.record === rec.id && x.rule === rule.id && x.until >= new Date().toISOString().slice(0, 10) && P.globMatch(x.where, site.file));
|
|
341
|
+
return e ? { ...site, exception: { where: e.where, by: names ? e.by : '', until: e.until } } : site;
|
|
342
|
+
});
|
|
343
|
+
const active = sites.filter((x) => !('exception' in x && x.exception));
|
|
344
|
+
const unbound = rec.state === 'adopted' ? '' : rec.state === 'draft' ? ' The record is a draft nobody has adopted, so this binds nobody yet.' : ` The record is ${rec.state}, so this binds nobody until a person adopts it again.`;
|
|
345
|
+
const verdict = rule.kind === 'guidance'
|
|
346
|
+
? { status: 'guidance', why: 'Guidance: coding agents follow it in the code the record covers; nothing is tested.' }
|
|
347
|
+
: !model
|
|
348
|
+
? { status: 'not-placed', why: 'GuardLink is not installed here, so where this rule is enforced is not known.' }
|
|
349
|
+
: !t
|
|
350
|
+
? { status: 'not-placed', why: `No threat in the model stands for it yet: bravos-records adds one with the reference record:${rec.id} and a description that starts "${rec.id} ${rule.id}:".` }
|
|
351
|
+
: afterChanges(ruleStatus(active), active);
|
|
352
|
+
recordRules.push({ id: `${rec.id} ${rule.id}`, record: rec.id, rule: rule.id, module: rec.module, kind: rule.kind, text: rule.text, recordState: rec.state, adoptedBy: names ? rec.adopters : null, threat: t ? `#${t.id}` : null, severity: t?.severity ?? null, status: verdict.status, why: `${verdict.why}${unbound}`, sites });
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
const recordOrder = (r) => (r.recordState === 'adopted' ? 0 : 1) * 100 + (r.status === 'guidance' ? STATUS_ORDER.length : STATUS_ORDER.indexOf(r.status));
|
|
356
|
+
recordRules.sort((a, b) => recordOrder(a) - recordOrder(b) || a.id.localeCompare(b.id, undefined, { numeric: true }));
|
|
357
|
+
const adoptedCount = recordCheck.adopted.length;
|
|
358
|
+
const brokenRecordRules = recordRules.filter((r) => r.recordState === 'adopted' && r.status === 'broken').length;
|
|
359
|
+
const recordsNote = !recordCheck.records.length
|
|
360
|
+
? recordCheck.ok ? '' : `A security decision record does not parse (${recordCheck.problems.length} problem${recordCheck.problems.length === 1 ? '' : 's'}): bravos records check.`
|
|
361
|
+
: `${recordCheck.records.length} security decision record${recordCheck.records.length === 1 ? '' : 's'} (${adoptedCount} adopted)${brokenRecordRules ? `, ${brokenRecordRules} rule${brokenRecordRules === 1 ? '' : 's'} broken` : ''}${recordCheck.ok ? '' : '; bravos records check lists what is wrong'}.`;
|
|
325
362
|
const summary = { total: rules.length, draft: rules.filter((r) => r.decided === 'draft').length, broken: 0, 'retest-due': 0, holds: 0, unguarded: 0, 'guarded-untested': 0, 'not-placed': 0 };
|
|
326
363
|
for (const r of rules)
|
|
327
364
|
summary[r.status] += 1;
|
|
328
365
|
if (!rules.length) {
|
|
329
|
-
return { schema: 'bravos.rules/v1', state: 'none', note: 'No design rules are recorded yet. Run /bravos-context: it asks for your design documents and writes the rules they state (who may do what, what must never happen) into .guardlink/intent.md.', summary, rules, principles, principlesNote };
|
|
366
|
+
return { schema: 'bravos.rules/v1', state: 'none', note: 'No design rules are recorded yet. Run /bravos-context: it asks for your design documents and writes the rules they state (who may do what, what must never happen) into .guardlink/intent.md.', summary, rules, principles, principlesNote, records: recordRules, recordsNote };
|
|
330
367
|
}
|
|
331
368
|
if (!model)
|
|
332
|
-
return { schema: 'bravos.rules/v1', state: 'no-guardlink', note: 'GuardLink is not installed on this machine, so the rules are listed without where the code enforces them: run bravos setup --tools -y, then bravos dashboard again.', summary, rules, principles, principlesNote };
|
|
369
|
+
return { schema: 'bravos.rules/v1', state: 'no-guardlink', note: 'GuardLink is not installed on this machine, so the rules are listed without where the code enforces them: run bravos setup --tools -y, then bravos dashboard again.', summary, rules, principles, principlesNote, records: recordRules, recordsNote };
|
|
333
370
|
const said = STATUS_ORDER.filter((s) => summary[s]).map((s) => `${summary[s]} ${STATUS_LABEL[s]}`);
|
|
334
|
-
return { schema: 'bravos.rules/v1', state: 'present', note: `${rules.length} design rule${rules.length === 1 ? '' : 's'} from the intent: ${said.join(', ')}${summary.draft ? `; ${summary.draft} still a draft nobody has confirmed` : ''}.`, summary, rules, principles, principlesNote };
|
|
371
|
+
return { schema: 'bravos.rules/v1', state: 'present', note: `${rules.length} design rule${rules.length === 1 ? '' : 's'} from the intent: ${said.join(', ')}${summary.draft ? `; ${summary.draft} still a draft nobody has confirmed` : ''}.`, summary, rules, principles, principlesNote, records: recordRules, recordsNote };
|
|
335
372
|
}
|
|
336
373
|
// @comment -- "The pre-PR gate's record of the times it stopped a change for breaking a principle, kept on this machine under the git directory (<git-common-dir>/bravos/principles-gate.jsonl, never committed): what the dashboard counts as the changes a principle stopped. Read-only, bounded; a missing or damaged file counts nothing."
|
|
337
374
|
export function gateStops(root, env) {
|
|
@@ -352,7 +389,7 @@ export function gateStops(root, env) {
|
|
|
352
389
|
return [];
|
|
353
390
|
}
|
|
354
391
|
}
|
|
355
|
-
// @comment -- "bravos rules as lines: the note, then one line per rule with its status, id, text, sources and the places it is enforced; then the adopted security design principles the same way."
|
|
392
|
+
// @comment -- "bravos rules as lines: the note, then one line per rule with its status, id, text, sources and the places it is enforced; then the adopted security design principles the same way, then each rule of each security decision record."
|
|
356
393
|
export function formatRules(doc) {
|
|
357
394
|
const lines = [doc.note];
|
|
358
395
|
for (const r of doc.rules) {
|
|
@@ -368,5 +405,12 @@ export function formatRules(doc) {
|
|
|
368
405
|
for (const s of p.sites)
|
|
369
406
|
lines.push(`${' '.repeat(19)}${s.kind === 'grant' ? 'granted in' : s.kind === 'gap' ? 'no control at' : 'enforced at'} ${s.file}${s.line ? `:${s.line}` : ''}${s.exception ? ` — under an exception until ${s.exception.until}` : s.state ? ` — ${SITE_WORD[s.state]}` : ''}`);
|
|
370
407
|
}
|
|
408
|
+
if (doc.recordsNote)
|
|
409
|
+
lines.push('', doc.recordsNote);
|
|
410
|
+
for (const r of doc.records ?? []) {
|
|
411
|
+
lines.push(`${(r.status === 'guidance' ? 'guidance' : STATUS_LABEL[r.status]).padEnd(18)} ${r.id.padEnd(9)} ${r.text}${r.recordState === 'adopted' ? '' : ` [${r.recordState}]`}`);
|
|
412
|
+
for (const x of r.sites)
|
|
413
|
+
lines.push(`${' '.repeat(19)}${x.kind === 'grant' ? 'granted in' : x.kind === 'gap' ? 'no control at' : 'enforced at'} ${x.file}${x.line ? `:${x.line}` : ''}${x.exception ? ` — under an exception until ${x.exception.until}${x.exception.by ? `, approved by ${x.exception.by}` : ''}` : x.state ? ` — ${SITE_WORD[x.state]}` : ''}`);
|
|
414
|
+
}
|
|
371
415
|
return lines;
|
|
372
416
|
}
|
package/dist/setup-route.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @comment -- "bravos setup is the one command for setting Bravos up: this decides, from the flags a person actually typed and whether there is a terminal, which of its jobs to do. It is a pure function so the whole table can be tested. First match wins: a read-only check; a refusal when machine and repository flags are mixed; the machine part (bundles, tools); the user-level install; the repository part by flags; an unattended first setup; the guided wizard; and otherwise safe upkeep, which is what an agent or a script with no terminal gets. The two meanings -y had on two commands are kept apart here: with a machine flag it means 'run the installers', alone it means 'no questions, take the defaults', and that second route never runs third-party installers."
|
|
2
2
|
/** Flags that say "set up this machine": Bravos's own bundles and the third-party tools. */
|
|
3
|
-
export const MACHINE_FLAGS = ['tools', 'analyzer', 'codegraph'];
|
|
3
|
+
export const MACHINE_FLAGS = ['tools', 'analyzer', 'codegraph', 'notifier'];
|
|
4
4
|
/** Flags that only mean something for a repository, so giving one says "set up (or re-apply to) this repository". */
|
|
5
5
|
export const REPOSITORY_FLAGS = ['agent', 'autopilot', 'prePrHook', 'ci', 'workflows', 'schedule', 'scope', 'linkSkills', 'force', 'guardlinkMode', 'guardlinkInit'];
|
|
6
6
|
// @comment -- "`given` holds the option names typed on the command line (commander's value source 'cli'), never defaults: --no-guardlink-init defaults to true, so truthiness would read it as given every time."
|
package/dist/setup.js
CHANGED
|
@@ -3,7 +3,7 @@ import { checkProofTool, formatProofTool } from './proof-tools.js';
|
|
|
3
3
|
import { spawnSync } from 'node:child_process';
|
|
4
4
|
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
|
5
5
|
import { isAbsolute, join } from 'node:path';
|
|
6
|
-
import { bundleEnvironment, hostTarget, install, missingPaths, olderThan, staged, stagedVersion, VERSIONS } from './artifacts.js';
|
|
6
|
+
import { bundleEnvironment, hostTarget, install, missingPaths, NOTIFIER_EXECUTABLE, olderThan, staged, stagedVersion, VERSIONS } from './artifacts.js';
|
|
7
7
|
import { graphBin, graphEnv, graphStore } from './codegraph.js';
|
|
8
8
|
import { whichBin } from './guardlink.js';
|
|
9
9
|
import { findAnalyzer } from './graphbin.js';
|
|
@@ -55,9 +55,11 @@ export async function runSetup(env, opts, io) {
|
|
|
55
55
|
for (const item of items)
|
|
56
56
|
if (item.proofTool)
|
|
57
57
|
lines.push(formatProofTool(item.proofTool));
|
|
58
|
+
lines.push(...notifierCheck(env, opts, io));
|
|
58
59
|
return lines;
|
|
59
60
|
}
|
|
60
|
-
const
|
|
61
|
+
const narrowed = opts.analyzer || opts.codegraph || opts.tools || opts.notifier;
|
|
62
|
+
const pick = narrowed ? { analyzer: !!opts.analyzer, codegraph: !!opts.codegraph, tools: !!opts.tools, notifier: !!opts.notifier } : { analyzer: true, codegraph: true, tools: false, notifier: true };
|
|
61
63
|
const bundles = [...(pick.codegraph ? ['codegraph'] : []), ...(pick.analyzer ? ['analyzer'] : [])];
|
|
62
64
|
for (const kind of bundles) {
|
|
63
65
|
const what = `bravos setup --${kind}`;
|
|
@@ -92,6 +94,8 @@ export async function runSetup(env, opts, io) {
|
|
|
92
94
|
lines.push(`${kind}: ${r.version} staged at ${r.dir}${missing.length ? ` — missing ${missing.join(', ')}` : ''}`);
|
|
93
95
|
lines.push(...selfTest(kind, r.dir, env));
|
|
94
96
|
}
|
|
97
|
+
if (pick.notifier)
|
|
98
|
+
lines.push(...(await setupNotifier(env, opts, io)));
|
|
95
99
|
if (pick.tools) {
|
|
96
100
|
for (const i of items) {
|
|
97
101
|
if (i.id !== 'guardlink' && i.id !== 'cxg')
|
|
@@ -127,6 +131,57 @@ export async function runSetup(env, opts, io) {
|
|
|
127
131
|
}
|
|
128
132
|
return lines;
|
|
129
133
|
}
|
|
134
|
+
const NOTIFY_OFF = 'desktop notifications are off for this repository (bravos prefs set notify on --by "<your name>" turns them on)';
|
|
135
|
+
// @comment -- "Whether the person asked for desktop notifications in this repository: their recorded notify answer (prefs.json under the git directory), or BRAVOS_NOTIFY=on for this shell. Read-only; a folder that is not a repository reads as off."
|
|
136
|
+
export async function notifyWanted(root, env) {
|
|
137
|
+
if (env.BRAVOS_NOTIFY === 'on')
|
|
138
|
+
return true;
|
|
139
|
+
try {
|
|
140
|
+
const { prefsLib } = await import('./prefs.js');
|
|
141
|
+
const L = await prefsLib();
|
|
142
|
+
return L.readPrefs(L.gitCommonDir(root, env)).notify?.value === 'on';
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
return false;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
/** bravos setup --check's line for the notifier: macOS only, and only worth a line where notifications are on or it is already staged. */
|
|
149
|
+
export function notifierCheck(env, opts, io = {}) {
|
|
150
|
+
if ((io.platform ?? process.platform) !== 'darwin')
|
|
151
|
+
return [];
|
|
152
|
+
const have = staged(env, 'notifier');
|
|
153
|
+
if (have)
|
|
154
|
+
return [`✔ ${'notifier'.padEnd(10)} ${have}${behindPin(env, 'notifier') ? ` (this bravos pins ${VERSIONS.notifier}: bravos setup --notifier fetches it)` : ''}`];
|
|
155
|
+
return [`✘ ${'notifier'.padEnd(10)} absent — ${opts.notify ? 'bravos setup --notifier fetches the Bravos notifier app' : `only needed with desktop notifications on; ${NOTIFY_OFF}`}`];
|
|
156
|
+
}
|
|
157
|
+
// @comment -- "The notifier step: on macOS, when the person turned desktop notifications on, fetch, verify and stage the Bravos notifier app (Bravos.app) under $BRAVOS_HOME/notifier/, so threat-card notifications show as Bravos instead of Script Editor. It is on every plan, so no licence is asked for. With notifications off nothing is fetched. Asked for by name (--notifier), a failure is an error; as part of a wider setup or upkeep it is a line, because cards fall back to osascript without it."
|
|
158
|
+
// @mitigates #notifier against #tampered-bundle using #artifact-signature -- "setupNotifier() installs only through install(), which verifies the manifest and the tarball against the committed artifact key before anything is unpacked"
|
|
159
|
+
export async function setupNotifier(env, opts, io) {
|
|
160
|
+
if ((io.platform ?? process.platform) !== 'darwin')
|
|
161
|
+
return opts.notifier ? ['notifier: the Bravos notifier is a macOS app; on Linux desktop notifications go through notify-send'] : [];
|
|
162
|
+
if (!opts.notify)
|
|
163
|
+
return opts.notifier ? [`notifier: not installed — ${NOTIFY_OFF}; then run bravos setup --notifier`] : [];
|
|
164
|
+
const have = staged(env, 'notifier');
|
|
165
|
+
const older = behindPin(env, 'notifier');
|
|
166
|
+
if (have && !opts.yes && !older)
|
|
167
|
+
return [`notifier: already staged at ${have}${opts.notifier ? ` (bravos setup --notifier -y fetches ${VERSIONS.notifier} again)` : ''}`];
|
|
168
|
+
if (opts.dryRun)
|
|
169
|
+
return [`dry-run: would fetch the Bravos notifier ${VERSIONS.notifier} from the public release bucket, verify its signature and stage it under $BRAVOS_HOME/notifier/${older ? ` (replacing ${older})` : ''}`];
|
|
170
|
+
let r;
|
|
171
|
+
try {
|
|
172
|
+
r = await install('notifier', { env, fetch: io.fetch, keys: io.keys, echo: io.echo });
|
|
173
|
+
}
|
|
174
|
+
catch (e) {
|
|
175
|
+
if (opts.notifier && (!older || opts.yes))
|
|
176
|
+
throw e;
|
|
177
|
+
const why = e.message.split('\n')[0].slice(0, 200);
|
|
178
|
+
return [older ? `notifier: ${older} stays staged at ${have}; ${VERSIONS.notifier} could not be fetched (${why}). Run bravos setup again later.` : `notifier: could not be fetched (${why}); notifications keep showing through osascript. Run bravos setup --notifier again later.`];
|
|
179
|
+
}
|
|
180
|
+
const out = [`notifier: ${r.version} staged at ${r.dir}${older ? ` (was ${older})` : ''}; threat-card notifications now show as Bravos`];
|
|
181
|
+
const v = spawnSync(join(r.dir, NOTIFIER_EXECUTABLE), ['--version'], { encoding: 'utf8', timeout: 10000, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
182
|
+
out.push(v.status === 0 ? ` ✔ Bravos.app ${(v.stdout || '').trim().split('\n')[0].slice(0, 80)}` : ` ✘ Bravos.app did not run: ${(v.stderr || v.error?.message || '').trim().split('\n')[0]}`);
|
|
183
|
+
return out;
|
|
184
|
+
}
|
|
130
185
|
// @comment -- "A staged bundle proves it runs: codegraph-build --version, bravos-cli --version, codegraph-mcp --help (it has no --version and answers with its usage), each under the bundle's own environment. A bundle that verifies but does not run is reported, not hidden."
|
|
131
186
|
export function selfTest(kind, dir, env) {
|
|
132
187
|
const out = [];
|
package/dist/uninstall.js
CHANGED
|
@@ -6,7 +6,7 @@ import { removeInstructionBlocks } from './instruction-blocks.js';
|
|
|
6
6
|
import { BravosError } from './types.js';
|
|
7
7
|
const isObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
8
8
|
// Any command bravos registers: the per-repo relative forms and the user-level absolute one.
|
|
9
|
-
const isBravosCommand = (c) => typeof c === 'string' && /\.bravos\/hooks\/(session-start|pre-pr|autopilot|coach|cards)\.mjs/.test(c);
|
|
9
|
+
const isBravosCommand = (c) => typeof c === 'string' && (/\.bravos\/hooks\/(session-start|pre-pr|autopilot|coach|cards)\.mjs/.test(c) || /\bbravos hook (session-start|pre-pr|autopilot|coach|cards|record-guard)(?![\w-])/.test(c));
|
|
10
10
|
function readJson(root, rel) {
|
|
11
11
|
const abs = join(root, rel);
|
|
12
12
|
if (!existsSync(abs))
|
package/dist/upkeep.js
CHANGED
|
@@ -6,6 +6,7 @@ import { installSkills } from './install.js';
|
|
|
6
6
|
import { licenceLib } from './licence.js';
|
|
7
7
|
import { LOCK_PATH, readLock } from './lock.js';
|
|
8
8
|
import { hooksDir as packageHooksDir, version } from './paths.js';
|
|
9
|
+
import { CLI_ONLY_HOOKS } from './hook-launcher.js';
|
|
9
10
|
import { behindPin } from './setup.js';
|
|
10
11
|
import { skillsRoot } from './skills.js';
|
|
11
12
|
export const UPKEEP_SCHEMA = 'bravos.upkeep/v1';
|
|
@@ -28,6 +29,8 @@ function staleHooks(root) {
|
|
|
28
29
|
const stale = [];
|
|
29
30
|
for (const abs of listFiles(src)) {
|
|
30
31
|
const rel = relative(src, abs).split('\\').join('/');
|
|
32
|
+
if (CLI_ONLY_HOOKS.includes(rel))
|
|
33
|
+
continue;
|
|
31
34
|
const dest = join(root, '.bravos', 'hooks', rel);
|
|
32
35
|
try {
|
|
33
36
|
if (!readFileSync(dest).equals(readFileSync(abs)))
|
package/dist/versions.js
CHANGED
|
@@ -6,4 +6,7 @@ import { hooksDir } from './paths.js';
|
|
|
6
6
|
export const ANALYZER_VERSION = '0.6.2';
|
|
7
7
|
/** The code graph binaries (codegraph-build, codegraph-mcp), published by specter-v1's codegraph-release workflow. */
|
|
8
8
|
export const CODEGRAPH_VERSION = '0.1.1';
|
|
9
|
+
// @comment -- "The Bravos notifier app (macOS), built from notifier/macos/ in this repository and released from Bugb-Technologies/specter-v1 (packaging/notifier, .github/workflows/notifier-release.yml), which vendors these sources; must equal notifier/macos/VERSION and specter-v1's packaging/notifier/VERSION."
|
|
10
|
+
/** The macOS notifier app that threat cards post desktop notifications through, installed by bravos setup when notify is on. */
|
|
11
|
+
export const NOTIFIER_VERSION = '1.0.0';
|
|
9
12
|
export const PROOF_TOOL_PINS = JSON.parse(readFileSync(join(hooksDir(), 'lib', 'proof-tool-pins.json'), 'utf8'));
|
package/docs/GUIDE.md
CHANGED
|
@@ -116,6 +116,12 @@ Skills: `/bravos-principles`
|
|
|
116
116
|
|
|
117
117
|
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.
|
|
118
118
|
|
|
119
|
+
### Write down what was decided for one module
|
|
120
|
+
|
|
121
|
+
Skills: `/bravos-records`
|
|
122
|
+
|
|
123
|
+
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.
|
|
124
|
+
|
|
119
125
|
### See which design rules hold
|
|
120
126
|
|
|
121
127
|
Skills: `/bravos` · `/bravos-recheck`
|
|
@@ -138,7 +144,7 @@ Bravos tells you when it is updated. At most once a day a session start asks the
|
|
|
138
144
|
|
|
139
145
|
Skills: `/bravos-prove` · `/bravos-env`
|
|
140
146
|
|
|
141
|
-
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).
|
|
147
|
+
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.
|
|
142
148
|
|
|
143
149
|
### The coach
|
|
144
150
|
|
|
@@ -314,6 +320,10 @@ Licensed static analysis joined to guardlink claims and reachability; gates on f
|
|
|
314
320
|
|
|
315
321
|
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.
|
|
316
322
|
|
|
323
|
+
### bravos-records
|
|
324
|
+
|
|
325
|
+
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.
|
|
326
|
+
|
|
317
327
|
### bravos-campaign
|
|
318
328
|
|
|
319
329
|
A goal over many rounds: disjoint batches, one subagent each, a gate per batch, rests, a final before-and-after.
|
package/docs/UPGRADING.md
CHANGED
|
@@ -2,6 +2,54 @@
|
|
|
2
2
|
|
|
3
3
|
After `npm install -g @bugb-technologies/bravos`, run **`bravos setup`** in a repository you work in: it brings this machine and that repository up to date. In repositories you work in with an agent you can skip even that: the agent runs it at the start of a session. From 1.12 on you do not have to watch for releases: Bravos tells you when a newer version is out, and after you install it the agent brings each repository up to date. The notes below say what else changes, newest first. (Before 1.9 the same was `bravos setup --tools -y` per machine and `bravos sync` per repository; both still work.)
|
|
4
4
|
|
|
5
|
+
## 1.25.0
|
|
6
|
+
|
|
7
|
+
- **Security decision records.** A record is one short document per module or feature, at `.guardlink/records/SDR-n-<module>.md`. It says what was decided for that code: the decision, the rules that follow, why, and what looks like a bug but is intended ("Not a bug"). Your coding agent reads it before changing that code and follows it. Ask your agent for "a security decision record for <module>", or see `bravos guide`.
|
|
8
|
+
- **Approval is a code owner's review.** A record counts once its text is on the default branch. It is fully approved when the branch requires a code owner's review for `.guardlink/records/`.
|
|
9
|
+
- `bravos records check` asks GitHub (with `gh`) whether that review is required, and says how strong the approval is.
|
|
10
|
+
- Without code-owner review, a record on main reads "review not enforced".
|
|
11
|
+
- Where there is no GitHub review, the fallback is a person typing their name: `bravos records adopt SDR-n` at their own terminal, or Agree on `bravos review records`. It is labelled "not verified" wherever it shows.
|
|
12
|
+
- **The agent reads the record before it edits.** The first edit in a session to a file a record covers is refused once, with the record in full. The agent reads it, then edits again, and the edit goes through. Afterwards, an edit that breaks a rule, or removes a check of one, shows a card. This works in all six agents Bravos sets up: Claude Code, Codex, Cursor, Antigravity, opencode and omp. Any hook error lets the edit through.
|
|
13
|
+
- **Pull requests.**
|
|
14
|
+
- The pre-PR gate holds a change that breaks an approved enforced rule, until the code is fixed, the record changes, or a person approves a dated exception (`bravos records except`, at their own terminal).
|
|
15
|
+
- A record that a branch adds or edits holds only that branch, never every pull request.
|
|
16
|
+
- The PR gate workflow gains a step that checks, with the job's own token, that a code owner approved each changed record. It only reports and never fails the job.
|
|
17
|
+
- **The module ledger**, `.guardlink/records/README.md`, lists which modules make security decisions, the code each covers, its owner (from CODEOWNERS) and its record status.
|
|
18
|
+
- Your agent proposes it (`bravos records ledger propose`) from your design documents, the threat model and the folders. With the code graph (Team), it also uses the routes.
|
|
19
|
+
- A person reviews it in a pull request. It is never enforced.
|
|
20
|
+
- From the first session the briefing counts it, and the first edit to a module that needs a record and has none gets one line offering to draft one (`bravos prefs set nudge off` silences it).
|
|
21
|
+
- **Background drafting (Team).** Once the ledger is reviewed, your agent drafts records for the modules that need one, in a background subagent: at most 2 a run, 3 waiting for review at once, and one per module.
|
|
22
|
+
- Each draft gets its own branch and worktree, so your checkout is never touched.
|
|
23
|
+
- Every line of a draft cites where it comes from: your documents, a confirmed rule, a person, or the code. Rules read from the code are marked "observed" and kept as guidance until the team confirms them. "Not a bug" is never filled from the code.
|
|
24
|
+
- The agent pushes nothing, and asks you before opening each draft's pull request. `bravos prefs set drafts off` stops it.
|
|
25
|
+
- **Free and Team.**
|
|
26
|
+
- **Free:** reading and following records, the before-edit read, the cards and the nudge in every agent, `bravos records list/show/for/check`, the ledger, and `bravos records codeowners`.
|
|
27
|
+
- **Team plan:** writing a record, adopting by name, exceptions, the pre-PR gate's records hold, the gaps report, the review page, the dashboard's Decision records view, and background drafting. `bravos account activate` starts a 30-day Team trial, no card.
|
|
28
|
+
- **Once per team:**
|
|
29
|
+
- Have your agent add the CODEOWNERS lines for the records. It shows them with `bravos records codeowners --owner @your-team` and writes them only after you say yes.
|
|
30
|
+
- Turn on "Require review from Code Owners" for your default branch on GitHub. Only an admin can.
|
|
31
|
+
- Review the module ledger your agent proposes, in its pull request.
|
|
32
|
+
- **What changes for an existing repository when you run `bravos setup`:**
|
|
33
|
+
- **New edit hooks are registered:**
|
|
34
|
+
- Claude Code and Codex get a before-edit hook. It does nothing in a repository with no records.
|
|
35
|
+
- Cursor gets `preToolUse` and `postToolUse` entries in `.cursor/hooks.json`.
|
|
36
|
+
- Antigravity's `bravos` group in `.agents/hooks.json` gains the edit hooks.
|
|
37
|
+
- The opencode plugin and the omp extension gain tool hooks.
|
|
38
|
+
- These all run the installed CLI (`bravos hook <name>`), so `bravos` must be on your PATH. Without it they stay silent.
|
|
39
|
+
- **The PR gate workflow** gains the records step and `pull-requests: read`.
|
|
40
|
+
- **The no-record nudge** no longer waits for an adopted record. It starts from the first session in a repository with security claims.
|
|
41
|
+
- **Fixed for Antigravity.** The session-start briefing is now in the nested shape Antigravity requires; it was most likely dropped before. Its hook command now finds the repository from any folder, because Antigravity runs hooks from `.agents/`.
|
|
42
|
+
- **`bravos hook <name>`** runs any of Bravos's hooks from the installed CLI. Nothing in your repository moves yet.
|
|
43
|
+
- **Not tested in a real session yet:** Cursor, Antigravity, opencode and omp. Their hooks were checked against each agent's documentation and installed version, and tested with each one's payloads, but none was run end to end in a live session of that agent. If one behaves unexpectedly, `bravos doctor` shows what is wired for it ("edit hooks"), and `BRAVOS_RECORD_GUARD=off` turns the before-edit read off for a run.
|
|
44
|
+
|
|
45
|
+
## 1.24.0
|
|
46
|
+
|
|
47
|
+
- **Threat-card notifications on macOS show as Bravos.** They used to come from `osascript` and show as "Script Editor". Bravos now installs a small app signed and notarized by Bugb, `Bravos.app`, under `~/.bravos/notifier/`, and posts them through it, with the Bravos name and icon.
|
|
48
|
+
- **Who gets it:** Macs with desktop notifications turned on (`bravos prefs set notify on`; off by default). The next `bravos setup` installs it, and so does the one the agent runs at the start of a session. `bravos setup --notifier` installs it on its own.
|
|
49
|
+
- **Before it is installed, or if the download fails,** notifications keep going through `osascript` as before, and setup says why.
|
|
50
|
+
- **Linux** is unchanged and still uses `notify-send`.
|
|
51
|
+
- Nothing else changes. Run `bravos setup` in each repository to refresh its installed hook copy.
|
|
52
|
+
|
|
5
53
|
## 1.23.0
|
|
6
54
|
|
|
7
55
|
- **A team trial licence finds out when the trial has ended.** A team's trial is one licence for the whole account and is never renewed, so until now it kept the Team features working offline until its own date, even after the team bought a plan or the trial was ended early.
|
package/hooks/cards.mjs
CHANGED
|
@@ -1,13 +1,17 @@
|
|
|
1
|
-
// @comment -- "bravos threat cards PostToolUse hook entry (Claude Code and Codex): after an edit, shows the developer a card for each new critical or high exposure no test has confirmed or refuted (hooks/lib/cards.mjs), gives the agent one line to raise it, logs it for bravos watch and, when the person turned it on, sends a desktop notification. Silent when BRAVOS_THREAT_CARDS=off, when the person switched cards off (bravos prefs set cards off), or when it is the plugin's copy in a repository that registers its own. Always exits 0; a failure shows nothing."
|
|
1
|
+
// @comment -- "bravos threat cards PostToolUse hook entry (Claude Code and Codex; Cursor postToolUse on Write; Antigravity PostToolUse, delivered at its next PreInvocation with --deliver; opencode and omp through their plugins): after an edit, shows the developer a card for each new critical or high exposure no test has confirmed or refuted (hooks/lib/cards.mjs), gives the agent one line to raise it, logs it for bravos watch and, when the person turned it on, sends a desktop notification. Silent when BRAVOS_THREAT_CARDS=off, when the person switched cards off (bravos prefs set cards off), or when it is the plugin's copy in a repository that registers its own; the no-record nudge has its own switch (bravos prefs set nudge off). Always exits 0; a failure shows nothing."
|
|
2
2
|
import { readFileSync, realpathSync } from 'node:fs';
|
|
3
3
|
import { basename, isAbsolute, join, relative } from 'node:path';
|
|
4
4
|
import { spawnSync } from 'node:child_process';
|
|
5
5
|
import { fileURLToPath } from 'node:url';
|
|
6
6
|
import { agentLine, decideCards, notify, readSeen, renderCard, targetRecorded, writeSeen } from './lib/cards.mjs';
|
|
7
7
|
import { gitCommonDir, readPrefs } from './lib/prefs.mjs';
|
|
8
|
+
import { cardsAnswer, cursorRunsOwn, deliverNotes, harnessArg, normalize, queueNote } from './lib/agent-io.mjs';
|
|
8
9
|
import { audience } from './lib/audience.mjs';
|
|
9
10
|
import { logWatchEvent } from './lib/snapshot.mjs';
|
|
10
11
|
import { adoptedPrinciples, principlesForFile } from './lib/principles.mjs';
|
|
12
|
+
import { moduleNudgeLine, noRecordLine, readSession, realInput, recordAgentLine, recordCardKey, renderRecordCard, ruleChanges, ruleThreats, uncoveredFiles, writeSession } from './lib/record-guard.mjs';
|
|
13
|
+
import { allRecords } from './lib/records.mjs';
|
|
14
|
+
import { touchedFiles } from './lib/cards.mjs';
|
|
11
15
|
|
|
12
16
|
// @comment -- "The after-edit note about the company's security design principles: when the edited file matches the paths an adopted principle names, one line for the agent naming that principle and its statement, so it keeps to it while it works. Statements come from principles.md, fingerprint-checked, cleaned to one line and cut short."
|
|
13
17
|
function principleNote(root, toolInput) {
|
|
@@ -36,7 +40,9 @@ async function readPayload() {
|
|
|
36
40
|
}
|
|
37
41
|
}
|
|
38
42
|
|
|
43
|
+
// @comment -- "The plugin's copy stays quiet where the repository registers its own cards: its .bravos/hooks/cards.mjs, or the hook launcher (bravos hook cards). The copy the launcher runs is the repository's own, so it never defers."
|
|
39
44
|
function deferToRepo(root) {
|
|
45
|
+
if (globalThis[Symbol.for('bravos.hook-launcher')] === true) return false;
|
|
40
46
|
try {
|
|
41
47
|
if (realpathSync(fileURLToPath(import.meta.url)) === realpathSync(join(root, '.bravos', 'hooks', 'cards.mjs'))) return false;
|
|
42
48
|
} catch {
|
|
@@ -44,7 +50,7 @@ function deferToRepo(root) {
|
|
|
44
50
|
}
|
|
45
51
|
for (const f of ['.claude/settings.json', '.codex/hooks.json']) {
|
|
46
52
|
try {
|
|
47
|
-
if (readFileSync(join(root, f), 'utf8')
|
|
53
|
+
if (/\.bravos\/hooks\/cards\.mjs|\bbravos hook cards\b/.test(readFileSync(join(root, f), 'utf8'))) return true;
|
|
48
54
|
} catch {
|
|
49
55
|
/* not registered there */
|
|
50
56
|
}
|
|
@@ -54,37 +60,80 @@ function deferToRepo(root) {
|
|
|
54
60
|
|
|
55
61
|
async function main() {
|
|
56
62
|
let out = {};
|
|
63
|
+
const asked = harnessArg(process.argv);
|
|
64
|
+
let n = { harness: asked, viaCursor: false };
|
|
65
|
+
let commonDir = null;
|
|
57
66
|
try {
|
|
58
67
|
if (process.env.BRAVOS_THREAT_CARDS === 'off') throw new Error('off');
|
|
59
68
|
// A machine without Bravos gets only the session-start invitation: no threat cards.
|
|
60
69
|
if (audience(process.env).kind === 'none') throw new Error('off');
|
|
61
|
-
|
|
62
|
-
const
|
|
63
|
-
const top = spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8', timeout: 3000, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
70
|
+
n = normalize(asked, await readPayload(), process.env);
|
|
71
|
+
const top = spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd: n.cwd || process.cwd(), encoding: 'utf8', timeout: 3000, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
64
72
|
if (top.status !== 0) throw new Error('not a repository');
|
|
65
73
|
const root = top.stdout.trim();
|
|
74
|
+
commonDir = gitCommonDir(root);
|
|
75
|
+
// Antigravity's PreInvocation: hand over what its after-edit hooks queued for this session, and nothing else.
|
|
76
|
+
if (process.argv.includes('--deliver')) {
|
|
77
|
+
process.stdout.write(JSON.stringify(n.harness === 'agy' ? deliverNotes(commonDir, n.sessionId) : {}) + '\n');
|
|
78
|
+
process.exit(0);
|
|
79
|
+
}
|
|
66
80
|
if (deferToRepo(root)) throw new Error('repo copy');
|
|
81
|
+
// Cursor also runs the Claude Code registration; where it has its own, that one answers.
|
|
82
|
+
if (n.viaCursor && cursorRunsOwn(root, 'cards')) throw new Error('cursor runs its own');
|
|
83
|
+
const payload = { tool_name: n.toolName, tool_input: n.toolInput, session_id: n.sessionId };
|
|
67
84
|
const note = principleNote(root, payload.tool_input);
|
|
68
85
|
if (note) out = { hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: note } };
|
|
69
|
-
const commonDir = gitCommonDir(root);
|
|
70
86
|
const prefs = readPrefs(commonDir);
|
|
71
|
-
|
|
72
|
-
const
|
|
73
|
-
const
|
|
74
|
-
|
|
87
|
+
// Cards switched off show no card; the principles note and the no-record nudge (its own switch) still speak.
|
|
88
|
+
const cardsOff = prefs.cards?.value === 'off';
|
|
89
|
+
const harness = n.harness;
|
|
90
|
+
const { cards, seen } = cardsOff ? { cards: [], seen: {} } : decideCards({ root, toolName: payload.tool_name, toolInput: payload.tool_input, seen: readSeen(commonDir) });
|
|
91
|
+
// @comment -- "Security decision records after an edit: a new exposure of an adopted record rule's threat, or a removed check of one, is a card once per rule and file; and, from the first session, the first edit of a module the ledger says needs a record and has none gets one line per module per session (code with security claims outside the ledger, one per file), unless the person switched the nudge off. Only adopted records raise cards; a failure here leaves the threat cards as they are."
|
|
92
|
+
let recordCards = [];
|
|
93
|
+
let recordNote = '';
|
|
94
|
+
try {
|
|
95
|
+
const records = allRecords(root);
|
|
96
|
+
const adopted = records.filter((r) => r.state === 'adopted');
|
|
97
|
+
const files = touchedFiles(root, realInput(payload.tool_input));
|
|
98
|
+
if (adopted.length && !cardsOff) {
|
|
99
|
+
recordCards = ruleChanges(root, files, ruleThreats(root, adopted)).filter((c) => !seen[recordCardKey(c)]);
|
|
100
|
+
for (const c of recordCards) seen[recordCardKey(c)] = new Date().toISOString();
|
|
101
|
+
}
|
|
102
|
+
// The no-record nudge speaks from the first session: no adopted record is needed, only the person not having switched it off.
|
|
103
|
+
if (typeof payload.session_id === 'string' && prefs.nudge?.value !== 'off' && process.env.BRAVOS_RECORD_NUDGE !== 'off') {
|
|
104
|
+
const s = uncoveredFiles(root, files, readSession(commonDir, payload.session_id), records);
|
|
105
|
+
if ((s.files.length || s.modules.length) && writeSession(commonDir, payload.session_id, s.state)) recordNote = [s.modules.length ? moduleNudgeLine(s.modules) : '', s.files.length ? noRecordLine(s.files) : ''].filter(Boolean).join('\n');
|
|
106
|
+
}
|
|
107
|
+
} catch {
|
|
108
|
+
recordCards = [];
|
|
109
|
+
recordNote = '';
|
|
110
|
+
}
|
|
111
|
+
if (cards.length || recordCards.length) {
|
|
75
112
|
writeSeen(commonDir, seen);
|
|
76
113
|
const target = targetRecorded(root);
|
|
77
114
|
const shown = cards.slice(0, 3);
|
|
78
115
|
const more = cards.length - shown.length;
|
|
79
|
-
const text = [
|
|
80
|
-
|
|
116
|
+
const text = [
|
|
117
|
+
...(recordCards.length ? ['bravos · decision record', ...recordCards.slice(0, 3).map(renderRecordCard)] : []),
|
|
118
|
+
...(cards.length ? ['bravos · threat card', ...shown.map((c) => renderCard(c, { target, harness })), ...(more > 0 ? [`… and ${more} more: bravos watch lists them`] : []), 'Shown once per threat. bravos watch and the dashboard keep the list.'] : []),
|
|
119
|
+
].join('\n');
|
|
120
|
+
out = { systemMessage: text, hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: [recordCards.length ? recordAgentLine(recordCards) : '', cards.length ? agentLine(cards, { target, harness }) : '', note, recordNote].filter(Boolean).join('\n') } };
|
|
81
121
|
for (const c of cards) logWatchEvent(root, { summary: `card: ${c.severity.toUpperCase()} ${c.threat} on ${c.asset} · ${c.file}${c.line ? `:${c.line}` : ''} · untested`, keys: [`bravos-card:${c.threat}`] });
|
|
82
|
-
|
|
122
|
+
for (const c of recordCards) logWatchEvent(root, { summary: `record: ${c.record.id} ${c.rule.id} ${c.kind === 'break' ? 'broken' : 'check removed'} · ${c.file}`, keys: [`bravos-record:${c.record.id}`] });
|
|
123
|
+
if (prefs.notify?.value === 'on' || process.env.BRAVOS_NOTIFY === 'on') {
|
|
124
|
+
if (cards.length) notify(cards[0], basename(root), { root });
|
|
125
|
+
}
|
|
126
|
+
} else if (recordNote) {
|
|
127
|
+
out = { hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: [note, recordNote].filter(Boolean).join('\n') } };
|
|
83
128
|
}
|
|
84
129
|
} catch (e) {
|
|
85
130
|
// Cards switched off still leave the principles note; anything else that failed shows nothing.
|
|
86
131
|
if (!(e instanceof Error && e.message === 'cards off')) out = {};
|
|
87
132
|
}
|
|
133
|
+
// @comment -- "The answer in the agent's own shape (hooks/lib/agent-io.mjs). Antigravity's after-edit hook cannot reach the model, so its note waits for the next model call (PreInvocation, bravos hook cards --harness agy --deliver)."
|
|
134
|
+
const said = { systemMessage: out.systemMessage ?? '', additionalContext: out.hookSpecificOutput?.additionalContext ?? '' };
|
|
135
|
+
if (n.harness === 'agy' && (said.systemMessage || said.additionalContext)) queueNote(commonDir, n.sessionId, [said.additionalContext, said.systemMessage ? `Show the person this, as it is:\n${said.systemMessage}` : ''].filter(Boolean).join('\n'));
|
|
136
|
+
out = n.harness === 'claude' || n.harness === 'codex' ? out : cardsAnswer(n.harness, said);
|
|
88
137
|
process.stdout.write(JSON.stringify(out) + '\n');
|
|
89
138
|
process.exit(0);
|
|
90
139
|
}
|
package/hooks/coach.mjs
CHANGED
|
@@ -32,7 +32,9 @@ const git = (cwd, args) => {
|
|
|
32
32
|
};
|
|
33
33
|
|
|
34
34
|
// The plugin's copy stays quiet where the repository registers its own coach, so the agent never hears it twice.
|
|
35
|
+
// @comment -- "The plugin's copy stays quiet where the repository registers its own coach: its .bravos/hooks/coach.mjs, or the hook launcher (bravos hook coach). The copy the launcher runs is the repository's own, so it never defers."
|
|
35
36
|
function deferToRepo(root) {
|
|
37
|
+
if (globalThis[Symbol.for('bravos.hook-launcher')] === true) return false;
|
|
36
38
|
try {
|
|
37
39
|
if (realpathSync(fileURLToPath(import.meta.url)) === realpathSync(join(root, '.bravos', 'hooks', 'coach.mjs'))) return false;
|
|
38
40
|
} catch {
|
|
@@ -40,7 +42,7 @@ function deferToRepo(root) {
|
|
|
40
42
|
}
|
|
41
43
|
for (const f of ['.claude/settings.json', '.codex/hooks.json']) {
|
|
42
44
|
try {
|
|
43
|
-
if (readFileSync(join(root, f), 'utf8')
|
|
45
|
+
if (/\.bravos\/hooks\/coach\.mjs|\bbravos hook coach\b/.test(readFileSync(join(root, f), 'utf8'))) return true;
|
|
44
46
|
} catch {
|
|
45
47
|
/* not registered there */
|
|
46
48
|
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// @comment -- "One place that knows how each coding agent hands an edit hook its payload and reads its answer, so the record guard (before an edit) and the cards hook (after one) speak every agent's shape: Claude Code and Codex (hookSpecificOutput), Cursor (.cursor/hooks.json preToolUse permission and postToolUse additional_context), Antigravity (.agents/hooks.json PreToolUse decision; its PostToolUse cannot reach the model, so notes wait for PreInvocation), and opencode and omp, whose plugins call bravos hook and translate a neutral { decision, reason } / { additionalContext } answer into a thrown error or a blocked tool call. Shapes were checked against each agent's docs and its installed build on 2026-11-28. Dependency-free and pure except the note queue, which writes only under the git directory."
|
|
2
|
+
import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
export const HARNESSES = ['claude', 'codex', 'cursor', 'agy', 'opencode', 'omp'];
|
|
6
|
+
const SESSION = /^[A-Za-z0-9._-]{1,128}$/;
|
|
7
|
+
// Cursor drops additional_context longer than this (and blocks with failClosed), so a note is cut to fit.
|
|
8
|
+
const CURSOR_CONTEXT_MAX = 9500;
|
|
9
|
+
|
|
10
|
+
/** The --harness value a hook was started with; anything unknown reads as claude, the shape every hook began with. */
|
|
11
|
+
export function harnessArg(argv) {
|
|
12
|
+
const i = argv.indexOf('--harness');
|
|
13
|
+
const v = i >= 0 ? argv[i + 1] : 'claude';
|
|
14
|
+
return HARNESSES.includes(v) ? v : 'claude';
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const str = (v) => (typeof v === 'string' && v ? v : null);
|
|
18
|
+
|
|
19
|
+
// @comment -- "The fields a hook needs, read from whichever agent sent the payload: the session id (session_id; Cursor's conversation_id; Antigravity's conversationId), the folder to find the repository from (cwd; Cursor's workspace_roots; Antigravity's workspacePaths), the tool and its input (Antigravity nests both in toolCall). A Claude-registered hook that Cursor runs (Cursor loads .claude/settings.json by default, and its payload carries cursor_version) is read as Cursor, so its answer is in Cursor's shape."
|
|
20
|
+
export function normalize(harness, payload, env = process.env) {
|
|
21
|
+
const p = payload && typeof payload === 'object' ? payload : {};
|
|
22
|
+
const viaCursor = harness !== 'cursor' && typeof p.cursor_version === 'string';
|
|
23
|
+
const h = viaCursor ? 'cursor' : harness;
|
|
24
|
+
const roots = (xs) => (Array.isArray(xs) ? xs.find((x) => typeof x === 'string' && x) : null);
|
|
25
|
+
if (h === 'agy') {
|
|
26
|
+
const call = p.toolCall && typeof p.toolCall === 'object' ? p.toolCall : {};
|
|
27
|
+
return { harness: h, viaCursor, sessionId: str(p.conversationId), cwd: roots(p.workspacePaths) ?? str(p.cwd), toolName: str(call.name), toolInput: call.args && typeof call.args === 'object' ? call.args : {} };
|
|
28
|
+
}
|
|
29
|
+
return {
|
|
30
|
+
harness: h,
|
|
31
|
+
viaCursor,
|
|
32
|
+
sessionId: str(p.session_id) ?? str(p.conversation_id),
|
|
33
|
+
cwd: h === 'cursor' ? roots(p.workspace_roots) ?? str(env.CURSOR_PROJECT_DIR) ?? str(p.cwd) : str(p.cwd) ?? str(env.CLAUDE_PROJECT_DIR),
|
|
34
|
+
toolName: str(p.tool_name),
|
|
35
|
+
toolInput: p.tool_input && typeof p.tool_input === 'object' ? p.tool_input : {},
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// @comment -- "The record guard's answer in the agent's own shape. Allowing prints the agent's empty answer where one is needed: Cursor blocks the edit on output that is not JSON, so it always gets {}. A refusal names the reason where that agent hands it to the model: Cursor's CLI builds the model's tool error from user_message, the server path from agent_message, so both carry it."
|
|
40
|
+
export function guardAnswer(harness, reason) {
|
|
41
|
+
if (!reason) return harness === 'cursor' || harness === 'agy' || harness === 'opencode' || harness === 'omp' ? {} : null;
|
|
42
|
+
if (harness === 'cursor') return { permission: 'deny', user_message: reason, agent_message: reason };
|
|
43
|
+
if (harness === 'agy' || harness === 'opencode' || harness === 'omp') return { decision: 'deny', reason };
|
|
44
|
+
return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: reason } };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// @comment -- "The cards hook's answer in the agent's own shape: for the person a card (systemMessage) where the agent can show one, and for the model the line it must act on (additionalContext). Cursor shows a hook's output to the model only, so the card goes into additional_context with the instruction to show it, cut to fit Cursor's limit. Antigravity's PostToolUse cannot reach the model: its note is queued (queueNote) and this answer is {}. opencode and omp get both texts and put them in the tool result their plugin hands the model."
|
|
48
|
+
export function cardsAnswer(harness, { systemMessage = '', additionalContext = '' } = {}) {
|
|
49
|
+
if (!systemMessage && !additionalContext) return harness === 'claude' || harness === 'codex' ? {} : {};
|
|
50
|
+
if (harness === 'cursor') {
|
|
51
|
+
const text = [additionalContext, systemMessage ? `Show the person this, as it is:\n${systemMessage}` : ''].filter(Boolean).join('\n');
|
|
52
|
+
return { additional_context: text.length > CURSOR_CONTEXT_MAX ? `${text.slice(0, CURSOR_CONTEXT_MAX - 1)}…` : text };
|
|
53
|
+
}
|
|
54
|
+
if (harness === 'agy') return {};
|
|
55
|
+
if (harness === 'opencode' || harness === 'omp') return { additionalContext: [additionalContext, systemMessage ? `Show the person this, as it is:\n${systemMessage}` : ''].filter(Boolean).join('\n') };
|
|
56
|
+
return { ...(systemMessage ? { systemMessage } : {}), hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext } };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const noteFile = (commonDir, sessionId) => (commonDir && typeof sessionId === 'string' && SESSION.test(sessionId) && !sessionId.startsWith('.') ? join(commonDir, 'bravos', 'agent-notes', `${sessionId}.json`) : null);
|
|
60
|
+
|
|
61
|
+
// @comment -- "Antigravity's after-edit notes wait here until its next model call: one small file per session under the git directory (never committed), 0600, bounded to the last 20 notes. A failure to write loses the note, never the edit."
|
|
62
|
+
export function queueNote(commonDir, sessionId, text) {
|
|
63
|
+
const file = noteFile(commonDir, sessionId);
|
|
64
|
+
if (!file || !text) return false;
|
|
65
|
+
try {
|
|
66
|
+
let notes = [];
|
|
67
|
+
try {
|
|
68
|
+
const j = JSON.parse(readFileSync(file, 'utf8'));
|
|
69
|
+
if (Array.isArray(j?.notes)) notes = j.notes.filter((n) => typeof n === 'string');
|
|
70
|
+
} catch {
|
|
71
|
+
/* none queued */
|
|
72
|
+
}
|
|
73
|
+
mkdirSync(join(file, '..'), { recursive: true, mode: 0o700 });
|
|
74
|
+
const tmp = `${file}.tmp-${process.pid}`;
|
|
75
|
+
writeFileSync(tmp, JSON.stringify({ notes: [...notes, text].slice(-20) }) + '\n', { mode: 0o600 });
|
|
76
|
+
renameSync(tmp, file);
|
|
77
|
+
return true;
|
|
78
|
+
} catch {
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// @comment -- "Hands Antigravity the notes waiting for this session, once, as its PreInvocation injectSteps system message (the nested { systemMessage: { systemMessage } } shape its hooks contract requires), and clears them. Nothing waiting: {}."
|
|
84
|
+
export function deliverNotes(commonDir, sessionId) {
|
|
85
|
+
const file = noteFile(commonDir, sessionId);
|
|
86
|
+
if (!file) return {};
|
|
87
|
+
let notes = [];
|
|
88
|
+
try {
|
|
89
|
+
notes = JSON.parse(readFileSync(file, 'utf8'))?.notes ?? [];
|
|
90
|
+
rmSync(file, { force: true });
|
|
91
|
+
} catch {
|
|
92
|
+
return {};
|
|
93
|
+
}
|
|
94
|
+
const text = (Array.isArray(notes) ? notes : []).filter((n) => typeof n === 'string' && n).join('\n\n');
|
|
95
|
+
return text ? { injectSteps: [{ systemMessage: { systemMessage: text, metadata: { source: 'bravos' } } }] } : {};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// @comment -- "Whether the repository's .cursor/hooks.json registers this Bravos hook itself (bravos hook <name> --harness cursor). Then a copy that Cursor runs from .claude/settings.json stays quiet, so the person and the model hear each card and refusal once."
|
|
99
|
+
export function cursorRunsOwn(root, name) {
|
|
100
|
+
try {
|
|
101
|
+
return new RegExp(`\\bbravos hook ${name} --harness cursor\\b`).test(readFileSync(join(root, '.cursor', 'hooks.json'), 'utf8'));
|
|
102
|
+
} catch {
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
}
|