@bugb-technologies/bravos 1.9.0 → 1.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -636,12 +636,27 @@ export function buildProgram(io, result) {
636
636
  if (!opts.yes && !interactive)
637
637
  throw new BravosError(`bravos ${name} asks questions, so it needs a terminal. In a script use: bravos ${name} --yes --preset pr <dir>`);
638
638
  const prompter = interactive ? ui.terminalPrompter() : ui.scriptedPrompter({}, io.stdout);
639
- const capture = async (argv) => {
639
+ // @comment -- "Every bravos command Apply runs is a child of this same node and cli.js, no shell, with its output captured line by line and each line passed to the spinner as it arrives. Run in this process instead, the installs (npm, and cargo compiling cxg for minutes) block it, the spinner cannot redraw and the screen looks frozen; guardlink init would also print straight into the terminal under it. The child gets no terminal, so nothing it runs can ask a question."
640
+ const capture = (argv, onLine) => new Promise((done) => {
640
641
  const out = [];
641
642
  const err = [];
642
- const code = await run(argv, { ...io, stdout: (x) => out.push(x), stderr: (x) => err.push(x) });
643
- return { code, out, err };
644
- };
643
+ const child = spawnChild(process.execPath, [fileURLToPath(import.meta.url), ...argv], { env: io.env, stdio: ['ignore', 'pipe', 'pipe'] });
644
+ const lines = (into) => {
645
+ let rest = '';
646
+ return (b) => {
647
+ const parts = (rest + b.toString('utf8')).split('\n');
648
+ rest = parts.pop() ?? '';
649
+ for (const l of parts) {
650
+ into.push(l);
651
+ onLine?.(l);
652
+ }
653
+ };
654
+ };
655
+ child.stdout.on('data', lines(out));
656
+ child.stderr.on('data', lines(err));
657
+ child.on('error', (e) => done({ code: 1, out, err: [...err, e.message] }));
658
+ child.on('close', (code) => done({ code: code ?? 1, out, err }));
659
+ });
645
660
  result.code = await runStart({ dir, again: opts.again, yes: opts.yes, preset: opts.preset, command: name }, {
646
661
  prompter,
647
662
  env: io.env,
@@ -47,6 +47,8 @@ export function installProofTool(name, env, echo, pins = PROOF_TOOL_PINS) {
47
47
  }
48
48
  const work = mkdtempSync(join(tmpdir(), 'bravos-tools-'));
49
49
  function invoke(command, args, cwd, step) {
50
+ // Each step is said before it runs, so whoever is watching (the guided setup's spinner) knows what the wait is for.
51
+ echo(`${name}: ${step}${command === 'cargo' ? ' (cargo compiles it from source; this is the long step)' : ''}…`);
50
52
  const result = spawnSync(executables.get(command) ?? command, args, {
51
53
  cwd, env: installEnv, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 32 * 1024 * 1024, timeout: 30 * 60 * 1000,
52
54
  });
@@ -458,7 +458,7 @@ async function flow(opts, d) {
458
458
  ...(has(s, 'codegraph') ? [`bravos graph build ${JSON.stringify(answers.repo)} --scip no-exec`] : []),
459
459
  ].join('\n'), 'Commands');
460
460
  }
461
- return apply(toAnswers(s), s, d, opts, { missingTools: missingTools(s).length > 0, missingBundles: missingBundles(s).length > 0, codegraph: has(s, 'codegraph'), join: !!s.join, commits: s.commits });
461
+ return apply(toAnswers(s), s, d, opts, { missingTools: missingTools(s).length > 0, missingBundles: missingBundles(s).length > 0, codegraph: has(s, 'codegraph'), join: !!s.join, commits: s.commits, cxgMissing: missingTools(s).some((i) => i.id === 'cxg') });
462
462
  }
463
463
  function toAnswers(s) {
464
464
  return {
@@ -483,8 +483,20 @@ async function apply(answers, s, d, opts, has) {
483
483
  const p = d.prompter;
484
484
  const { repo, agents } = answers;
485
485
  writeTheme(d.home, answers.theme);
486
+ // @comment -- "Apply says up front how many steps it will take and which may be slow, and numbers each one, so a person can tell it is working and roughly how far along it is. cxg is compiled from source by cargo, which is the one step that can take many minutes."
487
+ const steps = [
488
+ answers.installTools && has.missingTools && !opts.yes,
489
+ (answers.installTools || opts.yes) && has.missingBundles,
490
+ true,
491
+ has.codegraph,
492
+ ].filter(Boolean).length;
493
+ let at = 0;
494
+ const step = (label) => `[${++at}/${steps}] ${label}`;
495
+ const slowCxg = answers.installTools && has.missingTools && !opts.yes && has.cxgMissing;
496
+ const tools = slowCxg ? 'Installing guardlink and cxg (cxg is compiled from source: often 5 to 10 minutes)' : 'Installing guardlink and cxg';
497
+ p.info(`Applying: ${steps} step${steps === 1 ? '' : 's'}${slowCxg ? '. The first takes longest, because cargo compiles cxg; the clock and the line beside it show where it is' : ''}. Leave this window open until "Bravos is set up".`);
486
498
  if (answers.installTools && has.missingTools && !opts.yes) {
487
- const r = await p.spin('Installing guardlink and cxg', () => d.bravos(['setup', '--tools', '-y']), (r) => (r.code ? { fail: 'Installing guardlink and cxg — failed' } : 'Installed guardlink and cxg'));
499
+ const r = await p.spin(step(tools), (progress) => d.bravos(['setup', '--tools', '-y'], progress), (r) => (r.code ? { fail: `${tools} — failed` } : 'Installed guardlink and cxg'));
488
500
  for (const l of [...r.out, ...r.err])
489
501
  (r.code ? p.warn : p.info)(l);
490
502
  // A tool that would not install (no cargo, offline, an incompatible build) limits proving, not the
@@ -494,14 +506,14 @@ async function apply(answers, s, d, opts, has) {
494
506
  }
495
507
  // The bundles are named: a bare `bravos setup` is the whole setup now, and would start this wizard again. An unattended run fetches them too; they are Bravos's own, signed.
496
508
  if ((answers.installTools || opts.yes) && has.missingBundles) {
497
- const r = await p.spin('Fetching the Bravos analyzer and code graph', () => d.bravos(['setup', '--analyzer', '--codegraph']), (r) => (r.code ? { fail: 'Fetching the analyzer and code graph — failed' } : 'Fetched the analyzer and code graph'));
509
+ const r = await p.spin(step('Fetching the Bravos analyzer and code graph'), (progress) => d.bravos(['setup', '--analyzer', '--codegraph'], progress), (r) => (r.code ? { fail: 'Fetching the analyzer and code graph — failed' } : 'Fetched the analyzer and code graph'));
498
510
  for (const l of [...r.out, ...r.err])
499
511
  (r.code ? p.warn : p.info)(l);
500
512
  }
501
513
  // @comment -- "Joining runs bravos setup, which re-applies what the repository already has and never rewrites the team's choices; a first setup runs bravos setup with the flags the answers amount to."
502
514
  const init = has.join
503
- ? await p.spin('Bringing this machine up to date with the repository', () => d.bravos(['sync', repo]), (r) => (r.code ? { fail: 'Syncing the repository — failed' } : 'Repository in sync'))
504
- : await p.spin('Setting up the repository', () => d.bravos(initArgs(answers)), (r) => (r.code ? { fail: 'Setting up the repository — failed' } : 'Repository set up'));
515
+ ? await p.spin(step('Bringing this machine up to date with the repository'), (progress) => d.bravos(['sync', repo], progress), (r) => (r.code ? { fail: 'Syncing the repository — failed' } : 'Repository in sync'))
516
+ : await p.spin(step('Setting up the repository'), (progress) => d.bravos(initArgs(answers), progress), (r) => (r.code ? { fail: 'Setting up the repository — failed' } : 'Repository set up'));
505
517
  for (const l of init.out)
506
518
  p.info(l);
507
519
  if (init.code !== 0) {
@@ -534,7 +546,7 @@ async function apply(answers, s, d, opts, has) {
534
546
  (r.code ? p.warn : p.info)(r.code ? `gh secret set ${n} failed — add it in the repository's Settings → Secrets` : `secret ${n} set`);
535
547
  }
536
548
  if (has.codegraph) {
537
- const g = await p.spin('Building the code graph (a minute or two; longer on a big repository)', () => d.bravosChild(['graph', 'build', repo, '--scip', 'no-exec', '--json']), (r) => (graphSummary(r).ok ? graphSummary(r).line : { fail: graphSummary(r).line }));
549
+ const g = await p.spin(step('Building the code graph (a minute or two; longer on a big repository)'), () => d.bravosChild(['graph', 'build', repo, '--scip', 'no-exec', '--json']), (r) => (graphSummary(r).ok ? graphSummary(r).line : { fail: graphSummary(r).line }));
538
550
  const sum = graphSummary(g);
539
551
  for (const n of sum.notes)
540
552
  (sum.ok ? p.info : p.warn)(n);
package/dist/start/ui.js CHANGED
@@ -132,19 +132,26 @@ export function terminalPrompter() {
132
132
  });
133
133
  return String((await ask(k, p)) ?? '');
134
134
  },
135
+ // @comment -- "A step that takes minutes must look alive: the spinner shows a running clock, and the latest line the work reports (the install step it is on) beside the label, cut to the terminal's width. This only moves if the work leaves the event loop free, which is why Apply runs its long steps as child processes (src/cli.ts)."
135
136
  spin: async (label, work, done) => {
136
- const s = clack.spinner();
137
- const t0 = Date.now();
137
+ const s = clack.spinner({ indicator: 'timer' });
138
138
  s.start(label);
139
+ const width = Math.max(40, (process.stdout.columns || 80) - 14);
140
+ const progress = (line) => {
141
+ const text = line.replace(/\x1b\[[0-9;]*m/g, '').replace(/\s+/g, ' ').trim();
142
+ if (!text)
143
+ return;
144
+ const full = `${label} — ${text}`;
145
+ s.message(full.length > width ? `${full.slice(0, width - 1)}…` : full);
146
+ };
139
147
  try {
140
- const r = await work();
141
- const secs = Math.round((Date.now() - t0) / 1000);
148
+ const r = await work(progress);
149
+ // The spinner's own clock already prints the time taken beside the final line.
142
150
  const res = done ? done(r) : label;
143
- const took = secs >= 2 ? ` (${secs}s)` : '';
144
151
  if (typeof res === 'string')
145
- s.stop(`${res}${took}`);
152
+ s.stop(res);
146
153
  else
147
- s.error(`${res.fail}${took}`);
154
+ s.error(res.fail);
148
155
  return r;
149
156
  }
150
157
  catch (e) {
@@ -210,7 +217,7 @@ export function scriptedPrompter(answers, out = () => { }) {
210
217
  confirm: async (id, _m, initial) => pick(id, initial),
211
218
  secret: async (id) => String(pick(id, undefined)),
212
219
  spin: async (label, work, done) => {
213
- const r = await work();
220
+ const r = await work(() => { });
214
221
  const res = done ? done(r) : label;
215
222
  out(typeof res === 'string' ? res : `! ${res.fail}`);
216
223
  return r;
package/docs/UPGRADING.md CHANGED
@@ -2,6 +2,11 @@
2
2
 
3
3
  After `npm install -g @bugb-technologies/bravos`, run **`bravos setup`** in a repository you work in: it brings this machine and that repository up to date. In repositories you work in with an agent you can skip even that: the agent runs it at the start of a session. The notes below say what else changes, newest first. (Before 1.9 the same was `bravos setup --tools -y` per machine and `bravos sync` per repository; both still work.)
4
4
 
5
+ ## 1.9.1
6
+
7
+ - **Apply shows what it is doing.** After you choose Apply in `bravos setup`, the screen used to stay still while the tools installed, which can take several minutes because cargo compiles cxg. It now says how many steps there are, numbers each one, and shows a running clock and the step it is on.
8
+ - **Fixed:** two agent sessions starting at the same moment could build the same code graph twice.
9
+
5
10
  ## 1.9.0
6
11
 
7
12
  1.9 makes **`bravos setup`** the one command for setting Bravos up. It looks at this machine and the repository you are in and does only what is missing.
@@ -1,7 +1,7 @@
1
1
  // @comment -- "The background code graph build. A graph is keyed to the commit it was built at, so after every commit there is none, and until now only a person or an agent told to do so rebuilt it. When the session hook finds no graph for the commit, it starts one quiet build here: a detached process that runs `bravos graph build <root> --scip no-exec` (no model, no network, and no-exec means the repository's own build scripts are never run), records how it ended, tells bravos watch, and exits. One build per repository at a time, whatever the number of sessions: the runner takes an exclusive lock under $BRAVOS_HOME/autobuild/<repository>/ before it builds. It starts only on the Team plan, only in a repository that installed Bravos (never from the user-level or plugin copy of the hook), never in CI, and never when BRAVOS_GRAPH_AUTOBUILD=off. A build that failed is not retried for the same commit for six hours."
2
2
  import { spawn, spawnSync } from 'node:child_process';
3
3
  import { createHash } from 'node:crypto';
4
- import { existsSync, mkdirSync, openSync, closeSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { existsSync, linkSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
5
5
  import { join } from 'node:path';
6
6
  import { fileURLToPath } from 'node:url';
7
7
  import { bravosHome } from './licence.mjs';
@@ -43,10 +43,22 @@ const alive = (pid) => {
43
43
 
44
44
  const justBuilt = (last, sha, now) => !!last && last.ok === true && last.sha === sha && typeof last.at === 'number' && now - last.at >= 0 && now - last.at < JUST_BUILT_MS;
45
45
 
46
+ /** A lock can be seen before its contents are (a runner of 1.8 created it empty and filled it after): one that young is a build starting, not a dead one. */
47
+ export const LOCK_SETTLE_MS = 10 * 1000;
48
+
46
49
  /** The build running for this repository, if any: a lock whose process is alive and which is not older than a build can be. */
47
50
  export function runningBuild(dir, now = Date.now()) {
48
51
  const lock = dir ? readJson(join(dir, 'lock')) : null;
49
- if (!lock || typeof lock.at !== 'number') return null;
52
+ if (!lock || typeof lock.at !== 'number') {
53
+ // @comment -- "A lock with no readable contents is a build starting if it was made in the last few seconds, and a dead one's only after that; read sooner as dead, a second runner removed it and built too."
54
+ try {
55
+ const made = statSync(join(dir, 'lock')).mtimeMs;
56
+ if (now - made < LOCK_SETTLE_MS) return { pid: null, sha: null, at: made };
57
+ } catch {
58
+ /* no lock */
59
+ }
60
+ return null;
61
+ }
50
62
  return alive(lock.pid) && now - lock.at < LOCK_STALE_MS ? { pid: lock.pid, sha: typeof lock.sha === 'string' ? lock.sha : null, at: lock.at } : null;
51
63
  }
52
64
 
@@ -94,15 +106,17 @@ export function runBuild(root, dir, sha, { env = process.env, now = () => Date.n
94
106
  mkdirSync(dir, { recursive: true, mode: 0o700 });
95
107
  // A lock left by a build that died is cleared first; a live one stops us.
96
108
  if (existsSync(lock) && !runningBuild(dir, now())) rmSync(lock, { force: true });
97
- let fd;
109
+ // @comment -- "The lock is created with its contents already in it: written to a file of this process's own, then hard-linked to the lock name, which fails if the lock exists. Created empty and filled afterwards, a second runner could read it in between, take the empty lock for one a dead build left, remove it and build as well: two sessions starting together then built the same graph twice."
110
+ const mine = `${lock}.${process.pid}`;
98
111
  try {
99
- fd = openSync(lock, 'wx', 0o600);
112
+ writeFileSync(mine, JSON.stringify({ pid: process.pid, sha, at: now() }), { mode: 0o600 });
113
+ linkSync(mine, lock);
100
114
  } catch {
101
115
  return { ran: false };
116
+ } finally {
117
+ rmSync(mine, { force: true });
102
118
  }
103
119
  try {
104
- writeFileSync(fd, JSON.stringify({ pid: process.pid, sha, at: now() }));
105
- closeSync(fd);
106
120
  // Another runner may have finished this very commit between our session's probe and now: one build is enough.
107
121
  if (justBuilt(readJson(join(dir, 'last.json')), sha, now())) return { ran: false };
108
122
  logWatchEvent(root, { summary: `code graph: building in the background for ${sha}`, keys: ['graph'] });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bugb-technologies/bravos",
3
- "version": "1.9.0",
3
+ "version": "1.9.1",
4
4
  "description": "Skills pack and installer that make Claude Code and Codex power users of guardlink (threat-model-as-code) and cert-x-gen (pentest-as-code).",
5
5
  "keywords": [
6
6
  "security",