@bugb-technologies/bravos 1.6.0 → 1.8.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 (42) hide show
  1. package/dist/cli.js +82 -17
  2. package/dist/codegraph.js +21 -0
  3. package/dist/context.js +36 -0
  4. package/dist/graphbin.js +2 -0
  5. package/dist/guide.js +7 -5
  6. package/dist/help.js +24 -5
  7. package/dist/install.js +2 -1
  8. package/dist/lock.js +1 -0
  9. package/dist/mcp.js +18 -3
  10. package/dist/palette.js +4 -4
  11. package/dist/prefs.js +47 -0
  12. package/dist/review-server.js +4 -4
  13. package/dist/review-wait.js +76 -0
  14. package/dist/review.js +103 -18
  15. package/dist/start/answers.js +33 -4
  16. package/dist/start/index.js +138 -57
  17. package/dist/upkeep.js +89 -0
  18. package/dist/watch-frame.js +67 -42
  19. package/dist/watch.js +21 -7
  20. package/docs/GUIDE.md +17 -5
  21. package/docs/UPGRADING.md +27 -0
  22. package/hooks/lib/autopilot.mjs +3 -18
  23. package/hooks/lib/briefing.mjs +250 -173
  24. package/hooks/lib/graph-autobuild.mjs +131 -0
  25. package/hooks/lib/palette.mjs +4 -4
  26. package/hooks/lib/prefs.mjs +108 -0
  27. package/hooks/lib/refresh.mjs +45 -1
  28. package/hooks/lib/setup.mjs +1 -1
  29. package/hooks/lib/snapshot.mjs +19 -1
  30. package/hooks/session-start.mjs +29 -2
  31. package/package.json +1 -1
  32. package/skills/bravos/SKILL.md +4 -3
  33. package/skills/bravos-annotate/SKILL.md +2 -2
  34. package/skills/bravos-context/SKILL.md +7 -6
  35. package/skills/bravos-env/SKILL.md +2 -2
  36. package/skills/bravos-env/scope.example.yaml +2 -1
  37. package/skills/bravos-prove/SKILL.md +2 -2
  38. package/skills/bravos-recheck/SKILL.md +1 -1
  39. package/skills/bravos-resync/SKILL.md +1 -1
  40. package/skills/bravos-ship/SKILL.md +1 -1
  41. package/skills/bravos-templatize/SKILL.md +1 -1
  42. package/templates/review/review.html +369 -124
@@ -4,9 +4,10 @@ import { accessSync, constants, readFileSync } from 'node:fs';
4
4
  import { basename, delimiter, dirname, join } from 'node:path';
5
5
  import { contextGate, readContext } from './context.mjs';
6
6
  import { THEMES } from './palette.mjs';
7
+ import { commitsLine, commonDirFrom, readHandoff, readPrefs } from './prefs.mjs';
7
8
  import { readProving } from './proving.mjs';
8
9
  import { planLabel, planLine, status as licenceStatus } from './licence.mjs';
9
- import { refreshIfDue } from './refresh.mjs';
10
+ import { readLicenceNote, refreshIfDue } from './refresh.mjs';
10
11
  import { gitStaleness, staleLine, staleness, strandedBranches, strandedLine } from './resync.mjs';
11
12
  import { readSast, sastAvailable, sastLine } from './sast.mjs';
12
13
  import { hooksLocked, readSetup, setupLine, TRIAL } from './setup.mjs';
@@ -132,9 +133,11 @@ export function contextLine(context, harness) {
132
133
  }
133
134
 
134
135
  // @comment -- "The briefing's Intent line. While the context gate is closed it also says so in words an agent acts on: do not start threat-modelling, run the context skill first, and how a person declines. A recorded decline is shown with the name and date of the person who made it."
135
- function intentLine(intent, harness, gate) {
136
+ function intentLine(intent, harness, gate, handoff = false) {
136
137
  const run = harness === 'claude' ? '/bravos-context' : 'the bravos-context skill';
137
- const closed = gate && gate.open === false ? `. Context comes first: do not annotate or start a campaign until a named person has confirmed it (or run bravos context decline --by "<name>" themselves).` : '';
138
+ // Right after bravos start (a fresh hand-off marker), the person expects Bravos to begin: the agent starts the context step itself and goes on to annotation, unless their first message asks for something else.
139
+ const begin = handoff && intent.status === 'none' ? ` Setup just finished here and the person expects Bravos to begin: start ${run} in your first reply without being asked, and go on to annotation once they have confirmed. If their first message asks for something else, do that and offer this once after.` : '';
140
+ const closed = gate && gate.open === false ? `. Context comes first: do not annotate or start a campaign until a named person has confirmed it (or run bravos context decline --by "<name>" themselves).${begin}` : '';
138
141
  const declined = gate?.state === 'declined' ? `declined by ${gate.by} on ${gate.at}` : '';
139
142
  if (intent.status === 'none') return declined ? `Intent: ${declined} — severities are not calibrated to the product; ${run} when the team is ready` : `Intent: none — severities are not calibrated to the product; run ${run}${closed}`;
140
143
  if (intent.status === 'draft') return `Intent: draft (${intent.invariants} invariants, ${intent.drafts} items unconfirmed${declined ? `; context ${declined}` : ''}) — confirm with ${run}${closed}`;
@@ -159,7 +162,8 @@ function coachLines(i) {
159
162
  'How to help this person (offer, never lecture; one offer per topic per session):',
160
163
  `- In your first reply, if setup is under 5 or intent is none, offer once in plain words three starts that fit this repo, in setup order (${i.licence?.licensed === false ? 'on the Free plan: learn what the app intends, annotate the uncovered files, prove the top threats; never lead with a Team-plan step' : 'build the code graph first if it is off, then learn what the app intends, annotate the uncovered files, run SAST, prove the top threats; or check this branch before a PR'}) and \`bravos guide\` for more; then follow their lead.`,
161
164
  `- After you edit security-relevant code, offer to record what it exposes (${k('bravos-annotate')}); before a PR, run the ship check (${k('bravos-ship')}); after a fix, offer a recheck (${k('bravos-recheck')}).`,
162
- '- Commits are the person\'s call: before the first commit of a session ask once (commit now, or leave the files for them to review), even where a skill says to commit; skip the question only when they already asked for commits (a campaign, a schedule).',
165
+ // A standing answer is the briefing's Commits line; with none, ask once and (unless they chose to be asked each time) record it so no later session asks.
166
+ ...(commitsLine(i.prefs) ? [] : [`- Commits are the person's call: before the first commit of a session ask once (commit now, or leave the files for them to review), even where a skill says to commit; skip the question only when they already asked for commits (a campaign, a schedule).${i.prefs?.commits?.value === 'ask' ? '' : ' Then ask whether that is their answer from now on, and if so record it with `bravos prefs set commits commit|leave --by "<their name>"`: their answer and their name, never yours.'}`]),
163
167
  '- When a request would go better with the next unlock above, say what it would add, once. Plain words first, skill name second. Never send test traffic without the authorization bravos-env asks for.',
164
168
  '- Once, when it helps them follow along, mention that `bravos watch` in a second terminal pane shows this live as you work (free, read-only), and that `bravos dashboard` opens the findings as one page in their browser (rebuilt from the code each time; never open a saved copy instead).',
165
169
  );
@@ -232,9 +236,12 @@ export function buildBriefing(inputs) {
232
236
  else if (i.inFlight.prs > 0 || i.inFlight.files > 0) {
233
237
  tail.push(`In flight by teammates: ${i.inFlight.files} files in ${i.inFlight.prs} open PRs`);
234
238
  }
235
- if (i.intent && typeof i.intent === 'object') tail.push(intentLine(i.intent, i.harness, i.gate));
239
+ if (i.intent && typeof i.intent === 'object') tail.push(intentLine(i.intent, i.harness, i.gate, i.handoff === true));
236
240
  const documents = contextLine(i.context, i.harness);
237
241
  if (documents) tail.push(documents);
242
+ // The person's standing answer about commits, when they gave one (hooks/lib/prefs.mjs).
243
+ const commits = commitsLine(i.prefs);
244
+ if (commits) tail.push(commits);
238
245
  if (i.proving && typeof i.proving === 'object') {
239
246
  const p = i.proving;
240
247
  tail.push(p.status === 'set'
@@ -247,6 +254,10 @@ export function buildBriefing(inputs) {
247
254
  ? `Note: this repo's bravos (${i.shadow.repo}) is behind the person's user-level copy (${i.shadow.user}), which Claude Code uses; suggest they run bravos sync in this repo from their own terminal`
248
255
  : `Note: the person's user-level bravos skills (~/.claude/skills, ${i.shadow.user}) are used instead of this repo's (${i.shadow.repo}); tell them to run bravos sync --global from their own terminal, then start a new session`);
249
256
  }
257
+ const upkeep = upkeepLine(i.upkeep);
258
+ if (upkeep) tail.push(upkeep);
259
+ // The portal's last refusal to renew this machine, until it is signed in again (a revocation) or renewed (a plan that ended).
260
+ if (i.licenceNote && (i.licenceNote.outcome === 'lapsed' || i.licence?.licensed === false)) tail.push(`Licence: ${i.licenceNote.note} Tell the person once, in plain words.`);
250
261
  if ((i.autopilot || i.prePr) && hooksLocked(i)) {
251
262
  // The repo registers the hooks for everyone; this person's copy answers nothing until they have a licence.
252
263
  const which = i.autopilot ? 'Autopilot (the end-of-turn check and the pre-PR gate)' : 'The pre-PR gate';
@@ -254,6 +265,7 @@ export function buildBriefing(inputs) {
254
265
  } else if (i.autopilot) tail.push('Autopilot: on — at turn end, review changed behavior in new and annotated files and follow the proving choice for affected claims');
255
266
  if (i.codegraph === 'current') tail.push('Code graph: current');
256
267
  else if (i.codegraph === 'cli') tail.push('Code graph: ask it with `bravos graph <question> --json` (same answers as the codegraph_ tools; e.g. attack-surface, entry-points, callers, reachable-sinks, call-chain); if it says no graph, build it: bravos graph build . (bravos-codegraph)');
268
+ else if (i.codegraph === 'not-built' && i.graphBuild) tail.push('Code graph: none for this commit yet — bravos is building it in the background now (no tokens, a few minutes): do not start another build. Ask the graph again in a few minutes; until then skills trace routes by reading.');
257
269
  else if (i.codegraph === 'not-built') tail.push('Code graph: none for this commit — bravos keys a graph to the commit it was built at, so a new commit needs a rebuild: bravos graph build . --scip no-exec (bravos-codegraph; no tokens, a few minutes). Until then skills trace routes by reading.');
258
270
  else if (i.codegraph === 'diverged') tail.push('Code graph: diverged — rebuild with codegraph-build --scip no-exec');
259
271
  else if (i.codegraph === 'locked') tail.push('Code graph: on the Team plan (see Plan above) — skills trace routes by reading until then');
@@ -388,6 +400,43 @@ export async function probeGraph(root, env, timeoutMs = 3000) {
388
400
  return 'cli';
389
401
  }
390
402
 
403
+ // @comment -- "Asks the installed bravos what has fallen behind it here (bravos upkeep --json: read-only, no network, well under a second), only where the repository carries Bravos's files. Null when bravos is not on PATH, is too old to know the command, does not answer in time, or BRAVOS_UPKEEP_PROBE=off."
404
+ export async function probeUpkeep(root, env, timeoutMs = 3000) {
405
+ if (env.BRAVOS_UPKEEP_PROBE === 'off' || !whichOnPath('bravos', env)) return null;
406
+ try {
407
+ accessSync(join(root, '.bravos', 'skills.lock'), constants.R_OK);
408
+ } catch {
409
+ return null;
410
+ }
411
+ const r = await capture('bravos', ['upkeep', root, '--json'], { cwd: root, env, timeoutMs });
412
+ if (r.timedOut || r.error || r.status !== 0) return null;
413
+ try {
414
+ const j = JSON.parse(r.stdout);
415
+ return j?.schema === 'bravos.upkeep/v1' ? j : null;
416
+ } catch {
417
+ return null;
418
+ }
419
+ }
420
+
421
+ const VERSION_RE = /^\d+(?:\.\d+){0,3}(?:-[A-Za-z0-9.]{1,20})?$/;
422
+ // @comment -- "The briefing's Upkeep line: what the agent repairs by itself. A repository whose Bravos files are behind the installed bravos gets `bravos sync`; a staged bundle older than this bravos pins gets `bravos setup` (Bravos's own signed bundles, nothing third-party). When the repository is the newer side the agent is told not to sync, because an older bravos would roll it back, and to tell the person to update. Only version numbers, counts and the two known bundle names from the answer reach the text."
423
+ export function upkeepLine(u) {
424
+ if (!u || typeof u !== 'object') return null;
425
+ const ver = (v) => (typeof v === 'string' && VERSION_RE.test(v) ? v : null);
426
+ const cli = ver(u.cli);
427
+ const parts = [];
428
+ const files = Number.isInteger(u.sync?.files) && u.sync.files > 0 ? u.sync.files : 0;
429
+ if (files && cli) {
430
+ const repo = ver(u.repo);
431
+ const count = `${files} file${files === 1 ? '' : 's'}`;
432
+ if (u.sync.direction === 'repo-newer') parts.push(`this repository's Bravos files${repo ? ` (${repo})` : ''} are newer than the installed bravos (${cli}): do not run bravos sync from this machine, it would roll them back; tell the person once to update with npm install -g @bugb-technologies/bravos@latest`);
433
+ else parts.push(`this repository's Bravos files are behind the installed bravos (${repo && repo !== cli ? `${repo} → ${cli}, ` : ''}${count}): run \`bravos sync\` now without asking and include what it changes in your next commit of Bravos's files`);
434
+ }
435
+ const bundles = (Array.isArray(u.bundles) ? u.bundles : []).filter((b) => ['analyzer', 'codegraph'].includes(b?.id) && ver(b.staged) && ver(b.pinned));
436
+ if (bundles.length) parts.push(`the ${bundles.map((b) => `${b.id} bundle (${b.staged} → ${b.pinned})`).join(' and ')} on this machine ${bundles.length === 1 ? 'is' : 'are'} older than this bravos pins: run \`bravos setup\` now without asking (it fetches Bravos's own signed bundles and nothing else)`);
437
+ return parts.length ? `Upkeep: ${parts.join('; ')}.` : null;
438
+ }
439
+
391
440
  export async function collect(root, env, { deadlineMs = 20000, nextCount = 3 } = {}) {
392
441
  const deadline = Date.now() + deadlineMs;
393
442
  const budget = () => Math.min(10000, Math.max(0, deadline - Date.now()));
@@ -400,10 +449,12 @@ export async function collect(root, env, { deadlineMs = 20000, nextCount = 3 } =
400
449
  return r.timedOut || r.error || r.status !== 0 ? null : r.stdout.trim();
401
450
  };
402
451
  const gitFacts = (async () => {
403
- const [sha, ref, branch] = await Promise.all([
452
+ const [sha, ref, branch, common] = await Promise.all([
404
453
  git(['rev-parse', '--short', 'HEAD']),
405
454
  git(['symbolic-ref', '-q', '--short', 'refs/remotes/origin/HEAD']),
406
455
  git(['rev-parse', '--abbrev-ref', 'HEAD']),
456
+ // Where this clone keeps its own state: the person's preferences live there, out of any commit's reach.
457
+ git(['rev-parse', '--git-common-dir']),
407
458
  ]);
408
459
  const base = ref || 'origin/main';
409
460
  const name = branch && branch !== 'HEAD' ? branch : null;
@@ -419,6 +470,7 @@ export async function collect(root, env, { deadlineMs = 20000, nextCount = 3 } =
419
470
  ]);
420
471
  return {
421
472
  sha: sha ?? 'unknown',
473
+ commonDir: commonDirFrom(root, common),
422
474
  defaultBranch: defaultHead ? ref : null,
423
475
  base,
424
476
  branch: name,
@@ -444,12 +496,13 @@ export async function collect(root, env, { deadlineMs = 20000, nextCount = 3 } =
444
496
  });
445
497
 
446
498
  const graphRun = probeGraph(root, env, Math.min(3000, first));
499
+ const upkeepRun = probeUpkeep(root, env, Math.min(3000, first)).catch(() => null);
447
500
  // A signed-in machine's device licence is renewed here when it is due, alongside the other facts and under a short timeout of its own; it fails open, so a slow or absent portal only means the held token is read as it is.
448
501
  const renewal = refreshIfDue(env, { timeoutMs: Math.min(3000, first) }).catch(() => null);
449
502
  // At an app folder, each member's counts come from its own guardlink ci, alongside the rest.
450
503
  const workspace = readWorkspace(root);
451
504
  const countsRun = workspace?.isAppFolder && hasGuardlink ? memberCounts(workspace, runJsonAsync, env, first) : Promise.resolve(null);
452
- const [facts, pr, graphState, workspaceCounts, , ...gl] = await Promise.all([gitFacts, prRun, graphRun, countsRun, renewal, ...glRuns]);
505
+ const [facts, pr, graphState, workspaceCounts, , upkeep, ...gl] = await Promise.all([gitFacts, prRun, graphRun, countsRun, renewal, upkeepRun, ...glRuns]);
453
506
 
454
507
  let guardlink = 'missing';
455
508
  if (hasGuardlink) {
@@ -485,6 +538,11 @@ export async function collect(root, env, { deadlineMs = 20000, nextCount = 3 } =
485
538
  intent: readIntent(root),
486
539
  context: readContext(root),
487
540
  gate: contextGate(root),
541
+ prefs: readPrefs(facts.commonDir),
542
+ handoff: readHandoff(facts.commonDir),
543
+ upkeep,
544
+ // Read after the renewal above has run, so a refusal that just arrived is in it.
545
+ licenceNote: readLicenceNote(env),
488
546
  annotationMode: readAnnotationMode(root),
489
547
  // bravos on PATH: what its probe says (a graph for this commit or not); else codegraph-mcp on PATH means the MCP route.
490
548
  codegraph: graphState ?? (whichOnPath('codegraph-mcp', env) ? 'unknown' : 'unavailable'),
@@ -505,7 +563,6 @@ export async function collect(root, env, { deadlineMs = 20000, nextCount = 3 } =
505
563
  // Startup banner: shown to the human (systemMessage), never added to the model's context.
506
564
  // ---------------------------------------------------------------------------------------------
507
565
 
508
- const BANNER_WIDTH = 80;
509
566
  // A large shadowed wordmark, six rows, built letter by letter so every row has the same width.
510
567
  const GLYPHS = {
511
568
  B: ['██████╗ ', '██╔══██╗', '██████╔╝', '██╔══██╗', '██████╔╝', '╚═════╝ '],
@@ -516,7 +573,7 @@ const GLYPHS = {
516
573
  S: ['███████╗', '██╔════╝', '███████╗', '╚════██║', '███████║', '╚══════╝'],
517
574
  };
518
575
  export const LOGO = Array.from({ length: 6 }, (_, r) => [...'BRAVOS'].map((c) => GLYPHS[c][r]).join(''));
519
- const LOGO_WIDTH = Math.max(...LOGO.map((l) => [...l].length));
576
+
520
577
  // bravos's mascot: a hooded figure with two glowing eyes, eleven rows, left-right symmetric; ▓ is the hood, █ the eyes.
521
578
  export const MASCOT = [
522
579
  ' ▄▄▓▓▓▓▓▓▄▄ ',
@@ -531,8 +588,26 @@ export const MASCOT = [
531
588
  ' ▄▓▓▓▓▄▄▄▄▄▄▄▄▄▄▓▓▓▓▄ ',
532
589
  ' ▓▓▓▓▓▓▓▓ ▐ ▌ ▓▓▓▓▓▓▓▓ ',
533
590
  ];
534
- const MASCOT_WIDTH = 26;
535
- const LEFT_WIDTH = 36;
591
+ // The supplied Bravos mark, sampled as two vertical pixels per terminal cell.
592
+ // MASCOT and LOGO above remain available to earlier review and export clients.
593
+ export const BRAVOS_MARK = [
594
+ ' ▄▄██████▄▄',
595
+ ' ▄████████████▄',
596
+ ' ▄██████████████▄',
597
+ ' ████████████████',
598
+ ' ████████████████',
599
+ ' ████████████████',
600
+ '████ ████████████████ ████',
601
+ '████ ████████████████ ████',
602
+ '████ ██▀ ▀████▀ ▀██ ████',
603
+ '████▄ ██▄ ▄████▄ ▄██ ▄████',
604
+ ' ██████████████████████████████',
605
+ ' ▀▀████████████████████████▀▀',
606
+ ' ▄████▀▀████▄',
607
+ ' ▄▄████ ████▄▄',
608
+ ' ██████████▀ ▀██████████',
609
+ ' ███████▀▀ ▀▀███████',
610
+ ];
536
611
  // Two lines, so the plan nudge below the counts has room. The pre-PR gate is named only to people who have it.
537
612
  const INTRO_HEAD = 'bravos makes this agent a guardlink power user: it keeps the threat model beside';
538
613
  const INTRO_TEAM = 'the code, proves exposures on targets you own, and gates pull requests.';
@@ -691,124 +766,180 @@ const TIPS = [
691
766
  ];
692
767
  const dayNumber = () => Math.floor(Date.now() / 86400000);
693
768
 
694
- function countsLine(g) {
769
+ function bannerMetrics(g) {
770
+ if (!g.ci) return null;
695
771
  const ci = g.ci;
696
- if (!ci) return 'threat counts unknown (guardlink ci unavailable)';
697
772
  const s = ci.summary ?? {};
698
773
  const list = arr(ci.exposures);
699
774
  const by = s.by_severity ?? Object.fromEntries(SEVERITIES.map((k) => [k, list.filter((e) => e?.severity === k).length]));
700
- const total = typeof s.exposures === 'number' ? s.exposures : list.length;
701
- const sev = SEVERITIES.filter((k) => num(by[k]) > 0).map((k) => `${num(by[k])} ${k}`);
702
- let line = `${total} open${sev.length ? ` (${sev.join(', ')})` : ''} · ${arr(ci.confirmed).length} confirmed`;
703
- if (s.coverage) line += ` · coverage ${num(s.coverage.percent)}% (${num(s.coverage.annotated_files)}/${num(s.coverage.source_files)})`;
704
- return line;
775
+ return {
776
+ total: typeof s.exposures === 'number' ? s.exposures : list.length,
777
+ severities: SEVERITIES.filter((k) => num(by[k]) > 0).map((k) => `${num(by[k])} ${k}`),
778
+ confirmed: arr(ci.confirmed).length,
779
+ coverage: s.coverage,
780
+ };
705
781
  }
706
782
 
707
- // @comment -- "The banner's one-line state: intent, code graph, the two hooks, SAST and the setup score. A locked code graph says locked, never on. The full wording is kept while it fits 80 columns; past that it shortens in steps (one word for both hooks when they agree, PR for pre-PR, reach. for reachable, then the bare count) so the line is never cut mid-word."
708
- function statusLine(i) {
709
- const intent = i.intent?.status ?? 'unknown';
710
- const graph = i.codegraph === 'unavailable' ? 'graph off' : i.codegraph === 'not-built' ? 'graph none' : i.codegraph === 'diverged' ? 'graph stale' : i.codegraph === 'locked' ? 'graph locked' : 'graph on';
711
- const setup = i.root ? readSetup(i.root, i, i.harness) : null;
712
- const hook = (on) => (!on ? 'off' : hooksLocked(i) ? 'locked' : 'on');
713
- const [pr, auto] = [hook(i.prePr), hook(i.autopilot)];
714
- const build = (level) => {
715
- const hooks = level >= 1 && pr === auto ? `hooks ${pr}` : `${level >= 2 ? 'PR' : 'pre-PR'} ${pr} · auto ${auto}`;
716
- const sast = i.sast?.summary ? `sast ${i.sast.summary.reachable}${level >= 4 ? '' : level >= 3 ? ' reach.' : ' reachable'}` : i.sast?.available?.ok ? 'sast not run' : 'sast off';
717
- return `intent ${intent} · ${graph} · ${hooks} · ${sast}${setup ? ` · setup ${setup.done}/${setup.total}` : ''}`;
718
- };
719
- for (let level = 0; level < 4; level++) if (build(level).length <= BANNER_WIDTH) return build(level);
720
- return build(4);
783
+ function countsLine(g) {
784
+ const m = bannerMetrics(g);
785
+ if (!m) return 'threat counts unknown (guardlink ci unavailable)';
786
+ const c = m.coverage;
787
+ return `${m.total} open${m.severities.length ? ` (${m.severities.join(', ')})` : ''} · ${m.confirmed} confirmed` +
788
+ (c ? ` · coverage ${num(c.percent)}% (${num(c.annotated_files)}/${num(c.source_files)})` : '');
721
789
  }
722
790
 
723
- /**
724
- * Builds the startup banner for the human: logo, repo and counts, top threats (or FIX NOW) beside a
725
- * state-driven quick start, and a short introduction while the product's intent is not recorded.
726
- * Plain text, no ANSI; every line ≤ 80 columns; 35 lines at most with the introduction, 29 without.
727
- */
728
- // @comment -- "Pure text builder for the user-facing startup banner; reads only the inputs collect() already gathered, never throws on partial inputs."
729
- export function buildBanner(inputs, opts = {}) {
730
- const i = inputs ?? {};
731
- const harness = opts.harness ?? (i.harness === 'claude' ? 'claude' : 'other');
732
- // The mascot on the left; the wordmark beside its face, the repo facts beside its shoulders.
733
- const room = BANNER_WIDTH - MASCOT_WIDTH - 2;
734
- const facts = [
735
- [`bravos${opts.version ? ` ${opts.version}` : ''}`, i.repo].filter(Boolean).join(' · '),
736
- [i.branch, i.sha ? `@ ${i.sha}` : ''].filter(Boolean).join(' '),
737
- ];
738
- // The plan sits on the row between the wordmark and the repo facts, so it costs no line; nothing is shown while the licence is unknown.
739
- const plan = i.licence && typeof i.licence === 'object' && i.licence.state ? planLabel(i.licence) : null;
740
- const header = ['', '', ...LOGO, plan ? `Plan: ${plan.label}` : '', ...facts];
741
- const lines = MASCOT.map((row, r) => `${row} ${fit(header[r] ?? '', room)}`);
791
+ // Plain printable cells only: repository metadata goes into the human's terminal.
792
+ const clean = (s) => String(s ?? '').replace(/[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g, ' ');
793
+ function cellWidth(c) {
794
+ if (/\p{Mark}/u.test(c)) return 0;
795
+ return /[\u1100-\u115f\u2e80-\ua4cf\uac00-\ud7a3\uf900-\ufaff\ufe10-\ufe19\ufe30-\ufe6f\uff01-\uff60\uffe0-\uffe6\u{20000}-\u{3fffd}]|\p{Extended_Pictographic}/u.test(c) ? 2 : 1;
796
+ }
797
+ const cells = (s) => [...s].reduce((n, c) => n + cellWidth(c), 0);
798
+ function clipped(value, width) {
799
+ const s = clean(value);
800
+ if (cells(s) <= width) return s;
801
+ let out = '';
802
+ let used = 0;
803
+ for (const c of s) {
804
+ used += cellWidth(c);
805
+ if (used >= width) break;
806
+ out += c;
807
+ }
808
+ return out + '…';
809
+ }
810
+ function paired(left, right, leftWidth) {
811
+ const l = clipped(left, leftWidth);
812
+ return l + ' '.repeat(leftWidth - cells(l)) + ' │ ' + right;
813
+ }
742
814
 
743
- if (i.guardlink === 'missing') {
744
- lines.push('', 'guardlink not found on PATH — run bravos doctor');
745
- const out = lines.map((l) => fit(l.trimEnd(), BANNER_WIDTH));
746
- return (opts.color ? colorize(out, i, opts.theme) : out).join('\n');
747
- }
748
- const g = i.guardlink ?? {};
749
- lines.push('', countsLine(g), statusLine(i));
750
- // One plan nudge at most: hooks this repo registers but this person cannot run, a lapsed licence, or what Team would add.
815
+ function bannerWarnings(i, plan) {
816
+ const lines = [];
751
817
  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`);
752
818
  else if (plan && !plan.licensed && i.licence.state === 'expired') lines.push(`~ licence expired: ${TEAM_ADDS} locked · bravos licence`);
753
819
  else if (plan && !plan.licensed) lines.push(`~ Team adds ${TEAM_ADDS} · bravos account activate`);
754
- if (i.stale) lines.push(`! ${i.branch ?? 'this checkout'} is ${i.stale.behind} behind ${i.base} · findings describe older code · bravos-resync`);
755
- else if (arr(i.stranded).length > 0) lines.push(`~ annotation work on ${i.stranded[0].branch} is not on ${i.base} · bravos-resync`);
820
+ if (i.stale) lines.push(`! Findings describe older code · ${i.stale.behind} behind ${clean(i.base)} · bravos-resync`);
821
+ else if (arr(i.stranded).length > 0) lines.push(`~ Work on ${clean(i.stranded[0].branch)} is not on ${clean(i.base)} · bravos-resync`);
756
822
  if (i.shadow) {
757
823
  lines.push(i.shadow.userNewer
758
824
  ? `~ repo bravos ${i.shadow.repo} is behind your ${i.shadow.user} · run: bravos sync`
759
825
  : `! your user-level bravos ${i.shadow.user} overrides repo ${i.shadow.repo} · run: bravos sync --global`);
760
826
  }
761
- lines.push('');
827
+ return lines;
828
+ }
829
+
830
+ // Wrap at words so a warning's recovery command and a long setup instruction remain visible.
831
+ function wrap(text, width) {
832
+ const normalized = clean(text);
833
+ if (cells(normalized) <= width) return [normalized];
834
+ const rows = [''];
835
+ for (const word of normalized.split(/\s+/)) {
836
+ const i = rows.length - 1;
837
+ const next = rows[i] ? rows[i] + ' ' + word : word;
838
+ if (rows[i] && cells(next) > width) rows.push(clipped(word, width));
839
+ else rows[i] = clipped(next, width);
840
+ }
841
+ return rows;
842
+ }
762
843
 
844
+ // @comment -- "Renders the human's session briefing from collected facts. The supplied symbol and repo facts share the header; on wide terminals the real setup checklist sits beside confirmed findings. Known-free plans get free commands; missing CI counts and stale checkouts are identified before showing findings. Commands follow the harness syntax and untrusted repo text is cleaned before applying terminal colours."
845
+ export function buildBanner(inputs, opts = {}) {
846
+ const i = inputs ?? {};
847
+ const harness = opts.harness ?? i.harness ?? 'other';
848
+ const sk = (name) => (SIGIL[harness] ?? '') + name;
849
+ // Allow the host's four-column hook indent. Piped hooks with unknown terminal size use the 80-column design.
850
+ const columns = Number(opts.columns);
851
+ const width = Number.isSafeInteger(columns) && columns > 0 ? Math.max(1, Math.min(118, columns - 4)) : 76;
852
+ const wide = width >= 116;
853
+ const g = i.guardlink ?? {};
854
+ const m = bannerMetrics(g);
855
+ const plan = i.licence?.state ? planLabel(i.licence) : null;
856
+ const version = 'Bravos' + (opts.version ? ' ' + opts.version : '');
857
+ const coverage = m?.coverage;
858
+ const summary = m ? `${m.total} open${coverage ? ` · ${num(coverage.percent)}% annotation coverage` : ''}` : 'threat counts unknown';
859
+ const repo = [i.repo, i.sha].filter(Boolean).join(' / ');
860
+ const identity = [version, plan?.label].filter(Boolean).join(' · ');
861
+ const facts = [repo, i.branch, identity, summary, m?.severities.join(' · '),
862
+ coverage ? `${num(coverage.annotated_files)} / ${num(coverage.source_files)} files` : ''];
863
+ const brand = wide ? ['', '', ...LOGO, 'by bugb'] : ['', '', 'BRAVOS', 'by bugb', '', ''];
864
+ const labels = [...brand, ...facts];
865
+ const head = width >= 68
866
+ ? BRAVOS_MARK.map((row, n) => row.padEnd(32) + ' ' + (labels[n] ?? ''))
867
+ : ['BRAVOS', 'by bugb', ...facts].filter(Boolean);
868
+ const lines = head.map((l) => clipped(l, width).trimEnd());
869
+ const render = () => (opts.color ? colorize(lines, i, opts.theme) : lines).join('\n');
870
+ if (i.guardlink === 'missing') {
871
+ lines.push(...wrap('guardlink not found on PATH — run bravos doctor', width));
872
+ return render();
873
+ }
874
+ for (const warning of bannerWarnings(i, plan)) lines.push(...wrap(warning, width));
875
+ const rule = '─'.repeat(width);
876
+ const leftWidth = wide ? Math.floor(width * 0.54) : width;
877
+ const rightWidth = wide ? width - leftWidth - 5 : width;
763
878
  const confirmed = arr(g.ci?.confirmed).slice().sort((a, b) => sevRank(a.severity) - sevRank(b.severity));
764
- let left;
765
- if (confirmed.length > 0) {
766
- left = [`FIX NOW — confirmed (${confirmed.length})`, ...confirmed.slice(0, 3).map((c) => {
767
- const { threat } = assetThreat(c);
879
+ const findings = [];
880
+ if (confirmed.length) {
881
+ findings.push(`${confirmed.length} CONFIRMED FINDING${confirmed.length === 1 ? '' : 'S'}${confirmed.length > 3 ? ' · 3 shown' : ''}`);
882
+ for (const c of confirmed.slice(0, 3)) {
768
883
  const file = basename(String(c?.location?.file ?? c?.file ?? '?'));
769
- return `${threat} ${file}:${c?.location?.line ?? c?.line ?? '?'}`;
770
- })];
771
- } else if (!g.ci) {
772
- left = ['Top threats', 'unknown'];
773
- } else {
884
+ const locator = ':' + clipped(c?.location?.line ?? c?.line ?? '?', 8);
885
+ const threat = clipped(assetThreat(c).threat, Math.floor(leftWidth / 2));
886
+ findings.push(threat + ' ' + clipped(file, leftWidth - cells(threat) - cells(locator) - 2) + locator);
887
+ }
888
+ } else if (g.ci) {
889
+ findings.push('0 CONFIRMED FINDINGS · Top threats');
774
890
  const top = topThreats(g.ci.exposures);
775
- // The count is kept and a long threat id is shortened, so the column never loses the ×n.
776
- const row = (t) => {
777
- const head = `${t.severity.padEnd(9)}`;
778
- const tail = ` ×${t.count}`;
779
- return head + fit(t.threat, BANNER_WIDTH - head.length - tail.length) + tail;
780
- };
781
- left = ['Top threats', ...(top.length ? top.map(row) : ['none open'])];
782
- }
783
- // By role and by task: the skill each starts with, in the harness's own syntax. Campaigns, the ship check and
784
- // the code graph are on the Team plan, so an unlicensed person is shown free skills in their place.
785
- const sk = (name) => (SIGIL[harness] ?? '') + name;
786
- const free = hooksLocked(i);
787
- const roles = [['developer', 'bravos-annotate'], ['security', 'bravos-prove'], ['team lead', free ? 'bravos-report' : 'bravos-campaign'], ['new here', 'bravos']];
788
- const tasks = free
789
- ? [['what next?', 'bravos'], ['app intent', 'bravos-context'], ['after a fix', 'bravos-recheck'], ['write it up', 'bravos-report']]
790
- : [['what next?', 'bravos'], ['before a PR', 'bravos-ship'], ['after a fix', 'bravos-recheck'], ['find routes', 'bravos-codegraph']];
791
- const head = lines.splice(0);
792
- lines.push('', 'If you are'.padEnd(LEFT_WIDTH) + 'To');
793
- for (let r = 0; r < roles.length; r++) {
794
- lines.push(fit(`${roles[r][0].padEnd(11)}${sk(roles[r][1])}`, LEFT_WIDTH - 2).padEnd(LEFT_WIDTH) + `${tasks[r][0].padEnd(13)}${sk(tasks[r][1])}`);
891
+ for (const t of top) {
892
+ const tail = ' ×' + t.count;
893
+ findings.push(t.severity.padEnd(9) + clipped(t.threat, leftWidth - 9 - cells(tail)) + tail);
894
+ }
895
+ if (!top.length) findings.push('none open');
896
+ } else findings.push('Findings unavailable', 'threat counts unknown (guardlink ci unavailable)');
897
+ const allFindings = 'All findings bravos dashboard';
898
+ if (confirmed.length && !wide && width >= 72) {
899
+ findings.push(allFindings + ' After a fix ' + sk('bravos-recheck'));
900
+ } else {
901
+ findings.push(allFindings);
902
+ if (confirmed.length) findings.push('After a fix ' + sk('bravos-recheck'));
795
903
  }
796
- const setup = i.root ? readSetup(i.root, i, harness) : null;
797
- // The next step with its command; the pointer to bravos next is dropped when the command is long.
798
- const nextFull = setup?.next ? `Next: ${setup.next.label} → ${setup.next.cta} · more: bravos next` : null;
799
- const nextLine = nextFull && nextFull.length > BANNER_WIDTH ? `Next: ${setup.next.label} → ${setup.next.cta}` : nextFull;
800
- lines.push('', fit(nextLine ?? `Tip: ${TIPS[(opts.day ?? dayNumber()) % TIPS.length]}`, BANNER_WIDTH));
801
- lines.push('Guide (free, no tokens): bravos guide · bravos guide roles · bravos guide tasks');
802
904
 
905
+ const setup = i.root ? readSetup(i.root, i, harness) : null;
906
+ const graph = ({ current: 'on', cli: 'available', unknown: 'unknown', unavailable: 'off', diverged: 'stale', locked: 'locked', 'not-built': 'not built' })[i.codegraph] ?? 'unknown';
907
+ const hook = (on) => !on ? 'off' : hooksLocked(i) ? 'locked' : 'on';
908
+ const sast = i.sast?.summary ? `SAST ${i.sast.summary.reachable} reachable` : i.sast?.available?.ok ? 'SAST has not run' : 'SAST off';
909
+ const score = setup ? `SETUP ${setup.done}/${setup.total}` : 'SETUP';
910
+ const intentGraph = `Intent ${i.intent?.status ?? 'unknown'} · Code graph ${graph}`;
911
+ const hooks = `Pre-PR ${hook(i.prePr)} · Autopilot ${hook(i.autopilot)}`;
912
+ const checks = wide ? [score, intentGraph, hooks, sast] : [score + ' · ' + intentGraph, hooks + ' · ' + sast];
913
+ if (setup?.next) {
914
+ const step = setup.next;
915
+ checks.push(...wrap(step.paid ? 'Next: activate Team → bravos account activate' : `Next: ${step.label} → ${step.cta}`, rightWidth));
916
+ } else if (!setup) checks.push(...wrap('Tip: ' + TIPS[(opts.day ?? dayNumber()) % TIPS.length], rightWidth));
917
+ else checks.push('All setup steps complete');
918
+ const further = 'Further setup bravos next';
919
+ if (setup?.next && !wide && cells(checks.at(-1)) + 4 + further.length <= width) checks[checks.length - 1] += ' ' + further;
920
+ else checks.push(further);
921
+
922
+ lines.push(rule);
923
+ if (wide) {
924
+ const right = checks.flatMap((row) => wrap(row, rightWidth));
925
+ for (let r = 0; r < Math.max(findings.length, right.length); r++) {
926
+ lines.push(paired(findings[r] ?? '', right[r] ?? '', leftWidth).trimEnd());
927
+ }
928
+ } else {
929
+ lines.push(...findings.flatMap((s) => wrap(s, width)), rule, ...checks.flatMap((s) => wrap(s, width)));
930
+ }
931
+ lines.push(rule);
932
+ const shortcuts = hooksLocked(i)
933
+ ? `App intent ${sk('bravos-context')} Write report ${sk('bravos-report')}`
934
+ : `Before a PR ${sk('bravos-ship')} Find routes ${sk('bravos-codegraph')}`;
935
+ const guide = 'All commands bravos guide';
936
+ lines.push(...wrap(wide ? shortcuts + ' ' + guide : shortcuts, width));
937
+ if (!wide) lines.push(...wrap(guide, width));
803
938
  if (i.intent?.status === 'none') {
804
- lines.push('', INTRO_HEAD, free ? INTRO_FREE : INTRO_TEAM, `Start with the Next step above, or ask "help me get started" (${SIGIL[harness] ? `${SIGIL[harness]}bravos` : 'the bravos skill'}).`, 'Hide this banner with BRAVOS_BANNER=off.');
939
+ lines.push(...wrap(INTRO_HEAD + ' ' + (hooksLocked(i) ? INTRO_FREE : INTRO_TEAM), width));
940
+ lines.push(...wrap(`Ask "help me get started" (${SIGIL[harness] ? sk('bravos') : 'the bravos skill'}). Hide with BRAVOS_BANNER=off.`, width));
805
941
  }
806
- // When notes above the threats push the banner past its cap, threat rows give way (one always stays),
807
- // so the Next and Guide lines are never the ones cut.
808
- const cap = i.intent?.status === 'none' ? 35 : 29;
809
- while (head.length + left.length + lines.length > cap && left.length > 2) left.pop();
810
- const out = [...head, ...left.map((row) => fit(row, BANNER_WIDTH)), ...lines].map((l) => fit(l.trimEnd(), BANNER_WIDTH)).slice(0, cap);
811
- return (opts.color ? colorize(out, i, opts.theme) : out).join('\n');
942
+ return render();
812
943
  }
813
944
 
814
945
  // @comment -- "A three-line, uncoloured summary for harnesses that show a hook's message as a warning or notice rather than in the transcript (Codex)."
@@ -833,74 +964,20 @@ const fg = (hex) => (hex ? `\x1b[38;2;${parseInt(hex.slice(1, 3), 16)};${parseIn
833
964
  const RESET = '\x1b[0m';
834
965
  export const paint = (text, hex, bold = false) => (hex || bold ? `${bold ? '\x1b[1m' : ''}${fg(hex)}${text}${RESET}` : text);
835
966
 
836
- // @comment -- "Colours banner lines with the theme's palette (dark, light or neutral): the mascot's hood in slate and steel with green eyes, the wordmark in green with a blue shadow, severities by weight (critical and high in red), skills in green, and supporting text in steel; pure string transform."
837
- export function colorize(lines, inputs = {}, theme = 'dark') {
838
- const P = THEMES[theme] ?? THEMES.neutral;
839
- // One escape per run of same-coloured characters, so the banner stays far inside the 10,000-character cap.
840
- const runs = (chars, colourOf) => {
841
- let out = '';
842
- let cur = null;
843
- let buf = '';
844
- const flush = () => {
845
- if (buf) out += cur ? paint(buf, cur) : buf;
846
- buf = '';
847
- };
848
- for (const c of chars) {
849
- const k = c === ' ' ? cur : colourOf(c);
850
- if (k !== cur) {
851
- flush();
852
- cur = k;
853
- }
854
- buf += c;
855
- }
856
- flush();
857
- return out;
858
- };
859
- const mascotColour = (c) => (c === '▓' ? P.slate : c === '▄' || c === '▀' ? P.steel : '█▐▌'.includes(c) ? P.green : null);
860
- const wordColour = (c) => (c === '█' ? P.green : '╗╔╝╚═║'.includes(c) ? P.blue : null);
861
- return lines.map((line, n) => {
862
- if (n < MASCOT.length) {
863
- const chars = [...line];
864
- const left = runs(chars.slice(0, MASCOT_WIDTH), mascotColour);
865
- const rest = chars.slice(MASCOT_WIDTH).join('');
866
- if (n >= 2 && n < 2 + LOGO.length) return left + runs([...rest], wordColour);
867
- if (n === MASCOT.length - 3) return left + rest.replace(/Plan: (.+)$/, (_m, label) => paint('Plan: ', P.steel) + paint(label, P.light, true));
868
- if (n === MASCOT.length - 2) return left + rest.replace(/bravos( [\d.]+)?/, (m) => paint(m, P.green, true)).replace(/ · (.+)$/, (_m, r) => ` · ${paint(r, P.light, true)}`);
869
- if (n === MASCOT.length - 1) return left + rest.replace(/\S.*$/, (m) => paint(m, P.steel));
870
- return left + rest;
871
- }
872
- if (/^If you are/.test(line)) return line.replace(/^If you are/, paint('If you are', P.light, true)).replace(/To$/, paint('To', P.light, true));
873
- if (/^(developer|security|team lead|new here) /.test(line)) {
874
- return line.split(/((?:\/skill:|\/|\$)?bravos(?:-[a-z]+)?(?= |$))/).map((part, k) => (k % 2 ? paint(part, P.green) : part)).join('');
875
- }
876
- if (/^! your user-level bravos/.test(line)) return paint(line, P.red, true);
877
- if (/^~ (repo bravos |Team adds |licence expired)/.test(line)) return paint(line, P.steel);
878
- if (/^Tip: /.test(line)) return paint('Tip: ', P.green, true) + paint(line.slice(5), P.light);
879
- if (/^Next: /.test(line)) {
880
- const [what, rest = ''] = line.slice(6).split(' → ');
881
- const [cta, tailText] = rest.split(' · more: ');
882
- return paint('Next: ', P.green, true) + paint(what, P.light) + (cta ? ` → ${paint(cta, P.green)}` : '') + (tailText !== undefined ? ` · more: ${paint(tailText, P.green)}` : '');
883
- }
884
- if (/^Guide \(free/.test(line)) return line.replace(/^Guide \(free, no tokens\):/, (m) => paint(m, P.steel)).replace(/bravos guide[a-z ]*/g, (m) => paint(m, P.green));
885
- if (/^(Top threats|FIX NOW)/.test(line)) {
886
- return line
887
- .replace(/^Top threats/, paint('Top threats', P.light, true))
888
- .replace(/^FIX NOW — confirmed \(\d+\)/, (m) => paint(m, P.red, true))
889
- .replace(/Quick start( \(skills\))?/, (m) => paint(m, P.light, true));
890
- }
891
- let l = line
892
- .replace(/^(critical|high)(?= )/, (m) => paint(m, P.red, true))
893
- .replace(/^medium(?= )/, (m) => paint(m, P.light))
894
- .replace(/^low(?= )/, (m) => paint(m, P.steel))
895
- .replace(/(\d+) (critical|high)\b/g, (m) => paint(m, P.red))
896
- .replace(/\b([1-9]\d*) confirmed\b/, (m) => paint(m, P.red, true))
897
- .replace(/\b0 confirmed\b/, (m) => paint(m, P.green))
898
- .replace(/coverage \d+%( \(\d+\/\d+\))?/, (m) => paint(m, P.green))
899
- .replace(/((?:\/skill:|\/|\$)bravos(?:-[a-z]+)?)(\s+)([^\x1b]+)$/, (_m, cmd, sp, hint) => `${paint(cmd, P.green)}${sp}${paint(hint, P.steel)}`)
900
- .replace(/(?<![\w/$:-])((?:\/skill:|\/|\$)bravos(?:-[a-z]+)?)(?![\w-])(?![^\x1b]*\x1b\[0m)/g, (m) => paint(m, P.green));
901
- if (/^(Start with|Hide this|bravos makes|the code, proves)/.test(line)) {
902
- l = line.split(/((?:\/skill:|\/|\$)bravos-[a-z]+)/).map((part, k) => (k % 2 ? paint(part, P.green) : part ? paint(part, P.steel) : '')).join('');
903
- }
904
- return l;
967
+ // @comment -- "Applies theme colours to a finished plain-text layout. Each run of wordmark cells uses one escape. The supplied Bravos symbol, headings, severity and executable commands stay readable with colour disabled."
968
+ export function colorize(lines, _inputs = {}, theme = 'dark') {
969
+ const p = THEMES[theme] ?? THEMES.neutral;
970
+ // One pass over plain text; never run another replacement over terminal escapes.
971
+ const token = /[█▄▀]+(?: +[█▄▀]+)*|[╗╔╝╚═║]+(?: +[╗╔╝╚═║]+)*|[─│]+|\b\d+ CONFIRMED FINDINGS?\b|#[-\w]+|\b(?:\d+ )?(?:critical|high)\b|\b\d+% annotation coverage|\bSETUP\b|\bBRAVOS\b|by bugb|(?:\/skill:|\/|\$)?bravos-[\w-]+|\bbravos (?:dashboard|next|guide|doctor|sync|account activate|licence)\b/g;
972
+ return lines.map((line) => {
973
+ if (/^! /.test(line)) return paint(line, p.red, true);
974
+ if (/^~ /.test(line)) return paint(line, p.steel);
975
+ return line.replace(token, (word) => {
976
+ if (/^[╗╔╝╚═║]/.test(word)) return paint(word, p.blue);
977
+ if (/^[─│]/.test(word)) return paint(word, p.line);
978
+ if (/^(#|[1-9]\d* CONFIRMED)|\b(critical|high)$/.test(word)) return paint(word, p.red);
979
+ if (word === 'by bugb' || word.startsWith('0 CONFIRMED')) return paint(word, p.steel);
980
+ return paint(word, p.green);
981
+ });
905
982
  });
906
983
  }