@bugb-technologies/bravos 1.3.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +17 -10
  2. package/dist/ci.js +11 -3
  3. package/dist/cli.js +16 -6
  4. package/dist/doctor.js +2 -2
  5. package/dist/guide.js +2 -2
  6. package/dist/help.js +10 -14
  7. package/dist/install-proof-tool.js +117 -0
  8. package/dist/proof-tools.js +29 -0
  9. package/dist/report/check.js +4 -1
  10. package/dist/report/data.js +81 -149
  11. package/dist/report/markdown.js +1 -1
  12. package/dist/report/redact.js +16 -0
  13. package/dist/report/runs.js +169 -0
  14. package/dist/setup.js +43 -19
  15. package/dist/start/answers.js +5 -3
  16. package/dist/start/index.js +28 -14
  17. package/dist/versions.js +5 -4
  18. package/docs/GUIDE.md +2 -2
  19. package/hooks/lib/autopilot.mjs +155 -37
  20. package/hooks/lib/briefing.mjs +9 -3
  21. package/hooks/lib/nightly-stage.mjs +66 -0
  22. package/hooks/lib/nightly-tools.sh +45 -0
  23. package/hooks/lib/pre-pr.mjs +88 -17
  24. package/hooks/lib/proof-tool-pins.json +12 -0
  25. package/hooks/lib/replay.mjs +579 -0
  26. package/hooks/lib/setup.mjs +15 -6
  27. package/hooks/lib/snapshot.mjs +75 -9
  28. package/package.json +1 -1
  29. package/skills/bravos/SKILL.md +1 -1
  30. package/skills/bravos-annotate/SKILL.md +6 -5
  31. package/skills/bravos-annotate/scripts/slice.mjs +15 -8
  32. package/skills/bravos-cicd/SKILL.md +1 -1
  33. package/skills/bravos-env/SKILL.md +3 -3
  34. package/skills/bravos-prove/SKILL.md +11 -15
  35. package/skills/bravos-recheck/SKILL.md +3 -3
  36. package/skills/bravos-report/SKILL.md +1 -1
  37. package/skills/bravos-schedule/SKILL.md +1 -1
  38. package/skills/bravos-ship/SKILL.md +1 -1
  39. package/skills/bravos-templatize/SKILL.md +3 -3
  40. package/templates/workflows/bravos-nightly-claude.yml +131 -74
  41. package/templates/workflows/bravos-nightly-codex.yml +130 -73
  42. package/templates/workflows/bravos-pr-gate.yml +88 -14
@@ -0,0 +1,579 @@
1
+ // @comment -- "Run one supplied, bound JavaScript probe per CXG process. Authority for target contact comes from the reviewed policy and scope; a kit controls neither. Only an engine verdict and an unchanged binding can update an exposure."
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { spawnSync } from 'node:child_process';
4
+ import { closeSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readSync, readlinkSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
5
+ import { createConnection } from 'node:net';
6
+ import { homedir, tmpdir } from 'node:os';
7
+ import { join, relative, resolve, sep } from 'node:path';
8
+ import { pathToFileURL } from 'node:url';
9
+
10
+ const POLICY = '.guardlink/proving.md';
11
+ const SCOPE = '.guardlink/scope.yaml';
12
+ const KEY = /^[a-f0-9]{64}:\d+$/;
13
+ const PROFILE = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/;
14
+ const ID = /^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
15
+ const sha = (value) => createHash('sha256').update(value).digest('hex');
16
+
17
+ // Only accept ordinary files within the worktree. In particular the kit named by --templates must stay a JS probe.
18
+ function localFile(root, name) {
19
+ const file = resolve(root, name);
20
+ if (!file.startsWith(realpathSync(root) + sep) || realpathSync(file) !== file || !lstatSync(file).isFile()) {
21
+ throw new Error('A replay input is outside the repository, a symlink, or not a regular file.');
22
+ }
23
+ return file;
24
+ }
25
+
26
+ function invoke(command, args, cwd, opts = {}) {
27
+ const result = spawnSync(command, args, { cwd, env: opts.env ?? sanitizedEnv(process.env), input: opts.input, encoding: 'utf8', timeout: opts.timeout ?? 120000,
28
+ stdio: ['pipe', 'pipe', 'pipe'], maxBuffer: 64 * 1024 * 1024 });
29
+ if (result.error || !(opts.allowed ?? [0]).includes(result.status)) {
30
+ // Tool stderr can include provider bodies, session details or scan evidence.
31
+ throw new Error(`${command} ${args[0] ?? ''} failed (exit ${result.status ?? result.error?.code ?? 'unknown'}).`);
32
+ }
33
+ return result;
34
+ }
35
+
36
+ function git(root, args) {
37
+ return invoke('git', args, root).stdout;
38
+ }
39
+
40
+ function parsedJson(text, description) {
41
+ try { return JSON.parse(text); }
42
+ catch { throw new Error(`Invalid JSON in ${description}.`); } // Parse errors can quote session data.
43
+ }
44
+
45
+ function jsonTool(root, cmd, args) {
46
+ return parsedJson(invoke(cmd, args, root).stdout, cmd + ' output');
47
+ }
48
+
49
+ // A named choice on this checkout can revoke permission immediately. Local edits never expand a committed grant.
50
+ function committedFile(root, file) {
51
+ const path = localFile(root, file);
52
+ const current = readFileSync(path, 'utf8');
53
+ // An agent can commit a broader policy on a feature branch. Use the default branch's grant as the upper bound there.
54
+ const remoteDefault = spawnSync('git', ['symbolic-ref', '--quiet', 'refs/remotes/origin/HEAD'], { cwd: root, encoding: 'utf8' });
55
+ if ([POLICY, SCOPE].includes(file) && remoteDefault.status === 0 && git(root, ['show', `${remoteDefault.stdout.trim()}:${file}`]) !== current) {
56
+ throw new Error(`${file} differs from the default branch's recorded grant.`);
57
+ }
58
+ if (git(root, ['show', `HEAD:${file}`]) !== current) throw new Error(`${file} differs from its reviewed commit.`);
59
+ return current;
60
+ }
61
+
62
+ function uniqueHeader(text, name, optional = false) {
63
+ const rows = [...text.matchAll(new RegExp(`^//[ \\t]*@${name}:[ \\t]*(.*?)[ \\t]*\\r?$`, 'gm'))];
64
+ if (optional && rows.length === 0) return null;
65
+ if (rows.length !== 1 || !rows[0][1]) throw new Error(`The probe needs one @${name} header.`);
66
+ return rows[0][1];
67
+ }
68
+
69
+ function probe(root, name) {
70
+ if (!/\.js$/i.test(name)) throw new Error('Select one .js probe.');
71
+ const file = localFile(root, name);
72
+ const bytes = readFileSync(file);
73
+ const text = bytes.toString('utf8');
74
+ if (!/\basync\s+function\s+cxgProbe\s*\(\s*cxg\s*\)/.test(text) || uniqueHeader(text, 'attach_scheme', true) !== 'path') {
75
+ throw rebind('The kit must be a CXG JavaScript probe with @attach_scheme: path.');
76
+ }
77
+ const id = uniqueHeader(text, 'id');
78
+ const vulnClass = uniqueHeader(text, 'vuln_class');
79
+ if (!ID.test(id) || !ID.test(vulnClass)) throw new Error('Invalid probe ID or vulnerability class.');
80
+ return { file, text, id, vulnClass, digest: sha(bytes) };
81
+ }
82
+
83
+ function model(root) {
84
+ const sarif = jsonTool(root, 'guardlink', ['sarif', '.', '--profile', 'pentest']);
85
+ const hypotheses = jsonTool(root, 'guardlink', ['hypothesis', 'list', '--json']);
86
+ if (!Array.isArray(sarif.runs) || !Array.isArray(hypotheses.records)) throw new Error('Unavailable GuardLink model.');
87
+ const results = sarif.runs.flatMap((r) => r.results ?? []).filter((r) => KEY.test(r.properties?.claimKey ?? ''));
88
+ return { sarif, results, records: hypotheses.records };
89
+ }
90
+
91
+ function resolveBinding(root, kit, current, forBind = false) {
92
+ const ref = uniqueHeader(kit.text, 'guardlink_threat', true);
93
+ const bound = uniqueHeader(kit.text, 'bravos_claim_key', true);
94
+ const stamped = uniqueHeader(kit.text, 'exposure_claim_key', true);
95
+ if (bound && stamped && bound !== stamped) throw new Error('Conflicting kit claim keys.');
96
+ const key = bound ?? stamped;
97
+ const proofDigest = uniqueHeader(kit.text, 'bravos_kit_sha256', true);
98
+ if (!forBind && (bound || proofDigest) && proofDigest !== kitBodyDigest(kit.text)) {
99
+ throw new Error('The kit bytes no longer match their binding. Review the changed probe and run bind again.');
100
+ }
101
+ if (!forBind && !KEY.test(key ?? '')) throw rebind('Run bind on this kit before replay.');
102
+ if (key && !KEY.test(key)) throw new Error('Invalid claim key on the probe.');
103
+ if (!key && !ref) throw new Error('Use an exact @guardlink_threat with its source file and line.');
104
+ const reference = (row) => {
105
+ const loc = row.locations?.[0]?.physicalLocation;
106
+ return `${row.properties.threat?.replace(/^#/, '')}@${loc?.artifactLocation?.uri}:${loc?.region?.startLine}`;
107
+ };
108
+ const wanted = ref?.replace(/^#/, '');
109
+ const exact = current.results.filter((r) => wanted && reference(r) === wanted);
110
+ const matches = key ? current.results.filter((r) => r.properties.claimKey === key) : exact;
111
+ if (matches.length !== 1) throw new Error('The kit must identify one current exposure; review its reference and remove obsolete Bravos binding headers before rebinding.');
112
+ if (wanted && reference(matches[0]) !== wanted) {
113
+ // A pure line move may retain its key. Never borrow an occupied sibling's former reference.
114
+ const site = (r) => r.replace(/:\d+$/, '');
115
+ if (!key || !/:\d+$/.test(wanted) || exact.length || site(wanted) !== site(reference(matches[0]))) {
116
+ throw new Error('The bound claim and source reference disagree; review the changed exposure and rebind the kit.');
117
+ }
118
+ }
119
+ const hit = matches[0];
120
+ const claim = hit.properties.claimKey;
121
+ const records = current.records.filter((r) => r.key === claim);
122
+ if (records.length !== 1) throw new Error('The exact claim is unavailable in the GuardLink ledger.');
123
+ const record = records[0];
124
+ const source = hit.locations[0].physicalLocation.artifactLocation.uri;
125
+ const fileDigest = sha(readFileSync(localFile(root, source)));
126
+ return { claim, source, fileDigest, record, threatId: hit.properties.threatId, asset: hit.properties.asset, threat: hit.properties.threat, logicalLine: hit.locations[0].physicalLocation.region.startLine,
127
+ origin: stamped ? 'cxg-stamped' : 'bravos-bound' };
128
+ }
129
+
130
+ // @comment -- "An error for a kit written before claim binding (no cxgProbe shape, or no bound claim key): a scheduled run reports it as needing review and bind, and does not count it as a failure, so an upgrade from an older Bravos does not fail every nightly."
131
+ function rebind(message) {
132
+ return Object.assign(new Error(message), { code: 'KIT_NEEDS_REBIND' });
133
+ }
134
+
135
+ const HASH_HEADER = /^\/\/[ \t]*@bravos_kit_sha256:[^\n]*(?:\n|$)/gm;
136
+ const kitBodyDigest = (text) => sha(text.replace(HASH_HEADER, ''));
137
+
138
+ // Machine-maintained binding to a single current claim. GuardLink's descriptive human-readable reference remains intact.
139
+ export function bindKit(root, filename) {
140
+ const kit = probe(root, filename);
141
+ const binding = resolveBinding(root, kit, model(root), true);
142
+ let body = kit.text.replace(HASH_HEADER, '');
143
+ if (!uniqueHeader(kit.text, 'bravos_claim_key', true) && !uniqueHeader(kit.text, 'exposure_claim_key', true)) {
144
+ body = `// @bravos_claim_key: ${binding.claim}\n${body}`;
145
+ }
146
+ const bound = `// @bravos_kit_sha256: ${sha(body)}\n${body}`;
147
+ if (bound !== kit.text) writeFileSync(kit.file, bound);
148
+ return binding.claim;
149
+ }
150
+
151
+ // YAML is parsed with the same PyYAML dependency as the CXG pipeline. Refuse duplicate keys and non-mapping inputs.
152
+ function parseScope(root, yaml) {
153
+ const script = `import json, sys, site
154
+ sys.path.append(site.getusersitepackages())
155
+ import yaml
156
+ class Unique(yaml.SafeLoader): pass
157
+ def mapping(loader, node):
158
+ pairs = loader.construct_pairs(node, deep=True)
159
+ result = dict(pairs)
160
+ if len(pairs) != len(result): raise ValueError("duplicate scope keys")
161
+ return result
162
+ Unique.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, mapping)
163
+ data=yaml.load(sys.stdin.read(), Loader=Unique)
164
+ if not isinstance(data,dict): raise ValueError("scope must be a mapping")
165
+ print(json.dumps(data))`;
166
+ return JSON.parse(invoke(process.env.CXG_PYTHON || 'python3', ['-I', '-c', script], tmpdir(), { input: yaml, env: sanitizedEnv(process.env) }).stdout);
167
+ }
168
+
169
+ const loopback = (host) => host === 'localhost' || host === '[::1]' || host === '127.0.0.1';
170
+
171
+ // @comment -- "One proving-policy value. The choice is read the way proving.mjs readProving reads it (its first word, lowercased), so the autopilot line and replay never disagree about what the person chose; other keys are taken as written."
172
+ function policyValue(text, key) {
173
+ const values = [...text.matchAll(new RegExp(`^${key}:[ \\t]*(.*?)[ \\t]*\\r?$`, 'gmi'))];
174
+ if (values.length > 1) throw new Error(`Ambiguous ${key} in proving policy.`);
175
+ const value = values[0]?.[1] || '';
176
+ return key === 'choice' ? (value.toLowerCase().split(/\s/)[0] ?? '') : value;
177
+ }
178
+
179
+ // Scheduled jobs run from the current default-branch revision before any authoring step. A superseded job cannot spend a revoked grant.
180
+ function checkScheduledHead(root, env) {
181
+ const branch = env.BRAVOS_DEFAULT_BRANCH;
182
+ if (!branch || env.GITHUB_REF !== `refs/heads/${branch}` || !/^[a-f0-9]{40}$/.test(env.GITHUB_SHA ?? '')) {
183
+ throw new Error('Nightly replay requires the default branch.');
184
+ }
185
+ const head = git(root, ['rev-parse', 'HEAD']).trim();
186
+ const remote = git(root, ['ls-remote', '--exit-code', 'origin', `refs/heads/${branch}`]).split(/\s/)[0];
187
+ if (head !== env.GITHUB_SHA || remote !== head) throw new Error('The default branch changed; this run no longer has current consent.');
188
+ }
189
+
190
+ // @mitigates #replay-target against #out-of-scope-replay using #replay-authority -- "authority checks committed policy and scope, choice, exact target and attestation before CXG receives the URL or identities. Scheduled use also checks the current default branch."
191
+ function authority(root, mode, env) {
192
+ if (mode === 'scheduled') checkScheduledHead(root, env);
193
+ // @mitigates #replay-target against #out-of-scope-replay using #replay-authority -- "an automatic run needs the grant on a reviewed default branch; in a repository with no origin default the agent's own commit would be the only check, so automatic runs are refused there and only run-once, with the person's typed authorization, remains."
194
+ if (mode === 'run' && spawnSync('git', ['symbolic-ref', '--quiet', 'refs/remotes/origin/HEAD'], { cwd: root, encoding: 'utf8' }).status !== 0) {
195
+ throw new Error('Automatic replay needs the proving policy on a reviewed default branch, and this repository has no origin default (git remote set-head origin --auto). Without one, use run-once with the person\'s typed authorization.');
196
+ }
197
+ const policy = committedFile(root, POLICY);
198
+ const required = { run: 'auto', 'run-once': 'ask', scheduled: 'schedule' }[mode];
199
+ if (!/^—\s*confirmed by\s+[^,\n]+,\s*\S+/mi.test(policy) || policyValue(policy, 'choice') !== required) {
200
+ throw new Error(`Replay requires a confirmed ${required} proving policy: .guardlink/proving.md with choice: ${required} and a "— confirmed by <name>, <date>" line, recorded with bravos-prove and merged to the default branch.`);
201
+ }
202
+ const scopeText = committedFile(root, SCOPE);
203
+ const scope = parseScope(root, scopeText);
204
+ const named = policyValue(policy, 'target');
205
+ const raw = mode === 'run' ? named : env.BRAVOS_SCAN_TARGET;
206
+ if (!raw) {
207
+ throw new Error(mode === 'run'
208
+ ? 'Automatic replay needs the loopback app it may test: add a line like target: http://localhost:3000/ to .guardlink/proving.md and merge it to the default branch (bravos-env).'
209
+ : 'Configure the owned target for this proving choice first (BRAVOS_SCAN_TARGET).');
210
+ }
211
+ const url = new URL(raw);
212
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash || (named && new URL(named).href !== url.href)) {
213
+ throw new Error('The target does not match the recorded HTTP(S) target.');
214
+ }
215
+ const local = loopback(url.hostname);
216
+ if (!local && (mode === 'run' || !(Array.isArray(scope.host_allowlist) && scope.host_allowlist.includes(url.hostname)))) {
217
+ throw new Error('The remote target is outside the reviewed scope.');
218
+ }
219
+ const rows = policy.split(/\r?\n/).map((s) => s.trim()).filter((s) => s.startsWith('"'));
220
+ let words;
221
+ if (mode === 'run' && rows.length === 1) {
222
+ try { words = JSON.parse(rows[0]); } catch { /* Old wizard accepted literal backslashes in a single quoted line. */
223
+ const legacy = /^"([^"]+)"$/.exec(rows[0]);
224
+ if (legacy) words = legacy[1];
225
+ }
226
+ }
227
+ const attestation = mode === 'run-once' ? env.BRAVOS_REPLAY_ATTESTATION :
228
+ mode === 'scheduled' ? scope.authorization_attestation : words;
229
+ if (typeof attestation !== 'string' || !attestation.trim()) throw new Error('This run needs the owner’s recorded authorization.');
230
+ const kits = policyValue(policy, 'kits');
231
+ if (kits && kits !== 'session' && kits !== 'reviewed') throw new Error('Unknown kit policy.');
232
+ // Older start explicitly labeled generation=no as "only replay tests I approved".
233
+ const legacyReviewed = !kits && policy.includes('Recorded by `bravos start`') && policyValue(policy, 'generation') === 'no';
234
+ return { target: url.href, local, attestation, scopeText, cxgScopeText: cxgScope(scope, scopeText, mode), policy, reviewedOnly: mode === 'run' && (kits === 'reviewed' || legacyReviewed) };
235
+ }
236
+
237
+ // @mitigates #replay-target against #out-of-scope-replay using #loopback-only-scope -- "an automatic run (mode run, no typed authorization) hands CXG a derived scope whose host_allowlist keeps only loopback names and whose disposable_host_grants is empty, so a committed scope that lists remote services for a person-run engagement never widens what an agent-written probe may reach. JSON is valid YAML, so the derived copy needs no YAML writer."
238
+ export function cxgScope(scope, scopeText, mode) {
239
+ if (mode !== 'run') return scopeText;
240
+ const hosts = Array.isArray(scope.host_allowlist) ? scope.host_allowlist : [];
241
+ return JSON.stringify({ ...scope, host_allowlist: hosts.filter((h) => { const n = String(h ?? '').trim().toLowerCase(); return loopback(n) || n === '::1'; }), disposable_host_grants: [] });
242
+ }
243
+
244
+ function sanitizedEnv(env) {
245
+ // Do not pass CI secrets, git credentials or model provider keys to replayed code.
246
+ return Object.fromEntries(Object.entries(env).filter(([k]) =>
247
+ ['PATH', 'HOME', 'TMPDIR', 'LANG', 'LC_ALL', 'CERT_X_GEN_HOME', 'CXG_PYTHON', 'PLAYWRIGHT_BROWSERS_PATH', 'SSL_CERT_FILE', 'VIRTUAL_ENV'].includes(k)));
248
+ }
249
+
250
+ function identityArgs(root, mode, env, dir) {
251
+ const names = (env.BRAVOS_SCAN_AUTH ?? '').split(',').map((s) => s.trim()).filter(Boolean);
252
+ if (!names.every((n) => PROFILE.test(n)) || new Set(names).size !== names.length) throw new Error('Invalid or duplicate CXG auth profile names.');
253
+ if (!names.length) return [];
254
+ if (mode !== 'scheduled') return ['--auth', names.join(','), ...(env.BRAVOS_AUTH_DIR ? ['--auth-dir', env.BRAVOS_AUTH_DIR] : [])];
255
+ const states = env.BRAVOS_AUTH_STATES ? parsedJson(env.BRAVOS_AUTH_STATES, 'the CI auth-state roster') : {};
256
+ if (!states || typeof states !== 'object' || Array.isArray(states)) throw new Error('The CI auth-state roster must map profile names to storage states.');
257
+ if (names.length === 1 && env.BRAVOS_AUTH_STATE && !states[names[0]]) states[names[0]] = env.BRAVOS_AUTH_STATE;
258
+ mkdirSync(dir, { mode: 0o700 });
259
+ for (const name of names) {
260
+ if (typeof states[name] !== 'string' || !states[name]) continue; // CXG reports the individual kit's missing prerequisite.
261
+ invoke('cxg', ['pentest', 'auth', 'import', '--profile', name, '--target', env.BRAVOS_SCAN_TARGET, '--storage-state', '-', '--auth-dir', dir, '--ci'], root,
262
+ { input: Buffer.from(states[name], 'base64'), env: sanitizedEnv(env) });
263
+ }
264
+ return ['--auth', names.join(','), '--auth-dir', dir];
265
+ }
266
+
267
+ function filesForSchedule(root) {
268
+ return git(root, ['ls-files', '-z', '--', '.guardlink/cxg-replay']).split('\0').filter((f) => f.endsWith('.js')).sort();
269
+ }
270
+
271
+ const noModel = (a) => a?.mode === 'no_author' && a.ranking === false && a.model_calls === 0 && a.generation === false && a.mutation_retries === 0;
272
+
273
+ // One exact JS source, one target, one engine execution. Ignore caller-declared scanner verdicts and reject rerouted/mixed/contradictory outcomes.
274
+ // @mitigates #replay-ledger against #misattributed-proof using #bound-engine-verdict -- "verdict matches the native session, selected JS source, staged path, template ID and vulnerability class to an individually adjudicated execution before returning an outcome."
275
+ export function verdict(combined, kit, binding, target, exitCode) {
276
+ const result = combined?.probe_results;
277
+ if (![0, 2, 4].includes(exitCode) || !noModel(result?.authoring) || result?.sessions?.length !== 1) return null;
278
+ const session = result.sessions[0];
279
+ const native = session.report;
280
+ if (session.target !== target || native?.target !== target || !noModel(native.authoring) || native.hard_killed || native.templates_executed !== 1) return null;
281
+ const mapping = session.templates;
282
+ if (mapping?.length !== 1 || mapping[0].template !== kit.id || mapping[0].source !== kit.file) return null;
283
+ const executions = native.probe_executions;
284
+ if (executions?.length !== 1 || executions[0].template !== kit.id || executions[0].path !== mapping[0].staged) return null;
285
+ const status = executions[0].status;
286
+ if (!['confirmed', 'refuted'].includes(status)) return null;
287
+ const found = native.confirmed_findings;
288
+ const held = native.mitigation_verifications;
289
+ if (!Array.isArray(found) || !Array.isArray(held)) return null;
290
+ const rows = status === 'confirmed' ? found : held;
291
+ const refused = [...(result.refused_probes ?? []), ...(native.auth_skipped ?? []), ...(native.probe_refusals ?? []), ...(native.not_run ?? [])];
292
+ if (refused.some((r) => r.template === kit.id || r.template_id === kit.id || r.path === mapping[0].staged || r.path === kit.file)) return null;
293
+ if (!rows.length || (status === 'confirmed' ? held : found).length || native.ambiguous?.length || native.identity_withdrawn?.length) return null;
294
+ for (const row of rows) {
295
+ if ((status === 'confirmed' && row.proof_status !== 'proven') || (row.proof_status != null && row.proof_status !== 'proven') || row.template_id !== kit.id || row.vuln_class !== kit.vulnClass || row.triage !== status || row.oracle_routed_from || row.original_claim ||
296
+ row.boundary_claim_key || !row.evidence || !Object.keys(row.evidence).length ||
297
+ (row.claim_key != null && row.claim_key !== binding.claim) ||
298
+ (binding.origin === 'cxg-stamped' && row.claim_key !== binding.claim) ||
299
+ (row.threat_id != null && row.threat_id !== binding.threatId) ||
300
+ (row.annotation != null && (row.annotation.file !== binding.source || row.annotation.line !== binding.logicalLine)) ||
301
+ (row.asset != null && row.asset !== binding.asset) || (row.threat != null && row.threat !== binding.threat)) return null;
302
+ }
303
+ return status;
304
+ }
305
+
306
+ function pendingReason(combined, exit) {
307
+ const sessions = combined?.probe_results?.sessions ?? [];
308
+ const reports = sessions.map((s) => s.report).filter(Boolean);
309
+ const refusals = [...(combined?.probe_results?.refused_probes ?? []), ...reports.flatMap((r) => r.probe_refusals ?? [])];
310
+ if (exit === 3) return 'engagement stopped by CXG';
311
+ if (exit === 5) return 'test login expired';
312
+ if (reports.some((r) => r.auth_skipped?.length) || refusals.some((r) => /identit|authenticat|login/i.test(r.reason ?? ''))) return 'required test identity unavailable';
313
+ if (reports.some((r) => r.identity_withdrawn?.length)) return 'CXG withdrew the claim identity';
314
+ if (reports.some((r) => r.ambiguous?.length)) return 'engine evidence inconclusive';
315
+ if (reports.some((r) => r.review_only_threats?.length || r.not_run?.length)) return 'required engine capability or test precondition unavailable';
316
+ if (refusals.length || exit === 4) return 'CXG refused the supplied probe or target';
317
+ if (exit === 1) return 'no executable template';
318
+ return 'no unique matching engine verdict';
319
+ }
320
+
321
+ function evidenceSummary(combined, state) {
322
+ if (!state) return [];
323
+ const native = combined.probe_results.sessions[0].report;
324
+ const rows = state === 'confirmed' ? native.confirmed_findings : native.mitigation_verifications;
325
+ const seen = new Set();
326
+ const codes = ['status', 'guest_status', 'attacker_status', 'entitled_status', 'control_status', 'benign_status'];
327
+ for (const row of rows) {
328
+ const ev = row.evidence;
329
+ // Never copy free text, response bodies, credentials, paths or URLs into the committed ledger.
330
+ for (const observation of [ev, ev?._cxg_refusal_control, ev?._cxg_missing_authn_oracle]) {
331
+ for (const field of codes) {
332
+ const n = observation?.[field];
333
+ if (Number.isInteger(n) && n >= 100 && n < 600) seen.add(`${field}=${n}`);
334
+ }
335
+ }
336
+ }
337
+ return [...seen].sort();
338
+ }
339
+
340
+ // @exposes #replay-ledger to #concurrent-claim-change [medium] cwe:CWE-367 -- "record() passes record.file and record.line to invoke() for the GuardLink ledger write. A concurrent editor can move the declaration after resolveBinding() checks binding.claim. GuardLink accepts no expected claim key or anchor on that command."
341
+ // @audit #replay-ledger -- "The Joseph lock serializes Joseph writers. GuardLink needs an atomic expected-key and expected-anchor write to prevent a race with external writers. The ledger readback detects a mismatch after the write."
342
+ function record(root, state, binding, kit, receipt) {
343
+ const expected = receipt.provenance;
344
+ const record = binding.record;
345
+ const evidence = `CXG engine ${state} for ${kit.vulnClass}; ${receipt.statuses.join(', ') || 'no HTTP status summary'}. ` +
346
+ `Receipt ${receipt.id}${receipt.ciRun ? ' (Actions run ' + receipt.ciRun + ')' : ''}; kit ${kit.id} sha256 ${kit.digest}; ` +
347
+ `native evidence sha256 ${receipt.evidenceDigest}; checkout ${receipt.checkout}; worktree sha256 ${receipt.worktreeSha256}; ` +
348
+ `source sha256 ${binding.fileDigest}; ${receipt.build}; binding ${binding.origin}.`;
349
+ if (record.outcome?.by === expected && record.state === state && record.outcome.evidence === evidence) return;
350
+ // Write only the checked fact and a receipt; response bodies, cookies and account details remain private.
351
+ invoke('guardlink', ['hypothesis', state === 'confirmed' ? 'confirm' : 'refute', `${record.file}:${record.line}`, '--by', expected, '--evidence', evidence], root);
352
+ const reread = jsonTool(root, 'guardlink', ['hypothesis', 'list', '--json']).records.filter((r) => r.key === binding.claim);
353
+ if (reread.length !== 1 || reread[0].state !== state || reread[0].outcome?.by !== expected || reread[0].outcome?.evidence !== evidence) {
354
+ throw new Error('GuardLink did not persist the expected tested state and evidence on this claim.');
355
+ }
356
+ }
357
+
358
+ function sameAuthority(root, mode, env, expected) {
359
+ const now = authority(root, mode, env);
360
+ if (now.policy !== expected.policy || now.scopeText !== expected.scopeText || now.target !== expected.target || now.attestation !== expected.attestation) {
361
+ throw new Error('Target authorization changed during replay.');
362
+ }
363
+ }
364
+
365
+ // Fingerprint Git-tracked and nonignored untracked inputs, including dirty files, modes and symlink destinations.
366
+ // Build artifacts and external services remain the launcher's responsibility. The ledger is the writer's output.
367
+ export function sourceDigest(root) {
368
+ const hash = createHash('sha256');
369
+ // HEAD captures unchanged tracked blobs, modes and gitlinks cheaply. Hash actual bytes only for changed and untracked inputs.
370
+ hash.update(git(root, ['rev-parse', 'HEAD']).trim()).update('\0');
371
+ const trackedChanges = git(root, ['diff', '--no-ext-diff', '--ignore-submodules=none', '--no-renames', '--name-only', '-z', 'HEAD', '--']).split('\0').filter(Boolean);
372
+ const untracked = git(root, ['ls-files', '--others', '--exclude-standard', '-z']).split('\0').filter(Boolean)
373
+ .filter((f) => !f.endsWith('/') || !/^\.(?:claude|codex)\/worktrees\//.test(f));
374
+ const files = [...trackedChanges, ...untracked].sort();
375
+ const buffer = Buffer.alloc(65536);
376
+ for (const file of new Set(files)) {
377
+ if (file === '.guardlink/hypotheses.json') continue;
378
+ hash.update(file).update('\0');
379
+ const path = join(root, file);
380
+ let stat;
381
+ try { stat = lstatSync(path); } catch (error) { if (error.code === 'ENOENT') { hash.update('deleted\0'); continue; } throw error; }
382
+ hash.update(String(stat.mode & 0o111)).update('\0');
383
+ if (stat.isSymbolicLink()) { hash.update('link:').update(readlinkSync(path)).update('\0'); continue; }
384
+ if (!stat.isFile()) throw new Error('Cannot identify a changed Git submodule, untracked nested repository or special input. Use a clean submodule or exclude unrelated build inputs with Git.');
385
+ const item = createHash('sha256');
386
+ const fd = openSync(path, 'r');
387
+ try { let n; while ((n = readSync(fd, buffer)) > 0) item.update(buffer.subarray(0, n)); } finally { closeSync(fd); }
388
+ hash.update(item.digest('hex')).update('\0');
389
+ }
390
+ return hash.digest('hex');
391
+ }
392
+
393
+ function boundBuild(permit, env, digest) {
394
+ if (!permit.local || !env.BRAVOS_REPLAY_BUILD) return false;
395
+ const witness = parsedJson(env.BRAVOS_REPLAY_BUILD, 'the build witness');
396
+ return witness.target === permit.target && witness.sourceSha256 === digest;
397
+ }
398
+
399
+ function executeKit(root, mode, env, auth, permit, filename, privateDir, runId) {
400
+ const kit = probe(root, filename);
401
+ if (permit.reviewedOnly) {
402
+ // With no remote default, the policy commit bounds the set already present when consent was given.
403
+ const ref = spawnSync('git', ['symbolic-ref', '-q', 'refs/remotes/origin/HEAD'], { cwd: root, encoding: 'utf8' });
404
+ const base = ref.status === 0 ? ref.stdout.trim() : git(root, ['log', '-1', '--format=%H', 'HEAD', '--', POLICY]).trim();
405
+ const reviewed = spawnSync('git', ['show', base + ':' + relative(root, kit.file)], { cwd: root, maxBuffer: 2 * 1024 * 1024 });
406
+ if (reviewed.status !== 0 || sha(reviewed.stdout) !== kit.digest) {
407
+ throw new Error('The automatic policy permits reviewed kits only. This bound kit must match the reviewed base before replay.');
408
+ }
409
+ }
410
+ if (mode === 'scheduled') committedFile(root, relative(root, kit.file));
411
+ const snapshot = model(root);
412
+ const initial = resolveBinding(root, kit, snapshot);
413
+ const inputDigest = sourceDigest(root);
414
+ const attested = boundBuild(permit, env, inputDigest);
415
+ const head = git(root, ['rev-parse', 'HEAD']).trim();
416
+ sameAuthority(root, mode, env, permit);
417
+ const dir = mkdtempSync(join(privateDir, 'kit-'));
418
+ // Replay needs the exact SARIF snapshot for CXG's stamp verification, never an old whitebox export in the checkout.
419
+ const snapshotRoot = join(dir, 'model');
420
+ mkdirSync(join(snapshotRoot, 'whitebox'), { recursive: true, mode: 0o700 });
421
+ writeFileSync(join(snapshotRoot, 'whitebox', 'findings.sarif'), JSON.stringify(snapshot.sarif), { mode: 0o600 });
422
+ const scopePath = join(dir, 'scope.yaml');
423
+ writeFileSync(scopePath, permit.cxgScopeText ?? permit.scopeText, { mode: 0o600 });
424
+ // Freeze the exact bytes selected for this execution outside the mutable checkout. CXG maps that file to its staged probe.
425
+ const stagedKit = join(dir, 'kit.js');
426
+ writeFileSync(stagedKit, kit.text, { mode: 0o600 });
427
+ const scan = invoke('cxg', ['scan', '--scope', permit.target, '--templates', stagedKit, '--no-author', '--no-code-graph', '--codebase', snapshotRoot, '--scope-file', scopePath,
428
+ '--attestation', permit.attestation, '--ci', ...auth, '--session-dir', join(dir, 'sessions'), '--output', join(dir, 'combined'), '--output-format', 'json'],
429
+ root, { env: sanitizedEnv(env), allowed: [0, 1, 2, 3, 4, 5], timeout: 15 * 60 * 1000 });
430
+ const output = join(dir, 'combined.json');
431
+ if (!existsSync(output)) throw new Error(`CXG exited ${scan.status} without a structured report. Check that cxg scan supports supplied JS and --no-author.`);
432
+ const bytes = readFileSync(output);
433
+ const combined = parsedJson(bytes, 'the CXG report');
434
+ const result = verdict(combined, { ...kit, file: stagedKit }, initial, permit.target, scan.status);
435
+ const receipt = {
436
+ schema: 'bravos.replay/v1', id: sha(`${runId}\n${filename}\n${kit.digest}`).slice(0, 32), at: new Date().toISOString(),
437
+ kit: relative(root, kit.file), kitId: kit.id, vulnClass: kit.vulnClass, kitSha256: kit.digest, claimKey: initial.claim, binding: initial.origin,
438
+ sourceSha256: initial.fileDigest, checkout: head, targetHost: new URL(permit.target).host,
439
+ worktreeSha256: inputDigest, build: attested ? 'operator-attested loopback build' : 'target revision unverified', exit: scan.status, observed: result, recorded: false,
440
+ evidenceDigest: sha(bytes), statuses: evidenceSummary(combined, result), ciRun: /^\d+$/.test(env.GITHUB_RUN_ID ?? '') ? env.GITHUB_RUN_ID : null, reason: result ? (attested ? null : 'target build unverified') : pendingReason(combined, scan.status),
441
+ };
442
+ receipt.provenance = `bravos:cxg:${receipt.id}`;
443
+ const saveReceipt = () => writeFileSync(join(dir, 'receipt.json'), JSON.stringify(receipt, null, 2) + '\n', { mode: 0o600 });
444
+ saveReceipt();
445
+ if (result && attested) {
446
+ sameAuthority(root, mode, env, permit);
447
+ const latest = probe(root, filename);
448
+ const after = resolveBinding(root, latest, model(root));
449
+ if (sourceDigest(root) !== inputDigest || head !== git(root, ['rev-parse', 'HEAD']).trim() || latest.digest !== kit.digest || after.claim !== initial.claim || after.fileDigest !== initial.fileDigest) {
450
+ throw new Error('The kit, commit or tested source changed during replay. The run was not recorded against current code.');
451
+ }
452
+ sameAuthority(root, mode, env, permit);
453
+ record(root, result, after, kit, receipt);
454
+ receipt.recorded = true;
455
+ }
456
+ saveReceipt();
457
+ return receipt;
458
+ }
459
+
460
+ function output(value, env) {
461
+ console.log(value);
462
+ if (env.GITHUB_STEP_SUMMARY) writeFileSync(env.GITHUB_STEP_SUMMARY, value + '\n', { flag: 'a' });
463
+ }
464
+
465
+ export function replay(root, mode, names, env = process.env) {
466
+ const permit = authority(root, mode, env);
467
+ names = mode === 'scheduled' ? filesForSchedule(root) : names;
468
+ if (!names.length) { output('No replay kits selected; zero claims tested.', env); return []; }
469
+ const features = invoke('cxg', ['scan', '--help'], root).stdout;
470
+ if (!features.includes('--no-author') || !features.includes('--scope-file')) throw new Error('This installed cxg scan lacks model-free, scoped JS replay; install a compatible CXG build.');
471
+ const authDir = mkdtempSync(join(tmpdir(), 'bravos-auth-'));
472
+ const evidenceRoot = mode === 'scheduled' ? env.RUNNER_TEMP : join(env.BRAVOS_HOME || join(homedir(), '.bravos'), 'replay-evidence');
473
+ mkdirSync(evidenceRoot, { recursive: true, mode: 0o700 });
474
+ const evidencePath = realpathSync(evidenceRoot);
475
+ if (evidencePath === root || evidencePath.startsWith(root + sep)) throw new Error('Store raw replay evidence outside the worktree.');
476
+ const dir = mkdtempSync(join(evidencePath, 'replay-'));
477
+ const runId = env.GITHUB_RUN_ID ? `${env.GITHUB_RUN_ID}/${env.GITHUB_RUN_ATTEMPT || '1'}` : randomUUID();
478
+ const lock = join(git(root, ['rev-parse', '--absolute-git-dir']).trim(), 'bravos-replay.lock');
479
+ let locked = false;
480
+ try {
481
+ try { mkdirSync(lock, { mode: 0o700 }); } catch (error) {
482
+ if (error.code === 'EEXIST') throw new Error('Another replay owns the Git lock. If that process has ended, remove bravos-replay.lock in the Git directory and retry.');
483
+ throw error;
484
+ }
485
+ locked = true; writeFileSync(join(lock, 'pid'), String(process.pid), { mode: 0o600 });
486
+ const auth = identityArgs(root, mode, env, join(authDir, 'profiles'));
487
+ const receipts = [];
488
+ let failed = 0;
489
+ const needsBind = [];
490
+ for (const name of names) {
491
+ try {
492
+ const receipt = executeKit(root, mode, env, auth, permit, name, dir, runId);
493
+ receipts.push(receipt);
494
+ output(`${receipt.kitId}: ${receipt.observed || 'inconclusive or not run'}; ${receipt.recorded ? 'recorded in GuardLink' : 'no current claim recorded'}${receipt.reason ? ' (' + receipt.reason + ')' : ''} (CXG exit ${receipt.exit}).`, env);
495
+ if (mode === 'scheduled' && env.GITHUB_STEP_SUMMARY) {
496
+ const details = `Receipt ${receipt.id}, class ${receipt.vulnClass}, claim ${receipt.claimKey}, ${receipt.build}; ` +
497
+ `${receipt.statuses.join(', ') || 'no HTTP status summary'}. Kit ${receipt.kitSha256}, build ${receipt.worktreeSha256}, evidence ${receipt.evidenceDigest}.\n`;
498
+ writeFileSync(env.GITHUB_STEP_SUMMARY, details, { flag: 'a' });
499
+ }
500
+ if ([3, 5].includes(receipt.exit)) {
501
+ failed++;
502
+ output(`CXG stopped the engagement (exit ${receipt.exit}); ${names.length - names.indexOf(name) - 1} remaining kits were not run.`, env);
503
+ break;
504
+ }
505
+ } catch (error) {
506
+ if (mode !== 'scheduled') throw error;
507
+ if (error.code === 'KIT_NEEDS_REBIND') { needsBind.push(name); continue; }
508
+ failed++;
509
+ output(`A scheduled kit could not be recorded: ${error.message}`, env);
510
+ }
511
+ }
512
+ const confirmed = receipts.filter((r) => r.recorded && r.observed === 'confirmed').length;
513
+ const held = receipts.filter((r) => r.recorded && r.observed === 'refuted').length;
514
+ if (needsBind.length) {
515
+ output(`${needsBind.length} kit(s) predate claim binding and were not run: ${needsBind.join(', ')}. Review each, then run node .bravos/hooks/lib/replay.mjs bind <kit.js> (bravos-templatize) and merge it.`, env);
516
+ }
517
+ const summary = `Replay recorded ${confirmed} confirmed and ${held} refuted; ${names.length - confirmed - held} kits without a recorded outcome${needsBind.length ? ` (${needsBind.length} need review and bind)` : ''}.`;
518
+ output(summary, env);
519
+ if (mode === 'scheduled' && env.GITHUB_OUTPUT) writeFileSync(env.GITHUB_OUTPUT, `summary=${summary}\n`, { flag: 'a' });
520
+ if (failed) throw new Error(`${failed} replay kit(s) had a precondition, execution or writeback failure.`);
521
+ return receipts;
522
+ } finally {
523
+ if (locked) rmSync(lock, { recursive: true, force: true });
524
+ rmSync(authDir, { recursive: true, force: true });
525
+ if (mode === 'scheduled') rmSync(dir, { recursive: true, force: true });
526
+ else console.log(`Private replay evidence: ${dir}`);
527
+ }
528
+ }
529
+
530
+ async function main() {
531
+ const [cmd, ...args] = process.argv.slice(2);
532
+ const root = realpathSync(git(process.cwd(), ['rev-parse', '--show-toplevel']).trim());
533
+ if (cmd === 'check-port' && args.length === 1) {
534
+ const target = new URL(args[0]);
535
+ if (!loopback(target.hostname) || !['http:', 'https:'].includes(target.protocol)) throw new Error('A local build needs a loopback target.');
536
+ await new Promise((ok, fail) => {
537
+ const socket = createConnection({ host: target.hostname.replace(/^\[|\]$/g, ''), port: Number(target.port) || (target.protocol === 'https:' ? 443 : 80) });
538
+ socket.on('connect', () => { socket.destroy(); fail(new Error('The target port is already occupied. Cannot identify a freshly started build.')); });
539
+ socket.on('error', (error) => error.code === 'ECONNREFUSED' ? ok() : fail(error));
540
+ socket.setTimeout(3000, () => { socket.destroy(); fail(new Error('Unable to check the loopback port.')); });
541
+ });
542
+ return;
543
+ }
544
+ if (cmd === 'build' && args.length === 1) {
545
+ const target = new URL(args[0]);
546
+ if (!['http:', 'https:'].includes(target.protocol) || !loopback(target.hostname) || target.username || target.password || target.search || target.hash) throw new Error('Build witnesses apply to loopback HTTP targets only.');
547
+ console.log(JSON.stringify({ target: target.href, sourceSha256: sourceDigest(root) })); return;
548
+ }
549
+ if (cmd === 'bind' && args.length === 1) { console.log(bindKit(root, args[0])); return; }
550
+ if (cmd === 'scheduled-drafts' && !args.length) {
551
+ try {
552
+ checkScheduledHead(root, process.env);
553
+ const policy = committedFile(root, POLICY);
554
+ console.log(/^—\s*confirmed by\s+[^,\n]+,\s*\S+/mi.test(policy) && policyValue(policy, 'choice') === 'schedule' ? 'yes' : 'no');
555
+ } catch { console.log('no'); }
556
+ return;
557
+ }
558
+ if (cmd === 'scheduled-ready' && !args.length) {
559
+ try {
560
+ if (!process.env.BRAVOS_SCAN_TARGET || !existsSync(join(root, POLICY)) || !existsSync(join(root, SCOPE))) throw new Error('Scheduled proving is not configured.');
561
+ const permit = authority(root, 'scheduled', process.env);
562
+ if (!filesForSchedule(root).length) throw new Error('No committed replay kits.');
563
+ if (permit.local && !process.env.BRAVOS_APP_START) throw new Error('A loopback target needs BRAVOS_APP_START.');
564
+ console.log(permit.local ? 'loopback' : 'remote');
565
+ } catch (error) {
566
+ console.error(error.message); console.log('disabled');
567
+ if (process.env.GITHUB_STEP_SUMMARY) writeFileSync(process.env.GITHUB_STEP_SUMMARY, `Scheduled proof is off: ${error.message}\n`, { flag: 'a' });
568
+ }
569
+ return;
570
+ }
571
+ if ((['run', 'run-once'].includes(cmd) && args.length === 1) || (cmd === 'scheduled' && !args.length)) {
572
+ replay(root, cmd, args); return;
573
+ }
574
+ throw new Error('Use bind <kit.js>, run <kit.js>, run-once <kit.js>, or scheduled.');
575
+ }
576
+
577
+ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
578
+ try { await main(); } catch (err) { console.error(`Bravos replay: ${err.message}`); process.exitCode = 1; }
579
+ }
@@ -8,6 +8,14 @@ const SIGIL = { claude: '/', codex: '$', omp: '/skill:', opencode: '/' };
8
8
  /** A skill the person can invoke: /bravos-x, $bravos-x, /skill:bravos-x, or "the bravos-x skill" elsewhere. */
9
9
  const skill = (name, harness) => (SIGIL[harness] ? `${SIGIL[harness]}${name}` : `the ${name} skill`);
10
10
 
11
+ /** How a person without a licence starts one; the same words the plan line uses. */
12
+ export const TRIAL = 'bravos account activate starts a 30-day Team trial, no card';
13
+
14
+ // @comment -- "True when this person's licence is known and does not cover the paid hooks (autopilot, pre-PR gate): a repo can register them for everyone, but each one checks the licence of whoever runs it, so for this person they do nothing. An unknown licence (inputs without one) is not locked, which keeps older callers' readings."
15
+ export function hooksLocked(i) {
16
+ return i?.licence?.licensed === false;
17
+ }
18
+
11
19
  // @comment -- "Builds the nine setup items in dependency order: the code graph first (a machine step every later skill reads), then intent (people), coverage (annotate reads intent and the graph), SAST (reads the annotations), how findings are proven and a test target (needed to test), then the gates (autopilot, pre-PR, CI). Each has its done-state, what it unlocks and how, with skills in the harness syntax. bravos assumes a licensed bravos-cli, so a missing one is a to-do, not 'not available'."
12
20
  export function readSetup(root, i = {}, harness = 'other') {
13
21
  const coverage = Number(i.guardlink?.ci?.summary?.coverage?.percent);
@@ -62,19 +70,20 @@ export function readSetup(root, i = {}, harness = 'other') {
62
70
  },
63
71
  {
64
72
  id: 'autopilot',
65
- on: !!i.autopilot,
73
+ // Registered in the repo is not on for this person: without a licence the hook answers nothing.
74
+ on: !!i.autopilot && !hooksLocked(i),
66
75
  label: 'turn on autopilot',
67
- cta: 'bravos sync --autopilot',
76
+ cta: i.autopilot && hooksLocked(i) ? 'bravos account activate' : 'bravos sync --autopilot',
68
77
  unlocks: 'annotations and rechecks happen at the end of each turn without being asked',
69
- how: 'bravos sync --autopilot (cheap; fine to switch on early)',
78
+ how: i.autopilot && hooksLocked(i) ? `installed in this repo, but on the Team plan for you: ${TRIAL}` : 'bravos sync --autopilot (cheap; fine to switch on early)',
70
79
  },
71
80
  {
72
81
  id: 'prepr',
73
- on: !!i.prePr,
82
+ on: !!i.prePr && !hooksLocked(i),
74
83
  label: 'turn on the pre-PR gate',
75
- cta: 'bravos sync --pre-pr-hook',
84
+ cta: i.prePr && hooksLocked(i) ? 'bravos account activate' : 'bravos sync --pre-pr-hook',
76
85
  unlocks: 'no pull request goes out with undisclosed exposure or a confirmed exploit',
77
- how: 'bravos sync --pre-pr-hook (autopilot turns it on too)',
86
+ how: i.prePr && hooksLocked(i) ? `installed in this repo, but on the Team plan for you: ${TRIAL}` : 'bravos sync --pre-pr-hook (autopilot turns it on too)',
78
87
  },
79
88
  {
80
89
  id: 'ci',