@bugb-technologies/bravos 1.0.3 → 1.2.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,219 @@
1
+ // @comment -- "The prompts bravos start asks through: one small interface, a terminal implementation drawn by this file on @clack/core, and a scripted one for tests and --yes. Every prompt has an id so a test can answer it by name. The terminal one uses no dim or faint colour: markers are plain text ([x], ( ), ❯) in the terminal's own foreground, so they read on light and dark themes alike; Esc steps back, Ctrl-C quits."
2
+ import * as clack from '@clack/prompts';
3
+ import { MultiSelectPrompt, PasswordPrompt, SelectPrompt, TextPrompt, isCancel } from '@clack/core';
4
+ /** The person pressed Ctrl-C (or chose Cancel): nothing has been written. */
5
+ export class Cancelled extends Error {
6
+ constructor() {
7
+ super('setup cancelled — nothing was changed');
8
+ }
9
+ }
10
+ /** The person pressed Esc: go back to the previous question. */
11
+ export class Back extends Error {
12
+ constructor() {
13
+ super('back');
14
+ }
15
+ }
16
+ // Styling: bold, and the 16-colour cyan/red the terminal theme maps for itself; never dim.
17
+ const B = (s) => `\x1b[1m${s}\x1b[22m`;
18
+ const ACC = (s) => `\x1b[36m${s}\x1b[39m`;
19
+ const ERR = (s) => `\x1b[31m${s}\x1b[39m`;
20
+ const BAR = '│';
21
+ export const labelOf = (c) => `${c.label}${c.recommended ? ' (recommended)' : ''}`;
22
+ const keysLine = (extra) => `${BAR} ${['↑↓ move', ...extra, 'enter choose', 'esc back', 'ctrl-c quit'].join(' · ')}`;
23
+ /** Draws one option line: the pointer and marker are plain characters, so they never depend on colour. */
24
+ function optionLine(c, active, marker) {
25
+ const text = `${marker} ${labelOf(c)}${c.hint ? ` — ${c.hint}` : ''}`;
26
+ return `${BAR} ${active ? `${ACC('❯')} ${B(text)}` : ` ${text}`}`;
27
+ }
28
+ /** Runs a core prompt; Esc becomes Back and Ctrl-C becomes Cancelled. */
29
+ async function ask(flag, prompt) {
30
+ prompt.on('key', (_ch, key) => {
31
+ if (key?.name === 'escape')
32
+ flag.esc = true;
33
+ });
34
+ const v = await prompt.prompt();
35
+ if (isCancel(v))
36
+ throw flag.esc ? new Back() : new Cancelled();
37
+ return v;
38
+ }
39
+ /** The line a prompt leaves when it is left without an answer. */
40
+ const left = (flag, message) => `${ACC('◇')} ${message} ${B(flag.esc ? '↩ back' : '✕ quit')}`;
41
+ function header(state, message) {
42
+ return `${state === 'error' ? ERR('▲') : ACC('◆')} ${B(message)}`;
43
+ }
44
+ /** The answer line a finished prompt leaves behind. */
45
+ const answered = (message, answer) => `${ACC('◇')} ${message}\n${BAR} ${B(answer)}`;
46
+ /** The terminal, drawn here on @clack/core; notes, logs and the frame come from @clack/prompts. */
47
+ export function terminalPrompter() {
48
+ let count = 0;
49
+ const select = async (_id, message, choices, initial) => {
50
+ count++;
51
+ const opts = choices.map((c) => ({ ...c, value: c.value }));
52
+ const k = { esc: false };
53
+ const p = new SelectPrompt({
54
+ options: opts,
55
+ initialValue: initial,
56
+ render() {
57
+ if (this.state === 'submit')
58
+ return answered(message, labelOf(opts[this.cursor]));
59
+ if (this.state === 'cancel')
60
+ return left(k, message);
61
+ return [header(this.state, message), ...opts.map((c, i) => optionLine(c, i === this.cursor, i === this.cursor ? '(•)' : '( )')), keysLine([]), '└'].join('\n');
62
+ },
63
+ });
64
+ return (await ask(k, p));
65
+ };
66
+ return {
67
+ get count() {
68
+ return count;
69
+ },
70
+ intro: (t) => clack.intro(B(t)),
71
+ outro: (t) => clack.outro(t),
72
+ note: (b, t) => clack.note(b, t, { format: (l) => l }),
73
+ info: (t) => clack.log.info(t),
74
+ warn: (t) => clack.log.warn(t),
75
+ select,
76
+ multiselect: async (_id, message, choices, initial) => {
77
+ count++;
78
+ const opts = choices.map((c) => ({ ...c, value: c.value }));
79
+ const k = { esc: false };
80
+ const p = new MultiSelectPrompt({
81
+ options: opts,
82
+ initialValues: initial,
83
+ required: true,
84
+ render() {
85
+ const picked = (this.value ?? []);
86
+ if (this.state === 'submit')
87
+ return answered(message, opts.filter((o) => picked.includes(o.value)).map((o) => o.label).join(', '));
88
+ if (this.state === 'cancel')
89
+ return left(k, message);
90
+ const lines = opts.map((c, i) => optionLine(c, i === this.cursor, picked.includes(c.value) ? '[x]' : '[ ]'));
91
+ const err = this.state === 'error' ? [`${BAR} ${ERR('Tick at least one with space.')}`] : [];
92
+ return [header(this.state, message), ...lines, ...err, keysLine(['space tick']), '└'].join('\n');
93
+ },
94
+ });
95
+ return (await ask(k, p));
96
+ },
97
+ text: async (_id, message, o = {}) => {
98
+ count++;
99
+ const k = { esc: false };
100
+ const p = new TextPrompt({
101
+ initialValue: o.initial,
102
+ placeholder: o.placeholder,
103
+ validate: o.validate ? (v) => o.validate(String(v ?? '')) : undefined,
104
+ render() {
105
+ if (this.state === 'submit')
106
+ return answered(message, String(this.value ?? '') || '(empty)');
107
+ if (this.state === 'cancel')
108
+ return left(k, message);
109
+ const input = this.userInput ? this.userInputWithCursor : `${o.placeholder ? `e.g. ${o.placeholder}` : ''}█`;
110
+ const err = this.state === 'error' ? [`${BAR} ${ERR(this.error)}`] : [];
111
+ return [header(this.state, message), `${BAR} ${ACC('>')} ${input}`, ...err, `${BAR} enter accept · esc back · ctrl-c quit`, '└'].join('\n');
112
+ },
113
+ });
114
+ return String((await ask(k, p)) ?? '');
115
+ },
116
+ confirm: async (id, message, initial = true, o = {}) => select(id, message, [
117
+ { value: true, label: o.yes ?? 'Yes', recommended: o.recommend !== false && initial === true },
118
+ { value: false, label: o.no ?? 'No', recommended: o.recommend !== false && initial === false },
119
+ ], initial),
120
+ secret: async (_id, message) => {
121
+ count++;
122
+ const k = { esc: false };
123
+ const p = new PasswordPrompt({
124
+ mask: '•',
125
+ render() {
126
+ if (this.state === 'submit')
127
+ return answered(message, this.masked ? '•••• (hidden)' : '(skipped)');
128
+ if (this.state === 'cancel')
129
+ return left(k, message);
130
+ return [header(this.state, message), `${BAR} ${ACC('>')} ${this.masked}█`, `${BAR} paste, then enter · esc back · ctrl-c quit`, '└'].join('\n');
131
+ },
132
+ });
133
+ return String((await ask(k, p)) ?? '');
134
+ },
135
+ spin: async (label, work, done) => {
136
+ const s = clack.spinner();
137
+ const t0 = Date.now();
138
+ s.start(label);
139
+ try {
140
+ const r = await work();
141
+ const secs = Math.round((Date.now() - t0) / 1000);
142
+ const res = done ? done(r) : label;
143
+ const took = secs >= 2 ? ` (${secs}s)` : '';
144
+ if (typeof res === 'string')
145
+ s.stop(`${res}${took}`);
146
+ else
147
+ s.error(`${res.fail}${took}`);
148
+ return r;
149
+ }
150
+ catch (e) {
151
+ s.error(`${label} — failed`);
152
+ throw e;
153
+ }
154
+ },
155
+ };
156
+ }
157
+ /**
158
+ * Answers from a table, for tests and for `bravos start --yes`. An id with no answer
159
+ * takes the prompt's default (initial) when it has one, and is otherwise an error, so
160
+ * a scripted run never silently invents an answer a person should give. '__back__'
161
+ * answers as Esc would (once), '__cancel__' as Ctrl-C.
162
+ */
163
+ export function scriptedPrompter(answers, out = () => { }) {
164
+ const asked = [];
165
+ const backs = new Set();
166
+ const pick = (id, fallback) => {
167
+ asked.push(id);
168
+ let a = answers[id];
169
+ if (Array.isArray(a) && a[0] === '__seq__') {
170
+ // A sequence: each time the id is asked it takes the next answer.
171
+ const n = asked.filter((x) => x === id).length;
172
+ a = a[Math.min(n, a.length - 1)];
173
+ }
174
+ if (a === '__cancel__')
175
+ throw new Cancelled();
176
+ if (a === '__back__' && !backs.has(id)) {
177
+ backs.add(id);
178
+ throw new Back();
179
+ }
180
+ if (id in answers && a !== '__back__')
181
+ return a;
182
+ if (fallback !== undefined)
183
+ return fallback;
184
+ throw new Error(`no answer for '${id}'`);
185
+ };
186
+ return {
187
+ asked,
188
+ get count() {
189
+ return asked.length;
190
+ },
191
+ intro: (t) => out(t),
192
+ outro: (t) => out(t),
193
+ note: (b, t) => out(t ? `${t}\n${b}` : b),
194
+ info: (t) => out(t),
195
+ warn: (t) => out(`! ${t}`),
196
+ select: async (id, _m, choices, initial) => {
197
+ const v = pick(id, initial ?? choices[0]?.value);
198
+ if (!choices.some((c) => c.value === v))
199
+ throw new Error(`'${String(v)}' is not a choice for '${id}'`);
200
+ return v;
201
+ },
202
+ multiselect: async (id, _m, _c, initial) => pick(id, initial),
203
+ text: async (id, _m, o = {}) => {
204
+ const v = String(pick(id, o.initial));
205
+ const bad = o.validate?.(v);
206
+ if (bad)
207
+ throw new Error(`'${id}': ${bad}`);
208
+ return v;
209
+ },
210
+ confirm: async (id, _m, initial) => pick(id, initial),
211
+ secret: async (id) => String(pick(id, undefined)),
212
+ spin: async (label, work, done) => {
213
+ const r = await work();
214
+ const res = done ? done(r) : label;
215
+ out(typeof res === 'string' ? res : `! ${res.fail}`);
216
+ return r;
217
+ },
218
+ };
219
+ }
@@ -1,18 +1,20 @@
1
+ import { bgFor, fgFor } from './palette.js';
1
2
  // @comment -- "Draws bravos watch's frames: a header bar, a row of number tiles, bordered panels (setup, threat model, test next, top threats and assets, code graph, SAST, branch and team, the model's size, activity) arranged in three, two or one columns by terminal width, a scrollable body and a key bar. Pure: text in, text out. Colour is added per segment after layout, so the plain and coloured frames have the same characters, and every glyph that carries meaning (severity, bars) differs in plain text too."
2
3
  /* ------------------------------------------------------------------ segments */
3
- // Brand palette (bravos), plus amber for warnings and medium severity.
4
+ // Colour roles, not colours: renderLine turns each into the theme's colour
5
+ // (src/palette.ts), so the same frame reads on a dark or a light terminal.
4
6
  const C = {
5
- green: '#33d49d',
6
- deep: '#1f3943',
7
- ink: '#0e1b21',
8
- blue: '#0360a2',
9
- light: '#f0f0f0',
10
- steel: '#55899e',
11
- slate: '#3b6779',
12
- red: '#ea1d1d',
13
- amber: '#f0b429',
14
- white: '#ffffff',
15
- line: '#2b4f5c',
7
+ green: 'green',
8
+ deep: 'deep',
9
+ ink: 'ink',
10
+ blue: 'blue',
11
+ light: 'light',
12
+ steel: 'steel',
13
+ slate: 'slate',
14
+ red: 'red',
15
+ amber: 'amber',
16
+ white: 'white',
17
+ line: 'line',
16
18
  };
17
19
  const s = (t, c, b, bg) => ({ t, c, b, bg });
18
20
  const len = (l) => l.reduce((n, x) => n + [...x.t].length, 0);
@@ -40,8 +42,17 @@ export function fitLine(l, width, pad = false, padBg) {
40
42
  }
41
43
  const ESC = '\x1b[';
42
44
  const rgb = (hex) => `${parseInt(hex.slice(1, 3), 16)};${parseInt(hex.slice(3, 5), 16)};${parseInt(hex.slice(5, 7), 16)}`;
43
- export const renderLine = (l, color) => l
44
- .map((x) => (color && (x.c || x.b || x.bg) ? `${x.b ? `${ESC}1m` : ''}${x.c ? `${ESC}38;2;${rgb(x.c)}m` : ''}${x.bg ? `${ESC}48;2;${rgb(x.bg)}m` : ''}${x.t}${ESC}0m` : x.t))
45
+ // @comment -- "Colour per segment in the chosen theme: a role on the terminal's background takes the theme's colour (null is the terminal's own foreground); a role on a background of its own keeps the fixed pair"
46
+ export const renderLine = (l, color, theme = 'dark') => l
47
+ .map((x) => {
48
+ if (!color)
49
+ return x.t;
50
+ const bg = x.bg ? bgFor(x.bg) : null;
51
+ const fg = x.c ? fgFor(theme, x.c, !!bg) : null;
52
+ if (!fg && !bg && !x.b)
53
+ return x.t;
54
+ return `${x.b ? `${ESC}1m` : ''}${fg ? `${ESC}38;2;${rgb(fg)}m` : ''}${bg ? `${ESC}48;2;${rgb(bg)}m` : ''}${x.t}${ESC}0m`;
55
+ })
45
56
  .join('');
46
57
  /* ------------------------------------------------------------------ small pieces */
47
58
  const SEV = ['critical', 'high', 'medium', 'low'];
@@ -465,12 +476,13 @@ const KEYS = [
465
476
  ['s', 'services'],
466
477
  ['o', 'open'],
467
478
  ['u', 'update'],
479
+ ['c', 'colours'],
468
480
  ['j/k', 'scroll'],
469
481
  ['?', 'guide'],
470
482
  ['q', 'quit'],
471
483
  ];
472
484
  // Keys dropped first when the bar does not fit; quit always stays.
473
- const DROP_ORDER = ['u', 'o', 's', 'd', '?', 'i', 'p', 't', 'r', 'g', 'j/k', 'n'];
485
+ const DROP_ORDER = ['c', 'u', 'o', 's', 'd', '?', 'i', 'p', 't', 'r', 'g', 'j/k', 'n'];
474
486
  function keyBar(width) {
475
487
  let keys = KEYS;
476
488
  const chips = (ks) => ks.flatMap(([k, label]) => [s(` ${k} `, C.ink, true, C.green), s(` ${label} `, C.steel)]);
@@ -588,6 +600,6 @@ export function renderFrame(sn, events, opts) {
588
600
  }
589
601
  }
590
602
  const lines = [...top, ...body, ...bottom].map((l) => fitLine(l, width));
591
- return { text: lines.map((l) => renderLine(l, color)).join('\n'), maxScroll };
603
+ return { text: lines.map((l) => renderLine(l, color, opts.theme ?? 'dark')).join('\n'), maxScroll };
592
604
  }
593
605
  export const buildFrame = (sn, events, opts) => renderFrame(sn, events, opts).text;
package/dist/watch.js CHANGED
@@ -9,6 +9,7 @@ import { hooksDir, version } from './paths.js';
9
9
  import { readAllAnswers, readDraft } from './review.js';
10
10
  import { listReports, readMeta, reportDir } from './report/meta.js';
11
11
  import { renderFrame } from './watch-frame.js';
12
+ import { nextTheme, themeFromBackground } from './palette.js';
12
13
  export { buildFrame, layoutFor, renderFrame, tailPath } from './watch-frame.js';
13
14
  // @comment -- "bravos watch: a live, read-only, zero-token terminal view of a repository's security work, beside any harness. snapshot() gathers what the briefing gathers (guardlink ci, hypothesis next, tickets, git, gh, intent, proving, SAST, setup) plus the hypothesis and boundary ledgers, the model's size, review answers, branch state and the code graph's own answers; diffSnapshots() turns two snapshots into activity events in memory; watch-frame.ts draws them; handleKey() maps keys to read-only actions. Nothing here writes to the repository."
14
15
  export const WATCH_SCHEMA = 'bravos.watch/v1';
@@ -589,6 +590,8 @@ export function handleKey(key, sn, root = '.') {
589
590
  return { kind: 'overlay', what: 'services' };
590
591
  case 'o':
591
592
  return { kind: 'open-report' };
593
+ case 'c':
594
+ return { kind: 'theme' };
592
595
  case 'i':
593
596
  return { kind: 'overlay', what: 'intent' };
594
597
  case '?':
@@ -652,8 +655,40 @@ function copyToClipboard(text) {
652
655
  return false;
653
656
  }
654
657
  // @comment -- "Runs the live view in a TTY: alternate screen, redraw on file changes (debounced, one snapshot at a time), the slow parts (boundaries, model size, PRs) every interval and the code graph every graphInterval, keys for read-only actions and scrolling, and a clean restore on q, Ctrl-C, SIGTERM or a crash. Never writes to the repository."
658
+ /**
659
+ * Asks the terminal for its background colour (OSC 11) and waits up to `timeoutMs`
660
+ * for the answer. Most terminals answer at once; one that does not costs only the wait.
661
+ * Must run before anything else reads stdin. Null when there is no answer.
662
+ */
663
+ // @comment -- "Terminal background query (OSC 11) with a short timeout, so watch can pick the light or dark palette; read-only, raw mode restored afterwards"
664
+ export function queryBackground(timeoutMs = 150) {
665
+ const input = process.stdin;
666
+ if (!input.isTTY || !process.stdout.isTTY)
667
+ return Promise.resolve(null);
668
+ return new Promise((resolve) => {
669
+ let buf = '';
670
+ const done = (t) => {
671
+ clearTimeout(timer);
672
+ input.off('data', onData);
673
+ input.setRawMode(false);
674
+ input.pause();
675
+ resolve(t);
676
+ };
677
+ const onData = (d) => {
678
+ buf += d.toString();
679
+ if (/\x07|\x1b\\/.test(buf))
680
+ done(themeFromBackground(buf));
681
+ };
682
+ const timer = setTimeout(() => done(themeFromBackground(buf)), timeoutMs);
683
+ input.setRawMode(true);
684
+ input.resume();
685
+ input.on('data', onData);
686
+ process.stdout.write('\x1b]11;?\x07');
687
+ });
688
+ }
655
689
  export async function runWatch(root, env, opts) {
656
690
  const out = process.stdout;
691
+ let theme = opts.theme ?? 'dark';
657
692
  const events = [];
658
693
  const history = [];
659
694
  let sn = null;
@@ -688,7 +723,7 @@ export async function runWatch(root, env, opts) {
688
723
  frame = [...shown, '', `(${where}any other key closes)`].join('\n');
689
724
  }
690
725
  else {
691
- const r = renderFrame(sn, events, { width, height: height - (graphPrompt !== null ? 1 : 0), color: opts.color, status, compact: opts.compact, scroll, history, note, stats: { refreshes, lastMs } });
726
+ const r = renderFrame(sn, events, { width, height: height - (graphPrompt !== null ? 1 : 0), color: opts.color, theme, status, compact: opts.compact, scroll, history, note, stats: { refreshes, lastMs } });
692
727
  maxScroll = r.maxScroll;
693
728
  scroll = Math.min(scroll, maxScroll);
694
729
  frame = r.text;
@@ -821,6 +856,10 @@ export async function runWatch(root, env, opts) {
821
856
  if (file)
822
857
  openTarget(file);
823
858
  }
859
+ if (a.kind === 'theme') {
860
+ theme = nextTheme(theme);
861
+ note = `colours: ${theme} — keep it with BRAVOS_THEME=${theme} or bravos start`;
862
+ }
824
863
  if (a.kind === 'refresh') {
825
864
  note = 'refreshing everything, the code graph too…';
826
865
  void refresh({ slow: true, graph: true });
package/docs/GUIDE.md CHANGED
@@ -22,7 +22,7 @@ Claude Code and opencode: /bravos-ship. Codex: $bravos-ship. omp: /skill:bravos-
22
22
 
23
23
  ### Plans
24
24
 
25
- Free (researcher) needs no licence: context, annotate, templatize, env, prove, recheck, report and watch, in one repository. Team, licensed per developer (Solo is one seat), adds the pre-PR gate and autopilot, the CI and nightly workflows, scheduled upkeep, multi-repository workspaces, campaigns, SAST and the code graph. The briefing opens every session with a Plan: line; bravos licence shows the same in a shell. bravos account activate signs you in once in the browser and writes the licence (a 30-day Team trial, no card, when the account has no plan); bravos account import <file> installs a downloaded one. Without a licence a paid command explains what it would do and how to start the trial, a paid hook stands down with one line and never blocks, and a paid skill stops at its first step and says so.
25
+ Free (researcher) needs no licence: context, annotate, templatize, env, prove, recheck, report and watch, in one repository. Team, licensed per developer (Solo is one seat), adds the pre-PR gate and autopilot, the CI and nightly workflows, scheduled upkeep, multi-repository workspaces, campaigns, SAST and the code graph. The briefing opens every session with a Plan: line; bravos licence shows the same in a shell. bravos account activate signs you in once in the browser and writes the licence (a 30-day Team trial, no card, when the account has no plan); bravos account import <file> installs a downloaded one. On a team plan the licence is yours and this machine's: an owner or admin assigns you a licence, each machine you activate gets its own short-lived token that bravos renews automatically (at the session start and before a paid command), bravos account devices lists your machines, bravos account revoke <id> signs one out (a lost laptop), and bravos account logout signs this one out. Removing you from the team, or taking your licence back, stops every one of your machines at its next renewal. In CI, BRAVOS_LICENCE holds a CI licence an owner or admin creates for that repository, and the CLI never renews it. Without a licence a paid command explains what it would do and how to start the trial, a paid hook stands down with one line and never blocks, and a paid skill stops at its first step and says so.
26
26
 
27
27
  ### Effort
28
28
 
@@ -30,7 +30,9 @@ Every skill reads one dial: low, medium (default), high or max. Say it ("annotat
30
30
 
31
31
  ### Installing
32
32
 
33
- npm install -g @bugb-technologies/bravos (Node 20 or newer). Then bravos account activate signs you in once in the browser and writes the licence — a 30-day Team trial when the account has no plan; skip it to stay on Free — bravos init in a repository writes the skills, hooks and MCP wiring, and bravos setup puts the analyzer and the code graph on the machine (Team plan). guardlink and cxg come from bravos setup --tools -y, or npm and cargo by hand. If you used the Python bravos, rename its command so bravos means this one: mv ~/.local/bin/bravos ~/.local/bin/bravos-py (this CLI still finds its code graph and analyzer), or remove it with pipx or uv.
33
+ npm install -g @bugb-technologies/bravos (Node 20 or newer), then bravos start: a guided setup that asks one question at a time (colours, licence, tools, repository, AI tools, PR checks, a scheduled run, how testing is allowed), shows every change, and writes nothing until you choose Apply. It ends with the one thing to type in your agent.
34
+
35
+ By hand instead: bravos account activate signs you in once in the browser and writes the licence — a 30-day Team trial when the account has no plan; skip it to stay on Free — bravos init in a repository writes the skills, hooks and MCP wiring, and bravos setup puts the analyzer and the code graph on the machine (Team plan). guardlink and cxg come from bravos setup --tools -y, or npm and cargo by hand. If you used the Python bravos, rename its command so bravos means this one: mv ~/.local/bin/bravos ~/.local/bin/bravos-py (this CLI still finds its code graph and analyzer), or remove it with pipx or uv.
34
36
 
35
37
  ### Your first day
36
38
 
@@ -321,3 +323,5 @@ bravos init --global installs for your user: skills in ~/.claude/skills (linked
321
323
  ### Banner switches
322
324
 
323
325
  BRAVOS_BANNER=off hides it; BRAVOS_BANNER_COLOR=off or NO_COLOR prints it plain. The briefing for the model is unchanged either way.
326
+
327
+ Light terminal? BRAVOS_THEME=light (or dark, or neutral) picks the colours for the banner and bravos watch; otherwise COLORFGBG, the choice saved by bravos start, then neutral. bravos doctor shows which, and the c key in bravos watch switches.
@@ -53,28 +53,9 @@ async function json(run, args, o) {
53
53
  }
54
54
  }
55
55
 
56
- // @comment -- "Reads .guardlink/proving.md, the person's recorded answer to how findings should be proven (written by the agent from their words in bravos-env/bravos-prove): choice auto | ask | schedule | none, the loopback target, the start command, whether model-API generation is allowed, and who confirmed it. Anything without a named confirmation reads as not set."
57
- export function readProving(root) {
58
- let text;
59
- try {
60
- text = readFileSync(join(root, '.guardlink', 'proving.md'), 'utf8');
61
- } catch {
62
- return { status: 'not set' };
63
- }
64
- const field = (name) => text.match(new RegExp(`^${name}:\\s*(\\S[^\\n]*?)\\s*$`, 'mi'))?.[1]?.replace(/\s+\(.*\)$/, '') ?? null;
65
- const by = text.match(/—\s*confirmed by\s+([^,\n]+?)\s*,\s*(\S+)/i);
66
- const choice = (field('choice') ?? '').toLowerCase().split(/\s/)[0];
67
- if (!by || !['auto', 'ask', 'schedule', 'none'].includes(choice)) return { status: 'not set' };
68
- return {
69
- status: 'set',
70
- choice,
71
- target: field('target'),
72
- start: field('start'),
73
- generation: /^(yes|true|allowed)/i.test(field('generation') ?? ''),
74
- by: by[1],
75
- date: by[2],
76
- };
77
- }
56
+ // @comment -- "readProving lives in proving.mjs, a file with no process or environment access, so the session-start hook can import it without this module; re-exported here for existing callers."
57
+ import { readProving } from './proving.mjs';
58
+ export { readProving };
78
59
 
79
60
  /** Files changed in the working tree since HEAD, tracked or not. */
80
61
  export async function changedFiles(root, env, run) {
@@ -1,9 +1,11 @@
1
- // @comment -- "Pure text builder for the session-start briefing, collect() which gathers its read-only guardlink, git and gh facts concurrently under a shared deadline, and the runJson/runJsonAsync spawn wrappers; dependency-free so it can be copied verbatim into target repos."
1
+ // @comment -- "Pure text builder for the session-start briefing, collect() which gathers its read-only guardlink, git and gh facts concurrently under a shared deadline (and renews a signed-in machine's device licence when it is due, through refresh.mjs — the one write it makes, to $BRAVOS_HOME only), and the runJson/runJsonAsync spawn wrappers; dependency-free so it can be copied verbatim into target repos."
2
2
  import { spawn, spawnSync } from 'node:child_process';
3
3
  import { accessSync, constants, readFileSync } from 'node:fs';
4
4
  import { basename, delimiter, dirname, join } from 'node:path';
5
- import { readProving } from './autopilot.mjs';
5
+ import { THEMES } from './palette.mjs';
6
+ import { readProving } from './proving.mjs';
6
7
  import { planLine, status as licenceStatus } from './licence.mjs';
8
+ import { refreshIfDue } from './refresh.mjs';
7
9
  import { readSast, sastAvailable, sastLine } from './sast.mjs';
8
10
  import { readSetup, setupLine } from './setup.mjs';
9
11
  import { memberCounts, readWorkspace, workspaceLines } from './workspace.mjs';
@@ -340,10 +342,12 @@ export async function collect(root, env, { deadlineMs = 20000, nextCount = 3 } =
340
342
  });
341
343
 
342
344
  const graphRun = probeGraph(root, env, Math.min(3000, first));
345
+ // 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.
346
+ const renewal = refreshIfDue(env, { timeoutMs: Math.min(3000, first) }).catch(() => null);
343
347
  // At an app folder, each member's counts come from its own guardlink ci, alongside the rest.
344
348
  const workspace = readWorkspace(root);
345
349
  const countsRun = workspace?.isAppFolder && hasGuardlink ? memberCounts(workspace, runJsonAsync, env, first) : Promise.resolve(null);
346
- const [facts, pr, graphState, workspaceCounts, ...gl] = await Promise.all([gitFacts, prRun, graphRun, countsRun, ...glRuns]);
350
+ const [facts, pr, graphState, workspaceCounts, , ...gl] = await Promise.all([gitFacts, prRun, graphRun, countsRun, renewal, ...glRuns]);
347
351
 
348
352
  let guardlink = 'missing';
349
353
  if (hasGuardlink) {
@@ -601,7 +605,7 @@ export function buildBanner(inputs, opts = {}) {
601
605
  if (i.guardlink === 'missing') {
602
606
  lines.push('', 'guardlink not found on PATH — run bravos doctor');
603
607
  const out = lines.map((l) => fit(l.trimEnd(), BANNER_WIDTH));
604
- return (opts.color ? colorize(out, i) : out).join('\n');
608
+ return (opts.color ? colorize(out, i, opts.theme) : out).join('\n');
605
609
  }
606
610
  const g = i.guardlink ?? {};
607
611
  lines.push('', countsLine(g), statusLine(i));
@@ -654,7 +658,7 @@ export function buildBanner(inputs, opts = {}) {
654
658
  lines.push('', ...INTRO, `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.');
655
659
  }
656
660
  const out = lines.map((l) => fit(l.trimEnd(), BANNER_WIDTH)).slice(0, i.intent?.status === 'none' ? 35 : 29);
657
- return (opts.color ? colorize(out, i) : out).join('\n');
661
+ return (opts.color ? colorize(out, i, opts.theme) : out).join('\n');
658
662
  }
659
663
 
660
664
  // @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)."
@@ -669,18 +673,17 @@ export function buildSummary(inputs, opts = {}) {
669
673
  return `${head} · ${countsLine(i.guardlink ?? {})}\nintent ${i.intent?.status ?? 'unknown'} · skills: ${next}\n${third}`;
670
674
  }
671
675
 
672
- // Brand palette. Colour is truecolor ANSI, added after layout so widths are measured on plain text.
673
- export const PALETTE = {
674
- green: '#33d49d', navy: '#1f3943', blue: '#0360a2', light: '#f0f0f0',
675
- steel: '#55899e', red: '#ea1d1d', slate: '#3b6779', black: '#000000', white: '#ffffff',
676
- };
677
- const fg = (hex) => `\x1b[38;2;${parseInt(hex.slice(1, 3), 16)};${parseInt(hex.slice(3, 5), 16)};${parseInt(hex.slice(5, 7), 16)}m`;
676
+ // Brand palette by theme (hooks/lib/palette.mjs). Colour is truecolor ANSI, added after
677
+ // layout so widths are measured on plain text. A null colour is the terminal's own
678
+ // foreground, so it is readable on whatever background the terminal has.
679
+ export const PALETTE = THEMES.dark;
680
+ const fg = (hex) => (hex ? `\x1b[38;2;${parseInt(hex.slice(1, 3), 16)};${parseInt(hex.slice(3, 5), 16)};${parseInt(hex.slice(5, 7), 16)}m` : '');
678
681
  const RESET = '\x1b[0m';
679
- export const paint = (text, hex, bold = false) => `${bold ? '\x1b[1m' : ''}${fg(hex)}${text}${RESET}`;
682
+ export const paint = (text, hex, bold = false) => (hex || bold ? `${bold ? '\x1b[1m' : ''}${fg(hex)}${text}${RESET}` : text);
680
683
 
681
- // @comment -- "Colours banner lines with the brand palette: 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."
682
- export function colorize(lines, inputs = {}) {
683
- const P = PALETTE;
684
+ // @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."
685
+ export function colorize(lines, inputs = {}, theme = 'dark') {
686
+ const P = THEMES[theme] ?? THEMES.neutral;
684
687
  // One escape per run of same-coloured characters, so the banner stays far inside the 10,000-character cap.
685
688
  const runs = (chars, colourOf) => {
686
689
  let out = '';
@@ -0,0 +1,115 @@
1
+ // @comment -- "Bravos's terminal colours, by role, for three themes, and the one rule that picks a theme. Dependency-free, shared by the session-start banner (hooks/lib/briefing.mjs) and, as a checked twin, by bravos watch (src/palette.ts)."
2
+ //
3
+ // Why three themes. The original palette was tuned for a dark terminal: body text
4
+ // in near-white #f0f0f0 and bright green/amber accents, which all but vanish on a
5
+ // white background (contrast 1.1:1 to 1.9:1). Nothing can tell a hook which
6
+ // background its message will be drawn on, so the theme is chosen by what the
7
+ // person said (BRAVOS_THEME, or bravos start), what the terminal says (COLORFGBG),
8
+ // or, failing both, `neutral`: text in the terminal's own default colour and
9
+ // mid-tone accents that keep at least 3:1 against white AND black.
10
+ //
11
+ // A role whose value is null is drawn in the terminal's default foreground, which
12
+ // the terminal has already chosen to be readable on its own background.
13
+ //
14
+ // Text that sits on its own background (severity badges, key chips, the watch
15
+ // header bar) is a fixed pair and is drawn from FIXED in every theme.
16
+
17
+ import { existsSync, readFileSync } from 'node:fs';
18
+ import { homedir } from 'node:os';
19
+ import { join } from 'node:path';
20
+
21
+ export const THEMES = {
22
+ // The original palette: for dark terminals.
23
+ dark: {
24
+ green: '#33d49d', blue: '#0360a2', light: '#f0f0f0', steel: '#55899e', red: '#ea1d1d',
25
+ slate: '#3b6779', amber: '#f0b429', line: '#2b4f5c',
26
+ },
27
+ // For light terminals: every text colour at least 4.5:1 on white; borders 3:1.
28
+ light: {
29
+ green: '#0f7a55', blue: '#0360a2', light: null, steel: '#3f6576', red: '#c41616',
30
+ slate: '#4d6b78', amber: '#9a6400', line: '#7d98a3',
31
+ },
32
+ // When the background is unknown: at least 3:1 on white and on black.
33
+ neutral: {
34
+ green: '#1e9a6c', blue: '#2f7fc1', light: null, steel: '#4f8296', red: '#e02424',
35
+ slate: '#5a7d8b', amber: '#b07a00', line: '#5a7d8b',
36
+ },
37
+ };
38
+
39
+ // Pairs drawn on their own background: the same in every theme. Red is a shade
40
+ // deeper than the dark theme's text red so white on it keeps 4.5:1 (CRIT, HIGH).
41
+ export const FIXED = {
42
+ green: '#33d49d', blue: '#0360a2', light: '#f0f0f0', steel: '#55899e', red: '#dc1f1f',
43
+ slate: '#3b6779', amber: '#f0b429', line: '#2b4f5c', ink: '#0e1b21', deep: '#1f3943', white: '#ffffff',
44
+ };
45
+
46
+ export const THEME_NAMES = ['dark', 'light', 'neutral'];
47
+
48
+ /** The colour for a role in a theme; null means the terminal's default foreground. */
49
+ export function roleColour(theme, role) {
50
+ const t = THEMES[theme] ?? THEMES.neutral;
51
+ return role in t ? t[role] : FIXED[role] ?? null;
52
+ }
53
+
54
+ /** Where Bravos keeps its own settings: $BRAVOS_HOME, else ~/.bravos. */
55
+ export function bravosHome(env = process.env) {
56
+ return env.BRAVOS_HOME || join(env.HOME || homedir(), '.bravos');
57
+ }
58
+
59
+ /** The theme saved by `bravos start` (config.json in $BRAVOS_HOME), or null. Never throws. */
60
+ export function savedTheme(env = process.env) {
61
+ try {
62
+ const file = join(bravosHome(env), 'config.json');
63
+ if (!existsSync(file)) return null;
64
+ const t = JSON.parse(readFileSync(file, 'utf8'))?.theme;
65
+ return THEME_NAMES.includes(t) ? t : null;
66
+ } catch {
67
+ return null;
68
+ }
69
+ }
70
+
71
+ /**
72
+ * COLORFGBG is "fg;bg" (sometimes "fg;default;bg"), set by rxvt, Konsole, iTerm2 and
73
+ * others. A background of 7 (white) or 15 (bright white) is light; 0–6 and 8 dark.
74
+ */
75
+ export function themeFromColorFgBg(value) {
76
+ if (!value) return null;
77
+ const bg = Number(String(value).split(';').pop());
78
+ if (!Number.isInteger(bg)) return null;
79
+ if (bg === 7 || bg === 15) return 'light';
80
+ if ((bg >= 0 && bg <= 6) || bg === 8) return 'dark';
81
+ return null;
82
+ }
83
+
84
+ /** An OSC 11 answer ("rgb:ffff/ffff/ffff" or "#rrggbb") as a theme, or null. */
85
+ export function themeFromBackground(answer) {
86
+ if (!answer) return null;
87
+ let r, g, b;
88
+ const m = /rgb:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i.exec(answer);
89
+ if (m) {
90
+ [r, g, b] = [m[1], m[2], m[3]].map((h) => parseInt(h, 16) / (16 ** h.length - 1));
91
+ } else {
92
+ const h = /#([0-9a-f]{6})/i.exec(answer);
93
+ if (!h) return null;
94
+ [r, g, b] = [0, 2, 4].map((i) => parseInt(h[1].slice(i, i + 2), 16) / 255);
95
+ }
96
+ const lum = 0.2126 * r + 0.7152 * g + 0.0722 * b;
97
+ return lum > 0.5 ? 'light' : 'dark';
98
+ }
99
+
100
+ /**
101
+ * Which theme to draw in, and why. In order: BRAVOS_THEME (light, dark or neutral;
102
+ * auto or unset falls through), what the terminal answered (`detected`, watch only),
103
+ * COLORFGBG, the choice saved by `bravos start`, then neutral.
104
+ */
105
+ // @comment -- "Theme choice in a fixed order: BRAVOS_THEME, the terminal's own answer (watch), COLORFGBG, the saved choice, then neutral; returns the theme and the reason so bravos doctor can say why"
106
+ export function resolveTheme(env = process.env, detected = null) {
107
+ const asked = String(env.BRAVOS_THEME ?? '').toLowerCase();
108
+ if (THEME_NAMES.includes(asked)) return { theme: asked, source: 'BRAVOS_THEME' };
109
+ if (THEME_NAMES.includes(detected)) return { theme: detected, source: 'terminal' };
110
+ const fgbg = themeFromColorFgBg(env.COLORFGBG);
111
+ if (fgbg) return { theme: fgbg, source: 'COLORFGBG' };
112
+ const saved = savedTheme(env);
113
+ if (saved) return { theme: saved, source: 'saved by bravos start' };
114
+ return { theme: 'neutral', source: 'default (background unknown)' };
115
+ }
@@ -8,7 +8,7 @@ const READY_ARG = /(?:^|[\s;&|(])gh\s+pr\s+ready\s+([^\s;&|)-][^\s;&|)]*)/;
8
8
  const BODY_FILE = /(?:--body-file|-F)[=\s]+("([^"]+)"|'([^']+)'|(\S+))/;
9
9
  // @comment -- "The hook is registered with a 180 s timeout; the whole gate shares 150 s so it always answers before the harness kills it."
10
10
  export const GATE_DEADLINE_MS = 150000;
11
- // @comment -- "The person's recorded proving preference (see autopilot.mjs readProving); a branch that changes it must disclose that in the PR body."
11
+ // @comment -- "The person's recorded proving preference (see proving.mjs readProving); a branch that changes it must disclose that in the PR body."
12
12
  export const PROVING_FILE = '.guardlink/proving.md';
13
13
  const SPAWN_CAP_MS = 60000;
14
14