@bugb-technologies/bravos 1.18.0 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/account.js +19 -2
  2. package/dist/cli.js +133 -15
  3. package/dist/context.js +126 -3
  4. package/dist/cursor.js +4 -2
  5. package/dist/dashboard.js +9 -0
  6. package/dist/device.js +3 -1
  7. package/dist/doctor.js +4 -0
  8. package/dist/guide.js +7 -3
  9. package/dist/help.js +15 -8
  10. package/dist/instruction-blocks.js +257 -0
  11. package/dist/principles.js +279 -0
  12. package/dist/review-server.js +19 -4
  13. package/dist/review-wait.js +11 -0
  14. package/dist/review.js +342 -41
  15. package/dist/rules.js +82 -6
  16. package/dist/uninstall.js +9 -2
  17. package/docs/GUIDE.md +18 -2
  18. package/docs/UPGRADING.md +63 -0
  19. package/hooks/autopilot.mjs +2 -1
  20. package/hooks/cards.mjs +23 -5
  21. package/hooks/coach.mjs +3 -0
  22. package/hooks/invite.mjs +10 -0
  23. package/hooks/lib/audience.mjs +83 -0
  24. package/hooks/lib/briefing.mjs +83 -2
  25. package/hooks/lib/context.mjs +57 -1
  26. package/hooks/lib/display.mjs +11 -0
  27. package/hooks/lib/licence.mjs +2 -1
  28. package/hooks/lib/machine.mjs +77 -0
  29. package/hooks/lib/pre-pr.mjs +82 -1
  30. package/hooks/lib/principles.mjs +513 -0
  31. package/hooks/lib/refresh.mjs +11 -1
  32. package/hooks/lib/replay.mjs +218 -100
  33. package/hooks/pre-pr.mjs +3 -0
  34. package/hooks/session-start.mjs +35 -7
  35. package/package.json +1 -1
  36. package/skills/bravos/SKILL.md +1 -0
  37. package/skills/bravos-context/SKILL.md +4 -4
  38. package/skills/bravos-principles/SKILL.md +52 -0
  39. package/templates/dashboard/dashboard.html +75 -1
  40. package/templates/omp/bravos.js +10 -1
  41. package/templates/opencode/bravos.js +11 -2
  42. package/templates/review/review.html +140 -11
  43. package/templates/workflows/bravos-nightly-claude.yml +1 -1
  44. package/templates/workflows/bravos-nightly-codex.yml +1 -1
  45. package/templates/workflows/bravos-pr-gate.yml +1 -1
@@ -4,6 +4,7 @@ import { accessSync, constants, readFileSync } from 'node:fs';
4
4
  import { homedir } from 'node:os';
5
5
  import { basename, delimiter, dirname, join } from 'node:path';
6
6
  import { contextGate, readContext } from './context.mjs';
7
+ import { adoptedPrinciples } from './principles.mjs';
7
8
  import { legacySkills, legacySkillsLine } from './legacy-skills.mjs';
8
9
  import { deadHooksLine, deadUserHooks } from './dead-hooks.mjs';
9
10
  import { THEMES } from './palette.mjs';
@@ -124,17 +125,37 @@ export function readIntent(root) {
124
125
 
125
126
  // @comment -- "The briefing's line about the team's design documents, when there are any: how many, by id, that the rules cite them and that only the context skill opens them; and when the intent has fallen behind a document (edited, or added since), which ones and how to refresh. Ids only, never a title or any text from a document."
126
127
  export function contextLine(context, harness) {
127
- if (!context || typeof context !== 'object' || !context.count) return null;
128
+ if (!context || typeof context !== 'object') return null;
128
129
  const run = harness === 'claude' ? '/bravos-context' : 'the bravos-context skill';
130
+ // Added on the intake page and not text the CLI could store: the agent converts each one (bravos-context step 2).
131
+ const inbox = context.inbox > 0 ? `${context.inbox} design document${context.inbox === 1 ? '' : 's'} added on the intake page wait${context.inbox === 1 ? 's' : ''} in .bravos/context/inbox/ for you to convert and store with bravos context add (${run} step 2)` : '';
132
+ if (!context.count) return inbox ? `Design documents: ${inbox}` : null;
129
133
  const list = (ids) => (ids.length > 6 ? `${ids.slice(0, 6).join(', ')} and ${ids.length - 6} more` : ids.join(', '));
130
134
  const behind = [
131
135
  context.changed?.length ? `${list(context.changed)} changed since the rules were written` : '',
132
136
  context.unread?.length ? `${list(context.unread)} not read into the intent yet` : '',
133
137
  ].filter(Boolean);
134
138
  const head = `Design documents: ${context.count} in .bravos/context/ (${list(context.ids ?? [])})`;
135
- return behind.length
139
+ const line = behind.length
136
140
  ? `${head} — ${behind.join('; ')}: refresh the intent with ${run}`
137
141
  : `${head} — intent.md's rules cite them by id; only ${run} opens the documents themselves`;
142
+ return inbox ? `${line}. Also: ${inbox}` : line;
143
+ }
144
+
145
+ // @comment -- "The adopted security design principles as the briefing needs them: how many, which are enforced, and the ids of those that apply everywhere. Only principles whose fingerprint still matches their text count; a hand-edited one is left out, and the check reports it."
146
+ export function readPrinciples(root) {
147
+ const adopted = adoptedPrinciples(root);
148
+ if (!adopted.length) return null;
149
+ return { count: adopted.length, enforced: adopted.filter((p) => p.kind === 'enforced').map((p) => p.id), everywhere: adopted.filter((p) => !p.paths.length).map((p) => p.id), scoped: adopted.filter((p) => p.paths.length).map((p) => p.id) };
150
+ }
151
+
152
+ // @comment -- "The briefing's line about the company's security design principles, when the repository has adopted ones: read .guardlink/principles.md before changing code and follow it, raise a change that would break one, and never edit it. Ids only; the principles' text stays in their file, which the agent reads itself."
153
+ export function principlesLine(p) {
154
+ if (!p || typeof p !== 'object' || !p.count) return null;
155
+ const ids = (xs) => (xs.length > 8 ? `${xs.slice(0, 8).join(', ')} and ${xs.length - 8} more` : xs.join(', '));
156
+ const enforced = p.enforced?.length ? `; enforced (tested, and the pre-PR gate stops a change that breaks them): ${ids(p.enforced)}` : '';
157
+ const scoped = p.scoped?.length ? `; ${ids(p.scoped)} apply only to the paths they name, and the after-edit note says when you touch one` : '';
158
+ return `Security design principles: ${p.count} adopted in .guardlink/principles.md${enforced}${scoped}. Read the file before changing code here and follow each one; when a change would break one, say so and ask the person first. Never edit the file, its adoptions or its exceptions.`;
138
159
  }
139
160
 
140
161
  // @comment -- "The briefing's Intent line. Until a named person confirms what the product is for, it tells the agent to keep annotating against its own draft (drafting one first when there is none, without waiting for answers) and to ask the person once each session to confirm it on the intake page. Right after setup (a fresh hand-off marker) it says to begin in the first reply. A recorded decline is shown with its name and date, and ends the asking."
@@ -262,6 +283,8 @@ export function buildBriefing(inputs) {
262
283
  if (i.intent && typeof i.intent === 'object') tail.push(intentLine(i.intent, i.harness, i.gate, i.handoff === true));
263
284
  const documents = contextLine(i.context, i.harness);
264
285
  if (documents) tail.push(documents);
286
+ const principles = principlesLine(i.principles);
287
+ if (principles) tail.push(principles);
265
288
  // The person's standing answer about commits, when they gave one (hooks/lib/prefs.mjs).
266
289
  const commits = commitsLine(i.prefs);
267
290
  if (commits) tail.push(commits);
@@ -590,6 +613,7 @@ export async function collect(root, env, { deadlineMs = 20000, nextCount = 3 } =
590
613
  inFlight,
591
614
  intent: readIntent(root),
592
615
  context: readContext(root),
616
+ principles: readPrinciples(root),
593
617
  gate: contextGate(root),
594
618
  prefs: readPrefs(facts.commonDir),
595
619
  // The background annotation pass is off for this run (BRAVOS_AUTO_ANNOTATE=off) or in CI, where the nightly annotates.
@@ -895,6 +919,11 @@ function bannerWarnings(i, plan) {
895
919
  if ((i.autopilot || i.prePr) && hooksLocked(i)) lines.push(`~ ${i.autopilot ? 'autopilot' : 'the pre-PR gate'} is set up here, on the Team plan for you · bravos account activate`);
896
920
  else if (plan && !plan.licensed && i.licence.state === 'expired') lines.push(`~ licence expired: ${TEAM_ADDS} locked · bravos licence`);
897
921
  else if (plan && !plan.licensed) lines.push(`~ Team adds ${TEAM_ADDS} · bravos account activate`);
922
+ // A trial in its last days says so, so keeping Team is the person's (or their admin's) decision, not a surprise.
923
+ else if (plan && i.licence?.trial) {
924
+ const left = Math.ceil((Number(i.licence.trial.endsAt) - Math.floor(Date.now() / 1000)) / 86400);
925
+ if (Number.isFinite(left) && left <= 5) lines.push(`~ Team trial ends in ${Math.max(0, left)} day${left === 1 ? '' : 's'}: ask your admin to keep Team · bravos licence`);
926
+ }
898
927
  if (i.stale) lines.push(`! Findings describe older code · ${i.stale.behind} behind ${clean(i.base)} · bravos-resync`);
899
928
  else if (arr(i.stranded).length > 0) lines.push(`~ Work on ${clean(i.stranded[0].branch)} is not on ${clean(i.base)} · bravos-resync`);
900
929
  if (i.shadow) {
@@ -1079,6 +1108,58 @@ export function firstReplyStatus(inputs, opts = {}) {
1079
1108
  return `Status for the person: this agent cannot show Bravos's startup banner to the person, so open your first reply with the card below, copied exactly, inside a text code block, then answer their message. Show it once: skip it when this conversation already shows it.\n\`\`\`text\n${statusCard(inputs, opts)}\n\`\`\``;
1080
1109
  }
1081
1110
 
1111
+ const INSTALL = 'npm install -g @bugb-technologies/bravos';
1112
+ const KNOWN_SEVERITY = ['critical', 'high', 'medium', 'low'];
1113
+
1114
+ // @comment -- "The repository's own numbers for the invitation, read from the committed GuardLink report (.guardlink/report.json), so a machine with no Bravos and no GuardLink still shows them: recorded threats by severity, confirmed exploits and annotated files. Null when there is no report or it cannot be read. Only counts and a cleaned project name leave the file."
1115
+ export function readCommittedReport(root) {
1116
+ try {
1117
+ const j = JSON.parse(readFileSync(join(root, '.guardlink', 'report.json'), 'utf8'));
1118
+ const exposures = Array.isArray(j?.exposures) ? j.exposures : [];
1119
+ const by = Object.fromEntries(KNOWN_SEVERITY.map((k) => [k, exposures.filter((e) => e?.severity === k).length]));
1120
+ const files = (v) => (Array.isArray(v) ? v.length : Number.isFinite(v) ? v : null);
1121
+ return {
1122
+ project: typeof j?.project === 'string' ? clean(j.project).trim().slice(0, 40) : null,
1123
+ threats: exposures.length,
1124
+ by,
1125
+ confirmed: Array.isArray(j?.confirmed) ? j.confirmed.length : 0,
1126
+ annotated: files(j?.annotated_files),
1127
+ source: files(j?.source_files),
1128
+ };
1129
+ } catch {
1130
+ return null;
1131
+ }
1132
+ }
1133
+
1134
+ // @comment -- "The invitation a person without Bravos sees, in the card's plain 64-column style: that their team protects this repository with Bravos, the repository's real numbers when a report is committed, what Bravos would do for them, and the one command that sets it up (Free, no account). Nothing in it comes from the repository but counts and a cleaned name."
1135
+ export function inviteCard(root) {
1136
+ const r = readCommittedReport(root);
1137
+ const name = r?.project || clean(basename(root)).trim().slice(0, 40) || 'this repository';
1138
+ const rows = ['BRAVOS by bugb · your team protects this repository'];
1139
+ if (r && r.threats > 0) {
1140
+ const sev = KNOWN_SEVERITY.filter((k) => r.by[k] > 0).map((k) => `${r.by[k]} ${k}`).join(' · ');
1141
+ rows.push(clipped(`${name}: ${r.threats} threats recorded${sev ? ` · ${sev}` : ''}`, 64));
1142
+ const cover = r.annotated !== null && r.source ? `${r.annotated} / ${r.source} files annotated · ` : '';
1143
+ rows.push(`${cover}${r.confirmed} confirmed exploitable`);
1144
+ } else rows.push(clipped(`${name} keeps a security threat model with Bravos`, 64));
1145
+ const rule = '─'.repeat(64);
1146
+ rows.push(rule, 'With Bravos, your coding agent:', ' · knows these threats before it edits the code', ' · checks each pull request for new exposure', ' · proves which threats are real, on your own machine', rule);
1147
+ rows.push(`Join your team: ${INSTALL}`, ' then: bravos setup', 'Free, no account needed. Say "not now" to hide this for 7 days.');
1148
+ return rows.map((l) => l.replace(/`/g, "'")).join('\n');
1149
+ }
1150
+
1151
+ // @comment -- "What the agent of a person without Bravos is told: no security briefing, threat cards or checks run on this machine; show the invitation once (in the first reply, unless the person already saw it on screen); offer setup once and run it only on a yes; on 'not now', snooze it with node .bravos/hooks/invite.mjs snooze and say no more; never let it delay or block their request."
1152
+ export function inviteBriefing(card, { shownOnScreen = false } = {}) {
1153
+ const show = shownOnScreen
1154
+ ? 'The person has already seen the Bravos invitation on screen; do not repeat it.'
1155
+ : `Open your first reply with the card below, copied exactly, inside a text code block, then answer their message. Show it once: skip it when this conversation already shows it.\n\`\`\`text\n${card}\n\`\`\``;
1156
+ return [
1157
+ 'Bravos: this repository uses Bravos (security workflow for coding agents), but this machine does not have it installed, so no security briefing, threat cards or checks run here.',
1158
+ show,
1159
+ `After answering, offer once, in one sentence, to set Bravos up so this person gets what their team has: \`${INSTALL}\`, then \`bravos setup\` in this repository. Run them only if the person says yes. If they say no or not now, run \`node .bravos/hooks/invite.mjs snooze\` (it hides the invitation in this clone for 7 days) and do not mention Bravos again this session. Never let this delay or block what they asked for.`,
1160
+ ].join('\n');
1161
+ }
1162
+
1082
1163
  // Brand palette by theme (hooks/lib/palette.mjs). Colour is truecolor ANSI, added after
1083
1164
  // layout so widths are measured on plain text. A null colour is the terminal's own
1084
1165
  // foreground, so it is readable on whatever background the terminal has.
@@ -269,6 +269,39 @@ export function commitReader(root, commit) {
269
269
  // ---------------------------------------------------------------------------------------------
270
270
 
271
271
  // Files an agent writes beside the store and that are committed with it. They are scanned for local paths only.
272
+ const fold = (t) => String(t ?? '').toLowerCase().replace(/[*_`~]/g, '').replace(/[“”"'‘’]/g, '').replace(/\s+/g, ' ').trim();
273
+
274
+ // @comment -- "Where a citation points in a stored document: a heading whose words match the cited section, else the paragraph that contains the cited words. Returns that passage (at most 1,200 characters) or null. Case, spacing, quotes and Markdown emphasis are ignored; nothing else is guessed, so a section that is not in the document is reported, never invented."
275
+ export function findSection(text, section) {
276
+ const want = fold(section);
277
+ if (!want || want.length < 3) return null;
278
+ const lines = String(text).split('\n');
279
+ const cap = (t) => (t.length > 1200 ? `${t.slice(0, 1199)}…` : t);
280
+ for (let i = 0; i < lines.length; i++) {
281
+ const h = /^(#{1,6})\s+(.*)$/.exec(lines[i]);
282
+ if (!h) continue;
283
+ const head = fold(h[2]);
284
+ if (head !== want && !head.includes(want)) continue;
285
+ const out = [lines[i]];
286
+ for (let k = i + 1; k < lines.length; k++) {
287
+ const next = /^(#{1,6})\s/.exec(lines[k]);
288
+ if (next && next[1].length <= h[1].length) break;
289
+ out.push(lines[k]);
290
+ }
291
+ return cap(out.join('\n').trim());
292
+ }
293
+ const paragraphs = String(text).split(/\n\s*\n/);
294
+ const hit = paragraphs.find((p) => fold(p).includes(want));
295
+ return hit ? cap(hit.trim()) : null;
296
+ }
297
+
298
+ // @comment -- "Every citation with a section in some text: SRC-n followed by a quoted section name, straight or curly quotes. Citations that name no section are not returned; they are checked by id alone."
299
+ export function citations(text) {
300
+ const out = [];
301
+ for (const m of String(text).matchAll(/\b(SRC-[1-9][0-9]{0,4})\b\s*[,:]?\s*["“]([^"”\n]{3,200})["”]/g)) out.push({ id: m[1], section: m[2] });
302
+ return out;
303
+ }
304
+
272
305
  const WRITTEN_BESIDE = ['.guardlink/intent.md', '.guardlink/intent-draft.json'];
273
306
 
274
307
  // @comment -- "Checks the whole store and returns what is wrong: an unreadable index, a source with no file or with two, a file that is not a regular text file, text edited since it was recorded, secrets, local paths, embedded content, a link that should not be committed, a file in the folder that no entry owns, a source cited by the intent but absent, and a folder git ignores. `problems` fail the check; `notes` do not. Nothing here prints or throws, and no finding carries the text that triggered it."
@@ -293,6 +326,7 @@ export function checkContext(root, opts = {}) {
293
326
  for (const e of listing) if (!e.regular) problem({ kind: 'not-regular', file: `${SOURCES_DIR}/${e.name}`, message: 'it is a link or a folder, not a regular file: a source is one Markdown file' });
294
327
  const names = listing.filter((e) => e.regular).map((e) => e.name);
295
328
  const owned = new Set();
329
+ const stored = new Map();
296
330
 
297
331
  for (const s of parsed.sources) {
298
332
  const name = fileFor(s.id, names);
@@ -317,6 +351,7 @@ export function checkContext(root, opts = {}) {
317
351
  continue;
318
352
  }
319
353
  const text = decoded.text;
354
+ stored.set(s.id, text);
320
355
  if (sha256(Buffer.from(text, 'utf8')) !== s.sha256) {
321
356
  entry.state = 'changed';
322
357
  problem({ kind: 'changed', id: s.id, file, message: `${s.id}: edited since it was recorded: run bravos context update ${s.id}, then refresh the intent that cites it` });
@@ -337,6 +372,14 @@ export function checkContext(root, opts = {}) {
337
372
  if (!buf) continue;
338
373
  const text = buf.toString('utf8');
339
374
  for (const m of text.matchAll(/\bSRC-[1-9][0-9]{0,4}\b/g)) if (!known.has(m[0]) && !cited.has(m[0])) cited.set(m[0], rel);
375
+ // A cited section must be in the document it names: a wrong section is a rule resting on nothing.
376
+ const seen = new Set();
377
+ for (const c of citations(text)) {
378
+ const key = `${c.id}\u0000${fold(c.section)}`;
379
+ if (seen.has(key) || !stored.has(c.id)) continue;
380
+ seen.add(key);
381
+ if (!findSection(stored.get(c.id), c.section)) problem({ kind: 'cited-section', id: c.id, file: rel, message: `${rel} cites ${c.id} "${cleanLine(c.section, 80)}", which is not a heading or passage in ${c.id}: correct the citation, or the rule it supports` });
382
+ }
340
383
  for (const f of scanPaths(text, who)) problem({ kind: 'local-path', file: rel, line: f.line, message: `${rel}: line ${f.line} carries ${an(f.rule)}: cite the source by its SRC id, not by where the file was` });
341
384
  }
342
385
  for (const [id, rel] of cited) problem({ kind: 'cited-absent', id, file: rel, message: `${id} is cited in ${rel} but is not in the index` });
@@ -368,9 +411,21 @@ export function formatCheck(result) {
368
411
  return lines;
369
412
  }
370
413
 
414
+ export const INBOX_DIR = `${CONTEXT_DIR}/inbox`;
415
+
416
+ // @comment -- "Documents added on the intake page that the CLI does not convert (a PDF, Word file, slides or a link), waiting for the agent: one <name>.json record each in .bravos/context/inbox/, a folder git ignores. Count only, for the briefing; never a title or a name."
417
+ export function inboxCount(root) {
418
+ try {
419
+ const base = realpathSync(root);
420
+ return readdirSync(join(base, INBOX_DIR)).filter((n) => n.endsWith('.json')).length;
421
+ } catch {
422
+ return 0;
423
+ }
424
+ }
425
+
371
426
  // @comment -- "What a briefing needs about the store, cheaply and without ever throwing: whether it exists, the ids it lists, and which of them the intent has fallen behind. intent.md's Sources section records the hash each document had when the rules were written (`- SRC-2: … sha256 <prefix>`); a source whose text now hashes differently is `changed`, and one the section does not list is `unread`. Ids only: a document's title or text never reaches a briefing."
372
427
  export function readContext(root) {
373
- const none = { exists: false, count: 0, ids: [], changed: [], unread: [] };
428
+ const none = { exists: false, count: 0, ids: [], changed: [], unread: [], inbox: inboxCount(root) };
374
429
  try {
375
430
  const reader = treeReader(root);
376
431
  if (!reader.exists()) return none;
@@ -382,6 +437,7 @@ export function readContext(root) {
382
437
  if (intent !== null) for (const m of intent.matchAll(/^\s*[-*]\s+(SRC-[1-9][0-9]{0,4})\b.*?\bsha256\s+([a-f0-9]{8,64})\b/gm)) read.set(m[1], m[2]);
383
438
  return {
384
439
  exists: true,
440
+ inbox: inboxCount(root),
385
441
  count: sources.length,
386
442
  ids: sources.map((s) => s.id),
387
443
  // With no intent yet nothing is behind: the documents are simply waiting to be read.
@@ -0,0 +1,11 @@
1
+ // @comment -- "Where the person sees Bravos's startup picture, per agent and surface. The agent's own reply is the one channel every surface shows, so anything not known to draw a hook's message natively gets the card in the agent's first reply. banner: the hook's systemMessage holds the banner (the Claude Code CLI in a terminal, Gemini CLI); hook-card: the hook's systemMessage holds the card, drawn inline with the first prompt (Codex); reply: the agent opens its first reply with the card (Claude Code's desktop app, IDE extensions and SDK, Cursor, Antigravity). A run with no known harness (a manual run, an unknown host) keeps the banner, as before. Pure."
2
+ export function displayMode(harness, env = process.env) {
3
+ if (harness === 'claude') {
4
+ // Claude Code says where it runs; an older CLI that does not say is the terminal.
5
+ const entry = String(env.CLAUDE_CODE_ENTRYPOINT ?? '');
6
+ return entry === '' || entry === 'cli' ? 'banner' : 'reply';
7
+ }
8
+ if (harness === 'codex') return 'hook-card';
9
+ if (harness === 'gemini' || harness === 'other') return 'banner';
10
+ return 'reply';
11
+ }
@@ -42,7 +42,7 @@ export const _setTrustedKeysForTests = (keys) => {
42
42
  };
43
43
 
44
44
  /** What this product gates on a Team (or higher) licence; everything else is free. */
45
- export const PAID_FEATURES = ['pre-pr', 'ci', 'schedule', 'workspace', 'campaign', 'sast', 'codegraph'];
45
+ export const PAID_FEATURES = ['pre-pr', 'ci', 'schedule', 'workspace', 'campaign', 'sast', 'codegraph', 'principles'];
46
46
  export const PAID_FEATURE_LABELS = {
47
47
  'pre-pr': 'the pre-PR gate',
48
48
  ci: 'CI and nightly workflows',
@@ -51,6 +51,7 @@ export const PAID_FEATURE_LABELS = {
51
51
  campaign: 'campaigns',
52
52
  sast: 'SAST',
53
53
  codegraph: 'the code graph',
54
+ principles: 'security design principles',
54
55
  };
55
56
 
56
57
  // ---------------------------------------------------------------------------------------------
@@ -0,0 +1,77 @@
1
+ // @comment -- "A one-way fingerprint of this machine for the account portal: sha256 of a fixed label and the operating system's own machine id (macOS IOPlatformUUID, Linux /etc/machine-id, Windows MachineGuid), so the portal can tell one machine from another for the one-free-trial rule without ever learning the id. The raw id never leaves this function. No dependency, no shell; null with a reason when the id cannot be read or would be shared (a container, a CI runner), because a shared id would wrongly refuse real people."
2
+ //
3
+ // Used by `bravos account activate` (src/account.ts) and the licence refresh
4
+ // (hooks/lib/refresh.mjs). Never throws.
5
+ //
6
+ // NULL IS AN ANSWER. The portal treats "no fingerprint" as allowed and flagged,
7
+ // never as refused, so every doubtful case below says null rather than guessing:
8
+ // - a container (/.dockerenv, /run/.containerenv, or a container cgroup): base
9
+ // images often ship ONE /etc/machine-id, so every container from an image
10
+ // would look like the same machine;
11
+ // - a CI runner (CI=true): the same, for every job on a shared image;
12
+ // - an id that is empty, all zeros, or the wrong shape.
13
+
14
+ import { createHash } from 'node:crypto';
15
+ import { execFileSync } from 'node:child_process';
16
+ import { existsSync, readFileSync } from 'node:fs';
17
+
18
+ export const MACHINE_LABEL = 'bravos-machine-v1:';
19
+ const ID_RE = /^[0-9a-fA-F-]{16,64}$/;
20
+
21
+ const readText = (file) => {
22
+ try {
23
+ return readFileSync(file, 'utf8').trim();
24
+ } catch {
25
+ return null;
26
+ }
27
+ };
28
+
29
+ /** Whether this process runs in a container, from the markers the common runtimes leave. */
30
+ export function inContainer({ exists = existsSync, read = readText } = {}) {
31
+ if (exists('/.dockerenv') || exists('/run/.containerenv')) return true;
32
+ const cgroup = read('/proc/1/cgroup') ?? '';
33
+ return /docker|kubepods|containerd|libpod|lxc/.test(cgroup);
34
+ }
35
+
36
+ /** The operating system's own machine id, unhashed, or null. Kept inside this module. */
37
+ export function osMachineId({ platform = process.platform, read = readText, exec = execFileSync } = {}) {
38
+ try {
39
+ if (platform === 'darwin') {
40
+ const out = String(exec('/usr/sbin/ioreg', ['-rd1', '-c', 'IOPlatformExpertDevice'], { encoding: 'utf8', timeout: 2000, stdio: ['ignore', 'pipe', 'ignore'] }));
41
+ return out.match(/"IOPlatformUUID"\s*=\s*"([^"]+)"/)?.[1] ?? null;
42
+ }
43
+ if (platform === 'linux') return read('/etc/machine-id') || read('/var/lib/dbus/machine-id') || null;
44
+ if (platform === 'win32') {
45
+ const out = String(exec('reg', ['query', 'HKLM\\SOFTWARE\\Microsoft\\Cryptography', '/v', 'MachineGuid'], { encoding: 'utf8', timeout: 2000, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true }));
46
+ return out.match(/MachineGuid\s+REG_SZ\s+(\S+)/)?.[1] ?? null;
47
+ }
48
+ return null;
49
+ } catch {
50
+ return null;
51
+ }
52
+ }
53
+
54
+ let cached = null;
55
+
56
+ /**
57
+ * This machine's fingerprint: { key, reason }. `key` is 64 lowercase hex or
58
+ * null; `reason` says why it is null ('container', 'ci', 'unreadable').
59
+ * Memoised for the process; tests pass `deps` and bypass the cache.
60
+ */
61
+ export function machineFingerprint(env = process.env, deps = null) {
62
+ if (!deps && cached) return cached;
63
+ const d = deps ?? {};
64
+ let answer;
65
+ if (env.CI === 'true' || env.CI === '1') answer = { key: null, reason: 'ci' };
66
+ else if (inContainer(d)) answer = { key: null, reason: 'container' };
67
+ else {
68
+ const id = osMachineId(d);
69
+ const clean = typeof id === 'string' ? id.trim() : '';
70
+ answer =
71
+ ID_RE.test(clean) && !/^[0-]+$/.test(clean)
72
+ ? { key: createHash('sha256').update(MACHINE_LABEL + clean.toLowerCase()).digest('hex'), reason: null }
73
+ : { key: null, reason: 'unreadable' };
74
+ }
75
+ if (!deps) cached = answer;
76
+ return answer;
77
+ }
@@ -1,8 +1,9 @@
1
1
  // @comment -- "The pre-PR gate behind bravos's opt-in PreToolUse hook, matching bravos-ship's rulings: recognises gh pr create / gh pr ready in a Bash command, runs guardlink validate, lint --since <base> --json, diff <base> --json (each new unmitigated exposure must be disclosed in the PR body by threat and asset id) and ci -f json (a confirmed claim on a changed file blocks unless that file carries a @ticket for it), and returns allow or block with a reason. A gate input that fails or does not parse blocks as unknown. Read-only: every command is spawned with an argv array, no shell, a per-spawn timeout and one shared deadline."
2
2
  import { gitPatchArgs, parseChangedHunks } from './snapshot.mjs';
3
3
  import { spawnSync } from 'node:child_process';
4
- import { existsSync, readFileSync } from 'node:fs';
4
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
5
5
  import { isAbsolute, join } from 'node:path';
6
+ import { checkPrinciples, exceptionFor, treeReader as principlesReader } from './principles.mjs';
6
7
 
7
8
  const PR_COMMAND = /(?:^|[\s;&|(])gh\s+pr\s+(create|ready)(?![\w-])/;
8
9
  const READY_ARG = /(?:^|[\s;&|(])gh\s+pr\s+ready\s+([^\s;&|)-][^\s;&|)]*)/;
@@ -203,6 +204,68 @@ function designRuleChanges(root, base, run, options) {
203
204
  return { lapsed, untested };
204
205
  }
205
206
 
207
+ // @comment -- "The company's security design principles this branch breaks. An enforced principle stands behind every threat that carries principle:SDP-n, and behind each INV rule's threat when intent.md says the rule comes from it ('(principle: SDP-n)'). A break is a new exposure of such a threat with no control (from guardlink diff), or a confirmed claim of one on a changed file. A break in code a live exception covers is set aside and named. principles.md is checked too: a file that no longer matches what people adopted cannot be trusted to say what is enforced."
208
+ export function principleChanges(root, run, options, fresh, confirmed, now = new Date()) {
209
+ const check = checkPrinciples(principlesReader(root), now);
210
+ if (!check.exists) return { breaks: [], excepted: [], problems: [] };
211
+ const problems = check.ok ? [] : check.problems;
212
+ const enforced = new Map(check.adopted.filter((p) => p.kind === 'enforced').map((p) => [p.id, p]));
213
+ if (!enforced.size || (!fresh.length && !confirmed.length)) return { breaks: [], excepted: [], problems };
214
+ const model = runJson(run, 'guardlink parse', 'guardlink', ['parse', '.'], options);
215
+ if (!model.ok) return model;
216
+ const bare = (id) => String(id ?? '').replace(/^#/, '');
217
+ const fromRule = new Map();
218
+ try {
219
+ for (const line of readFileSync(join(root, '.guardlink', 'intent.md'), 'utf8').split(/\r?\n/)) {
220
+ const m = /^\s*[-*]\s+(INV-\d+)\s*:.*\(principles?:\s*([^)]*)\)/i.exec(line);
221
+ if (m) fromRule.set(m[1].toUpperCase(), [...m[2].matchAll(/\bSDP-[1-9][0-9]{0,3}\b/g)].map((x) => x[0]));
222
+ }
223
+ } catch {
224
+ /* no intent */
225
+ }
226
+ const byThreat = new Map();
227
+ for (const t of Array.isArray(model.json?.threats) ? model.json.threats : []) {
228
+ const refs = (Array.isArray(t?.external_refs) ? t.external_refs : []).map(String);
229
+ const ids = new Set();
230
+ for (const r of refs) {
231
+ const p = /^principle:(SDP-[1-9][0-9]{0,3})$/i.exec(r);
232
+ if (p) ids.add(p[1].toUpperCase());
233
+ const inv = /^intent:(INV-\d+)$/i.exec(r);
234
+ if (inv) for (const x of fromRule.get(inv[1].toUpperCase()) ?? []) ids.add(x);
235
+ }
236
+ const kept = [...ids].filter((x) => enforced.has(x));
237
+ if (kept.length) byThreat.set(bare(t.id), kept);
238
+ }
239
+ const breaks = [];
240
+ const excepted = [];
241
+ const consider = (c, how) => {
242
+ for (const id of byThreat.get(bare(c?.threat)) ?? []) {
243
+ const files = [c?.location?.file, c?.location?.origin_file].filter((f) => typeof f === 'string');
244
+ const e = files.map((f) => exceptionFor(check.exceptions, id, f, now)).find(Boolean);
245
+ const row = { principle: enforced.get(id), claim: c, how };
246
+ if (e) excepted.push({ ...row, exception: e });
247
+ else breaks.push(row);
248
+ }
249
+ };
250
+ for (const c of fresh) consider(c, 'a new exposure with no control');
251
+ for (const c of confirmed) consider(c, 'confirmed by a test');
252
+ return { breaks, excepted, problems };
253
+ }
254
+
255
+ // @comment -- "Counts a principle's gate stop on this machine, for the dashboard's value line: one JSON line per principle per stop under <git-common-dir>/bravos/, never committed. Best effort; a failure never changes the gate's answer."
256
+ function recordStops(root, env, run, ids) {
257
+ try {
258
+ const r = run('git', ['rev-parse', '--path-format=absolute', '--git-common-dir'], { cwd: root, env });
259
+ if (r.status !== 0 || !r.stdout.trim()) return;
260
+ const dir = join(r.stdout.trim(), 'bravos');
261
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
262
+ const at = new Date().toISOString();
263
+ appendFileSync(join(dir, 'principles-gate.jsonl'), [...new Set(ids)].map((principle) => JSON.stringify({ at, principle })).join('\n') + '\n', { mode: 0o600 });
264
+ } catch {
265
+ /* the count is a courtesy */
266
+ }
267
+ }
268
+
206
269
  function changeReview(root, base, env, run) {
207
270
  const o = { cwd: root, env, timeoutMs: 4000 };
208
271
  const patch = run('git', gitPatchArgs(base, 'HEAD'), o);
@@ -268,6 +331,7 @@ export function runGate({ root, action, command, cwd = root, env = process.env,
268
331
  // (b) each new unmitigated exposure is disclosed in the PR body by its threat and asset ids.
269
332
  const diff = runJson(run, `guardlink diff ${base}`, 'guardlink', ['diff', base, '--json'], o);
270
333
  const fresh = diff.ok ? diff.json?.newUnmitigatedExposures : undefined;
334
+ let confirmedOnChanged = [];
271
335
  if (!diff.ok) unknown(diff);
272
336
  else if (!Array.isArray(fresh)) unknown({ error: `guardlink diff ${base} JSON has no newUnmitigatedExposures` });
273
337
  else if (fresh.length > 0) {
@@ -303,6 +367,7 @@ export function runGate({ root, action, command, cwd = root, env = process.env,
303
367
  else {
304
368
  const changed = new Set(names.stdout.split('\0').filter(Boolean));
305
369
  const relevant = confirmed.filter(c => changed.has(c?.location?.file) || changed.has(c?.location?.origin_file));
370
+ confirmedOnChanged = relevant;
306
371
  const sameClaimSite = (a, b) => a.threat === b.threat && a.asset === b.asset && a.location.file === b.location.file &&
307
372
  (a.location.line === b.location.line || (a.location.anchor?.scope === 'symbol' && b.location.anchor?.scope === 'symbol' &&
308
373
  a.location.anchor.start_line === b.location.anchor.start_line && a.location.anchor.hash === b.location.anchor.hash));
@@ -364,6 +429,22 @@ export function runGate({ root, action, command, cwd = root, env = process.env,
364
429
  if (design.untested.length) notes.push(`bravos pre-PR gate: this branch changes code under design rule(s) no test has tried yet (bravos rules lists them):\n${design.untested.map(line).join('\n')}`);
365
430
  }
366
431
 
432
+ // (f) the company's security design principles: a break of an enforced one blocks whatever the PR body says, unless
433
+ // a live exception a named person approved covers that code; a principles.md that no longer matches the adoptions blocks too.
434
+ // @mitigates #principles against #principle-bypass using #principle-gate -- "A branch that adds an uncontrolled exposure of an enforced principle's threat, or carries a confirmed break of one on changed code, cannot open or ready a PR, and disclosure in the body does not let it through; only a live exception a person approved covers the code"
435
+ // @mitigates #principles against #forged-principle using #adoption-fingerprint -- "The gate refuses a PR while principles.md does not match the confirmed adoptions or an exception has ended"
436
+ const principled = principleChanges(root, run, o, Array.isArray(fresh) ? fresh : [], confirmedOnChanged);
437
+ if (principled.error) unknown(principled);
438
+ else {
439
+ const where = (c) => `${c?.threat ?? '?'} on ${c?.asset ?? '?'} at ${c?.location?.file ?? '?'}:${c?.location?.line ?? '?'}`;
440
+ if (principled.problems.length) blocks.push(`.guardlink/principles.md does not match what people adopted, so what this repository enforces cannot be trusted. bravos principles check lists it; bravos principles write rewrites the file from the adoptions:\n${principled.problems.map((p) => ` - ${p}`).join('\n')}`);
441
+ if (principled.breaks.length) {
442
+ blocks.push(`this branch breaks the team's security design principles. Fix the code, or a person approves an exception for it (bravos principles except, at their own terminal); naming it in the PR body is not enough:\n${principled.breaks.map((b) => ` - ${b.principle.id} "${b.principle.statement}": ${where(b.claim)} — ${b.how}`).join('\n')}`);
443
+ recordStops(root, env, run, principled.breaks.map((b) => b.principle.id));
444
+ }
445
+ for (const x of principled.excepted) notes.push(`Under an approved exception: ${x.principle.id} at ${where(x.claim)} — ${x.exception.reason} (approved by ${x.exception.by}, until ${x.exception.until}).`);
446
+ }
447
+
367
448
  const review = changeReview(root, base, env, run);
368
449
  if (review) notes.push(review);
369
450
  if (blocks.length > 0) return { decision: 'block', reason: ['bravos pre-PR gate: blocked.', ...blocks.map((b) => `- ${b}`), ...notes].join('\n') };