@bugb-technologies/bravos 1.12.1 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ // @comment -- "Threat cards: right after an edit, a new critical or high @exposes claim that no test has confirmed or refuted is shown to the developer as a card in their terminal (the hook's systemMessage), and the agent is told to raise it and recommend confirming it. Only lines that are not in the last commit count, so existing claims never raise a card; each threat raises one card per clone (recorded under the git directory). Reads files, git's HEAD copy and the local ledger; never runs guardlink, never runs a test and never contacts the network. Dependency-free."
2
+ import { spawnSync } from 'node:child_process';
3
+ import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
4
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path';
5
+ import { readProving } from './proving.mjs';
6
+
7
+ export const CARDS_SCHEMA = 'bravos.cards/v1';
8
+ const SEVERITY = { critical: 'critical', p0: 'critical', high: 'high', p1: 'high' };
9
+ const MAX_FILES = 40;
10
+ const MAX_BYTES = 2 * 1024 * 1024;
11
+ const MAX_SEEN = 4000;
12
+
13
+ // An exposes line: the asset, "to", the threat, a severity in brackets, optional refs, then the quoted description.
14
+ const EXPOSES = /@exposes\s+(\S+)\s+to\s+(#[\w.-]+)\s*\[(critical|high|p0|p1)\]([^"\n]*?)(?:--\s*"((?:[^"\\]|\\.)*)"|\s*(?:\*\/)?\s*$)/i;
15
+
16
+ export const cardsFile = (commonDir) => join(commonDir, 'bravos', 'cards.json');
17
+
18
+ // @comment -- "The repository files an edit touched: file_path or notebook_path in the tool input, and every path an apply_patch text names (*** Add File / *** Update File / *** Move to). Paths outside the repository are dropped, so a payload cannot point the hook at other files."
19
+ // @mitigates #threat-cards against #out-of-repo-read using #repo-bound-paths -- "touchedFiles() keeps only paths that resolve inside the repository root and outside .git, so a crafted tool payload cannot make the hook read other files"
20
+ export function touchedFiles(root, toolInput) {
21
+ const out = new Set();
22
+ const add = (p) => {
23
+ if (typeof p !== 'string' || !p.trim()) return;
24
+ const abs = isAbsolute(p) ? resolve(p) : resolve(root, p.trim());
25
+ const rel = relative(root, abs);
26
+ if (!rel || rel.startsWith('..') || isAbsolute(rel) || rel.split(sep).includes('.git')) return;
27
+ out.add(rel.split(sep).join('/'));
28
+ };
29
+ const input = toolInput && typeof toolInput === 'object' ? toolInput : {};
30
+ add(input.file_path);
31
+ add(input.notebook_path);
32
+ for (const v of Object.values(input)) {
33
+ if (typeof v !== 'string') continue;
34
+ for (const m of v.matchAll(/^\*\*\* (?:Add File|Update File|Move to): (.+)$/gm)) add(m[1]);
35
+ }
36
+ return [...out].slice(0, MAX_FILES);
37
+ }
38
+
39
+ // @comment -- "The files changed in the working tree against HEAD (tracked and untracked), for a harness whose edit tool does not name its files. Bounded and read-only."
40
+ export function changedFiles(root) {
41
+ const r = spawnSync('git', ['status', '--porcelain', '-z', '--untracked-files=all'], { cwd: root, encoding: 'utf8', timeout: 3000, stdio: ['ignore', 'pipe', 'ignore'] });
42
+ if (r.status !== 0) return [];
43
+ return r.stdout.split('\0').filter(Boolean).map((l) => l.slice(3)).filter((p) => p && !p.startsWith('.git/')).slice(0, MAX_FILES);
44
+ }
45
+
46
+ /** A sidecar under .guardlink/annotations/<source>.gal describes <source>. */
47
+ export const logicalFile = (rel) => (rel.startsWith('.guardlink/annotations/') && rel.endsWith('.gal') ? rel.slice('.guardlink/annotations/'.length, -'.gal'.length) : rel);
48
+
49
+ function headLines(root, rel) {
50
+ const r = spawnSync('git', ['show', `HEAD:${rel}`], { cwd: root, encoding: 'utf8', timeout: 3000, maxBuffer: MAX_BYTES, stdio: ['ignore', 'pipe', 'ignore'] });
51
+ return r.status === 0 ? new Set(r.stdout.split('\n').map((l) => l.trim())) : new Set();
52
+ }
53
+
54
+ // @comment -- "The critical and high exposures in the given files whose line is not in the file's last commit: what this work added. Each gives the asset, threat, severity, any cwe reference, the description, the logical file (a sidecar's source) and the line."
55
+ export function newExposures(root, files) {
56
+ const out = [];
57
+ for (const rel of files) {
58
+ const abs = join(root, rel);
59
+ let text;
60
+ try {
61
+ if (!statSync(abs).isFile() || statSync(abs).size > MAX_BYTES) continue;
62
+ text = readFileSync(abs, 'utf8');
63
+ } catch {
64
+ continue;
65
+ }
66
+ if (!/@exposes/i.test(text)) continue;
67
+ const before = headLines(root, rel);
68
+ text.split('\n').forEach((line, n) => {
69
+ const m = EXPOSES.exec(line);
70
+ if (!m || before.has(line.trim())) return;
71
+ const cwe = /\bcwe:(CWE-\d+)/i.exec(m[4] ?? '')?.[1] ?? null;
72
+ out.push({ asset: m[1], threat: m[2], severity: SEVERITY[m[3].toLowerCase()], cwe, description: (m[5] ?? '').replace(/\\"/g, '"').slice(0, 400), file: logicalFile(rel), line: rel === logicalFile(rel) ? n + 1 : null, written: rel });
73
+ });
74
+ }
75
+ return out;
76
+ }
77
+
78
+ // @comment -- "Whether the local ledger already has a confirmed or refuted outcome for this claim: an entry for the same logical file whose claim names both the threat and the asset. A missing or damaged ledger means untested."
79
+ export function tested(root, x) {
80
+ let ledger;
81
+ try {
82
+ ledger = JSON.parse(readFileSync(join(root, '.guardlink', 'hypotheses.json'), 'utf8'));
83
+ } catch {
84
+ return false;
85
+ }
86
+ const entries = Array.isArray(ledger?.entries) ? ledger.entries : [];
87
+ return entries.some((e) => e && e.file === x.file && typeof e.claim === 'string' && e.claim.includes(x.threat) && e.claim.includes(x.asset) && (e.outcome === 'confirmed' || e.outcome === 'refuted'));
88
+ }
89
+
90
+ export const cardKey = (x) => `${x.file}|${x.asset}|${x.threat}|${x.severity}`;
91
+
92
+ export function readSeen(commonDir) {
93
+ try {
94
+ const d = JSON.parse(readFileSync(cardsFile(commonDir), 'utf8'));
95
+ return d?.schema === CARDS_SCHEMA && d.seen && typeof d.seen === 'object' ? d.seen : {};
96
+ } catch {
97
+ return {};
98
+ }
99
+ }
100
+
101
+ export function writeSeen(commonDir, seen) {
102
+ try {
103
+ const file = cardsFile(commonDir);
104
+ mkdirSync(join(file, '..'), { recursive: true, mode: 0o700 });
105
+ const keys = Object.keys(seen).sort((a, b) => String(seen[a]).localeCompare(String(seen[b]))).slice(-MAX_SEEN);
106
+ const tmp = `${file}.tmp-${process.pid}`;
107
+ writeFileSync(tmp, JSON.stringify({ schema: CARDS_SCHEMA, seen: Object.fromEntries(keys.map((k) => [k, seen[k]])) }) + '\n', { mode: 0o600 });
108
+ renameSync(tmp, file);
109
+ } catch {
110
+ /* best effort: at worst a card shows again */
111
+ }
112
+ }
113
+
114
+ // Only printable text from an annotation reaches the terminal or the agent.
115
+ const clean = (s, max) => String(s ?? '').replace(/[\u0000-\u001F\u007F-\u009F​-‏‪-‮⁠-⁤⁦-⁩]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, max);
116
+
117
+ function wrap(text, width) {
118
+ const out = [];
119
+ let line = '';
120
+ for (const word of text.split(' ')) {
121
+ if (!word) continue;
122
+ if ((line + ' ' + word).trim().length > width) {
123
+ if (line) out.push(line);
124
+ line = word.length > width ? word.slice(0, width) : word;
125
+ } else line = (line + ' ' + word).trim();
126
+ }
127
+ if (line) out.push(line);
128
+ return out;
129
+ }
130
+
131
+ // @comment -- "One card as plain text in a box, for the developer's terminal: severity, the description, the claim and where it is, the state, and one next step (bravos-prove when a test target is recorded, else bravos-env first). Annotation text is cleaned of control and invisible characters first."
132
+ // @exposes #threat-cards to #terminal-escape-injection [low] cwe:CWE-150 -- "renderCard() and agentLine() draw the description, threat and asset ids that newExposures() read from a file's @exposes line, text anyone who can edit the repository controls, into the developer's terminal and the agent's context"
133
+ // @mitigates #threat-cards against #terminal-escape-injection using #printable-text-only -- "clean() removes control, bidirectional and invisible characters and caps the length before any annotation text is drawn"
134
+ export function renderCard(x, { target = false, harness = 'claude', width = 58 } = {}) {
135
+ const k = (n) => (harness === 'claude' ? `/${n}` : n);
136
+ const sev = x.severity === 'critical' ? 'CRITICAL' : 'HIGH';
137
+ const where = `${clean(x.file, 120)}${x.line ? `:${x.line}` : ''}`;
138
+ const body = [
139
+ `${sev} · new threat, not confirmed yet`,
140
+ '',
141
+ ...wrap(clean(x.description, 400) || `${clean(x.threat, 60)} on ${clean(x.asset, 60)}`, width),
142
+ `${clean(x.threat, 60)} on ${clean(x.asset, 60)}${x.cwe ? ` · cwe:${x.cwe}` : ''}`,
143
+ ...wrap(where, width),
144
+ '',
145
+ 'state untested · found in this session',
146
+ target ? `next ${k('bravos-prove')} to confirm it on the recorded target` : `next ${k('bravos-env')} to set up a test target, then ${k('bravos-prove')}`,
147
+ ];
148
+ const w = Math.max(...body.map((l) => l.length));
149
+ return ['╭' + '─'.repeat(w + 2) + '╮', ...body.map((l) => `│ ${l.padEnd(w)} │`), '╰' + '─'.repeat(w + 2) + '╯'].join('\n');
150
+ }
151
+
152
+ // @comment -- "What the agent is told for the new cards: raise each in this reply, in plain words, and recommend confirming it now; never confirm, refute or accept it itself."
153
+ export function agentLine(cards, { target = false, harness = 'claude' } = {}) {
154
+ if (!cards.length) return '';
155
+ const k = (n) => (harness === 'claude' ? `/${n}` : n);
156
+ const list = cards.map((x) => `${x.severity} ${clean(x.threat, 60)} on ${clean(x.asset, 60)} (${clean(x.file, 120)}${x.line ? `:${x.line}` : ''})`).join('; ');
157
+ const how = target ? `${k('bravos-prove')} on the recorded target` : `${k('bravos-env')} to set up a target (the person types their own authorization), then ${k('bravos-prove')}`;
158
+ return `Bravos threat card${cards.length === 1 ? '' : 's'} shown to the person: ${list}. In this reply, say in plain words what ${cards.length === 1 ? 'it is' : 'they are'} and recommend confirming ${cards.length === 1 ? 'it' : 'them'} now with ${how}. Only a real test confirms or refutes a threat, and only a named person accepts one: never write @confirmed or @accepts.`;
159
+ }
160
+
161
+ // @comment -- "The whole decision for one edit: the files it touched (or, when the payload names none and the tool can write files, the working tree's changed files), their new critical and high exposures, minus those already tested and those already carded in this clone. Returns the cards to show and the updated seen record."
162
+ export function decideCards({ root, toolName = '', toolInput = {}, seen = {}, now = new Date() }) {
163
+ let files = touchedFiles(root, toolInput);
164
+ if (!files.length && /patch|shell|bash|exec|write|edit/i.test(String(toolName))) files = changedFiles(root);
165
+ if (!files.length) return { cards: [], seen };
166
+ const next = { ...seen };
167
+ const cards = [];
168
+ for (const x of newExposures(root, files)) {
169
+ const key = cardKey(x);
170
+ if (next[key] || tested(root, x)) continue;
171
+ next[key] = now.toISOString();
172
+ cards.push(x);
173
+ }
174
+ return { cards, seen: next };
175
+ }
176
+
177
+ // @comment -- "An opt-in desktop notification (bravos prefs set notify on): macOS through osascript and Linux through notify-send, with the text passed as arguments to a fixed script, never spliced into it, and nothing waited on."
178
+ // @mitigates #threat-cards against #notification-script-injection using #argv-only -- "notify() passes the title and text as osascript and notify-send arguments to a fixed program, so annotation text is never parsed as AppleScript or options"
179
+ export function notify(card, repo) {
180
+ const title = `${card.severity === 'critical' ? 'Critical' : 'High'} threat found · ${clean(repo, 40)}`;
181
+ const text = `${clean(card.file, 80)}${card.line ? `:${card.line}` : ''} · ${clean(card.description, 140) || clean(card.threat, 60)}. Not confirmed yet.`;
182
+ try {
183
+ if (process.platform === 'darwin') {
184
+ spawnSync('osascript', ['-e', 'on run argv', '-e', 'display notification (item 2 of argv) with title (item 1 of argv)', '-e', 'end run', title, text], { timeout: 3000, stdio: 'ignore' });
185
+ } else if (process.platform === 'linux') {
186
+ spawnSync('notify-send', ['--', title, text], { timeout: 3000, stdio: 'ignore' });
187
+ }
188
+ } catch {
189
+ /* a notification is a convenience */
190
+ }
191
+ }
192
+
193
+ /** Whether a test target is recorded in the person's proving answer (.guardlink/proving.md), for the next-step wording. */
194
+ export function targetRecorded(root) {
195
+ try {
196
+ const p = readProving(root);
197
+ return p?.status === 'set' && !!p.target;
198
+ } catch {
199
+ return false;
200
+ }
201
+ }
@@ -1,4 +1,4 @@
1
- // @comment -- "A person's standing answers to questions Bravos would otherwise ask every session, kept per clone and never committed. Two today: what to do with Bravos's own files (annotations, intent, definitions, tests, the ledger) once they are written: commit them, leave them for the person, or keep asking; whether the agent starts one background annotation pass each session while coverage is incomplete (background, the default) or not (off); and whether the coach adds reminders before prompts (on, the default) or not (off). The file lives under the git directory (<git-common-dir>/bravos/prefs.json), which no commit, clone or pull can write, so a repository cannot ship an answer and grant itself silent commits, and every worktree of a clone shares it. Dependency-free: the session hook reads it, the CLI writes it."
1
+ // @comment -- "A person's standing answers to questions Bravos would otherwise ask every session, kept per clone and never committed. Two today: what to do with Bravos's own files (annotations, intent, definitions, tests, the ledger) once they are written: commit them, leave them for the person, or keep asking; whether the agent starts one background annotation pass each session while coverage is incomplete (background, the default) or not (off); whether the coach adds reminders before prompts (on, the default) or not (off); and whether threat cards show (on, the default) and send a desktop notification (off by default). The file lives under the git directory (<git-common-dir>/bravos/prefs.json), which no commit, clone or pull can write, so a repository cannot ship an answer and grant itself silent commits, and every worktree of a clone shares it. Dependency-free: the session hook reads it, the CLI writes it."
2
2
  import { spawnSync } from 'node:child_process';
3
3
  import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
4
4
  import { isAbsolute, join, resolve } from 'node:path';
@@ -11,7 +11,10 @@ export const ANNOTATE_CHOICES = ['background', 'off'];
11
11
  /** on: the coach adds a reminder before a prompt when one is due (the default when nothing is recorded). off: none. */
12
12
  export const COACH_CHOICES = ['on', 'off'];
13
13
  /** Each recorded answer and the choices it may hold. */
14
- export const PREF_CHOICES = { commits: COMMIT_CHOICES, annotate: ANNOTATE_CHOICES, coach: COACH_CHOICES };
14
+ /** cards: on shows a threat card after an edit adds an untested critical or high exposure (the default); off shows none. notify: on also sends a desktop notification for it (off by default). */
15
+ export const CARDS_CHOICES = ['on', 'off'];
16
+ export const NOTIFY_CHOICES = ['off', 'on'];
17
+ export const PREF_CHOICES = { commits: COMMIT_CHOICES, annotate: ANNOTATE_CHOICES, coach: COACH_CHOICES, cards: CARDS_CHOICES, notify: NOTIFY_CHOICES };
15
18
 
16
19
  // One line of visible text: a name goes into the briefing, so control and invisible characters never do.
17
20
  const clean = (v, max) => String(v ?? '').replace(/[\u0000-\u001F\u007F-\u009F​-‏‪-‮⁠-⁤⁦-⁩]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, max);
@@ -35,7 +38,7 @@ export const prefsFile = (commonDir) => join(commonDir, 'bravos', 'prefs.json');
35
38
  // @comment -- "Reads the preferences for a clone, each answer on its own. An answer that is not exactly the recorded shape (another schema, an unknown choice, no name, a date that is not a date) reads as nothing recorded, so a damaged or hand-made file can only make Bravos ask again or fall back to its default, never commit."
36
39
  // @mitigates #person-prefs against #governance-forgery using #prefs-outside-tree -- "Only a well-formed record under the git directory counts as the person's answer."
37
40
  export function readPrefs(commonDir) {
38
- const none = { commits: null, annotate: null, coach: null };
41
+ const none = { commits: null, annotate: null, coach: null, cards: null, notify: null };
39
42
  if (!commonDir) return none;
40
43
  let doc;
41
44
  try {
@@ -51,7 +54,7 @@ export function readPrefs(commonDir) {
51
54
  if (!by || by.startsWith('<') || typeof c.at !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(c.at)) return null;
52
55
  return { value: c.value, by, at: c.at };
53
56
  };
54
- return { commits: one('commits'), annotate: one('annotate'), coach: one('coach') };
57
+ return { commits: one('commits'), annotate: one('annotate'), coach: one('coach'), cards: one('cards'), notify: one('notify') };
55
58
  }
56
59
 
57
60
  // @comment -- "Records the commits answer a named person gave (writePref does the work)."
@@ -0,0 +1,343 @@
1
+ #!/usr/bin/env node
2
+ // @comment -- "The nightly's opt-in team view (repository variable BRAVOS_THREAT_ISSUES=on): one GitHub issue per critical or high @exposes claim still untested BRAVOS_THREAT_ISSUES_DAYS days (default 2) after its annotation was committed, and the issue closed again once the claim is refuted, fixed (a covering @mitigates), accepted by a named person, lowered below high, or removed. A confirmed claim keeps its issue open, relabelled confirmed; a claim whose code changed after its last result (retest, or untested again) reopens the issue the nightly closed. Reads three files the workflow step wrote from guardlink parse, guardlink hypothesis list --json and guardlink blame --json; talks to GitHub only through gh with argument arrays and --body-file, so no annotation text is ever part of a shell line. One issue per claim key, found again by a hidden marker on the body's first line of an issue the workflow's own bot opened, listed both by the bravos label and by that author so a removed label never makes a second one. Dependency-free."
3
+ import { spawnSync } from 'node:child_process';
4
+ import { appendFileSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from 'node:fs';
5
+ import { tmpdir } from 'node:os';
6
+ import { join } from 'node:path';
7
+ import { pathToFileURL } from 'node:url';
8
+
9
+ export const MARKER = 'bravos:threat-issue';
10
+ export const CLOSED_MARKER = `<!-- ${MARKER}-closed -->`;
11
+ const KEY = /^[0-9a-f]{64}:\d+$/;
12
+ const SEVERE = new Set(['critical', 'high']);
13
+ const DAY_MS = 86400000;
14
+ /** New issues per run, so turning the view on over a large backlog opens them over a few nights instead of all at once. */
15
+ export const MAX_NEW = 10;
16
+ /** gh's page for one issue list; the summary says when a list reaches it. */
17
+ export const LIST_LIMIT = 1000;
18
+ const BOT = /^(app\/)?github-actions(\[bot\])?$/;
19
+ const LABELS = {
20
+ bravos: ['1E9A6C', 'Opened by the bravos nightly'],
21
+ untested: ['FBCA04', 'A threat no test has confirmed or refuted yet'],
22
+ confirmed: ['5C0011', 'A test showed this threat is exploitable'],
23
+ critical: ['B60205', 'Critical severity'],
24
+ high: ['D93F0B', 'High severity'],
25
+ };
26
+
27
+ // Only printable text from an annotation reaches an issue.
28
+ // @exposes #threat-issues to #issue-markup-injection [low] cwe:CWE-116 -- "renderTitle() and renderBody() write the description, file path and ids that guardlink parse read from @exposes lines, text anyone who can edit the repository controls, into a GitHub issue that the whole team is notified of"
29
+ // @mitigates #threat-issues against #issue-markup-injection using #code-fenced-text -- "clean() strips control, bidirectional and invisible characters and caps the length; the description sits inside a code fence longer than any backtick run in it and ids and paths in inline code, so no @mention, link or markup in it renders; the title is cleaned and reaches gh as one argument"
30
+ export const clean = (s, max) => String(s ?? '').replace(/[\u0000-\u001F\u007F-\u009F\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u2069\uFEFF]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, max);
31
+ const code = (s, max = 200) => '`' + clean(s, max).replace(/`/g, "'") + '`';
32
+ function fenced(text) {
33
+ const run = Math.max(0, ...[...text.matchAll(/`+/g)].map((m) => m[0].length));
34
+ const fence = '`'.repeat(Math.max(3, run + 1));
35
+ return `${fence}text\n${text}\n${fence}`;
36
+ }
37
+ const titleCase = (s) => s.charAt(0).toUpperCase() + s.slice(1);
38
+
39
+ // @comment -- "The issue's title: [bravos] <Severity>: <description> (<file>:<line>), or [bravos] <Severity>, confirmed: … once a test confirmed it, cleaned and short enough for GitHub's limit."
40
+ export function renderTitle(c, { confirmed = false } = {}) {
41
+ const desc = clean(c.description, 110) || `${clean(c.threat, 40)} on ${clean(c.asset, 40)}`;
42
+ const more = clean(c.description, 111).length > 110 ? '…' : '';
43
+ return `[bravos] ${titleCase(c.severity)}${confirmed ? ', confirmed' : ''}: ${desc}${more} (${clean(c.file, 100)}:${c.line})`;
44
+ }
45
+
46
+ // @comment -- "The issue's body: the hidden key marker on the first line, the claim, where it is (a link to the line at the commit the nightly read), how long it has waited, and the three ways to close it: test it with bravos-prove, fix it with a @mitigates, or have a named person accept it. Annotation text appears only fenced or in inline code."
47
+ export function renderBody(c, { days, link }) {
48
+ const where = link ? `[${code(`${c.file}:${c.line}`)}](${link})` : code(`${c.file}:${c.line}`);
49
+ return [
50
+ `<!-- ${MARKER} ${c.key} -->`,
51
+ `**${titleCase(c.severity)}** · untested · ${code(c.threat, 80)} on ${code(c.asset, 80)}${c.cwe ? ` · ${c.cwe}` : ''}`,
52
+ '',
53
+ fenced(clean(c.description, 2000) || '(no description)'),
54
+ '',
55
+ `- **Where:** ${where}`,
56
+ `- **Recorded:** ${c.since.slice(0, 10)}${c.commit ? ` in ${code(c.commit.slice(0, 12))}` : ''}, and no test has confirmed or refuted it in the ${days} day${days === 1 ? '' : 's'} since.`,
57
+ '',
58
+ '### How to close it',
59
+ '',
60
+ 'Test it first. The nightly closes this issue by itself once a refutation, a fix or an acceptance is on the default branch:',
61
+ '',
62
+ `- **Test it.** Run \`bravos-prove\` on this claim against your own app (\`bravos-env\` sets up the target first). A refuted result in \`.guardlink/hypotheses.json\` closes it. A confirmed one keeps it open, relabelled \`confirmed\`, and blocks pull requests that change this code until it is fixed or ticketed.`,
63
+ `- **Fix it.** Fix the code and add \`@mitigates ${clean(c.asset, 80).replace(/`/g, "'")} against ${clean(c.threat, 80).replace(/`/g, "'")} using #<control>\` beside the fix.`,
64
+ `- **Accept it.** A named person decides to live with it and writes the \`@accepts\` line themselves, with their name and reasons. Agents never write it.`,
65
+ '',
66
+ 'Removing a claim that turns out to be wrong closes it too.',
67
+ '',
68
+ `<sub>Opened by the bravos nightly team view (repository variable \`BRAVOS_THREAT_ISSUES\`). Claim key \`${c.key}\`.</sub>`,
69
+ ].join('\n');
70
+ }
71
+
72
+ const readJson = (p, what) => {
73
+ try {
74
+ return JSON.parse(readFileSync(p, 'utf8'));
75
+ } catch {
76
+ throw new Error(`unknown: ${what} is not JSON`);
77
+ }
78
+ };
79
+
80
+ // @comment -- "Joins the three GuardLink answers into one row per critical or high @exposes claim: the hypothesis record (key, state, severity) to its model exposure by declaration site, as the PR gate does, for the description, cwe and the logical file and line; to its blame entry by claim key, for when its annotation was committed (found_by) and whether a @mitigates covers it (fixed_by); and to an unexpired @accepts on the same asset and threat. Rows that cannot be joined are counted, never guessed."
81
+ export function claims(model, ledger, blame, today = new Date().toISOString().slice(0, 10)) {
82
+ const exposures = Array.isArray(model?.exposures) ? model.exposures : [];
83
+ const acceptances = Array.isArray(model?.acceptances) ? model.acceptances : [];
84
+ const byKey = new Map((Array.isArray(blame?.entries) ? blame.entries : []).filter((e) => e && e.verb === 'exposes').map((e) => [e.key, e]));
85
+ const rows = new Map();
86
+ let unjoined = 0;
87
+ for (const r of ledger.records) {
88
+ if (!r || typeof r.key !== 'string' || !KEY.test(r.key)) continue;
89
+ const severity = String(r.severity ?? '').toLowerCase();
90
+ const site = exposures.filter((e) => e.asset === r.asset && e.threat === r.threat && (e.location?.origin_file ?? e.location?.file) === r.file && (e.location?.origin_line ?? e.location?.line) === r.line);
91
+ if (site.length !== 1) {
92
+ if (SEVERE.has(severity)) unjoined++;
93
+ rows.set(r.key, { key: r.key, state: r.state, severity, joined: false });
94
+ continue;
95
+ }
96
+ const e = site[0];
97
+ const b = byKey.get(r.key)?.blame;
98
+ const accepted = acceptances.find((a) => a.asset === r.asset && a.threat === r.threat && (!a.expires || String(a.expires) >= today));
99
+ const cwe = (e.external_refs ?? []).map((x) => /^cwe:(CWE-\d{1,5})$/i.exec(String(x))?.[1]).find(Boolean)?.toUpperCase() ?? null;
100
+ rows.set(r.key, {
101
+ key: r.key,
102
+ joined: true,
103
+ state: r.state,
104
+ severity,
105
+ asset: r.asset,
106
+ threat: r.threat,
107
+ description: e.description ?? '',
108
+ cwe,
109
+ file: e.location?.file ?? r.file,
110
+ line: e.location?.line ?? r.line,
111
+ since: typeof b?.found_by?.date === 'string' ? b.found_by.date : null,
112
+ commit: typeof b?.found_by?.sha === 'string' ? b.found_by.sha : null,
113
+ fixed: !!b?.fixed_by,
114
+ // A recorded result, holding or lapsed: GuardLink keeps the entry (outcome) and, once code changed, the lapsed result (previous).
115
+ tested: !!(r.outcome || r.previous),
116
+ last: r.outcome?.outcome ?? r.previous?.outcome ?? null,
117
+ accepted: accepted ? (accepted.accepted_by ?? 'a named person') : null,
118
+ });
119
+ }
120
+ return { rows, unjoined };
121
+ }
122
+
123
+ // @comment -- "Why a claim no longer needs its issue, or null while it still does. Confirmed and retest are never reasons: a proven threat stays in the team's view until it is fixed or accepted, and a retest is untested again."
124
+ export function closeReason(row) {
125
+ if (!row) return 'The claim is no longer in the threat model (its @exposes was removed or rewritten).';
126
+ if (row.state === 'refuted') return 'A test refuted it: the attack did not work against this code.';
127
+ if (row.accepted) return `Accepted by ${code(row.accepted, 80)} with an @accepts line.`;
128
+ if (row.fixed) return 'Fixed: a @mitigates now covers it.';
129
+ if (!SEVERE.has(row.severity)) return `Its severity is now ${code(row.severity || 'unrated', 20)}, below high.`;
130
+ return null;
131
+ }
132
+
133
+ // @comment -- "The comment on an issue the nightly reopens, by the reason the claim needs it again."
134
+ export function reopenComment(row) {
135
+ if (row.state === 'retest') return 'Retest due: a test confirmed this threat, and the code under it changed after that, so the result no longer applies. Replay the test (bravos-recheck) or run bravos-prove again.';
136
+ if (row.last === 'refuted') return 'Untested again: a test refuted this threat, and the code under it changed after that, so the result no longer applies.';
137
+ return 'Open again: this claim is critical or high and untested once more; what closed the issue (a fix, an acceptance, a lower severity or its removal) no longer holds.';
138
+ }
139
+
140
+ // @comment -- "An issue counts as a claim's issue only when the workflow's own bot opened it and its body's first line is the marker with a key of GuardLink's shape: a marker in someone else's issue, or quoted inside a description further down, is never read."
141
+ // @exposes #threat-issues to #forged-issue-key [low] cwe:CWE-345 -- "existing() trusts the hidden marker on an issue's first line to say which claim the issue tracks; a forged marker would hide a claim's issue or close the wrong one"
142
+ // @mitigates #threat-issues against #forged-issue-key using #bot-authored-marker -- "only issues whose author is exactly the github-actions bot (app/github-actions or github-actions[bot], is_bot) are read, never another app whose name merely contains it; only the first line is parsed, and the key must match GuardLink's claim-key shape"
143
+ export function existing(issues) {
144
+ const out = new Map();
145
+ for (const i of Array.isArray(issues) ? issues : []) {
146
+ if (!i?.author?.is_bot || !BOT.test(String(i.author.login ?? ''))) continue;
147
+ const body = String(i.body ?? '');
148
+ const m = new RegExp(`^<!-- ${MARKER} ([0-9a-f]{64}:\\d+) -->`).exec(body.split('\n')[0] ?? '');
149
+ if (!m || out.has(m[1])) continue;
150
+ const lines = body.trimEnd().split('\n');
151
+ const labels = (Array.isArray(i.labels) ? i.labels : []).map((l) => String(l?.name ?? l).toLowerCase());
152
+ out.set(m[1], { number: i.number, open: String(i.state).toUpperCase() === 'OPEN', closedByBravos: lines[lines.length - 1]?.trim() === CLOSED_MARKER, labels, body });
153
+ }
154
+ return out;
155
+ }
156
+
157
+ // @comment -- "What one run does, decided before gh is called: close the open issues whose claim no longer needs one; relabel and retitle an open issue whose claim a test confirmed; open an issue for each due claim that has none and never had a test result (most severe and oldest first, at most MAX_NEW); and reopen an issue the nightly itself closed when its claim is untested or due a retest again. An issue a person closed stays closed, and one a person reopened after the nightly closed it stays open."
158
+ export function plan(rows, issues, { days, now = Date.now() }) {
159
+ const close = [];
160
+ const confirm = [];
161
+ const open = [];
162
+ const reopen = [];
163
+ const waiting = [];
164
+ let manual = 0;
165
+ let manualOpen = 0;
166
+ let tested = 0;
167
+ for (const [key, issue] of issues) {
168
+ if (!issue.open) continue;
169
+ // Still ends with the nightly's closing note, yet open: a person reopened it, and that is their call.
170
+ if (issue.closedByBravos) {
171
+ manualOpen++;
172
+ continue;
173
+ }
174
+ const row = rows.get(key);
175
+ const reason = closeReason(row);
176
+ if (reason) close.push({ key, number: issue.number, reason, body: issue.body, labels: issue.labels });
177
+ else if (row?.joined && row.state === 'confirmed' && !issue.labels.includes('confirmed')) confirm.push({ ...row, number: issue.number, labels: issue.labels });
178
+ }
179
+ const due = [];
180
+ for (const row of rows.values()) {
181
+ if (!row.joined || (row.state !== 'untested' && row.state !== 'retest') || closeReason(row)) continue;
182
+ const issue = issues.get(row.key);
183
+ if (issue?.open) continue;
184
+ if (issue && !issue.closedByBravos) {
185
+ manual++;
186
+ continue;
187
+ }
188
+ // A claim with a test result, holding or lapsed (every retest has one), was tested in time: it gets no new issue,
189
+ // only its old one back. Its changed code is the PR gate's to flag.
190
+ if (!issue && row.tested) {
191
+ tested++;
192
+ continue;
193
+ }
194
+ if (!row.since || Number.isNaN(Date.parse(row.since))) {
195
+ waiting.push({ ...row, why: 'no commit date from guardlink blame' });
196
+ continue;
197
+ }
198
+ const age = Math.floor((now - Date.parse(row.since)) / DAY_MS);
199
+ if (age < days) {
200
+ waiting.push({ ...row, why: `untested for ${age} of ${days} days` });
201
+ continue;
202
+ }
203
+ (issue ? reopen : due).push({ ...row, age, number: issue?.number });
204
+ }
205
+ due.sort((a, b) => (a.severity === b.severity ? 0 : a.severity === 'critical' ? -1 : 1) || Date.parse(a.since) - Date.parse(b.since) || a.key.localeCompare(b.key));
206
+ open.push(...due.slice(0, MAX_NEW));
207
+ return { close, confirm, open, reopen, waiting, manual, manualOpen, tested, deferred: Math.max(0, due.length - MAX_NEW) };
208
+ }
209
+
210
+ function gh(args) {
211
+ const r = spawnSync('gh', args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
212
+ return { ok: r.status === 0, out: r.stdout ?? '', err: (r.stderr || r.error?.message || '').trim() };
213
+ }
214
+
215
+ // @comment -- "Runs the plan with gh against the job's repository and GITHUB_TOKEN: creates any of its labels that are missing, writes every body to a private temp file passed by --body-file, and passes titles, labels and comments as single arguments. A failed gh call is reported and fails the run at the end; the rest still runs, and the next run picks up where it stopped."
216
+ // @flows #threat-issues -> #github-issues via gh -- "issue list, label list/create, issue create/edit/close/reopen with the job's GITHUB_TOKEN (issues: write)"
217
+ export function main(argv = process.argv.slice(2), env = process.env) {
218
+ const [modelPath, ledgerPath, blamePath] = argv;
219
+ const out = (l) => process.stdout.write(l + '\n');
220
+ const fail = (l) => {
221
+ out(`::error::${l}`);
222
+ return 1;
223
+ };
224
+ const repo = String(env.REPO ?? '');
225
+ if (!/^[\w.-]+\/[\w.-]+$/.test(repo)) return fail('unknown: REPO is not owner/name');
226
+ const rawDays = String(env.DAYS ?? '').trim();
227
+ if (rawDays && !/^\d{1,3}$/.test(rawDays)) return fail(`BRAVOS_THREAT_ISSUES_DAYS must be a whole number of days, not ${JSON.stringify(clean(rawDays, 20))}`);
228
+ const days = rawDays ? Number(rawDays) : 2;
229
+ let model, ledger, blame;
230
+ try {
231
+ model = readJson(modelPath, 'guardlink parse');
232
+ ledger = readJson(ledgerPath, 'guardlink hypothesis list');
233
+ blame = readJson(blamePath, 'guardlink blame');
234
+ } catch (e) {
235
+ return fail(e.message);
236
+ }
237
+ if (!Array.isArray(model?.exposures)) return fail('unknown: guardlink parse has no exposures[]');
238
+ if (!['present', 'absent'].includes(ledger?.ledger) || !Array.isArray(ledger?.records)) return fail('unknown: GuardLink hypothesis ledger unreadable');
239
+ if (!Array.isArray(blame?.entries)) return fail('unknown: guardlink blame has no entries[]');
240
+
241
+ // Listed twice and joined by number: by the bravos label, and by the github-actions author (GitHub's author:app/ search),
242
+ // so an issue whose label someone removed is still found and never gets a second one.
243
+ const fields = 'number,state,title,body,author,labels';
244
+ const issues = new Map();
245
+ let full = false;
246
+ for (const by of [['--label', 'bravos'], ['--search', 'author:app/github-actions']]) {
247
+ const listed = gh(['issue', 'list', '-R', repo, ...by, '--state', 'all', '--limit', String(LIST_LIMIT), '--json', fields]);
248
+ try {
249
+ if (!listed.ok) throw new Error(listed.err);
250
+ const page = JSON.parse(listed.out);
251
+ if (!Array.isArray(page)) throw new Error('not a list');
252
+ if (page.length >= LIST_LIMIT) full = true;
253
+ for (const i of page) if (i && !issues.has(i.number)) issues.set(i.number, i);
254
+ } catch (e) {
255
+ return fail(`unknown: gh issue list ${by.join(' ')} failed: ${clean(e.message, 200)}`);
256
+ }
257
+ }
258
+ if (full) out(`::warning::An issue list reached gh's ${LIST_LIMIT}-issue limit: an older claim's issue may be missed, and opened again.`);
259
+ const { rows, unjoined } = claims(model, ledger, blame);
260
+ const p = plan(rows, existing([...issues.values()]), { days });
261
+ const sha = /^[0-9a-f]{40}$/.test(String(env.SHA ?? '')) ? env.SHA : null;
262
+ const server = /^https:\/\/[\w.-]+(:\d+)?$/.test(String(env.SERVER ?? '')) ? env.SERVER : null;
263
+ const link = (c) => (sha && server ? `${server}/${repo}/blob/${sha}/${String(c.file).split('/').map(encodeURIComponent).join('/')}#L${Number(c.line) || 1}` : null);
264
+ const dir = mkdtempSync(join(env.RUNNER_TEMP || tmpdir(), 'bravos-issues-'));
265
+ let n = 0;
266
+ const bodyFile = (text) => {
267
+ const f = join(dir, `body-${++n}.md`);
268
+ writeFileSync(f, text + '\n', { mode: 0o600 });
269
+ return f;
270
+ };
271
+ let failed = 0;
272
+ const run = (args, what) => {
273
+ const r = gh(args);
274
+ if (!r.ok) {
275
+ failed++;
276
+ out(`::warning::${what} failed: ${clean(r.err, 300)}`);
277
+ }
278
+ return r;
279
+ };
280
+
281
+ // Labels the new and reopened issues carry, created when missing.
282
+ const wanted = new Set();
283
+ for (const c of [...p.open, ...p.reopen]) for (const l of ['bravos', 'untested', c.severity, ...(c.cwe ? [c.cwe] : [])]) wanted.add(l);
284
+ if (p.confirm.length) wanted.add('confirmed');
285
+ if (wanted.size) {
286
+ const have = gh(['label', 'list', '-R', repo, '--limit', '1000', '--json', 'name']);
287
+ let names = new Set();
288
+ try {
289
+ names = new Set(JSON.parse(have.out).map((l) => String(l.name).toLowerCase()));
290
+ } catch {
291
+ /* unknown: try to create each; an existing one only fails that call */
292
+ }
293
+ for (const l of wanted) {
294
+ if (names.has(l.toLowerCase())) continue;
295
+ const [color, description] = LABELS[l] ?? ['5319E7', `Weakness ${l}`];
296
+ gh(['label', 'create', l, '-R', repo, '--color', color, '--description', description]);
297
+ }
298
+ }
299
+
300
+ const today = new Date().toISOString().slice(0, 10);
301
+ for (const c of p.close) {
302
+ const closedBody = `${c.body.trimEnd()}\n\n---\n\nClosed by the bravos nightly on ${today}: ${c.reason}\n\n${CLOSED_MARKER}`;
303
+ const drop = c.labels.includes('untested') ? ['--remove-label', 'untested'] : [];
304
+ if (run(['issue', 'edit', String(c.number), '-R', repo, '--body-file', bodyFile(closedBody), ...drop], `editing #${c.number}`).ok &&
305
+ run(['issue', 'close', String(c.number), '-R', repo, '--reason', 'completed', '--comment', c.reason], `closing #${c.number}`).ok) out(`closed #${c.number}: ${c.reason}`);
306
+ }
307
+ for (const c of p.confirm) {
308
+ const drop = c.labels.includes('untested') ? ['--remove-label', 'untested'] : [];
309
+ if (run(['issue', 'edit', String(c.number), '-R', repo, '--title', renderTitle(c, { confirmed: true }), '--add-label', 'confirmed', ...drop], `relabelling #${c.number}`).ok &&
310
+ run(['issue', 'comment', String(c.number), '-R', repo, '--body-file', bodyFile('A test confirmed this threat is exploitable. The issue stays open until it is fixed (a @mitigates beside the fix) or a named person accepts it, and the PR gate blocks changes to this code until then unless a @ticket tracks it.')], `commenting on #${c.number}`).ok) out(`confirmed #${c.number}`);
311
+ }
312
+ for (const c of p.reopen) {
313
+ const labels = ['untested', c.severity, ...(c.cwe ? [c.cwe] : [])].join(',');
314
+ if (run(['issue', 'edit', String(c.number), '-R', repo, '--title', renderTitle(c), '--body-file', bodyFile(renderBody(c, { days: c.age, link: link(c) })), '--add-label', labels], `editing #${c.number}`).ok &&
315
+ run(['issue', 'reopen', String(c.number), '-R', repo, '--comment', reopenComment(c)], `reopening #${c.number}`).ok) out(`reopened #${c.number}`);
316
+ }
317
+ for (const c of p.open) {
318
+ const labels = ['bravos', c.severity, 'untested', ...(c.cwe ? [c.cwe] : [])].join(',');
319
+ const r = run(['issue', 'create', '-R', repo, '--title', renderTitle(c), '--body-file', bodyFile(renderBody(c, { days: c.age, link: link(c) })), '--label', labels], `opening an issue for ${c.file}:${c.line}`);
320
+ if (r.ok) out(`opened ${clean(r.out, 200)}`);
321
+ }
322
+
323
+ const summary = [
324
+ '### Untested threats (team view)',
325
+ '',
326
+ `Critical and high claims still untested ${days} day${days === 1 ? '' : 's'} after they were committed get an issue; a confirmed one keeps it open.`,
327
+ '',
328
+ `- opened ${p.open.length}, reopened ${p.reopen.length}, marked confirmed ${p.confirm.length}, closed ${p.close.length}`,
329
+ `- ${issues.size} issue(s) read (labelled bravos or opened by github-actions; at most ${LIST_LIMIT} each list)${full ? `: a list reached the limit, so an older issue may be missed and opened again` : ''}`,
330
+ ...(p.deferred ? [`- ${p.deferred} more due: opened on later runs, ${MAX_NEW} a run`] : []),
331
+ ...(p.waiting.length ? [`- ${p.waiting.length} not due yet (${p.waiting.slice(0, 5).map((w) => `${code(`${w.file}:${w.line}`, 120)} ${w.why}`).join('; ')}${p.waiting.length > 5 ? '; …' : ''})`] : []),
332
+ ...(p.manual ? [`- ${p.manual} still untested with an issue a person closed: left closed`] : []),
333
+ ...(p.manualOpen ? [`- ${p.manualOpen} reopened by a person after the nightly closed it: left open`] : []),
334
+ ...(p.tested ? [`- ${p.tested} untested again or due a retest after an earlier result, with no issue: none opened (the PR gate flags changes under them)`] : []),
335
+ ...(unjoined ? [`- ${unjoined} critical or high claim(s) could not be matched to one exposure in the model: skipped`] : []),
336
+ '',
337
+ ].join('\n');
338
+ out(summary);
339
+ if (env.GITHUB_STEP_SUMMARY) appendFileSync(env.GITHUB_STEP_SUMMARY, summary + '\n');
340
+ return failed ? fail(`${failed} gh call(s) failed; the next run retries them`) : 0;
341
+ }
342
+
343
+ if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) process.exitCode = main();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bugb-technologies/bravos",
3
- "version": "1.12.1",
3
+ "version": "1.14.0",
4
4
  "description": "Skills pack and installer that make Claude Code and Codex power users of guardlink (threat-model-as-code) and cert-x-gen (pentest-as-code).",
5
5
  "keywords": [
6
6
  "security",