@bugb-technologies/bravos 1.11.0 → 1.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/doctor.js CHANGED
@@ -1,4 +1,4 @@
1
- import { existsSync, readdirSync } from 'node:fs';
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
2
  import { homedir } from 'node:os';
3
3
  import { join } from 'node:path';
4
4
  import { installedGuardlinkSkills, whichBin } from './guardlink.js';
@@ -8,7 +8,8 @@ import { ALL_AUTOPILOT_COMMANDS, ALL_COACH_COMMANDS, ALL_PRE_PR_COMMANDS, HOOK_C
8
8
  import { skillsRoot } from './skills.js';
9
9
  import { resolveTheme } from './palette.js';
10
10
  import { pathToFileURL } from 'node:url';
11
- import { hooksDir } from './paths.js';
11
+ import { hooksDir, version as packageVersion } from './paths.js';
12
+ import { cargoPathFix, findTool } from './tool-path.js';
12
13
  const TOOLS = [
13
14
  { name: 'guardlink', hint: 'bravos setup --tools -y installs a compatible GuardLink' },
14
15
  { name: 'cxg', hint: 'bravos setup --tools -y installs a compatible CXG' },
@@ -44,6 +45,13 @@ function guardlinkSkills(root, harness) {
44
45
  export function runDoctor(root, env = process.env) {
45
46
  const tools = TOOLS.map(({ name, hint }) => {
46
47
  // codegraph-mcp and bravos-cli also count when they sit inside the bravos install (bravos uses them from there).
48
+ // guardlink and cxg also count when they sit outside PATH (cxg in cargo's folder): Bravos runs them by full path and says how to fix PATH.
49
+ if (name === 'guardlink' || name === 'cxg') {
50
+ const t = findTool(name, env);
51
+ if (!t)
52
+ return { name, found: false, hint };
53
+ return t.onPath ? { name, found: true, path: t.path, hint, onPath: true } : { name, found: true, path: t.path, hint, onPath: false, fix: cargoPathFix(env) };
54
+ }
47
55
  const path = name === 'codegraph-mcp' ? graphBin('codegraph-mcp', env) : name === 'bravos-cli' ? findAnalyzer(env) : whichBin(name, env);
48
56
  return path ? { name, found: true, path, hint } : { name, found: false, hint };
49
57
  });
@@ -72,8 +80,45 @@ export function runDoctor(root, env = process.env) {
72
80
  codex: hookRegistered(join(root, '.codex', 'hooks.json'), 'PreToolUse', ALL_PRE_PR_COMMANDS),
73
81
  },
74
82
  theme: resolveTheme(env),
83
+ updates: readUpdates(env),
75
84
  };
76
85
  }
86
+ // @comment -- "What the daily update check last saw (~/.bravos/update-check.json, written by hooks/lib/update-check.mjs): off, never checked, or the latest published version and when it was checked. Only a dotted version string is read from the file."
87
+ function readUpdates(env) {
88
+ const installed = packageVersion();
89
+ if (env.BRAVOS_UPDATE_CHECK === 'off')
90
+ return { state: 'off', latest: null, checkedAt: null, installed };
91
+ try {
92
+ const d = JSON.parse(readFileSync(join(env.HOME || homedir(), '.bravos', 'update-check.json'), 'utf8'));
93
+ const at = typeof d?.checkedAt === 'string' && Number.isFinite(Date.parse(d.checkedAt)) ? d.checkedAt : null;
94
+ const latest = typeof d?.latest === 'string' && /^\d+(?:\.\d+){0,3}(?:-[A-Za-z0-9.]{1,20})?$/.test(d.latest) ? d.latest : null;
95
+ return at ? { state: 'checked', latest, checkedAt: at, installed } : { state: 'never', latest: null, checkedAt: null, installed };
96
+ }
97
+ catch {
98
+ return { state: 'never', latest: null, checkedAt: null, installed };
99
+ }
100
+ }
101
+ const newerVersion = (a, b) => {
102
+ const n = (v) => v.split('-')[0].split('.').map(Number);
103
+ const [x, y] = [n(a), n(b)];
104
+ for (let i = 0; i < Math.max(x.length, y.length); i++)
105
+ if ((x[i] ?? 0) !== (y[i] ?? 0))
106
+ return (x[i] ?? 0) > (y[i] ?? 0);
107
+ return !a.includes('-') && b.includes('-');
108
+ };
109
+ function updatesLine(u) {
110
+ if (u.state === 'off')
111
+ return 'updates off (BRAVOS_UPDATE_CHECK=off)';
112
+ if (u.state === 'never' || !u.checkedAt)
113
+ return 'updates never checked (the next session start checks, at most once a day)';
114
+ const hours = Math.max(0, Math.round((Date.now() - Date.parse(u.checkedAt)) / 3600000));
115
+ const when = hours < 1 ? 'within the hour' : hours < 48 ? `${hours} hours ago` : `${Math.round(hours / 24)} days ago`;
116
+ if (!u.latest)
117
+ return `updates checked ${when}; no answer from the registry yet`;
118
+ return newerVersion(u.latest, u.installed)
119
+ ? `updates bravos ${u.latest} is out (you have ${u.installed}, checked ${when}) — npm install -g @bugb-technologies/bravos`
120
+ : `updates up to date (${u.installed}; checked ${when})`;
121
+ }
77
122
  // @comment -- "Renders a DoctorReport as one line per check, with an install hint for each missing tool and guardlink's playbook skills named per root."
78
123
  // @comment -- "Adds the verified licence status (plan line, licensed) to a report built synchronously; the verifier lives in the hook library, which the CLI loads asynchronously."
79
124
  export function withLicence(r, plan, licensed) {
@@ -89,7 +134,7 @@ export function formatDoctor(r) {
89
134
  const yn = (b) => (b ? 'yes' : 'no');
90
135
  const names = (l) => (l.length ? l.join(', ') : 'none');
91
136
  return [
92
- ...r.tools.map((t) => (t.found ? `✔ ${t.name} ${t.path}` : `✘ ${t.name} ${t.hint}`)),
137
+ ...r.tools.map((t) => (t.found ? `✔ ${t.name} ${t.path}${t.onPath === false ? ` (installed, but its folder is not on PATH here; Bravos runs it by this path. To fix PATH: ${t.fix})` : ''}` : `✘ ${t.name} ${t.hint}`)),
93
138
  r.licence.plan ? `${r.licence.licensed ? '✔' : '✘'} licence ${r.licence.plan}` : r.licence.present ? `✔ licence ${r.licence.source}` : '✘ licence not found — Free (researcher) plan; bravos account activate starts a 30-day Team trial',
94
139
  r.guardlink_initialised ? '✔ guardlink initialised (.guardlink/)' : '✘ guardlink not initialised — run bravos setup',
95
140
  `skills claude: ${r.skills.claude.length} agents: ${r.skills.agents.length}`,
@@ -99,6 +144,7 @@ export function formatDoctor(r) {
99
144
  `autopilot claude: ${yn(r.autopilot.claude)} codex: ${yn(r.autopilot.codex)}${r.autopilot.claude || r.autopilot.codex ? '' : ' (opt-in: bravos setup --autopilot)'}`,
100
145
  `coach claude: ${yn(r.coach.claude)} codex: ${yn(r.coach.codex)}${r.coach.claude || r.coach.codex ? (process.env.BRAVOS_COACH === 'off' ? ' (off for this run: BRAVOS_COACH=off)' : '') : ' (bravos setup adds it)'}`,
101
146
  ...(r.legacy_skills?.length ? [`✘ old Python bravos skills ${r.legacy_skills.map((f) => `${f.root}: ${f.names.join(', ')}`).join('; ')} — your agent may load them instead of this repository's. Move them aside (reversible): ${r.legacy_command}`] : r.legacy_skills ? ['✔ no old Python bravos skills at user level'] : []),
147
+ ...(r.updates ? [updatesLine(r.updates)] : []),
102
148
  ...(r.theme ? [`colours ${r.theme.theme} (${r.theme.source})${r.theme.source.startsWith('default') ? ' — pick yours: BRAVOS_THEME=light or dark, or bravos setup' : ''}`] : []),
103
149
  ].join('\n');
104
150
  }
package/dist/guide.js CHANGED
@@ -116,6 +116,7 @@ export const GUIDE_TOPICS = [
116
116
  { name: 'Start from your design documents', skills: ['bravos-context'], body: ['Give bravos-context your PRDs, design documents or an earlier threat model, as files or links. Each is kept in the repository as Markdown under .bravos/context/ (bravos context add; committed, so the team can keep it current) after a check for secrets and local paths; a link is kept beside its snapshot. Every rule then names the document it came from (INV-4, source: SRC-2), including who may do what: "sales may see every report except the revenue report" becomes a rule that can be tested, where a scan would see nothing wrong. bravos context list shows the documents, bravos context check re-checks them, and a pre-push check stops a push that would send a secret in one. Free; the CLI runs no model and fetches nothing: your agent converts and fetches with your own access.'] },
117
117
  { name: 'See which design rules hold', skills: ['bravos', 'bravos-recheck'], body: ['bravos rules lists every rule your design states (INV-n in the intent) with its status: broken (a test got through), retest due (the code under it changed since it was tested), unguarded (it can break somewhere and nothing stops it), guarded but untested, not placed (no code is tied to it yet), or holds (a test tried and was refused everywhere it is enforced). Each line names the document the rule came from and the places it is enforced. bravos dashboard shows the same as its Design rules tab, worst first, beside GuardLink\'s threat model. Free, read-only, no model; --json prints bravos.rules/v1. On the Team plan the pre-PR check and the PR workflow hold a pull request that changes a file a holding rule is enforced in (the check, or the role table that grants the permission) after that rule was last tested, until its test is replayed or the PR body names the rule; the after-edit note says the same while you work.'] },
118
118
  { name: 'The intake asks, it never blocks', skills: ['bravos-context', 'bravos-annotate'], body: ['Annotation starts in the first session. With no confirmed intent, the agent drafts what the product is for from the README, docs and code (.guardlink/intent.md, every item marked draft), annotates against that draft, and opens the intake page without waiting. Each session asks once for a person to confirm it (bravos review intent, a few minutes) until someone confirms or declines; the agent never confirms for you. Rules drafted from the design are tested and can block a pull request right away; bravos rules and the block message label them draft until a person confirms them. When the answers arrive, the agent re-judges what they changed: an item you mark intended by design is annotated as intended, not as a finding. A team that chooses to go without records that under a name, bravos context decline --by "<name>", which is committed like the intent and ends the asking; a coding agent is told never to decline for you. bravos context gate says which state a repository is in.'] },
119
+ { name: 'Updates', skills: ['bravos'], body: ['Bravos tells you when it is updated. At most once a day a session start asks the npm registry, in a background process the session never waits on, for the latest published version: the same request npm install makes, with only the package name. A newer version shows in the banner and the briefing, and the coach tells a session that is already running, once. Installing it is yours to do (npm install -g @bugb-technologies/bravos); once it is installed the coach has the agent run bravos setup in the repository, which brings its Bravos files up to date. bravos doctor shows the last check. BRAVOS_UPDATE_CHECK=off stops the check, and it never runs in CI.'] },
119
120
  { name: 'The coach', skills: ['bravos'], body: ['Bravos does not wait to be asked. Before each prompt a fast hook (it runs no guardlink and no network) may add one line for the agent. A question about issues, threats, vulnerabilities, findings or risks builds the dashboard while the agent answers, and opens it in your browser the first time in a session; later questions rebuild it and give the path. From the second prompt on it reminds, each topic once a session and at most one per prompt: claims waiting to be confirmed, with the next step (bravos-env to set up a target, where you type the authorization, then bravos-prove); how much of the code the threat model covers, with the next round; and a dashboard that is older than the model. Skills end every round the same way. bravos watch lists each reminder. BRAVOS_COACH=off turns it off for one run, and bravos prefs set coach off --by "<your name>" for this clone.'] },
120
121
  { name: 'Background annotation', skills: ['bravos-annotate'], body: ['While coverage is under 100%, each new session asks the agent to start one annotation pass in a background subagent (one slice at the default budget) beside whatever you asked, and to tell you in one line. It writes annotations only, never code; it commits only as your commits answer allows (bravos prefs set commits), and otherwise leaves its files for you; it reports the files it covered and the coverage change in one line. It does not run again on resume or compact, nor in CI, where the nightly annotates. bravos prefs set annotate off --by "<your name>" switches it off for this clone (background turns it back on), and BRAVOS_AUTO_ANNOTATE=off for one run. In a harness without subagents the agent offers the pass instead.'] },
121
122
  { name: 'Threat-model someone else\'s project', skills: ['bravos-context', 'bravos-annotate'], body: ['bravos-context assumes you are researching software you do not own (an open-source project, a vendor\'s code): it drafts the intent from upstream\'s own docs with links and asks only the scope decisions — which configuration to rate against (shipped defaults or the hardened setup upstream recommends), single organisation or multi-tenant, which attackers are in scope, and the intended-looking behaviours upstream does not document. intent.md records them as Assumptions, and severities are rated against them. Say "this is our product" for the owner interview instead.'] },
package/dist/help.js CHANGED
@@ -181,6 +181,13 @@ The coach
181
181
  model covers, and a dashboard older than the model. bravos watch shows each reminder.
182
182
  BRAVOS_COACH=off for one run; bravos prefs set coach off --by "<your name>" for this clone.
183
183
 
184
+ Updates
185
+ At most once a day a session start asks the npm registry, in the background, for the latest
186
+ Bravos (only the package name is sent; never in CI). A newer one shows in the banner and the
187
+ briefing, and the coach tells a session that is already running. After you install it, the
188
+ coach has the agent run bravos setup in the repository. bravos doctor shows the last check.
189
+ BRAVOS_UPDATE_CHECK=off stops the check.
190
+
184
191
  Session start
185
192
  One hook run returns two things. The briefing (counts, FIX NOW, what to test next, stale
186
193
  claims, tickets, intent) goes to the model on every start, resume, clear and compact. On a
@@ -23,27 +23,9 @@ const prerequisites = {
23
23
  tar: 'install tar for the pinned GuardLink grammar build',
24
24
  cargo: 'install the Rust toolchain (cargo and rustc) and a native linker',
25
25
  };
26
- // @comment -- "Where cargo puts what it installs (CARGO_INSTALL_ROOT, else CARGO_HOME, else ~/.cargo, then /bin), and whether that folder is on PATH. A cargo from Homebrew or a package manager runs fine while that folder is missing from PATH, so cxg builds for minutes and then nothing can find it; setup checks first and says the one line to add."
27
- export function cargoBinDir(env) {
28
- const root = env.CARGO_INSTALL_ROOT || env.CARGO_HOME || (env.HOME ? join(env.HOME, '.cargo') : null);
29
- return root ? join(isAbsolute(root) ? root : resolve(root), 'bin') : null;
30
- }
31
- export function cargoBinOnPath(env) {
32
- const dir = cargoBinDir(env);
33
- if (!dir)
34
- return true;
35
- return (env.PATH ?? '').split(delimiter).some((p) => p && resolve(p) === dir);
36
- }
37
- /** The line that puts cargo's folder on PATH, for the person's own shell profile. */
38
- export function cargoPathFix(env) {
39
- const dir = cargoBinDir(env) ?? '~/.cargo/bin';
40
- const shown = env.HOME && dir.startsWith(env.HOME + '/') ? `$HOME${dir.slice(env.HOME.length)}` : dir;
41
- const shell = (env.SHELL ?? '').split('/').pop();
42
- const profile = shell === 'zsh' ? '~/.zshrc' : shell === 'bash' ? '~/.bash_profile' : shell === 'fish' ? null : '~/.profile';
43
- return profile
44
- ? `echo 'export PATH="${shown}:$PATH"' >> ${profile}, then open a new terminal`
45
- : `fish_add_path ${shown}, then open a new terminal`;
46
- }
26
+ // The cargo folder helpers live in tool-path.ts, shared with doctor and the proof tools; re-exported here for existing callers.
27
+ export { cargoBinDir, cargoBinOnPath, cargoPathFix } from './tool-path.js';
28
+ import { cargoBinDir, cargoBinOnPath, cargoPathFix } from './tool-path.js';
47
29
  // @comment -- "Use fixed package-manager argv in a private scratch directory, outside the customer repository. Ignore inherited Git working-tree overrides and relative PATH entries, so the checkout cannot supply a .cargo/config.toml, .npmrc, Git config or executable for the install."
48
30
  export function installProofTool(name, env, echo, pins = PROOF_TOOL_PINS) {
49
31
  const pin = pins[name];
@@ -1,15 +1,17 @@
1
1
  import { spawnSync } from 'node:child_process';
2
2
  import { resolve } from 'node:path';
3
- import { whichBin } from './guardlink.js';
3
+ import { findTool, withToolDir } from './tool-path.js';
4
4
  // @comment -- "Checks the CLI interface in the executable that will run. Release and development binaries can have identical version strings. Only fixed help arguments are passed, with no shell, bounded output and a deadline (10 s: a cold start on a busy machine can take several); no URL, credentials or template is supplied."
5
5
  export function checkProofTool(name, env, timeoutMs = 10000) {
6
6
  const guardlink = name === 'guardlink';
7
7
  const capability = guardlink ? 'in-session probe translation' : 'plain scan of supplied JS probes with zero model calls';
8
- const binary = whichBin(name, env);
8
+ // Found on PATH or, for cxg, in cargo's folder off PATH: it is checked, and later run, by its full path.
9
+ const found = findTool(name, env);
10
+ const binary = found?.path;
9
11
  if (!binary)
10
12
  return { name, capability, status: 'missing' };
11
13
  const args = guardlink ? ['translate', '--help'] : ['--disable-update-check', 'scan', '--help'];
12
- const help = spawnSync(resolve(binary), args, { env, encoding: 'utf8', timeout: timeoutMs, maxBuffer: 512 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
14
+ const help = spawnSync(resolve(binary), args, { env: withToolDir(env, found), encoding: 'utf8', timeout: timeoutMs, maxBuffer: 512 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
13
15
  if (help.error || help.status !== 0)
14
16
  return { name, capability, status: 'unavailable' };
15
17
  const flags = guardlink ? ['--stdout', '--contract', '--threat'] : ['--no-author', '--templates', '--scope-file', '--auth-dir', '--session-dir'];
@@ -2,6 +2,7 @@ import { spawnSync } from 'node:child_process';
2
2
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
3
  import { basename, join, relative } from 'node:path';
4
4
  import { graphBin } from '../codegraph.js';
5
+ import { findTool } from '../tool-path.js';
5
6
  import { version } from '../paths.js';
6
7
  import { graphDetail, lib, parseJson, runner } from '../watch.js';
7
8
  import { readRuns } from './runs.js';
@@ -45,7 +46,7 @@ export async function gatherEvidence(root, env, opts) {
45
46
  run('guardlink', ['hypothesis', 'list', '--json', '.'], o),
46
47
  run('guardlink', ['hypothesis', 'boundaries', '--json', '.'], o),
47
48
  run('guardlink', ['--version'], quick),
48
- run('cxg', ['--version'], quick),
49
+ run(findTool('cxg', env)?.path ?? 'cxg', ['--version'], quick),
49
50
  (() => { const b = graphBin('codegraph-build', env); return b ? run(b, ['--version'], quick) : Promise.resolve(null); })(),
50
51
  opts.graph === false ? Promise.resolve(null) : graphDetail(root, env),
51
52
  ]);
@@ -0,0 +1,58 @@
1
+ // @comment -- "Where Bravos finds the tools it runs when they are not on PATH. cxg is built by cargo into cargo's own folder (CARGO_INSTALL_ROOT, else CARGO_HOME, else ~/.cargo, then /bin). A cargo from Homebrew or a package manager runs fine while that folder is missing from PATH, and a session started from a desktop app or a non-interactive shell often has a shorter PATH than the person's terminal, so 'not on PATH' must not read as 'not installed'. PATH lookups and file checks only; nothing is run."
2
+ import { accessSync, constants, statSync } from 'node:fs';
3
+ import { delimiter, isAbsolute, join, resolve } from 'node:path';
4
+ /** Where cargo puts what it installs, or null when there is no home to find it in. */
5
+ export function cargoBinDir(env) {
6
+ const root = env.CARGO_INSTALL_ROOT || env.CARGO_HOME || (env.HOME ? join(env.HOME, '.cargo') : null);
7
+ return root ? join(isAbsolute(root) ? root : resolve(root), 'bin') : null;
8
+ }
9
+ export function cargoBinOnPath(env) {
10
+ const dir = cargoBinDir(env);
11
+ if (!dir)
12
+ return true;
13
+ return (env.PATH ?? '').split(delimiter).some((p) => p && resolve(p) === dir);
14
+ }
15
+ // @comment -- "The line that puts cargo's folder on PATH, for the person's own shell profile. For zsh it is ~/.zshenv, which every zsh reads (a script, an agent's shell, a desktop app's), not ~/.zshrc, which only interactive terminals read: that difference is how a session ended up unable to see a cxg the terminal could run."
16
+ export function cargoPathFix(env) {
17
+ const dir = cargoBinDir(env) ?? '~/.cargo/bin';
18
+ const shown = env.HOME && dir.startsWith(env.HOME + '/') ? `$HOME${dir.slice(env.HOME.length)}` : dir;
19
+ const shell = (env.SHELL ?? '').split('/').pop();
20
+ const profile = shell === 'zsh' ? '~/.zshenv' : shell === 'bash' ? '~/.bash_profile' : shell === 'fish' ? null : '~/.profile';
21
+ return profile
22
+ ? `echo 'export PATH="${shown}:$PATH"' >> ${profile}, then open a new terminal`
23
+ : `fish_add_path ${shown}, then open a new terminal`;
24
+ }
25
+ const executable = (file) => {
26
+ try {
27
+ if (!statSync(file).isFile())
28
+ return false;
29
+ accessSync(file, constants.X_OK);
30
+ return true;
31
+ }
32
+ catch {
33
+ return false;
34
+ }
35
+ };
36
+ /** The folders a tool may sit in when PATH does not have it: cargo's, for cxg (cargo installs it there). Other tools are found on PATH only. */
37
+ export function fallbackDirs(name, env) {
38
+ const dir = name === 'cxg' ? cargoBinDir(env) : null;
39
+ return dir ? [dir] : [];
40
+ }
41
+ // @comment -- "Finds a tool: the first executable on PATH, else the first in its fallback folders. onPath says which, so a caller can run it by its full path and tell the person the one line that fixes their PATH. Null only when it is in neither."
42
+ export function findTool(name, env = process.env) {
43
+ for (const dir of (env.PATH ?? '').split(delimiter)) {
44
+ if (dir && executable(join(dir, name)))
45
+ return { path: join(dir, name), onPath: true, dir };
46
+ }
47
+ for (const dir of fallbackDirs(name, env)) {
48
+ if (executable(join(dir, name)))
49
+ return { path: join(dir, name), onPath: false, dir };
50
+ }
51
+ return null;
52
+ }
53
+ /** env with the tool's folder added to the end of PATH, so the tool and anything it starts can be found. */
54
+ export function withToolDir(env, found) {
55
+ if (!found || found.onPath)
56
+ return env;
57
+ return { ...env, PATH: [env.PATH, found.dir].filter(Boolean).join(delimiter) };
58
+ }
package/docs/GUIDE.md CHANGED
@@ -118,6 +118,12 @@ Skills: `/bravos-context` · `/bravos-annotate`
118
118
 
119
119
  Annotation starts in the first session. With no confirmed intent, the agent drafts what the product is for from the README, docs and code (.guardlink/intent.md, every item marked draft), annotates against that draft, and opens the intake page without waiting. Each session asks once for a person to confirm it (bravos review intent, a few minutes) until someone confirms or declines; the agent never confirms for you. Rules drafted from the design are tested and can block a pull request right away; bravos rules and the block message label them draft until a person confirms them. When the answers arrive, the agent re-judges what they changed: an item you mark intended by design is annotated as intended, not as a finding. A team that chooses to go without records that under a name, bravos context decline --by "<name>", which is committed like the intent and ends the asking; a coding agent is told never to decline for you. bravos context gate says which state a repository is in.
120
120
 
121
+ ### Updates
122
+
123
+ Skills: `/bravos`
124
+
125
+ Bravos tells you when it is updated. At most once a day a session start asks the npm registry, in a background process the session never waits on, for the latest published version: the same request npm install makes, with only the package name. A newer version shows in the banner and the briefing, and the coach tells a session that is already running, once. Installing it is yours to do (npm install -g @bugb-technologies/bravos); once it is installed the coach has the agent run bravos setup in the repository, which brings its Bravos files up to date. bravos doctor shows the last check. BRAVOS_UPDATE_CHECK=off stops the check, and it never runs in CI.
126
+
121
127
  ### The coach
122
128
 
123
129
  Skills: `/bravos`
package/docs/UPGRADING.md CHANGED
@@ -1,6 +1,28 @@
1
1
  # Upgrading Bravos
2
2
 
3
- After `npm install -g @bugb-technologies/bravos`, run **`bravos setup`** in a repository you work in: it brings this machine and that repository up to date. In repositories you work in with an agent you can skip even that: the agent runs it at the start of a session. The notes below say what else changes, newest first. (Before 1.9 the same was `bravos setup --tools -y` per machine and `bravos sync` per repository; both still work.)
3
+ After `npm install -g @bugb-technologies/bravos`, run **`bravos setup`** in a repository you work in: it brings this machine and that repository up to date. In repositories you work in with an agent you can skip even that: the agent runs it at the start of a session. From 1.12 on you do not have to watch for releases: Bravos tells you when a newer version is out, and after you install it the agent brings each repository up to date. The notes below say what else changes, newest first. (Before 1.9 the same was `bravos setup --tools -y` per machine and `bravos sync` per repository; both still work.)
4
+
5
+ ## 1.12.1
6
+
7
+ - **Bravos finds cxg when your PATH doesn't have it.** cargo installs cxg into its own folder (`~/.cargo/bin`, or `CARGO_HOME`/`CARGO_INSTALL_ROOT`). A session started from a desktop app or a non-interactive shell often lacks that folder on PATH, and Bravos used to read that as "cxg is not installed".
8
+ - Bravos now looks in cargo's folder too, and runs cxg from there by its full path.
9
+ - `bravos doctor` shows it as installed, with where it is and the line that fixes PATH.
10
+ - The session briefing tells the agent that cxg isn't missing and how to run it.
11
+ - In CI the replay runner still runs only the cxg the job put on PATH.
12
+ - **The PATH fix for zsh now goes in `~/.zshenv`,** which every zsh reads, including the shells agents and desktop apps start. `~/.zshrc` is read only by interactive terminals. To fix it once, run `echo 'export PATH="$HOME/.cargo/bin:$PATH"' >> ~/.zshenv`, then open a new terminal.
13
+ - **For scripts:** each tool entry in `bravos doctor --json` gains `onPath` (and `fix` when it is false).
14
+
15
+ ## 1.12.0
16
+
17
+ - **Bravos tells you when it is updated.**
18
+ - **The check:** at most once a day, a session start asks the npm registry for the latest version, in a background process the session never waits on. It is the same request `npm install` makes, and it sends only the package name. It never runs in CI.
19
+ - **Where it shows:** a newer version appears in the banner and the briefing ("Bravos X is out (you have Y)"). The coach also tells a session that is already running, once.
20
+ - **After you install it:** the coach has the agent run `bravos setup` in the repository you are in, once.
21
+ - **Installing stays yours:** `npm install -g @bugb-technologies/bravos`. The agent never runs it.
22
+ - **Seeing and stopping it:** `bravos doctor` shows the last check. `BRAVOS_UPDATE_CHECK=off` stops it.
23
+ - **The record:** the answer is kept in `~/.bravos/update-check.json`, and only a version-shaped string from the registry is ever kept.
24
+ - **This release itself is not announced automatically.** Anyone on 1.11.0 or older doesn't have the check yet, so tell them once to run `npm install -g @bugb-technologies/bravos`, then `bravos setup`.
25
+ - **For scripts:** `bravos doctor --json` gains `updates` (`state`, `latest`, `checkedAt`, `installed`).
4
26
 
5
27
  ## 1.11.0
6
28
 
package/hooks/coach.mjs CHANGED
@@ -1,11 +1,13 @@
1
1
  // @comment -- "bravos coach UserPromptSubmit hook entry (Claude Code and Codex): reads the prompt payload with a bounded wait, decides what to add for the agent (hooks/lib/coach.mjs) and prints it as additionalContext, logging each reminder for bravos watch. Never runs guardlink or the network. Silent when BRAVOS_COACH=off, when the person switched the coach off (bravos prefs set coach off), or when it is the plugin's copy in a repository that registers its own. Always exits 0; a failure adds nothing."
2
2
  import { realpathSync, readFileSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
3
4
  import { join } from 'node:path';
4
5
  import { spawnSync } from 'node:child_process';
5
6
  import { fileURLToPath } from 'node:url';
6
7
  import { coachTurn, newestModelChange, readCoach, writeCoach } from './lib/coach.mjs';
7
8
  import { gitCommonDir, readPrefs } from './lib/prefs.mjs';
8
9
  import { logWatchEvent } from './lib/snapshot.mjs';
10
+ import { cliVersion, readUpdate, repoVersion } from './lib/update-check.mjs';
9
11
 
10
12
  async function readPayload() {
11
13
  if (process.stdin.isTTY) return {};
@@ -68,7 +70,9 @@ async function main() {
68
70
  const harness = process.argv.includes('--harness') ? process.argv[process.argv.indexOf('--harness') + 1] : process.env.CLAUDE_PROJECT_DIR ? 'claude' : 'other';
69
71
  const record = readCoach(commonDir, payload.session_id) ?? { facts: { coverage: null, queued: 0, top: [], target: false, licensed: null, harness: harness === 'claude' ? 'claude' : 'other' }, raised: [], prompts: 0, opened: false };
70
72
  const dashboard = readDashboard(root);
71
- const r = coachTurn({ record, prompt: payload.prompt, dashboard, modelChangedAt: dashboard ? newestModelChange(root) : 0, head: dashboard?.commit ? git(root, ['rev-parse', 'HEAD']) : null });
73
+ // File reads only: the last daily update check, the installed CLI's version and the repository's.
74
+ const versions = { cli: cliVersion(process.env), repo: repoVersion(root), latest: readUpdate(process.env.HOME || homedir())?.latest ?? null };
75
+ const r = coachTurn({ record, prompt: payload.prompt, dashboard, modelChangedAt: dashboard ? newestModelChange(root) : 0, head: dashboard?.commit ? git(root, ['rev-parse', 'HEAD']) : null, versions });
72
76
  const { facts, ...rest } = r.record;
73
77
  writeCoach(commonDir, payload.session_id, { facts, ...rest });
74
78
  if (r.text) {
@@ -1,11 +1,14 @@
1
1
  // @comment -- "Pure text builder for the session-start briefing, collect() which gathers its read-only guardlink, git and gh facts concurrently under a shared deadline (and renews a signed-in machine's device licence when it is due, through refresh.mjs — the one write it makes, to $BRAVOS_HOME only), and the runJson/runJsonAsync spawn wrappers; dependency-free so it can be copied verbatim into target repos."
2
2
  import { spawn, spawnSync } from 'node:child_process';
3
3
  import { accessSync, constants, readFileSync } from 'node:fs';
4
+ import { homedir } from 'node:os';
4
5
  import { basename, delimiter, dirname, join } from 'node:path';
5
6
  import { contextGate, readContext } from './context.mjs';
6
7
  import { legacySkills, legacySkillsLine } from './legacy-skills.mjs';
7
8
  import { THEMES } from './palette.mjs';
8
9
  import { commitsLine, commonDirFrom, readHandoff, readPrefs } from './prefs.mjs';
10
+ import { cliVersion, newer, readUpdate, updateLine } from './update-check.mjs';
11
+ import { cxgPathLine, findTool } from './tool-path.mjs';
9
12
  import { readProving } from './proving.mjs';
10
13
  import { planLabel, planLine, status as licenceStatus } from './licence.mjs';
11
14
  import { readLicenceNote, refreshIfDue } from './refresh.mjs';
@@ -277,6 +280,11 @@ export function buildBriefing(inputs) {
277
280
  }
278
281
  const upkeep = upkeepLine(i.upkeep);
279
282
  if (upkeep) tail.push(upkeep);
283
+ // A newer Bravos published than the one installed (hooks/lib/update-check.mjs): the person installs it.
284
+ const update = updateLine(i.update, i.cli);
285
+ if (update) tail.push(update);
286
+ const cxgLine = cxgPathLine(i.cxg, { HOME: i.env?.HOME ?? process.env.HOME, SHELL: i.env?.SHELL ?? process.env.SHELL });
287
+ if (cxgLine) tail.push(cxgLine);
280
288
  // The portal's last refusal to renew this machine, until it is signed in again (a revocation) or renewed (a plan that ended).
281
289
  if (i.licenceNote && (i.licenceNote.outcome === 'lapsed' || i.licence?.licensed === false)) tail.push(`Licence: ${i.licenceNote.note} Tell the person once, in plain words.`);
282
290
  // Skills the retired Python bravos left at user level: the agent must not follow them (hooks/lib/legacy-skills.mjs).
@@ -582,6 +590,11 @@ export async function collect(root, env, { deadlineMs = 20000, nextCount = 3 } =
582
590
  upkeep,
583
591
  // Read after the renewal above has run, so a refusal that just arrived is in it.
584
592
  licenceNote: readLicenceNote(env),
593
+ // The last daily update check (~/.bravos/update-check.json) and the installed CLI's version, both file reads.
594
+ update: readUpdate(env.HOME || homedir()),
595
+ cli: cliVersion(env),
596
+ // Where cxg is, when it is installed: off PATH in this session is not missing (hooks/lib/tool-path.mjs).
597
+ cxg: findTool('cxg', { ...env, HOME: env.HOME || homedir() }),
585
598
  annotationMode: readAnnotationMode(root),
586
599
  // bravos on PATH: what its probe says (a graph for this commit or not); else codegraph-mcp on PATH means the MCP route.
587
600
  codegraph: graphState ?? (whichOnPath('codegraph-mcp', env) ? 'unknown' : 'unavailable'),
@@ -867,6 +880,7 @@ function bannerWarnings(i, plan) {
867
880
  // One line for old Python skills at user level; bravos doctor prints the command that moves them aside.
868
881
  const old = arr(i.legacy).reduce((n, f) => n + arr(f?.names).length, 0);
869
882
  if (old > 0) lines.push(`! ${old} old Python bravos skill${old === 1 ? '' : 's'} in your user folder · bravos doctor`);
883
+ if (i.update?.latest && i.cli && newer(i.update.latest, i.cli)) lines.push(`~ Update available: bravos ${i.update.latest} (you have ${i.cli}) · npm install -g @bugb-technologies/bravos`);
870
884
  return lines;
871
885
  }
872
886
 
@@ -996,7 +1010,8 @@ export function buildSummary(inputs, opts = {}) {
996
1010
  const plan = i.licence && typeof i.licence === 'object' && i.licence.state ? planLabel(i.licence) : null;
997
1011
  const trial = !plan || plan.licensed ? '' : i.licence.state === 'expired' ? ' · renew: bravos licence' : ' · Team trial: bravos account activate';
998
1012
  const third = (setup ? `setup ${setup.done}/${setup.total}${setup.next ? ` · next: ${setup.next.label} · bravos next` : ''} · bravos guide` : guide) + trial;
999
- return `${head} · ${countsLine(i.guardlink ?? {})}\n${plan ? `plan ${plan.label} · ` : ''}intent ${i.intent?.status ?? 'unknown'} · skills: ${next}\n${third}`;
1013
+ const update = i.update?.latest && i.cli && newer(i.update.latest, i.cli) ? ` · update: ${i.update.latest} (npm install -g @bugb-technologies/bravos)` : '';
1014
+ return `${head} · ${countsLine(i.guardlink ?? {})}\n${plan ? `plan ${plan.label} · ` : ''}intent ${i.intent?.status ?? 'unknown'} · skills: ${next}\n${third}${update}`;
1000
1015
  }
1001
1016
 
1002
1017
  // Brand palette by theme (hooks/lib/palette.mjs). Colour is truecolor ANSI, added after
@@ -1,10 +1,11 @@
1
- // @comment -- "bravos's coach: before each prompt, at most one dashboard instruction and one reminder for the agent, so Bravos steps up at the moments no skill is loaded. Facts come from a small per-session record the session hook writes under the clone's git directory (<git-common-dir>/bravos/coach/<session>.json), never from guardlink or the network, so the hook stays fast. Each topic is raised once per session; the first prompt gets no reminder (the briefing covers it). Dependency-free."
1
+ // @comment -- "bravos's coach: before each prompt, at most one dashboard instruction and one reminder for the agent, so Bravos steps up at the moments no skill is loaded. Facts come from a small per-session record the session hook writes under the clone's git directory (<git-common-dir>/bravos/coach/<session>.json), never from guardlink or the network, so the hook stays fast. Each topic is raised once per session; the first prompt gets no reminder (the briefing covers it). It also says, once, when a newer Bravos is out or was just installed, which reaches a session that is already running. Dependency-free."
2
2
  import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
+ import { newer } from './update-check.mjs';
4
5
 
5
6
  export const COACH_SCHEMA = 'bravos.coach/v1';
6
7
  /** The reminders, in the order they are given when several apply. */
7
- export const REMINDERS = ['confirm', 'coverage', 'dashboard-stale'];
8
+ export const REMINDERS = ['update-installed', 'confirm', 'coverage', 'update-available', 'dashboard-stale'];
8
9
 
9
10
  const SESSION_ID = /^[A-Za-z0-9._-]{1,128}$/;
10
11
 
@@ -106,7 +107,7 @@ export function newestModelChange(root, limit = 4000) {
106
107
  const where = (t) => `${t.threat}${t.asset ? ` on ${t.asset}` : ''}${t.file ? ` (${t.file}${t.line ? `:${t.line}` : ''})` : ''}`;
107
108
 
108
109
  // @comment -- "Decides what the coach says before one prompt. Returns the text for the agent (or '') and the record to keep. The dashboard instruction comes whenever the prompt asks about the security picture, opening the page only the first time in the session; then at most one reminder, never on the first prompt and never a topic already raised. Free-plan text names no Team step. Pure: the caller supplies the dashboard record and the newest model change."
109
- export function coachTurn({ record, prompt, dashboard = null, modelChangedAt = 0, head = null }) {
110
+ export function coachTurn({ record, prompt, dashboard = null, modelChangedAt = 0, head = null, versions = {} }) {
110
111
  if (!record?.facts) return { text: '', record, topics: [] };
111
112
  const f = record.facts;
112
113
  const k = (n) => (f.harness === 'claude' ? `/${n}` : n);
@@ -126,13 +127,20 @@ export function coachTurn({ record, prompt, dashboard = null, modelChangedAt = 0
126
127
  if (record.prompts > 0) {
127
128
  const cov = f.coverage;
128
129
  const stale = dashboard && Number.isFinite(dashboard.generatedAt) && (modelChangedAt > dashboard.generatedAt || (head && dashboard.commit && !head.startsWith(dashboard.commit) && !dashboard.commit.startsWith(head)));
130
+ const { cli = null, repo = null, latest = null } = versions;
129
131
  const due = {
132
+ 'update-installed': !!cli && !!repo && newer(cli, repo),
133
+ 'update-available': !!latest && !!cli && newer(latest, cli),
130
134
  confirm: f.queued > 0,
131
135
  coverage: !!cov && Number.isFinite(cov.percent) && cov.percent < 100,
132
136
  'dashboard-stale': !!stale && !topics.length,
133
137
  };
134
138
  const pick = REMINDERS.find((t) => due[t] && !raised.has(t));
135
- if (pick === 'confirm') {
139
+ if (pick === 'update-installed') {
140
+ lines.push(`Bravos reminder (once this session): Bravos was updated to ${cli}, and this repository's Bravos files are from ${repo}. Run \`bravos setup\` here now (from an agent it only brings Bravos's own files and bundles up to date) and say so in one line; the new hooks apply from the next prompt, new skills when next loaded.`);
141
+ } else if (pick === 'update-available') {
142
+ lines.push(`Bravos reminder (once this session): Bravos ${latest} is out (installed ${cli}). After answering, tell the person in one line: npm install -g @bugb-technologies/bravos in their own terminal. Never run it yourself.`);
143
+ } else if (pick === 'confirm') {
136
144
  const top = f.top.filter((t) => t.threat).map(where);
137
145
  const how = f.target
138
146
  ? `${k('bravos-prove')} can test them now on the recorded target`
@@ -1,5 +1,6 @@
1
1
  // @comment -- "Run one supplied, bound JavaScript probe per CXG process. Authority for target contact comes from the reviewed policy and scope; a kit controls neither. Only an engine verdict and an unchanged binding can update an exposure."
2
2
  import { createHash, randomUUID } from 'node:crypto';
3
+ import { findTool, withToolDir } from './tool-path.mjs';
3
4
  import { spawnSync } from 'node:child_process';
4
5
  import { closeSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readSync, readlinkSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
5
6
  import { createConnection } from 'node:net';
@@ -23,8 +24,19 @@ function localFile(root, name) {
23
24
  return file;
24
25
  }
25
26
 
27
+ // @comment -- "Runs a fixed command with no shell. cxg is found on PATH or, when the session's PATH lacks it, in cargo's folder (hooks/lib/tool-path.mjs), and run by that full path with its folder added to PATH, so 'not on PATH' never stops a replay of an installed cxg. In CI there is no fallback: only the job's own cxg on PATH runs."
28
+ // @mitigates #replay-ledger against #tool-tampering using #cache-isolation -- "invoke() looks outside PATH for cxg only off CI, so a CI replay runs only the cxg its own job installed"
26
29
  function invoke(command, args, cwd, opts = {}) {
27
- const result = spawnSync(command, args, { cwd, env: opts.env ?? sanitizedEnv(process.env), input: opts.input, encoding: 'utf8', timeout: opts.timeout ?? 120000,
30
+ let env = opts.env ?? sanitizedEnv(process.env);
31
+ if (command === 'cxg') {
32
+ // In CI only the cxg the job put on PATH runs: a binary left in a home folder by an earlier step is never picked up.
33
+ const found = findTool('cxg', { ...env, HOME: env.HOME ?? process.env.HOME }, { fallback: !(process.env.CI || process.env.GITHUB_ACTIONS) });
34
+ if (found) {
35
+ command = found.path;
36
+ env = withToolDir(env, found);
37
+ }
38
+ }
39
+ const result = spawnSync(command, args, { cwd, env, input: opts.input, encoding: 'utf8', timeout: opts.timeout ?? 120000,
28
40
  stdio: ['pipe', 'pipe', 'pipe'], maxBuffer: 64 * 1024 * 1024 });
29
41
  if (result.error || !(opts.allowed ?? [0]).includes(result.status)) {
30
42
  // Tool stderr can include provider bodies, session details or scan evidence.
@@ -0,0 +1,56 @@
1
+ // @comment -- "The hooks' copy of src/tool-path.ts (the hook scripts are installed apart from the CLI and cannot import it): finds a tool on PATH or, for cxg, in cargo's folder (CARGO_INSTALL_ROOT, else CARGO_HOME, else ~/.cargo, then /bin) so a session whose PATH is shorter than the person's terminal still runs cxg and is told how to fix PATH. File checks only; nothing is run. Dependency-free."
2
+ import { accessSync, constants, statSync } from 'node:fs';
3
+ import { delimiter, isAbsolute, join, resolve } from 'node:path';
4
+
5
+ export function cargoBinDir(env) {
6
+ const root = env.CARGO_INSTALL_ROOT || env.CARGO_HOME || (env.HOME ? join(env.HOME, '.cargo') : null);
7
+ return root ? join(isAbsolute(root) ? root : resolve(root), 'bin') : null;
8
+ }
9
+
10
+ const executable = (file) => {
11
+ try {
12
+ if (!statSync(file).isFile()) return false;
13
+ accessSync(file, constants.X_OK);
14
+ return true;
15
+ } catch {
16
+ return false;
17
+ }
18
+ };
19
+
20
+ // cargo's folder, for cxg: other tools are found on PATH only.
21
+ export function fallbackDirs(name, env) {
22
+ const dir = name === 'cxg' ? cargoBinDir(env) : null;
23
+ return dir ? [dir] : [];
24
+ }
25
+
26
+ // @comment -- "The first executable named name on PATH, else (unless fallback is false) in its fallback folders; { path, onPath, dir } or null."
27
+ export function findTool(name, env = process.env, { fallback = true } = {}) {
28
+ for (const dir of String(env.PATH ?? '').split(delimiter)) {
29
+ if (dir && executable(join(dir, name))) return { path: join(dir, name), onPath: true, dir };
30
+ }
31
+ if (!fallback) return null;
32
+ for (const dir of fallbackDirs(name, env)) {
33
+ if (executable(join(dir, name))) return { path: join(dir, name), onPath: false, dir };
34
+ }
35
+ return null;
36
+ }
37
+
38
+ /** env with the tool's folder added to the end of PATH, so the tool and what it starts are found. */
39
+ export function withToolDir(env, found) {
40
+ if (!found || found.onPath) return env;
41
+ return { ...env, PATH: [env.PATH, found.dir].filter(Boolean).join(delimiter) };
42
+ }
43
+
44
+ /** How to put the folder on PATH for good, in the person's own shell: ~/.zshenv for zsh, which every zsh reads. */
45
+ export function pathFix(dir, env) {
46
+ const shown = env.HOME && dir.startsWith(env.HOME + '/') ? `$HOME${dir.slice(env.HOME.length)}` : dir;
47
+ const shell = String(env.SHELL ?? '').split('/').pop();
48
+ if (shell === 'fish') return `fish_add_path ${shown}`;
49
+ return `echo 'export PATH="${shown}:$PATH"' >> ${shell === 'bash' ? '~/.bash_profile' : shell === 'zsh' ? '~/.zshenv' : '~/.profile'}`;
50
+ }
51
+
52
+ // @comment -- "The briefing's cxg line when cxg is installed but its folder is not on this session's PATH: run it by its full path (or put the folder in front of PATH for the command), never say it is not installed, and tell the person once the line that fixes their shell. Null when cxg is on PATH or not installed at all."
53
+ export function cxgPathLine(found, env) {
54
+ if (!found || found.onPath) return null;
55
+ return `cxg: installed at ${found.path}, but its folder is not on PATH in this session. It is not missing: run it as ${found.path} (or start the command with PATH="${found.dir}:$PATH"), and tell the person once that ${pathFix(found.dir, env)} makes every new session find it.`;
56
+ }
@@ -0,0 +1,138 @@
1
+ // @comment -- "Tells people when a newer Bravos is published. At most once a day the session hook starts a detached fetch of the latest version from the npm registry (the request npm install itself makes; nothing about the person or the repository is sent) and keeps the answer in ~/.bravos/update-check.json. The briefing, the banner and the coach read that file, and the installed CLI's and the repository's versions, with file reads only. Dependency-free; off with BRAVOS_UPDATE_CHECK=off and in CI."
2
+ import { spawn } from 'node:child_process';
3
+ import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs';
4
+ import { homedir } from 'node:os';
5
+ import { delimiter, dirname, join } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ export const UPDATE_SCHEMA = 'bravos.update-check/v1';
9
+ export const PACKAGE = '@bugb-technologies/bravos';
10
+ export const REGISTRY_URL = 'https://registry.npmjs.org/@bugb-technologies%2fbravos/latest';
11
+ export const CHECK_EVERY_MS = 24 * 3600 * 1000;
12
+ const VERSION_RE = /^\d+(?:\.\d+){0,3}(?:-[A-Za-z0-9.]{1,20})?$/;
13
+ const MAX_BODY = 256 * 1024;
14
+
15
+ export const updateFile = (home) => join(home, '.bravos', 'update-check.json');
16
+ const homeOf = (env) => env?.HOME || homedir();
17
+ export const isVersion = (v) => typeof v === 'string' && VERSION_RE.test(v);
18
+
19
+ // @comment -- "Whether version a is newer than b: dotted numbers compared in order; a prerelease is older than its release. False when either is not a version."
20
+ export function newer(a, b) {
21
+ if (!isVersion(a) || !isVersion(b)) return false;
22
+ const [an, ap] = a.split('-');
23
+ const [bn, bp] = b.split('-');
24
+ const x = an.split('.').map(Number);
25
+ const y = bn.split('.').map(Number);
26
+ for (let i = 0; i < Math.max(x.length, y.length); i++) {
27
+ const d = (x[i] ?? 0) - (y[i] ?? 0);
28
+ if (d) return d > 0;
29
+ }
30
+ if (ap && !bp) return false;
31
+ if (!ap && bp) return true;
32
+ return (ap ?? '') > (bp ?? '');
33
+ }
34
+
35
+ // @comment -- "Reads the record of the last check; anything that is not exactly the recorded shape, or a latest that is not a version, reads as none."
36
+ // @mitigates #update-notice against #forged-update-notice using #version-shape-only -- "Only a dotted version string from the record ever reaches the briefing or the coach."
37
+ export function readUpdate(home) {
38
+ try {
39
+ const d = JSON.parse(readFileSync(updateFile(home), 'utf8'));
40
+ if (!d || d.schema !== UPDATE_SCHEMA || !Number.isFinite(Date.parse(d.checkedAt))) return null;
41
+ return { latest: isVersion(d.latest) ? d.latest : null, checkedAt: Date.parse(d.checkedAt) };
42
+ } catch {
43
+ return null;
44
+ }
45
+ }
46
+
47
+ function writeUpdate(home, record) {
48
+ const file = updateFile(home);
49
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
50
+ const tmp = `${file}.tmp-${process.pid}`;
51
+ writeFileSync(tmp, JSON.stringify({ schema: UPDATE_SCHEMA, ...record }) + '\n', { mode: 0o600 });
52
+ renameSync(tmp, file);
53
+ }
54
+
55
+ // @comment -- "The installed CLI's version without starting it: find bravos on PATH, follow the link npm made, and read the version from the package.json named @bugb-technologies/bravos above it. Null when there is none."
56
+ export function cliVersion(env = process.env) {
57
+ for (const dir of String(env.PATH ?? '').split(delimiter).filter(Boolean)) {
58
+ const bin = join(dir, process.platform === 'win32' ? 'bravos.cmd' : 'bravos');
59
+ if (!existsSync(bin)) continue;
60
+ try {
61
+ let d = dirname(realpathSync(bin));
62
+ for (let i = 0; i < 6; i++) {
63
+ const pj = join(d, 'package.json');
64
+ if (existsSync(pj)) {
65
+ const j = JSON.parse(readFileSync(pj, 'utf8'));
66
+ if (j?.name === PACKAGE) return isVersion(j.version) ? j.version : null;
67
+ }
68
+ d = dirname(d);
69
+ }
70
+ } catch {
71
+ /* try the next */
72
+ }
73
+ return null;
74
+ }
75
+ return null;
76
+ }
77
+
78
+ // @comment -- "The Bravos version the repository's files were set up with: bravos_version in .bravos/skills.lock. Null when there is no lock."
79
+ export function repoVersion(root) {
80
+ try {
81
+ const v = JSON.parse(readFileSync(join(root, '.bravos', 'skills.lock'), 'utf8'))?.bravos_version;
82
+ return isVersion(v) ? v : null;
83
+ } catch {
84
+ return null;
85
+ }
86
+ }
87
+
88
+ // @comment -- "Starts the daily check, never waited on: nothing when it is off, in CI, or checked in the last day. It stamps the time first, so sessions starting together fetch once, then runs the fetch as a detached process that outlives the hook. Returns whether it started one."
89
+ export function checkUpdates({ env = process.env, now = Date.now() } = {}) {
90
+ try {
91
+ if (env.BRAVOS_UPDATE_CHECK === 'off' || env.CI || env.GITHUB_ACTIONS) return false;
92
+ const home = homeOf(env);
93
+ const last = readUpdate(home);
94
+ if (last && now - last.checkedAt < CHECK_EVERY_MS) return false;
95
+ writeUpdate(home, { latest: last?.latest ?? null, checkedAt: new Date(now).toISOString() });
96
+ const child = spawn(process.execPath, [fileURLToPath(import.meta.url), '--fetch'], { detached: true, stdio: 'ignore', env: { PATH: env.PATH ?? '', HOME: home, ...(env.BRAVOS_UPDATE_URL_FOR_TESTS ? { BRAVOS_UPDATE_URL_FOR_TESTS: env.BRAVOS_UPDATE_URL_FOR_TESTS } : {}) } });
97
+ child.unref();
98
+ return true;
99
+ } catch {
100
+ return false;
101
+ }
102
+ }
103
+
104
+ // @comment -- "The fetch itself: one GET for the package's latest dist-tag, 5 seconds at most and 256 KB at most, with a generic user agent and no other headers. Keeps the version only when it has a version's shape; any failure leaves the stamped record as it is. A test may point it at a local server (BRAVOS_UPDATE_URL_FOR_TESTS, loopback only)."
105
+ // @flows #npm-registry -> #update-notice via https -- "registry.npmjs.org answers the latest version of @bugb-technologies/bravos; only the version string is kept"
106
+ // @exposes #update-notice to #forged-update-notice [low] cwe:CWE-345 -- "fetchLatest() takes JSON.parse(text).version from the registry response, which the registry or a proxy in front of it controls, and writeUpdate() stores it for updateLine() and coachTurn() to put into the agent's context; nothing verifies the release is real, only isVersion() checks its shape"
107
+ // @mitigates #update-notice against #forged-update-notice using #version-shape-only -- "A value that is not a dotted version is dropped before it is written"
108
+ export async function fetchLatest({ env = process.env, now = Date.now() } = {}) {
109
+ const home = homeOf(env);
110
+ const test = env.BRAVOS_UPDATE_URL_FOR_TESTS;
111
+ const url = test && /^http:\/\/127\.0\.0\.1:\d+\//.test(test) ? test : REGISTRY_URL;
112
+ const ac = new AbortController();
113
+ const timer = setTimeout(() => ac.abort(), 5000);
114
+ try {
115
+ const res = await fetch(url, { headers: { accept: 'application/json', 'user-agent': 'bravos-update-check' }, signal: ac.signal, redirect: 'error' });
116
+ if (!res.ok) return null;
117
+ const text = await res.text();
118
+ if (text.length > MAX_BODY) return null;
119
+ const v = JSON.parse(text)?.version;
120
+ if (!isVersion(v)) return null;
121
+ writeUpdate(home, { latest: v, checkedAt: new Date(now).toISOString() });
122
+ return v;
123
+ } catch {
124
+ return null;
125
+ } finally {
126
+ clearTimeout(timer);
127
+ }
128
+ }
129
+
130
+ // @comment -- "The briefing's Update line, when the latest published version is newer than the installed CLI. The agent only tells the person; installing software is theirs to do."
131
+ export function updateLine(update, cli) {
132
+ if (!update?.latest || !cli || !newer(update.latest, cli)) return null;
133
+ return `Update: Bravos ${update.latest} is out (installed ${cli}) — tell the person once: npm install -g ${PACKAGE} in their own terminal, then bravos setup in each repository. Never run npm install -g yourself.`;
134
+ }
135
+
136
+ if (process.argv[2] === '--fetch' && fileURLToPath(import.meta.url) === realpathSync(process.argv[1] ?? '')) {
137
+ fetchLatest().finally(() => process.exit(0));
138
+ }
@@ -8,6 +8,7 @@ import { resolveTheme } from './lib/palette.mjs';
8
8
  import { startGraphBuild } from './lib/graph-autobuild.mjs';
9
9
  import { takeSnapshot } from './lib/snapshot.mjs';
10
10
  import { startCoach } from './lib/coach.mjs';
11
+ import { checkUpdates } from './lib/update-check.mjs';
11
12
  import { gitCommonDir } from './lib/prefs.mjs';
12
13
 
13
14
  const STDIN_WAIT_MS = 1000;
@@ -108,6 +109,8 @@ async function main() {
108
109
  inputs.source = source;
109
110
  // @comment -- "Leaves the facts the coach hook needs for this session (coverage, what waits to be tested, the target, the plan) under the git directory, so the per-prompt hook never runs guardlink. Skipped when the coach is switched off for the run; a resume or compact keeps what was already raised."
110
111
  if (env.BRAVOS_COACH !== 'off' && typeof payload.session_id === 'string') startCoach(gitCommonDir(root, env), payload.session_id, inputs);
112
+ // @comment -- "Starts the daily check for a newer Bravos in a detached process (hooks/lib/update-check.mjs); this session never waits on it, and the next prompt's coach or the next session reads its answer."
113
+ checkUpdates({ env });
111
114
  text = buildBriefing(inputs);
112
115
  if (env.BRAVOS_BANNER !== 'off' && (source === null || source === 'startup') && harness !== 'agy') {
113
116
  const version = readVersion(dirname(fileURLToPath(import.meta.url)));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bugb-technologies/bravos",
3
- "version": "1.11.0",
3
+ "version": "1.12.1",
4
4
  "description": "Skills pack and installer that make Claude Code and Codex power users of guardlink (threat-model-as-code) and cert-x-gen (pentest-as-code).",
5
5
  "keywords": [
6
6
  "security",
@@ -9,6 +9,7 @@ description: "Bring up a test target the user owns and prepare it for an authori
9
9
  - bravos-prove or bravos-recheck needs a running target and none is up.
10
10
  - The user asks to start the app for testing, seed test users, roles or orgs, or capture a login session.
11
11
  - A run was refused at pre-flight (cxg exit 4) or stopped on a dead session (exit 5).
12
+ - cxg looks missing: Before you say cxg is missing, check where it is: the briefing's `cxg:` line or `bravos doctor` names it when it is installed but its folder is not on this session's PATH (cxg lives in cargo's folder, `~/.cargo/bin`). Then it is not missing: run it by that full path, or start each command with `PATH="$HOME/.cargo/bin:$PATH"`, and tell the person once the line that fixes their shell. Only `bravos doctor` saying `✘ cxg` means it is not installed (`bravos setup --tools` installs it, with their go-ahead).
12
13
 
13
14
  ## Do
14
15
 
@@ -12,7 +12,7 @@ description: "Prove a new or changed GuardLink claim, or replay it after a fix,
12
12
 
13
13
  ## Do
14
14
 
15
- 1. Check the preconditions from bravos-env before any traffic: authorization for this run, a target that answers, `.guardlink/scope.yaml` committed, each profile passing `cxg pentest auth verify --profile <name>`, and for any non-loopback target both a reviewed scope and the human's authorization typed in this session. If one is missing, stop and hand back to bravos-env. Read the effort: the user's words ("at high"), else a `bravos effort: <level>` line in `AGENTS.md` / `CLAUDE.md`, else medium. It sets a starting budget, not a limit; go beyond it when the work needs it and say why in one line. Starting budget — low: replay a matching kit; medium: also author the first missing test in this session; high: include affected callers and controls; max: cover the testable in-scope queue. A higher effort does not authorize spending on an external model.
15
+ 1. Before you say cxg is missing, check where it is: the briefing's `cxg:` line or `bravos doctor` names it when it is installed but its folder is not on this session's PATH (cxg lives in cargo's folder, `~/.cargo/bin`). Then it is not missing: run it by that full path, or start each command with `PATH="$HOME/.cargo/bin:$PATH"`, and tell the person once the line that fixes their shell. Only `bravos doctor` saying `✘ cxg` means it is not installed (`bravos setup --tools` installs it, with their go-ahead). Check the preconditions from bravos-env before any traffic: authorization for this run, a target that answers, `.guardlink/scope.yaml` committed, each profile passing `cxg pentest auth verify --profile <name>`, and for any non-loopback target both a reviewed scope and the human's authorization typed in this session. If one is missing, stop and hand back to bravos-env. Read the effort: the user's words ("at high"), else a `bravos effort: <level>` line in `AGENTS.md` / `CLAUDE.md`, else medium. It sets a starting budget, not a limit; go beyond it when the work needs it and say why in one line. Starting budget — low: replay a matching kit; medium: also author the first missing test in this session; high: include affected callers and controls; max: cover the testable in-scope queue. A higher effort does not authorize spending on an external model.
16
16
  2. Order what to test, then read how the person wants proving handled. With the code graph (its MCP tools, or `bravos graph <question> --json` — same answers; see bravos-codegraph) (briefing `Code graph:` says `current`): `codegraph_untested_exposures` and `codegraph_untested_reach` rank untested exposures by reach; test the ones intent.md's Assumptions put in scope first, least privileged entry point first, and report exposures only an out-of-scope attacker reaches instead of running them. Without the graph, say "code graph unavailable; using guardlink hypothesis next order" and use that queue. Within that order, an exposure with a reachable SAST finding joined to it (`bravos sast candidates`) goes before one without, and its route goes into the run notes; with no SAST report or SAST unavailable, skip this. Then, for how the person wants proving handled: the briefing's `Proving:` line, from `.guardlink/proving.md`. If it is not set, ask them once, with a suggestion drawn from the repo (for example, "you have a docker-compose; I'd prove automatically on 127.0.0.1:8080"): prove automatically on their loopback target whenever new or changed exposures appear, ask each time, on a schedule (bravos-schedule's nightly), or not now. Record their answer in `.guardlink/proving.md`: lines `choice: auto|ask|schedule|none`, `target: <loopback url>`, `start: <start command>`, `generation: no` (Bravos never uses cxg's model generation), their words quoted verbatim, and `— confirmed by <their name>, <date>`. Before offering or following `auto`, check that `git symbolic-ref --quiet refs/remotes/origin/HEAD` names an existing commit. If missing, warn: fetch the default branch, then `git remote set-head origin --auto` (or `git remote set-head origin <branch>`); use `ask` meanwhile. Then follow it: `auto` proceeds on that target with their quoted words as the attestation; `ask` asks now; `schedule` hands to bravos-schedule; `none` stops here and says so. When they change their mind, rewrite the file with their new words.
17
17
  3. Read the affected claim from `guardlink hypothesis list --json`. Include a declared mitigation awaiting its first test and a previously confirmed claim now marked retest. Match its key to the logical source location in `guardlink sarif . --profile pentest -o whitebox/findings.sarif`; external annotations also have a physical declaration in a .gal file. Keep both locations. Record the tested source revision or worktree, application build, identity roles and intended oracle.
18
18
  4. For a web claim, use its bound JavaScript kit in .guardlink/cxg-replay/. For a missing or mismatched kit, follow bravos-templatize in this session. A matching kit exercises the intended operation and includes a positive control for a claimed defense. Validate the kit and review its scope. Honor the recorded kit policy and the person’s stated limits. An automatic reviewed-only policy requires identical bound test bytes on the default branch. On a clone whose upstream has no testing policy, use `ask` with locally committed policy and scope and typed authorization for loopback `run-once`. The earlier wizard’s “only replay tests I approved” choice retains that restriction.