@bugb-technologies/bravos 1.24.0 → 1.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/bin.js +12 -0
  2. package/dist/cli.js +222 -16
  3. package/dist/context.js +4 -4
  4. package/dist/cursor.js +24 -5
  5. package/dist/dashboard-sast.js +113 -0
  6. package/dist/dashboard.js +22 -11
  7. package/dist/doctor.js +29 -2
  8. package/dist/graphbin.js +2 -2
  9. package/dist/guide.js +4 -2
  10. package/dist/hook-launcher.js +92 -0
  11. package/dist/hooks.js +56 -3
  12. package/dist/plugin-release.js +38 -12
  13. package/dist/prefs.js +13 -3
  14. package/dist/principles.js +1 -1
  15. package/dist/records-conflicts.js +128 -0
  16. package/dist/records-drafts.js +106 -0
  17. package/dist/records-ledger.js +103 -0
  18. package/dist/records-team.js +398 -0
  19. package/dist/records.js +158 -0
  20. package/dist/review-server.js +3 -1
  21. package/dist/review.js +16 -1
  22. package/dist/rules.js +97 -4
  23. package/dist/setup.js +6 -6
  24. package/dist/uninstall.js +1 -1
  25. package/dist/upkeep.js +3 -0
  26. package/docs/GUIDE.md +11 -1
  27. package/docs/UPGRADING.md +56 -0
  28. package/hooks/cards.mjs +63 -14
  29. package/hooks/coach.mjs +3 -1
  30. package/hooks/lib/agent-io.mjs +118 -0
  31. package/hooks/lib/briefing.mjs +94 -3
  32. package/hooks/lib/cards.mjs +8 -1
  33. package/hooks/lib/draft-check.mjs +104 -0
  34. package/hooks/lib/drafts.mjs +121 -0
  35. package/hooks/lib/ledger.mjs +270 -0
  36. package/hooks/lib/pre-pr.mjs +74 -0
  37. package/hooks/lib/prefs.mjs +7 -3
  38. package/hooks/lib/record-guard.mjs +272 -0
  39. package/hooks/lib/records.mjs +581 -0
  40. package/hooks/lib/replay.mjs +2 -1
  41. package/hooks/lib/sast.mjs +3 -1
  42. package/hooks/record-guard.mjs +62 -0
  43. package/hooks/session-start.mjs +4 -3
  44. package/package.json +2 -2
  45. package/skills/bravos/SKILL.md +1 -0
  46. package/skills/bravos-records/SKILL.md +57 -0
  47. package/templates/dashboard/dashboard.html +198 -1
  48. package/templates/omp/bravos.js +85 -1
  49. package/templates/opencode/bravos.js +84 -1
  50. package/templates/plugin/workspace-hook.mjs +37 -0
  51. package/templates/workflows/bravos-pr-gate.yml +23 -0
@@ -0,0 +1,270 @@
1
+ // @comment -- "The module ledger (records round two): .guardlink/records/README.md lists the application's modules, the code each covers, whether it makes security decisions (and so needs a security decision record), its owner and its record's status. A coding agent proposes the modules from the team's stored documents, the threat model and the folder layout (and, on the Team plan, the code graph it asks itself); a person reviews them in a pull request. Bravos writes only the Owner (from CODEOWNERS) and Record columns. Nothing here is enforced: the ledger feeds the briefing and the no-record nudge and never holds a pull request. Reads the repository and git only; never throws to a hook."
2
+ import { spawnSync } from 'node:child_process';
3
+ import { readFileSync, readdirSync, statSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { globMatch, oneLine, treeReader, validGlob } from './principles.mjs';
6
+ import { allRecords, approvalContext, onDefault, ownersFor, readCodeowners, RECORDS_DIR } from './records.mjs';
7
+
8
+ export const LEDGER_FILE = `${RECORDS_DIR}/README.md`;
9
+ export const LEDGER_MARK = '<!-- bravos:ledger v1 -->';
10
+ export const LEDGER_SCHEMA = 'bravos.records-ledger/v1';
11
+ const MAX_MODULES = 200;
12
+ const MAX_FILES = 50000;
13
+ const MAX_BYTES = 2 * 1024 * 1024;
14
+ const HEADER = ['Module', 'Code', 'Needs a record', 'Why', 'Owner', 'Record', 'Evidence'];
15
+
16
+ const cell = (v, max = 300) => oneLine(v, max).replace(/\|/g, '/');
17
+ const keyOf = (name) => String(name ?? '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').replace(/s$/, '');
18
+ const titleOf = (slug) => {
19
+ const t = String(slug).replace(/[-_]+/g, ' ').trim();
20
+ return t ? t[0].toUpperCase() + t.slice(1) : t;
21
+ };
22
+
23
+ // ---------------------------------------------------------------------------------------------
24
+ // The file: parse and render
25
+ // ---------------------------------------------------------------------------------------------
26
+
27
+ // @comment -- "Reads the ledger's table: one module per row, its code as backticked repository globs, 'yes' or 'optional' for whether it needs a record, then why, owner, record status and evidence. Rows that do not parse are reported, never guessed; a glob outside the repository (absolute, ..) is refused like a record's paths are."
28
+ export function parseLedger(text) {
29
+ const modules = [];
30
+ const problems = [];
31
+ if (typeof text !== 'string') return { modules, problems };
32
+ const rows = text.split(/\r?\n/).filter((l) => /^\s*\|/.test(l));
33
+ for (const [n, line] of rows.entries()) {
34
+ const cells = line.trim().replace(/^\|/, '').replace(/\|\s*$/, '').split('|').map((c) => c.trim());
35
+ if (n === 0 && cells[0] === HEADER[0]) continue;
36
+ if (cells.every((c) => /^:?-{2,}:?$/.test(c))) continue;
37
+ const [name, code = '', needs = '', why = '', owner = '', record = '', evidence = ''] = cells;
38
+ if (!name) continue;
39
+ const paths = [...code.matchAll(/`([^`]+)`/g)].map((m) => m[1].trim());
40
+ const bad = paths.filter((g) => !validGlob(g));
41
+ if (!paths.length || bad.length) {
42
+ problems.push(`${LEDGER_FILE}: module "${cell(name, 60)}" ${bad.length ? `has a path that is not a repository glob: ${bad.join(', ')}` : 'names no code (put its globs in backticks in the Code column)'}`);
43
+ continue;
44
+ }
45
+ if (!/^(yes|optional)\b/i.test(needs)) problems.push(`${LEDGER_FILE}: module "${cell(name, 60)}" says "${cell(needs, 40)}" under Needs a record; write yes or optional`);
46
+ if (modules.length >= MAX_MODULES) break;
47
+ modules.push({ name: cell(name, 80), key: keyOf(name), paths, needs: /^yes\b/i.test(needs) ? 'yes' : 'optional', why: cell(why), owner: cell(owner, 120), record: cell(record, 120), evidence: cell(evidence) });
48
+ }
49
+ return { modules, problems };
50
+ }
51
+
52
+ // @comment -- "Writes the ledger back in one fixed form: a short preamble saying what it is, that a person reviews it and that it is never enforced, then the table. The preamble is Bravos's; the rows are the team's, kept in their order."
53
+ export function renderLedger(modules) {
54
+ const row = (cs) => `| ${cs.join(' | ')} |`;
55
+ return [
56
+ '# Modules and their security decision records',
57
+ LEDGER_MARK,
58
+ '',
59
+ 'Which parts of this application make security decisions, and which security decision record (SDR-n) says what was decided for each. A coding agent proposes the modules from the team\'s documents, the threat model and the code; a person reviews them in a pull request, like any change. Nothing here is enforced: the ledger holds no pull request.',
60
+ '',
61
+ 'A module marked **yes** makes security decisions (who can see or do what, outside connections, customer data, money) and should have a record; **optional** ones may. The company\'s principles (`.guardlink/principles.md`) and the application\'s rules (`.guardlink/intent.md`) apply to every module, with a record or without.',
62
+ '',
63
+ 'Bravos writes the Owner column from CODEOWNERS (when there is one) and the Record column from the records (`bravos records ledger refresh`). The team owns the rest.',
64
+ '',
65
+ row(HEADER),
66
+ row(HEADER.map(() => '---')),
67
+ ...modules.map((m) => row([cell(m.name, 80), m.paths.map((g) => `\`${g}\``).join(', '), m.needs, cell(m.why) || '—', cell(m.owner, 120) || '—', cell(m.record, 120) || '—', cell(m.evidence) || '—'])),
68
+ '',
69
+ ].join('\n');
70
+ }
71
+
72
+ // ---------------------------------------------------------------------------------------------
73
+ // Status: what Bravos writes, and what the hooks read
74
+ // ---------------------------------------------------------------------------------------------
75
+
76
+ /** The repository's tracked and untracked-but-not-ignored files, bounded; [] outside git. */
77
+ export function repoFiles(root) {
78
+ const r = spawnSync('git', ['ls-files', '-co', '--exclude-standard', '-z'], { cwd: root, encoding: 'utf8', timeout: 15000, maxBuffer: 64 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] });
79
+ return r.status === 0 ? r.stdout.split('\0').filter(Boolean).slice(0, MAX_FILES) : [];
80
+ }
81
+
82
+ // A glob's literal start (src/trust/ for src/trust/**), so a large repository is filtered by prefix before any glob is matched.
83
+ const literal = (g) => g.slice(0, g.search(/[*?{]|$/));
84
+ export const moduleFiles = (m, files) => files.filter((f) => m.paths.some((g) => f.startsWith(literal(g)) && globMatch(g, f)));
85
+ export const moduleForFile = (modules, file) => modules.find((m) => m.paths.some((g) => globMatch(g, file))) ?? null;
86
+
87
+ // @comment -- "The records that belong to a module: one whose module name is the module's, or whose paths cover any of the module's files (or, for a module whose code is not there yet, one that names the same glob). The record's own state decides the words."
88
+ export function recordsOfModule(m, records, files) {
89
+ const mine = moduleFiles(m, files);
90
+ return records.filter((r) => keyOf(r.module) === m.key || r.paths.some((g) => m.paths.includes(g)) || mine.some((f) => r.paths.some((g) => f.startsWith(literal(g)) && globMatch(g, f))));
91
+ }
92
+
93
+ const STATE_WORDS = { adopted: 'approved', proposed: 'proposed change', draft: 'draft', changed: 'changed after adoption', disputed: 'disputed', declined: 'declined' };
94
+
95
+ /** The Record column for a module: each of its records and state, or "needs one" / "none (optional)". */
96
+ export function statusText(m, records) {
97
+ if (!records.length) return m.needs === 'yes' ? 'needs one' : 'none (optional)';
98
+ return records.map((r) => `${r.id} ${r.state === 'adopted' && r.approval?.via === 'name' ? 'adopted by name' : STATE_WORDS[r.state] ?? r.state}`).join(', ');
99
+ }
100
+
101
+ // @comment -- "Whether a person has reviewed the ledger: its module list (names, code, yes or optional, not the columns Bravos writes) is the same on the default branch, as of the last fetch, which a pull request brings there. Different there, or not there yet, it is a proposal; with no default branch to compare it is unreviewed. A ledger never binds anyone either way: this only says how far to trust its boundaries."
102
+ export function ledgerReview(root, modules) {
103
+ const ctx = approvalContext(root);
104
+ if (!ctx) return { state: 'unreviewed', ref: null, words: 'not reviewed: there is no default branch to compare it with' };
105
+ const there = onDefault(ctx, LEDGER_FILE);
106
+ if (there === null) return { state: 'proposed', ref: ctx.ref, words: `proposed: not on ${ctx.ref} yet, so nobody has reviewed it` };
107
+ const sig = (ms) => JSON.stringify(ms.map((m) => [m.key, [...m.paths].sort(), m.needs]));
108
+ return sig(parseLedger(there).modules) === sig(modules)
109
+ ? { state: 'reviewed', ref: ctx.ref, words: `reviewed: its modules are the ones on ${ctx.ref}` }
110
+ : { state: 'proposed', ref: ctx.ref, words: `proposed: its modules differ from ${ctx.ref}'s, so the change waits for review in its pull request` };
111
+ }
112
+
113
+ // @comment -- "The ledger as the briefing, the nudge and the CLI read it: its modules, problems and review state, and per module the records it has. Missing file: exists false. Never throws."
114
+ export function readLedger(root, opts = {}) {
115
+ const none = { exists: false, modules: [], problems: [], review: null };
116
+ try {
117
+ const reader = treeReader(root);
118
+ const text = reader.read(LEDGER_FILE);
119
+ if (text === null) return none;
120
+ const { modules, problems } = parseLedger(text);
121
+ const records = opts.records ?? allRecords(root);
122
+ const files = opts.files ?? repoFiles(root);
123
+ const rows = modules.map((m) => {
124
+ const own = recordsOfModule(m, records, files);
125
+ return { ...m, records: own.map((r) => ({ id: r.id, state: r.state, via: r.approval?.via ?? null })), status: statusText(m, own) };
126
+ });
127
+ return { exists: true, text, modules: rows, problems, review: opts.review === false ? null : ledgerReview(root, modules) };
128
+ } catch {
129
+ return none;
130
+ }
131
+ }
132
+
133
+ // @comment -- "The briefing's numbers: how many modules, how many need a record, how many of those have one, and whether a person reviewed the list. Names only, cleaned to one short line each; no row text beyond that reaches the briefing."
134
+ export function ledgerBrief(root) {
135
+ const l = readLedger(root);
136
+ if (!l.exists) return { exists: false };
137
+ const needs = l.modules.filter((m) => m.needs === 'yes');
138
+ const name = (m) => String(m.name).replace(/[^\p{L}\p{N} &_\-./]/gu, '').slice(0, 40);
139
+ return { exists: true, count: l.modules.length, needs: needs.length, withRecords: l.modules.filter((m) => m.records.length).length, missing: needs.filter((m) => !m.records.length).map(name), review: l.review?.state ?? 'unreviewed', problems: l.problems.length };
140
+ }
141
+
142
+ // @comment -- "bravos records ledger refresh: rewrites the two columns Bravos owns, the Record column from the records and the Owner column from CODEOWNERS (the owners of the module's files, last match wins as on GitHub; with no CODEOWNERS the team's own cell is kept). The team's rows, order and words are kept. Returns the new text and whether it changed."
143
+ export function refreshLedger(root, opts = {}) {
144
+ const reader = treeReader(root);
145
+ const text = reader.read(LEDGER_FILE);
146
+ if (text === null) return null;
147
+ const { modules, problems } = parseLedger(text);
148
+ const records = opts.records ?? allRecords(root);
149
+ const files = opts.files ?? repoFiles(root);
150
+ const co = readCodeowners(reader);
151
+ const next = modules.map((m) => {
152
+ const own = recordsOfModule(m, records, files);
153
+ let owner = m.owner === '—' ? '' : m.owner;
154
+ if (co) {
155
+ const sample = moduleFiles(m, files);
156
+ const set = new Set((sample.length ? sample : m.paths.map((g) => g.replace(/\/\*\*$/, '/x'))).flatMap((f) => ownersFor(co, f)));
157
+ owner = [...set].slice(0, 4).join(' ');
158
+ }
159
+ return { ...m, owner, record: statusText(m, own) };
160
+ });
161
+ const out = renderLedger(next);
162
+ return { text: out, changed: out !== text, problems, modules: next };
163
+ }
164
+
165
+ // ---------------------------------------------------------------------------------------------
166
+ // Proposing modules: the agent's first pass, for a person to review
167
+ // ---------------------------------------------------------------------------------------------
168
+
169
+ // Folders that hold features rather than being one; a feature is the first folder below them.
170
+ const CONTAINERS = new Set(['src', 'app', 'apps', 'lib', 'libs', 'packages', 'services', 'service', 'server', 'api', 'routes', 'router', 'routers', 'pages', 'modules', 'features', 'components', 'controllers', 'handlers', 'internal', 'pkg', 'cmd', 'web', 'client', 'backend', 'frontend', 'views', 'screens', 'domain', 'domains', 'actions', 'endpoints', 'resolvers', 'v1', 'v2']);
171
+ // Folders shared by every feature, never one themselves.
172
+ const SHARED = new Set(['utils', 'util', 'helpers', 'common', 'shared', 'types', 'hooks', 'styles', 'test', 'tests', '__tests__', 'spec', 'assets', 'public', 'static', 'config', 'configs', 'constants', 'ui', 'layout', 'layouts', 'generated', 'node_modules', 'dist', 'build', 'vendor', 'fixtures', 'mocks', 'scripts', 'docs', 'migrations', 'i18n', 'locales', 'icons', 'images']);
173
+ const SKIP_TOP = /^(\.|node_modules\/|dist\/|build\/|coverage\/|vendor\/|plugin\/|plugin-codex\/)/;
174
+ // Generic security domains: a module named for one of these decides who can see or do something.
175
+ const DOMAINS = /^(auth|authn|authz|login|signin|signup|sign-up|session|account|user|member|team|org|organisation|organization|tenant|role|permission|access|admin|billing|payment|invoice|checkout|subscription|plan|integration|webhook|oauth|sso|saml|token|api-key|apikey|key|secret|credential|upload|file|export|import|share|sharing|invite|invitation|setting|profile|notification|email|audit)$/;
176
+ // Code that decides access or reaches outside, seen in a module's files.
177
+ const DECIDES = /\b(req\.user|currentUser|getServerSession|getSession|session\.user|isAdmin|hasRole|hasPermission|can\(|authorize|requireAuth|requireRole|permissions?\b|role\s*[!=]==|roles?\.includes|tenantId|orgId|organizationId|ownerId|jwt|bearer|apiKey|api_key|webhook|signature|fetch\(|axios|https?:\/\/|stripe|razorpay|S3Client|presign|password|bcrypt|encrypt|decrypt|public\s*:\s*true|isPublic|visibility)\b/i;
178
+ const CLAIMS = /@(?:exposes|mitigates|handles|flows|boundary|validates)\s+([\w.:#-]+)/g;
179
+
180
+ function readSmall(root, rel) {
181
+ try {
182
+ const abs = join(root, rel);
183
+ const s = statSync(abs);
184
+ return s.isFile() && s.size <= MAX_BYTES ? readFileSync(abs, 'utf8') : '';
185
+ } catch {
186
+ return '';
187
+ }
188
+ }
189
+
190
+ // @comment -- "The team's stored documents' section headings, as feature names to match: .bravos/context/sources/SRC-n-*.md, headings at levels 2 and 3 (the first level is the document's title). Read-only, bounded; a document's text goes no further than the heading it cites."
191
+ export function documentSections(root) {
192
+ const dir = join(root, '.bravos', 'context', 'sources');
193
+ const out = [];
194
+ let names = [];
195
+ try {
196
+ names = readdirSync(dir).filter((n) => /^SRC-[1-9][0-9]{0,4}(?:-[a-z0-9-]+)?\.md$/.test(n)).slice(0, 200);
197
+ } catch {
198
+ return out;
199
+ }
200
+ for (const n of names) {
201
+ const id = /^(SRC-[1-9][0-9]{0,4})/.exec(n)[1];
202
+ for (const m of readSmall(root, `.bravos/context/sources/${n}`).matchAll(/^#{2,3}\s+(.+?)\s*#*\s*$/gm)) {
203
+ const heading = oneLine(m[1], 80);
204
+ if (heading) out.push({ id, heading, key: keyOf(heading) });
205
+ }
206
+ }
207
+ return out;
208
+ }
209
+
210
+ const globSafe = (seg) => (/^[A-Za-z0-9_.\-]+$/.test(seg) ? seg : '*');
211
+
212
+ // @comment -- "The first pass at modules, for the agent to review and a person to approve: features found from the folder layout (the first folder below src, app, api, routes and the like; the same name in several places is one feature with several paths, not one module per folder), each with its evidence: the stored documents' sections that name it, the threat-model assets its code carries claims about, and the code in it that decides access or reaches outside. A module is flagged as needing a record only with such evidence of security decisions or a name from the generic security domains; the rest are optional. Document sections that match no code are returned on their own, never invented into a module. The code graph's routes and auth boundary are not read here: on the Team plan the agent asks the graph and adjusts the list; without it, a feature split across folders with different names can show as two modules or be missed."
213
+ export function proposeModules(root, opts = {}) {
214
+ const files = (opts.files ?? repoFiles(root)).filter((f) => !SKIP_TOP.test(f) && !f.startsWith('.guardlink/'));
215
+ const read = opts.read ?? ((rel) => readSmall(root, rel));
216
+ const features = new Map();
217
+ for (const f of files) {
218
+ const parts = f.split('/');
219
+ let i = 0;
220
+ while (i < parts.length - 1 && (CONTAINERS.has(parts[i].toLowerCase()) || /^\(.*\)$|^\[.*\]$|^@/.test(parts[i]))) i++;
221
+ if (i >= parts.length - 1) continue;
222
+ const seg = parts[i];
223
+ if (SHARED.has(seg.toLowerCase()) || seg.startsWith('.') || seg.startsWith('_')) continue;
224
+ const key = keyOf(seg);
225
+ if (!key) continue;
226
+ const dir = [...parts.slice(0, i).map(globSafe), seg].join('/');
227
+ if (!validGlob(`${dir}/**`)) continue;
228
+ const ft = features.get(key) ?? { key, name: titleOf(seg), dirs: new Set(), files: [] };
229
+ ft.dirs.add(`${dir}/**`);
230
+ ft.files.push(f);
231
+ features.set(key, ft);
232
+ }
233
+ const sections = opts.sections ?? documentSections(root);
234
+ const used = new Set();
235
+ const modules = [];
236
+ for (const ft of [...features.values()].sort((a, b) => b.files.length - a.files.length || a.key.localeCompare(b.key)).slice(0, MAX_MODULES)) {
237
+ const docs = sections.filter((s) => s.key === ft.key || s.key.split('-').includes(ft.key) || ft.key.split('-').every((w) => s.key.split('-').includes(w)));
238
+ for (const d of docs) used.add(`${d.id}|${d.heading}`);
239
+ const assets = new Map();
240
+ let decides = 0;
241
+ for (const f of ft.files.slice(0, 400)) {
242
+ const text = read(f);
243
+ const side = read(`.guardlink/annotations/${f}.gal`);
244
+ for (const m of `${text}\n${side}`.matchAll(CLAIMS)) if (!m[1].startsWith('#')) assets.set(m[1], (assets.get(m[1]) ?? 0) + 1);
245
+ if (DECIDES.test(text)) decides++;
246
+ }
247
+ const domain = DOMAINS.test(ft.key);
248
+ const why = [
249
+ decides ? `${decides} file${decides === 1 ? ' checks' : 's check'} access or reach outside` : '',
250
+ assets.size ? `security claims about ${[...assets.keys()].slice(0, 3).join(', ')}` : '',
251
+ domain ? `the name is a security domain (${ft.key})` : '',
252
+ ].filter(Boolean);
253
+ const evidence = [
254
+ ...docs.slice(0, 3).map((d) => `${d.id} § ${d.heading}`),
255
+ ...[...assets.entries()].slice(0, 3).map(([a, n]) => `asset ${a} (${n} claim${n === 1 ? '' : 's'})`),
256
+ `${ft.files.length} file${ft.files.length === 1 ? '' : 's'} in ${[...ft.dirs].length} place${ft.dirs.size === 1 ? '' : 's'}`,
257
+ ];
258
+ modules.push({ name: ft.name, key: ft.key, paths: [...ft.dirs].sort(), needs: why.length ? 'yes' : 'optional', why: why.length ? why.join('; ') : 'no access checks, outside calls or security claims seen', owner: '', record: '', evidence: evidence.join('; '), files: ft.files.length });
259
+ }
260
+ const documentedOnly = sections.filter((s) => !used.has(`${s.id}|${s.heading}`) && s.key && !/^(overview|introduction|summary|goals?|non-goals?|background|scope|requirements?|appendix|glossary|open-questions?|risks?|timeline|faq|context|problem|solution|users?|personas?|metrics?|success-metrics?|out-of-scope)$/.test(s.key));
261
+ modules.sort((a, b) => (a.needs === b.needs ? 0 : a.needs === 'yes' ? -1 : 1));
262
+ return { modules, documentedOnly: documentedOnly.slice(0, 20), files: files.length };
263
+ }
264
+
265
+ // @comment -- "Adds proposed modules to the ledger without touching the team's rows: a module whose name or code is already listed is left as the team wrote it. Writes a new ledger when there is none. Returns the text and the modules it added."
266
+ export function mergeProposal(existingText, proposed) {
267
+ const { modules } = parseLedger(existingText ?? '');
268
+ const added = proposed.filter((p) => !modules.some((m) => m.key === p.key || m.paths.some((g) => p.paths.includes(g))));
269
+ return { text: renderLedger([...modules, ...added]), added };
270
+ }
@@ -4,6 +4,7 @@ import { spawnSync } from 'node:child_process';
4
4
  import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
5
5
  import { isAbsolute, join } from 'node:path';
6
6
  import { checkPrinciples, exceptionFor, treeReader as principlesReader } from './principles.mjs';
7
+ import { EXCEPTIONS_FILE as RECORD_EXCEPTIONS_FILE, checkRecords, recordExceptionFor, ruleOfThreat } from './records.mjs';
7
8
 
8
9
  const PR_COMMAND = /(?:^|[\s;&|(])gh\s+pr\s+(create|ready)(?![\w-])/;
9
10
  const READY_ARG = /(?:^|[\s;&|(])gh\s+pr\s+ready\s+([^\s;&|)-][^\s;&|)]*)/;
@@ -252,6 +253,63 @@ export function principleChanges(root, run, options, fresh, confirmed, now = new
252
253
  return { breaks, excepted, problems };
253
254
  }
254
255
 
256
+ // @comment -- "The security decision record rules this branch breaks, and the records this branch itself changes. An adopted record's enforced rule stands behind every threat that carries record:SDR-n and whose description names the rule (or the record's one enforced rule). A break is a new exposure of such a threat with no control, or a confirmed claim of one on changed code; a live exception for that rule and place sets it aside. A record this branch edits or adds waits on this branch only: where the default branch requires a code owner's review GitHub makes this pull request wait, so Bravos only says so; elsewhere it holds until a person adopts the new text by name. A record that reads differently from its adoption without this branch touching it is noted, never held, so one edit never holds every pull request. An exceptions file that does not check out holds."
257
+ export function recordChanges(root, run, options, fresh, confirmed, now = new Date(), base = null) {
258
+ const check = checkRecords(principlesReader(root), { now, root });
259
+ if (!check.exists) return { breaks: [], excepted: [], problems: [], notes: [] };
260
+ let touched = null;
261
+ if (base) {
262
+ const d = run('git', ['diff', '--name-only', `${base}...HEAD`], options);
263
+ if (d.status === 0) touched = new Set(String(d.stdout ?? '').split('\n').map((l) => l.trim()).filter(Boolean));
264
+ }
265
+ const mine = (r) => (touched ? touched.has(r.file) : true);
266
+ const enforcedReview = check.approval?.review?.enforced === true;
267
+ const problems = [...check.problems.filter((p) => p.startsWith(RECORD_EXCEPTIONS_FILE))];
268
+ const notes = [];
269
+ for (const r of check.records) {
270
+ if (r.state === 'adopted' && r.approval?.via === 'name' && check.approval) notes.push(`${r.id} is adopted by name (${r.approval.by.join(', ')}), not verified: approving it on ${check.approval.ref} through a code owner's review proves who approved it`);
271
+ // A record this branch adds (a draft, here or from background drafting) waits for approval on this branch only, like an edit.
272
+ if (r.state === 'draft' && check.approval && touched?.has(r.file)) {
273
+ if (enforcedReview) notes.push(`${r.id} is new on this branch, a draft: it binds once a code owner approves this pull request and it merges (${check.approval.ref} requires that review).`);
274
+ else problems.push(`${r.id} is new on this branch, a draft, and ${check.approval.review?.enforced === false ? `${check.approval.ref} does not require a code owner's review` : `whether ${check.approval.ref} requires a code owner's review is not known`}, so merging it would make it bind with nobody's approval. A person adopts it by name (bravos review records, or bravos records adopt ${r.id}), or the team requires code-owner review for .guardlink/records/ (bravos records codeowners) and bravos records check confirms it`);
275
+ continue;
276
+ }
277
+ if (r.state !== 'proposed' && r.state !== 'changed' && r.state !== 'disputed') continue;
278
+ if (!mine(r)) {
279
+ notes.push(`${r.id} (${r.file}) does not match what was approved, but this branch does not change it, so it does not hold this pull request (bravos records check)`);
280
+ continue;
281
+ }
282
+ if (r.state === 'disputed') problems.push(`${r.id} (${r.file}) is adopted by ${r.adopters.map((x) => x.by).join(', ')} and declined by ${r.decliners.map((x) => x.by).join(', ')}; they need to settle it`);
283
+ else if (r.state === 'proposed' && enforcedReview) notes.push(`${r.id} changes on this branch: it binds once a code owner approves this pull request and it merges (${check.approval.ref} requires that review). Until then ${check.approval.ref}'s text is the approved one.`);
284
+ else if (r.state === 'proposed') problems.push(`${r.id} changes on this branch, and ${check.approval.review.enforced === false ? `${check.approval.ref} does not require a code owner's review` : `whether ${check.approval.ref} requires a code owner's review is not known`}, so nothing would make this change wait for approval. A person adopts the new text by name (bravos review records, or bravos records adopt ${r.id}), or the team requires code-owner review for .guardlink/records/ (bravos records codeowners) and bravos records check confirms it`);
285
+ else problems.push(`${r.id} (${r.file}) was changed after ${r.stale.map((x) => x.by).join(', ')} adopted it; it binds once a person adopts the new text (bravos records adopt ${r.id}, or bravos review records)`);
286
+ }
287
+ const enforced = check.adopted.some((r) => r.rules.some((x) => x.kind === 'enforced'));
288
+ if (!enforced || (!fresh.length && !confirmed.length)) return { breaks: [], excepted: [], problems, notes };
289
+ const model = runJson(run, 'guardlink parse', 'guardlink', ['parse', '.'], options);
290
+ if (!model.ok) return model;
291
+ const bare = (id) => String(id ?? '').replace(/^#/, '');
292
+ const byThreat = new Map();
293
+ for (const t of Array.isArray(model.json?.threats) ? model.json.threats : []) {
294
+ const hit = ruleOfThreat({ refs: Array.isArray(t?.external_refs) ? t.external_refs : [], description: t?.description }, check.adopted);
295
+ if (hit && hit.rule.kind === 'enforced') byThreat.set(bare(t.id), hit);
296
+ }
297
+ const breaks = [];
298
+ const excepted = [];
299
+ const consider = (c, how) => {
300
+ const hit = byThreat.get(bare(c?.threat));
301
+ if (!hit) return;
302
+ const files = [c?.location?.file, c?.location?.origin_file].filter((f) => typeof f === 'string');
303
+ const e = files.map((f) => recordExceptionFor(check.exceptions, hit.record.id, hit.rule.id, f, now)).find(Boolean);
304
+ const row = { record: hit.record, rule: hit.rule, claim: c, how };
305
+ if (e) excepted.push({ ...row, exception: e });
306
+ else breaks.push(row);
307
+ };
308
+ for (const c of fresh) consider(c, 'a new exposure with no control');
309
+ for (const c of confirmed) consider(c, 'confirmed by a test');
310
+ return { breaks, excepted, problems, notes };
311
+ }
312
+
255
313
  // @comment -- "Counts a principle's gate stop on this machine, for the dashboard's value line: one JSON line per principle per stop under <git-common-dir>/bravos/, never committed. Best effort; a failure never changes the gate's answer."
256
314
  function recordStops(root, env, run, ids) {
257
315
  try {
@@ -445,6 +503,22 @@ export function runGate({ root, action, command, cwd = root, env = process.env,
445
503
  for (const x of principled.excepted) notes.push(`Under an approved exception: ${x.principle.id} at ${where(x.claim)} — ${x.exception.reason} (approved by ${x.exception.by}, until ${x.exception.until}).`);
446
504
  }
447
505
 
506
+ // (g) the modules' security decision records: a break of an adopted record's enforced rule holds the PR whatever the
507
+ // PR body says; it clears when the code is fixed, a named person approves a dated exception for that rule and place,
508
+ // or the record is changed and adopted again. A record changed since its adoption holds the PR on its own.
509
+ // @mitigates #records against #forged-record using #record-gate -- "A branch that breaks an adopted record's enforced rule (a new uncontrolled exposure of its threat, or a confirmed claim on changed code) cannot open or ready a PR unless a live exception a named person approved covers that place, and a record changed since its adoption holds every PR until a person adopts the new text"
510
+ const recorded = recordChanges(root, run, o, Array.isArray(fresh) ? fresh : [], confirmedOnChanged, new Date(), base);
511
+ if (recorded.error) unknown(recorded);
512
+ else {
513
+ const where = (c) => `${c?.location?.file ?? '?'}${c?.location?.line ? `:${c.location.line}` : ''}`;
514
+ if (recorded.problems.length) blocks.push(`a security decision record this branch changes is not approved yet, or the records' exceptions do not check out (bravos records check):\n${recorded.problems.map((p) => ` - ${p}`).join('\n')}`);
515
+ if (recorded.breaks.length) {
516
+ blocks.push(`this branch breaks an adopted security decision record. Fix the code; or a person approves an exception for that rule and place (bravos records except SDR-n Rk --where "<glob>" --reason "<why>" --until <day>, at their own terminal); or the record is changed and adopted again. Naming it in the PR body is not enough:\n${recorded.breaks.map((b) => ` - ${b.record.id} ${b.rule.id} ("${b.rule.text}", adopted by ${b.record.adopters.map((a) => a.by).join(', ')}): ${b.how} at ${where(b.claim)}`).join('\n')}`);
517
+ }
518
+ for (const x of recorded.excepted) notes.push(`Under an approved exception: ${x.record.id} ${x.rule.id} at ${where(x.claim)} — ${x.exception.reason} (${x.exception.approval?.via === 'main' ? `on the default branch, approved by ${x.exception.by}` : `approved by name, ${x.exception.by}, not verified`}, until ${x.exception.until}).`);
519
+ for (const n of recorded.notes ?? []) notes.push(`bravos pre-PR gate: ${n}`);
520
+ }
521
+
448
522
  const review = changeReview(root, base, env, run);
449
523
  if (review) notes.push(review);
450
524
  if (blocks.length > 0) return { decision: 'block', reason: ['bravos pre-PR gate: blocked.', ...blocks.map((b) => `- ${b}`), ...notes].join('\n') };
@@ -14,7 +14,11 @@ export const COACH_CHOICES = ['on', 'off'];
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
15
  export const CARDS_CHOICES = ['on', 'off'];
16
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 };
17
+ /** nudge: on says once per module per session, at the first edit, that a module the ledger marks as needing a security decision record has none (the default); off says nothing. */
18
+ export const NUDGE_CHOICES = ['on', 'off'];
19
+ /** drafts: background has one background pass per session draft security decision records for the reviewed ledger's modules that need one (Team plan; the default); off drafts none unless asked. */
20
+ export const DRAFTS_CHOICES = ['background', 'off'];
21
+ export const PREF_CHOICES = { commits: COMMIT_CHOICES, annotate: ANNOTATE_CHOICES, coach: COACH_CHOICES, cards: CARDS_CHOICES, notify: NOTIFY_CHOICES, nudge: NUDGE_CHOICES, drafts: DRAFTS_CHOICES };
18
22
 
19
23
  // One line of visible text: a name goes into the briefing, so control and invisible characters never do.
20
24
  const clean = (v, max) => String(v ?? '').replace(/[\u0000-\u001F\u007F-\u009F​-‏‪-‮⁠-⁤⁦-⁩]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, max);
@@ -38,7 +42,7 @@ export const prefsFile = (commonDir) => join(commonDir, 'bravos', 'prefs.json');
38
42
  // @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."
39
43
  // @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."
40
44
  export function readPrefs(commonDir) {
41
- const none = { commits: null, annotate: null, coach: null, cards: null, notify: null };
45
+ const none = { commits: null, annotate: null, coach: null, cards: null, notify: null, nudge: null, drafts: null };
42
46
  if (!commonDir) return none;
43
47
  let doc;
44
48
  try {
@@ -54,7 +58,7 @@ export function readPrefs(commonDir) {
54
58
  if (!by || by.startsWith('<') || typeof c.at !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(c.at)) return null;
55
59
  return { value: c.value, by, at: c.at };
56
60
  };
57
- return { commits: one('commits'), annotate: one('annotate'), coach: one('coach'), cards: one('cards'), notify: one('notify') };
61
+ return { commits: one('commits'), annotate: one('annotate'), coach: one('coach'), cards: one('cards'), notify: one('notify'), nudge: one('nudge'), drafts: one('drafts') };
58
62
  }
59
63
 
60
64
  // @comment -- "Records the commits answer a named person gave (writePref does the work)."