@bugb-technologies/bravos 1.9.3 → 1.12.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/cli.js +10 -10
- package/dist/context.js +1 -1
- package/dist/doctor.js +46 -3
- package/dist/guide.js +5 -2
- package/dist/help.js +32 -5
- package/dist/hooks.js +10 -1
- package/dist/plugin.js +4 -2
- package/dist/prefs.js +25 -5
- package/dist/start/index.js +3 -3
- package/dist/uninstall.js +1 -1
- package/docs/GUIDE.md +21 -3
- package/docs/UPGRADING.md +56 -1
- package/hooks/coach.mjs +89 -0
- package/hooks/lib/autopilot.mjs +8 -13
- package/hooks/lib/briefing.mjs +43 -11
- package/hooks/lib/coach.mjs +161 -0
- package/hooks/lib/context.mjs +6 -5
- package/hooks/lib/pre-pr.mjs +23 -2
- package/hooks/lib/prefs.mjs +28 -12
- package/hooks/lib/setup.mjs +3 -3
- package/hooks/lib/update-check.mjs +138 -0
- package/hooks/session-start.mjs +9 -0
- package/package.json +1 -1
- package/skills/bravos/SKILL.md +6 -5
- package/skills/bravos-annotate/SKILL.md +7 -5
- package/skills/bravos-annotate/scripts/lib/gate.mjs +6 -5
- package/skills/bravos-annotate/scripts/slice.mjs +4 -6
- package/skills/bravos-campaign/SKILL.md +2 -2
- package/skills/bravos-context/SKILL.md +8 -7
- package/skills/bravos-prove/SKILL.md +2 -0
- package/skills/bravos-recheck/SKILL.md +2 -1
- package/templates/review/review.html +5 -23
- package/templates/workflows/bravos-nightly-claude.yml +11 -10
- package/templates/workflows/bravos-nightly-codex.yml +11 -10
- package/templates/workflows/bravos-nightly-copilot.yml +6 -7
- package/templates/workflows/bravos-pr-gate.yml +9 -3
package/hooks/coach.mjs
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
// @comment -- "bravos coach UserPromptSubmit hook entry (Claude Code and Codex): reads the prompt payload with a bounded wait, decides what to add for the agent (hooks/lib/coach.mjs) and prints it as additionalContext, logging each reminder for bravos watch. Never runs guardlink or the network. Silent when BRAVOS_COACH=off, when the person switched the coach off (bravos prefs set coach off), or when it is the plugin's copy in a repository that registers its own. Always exits 0; a failure adds nothing."
|
|
2
|
+
import { realpathSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { spawnSync } from 'node:child_process';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
import { coachTurn, newestModelChange, readCoach, writeCoach } from './lib/coach.mjs';
|
|
8
|
+
import { gitCommonDir, readPrefs } from './lib/prefs.mjs';
|
|
9
|
+
import { logWatchEvent } from './lib/snapshot.mjs';
|
|
10
|
+
import { cliVersion, readUpdate, repoVersion } from './lib/update-check.mjs';
|
|
11
|
+
|
|
12
|
+
async function readPayload() {
|
|
13
|
+
if (process.stdin.isTTY) return {};
|
|
14
|
+
const read = (async () => {
|
|
15
|
+
const chunks = [];
|
|
16
|
+
for await (const c of process.stdin) chunks.push(c);
|
|
17
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
18
|
+
})().catch(() => '');
|
|
19
|
+
const raw = await Promise.race([read, new Promise((r) => setTimeout(() => r(''), 1000).unref())]);
|
|
20
|
+
try {
|
|
21
|
+
const p = JSON.parse(raw);
|
|
22
|
+
return p && typeof p === 'object' ? p : {};
|
|
23
|
+
} catch {
|
|
24
|
+
return {};
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const git = (cwd, args) => {
|
|
29
|
+
const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 3000, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
30
|
+
return r.status === 0 ? r.stdout.trim() : '';
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
// The plugin's copy stays quiet where the repository registers its own coach, so the agent never hears it twice.
|
|
34
|
+
function deferToRepo(root) {
|
|
35
|
+
try {
|
|
36
|
+
if (realpathSync(fileURLToPath(import.meta.url)) === realpathSync(join(root, '.bravos', 'hooks', 'coach.mjs'))) return false;
|
|
37
|
+
} catch {
|
|
38
|
+
/* no repository copy */
|
|
39
|
+
}
|
|
40
|
+
for (const f of ['.claude/settings.json', '.codex/hooks.json']) {
|
|
41
|
+
try {
|
|
42
|
+
if (readFileSync(join(root, f), 'utf8').includes('.bravos/hooks/coach.mjs')) return true;
|
|
43
|
+
} catch {
|
|
44
|
+
/* not registered there */
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function readDashboard(root) {
|
|
51
|
+
try {
|
|
52
|
+
const m = JSON.parse(readFileSync(join(root, '.bravos', 'dashboard', 'meta.json'), 'utf8'));
|
|
53
|
+
const at = Date.parse(m?.generatedAt);
|
|
54
|
+
return Number.isFinite(at) ? { generatedAt: at, commit: typeof m.commit === 'string' && /^[0-9a-f]{7,40}$/.test(m.commit) ? m.commit : null } : null;
|
|
55
|
+
} catch {
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async function main() {
|
|
61
|
+
let out = {};
|
|
62
|
+
try {
|
|
63
|
+
if (process.env.BRAVOS_COACH === 'off') throw new Error('off');
|
|
64
|
+
const payload = await readPayload();
|
|
65
|
+
const cwd = typeof payload.cwd === 'string' ? payload.cwd : process.env.CLAUDE_PROJECT_DIR || process.cwd();
|
|
66
|
+
const root = git(cwd, ['rev-parse', '--show-toplevel']) || cwd;
|
|
67
|
+
if (deferToRepo(root)) throw new Error('repo copy');
|
|
68
|
+
const commonDir = gitCommonDir(root);
|
|
69
|
+
if (readPrefs(commonDir).coach?.value === 'off') throw new Error('off');
|
|
70
|
+
const harness = process.argv.includes('--harness') ? process.argv[process.argv.indexOf('--harness') + 1] : process.env.CLAUDE_PROJECT_DIR ? 'claude' : 'other';
|
|
71
|
+
const record = readCoach(commonDir, payload.session_id) ?? { facts: { coverage: null, queued: 0, top: [], target: false, licensed: null, harness: harness === 'claude' ? 'claude' : 'other' }, raised: [], prompts: 0, opened: false };
|
|
72
|
+
const dashboard = readDashboard(root);
|
|
73
|
+
// File reads only: the last daily update check, the installed CLI's version and the repository's.
|
|
74
|
+
const versions = { cli: cliVersion(process.env), repo: repoVersion(root), latest: readUpdate(process.env.HOME || homedir())?.latest ?? null };
|
|
75
|
+
const r = coachTurn({ record, prompt: payload.prompt, dashboard, modelChangedAt: dashboard ? newestModelChange(root) : 0, head: dashboard?.commit ? git(root, ['rev-parse', 'HEAD']) : null, versions });
|
|
76
|
+
const { facts, ...rest } = r.record;
|
|
77
|
+
writeCoach(commonDir, payload.session_id, { facts, ...rest });
|
|
78
|
+
if (r.text) {
|
|
79
|
+
out = { hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: r.text } };
|
|
80
|
+
logWatchEvent(root, { summary: `coach: ${r.topics.join(', ')}`, keys: r.topics.map((t) => `bravos-coach:${t}`) });
|
|
81
|
+
}
|
|
82
|
+
} catch {
|
|
83
|
+
out = {};
|
|
84
|
+
}
|
|
85
|
+
process.stdout.write(JSON.stringify(out) + '\n');
|
|
86
|
+
process.exit(0);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
main();
|
package/hooks/lib/autopilot.mjs
CHANGED
|
@@ -181,20 +181,15 @@ export async function runAutopilot({ root, env = process.env, payload = {}, run
|
|
|
181
181
|
}
|
|
182
182
|
const paths = rows => arr(rows).map(w => typeof w === 'string' ? w : w?.file ?? w?.path)
|
|
183
183
|
.filter(path => changedSource(path) && !isGenerated(path) && !configFiles.has(path));
|
|
184
|
-
//
|
|
185
|
-
// forward for annotation: one note says why and what to do, in place of a note per file. Notes about claims that
|
|
186
|
-
// already exist (stale, to retest, removed) still follow: they maintain the model, they do not start one.
|
|
184
|
+
// @comment -- "Changed files are put forward for annotation whatever the intake's state. While nobody has confirmed what the product is for, one more note (raised once a session, like every note) asks the agent to ask the person to confirm the draft: the intake informs, it never holds annotation back."
|
|
187
185
|
const gate = contextGate(root);
|
|
188
|
-
if (!gate.open) {
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
const ranges = hunks.get(path)?.map(h => h.start === h.end ? h.start : `${h.start}-${h.end}`).join(', ');
|
|
196
|
-
add(`review:${path}`, `review changed code in ${path}${ranges ? ` (lines ${ranges})` : ''} with bravos-annotate. Check new behavior and guards even when another symbol in this file already has an annotation.`);
|
|
197
|
-
}
|
|
186
|
+
if (!gate.open && (paths(wl?.worklist).length || paths(wl?.annotated).length)) add(`context:${gate.state}`, gate.message);
|
|
187
|
+
for (const path of paths(wl?.worklist)) {
|
|
188
|
+
add(`unannotated:${path}`, `${path} has no GuardLink annotation: review the change with bravos-annotate; record any security-relevant behavior.`);
|
|
189
|
+
}
|
|
190
|
+
for (const path of paths(wl?.annotated)) {
|
|
191
|
+
const ranges = hunks.get(path)?.map(h => h.start === h.end ? h.start : `${h.start}-${h.end}`).join(', ');
|
|
192
|
+
add(`review:${path}`, `review changed code in ${path}${ranges ? ` (lines ${ranges})` : ''} with bravos-annotate. Check new behavior and guards even when another symbol in this file already has an annotation.`);
|
|
198
193
|
}
|
|
199
194
|
|
|
200
195
|
const excluded = new Set(arr(wl?.excluded).map(e => e?.path ?? e?.file));
|
package/hooks/lib/briefing.mjs
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
// @comment -- "Pure text builder for the session-start briefing, collect() which gathers its read-only guardlink, git and gh facts concurrently under a shared deadline (and renews a signed-in machine's device licence when it is due, through refresh.mjs — the one write it makes, to $BRAVOS_HOME only), and the runJson/runJsonAsync spawn wrappers; dependency-free so it can be copied verbatim into target repos."
|
|
2
2
|
import { spawn, spawnSync } from 'node:child_process';
|
|
3
3
|
import { accessSync, constants, readFileSync } from 'node:fs';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
4
5
|
import { basename, delimiter, dirname, join } from 'node:path';
|
|
5
6
|
import { contextGate, readContext } from './context.mjs';
|
|
6
7
|
import { legacySkills, legacySkillsLine } from './legacy-skills.mjs';
|
|
7
8
|
import { THEMES } from './palette.mjs';
|
|
8
9
|
import { commitsLine, commonDirFrom, readHandoff, readPrefs } from './prefs.mjs';
|
|
10
|
+
import { cliVersion, newer, readUpdate, updateLine } from './update-check.mjs';
|
|
9
11
|
import { readProving } from './proving.mjs';
|
|
10
12
|
import { planLabel, planLine, status as licenceStatus } from './licence.mjs';
|
|
11
13
|
import { readLicenceNote, refreshIfDue } from './refresh.mjs';
|
|
@@ -133,22 +135,40 @@ export function contextLine(context, harness) {
|
|
|
133
135
|
: `${head} — intent.md's rules cite them by id; only ${run} opens the documents themselves`;
|
|
134
136
|
}
|
|
135
137
|
|
|
136
|
-
// @comment -- "The briefing's Intent line.
|
|
138
|
+
// @comment -- "The briefing's Intent line. Until a named person confirms what the product is for, it tells the agent to keep annotating against its own draft (drafting one first when there is none, without waiting for answers) and to ask the person once each session to confirm it on the intake page. Right after setup (a fresh hand-off marker) it says to begin in the first reply. A recorded decline is shown with its name and date, and ends the asking."
|
|
137
139
|
function intentLine(intent, harness, gate, handoff = false) {
|
|
138
140
|
const run = harness === 'claude' ? '/bravos-context' : 'the bravos-context skill';
|
|
139
|
-
|
|
140
|
-
const
|
|
141
|
-
const
|
|
141
|
+
const open = !gate || gate.open !== false;
|
|
142
|
+
const ask = ' Ask the person once this session to confirm it on the intake page (bravos review intent, a few minutes); keep working meanwhile, and never confirm anything for them.';
|
|
143
|
+
const begin = handoff && !open ? ` Setup just finished here and the person expects Bravos to begin: in your first reply, draft the context (${run}, without waiting for answers), start annotating, and show them the intake page. If their first message asks for something else, do that and start this alongside.` : '';
|
|
142
144
|
const declined = gate?.state === 'declined' ? `declined by ${gate.by} on ${gate.at}` : '';
|
|
143
|
-
if (intent.status === 'none')
|
|
144
|
-
|
|
145
|
+
if (intent.status === 'none') {
|
|
146
|
+
if (declined) return `Intent: ${declined} — severities are not calibrated to the product; ${run} when the team is ready`;
|
|
147
|
+
return `Intent: none yet — draft it with ${run} (without waiting for answers) and annotate against that draft.${open ? '' : ask}${begin}`;
|
|
148
|
+
}
|
|
149
|
+
if (intent.status === 'draft') return `Intent: draft (${intent.invariants} invariants, ${intent.drafts} items unconfirmed${declined ? `; context ${declined}` : ''}) — annotate against this draft; its design rules are tested and can block pull requests, labelled as drafts.${open ? '' : ask}`;
|
|
145
150
|
return `Intent: confirmed (${intent.invariants} invariants)`;
|
|
146
151
|
}
|
|
147
152
|
|
|
148
153
|
|
|
149
154
|
const SKILL_SIGIL = { claude: '/', codex: '$', omp: '/skill:', opencode: '/' };
|
|
150
155
|
|
|
151
|
-
// @comment -- "The
|
|
156
|
+
// @comment -- "The background annotation pass: while coverage is under 100%, the briefing asks the agent to start one bravos-annotate slice in a subagent in its first reply, beside whatever the person asked, and to say so. Not on resume or compact (the session already had its pass), not in CI (the nightly is the annotator there), not when the person switched it off (bravos prefs set annotate off) or BRAVOS_AUTO_ANNOTATE=off is set, and not when coverage is unknown. With no intent yet the pass starts after the draft is written, so two agents never draft it at once. A harness without subagents offers the pass instead."
|
|
157
|
+
export function backgroundLine(i) {
|
|
158
|
+
const coverage = Number(i.guardlink?.ci?.summary?.coverage?.percent);
|
|
159
|
+
if (!Number.isFinite(coverage) || coverage >= 100) return null;
|
|
160
|
+
if (i.autoAnnotate === false || i.prefs?.annotate?.value === 'off') return null;
|
|
161
|
+
if (i.source === 'resume' || i.source === 'compact') return null;
|
|
162
|
+
const skill = i.harness === 'claude' ? '/bravos-annotate' : 'the bravos-annotate skill';
|
|
163
|
+
const when = i.intent?.status === 'none' ? 'once the draft intent is written' : 'in your first reply';
|
|
164
|
+
const how = i.harness === 'claude'
|
|
165
|
+
? `start one background annotation pass in a subagent (${skill}, one slice at its default budget) alongside the person's request, and say so in one line`
|
|
166
|
+
: `start one background annotation pass in a subagent (${skill}, one slice at its default budget) alongside the person's request and say so in one line; where this harness has no subagents, offer it once instead`;
|
|
167
|
+
const commits = i.prefs?.commits?.value === 'commit' ? 'it commits only Bravos\'s own files, as the Commits line allows' : 'it commits nothing; it leaves its files for the person';
|
|
168
|
+
return `Background annotation: coverage is ${coverage}% — ${when}, ${how}. It never edits the person's code; ${commits}; when it ends, report in one line what it covered. The person switches this off with bravos prefs set annotate off --by "<their name>".`;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// @comment -- "The coaching block the briefing gives the agent in every harness: the Setup line (score and next unlock with its command) and, unless BRAVOS_COACH=off, a few rules for guiding a person who is not a power user — step up rather than stay silent: every security-relevant reply ends with one concrete next step, a question about issues builds and opens the dashboard, each reminder once per topic per session, plain words first, never lecture; shrinks to one rule once most of setup is on."
|
|
152
172
|
function coachLines(i) {
|
|
153
173
|
if (!i.root || i.guardlink === 'missing') return [];
|
|
154
174
|
const s = readSetup(i.root, i, i.harness);
|
|
@@ -156,13 +176,13 @@ function coachLines(i) {
|
|
|
156
176
|
if (i.env?.BRAVOS_COACH === 'off' || process.env.BRAVOS_COACH === 'off') return out;
|
|
157
177
|
const k = (n) => (SKILL_SIGIL[i.harness] ? `${SKILL_SIGIL[i.harness]}${n}` : n);
|
|
158
178
|
if (s.done > 7) {
|
|
159
|
-
out.push(`How to help:
|
|
179
|
+
out.push(`How to help: step up, never stay silent — end every security-relevant reply with one concrete next step in one plain line (annotate after security edits, confirm untested exposures with ${k('bravos-prove')}, ${k('bravos-ship')} before a PR, ${k('bravos-recheck')} after a fix); once per topic per session, never nag.`);
|
|
160
180
|
return out;
|
|
161
181
|
}
|
|
162
182
|
out.push(
|
|
163
|
-
'How to help this person (
|
|
183
|
+
'How to help this person (step up, never stay silent, never lecture; one reminder per topic per session):',
|
|
164
184
|
`- In your first reply, if setup is under 5 or intent is none, offer once in plain words three starts that fit this repo, in setup order (${i.licence?.licensed === false ? 'on the Free plan: learn what the app intends, annotate the uncovered files, prove the top threats; never lead with a Team-plan step' : 'build the code graph first if it is off, then learn what the app intends, annotate the uncovered files, run SAST, prove the top threats; or check this branch before a PR'}) and \`bravos guide\` for more; then follow their lead.`,
|
|
165
|
-
`-
|
|
185
|
+
`- End every security-relevant reply with one concrete next step, said as a recommendation: after you edit security-relevant code, record what it exposes (${k('bravos-annotate')}); with untested exposures, confirm the top three (${k('bravos-prove')}, or ${k('bravos-env')} first when no target is recorded); before a PR, the ship check (${k('bravos-ship')}); after a fix, a recheck (${k('bravos-recheck')}). When they ask about issues, threats or vulnerabilities, build the dashboard while you answer, without waiting on it (\`bravos dashboard\`: it opens in their browser the first time this session, then \`--no-open\` with the path).`,
|
|
166
186
|
// A standing answer is the briefing's Commits line; with none, ask once and (unless they chose to be asked each time) record it so no later session asks.
|
|
167
187
|
...(commitsLine(i.prefs) ? [] : [`- Commits are the person's call: before the first commit of a session ask once (commit now, or leave the files for them to review), even where a skill says to commit; skip the question only when they already asked for commits (a campaign, a schedule).${i.prefs?.commits?.value === 'ask' ? '' : ' Then ask whether that is their answer from now on, and if so record it with `bravos prefs set commits commit|leave --by "<their name>"`: their answer and their name, never yours.'}`]),
|
|
168
188
|
'- When a request would go better with the next unlock above, say what it would add, once. Plain words first, skill name second. Never send test traffic without the authorization bravos-env asks for.',
|
|
@@ -243,6 +263,8 @@ export function buildBriefing(inputs) {
|
|
|
243
263
|
// The person's standing answer about commits, when they gave one (hooks/lib/prefs.mjs).
|
|
244
264
|
const commits = commitsLine(i.prefs);
|
|
245
265
|
if (commits) tail.push(commits);
|
|
266
|
+
const background = backgroundLine(i);
|
|
267
|
+
if (background) tail.push(background);
|
|
246
268
|
if (i.proving && typeof i.proving === 'object') {
|
|
247
269
|
const p = i.proving;
|
|
248
270
|
tail.push(p.status === 'set'
|
|
@@ -257,6 +279,9 @@ export function buildBriefing(inputs) {
|
|
|
257
279
|
}
|
|
258
280
|
const upkeep = upkeepLine(i.upkeep);
|
|
259
281
|
if (upkeep) tail.push(upkeep);
|
|
282
|
+
// A newer Bravos published than the one installed (hooks/lib/update-check.mjs): the person installs it.
|
|
283
|
+
const update = updateLine(i.update, i.cli);
|
|
284
|
+
if (update) tail.push(update);
|
|
260
285
|
// The portal's last refusal to renew this machine, until it is signed in again (a revocation) or renewed (a plan that ended).
|
|
261
286
|
if (i.licenceNote && (i.licenceNote.outcome === 'lapsed' || i.licence?.licensed === false)) tail.push(`Licence: ${i.licenceNote.note} Tell the person once, in plain words.`);
|
|
262
287
|
// Skills the retired Python bravos left at user level: the agent must not follow them (hooks/lib/legacy-skills.mjs).
|
|
@@ -556,10 +581,15 @@ export async function collect(root, env, { deadlineMs = 20000, nextCount = 3 } =
|
|
|
556
581
|
context: readContext(root),
|
|
557
582
|
gate: contextGate(root),
|
|
558
583
|
prefs: readPrefs(facts.commonDir),
|
|
584
|
+
// The background annotation pass is off for this run (BRAVOS_AUTO_ANNOTATE=off) or in CI, where the nightly annotates.
|
|
585
|
+
autoAnnotate: env.BRAVOS_AUTO_ANNOTATE !== 'off' && !env.CI && !env.GITHUB_ACTIONS,
|
|
559
586
|
handoff: readHandoff(facts.commonDir),
|
|
560
587
|
upkeep,
|
|
561
588
|
// Read after the renewal above has run, so a refusal that just arrived is in it.
|
|
562
589
|
licenceNote: readLicenceNote(env),
|
|
590
|
+
// The last daily update check (~/.bravos/update-check.json) and the installed CLI's version, both file reads.
|
|
591
|
+
update: readUpdate(env.HOME || homedir()),
|
|
592
|
+
cli: cliVersion(env),
|
|
563
593
|
annotationMode: readAnnotationMode(root),
|
|
564
594
|
// bravos on PATH: what its probe says (a graph for this commit or not); else codegraph-mcp on PATH means the MCP route.
|
|
565
595
|
codegraph: graphState ?? (whichOnPath('codegraph-mcp', env) ? 'unknown' : 'unavailable'),
|
|
@@ -845,6 +875,7 @@ function bannerWarnings(i, plan) {
|
|
|
845
875
|
// One line for old Python skills at user level; bravos doctor prints the command that moves them aside.
|
|
846
876
|
const old = arr(i.legacy).reduce((n, f) => n + arr(f?.names).length, 0);
|
|
847
877
|
if (old > 0) lines.push(`! ${old} old Python bravos skill${old === 1 ? '' : 's'} in your user folder · bravos doctor`);
|
|
878
|
+
if (i.update?.latest && i.cli && newer(i.update.latest, i.cli)) lines.push(`~ Update available: bravos ${i.update.latest} (you have ${i.cli}) · npm install -g @bugb-technologies/bravos`);
|
|
848
879
|
return lines;
|
|
849
880
|
}
|
|
850
881
|
|
|
@@ -974,7 +1005,8 @@ export function buildSummary(inputs, opts = {}) {
|
|
|
974
1005
|
const plan = i.licence && typeof i.licence === 'object' && i.licence.state ? planLabel(i.licence) : null;
|
|
975
1006
|
const trial = !plan || plan.licensed ? '' : i.licence.state === 'expired' ? ' · renew: bravos licence' : ' · Team trial: bravos account activate';
|
|
976
1007
|
const third = (setup ? `setup ${setup.done}/${setup.total}${setup.next ? ` · next: ${setup.next.label} · bravos next` : ''} · bravos guide` : guide) + trial;
|
|
977
|
-
|
|
1008
|
+
const update = i.update?.latest && i.cli && newer(i.update.latest, i.cli) ? ` · update: ${i.update.latest} (npm install -g @bugb-technologies/bravos)` : '';
|
|
1009
|
+
return `${head} · ${countsLine(i.guardlink ?? {})}\n${plan ? `plan ${plan.label} · ` : ''}intent ${i.intent?.status ?? 'unknown'} · skills: ${next}\n${third}${update}`;
|
|
978
1010
|
}
|
|
979
1011
|
|
|
980
1012
|
// Brand palette by theme (hooks/lib/palette.mjs). Colour is truecolor ANSI, added after
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
// @comment -- "bravos's coach: before each prompt, at most one dashboard instruction and one reminder for the agent, so Bravos steps up at the moments no skill is loaded. Facts come from a small per-session record the session hook writes under the clone's git directory (<git-common-dir>/bravos/coach/<session>.json), never from guardlink or the network, so the hook stays fast. Each topic is raised once per session; the first prompt gets no reminder (the briefing covers it). It also says, once, when a newer Bravos is out or was just installed, which reaches a session that is already running. Dependency-free."
|
|
2
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { newer } from './update-check.mjs';
|
|
5
|
+
|
|
6
|
+
export const COACH_SCHEMA = 'bravos.coach/v1';
|
|
7
|
+
/** The reminders, in the order they are given when several apply. */
|
|
8
|
+
export const REMINDERS = ['update-installed', 'confirm', 'coverage', 'update-available', 'dashboard-stale'];
|
|
9
|
+
|
|
10
|
+
const SESSION_ID = /^[A-Za-z0-9._-]{1,128}$/;
|
|
11
|
+
|
|
12
|
+
// @comment -- "Where a session's coach record lives: under the git directory, like the preferences, so nothing a repository ships can set it; null for a session id that is not a plain token, so a payload cannot point the path elsewhere."
|
|
13
|
+
// @mitigates #person-prefs against #governance-forgery using #prefs-outside-tree -- "The coach record is written under the git directory, never in the working tree."
|
|
14
|
+
export function coachFile(commonDir, sessionId) {
|
|
15
|
+
if (!commonDir || typeof sessionId !== 'string' || !SESSION_ID.test(sessionId) || sessionId.startsWith('.')) return null;
|
|
16
|
+
return join(commonDir, 'bravos', 'coach', `${sessionId}.json`);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// @comment -- "Reads a session's coach record; anything that is not exactly the recorded shape reads as none, so a damaged file only means no reminders, never an error."
|
|
20
|
+
export function readCoach(commonDir, sessionId) {
|
|
21
|
+
const file = coachFile(commonDir, sessionId);
|
|
22
|
+
if (!file) return null;
|
|
23
|
+
try {
|
|
24
|
+
const d = JSON.parse(readFileSync(file, 'utf8'));
|
|
25
|
+
if (!d || typeof d !== 'object' || d.schema !== COACH_SCHEMA || !d.facts || typeof d.facts !== 'object') return null;
|
|
26
|
+
return { facts: d.facts, raised: Array.isArray(d.raised) ? d.raised.filter((t) => typeof t === 'string') : [], prompts: Number.isInteger(d.prompts) && d.prompts >= 0 ? d.prompts : 0, opened: d.opened === true };
|
|
27
|
+
} catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// @comment -- "Writes a session's coach record through a temporary file and a rename, 0600. Best effort: a failure only means no reminders this session."
|
|
33
|
+
export function writeCoach(commonDir, sessionId, record) {
|
|
34
|
+
const file = coachFile(commonDir, sessionId);
|
|
35
|
+
if (!file) return null;
|
|
36
|
+
try {
|
|
37
|
+
mkdirSync(join(file, '..'), { recursive: true, mode: 0o700 });
|
|
38
|
+
const tmp = `${file}.tmp-${process.pid}`;
|
|
39
|
+
writeFileSync(tmp, JSON.stringify({ schema: COACH_SCHEMA, ...record }) + '\n', { mode: 0o600 });
|
|
40
|
+
renameSync(tmp, file);
|
|
41
|
+
return file;
|
|
42
|
+
} catch {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// @comment -- "The facts the coach needs, taken from what the session hook already collected (BriefingInputs): coverage, how many claims guardlink queues to test or fix and the top three, whether a test target is recorded, the plan and the intake state. Pure."
|
|
48
|
+
export function coachFacts(i) {
|
|
49
|
+
const cov = i?.guardlink?.ci?.summary?.coverage;
|
|
50
|
+
const next = i?.guardlink?.next;
|
|
51
|
+
const queue = Array.isArray(next?.queue) ? next.queue : [];
|
|
52
|
+
const num = (v) => (Number.isFinite(Number(v)) ? Number(v) : null);
|
|
53
|
+
return {
|
|
54
|
+
coverage: cov ? { percent: num(cov.percent), annotated: num(cov.annotated_files), source: num(cov.source_files) } : null,
|
|
55
|
+
queued: num(next?.total) ?? queue.length,
|
|
56
|
+
top: queue.slice(0, 3).map((q) => ({ threat: String(q?.threat ?? ''), asset: String(q?.asset ?? ''), file: String(q?.file ?? ''), line: num(q?.line), state: String(q?.state ?? '') })),
|
|
57
|
+
target: i?.proving?.status === 'set' && !!i?.proving?.target,
|
|
58
|
+
licensed: i?.licence?.licensed === true ? true : i?.licence?.licensed === false ? false : null,
|
|
59
|
+
harness: i?.harness === 'claude' ? 'claude' : 'other',
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// @comment -- "Records the session's facts when it starts. A resume or compact of the same session keeps what was already raised, so a reminder is never given twice in one session."
|
|
64
|
+
export function startCoach(commonDir, sessionId, inputs) {
|
|
65
|
+
const old = readCoach(commonDir, sessionId);
|
|
66
|
+
return writeCoach(commonDir, sessionId, { facts: coachFacts(inputs), raised: old?.raised ?? [], prompts: old?.prompts ?? 0, opened: old?.opened ?? false });
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// The questions that mean "show me the security picture". Plain "issue" or "bug" counts only with a word that makes it about findings, so "fix this issue" does not open a dashboard.
|
|
70
|
+
const STRONG = /\b(threats?|vulns?|vulnerab\w*|findings?|exposures?|cves?|exploitable|attack surface|threat model|security (?:posture|picture|status|issues?|problems?|risks?)|risks?|risky|dashboard)\b/i;
|
|
71
|
+
const SOFT = /\b(?:what|which|show|list|any|identified|found|open|known|all|remaining|outstanding)\b[^.?!\n]{0,40}\b(?:issues|bugs|problems)\b|\bwhat(?:'s| is) open\b/i;
|
|
72
|
+
|
|
73
|
+
// @comment -- "Whether the person's prompt asks about the security picture: issues, threats, vulnerabilities, findings, risks, exposures, the dashboard. Pure."
|
|
74
|
+
export function asksAboutIssues(prompt) {
|
|
75
|
+
const p = String(prompt ?? '').slice(0, 4000);
|
|
76
|
+
return STRONG.test(p) || SOFT.test(p);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// @comment -- "The newest modification time under .guardlink/ (sidecars, definitions, intent, the ledger), bounded to a few thousand entries so the hook stays fast; 0 when there is none. Inline annotations in source files are not seen: the session's own commits are caught by the dashboard's commit."
|
|
80
|
+
export function newestModelChange(root, limit = 4000) {
|
|
81
|
+
let newest = 0;
|
|
82
|
+
let seen = 0;
|
|
83
|
+
const walk = (dir) => {
|
|
84
|
+
let entries;
|
|
85
|
+
try {
|
|
86
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
87
|
+
} catch {
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
for (const e of entries) {
|
|
91
|
+
if (++seen > limit) return;
|
|
92
|
+
const p = join(dir, e.name);
|
|
93
|
+
if (e.isDirectory()) walk(p);
|
|
94
|
+
else if (e.isFile()) {
|
|
95
|
+
try {
|
|
96
|
+
newest = Math.max(newest, statSync(p).mtimeMs);
|
|
97
|
+
} catch {
|
|
98
|
+
/* gone */
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
if (existsSync(join(root, '.guardlink'))) walk(join(root, '.guardlink'));
|
|
104
|
+
return newest;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const where = (t) => `${t.threat}${t.asset ? ` on ${t.asset}` : ''}${t.file ? ` (${t.file}${t.line ? `:${t.line}` : ''})` : ''}`;
|
|
108
|
+
|
|
109
|
+
// @comment -- "Decides what the coach says before one prompt. Returns the text for the agent (or '') and the record to keep. The dashboard instruction comes whenever the prompt asks about the security picture, opening the page only the first time in the session; then at most one reminder, never on the first prompt and never a topic already raised. Free-plan text names no Team step. Pure: the caller supplies the dashboard record and the newest model change."
|
|
110
|
+
export function coachTurn({ record, prompt, dashboard = null, modelChangedAt = 0, head = null, versions = {} }) {
|
|
111
|
+
if (!record?.facts) return { text: '', record, topics: [] };
|
|
112
|
+
const f = record.facts;
|
|
113
|
+
const k = (n) => (f.harness === 'claude' ? `/${n}` : n);
|
|
114
|
+
const raised = new Set(record.raised);
|
|
115
|
+
const lines = [];
|
|
116
|
+
const topics = [];
|
|
117
|
+
let opened = record.opened;
|
|
118
|
+
|
|
119
|
+
if (asksAboutIssues(prompt)) {
|
|
120
|
+
lines.push(opened
|
|
121
|
+
? 'Bravos: they are asking about the security picture. As you answer, rebuild the dashboard without waiting on it (`bravos dashboard --no-open`, as a background job or subagent) and give its path in one line.'
|
|
122
|
+
: 'Bravos: they are asking about the security picture. As you answer, build the dashboard without waiting on it (`bravos dashboard`, as a background job or subagent): it rebuilds from the code and opens in their browser. Say in one line that it is opening.');
|
|
123
|
+
topics.push(opened ? 'dashboard' : 'dashboard-open');
|
|
124
|
+
opened = true;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
if (record.prompts > 0) {
|
|
128
|
+
const cov = f.coverage;
|
|
129
|
+
const stale = dashboard && Number.isFinite(dashboard.generatedAt) && (modelChangedAt > dashboard.generatedAt || (head && dashboard.commit && !head.startsWith(dashboard.commit) && !dashboard.commit.startsWith(head)));
|
|
130
|
+
const { cli = null, repo = null, latest = null } = versions;
|
|
131
|
+
const due = {
|
|
132
|
+
'update-installed': !!cli && !!repo && newer(cli, repo),
|
|
133
|
+
'update-available': !!latest && !!cli && newer(latest, cli),
|
|
134
|
+
confirm: f.queued > 0,
|
|
135
|
+
coverage: !!cov && Number.isFinite(cov.percent) && cov.percent < 100,
|
|
136
|
+
'dashboard-stale': !!stale && !topics.length,
|
|
137
|
+
};
|
|
138
|
+
const pick = REMINDERS.find((t) => due[t] && !raised.has(t));
|
|
139
|
+
if (pick === 'update-installed') {
|
|
140
|
+
lines.push(`Bravos reminder (once this session): Bravos was updated to ${cli}, and this repository's Bravos files are from ${repo}. Run \`bravos setup\` here now (from an agent it only brings Bravos's own files and bundles up to date) and say so in one line; the new hooks apply from the next prompt, new skills when next loaded.`);
|
|
141
|
+
} else if (pick === 'update-available') {
|
|
142
|
+
lines.push(`Bravos reminder (once this session): Bravos ${latest} is out (installed ${cli}). After answering, tell the person in one line: npm install -g @bugb-technologies/bravos in their own terminal. Never run it yourself.`);
|
|
143
|
+
} else if (pick === 'confirm') {
|
|
144
|
+
const top = f.top.filter((t) => t.threat).map(where);
|
|
145
|
+
const how = f.target
|
|
146
|
+
? `${k('bravos-prove')} can test them now on the recorded target`
|
|
147
|
+
: `none has a test target yet, so offer to set one up now with ${k('bravos-env')} (the person types their own authorization), then ${k('bravos-prove')}`;
|
|
148
|
+
lines.push(`Bravos reminder (once this session): ${f.queued} claim${f.queued === 1 ? '' : 's'} wait${f.queued === 1 ? 's' : ''} to be tested or fixed${top.length ? `, starting with ${top.join('; ')}` : ''}. After answering, recommend confirming the top three now: ${how}.`);
|
|
149
|
+
} else if (pick === 'coverage') {
|
|
150
|
+
const files = Number.isFinite(cov.annotated) && Number.isFinite(cov.source) ? ` (${cov.annotated} of ${cov.source} files)` : '';
|
|
151
|
+
const more = f.licensed === false ? `the next round (${k('bravos-annotate')})` : `the next round (${k('bravos-annotate')}), or a campaign to a coverage goal (${k('bravos-campaign')})`;
|
|
152
|
+
lines.push(`Bravos reminder (once this session): the threat model covers ${cov.percent}% of the code${files}. After answering, say so in one line and offer ${more}.`);
|
|
153
|
+
} else if (pick === 'dashboard-stale') {
|
|
154
|
+
lines.push('Bravos reminder (once this session): the threat model changed after the dashboard was built. After answering, offer to rebuild it (`bravos dashboard --no-open`).');
|
|
155
|
+
}
|
|
156
|
+
if (pick) topics.push(pick);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const next = { facts: f, raised: [...raised, ...topics.filter((t) => REMINDERS.includes(t))], prompts: record.prompts + 1, opened };
|
|
160
|
+
return { text: lines.join('\n'), record: next, topics };
|
|
161
|
+
}
|
package/hooks/lib/context.mjs
CHANGED
|
@@ -400,7 +400,7 @@ export function readContext(root) {
|
|
|
400
400
|
export const STATUS_PATH = `${CONTEXT_DIR}/status.json`;
|
|
401
401
|
export const STATUS_SCHEMA = 'bravos.context-status/v1';
|
|
402
402
|
|
|
403
|
-
// @comment -- "Whether
|
|
403
|
+
// @comment -- "Whether a named person has settled the intake 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 a message asking for the intake, when there is no intent or only the agent's draft. Nothing refuses on it any more: annotation, autopilot and the nightlies go on, and the briefing asks once a session while it is closed. Reads two files and never throws; the same function, byte for byte, ships with the annotate skill."
|
|
404
404
|
// gate:begin — kept identical, between these two markers, in skills/bravos-annotate/scripts/lib/gate.mjs (the copy the
|
|
405
405
|
// annotate script runs, which cannot import from the hook scripts); tests/context-gate.test.ts holds the two together.
|
|
406
406
|
const GATE_INTENT = '.guardlink/intent.md';
|
|
@@ -435,10 +435,11 @@ export function contextGate(root, fs = { readFileSync, join }) {
|
|
|
435
435
|
state,
|
|
436
436
|
message:
|
|
437
437
|
(state === 'none'
|
|
438
|
-
? 'Context
|
|
439
|
-
: 'Context
|
|
440
|
-
'
|
|
441
|
-
'
|
|
438
|
+
? 'Context not recorded yet: nobody has said what this product is meant to do.'
|
|
439
|
+
: 'Context not confirmed yet: the intent here is the agent\'s draft, and no named person has confirmed it.') +
|
|
440
|
+
' Annotation goes on regardless, judged against the draft (with no intent yet, the bravos-context skill drafts one first, without waiting for answers).' +
|
|
441
|
+
' Ask the person once this session to confirm it on the intake page: bravos review intent.' +
|
|
442
|
+
' A team that chooses to go without records that by a named person: bravos context decline --by "<name>".',
|
|
442
443
|
};
|
|
443
444
|
}
|
|
444
445
|
// gate:end
|
package/hooks/lib/pre-pr.mjs
CHANGED
|
@@ -137,6 +137,26 @@ function ledgerGateClaims(root, run, options) {
|
|
|
137
137
|
}
|
|
138
138
|
|
|
139
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
|
+
// @comment -- "The INV ids in .guardlink/intent.md that no named person has confirmed: an INV-n bullet whose text after the last ' — ' starts with draft, or that has no attribution at all (the same reading as bravos rules). A draft rule blocks like a confirmed one; this only labels it, so the person sees the rule came from the agent's draft."
|
|
141
|
+
function draftRuleIds(root) {
|
|
142
|
+
const ids = new Set();
|
|
143
|
+
const seen = new Set();
|
|
144
|
+
let text = '';
|
|
145
|
+
try {
|
|
146
|
+
text = readFileSync(join(root, '.guardlink', 'intent.md'), 'utf8');
|
|
147
|
+
} catch {
|
|
148
|
+
return ids;
|
|
149
|
+
}
|
|
150
|
+
for (const line of text.split(/\r?\n/)) {
|
|
151
|
+
const m = /^\s*[-*]\s+(INV-\d+)\s*:\s*(.+)$/.exec(line);
|
|
152
|
+
if (!m || seen.has(m[1])) continue;
|
|
153
|
+
seen.add(m[1]);
|
|
154
|
+
const dash = m[2].lastIndexOf(' — ');
|
|
155
|
+
if (dash < 0 || /^draft\b/i.test(m[2].slice(dash + 3).trim())) ids.add(m[1]);
|
|
156
|
+
}
|
|
157
|
+
return ids;
|
|
158
|
+
}
|
|
159
|
+
|
|
140
160
|
function designRuleChanges(root, base, run, options) {
|
|
141
161
|
if (!existsSync(join(root, '.guardlink', 'intent.md'))) return { lapsed: [], untested: [] };
|
|
142
162
|
const model = runJson(run, 'guardlink parse', 'guardlink', ['parse', '.'], options);
|
|
@@ -157,13 +177,14 @@ function designRuleChanges(root, base, run, options) {
|
|
|
157
177
|
const sites = [...(Array.isArray(model.json.exposures) ? model.json.exposures : []), ...(Array.isArray(model.json.mitigations) ? model.json.mitigations : [])];
|
|
158
178
|
const lapsed = [];
|
|
159
179
|
const untested = [];
|
|
180
|
+
const drafts = draftRuleIds(root);
|
|
160
181
|
for (const t of rules) {
|
|
161
182
|
const id = bare(t.id);
|
|
162
183
|
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
184
|
if (!files.length) continue;
|
|
164
185
|
const inv = (Array.isArray(t.external_refs) ? t.external_refs : []).map(r => /^intent:(INV-\d+)$/i.exec(String(r))?.[1]).find(Boolean) ?? null;
|
|
165
186
|
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 };
|
|
187
|
+
const row = { threat: `#${id}`, inv, files, draft: !!inv && drafts.has(inv.toUpperCase()) };
|
|
167
188
|
if (!held.length) {
|
|
168
189
|
untested.push(row);
|
|
169
190
|
continue;
|
|
@@ -324,7 +345,7 @@ export function runGate({ root, action, command, cwd = root, env = process.env,
|
|
|
324
345
|
const design = designRuleChanges(root, base, run, o);
|
|
325
346
|
if (design.error) unknown(design);
|
|
326
347
|
else {
|
|
327
|
-
const line = (r) => ` - ${r.inv ? `${r.inv} ` : ''}${r.threat} — ${r.files.join(', ')}${r.tested ? ` (last tested ${r.tested})` : ''}`;
|
|
348
|
+
const line = (r) => ` - ${r.inv ? `${r.inv} ` : ''}${r.draft ? '(draft: not yet confirmed by a person) ' : ''}${r.threat} — ${r.files.join(', ')}${r.tested ? ` (last tested ${r.tested})` : ''}`;
|
|
328
349
|
if (design.lapsed.length) {
|
|
329
350
|
let body = null;
|
|
330
351
|
if (action === 'create') body = commandBody(command, cwd);
|
package/hooks/lib/prefs.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// @comment -- "A person's standing answers to questions Bravos would otherwise ask every session, kept per clone and never committed.
|
|
1
|
+
// @comment -- "A person's standing answers to questions Bravos would otherwise ask every session, kept per clone and never committed. Two today: what to do with Bravos's own files (annotations, intent, definitions, tests, the ledger) once they are written: commit them, leave them for the person, or keep asking; whether the agent starts one background annotation pass each session while coverage is incomplete (background, the default) or not (off); and whether the coach adds reminders before prompts (on, the default) or not (off). The file lives under the git directory (<git-common-dir>/bravos/prefs.json), which no commit, clone or pull can write, so a repository cannot ship an answer and grant itself silent commits, and every worktree of a clone shares it. Dependency-free: the session hook reads it, the CLI writes it."
|
|
2
2
|
import { spawnSync } from 'node:child_process';
|
|
3
3
|
import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
4
4
|
import { isAbsolute, join, resolve } from 'node:path';
|
|
@@ -6,6 +6,12 @@ import { isAbsolute, join, resolve } from 'node:path';
|
|
|
6
6
|
export const PREFS_SCHEMA = 'bravos.prefs/v1';
|
|
7
7
|
/** commit: commit Bravos's own files without asking. leave: never commit them, list them. ask: ask each session (the default when nothing is recorded). */
|
|
8
8
|
export const COMMIT_CHOICES = ['commit', 'leave', 'ask'];
|
|
9
|
+
/** background: one annotation pass in a subagent each session while coverage is incomplete (the default when nothing is recorded). off: none. */
|
|
10
|
+
export const ANNOTATE_CHOICES = ['background', 'off'];
|
|
11
|
+
/** on: the coach adds a reminder before a prompt when one is due (the default when nothing is recorded). off: none. */
|
|
12
|
+
export const COACH_CHOICES = ['on', 'off'];
|
|
13
|
+
/** Each recorded answer and the choices it may hold. */
|
|
14
|
+
export const PREF_CHOICES = { commits: COMMIT_CHOICES, annotate: ANNOTATE_CHOICES, coach: COACH_CHOICES };
|
|
9
15
|
|
|
10
16
|
// One line of visible text: a name goes into the briefing, so control and invisible characters never do.
|
|
11
17
|
const clean = (v, max) => String(v ?? '').replace(/[\u0000-\u001F\u007F-\u009F----]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, max);
|
|
@@ -26,10 +32,10 @@ export function commonDirFrom(root, printed) {
|
|
|
26
32
|
|
|
27
33
|
export const prefsFile = (commonDir) => join(commonDir, 'bravos', 'prefs.json');
|
|
28
34
|
|
|
29
|
-
// @comment -- "Reads the preferences for a clone.
|
|
35
|
+
// @comment -- "Reads the preferences for a clone, each answer on its own. An answer that is not exactly the recorded shape (another schema, an unknown choice, no name, a date that is not a date) reads as nothing recorded, so a damaged or hand-made file can only make Bravos ask again or fall back to its default, never commit."
|
|
30
36
|
// @mitigates #person-prefs against #governance-forgery using #prefs-outside-tree -- "Only a well-formed record under the git directory counts as the person's answer."
|
|
31
37
|
export function readPrefs(commonDir) {
|
|
32
|
-
const none = { commits: null };
|
|
38
|
+
const none = { commits: null, annotate: null, coach: null };
|
|
33
39
|
if (!commonDir) return none;
|
|
34
40
|
let doc;
|
|
35
41
|
try {
|
|
@@ -38,17 +44,27 @@ export function readPrefs(commonDir) {
|
|
|
38
44
|
return none;
|
|
39
45
|
}
|
|
40
46
|
if (!doc || typeof doc !== 'object' || doc.schema !== PREFS_SCHEMA) return none;
|
|
41
|
-
const
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
47
|
+
const one = (key) => {
|
|
48
|
+
const c = doc[key];
|
|
49
|
+
if (!c || typeof c !== 'object' || !PREF_CHOICES[key].includes(c.value)) return null;
|
|
50
|
+
const by = clean(c.by, 80);
|
|
51
|
+
if (!by || by.startsWith('<') || typeof c.at !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(c.at)) return null;
|
|
52
|
+
return { value: c.value, by, at: c.at };
|
|
53
|
+
};
|
|
54
|
+
return { commits: one('commits'), annotate: one('annotate'), coach: one('coach') };
|
|
46
55
|
}
|
|
47
56
|
|
|
48
|
-
// @comment -- "Records the answer a named person gave
|
|
57
|
+
// @comment -- "Records the commits answer a named person gave (writePref does the work)."
|
|
49
58
|
export function writeCommits(commonDir, value, by, at) {
|
|
59
|
+
return writePref(commonDir, 'commits', value, by, at);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// @comment -- "Records one answer a named person gave: the choice, their name and the date, written 0600 through a temporary file and a rename. Refuses an unknown key or choice and an empty or placeholder name; other keys already in the file are kept."
|
|
63
|
+
export function writePref(commonDir, key, value, by, at) {
|
|
50
64
|
if (!commonDir) throw new Error('this is not a git repository: preferences are kept under its git directory');
|
|
51
|
-
if (!
|
|
65
|
+
if (!Object.hasOwn(PREF_CHOICES, key)) throw new Error(`no such preference: ${key} (one of ${Object.keys(PREF_CHOICES).join(', ')})`);
|
|
66
|
+
const choices = PREF_CHOICES[key];
|
|
67
|
+
if (!choices.includes(value)) throw new Error(`the choice must be one of ${choices.join(', ')}`);
|
|
52
68
|
const name = clean(by, 80);
|
|
53
69
|
if (!name || name.startsWith('<')) throw new Error('say whose answer this is: --by "<their name>"');
|
|
54
70
|
if (!/^\d{4}-\d{2}-\d{2}$/.test(String(at))) throw new Error('the date must be YYYY-MM-DD');
|
|
@@ -62,7 +78,7 @@ export function writeCommits(commonDir, value, by, at) {
|
|
|
62
78
|
}
|
|
63
79
|
mkdirSync(join(file, '..'), { recursive: true, mode: 0o700 });
|
|
64
80
|
const tmp = `${file}.tmp-${process.pid}`;
|
|
65
|
-
writeFileSync(tmp, JSON.stringify({ ...doc, schema: PREFS_SCHEMA,
|
|
81
|
+
writeFileSync(tmp, JSON.stringify({ ...doc, schema: PREFS_SCHEMA, [key]: { value, by: name, at } }, null, 2) + '\n', { mode: 0o600 });
|
|
66
82
|
try {
|
|
67
83
|
chmodSync(tmp, 0o600);
|
|
68
84
|
} catch {
|
|
@@ -82,7 +98,7 @@ export function commitsLine(prefs) {
|
|
|
82
98
|
: `Commits: leave Bravos's own files uncommitted and list them; do not ask (${whose}).`;
|
|
83
99
|
}
|
|
84
100
|
|
|
85
|
-
// @comment -- "The hand-off from bravos setup to the first agent session: a dated marker in this clone's git directory saying setup just finished here and the person expects Bravos to begin. While it is fresh and
|
|
101
|
+
// @comment -- "The hand-off from bravos setup to the first agent session: a dated marker in this clone's git directory saying setup just finished here and the person expects Bravos to begin. While it is fresh and there is no intent yet, the briefing tells the agent, in its first reply, to draft the context, start annotating and show the intake page; without it, or after a few days, the briefing only offers, so a session opened for something else is never taken over. Like the preferences, nothing in a repository's tree can write it."
|
|
86
102
|
export const HANDOFF_DAYS = 3;
|
|
87
103
|
export const handoffFile = (commonDir) => join(commonDir, 'bravos', 'handoff.json');
|
|
88
104
|
|
package/hooks/lib/setup.mjs
CHANGED
|
@@ -30,9 +30,9 @@ export function readSetup(root, i = {}, harness = 'other') {
|
|
|
30
30
|
},
|
|
31
31
|
{
|
|
32
32
|
id: 'intent',
|
|
33
|
-
// Done when
|
|
34
|
-
//
|
|
35
|
-
//
|
|
33
|
+
// Done when a named person confirmed the intent, or declined. A draft nobody confirmed is not done: annotation
|
|
34
|
+
// goes on against the draft meanwhile, and this item keeps asking a person to confirm it. Callers that do not
|
|
35
|
+
// pass the gate (older ones) keep the earlier reading: any intent at all.
|
|
36
36
|
on: i.gate && typeof i.gate.open === 'boolean' ? i.gate.open : !!(i.intent?.status && i.intent.status !== 'none'),
|
|
37
37
|
label: i.intent?.status === 'draft' ? 'confirm what the app intends' : 'record what the app intends',
|
|
38
38
|
cta: skill('bravos-context', harness),
|