@bridge_gpt/mcp-server 0.2.74 → 0.2.76

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 (102) hide show
  1. package/README.md +14 -7
  2. package/build/agent-launchers/prompt.js +9 -21
  3. package/build/agents.generated.js +6 -6
  4. package/build/authored-plan.js +542 -0
  5. package/build/bridge-permissions.js +8 -0
  6. package/build/codex-auto-recovery.js +25 -7
  7. package/build/commands.generated.js +7 -7
  8. package/build/conductor/bridge-api-client.js +807 -52
  9. package/build/conductor/declare-blocked.js +4 -0
  10. package/build/conductor/driver-pass.js +8 -0
  11. package/build/conductor/epic-implementer-cli.js +341 -96
  12. package/build/conductor/epic-server-journal.js +13 -0
  13. package/build/conductor/epic-server-recipe.js +15 -5
  14. package/build/conductor/epic-server-runtime.js +163 -45
  15. package/build/conductor/epic-server.js +13 -6
  16. package/build/conductor/gate-discovery.js +209 -9
  17. package/build/conductor/gate-settings-review.js +7 -11
  18. package/build/conductor/install-doctor.js +30 -2
  19. package/build/conductor/launch-plan.js +58 -12
  20. package/build/conductor/local-merge.js +54 -12
  21. package/build/conductor/open-decision-phrases.js +50 -0
  22. package/build/conductor/pr-ci-producer.js +12 -3
  23. package/build/conductor/prerequisite-inputs.js +181 -14
  24. package/build/conductor/readiness-sections.js +46 -13
  25. package/build/conductor/readiness.js +3 -40
  26. package/build/conductor/recovery-cli.js +12 -12
  27. package/build/conductor/repository-workflow-remedy.js +147 -7
  28. package/build/conductor/ui-readiness.js +224 -0
  29. package/build/conductor/wait-run-attention.js +9 -4
  30. package/build/conductor/wait-run-cli.js +9 -2
  31. package/build/connect-github-api.js +18 -0
  32. package/build/connect-github.js +35 -18
  33. package/build/docs.generated.js +3 -3
  34. package/build/drive-epic.js +787 -37
  35. package/build/epic-ci-workflow.js +3 -2
  36. package/build/epic-implementer-bin.js +200 -66
  37. package/build/epic-implementer-bundle-cli.js +61 -0
  38. package/build/epic-implementer-claude-hook-bin.js +1 -1
  39. package/build/epic-implementer-env.js +3 -4
  40. package/build/epic-integration-pr.js +5 -2
  41. package/build/epic-launch-context.js +8 -1
  42. package/build/epic-shared/cut-protocol.js +55 -3
  43. package/build/executor/completion-contract.js +24 -1
  44. package/build/executor/failure-reason-codes.js +2 -0
  45. package/build/executor/gate-qualification-job.js +193 -23
  46. package/build/executor/gate-qualification-tests-ran.js +232 -0
  47. package/build/executor/integration-job.js +56 -2
  48. package/build/executor/job-runner.js +13 -723
  49. package/build/executor/job-type-wrappers.js +734 -0
  50. package/build/executor/merge-job.js +45 -1
  51. package/build/executor/permissions.js +187 -2
  52. package/build/executor/preflight.js +6 -2
  53. package/build/executor/process-containment.js +8 -1
  54. package/build/executor/provider-checks.js +28 -5
  55. package/build/executor/reconcile-overlap-job.js +70 -17
  56. package/build/executor/required-verification.js +28 -2
  57. package/build/executor/required-work-ledger.js +7 -2
  58. package/build/executor/resume-pre-spawn.js +32 -8
  59. package/build/executor/runner.js +30 -5
  60. package/build/executor/types.js +9 -0
  61. package/build/executor/worker-database.js +6 -1
  62. package/build/executor/worker-guard-hook.js +24 -2
  63. package/build/executor/worktree.js +12 -1
  64. package/build/generated/ticket-status.js +20 -0
  65. package/build/index.js +627 -551
  66. package/build/init.js +16 -0
  67. package/build/install-bridge-conductor-answers.js +32 -1
  68. package/build/install-bridge-conductor-apply.js +21 -3
  69. package/build/install-bridge-conductor-assessment.js +185 -12
  70. package/build/install-bridge-conductor-compact.js +2 -0
  71. package/build/install-bridge-conductor-contracts.js +9 -1
  72. package/build/install-bridge-conductor-gate.js +257 -80
  73. package/build/install-bridge-conductor-setup.js +106 -6
  74. package/build/install-bridge-conductor-trial-report.js +170 -0
  75. package/build/install-bridge-conductor.js +740 -124
  76. package/build/mcp-host-config.js +54 -37
  77. package/build/phase-context-git-probe.js +16 -0
  78. package/build/pipelines.generated.js +15 -15
  79. package/build/plan-execution-ledger.js +27 -0
  80. package/build/plan-generation.js +17 -0
  81. package/build/plane/plane-freshness.js +43 -26
  82. package/build/printed-remedy-commands.js +62 -0
  83. package/build/readme.generated.js +1 -1
  84. package/build/repository-toolchains.js +11 -5
  85. package/build/scripts/saved-commands-config-field-driver.js +65 -0
  86. package/build/secret-redaction.js +3 -0
  87. package/build/setup-epic.js +51 -9
  88. package/build/test-support/create-preview-world.js +232 -0
  89. package/build/test-support/executor-source-files.js +1 -1
  90. package/build/ticket-delivery.js +65 -0
  91. package/build/v2-readiness-requirements.js +13 -4
  92. package/build/version.generated.js +3 -3
  93. package/build/worker-guard-hook-bin.js +2 -2
  94. package/build/worktree-core.js +51 -7
  95. package/docs/EPIC-IMPLEMENTER.md +83 -4
  96. package/docs/epic-implementer/getting-started.md +1 -1
  97. package/docs/install/github-app.md +79 -92
  98. package/package.json +1 -1
  99. package/pipelines/implement-ticket.json +2 -2
  100. package/build/conductor/epic-reconcile.js +0 -603
  101. package/build/conductor/epic-runtime.js +0 -2020
  102. package/build/conductor/epic-state.js +0 -774
@@ -36,6 +36,56 @@ import { boundedResult, ensurePrivateDirectory, epicServerLoginFilePath, epicSer
36
36
  import { buildEpicServerCommandEnv, formatLoginFile, isOwnershipInspectionSupported, parseSeedOutput, readProcessStartTime, stopOwnedProcessGroup, verifyOwnedProcess, } from "./epic-server-processes.js";
37
37
  import { dropTurnDatabase, isCurrentTurnDatabase, provisionTurnDatabase, sweepOwnLeftoverDatabases, } from "./epic-server-database.js";
38
38
  import { epicServerRecipeDigest, proofCoversStart, substituteRecipeArgv, validateEpicServerProof, validateEpicServerRecipe, EPIC_SERVER_PROOF_VERSION, } from "./epic-server-recipe.js";
39
+ function watchStartupExit(child) {
40
+ let latched = null;
41
+ let resolveExit = () => undefined;
42
+ const exited = new Promise((resolve) => {
43
+ resolveExit = resolve;
44
+ });
45
+ const latch = (exit) => {
46
+ if (latched !== null)
47
+ return;
48
+ latched = exit;
49
+ resolveExit(exit);
50
+ };
51
+ const onExit = (code, signal) => {
52
+ child.off("error", onError);
53
+ latch({ code: typeof code === "number" ? code : null, signal: typeof signal === "string" ? signal : null });
54
+ };
55
+ // A spawn error carries raw text that may hold secrets: it is never retained.
56
+ const onError = () => {
57
+ child.off("exit", onExit);
58
+ latch({ code: null, signal: null });
59
+ };
60
+ child.once("exit", onExit);
61
+ child.once("error", onError);
62
+ // An exit that completed before the listeners attached is seeded from the child.
63
+ if (typeof child.exitCode === "number" || typeof child.signalCode === "string") {
64
+ child.off("exit", onExit);
65
+ child.off("error", onError);
66
+ latch({
67
+ code: typeof child.exitCode === "number" ? child.exitCode : null,
68
+ signal: typeof child.signalCode === "string" ? child.signalCode : null,
69
+ });
70
+ }
71
+ return {
72
+ latched: () => latched,
73
+ exited,
74
+ dispose: () => {
75
+ child.off("exit", onExit);
76
+ child.off("error", onError);
77
+ },
78
+ };
79
+ }
80
+ /** Race a promise against app exit; the loser's eventual rejection is always handled. */
81
+ async function raceStartupExit(work, watcher) {
82
+ work.catch(() => undefined);
83
+ const winner = await Promise.race([
84
+ work.then((value) => ({ exited: false, value })),
85
+ watcher.exited.then(() => ({ exited: true })),
86
+ ]);
87
+ return winner;
88
+ }
39
89
  async function resolveCredentials(recipe, deps) {
40
90
  const out = {};
41
91
  for (const [name, { ref, key }] of Object.entries(recipe.credential_refs)) {
@@ -66,49 +116,80 @@ async function runSteps(steps, cwd, env, port, ctx) {
66
116
  }
67
117
  return "ok";
68
118
  }
69
- async function awaitReady(ctx, env, cwd) {
119
+ async function awaitReady(ctx, env, cwd, watcher) {
70
120
  const ready = ctx.recipe.ready;
71
121
  const deadline = Date.now() + ready.timeout_seconds * 1000;
72
122
  const base = epicServerLoopbackUrl(ctx.port);
123
+ const exitedResult = () => {
124
+ const exit = watcher.latched();
125
+ return exit === null ? null : { outcome: "app_exited", exit };
126
+ };
73
127
  while (Date.now() < deadline) {
74
128
  if (ctx.signal?.aborted)
75
- return "cancelled";
129
+ return { outcome: "cancelled" };
130
+ const early = exitedResult();
131
+ if (early !== null)
132
+ return early;
76
133
  if (ready.kind === "url") {
77
- const res = await ctx.deps.http.get(`${base}${ready.path}`, Math.min(5_000, Math.max(1, deadline - Date.now())));
134
+ const probe = await raceStartupExit(ctx.deps.http.get(`${base}${ready.path}`, Math.min(5_000, Math.max(1, deadline - Date.now()))), watcher);
135
+ if (probe.exited)
136
+ return exitedResult() ?? { outcome: "app_exited" };
137
+ const res = probe.value;
78
138
  if (res !== null) {
79
139
  if (res.status >= 200 && res.status < 300)
80
- return "ok";
140
+ return exitedResult() ?? { outcome: "ok" };
81
141
  if (res.status >= 300 && res.status < 400) {
82
142
  // A redirect is ready only when it stays on the run's own address.
83
143
  if (res.location === null)
84
- return "ready_redirect_refused";
144
+ return { outcome: "ready_redirect_refused" };
85
145
  let target;
86
146
  try {
87
147
  target = new URL(res.location, base);
88
148
  }
89
149
  catch {
90
- return "ready_redirect_refused";
150
+ return { outcome: "ready_redirect_refused" };
91
151
  }
92
- return target.origin === base ? "ok" : "ready_redirect_refused";
152
+ return target.origin === base ? (exitedResult() ?? { outcome: "ok" }) : { outcome: "ready_redirect_refused" };
93
153
  }
94
154
  }
95
155
  }
96
156
  else {
97
- const outcome = await ctx.deps.runCommand(substituteRecipeArgv(ready.argv, ctx.port), {
98
- cwd,
99
- env,
100
- timeoutMs: Math.max(1, Math.min(10_000, deadline - Date.now())),
101
- captureStdout: false,
102
- ...(ctx.signal ? { signal: ctx.signal } : {}),
103
- });
104
- if (outcome.kind === "ok")
105
- return "ok";
106
- if (outcome.kind === "cancelled")
107
- return "cancelled";
157
+ // Each probe gets its own signal, chained to the run's, so app exit can stop
158
+ // a pending command without being mistaken for a cancellation.
159
+ const probeController = new AbortController();
160
+ const onParentAbort = () => probeController.abort();
161
+ if (ctx.signal?.aborted)
162
+ probeController.abort();
163
+ else
164
+ ctx.signal?.addEventListener("abort", onParentAbort, { once: true });
165
+ try {
166
+ const probe = await raceStartupExit(ctx.deps.runCommand(substituteRecipeArgv(ready.argv, ctx.port), {
167
+ cwd,
168
+ env,
169
+ timeoutMs: Math.max(1, Math.min(10_000, deadline - Date.now())),
170
+ captureStdout: false,
171
+ signal: probeController.signal,
172
+ }), watcher);
173
+ if (probe.exited) {
174
+ probeController.abort();
175
+ return exitedResult() ?? { outcome: "app_exited" };
176
+ }
177
+ const outcome = probe.value;
178
+ if (outcome.kind === "ok")
179
+ return exitedResult() ?? { outcome: "ok" };
180
+ if (outcome.kind === "cancelled") {
181
+ return exitedResult() ?? { outcome: "cancelled" };
182
+ }
183
+ }
184
+ finally {
185
+ ctx.signal?.removeEventListener("abort", onParentAbort);
186
+ }
108
187
  }
109
- await ctx.deps.sleep(Math.min(500, Math.max(1, deadline - Date.now())));
188
+ const slept = await raceStartupExit(ctx.deps.sleep(Math.min(500, Math.max(1, deadline - Date.now()))), watcher);
189
+ if (slept.exited)
190
+ return exitedResult() ?? { outcome: "app_exited" };
110
191
  }
111
- return "ready_timeout";
192
+ return exitedResult() ?? { outcome: "ready_timeout" };
112
193
  }
113
194
  /**
114
195
  * Replay the recipe against one exact head: a fresh detached serving checkout,
@@ -119,7 +200,12 @@ async function awaitReady(ctx, env, cwd) {
119
200
  export async function runServingPipeline(ctx, sha, generation) {
120
201
  const { deps, paths, recipe } = ctx;
121
202
  const turn = { generation, sha, app: null, database: null, loginFile: null };
122
- const fail = (reason) => ({ ok: false, reason, partial: turn });
203
+ const fail = (reason, exit) => ({
204
+ ok: false,
205
+ reason,
206
+ partial: turn,
207
+ ...(exit !== undefined ? { exit } : {}),
208
+ });
123
209
  // A fresh checkout for every head: ignored artifacts and generated files from
124
210
  // an earlier turn can never reach another worker's verification.
125
211
  const worktree = paths.servingWorktree;
@@ -190,17 +276,27 @@ export async function runServingPipeline(ctx, sha, generation) {
190
276
  const started = deps.startApp(substituteRecipeArgv(recipe.start.argv, ctx.port), { cwd: worktree, env });
191
277
  if (started === null)
192
278
  return fail("start_failed");
193
- const startedAt = await readProcessStartTime(started.pid, deps.proc);
194
- if (startedAt === null) {
195
- // The app died at once, or its identity cannot be read: never signalled blind.
196
- return fail("start_failed");
279
+ // Latch termination from the moment the child exists, before any await, so no
280
+ // exit shape between here and readiness can be missed.
281
+ const watcher = watchStartupExit(started.child);
282
+ try {
283
+ const startedAt = await readProcessStartTime(started.pid, deps.proc);
284
+ if (startedAt === null) {
285
+ // The app died at once, or its identity cannot be read: never signalled blind.
286
+ return fail("start_failed");
287
+ }
288
+ turn.app = { pid: started.pid, started_at: startedAt, child: started.child };
289
+ await ctx.recordOwnership({ app: { pid: started.pid, started_at: startedAt } });
290
+ const ready = await awaitReady(ctx, env, worktree, watcher);
291
+ if (ready.outcome !== "ok")
292
+ return fail(ready.outcome, ready.exit);
293
+ return { ok: true, turn };
294
+ }
295
+ finally {
296
+ // Success, failure, and cancellation all hand over cleanly: the post-ready
297
+ // `watchApp` listener (or `teardownTurn`) takes it from here.
298
+ watcher.dispose();
197
299
  }
198
- turn.app = { pid: started.pid, started_at: startedAt, child: started.child };
199
- await ctx.recordOwnership({ app: { pid: started.pid, started_at: startedAt } });
200
- const ready = await awaitReady(ctx, env, worktree);
201
- if (ready !== "ok")
202
- return fail(ready);
203
- return { ok: true, turn };
204
300
  }
205
301
  /**
206
302
  * Tear one turn down: stop the app (guarded), drop its database, remove its
@@ -238,15 +334,12 @@ export async function teardownTurn(ctx, turn) {
238
334
  });
239
335
  return clean;
240
336
  }
241
- // ---------------------------------------------------------------------------
242
- // Recipe, proof, and ownership files
243
- // ---------------------------------------------------------------------------
244
337
  export async function readRecipe(paths, fs) {
245
338
  const raw = await readPrivateJson(fs, paths.recipe);
246
339
  if (raw === null)
247
- return null;
340
+ return { ok: false, detail: "recipe file is missing or unreadable" };
248
341
  const validated = validateEpicServerRecipe(raw);
249
- return validated.ok ? validated.recipe : null;
342
+ return validated.ok ? { ok: true, recipe: validated.recipe } : { ok: false, detail: validated.error };
250
343
  }
251
344
  export async function readProof(paths, fs) {
252
345
  return validateEpicServerProof(await readPrivateJson(fs, paths.proof));
@@ -314,6 +407,14 @@ export async function recoverAbandonedResources(paths, deps) {
314
407
  }
315
408
  return "retained";
316
409
  }
410
+ /** Format startup-exit evidence. Explicit null checks keep exit code 0 from being lost. */
411
+ function formatStartupExit(exit) {
412
+ if (exit !== undefined && exit.code !== null)
413
+ return `app exited with code ${exit.code}`;
414
+ if (exit !== undefined && exit.signal !== null)
415
+ return `app exited on signal ${exit.signal}`;
416
+ return "app exited without an exit code or signal";
417
+ }
317
418
  /**
318
419
  * Prove one recipe revision against the exact epic head: an exclusively owned
319
420
  * run of the serving pipeline, fully cleaned up before returning. A matching
@@ -323,9 +424,10 @@ export async function proveRecipe(input, deps) {
323
424
  const { paths } = input;
324
425
  if (!isOwnershipInspectionSupported(deps.proc.platform))
325
426
  return { ok: false, reason: "inspection_unsupported" };
326
- const recipe = await readRecipe(paths, deps.fs);
327
- if (recipe === null)
328
- return { ok: false, reason: "recipe_invalid" };
427
+ const recipeRead = await readRecipe(paths, deps.fs);
428
+ if (!recipeRead.ok)
429
+ return { ok: false, reason: "recipe_invalid", detail: recipeRead.detail };
430
+ const recipe = recipeRead.recipe;
329
431
  const live = await readEpicServerLiveState(paths.state, input.runId, { fs: deps.fs, probe: { identity: async (pid) => {
330
432
  const s = await readProcessStartTime(pid, deps.proc);
331
433
  return s === null ? null : { startedAt: s };
@@ -392,8 +494,11 @@ export async function proveRecipe(input, deps) {
392
494
  if (clean)
393
495
  await removeFileQuietly(deps.fs, paths.ownership);
394
496
  await removeFileQuietly(deps.fs, paths.claim);
395
- if (!served.ok)
396
- return { ok: false, reason: served.reason };
497
+ if (!served.ok) {
498
+ return served.reason === "app_exited"
499
+ ? { ok: false, reason: served.reason, detail: formatStartupExit(served.exit) }
500
+ : { ok: false, reason: served.reason };
501
+ }
397
502
  if (!clean)
398
503
  return { ok: false, reason: "cleanup_incomplete" };
399
504
  const proof = {
@@ -870,7 +975,19 @@ export class EpicServerHelper {
870
975
  this.turn = served.partial;
871
976
  await this.endTurn();
872
977
  await this.writeState();
873
- await this.options.journal.append("serving_failed", { generation, ticket: next.ticket, sha: next.head, reason: served.reason, outcome: "failed" });
978
+ await this.options.journal.append("serving_failed", {
979
+ generation,
980
+ ticket: next.ticket,
981
+ sha: next.head,
982
+ reason: served.reason,
983
+ outcome: "failed",
984
+ ...(served.reason === "app_exited" && served.exit !== undefined
985
+ ? {
986
+ ...(served.exit.code !== null ? { exit_code: served.exit.code } : {}),
987
+ ...(served.exit.signal !== null ? { exit_signal: served.exit.signal } : {}),
988
+ }
989
+ : {}),
990
+ });
874
991
  if (!next.cancelled) {
875
992
  next.cancelled = true;
876
993
  next.respond({ ok: false, outcome: "unavailable", reason: served.reason === "cancelled" ? "build_timeout" : served.reason });
@@ -996,9 +1113,10 @@ export async function startEpicServerHelper(input, deps) {
996
1113
  const { paths } = input;
997
1114
  if (!isOwnershipInspectionSupported(rt.proc.platform))
998
1115
  return { ok: false, reason: "inspection_unsupported" };
999
- const recipe = await readRecipe(paths, rt.fs);
1000
- if (recipe === null)
1001
- return { ok: false, reason: "recipe_invalid" };
1116
+ const recipeRead = await readRecipe(paths, rt.fs);
1117
+ if (!recipeRead.ok)
1118
+ return { ok: false, reason: "recipe_invalid", detail: recipeRead.detail };
1119
+ const recipe = recipeRead.recipe;
1002
1120
  if (!proofCoversStart(await readProof(paths, rt.fs), recipe, input.epicHead))
1003
1121
  return { ok: false, reason: "not_proven" };
1004
1122
  const deadline = Date.now() + recipe.timing.start_seconds * 1000;
@@ -409,8 +409,11 @@ async function runProve(deps, cmd) {
409
409
  }
410
410
  const outcome = await proveRecipe({ paths, repoRoot, epicHead: cmd.head, runId: cmd.epicRunId }, deps.runtime());
411
411
  if (!outcome.ok) {
412
- emit(deps, { outcome: "failed", verb: "prove", reason: outcome.reason });
413
- deps.stderr(`epic-server prove: failed (${outcome.reason}); the run continues with the epic server unavailable`);
412
+ // BAPI-1733: detail is closed-form evidence (a safe recipe field label or a
413
+ // formatted exit), only for these two reasons, and never a raw error or value.
414
+ const detail = (outcome.reason === "recipe_invalid" || outcome.reason === "app_exited") && outcome.detail !== undefined ? outcome.detail : undefined;
415
+ emit(deps, { outcome: "failed", verb: "prove", reason: outcome.reason, ...(detail !== undefined ? { detail } : {}) });
416
+ deps.stderr(`epic-server prove: failed (${outcome.reason}${detail !== undefined ? `: ${detail}` : ""}); the run continues with the epic server unavailable`);
414
417
  return 1;
415
418
  }
416
419
  emit(deps, { outcome: "proven", recipe_revision: outcome.proof.recipe_revision, epic_head: outcome.proof.epic_head });
@@ -428,8 +431,9 @@ async function runStart(deps, cmd) {
428
431
  }
429
432
  const outcome = await startEpicServerHelper({ paths, epicKey: cmd.epicKey, runId: cmd.epicRunId, repoName: mode.repoName, repoRoot, epicHead: cmd.head }, { runtime: deps.runtime(), launchHelper: deps.launchHelper });
430
433
  if (!outcome.ok) {
431
- emit(deps, { outcome: "failed", verb: "start", reason: outcome.reason });
432
- deps.stderr(`epic-server start: failed (${outcome.reason}); the run continues with the epic server unavailable`);
434
+ const detail = outcome.reason === "recipe_invalid" && outcome.detail !== undefined ? outcome.detail : undefined;
435
+ emit(deps, { outcome: "failed", verb: "start", reason: outcome.reason, ...(detail !== undefined ? { detail } : {}) });
436
+ deps.stderr(`epic-server start: failed (${outcome.reason}${detail !== undefined ? `: ${detail}` : ""}); the run continues with the epic server unavailable`);
433
437
  return 1;
434
438
  }
435
439
  emit(deps, {
@@ -584,9 +588,12 @@ async function runHelper(deps, cmd) {
584
588
  const nonce = deps.env.BRIDGE_EPIC_SERVER_INSTANCE_TAG;
585
589
  if (paths === null || typeof nonce !== "string" || !/^[0-9a-f]{64}$/.test(nonce))
586
590
  return 1;
587
- const recipe = await readRecipe(paths, rt.fs);
591
+ const recipeRead = await readRecipe(paths, rt.fs);
592
+ if (!recipeRead.ok)
593
+ return 1;
594
+ const recipe = recipeRead.recipe;
588
595
  const proof = validateEpicServerProof(await import("./epic-server-state.js").then((m) => m.readPrivateJson(rt.fs, paths.proof)));
589
- if (recipe === null || !proofCoversStart(proof, recipe, cmd.head))
596
+ if (!proofCoversStart(proof, recipe, cmd.head))
590
597
  return 1;
591
598
  const journal = new EpicServerJournal(paths.journal, cmd.epicRunId, rt.fs, rt.now);
592
599
  const helper = new EpicServerHelper({
@@ -59,7 +59,7 @@ import path from "node:path";
59
59
  import { LEGACY_EPIC_IMPLEMENTER_NODE_PATH_ENV } from "../epic-implementer-env.js";
60
60
  import { deriveDeclaredExtras } from "./declared-extras.js";
61
61
  import { MAX_MUST_ORDER_PATHS, canonicalMustOrderPaths, isValidMustOrderPath, } from "../dependency-install-declarations.js";
62
- import { TOOLCHAIN_CONTENT_FILES, installArgvForJavaScript, installArgvForPython, resolveRepositoryToolchains, } from "../repository-toolchains.js";
62
+ import { TOOLCHAIN_CONTENT_FILES, UNSUPPORTED_PYTHON_MANIFESTS, installArgvForJavaScript, installArgvForPython, resolveRepositoryToolchains, } from "../repository-toolchains.js";
63
63
  // ---------------------------------------------------------------------------
64
64
  // Bounds and fixed vocabularies
65
65
  // ---------------------------------------------------------------------------
@@ -1225,11 +1225,176 @@ export async function proposeWorkerDatabase(fsSeam) {
1225
1225
  }
1226
1226
  return undefined;
1227
1227
  }
1228
+ /**
1229
+ * BAPI-1698 — the ONE pip install discovery may propose: a checkout-local
1230
+ * virtual environment, recreated from scratch, then `requirements.txt` installed
1231
+ * into it with that environment's own interpreter. It never touches whatever
1232
+ * Python is first on the executor's `PATH` beyond creating the environment.
1233
+ */
1234
+ export const PIP_BOOTSTRAP_COMMAND = "python3 -m venv --clear .venv && .venv/bin/python -m pip install -r requirements.txt";
1235
+ export const PIP_BOOTSTRAP_ARGV = Object.freeze(["sh", "-c", PIP_BOOTSTRAP_COMMAND]);
1236
+ const VENV_IGNORE_DECLARATIONS = new Set([".venv", ".venv/", "/.venv", "/.venv/"]);
1237
+ /** A minimal gitignore glob test for ONE path segment: `*`, `?`, and `[...]`. */
1238
+ function globSegmentMatches(pattern, name) {
1239
+ let source = "^";
1240
+ for (let i = 0; i < pattern.length; i += 1) {
1241
+ const ch = pattern[i];
1242
+ if (ch === "*")
1243
+ source += "[^/]*";
1244
+ else if (ch === "?")
1245
+ source += "[^/]";
1246
+ else if (ch === "[") {
1247
+ const end = pattern.indexOf("]", i + 1);
1248
+ if (end === -1)
1249
+ return null;
1250
+ const body = pattern.slice(i + 1, end).replace(/^!/, "^");
1251
+ if (/[\\\]]/.test(body))
1252
+ return null;
1253
+ source += `[${body}]`;
1254
+ i = end;
1255
+ }
1256
+ else
1257
+ source += ch.replace(/[.+^${}()|]/g, "\\$&");
1258
+ }
1259
+ try {
1260
+ return new RegExp(`${source}$`).test(name);
1261
+ }
1262
+ catch {
1263
+ return null;
1264
+ }
1265
+ }
1266
+ /**
1267
+ * BAPI-1698 — whether the ROOT `.gitignore` plainly ignores `.venv`. Only the four
1268
+ * plain forms count. A `!` line after the declaration that could re-include the
1269
+ * `.venv` directory (`!.venv`, `!.*`, `!*`, `!**`...) suppresses the proposal;
1270
+ * a negation that cannot match it (`!README.md`) is ignored. Anything this reader
1271
+ * cannot interpret with certainty is `uncertain`. Global excludes are never read.
1272
+ */
1273
+ export function gitignoreVenvCoverage(text) {
1274
+ let declared = false;
1275
+ for (const raw of text.split(/\r?\n/)) {
1276
+ const line = raw.replace(/[ \t]+$/, "");
1277
+ if (line.length === 0 || line.startsWith("#"))
1278
+ continue;
1279
+ if (line.includes("\\")) {
1280
+ // An escape changes meaning in ways this reader does not model.
1281
+ if (declared)
1282
+ return "uncertain";
1283
+ continue;
1284
+ }
1285
+ if (VENV_IGNORE_DECLARATIONS.has(line)) {
1286
+ declared = true;
1287
+ continue;
1288
+ }
1289
+ if (!declared || !line.startsWith("!"))
1290
+ continue;
1291
+ let pattern = line.slice(1).replace(/^\//, "").replace(/\/$/, "");
1292
+ while (pattern.startsWith("**/"))
1293
+ pattern = pattern.slice(3);
1294
+ if (pattern.length === 0)
1295
+ continue;
1296
+ const first = pattern.split("/")[0];
1297
+ if (first === "**")
1298
+ return "negated";
1299
+ if (!/[*?[]/.test(first)) {
1300
+ if (first === ".venv")
1301
+ return "negated";
1302
+ continue;
1303
+ }
1304
+ const matches = globSegmentMatches(first, ".venv");
1305
+ if (matches === null)
1306
+ return "uncertain";
1307
+ if (matches)
1308
+ return "negated";
1309
+ }
1310
+ return declared ? "covered" : "missing";
1311
+ }
1312
+ /** BAPI-1698 — whether the isolated pip bootstrap may be proposed, and why not. */
1313
+ async function pipBootstrapEligibility(fsSeam, platform) {
1314
+ if (platform === "win32")
1315
+ return { ok: false, reason: "windows_host" };
1316
+ const text = await readBounded(fsSeam, ".gitignore");
1317
+ if (text === null)
1318
+ return { ok: false, reason: "ignore_file_missing" };
1319
+ switch (gitignoreVenvCoverage(text)) {
1320
+ case "covered":
1321
+ return { ok: true };
1322
+ case "missing":
1323
+ return { ok: false, reason: "ignore_declaration_missing" };
1324
+ case "negated":
1325
+ return { ok: false, reason: "ignore_negation" };
1326
+ default:
1327
+ return { ok: false, reason: "ignore_coverage_unestablished" };
1328
+ }
1329
+ }
1330
+ /** Root requirement files: `requirements.txt`, `requirements-dev.txt`, `requirements_test.txt`, ... */
1331
+ const ROOT_REQUIREMENTS_RE = /^requirements(?:[-_.][A-Za-z0-9_.-]+)?\.txt$/;
1332
+ /**
1333
+ * BAPI-1698 — the root dependency manifests no candidate covers. Reads ONE root
1334
+ * listing. A manifest counts as covered when a candidate watches it, or when it
1335
+ * is the project file of the manager a candidate installs with (`package.json`
1336
+ * for JavaScript, `pyproject.toml` for uv and poetry). Advisory only.
1337
+ */
1338
+ async function uncoveredRootManifests(fsSeam, candidates, pythonManager, hasJavaScript) {
1339
+ const names = (await fsSeam.listDir("")) ?? [];
1340
+ const covered = new Set(candidates.flatMap((c) => (c.cwd === "." ? c.lockfiles : [])));
1341
+ if (hasJavaScript)
1342
+ covered.add("package.json");
1343
+ if (pythonManager === "uv" || pythonManager === "poetry")
1344
+ covered.add("pyproject.toml");
1345
+ const manifests = names.filter((name) => ROOT_REQUIREMENTS_RE.test(name) ||
1346
+ UNSUPPORTED_PYTHON_MANIFESTS.includes(name) ||
1347
+ name === "package.json");
1348
+ return manifests.filter((name) => !covered.has(name)).sort(byCodeUnit);
1349
+ }
1350
+ /**
1351
+ * BAPI-1698 — the plain sentences every setup surface shows for the dependency
1352
+ * notes, pip reason, and uncovered manifests of one discovery. One sentence per
1353
+ * fact, each file named once. Advisory: none of them stops setup.
1354
+ */
1355
+ export function dependencyInstallNoteSentences(fields) {
1356
+ const sentences = [];
1357
+ for (const note of fields.dependencyInstallNotes ?? []) {
1358
+ if (note === "dependency_install_toolchain_unresolved") {
1359
+ sentences.push("The repository's toolchains could not be read with certainty, so nothing is proposed.");
1360
+ }
1361
+ else if (note === "dependency_install_pip_not_proposed") {
1362
+ sentences.push(`requirements.txt was found, but no install is proposed for it: ${PIP_REASON_TEXT[fields.dependencyInstallPipReason ?? "ignore_coverage_unestablished"]}. Workers and the test trial will not install it unless you add an entry.`);
1363
+ }
1364
+ }
1365
+ for (const file of fields.dependencyInstallUncoveredManifests ?? []) {
1366
+ sentences.push(`No proposed install covers ${file}. Workers and the test trial will not install what it lists unless you add an entry.`);
1367
+ }
1368
+ return sentences;
1369
+ }
1370
+ const PIP_REASON_TEXT = Object.freeze({
1371
+ windows_host: "the isolated .venv install is not offered on a Windows host",
1372
+ ignore_file_missing: "there is no readable .gitignore at the repository root, so a created .venv folder would not be ignored",
1373
+ ignore_declaration_missing: "the root .gitignore does not ignore .venv",
1374
+ ignore_negation: "a later line in the root .gitignore could bring .venv back",
1375
+ ignore_coverage_unestablished: "setup could not tell for certain whether the root .gitignore ignores .venv",
1376
+ });
1377
+ /**
1378
+ * BAPI-1698 — the same seam with ONE root listing shared by every proposer in a
1379
+ * discovery run (must-order paths and the uncovered-manifest scan), so adding a
1380
+ * reader never adds a second listing of the repository root.
1381
+ */
1382
+ export function withSharedRootListing(fsSeam) {
1383
+ let root;
1384
+ return {
1385
+ readText: (relPath) => fsSeam.readText(relPath),
1386
+ exists: (relPath) => fsSeam.exists(relPath),
1387
+ listDir: (relPath) => (relPath === "" ? (root ??= fsSeam.listDir("")) : fsSeam.listDir(relPath)),
1388
+ };
1389
+ }
1228
1390
  /** BAPI-1551 — the root dependency-refresh proposals and the notes on what was left out. */
1229
1391
  export async function proposeDependencyInstall(fsSeam,
1230
1392
  /**
1231
1393
  * BAPI-1677 — the learned-text snapshot extras are worked out from. Absent means no
1232
1394
  * derivation was asked for. `null` means the text could not be read: a limitation.
1395
+ *
1396
+ * BAPI-1698 — `platform` is the executor host's platform, defaulting to
1397
+ * `process.platform`; the isolated pip bootstrap is never proposed on Windows.
1233
1398
  */
1234
1399
  options = {}) {
1235
1400
  let resolution;
@@ -1256,9 +1421,25 @@ options = {}) {
1256
1421
  const py = resolution.toolchains.python;
1257
1422
  let limitations = [];
1258
1423
  let unknown = false;
1424
+ let pipReason;
1259
1425
  if (py !== null) {
1260
- if (py.manager === "pip")
1261
- notes.push("dependency_install_pip_not_proposed");
1426
+ if (py.manager === "pip") {
1427
+ // BAPI-1698 — one checkout-local `.venv` bootstrap, only when it is portable
1428
+ // and the root `.gitignore` plainly keeps the created folder out of git.
1429
+ const eligibility = await pipBootstrapEligibility(fsSeam, options.platform ?? process.platform);
1430
+ if (eligibility.ok) {
1431
+ candidates.push({
1432
+ cwd: ".",
1433
+ argv: [...PIP_BOOTSTRAP_ARGV],
1434
+ lockfiles: [py.dependencyFile],
1435
+ label: "pip (isolated .venv)",
1436
+ });
1437
+ }
1438
+ else {
1439
+ notes.push("dependency_install_pip_not_proposed");
1440
+ pipReason = eligibility.reason;
1441
+ }
1442
+ }
1262
1443
  else {
1263
1444
  // The install target is resolved first: its own file, never a union across projects.
1264
1445
  const derived = options.learned === undefined
@@ -1275,9 +1456,14 @@ options = {}) {
1275
1456
  });
1276
1457
  }
1277
1458
  }
1459
+ // BAPI-1698 — name every root manifest nothing covers. Root `requirements.txt`
1460
+ // is already named by the pip note when it got no proposal.
1461
+ const uncovered = (await uncoveredRootManifests(fsSeam, candidates, py?.manager ?? null, js !== null)).filter((name) => !(pipReason !== undefined && name === "requirements.txt"));
1278
1462
  return {
1279
1463
  candidates,
1280
1464
  notes,
1465
+ ...(pipReason !== undefined ? { pipReason } : {}),
1466
+ ...(uncovered.length > 0 ? { uncoveredManifests: uncovered } : {}),
1281
1467
  ...(limitations.length > 0 ? { limitations } : {}),
1282
1468
  ...(unknown ? { unknown: true } : {}),
1283
1469
  };
@@ -1548,7 +1734,9 @@ async function queryHistory(lookupHistory, names) {
1548
1734
  * than presenting an empty provider list as a gate.
1549
1735
  */
1550
1736
  export async function discoverGate(input) {
1551
- const { fs: fsSeam, lookupHistory } = input;
1737
+ const { lookupHistory } = input;
1738
+ // BAPI-1698: one root listing for the whole run.
1739
+ const fsSeam = withSharedRootListing(input.fs);
1552
1740
  const evidence = [];
1553
1741
  const localCandidates = [];
1554
1742
  const lookups = new LookupNames();
@@ -1591,7 +1779,10 @@ export async function discoverGate(input) {
1591
1779
  const localCommandIds = providerChecks.length > 0 ? [] : validLocal.filter((c) => c.confidence === "high").map((c) => c.id);
1592
1780
  const workerEnv = resolveWorkerEnv(extras.envObservations);
1593
1781
  const hints = await proposeReproductionHints(fsSeam, providerChecks, extras.hintJobs);
1594
- const dependencyInstall = await proposeDependencyInstall(fsSeam, input.learned !== undefined ? { learned: input.learned } : {});
1782
+ const dependencyInstall = await proposeDependencyInstall(fsSeam, {
1783
+ ...(input.learned !== undefined ? { learned: input.learned } : {}),
1784
+ ...(input.platform !== undefined ? { platform: input.platform } : {}),
1785
+ });
1595
1786
  const mustOrder = await proposeMustOrderPaths(fsSeam);
1596
1787
  return {
1597
1788
  providerCandidates,
@@ -1618,11 +1809,16 @@ export async function discoverGate(input) {
1618
1809
  * Makes no provider-history call.
1619
1810
  */
1620
1811
  export async function discoverDeclarations(input) {
1812
+ // BAPI-1698: one root listing for the whole run.
1813
+ const fsSeam = withSharedRootListing(input.fs);
1621
1814
  const extras = { envObservations: [], hintJobs: new Map(), workflowFiles: [] };
1622
- await collectWorkflows(input.fs, [], new LookupNames(), extras);
1623
- const dependencyInstall = await proposeDependencyInstall(input.fs, input.learned !== undefined ? { learned: input.learned } : {});
1624
- const mustOrder = await proposeMustOrderPaths(input.fs);
1625
- return declarationFields(dependencyInstall, proposeCiDatabase(input.providerChecks, extras.workflowFiles), mustOrder, await proposeWorkerDatabase(input.fs));
1815
+ await collectWorkflows(fsSeam, [], new LookupNames(), extras);
1816
+ const dependencyInstall = await proposeDependencyInstall(fsSeam, {
1817
+ ...(input.learned !== undefined ? { learned: input.learned } : {}),
1818
+ ...(input.platform !== undefined ? { platform: input.platform } : {}),
1819
+ });
1820
+ const mustOrder = await proposeMustOrderPaths(fsSeam);
1821
+ return declarationFields(dependencyInstall, proposeCiDatabase(input.providerChecks, extras.workflowFiles), mustOrder, await proposeWorkerDatabase(fsSeam));
1626
1822
  }
1627
1823
  /**
1628
1824
  * BAPI-1551 — the declaration fields of a proposal. Each is present only when it
@@ -1635,6 +1831,10 @@ function declarationFields(dependencyInstall, ciDatabase, mustOrder, workerDatab
1635
1831
  ...(dependencyInstall.candidates.length > 0 ? { dependencyInstallCandidates: dependencyInstall.candidates } : {}),
1636
1832
  ...(dependencyInstall.notes.length > 0 ? { dependencyInstallNotes: dependencyInstall.notes } : {}),
1637
1833
  ...(dependencyInstall.limitations !== undefined ? { dependencyInstallLimitations: dependencyInstall.limitations } : {}),
1834
+ ...(dependencyInstall.pipReason !== undefined ? { dependencyInstallPipReason: dependencyInstall.pipReason } : {}),
1835
+ ...(dependencyInstall.uncoveredManifests !== undefined
1836
+ ? { dependencyInstallUncoveredManifests: dependencyInstall.uncoveredManifests }
1837
+ : {}),
1638
1838
  ...(dependencyInstall.unknown === true ? { dependencyInstallUnknown: true } : {}),
1639
1839
  ...(ciDatabase.value !== "unknown" ? { ciDatabaseProposal: ciDatabase } : {}),
1640
1840
  ...(mustOrder.candidates.length > 0 ? { mustOrderPathCandidates: mustOrder.candidates } : {}),