@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.
- package/dist/bin.js +12 -0
- package/dist/cli.js +222 -16
- package/dist/context.js +4 -4
- package/dist/cursor.js +24 -5
- package/dist/dashboard-sast.js +113 -0
- package/dist/dashboard.js +22 -11
- 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/plugin-release.js +38 -12
- package/dist/prefs.js +13 -3
- package/dist/principles.js +1 -1
- package/dist/records-conflicts.js +128 -0
- 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 +97 -4
- package/dist/setup.js +6 -6
- package/dist/uninstall.js +1 -1
- package/dist/upkeep.js +3 -0
- package/docs/GUIDE.md +11 -1
- package/docs/UPGRADING.md +56 -0
- package/hooks/cards.mjs +63 -14
- package/hooks/coach.mjs +3 -1
- package/hooks/lib/agent-io.mjs +118 -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/lib/sast.mjs +3 -1
- package/hooks/record-guard.mjs +62 -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 +198 -1
- package/templates/omp/bravos.js +85 -1
- package/templates/opencode/bravos.js +84 -1
- package/templates/plugin/workspace-hook.mjs +37 -0
- package/templates/workflows/bravos-pr-gate.yml +23 -0
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
// @comment -- "Security decision records, part three, the CLI side (Team plan): exceptions a person approves for one rule in one area, the gaps report (code with security claims no record covers), the review-page draft built from the record files, and what a Confirm on that page records: per rule Agree, Change or No; a record is adopted by that person only when every part of it was agreed or changed by them, a Change rewrites the record in their words first, and a No declines it. The format, fingerprints and the check stay in hooks/lib/records.mjs."
|
|
2
|
+
import { execFileSync } from 'node:child_process';
|
|
3
|
+
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { pathToFileURL } from 'node:url';
|
|
6
|
+
import { hooksDir } from './paths.js';
|
|
7
|
+
import { writeInRepo } from './principles.js';
|
|
8
|
+
import { checkRecordsAt, recordsLib } from './records.js';
|
|
9
|
+
import { slug } from './review.js';
|
|
10
|
+
import { BravosError } from './types.js';
|
|
11
|
+
const lib = async () => (await recordsLib());
|
|
12
|
+
const P = async () => (await import(pathToFileURL(join(hooksDir(), 'lib', 'principles.mjs')).href));
|
|
13
|
+
const DAY = /^\d{4}-\d{2}-\d{2}$/;
|
|
14
|
+
const today = (now) => now.toISOString().slice(0, 10);
|
|
15
|
+
function writeExceptions(root, L, exceptions) {
|
|
16
|
+
writeInRepo(root, L.EXCEPTIONS_FILE, JSON.stringify({ schema: L.EXCEPTIONS_SCHEMA, exceptions }, null, 2) + '\n');
|
|
17
|
+
}
|
|
18
|
+
// @comment -- "Records an exception a person approved: the record must be adopted and the rule one of its enforced rules, the area a repository glob, the reason and the approver's name given, and the end day after today and within a year. The CLI calls this only from an interactive terminal after the approver typed their name and the rule; it never extends an existing exception, it adds one."
|
|
19
|
+
// @mitigates #records against #forged-record using #person-only-adoption -- "An exception to a record rule is written only from an interactive terminal where the approver typed their name and the rule, ends within a year, and carries a fingerprint the gate checks"
|
|
20
|
+
export async function addRecordException(root, input, env = process.env, now = new Date()) {
|
|
21
|
+
const L = await lib();
|
|
22
|
+
const p = await P();
|
|
23
|
+
const by = p.oneLine(input.by, 80);
|
|
24
|
+
const reason = p.oneLine(input.reason, 400);
|
|
25
|
+
if (!by)
|
|
26
|
+
throw new BravosError('an exception needs the name of the person approving it');
|
|
27
|
+
if (!reason)
|
|
28
|
+
throw new BravosError('an exception needs a reason: why this code may go against the rule for now');
|
|
29
|
+
if (!p.validGlob(input.where))
|
|
30
|
+
throw new BravosError(`"${input.where}" is not a repository glob (src/legacy/**)`);
|
|
31
|
+
if (!DAY.test(input.until))
|
|
32
|
+
throw new BravosError('--until is a day, YYYY-MM-DD');
|
|
33
|
+
const span = (Date.parse(`${input.until}T00:00:00Z`) - Date.parse(`${today(now)}T00:00:00Z`)) / 86400000;
|
|
34
|
+
if (!(span >= 1))
|
|
35
|
+
throw new BravosError('an exception ends after today');
|
|
36
|
+
if (span > L.MAX_EXCEPTION_DAYS)
|
|
37
|
+
throw new BravosError(`an exception ends within ${L.MAX_EXCEPTION_DAYS} days`);
|
|
38
|
+
const { result } = await checkRecordsAt(root, env);
|
|
39
|
+
const record = result.adopted.find((r) => r.id === input.record);
|
|
40
|
+
if (!record)
|
|
41
|
+
throw new BravosError(`${input.record} is not an adopted record here (bravos records list)`);
|
|
42
|
+
const rule = record.rules.find((x) => x.id === input.rule);
|
|
43
|
+
if (!rule)
|
|
44
|
+
throw new BravosError(`${input.record} has no rule ${input.rule}`);
|
|
45
|
+
if (rule.kind !== 'enforced')
|
|
46
|
+
throw new BravosError(`${input.record} ${input.rule} is guidance: nothing holds a pull request for it, so it needs no exception`);
|
|
47
|
+
const { exceptions, problems } = L.readRecordExceptions(p.treeReader(root));
|
|
48
|
+
if (problems.length)
|
|
49
|
+
throw new BravosError(`${L.EXCEPTIONS_FILE} has problems; fix them first:\n${problems.map((x) => ` ${x}`).join('\n')}`);
|
|
50
|
+
const fields = { record: input.record, rule: input.rule, where: input.where, reason, by, approved: today(now), until: input.until };
|
|
51
|
+
const x = { ...fields, hash: L.exceptionFingerprint(fields) };
|
|
52
|
+
writeExceptions(root, L, [...exceptions, x]);
|
|
53
|
+
return [
|
|
54
|
+
`Exception recorded: ${x.record} ${x.rule} ("${rule.text}") in ${x.where} until ${x.until}, approved by ${x.by}: ${x.reason}`,
|
|
55
|
+
`Commit ${L.EXCEPTIONS_FILE}: the pre-PR gate then lets a break of this rule in that area through, and holds again the day after ${x.until}.`,
|
|
56
|
+
];
|
|
57
|
+
}
|
|
58
|
+
// @comment -- "Removes the exceptions whose last day has passed. Removing one only tightens the gate, so it needs no approver."
|
|
59
|
+
export async function clearExpiredRecordExceptions(root, now = new Date()) {
|
|
60
|
+
const L = await lib();
|
|
61
|
+
const p = await P();
|
|
62
|
+
const { exceptions, problems } = L.readRecordExceptions(p.treeReader(root));
|
|
63
|
+
if (problems.length)
|
|
64
|
+
throw new BravosError(`${L.EXCEPTIONS_FILE} has problems; fix them first:\n${problems.map((x) => ` ${x}`).join('\n')}`);
|
|
65
|
+
const live = exceptions.filter((e) => L.liveException(e, now));
|
|
66
|
+
if (live.length === exceptions.length)
|
|
67
|
+
return ['records: no exception has ended'];
|
|
68
|
+
writeExceptions(root, L, live);
|
|
69
|
+
return [`records: removed ${exceptions.length - live.length} ended exception${exceptions.length - live.length === 1 ? '' : 's'}`];
|
|
70
|
+
}
|
|
71
|
+
// ---------------------------------------------------------------------------------------------
|
|
72
|
+
// Gaps
|
|
73
|
+
// ---------------------------------------------------------------------------------------------
|
|
74
|
+
const RELEVANT = /@(?:exposes|mitigates|handles|flows|boundary|assumes|validates)\b/;
|
|
75
|
+
/** The module a file belongs to for the gaps report: its first two folders (src/billing), or its folder. */
|
|
76
|
+
const moduleOf = (file) => {
|
|
77
|
+
const parts = file.split('/');
|
|
78
|
+
return parts.length > 2 ? parts.slice(0, 2).join('/') : parts.length === 2 ? parts[0] : '.';
|
|
79
|
+
};
|
|
80
|
+
// @comment -- "bravos records gaps: the tracked files that carry security claims (inline, or in their .guardlink/annotations sidecar) and that no record's paths cover, grouped by module (their first two folders), most files first. Read-only: git ls-files and the files themselves, each at most 2 MB."
|
|
81
|
+
export async function recordGaps(root, env = process.env) {
|
|
82
|
+
const R = await recordsLib();
|
|
83
|
+
const { result } = await checkRecordsAt(root, env);
|
|
84
|
+
let files = [];
|
|
85
|
+
try {
|
|
86
|
+
files = execFileSync('git', ['ls-files', '-co', '--exclude-standard', '-z'], { cwd: root, env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 15000, maxBuffer: 64 * 1024 * 1024 }).split('\0').filter(Boolean);
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
throw new BravosError('bravos records gaps reads the repository through git; run it inside a git repository');
|
|
90
|
+
}
|
|
91
|
+
const read = (rel) => {
|
|
92
|
+
try {
|
|
93
|
+
const abs = join(root, rel);
|
|
94
|
+
return statSync(abs).isFile() && statSync(abs).size <= 2 * 1024 * 1024 ? readFileSync(abs, 'utf8') : '';
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
return '';
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
const byModule = new Map();
|
|
101
|
+
for (const f of files) {
|
|
102
|
+
if (f.startsWith('.guardlink/') || f.startsWith('.bravos/') || f.startsWith('.claude/') || f.startsWith('.agents/'))
|
|
103
|
+
continue;
|
|
104
|
+
if (R.recordsForFile(result.records, f).length)
|
|
105
|
+
continue;
|
|
106
|
+
if (!RELEVANT.test(read(f)) && !RELEVANT.test(read(`.guardlink/annotations/${f}.gal`)))
|
|
107
|
+
continue;
|
|
108
|
+
const m = moduleOf(f);
|
|
109
|
+
byModule.set(m, [...(byModule.get(m) ?? []), f]);
|
|
110
|
+
}
|
|
111
|
+
const modules = [...byModule.entries()].map(([module, fs]) => ({ module, files: fs.sort() })).sort((a, b) => b.files.length - a.files.length || a.module.localeCompare(b.module));
|
|
112
|
+
if (!modules.length)
|
|
113
|
+
return { modules, lines: [result.records.length ? 'records gaps: every file with security claims is covered by a record' : 'records gaps: no record here yet, and no file carries security claims'] };
|
|
114
|
+
return {
|
|
115
|
+
modules,
|
|
116
|
+
lines: [
|
|
117
|
+
`records gaps: ${modules.length} module${modules.length === 1 ? '' : 's'} with security claims and no record covering them:`,
|
|
118
|
+
...modules.map((m) => ` ${m.module} ${m.files.length} file${m.files.length === 1 ? '' : 's'} (${m.files.slice(0, 3).join(', ')}${m.files.length > 3 ? ', …' : ''})`),
|
|
119
|
+
'Ask your agent to draft a record for one: "write a security decision record for <module>" (bravos-records).',
|
|
120
|
+
],
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
// ---------------------------------------------------------------------------------------------
|
|
124
|
+
// Replay tests for enforced rules
|
|
125
|
+
// ---------------------------------------------------------------------------------------------
|
|
126
|
+
// @comment -- "The threats a bound replay kit already tests: every .guardlink/cxg-replay/*.js kit names its claim on a `// @guardlink_threat: <threat>@<file>:<line>` line. Read-only; an unreadable kit is skipped."
|
|
127
|
+
export function threatsWithKits(root) {
|
|
128
|
+
const dir = join(root, '.guardlink', 'cxg-replay');
|
|
129
|
+
const out = new Set();
|
|
130
|
+
if (!existsSync(dir))
|
|
131
|
+
return out;
|
|
132
|
+
for (const name of readdirSync(dir).filter((n) => n.endsWith('.js')).slice(0, 500)) {
|
|
133
|
+
try {
|
|
134
|
+
const text = readFileSync(join(dir, name), 'utf8').slice(0, 64 * 1024);
|
|
135
|
+
for (const m of text.matchAll(/@guardlink_threat:\s*#?([\w.-]+)@/g))
|
|
136
|
+
out.add(m[1]);
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
/* skipped */
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return out;
|
|
143
|
+
}
|
|
144
|
+
// @comment -- "What adopting a record leaves to prepare, rule by rule: each enforced rule's threat (record:SDR-n in the definitions) and whether a bound replay kit already tests it. Bravos cannot write a kit itself (an agent does, through bravos-templatize), so this says what is missing; once a kit runs, bravos-prove records a reproduced break as confirmed and the gate and bravos rules read it from the ledger."
|
|
145
|
+
export async function testPlanLines(root, record) {
|
|
146
|
+
const G = (await import(pathToFileURL(join(hooksDir(), 'lib', 'record-guard.mjs')).href));
|
|
147
|
+
const threats = G.ruleThreats(root, [record]);
|
|
148
|
+
const kits = threatsWithKits(root);
|
|
149
|
+
const out = [];
|
|
150
|
+
for (const rule of record.rules.filter((x) => x.kind === 'enforced')) {
|
|
151
|
+
const threat = [...threats.entries()].find(([, v]) => v.rule.id === rule.id)?.[0];
|
|
152
|
+
if (!threat)
|
|
153
|
+
out.push(`${record.id} ${rule.id} (enforced): no threat stands for it yet; your agent adds one with record:${record.id} (bravos-records) so the gate can hold a break`);
|
|
154
|
+
else if (!kits.has(threat))
|
|
155
|
+
out.push(`${record.id} ${rule.id} (enforced): #${threat} has no replay test yet; ask your agent to write one (bravos-templatize), so a break is confirmed by a test (bravos-prove)`);
|
|
156
|
+
else
|
|
157
|
+
out.push(`${record.id} ${rule.id} (enforced): #${threat} has a replay test`);
|
|
158
|
+
}
|
|
159
|
+
return out;
|
|
160
|
+
}
|
|
161
|
+
// ---------------------------------------------------------------------------------------------
|
|
162
|
+
// The review page
|
|
163
|
+
// ---------------------------------------------------------------------------------------------
|
|
164
|
+
export const RECORDS_DRAFT = '.guardlink/records-draft.json';
|
|
165
|
+
// @comment -- "The review page's draft, built from the record files as they read now: for each record that parses, one decision for its Decision, one per rule and one per not-a-bug line, each a must-touch item (Agree, Change or No; there is no adopt-all), each carrying the record's fingerprint so a Confirm against text that changed since the page loaded is refused. Bravos writes this file; an agent never does."
|
|
166
|
+
export async function recordsDraft(root, env = process.env) {
|
|
167
|
+
const { result } = await checkRecordsAt(root, env);
|
|
168
|
+
const questions = [];
|
|
169
|
+
for (const r of result.records) {
|
|
170
|
+
const base = { section: `${r.id} ${r.module}${r.title && !r.title.toLowerCase().startsWith(r.module.toLowerCase()) ? `: ${r.title}` : ''}`, mustTouch: true, suggested: 'agree', type: 'item' };
|
|
171
|
+
const meta = (part, key) => ({ record: r.id, part, key, hash: r.hash, file: r.file });
|
|
172
|
+
questions.push({ ...base, id: `${r.id}.decision`, title: 'Decision', text: r.decision, why: r.why || undefined, record: meta('decision', 'decision') });
|
|
173
|
+
for (const x of r.rules)
|
|
174
|
+
questions.push({ ...base, id: `${r.id}.${x.id}`, title: `${x.id} (${x.kind})`, text: x.text, why: x.kind === 'enforced' ? 'Enforced: a test can show it broken, and the pre-PR gate holds a change that breaks it.' : 'Guidance: coding agents follow it; nothing is tested.', record: meta('rule', x.id) });
|
|
175
|
+
r.notABug.forEach((t, n) => questions.push({ ...base, id: `${r.id}.notabug-${n + 1}`, title: 'Not a bug', text: t, record: meta('notabug', String(n)) }));
|
|
176
|
+
}
|
|
177
|
+
if (!questions.length)
|
|
178
|
+
throw new BravosError(result.records.length ? 'no record here parses: bravos records check lists what to fix' : 'no records here yet: ask your agent for "a security decision record for <module>" (bravos-records)');
|
|
179
|
+
const draft = { schema: 'bravos.review/v1', kind: 'records', repo: root.split('/').pop(), questions };
|
|
180
|
+
writeInRepo(root, RECORDS_DRAFT, JSON.stringify(draft, null, 2) + '\n');
|
|
181
|
+
return draft;
|
|
182
|
+
}
|
|
183
|
+
// @comment -- "Rewrites the parts of a record a person changed on the page, in their words, each cleaned to one line: the Decision section's text, a rule's text after its `R1 (kind):`, or one not-a-bug line. Everything else in the file is kept as it was."
|
|
184
|
+
export function rewriteRecord(text, edits) {
|
|
185
|
+
const lines = text.replace(/\r\n?/g, '\n').split('\n');
|
|
186
|
+
const one = (s) => s.replace(/[\u0000-\u001F\u007F]/g, ' ').replace(/\s+/g, ' ').trim();
|
|
187
|
+
const section = (name) => {
|
|
188
|
+
const start = lines.findIndex((l) => new RegExp(`^##\\s+${name}\\s*$`, 'i').test(l));
|
|
189
|
+
if (start < 0)
|
|
190
|
+
return null;
|
|
191
|
+
let end = lines.findIndex((l, i) => i > start && /^##\s+/.test(l));
|
|
192
|
+
if (end < 0)
|
|
193
|
+
end = lines.length;
|
|
194
|
+
return { start, end };
|
|
195
|
+
};
|
|
196
|
+
for (const e of edits) {
|
|
197
|
+
const t = one(e.text);
|
|
198
|
+
if (!t)
|
|
199
|
+
continue;
|
|
200
|
+
if (e.part === 'decision') {
|
|
201
|
+
const s = section('Decision');
|
|
202
|
+
if (s)
|
|
203
|
+
lines.splice(s.start + 1, s.end - s.start - 1, t, '');
|
|
204
|
+
}
|
|
205
|
+
else if (e.part === 'rule') {
|
|
206
|
+
const s = section('Rules');
|
|
207
|
+
if (!s)
|
|
208
|
+
continue;
|
|
209
|
+
for (let i = s.start + 1; i < s.end; i++) {
|
|
210
|
+
const m = new RegExp(`^(\\s*[-*]\\s+${e.key}\\s*\\((?:enforced|guidance)\\)\\s*:)\\s*.*$`, 'i').exec(lines[i]);
|
|
211
|
+
if (m) {
|
|
212
|
+
lines[i] = `${m[1]} ${t}`;
|
|
213
|
+
while (i + 1 < s.end && /^\s+\S/.test(lines[i + 1]) && !/^\s*[-*]\s+/.test(lines[i + 1]))
|
|
214
|
+
lines.splice(i + 1, 1);
|
|
215
|
+
break;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
else {
|
|
220
|
+
const s = section('Not a bug');
|
|
221
|
+
if (!s)
|
|
222
|
+
continue;
|
|
223
|
+
let n = -1;
|
|
224
|
+
for (let i = s.start + 1; i < s.end; i++) {
|
|
225
|
+
if (!/^\s*[-*]\s+/.test(lines[i]))
|
|
226
|
+
continue;
|
|
227
|
+
n++;
|
|
228
|
+
if (String(n) === e.key) {
|
|
229
|
+
lines[i] = `- ${t}`;
|
|
230
|
+
break;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
return lines.join('\n');
|
|
236
|
+
}
|
|
237
|
+
const AGREED = new Set(['accepted', 'chosen', 'agree']);
|
|
238
|
+
// @comment -- "What a Confirm on the records page records for that person, server side. Per record in the draft: every part agreed adopts the record as it reads now; any part changed rewrites the record file in the person's words and adopts the new text by them; any part answered No declines the record, with their comments. A record whose file changed since the page loaded is refused, so nobody adopts text they did not see. The person's earlier adoptions of records this page did not ask about are kept. Returns the answers to save (per-question answers for the page, per-record adoptions for the check) and lines for the page."
|
|
239
|
+
export async function withRecordAdoptions(root, draft, a, now = new Date()) {
|
|
240
|
+
const L = await lib();
|
|
241
|
+
const p = await P();
|
|
242
|
+
const reader = p.treeReader(root);
|
|
243
|
+
const rel = `${L.ANSWERS_DIR}/${slug(a.by)}.json`;
|
|
244
|
+
let kept = {};
|
|
245
|
+
const had = reader.read(rel);
|
|
246
|
+
if (had !== null) {
|
|
247
|
+
try {
|
|
248
|
+
const j = JSON.parse(had);
|
|
249
|
+
for (const [k, v] of Object.entries(j.answers ?? {}))
|
|
250
|
+
if (/^SDR-[1-9][0-9]{0,3}$/.test(k))
|
|
251
|
+
kept[k] = v;
|
|
252
|
+
}
|
|
253
|
+
catch {
|
|
254
|
+
kept = {};
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
const byRecord = new Map();
|
|
258
|
+
for (const q of draft.questions)
|
|
259
|
+
if (q.record)
|
|
260
|
+
byRecord.set(q.record.record, [...(byRecord.get(q.record.record) ?? []), q]);
|
|
261
|
+
const lines = [];
|
|
262
|
+
const out = Object.create(null);
|
|
263
|
+
for (const [id, ans] of Object.entries(a.answers)) {
|
|
264
|
+
const { adopted: _drop, ...rest } = ans;
|
|
265
|
+
out[id] = rest;
|
|
266
|
+
}
|
|
267
|
+
for (const [id, qs] of byRecord) {
|
|
268
|
+
const answers = qs.map((q) => ({ q, ans: a.answers[q.id] }));
|
|
269
|
+
if (answers.some((x) => !x.ans))
|
|
270
|
+
continue;
|
|
271
|
+
const file = qs[0].record.file;
|
|
272
|
+
const text = reader.read(file);
|
|
273
|
+
if (text === null)
|
|
274
|
+
throw new BravosError(`${file} is gone; reload the page`);
|
|
275
|
+
const now0 = L.parseRecord(text, file);
|
|
276
|
+
if (L.fingerprint(now0) !== qs[0].record.hash)
|
|
277
|
+
throw new BravosError(`${id} changed since this page loaded; reload the page and decide on the text it has now`);
|
|
278
|
+
if (answers.some((x) => x.ans.verdict === 'no')) {
|
|
279
|
+
const comment = answers.map((x) => x.ans.comment).filter(Boolean).join(' / ');
|
|
280
|
+
kept[id] = { verdict: 'no', ...(comment ? { comment } : {}), at: now.toISOString() };
|
|
281
|
+
lines.push(`${id}: declined by ${a.by}`);
|
|
282
|
+
continue;
|
|
283
|
+
}
|
|
284
|
+
const edits = answers.filter((x) => x.ans.verdict === 'edited' && typeof x.ans.value === 'string' && x.ans.value !== 'agree' && x.ans.value.trim()).map((x) => ({ part: x.q.record.part, key: x.q.record.key, text: x.ans.value }));
|
|
285
|
+
if (!answers.every((x) => AGREED.has(x.ans.verdict) || x.ans.verdict === 'edited'))
|
|
286
|
+
continue;
|
|
287
|
+
let record = now0;
|
|
288
|
+
if (edits.length) {
|
|
289
|
+
const next = rewriteRecord(text, edits);
|
|
290
|
+
record = L.parseRecord(next, file);
|
|
291
|
+
if (record.problems.length)
|
|
292
|
+
throw new BravosError(`${id}: the change would leave the record unreadable (${record.problems[0]}); keep each rule to one sentence`);
|
|
293
|
+
writeInRepo(root, file, next);
|
|
294
|
+
lines.push(`${id}: ${edits.length} part${edits.length === 1 ? '' : 's'} rewritten in ${a.by}'s words`);
|
|
295
|
+
}
|
|
296
|
+
kept[id] = { verdict: 'yes', adopted: L.adoptedFields(record), adoptedAt: now.toISOString(), on: 'review page' };
|
|
297
|
+
lines.push(`${id} (${record.module}) adopted by ${a.by}`);
|
|
298
|
+
lines.push(...(await testPlanLines(root, { ...record, id })));
|
|
299
|
+
}
|
|
300
|
+
for (const [k, v] of Object.entries(kept))
|
|
301
|
+
out[k] = v;
|
|
302
|
+
return { answers: { ...a, answers: out }, lines };
|
|
303
|
+
}
|
|
304
|
+
const approvalLib = async () => (await recordsLib());
|
|
305
|
+
/** owner/repo of a GitHub origin URL (https or ssh), or null for any other host. */
|
|
306
|
+
export function githubRepo(url) {
|
|
307
|
+
const m = /github\.com[:/]+([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/.exec(url.trim());
|
|
308
|
+
return m ? `${m[1]}/${m[2]}` : null;
|
|
309
|
+
}
|
|
310
|
+
const runCmd = (cmd, args) => {
|
|
311
|
+
try {
|
|
312
|
+
return { status: 0, stdout: execFileSync(cmd, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 15000 }) };
|
|
313
|
+
}
|
|
314
|
+
catch (e) {
|
|
315
|
+
return { status: e.status ?? 1, stdout: String(e.stdout ?? '') };
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
// @comment -- "Whether the default branch requires a code owner's review for .guardlink/records/, asked of GitHub with gh as the person signed in: a ruleset's pull-request rule or the classic branch protection with require_code_owner_reviews, and a CODEOWNERS line that names an owner for the records. The answer is cached under the git directory (never committed) for the hooks, which stay offline. Unreadable (gh missing or signed out, no GitHub origin, no permission) is unknown, never yes."
|
|
319
|
+
// @flows #records -> GitHub.API via gh -- "bravos records check asks GitHub, through the person's own gh login, whether the default branch requires code-owner review"
|
|
320
|
+
export async function refreshReview(root, env = process.env, run = runCmd) {
|
|
321
|
+
const A = await approvalLib();
|
|
322
|
+
const p = await P();
|
|
323
|
+
const ctx = A.approvalContext(root);
|
|
324
|
+
if (!ctx)
|
|
325
|
+
return null;
|
|
326
|
+
const url = run('git', ['-C', root, 'remote', 'get-url', 'origin']).stdout.trim();
|
|
327
|
+
const repo = githubRepo(url);
|
|
328
|
+
const branch = ctx.ref.replace(/^origin\//, '');
|
|
329
|
+
let enforced = null;
|
|
330
|
+
let reason = '';
|
|
331
|
+
const co = A.readCodeowners(p.treeReader(root));
|
|
332
|
+
const owners = A.ownersFor(co, '.guardlink/records/x.md');
|
|
333
|
+
if (!repo)
|
|
334
|
+
reason = 'origin is not a GitHub repository, so only typed-name adoption is available';
|
|
335
|
+
else if (!owners.length) {
|
|
336
|
+
enforced = false;
|
|
337
|
+
reason = `no CODEOWNERS line names an owner for .guardlink/records/ (bravos records codeowners shows the line to add)`;
|
|
338
|
+
}
|
|
339
|
+
else if (run('gh', ['--version']).status !== 0)
|
|
340
|
+
reason = 'gh is not installed, so GitHub was not asked';
|
|
341
|
+
else {
|
|
342
|
+
const rules = run('gh', ['api', `repos/${repo}/rules/branches/${encodeURIComponent(branch)}`]);
|
|
343
|
+
let viaRuleset = false;
|
|
344
|
+
try {
|
|
345
|
+
viaRuleset = rules.status === 0 && JSON.parse(rules.stdout).some((r) => r?.type === 'pull_request' && r.parameters?.require_code_owner_review === true);
|
|
346
|
+
}
|
|
347
|
+
catch {
|
|
348
|
+
viaRuleset = false;
|
|
349
|
+
}
|
|
350
|
+
const classic = run('gh', ['api', `repos/${repo}/branches/${encodeURIComponent(branch)}/protection/required_pull_request_reviews`]);
|
|
351
|
+
let viaClassic = false;
|
|
352
|
+
try {
|
|
353
|
+
viaClassic = classic.status === 0 && JSON.parse(classic.stdout).require_code_owner_reviews === true;
|
|
354
|
+
}
|
|
355
|
+
catch {
|
|
356
|
+
viaClassic = false;
|
|
357
|
+
}
|
|
358
|
+
if (viaRuleset || viaClassic) {
|
|
359
|
+
enforced = true;
|
|
360
|
+
reason = `${branch} requires a code owner's review (${viaRuleset ? 'a ruleset' : 'branch protection'}), and CODEOWNERS names ${owners.join(' ')} for .guardlink/records/`;
|
|
361
|
+
}
|
|
362
|
+
else if (rules.status === 0) {
|
|
363
|
+
enforced = false;
|
|
364
|
+
reason = `${branch} does not require a code owner's review for pull requests`;
|
|
365
|
+
}
|
|
366
|
+
else
|
|
367
|
+
reason = `GitHub did not answer for ${repo} (gh signed out, or no permission to read its rules)`;
|
|
368
|
+
}
|
|
369
|
+
const dir = run('git', ['-C', root, 'rev-parse', '--path-format=absolute', '--git-common-dir']).stdout.trim();
|
|
370
|
+
if (dir) {
|
|
371
|
+
try {
|
|
372
|
+
writeInRepo(dir, 'bravos/records-review.json', JSON.stringify({ schema: A.REVIEW_SCHEMA, branch: ctx.ref, enforced, reason, checkedAt: new Date().toISOString() }, null, 2) + '\n');
|
|
373
|
+
}
|
|
374
|
+
catch {
|
|
375
|
+
/* the cache is best effort */
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
return { enforced, reason };
|
|
379
|
+
}
|
|
380
|
+
// @comment -- "bravos records codeowners: the CODEOWNERS lines that make a record (and an exception) need its owner's review on GitHub. Without --yes it only shows what it would add and where; with --yes, given after the person said so, it appends them to the CODEOWNERS file GitHub reads (creating .github/CODEOWNERS if there is none). It never removes or changes a line someone wrote."
|
|
381
|
+
export async function codeownersLines(root, owner, yes) {
|
|
382
|
+
const A = await approvalLib();
|
|
383
|
+
const p = await P();
|
|
384
|
+
if (!/^@[\w.-]+(?:\/[\w.-]+)?$/.test(owner))
|
|
385
|
+
throw new BravosError('the owner is a GitHub user or team, e.g. --owner @security-leads or --owner @your-org/security');
|
|
386
|
+
const co = A.readCodeowners(p.treeReader(root));
|
|
387
|
+
const file = co?.file ?? '.github/CODEOWNERS';
|
|
388
|
+
const want = ['/.guardlink/records/', '/.guardlink/records-exceptions.json'];
|
|
389
|
+
const missing = want.filter((pat) => !A.ownersFor(co, pat === want[0] ? '.guardlink/records/x.md' : '.guardlink/records-exceptions.json').includes(owner));
|
|
390
|
+
if (!missing.length)
|
|
391
|
+
return [`${file} already names ${owner} for the records and their exceptions`];
|
|
392
|
+
const add = missing.map((pat) => `${pat} ${owner}`);
|
|
393
|
+
if (!yes)
|
|
394
|
+
return [`To make a record and an exception need ${owner}'s review on GitHub, add to ${file}:`, ...add.map((l) => ` ${l}`), 'Ask the person first; on their go-ahead run this again with --yes. Then require code-owner review for the default branch (Settings > Branches or Rules), and bravos records check confirms it.'];
|
|
395
|
+
const text = p.treeReader(root).read(file) ?? '';
|
|
396
|
+
writeInRepo(root, file, `${text}${text && !text.endsWith('\n') ? '\n' : ''}# Security decision records: a change needs its owner's review (bravos records codeowners)\n${add.join('\n')}\n`);
|
|
397
|
+
return [`Added to ${file}:`, ...add.map((l) => ` ${l}`), 'Commit it, then require code-owner review for the default branch on GitHub; bravos records check confirms it.'];
|
|
398
|
+
}
|
package/dist/records.js
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
// @comment -- "bravos records, the CLI side: lists and shows the security decision records under .guardlink/records/, checks them, says which record covers a file, writes the skeleton of a new one, and records a person's adoption. The format, the fingerprint and the check itself are in hooks/lib/records.mjs, shared with the briefing and the hooks."
|
|
2
|
+
import { execFileSync } from 'node:child_process';
|
|
3
|
+
import { userInfo } from 'node:os';
|
|
4
|
+
import { isAbsolute, join, relative, resolve } from 'node:path';
|
|
5
|
+
import { pathToFileURL } from 'node:url';
|
|
6
|
+
import { hooksDir } from './paths.js';
|
|
7
|
+
import { writeInRepo } from './principles.js';
|
|
8
|
+
import { slug } from './review.js';
|
|
9
|
+
import { BravosError } from './types.js';
|
|
10
|
+
let cached = null;
|
|
11
|
+
export const recordsLib = () => (cached ??= import(pathToFileURL(join(hooksDir(), 'lib', 'records.mjs')).href));
|
|
12
|
+
const reader = async (root) => (await import(pathToFileURL(join(hooksDir(), 'lib', 'principles.mjs')).href)).treeReader(root);
|
|
13
|
+
// @comment -- "The repository's files as git knows them (tracked, and untracked ones that are not ignored), for the note about a record path that matches nothing. argv only, bounded; null outside a repository or without git, and the note is then skipped."
|
|
14
|
+
function repoFiles(root, env) {
|
|
15
|
+
try {
|
|
16
|
+
return execFileSync('git', ['ls-files', '-co', '--exclude-standard', '-z'], { cwd: root, env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 15000, maxBuffer: 64 * 1024 * 1024 }).split('\0').filter(Boolean);
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
const who = (env) => {
|
|
23
|
+
let user;
|
|
24
|
+
try {
|
|
25
|
+
user = userInfo().username;
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
user = undefined;
|
|
29
|
+
}
|
|
30
|
+
return { home: env.HOME, user };
|
|
31
|
+
};
|
|
32
|
+
// @comment -- "Runs the records check on the working tree, with the repository's file list (so a path that matches nothing is noted) and this person's home folder (so a record that names it is refused)."
|
|
33
|
+
export async function checkRecordsAt(root, env = process.env) {
|
|
34
|
+
const L = await recordsLib();
|
|
35
|
+
const result = L.checkRecords(await reader(root), { files: repoFiles(root, env), who: who(env), root });
|
|
36
|
+
// What each approval proves, in words, for every place a record is printed.
|
|
37
|
+
for (const r of result.records)
|
|
38
|
+
r.approvalText = L.approvalWords(r.approval);
|
|
39
|
+
return { result, lines: L.formatCheck(result) };
|
|
40
|
+
}
|
|
41
|
+
/** A record as an agent or a person reads it in a terminal: who adopted it, what it covers, the decision, each rule and what is not a bug. */
|
|
42
|
+
export function recordLines(r) {
|
|
43
|
+
const words = r.approvalText ?? '';
|
|
44
|
+
const state = r.state === 'adopted' ? words || `adopted by ${r.adopters.map((a) => `${a.by} (${a.date})`).join(', ')}` : r.state === 'proposed' ? 'a proposed change: binds once approved on the default branch (a code owner\'s review) or adopted by name' : r.state === 'draft' ? 'draft: not approved yet, so it binds nobody' : r.state === 'changed' ? `changed since ${r.stale.map((a) => a.by).join(', ')} adopted it, so it binds nobody until it is adopted again` : r.state;
|
|
45
|
+
return [
|
|
46
|
+
`${r.id} ${r.title && r.title.toLowerCase().startsWith(r.module.toLowerCase()) ? r.title : `${r.module}${r.title ? `: ${r.title}` : ''}`}`,
|
|
47
|
+
` ${state}`,
|
|
48
|
+
` file: ${r.file}`,
|
|
49
|
+
` covers: ${r.paths.join(', ')}`,
|
|
50
|
+
` decision: ${r.decision}`,
|
|
51
|
+
...r.rules.map((x) => ` ${x.id} (${x.kind}): ${x.text}`),
|
|
52
|
+
...r.notABug.map((x) => ` not a bug: ${x}`),
|
|
53
|
+
];
|
|
54
|
+
}
|
|
55
|
+
// @comment -- "bravos records show SDR-n: the one record, or a refusal that names the ids there are."
|
|
56
|
+
export async function showRecord(root, id, env = process.env) {
|
|
57
|
+
const { result } = await checkRecordsAt(root, env);
|
|
58
|
+
const r = result.records.find((x) => x.id === id);
|
|
59
|
+
if (!r)
|
|
60
|
+
throw new BravosError(result.records.length ? `no record ${id} here; there ${result.records.length === 1 ? 'is' : 'are'} ${result.records.map((x) => x.id).join(', ')} (a record that does not parse is not listed: bravos records check)` : `no record ${id} here: .guardlink/records/ holds none that parse (bravos records check)`);
|
|
61
|
+
return { record: r, lines: recordLines(r) };
|
|
62
|
+
}
|
|
63
|
+
// @comment -- "bravos records for <file>: the records whose paths cover a repository file, adopted ones first. The path is taken relative to the repository and refused when it points outside it."
|
|
64
|
+
export async function recordsFor(root, file, env = process.env) {
|
|
65
|
+
const L = await recordsLib();
|
|
66
|
+
const rel = (isAbsolute(file) ? relative(resolve(root), file) : file).split('\\').join('/').replace(/^\.\//, '');
|
|
67
|
+
if (!rel || rel.startsWith('..'))
|
|
68
|
+
throw new BravosError(`${file} is not inside this repository`);
|
|
69
|
+
const { result } = await checkRecordsAt(root, env);
|
|
70
|
+
const hits = L.recordsForFile(result.records, rel).sort((a, b) => Number(b.state === 'adopted') - Number(a.state === 'adopted'));
|
|
71
|
+
if (!hits.length)
|
|
72
|
+
return { file: rel, records: [], lines: [`${rel}: no security decision record covers this file${result.adopted.length ? '. If it holds security decisions for its module, tell the developer and offer to draft one (bravos-records).' : '.'}`] };
|
|
73
|
+
return { file: rel, records: hits, lines: [`${rel} is covered by ${hits.map((r) => r.id).join(', ')}. Read ${hits.length === 1 ? 'it' : 'each'} before changing this file:`, ...hits.flatMap(recordLines)] };
|
|
74
|
+
}
|
|
75
|
+
const SKELETON = (id, module, paths) => `---
|
|
76
|
+
record: ${id}
|
|
77
|
+
module: ${module}
|
|
78
|
+
paths: [${paths.join(', ')}]
|
|
79
|
+
---
|
|
80
|
+
# ${module}: <what this record decides, in a few words>
|
|
81
|
+
|
|
82
|
+
## Decision
|
|
83
|
+
<What was decided for this module, in two or three plain sentences. Who may do what, and what is closed.>
|
|
84
|
+
|
|
85
|
+
## Rules
|
|
86
|
+
- R1 (enforced): <One rule a test can show broken, in one sentence.>
|
|
87
|
+
- R2 (guidance): <One rule to follow that no test checks.>
|
|
88
|
+
|
|
89
|
+
## Why
|
|
90
|
+
<The reason, so the next person does not undo it by accident.>
|
|
91
|
+
|
|
92
|
+
## Not a bug
|
|
93
|
+
- <Something that looks wrong and is the decision, e.g. "Sales gets 'not allowed' on the margin report.">
|
|
94
|
+
`;
|
|
95
|
+
// @comment -- "bravos records new: writes the skeleton of the next record (the next free SDR id, a file name from the module, the paths given) for a person or their agent to fill in. It refuses a module name with no letters or digits, a path that is not a repository glob, and a file that already exists. A new record is a draft: it binds nobody until a person adopts it."
|
|
96
|
+
export async function newRecord(root, module, paths) {
|
|
97
|
+
const L = await recordsLib();
|
|
98
|
+
const P = (await import(pathToFileURL(join(hooksDir(), 'lib', 'principles.mjs')).href));
|
|
99
|
+
const name = P.oneLine(module, 80);
|
|
100
|
+
const part = slug(name);
|
|
101
|
+
if (!part)
|
|
102
|
+
throw new BravosError('a record needs the name of its module or feature, e.g. bravos records new "Reports" --paths "src/reports/**"');
|
|
103
|
+
if (!paths.length)
|
|
104
|
+
throw new BravosError('a record needs the code it covers: --paths "<glob>,<glob>" (repository globs, e.g. src/reports/**)');
|
|
105
|
+
for (const p of paths)
|
|
106
|
+
if (!P.validGlob(p))
|
|
107
|
+
throw new BravosError(`"${p}" is not a repository glob (letters, digits, . _ - / * ? { } , only; no leading / and no ..)`);
|
|
108
|
+
const r = await reader(root);
|
|
109
|
+
const existing = L.readRecords(r);
|
|
110
|
+
const id = L.nextId(existing);
|
|
111
|
+
const rel = `${L.RECORDS_DIR}/${id}-${part}.md`;
|
|
112
|
+
if (r.read(rel) !== null)
|
|
113
|
+
throw new BravosError(`${rel} already exists`);
|
|
114
|
+
writeInRepo(root, rel, SKELETON(id, name, paths));
|
|
115
|
+
return [`${rel} written: fill in the decision, the rules, why, and what is not a bug, in the developer's own words.`, `It is a draft and binds nobody until it is approved: a code owner's review of its pull request, or, the fallback, bravos records adopt ${id} at a person's own terminal.`];
|
|
116
|
+
}
|
|
117
|
+
// @comment -- "Records one person's adoption of a record as it reads now: the record must pass the check's own reading (it parses, carries no secret and no local path), and the answers file for that person gains the record's fingerprint, module, paths and rules. An earlier adoption by the same person of the same record is replaced; their adoptions of other records are kept. The CLI calls this only from an interactive terminal after the person typed their name and the record id; it never runs for an agent."
|
|
118
|
+
// @mitigates #records against #forged-record using #record-fingerprint -- "The adoption written for a person carries the fingerprint of the exact text they adopted, so a later edit to the record no longer matches it"
|
|
119
|
+
export async function adoptRecord(root, id, by, env = process.env, now = new Date()) {
|
|
120
|
+
const L = await recordsLib();
|
|
121
|
+
const P = (await import(pathToFileURL(join(hooksDir(), 'lib', 'principles.mjs')).href));
|
|
122
|
+
const name = P.oneLine(by, 80);
|
|
123
|
+
if (!name || !slug(name))
|
|
124
|
+
throw new BravosError('an adoption needs the name of the person adopting');
|
|
125
|
+
if (!L.ID.test(id))
|
|
126
|
+
throw new BravosError(`"${id}" is not a record id (SDR-n)`);
|
|
127
|
+
const r = await reader(root);
|
|
128
|
+
const check = L.checkRecords(r, { who: who(env) });
|
|
129
|
+
const record = check.records.find((x) => x.id === id);
|
|
130
|
+
const about = check.problems.filter((p) => p.includes(`${L.RECORDS_DIR}/${id}-`) || p.includes(`${L.RECORDS_DIR}/${id}.md`));
|
|
131
|
+
if (!record)
|
|
132
|
+
throw new BravosError(about.length ? `${id} cannot be adopted until it is fixed:\n${about.map((p) => ` ${p}`).join('\n')}` : `no record ${id} here (bravos records list)`);
|
|
133
|
+
const unsafe = about.filter((p) => /looks like it holds|names a local path/.test(p));
|
|
134
|
+
if (unsafe.length)
|
|
135
|
+
throw new BravosError(`${id} cannot be adopted until it is fixed:\n${unsafe.map((p) => ` ${p}`).join('\n')}`);
|
|
136
|
+
const rel = `${L.ANSWERS_DIR}/${slug(name)}.json`;
|
|
137
|
+
let answers = {};
|
|
138
|
+
const had = r.read(rel);
|
|
139
|
+
if (had !== null) {
|
|
140
|
+
let j;
|
|
141
|
+
try {
|
|
142
|
+
j = JSON.parse(had);
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
throw new BravosError(`${rel} is not valid JSON; fix or remove it first`);
|
|
146
|
+
}
|
|
147
|
+
if (j.schema !== L.ANSWERS_SCHEMA || j.kind !== 'records' || typeof j.answers !== 'object' || j.answers === null || Array.isArray(j.answers))
|
|
148
|
+
throw new BravosError(`${rel} is not a records answers file; fix or remove it first`);
|
|
149
|
+
if (typeof j.by === 'string' && P.oneLine(j.by, 80) !== name)
|
|
150
|
+
throw new BravosError(`${rel} holds the adoptions of "${P.oneLine(j.by, 80)}", whose name gives the same file name; adopt under a name that differs`);
|
|
151
|
+
answers = j.answers;
|
|
152
|
+
}
|
|
153
|
+
const adopted = L.adoptedFields(record);
|
|
154
|
+
answers[id] = { verdict: 'yes', adopted, adoptedAt: now.toISOString() };
|
|
155
|
+
writeInRepo(root, rel, JSON.stringify({ schema: L.ANSWERS_SCHEMA, kind: 'records', by: name, date: now.toISOString().slice(0, 10), confirmedAt: now.toISOString(), status: 'confirmed', answers }, null, 2) + '\n');
|
|
156
|
+
const plan = await (await import('./records-team.js')).testPlanLines(root, record).catch(() => []);
|
|
157
|
+
return [`${id} (${record.module}) adopted by ${name}: ${record.rules.length} rule${record.rules.length === 1 ? '' : 's'}, fingerprint ${adopted.hash}.`, ...plan, `Recorded in ${rel}. Commit it with ${record.file} so every clone and every agent follows the record.`];
|
|
158
|
+
}
|
package/dist/review-server.js
CHANGED
|
@@ -3,7 +3,9 @@ import { addPageDocument } from './context.js';
|
|
|
3
3
|
import { prepareReview, readDraft, renderReview, startReviewServer } from './review.js';
|
|
4
4
|
const [root, kind, token, port] = process.argv.slice(2);
|
|
5
5
|
const load = async () => {
|
|
6
|
-
|
|
6
|
+
// A records page is rebuilt from the record files on each load, so it always shows the text a Confirm adopts.
|
|
7
|
+
const draft = kind === 'records' ? await (await import('./records-team.js')).recordsDraft(root) : readDraft(root, kind);
|
|
8
|
+
const review = await prepareReview(root, draft);
|
|
7
9
|
return { draft: review.draft, page: await renderReview(review, { kind: 'serve', token }) };
|
|
8
10
|
};
|
|
9
11
|
const first = await load();
|
package/dist/review.js
CHANGED
|
@@ -84,6 +84,14 @@ export function validateDraft(value, kind) {
|
|
|
84
84
|
checkPrincipleQuestion(q, bad);
|
|
85
85
|
else if (q.principle !== undefined)
|
|
86
86
|
throw bad(`${q.id}: principle details belong in the principles draft only`);
|
|
87
|
+
// A records draft is written by bravos from the record files; each question names its record, the part and the fingerprint.
|
|
88
|
+
if (kind === 'records') {
|
|
89
|
+
const r = q.record;
|
|
90
|
+
if (q.type !== 'item' || q.mustTouch !== true || !isObject(r) || !/^SDR-[1-9][0-9]{0,3}$/.test(String(r.record)) || !['decision', 'rule', 'notabug'].includes(String(r.part)) || !str(r.key, 20) || !/^[0-9a-f]{16}$/.test(String(r.hash)) || !/^\.guardlink\/records\/SDR-[1-9][0-9]{0,3}[a-z0-9-]*\.md$/.test(String(r.file)))
|
|
91
|
+
throw bad(`${q.id}: a records question is a must-touch item naming its record, part, fingerprint and file (bravos review records writes this draft)`);
|
|
92
|
+
}
|
|
93
|
+
else if (q.record !== undefined)
|
|
94
|
+
throw bad(`${q.id}: record details belong in the records draft only`);
|
|
87
95
|
if (q.permission !== undefined) {
|
|
88
96
|
const p = q.permission;
|
|
89
97
|
const label = (v) => typeof v === 'string' && v.trim().length > 0 && v.length <= 160;
|
|
@@ -583,12 +591,19 @@ export function startReviewServer(root, draft, page, token, port = 0, opts = {})
|
|
|
583
591
|
const missing = missingDecisions(c.draft, a);
|
|
584
592
|
if (missing.length)
|
|
585
593
|
return send(400, `these decisions still need your call: ${missing.join(', ')}`);
|
|
594
|
+
// Records: each record is adopted, rewritten in the person's words and adopted, or declined, server side (src/records-team.ts).
|
|
595
|
+
let recorded = [];
|
|
596
|
+
if (c.draft.kind === 'records') {
|
|
597
|
+
const r = await (await import('./records-team.js')).withRecordAdoptions(root, c.draft, a, now());
|
|
598
|
+
a = r.answers;
|
|
599
|
+
recorded = r.lines;
|
|
600
|
+
}
|
|
586
601
|
const rel = `${answersDir(c.draft.kind)}/${slug(a.by)}.json`;
|
|
587
602
|
const confirmedAt = now().toISOString();
|
|
588
603
|
writeReviewFile(root, rel, JSON.stringify({ ...a, status: 'confirmed', confirmedAt }, null, 2) + '\n');
|
|
589
604
|
rmSync(join(root, progressPath(c.draft.kind, a.by)), { force: true });
|
|
590
605
|
const after = opts.afterConfirm ? await opts.afterConfirm(c.draft.kind).catch((e) => [`could not update after Confirm: ${e instanceof Error ? e.message : String(e)}`]) : [];
|
|
591
|
-
send(200, JSON.stringify({ saved: rel, confirmedAt, lines: after }), 'application/json');
|
|
606
|
+
send(200, JSON.stringify({ saved: rel, confirmedAt, lines: [...recorded, ...after] }), 'application/json');
|
|
592
607
|
}
|
|
593
608
|
catch (e) {
|
|
594
609
|
send(400, e instanceof Error ? e.message : 'bad answers');
|