@bugb-technologies/bravos 1.1.0 → 1.2.1

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.
@@ -0,0 +1,454 @@
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';
3
+ import { join, resolve } from 'node:path';
4
+ import { resolveTheme, THEMES } from '../palette.js';
5
+ import { detectHarnesses } from '../detect.js';
6
+ import { CRON } from '../ci.js';
7
+ import { initArgs, nightlySecrets, PENTEST_COST_URL, PRESETS, provingText, readAnswers, writeAnswers, writeTheme, } from './answers.js';
8
+ import { findRepos, isGitRepo, repoHint, repoProblem, tildify } from './repos.js';
9
+ import { Back, Cancelled } from './ui.js';
10
+ const AGENTS = [
11
+ { value: 'claude', label: 'Claude Code' },
12
+ { value: 'codex', label: 'Codex' },
13
+ { value: 'opencode', label: 'opencode' },
14
+ { value: 'omp', label: 'oh-my-pi (omp)' },
15
+ { value: 'agy', label: 'Antigravity' },
16
+ ];
17
+ const sigil = (a) => (a === 'codex' ? '$' : '/');
18
+ /** A line drawn in each theme, so the person can see which reads well on their screen. */
19
+ function themeSample() {
20
+ const swatch = (t) => {
21
+ const p = THEMES[t];
22
+ const fg = (hex, s) => (hex ? `\x1b[38;2;${parseInt(hex.slice(1, 3), 16)};${parseInt(hex.slice(3, 5), 16)};${parseInt(hex.slice(5, 7), 16)}m${s}\x1b[0m` : s);
23
+ return `${t.padEnd(8)} ${fg(p.green, '■ bravos')} ${fg(p.light, 'Top threats')} ${fg(p.red, 'high')} ${fg(p.amber, 'medium')} ${fg(p.steel, 'low')}`;
24
+ };
25
+ return ['dark', 'light', 'neutral'].map(swatch).join('\n');
26
+ }
27
+ // @comment -- "The one-line result of bravos graph build --json: files and languages indexed, annotations linked, and any language whose calls could not be resolved with the fix the builder gave. Never throws: an unreadable answer says so."
28
+ export function graphSummary(r) {
29
+ if (r.code !== 0) {
30
+ const why = (r.err || r.out).split('\n').map((l) => l.trim()).find((l) => l && !l.startsWith('{')) ?? `exit ${r.code}`;
31
+ return { ok: false, line: 'Code graph did not build', notes: [why, 'Your agent can build it later: ask it to "build the code graph".'] };
32
+ }
33
+ try {
34
+ const j = JSON.parse(r.out.slice(r.out.indexOf('{')));
35
+ const langs = j?.semantic?.languages ?? [];
36
+ const files = langs.reduce((n, l) => n + (l.files ?? 0), 0) || j.files || 0;
37
+ const names = langs.map((l) => l.language).join(', ');
38
+ const line = `Code graph ${j.was_built === false ? 'up to date' : 'built'}: ${files ? `${files} file${files === 1 ? '' : 's'}` : 'indexed'}${names ? ` (${names})` : ''}${j.annotations ? `, ${j.annotations} annotations linked` : ''}`;
39
+ const notes = langs.filter((l) => l.resolved === false).map((l) => `${l.language}: calls not fully resolved (${(l.status ?? 'unresolved').replace(/_/g, ' ')})${l.fix ? ` — fix: ${l.fix}` : ''}`);
40
+ return { ok: true, line, notes };
41
+ }
42
+ catch {
43
+ return { ok: true, line: 'Code graph built', notes: [] };
44
+ }
45
+ }
46
+ // @comment -- "Runs the steps; returns the exit code. A Cancelled (Ctrl-C, or Cancel at the review) at any step before Apply writes nothing and exits 1."
47
+ export async function runStart(opts, d) {
48
+ const p = d.prompter;
49
+ try {
50
+ return await flow(opts, d);
51
+ }
52
+ catch (e) {
53
+ if (e instanceof Cancelled) {
54
+ p.outro(e.message);
55
+ return 1;
56
+ }
57
+ throw e;
58
+ }
59
+ }
60
+ async function flow(opts, d) {
61
+ const p = d.prompter;
62
+ const saved = opts.again ? readAnswers(opts.dir ? resolve(opts.dir) : d.cwd) : null;
63
+ p.intro(`Bravos ${d.version} setup`);
64
+ p.info('About five minutes. Esc goes back a step, Ctrl-C quits. Signing in happens when you choose it; everything else waits for your OK at the end.');
65
+ const major = Number(process.versions.node.split('.')[0]);
66
+ if (major < 20)
67
+ p.warn(`Node ${process.versions.node} is older than Bravos needs (20 or newer). Update Node first.`);
68
+ const shadow = d.which('bravos');
69
+ if (shadow && /\.local\/bin\/bravos$|site-packages|pipx/.test(shadow)) {
70
+ p.warn(`The old Python bravos at ${shadow} may run instead of this one. Rename it: mv ${shadow} ${shadow}-py`);
71
+ }
72
+ const has = (s, f) => !!s.lic?.unlocked.includes(f);
73
+ const missingTools = (s) => (s.items ?? []).filter((i) => (i.id === 'guardlink' || i.id === 'cxg') && !i.present);
74
+ const missingBundles = (s) => (s.items ?? []).filter((i) => (i.id === 'analyzer' || i.id === 'codegraph') && !i.present && i.licensed);
75
+ const steps = [
76
+ // theme
77
+ async (s) => {
78
+ p.note(themeSample(), 'Colours');
79
+ const detected = resolveTheme(d.env);
80
+ const initial = s.theme ?? saved?.theme ?? detected.theme;
81
+ s.theme = await p.select('theme', 'How does your terminal look?', [
82
+ { value: 'dark', label: 'Dark background', recommended: detected.source !== 'default' && detected.theme === 'dark' },
83
+ { value: 'light', label: 'Light background', recommended: detected.source !== 'default' && detected.theme === 'light' },
84
+ { value: 'neutral', label: 'Not sure / it changes', hint: 'readable on both', recommended: detected.source === 'default' || detected.theme === 'neutral' },
85
+ ], initial);
86
+ },
87
+ // licence
88
+ async (s) => {
89
+ s.lic = await d.licence();
90
+ if (!s.lic.licensed && !opts.yes) {
91
+ const how = await p.select('licence', 'No Bravos licence on this machine yet.', [
92
+ { value: 'activate', label: 'Sign in now', hint: 'activate your licence, or start the free 30-day Team trial', recommended: true },
93
+ { value: 'skip', label: 'Continue on the free plan', hint: 'annotations only; PR checks and schedules need Team' },
94
+ ], 'activate');
95
+ if (how === 'activate') {
96
+ try {
97
+ for (const l of await d.activate())
98
+ p.info(l);
99
+ }
100
+ catch (e) {
101
+ p.warn(`Sign-in did not finish: ${e instanceof Error ? e.message : String(e)}. Continuing on the free plan; run bravos account activate later.`);
102
+ }
103
+ s.lic = await d.licence();
104
+ }
105
+ }
106
+ const lic = s.lic;
107
+ const tier = lic.tier ? lic.tier[0].toUpperCase() + lic.tier.slice(1) : 'Team';
108
+ p.info(lic.licensed ? `Licence: ${tier}${lic.seats ? `, ${lic.seats} seat${lic.seats === 1 ? '' : 's'}` : ''}${lic.trial ? ' (trial)' : ''}` : 'Licence: free plan');
109
+ },
110
+ // tools
111
+ async (s) => {
112
+ s.items = (await d.setupPlan()).items;
113
+ p.note(s.items.map((i) => `${i.present ? '✔' : '✗'} ${i.id.padEnd(10)} ${i.present ? 'installed' : i.licensed === false ? 'Team plan' : `missing — ${i.action}`}`).join('\n'), 'Tools');
114
+ const missing = [...missingTools(s), ...missingBundles(s)];
115
+ s.installTools = false;
116
+ if (!missing.length)
117
+ return;
118
+ if (missingTools(s).some((i) => i.id === 'cxg') && !d.which('cargo')) {
119
+ p.warn('cxg (the test engine) installs with Rust\'s cargo, which is not here. Install Rust first: curl --proto \'=https\' --tlsv1.2 -sSf https://sh.rustup.rs | sh — or skip cxg for now; annotations work without it.');
120
+ }
121
+ s.installTools = await p.confirm('tools', `Install ${missing.map((i) => i.id).join(', ')} when you apply?`, s.installTools ?? true);
122
+ },
123
+ // repository
124
+ async (s) => {
125
+ let repo = opts.dir ? resolve(opts.dir) : '';
126
+ if (repo && repoProblem(repo)) {
127
+ p.warn(`${tildify(repo)}: ${repoProblem(repo)}`);
128
+ repo = '';
129
+ }
130
+ if (!repo) {
131
+ const found = findRepos(d.cwd, { home: d.home });
132
+ 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…' }];
133
+ const prev = s.repoPicked ?? (saved?.repo && isGitRepo(saved.repo) ? saved.repo : undefined);
134
+ const initial = prev && choices.some((c) => c.value === prev) ? prev : found[0] ?? '__path__';
135
+ for (;;) {
136
+ s.repoPicked = await p.select('repo', 'Which repository do you want to secure?', choices, s.repoPicked ?? initial);
137
+ repo = s.repoPicked;
138
+ if (repo !== '__path__')
139
+ break;
140
+ try {
141
+ const typed = await p.text('repo-path', 'Path to the repository', { placeholder: '~/code/my-app', validate: (v) => repoProblem(resolve(v.replace(/^~(?=$|\/)/, d.home))) });
142
+ repo = resolve(typed.replace(/^~(?=$|\/)/, d.home));
143
+ break;
144
+ }
145
+ catch (e) {
146
+ if (!(e instanceof Back))
147
+ throw e; // Esc on the path: back to the list
148
+ }
149
+ }
150
+ }
151
+ s.repo = repo;
152
+ },
153
+ // agents
154
+ async (s) => {
155
+ const det = detectHarnesses(s.repo);
156
+ const seen = new Set([
157
+ ...(det.harnesses.includes('claude') && !det.defaulted ? ['claude'] : []),
158
+ ...(det.harnesses.includes('agents') && !det.defaulted ? ['codex'] : []),
159
+ ...(d.which('claude') ? ['claude'] : []),
160
+ ...(d.which('codex') ? ['codex'] : []),
161
+ ...(d.which('opencode') ? ['opencode'] : []),
162
+ ]);
163
+ 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']));
164
+ s.agents = agents.length ? agents : ['claude'];
165
+ },
166
+ // goal
167
+ async (s) => {
168
+ if (opts.preset) {
169
+ s.preset = opts.preset;
170
+ return;
171
+ }
172
+ 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');
173
+ },
174
+ // pull requests
175
+ async (s) => {
176
+ const prChoices = [
177
+ { value: 'none', label: 'Nothing' },
178
+ ...(has(s, 'pre-pr') ? [{ value: 'hook', label: 'Check before a PR is opened', hint: 'your agent\'s gh pr create waits for annotations' }] : []),
179
+ ...(has(s, 'pre-pr') && has(s, 'ci') ? [{ value: 'hook+github', label: 'Also check every PR in GitHub', hint: 'a workflow; no AI, no API key', recommended: true }] : []),
180
+ ];
181
+ if (!has(s, 'pre-pr')) {
182
+ p.info('PR checks are on the Team plan (bravos account activate starts a trial).');
183
+ s.pr = 'none';
184
+ return;
185
+ }
186
+ const want = s.pr ?? saved?.pr ?? PRESETS[s.preset].pr;
187
+ s.pr = await p.select('pr', 'When someone opens a pull request:', prChoices, prChoices.some((c) => c.value === want) ? want : 'none');
188
+ },
189
+ // autopilot
190
+ async (s) => {
191
+ if (!has(s, 'pre-pr') || s.preset === 'annotate') {
192
+ s.autopilot = false;
193
+ return;
194
+ }
195
+ s.autopilot = await p.confirm('autopilot', 'Turn on autopilot? At the end of each agent turn it sends the agent back once if changed code lacks annotations.', s.autopilot ?? saved?.autopilot ?? PRESETS[s.preset].autopilot);
196
+ },
197
+ // scheduled run (GitHub Actions)
198
+ async (s) => {
199
+ s.nightlyAgent = s.agents.includes('codex') && !s.agents.includes('claude') ? 'codex' : 'claude';
200
+ if (!has(s, 'ci')) {
201
+ p.info('Scheduled runs are on the Team plan.');
202
+ s.schedule = 'none';
203
+ return;
204
+ }
205
+ p.info('A scheduled run has an agent annotate what changed, on GitHub. Claude Code signs in there with your Claude plan and GitHub Copilot uses your Copilot plan, like a session would; Codex needs an OpenAI API key. The PR check uses no AI.');
206
+ s.schedule = await p.select('schedule', 'Run Bravos on a schedule in GitHub Actions?', [
207
+ { value: 'none', label: 'No schedule', hint: 'no sign-in needed' },
208
+ { value: 'weekly', label: 'Once a week', hint: 'Sunday night; the cheapest', recommended: true },
209
+ { value: 'weekday', label: 'Every weekday night' },
210
+ { value: 'daily', label: 'Every night' },
211
+ ], s.schedule ?? saved?.schedule ?? PRESETS[s.preset].schedule);
212
+ },
213
+ // which agent runs on the schedule
214
+ async (s) => {
215
+ if (s.schedule === 'none' || opts.yes)
216
+ return;
217
+ const usual = s.nightlyAgent ?? 'claude';
218
+ s.nightlyAgent = await p.select('nightly-agent', 'Which agent should the scheduled run use?', [
219
+ { value: 'claude', label: 'Claude Code', hint: 'runs on your Claude plan', recommended: usual === 'claude' },
220
+ { value: 'copilot', label: 'GitHub Copilot', hint: 'runs on your Copilot plan; Copilot opens the pull request' },
221
+ { value: 'codex', label: 'Codex', hint: 'needs an OpenAI API key', recommended: usual === 'codex' },
222
+ ], saved?.nightlyAgent ?? usual);
223
+ },
224
+ // testing permission
225
+ async (s) => {
226
+ if (opts.yes) {
227
+ s.proving = 'none';
228
+ return;
229
+ }
230
+ const choices = [
231
+ { value: 'ask', label: 'Ask me every time before testing', recommended: true },
232
+ { value: 'auto', label: 'Test my local app automatically', hint: 'localhost only' },
233
+ ...(s.schedule !== 'none' ? [{ value: 'schedule', label: 'Only in the scheduled run' }] : []),
234
+ { value: 'none', label: 'Never test, just annotate' },
235
+ ];
236
+ p.info('Bravos only tests apps you own, on localhost; your agent finds how to start the app when it tests. Anything else needs a reviewed scope file and your own typed authorization at that time; setup never fills that in.');
237
+ const want = s.proving ?? saved?.proving ?? PRESETS[s.preset].proving;
238
+ s.proving = await p.select('proving', 'How should Bravos handle testing?', choices, choices.some((c) => c.value === want) ? want : 'ask');
239
+ },
240
+ // continuous pentest (model-written tests; spends credits)
241
+ async (s) => {
242
+ if (s.proving === 'none') {
243
+ s.generation = false;
244
+ return;
245
+ }
246
+ p.info(`This will cost additional credits: an AI model writes new tests for new code as you build. What one pentest costs: ${PENTEST_COST_URL}`);
247
+ s.generation = await p.confirm('generation', 'May Bravos continuously pentest your application as you build it?', s.generation ?? saved?.generation ?? false, { yes: 'Yes, keep testing as I build', no: 'No, only replay tests I approved', recommend: false });
248
+ },
249
+ // the person's own words
250
+ async (s) => {
251
+ if (s.proving !== 'auto' && s.proving !== 'schedule')
252
+ return;
253
+ 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.') });
254
+ },
255
+ // who confirmed it
256
+ async (s) => {
257
+ if (opts.yes) {
258
+ s.name = '';
259
+ return;
260
+ }
261
+ const gitName = s.name || d.exec('git', ['config', 'user.name'], { cwd: s.repo }).out.trim();
262
+ s.name = await p.text('name', 'Your name, recorded with this choice', { initial: gitName || undefined, validate: (v) => (v.trim() ? undefined : 'Your name, please.') });
263
+ },
264
+ // GitHub secrets for the scheduled run: held in memory until Apply, never written to a file.
265
+ async (s) => {
266
+ s.secrets = {};
267
+ const needed = nightlySecrets({ schedule: s.schedule, nightlyAgent: s.nightlyAgent });
268
+ if (!needed.length)
269
+ return;
270
+ const gh = d.which('gh') && d.exec('gh', ['auth', 'status'], { cwd: s.repo }).code === 0;
271
+ p.note([
272
+ `The ${s.schedule} run needs these GitHub secrets: ${needed.join(', ')}.`,
273
+ ...(s.nightlyAgent === 'copilot'
274
+ ? [
275
+ 'COPILOT_ASSIGN_TOKEN is a personal access token of someone with Copilot: GitHub lets only a user assign Copilot. Fine-grained: read access to metadata, read and write access to actions, contents, issues and pull requests (classic: the repo scope). Each run uses that person\'s Copilot plan.',
276
+ 'Also: turn on Copilot cloud agent for this repository, and add BRAVOS_LICENCE under Settings → Secrets and variables → Agents. Copilot does not see ordinary Actions secrets.',
277
+ ]
278
+ : [
279
+ s.nightlyAgent === 'codex'
280
+ ? `${needed[1]} lets Codex run in GitHub Actions; each run spends credits on it (weekly uses about a fifth of weekday).`
281
+ : `${needed[1]} lets Claude Code run there on your Claude plan: run \`claude setup-token\` in a terminal and paste what it prints. Each run uses your plan like a session would (weekly uses about a fifth of weekday).`,
282
+ 'Also: Settings → Actions → General → "Allow GitHub Actions to create and approve pull requests".',
283
+ ]),
284
+ ].join('\n'), 'Scheduled run');
285
+ if (!gh) {
286
+ p.info(`To add them later: gh secret set ${needed[0]} (or the repository's Settings → Secrets).`);
287
+ return;
288
+ }
289
+ if (opts.yes)
290
+ return;
291
+ s.setSecrets = await p.confirm('set-secrets', 'Set the secrets now with gh? You paste each value; it goes straight to GitHub and is never shown or saved.', s.setSecrets ?? true);
292
+ if (!s.setSecrets)
293
+ return;
294
+ for (const n of needed) {
295
+ const v = await p.secret(`secret:${n}`, `${n} (leave empty to skip)`);
296
+ if (v.trim())
297
+ s.secrets[n] = v.trim();
298
+ }
299
+ },
300
+ ];
301
+ // Run the steps. Esc in a step returns to the last step that asked something.
302
+ const s = { secrets: {} };
303
+ const trail = [];
304
+ const runFrom = async (start) => {
305
+ for (let i = start; i < steps.length;) {
306
+ const before = p.count;
307
+ try {
308
+ await steps[i](s);
309
+ if (p.count > before)
310
+ trail.push(i);
311
+ i++;
312
+ }
313
+ catch (e) {
314
+ if (!(e instanceof Back))
315
+ throw e;
316
+ i = trail.pop() ?? 0;
317
+ }
318
+ }
319
+ };
320
+ await runFrom(0);
321
+ // review: Esc here returns to the questions.
322
+ for (;;) {
323
+ const answers = toAnswers(s);
324
+ const changes = [
325
+ `Colours: ${answers.theme} (saved in ${tildify(join(d.home, 'config.json'), d.env.HOME)})`,
326
+ ...(answers.installTools ? [`Install: ${[...missingTools(s), ...missingBundles(s)].map((i) => i.id).join(', ')}`] : []),
327
+ `In ${tildify(answers.repo, d.env.HOME)}:`,
328
+ ` + skills, hooks and MCP for ${answers.agents.join(', ')}`,
329
+ ' + .guardlink/ threat model (guardlink init, if not there yet)',
330
+ ...(answers.pr !== 'none' ? [' + pre-PR check'] : []),
331
+ ...(answers.pr === 'hook+github' ? [' + .github/workflows/bravos-pr-gate.yml'] : []),
332
+ ...(answers.autopilot ? [' + autopilot'] : []),
333
+ ...(answers.schedule !== 'none' ? [` + .github/workflows/bravos-nightly-${answers.nightlyAgent}.yml (${answers.schedule}, cron ${CRON[answers.schedule]} UTC)`] : []),
334
+ ...(answers.schedule !== 'none' && answers.nightlyAgent === 'copilot' ? [' + .github/workflows/copilot-setup-steps.yml (prepares Copilot\'s session: Node and guardlink)'] : []),
335
+ ...(answers.proving !== 'none' ? [' + .guardlink/scope.yaml (localhost only; authorization left for you)'] : []),
336
+ ...(answers.name ? [` + .guardlink/proving.md (${answers.proving}${answers.generation ? ', continuous pentest' : ''}, confirmed by ${answers.name})`] : []),
337
+ ...(Object.keys(s.secrets).length ? [` + GitHub secrets: ${Object.keys(s.secrets).join(', ')}`] : []),
338
+ ' + .bravos/setup.json (your answers, for bravos start --again)',
339
+ ...(has(s, 'codegraph') ? ['Then: build the code graph for this repository'] : []),
340
+ ];
341
+ p.note(changes.join('\n'), 'About to make these changes');
342
+ let go;
343
+ try {
344
+ go = opts.yes ? 'apply' : await p.select('review', 'Apply?', [
345
+ { value: 'apply', label: 'Apply', recommended: true },
346
+ { value: 'show', label: 'Show the exact commands' },
347
+ { value: 'cancel', label: 'Cancel', hint: 'nothing changes' },
348
+ ], 'apply');
349
+ }
350
+ catch (e) {
351
+ if (!(e instanceof Back))
352
+ throw e;
353
+ // Back from the review: re-ask the last question, then come back here.
354
+ const k = trail.pop();
355
+ if (k !== undefined)
356
+ await runFrom(k);
357
+ continue;
358
+ }
359
+ if (go === 'cancel')
360
+ throw new Cancelled();
361
+ if (go === 'apply')
362
+ break;
363
+ p.note([
364
+ ...(answers.installTools && missingTools(s).length ? ['bravos setup --tools -y'] : []),
365
+ ...(answers.installTools && missingBundles(s).length ? ['bravos setup'] : []),
366
+ `bravos ${initArgs(answers).map((x) => (/\s/.test(x) ? JSON.stringify(x) : x)).join(' ')}`,
367
+ ...Object.keys(s.secrets).map((n) => `gh secret set ${n} (value from your paste)`),
368
+ ...(has(s, 'codegraph') ? [`bravos graph build ${JSON.stringify(answers.repo)} --scip no-exec`] : []),
369
+ ].join('\n'), 'Commands');
370
+ }
371
+ return apply(toAnswers(s), s, d, opts, { missingTools: missingTools(s).length > 0, missingBundles: missingBundles(s).length > 0, codegraph: has(s, 'codegraph') });
372
+ }
373
+ function toAnswers(s) {
374
+ return {
375
+ theme: s.theme ?? 'neutral',
376
+ installTools: !!s.installTools,
377
+ repo: s.repo,
378
+ agents: s.agents ?? ['claude'],
379
+ preset: s.preset ?? 'pr',
380
+ pr: s.pr ?? 'none',
381
+ autopilot: !!s.autopilot,
382
+ schedule: s.schedule ?? 'none',
383
+ nightlyAgent: s.nightlyAgent ?? 'claude',
384
+ proving: s.proving ?? 'none',
385
+ generation: !!s.generation,
386
+ words: s.proving === 'auto' || s.proving === 'schedule' ? (s.words ?? '') : '',
387
+ name: s.name ?? '',
388
+ };
389
+ }
390
+ async function apply(answers, s, d, opts, has) {
391
+ const p = d.prompter;
392
+ const { repo, agents } = answers;
393
+ writeTheme(d.home, answers.theme);
394
+ if (answers.installTools && has.missingTools) {
395
+ const r = await p.spin('Installing guardlink and cxg', () => d.bravos(['setup', '--tools', '-y']), (r) => (r.code ? { fail: 'Installing guardlink and cxg — failed' } : 'Installed guardlink and cxg'));
396
+ for (const l of [...r.out, ...r.err])
397
+ (r.code ? p.warn : p.info)(l);
398
+ }
399
+ if (answers.installTools && has.missingBundles) {
400
+ const r = await p.spin('Fetching the Bravos analyzer and code graph', () => d.bravos(['setup']), (r) => (r.code ? { fail: 'Fetching the analyzer and code graph — failed' } : 'Fetched the analyzer and code graph'));
401
+ for (const l of [...r.out, ...r.err])
402
+ (r.code ? p.warn : p.info)(l);
403
+ }
404
+ 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'));
405
+ for (const l of init.out)
406
+ p.info(l);
407
+ if (init.code !== 0) {
408
+ for (const l of init.err)
409
+ p.warn(l);
410
+ p.outro('Setup stopped: bravos init did not finish. Fix the line above and run bravos start --again.');
411
+ return init.code;
412
+ }
413
+ if (answers.name) {
414
+ mkdirSync(join(repo, '.guardlink'), { recursive: true });
415
+ writeFileSync(join(repo, '.guardlink', 'proving.md'), provingText({ ...answers, words: answers.words || provingLabel(answers.proving) }, d.today()));
416
+ }
417
+ for (const [n, v] of Object.entries(s.secrets)) {
418
+ const r = d.exec('gh', ['secret', 'set', n], { input: v, cwd: repo });
419
+ (r.code ? p.warn : p.info)(r.code ? `gh secret set ${n} failed — add it in the repository's Settings → Secrets` : `secret ${n} set`);
420
+ }
421
+ if (has.codegraph) {
422
+ const g = await p.spin('Building the code graph (a minute or two; longer on a big repository)', () => d.bravosChild(['graph', 'build', repo, '--scip', 'no-exec', '--json']), (r) => (graphSummary(r).ok ? graphSummary(r).line : { fail: graphSummary(r).line }));
423
+ const sum = graphSummary(g);
424
+ for (const n of sum.notes)
425
+ (sum.ok ? p.info : p.warn)(n);
426
+ }
427
+ writeAnswers(repo, answers, d.version, new Date().toISOString());
428
+ // hand-off
429
+ const next = await d.bravos(['next', repo]);
430
+ if (next.out.length)
431
+ p.note(next.out.slice(0, 12).join('\n'), 'Setup score');
432
+ const lead = agents.includes('claude') ? 'claude' : agents[0];
433
+ const tool = AGENTS.find((a) => a.value === lead)?.label ?? 'your agent';
434
+ const handoff = `${sigil(lead)}bravos-context`;
435
+ // A scripted run (--yes) leaves the person's clipboard alone.
436
+ const copied = opts.yes ? false : d.clipboard(handoff);
437
+ p.note([
438
+ `Open ${tool} in ${tildify(repo, d.env.HOME)} and type:`,
439
+ '',
440
+ ` ${handoff} learns what the app is for (asks you a few questions)`,
441
+ ` ${sigil(lead)}bravos-annotate maps the threats in your code, then runs the first SAST scan over them`,
442
+ '',
443
+ 'SAST waits for that first annotation on purpose: it reads the threat model to know what matters.',
444
+ 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.',
445
+ 'Follow along in a second terminal: bravos watch',
446
+ ].join('\n'), 'One step left, in your agent');
447
+ if (opts.yes && !answers.name)
448
+ p.info('Testing permission was not recorded (a person has to answer it): run bravos start --again in a terminal.');
449
+ p.outro('Bravos is set up.');
450
+ return 0;
451
+ }
452
+ function provingLabel(p) {
453
+ return { ask: 'Ask me every time before testing', auto: 'Test my local app automatically', schedule: 'Only in the scheduled run', none: 'Never test, just annotate' }[p];
454
+ }
@@ -0,0 +1,78 @@
1
+ // @comment -- "Finds git repositories to offer in bravos start: the current folder, then repos at most two levels under the current folder's parent and the usual code folders. Read-only directory listings only, capped in count and time, never inside node_modules or dot folders."
2
+ import { existsSync, readdirSync, statSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { basename, dirname, join, resolve } from 'node:path';
5
+ export const CODE_FOLDERS = ['code', 'src', 'projects', 'dev', 'repos', 'git', 'work', join('Documents', 'GITHUB'), join('Documents', 'GitHub'), join('Documents', 'code')];
6
+ const SKIP = new Set(['node_modules', 'vendor', 'target', 'dist', 'build', 'Library', 'Applications', 'Pictures', 'Music', 'Movies']);
7
+ /** True when `dir` is the top of a git work tree (a .git folder, or a .git file for a worktree). */
8
+ export const isGitRepo = (dir) => {
9
+ try {
10
+ return existsSync(join(dir, '.git'));
11
+ }
12
+ catch {
13
+ return false;
14
+ }
15
+ };
16
+ // @comment -- "Lists candidate repositories, nearest first: cwd (if a repo), siblings under cwd's parent, then the usual code folders in the home folder; depth two, capped, deduplicated"
17
+ export function findRepos(cwd, opts = {}) {
18
+ const limit = opts.limit ?? 12;
19
+ const now = opts.now ?? Date.now;
20
+ const deadline = now() + (opts.budgetMs ?? 400);
21
+ const home = opts.home ?? homedir();
22
+ const found = [];
23
+ const seen = new Set();
24
+ const add = (d) => {
25
+ const r = resolve(d);
26
+ if (!seen.has(r) && isGitRepo(r)) {
27
+ seen.add(r);
28
+ found.push(r);
29
+ }
30
+ };
31
+ const children = (d) => {
32
+ try {
33
+ return readdirSync(d, { withFileTypes: true })
34
+ .filter((e) => e.isDirectory() && !e.name.startsWith('.') && !SKIP.has(e.name))
35
+ .map((e) => join(d, e.name));
36
+ }
37
+ catch {
38
+ return [];
39
+ }
40
+ };
41
+ const walk = (root, depth) => {
42
+ if (found.length >= limit || now() > deadline || !existsSync(root))
43
+ return;
44
+ if (isGitRepo(root)) {
45
+ add(root);
46
+ return; // a repo's own subfolders are not separate projects
47
+ }
48
+ if (depth === 0)
49
+ return;
50
+ for (const c of children(root)) {
51
+ if (found.length >= limit || now() > deadline)
52
+ return;
53
+ walk(c, depth - 1);
54
+ }
55
+ };
56
+ add(cwd);
57
+ if (found.length === 0)
58
+ walk(cwd, 2);
59
+ walk(dirname(resolve(cwd)), 1);
60
+ for (const f of CODE_FOLDERS)
61
+ walk(join(home, f), 2);
62
+ return found.slice(0, limit);
63
+ }
64
+ /** "~/code/app" for a path under the home folder. */
65
+ export const tildify = (p, home = homedir()) => (p === home ? '~' : p.startsWith(home + '/') ? '~' + p.slice(home.length) : p);
66
+ /** A short hint for a repository: "current folder", or its parent's name. */
67
+ export const repoHint = (p, cwd) => (resolve(p) === resolve(cwd) ? 'current folder' : basename(dirname(p)));
68
+ /** Not a folder, or not the top of a git repository: a sentence that says so. */
69
+ export function repoProblem(p) {
70
+ try {
71
+ if (!statSync(p).isDirectory())
72
+ return 'That is a file, not a folder.';
73
+ }
74
+ catch {
75
+ return 'No folder there.';
76
+ }
77
+ return isGitRepo(p) ? undefined : 'Not a git repository (no .git here). Run git init first, or pick the repository folder.';
78
+ }