@bugb-technologies/bravos 1.12.0 → 1.14.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/cli.js +6 -3
- package/dist/doctor.js +15 -2
- package/dist/guide.js +2 -0
- package/dist/help.js +16 -0
- package/dist/hooks.js +12 -2
- package/dist/install-proof-tool.js +3 -21
- package/dist/plugin.js +4 -2
- package/dist/prefs.js +13 -3
- package/dist/proof-tools.js +5 -3
- package/dist/report/data.js +2 -1
- package/dist/start/answers.js +4 -0
- package/dist/start/index.js +27 -1
- package/dist/tool-path.js +58 -0
- package/dist/uninstall.js +1 -1
- package/docs/GUIDE.md +8 -0
- package/docs/UPGRADING.md +40 -0
- package/hooks/cards.mjs +74 -0
- package/hooks/lib/briefing.mjs +5 -0
- package/hooks/lib/cards.mjs +201 -0
- package/hooks/lib/prefs.mjs +7 -4
- package/hooks/lib/replay.mjs +13 -1
- package/hooks/lib/threat-issues.mjs +343 -0
- package/hooks/lib/tool-path.mjs +56 -0
- package/package.json +1 -1
- package/skills/bravos-env/SKILL.md +1 -0
- package/skills/bravos-prove/SKILL.md +1 -1
- package/templates/workflows/bravos-nightly-claude.yml +60 -0
- package/templates/workflows/bravos-nightly-codex.yml +60 -0
- package/templates/workflows/bravos-nightly-copilot.yml +60 -0
package/hooks/cards.mjs
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
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."
|
|
2
|
+
import { readFileSync, realpathSync } from 'node:fs';
|
|
3
|
+
import { basename, join } from 'node:path';
|
|
4
|
+
import { spawnSync } from 'node:child_process';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { agentLine, decideCards, notify, readSeen, renderCard, targetRecorded, writeSeen } from './lib/cards.mjs';
|
|
7
|
+
import { gitCommonDir, readPrefs } from './lib/prefs.mjs';
|
|
8
|
+
import { logWatchEvent } from './lib/snapshot.mjs';
|
|
9
|
+
|
|
10
|
+
async function readPayload() {
|
|
11
|
+
if (process.stdin.isTTY) return {};
|
|
12
|
+
const read = (async () => {
|
|
13
|
+
const chunks = [];
|
|
14
|
+
for await (const c of process.stdin) chunks.push(c);
|
|
15
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
16
|
+
})().catch(() => '');
|
|
17
|
+
const raw = await Promise.race([read, new Promise((r) => setTimeout(() => r(''), 1000).unref())]);
|
|
18
|
+
try {
|
|
19
|
+
const p = JSON.parse(raw);
|
|
20
|
+
return p && typeof p === 'object' ? p : {};
|
|
21
|
+
} catch {
|
|
22
|
+
return {};
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function deferToRepo(root) {
|
|
27
|
+
try {
|
|
28
|
+
if (realpathSync(fileURLToPath(import.meta.url)) === realpathSync(join(root, '.bravos', 'hooks', 'cards.mjs'))) return false;
|
|
29
|
+
} catch {
|
|
30
|
+
/* no repository copy */
|
|
31
|
+
}
|
|
32
|
+
for (const f of ['.claude/settings.json', '.codex/hooks.json']) {
|
|
33
|
+
try {
|
|
34
|
+
if (readFileSync(join(root, f), 'utf8').includes('.bravos/hooks/cards.mjs')) return true;
|
|
35
|
+
} catch {
|
|
36
|
+
/* not registered there */
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async function main() {
|
|
43
|
+
let out = {};
|
|
44
|
+
try {
|
|
45
|
+
if (process.env.BRAVOS_THREAT_CARDS === 'off') throw new Error('off');
|
|
46
|
+
const payload = await readPayload();
|
|
47
|
+
const cwd = typeof payload.cwd === 'string' ? payload.cwd : process.env.CLAUDE_PROJECT_DIR || process.cwd();
|
|
48
|
+
const top = spawnSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8', timeout: 3000, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
49
|
+
if (top.status !== 0) throw new Error('not a repository');
|
|
50
|
+
const root = top.stdout.trim();
|
|
51
|
+
if (deferToRepo(root)) throw new Error('repo copy');
|
|
52
|
+
const commonDir = gitCommonDir(root);
|
|
53
|
+
const prefs = readPrefs(commonDir);
|
|
54
|
+
if (prefs.cards?.value === 'off') throw new Error('off');
|
|
55
|
+
const harness = process.argv.includes('--harness') ? process.argv[process.argv.indexOf('--harness') + 1] : 'claude';
|
|
56
|
+
const { cards, seen } = decideCards({ root, toolName: payload.tool_name, toolInput: payload.tool_input, seen: readSeen(commonDir) });
|
|
57
|
+
if (cards.length) {
|
|
58
|
+
writeSeen(commonDir, seen);
|
|
59
|
+
const target = targetRecorded(root);
|
|
60
|
+
const shown = cards.slice(0, 3);
|
|
61
|
+
const more = cards.length - shown.length;
|
|
62
|
+
const text = ['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.'].join('\n');
|
|
63
|
+
out = { systemMessage: text, hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: agentLine(cards, { target, harness }) } };
|
|
64
|
+
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}`] });
|
|
65
|
+
if (prefs.notify?.value === 'on' || process.env.BRAVOS_NOTIFY === 'on') notify(cards[0], basename(root));
|
|
66
|
+
}
|
|
67
|
+
} catch {
|
|
68
|
+
out = {};
|
|
69
|
+
}
|
|
70
|
+
process.stdout.write(JSON.stringify(out) + '\n');
|
|
71
|
+
process.exit(0);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
main();
|
package/hooks/lib/briefing.mjs
CHANGED
|
@@ -8,6 +8,7 @@ import { legacySkills, legacySkillsLine } from './legacy-skills.mjs';
|
|
|
8
8
|
import { THEMES } from './palette.mjs';
|
|
9
9
|
import { commitsLine, commonDirFrom, readHandoff, readPrefs } from './prefs.mjs';
|
|
10
10
|
import { cliVersion, newer, readUpdate, updateLine } from './update-check.mjs';
|
|
11
|
+
import { cxgPathLine, findTool } from './tool-path.mjs';
|
|
11
12
|
import { readProving } from './proving.mjs';
|
|
12
13
|
import { planLabel, planLine, status as licenceStatus } from './licence.mjs';
|
|
13
14
|
import { readLicenceNote, refreshIfDue } from './refresh.mjs';
|
|
@@ -282,6 +283,8 @@ export function buildBriefing(inputs) {
|
|
|
282
283
|
// A newer Bravos published than the one installed (hooks/lib/update-check.mjs): the person installs it.
|
|
283
284
|
const update = updateLine(i.update, i.cli);
|
|
284
285
|
if (update) tail.push(update);
|
|
286
|
+
const cxgLine = cxgPathLine(i.cxg, { HOME: i.env?.HOME ?? process.env.HOME, SHELL: i.env?.SHELL ?? process.env.SHELL });
|
|
287
|
+
if (cxgLine) tail.push(cxgLine);
|
|
285
288
|
// The portal's last refusal to renew this machine, until it is signed in again (a revocation) or renewed (a plan that ended).
|
|
286
289
|
if (i.licenceNote && (i.licenceNote.outcome === 'lapsed' || i.licence?.licensed === false)) tail.push(`Licence: ${i.licenceNote.note} Tell the person once, in plain words.`);
|
|
287
290
|
// Skills the retired Python bravos left at user level: the agent must not follow them (hooks/lib/legacy-skills.mjs).
|
|
@@ -590,6 +593,8 @@ export async function collect(root, env, { deadlineMs = 20000, nextCount = 3 } =
|
|
|
590
593
|
// The last daily update check (~/.bravos/update-check.json) and the installed CLI's version, both file reads.
|
|
591
594
|
update: readUpdate(env.HOME || homedir()),
|
|
592
595
|
cli: cliVersion(env),
|
|
596
|
+
// Where cxg is, when it is installed: off PATH in this session is not missing (hooks/lib/tool-path.mjs).
|
|
597
|
+
cxg: findTool('cxg', { ...env, HOME: env.HOME || homedir() }),
|
|
593
598
|
annotationMode: readAnnotationMode(root),
|
|
594
599
|
// bravos on PATH: what its probe says (a graph for this commit or not); else codegraph-mcp on PATH means the MCP route.
|
|
595
600
|
codegraph: graphState ?? (whichOnPath('codegraph-mcp', env) ? 'unknown' : 'unavailable'),
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
// @comment -- "Threat cards: right after an edit, a new critical or high @exposes claim that no test has confirmed or refuted is shown to the developer as a card in their terminal (the hook's systemMessage), and the agent is told to raise it and recommend confirming it. Only lines that are not in the last commit count, so existing claims never raise a card; each threat raises one card per clone (recorded under the git directory). Reads files, git's HEAD copy and the local ledger; never runs guardlink, never runs a test and never contacts the network. Dependency-free."
|
|
2
|
+
import { spawnSync } from 'node:child_process';
|
|
3
|
+
import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
5
|
+
import { readProving } from './proving.mjs';
|
|
6
|
+
|
|
7
|
+
export const CARDS_SCHEMA = 'bravos.cards/v1';
|
|
8
|
+
const SEVERITY = { critical: 'critical', p0: 'critical', high: 'high', p1: 'high' };
|
|
9
|
+
const MAX_FILES = 40;
|
|
10
|
+
const MAX_BYTES = 2 * 1024 * 1024;
|
|
11
|
+
const MAX_SEEN = 4000;
|
|
12
|
+
|
|
13
|
+
// An exposes line: the asset, "to", the threat, a severity in brackets, optional refs, then the quoted description.
|
|
14
|
+
const EXPOSES = /@exposes\s+(\S+)\s+to\s+(#[\w.-]+)\s*\[(critical|high|p0|p1)\]([^"\n]*?)(?:--\s*"((?:[^"\\]|\\.)*)"|\s*(?:\*\/)?\s*$)/i;
|
|
15
|
+
|
|
16
|
+
export const cardsFile = (commonDir) => join(commonDir, 'bravos', 'cards.json');
|
|
17
|
+
|
|
18
|
+
// @comment -- "The repository files an edit touched: file_path or notebook_path in the tool input, and every path an apply_patch text names (*** Add File / *** Update File / *** Move to). Paths outside the repository are dropped, so a payload cannot point the hook at other files."
|
|
19
|
+
// @mitigates #threat-cards against #out-of-repo-read using #repo-bound-paths -- "touchedFiles() keeps only paths that resolve inside the repository root and outside .git, so a crafted tool payload cannot make the hook read other files"
|
|
20
|
+
export function touchedFiles(root, toolInput) {
|
|
21
|
+
const out = new Set();
|
|
22
|
+
const add = (p) => {
|
|
23
|
+
if (typeof p !== 'string' || !p.trim()) return;
|
|
24
|
+
const abs = isAbsolute(p) ? resolve(p) : resolve(root, p.trim());
|
|
25
|
+
const rel = relative(root, abs);
|
|
26
|
+
if (!rel || rel.startsWith('..') || isAbsolute(rel) || rel.split(sep).includes('.git')) return;
|
|
27
|
+
out.add(rel.split(sep).join('/'));
|
|
28
|
+
};
|
|
29
|
+
const input = toolInput && typeof toolInput === 'object' ? toolInput : {};
|
|
30
|
+
add(input.file_path);
|
|
31
|
+
add(input.notebook_path);
|
|
32
|
+
for (const v of Object.values(input)) {
|
|
33
|
+
if (typeof v !== 'string') continue;
|
|
34
|
+
for (const m of v.matchAll(/^\*\*\* (?:Add File|Update File|Move to): (.+)$/gm)) add(m[1]);
|
|
35
|
+
}
|
|
36
|
+
return [...out].slice(0, MAX_FILES);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// @comment -- "The files changed in the working tree against HEAD (tracked and untracked), for a harness whose edit tool does not name its files. Bounded and read-only."
|
|
40
|
+
export function changedFiles(root) {
|
|
41
|
+
const r = spawnSync('git', ['status', '--porcelain', '-z', '--untracked-files=all'], { cwd: root, encoding: 'utf8', timeout: 3000, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
42
|
+
if (r.status !== 0) return [];
|
|
43
|
+
return r.stdout.split('\0').filter(Boolean).map((l) => l.slice(3)).filter((p) => p && !p.startsWith('.git/')).slice(0, MAX_FILES);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** A sidecar under .guardlink/annotations/<source>.gal describes <source>. */
|
|
47
|
+
export const logicalFile = (rel) => (rel.startsWith('.guardlink/annotations/') && rel.endsWith('.gal') ? rel.slice('.guardlink/annotations/'.length, -'.gal'.length) : rel);
|
|
48
|
+
|
|
49
|
+
function headLines(root, rel) {
|
|
50
|
+
const r = spawnSync('git', ['show', `HEAD:${rel}`], { cwd: root, encoding: 'utf8', timeout: 3000, maxBuffer: MAX_BYTES, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
51
|
+
return r.status === 0 ? new Set(r.stdout.split('\n').map((l) => l.trim())) : new Set();
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// @comment -- "The critical and high exposures in the given files whose line is not in the file's last commit: what this work added. Each gives the asset, threat, severity, any cwe reference, the description, the logical file (a sidecar's source) and the line."
|
|
55
|
+
export function newExposures(root, files) {
|
|
56
|
+
const out = [];
|
|
57
|
+
for (const rel of files) {
|
|
58
|
+
const abs = join(root, rel);
|
|
59
|
+
let text;
|
|
60
|
+
try {
|
|
61
|
+
if (!statSync(abs).isFile() || statSync(abs).size > MAX_BYTES) continue;
|
|
62
|
+
text = readFileSync(abs, 'utf8');
|
|
63
|
+
} catch {
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
if (!/@exposes/i.test(text)) continue;
|
|
67
|
+
const before = headLines(root, rel);
|
|
68
|
+
text.split('\n').forEach((line, n) => {
|
|
69
|
+
const m = EXPOSES.exec(line);
|
|
70
|
+
if (!m || before.has(line.trim())) return;
|
|
71
|
+
const cwe = /\bcwe:(CWE-\d+)/i.exec(m[4] ?? '')?.[1] ?? null;
|
|
72
|
+
out.push({ asset: m[1], threat: m[2], severity: SEVERITY[m[3].toLowerCase()], cwe, description: (m[5] ?? '').replace(/\\"/g, '"').slice(0, 400), file: logicalFile(rel), line: rel === logicalFile(rel) ? n + 1 : null, written: rel });
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// @comment -- "Whether the local ledger already has a confirmed or refuted outcome for this claim: an entry for the same logical file whose claim names both the threat and the asset. A missing or damaged ledger means untested."
|
|
79
|
+
export function tested(root, x) {
|
|
80
|
+
let ledger;
|
|
81
|
+
try {
|
|
82
|
+
ledger = JSON.parse(readFileSync(join(root, '.guardlink', 'hypotheses.json'), 'utf8'));
|
|
83
|
+
} catch {
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
const entries = Array.isArray(ledger?.entries) ? ledger.entries : [];
|
|
87
|
+
return entries.some((e) => e && e.file === x.file && typeof e.claim === 'string' && e.claim.includes(x.threat) && e.claim.includes(x.asset) && (e.outcome === 'confirmed' || e.outcome === 'refuted'));
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export const cardKey = (x) => `${x.file}|${x.asset}|${x.threat}|${x.severity}`;
|
|
91
|
+
|
|
92
|
+
export function readSeen(commonDir) {
|
|
93
|
+
try {
|
|
94
|
+
const d = JSON.parse(readFileSync(cardsFile(commonDir), 'utf8'));
|
|
95
|
+
return d?.schema === CARDS_SCHEMA && d.seen && typeof d.seen === 'object' ? d.seen : {};
|
|
96
|
+
} catch {
|
|
97
|
+
return {};
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function writeSeen(commonDir, seen) {
|
|
102
|
+
try {
|
|
103
|
+
const file = cardsFile(commonDir);
|
|
104
|
+
mkdirSync(join(file, '..'), { recursive: true, mode: 0o700 });
|
|
105
|
+
const keys = Object.keys(seen).sort((a, b) => String(seen[a]).localeCompare(String(seen[b]))).slice(-MAX_SEEN);
|
|
106
|
+
const tmp = `${file}.tmp-${process.pid}`;
|
|
107
|
+
writeFileSync(tmp, JSON.stringify({ schema: CARDS_SCHEMA, seen: Object.fromEntries(keys.map((k) => [k, seen[k]])) }) + '\n', { mode: 0o600 });
|
|
108
|
+
renameSync(tmp, file);
|
|
109
|
+
} catch {
|
|
110
|
+
/* best effort: at worst a card shows again */
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Only printable text from an annotation reaches the terminal or the agent.
|
|
115
|
+
const clean = (s, max) => String(s ?? '').replace(/[\u0000-\u001F\u007F-\u009F----]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, max);
|
|
116
|
+
|
|
117
|
+
function wrap(text, width) {
|
|
118
|
+
const out = [];
|
|
119
|
+
let line = '';
|
|
120
|
+
for (const word of text.split(' ')) {
|
|
121
|
+
if (!word) continue;
|
|
122
|
+
if ((line + ' ' + word).trim().length > width) {
|
|
123
|
+
if (line) out.push(line);
|
|
124
|
+
line = word.length > width ? word.slice(0, width) : word;
|
|
125
|
+
} else line = (line + ' ' + word).trim();
|
|
126
|
+
}
|
|
127
|
+
if (line) out.push(line);
|
|
128
|
+
return out;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// @comment -- "One card as plain text in a box, for the developer's terminal: severity, the description, the claim and where it is, the state, and one next step (bravos-prove when a test target is recorded, else bravos-env first). Annotation text is cleaned of control and invisible characters first."
|
|
132
|
+
// @exposes #threat-cards to #terminal-escape-injection [low] cwe:CWE-150 -- "renderCard() and agentLine() draw the description, threat and asset ids that newExposures() read from a file's @exposes line, text anyone who can edit the repository controls, into the developer's terminal and the agent's context"
|
|
133
|
+
// @mitigates #threat-cards against #terminal-escape-injection using #printable-text-only -- "clean() removes control, bidirectional and invisible characters and caps the length before any annotation text is drawn"
|
|
134
|
+
export function renderCard(x, { target = false, harness = 'claude', width = 58 } = {}) {
|
|
135
|
+
const k = (n) => (harness === 'claude' ? `/${n}` : n);
|
|
136
|
+
const sev = x.severity === 'critical' ? 'CRITICAL' : 'HIGH';
|
|
137
|
+
const where = `${clean(x.file, 120)}${x.line ? `:${x.line}` : ''}`;
|
|
138
|
+
const body = [
|
|
139
|
+
`${sev} · new threat, not confirmed yet`,
|
|
140
|
+
'',
|
|
141
|
+
...wrap(clean(x.description, 400) || `${clean(x.threat, 60)} on ${clean(x.asset, 60)}`, width),
|
|
142
|
+
`${clean(x.threat, 60)} on ${clean(x.asset, 60)}${x.cwe ? ` · cwe:${x.cwe}` : ''}`,
|
|
143
|
+
...wrap(where, width),
|
|
144
|
+
'',
|
|
145
|
+
'state untested · found in this session',
|
|
146
|
+
target ? `next ${k('bravos-prove')} to confirm it on the recorded target` : `next ${k('bravos-env')} to set up a test target, then ${k('bravos-prove')}`,
|
|
147
|
+
];
|
|
148
|
+
const w = Math.max(...body.map((l) => l.length));
|
|
149
|
+
return ['╭' + '─'.repeat(w + 2) + '╮', ...body.map((l) => `│ ${l.padEnd(w)} │`), '╰' + '─'.repeat(w + 2) + '╯'].join('\n');
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// @comment -- "What the agent is told for the new cards: raise each in this reply, in plain words, and recommend confirming it now; never confirm, refute or accept it itself."
|
|
153
|
+
export function agentLine(cards, { target = false, harness = 'claude' } = {}) {
|
|
154
|
+
if (!cards.length) return '';
|
|
155
|
+
const k = (n) => (harness === 'claude' ? `/${n}` : n);
|
|
156
|
+
const list = cards.map((x) => `${x.severity} ${clean(x.threat, 60)} on ${clean(x.asset, 60)} (${clean(x.file, 120)}${x.line ? `:${x.line}` : ''})`).join('; ');
|
|
157
|
+
const how = target ? `${k('bravos-prove')} on the recorded target` : `${k('bravos-env')} to set up a target (the person types their own authorization), then ${k('bravos-prove')}`;
|
|
158
|
+
return `Bravos threat card${cards.length === 1 ? '' : 's'} shown to the person: ${list}. In this reply, say in plain words what ${cards.length === 1 ? 'it is' : 'they are'} and recommend confirming ${cards.length === 1 ? 'it' : 'them'} now with ${how}. Only a real test confirms or refutes a threat, and only a named person accepts one: never write @confirmed or @accepts.`;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// @comment -- "The whole decision for one edit: the files it touched (or, when the payload names none and the tool can write files, the working tree's changed files), their new critical and high exposures, minus those already tested and those already carded in this clone. Returns the cards to show and the updated seen record."
|
|
162
|
+
export function decideCards({ root, toolName = '', toolInput = {}, seen = {}, now = new Date() }) {
|
|
163
|
+
let files = touchedFiles(root, toolInput);
|
|
164
|
+
if (!files.length && /patch|shell|bash|exec|write|edit/i.test(String(toolName))) files = changedFiles(root);
|
|
165
|
+
if (!files.length) return { cards: [], seen };
|
|
166
|
+
const next = { ...seen };
|
|
167
|
+
const cards = [];
|
|
168
|
+
for (const x of newExposures(root, files)) {
|
|
169
|
+
const key = cardKey(x);
|
|
170
|
+
if (next[key] || tested(root, x)) continue;
|
|
171
|
+
next[key] = now.toISOString();
|
|
172
|
+
cards.push(x);
|
|
173
|
+
}
|
|
174
|
+
return { cards, seen: next };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// @comment -- "An opt-in desktop notification (bravos prefs set notify on): macOS through osascript and Linux through notify-send, with the text passed as arguments to a fixed script, never spliced into it, and nothing waited on."
|
|
178
|
+
// @mitigates #threat-cards against #notification-script-injection using #argv-only -- "notify() passes the title and text as osascript and notify-send arguments to a fixed program, so annotation text is never parsed as AppleScript or options"
|
|
179
|
+
export function notify(card, repo) {
|
|
180
|
+
const title = `${card.severity === 'critical' ? 'Critical' : 'High'} threat found · ${clean(repo, 40)}`;
|
|
181
|
+
const text = `${clean(card.file, 80)}${card.line ? `:${card.line}` : ''} · ${clean(card.description, 140) || clean(card.threat, 60)}. Not confirmed yet.`;
|
|
182
|
+
try {
|
|
183
|
+
if (process.platform === 'darwin') {
|
|
184
|
+
spawnSync('osascript', ['-e', 'on run argv', '-e', 'display notification (item 2 of argv) with title (item 1 of argv)', '-e', 'end run', title, text], { timeout: 3000, stdio: 'ignore' });
|
|
185
|
+
} else if (process.platform === 'linux') {
|
|
186
|
+
spawnSync('notify-send', ['--', title, text], { timeout: 3000, stdio: 'ignore' });
|
|
187
|
+
}
|
|
188
|
+
} catch {
|
|
189
|
+
/* a notification is a convenience */
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Whether a test target is recorded in the person's proving answer (.guardlink/proving.md), for the next-step wording. */
|
|
194
|
+
export function targetRecorded(root) {
|
|
195
|
+
try {
|
|
196
|
+
const p = readProving(root);
|
|
197
|
+
return p?.status === 'set' && !!p.target;
|
|
198
|
+
} catch {
|
|
199
|
+
return false;
|
|
200
|
+
}
|
|
201
|
+
}
|
package/hooks/lib/prefs.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// @comment -- "A person's standing answers to questions Bravos would otherwise ask every session, kept per clone and never committed. Two today: what to do with Bravos's own files (annotations, intent, definitions, tests, the ledger) once they are written: commit them, leave them for the person, or keep asking; whether the agent starts one background annotation pass each session while coverage is incomplete (background, the default) or not (off);
|
|
1
|
+
// @comment -- "A person's standing answers to questions Bravos would otherwise ask every session, kept per clone and never committed. Two today: what to do with Bravos's own files (annotations, intent, definitions, tests, the ledger) once they are written: commit them, leave them for the person, or keep asking; whether the agent starts one background annotation pass each session while coverage is incomplete (background, the default) or not (off); whether the coach adds reminders before prompts (on, the default) or not (off); and whether threat cards show (on, the default) and send a desktop notification (off by default). The file lives under the git directory (<git-common-dir>/bravos/prefs.json), which no commit, clone or pull can write, so a repository cannot ship an answer and grant itself silent commits, and every worktree of a clone shares it. Dependency-free: the session hook reads it, the CLI writes it."
|
|
2
2
|
import { spawnSync } from 'node:child_process';
|
|
3
3
|
import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
4
4
|
import { isAbsolute, join, resolve } from 'node:path';
|
|
@@ -11,7 +11,10 @@ export const ANNOTATE_CHOICES = ['background', 'off'];
|
|
|
11
11
|
/** on: the coach adds a reminder before a prompt when one is due (the default when nothing is recorded). off: none. */
|
|
12
12
|
export const COACH_CHOICES = ['on', 'off'];
|
|
13
13
|
/** Each recorded answer and the choices it may hold. */
|
|
14
|
-
|
|
14
|
+
/** cards: on shows a threat card after an edit adds an untested critical or high exposure (the default); off shows none. notify: on also sends a desktop notification for it (off by default). */
|
|
15
|
+
export const CARDS_CHOICES = ['on', 'off'];
|
|
16
|
+
export const NOTIFY_CHOICES = ['off', 'on'];
|
|
17
|
+
export const PREF_CHOICES = { commits: COMMIT_CHOICES, annotate: ANNOTATE_CHOICES, coach: COACH_CHOICES, cards: CARDS_CHOICES, notify: NOTIFY_CHOICES };
|
|
15
18
|
|
|
16
19
|
// One line of visible text: a name goes into the briefing, so control and invisible characters never do.
|
|
17
20
|
const clean = (v, max) => String(v ?? '').replace(/[\u0000-\u001F\u007F-\u009F----]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, max);
|
|
@@ -35,7 +38,7 @@ export const prefsFile = (commonDir) => join(commonDir, 'bravos', 'prefs.json');
|
|
|
35
38
|
// @comment -- "Reads the preferences for a clone, each answer on its own. An answer that is not exactly the recorded shape (another schema, an unknown choice, no name, a date that is not a date) reads as nothing recorded, so a damaged or hand-made file can only make Bravos ask again or fall back to its default, never commit."
|
|
36
39
|
// @mitigates #person-prefs against #governance-forgery using #prefs-outside-tree -- "Only a well-formed record under the git directory counts as the person's answer."
|
|
37
40
|
export function readPrefs(commonDir) {
|
|
38
|
-
const none = { commits: null, annotate: null, coach: null };
|
|
41
|
+
const none = { commits: null, annotate: null, coach: null, cards: null, notify: null };
|
|
39
42
|
if (!commonDir) return none;
|
|
40
43
|
let doc;
|
|
41
44
|
try {
|
|
@@ -51,7 +54,7 @@ export function readPrefs(commonDir) {
|
|
|
51
54
|
if (!by || by.startsWith('<') || typeof c.at !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(c.at)) return null;
|
|
52
55
|
return { value: c.value, by, at: c.at };
|
|
53
56
|
};
|
|
54
|
-
return { commits: one('commits'), annotate: one('annotate'), coach: one('coach') };
|
|
57
|
+
return { commits: one('commits'), annotate: one('annotate'), coach: one('coach'), cards: one('cards'), notify: one('notify') };
|
|
55
58
|
}
|
|
56
59
|
|
|
57
60
|
// @comment -- "Records the commits answer a named person gave (writePref does the work)."
|
package/hooks/lib/replay.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// @comment -- "Run one supplied, bound JavaScript probe per CXG process. Authority for target contact comes from the reviewed policy and scope; a kit controls neither. Only an engine verdict and an unchanged binding can update an exposure."
|
|
2
2
|
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import { findTool, withToolDir } from './tool-path.mjs';
|
|
3
4
|
import { spawnSync } from 'node:child_process';
|
|
4
5
|
import { closeSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readSync, readlinkSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
|
|
5
6
|
import { createConnection } from 'node:net';
|
|
@@ -23,8 +24,19 @@ function localFile(root, name) {
|
|
|
23
24
|
return file;
|
|
24
25
|
}
|
|
25
26
|
|
|
27
|
+
// @comment -- "Runs a fixed command with no shell. cxg is found on PATH or, when the session's PATH lacks it, in cargo's folder (hooks/lib/tool-path.mjs), and run by that full path with its folder added to PATH, so 'not on PATH' never stops a replay of an installed cxg. In CI there is no fallback: only the job's own cxg on PATH runs."
|
|
28
|
+
// @mitigates #replay-ledger against #tool-tampering using #cache-isolation -- "invoke() looks outside PATH for cxg only off CI, so a CI replay runs only the cxg its own job installed"
|
|
26
29
|
function invoke(command, args, cwd, opts = {}) {
|
|
27
|
-
|
|
30
|
+
let env = opts.env ?? sanitizedEnv(process.env);
|
|
31
|
+
if (command === 'cxg') {
|
|
32
|
+
// In CI only the cxg the job put on PATH runs: a binary left in a home folder by an earlier step is never picked up.
|
|
33
|
+
const found = findTool('cxg', { ...env, HOME: env.HOME ?? process.env.HOME }, { fallback: !(process.env.CI || process.env.GITHUB_ACTIONS) });
|
|
34
|
+
if (found) {
|
|
35
|
+
command = found.path;
|
|
36
|
+
env = withToolDir(env, found);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
const result = spawnSync(command, args, { cwd, env, input: opts.input, encoding: 'utf8', timeout: opts.timeout ?? 120000,
|
|
28
40
|
stdio: ['pipe', 'pipe', 'pipe'], maxBuffer: 64 * 1024 * 1024 });
|
|
29
41
|
if (result.error || !(opts.allowed ?? [0]).includes(result.status)) {
|
|
30
42
|
// Tool stderr can include provider bodies, session details or scan evidence.
|