@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.
- package/README.md +55 -17
- package/build/agent-launchers/claude-executor-adapter.js +22 -3
- package/build/agent-notes.js +171 -95
- package/build/agents.generated.js +7 -7
- package/build/bridge-permissions.js +31 -0
- package/build/bridge-worktree-inspection.js +237 -0
- package/build/check-evidence.js +6 -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/claude-review-workflow.js +1 -1
- package/build/cli-help.js +6 -0
- package/build/codex-auto-recovery.js +126 -0
- package/build/codex-launcher-pin.js +33 -2
- package/build/codex-skill-adapter.js +5 -1
- package/build/command-host.js +33 -0
- package/build/commands.generated.js +7 -6
- package/build/conductor/bridge-api-client.js +1352 -50
- 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 +187 -28
- 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 +213 -13
- 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 +281 -10
- package/build/conductor/gate-settings-review.js +525 -5
- package/build/conductor/git-hooks-uninstall.js +112 -0
- package/build/conductor/git-hooks.js +81 -15
- package/build/conductor/guided-repair.js +10 -1
- package/build/conductor/install-doctor.js +2 -4
- package/build/conductor/launch-need-probes.js +6 -53
- package/build/conductor/launch-plan.js +318 -121
- package/build/conductor/local-merge.js +12 -1
- package/build/conductor/merge-execution-contract.js +1 -1
- package/build/conductor/merged-child-check.js +2 -1
- package/build/conductor/prerequisite-inputs.js +1213 -0
- package/build/conductor/readiness-assessment.js +93 -0
- package/build/conductor/readiness-cli.js +30 -9
- package/build/conductor/readiness-prerequisites.js +77 -5
- package/build/conductor/readiness-sections.js +146 -126
- package/build/conductor/readiness.js +21 -3
- package/build/conductor/recovery-cli.js +236 -15
- package/build/conductor/recovery-operations.js +34 -4
- package/build/conductor/repair-contract.js +33 -0
- package/build/conductor/tools.js +36 -4
- package/build/conductor/wait-run-attention.js +115 -0
- package/build/conductor/wait-run-cli.js +300 -21
- package/build/conductor/worker-database-doctor-inspector.js +34 -2
- package/build/conductor/worker-setup-tally.js +27 -0
- package/build/credential-store.js +96 -21
- package/build/dependency-install-declarations.js +212 -0
- package/build/docs.generated.js +4 -4
- package/build/doctor.js +91 -8
- package/build/drive-epic-help.js +23 -4
- package/build/drive-epic.js +1841 -340
- 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 +2184 -52
- package/build/epic-launch-context.js +607 -0
- package/build/epic-launch-profile.js +1 -1
- 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/cli.js +2 -0
- package/build/executor/completion-contract.js +24 -1
- package/build/executor/credentials.js +1 -1
- package/build/executor/delivery-observations.js +113 -0
- package/build/executor/delivery-outcome.js +30 -0
- package/build/executor/dependency-refresh-runner.js +132 -0
- package/build/executor/dependency-refresh.js +530 -0
- package/build/executor/deps.js +4 -0
- package/build/executor/env.js +119 -17
- package/build/executor/epic-server-context.js +141 -0
- package/build/executor/gate-qualification-job.js +127 -26
- package/build/executor/harness-coverage.js +19 -0
- package/build/executor/http-client.js +87 -6
- package/build/executor/index.js +2 -1
- package/build/executor/install-preflight.js +1 -1
- package/build/executor/job-runner.js +659 -87
- package/build/executor/likely-tests.js +94 -97
- package/build/executor/observation.js +8 -0
- package/build/executor/pre-pr-checks.js +363 -0
- package/build/executor/prompt-spec.js +127 -5
- package/build/executor/reconcile-overlap-job.js +5 -3
- package/build/executor/required-verification.js +28 -0
- package/build/executor/required-work-diagnostics.js +32 -0
- package/build/executor/required-work-ledger.js +955 -39
- package/build/executor/results.js +100 -0
- package/build/executor/service-discovery.js +42 -0
- package/build/executor/service-lifecycle.js +109 -2
- package/build/executor/service-uninstall.js +205 -0
- package/build/executor/service-unit.js +5 -3
- package/build/executor/terminal-mutation.js +8 -0
- package/build/executor/test-clock.js +3 -0
- package/build/executor/verification-hints.js +179 -0
- package/build/executor/worker-command.js +126 -5
- package/build/executor/worker-database-config.js +281 -0
- package/build/executor/worker-database-target.js +16 -12
- package/build/executor/worker-database.js +575 -116
- package/build/executor/worker-finalization.js +71 -10
- package/build/executor/worker-guard-hook.js +10 -2
- package/build/executor/worker-resources.js +25 -3
- package/build/executor/worker-verification-guidance.js +55 -5
- package/build/executor/worktree-inspection.js +42 -0
- package/build/executor/worktree.js +20 -1
- package/build/executor-launch.js +54 -2
- package/build/generated-assets-catalog.js +2 -2
- package/build/github-sign-in.js +1 -1
- package/build/index.js +1111 -381
- package/build/init.js +29 -14
- 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 +1383 -188
- package/build/install-bridge-conductor-setup.js +637 -92
- package/build/install-bridge-conductor.js +3163 -740
- package/build/install-bridge.js +601 -128
- package/build/install-maintenance.js +127 -0
- package/build/install-reexec.js +1 -1
- package/build/launcher-config-inspection.js +162 -1
- package/build/local-cleanup.js +59 -0
- 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-install-state.js +68 -2
- 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 +236 -111
- package/build/package-script-semantics.js +10 -0
- package/build/pipeline-utils.js +1 -1
- package/build/pipelines.generated.js +6 -6
- package/build/plan-discovery.js +97 -4
- package/build/plan-execution-ledger.js +248 -9
- 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 +23 -7
- package/build/plane/preflight.js +50 -10
- package/build/plane/shutdown.js +19 -0
- package/build/plane/terminal-run-cleanup.js +23 -5
- package/build/plane/terminal-run-status.js +4 -0
- package/build/printed-remedy-commands.js +229 -15
- package/build/readiness-check.js +1 -1
- package/build/readiness-prerequisites.generated.js +311 -4
- package/build/readme.generated.js +1 -1
- package/build/repository-state-paths.js +38 -0
- package/build/repository-toolchains.js +50 -8
- package/build/run-unit-tests-launcher.js +8 -1
- package/build/setup-change-policy.js +32 -0
- package/build/setup-epic.js +1192 -198
- package/build/setup-progress.js +44 -0
- package/build/setup-question.js +180 -0
- package/build/start-tickets.js +4 -0
- package/build/test-command-detection.js +32 -88
- package/build/test-support/notes-fs.js +40 -0
- package/build/third-party-mcp-targets.js +30 -0
- package/build/ticket-delivery-enrollment.js +30 -8
- package/build/ticket-delivery-run-scope.js +128 -0
- package/build/upgrade-cli.js +85 -2
- package/build/v2-readiness-requirements.js +28 -1
- package/build/version.generated.js +3 -3
- package/build/worker-guard-hook-bin.js +2 -2
- package/build/worktrees.js +105 -0
- package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
- package/docs/EPIC-IMPLEMENTER.md +5 -0
- package/docs/epic-implementer/getting-started.md +42 -15
- package/docs/epic-implementer/self-hosting.md +14 -1
- package/package.json +2 -2
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `epic-implementer driver-register --epic-run-id <id>` (BAPI-1642).
|
|
3
|
+
*
|
|
4
|
+
* Binds the current Claude Code driving session to one epic run so the Stop-hook
|
|
5
|
+
* guard (`driver-guard`) knows whose turn ends to check. The `/drive-epic-run`
|
|
6
|
+
* prompt runs it once after attach and confirmation, then starts the waiter it
|
|
7
|
+
* prints in the background.
|
|
8
|
+
*
|
|
9
|
+
* WHAT IT DOES. It reads `$CLAUDE_CODE_SESSION_ID`; when that is unset the host
|
|
10
|
+
* is not Claude Code, so it says the guard is not armed, writes nothing, and
|
|
11
|
+
* exits 0. Otherwise it reads the run once through the state route, mints a new
|
|
12
|
+
* random generation, provisions that generation's guard state, and atomically
|
|
13
|
+
* writes the session's registration and then the run's `driver-current.json`
|
|
14
|
+
* pointer. A re-attach always mints a new generation, so an old waiter or an old
|
|
15
|
+
* release can never clear the new one, and quiet time never expires it.
|
|
16
|
+
*
|
|
17
|
+
* WHAT IT IS NOT. It writes no run state, makes no other request, and never
|
|
18
|
+
* starts the waiter itself. A failure to arm is reported with the safe next
|
|
19
|
+
* step (keep monitoring in the foreground) and never stops the run.
|
|
20
|
+
*/
|
|
21
|
+
import { randomBytes } from "node:crypto";
|
|
22
|
+
import { fetchEpicRunState, resolveConductorBridgeApiAccess, } from "./bridge-api-client.js";
|
|
23
|
+
import { renderReleaseCommand, renderWaiterCommand, resolveDriverLauncher, } from "./driver-commands.js";
|
|
24
|
+
import { transcribeLapseResult } from "./driver-lapse.js";
|
|
25
|
+
import { DRIVER_KEY_PATTERN, DRIVER_RUN_REF_PATTERN, DRIVER_SESSION_ID_PATTERN, DRIVER_STATE_VERSION, appendDriverTallyLine, createDriverJsonExclusive, currentPointerPath, formatDriverTallyLine, generationFilePath, generationLabel, parseRegistration, readDriverJson, registrationPath, resolveDriverStateRoots, writeDriverJsonAtomic, } from "./driver-session-state.js";
|
|
26
|
+
const TERMINAL_RUN_STATUSES = new Set(["done", "abandoned"]);
|
|
27
|
+
const NOT_ARMED_NEXT_STEP = "Keep monitoring in the foreground; do not end a turn while the run is active.";
|
|
28
|
+
export function getDriverRegisterUsage() {
|
|
29
|
+
return [
|
|
30
|
+
"Usage: epic-implementer driver-register --epic-run-id <id> [--json]",
|
|
31
|
+
"",
|
|
32
|
+
"Arm the /drive-epic-run Stop-hook guard for this Claude Code session and print the",
|
|
33
|
+
"exact background waiter to keep running. Outside Claude Code it arms nothing and exits 0.",
|
|
34
|
+
].join("\n");
|
|
35
|
+
}
|
|
36
|
+
function parseArgs(argv) {
|
|
37
|
+
let epicRunId;
|
|
38
|
+
let json = false;
|
|
39
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
40
|
+
const token = argv[i];
|
|
41
|
+
if (token === "--help" || token === "-h")
|
|
42
|
+
return { help: true };
|
|
43
|
+
if (token === "--json") {
|
|
44
|
+
json = true;
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
if (token === "--epic-run-id" || token.startsWith("--epic-run-id=")) {
|
|
48
|
+
const value = token.includes("=") ? token.slice(token.indexOf("=") + 1) : argv[++i];
|
|
49
|
+
if (value === undefined)
|
|
50
|
+
throw new Error('Flag "--epic-run-id" requires a value.');
|
|
51
|
+
epicRunId = value.trim();
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
throw new Error('Unknown driver-register option. Run "epic-implementer driver-register --help" for usage.');
|
|
55
|
+
}
|
|
56
|
+
if (!epicRunId || !DRIVER_RUN_REF_PATTERN.test(epicRunId)) {
|
|
57
|
+
throw new Error('Flag "--epic-run-id" is required and must be a run id or epic key.');
|
|
58
|
+
}
|
|
59
|
+
return { help: false, epicRunId, json };
|
|
60
|
+
}
|
|
61
|
+
/** Provision the new generation's cap, then publish registration and pointer. */
|
|
62
|
+
async function publishRegistration(roots, registration) {
|
|
63
|
+
const cap = {
|
|
64
|
+
version: DRIVER_STATE_VERSION, generation: registration.generation, blocks: 0, lapsed: false,
|
|
65
|
+
};
|
|
66
|
+
const created = await createDriverJsonExclusive(generationFilePath(roots, registration.session_id, registration.generation, "cap.json"), cap);
|
|
67
|
+
if (!created)
|
|
68
|
+
throw new Error("generation collision");
|
|
69
|
+
await writeDriverJsonAtomic(registrationPath(roots, registration.session_id), registration);
|
|
70
|
+
const pointer = {
|
|
71
|
+
version: DRIVER_STATE_VERSION,
|
|
72
|
+
session_id: registration.session_id,
|
|
73
|
+
generation: registration.generation,
|
|
74
|
+
registered_at: registration.registered_at,
|
|
75
|
+
};
|
|
76
|
+
// Written last: until it lands, the guard sees a stale registration and allows.
|
|
77
|
+
await writeDriverJsonAtomic(currentPointerPath(roots, registration.epic_key), pointer);
|
|
78
|
+
}
|
|
79
|
+
/** Run `driver-register`. Never throws; returns the exit code. */
|
|
80
|
+
export async function runDriverRegisterCommand(argv, deps = {}) {
|
|
81
|
+
const env = deps.env ?? process.env;
|
|
82
|
+
const now = deps.now ?? (() => new Date());
|
|
83
|
+
const out = deps.writeStdout ?? ((text) => console.log(text));
|
|
84
|
+
const err = deps.writeStderr ?? ((line) => console.error(line));
|
|
85
|
+
const fail = (message) => {
|
|
86
|
+
err(`Error: ${message} The driver guard is not armed. ${NOT_ARMED_NEXT_STEP}`);
|
|
87
|
+
return 1;
|
|
88
|
+
};
|
|
89
|
+
let parsed;
|
|
90
|
+
try {
|
|
91
|
+
parsed = parseArgs(argv);
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
err(`Error: ${error.message}`);
|
|
95
|
+
return 1;
|
|
96
|
+
}
|
|
97
|
+
if (parsed.help) {
|
|
98
|
+
out(getDriverRegisterUsage());
|
|
99
|
+
return 0;
|
|
100
|
+
}
|
|
101
|
+
const sessionId = env.CLAUDE_CODE_SESSION_ID?.trim() ?? "";
|
|
102
|
+
if (sessionId.length === 0) {
|
|
103
|
+
out("Driver guard not armed: this host is not Claude Code (CLAUDE_CODE_SESSION_ID is unset). " +
|
|
104
|
+
NOT_ARMED_NEXT_STEP);
|
|
105
|
+
return 0;
|
|
106
|
+
}
|
|
107
|
+
if (!DRIVER_SESSION_ID_PATTERN.test(sessionId)) {
|
|
108
|
+
// The value is never echoed: it may be anything.
|
|
109
|
+
return fail("the Claude Code session id is not a plain token (letters, digits, '-').");
|
|
110
|
+
}
|
|
111
|
+
const launcher = resolveDriverLauncher(env);
|
|
112
|
+
if (!launcher)
|
|
113
|
+
return fail("BAPI_MCP_CLI cannot be used as a command prefix.");
|
|
114
|
+
try {
|
|
115
|
+
const resolveAccess = deps.resolveAccess ?? (async () => {
|
|
116
|
+
const resolved = await resolveConductorBridgeApiAccess({ followEpicLaunchProfile: true });
|
|
117
|
+
return resolved.ok ? resolved.access : null;
|
|
118
|
+
});
|
|
119
|
+
const access = await resolveAccess();
|
|
120
|
+
if (!access)
|
|
121
|
+
return fail("Bridge API credentials could not be resolved.");
|
|
122
|
+
const state = await (deps.fetchState ?? ((a, id) => fetchEpicRunState(a, id)))(access, parsed.epicRunId);
|
|
123
|
+
const run = state?.epic_run;
|
|
124
|
+
if (!run || !DRIVER_RUN_REF_PATTERN.test(run.epic_run_id) || !DRIVER_KEY_PATTERN.test(run.epic_key) ||
|
|
125
|
+
typeof run.repo_name !== "string" || run.repo_name.length === 0 ||
|
|
126
|
+
(parsed.epicRunId !== run.epic_run_id && parsed.epicRunId !== run.epic_key)) {
|
|
127
|
+
return fail("the run state read did not name this run.");
|
|
128
|
+
}
|
|
129
|
+
if (TERMINAL_RUN_STATUSES.has(run.status)) {
|
|
130
|
+
out(`Driver guard not armed: run ${run.epic_key} is ${run.status}; there is nothing left to supervise.`);
|
|
131
|
+
return 0;
|
|
132
|
+
}
|
|
133
|
+
const roots = resolveDriverStateRoots(deps.homeDir);
|
|
134
|
+
// Carry an earlier generation's finished lapse FYI into its own tally first.
|
|
135
|
+
const previous = await readDriverJson(registrationPath(roots, sessionId));
|
|
136
|
+
const previousRegistration = previous.state === "ok" ? parseRegistration(previous.value) : null;
|
|
137
|
+
if (previousRegistration)
|
|
138
|
+
await transcribeLapseResult(roots, previousRegistration, now).catch(() => undefined);
|
|
139
|
+
const generation = (deps.newGeneration ?? (() => randomBytes(16).toString("hex")))();
|
|
140
|
+
const registration = {
|
|
141
|
+
version: DRIVER_STATE_VERSION,
|
|
142
|
+
session_id: sessionId,
|
|
143
|
+
epic_run_id: run.epic_run_id,
|
|
144
|
+
epic_key: run.epic_key,
|
|
145
|
+
repo_name: run.repo_name,
|
|
146
|
+
generation,
|
|
147
|
+
waiter_command: renderWaiterCommand(launcher, run.epic_run_id, generation),
|
|
148
|
+
registered_at: now().toISOString(),
|
|
149
|
+
};
|
|
150
|
+
await publishRegistration(roots, registration);
|
|
151
|
+
await appendDriverTallyLine(roots, run.epic_key, formatDriverTallyLine("driver-guard", { event: "register", generation: generationLabel(generation) }, now())).catch(() => undefined);
|
|
152
|
+
if (parsed.json) {
|
|
153
|
+
out(JSON.stringify({
|
|
154
|
+
armed: true,
|
|
155
|
+
epic_key: run.epic_key,
|
|
156
|
+
epic_run_id: run.epic_run_id,
|
|
157
|
+
generation,
|
|
158
|
+
waiter_command: registration.waiter_command,
|
|
159
|
+
}));
|
|
160
|
+
return 0;
|
|
161
|
+
}
|
|
162
|
+
out([
|
|
163
|
+
`Driver guard armed for ${run.epic_key} (generation ${generationLabel(generation)}).`,
|
|
164
|
+
"Before any turn ends, keep this waiter running as a background task:",
|
|
165
|
+
registration.waiter_command,
|
|
166
|
+
"Release supervision only with one of:",
|
|
167
|
+
` ${renderReleaseCommand(launcher, "done", run.epic_run_id)} # the run is done or abandoned`,
|
|
168
|
+
` ${renderReleaseCommand(launcher, "handoff", run.epic_run_id)} # the hand-off report is published`,
|
|
169
|
+
` ${renderReleaseCommand(launcher, "owner", run.epic_run_id)} # only on the owner's explicit instruction`,
|
|
170
|
+
].join("\n"));
|
|
171
|
+
return 0;
|
|
172
|
+
}
|
|
173
|
+
catch {
|
|
174
|
+
return fail("the registration could not be written or the run could not be read.");
|
|
175
|
+
}
|
|
176
|
+
}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `epic-implementer driver-release --reason owner|done|handoff --epic-run-id <id>`
|
|
3
|
+
* (BAPI-1642).
|
|
4
|
+
*
|
|
5
|
+
* The only way a registered driving session may stop with no waiter running.
|
|
6
|
+
* `--reason` must come first, so permission rules can pre-authorize `done` and
|
|
7
|
+
* `handoff` for an unattended driver while `owner` still gets the host's own
|
|
8
|
+
* permission prompt (the BAPI-1448 `--user-consented` precedent).
|
|
9
|
+
*
|
|
10
|
+
* done the run is `done` or `abandoned`, read through the state route and
|
|
11
|
+
* matched to the registered run id;
|
|
12
|
+
* handoff the run's hand-off report is `published` (`run.handoff_report.state`
|
|
13
|
+
* from `explain_run`), the server's own proof the report was posted;
|
|
14
|
+
* owner recorded as a closed reason only. Use it only on the owner's
|
|
15
|
+
* explicit instruction to stop driving; a reply or a status question is
|
|
16
|
+
* never a release, and the guard never reads conversation text.
|
|
17
|
+
*
|
|
18
|
+
* A release is a marker in the guard-owned directory for this session's current
|
|
19
|
+
* generation. It lasts until the next `driver-register` and never touches the run.
|
|
20
|
+
* A refusal prints the registered waiter as the next step and exits 1; it pauses,
|
|
21
|
+
* parks, and holds nothing.
|
|
22
|
+
*/
|
|
23
|
+
import { fetchEpicRunState, fetchExplainRun, resolveConductorBridgeApiAccess, } from "./bridge-api-client.js";
|
|
24
|
+
import { DRIVER_RELEASE_REASONS, DRIVER_RUN_REF_PATTERN, DRIVER_SESSION_ID_PATTERN, DRIVER_STATE_VERSION, appendDriverTallyLine, currentPointerPath, formatDriverTallyLine, generationFilePath, generationLabel, parseCurrentPointer, parseRegistration, readDriverJson, registrationPath, resolveDriverStateRoots, writeDriverJsonAtomic, } from "./driver-session-state.js";
|
|
25
|
+
const TERMINAL_RUN_STATUSES = new Set(["done", "abandoned"]);
|
|
26
|
+
export function getDriverReleaseUsage() {
|
|
27
|
+
return [
|
|
28
|
+
"Usage: epic-implementer driver-release --reason owner|done|handoff --epic-run-id <id>",
|
|
29
|
+
"",
|
|
30
|
+
"Release this Claude Code session from /drive-epic-run supervision. --reason comes first.",
|
|
31
|
+
" done only after the run is done or abandoned (checked on the server)",
|
|
32
|
+
" handoff only after the run's hand-off report is published (checked on the server)",
|
|
33
|
+
" owner only when the owner explicitly tells you to stop driving",
|
|
34
|
+
"A release changes nothing on the run and lasts until the next driver-register.",
|
|
35
|
+
].join("\n");
|
|
36
|
+
}
|
|
37
|
+
function parseArgs(argv) {
|
|
38
|
+
if (argv.includes("--help") || argv.includes("-h"))
|
|
39
|
+
return { help: true };
|
|
40
|
+
if (argv.length !== 4 || argv[0] !== "--reason" || argv[2] !== "--epic-run-id") {
|
|
41
|
+
throw new Error('driver-release takes exactly "--reason <owner|done|handoff> --epic-run-id <id>", in that order.');
|
|
42
|
+
}
|
|
43
|
+
const reason = argv[1];
|
|
44
|
+
if (!DRIVER_RELEASE_REASONS.includes(reason)) {
|
|
45
|
+
throw new Error('Flag "--reason" must be owner, done, or handoff.');
|
|
46
|
+
}
|
|
47
|
+
const epicRunId = argv[3].trim();
|
|
48
|
+
if (!DRIVER_RUN_REF_PATTERN.test(epicRunId)) {
|
|
49
|
+
throw new Error('Flag "--epic-run-id" must be a run id or epic key.');
|
|
50
|
+
}
|
|
51
|
+
return { help: false, reason: reason, epicRunId };
|
|
52
|
+
}
|
|
53
|
+
async function checkReason(reason, registration, deps) {
|
|
54
|
+
if (reason === "owner")
|
|
55
|
+
return { ok: true };
|
|
56
|
+
const resolveAccess = deps.resolveAccess ?? (async () => {
|
|
57
|
+
const resolved = await resolveConductorBridgeApiAccess({ followEpicLaunchProfile: true });
|
|
58
|
+
return resolved.ok ? resolved.access : null;
|
|
59
|
+
});
|
|
60
|
+
const access = await resolveAccess();
|
|
61
|
+
if (!access)
|
|
62
|
+
return { ok: false, why: "Bridge API credentials could not be resolved, so the release could not be checked." };
|
|
63
|
+
if (reason === "done") {
|
|
64
|
+
const state = await (deps.fetchState ?? ((a, id) => fetchEpicRunState(a, id)))(access, registration.epic_run_id);
|
|
65
|
+
const run = state?.epic_run;
|
|
66
|
+
if (!run || run.epic_run_id !== registration.epic_run_id) {
|
|
67
|
+
return { ok: false, why: "the state read did not name the registered run." };
|
|
68
|
+
}
|
|
69
|
+
return TERMINAL_RUN_STATUSES.has(run.status)
|
|
70
|
+
? { ok: true }
|
|
71
|
+
: { ok: false, why: `the run is ${typeof run.status === "string" ? run.status.slice(0, 40) : "not terminal"}, not done or abandoned.` };
|
|
72
|
+
}
|
|
73
|
+
const explain = await (deps.fetchExplain ?? ((a, id) => fetchExplainRun(a, id)))(access, registration.epic_run_id);
|
|
74
|
+
const run = explain?.run;
|
|
75
|
+
if (!run || run.epic_run_id !== registration.epic_run_id) {
|
|
76
|
+
return { ok: false, why: "the explain read did not name the registered run." };
|
|
77
|
+
}
|
|
78
|
+
const state = run.handoff_report?.state;
|
|
79
|
+
return state === "published"
|
|
80
|
+
? { ok: true }
|
|
81
|
+
: { ok: false, why: `the hand-off report is ${typeof state === "string" ? state.slice(0, 40) : "not readable"}, not published.` };
|
|
82
|
+
}
|
|
83
|
+
async function loadCurrentRegistration(roots, sessionId) {
|
|
84
|
+
const read = await readDriverJson(registrationPath(roots, sessionId));
|
|
85
|
+
if (read.state === "absent")
|
|
86
|
+
return "absent";
|
|
87
|
+
const registration = read.state === "ok" ? parseRegistration(read.value) : null;
|
|
88
|
+
if (!registration || registration.session_id !== sessionId)
|
|
89
|
+
return "unreadable";
|
|
90
|
+
const pointerRead = await readDriverJson(currentPointerPath(roots, registration.epic_key));
|
|
91
|
+
const pointer = pointerRead.state === "ok" ? parseCurrentPointer(pointerRead.value) : null;
|
|
92
|
+
if (!pointer)
|
|
93
|
+
return "unreadable";
|
|
94
|
+
return pointer.generation === registration.generation && pointer.session_id === sessionId ? registration : "stale";
|
|
95
|
+
}
|
|
96
|
+
/** Run `driver-release`. Never throws; returns the exit code. */
|
|
97
|
+
export async function runDriverReleaseCommand(argv, deps = {}) {
|
|
98
|
+
const env = deps.env ?? process.env;
|
|
99
|
+
const now = deps.now ?? (() => new Date());
|
|
100
|
+
const out = deps.writeStdout ?? ((text) => console.log(text));
|
|
101
|
+
const err = deps.writeStderr ?? ((line) => console.error(line));
|
|
102
|
+
let parsed;
|
|
103
|
+
try {
|
|
104
|
+
parsed = parseArgs(argv);
|
|
105
|
+
}
|
|
106
|
+
catch (error) {
|
|
107
|
+
err(`Error: ${error.message}`);
|
|
108
|
+
return 1;
|
|
109
|
+
}
|
|
110
|
+
if (parsed.help) {
|
|
111
|
+
out(getDriverReleaseUsage());
|
|
112
|
+
return 0;
|
|
113
|
+
}
|
|
114
|
+
const sessionId = env.CLAUDE_CODE_SESSION_ID?.trim() ?? "";
|
|
115
|
+
if (sessionId.length === 0) {
|
|
116
|
+
out("Nothing to release: this host is not Claude Code, so no driver guard was armed.");
|
|
117
|
+
return 0;
|
|
118
|
+
}
|
|
119
|
+
if (!DRIVER_SESSION_ID_PATTERN.test(sessionId)) {
|
|
120
|
+
err("Error: the Claude Code session id is not a plain token; nothing was released.");
|
|
121
|
+
return 1;
|
|
122
|
+
}
|
|
123
|
+
try {
|
|
124
|
+
const roots = resolveDriverStateRoots(deps.homeDir);
|
|
125
|
+
const registration = await loadCurrentRegistration(roots, sessionId);
|
|
126
|
+
if (registration === "absent") {
|
|
127
|
+
out("Nothing to release: this session is not registered as a driver.");
|
|
128
|
+
return 0;
|
|
129
|
+
}
|
|
130
|
+
if (registration === "stale") {
|
|
131
|
+
out("Nothing to release: this session's registration was replaced by a newer driver-register, " +
|
|
132
|
+
"so the guard no longer applies to it.");
|
|
133
|
+
return 0;
|
|
134
|
+
}
|
|
135
|
+
if (registration === "unreadable") {
|
|
136
|
+
err("Error: this session's registration could not be read; nothing was released. " +
|
|
137
|
+
"Run driver-register again to re-arm, then release.");
|
|
138
|
+
return 1;
|
|
139
|
+
}
|
|
140
|
+
if (parsed.epicRunId !== registration.epic_run_id && parsed.epicRunId !== registration.epic_key) {
|
|
141
|
+
err(`Error: this session is registered for ${registration.epic_key}, not the named run; nothing was released.`);
|
|
142
|
+
return 1;
|
|
143
|
+
}
|
|
144
|
+
const check = await checkReason(parsed.reason, registration, deps);
|
|
145
|
+
if (!check.ok) {
|
|
146
|
+
err(`Error: release refused (--reason ${parsed.reason}): ${check.why} Supervision continues. ` +
|
|
147
|
+
`Next step: keep this waiter running in the background: ${registration.waiter_command}`);
|
|
148
|
+
await appendDriverTallyLine(roots, registration.epic_key, formatDriverTallyLine("driver-guard", { event: "release_refused", reason: parsed.reason, generation: generationLabel(registration.generation) }, now())).catch(() => undefined);
|
|
149
|
+
return 1;
|
|
150
|
+
}
|
|
151
|
+
// Re-read the pointer immediately before committing: a re-attach since the
|
|
152
|
+
// check must not receive a release meant for the generation it replaced.
|
|
153
|
+
const again = await loadCurrentRegistration(roots, sessionId);
|
|
154
|
+
if (typeof again === "string" || again.generation !== registration.generation) {
|
|
155
|
+
err("Error: this session was re-registered during the release; nothing was released. Release again.");
|
|
156
|
+
return 1;
|
|
157
|
+
}
|
|
158
|
+
const marker = {
|
|
159
|
+
version: DRIVER_STATE_VERSION,
|
|
160
|
+
generation: registration.generation,
|
|
161
|
+
reason: parsed.reason,
|
|
162
|
+
released_at: now().toISOString(),
|
|
163
|
+
};
|
|
164
|
+
await writeDriverJsonAtomic(generationFilePath(roots, sessionId, registration.generation, "release.json"), marker);
|
|
165
|
+
await appendDriverTallyLine(roots, registration.epic_key, formatDriverTallyLine("driver-guard", { event: "release", reason: parsed.reason, generation: generationLabel(registration.generation) }, now())).catch(() => undefined);
|
|
166
|
+
out(`Released (--reason ${parsed.reason}): this session may now stop without a waiter. ` +
|
|
167
|
+
"The run itself is unchanged.");
|
|
168
|
+
return 0;
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
err("Error: the release could not be checked or recorded; nothing was released. Supervision continues.");
|
|
172
|
+
return 1;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Private local state for the `/drive-epic-run` driver guard (BAPI-1642).
|
|
3
|
+
*
|
|
4
|
+
* WHAT LIVES WHERE. Two roots, both under the user's home:
|
|
5
|
+
*
|
|
6
|
+
* ~/.local/state/bapi-conductor-runs/ (BRIDGE_RUN_STATE_DIR)
|
|
7
|
+
* driver-sessions/<session_id>.json the session's registration
|
|
8
|
+
* <KEY>/driver-current.json the run's current generation
|
|
9
|
+
* <KEY>/tally.md the run's tally (append only)
|
|
10
|
+
* <KEY>/blocker-receipt-<TICKET>.json the last declare-blocked receipt
|
|
11
|
+
*
|
|
12
|
+
* ~/.local/state/bapi-conductor-guard/<session_id>/<generation>/
|
|
13
|
+
* cap.json release.json lapse-pending.json lapse-result.json
|
|
14
|
+
* lapse-output.log lapse-transcribed.json lock
|
|
15
|
+
*
|
|
16
|
+
* The second root is outside the run-state `Edit`/`Write` permission rules, so
|
|
17
|
+
* the driving agent is never pre-authorized to reset its own block counter or
|
|
18
|
+
* forge a release. The registration and `driver-current.json` stay at the paths
|
|
19
|
+
* the ticket fixed, under the agent-writable run-state root: editing them can
|
|
20
|
+
* only make the guard see a stale or unreadable registration, which allows the
|
|
21
|
+
* stop (fail-open), never blocks. The guard targets model mistakes, not an
|
|
22
|
+
* adversarial agent. This state is independent of conversation state and of any
|
|
23
|
+
* claim the agent makes, but it is NOT isolated from another process running as
|
|
24
|
+
* the same user: POSIX modes keep other users out, nothing more, and on Windows
|
|
25
|
+
* they are advisory.
|
|
26
|
+
*
|
|
27
|
+
* Every identifier that becomes a path segment is validated first, so a session
|
|
28
|
+
* id, generation, epic key, or ticket key can never form a path. Every JSON
|
|
29
|
+
* write is a private temp file plus rename. Every read is bounded and reports
|
|
30
|
+
* absent, malformed, or failed distinctly, so a corrupt counter is never read as
|
|
31
|
+
* a fresh zero.
|
|
32
|
+
*/
|
|
33
|
+
import { randomBytes } from "node:crypto";
|
|
34
|
+
import { appendFile, mkdir, open, readFile, rename, stat, unlink } from "node:fs/promises";
|
|
35
|
+
import os from "node:os";
|
|
36
|
+
import path from "node:path";
|
|
37
|
+
import { BRIDGE_DRIVER_GUARD_STATE_DIR, BRIDGE_RUN_STATE_DIR } from "../bridge-permissions.js";
|
|
38
|
+
// ---------------------------------------------------------------------------
|
|
39
|
+
// Constants and identifier shapes
|
|
40
|
+
// ---------------------------------------------------------------------------
|
|
41
|
+
export const DRIVER_STATE_VERSION = 1;
|
|
42
|
+
/** A Claude Code session id: letters, digits and `-` only, so it never forms a path. */
|
|
43
|
+
export const DRIVER_SESSION_ID_PATTERN = /^[A-Za-z0-9-]{1,128}$/;
|
|
44
|
+
/** A registration generation: 32 lowercase hex characters from a CSPRNG. */
|
|
45
|
+
export const DRIVER_GENERATION_PATTERN = /^[0-9a-f]{32}$/;
|
|
46
|
+
/** An epic or ticket key, the same shape `drive-epic` accepts. */
|
|
47
|
+
export const DRIVER_KEY_PATTERN = /^[A-Z][A-Z0-9_]{0,19}-[0-9]+$/;
|
|
48
|
+
/** A run id or epic key as passed on the command line. */
|
|
49
|
+
export const DRIVER_RUN_REF_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
|
|
50
|
+
/** No state file this module reads may be larger than this. */
|
|
51
|
+
export const DRIVER_STATE_MAX_BYTES = 16 * 1024;
|
|
52
|
+
/** A lock file older than this is a crashed holder's and may be cleared once. */
|
|
53
|
+
export const DRIVER_LOCK_STALE_MS = 10_000;
|
|
54
|
+
/** The three authorized release reasons. */
|
|
55
|
+
export const DRIVER_RELEASE_REASONS = ["owner", "done", "handoff"];
|
|
56
|
+
/** Blocks 1..3 are enforced; the next attempt allows and records a lapse. */
|
|
57
|
+
export const DRIVER_GUARD_BLOCK_CAP = 3;
|
|
58
|
+
function expandHome(dir, homeDir) {
|
|
59
|
+
return dir.startsWith("~/") ? path.join(homeDir, ...dir.slice(2).split("/")) : dir;
|
|
60
|
+
}
|
|
61
|
+
/** Expand both roots against `homeDir` (defaults to the OS home directory). */
|
|
62
|
+
export function resolveDriverStateRoots(homeDir = os.homedir()) {
|
|
63
|
+
return {
|
|
64
|
+
runRoot: expandHome(BRIDGE_RUN_STATE_DIR, homeDir),
|
|
65
|
+
guardRoot: expandHome(BRIDGE_DRIVER_GUARD_STATE_DIR, homeDir),
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
function requireSegment(value, pattern) {
|
|
69
|
+
if (!pattern.test(value))
|
|
70
|
+
throw new Error("invalid driver state identifier");
|
|
71
|
+
return value;
|
|
72
|
+
}
|
|
73
|
+
export function registrationPath(roots, sessionId) {
|
|
74
|
+
return path.join(roots.runRoot, "driver-sessions", `${requireSegment(sessionId, DRIVER_SESSION_ID_PATTERN)}.json`);
|
|
75
|
+
}
|
|
76
|
+
export function runDirPath(roots, epicKey) {
|
|
77
|
+
return path.join(roots.runRoot, requireSegment(epicKey, DRIVER_KEY_PATTERN));
|
|
78
|
+
}
|
|
79
|
+
export function currentPointerPath(roots, epicKey) {
|
|
80
|
+
return path.join(runDirPath(roots, epicKey), "driver-current.json");
|
|
81
|
+
}
|
|
82
|
+
export function tallyPath(roots, epicKey) {
|
|
83
|
+
return path.join(runDirPath(roots, epicKey), "tally.md");
|
|
84
|
+
}
|
|
85
|
+
export function blockerReceiptPath(roots, epicKey, ticketKey) {
|
|
86
|
+
return path.join(runDirPath(roots, epicKey), `blocker-receipt-${requireSegment(ticketKey, DRIVER_KEY_PATTERN)}.json`);
|
|
87
|
+
}
|
|
88
|
+
/** The guard-owned directory of one session's one generation. */
|
|
89
|
+
export function generationDirPath(roots, sessionId, generation) {
|
|
90
|
+
return path.join(roots.guardRoot, requireSegment(sessionId, DRIVER_SESSION_ID_PATTERN), requireSegment(generation, DRIVER_GENERATION_PATTERN));
|
|
91
|
+
}
|
|
92
|
+
export function generationFilePath(roots, sessionId, generation, file) {
|
|
93
|
+
return path.join(generationDirPath(roots, sessionId, generation), file);
|
|
94
|
+
}
|
|
95
|
+
export const LAPSE_OUTCOMES = ["escalated", "suppressed_terminal", "failed"];
|
|
96
|
+
/** A closed token safe for a tally line: no spaces, no punctuation beyond `_.:-`. */
|
|
97
|
+
export const DRIVER_CLOSED_TOKEN_PATTERN = /^[A-Za-z0-9_.:-]{1,80}$/;
|
|
98
|
+
/** `delivery_status` values the server can return (the `unknown:` reason is a closed token). */
|
|
99
|
+
export const DRIVER_DELIVERY_STATUS_PATTERN = /^(queued|handed_off|failed|not delivered: local no-op transport|not delivered: recorded locally|unknown: [a-z_]{1,64})$/;
|
|
100
|
+
function isRecord(value) {
|
|
101
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
102
|
+
}
|
|
103
|
+
function isIso(value) {
|
|
104
|
+
return typeof value === "string" && value.length <= 40 && !Number.isNaN(Date.parse(value));
|
|
105
|
+
}
|
|
106
|
+
function isToken(value, pattern) {
|
|
107
|
+
return typeof value === "string" && pattern.test(value);
|
|
108
|
+
}
|
|
109
|
+
export function parseRegistration(value) {
|
|
110
|
+
if (!isRecord(value) || value.version !== DRIVER_STATE_VERSION)
|
|
111
|
+
return null;
|
|
112
|
+
if (!isToken(value.session_id, DRIVER_SESSION_ID_PATTERN) ||
|
|
113
|
+
!isToken(value.epic_run_id, DRIVER_RUN_REF_PATTERN) ||
|
|
114
|
+
!isToken(value.epic_key, DRIVER_KEY_PATTERN) ||
|
|
115
|
+
typeof value.repo_name !== "string" || value.repo_name.length === 0 || value.repo_name.length > 200 ||
|
|
116
|
+
!isToken(value.generation, DRIVER_GENERATION_PATTERN) ||
|
|
117
|
+
typeof value.waiter_command !== "string" || value.waiter_command.length === 0 ||
|
|
118
|
+
value.waiter_command.length > 1000 || !isIso(value.registered_at)) {
|
|
119
|
+
return null;
|
|
120
|
+
}
|
|
121
|
+
return value;
|
|
122
|
+
}
|
|
123
|
+
export function parseCurrentPointer(value) {
|
|
124
|
+
if (!isRecord(value) || value.version !== DRIVER_STATE_VERSION)
|
|
125
|
+
return null;
|
|
126
|
+
if (!isToken(value.session_id, DRIVER_SESSION_ID_PATTERN) ||
|
|
127
|
+
!isToken(value.generation, DRIVER_GENERATION_PATTERN) || !isIso(value.registered_at)) {
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
return value;
|
|
131
|
+
}
|
|
132
|
+
export function parseCapState(value) {
|
|
133
|
+
if (!isRecord(value) || value.version !== DRIVER_STATE_VERSION)
|
|
134
|
+
return null;
|
|
135
|
+
if (!isToken(value.generation, DRIVER_GENERATION_PATTERN) ||
|
|
136
|
+
!Number.isSafeInteger(value.blocks) || value.blocks < 0 ||
|
|
137
|
+
value.blocks > DRIVER_GUARD_BLOCK_CAP || typeof value.lapsed !== "boolean") {
|
|
138
|
+
return null;
|
|
139
|
+
}
|
|
140
|
+
return value;
|
|
141
|
+
}
|
|
142
|
+
export function parseReleaseMarker(value) {
|
|
143
|
+
if (!isRecord(value) || value.version !== DRIVER_STATE_VERSION)
|
|
144
|
+
return null;
|
|
145
|
+
if (!isToken(value.generation, DRIVER_GENERATION_PATTERN) ||
|
|
146
|
+
!DRIVER_RELEASE_REASONS.includes(value.reason) || !isIso(value.released_at)) {
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
return value;
|
|
150
|
+
}
|
|
151
|
+
export function parsePendingLapse(value) {
|
|
152
|
+
if (!isRecord(value) || value.version !== DRIVER_STATE_VERSION)
|
|
153
|
+
return null;
|
|
154
|
+
if (!isToken(value.session_id, DRIVER_SESSION_ID_PATTERN) ||
|
|
155
|
+
!isToken(value.generation, DRIVER_GENERATION_PATTERN) ||
|
|
156
|
+
!isToken(value.epic_run_id, DRIVER_RUN_REF_PATTERN) ||
|
|
157
|
+
!isToken(value.epic_key, DRIVER_KEY_PATTERN) || !isIso(value.created_at)) {
|
|
158
|
+
return null;
|
|
159
|
+
}
|
|
160
|
+
return value;
|
|
161
|
+
}
|
|
162
|
+
export function parseLapseResult(value) {
|
|
163
|
+
if (!isRecord(value) || value.version !== DRIVER_STATE_VERSION)
|
|
164
|
+
return null;
|
|
165
|
+
if (!isToken(value.generation, DRIVER_GENERATION_PATTERN) ||
|
|
166
|
+
!LAPSE_OUTCOMES.includes(value.outcome) || !isIso(value.finished_at)) {
|
|
167
|
+
return null;
|
|
168
|
+
}
|
|
169
|
+
if (value.ticket_key !== null && !isToken(value.ticket_key, DRIVER_KEY_PATTERN))
|
|
170
|
+
return null;
|
|
171
|
+
if (value.notification_id !== null &&
|
|
172
|
+
(!Number.isSafeInteger(value.notification_id) || value.notification_id <= 0))
|
|
173
|
+
return null;
|
|
174
|
+
if (value.delivery_status !== null && !isToken(value.delivery_status, DRIVER_DELIVERY_STATUS_PATTERN))
|
|
175
|
+
return null;
|
|
176
|
+
if (value.failure_reason !== null && !isToken(value.failure_reason, DRIVER_CLOSED_TOKEN_PATTERN))
|
|
177
|
+
return null;
|
|
178
|
+
return value;
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Read one small JSON file. Absent, malformed (bad JSON or over the size cap),
|
|
182
|
+
* and failed (any other I/O error, including an abort) are distinct, so a
|
|
183
|
+
* caller can never mistake a corrupt record for a missing one.
|
|
184
|
+
*/
|
|
185
|
+
export async function readDriverJson(filePath, signal) {
|
|
186
|
+
let raw;
|
|
187
|
+
try {
|
|
188
|
+
raw = await readFile(filePath, signal ? { signal } : {});
|
|
189
|
+
}
|
|
190
|
+
catch (error) {
|
|
191
|
+
const code = error?.code;
|
|
192
|
+
return code === "ENOENT" ? { state: "absent" } : { state: "failed" };
|
|
193
|
+
}
|
|
194
|
+
if (raw.length > DRIVER_STATE_MAX_BYTES)
|
|
195
|
+
return { state: "malformed" };
|
|
196
|
+
try {
|
|
197
|
+
return { state: "ok", value: JSON.parse(raw.toString("utf-8")) };
|
|
198
|
+
}
|
|
199
|
+
catch {
|
|
200
|
+
return { state: "malformed" };
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
/** Create `dir` (and parents) with mode 0700. */
|
|
204
|
+
export async function ensurePrivateDir(dir) {
|
|
205
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Replace `filePath` with `value` atomically: a unique 0600 temp file in the
|
|
209
|
+
* same directory, then a rename. A reader sees the old file or the new one,
|
|
210
|
+
* never a partial write.
|
|
211
|
+
*/
|
|
212
|
+
export async function writeDriverJsonAtomic(filePath, value) {
|
|
213
|
+
await ensurePrivateDir(path.dirname(filePath));
|
|
214
|
+
const temp = `${filePath}.${randomBytes(6).toString("hex")}.tmp`;
|
|
215
|
+
try {
|
|
216
|
+
const handle = await open(temp, "wx", 0o600);
|
|
217
|
+
try {
|
|
218
|
+
await handle.writeFile(`${JSON.stringify(value)}\n`, "utf-8");
|
|
219
|
+
}
|
|
220
|
+
finally {
|
|
221
|
+
await handle.close();
|
|
222
|
+
}
|
|
223
|
+
await rename(temp, filePath);
|
|
224
|
+
}
|
|
225
|
+
catch (error) {
|
|
226
|
+
await unlink(temp).catch(() => undefined);
|
|
227
|
+
throw error;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Create `filePath` only if it does not exist (0600). Returns false when it
|
|
232
|
+
* already exists. Used for once-only records such as a pending lapse.
|
|
233
|
+
*/
|
|
234
|
+
export async function createDriverJsonExclusive(filePath, value) {
|
|
235
|
+
await ensurePrivateDir(path.dirname(filePath));
|
|
236
|
+
let handle;
|
|
237
|
+
try {
|
|
238
|
+
handle = await open(filePath, "wx", 0o600);
|
|
239
|
+
}
|
|
240
|
+
catch (error) {
|
|
241
|
+
if (error?.code === "EEXIST")
|
|
242
|
+
return false;
|
|
243
|
+
throw error;
|
|
244
|
+
}
|
|
245
|
+
try {
|
|
246
|
+
await handle.writeFile(`${JSON.stringify(value)}\n`, "utf-8");
|
|
247
|
+
}
|
|
248
|
+
finally {
|
|
249
|
+
await handle.close();
|
|
250
|
+
}
|
|
251
|
+
return true;
|
|
252
|
+
}
|
|
253
|
+
// ---------------------------------------------------------------------------
|
|
254
|
+
// The exclusive operation lock
|
|
255
|
+
// ---------------------------------------------------------------------------
|
|
256
|
+
/**
|
|
257
|
+
* Run `fn` while holding `lockPath` exclusively. Never waits: when another
|
|
258
|
+
* holder is live the result is `contended`, and the caller fails open. A lock
|
|
259
|
+
* older than {@link DRIVER_LOCK_STALE_MS} belongs to a crashed holder and is
|
|
260
|
+
* cleared once before one more attempt.
|
|
261
|
+
*/
|
|
262
|
+
export async function withDriverLock(lockPath, fn, now = Date.now) {
|
|
263
|
+
await ensurePrivateDir(path.dirname(lockPath));
|
|
264
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
265
|
+
let handle;
|
|
266
|
+
try {
|
|
267
|
+
handle = await open(lockPath, "wx", 0o600);
|
|
268
|
+
}
|
|
269
|
+
catch (error) {
|
|
270
|
+
if (error?.code !== "EEXIST")
|
|
271
|
+
throw error;
|
|
272
|
+
if (attempt > 0)
|
|
273
|
+
return { state: "contended" };
|
|
274
|
+
const info = await stat(lockPath).catch(() => null);
|
|
275
|
+
if (!info || now() - info.mtimeMs < DRIVER_LOCK_STALE_MS)
|
|
276
|
+
return { state: "contended" };
|
|
277
|
+
await unlink(lockPath).catch(() => undefined);
|
|
278
|
+
continue;
|
|
279
|
+
}
|
|
280
|
+
await handle.close();
|
|
281
|
+
try {
|
|
282
|
+
return { state: "held", value: await fn() };
|
|
283
|
+
}
|
|
284
|
+
finally {
|
|
285
|
+
await unlink(lockPath).catch(() => undefined);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
return { state: "contended" };
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Format one CLI-written tally line: `- <UTC> <kind>: k=v k=v`. Every value
|
|
292
|
+
* must be a closed token or a safe integer; anything else is written as
|
|
293
|
+
* `invalid`, so no free text, message, or secret can reach the line.
|
|
294
|
+
*/
|
|
295
|
+
export function formatDriverTallyLine(kind, fields, at) {
|
|
296
|
+
const parts = Object.entries(fields).map(([key, value]) => {
|
|
297
|
+
const safe = typeof value === "number"
|
|
298
|
+
? (Number.isSafeInteger(value) ? String(value) : "invalid")
|
|
299
|
+
: (DRIVER_CLOSED_TOKEN_PATTERN.test(value) ? value : "invalid");
|
|
300
|
+
return `${key}=${safe}`;
|
|
301
|
+
});
|
|
302
|
+
return `- ${at.toISOString()} ${kind}: ${parts.join(" ")}\n`;
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Append one complete line to `<KEY>/tally.md` in a single `appendFile()` call
|
|
306
|
+
* (0600 on create). The run directory is created private when missing.
|
|
307
|
+
*/
|
|
308
|
+
export async function appendDriverTallyLine(roots, epicKey, line) {
|
|
309
|
+
await ensurePrivateDir(runDirPath(roots, epicKey));
|
|
310
|
+
await appendFile(tallyPath(roots, epicKey), line.endsWith("\n") ? line : `${line}\n`, { encoding: "utf-8", mode: 0o600 });
|
|
311
|
+
}
|
|
312
|
+
/** A short, non-identifying prefix of a generation for tally lines. */
|
|
313
|
+
export function generationLabel(generation) {
|
|
314
|
+
return generation.slice(0, 8);
|
|
315
|
+
}
|