@bridge_gpt/mcp-server 0.2.71 → 0.2.73

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 (198) hide show
  1. package/README.md +55 -17
  2. package/build/agent-launchers/claude-executor-adapter.js +22 -3
  3. package/build/agent-notes.js +171 -95
  4. package/build/agents.generated.js +7 -7
  5. package/build/bridge-permissions.js +31 -0
  6. package/build/bridge-worktree-inspection.js +237 -0
  7. package/build/check-evidence.js +6 -0
  8. package/build/ci-system-detection.js +50 -0
  9. package/build/ci-trigger-adapters.js +631 -0
  10. package/build/ci-trigger-install.js +106 -0
  11. package/build/claude-review-workflow.js +1 -1
  12. package/build/cli-help.js +6 -0
  13. package/build/codex-auto-recovery.js +126 -0
  14. package/build/codex-launcher-pin.js +33 -2
  15. package/build/codex-skill-adapter.js +5 -1
  16. package/build/command-host.js +33 -0
  17. package/build/commands.generated.js +7 -6
  18. package/build/conductor/bridge-api-client.js +1352 -50
  19. package/build/conductor/bring-up-facts.js +18 -5
  20. package/build/conductor/command-drift-production.js +42 -17
  21. package/build/conductor/command-drift.js +47 -0
  22. package/build/conductor/declare-blocked.js +554 -0
  23. package/build/conductor/doctor.js +187 -28
  24. package/build/conductor/driver-commands.js +141 -0
  25. package/build/conductor/driver-guard.js +277 -0
  26. package/build/conductor/driver-lapse.js +321 -0
  27. package/build/conductor/driver-register.js +176 -0
  28. package/build/conductor/driver-release.js +174 -0
  29. package/build/conductor/driver-session-state.js +315 -0
  30. package/build/conductor/epic-branch-ci-inspection.js +222 -29
  31. package/build/conductor/epic-implementer-cli.js +213 -13
  32. package/build/conductor/epic-server-database.js +162 -0
  33. package/build/conductor/epic-server-guidance.js +278 -0
  34. package/build/conductor/epic-server-journal.js +239 -0
  35. package/build/conductor/epic-server-processes.js +324 -0
  36. package/build/conductor/epic-server-recipe.js +397 -0
  37. package/build/conductor/epic-server-runtime.js +1207 -0
  38. package/build/conductor/epic-server-sfcc.js +107 -0
  39. package/build/conductor/epic-server-state.js +427 -0
  40. package/build/conductor/epic-server.js +594 -0
  41. package/build/conductor/gate-discovery.js +281 -10
  42. package/build/conductor/gate-settings-review.js +525 -5
  43. package/build/conductor/git-hooks-uninstall.js +112 -0
  44. package/build/conductor/git-hooks.js +81 -15
  45. package/build/conductor/guided-repair.js +10 -1
  46. package/build/conductor/install-doctor.js +2 -4
  47. package/build/conductor/launch-need-probes.js +6 -53
  48. package/build/conductor/launch-plan.js +318 -121
  49. package/build/conductor/local-merge.js +12 -1
  50. package/build/conductor/merge-execution-contract.js +1 -1
  51. package/build/conductor/merged-child-check.js +2 -1
  52. package/build/conductor/prerequisite-inputs.js +1213 -0
  53. package/build/conductor/readiness-assessment.js +93 -0
  54. package/build/conductor/readiness-cli.js +30 -9
  55. package/build/conductor/readiness-prerequisites.js +77 -5
  56. package/build/conductor/readiness-sections.js +146 -126
  57. package/build/conductor/readiness.js +21 -3
  58. package/build/conductor/recovery-cli.js +236 -15
  59. package/build/conductor/recovery-operations.js +34 -4
  60. package/build/conductor/repair-contract.js +33 -0
  61. package/build/conductor/tools.js +36 -4
  62. package/build/conductor/wait-run-attention.js +115 -0
  63. package/build/conductor/wait-run-cli.js +300 -21
  64. package/build/conductor/worker-database-doctor-inspector.js +34 -2
  65. package/build/conductor/worker-setup-tally.js +27 -0
  66. package/build/credential-store.js +96 -21
  67. package/build/dependency-install-declarations.js +212 -0
  68. package/build/docs.generated.js +4 -4
  69. package/build/doctor.js +91 -8
  70. package/build/drive-epic-help.js +23 -4
  71. package/build/drive-epic.js +1841 -340
  72. package/build/engine-paths.js +20 -0
  73. package/build/epic-branch-ci-summary.js +140 -0
  74. package/build/epic-capability-statement.js +107 -0
  75. package/build/epic-ci-workflow-drift.js +30 -15
  76. package/build/epic-ci-workflow-install.js +110 -42
  77. package/build/epic-ci-workflow-v2.js +274 -0
  78. package/build/epic-ci-workflow.js +38 -12
  79. package/build/epic-implementer-bin.js +2184 -52
  80. package/build/epic-launch-context.js +607 -0
  81. package/build/epic-launch-profile.js +1 -1
  82. package/build/epic-server-record.js +273 -0
  83. package/build/epic-shared/bridge-client.js +11 -3
  84. package/build/escalation-reachability.js +43 -0
  85. package/build/executor/ci-fix-test-runs.js +334 -0
  86. package/build/executor/cli.js +2 -0
  87. package/build/executor/completion-contract.js +24 -1
  88. package/build/executor/credentials.js +1 -1
  89. package/build/executor/delivery-observations.js +113 -0
  90. package/build/executor/delivery-outcome.js +30 -0
  91. package/build/executor/dependency-refresh-runner.js +132 -0
  92. package/build/executor/dependency-refresh.js +530 -0
  93. package/build/executor/deps.js +4 -0
  94. package/build/executor/env.js +119 -17
  95. package/build/executor/epic-server-context.js +141 -0
  96. package/build/executor/gate-qualification-job.js +127 -26
  97. package/build/executor/harness-coverage.js +19 -0
  98. package/build/executor/http-client.js +87 -6
  99. package/build/executor/index.js +2 -1
  100. package/build/executor/install-preflight.js +1 -1
  101. package/build/executor/job-runner.js +659 -87
  102. package/build/executor/likely-tests.js +94 -97
  103. package/build/executor/observation.js +8 -0
  104. package/build/executor/pre-pr-checks.js +363 -0
  105. package/build/executor/prompt-spec.js +127 -5
  106. package/build/executor/reconcile-overlap-job.js +5 -3
  107. package/build/executor/required-verification.js +28 -0
  108. package/build/executor/required-work-diagnostics.js +32 -0
  109. package/build/executor/required-work-ledger.js +955 -39
  110. package/build/executor/results.js +100 -0
  111. package/build/executor/service-discovery.js +42 -0
  112. package/build/executor/service-lifecycle.js +109 -2
  113. package/build/executor/service-uninstall.js +205 -0
  114. package/build/executor/service-unit.js +5 -3
  115. package/build/executor/terminal-mutation.js +8 -0
  116. package/build/executor/test-clock.js +3 -0
  117. package/build/executor/verification-hints.js +179 -0
  118. package/build/executor/worker-command.js +126 -5
  119. package/build/executor/worker-database-config.js +281 -0
  120. package/build/executor/worker-database-target.js +16 -12
  121. package/build/executor/worker-database.js +575 -116
  122. package/build/executor/worker-finalization.js +71 -10
  123. package/build/executor/worker-guard-hook.js +10 -2
  124. package/build/executor/worker-resources.js +25 -3
  125. package/build/executor/worker-verification-guidance.js +55 -5
  126. package/build/executor/worktree-inspection.js +42 -0
  127. package/build/executor/worktree.js +20 -1
  128. package/build/executor-launch.js +54 -2
  129. package/build/generated-assets-catalog.js +2 -2
  130. package/build/github-sign-in.js +1 -1
  131. package/build/index.js +1111 -381
  132. package/build/init.js +29 -14
  133. package/build/install-bridge-conductor-answers.js +465 -0
  134. package/build/install-bridge-conductor-apply.js +259 -0
  135. package/build/install-bridge-conductor-assessment.js +895 -0
  136. package/build/install-bridge-conductor-compact.js +161 -0
  137. package/build/install-bridge-conductor-contracts.js +63 -0
  138. package/build/install-bridge-conductor-gate.js +1383 -188
  139. package/build/install-bridge-conductor-setup.js +637 -92
  140. package/build/install-bridge-conductor.js +3163 -740
  141. package/build/install-bridge.js +601 -128
  142. package/build/install-maintenance.js +127 -0
  143. package/build/install-reexec.js +1 -1
  144. package/build/launcher-config-inspection.js +162 -1
  145. package/build/local-cleanup.js +59 -0
  146. package/build/mcp-grant-candidates.js +767 -0
  147. package/build/mcp-grant-doctor.js +63 -0
  148. package/build/mcp-grant.js +288 -0
  149. package/build/mcp-host-targets.js +8 -0
  150. package/build/mcp-identity.js +23 -0
  151. package/build/mcp-install-state.js +68 -2
  152. package/build/mcp-invoke.js +126 -13
  153. package/build/mcp-presets.js +107 -0
  154. package/build/mcp-provisioning.js +134 -2
  155. package/build/mcp-registration-doctor.js +31 -2
  156. package/build/mcp-server-invocation.js +6 -1
  157. package/build/merge-workflow-install.js +236 -111
  158. package/build/package-script-semantics.js +10 -0
  159. package/build/pipeline-utils.js +1 -1
  160. package/build/pipelines.generated.js +6 -6
  161. package/build/plan-discovery.js +97 -4
  162. package/build/plan-execution-ledger.js +248 -9
  163. package/build/plan-generation-io.js +262 -0
  164. package/build/plan-generation.js +424 -0
  165. package/build/plane/build-freshness.js +6 -1
  166. package/build/plane/cli.js +75 -9
  167. package/build/plane/plane-freshness.js +23 -7
  168. package/build/plane/preflight.js +50 -10
  169. package/build/plane/shutdown.js +19 -0
  170. package/build/plane/terminal-run-cleanup.js +23 -5
  171. package/build/plane/terminal-run-status.js +4 -0
  172. package/build/printed-remedy-commands.js +229 -15
  173. package/build/readiness-check.js +1 -1
  174. package/build/readiness-prerequisites.generated.js +311 -4
  175. package/build/readme.generated.js +1 -1
  176. package/build/repository-state-paths.js +38 -0
  177. package/build/repository-toolchains.js +50 -8
  178. package/build/run-unit-tests-launcher.js +8 -1
  179. package/build/setup-change-policy.js +32 -0
  180. package/build/setup-epic.js +1192 -198
  181. package/build/setup-progress.js +44 -0
  182. package/build/setup-question.js +180 -0
  183. package/build/start-tickets.js +4 -0
  184. package/build/test-command-detection.js +32 -88
  185. package/build/test-support/notes-fs.js +40 -0
  186. package/build/third-party-mcp-targets.js +30 -0
  187. package/build/ticket-delivery-enrollment.js +30 -8
  188. package/build/ticket-delivery-run-scope.js +128 -0
  189. package/build/upgrade-cli.js +85 -2
  190. package/build/v2-readiness-requirements.js +28 -1
  191. package/build/version.generated.js +3 -3
  192. package/build/worker-guard-hook-bin.js +2 -2
  193. package/build/worktrees.js +105 -0
  194. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  195. package/docs/EPIC-IMPLEMENTER.md +5 -0
  196. package/docs/epic-implementer/getting-started.md +42 -15
  197. package/docs/epic-implementer/self-hosting.md +14 -1
  198. package/package.json +2 -2
@@ -7,6 +7,7 @@
7
7
  * delegated to T3b — this ticket only reads the human-readable critique.
8
8
  */
9
9
  import path from "node:path";
10
+ import { CI_FIX_TEST_RUNS_PATH, parseCiFixTestRuns, } from "./ci-fix-test-runs.js";
10
11
  /** Smoke evidence byte cap (mirrors server `SMOKE_EVIDENCE_MAX_BYTES`). */
11
12
  export const SMOKE_EVIDENCE_MAX_BYTES = 8_000;
12
13
  /** Whole-envelope byte cap (mirrors server `RESULT_JSONB_MAX_BYTES`). */
@@ -162,6 +163,44 @@ export const CI_FIX_CHECK_CLAIMS_KEY = "check_fix_claims";
162
163
  export const CI_FIX_ATTRIBUTION_KEY = "ci_failure_attribution";
163
164
  export const CI_FIX_ATTRIBUTION_REASON_KEY = "ci_failure_attribution_reason";
164
165
  export const CI_FIX_ATTRIBUTION_EXTERNAL = "external";
166
+ export const CI_FIX_NO_PUSH_REASON_KEY = "no_push_reason";
167
+ export const CI_FIX_NO_PUSH_REASON_MAX_BYTES = 300;
168
+ /** Optional diagnostics are tolerant; unrelated artifact fields remain strict. */
169
+ export function normalizeCiFixNoPushReason(value) {
170
+ if (value === undefined || value === null)
171
+ return undefined;
172
+ const data = isPlainRecord(value) ? value : {};
173
+ const codes = ["not_reproducible", "external_failure", "already_fixed", "no_safe_change", "other"];
174
+ const reason = {
175
+ code: typeof data.code === "string" && codes.includes(data.code)
176
+ ? data.code : "other",
177
+ };
178
+ if (typeof data.text === "string") {
179
+ // Buffer replaces malformed surrogates; iterate code points when bounding.
180
+ let text = Buffer.from(data.text, "utf8").toString("utf8")
181
+ .replace(/[\s\u0085\u0000-\u001f\u007f-\u009f]+/gu, " ").trim();
182
+ text = text
183
+ .replace(/\b(authorization|cookie|set-cookie|x-api-key|x-bgpt-api-key|x-forge-oauth-system|x-forge-oauth-user)\b[ \t]*[:=][^\r\n]*/gi, "$1: [REDACTED]")
184
+ .replace(/\bBearer\s+\S+/gi, "Bearer [REDACTED]")
185
+ .replace(/\bBasic\s+\S+/gi, "Basic [REDACTED]")
186
+ .replace(/([\w.\-]*(?:token|api[-_]?key|secret|password|passwd|pwd)[\w.\-]*)\s*[:=]\s*\S+/gi, "$1=[REDACTED]")
187
+ .replace(/\b([a-z][a-z0-9+.\-]*:\/\/)[^\s:/@]+:[^\s/@]+@/gi, "$1[REDACTED]@")
188
+ .replace(/\b(?:sk|pk|rk)-[A-Za-z0-9_-]{16,}/g, "[REDACTED]")
189
+ .replace(/\bgh[pousr]_[A-Za-z0-9]{16,}/g, "[REDACTED]");
190
+ const originalBytes = byteLength(text);
191
+ const marker = originalBytes > CI_FIX_NO_PUSH_REASON_MAX_BYTES ? `…[truncated, was ${originalBytes} bytes]` : "";
192
+ const budget = CI_FIX_NO_PUSH_REASON_MAX_BYTES - byteLength(marker);
193
+ let bounded = "";
194
+ for (const point of text) {
195
+ if (byteLength(bounded + point) > budget)
196
+ break;
197
+ bounded += point;
198
+ }
199
+ if (bounded.trim() || marker)
200
+ reason.text = bounded.trimEnd() + marker;
201
+ }
202
+ return reason;
203
+ }
165
204
  /**
166
205
  * Executor-owned status of the artifact, carried at `result.check_fix_claims_status`
167
206
  * so an operator can tell "the worker wrote nothing" from "the worker wrote
@@ -170,6 +209,7 @@ export const CI_FIX_ATTRIBUTION_EXTERNAL = "external";
170
209
  */
171
210
  export const CI_FIX_CLAIMS_STATUS_KEY = "check_fix_claims_status";
172
211
  const CI_FIX_RESULT_ALLOWED_KEYS = new Set([
212
+ CI_FIX_NO_PUSH_REASON_KEY,
173
213
  CI_FIX_CHECK_CLAIMS_KEY,
174
214
  CI_FIX_ATTRIBUTION_KEY,
175
215
  CI_FIX_ATTRIBUTION_REASON_KEY,
@@ -254,6 +294,9 @@ export async function readCiFixResultArtifact(worktreePath, requiredChecks, deps
254
294
  validatedClaims[name] = value;
255
295
  }
256
296
  const fields = { [CI_FIX_CHECK_CLAIMS_KEY]: validatedClaims };
297
+ const noPushReason = normalizeCiFixNoPushReason(parsed[CI_FIX_NO_PUSH_REASON_KEY]);
298
+ if (noPushReason !== undefined)
299
+ fields[CI_FIX_NO_PUSH_REASON_KEY] = noPushReason;
257
300
  const hasAttribution = Object.prototype.hasOwnProperty.call(parsed, CI_FIX_ATTRIBUTION_KEY);
258
301
  const hasReason = Object.prototype.hasOwnProperty.call(parsed, CI_FIX_ATTRIBUTION_REASON_KEY);
259
302
  if (hasAttribution || hasReason) {
@@ -274,3 +317,60 @@ export async function readCiFixResultArtifact(worktreePath, requiredChecks, deps
274
317
  const covered = requiredChecks.every((name) => Object.prototype.hasOwnProperty.call(validatedClaims, name));
275
318
  return { status: covered ? "complete" : "partial", fields };
276
319
  }
320
+ /** BAPI-1582 — the bounded, no-follow pre-PR evidence reader lives with its contract. */
321
+ export { readPrePrEvidenceArtifact } from "./pre-pr-checks.js";
322
+ /**
323
+ * Read `<worktree>/.conductor/ci-fix-test-runs.json` with the same contained,
324
+ * no-follow, bounded read as {@link readCiFixResultArtifact}, capped at
325
+ * {@link RESULT_JSONB_MAX_BYTES}, and validate it against the dispatched logical
326
+ * job. An oversized, unparseable, malformed, or other-job file is never partly
327
+ * trusted. Never throws; `code` is a fixed, secret-free token.
328
+ */
329
+ export async function readCiFixTestRunsArtifact(worktreePath, expected, deps) {
330
+ if (!expected)
331
+ return { status: "invalid", code: "logical_job_unavailable" };
332
+ const directory = path.join(worktreePath, ".conductor");
333
+ const artifactPath = path.join(worktreePath, CI_FIX_TEST_RUNS_PATH);
334
+ if (deps.lstatPath) {
335
+ try {
336
+ const dirMeta = await deps.lstatPath(directory);
337
+ if (dirMeta === null)
338
+ return { status: "missing", code: "artifact_absent" };
339
+ if (!dirMeta.isDirectory || dirMeta.isSymbolicLink) {
340
+ return { status: "invalid", code: "artifact_directory_unsafe" };
341
+ }
342
+ const meta = await deps.lstatPath(artifactPath);
343
+ if (meta === null)
344
+ return { status: "missing", code: "artifact_absent" };
345
+ if (meta.isDirectory || meta.isSymbolicLink) {
346
+ return { status: "invalid", code: "artifact_not_regular_file" };
347
+ }
348
+ }
349
+ catch {
350
+ return { status: "invalid", code: "artifact_unreadable" };
351
+ }
352
+ }
353
+ let raw;
354
+ try {
355
+ raw = await deps.readFile(artifactPath);
356
+ }
357
+ catch (err) {
358
+ const code = err && typeof err === "object" ? err.code : undefined;
359
+ return code === "ENOENT"
360
+ ? { status: "missing", code: "artifact_absent" }
361
+ : { status: "invalid", code: "artifact_unreadable" };
362
+ }
363
+ if (typeof raw !== "string")
364
+ return { status: "invalid", code: "artifact_unreadable" };
365
+ if (byteLength(raw) > RESULT_JSONB_MAX_BYTES)
366
+ return { status: "invalid", code: "artifact_oversized" };
367
+ let parsed;
368
+ try {
369
+ parsed = JSON.parse(raw);
370
+ }
371
+ catch {
372
+ return { status: "invalid", code: "artifact_not_json" };
373
+ }
374
+ const evidence = parseCiFixTestRuns(parsed, expected);
375
+ return evidence ? { status: "valid", evidence } : { status: "invalid", code: "artifact_invalid" };
376
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Filesystem-only discovery for locally installed executor service units.
3
+ *
4
+ * This deliberately neither consults install state nor runs a service manager:
5
+ * an uninstall must be able to show stale on-disk units without credentials or
6
+ * an active executor runtime.
7
+ */
8
+ import { readdir } from "node:fs/promises";
9
+ import { executorIdFromLaunchdFilename, executorIdFromSystemdFilename, executorLaunchdDirForHome, executorLaunchdPlistPathForId, executorSystemdDirForHome, executorSystemdUnitPathForId, validateExecutorId, } from "./service-unit.js";
10
+ const defaultDeps = { readdir };
11
+ /** Enumerate only convention-matching filenames in the fixed per-user directory. */
12
+ export async function discoverExecutorServiceUnits(platform, homeDir, deps = defaultDeps) {
13
+ if (platform !== "darwin" && platform !== "linux")
14
+ return { ok: false, reason: "unsupported-platform" };
15
+ const directory = platform === "darwin" ? executorLaunchdDirForHome(homeDir) : executorSystemdDirForHome(homeDir);
16
+ let names;
17
+ try {
18
+ names = await deps.readdir(directory);
19
+ }
20
+ catch (error) {
21
+ if (error.code === "ENOENT")
22
+ return { ok: true, units: [] };
23
+ return { ok: false, reason: "directory-unavailable" };
24
+ }
25
+ const parser = platform === "darwin" ? executorIdFromLaunchdFilename : executorIdFromSystemdFilename;
26
+ const pathFor = platform === "darwin" ? executorLaunchdPlistPathForId : executorSystemdUnitPathForId;
27
+ return {
28
+ ok: true,
29
+ units: names.flatMap((name) => {
30
+ const executorId = parser(name);
31
+ if (executorId) {
32
+ try {
33
+ validateExecutorId(executorId, platform);
34
+ }
35
+ catch {
36
+ return [];
37
+ }
38
+ }
39
+ return executorId ? [{ executorId, path: pathFor(executorId, homeDir), platform }] : [];
40
+ }).sort((a, b) => a.executorId.localeCompare(b.executorId)),
41
+ };
42
+ }
@@ -4,7 +4,7 @@
4
4
  * WHY THIS MODULE EXISTS SEPARATELY. `service-unit.ts` carries an invariant
5
5
  * titled "Never manages service lifecycle": it renders and writes a unit file
6
6
  * and runs no `launchctl` / `systemctl`. R-1 (2026-08-14) deliberately amends
7
- * the *product* rule — `install conductor` may now start the service the
7
+ * the *product* rule — `install epic-implementer` may now start the service the
8
8
  * generator just wrote — while keeping the *module* rule intact. So lifecycle
9
9
  * lives here, behind its own entry points, and the generator stays lifecycle
10
10
  * free. A caller that only wants a unit written physically cannot start a
@@ -211,6 +211,113 @@ export function formatExecutorServiceStartFailure(result) {
211
211
  : `exit code ${result.exitCode}`;
212
212
  return `service start did not complete: '${result.failedStage}' failed (${detail}).`;
213
213
  }
214
+ /**
215
+ * Build the destructive half of an uninstall. This is pure: callers still
216
+ * obtain consent and verify state before passing the plan to the runner.
217
+ * Linux reload is deliberately absent; it belongs after deleting the unit.
218
+ */
219
+ export function buildExecutorServiceStopPlan(target) {
220
+ if (typeof target.serviceIdentifier !== "string" || target.serviceIdentifier.length === 0) {
221
+ return { ok: false, error: "the service identifier is missing, so no unit can be stopped." };
222
+ }
223
+ if (/[/\\\x00-\x1f\x7f]/.test(target.serviceIdentifier) || target.serviceIdentifier.startsWith("-") ||
224
+ (target.platform === "linux" && !/^[A-Za-z0-9][A-Za-z0-9:_.-]*\.service$/.test(target.serviceIdentifier))) {
225
+ return { ok: false, error: "the service identifier is not a literal user-service target." };
226
+ }
227
+ if (target.platform === "darwin") {
228
+ if (typeof target.uid !== "number" || !Number.isInteger(target.uid) || target.uid < 0) {
229
+ return { ok: false, error: "a numeric uid is required for the launchd domain target." };
230
+ }
231
+ const commands = [{
232
+ stage: "launchctl bootout",
233
+ executable: "launchctl",
234
+ args: ["bootout", `gui/${target.uid}/${target.serviceIdentifier}`],
235
+ }];
236
+ return { ok: true, plan: { platform: "darwin", serviceManager: "launchd", commands, manualCommand: commands.map(renderCommand).join(" && ") } };
237
+ }
238
+ if (target.platform === "linux") {
239
+ const commands = [{
240
+ stage: "systemctl --user disable --now",
241
+ executable: "systemctl",
242
+ args: ["--user", "disable", "--now", target.serviceIdentifier],
243
+ }];
244
+ return { ok: true, plan: { platform: "linux", serviceManager: "systemd-user", commands, manualCommand: commands.map(renderCommand).join(" && ") } };
245
+ }
246
+ return { ok: false, error: "consented service removal is supported on darwin and linux only." };
247
+ }
248
+ /** Execute every planned stop command at most once and stop at the first failure. */
249
+ export async function stopExecutorService(plan, run) {
250
+ let commandsRun = 0;
251
+ for (const command of plan.commands) {
252
+ commandsRun++;
253
+ try {
254
+ const result = await run(command.executable, command.args);
255
+ const exitCode = typeof result?.exitCode === "number" ? result.exitCode : 1;
256
+ if (exitCode !== 0)
257
+ return { ok: false, manualCommand: plan.manualCommand, failedStage: command.stage, exitCode, reason: "nonzero-exit", commandsRun };
258
+ }
259
+ catch {
260
+ return { ok: false, manualCommand: plan.manualCommand, failedStage: command.stage, exitCode: null, reason: "runner-refused", commandsRun };
261
+ }
262
+ }
263
+ return { ok: true, manualCommand: plan.manualCommand, commandsRun };
264
+ }
265
+ /** Linux only: run after the unit file was deleted or found absent. */
266
+ export async function reloadExecutorServiceManager(platform, run) {
267
+ if (platform !== "linux")
268
+ return { ok: true, manualCommand: "", commandsRun: 0 };
269
+ const command = { stage: "systemctl --user daemon-reload", executable: "systemctl", args: ["--user", "daemon-reload"] };
270
+ return stopExecutorService({ platform, serviceManager: "systemd-user", commands: [command], manualCommand: renderCommand(command) }, run);
271
+ }
272
+ export function formatExecutorServiceStopFailure(result) {
273
+ const detail = result.reason === "runner-refused" ? "the command could not be run on this host" : `exit code ${result.exitCode}`;
274
+ return `service stop did not complete: '${result.failedStage}' failed (${detail}).`;
275
+ }
276
+ /** Strict uninstall observation; ordinary diagnostic compatibility stays intact. */
277
+ export async function inspectExecutorServiceForUninstall(target, run) {
278
+ const unknown = { state: "unknown", disabled: false, definitionAbsent: false };
279
+ const probe = buildExecutorServiceStateProbe(target);
280
+ if (!probe)
281
+ return unknown;
282
+ try {
283
+ if (target.platform === "darwin") {
284
+ const result = await run(probe.executable, probe.args);
285
+ if (result.exitCode === 0)
286
+ return { state: "active", disabled: false, definitionAbsent: false };
287
+ // Permission/session errors must never be mistaken for an unloaded job.
288
+ const expected = `Could not find service "${target.serviceIdentifier}" in domain for user gui: ${target.uid}`;
289
+ const lines = [result.stdout ?? "", result.stderr ?? ""].join("\n").split(/\r?\n/).map(line => line.trim()).filter(Boolean);
290
+ // Real launchctl on macOS 26 prefixes the exact absence line with
291
+ // `Bad request.`. Keep target/domain matching strict, including exit 113.
292
+ if (result.exitCode === 113 && lines.filter(line => line === expected).length === 1 && lines.every(line => line === expected || line === "Bad request."))
293
+ return { state: "absent", disabled: true, definitionAbsent: true };
294
+ return unknown;
295
+ }
296
+ const result = await run("systemctl", ["--user", "show", target.serviceIdentifier, "--property=LoadState,ActiveState,UnitFileState"]);
297
+ if (result.exitCode !== 0)
298
+ return unknown;
299
+ const values = new Map((result.stdout ?? "").trim().split(/\r?\n/).map(line => {
300
+ const at = line.indexOf("=");
301
+ return [line.slice(0, at), line.slice(at + 1)];
302
+ }));
303
+ const load = values.get("LoadState"), active = values.get("ActiveState"), enabled = values.get("UnitFileState");
304
+ if (load === "not-found" && active === "inactive")
305
+ return { state: "absent", disabled: true, definitionAbsent: true };
306
+ if (load !== "loaded")
307
+ return unknown;
308
+ const disabled = enabled === "disabled" || enabled === "static" || enabled === "masked";
309
+ if (active === "active")
310
+ return { state: "active", disabled, definitionAbsent: false };
311
+ if (active === "inactive" || active === "failed")
312
+ return { state: "stopped", disabled, definitionAbsent: false };
313
+ if (["activating", "deactivating", "reloading"].includes(active ?? ""))
314
+ return { state: "transitional", disabled, definitionAbsent: false };
315
+ return unknown;
316
+ }
317
+ catch {
318
+ return unknown;
319
+ }
320
+ }
214
321
  /**
215
322
  * Build the strictly read-only state probe for a target.
216
323
  *
@@ -370,7 +477,7 @@ export async function inspectExecutorServiceDurability(target, run) {
370
477
  // durability the probe did not establish.
371
478
  //
372
479
  // A ZERO exit is NOT `configured`. It says the gui/<uid> domain exists at
373
- // this instant — which it does whenever an operator runs `install conductor`
480
+ // this instant — which it does whenever an operator runs `install epic-implementer`
374
481
  // or `doctor` from their own logged-in session — and a LaunchAgent in that
375
482
  // domain is tied to the login, not to the machine being powered on. Calling
376
483
  // it `configured` would let a renderer that means "survives logout" assert
@@ -0,0 +1,205 @@
1
+ /** Consented local removal of one home-scoped executor service. */
2
+ import { lstat, readFile, unlink } from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { confirmLocalCleanup, runLocalCommand } from "../local-cleanup.js";
6
+ import { forgetInstalledExecutorServiceUnit } from "../mcp-install-state.js";
7
+ import { posixShellQuote, xmlEscape } from "../platform-escaping.js";
8
+ import { MCP_PACKAGE_NAME } from "../mcp-identity.js";
9
+ import { discoverExecutorServiceUnits } from "./service-discovery.js";
10
+ import { buildExecutorServiceStopPlan, stopExecutorService, reloadExecutorServiceManager, inspectExecutorServiceForUninstall } from "./service-lifecycle.js";
11
+ import { executorLaunchdPlistPathForId, executorSystemdUnitPathForId, executorLaunchdLabelForId, executorSystemdUnitNameForId, executorLaunchdLogPathsForId, inspectExecutorServiceArtifact, validateExecutorId } from "./service-unit.js";
12
+ import { parseExecutorWorktreeLock } from "./worktree-lock.js";
13
+ import { parseGitWorktreePorcelain } from "./worktree-inspection.js";
14
+ export function getExecutorUninstallServiceUsage() {
15
+ return "Usage: mcp-server executor uninstall-service [--executor-id <id>] [--dry-run]\nWithout an id, list filesystem-discovered units. Removal requires interactive consent; logs are retained.\n -h, --help Show help.";
16
+ }
17
+ /** A matching live worker lock is positive job evidence. Unknown remains disclosed. */
18
+ async function localActivity(cwd, executorId) {
19
+ const list = await runLocalCommand("git", ["worktree", "list", "--porcelain"], cwd);
20
+ if (list.exitCode !== 0)
21
+ return "unknown";
22
+ for (const wt of parseGitWorktreePorcelain(list.stdout)) {
23
+ try {
24
+ const raw = await readFile(path.join(wt.path, ".conductor", "worker.lock"), "utf8");
25
+ const owner = parseExecutorWorktreeLock(raw);
26
+ if (!owner)
27
+ continue;
28
+ if (owner.executorId !== executorId)
29
+ continue;
30
+ try {
31
+ process.kill(owner.ownerPid, 0);
32
+ return "active";
33
+ }
34
+ catch (error) {
35
+ if (error.code !== "ESRCH")
36
+ return "unknown";
37
+ }
38
+ }
39
+ catch (error) {
40
+ if (error.code !== "ENOENT")
41
+ return "unknown";
42
+ }
43
+ }
44
+ // Other repositories may be served by this home-scoped unit.
45
+ return "unknown";
46
+ }
47
+ export async function runExecutorUninstallServiceCli(argv, overrides = {}) {
48
+ const deps = { platform: process.platform, homeDir: os.homedir(), cwd: process.cwd(), uid: process.getuid?.() ?? null,
49
+ isTTY: Boolean(process.stdin.isTTY && process.stdout.isTTY), log: text => process.stderr.write(text + "\n"), prompt: confirmLocalCleanup,
50
+ run: runLocalCommand, lstat, readFile, unlink, discover: discoverExecutorServiceUnits, forget: forgetInstalledExecutorServiceUnit, activity: localActivity, ...overrides };
51
+ let id, dryRun = false;
52
+ for (let i = 0; i < argv.length; i++) {
53
+ if (argv[i] === "--help" || argv[i] === "-h") {
54
+ deps.log(getExecutorUninstallServiceUsage());
55
+ return 0;
56
+ }
57
+ if (argv[i] === "--dry-run")
58
+ dryRun = true;
59
+ else if (argv[i] === "--executor-id" && !id && argv[i + 1] && !argv[i + 1].startsWith("--"))
60
+ id = argv[++i];
61
+ else {
62
+ deps.log("Invalid uninstall-service arguments.\n" + getExecutorUninstallServiceUsage());
63
+ return 1;
64
+ }
65
+ }
66
+ if (deps.platform !== "darwin" && deps.platform !== "linux") {
67
+ deps.log("Service removal supports darwin and linux only.");
68
+ return 1;
69
+ }
70
+ const platform = deps.platform;
71
+ if (!id) {
72
+ const found = await deps.discover(platform, deps.homeDir);
73
+ if (!found.ok) {
74
+ deps.log("Executor service directory unavailable; no absence is established.");
75
+ return 0;
76
+ }
77
+ for (const unit of found.units)
78
+ deps.log(`${unit.executorId}: ${unit.path}`);
79
+ if (!found.units.length)
80
+ deps.log("No executor service unit files found.");
81
+ return 0;
82
+ }
83
+ try {
84
+ validateExecutorId(id, platform);
85
+ }
86
+ catch {
87
+ deps.log("Invalid executor id.");
88
+ return 1;
89
+ }
90
+ const unitPath = platform === "darwin" ? executorLaunchdPlistPathForId(id, deps.homeDir) : executorSystemdUnitPathForId(id, deps.homeDir);
91
+ const identifier = platform === "darwin" ? executorLaunchdLabelForId(id) : executorSystemdUnitNameForId(id);
92
+ const target = { platform, unitPath, serviceIdentifier: identifier, uid: deps.uid };
93
+ const built = buildExecutorServiceStopPlan(target);
94
+ if (!built.ok) {
95
+ deps.log(built.error);
96
+ return 1;
97
+ }
98
+ const snapshot = async () => {
99
+ try {
100
+ const stat = await deps.lstat(unitPath);
101
+ if (!stat.isFile() || stat.isSymbolicLink())
102
+ throw new Error("unsafe");
103
+ const bytes = await deps.readFile(unitPath);
104
+ if (bytes.length > 1024 * 1024)
105
+ throw new Error("oversize");
106
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
107
+ const inspection = inspectExecutorServiceArtifact(platform === "darwin" ? "launchd-plist" : "systemd-service", text);
108
+ if (!inspection.ok || inspection.executorId !== id || text.includes("\0"))
109
+ throw new Error("identity");
110
+ if (platform === "darwin") {
111
+ const labels = [...text.matchAll(/<key>Label<\/key>\s*<string>([^<]*)<\/string>/g)];
112
+ if (labels.length !== 1 || labels[0][1] !== xmlEscape(identifier))
113
+ throw new Error("label");
114
+ }
115
+ return { stat, bytes };
116
+ }
117
+ catch (error) {
118
+ if (error.code === "ENOENT")
119
+ return null;
120
+ throw error;
121
+ }
122
+ };
123
+ try {
124
+ const before = await snapshot();
125
+ const unchanged = async () => {
126
+ const now = await snapshot();
127
+ return before === null ? now === null : now !== null && now.stat.ino === before.stat.ino && now.stat.dev === before.stat.dev && now.stat.mode === before.stat.mode && now.bytes.equals(before.bytes);
128
+ };
129
+ const activity = await deps.activity(deps.cwd, id);
130
+ deps.log(`Executor: ${id}\nUnit: ${unitPath}\nPhases: stop/unload, verify stopped, delete definition, reload (Linux), verify removal, forget current-repository locator.\nService removal is home-scoped; locator cleanup is limited to the current repository.\nLocal job activity: ${activity}. Live service state has not yet been probed.\nStopping may interrupt jobs and does not certify termination of every child process. Finish or stop work through the existing executor/plane workflow first.`);
131
+ if (platform === "darwin") {
132
+ const logs = executorLaunchdLogPathsForId(id, deps.homeDir);
133
+ deps.log(`Retained logs for manual review:\n${logs.stdout}\n${logs.stderr}`);
134
+ }
135
+ else
136
+ deps.log("Linux logs are retained in the user journald journal.");
137
+ if (dryRun) {
138
+ deps.log("dry run — nothing was removed");
139
+ return 0;
140
+ }
141
+ if (activity === "active") {
142
+ deps.log("Retained: active worker evidence. Finish the job before retrying.");
143
+ return 0;
144
+ }
145
+ if (!deps.isTTY || !await deps.prompt(`Remove executor service ${id}?`)) {
146
+ deps.log("declined — nothing was removed");
147
+ return 0;
148
+ }
149
+ if (await deps.activity(deps.cwd, id) === "active" || !await unchanged()) {
150
+ deps.log("Retained: activity or definition changed after consent.");
151
+ return 0;
152
+ }
153
+ const initial = await inspectExecutorServiceForUninstall(target, deps.run);
154
+ if (initial.state === "unknown" || initial.state === "transitional") {
155
+ deps.log("Failed: service state unavailable; unit and locator retained.");
156
+ return 1;
157
+ }
158
+ if (initial.state !== "absent") {
159
+ const stopped = await stopExecutorService(built.plan, deps.run);
160
+ if (!stopped.ok) {
161
+ const raced = await inspectExecutorServiceForUninstall(target, deps.run);
162
+ if (raced.state !== "absent") {
163
+ deps.log(`Failed: ${stopped.failedStage}; unit and locator retained. Manual recovery: ${stopped.manualCommand}`);
164
+ return 1;
165
+ }
166
+ }
167
+ }
168
+ const stopped = await inspectExecutorServiceForUninstall(target, deps.run);
169
+ if (!(platform === "darwin" ? stopped.state === "absent" : (stopped.state === "stopped" || stopped.state === "absent") && stopped.disabled)) {
170
+ deps.log("Failed: stop verification; unit and locator retained.");
171
+ return 1;
172
+ }
173
+ if (!await unchanged()) {
174
+ deps.log("Failed: definition changed; retained.");
175
+ return 1;
176
+ }
177
+ if (before) {
178
+ await deps.unlink(unitPath);
179
+ deps.log(`Completed: deleted ${unitPath}`);
180
+ }
181
+ const reload = await reloadExecutorServiceManager(platform, deps.run);
182
+ const final = reload.ok ? await inspectExecutorServiceForUninstall(target, deps.run) : null;
183
+ if (!final || final.state !== "absent" || !final.definitionAbsent) {
184
+ deps.log("Failed: final service verification; locator retained.");
185
+ return 1;
186
+ }
187
+ const root = await deps.run("git", ["rev-parse", "--show-toplevel"], deps.cwd);
188
+ if (root.exitCode === 0) {
189
+ const forgotten = await deps.forget(root.stdout.trim(), unitPath, deps.homeDir);
190
+ if (!forgotten.ok) {
191
+ deps.log(`Failed: current-repository locator retained (${forgotten.reason}). Retry: npx -y ${MCP_PACKAGE_NAME} executor uninstall-service --executor-id ${posixShellQuote(id)}`);
192
+ return 1;
193
+ }
194
+ deps.log(`Completed: locator ${forgotten.outcome}.`);
195
+ }
196
+ else
197
+ deps.log("Current directory is outside a repository; no locator cleanup attempted.");
198
+ deps.log(before ? "Completed: executor service removed; logs retained." : "nothing to remove — service already absent; stale locator reconciled and logs retained.");
199
+ return 0;
200
+ }
201
+ catch {
202
+ deps.log("Failed: unsafe or unavailable service definition; retained remaining resources.");
203
+ return 1;
204
+ }
205
+ }
@@ -52,7 +52,7 @@
52
52
  * longer forbidden to Bridge outright: consented, one-shot start and
53
53
  * read-only state inspection now live in a SEPARATE module,
54
54
  * {@link ../executor/service-lifecycle.js `executor/service-lifecycle.ts`},
55
- * which `install conductor` drives behind its own independent consent. The
55
+ * which `install epic-implementer` drives behind its own independent consent. The
56
56
  * split is the point — a caller that wants a unit written cannot
57
57
  * accidentally start a persistent daemon, because the two capabilities are
58
58
  * in different modules with different entry points.
@@ -935,7 +935,7 @@ export function getExecutorInstallServiceUsage() {
935
935
  "The FILE-GENERATION LEG of durable-host mode. It writes one unit and stops there.",
936
936
  "For the supported composed bring-up — planning, consented write, consented start,",
937
937
  "read-only local inspection, and bounded server-observed readiness — run",
938
- "`install conductor` instead. Use this command when you deliberately manage the",
938
+ "`install epic-implementer` instead. Use this command when you deliberately manage the",
939
939
  "service lifecycle yourself.",
940
940
  "",
941
941
  "Generates ONE long-running user-domain service unit for ONE stable executor id:",
@@ -978,7 +978,7 @@ export function getExecutorInstallServiceUsage() {
978
978
  "host's output is readable after the fact; a systemd --user unit logs to journald.",
979
979
  "",
980
980
  "This command writes a file and nothing else. Starting, stopping, enabling, and",
981
- "removing the service stay operator-managed via launchctl / systemctl --user /",
981
+ "removing the service use separately consented executor uninstall-service, or launchctl / systemctl --user /",
982
982
  "Task Scheduler. A written unit is NOT readiness, and neither is a started one:",
983
983
  "only a server-observed executor claim, after a start you perform separately, makes",
984
984
  "this host ready to do work.",
@@ -1400,6 +1400,7 @@ function formatPostWriteGuidance(artifact, executorId) {
1400
1400
  ` launchctl bootstrap gui/$(id -u) ${posixShellQuote(artifact.path)}`,
1401
1401
  ` launchctl print gui/$(id -u)/${label} # status`,
1402
1402
  ` launchctl bootout gui/$(id -u)/${label} # stop + unload`,
1403
+ ` npx -y ${MCP_SERVER_PACKAGE_NAME} executor uninstall-service --executor-id ${posixShellQuote(executorId)} # consented removal`,
1403
1404
  "",
1404
1405
  "Starting it is still not readiness: this host is ready only once the Bridge",
1405
1406
  "server observes an executor claim from it.",
@@ -1411,6 +1412,7 @@ function formatPostWriteGuidance(artifact, executorId) {
1411
1412
  " systemctl --user daemon-reload",
1412
1413
  ` systemctl --user enable --now ${unit}`,
1413
1414
  ` systemctl --user status ${unit}`,
1415
+ ` npx -y ${MCP_SERVER_PACKAGE_NAME} executor uninstall-service --executor-id ${posixShellQuote(executorId)} # consented removal`,
1414
1416
  "",
1415
1417
  "On a headless host, also run `loginctl enable-linger $USER` so the user service",
1416
1418
  "keeps running without an active login session.",
@@ -7,6 +7,9 @@
7
7
  * window has not elapsed; then abandon.
8
8
  * - `invalid_job_result` → (complete only) terminal non-success; the server has
9
9
  * already failed the job, so DO NOT then call `/fail`.
10
+ * - completion-evidence refusal (BAPI-1590, marked) → one send, no retry, not
11
+ * abandoned; the job is still running, so the runner may
12
+ * send its `/fail`.
10
13
  *
11
14
  * Retry diagnostics are bounded and never include raw result envelopes, secrets,
12
15
  * or unbounded stdout/stderr.
@@ -31,6 +34,11 @@ export async function sendTerminalMutationWithRetry(params) {
31
34
  // a lost/stale claim) and never invokes `send()` a second time.
32
35
  return { outcome: "auth_fatal", httpStatus: mapped.authHttpStatus ?? 401 };
33
36
  }
37
+ // BAPI-1590: ordered BEFORE the stale-claim branch on purpose.
38
+ if (mapped.completionEvidenceRefused === true) {
39
+ params.log?.(`${params.kind}: server refused success on the completion evidence`);
40
+ return { outcome: "completion_evidence_refused", completionEvidenceRefused: true };
41
+ }
34
42
  if (outcome === "stale_claim") {
35
43
  ownership.abandoned = true;
36
44
  ownership.abandonReason = "stale_claim";
@@ -144,6 +144,9 @@ export function makeFakeExecutorDeps(clock, overrides = {}) {
144
144
  throw Object.assign(new Error("ENOENT"), { code: "ENOENT" });
145
145
  },
146
146
  writeFile: async () => { },
147
+ // BAPI-1551: no hints file. The real reader's filesystem I/O would resolve
148
+ // outside the virtual clock's microtask flush and strand the spawn.
149
+ readVerificationHints: async () => ({ status: "missing" }),
147
150
  // The exclude writer publishes through a temporary file plus rename.
148
151
  rename: async () => { },
149
152
  mkdir: async () => undefined,