@bugb-technologies/bravos 1.2.1 → 1.4.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 +17 -10
- package/dist/ci.js +11 -3
- package/dist/cli.js +50 -8
- package/dist/doctor.js +4 -16
- package/dist/guide.js +5 -3
- package/dist/help.js +16 -16
- package/dist/hooks.js +21 -0
- package/dist/install-proof-tool.js +117 -0
- package/dist/proof-tools.js +29 -0
- package/dist/report/check.js +4 -1
- package/dist/report/data.js +81 -149
- package/dist/report/markdown.js +1 -1
- package/dist/report/redact.js +16 -0
- package/dist/report/runs.js +169 -0
- package/dist/resync.js +272 -0
- package/dist/setup.js +31 -16
- package/dist/start/answers.js +5 -3
- package/dist/start/index.js +28 -14
- package/dist/versions.js +4 -3
- package/docs/GUIDE.md +12 -2
- package/hooks/lib/autopilot.mjs +216 -77
- package/hooks/lib/briefing.mjs +36 -5
- package/hooks/lib/nightly-stage.mjs +66 -0
- package/hooks/lib/nightly-tools.sh +45 -0
- package/hooks/lib/pre-pr.mjs +88 -17
- package/hooks/lib/proof-tool-pins.json +12 -0
- package/hooks/lib/replay.mjs +579 -0
- package/hooks/lib/resync.mjs +78 -0
- package/hooks/lib/setup.mjs +15 -6
- package/hooks/lib/snapshot.mjs +189 -0
- package/hooks/session-start.mjs +7 -3
- package/package.json +1 -1
- package/skills/bravos/SKILL.md +2 -1
- package/skills/bravos-annotate/SKILL.md +6 -5
- package/skills/bravos-annotate/scripts/slice.mjs +15 -8
- package/skills/bravos-cicd/SKILL.md +1 -1
- package/skills/bravos-env/SKILL.md +3 -3
- package/skills/bravos-prove/SKILL.md +11 -15
- package/skills/bravos-recheck/SKILL.md +3 -3
- package/skills/bravos-report/SKILL.md +1 -1
- package/skills/bravos-resync/SKILL.md +52 -0
- package/skills/bravos-schedule/SKILL.md +1 -1
- package/skills/bravos-ship/SKILL.md +1 -1
- package/skills/bravos-templatize/SKILL.md +3 -3
- package/templates/workflows/bravos-nightly-claude.yml +131 -74
- package/templates/workflows/bravos-nightly-codex.yml +130 -73
- package/templates/workflows/bravos-pr-gate.yml +88 -14
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// @comment -- "Staleness and stranded-work facts shared by the session briefing, the autopilot Stop hook and bravos resync: how far the checkout's branch is behind its base (as of the last fetch, never fetching), and which local branches carry .guardlink/ work their base does not have. Read-only git calls through a runner the caller supplies (argv, no shell); every failure reads as nothing to report."
|
|
2
|
+
|
|
3
|
+
/** A branch this many commits behind its base is stale whatever its age. */
|
|
4
|
+
export const STALE_BEHIND = 20;
|
|
5
|
+
/** A branch any number of commits behind is stale once its shared base is older than this. */
|
|
6
|
+
export const STALE_DAYS = 7;
|
|
7
|
+
/** How many local branches, most recently committed first, are looked at for stranded annotation work. */
|
|
8
|
+
export const STRANDED_SCAN = 10;
|
|
9
|
+
|
|
10
|
+
const DAY_MS = 86400000;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Decides whether a checkout is stale. `behind` is commits on the base not on HEAD; `baseAge` is the
|
|
14
|
+
* shared base's commit time in seconds. Returns { behind, baseDate } or null when nothing is worth saying.
|
|
15
|
+
*/
|
|
16
|
+
// @comment -- "Pure threshold: stale at STALE_BEHIND commits behind, or any commits behind with a shared base older than STALE_DAYS; never stale on the base branch itself or with unreadable inputs."
|
|
17
|
+
export function staleness({ behind, baseAge, branch, base, now = Date.now() } = {}) {
|
|
18
|
+
const n = Number(behind);
|
|
19
|
+
if (!Number.isFinite(n) || n <= 0) return null;
|
|
20
|
+
if (branch && base && (base === branch || base.endsWith(`/${branch}`))) return null;
|
|
21
|
+
const at = Number(baseAge) * 1000;
|
|
22
|
+
const old = Number.isFinite(at) && at > 0 && now - at > STALE_DAYS * DAY_MS;
|
|
23
|
+
if (n < STALE_BEHIND && !old) return null;
|
|
24
|
+
return { behind: n, baseDate: Number.isFinite(at) && at > 0 ? new Date(at).toISOString().slice(0, 10) : null };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Reads behind-count and shared-base time for HEAD against `base`. `git(args)` resolves to trimmed
|
|
29
|
+
* stdout or null. Resolves { behind, baseAge } with nulls where git could not answer.
|
|
30
|
+
*/
|
|
31
|
+
// @comment -- "Two read-only git calls against the last-fetched base ref: rev-list --count HEAD..base and the merge-base's commit time."
|
|
32
|
+
export async function gitStaleness(git, base) {
|
|
33
|
+
const [behind, mb] = await Promise.all([git(['rev-list', '--count', `HEAD..${base}`]), git(['merge-base', 'HEAD', base])]);
|
|
34
|
+
const baseAge = mb ? await git(['log', '-1', '--format=%ct', mb]) : null;
|
|
35
|
+
return { behind: behind === null ? null : Number(behind), baseAge: baseAge === null ? null : Number(baseAge) };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Local branches that look left behind (no commit for STALE_DAYS) yet carry `.guardlink/` changes their
|
|
40
|
+
* base does not have: [{ branch, files }], most recently committed first. A branch being worked on is a
|
|
41
|
+
* feature branch, not stranded work, so it is never listed; nor is `current` (the stale line covers it).
|
|
42
|
+
*/
|
|
43
|
+
// @comment -- "Lists up to STRANDED_SCAN local branches by recency, keeps those idle for STALE_DAYS other than the base and the current branch, and counts the .guardlink/ files each changed since it left base (base...branch); branches with nothing there are dropped."
|
|
44
|
+
export async function strandedBranches(git, base, { scan = STRANDED_SCAN, current = null, now = Date.now() } = {}) {
|
|
45
|
+
const refs = await git(['for-each-ref', '--sort=-committerdate', `--count=${scan}`, '--format=%(refname:short) %(committerdate:unix)', 'refs/heads']);
|
|
46
|
+
if (!refs) return [];
|
|
47
|
+
const short = base.replace(/^origin\//, '');
|
|
48
|
+
const names = refs
|
|
49
|
+
.split('\n')
|
|
50
|
+
.map((l) => l.trim().split(' '))
|
|
51
|
+
.filter(([name, at]) => name && name !== short && name !== current && now - Number(at) * 1000 > STALE_DAYS * DAY_MS)
|
|
52
|
+
.map(([name]) => name);
|
|
53
|
+
const found = await Promise.all(
|
|
54
|
+
names.map(async (branch) => {
|
|
55
|
+
const out = await git(['diff', '--name-only', `${base}...${branch}`, '--', '.guardlink/']);
|
|
56
|
+
const files = out ? out.split('\n').filter(Boolean).length : 0;
|
|
57
|
+
return files > 0 ? { branch, files } : null;
|
|
58
|
+
}),
|
|
59
|
+
);
|
|
60
|
+
return found.filter(Boolean);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The briefing line for a stale checkout, or null. */
|
|
64
|
+
// @comment -- "Formats the stale-checkout line the agent reads: how far behind, since when, and the two ways out (update the branch, or carry its annotations with bravos-resync)."
|
|
65
|
+
export function staleLine(s, { branch, base }) {
|
|
66
|
+
if (!s) return null;
|
|
67
|
+
const since = s.baseDate ? ` (shared base ${s.baseDate}, as of last fetch)` : ' (as of last fetch)';
|
|
68
|
+
return `Branch: ${branch ?? 'this checkout'} is ${s.behind} commits behind ${base}${since}. The model below describes that older code: update the branch, or carry its annotation work to ${base} with bravos-resync.`;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The briefing line for stranded annotation work, or null. */
|
|
72
|
+
// @comment -- "Formats the stranded-work line: up to three branches with their .guardlink/ file counts, then a count of the rest."
|
|
73
|
+
export function strandedLine(list, base) {
|
|
74
|
+
if (!Array.isArray(list) || list.length === 0) return null;
|
|
75
|
+
const shown = list.slice(0, 3).map((b) => `${b.branch} (${b.files} files)`).join(', ');
|
|
76
|
+
const more = list.length > 3 ? ` and ${list.length - 3} more` : '';
|
|
77
|
+
return `Annotation work not on ${base}: ${shown}${more}; bravos-resync carries it.`;
|
|
78
|
+
}
|
package/hooks/lib/setup.mjs
CHANGED
|
@@ -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:
|
|
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',
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
// @comment -- "The session-start snapshot autopilot compares against: the working-tree changes present when a session began (path to content fingerprint) and HEAD at that moment, written to .bravos/watch/turn-base/<session_id>.json (the watch folder ignores itself), plus the read-only spawn runner both hooks use. Kept apart from autopilot.mjs because the session-start hook imports it and plugin hook bundles ship without the autopilot module."
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { spawn } from 'node:child_process';
|
|
4
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, readlinkSync, lstatSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
|
|
7
|
+
const OUTPUT_CAP = 64 * 1024 * 1024;
|
|
8
|
+
|
|
9
|
+
// @comment -- "Async spawn with the pre-PR runner's result shape: argv array, no shell, stdin closed, output capped, killed at timeoutMs; never rejects."
|
|
10
|
+
export function asyncRunner(cmd, args, { cwd, env, timeoutMs = 20000 }) {
|
|
11
|
+
return new Promise((resolve) => {
|
|
12
|
+
let child;
|
|
13
|
+
try {
|
|
14
|
+
child = spawn(cmd, args, { cwd, env, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
15
|
+
} catch (e) {
|
|
16
|
+
resolve({ missing: e?.code === 'ENOENT', error: e?.code ?? String(e), status: null, stdout: '' });
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
const chunks = [];
|
|
20
|
+
let size = 0;
|
|
21
|
+
let done = false;
|
|
22
|
+
const finish = (r) => {
|
|
23
|
+
if (done) return;
|
|
24
|
+
done = true;
|
|
25
|
+
clearTimeout(timer);
|
|
26
|
+
resolve(r);
|
|
27
|
+
};
|
|
28
|
+
child.stdout.on('data', (b) => {
|
|
29
|
+
size += b.length;
|
|
30
|
+
if (size > OUTPUT_CAP) {
|
|
31
|
+
child.kill('SIGKILL');
|
|
32
|
+
finish({ status: null, error: 'EOUTPUTLIMIT', stdout: '' });
|
|
33
|
+
} else chunks.push(b);
|
|
34
|
+
});
|
|
35
|
+
const timer = setTimeout(() => {
|
|
36
|
+
child.kill('SIGKILL');
|
|
37
|
+
finish({ status: null, error: 'ETIMEDOUT', stdout: '' });
|
|
38
|
+
}, timeoutMs);
|
|
39
|
+
child.on('error', (e) => finish({ missing: e.code === 'ENOENT', error: e.code ?? e.message, status: null, stdout: '' }));
|
|
40
|
+
child.on('close', (status) => finish({ status, stdout: Buffer.concat(chunks).toString('utf8') }));
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Files changed in the working tree since HEAD, tracked or not (bravos's own files included). */
|
|
45
|
+
// @comment -- "Lists working-tree changes since HEAD (git diff --name-only HEAD) plus untracked files (ls-files --others --exclude-standard); read-only argv spawns."
|
|
46
|
+
export async function workingChanges(root, env, run) {
|
|
47
|
+
const o = { cwd: root, env };
|
|
48
|
+
const out = new Set();
|
|
49
|
+
const [diff, untracked] = await Promise.all([
|
|
50
|
+
run('git', ['diff', '--name-only', 'HEAD', '-z', '--no-renames', '--'], o),
|
|
51
|
+
run('git', ['ls-files', '-z', '--others', '--exclude-standard'], o),
|
|
52
|
+
]);
|
|
53
|
+
for (const result of [diff, untracked]) {
|
|
54
|
+
if (result.status === 0) for (const path of result.stdout.split('\0')) if (path) out.add(path);
|
|
55
|
+
}
|
|
56
|
+
return out;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** A session id safe to use as a file name, or null. */
|
|
60
|
+
// @comment -- "Path-traversal guard: the Stop and SessionStart payloads' session_id becomes a file name only when it is 1-128 characters of [A-Za-z0-9_-]; anything else (a slash, dots, empty) means no snapshot, never a path outside .bravos/watch/turn-base"
|
|
61
|
+
export function safeSessionId(id) {
|
|
62
|
+
return typeof id === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(id) ? id : null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export const SNAPSHOT_MAX_FILES = 2000;
|
|
66
|
+
const SNAPSHOT_MAX_BYTES = 2 * 1024 * 1024;
|
|
67
|
+
const SNAPSHOT_KEEP_MS = 7 * 86400000;
|
|
68
|
+
const snapshotDir = (root) => join(root, '.bravos', 'watch', 'turn-base');
|
|
69
|
+
|
|
70
|
+
// @comment -- "A cheap fingerprint of one working-tree file: sha1 of its content, size and mtime for a file over 2 MB, 'absent' when it cannot be read (deleted counts as a state too)."
|
|
71
|
+
export function fingerprint(root, rel) {
|
|
72
|
+
try {
|
|
73
|
+
const st = lstatSync(join(root, rel));
|
|
74
|
+
if (st.isSymbolicLink()) return createHash('sha1').update(readlinkSync(join(root, rel))).digest('hex');
|
|
75
|
+
if (!st.isFile()) return 'non-file';
|
|
76
|
+
if (st.size > SNAPSHOT_MAX_BYTES) return `size:${st.size}:${st.mtimeMs}`;
|
|
77
|
+
return 'sha1:' + createHash('sha1').update(readFileSync(join(root, rel))).digest('hex');
|
|
78
|
+
} catch {
|
|
79
|
+
return 'absent';
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Git quotes paths containing controls. core.quotePath=false keeps Unicode as UTF-8;
|
|
84
|
+
// the remaining escapes are Git's C-style control and quote escapes.
|
|
85
|
+
function patchPath(header) {
|
|
86
|
+
const path = header.split('\t')[0];
|
|
87
|
+
if (path === '/dev/null') return null;
|
|
88
|
+
const escapes = { a: '\x07', b: '\b', t: '\t', n: '\n', v: '\v', f: '\f', r: '\r' };
|
|
89
|
+
const unquoted = path.startsWith('"')
|
|
90
|
+
? path.slice(1, -1).replace(/\\([0-7]{3}|.)/g, (_, c) => c.length === 3 ? String.fromCharCode(parseInt(c, 8)) : escapes[c] ?? c)
|
|
91
|
+
: path;
|
|
92
|
+
return unquoted.slice(2);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// @comment -- "Read a zero-context Git patch from a fixed revision to disk, with external diff and text conversion disabled. Keep line ranges and hashes only. Old-side coordinates identify pre-existing dirty hunks even when a later insertion shifts their new line numbers."
|
|
96
|
+
export function gitPatchArgs(base, head) {
|
|
97
|
+
return ['-c', 'core.quotePath=false', 'diff', '--no-ext-diff', '--no-textconv', '--no-renames',
|
|
98
|
+
'--no-color', '--unified=0', '--src-prefix=a/', '--dst-prefix=b/', '--end-of-options', base, ...(head ? [head] : []), '--'];
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export async function changedHunks(root, env, run, base, timeoutMs = 10000) {
|
|
102
|
+
const result = await run('git', gitPatchArgs(base), { cwd: root, env, timeoutMs });
|
|
103
|
+
return result.status === 0 ? parseChangedHunks(result.stdout) : new Map();
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function parseChangedHunks(patch) {
|
|
107
|
+
const files = new Map();
|
|
108
|
+
let oldFile, file, hunk, deleted;
|
|
109
|
+
for (const line of patch.split('\n')) {
|
|
110
|
+
if (line.startsWith('diff --git ')) {
|
|
111
|
+
oldFile = file = hunk = null;
|
|
112
|
+
deleted = false;
|
|
113
|
+
} else if (!hunk && line.startsWith('--- ')) {
|
|
114
|
+
oldFile = patchPath(line.slice(4));
|
|
115
|
+
} else if (!hunk && line.startsWith('+++ ')) {
|
|
116
|
+
const destination = patchPath(line.slice(4));
|
|
117
|
+
deleted = destination === null;
|
|
118
|
+
file = destination ?? oldFile;
|
|
119
|
+
} else if (file && line.startsWith('@@ ')) {
|
|
120
|
+
const m = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(line);
|
|
121
|
+
if (!m) continue;
|
|
122
|
+
const start = Math.max(1, Number(m[3]));
|
|
123
|
+
hunk = { start, deleted, end: start + Math.max(1, Number(m[4] ?? 1)) - 1, hash: createHash('sha256').update(m[1] + ':' + (m[2] ?? '1')) };
|
|
124
|
+
if (!files.has(file)) files.set(file, []);
|
|
125
|
+
files.get(file).push(hunk);
|
|
126
|
+
} else if (hunk && (line.startsWith('+') || line.startsWith('-'))) {
|
|
127
|
+
hunk.hash.update('\n' + line);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
for (const hunks of files.values()) for (const h of hunks) h.hash = h.hash.digest('hex');
|
|
131
|
+
return files;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Records what the working tree already held when a session started, so the end-of-turn check can
|
|
136
|
+
* tell this session's changes from edits that were there before it. Never throws.
|
|
137
|
+
*/
|
|
138
|
+
// @comment -- "Writes .bravos/watch/turn-base/<session_id>.json = {head, files: {path: fingerprint}} for the working-tree changes present at session start (at most SNAPSHOT_MAX_FILES), keeps an existing snapshot for the same session (a resume or compact keeps the session's own start), and prunes snapshots older than seven days; the watch folder ignores itself in git."
|
|
139
|
+
export async function takeSnapshot(root, sessionId, { env = process.env, run = asyncRunner, now = Date.now() } = {}) {
|
|
140
|
+
const id = safeSessionId(sessionId);
|
|
141
|
+
if (!id) return null;
|
|
142
|
+
try {
|
|
143
|
+
const dir = snapshotDir(root);
|
|
144
|
+
const file = join(dir, `${id}.json`);
|
|
145
|
+
if (existsSync(file)) return file;
|
|
146
|
+
const o = { cwd: root, env, timeoutMs: 5000 };
|
|
147
|
+
const head = await run('git', ['rev-parse', 'HEAD'], o);
|
|
148
|
+
if (head.status !== 0) return null;
|
|
149
|
+
const files = Object.create(null);
|
|
150
|
+
let n = 0;
|
|
151
|
+
for (const rel of await workingChanges(root, env, run)) {
|
|
152
|
+
if (n++ >= SNAPSHOT_MAX_FILES) break;
|
|
153
|
+
files[rel] = fingerprint(root, rel);
|
|
154
|
+
}
|
|
155
|
+
const initialHunks = n ? await changedHunks(root, env, run, head.stdout.trim(), 5000) : new Map();
|
|
156
|
+
const hunks = Object.fromEntries(Object.keys(files).filter(path => initialHunks.has(path))
|
|
157
|
+
.map(path => [path, initialHunks.get(path).map(h => h.hash)]));
|
|
158
|
+
mkdirSync(dir, { recursive: true });
|
|
159
|
+
const ignore = join(root, '.bravos', 'watch', '.gitignore');
|
|
160
|
+
if (!existsSync(ignore)) writeFileSync(ignore, '*\n');
|
|
161
|
+
writeFileSync(file, JSON.stringify({ at: new Date(now).toISOString(), head: head.stdout.trim(), files, hunks, truncated: n > SNAPSHOT_MAX_FILES }));
|
|
162
|
+
for (const f of readdirSync(dir)) {
|
|
163
|
+
try {
|
|
164
|
+
if (f.endsWith('.json') && now - statSync(join(dir, f)).mtimeMs > SNAPSHOT_KEEP_MS) rmSync(join(dir, f));
|
|
165
|
+
} catch {
|
|
166
|
+
/* a snapshot that cannot be pruned is harmless */
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
return file;
|
|
170
|
+
} catch {
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// @comment -- "Reads a session's start snapshot; a missing, unreadable or malformed one is null, which keeps the pre-snapshot behaviour."
|
|
176
|
+
export function readSnapshot(root, sessionId) {
|
|
177
|
+
const id = safeSessionId(sessionId);
|
|
178
|
+
if (!id) return null;
|
|
179
|
+
try {
|
|
180
|
+
const s = JSON.parse(readFileSync(join(snapshotDir(root), `${id}.json`), 'utf8'));
|
|
181
|
+
if (!s || !/^[a-zA-Z0-9]+$/.test(s.head) || !s.files || typeof s.files !== 'object' || Array.isArray(s.files)) return null;
|
|
182
|
+
// Snapshot files are local inputs. Never fingerprint an absolute or traversing path.
|
|
183
|
+
if (Object.keys(s.files).some(p => !p || p.startsWith('/') || p.split('/').includes('..'))) return null;
|
|
184
|
+
return s;
|
|
185
|
+
} catch {
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
package/hooks/session-start.mjs
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
// @comment -- "SessionStart hook entry (--global: the user-level copy, silent where the repo has its own bravos hook or no .guardlink/; --briefing prints only the briefing text, for a skill that runs it by hand): reads the hook payload from stdin (bounded wait, bad input ignored; source, and Antigravity's workspacePaths), awaits collect() (read-only guardlink, git and gh facts under a shared 20 s deadline), and prints one JSON envelope: the briefing as additionalContext for the model, plus on a fresh start a banner as systemMessage for the human (brand-coloured; a three-line summary for Codex). With --harness agy it prints Antigravity's injectSteps instead. Always exits 0 so a session never fails to start."
|
|
1
|
+
// @comment -- "SessionStart hook entry (--global: the user-level copy, silent where the repo has its own bravos hook or no .guardlink/; --briefing prints only the briefing text, for a skill that runs it by hand): reads the hook payload from stdin (bounded wait, bad input ignored; source, and Antigravity's workspacePaths), awaits collect() (read-only guardlink, git and gh facts under a shared 20 s deadline) and, where autopilot is registered, the session-start snapshot of the working tree (.bravos/watch/turn-base), and prints one JSON envelope: the briefing as additionalContext for the model, plus on a fresh start a banner as systemMessage for the human (brand-coloured; a three-line summary for Codex). With --harness agy it prints Antigravity's injectSteps instead. Always exits 0 so a session never fails to start."
|
|
2
2
|
import { existsSync } from 'node:fs';
|
|
3
3
|
import { dirname, join } from 'node:path';
|
|
4
4
|
import { fileURLToPath } from 'node:url';
|
|
5
|
-
import { buildBanner, buildBriefing, buildSummary, collect, readVersion } from './lib/briefing.mjs';
|
|
5
|
+
import { autopilotRegistered, buildBanner, buildBriefing, buildSummary, collect, readVersion } from './lib/briefing.mjs';
|
|
6
6
|
import { resolveTheme } from './lib/palette.mjs';
|
|
7
|
+
import { takeSnapshot } from './lib/snapshot.mjs';
|
|
7
8
|
|
|
8
9
|
const STDIN_WAIT_MS = 1000;
|
|
9
10
|
|
|
@@ -58,7 +59,10 @@ async function main() {
|
|
|
58
59
|
if (process.argv.includes('--global') && (existsSync(join(root, '.bravos', 'hooks', 'session-start.mjs')) || !existsSync(join(root, '.guardlink')))) {
|
|
59
60
|
process.exit(0);
|
|
60
61
|
}
|
|
61
|
-
|
|
62
|
+
// Where autopilot is on, record what the working tree held at the start, beside the briefing, so its
|
|
63
|
+
// end-of-turn check judges only this session's changes (no autopilot, nothing written).
|
|
64
|
+
const snap = autopilotRegistered(root) ? takeSnapshot(root, payload.session_id, { env }) : null;
|
|
65
|
+
const [inputs] = await Promise.all([collect(root, env), snap]);
|
|
62
66
|
text = buildBriefing(inputs);
|
|
63
67
|
if (env.BRAVOS_BANNER !== 'off' && (source === null || source === 'startup') && harness !== 'agy') {
|
|
64
68
|
const version = readVersion(dirname(fileURLToPath(import.meta.url)));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bugb-technologies/bravos",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.0",
|
|
4
4
|
"description": "Skills pack and installer that make Claude Code and Codex power users of guardlink (threat-model-as-code) and cert-x-gen (pentest-as-code).",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"security",
|
package/skills/bravos/SKILL.md
CHANGED
|
@@ -26,6 +26,7 @@ description: "Start here in any repo bravos is installed in: reads the security
|
|
|
26
26
|
standing up a test target, seeding test users, capturing a session → bravos-env.
|
|
27
27
|
proving a finding, testing whether an exposure is exploitable → bravos-prove (after bravos-env).
|
|
28
28
|
a fix landed, stale claims, closing a security ticket → bravos-recheck.
|
|
29
|
+
the briefing says the branch is far behind its base, annotation work sits on an idle branch, a branch was moved or abandoned → bravos-resync.
|
|
29
30
|
write up the assessment, a finding, a retest or a brief for leadership → bravos-report.
|
|
30
31
|
static analysis, dependency, secret or IaC findings → bravos-sast; "what did SAST find" → `bravos sast candidates` (the briefing's `SAST:` line says whether a run exists, or that SAST is unavailable).
|
|
31
32
|
keep annotating while I work, nightly or periodic runs → bravos-schedule.
|
|
@@ -56,7 +57,7 @@ description: "Start here in any repo bravos is installed in: reads the security
|
|
|
56
57
|
|
|
57
58
|
## Go deeper
|
|
58
59
|
|
|
59
|
-
- Autopilot (`bravos init --autopilot`): an end-of-turn check
|
|
60
|
+
- Autopilot (`bravos init --autopilot`): an end-of-turn check points you to changed code and affected claims, including untested controls and claims due for retest; the briefing's `Autopilot:` and `Proving:` lines say whether it is on and how the person wants proving handled.
|
|
60
61
|
- `bravos guide` (in a shell; no model) explains bravos by role, by task and skill by skill, with the safety rules; `docs/GUIDE.md` in the bravos package is the same text. Point a person there when they ask how to use bravos.
|
|
61
62
|
- `docs/GUARDLINK_REFERENCE.md` — annotation syntax and verbs.
|
|
62
63
|
- `.guardlink/README.md` — where annotations go in this repo.
|
|
@@ -16,17 +16,18 @@ description: "Keep the GuardLink threat model correct and growing, in this sessi
|
|
|
16
16
|
1. Set up. You annotate in this session: guardlink supplies the method (its playbook skills), you supply the edits. `<base>` below is the base branch name, e.g. `main`; the briefing prints it as `base origin/<base>`, and without a briefing `git symbolic-ref -q --short refs/remotes/origin/HEAD` prints `origin/<base>` (if it prints nothing, use `main`). Run `git fetch origin <base>` before you use `origin/<base>`, so it is current; if the fetch fails (offline, no `origin`), say so and continue with the local ref. Record `git rev-parse HEAD` now as `<start>`: the lint gate judges only what this session writes. Definitions (`@asset`, `@threat`, `@control` with `#id`) live in `.guardlink/definitions.*`; reuse those ids and never redefine one. Read `.guardlink/intent.md`: its invariants (`INV-n`), intended-by-design items (`INT-n`), actors and crown jewels shape every claim below. If it is missing, run bravos-context first; if the user declines, carry on and tell them severities are not calibrated to the product.
|
|
17
17
|
2. Run `guardlink ci -f json`. Note `summary.coverage.percent` as p0 and the worklist size from the briefing or `guardlink unannotated --json` (`summary.worklist`).
|
|
18
18
|
3. Read the effort: the user's words ("at high"), else a `bravos effort: <level>` line in `AGENTS.md` / `CLAUDE.md`, else medium. Starting budgets — low: the changed files only; medium: changed plus 5 from the worklist; high: 25 per round, then the `chains` playbook; max: rounds until the worklist is empty (bravos-campaign runs those with subagents). These are defaults, not limits: take more or fewer when the code calls for it, and say why in one line ("12 files, not 5: the auth path spans them"). For a large pick, tell the user the files and rounds before you start.
|
|
19
|
-
4. Run `node {{SKILL_DIR}}/scripts/slice.mjs --base origin/<base> --n <budget>` (`--deep` for no limit, `--batches <k>` to split the pick for parallel work, `--prefer <file>` for entry points `codegraph_entry_points` found). It prints one JSON object: `diff` (changed
|
|
20
|
-
5. Pick the playbook: `diff` files → `diff`; `coverage` files → `coverage`. Deep rounds run `exploitable`, then `chains`, then `coverage`, then `verify`. Add a logic pass when intent.md lists invariants (always at high and max, or when guardlink offers a `logic` playbook use it): walk each user journey that touches an invariant — signup, invite, role change, checkout, refund, export — and at each step ask what it assumes about the caller and the step before: ownership, tenant, state, amount, rate. The sink of a logic claim is the state change (the write, the transfer, the grant); the absent control is the missing ownership or state check. Claim it against the invariant's threat: `@mitigates <Asset> against #inv-… using #<control>` for a check that holds, `@exposes <Asset> to #inv-…` for one that is missing and meets the evidence bar, `@audit` for a doubt.
|
|
19
|
+
4. Run `node {{SKILL_DIR}}/scripts/slice.mjs --base origin/<base> --n <budget>` (`--deep` for no limit, `--batches <k>` to split the pick for parallel work, `--prefer <file>` for entry points `codegraph_entry_points` found). It prints one JSON object: `diff` (files changed from the merge base to disk, including staged, unstaged and untracked source), `coverage` (unannotated files to cover, entry points and trust code first, generated, test and CI files last), `coverage_detail` (`{path, tier, why}`), `batches`, `skipped` (`{path, reason}`), `coverage_before`, `notes`. The order is advice: if your reading of the code says a different file matters more, take it and say why. Tell the user which `skipped` files teammates have in flight. Report every `notes` entry to the user; if one says gh was unavailable, say in-flight PRs were not checked before you take the `coverage` files. Exit 1 means `guardlink unannotated --json` failed: report it and stop. When the briefing's `SAST:` line shows a run, `bravos sast candidates` lists reachable findings not in the threat model yet: add their files to the pick as leads, open each, and annotate only what meets the evidence bar, as `@exposes` + `@audit` citing the rule and route, or an `@audit` naming a false positive. A static finding is never `@confirmed`. With SAST unavailable or no report, pick as usual.
|
|
20
|
+
5. When a Stop hook names files or lines, review those changes first, including already annotated files. Read the actual patch and both sides of a move or deletion. Open each affected handler, guard and caller. With a current graph, ask `codegraph_annotation_gaps` with explicit new-side file ranges for working edits or the merge base for committed changes. Inspect stale and unindexed files and read unsupported routes from source. An existing annotation in the file does not establish that it describes the new behavior. Record the changed threat, guard, or flow, recheck an affected existing claim, or finish the review quietly when the change has no security consequence. Keep ordinary turn-end review to the changed code. Pick the playbook: `diff` files → `diff`; `coverage` files → `coverage`. Deep rounds run `exploitable`, then `chains`, then `coverage`, then `verify`. Add a logic pass when intent.md lists invariants (always at high and max, or when guardlink offers a `logic` playbook use it): walk each user journey that touches an invariant — signup, invite, role change, checkout, refund, export — and at each step ask what it assumes about the caller and the step before: ownership, tenant, state, amount, rate. The sink of a logic claim is the state change (the write, the transfer, the grant); the absent control is the missing ownership or state check. Claim it against the invariant's threat: `@mitigates <Asset> against #inv-… using #<control>` for a check that holds, `@exposes <Asset> to #inv-…` for one that is missing and meets the evidence bar, `@audit` for a doubt.
|
|
21
21
|
6. Open `{{SKILLS_ROOT}}/guardlink-annotate-<id>/SKILL.md` (guardlink writes it under `.claude/skills/`, and `bravos init` mirrors it into `.agents/skills/` for Codex) and follow it. Otherwise call the MCP tool `guardlink_annotate` (server `guardlink`) with `prompt: "<scope>"` and `playbook: "<id>"`, or run `guardlink annotate --stdout --playbook <id> "<scope>"` (for the `diff` playbook, `guardlink annotate --stdout --playbook diff --since origin/<base> "<scope>"`, since `--since` defaults to HEAD and would list no changed files), and follow the prompt it returns.
|
|
22
|
-
7.
|
|
22
|
+
7. Read the repository's annotation mode in `.guardlink/README.md` and its configuration. In inline mode write annotations in the file's comment syntax directly above the code. In external mode update its `.guardlink/annotations/<source-path>.gal` sidecar and anchor the block to the logical source line and symbol using the local GuardLink playbook. Couple the claims: every `@exposes` with its `@mitigates` or `@audit`, the `@flows` the data takes, and a `@comment` on what the code does. Each claim meets the evidence bar: it names the code, the threat and the control by id, and you could point at the line that makes it true.
|
|
23
23
|
Rate each `@exposes` by impact × reach × ease, within its threat's band, under intent.md's `## Assumptions` when it has them (the configuration baseline, deployment and attackers in scope; an exposure only an out-of-scope attacker reaches gets an `@audit`, not a severity): impact from the asset's `@handles` class and intent.md's crown jewels; reach from the boundary in front of it (public, then signed-in, then admin-only, then internal; with the code graph (its MCP tools, or `bravos graph <question> --json` — same answers; see bravos-codegraph), `codegraph_auth_boundary` for the route and `codegraph_reachable_sinks` for what the handler reaches; code `codegraph_entry_reach` or `codegraph_dead_code` shows no entry point reaches gets an `@audit` "not reachable per code graph", not a severity; without the graph, judge reach by reading the code and say the graph was unavailable); ease from its preconditions. Write the severity inline and the reason in the description ("high: reachable unauthenticated, touches payment records").
|
|
24
24
|
Intended? When the code does what an intent.md `INT-n` item says the product does on purpose, write no `@exposes`: write an `@audit` citing it ("by design per intent.md INT-2; check only admins reach it") and annotate the guard that should hold. When it looks intended but intent.md is silent, write an `@audit` asking "intended?" with your reason, and list it for the user. They answer with a fix, an intent.md line or their own `@accepts`; you never accept it. In a bravos workspace (the briefing's `Workspace:` line, or `.bravos/workspace/workspace.json`), define only this service's own assets, with ids prefixed by the service (`#orders-create`), never another service's; declare each call to another service as `@flows #<this>-<x> -> #<other>-<y> via http|grpc|queue -- "..."` with the other service's own id. Do not write the dotted `#repo.tag` form that guardlink's Workspace Context block suggests: cxg cannot chain it, so the cross-service attack is never tested.
|
|
25
|
+
If a patch changes a caller, destination, trust boundary or security control, trace who can reach it, the data crossing it, the guard and where it is enforced. Reconcile the specific `@flows`, `@boundary` and control claims with the new behavior. For tools the application gives an agent, review `@agents` or `@reaches` at registration, `@effects` where the action occurs and `@gates` where approval is enforced. For coding-agent configuration, run `guardlink lookup "unentitled coding-agent reach"` and inspect the changed configuration lines. GuardLink derives the agent's reach from those files. Propose a missing entitlement for the human's decision; report an unapproved capability and the evidence separately from an exploitable finding.
|
|
25
26
|
8. Gate: run `guardlink lint . --since <start> --json`. For each entry in `violations[]`, apply its `fix`. Repeat until `summary.errors` is 0. A violation on a line you did not write this session is not yours: leave the line as it is and report it to the user.
|
|
26
27
|
9. Run `guardlink validate .` and fix what it reports in the lines you wrote.
|
|
27
28
|
10. Run `guardlink ci -f json` again and report `+<files>, <p0>% → <p1>%, <errors> lint errors`. Deep only: repeat steps 4–10 once per round, and stop when `coverage` comes back empty or a round adds no claims.
|
|
28
|
-
11.
|
|
29
|
-
12. Hand
|
|
29
|
+
11. On a normal coding turn keep annotations with the code change and preserve the user's staged and uncommitted edits. For a requested standalone coverage slice, commit the slice on its own: `git add` only the annotated files, message `annotate: <n> files, <playbook>`. Ship it as a small PR or on the feature branch, whichever the team does.
|
|
30
|
+
12. Read `guardlink hypothesis list --json`. Keep each changed exposure's stable key, source location, sidecar location when applicable, and tested state. Include untested claims with a declared mitigation. Hand new claims to bravos-templatize for a concrete kit; expired or previously tested claims go to bravos-recheck. Apply the recorded proving choice before execution: auto follows bravos-env and bravos-prove in its authorized scope; ask seeks a decision; schedule leaves the claim queued; none records that it was not tested. Evidence from a real run is required before marking a claim confirmed or refuted. Hand the change to bravos-ship before a PR.
|
|
30
31
|
|
|
31
32
|
## Never
|
|
32
33
|
|
|
@@ -63,13 +63,20 @@ if (!base) {
|
|
|
63
63
|
base = r.status === 0 && r.stdout.trim() ? r.stdout.trim() : 'origin/main';
|
|
64
64
|
}
|
|
65
65
|
|
|
66
|
-
|
|
67
|
-
const
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
66
|
+
// @comment -- "Review committed changes since the merge base and what is on disk, including the index and nonignored untracked files. Git's NUL-terminated path output preserves spaces and newlines. A missing remote base still permits reviewing local changes."
|
|
67
|
+
const gitOptions = { cwd, encoding: 'utf8', timeout: 10000, maxBuffer: 64 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] };
|
|
68
|
+
const ancestor = spawnSync('git', ['merge-base', '--', base, 'HEAD'], gitOptions);
|
|
69
|
+
const from = ancestor.status === 0 ? ancestor.stdout.trim() : 'HEAD';
|
|
70
|
+
if (ancestor.status !== 0) notes.push('no merge base for ' + base + '; reviewing changes since HEAD and untracked files');
|
|
71
|
+
const changed = new Set();
|
|
72
|
+
for (const args of [
|
|
73
|
+
['diff', '--name-only', '-z', '--no-renames', from, '--'],
|
|
74
|
+
['ls-files', '-z', '--others', '--exclude-standard'],
|
|
75
|
+
]) {
|
|
76
|
+
const result = spawnSync('git', args, gitOptions);
|
|
77
|
+
if (result.status === 0) {
|
|
78
|
+
for (const path of result.stdout.split('\0')) if (path) changed.add(path);
|
|
79
|
+
} else notes.push('git ' + args[0] + ' failed: ' + (result.error?.code ?? result.status));
|
|
73
80
|
}
|
|
74
81
|
|
|
75
82
|
const un = runJson('guardlink', ['unannotated', '--json'], { cwd });
|
|
@@ -114,7 +121,7 @@ const picked = pickSlice({
|
|
|
114
121
|
worklist: worklistPaths,
|
|
115
122
|
annotated: paths(un.json?.annotated),
|
|
116
123
|
excluded: paths(un.json?.excluded),
|
|
117
|
-
changed,
|
|
124
|
+
changed: [...changed],
|
|
118
125
|
inFlight,
|
|
119
126
|
ownedDirs: [],
|
|
120
127
|
generated,
|
|
@@ -28,7 +28,7 @@ description: "Audit and write the repo's security CI: the bravos PR gate (valida
|
|
|
28
28
|
- Write a secret, token, licence or session into a workflow or any committed file.
|
|
29
29
|
- Interpolate pull-request, issue or comment text, or a branch name, directly into a `run:` line.
|
|
30
30
|
- Use `guardlink validate . --strict` as a PR gate on a repo with recorded legacy exposures; it fails on every one of them, not on what the PR adds.
|
|
31
|
-
- Add
|
|
31
|
+
- Add live testing to the PR gate. Only the reviewed scheduled workflow may replay bound kits under a current scheduled proving grant and committed scope. Check that disabling the policy stops replay before any target contact.
|
|
32
32
|
- Delete or rewrite a workflow bravos did not write without the user's go-ahead.
|
|
33
33
|
- Write `@accepts`, `@entitles` or `@confirmed`.
|
|
34
34
|
|
|
@@ -12,12 +12,12 @@ description: "Bring up a test target the user owns and prepare it for an authori
|
|
|
12
12
|
|
|
13
13
|
## Do
|
|
14
14
|
|
|
15
|
-
1.
|
|
16
|
-
2. On loopback, a recorded proving preference (`.guardlink/proving.md`, `choice: auto`) is the person's go-ahead for its target: start
|
|
15
|
+
1. Read the current proving choice before target contact, login or auth verification. Use the owned local app named in the standing authorization or the target explicitly authorized for this invocation. The default is a loopback address (`127.0.0.1`, `localhost`, `[::1]`). Start it with the repo's own tooling (its compose file, dev server script or desktop build) and wait until it answers. In a bravos workspace each service has its own target: take the URLs from `bravos workspace show` (set a missing one with `bravos workspace target <name> <service>=http://127.0.0.1:<port>`), bring up every service the test crosses, and list every service host in the reviewed scope's `host_allowlist`.
|
|
16
|
+
2. On loopback, a recorded proving preference (`.guardlink/proving.md`, `choice: auto`) is the person's go-ahead for its target: use the recorded target and start command. If the setup wizard left them empty, inspect the repository’s documented development command and listening address. When these match the app the person authorized, record the actual target and start command alongside their original words. Commit the policy and scope before automatic replay. Ask only if the target or authority is ambiguous. If the user names a non-loopback target, stop and get two things before going on: the host listed in a committed `scope.yaml` that has been through a reviewed PR, and the human's authorization typed by them in this session in their own words. Without both, the target is out of scope; say so and stay on loopback.
|
|
17
17
|
3. Write the scope. Copy `{{SKILL_DIR}}/scope.example.yaml` to `.guardlink/scope.yaml`, or run `cxg pentest scope-init -o .guardlink/scope.yaml` for the full field reference, then narrow `url_allowlist` to the routes under test. `method_allowlist` is a strict bound: cxg refuses every method it does not list, even with `--destructive-ok`, so a test that needs PUT, PATCH or DELETE needs the target's owner to add them in the reviewed PR; never add them yourself. scope-init pre-fills `authorization_attestation` with an example sentence: blank it. Leave that field for the human to fill. Commit it and ship it as a PR for review before any non-loopback run.
|
|
18
18
|
4. Seed test data with the repo's own fixtures, seed scripts or admin endpoints: the roles and users the threats need, such as two users of different tenants for an ownership check. Name any test that needs production-like data as such, and run it only where that data is synthetic.
|
|
19
19
|
5. Get a session. On loopback, do it yourself: create the test accounts through the app's own signup, seed script or admin endpoint, write their email and password to a gitignored file under `.bravos/`, and log in with `cxg pentest auth --target <url> --profile <name> --creds-file <file> --login-path <login route>`, one profile per identity a check needs. If the app's login is not a JSON POST, drive the signup and login in your own browser tool and capture the session interactively with `cxg pentest auth --target <url> --profile <name>`. For an authorized non-loopback target, ask the human to capture the session in their own browser with the same command, or to paste a storage state you import with `cxg pentest auth import --storage-state <file> --profile <name> --target <url>`; CI uses the import with a session the human exported once.
|
|
20
|
-
6. Confirm each session is live with `cxg pentest auth verify --profile <name>` before handing the target on, so a run never spends its budget unauthenticated.
|
|
20
|
+
6. Verify the target URL and scope against the current recorded policy before sending any request. For a fresh local build or launch from this repository, capture the matching worktree witness at that time with `bravos hook replay build <loopback-url>`. Pass that output to bravos-prove in BRAVOS_REPLAY_BUILD, recording the actual target and revision. A hash computed beside a previously running app does not establish which code it serves. If a remote or already-running service cannot be tied to this build, report observations without updating the current claim. Confirm each required session is live with `cxg pentest auth verify --profile <name>` before handing the target on, so a run never spends its budget unauthenticated.
|
|
21
21
|
7. Record the target URL, the profile names, the scope path and whether the target is loopback, and hand them to bravos-prove.
|
|
22
22
|
|
|
23
23
|
## Never
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: bravos-prove
|
|
3
|
-
description: "
|
|
3
|
+
description: "Prove a new or changed GuardLink claim, or replay it after a fix, against an authorized target. Use the active coding agent to author a missing kit, run the selected kit through CXG, and record the evidence for that exact claim."
|
|
4
4
|
---
|
|
5
5
|
# Bravos prove: an authorized run, and only a run decides
|
|
6
6
|
|
|
@@ -12,18 +12,14 @@ description: "Run the authorized test against a target the user owns and record
|
|
|
12
12
|
|
|
13
13
|
## Do
|
|
14
14
|
|
|
15
|
-
1. Check the preconditions from bravos-env: a target that answers, `.guardlink/scope.yaml` committed, each profile passing `cxg pentest auth verify --profile <name>`, and for any non-loopback target both a reviewed scope and the human's authorization typed in this session. If one is missing, stop and hand back to bravos-env. Read the effort: the user's words ("at high"), else a `bravos effort: <level>` line in `AGENTS.md` / `CLAUDE.md`, else medium. It sets a starting budget, not a limit; go beyond it when the work needs it and say why in one line. Starting budget — low: replay
|
|
15
|
+
1. Check the preconditions from bravos-env before any traffic: authorization for this run, a target that answers, `.guardlink/scope.yaml` committed, each profile passing `cxg pentest auth verify --profile <name>`, and for any non-loopback target both a reviewed scope and the human's authorization typed in this session. If one is missing, stop and hand back to bravos-env. Read the effort: the user's words ("at high"), else a `bravos effort: <level>` line in `AGENTS.md` / `CLAUDE.md`, else medium. It sets a starting budget, not a limit; go beyond it when the work needs it and say why in one line. Starting budget — low: replay a matching kit; medium: also author the first missing test in this session; high: include affected callers and controls; max: cover the testable in-scope queue. A higher effort does not authorize spending on an external model.
|
|
16
16
|
2. Order what to test, then read how the person wants proving handled. With the code graph (its MCP tools, or `bravos graph <question> --json` — same answers; see bravos-codegraph) (briefing `Code graph:` says `current`): `codegraph_untested_exposures` and `codegraph_untested_reach` rank untested exposures by reach; test the ones intent.md's Assumptions put in scope first, least privileged entry point first, and report exposures only an out-of-scope attacker reaches instead of running them. Without the graph, say "code graph unavailable; using guardlink hypothesis next order" and use that queue. Within that order, an exposure with a reachable SAST finding joined to it (`bravos sast candidates`) goes before one without, and its route goes into the run notes; with no SAST report or SAST unavailable, skip this. Then, for how the person wants proving handled: the briefing's `Proving:` line, from `.guardlink/proving.md`. If it is not set, ask them once, with a suggestion drawn from the repo (for example, "you have a docker-compose; I'd prove automatically on 127.0.0.1:8080"): prove automatically on their loopback target whenever new or changed exposures appear, ask each time, on a schedule (bravos-schedule's nightly), or not now; and whether cxg may generate probes through a model API, which spends money. Record their answer in `.guardlink/proving.md`: lines `choice: auto|ask|schedule|none`, `target: <loopback url>`, `start: <start command>`, `generation: yes|no`, their words quoted verbatim, and `— confirmed by <their name>, <date>`. Then follow it: `auto` proceeds on that target with their quoted words as the attestation and, with `generation: yes`, the spend approved; `ask` asks now; `schedule` hands to bravos-schedule; `none` stops here and says so. When they change their mind, rewrite the file with their new words.
|
|
17
|
-
3.
|
|
18
|
-
4.
|
|
19
|
-
5.
|
|
20
|
-
6.
|
|
21
|
-
7.
|
|
22
|
-
8.
|
|
23
|
-
9. Write back the confirmations: `guardlink hypothesis confirm --from-scan .guardlink/pentest-findings/<run>/report.json --write`. It records only findings whose claim key resolves, and writes the source line only for uncontested ones.
|
|
24
|
-
10. Record each refuted result against its claim: `guardlink hypothesis refute <file:line> --evidence "<request sent and response received>"`, quoting the report entry.
|
|
25
|
-
11. Run `guardlink hypothesis list --state confirmed --json` and report each new confirmation with its threat, asset and file:line, plus the refutations and every result left untested.
|
|
26
|
-
12. Hand confirmed threats to the user as fix-first, and to bravos-recheck once a fix lands.
|
|
17
|
+
3. Read the affected claim from `guardlink hypothesis list --json`. Include a declared mitigation awaiting its first test and a previously confirmed claim now marked retest. Match its key to the logical source location in `guardlink sarif . --profile pentest -o whitebox/findings.sarif`; external annotations also have a physical declaration in a .gal file. Keep both locations. Record the tested source revision or worktree, application build, identity roles and intended oracle.
|
|
18
|
+
4. For a web claim, use its bound JavaScript kit in .guardlink/cxg-replay/. For a missing or mismatched kit, follow bravos-templatize in this session. A matching kit exercises the intended operation and includes a positive control for a claimed defense. Validate the kit and review its scope. Honor the recorded kit policy and the person’s stated limits. An automatic reviewed-only policy requires identical bound test bytes on the default branch (the consent commit when Git has no local origin/HEAD). The earlier wizard’s “only replay tests I approved” choice retains that restriction.
|
|
19
|
+
5. Pass the build witness that bravos-env captured at launch in BRAVOS_REPLAY_BUILD. Without fresh build provenance, retain the observation and leave the current-code claim pending. Under a recorded automatic loopback policy, run `bravos hook replay run <kit.js>`. For a one-time approved run under an ask policy, use `bravos hook replay run-once <kit.js>` with the target in BRAVOS_SCAN_TARGET and the person's exact words in BRAVOS_REPLAY_ATTESTATION for that invocation. Keep private identity state outside Git. A scheduled-only policy hands the kit to bravos-schedule. A disabled policy leaves the claim pending. The helper selects one file through plain CXG scan with model authoring disabled. Only evidence tied to the exact claim, tested source and kit is eligible for writeback.
|
|
20
|
+
6. Read the individual native CXG execution and ledger result. A reproduced exploit needs an engine-adjudicated confirmation. A held control needs observed denial and a working positive control. Missing roles, ambiguous tests, incomplete imports, a different target build or stale inputs stay pending with the reason. Exit 4 can include both a refusal and valid results from other probes. An ordinary scanner's template-reported match is a lead for a runtime test. Keep private HTTP and auth material out of reports and commits.
|
|
21
|
+
7. For workspaces, bind each hop to its own service URL and authorized scope. For Electron, use its configured launch and verified desktop profile. Ordinary network or local CLI scanner templates use the scanner contract and produce leads. Use explicit CXG orchestration only when the requested target or technique needs it, for example Tauri's in-process proof or operator-requested CXG model generation. Check the CXG pentest run help for the selected platform, method and authorization before execution. For generation require the recorded permission for the API spend, available provider credentials and a specific threat selector for fresh web probes. Use the reviewed scope, approved target and identities. Keep the resulting native evidence separate. For an independently stamped result, the GuardLink import is `guardlink hypothesis confirm --from-scan <native-report.json> --write`; check every intended claim key and tested anchor, import only an uncontested exact match, and reread the ledger. A missing key, changed build or failed write is unrecorded. Boundary outcomes use GuardLink's boundary ledger.
|
|
22
|
+
8. Report which claims were confirmed or refuted, which still need testing and which were actually recorded. Keep the run ID and the kit for bravos-recheck.
|
|
27
23
|
|
|
28
24
|
## Never
|
|
29
25
|
|
|
@@ -32,14 +28,14 @@ description: "Run the authorized test against a target the user owns and record
|
|
|
32
28
|
- Write `--attestation` text the human did not type, here or in `.guardlink/proving.md`.
|
|
33
29
|
- Record a proving preference the person did not state, or read one as covering more than it says: it never covers a non-loopback target or a destructive class.
|
|
34
30
|
- Use `--destructive-ok` unless the target is a disposable loopback instance and the human asked for it.
|
|
35
|
-
- Write `@confirmed` yourself, or treat reading code as a confirmation;
|
|
31
|
+
- Write `@confirmed` yourself, or treat reading code as a confirmation; the replay helper uses GuardLink to persist the actual engine verdict and rereads the intended entry.
|
|
36
32
|
- Call an exposure refuted because a run found nothing, or because the run was killed, refused or never ran its template.
|
|
37
33
|
- Write `@accepts` or `@entitles`.
|
|
38
34
|
|
|
39
35
|
## Done when
|
|
40
36
|
|
|
41
|
-
-
|
|
42
|
-
- Every
|
|
37
|
+
- Each selected kit has a native outcome and a verified ledger result, or an explicit reason it remains pending.
|
|
38
|
+
- Every recorded outcome is bound to the selected claim and tested inputs. A refutation includes evidence of the working control.
|
|
43
39
|
- For each claim you reported its three states: open or mitigated, confirmed, refuted or untested, and verified or stale, plus what was not tested.
|
|
44
40
|
|
|
45
41
|
## What it leaves for the next skill
|