@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.
- package/dist/artifacts.js +31 -1
- package/dist/cli.js +78 -5
- package/dist/codegraph.js +32 -4
- package/dist/context.js +351 -0
- package/dist/dashboard.js +35 -10
- package/dist/guide.js +3 -0
- package/dist/help.js +19 -0
- package/dist/report/data.js +2 -1
- package/dist/rules.js +218 -0
- package/dist/setup.js +33 -7
- package/dist/uninstall.js +6 -0
- package/dist/versions.js +1 -1
- package/dist/watch-frame.js +8 -1
- package/dist/watch.js +11 -2
- package/docs/GUIDE.md +18 -0
- package/docs/UPGRADING.md +30 -0
- package/hooks/lib/autopilot.mjs +29 -7
- package/hooks/lib/briefing.mjs +29 -5
- package/hooks/lib/context.mjs +522 -0
- package/hooks/lib/pre-pr.mjs +70 -0
- package/hooks/lib/setup.mjs +5 -2
- package/package.json +1 -1
- package/skills/bravos/SKILL.md +1 -1
- package/skills/bravos-annotate/SKILL.md +5 -3
- package/skills/bravos-annotate/scripts/lib/gate.mjs +45 -0
- package/skills/bravos-annotate/scripts/slice.mjs +10 -0
- package/skills/bravos-campaign/SKILL.md +1 -1
- package/skills/bravos-codegraph/SKILL.md +1 -1
- package/skills/bravos-context/SKILL.md +16 -10
- package/skills/bravos-context/intent.example.md +14 -1
- package/skills/bravos-recheck/SKILL.md +1 -1
- package/skills/bravos-ship/SKILL.md +2 -1
- package/skills/bravos-templatize/SKILL.md +1 -1
- package/templates/dashboard/dashboard.html +97 -0
- package/templates/workflows/bravos-nightly-claude.yml +36 -2
- package/templates/workflows/bravos-nightly-codex.yml +36 -2
- package/templates/workflows/bravos-nightly-copilot.yml +23 -0
- package/templates/workflows/bravos-pr-gate.yml +76 -0
package/dist/artifacts.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { createHash, createPublicKey, verify as cryptoVerify } from 'node:crypto';
|
|
3
3
|
import { chmodSync, closeSync, existsSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, symlinkSync, unlinkSync, writeSync } from 'node:fs';
|
|
4
4
|
import { arch, platform } from 'node:os';
|
|
5
|
-
import { dirname, join } from 'node:path';
|
|
5
|
+
import { basename, dirname, join } from 'node:path';
|
|
6
6
|
import { gunzipSync } from 'node:zlib';
|
|
7
7
|
import { refresh, userAgent } from './device.js';
|
|
8
8
|
import { licenceLib } from './licence.js';
|
|
@@ -276,6 +276,36 @@ export function staged(env, kind) {
|
|
|
276
276
|
}
|
|
277
277
|
return null;
|
|
278
278
|
}
|
|
279
|
+
// @comment -- "The version of a staged bundle: what its own BUNDLE.json says, else the version folder it sits in ($BRAVOS_HOME/<kind>/<version>/<target>), else null. Read-only; a bundle that names no version is never treated as old."
|
|
280
|
+
export function stagedVersion(root) {
|
|
281
|
+
const dotted = (v) => (typeof v === 'string' && /^\d+(\.\d+)+/.test(v) ? v : null);
|
|
282
|
+
try {
|
|
283
|
+
const said = dotted(JSON.parse(readFileSync(join(root, BUNDLE_FILE), 'utf8'))?.version);
|
|
284
|
+
if (said)
|
|
285
|
+
return said;
|
|
286
|
+
}
|
|
287
|
+
catch {
|
|
288
|
+
/* fall through to the folder name */
|
|
289
|
+
}
|
|
290
|
+
return dotted(basename(dirname(root)));
|
|
291
|
+
}
|
|
292
|
+
// @comment -- "Whether dotted version `have` is lower than `want`, comparing the numeric parts left to right; anything after the numbers (a pre-release tag) is ignored, and a version that does not parse is never older."
|
|
293
|
+
export function olderThan(have, want) {
|
|
294
|
+
const parts = (v) => {
|
|
295
|
+
const m = /^(\d+(?:\.\d+)*)/.exec(v);
|
|
296
|
+
return m ? m[1].split('.').map(Number) : null;
|
|
297
|
+
};
|
|
298
|
+
const a = parts(have);
|
|
299
|
+
const b = parts(want);
|
|
300
|
+
if (!a || !b)
|
|
301
|
+
return false;
|
|
302
|
+
for (let i = 0; i < Math.max(a.length, b.length); i++) {
|
|
303
|
+
const d = (a[i] ?? 0) - (b[i] ?? 0);
|
|
304
|
+
if (d !== 0)
|
|
305
|
+
return d < 0;
|
|
306
|
+
}
|
|
307
|
+
return false;
|
|
308
|
+
}
|
|
279
309
|
/** The environment a staged bundle declares in BUNDLE.json: `env` (relative paths made absolute) and `path_prepend`. */
|
|
280
310
|
export function bundleEnvironment(root, base) {
|
|
281
311
|
const env = { ...base };
|
package/dist/cli.js
CHANGED
|
@@ -12,6 +12,8 @@ import { writeOmpExtension } from './omp.js';
|
|
|
12
12
|
import { homeOf, installGlobal } from './global.js';
|
|
13
13
|
import { uninstall } from './uninstall.js';
|
|
14
14
|
import { checkKind, newToken, 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);
|
|
@@ -560,6 +575,7 @@ export function buildProgram(io, result) {
|
|
|
560
575
|
}
|
|
561
576
|
const extra = args.filter((a) => a !== '--json');
|
|
562
577
|
// The same document the Python CLI printed: {result} on an answer, {error, message, remedy} on a refusal, exit 2 when the graph is not built.
|
|
578
|
+
// A graph another session or a build holds is {error: graph_busy} with exit 1: only "not built" is exit 2, which is what callers rebuild on.
|
|
563
579
|
const a = await askGraph(root, io.env, question, extra);
|
|
564
580
|
if (!a)
|
|
565
581
|
throw new BravosError('codegraph-mcp is not installed: bravos setup --codegraph fetches it');
|
|
@@ -580,10 +596,10 @@ export function buildProgram(io, result) {
|
|
|
580
596
|
.allowUnknownOption()
|
|
581
597
|
.helpOption(false)
|
|
582
598
|
.action((name, args) => guarded((lines) => {
|
|
583
|
-
const known = ['session-start', 'pre-pr', 'autopilot', 'replay'];
|
|
599
|
+
const known = ['session-start', 'pre-pr', 'autopilot', 'replay', 'context'];
|
|
584
600
|
if (!known.includes(name))
|
|
585
601
|
throw new BravosError(`unknown hook '${name}'; use ${known.join(', ')}`);
|
|
586
|
-
const script = name === 'replay' ?
|
|
602
|
+
const script = name === 'replay' || name === 'context' ? `lib/${name}.mjs` : `${name}.mjs`;
|
|
587
603
|
const r = spawnSync(process.execPath, [pathJoin(hooksDir(), script), ...args], { env: io.env, encoding: 'utf8', stdio: ['inherit', 'pipe', 'pipe'], maxBuffer: 16 * 1024 * 1024 });
|
|
588
604
|
if (r.stdout)
|
|
589
605
|
lines.push(r.stdout.replace(/\n$/, ''));
|
|
@@ -687,6 +703,63 @@ export function buildProgram(io, result) {
|
|
|
687
703
|
if (r.unregistered.some((u) => u.includes('.codex')))
|
|
688
704
|
lines.push('Codex keeps its own trust record for removed hooks; nothing to do there.');
|
|
689
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
|
+
}));
|
|
690
763
|
program
|
|
691
764
|
.command('review <kind> [dir]')
|
|
692
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.")
|
|
@@ -786,7 +859,7 @@ export function buildProgram(io, result) {
|
|
|
786
859
|
}));
|
|
787
860
|
program
|
|
788
861
|
.command('dashboard [dir]')
|
|
789
|
-
.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.")
|
|
790
863
|
.option('--out <file>', 'write the page here instead; nothing is then written inside the repository')
|
|
791
864
|
.option('--since <ref>', "compare against this branch, tag or commit instead of the repository's default branch")
|
|
792
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')
|
|
@@ -801,10 +874,10 @@ export function buildProgram(io, result) {
|
|
|
801
874
|
// Opening is a convenience: the path is always printed, and a session with no display just reads it.
|
|
802
875
|
const opened = opts.open !== false && !opts.json && openInBrowser(r.path, io.env);
|
|
803
876
|
if (opts.json) {
|
|
804
|
-
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));
|
|
805
878
|
return;
|
|
806
879
|
}
|
|
807
|
-
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}`);
|
|
808
881
|
if (!opened && opts.open !== false)
|
|
809
882
|
lines.push(' No browser could be opened here; open the file above.');
|
|
810
883
|
}));
|
package/dist/codegraph.js
CHANGED
|
@@ -57,6 +57,18 @@ export class GraphUnavailable extends BravosError {
|
|
|
57
57
|
super(message);
|
|
58
58
|
}
|
|
59
59
|
}
|
|
60
|
+
// @comment -- "The code graph is there and another process holds its lock: a second session reading the same snapshot, or a build in progress. codegraph-mcp 0.1.1 waits for the lock (20 s by default) and then answers this, with data.reason 'graph_busy'. It is never 'no graph': the remedy is to ask again, not to rebuild."
|
|
61
|
+
export class GraphBusy extends BravosError {
|
|
62
|
+
constructor(message) {
|
|
63
|
+
super(message);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/** What to tell a person, or an agent, when the graph answered busy. */
|
|
67
|
+
export const GRAPH_BUSY_REMEDY = 'another session or a build is using the code graph; ask again in a moment (do not rebuild it)';
|
|
68
|
+
// The server's own sentence, for an answer that reached us as text only (a stored error string).
|
|
69
|
+
const BUSY_TEXT = /code graph for project \S+ is busy/i;
|
|
70
|
+
/** Whether an error, or an error's text, is the graph's busy answer. */
|
|
71
|
+
export const isGraphBusy = (e) => e instanceof GraphBusy || BUSY_TEXT.test(typeof e === 'string' ? e : (e?.message ?? ''));
|
|
60
72
|
// @comment -- "A minimal MCP stdio client: newline-delimited JSON-RPC 2.0 to a child codegraph-mcp --project-path ROOT. One session per question; the server is killed on close or timeout. stderr is kept for the error message; stdout is parsed line by line, with anything that is not a JSON-RPC message ignored."
|
|
61
73
|
export class GraphSession {
|
|
62
74
|
child;
|
|
@@ -103,8 +115,11 @@ export class GraphSession {
|
|
|
103
115
|
if (!p)
|
|
104
116
|
continue;
|
|
105
117
|
this.pending.delete(msg.id);
|
|
106
|
-
if (msg.error)
|
|
107
|
-
|
|
118
|
+
if (msg.error) {
|
|
119
|
+
const said = msg.error.message ?? 'the graph answered an error';
|
|
120
|
+
// The structured reason first; the sentence is the fallback for a server that sends only text.
|
|
121
|
+
p.reject(msg.error.data?.reason === 'graph_busy' || BUSY_TEXT.test(said) ? new GraphBusy(said) : new BravosError(said));
|
|
122
|
+
}
|
|
108
123
|
else
|
|
109
124
|
p.resolve(msg.result);
|
|
110
125
|
}
|
|
@@ -222,7 +237,7 @@ export async function ask(root, env, question, argv, timeoutMs = 60000) {
|
|
|
222
237
|
};
|
|
223
238
|
return withGraphRetry(once, (o) => !!o.error && NO_GRAPH.test(o.error.message ?? ''));
|
|
224
239
|
}
|
|
225
|
-
// @comment -- "Several questions in one session: the server loads the graph once instead of once per question. A tool the binary does not offer, or one that refuses or times out, is recorded as an error for that question alone; the others are still asked. A session whose first answer is 'no graph' is run again (withGraphRetry). Throws only when no session can be opened (codegraph-mcp missing or not starting)."
|
|
240
|
+
// @comment -- "Several questions in one session: the server loads the graph once instead of once per question. A tool the binary does not offer, or one that refuses or times out, is recorded as an error for that question alone; the others are still asked. The exception is a busy graph: the server has already waited its whole lock wait for that answer, so the remaining questions are marked busy without being asked (asking each would wait that long again). A session whose first answer is 'no graph' is run again (withGraphRetry). Throws only when no session can be opened (codegraph-mcp missing or not starting)."
|
|
226
241
|
export async function askMany(root, env, calls, timeoutMs = 60000) {
|
|
227
242
|
const once = async () => {
|
|
228
243
|
const s = open(root, env);
|
|
@@ -230,16 +245,26 @@ export async function askMany(root, env, calls, timeoutMs = 60000) {
|
|
|
230
245
|
await s.initialize(Math.min(timeoutMs, 30000));
|
|
231
246
|
const tools = (await s.tools(Math.min(timeoutMs, 30000))).map((t) => t.name);
|
|
232
247
|
const answers = {};
|
|
248
|
+
let busy = null;
|
|
233
249
|
for (const c of calls) {
|
|
234
250
|
if (!tools.includes(c.tool)) {
|
|
235
251
|
answers[c.tool] = { error: 'this code graph does not answer that question' };
|
|
236
252
|
continue;
|
|
237
253
|
}
|
|
254
|
+
if (busy) {
|
|
255
|
+
answers[c.tool] = { error: busy, busy: true };
|
|
256
|
+
continue;
|
|
257
|
+
}
|
|
238
258
|
try {
|
|
239
259
|
answers[c.tool] = { result: await s.call(c.tool, c.args ?? {}, timeoutMs) };
|
|
240
260
|
}
|
|
241
261
|
catch (e) {
|
|
242
|
-
|
|
262
|
+
if (isGraphBusy(e)) {
|
|
263
|
+
busy = e.message;
|
|
264
|
+
answers[c.tool] = { error: busy, busy: true };
|
|
265
|
+
}
|
|
266
|
+
else
|
|
267
|
+
answers[c.tool] = { error: e.message };
|
|
243
268
|
}
|
|
244
269
|
}
|
|
245
270
|
return { tools, answers };
|
|
@@ -323,6 +348,9 @@ export async function probe(root, env, timeoutMs = 3000) {
|
|
|
323
348
|
}
|
|
324
349
|
catch (e) {
|
|
325
350
|
const m = e.message ?? '';
|
|
351
|
+
// Busy means a graph is there (or being built): the same reading as one that is still loading.
|
|
352
|
+
if (isGraphBusy(e))
|
|
353
|
+
return 'cli';
|
|
326
354
|
if (/no graph|codegraph_unavailable|not built|no CodeGraph|nothing is there/i.test(m))
|
|
327
355
|
return 'not-built';
|
|
328
356
|
if (e instanceof GraphUnavailable && /within \d+s/.test(m))
|
package/dist/context.js
ADDED
|
@@ -0,0 +1,351 @@
|
|
|
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
|
+
function writeAtomic(abs, data) {
|
|
84
|
+
const tmp = `${abs}.writing-${process.pid}`;
|
|
85
|
+
writeFileSync(tmp, data, { mode: 0o644 });
|
|
86
|
+
renameSync(tmp, abs);
|
|
87
|
+
}
|
|
88
|
+
// @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."
|
|
89
|
+
function refuseIfIgnored(root, L, env) {
|
|
90
|
+
try {
|
|
91
|
+
execFileSync('git', ['check-ignore', '-q', L.INDEX_PATH], { cwd: root, env, stdio: 'ignore', timeout: 10000 });
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
return; // exit 1: not ignored. 128 or no git: not a repository, nothing to defeat.
|
|
95
|
+
}
|
|
96
|
+
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`);
|
|
97
|
+
}
|
|
98
|
+
function byline(opts, root, env, L) {
|
|
99
|
+
const by = L.cleanLine(opts.by ?? git(root, ['config', 'user.name'], env) ?? '', 80);
|
|
100
|
+
if (!by)
|
|
101
|
+
throw new BravosError('who is adding this? give --by "<your name>" (git has no user.name set here)');
|
|
102
|
+
return by;
|
|
103
|
+
}
|
|
104
|
+
function originFor(input, opts, L, cwd, now) {
|
|
105
|
+
if (opts.url) {
|
|
106
|
+
const u = L.checkUrl(opts.url, { keepQuery: opts.keepQuery });
|
|
107
|
+
if (!u.url)
|
|
108
|
+
throw new BravosError(`the link was not kept: ${u.problems.join('; ')}`);
|
|
109
|
+
return { type: 'link', url: u.url, fetched: today(now), ...(opts.keepQuery ? { query: 'kept' } : {}) };
|
|
110
|
+
}
|
|
111
|
+
if (opts.original) {
|
|
112
|
+
const abs = isAbsolute(opts.original) ? opts.original : resolve(cwd, opts.original);
|
|
113
|
+
let st;
|
|
114
|
+
try {
|
|
115
|
+
st = lstatSync(abs);
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
throw new BravosError(`--original: no file at ${opts.original}`);
|
|
119
|
+
}
|
|
120
|
+
if (!st.isFile())
|
|
121
|
+
throw new BravosError('--original must be the document file itself, not a link or a folder');
|
|
122
|
+
const name = L.cleanLine(basename(abs), 200).replace(/[\\/]/g, '-');
|
|
123
|
+
// Hashed, never copied: the original may be a binary of any size, and only its identity is recorded.
|
|
124
|
+
return { type: 'file', name, sha256: createHash('sha256').update(readFileSync(abs)).digest('hex') };
|
|
125
|
+
}
|
|
126
|
+
if (input.name)
|
|
127
|
+
return { type: 'file', name: L.cleanLine(input.name, 200).replace(/[\\/]/g, '-'), sha256: L.sha256(input.bytes) };
|
|
128
|
+
return { type: 'pasted' };
|
|
129
|
+
}
|
|
130
|
+
const firstHeading = (text) => (/^#{1,3}\s+(.+)$/m.exec(text)?.[1] ?? '').trim();
|
|
131
|
+
const size = (n) => (n < 1024 ? `${n} B` : n < 1024 * 1024 ? `${(n / 1024).toFixed(1)} kB` : `${(n / 1048576).toFixed(1)} MB`);
|
|
132
|
+
// @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."
|
|
133
|
+
export async function addSource(dir, input, opts, env, cwd = process.cwd()) {
|
|
134
|
+
const L = await contextLib();
|
|
135
|
+
const root = storeRoot(dir, env);
|
|
136
|
+
refuseIfIgnored(root, L, env);
|
|
137
|
+
const sources = loadIndex(root, L);
|
|
138
|
+
if (sources.length >= L.MAX_SOURCES)
|
|
139
|
+
throw new BravosError(`this repository already has ${L.MAX_SOURCES} sources: remove ones nobody cites before adding more`);
|
|
140
|
+
const read = readInput(input, L, cwd);
|
|
141
|
+
const text = vet(read.bytes, L, whoAmI(env), read.name ?? 'the document');
|
|
142
|
+
const kind = opts.kind ?? 'other';
|
|
143
|
+
if (!L.KINDS.includes(kind))
|
|
144
|
+
throw new BravosError(`--kind must be one of ${L.KINDS.join(', ')}`);
|
|
145
|
+
const title = L.cleanLine(opts.title ?? firstHeading(text), 120) || L.cleanLine((read.name ?? '').replace(/\.[A-Za-z0-9]{1,8}$/, ''), 120);
|
|
146
|
+
if (!title)
|
|
147
|
+
throw new BravosError('give the document a title: --title "<what it is>"');
|
|
148
|
+
const now = opts.now ?? new Date();
|
|
149
|
+
const by = byline(opts, root, env, L);
|
|
150
|
+
const origin = originFor(read, opts, L, cwd, now);
|
|
151
|
+
const id = L.nextId(sources);
|
|
152
|
+
const name = L.sourceName(id, title);
|
|
153
|
+
const stored = Buffer.from(text, 'utf8');
|
|
154
|
+
const entry = { id, title, kind, sha256: L.sha256(stored), bytes: stored.length, origin, added: { by, at: today(now) } };
|
|
155
|
+
const first = sources.length === 0 && !existsSync(join(root, L.INDEX_PATH));
|
|
156
|
+
mkdirSync(join(root, L.SOURCES_DIR), { recursive: true });
|
|
157
|
+
writeAtomic(join(root, L.SOURCES_DIR, name), stored);
|
|
158
|
+
writeAtomic(join(root, L.INDEX_PATH), L.renderIndex([...sources, entry]));
|
|
159
|
+
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`];
|
|
160
|
+
if (origin.type === 'link')
|
|
161
|
+
lines.push(` link kept in full: ${origin.url}`);
|
|
162
|
+
const hidden = L.hiddenText(text);
|
|
163
|
+
if (hidden.invisible || hidden.comments)
|
|
164
|
+
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`);
|
|
165
|
+
if (first) {
|
|
166
|
+
lines.push(`Everyone with access to this repository can read what is added under ${L.CONTEXT_DIR}/, and links are kept in full.`);
|
|
167
|
+
lines.push(...installPrePush(root, env));
|
|
168
|
+
}
|
|
169
|
+
lines.push(`Commit it with the team's other context: git add ${L.CONTEXT_DIR}`);
|
|
170
|
+
return lines;
|
|
171
|
+
}
|
|
172
|
+
// @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."
|
|
173
|
+
export async function updateSource(dir, id, input, opts, env, cwd = process.cwd()) {
|
|
174
|
+
const L = await contextLib();
|
|
175
|
+
const root = storeRoot(dir, env);
|
|
176
|
+
if (!L.ID.test(id))
|
|
177
|
+
throw new BravosError(`'${id}' is not a source id: they look like SRC-3 (bravos context list shows them)`);
|
|
178
|
+
const sources = loadIndex(root, L);
|
|
179
|
+
const entry = sources.find((s) => s.id === id);
|
|
180
|
+
if (!entry)
|
|
181
|
+
throw new BravosError(`there is no ${id} in ${L.INDEX_PATH}`);
|
|
182
|
+
let names = [];
|
|
183
|
+
try {
|
|
184
|
+
names = readdirSync(join(root, L.SOURCES_DIR));
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
/* no folder: handled below */
|
|
188
|
+
}
|
|
189
|
+
const name = L.fileFor(id, names);
|
|
190
|
+
const who = whoAmI(env);
|
|
191
|
+
let text;
|
|
192
|
+
let read = null;
|
|
193
|
+
if (input) {
|
|
194
|
+
read = readInput(input, L, cwd);
|
|
195
|
+
text = vet(read.bytes, L, who, read.name ?? 'the document');
|
|
196
|
+
}
|
|
197
|
+
else {
|
|
198
|
+
if (!name)
|
|
199
|
+
throw new BravosError(`${id} has no single file in ${L.SOURCES_DIR}/: restore it, or give the new text (bravos context update ${id} <file>)`);
|
|
200
|
+
const abs = join(root, L.SOURCES_DIR, name);
|
|
201
|
+
if (!lstatSync(abs).isFile())
|
|
202
|
+
throw new BravosError(`${L.SOURCES_DIR}/${name} is not a regular file`);
|
|
203
|
+
text = vet(readFileSync(abs), L, who, `${L.SOURCES_DIR}/${name}`, 'was not recorded');
|
|
204
|
+
}
|
|
205
|
+
const now = opts.now ?? new Date();
|
|
206
|
+
const stored = Buffer.from(text, 'utf8');
|
|
207
|
+
const before = entry.sha256;
|
|
208
|
+
entry.sha256 = L.sha256(stored);
|
|
209
|
+
entry.bytes = stored.length;
|
|
210
|
+
if (opts.title)
|
|
211
|
+
entry.title = L.cleanLine(opts.title, 120) || entry.title;
|
|
212
|
+
if (opts.kind) {
|
|
213
|
+
if (!L.KINDS.includes(opts.kind))
|
|
214
|
+
throw new BravosError(`--kind must be one of ${L.KINDS.join(', ')}`);
|
|
215
|
+
entry.kind = opts.kind;
|
|
216
|
+
}
|
|
217
|
+
if (read && (opts.url || opts.original || read.name))
|
|
218
|
+
entry.origin = originFor(read, opts, L, cwd, now);
|
|
219
|
+
entry.updated = { by: byline(opts, root, env, L), at: today(now) };
|
|
220
|
+
const target = name ?? L.sourceName(id, entry.title);
|
|
221
|
+
mkdirSync(join(root, L.SOURCES_DIR), { recursive: true });
|
|
222
|
+
writeAtomic(join(root, L.SOURCES_DIR, target), stored);
|
|
223
|
+
writeAtomic(join(root, L.INDEX_PATH), L.renderIndex(sources));
|
|
224
|
+
const changed = before !== entry.sha256;
|
|
225
|
+
return [
|
|
226
|
+
changed ? `${id} updated: ${entry.title} (${size(stored.length)})` : `${id} recorded: the text is unchanged`,
|
|
227
|
+
...(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`] : []),
|
|
228
|
+
];
|
|
229
|
+
}
|
|
230
|
+
// @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."
|
|
231
|
+
export async function listSources(dir, env, json = false) {
|
|
232
|
+
const L = await contextLib();
|
|
233
|
+
const root = storeRoot(dir, env);
|
|
234
|
+
const abs = join(root, L.INDEX_PATH);
|
|
235
|
+
if (!existsSync(abs))
|
|
236
|
+
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'];
|
|
237
|
+
const sources = L.parseIndex(readFileSync(abs, 'utf8')).sources;
|
|
238
|
+
const check = L.checkContext(root, { who: whoAmI(env) });
|
|
239
|
+
const state = (id) => check.sources.find((s) => s.id === id)?.state ?? 'ok';
|
|
240
|
+
const file = (id) => check.sources.find((s) => s.id === id)?.file ?? null;
|
|
241
|
+
if (json)
|
|
242
|
+
return [JSON.stringify({ schema: 'bravos.context-list/v1', sources: sources.map((s) => ({ ...s, file: file(s.id), state: state(s.id) })) }, null, 2)];
|
|
243
|
+
const lines = sources.map((s) => {
|
|
244
|
+
const from = s.origin.type === 'link' ? ` · ${hostOf(s.origin.url)}` : '';
|
|
245
|
+
const st = state(s.id) === 'ok' ? '' : ` [${state(s.id)}]`;
|
|
246
|
+
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}`;
|
|
247
|
+
});
|
|
248
|
+
if (!check.ok)
|
|
249
|
+
lines.push(`${check.problems.length} problem${check.problems.length === 1 ? '' : 's'}: bravos context check`);
|
|
250
|
+
return lines;
|
|
251
|
+
}
|
|
252
|
+
const hostOf = (url) => {
|
|
253
|
+
try {
|
|
254
|
+
return new URL(url ?? '').host;
|
|
255
|
+
}
|
|
256
|
+
catch {
|
|
257
|
+
return 'link';
|
|
258
|
+
}
|
|
259
|
+
};
|
|
260
|
+
// @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."
|
|
261
|
+
export async function checkSources(dir, env) {
|
|
262
|
+
const L = await contextLib();
|
|
263
|
+
const result = L.checkContext(storeRoot(dir, env), { who: whoAmI(env) });
|
|
264
|
+
return { result, lines: L.formatCheck(result) };
|
|
265
|
+
}
|
|
266
|
+
// ---------------------------------------------------------------------------------------------
|
|
267
|
+
// Context before threat-modelling
|
|
268
|
+
// ---------------------------------------------------------------------------------------------
|
|
269
|
+
// @comment -- "Whether threat-modelling may start in this repository (hooks/lib/context.mjs contextGate), for the CLI and the tests."
|
|
270
|
+
export async function gateFor(dir, env) {
|
|
271
|
+
return (await contextLib()).contextGate(storeRoot(dir, env));
|
|
272
|
+
}
|
|
273
|
+
// @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."
|
|
274
|
+
export async function declineContext(dir, opts, env) {
|
|
275
|
+
const L = await contextLib();
|
|
276
|
+
const root = storeRoot(dir, env);
|
|
277
|
+
const by = L.cleanLine(opts.by ?? '', 80);
|
|
278
|
+
if (!by)
|
|
279
|
+
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');
|
|
280
|
+
const gate = L.contextGate(root);
|
|
281
|
+
if (gate.open && gate.state === 'confirmed')
|
|
282
|
+
return ['Nothing to decline: the intent here is already confirmed by a named person (.guardlink/intent.md).'];
|
|
283
|
+
refuseIfIgnored(root, L, env);
|
|
284
|
+
const reason = L.cleanLine(opts.reason ?? '', 300);
|
|
285
|
+
const status = { schema: L.STATUS_SCHEMA, state: 'declined', by, at: today(opts.now ?? new Date()), ...(reason ? { reason } : {}) };
|
|
286
|
+
mkdirSync(join(root, L.CONTEXT_DIR), { recursive: true });
|
|
287
|
+
writeAtomic(join(root, L.STATUS_PATH), JSON.stringify(status, null, 2) + '\n');
|
|
288
|
+
return [
|
|
289
|
+
`Recorded: ${by} chose to threat-model this repository without design context (${L.STATUS_PATH}, ${status.at}).`,
|
|
290
|
+
'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.',
|
|
291
|
+
`Commit it so the team and the nightly see the same decision: git add ${L.STATUS_PATH}`,
|
|
292
|
+
];
|
|
293
|
+
}
|
|
294
|
+
// ---------------------------------------------------------------------------------------------
|
|
295
|
+
// The pre-push check
|
|
296
|
+
// ---------------------------------------------------------------------------------------------
|
|
297
|
+
export const PRE_PUSH_MARKER = 'bravos-context-pre-push';
|
|
298
|
+
// @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."
|
|
299
|
+
export const PRE_PUSH_SCRIPT = `#!/bin/sh
|
|
300
|
+
# ${PRE_PUSH_MARKER} v1: checks the design documents under .bravos/context/ before they reach the remote.
|
|
301
|
+
# Written by bravos. Delete this file to stop it; git push --no-verify skips it once.
|
|
302
|
+
if [ -f .bravos/hooks/lib/context.mjs ] && command -v node >/dev/null 2>&1; then
|
|
303
|
+
exec node .bravos/hooks/lib/context.mjs pre-push
|
|
304
|
+
fi
|
|
305
|
+
if command -v bravos >/dev/null 2>&1; then
|
|
306
|
+
exec bravos hook context pre-push
|
|
307
|
+
fi
|
|
308
|
+
exit 0
|
|
309
|
+
`;
|
|
310
|
+
// @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."
|
|
311
|
+
export function installPrePush(root, env) {
|
|
312
|
+
const rel = git(root, ['rev-parse', '--git-path', 'hooks'], env);
|
|
313
|
+
if (!rel)
|
|
314
|
+
return [];
|
|
315
|
+
const dir = isAbsolute(rel) ? rel : join(root, rel);
|
|
316
|
+
const file = join(dir, 'pre-push');
|
|
317
|
+
const line = 'node .bravos/hooks/lib/context.mjs pre-push || exit 1';
|
|
318
|
+
try {
|
|
319
|
+
if (existsSync(file)) {
|
|
320
|
+
const have = readFileSync(file, 'utf8');
|
|
321
|
+
if (have === PRE_PUSH_SCRIPT)
|
|
322
|
+
return [];
|
|
323
|
+
if (!have.includes(PRE_PUSH_MARKER))
|
|
324
|
+
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}`];
|
|
325
|
+
}
|
|
326
|
+
mkdirSync(dir, { recursive: true });
|
|
327
|
+
writeFileSync(file, PRE_PUSH_SCRIPT, { mode: 0o755 });
|
|
328
|
+
chmodSync(file, 0o755);
|
|
329
|
+
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).'];
|
|
330
|
+
}
|
|
331
|
+
catch (e) {
|
|
332
|
+
return [`The pre-push check could not be installed (${e.message.split('\n')[0]}); bravos context check does the same by hand.`];
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
// @comment -- "Removes the pre-push check on uninstall, only when the file is still exactly what bravos wrote."
|
|
336
|
+
export function removePrePush(root, env, dryRun = false) {
|
|
337
|
+
const rel = git(root, ['rev-parse', '--git-path', 'hooks'], env);
|
|
338
|
+
if (!rel)
|
|
339
|
+
return false;
|
|
340
|
+
const file = join(isAbsolute(rel) ? rel : join(root, rel), 'pre-push');
|
|
341
|
+
try {
|
|
342
|
+
if (readFileSync(file, 'utf8') !== PRE_PUSH_SCRIPT)
|
|
343
|
+
return false;
|
|
344
|
+
if (!dryRun)
|
|
345
|
+
rmSync(file);
|
|
346
|
+
return true;
|
|
347
|
+
}
|
|
348
|
+
catch {
|
|
349
|
+
return false;
|
|
350
|
+
}
|
|
351
|
+
}
|