@bugb-technologies/bravos 1.5.3 → 1.7.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/cli.js +81 -9
  2. package/dist/context.js +387 -0
  3. package/dist/dashboard.js +19 -5
  4. package/dist/guide.js +5 -2
  5. package/dist/help.js +19 -0
  6. package/dist/palette.js +4 -4
  7. package/dist/review-server.js +4 -4
  8. package/dist/review.js +103 -18
  9. package/dist/rules.js +218 -0
  10. package/dist/uninstall.js +6 -0
  11. package/dist/watch-frame.js +67 -42
  12. package/dist/watch.js +21 -7
  13. package/docs/GUIDE.md +20 -2
  14. package/docs/UPGRADING.md +28 -0
  15. package/hooks/lib/autopilot.mjs +29 -7
  16. package/hooks/lib/briefing.mjs +214 -171
  17. package/hooks/lib/context.mjs +522 -0
  18. package/hooks/lib/palette.mjs +4 -4
  19. package/hooks/lib/pre-pr.mjs +70 -0
  20. package/hooks/lib/setup.mjs +5 -2
  21. package/hooks/session-start.mjs +24 -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-context/SKILL.md +17 -10
  29. package/skills/bravos-context/intent.example.md +14 -1
  30. package/skills/bravos-recheck/SKILL.md +1 -1
  31. package/skills/bravos-ship/SKILL.md +2 -1
  32. package/skills/bravos-templatize/SKILL.md +1 -1
  33. package/templates/dashboard/dashboard.html +97 -0
  34. package/templates/review/review.html +368 -123
  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
package/dist/cli.js CHANGED
@@ -11,7 +11,9 @@ import { writeCursorPointer } from './cursor.js';
11
11
  import { writeOmpExtension } from './omp.js';
12
12
  import { homeOf, installGlobal } from './global.js';
13
13
  import { uninstall } from './uninstall.js';
14
- import { checkKind, newToken, readAllAnswers, readDraft, renderReview, summarize, writePage } from './review.js';
14
+ import { checkKind, newToken, prepareReview, readAllAnswers, readDraft, renderReview, summarize, writePage } from './review.js';
15
+ import { addSource, checkSources, declineContext, gateFor, installPrePush, listSources, updateSource } from './context.js';
16
+ import { formatRules, gatherRules } from './rules.js';
15
17
  import { spawn as spawnChild, spawnSync } from 'node:child_process';
16
18
  import { createServer as netServer } from 'node:net';
17
19
  import { dirname as pathDirname, join as pathJoin } from 'node:path';
@@ -64,6 +66,15 @@ function parseAgents(value) {
64
66
  return out;
65
67
  }
66
68
  const names = (list) => (list.length ? list.join(', ') : 'none');
69
+ // @comment -- "Everything on standard input, for `bravos context add -`: how converted text arrives without first being a file. Empty when nothing is piped in."
70
+ const readStdin = () => {
71
+ try {
72
+ return process.stdin.isTTY ? Buffer.alloc(0) : readFileSync(0);
73
+ }
74
+ catch {
75
+ return Buffer.alloc(0);
76
+ }
77
+ };
67
78
  // @comment -- "Asks git (one `git check-ignore --stdin`, argv array, cwd root) which of the repo-relative paths bravos wrote are ignored and returns one warning per ignored top-level directory; silent when git is absent, the dir is not a repo, or nothing is ignored."
68
79
  function gitignoreWarnings(root, paths, env) {
69
80
  if (paths.length === 0)
@@ -230,6 +241,10 @@ function pipeline(root, io, opts, withGuardlink, lines) {
230
241
  }
231
242
  for (const r of hook.registered)
232
243
  lines.push(`Hooks: ${r.file} ${r.changed ? 'registered' : 'already registered'}`);
244
+ // A repository that keeps design documents gets the pre-push check in every clone that runs init or sync, not only
245
+ // in the clone of whoever added the first one.
246
+ if (!dryRun && !opts.global && existsSync(join(root, '.bravos', 'context', 'sources.json')))
247
+ lines.push(...installPrePush(root, io.env));
233
248
  // An agent left out of --agent keeps its own settings, which may still run the old-name hook the migration moved.
234
249
  for (const w of oldHookReferences(root))
235
250
  lines.push(w);
@@ -581,10 +596,10 @@ export function buildProgram(io, result) {
581
596
  .allowUnknownOption()
582
597
  .helpOption(false)
583
598
  .action((name, args) => guarded((lines) => {
584
- const known = ['session-start', 'pre-pr', 'autopilot', 'replay'];
599
+ const known = ['session-start', 'pre-pr', 'autopilot', 'replay', 'context'];
585
600
  if (!known.includes(name))
586
601
  throw new BravosError(`unknown hook '${name}'; use ${known.join(', ')}`);
587
- const script = name === 'replay' ? 'lib/replay.mjs' : `${name}.mjs`;
602
+ const script = name === 'replay' || name === 'context' ? `lib/${name}.mjs` : `${name}.mjs`;
588
603
  const r = spawnSync(process.execPath, [pathJoin(hooksDir(), script), ...args], { env: io.env, encoding: 'utf8', stdio: ['inherit', 'pipe', 'pipe'], maxBuffer: 16 * 1024 * 1024 });
589
604
  if (r.stdout)
590
605
  lines.push(r.stdout.replace(/\n$/, ''));
@@ -688,6 +703,63 @@ export function buildProgram(io, result) {
688
703
  if (r.unregistered.some((u) => u.includes('.codex')))
689
704
  lines.push('Codex keeps its own trust record for removed hooks; nothing to do there.');
690
705
  }));
706
+ // @comment -- "bravos context: the design documents behind the threat model. add and update take text (a file, or - for standard input) and refuse a secret, a local path or embedded content before anything is written; list and check read. Free on every plan and runs no model: converting a PDF or fetching a link is the coding agent's job, in the session, with the person's own access."
707
+ program
708
+ .command('context <action> [args...]')
709
+ .description('Keep the design documents behind the threat model in the repository (.bravos/context/, committed): `context add <file.md|-> --title "<what it is>" --kind prd` stores a document after checking it for secrets and local paths; `context update SRC-n [file]` replaces it or records a hand edit; `context list`; `context check`; `context gate` says whether threat-modelling may start (context confirmed, or declined); `context decline --by "<name>"` records that a named person chose to go without. Text only: your coding agent converts PDFs and fetches links. Free; runs no model.')
710
+ .option('-C, --dir <dir>', 'the repository (default: the current directory)')
711
+ .option('--title <title>', 'add/update: what the document is, in a few words')
712
+ .option('--kind <kind>', 'add/update: prd, design, threat-model, policy, api, upstream or other')
713
+ .option('--by <name>', 'add/update: who is adding it (default: git user.name)')
714
+ .option('--original <file>', 'add/update: the file this text was converted from; only its name and hash are kept')
715
+ .option('--url <url>', 'add/update: the link this text was fetched from; kept in full beside the snapshot')
716
+ .option('--keep-query', 'add/update: keep a link whose query looks like an access token')
717
+ .option('--reason <why>', 'decline: why the team goes without design context')
718
+ .option('--json', 'list/check/gate: print JSON')
719
+ .action((action, args, opts) => guardedAsync(async (lines) => {
720
+ const dir = dirArg(opts.dir);
721
+ const source = (from) => (from === '-' ? { from, stdin: readStdin() } : { from });
722
+ if (action === 'add') {
723
+ if (args.length !== 1)
724
+ throw new BravosError('usage: bravos context add <file.md|-> --title "<what it is>" [--kind prd] [--url <link> | --original <file>]');
725
+ lines.push(...(await addSource(dir, source(args[0]), opts, io.env)));
726
+ }
727
+ else if (action === 'update') {
728
+ if (args.length < 1 || args.length > 2)
729
+ throw new BravosError('usage: bravos context update SRC-n [file.md|-]');
730
+ lines.push(...(await updateSource(dir, args[0], args[1] ? source(args[1]) : null, opts, io.env)));
731
+ }
732
+ else if (action === 'list') {
733
+ lines.push(...(await listSources(dir, io.env, !!opts.json)));
734
+ }
735
+ else if (action === 'check') {
736
+ const { result: checked, lines: said } = await checkSources(dir, io.env);
737
+ lines.push(...(opts.json ? [JSON.stringify(checked, null, 2)] : said));
738
+ if (!checked.ok)
739
+ result.code = 1;
740
+ }
741
+ else if (action === 'gate') {
742
+ // Exit 0 when threat-modelling may start here, 1 with what to do when it may not.
743
+ const gate = await gateFor(dir, io.env);
744
+ lines.push(opts.json ? JSON.stringify(gate) : gate.open ? `context: ${gate.state === 'declined' ? `declined by ${gate.by} on ${gate.at}` : 'confirmed'}` : gate.message);
745
+ if (!gate.open)
746
+ result.code = 1;
747
+ }
748
+ else if (action === 'decline') {
749
+ lines.push(...(await declineContext(dir, opts, io.env)));
750
+ }
751
+ else
752
+ throw new BravosError(`unknown context action '${action}'; use add, update, list, check, gate or decline`);
753
+ }));
754
+ // @comment -- "bravos rules: the design rules (INV-n in the intent, each a #inv- threat) with where the code enforces each and what testing has shown. Read-only and free; runs guardlink parse and hypothesis list, no model."
755
+ program
756
+ .command('rules [dir]')
757
+ .description('List the design rules from .guardlink/intent.md (the business-logic rules your design states) with each one\'s status: broken, retest due, holds, unguarded, guarded but untested, or not placed, and where the code enforces it. Read-only; free; runs no model. bravos dashboard shows the same as its Design rules view.')
758
+ .option('--json', 'print bravos.rules/v1')
759
+ .action((dir, opts) => guardedAsync(async (lines) => {
760
+ const doc = await gatherRules(dirArg(dir), io.env);
761
+ lines.push(...(opts.json ? [JSON.stringify(doc, null, 2)] : formatRules(doc)));
762
+ }));
691
763
  program
692
764
  .command('review <kind> [dir]')
693
765
  .description("Open bravos's questions (.guardlink/<kind>-draft.json, e.g. kind 'intent') as a branded page people answer in; answers are saved to .guardlink/<kind>-answers/<name>.json. Runs no model.")
@@ -705,7 +777,7 @@ export function buildProgram(io, result) {
705
777
  return;
706
778
  }
707
779
  if (opts.share) {
708
- const rel = writePage(root, `${kind}-share`, await renderReview(draft, { kind: 'artifact' }));
780
+ const rel = writePage(root, `${kind}-share`, await renderReview(await prepareReview(root, draft), { kind: 'artifact' }));
709
781
  lines.push(`Share page: ${rel}`);
710
782
  lines.push('Sharing publishes your security intent to claude.ai, private until you share the link; teammates need access there.');
711
783
  lines.push('In Claude Code: publish that file with the Artifact tool and capabilities {db: {}}; share the link with the team.');
@@ -714,8 +786,8 @@ export function buildProgram(io, result) {
714
786
  return;
715
787
  }
716
788
  if (opts.serve === false) {
717
- const rel = writePage(root, kind, await renderReview(draft, { kind: 'file' }));
718
- lines.push(`Review page: ${rel} (Save downloads your answers; put them in .guardlink/${kind}-answers/ and commit)`);
789
+ const rel = writePage(root, kind, await renderReview(await prepareReview(root, draft), { kind: 'file' }));
790
+ lines.push(`Review page: ${rel} (includes available cited document text; Save downloads your answers; put them in .guardlink/${kind}-answers/ and commit)`);
719
791
  if (opts.open !== false)
720
792
  openInBrowser(pathJoin(root, rel), io.env);
721
793
  return;
@@ -787,7 +859,7 @@ export function buildProgram(io, result) {
787
859
  }));
788
860
  program
789
861
  .command('dashboard [dir]')
790
- .description("One page for the repository's security picture, opened in the browser: GuardLink's threat model with who introduced and fixed each exposure and what changed since the default branch, and on the Team plan the code graph (map, owners, coupling, attack surface, entry points). Rebuilt from the code every time: on the Team plan a code graph that is missing or behind is rebuilt first. Written to .bravos/dashboard/index.html (git-ignored); one self-contained file, no server, no network, no model.")
862
+ .description("One page for the repository's security picture, opened in the browser: GuardLink's threat model with who introduced and fixed each exposure and what changed since the default branch, the design rules from your intent with which hold and which are broken or due a retest, and on the Team plan the code graph (map, owners, coupling, attack surface, entry points). Rebuilt from the code every time: on the Team plan a code graph that is missing or behind is rebuilt first. Written to .bravos/dashboard/index.html (git-ignored); one self-contained file, no server, no network, no model.")
791
863
  .option('--out <file>', 'write the page here instead; nothing is then written inside the repository')
792
864
  .option('--since <ref>', "compare against this branch, tag or commit instead of the repository's default branch")
793
865
  .option('--no-blame', 'leave git names out (who introduced and fixed each exposure, and the code graph\'s owners), for a page you will share')
@@ -802,10 +874,10 @@ export function buildProgram(io, result) {
802
874
  // Opening is a convenience: the path is always printed, and a session with no display just reads it.
803
875
  const opened = opts.open !== false && !opts.json && openInBrowser(r.path, io.env);
804
876
  if (opts.json) {
805
- lines.push(JSON.stringify({ schema: 'bravos.dashboard-run/v1', path: r.path, opened, threatModel: r.threatModel, codeGraph: r.codeGraph }, null, 2));
877
+ lines.push(JSON.stringify({ schema: 'bravos.dashboard-run/v1', path: r.path, opened, threatModel: r.threatModel, rules: r.rules, codeGraph: r.codeGraph }, null, 2));
806
878
  return;
807
879
  }
808
- lines.push(`Dashboard: ${r.path}${opened ? ' (opened in your browser)' : ''}`, ` threat model: ${r.threatModel.note}`, ` code graph: ${r.codeGraph.note}`);
880
+ lines.push(`Dashboard: ${r.path}${opened ? ' (opened in your browser)' : ''}`, ` threat model: ${r.threatModel.note}`, ` design rules: ${r.rules.note}`, ` code graph: ${r.codeGraph.note}`);
809
881
  if (!opened && opts.open !== false)
810
882
  lines.push(' No browser could be opened here; open the file above.');
811
883
  }));
@@ -0,0 +1,387 @@
1
+ // @comment -- "bravos context: the design documents a team gives bravos (PRDs, design documents, earlier threat models), kept as committed Markdown under .bravos/context/ so every rule can name the document it came from. This side adds, updates and lists; the checks themselves live in hooks/lib/context.mjs, which a pre-push hook and CI also run. The CLI takes text only: it never fetches a link, converts a document or runs a model, and it never records where on this machine a file came from."
2
+ import { execFileSync } from 'node:child_process';
3
+ import { createHash } from 'node:crypto';
4
+ import { chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
5
+ import { homedir, userInfo } from 'node:os';
6
+ import { basename, isAbsolute, join, resolve } from 'node:path';
7
+ import { pathToFileURL } from 'node:url';
8
+ import { hooksDir } from './paths.js';
9
+ import { BravosError } from './types.js';
10
+ let cached;
11
+ export const contextLib = () => (cached ??= import(pathToFileURL(join(hooksDir(), 'lib', 'context.mjs')).href));
12
+ const today = (now = new Date()) => now.toISOString().slice(0, 10);
13
+ export const whoAmI = (env) => {
14
+ try {
15
+ return { home: env.HOME || homedir(), user: env.USER || env.LOGNAME || userInfo().username };
16
+ }
17
+ catch {
18
+ return { home: env.HOME };
19
+ }
20
+ };
21
+ const git = (root, args, env) => {
22
+ try {
23
+ return execFileSync('git', args, { cwd: root, env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 10000 }).trim();
24
+ }
25
+ catch {
26
+ return null;
27
+ }
28
+ };
29
+ // @comment -- "The folder the store belongs to: the top of the git repository holding `dir`, so a command run from a subfolder cannot start a second store; `dir` itself where there is no repository."
30
+ export function storeRoot(dir, env) {
31
+ const abs = resolve(dir);
32
+ return git(abs, ['rev-parse', '--show-toplevel'], env) || abs;
33
+ }
34
+ // @comment -- "Reads the text to store. A path must be a regular file, not a link, a folder or a device, and its size is checked before it is read; '-' takes what the caller read from standard input, which is how converted text arrives without ever being a file in the worktree. Returns the bytes and the bare file name."
35
+ // @mitigates #context-sources against #committed-secret using #refuse-before-store -- "Only a regular file under the size cap is read: a link, a device or a folder handed to bravos context add is refused, so the command cannot be pointed through a link at another file"
36
+ function readInput(input, L, cwd) {
37
+ if (input.from === '-') {
38
+ if (!input.stdin || input.stdin.length === 0)
39
+ throw new BravosError('nothing arrived on standard input: pipe the document in, e.g. cat prd.md | bravos context add - --title "Billing PRD"');
40
+ return { bytes: input.stdin, name: null };
41
+ }
42
+ const abs = isAbsolute(input.from) ? input.from : resolve(cwd, input.from);
43
+ let st;
44
+ try {
45
+ st = lstatSync(abs);
46
+ }
47
+ catch {
48
+ throw new BravosError(`no file at ${input.from}`);
49
+ }
50
+ if (!st.isFile())
51
+ throw new BravosError(`${basename(abs)} is not a regular file (a link, a folder or a device): give the document itself`);
52
+ if (st.size > L.MAX_SOURCE_BYTES)
53
+ throw new BravosError(`${basename(abs)} is ${st.size} bytes, past the ${L.MAX_SOURCE_BYTES}-byte limit for one document: split it, or keep only the parts about how the product should behave`);
54
+ return { bytes: readFileSync(abs), name: basename(abs) };
55
+ }
56
+ // @comment -- "The text as it will be stored, or a refusal that lists what is wrong by line number and kind: not text, a secret-shaped string, a local path, embedded content. Nothing is written when anything is refused, and the refusal never repeats the offending text."
57
+ function vet(bytes, L, who, what, verdict = 'was not stored') {
58
+ const decoded = L.decodeText(bytes);
59
+ if (decoded.error || decoded.text === undefined)
60
+ throw new BravosError(`${what}: ${decoded.error}`);
61
+ const text = decoded.text.endsWith('\n') ? decoded.text : `${decoded.text}\n`;
62
+ if (!text.trim())
63
+ throw new BravosError(`${what}: it is empty`);
64
+ const findings = [
65
+ ...L.scanSecrets(text).map((f) => ` line ${f.line}: looks like ${L.an(f.rule)}`),
66
+ ...L.scanPaths(text, who).map((f) => ` line ${f.line}: ${L.an(f.rule)}`),
67
+ ...L.scanEmbedded(text).map((f) => ` line ${f.line}: ${f.rule}`),
68
+ ];
69
+ if (findings.length) {
70
+ throw new BravosError([`${what} ${verdict}. It would be committed for the whole team to read, and it has:`, ...findings.slice(0, 40), ...(findings.length > 40 ? [` and ${findings.length - 40} more`] : []), 'Replace each secret with a placeholder such as <redacted>, remove local paths, describe an embedded image in words, then try again.'].join('\n'));
71
+ }
72
+ return text;
73
+ }
74
+ function loadIndex(root, L) {
75
+ const abs = join(root, L.INDEX_PATH);
76
+ if (!existsSync(abs))
77
+ return [];
78
+ const parsed = L.parseIndex(readFileSync(abs, 'utf8'));
79
+ if (parsed.problems.length)
80
+ throw new BravosError([`${L.INDEX_PATH} needs fixing before anything is added to it:`, ...parsed.problems.map((p) => ` ${p.message}`), 'bravos context check shows the same list.'].join('\n'));
81
+ return parsed.sources;
82
+ }
83
+ // @comment -- "Only the local review includes document bodies. Use the context store's regular-file reader, match the recorded hash and recheck the exact bytes before displaying them. The draft can cite an id, never choose a path. Keep the total payload bounded even in a large store."
84
+ // @mitigates #context-sources against #untrusted-index-path using #derived-source-path -- "A citation selects an indexed source by id. Its Markdown file must resolve to its own location under the store and match the recorded digest."
85
+ export async function reviewSources(root, cited) {
86
+ if (!cited.size)
87
+ return [];
88
+ const lib = await contextLib();
89
+ const reader = lib.treeReader(root);
90
+ const index = reader.read(lib.INDEX_PATH);
91
+ if (!index)
92
+ return [];
93
+ const parsed = lib.parseIndex(index.toString('utf8'));
94
+ if (parsed.problems.length)
95
+ return [];
96
+ const names = reader.list(lib.SOURCES_DIR).map((entry) => entry.name);
97
+ const who = whoAmI(process.env);
98
+ const docs = [];
99
+ let remaining = 8 * 1024 * 1024;
100
+ for (const { id, title, kind, bytes, sha256 } of parsed.sources) {
101
+ if (!cited.has(id) || bytes > Math.min(remaining, lib.MAX_SOURCE_BYTES))
102
+ continue;
103
+ const name = lib.fileFor(id, names);
104
+ const data = name ? reader.read(`${lib.SOURCES_DIR}/${name}`) : null;
105
+ if (!data || data.length !== bytes || lib.sha256(data) !== sha256)
106
+ continue;
107
+ try {
108
+ vet(Buffer.from(title), lib, who, id);
109
+ const text = vet(data, lib, who, id);
110
+ docs.push({ id, title, kind, sha256, text });
111
+ remaining -= bytes;
112
+ }
113
+ catch {
114
+ // The review still shows the citation. Only verified, safe text may accompany it.
115
+ }
116
+ }
117
+ return docs;
118
+ }
119
+ function writeAtomic(abs, data) {
120
+ const tmp = `${abs}.writing-${process.pid}`;
121
+ writeFileSync(tmp, data, { mode: 0o644 });
122
+ renameSync(tmp, abs);
123
+ }
124
+ // @comment -- "Refuses to store anything where git ignores the folder: the documents are meant to be committed for the team, and an ignore rule would quietly keep them on one machine."
125
+ function refuseIfIgnored(root, L, env) {
126
+ try {
127
+ execFileSync('git', ['check-ignore', '-q', L.INDEX_PATH], { cwd: root, env, stdio: 'ignore', timeout: 10000 });
128
+ }
129
+ catch {
130
+ return; // exit 1: not ignored. 128 or no git: not a repository, nothing to defeat.
131
+ }
132
+ throw new BravosError(`${L.CONTEXT_DIR}/ is git-ignored in this repository, so the documents would never reach the team: remove the rule that ignores it (git check-ignore -v ${L.INDEX_PATH} names it), then add again`);
133
+ }
134
+ function byline(opts, root, env, L) {
135
+ const by = L.cleanLine(opts.by ?? git(root, ['config', 'user.name'], env) ?? '', 80);
136
+ if (!by)
137
+ throw new BravosError('who is adding this? give --by "<your name>" (git has no user.name set here)');
138
+ return by;
139
+ }
140
+ function originFor(input, opts, L, cwd, now) {
141
+ if (opts.url) {
142
+ const u = L.checkUrl(opts.url, { keepQuery: opts.keepQuery });
143
+ if (!u.url)
144
+ throw new BravosError(`the link was not kept: ${u.problems.join('; ')}`);
145
+ return { type: 'link', url: u.url, fetched: today(now), ...(opts.keepQuery ? { query: 'kept' } : {}) };
146
+ }
147
+ if (opts.original) {
148
+ const abs = isAbsolute(opts.original) ? opts.original : resolve(cwd, opts.original);
149
+ let st;
150
+ try {
151
+ st = lstatSync(abs);
152
+ }
153
+ catch {
154
+ throw new BravosError(`--original: no file at ${opts.original}`);
155
+ }
156
+ if (!st.isFile())
157
+ throw new BravosError('--original must be the document file itself, not a link or a folder');
158
+ const name = L.cleanLine(basename(abs), 200).replace(/[\\/]/g, '-');
159
+ // Hashed, never copied: the original may be a binary of any size, and only its identity is recorded.
160
+ return { type: 'file', name, sha256: createHash('sha256').update(readFileSync(abs)).digest('hex') };
161
+ }
162
+ if (input.name)
163
+ return { type: 'file', name: L.cleanLine(input.name, 200).replace(/[\\/]/g, '-'), sha256: L.sha256(input.bytes) };
164
+ return { type: 'pasted' };
165
+ }
166
+ const firstHeading = (text) => (/^#{1,3}\s+(.+)$/m.exec(text)?.[1] ?? '').trim();
167
+ const size = (n) => (n < 1024 ? `${n} B` : n < 1024 * 1024 ? `${(n / 1024).toFixed(1)} kB` : `${(n / 1048576).toFixed(1)} MB`);
168
+ // @comment -- "bravos context add: vets the text, gives it the next SRC id, writes it as sources/SRC-n-<title>.md and records it in the index with its kind, hash, who added it and where it came from (a file name, a link, or pasted). The local path of the file is used to read it and is not written anywhere. The first source in a repository also installs the pre-push check."
169
+ export async function addSource(dir, input, opts, env, cwd = process.cwd()) {
170
+ const L = await contextLib();
171
+ const root = storeRoot(dir, env);
172
+ refuseIfIgnored(root, L, env);
173
+ const sources = loadIndex(root, L);
174
+ if (sources.length >= L.MAX_SOURCES)
175
+ throw new BravosError(`this repository already has ${L.MAX_SOURCES} sources: remove ones nobody cites before adding more`);
176
+ const read = readInput(input, L, cwd);
177
+ const text = vet(read.bytes, L, whoAmI(env), read.name ?? 'the document');
178
+ const kind = opts.kind ?? 'other';
179
+ if (!L.KINDS.includes(kind))
180
+ throw new BravosError(`--kind must be one of ${L.KINDS.join(', ')}`);
181
+ const title = L.cleanLine(opts.title ?? firstHeading(text), 120) || L.cleanLine((read.name ?? '').replace(/\.[A-Za-z0-9]{1,8}$/, ''), 120);
182
+ if (!title)
183
+ throw new BravosError('give the document a title: --title "<what it is>"');
184
+ const now = opts.now ?? new Date();
185
+ const by = byline(opts, root, env, L);
186
+ const origin = originFor(read, opts, L, cwd, now);
187
+ const id = L.nextId(sources);
188
+ const name = L.sourceName(id, title);
189
+ const stored = Buffer.from(text, 'utf8');
190
+ const entry = { id, title, kind, sha256: L.sha256(stored), bytes: stored.length, origin, added: { by, at: today(now) } };
191
+ const first = sources.length === 0 && !existsSync(join(root, L.INDEX_PATH));
192
+ mkdirSync(join(root, L.SOURCES_DIR), { recursive: true });
193
+ writeAtomic(join(root, L.SOURCES_DIR, name), stored);
194
+ writeAtomic(join(root, L.INDEX_PATH), L.renderIndex([...sources, entry]));
195
+ const lines = [`${id} added: ${title} (${kind}, ${size(stored.length)})`, ` stored as ${L.SOURCES_DIR}/${name}; where the file was on this machine is not recorded`];
196
+ if (origin.type === 'link')
197
+ lines.push(` link kept in full: ${origin.url}`);
198
+ const hidden = L.hiddenText(text);
199
+ if (hidden.invisible || hidden.comments)
200
+ lines.push(` note: it has ${[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 stored file`);
201
+ if (first) {
202
+ lines.push(`Everyone with access to this repository can read what is added under ${L.CONTEXT_DIR}/, and links are kept in full.`);
203
+ lines.push(...installPrePush(root, env));
204
+ }
205
+ lines.push(`Commit it with the team's other context: git add ${L.CONTEXT_DIR}`);
206
+ return lines;
207
+ }
208
+ // @comment -- "bravos context update SRC-n [file]: with a file (or '-'), replaces the stored text after the same vetting; with none, records the file as it now stands, which is how a hand edit is accepted. Either way the stored text must pass the checks, the hash and size are refreshed, and who updated it and when is recorded."
209
+ export async function updateSource(dir, id, input, opts, env, cwd = process.cwd()) {
210
+ const L = await contextLib();
211
+ const root = storeRoot(dir, env);
212
+ if (!L.ID.test(id))
213
+ throw new BravosError(`'${id}' is not a source id: they look like SRC-3 (bravos context list shows them)`);
214
+ const sources = loadIndex(root, L);
215
+ const entry = sources.find((s) => s.id === id);
216
+ if (!entry)
217
+ throw new BravosError(`there is no ${id} in ${L.INDEX_PATH}`);
218
+ let names = [];
219
+ try {
220
+ names = readdirSync(join(root, L.SOURCES_DIR));
221
+ }
222
+ catch {
223
+ /* no folder: handled below */
224
+ }
225
+ const name = L.fileFor(id, names);
226
+ const who = whoAmI(env);
227
+ let text;
228
+ let read = null;
229
+ if (input) {
230
+ read = readInput(input, L, cwd);
231
+ text = vet(read.bytes, L, who, read.name ?? 'the document');
232
+ }
233
+ else {
234
+ if (!name)
235
+ throw new BravosError(`${id} has no single file in ${L.SOURCES_DIR}/: restore it, or give the new text (bravos context update ${id} <file>)`);
236
+ const abs = join(root, L.SOURCES_DIR, name);
237
+ if (!lstatSync(abs).isFile())
238
+ throw new BravosError(`${L.SOURCES_DIR}/${name} is not a regular file`);
239
+ text = vet(readFileSync(abs), L, who, `${L.SOURCES_DIR}/${name}`, 'was not recorded');
240
+ }
241
+ const now = opts.now ?? new Date();
242
+ const stored = Buffer.from(text, 'utf8');
243
+ const before = entry.sha256;
244
+ entry.sha256 = L.sha256(stored);
245
+ entry.bytes = stored.length;
246
+ if (opts.title)
247
+ entry.title = L.cleanLine(opts.title, 120) || entry.title;
248
+ if (opts.kind) {
249
+ if (!L.KINDS.includes(opts.kind))
250
+ throw new BravosError(`--kind must be one of ${L.KINDS.join(', ')}`);
251
+ entry.kind = opts.kind;
252
+ }
253
+ if (read && (opts.url || opts.original || read.name))
254
+ entry.origin = originFor(read, opts, L, cwd, now);
255
+ entry.updated = { by: byline(opts, root, env, L), at: today(now) };
256
+ const target = name ?? L.sourceName(id, entry.title);
257
+ mkdirSync(join(root, L.SOURCES_DIR), { recursive: true });
258
+ writeAtomic(join(root, L.SOURCES_DIR, target), stored);
259
+ writeAtomic(join(root, L.INDEX_PATH), L.renderIndex(sources));
260
+ const changed = before !== entry.sha256;
261
+ return [
262
+ changed ? `${id} updated: ${entry.title} (${size(stored.length)})` : `${id} recorded: the text is unchanged`,
263
+ ...(changed ? [` rules that cite ${id} were written from the earlier text: refresh the intent (the bravos-context skill) so they are checked against this one`] : []),
264
+ ];
265
+ }
266
+ // @comment -- "bravos context list: one line per source (id, kind, title, size, who added it, and for a link its site), or with --json the index entries beside each one's state from the check."
267
+ export async function listSources(dir, env, json = false) {
268
+ const L = await contextLib();
269
+ const root = storeRoot(dir, env);
270
+ const abs = join(root, L.INDEX_PATH);
271
+ if (!existsSync(abs))
272
+ return json ? [JSON.stringify({ schema: 'bravos.context-list/v1', sources: [] }, null, 2)] : ['No design documents yet. Add one: bravos context add <file.md> --title "<what it is>" --kind prd'];
273
+ const sources = L.parseIndex(readFileSync(abs, 'utf8')).sources;
274
+ const check = L.checkContext(root, { who: whoAmI(env) });
275
+ const state = (id) => check.sources.find((s) => s.id === id)?.state ?? 'ok';
276
+ const file = (id) => check.sources.find((s) => s.id === id)?.file ?? null;
277
+ if (json)
278
+ return [JSON.stringify({ schema: 'bravos.context-list/v1', sources: sources.map((s) => ({ ...s, file: file(s.id), state: state(s.id) })) }, null, 2)];
279
+ const lines = sources.map((s) => {
280
+ const from = s.origin.type === 'link' ? ` · ${hostOf(s.origin.url)}` : '';
281
+ const st = state(s.id) === 'ok' ? '' : ` [${state(s.id)}]`;
282
+ return `${s.id.padEnd(7)} ${s.kind.padEnd(12)} ${s.title} (${size(s.bytes)}, ${s.added.by}, ${s.updated?.at ?? s.added.at}${from})${st}`;
283
+ });
284
+ if (!check.ok)
285
+ lines.push(`${check.problems.length} problem${check.problems.length === 1 ? '' : 's'}: bravos context check`);
286
+ return lines;
287
+ }
288
+ const hostOf = (url) => {
289
+ try {
290
+ return new URL(url ?? '').host;
291
+ }
292
+ catch {
293
+ return 'link';
294
+ }
295
+ };
296
+ // @comment -- "bravos context check: the store's problems as lines or JSON, and whether it passed. The same function the pre-push hook and CI run."
297
+ export async function checkSources(dir, env) {
298
+ const L = await contextLib();
299
+ const result = L.checkContext(storeRoot(dir, env), { who: whoAmI(env) });
300
+ return { result, lines: L.formatCheck(result) };
301
+ }
302
+ // ---------------------------------------------------------------------------------------------
303
+ // Context before threat-modelling
304
+ // ---------------------------------------------------------------------------------------------
305
+ // @comment -- "Whether threat-modelling may start in this repository (hooks/lib/context.mjs contextGate), for the CLI and the tests."
306
+ export async function gateFor(dir, env) {
307
+ return (await contextLib()).contextGate(storeRoot(dir, env));
308
+ }
309
+ // @comment -- "bravos context decline --by <name>: records, in the committed .bravos/context/status.json, that a named person chose to threat-model this repository without design context. It is the one way past the context gate other than doing the context step, so the name is required and never taken from git's configuration: it is a person's decision, and a coding agent is told never to make it for them."
310
+ export async function declineContext(dir, opts, env) {
311
+ const L = await contextLib();
312
+ const root = storeRoot(dir, env);
313
+ const by = L.cleanLine(opts.by ?? '', 80);
314
+ if (!by)
315
+ throw new BravosError('who is deciding this? bravos context decline --by "<your name>" [--reason "<why>"]: going without context is a person\'s call, recorded under their name');
316
+ const gate = L.contextGate(root);
317
+ if (gate.open && gate.state === 'confirmed')
318
+ return ['Nothing to decline: the intent here is already confirmed by a named person (.guardlink/intent.md).'];
319
+ refuseIfIgnored(root, L, env);
320
+ const reason = L.cleanLine(opts.reason ?? '', 300);
321
+ const status = { schema: L.STATUS_SCHEMA, state: 'declined', by, at: today(opts.now ?? new Date()), ...(reason ? { reason } : {}) };
322
+ mkdirSync(join(root, L.CONTEXT_DIR), { recursive: true });
323
+ writeAtomic(join(root, L.STATUS_PATH), JSON.stringify(status, null, 2) + '\n');
324
+ return [
325
+ `Recorded: ${by} chose to threat-model this repository without design context (${L.STATUS_PATH}, ${status.at}).`,
326
+ 'Severities will not be calibrated to the product, and rules that only a design states will not be found. The bravos-context skill can still be run at any time.',
327
+ `Commit it so the team and the nightly see the same decision: git add ${L.STATUS_PATH}`,
328
+ ];
329
+ }
330
+ // ---------------------------------------------------------------------------------------------
331
+ // The pre-push check
332
+ // ---------------------------------------------------------------------------------------------
333
+ export const PRE_PUSH_MARKER = 'bravos-context-pre-push';
334
+ // @comment -- "The git pre-push hook bravos writes: a few lines of sh that hand git's list of pushed refs to the context check, from the repository's own copy of the hook scripts or, failing that, the bravos on PATH. With neither it does nothing, so a clone without bravos is never blocked."
335
+ export const PRE_PUSH_SCRIPT = `#!/bin/sh
336
+ # ${PRE_PUSH_MARKER} v1: checks the design documents under .bravos/context/ before they reach the remote.
337
+ # Written by bravos. Delete this file to stop it; git push --no-verify skips it once.
338
+ if [ -f .bravos/hooks/lib/context.mjs ] && command -v node >/dev/null 2>&1; then
339
+ exec node .bravos/hooks/lib/context.mjs pre-push
340
+ fi
341
+ if command -v bravos >/dev/null 2>&1; then
342
+ exec bravos hook context pre-push
343
+ fi
344
+ exit 0
345
+ `;
346
+ // @comment -- "Installs the pre-push check in this clone's git hooks folder (git rev-parse --git-path hooks, so worktrees and a configured hooks path are respected). It only ever writes a file that is absent or already bravos's own; where another pre-push hook exists it is left alone and the one line to add is printed. Returns what it did, as lines."
347
+ export function installPrePush(root, env) {
348
+ const rel = git(root, ['rev-parse', '--git-path', 'hooks'], env);
349
+ if (!rel)
350
+ return [];
351
+ const dir = isAbsolute(rel) ? rel : join(root, rel);
352
+ const file = join(dir, 'pre-push');
353
+ const line = 'node .bravos/hooks/lib/context.mjs pre-push || exit 1';
354
+ try {
355
+ if (existsSync(file)) {
356
+ const have = readFileSync(file, 'utf8');
357
+ if (have === PRE_PUSH_SCRIPT)
358
+ return [];
359
+ if (!have.includes(PRE_PUSH_MARKER))
360
+ return [`This clone already has a pre-push hook, so bravos left it alone. To check design documents before every push, add this line to it: ${line}`];
361
+ }
362
+ mkdirSync(dir, { recursive: true });
363
+ writeFileSync(file, PRE_PUSH_SCRIPT, { mode: 0o755 });
364
+ chmodSync(file, 0o755);
365
+ return ['A pre-push check now runs in this clone: a push that changes the design documents is stopped if one carries a secret or a local path (teammates get it from bravos sync).'];
366
+ }
367
+ catch (e) {
368
+ return [`The pre-push check could not be installed (${e.message.split('\n')[0]}); bravos context check does the same by hand.`];
369
+ }
370
+ }
371
+ // @comment -- "Removes the pre-push check on uninstall, only when the file is still exactly what bravos wrote."
372
+ export function removePrePush(root, env, dryRun = false) {
373
+ const rel = git(root, ['rev-parse', '--git-path', 'hooks'], env);
374
+ if (!rel)
375
+ return false;
376
+ const file = join(isAbsolute(rel) ? rel : join(root, rel), 'pre-push');
377
+ try {
378
+ if (readFileSync(file, 'utf8') !== PRE_PUSH_SCRIPT)
379
+ return false;
380
+ if (!dryRun)
381
+ rmSync(file);
382
+ return true;
383
+ }
384
+ catch {
385
+ return false;
386
+ }
387
+ }
package/dist/dashboard.js CHANGED
@@ -6,6 +6,7 @@ import * as graph from './codegraph.js';
6
6
  import { featureState, licenceLib } from './licence.js';
7
7
  import { templatesDir, version } from './paths.js';
8
8
  import { BravosError } from './types.js';
9
+ import { gatherRules } from './rules.js';
9
10
  export const DASHBOARD_DIR = '.bravos/dashboard';
10
11
  export const DASHBOARD_PATH = `${DASHBOARD_DIR}/index.html`;
11
12
  /** What the saved page was built from, for the session briefing to tell a current page from an old one. */
@@ -230,7 +231,7 @@ export function shareCodeMap(store) {
230
231
  return { codemap: shared, pages };
231
232
  }
232
233
  // @comment -- "Renders the one-file dashboard: the page template with its facts and GuardLink's page each embedded as JSON in a non-executing script tag, every '<' escaped so none can close its tag. When there are code graph answers, they and the vendored Code graph pages (script and stylesheet) are embedded the same way; the page assembles them into a second sandboxed frame. Both go in through one pass with a function replacer, so nothing in either is read as a placeholder or a replacement pattern."
233
- export function renderDashboard(data, threatModelHtml, store = null) {
234
+ export function renderDashboard(data, threatModelHtml, store = null, rules = null) {
234
235
  const template = readFileSync(join(templatesDir(), 'dashboard', 'dashboard.html'), 'utf8');
235
236
  // One pass over the template, so text inside either value that looks like a placeholder is never filled in turn.
236
237
  // The pages' script and stylesheet travel only with a page that has graph answers to draw.
@@ -241,8 +242,9 @@ export function renderDashboard(data, threatModelHtml, store = null) {
241
242
  CODEGRAPH: () => (store ? shareCodeMap(store) : null),
242
243
  PAGES_JS: () => asset('codegraph-pages.js'),
243
244
  PAGES_CSS: () => asset('codegraph-pages.css'),
245
+ RULES: () => rules,
244
246
  };
245
- return template.replace(/__BRAVOS_(DATA|THREAT_MODEL|CODEGRAPH|PAGES_JS|PAGES_CSS)__/g, (_m, which) => inert(fill[which]()));
247
+ return template.replace(/__BRAVOS_(DATA|THREAT_MODEL|CODEGRAPH|PAGES_JS|PAGES_CSS|RULES)__/g, (_m, which) => inert(fill[which]()));
246
248
  }
247
249
  // @comment -- "bravos dashboard: gathers the repository's facts (read-only git, this machine's plan label), builds GuardLink's page and, on the Team plan, the Code graph pages from the graph's answers, and writes one self-contained HTML file. By default that is .bravos/dashboard/index.html beside a .gitignore of '*', since the page can carry git identities and findings; with `out` nothing is written inside the repository. A page is written even when GuardLink has nothing to show, so the person always gets a file that says what to do next."
248
250
  export async function buildDashboard(root, env, opts = {}) {
@@ -253,6 +255,17 @@ export async function buildDashboard(root, env, opts = {}) {
253
255
  const base = opts.since ?? baseRef(root, env);
254
256
  const tm = buildThreatModel(root, env, { base, blame: opts.blame !== false });
255
257
  const cg = await buildCodeGraph(root, env, { names: opts.blame !== false, refresh: opts.graphBuild !== false, onProgress: opts.onProgress });
258
+ // The design rules: free on every plan, read from the intent, GuardLink's model and its test ledger. A failure
259
+ // here is a note on that view, never a failed page.
260
+ let rules = null;
261
+ let rulesPart;
262
+ try {
263
+ rules = await gatherRules(root, env, { names: opts.blame !== false });
264
+ rulesPart = { state: rules.state === 'none' ? 'missing' : 'present', note: rules.note };
265
+ }
266
+ catch (e) {
267
+ rulesPart = { state: 'failed', note: `The design rules could not be read (${e.message.split('\n')[0].slice(0, 200)}).` };
268
+ }
256
269
  let plan = null;
257
270
  try {
258
271
  const L = (await licenceLib());
@@ -271,8 +284,9 @@ export async function buildDashboard(root, env, opts = {}) {
271
284
  plan,
272
285
  threatModel: { state: tm.state, note: tm.note, blame: tm.blame, since: tm.since },
273
286
  codeGraph: { state: cg.state, note: cg.note },
287
+ rules: rulesPart,
274
288
  };
275
- const page = renderDashboard(data, tm.html, cg.store);
289
+ const page = renderDashboard(data, tm.html, cg.store, rules);
276
290
  let path;
277
291
  if (opts.out) {
278
292
  path = resolve(opts.out);
@@ -286,9 +300,9 @@ export async function buildDashboard(root, env, opts = {}) {
286
300
  writeFileSync(ignore, '*\n');
287
301
  path = join(root, DASHBOARD_PATH);
288
302
  // Beside the page: what it was built from, so the session briefing can say when it has fallen behind.
289
- const meta = { schema: 'bravos.dashboard-meta/v1', generatedAt: data.generatedAt, commit: git(root, env, ['rev-parse', 'HEAD']), branch: data.branch, threatModel: tm.state, codeGraph: cg.state };
303
+ const meta = { schema: 'bravos.dashboard-meta/v1', generatedAt: data.generatedAt, commit: git(root, env, ['rev-parse', 'HEAD']), branch: data.branch, threatModel: tm.state, codeGraph: cg.state, rules: rulesPart.state };
290
304
  writeFileSync(join(root, DASHBOARD_META), `${JSON.stringify(meta, null, 2)}\n`);
291
305
  }
292
306
  writeFileSync(path, page);
293
- return { path, threatModel: { state: tm.state, note: tm.note }, codeGraph: { state: cg.state, note: cg.note } };
307
+ return { path, threatModel: { state: tm.state, note: tm.note }, codeGraph: { state: cg.state, note: cg.note }, rules: rulesPart };
294
308
  }