@bugb-technologies/bravos 1.18.0 → 1.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/account.js +19 -2
  2. package/dist/cli.js +133 -15
  3. package/dist/context.js +126 -3
  4. package/dist/cursor.js +4 -2
  5. package/dist/dashboard.js +9 -0
  6. package/dist/device.js +3 -1
  7. package/dist/doctor.js +4 -0
  8. package/dist/guide.js +7 -3
  9. package/dist/help.js +15 -8
  10. package/dist/instruction-blocks.js +257 -0
  11. package/dist/principles.js +279 -0
  12. package/dist/review-server.js +19 -4
  13. package/dist/review-wait.js +11 -0
  14. package/dist/review.js +342 -41
  15. package/dist/rules.js +82 -6
  16. package/dist/uninstall.js +9 -2
  17. package/docs/GUIDE.md +18 -2
  18. package/docs/UPGRADING.md +63 -0
  19. package/hooks/autopilot.mjs +2 -1
  20. package/hooks/cards.mjs +23 -5
  21. package/hooks/coach.mjs +3 -0
  22. package/hooks/invite.mjs +10 -0
  23. package/hooks/lib/audience.mjs +83 -0
  24. package/hooks/lib/briefing.mjs +83 -2
  25. package/hooks/lib/context.mjs +57 -1
  26. package/hooks/lib/display.mjs +11 -0
  27. package/hooks/lib/licence.mjs +2 -1
  28. package/hooks/lib/machine.mjs +77 -0
  29. package/hooks/lib/pre-pr.mjs +82 -1
  30. package/hooks/lib/principles.mjs +513 -0
  31. package/hooks/lib/refresh.mjs +11 -1
  32. package/hooks/lib/replay.mjs +218 -100
  33. package/hooks/pre-pr.mjs +3 -0
  34. package/hooks/session-start.mjs +35 -7
  35. package/package.json +1 -1
  36. package/skills/bravos/SKILL.md +1 -0
  37. package/skills/bravos-context/SKILL.md +4 -4
  38. package/skills/bravos-principles/SKILL.md +52 -0
  39. package/templates/dashboard/dashboard.html +75 -1
  40. package/templates/omp/bravos.js +10 -1
  41. package/templates/opencode/bravos.js +11 -2
  42. package/templates/review/review.html +140 -11
  43. package/templates/workflows/bravos-nightly-claude.yml +1 -1
  44. package/templates/workflows/bravos-nightly-codex.yml +1 -1
  45. package/templates/workflows/bravos-pr-gate.yml +1 -1
package/dist/guide.js CHANGED
@@ -14,6 +14,7 @@ export const GUIDE_TOPICS = [
14
14
  body: [
15
15
  'A hook gathers the repo\'s security picture (open exposures, confirmed exploits, what to test next, stale claims, tickets, teammates\' open PRs, intent) and hands it to the model, so you never need a command to load it. On a fresh start you also see the banner; the model does not.',
16
16
  'Every agent shows the same Bravos picture, through the best channel it has. Claude Code shows the banner above the first prompt, and Gemini shows it at session start. omp shows it above the editor until your first prompt. Codex shows the Bravos card (the banner without the logo) with your first message. Cursor and opencode cannot draw anything at launch, so the agent opens its first reply with the card. Antigravity gets the briefing for the model only. Anywhere else, the bravos skill loads the briefing when you run it.',
17
+ 'Teammates without Bravos: the hooks travel with the repository, but on a machine without Bravos (no bravos command, licence or plugin) they show only an invitation, once per session: the repository\'s own numbers from the committed threat model and the one command to join. Nothing else runs for them: no briefing, coach, threat cards, checks or background work, and nothing is sent anywhere. Their agent offers setup once and runs it only on a yes; "not now" hides it for 7 days in that clone (node .bravos/hooks/invite.mjs snooze). A team switches it off with {"invite": "off"} in .bravos/config.json.',
17
18
  ],
18
19
  },
19
20
  {
@@ -25,7 +26,7 @@ export const GUIDE_TOPICS = [
25
26
  {
26
27
  name: 'Plans',
27
28
  body: [
28
- 'Free (researcher) needs no licence: context, annotate, templatize, env, prove, recheck, report and watch, in each repository on its own, with no limit on how many. Team, licensed per developer (Solo is one seat), adds the pre-PR gate and autopilot, the CI and nightly workflows, scheduled upkeep, multi-repository workspaces, campaigns, SAST and the code graph. The briefing opens every session with a Plan: line; bravos licence shows the same in a shell. bravos account activate signs you in once in the browser and writes the licence (a 30-day Team trial, no card, when the account has no plan); bravos account import <file> installs a downloaded one. On a team plan the licence is yours and this machine\'s: an owner or admin assigns you a licence, each machine you activate gets its own short-lived token that bravos renews automatically (at the session start and before a paid command), bravos account devices lists your machines, bravos account revoke <id> signs one out (a lost laptop), and bravos account logout signs this one out. Removing you from the team, or taking your licence back, stops every one of your machines at its next renewal. In CI, BRAVOS_LICENCE holds a CI licence an owner or admin creates for that repository, and the CLI never renews it. Without a licence a paid command explains what it would do and how to start the trial, a paid hook stands down with one line and never blocks, and a paid skill stops at its first step and says so.',
29
+ 'Free (researcher) needs no licence: context, annotate, templatize, env, prove, recheck, report and watch, in each repository on its own, with no limit on how many. Team, licensed per developer (Solo is one seat), adds the pre-PR gate and autopilot, the CI and nightly workflows, scheduled upkeep, multi-repository workspaces, campaigns, SAST and the code graph. The briefing opens every session with a Plan: line; bravos licence shows the same in a shell. bravos account activate signs you in once in the browser and writes the licence (a 30-day Team trial, no card, when the account has no plan); bravos account import <file> installs a downloaded one. On a team plan the licence is yours and this machine\'s: an owner or admin assigns you a licence, each machine you activate gets its own short-lived token that bravos renews automatically (at the session start and before a paid command), bravos account devices lists your machines, bravos account revoke <id> signs one out (a lost laptop), and bravos account logout signs this one out. Removing you from the team, or taking your licence back, stops every one of your machines at its next renewal. At activation and at each renewal bravos sends the account portal a one-way fingerprint of the machine (a hash of the operating system machine id, never the id itself, and none in a container or CI), which the portal uses to allow one free trial per person and machine. In CI, BRAVOS_LICENCE holds a CI licence an owner or admin creates for that repository, and the CLI never renews it. Without a licence a paid command explains what it would do and how to start the trial, a paid hook stands down with one line and never blocks, and a paid skill stops at its first step and says so.',
29
30
  ],
30
31
  },
31
32
  {
@@ -115,8 +116,9 @@ export const GUIDE_TOPICS = [
115
116
  { name: 'Where do I start? What is open?', skills: ['bravos'], body: ['Reads the briefing and names the one next step, with the reason.'] },
116
117
  { name: 'Teach bravos what the app is for', skills: ['bravos-context'], body: ['Writes .guardlink/intent.md: invariants (INV-n) that become threats, and intended-by-design items (INT-n) that get an "intended?" audit instead of a high rating.'] },
117
118
  { 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.'] },
119
+ { name: 'Write down your company\'s security design principles', skills: ['bravos-principles'], body: ['Ask for "our security design principles". bravos-principles proposes candidates only from your stored documents (cited by section, checked against the text), INV rules a person already confirmed in this or another repository, or an optional starter list mapped to OWASP ASVS 4.0.3, which is never pre-selected; bravos review principles refuses anything else. On the page each principle is its own decision (Agree, Change the wording, or No); there is no adopt-all. Confirm records your adoption with the exact wording and a fingerprint, and bravos writes .guardlink/principles.md from the adoptions: committed, so every developer who pulls gets it, and the Bravos block in AGENTS.md and CLAUDE.md tells every coding agent to read and follow it and never edit it. A principle is enforced (it becomes a threat with principle:SDP-n, is tested, and the pre-PR gate stops a change that breaks it, whatever the PR body says) or guidance (followed, not tested). bravos principles check (free; the pre-push hook and the gate run it) fails a hand-edited line, an adoption nobody made, or an exception past its date. An exception is approved by a person at their own terminal: bravos principles except SDP-n --where "<glob>" --reason "<why>" --until <date>, at most a year, never extended; a coding agent cannot run it. bravos principles copy --from <repository> takes the same set into another repository, and check says when the source changes. The dashboard\'s Security design view shows each principle, where it is enforced, its exceptions, and what it caught or stopped in the last 30 and 90 days. Team plan for authoring, the gate and the view; adopted principles are followed on every plan.'] },
118
120
  { 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 under Threat model, as Design rules in GuardLink\'s sidebar beside Exposures, worst first. 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.'] },
119
- { 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.'] },
121
+ { 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. The intake page brings back the answers each person gave when they reopen it, and saves them as they go; only Confirm makes them count, and it records who and when. Design documents (a PRD, a design document, an earlier threat model) can be added on the page itself: Markdown and text are stored with the usual checks, and a PDF, Word file, slides or link waits for the agent to convert. Every rule cites the section of the document it came from, the page shows that passage under the question, and bravos context check refuses a section the document does not have. The intake and the documents are committed so the team gets them on their next pull; bravos doctor warns when a .gitignore rule keeps them on one machine, and bravos context share --yes narrows a blanket .bravos/ rule. 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
122
  { 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.'] },
121
123
  { name: 'Threat cards', skills: ['bravos-prove', 'bravos-env'], body: ['When an edit adds a critical or high threat to the threat model (an @exposes claim) that no test has confirmed or refuted, a hook that runs after the edit shows you a card in the terminal straight away: the severity, what the threat is, the claim and where it is, its state, and one next step (bravos-env to set up a test target, where you type the authorization, then bravos-prove). The agent is told to raise it in the same reply and recommend confirming it; it never confirms, refutes or accepts a threat itself. Only lines that are not in the last commit count, so existing claims never raise a card, and each threat raises one card per clone. The hook reads the edited files, their committed copy and the local ledger; it runs no guardlink, no test and no network. bravos watch lists every card. BRAVOS_THREAT_CARDS=off turns cards off for a run and bravos prefs set cards off --by "<your name>" for the clone; bravos prefs set notify on --by "<your name>" adds a desktop notification (macOS and Linux).'] },
122
124
  { 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.'] },
@@ -144,7 +146,7 @@ export const GUIDE_TOPICS = [
144
146
  {
145
147
  id: 'skills',
146
148
  title: 'Every skill',
147
- summary: 'all fifteen skills, what each does and leaves for the next',
149
+ summary: 'all seventeen skills, what each does and leaves for the next',
148
150
  items: [
149
151
  { name: 'bravos', body: ['Front door: reads the security picture, explains the evidence loop, routes to the right skill.'] },
150
152
  { name: 'bravos-context', body: ['Learns what the product intends from the repo and a short interview; records invariants, intended behaviour, actors, assets and boundaries.'] },
@@ -158,6 +160,7 @@ export const GUIDE_TOPICS = [
158
160
  { name: 'bravos-resync', body: ['A stale checkout or a left-behind branch: carries its annotation work onto the base with bravos resync, maps duplicate ids, re-reads every carried claim on changed code.'] },
159
161
  { name: 'bravos-sast', body: ['Licensed static analysis joined to guardlink claims and reachability; gates on findings new since the base.'] },
160
162
  { name: 'bravos-threat-hunt', body: ['"Identify all the threats": maps the attack surface with the code graph, runs SAST, records every finding in the threat model with bravos-annotate, rebuilds the dashboard and reports from what was recorded, then recommends confirming the top three.'] },
163
+ { name: 'bravos-principles', body: ['Your company\'s security design principles, from your own documents and confirmed rules (or an optional starter list mapped to OWASP ASVS): proposed on the review page, adopted one by one by named people, written by bravos to .guardlink/principles.md, followed by every coding agent, and enforced ones tested and held to by the pre-PR gate.'] },
161
164
  { name: 'bravos-campaign', body: ['A goal over many rounds: disjoint batches, one subagent each, a gate per batch, rests, a final before-and-after.'] },
162
165
  { name: 'bravos-schedule', body: ['Recurring upkeep with each harness\'s own mechanism; never live tests from a loop.'] },
163
166
  { name: 'bravos-cicd', body: ['Audits and writes the security workflows.'] },
@@ -199,6 +202,7 @@ export const GUIDE_TOPICS = [
199
202
  { name: 'opencode', body: ['Finds the skills in .claude/skills and .agents/skills through its skill tool; bravos adds /bravos… commands in .opencode/commands that load them, a plugin in .opencode/plugins (opencode 2.x) that adds the briefing to the system prompt, and guardlink MCP in opencode.json.'] },
200
203
  { name: 'Antigravity (agy)', body: ['Reads .agents/skills; .agents/hooks.json carries a bravos SessionStart group that injects the briefing.'] },
201
204
  { name: 'Cursor', body: ['When the repo has a .cursor/ folder (or with --agent cursor): .cursor/rules/bravos.mdc points at the skills, and a sessionStart hook in .cursor/hooks.json gives the agent the briefing and the Bravos card for its first reply.'] },
205
+ { name: 'Agents without hooks', body: ['A short Bravos block, between <!-- bravos:begin --> and <!-- bravos:end -->, in AGENTS.md and CLAUDE.md (when they exist or their skills are installed), GEMINI.md and .github/copilot-instructions.md (when they exist), and .windsurf/rules/bravos.md (with a .windsurf/ folder): an agent that got no briefing from a hook runs node .bravos/hooks/session-start.mjs --briefing. Setup replaces only that block; uninstall removes it.'] },
202
206
  { name: 'VS Code (Copilot agent)', body: ['Reads hooks from .claude/settings.json (preview), so the briefing can load there too.'] },
203
207
  { name: 'Every repo, or one copy of each skill', body: ['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.'] },
204
208
  { name: 'Banner switches', body: ['BRAVOS_BANNER=off hides it; BRAVOS_BANNER_COLOR=off or NO_COLOR prints it plain. The briefing for the model is unchanged either way.', '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/dist/help.js CHANGED
@@ -8,11 +8,22 @@ What bravos is
8
8
  The agents do the work with the real CLIs. bravos has no orchestrator and keeps no state:
9
9
  .bravos/ holds only its hooks and a lock file.
10
10
 
11
+ Getting started
12
+ npm install -g @bugb-technologies/bravos
13
+ bravos setup in a repository, in a terminal: the guided setup, one question at a time.
14
+ Sign in (a 30-day Team trial, no card) or continue on the Free plan, install
15
+ guardlink and cxg, choose your agents, PR checks and schedule. Nothing changes
16
+ until you choose Apply. Then open your coding agent.
17
+
11
18
  Commands
12
- init [dir] First install in a repository. Runs guardlink init if .guardlink/ is absent.
13
- sync [dir] Re-apply bravos to a repository that already has it (after upgrading bravos,
14
- or to add --ci / --pre-pr-hook / --scope / --autopilot later; hooks already
15
- installed stay installed). Never runs guardlink init. init and sync take --global for a user-level install.
19
+ setup [dir] The one setup command. In a terminal: the guided setup above (--change asks
20
+ again; --yes takes the defaults). Where nobody can be asked (an agent, a script,
21
+ CI): brings what is installed up to date and installs nothing new. Flags add
22
+ one thing at a time: --ci (PR gate and nightly workflows), --pre-pr-hook,
23
+ --autopilot, --scope, --agent <ids>, --tools -y (guardlink and cxg),
24
+ --analyzer / --codegraph (the Team plan's signed bundles), --global (user-level
25
+ install). --check reports and changes nothing; --dry-run says what would happen.
26
+ (init, sync and start are older names for it and still work.)
16
27
  doctor [dir] Read-only check of tools, licence, installed skills and hooks.
17
28
  resync [dir] Carry annotation work from another branch onto this checkout: --from <ref>
18
29
  (a dry run; --apply writes, reanchors and validates), or --list to find it.
@@ -57,10 +68,6 @@ Commands
57
68
  (Team plan; not committed); status is one line about the newest run; candidates
58
69
  lists its reachable findings joined to a claim, not yet in the threat model,
59
70
  dependencies and secrets. No model.
60
- setup Put the binaries bravos drives on this machine: the analyzer (SAST) and the
61
- code graph are signed bundles fetched through the account portal (Team plan),
62
- verified and staged under $BRAVOS_HOME; --tools adds guardlink and cxg (-y).
63
- --check reports, --dry-run says what would happen.
64
71
  graph The code graph (Team plan): graph build [DIR] [--scip MODE] indexes a repo;
65
72
  graph <question> [args] --json asks it (the codegraph_ tools' answers);
66
73
  graph --json lists every question this machine's binary answers.
@@ -0,0 +1,257 @@
1
+ import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join, relative, isAbsolute } from 'node:path';
3
+ import { readLock, sha256, writeLock } from './lock.js';
4
+ import { MARKER, skillsRoot } from './skills.js';
5
+ // @comment -- "The markers around Bravos's block in an instruction file other people also edit. Distinct from GuardLink's <!-- guardlink:begin --> / <!-- guardlink:end -->, so neither tool's sync can mistake the other's block for its own."
6
+ export const BLOCK_BEGIN = '<!-- bravos:begin -->';
7
+ export const BLOCK_END = '<!-- bravos:end -->';
8
+ const GUARDLINK_BEGIN = '<!-- guardlink:begin -->';
9
+ const GUARDLINK_END = '<!-- guardlink:end -->';
10
+ // @comment -- "The block's text, written for an agent: what Bravos is, the one command that brings the briefing (or, on a machine without Bravos, the invitation) when no hook delivered it, what to say when node is missing, that nothing is installed without the person's go-ahead, and that the company's security design principles (when the repository has them) are read, followed and never edited. Fixed text: no repository or user content is ever spliced in; the principles stay in their own file. On every plan: a team's own principles are never hidden from its developers."
11
+ export const BLOCK_BODY = [
12
+ '## Bravos',
13
+ '',
14
+ 'This repository uses Bravos, a security workflow for coding agents.',
15
+ '- If no Bravos briefing reached you through a hook at session start, run `node .bravos/hooks/session-start.mjs --briefing` from the repository root once, at the start of the session, and follow what it prints: the security briefing, or an invitation to show the person when Bravos is not installed on this machine.',
16
+ '- If `node` is not available, tell the person once that this repository uses Bravos (`npm install -g @bugb-technologies/bravos && bravos setup`), then continue.',
17
+ '- Never install anything without the person\'s go-ahead.',
18
+ '- If `.guardlink/principles.md` exists, it holds this company\'s security design principles, adopted by named people. Read it before changing code here and follow every principle under Adopted. When a change would break one, say so and ask the person before going on; an approved exception listed there covers only its own code until its date. Never edit that file, its adoptions or its exceptions yourself: people change them on `bravos review principles`.',
19
+ ];
20
+ // @comment -- "The whole delimited block, ending with one line break, in the file's own line ending."
21
+ export function bravosBlock(eol = '\n') {
22
+ return [BLOCK_BEGIN, ...BLOCK_BODY, BLOCK_END].join(eol) + eol;
23
+ }
24
+ // @comment -- "Where Bravos's Windsurf rule lives: Windsurf reads workspace rules from .windsurf/rules/*.md, and trigger: always_on puts it in every Cascade session. The whole file is Bravos's, so it is lock-recorded and uninstall deletes it when unchanged."
25
+ export const WINDSURF_RULE_PATH = '.windsurf/rules/bravos.md';
26
+ export const windsurfRule = () => `---\ntrigger: always_on\n---\n${MARKER}\n${bravosBlock()}`;
27
+ // @comment -- "The shared instruction files that carry the block, the agents that read each, and when each is created: AGENTS.md and CLAUDE.md also when their agent's skills root is installed, GEMINI.md and Copilot's file only when they already exist."
28
+ export const SHARED_FILES = [
29
+ { path: 'AGENTS.md', agents: ['agents', 'agy', 'opencode', 'omp', 'cursor'], skills: 'agents' },
30
+ { path: 'CLAUDE.md', agents: ['claude'], skills: 'claude' },
31
+ { path: 'GEMINI.md', agents: ['agy'] },
32
+ { path: '.github/copilot-instructions.md', agents: [] },
33
+ ];
34
+ /** [start, end) ranges of GuardLink's own blocks, where a Bravos marker is never looked for. */
35
+ function guardlinkRanges(text) {
36
+ const out = [];
37
+ let from = 0;
38
+ for (;;) {
39
+ const b = text.indexOf(GUARDLINK_BEGIN, from);
40
+ if (b === -1)
41
+ return out;
42
+ const e = text.indexOf(GUARDLINK_END, b);
43
+ if (e === -1) {
44
+ out.push([b, text.length]);
45
+ return out;
46
+ }
47
+ out.push([b, e + GUARDLINK_END.length]);
48
+ from = e + GUARDLINK_END.length;
49
+ }
50
+ }
51
+ /** The first index of `needle` at or after `from` that is not inside a GuardLink block, or -1. */
52
+ function indexOutside(text, needle, from, ranges) {
53
+ for (let i = text.indexOf(needle, from); i !== -1; i = text.indexOf(needle, i + 1)) {
54
+ if (!ranges.some(([s, e]) => i >= s && i < e))
55
+ return i;
56
+ }
57
+ return -1;
58
+ }
59
+ /** Where Bravos's block sits in `text`: its begin and end-marker offsets, null when absent, or an error for a begin with no end. */
60
+ function findBlock(text) {
61
+ const ranges = guardlinkRanges(text);
62
+ const begin = indexOutside(text, BLOCK_BEGIN, 0, ranges);
63
+ if (begin === -1)
64
+ return null;
65
+ const end = indexOutside(text, BLOCK_END, begin, ranges);
66
+ if (end === -1)
67
+ return { error: `has ${BLOCK_BEGIN} with no ${BLOCK_END} after it; fix it and run bravos setup again` };
68
+ return { begin, end };
69
+ }
70
+ // @comment -- "Puts the block into an instruction file's text: replaces the existing Bravos block in place, or appends it after everything else with one blank line before it. Text outside the markers, GuardLink's block included, is kept byte for byte."
71
+ export function upsertBlock(text) {
72
+ const eol = text.includes('\r\n') ? '\r\n' : '\n';
73
+ const block = bravosBlock(eol);
74
+ const at = findBlock(text);
75
+ if (at && 'error' in at)
76
+ return at;
77
+ if (at) {
78
+ // The block ends with one line break the previous write put there; drop exactly that one so a re-run is unchanged.
79
+ const tail = text.slice(at.end + BLOCK_END.length).replace(/^\r?\n/, '');
80
+ return { text: text.slice(0, at.begin) + block + tail };
81
+ }
82
+ if (text === '')
83
+ return { text: block };
84
+ const sep = text.endsWith('\n') ? eol : eol + eol;
85
+ return { text: text + sep + block };
86
+ }
87
+ // @comment -- "Takes the block out of an instruction file's text, with the line break that ends it and the blank line upsertBlock put before it; returns null when the file holds no Bravos block. Nothing else is changed."
88
+ export function removeBlock(text) {
89
+ const at = findBlock(text);
90
+ if (!at || 'error' in at)
91
+ return null;
92
+ let head = text.slice(0, at.begin);
93
+ const tail = text.slice(at.end + BLOCK_END.length).replace(/^\r?\n/, '');
94
+ if (/(\r?\n){2}$/.test(head))
95
+ head = head.replace(/\r?\n$/, '');
96
+ return head + tail;
97
+ }
98
+ // @comment -- "Resolves an instruction file for writing: absent, a regular file whose real path stays inside the repository, or a reason to leave it alone (a folder, a link that leaves the repository)."
99
+ // @exposes #instruction-blocks to #out-of-repo-write [medium] cwe:CWE-59 -- "AGENTS.md, CLAUDE.md and the rest come from the cloned repository, and any of them can be a link."
100
+ // @mitigates #instruction-blocks against #out-of-repo-write using #in-repo-target -- "A link such as CLAUDE.md -> AGENTS.md is followed only when it ends at a regular file inside the repository; anything else is reported and never written."
101
+ function target(root, rel) {
102
+ const abs = join(root, rel);
103
+ let st;
104
+ try {
105
+ st = lstatSync(abs);
106
+ }
107
+ catch {
108
+ // Absent: the parent must also stay inside the repository (a linked .github/ or .windsurf/ is not followed out).
109
+ try {
110
+ const parent = realpathSync(dirname(abs));
111
+ const rp = relative(realpathSync(root), parent);
112
+ if (rp.startsWith('..') || isAbsolute(rp))
113
+ return { reason: 'its folder is a link that leaves the repository' };
114
+ }
115
+ catch {
116
+ /* the folder does not exist yet; mkdir creates it inside root */
117
+ }
118
+ return { exists: false };
119
+ }
120
+ if (st.isSymbolicLink()) {
121
+ let real;
122
+ try {
123
+ real = realpathSync(abs);
124
+ }
125
+ catch {
126
+ return { reason: 'a link to a file that does not exist' };
127
+ }
128
+ const rp = relative(realpathSync(root), real);
129
+ if (rp.startsWith('..') || isAbsolute(rp))
130
+ return { reason: 'a link that leaves the repository' };
131
+ if (!lstatSync(real).isFile())
132
+ return { reason: 'not a regular file' };
133
+ return { exists: true };
134
+ }
135
+ if (!st.isFile())
136
+ return { reason: 'not a regular file' };
137
+ return { exists: true };
138
+ }
139
+ const lexists = (abs) => {
140
+ try {
141
+ lstatSync(abs);
142
+ return true;
143
+ }
144
+ catch {
145
+ return false;
146
+ }
147
+ };
148
+ // @comment -- "Writes or refreshes the Bravos block in each shared instruction file under its condition: the file exists, or (AGENTS.md, CLAUDE.md) that agent's skills root is installed. With an explicit --agent a file is written only when one of its agents was chosen, or when no --agent can name it (Copilot's file); upkeep also refreshes a block already present. Shared files are never lock-recorded, since people edit them."
149
+ export function writeInstructionBlocks(root, opts) {
150
+ const out = [];
151
+ const seen = new Set();
152
+ for (const f of SHARED_FILES) {
153
+ const t = target(root, f.path);
154
+ const has = 'exists' in t && t.exists;
155
+ const chosen = opts.agents === undefined || f.agents.length === 0 || f.agents.some((a) => opts.agents.includes(a));
156
+ const text = has ? readFileSync(join(root, f.path), 'utf8') : '';
157
+ const present = has && findBlock(text) !== null;
158
+ if (!chosen && !(opts.refreshOnly && present))
159
+ continue;
160
+ const installed = f.skills !== undefined && (opts.harnesses.includes(f.skills) || existsSync(join(root, skillsRoot(f.skills), 'bravos', 'SKILL.md')));
161
+ if ('reason' in t) {
162
+ if (installed || lexists(join(root, f.path)))
163
+ out.push({ path: f.path, status: 'skipped', reason: t.reason });
164
+ continue;
165
+ }
166
+ if (!has && !installed)
167
+ continue;
168
+ // CLAUDE.md linked to AGENTS.md is one file: it gets one block.
169
+ const real = has ? realpathSync(join(root, f.path)) : join(root, f.path);
170
+ if (seen.has(real)) {
171
+ out.push({ path: f.path, status: 'unchanged' });
172
+ continue;
173
+ }
174
+ seen.add(real);
175
+ const next = upsertBlock(text);
176
+ if ('error' in next) {
177
+ out.push({ path: f.path, status: 'skipped', reason: next.error });
178
+ continue;
179
+ }
180
+ if (has && next.text === text) {
181
+ out.push({ path: f.path, status: 'unchanged' });
182
+ continue;
183
+ }
184
+ if (!opts.dryRun) {
185
+ mkdirSync(dirname(join(root, f.path)), { recursive: true });
186
+ writeFileSync(join(root, f.path), next.text);
187
+ }
188
+ out.push({ path: f.path, status: has ? 'updated' : 'written' });
189
+ }
190
+ const w = writeWindsurfRule(root, opts);
191
+ if (w)
192
+ out.push(w);
193
+ return out;
194
+ }
195
+ // @comment -- "Writes .windsurf/rules/bravos.md when the repo has a .windsurf/ folder. Windsurf has no --agent value, so it follows the folder alone. The file is Bravos's whole: replaced only when the lock vouches for it or it carries the generated marker, unless --force, and the lock records what was written."
196
+ export function writeWindsurfRule(root, opts = {}) {
197
+ if (!existsSync(join(root, '.windsurf')))
198
+ return null;
199
+ const path = WINDSURF_RULE_PATH;
200
+ const t = target(root, path);
201
+ if ('reason' in t)
202
+ return { path, status: 'skipped', reason: t.reason };
203
+ const abs = join(root, path);
204
+ const content = Buffer.from(windsurfRule());
205
+ const hash = sha256(content);
206
+ const lock = readLock(root);
207
+ let status = 'written';
208
+ if (t.exists) {
209
+ const disk = readFileSync(abs);
210
+ const diskHash = sha256(disk);
211
+ if (diskHash === hash)
212
+ return { path, status: 'unchanged' };
213
+ const locked = lock.files[path];
214
+ if (locked !== undefined && diskHash !== locked && !opts.force)
215
+ return { path, status: 'skipped', reason: 'edited since last install (use --force to overwrite)' };
216
+ if (locked === undefined && !disk.toString('utf8').includes(MARKER) && !opts.force)
217
+ return { path, status: 'skipped', reason: 'authored file, not managed by bravos (use --force to overwrite)' };
218
+ status = 'updated';
219
+ }
220
+ if (!opts.dryRun) {
221
+ mkdirSync(dirname(abs), { recursive: true });
222
+ writeFileSync(abs, content);
223
+ writeLock(root, { ...lock, files: { ...lock.files, [path]: hash } });
224
+ }
225
+ return { path, status };
226
+ }
227
+ // @comment -- "Uninstall's part: takes the Bravos block out of each shared instruction file and keeps every other line; a file left holding nothing but blank space (Bravos created it) is deleted. The Windsurf rule is lock-recorded, so the lock pass removes it when unchanged. Links that leave the repository are not followed."
228
+ export function removeInstructionBlocks(root, opts = {}) {
229
+ const cleaned = [];
230
+ const deleted = [];
231
+ const seen = new Set();
232
+ for (const f of SHARED_FILES) {
233
+ const t = target(root, f.path);
234
+ if (!('exists' in t) || !t.exists)
235
+ continue;
236
+ const abs = join(root, f.path);
237
+ const real = realpathSync(abs);
238
+ if (seen.has(real))
239
+ continue;
240
+ seen.add(real);
241
+ const text = readFileSync(abs, 'utf8');
242
+ const next = removeBlock(text);
243
+ if (next === null)
244
+ continue;
245
+ if (next.trim() === '' && !lstatSync(abs).isSymbolicLink()) {
246
+ deleted.push(f.path);
247
+ if (!opts.dryRun)
248
+ unlinkSync(abs);
249
+ }
250
+ else {
251
+ cleaned.push(f.path);
252
+ if (!opts.dryRun)
253
+ writeFileSync(abs, next);
254
+ }
255
+ }
256
+ return { cleaned, deleted };
257
+ }