@bugb-technologies/bravos 1.5.2 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/artifacts.js +31 -1
  2. package/dist/cli.js +78 -5
  3. package/dist/codegraph.js +32 -4
  4. package/dist/context.js +351 -0
  5. package/dist/dashboard.js +35 -10
  6. package/dist/guide.js +3 -0
  7. package/dist/help.js +19 -0
  8. package/dist/report/data.js +2 -1
  9. package/dist/rules.js +218 -0
  10. package/dist/setup.js +33 -7
  11. package/dist/uninstall.js +6 -0
  12. package/dist/versions.js +1 -1
  13. package/dist/watch-frame.js +8 -1
  14. package/dist/watch.js +11 -2
  15. package/docs/GUIDE.md +18 -0
  16. package/docs/UPGRADING.md +30 -0
  17. package/hooks/lib/autopilot.mjs +29 -7
  18. package/hooks/lib/briefing.mjs +29 -5
  19. package/hooks/lib/context.mjs +522 -0
  20. package/hooks/lib/pre-pr.mjs +70 -0
  21. package/hooks/lib/setup.mjs +5 -2
  22. package/package.json +1 -1
  23. package/skills/bravos/SKILL.md +1 -1
  24. package/skills/bravos-annotate/SKILL.md +5 -3
  25. package/skills/bravos-annotate/scripts/lib/gate.mjs +45 -0
  26. package/skills/bravos-annotate/scripts/slice.mjs +10 -0
  27. package/skills/bravos-campaign/SKILL.md +1 -1
  28. package/skills/bravos-codegraph/SKILL.md +1 -1
  29. package/skills/bravos-context/SKILL.md +16 -10
  30. package/skills/bravos-context/intent.example.md +14 -1
  31. package/skills/bravos-recheck/SKILL.md +1 -1
  32. package/skills/bravos-ship/SKILL.md +2 -1
  33. package/skills/bravos-templatize/SKILL.md +1 -1
  34. package/templates/dashboard/dashboard.html +97 -0
  35. package/templates/workflows/bravos-nightly-claude.yml +36 -2
  36. package/templates/workflows/bravos-nightly-codex.yml +36 -2
  37. package/templates/workflows/bravos-nightly-copilot.yml +23 -0
  38. package/templates/workflows/bravos-pr-gate.yml +76 -0
@@ -0,0 +1,522 @@
1
+ // @comment -- "The design-document store, .bravos/context/: the documents a team gives bravos (PRDs, design documents, earlier threat models) as committed Markdown, with an index. This one file validates the index, scans a document for secrets, local paths and embedded content, and checks the store as a whole. It imports nothing of bravos's own, so the CLI, a git pre-push hook and a CI step loaded from the base branch all run the same checks."
2
+ import { createHash } from 'node:crypto';
3
+ import { execFileSync } from 'node:child_process';
4
+ import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync } from 'node:fs';
5
+ import { homedir, userInfo } from 'node:os';
6
+ import { join, resolve, sep } from 'node:path';
7
+ import { pathToFileURL } from 'node:url';
8
+
9
+ export const CONTEXT_DIR = '.bravos/context';
10
+ export const INDEX_PATH = `${CONTEXT_DIR}/sources.json`;
11
+ export const SOURCES_DIR = `${CONTEXT_DIR}/sources`;
12
+ export const SOURCES_SCHEMA = 'bravos.context-sources/v1';
13
+ export const CHECK_SCHEMA = 'bravos.context-check/v1';
14
+ export const KINDS = ['prd', 'design', 'threat-model', 'policy', 'api', 'upstream', 'other'];
15
+ /** One document. Design documents are prose; anything larger is a data dump or an embedded binary. */
16
+ export const MAX_SOURCE_BYTES = 2 * 1024 * 1024;
17
+ export const MAX_SOURCES = 500;
18
+ const MAX_INDEX_BYTES = 1024 * 1024;
19
+
20
+ export const sha256 = (buf) => createHash('sha256').update(buf).digest('hex');
21
+ export const ID = /^SRC-[1-9][0-9]{0,4}$/;
22
+ const idNumber = (id) => Number(id.slice(4));
23
+
24
+ // ---------------------------------------------------------------------------------------------
25
+ // Text hygiene
26
+ // ---------------------------------------------------------------------------------------------
27
+
28
+ // Characters a reader does not see: zero-width and joiner characters, bidirectional overrides and isolates, the
29
+ // byte-order mark. In a title they can disguise it; in a document they can hide text from the person skimming it.
30
+ const INVISIBLE = /[​-‏‪-‮⁠-⁤⁦-⁩]/g;
31
+ const CONTROL = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/g;
32
+
33
+ // @comment -- "One clean line from text a person or a document supplied (a title, a name, a reason): control and invisible characters removed, whitespace collapsed, cut to max. Used for everything that is later printed in a terminal or a briefing."
34
+ export function cleanLine(value, max = 120) {
35
+ return String(value ?? '').replace(INVISIBLE, '').replace(CONTROL, ' ').replace(/\s+/g, ' ').trim().slice(0, max);
36
+ }
37
+
38
+ // @comment -- "Decodes a document's bytes as UTF-8 text or says why not: over the size cap, not valid UTF-8, or carrying NUL bytes (a binary file). A leading byte-order mark is dropped and line endings become \\n, so the stored text hashes the same on every machine."
39
+ export function decodeText(buf) {
40
+ if (buf.length > MAX_SOURCE_BYTES) return { error: `it is ${buf.length} bytes, past the ${MAX_SOURCE_BYTES}-byte limit for one document` };
41
+ if (buf.includes(0)) return { error: 'it is a binary file, not text: convert it to Markdown first' };
42
+ let text;
43
+ try {
44
+ text = new TextDecoder('utf-8', { fatal: true }).decode(buf);
45
+ } catch {
46
+ return { error: 'it is not UTF-8 text: convert it to Markdown first' };
47
+ }
48
+ return { text: text.replace(/^/, '').replace(/\r\n?/g, '\n') };
49
+ }
50
+
51
+ // ---------------------------------------------------------------------------------------------
52
+ // Scans. Each returns [{line, rule}] and never the matched text: the finding is printed in terminals and CI logs.
53
+ // ---------------------------------------------------------------------------------------------
54
+
55
+ // A superset of the shapes the report redacts (src/report/redact.ts; tests/context.test.ts holds the two together),
56
+ // widened with the vendor token formats and credential-bearing URLs that design documents quote from real systems.
57
+ // None is global: each is tested once per line.
58
+ export const SECRET_RULES = [
59
+ { rule: 'private key', re: /-----BEGIN [A-Z ]*PRIVATE KEY-----/ },
60
+ { rule: 'aws access key', re: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/ },
61
+ { rule: 'github token', re: /\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{50,})\b/ },
62
+ { rule: 'slack token', re: /\bxox[abeprs]-[A-Za-z0-9-]{10,}/ },
63
+ { rule: 'slack webhook', re: /hooks\.slack\.com\/services\/T[A-Z0-9]+\/B[A-Z0-9]+\/[A-Za-z0-9]{16,}/ },
64
+ { rule: 'stripe key', re: /\b[rs]k_(?:live|test)_[A-Za-z0-9]{16,}\b/ },
65
+ { rule: 'google api key', re: /\bAIza[0-9A-Za-z_-]{35}\b/ },
66
+ { rule: 'model provider key', re: /\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{24,}/ },
67
+ { rule: 'jwt', re: /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/ },
68
+ { rule: 'bearer token', re: /\bBearer\s+(?!<)[A-Za-z0-9._~+/-]{20,}=*/i },
69
+ { rule: 'credentials in a url', re: /\b[a-z][a-z0-9+.-]*:\/\/[^\s/:@]+:[^\s/@]+@/i },
70
+ { rule: 'credential assignment', re: /\b(?:api[_-]?key|secret[_-]?key|client[_-]?secret|password|passwd|access[_-]?token|auth[_-]?token)\s*[:=]\s*["']?(?!<)[A-Za-z0-9/+_.-]{12,}/i },
71
+ ];
72
+
73
+ const scanLines = (text, rules) => {
74
+ const found = [];
75
+ const lines = text.split('\n');
76
+ for (let i = 0; i < lines.length; i++) {
77
+ for (const { rule, re } of rules) if (re.test(lines[i])) found.push({ line: i + 1, rule });
78
+ }
79
+ return found;
80
+ };
81
+
82
+ // @mitigates #context-sources against #committed-secret using #refuse-before-store -- "Every document is tested line by line against credential shapes before it is stored and again whenever the store is checked; a finding names the line and the kind, never the value"
83
+ export function scanSecrets(text) {
84
+ return scanLines(text, SECRET_RULES);
85
+ }
86
+
87
+ /** 'an aws access key', 'a github token': the finding as it reads in a sentence. */
88
+ export const an = (rule) => `${/^[aeiou]/i.test(rule) ? 'an' : 'a'} ${rule}`;
89
+
90
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
91
+
92
+ // @comment -- "Local paths in a document. A converter leaves them behind as image targets and file links; they name the machine and the person the document came from. Flags file: URLs, macOS and Windows user folders, a link or image whose target is an absolute local path, and (when known) this user's own home folder and user name under /home. A path that is part of the design itself, such as /home/app/data in prose, is not flagged."
93
+ // @mitigates #context-sources against #local-path-disclosure using #refuse-before-store -- "A document carrying a file: URL, a user folder or a link to an absolute local path is refused before it is stored, so the path of the person who added it never reaches the repository"
94
+ export function scanPaths(text, who = {}) {
95
+ const rules = [
96
+ { rule: 'file: url', re: /\bfile:\/\//i },
97
+ { rule: 'macOS user folder', re: /\/Users\/[^/\s"'<>)]+\// },
98
+ { rule: 'Windows user folder', re: /\b[A-Za-z]:\\Users\\[^\\\s"'<>)]+\\/ },
99
+ { rule: 'link to a local path', re: /\]\(\s*<?(?:\/(?:home|Users|var|tmp|private|Volumes|mnt|root)\/|[A-Za-z]:\\|~\/)/ },
100
+ ];
101
+ if (who.home && who.home.length > 3) rules.push({ rule: 'home folder', re: new RegExp(escapeRe(who.home)) });
102
+ if (who.user && who.user.length > 1) rules.push({ rule: 'home folder', re: new RegExp(`/home/${escapeRe(who.user)}(?:/|\\b)`) });
103
+ const seen = new Set();
104
+ return scanLines(text, rules).filter((f) => (seen.has(f.line) ? false : (seen.add(f.line), true)));
105
+ }
106
+
107
+ // @comment -- "Embedded content: a base64 data: URI. A converted PDF leaves images behind this way; they hide whatever they hold from every scan here and from the person skimming the snapshot, and they bloat the repository."
108
+ export function scanEmbedded(text) {
109
+ return scanLines(text, [{ rule: 'embedded data: content', re: /\bdata:[a-z]+\/[a-z0-9.+-]+;base64,/i }]);
110
+ }
111
+
112
+ // @comment -- "Counts what a reader skimming the document would not see: invisible characters and HTML comments. Reported as a note, not refused: an exported page legitimately carries a few, but a snapshot with many deserves a second look before an agent reads it."
113
+ export function hiddenText(text) {
114
+ return { invisible: (text.match(INVISIBLE) ?? []).length, comments: (text.match(/<!--/g) ?? []).length };
115
+ }
116
+
117
+ const TOKEN_PARAM = /^(?:token|access_token|id_token|auth|authkey|key|apikey|api_key|secret|password|pwd|sig|signature|code|x-amz-signature|x-amz-credential|x-amz-security-token|x-goog-signature|x-goog-credential)$/i;
118
+
119
+ // @comment -- "A link is kept beside its snapshot, so it is checked as something that will be committed: http or https only, no user name or password, no secret shape anywhere in it, and no query parameter that is itself the credential (a share token, a presigned signature) unless the person keeps the query on purpose. Returns the normalized URL or the reasons it was refused."
120
+ // @mitigates #context-sources against #committed-secret using #refuse-before-store -- "A link whose query string is the credential (a presigned or share link) is refused unless the query is kept on purpose, and a URL with a user name or password is always refused"
121
+ export function checkUrl(raw, opts = {}) {
122
+ const problems = [];
123
+ let u;
124
+ try {
125
+ u = new URL(String(raw).trim());
126
+ } catch {
127
+ return { problems: ['it is not a URL'] };
128
+ }
129
+ if (u.protocol !== 'http:' && u.protocol !== 'https:') problems.push(`only http and https links are kept, not ${u.protocol}`);
130
+ if (u.username || u.password) problems.push('it carries a user name or password');
131
+ const tokens = [...u.searchParams.keys()].filter((k) => TOKEN_PARAM.test(k));
132
+ if (tokens.length && !opts.keepQuery) problems.push(`its query carries what looks like an access token (${tokens.join(', ')}): give the link without it`);
133
+ if (scanSecrets(u.href).length) problems.push('it contains a secret-shaped string');
134
+ if (u.href.length > 2000) problems.push('it is longer than 2000 characters');
135
+ return problems.length ? { problems } : { url: u.href, host: u.host, problems: [] };
136
+ }
137
+
138
+ // ---------------------------------------------------------------------------------------------
139
+ // The index
140
+ // ---------------------------------------------------------------------------------------------
141
+
142
+ const isObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
143
+ const str = (v, max) => typeof v === 'string' && v.length > 0 && v.length <= max && v === cleanLine(v, max);
144
+ const day = (v) => typeof v === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(v);
145
+ const hex = (v) => typeof v === 'string' && /^[a-f0-9]{64}$/.test(v);
146
+
147
+ // @comment -- "Reads the index as untrusted input (it is a committed, hand-editable file and a hook reads it): bounded size, exact shape, known kinds, clean one-line strings. Returns the entries that are well formed and one problem per entry that is not; it never throws."
148
+ // @mitigates #context-sources against #untrusted-index-path using #derived-source-path -- "The index carries no file path: a source's file is found by its id in the one sources folder, so an edited index cannot point the checks or an agent at another file"
149
+ export function parseIndex(text) {
150
+ const problems = [];
151
+ const bad = (message) => ({ sources: [], problems: [{ kind: 'index', file: INDEX_PATH, message }] });
152
+ if (text.length > MAX_INDEX_BYTES) return bad('the index is larger than 1 MB');
153
+ let doc;
154
+ try {
155
+ doc = JSON.parse(text);
156
+ } catch {
157
+ return bad('the index is not JSON (a merge conflict left in it?)');
158
+ }
159
+ if (!isObject(doc) || doc.schema !== SOURCES_SCHEMA || !Array.isArray(doc.sources)) return bad(`the index is not a ${SOURCES_SCHEMA} document`);
160
+ if (doc.sources.length > MAX_SOURCES) return bad(`the index lists more than ${MAX_SOURCES} sources`);
161
+ const sources = [];
162
+ const seen = new Set();
163
+ doc.sources.forEach((s, i) => {
164
+ const where = isObject(s) && typeof s.id === 'string' && ID.test(s.id) ? s.id : `entry ${i + 1}`;
165
+ const no = (message) => problems.push({ kind: 'index', file: INDEX_PATH, ...(where.startsWith('SRC-') ? { id: where } : {}), message: `${where}: ${message}` });
166
+ if (!isObject(s)) return no('is not an object');
167
+ if (typeof s.id !== 'string' || !ID.test(s.id)) return no('has no SRC-n id');
168
+ if (seen.has(s.id)) return no('is listed twice (two branches added a source with the same id: renumber one with bravos context add)');
169
+ seen.add(s.id);
170
+ if (!str(s.title, 120)) return no('needs a one-line title of at most 120 characters');
171
+ if (!KINDS.includes(s.kind)) return no(`kind must be one of ${KINDS.join(', ')}`);
172
+ if (!hex(s.sha256) || !Number.isInteger(s.bytes) || s.bytes < 0) return no('needs the sha256 and size of its text');
173
+ const o = s.origin;
174
+ if (!isObject(o) || !['file', 'link', 'pasted'].includes(o.type)) return no('needs an origin of type file, link or pasted');
175
+ if (o.type === 'file' && (!str(o.name, 200) || /[\\/]/.test(o.name) || (o.sha256 !== undefined && !hex(o.sha256)))) return no('a file origin is a bare file name, never a path');
176
+ if (o.type === 'link' && (typeof o.url !== 'string' || !day(o.fetched))) return no('a link origin needs its url and the date it was fetched');
177
+ if (!isObject(s.added) || !str(s.added.by, 80) || !day(s.added.at)) return no('needs who added it and when');
178
+ if (s.updated !== undefined && (!isObject(s.updated) || !str(s.updated.by, 80) || !day(s.updated.at))) return no('its updated field needs who and when');
179
+ sources.push(s);
180
+ });
181
+ sources.sort((a, b) => idNumber(a.id) - idNumber(b.id));
182
+ return { sources, problems };
183
+ }
184
+
185
+ export const emptyIndex = () => ({ schema: SOURCES_SCHEMA, sources: [] });
186
+ export const renderIndex = (sources) => JSON.stringify({ schema: SOURCES_SCHEMA, sources: [...sources].sort((a, b) => idNumber(a.id) - idNumber(b.id)) }, null, 2) + '\n';
187
+ export const nextId = (sources) => `SRC-${sources.reduce((m, s) => Math.max(m, idNumber(s.id)), 0) + 1}`;
188
+
189
+ /** `SRC-3-billing-prd.md`, or `SRC-3.md` when the title has no Latin letters or digits to make a name from. */
190
+ export function sourceName(id, title) {
191
+ const slug = String(title ?? '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40).replace(/-+$/, '');
192
+ return slug ? `${id}-${slug}.md` : `${id}.md`;
193
+ }
194
+ /** The one file in the sources folder that belongs to `id`, by name; null when there is none or more than one. */
195
+ export function fileFor(id, names) {
196
+ const mine = names.filter((n) => n === `${id}.md` || (n.startsWith(`${id}-`) && n.endsWith('.md')));
197
+ return mine.length === 1 ? mine[0] : null;
198
+ }
199
+
200
+ // ---------------------------------------------------------------------------------------------
201
+ // Readers: the working tree, or one commit (what a push is about to send)
202
+ // ---------------------------------------------------------------------------------------------
203
+
204
+ const git = (root, args, opts = {}) => execFileSync('git', args, { cwd: root, encoding: opts.buffer ? 'buffer' : 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 15000, maxBuffer: 16 * 1024 * 1024, ...(opts.input !== undefined ? { input: opts.input, stdio: ['pipe', 'pipe', 'ignore'] } : {}) });
205
+
206
+ // @comment -- "Reads the store from the working tree. A file is read only when it is a regular file that sits, after links are resolved, exactly where its name says inside the repository: a symlink planted in the sources folder is reported, never followed."
207
+ export function treeReader(root) {
208
+ const base = realpathSync(root);
209
+ const regular = (rel) => {
210
+ const abs = resolve(base, rel);
211
+ try {
212
+ return abs.startsWith(base + sep) && lstatSync(abs).isFile() && realpathSync(abs) === abs ? abs : null;
213
+ } catch {
214
+ return null;
215
+ }
216
+ };
217
+ return {
218
+ exists: () => existsSync(join(base, CONTEXT_DIR)),
219
+ read: (rel) => {
220
+ const abs = regular(rel);
221
+ if (!abs) return null;
222
+ try {
223
+ return lstatSync(abs).size > MAX_SOURCE_BYTES + 1 ? Buffer.alloc(MAX_SOURCE_BYTES + 1) : readFileSync(abs);
224
+ } catch {
225
+ return null;
226
+ }
227
+ },
228
+ list: (rel) => {
229
+ try {
230
+ return readdirSync(join(base, rel), { withFileTypes: true }).map((e) => ({ name: e.name, regular: !!regular(`${rel}/${e.name}`) }));
231
+ } catch {
232
+ return [];
233
+ }
234
+ },
235
+ };
236
+ }
237
+
238
+ // @comment -- "Reads the store as one commit holds it (git ls-tree, git cat-file; argv arrays, no shell), so a push is judged by what it sends and not by what happens to be in the working tree."
239
+ export function commitReader(root, commit) {
240
+ const entries = () => {
241
+ try {
242
+ return git(root, ['ls-tree', '-r', '-z', commit, '--', `${CONTEXT_DIR}/`]).split('\0').filter(Boolean).map((l) => {
243
+ const [meta, path] = l.split('\t');
244
+ const [mode, type] = meta.split(' ');
245
+ return { path, regular: type === 'blob' && mode !== '120000' };
246
+ });
247
+ } catch {
248
+ return [];
249
+ }
250
+ };
251
+ let cache;
252
+ const all = () => (cache ??= entries());
253
+ return {
254
+ exists: () => all().length > 0,
255
+ read: (rel) => {
256
+ if (!all().some((e) => e.path === rel && e.regular)) return null;
257
+ try {
258
+ return git(root, ['cat-file', 'blob', `${commit}:${rel}`], { buffer: true });
259
+ } catch {
260
+ return null;
261
+ }
262
+ },
263
+ list: (rel) => all().filter((e) => e.path.startsWith(`${rel}/`) && !e.path.slice(rel.length + 1).includes('/')).map((e) => ({ name: e.path.slice(rel.length + 1), regular: e.regular })),
264
+ };
265
+ }
266
+
267
+ // ---------------------------------------------------------------------------------------------
268
+ // The check
269
+ // ---------------------------------------------------------------------------------------------
270
+
271
+ // Files an agent writes beside the store and that are committed with it. They are scanned for local paths only.
272
+ const WRITTEN_BESIDE = ['.guardlink/intent.md', '.guardlink/intent-draft.json'];
273
+
274
+ // @comment -- "Checks the whole store and returns what is wrong: an unreadable index, a source with no file or with two, a file that is not a regular text file, text edited since it was recorded, secrets, local paths, embedded content, a link that should not be committed, a file in the folder that no entry owns, a source cited by the intent but absent, and a folder git ignores. `problems` fail the check; `notes` do not. Nothing here prints or throws, and no finding carries the text that triggered it."
275
+ export function checkContext(root, opts = {}) {
276
+ const reader = opts.reader ?? treeReader(root);
277
+ const who = opts.who ?? {};
278
+ const result = { schema: CHECK_SCHEMA, exists: false, ok: true, sources: [], problems: [], notes: [] };
279
+ const problem = (p) => result.problems.push(p);
280
+ if (!reader.exists()) return result;
281
+ result.exists = true;
282
+
283
+ const indexBytes = reader.read(INDEX_PATH);
284
+ const listing = reader.list(SOURCES_DIR);
285
+ if (!indexBytes) {
286
+ if (listing.length) problem({ kind: 'index', file: INDEX_PATH, message: 'the sources folder has files but there is no index: add each with bravos context add' });
287
+ result.ok = result.problems.length === 0;
288
+ return result;
289
+ }
290
+ const parsed = parseIndex(indexBytes.toString('utf8'));
291
+ for (const p of parsed.problems) problem(p);
292
+
293
+ for (const e of listing) if (!e.regular) problem({ kind: 'not-regular', file: `${SOURCES_DIR}/${e.name}`, message: 'it is a link or a folder, not a regular file: a source is one Markdown file' });
294
+ const names = listing.filter((e) => e.regular).map((e) => e.name);
295
+ const owned = new Set();
296
+
297
+ for (const s of parsed.sources) {
298
+ const name = fileFor(s.id, names);
299
+ const entry = { id: s.id, title: s.title, kind: s.kind, file: name ? `${SOURCES_DIR}/${name}` : null, origin: s.origin.type, state: 'ok' };
300
+ result.sources.push(entry);
301
+ if (s.origin.type === 'link') {
302
+ const u = checkUrl(s.origin.url, { keepQuery: s.origin.query === 'kept' });
303
+ for (const why of u.problems) problem({ kind: 'url', id: s.id, file: INDEX_PATH, message: `${s.id}: the link should not be committed, ${why}` });
304
+ }
305
+ if (!name) {
306
+ entry.state = 'missing';
307
+ const dup = names.filter((n) => n === `${s.id}.md` || (n.startsWith(`${s.id}-`) && n.endsWith('.md'))).length > 1;
308
+ problem({ kind: 'missing', id: s.id, file: INDEX_PATH, message: dup ? `${s.id}: more than one file in the sources folder carries this id` : `${s.id}: its file is not in the sources folder` });
309
+ continue;
310
+ }
311
+ owned.add(name);
312
+ const file = entry.file;
313
+ const decoded = decodeText(reader.read(file) ?? Buffer.alloc(0));
314
+ if (decoded.error) {
315
+ entry.state = 'unreadable';
316
+ problem({ kind: 'not-text', id: s.id, file, message: `${s.id}: ${decoded.error}` });
317
+ continue;
318
+ }
319
+ const text = decoded.text;
320
+ if (sha256(Buffer.from(text, 'utf8')) !== s.sha256) {
321
+ entry.state = 'changed';
322
+ problem({ kind: 'changed', id: s.id, file, message: `${s.id}: edited since it was recorded: run bravos context update ${s.id}, then refresh the intent that cites it` });
323
+ }
324
+ for (const f of scanSecrets(text)) problem({ kind: 'secret', id: s.id, file, line: f.line, message: `${s.id}: line ${f.line} looks like ${an(f.rule)}: replace the value with a placeholder` });
325
+ for (const f of scanPaths(text, who)) problem({ kind: 'local-path', id: s.id, file, line: f.line, message: `${s.id}: line ${f.line} carries ${an(f.rule)}: remove it or make it relative` });
326
+ for (const f of scanEmbedded(text)) problem({ kind: 'embedded', id: s.id, file, line: f.line, message: `${s.id}: line ${f.line} has ${f.rule}: describe the image in words instead` });
327
+ const hidden = hiddenText(text);
328
+ if (hidden.invisible || hidden.comments) result.notes.push(`${s.id}: ${[hidden.invisible ? `${hidden.invisible} invisible character${hidden.invisible === 1 ? '' : 's'}` : '', hidden.comments ? `${hidden.comments} HTML comment${hidden.comments === 1 ? '' : 's'}` : ''].filter(Boolean).join(' and ')} a reader would not see: skim the file`);
329
+ }
330
+ // With a damaged index nothing can be said about ownership: report the index, not every file beside it.
331
+ if (!parsed.problems.length) for (const n of names) if (!owned.has(n)) problem({ kind: 'orphan', file: `${SOURCES_DIR}/${n}`, message: 'no entry in the index owns this file: add it with bravos context add, or delete it' });
332
+
333
+ const known = new Set(parsed.sources.map((s) => s.id));
334
+ const cited = new Map();
335
+ for (const rel of WRITTEN_BESIDE) {
336
+ const buf = reader.read(rel);
337
+ if (!buf) continue;
338
+ const text = buf.toString('utf8');
339
+ for (const m of text.matchAll(/\bSRC-[1-9][0-9]{0,4}\b/g)) if (!known.has(m[0]) && !cited.has(m[0])) cited.set(m[0], rel);
340
+ for (const f of scanPaths(text, who)) problem({ kind: 'local-path', file: rel, line: f.line, message: `${rel}: line ${f.line} carries ${an(f.rule)}: cite the source by its SRC id, not by where the file was` });
341
+ }
342
+ for (const [id, rel] of cited) problem({ kind: 'cited-absent', id, file: rel, message: `${id} is cited in ${rel} but is not in the index` });
343
+
344
+ if (opts.git !== false && !opts.reader) {
345
+ try {
346
+ git(root, ['check-ignore', '-q', INDEX_PATH]);
347
+ problem({ kind: 'ignored', file: CONTEXT_DIR, message: `${CONTEXT_DIR}/ is git-ignored here, so the documents would never reach the team: remove the rule that ignores it` });
348
+ } catch {
349
+ /* exit 1: not ignored; anything else: not a repository or no git, which is not this check's concern */
350
+ }
351
+ try {
352
+ if (git(root, ['status', '--porcelain', '--', CONTEXT_DIR]).trim()) result.notes.push(`${CONTEXT_DIR}/ has changes that are not committed yet`);
353
+ } catch {
354
+ /* not a repository */
355
+ }
356
+ }
357
+ result.ok = result.problems.length === 0;
358
+ return result;
359
+ }
360
+
361
+ // @comment -- "The check as lines for a terminal: one per problem (file, then what to do), the notes, and a one-line verdict. Titles are not printed here, only ids, so nothing a document supplied reaches a CI log."
362
+ export function formatCheck(result) {
363
+ if (!result.exists) return ['context: no design documents here (.bravos/context/ is absent)'];
364
+ const lines = result.problems.map((p) => `✘ ${p.message}`);
365
+ for (const n of result.notes) lines.push(`· ${n}`);
366
+ const n = result.sources.length;
367
+ lines.push(result.ok ? `context: ${n} source${n === 1 ? '' : 's'}, nothing to fix` : `context: ${result.problems.length} problem${result.problems.length === 1 ? '' : 's'} in ${n} source${n === 1 ? '' : 's'}`);
368
+ return lines;
369
+ }
370
+
371
+ // @comment -- "What a briefing needs about the store, cheaply and without ever throwing: whether it exists, the ids it lists, and which of them the intent has fallen behind. intent.md's Sources section records the hash each document had when the rules were written (`- SRC-2: … sha256 <prefix>`); a source whose text now hashes differently is `changed`, and one the section does not list is `unread`. Ids only: a document's title or text never reaches a briefing."
372
+ export function readContext(root) {
373
+ const none = { exists: false, count: 0, ids: [], changed: [], unread: [] };
374
+ try {
375
+ const reader = treeReader(root);
376
+ if (!reader.exists()) return none;
377
+ const buf = reader.read(INDEX_PATH);
378
+ if (!buf) return { ...none, exists: true };
379
+ const { sources } = parseIndex(buf.toString('utf8'));
380
+ const intent = reader.read('.guardlink/intent.md')?.toString('utf8') ?? null;
381
+ const read = new Map();
382
+ if (intent !== null) for (const m of intent.matchAll(/^\s*[-*]\s+(SRC-[1-9][0-9]{0,4})\b.*?\bsha256\s+([a-f0-9]{8,64})\b/gm)) read.set(m[1], m[2]);
383
+ return {
384
+ exists: true,
385
+ count: sources.length,
386
+ ids: sources.map((s) => s.id),
387
+ // With no intent yet nothing is behind: the documents are simply waiting to be read.
388
+ changed: intent === null ? [] : sources.filter((s) => read.has(s.id) && !s.sha256.startsWith(read.get(s.id))).map((s) => s.id),
389
+ unread: intent === null ? [] : sources.filter((s) => !read.has(s.id)).map((s) => s.id),
390
+ };
391
+ } catch {
392
+ return none;
393
+ }
394
+ }
395
+
396
+ // ---------------------------------------------------------------------------------------------
397
+ // The gate: context before threat-modelling
398
+ // ---------------------------------------------------------------------------------------------
399
+
400
+ export const STATUS_PATH = `${CONTEXT_DIR}/status.json`;
401
+ export const STATUS_SCHEMA = 'bravos.context-status/v1';
402
+
403
+ // @comment -- "Whether threat-modelling may start here. Open when .guardlink/intent.md has at least one line a named person agreed to, or when a named person recorded that the team goes without context (.bravos/context/status.json); closed, with what to do, when there is no intent or only an unconfirmed draft. Reads two files and never throws; the same function, byte for byte, ships with the annotate skill."
404
+ // gate:begin — kept identical, between these two markers, in skills/bravos-annotate/scripts/lib/gate.mjs (the copy the
405
+ // annotate script runs, which cannot import from the hook scripts); tests/context-gate.test.ts holds the two together.
406
+ const GATE_INTENT = '.guardlink/intent.md';
407
+ const GATE_STATUS = '.bravos/context/status.json';
408
+ // A line a named person agreed to: "— accepted by Asha", "— edited by …", "— chosen by …", "— set by …". A template
409
+ // placeholder ("— set by <names>") and "— draft" do not count.
410
+ const GATE_AGREED = /—\s*(?:suggested by bravos,\s*)?(?:accepted|edited|chosen|set|confirmed) by\s+(?!<)[^\s,]/i;
411
+ const gateLine = (v, max) => String(v ?? '').replace(/[\u0000-\u001F\u007F-\u009F​-‏‪-‮⁠-⁤⁦-⁩]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, max);
412
+
413
+ export function contextGate(root, fs = { readFileSync, join }) {
414
+ const read = (rel) => {
415
+ try {
416
+ return fs.readFileSync(fs.join(root, rel), 'utf8');
417
+ } catch {
418
+ return null;
419
+ }
420
+ };
421
+ const intent = read(GATE_INTENT);
422
+ if (intent !== null && intent.split('\n').some((l) => /^\s*[-*]\s/.test(l) && GATE_AGREED.test(l))) return { open: true, state: 'confirmed', message: '' };
423
+ let status = null;
424
+ try {
425
+ status = JSON.parse(read(GATE_STATUS) ?? 'null');
426
+ } catch {
427
+ status = null;
428
+ }
429
+ if (status && typeof status === 'object' && status.schema === 'bravos.context-status/v1' && status.state === 'declined' && gateLine(status.by, 80) && /^\d{4}-\d{2}-\d{2}$/.test(String(status.at))) {
430
+ return { open: true, state: 'declined', by: gateLine(status.by, 80), at: status.at, message: '' };
431
+ }
432
+ const state = intent === null ? 'none' : 'draft';
433
+ return {
434
+ open: false,
435
+ state,
436
+ message:
437
+ (state === 'none'
438
+ ? 'Context first: nobody has told bravos what this product is meant to do, so there is nothing to judge its code against.'
439
+ : 'Context first: the intent here is still a draft that no named person has confirmed.') +
440
+ ' Run the bravos-context skill (it asks for design documents and a few decisions) before threat-modelling.' +
441
+ ' If the team chooses to go without, a named person records that: bravos context decline --by "<name>".',
442
+ };
443
+ }
444
+ // gate:end
445
+
446
+ // ---------------------------------------------------------------------------------------------
447
+ // Entry points: `node context.mjs check [dir] [--json]`, `gate [dir] [--json]` and `pre-push` (git's hook protocol on stdin)
448
+ // ---------------------------------------------------------------------------------------------
449
+
450
+ const ZERO = /^0+$/;
451
+
452
+ // @comment -- "The pre-push check. git gives one line per ref being pushed (local ref and commit, remote ref and commit). For each, when the commits being sent change anything under .bravos/context/ (or that cannot be worked out), the store is checked as the pushed commit holds it. Returns the lines to print and whether to stop the push; a push that does not touch the store is never slowed or blocked."
453
+ // @mitigates #context-sources against #committed-secret using #refuse-before-store -- "A push whose commits change the store is checked as the pushed commit holds it and stopped on a secret, a local path or a damaged index, which covers a document edited by hand and never passed through bravos context add"
454
+ export function prePush(root, stdin, who = {}) {
455
+ const lines = [];
456
+ let blocked = false;
457
+ const seen = new Set();
458
+ for (const row of String(stdin ?? '').split('\n')) {
459
+ const [, local, , remote] = row.trim().split(/\s+/);
460
+ if (!local || ZERO.test(local) || seen.has(local)) continue;
461
+ seen.add(local);
462
+ let touched = true;
463
+ try {
464
+ const base = remote && !ZERO.test(remote) ? remote : git(root, ['merge-base', local, 'refs/remotes/origin/HEAD']).trim();
465
+ touched = git(root, ['diff', '--name-only', `${base}..${local}`, '--', CONTEXT_DIR]).trim() !== '';
466
+ } catch {
467
+ touched = true;
468
+ }
469
+ if (!touched) continue;
470
+ const result = checkContext(root, { reader: commitReader(root, local), git: false, who });
471
+ if (!result.exists || result.ok) continue;
472
+ blocked = true;
473
+ lines.push(`bravos: the design documents in this push (${local.slice(0, 9)}) need fixing before they reach the remote:`, ...formatCheck(result).map((l) => ` ${l}`));
474
+ }
475
+ if (blocked) lines.push('Fix them and commit again (bravos context check shows the same list). To push anyway: git push --no-verify.');
476
+ return { blocked, lines };
477
+ }
478
+
479
+ const isMain = (() => {
480
+ try {
481
+ return !!process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href;
482
+ } catch {
483
+ return false;
484
+ }
485
+ })();
486
+
487
+ if (isMain) {
488
+ const [mode, ...rest] = process.argv.slice(2);
489
+ const who = (() => {
490
+ try {
491
+ return { home: homedir(), user: userInfo().username };
492
+ } catch {
493
+ return {};
494
+ }
495
+ })();
496
+ if (mode === 'pre-push') {
497
+ let input = '';
498
+ try {
499
+ input = readFileSync(0, 'utf8');
500
+ } catch {
501
+ /* no stdin: nothing is being pushed */
502
+ }
503
+ const { blocked, lines } = prePush(process.cwd(), input, who);
504
+ for (const l of lines) process.stderr.write(`${l}\n`);
505
+ process.exit(blocked ? 1 : 0);
506
+ } else if (mode === 'check') {
507
+ const json = rest.includes('--json');
508
+ const dir = rest.find((a) => !a.startsWith('--')) ?? process.cwd();
509
+ const result = checkContext(resolve(dir), { who });
510
+ process.stdout.write(json ? `${JSON.stringify(result, null, 2)}\n` : `${formatCheck(result).join('\n')}\n`);
511
+ process.exit(result.ok ? 0 : 1);
512
+ } else if (mode === 'gate') {
513
+ const dir = rest.find((a) => !a.startsWith('--')) ?? process.cwd();
514
+ const gate = contextGate(resolve(dir));
515
+ if (rest.includes('--json')) process.stdout.write(`${JSON.stringify(gate)}\n`);
516
+ else process.stdout.write(`${gate.open ? `context: ${gate.state === 'declined' ? `declined by ${gate.by} on ${gate.at}` : 'confirmed'}` : gate.message}\n`);
517
+ process.exit(gate.open ? 0 : 1);
518
+ } else {
519
+ process.stderr.write('usage: node context.mjs check [dir] [--json] | gate [dir] [--json] | pre-push\n');
520
+ process.exit(2);
521
+ }
522
+ }
@@ -136,6 +136,52 @@ function ledgerGateClaims(root, run, options) {
136
136
  return { claims };
137
137
  }
138
138
 
139
+ // @comment -- "Design rules this branch may have disturbed. A design rule is a threat whose id starts inv- (written by bravos-context from the team's design). For each one, the files that hold a place it is enforced (its @exposes and @mitigates, by logical file and by sidecar) are intersected with the files this branch changed. A rule whose test was last refused (it held) and whose file changed in a commit made after that test is `lapsed`: the result no longer describes the code. A rule no test has tried is only `untested`. File level on purpose: the workflow mirrors this with git and jq, and the two must agree; and a permission flipped in a role table, in another file from the check, lapses nothing in GuardLink's ledger, so the time of the change is what tells."
140
+ function designRuleChanges(root, base, run, options) {
141
+ if (!existsSync(join(root, '.guardlink', 'intent.md'))) return { lapsed: [], untested: [] };
142
+ const model = runJson(run, 'guardlink parse', 'guardlink', ['parse', '.'], options);
143
+ if (!model.ok) return model;
144
+ const bare = (id) => String(id ?? '').replace(/^#/, '');
145
+ const rules = (Array.isArray(model.json?.threats) ? model.json.threats : []).filter(t => /^inv-/i.test(bare(t?.id)));
146
+ if (!rules.length) return { lapsed: [], untested: [] };
147
+ const names = run('git', ['diff', '--name-only', '-z', `${base}...HEAD`], options);
148
+ if (names.error || names.status !== 0) return { error: `git diff --name-only ${base}...HEAD ${why(names)}` };
149
+ const changed = new Set(names.stdout.split('\0').filter(Boolean));
150
+ let records = [];
151
+ if (existsSync(join(root, '.guardlink', 'hypotheses.json'))) {
152
+ const ledger = runJson(run, 'guardlink hypothesis list', 'guardlink', ['hypothesis', 'list', '--json'], options);
153
+ if (!ledger.ok) return ledger;
154
+ if (ledger.json?.ledger !== 'present' || !Array.isArray(ledger.json.records)) return { error: 'GuardLink hypothesis ledger unreadable' };
155
+ records = ledger.json.records;
156
+ }
157
+ const sites = [...(Array.isArray(model.json.exposures) ? model.json.exposures : []), ...(Array.isArray(model.json.mitigations) ? model.json.mitigations : [])];
158
+ const lapsed = [];
159
+ const untested = [];
160
+ for (const t of rules) {
161
+ const id = bare(t.id);
162
+ const files = [...new Set(sites.filter(x => bare(x?.threat) === id).flatMap(x => [x.location?.file, x.location?.origin_file]).filter(f => typeof f === 'string' && changed.has(f)))].sort();
163
+ if (!files.length) continue;
164
+ const inv = (Array.isArray(t.external_refs) ? t.external_refs : []).map(r => /^intent:(INV-\d+)$/i.exec(String(r))?.[1]).find(Boolean) ?? null;
165
+ const held = records.filter(r => bare(r?.threat) === id && r.outcome?.outcome === 'refuted' && Number.isFinite(Date.parse(r.outcome?.at)));
166
+ const row = { threat: `#${id}`, inv, files };
167
+ if (!held.length) {
168
+ untested.push(row);
169
+ continue;
170
+ }
171
+ // The oldest of the rule's refused tests: every place must have been tested since the change.
172
+ const tested = Math.min(...held.map(r => Date.parse(r.outcome.at)));
173
+ const after = [];
174
+ for (const f of files) {
175
+ const at = run('git', ['log', '-1', '--format=%ct', `${base}..HEAD`, '--', f], options);
176
+ if (at.error || at.status !== 0) return { error: `git log ${base}..HEAD -- ${f} ${why(at)}` };
177
+ const seconds = Number(at.stdout.trim());
178
+ if (Number.isFinite(seconds) && seconds > 0 && seconds * 1000 > tested) after.push(f);
179
+ }
180
+ if (after.length) lapsed.push({ ...row, files: after, tested: new Date(tested).toISOString().slice(0, 10) });
181
+ }
182
+ return { lapsed, untested };
183
+ }
184
+
139
185
  function changeReview(root, base, env, run) {
140
186
  const o = { cwd: root, env, timeoutMs: 4000 };
141
187
  const patch = run('git', gitPatchArgs(base, 'HEAD'), o);
@@ -273,6 +319,30 @@ export function runGate({ root, action, command, cwd = root, env = process.env,
273
319
  else if (body !== null && !/proving preference/i.test(body)) blocks.push(`${say}, then retry.`);
274
320
  }
275
321
 
322
+ // (e) a design rule that was holding, on code this branch changed after its last test, is named in the PR body.
323
+ // @mitigates #replay-ledger against #stale-held-rule using #named-rule-change -- "A branch that changes a file enforcing a design rule after that rule's last refused test cannot open or ready a PR until the PR body names the rule, so a held result that no longer describes the code is never carried through review unseen"
324
+ const design = designRuleChanges(root, base, run, o);
325
+ if (design.error) unknown(design);
326
+ else {
327
+ const line = (r) => ` - ${r.inv ? `${r.inv} ` : ''}${r.threat} — ${r.files.join(', ')}${r.tested ? ` (last tested ${r.tested})` : ''}`;
328
+ if (design.lapsed.length) {
329
+ let body = null;
330
+ if (action === 'create') body = commandBody(command, cwd);
331
+ else if (action === 'ready') {
332
+ const view = runJson(run, 'gh pr view', 'gh', ['pr', 'view', ...(readyTarget(command) ? [readyTarget(command)] : []), '--json', 'body'], o);
333
+ body = view.ok && typeof view.json?.body === 'string' ? view.json.body : null;
334
+ if (body === null) unknown(view.ok ? { error: 'gh pr view JSON has no body' } : { error: 'gh pr view failed', detail: view.error });
335
+ }
336
+ const say = 'this branch changes code under a design rule that was holding, after the rule was last tested, so that result no longer describes the code';
337
+ if (action === 'check') notes.push(`bravos pre-PR gate: ${say}. Replay its test (bravos-recheck), or name the rule in the PR body:\n${design.lapsed.map(line).join('\n')}`);
338
+ else if (body !== null) {
339
+ const unnamed = design.lapsed.filter((r) => !(mentionsId(body, r.threat) || (r.inv && mentionsId(body, r.inv))));
340
+ if (unnamed.length) blocks.push(`${say}. Replay its test (bravos-recheck), or name each rule (its INV id or threat id) in the PR body so reviewers see it, then retry:\n${unnamed.map(line).join('\n')}`);
341
+ }
342
+ }
343
+ if (design.untested.length) notes.push(`bravos pre-PR gate: this branch changes code under design rule(s) no test has tried yet (bravos rules lists them):\n${design.untested.map(line).join('\n')}`);
344
+ }
345
+
276
346
  const review = changeReview(root, base, env, run);
277
347
  if (review) notes.push(review);
278
348
  if (blocks.length > 0) return { decision: 'block', reason: ['bravos pre-PR gate: blocked.', ...blocks.map((b) => `- ${b}`), ...notes].join('\n') };
@@ -30,8 +30,11 @@ export function readSetup(root, i = {}, harness = 'other') {
30
30
  },
31
31
  {
32
32
  id: 'intent',
33
- on: i.intent?.status && i.intent.status !== 'none',
34
- label: 'record what the app intends',
33
+ // Done when the context gate is open: a named person confirmed the intent, or declined. A draft nobody confirmed
34
+ // is not done, or setup would send people on to annotation while the gate still refuses it. Callers that do
35
+ // not pass the gate (older ones) keep the earlier reading: any intent at all.
36
+ on: i.gate && typeof i.gate.open === 'boolean' ? i.gate.open : !!(i.intent?.status && i.intent.status !== 'none'),
37
+ label: i.intent?.status === 'draft' ? 'confirm what the app intends' : 'record what the app intends',
35
38
  cta: skill('bravos-context', harness),
36
39
  unlocks: 'severities judged against what the software is meant to do and which attackers are in scope',
37
40
  how: `ask "learn what this app intends" (${skill('bravos-context', harness)})`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bugb-technologies/bravos",
3
- "version": "1.5.2",
3
+ "version": "1.6.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",
@@ -18,7 +18,7 @@ description: "Start here in any repo bravos is installed in: reads the security
18
18
  claim (an annotation says code is exposed or mitigated) → testable template → authorized run against a target the user owns → verified outcome → recheck when the code changes.
19
19
  Three states are independent of each other: open / mitigated / accepted · untested / confirmed / refuted · verified / stale. A mitigated claim can still be untested; a confirmed one can go stale.
20
20
  3. Route the request:
21
- no `.guardlink/intent.md` yet, business logic, "what matters here", "is this intended?", learning the app → bravos-context (run it before a first annotation pass).
21
+ no `.guardlink/intent.md` yet, business logic, "what matters here", "is this intended?", learning the app → bravos-context (it comes before a first annotation pass: bravos-annotate and campaigns wait until a named person has confirmed the intent, or declined with `bravos context decline`).
22
22
  coverage, annotating, "threat-model this", a worklist in the briefing → bravos-annotate.
23
23
  reachability, blast radius, "is this live", tracing a handler to sinks → bravos-codegraph.
24
24
  before a PR, push for review, or marking a draft ready → bravos-ship.