@bridge_gpt/mcp-server 0.2.72 → 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.
- package/README.md +5 -5
- package/build/agent-launchers/claude-executor-adapter.js +3 -0
- package/build/agents.generated.js +6 -6
- package/build/bridge-permissions.js +27 -0
- package/build/ci-system-detection.js +50 -0
- package/build/ci-trigger-adapters.js +631 -0
- package/build/ci-trigger-install.js +106 -0
- package/build/codex-launcher-pin.js +33 -2
- package/build/codex-skill-adapter.js +3 -1
- package/build/command-host.js +33 -0
- package/build/commands.generated.js +7 -6
- package/build/conductor/bridge-api-client.js +842 -35
- package/build/conductor/bring-up-facts.js +18 -5
- package/build/conductor/command-drift-production.js +42 -17
- package/build/conductor/command-drift.js +47 -0
- package/build/conductor/declare-blocked.js +554 -0
- package/build/conductor/doctor.js +106 -21
- package/build/conductor/driver-commands.js +141 -0
- package/build/conductor/driver-guard.js +277 -0
- package/build/conductor/driver-lapse.js +321 -0
- package/build/conductor/driver-register.js +176 -0
- package/build/conductor/driver-release.js +174 -0
- package/build/conductor/driver-session-state.js +315 -0
- package/build/conductor/epic-branch-ci-inspection.js +222 -29
- package/build/conductor/epic-implementer-cli.js +166 -15
- package/build/conductor/epic-server-database.js +162 -0
- package/build/conductor/epic-server-guidance.js +278 -0
- package/build/conductor/epic-server-journal.js +239 -0
- package/build/conductor/epic-server-processes.js +324 -0
- package/build/conductor/epic-server-recipe.js +397 -0
- package/build/conductor/epic-server-runtime.js +1207 -0
- package/build/conductor/epic-server-sfcc.js +107 -0
- package/build/conductor/epic-server-state.js +427 -0
- package/build/conductor/epic-server.js +594 -0
- package/build/conductor/gate-discovery.js +150 -5
- package/build/conductor/gate-settings-review.js +224 -4
- package/build/conductor/launch-need-probes.js +6 -53
- package/build/conductor/launch-plan.js +313 -156
- package/build/conductor/prerequisite-inputs.js +879 -45
- package/build/conductor/readiness-assessment.js +16 -1
- package/build/conductor/readiness-cli.js +20 -9
- package/build/conductor/readiness-prerequisites.js +28 -9
- package/build/conductor/readiness-sections.js +133 -126
- package/build/conductor/readiness.js +1 -1
- package/build/conductor/recovery-cli.js +13 -2
- package/build/conductor/tools.js +6 -5
- package/build/conductor/wait-run-attention.js +2 -2
- package/build/conductor/wait-run-cli.js +208 -22
- package/build/conductor/worker-database-doctor-inspector.js +33 -2
- package/build/conductor/worker-setup-tally.js +27 -0
- package/build/credential-store.js +71 -1
- package/build/dependency-install-declarations.js +55 -0
- package/build/docs.generated.js +2 -2
- package/build/doctor.js +54 -3
- package/build/drive-epic-help.js +21 -2
- package/build/drive-epic.js +1811 -351
- package/build/engine-paths.js +20 -0
- package/build/epic-branch-ci-summary.js +140 -0
- package/build/epic-capability-statement.js +107 -0
- package/build/epic-ci-workflow-drift.js +30 -15
- package/build/epic-ci-workflow-install.js +110 -42
- package/build/epic-ci-workflow-v2.js +274 -0
- package/build/epic-ci-workflow.js +38 -12
- package/build/epic-implementer-bin.js +2101 -44
- package/build/epic-launch-context.js +607 -0
- package/build/epic-server-record.js +273 -0
- package/build/epic-shared/bridge-client.js +11 -3
- package/build/escalation-reachability.js +43 -0
- package/build/executor/ci-fix-test-runs.js +334 -0
- package/build/executor/completion-contract.js +8 -1
- package/build/executor/env.js +59 -22
- package/build/executor/epic-server-context.js +141 -0
- package/build/executor/gate-qualification-job.js +127 -26
- package/build/executor/http-client.js +52 -5
- package/build/executor/job-runner.js +423 -69
- package/build/executor/observation.js +8 -0
- package/build/executor/pre-pr-checks.js +363 -0
- package/build/executor/prompt-spec.js +114 -2
- package/build/executor/reconcile-overlap-job.js +5 -3
- package/build/executor/required-work-diagnostics.js +4 -2
- package/build/executor/required-work-ledger.js +936 -38
- package/build/executor/results.js +58 -0
- package/build/executor/terminal-mutation.js +8 -0
- package/build/executor/worker-command.js +72 -3
- package/build/executor/worker-database-config.js +281 -0
- package/build/executor/worker-database-target.js +16 -12
- package/build/executor/worker-database.js +320 -101
- package/build/executor/worker-finalization.js +7 -1
- package/build/executor/worker-resources.js +25 -3
- package/build/executor/worker-verification-guidance.js +18 -3
- package/build/executor/worktree.js +20 -1
- package/build/executor-launch.js +54 -2
- package/build/generated-assets-catalog.js +2 -2
- package/build/index.js +664 -335
- package/build/init.js +26 -11
- package/build/install-bridge-conductor-answers.js +465 -0
- package/build/install-bridge-conductor-apply.js +259 -0
- package/build/install-bridge-conductor-assessment.js +895 -0
- package/build/install-bridge-conductor-compact.js +161 -0
- package/build/install-bridge-conductor-contracts.js +63 -0
- package/build/install-bridge-conductor-gate.js +1197 -196
- package/build/install-bridge-conductor-setup.js +535 -79
- package/build/install-bridge-conductor.js +2885 -560
- package/build/install-bridge.js +199 -21
- package/build/install-maintenance.js +26 -3
- package/build/launcher-config-inspection.js +162 -1
- package/build/mcp-grant-candidates.js +767 -0
- package/build/mcp-grant-doctor.js +63 -0
- package/build/mcp-grant.js +288 -0
- package/build/mcp-host-targets.js +8 -0
- package/build/mcp-identity.js +23 -0
- package/build/mcp-invoke.js +126 -13
- package/build/mcp-presets.js +107 -0
- package/build/mcp-provisioning.js +134 -2
- package/build/mcp-registration-doctor.js +31 -2
- package/build/mcp-server-invocation.js +6 -1
- package/build/merge-workflow-install.js +234 -109
- package/build/pipelines.generated.js +5 -5
- package/build/plan-discovery.js +97 -4
- package/build/plan-execution-ledger.js +100 -7
- package/build/plan-generation-io.js +262 -0
- package/build/plan-generation.js +424 -0
- package/build/plane/build-freshness.js +6 -1
- package/build/plane/cli.js +75 -9
- package/build/plane/plane-freshness.js +17 -0
- package/build/plane/preflight.js +50 -10
- package/build/plane/shutdown.js +19 -0
- package/build/plane/terminal-run-cleanup.js +18 -4
- package/build/printed-remedy-commands.js +206 -12
- package/build/readiness-check.js +77 -0
- package/build/readiness-prerequisites.generated.js +122 -14
- package/build/readme.generated.js +1 -1
- package/build/repository-state-paths.js +38 -0
- package/build/run-unit-tests-launcher.js +8 -1
- package/build/setup-epic.js +1190 -196
- package/build/setup-progress.js +44 -0
- package/build/setup-question.js +122 -4
- package/build/third-party-mcp-targets.js +30 -0
- package/build/ticket-delivery-enrollment.js +9 -0
- package/build/upgrade-cli.js +85 -2
- package/build/v2-readiness-requirements.js +28 -1
- package/build/version.generated.js +3 -3
- package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
- package/docs/epic-implementer/getting-started.md +3 -1
- package/docs/epic-implementer/self-hosting.md +14 -1
- package/package.json +2 -2
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SFCC shared-active-version mode (BAPI-1546).
|
|
3
|
+
*
|
|
4
|
+
* There is no local server and no turns. The run uses the ONE sandbox approved
|
|
5
|
+
* at setup. The driver uploads the epic's code, branched from base, onto that
|
|
6
|
+
* sandbox's active code version at run start; each worker uploads its own
|
|
7
|
+
* branch's changes onto the same active version as it works. Briefly seeing
|
|
8
|
+
* other workers' changes is accepted.
|
|
9
|
+
*
|
|
10
|
+
* Uploads go through the granted SFCC MCP or CLI, which resolves the sandbox
|
|
11
|
+
* account's credential reference outside every worktree. No credential value is
|
|
12
|
+
* ever an argument here, and none reaches a prompt, the tally, or evidence.
|
|
13
|
+
*
|
|
14
|
+
* The testable rules live here, behind injected uploader and check seams, and
|
|
15
|
+
* the worker prompt states them from these same constants:
|
|
16
|
+
*
|
|
17
|
+
* - every check runs after the worker's OWN upload;
|
|
18
|
+
* - a failed check is retried exactly ONCE, after a FRESH upload;
|
|
19
|
+
* - evidence is labeled `shared_active_version` and carries each upload's
|
|
20
|
+
* start and end time;
|
|
21
|
+
* - a failed upload is a missing server (`no_live_server`, hand-off eligible);
|
|
22
|
+
* - a check that still fails after the retry is a real verification failure
|
|
23
|
+
* and is never relabeled unrunnable because the sandbox is shared.
|
|
24
|
+
*/
|
|
25
|
+
/** The evidence label every SFCC check carries. */
|
|
26
|
+
export const SFCC_EVIDENCE_LABEL = "shared_active_version";
|
|
27
|
+
/** How many times a failed check is retried (each after a fresh upload). */
|
|
28
|
+
export const SFCC_CHECK_RETRIES = 1;
|
|
29
|
+
/** The hand-off cause for a failed upload. */
|
|
30
|
+
export const SFCC_UPLOAD_FAILURE_CAUSE = "no_live_server";
|
|
31
|
+
const SHA_RE = /^[0-9a-f]{40}$/;
|
|
32
|
+
/**
|
|
33
|
+
* Run one SFCC check under the shared-active-version rules: upload, check, and
|
|
34
|
+
* only if that check fails, one fresh upload and exactly one retry. The upload
|
|
35
|
+
* always targets the APPROVED sandbox; a request for any other sandbox is refused.
|
|
36
|
+
*/
|
|
37
|
+
export async function runSfccSharedActiveCheck(input) {
|
|
38
|
+
if (input.sandboxId !== input.approved.sandbox_id)
|
|
39
|
+
return { outcome: "refused", reason: "sandbox_mismatch" };
|
|
40
|
+
if (!SHA_RE.test(input.head))
|
|
41
|
+
return { outcome: "refused", reason: "invalid_head" };
|
|
42
|
+
const evidence = {
|
|
43
|
+
label: SFCC_EVIDENCE_LABEL,
|
|
44
|
+
sandbox_id: input.approved.sandbox_id,
|
|
45
|
+
worker_head: input.head,
|
|
46
|
+
uploads: [],
|
|
47
|
+
check_attempts: 0,
|
|
48
|
+
first_check: "not_run",
|
|
49
|
+
};
|
|
50
|
+
const upload = async () => {
|
|
51
|
+
const started = input.now().toISOString();
|
|
52
|
+
let ok = false;
|
|
53
|
+
try {
|
|
54
|
+
ok = (await input.uploader.upload({
|
|
55
|
+
sandbox_id: input.approved.sandbox_id,
|
|
56
|
+
credential_ref: input.approved.credential_ref,
|
|
57
|
+
head: input.head,
|
|
58
|
+
})).ok;
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
ok = false;
|
|
62
|
+
}
|
|
63
|
+
evidence.uploads.push({ started_at: started, ended_at: input.now().toISOString(), ok });
|
|
64
|
+
return ok;
|
|
65
|
+
};
|
|
66
|
+
const check = async () => {
|
|
67
|
+
evidence.check_attempts += 1;
|
|
68
|
+
try {
|
|
69
|
+
return (await input.check.run()).passed;
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
if (!(await upload()))
|
|
76
|
+
return { outcome: "unavailable", cause: SFCC_UPLOAD_FAILURE_CAUSE, evidence };
|
|
77
|
+
const first = await check();
|
|
78
|
+
evidence.first_check = first ? "passed" : "failed";
|
|
79
|
+
if (first)
|
|
80
|
+
return { outcome: "passed", evidence };
|
|
81
|
+
for (let retry = 0; retry < SFCC_CHECK_RETRIES; retry++) {
|
|
82
|
+
// The retry follows a FRESH upload of the worker's own head.
|
|
83
|
+
if (!(await upload()))
|
|
84
|
+
return { outcome: "unavailable", cause: SFCC_UPLOAD_FAILURE_CAUSE, evidence };
|
|
85
|
+
if (await check())
|
|
86
|
+
return { outcome: "passed", evidence };
|
|
87
|
+
}
|
|
88
|
+
// Still failing after the retry: a real failure, never relabeled unrunnable.
|
|
89
|
+
return { outcome: "failed", evidence };
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* The SFCC worker paragraph, generated from the constants above so the prompt
|
|
93
|
+
* and the rules cannot drift. Single-line, and free of `;`, quotes, and
|
|
94
|
+
* apostrophes, like the other launch-prompt instructions.
|
|
95
|
+
*/
|
|
96
|
+
export function buildSfccWorkerPolicyText(origin) {
|
|
97
|
+
return ("Epic server, SFCC shared active version: there is no local epic server and there are no turns. " +
|
|
98
|
+
"Browser checks run against the approved sandbox storefront at " + origin + ". Before each e2e_tests " +
|
|
99
|
+
"or rendered_ui_review check, upload your own branch changes onto the sandbox active code version through " +
|
|
100
|
+
"the granted SFCC MCP or CLI, never with a credential value in a command. Other workers upload onto the " +
|
|
101
|
+
"same version, so if a check fails, do one fresh upload of your own head and retry that check exactly " +
|
|
102
|
+
SFCC_CHECK_RETRIES + " time, no more. Label the step evidence " + SFCC_EVIDENCE_LABEL + " and record each " +
|
|
103
|
+
"upload start and end time and your head SHA. If an upload fails, that is an unavailable server: record the " +
|
|
104
|
+
"step escalated with a hand-off whose cause is " + SFCC_UPLOAD_FAILURE_CAUSE + " under the hand-off rules " +
|
|
105
|
+
"above. A check that still fails after the retry is a real verification failure. Record it as failed and " +
|
|
106
|
+
"never relabel it unrunnable because the sandbox is shared.");
|
|
107
|
+
}
|
|
@@ -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
|
+
}
|