@bridge_gpt/mcp-server 0.2.70 → 0.2.71

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 (61) hide show
  1. package/README.md +5 -5
  2. package/build/agent-launchers/claude-executor-adapter.js +10 -1
  3. package/build/agent-registry.js +5 -5
  4. package/build/agents.generated.js +11 -1
  5. package/build/bounded-wait.js +9 -1
  6. package/build/bridge-permissions.js +13 -5
  7. package/build/commands.generated.js +3 -3
  8. package/build/conductor/bridge-api-client.js +260 -2
  9. package/build/conductor/command-drift-production.js +7 -2
  10. package/build/conductor/doctor.js +9 -3
  11. package/build/conductor/epic-implementer-cli.js +4 -0
  12. package/build/conductor/gate-discovery.js +524 -10
  13. package/build/conductor/gate-settings-review.js +451 -0
  14. package/build/conductor/launch-need-probes.js +16 -11
  15. package/build/conductor/launch-plan.js +145 -0
  16. package/build/conductor/precheck-timings.js +14 -0
  17. package/build/conductor/preview-observations.js +10 -0
  18. package/build/conductor/readiness-sections.js +4 -1
  19. package/build/conductor/recovery-cli.js +59 -2
  20. package/build/conductor/recovery-operations.js +45 -2
  21. package/build/docs.generated.js +1 -1
  22. package/build/drive-epic.js +188 -45
  23. package/build/epic-ci-workflow-drift.js +71 -23
  24. package/build/epic-ci-workflow-install.js +83 -26
  25. package/build/epic-ci-workflow-v1.js +132 -0
  26. package/build/epic-ci-workflow.js +174 -13
  27. package/build/epic-implementer-bin.js +18 -18
  28. package/build/executor/ci-rerun-job.js +220 -14
  29. package/build/executor/env.js +207 -3
  30. package/build/executor/gate-qualification-job.js +20 -5
  31. package/build/executor/job-runner.js +112 -11
  32. package/build/executor/likely-tests.js +6 -1
  33. package/build/executor/preflight.js +5 -0
  34. package/build/executor/process-containment.js +18 -0
  35. package/build/executor/prompt-spec.js +72 -13
  36. package/build/executor/reconcile-overlap-job.js +6 -1
  37. package/build/executor/worker-command.js +136 -1
  38. package/build/executor/worker-database.js +30 -11
  39. package/build/executor/worker-resources.js +12 -1
  40. package/build/executor/worker-verification-guidance.js +29 -0
  41. package/build/index.js +221 -165
  42. package/build/install-bridge-conductor-gate.js +195 -14
  43. package/build/install-bridge-conductor-setup.js +20 -6
  44. package/build/install-bridge-conductor.js +355 -37
  45. package/build/install-bridge.js +1 -1
  46. package/build/merge-workflow-install.js +20 -0
  47. package/build/pipelines.generated.js +2 -2
  48. package/build/plan-execution-ledger.js +23 -8
  49. package/build/plane/plane-freshness.js +6 -2
  50. package/build/plane/preflight.js +19 -0
  51. package/build/printed-remedy-commands.js +8 -1
  52. package/build/readme.generated.js +1 -1
  53. package/build/repository-toolchains.js +581 -0
  54. package/build/setup-epic.js +24 -7
  55. package/build/test-command-detection.js +58 -21
  56. package/build/ticket-delivery-artifacts.js +7 -0
  57. package/build/ticket-delivery-enrollment.js +67 -4
  58. package/build/version.generated.js +3 -3
  59. package/docs/EPIC-IMPLEMENTER.md +38 -0
  60. package/docs/epic-implementer/getting-started.md +58 -2
  61. package/package.json +2 -2
@@ -0,0 +1,451 @@
1
+ /**
2
+ * The interactive review of discovered CI settings (BAPI-1520).
3
+ *
4
+ * `install-bridge conductor` can propose two optional settings beside the gate:
5
+ *
6
+ * - **worker variables** — literal environment values found in CI config; and
7
+ * - **local reproduction hints** — a structured command for a reported provider
8
+ * check, so a worker can reproduce a failing check locally.
9
+ *
10
+ * Both are stored now and delivered to workers later (a follow-up ticket). Both
11
+ * are high-trust: a value is confirmed by the repository owner, one decision at
12
+ * a time, and only in an interactive terminal.
13
+ *
14
+ * ## Why values stay in this module
15
+ *
16
+ * A worker variable's VALUE is rendered here, through {@link terminalSafe}, to
17
+ * the interactive prompt channel and nowhere else. Everything this module
18
+ * returns for logs, reports, or MCP output is names and counts. A run with no
19
+ * terminal never reaches {@link reviewDiscoveredSettings}, so it neither shows
20
+ * nor sends either setting.
21
+ *
22
+ * ## Presence-aware results
23
+ *
24
+ * {@link SettingsEdit} separates "untouched" (`undefined`) from "changed". An
25
+ * untouched setting is omitted from the write, so the server keeps what it has;
26
+ * an empty `workerEnv` list is a deliberate removal of every stored variable.
27
+ */
28
+ import { LOCAL_COMMAND_TIMEOUT_SECONDS, } from "./gate-discovery.js";
29
+ /** Limits that mirror `gate_profile.py` for hand-typed hints. */
30
+ const MAX_HINT_WORDS = 32;
31
+ const MAX_HINT_WORD_CHARS = 1024;
32
+ const MAX_REVIEW_ATTEMPTS = 3;
33
+ // ---------------------------------------------------------------------------
34
+ // Terminal-safe rendering
35
+ // ---------------------------------------------------------------------------
36
+ /**
37
+ * Quote `text` for a terminal so it cannot act on the terminal: quotes and
38
+ * backslashes are escaped, and control characters (including ESC and the C1
39
+ * range), line and paragraph separators, zero-width and bidirectional
40
+ * formatting characters are written as `\u{hex}`. Nothing is truncated; callers
41
+ * pass values already bounded by the validated input limits.
42
+ */
43
+ export function terminalSafe(text) {
44
+ let out = "";
45
+ for (const ch of text) {
46
+ const cp = ch.codePointAt(0) ?? 0;
47
+ if (ch === '"')
48
+ out += '\\"';
49
+ else if (ch === "\\")
50
+ out += "\\\\";
51
+ else if (cp < 0x20 ||
52
+ cp === 0x7f ||
53
+ (cp >= 0x80 && cp <= 0x9f) ||
54
+ cp === 0x2028 ||
55
+ cp === 0x2029 ||
56
+ (cp >= 0x200b && cp <= 0x200f) ||
57
+ (cp >= 0x202a && cp <= 0x202e) ||
58
+ (cp >= 0x2066 && cp <= 0x2069) ||
59
+ cp === 0xfeff) {
60
+ out += `\\u{${cp.toString(16)}}`;
61
+ }
62
+ else
63
+ out += ch;
64
+ }
65
+ return `"${out}"`;
66
+ }
67
+ function safeList(names) {
68
+ return names.map(terminalSafe).join(", ");
69
+ }
70
+ // ---------------------------------------------------------------------------
71
+ // Equality (flag-normalized, order-insensitive for variables)
72
+ // ---------------------------------------------------------------------------
73
+ function sameEntry(a, b) {
74
+ return a.name === b.name && a.value === b.value && (a.committed_literal === true) === (b.committed_literal === true);
75
+ }
76
+ /** Whether two variable lists are the same set (ordering never matters; `false` and omitted flags are equal). */
77
+ export function workerEnvEqual(a, b) {
78
+ const left = a ?? [];
79
+ const right = b ?? [];
80
+ if (left.length !== right.length)
81
+ return false;
82
+ return left.every((entry) => {
83
+ const other = right.find((e) => e.name === entry.name);
84
+ return other !== undefined && sameEntry(entry, other);
85
+ });
86
+ }
87
+ /** Whether two reproduction hints are identical. */
88
+ export function hintEqual(a, b) {
89
+ return (a.timeout_seconds === b.timeout_seconds && a.argv.length === b.argv.length && a.argv.every((w, i) => w === b.argv[i]));
90
+ }
91
+ /**
92
+ * Whether `edit` leaves the stored settings exactly as they are. Omitted
93
+ * settings and per-check hints resolve against `stored` first, so a request
94
+ * that restates what is stored is a no-op rather than a write.
95
+ */
96
+ export function settingsMatchStored(edit, stored) {
97
+ if (edit.workerEnv !== undefined && !workerEnvEqual(edit.workerEnv, stored?.worker_env))
98
+ return false;
99
+ for (const [check, hint] of edit.reproduce ?? []) {
100
+ const current = stored?.reproduction_hints?.get(check) ?? null;
101
+ if (hint === null) {
102
+ if (current !== null)
103
+ return false;
104
+ }
105
+ else if (current === null || !hintEqual(hint, current)) {
106
+ return false;
107
+ }
108
+ }
109
+ return true;
110
+ }
111
+ // ---------------------------------------------------------------------------
112
+ // Rows
113
+ // ---------------------------------------------------------------------------
114
+ function candidateEntry(candidate) {
115
+ return {
116
+ name: candidate.name,
117
+ value: candidate.value,
118
+ ...(candidate.committedLiteral ? { committed_literal: true } : {}),
119
+ };
120
+ }
121
+ function envRows(proposal, stored) {
122
+ const storedList = stored?.worker_env ?? [];
123
+ const rows = [];
124
+ for (const entry of storedList) {
125
+ const candidate = proposal.workerEnvCandidates.find((c) => c.name === entry.name);
126
+ if (candidate !== undefined && candidate.value !== entry.value) {
127
+ rows.push({
128
+ name: entry.name,
129
+ status: "Changed",
130
+ stored: entry,
131
+ proposed: candidateEntry(candidate),
132
+ sources: candidate.sources,
133
+ });
134
+ }
135
+ else {
136
+ rows.push({ name: entry.name, status: "Stored", stored: entry, sources: candidate?.sources ?? [] });
137
+ }
138
+ }
139
+ for (const candidate of proposal.workerEnvCandidates) {
140
+ if (storedList.some((e) => e.name === candidate.name))
141
+ continue;
142
+ rows.push({ name: candidate.name, status: "Proposed", proposed: candidateEntry(candidate), sources: candidate.sources });
143
+ }
144
+ return rows;
145
+ }
146
+ function describeEnvRow(row, index) {
147
+ const label = index === null ? " " : ` [${index}] `;
148
+ const lines = [];
149
+ if (row.status === "Stored" && row.stored) {
150
+ lines.push(`${label}${row.name} = ${terminalSafe(row.stored.value)} — Stored`);
151
+ }
152
+ else if (row.status === "Changed" && row.stored && row.proposed) {
153
+ lines.push(`${label}${row.name} = ${terminalSafe(row.proposed.value)} — Changed (stored: ${terminalSafe(row.stored.value)})`);
154
+ }
155
+ else if (row.proposed) {
156
+ lines.push(`${label}${row.name} = ${terminalSafe(row.proposed.value)} — Proposed`);
157
+ }
158
+ if (row.proposed?.committed_literal === true) {
159
+ lines.push(" Requires confirmation: the name looks secret, so this is a plain-text value committed to CI. " +
160
+ "Storing it makes it readable to anyone who can read this repository's gate profile.");
161
+ }
162
+ if (row.sources.length > 0)
163
+ lines.push(` from ${safeList(row.sources)}`);
164
+ return lines;
165
+ }
166
+ const NO_HINT_TEXT = "No local command declared; the stored test command remains the fallback.";
167
+ function hintRows(proposal, stored, providerChecks) {
168
+ return providerChecks.map((check) => ({
169
+ check,
170
+ stored: stored?.reproduction_hints?.get(check) ?? null,
171
+ proposed: proposal.reproductionHints.find((h) => h.check === check) ?? null,
172
+ }));
173
+ }
174
+ function describeHint(hint) {
175
+ return `${hint.argv.map(terminalSafe).join(" ")} (timeout ${hint.timeout_seconds}s)`;
176
+ }
177
+ // ---------------------------------------------------------------------------
178
+ // Rendering
179
+ // ---------------------------------------------------------------------------
180
+ /** Whether there is anything to show or decide. */
181
+ export function hasSettingsToReview(proposal, stored, providerChecks) {
182
+ return (proposal.workerEnvCandidates.length > 0 ||
183
+ (stored?.worker_env?.length ?? 0) > 0 ||
184
+ proposal.workerEnvConflicts.length > 0 ||
185
+ hintRows(proposal, stored, providerChecks).some((r) => r.stored !== null || r.proposed !== null));
186
+ }
187
+ /**
188
+ * Print the review surface. Values appear only when `showValues` is true (an
189
+ * interactive terminal); otherwise only names and counts are printed.
190
+ */
191
+ export function renderSettingsReview(io, proposal, stored, providerChecks, showValues) {
192
+ io.log("");
193
+ io.log("Review discovered CI settings");
194
+ io.log("─────────────────────────────");
195
+ io.log(" These are repository-specific, non-secret execution facts. Worker variables reach workers and");
196
+ io.log(" qualification jobs; reproduction commands appear in repair prompts as hints only, and never");
197
+ io.log(" change which checks gate a merge. A secret-looking name is refused unless you individually");
198
+ io.log(" confirm that it holds a plain-text value already committed to CI. Removing every variable means");
199
+ io.log(" workers receive none, not the old built-in defaults. Nothing is stored until you confirm it below.");
200
+ io.log("");
201
+ io.log(" Worker variables");
202
+ const rows = envRows(proposal, stored);
203
+ if (rows.length === 0) {
204
+ io.log(" None stored and none proposed.");
205
+ }
206
+ else if (showValues) {
207
+ let number = 0;
208
+ for (const row of rows) {
209
+ const selectable = row.status !== "Stored";
210
+ if (selectable)
211
+ number += 1;
212
+ for (const line of describeEnvRow(row, selectable ? number : null))
213
+ io.log(line);
214
+ }
215
+ }
216
+ else {
217
+ io.log(` ${rows.length} variable(s): ${safeList(rows.map((r) => r.name))} (values are shown only in a terminal)`);
218
+ }
219
+ if (proposal.workerEnvConflicts.length > 0) {
220
+ io.log(` Conflict (declared with different values; not proposed): ${safeList(proposal.workerEnvConflicts)}`);
221
+ }
222
+ if (proposal.workerEnvSkipped.length > 0) {
223
+ io.log(` Not proposed (unsupported, reserved, or out of bounds): ${safeList(proposal.workerEnvSkipped)}`);
224
+ }
225
+ if (proposal.workerEnvOverflow > 0) {
226
+ io.log(` ${proposal.workerEnvOverflow} more eligible variable(s) were left out by the 32-variable limit.`);
227
+ }
228
+ if (rows.length === 0 && proposal.noCandidates) {
229
+ io.log(" Discovery found nothing to propose. Cargo, Go, and Gradle command candidates must be entered by hand.");
230
+ }
231
+ io.log("");
232
+ io.log(" Local reproduction hints — Hint only — never changes gating or completion.");
233
+ const hints = hintRows(proposal, stored, providerChecks);
234
+ if (hints.length === 0)
235
+ io.log(` ${NO_HINT_TEXT}`);
236
+ for (const row of hints) {
237
+ io.log(` ${terminalSafe(row.check)}`);
238
+ if (!showValues) {
239
+ io.log(row.stored || row.proposed
240
+ ? ` ${row.stored ? "a hint is stored" : "a hint is proposed"} (commands are shown only in a terminal)`
241
+ : ` ${NO_HINT_TEXT}`);
242
+ continue;
243
+ }
244
+ if (row.stored)
245
+ io.log(` Stored: ${describeHint(row.stored)}`);
246
+ if (row.proposed && (row.stored === null || !hintEqual(row.stored, hintFrom(row.proposed)))) {
247
+ io.log(` ${row.stored ? "Changed" : "Proposed"}: ${describeHint({ argv: row.proposed.argv, timeout_seconds: row.proposed.timeoutSeconds })}`);
248
+ }
249
+ if (!row.stored && !row.proposed)
250
+ io.log(` ${NO_HINT_TEXT}`);
251
+ }
252
+ if (proposal.reproductionHintsSkipped.length > 0) {
253
+ io.log(` Not proposed (no single plain command could be read for): ${safeList(proposal.reproductionHintsSkipped)}`);
254
+ }
255
+ io.log("");
256
+ }
257
+ function hintFrom(candidate) {
258
+ return { argv: [...candidate.argv], timeout_seconds: candidate.timeoutSeconds };
259
+ }
260
+ function parseEnvChoice(answer, hasStored, hasProposals) {
261
+ const a = answer.trim().toLowerCase();
262
+ if (a === "")
263
+ return hasStored || !hasProposals ? "keep" : "ignore";
264
+ if (a === "k" || a === "keep")
265
+ return hasStored ? "keep" : null;
266
+ if (a === "e" || a === "edit")
267
+ return "edit";
268
+ if (a === "i" || a === "ignore")
269
+ return hasProposals ? "ignore" : null;
270
+ if (a === "r" || a === "remove")
271
+ return hasStored ? "remove" : null;
272
+ return null;
273
+ }
274
+ async function yes(prompt, text) {
275
+ const answer = (await prompt(text)).trim().toLowerCase();
276
+ return answer === "y" || answer === "yes";
277
+ }
278
+ /**
279
+ * Ask about worker variables. Returns the complete new list, or `undefined`
280
+ * when the owner leaves the stored settings untouched.
281
+ */
282
+ async function reviewWorkerEnv(io, proposal, stored) {
283
+ const prompt = io.promptLine;
284
+ const storedList = stored?.worker_env ?? [];
285
+ const rows = envRows(proposal, stored);
286
+ const proposals = rows.filter((r) => r.status !== "Stored");
287
+ if (storedList.length === 0 && proposals.length === 0)
288
+ return undefined;
289
+ const options = [
290
+ ...(storedList.length > 0 ? ["[k]eep stored variables as they are"] : []),
291
+ "[e]dit — decide each variable one at a time",
292
+ ...(proposals.length > 0 ? ["[i]gnore the proposals (stored settings stay untouched)"] : []),
293
+ ...(storedList.length > 0 ? ["[r]emove every stored variable"] : []),
294
+ ];
295
+ let choice = null;
296
+ for (let attempt = 0; attempt < MAX_REVIEW_ATTEMPTS && choice === null; attempt++) {
297
+ choice = parseEnvChoice(await prompt(`Worker variables — ${options.join(", ")} (Enter leaves them untouched): `), storedList.length > 0, proposals.length > 0);
298
+ if (choice === null)
299
+ io.log(" Choose one of the listed letters, or press Enter.");
300
+ }
301
+ if (choice === "ignore" && proposals.length > 0) {
302
+ io.log(` Ignored ${proposals.length} proposal(s): ${safeList(proposals.map((r) => r.name))}. ` +
303
+ "Stored settings are untouched; nothing was removed.");
304
+ }
305
+ if (choice === null || choice === "keep" || choice === "ignore")
306
+ return undefined;
307
+ if (choice === "remove") {
308
+ io.log(` Removal requested for ${storedList.length} stored variable(s): ${safeList(storedList.map((e) => e.name))}.`);
309
+ const confirmed = await yes(prompt, "Remove every stored worker variable? [y/N]: ");
310
+ return confirmed ? [] : undefined;
311
+ }
312
+ // edit: one decision per proposal, then one per stored variable.
313
+ let result = storedList.map((e) => ({ ...e }));
314
+ for (const row of proposals) {
315
+ const entry = row.proposed;
316
+ if (entry === undefined)
317
+ continue;
318
+ if (entry.committed_literal === true) {
319
+ io.log(` ${row.name} looks secret. Its value is a plain-text literal committed to CI; storing it makes it ` +
320
+ "readable to anyone who can read this repository's gate profile.");
321
+ const answer = (await prompt(`Type "yes" to confirm ${row.name} = ${terminalSafe(entry.value)} is a committed literal (anything else skips it): `)).trim();
322
+ if (answer !== "yes") {
323
+ io.log(` Ignored the proposal for ${row.name}: not stored. Stored settings are untouched; nothing was removed.`);
324
+ continue;
325
+ }
326
+ }
327
+ else if (!(await yes(prompt, `Apply ${row.name} = ${terminalSafe(entry.value)}? [y/N]: `))) {
328
+ io.log(` Ignored the proposal for ${row.name}: not stored. Stored settings are untouched; nothing was removed.`);
329
+ continue;
330
+ }
331
+ result = [...result.filter((e) => e.name !== row.name), { ...entry }];
332
+ }
333
+ for (const entry of storedList) {
334
+ if (!result.some((e) => e.name === entry.name))
335
+ continue;
336
+ if (await yes(prompt, `Remove stored ${entry.name}? [y/N]: `)) {
337
+ io.log(` Removal requested: ${entry.name}.`);
338
+ result = result.filter((e) => e.name !== entry.name);
339
+ }
340
+ }
341
+ result.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
342
+ return workerEnvEqual(result, storedList) ? undefined : result;
343
+ }
344
+ /** Parse hand-typed command words; `null` when they cannot be a reproduction command. */
345
+ export function parseHintWords(line) {
346
+ const words = line.trim().split(/\s+/).filter((w) => w !== "");
347
+ if (words.length === 0 || words.length > MAX_HINT_WORDS)
348
+ return null;
349
+ if (words.some((w) => w.length > MAX_HINT_WORD_CHARS || w.includes("\0")))
350
+ return null;
351
+ return words;
352
+ }
353
+ async function typedHint(prompt, io) {
354
+ const line = await prompt("Command words, space separated, no shell syntax (Enter cancels): ");
355
+ if (line.trim() === "")
356
+ return null;
357
+ const argv = parseHintWords(line);
358
+ if (argv === null) {
359
+ io.log(` A hint needs 1 to ${MAX_HINT_WORDS} words of at most ${MAX_HINT_WORD_CHARS} characters.`);
360
+ return null;
361
+ }
362
+ const rawTimeout = (await prompt(`Timeout seconds, 1-1800 (Enter = ${LOCAL_COMMAND_TIMEOUT_SECONDS}): `)).trim();
363
+ const timeout = rawTimeout === "" ? LOCAL_COMMAND_TIMEOUT_SECONDS : Number(rawTimeout);
364
+ if (!Number.isInteger(timeout) || timeout < 1 || timeout > 1800) {
365
+ io.log(" The timeout must be a whole number from 1 to 1800.");
366
+ return null;
367
+ }
368
+ return { argv, timeout_seconds: timeout };
369
+ }
370
+ async function reviewHints(io, proposal, stored, providerChecks) {
371
+ const prompt = io.promptLine;
372
+ const edits = new Map();
373
+ for (const row of hintRows(proposal, stored, providerChecks)) {
374
+ const proposed = row.proposed === null ? null : hintFrom(row.proposed);
375
+ const newProposal = proposed !== null && (row.stored === null || !hintEqual(row.stored, proposed));
376
+ if (row.stored === null && !newProposal)
377
+ continue;
378
+ const letters = [
379
+ ...(row.stored ? ["[k]eep stored"] : []),
380
+ ...(newProposal ? ["[a]pply proposed"] : []),
381
+ "[e]dit",
382
+ ...(row.stored ? ["[d]rop stored"] : ["[i]gnore"]),
383
+ ];
384
+ const answer = (await prompt(`Hint for ${terminalSafe(row.check)} — ${letters.join(", ")} (Enter leaves it untouched): `))
385
+ .trim()
386
+ .toLowerCase();
387
+ if (answer === "" || answer === "k" || answer === "keep" || answer === "i" || answer === "ignore")
388
+ continue;
389
+ if ((answer === "a" || answer === "apply") && newProposal && proposed !== null) {
390
+ edits.set(row.check, proposed);
391
+ }
392
+ else if ((answer === "d" || answer === "drop") && row.stored !== null) {
393
+ io.log(` Removal requested: the stored hint for ${terminalSafe(row.check)}.`);
394
+ edits.set(row.check, null);
395
+ }
396
+ else if (answer === "e" || answer === "edit") {
397
+ const typed = await typedHint(prompt, io);
398
+ if (typed !== null)
399
+ edits.set(row.check, typed);
400
+ }
401
+ else {
402
+ io.log(" Not recognized; the hint is left untouched.");
403
+ }
404
+ }
405
+ // Restating the stored hint is not an edit.
406
+ for (const [check, hint] of [...edits]) {
407
+ const current = stored?.reproduction_hints?.get(check) ?? null;
408
+ if (hint === null ? current === null : current !== null && hintEqual(hint, current))
409
+ edits.delete(check);
410
+ }
411
+ return edits.size > 0 ? edits : undefined;
412
+ }
413
+ /**
414
+ * Show the review surface and collect the owner's decisions. Requires a
415
+ * terminal. Returns what changed; nothing is stored here.
416
+ */
417
+ export async function reviewDiscoveredSettings(io, proposal, stored, providerChecks) {
418
+ renderSettingsReview(io, proposal, stored, providerChecks, true);
419
+ const edit = {};
420
+ const workerEnv = await reviewWorkerEnv(io, proposal, stored);
421
+ if (workerEnv !== undefined)
422
+ edit.workerEnv = workerEnv;
423
+ const reproduce = await reviewHints(io, proposal, stored, providerChecks);
424
+ if (reproduce !== undefined)
425
+ edit.reproduce = reproduce;
426
+ return edit;
427
+ }
428
+ /** Name-only lines describing what an edit changes, for the gate comparison. */
429
+ export function describeSettingsEdit(edit, stored) {
430
+ const lines = [];
431
+ if (edit.workerEnv !== undefined) {
432
+ const before = stored?.worker_env ?? [];
433
+ const added = edit.workerEnv.filter((e) => !before.some((b) => b.name === e.name)).map((e) => e.name);
434
+ const changed = edit.workerEnv
435
+ .filter((e) => before.some((b) => b.name === e.name && !sameEntry(b, e)))
436
+ .map((e) => e.name);
437
+ const removed = before.filter((b) => !(edit.workerEnv ?? []).some((e) => e.name === b.name)).map((b) => b.name);
438
+ const parts = [
439
+ added.length > 0 ? `added ${safeList(added)}` : "",
440
+ changed.length > 0 ? `changed ${safeList(changed)}` : "",
441
+ removed.length > 0 ? `removal requested for ${safeList(removed)}` : "",
442
+ ].filter((p) => p !== "");
443
+ lines.push(` worker variables: ${edit.workerEnv.length} after this change (${parts.join("; ")})`);
444
+ }
445
+ for (const [check, hint] of edit.reproduce ?? []) {
446
+ lines.push(hint === null
447
+ ? ` reproduction hint for ${terminalSafe(check)}: removal requested`
448
+ : ` reproduction hint for ${terminalSafe(check)}: set (hint only — never changes gating)`);
449
+ }
450
+ return lines;
451
+ }
@@ -201,6 +201,22 @@ export async function inspectRequiredSelfHostedRunners(input) {
201
201
  async function probeRunners(input) {
202
202
  const now = input.now ?? Date.now;
203
203
  const deadline = now() + LAUNCH_RUNNER_PROBE_DEADLINE_MS;
204
+ // Every workflow job, from both `.yml` and `.yaml` files.
205
+ const dir = path.join(input.repoRoot, ".github", "workflows");
206
+ let files;
207
+ try {
208
+ files = (await input.workflows.list(dir)).filter((file) => /\.ya?ml$/.test(file)).sort();
209
+ }
210
+ catch (error) {
211
+ const code = error.code;
212
+ if (code === "ENOENT" || code === "ENOTDIR")
213
+ return { state: "not_applicable", reason: "no_github_actions_workflows" };
214
+ return { state: "unverifiable", reason: "workflows_unreadable" };
215
+ }
216
+ if (files.length > WORKFLOW_MAX_FILES)
217
+ return { state: "unverifiable", reason: "workflows_unreadable" };
218
+ if (files.length === 0)
219
+ return { state: "not_applicable", reason: "no_github_actions_workflows" };
204
220
  const profile = input.gateProfile;
205
221
  if (profile === null || profile === undefined || profile.read_failed || !Array.isArray(profile.provider_checks)) {
206
222
  return { state: "unverifiable", reason: "no_gate_profile" };
@@ -213,17 +229,6 @@ async function probeRunners(input) {
213
229
  }
214
230
  if (required.length === 0)
215
231
  return { state: "not_applicable" };
216
- // Every workflow job, from both `.yml` and `.yaml` files.
217
- const dir = path.join(input.repoRoot, ".github", "workflows");
218
- let files;
219
- try {
220
- files = (await input.workflows.list(dir)).filter((file) => /\.ya?ml$/.test(file)).sort();
221
- }
222
- catch {
223
- return { state: "unverifiable", reason: "workflows_unreadable" };
224
- }
225
- if (files.length > WORKFLOW_MAX_FILES)
226
- return { state: "unverifiable", reason: "workflows_unreadable" };
227
232
  const jobs = [];
228
233
  for (const file of files) {
229
234
  try {
@@ -0,0 +1,145 @@
1
+ import { EPIC_KEY_PATTERN } from "../drive-epic-key.js";
2
+ import { ESCALATION_REACHABILITY_CHECK_ID } from "../escalation-reachability.js";
3
+ import { LAUNCH_NEEDS, LAUNCH_NEED_ROW_IDS, LAUNCH_NEED_REMEDIES } from "./readiness-sections.js";
4
+ import { WORKER_DATABASE_DOCTOR_OWNER, WORKER_DATABASE_DOCTOR_RUNBOOK_SECTION } from "./doctor.js";
5
+ import { normalizeRepoRelativePath } from "./file-scope-guard.js";
6
+ /**
7
+ * Advisory decision table (source order within each group):
8
+ * reachability unconfirmed | proceed | [] | fix the channel before retrying
9
+ * probably_done child | run it | [] | skip: [--skip-child, KEY]
10
+ * applicable relevant role / other unhealthy DB | fix first | [] | launch anyway: []
11
+ * asked/present runner | fix first | [] | launch anyway: []
12
+ * asked/present power | proceed, keep the lid open | [] | fix first: []
13
+ * asked/present usage | proceed | [] | fix first: []
14
+ * Fix-first acceptance accepts unresolved risk; it never performs remediation.
15
+ * verification_gap belongs exclusively to the command session, not this union.
16
+ */
17
+ /** Bridge-specific hints are consulted only after positive repository applicability. */
18
+ export const DB_OR_HARNESS_PATH_HINTS = ["db/alembic/", "tests/integration/conductor_harness/", "migrations/"];
19
+ export function planDatabaseRelevance(nodes, applicable) {
20
+ if (!applicable || !Array.isArray(nodes))
21
+ return "unknown";
22
+ let declared = false;
23
+ let malformed = false;
24
+ let relevant = false;
25
+ for (const node of nodes) {
26
+ if (!isObject(node)) {
27
+ malformed = true;
28
+ continue;
29
+ }
30
+ if (!("touched_files" in node))
31
+ continue;
32
+ if (!Array.isArray(node.touched_files)) {
33
+ malformed = true;
34
+ continue;
35
+ }
36
+ declared = true;
37
+ for (const raw of node.touched_files) {
38
+ const path = normalizeRepoRelativePath(raw);
39
+ if (path === null) {
40
+ malformed = true;
41
+ continue;
42
+ }
43
+ if (DB_OR_HARNESS_PATH_HINTS.some((hint) => path.startsWith(hint)) || path.includes("/migrations/"))
44
+ relevant = true;
45
+ }
46
+ }
47
+ return relevant ? true : malformed || !declared ? "unknown" : false;
48
+ }
49
+ export const LAUNCH_PLAN_REACHABILITY_COPY = {
50
+ summary: "Escalation reachability",
51
+ reason: "Live delivery is not confirmed; escalations are also shown in the driving session.",
52
+ remedy: "Declare notify.webhook_url in the run policy, or configure live email.",
53
+ };
54
+ export const LAUNCH_PLAN_CHILD_COPY = {
55
+ summary: "Probably done child",
56
+ reason: "The child is on the indexed commit but has no confirmed delivery record; run it to be sure.",
57
+ remedy: "Run the child, or explicitly skip it in this plan.",
58
+ };
59
+ export const LAUNCH_PLAN_NEED_COPY = {
60
+ worker_db_role: { summary: "Worker DB role", reason: "This database-relevant plan needs a safe worker database role.", recommendation: "fix first" },
61
+ self_hosted_runner: { summary: "Self-hosted runner", reason: "Child CI cannot become green while the required runner is offline.", recommendation: "fix first" },
62
+ host_power: { summary: "Host sleep", reason: "The executor needs the host to remain awake during the run.", recommendation: "proceed, keep the lid open" },
63
+ usage_reset_after_run: { summary: "Usage reset after the run", reason: "Capacity waits resume automatically when usage resets.", recommendation: "proceed" },
64
+ };
65
+ export const LAUNCH_PLAN_DB_COPY = {
66
+ "worker-db-boundary": { summary: "Worker database boundary", reason: "The worker database boundary is not confirmed healthy." },
67
+ "worker-db-alembic": { summary: "Worker database migrations", reason: "The operator migration state is not confirmed healthy." },
68
+ "worker-db-leftovers": { summary: "Worker database leftovers", reason: "Worker database cleanup needs attention." },
69
+ "worker-db-unverifiable": { summary: "Worker database inspection", reason: "Worker database safety could not be verified." },
70
+ "worker-db-harness": { summary: "Worker database harness", reason: "Harness database cleanup is not confirmed healthy." },
71
+ };
72
+ function isObject(value) {
73
+ return value !== null && typeof value === "object" && !Array.isArray(value);
74
+ }
75
+ /** Only complete, asked/present typed rows participate. Untrusted prose is never copied. */
76
+ function eligibleNeed(row) {
77
+ const meta = row.launch_need;
78
+ if (!isObject(meta) || !LAUNCH_NEEDS.includes(meta.need))
79
+ return undefined;
80
+ const need = meta.need;
81
+ if (need === "epic_branch_behind_base" || row.id !== LAUNCH_NEED_ROW_IDS[need] ||
82
+ meta.asked !== true || meta.state !== "present" || row.status !== "warn" ||
83
+ row.blocking !== false || typeof row.remedy !== "string" || row.remedy.trim() === "")
84
+ return undefined;
85
+ return { need, state: "present", asked: true };
86
+ }
87
+ function item(id, kind, copy, recommendation, alternatives) {
88
+ return { id, kind, ...copy, recommendation, alternatives, flags_if_accepted: [] };
89
+ }
90
+ /** Pure projection of a finished preview; no admission decision or input is changed. */
91
+ export function buildLaunchPlan(preview) {
92
+ if (preview.decision !== "create")
93
+ return undefined;
94
+ const rows = Array.isArray(preview.launch_checks) ? preview.launch_checks.filter(isObject) : [];
95
+ const items = [];
96
+ const seen = new Set();
97
+ const add = (entry) => {
98
+ if (!seen.has(entry.id)) {
99
+ seen.add(entry.id);
100
+ items.push(entry);
101
+ }
102
+ };
103
+ if (preview.summary?.escalation_channel !== "webhook" &&
104
+ !rows.some((row) => row.id === ESCALATION_REACHABILITY_CHECK_ID && row.status === "pass")) {
105
+ add(item(ESCALATION_REACHABILITY_CHECK_ID, "reachability", LAUNCH_PLAN_REACHABILITY_COPY, "proceed", [{ choice: "fix first", flags: [] }]));
106
+ }
107
+ const children = preview.already_done_children;
108
+ if (isObject(children) && children.status === "checked" && Array.isArray(children.children)) {
109
+ for (const child of children.children) {
110
+ if (!isObject(child) || child.classification !== "probably_done" || child.will_skip !== false ||
111
+ typeof child.ticket_key !== "string" || !EPIC_KEY_PATTERN.test(child.ticket_key))
112
+ continue;
113
+ add(item(`probably-done-${child.ticket_key}`, "probably_done", {
114
+ ...LAUNCH_PLAN_CHILD_COPY, summary: `${LAUNCH_PLAN_CHILD_COPY.summary} ${child.ticket_key}`,
115
+ }, "run it", [{ choice: "skip", flags: ["--skip-child", child.ticket_key] }]));
116
+ }
117
+ }
118
+ const addNeed = (row, need) => {
119
+ const copy = LAUNCH_PLAN_NEED_COPY[need];
120
+ add(item(LAUNCH_NEED_ROW_IDS[need], need === "worker_db_role" ? "worker_db" : "launch_need", {
121
+ summary: copy.summary, reason: copy.reason, remedy: LAUNCH_NEED_REMEDIES[need],
122
+ }, copy.recommendation, [{ choice: copy.recommendation === "fix first" ? "launch anyway" : "fix first", flags: [] }]));
123
+ };
124
+ for (const row of rows) {
125
+ // The role never falls through into generic database handling, even if malformed.
126
+ if (row.id === LAUNCH_NEED_ROW_IDS.worker_db_role) {
127
+ if (eligibleNeed(row)?.need === "worker_db_role" && preview.plan_database_relevance === true)
128
+ addNeed(row, "worker_db_role");
129
+ continue;
130
+ }
131
+ if (typeof row.id !== "string" || !Object.hasOwn(LAUNCH_PLAN_DB_COPY, row.id) ||
132
+ !["warn", "fail", "unverified"].includes(row.status) || row.blocking !== false)
133
+ continue;
134
+ const id = row.id;
135
+ add(item(id, "worker_db", { ...LAUNCH_PLAN_DB_COPY[id], remedy: `${WORKER_DATABASE_DOCTOR_OWNER}: see ${WORKER_DATABASE_DOCTOR_RUNBOOK_SECTION}` }, "fix first", [{ choice: "launch anyway", flags: [] }]));
136
+ }
137
+ for (const need of LAUNCH_NEEDS) {
138
+ if (need === "worker_db_role" || need === "epic_branch_behind_base")
139
+ continue;
140
+ const row = rows.find((row) => eligibleNeed(row)?.need === need);
141
+ if (row)
142
+ addNeed(row, need);
143
+ }
144
+ return { launch_plan: { version: 1, items, fix_first: items.some((entry) => entry.recommendation === "fix first") } };
145
+ }
@@ -0,0 +1,14 @@
1
+ export const monotonicNow = () => performance.now();
2
+ export function elapsedMs(started, now = monotonicNow) {
3
+ const elapsed = now() - started;
4
+ return Number.isFinite(elapsed) ? Math.max(0, elapsed) : 0;
5
+ }
6
+ export async function measurePrecheck(run, record, now = monotonicNow) {
7
+ const started = now();
8
+ try {
9
+ return await run();
10
+ }
11
+ finally {
12
+ record(elapsedMs(started, now));
13
+ }
14
+ }
@@ -0,0 +1,10 @@
1
+ export function previewObservationScopeMatches(observed, access, epic) {
2
+ try {
3
+ const normalize = (url) => new URL(url).href.replace(/\/+$/, "");
4
+ return normalize(observed.endpoint) === normalize(access.baseUrl) &&
5
+ observed.repository === access.repoName && observed.epic === epic;
6
+ }
7
+ catch {
8
+ return false;
9
+ }
10
+ }