@bugb-technologies/bravos 1.4.1 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +53 -219
  2. package/dist/account.js +2 -11
  3. package/dist/cli.js +77 -29
  4. package/dist/codegraph.js +25 -0
  5. package/dist/dashboard.js +242 -0
  6. package/dist/guardlink.js +4 -3
  7. package/dist/guide.js +2 -1
  8. package/dist/help.js +8 -0
  9. package/dist/hooks.js +27 -5
  10. package/dist/install-proof-tool.js +5 -7
  11. package/dist/install.js +2 -2
  12. package/dist/licence.js +11 -4
  13. package/dist/omp.js +2 -1
  14. package/dist/open.js +22 -0
  15. package/dist/opencode.js +2 -1
  16. package/dist/setup.js +11 -2
  17. package/dist/skills.js +8 -0
  18. package/dist/start/index.js +10 -2
  19. package/dist/watch.js +8 -24
  20. package/docs/GUIDE.md +7 -1
  21. package/docs/UPGRADING.md +50 -0
  22. package/hooks/lib/briefing.mjs +82 -27
  23. package/hooks/lib/licence.mjs +13 -0
  24. package/hooks/lib/nightly-tools.sh +8 -2
  25. package/hooks/lib/replay.mjs +18 -7
  26. package/hooks/lib/setup.mjs +1 -1
  27. package/package.json +3 -2
  28. package/skills/bravos/SKILL.md +3 -2
  29. package/skills/bravos-annotate/SKILL.md +1 -1
  30. package/skills/bravos-annotate/scripts/lib/pick.mjs +1 -1
  31. package/skills/bravos-annotate/scripts/slice.mjs +1 -1
  32. package/skills/bravos-context/SKILL.md +5 -4
  33. package/skills/bravos-env/SKILL.md +2 -2
  34. package/skills/bravos-env/scope.example.yaml +2 -2
  35. package/skills/bravos-prove/SKILL.md +5 -5
  36. package/skills/bravos-templatize/SKILL.md +3 -3
  37. package/skills/bravos-templatize/operator-guidance.md +4 -4
  38. package/templates/dashboard/codegraph-pages.css +279 -0
  39. package/templates/dashboard/codegraph-pages.js +6230 -0
  40. package/templates/dashboard/codegraph-pages.json +11 -0
  41. package/templates/dashboard/dashboard.html +252 -0
package/dist/codegraph.js CHANGED
@@ -190,6 +190,31 @@ export async function ask(root, env, question, argv, timeoutMs = 60000) {
190
190
  s.close();
191
191
  }
192
192
  }
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)."
194
+ 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 };
210
+ }
211
+ }
212
+ return { tools, answers };
213
+ }
214
+ finally {
215
+ s.close();
216
+ }
217
+ }
193
218
  export async function listTools(root, env, timeoutMs = 30000) {
194
219
  const s = open(root, env);
195
220
  try {
@@ -0,0 +1,242 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { basename, dirname, join, resolve } from 'node:path';
5
+ import * as graph from './codegraph.js';
6
+ import { featureState, licenceLib } from './licence.js';
7
+ import { templatesDir, version } from './paths.js';
8
+ import { BravosError } from './types.js';
9
+ export const DASHBOARD_DIR = '.bravos/dashboard';
10
+ export const DASHBOARD_PATH = `${DASHBOARD_DIR}/index.html`;
11
+ const git = (root, env, args) => {
12
+ const r = spawnSync('git', args, { cwd: root, env, encoding: 'utf8', timeout: 10000, stdio: ['ignore', 'pipe', 'ignore'] });
13
+ return r.error || r.status !== 0 ? null : r.stdout.trim();
14
+ };
15
+ // @comment -- "The repository's name for the page header: the last part of the origin URL when there is one (a worktree's folder is not the project's name), else the folder name."
16
+ export function repoName(root, env) {
17
+ const url = git(root, env, ['config', '--get', 'remote.origin.url']);
18
+ const fromUrl = url ? url.replace(/\/+$/, '').replace(/\.git$/, '').split(/[/:]/).pop() : '';
19
+ return fromUrl || basename(resolve(root)) || 'repository';
20
+ }
21
+ // @comment -- "The ref the dashboard compares against: the origin's default branch when git knows it, else origin/main, and only when that ref resolves to a commit; null when there is nothing to compare with (a new repository, no remote). Read-only git, argv only."
22
+ export function baseRef(root, env) {
23
+ const head = git(root, env, ['symbolic-ref', '-q', '--short', 'refs/remotes/origin/HEAD']);
24
+ for (const ref of [head, 'origin/main']) {
25
+ if (ref && git(root, env, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]) !== null)
26
+ return ref;
27
+ }
28
+ return null;
29
+ }
30
+ // @comment -- "Builds GuardLink's own dashboard for the repository and returns its HTML. GuardLink writes nothing and exits non-zero when --since cannot be read or blame has no history, so the richest form is tried first (blame and what changed since the base), then without the comparison, then plain; the first that writes a page wins and the result says which extras it carries. A missing guardlink, or no page at all, is a note for the page and never an exception. The page is written to a private temp folder and removed; argv only, no shell."
31
+ export function buildThreatModel(root, env, opts) {
32
+ const dir = mkdtempSync(join(tmpdir(), 'bravos-dashboard-'));
33
+ const file = join(dir, 'threat-model.html');
34
+ const attempts = [];
35
+ if (opts.blame && opts.base)
36
+ attempts.push({ blame: true, since: opts.base });
37
+ if (opts.base)
38
+ attempts.push({ blame: false, since: opts.base });
39
+ if (opts.blame)
40
+ attempts.push({ blame: true, since: null });
41
+ attempts.push({ blame: false, since: null });
42
+ let last = '';
43
+ try {
44
+ for (const a of attempts) {
45
+ const args = ['dashboard', '.', '-o', file, ...(a.blame ? ['--blame'] : []), ...(a.since ? ['--since', a.since] : [])];
46
+ const r = spawnSync('guardlink', args, { cwd: root, env, encoding: 'utf8', timeout: 300000, maxBuffer: 64 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
47
+ if (r.error) {
48
+ const missing = r.error.code === 'ENOENT';
49
+ return { state: missing ? 'missing' : 'failed', html: null, blame: false, since: null, note: missing ? 'GuardLink is not installed on this machine: run bravos setup --tools -y, then bravos dashboard again.' : `GuardLink could not be run (${r.error.message}).` };
50
+ }
51
+ if (r.status === 0 && existsSync(file)) {
52
+ const extras = [a.blame ? 'who introduced and fixed each exposure' : null, a.since ? `what changed since ${a.since}` : null].filter(Boolean);
53
+ return { state: 'present', html: readFileSync(file, 'utf8'), blame: a.blame, since: a.since, note: `GuardLink's threat model${extras.length ? `, with ${extras.join(' and ')}` : ''}.` };
54
+ }
55
+ last = `${r.stderr ?? ''}\n${r.stdout ?? ''}`.split('\n').map((l) => l.trim()).filter(Boolean)[0] ?? `guardlink exited ${r.status}`;
56
+ }
57
+ return { state: 'failed', html: null, blame: false, since: null, note: `GuardLink wrote no dashboard (${last.slice(0, 200)}). Run guardlink validate . to see what it needs.` };
58
+ }
59
+ finally {
60
+ rmSync(dir, { recursive: true, force: true });
61
+ }
62
+ }
63
+ const obj = (v) => (v && typeof v === 'object' && !Array.isArray(v) ? v : {});
64
+ const text = (v) => (typeof v === 'string' ? v : '');
65
+ // The questions the seven pages are drawn from, with the arguments the Bravos VS Code extension asks them with
66
+ // (siete: clients/vscode/src/webview/pagesPanel.ts): the code map with its caps lifted so nothing is trimmed,
67
+ // hotspots by heat, and the full entry-point and access lists.
68
+ const QUESTIONS = {
69
+ codemap: { tool: 'codegraph_codemap', args: { max_children_per_parent: 100000, max_nodes: 100000 } },
70
+ threat: { tool: 'codegraph_threat_model', args: {} },
71
+ hotspots: { tool: 'codegraph_hotspots', args: { rank_by: 'heat', limit: 500 } },
72
+ mix: { tool: 'codegraph_commit_mix', args: {} },
73
+ coChange: { tool: 'codegraph_co_change', args: {} },
74
+ surface: { tool: 'codegraph_attack_surface', args: {} },
75
+ entries: { tool: 'codegraph_entry_points', args: { limit: 5000 } },
76
+ access: { tool: 'codegraph_auth_boundary', args: { limit: 5000 } },
77
+ };
78
+ /** The command line a reader can run to ask the same question; each page prints the ones it was drawn from. */
79
+ const commandLine = (q) => {
80
+ const { tool, args } = QUESTIONS[q];
81
+ const flags = Object.entries(args).map(([k, v]) => ` --${k.replace(/_/g, '-')} ${v}`).join('');
82
+ return `bravos graph ${tool.replace(/^codegraph_/, '').replace(/_/g, '-')}${flags} --json`;
83
+ };
84
+ // @comment -- "Replaces what a shared page should not carry in the graph's answers. Always: the repository's absolute path on this machine becomes its name, since the path names the person's home folder. With names off (--no-blame): every author and owner name the answers carry (the code map's owners, the hotspots' and commit mix's authors) becomes a stable stand-in, 'person 1', 'person 2', so the pages still draw who-carries-what without saying who. Pure; returns a copy."
85
+ export function scrubAnswers(value, opts) {
86
+ const people = new Map();
87
+ const person = (name) => {
88
+ if (!people.has(name))
89
+ people.set(name, `person ${people.size + 1}`);
90
+ return people.get(name);
91
+ };
92
+ const NAME_KEYS = new Set(['author', 'top_author', 'top_owner']);
93
+ const NAME_LISTS = new Set(['owners', 'authors', 'top_contributions']);
94
+ const walk = (v, key, parent) => {
95
+ if (typeof v === 'string') {
96
+ if (!opts.names && v && (NAME_KEYS.has(key) || (key === 'name' && NAME_LISTS.has(parent))))
97
+ return person(v);
98
+ if (v === opts.root)
99
+ return opts.repo;
100
+ return v.startsWith(`${opts.root}/`) ? `${opts.repo}${v.slice(opts.root.length)}` : v;
101
+ }
102
+ if (Array.isArray(v))
103
+ return v.map((x) => walk(x, key, parent));
104
+ if (v && typeof v === 'object')
105
+ return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, walk(x, k, Array.isArray(x) ? k : key)]));
106
+ return v;
107
+ };
108
+ return walk(value, '', '');
109
+ }
110
+ // @comment -- "Pure: turns the graph's answers into the message each Code graph page is drawn from, with the rules the VS Code extension's host applies (siete: pagesPanel.ts `load`). A page whose main question was not answered gets a 'refused' message carrying the graph's own words, never an empty drawing; a secondary answer that is missing is passed through as not-ok so the page says so itself. Every message lists the command lines it came from. No stored code-analysis issues are supplied, so the Map's Findings lens and the Attack surface's pinned column say they have none."
111
+ export function codeGraphStore(answers) {
112
+ const got = (q) => {
113
+ const a = answers[QUESTIONS[q].tool];
114
+ if (!a)
115
+ return { ok: false, message: 'the code graph was not asked' };
116
+ return 'error' in a ? { ok: false, message: a.error } : { ok: true, value: a.result };
117
+ };
118
+ const refused = (page, what, a) => ({ type: 'refused', page, what, message: a.ok ? '' : a.message, remedy: 'bravos graph build . rebuilds the graph; then run bravos dashboard again' });
119
+ const cm = got('codemap');
120
+ const doc = cm.ok ? obj(cm.value).codemap : undefined;
121
+ const codemap = cm.ok && doc ? { ok: true, value: doc } : cm.ok ? { ok: false, message: 'the code graph answered without a map' } : cm;
122
+ const asked = (...qs) => qs.map(commandLine);
123
+ const [threat, hot, mix, co, surface, entries, access] = [got('threat'), got('hotspots'), got('mix'), got('coChange'), got('surface'), got('entries'), got('access')];
124
+ return {
125
+ map: codemap.ok ? { type: 'map', codemap: codemap.value, asked: asked('codemap'), findings: null } : refused('map', 'The map could not be built', codemap),
126
+ trust: codemap.ok ? { type: 'trust', codemap: codemap.value, threatModel: threat, asked: asked('codemap', 'threat') } : refused('trust', 'The graph could not describe itself', codemap),
127
+ owners: !hot.ok
128
+ ? refused('owners', 'Churn and ownership are not available', hot)
129
+ : !codemap.ok
130
+ ? refused('owners', 'Churn and ownership are not available', codemap)
131
+ : { type: 'owners', hotspots: hot.value, codemap: codemap.value, commitMix: mix, asked: asked('hotspots', 'codemap', 'mix') },
132
+ coupling: co.ok ? { type: 'coupling', coChange: co.value, codemap, asked: asked('coChange', 'codemap') } : refused('coupling', 'Co-change coupling is not available', co),
133
+ surface: surface.ok ? { type: 'surface', attackSurface: surface.value, issues: null, asked: asked('surface') } : refused('surface', 'The attack surface is not available', surface),
134
+ entries: entries.ok ? { type: 'entries', entryPoints: entries.value, access, asked: asked('entries', 'access') } : refused('entries', 'Entry points are not available', entries),
135
+ links: { type: 'links', entryPoints: entries, asked: asked('entries') },
136
+ };
137
+ }
138
+ // @comment -- "The Code graph part of the dashboard. The code graph is on the Team plan, so the licence is checked before anything is asked (a refusal is a note on the page, not an error, and the graph binary is never started without a licence). Then one session asks the eight questions the pages are drawn from; they read git history and the whole map, so each may take minutes on a large repository. A graph that is not installed, not built for this commit, or that answers nothing is a short note naming the command that fixes it. Read-only: the graph is asked, never built here."
139
+ export async function buildCodeGraph(root, env, opts = {}) {
140
+ const note = (state, sentence) => ({ state, note: sentence, store: null });
141
+ let entitled = false;
142
+ try {
143
+ entitled = (await featureState(env, 'codegraph', 'bravos dashboard', { fetch: opts.fetch })).entitled;
144
+ }
145
+ catch {
146
+ /* an unreadable licence reads as none */
147
+ }
148
+ if (!entitled)
149
+ 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.');
150
+ if (!graph.graphBin('codegraph-mcp', env))
151
+ return note('missing', 'The code graph is not installed on this machine: run bravos setup --codegraph, then bravos graph build . and bravos dashboard again.');
152
+ let answered;
153
+ try {
154
+ answered = await graph.askMany(root, env, Object.values(QUESTIONS).map((q) => ({ tool: q.tool, args: { ...q.args } })), 300000);
155
+ }
156
+ catch (e) {
157
+ return note('failed', `The code graph could not be asked (${e.message.slice(0, 200)}).`);
158
+ }
159
+ const errors = Object.values(answered.answers).map((a) => ('error' in a ? a.error : ''));
160
+ if (errors.some((m) => /no graph|No CodeGraph|codegraph_unavailable|not built|nothing is there|not available for project/i.test(m))) {
161
+ 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.');
162
+ }
163
+ if (errors.every(Boolean))
164
+ return note('failed', `The code graph answered none of the questions (${errors[0].slice(0, 200)}).`);
165
+ // Scrubbed first, so the pages that share the code map still share one object and it is stored once.
166
+ const store = codeGraphStore(scrubAnswers(answered.answers, { root: resolve(root), repo: repoName(root, env), names: opts.names !== false }));
167
+ const states = Object.values(answered.answers).map((a) => ('result' in a ? text(obj(obj(a.result).graph_currency).state) : '')).filter(Boolean);
168
+ const stale = states.find((x) => x !== 'current');
169
+ return { state: 'present', store, note: `The code graph's answers when this page was built: the map, owners and history, coupling, trust, attack surface, entry points and links.${stale ? ` The graph is ${stale}: the code has moved since it was built, so rebuild it with bravos graph build .` : ''}` };
170
+ }
171
+ /** A value as JSON that is safe inside a <script type="application/json"> tag: no '<' can close the tag, no raw line separators. */
172
+ const inert = (value) => JSON.stringify(value).replace(/</g, '\\u003c').replace(/[\u2028\u2029]/g, (c) => `\\u${c.charCodeAt(0).toString(16)}`);
173
+ // @comment -- "Four of the seven pages draw from the same code map, the largest answer by far (megabytes on a large repository). It is written into the page once, and each message that carried it carries a reference the page's host resolves before posting. Sharing is by identity: only the very object the Map page holds is replaced."
174
+ export function shareCodeMap(store) {
175
+ const shared = store.map.type === 'map' ? store.map.codemap : null;
176
+ if (!shared || typeof shared !== 'object')
177
+ return { codemap: null, pages: store };
178
+ const ref = { $ref: 'codemap' };
179
+ const swap = (v) => (v === shared ? ref : v && typeof v === 'object' && !Array.isArray(v) && v.value === shared ? { ...v, value: ref } : v);
180
+ const pages = Object.fromEntries(Object.entries(store).map(([page, message]) => [page, Object.fromEntries(Object.entries(message).map(([k, v]) => [k, swap(v)]))]));
181
+ return { codemap: shared, pages };
182
+ }
183
+ // @comment -- "Renders the one-file dashboard: the page template with its facts and GuardLink's page each embedded as JSON in a non-executing script tag, every '<' escaped so none can close its tag. When there are code graph answers, they and the vendored Code graph pages (script and stylesheet) are embedded the same way; the page assembles them into a second sandboxed frame. Both go in through one pass with a function replacer, so nothing in either is read as a placeholder or a replacement pattern."
184
+ export function renderDashboard(data, threatModelHtml, store = null) {
185
+ const template = readFileSync(join(templatesDir(), 'dashboard', 'dashboard.html'), 'utf8');
186
+ // One pass over the template, so text inside either value that looks like a placeholder is never filled in turn.
187
+ // The pages' script and stylesheet travel only with a page that has graph answers to draw.
188
+ const asset = (name) => (store ? readFileSync(join(templatesDir(), 'dashboard', name), 'utf8') : '');
189
+ const fill = {
190
+ DATA: () => data,
191
+ THREAT_MODEL: () => threatModelHtml ?? '',
192
+ CODEGRAPH: () => (store ? shareCodeMap(store) : null),
193
+ PAGES_JS: () => asset('codegraph-pages.js'),
194
+ PAGES_CSS: () => asset('codegraph-pages.css'),
195
+ };
196
+ return template.replace(/__BRAVOS_(DATA|THREAT_MODEL|CODEGRAPH|PAGES_JS|PAGES_CSS)__/g, (_m, which) => inert(fill[which]()));
197
+ }
198
+ // @comment -- "bravos dashboard: gathers the repository's facts (read-only git, this machine's plan label), builds GuardLink's page and, on the Team plan, the Code graph pages from the graph's answers, and writes one self-contained HTML file. By default that is .bravos/dashboard/index.html beside a .gitignore of '*', since the page can carry git identities and findings; with `out` nothing is written inside the repository. A page is written even when GuardLink has nothing to show, so the person always gets a file that says what to do next."
199
+ export async function buildDashboard(root, env, opts = {}) {
200
+ // --since reaches git and guardlink as an argument, so a value that could be read as an option is refused first.
201
+ if (opts.since !== undefined && (opts.since.length === 0 || opts.since.startsWith('-') || /[\0\n]/.test(opts.since))) {
202
+ throw new BravosError(`bravos dashboard: --since needs a branch, tag or commit name (got "${opts.since}")`);
203
+ }
204
+ const base = opts.since ?? baseRef(root, env);
205
+ const tm = buildThreatModel(root, env, { base, blame: opts.blame !== false });
206
+ const cg = await buildCodeGraph(root, env, { names: opts.blame !== false });
207
+ let plan = null;
208
+ try {
209
+ const L = (await licenceLib());
210
+ plan = L.planLabel(L.status(env)).label;
211
+ }
212
+ catch {
213
+ /* the page carries no plan label */
214
+ }
215
+ const data = {
216
+ schema: 'bravos.dashboard/v1',
217
+ repo: repoName(root, env),
218
+ branch: git(root, env, ['rev-parse', '--abbrev-ref', 'HEAD']),
219
+ sha: git(root, env, ['rev-parse', '--short', 'HEAD']),
220
+ generatedAt: new Date().toISOString(),
221
+ version: version(),
222
+ plan,
223
+ threatModel: { state: tm.state, note: tm.note, blame: tm.blame, since: tm.since },
224
+ codeGraph: { state: cg.state, note: cg.note },
225
+ };
226
+ const page = renderDashboard(data, tm.html, cg.store);
227
+ let path;
228
+ if (opts.out) {
229
+ path = resolve(opts.out);
230
+ mkdirSync(dirname(path), { recursive: true });
231
+ }
232
+ else {
233
+ const dir = join(root, DASHBOARD_DIR);
234
+ mkdirSync(dir, { recursive: true });
235
+ const ignore = join(dir, '.gitignore');
236
+ if (!existsSync(ignore))
237
+ writeFileSync(ignore, '*\n');
238
+ path = join(root, DASHBOARD_PATH);
239
+ }
240
+ writeFileSync(path, page);
241
+ return { path, threatModel: { state: tm.state, note: tm.note }, codeGraph: { state: cg.state, note: cg.note } };
242
+ }
package/dist/guardlink.js CHANGED
@@ -24,7 +24,7 @@ export function whichBin(name, env = process.env) {
24
24
  return null;
25
25
  }
26
26
  /** Runs `guardlink init` (argv array, no shell) only when `<root>/.guardlink` is absent. */
27
- // @comment -- "Runs guardlink init (argv array, no shell) only when <root>/.guardlink is absent, and reports what it did or would do with the argv it used."
27
+ // @comment -- "Runs guardlink init (argv array, no shell) only when <root>/.guardlink is absent, and reports what it did or would do with the argv it used. Annotation mode is left to GuardLink unless explicitly selected."
28
28
  export function ensureGuardlink(root, harnesses, opts = {}) {
29
29
  if (existsSync(join(root, '.guardlink')))
30
30
  return { status: 'present' };
@@ -33,9 +33,10 @@ export function ensureGuardlink(root, harnesses, opts = {}) {
33
33
  const env = opts.env ?? process.env;
34
34
  const command = [
35
35
  'guardlink', 'init',
36
- '--agent', harnesses.map((h) => AGENT_ID[h]).join(','),
37
- '--mode', opts.mode ?? 'inline',
36
+ '--agent', harnesses.map((h) => AGENT_ID[h]).join(',') || 'none',
38
37
  ];
38
+ if (opts.mode)
39
+ command.push('--mode', opts.mode);
39
40
  if (opts.dryRun)
40
41
  return { status: 'dry-run', command };
41
42
  if (!whichBin('guardlink', env))
package/dist/guide.js CHANGED
@@ -45,7 +45,7 @@ export const GUIDE_TOPICS = [
45
45
  body: [
46
46
  'Run bravos next in a shell (free): it shows which of the nine steps are done here, in the order they build on each other — the code graph first (a machine step every later skill reads), then what the app intends, annotation coverage, SAST (which reads the annotations), how findings are proven and a test target, then the gates (autopilot, the pre-PR gate, CI, cheap to switch on any time) — what each unlocks, and the exact command for the next one. The banner shows the next step too, and every harness gives it to the agent, which offers a few starts the first time and suggests the next step at natural moments.',
47
47
  'Or just ask the agent "help me get started" (or run /bravos, $bravos in Codex): it gives a short tour fitted to this repo. BRAVOS_COACH=off stops the coaching; the Setup line stays.',
48
- 'Keep bravos watch running in a second terminal pane beside your agent (free, read-only, no model): the setup score, open and confirmed exposures, what to test next, stale claims and autopilot nudges, redrawn within seconds of a change. It also shows the hypothesis ledger, boundaries, the model\'s size, the code graph\'s call resolution and entry points, and the branch\'s commits. Keys: n copies the next command, r opens the intent review, d guardlink\'s dashboard, g asks the code graph, t shows test-next, i shows the recorded intent, u refreshes now, j and k scroll, q quits. Three columns from 150 wide, two from 110, one in an 80-column split.',
48
+ 'Keep bravos watch running in a second terminal pane beside your agent (free, read-only, no model): the setup score, open and confirmed exposures, what to test next, stale claims and autopilot nudges, redrawn within seconds of a change. It also shows the hypothesis ledger, boundaries, the model\'s size, the code graph\'s call resolution and entry points, and the branch\'s commits. Keys: n copies the next command, r opens the intent review, d the dashboard (bravos dashboard), g asks the code graph, t shows test-next, i shows the recorded intent, u refreshes now, j and k scroll, q quits. Three columns from 150 wide, two from 110, one in an 80-column split.',
49
49
  ],
50
50
  },
51
51
  {
@@ -127,6 +127,7 @@ export const GUIDE_TOPICS = [
127
127
  { name: 'Keep it fresh while I work, or nightly', skills: ['bravos-schedule'], body: ['An in-session /loop from .claude/loop.md, the nightly workflow, or a cloud task you create. Loops never send test traffic.'] },
128
128
  { name: 'Add or fix security CI', skills: ['bravos-cicd'], body: ['PR gate, nightly annotation, SARIF to code scanning, script-injection fixes.'] },
129
129
  { name: 'An app made of several repositories (microservices)', skills: ['bravos-annotate', 'bravos-codegraph', 'bravos-prove'], body: ['Clone the services side by side in one folder, then run bravos workspace create NAME --member ./gateway=gateway@http://127.0.0.1:8080 --member ./orders=orders@http://127.0.0.1:8081 (bravos workspace plus guardlink link-project plus bravos in each repo and in the shared folder). Work on a service from its own repo; ask questions that cross services from the shared folder, where the briefing and bravos watch show every service. Declare each call to another service as @flows #<this>-<x> -> #<other>-<y> via http (plain ids, not #repo.tag). Build the code graph over the shared folder so it links one service\'s client calls to another\'s handlers. bravos report data --workspace writes one report across the services.'] },
130
+ { name: 'See the findings on one page', skills: ['bravos'], body: ['Run bravos dashboard (free, no model): it writes one self-contained page under .bravos/dashboard/ (git-ignored) and opens it in your browser. It is GuardLink\'s threat model with who introduced and fixed each exposure and what changed since the default branch; on the Team plan, with the code graph built, a second tab shows the code graph: a map of where the risk sits, owners and history, coupling, trust, the attack surface, entry points and links. --no-blame leaves git names out of a page you will share; --no-open only prints the path. Or ask your agent "show me the findings".'] },
130
131
  { name: 'Write up the assessment, a finding or a retest', skills: ['bravos-report'], body: ['Ask "write the assessment report" (or a finding, a retest, an executive brief). bravos report data gathers the evidence; the agent writes report.md in the eight-section reading order, with every proof claim citing its evidence; bravos report check refuses a finding labelled reproduced without a run or ledger record; bravos report export writes md, txt, html and pdf. bravos watch shows the newest report (p to read it, o to open the pdf or html).'] },
131
132
  ],
132
133
  },
package/dist/help.js CHANGED
@@ -25,6 +25,14 @@ Commands
25
25
  --summary for the agent, --share for a claude.ai link (Claude Code).
26
26
  next [dir] The setup score: what is switched on, what each step unlocks, the exact
27
27
  command for the next one (also in the banner and the agent's briefing).
28
+ dashboard [dir]
29
+ One page for the repository's security picture, opened in the browser:
30
+ GuardLink's threat model with who introduced and fixed each exposure and what
31
+ changed since the default branch, and on the Team plan the code graph: a map of
32
+ where the risk sits, owners and history, coupling, trust, attack surface, entry
33
+ points and links. One self-contained file under
34
+ .bravos/dashboard/ (git-ignored); no server, no network, no model. --no-open
35
+ prints the path only, --no-blame leaves git names out, --out writes elsewhere.
28
36
  watch [dir] A live view for a second terminal pane beside any agent: setup, open and
29
37
  confirmed exposures, the hypothesis ledger, what to test next, stale claims, the
30
38
  code graph's resolution and entry points, SAST, the branch, PRs and autopilot
package/dist/hooks.js CHANGED
@@ -62,7 +62,7 @@ function listFiles(dir) {
62
62
  return out;
63
63
  }
64
64
  // @comment -- "Reads and validates one harness settings file and decides which of bravos's hook groups must be appended and which superseded bravos commands removed; writes nothing so every file can be validated before any write."
65
- function planRegistration(root, rel, regs) {
65
+ function planRegistration(root, rel, regs, drops = []) {
66
66
  const abs = join(root, rel);
67
67
  let doc = {};
68
68
  if (existsSync(abs)) {
@@ -106,6 +106,23 @@ function planRegistration(root, rel, regs) {
106
106
  hooks[reg.event] = [...groups, reg.group];
107
107
  changed = true;
108
108
  }
109
+ // @comment -- "Old-name commands for hooks this sync does not register again (the pre-PR gate or autopilot under the old name) point at scripts the migration removed; drop them from this agent's settings, and any group they leave empty. Only exact old-name commands are touched."
110
+ for (const { event, commands } of drops) {
111
+ if (!Array.isArray(hooks[event]))
112
+ continue;
113
+ const gone = new Set(commands);
114
+ const before = JSON.stringify(hooks[event]);
115
+ const groups = hooks[event]
116
+ .map((g) => (isObject(g) && Array.isArray(g.hooks) ? { ...g, hooks: g.hooks.filter((h) => !(isObject(h) && typeof h.command === 'string' && gone.has(h.command))) } : g))
117
+ .filter((g) => !(isObject(g) && Array.isArray(g.hooks) && g.hooks.length === 0));
118
+ if (JSON.stringify(groups) === before)
119
+ continue;
120
+ if (groups.length)
121
+ hooks[event] = groups;
122
+ else
123
+ delete hooks[event];
124
+ changed = true;
125
+ }
109
126
  if (changed)
110
127
  doc.hooks = hooks;
111
128
  return { file: rel, changed, doc };
@@ -162,13 +179,18 @@ export function installHook(root, harnesses, opts = {}) {
162
179
  const src = opts.hooksDir ?? packageHooksDir();
163
180
  const files = listFiles(src).map((abs) => relative(src, abs).split('\\').join('/')).sort();
164
181
  const copied = files.map((f) => `.bravos/hooks/${f}`);
182
+ const withPrePr = (opts.prePr || opts.autopilot) && !opts.globalHome;
183
+ const withAutopilot = opts.autopilot && !opts.globalHome;
165
184
  const plans = [...new Set(harnesses)].map((h) => planRegistration(root, SETTINGS_FILE[h], [
166
185
  sessionStart(h, opts.globalHome),
167
- ...((opts.prePr || opts.autopilot) && !opts.globalHome ? [PRE_PR] : []),
168
- ...(opts.autopilot && !opts.globalHome ? [AUTOPILOT] : []),
186
+ ...(withPrePr ? [PRE_PR] : []),
187
+ ...(withAutopilot ? [AUTOPILOT] : []),
188
+ ], [
189
+ ...(withPrePr ? [] : [{ event: 'PreToolUse', commands: [OLD_HOOK_COMMANDS.prePr] }]),
190
+ ...(withAutopilot ? [] : [{ event: 'Stop', commands: [OLD_HOOK_COMMANDS.autopilot] }]),
169
191
  ]));
170
- // Antigravity reads .agents/skills and .agents/hooks.json, so it rides on the shared-agents harness (per repo only).
171
- if (harnesses.includes('agents') && !opts.globalHome)
192
+ // @comment -- "Antigravity may share skills with Codex, but explicit selection controls its hook independently. Legacy callers retain detection-based registration."
193
+ if ((opts.antigravity ?? harnesses.includes('agents')) && !opts.globalHome)
172
194
  plans.push(planAgy(root));
173
195
  if (!opts.dryRun) {
174
196
  for (const f of files) {
@@ -14,8 +14,8 @@ export function proofToolAction(name, pins = PROOF_TOOL_PINS) {
14
14
  ? `build GuardLink from ${repository} at ${revision} with git and npm, then install its packed CLI globally`
15
15
  : `npm install --global guardlink@${version}`;
16
16
  return revision
17
- ? `cargo install --locked --force --git ${repository} --rev ${revision} cert-x-gen and update its pentest pipeline`
18
- : `cargo install --locked --force --version =${version} cert-x-gen and update its pentest pipeline`;
17
+ ? `cargo install --locked --force --git ${repository} --rev ${revision} cert-x-gen `
18
+ : `cargo install --locked --force --version =${version} cert-x-gen `;
19
19
  }
20
20
  const prerequisites = {
21
21
  git: 'install Git and make git available on PATH',
@@ -57,7 +57,7 @@ export function installProofTool(name, env, echo, pins = PROOF_TOOL_PINS) {
57
57
  cargo: 'Check cargo and rustc, the native linker, network access and the Cargo install root.',
58
58
  git: 'Check Git and network access to the public upstream repository.',
59
59
  npm: 'Check Node and npm, registry access, tar for grammar assets and permission to the global prefix.',
60
- cxg: 'Check cxg pentest status for an existing source-managed pipeline.',
60
+ cxg: 'Check that cxg runs and that its Python environment is writable.',
61
61
  };
62
62
  throw new BravosError(name + ' setup failed during ' + step + ' (' + detail + '). ' + hints[command] + ' Retry with bravos setup --tools -y.');
63
63
  }
@@ -105,10 +105,8 @@ export function installProofTool(name, env, echo, pins = PROOF_TOOL_PINS) {
105
105
  const destination = name === 'guardlink' ? 'the bin directory under npm prefix --global' : 'the bin directory under your Cargo install root (normally ~/.cargo/bin)';
106
106
  throw new BravosError(`${name} was installed but ${found ?? 'no executable'} is selected on PATH (${status.status}). Put ${destination} first, check which -a ${name}, then run bravos setup --check.`);
107
107
  }
108
- if (name === 'cxg') {
109
- executables.set('cxg', found);
110
- invoke('cxg', ['--disable-update-check', 'pentest', 'update'], work, 'synchronizing the embedded pentest pipeline');
111
- }
108
+ // Bravos drives cxg only through `cxg scan`, whose first probe run installs or refreshes cxg's
109
+ // embedded pipeline itself; no `cxg pentest` command is run here.
112
110
  return found;
113
111
  }
114
112
  finally {
package/dist/install.js CHANGED
@@ -3,7 +3,7 @@ import { dirname, join } from 'node:path';
3
3
  import { installedGuardlinkSkills } from './guardlink.js';
4
4
  import { readLock, sha256, writeLock } from './lock.js';
5
5
  import { skillsDir as bundledSkillsDir, version } from './paths.js';
6
- import { listBundledSkills, MARKER, renderSkillFile, skillsRoot } from './skills.js';
6
+ import { listBundledSkills, MARKER, renderSkillFile, skillsRoot, withoutOwnAnnotations } from './skills.js';
7
7
  // @comment -- "Writes the bundled skills into each harness skills root, rendering placeholders and marking SKILL.md only; overwrites only files bravos wrote and nobody edited (lock hash, or the marker for an unlocked SKILL.md) unless forced, and records hashes in the skills lock."
8
8
  export function installSkills(root, harnesses, opts = {}) {
9
9
  const report = { written: [], updated: [], unchanged: [], skipped: [] };
@@ -18,7 +18,7 @@ export function installSkills(root, harnesses, opts = {}) {
18
18
  const isSkillMd = file.rel === 'SKILL.md';
19
19
  const content = isMd
20
20
  ? Buffer.from((opts.render ?? renderSkillFile)(file.content.toString('utf8'), harness, skill.name, file.rel))
21
- : file.content;
21
+ : withoutOwnAnnotations(file.content, file.rel);
22
22
  const newHash = sha256(content);
23
23
  const abs = join(root, path);
24
24
  try {
package/dist/licence.js CHANGED
@@ -9,15 +9,22 @@ export const licenceLib = () => (cached ??= import(pathToFileURL(join(hooksDir()
9
9
  export async function licenceStatus(env) {
10
10
  return (await licenceLib()).status(env);
11
11
  }
12
- // @comment -- "The gate: first renews this machine's device licence when it is due (hooks/lib/refresh.mjs; fail-open, never for a token from the environment), then returns the status when `feature` is unlocked, else throws a BravosError whose message says what `what` does, that it is on the Team plan, and how to start the trial or renew — prefixed with why, when the renewal found this machine is no longer licensed. Every paid command and flag goes through here, so a refusal always reads the same."
13
- export async function requireFeature(env, feature, what, io = {}) {
12
+ // @comment -- "Whether `feature` is unlocked on this machine, without throwing: renews the device licence when it is due (hooks/lib/refresh.mjs; fail-open, never for a token from the environment), then returns the status, the answer, and the sentence to show when it is locked. For callers that carry on without the feature (the dashboard leaves its code-graph tab as a note) instead of refusing."
13
+ export async function featureState(env, feature, what, io = {}) {
14
14
  const L = await licenceLib();
15
15
  const renewed = await refresh({ env, fetch: io.fetch });
16
16
  const v = L.status(env);
17
17
  if (L.entitled(v, feature))
18
- return v;
18
+ return { status: v, entitled: true, refusal: '' };
19
19
  const why = renewed.outcome === 'revoked' || renewed.outcome === 'lapsed' ? `${renewed.note} ` : '';
20
- throw new BravosError(why + L.refusal(v, feature, what));
20
+ return { status: v, entitled: false, refusal: why + L.refusal(v, feature, what) };
21
+ }
22
+ // @comment -- "The gate: featureState, then the status when `feature` is unlocked, else a BravosError whose message says what `what` does, that it is on the Team plan, and how to start the trial or renew — prefixed with why, when the renewal found this machine is no longer licensed. Every paid command and flag goes through here, so a refusal always reads the same."
23
+ export async function requireFeature(env, feature, what, io = {}) {
24
+ const f = await featureState(env, feature, what, io);
25
+ if (f.entitled)
26
+ return f.status;
27
+ throw new BravosError(f.refusal);
21
28
  }
22
29
  /** The JSON document `bravos licence --json` prints: the status without the tenant id (an account id is not for logs). */
23
30
  export function licenceDocument(v) {
package/dist/omp.js CHANGED
@@ -2,6 +2,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
2
  import { delimiter, dirname, join } from 'node:path';
3
3
  import { readLock, sha256, writeLock } from './lock.js';
4
4
  import { templatesDir } from './paths.js';
5
+ import { withoutOwnAnnotations } from './skills.js';
5
6
  // @comment -- "Where bravos's omp extension lives; omp auto-loads project extensions from .omp/extensions/ in the working directory."
6
7
  export const OMP_EXTENSION_PATH = '.omp/extensions/bravos.js';
7
8
  const MANAGED = '// bravos (managed by bravos init/sync';
@@ -19,7 +20,7 @@ export function writeOmpExtension(root, env, opts = {}) {
19
20
  return { status: 'absent' };
20
21
  const path = OMP_EXTENSION_PATH;
21
22
  const abs = join(root, path);
22
- const content = readFileSync(opts.source ?? join(templatesDir(), 'omp', 'bravos.js'));
23
+ const content = withoutOwnAnnotations(readFileSync(opts.source ?? join(templatesDir(), 'omp', 'bravos.js')), 'bravos.js');
23
24
  const hash = sha256(content);
24
25
  const lock = readLock(root);
25
26
  let status = 'written';
package/dist/open.js ADDED
@@ -0,0 +1,22 @@
1
+ import { spawn } from 'node:child_process';
2
+ // @comment -- "Whether opening a browser can work here: never in CI, and on Linux only with a display. macOS and Windows always have an opener."
3
+ export function canOpen(env = process.env, platform = process.platform) {
4
+ if (env.CI)
5
+ return false;
6
+ if (platform === 'darwin' || platform === 'win32')
7
+ return true;
8
+ return !!(env.DISPLAY || env.WAYLAND_DISPLAY);
9
+ }
10
+ // @comment -- "Opens a URL or a file in the person's browser with the OS opener (argv, no shell). Returns false when nothing was started; failure is otherwise silent, because every caller prints the URL or path anyway."
11
+ export function openInBrowser(target, env = process.env) {
12
+ if (!canOpen(env))
13
+ return false;
14
+ const [cmd, args] = process.platform === 'darwin' ? ['open', [target]] : process.platform === 'win32' ? ['cmd', ['/c', 'start', '', target]] : ['xdg-open', [target]];
15
+ try {
16
+ spawn(cmd, args, { detached: true, stdio: 'ignore' }).on('error', () => { }).unref();
17
+ return true;
18
+ }
19
+ catch {
20
+ return false;
21
+ }
22
+ }
package/dist/opencode.js CHANGED
@@ -3,6 +3,7 @@ import { delimiter, dirname, join } from 'node:path';
3
3
  import { readLock, sha256, writeLock } from './lock.js';
4
4
  import { staleGraphEntry } from './mcp.js';
5
5
  import { skillsDir as bundledSkillsDir, templatesDir } from './paths.js';
6
+ import { withoutOwnAnnotations } from './skills.js';
6
7
  import { BravosError } from './types.js';
7
8
  // @comment -- "Where bravos's opencode files live: the plugin (session start), one command per skill (opencode lists skills only through its skill tool, not as /commands), and the project opencode.json for MCP."
8
9
  export const OPENCODE_PLUGIN_PATH = '.opencode/plugins/bravos.js';
@@ -69,7 +70,7 @@ export function writeOpencode(root, env, servers, opts = {}) {
69
70
  mcp[n] = { type: 'local', command: [servers[n].command, ...servers[n].args], enabled: true, ...(servers[n].env ? { environment: servers[n].env } : {}) };
70
71
  }
71
72
  const files = [];
72
- files.push({ path: OPENCODE_PLUGIN_PATH, content: readFileSync(opts.plugin ?? join(templatesDir(), 'opencode', 'bravos.js')) });
73
+ files.push({ path: OPENCODE_PLUGIN_PATH, content: withoutOwnAnnotations(readFileSync(opts.plugin ?? join(templatesDir(), 'opencode', 'bravos.js')), 'bravos.js') });
73
74
  const sdir = opts.skillsDir ?? bundledSkillsDir();
74
75
  for (const name of readdirSync(sdir).filter((n) => existsSync(join(sdir, n, 'SKILL.md'))).sort()) {
75
76
  const desc = skillSummary(readFileSync(join(sdir, name, 'SKILL.md'), 'utf8'));
package/dist/setup.js CHANGED
@@ -152,8 +152,17 @@ export async function runSast(root, env, opts = {}) {
152
152
  }
153
153
  writeFileSync(join(runDir, 'meta.json'), JSON.stringify({ sha, base: null, scope: opts.scope?.length ? opts.scope.join(',') : 'all', exit: r.status, at: new Date().toISOString(), analyzer: bin, codegraph }, null, 2) + '\n');
154
154
  const lines = [`SAST run ${run}: bravos-cli exited ${r.status ?? 'by signal'} (0 clean at the level, 1 findings, 3 licence refused or analysis failed, 4 a stage failed)`, ` report: ${join(runDir, 'report.json')}`, ...notes];
155
- if (r.status !== 0 && r.status !== 1)
156
- lines.push(` ${(r.stderr || r.stdout || '').trim().split('\n').slice(-3).join('\n ')}`);
155
+ // @comment -- "Keep analyzer diagnostics in the gitignored run folder with owner-only permissions, including warnings on exit 0/1. Failure summaries show both ends so trailing progress cannot hide the cause; spawn errors have no stderr."
156
+ if (r.stderr) {
157
+ const stderrPath = join(runDir, 'analyzer.stderr.log');
158
+ writeFileSync(stderrPath, r.stderr, { mode: 0o600 });
159
+ lines.push(` analyzer stderr: ${stderrPath}`);
160
+ }
161
+ if (r.status !== 0 && r.status !== 1) {
162
+ const detail = (r.stderr?.trim() || r.error?.message || r.stdout?.trim() || `terminated by ${r.signal ?? 'unknown signal'}`).split('\n');
163
+ const summary = detail.length > 20 ? [...detail.slice(0, 10), '… (full stderr in the run log)', ...detail.slice(-10)] : detail;
164
+ lines.push(` analyzer failed: ${summary.map((line) => line.slice(0, 1000)).join('\n ')}`);
165
+ }
157
166
  lines.push(' next: bravos sast candidates');
158
167
  return { dir: runDir, exit: r.status, lines };
159
168
  }
package/dist/skills.js CHANGED
@@ -47,6 +47,14 @@ function withMarker(content, rel) {
47
47
  lines.splice(at, 0, MARKER);
48
48
  return lines.join('\n');
49
49
  }
50
+ // @comment -- "Bravos's own GuardLink annotations must not travel into a customer's repository with the scripts it installs there: GuardLink counts any annotated file towards coverage, so a fresh project used to report 50% before anyone had annotated anything, and the model listed Bravos's files as the customer's. Each one-line annotation comment (// @verb … -- \"text\") becomes a plain comment carrying the same text; every other byte is kept."
51
+ export function withoutOwnAnnotations(content, rel) {
52
+ if (!/\.(mjs|cjs|js|ts)$/.test(rel))
53
+ return content;
54
+ const text = content.toString('utf8');
55
+ const out = text.replace(/^([ \t]*\/\/)[ \t]*@[a-z]+\b[^\n]*?-- "((?:[^"\\\n]|\\.)*)"[ \t]*$/gm, (_m, lead, desc) => `${lead} ${desc.replace(/\\(.)/g, '$1')}`);
56
+ return out === text ? content : Buffer.from(out);
57
+ }
50
58
  /** Insert the generated marker into SKILL.md after the frontmatter (or at line 1) and substitute placeholders. */
51
59
  // @comment -- "Renders a bundled skill file for one harness: inserts the generated marker into SKILL.md (rel is the file's path inside the skill folder) and substitutes {{SKILL_DIR}} and {{SKILLS_ROOT}} in every .md file."
52
60
  export function renderSkillFile(content, harness, name, rel = 'SKILL.md') {
@@ -231,10 +231,18 @@ async function flow(opts, d) {
231
231
  s.proving = 'none';
232
232
  return;
233
233
  }
234
+ // @comment -- "Automatic replay needs an origin default grant. Detect a missing or dangling pointer before offering consent, and show the repair without changing Git configuration."
235
+ const defaultRef = d.exec('git', ['symbolic-ref', '--quiet', 'refs/remotes/origin/HEAD'], { cwd: s.repo });
236
+ const autoReady = defaultRef.code === 0 && !!defaultRef.out.trim()
237
+ && d.exec('git', ['rev-parse', '--verify', `${defaultRef.out.trim()}^{commit}`], { cwd: s.repo }).code === 0;
238
+ if (!autoReady)
239
+ p.warn('Automatic proving is unavailable: origin/HEAD is missing or unresolved. Fetch the default branch, then run git remote set-head origin --auto (or git remote set-head origin <branch>), and run bravos start --again. Use Ask me every time for a local clone.');
234
240
  const choices = [
235
241
  { value: 'ask', label: 'Ask me every time before testing', recommended: true },
236
- { value: 'auto', label: 'Test my local app as I build', hint: 'includes scoped tests written by this agent' },
237
- { value: 'auto-reviewed', label: 'Automatically replay reviewed kits only', hint: 'uses the tested kit version on the default branch' },
242
+ ...(autoReady ? [
243
+ { value: 'auto', label: 'Test my local app as I build', hint: 'includes scoped tests written by this agent' },
244
+ { value: 'auto-reviewed', label: 'Automatically replay reviewed kits only', hint: 'uses the tested kit version on the default branch' },
245
+ ] : []),
238
246
  ...(s.schedule !== 'none' && s.nightlyAgent !== 'copilot' ? [{ value: 'schedule', label: 'Only in the scheduled run' }] : []),
239
247
  { value: 'none', label: 'Never test, just annotate' },
240
248
  ];