@bridge_gpt/mcp-server 0.2.72 → 0.2.74

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 (181) hide show
  1. package/README.md +5 -5
  2. package/build/agent-launchers/claude-executor-adapter.js +15 -0
  3. package/build/agents.generated.js +6 -6
  4. package/build/bridge-config.js +7 -1
  5. package/build/bridge-permissions.js +30 -0
  6. package/build/ci-system-detection.js +50 -0
  7. package/build/ci-trigger-adapters.js +631 -0
  8. package/build/ci-trigger-install.js +106 -0
  9. package/build/codex-launcher-pin.js +33 -2
  10. package/build/codex-skill-adapter.js +3 -1
  11. package/build/command-host.js +33 -0
  12. package/build/command-provisioning.js +4 -3
  13. package/build/commands.generated.js +7 -6
  14. package/build/conductor/bridge-api-client.js +867 -35
  15. package/build/conductor/bring-up-facts.js +18 -5
  16. package/build/conductor/command-drift-production.js +42 -17
  17. package/build/conductor/command-drift.js +48 -1
  18. package/build/conductor/declare-blocked.js +554 -0
  19. package/build/conductor/declared-extras.js +335 -0
  20. package/build/conductor/doctor.js +108 -21
  21. package/build/conductor/driver-commands.js +141 -0
  22. package/build/conductor/driver-guard.js +277 -0
  23. package/build/conductor/driver-lapse.js +321 -0
  24. package/build/conductor/driver-pass-output.js +104 -0
  25. package/build/conductor/driver-pass.js +571 -0
  26. package/build/conductor/driver-register.js +176 -0
  27. package/build/conductor/driver-release.js +174 -0
  28. package/build/conductor/driver-session-state.js +315 -0
  29. package/build/conductor/epic-branch-ci-inspection.js +281 -43
  30. package/build/conductor/epic-implementer-cli.js +199 -15
  31. package/build/conductor/epic-server-database.js +162 -0
  32. package/build/conductor/epic-server-guidance.js +278 -0
  33. package/build/conductor/epic-server-journal.js +239 -0
  34. package/build/conductor/epic-server-processes.js +324 -0
  35. package/build/conductor/epic-server-recipe.js +397 -0
  36. package/build/conductor/epic-server-runtime.js +1207 -0
  37. package/build/conductor/epic-server-sfcc-upload.js +1567 -0
  38. package/build/conductor/epic-server-sfcc.js +85 -0
  39. package/build/conductor/epic-server-state.js +427 -0
  40. package/build/conductor/epic-server.js +647 -0
  41. package/build/conductor/gate-discovery.js +196 -11
  42. package/build/conductor/gate-settings-review.js +261 -4
  43. package/build/conductor/launch-need-probes.js +6 -53
  44. package/build/conductor/launch-plan.js +313 -156
  45. package/build/conductor/prerequisite-inputs.js +879 -45
  46. package/build/conductor/readiness-assessment.js +16 -1
  47. package/build/conductor/readiness-cli.js +20 -9
  48. package/build/conductor/readiness-prerequisites.js +28 -9
  49. package/build/conductor/readiness-sections.js +133 -126
  50. package/build/conductor/readiness.js +1 -1
  51. package/build/conductor/recovery-cli.js +13 -2
  52. package/build/conductor/tools.js +6 -5
  53. package/build/conductor/wait-run-attention.js +2 -2
  54. package/build/conductor/wait-run-cli.js +208 -22
  55. package/build/conductor/worker-database-doctor-inspector.js +33 -2
  56. package/build/conductor/worker-setup-tally.js +27 -0
  57. package/build/credential-delivery.js +280 -0
  58. package/build/credential-launch-safety.js +142 -0
  59. package/build/credential-materialization.js +91 -16
  60. package/build/credential-references-node-deps.js +29 -0
  61. package/build/credential-references.js +1394 -0
  62. package/build/credential-references.test-fixtures.js +211 -0
  63. package/build/credential-scan-conventions.js +145 -0
  64. package/build/credential-scan.js +517 -0
  65. package/build/credential-store.js +121 -1
  66. package/build/credentials-cli.js +252 -3
  67. package/build/dependency-install-declarations.js +102 -1
  68. package/build/docs.generated.js +10 -3
  69. package/build/doctor.js +95 -3
  70. package/build/drive-epic-help.js +21 -2
  71. package/build/drive-epic.js +2095 -375
  72. package/build/engine-paths.js +20 -0
  73. package/build/epic-branch-ci-summary.js +157 -0
  74. package/build/epic-capability-statement.js +175 -0
  75. package/build/epic-ci-workflow-drift.js +77 -23
  76. package/build/epic-ci-workflow-install.js +137 -44
  77. package/build/epic-ci-workflow-v2.js +274 -0
  78. package/build/epic-ci-workflow-v3.js +273 -0
  79. package/build/epic-ci-workflow.js +165 -18
  80. package/build/epic-implementer-bin.js +2204 -56
  81. package/build/epic-launch-context.js +702 -0
  82. package/build/epic-server-record.js +288 -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/completion-contract.js +8 -1
  87. package/build/executor/credential-delivery-step.js +168 -0
  88. package/build/executor/deps.js +3 -1
  89. package/build/executor/env.js +98 -23
  90. package/build/executor/epic-server-context.js +157 -0
  91. package/build/executor/gate-qualification-job.js +127 -26
  92. package/build/executor/guarded-fast-forward-push.js +13 -8
  93. package/build/executor/http-client.js +52 -5
  94. package/build/executor/job-runner.js +577 -81
  95. package/build/executor/observation.js +8 -0
  96. package/build/executor/permissions.js +85 -3
  97. package/build/executor/pre-pr-checks.js +363 -0
  98. package/build/executor/prompt-spec.js +149 -3
  99. package/build/executor/reconcile-overlap-job.js +5 -3
  100. package/build/executor/required-work-diagnostics.js +4 -2
  101. package/build/executor/required-work-ledger.js +936 -38
  102. package/build/executor/results.js +58 -0
  103. package/build/executor/terminal-mutation.js +8 -0
  104. package/build/executor/worker-command.js +72 -3
  105. package/build/executor/worker-database-config.js +281 -0
  106. package/build/executor/worker-database-target.js +16 -12
  107. package/build/executor/worker-database.js +320 -101
  108. package/build/executor/worker-finalization.js +7 -1
  109. package/build/executor/worker-resources.js +25 -3
  110. package/build/executor/worker-verification-guidance.js +18 -3
  111. package/build/executor/worktree.js +20 -1
  112. package/build/executor-launch.js +58 -4
  113. package/build/generated-assets-catalog.js +2 -2
  114. package/build/git-exclude-lock.js +187 -0
  115. package/build/index.js +824 -366
  116. package/build/init.js +26 -11
  117. package/build/install-bridge-conductor-answers.js +528 -0
  118. package/build/install-bridge-conductor-apply.js +288 -0
  119. package/build/install-bridge-conductor-assessment.js +1222 -0
  120. package/build/install-bridge-conductor-compact.js +186 -0
  121. package/build/install-bridge-conductor-contracts.js +72 -0
  122. package/build/install-bridge-conductor-gate.js +1312 -198
  123. package/build/install-bridge-conductor-setup.js +577 -83
  124. package/build/install-bridge-conductor.js +3381 -544
  125. package/build/install-bridge.js +280 -25
  126. package/build/install-doctor.js +38 -8
  127. package/build/install-maintenance.js +26 -3
  128. package/build/install-sfcc-detection.js +120 -0
  129. package/build/install-sfcc-setup.js +185 -0
  130. package/build/launcher-config-inspection.js +162 -1
  131. package/build/mcp-grant-candidates.js +779 -0
  132. package/build/mcp-grant-doctor.js +63 -0
  133. package/build/mcp-grant.js +288 -0
  134. package/build/mcp-host-targets.js +8 -0
  135. package/build/mcp-identity.js +23 -0
  136. package/build/mcp-invoke.js +292 -15
  137. package/build/mcp-presets.js +107 -0
  138. package/build/mcp-provisioning.js +155 -6
  139. package/build/mcp-registration-doctor.js +31 -2
  140. package/build/mcp-server-invocation.js +19 -1
  141. package/build/merge-workflow-install.js +243 -110
  142. package/build/pipelines.generated.js +7 -6
  143. package/build/plan-discovery.js +97 -4
  144. package/build/plan-execution-ledger.js +100 -7
  145. package/build/plan-generation-io.js +262 -0
  146. package/build/plan-generation.js +424 -0
  147. package/build/plane/build-freshness.js +6 -1
  148. package/build/plane/cli.js +75 -9
  149. package/build/plane/plane-freshness.js +17 -0
  150. package/build/plane/preflight.js +50 -10
  151. package/build/plane/shutdown.js +19 -0
  152. package/build/plane/status.js +8 -2
  153. package/build/plane/terminal-run-cleanup.js +18 -4
  154. package/build/printed-remedy-commands.js +211 -12
  155. package/build/project-root.js +40 -0
  156. package/build/readiness-check.js +77 -0
  157. package/build/readiness-prerequisites.generated.js +122 -14
  158. package/build/readme.generated.js +1 -1
  159. package/build/repository-state-paths.js +41 -0
  160. package/build/repository-toolchains.js +6 -3
  161. package/build/run-unit-tests-launcher.js +8 -1
  162. package/build/setup-epic.js +1305 -210
  163. package/build/setup-progress.js +44 -0
  164. package/build/setup-question.js +122 -4
  165. package/build/sfcc/credentials.js +3 -2
  166. package/build/sfcc/hostname.js +98 -2
  167. package/build/sfcc/tool-wrapper.js +6 -95
  168. package/build/start-tickets.js +193 -29
  169. package/build/test-support/executor-source-files.js +200 -0
  170. package/build/testing-config-client.js +25 -2
  171. package/build/third-party-mcp-targets.js +63 -2
  172. package/build/ticket-delivery-enrollment.js +9 -0
  173. package/build/upgrade-cli.js +85 -2
  174. package/build/v2-readiness-requirements.js +28 -1
  175. package/build/version.generated.js +3 -3
  176. package/build/with-credentials.js +208 -0
  177. package/build/worktree-credential-delivery.js +340 -0
  178. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  179. package/docs/epic-implementer/getting-started.md +3 -1
  180. package/docs/epic-implementer/self-hosting.md +14 -1
  181. package/package.json +2 -2
@@ -0,0 +1,85 @@
1
+ /**
2
+ * SFCC shared-active-version policy (BAPI-1546, reworked by BAPI-1669).
3
+ *
4
+ * There is no local server and no turns in `sfcc_shared_active` mode. The run
5
+ * uses the ONE sandbox approved at setup. The driver uploads the whole cartridge
6
+ * tree at the epic head at run start (`epic-server sfcc-upload --full`) and
7
+ * records a baseline. Each worker uploads only the cartridge files its branch
8
+ * changed (`epic-server sfcc-upload --ticket <KEY> --head <SHA>`) onto the same
9
+ * code version as it works. Briefly seeing other workers' changes is accepted.
10
+ *
11
+ * Upload is independent of the epic-server mode: it needs only an approved
12
+ * sandbox in the record. The mode only picks where browser checks run. A `head`
13
+ * in upload evidence names the source commit of THIS invocation's uploaded files.
14
+ * It is not proof that the whole shared version equals that commit.
15
+ *
16
+ * No credential value is ever an argument, and none reaches a prompt, the tally,
17
+ * or evidence. The testable rules live in `epic-server-sfcc-upload.ts`. The
18
+ * worker prompt states the same rules from the constants below:
19
+ *
20
+ * - every check runs after the worker's OWN upload;
21
+ * - a failed check is retried exactly ONCE, after a FRESH upload;
22
+ * - evidence is labeled `shared_active_version` and carries each upload's
23
+ * code version, source head, and start and end time;
24
+ * - a failed upload is a missing server (`no_live_server`, hand-off eligible);
25
+ * - a check that still fails after the retry is a real verification failure
26
+ * and is never relabeled unrunnable because the sandbox is shared.
27
+ */
28
+ /** The evidence label every SFCC check carries. */
29
+ export const SFCC_EVIDENCE_LABEL = "shared_active_version";
30
+ /** How many times a failed check is retried (each after a fresh upload). */
31
+ export const SFCC_CHECK_RETRIES = 1;
32
+ /** The hand-off cause for a failed upload. */
33
+ export const SFCC_UPLOAD_FAILURE_CAUSE = "no_live_server";
34
+ /** The pinned b2c CLI used when the repository has no local bin. */
35
+ export const SFCC_B2C_CLI_PINNED_PACKAGE = "@salesforce/b2c-cli@2.10.2";
36
+ /** The minimum Node version for the pinned npx fallback. */
37
+ export const SFCC_B2C_NPX_MIN_NODE = "22.16.0";
38
+ // Worker form: cumulative b2c budget, per-call cap, and whole-command ceiling.
39
+ export const SFCC_UPLOAD_WORKER_BUDGET_SECONDS = 300;
40
+ export const SFCC_UPLOAD_WORKER_CALL_SECONDS = 120;
41
+ /** The longest a worker upload command can run before it prints. The prompt and the spawn env both use it. */
42
+ export const SFCC_UPLOAD_WORKER_COMMAND_SECONDS = 660;
43
+ // Full (driver) form.
44
+ export const SFCC_UPLOAD_FULL_BUDGET_SECONDS = 900;
45
+ export const SFCC_UPLOAD_FULL_CALL_SECONDS = 600;
46
+ export const SFCC_UPLOAD_FULL_COMMAND_SECONDS = 1020;
47
+ // Lock.
48
+ export const SFCC_UPLOAD_LOCK_WAIT_SECONDS = 300;
49
+ export const SFCC_UPLOAD_FULL_LOCK_WAIT_SECONDS = 60;
50
+ export const SFCC_UPLOAD_LOCK_POLL_SECONDS = 2;
51
+ export const SFCC_UPLOAD_LOCK_MAX_HOLD_SECONDS = 960;
52
+ /** The largest one archive may be before any b2c mutation. */
53
+ export const SFCC_UPLOAD_MAX_ARCHIVE_BYTES = 64 * 1024 * 1024;
54
+ /** The most remote deletes one worker run sends. */
55
+ export const SFCC_UPLOAD_MAX_WORKER_DELETES = 50;
56
+ /**
57
+ * The shared upload sentences, for both the SFCC and the local-with-sandbox
58
+ * worker texts so they never drift. Single-line, and free of `;`, quotes, and
59
+ * apostrophes, like the other launch-prompt instructions.
60
+ */
61
+ export function buildSfccUploadWorkerText(ticketKey, commandSeconds) {
62
+ return ("Commit your work first. Before each e2e_tests or rendered_ui_review check, run " +
63
+ "epic-implementer epic-server sfcc-upload --ticket " + ticketKey + " --head <your full head SHA> through the " +
64
+ "epic-implementer launcher on your PATH, in the foreground, with a command timeout of at least " + commandSeconds +
65
+ " seconds. It uploads only the cartridge files your branch changed onto the shared sandbox code version. " +
66
+ "Outcome uploaded or nothing_to_upload means run the check. That is permission to run it and not proof that it passes. " +
67
+ "Never upload any other way and never put a credential value in a command. Other workers upload onto the same " +
68
+ "version, so if a check fails, rerun the upload once and retry that check exactly " + SFCC_CHECK_RETRIES +
69
+ " time, no more. Label the step evidence " + SFCC_EVIDENCE_LABEL + " and record each upload code_version, head, " +
70
+ "and start and end times. Any other upload outcome means rerun the same command once as the corrected invocation. " +
71
+ "If that also fails, record the step escalated with a hand-off whose cause is " + SFCC_UPLOAD_FAILURE_CAUSE +
72
+ ", quoting the command, its output, and your head SHA. Nothing parks for this. A check that still fails after " +
73
+ "the retry is a real verification failure. Record it as failed and never relabel it unrunnable because the " +
74
+ "sandbox is shared.");
75
+ }
76
+ /**
77
+ * The SFCC worker paragraph, generated from the constants above so the prompt
78
+ * and the rules cannot drift. Single-line, and free of `;`, quotes, and
79
+ * apostrophes.
80
+ */
81
+ export function buildSfccWorkerPolicyText(origin, ticketKey, commandSeconds) {
82
+ return ("Epic server, SFCC shared active version: there is no local epic server and there are no turns. " +
83
+ "Browser checks run against the approved sandbox storefront at " + origin + ". " +
84
+ buildSfccUploadWorkerText(ticketKey, commandSeconds));
85
+ }
@@ -0,0 +1,427 @@
1
+ /**
2
+ * Private, run-specific state for the epic-server helper (BAPI-1546).
3
+ *
4
+ * Every helper file lives OUTSIDE every worktree, under
5
+ *
6
+ * ~/.local/state/bapi-conductor-runs/<EPIC>/epic-server/<RUN_ID>/
7
+ *
8
+ * so two runs of one epic never share a recipe, a state file, a login file, a
9
+ * claim, or an IPC endpoint. Directories are `0700` and files `0600`. Nothing
10
+ * here follows a symbolic link, and every identity (epic key, run id) is
11
+ * validated before it reaches a path. The run identity comes from the trusted
12
+ * caller (the driver's confirmed run, or the executor's claimed job), never
13
+ * from a branch-controlled file.
14
+ *
15
+ * The live-state file (`state.json`) is advisory: a reader treats a file whose
16
+ * helper pid is dead, whose process start time does not match, whose run id
17
+ * differs, or that cannot be read as MISSING. It never falls back to "the pid
18
+ * exists". Resource ownership (`ownership.json`) is persisted separately, so a
19
+ * helper killed without cleanup can still be reclaimed by the next guarded
20
+ * `start` or `stop`.
21
+ *
22
+ * The IPC endpoint is a Unix socket. Socket paths are short-limited (about 104
23
+ * bytes on macOS), so it lives in a private `0700` directory under the system
24
+ * temporary directory, named from a digest of the run id, and its path is
25
+ * recorded in `state.json`.
26
+ */
27
+ import { createHash } from "node:crypto";
28
+ import * as nodeFs from "node:fs/promises";
29
+ import os from "node:os";
30
+ import path from "node:path";
31
+ export const EPIC_SERVER_STATE_VERSION = 1;
32
+ export const EPIC_SERVER_OWNERSHIP_VERSION = 1;
33
+ /** The run-state root, relative to the home directory (shared with the tally). */
34
+ export const EPIC_SERVER_RUN_STATE_SEGMENTS = [".local", "state", "bapi-conductor-runs"];
35
+ /** The env variable carrying the helper instance's ownership tag (never the executor's). */
36
+ export const EPIC_SERVER_INSTANCE_TAG_ENV = "BRIDGE_EPIC_SERVER_INSTANCE_TAG";
37
+ /** Executor-injected: the run id a worker's `turn acquire` addresses. */
38
+ export const EPIC_SERVER_RUN_ID_ENV = "BRIDGE_EPIC_SERVER_RUN_ID";
39
+ /** Executor-injected: the served address (local) or approved storefront origin (SFCC). */
40
+ export const EPIC_SERVER_URL_ENV = "BRIDGE_EPIC_SERVER_URL";
41
+ const EPIC_KEY_RE = /^[A-Z][A-Z0-9_]{0,19}-\d{1,9}$/;
42
+ const RUN_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{7,63}$/;
43
+ const NONCE_RE = /^[0-9a-f]{64}$/;
44
+ const SHA_RE = /^[0-9a-f]{40}$/;
45
+ const MAX_STATE_BYTES = 16 * 1024;
46
+ const MAX_LISTED_EPICS = 512;
47
+ export function isValidEpicKey(value) {
48
+ return typeof value === "string" && EPIC_KEY_RE.test(value);
49
+ }
50
+ /** A run id: the run's own identifier, never an epic key (which would collide across runs). */
51
+ export function isValidEpicRunId(value) {
52
+ return typeof value === "string" && RUN_ID_RE.test(value) && !EPIC_KEY_RE.test(value);
53
+ }
54
+ export function isInstanceNonce(value) {
55
+ return typeof value === "string" && NONCE_RE.test(value);
56
+ }
57
+ /** The run-state root under a home directory. */
58
+ export function epicServerRunStateRoot(home) {
59
+ return path.join(home, ...EPIC_SERVER_RUN_STATE_SEGMENTS);
60
+ }
61
+ /**
62
+ * Every path for one run, or null when the identity is not usable. The serving
63
+ * worktree is inside the run directory, never a worker's worktree.
64
+ */
65
+ export function epicServerRunPaths(home, identity, tmpdir = os.tmpdir()) {
66
+ if (!isValidEpicKey(identity.epicKey) || !isValidEpicRunId(identity.epicRunId))
67
+ return null;
68
+ if (!path.isAbsolute(home) || !path.isAbsolute(tmpdir))
69
+ return null;
70
+ const root = epicServerRunStateRoot(home);
71
+ const runDir = path.join(root, identity.epicKey, "epic-server", identity.epicRunId);
72
+ const socketDir = path.join(tmpdir, `bapi-es-${createHash("sha256").update(identity.epicRunId).digest("hex").slice(0, 16)}`);
73
+ return {
74
+ root,
75
+ runDir,
76
+ recipe: path.join(runDir, "recipe.json"),
77
+ proof: path.join(runDir, "proof.json"),
78
+ state: path.join(runDir, "state.json"),
79
+ ownership: path.join(runDir, "ownership.json"),
80
+ claim: path.join(runDir, "claim.json"),
81
+ journal: path.join(runDir, "journal.json"),
82
+ servingWorktree: path.join(runDir, "serving"),
83
+ socketDir,
84
+ socket: path.join(socketDir, "ipc.sock"),
85
+ helperLog: path.join(runDir, "helper.log"),
86
+ };
87
+ }
88
+ /** The login file for one generation: `0600`, inside the run directory. */
89
+ export function epicServerLoginFilePath(paths, generation) {
90
+ return path.join(paths.runDir, `login-${generation}.env`);
91
+ }
92
+ /** True when `candidate` is `parent` or strictly inside it (no traversal). */
93
+ export function isInsideDirectory(parent, candidate) {
94
+ const rel = path.relative(path.resolve(parent), path.resolve(candidate));
95
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
96
+ }
97
+ /** The production filesystem seam. */
98
+ export function createDefaultEpicServerStateFs() {
99
+ return {
100
+ readFile: (p, enc) => nodeFs.readFile(p, enc),
101
+ open: async (p, flags, mode) => {
102
+ const handle = await nodeFs.open(p, flags, mode);
103
+ return {
104
+ writeFile: (data, options) => handle.writeFile(data, options),
105
+ sync: () => handle.sync(),
106
+ close: () => handle.close(),
107
+ };
108
+ },
109
+ rename: (a, b) => nodeFs.rename(a, b),
110
+ mkdir: (p, options) => nodeFs.mkdir(p, options),
111
+ chmod: (p, mode) => nodeFs.chmod(p, mode),
112
+ lstat: (p) => nodeFs.lstat(p),
113
+ unlink: (p) => nodeFs.unlink(p),
114
+ readdir: (p) => nodeFs.readdir(p),
115
+ rm: (p, options) => nodeFs.rm(p, options),
116
+ };
117
+ }
118
+ let tempCounter = 0;
119
+ /**
120
+ * Create `dir` (and parents) privately. Refuses when `dir` exists as a symbolic
121
+ * link or as anything but a directory. Holds `dir` at `0700`.
122
+ */
123
+ export async function ensurePrivateDirectory(fs, dir) {
124
+ await fs.mkdir(dir, { recursive: true, mode: 0o700 });
125
+ const st = await fs.lstat(dir);
126
+ if (st.isSymbolicLink() || !st.isDirectory())
127
+ throw new Error("not a private directory");
128
+ if (typeof process.getuid === "function" && typeof st.uid === "number" && st.uid !== process.getuid()) {
129
+ throw new Error("directory owned by another user");
130
+ }
131
+ await fs.chmod(dir, 0o700);
132
+ }
133
+ /**
134
+ * Atomically write JSON (or text) to `filePath`: an exclusively created temp file
135
+ * in the same directory with mode `0600`, fsync, rename. A symbolic link at the
136
+ * destination is refused rather than followed.
137
+ */
138
+ export async function writePrivateFileAtomic(fs, filePath, text) {
139
+ const dir = path.dirname(filePath);
140
+ await ensurePrivateDirectory(fs, dir);
141
+ try {
142
+ const st = await fs.lstat(filePath);
143
+ if (st.isSymbolicLink() || !st.isFile())
144
+ throw new Error("refusing to replace a non-file");
145
+ }
146
+ catch (err) {
147
+ if (err.code !== "ENOENT")
148
+ throw err;
149
+ }
150
+ tempCounter += 1;
151
+ const temp = path.join(dir, `.${path.basename(filePath)}.${process.pid}.${tempCounter}.tmp`);
152
+ const handle = await fs.open(temp, "wx", 0o600);
153
+ try {
154
+ await handle.writeFile(text, { encoding: "utf-8" });
155
+ await handle.sync();
156
+ }
157
+ finally {
158
+ await handle.close();
159
+ }
160
+ try {
161
+ await fs.chmod(temp, 0o600);
162
+ await fs.rename(temp, filePath);
163
+ }
164
+ catch (err) {
165
+ await fs.unlink(temp).catch(() => undefined);
166
+ throw err;
167
+ }
168
+ }
169
+ /** Read a private JSON file: a regular file, not a link, owner-only, bounded. Null when anything is off. */
170
+ export async function readPrivateJson(fs, filePath) {
171
+ try {
172
+ const st = await fs.lstat(filePath);
173
+ if (st.isSymbolicLink() || !st.isFile())
174
+ return null;
175
+ if (process.platform !== "win32" && (st.mode & 0o077) !== 0)
176
+ return null;
177
+ const text = await fs.readFile(filePath, "utf-8");
178
+ if (text.length > MAX_STATE_BYTES * 64)
179
+ return null;
180
+ return JSON.parse(text);
181
+ }
182
+ catch {
183
+ return null;
184
+ }
185
+ }
186
+ /** Remove a file if present. Never follows a link (unlink removes the link itself). Never throws. */
187
+ export async function removeFileQuietly(fs, filePath) {
188
+ try {
189
+ await fs.unlink(filePath);
190
+ return true;
191
+ }
192
+ catch (err) {
193
+ return err.code === "ENOENT";
194
+ }
195
+ }
196
+ function isPlainObject(value) {
197
+ return value !== null && typeof value === "object" && !Array.isArray(value);
198
+ }
199
+ function isPort(value) {
200
+ return typeof value === "number" && Number.isInteger(value) && value > 1024 && value < 65536 && value !== 8000;
201
+ }
202
+ function isPositiveSeconds(value) {
203
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 && value <= 2 * 24 * 60 * 60;
204
+ }
205
+ /** A loopback URL on the given port, exactly. */
206
+ export function epicServerLoopbackUrl(port) {
207
+ return `http://127.0.0.1:${port}`;
208
+ }
209
+ /** Validate a parsed `state.json`. Incomplete or unknown-schema state is null, never partly trusted. */
210
+ export function validateEpicServerLiveState(raw) {
211
+ if (!isPlainObject(raw) || raw.version !== EPIC_SERVER_STATE_VERSION)
212
+ return null;
213
+ if (!isValidEpicKey(raw.epic_key) || !isValidEpicRunId(raw.epic_run_id))
214
+ return null;
215
+ if (typeof raw.repo_name !== "string" || raw.repo_name.length === 0 || raw.repo_name.length > 200)
216
+ return null;
217
+ if (typeof raw.helper_pid !== "number" || !Number.isSafeInteger(raw.helper_pid) || raw.helper_pid <= 1)
218
+ return null;
219
+ if (typeof raw.helper_started_at !== "string" || raw.helper_started_at.length === 0 || raw.helper_started_at.length > 64)
220
+ return null;
221
+ if (!isInstanceNonce(raw.instance_nonce))
222
+ return null;
223
+ if (!isPort(raw.port))
224
+ return null;
225
+ if (raw.url !== epicServerLoopbackUrl(raw.port))
226
+ return null;
227
+ if (typeof raw.socket_path !== "string" || !path.isAbsolute(raw.socket_path) || raw.socket_path.length > 200)
228
+ return null;
229
+ if (!isPositiveSeconds(raw.turn_wait_seconds) || !isPositiveSeconds(raw.turn_build_seconds))
230
+ return null;
231
+ if (raw.served_sha !== null && (typeof raw.served_sha !== "string" || !SHA_RE.test(raw.served_sha)))
232
+ return null;
233
+ if (typeof raw.generation !== "number" || !Number.isSafeInteger(raw.generation) || raw.generation < 0)
234
+ return null;
235
+ if (typeof raw.updated_at !== "string" || Number.isNaN(Date.parse(raw.updated_at)))
236
+ return null;
237
+ return {
238
+ version: EPIC_SERVER_STATE_VERSION,
239
+ epic_key: raw.epic_key,
240
+ epic_run_id: raw.epic_run_id,
241
+ repo_name: raw.repo_name,
242
+ helper_pid: raw.helper_pid,
243
+ helper_started_at: raw.helper_started_at,
244
+ instance_nonce: raw.instance_nonce,
245
+ port: raw.port,
246
+ url: raw.url,
247
+ socket_path: raw.socket_path,
248
+ turn_wait_seconds: raw.turn_wait_seconds,
249
+ turn_build_seconds: raw.turn_build_seconds,
250
+ served_sha: raw.served_sha,
251
+ generation: raw.generation,
252
+ updated_at: raw.updated_at,
253
+ };
254
+ }
255
+ /**
256
+ * Read live state for exactly `expectedRunId`. Missing, unreadable, malformed,
257
+ * another run's, a dead helper, a start-time mismatch, or an identity that
258
+ * cannot be read are all `missing`. Bounded by `budgetMs`; never throws.
259
+ */
260
+ export async function readEpicServerLiveState(statePath, expectedRunId, deps) {
261
+ const work = (async () => {
262
+ const raw = await readPrivateJson(deps.fs, statePath);
263
+ const value = validateEpicServerLiveState(raw);
264
+ if (value === null || value.epic_run_id !== expectedRunId)
265
+ return { state: "missing" };
266
+ let identity;
267
+ try {
268
+ identity = await deps.probe.identity(value.helper_pid);
269
+ }
270
+ catch {
271
+ identity = null;
272
+ }
273
+ if (identity === null || identity.startedAt !== value.helper_started_at)
274
+ return { state: "missing" };
275
+ return { state: "live", value };
276
+ })().catch(() => ({ state: "missing" }));
277
+ return boundedResult(work, deps.budgetMs ?? 5_000, { state: "missing" });
278
+ }
279
+ /** Race `work` against a timer; the timer's value wins on timeout. */
280
+ export async function boundedResult(work, budgetMs, onTimeout) {
281
+ let timer;
282
+ const timeout = new Promise((resolve) => {
283
+ timer = setTimeout(() => resolve(onTimeout), Math.max(1, budgetMs));
284
+ timer.unref?.();
285
+ });
286
+ try {
287
+ return await Promise.race([work, timeout]);
288
+ }
289
+ finally {
290
+ if (timer)
291
+ clearTimeout(timer);
292
+ }
293
+ }
294
+ /**
295
+ * Find a run's directory from its run id alone (the executor knows the run id,
296
+ * not the epic key). Lists at most {@link MAX_LISTED_EPICS} epic directories.
297
+ * Returns the paths for the one epic whose `epic-server/<RUN_ID>` exists, or null.
298
+ */
299
+ export async function findEpicServerRunPaths(home, epicRunId, fs, tmpdir = os.tmpdir()) {
300
+ if (!isValidEpicRunId(epicRunId))
301
+ return null;
302
+ let entries;
303
+ try {
304
+ entries = await fs.readdir(epicServerRunStateRoot(home));
305
+ }
306
+ catch {
307
+ return null;
308
+ }
309
+ let found = null;
310
+ for (const entry of entries.slice(0, MAX_LISTED_EPICS)) {
311
+ if (!isValidEpicKey(entry))
312
+ continue;
313
+ const paths = epicServerRunPaths(home, { epicKey: entry, epicRunId }, tmpdir);
314
+ if (paths === null)
315
+ continue;
316
+ try {
317
+ const st = await fs.lstat(paths.runDir);
318
+ if (st.isSymbolicLink() || !st.isDirectory())
319
+ continue;
320
+ }
321
+ catch {
322
+ continue;
323
+ }
324
+ // Two epics claiming one run id is ambiguous: treat as not found.
325
+ if (found !== null)
326
+ return null;
327
+ found = paths;
328
+ }
329
+ return found;
330
+ }
331
+ export function validateEpicServerOwnership(raw) {
332
+ if (!isPlainObject(raw) || raw.version !== EPIC_SERVER_OWNERSHIP_VERSION)
333
+ return null;
334
+ if (!isValidEpicKey(raw.epic_key) || !isValidEpicRunId(raw.epic_run_id))
335
+ return null;
336
+ if (typeof raw.helper_pid !== "number" || !Number.isSafeInteger(raw.helper_pid) || raw.helper_pid <= 1)
337
+ return null;
338
+ if (typeof raw.helper_started_at !== "string" || raw.helper_started_at.length === 0)
339
+ return null;
340
+ if (!isInstanceNonce(raw.instance_nonce))
341
+ return null;
342
+ if (typeof raw.repo_root !== "string" || !path.isAbsolute(raw.repo_root))
343
+ return null;
344
+ let app = null;
345
+ if (raw.app !== null) {
346
+ if (!isPlainObject(raw.app))
347
+ return null;
348
+ const { pid, started_at } = raw.app;
349
+ if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 1 || typeof started_at !== "string")
350
+ return null;
351
+ app = { pid, started_at };
352
+ }
353
+ if (raw.serving_worktree !== null && (typeof raw.serving_worktree !== "string" || !path.isAbsolute(raw.serving_worktree))) {
354
+ return null;
355
+ }
356
+ if (!Array.isArray(raw.databases) || raw.databases.length > 64)
357
+ return null;
358
+ const databases = [];
359
+ for (const db of raw.databases) {
360
+ if (!isPlainObject(db) || typeof db.name !== "string" || typeof db.role !== "string")
361
+ return null;
362
+ if (typeof db.generation !== "number" || !Number.isSafeInteger(db.generation))
363
+ return null;
364
+ databases.push({ name: db.name, role: db.role, generation: db.generation });
365
+ }
366
+ if (!Array.isArray(raw.login_files) || raw.login_files.length > 64 || raw.login_files.some((f) => typeof f !== "string")) {
367
+ return null;
368
+ }
369
+ return {
370
+ version: EPIC_SERVER_OWNERSHIP_VERSION,
371
+ epic_key: raw.epic_key,
372
+ epic_run_id: raw.epic_run_id,
373
+ helper_pid: raw.helper_pid,
374
+ helper_started_at: raw.helper_started_at,
375
+ instance_nonce: raw.instance_nonce,
376
+ repo_root: raw.repo_root,
377
+ app,
378
+ serving_worktree: raw.serving_worktree,
379
+ databases,
380
+ login_files: [...raw.login_files],
381
+ };
382
+ }
383
+ export function validateEpicServerClaim(raw) {
384
+ if (!isPlainObject(raw) || !isValidEpicRunId(raw.epic_run_id))
385
+ return null;
386
+ if (typeof raw.helper_pid !== "number" || !Number.isSafeInteger(raw.helper_pid) || raw.helper_pid <= 1)
387
+ return null;
388
+ if (typeof raw.helper_started_at !== "string" || !isInstanceNonce(raw.instance_nonce))
389
+ return null;
390
+ if (typeof raw.created_at !== "string")
391
+ return null;
392
+ return {
393
+ epic_run_id: raw.epic_run_id,
394
+ helper_pid: raw.helper_pid,
395
+ helper_started_at: raw.helper_started_at,
396
+ instance_nonce: raw.instance_nonce,
397
+ created_at: raw.created_at,
398
+ };
399
+ }
400
+ /**
401
+ * Take the singleton claim with an exclusive create. Returns false when a claim
402
+ * already exists (the caller then attaches to, or recovers from, its owner).
403
+ */
404
+ export async function tryCreateClaim(fs, claimPath, claim) {
405
+ await ensurePrivateDirectory(fs, path.dirname(claimPath));
406
+ let handle;
407
+ try {
408
+ handle = await fs.open(claimPath, "wx", 0o600);
409
+ }
410
+ catch (err) {
411
+ if (err.code === "EEXIST")
412
+ return false;
413
+ throw err;
414
+ }
415
+ try {
416
+ await handle.writeFile(`${JSON.stringify(claim)}\n`, { encoding: "utf-8" });
417
+ await handle.sync();
418
+ }
419
+ finally {
420
+ await handle.close();
421
+ }
422
+ return true;
423
+ }
424
+ /** True for a full 40-character lowercase commit SHA. */
425
+ export function isFullCommitShaLike(value) {
426
+ return typeof value === "string" && SHA_RE.test(value);
427
+ }