@bridge_gpt/mcp-server 0.2.71 → 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 (116) hide show
  1. package/README.md +55 -17
  2. package/build/agent-launchers/claude-executor-adapter.js +19 -3
  3. package/build/agent-notes.js +171 -95
  4. package/build/agents.generated.js +4 -4
  5. package/build/bridge-permissions.js +4 -0
  6. package/build/bridge-worktree-inspection.js +237 -0
  7. package/build/check-evidence.js +6 -0
  8. package/build/claude-review-workflow.js +1 -1
  9. package/build/cli-help.js +6 -0
  10. package/build/codex-auto-recovery.js +126 -0
  11. package/build/codex-skill-adapter.js +2 -0
  12. package/build/commands.generated.js +5 -5
  13. package/build/conductor/bridge-api-client.js +518 -23
  14. package/build/conductor/doctor.js +84 -10
  15. package/build/conductor/epic-implementer-cli.js +51 -2
  16. package/build/conductor/gate-discovery.js +136 -10
  17. package/build/conductor/gate-settings-review.js +305 -5
  18. package/build/conductor/git-hooks-uninstall.js +112 -0
  19. package/build/conductor/git-hooks.js +81 -15
  20. package/build/conductor/guided-repair.js +10 -1
  21. package/build/conductor/install-doctor.js +2 -4
  22. package/build/conductor/launch-plan.js +42 -2
  23. package/build/conductor/local-merge.js +12 -1
  24. package/build/conductor/merge-execution-contract.js +1 -1
  25. package/build/conductor/merged-child-check.js +2 -1
  26. package/build/conductor/prerequisite-inputs.js +379 -0
  27. package/build/conductor/readiness-assessment.js +78 -0
  28. package/build/conductor/readiness-cli.js +10 -0
  29. package/build/conductor/readiness-prerequisites.js +53 -0
  30. package/build/conductor/readiness-sections.js +21 -8
  31. package/build/conductor/readiness.js +20 -2
  32. package/build/conductor/recovery-cli.js +223 -13
  33. package/build/conductor/recovery-operations.js +34 -4
  34. package/build/conductor/repair-contract.js +33 -0
  35. package/build/conductor/tools.js +34 -3
  36. package/build/conductor/wait-run-attention.js +115 -0
  37. package/build/conductor/wait-run-cli.js +96 -3
  38. package/build/conductor/worker-database-doctor-inspector.js +1 -0
  39. package/build/credential-store.js +25 -20
  40. package/build/dependency-install-declarations.js +157 -0
  41. package/build/docs.generated.js +4 -4
  42. package/build/doctor.js +37 -5
  43. package/build/drive-epic-help.js +2 -2
  44. package/build/drive-epic.js +52 -11
  45. package/build/epic-implementer-bin.js +118 -43
  46. package/build/epic-launch-profile.js +1 -1
  47. package/build/executor/cli.js +2 -0
  48. package/build/executor/completion-contract.js +16 -0
  49. package/build/executor/credentials.js +1 -1
  50. package/build/executor/delivery-observations.js +113 -0
  51. package/build/executor/delivery-outcome.js +30 -0
  52. package/build/executor/dependency-refresh-runner.js +132 -0
  53. package/build/executor/dependency-refresh.js +530 -0
  54. package/build/executor/deps.js +4 -0
  55. package/build/executor/env.js +67 -2
  56. package/build/executor/harness-coverage.js +19 -0
  57. package/build/executor/http-client.js +35 -1
  58. package/build/executor/index.js +2 -1
  59. package/build/executor/install-preflight.js +1 -1
  60. package/build/executor/job-runner.js +246 -28
  61. package/build/executor/likely-tests.js +94 -97
  62. package/build/executor/prompt-spec.js +13 -3
  63. package/build/executor/required-verification.js +28 -0
  64. package/build/executor/required-work-diagnostics.js +30 -0
  65. package/build/executor/required-work-ledger.js +19 -1
  66. package/build/executor/results.js +42 -0
  67. package/build/executor/service-discovery.js +42 -0
  68. package/build/executor/service-lifecycle.js +109 -2
  69. package/build/executor/service-uninstall.js +205 -0
  70. package/build/executor/service-unit.js +5 -3
  71. package/build/executor/test-clock.js +3 -0
  72. package/build/executor/verification-hints.js +179 -0
  73. package/build/executor/worker-command.js +54 -2
  74. package/build/executor/worker-database.js +271 -31
  75. package/build/executor/worker-finalization.js +65 -10
  76. package/build/executor/worker-guard-hook.js +10 -2
  77. package/build/executor/worker-verification-guidance.js +37 -2
  78. package/build/executor/worktree-inspection.js +42 -0
  79. package/build/github-sign-in.js +1 -1
  80. package/build/index.js +679 -278
  81. package/build/init.js +3 -3
  82. package/build/install-bridge-conductor-gate.js +236 -42
  83. package/build/install-bridge-conductor-setup.js +115 -26
  84. package/build/install-bridge-conductor.js +448 -350
  85. package/build/install-bridge.js +418 -123
  86. package/build/install-maintenance.js +104 -0
  87. package/build/install-reexec.js +1 -1
  88. package/build/local-cleanup.js +59 -0
  89. package/build/mcp-install-state.js +68 -2
  90. package/build/merge-workflow-install.js +2 -2
  91. package/build/package-script-semantics.js +10 -0
  92. package/build/pipeline-utils.js +1 -1
  93. package/build/pipelines.generated.js +5 -5
  94. package/build/plan-execution-ledger.js +148 -2
  95. package/build/plane/plane-freshness.js +6 -7
  96. package/build/plane/terminal-run-cleanup.js +5 -1
  97. package/build/plane/terminal-run-status.js +4 -0
  98. package/build/printed-remedy-commands.js +24 -4
  99. package/build/readiness-check.js +1 -78
  100. package/build/readiness-prerequisites.generated.js +199 -0
  101. package/build/readme.generated.js +1 -1
  102. package/build/repository-toolchains.js +50 -8
  103. package/build/setup-change-policy.js +32 -0
  104. package/build/setup-epic.js +2 -2
  105. package/build/setup-question.js +62 -0
  106. package/build/start-tickets.js +4 -0
  107. package/build/test-command-detection.js +32 -88
  108. package/build/test-support/notes-fs.js +40 -0
  109. package/build/ticket-delivery-enrollment.js +21 -8
  110. package/build/ticket-delivery-run-scope.js +128 -0
  111. package/build/version.generated.js +3 -3
  112. package/build/worker-guard-hook-bin.js +2 -2
  113. package/build/worktrees.js +105 -0
  114. package/docs/EPIC-IMPLEMENTER.md +5 -0
  115. package/docs/epic-implementer/getting-started.md +40 -15
  116. package/package.json +1 -1
@@ -509,36 +509,78 @@ function describeManagerVersion(name, version, fallback) {
509
509
  ? `${name} ${version.version} (from package.json)`
510
510
  : `${name} ${fallback} (fixed fallback)`;
511
511
  }
512
+ /**
513
+ * BAPI-1551 — the ONE fixed install argv per toolchain. The plain-language text
514
+ * below is built from it, so the text a person reads and the argv a dependency
515
+ * refresh declaration proposes can never drift apart.
516
+ */
517
+ export function installArgvForJavaScript(js) {
518
+ switch (js.manager) {
519
+ case "npm":
520
+ return ["npm", "ci"];
521
+ case "pnpm":
522
+ return ["pnpm", "install", "--frozen-lockfile"];
523
+ case "yarn":
524
+ return js.generation === "classic"
525
+ ? ["yarn", "install", "--frozen-lockfile"]
526
+ : ["yarn", "install", "--immutable"];
527
+ case "bun":
528
+ return ["bun", "install", "--frozen-lockfile"];
529
+ }
530
+ }
531
+ /**
532
+ * BAPI-1551 — the fixed install argv for a Python toolchain. pip's argv is kept
533
+ * for the description only: a bare `pip install` targets whatever interpreter is
534
+ * first on `PATH`, so a dependency refresh never proposes it.
535
+ */
536
+ export function installArgvForPython(py) {
537
+ switch (py.manager) {
538
+ case "uv":
539
+ return ["uv", "sync", "--frozen"];
540
+ case "poetry":
541
+ return ["poetry", "install"];
542
+ case "pip":
543
+ return ["pip", "install", "-r", "requirements.txt"];
544
+ }
545
+ }
546
+ /**
547
+ * BAPI-1551 — the files whose CONTENT the resolver reads. Every other file it
548
+ * consults is checked for existence only, so a reader that cannot return a
549
+ * large lockfile's bytes may still report that it exists.
550
+ */
551
+ export const TOOLCHAIN_CONTENT_FILES = Object.freeze(["package.json", "yarn.lock"]);
512
552
  /** One plain line for the JavaScript selection. Never carries repository text beyond a validated version. */
513
553
  export function describeJavaScriptToolchain(js) {
554
+ const installs = `installs with ${installArgvForJavaScript(js).join(" ")}`;
514
555
  switch (js.manager) {
515
556
  case "npm":
516
- return `JavaScript: npm (${js.dependencyFile}); ${describeNode(js.node)}; installs with npm ci`;
557
+ return `JavaScript: npm (${js.dependencyFile}); ${describeNode(js.node)}; ${installs}`;
517
558
  case "pnpm":
518
559
  return (`JavaScript: pnpm (${js.dependencyFile}); ${describeManagerVersion("pnpm", js.pnpm, PNPM_FALLBACK_MAJOR)}; ` +
519
- `${describeNode(js.node)}; installs with pnpm install --frozen-lockfile`);
560
+ `${describeNode(js.node)}; ${installs}`);
520
561
  case "yarn":
521
562
  return js.generation === "classic"
522
- ? `JavaScript: Yarn classic (${js.dependencyFile}); ${describeNode(js.node)}; installs with yarn install --frozen-lockfile`
563
+ ? `JavaScript: Yarn classic (${js.dependencyFile}); ${describeNode(js.node)}; ${installs}`
523
564
  : `JavaScript: Yarn Berry (${js.dependencyFile}); ` +
524
565
  (js.yarn === "package_manager"
525
566
  ? "Yarn version from package.json through Corepack"
526
567
  : `Yarn ${YARN_BERRY_FALLBACK_MAJOR} (fixed fallback) through Corepack`) +
527
- `; ${describeNode(js.node)}; installs with yarn install --immutable`;
568
+ `; ${describeNode(js.node)}; ${installs}`;
528
569
  case "bun":
529
- return `JavaScript: Bun (${js.dependencyFile}); Bun ${BUN_VERSION_RANGE}; installs with bun install --frozen-lockfile`;
570
+ return `JavaScript: Bun (${js.dependencyFile}); Bun ${BUN_VERSION_RANGE}; ${installs}`;
530
571
  }
531
572
  }
532
573
  /** One plain line for the Python selection. */
533
574
  export function describePythonToolchain(py) {
575
+ const installs = `installs with ${installArgvForPython(py).join(" ")}`;
534
576
  switch (py.manager) {
535
577
  case "uv":
536
- return `Python: uv (${py.dependencyFile}); ${describePython(py.python)}; installs with uv sync --frozen`;
578
+ return `Python: uv (${py.dependencyFile}); ${describePython(py.python)}; ${installs}`;
537
579
  case "poetry":
538
580
  return (`Python: Poetry (${py.dependencyFile}); Poetry ${POETRY_VERSION}; ${describePython(py.python)}; ` +
539
- "installs with poetry install");
581
+ installs);
540
582
  case "pip":
541
- return `Python: pip (${py.dependencyFile}); ${describePython(py.python)}; installs with pip install -r requirements.txt`;
583
+ return `Python: pip (${py.dependencyFile}); ${describePython(py.python)}; ${installs}`;
542
584
  }
543
585
  }
544
586
  /** The selected ecosystems as plain lines, in JavaScript, Python, Go order. */
@@ -0,0 +1,32 @@
1
+ export function classifySetupAction(action) {
2
+ if (action.state.status === "unknown" || !action.trusted)
3
+ return "missing-information";
4
+ if (action.unchanged)
5
+ return "no-op";
6
+ if (action.category === "bookkeeping")
7
+ return "routine";
8
+ if (action.category === "test-command" && action.state.status === "absent" && action.eligibleCommand)
9
+ return "routine";
10
+ return "consequential";
11
+ }
12
+ export function authorizeSetupAction(action, authorization, now = Date.now()) {
13
+ const classification = classifySetupAction(action);
14
+ if (classification === "missing-information")
15
+ return false;
16
+ if (classification === "no-op" || classification === "routine")
17
+ return true;
18
+ return !!authorization && authorization.expiresAt > now
19
+ && authorization.effect === action.effect && authorization.context === action.context
20
+ && authorization.repository === action.repository && authorization.principal === action.principal;
21
+ }
22
+ export function classifyServerSetupEffects(effects, approvalRequired) {
23
+ if (!Array.isArray(effects) || typeof approvalRequired !== "boolean")
24
+ return "invalid";
25
+ const categories = new Set(["gate", "setup", "config", "sources", "qualification"]);
26
+ if (effects.some(e => !e || typeof e !== "object" || e.classification !== "consequential"
27
+ || !categories.has(e.category) || !("before" in e) || !("after" in e)))
28
+ return "invalid";
29
+ if (approvalRequired !== (effects.length > 0))
30
+ return "invalid";
31
+ return effects.length ? "consequential" : "no-op";
32
+ }
@@ -402,7 +402,7 @@ export function getSetupEpicUsage() {
402
402
  " is an explicit opt-in (--review-policy verdict_protocol).",
403
403
  " This flag sets the policy for THIS run only and never",
404
404
  " changes a repository default. To persist one, pass",
405
- " --review-policy to `install-bridge conductor`, which",
405
+ " --review-policy to `install epic-implementer`, which",
406
406
  " stores it as the supervisor project default; that",
407
407
  " default is stamped into a new run only when the run",
408
408
  " sets no review policy of its own, so a value supplied",
@@ -3044,7 +3044,7 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
3044
3044
  }
3045
3045
  }
3046
3046
  if (opts.reviewPolicy !== undefined) {
3047
- 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)`);
3048
3048
  }
3049
3049
  say(` - POST /jira/epic-runs/runs/${opts.epicKey}/plan (v${plan.plan_version})`);
3050
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,45 +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`, else a chain of the usable `lint`,
16
- * `typecheck`/`type-check`, and `build` scripts; the runner comes from the
17
- * shared lockfile resolver, `repository-toolchains.ts`), Make (a real
18
- * `test:` target), pytest (each listed marker), Go (`go.mod`), Rust
19
- * (`Cargo.toml`). An uninspectable repository is a `failed` result, never an
20
- * ordinary absence of scripts or lockfiles.
21
- * 3. When more than one stack is detected, the learned `unit_testing_stack`
22
- * prose picks among them through a fixed vocabulary. It is a hint and is
23
- * never interpreted as a command.
24
- * 4. No candidate means exactly one required question, with no default.
25
- *
26
- * ## Caller contract (the setup command)
27
- *
28
- * - `question: "none"` — use `selected` as is.
29
- * - `question: "accept_or_replace"` — ask once, offering `selected` as the
30
- * default and the other candidates as alternatives.
31
- * - `question: "required"` — ask once with no default. An empty answer is the
32
- * named cancellation outcome {@link TEST_COMMAND_DETECTION_CANCELLED}; nothing
33
- * is stored.
34
- * - Every chosen or typed command is validated with `validateTestCommand` and
35
- * saved through `PUT /setup/testing-config`. An invalid answer is explained
36
- * with the validation message and is never stored.
37
- *
38
- * A detected command is an UNVERIFIED proposal: passing the syntax rules does
39
- * 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.
40
7
  */
41
8
  import { readOptionalRepositoryFile, RepositoryReadError, resolveRepositoryToolchains, } from "./repository-toolchains.js";
42
- import { readStoredTestCommand, readUnitTestingStack, } from "./testing-config-client.js";
9
+ import { readStoredTestCommand, } from "./testing-config-client.js";
43
10
  /** The stacks detection recognizes, in detection order. */
44
11
  export const DETECTED_STACKS = ["javascript", "make", "python", "go", "rust"];
45
12
  /** Named outcome for an empty answer to the required question. */
@@ -67,16 +34,10 @@ function selectJavaScriptRunner(resolution) {
67
34
  const js = resolution.toolchains.javascript;
68
35
  return js === null ? { manager: "npm", lockfile: null } : { manager: js.manager, lockfile: js.dependencyFile };
69
36
  }
70
- /** The scripts a fallback chain may run, in order. `typecheck` wins over `type-check`. */
71
- const FALLBACK_SCRIPT_GROUPS = [["lint"], ["typecheck", "type-check"], ["build"]];
72
- function isUsableScript(scripts, name) {
73
- const value = scripts[name];
74
- return typeof value === "string" && value.trim().length > 0;
75
- }
76
37
  async function detectJavaScript(deps, resolution) {
77
38
  const raw = await readOptional(deps, "package.json");
78
39
  if (raw === null)
79
- return null;
40
+ return [];
80
41
  let parsed;
81
42
  try {
82
43
  parsed = JSON.parse(raw);
@@ -89,31 +50,23 @@ async function detectJavaScript(deps, resolution) {
89
50
  }
90
51
  const scripts = parsed.scripts;
91
52
  if (!scripts || typeof scripts !== "object" || Array.isArray(scripts))
92
- return null;
53
+ return [];
93
54
  const table = scripts;
94
55
  const { manager, lockfile } = selectJavaScriptRunner(resolution);
95
56
  const source = lockfile === null ? "package.json" : `package.json + ${lockfile}`;
96
- if (isUsableScript(table, "test")) {
97
- // `bun test` is Bun's own runner, not the script, so Bun runs it explicitly.
98
- const command = manager === "bun" ? "bun run test" : `${manager} test`;
99
- return { stack: "javascript", command, provenance: source, verified: false };
100
- }
101
- // No test script: chain the checks the project defines. Only script NAMES
102
- // are used; script bodies are never read into a command.
103
- const chosen = [];
104
- for (const group of FALLBACK_SCRIPT_GROUPS) {
105
- const name = group.find((candidate) => isUsableScript(table, candidate));
106
- if (name !== undefined)
107
- chosen.push(name);
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);
108
61
  }
109
- if (chosen.length === 0)
110
- return null;
111
- return {
62
+ const conflicting = lockManagers.size > 1;
63
+ return Object.entries(table).filter(([name, body]) => isTestScript(name, body)).map(([name]) => ({
112
64
  stack: "javascript",
113
- command: chosen.map((name) => `${manager} run ${name}`).join(" && "),
114
- provenance: `${lockfile === null ? "package.json" : source} scripts (${chosen.join(", ")})`,
115
- verified: false,
116
- };
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
+ }));
117
70
  }
118
71
  /**
119
72
  * Whether a Makefile declares a real `test` target: a rule line (not a recipe,
@@ -140,7 +93,7 @@ async function detectMake(deps) {
140
93
  continue;
141
94
  if (!makefileHasTestTarget(raw))
142
95
  return null;
143
- 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 };
144
97
  }
145
98
  return null;
146
99
  }
@@ -164,12 +117,12 @@ async function detectPython(deps) {
164
117
  async function detectGo(deps) {
165
118
  if ((await readOptional(deps, "go.mod")) === null)
166
119
  return null;
167
- 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 };
168
121
  }
169
122
  async function detectRust(deps) {
170
123
  if ((await readOptional(deps, "Cargo.toml")) === null)
171
124
  return null;
172
- 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 };
173
126
  }
174
127
  /**
175
128
  * Words in the learned `unit_testing_stack` prose that name each stack. Matched
@@ -214,9 +167,8 @@ async function detectCandidates(deps) {
214
167
  const first = resolution.failures[0];
215
168
  throw new DetectionReadError(first.reason === "unreadable" ? "repository_read_failed" : "malformed_repository_file", first.file);
216
169
  }
217
- const found = [];
170
+ const found = await detectJavaScript(deps, resolution);
218
171
  const detectors = [
219
- () => detectJavaScript(deps, resolution),
220
172
  () => detectMake(deps),
221
173
  () => detectPython(deps),
222
174
  () => detectGo(deps),
@@ -225,7 +177,12 @@ async function detectCandidates(deps) {
225
177
  for (const detect of detectors) {
226
178
  const candidate = await detect();
227
179
  if (candidate)
228
- 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
+ });
229
186
  }
230
187
  return found;
231
188
  }
@@ -257,7 +214,7 @@ export async function detectTestCommand(options, deps) {
257
214
  if (candidates.length === 0) {
258
215
  return { status: "none_detected", selected: null, question: "required", candidates };
259
216
  }
260
- if (candidates.length === 1) {
217
+ if (candidates.length === 1 && candidates[0].autoSaveEligible) {
261
218
  return {
262
219
  status: "detected",
263
220
  selected: candidates[0].command,
@@ -267,18 +224,5 @@ export async function detectTestCommand(options, deps) {
267
224
  candidates,
268
225
  };
269
226
  }
270
- // The learned stack is advisory: an unreadable hint falls back to the first
271
- // candidate rather than stopping detection.
272
- const stackHint = await readUnitTestingStack(deps.config);
273
- const named = stacksNamedByHint(stackHint.ok ? stackHint.value : null);
274
- const hinted = candidates.find((c) => named.has(c.stack));
275
- const chosen = hinted ?? candidates[0];
276
- return {
277
- status: "detected",
278
- selected: chosen.command,
279
- provenance: chosen.provenance,
280
- question: "accept_or_replace",
281
- selectedByStackHint: hinted !== undefined,
282
- candidates,
283
- };
227
+ return { status: "alternatives", selected: null, question: "required", candidates };
284
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
+ }
@@ -77,7 +77,9 @@ export async function ensureDeliveryBinding(deps, ticketKey) {
77
77
  remembered.repo_name === deps.repoName &&
78
78
  (sourceBranch === undefined || remembered.source_branch === sourceBranch)) {
79
79
  const confirmed = await confirmExecutorJob(deps, store, ticketKey, journal.registration_key, remembered);
80
- return { enrollment: "resumed", binding: confirmed, newlyRegistered: false };
80
+ return confirmed.replaced
81
+ ? { enrollment: "registered", binding: confirmed.binding, newlyRegistered: true }
82
+ : { enrollment: "resumed", binding: confirmed.binding, newlyRegistered: false };
81
83
  }
82
84
  if (!sourceBranch || sourceBranch === "HEAD") {
83
85
  return unavailable("the source branch could not be read (detached HEAD or git unavailable)");
@@ -92,7 +94,9 @@ export async function ensureDeliveryBinding(deps, ticketKey) {
92
94
  const binding = referenceFrom(recovered.body.binding);
93
95
  await store.recordBindingReference(deps.docsDir, ticketKey, binding);
94
96
  const confirmed = await confirmExecutorJob(deps, store, ticketKey, journal.registration_key, binding);
95
- return { enrollment: "recovered", binding: confirmed, newlyRegistered: false };
97
+ return confirmed.replaced
98
+ ? { enrollment: "registered", binding: confirmed.binding, newlyRegistered: true }
99
+ : { enrollment: "recovered", binding: confirmed.binding, newlyRegistered: false };
96
100
  }
97
101
  if (recovered.status !== 404) {
98
102
  return unavailable(`recovery failed (${recovered.error}): ${recovered.message}`);
@@ -162,8 +166,9 @@ function acknowledgedJobId(body, sent) {
162
166
  */
163
167
  async function confirmExecutorJob(deps, store, ticketKey, registrationKey, binding) {
164
168
  const jobId = deps.executorJobId;
165
- if (jobId === undefined || binding.confirmed_executor_job_id === jobId)
166
- return binding;
169
+ if (jobId === undefined || binding.confirmed_executor_job_id === jobId) {
170
+ return { binding, replaced: false };
171
+ }
167
172
  try {
168
173
  const response = await registerExecution(deps.client, {
169
174
  repo_name: binding.repo_name,
@@ -174,16 +179,24 @@ async function confirmExecutorJob(deps, store, ticketKey, registrationKey, bindi
174
179
  executor_job_id: jobId,
175
180
  });
176
181
  if (!response.ok)
177
- return binding;
182
+ return { binding, replaced: false };
178
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
+ }
179
192
  if (confirmed === undefined)
180
- return binding;
193
+ return { binding, replaced: false };
181
194
  const updated = { ...binding, confirmed_executor_job_id: confirmed };
182
195
  await store.recordBindingReference(deps.docsDir, ticketKey, updated);
183
- return updated;
196
+ return { binding: updated, replaced: false };
184
197
  }
185
198
  catch {
186
- return binding;
199
+ return { binding, replaced: false };
187
200
  }
188
201
  }
189
202
  /**
@@ -0,0 +1,128 @@
1
+ /**
2
+ * BAPI-1557 — recovery-only, run-scoped delivery preparation for the phase tools.
3
+ *
4
+ * A repair worker running in a detached worktree has no branch the server
5
+ * registered, so the ordinary branch-based enrollment cannot find its binding.
6
+ * This module recovers an EXISTING execution by `(repo_name, ticket_number,
7
+ * epic_run_id)` and, when evidence will be written, verifies the repair worktree
8
+ * and captures its head and tree once.
9
+ *
10
+ * It never registers an execution, supersedes a binding, enrolls a branch, or
11
+ * touches local conductor state. It returns closed outcomes only: raw
12
+ * exceptions, git stderr, and filesystem paths never leave this module.
13
+ *
14
+ * Verifying that a worktree belongs to this repository does NOT establish that it
15
+ * is the worktree of this ticket. Assigning the correct repair worktree stays the
16
+ * supervisor's responsibility.
17
+ */
18
+ import { execFile } from "child_process";
19
+ import { realpath } from "fs/promises";
20
+ import path from "path";
21
+ import { recoverExecutionForRun, } from "./ticket-delivery.js";
22
+ import { serverShaOrUndefined } from "./ticket-delivery-enrollment.js";
23
+ /** Bound on each local git call. */
24
+ export const RUN_SCOPE_GIT_TIMEOUT_MS = 5000;
25
+ const WORKTREE_MESSAGES = {
26
+ worktree_unverified: "The repair worktree could not be verified for this repository. No evidence was submitted.",
27
+ worktree_head_changed: "The repair worktree head moved after it was captured. No evidence was submitted.",
28
+ };
29
+ export const defaultRunScopeGitRunner = (cwd, args) => new Promise((resolve, reject) => {
30
+ execFile("git", args, { cwd, shell: false, timeout: RUN_SCOPE_GIT_TIMEOUT_MS, windowsHide: true }, (err, stdout) => {
31
+ if (err)
32
+ reject(err);
33
+ else
34
+ resolve(String(stdout));
35
+ });
36
+ });
37
+ function refusal(outcome) {
38
+ return { ok: false, outcome, status: 0, message: WORKTREE_MESSAGES[outcome] };
39
+ }
40
+ /** Resolve a path Git printed relative to the directory the command ran in. */
41
+ async function canonicalGitPath(cwd, printed, realpathImpl) {
42
+ return realpathImpl(path.resolve(cwd, printed.trim()));
43
+ }
44
+ /**
45
+ * Verify `worktreePath` is an existing, non-bare Git worktree of this repository,
46
+ * then capture its head once and derive the tree from that SHA. Returns
47
+ * `undefined` for every failure; the cause is deliberately not distinguished.
48
+ */
49
+ export async function verifyRepairWorktree(deps, worktreePath) {
50
+ const runGit = deps.runGit ?? defaultRunScopeGitRunner;
51
+ const realpathImpl = deps.realpathImpl ?? realpath;
52
+ try {
53
+ const canonical = await realpathImpl(worktreePath);
54
+ const bare = (await runGit(canonical, ["rev-parse", "--is-bare-repository"])).trim();
55
+ if (bare !== "false")
56
+ return undefined;
57
+ const topLevel = await canonicalGitPath(canonical, await runGit(canonical, ["rev-parse", "--show-toplevel"]), realpathImpl);
58
+ if (topLevel !== canonical)
59
+ return undefined;
60
+ const serverRoot = await realpathImpl(deps.serverRoot);
61
+ const worktreeCommon = await canonicalGitPath(canonical, await runGit(canonical, ["rev-parse", "--git-common-dir"]), realpathImpl);
62
+ const serverCommon = await canonicalGitPath(serverRoot, await runGit(serverRoot, ["rev-parse", "--git-common-dir"]), realpathImpl);
63
+ if (worktreeCommon !== serverCommon)
64
+ return undefined;
65
+ // HEAD is resolved once; the tree comes from that captured SHA, never from a
66
+ // second read of a HEAD that may have moved in between.
67
+ const head = serverShaOrUndefined(await runGit(canonical, ["rev-parse", "HEAD"]));
68
+ if (!head)
69
+ return undefined;
70
+ const tree = serverShaOrUndefined(await runGit(canonical, ["rev-parse", `${head}^{tree}`]));
71
+ if (!tree)
72
+ return undefined;
73
+ return { path: canonical, head, tree };
74
+ }
75
+ catch {
76
+ return undefined;
77
+ }
78
+ }
79
+ /**
80
+ * Recheck, immediately before evidence submission, that the worktree head is still
81
+ * the captured one. Returns the closed refusal when it moved or cannot be read.
82
+ */
83
+ export async function guardWorktreeHead(deps, worktree) {
84
+ const runGit = deps.runGit ?? defaultRunScopeGitRunner;
85
+ try {
86
+ const current = serverShaOrUndefined(await runGit(worktree.path, ["rev-parse", "HEAD"]));
87
+ if (current === worktree.head)
88
+ return { ok: true };
89
+ }
90
+ catch {
91
+ // fall through to the closed refusal
92
+ }
93
+ return {
94
+ ok: false,
95
+ outcome: "worktree_head_changed",
96
+ message: WORKTREE_MESSAGES.worktree_head_changed,
97
+ };
98
+ }
99
+ /**
100
+ * Recover the run's existing execution and, when a worktree is supplied or
101
+ * required, verify it. Recovery runs first so an unmanaged or ambiguous scope
102
+ * reports its own closed outcome. Never throws and never registers anything.
103
+ */
104
+ export async function prepareRunScopedDelivery(deps, options) {
105
+ const recovered = await recoverExecutionForRun(deps.client, {
106
+ repo_name: options.repo_name,
107
+ ticket_number: options.ticket_number.trim().toUpperCase(),
108
+ epic_run_id: options.epic_run_id.trim(),
109
+ });
110
+ if (!recovered.ok) {
111
+ return {
112
+ ok: false,
113
+ outcome: recovered.outcome,
114
+ status: recovered.status,
115
+ message: recovered.message,
116
+ };
117
+ }
118
+ const suppliedPath = options.worktree_path?.trim();
119
+ if (!suppliedPath) {
120
+ if (options.requireVerifiedEvidenceScope)
121
+ return refusal("worktree_unverified");
122
+ return { ok: true, binding: recovered.body.binding };
123
+ }
124
+ const worktree = await verifyRepairWorktree(deps, suppliedPath);
125
+ if (!worktree)
126
+ return refusal("worktree_unverified");
127
+ return { ok: true, binding: recovered.body.binding, worktree };
128
+ }
@@ -1,4 +1,4 @@
1
1
  // AUTO-GENERATED — do not edit manually. Regenerate with: npm run build
2
- export const VERSION = "0.2.71";
3
- export const BUILD_COMMIT = "4cb2a30d7abb";
4
- export const LAUNCHER_ARGS = ["-y", "--prefer-offline", "@bridge_gpt/mcp-server@0.2.71", "serve"];
2
+ export const VERSION = "0.2.72";
3
+ export const BUILD_COMMIT = "bfa72f4a97cf";
4
+ export const LAUNCHER_ARGS = ["-y", "--prefer-offline", "@bridge_gpt/mcp-server@0.2.72", "serve"];