@bugb-technologies/bravos 1.11.0 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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,7 @@ 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
12
  const TOOLS = [
13
13
  { name: 'guardlink', hint: 'bravos setup --tools -y installs a compatible GuardLink' },
14
14
  { name: 'cxg', hint: 'bravos setup --tools -y installs a compatible CXG' },
@@ -72,8 +72,45 @@ export function runDoctor(root, env = process.env) {
72
72
  codex: hookRegistered(join(root, '.codex', 'hooks.json'), 'PreToolUse', ALL_PRE_PR_COMMANDS),
73
73
  },
74
74
  theme: resolveTheme(env),
75
+ updates: readUpdates(env),
75
76
  };
76
77
  }
78
+ // @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."
79
+ function readUpdates(env) {
80
+ const installed = packageVersion();
81
+ if (env.BRAVOS_UPDATE_CHECK === 'off')
82
+ return { state: 'off', latest: null, checkedAt: null, installed };
83
+ try {
84
+ const d = JSON.parse(readFileSync(join(env.HOME || homedir(), '.bravos', 'update-check.json'), 'utf8'));
85
+ const at = typeof d?.checkedAt === 'string' && Number.isFinite(Date.parse(d.checkedAt)) ? d.checkedAt : null;
86
+ const latest = typeof d?.latest === 'string' && /^\d+(?:\.\d+){0,3}(?:-[A-Za-z0-9.]{1,20})?$/.test(d.latest) ? d.latest : null;
87
+ return at ? { state: 'checked', latest, checkedAt: at, installed } : { state: 'never', latest: null, checkedAt: null, installed };
88
+ }
89
+ catch {
90
+ return { state: 'never', latest: null, checkedAt: null, installed };
91
+ }
92
+ }
93
+ const newerVersion = (a, b) => {
94
+ const n = (v) => v.split('-')[0].split('.').map(Number);
95
+ const [x, y] = [n(a), n(b)];
96
+ for (let i = 0; i < Math.max(x.length, y.length); i++)
97
+ if ((x[i] ?? 0) !== (y[i] ?? 0))
98
+ return (x[i] ?? 0) > (y[i] ?? 0);
99
+ return !a.includes('-') && b.includes('-');
100
+ };
101
+ function updatesLine(u) {
102
+ if (u.state === 'off')
103
+ return 'updates off (BRAVOS_UPDATE_CHECK=off)';
104
+ if (u.state === 'never' || !u.checkedAt)
105
+ return 'updates never checked (the next session start checks, at most once a day)';
106
+ const hours = Math.max(0, Math.round((Date.now() - Date.parse(u.checkedAt)) / 3600000));
107
+ const when = hours < 1 ? 'within the hour' : hours < 48 ? `${hours} hours ago` : `${Math.round(hours / 24)} days ago`;
108
+ if (!u.latest)
109
+ return `updates checked ${when}; no answer from the registry yet`;
110
+ return newerVersion(u.latest, u.installed)
111
+ ? `updates bravos ${u.latest} is out (you have ${u.installed}, checked ${when}) — npm install -g @bugb-technologies/bravos`
112
+ : `updates up to date (${u.installed}; checked ${when})`;
113
+ }
77
114
  // @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
115
  // @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
116
  export function withLicence(r, plan, licensed) {
@@ -99,6 +136,7 @@ export function formatDoctor(r) {
99
136
  `autopilot claude: ${yn(r.autopilot.claude)} codex: ${yn(r.autopilot.codex)}${r.autopilot.claude || r.autopilot.codex ? '' : ' (opt-in: bravos setup --autopilot)'}`,
100
137
  `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
138
  ...(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'] : []),
139
+ ...(r.updates ? [updatesLine(r.updates)] : []),
102
140
  ...(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
141
  ].join('\n');
104
142
  }
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
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,18 @@
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.0
6
+
7
+ - **Bravos tells you when it is updated.**
8
+ - **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.
9
+ - **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.
10
+ - **After you install it:** the coach has the agent run `bravos setup` in the repository you are in, once.
11
+ - **Installing stays yours:** `npm install -g @bugb-technologies/bravos`. The agent never runs it.
12
+ - **Seeing and stopping it:** `bravos doctor` shows the last check. `BRAVOS_UPDATE_CHECK=off` stops it.
13
+ - **The record:** the answer is kept in `~/.bravos/update-check.json`, and only a version-shaped string from the registry is ever kept.
14
+ - **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`.
15
+ - **For scripts:** `bravos doctor --json` gains `updates` (`state`, `latest`, `checkedAt`, `installed`).
4
16
 
5
17
  ## 1.11.0
6
18
 
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,13 @@
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';
9
11
  import { readProving } from './proving.mjs';
10
12
  import { planLabel, planLine, status as licenceStatus } from './licence.mjs';
11
13
  import { readLicenceNote, refreshIfDue } from './refresh.mjs';
@@ -277,6 +279,9 @@ export function buildBriefing(inputs) {
277
279
  }
278
280
  const upkeep = upkeepLine(i.upkeep);
279
281
  if (upkeep) tail.push(upkeep);
282
+ // A newer Bravos published than the one installed (hooks/lib/update-check.mjs): the person installs it.
283
+ const update = updateLine(i.update, i.cli);
284
+ if (update) tail.push(update);
280
285
  // The portal's last refusal to renew this machine, until it is signed in again (a revocation) or renewed (a plan that ended).
281
286
  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
287
  // Skills the retired Python bravos left at user level: the agent must not follow them (hooks/lib/legacy-skills.mjs).
@@ -582,6 +587,9 @@ export async function collect(root, env, { deadlineMs = 20000, nextCount = 3 } =
582
587
  upkeep,
583
588
  // Read after the renewal above has run, so a refusal that just arrived is in it.
584
589
  licenceNote: readLicenceNote(env),
590
+ // The last daily update check (~/.bravos/update-check.json) and the installed CLI's version, both file reads.
591
+ update: readUpdate(env.HOME || homedir()),
592
+ cli: cliVersion(env),
585
593
  annotationMode: readAnnotationMode(root),
586
594
  // bravos on PATH: what its probe says (a graph for this commit or not); else codegraph-mcp on PATH means the MCP route.
587
595
  codegraph: graphState ?? (whichOnPath('codegraph-mcp', env) ? 'unknown' : 'unavailable'),
@@ -867,6 +875,7 @@ function bannerWarnings(i, plan) {
867
875
  // One line for old Python skills at user level; bravos doctor prints the command that moves them aside.
868
876
  const old = arr(i.legacy).reduce((n, f) => n + arr(f?.names).length, 0);
869
877
  if (old > 0) lines.push(`! ${old} old Python bravos skill${old === 1 ? '' : 's'} in your user folder · bravos doctor`);
878
+ 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
879
  return lines;
871
880
  }
872
881
 
@@ -996,7 +1005,8 @@ export function buildSummary(inputs, opts = {}) {
996
1005
  const plan = i.licence && typeof i.licence === 'object' && i.licence.state ? planLabel(i.licence) : null;
997
1006
  const trial = !plan || plan.licensed ? '' : i.licence.state === 'expired' ? ' · renew: bravos licence' : ' · Team trial: bravos account activate';
998
1007
  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}`;
1008
+ const update = i.update?.latest && i.cli && newer(i.update.latest, i.cli) ? ` · update: ${i.update.latest} (npm install -g @bugb-technologies/bravos)` : '';
1009
+ return `${head} · ${countsLine(i.guardlink ?? {})}\n${plan ? `plan ${plan.label} · ` : ''}intent ${i.intent?.status ?? 'unknown'} · skills: ${next}\n${third}${update}`;
1000
1010
  }
1001
1011
 
1002
1012
  // 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`
@@ -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.0",
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",