@bridge_gpt/mcp-server 0.2.70 → 0.2.72

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/README.md +55 -17
  2. package/build/agent-launchers/claude-executor-adapter.js +29 -4
  3. package/build/agent-notes.js +171 -95
  4. package/build/agent-registry.js +5 -5
  5. package/build/agents.generated.js +12 -2
  6. package/build/bounded-wait.js +9 -1
  7. package/build/bridge-permissions.js +17 -5
  8. package/build/bridge-worktree-inspection.js +237 -0
  9. package/build/check-evidence.js +6 -0
  10. package/build/claude-review-workflow.js +1 -1
  11. package/build/cli-help.js +6 -0
  12. package/build/codex-auto-recovery.js +126 -0
  13. package/build/codex-skill-adapter.js +2 -0
  14. package/build/commands.generated.js +5 -5
  15. package/build/conductor/bridge-api-client.js +776 -23
  16. package/build/conductor/command-drift-production.js +7 -2
  17. package/build/conductor/doctor.js +93 -13
  18. package/build/conductor/epic-implementer-cli.js +55 -2
  19. package/build/conductor/gate-discovery.js +659 -19
  20. package/build/conductor/gate-settings-review.js +751 -0
  21. package/build/conductor/git-hooks-uninstall.js +112 -0
  22. package/build/conductor/git-hooks.js +81 -15
  23. package/build/conductor/guided-repair.js +10 -1
  24. package/build/conductor/install-doctor.js +2 -4
  25. package/build/conductor/launch-need-probes.js +16 -11
  26. package/build/conductor/launch-plan.js +185 -0
  27. package/build/conductor/local-merge.js +12 -1
  28. package/build/conductor/merge-execution-contract.js +1 -1
  29. package/build/conductor/merged-child-check.js +2 -1
  30. package/build/conductor/precheck-timings.js +14 -0
  31. package/build/conductor/prerequisite-inputs.js +379 -0
  32. package/build/conductor/preview-observations.js +10 -0
  33. package/build/conductor/readiness-assessment.js +78 -0
  34. package/build/conductor/readiness-cli.js +10 -0
  35. package/build/conductor/readiness-prerequisites.js +53 -0
  36. package/build/conductor/readiness-sections.js +25 -9
  37. package/build/conductor/readiness.js +20 -2
  38. package/build/conductor/recovery-cli.js +281 -14
  39. package/build/conductor/recovery-operations.js +78 -5
  40. package/build/conductor/repair-contract.js +33 -0
  41. package/build/conductor/tools.js +34 -3
  42. package/build/conductor/wait-run-attention.js +115 -0
  43. package/build/conductor/wait-run-cli.js +96 -3
  44. package/build/conductor/worker-database-doctor-inspector.js +1 -0
  45. package/build/credential-store.js +25 -20
  46. package/build/dependency-install-declarations.js +157 -0
  47. package/build/docs.generated.js +4 -4
  48. package/build/doctor.js +37 -5
  49. package/build/drive-epic-help.js +2 -2
  50. package/build/drive-epic.js +240 -56
  51. package/build/epic-ci-workflow-drift.js +71 -23
  52. package/build/epic-ci-workflow-install.js +83 -26
  53. package/build/epic-ci-workflow-v1.js +132 -0
  54. package/build/epic-ci-workflow.js +174 -13
  55. package/build/epic-implementer-bin.js +119 -44
  56. package/build/epic-launch-profile.js +1 -1
  57. package/build/executor/ci-rerun-job.js +220 -14
  58. package/build/executor/cli.js +2 -0
  59. package/build/executor/completion-contract.js +16 -0
  60. package/build/executor/credentials.js +1 -1
  61. package/build/executor/delivery-observations.js +113 -0
  62. package/build/executor/delivery-outcome.js +30 -0
  63. package/build/executor/dependency-refresh-runner.js +132 -0
  64. package/build/executor/dependency-refresh.js +530 -0
  65. package/build/executor/deps.js +4 -0
  66. package/build/executor/env.js +274 -5
  67. package/build/executor/gate-qualification-job.js +20 -5
  68. package/build/executor/harness-coverage.js +19 -0
  69. package/build/executor/http-client.js +35 -1
  70. package/build/executor/index.js +2 -1
  71. package/build/executor/install-preflight.js +1 -1
  72. package/build/executor/job-runner.js +355 -36
  73. package/build/executor/likely-tests.js +100 -98
  74. package/build/executor/preflight.js +5 -0
  75. package/build/executor/process-containment.js +18 -0
  76. package/build/executor/prompt-spec.js +84 -15
  77. package/build/executor/reconcile-overlap-job.js +6 -1
  78. package/build/executor/required-verification.js +28 -0
  79. package/build/executor/required-work-diagnostics.js +30 -0
  80. package/build/executor/required-work-ledger.js +19 -1
  81. package/build/executor/results.js +42 -0
  82. package/build/executor/service-discovery.js +42 -0
  83. package/build/executor/service-lifecycle.js +109 -2
  84. package/build/executor/service-uninstall.js +205 -0
  85. package/build/executor/service-unit.js +5 -3
  86. package/build/executor/test-clock.js +3 -0
  87. package/build/executor/verification-hints.js +179 -0
  88. package/build/executor/worker-command.js +188 -1
  89. package/build/executor/worker-database.js +299 -40
  90. package/build/executor/worker-finalization.js +65 -10
  91. package/build/executor/worker-guard-hook.js +10 -2
  92. package/build/executor/worker-resources.js +12 -1
  93. package/build/executor/worker-verification-guidance.js +64 -0
  94. package/build/executor/worktree-inspection.js +42 -0
  95. package/build/github-sign-in.js +1 -1
  96. package/build/index.js +767 -310
  97. package/build/init.js +3 -3
  98. package/build/install-bridge-conductor-gate.js +416 -41
  99. package/build/install-bridge-conductor-setup.js +135 -32
  100. package/build/install-bridge-conductor.js +769 -353
  101. package/build/install-bridge.js +419 -124
  102. package/build/install-maintenance.js +104 -0
  103. package/build/install-reexec.js +1 -1
  104. package/build/local-cleanup.js +59 -0
  105. package/build/mcp-install-state.js +68 -2
  106. package/build/merge-workflow-install.js +22 -2
  107. package/build/package-script-semantics.js +10 -0
  108. package/build/pipeline-utils.js +1 -1
  109. package/build/pipelines.generated.js +6 -6
  110. package/build/plan-execution-ledger.js +171 -10
  111. package/build/plane/plane-freshness.js +12 -9
  112. package/build/plane/preflight.js +19 -0
  113. package/build/plane/terminal-run-cleanup.js +5 -1
  114. package/build/plane/terminal-run-status.js +4 -0
  115. package/build/printed-remedy-commands.js +31 -4
  116. package/build/readiness-check.js +1 -78
  117. package/build/readiness-prerequisites.generated.js +199 -0
  118. package/build/readme.generated.js +1 -1
  119. package/build/repository-toolchains.js +623 -0
  120. package/build/setup-change-policy.js +32 -0
  121. package/build/setup-epic.js +26 -9
  122. package/build/setup-question.js +62 -0
  123. package/build/start-tickets.js +4 -0
  124. package/build/test-command-detection.js +61 -80
  125. package/build/test-support/notes-fs.js +40 -0
  126. package/build/ticket-delivery-artifacts.js +7 -0
  127. package/build/ticket-delivery-enrollment.js +80 -4
  128. package/build/ticket-delivery-run-scope.js +128 -0
  129. package/build/version.generated.js +3 -3
  130. package/build/worker-guard-hook-bin.js +2 -2
  131. package/build/worktrees.js +105 -0
  132. package/docs/EPIC-IMPLEMENTER.md +43 -0
  133. package/docs/epic-implementer/getting-started.md +95 -14
  134. package/package.json +2 -2
@@ -0,0 +1,112 @@
1
+ /** Byte-preserving removal of managed hook spans, independent of hook runtime. */
2
+ import { lstat, readFile, open, rename, unlink } from "node:fs/promises";
3
+ import { randomUUID } from "node:crypto";
4
+ import { join } from "node:path";
5
+ import { confirmLocalCleanup } from "../local-cleanup.js";
6
+ import { MANAGED_HOOK_NAMES, BRIDGE_CONDUCTOR_HOOK_START, BRIDGE_CONDUCTOR_HOOK_END, removeManagedHookSnippet, resolveGitHooksDirectory } from "./git-hooks.js";
7
+ export async function planConductorGitHooksUninstall(deps = {}) {
8
+ const directory = resolveGitHooksDirectory(deps);
9
+ if (!directory.hooks_dir)
10
+ throw new Error("hooks directory unavailable");
11
+ const io = deps.io ?? { lstat, readFile, open, rename, unlink };
12
+ const items = [];
13
+ for (const name of MANAGED_HOOK_NAMES) {
14
+ const target = join(directory.hooks_dir, name);
15
+ try {
16
+ const stat = await io.lstat(target);
17
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size > 1024 * 1024) {
18
+ items.push({ path: target, action: "retained", warning: "unsafe hook file" });
19
+ continue;
20
+ }
21
+ const bytes = await io.readFile(target);
22
+ const content = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
23
+ const removal = removeManagedHookSnippet(content);
24
+ items.push({ path: target, ...removal, snapshot: { bytes, dev: stat.dev, ino: stat.ino, mode: stat.mode } });
25
+ }
26
+ catch (error) {
27
+ items.push({ path: target, action: error.code === "ENOENT" ? "unchanged" : "retained", warning: error.code === "ENOENT" ? undefined : "hook bytes unavailable" });
28
+ }
29
+ }
30
+ return items;
31
+ }
32
+ export async function uninstallConductorGitHooks(items, deps = {}) {
33
+ const io = deps.io ?? { lstat, readFile, open, rename, unlink };
34
+ const results = [];
35
+ let ok = true;
36
+ for (const item of items) {
37
+ if (item.action === "unchanged") {
38
+ results.push({ path: item.path, outcome: "nothing to remove" });
39
+ continue;
40
+ }
41
+ if (item.action === "retained" || !item.snapshot) {
42
+ ok = false;
43
+ results.push({ path: item.path, outcome: `retained: ${item.warning}; owner repair required between ${BRIDGE_CONDUCTOR_HOOK_START} and ${BRIDGE_CONDUCTOR_HOOK_END}` });
44
+ continue;
45
+ }
46
+ const temp = `${item.path}.${randomUUID()}.tmp`;
47
+ let owned = false;
48
+ try {
49
+ if (item.action === "rewrite") {
50
+ const handle = await io.open(temp, "wx", 0o600);
51
+ owned = true;
52
+ try {
53
+ await handle.writeFile(item.content, "utf8");
54
+ await handle.chmod(item.snapshot.mode & 0o7777);
55
+ }
56
+ finally {
57
+ await handle.close();
58
+ }
59
+ }
60
+ const now = await io.lstat(item.path);
61
+ if (!now.isFile() || now.isSymbolicLink() || now.dev !== item.snapshot.dev || now.ino !== item.snapshot.ino || now.mode !== item.snapshot.mode || !(await io.readFile(item.path)).equals(item.snapshot.bytes))
62
+ throw new Error("changed");
63
+ if (item.action === "delete")
64
+ await io.unlink(item.path);
65
+ else {
66
+ await io.rename(temp, item.path);
67
+ owned = false;
68
+ }
69
+ results.push({ path: item.path, outcome: item.action === "delete" ? "deleted" : "user content restored" });
70
+ }
71
+ catch {
72
+ ok = false;
73
+ results.push({ path: item.path, outcome: "retained: changed or unavailable; retry after owner review" });
74
+ }
75
+ finally {
76
+ if (owned)
77
+ await io.unlink(temp).catch(() => { });
78
+ }
79
+ }
80
+ return { ok, results };
81
+ }
82
+ export async function runUninstallGitHooksCommand(argv) {
83
+ if (argv.includes("--help") || argv.includes("-h")) {
84
+ process.stderr.write("Usage: epic-implementer uninstall-git-hooks [--dry-run]\nRemove only Bridge-managed hook text with interactive consent.\n");
85
+ return 0;
86
+ }
87
+ if (argv.some(arg => arg !== "--dry-run")) {
88
+ process.stderr.write("Unsupported uninstall-git-hooks argument.\n");
89
+ return 1;
90
+ }
91
+ try {
92
+ const items = await planConductorGitHooksUninstall();
93
+ for (const item of items)
94
+ process.stderr.write(`${item.path}: ${item.action}${item.warning ? ` (${item.warning})` : ""}\n`);
95
+ if (argv.includes("--dry-run")) {
96
+ process.stderr.write("dry run — nothing was removed\n");
97
+ return 0;
98
+ }
99
+ if (!await confirmLocalCleanup("Remove only Bridge-managed text from these shared Git hooks?")) {
100
+ process.stderr.write("declined — nothing was removed\n");
101
+ return 0;
102
+ }
103
+ const result = await uninstallConductorGitHooks(items);
104
+ for (const item of result.results)
105
+ process.stderr.write(`${item.path}: ${item.outcome}\n`);
106
+ return result.ok ? 0 : 1;
107
+ }
108
+ catch {
109
+ process.stderr.write("Git hook removal unavailable; files retained. Run from a Git worktree.\n");
110
+ return 1;
111
+ }
112
+ }
@@ -296,6 +296,50 @@ export function buildReferenceTransactionHookSnippet(conductorBin) {
296
296
  function looksBinary(content) {
297
297
  return content.includes("\u0000");
298
298
  }
299
+ /** Unique line-bounded managed span, rejecting ambiguous marker arrangements. */
300
+ export function managedHookSpan(content) {
301
+ const starts = [...content.matchAll(new RegExp(BRIDGE_CONDUCTOR_HOOK_START.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"))];
302
+ const ends = [...content.matchAll(new RegExp(BRIDGE_CONDUCTOR_HOOK_END.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"))];
303
+ if (!starts.length && !ends.length)
304
+ return null;
305
+ if (starts.length !== 1 || ends.length !== 1)
306
+ return "unsafe";
307
+ const start = starts[0].index, end = ends[0].index + BRIDGE_CONDUCTOR_HOOK_END.length;
308
+ if (end <= start || (start > 0 && content[start - 1] !== "\n") || (end < content.length && content[end] !== "\n" && content.slice(end, end + 2) !== "\r\n"))
309
+ return "unsafe";
310
+ return { start, end };
311
+ }
312
+ const SEPARATOR_METADATA = "# bridge-hook-separators-v1:";
313
+ function withSeparatorMetadata(block, prefix, suffix) {
314
+ return block.replace(BRIDGE_CONDUCTOR_HOOK_START, `${BRIDGE_CONDUCTOR_HOOK_START}\n${SEPARATOR_METADATA}${Buffer.from(prefix).toString("hex")}:${Buffer.from(suffix).toString("hex")}`);
315
+ }
316
+ export function removeManagedHookSnippet(existing) {
317
+ if (looksBinary(existing))
318
+ return { action: "retained", content: existing, warning: "unsafe hook bytes" };
319
+ const span = managedHookSpan(existing);
320
+ if (span === "unsafe")
321
+ return { action: "retained", content: existing, warning: "ambiguous managed markers" };
322
+ if (span === null)
323
+ return { action: "unchanged", content: existing };
324
+ let start = span.start, end = span.end;
325
+ const metadata = existing.slice(start, end).split(/\r?\n/)[1];
326
+ let warning;
327
+ if (metadata?.startsWith(SEPARATOR_METADATA)) {
328
+ const match = metadata.slice(SEPARATOR_METADATA.length).match(/^((?:0a)?):((?:0a)?)$/);
329
+ if (!match)
330
+ return { action: "retained", content: existing, warning: "invalid separator provenance" };
331
+ const prefix = Buffer.from(match[1], "hex").toString(), suffix = Buffer.from(match[2], "hex").toString();
332
+ if ((prefix && existing.slice(start - prefix.length, start) !== prefix) || (suffix && existing.slice(end, end + suffix.length) !== suffix))
333
+ return { action: "retained", content: existing, warning: "separator provenance changed" };
334
+ start -= prefix.length;
335
+ end += suffix.length;
336
+ }
337
+ else
338
+ warning = "legacy block: adjacent user newlines retained";
339
+ const content = existing.slice(0, start) + existing.slice(end);
340
+ const deletable = /^\s*$/.test(content) || /^\s*#![^\r\n]*(?:\r?\n)?\s*$/.test(content);
341
+ return { action: deletable ? "delete" : "rewrite", content, ...(warning ? { warning } : {}) };
342
+ }
299
343
  /**
300
344
  * Insert or replace ONLY the conductor-managed block within existing hook content,
301
345
  * preserving all surrounding user content. A binary/unsafe existing hook is left
@@ -304,7 +348,7 @@ function looksBinary(content) {
304
348
  */
305
349
  export function mergeManagedHookSnippet(existing, managedBlock) {
306
350
  if (existing === null || existing.length === 0) {
307
- const content = `#!/bin/sh\n${managedBlock}\n`;
351
+ const content = `#!/bin/sh\n${withSeparatorMetadata(managedBlock, "", "\n")}\n`;
308
352
  return { ok: true, content, action: "created" };
309
353
  }
310
354
  if (looksBinary(existing)) {
@@ -315,17 +359,20 @@ export function mergeManagedHookSnippet(existing, managedBlock) {
315
359
  warning: "existing hook appears binary/unsafe to merge; left untouched",
316
360
  };
317
361
  }
318
- const startIdx = existing.indexOf(BRIDGE_CONDUCTOR_HOOK_START);
319
- const endIdx = existing.indexOf(BRIDGE_CONDUCTOR_HOOK_END);
320
- if (startIdx !== -1 && endIdx !== -1 && endIdx > startIdx) {
321
- const before = existing.slice(0, startIdx);
322
- const after = existing.slice(endIdx + BRIDGE_CONDUCTOR_HOOK_END.length);
323
- const content = `${before}${managedBlock}${after}`;
362
+ const span = managedHookSpan(existing);
363
+ if (span === "unsafe")
364
+ return { ok: false, content: existing, action: "skipped", warning: "ambiguous managed markers; left untouched" };
365
+ if (span) {
366
+ const before = existing.slice(0, span.start);
367
+ const after = existing.slice(span.end);
368
+ const metadata = existing.slice(span.start, span.end).split(/\r?\n/)[1];
369
+ const replacement = metadata?.startsWith(SEPARATOR_METADATA) ? managedBlock.replace(BRIDGE_CONDUCTOR_HOOK_START, `${BRIDGE_CONDUCTOR_HOOK_START}\n${metadata}`) : managedBlock;
370
+ const content = `${before}${replacement}${after}`;
324
371
  return { ok: true, content, action: "replaced" };
325
372
  }
326
373
  // No managed block yet — append after the user's content, preserving it.
327
374
  const separator = existing.endsWith("\n") ? "" : "\n";
328
- const content = `${existing}${separator}${managedBlock}\n`;
375
+ const content = `${existing}${separator}${withSeparatorMetadata(managedBlock, separator, "\n")}\n`;
329
376
  return { ok: true, content, action: "appended" };
330
377
  }
331
378
  /** Stable discriminator for an install that never touched the filesystem. */
@@ -377,7 +424,7 @@ const DEFAULT_PUBLICATION_FS = {
377
424
  lstat: (filePath) => {
378
425
  try {
379
426
  const st = lstatSync(filePath);
380
- return { isFile: st.isFile(), isSymlink: st.isSymbolicLink(), mode: st.mode & 0o7777 };
427
+ return { isFile: st.isFile(), isSymlink: st.isSymbolicLink(), mode: st.mode & 0o7777, dev: st.dev, ino: st.ino };
381
428
  }
382
429
  catch (err) {
383
430
  if (err.code === "ENOENT")
@@ -385,7 +432,7 @@ const DEFAULT_PUBLICATION_FS = {
385
432
  throw err;
386
433
  }
387
434
  },
388
- readFile: (filePath) => readFileSync(filePath, "utf-8"),
435
+ readFile: (filePath) => new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(readFileSync(filePath)),
389
436
  };
390
437
  /**
391
438
  * The mode a published hook gets: the ORIGINAL mode with only the missing
@@ -489,7 +536,7 @@ export function installConductorGitHooks(deps = {}) {
489
536
  refused.push({ name, path: hookPath, warning: "could not read existing hook; left untouched" });
490
537
  continue;
491
538
  }
492
- snapshot = { content, mode: stat.mode };
539
+ snapshot = { content, mode: stat.mode, dev: stat.dev, ino: stat.ino };
493
540
  }
494
541
  const merge = mergeManagedHookSnippet(snapshot?.content ?? null, snippetForHook(name, conductorBin));
495
542
  if (!merge.ok) {
@@ -585,6 +632,8 @@ function targetMatchesSnapshot(plan, fs) {
585
632
  return false;
586
633
  if (current.mode !== plan.snapshot.mode)
587
634
  return false;
635
+ if (current.dev !== plan.snapshot.dev || current.ino !== plan.snapshot.ino)
636
+ return false;
588
637
  return fs.readFile(plan.path) === plan.snapshot.content;
589
638
  }
590
639
  function publishPlannedHook(plan, hooksDir, fs, platform) {
@@ -771,12 +820,20 @@ export function inspectConductorGitHooks(deps = {}) {
771
820
  const hooks = [];
772
821
  for (const name of MANAGED_HOOK_NAMES) {
773
822
  const hookPath = resolve(hooks_dir, name);
774
- const exists = existsSync(hookPath);
823
+ let exists = false;
824
+ let existenceUnknown = false;
825
+ try {
826
+ lstatSync(hookPath);
827
+ exists = true;
828
+ }
829
+ catch (error) {
830
+ existenceUnknown = error.code !== "ENOENT";
831
+ }
775
832
  let executable = false;
776
833
  let managedPresent = false;
777
834
  let embeddedBinPath = null;
778
835
  let embeddedBinIsFile = false;
779
- let state = "not-installed";
836
+ let state = existenceUnknown ? "unknown" : "not-installed";
780
837
  if (exists) {
781
838
  try {
782
839
  const mode = statSync(hookPath).mode;
@@ -787,7 +844,12 @@ export function inspectConductorGitHooks(deps = {}) {
787
844
  }
788
845
  state = "no-managed-block";
789
846
  try {
790
- const content = readFileSync(hookPath, "utf-8");
847
+ const stat = lstatSync(hookPath);
848
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1024 * 1024)
849
+ throw new Error("unsafe");
850
+ const content = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(readFileSync(hookPath));
851
+ if (looksBinary(content) || managedHookSpan(content) === "unsafe")
852
+ throw new Error("unsafe");
791
853
  managedPresent = content.includes(BRIDGE_CONDUCTOR_HOOK_START);
792
854
  if (managedPresent) {
793
855
  // BAPI-772: a managed block is not enough — the block written by an
@@ -801,7 +863,10 @@ export function inspectConductorGitHooks(deps = {}) {
801
863
  embeddedBinPath !== null &&
802
864
  basename(embeddedBinPath) === CONDUCTOR_BIN_FILENAME &&
803
865
  defaultIsFile(embeddedBinPath);
804
- if (embeddedBinPath === null) {
866
+ if (deps.presenceOnly) {
867
+ state = "unrecognized";
868
+ }
869
+ else if (embeddedBinPath === null) {
805
870
  state = "unrecognized";
806
871
  }
807
872
  else {
@@ -825,6 +890,7 @@ export function inspectConductorGitHooks(deps = {}) {
825
890
  exists,
826
891
  executable,
827
892
  managed_block_present: managedPresent,
893
+ managed_block_observation: state === "unknown" ? "unknown" : managedPresent ? "present" : "absent",
828
894
  embedded_bin_path: embeddedBinPath,
829
895
  embedded_bin_is_file: embeddedBinIsFile,
830
896
  recognized_command: embeddedBinPath !== null,
@@ -35,6 +35,7 @@ export const GUIDED_REPAIR_VERBS = [
35
35
  // BAPI-1388 — ticket-addressed, pinned to the same version-and-head subject as
36
36
  // `dispatch-remediation`, and consuming the binding ExplainRun renders.
37
37
  "rerun-ci",
38
+ "adopt-current-head-and-unpark",
38
39
  ];
39
40
  /** A malformed or mismatched binding. The message never echoes the token. */
40
41
  export class GuidedBindingError extends Error {
@@ -61,6 +62,7 @@ const ALLOWED_KEYS = {
61
62
  "scope-catch-up": ["scope_id", "lifecycle_state", "required_commit_sha"],
62
63
  "dispatch-remediation": ["ticket_key", "expected_row_version", "expected_head_sha"],
63
64
  "rerun-ci": ["ticket_key", "expected_row_version", "expected_head_sha"],
65
+ "adopt-current-head-and-unpark": ["ticket_key", "expected_row_version", "external_repair_operation_id"],
64
66
  };
65
67
  function invalid() {
66
68
  return new GuidedBindingError("--binding is not a valid guided-repair binding; nothing was sent. Copy the " +
@@ -152,10 +154,16 @@ export function decodeGuidedBinding(token) {
152
154
  throw invalid();
153
155
  }
154
156
  }
155
- else if (guidedVerb === "dispatch-remediation" || guidedVerb === "rerun-ci") {
157
+ else if (guidedVerb === "dispatch-remediation" || guidedVerb === "rerun-ci" || guidedVerb === "adopt-current-head-and-unpark") {
156
158
  binding.ticketKey = boundedString(raw.ticket_key, 64);
157
159
  binding.expectedRowVersion = nonNegativeInt(raw.expected_row_version);
158
160
  binding.expectedHeadSha = optionalSha(raw.expected_head_sha);
161
+ if (guidedVerb === "adopt-current-head-and-unpark") {
162
+ const operation = boundedString(raw.external_repair_operation_id, 128);
163
+ if (!/^[A-Za-z0-9._:-]+$/.test(operation))
164
+ throw invalid();
165
+ binding.externalRepairOperationId = operation;
166
+ }
159
167
  }
160
168
  else {
161
169
  binding.scopeId = boundedString(raw.scope_id, 200);
@@ -181,6 +189,7 @@ export function bindingIdentity(binding) {
181
189
  ["required_commit_sha", binding.requiredCommitSha],
182
190
  ["ticket_key", binding.ticketKey],
183
191
  ["expected_row_version", binding.expectedRowVersion],
192
+ ["external_repair_operation_id", binding.externalRepairOperationId],
184
193
  ["expected_head_sha", binding.expectedHeadSha],
185
194
  ];
186
195
  for (const [key, value] of pairs) {
@@ -18,7 +18,7 @@
18
18
  * doctor reports about it.
19
19
  *
20
20
  * BAPI-775 adds three more named sections for the LOCAL conductor capabilities
21
- * `install conductor` can now provision: host MCP profile-token presence,
21
+ * `install epic-implementer` can now provision: host MCP profile-token presence,
22
22
  * managed hook-target usability, and native ledger loadability. All three are
23
23
  * DERIVED — from the shared read-only host-config inspector and from the legacy
24
24
  * conductor report already composed above — so none of them re-probes anything
@@ -129,9 +129,7 @@ export async function runConductorInstallDoctor(deps) {
129
129
  }
130
130
  else {
131
131
  try {
132
- readiness = deps.epicRunId
133
- ? await fetchConductorReadiness(deps.access, deps.fetch, { epicRunId: deps.epicRunId })
134
- : await fetchConductorReadiness(deps.access, deps.fetch);
132
+ readiness = await fetchConductorReadiness(deps.access, deps.fetch, { epicRunId: deps.epicRunId, assessmentVersion: deps.assessmentVersion });
135
133
  }
136
134
  catch (err) {
137
135
  const kind = err instanceof ConductorBridgeApiError ? err.kind : "network";
@@ -201,6 +201,22 @@ export async function inspectRequiredSelfHostedRunners(input) {
201
201
  async function probeRunners(input) {
202
202
  const now = input.now ?? Date.now;
203
203
  const deadline = now() + LAUNCH_RUNNER_PROBE_DEADLINE_MS;
204
+ // Every workflow job, from both `.yml` and `.yaml` files.
205
+ const dir = path.join(input.repoRoot, ".github", "workflows");
206
+ let files;
207
+ try {
208
+ files = (await input.workflows.list(dir)).filter((file) => /\.ya?ml$/.test(file)).sort();
209
+ }
210
+ catch (error) {
211
+ const code = error.code;
212
+ if (code === "ENOENT" || code === "ENOTDIR")
213
+ return { state: "not_applicable", reason: "no_github_actions_workflows" };
214
+ return { state: "unverifiable", reason: "workflows_unreadable" };
215
+ }
216
+ if (files.length > WORKFLOW_MAX_FILES)
217
+ return { state: "unverifiable", reason: "workflows_unreadable" };
218
+ if (files.length === 0)
219
+ return { state: "not_applicable", reason: "no_github_actions_workflows" };
204
220
  const profile = input.gateProfile;
205
221
  if (profile === null || profile === undefined || profile.read_failed || !Array.isArray(profile.provider_checks)) {
206
222
  return { state: "unverifiable", reason: "no_gate_profile" };
@@ -213,17 +229,6 @@ async function probeRunners(input) {
213
229
  }
214
230
  if (required.length === 0)
215
231
  return { state: "not_applicable" };
216
- // Every workflow job, from both `.yml` and `.yaml` files.
217
- const dir = path.join(input.repoRoot, ".github", "workflows");
218
- let files;
219
- try {
220
- files = (await input.workflows.list(dir)).filter((file) => /\.ya?ml$/.test(file)).sort();
221
- }
222
- catch {
223
- return { state: "unverifiable", reason: "workflows_unreadable" };
224
- }
225
- if (files.length > WORKFLOW_MAX_FILES)
226
- return { state: "unverifiable", reason: "workflows_unreadable" };
227
232
  const jobs = [];
228
233
  for (const file of files) {
229
234
  try {
@@ -0,0 +1,185 @@
1
+ import { sanitizeHarnessCoverage } from "../executor/harness-coverage.js";
2
+ import { EPIC_KEY_PATTERN } from "../drive-epic-key.js";
3
+ import { ESCALATION_REACHABILITY_CHECK_ID } from "../escalation-reachability.js";
4
+ import { LAUNCH_NEEDS, LAUNCH_NEED_ROW_IDS, LAUNCH_NEED_REMEDIES } from "./readiness-sections.js";
5
+ import { WORKER_DATABASE_DOCTOR_OWNER, WORKER_DATABASE_DOCTOR_RUNBOOK_SECTION, formatOwnerRoles, sanitizeOwnerRoles, sanitizeOwnerRoleTotal, } from "./doctor.js";
6
+ import { normalizeRepoRelativePath } from "./file-scope-guard.js";
7
+ /**
8
+ * Advisory decision table (source order within each group):
9
+ * reachability unconfirmed | proceed | [] | fix the channel before retrying
10
+ * already merged child (will skip) | skip | [] | keep: [--keep-child, KEY]
11
+ * probably_done child | run it | [] | skip: [--skip-child, KEY]
12
+ * applicable relevant role / other unhealthy DB | fix first | [] | launch anyway: []
13
+ * asked/present runner | fix first | [] | launch anyway: []
14
+ * asked/present power | proceed, keep the lid open | [] | fix first: []
15
+ * asked/present usage | proceed | [] | fix first: []
16
+ * Fix-first acceptance accepts unresolved risk; it never performs remediation.
17
+ * verification_gap belongs exclusively to the command session, not this union.
18
+ */
19
+ /** Bridge-specific hints are consulted only after positive repository applicability. */
20
+ export const DB_OR_HARNESS_PATH_HINTS = ["db/alembic/", "tests/integration/conductor_harness/", "migrations/"];
21
+ export function planDatabaseRelevance(nodes, applicable) {
22
+ if (!applicable || !Array.isArray(nodes))
23
+ return "unknown";
24
+ let declared = false;
25
+ let malformed = false;
26
+ let relevant = false;
27
+ for (const node of nodes) {
28
+ if (!isObject(node)) {
29
+ malformed = true;
30
+ continue;
31
+ }
32
+ if (!("touched_files" in node))
33
+ continue;
34
+ if (!Array.isArray(node.touched_files)) {
35
+ malformed = true;
36
+ continue;
37
+ }
38
+ declared = true;
39
+ for (const raw of node.touched_files) {
40
+ const path = normalizeRepoRelativePath(raw);
41
+ if (path === null) {
42
+ malformed = true;
43
+ continue;
44
+ }
45
+ if (DB_OR_HARNESS_PATH_HINTS.some((hint) => path.startsWith(hint)) || path.includes("/migrations/"))
46
+ relevant = true;
47
+ }
48
+ }
49
+ return relevant ? true : malformed || !declared ? "unknown" : false;
50
+ }
51
+ export const LAUNCH_PLAN_REACHABILITY_COPY = {
52
+ summary: "Escalation reachability",
53
+ reason: "Live delivery is not confirmed; escalations are also shown in the driving session.",
54
+ remedy: "Declare notify.webhook_url in the run policy, or configure live email.",
55
+ };
56
+ export const LAUNCH_PLAN_MERGED_CHILD_COPY = {
57
+ summary: "Already merged child",
58
+ reason: "The child is already merged on the indexed commit and is scheduled to be skipped.",
59
+ remedy: "Nothing to do, or keep the child in this plan to run it again.",
60
+ };
61
+ export const LAUNCH_PLAN_CHILD_COPY = {
62
+ summary: "Probably done child",
63
+ reason: "The child is on the indexed commit but has no confirmed delivery record; run it to be sure.",
64
+ remedy: "Run the child, or explicitly skip it in this plan.",
65
+ };
66
+ export const LAUNCH_PLAN_NEED_COPY = {
67
+ worker_db_role: { summary: "Worker DB role", reason: "This database-relevant plan needs a safe worker database role.", recommendation: "fix first" },
68
+ self_hosted_runner: { summary: "Self-hosted runner", reason: "Child CI cannot become green while the required runner is offline.", recommendation: "fix first" },
69
+ host_power: { summary: "Host sleep", reason: "The executor needs the host to remain awake during the run.", recommendation: "proceed, keep the lid open" },
70
+ usage_reset_after_run: { summary: "Usage reset after the run", reason: "Capacity waits resume automatically when usage resets.", recommendation: "proceed" },
71
+ };
72
+ export const LAUNCH_PLAN_DB_COPY = {
73
+ "worker-db-boundary": { summary: "Worker database boundary", reason: "The worker database boundary is not confirmed healthy." },
74
+ "worker-db-alembic": { summary: "Worker database migrations", reason: "The operator migration state is not confirmed healthy." },
75
+ "worker-db-leftovers": { summary: "Worker database leftovers", reason: "Worker database cleanup needs attention." },
76
+ "worker-db-unverifiable": { summary: "Worker database inspection", reason: "Worker database safety could not be verified." },
77
+ "worker-db-harness": { summary: "Worker database harness", reason: "Harness database cleanup is not confirmed healthy." },
78
+ };
79
+ function isObject(value) {
80
+ return value !== null && typeof value === "object" && !Array.isArray(value);
81
+ }
82
+ /** Only complete, asked/present typed rows participate. Untrusted prose is never copied. */
83
+ function eligibleNeed(row) {
84
+ const meta = row.launch_need;
85
+ if (!isObject(meta) || !LAUNCH_NEEDS.includes(meta.need))
86
+ return undefined;
87
+ const need = meta.need;
88
+ if (need === "epic_branch_behind_base" || row.id !== LAUNCH_NEED_ROW_IDS[need] ||
89
+ meta.asked !== true || meta.state !== "present" || row.status !== "warn" ||
90
+ row.blocking !== false || typeof row.remedy !== "string" || row.remedy.trim() === "")
91
+ return undefined;
92
+ return { need, state: "present", asked: true };
93
+ }
94
+ function item(id, kind, copy, recommendation, alternatives) {
95
+ return { id, kind, ...copy, recommendation, alternatives, flags_if_accepted: [] };
96
+ }
97
+ /**
98
+ * The worker-database remedy. Fixed wording; the only variable part is the list of
99
+ * owner roles, revalidated here from the typed `owner_roles` field. Free prose in
100
+ * `detail` is never read. No usable owner keeps the historical remedy byte for byte.
101
+ */
102
+ function workerDatabaseRemedy(id, row) {
103
+ const historical = `${WORKER_DATABASE_DOCTOR_OWNER}: see ${WORKER_DATABASE_DOCTOR_RUNBOOK_SECTION}`;
104
+ if (id !== "worker-db-harness")
105
+ return historical;
106
+ const roles = sanitizeOwnerRoles(row.owner_roles);
107
+ if (roles.length === 0)
108
+ return historical;
109
+ const shown = formatOwnerRoles(roles, sanitizeOwnerRoleTotal(row.owner_role_total, roles.length));
110
+ return (`${WORKER_DATABASE_DOCTOR_OWNER}: terminate sessions and drop the leftover harness databases as their owner ` +
111
+ `role (${shown}), not the CI role; see ${WORKER_DATABASE_DOCTOR_RUNBOOK_SECTION}`);
112
+ }
113
+ /** Pure projection of a finished preview; no admission decision or input is changed. */
114
+ export function buildLaunchPlan(preview) {
115
+ if (preview.decision !== "create")
116
+ return undefined;
117
+ const rows = Array.isArray(preview.launch_checks) ? preview.launch_checks.filter(isObject) : [];
118
+ const items = [];
119
+ const seen = new Set();
120
+ const add = (entry) => {
121
+ if (!seen.has(entry.id)) {
122
+ seen.add(entry.id);
123
+ items.push(entry);
124
+ }
125
+ };
126
+ if (preview.summary?.escalation_channel !== "webhook" &&
127
+ !rows.some((row) => row.id === ESCALATION_REACHABILITY_CHECK_ID && row.status === "pass")) {
128
+ add(item(ESCALATION_REACHABILITY_CHECK_ID, "reachability", LAUNCH_PLAN_REACHABILITY_COPY, "proceed", [{ choice: "fix first", flags: [] }]));
129
+ }
130
+ const children = preview.already_done_children;
131
+ if (isObject(children) && children.status === "checked" && Array.isArray(children.children)) {
132
+ for (const child of children.children) {
133
+ if (!isObject(child) || child.classification !== "done" || child.will_skip !== true ||
134
+ typeof child.ticket_key !== "string" || !EPIC_KEY_PATTERN.test(child.ticket_key))
135
+ continue;
136
+ add(item(`already-merged-${child.ticket_key}`, "already_merged", {
137
+ ...LAUNCH_PLAN_MERGED_CHILD_COPY, summary: `${LAUNCH_PLAN_MERGED_CHILD_COPY.summary} ${child.ticket_key}`,
138
+ }, "skip", [{ choice: "keep", flags: ["--keep-child", child.ticket_key] }]));
139
+ }
140
+ for (const child of children.children) {
141
+ if (!isObject(child) || child.classification !== "probably_done" || child.will_skip !== false ||
142
+ typeof child.ticket_key !== "string" || !EPIC_KEY_PATTERN.test(child.ticket_key))
143
+ continue;
144
+ add(item(`probably-done-${child.ticket_key}`, "probably_done", {
145
+ ...LAUNCH_PLAN_CHILD_COPY, summary: `${LAUNCH_PLAN_CHILD_COPY.summary} ${child.ticket_key}`,
146
+ }, "run it", [{ choice: "skip", flags: ["--skip-child", child.ticket_key] }]));
147
+ }
148
+ }
149
+ const addNeed = (row, need) => {
150
+ const copy = LAUNCH_PLAN_NEED_COPY[need];
151
+ add(item(LAUNCH_NEED_ROW_IDS[need], need === "worker_db_role" ? "worker_db" : "launch_need", {
152
+ summary: copy.summary, reason: copy.reason, remedy: LAUNCH_NEED_REMEDIES[need],
153
+ }, copy.recommendation, [{ choice: copy.recommendation === "fix first" ? "launch anyway" : "fix first", flags: [] }]));
154
+ };
155
+ for (const row of rows) {
156
+ // The role never falls through into generic database handling, even if malformed.
157
+ if (row.id === LAUNCH_NEED_ROW_IDS.worker_db_role) {
158
+ if (eligibleNeed(row)?.need === "worker_db_role" && preview.plan_database_relevance === true)
159
+ addNeed(row, "worker_db_role");
160
+ continue;
161
+ }
162
+ if (typeof row.id !== "string" || !Object.hasOwn(LAUNCH_PLAN_DB_COPY, row.id) ||
163
+ !["warn", "fail", "unverified"].includes(row.status) || row.blocking !== false)
164
+ continue;
165
+ const id = row.id;
166
+ const coverage = id === "worker-db-harness" ? sanitizeHarnessCoverage(row.harness_coverage) : undefined;
167
+ if (coverage && coverage.total > 0 && coverage.activity === "known" && coverage.uncovered === 0) {
168
+ add(item(id, "worker_db", {
169
+ summary: "Harness databases in use or CI-owned",
170
+ remedy: "Proceed; no harness cleanup is requested by launch.",
171
+ reason: "Every harness database is in use or CI-owned; no harness cleanup is requested by launch.",
172
+ }, "proceed", []));
173
+ continue;
174
+ }
175
+ add(item(id, "worker_db", { ...LAUNCH_PLAN_DB_COPY[id], remedy: workerDatabaseRemedy(id, row) }, "fix first", [{ choice: "launch anyway", flags: [] }]));
176
+ }
177
+ for (const need of LAUNCH_NEEDS) {
178
+ if (need === "worker_db_role" || need === "epic_branch_behind_base")
179
+ continue;
180
+ const row = rows.find((row) => eligibleNeed(row)?.need === need);
181
+ if (row)
182
+ addNeed(row, need);
183
+ }
184
+ return { launch_plan: { version: 1, items, fix_first: items.some((entry) => entry.recommendation === "fix first") } };
185
+ }
@@ -1342,7 +1342,18 @@ export async function runApprovedLocalMerge(request, options = {}, deps = {}) {
1342
1342
  },
1343
1343
  ]);
1344
1344
  }
1345
- const executor = makeLocalMergeExecutor({ method: options.method, skipCiWait: true }, { ...deps, credential });
1345
+ // BAPI-1564 — a `merge-child --carry-gaps` approval forwards the server-resolved
1346
+ // base, so the ordered ref guard refuses `ref_mismatch` for a retargeted PR
1347
+ // before any merge subprocess. `--match-head-commit` still pins the head. The
1348
+ // guard cannot pin the base atomically for `gh`; a retarget in that last window
1349
+ // is caught at completion, which re-reads the provider base and head.
1350
+ const executor = makeLocalMergeExecutor({
1351
+ method: options.method,
1352
+ skipCiWait: true,
1353
+ ...(options.expectedBaseBranch !== undefined
1354
+ ? { expectedBaseBranch: options.expectedBaseBranch }
1355
+ : {}),
1356
+ }, { ...deps, credential });
1346
1357
  // `access` is only ever used by the CI poll, which `skipCiWait` bypasses. The
1347
1358
  // throwing stub makes that structural, not a comment: if a future edit ever
1348
1359
  // reaches the poll from this path, it fails loudly in tests instead of
@@ -84,7 +84,7 @@ export function mergeWorkflowVersionSupportsIntegrationActions(version) {
84
84
  * (`install`), not the launcher that starts it. The Python mirror derives its
85
85
  * command head from this value.
86
86
  */
87
- export const MERGE_WORKFLOW_SUBCOMMAND = "install conductor --merge-workflow";
87
+ export const MERGE_WORKFLOW_SUBCOMMAND = "install epic-implementer --merge-workflow";
88
88
  /**
89
89
  * The complete, copy-ready command that generates the merge workflow and opens
90
90
  * its pull request. Every refusal, remediation, and readiness line imports this
@@ -5,7 +5,8 @@
5
5
  * file, or touches the network except through the injected `classify` function.
6
6
  *
7
7
  * The posture is conservative: only a current server verdict of `done` (completed
8
- * delivery binding, confirmed merge commit, covered by the indexed cut) is ever
8
+ * delivery binding, or an active binding with no live executor whose own branch
9
+ * merged outside this run, plus a confirmed merge commit covered by the indexed cut) is ever
9
10
  * skipped on its own. `probably_done` needs the operator's explicit `--skip-child`.
10
11
  * Every uncertain, failed, or malformed result keeps the child in the plan.
11
12
  */
@@ -0,0 +1,14 @@
1
+ export const monotonicNow = () => performance.now();
2
+ export function elapsedMs(started, now = monotonicNow) {
3
+ const elapsed = now() - started;
4
+ return Number.isFinite(elapsed) ? Math.max(0, elapsed) : 0;
5
+ }
6
+ export async function measurePrecheck(run, record, now = monotonicNow) {
7
+ const started = now();
8
+ try {
9
+ return await run();
10
+ }
11
+ finally {
12
+ record(elapsedMs(started, now));
13
+ }
14
+ }