@bugb-technologies/bravos 1.6.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/cli.js +82 -17
  2. package/dist/codegraph.js +21 -0
  3. package/dist/context.js +36 -0
  4. package/dist/graphbin.js +2 -0
  5. package/dist/guide.js +7 -5
  6. package/dist/help.js +24 -5
  7. package/dist/install.js +2 -1
  8. package/dist/lock.js +1 -0
  9. package/dist/mcp.js +18 -3
  10. package/dist/palette.js +4 -4
  11. package/dist/prefs.js +47 -0
  12. package/dist/review-server.js +4 -4
  13. package/dist/review-wait.js +76 -0
  14. package/dist/review.js +103 -18
  15. package/dist/start/answers.js +33 -4
  16. package/dist/start/index.js +138 -57
  17. package/dist/upkeep.js +89 -0
  18. package/dist/watch-frame.js +67 -42
  19. package/dist/watch.js +21 -7
  20. package/docs/GUIDE.md +17 -5
  21. package/docs/UPGRADING.md +27 -0
  22. package/hooks/lib/autopilot.mjs +3 -18
  23. package/hooks/lib/briefing.mjs +250 -173
  24. package/hooks/lib/graph-autobuild.mjs +131 -0
  25. package/hooks/lib/palette.mjs +4 -4
  26. package/hooks/lib/prefs.mjs +108 -0
  27. package/hooks/lib/refresh.mjs +45 -1
  28. package/hooks/lib/setup.mjs +1 -1
  29. package/hooks/lib/snapshot.mjs +19 -1
  30. package/hooks/session-start.mjs +29 -2
  31. package/package.json +1 -1
  32. package/skills/bravos/SKILL.md +4 -3
  33. package/skills/bravos-annotate/SKILL.md +2 -2
  34. package/skills/bravos-context/SKILL.md +7 -6
  35. package/skills/bravos-env/SKILL.md +2 -2
  36. package/skills/bravos-env/scope.example.yaml +2 -1
  37. package/skills/bravos-prove/SKILL.md +2 -2
  38. package/skills/bravos-recheck/SKILL.md +1 -1
  39. package/skills/bravos-resync/SKILL.md +1 -1
  40. package/skills/bravos-ship/SKILL.md +1 -1
  41. package/skills/bravos-templatize/SKILL.md +1 -1
  42. package/templates/review/review.html +369 -124
package/dist/review.js CHANGED
@@ -1,9 +1,10 @@
1
+ import { execFileSync } from 'node:child_process';
1
2
  import { randomBytes } from 'node:crypto';
2
- import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
3
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
4
  import { createServer } from 'node:http';
4
5
  import { dirname, join } from 'node:path';
5
- import { pathToFileURL } from 'node:url';
6
- import { hooksDir, templatesDir } from './paths.js';
6
+ import { reviewSources } from './context.js';
7
+ import { templatesDir } from './paths.js';
7
8
  import { BravosError } from './types.js';
8
9
  // @comment -- "bravos review: the drafts an agent wrote (.guardlink/<kind>-draft.json) rendered as a bravos-branded page people answer in, a loopback-only server that saves each person's answers to .guardlink/<kind>-answers/<name>.json, and a plain-text summary of agreement and disagreement for the agent. Draft text comes from repo files and is untrusted: it travels as JSON and the page renders it with textContent."
9
10
  export const REVIEW_SCHEMA = 'bravos.review/v1';
@@ -32,9 +33,12 @@ export function validateDraft(value, kind) {
32
33
  throw bad(`kind must be '${kind}'`);
33
34
  if (!Array.isArray(value.questions) || value.questions.length === 0 || value.questions.length > 300)
34
35
  throw bad('needs 1 to 300 questions');
36
+ if (value.repo !== undefined && !str(value.repo))
37
+ throw bad('repo must be a string');
35
38
  if (value.perspective !== undefined && value.perspective !== 'researcher' && value.perspective !== 'owner')
36
39
  throw bad('perspective must be researcher or owner');
37
40
  const seen = new Set();
41
+ const cells = new Set();
38
42
  for (const [n, q] of value.questions.entries()) {
39
43
  if (!isObject(q))
40
44
  throw bad(`question ${n + 1} is not an object`);
@@ -69,6 +73,22 @@ export function validateDraft(value, kind) {
69
73
  throw bad(`${q.id}: an item needs its text`);
70
74
  if (q.sources !== undefined && !(Array.isArray(q.sources) && q.sources.every((s) => str(s, 400))))
71
75
  throw bad(`${q.id}: sources must be strings`);
76
+ if (q.permission !== undefined) {
77
+ const p = q.permission;
78
+ const label = (v) => typeof v === 'string' && v.trim().length > 0 && v.length <= 160;
79
+ if (!isObject(p) || !label(p.role) || !label(p.action) || (p.group !== undefined && !label(p.group)) || (p.effect !== 'allow' && p.effect !== 'deny')) {
80
+ throw bad(`${q.id}: permission needs a role, action and allow or deny effect`);
81
+ }
82
+ if (q.type !== 'item' || q.suggested !== 'agree' || !Array.isArray(q.sources) || !q.sources.some((s) => /\bSRC-[1-9][0-9]{0,4}\b/.test(s))) {
83
+ throw bad(`${q.id}: a permission must be an item with suggested agree and a stored source citation`);
84
+ }
85
+ if ((p.effect === 'deny' || q.confidence === 'low') && q.mustTouch !== true)
86
+ throw bad(`${q.id}: a denied or uncertain permission needs mustTouch`);
87
+ const key = JSON.stringify([p.group ?? (q.section || 'Permissions'), p.role, p.action]);
88
+ if (cells.has(key))
89
+ throw bad(`${q.id}: duplicate permission cell; combine its evidence in one question`);
90
+ cells.add(key);
91
+ }
72
92
  }
73
93
  return value;
74
94
  }
@@ -81,7 +101,7 @@ export function validateAnswers(value, draft) {
81
101
  if (!isObject(value.answers))
82
102
  throw new BravosError('answers must be an object keyed by question id');
83
103
  const ids = new Set(draft.questions.map((q) => q.id));
84
- const answers = {};
104
+ const answers = Object.create(null);
85
105
  for (const [id, a] of Object.entries(value.answers)) {
86
106
  if (!ids.has(id) || !isObject(a))
87
107
  continue;
@@ -125,9 +145,17 @@ export function readAllAnswers(root, draft) {
125
145
  const skipped = [];
126
146
  if (!existsSync(dir))
127
147
  return { files, skipped };
148
+ const base = join(realpathSync(root), answersDir(draft.kind));
149
+ if (realpathSync(dir) !== base || !lstatSync(dir).isDirectory())
150
+ return { files, skipped: [answersDir(draft.kind)] };
128
151
  for (const f of readdirSync(dir).filter((n) => n.endsWith('.json')).sort()) {
129
152
  try {
130
- files.push(validateAnswers(JSON.parse(readFileSync(join(dir, f), 'utf8')), draft));
153
+ const abs = join(base, f);
154
+ if (!lstatSync(abs).isFile() || realpathSync(abs) !== abs) {
155
+ skipped.push(f);
156
+ continue;
157
+ }
158
+ files.push(validateAnswers(JSON.parse(readFileSync(abs, 'utf8')), draft));
131
159
  }
132
160
  catch {
133
161
  skipped.push(f);
@@ -135,17 +163,76 @@ export function readAllAnswers(root, draft) {
135
163
  }
136
164
  return { files, skipped };
137
165
  }
138
- /** The brand art for the page header, from the hook's own constants (one source for banner and page). */
139
- async function brandArt() {
140
- const lib = await import(pathToFileURL(join(hooksDir(), 'lib', 'briefing.mjs')).href);
141
- return { mascot: lib.MASCOT, logo: lib.LOGO };
166
+ // @comment -- "Review pages may contain a team's design documents and answers may contain names or comments. Write only below real repository directories, then atomically replace the destination so a pre-existing link cannot redirect the write."
167
+ function writeReviewFile(root, rel, data) {
168
+ let dir = realpathSync(root);
169
+ for (const part of dirname(rel).split(/[\\/]/)) {
170
+ dir = join(dir, part);
171
+ try {
172
+ mkdirSync(dir, { mode: 0o700 });
173
+ }
174
+ catch (e) {
175
+ if (e.code !== 'EEXIST')
176
+ throw e;
177
+ }
178
+ if (!lstatSync(dir).isDirectory() || realpathSync(dir) !== dir)
179
+ throw new BravosError(`refusing to write through a link in ${rel}`);
180
+ }
181
+ const temp = join(dir, `.bravos-${randomBytes(16).toString('hex')}.tmp`);
182
+ try {
183
+ writeFileSync(temp, data, { flag: 'wx', mode: 0o600 });
184
+ renameSync(temp, join(root, rel));
185
+ }
186
+ finally {
187
+ rmSync(temp, { force: true });
188
+ }
189
+ }
190
+ // @comment -- "Make the repository label a link only when the draft names the same project as this checkout's GitHub origin. Reconstruct a public HTTPS path so credentials, local paths and URL parameters never enter the page."
191
+ function reviewRepoUrl(root, label) {
192
+ if (!label)
193
+ return;
194
+ try {
195
+ const origin = execFileSync('git', ['config', '--get', 'remote.origin.url'], {
196
+ cwd: root, encoding: 'utf8', timeout: 1500, stdio: ['ignore', 'pipe', 'ignore'],
197
+ }).trim();
198
+ const match = /^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([a-z0-9-]+)\/([a-z0-9_.-]+?)\/?$/i.exec(origin);
199
+ if (!match)
200
+ return;
201
+ const owner = match[1], repo = match[2].replace(/\.git$/i, '');
202
+ if (!repo || repo === '.' || repo === '..')
203
+ return;
204
+ if (![repo, `${owner}/${repo}`].some((name) => name.toLowerCase() === label.toLowerCase()))
205
+ return;
206
+ return `https://github.com/${owner}/${repo}`;
207
+ }
208
+ catch {
209
+ return;
210
+ }
211
+ }
212
+ const citedIds = (q) => (q.sources ?? []).flatMap((s) => s.match(/\bSRC-[1-9][0-9]{0,4}\b/g) ?? []);
213
+ // @comment -- "Take one local evidence snapshot for both the page and the server that accepts answers. A permission whose citations cannot all be verified needs an explicit decision, even when the draft suggested accepting it."
214
+ export async function prepareReview(root, draft) {
215
+ const sources = await reviewSources(root, new Set(draft.questions.flatMap(citedIds)));
216
+ const verified = new Set(sources.map((s) => s.id));
217
+ const questions = draft.questions.map((q) => {
218
+ if (!q.permission)
219
+ return q;
220
+ const missing = [...new Set(citedIds(q).filter((id) => !verified.has(id)))];
221
+ if (!missing.length)
222
+ return q;
223
+ return { ...q, mustTouch: true, confidence: 'low',
224
+ reason: [q.reason, `Check ${missing.join(', ')} before deciding. Its source text could not be included and verified for this review.`].filter(Boolean).join(' ') };
225
+ });
226
+ return { draft: { ...draft, questions }, sources, repoUrl: reviewRepoUrl(root, draft.repo) };
142
227
  }
143
- // @comment -- "Renders the self-contained review page: the template with the draft, mode and brand art embedded as JSON in a non-executing script tag, every '<' escaped so draft text cannot close the tag."
144
- export async function renderReview(draft, mode) {
228
+ // @comment -- "Embed the draft as inert JSON with escaped tag delimiters. Only a local review may add verified document bodies. Shared artifacts carry the citations and excerpts already present in the draft."
229
+ export async function renderReview(review, mode) {
145
230
  const template = readFileSync(join(templatesDir(), 'review', 'review.html'), 'utf8');
146
- const art = await brandArt();
231
+ const prepared = 'schema' in review ? { draft: review, sources: [], repoUrl: undefined } : review;
232
+ const { draft, repoUrl } = prepared;
233
+ const sources = mode.kind === 'artifact' ? [] : prepared.sources;
147
234
  const heading = draft.kind !== 'intent' ? `bravos asks: ${draft.kind}` : draft.perspective === 'owner' ? 'What does this product intend?' : `How should bravos judge ${draft.repo ?? 'this project'}?`;
148
- const data = JSON.stringify({ draft, mode, heading, ...art }).replace(/</g, '\\u003c').replace(/[\u2028\u2029]/g, (c) => `\\u${c.charCodeAt(0).toString(16)}`);
235
+ const data = JSON.stringify({ draft, mode, heading, sources, repoUrl }).replace(/</g, '\\u003c').replace(/[\u2028\u2029]/g, (c) => `\\u${c.charCodeAt(0).toString(16)}`);
149
236
  const page = template.replace('__BRAVOS_DATA__', () => data);
150
237
  // On claude.ai the runtime bridge supplies the shared database, so the page drops its own CSP there.
151
238
  return mode.kind === 'artifact' ? page.replace(/<meta http-equiv="Content-Security-Policy"[^>]*>\n?/, '') : page;
@@ -166,7 +253,7 @@ export function summarize(draft, files, skipped = []) {
166
253
  if (skipped.length)
167
254
  out.push(`skipped unreadable answer files: ${skipped.join(', ')}`);
168
255
  const groups = { DISAGREE: [], EDITED: [], DECIDED: [], 'NO ANSWER': [] };
169
- const accepted = {};
256
+ const accepted = Object.create(null);
170
257
  let acceptedCount = 0;
171
258
  for (const q of draft.questions) {
172
259
  const rows = files.map((f) => ({ by: f.by, a: f.answers[q.id] })).filter((r) => !!r.a);
@@ -243,8 +330,7 @@ export function startReviewServer(root, draft, page, token, port = 0) {
243
330
  if (missing.length)
244
331
  return send(400, `these decisions still need your call: ${missing.join(', ')}`);
245
332
  const rel = `${answersDir(draft.kind)}/${slug(a.by)}.json`;
246
- mkdirSync(dirname(join(root, rel)), { recursive: true });
247
- writeFileSync(join(root, rel), JSON.stringify(a, null, 2) + '\n');
333
+ writeReviewFile(root, rel, JSON.stringify(a, null, 2) + '\n');
248
334
  send(200, JSON.stringify({ saved: rel }), 'application/json');
249
335
  }
250
336
  catch (e) {
@@ -268,7 +354,6 @@ export const newToken = () => randomBytes(16).toString('hex');
268
354
  // @comment -- "Writes the rendered page for file mode (no server) to .bravos/review/<kind>.html and returns its path."
269
355
  export function writePage(root, kind, page) {
270
356
  const rel = `.bravos/review/${checkKind(kind)}.html`;
271
- mkdirSync(dirname(join(root, rel)), { recursive: true });
272
- writeFileSync(join(root, rel), page);
357
+ writeReviewFile(root, rel, page);
273
358
  return rel;
274
359
  }
@@ -3,8 +3,10 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
3
  import { dirname, join } from 'node:path';
4
4
  export const PRESETS = {
5
5
  annotate: { label: 'Map my threats only', hint: 'annotations; nothing runs on its own', pr: 'none', autopilot: false, schedule: 'none', proving: 'none' },
6
- pr: { label: 'Map threats and check every pull request', hint: 'no AI key needed', pr: 'hook+github', autopilot: false, schedule: 'none', proving: 'ask' },
7
- everything: { label: 'Everything: annotations, PR checks and scheduled testing', hint: 'weekly nightly run, autopilot on', pr: 'hook+github', autopilot: true, schedule: 'weekly', proving: 'ask' },
6
+ // @comment -- "Autopilot is on for the pr preset in the preset itself, so bravos start --yes and the interactive default agree."
7
+ pr: { label: 'Map threats and check every pull request', hint: 'no AI key needed', pr: 'hook+github', autopilot: true, schedule: 'none', proving: 'ask' },
8
+ // @comment -- "The label says what the schedule does by default: an annotation run. Scheduled testing happens only when the person picks it at the testing question."
9
+ everything: { label: 'Everything: annotations, PR checks and a scheduled annotation run', hint: 'weekly run, autopilot on; testing is the next choice', pr: 'hook+github', autopilot: true, schedule: 'weekly', proving: 'ask' },
8
10
  };
9
11
  /** Pricing for optional CXG model generation. */
10
12
  export const PENTEST_COST_URL = 'https://bugb.io/pricing#pentest-cost';
@@ -43,10 +45,11 @@ export function provingText(a, date) {
43
45
  '',
44
46
  `choice: ${a.proving}`,
45
47
  ...(a.proving === 'auto' ? [`kits: ${a.kitPolicy ?? 'reviewed'}`] : []),
48
+ ...(a.proving === 'auto' && a.target ? [`target: ${a.target}`] : []),
46
49
  `generation: ${a.generation ? 'yes' : 'no'}`,
47
50
  '',
48
51
  // Automatic tests need the one local app they may contact; the agent finds it (bravos-env) and a person merges it.
49
- ...(a.proving === 'auto' ? ['Automatic tests start once a `target: http://localhost:<port>/` line naming your local app is added here and merged to the default branch (bravos-env does this with you).', ''] : []),
52
+ ...(a.proving === 'auto' && !a.target ? ['Automatic tests start once a `target: http://localhost:<port>/` line naming your local app is added here and merged to the default branch (bravos-env does this with you).', ''] : []),
50
53
  JSON.stringify(a.words.trim()),
51
54
  '',
52
55
  `— confirmed by ${a.name.trim()}, ${date}`,
@@ -67,7 +70,8 @@ export function readAnswers(root) {
67
70
  export function writeAnswers(root, a, version, at) {
68
71
  const p = join(root, SETUP_FILE);
69
72
  mkdirSync(dirname(p), { recursive: true });
70
- const { words: _w, name: _n, ...kept } = a;
73
+ // @comment -- "setup.json is committed for the team, so it holds only repository-level answers: never the absolute path of the first person's checkout, their terminal theme or what their machine was missing."
74
+ const { words: _w, name: _n, repo: _r, theme: _t, installTools: _i, ...kept } = a;
71
75
  writeFileSync(p, JSON.stringify({ schema: 'bravos.start/v1', bravos_version: version, at, answers: kept }, null, 2) + '\n');
72
76
  }
73
77
  /** Saves the colour theme in $BRAVOS_HOME/config.json, keeping anything else in it. */
@@ -85,3 +89,28 @@ export function writeTheme(home, theme) {
85
89
  writeFileSync(p, JSON.stringify({ ...cfg, theme }, null, 2) + '\n');
86
90
  return p;
87
91
  }
92
+ // @comment -- "Checks the optional local app URL the wizard asks for, by the same rules replay enforces for an automatic run (hooks/lib/replay.mjs): http or https, a loopback host, no credentials, query or fragment. Empty is fine: the agent finds the target later. Returns the problem in words, or undefined."
93
+ // @mitigates #replay-target against #out-of-scope-replay using #loopback-only-scope -- "A target recorded by setup can only be the person's own loopback app; replay checks it again before every run."
94
+ export function targetProblem(value) {
95
+ const v = value.trim();
96
+ if (!v)
97
+ return undefined;
98
+ let url;
99
+ try {
100
+ url = new URL(v);
101
+ }
102
+ catch {
103
+ return 'A full address, please, like http://localhost:3000';
104
+ }
105
+ if (!['http:', 'https:'].includes(url.protocol))
106
+ return 'It must start with http:// or https://';
107
+ if (!['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))
108
+ return 'Only an app on this machine: localhost, 127.0.0.1 or [::1]';
109
+ if (url.username || url.password)
110
+ return 'No user name or password in the address';
111
+ if (url.search || url.hash)
112
+ return 'No ? or # part: just where the app listens';
113
+ return undefined;
114
+ }
115
+ /** The target as replay compares it (URL.href), or undefined when none was given. */
116
+ export const normalTarget = (value) => (value?.trim() ? new URL(value.trim()).href : undefined);
@@ -1,12 +1,13 @@
1
1
  // @comment -- "bravos start: the guided first run. One question per step (theme, licence, tools, repository, agents, goal, PR checks, autopilot, schedule, testing permission, continuous pentest, the person's words and name, GitHub secrets), each step able to go back with Esc, then every change and the equivalent bravos init command, and nothing written until the person says Apply; signing in is the one step that acts when chosen. It then installs through the existing commands, records the proving choice in the person's own words, builds the code graph and reports what it found, and hands the first annotation to their own agent — bravos never starts an agent itself."
2
- import { mkdirSync, writeFileSync } from 'node:fs';
2
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
3
3
  import { join, resolve } from 'node:path';
4
4
  import { resolveTheme, THEMES } from '../palette.js';
5
5
  import { detectHarnesses } from '../detect.js';
6
6
  import { CRON } from '../ci.js';
7
- import { initArgs, nightlySecrets, PENTEST_COST_URL, PRESETS, provingText, readAnswers, writeAnswers, writeTheme, } from './answers.js';
7
+ import { initArgs, nightlySecrets, normalTarget, PRESETS, provingText, readAnswers, targetProblem, writeAnswers, writeTheme, } from './answers.js';
8
8
  import { findRepos, isGitRepo, repoHint, repoProblem, tildify } from './repos.js';
9
9
  import { Back, Cancelled } from './ui.js';
10
+ import { prefsLib } from '../prefs.js';
10
11
  const AGENTS = [
11
12
  { value: 'claude', label: 'Claude Code' },
12
13
  { value: 'codex', label: 'Codex' },
@@ -72,6 +73,11 @@ async function flow(opts, d) {
72
73
  const has = (s, f) => !!s.lic?.unlocked.includes(f);
73
74
  const missingTools = (s) => (s.items ?? []).filter((i) => (i.id === 'guardlink' || i.id === 'cxg') && (!i.present || (i.proofTool && i.proofTool.status !== 'ready')));
74
75
  const missingBundles = (s) => (s.items ?? []).filter((i) => (i.id === 'analyzer' || i.id === 'codegraph') && !i.present && i.licensed);
76
+ // @comment -- "A repository-level question is skipped when joining: those answers are the team's, already committed."
77
+ const team = (step) => async (s) => {
78
+ if (!s.join)
79
+ await step(s);
80
+ };
75
81
  const steps = [
76
82
  // theme
77
83
  async (s) => {
@@ -134,6 +140,7 @@ async function flow(opts, d) {
134
140
  if (!repo) {
135
141
  const found = findRepos(d.cwd, { home: d.home });
136
142
  const choices = [...found.map((r, i) => ({ value: r, label: tildify(r, d.home), hint: repoHint(r, d.cwd), recommended: i === 0 && r === d.cwd })), { value: '__path__', label: 'Type a path…' }];
143
+ // An older setup.json may still hold the path it was written with; newer ones never do.
137
144
  const prev = s.repoPicked ?? (saved?.repo && isGitRepo(saved.repo) ? saved.repo : undefined);
138
145
  const initial = prev && choices.some((c) => c.value === prev) ? prev : found[0] ?? '__path__';
139
146
  for (;;) {
@@ -153,9 +160,15 @@ async function flow(opts, d) {
153
160
  }
154
161
  }
155
162
  s.repo = repo;
163
+ // @comment -- "Joining: the repository already carries Bravos's files and the team's recorded setup, so a teammate (or a second machine) is asked only about this machine, and nothing the team decided is rewritten. bravos start --again is the way to change the repository's setup."
164
+ s.join = !opts.again && existsSync(join(repo, '.bravos', 'skills.lock')) && existsSync(join(repo, '.bravos', 'setup.json'));
165
+ if (s.join) {
166
+ s.agents = readAnswers(repo)?.agents ?? s.agents;
167
+ p.info('Bravos is already set up in this repository, so only this machine is set up now; the team\'s choices stay as they are. To change them: bravos start --again');
168
+ }
156
169
  },
157
170
  // agents
158
- async (s) => {
171
+ team(async (s) => {
159
172
  const det = detectHarnesses(s.repo);
160
173
  const seen = new Set([
161
174
  ...(det.harnesses.includes('claude') && !det.defaulted ? ['claude'] : []),
@@ -166,17 +179,17 @@ async function flow(opts, d) {
166
179
  ]);
167
180
  const agents = await p.multiselect('agents', 'Which AI coding tools do you use here?', AGENTS.map((a) => ({ ...a, hint: seen.has(a.value) ? 'found on this machine' : undefined })), s.agents ?? saved?.agents ?? (seen.size ? [...seen] : ['claude']));
168
181
  s.agents = agents.length ? agents : ['claude'];
169
- },
182
+ }),
170
183
  // goal
171
- async (s) => {
184
+ team(async (s) => {
172
185
  if (opts.preset) {
173
186
  s.preset = opts.preset;
174
187
  return;
175
188
  }
176
189
  s.preset = await p.select('preset', 'What should Bravos do for you? (you can change each part next)', Object.keys(PRESETS).map((k) => ({ value: k, label: PRESETS[k].label, hint: PRESETS[k].hint, recommended: k === 'pr' })), s.preset ?? saved?.preset ?? 'pr');
177
- },
190
+ }),
178
191
  // pull requests
179
- async (s) => {
192
+ team(async (s) => {
180
193
  const prChoices = [
181
194
  { value: 'none', label: 'Nothing' },
182
195
  ...(has(s, 'pre-pr') ? [{ value: 'hook', label: 'Check before a PR is opened', hint: 'your agent\'s gh pr create waits for annotations' }] : []),
@@ -189,17 +202,17 @@ async function flow(opts, d) {
189
202
  }
190
203
  const want = s.pr ?? saved?.pr ?? PRESETS[s.preset].pr;
191
204
  s.pr = await p.select('pr', 'When someone opens a pull request:', prChoices, prChoices.some((c) => c.value === want) ? want : 'none');
192
- },
205
+ }),
193
206
  // autopilot
194
- async (s) => {
207
+ team(async (s) => {
195
208
  if (!has(s, 'pre-pr') || s.preset === 'annotate') {
196
209
  s.autopilot = false;
197
210
  return;
198
211
  }
199
- s.autopilot = await p.confirm('autopilot', 'Review changed code at the end of each agent turn? Autopilot asks the agent to update relevant claims and follows your testing preference.', s.autopilot ?? saved?.autopilot ?? (s.preset === 'pr' && !opts.yes ? true : PRESETS[s.preset].autopilot));
200
- },
212
+ s.autopilot = await p.confirm('autopilot', 'Review changed code at the end of each agent turn? Autopilot asks the agent to update relevant claims and follows your testing preference.', s.autopilot ?? saved?.autopilot ?? PRESETS[s.preset].autopilot);
213
+ }),
201
214
  // scheduled run (GitHub Actions)
202
- async (s) => {
215
+ team(async (s) => {
203
216
  s.nightlyAgent = s.agents.includes('codex') && !s.agents.includes('claude') ? 'codex' : 'claude';
204
217
  if (!has(s, 'ci')) {
205
218
  p.info('Scheduled runs are on the Team plan.');
@@ -213,9 +226,9 @@ async function flow(opts, d) {
213
226
  { value: 'weekday', label: 'Every weekday night' },
214
227
  { value: 'daily', label: 'Every night' },
215
228
  ], s.schedule ?? saved?.schedule ?? PRESETS[s.preset].schedule);
216
- },
229
+ }),
217
230
  // which agent runs on the schedule
218
- async (s) => {
231
+ team(async (s) => {
219
232
  if (s.schedule === 'none' || opts.yes)
220
233
  return;
221
234
  const usual = s.nightlyAgent ?? 'claude';
@@ -224,9 +237,9 @@ async function flow(opts, d) {
224
237
  { value: 'copilot', label: 'GitHub Copilot', hint: 'runs on your Copilot plan; Copilot opens the pull request' },
225
238
  { value: 'codex', label: 'Codex', hint: 'needs an OpenAI API key', recommended: usual === 'codex' },
226
239
  ], saved?.nightlyAgent ?? usual);
227
- },
240
+ }),
228
241
  // testing permission
229
- async (s) => {
242
+ team(async (s) => {
230
243
  if (opts.yes) {
231
244
  s.proving = 'none';
232
245
  return;
@@ -253,33 +266,48 @@ async function flow(opts, d) {
253
266
  const choice = await p.select('proving', 'How should Bravos handle testing?', choices, choices.some((c) => c.value === want) ? want : 'ask');
254
267
  s.proving = choice === 'auto-reviewed' ? 'auto' : choice;
255
268
  s.kitPolicy = choice === 'auto-reviewed' ? 'reviewed' : 'session';
256
- },
257
- // Optional external generation is separate from replaying harness-authored tests.
258
- async (s) => {
259
- if (s.proving === 'none') {
260
- s.generation = false;
269
+ }),
270
+ // where the app runs locally: optional, and only for automatic testing
271
+ // @comment -- "With automatic testing chosen, the person may say where their own app listens. It is checked by the rules replay enforces and written into proving.md, so the policy needs one merge and not a second one just to add the target. Empty is a fine answer: the agent finds it later (bravos-env). The model-API generation question that stood here is gone: Bravos never uses cxg's model generation, so there was nothing a yes could turn on."
272
+ team(async (s) => {
273
+ s.generation = false;
274
+ if (s.proving !== 'auto') {
275
+ s.target = undefined;
261
276
  return;
262
277
  }
263
- p.info(`Your coding agent can write tests in this session. Optional CXG model generation spends additional credits. See ${PENTEST_COST_URL}`);
264
- s.generation = await p.confirm('generation', 'Allow CXG to generate additional probes through a paid model API?', s.generation ?? saved?.generation ?? false, { yes: 'Allow model API spend', no: 'Use the current agent and supplied tests', recommend: false });
265
- },
278
+ const typed = await p.text('target', 'Where does your app run locally? (leave empty and your agent finds it)', { initial: s.target ?? saved?.target ?? '', placeholder: 'http://localhost:3000', validate: targetProblem });
279
+ s.target = normalTarget(typed);
280
+ }),
266
281
  // the person's own words
267
- async (s) => {
282
+ team(async (s) => {
268
283
  if (s.proving !== 'auto' && s.proving !== 'schedule')
269
284
  return;
270
285
  s.words = await p.text('words', 'In your own words: what may Bravos test without asking? (recorded as your authorization)', { initial: s.words, validate: (v) => (v.trim().length >= 10 ? undefined : 'Write a sentence in your own words.') });
271
- },
286
+ }),
272
287
  // who confirmed it
273
- async (s) => {
288
+ team(async (s) => {
274
289
  if (opts.yes) {
275
290
  s.name = '';
276
291
  return;
277
292
  }
278
293
  const gitName = s.name || d.exec('git', ['config', 'user.name'], { cwd: s.repo }).out.trim();
279
294
  s.name = await p.text('name', 'Your name, recorded with this choice', { initial: gitName || undefined, validate: (v) => (v.trim() ? undefined : 'Your name, please.') });
295
+ }),
296
+ // commits: asked of every person, joining or not, because the answer is theirs and stays in their clone
297
+ // @comment -- "The one question the agent used to ask at the start of every session: what to do with the files Bravos writes. Asked once here and recorded for this person in this clone (bravos prefs), so sessions follow it without asking. --yes records nothing: a person has to answer it."
298
+ async (s) => {
299
+ if (opts.yes) {
300
+ s.commits = undefined;
301
+ return;
302
+ }
303
+ s.commits = await p.select('commits', 'When Bravos writes its own files (annotations, intent, tests), should your agent commit them?', [
304
+ { value: 'commit', label: 'Yes, commit them', hint: 'never your own code; change it any time with bravos prefs', recommended: true },
305
+ { value: 'leave', label: 'No, leave them for me', hint: 'the agent lists what it wrote' },
306
+ { value: 'ask', label: 'Ask me each session' },
307
+ ], s.commits ?? 'commit');
280
308
  },
281
309
  // GitHub secrets for the scheduled run: held in memory until Apply, never written to a file.
282
- async (s) => {
310
+ team(async (s) => {
283
311
  s.secrets = {};
284
312
  const needed = nightlySecrets({ schedule: s.schedule, nightlyAgent: s.nightlyAgent });
285
313
  if (!needed.length)
@@ -313,7 +341,7 @@ async function flow(opts, d) {
313
341
  if (v.trim())
314
342
  s.secrets[n] = v.trim();
315
343
  }
316
- },
344
+ }),
317
345
  ];
318
346
  // Run the steps. Esc in a step returns to the last step that asked something.
319
347
  const s = { secrets: {} };
@@ -341,18 +369,22 @@ async function flow(opts, d) {
341
369
  const changes = [
342
370
  `Colours: ${answers.theme} (saved in ${tildify(join(d.home, 'config.json'), d.env.HOME)})`,
343
371
  ...(answers.installTools ? [`Install: ${[...missingTools(s), ...missingBundles(s)].map((i) => i.id).join(', ')}`] : []),
372
+ ...(s.commits ? [`Commits: ${{ commit: 'your agent commits Bravos\'s own files without asking', leave: 'your agent leaves Bravos\'s files for you', ask: 'your agent asks each session' }[s.commits]} (your answer, kept in this clone only)`] : []),
344
373
  `In ${tildify(answers.repo, d.env.HOME)}:`,
345
- ` + skills, hooks and MCP for ${answers.agents.join(', ')}`,
346
- ' + .guardlink/ threat model (guardlink init, if not there yet)',
347
- ...(answers.pr !== 'none' ? [' + pre-PR check'] : []),
348
- ...(answers.pr === 'hook+github' ? [' + .github/workflows/bravos-pr-gate.yml'] : []),
349
- ...(answers.autopilot ? [' + autopilot'] : []),
350
- ...(answers.schedule !== 'none' ? [` + .github/workflows/bravos-nightly-${answers.nightlyAgent}.yml (${answers.schedule}, cron ${CRON[answers.schedule]} UTC)`] : []),
351
- ...(answers.schedule !== 'none' && answers.nightlyAgent === 'copilot' ? [' + .github/workflows/copilot-setup-steps.yml (prepares Copilot\'s session: Node and guardlink)'] : []),
352
- ...(answers.proving !== 'none' ? [' + .guardlink/scope.yaml (localhost only; authorization left for you)'] : []),
353
- ...(answers.name ? [` + .guardlink/proving.md (${answers.proving}${answers.generation ? ', model API generation allowed' : ''}, confirmed by ${answers.name})`] : []),
354
- ...(Object.keys(s.secrets).length ? [` + GitHub secrets: ${Object.keys(s.secrets).join(', ')}`] : []),
355
- ' + .bravos/setup.json (your answers, for bravos start --again)',
374
+ ...(s.join ? [' ~ skills, hooks and MCP brought up to date for this machine (bravos sync)', ' = the team\'s setup, testing permission and workflows stay as they are'] : []),
375
+ ...(s.join ? [] : [
376
+ ` + skills, hooks and MCP for ${answers.agents.join(', ')}`,
377
+ ' + .guardlink/ threat model (guardlink init, if not there yet)',
378
+ ...(answers.pr !== 'none' ? [' + pre-PR check'] : []),
379
+ ...(answers.pr === 'hook+github' ? [' + .github/workflows/bravos-pr-gate.yml'] : []),
380
+ ...(answers.autopilot ? [' + autopilot'] : []),
381
+ ...(answers.schedule !== 'none' ? [` + .github/workflows/bravos-nightly-${answers.nightlyAgent}.yml (${answers.schedule}, cron ${CRON[answers.schedule]} UTC)`] : []),
382
+ ...(answers.schedule !== 'none' && answers.nightlyAgent === 'copilot' ? [' + .github/workflows/copilot-setup-steps.yml (prepares Copilot\'s session: Node and guardlink)'] : []),
383
+ ...(answers.proving !== 'none' ? [' + .guardlink/scope.yaml (localhost only; authorization left for you)'] : []),
384
+ ...(answers.name ? [` + .guardlink/proving.md (${answers.proving}${answers.target ? ` on ${answers.target}` : ''}, confirmed by ${answers.name})`] : []),
385
+ ...(Object.keys(s.secrets).length ? [` + GitHub secrets: ${Object.keys(s.secrets).join(', ')}`] : []),
386
+ ' + .bravos/setup.json (your answers, for bravos start --again)',
387
+ ]),
356
388
  ...(has(s, 'codegraph') ? ['Then: build the code graph for this repository'] : []),
357
389
  ];
358
390
  p.note(changes.join('\n'), 'About to make these changes');
@@ -380,12 +412,12 @@ async function flow(opts, d) {
380
412
  p.note([
381
413
  ...(answers.installTools && missingTools(s).length ? ['bravos setup --tools -y'] : []),
382
414
  ...(answers.installTools && missingBundles(s).length ? ['bravos setup'] : []),
383
- `bravos ${initArgs(answers).map((x) => (/\s/.test(x) ? JSON.stringify(x) : x)).join(' ')}`,
415
+ s.join ? `bravos sync ${JSON.stringify(answers.repo)}` : `bravos ${initArgs(answers).map((x) => (/\s/.test(x) ? JSON.stringify(x) : x)).join(' ')}`,
384
416
  ...Object.keys(s.secrets).map((n) => `gh secret set ${n} (value from your paste)`),
385
417
  ...(has(s, 'codegraph') ? [`bravos graph build ${JSON.stringify(answers.repo)} --scip no-exec`] : []),
386
418
  ].join('\n'), 'Commands');
387
419
  }
388
- return apply(toAnswers(s), s, d, opts, { missingTools: missingTools(s).length > 0, missingBundles: missingBundles(s).length > 0, codegraph: has(s, 'codegraph') });
420
+ return apply(toAnswers(s), s, d, opts, { missingTools: missingTools(s).length > 0, missingBundles: missingBundles(s).length > 0, codegraph: has(s, 'codegraph'), join: !!s.join, commits: s.commits });
389
421
  }
390
422
  function toAnswers(s) {
391
423
  return {
@@ -400,7 +432,8 @@ function toAnswers(s) {
400
432
  nightlyAgent: s.nightlyAgent ?? 'claude',
401
433
  proving: s.proving ?? 'none',
402
434
  ...(s.proving === 'auto' ? { kitPolicy: s.kitPolicy } : {}),
403
- generation: !!s.generation,
435
+ generation: false,
436
+ ...(s.proving === 'auto' && s.target ? { target: s.target } : {}),
404
437
  words: s.proving === 'auto' || s.proving === 'schedule' ? (s.words ?? '') : '',
405
438
  name: s.name ?? '',
406
439
  };
@@ -423,19 +456,37 @@ async function apply(answers, s, d, opts, has) {
423
456
  for (const l of [...r.out, ...r.err])
424
457
  (r.code ? p.warn : p.info)(l);
425
458
  }
426
- const init = await p.spin('Setting up the repository', () => d.bravos(initArgs(answers)), (r) => (r.code ? { fail: 'Setting up the repository — failed' } : 'Repository set up'));
459
+ // @comment -- "Joining runs bravos sync, which re-applies what the repository already has and never rewrites the team's choices; a first setup runs bravos init with the flags the answers amount to."
460
+ const init = has.join
461
+ ? await p.spin('Bringing this machine up to date with the repository', () => d.bravos(['sync', repo]), (r) => (r.code ? { fail: 'Syncing the repository — failed' } : 'Repository in sync'))
462
+ : await p.spin('Setting up the repository', () => d.bravos(initArgs(answers)), (r) => (r.code ? { fail: 'Setting up the repository — failed' } : 'Repository set up'));
427
463
  for (const l of init.out)
428
464
  p.info(l);
429
465
  if (init.code !== 0) {
430
466
  for (const l of init.err)
431
467
  p.warn(l);
432
- p.outro('Setup stopped: bravos init did not finish. Fix the line above and run bravos start --again.');
468
+ p.outro(has.join ? 'Setup stopped: bravos sync did not finish. Fix the line above and run bravos start again.' : 'Setup stopped: bravos init did not finish. Fix the line above and run bravos start --again.');
433
469
  return init.code;
434
470
  }
435
- if (answers.name) {
471
+ // Joining never writes the team's proving.md or setup.json: both are theirs, already committed.
472
+ if (answers.name && !has.join) {
436
473
  mkdirSync(join(repo, '.guardlink'), { recursive: true });
437
474
  writeFileSync(join(repo, '.guardlink', 'proving.md'), provingText({ ...answers, words: answers.words || provingLabel(answers.proving) }, d.today()));
438
475
  }
476
+ if (has.commits) {
477
+ // The answer carries the name of the person at this terminal: the one they gave above, else git's.
478
+ const by = answers.name || d.exec('git', ['config', 'user.name'], { cwd: repo }).out.trim();
479
+ const later = `bravos prefs set commits ${has.commits} --by "<your name>"`;
480
+ if (!by)
481
+ p.warn(`Your answer about commits was not recorded (no name to record it under). Later: ${later}`);
482
+ else {
483
+ const r = await d.bravos(['prefs', 'set', 'commits', has.commits, '--by', by, '-C', repo]);
484
+ if (r.code)
485
+ p.warn(`Your answer about commits was not recorded: ${r.err[0] ?? 'bravos prefs failed'}. Later: ${later}`);
486
+ else
487
+ p.info(r.out[0]);
488
+ }
489
+ }
439
490
  for (const [n, v] of Object.entries(s.secrets)) {
440
491
  const r = d.exec('gh', ['secret', 'set', n], { input: v, cwd: repo });
441
492
  (r.code ? p.warn : p.info)(r.code ? `gh secret set ${n} failed — add it in the repository's Settings → Secrets` : `secret ${n} set`);
@@ -446,26 +497,56 @@ async function apply(answers, s, d, opts, has) {
446
497
  for (const n of sum.notes)
447
498
  (sum.ok ? p.info : p.warn)(n);
448
499
  }
449
- writeAnswers(repo, answers, d.version, new Date().toISOString());
500
+ if (!has.join)
501
+ writeAnswers(repo, answers, d.version, new Date().toISOString());
450
502
  // hand-off
451
503
  const next = await d.bravos(['next', repo]);
452
504
  if (next.out.length)
453
505
  p.note(next.out.slice(0, 12).join('\n'), 'Setup score');
454
506
  const lead = agents.includes('claude') ? 'claude' : agents[0];
455
507
  const tool = AGENTS.find((a) => a.value === lead)?.label ?? 'your agent';
508
+ if (has.join) {
509
+ // Joining: the context and the annotations are already the team's; there is nothing to type first.
510
+ p.note([`Open ${tool} in ${tildify(repo, d.env.HOME)}: the Bravos banner shows where the team's threat model stands and the next step.`, 'Follow along in a second terminal: bravos watch'].join('\n'), 'Ready');
511
+ p.outro('This machine is set up for the repository.');
512
+ return 0;
513
+ }
456
514
  const handoff = `${sigil(lead)}bravos-context`;
457
515
  // A scripted run (--yes) leaves the person's clipboard alone.
458
516
  const copied = opts.yes ? false : d.clipboard(handoff);
459
- p.note([
460
- `Open ${tool} in ${tildify(repo, d.env.HOME)} and type:`,
461
- '',
462
- ` ${handoff} learns what the app is for (asks you a few questions)`,
463
- ` ${sigil(lead)}bravos-annotate maps the threats in your code`,
464
- '',
465
- 'Autopilot can review later changes in your agent. Live testing follows the preference and target you authorized.',
466
- copied ? `(${handoff} is on your clipboard.) The Bravos banner shows the next step each time you open a session.` : 'The Bravos banner shows the next step each time you open a session.',
467
- 'Follow along in a second terminal: bravos watch',
468
- ].join('\n'), 'One step left, in your agent');
517
+ // @comment -- "The hand-off: a dated marker in this clone's git directory tells the next agent session that setup just finished, so the briefing has the agent begin the context step itself and the person types no skill name. Harnesses that run the session hook (Claude Code, Codex, Antigravity) get that; the others are still told what to type. A marker that cannot be written only means the person types the command."
518
+ let begins = false;
519
+ if (['claude', 'codex', 'agy'].includes(lead)) {
520
+ try {
521
+ const L = await prefsLib();
522
+ begins = !!L.writeHandoff(L.gitCommonDir(repo, d.env), new Date().toISOString());
523
+ }
524
+ catch {
525
+ begins = false;
526
+ }
527
+ }
528
+ const banner = 'The Bravos banner shows the next step each time you open a session.';
529
+ p.note((begins
530
+ ? [
531
+ `Open ${tool} in ${tildify(repo, d.env.HOME)} and say anything, for example "let's start".`,
532
+ '',
533
+ ' Bravos begins by learning what the app is for: it asks for your design documents,',
534
+ ' then opens a page for you to confirm. After that it maps the threats in your code.',
535
+ '',
536
+ 'Autopilot can review later changes in your agent. Live testing follows the preference and target you authorized.',
537
+ copied ? `If it does not begin by itself, type ${handoff} (it is on your clipboard). ${banner}` : `If it does not begin by itself, type ${handoff}. ${banner}`,
538
+ 'Follow along in a second terminal: bravos watch',
539
+ ]
540
+ : [
541
+ `Open ${tool} in ${tildify(repo, d.env.HOME)} and type:`,
542
+ '',
543
+ ` ${handoff} learns what the app is for (asks you a few questions)`,
544
+ ` ${sigil(lead)}bravos-annotate maps the threats in your code`,
545
+ '',
546
+ 'Autopilot can review later changes in your agent. Live testing follows the preference and target you authorized.',
547
+ copied ? `(${handoff} is on your clipboard.) ${banner}` : banner,
548
+ 'Follow along in a second terminal: bravos watch',
549
+ ]).join('\n'), 'One step left, in your agent');
469
550
  if (opts.yes && !answers.name)
470
551
  p.info('Testing permission was not recorded (a person has to answer it): run bravos start --again in a terminal.');
471
552
  p.outro('Bravos is set up.');