@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
package/dist/prefs.js
CHANGED
|
@@ -24,6 +24,14 @@ const NOTIFY_WHAT = {
|
|
|
24
24
|
on: 'also send a desktop notification for each threat card',
|
|
25
25
|
off: 'send no desktop notifications',
|
|
26
26
|
};
|
|
27
|
+
const NUDGE_WHAT = {
|
|
28
|
+
on: 'say once per module per session, at the first edit, when a module the ledger marks as needing a security decision record has none',
|
|
29
|
+
off: 'say nothing about modules without a record; the briefing still counts them',
|
|
30
|
+
};
|
|
31
|
+
const DRAFTS_WHAT = {
|
|
32
|
+
background: 'let one background pass each session draft security decision records for the reviewed ledger\'s modules that need one (Team plan), pushing nothing without asking',
|
|
33
|
+
off: 'draft no records in the background; the agent drafts one when asked',
|
|
34
|
+
};
|
|
27
35
|
const ANNOTATE_WHAT = {
|
|
28
36
|
background: 'start one background annotation pass each session while coverage is incomplete',
|
|
29
37
|
off: 'start no background annotation pass; annotate when asked and after your edits',
|
|
@@ -44,6 +52,8 @@ export async function getPrefs(root, env, json = false) {
|
|
|
44
52
|
a ? `annotate: ${a.value} — ${ANNOTATE_WHAT[a.value]} (${a.by}, ${a.at})` : `annotate: not recorded — ${ANNOTATE_WHAT.background} (the default)`,
|
|
45
53
|
prefs.cards ? `cards: ${prefs.cards.value} — ${CARDS_WHAT[prefs.cards.value]} (${prefs.cards.by}, ${prefs.cards.at})` : `cards: not recorded — ${CARDS_WHAT.on} (the default)`,
|
|
46
54
|
prefs.notify ? `notify: ${prefs.notify.value} — ${NOTIFY_WHAT[prefs.notify.value]} (${prefs.notify.by}, ${prefs.notify.at})` : `notify: not recorded — ${NOTIFY_WHAT.off} (the default)`,
|
|
55
|
+
prefs.nudge ? `nudge: ${prefs.nudge.value} — ${NUDGE_WHAT[prefs.nudge.value]} (${prefs.nudge.by}, ${prefs.nudge.at})` : `nudge: not recorded — ${NUDGE_WHAT.on} (the default)`,
|
|
56
|
+
prefs.drafts ? `drafts: ${prefs.drafts.value} — ${DRAFTS_WHAT[prefs.drafts.value]} (${prefs.drafts.by}, ${prefs.drafts.at})` : `drafts: not recorded — ${DRAFTS_WHAT.background} (the default)`,
|
|
47
57
|
prefs.coach ? `coach: ${prefs.coach.value} — ${COACH_WHAT[prefs.coach.value]} (${prefs.coach.by}, ${prefs.coach.at})` : `coach: not recorded — ${COACH_WHAT.on} (the default)`,
|
|
48
58
|
`kept in ${L.prefsFile(dir)} (this clone only; never committed)`,
|
|
49
59
|
];
|
|
@@ -57,9 +67,9 @@ export async function setCommits(root, value, by, env, now = new Date()) {
|
|
|
57
67
|
// @mitigates #person-prefs against #governance-forgery using #prefs-outside-tree -- "Every answer is written under the git directory with the name of the person who gave it."
|
|
58
68
|
export async function setPref(root, key, value, by, env, now = new Date()) {
|
|
59
69
|
const L = await prefsLib();
|
|
60
|
-
const choices = key === 'commits' || key === 'annotate' || key === 'coach' || key === 'cards' || key === 'notify' ? L.PREF_CHOICES[key] : null;
|
|
70
|
+
const choices = key === 'commits' || key === 'annotate' || key === 'coach' || key === 'cards' || key === 'notify' || key === 'nudge' || key === 'drafts' ? L.PREF_CHOICES[key] : null;
|
|
61
71
|
if (!choices)
|
|
62
|
-
throw new BravosError('usage: bravos prefs set commits <commit|leave|ask> --by "<your name>" | bravos prefs set annotate <background|off> --by "<your name>" | bravos prefs set coach|cards|notify <on|off> --by "<your name>"');
|
|
72
|
+
throw new BravosError('usage: bravos prefs set commits <commit|leave|ask> --by "<your name>" | bravos prefs set annotate|drafts <background|off> --by "<your name>" | bravos prefs set coach|cards|notify|nudge <on|off> --by "<your name>"');
|
|
63
73
|
if (!choices.includes(value))
|
|
64
74
|
throw new BravosError(`usage: bravos prefs set ${key} <${choices.join('|')}> --by "<your name>"`);
|
|
65
75
|
if (!by?.trim())
|
|
@@ -74,7 +84,7 @@ export async function setPref(root, key, value, by, env, now = new Date()) {
|
|
|
74
84
|
catch (e) {
|
|
75
85
|
throw new BravosError(e instanceof Error ? e.message : String(e));
|
|
76
86
|
}
|
|
77
|
-
const what = key === 'commits' ? WHAT[value] : key === 'coach' ? COACH_WHAT[value] : key === 'cards' ? CARDS_WHAT[value] : key === 'notify' ? NOTIFY_WHAT[value] : ANNOTATE_WHAT[value];
|
|
87
|
+
const what = key === 'commits' ? WHAT[value] : key === 'coach' ? COACH_WHAT[value] : key === 'cards' ? CARDS_WHAT[value] : key === 'notify' ? NOTIFY_WHAT[value] : key === 'nudge' ? NUDGE_WHAT[value] : key === 'drafts' ? DRAFTS_WHAT[value] : ANNOTATE_WHAT[value];
|
|
78
88
|
const lines = [`${key}: ${value} — from now on the agent will ${what}`, `recorded in ${file} (this clone only; never committed)`];
|
|
79
89
|
// On macOS the notifications come through osascript (shown as Script Editor) until the Bravos notifier app is staged.
|
|
80
90
|
if (key === 'notify' && value === 'on' && process.platform === 'darwin')
|
package/dist/principles.js
CHANGED
|
@@ -11,7 +11,7 @@ let cached = null;
|
|
|
11
11
|
export const principlesLib = () => (cached ??= import(pathToFileURL(join(hooksDir(), 'lib', 'principles.mjs')).href));
|
|
12
12
|
const today = (now) => now.toISOString().slice(0, 10);
|
|
13
13
|
// @comment -- "Writes one file inside the repository: every folder on the way must be a real folder (no link), and the file is replaced atomically through a temporary name, so a planted link cannot redirect the write."
|
|
14
|
-
function writeInRepo(root, rel, data) {
|
|
14
|
+
export function writeInRepo(root, rel, data) {
|
|
15
15
|
let dir = realpathSync(root);
|
|
16
16
|
for (const part of dirname(rel).split(/[\\/]/).filter((p) => p && p !== '.')) {
|
|
17
17
|
dir = join(dir, part);
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { BravosError } from './types.js';
|
|
5
|
+
// @comment -- "Possible conflicts between a security decision record and the code it covers: open exposures (no control, not accepted) and SAST findings inside a record's paths whose weakness bears on one of its rules, each with the reason it was matched. Deterministic, no model: a fixed table maps a rule's words to weakness families, and a candidate matches a family by its CWE, or, with none, by its threat or rule name. These are suggestions for a person: they never mark a rule broken or unguarded, never reach the pre-PR gate and never write an annotation. A person dismisses one at their own terminal, recorded with their name in .guardlink/records-dismissals.json, never as @accepts."
|
|
6
|
+
export const DISMISSALS_FILE = '.guardlink/records-dismissals.json';
|
|
7
|
+
export const DISMISSALS_SCHEMA = 'bravos.records-dismissals/v1';
|
|
8
|
+
// The weakness families a rule can be about. Words are matched in a rule's text; CWEs and names in a candidate's.
|
|
9
|
+
export const FAMILIES = [
|
|
10
|
+
{ id: 'access', label: 'an access-control weakness', about: 'who may see or do what', strong: /\b(admins?|owners?|roles?|permissions?|authori[sz]\w*|tenants?|private)\b/i, words: /\b(admins?|owners?|roles?|permissions?|authori[sz]\w*|allowed|only|may|can (?:open|view|see|read|edit|delete|change)|access|tenants?|private|visible|sees?|opens?)\b/i, cwes: [284, 285, 269, 266, 425, 639, 732, 862, 863, 915, 1220], names: /idor|access|authz|authori[sz]|privilege|bac\b|permission|tenant|ownership|admin/i },
|
|
11
|
+
{ id: 'injection', label: 'an injection weakness', about: 'how input reaches a query, a command or a page', words: /\b(sql|query|queries|parameters?|parameteri[sz]ed|escaped?|saniti[sz]ed?|input|shell|commands?|exec\w*|templates?|html|scripts?|inject\w*)\b/i, cwes: [74, 77, 78, 79, 80, 89, 90, 91, 94, 95, 611, 643, 917, 943, 1336], names: /sqli|sql|inject|cmdi|command|xss|script|template|rce|ssti|xxe/i },
|
|
12
|
+
{ id: 'credentials', label: 'a credentials weakness', about: 'how secrets and credentials are kept', words: /\b(secrets?|passwords?|tokens?|keys?|credentials?|api[- ]keys?)\b/i, cwes: [256, 259, 312, 321, 522, 532, 798], names: /secret|password|token|credential|hard-?coded|key/i },
|
|
13
|
+
{ id: 'crypto', label: 'a cryptography weakness', about: 'encryption, hashing or signing', words: /\b(encrypt\w*|hash\w*|tls|https|cipher|signatures?|signed|sign)\b/i, cwes: [319, 326, 327, 328, 330, 338, 347, 916], names: /crypt|hash|tls|cipher|signature|random/i },
|
|
14
|
+
{ id: 'session', label: 'a session weakness', about: 'sessions, cookies and sign-out', words: /\b(sessions?|cookies?|expire\w*|log ?out|sign ?out)\b/i, cwes: [384, 613, 614, 1004], names: /session|cookie|fixation/i },
|
|
15
|
+
{ id: 'files', label: 'a file-handling weakness', about: 'files, uploads and paths', words: /\b(files?|uploads?|paths?|downloads?)\b/i, cwes: [22, 23, 73, 434], names: /path|travers|upload|file/i },
|
|
16
|
+
{ id: 'logging', label: 'a logging weakness', about: 'what is logged or audited', words: /\b(logs?|logged|logging|audit\w*)\b/i, cwes: [117, 223, 532, 778], names: /log|audit/i },
|
|
17
|
+
{ id: 'rate', label: 'a rate-limiting weakness', about: 'limits on how often something is tried', words: /\b(rate|limits?|throttl\w*|brute\w*|attempts?)\b/i, cwes: [307, 770, 799], names: /brute|rate|throttl|dos\b|flood/i },
|
|
18
|
+
{ id: 'data', label: 'a data-exposure weakness', about: 'which data leaves the application', words: /\b(personal|pii|customer data|emails?|phone|exports?|leak\w*|disclos\w*|shared?|revenue)\b/i, cwes: [200, 201, 359, 538], names: /disclos|leak|exposure|pii|privacy/i },
|
|
19
|
+
{ id: 'redirect', label: 'an open-redirect weakness', about: 'where users are sent', words: /\bredirect\w*\b/i, cwes: [601], names: /redirect/i },
|
|
20
|
+
{ id: 'csrf', label: 'a cross-site request forgery weakness', about: 'requests made on a user\'s behalf', words: /\b(csrf|cross-site request|forged requests?)\b/i, cwes: [352], names: /csrf/i },
|
|
21
|
+
];
|
|
22
|
+
export const cweNumbers = (refs) => [...new Set((Array.isArray(refs) ? refs : [refs]).flatMap((r) => [...String(r ?? '').matchAll(/CWE-(\d{1,5})/gi)].map((m) => Number(m[1]))))].sort((a, b) => a - b);
|
|
23
|
+
/** The families a rule's words are about, with the word that showed each. */
|
|
24
|
+
export function ruleFamilies(text) {
|
|
25
|
+
return FAMILIES.flatMap((f) => {
|
|
26
|
+
// The telling word when there is one ("admins"), else the first the family knows ("only").
|
|
27
|
+
const m = f.strong?.exec(text) ?? f.words.exec(text);
|
|
28
|
+
return m ? [{ family: f, word: m[0] }] : [];
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
// @comment -- "Why a candidate bears on a family: its CWE is one the family lists (the strongest reason), or, when it carries no CWE at all, its threat or rule name says so. A candidate whose CWEs all lie outside the family is not matched by name: the CWE is what the person or the analyzer chose."
|
|
32
|
+
function candidateReason(c, f) {
|
|
33
|
+
const hit = c.cwes.find((n) => f.cwes.includes(n));
|
|
34
|
+
if (hit)
|
|
35
|
+
return `CWE-${hit} is ${f.label}`;
|
|
36
|
+
if (!c.cwes.length) {
|
|
37
|
+
const m = f.names.exec(c.names);
|
|
38
|
+
if (m) {
|
|
39
|
+
// The whole word the match sits in ("authorization", not "authoriz").
|
|
40
|
+
const start = c.names.slice(0, m.index).search(/[\w]*$/);
|
|
41
|
+
const word = (c.names.slice(start).match(/^[\w]+/) ?? [m[0]])[0];
|
|
42
|
+
return `its name ("${word}") is ${f.label}`;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
/** A stable key for one suggestion: the record and rule, where it came from, what it is and the file it is in. */
|
|
48
|
+
export const conflictKey = (record, rule, c) => createHash('sha256').update(JSON.stringify([record, rule, c.source, c.id, c.file])).digest('hex').slice(0, 12);
|
|
49
|
+
// @comment -- "The possible conflicts for each record: every candidate inside the record's paths (as the record's own globs say) whose weakness bears on a family one of the record's rules is about, once per rule, with the reason. A candidate on a rule's own threat is not a conflict, that is the rule's own place; guidance rules are matched too, since a person may still want to know. Dismissed ones are kept, marked, for the person to review."
|
|
50
|
+
export function findConflicts(records, candidates, opts) {
|
|
51
|
+
const dismissed = new Map((opts.dismissals ?? []).map((d) => [d.key, d]));
|
|
52
|
+
const out = [];
|
|
53
|
+
for (const rec of records) {
|
|
54
|
+
const mine = candidates.filter((c) => rec.paths.some((g) => opts.inPaths(g, c.file)));
|
|
55
|
+
if (!mine.length)
|
|
56
|
+
continue;
|
|
57
|
+
for (const rule of rec.rules) {
|
|
58
|
+
const own = opts.ruleThreat(rec.id, rule.id);
|
|
59
|
+
for (const { family, word } of ruleFamilies(rule.text)) {
|
|
60
|
+
for (const c of mine) {
|
|
61
|
+
if (own && c.threat === own)
|
|
62
|
+
continue;
|
|
63
|
+
const why = candidateReason(c, family);
|
|
64
|
+
if (!why)
|
|
65
|
+
continue;
|
|
66
|
+
const key = conflictKey(rec.id, rule.id, c);
|
|
67
|
+
if (out.some((x) => x.key === key))
|
|
68
|
+
continue;
|
|
69
|
+
const d = dismissed.get(key);
|
|
70
|
+
out.push({
|
|
71
|
+
key,
|
|
72
|
+
record: rec.id,
|
|
73
|
+
rule: rule.id,
|
|
74
|
+
ruleText: rule.text,
|
|
75
|
+
source: c.source,
|
|
76
|
+
what: c.title,
|
|
77
|
+
file: c.file,
|
|
78
|
+
line: c.line,
|
|
79
|
+
severity: c.severity,
|
|
80
|
+
family: family.id,
|
|
81
|
+
reason: `${why}, and ${rec.id} ${rule.id} is about ${family.about} ("${word}"); ${c.file} is in ${rec.id}'s paths.`,
|
|
82
|
+
dismissed: d ? { by: d.by, at: d.at, reason: d.reason } : null,
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const sev = (s) => ['critical', 'error', 'high', 'medium', 'warning', 'low'].indexOf(String(s ?? '').toLowerCase());
|
|
89
|
+
return out.sort((a, b) => a.record.localeCompare(b.record, undefined, { numeric: true }) || a.rule.localeCompare(b.rule, undefined, { numeric: true }) || (a.dismissed ? 1 : 0) - (b.dismissed ? 1 : 0) || sev(a.severity) - sev(b.severity) || a.file.localeCompare(b.file));
|
|
90
|
+
}
|
|
91
|
+
/** The dismissals people recorded; a missing file is none, a damaged one is said. */
|
|
92
|
+
export function readDismissals(root) {
|
|
93
|
+
const abs = join(root, DISMISSALS_FILE);
|
|
94
|
+
if (!existsSync(abs))
|
|
95
|
+
return [];
|
|
96
|
+
const j = JSON.parse(readFileSync(abs, 'utf8'));
|
|
97
|
+
if (j?.schema !== DISMISSALS_SCHEMA || !Array.isArray(j.dismissals))
|
|
98
|
+
throw new BravosError(`${DISMISSALS_FILE} is not a records dismissals file bravos wrote; fix or remove it`);
|
|
99
|
+
return j.dismissals.filter((d) => !!d && typeof d === 'object' && typeof d.key === 'string' && typeof d.by === 'string');
|
|
100
|
+
}
|
|
101
|
+
// @comment -- "Records one person's dismissal of one possible conflict: the key, the record and rule, what it was and where, the person's name, the day and their reason. Called only from an interactive terminal after the person typed their name (a person's decision, as adopting is); it writes nothing else, and never an @accepts: the exposure or finding stays exactly as it is."
|
|
102
|
+
// @mitigates #records against #forged-record using #person-only-adoption -- "A dismissal is recorded only for a name a person typed at an interactive terminal; the CLI refuses an agent's shell"
|
|
103
|
+
export function addDismissal(root, c, by, reason, now = new Date()) {
|
|
104
|
+
const list = readDismissals(root).filter((d) => d.key !== c.key);
|
|
105
|
+
const d = { key: c.key, record: c.record, rule: c.rule, what: c.what.slice(0, 200), where: `${c.file}${c.line ? `:${c.line}` : ''}`, by: by.slice(0, 80), at: now.toISOString().slice(0, 10), reason: reason.replace(/\s+/g, ' ').trim().slice(0, 400) };
|
|
106
|
+
writeFileSync(join(root, DISMISSALS_FILE), `${JSON.stringify({ schema: DISMISSALS_SCHEMA, dismissals: [...list, d] }, null, 2)}\n`);
|
|
107
|
+
return d;
|
|
108
|
+
}
|
|
109
|
+
/** The conflicts as terminal lines, grouped by record and rule. */
|
|
110
|
+
export function conflictLines(conflicts) {
|
|
111
|
+
if (!conflicts.length)
|
|
112
|
+
return ['records conflicts: none found: no open exposure or SAST finding in a record\'s paths bears on one of its rules.'];
|
|
113
|
+
const open = conflicts.filter((c) => !c.dismissed);
|
|
114
|
+
const lines = [`records conflicts: ${open.length} possible conflict${open.length === 1 ? '' : 's'}${conflicts.length > open.length ? ` (${conflicts.length - open.length} dismissed)` : ''}. Suggestions for a person: they change no rule's status and never hold a pull request.`];
|
|
115
|
+
let last = '';
|
|
116
|
+
for (const c of conflicts) {
|
|
117
|
+
const head = `${c.record} ${c.rule}`;
|
|
118
|
+
if (head !== last)
|
|
119
|
+
lines.push(`${head} "${c.ruleText}"`);
|
|
120
|
+
last = head;
|
|
121
|
+
lines.push(` ${c.dismissed ? 'dismissed ' : ''}[${c.key}] ${c.source === 'sast' ? 'SAST' : 'exposure'} ${c.what} at ${c.file}${c.line ? `:${c.line}` : ''}${c.severity ? ` (${c.severity})` : ''}`);
|
|
122
|
+
lines.push(` why: ${c.reason}`);
|
|
123
|
+
if (c.dismissed)
|
|
124
|
+
lines.push(` dismissed by ${c.dismissed.by} on ${c.dismissed.at}: ${c.dismissed.reason}`);
|
|
125
|
+
}
|
|
126
|
+
lines.push('Link one to its rule: ask your agent to "link records conflict <key>" (bravos-annotate records it as an exposure of the rule\'s threat). Not a conflict: bravos records conflicts dismiss <key> --reason "<why>", at your own terminal.');
|
|
127
|
+
return lines;
|
|
128
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { dirname, isAbsolute, join, resolve } from 'node:path';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import { hooksDir } from './paths.js';
|
|
6
|
+
import { BravosError } from './types.js';
|
|
7
|
+
const lib = (name) => import(pathToFileURL(join(hooksDir(), 'lib', name)).href);
|
|
8
|
+
const git = (root, args, env = process.env) => execFileSync('git', args, { cwd: root, env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 30000 }).trim();
|
|
9
|
+
// @comment -- "The open pull requests whose head is a draft branch, asked of GitHub with gh as the person when gh is there and signed in; null when it cannot say, so the branches alone decide. Read-only."
|
|
10
|
+
// @flows #records -> GitHub.API via gh -- "bravos records drafts lists open pull requests (head branch names only) to keep one draft per module"
|
|
11
|
+
export function openDraftPrs(root, env = process.env) {
|
|
12
|
+
try {
|
|
13
|
+
const out = execFileSync('gh', ['pr', 'list', '--state', 'open', '--limit', '200', '--json', 'headRefName,number,url'], { cwd: root, env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 15000 });
|
|
14
|
+
const j = JSON.parse(out);
|
|
15
|
+
return Array.isArray(j) ? j.filter((p) => typeof p?.headRefName === 'string' && p.headRefName.startsWith('bravos/record-')) : null;
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
const RULES = [
|
|
22
|
+
'How to draft (bravos-records): state only what a stored document, a confirmed intent rule or a person said, and cite it on the line: (SRC-n § Section), (intent: INV-n), (said by <name>).',
|
|
23
|
+
' What the code does today is (observed: <file>:<line>): not a decision, so it is guidance until the team confirms it.',
|
|
24
|
+
' Leave "Not a bug" empty unless a document, a confirmed rule or the person says it; never fill it from the code. Leave the decision as the team\'s placeholder when nobody stated one.',
|
|
25
|
+
' Then bravos records check -C <worktree> until it passes, commit in the worktree, and tell the person. Push and open the pull request only after they say yes.',
|
|
26
|
+
];
|
|
27
|
+
/** `bravos records drafts [--limit n] [--json]`: what to draft now. */
|
|
28
|
+
export async function draftsList(root, env, limit) {
|
|
29
|
+
const D = await lib('drafts.mjs');
|
|
30
|
+
const prs = openDraftPrs(root, env);
|
|
31
|
+
const q = D.draftQueue(root, { limit, openPrs: prs ?? [] });
|
|
32
|
+
const json = { schema: 'bravos.records-drafts/v1', ...q, github: prs === null ? 'did not answer (gh missing, signed out, or not a GitHub repository): draft branches decide' : 'asked', briefs: q.queue.map((m) => D.draftBrief(root, m)) };
|
|
33
|
+
if (q.state === 'no-ledger')
|
|
34
|
+
return { json, lines: ['records drafts: no module ledger yet. Map the modules first (bravos records ledger propose); drafting works from a ledger a person reviewed.'] };
|
|
35
|
+
if (q.state === 'unreviewed')
|
|
36
|
+
return { json, lines: [`records drafts: the module ledger is ${q.review?.words ?? 'not reviewed'}. Drafting waits until a person has reviewed it in its pull request, so no draft is written for a boundary nobody agreed.`] };
|
|
37
|
+
const lines = [];
|
|
38
|
+
if (q.open.length)
|
|
39
|
+
lines.push(`Waiting for review (one draft per module, never two): ${q.open.map((o) => `${o.name} on ${o.branch}${o.pr ? ' (pull request open)' : ''}`).join('; ')}`);
|
|
40
|
+
if (q.state === 'none') {
|
|
41
|
+
lines.unshift(`records drafts: nothing to draft now: every module the ledger says needs a record has one${q.open.length ? ' or a draft waiting' : ''}.`);
|
|
42
|
+
return { json, lines };
|
|
43
|
+
}
|
|
44
|
+
if (!q.queue.length) {
|
|
45
|
+
lines.unshift(`records drafts: ${q.waiting.length} module${q.waiting.length === 1 ? '' : 's'} need${q.waiting.length === 1 ? 's' : ''} a record, but ${q.open.length} draft${q.open.length === 1 ? '' : 's'} already wait for review (at most ${q.maxOpen} at once). Draft more once those are reviewed.`);
|
|
46
|
+
return { json, lines };
|
|
47
|
+
}
|
|
48
|
+
lines.unshift(`records drafts: draft ${q.queue.length} now (at most ${q.limit} per run, ${q.maxOpen} waiting at once)${q.waiting.length ? `; ${q.waiting.length} more after these: ${q.waiting.map((m) => m.name).join(', ')}` : ''}${prs === null ? '. GitHub did not answer (gh missing, signed out, or not a GitHub repository), so draft branches alone show what waits.' : '.'}`);
|
|
49
|
+
for (const b of json.briefs) {
|
|
50
|
+
lines.push(` ${b.name} (${b.paths.join(', ')}): bravos records draft "${b.name}" → branch ${b.branch}`, ` code: ${b.files.slice(0, 12).join(', ') || 'no files yet'}${b.files.length + b.moreFiles > 12 ? ` and ${b.files.length + b.moreFiles - 12} more` : ''}`, ` cite from the documents: ${b.documents.length ? b.documents.join('; ') : 'no stored document names this module (bravos context list)'}`, ` confirmed intent rules: ${b.intent.length ? b.intent.map((i) => i.id).join(', ') : 'none confirmed yet'}`, ` the ledger says: ${b.why}`);
|
|
51
|
+
}
|
|
52
|
+
lines.push(...RULES);
|
|
53
|
+
return { json, lines };
|
|
54
|
+
}
|
|
55
|
+
/** `bravos records draft "<module>" [--worktree <dir>]`: a branch, a worktree and a skeleton for one module. */
|
|
56
|
+
export async function draftStart(root, module, env, opts = {}) {
|
|
57
|
+
const D = await lib('drafts.mjs');
|
|
58
|
+
const Lg = await lib('ledger.mjs');
|
|
59
|
+
const l = Lg.readLedger(root);
|
|
60
|
+
const want = module.trim().toLowerCase();
|
|
61
|
+
const m = l.modules.find((x) => x.name.toLowerCase() === want || x.key === want);
|
|
62
|
+
if (!l.exists || !m)
|
|
63
|
+
throw new BravosError(`no module "${module}" in the ledger (bravos records ledger)`);
|
|
64
|
+
if (m.needs !== 'yes' || m.records.length)
|
|
65
|
+
throw new BravosError(`${m.name} ${m.records.length ? 'already has a record' : 'is optional in the ledger'}; drafting is for modules that need a record and have none`);
|
|
66
|
+
const prs = openDraftPrs(root, env);
|
|
67
|
+
const q = D.draftQueue(root, { limit: 1000, openPrs: prs ?? [] });
|
|
68
|
+
if (q.state === 'unreviewed')
|
|
69
|
+
throw new BravosError(`the module ledger is ${q.review?.words ?? 'not reviewed'}; drafting waits until a person has reviewed it`);
|
|
70
|
+
const mine = q.open.find((o) => o.key === m.key);
|
|
71
|
+
// @comment -- "One draft per module: a module with a draft branch or an open draft pull request is never drafted again, and no new draft starts while the most allowed already wait for review"
|
|
72
|
+
if (mine)
|
|
73
|
+
throw new BravosError(`${m.name} already has a draft waiting (${mine.branch}${mine.pr ? ', pull request open' : ''}); there is never more than one per module`);
|
|
74
|
+
if (q.open.length >= D.MAX_OPEN)
|
|
75
|
+
throw new BravosError(`${q.open.length} drafts already wait for review (at most ${D.MAX_OPEN} at once): ${q.open.map((o) => o.name).join(', ')}. Draft more once those are reviewed.`);
|
|
76
|
+
const branch = D.draftBranch(m.key);
|
|
77
|
+
const common = git(root, ['rev-parse', '--path-format=absolute', '--git-common-dir'], env);
|
|
78
|
+
const dir = opts.worktree ? (isAbsolute(opts.worktree) ? opts.worktree : resolve(root, opts.worktree)) : join(common, 'bravos', 'drafts', m.key);
|
|
79
|
+
if (existsSync(dir))
|
|
80
|
+
throw new BravosError(`${dir} already exists; remove it (git worktree remove) or pass --worktree <another dir>`);
|
|
81
|
+
let base = 'HEAD';
|
|
82
|
+
try {
|
|
83
|
+
base = git(root, ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'], env);
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
/* no default branch known: draft from this commit */
|
|
87
|
+
}
|
|
88
|
+
const id = D.nextDraftId(root);
|
|
89
|
+
mkdirSync(dirname(dir), { recursive: true });
|
|
90
|
+
git(root, ['worktree', 'add', '-q', '-b', branch, dir, base], env);
|
|
91
|
+
const rel = `.guardlink/records/${id}-${m.key}.md`;
|
|
92
|
+
const today = (opts.now ?? new Date()).toISOString().slice(0, 10);
|
|
93
|
+
mkdirSync(join(dir, '.guardlink', 'records'), { recursive: true });
|
|
94
|
+
writeFileSync(join(dir, rel), D.draftSkeleton(id, m.name, m.paths, today));
|
|
95
|
+
const brief = D.draftBrief(root, m);
|
|
96
|
+
return [
|
|
97
|
+
`Started ${id} for ${m.name}: ${join(dir, rel)}`,
|
|
98
|
+
` branch ${branch} off ${base}, in its own worktree (${dir}); this checkout and its branch are untouched.`,
|
|
99
|
+
` code: ${brief.files.slice(0, 12).join(', ')}${brief.files.length > 12 ? ', …' : ''}`,
|
|
100
|
+
` cite from the documents: ${brief.documents.length ? brief.documents.join('; ') : 'no stored document names this module'}`,
|
|
101
|
+
` confirmed intent rules: ${brief.intent.length ? brief.intent.map((i) => `${i.id} ${i.text}`).join('; ') : 'none confirmed yet'}`,
|
|
102
|
+
...RULES.map((r) => r.replace('<worktree>', dir)),
|
|
103
|
+
` Before committing, run bravos records ledger refresh -C ${dir} so the ledger's Record column says ${id} draft.`,
|
|
104
|
+
` On the person's yes: git -C ${dir} push -u origin ${branch}, then gh pr create --head ${branch} --title "${id}: security decision record for ${m.name} (draft for review)". It binds nobody until a code owner approves the pull request.`,
|
|
105
|
+
];
|
|
106
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
import { pathToFileURL } from 'node:url';
|
|
4
|
+
import { BravosError } from './types.js';
|
|
5
|
+
import { hooksDir } from './paths.js';
|
|
6
|
+
let cached;
|
|
7
|
+
const lib = () => (cached ??= import(pathToFileURL(join(hooksDir(), 'lib', 'ledger.mjs')).href));
|
|
8
|
+
const GRAPH_NOTE = [
|
|
9
|
+
'Code graph: this command reads the stored documents, the threat model and the folders, not the routes.',
|
|
10
|
+
' With the code graph (Team plan), ask codegraph_routes, codegraph_auth_boundary and codegraph_attack_surface in the session and adjust the modules: merge folders that serve one feature, split one that holds two, and add the routes each module answers to its evidence.',
|
|
11
|
+
' Without it (Free), modules come from folder names and what the documents and annotations say. A feature spread over folders with different names can show as two modules, and code with no annotations yet can be marked optional when it is not: review each boundary before a person does.',
|
|
12
|
+
];
|
|
13
|
+
function write(root, file, text) {
|
|
14
|
+
const abs = join(root, file);
|
|
15
|
+
mkdirSync(dirname(abs), { recursive: true });
|
|
16
|
+
writeFileSync(abs, text);
|
|
17
|
+
}
|
|
18
|
+
const row = (m) => ` ${m.name} ${m.needs === 'yes' ? 'needs a record' : 'optional'} ${m.status ?? m.record ?? ''} (${m.paths.join(', ')})${m.owner && m.owner !== '—' ? ` owner ${m.owner}` : ''}`;
|
|
19
|
+
/** `bravos records ledger` (list). */
|
|
20
|
+
export async function ledgerList(root) {
|
|
21
|
+
const L = await lib();
|
|
22
|
+
const l = L.readLedger(root);
|
|
23
|
+
if (!l.exists)
|
|
24
|
+
return { lines: [`records ledger: no ${L.LEDGER_FILE} yet. bravos records ledger propose shows a first pass at the modules; --write adds them for review.`], json: { schema: 'bravos.records-ledger/v1', exists: false } };
|
|
25
|
+
const needs = l.modules.filter((m) => m.needs === 'yes');
|
|
26
|
+
return {
|
|
27
|
+
json: { schema: 'bravos.records-ledger/v1', exists: true, review: l.review, problems: l.problems, modules: l.modules },
|
|
28
|
+
lines: [
|
|
29
|
+
`records ledger: ${l.modules.length} module${l.modules.length === 1 ? '' : 's'}, ${l.modules.filter((m) => m.records?.length).length} with records, ${needs.length} need${needs.length === 1 ? 's' : ''} one — ${l.review?.words ?? 'not reviewed'}`,
|
|
30
|
+
...l.modules.map(row),
|
|
31
|
+
...l.problems.map((p) => `✗ ${p}`),
|
|
32
|
+
'Proposed and reviewed by people, never enforced: the ledger holds no pull request.',
|
|
33
|
+
],
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
/** `bravos records ledger propose [--write]`. */
|
|
37
|
+
export async function ledgerPropose(root, writeIt) {
|
|
38
|
+
const L = await lib();
|
|
39
|
+
const p = L.proposeModules(root);
|
|
40
|
+
const lines = [`records ledger propose: ${p.modules.length} candidate module${p.modules.length === 1 ? '' : 's'} from ${p.files} files (features, not one per folder):`];
|
|
41
|
+
for (const m of p.modules)
|
|
42
|
+
lines.push(` ${m.name} ${m.needs === 'yes' ? 'needs a record' : 'optional'} (${m.paths.join(', ')})`, ` why: ${m.why}`, ` evidence: ${m.evidence}`);
|
|
43
|
+
if (p.documentedOnly.length)
|
|
44
|
+
lines.push(`Sections of the stored documents that match no code (a feature not built yet, or named differently in the code; say which): ${p.documentedOnly.map((d) => `${d.id} § ${d.heading}`).join('; ')}`);
|
|
45
|
+
lines.push(...GRAPH_NOTE);
|
|
46
|
+
if (!writeIt) {
|
|
47
|
+
lines.push('Nothing written. Review the list, then run this again with --write; adjust rows with bravos records ledger add / remove.');
|
|
48
|
+
return lines;
|
|
49
|
+
}
|
|
50
|
+
const abs = join(root, L.LEDGER_FILE);
|
|
51
|
+
const before = existsSync(abs) ? readFileSync(abs, 'utf8') : null;
|
|
52
|
+
const merged = L.mergeProposal(before, p.modules);
|
|
53
|
+
write(root, L.LEDGER_FILE, merged.text);
|
|
54
|
+
const r = L.refreshLedger(root);
|
|
55
|
+
if (r)
|
|
56
|
+
write(root, L.LEDGER_FILE, r.text);
|
|
57
|
+
lines.push(before === null ? `Wrote ${L.LEDGER_FILE} with ${merged.added.length} modules.` : `Added ${merged.added.length} module${merged.added.length === 1 ? '' : 's'} to ${L.LEDGER_FILE}; the team's rows are as they were.`, 'It is a proposal: tell the person, and have them review it in a pull request (the same review as a record). Rewrite the Why of each row in their words when they correct it.');
|
|
58
|
+
return lines;
|
|
59
|
+
}
|
|
60
|
+
/** `bravos records ledger add "<Module>" --paths … --needs yes|optional [--why …] [--evidence …]`: adds the row, or replaces the one with that name. */
|
|
61
|
+
export async function ledgerAdd(root, name, o) {
|
|
62
|
+
const L = await lib();
|
|
63
|
+
const paths = (o.paths ?? '').split(',').map((s) => s.trim()).filter(Boolean);
|
|
64
|
+
if (!name || !paths.length || !['yes', 'optional'].includes(o.needs ?? ''))
|
|
65
|
+
throw new BravosError('usage: bravos records ledger add "<module>" --paths "<glob>,<glob>" --needs yes|optional [--why "<what it decides>"] [--evidence "<SRC-n § section; routes>"]');
|
|
66
|
+
const abs = join(root, L.LEDGER_FILE);
|
|
67
|
+
const parsed = L.parseLedger(existsSync(abs) ? readFileSync(abs, 'utf8') : '');
|
|
68
|
+
const probe = L.parseLedger(L.renderLedger([{ name, key: '', paths, needs: o.needs, why: o.why ?? '', owner: '', record: '', evidence: o.evidence ?? '' }]));
|
|
69
|
+
if (probe.problems.length || !probe.modules.length)
|
|
70
|
+
throw new BravosError(probe.problems[0] ?? 'that module does not make a ledger row');
|
|
71
|
+
const m = probe.modules[0];
|
|
72
|
+
const i = parsed.modules.findIndex((x) => x.key === m.key);
|
|
73
|
+
const next = i >= 0 ? parsed.modules.map((x, j) => (j === i ? { ...m, owner: x.owner } : x)) : [...parsed.modules, m];
|
|
74
|
+
write(root, L.LEDGER_FILE, L.renderLedger(next));
|
|
75
|
+
const r = L.refreshLedger(root);
|
|
76
|
+
if (r)
|
|
77
|
+
write(root, L.LEDGER_FILE, r.text);
|
|
78
|
+
return [`${i >= 0 ? 'Updated' : 'Added'} ${m.name} in ${L.LEDGER_FILE}. A person reviews the change in its pull request.`];
|
|
79
|
+
}
|
|
80
|
+
/** `bravos records ledger remove "<Module>"`. */
|
|
81
|
+
export async function ledgerRemove(root, name) {
|
|
82
|
+
const L = await lib();
|
|
83
|
+
const abs = join(root, L.LEDGER_FILE);
|
|
84
|
+
if (!existsSync(abs))
|
|
85
|
+
throw new BravosError(`no ${L.LEDGER_FILE} here`);
|
|
86
|
+
const parsed = L.parseLedger(readFileSync(abs, 'utf8'));
|
|
87
|
+
const key = L.parseLedger(L.renderLedger([{ name, key: '', paths: ['x/**'], needs: 'optional', why: '', owner: '', record: '', evidence: '' }])).modules[0]?.key;
|
|
88
|
+
const next = parsed.modules.filter((m) => m.key !== key);
|
|
89
|
+
if (next.length === parsed.modules.length)
|
|
90
|
+
throw new BravosError(`no module named "${name}" in ${L.LEDGER_FILE}`);
|
|
91
|
+
write(root, L.LEDGER_FILE, L.renderLedger(next));
|
|
92
|
+
return [`Removed ${name} from ${L.LEDGER_FILE}.`];
|
|
93
|
+
}
|
|
94
|
+
/** `bravos records ledger refresh`: the Record and Owner columns, from the records and CODEOWNERS. */
|
|
95
|
+
export async function ledgerRefresh(root) {
|
|
96
|
+
const L = await lib();
|
|
97
|
+
const r = L.refreshLedger(root);
|
|
98
|
+
if (!r)
|
|
99
|
+
return [`records ledger: no ${L.LEDGER_FILE} yet (bravos records ledger propose)`];
|
|
100
|
+
if (r.changed)
|
|
101
|
+
write(root, L.LEDGER_FILE, r.text);
|
|
102
|
+
return [r.changed ? `Refreshed ${L.LEDGER_FILE}: the Record and Owner columns now match the records and CODEOWNERS.` : `${L.LEDGER_FILE} is current.`, ...r.problems.map((p) => `✗ ${p}`)];
|
|
103
|
+
}
|