@bridge_gpt/mcp-server 0.2.70 → 0.2.72

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 (134) hide show
  1. package/README.md +55 -17
  2. package/build/agent-launchers/claude-executor-adapter.js +29 -4
  3. package/build/agent-notes.js +171 -95
  4. package/build/agent-registry.js +5 -5
  5. package/build/agents.generated.js +12 -2
  6. package/build/bounded-wait.js +9 -1
  7. package/build/bridge-permissions.js +17 -5
  8. package/build/bridge-worktree-inspection.js +237 -0
  9. package/build/check-evidence.js +6 -0
  10. package/build/claude-review-workflow.js +1 -1
  11. package/build/cli-help.js +6 -0
  12. package/build/codex-auto-recovery.js +126 -0
  13. package/build/codex-skill-adapter.js +2 -0
  14. package/build/commands.generated.js +5 -5
  15. package/build/conductor/bridge-api-client.js +776 -23
  16. package/build/conductor/command-drift-production.js +7 -2
  17. package/build/conductor/doctor.js +93 -13
  18. package/build/conductor/epic-implementer-cli.js +55 -2
  19. package/build/conductor/gate-discovery.js +659 -19
  20. package/build/conductor/gate-settings-review.js +751 -0
  21. package/build/conductor/git-hooks-uninstall.js +112 -0
  22. package/build/conductor/git-hooks.js +81 -15
  23. package/build/conductor/guided-repair.js +10 -1
  24. package/build/conductor/install-doctor.js +2 -4
  25. package/build/conductor/launch-need-probes.js +16 -11
  26. package/build/conductor/launch-plan.js +185 -0
  27. package/build/conductor/local-merge.js +12 -1
  28. package/build/conductor/merge-execution-contract.js +1 -1
  29. package/build/conductor/merged-child-check.js +2 -1
  30. package/build/conductor/precheck-timings.js +14 -0
  31. package/build/conductor/prerequisite-inputs.js +379 -0
  32. package/build/conductor/preview-observations.js +10 -0
  33. package/build/conductor/readiness-assessment.js +78 -0
  34. package/build/conductor/readiness-cli.js +10 -0
  35. package/build/conductor/readiness-prerequisites.js +53 -0
  36. package/build/conductor/readiness-sections.js +25 -9
  37. package/build/conductor/readiness.js +20 -2
  38. package/build/conductor/recovery-cli.js +281 -14
  39. package/build/conductor/recovery-operations.js +78 -5
  40. package/build/conductor/repair-contract.js +33 -0
  41. package/build/conductor/tools.js +34 -3
  42. package/build/conductor/wait-run-attention.js +115 -0
  43. package/build/conductor/wait-run-cli.js +96 -3
  44. package/build/conductor/worker-database-doctor-inspector.js +1 -0
  45. package/build/credential-store.js +25 -20
  46. package/build/dependency-install-declarations.js +157 -0
  47. package/build/docs.generated.js +4 -4
  48. package/build/doctor.js +37 -5
  49. package/build/drive-epic-help.js +2 -2
  50. package/build/drive-epic.js +240 -56
  51. package/build/epic-ci-workflow-drift.js +71 -23
  52. package/build/epic-ci-workflow-install.js +83 -26
  53. package/build/epic-ci-workflow-v1.js +132 -0
  54. package/build/epic-ci-workflow.js +174 -13
  55. package/build/epic-implementer-bin.js +119 -44
  56. package/build/epic-launch-profile.js +1 -1
  57. package/build/executor/ci-rerun-job.js +220 -14
  58. package/build/executor/cli.js +2 -0
  59. package/build/executor/completion-contract.js +16 -0
  60. package/build/executor/credentials.js +1 -1
  61. package/build/executor/delivery-observations.js +113 -0
  62. package/build/executor/delivery-outcome.js +30 -0
  63. package/build/executor/dependency-refresh-runner.js +132 -0
  64. package/build/executor/dependency-refresh.js +530 -0
  65. package/build/executor/deps.js +4 -0
  66. package/build/executor/env.js +274 -5
  67. package/build/executor/gate-qualification-job.js +20 -5
  68. package/build/executor/harness-coverage.js +19 -0
  69. package/build/executor/http-client.js +35 -1
  70. package/build/executor/index.js +2 -1
  71. package/build/executor/install-preflight.js +1 -1
  72. package/build/executor/job-runner.js +355 -36
  73. package/build/executor/likely-tests.js +100 -98
  74. package/build/executor/preflight.js +5 -0
  75. package/build/executor/process-containment.js +18 -0
  76. package/build/executor/prompt-spec.js +84 -15
  77. package/build/executor/reconcile-overlap-job.js +6 -1
  78. package/build/executor/required-verification.js +28 -0
  79. package/build/executor/required-work-diagnostics.js +30 -0
  80. package/build/executor/required-work-ledger.js +19 -1
  81. package/build/executor/results.js +42 -0
  82. package/build/executor/service-discovery.js +42 -0
  83. package/build/executor/service-lifecycle.js +109 -2
  84. package/build/executor/service-uninstall.js +205 -0
  85. package/build/executor/service-unit.js +5 -3
  86. package/build/executor/test-clock.js +3 -0
  87. package/build/executor/verification-hints.js +179 -0
  88. package/build/executor/worker-command.js +188 -1
  89. package/build/executor/worker-database.js +299 -40
  90. package/build/executor/worker-finalization.js +65 -10
  91. package/build/executor/worker-guard-hook.js +10 -2
  92. package/build/executor/worker-resources.js +12 -1
  93. package/build/executor/worker-verification-guidance.js +64 -0
  94. package/build/executor/worktree-inspection.js +42 -0
  95. package/build/github-sign-in.js +1 -1
  96. package/build/index.js +767 -310
  97. package/build/init.js +3 -3
  98. package/build/install-bridge-conductor-gate.js +416 -41
  99. package/build/install-bridge-conductor-setup.js +135 -32
  100. package/build/install-bridge-conductor.js +769 -353
  101. package/build/install-bridge.js +419 -124
  102. package/build/install-maintenance.js +104 -0
  103. package/build/install-reexec.js +1 -1
  104. package/build/local-cleanup.js +59 -0
  105. package/build/mcp-install-state.js +68 -2
  106. package/build/merge-workflow-install.js +22 -2
  107. package/build/package-script-semantics.js +10 -0
  108. package/build/pipeline-utils.js +1 -1
  109. package/build/pipelines.generated.js +6 -6
  110. package/build/plan-execution-ledger.js +171 -10
  111. package/build/plane/plane-freshness.js +12 -9
  112. package/build/plane/preflight.js +19 -0
  113. package/build/plane/terminal-run-cleanup.js +5 -1
  114. package/build/plane/terminal-run-status.js +4 -0
  115. package/build/printed-remedy-commands.js +31 -4
  116. package/build/readiness-check.js +1 -78
  117. package/build/readiness-prerequisites.generated.js +199 -0
  118. package/build/readme.generated.js +1 -1
  119. package/build/repository-toolchains.js +623 -0
  120. package/build/setup-change-policy.js +32 -0
  121. package/build/setup-epic.js +26 -9
  122. package/build/setup-question.js +62 -0
  123. package/build/start-tickets.js +4 -0
  124. package/build/test-command-detection.js +61 -80
  125. package/build/test-support/notes-fs.js +40 -0
  126. package/build/ticket-delivery-artifacts.js +7 -0
  127. package/build/ticket-delivery-enrollment.js +80 -4
  128. package/build/ticket-delivery-run-scope.js +128 -0
  129. package/build/version.generated.js +3 -3
  130. package/build/worker-guard-hook-bin.js +2 -2
  131. package/build/worktrees.js +105 -0
  132. package/docs/EPIC-IMPLEMENTER.md +43 -0
  133. package/docs/epic-implementer/getting-started.md +95 -14
  134. package/package.json +2 -2
@@ -0,0 +1,751 @@
1
+ /**
2
+ * The interactive review of discovered CI settings (BAPI-1520).
3
+ *
4
+ * `install epic-implementer` 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
+ * BAPI-1551 adds two more, reviewed in the same step:
11
+ *
12
+ * - **dependency refresh** — `{cwd, argv, lockfiles}` entries the executor runs
13
+ * before a worker starts, only when a declared lockfile changed; and
14
+ * - **CI database behavior** — whether the repository's CI runs with a database
15
+ * (`none`, `provided`, or `unknown`).
16
+ *
17
+ * All are high-trust: a value is confirmed by the repository owner, one decision
18
+ * at a time, and only in an interactive terminal. An install argv is shown and
19
+ * edited only here, as an argument array, never as a shell string.
20
+ *
21
+ * ## Why values stay in this module
22
+ *
23
+ * A worker variable's VALUE is rendered here, through {@link terminalSafe}, to
24
+ * the interactive prompt channel and nowhere else. Everything this module
25
+ * returns for logs, reports, or MCP output is names and counts. A run with no
26
+ * terminal never reaches {@link reviewDiscoveredSettings}, so it neither shows
27
+ * nor sends either setting.
28
+ *
29
+ * ## Presence-aware results
30
+ *
31
+ * {@link SettingsEdit} separates "untouched" (`undefined`) from "changed". An
32
+ * untouched setting is omitted from the write, so the server keeps what it has;
33
+ * an empty `workerEnv` list is a deliberate removal of every stored variable.
34
+ */
35
+ import { LOCAL_COMMAND_TIMEOUT_SECONDS, } from "./gate-discovery.js";
36
+ import { CI_DATABASE_DEFAULT, MAX_DEPENDENCY_INSTALL_ENTRIES, MAX_DEPENDENCY_INSTALL_LOCKFILES, admitDependencyInstallDeclarations, dependencyInstallEntryIdentity, isCiDatabase, isSafeRepoRelativePath, sameDependencyInstall, } from "../dependency-install-declarations.js";
37
+ /** Limits that mirror `gate_profile.py` for hand-typed hints. */
38
+ const MAX_HINT_WORDS = 32;
39
+ const MAX_HINT_WORD_CHARS = 1024;
40
+ const MAX_REVIEW_ATTEMPTS = 3;
41
+ // ---------------------------------------------------------------------------
42
+ // Terminal-safe rendering
43
+ // ---------------------------------------------------------------------------
44
+ /**
45
+ * Quote `text` for a terminal so it cannot act on the terminal: quotes and
46
+ * backslashes are escaped, and control characters (including ESC and the C1
47
+ * range), line and paragraph separators, zero-width and bidirectional
48
+ * formatting characters are written as `\u{hex}`. Nothing is truncated; callers
49
+ * pass values already bounded by the validated input limits.
50
+ */
51
+ export function terminalSafe(text) {
52
+ let out = "";
53
+ for (const ch of text) {
54
+ const cp = ch.codePointAt(0) ?? 0;
55
+ if (ch === '"')
56
+ out += '\\"';
57
+ else if (ch === "\\")
58
+ out += "\\\\";
59
+ else if (cp < 0x20 ||
60
+ cp === 0x7f ||
61
+ (cp >= 0x80 && cp <= 0x9f) ||
62
+ cp === 0x2028 ||
63
+ cp === 0x2029 ||
64
+ (cp >= 0x200b && cp <= 0x200f) ||
65
+ (cp >= 0x202a && cp <= 0x202e) ||
66
+ (cp >= 0x2066 && cp <= 0x2069) ||
67
+ cp === 0xfeff) {
68
+ out += `\\u{${cp.toString(16)}}`;
69
+ }
70
+ else
71
+ out += ch;
72
+ }
73
+ return `"${out}"`;
74
+ }
75
+ function safeList(names) {
76
+ return names.map(terminalSafe).join(", ");
77
+ }
78
+ // ---------------------------------------------------------------------------
79
+ // Equality (flag-normalized, order-insensitive for variables)
80
+ // ---------------------------------------------------------------------------
81
+ function sameEntry(a, b) {
82
+ return a.name === b.name && a.value === b.value && (a.committed_literal === true) === (b.committed_literal === true);
83
+ }
84
+ /** Whether two variable lists are the same set (ordering never matters; `false` and omitted flags are equal). */
85
+ export function workerEnvEqual(a, b) {
86
+ const left = a ?? [];
87
+ const right = b ?? [];
88
+ if (left.length !== right.length)
89
+ return false;
90
+ return left.every((entry) => {
91
+ const other = right.find((e) => e.name === entry.name);
92
+ return other !== undefined && sameEntry(entry, other);
93
+ });
94
+ }
95
+ /** Whether two reproduction hints are identical. */
96
+ export function hintEqual(a, b) {
97
+ return (a.timeout_seconds === b.timeout_seconds && a.argv.length === b.argv.length && a.argv.every((w, i) => w === b.argv[i]));
98
+ }
99
+ /** BAPI-1551 — whether two dependency-refresh lists are the same (absent is empty; order matters). */
100
+ export function dependencyInstallEqual(a, b) {
101
+ return sameDependencyInstall(a ?? [], b ?? []);
102
+ }
103
+ /** BAPI-1551 — the stored `ci_database`; absent is `unknown`. */
104
+ export function storedCiDatabase(stored) {
105
+ return stored?.ci_database ?? CI_DATABASE_DEFAULT;
106
+ }
107
+ /**
108
+ * Whether `edit` leaves the stored settings exactly as they are. Omitted
109
+ * settings and per-check hints resolve against `stored` first, so a request
110
+ * that restates what is stored is a no-op rather than a write.
111
+ */
112
+ export function settingsMatchStored(edit, stored) {
113
+ if (edit.workerEnv !== undefined && !workerEnvEqual(edit.workerEnv, stored?.worker_env))
114
+ return false;
115
+ if (edit.dependencyInstall !== undefined && !dependencyInstallEqual(edit.dependencyInstall, stored?.dependency_install)) {
116
+ return false;
117
+ }
118
+ if (edit.ciDatabase !== undefined && edit.ciDatabase !== storedCiDatabase(stored))
119
+ return false;
120
+ for (const [check, hint] of edit.reproduce ?? []) {
121
+ const current = stored?.reproduction_hints?.get(check) ?? null;
122
+ if (hint === null) {
123
+ if (current !== null)
124
+ return false;
125
+ }
126
+ else if (current === null || !hintEqual(hint, current)) {
127
+ return false;
128
+ }
129
+ }
130
+ return true;
131
+ }
132
+ // ---------------------------------------------------------------------------
133
+ // Rows
134
+ // ---------------------------------------------------------------------------
135
+ function candidateEntry(candidate) {
136
+ return {
137
+ name: candidate.name,
138
+ value: candidate.value,
139
+ ...(candidate.committedLiteral ? { committed_literal: true } : {}),
140
+ };
141
+ }
142
+ function envRows(proposal, stored) {
143
+ const storedList = stored?.worker_env ?? [];
144
+ const rows = [];
145
+ for (const entry of storedList) {
146
+ const candidate = proposal.workerEnvCandidates.find((c) => c.name === entry.name);
147
+ if (candidate !== undefined && candidate.value !== entry.value) {
148
+ rows.push({
149
+ name: entry.name,
150
+ status: "Changed",
151
+ stored: entry,
152
+ proposed: candidateEntry(candidate),
153
+ sources: candidate.sources,
154
+ });
155
+ }
156
+ else {
157
+ rows.push({ name: entry.name, status: "Stored", stored: entry, sources: candidate?.sources ?? [] });
158
+ }
159
+ }
160
+ for (const candidate of proposal.workerEnvCandidates) {
161
+ if (storedList.some((e) => e.name === candidate.name))
162
+ continue;
163
+ rows.push({ name: candidate.name, status: "Proposed", proposed: candidateEntry(candidate), sources: candidate.sources });
164
+ }
165
+ return rows;
166
+ }
167
+ function describeEnvRow(row, index) {
168
+ const label = index === null ? " " : ` [${index}] `;
169
+ const lines = [];
170
+ if (row.status === "Stored" && row.stored) {
171
+ lines.push(`${label}${row.name} = ${terminalSafe(row.stored.value)} — Stored`);
172
+ }
173
+ else if (row.status === "Changed" && row.stored && row.proposed) {
174
+ lines.push(`${label}${row.name} = ${terminalSafe(row.proposed.value)} — Changed (stored: ${terminalSafe(row.stored.value)})`);
175
+ }
176
+ else if (row.proposed) {
177
+ lines.push(`${label}${row.name} = ${terminalSafe(row.proposed.value)} — Proposed`);
178
+ }
179
+ if (row.proposed?.committed_literal === true) {
180
+ lines.push(" Requires confirmation: the name looks secret, so this is a plain-text value committed to CI. " +
181
+ "Storing it makes it readable to anyone who can read this repository's gate profile.");
182
+ }
183
+ if (row.sources.length > 0)
184
+ lines.push(` from ${safeList(row.sources)}`);
185
+ return lines;
186
+ }
187
+ const NO_HINT_TEXT = "No local command declared; the stored test command remains the fallback.";
188
+ function hintRows(proposal, stored, providerChecks) {
189
+ return providerChecks.map((check) => ({
190
+ check,
191
+ stored: stored?.reproduction_hints?.get(check) ?? null,
192
+ proposed: proposal.reproductionHints.find((h) => h.check === check) ?? null,
193
+ }));
194
+ }
195
+ function describeHint(hint) {
196
+ return `${hint.argv.map(terminalSafe).join(" ")} (timeout ${hint.timeout_seconds}s)`;
197
+ }
198
+ // ---------------------------------------------------------------------------
199
+ // Rendering
200
+ // ---------------------------------------------------------------------------
201
+ /** Whether there is anything to show or decide. */
202
+ export function hasSettingsToReview(proposal, stored, providerChecks) {
203
+ return (proposal.workerEnvCandidates.length > 0 ||
204
+ (stored?.worker_env?.length ?? 0) > 0 ||
205
+ proposal.workerEnvConflicts.length > 0 ||
206
+ hintRows(proposal, stored, providerChecks).some((r) => r.stored !== null || r.proposed !== null) ||
207
+ hasDeclarationsToReview(proposal, stored));
208
+ }
209
+ /**
210
+ * BAPI-1551 — whether the dependency-refresh or CI-database declarations have
211
+ * anything stored or newly proposed.
212
+ */
213
+ export function hasDeclarationsToReview(proposal, stored) {
214
+ return ((stored?.dependency_install?.length ?? 0) > 0 ||
215
+ newDependencyProposals(proposal, stored).length > 0 ||
216
+ storedCiDatabase(stored) !== CI_DATABASE_DEFAULT ||
217
+ proposedCiDatabase(proposal) !== CI_DATABASE_DEFAULT);
218
+ }
219
+ /**
220
+ * BAPI-1551 — whether discovery proposes a declaration the stored profile does
221
+ * not already hold. This is the advisory gate change setup offers; it is never a
222
+ * blocking item.
223
+ */
224
+ export function hasUnstoredDeclarationProposal(proposal, stored) {
225
+ const ci = proposedCiDatabase(proposal);
226
+ return newDependencyProposals(proposal, stored).length > 0 || (ci !== CI_DATABASE_DEFAULT && ci !== storedCiDatabase(stored));
227
+ }
228
+ /** Proposed entries whose identity (cwd and lockfiles) is not stored with the same argv. */
229
+ function newDependencyProposals(proposal, stored) {
230
+ const storedList = stored?.dependency_install ?? [];
231
+ return (proposal.dependencyInstallCandidates ?? []).filter((c) => !storedList.some((e) => dependencyInstallEqual([entryOf(c)], [e])));
232
+ }
233
+ function entryOf(candidate) {
234
+ return { cwd: candidate.cwd, argv: [...candidate.argv], lockfiles: [...candidate.lockfiles] };
235
+ }
236
+ function proposedCiDatabase(proposal) {
237
+ return proposal.ciDatabaseProposal?.value ?? CI_DATABASE_DEFAULT;
238
+ }
239
+ /**
240
+ * Print the review surface. Values appear only when `showValues` is true (an
241
+ * interactive terminal); otherwise only names and counts are printed.
242
+ */
243
+ export function renderSettingsReview(io, proposal, stored, providerChecks, showValues) {
244
+ io.log("");
245
+ io.log("Review discovered CI settings");
246
+ io.log("─────────────────────────────");
247
+ io.log(" These are repository-specific, non-secret execution facts. Worker variables reach workers and");
248
+ io.log(" qualification jobs; reproduction commands appear in repair prompts as hints only, and never");
249
+ io.log(" change which checks gate a merge. A secret-looking name is refused unless you individually");
250
+ io.log(" confirm that it holds a plain-text value already committed to CI. Removing every variable means");
251
+ io.log(" workers receive none, not the old built-in defaults. Nothing is stored until you confirm it below.");
252
+ io.log("");
253
+ io.log(" Worker variables");
254
+ const rows = envRows(proposal, stored);
255
+ if (rows.length === 0) {
256
+ io.log(" None stored and none proposed.");
257
+ }
258
+ else if (showValues) {
259
+ let number = 0;
260
+ for (const row of rows) {
261
+ const selectable = row.status !== "Stored";
262
+ if (selectable)
263
+ number += 1;
264
+ for (const line of describeEnvRow(row, selectable ? number : null))
265
+ io.log(line);
266
+ }
267
+ }
268
+ else {
269
+ io.log(` ${rows.length} variable(s): ${safeList(rows.map((r) => r.name))} (values are shown only in a terminal)`);
270
+ }
271
+ if (proposal.workerEnvConflicts.length > 0) {
272
+ io.log(` Conflict (declared with different values; not proposed): ${safeList(proposal.workerEnvConflicts)}`);
273
+ }
274
+ if (proposal.workerEnvSkipped.length > 0) {
275
+ io.log(` Not proposed (unsupported, reserved, or out of bounds): ${safeList(proposal.workerEnvSkipped)}`);
276
+ }
277
+ if (proposal.workerEnvOverflow > 0) {
278
+ io.log(` ${proposal.workerEnvOverflow} more eligible variable(s) were left out by the 32-variable limit.`);
279
+ }
280
+ if (rows.length === 0 && proposal.noCandidates) {
281
+ io.log(" Discovery found nothing to propose. Cargo, Go, and Gradle command candidates must be entered by hand.");
282
+ }
283
+ io.log("");
284
+ io.log(" Local reproduction hints — Hint only — never changes gating or completion.");
285
+ const hints = hintRows(proposal, stored, providerChecks);
286
+ if (hints.length === 0)
287
+ io.log(` ${NO_HINT_TEXT}`);
288
+ for (const row of hints) {
289
+ io.log(` ${terminalSafe(row.check)}`);
290
+ if (!showValues) {
291
+ io.log(row.stored || row.proposed
292
+ ? ` ${row.stored ? "a hint is stored" : "a hint is proposed"} (commands are shown only in a terminal)`
293
+ : ` ${NO_HINT_TEXT}`);
294
+ continue;
295
+ }
296
+ if (row.stored)
297
+ io.log(` Stored: ${describeHint(row.stored)}`);
298
+ if (row.proposed && (row.stored === null || !hintEqual(row.stored, hintFrom(row.proposed)))) {
299
+ io.log(` ${row.stored ? "Changed" : "Proposed"}: ${describeHint({ argv: row.proposed.argv, timeout_seconds: row.proposed.timeoutSeconds })}`);
300
+ }
301
+ if (!row.stored && !row.proposed)
302
+ io.log(` ${NO_HINT_TEXT}`);
303
+ }
304
+ if (proposal.reproductionHintsSkipped.length > 0) {
305
+ io.log(` Not proposed (no single plain command could be read for): ${safeList(proposal.reproductionHintsSkipped)}`);
306
+ }
307
+ // Shown only when there is something to say, so a review without either
308
+ // declaration renders exactly as it did before BAPI-1551.
309
+ if (hasDeclarationsToReview(proposal, stored) || (proposal.dependencyInstallNotes?.length ?? 0) > 0) {
310
+ renderDeclarationsReview(io, proposal, stored, showValues);
311
+ }
312
+ io.log("");
313
+ }
314
+ const CI_DATABASE_TEXT = Object.freeze({
315
+ none: "none — CI runs without a database",
316
+ provided: "provided — CI provides a database",
317
+ unknown: "unknown — not declared",
318
+ });
319
+ const DEPENDENCY_NOTE_TEXT = Object.freeze({
320
+ dependency_install_pip_not_proposed: "A pip requirements file was found. It is not proposed: a bare pip install would use whatever " +
321
+ "Python is first on the executor's PATH, not this worktree's environment. Add an entry by hand if you need one.",
322
+ dependency_install_toolchain_unresolved: "The repository's toolchains could not be read with certainty, so nothing is proposed.",
323
+ });
324
+ /** One entry as a person reads it: where it runs and what it watches first, then the command. */
325
+ function describeDependencyEntry(entry, label, showValues) {
326
+ const where = entry.cwd === "." ? "repository root" : terminalSafe(entry.cwd);
327
+ const lines = [`${where}, when ${safeList(entry.lockfiles)} change${entry.lockfiles.length === 1 ? "s" : ""}${label ? ` (${label})` : ""}`];
328
+ lines.push(showValues
329
+ ? ` runs: ${entry.argv.map(terminalSafe).join(" ")}`
330
+ : " (the install command is shown only in a terminal)");
331
+ return lines;
332
+ }
333
+ /** BAPI-1551 — the Dependency refresh and CI database behavior groups. */
334
+ function renderDeclarationsReview(io, proposal, stored, showValues) {
335
+ io.log("");
336
+ io.log(" Dependency refresh — before a worker starts, reinstall dependencies when a lockfile changed.");
337
+ const storedList = stored?.dependency_install ?? [];
338
+ const proposals = newDependencyProposals(proposal, stored);
339
+ if (storedList.length === 0 && proposals.length === 0)
340
+ io.log(" None stored and none proposed.");
341
+ storedList.forEach((entry) => {
342
+ const [first, ...rest] = describeDependencyEntry(entry, null, showValues);
343
+ io.log(` ${first} — Stored`);
344
+ for (const line of rest)
345
+ io.log(line);
346
+ });
347
+ proposals.forEach((candidate, index) => {
348
+ const [first, ...rest] = describeDependencyEntry(candidate, candidate.label, showValues);
349
+ io.log(` [${index + 1}] ${first} — Proposed`);
350
+ for (const line of rest)
351
+ io.log(line);
352
+ });
353
+ for (const note of proposal.dependencyInstallNotes ?? [])
354
+ io.log(` ${DEPENDENCY_NOTE_TEXT[note] ?? note}`);
355
+ io.log(" Discovery looks at the repository root only, so it can miss a subdirectory project. Stored entries stay " +
356
+ "as they are unless you change them; you can add a subdirectory entry by hand below.");
357
+ io.log("");
358
+ io.log(" CI database behavior — tells workers whether CI runs with a database.");
359
+ io.log(` Stored: ${CI_DATABASE_TEXT[storedCiDatabase(stored)]}`);
360
+ const ci = proposal.ciDatabaseProposal;
361
+ if (ci !== undefined && ci.value !== CI_DATABASE_DEFAULT && ci.value !== storedCiDatabase(stored)) {
362
+ io.log(` Proposed: ${CI_DATABASE_TEXT[ci.value]}${ci.sources.length > 0 ? ` (from ${safeList(ci.sources)})` : ""}`);
363
+ }
364
+ }
365
+ function hintFrom(candidate) {
366
+ return { argv: [...candidate.argv], timeout_seconds: candidate.timeoutSeconds };
367
+ }
368
+ function parseEnvChoice(answer, hasStored, hasProposals) {
369
+ const a = answer.trim().toLowerCase();
370
+ if (a === "")
371
+ return hasStored || !hasProposals ? "keep" : "ignore";
372
+ if (a === "k" || a === "keep")
373
+ return hasStored ? "keep" : null;
374
+ if (a === "e" || a === "edit")
375
+ return "edit";
376
+ if (a === "i" || a === "ignore")
377
+ return hasProposals ? "ignore" : null;
378
+ if (a === "r" || a === "remove")
379
+ return hasStored ? "remove" : null;
380
+ return null;
381
+ }
382
+ async function yes(prompt, text) {
383
+ const answer = (await prompt(text)).trim().toLowerCase();
384
+ return answer === "y" || answer === "yes";
385
+ }
386
+ /**
387
+ * Ask about worker variables. Returns the complete new list, or `undefined`
388
+ * when the owner leaves the stored settings untouched.
389
+ */
390
+ async function reviewWorkerEnv(io, proposal, stored) {
391
+ const prompt = io.promptLine;
392
+ const storedList = stored?.worker_env ?? [];
393
+ const rows = envRows(proposal, stored);
394
+ const proposals = rows.filter((r) => r.status !== "Stored");
395
+ if (storedList.length === 0 && proposals.length === 0)
396
+ return undefined;
397
+ const options = [
398
+ ...(storedList.length > 0 ? ["[k]eep stored variables as they are"] : []),
399
+ "[e]dit — decide each variable one at a time",
400
+ ...(proposals.length > 0 ? ["[i]gnore the proposals (stored settings stay untouched)"] : []),
401
+ ...(storedList.length > 0 ? ["[r]emove every stored variable"] : []),
402
+ ];
403
+ let choice = null;
404
+ for (let attempt = 0; attempt < MAX_REVIEW_ATTEMPTS && choice === null; attempt++) {
405
+ choice = parseEnvChoice(await prompt(`Worker variables — ${options.join(", ")} (Enter leaves them untouched): `), storedList.length > 0, proposals.length > 0);
406
+ if (choice === null)
407
+ io.log(" Choose one of the listed letters, or press Enter.");
408
+ }
409
+ if (choice === "ignore" && proposals.length > 0) {
410
+ io.log(` Ignored ${proposals.length} proposal(s): ${safeList(proposals.map((r) => r.name))}. ` +
411
+ "Stored settings are untouched; nothing was removed.");
412
+ }
413
+ if (choice === null || choice === "keep" || choice === "ignore")
414
+ return undefined;
415
+ if (choice === "remove") {
416
+ io.log(` Removal requested for ${storedList.length} stored variable(s): ${safeList(storedList.map((e) => e.name))}.`);
417
+ const confirmed = await yes(prompt, "Remove every stored worker variable? [y/N]: ");
418
+ return confirmed ? [] : undefined;
419
+ }
420
+ // edit: one decision per proposal, then one per stored variable.
421
+ let result = storedList.map((e) => ({ ...e }));
422
+ for (const row of proposals) {
423
+ const entry = row.proposed;
424
+ if (entry === undefined)
425
+ continue;
426
+ if (entry.committed_literal === true) {
427
+ io.log(` ${row.name} looks secret. Its value is a plain-text literal committed to CI; storing it makes it ` +
428
+ "readable to anyone who can read this repository's gate profile.");
429
+ const answer = (await prompt(`Type "yes" to confirm ${row.name} = ${terminalSafe(entry.value)} is a committed literal (anything else skips it): `)).trim();
430
+ if (answer !== "yes") {
431
+ io.log(` Ignored the proposal for ${row.name}: not stored. Stored settings are untouched; nothing was removed.`);
432
+ continue;
433
+ }
434
+ }
435
+ else if (!(await yes(prompt, `Apply ${row.name} = ${terminalSafe(entry.value)}? [y/N]: `))) {
436
+ io.log(` Ignored the proposal for ${row.name}: not stored. Stored settings are untouched; nothing was removed.`);
437
+ continue;
438
+ }
439
+ result = [...result.filter((e) => e.name !== row.name), { ...entry }];
440
+ }
441
+ for (const entry of storedList) {
442
+ if (!result.some((e) => e.name === entry.name))
443
+ continue;
444
+ if (await yes(prompt, `Remove stored ${entry.name}? [y/N]: `)) {
445
+ io.log(` Removal requested: ${entry.name}.`);
446
+ result = result.filter((e) => e.name !== entry.name);
447
+ }
448
+ }
449
+ result.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
450
+ return workerEnvEqual(result, storedList) ? undefined : result;
451
+ }
452
+ /** Parse hand-typed command words; `null` when they cannot be a reproduction command. */
453
+ export function parseHintWords(line) {
454
+ const words = line.trim().split(/\s+/).filter((w) => w !== "");
455
+ if (words.length === 0 || words.length > MAX_HINT_WORDS)
456
+ return null;
457
+ if (words.some((w) => w.length > MAX_HINT_WORD_CHARS || w.includes("\0")))
458
+ return null;
459
+ return words;
460
+ }
461
+ async function typedHint(prompt, io) {
462
+ const line = await prompt("Command words, space separated, no shell syntax (Enter cancels): ");
463
+ if (line.trim() === "")
464
+ return null;
465
+ const argv = parseHintWords(line);
466
+ if (argv === null) {
467
+ io.log(` A hint needs 1 to ${MAX_HINT_WORDS} words of at most ${MAX_HINT_WORD_CHARS} characters.`);
468
+ return null;
469
+ }
470
+ const rawTimeout = (await prompt(`Timeout seconds, 1-1800 (Enter = ${LOCAL_COMMAND_TIMEOUT_SECONDS}): `)).trim();
471
+ const timeout = rawTimeout === "" ? LOCAL_COMMAND_TIMEOUT_SECONDS : Number(rawTimeout);
472
+ if (!Number.isInteger(timeout) || timeout < 1 || timeout > 1800) {
473
+ io.log(" The timeout must be a whole number from 1 to 1800.");
474
+ return null;
475
+ }
476
+ return { argv, timeout_seconds: timeout };
477
+ }
478
+ async function reviewHints(io, proposal, stored, providerChecks) {
479
+ const prompt = io.promptLine;
480
+ const edits = new Map();
481
+ for (const row of hintRows(proposal, stored, providerChecks)) {
482
+ const proposed = row.proposed === null ? null : hintFrom(row.proposed);
483
+ const newProposal = proposed !== null && (row.stored === null || !hintEqual(row.stored, proposed));
484
+ if (row.stored === null && !newProposal)
485
+ continue;
486
+ const letters = [
487
+ ...(row.stored ? ["[k]eep stored"] : []),
488
+ ...(newProposal ? ["[a]pply proposed"] : []),
489
+ "[e]dit",
490
+ ...(row.stored ? ["[d]rop stored"] : ["[i]gnore"]),
491
+ ];
492
+ const answer = (await prompt(`Hint for ${terminalSafe(row.check)} — ${letters.join(", ")} (Enter leaves it untouched): `))
493
+ .trim()
494
+ .toLowerCase();
495
+ if (answer === "" || answer === "k" || answer === "keep" || answer === "i" || answer === "ignore")
496
+ continue;
497
+ if ((answer === "a" || answer === "apply") && newProposal && proposed !== null) {
498
+ edits.set(row.check, proposed);
499
+ }
500
+ else if ((answer === "d" || answer === "drop") && row.stored !== null) {
501
+ io.log(` Removal requested: the stored hint for ${terminalSafe(row.check)}.`);
502
+ edits.set(row.check, null);
503
+ }
504
+ else if (answer === "e" || answer === "edit") {
505
+ const typed = await typedHint(prompt, io);
506
+ if (typed !== null)
507
+ edits.set(row.check, typed);
508
+ }
509
+ else {
510
+ io.log(" Not recognized; the hint is left untouched.");
511
+ }
512
+ }
513
+ // Restating the stored hint is not an edit.
514
+ for (const [check, hint] of [...edits]) {
515
+ const current = stored?.reproduction_hints?.get(check) ?? null;
516
+ if (hint === null ? current === null : current !== null && hintEqual(hint, current))
517
+ edits.delete(check);
518
+ }
519
+ return edits.size > 0 ? edits : undefined;
520
+ }
521
+ /** Read hand-typed relative paths (comma separated); `null` when any is unsafe. */
522
+ function parsePathList(line) {
523
+ const items = line.split(",").map((p) => p.trim()).filter((p) => p !== "");
524
+ if (items.length === 0 || items.length > MAX_DEPENDENCY_INSTALL_LOCKFILES)
525
+ return null;
526
+ if (items.some((p) => !isSafeRepoRelativePath(p)) || new Set(items).size !== items.length)
527
+ return null;
528
+ return items;
529
+ }
530
+ /** Ask for one entry by hand: directory, lockfiles, then the command as words. `null` cancels. */
531
+ async function typedDependencyEntry(prompt, io, initial) {
532
+ const cwdAnswer = (await prompt(`Directory to run in, relative to the repository root ("." is the root)${initial ? ` (Enter keeps ${terminalSafe(initial.cwd)})` : ""}: `)).trim();
533
+ const cwd = cwdAnswer === "" && initial ? initial.cwd : cwdAnswer;
534
+ if (!isSafeRepoRelativePath(cwd, { allowRoot: true })) {
535
+ io.log(" A directory must be repository-relative, with no .., backslash, colon, or leading /.");
536
+ return null;
537
+ }
538
+ const lockAnswer = (await prompt(`Lockfiles, relative to the repository root, comma separated${initial ? ` (Enter keeps ${safeList(initial.lockfiles)})` : ""}: `)).trim();
539
+ const lockfiles = lockAnswer === "" && initial ? [...initial.lockfiles] : parsePathList(lockAnswer);
540
+ if (lockfiles === null) {
541
+ io.log(` Give 1 to ${MAX_DEPENDENCY_INSTALL_LOCKFILES} distinct repository-relative file paths.`);
542
+ return null;
543
+ }
544
+ const argvAnswer = await prompt(`Install command words, space separated, no shell syntax${initial ? " (Enter keeps the current command)" : ""}: `);
545
+ const argv = argvAnswer.trim() === "" && initial ? [...initial.argv] : parseHintWords(argvAnswer);
546
+ if (argv === null) {
547
+ io.log(` A command needs 1 to ${MAX_HINT_WORDS} words of at most ${MAX_HINT_WORD_CHARS} characters.`);
548
+ return null;
549
+ }
550
+ const admitted = admitDependencyInstallDeclarations([{ cwd, argv, lockfiles }]);
551
+ if (admitted.entries.length !== 1) {
552
+ io.log(" That entry cannot be stored. Nothing was changed.");
553
+ return null;
554
+ }
555
+ return admitted.entries[0];
556
+ }
557
+ /**
558
+ * BAPI-1551 — ask about dependency refresh. Returns the complete new list, or
559
+ * `undefined` when the owner leaves the stored list untouched. Declining a
560
+ * proposal never clears a stored entry.
561
+ */
562
+ async function reviewDependencyInstall(io, proposal, stored) {
563
+ const prompt = io.promptLine;
564
+ const storedList = (stored?.dependency_install ?? []).map(entryOf);
565
+ const proposals = newDependencyProposals(proposal, stored);
566
+ if (storedList.length === 0 && proposals.length === 0 && (proposal.dependencyInstallNotes?.length ?? 0) === 0) {
567
+ return undefined;
568
+ }
569
+ const letters = [
570
+ ...(storedList.length > 0 ? ["[k]eep stored entries as they are"] : []),
571
+ ...(proposals.length > 0 ? ["[a]pply every proposal", "[i]gnore the proposals (stored entries stay untouched)"] : []),
572
+ "[e]dit — decide each entry one at a time, or add one by hand",
573
+ ...(storedList.length > 0 ? ["[r]emove every stored entry"] : []),
574
+ ];
575
+ let choice = null;
576
+ for (let attempt = 0; attempt < MAX_REVIEW_ATTEMPTS && choice === null; attempt++) {
577
+ const a = (await prompt(`Dependency refresh — ${letters.join(", ")} (Enter leaves it untouched): `)).trim().toLowerCase();
578
+ if (a === "")
579
+ choice = "keep";
580
+ else if ((a === "k" || a === "keep") && storedList.length > 0)
581
+ choice = "keep";
582
+ else if ((a === "a" || a === "apply") && proposals.length > 0)
583
+ choice = "apply";
584
+ else if ((a === "i" || a === "ignore") && proposals.length > 0)
585
+ choice = "ignore";
586
+ else if (a === "e" || a === "edit")
587
+ choice = "edit";
588
+ else if ((a === "r" || a === "remove") && storedList.length > 0)
589
+ choice = "remove";
590
+ else
591
+ io.log(" Choose one of the listed letters, or press Enter.");
592
+ }
593
+ if (choice === "ignore") {
594
+ io.log(` Ignored ${proposals.length} proposal(s). Stored entries are untouched; nothing was removed.`);
595
+ }
596
+ if (choice === null || choice === "keep" || choice === "ignore")
597
+ return undefined;
598
+ if (choice === "remove") {
599
+ io.log(` Removal requested for ${storedList.length} stored dependency refresh entr${storedList.length === 1 ? "y" : "ies"}.`);
600
+ return (await yes(prompt, "Remove every stored dependency refresh entry? [y/N]: ")) ? [] : undefined;
601
+ }
602
+ let result = storedList.map(entryOf);
603
+ const place = (entry) => {
604
+ const identity = dependencyInstallEntryIdentity(entry);
605
+ const at = result.findIndex((e) => dependencyInstallEntryIdentity(e) === identity);
606
+ if (at === -1)
607
+ result.push(entry);
608
+ else
609
+ result[at] = entry;
610
+ };
611
+ if (choice === "apply") {
612
+ for (const candidate of proposals)
613
+ place(entryOf(candidate));
614
+ }
615
+ else {
616
+ for (const candidate of proposals) {
617
+ const where = candidate.cwd === "." ? "the repository root" : terminalSafe(candidate.cwd);
618
+ const a = (await prompt(`Proposed for ${where} (${safeList(candidate.lockfiles)}): ${candidate.argv.map(terminalSafe).join(" ")} — ` +
619
+ "[a]pply, [e]dit, or Enter to ignore: ")).trim().toLowerCase();
620
+ if (a === "a" || a === "apply")
621
+ place(entryOf(candidate));
622
+ else if (a === "e" || a === "edit") {
623
+ const typed = await typedDependencyEntry(prompt, io, entryOf(candidate));
624
+ if (typed !== null)
625
+ place(typed);
626
+ }
627
+ else
628
+ io.log(" Ignored that proposal. Stored entries are untouched.");
629
+ }
630
+ for (const entry of storedList) {
631
+ const where = entry.cwd === "." ? "the repository root" : terminalSafe(entry.cwd);
632
+ const a = (await prompt(`Stored entry for ${where} — [e]dit, [r]emove, or Enter to keep: `)).trim().toLowerCase();
633
+ const identity = dependencyInstallEntryIdentity(entry);
634
+ if (a === "r" || a === "remove") {
635
+ io.log(` Removal requested: the stored entry for ${where}.`);
636
+ result = result.filter((e) => dependencyInstallEntryIdentity(e) !== identity);
637
+ }
638
+ else if (a === "e" || a === "edit") {
639
+ const typed = await typedDependencyEntry(prompt, io, entry);
640
+ if (typed !== null) {
641
+ result = result.filter((e) => dependencyInstallEntryIdentity(e) !== identity);
642
+ place(typed);
643
+ }
644
+ }
645
+ }
646
+ while (result.length < MAX_DEPENDENCY_INSTALL_ENTRIES && (await yes(prompt, "Add a dependency refresh entry by hand? [y/N]: "))) {
647
+ const typed = await typedDependencyEntry(prompt, io);
648
+ if (typed !== null)
649
+ place(typed);
650
+ }
651
+ }
652
+ if (result.length > MAX_DEPENDENCY_INSTALL_ENTRIES) {
653
+ io.log(` At most ${MAX_DEPENDENCY_INSTALL_ENTRIES} entries can be stored. Nothing was changed.`);
654
+ return undefined;
655
+ }
656
+ return dependencyInstallEqual(result, storedList) ? undefined : result;
657
+ }
658
+ /** BAPI-1551 — ask about CI database behavior. `undefined` leaves the stored value untouched. */
659
+ async function reviewCiDatabase(io, proposal, stored) {
660
+ const current = storedCiDatabase(stored);
661
+ const proposed = proposedCiDatabase(proposal);
662
+ const offer = proposed !== CI_DATABASE_DEFAULT && proposed !== current ? proposed : null;
663
+ if (current === CI_DATABASE_DEFAULT && offer === null)
664
+ return undefined;
665
+ const answer = (await io.promptLine(`CI database behavior — ${offer ? `[a]pply proposed (${offer}), ` : ""}or type none, provided, or unknown ` +
666
+ "(unknown clears it) (Enter leaves it untouched): ")).trim().toLowerCase();
667
+ if (answer === "") {
668
+ if (offer)
669
+ io.log(" Ignored the proposal. The stored value is untouched.");
670
+ return undefined;
671
+ }
672
+ const chosen = (answer === "a" || answer === "apply") && offer ? offer : answer;
673
+ if (!isCiDatabase(chosen)) {
674
+ io.log(" Not recognized; the CI database behavior is left untouched.");
675
+ return undefined;
676
+ }
677
+ return chosen === current ? undefined : chosen;
678
+ }
679
+ /**
680
+ * Show the review surface and collect the owner's decisions. Requires a
681
+ * terminal. Returns what changed; nothing is stored here.
682
+ */
683
+ export async function reviewDiscoveredSettings(io, proposal, stored, providerChecks) {
684
+ renderSettingsReview(io, proposal, stored, providerChecks, true);
685
+ const edit = {};
686
+ const workerEnv = await reviewWorkerEnv(io, proposal, stored);
687
+ if (workerEnv !== undefined)
688
+ edit.workerEnv = workerEnv;
689
+ const reproduce = await reviewHints(io, proposal, stored, providerChecks);
690
+ if (reproduce !== undefined)
691
+ edit.reproduce = reproduce;
692
+ Object.assign(edit, await reviewDeclarations(io, proposal, stored));
693
+ return edit;
694
+ }
695
+ /**
696
+ * BAPI-1551 — collect only the dependency-refresh and CI-database decisions.
697
+ * Used beside the full review, and by setup when a confirmed gate is kept and
698
+ * discovery proposes a declaration that is not stored yet.
699
+ */
700
+ export async function reviewDeclarations(io, proposal, stored) {
701
+ const edit = {};
702
+ if (!hasDeclarationsToReview(proposal, stored))
703
+ return edit;
704
+ const dependencyInstall = await reviewDependencyInstall(io, proposal, stored);
705
+ if (dependencyInstall !== undefined)
706
+ edit.dependencyInstall = dependencyInstall;
707
+ const ciDatabase = await reviewCiDatabase(io, proposal, stored);
708
+ if (ciDatabase !== undefined)
709
+ edit.ciDatabase = ciDatabase;
710
+ return edit;
711
+ }
712
+ /** BAPI-1551 — print only the declaration groups (setup's advisory offer). */
713
+ export function renderDeclarationsOnly(io, proposal, stored, showValues) {
714
+ renderDeclarationsReview(io, proposal, stored, showValues);
715
+ io.log("");
716
+ }
717
+ /** Name-only lines describing what an edit changes, for the gate comparison. */
718
+ export function describeSettingsEdit(edit, stored) {
719
+ const lines = [];
720
+ if (edit.workerEnv !== undefined) {
721
+ const before = stored?.worker_env ?? [];
722
+ const added = edit.workerEnv.filter((e) => !before.some((b) => b.name === e.name)).map((e) => e.name);
723
+ const changed = edit.workerEnv
724
+ .filter((e) => before.some((b) => b.name === e.name && !sameEntry(b, e)))
725
+ .map((e) => e.name);
726
+ const removed = before.filter((b) => !(edit.workerEnv ?? []).some((e) => e.name === b.name)).map((b) => b.name);
727
+ const parts = [
728
+ added.length > 0 ? `added ${safeList(added)}` : "",
729
+ changed.length > 0 ? `changed ${safeList(changed)}` : "",
730
+ removed.length > 0 ? `removal requested for ${safeList(removed)}` : "",
731
+ ].filter((p) => p !== "");
732
+ lines.push(` worker variables: ${edit.workerEnv.length} after this change (${parts.join("; ")})`);
733
+ }
734
+ for (const [check, hint] of edit.reproduce ?? []) {
735
+ lines.push(hint === null
736
+ ? ` reproduction hint for ${terminalSafe(check)}: removal requested`
737
+ : ` reproduction hint for ${terminalSafe(check)}: set (hint only — never changes gating)`);
738
+ }
739
+ if (edit.dependencyInstall !== undefined) {
740
+ const where = edit.dependencyInstall.map((e) => (e.cwd === "." ? "repository root" : e.cwd));
741
+ lines.push(edit.dependencyInstall.length === 0
742
+ ? " dependency refresh: removal requested for every stored entry"
743
+ : ` dependency refresh: ${edit.dependencyInstall.length} entr${edit.dependencyInstall.length === 1 ? "y" : "ies"} (${safeList(where)})`);
744
+ }
745
+ if (edit.ciDatabase !== undefined) {
746
+ lines.push(edit.ciDatabase === CI_DATABASE_DEFAULT
747
+ ? " CI database behavior: reset to unknown"
748
+ : ` CI database behavior: ${edit.ciDatabase}`);
749
+ }
750
+ return lines;
751
+ }