@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
@@ -1,5 +1,6 @@
1
1
  import { ticketReviewSummary } from "./ticket-review-summary.js";
2
2
  import { previewLaunchReadiness } from "./conductor/bridge-api-client.js";
3
+ import { previewObservationScopeMatches } from "./conductor/preview-observations.js";
3
4
  /**
4
5
  * `setup-epic` — one-command bootstrap for an Epic Implementer run.
5
6
  *
@@ -127,7 +128,11 @@ export const SETUP_EPIC_VERIFICATION_HANDOFF_EXCEPTIONS_KEY = "verification_hand
127
128
  * `VERIFICATION_HANDOFF_STEP_CLASSES` in `api/models/epic_run.py`; a client
128
129
  * cannot import a Python constant, so a test pins the two together.
129
130
  */
130
- export const SETUP_EPIC_VERIFICATION_HANDOFF_STEP_CLASSES = ["e2e_tests", "rendered_ui_review"];
131
+ export const SETUP_EPIC_VERIFICATION_HANDOFF_STEP_CLASSES = [
132
+ "unit_tests",
133
+ "e2e_tests",
134
+ "rendered_ui_review",
135
+ ];
131
136
  /** Mirrors the server's `MAX_VERIFICATION_HANDOFF_EXCEPTIONS`. */
132
137
  export const SETUP_EPIC_MAX_VERIFICATION_HANDOFF_EXCEPTIONS = 200;
133
138
  /**
@@ -397,7 +402,7 @@ export function getSetupEpicUsage() {
397
402
  " is an explicit opt-in (--review-policy verdict_protocol).",
398
403
  " This flag sets the policy for THIS run only and never",
399
404
  " changes a repository default. To persist one, pass",
400
- " --review-policy to `install-bridge conductor`, which",
405
+ " --review-policy to `install epic-implementer`, which",
401
406
  " stores it as the supervisor project default; that",
402
407
  " default is stamped into a new run only when the run",
403
408
  " sets no review policy of its own, so a value supplied",
@@ -2364,6 +2369,7 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2364
2369
  selectedProfilePolicyPath = profileRead.profile.policyRef?.path;
2365
2370
  }
2366
2371
  }
2372
+ let observations;
2367
2373
  let existingRunId = null;
2368
2374
  let existingTicketReview;
2369
2375
  let existingStatus = null;
@@ -2402,6 +2408,12 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2402
2408
  return 1;
2403
2409
  }
2404
2410
  access = accessResult.access;
2411
+ observations = opts.dryRun ? deps.previewObservations : undefined;
2412
+ if (observations !== undefined && (!previewObservationScopeMatches(observations, access, opts.epicKey) ||
2413
+ observations.liveRun.state === "error" || observations.readiness.state !== "supplied")) {
2414
+ deps.errorLog("Preview observations are unavailable or have a mismatched scope. Nothing was created.");
2415
+ return 1;
2416
+ }
2405
2417
  say(`Epic: ${opts.epicKey}`);
2406
2418
  say(`Repo: ${access.repoName}`);
2407
2419
  say(`Plan: v${plan.plan_version}, ${plan.nodes.length} node(s), ${countDeclaredOrderingPairs(plan)} edge(s)`);
@@ -2414,13 +2426,15 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2414
2426
  // --- Step 0: pre-check ---------------------------------------------------
2415
2427
  // Never create on an ambiguous read. A wrong answer here mints a duplicate run.
2416
2428
  try {
2417
- const state = await fetchEpicRunState(access, opts.epicKey, deps.fetch);
2418
- existingRunId = state.epic_run?.epic_run_id ?? null;
2419
- existingTicketReview = state.epic_run?.ticket_review;
2420
- existingStatus = state.epic_run?.status ?? null;
2421
- const existingPolicy = state.epic_run?.policy_json;
2429
+ const state = observations === undefined
2430
+ ? await fetchEpicRunState(access, opts.epicKey, deps.fetch)
2431
+ : observations.liveRun.state === "supplied" ? observations.liveRun.value : null;
2432
+ existingRunId = state?.epic_run?.epic_run_id ?? null;
2433
+ existingTicketReview = state?.epic_run?.ticket_review;
2434
+ existingStatus = state?.epic_run?.status ?? null;
2435
+ const existingPolicy = state?.epic_run?.policy_json;
2422
2436
  existingPolicyJson = existingPolicy ?? null;
2423
- existingNotificationSink = state.notification_sink ?? null;
2437
+ existingNotificationSink = state?.notification_sink ?? null;
2424
2438
  const existingBase = existingPolicy && typeof existingPolicy === "object"
2425
2439
  ? existingPolicy.base_branch
2426
2440
  : undefined;
@@ -2649,6 +2663,9 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
2649
2663
  let launchReadiness = null;
2650
2664
  if (!opts.localOnly) {
2651
2665
  try {
2666
+ // Repository GET readiness uses the server's default policy. This POST
2667
+ // evaluates the actual run policy (including webhook/review settings), so
2668
+ // it is a different check and cannot consume that repository observation.
2652
2669
  launchReadiness = await previewLaunchReadiness(access, existingRunId !== null ? existingPolicyJson ?? {} : composedForCreate, deps.fetch);
2653
2670
  }
2654
2671
  catch {
@@ -3027,7 +3044,7 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3027
3044
  }
3028
3045
  }
3029
3046
  if (opts.reviewPolicy !== undefined) {
3030
- say(` - review policy: ${opts.reviewPolicy} (per-run policy_json.review_policy; sets no repository default — use \`install-bridge conductor --review-policy\` for that)`);
3047
+ say(` - review policy: ${opts.reviewPolicy} (per-run policy_json.review_policy; sets no repository default — use \`install epic-implementer --review-policy\` for that)`);
3031
3048
  }
3032
3049
  say(` - POST /jira/epic-runs/runs/${opts.epicKey}/plan (v${plan.plan_version})`);
3033
3050
  say(` - POST /jira/epic-runs/runs/${opts.epicKey}/approve-plan (v${plan.plan_version})`);
@@ -0,0 +1,62 @@
1
+ export function renderSetupQuestion(spec) {
2
+ return [spec.purpose, `Current evidence:\n${spec.evidence.join("\n")}`,
3
+ `Options:\n${spec.options.map(o => `${o.id}: ${o.label}`).join("\n")}`,
4
+ `Consequences:\n${spec.consequences.join("\n")}`,
5
+ `Defer: ${spec.deferred}\nRecovery: ${spec.recovery}`].join("\n\n");
6
+ }
7
+ export function parseSetupDecision(input, options = []) {
8
+ const value = input?.trim().toLowerCase();
9
+ if (!value)
10
+ return { status: "defer" };
11
+ if (value === "y" || value === "yes")
12
+ return { status: "accept" };
13
+ if (value === "n" || value === "no")
14
+ return { status: "decline" };
15
+ const option = options.find(o => o.id.toLowerCase() === value);
16
+ return option ? { status: "selected", id: option.id } : { status: "invalid" };
17
+ }
18
+ export async function askSetupQuestion(spec, terminal) {
19
+ terminal.write?.(renderSetupQuestion(spec));
20
+ if (!terminal.read)
21
+ return { status: "defer" };
22
+ try {
23
+ return parseSetupDecision(await terminal.read(spec.prompt ?? spec.purpose), spec.options);
24
+ }
25
+ catch {
26
+ return { status: "defer" };
27
+ }
28
+ }
29
+ export async function readCustomSetupCommand(terminal) {
30
+ if (!terminal.read)
31
+ return { status: "defer" };
32
+ let value;
33
+ try {
34
+ value = (await terminal.read("Enter the custom command (Enter defers): "))?.trim();
35
+ }
36
+ catch {
37
+ return { status: "defer" };
38
+ }
39
+ if (!value)
40
+ return { status: "defer" };
41
+ if (/^(y|yes|n|no)$/i.test(value))
42
+ return { status: "invalid" };
43
+ return { status: "custom", value };
44
+ }
45
+ /** Migration adapter for existing one-effect questions; secret reads stay separate. */
46
+ export function setupConsentQuestion(purpose) {
47
+ let consequence = "Only the operation named above is authorized; other setup permissions are unchanged.";
48
+ if (/token|credential/i.test(purpose))
49
+ consequence = "Credential identity affects which account may act. Secret entry uses a separate no-echo reader.";
50
+ else if (/service|executor|start|hook/i.test(purpose))
51
+ consequence = "This can install persistent automation or execute local commands with the executor's permissions.";
52
+ else if (/workflow|replace|overwrite|file/i.test(purpose))
53
+ consequence = "This can create or replace the named repository content; later CI may execute that content.";
54
+ else if (/gate|qualif|approval/i.test(purpose))
55
+ consequence = "This affects merge admission or executes the selected local gate commands. Existing required checks remain authoritative.";
56
+ else if (/url|destination|trust/i.test(purpose))
57
+ consequence = "Authenticated requests will be sent to this destination. Trust in another destination grants no permission here.";
58
+ return { purpose: purpose.replace(/\s*\[y\/n\]:?\s*$/i, "").trim(), prompt: purpose, evidence: ["Review the current state and operation details shown above. Unreadable state remains unresolved."],
59
+ options: [{ id: "yes", label: "Authorize this operation" }, { id: "no", label: "Defer this operation" }],
60
+ consequences: [consequence], deferred: "Only this operation is deferred; completed independent work is retained.",
61
+ recovery: "Rerun setup interactively after resolving the affected prerequisite." };
62
+ }
@@ -1262,6 +1262,10 @@ export { validateBranchName, fetchAndResolveBaseSha };
1262
1262
  * historical branch-name behavior unchanged.
1263
1263
  */
1264
1264
  export async function createWorktrees(deps, options, worktrunkBinary, baseStartPoint = options.baseBranch) {
1265
+ const { bridgeWorktreeCleanupAdvisory } = await import("./bridge-worktree-inspection.js");
1266
+ const cleanupAdvisory = await bridgeWorktreeCleanupAdvisory(deps.cwd);
1267
+ if (cleanupAdvisory)
1268
+ process.stderr.write(cleanupAdvisory + "\n");
1265
1269
  // BAPI-586: for guard-enabled Conductor fresh dispatch the caller has already
1266
1270
  // resolved `baseStartPoint` to an immutable base SHA (`nonMutatingBase`). Align
1267
1271
  // any safe pre-existing branch exactly to that SHA and verify the resulting
@@ -1,41 +1,12 @@
1
- /**
2
- * Read-only test-command detection (BAPI-1460).
3
- *
4
- * Proposes the one runnable command a repository's CI workflow should run. It
5
- * READS ONLY: the stored command, the learned `unit_testing_stack` prose, and a
6
- * handful of repository files. It never runs the command, never runs a package
7
- * manager, never imports Python, never evaluates a Make recipe, never prompts,
8
- * and never writes. Its dependency surface has no subprocess runner, no prompt
9
- * function, and no configuration writer, so it cannot.
10
- *
11
- * ## Order
12
- *
13
- * 1. A stored command (`GET /setup/testing-config`) wins, with no question.
14
- * 2. Otherwise repository files are scanned, in a fixed order: JavaScript
15
- * (`package.json` `scripts.test`, runner from the lockfile), Make (a real
16
- * `test:` target), pytest (each listed marker), Go (`go.mod`), Rust
17
- * (`Cargo.toml`).
18
- * 3. When more than one stack is detected, the learned `unit_testing_stack`
19
- * prose picks among them through a fixed vocabulary. It is a hint and is
20
- * never interpreted as a command.
21
- * 4. No candidate means exactly one required question, with no default.
22
- *
23
- * ## Caller contract (the setup command)
24
- *
25
- * - `question: "none"` — use `selected` as is.
26
- * - `question: "accept_or_replace"` — ask once, offering `selected` as the
27
- * default and the other candidates as alternatives.
28
- * - `question: "required"` — ask once with no default. An empty answer is the
29
- * named cancellation outcome {@link TEST_COMMAND_DETECTION_CANCELLED}; nothing
30
- * is stored.
31
- * - Every chosen or typed command is validated with `validateTestCommand` and
32
- * saved through `PUT /setup/testing-config`. An invalid answer is explained
33
- * with the validation message and is never stored.
34
- *
35
- * A detected command is an UNVERIFIED proposal: passing the syntax rules does
36
- * not mean the command was run or that it works.
1
+ import { isTestScript } from "./package-script-semantics.js";
2
+ /** Read-only command evidence. Stored commands are preserved. Exactly one
3
+ * explicitly test-oriented command with an established runner and directory
4
+ * may be saved routinely. Multiple suites, conflicting runners and manifest
5
+ * hints require named selection. Unknown reads never mean no tests exist.
6
+ * Nothing here prompts, executes a command, installs dependencies or writes.
37
7
  */
38
- import { readStoredTestCommand, readUnitTestingStack, } from "./testing-config-client.js";
8
+ import { readOptionalRepositoryFile, RepositoryReadError, resolveRepositoryToolchains, } from "./repository-toolchains.js";
9
+ import { readStoredTestCommand, } from "./testing-config-client.js";
39
10
  /** The stacks detection recognizes, in detection order. */
40
11
  export const DETECTED_STACKS = ["javascript", "make", "python", "go", "rust"];
41
12
  /** Named outcome for an empty answer to the required question. */
@@ -49,24 +20,24 @@ class DetectionReadError extends Error {
49
20
  this.file = file;
50
21
  }
51
22
  }
52
- function isMissing(err) {
53
- const code = typeof err === "object" && err !== null ? err.code : undefined;
54
- return code === "ENOENT" || code === "ENOTDIR";
55
- }
56
23
  async function readOptional(deps, relPath) {
57
24
  try {
58
- return await deps.readFile(relPath);
25
+ return await readOptionalRepositoryFile(deps.readFile, relPath);
59
26
  }
60
27
  catch (err) {
61
- if (isMissing(err))
62
- return null;
63
- throw new DetectionReadError("repository_read_failed", relPath);
28
+ if (err instanceof RepositoryReadError)
29
+ throw new DetectionReadError("repository_read_failed", relPath);
30
+ throw err;
64
31
  }
65
32
  }
66
- async function detectJavaScript(deps) {
33
+ function selectJavaScriptRunner(resolution) {
34
+ const js = resolution.toolchains.javascript;
35
+ return js === null ? { manager: "npm", lockfile: null } : { manager: js.manager, lockfile: js.dependencyFile };
36
+ }
37
+ async function detectJavaScript(deps, resolution) {
67
38
  const raw = await readOptional(deps, "package.json");
68
39
  if (raw === null)
69
- return null;
40
+ return [];
70
41
  let parsed;
71
42
  try {
72
43
  parsed = JSON.parse(raw);
@@ -79,17 +50,23 @@ async function detectJavaScript(deps) {
79
50
  }
80
51
  const scripts = parsed.scripts;
81
52
  if (!scripts || typeof scripts !== "object" || Array.isArray(scripts))
82
- return null;
83
- const test = scripts.test;
84
- if (typeof test !== "string" || test.trim().length === 0)
85
- return null;
86
- if ((await readOptional(deps, "pnpm-lock.yaml")) !== null) {
87
- return { stack: "javascript", command: "pnpm test", provenance: "package.json + pnpm-lock.yaml", verified: false };
88
- }
89
- if ((await readOptional(deps, "yarn.lock")) !== null) {
90
- return { stack: "javascript", command: "yarn test", provenance: "package.json + yarn.lock", verified: false };
91
- }
92
- return { stack: "javascript", command: "npm test", provenance: "package.json", verified: false };
53
+ return [];
54
+ const table = scripts;
55
+ const { manager, lockfile } = selectJavaScriptRunner(resolution);
56
+ const source = lockfile === null ? "package.json" : `package.json + ${lockfile}`;
57
+ const lockManagers = new Set();
58
+ for (const [file, runner] of [["pnpm-lock.yaml", "pnpm"], ["yarn.lock", "yarn"], ["package-lock.json", "npm"], ["npm-shrinkwrap.json", "npm"], ["bun.lock", "bun"], ["bun.lockb", "bun"]]) {
59
+ if (await readOptional(deps, file) !== null)
60
+ lockManagers.add(runner);
61
+ }
62
+ const conflicting = lockManagers.size > 1;
63
+ return Object.entries(table).filter(([name, body]) => isTestScript(name, body)).map(([name]) => ({
64
+ stack: "javascript",
65
+ command: name === "test" && manager !== "bun" ? `${manager} test` : `${manager} run ${name}`,
66
+ provenance: `${source} scripts.${name}${conflicting ? " (conflicting runner lockfiles)" : ""}`, verified: false,
67
+ runner: manager, workingDirectory: ".", scopeEvidence: `explicit test script: ${name}`,
68
+ autoSaveEligible: lockfile !== null && !conflicting,
69
+ }));
93
70
  }
94
71
  /**
95
72
  * Whether a Makefile declares a real `test` target: a rule line (not a recipe,
@@ -116,7 +93,7 @@ async function detectMake(deps) {
116
93
  continue;
117
94
  if (!makefileHasTestTarget(raw))
118
95
  return null;
119
- return { stack: "make", command: "make test", provenance: name, verified: false };
96
+ return { stack: "make", command: "make test", provenance: name, verified: false, runner: "make", workingDirectory: ".", scopeEvidence: "explicit test target", autoSaveEligible: true };
120
97
  }
121
98
  return null;
122
99
  }
@@ -140,12 +117,12 @@ async function detectPython(deps) {
140
117
  async function detectGo(deps) {
141
118
  if ((await readOptional(deps, "go.mod")) === null)
142
119
  return null;
143
- return { stack: "go", command: "go test ./...", provenance: "go.mod", verified: false };
120
+ return { stack: "go", command: "go test ./...", provenance: "go.mod (manifest hint only)", verified: false, autoSaveEligible: false };
144
121
  }
145
122
  async function detectRust(deps) {
146
123
  if ((await readOptional(deps, "Cargo.toml")) === null)
147
124
  return null;
148
- return { stack: "rust", command: "cargo test", provenance: "Cargo.toml", verified: false };
125
+ return { stack: "rust", command: "cargo test", provenance: "Cargo.toml (manifest hint only)", verified: false, autoSaveEligible: false };
149
126
  }
150
127
  /**
151
128
  * Words in the learned `unit_testing_stack` prose that name each stack. Matched
@@ -184,11 +161,28 @@ export function stacksNamedByHint(hint) {
184
161
  * {@link DetectionReadError} for an unreadable or malformed file.
185
162
  */
186
163
  async function detectCandidates(deps) {
187
- const found = [];
188
- for (const detect of [detectJavaScript, detectMake, detectPython, detectGo, detectRust]) {
189
- const candidate = await detect(deps);
164
+ const resolution = await resolveRepositoryToolchains(deps.readFile);
165
+ if (resolution.status === "unknown") {
166
+ // Unknown inspection is a failure, never an ordinary absence of lockfiles.
167
+ const first = resolution.failures[0];
168
+ throw new DetectionReadError(first.reason === "unreadable" ? "repository_read_failed" : "malformed_repository_file", first.file);
169
+ }
170
+ const found = await detectJavaScript(deps, resolution);
171
+ const detectors = [
172
+ () => detectMake(deps),
173
+ () => detectPython(deps),
174
+ () => detectGo(deps),
175
+ () => detectRust(deps),
176
+ ];
177
+ for (const detect of detectors) {
178
+ const candidate = await detect();
190
179
  if (candidate)
191
- found.push(candidate);
180
+ found.push({ ...candidate,
181
+ runner: candidate.runner ?? (candidate.stack === "python" ? "pytest" : candidate.stack === "rust" ? "cargo" : candidate.stack),
182
+ workingDirectory: candidate.workingDirectory ?? ".",
183
+ scopeEvidence: candidate.scopeEvidence ?? "configuration/manifest hint; test scope unestablished",
184
+ autoSaveEligible: candidate.autoSaveEligible ?? false,
185
+ });
192
186
  }
193
187
  return found;
194
188
  }
@@ -220,7 +214,7 @@ export async function detectTestCommand(options, deps) {
220
214
  if (candidates.length === 0) {
221
215
  return { status: "none_detected", selected: null, question: "required", candidates };
222
216
  }
223
- if (candidates.length === 1) {
217
+ if (candidates.length === 1 && candidates[0].autoSaveEligible) {
224
218
  return {
225
219
  status: "detected",
226
220
  selected: candidates[0].command,
@@ -230,18 +224,5 @@ export async function detectTestCommand(options, deps) {
230
224
  candidates,
231
225
  };
232
226
  }
233
- // The learned stack is advisory: an unreadable hint falls back to the first
234
- // candidate rather than stopping detection.
235
- const stackHint = await readUnitTestingStack(deps.config);
236
- const named = stacksNamedByHint(stackHint.ok ? stackHint.value : null);
237
- const hinted = candidates.find((c) => named.has(c.stack));
238
- const chosen = hinted ?? candidates[0];
239
- return {
240
- status: "detected",
241
- selected: chosen.command,
242
- provenance: chosen.provenance,
243
- question: "accept_or_replace",
244
- selectedByStackHint: hinted !== undefined,
245
- candidates,
246
- };
227
+ return { status: "alternatives", selected: null, question: "required", candidates };
247
228
  }
@@ -0,0 +1,40 @@
1
+ /** Hermetic notes handles for orchestration fixtures; no ambient filesystem fallback. */
2
+ import { constants } from "node:fs";
3
+ import path from "node:path";
4
+ export function memoryNotesFs(cwd, files, read, write) {
5
+ const ids = new Map();
6
+ const absent = () => Object.assign(new Error("missing fixture file"), { code: "ENOENT" });
7
+ const identity = (p) => {
8
+ if (!ids.has(p))
9
+ ids.set(p, ids.size + 1);
10
+ return { dev: 1, ino: ids.get(p), isFile: () => true, isSymbolicLink: () => false };
11
+ };
12
+ return {
13
+ realpath: async (p) => { if (path.normalize(p) === path.normalize(cwd) || files.has(p))
14
+ return path.normalize(p); throw absent(); },
15
+ lstat: async (p) => { if (!files.has(p))
16
+ throw absent(); return identity(p); },
17
+ readBytes: async (p) => Buffer.from(await read(p)),
18
+ unlink: async (p) => { files.delete(p); },
19
+ open: async (p, flags) => {
20
+ if ((flags & constants.O_EXCL) && files.has(p))
21
+ throw Object.assign(new Error("exists"), { code: "EEXIST" });
22
+ if (!files.has(p)) {
23
+ if (!(flags & constants.O_CREAT))
24
+ throw absent();
25
+ files.set(p, "");
26
+ }
27
+ let content = Buffer.from(files.get(p));
28
+ return { stat: async () => identity(p), readFile: async () => Buffer.from(await read(p)),
29
+ write: async (buffer, offset, length, position) => {
30
+ const next = Buffer.alloc(Math.max(content.length, position + length));
31
+ content.copy(next);
32
+ buffer.copy(next, position, offset, offset + length);
33
+ await write(p, next.toString());
34
+ content = next;
35
+ return { bytesWritten: length };
36
+ }, truncate: async (length) => { content = content.subarray(0, length); files.set(p, content.toString()); },
37
+ sync: async () => { }, close: async () => { } };
38
+ },
39
+ };
40
+ }
@@ -69,12 +69,19 @@ function validateBinding(value, relativePath) {
69
69
  throw corrupt(relativePath, `binding is missing ${field}`);
70
70
  }
71
71
  }
72
+ const confirmed = value.confirmed_executor_job_id;
73
+ if (confirmed !== undefined &&
74
+ confirmed !== null &&
75
+ !(typeof confirmed === "number" && Number.isSafeInteger(confirmed) && confirmed > 0)) {
76
+ throw corrupt(relativePath, "binding has an invalid confirmed_executor_job_id");
77
+ }
72
78
  return {
73
79
  attempt_id: value.attempt_id,
74
80
  repo_name: value.repo_name,
75
81
  ticket_number: value.ticket_number,
76
82
  source_branch: value.source_branch,
77
83
  base_branch: value.base_branch,
84
+ ...(typeof confirmed === "number" ? { confirmed_executor_job_id: confirmed } : {}),
78
85
  };
79
86
  }
80
87
  function validatePending(value, relativePath) {
@@ -32,6 +32,18 @@ export const DEFAULT_DELIVERY_JOURNAL_STORE = {
32
32
  recordSubmissionReceipt,
33
33
  listPendingSubmissions,
34
34
  };
35
+ /**
36
+ * BAPI-1544 — read the executor-injected `BRIDGE_EXECUTOR_JOB_ID`. Only an
37
+ * unpadded positive safe decimal integer counts. No trimming and no partial-number
38
+ * parsing (`"12abc"`, `"1e3"`, `" 7"`, `"0"`, `"-4"`, `"1.5"` are all absent), and
39
+ * anything else is `undefined`, which leaves enrollment exactly as it was.
40
+ */
41
+ export function parseExecutorJobIdEnv(raw) {
42
+ if (typeof raw !== "string" || !/^[1-9][0-9]*$/.test(raw))
43
+ return undefined;
44
+ const value = Number(raw);
45
+ return Number.isSafeInteger(value) ? value : undefined;
46
+ }
35
47
  function storeOf(deps) {
36
48
  return deps.store ?? DEFAULT_DELIVERY_JOURNAL_STORE;
37
49
  }
@@ -64,7 +76,10 @@ export async function ensureDeliveryBinding(deps, ticketKey) {
64
76
  if (remembered &&
65
77
  remembered.repo_name === deps.repoName &&
66
78
  (sourceBranch === undefined || remembered.source_branch === sourceBranch)) {
67
- return { enrollment: "resumed", binding: remembered, newlyRegistered: false };
79
+ const confirmed = await confirmExecutorJob(deps, store, ticketKey, journal.registration_key, remembered);
80
+ return confirmed.replaced
81
+ ? { enrollment: "registered", binding: confirmed.binding, newlyRegistered: true }
82
+ : { enrollment: "resumed", binding: confirmed.binding, newlyRegistered: false };
68
83
  }
69
84
  if (!sourceBranch || sourceBranch === "HEAD") {
70
85
  return unavailable("the source branch could not be read (detached HEAD or git unavailable)");
@@ -78,7 +93,10 @@ export async function ensureDeliveryBinding(deps, ticketKey) {
78
93
  if (recovered.ok) {
79
94
  const binding = referenceFrom(recovered.body.binding);
80
95
  await store.recordBindingReference(deps.docsDir, ticketKey, binding);
81
- return { enrollment: "recovered", binding, newlyRegistered: false };
96
+ const confirmed = await confirmExecutorJob(deps, store, ticketKey, journal.registration_key, binding);
97
+ return confirmed.replaced
98
+ ? { enrollment: "registered", binding: confirmed.binding, newlyRegistered: true }
99
+ : { enrollment: "recovered", binding: confirmed.binding, newlyRegistered: false };
82
100
  }
83
101
  if (recovered.status !== 404) {
84
102
  return unavailable(`recovery failed (${recovered.error}): ${recovered.message}`);
@@ -92,7 +110,7 @@ export async function ensureDeliveryBinding(deps, ticketKey) {
92
110
  ...(deps.executorJobId !== undefined ? { executor_job_id: deps.executorJobId } : {}),
93
111
  });
94
112
  if (registered.ok) {
95
- const binding = referenceFrom(registered.body.binding);
113
+ const binding = referenceFrom(registered.body.binding, acknowledgedJobId(registered.body, deps.executorJobId));
96
114
  await store.recordBindingReference(deps.docsDir, ticketKey, binding);
97
115
  const replayed = registered.body.operation_status === "resumed";
98
116
  return {
@@ -114,15 +132,73 @@ export async function ensureDeliveryBinding(deps, ticketKey) {
114
132
  return unavailable(err);
115
133
  }
116
134
  }
117
- function referenceFrom(view) {
135
+ function referenceFrom(view, confirmedExecutorJobId) {
118
136
  return {
119
137
  attempt_id: view.attempt_id,
120
138
  repo_name: view.repo_name,
121
139
  ticket_number: view.ticket_number,
122
140
  source_branch: view.source_branch,
123
141
  base_branch: view.base_branch,
142
+ ...(confirmedExecutorJobId !== undefined ? { confirmed_executor_job_id: confirmedExecutorJobId } : {}),
124
143
  };
125
144
  }
145
+ /**
146
+ * The job ID the server acknowledged, or undefined. An acknowledgement counts only
147
+ * when it equals the ID this call sent: an absent field (an older server, or a
148
+ * request that sent none) or a different value confirms nothing.
149
+ */
150
+ function acknowledgedJobId(body, sent) {
151
+ return sent !== undefined && body.confirmed_executor_job_id === sent ? sent : undefined;
152
+ }
153
+ /**
154
+ * BAPI-1544 — make at most ONE registration attempt per call to attach the claimed
155
+ * executor job to a binding the server may hold without one.
156
+ *
157
+ * A remembered or recovered binding skips registration, so a binding created
158
+ * before the worker had its job ID would never learn it. This sends the same
159
+ * registration key with the job ID; the server fills it first-writer-wins and
160
+ * echoes `confirmed_executor_job_id` only when its binding carries exactly that ID.
161
+ * The ID is persisted to the journal only on that exact echo. Everything else
162
+ * (no job ID, already confirmed, a network error, a refusal, an absent or different
163
+ * acknowledgement) leaves the binding as it was and enrollment fail-open, so a
164
+ * later call retries. A continuation that sends a different job ID keeps the same
165
+ * binding and never records a confirmation the server did not give.
166
+ */
167
+ async function confirmExecutorJob(deps, store, ticketKey, registrationKey, binding) {
168
+ const jobId = deps.executorJobId;
169
+ if (jobId === undefined || binding.confirmed_executor_job_id === jobId) {
170
+ return { binding, replaced: false };
171
+ }
172
+ try {
173
+ const response = await registerExecution(deps.client, {
174
+ repo_name: binding.repo_name,
175
+ ticket_number: binding.ticket_number,
176
+ source_branch: binding.source_branch,
177
+ base_branch: binding.base_branch,
178
+ registration_key: registrationKey,
179
+ executor_job_id: jobId,
180
+ });
181
+ if (!response.ok)
182
+ return { binding, replaced: false };
183
+ const confirmed = acknowledgedJobId(response.body, jobId);
184
+ // BAPI-1556 — the server may answer with a different attempt than the one this
185
+ // worker holds. Adopt it whole, built from the response and never by spreading
186
+ // the stale reference, and never carry the old attempt's job confirmation over.
187
+ if (response.body.binding.attempt_id !== binding.attempt_id) {
188
+ const replacement = referenceFrom(response.body.binding, confirmed);
189
+ await store.recordBindingReference(deps.docsDir, ticketKey, replacement);
190
+ return { binding: replacement, replaced: true };
191
+ }
192
+ if (confirmed === undefined)
193
+ return { binding, replaced: false };
194
+ const updated = { ...binding, confirmed_executor_job_id: confirmed };
195
+ await store.recordBindingReference(deps.docsDir, ticketKey, updated);
196
+ return { binding: updated, replaced: false };
197
+ }
198
+ catch {
199
+ return { binding, replaced: false };
200
+ }
201
+ }
126
202
  /**
127
203
  * Send every pending batch, oldest first. Never throws.
128
204
  *