@bugb-technologies/bravos 1.5.1 → 1.5.3

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/artifacts.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { createHash, createPublicKey, verify as cryptoVerify } from 'node:crypto';
3
3
  import { chmodSync, closeSync, existsSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, symlinkSync, unlinkSync, writeSync } from 'node:fs';
4
4
  import { arch, platform } from 'node:os';
5
- import { dirname, join } from 'node:path';
5
+ import { basename, dirname, join } from 'node:path';
6
6
  import { gunzipSync } from 'node:zlib';
7
7
  import { refresh, userAgent } from './device.js';
8
8
  import { licenceLib } from './licence.js';
@@ -276,6 +276,36 @@ export function staged(env, kind) {
276
276
  }
277
277
  return null;
278
278
  }
279
+ // @comment -- "The version of a staged bundle: what its own BUNDLE.json says, else the version folder it sits in ($BRAVOS_HOME/<kind>/<version>/<target>), else null. Read-only; a bundle that names no version is never treated as old."
280
+ export function stagedVersion(root) {
281
+ const dotted = (v) => (typeof v === 'string' && /^\d+(\.\d+)+/.test(v) ? v : null);
282
+ try {
283
+ const said = dotted(JSON.parse(readFileSync(join(root, BUNDLE_FILE), 'utf8'))?.version);
284
+ if (said)
285
+ return said;
286
+ }
287
+ catch {
288
+ /* fall through to the folder name */
289
+ }
290
+ return dotted(basename(dirname(root)));
291
+ }
292
+ // @comment -- "Whether dotted version `have` is lower than `want`, comparing the numeric parts left to right; anything after the numbers (a pre-release tag) is ignored, and a version that does not parse is never older."
293
+ export function olderThan(have, want) {
294
+ const parts = (v) => {
295
+ const m = /^(\d+(?:\.\d+)*)/.exec(v);
296
+ return m ? m[1].split('.').map(Number) : null;
297
+ };
298
+ const a = parts(have);
299
+ const b = parts(want);
300
+ if (!a || !b)
301
+ return false;
302
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
303
+ const d = (a[i] ?? 0) - (b[i] ?? 0);
304
+ if (d !== 0)
305
+ return d < 0;
306
+ }
307
+ return false;
308
+ }
279
309
  /** The environment a staged bundle declares in BUNDLE.json: `env` (relative paths made absolute) and `path_prepend`. */
280
310
  export function bundleEnvironment(root, base) {
281
311
  const env = { ...base };
package/dist/cli.js CHANGED
@@ -560,6 +560,7 @@ export function buildProgram(io, result) {
560
560
  }
561
561
  const extra = args.filter((a) => a !== '--json');
562
562
  // The same document the Python CLI printed: {result} on an answer, {error, message, remedy} on a refusal, exit 2 when the graph is not built.
563
+ // A graph another session or a build holds is {error: graph_busy} with exit 1: only "not built" is exit 2, which is what callers rebuild on.
563
564
  const a = await askGraph(root, io.env, question, extra);
564
565
  if (!a)
565
566
  throw new BravosError('codegraph-mcp is not installed: bravos setup --codegraph fetches it');
package/dist/codegraph.js CHANGED
@@ -57,6 +57,18 @@ export class GraphUnavailable extends BravosError {
57
57
  super(message);
58
58
  }
59
59
  }
60
+ // @comment -- "The code graph is there and another process holds its lock: a second session reading the same snapshot, or a build in progress. codegraph-mcp 0.1.1 waits for the lock (20 s by default) and then answers this, with data.reason 'graph_busy'. It is never 'no graph': the remedy is to ask again, not to rebuild."
61
+ export class GraphBusy extends BravosError {
62
+ constructor(message) {
63
+ super(message);
64
+ }
65
+ }
66
+ /** What to tell a person, or an agent, when the graph answered busy. */
67
+ export const GRAPH_BUSY_REMEDY = 'another session or a build is using the code graph; ask again in a moment (do not rebuild it)';
68
+ // The server's own sentence, for an answer that reached us as text only (a stored error string).
69
+ const BUSY_TEXT = /code graph for project \S+ is busy/i;
70
+ /** Whether an error, or an error's text, is the graph's busy answer. */
71
+ export const isGraphBusy = (e) => e instanceof GraphBusy || BUSY_TEXT.test(typeof e === 'string' ? e : (e?.message ?? ''));
60
72
  // @comment -- "A minimal MCP stdio client: newline-delimited JSON-RPC 2.0 to a child codegraph-mcp --project-path ROOT. One session per question; the server is killed on close or timeout. stderr is kept for the error message; stdout is parsed line by line, with anything that is not a JSON-RPC message ignored."
61
73
  export class GraphSession {
62
74
  child;
@@ -103,8 +115,11 @@ export class GraphSession {
103
115
  if (!p)
104
116
  continue;
105
117
  this.pending.delete(msg.id);
106
- if (msg.error)
107
- p.reject(new BravosError(msg.error.message ?? 'the graph answered an error'));
118
+ if (msg.error) {
119
+ const said = msg.error.message ?? 'the graph answered an error';
120
+ // The structured reason first; the sentence is the fallback for a server that sends only text.
121
+ p.reject(msg.error.data?.reason === 'graph_busy' || BUSY_TEXT.test(said) ? new GraphBusy(said) : new BravosError(said));
122
+ }
108
123
  else
109
124
  p.resolve(msg.result);
110
125
  }
@@ -174,46 +189,95 @@ export function open(root, env) {
174
189
  throw new GraphUnavailable('codegraph-mcp is not installed: bravos setup --codegraph fetches it (on the Team plan)');
175
190
  return new GraphSession(bin, root, env);
176
191
  }
192
+ // What codegraph-mcp answers when it finds no graph for the project. It gives the same answer, wrongly, to a
193
+ // session that opens the graph in the same few hundred milliseconds as another one (measured: two sessions
194
+ // started together, exactly one answers; a session started while another is mid-question answers fine).
195
+ const NO_GRAPH = /No CodeGraph for project/i;
196
+ // Two more tries, each after a short pause of uneven length so sessions that collided do not collide again, step
197
+ // out of another session's opening moment and keep a true "no graph" answer fast (about a second more; the
198
+ // session-start probe reads an answer slower than three seconds as a graph that is loading).
199
+ export const GRAPH_RETRIES = 2;
200
+ export const GRAPH_RETRY_MS = 250;
201
+ const pause = (ms) => new Promise((r) => setTimeout(r, ms));
202
+ // @comment -- "Runs one graph session and, when it reports no graph, runs it again, up to twice, after short pauses of uneven length, before believing it: codegraph-mcp gives that answer to a session that opens the graph at the same moment as another (a second terminal, the agent's own MCP server, bravos watch beside bravos dashboard). `noGraph` says whether a session's outcome was that answer. A real 'no graph' costs two extra short sessions, about a second; anything else is returned or thrown as it came."
203
+ export async function withGraphRetry(session, noGraph, retries = GRAPH_RETRIES, waitMs = GRAPH_RETRY_MS) {
204
+ for (let attempt = 0;; attempt++) {
205
+ let outcome;
206
+ try {
207
+ outcome = { value: await session() };
208
+ }
209
+ catch (e) {
210
+ outcome = { error: e };
211
+ }
212
+ if (attempt < retries && noGraph(outcome)) {
213
+ await pause(waitMs + Math.floor(Math.random() * waitMs * 1.4));
214
+ continue;
215
+ }
216
+ if (outcome.error)
217
+ throw outcome.error;
218
+ return outcome.value;
219
+ }
220
+ }
177
221
  // @comment -- "One question, in and out: `bravos graph attack-surface --json` becomes tools/call codegraph_attack_surface. Positional words fill the tool's first required string argument (symbol, query); --name value pairs fill the rest, parsed as JSON when they look like it. The tool list comes from the binary on this machine, never from a stored copy."
178
222
  export async function ask(root, env, question, argv, timeoutMs = 60000) {
179
- const s = open(root, env);
180
- try {
181
- await s.initialize(Math.min(timeoutMs, 30000));
182
- const tools = await s.tools(Math.min(timeoutMs, 30000));
183
- const name = question.startsWith('codegraph_') ? question : `codegraph_${question.replace(/-/g, '_')}`;
184
- const tool = tools.find((t) => t.name === name);
185
- if (!tool)
186
- throw new BravosError(`the graph has no question ${JSON.stringify(question)}; it answers: ${tools.map((t) => t.name.replace(/^codegraph_/, '').replace(/_/g, '-')).join(', ')}`);
187
- return await s.call(name, bindArguments(tool, argv), timeoutMs);
188
- }
189
- finally {
190
- s.close();
191
- }
223
+ const once = async () => {
224
+ const s = open(root, env);
225
+ try {
226
+ await s.initialize(Math.min(timeoutMs, 30000));
227
+ const tools = await s.tools(Math.min(timeoutMs, 30000));
228
+ const name = question.startsWith('codegraph_') ? question : `codegraph_${question.replace(/-/g, '_')}`;
229
+ const tool = tools.find((t) => t.name === name);
230
+ if (!tool)
231
+ throw new BravosError(`the graph has no question ${JSON.stringify(question)}; it answers: ${tools.map((t) => t.name.replace(/^codegraph_/, '').replace(/_/g, '-')).join(', ')}`);
232
+ return await s.call(name, bindArguments(tool, argv), timeoutMs);
233
+ }
234
+ finally {
235
+ s.close();
236
+ }
237
+ };
238
+ return withGraphRetry(once, (o) => !!o.error && NO_GRAPH.test(o.error.message ?? ''));
192
239
  }
193
- // @comment -- "Several questions in one session: the server loads the graph once instead of once per question. A tool the binary does not offer, or one that refuses or times out, is recorded as an error for that question alone; the others are still asked. Throws only when no session can be opened (codegraph-mcp missing or not starting)."
240
+ // @comment -- "Several questions in one session: the server loads the graph once instead of once per question. A tool the binary does not offer, or one that refuses or times out, is recorded as an error for that question alone; the others are still asked. The exception is a busy graph: the server has already waited its whole lock wait for that answer, so the remaining questions are marked busy without being asked (asking each would wait that long again). A session whose first answer is 'no graph' is run again (withGraphRetry). Throws only when no session can be opened (codegraph-mcp missing or not starting)."
194
241
  export async function askMany(root, env, calls, timeoutMs = 60000) {
195
- const s = open(root, env);
196
- try {
197
- await s.initialize(Math.min(timeoutMs, 30000));
198
- const tools = (await s.tools(Math.min(timeoutMs, 30000))).map((t) => t.name);
199
- const answers = {};
200
- for (const c of calls) {
201
- if (!tools.includes(c.tool)) {
202
- answers[c.tool] = { error: 'this code graph does not answer that question' };
203
- continue;
204
- }
205
- try {
206
- answers[c.tool] = { result: await s.call(c.tool, c.args ?? {}, timeoutMs) };
207
- }
208
- catch (e) {
209
- answers[c.tool] = { error: e.message };
242
+ const once = async () => {
243
+ const s = open(root, env);
244
+ try {
245
+ await s.initialize(Math.min(timeoutMs, 30000));
246
+ const tools = (await s.tools(Math.min(timeoutMs, 30000))).map((t) => t.name);
247
+ const answers = {};
248
+ let busy = null;
249
+ for (const c of calls) {
250
+ if (!tools.includes(c.tool)) {
251
+ answers[c.tool] = { error: 'this code graph does not answer that question' };
252
+ continue;
253
+ }
254
+ if (busy) {
255
+ answers[c.tool] = { error: busy, busy: true };
256
+ continue;
257
+ }
258
+ try {
259
+ answers[c.tool] = { result: await s.call(c.tool, c.args ?? {}, timeoutMs) };
260
+ }
261
+ catch (e) {
262
+ if (isGraphBusy(e)) {
263
+ busy = e.message;
264
+ answers[c.tool] = { error: busy, busy: true };
265
+ }
266
+ else
267
+ answers[c.tool] = { error: e.message };
268
+ }
210
269
  }
270
+ return { tools, answers };
211
271
  }
212
- return { tools, answers };
213
- }
214
- finally {
215
- s.close();
216
- }
272
+ finally {
273
+ s.close();
274
+ }
275
+ };
276
+ // The graph is opened by the session's first question, so "no graph" on the first one asked is the answer to retry.
277
+ return withGraphRetry(once, (o) => {
278
+ const first = o.value && calls.map((c) => o.value.answers[c.tool]).find((a) => a && !('error' in a && a.error === 'this code graph does not answer that question'));
279
+ return !!first && 'error' in first && NO_GRAPH.test(first.error);
280
+ });
217
281
  }
218
282
  export async function listTools(root, env, timeoutMs = 30000) {
219
283
  const s = open(root, env);
@@ -284,6 +348,9 @@ export async function probe(root, env, timeoutMs = 3000) {
284
348
  }
285
349
  catch (e) {
286
350
  const m = e.message ?? '';
351
+ // Busy means a graph is there (or being built): the same reading as one that is still loading.
352
+ if (isGraphBusy(e))
353
+ return 'cli';
287
354
  if (/no graph|codegraph_unavailable|not built|no CodeGraph|nothing is there/i.test(m))
288
355
  return 'not-built';
289
356
  if (e instanceof GraphUnavailable && /within \d+s/.test(m))
package/dist/dashboard.js CHANGED
@@ -138,12 +138,14 @@ export function codeGraphStore(answers) {
138
138
  };
139
139
  }
140
140
  const NOT_BUILT = /no graph|No CodeGraph|codegraph_unavailable|not built|nothing is there|not available for project/i;
141
- // @comment -- "What the code graph says about itself for this checkout, from one cheap question: current, not-built (no graph for this commit), diverged (the working tree has moved since it was built), or unknown when it cannot say. Read-only."
141
+ // @comment -- "What the code graph says about itself for this checkout, from one cheap question: current, not-built (no graph for this commit), diverged (the working tree has moved since it was built), busy (it is there and another session or a build holds it), or unknown when it cannot say. Busy is tested before not-built and is never a reason to build. Read-only."
142
142
  export async function graphState(root, env) {
143
143
  try {
144
144
  const a = (await graph.askMany(root, env, [{ tool: 'codegraph_entry_points', args: { limit: 1 } }], 60000)).answers.codegraph_entry_points;
145
145
  if (!a)
146
146
  return 'unknown';
147
+ if ('error' in a && (a.busy || graph.isGraphBusy(a.error)))
148
+ return 'busy';
147
149
  if ('error' in a)
148
150
  return NOT_BUILT.test(a.error) ? 'not-built' : 'unknown';
149
151
  const state = text(obj(obj(a.result).graph_currency).state);
@@ -154,8 +156,8 @@ export async function graphState(root, env) {
154
156
  }
155
157
  }
156
158
  // @comment -- "Makes the code graph match the code before the dashboard draws from it, so a fresh page is never drawn from an old graph: no graph for this commit is built, and one the working tree has moved away from is rebuilt for the tree as it stands (--mode build; the default mode would reuse the commit's graph). Always --scip no-exec, which runs none of the repository's code, and no model. Returns a sentence for the page, empty when nothing was needed; a failed build is said, never thrown."
157
- export async function refreshGraph(root, env, onProgress) {
158
- const state = await graphState(root, env);
159
+ export async function refreshGraph(root, env, onProgress, known) {
160
+ const state = known ?? (await graphState(root, env));
159
161
  if (state !== 'not-built' && state !== 'diverged')
160
162
  return '';
161
163
  onProgress?.(state === 'not-built' ? 'Building the code graph for this commit first (no repository code runs; minutes on a large repository)…' : 'The code has moved since the code graph was built: rebuilding it first…');
@@ -185,8 +187,13 @@ export async function buildCodeGraph(root, env, opts = {}) {
185
187
  return note('locked', 'The code graph is on the Team plan: bravos account activate starts a 30-day trial, no card. The threat model tab is complete without it.');
186
188
  if (!graph.graphBin('codegraph-mcp', env))
187
189
  return note('missing', 'The code graph is not installed on this machine: run bravos setup --codegraph, then bravos graph build . and bravos dashboard again.');
188
- // The licence and the binary are settled, so a missing or behind graph is rebuilt before it is asked.
189
- const rebuilt = opts.refresh === false ? '' : await refreshGraph(root, env, opts.onProgress);
190
+ const BUSY = 'The code graph is busy: another session or a build is using it. Nothing needs rebuilding; run bravos dashboard again in a moment.';
191
+ // The licence and the binary are settled, so a missing or behind graph is rebuilt before it is asked. A busy one
192
+ // is neither: the server already waited for it, so the page says so now and nothing is built or asked again.
193
+ const state = opts.refresh === false ? null : await graphState(root, env);
194
+ if (state === 'busy')
195
+ return note('failed', BUSY);
196
+ const rebuilt = state ? await refreshGraph(root, env, opts.onProgress, state) : '';
190
197
  let answered;
191
198
  try {
192
199
  answered = await graph.askMany(root, env, Object.values(QUESTIONS).map((q) => ({ tool: q.tool, args: { ...q.args } })), 300000);
@@ -194,6 +201,10 @@ export async function buildCodeGraph(root, env, opts = {}) {
194
201
  catch (e) {
195
202
  return note('failed', `The code graph could not be asked (${e.message.slice(0, 200)}).`);
196
203
  }
204
+ // Asked and busy: the graph is there and another session or a build holds it. Said as that, never as "not built".
205
+ if (Object.values(answered.answers).some((a) => 'error' in a && (a.busy || graph.isGraphBusy(a.error)))) {
206
+ return note('failed', `${BUSY}${rebuilt}`);
207
+ }
197
208
  const errors = Object.values(answered.answers).map((a) => ('error' in a ? a.error : ''));
198
209
  if (errors.some((m) => NOT_BUILT.test(m))) {
199
210
  return note('not-built', `No code graph is built for this repository at this commit: run bravos graph build . (a few minutes, no tokens), then bravos dashboard again.${rebuilt}`);
@@ -244,7 +244,8 @@ export async function gatherEvidence(root, env, opts) {
244
244
  items,
245
245
  runs,
246
246
  sast: sastSummary,
247
- graph: graph && 'notBuilt' in graph ? 'not-built' : graph,
247
+ // A graph in use by another session says nothing this time: the report leaves its graph facts out, as when it is not installed.
248
+ graph: graph && 'notBuilt' in graph ? 'not-built' : graph && 'busy' in graph ? null : graph,
248
249
  gaps,
249
250
  };
250
251
  }
package/dist/setup.js CHANGED
@@ -3,7 +3,7 @@ import { checkProofTool, formatProofTool } from './proof-tools.js';
3
3
  import { spawnSync } from 'node:child_process';
4
4
  import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
5
5
  import { isAbsolute, join } from 'node:path';
6
- import { bundleEnvironment, hostTarget, install, missingPaths, staged, VERSIONS } from './artifacts.js';
6
+ import { bundleEnvironment, hostTarget, install, missingPaths, olderThan, staged, stagedVersion, VERSIONS } from './artifacts.js';
7
7
  import { graphBin, graphEnv } from './codegraph.js';
8
8
  import { whichBin } from './guardlink.js';
9
9
  import { findAnalyzer } from './graphbin.js';
@@ -11,6 +11,12 @@ import { licenceLib, requireFeature } from './licence.js';
11
11
  import { BravosError } from './types.js';
12
12
  import { PROOF_TOOL_PINS } from './versions.js';
13
13
  import { installProofTool, proofToolAction } from './install-proof-tool.js';
14
+ // @comment -- "The version of a staged bundle when it is older than the one this bravos pins, else null. An existing install keeps working on the old bundle until setup runs; this is how setup, and its --check, know there is a newer one to fetch. Read-only."
15
+ export function behindPin(env, kind) {
16
+ const dir = staged(env, kind);
17
+ const have = dir ? stagedVersion(dir) : null;
18
+ return have && olderThan(have, VERSIONS[kind]) ? have : null;
19
+ }
14
20
  // @comment -- "What is here and what setup would do, read-only: for each piece its path when present, the pinned version, whether the licence covers it, and the one action."
15
21
  export async function plan(env) {
16
22
  const L = await licenceLib();
@@ -18,9 +24,13 @@ export async function plan(env) {
18
24
  const sast = L.entitled(v, 'sast');
19
25
  const graph = L.entitled(v, 'codegraph');
20
26
  const t = hostTarget();
27
+ const behind = (kind) => {
28
+ const have = behindPin(env, kind);
29
+ return have ? { behind: have } : {};
30
+ };
21
31
  const items = [
22
- { id: 'analyzer', present: staged(env, 'analyzer') ?? findAnalyzer(env), wanted: VERSIONS.analyzer, licensed: sast, action: !t ? 'no build for this platform' : sast ? 'fetch, verify and stage the analyzer bundle' : 'on the Team plan: bravos account activate' },
23
- { id: 'codegraph', present: staged(env, 'codegraph') ?? graphBin('codegraph-build', env), wanted: VERSIONS.codegraph, licensed: graph, action: !t ? 'no build for this platform' : graph ? 'fetch, verify and stage codegraph-build and codegraph-mcp' : 'on the Team plan: bravos account activate' },
32
+ { id: 'analyzer', present: staged(env, 'analyzer') ?? findAnalyzer(env), wanted: VERSIONS.analyzer, licensed: sast, action: !t ? 'no build for this platform' : sast ? 'fetch, verify and stage the analyzer bundle' : 'on the Team plan: bravos account activate', ...behind('analyzer') },
33
+ { id: 'codegraph', present: staged(env, 'codegraph') ?? graphBin('codegraph-build', env), wanted: VERSIONS.codegraph, licensed: graph, action: !t ? 'no build for this platform' : graph ? 'fetch, verify and stage codegraph-build and codegraph-mcp' : 'on the Team plan: bravos account activate', ...behind('codegraph') },
24
34
  ...['guardlink', 'cxg'].map(id => ({
25
35
  id, present: whichBin(id, env), wanted: PROOF_TOOL_PINS[id].revision ?? PROOF_TOOL_PINS[id].version,
26
36
  licensed: null, action: proofToolAction(id), proofTool: checkProofTool(id, env),
@@ -33,7 +43,8 @@ export const formatPlan = (items) => items.map(i => {
33
43
  return '✘ ' + i.id.padEnd(10) + ' ' + i.present + ' (' + i.proofTool.status + ') — ' + i.action;
34
44
  }
35
45
  const status = i.present ? i.present : 'absent — ' + i.action;
36
- return (i.present ? '✔ ' : '✘ ') + i.id.padEnd(10) + ' ' + status + (i.present && i.licensed === false ? ' (licence does not cover it now)' : '');
46
+ const older = i.present && i.behind ? ` (${i.behind}; this bravos pins ${i.wanted}: bravos setup fetches it)` : '';
47
+ return (i.present ? '✔ ' : '✘ ') + i.id.padEnd(10) + ' ' + status + older + (i.present && i.licensed === false ? ' (licence does not cover it now)' : '');
37
48
  });
38
49
  // @comment -- "The setup itself. Default: the two licensed bundles for a licensed machine; --tools adds guardlink and cxg; --analyzer/--codegraph narrow it. Each licensed piece passes the gate before the first request. --dry-run prints the actions; -y is required for the package-manager installs because they run other people's installers."
39
50
  export async function runSetup(env, opts, io) {
@@ -52,15 +63,30 @@ export async function runSetup(env, opts, io) {
52
63
  const what = `bravos setup --${kind}`;
53
64
  await requireFeature(env, kind === 'analyzer' ? 'sast' : 'codegraph', what, { fetch: io.fetch });
54
65
  const have = staged(env, kind);
55
- if (have && !opts.yes) {
66
+ // A bundle older than the pin is fetched without -y: the pin is what this bravos was tested with, and
67
+ // "already staged" would leave an existing install on the old one for good.
68
+ const older = behindPin(env, kind);
69
+ if (have && !opts.yes && !older) {
56
70
  lines.push(`${kind}: already staged at ${have} (add -y to fetch ${VERSIONS[kind]} again)`);
57
71
  continue;
58
72
  }
59
73
  if (opts.dryRun) {
60
- lines.push(`dry-run: would fetch ${kind} ${VERSIONS[kind]} for ${hostTarget() ?? 'this platform'} through the account portal, verify its signature and stage it under $BRAVOS_HOME/${kind}/`);
74
+ lines.push(`dry-run: would fetch ${kind} ${VERSIONS[kind]} for ${hostTarget() ?? 'this platform'} through the account portal, verify its signature and stage it under $BRAVOS_HOME/${kind}/${older ? ` (replacing ${older})` : ''}`);
75
+ continue;
76
+ }
77
+ let r;
78
+ try {
79
+ r = await install(kind, { env, fetch: io.fetch, keys: io.keys, echo: io.echo });
80
+ }
81
+ catch (e) {
82
+ // The older bundle is complete and still the one in use, so a failed upgrade is said, not thrown.
83
+ if (!older || opts.yes)
84
+ throw e;
85
+ lines.push(`${kind}: ${older} stays staged at ${have}; ${VERSIONS[kind]} could not be fetched (${e.message.split('\n')[0].slice(0, 200)}). Run bravos setup again later.`);
61
86
  continue;
62
87
  }
63
- const r = await install(kind, { env, fetch: io.fetch, keys: io.keys, echo: io.echo });
88
+ if (older)
89
+ lines.push(`${kind}: ${older} was staged; this bravos pins ${VERSIONS[kind]}`);
64
90
  const missing = missingPaths(kind, r.dir);
65
91
  lines.push(`${kind}: ${r.version} staged at ${r.dir}${missing.length ? ` — missing ${missing.join(', ')}` : ''}`);
66
92
  lines.push(...selfTest(kind, r.dir, env));
package/dist/versions.js CHANGED
@@ -5,5 +5,5 @@ import { hooksDir } from './paths.js';
5
5
  /** The licensed analyzer bundle (bravos-cli plus gitleaks, osv-scanner, kics, zizmor and the rules), published by specter-v1's analyzer-release workflow. */
6
6
  export const ANALYZER_VERSION = '0.6.2';
7
7
  /** The code graph binaries (codegraph-build, codegraph-mcp), published by specter-v1's codegraph-release workflow. */
8
- export const CODEGRAPH_VERSION = '0.1.0';
8
+ export const CODEGRAPH_VERSION = '0.1.1';
9
9
  export const PROOF_TOOL_PINS = JSON.parse(readFileSync(join(hooksDir(), 'lib', 'proof-tool-pins.json'), 'utf8'));
@@ -268,6 +268,13 @@ function graphPanel(sn, inner) {
268
268
  body: [[s(`no graph for this commit (${sn.sha})`, C.amber)], [s('bravos keys the graph to the commit: rebuild after you commit', C.steel)], [s('→ bravos graph build . --scip no-exec', C.green)]],
269
269
  };
270
270
  }
271
+ if (g.state === 'busy') {
272
+ return {
273
+ title: 'CODE GRAPH',
274
+ right: 'busy',
275
+ body: [[s('in use by another session or a build', C.steel)], [s('nothing to do: watch asks again on the next refresh', C.steel)]],
276
+ };
277
+ }
271
278
  if (!d) {
272
279
  const body = g.entryPoints !== null ? [[s(`${g.entryPoints} entry points`)]] : [[s('askable: bravos graph <question>', C.steel)]];
273
280
  return { title: 'CODE GRAPH', right: 'asking…', body };
@@ -520,7 +527,7 @@ function tileItems(sn) {
520
527
  { label: 'COVERAGE', value: sn.coverage ? `${sn.coverage.percent}%` : '?', c: (sn.coverage?.percent ?? 0) >= 80 ? C.green : C.amber },
521
528
  { label: 'STALE', value: c ? String(c.stale) : '?', c: c?.stale ? C.amber : C.green },
522
529
  { label: 'SETUP', value: `${sn.setup.done}/${sn.setup.total}`, c: C.green },
523
- { label: 'GRAPH', value: worst ? `${Math.round(worst.ratio * 100)}%` : sn.graph.state === 'not-built' ? 'none' : sn.graph.state === 'unavailable' ? 'off' : '—', c: worst ? (worst.sufficient ? C.green : C.amber) : C.steel, sub: worst ? worst.language : undefined },
530
+ { label: 'GRAPH', value: worst ? `${Math.round(worst.ratio * 100)}%` : sn.graph.state === 'not-built' ? 'none' : sn.graph.state === 'unavailable' ? 'off' : sn.graph.state === 'busy' ? 'busy' : '—', c: worst ? (worst.sufficient ? C.green : C.amber) : C.steel, sub: worst ? worst.language : undefined },
524
531
  { label: 'SAST', value: sn.sast ? String(sn.sast.total) : sn.sastAvailable ? 'ready' : 'off', c: sn.sast?.unjoinedReachable ? C.red : C.steel },
525
532
  ];
526
533
  }
package/dist/watch.js CHANGED
@@ -57,7 +57,7 @@ const fileOf = (c) => String(c.location?.file ?? c.file ?? '?');
57
57
  const lineOf = (c) => num(c.location?.line ?? c.line);
58
58
  const keyOf = (c) => `${c.threat ?? '?'}|${c.asset ?? '?'}|${fileOf(c)}`;
59
59
  const sevRank = (s) => ['critical', 'high', 'medium', 'low'].indexOf(s) >>> 0;
60
- // @comment -- "One graph question in the shape the Python CLI's `bravos graph --json` printed ({result} or {error: codegraph_unavailable}), so summarizeGraph and graphAnswer read both the old transcript fixtures and the live MCP answers alike."
60
+ // @comment -- "One graph question in the shape the Python CLI's `bravos graph --json` printed ({result} or {error: codegraph_unavailable}), so summarizeGraph and graphAnswer read both the old transcript fixtures and the live MCP answers alike. A graph another process holds is {error: graph_busy} with an ask-again remedy, never codegraph_unavailable."
61
61
  export async function askGraph(root, env, question, args = [], timeoutMs = 60000) {
62
62
  if (!graph.graphBin('codegraph-mcp', env))
63
63
  return null;
@@ -66,6 +66,9 @@ export async function askGraph(root, env, question, args = [], timeoutMs = 60000
66
66
  }
67
67
  catch (e) {
68
68
  const m = e.message ?? '';
69
+ // Before the "not built" test, and never that: a busy graph must not send anyone to rebuild it.
70
+ if (graph.isGraphBusy(e))
71
+ return { error: 'graph_busy', message: m, remedy: graph.GRAPH_BUSY_REMEDY };
69
72
  if (/no graph|No CodeGraph|codegraph_unavailable|not built/i.test(m))
70
73
  return { error: 'codegraph_unavailable', message: m, remedy: '`bravos graph build .` indexes this repository' };
71
74
  return { error: 'graph_error', message: m };
@@ -99,19 +102,29 @@ export function summarizeGraph(a, askedAt) {
99
102
  acceptances: accept ? { total: Number(accept.total) || 0, expiring: arr(accept.acceptances).filter((x) => x.status === 'expiring').length } : null,
100
103
  };
101
104
  }
102
- // @comment -- "Asks the code graph five read-only questions at once through bravos graph --json (argv, no shell, 60 s cap each) and summarizes them; notBuilt when bravos reports no graph for this checkout, null when bravos is missing."
105
+ // @comment -- "Asks the code graph five read-only questions in one session (argv, no shell, 60 s cap each) and summarizes them; notBuilt when the graph reports none for this checkout, null when it is not installed or answers nothing. One session, not five at once: codegraph-mcp tells all but one of several sessions opened together that there is no graph, which made watch ask for a rebuild of a graph that was there."
103
106
  export async function graphDetail(root, env) {
104
107
  if (!graph.graphBin('codegraph-mcp', env))
105
108
  return null;
106
- const entry = await askGraph(root, env, 'entry-points');
107
- if (!entry)
109
+ const QUESTIONS = { entry: 'codegraph_entry_points', auth: 'codegraph_auth_boundary', tests: 'codegraph_untested_exposures', hot: 'codegraph_hotspots', accept: 'codegraph_acceptance_register' };
110
+ let got;
111
+ try {
112
+ got = await graph.askMany(root, env, Object.values(QUESTIONS).map((tool) => ({ tool })));
113
+ }
114
+ catch {
108
115
  return null;
109
- if (entry.error === 'codegraph_unavailable')
116
+ }
117
+ const entry = got.answers[QUESTIONS.entry];
118
+ // Busy first: the graph is there and in use, so the panel keeps what it knew and asks again on the next refresh.
119
+ if (Object.values(got.answers).some((a) => 'error' in a && (a.busy || graph.isGraphBusy(a.error))))
120
+ return { busy: true };
121
+ if (entry && 'error' in entry && /no graph|No CodeGraph|codegraph_unavailable|not built/i.test(entry.error))
110
122
  return { notBuilt: true };
111
- // The first answer decided whether a graph is there; the other four run together on the same store.
112
- const [auth, tests, hot, accept] = await Promise.all(['auth-boundary', 'untested-exposures', 'hotspots', 'acceptance-register'].map((q) => askGraph(root, env, q)));
113
- const ok = (x) => (x && !x.error ? x : null);
114
- const answers = { entry: ok(entry), auth: ok(auth), tests: ok(tests), hot: ok(hot), accept: ok(accept) };
123
+ const ok = (tool) => {
124
+ const a = got.answers[tool];
125
+ return a && 'result' in a ? { result: a.result } : null;
126
+ };
127
+ const answers = { entry: ok(QUESTIONS.entry), auth: ok(QUESTIONS.auth), tests: ok(QUESTIONS.tests), hot: ok(QUESTIONS.hot), accept: ok(QUESTIONS.accept) };
115
128
  if (!Object.values(answers).some(Boolean))
116
129
  return null;
117
130
  return summarizeGraph(answers, new Date().toISOString());
@@ -155,15 +168,23 @@ export async function snapshot(root, env, opts = {}) {
155
168
  const prev = opts.previous ?? null;
156
169
  const slow = opts.refreshSlow || !prev;
157
170
  const gl = (args) => run('guardlink', args, { cwd: root, env, timeoutMs: 30000 });
171
+ const collecting = briefing.collect(root, env, { nextCount: 5 });
172
+ // The graph is asked only after collect()'s own probe of it has finished, so the two never open it at the same
173
+ // moment, and never for a person whose plan does not include it.
174
+ const graphing = opts.refreshGraph ? collecting.then((c) => (c.codegraph === 'locked' ? null : graphDetail(root, env)), () => null) : null;
158
175
  const [collected, ledgerR, boundR, statusR, unannR, graphR] = await Promise.all([
159
- briefing.collect(root, env, { nextCount: 5 }),
176
+ collecting,
160
177
  gl(['hypothesis', 'list', '--json', '.']),
161
178
  slow ? gl(['hypothesis', 'boundaries', '--json', '.']) : null,
162
179
  slow ? gl(['status', '.']) : null,
163
180
  slow ? gl(['unannotated', '--json']) : null,
164
- opts.refreshGraph ? graphDetail(root, env) : null,
181
+ graphing,
165
182
  ]);
166
183
  const i = collected;
184
+ // The graph's own answers outrank the probe: a graph that just answered five questions is there, whatever a
185
+ // probe that collided with another session said. Set before the setup score reads it.
186
+ if (graphR && !('notBuilt' in graphR) && !('busy' in graphR) && (i.codegraph === 'not-built' || i.codegraph === 'unknown'))
187
+ i.codegraph = 'current';
167
188
  const g = i.guardlink === 'missing' ? null : (i.guardlink ?? {});
168
189
  const ci = g?.ci ?? null;
169
190
  const exposures = arr(ci?.exposures).map((e) => ({ key: keyOf(e), threat: String(e.threat ?? '?'), asset: String(e.asset ?? '?'), severity: String(e.severity ?? 'unset'), file: fileOf(e), line: lineOf(e) }));
@@ -213,6 +234,9 @@ export async function snapshot(root, env, opts = {}) {
213
234
  graph = { state: 'unavailable', entryPoints: null, byKind: null, detail: null };
214
235
  else if (graphR && 'notBuilt' in graphR)
215
236
  graph = { state: 'not-built', entryPoints: null, byKind: null, detail: null };
237
+ // In use by another session or a build: what the last refresh read still stands; with nothing read yet, say busy.
238
+ else if (graphR && 'busy' in graphR)
239
+ graph = prev?.graph?.detail ? prev.graph : { state: 'busy', entryPoints: null, byKind: null, detail: null };
216
240
  else
217
241
  graph = { state: String(i.codegraph ?? 'unavailable'), entryPoints: graphR?.entry?.total ?? null, byKind: graphR?.entry?.byKind ?? null, detail: graphR ?? null };
218
242
  }
package/docs/UPGRADING.md CHANGED
@@ -2,6 +2,22 @@
2
2
 
3
3
  After `npm install -g @bugb-technologies/bravos`, run **`bravos setup --tools -y`** once on each machine and **`bravos sync`** in each repository. The notes below say what else changes, newest first.
4
4
 
5
+ ## 1.5.3
6
+
7
+ 1.5.3 ships with code graph 0.1.1 (Team plan), which fixes the fault 1.5.2 worked around.
8
+
9
+ - **Run `bravos setup` once on each machine.** It now fetches the newer code graph when the one you have is older; before, it said "already staged" and you stayed on 0.1.0 unless you added `-y`. `bravos setup --check` says when a bundle is behind. If the download fails, the one you have keeps working and setup says so.
10
+ - **Several sessions on one repository all get an answer.** The graph used to tell all but one of them "No CodeGraph … Index the repository", and kept saying it to that session until it was restarted. It now waits its turn (up to 20 seconds).
11
+ - **A graph that is in use says "busy", not "no graph".** This happens while a build runs. `bravos graph` prints `graph_busy` with "ask again in a moment", `bravos watch` shows `GRAPH busy` and keeps what it last read, and `bravos dashboard` says the graph is busy and builds nothing. None of these is a reason to rebuild.
12
+ - **For scripts:** `bravos graph … --json` can now answer `{"error":"graph_busy"}` with exit 1. Exit 2 still means the graph is not built.
13
+ - Graphs built with 0.1.0 are read as they are; nothing needs rebuilding. Run `bravos sync` in each repository to get the updated code graph skill.
14
+
15
+ ## 1.5.2
16
+
17
+ - **`bravos watch` no longer says "no graph" for a graph that is there.** The code graph answers "no graph" to a question that arrives at the same moment as another one; Bravos now asks again before believing it, and `bravos watch` asks its questions in one go instead of several at once. If you rebuilt a graph because watch told you to, it was not needed.
18
+ - **One banner and one briefing per session.** Where a project has its own Bravos install and the Bravos plugin is also enabled, the plugin's hook now stays quiet. This reaches plugin users when the plugin is next published; until then, disable one of the two.
19
+ - Run `bravos sync` in each repository to get the updated hook.
20
+
5
21
  ## 1.5.1
6
22
 
7
23
  - **`bravos dashboard` makes the code graph current first** (Team plan). With no graph for this commit it builds one; when the code has moved since the graph was built, it rebuilds it. It says so as it starts and runs none of the repository's code. A first build on a large repository takes minutes; `--no-graph-build` draws from the graph as it is.
@@ -519,6 +519,18 @@ const TEAM_ADDS = 'autopilot, PR gate, SAST, code graph';
519
519
 
520
520
  export const fit = (s, w) => (s.length <= w ? s : s.slice(0, Math.max(0, w - 1)) + '…');
521
521
 
522
+ // @comment -- "True when the project registers its own Bravos session-start hook for this harness (Claude Code: .claude/settings.json, Codex: .codex/hooks.json), so another copy of the hook, the plugin's, can stay quiet and the banner and briefing arrive once. A file that is missing or unreadable reads as not registered, and so does any other harness. Read-only."
523
+ export function sessionHookRegistered(root, harness) {
524
+ const rel = harness === 'claude' ? '.claude/settings.json' : harness === 'codex' ? '.codex/hooks.json' : null;
525
+ if (!rel) return false;
526
+ try {
527
+ const groups = JSON.parse(readFileSync(join(root, rel), 'utf8'))?.hooks?.SessionStart;
528
+ return Array.isArray(groups) && groups.some((g) => arr(g?.hooks).some((h) => typeof h?.command === 'string' && h.command.includes('.bravos/hooks/session-start.mjs')));
529
+ } catch {
530
+ return false;
531
+ }
532
+ }
533
+
522
534
  // @comment -- "True when a harness settings file in the repo registers bravos's pre-PR gate; read-only, and unreadable files read as off."
523
535
  export function prePrRegistered(root) {
524
536
  for (const rel of ['.claude/settings.json', '.codex/hooks.json']) {
@@ -1,8 +1,8 @@
1
1
  // @comment -- "SessionStart hook entry (--global: the user-level copy, silent where the repo has its own bravos hook or no .guardlink/; --briefing prints only the briefing text, for a skill that runs it by hand): reads the hook payload from stdin (bounded wait, bad input ignored; source, and Antigravity's workspacePaths), awaits collect() (read-only guardlink, git and gh facts under a shared 20 s deadline) and, where autopilot is registered, the session-start snapshot of the working tree (.bravos/watch/turn-base), and prints one JSON envelope: the briefing as additionalContext for the model, plus on a fresh start a banner as systemMessage for the human (brand-coloured; a three-line summary for Codex). With --harness agy it prints Antigravity's injectSteps instead. Always exits 0 so a session never fails to start."
2
- import { existsSync } from 'node:fs';
2
+ import { existsSync, realpathSync } from 'node:fs';
3
3
  import { dirname, join } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
- import { autopilotRegistered, buildBanner, buildBriefing, buildSummary, collect, readVersion } from './lib/briefing.mjs';
5
+ import { autopilotRegistered, buildBanner, buildBriefing, buildSummary, collect, readVersion, sessionHookRegistered } from './lib/briefing.mjs';
6
6
  import { resolveTheme } from './lib/palette.mjs';
7
7
  import { takeSnapshot } from './lib/snapshot.mjs';
8
8
 
@@ -32,6 +32,15 @@ function harnessArg(argv, env) {
32
32
  return env.CLAUDE_PROJECT_DIR ? 'claude' : 'other';
33
33
  }
34
34
 
35
+ // @comment -- "Whether the script running is the project's own .bravos/hooks/session-start.mjs (compared by real path, so a symlinked checkout still matches); false for the plugin's copy, the user-level copy and this repository's source."
36
+ function ownCopy(root) {
37
+ try {
38
+ return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(join(root, '.bravos', 'hooks', 'session-start.mjs'));
39
+ } catch {
40
+ return false;
41
+ }
42
+ }
43
+
35
44
  async function main() {
36
45
  const env = process.env;
37
46
  const harness = harnessArg(process.argv, env);
@@ -59,6 +68,9 @@ async function main() {
59
68
  if (process.argv.includes('--global') && (existsSync(join(root, '.bravos', 'hooks', 'session-start.mjs')) || !existsSync(join(root, '.guardlink')))) {
60
69
  process.exit(0);
61
70
  }
71
+ // A copy of this hook that is not the project's own (the Claude Code or Codex plugin's) stays quiet where the
72
+ // project registers its own: that one speaks, so the banner and the briefing never arrive twice.
73
+ if (!ownCopy(root) && existsSync(join(root, '.bravos', 'hooks', 'session-start.mjs')) && sessionHookRegistered(root, harness)) process.exit(0);
62
74
  // Where autopilot is on, record what the working tree held at the start, beside the briefing, so its
63
75
  // end-of-turn check judges only this session's changes (no autopilot, nothing written).
64
76
  const snap = autopilotRegistered(root) ? takeSnapshot(root, payload.session_id, { env }) : null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bugb-technologies/bravos",
3
- "version": "1.5.1",
3
+ "version": "1.5.3",
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",
@@ -16,7 +16,7 @@ description: "Ask the repo's code graph (codegraph-mcp) one bounded question —
16
16
  **Plan check first.** The code graph is on the Team plan. Run `bravos licence --json` once per session (the briefing's `Plan:` line says the same); if `licensed` is false, tell the person in two sentences what this skill would do here and that it needs a Team licence — `bravos account activate` starts a 30-day trial with no card, or https://account.bugb.io/pricing — then stop, and do nothing else from this skill. A licence in grace still counts.
17
17
 
18
18
  1. Ask the graph one bounded question per call; a graph answer replaces reading or grepping the tree. There are two ways in, with the same answers: the MCP tools (`codegraph_attack_surface` …) when the `codegraph` server is connected, or `bravos graph <question> --json` in the shell, where the question is the tool name without `codegraph_` and with hyphens (`codegraph_attack_surface` → `bravos graph attack-surface --json`, `codegraph_callers` → `bravos graph callers '<file>::<symbol>' --json`; `bravos graph --json` lists every question and its arguments). The shell route needs no MCP reconnect and works in every harness. The briefing's `Code graph:` line says which route is there. If neither is (no codegraph-mcp), set it up yourself: `bravos setup --check` reports what is missing without changing anything; show the person `bravos setup --dry-run --codegraph` and with their go-ahead run `bravos setup --codegraph` (it fetches the signed bundle through the account portal and verifies it before anything lands). If an install fails, quote its error and give the exact command for their own terminal; until then say "code graph unavailable; the other skills read the code instead" and answer by reading. Read the effort: the user's words ("at high"), else a `bravos effort: <level>` line in `AGENTS.md` / `CLAUDE.md`, else medium. It sets a starting budget, not a limit; go beyond it when the work needs it and say why in one line. Starting budget — low: the one question asked; medium: whatever questions the task needs; high: start from `codegraph_attack_surface`; max: the full attack surface plus `codegraph_impact` on every changed symbol.
19
- 2. Build or refresh the graph when an answer says there is none for this repository, or its `graph_currency` is `diverged`: `bravos graph build . --scip no-exec` indexes without running the repository's build scripts (`--scip auto` and `--isolate` run them; use those only on a repo the user trusts and only when they say so). A build that reports `semantic <language>: off` lacks that language's type checker; say that calls through interfaces may not connect and that `bravos setup --indexers` (with their go-ahead) adds it. For the MCP route, `bravos sync` registers the server from the bravos install; the person reconnects MCP (`/mcp` in Claude Code) to load it. In a bravos workspace, build one graph over the app folder (`bravos graph build <app folder> --scip no-exec`, the folder the briefing's `Workspace:` line names) and ask cross-service questions there: only a graph that holds both services links one service's HTTP, gRPC, GraphQL or OpenAPI client call to the other's handler (`callees` shows `via_framework`). A graph built inside one member stops at its own repository. A graph belongs to the commit it was built at: after a commit it answers nothing until it is rebuilt, so rebuild before the next graph question and carry on with other work while it builds. `bravos dashboard` rebuilds a missing or behind graph itself and draws it as the Code graph tab (the map, owners and history, coupling, the attack surface, entry points), which is the view to offer a person who wants to see the graph.
19
+ 2. Build or refresh the graph when an answer says there is none for this repository, or its `graph_currency` is `diverged`: `bravos graph build . --scip no-exec` indexes without running the repository's build scripts (`--scip auto` and `--isolate` run them; use those only on a repo the user trusts and only when they say so). A build that reports `semantic <language>: off` lacks that language's type checker; say that calls through interfaces may not connect and that `bravos setup --indexers` (with their go-ahead) adds it. For the MCP route, `bravos sync` registers the server from the bravos install; the person reconnects MCP (`/mcp` in Claude Code) to load it. In a bravos workspace, build one graph over the app folder (`bravos graph build <app folder> --scip no-exec`, the folder the briefing's `Workspace:` line names) and ask cross-service questions there: only a graph that holds both services links one service's HTTP, gRPC, GraphQL or OpenAPI client call to the other's handler (`callees` shows `via_framework`). A graph built inside one member stops at its own repository. An answer of `graph_busy` ("the code graph … is busy") means the graph is there and another session or a build is using it: ask again in a moment and never rebuild for it. An older graph server (code graph 0.1.0) says "No CodeGraph for project" in that case instead, and keeps saying it for that session: when a graph answered moments ago, ask once more before rebuilding, and offer `bravos setup` (it fetches the newer server). A graph belongs to the commit it was built at: after a commit it answers nothing until it is rebuilt, so rebuild before the next graph question and carry on with other work while it builds. `bravos dashboard` rebuilds a missing or behind graph itself and draws it as the Code graph tab (the map, owners and history, coupling, the attack surface, entry points), which is the view to offer a person who wants to see the graph.
20
20
  3. Pick the one tool that answers the question:
21
21
  find a symbol → `codegraph_search`
22
22
  routes → `codegraph_routes`