@bugb-technologies/bravos 1.5.1 → 1.5.2

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/codegraph.js CHANGED
@@ -174,46 +174,85 @@ export function open(root, env) {
174
174
  throw new GraphUnavailable('codegraph-mcp is not installed: bravos setup --codegraph fetches it (on the Team plan)');
175
175
  return new GraphSession(bin, root, env);
176
176
  }
177
+ // What codegraph-mcp answers when it finds no graph for the project. It gives the same answer, wrongly, to a
178
+ // session that opens the graph in the same few hundred milliseconds as another one (measured: two sessions
179
+ // started together, exactly one answers; a session started while another is mid-question answers fine).
180
+ const NO_GRAPH = /No CodeGraph for project/i;
181
+ // Two more tries, each after a short pause of uneven length so sessions that collided do not collide again, step
182
+ // out of another session's opening moment and keep a true "no graph" answer fast (about a second more; the
183
+ // session-start probe reads an answer slower than three seconds as a graph that is loading).
184
+ export const GRAPH_RETRIES = 2;
185
+ export const GRAPH_RETRY_MS = 250;
186
+ const pause = (ms) => new Promise((r) => setTimeout(r, ms));
187
+ // @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."
188
+ export async function withGraphRetry(session, noGraph, retries = GRAPH_RETRIES, waitMs = GRAPH_RETRY_MS) {
189
+ for (let attempt = 0;; attempt++) {
190
+ let outcome;
191
+ try {
192
+ outcome = { value: await session() };
193
+ }
194
+ catch (e) {
195
+ outcome = { error: e };
196
+ }
197
+ if (attempt < retries && noGraph(outcome)) {
198
+ await pause(waitMs + Math.floor(Math.random() * waitMs * 1.4));
199
+ continue;
200
+ }
201
+ if (outcome.error)
202
+ throw outcome.error;
203
+ return outcome.value;
204
+ }
205
+ }
177
206
  // @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
207
  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
- }
208
+ const once = async () => {
209
+ const s = open(root, env);
210
+ try {
211
+ await s.initialize(Math.min(timeoutMs, 30000));
212
+ const tools = await s.tools(Math.min(timeoutMs, 30000));
213
+ const name = question.startsWith('codegraph_') ? question : `codegraph_${question.replace(/-/g, '_')}`;
214
+ const tool = tools.find((t) => t.name === name);
215
+ if (!tool)
216
+ throw new BravosError(`the graph has no question ${JSON.stringify(question)}; it answers: ${tools.map((t) => t.name.replace(/^codegraph_/, '').replace(/_/g, '-')).join(', ')}`);
217
+ return await s.call(name, bindArguments(tool, argv), timeoutMs);
218
+ }
219
+ finally {
220
+ s.close();
221
+ }
222
+ };
223
+ return withGraphRetry(once, (o) => !!o.error && NO_GRAPH.test(o.error.message ?? ''));
192
224
  }
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)."
225
+ // @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. 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
226
  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 };
227
+ const once = async () => {
228
+ const s = open(root, env);
229
+ try {
230
+ await s.initialize(Math.min(timeoutMs, 30000));
231
+ const tools = (await s.tools(Math.min(timeoutMs, 30000))).map((t) => t.name);
232
+ const answers = {};
233
+ for (const c of calls) {
234
+ if (!tools.includes(c.tool)) {
235
+ answers[c.tool] = { error: 'this code graph does not answer that question' };
236
+ continue;
237
+ }
238
+ try {
239
+ answers[c.tool] = { result: await s.call(c.tool, c.args ?? {}, timeoutMs) };
240
+ }
241
+ catch (e) {
242
+ answers[c.tool] = { error: e.message };
243
+ }
210
244
  }
245
+ return { tools, answers };
211
246
  }
212
- return { tools, answers };
213
- }
214
- finally {
215
- s.close();
216
- }
247
+ finally {
248
+ s.close();
249
+ }
250
+ };
251
+ // The graph is opened by the session's first question, so "no graph" on the first one asked is the answer to retry.
252
+ return withGraphRetry(once, (o) => {
253
+ 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'));
254
+ return !!first && 'error' in first && NO_GRAPH.test(first.error);
255
+ });
217
256
  }
218
257
  export async function listTools(root, env, timeoutMs = 30000) {
219
258
  const s = open(root, env);
package/dist/watch.js CHANGED
@@ -99,19 +99,26 @@ export function summarizeGraph(a, askedAt) {
99
99
  acceptances: accept ? { total: Number(accept.total) || 0, expiring: arr(accept.acceptances).filter((x) => x.status === 'expiring').length } : null,
100
100
  };
101
101
  }
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."
102
+ // @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
103
  export async function graphDetail(root, env) {
104
104
  if (!graph.graphBin('codegraph-mcp', env))
105
105
  return null;
106
- const entry = await askGraph(root, env, 'entry-points');
107
- if (!entry)
106
+ const QUESTIONS = { entry: 'codegraph_entry_points', auth: 'codegraph_auth_boundary', tests: 'codegraph_untested_exposures', hot: 'codegraph_hotspots', accept: 'codegraph_acceptance_register' };
107
+ let got;
108
+ try {
109
+ got = await graph.askMany(root, env, Object.values(QUESTIONS).map((tool) => ({ tool })));
110
+ }
111
+ catch {
108
112
  return null;
109
- if (entry.error === 'codegraph_unavailable')
113
+ }
114
+ const entry = got.answers[QUESTIONS.entry];
115
+ if (entry && 'error' in entry && /no graph|No CodeGraph|codegraph_unavailable|not built/i.test(entry.error))
110
116
  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) };
117
+ const ok = (tool) => {
118
+ const a = got.answers[tool];
119
+ return a && 'result' in a ? { result: a.result } : null;
120
+ };
121
+ const answers = { entry: ok(QUESTIONS.entry), auth: ok(QUESTIONS.auth), tests: ok(QUESTIONS.tests), hot: ok(QUESTIONS.hot), accept: ok(QUESTIONS.accept) };
115
122
  if (!Object.values(answers).some(Boolean))
116
123
  return null;
117
124
  return summarizeGraph(answers, new Date().toISOString());
@@ -155,15 +162,23 @@ export async function snapshot(root, env, opts = {}) {
155
162
  const prev = opts.previous ?? null;
156
163
  const slow = opts.refreshSlow || !prev;
157
164
  const gl = (args) => run('guardlink', args, { cwd: root, env, timeoutMs: 30000 });
165
+ const collecting = briefing.collect(root, env, { nextCount: 5 });
166
+ // The graph is asked only after collect()'s own probe of it has finished, so the two never open it at the same
167
+ // moment, and never for a person whose plan does not include it.
168
+ const graphing = opts.refreshGraph ? collecting.then((c) => (c.codegraph === 'locked' ? null : graphDetail(root, env)), () => null) : null;
158
169
  const [collected, ledgerR, boundR, statusR, unannR, graphR] = await Promise.all([
159
- briefing.collect(root, env, { nextCount: 5 }),
170
+ collecting,
160
171
  gl(['hypothesis', 'list', '--json', '.']),
161
172
  slow ? gl(['hypothesis', 'boundaries', '--json', '.']) : null,
162
173
  slow ? gl(['status', '.']) : null,
163
174
  slow ? gl(['unannotated', '--json']) : null,
164
- opts.refreshGraph ? graphDetail(root, env) : null,
175
+ graphing,
165
176
  ]);
166
177
  const i = collected;
178
+ // The graph's own answers outrank the probe: a graph that just answered five questions is there, whatever a
179
+ // probe that collided with another session said. Set before the setup score reads it.
180
+ if (graphR && !('notBuilt' in graphR) && (i.codegraph === 'not-built' || i.codegraph === 'unknown'))
181
+ i.codegraph = 'current';
167
182
  const g = i.guardlink === 'missing' ? null : (i.guardlink ?? {});
168
183
  const ci = g?.ci ?? null;
169
184
  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) }));
package/docs/UPGRADING.md CHANGED
@@ -2,6 +2,12 @@
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.2
6
+
7
+ - **`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.
8
+ - **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.
9
+ - Run `bravos sync` in each repository to get the updated hook.
10
+
5
11
  ## 1.5.1
6
12
 
7
13
  - **`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.2",
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. The graph can also answer "No CodeGraph for project" to a question that arrives at the same moment as another one (a second terminal, `bravos watch`, `bravos dashboard`): when a graph answered moments ago, ask once more before rebuilding. 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`