@bugb-technologies/bravos 1.7.0 → 1.9.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/README.md +11 -7
- package/dist/ci.js +1 -1
- package/dist/cli.js +271 -111
- package/dist/codegraph.js +21 -0
- package/dist/context.js +1 -1
- package/dist/doctor.js +20 -11
- package/dist/global.js +3 -3
- package/dist/graphbin.js +2 -0
- package/dist/guardlink.js +1 -1
- package/dist/guide.js +12 -10
- package/dist/help.js +45 -19
- package/dist/hooks.js +44 -21
- package/dist/install.js +2 -1
- package/dist/lock.js +1 -0
- package/dist/mcp.js +21 -5
- package/dist/palette.js +2 -2
- package/dist/plugin-release.js +2 -2
- package/dist/plugin.js +3 -3
- package/dist/prefs.js +66 -0
- package/dist/review-wait.js +76 -0
- package/dist/setup-route.js +37 -0
- package/dist/setup.js +3 -2
- package/dist/skills.js +1 -1
- package/dist/start/answers.js +36 -7
- package/dist/start/index.js +190 -69
- package/dist/start/repos.js +1 -1
- package/dist/start/ui.js +2 -2
- package/dist/upkeep.js +89 -0
- package/dist/watch-frame.js +1 -1
- package/dist/watch.js +1 -1
- package/docs/GUIDE.md +23 -11
- package/docs/UPGRADING.md +43 -1
- package/hooks/lib/autopilot.mjs +3 -18
- package/hooks/lib/briefing.mjs +93 -14
- package/hooks/lib/graph-autobuild.mjs +131 -0
- package/hooks/lib/legacy-skills.mjs +68 -0
- package/hooks/lib/palette.mjs +4 -4
- package/hooks/lib/prefs.mjs +108 -0
- package/hooks/lib/refresh.mjs +45 -1
- package/hooks/lib/setup.mjs +8 -8
- package/hooks/lib/snapshot.mjs +19 -1
- package/hooks/session-start.mjs +7 -2
- package/package.json +1 -1
- package/skills/bravos/SKILL.md +5 -4
- package/skills/bravos-annotate/SKILL.md +4 -4
- package/skills/bravos-cicd/SKILL.md +1 -1
- package/skills/bravos-codegraph/SKILL.md +1 -1
- package/skills/bravos-context/SKILL.md +6 -6
- package/skills/bravos-env/SKILL.md +2 -2
- package/skills/bravos-env/scope.example.yaml +2 -1
- package/skills/bravos-prove/SKILL.md +2 -2
- package/skills/bravos-recheck/SKILL.md +1 -1
- package/skills/bravos-resync/SKILL.md +1 -1
- package/skills/bravos-schedule/SKILL.md +1 -1
- package/skills/bravos-ship/SKILL.md +3 -3
- package/skills/bravos-templatize/SKILL.md +1 -1
- package/templates/review/review.html +1 -1
package/docs/GUIDE.md
CHANGED
|
@@ -30,9 +30,9 @@ Every skill reads one dial: low, medium (default), high or max. Say it ("annotat
|
|
|
30
30
|
|
|
31
31
|
### Installing
|
|
32
32
|
|
|
33
|
-
npm install -g @bugb-technologies/bravos (Node 20 or newer), then bravos
|
|
33
|
+
npm install -g @bugb-technologies/bravos (Node 20 or newer), then bravos setup: a guided setup that asks one question at a time (colours, licence, tools, repository, AI tools, PR checks, a scheduled run, how testing is allowed), shows every change, and writes nothing until you choose Apply. Then open your agent and say anything: Bravos begins with what the app is for and goes on to your code once you confirm (where the agent runs no hooks, it tells you the one thing to type).
|
|
34
34
|
|
|
35
|
-
By hand instead: bravos account activate signs you in once in the browser and writes the licence — a 30-day Team trial when the account has no plan; skip it to stay on Free — bravos
|
|
35
|
+
By hand instead: bravos account activate signs you in once in the browser and writes the licence — a 30-day Team trial when the account has no plan; skip it to stay on Free — bravos setup --agent claude in a repository writes the skills, hooks and MCP wiring, bravos setup --analyzer --codegraph puts the analyzer and the code graph on the machine (Team plan), and guardlink and cxg come from bravos setup --tools -y, or npm and cargo by hand. If you used the Python bravos, rename its command so bravos means this one: mv ~/.local/bin/bravos ~/.local/bin/bravos-py (this CLI still finds its code graph and analyzer), or remove it with pipx or uv.
|
|
36
36
|
|
|
37
37
|
### Your first day
|
|
38
38
|
|
|
@@ -44,7 +44,7 @@ Keep bravos watch running in a second terminal pane beside your agent (free, rea
|
|
|
44
44
|
|
|
45
45
|
### Hands-off: autopilot
|
|
46
46
|
|
|
47
|
-
bravos
|
|
47
|
+
bravos setup --autopilot makes upkeep happen without anyone asking. At turn end the agent reviews changed code, including edits inside annotated files. It follows the recorded proving preference for affected claims. The pre-PR gate runs on every gh pr create.
|
|
48
48
|
|
|
49
49
|
Proving follows your choice, not a fixed rule: the first time it comes up the agent asks you once — prove automatically on your loopback target, ask each time, on a schedule, or not now — and records your words in .guardlink/proving.md. Say "ask me first" or "stop auto-proving" at any time to change it. Non-loopback targets still need a reviewed scope and your typed authorization every time.
|
|
50
50
|
|
|
@@ -70,7 +70,7 @@ Start by recording what the product intends (bravos-context), so severities refl
|
|
|
70
70
|
|
|
71
71
|
Skills: `/bravos-campaign` · `/bravos-schedule` · `/bravos-cicd`
|
|
72
72
|
|
|
73
|
-
Turn on bravos
|
|
73
|
+
Turn on bravos setup --autopilot so the threat model keeps up as people work, with no commands to remember, and settle once with the team how findings should be proven (it is recorded in .guardlink/proving.md and shows in every briefing).
|
|
74
74
|
|
|
75
75
|
Coverage and findings are visible to everyone from the repo itself. To raise coverage or clear the backlog, run bravos-campaign with a goal ("coverage 100%", "test every open exposure"): it plans disjoint batches, runs one subagent per batch, gates each, rests, and reports before-and-after numbers. Use bravos-schedule for recurring upkeep (an in-session loop or the nightly workflow) and bravos-cicd for the PR gate and code-scanning upload. Acceptances (@accepts) and entitlements are yours to write; agents never write them.
|
|
76
76
|
|
|
@@ -84,7 +84,7 @@ Run bravos first: it reads the briefing, explains the loop in five lines and rou
|
|
|
84
84
|
|
|
85
85
|
Skills: `/bravos-cicd` · `/bravos-schedule`
|
|
86
86
|
|
|
87
|
-
bravos
|
|
87
|
+
bravos setup --ci writes the PR gate and nightly workflows. bravos-cicd audits existing workflows: broken guardlink calls, script injection from pull-request text, missing SARIF upload. The Claude and Codex nightlies can replay committed, bound kits when scheduled testing is authorized. The Copilot job assigns an annotation task.
|
|
88
88
|
|
|
89
89
|
## What to do, by task
|
|
90
90
|
|
|
@@ -128,7 +128,7 @@ bravos-context assumes you are researching software you do not own (an open-sour
|
|
|
128
128
|
|
|
129
129
|
Skills: `/bravos-context`
|
|
130
130
|
|
|
131
|
-
bravos-context opens its questions as a bravos page (bravos review intent): pre-filled with bravos's suggestions and their sources; change what is wrong, make the calls marked 'needs your call' (Confirm stays off until you do), and the facts bravos drafted stay folded unless you open one to object. The role-by-action matrix links each documented permission to its question. In local reviews, open a cited SRC document to read its verified text. The saved HTML can contain these documents. Each person's answers save to .guardlink/intent-answers/<name>.json; teammates run bravos review intent after pulling and commit theirs. bravos review intent --summary shows where people agree and disagree; only what a named person agreed to is marked confirmed. On Claude Code, --share prepares an artifact with the draft and its citations. Publish that artifact to share it.
|
|
131
|
+
bravos-context opens its questions as a bravos page (bravos review intent): pre-filled with bravos's suggestions and their sources; change what is wrong, make the calls marked 'needs your call' (Confirm stays off until you do), and the facts bravos drafted stay folded unless you open one to object. The role-by-action matrix links each documented permission to its question. In local reviews, open a cited SRC document to read its verified text. The saved HTML can contain these documents. Each person's answers save to .guardlink/intent-answers/<name>.json; teammates run bravos review intent after pulling and commit theirs. Press Done when you are finished: the agent runs bravos review intent --wait and carries on by itself. bravos review intent --summary shows where people agree and disagree; only what a named person agreed to is marked confirmed. On Claude Code, --share prepares an artifact with the draft and its citations. Publish that artifact to share it.
|
|
132
132
|
|
|
133
133
|
### I wrote security-relevant code
|
|
134
134
|
|
|
@@ -170,7 +170,7 @@ The no-mistakes gate: validate, lint since the merge base, disclose new exposure
|
|
|
170
170
|
|
|
171
171
|
Skills: `/bravos-codegraph`
|
|
172
172
|
|
|
173
|
-
One bounded question to the code graph instead of grepping. Team plan: bravos setup --codegraph stages codegraph-mcp, then bravos graph build . indexes the repository. With it, other skills get sharper on their own: bravos-templatize targets the route and auth that actually reach each sink, bravos-recheck follows a fix's callers and blast radius into other files, bravos-context drafts the real public surface, and bravos-prove tests the most reachable exposures first. Without it they read the code and say so.
|
|
173
|
+
One bounded question to the code graph instead of grepping. Team plan: bravos setup --codegraph stages codegraph-mcp, then bravos graph build . indexes the repository. With it, other skills get sharper on their own: bravos-templatize targets the route and auth that actually reach each sink, bravos-recheck follows a fix's callers and blast radius into other files, bravos-context drafts the real public surface, and bravos-prove tests the most reachable exposures first. After each commit the graph is rebuilt for you: when a session starts and the commit has none, the session hook starts one quiet background build (no tokens; one at a time; never in CI; BRAVOS_GRAPH_AUTOBUILD=off turns it off). Without it they read the code and say so.
|
|
174
174
|
|
|
175
175
|
### Scan for dependency CVEs, secrets, IaC
|
|
176
176
|
|
|
@@ -202,6 +202,18 @@ Skills: `/bravos-annotate` · `/bravos-codegraph` · `/bravos-prove`
|
|
|
202
202
|
|
|
203
203
|
Clone the services side by side in one folder, then run bravos workspace create NAME --member ./gateway=gateway@http://127.0.0.1:8080 --member ./orders=orders@http://127.0.0.1:8081 (bravos workspace plus guardlink link-project plus bravos in each repo and in the shared folder). Work on a service from its own repo; ask questions that cross services from the shared folder, where the briefing and bravos watch show every service. Declare each call to another service as @flows #<this>-<x> -> #<other>-<y> via http (plain ids, not #repo.tag). Build the code graph over the shared folder so it links one service's client calls to another's handlers. bravos report data --workspace writes one report across the services.
|
|
204
204
|
|
|
205
|
+
### After updating bravos
|
|
206
|
+
|
|
207
|
+
Skills: `/bravos`
|
|
208
|
+
|
|
209
|
+
Nothing to run by hand in a repository you work in with an agent: at the start of a session bravos upkeep (read-only, no network) tells the agent what is behind the installed version, and the agent runs bravos setup, which brings the repository's skills and hooks and Bravos's own bundles up to date, without asking. If a teammate synced the repository with a newer bravos than yours, the agent syncs nothing and tells you to update. Installing guardlink and cxg (bravos setup --tools) still waits for your go-ahead.
|
|
210
|
+
|
|
211
|
+
### Stop being asked about commits
|
|
212
|
+
|
|
213
|
+
Skills: `/bravos`
|
|
214
|
+
|
|
215
|
+
Say once whether your agent commits the files Bravos writes (annotations, intent, definitions, tests): bravos prefs set commits commit|leave|ask --by "<your name>". bravos setup asks it too. The answer is kept in this clone's git directory, never committed, and your own code is never part of such a commit. bravos prefs get shows it.
|
|
216
|
+
|
|
205
217
|
### See the findings on one page
|
|
206
218
|
|
|
207
219
|
Skills: `/bravos`
|
|
@@ -234,7 +246,7 @@ Bounded questions to codegraph-mcp: routes, attack surface, sinks a symbol reach
|
|
|
234
246
|
|
|
235
247
|
### bravos-ship
|
|
236
248
|
|
|
237
|
-
The pre-PR gate. Optional PreToolUse hook (bravos
|
|
249
|
+
The pre-PR gate. Optional PreToolUse hook (bravos setup --pre-pr-hook) runs it on every gh pr create / gh pr ready.
|
|
238
250
|
|
|
239
251
|
### bravos-templatize
|
|
240
252
|
|
|
@@ -314,7 +326,7 @@ Never invented. Test users and sessions are seeded or captured for real, or the
|
|
|
314
326
|
|
|
315
327
|
### No hidden agents
|
|
316
328
|
|
|
317
|
-
The agent in your session does the work; bravos never spawns another agent CLI
|
|
329
|
+
The agent in your session does the work; bravos never spawns another agent CLI, and never uses cxg's model-API probe generation: the tests it runs are the ones written and reviewed in your session.
|
|
318
330
|
|
|
319
331
|
### Governance
|
|
320
332
|
|
|
@@ -352,10 +364,10 @@ Reads hooks from .claude/settings.json (preview), so the briefing can load there
|
|
|
352
364
|
|
|
353
365
|
### Every repo, or one copy of each skill
|
|
354
366
|
|
|
355
|
-
bravos
|
|
367
|
+
bravos setup --global installs for your user: skills in ~/.claude/skills (linked from ~/.agents/skills) and a user hook that briefs repos with a threat model but no bravos install. bravos setup --link-skills makes a repo's .agents/skills a link to .claude/skills, so tools that read both (Warp) list each skill once.
|
|
356
368
|
|
|
357
369
|
### Banner switches
|
|
358
370
|
|
|
359
371
|
BRAVOS_BANNER=off hides it; BRAVOS_BANNER_COLOR=off or NO_COLOR prints it plain. The briefing for the model is unchanged either way.
|
|
360
372
|
|
|
361
|
-
Light terminal? BRAVOS_THEME=light (or dark, or neutral) picks the colours for the banner and bravos watch; otherwise COLORFGBG, the choice saved by bravos
|
|
373
|
+
Light terminal? BRAVOS_THEME=light (or dark, or neutral) picks the colours for the banner and bravos watch; otherwise COLORFGBG, the choice saved by bravos setup, then neutral. bravos doctor shows which, and the c key in bravos watch switches.
|
package/docs/UPGRADING.md
CHANGED
|
@@ -1,6 +1,48 @@
|
|
|
1
1
|
# Upgrading Bravos
|
|
2
2
|
|
|
3
|
-
After `npm install -g @bugb-technologies/bravos`, run **`bravos setup
|
|
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.)
|
|
4
|
+
|
|
5
|
+
## 1.9.0
|
|
6
|
+
|
|
7
|
+
1.9 makes **`bravos setup`** the one command for setting Bravos up. It looks at this machine and the repository you are in and does only what is missing.
|
|
8
|
+
|
|
9
|
+
- **In a terminal, `bravos setup` is the guided setup.**
|
|
10
|
+
- The first time on a machine it signs you in and installs the tools, then asks about the repository.
|
|
11
|
+
- In another repository it skips what the machine has ("This machine is ready") and asks only that repository's questions.
|
|
12
|
+
- In a repository that already has Bravos it brings the machine and the repository up to date. `bravos setup --change` asks the repository's questions again.
|
|
13
|
+
- **`bravos start`, `bravos init` and `bravos sync` still work**, with the same flags, but help and every hint name `bravos setup`: `bravos sync --ci` is `bravos setup --ci`, `bravos init --agent claude` is `bravos setup --agent claude`, `bravos start --again` is `bravos setup --change`.
|
|
14
|
+
- **Two things behave differently under the name `setup`:**
|
|
15
|
+
- A plain `bravos setup` in a terminal opens the guided setup. It used to fetch the bundles; that is `bravos setup --analyzer --codegraph`.
|
|
16
|
+
- `bravos setup -y` on its own is an unattended first setup of the repository you are in. Fetching a staged bundle again is `bravos setup --codegraph -y` (or `--analyzer -y`).
|
|
17
|
+
- **With no terminal, a plain `bravos setup` is safe upkeep.** This is what an agent or a script gets: the repository's Bravos files and Bravos's own bundles brought up to date, and nothing else. It never installs Bravos into a repository, never installs guardlink or cxg, never adds agents or MCP entries, and leaves your own `~/.claude` alone. A bundle that is missing is named, not fetched.
|
|
18
|
+
- **`bravos setup --yes` is the unattended first setup.** It sets up the folder it is given or run in, refuses a folder that is not a git repository, and never picks one for you. It fetches Bravos's bundles and leaves guardlink and cxg to `bravos setup --tools -y`.
|
|
19
|
+
- **Any first install makes the agent begin.** Installing by flags or from a script now leaves the same hand-off the guided setup does, so the next agent session starts the context step by itself.
|
|
20
|
+
- **Fixed:** "Install guardlink, cxg when you apply?" defaulted to No; it defaults to Yes. A bundle older than this version uses is now offered for install in the guided setup.
|
|
21
|
+
- `bravos next` prints "Setup N/9 for <repo>".
|
|
22
|
+
|
|
23
|
+
## 1.8.1
|
|
24
|
+
|
|
25
|
+
- **Hooks work from any folder.** Until now the hook commands were relative to the current folder, so once your agent changed folder (`cd ios/Runner`) every hook failed with "Cannot find module": autopilot stopped, and the pre-PR check let `gh pr create` through. Claude Code's commands now start from the project root (`${CLAUDE_PROJECT_DIR}`), Codex's from the git top level. **Run `bravos sync` in each repository**: it rewrites the commands in `.claude/settings.json` and `.codex/hooks.json`, one line per hook.
|
|
26
|
+
- **Old skills from the Python bravos are named.** If you used the earlier Python CLI, its skills may still sit in `~/.claude/skills` and `~/.agents/skills`, and an agent can load one and follow commands this bravos does not have. The session briefing now tells the agent not to follow them, and `bravos doctor` lists them with one command that moves them aside (nothing is deleted).
|
|
27
|
+
|
|
28
|
+
## 1.8.0
|
|
29
|
+
|
|
30
|
+
1.8 removes the stops Bravos put between a developer and their code. After `bravos start`, you open your agent and say anything; Bravos asks once for what only you can decide, then keeps itself current.
|
|
31
|
+
|
|
32
|
+
- **Run `bravos sync` once in each repository, by hand.** It is the last time: from now on the agent's session briefing says when a repository is behind and the agent runs `bravos sync` (and `bravos setup` for Bravos's own bundles) itself. `bravos upkeep` shows what is behind. A bravos older than the one that last synced a repository never syncs it; it tells you to update instead. `BRAVOS_UPKEEP_PROBE=off` stops the check.
|
|
33
|
+
- **After `bravos start`, the agent begins by itself.** For three days, in that clone, the first session starts the context step without being asked and goes on to annotation once a named person confirms. The context gate is unchanged: nothing is annotated before that confirmation.
|
|
34
|
+
- **Done on the review page is enough.** `bravos review intent --wait` returns with everyone's answers when the person presses Done, so nobody types "done" in chat. Run again, it joins the same page.
|
|
35
|
+
- **The commit question is asked once.** `bravos start` asks whether your agent commits the files Bravos writes (annotations, intent, definitions, tests); `bravos prefs set commits commit|leave|ask --by "<your name>"` changes it. The answer is kept under the clone's git directory, never committed, and never covers your own code.
|
|
36
|
+
- **The code graph rebuilds itself (Team plan).** When a session starts and the commit has no graph, the session hook starts one background build (`--scip no-exec`, no tokens). One per repository at a time; never in CI; `BRAVOS_GRAPH_AUTOBUILD=off` turns it off.
|
|
37
|
+
- **`bravos start`:**
|
|
38
|
+
- `--yes` keeps autopilot on for the pull-request preset, as the interactive default does.
|
|
39
|
+
- In a repository that already has Bravos, it sets up only this machine and leaves the team's `proving.md` and setup alone; `bravos start --again` changes the repository's setup.
|
|
40
|
+
- With automatic testing it can take your local app's address and write the target, so the policy needs one merge.
|
|
41
|
+
- It no longer asks about cxg model generation, which Bravos never uses.
|
|
42
|
+
- **`.mcp.json` no longer holds a path from one machine.** The code graph server is registered as `bravos graph mcp`; the next `bravos sync` rewrites an older entry. Reconnect MCP in your agent once (`/mcp` in Claude Code). `bravos` must be on PATH where the agent runs.
|
|
43
|
+
- **`.bravos/setup.json` no longer records your repository path**, theme or tool install.
|
|
44
|
+
- **Licence:** if the portal revokes a machine or a plan ends, the briefing now says so; before, that was lost.
|
|
45
|
+
- **Skills:** no skill tells the agent to stash; the dashboard is built and its path given instead of offered; `bravos-resync` asks before committing your work in progress.
|
|
4
46
|
|
|
5
47
|
## 1.7.0
|
|
6
48
|
|
package/hooks/lib/autopilot.mjs
CHANGED
|
@@ -4,7 +4,7 @@ import { appendFileSync, existsSync, mkdirSync, openSync, readFileSync, readSync
|
|
|
4
4
|
import { join } from 'node:path';
|
|
5
5
|
import { contextGate } from './context.mjs';
|
|
6
6
|
import { gitStaleness, staleness } from './resync.mjs';
|
|
7
|
-
import { asyncRunner, changedHunks, fingerprint, readSnapshot, workingChanges } from './snapshot.mjs';
|
|
7
|
+
import { asyncRunner, changedHunks, fingerprint, logWatchEvent, readSnapshot, workingChanges } from './snapshot.mjs';
|
|
8
8
|
|
|
9
9
|
export { asyncRunner, readSnapshot, safeSessionId, takeSnapshot } from './snapshot.mjs';
|
|
10
10
|
|
|
@@ -314,20 +314,5 @@ function finish(findings, payload) {
|
|
|
314
314
|
return { decision: 'block', reason, summary, keys: fresh2.map((f) => f.key) };
|
|
315
315
|
}
|
|
316
316
|
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
// @comment -- "Appends one autopilot nudge to .bravos/watch/events.jsonl for bravos watch to show: a local log, not a state store. The folder carries its own .gitignore of *, the file keeps its newest WATCH_LOG_CAP lines, and any failure is swallowed because the nudge itself already went out."
|
|
320
|
-
export function logWatchEvent(root, { summary, keys = [] }, now = new Date()) {
|
|
321
|
-
try {
|
|
322
|
-
const dir = join(root, '.bravos', 'watch');
|
|
323
|
-
mkdirSync(dir, { recursive: true });
|
|
324
|
-
const ignore = join(dir, '.gitignore');
|
|
325
|
-
if (!existsSync(ignore)) writeFileSync(ignore, '*\n');
|
|
326
|
-
const file = join(dir, 'events.jsonl');
|
|
327
|
-
appendFileSync(file, JSON.stringify({ at: now.toISOString(), text: String(summary ?? '').slice(0, 400), keys }) + '\n');
|
|
328
|
-
const lines = readFileSync(file, 'utf8').split('\n').filter(Boolean);
|
|
329
|
-
if (lines.length > WATCH_LOG_CAP) writeFileSync(file, lines.slice(-WATCH_LOG_CAP).join('\n') + '\n');
|
|
330
|
-
} catch {
|
|
331
|
-
/* the log is a convenience for bravos watch */
|
|
332
|
-
}
|
|
333
|
-
}
|
|
317
|
+
// The watch log lives in snapshot.mjs so the session hook's background graph build can write to it too.
|
|
318
|
+
export { logWatchEvent, WATCH_LOG_CAP } from './snapshot.mjs';
|
package/hooks/lib/briefing.mjs
CHANGED
|
@@ -3,10 +3,12 @@ import { spawn, spawnSync } from 'node:child_process';
|
|
|
3
3
|
import { accessSync, constants, readFileSync } from 'node:fs';
|
|
4
4
|
import { basename, delimiter, dirname, join } from 'node:path';
|
|
5
5
|
import { contextGate, readContext } from './context.mjs';
|
|
6
|
+
import { legacySkills, legacySkillsLine } from './legacy-skills.mjs';
|
|
6
7
|
import { THEMES } from './palette.mjs';
|
|
8
|
+
import { commitsLine, commonDirFrom, readHandoff, readPrefs } from './prefs.mjs';
|
|
7
9
|
import { readProving } from './proving.mjs';
|
|
8
10
|
import { planLabel, planLine, status as licenceStatus } from './licence.mjs';
|
|
9
|
-
import { refreshIfDue } from './refresh.mjs';
|
|
11
|
+
import { readLicenceNote, refreshIfDue } from './refresh.mjs';
|
|
10
12
|
import { gitStaleness, staleLine, staleness, strandedBranches, strandedLine } from './resync.mjs';
|
|
11
13
|
import { readSast, sastAvailable, sastLine } from './sast.mjs';
|
|
12
14
|
import { hooksLocked, readSetup, setupLine, TRIAL } from './setup.mjs';
|
|
@@ -132,9 +134,11 @@ export function contextLine(context, harness) {
|
|
|
132
134
|
}
|
|
133
135
|
|
|
134
136
|
// @comment -- "The briefing's Intent line. While the context gate is closed it also says so in words an agent acts on: do not start threat-modelling, run the context skill first, and how a person declines. A recorded decline is shown with the name and date of the person who made it."
|
|
135
|
-
function intentLine(intent, harness, gate) {
|
|
137
|
+
function intentLine(intent, harness, gate, handoff = false) {
|
|
136
138
|
const run = harness === 'claude' ? '/bravos-context' : 'the bravos-context skill';
|
|
137
|
-
|
|
139
|
+
// Right after bravos setup (a fresh hand-off marker), the person expects Bravos to begin: the agent starts the context step itself and goes on to annotation, unless their first message asks for something else.
|
|
140
|
+
const begin = handoff && intent.status === 'none' ? ` Setup just finished here and the person expects Bravos to begin: start ${run} in your first reply without being asked, and go on to annotation once they have confirmed. If their first message asks for something else, do that and offer this once after.` : '';
|
|
141
|
+
const closed = gate && gate.open === false ? `. Context comes first: do not annotate or start a campaign until a named person has confirmed it (or run bravos context decline --by "<name>" themselves).${begin}` : '';
|
|
138
142
|
const declined = gate?.state === 'declined' ? `declined by ${gate.by} on ${gate.at}` : '';
|
|
139
143
|
if (intent.status === 'none') return declined ? `Intent: ${declined} — severities are not calibrated to the product; ${run} when the team is ready` : `Intent: none — severities are not calibrated to the product; run ${run}${closed}`;
|
|
140
144
|
if (intent.status === 'draft') return `Intent: draft (${intent.invariants} invariants, ${intent.drafts} items unconfirmed${declined ? `; context ${declined}` : ''}) — confirm with ${run}${closed}`;
|
|
@@ -159,7 +163,8 @@ function coachLines(i) {
|
|
|
159
163
|
'How to help this person (offer, never lecture; one offer per topic per session):',
|
|
160
164
|
`- In your first reply, if setup is under 5 or intent is none, offer once in plain words three starts that fit this repo, in setup order (${i.licence?.licensed === false ? 'on the Free plan: learn what the app intends, annotate the uncovered files, prove the top threats; never lead with a Team-plan step' : 'build the code graph first if it is off, then learn what the app intends, annotate the uncovered files, run SAST, prove the top threats; or check this branch before a PR'}) and \`bravos guide\` for more; then follow their lead.`,
|
|
161
165
|
`- After you edit security-relevant code, offer to record what it exposes (${k('bravos-annotate')}); before a PR, run the ship check (${k('bravos-ship')}); after a fix, offer a recheck (${k('bravos-recheck')}).`,
|
|
162
|
-
|
|
166
|
+
// A standing answer is the briefing's Commits line; with none, ask once and (unless they chose to be asked each time) record it so no later session asks.
|
|
167
|
+
...(commitsLine(i.prefs) ? [] : [`- Commits are the person's call: before the first commit of a session ask once (commit now, or leave the files for them to review), even where a skill says to commit; skip the question only when they already asked for commits (a campaign, a schedule).${i.prefs?.commits?.value === 'ask' ? '' : ' Then ask whether that is their answer from now on, and if so record it with `bravos prefs set commits commit|leave --by "<their name>"`: their answer and their name, never yours.'}`]),
|
|
163
168
|
'- When a request would go better with the next unlock above, say what it would add, once. Plain words first, skill name second. Never send test traffic without the authorization bravos-env asks for.',
|
|
164
169
|
'- Once, when it helps them follow along, mention that `bravos watch` in a second terminal pane shows this live as you work (free, read-only), and that `bravos dashboard` opens the findings as one page in their browser (rebuilt from the code each time; never open a saved copy instead).',
|
|
165
170
|
);
|
|
@@ -232,9 +237,12 @@ export function buildBriefing(inputs) {
|
|
|
232
237
|
else if (i.inFlight.prs > 0 || i.inFlight.files > 0) {
|
|
233
238
|
tail.push(`In flight by teammates: ${i.inFlight.files} files in ${i.inFlight.prs} open PRs`);
|
|
234
239
|
}
|
|
235
|
-
if (i.intent && typeof i.intent === 'object') tail.push(intentLine(i.intent, i.harness, i.gate));
|
|
240
|
+
if (i.intent && typeof i.intent === 'object') tail.push(intentLine(i.intent, i.harness, i.gate, i.handoff === true));
|
|
236
241
|
const documents = contextLine(i.context, i.harness);
|
|
237
242
|
if (documents) tail.push(documents);
|
|
243
|
+
// The person's standing answer about commits, when they gave one (hooks/lib/prefs.mjs).
|
|
244
|
+
const commits = commitsLine(i.prefs);
|
|
245
|
+
if (commits) tail.push(commits);
|
|
238
246
|
if (i.proving && typeof i.proving === 'object') {
|
|
239
247
|
const p = i.proving;
|
|
240
248
|
tail.push(p.status === 'set'
|
|
@@ -244,9 +252,16 @@ export function buildBriefing(inputs) {
|
|
|
244
252
|
}
|
|
245
253
|
if (i.shadow) {
|
|
246
254
|
tail.push(i.shadow.userNewer
|
|
247
|
-
? `Note: this repo's bravos (${i.shadow.repo}) is behind the person's user-level copy (${i.shadow.user}), which Claude Code uses; suggest they run bravos
|
|
248
|
-
: `Note: the person's user-level bravos skills (~/.claude/skills, ${i.shadow.user}) are used instead of this repo's (${i.shadow.repo}); tell them to run bravos
|
|
249
|
-
}
|
|
255
|
+
? `Note: this repo's bravos (${i.shadow.repo}) is behind the person's user-level copy (${i.shadow.user}), which Claude Code uses; suggest they run bravos setup in this repo from their own terminal`
|
|
256
|
+
: `Note: the person's user-level bravos skills (~/.claude/skills, ${i.shadow.user}) are used instead of this repo's (${i.shadow.repo}); tell them to run bravos setup --global from their own terminal, then start a new session`);
|
|
257
|
+
}
|
|
258
|
+
const upkeep = upkeepLine(i.upkeep);
|
|
259
|
+
if (upkeep) tail.push(upkeep);
|
|
260
|
+
// The portal's last refusal to renew this machine, until it is signed in again (a revocation) or renewed (a plan that ended).
|
|
261
|
+
if (i.licenceNote && (i.licenceNote.outcome === 'lapsed' || i.licence?.licensed === false)) tail.push(`Licence: ${i.licenceNote.note} Tell the person once, in plain words.`);
|
|
262
|
+
// Skills the retired Python bravos left at user level: the agent must not follow them (hooks/lib/legacy-skills.mjs).
|
|
263
|
+
const legacy = legacySkillsLine(i.legacy);
|
|
264
|
+
if (legacy) tail.push(legacy);
|
|
250
265
|
if ((i.autopilot || i.prePr) && hooksLocked(i)) {
|
|
251
266
|
// The repo registers the hooks for everyone; this person's copy answers nothing until they have a licence.
|
|
252
267
|
const which = i.autopilot ? 'Autopilot (the end-of-turn check and the pre-PR gate)' : 'The pre-PR gate';
|
|
@@ -254,6 +269,7 @@ export function buildBriefing(inputs) {
|
|
|
254
269
|
} else if (i.autopilot) tail.push('Autopilot: on — at turn end, review changed behavior in new and annotated files and follow the proving choice for affected claims');
|
|
255
270
|
if (i.codegraph === 'current') tail.push('Code graph: current');
|
|
256
271
|
else if (i.codegraph === 'cli') tail.push('Code graph: ask it with `bravos graph <question> --json` (same answers as the codegraph_ tools; e.g. attack-surface, entry-points, callers, reachable-sinks, call-chain); if it says no graph, build it: bravos graph build . (bravos-codegraph)');
|
|
272
|
+
else if (i.codegraph === 'not-built' && i.graphBuild) tail.push('Code graph: none for this commit yet — bravos is building it in the background now (no tokens, a few minutes): do not start another build. Ask the graph again in a few minutes; until then skills trace routes by reading.');
|
|
257
273
|
else if (i.codegraph === 'not-built') tail.push('Code graph: none for this commit — bravos keys a graph to the commit it was built at, so a new commit needs a rebuild: bravos graph build . --scip no-exec (bravos-codegraph; no tokens, a few minutes). Until then skills trace routes by reading.');
|
|
258
274
|
else if (i.codegraph === 'diverged') tail.push('Code graph: diverged — rebuild with codegraph-build --scip no-exec');
|
|
259
275
|
else if (i.codegraph === 'locked') tail.push('Code graph: on the Team plan (see Plan above) — skills trace routes by reading until then');
|
|
@@ -388,6 +404,56 @@ export async function probeGraph(root, env, timeoutMs = 3000) {
|
|
|
388
404
|
return 'cli';
|
|
389
405
|
}
|
|
390
406
|
|
|
407
|
+
// @comment -- "Asks the installed bravos what has fallen behind it here (bravos upkeep --json: read-only, no network, well under a second), only where the repository carries Bravos's files. Null when bravos is not on PATH, is too old to know the command, does not answer in time, or BRAVOS_UPKEEP_PROBE=off."
|
|
408
|
+
export async function probeUpkeep(root, env, timeoutMs = 3000) {
|
|
409
|
+
if (env.BRAVOS_UPKEEP_PROBE === 'off' || !whichOnPath('bravos', env)) return null;
|
|
410
|
+
try {
|
|
411
|
+
accessSync(join(root, '.bravos', 'skills.lock'), constants.R_OK);
|
|
412
|
+
} catch {
|
|
413
|
+
return null;
|
|
414
|
+
}
|
|
415
|
+
const r = await capture('bravos', ['upkeep', root, '--json'], { cwd: root, env, timeoutMs });
|
|
416
|
+
if (r.timedOut || r.error || r.status !== 0) return null;
|
|
417
|
+
try {
|
|
418
|
+
const j = JSON.parse(r.stdout);
|
|
419
|
+
return j?.schema === 'bravos.upkeep/v1' ? j : null;
|
|
420
|
+
} catch {
|
|
421
|
+
return null;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
const VERSION_RE = /^\d+(?:\.\d+){0,3}(?:-[A-Za-z0-9.]{1,20})?$/;
|
|
426
|
+
// @comment -- "The briefing's Upkeep line: what the agent repairs by itself. A repository whose Bravos files are behind the installed bravos gets `bravos sync`; a staged bundle older than this bravos pins gets `bravos setup` (Bravos's own signed bundles, nothing third-party). When the repository is the newer side the agent is told not to sync, because an older bravos would roll it back, and to tell the person to update. Only version numbers, counts and the two known bundle names from the answer reach the text."
|
|
427
|
+
export function upkeepLine(u) {
|
|
428
|
+
if (!u || typeof u !== 'object') return null;
|
|
429
|
+
const ver = (v) => (typeof v === 'string' && VERSION_RE.test(v) ? v : null);
|
|
430
|
+
const cli = ver(u.cli);
|
|
431
|
+
const parts = [];
|
|
432
|
+
const files = Number.isInteger(u.sync?.files) && u.sync.files > 0 ? u.sync.files : 0;
|
|
433
|
+
if (files && cli) {
|
|
434
|
+
const repo = ver(u.repo);
|
|
435
|
+
const count = `${files} file${files === 1 ? '' : 's'}`;
|
|
436
|
+
if (u.sync.direction === 'repo-newer') parts.push(`this repository's Bravos files${repo ? ` (${repo})` : ''} are newer than the installed bravos (${cli}): do not run bravos sync from this machine, it would roll them back; tell the person once to update with npm install -g @bugb-technologies/bravos@latest`);
|
|
437
|
+
else parts.push(`this repository's Bravos files are behind the installed bravos (${repo && repo !== cli ? `${repo} → ${cli}, ` : ''}${count}): run \`bravos sync\` now without asking and include what it changes in your next commit of Bravos's files`);
|
|
438
|
+
}
|
|
439
|
+
const bundles = (Array.isArray(u.bundles) ? u.bundles : []).filter((b) => ['analyzer', 'codegraph'].includes(b?.id) && ver(b.staged) && ver(b.pinned));
|
|
440
|
+
// From 1.9 one command does all of this upkeep (the answer says so with `unified`); an older bravos on PATH keeps the two commands it understands, below.
|
|
441
|
+
if (u.unified === true && cli) {
|
|
442
|
+
const repo = ver(u.repo);
|
|
443
|
+
const newer = files > 0 && u.sync.direction === 'repo-newer';
|
|
444
|
+
const behind = [
|
|
445
|
+
...(files && !newer ? [`this repository's Bravos files (${repo && repo !== cli ? `${repo} → ${cli}, ` : ''}${files} file${files === 1 ? '' : 's'})`] : []),
|
|
446
|
+
...bundles.map((b) => `the ${b.id} bundle on this machine (${b.staged} → ${b.pinned})`),
|
|
447
|
+
];
|
|
448
|
+
const out = [];
|
|
449
|
+
if (behind.length) out.push(`${behind.join(' and ')} ${behind.length === 1 && bundles.length === 1 ? 'is' : 'are'} behind the installed bravos: run \`bravos setup\` now without asking. With no terminal it only brings what is already installed up to date (Bravos's own files and signed bundles), asks nothing and installs nothing new; include what it changes in your next commit of Bravos's files`);
|
|
450
|
+
if (newer) out.push(`this repository's Bravos files${repo ? ` (${repo})` : ''} are newer than the installed bravos (${cli}): bravos setup will leave them alone; tell the person once to update with npm install -g @bugb-technologies/bravos@latest`);
|
|
451
|
+
return out.length ? `Upkeep: ${out.join('; ')}.` : null;
|
|
452
|
+
}
|
|
453
|
+
if (bundles.length) parts.push(`the ${bundles.map((b) => `${b.id} bundle (${b.staged} → ${b.pinned})`).join(' and ')} on this machine ${bundles.length === 1 ? 'is' : 'are'} older than this bravos pins: run \`bravos setup\` now without asking (it fetches Bravos's own signed bundles and nothing else)`);
|
|
454
|
+
return parts.length ? `Upkeep: ${parts.join('; ')}.` : null;
|
|
455
|
+
}
|
|
456
|
+
|
|
391
457
|
export async function collect(root, env, { deadlineMs = 20000, nextCount = 3 } = {}) {
|
|
392
458
|
const deadline = Date.now() + deadlineMs;
|
|
393
459
|
const budget = () => Math.min(10000, Math.max(0, deadline - Date.now()));
|
|
@@ -400,10 +466,12 @@ export async function collect(root, env, { deadlineMs = 20000, nextCount = 3 } =
|
|
|
400
466
|
return r.timedOut || r.error || r.status !== 0 ? null : r.stdout.trim();
|
|
401
467
|
};
|
|
402
468
|
const gitFacts = (async () => {
|
|
403
|
-
const [sha, ref, branch] = await Promise.all([
|
|
469
|
+
const [sha, ref, branch, common] = await Promise.all([
|
|
404
470
|
git(['rev-parse', '--short', 'HEAD']),
|
|
405
471
|
git(['symbolic-ref', '-q', '--short', 'refs/remotes/origin/HEAD']),
|
|
406
472
|
git(['rev-parse', '--abbrev-ref', 'HEAD']),
|
|
473
|
+
// Where this clone keeps its own state: the person's preferences live there, out of any commit's reach.
|
|
474
|
+
git(['rev-parse', '--git-common-dir']),
|
|
407
475
|
]);
|
|
408
476
|
const base = ref || 'origin/main';
|
|
409
477
|
const name = branch && branch !== 'HEAD' ? branch : null;
|
|
@@ -419,6 +487,7 @@ export async function collect(root, env, { deadlineMs = 20000, nextCount = 3 } =
|
|
|
419
487
|
]);
|
|
420
488
|
return {
|
|
421
489
|
sha: sha ?? 'unknown',
|
|
490
|
+
commonDir: commonDirFrom(root, common),
|
|
422
491
|
defaultBranch: defaultHead ? ref : null,
|
|
423
492
|
base,
|
|
424
493
|
branch: name,
|
|
@@ -444,12 +513,13 @@ export async function collect(root, env, { deadlineMs = 20000, nextCount = 3 } =
|
|
|
444
513
|
});
|
|
445
514
|
|
|
446
515
|
const graphRun = probeGraph(root, env, Math.min(3000, first));
|
|
516
|
+
const upkeepRun = probeUpkeep(root, env, Math.min(3000, first)).catch(() => null);
|
|
447
517
|
// A signed-in machine's device licence is renewed here when it is due, alongside the other facts and under a short timeout of its own; it fails open, so a slow or absent portal only means the held token is read as it is.
|
|
448
518
|
const renewal = refreshIfDue(env, { timeoutMs: Math.min(3000, first) }).catch(() => null);
|
|
449
519
|
// At an app folder, each member's counts come from its own guardlink ci, alongside the rest.
|
|
450
520
|
const workspace = readWorkspace(root);
|
|
451
521
|
const countsRun = workspace?.isAppFolder && hasGuardlink ? memberCounts(workspace, runJsonAsync, env, first) : Promise.resolve(null);
|
|
452
|
-
const [facts, pr, graphState, workspaceCounts, , ...gl] = await Promise.all([gitFacts, prRun, graphRun, countsRun, renewal, ...glRuns]);
|
|
522
|
+
const [facts, pr, graphState, workspaceCounts, , upkeep, ...gl] = await Promise.all([gitFacts, prRun, graphRun, countsRun, renewal, upkeepRun, ...glRuns]);
|
|
453
523
|
|
|
454
524
|
let guardlink = 'missing';
|
|
455
525
|
if (hasGuardlink) {
|
|
@@ -485,6 +555,11 @@ export async function collect(root, env, { deadlineMs = 20000, nextCount = 3 } =
|
|
|
485
555
|
intent: readIntent(root),
|
|
486
556
|
context: readContext(root),
|
|
487
557
|
gate: contextGate(root),
|
|
558
|
+
prefs: readPrefs(facts.commonDir),
|
|
559
|
+
handoff: readHandoff(facts.commonDir),
|
|
560
|
+
upkeep,
|
|
561
|
+
// Read after the renewal above has run, so a refusal that just arrived is in it.
|
|
562
|
+
licenceNote: readLicenceNote(env),
|
|
488
563
|
annotationMode: readAnnotationMode(root),
|
|
489
564
|
// bravos on PATH: what its probe says (a graph for this commit or not); else codegraph-mcp on PATH means the MCP route.
|
|
490
565
|
codegraph: graphState ?? (whichOnPath('codegraph-mcp', env) ? 'unknown' : 'unavailable'),
|
|
@@ -493,6 +568,7 @@ export async function collect(root, env, { deadlineMs = 20000, nextCount = 3 } =
|
|
|
493
568
|
harness: env.CLAUDE_PROJECT_DIR ? 'claude' : 'other',
|
|
494
569
|
prePr: prePrRegistered(root),
|
|
495
570
|
shadow: userSkillsShadow(root, env),
|
|
571
|
+
legacy: legacySkills(env),
|
|
496
572
|
autopilot: autopilotRegistered(root),
|
|
497
573
|
proving: readProving(root),
|
|
498
574
|
workspace,
|
|
@@ -597,7 +673,7 @@ export function autopilotRegistered(root) {
|
|
|
597
673
|
return false;
|
|
598
674
|
}
|
|
599
675
|
|
|
600
|
-
// @comment -- "Detects a user-level bravos install (bravos
|
|
676
|
+
// @comment -- "Detects a user-level bravos install (bravos setup --global) whose version differs from this repo's: Claude Code prefers personal skills over project skills of the same name, so an older ~/.claude/skills copy silently replaces the repo's. Returns { user, repo } versions, or null when there is no conflict."
|
|
601
677
|
export function userSkillsShadow(root, env) {
|
|
602
678
|
const home = env?.HOME;
|
|
603
679
|
if (!home) return null;
|
|
@@ -698,7 +774,7 @@ const TIPS = [
|
|
|
698
774
|
'run bravos doctor to see which of guardlink, cxg, codegraph-mcp, bravos-cli you have.',
|
|
699
775
|
'"unknown" in the briefing means a tool failed, never that the count is zero.',
|
|
700
776
|
'bravos-campaign clears big backlogs in rounds of subagents, with rests between.',
|
|
701
|
-
'bravos
|
|
777
|
+
'bravos setup --pre-pr-hook runs the ship gate on every gh pr create.',
|
|
702
778
|
'intended-by-design behaviour goes in .guardlink/intent.md, not in @accepts.',
|
|
703
779
|
'stale means the code under a claim changed; bravos-recheck clears it.',
|
|
704
780
|
'anything beyond loopback needs a reviewed scope.yaml and your typed authorization.',
|
|
@@ -763,9 +839,12 @@ function bannerWarnings(i, plan) {
|
|
|
763
839
|
else if (arr(i.stranded).length > 0) lines.push(`~ Work on ${clean(i.stranded[0].branch)} is not on ${clean(i.base)} · bravos-resync`);
|
|
764
840
|
if (i.shadow) {
|
|
765
841
|
lines.push(i.shadow.userNewer
|
|
766
|
-
? `~ repo bravos ${i.shadow.repo} is behind your ${i.shadow.user} · run: bravos
|
|
767
|
-
: `! your user-level bravos ${i.shadow.user} overrides repo ${i.shadow.repo} · run: bravos
|
|
842
|
+
? `~ repo bravos ${i.shadow.repo} is behind your ${i.shadow.user} · run: bravos setup`
|
|
843
|
+
: `! your user-level bravos ${i.shadow.user} overrides repo ${i.shadow.repo} · run: bravos setup --global`);
|
|
768
844
|
}
|
|
845
|
+
// One line for old Python skills at user level; bravos doctor prints the command that moves them aside.
|
|
846
|
+
const old = arr(i.legacy).reduce((n, f) => n + arr(f?.names).length, 0);
|
|
847
|
+
if (old > 0) lines.push(`! ${old} old Python bravos skill${old === 1 ? '' : 's'} in your user folder · bravos doctor`);
|
|
769
848
|
return lines;
|
|
770
849
|
}
|
|
771
850
|
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// @comment -- "The background code graph build. A graph is keyed to the commit it was built at, so after every commit there is none, and until now only a person or an agent told to do so rebuilt it. When the session hook finds no graph for the commit, it starts one quiet build here: a detached process that runs `bravos graph build <root> --scip no-exec` (no model, no network, and no-exec means the repository's own build scripts are never run), records how it ended, tells bravos watch, and exits. One build per repository at a time, whatever the number of sessions: the runner takes an exclusive lock under $BRAVOS_HOME/autobuild/<repository>/ before it builds. It starts only on the Team plan, only in a repository that installed Bravos (never from the user-level or plugin copy of the hook), never in CI, and never when BRAVOS_GRAPH_AUTOBUILD=off. A build that failed is not retried for the same commit for six hours."
|
|
2
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { existsSync, mkdirSync, openSync, closeSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { bravosHome } from './licence.mjs';
|
|
8
|
+
import { logWatchEvent } from './snapshot.mjs';
|
|
9
|
+
|
|
10
|
+
/** A lock older than this belongs to a build that died without cleaning up. bravos graph build gives up at 30 minutes itself. */
|
|
11
|
+
export const LOCK_STALE_MS = 45 * 60 * 1000;
|
|
12
|
+
export const RETRY_AFTER_FAILURE_MS = 6 * 60 * 60 * 1000;
|
|
13
|
+
/** A session whose probe ran while another session's build was finishing still reads "no graph"; a build that succeeded for this commit this recently is believed over that probe. */
|
|
14
|
+
export const JUST_BUILT_MS = 10 * 60 * 1000;
|
|
15
|
+
const BUILD_TIMEOUT_MS = 35 * 60 * 1000;
|
|
16
|
+
const SHA_RE = /^[0-9a-f]{7,40}$/;
|
|
17
|
+
|
|
18
|
+
// @comment -- "Where one repository's build state lives: a folder under $BRAVOS_HOME named by a hash of the repository's path, so nothing is written into a repository for this and two clones never share a lock."
|
|
19
|
+
export function stateDir(root, env = process.env) {
|
|
20
|
+
const home = bravosHome(env);
|
|
21
|
+
if (!home) return null;
|
|
22
|
+
return join(home, 'autobuild', createHash('sha256').update(String(root)).digest('hex').slice(0, 16));
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const readJson = (file) => {
|
|
26
|
+
try {
|
|
27
|
+
const j = JSON.parse(readFileSync(file, 'utf8'));
|
|
28
|
+
return j && typeof j === 'object' ? j : null;
|
|
29
|
+
} catch {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const alive = (pid) => {
|
|
35
|
+
if (!Number.isInteger(pid) || pid <= 1) return false;
|
|
36
|
+
try {
|
|
37
|
+
process.kill(pid, 0);
|
|
38
|
+
return true;
|
|
39
|
+
} catch {
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const justBuilt = (last, sha, now) => !!last && last.ok === true && last.sha === sha && typeof last.at === 'number' && now - last.at >= 0 && now - last.at < JUST_BUILT_MS;
|
|
45
|
+
|
|
46
|
+
/** The build running for this repository, if any: a lock whose process is alive and which is not older than a build can be. */
|
|
47
|
+
export function runningBuild(dir, now = Date.now()) {
|
|
48
|
+
const lock = dir ? readJson(join(dir, 'lock')) : null;
|
|
49
|
+
if (!lock || typeof lock.at !== 'number') return null;
|
|
50
|
+
return alive(lock.pid) && now - lock.at < LOCK_STALE_MS ? { pid: lock.pid, sha: typeof lock.sha === 'string' ? lock.sha : null, at: lock.at } : null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// @comment -- "Decides whether to start a build, and why not when not. Pure but for reading the lock and the last result: the session hook and the tests ask it the same way."
|
|
54
|
+
export function buildDecision({ root, env = process.env, codegraph, licensed, sha, installed, now = Date.now() }) {
|
|
55
|
+
if (codegraph !== 'not-built') return { start: false, reason: 'graph-present' };
|
|
56
|
+
if (!licensed) return { start: false, reason: 'unlicensed' };
|
|
57
|
+
if (!installed) return { start: false, reason: 'not-installed-here' };
|
|
58
|
+
if (env.BRAVOS_GRAPH_AUTOBUILD === 'off') return { start: false, reason: 'switched-off' };
|
|
59
|
+
if (env.CI) return { start: false, reason: 'ci' };
|
|
60
|
+
if (typeof sha !== 'string' || !SHA_RE.test(sha)) return { start: false, reason: 'no-commit' };
|
|
61
|
+
const dir = stateDir(root, env);
|
|
62
|
+
if (!dir) return { start: false, reason: 'no-home' };
|
|
63
|
+
if (runningBuild(dir, now)) return { start: false, running: true, reason: 'already-building' };
|
|
64
|
+
const last = readJson(join(dir, 'last.json'));
|
|
65
|
+
if (justBuilt(last, sha, now)) return { start: false, reason: 'just-built' };
|
|
66
|
+
if (last && last.ok === false && last.sha === sha && typeof last.at === 'number' && now - last.at < RETRY_AFTER_FAILURE_MS) return { start: false, reason: 'failed-recently' };
|
|
67
|
+
return { start: true, dir };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// @comment -- "Starts the runner detached from the hook (which must return within its timeout) and says what happened: 'started', 'running' when a build is already going, or null. The runner is this same file, run with the node that runs the hook; it outlives the session that started it. Never throws: a build that cannot start only means the briefing prints the command, as before."
|
|
71
|
+
export function startGraphBuild(opts) {
|
|
72
|
+
let d;
|
|
73
|
+
try {
|
|
74
|
+
d = buildDecision(opts);
|
|
75
|
+
} catch {
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
if (d.running) return 'running';
|
|
79
|
+
if (!d.start) return null;
|
|
80
|
+
try {
|
|
81
|
+
mkdirSync(d.dir, { recursive: true, mode: 0o700 });
|
|
82
|
+
const child = spawn(process.execPath, [fileURLToPath(import.meta.url), 'run', opts.root, d.dir, opts.sha], { cwd: opts.root, env: opts.env ?? process.env, detached: true, stdio: 'ignore' });
|
|
83
|
+
child.on('error', () => {});
|
|
84
|
+
child.unref();
|
|
85
|
+
return child.pid ? 'started' : null;
|
|
86
|
+
} catch {
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// @comment -- "The runner: takes the lock (exclusive create, so of two runners started together one builds and the other exits), runs the build, writes last.json and a short log, tells bravos watch, and removes the lock. `build` is replaceable so the tests need no real graph binary."
|
|
92
|
+
export function runBuild(root, dir, sha, { env = process.env, now = () => Date.now(), build } = {}) {
|
|
93
|
+
const lock = join(dir, 'lock');
|
|
94
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
95
|
+
// A lock left by a build that died is cleared first; a live one stops us.
|
|
96
|
+
if (existsSync(lock) && !runningBuild(dir, now())) rmSync(lock, { force: true });
|
|
97
|
+
let fd;
|
|
98
|
+
try {
|
|
99
|
+
fd = openSync(lock, 'wx', 0o600);
|
|
100
|
+
} catch {
|
|
101
|
+
return { ran: false };
|
|
102
|
+
}
|
|
103
|
+
try {
|
|
104
|
+
writeFileSync(fd, JSON.stringify({ pid: process.pid, sha, at: now() }));
|
|
105
|
+
closeSync(fd);
|
|
106
|
+
// Another runner may have finished this very commit between our session's probe and now: one build is enough.
|
|
107
|
+
if (justBuilt(readJson(join(dir, 'last.json')), sha, now())) return { ran: false };
|
|
108
|
+
logWatchEvent(root, { summary: `code graph: building in the background for ${sha}`, keys: ['graph'] });
|
|
109
|
+
const run = build ?? (() => spawnSync('bravos', ['graph', 'build', root, '--scip', 'no-exec', '--json'], { cwd: root, env, encoding: 'utf8', timeout: BUILD_TIMEOUT_MS, maxBuffer: 16 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] }));
|
|
110
|
+
const r = run();
|
|
111
|
+
const ok = !r.error && r.status === 0;
|
|
112
|
+
const why = ok ? '' : String(r.error?.code ?? (r.stderr || r.stdout || `exit ${r.status}`)).split('\n').map((l) => l.trim()).find((l) => l && !l.startsWith('{')) ?? `exit ${r.status}`;
|
|
113
|
+
writeFileSync(join(dir, 'last.json'), JSON.stringify({ ok, sha, at: now(), ...(ok ? {} : { why: why.slice(0, 300) }) }) + '\n', { mode: 0o600 });
|
|
114
|
+
writeFileSync(join(dir, 'build.log'), `${new Date(now()).toISOString()} ${sha} ${ok ? 'built' : 'failed'}\n${String(r.stderr ?? '').slice(-4000)}\n`, { mode: 0o600 });
|
|
115
|
+
logWatchEvent(root, { summary: ok ? `code graph: built for ${sha}` : `code graph: the background build did not finish (${why.slice(0, 160)}); bravos graph build . shows why`, keys: ['graph'] });
|
|
116
|
+
return { ran: true, ok };
|
|
117
|
+
} finally {
|
|
118
|
+
rmSync(lock, { force: true });
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Run as a script: `node graph-autobuild.mjs run <root> <stateDir> <sha>`.
|
|
123
|
+
if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1] && process.argv[2] === 'run') {
|
|
124
|
+
const [root, dir, sha] = process.argv.slice(3);
|
|
125
|
+
try {
|
|
126
|
+
if (root && dir && SHA_RE.test(sha ?? '')) runBuild(root, dir, sha);
|
|
127
|
+
} catch {
|
|
128
|
+
/* nothing to tell: the next session's briefing prints the command */
|
|
129
|
+
}
|
|
130
|
+
process.exit(0);
|
|
131
|
+
}
|