@bugb-technologies/bravos 1.24.0 → 1.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +12 -0
- package/dist/cli.js +189 -15
- 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 +3 -1
- package/dist/hook-launcher.js +92 -0
- package/dist/hooks.js +56 -3
- package/dist/prefs.js +13 -3
- 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/uninstall.js +1 -1
- package/dist/upkeep.js +3 -0
- package/docs/GUIDE.md +10 -0
- package/docs/UPGRADING.md +40 -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 +8 -1
- 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
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
// @comment -- "Security decision records at edit time (records part two). Before an edit: the first edit in a session to a file an adopted record covers is refused once, with the record's id, path, adopters, rules and not-a-bug list, so the agent reads the decision before it changes the code; the next attempt goes through. After an edit: a new exposure of a record rule's threat, or a removed check of one, is a card for the developer and a line for the agent; 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 (security-relevant code outside the ledger, or with no ledger yet, one line per file per session). Everything here only reads the repository and writes one small session file under the git directory; any failure means allow and say nothing."
|
|
2
|
+
import { spawnSync } from 'node:child_process';
|
|
3
|
+
import { mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, statSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { basename, dirname, isAbsolute, join } from 'node:path';
|
|
5
|
+
import { logicalFile, touchedFiles } from './cards.mjs';
|
|
6
|
+
import { moduleForFile, readLedger } from './ledger.mjs';
|
|
7
|
+
import { adoptedRecords, allRecords, recordsForFile, ruleOfThreat } from './records.mjs';
|
|
8
|
+
|
|
9
|
+
const SESSION = /^[A-Za-z0-9._-]{1,128}$/;
|
|
10
|
+
const MAX_BYTES = 2 * 1024 * 1024;
|
|
11
|
+
const MAX_KEPT = 2000;
|
|
12
|
+
export const SESSION_SCHEMA = 'bravos.records-session/v1';
|
|
13
|
+
|
|
14
|
+
// ---------------------------------------------------------------------------------------------
|
|
15
|
+
// Per-session state: which covered files this session has been shown its record for, and which
|
|
16
|
+
// uncovered files it was told have no record.
|
|
17
|
+
// ---------------------------------------------------------------------------------------------
|
|
18
|
+
|
|
19
|
+
// @comment -- "Where a session's records state lives: under the git directory (never committed, nothing a repository ships can set it), one file per session; null for a session id that is not a plain token, so a payload cannot name a path."
|
|
20
|
+
export function sessionFile(commonDir, sessionId) {
|
|
21
|
+
if (!commonDir || typeof sessionId !== 'string' || !SESSION.test(sessionId) || sessionId.startsWith('.')) return null;
|
|
22
|
+
return join(commonDir, 'bravos', 'records-session', `${sessionId}.json`);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function readSession(commonDir, sessionId) {
|
|
26
|
+
const file = sessionFile(commonDir, sessionId);
|
|
27
|
+
const empty = { read: {}, noRecord: {} };
|
|
28
|
+
if (!file) return empty;
|
|
29
|
+
try {
|
|
30
|
+
const j = JSON.parse(readFileSync(file, 'utf8'));
|
|
31
|
+
const obj = (v) => (v && typeof v === 'object' && !Array.isArray(v) ? v : {});
|
|
32
|
+
return j?.schema === SESSION_SCHEMA ? { read: obj(j.read), noRecord: obj(j.noRecord) } : empty;
|
|
33
|
+
} catch {
|
|
34
|
+
return empty;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// @comment -- "Writes a session's records state atomically (temporary file, then rename), 0600 in a 0700 folder, bounded in size. A failure to write is swallowed: at worst a record is shown again."
|
|
39
|
+
export function writeSession(commonDir, sessionId, state) {
|
|
40
|
+
const file = sessionFile(commonDir, sessionId);
|
|
41
|
+
if (!file) return null;
|
|
42
|
+
const trim = (o) => Object.fromEntries(Object.entries(o).slice(-MAX_KEPT));
|
|
43
|
+
try {
|
|
44
|
+
mkdirSync(join(file, '..'), { recursive: true, mode: 0o700 });
|
|
45
|
+
const tmp = `${file}.tmp-${process.pid}`;
|
|
46
|
+
writeFileSync(tmp, JSON.stringify({ schema: SESSION_SCHEMA, read: trim(state.read), noRecord: trim(state.noRecord) }) + '\n', { mode: 0o600 });
|
|
47
|
+
renameSync(tmp, file);
|
|
48
|
+
return file;
|
|
49
|
+
} catch {
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// ---------------------------------------------------------------------------------------------
|
|
55
|
+
// Which threat stands for which record rule
|
|
56
|
+
// ---------------------------------------------------------------------------------------------
|
|
57
|
+
|
|
58
|
+
// @comment -- "The definitions file GuardLink reads (.guardlink/config.json names it, else any .guardlink/definitions.*). Read-only, bounded."
|
|
59
|
+
function definitionsText(root) {
|
|
60
|
+
let names = [];
|
|
61
|
+
try {
|
|
62
|
+
const c = JSON.parse(readFileSync(join(root, '.guardlink', 'config.json'), 'utf8'));
|
|
63
|
+
if (typeof c?.definitions === 'string' && /^[\w.-]+$/.test(c.definitions)) names = [c.definitions];
|
|
64
|
+
} catch {
|
|
65
|
+
/* no config */
|
|
66
|
+
}
|
|
67
|
+
if (!names.length) {
|
|
68
|
+
try {
|
|
69
|
+
names = readdirSync(join(root, '.guardlink')).filter((n) => /^definitions\.[a-z]+$/.test(n));
|
|
70
|
+
} catch {
|
|
71
|
+
names = [];
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return names
|
|
75
|
+
.map((n) => {
|
|
76
|
+
try {
|
|
77
|
+
const abs = join(root, '.guardlink', n);
|
|
78
|
+
return statSync(abs).size <= MAX_BYTES ? readFileSync(abs, 'utf8') : '';
|
|
79
|
+
} catch {
|
|
80
|
+
return '';
|
|
81
|
+
}
|
|
82
|
+
})
|
|
83
|
+
.join('\n');
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// @comment -- "Each threat the definitions give a record reference (record:SDR-n), mapped to that record's rule: the rule its description starts with ('SDR-3 R1: …'), or, when the description names none and the record has exactly one enforced rule, that rule. A threat that names no rule of a record with several is left out."
|
|
87
|
+
export function ruleThreats(root, records) {
|
|
88
|
+
const out = new Map();
|
|
89
|
+
for (const line of definitionsText(root).split('\n')) {
|
|
90
|
+
if (!/@threat\b/.test(line)) continue;
|
|
91
|
+
const id = /\(#([\w.-]+)\)/.exec(line)?.[1];
|
|
92
|
+
if (!id) continue;
|
|
93
|
+
const refs = [...line.matchAll(/\brecord:(SDR-[1-9][0-9]{0,3})\b/gi)].map((m) => `record:${m[1]}`);
|
|
94
|
+
const description = /--\s*"((?:[^"\\]|\\.)*)"/.exec(line)?.[1] ?? '';
|
|
95
|
+
const hit = ruleOfThreat({ refs, description }, records);
|
|
96
|
+
if (hit) out.set(id, hit);
|
|
97
|
+
}
|
|
98
|
+
return out;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// @comment -- "The tool input with each absolute file path resolved to its real path (for a file that does not exist yet, its folder's), so a path through a link (a symlinked checkout, macOS /tmp and /var) matches the repository root git reports. Only the path fields agents use (file_path, notebook_path, filePath, path, Path, target_file, TargetFile, paths) are touched; anything unresolvable is left as it was."
|
|
102
|
+
export function realInput(toolInput) {
|
|
103
|
+
if (!toolInput || typeof toolInput !== 'object') return toolInput;
|
|
104
|
+
const real = (p) => {
|
|
105
|
+
if (typeof p !== 'string' || !isAbsolute(p)) return p;
|
|
106
|
+
try {
|
|
107
|
+
return realpathSync(p);
|
|
108
|
+
} catch {
|
|
109
|
+
try {
|
|
110
|
+
return join(realpathSync(dirname(p)), basename(p));
|
|
111
|
+
} catch {
|
|
112
|
+
return p;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
const out = { ...toolInput };
|
|
117
|
+
for (const k of ['file_path', 'notebook_path', 'filePath', 'path', 'Path', 'target_file', 'TargetFile']) if (k in toolInput) out[k] = real(toolInput[k]);
|
|
118
|
+
if (Array.isArray(toolInput.paths)) out.paths = toolInput.paths.map(real);
|
|
119
|
+
return out;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// ---------------------------------------------------------------------------------------------
|
|
123
|
+
// Before an edit
|
|
124
|
+
// ---------------------------------------------------------------------------------------------
|
|
125
|
+
|
|
126
|
+
/** How a record came to bind, in a few words: approved on the default branch, or adopted by the people who typed their names. */
|
|
127
|
+
export const approvedHow = (r) => (r.approval?.via === 'main' ? `approved on ${r.approval.ref}` : `adopted by ${(r.adopters ?? []).map((a) => a.by).join(', ') || 'nobody named'}`);
|
|
128
|
+
|
|
129
|
+
/** A record as the agent is shown it before its first edit: id, file, how it was approved, each rule and what is not a bug. */
|
|
130
|
+
export function recordBrief(r) {
|
|
131
|
+
return [
|
|
132
|
+
`${r.id} (${r.module}) governs this code: ${r.file}, ${approvedHow(r)}.`,
|
|
133
|
+
`Decision: ${r.decision}`,
|
|
134
|
+
...r.rules.map((x) => `${x.id} (${x.kind}): ${x.text}`),
|
|
135
|
+
...r.notABug.map((x) => `Not a bug: ${x}`),
|
|
136
|
+
].join('\n');
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// @comment -- "The decision before one edit. The files it would touch (a sidecar counts as its source file) that an adopted record covers and this session has not yet been shown: refuse once, naming each record in full, and mark the files shown so the next attempt goes through. No adopted record, no session id, nothing covered or everything already shown: allow. Returns the refusal text (or null) and the state to keep."
|
|
140
|
+
export function guardDecision({ root, toolInput, state, records }) {
|
|
141
|
+
const adopted = records ?? adoptedRecords(root);
|
|
142
|
+
if (!adopted.length) return { refuse: null, state };
|
|
143
|
+
const files = touchedFiles(root, realInput(toolInput)).map(logicalFile);
|
|
144
|
+
const first = new Map();
|
|
145
|
+
for (const f of files) {
|
|
146
|
+
if (state.read[f]) continue;
|
|
147
|
+
for (const r of recordsForFile(adopted, f)) {
|
|
148
|
+
if (!first.has(r.id)) first.set(r.id, { record: r, files: [] });
|
|
149
|
+
first.get(r.id).files.push(f);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
if (!first.size) return { refuse: null, state };
|
|
153
|
+
const now = new Date().toISOString();
|
|
154
|
+
const read = { ...state.read };
|
|
155
|
+
for (const { files: fs } of first.values()) for (const f of fs) read[f] = now;
|
|
156
|
+
const shown = [...first.values()];
|
|
157
|
+
const refuse = [
|
|
158
|
+
`Bravos stopped this edit once: ${[...new Set(shown.flatMap((x) => x.files))].join(', ')} ${shown.length === 1 ? 'is' : 'are'} covered by an adopted security decision record, the team's standard for this code. Read it before you change anything here:`,
|
|
159
|
+
'',
|
|
160
|
+
...shown.map((x) => recordBrief(x.record)).join('\n\n').split('\n'),
|
|
161
|
+
'',
|
|
162
|
+
'Then make the edit again; it will go through. Follow the rules, and treat what is listed as not a bug as intended. If the change you were asked for goes against a rule, do not make it: tell the person which rule, how it was approved, and ask whether they want the decision changed. A changed record binds once its pull request is approved and merges (or, the fallback, a person adopts it with bravos records adopt <id> at their own terminal); you cannot approve or adopt it.',
|
|
163
|
+
].join('\n');
|
|
164
|
+
return { refuse, state: { ...state, read } };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// ---------------------------------------------------------------------------------------------
|
|
168
|
+
// After an edit
|
|
169
|
+
// ---------------------------------------------------------------------------------------------
|
|
170
|
+
|
|
171
|
+
function read(root, rel) {
|
|
172
|
+
try {
|
|
173
|
+
const abs = join(root, rel);
|
|
174
|
+
return statSync(abs).isFile() && statSync(abs).size <= MAX_BYTES ? readFileSync(abs, 'utf8') : null;
|
|
175
|
+
} catch {
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function head(root, rel) {
|
|
181
|
+
const r = spawnSync('git', ['show', `HEAD:${rel}`], { cwd: root, encoding: 'utf8', timeout: 3000, maxBuffer: MAX_BYTES, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
182
|
+
return r.status === 0 ? r.stdout : '';
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const EXPOSES_ANY = /@exposes\s+(\S+)\s+to\s+#([\w.-]+)[^"\n]*?(?:--\s*"((?:[^"\\]|\\.)*)")?/i;
|
|
186
|
+
const MITIGATES_ANY = /@mitigates\s+(\S+)\s+against\s+#([\w.-]+)/i;
|
|
187
|
+
|
|
188
|
+
// @comment -- "What an edit did to the record rules: in each touched file (and a source file's sidecar), an @exposes of a rule's threat whose line is not in the last commit is a break; an @mitigates of a rule's threat that the last commit had and the file no longer has is a removed check. Reads the files and git's HEAD copy only. A check removed from code whose annotation stays, or from code annotated in a sidecar the edit did not touch, is not seen here: the rule's test and bravos rules are what catch those."
|
|
189
|
+
export function ruleChanges(root, files, threats) {
|
|
190
|
+
if (!threats.size) return [];
|
|
191
|
+
const out = [];
|
|
192
|
+
for (const rel of files) {
|
|
193
|
+
const now = read(root, rel);
|
|
194
|
+
if (now === null) continue;
|
|
195
|
+
const before = head(root, rel);
|
|
196
|
+
const had = new Set(before.split('\n').map((l) => l.trim()));
|
|
197
|
+
const has = new Set(now.split('\n').map((l) => l.trim()));
|
|
198
|
+
now.split('\n').forEach((line, n) => {
|
|
199
|
+
const m = EXPOSES_ANY.exec(line);
|
|
200
|
+
if (!m || had.has(line.trim()) || !threats.has(m[2])) return;
|
|
201
|
+
const { record, rule } = threats.get(m[2]);
|
|
202
|
+
out.push({ kind: 'break', record, rule, file: logicalFile(rel), line: rel === logicalFile(rel) ? n + 1 : null, description: (m[3] ?? '').replace(/\\"/g, '"').slice(0, 300) });
|
|
203
|
+
});
|
|
204
|
+
for (const line of before.split('\n')) {
|
|
205
|
+
const m = MITIGATES_ANY.exec(line);
|
|
206
|
+
if (!m || has.has(line.trim()) || !threats.has(m[2])) continue;
|
|
207
|
+
const { record, rule } = threats.get(m[2]);
|
|
208
|
+
out.push({ kind: 'removed', record, rule, file: logicalFile(rel), line: null, description: '' });
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
return out;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** The key a record card is shown once under, in the cards' seen file. */
|
|
215
|
+
export const recordCardKey = (c) => `record|${c.kind}|${c.record.id}|${c.rule.id}|${c.file}`;
|
|
216
|
+
|
|
217
|
+
// @comment -- "A record card for the developer's terminal: which rule, of which record and who adopted it, where, and what to do. Text from annotations and records is already cleaned to one line by the records library."
|
|
218
|
+
export function renderRecordCard(c) {
|
|
219
|
+
const where = `${c.file}${c.line ? `:${c.line}` : ''}`;
|
|
220
|
+
const head = c.kind === 'break' ? `${c.record.id} ${c.rule.id} broken in ${where}` : `${c.record.id} ${c.rule.id}: its check was removed from ${where}`;
|
|
221
|
+
return [
|
|
222
|
+
`┌ ${head}`,
|
|
223
|
+
`│ "${c.rule.text}"`,
|
|
224
|
+
`│ ${c.record.module}, ${approvedHow(c.record)} (${c.record.file})`,
|
|
225
|
+
`└ Fix the code, or the record's owner changes the record and the new text is approved.`,
|
|
226
|
+
].join('\n');
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// @comment -- "What the agent is told about record cards: say it now, in plain words, before going on; a change the person still insists on stays recorded as an open exposure with @audit, never accepted, and bravos rules shows the rule as unguarded until the code or the record changes."
|
|
230
|
+
export function recordAgentLine(cards) {
|
|
231
|
+
const said = cards.map((c) => `${c.record.id} ${c.rule.id} ("${c.rule.text}") ${c.kind === 'break' ? `is broken in ${c.file}` : `lost its check in ${c.file}`}`).join('; ');
|
|
232
|
+
return `This edit goes against an adopted security decision record: ${said}. Tell the person now, in plain words, which rule and how it was approved, and ask whether they want the decision changed (edit the record in a pull request a code owner reviews, or a person adopts the new text with bravos records adopt <id> at their own terminal) before you go on. If they insist on the change, keep it recorded as an open @exposes of the rule's threat with @audit (never @accepts); bravos rules shows the rule as unguarded until the code or the record changes.`;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const RELEVANT = /@(?:exposes|mitigates|handles|flows|boundary|assumes|validates)\b/;
|
|
236
|
+
|
|
237
|
+
// @comment -- "The no-record nudge after an edit, never a block, from the first session. With a module ledger: the first edit in a session to a module the ledger marks as needing a record, which has none, gets one line naming the module, once per module per session; an optional module, or one with a record (even a draft), gets nothing. A file no ledger module covers, or a repository with no ledger yet, falls back to the code-with-claims rule: a file that already carries security claims and that no record covers gets one line, once per file per session. Neither needs an adopted record anywhere in the repository any more. The person can switch it off (bravos prefs set nudge off)."
|
|
238
|
+
export function uncoveredFiles(root, files, state, records = allRecords(root), ledger = readLedger(root, { records, review: false, files: [] })) {
|
|
239
|
+
const out = [];
|
|
240
|
+
const modules = [];
|
|
241
|
+
const noRecord = { ...state.noRecord };
|
|
242
|
+
const at = new Date().toISOString();
|
|
243
|
+
for (const rel of files) {
|
|
244
|
+
const logical = logicalFile(rel);
|
|
245
|
+
if (logical.startsWith('.guardlink/') || logical.startsWith('.bravos/')) continue;
|
|
246
|
+
if (recordsForFile(records, logical).length) continue;
|
|
247
|
+
const m = ledger.exists ? moduleForFile(ledger.modules, logical) : null;
|
|
248
|
+
if (m) {
|
|
249
|
+
const key = `module:${m.key}`;
|
|
250
|
+
if (m.needs !== 'yes' || m.records.length || noRecord[key]) continue;
|
|
251
|
+
noRecord[key] = at;
|
|
252
|
+
modules.push({ name: m.name, paths: m.paths, file: logical });
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
if (noRecord[logical]) continue;
|
|
256
|
+
const text = read(root, logical) ?? '';
|
|
257
|
+
const side = read(root, `.guardlink/annotations/${logical}.gal`) ?? '';
|
|
258
|
+
if (!RELEVANT.test(text) && !RELEVANT.test(side)) continue;
|
|
259
|
+
noRecord[logical] = at;
|
|
260
|
+
out.push(logical);
|
|
261
|
+
}
|
|
262
|
+
return { files: out, modules, state: { ...state, noRecord } };
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// @comment -- "What the agent is told for a module without a record: the module, that the company's principles and the application's rules still apply, and one offer to make in a line: draft a record after this change, or keep to the principles alone. A record holds only what was decided for this module, so the agent is told not to copy principles into one. It never blocks the task."
|
|
266
|
+
export const moduleNudgeLine = (modules) => {
|
|
267
|
+
const named = modules.map((m) => `${m.name} (${m.paths.join(', ')})`).join('; ');
|
|
268
|
+
return `${modules.length === 1 ? 'This edit is in a module' : 'This edit touches modules'} the module ledger (.guardlink/records/README.md) marks as making security decisions, with no security decision record yet: ${named}. The company's principles (.guardlink/principles.md) and the application's rules (.guardlink/intent.md) still apply here. Tell the person in one line and offer: draft a record for ${modules.length === 1 ? 'it' : 'them'} after this change (bravos-records), or keep to the principles alone. A record holds only what was decided for one module, so do not copy principles into it. Carry on with the task: this does not block it, and it is said once per module per session.`;
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
export const noRecordLine = (files) =>
|
|
272
|
+
`No security decision record covers ${files.join(', ')}, though ${files.length === 1 ? 'it carries' : 'they carry'} security claims. The company's principles and the application's rules still apply. Look for a written decision (bravos context list, docs/, .guardlink/intent.md); if there is none, tell the developer in one line and offer to draft a record (bravos-records), or to map the application's modules first (bravos records ledger propose) when there is no ledger. Carry on with the task: this does not block it.`;
|