@bugb-technologies/bravos 1.4.2 → 1.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -36,6 +36,7 @@ For manual setup, run `bravos init` in your repository to write skills, hooks an
36
36
  | `bravos doctor` | Check installed tools and configuration. |
37
37
  | `bravos next` | Show setup progress and the next step. |
38
38
  | `bravos watch` | Watch security work live in a second terminal pane. |
39
+ | `bravos dashboard` | Open the findings as one page in your browser: the threat model and, on Team, the code graph. |
39
40
  | `bravos guide` | Read the guide by role, task or skill. |
40
41
 
41
42
  ## Skills
package/dist/account.js CHANGED
@@ -1,9 +1,9 @@
1
1
  // @comment -- "bravos account: how a licence gets onto this machine. `activate` is the device-code pairing with the account portal (one POST to start, the browser to approve, polling until the portal hands back a signed token); `import` takes a downloaded file. Either way the token is verified by the same offline verifier before it is written, so a token the portal signed with a key this build does not trust is refused here, not at the first gated command. The origin is fixed (BRAVOS_ACCOUNT_ORIGIN overrides it for a local portal), no proxy is read from the environment, and the token is written 0600."
2
- import { spawn } from 'node:child_process';
3
2
  import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
4
3
  import { hostname } from 'node:os';
5
4
  import { join } from 'node:path';
6
5
  import { refreshLib, userAgent } from './device.js';
6
+ import { openInBrowser } from './open.js';
7
7
  import { licenceLib, licenceLines } from './licence.js';
8
8
  import { BravosError } from './types.js';
9
9
  export const ACTIVATION_PATH = '/api/v1/cli/activation';
@@ -18,15 +18,6 @@ export const accountOrigin = (env, L) => {
18
18
  throw new BravosError(`BRAVOS_ACCOUNT_ORIGIN must be an origin like https://account.bugb.io, got ${JSON.stringify(raw)}`);
19
19
  return raw;
20
20
  };
21
- const defaultOpen = (url) => {
22
- const [cmd, args] = process.platform === 'darwin' ? ['open', [url]] : process.platform === 'win32' ? ['cmd', ['/c', 'start', '', url]] : ['xdg-open', [url]];
23
- try {
24
- spawn(cmd, args, { stdio: 'ignore', detached: true }).unref();
25
- }
26
- catch {
27
- /* the URL is printed anyway */
28
- }
29
- };
30
21
  const licenceFile = (env, L) => {
31
22
  const home = L.bravosHome(env);
32
23
  if (!home)
@@ -71,7 +62,7 @@ export async function activate(io) {
71
62
  const f = io.fetch ?? fetch;
72
63
  const sleep = io.sleep ?? ((s) => new Promise((r) => setTimeout(r, s * 1000)));
73
64
  const now = io.now ?? (() => Date.now() / 1000);
74
- const open = io.open ?? defaultOpen;
65
+ const open = io.open ?? ((url) => void openInBrowser(url, io.env));
75
66
  const ua = { 'User-Agent': userAgent(), Accept: 'application/json' };
76
67
  let start;
77
68
  try {
package/dist/cli.js CHANGED
@@ -26,6 +26,7 @@ import { listDevices, logout, refresh as refreshDevice, revokeDevice } from './d
26
26
  import * as graph from './codegraph.js';
27
27
  import { askGraph } from './watch.js';
28
28
  import { plan as setupPlan, runSast, runSetup } from './setup.js';
29
+ import { openInBrowser } from './open.js';
29
30
  import { licenceDocument, licenceLib, licenceLines, requireFeature } from './licence.js';
30
31
  import { migrateFromOldName, OLD_DIR, reportMigration } from './migrate.js';
31
32
  import { listBundledSkills } from './skills.js';
@@ -715,7 +716,7 @@ export function buildProgram(io, result) {
715
716
  const rel = writePage(root, kind, await renderReview(draft, { kind: 'file' }));
716
717
  lines.push(`Review page: ${rel} (Save downloads your answers; put them in .guardlink/${kind}-answers/ and commit)`);
717
718
  if (opts.open !== false)
718
- openInBrowser(pathJoin(root, rel));
719
+ openInBrowser(pathJoin(root, rel), io.env);
719
720
  return;
720
721
  }
721
722
  const port = await freePort();
@@ -729,7 +730,7 @@ export function buildProgram(io, result) {
729
730
  lines.push(`Answers save to .guardlink/${kind}-answers/<name>.json. Teammates run bravos review ${kind} after pulling. The page stops on Done or after 30 minutes idle.`);
730
731
  lines.push(`When everyone is done: bravos review ${kind} --summary`);
731
732
  if (opts.open !== false)
732
- openInBrowser(url);
733
+ openInBrowser(url, io.env);
733
734
  }));
734
735
  program
735
736
  .command('next [dir]')
@@ -746,7 +747,16 @@ export function buildProgram(io, result) {
746
747
  lines.push(JSON.stringify(s, null, 2));
747
748
  return;
748
749
  }
749
- lines.push(`bravos setup ${s.done}/${s.total} for ${inputs.repo}`, '');
750
+ lines.push(`bravos setup ${s.done}/${s.total} for ${inputs.repo}`);
751
+ // Which plan this machine is on, so the Team-plan steps below read as a choice and not a fault.
752
+ try {
753
+ if (inputs.licence?.state)
754
+ lines.push((await licenceLib()).planLine(inputs.licence));
755
+ }
756
+ catch {
757
+ /* no plan line */
758
+ }
759
+ lines.push('');
750
760
  for (const item of s.items) {
751
761
  const mark = item.on ? '✔' : item.unavailable ? '·' : item === s.next ? '→' : '✘';
752
762
  lines.push(`${mark} ${item.label}${item.on ? '' : item.unavailable ? ' (not available here)' : ''}`);
@@ -774,6 +784,30 @@ export function buildProgram(io, result) {
774
784
  const report = r.resync(root, opts.from, { apply: !!opts.apply, env: io.env });
775
785
  lines.push(...(opts.json ? [JSON.stringify(report, null, 2)] : r.formatReport(report)));
776
786
  }));
787
+ program
788
+ .command('dashboard [dir]')
789
+ .description("One page for the repository's security picture, opened in the browser: GuardLink's threat model with who introduced and fixed each exposure and what changed since the default branch, and on the Team plan the code graph (map, owners, coupling, attack surface, entry points). Rebuilt from the code every time: on the Team plan a code graph that is missing or behind is rebuilt first. Written to .bravos/dashboard/index.html (git-ignored); one self-contained file, no server, no network, no model.")
790
+ .option('--out <file>', 'write the page here instead; nothing is then written inside the repository')
791
+ .option('--since <ref>', "compare against this branch, tag or commit instead of the repository's default branch")
792
+ .option('--no-blame', 'leave git names out (who introduced and fixed each exposure, and the code graph\'s owners), for a page you will share')
793
+ .option('--no-open', 'write the page and print its path without opening a browser')
794
+ .option('--no-graph-build', 'draw from the code graph as it is; do not rebuild it first when it is missing or behind the code')
795
+ .option('--json', 'print the result as JSON (bravos.dashboard-run/v1)')
796
+ .action((dir, opts) => guardedAsync(async (lines) => {
797
+ const root = dirArg(dir);
798
+ const { buildDashboard } = await import('./dashboard.js');
799
+ // What takes minutes is said as it starts, on stderr, so --json output stays one document.
800
+ const r = await buildDashboard(root, io.env, { out: opts.out, since: opts.since, blame: opts.blame, graphBuild: opts.graphBuild, onProgress: (line) => io.stderr(line) });
801
+ // Opening is a convenience: the path is always printed, and a session with no display just reads it.
802
+ const opened = opts.open !== false && !opts.json && openInBrowser(r.path, io.env);
803
+ if (opts.json) {
804
+ lines.push(JSON.stringify({ schema: 'bravos.dashboard-run/v1', path: r.path, opened, threatModel: r.threatModel, codeGraph: r.codeGraph }, null, 2));
805
+ return;
806
+ }
807
+ lines.push(`Dashboard: ${r.path}${opened ? ' (opened in your browser)' : ''}`, ` threat model: ${r.threatModel.note}`, ` code graph: ${r.codeGraph.note}`);
808
+ if (!opened && opts.open !== false)
809
+ lines.push(' No browser could be opened here; open the file above.');
810
+ }));
777
811
  program
778
812
  .command('watch [dir]')
779
813
  .description('A live, read-only view of the repository\'s security work for a second terminal pane beside any agent: setup, open and confirmed exposures, what to test next, stale claims, the code graph, SAST, teammates\' PRs and autopilot nudges. Redraws when files change. Runs no model.')
@@ -1008,7 +1042,7 @@ export function buildProgram(io, result) {
1008
1042
  if (opts.open) {
1009
1043
  const target = r.written.find((w) => w.format === 'pdf') ?? r.written.find((w) => w.format === 'html');
1010
1044
  if (target)
1011
- openInBrowser(target.path);
1045
+ openInBrowser(target.path, io.env);
1012
1046
  }
1013
1047
  lines.push('These files quote assessment evidence and are not committed; share them deliberately.');
1014
1048
  return;
@@ -1109,16 +1143,6 @@ function seconds(min) {
1109
1143
  return n;
1110
1144
  };
1111
1145
  }
1112
- // @comment -- "Opens a URL or file in the person's browser with the OS opener (argv, no shell); failure is silent because the URL is printed anyway."
1113
- function openInBrowser(target) {
1114
- const [cmd, args] = process.platform === 'darwin' ? ['open', [target]] : process.platform === 'win32' ? ['cmd', ['/c', 'start', '', target]] : ['xdg-open', [target]];
1115
- try {
1116
- spawnChild(cmd, args, { detached: true, stdio: 'ignore' }).on('error', () => { }).unref();
1117
- }
1118
- catch {
1119
- /* printed URL is enough */
1120
- }
1121
- }
1122
1146
  // @comment -- "Runs the CLI in-process and returns the exit code: 0 ok, 1 BravosError, 2 commander usage error."
1123
1147
  export async function run(argv, io = {}) {
1124
1148
  const full = {
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,283 @@
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
+ /** What the saved page was built from, for the session briefing to tell a current page from an old one. */
12
+ export const DASHBOARD_META = `${DASHBOARD_DIR}/meta.json`;
13
+ const git = (root, env, args) => {
14
+ const r = spawnSync('git', args, { cwd: root, env, encoding: 'utf8', timeout: 10000, stdio: ['ignore', 'pipe', 'ignore'] });
15
+ return r.error || r.status !== 0 ? null : r.stdout.trim();
16
+ };
17
+ // @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."
18
+ export function repoName(root, env) {
19
+ const url = git(root, env, ['config', '--get', 'remote.origin.url']);
20
+ const fromUrl = url ? url.replace(/\/+$/, '').replace(/\.git$/, '').split(/[/:]/).pop() : '';
21
+ return fromUrl || basename(resolve(root)) || 'repository';
22
+ }
23
+ // @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."
24
+ export function baseRef(root, env) {
25
+ const head = git(root, env, ['symbolic-ref', '-q', '--short', 'refs/remotes/origin/HEAD']);
26
+ for (const ref of [head, 'origin/main']) {
27
+ if (ref && git(root, env, ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`]) !== null)
28
+ return ref;
29
+ }
30
+ return null;
31
+ }
32
+ // @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."
33
+ export function buildThreatModel(root, env, opts) {
34
+ const dir = mkdtempSync(join(tmpdir(), 'bravos-dashboard-'));
35
+ const file = join(dir, 'threat-model.html');
36
+ const attempts = [];
37
+ if (opts.blame && opts.base)
38
+ attempts.push({ blame: true, since: opts.base });
39
+ if (opts.base)
40
+ attempts.push({ blame: false, since: opts.base });
41
+ if (opts.blame)
42
+ attempts.push({ blame: true, since: null });
43
+ attempts.push({ blame: false, since: null });
44
+ let last = '';
45
+ try {
46
+ for (const a of attempts) {
47
+ const args = ['dashboard', '.', '-o', file, ...(a.blame ? ['--blame'] : []), ...(a.since ? ['--since', a.since] : [])];
48
+ const r = spawnSync('guardlink', args, { cwd: root, env, encoding: 'utf8', timeout: 300000, maxBuffer: 64 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
49
+ if (r.error) {
50
+ const missing = r.error.code === 'ENOENT';
51
+ 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}).` };
52
+ }
53
+ if (r.status === 0 && existsSync(file)) {
54
+ const extras = [a.blame ? 'who introduced and fixed each exposure' : null, a.since ? `what changed since ${a.since}` : null].filter(Boolean);
55
+ return { state: 'present', html: readFileSync(file, 'utf8'), blame: a.blame, since: a.since, note: `GuardLink's threat model${extras.length ? `, with ${extras.join(' and ')}` : ''}.` };
56
+ }
57
+ last = `${r.stderr ?? ''}\n${r.stdout ?? ''}`.split('\n').map((l) => l.trim()).filter(Boolean)[0] ?? `guardlink exited ${r.status}`;
58
+ }
59
+ 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.` };
60
+ }
61
+ finally {
62
+ rmSync(dir, { recursive: true, force: true });
63
+ }
64
+ }
65
+ const obj = (v) => (v && typeof v === 'object' && !Array.isArray(v) ? v : {});
66
+ const text = (v) => (typeof v === 'string' ? v : '');
67
+ // The questions the seven pages are drawn from, with the arguments the Bravos VS Code extension asks them with
68
+ // (siete: clients/vscode/src/webview/pagesPanel.ts): the code map with its caps lifted so nothing is trimmed,
69
+ // hotspots by heat, and the full entry-point and access lists.
70
+ const QUESTIONS = {
71
+ codemap: { tool: 'codegraph_codemap', args: { max_children_per_parent: 100000, max_nodes: 100000 } },
72
+ threat: { tool: 'codegraph_threat_model', args: {} },
73
+ hotspots: { tool: 'codegraph_hotspots', args: { rank_by: 'heat', limit: 500 } },
74
+ mix: { tool: 'codegraph_commit_mix', args: {} },
75
+ coChange: { tool: 'codegraph_co_change', args: {} },
76
+ surface: { tool: 'codegraph_attack_surface', args: {} },
77
+ entries: { tool: 'codegraph_entry_points', args: { limit: 5000 } },
78
+ access: { tool: 'codegraph_auth_boundary', args: { limit: 5000 } },
79
+ };
80
+ /** The command line a reader can run to ask the same question; each page prints the ones it was drawn from. */
81
+ const commandLine = (q) => {
82
+ const { tool, args } = QUESTIONS[q];
83
+ const flags = Object.entries(args).map(([k, v]) => ` --${k.replace(/_/g, '-')} ${v}`).join('');
84
+ return `bravos graph ${tool.replace(/^codegraph_/, '').replace(/_/g, '-')}${flags} --json`;
85
+ };
86
+ // @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."
87
+ export function scrubAnswers(value, opts) {
88
+ const people = new Map();
89
+ const person = (name) => {
90
+ if (!people.has(name))
91
+ people.set(name, `person ${people.size + 1}`);
92
+ return people.get(name);
93
+ };
94
+ const NAME_KEYS = new Set(['author', 'top_author', 'top_owner']);
95
+ const NAME_LISTS = new Set(['owners', 'authors', 'top_contributions']);
96
+ const walk = (v, key, parent) => {
97
+ if (typeof v === 'string') {
98
+ if (!opts.names && v && (NAME_KEYS.has(key) || (key === 'name' && NAME_LISTS.has(parent))))
99
+ return person(v);
100
+ if (v === opts.root)
101
+ return opts.repo;
102
+ return v.startsWith(`${opts.root}/`) ? `${opts.repo}${v.slice(opts.root.length)}` : v;
103
+ }
104
+ if (Array.isArray(v))
105
+ return v.map((x) => walk(x, key, parent));
106
+ if (v && typeof v === 'object')
107
+ return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, walk(x, k, Array.isArray(x) ? k : key)]));
108
+ return v;
109
+ };
110
+ return walk(value, '', '');
111
+ }
112
+ // @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."
113
+ export function codeGraphStore(answers) {
114
+ const got = (q) => {
115
+ const a = answers[QUESTIONS[q].tool];
116
+ if (!a)
117
+ return { ok: false, message: 'the code graph was not asked' };
118
+ return 'error' in a ? { ok: false, message: a.error } : { ok: true, value: a.result };
119
+ };
120
+ 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' });
121
+ const cm = got('codemap');
122
+ const doc = cm.ok ? obj(cm.value).codemap : undefined;
123
+ const codemap = cm.ok && doc ? { ok: true, value: doc } : cm.ok ? { ok: false, message: 'the code graph answered without a map' } : cm;
124
+ const asked = (...qs) => qs.map(commandLine);
125
+ const [threat, hot, mix, co, surface, entries, access] = [got('threat'), got('hotspots'), got('mix'), got('coChange'), got('surface'), got('entries'), got('access')];
126
+ return {
127
+ map: codemap.ok ? { type: 'map', codemap: codemap.value, asked: asked('codemap'), findings: null } : refused('map', 'The map could not be built', codemap),
128
+ trust: codemap.ok ? { type: 'trust', codemap: codemap.value, threatModel: threat, asked: asked('codemap', 'threat') } : refused('trust', 'The graph could not describe itself', codemap),
129
+ owners: !hot.ok
130
+ ? refused('owners', 'Churn and ownership are not available', hot)
131
+ : !codemap.ok
132
+ ? refused('owners', 'Churn and ownership are not available', codemap)
133
+ : { type: 'owners', hotspots: hot.value, codemap: codemap.value, commitMix: mix, asked: asked('hotspots', 'codemap', 'mix') },
134
+ coupling: co.ok ? { type: 'coupling', coChange: co.value, codemap, asked: asked('coChange', 'codemap') } : refused('coupling', 'Co-change coupling is not available', co),
135
+ surface: surface.ok ? { type: 'surface', attackSurface: surface.value, issues: null, asked: asked('surface') } : refused('surface', 'The attack surface is not available', surface),
136
+ entries: entries.ok ? { type: 'entries', entryPoints: entries.value, access, asked: asked('entries', 'access') } : refused('entries', 'Entry points are not available', entries),
137
+ links: { type: 'links', entryPoints: entries, asked: asked('entries') },
138
+ };
139
+ }
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."
142
+ export async function graphState(root, env) {
143
+ try {
144
+ const a = (await graph.askMany(root, env, [{ tool: 'codegraph_entry_points', args: { limit: 1 } }], 60000)).answers.codegraph_entry_points;
145
+ if (!a)
146
+ return 'unknown';
147
+ if ('error' in a)
148
+ return NOT_BUILT.test(a.error) ? 'not-built' : 'unknown';
149
+ const state = text(obj(obj(a.result).graph_currency).state);
150
+ return state === 'current' ? 'current' : state ? 'diverged' : 'unknown';
151
+ }
152
+ catch {
153
+ return 'unknown';
154
+ }
155
+ }
156
+ // @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
+ if (state !== 'not-built' && state !== 'diverged')
160
+ return '';
161
+ 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…');
162
+ const started = Date.now();
163
+ try {
164
+ const r = graph.build(root, env, { scip: 'no-exec', ...(state === 'diverged' ? { mode: 'build' } : {}) });
165
+ if (r.status === 0)
166
+ return ` The graph was rebuilt for this page (${Math.max(1, Math.round((Date.now() - started) / 1000))} s).`;
167
+ const why = `${r.stderr}\n${r.stdout}`.split('\n').map((l) => l.trim()).filter(Boolean).pop() ?? `exit ${r.status}`;
168
+ return ` The graph could not be rebuilt (${why.slice(0, 160)}).`;
169
+ }
170
+ catch (e) {
171
+ return ` The graph could not be rebuilt (${e.message.slice(0, 160)}).`;
172
+ }
173
+ }
174
+ // @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. Unless told not to, a graph that is missing for this commit or behind the code is rebuilt first (refreshGraph), so the page is drawn from the code as it stands. A graph that is not installed, still not built, or that answers nothing is a short note naming the command that fixes it."
175
+ export async function buildCodeGraph(root, env, opts = {}) {
176
+ const note = (state, sentence) => ({ state, note: sentence, store: null });
177
+ let entitled = false;
178
+ try {
179
+ entitled = (await featureState(env, 'codegraph', 'bravos dashboard', { fetch: opts.fetch })).entitled;
180
+ }
181
+ catch {
182
+ /* an unreadable licence reads as none */
183
+ }
184
+ if (!entitled)
185
+ 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
+ if (!graph.graphBin('codegraph-mcp', env))
187
+ 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
+ let answered;
191
+ try {
192
+ answered = await graph.askMany(root, env, Object.values(QUESTIONS).map((q) => ({ tool: q.tool, args: { ...q.args } })), 300000);
193
+ }
194
+ catch (e) {
195
+ return note('failed', `The code graph could not be asked (${e.message.slice(0, 200)}).`);
196
+ }
197
+ const errors = Object.values(answered.answers).map((a) => ('error' in a ? a.error : ''));
198
+ if (errors.some((m) => NOT_BUILT.test(m))) {
199
+ 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}`);
200
+ }
201
+ if (errors.every(Boolean))
202
+ return note('failed', `The code graph answered none of the questions (${errors[0].slice(0, 200)}).`);
203
+ // Scrubbed first, so the pages that share the code map still share one object and it is stored once.
204
+ const store = codeGraphStore(scrubAnswers(answered.answers, { root: resolve(root), repo: repoName(root, env), names: opts.names !== false }));
205
+ const states = Object.values(answered.answers).map((a) => ('result' in a ? text(obj(obj(a.result).graph_currency).state) : '')).filter(Boolean);
206
+ const stale = states.find((x) => x !== 'current');
207
+ 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.${rebuilt}${stale ? ` The graph is ${stale}: the code has moved since it was built, so rebuild it with bravos graph build .` : ''}` };
208
+ }
209
+ /** A value as JSON that is safe inside a <script type="application/json"> tag: no '<' can close the tag, no raw line separators. */
210
+ const inert = (value) => JSON.stringify(value).replace(/</g, '\\u003c').replace(/[\u2028\u2029]/g, (c) => `\\u${c.charCodeAt(0).toString(16)}`);
211
+ // @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."
212
+ export function shareCodeMap(store) {
213
+ const shared = store.map.type === 'map' ? store.map.codemap : null;
214
+ if (!shared || typeof shared !== 'object')
215
+ return { codemap: null, pages: store };
216
+ const ref = { $ref: 'codemap' };
217
+ const swap = (v) => (v === shared ? ref : v && typeof v === 'object' && !Array.isArray(v) && v.value === shared ? { ...v, value: ref } : v);
218
+ const pages = Object.fromEntries(Object.entries(store).map(([page, message]) => [page, Object.fromEntries(Object.entries(message).map(([k, v]) => [k, swap(v)]))]));
219
+ return { codemap: shared, pages };
220
+ }
221
+ // @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."
222
+ export function renderDashboard(data, threatModelHtml, store = null) {
223
+ const template = readFileSync(join(templatesDir(), 'dashboard', 'dashboard.html'), 'utf8');
224
+ // One pass over the template, so text inside either value that looks like a placeholder is never filled in turn.
225
+ // The pages' script and stylesheet travel only with a page that has graph answers to draw.
226
+ const asset = (name) => (store ? readFileSync(join(templatesDir(), 'dashboard', name), 'utf8') : '');
227
+ const fill = {
228
+ DATA: () => data,
229
+ THREAT_MODEL: () => threatModelHtml ?? '',
230
+ CODEGRAPH: () => (store ? shareCodeMap(store) : null),
231
+ PAGES_JS: () => asset('codegraph-pages.js'),
232
+ PAGES_CSS: () => asset('codegraph-pages.css'),
233
+ };
234
+ return template.replace(/__BRAVOS_(DATA|THREAT_MODEL|CODEGRAPH|PAGES_JS|PAGES_CSS)__/g, (_m, which) => inert(fill[which]()));
235
+ }
236
+ // @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."
237
+ export async function buildDashboard(root, env, opts = {}) {
238
+ // --since reaches git and guardlink as an argument, so a value that could be read as an option is refused first.
239
+ if (opts.since !== undefined && (opts.since.length === 0 || opts.since.startsWith('-') || /[\0\n]/.test(opts.since))) {
240
+ throw new BravosError(`bravos dashboard: --since needs a branch, tag or commit name (got "${opts.since}")`);
241
+ }
242
+ const base = opts.since ?? baseRef(root, env);
243
+ const tm = buildThreatModel(root, env, { base, blame: opts.blame !== false });
244
+ const cg = await buildCodeGraph(root, env, { names: opts.blame !== false, refresh: opts.graphBuild !== false, onProgress: opts.onProgress });
245
+ let plan = null;
246
+ try {
247
+ const L = (await licenceLib());
248
+ plan = L.planLabel(L.status(env)).label;
249
+ }
250
+ catch {
251
+ /* the page carries no plan label */
252
+ }
253
+ const data = {
254
+ schema: 'bravos.dashboard/v1',
255
+ repo: repoName(root, env),
256
+ branch: git(root, env, ['rev-parse', '--abbrev-ref', 'HEAD']),
257
+ sha: git(root, env, ['rev-parse', '--short', 'HEAD']),
258
+ generatedAt: new Date().toISOString(),
259
+ version: version(),
260
+ plan,
261
+ threatModel: { state: tm.state, note: tm.note, blame: tm.blame, since: tm.since },
262
+ codeGraph: { state: cg.state, note: cg.note },
263
+ };
264
+ const page = renderDashboard(data, tm.html, cg.store);
265
+ let path;
266
+ if (opts.out) {
267
+ path = resolve(opts.out);
268
+ mkdirSync(dirname(path), { recursive: true });
269
+ }
270
+ else {
271
+ const dir = join(root, DASHBOARD_DIR);
272
+ mkdirSync(dir, { recursive: true });
273
+ const ignore = join(dir, '.gitignore');
274
+ if (!existsSync(ignore))
275
+ writeFileSync(ignore, '*\n');
276
+ path = join(root, DASHBOARD_PATH);
277
+ // Beside the page: what it was built from, so the session briefing can say when it has fallen behind.
278
+ const meta = { schema: 'bravos.dashboard-meta/v1', generatedAt: data.generatedAt, commit: git(root, env, ['rev-parse', 'HEAD']), branch: data.branch, threatModel: tm.state, codeGraph: cg.state };
279
+ writeFileSync(join(root, DASHBOARD_META), `${JSON.stringify(meta, null, 2)}\n`);
280
+ }
281
+ writeFileSync(path, page);
282
+ return { path, threatModel: { state: tm.state, note: tm.note }, codeGraph: { state: cg.state, note: cg.note } };
283
+ }
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. Run it again whenever you want the picture: it rebuilds from the code as it stands, rebuilding a code graph that is missing or behind first, and a saved page says when it is more than half a day old. --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,17 @@ 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. Rebuilt from
35
+ the code every time: a code graph that is missing or behind is rebuilt first
36
+ (--no-graph-build skips that), and the page says when it has grown old.
37
+ --no-open prints the path only, --no-blame leaves git names out, --out writes
38
+ elsewhere.
28
39
  watch [dir] A live view for a second terminal pane beside any agent: setup, open and
29
40
  confirmed exposures, the hypothesis ledger, what to test next, stale claims, the
30
41
  code graph's resolution and entry points, SAST, the branch, PRs and autopilot
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'));