@code-yeongyu/senpi
Version:
Coding agent CLI with read, bash, edit, write tools and session management
111 lines • 5.79 kB
JavaScript
/**
* The startup intent of one endpoint (senpi#4602, A-amended section 5): recovery evidence a launcher
* writes under the endpoint's ensure lock BEFORE it spawns, so a later lock holder can tell a start
* that may still be running from one that is provably over. It is not a progress channel and grants
* no right to signal anything.
*
* The next holder reconciles a leftover intent through the candidate's OWN identity: the child the launcher
* bound, or else the supervisor that recorded the same attempt nonce in its generation directory. Only a
* candidate proven gone is cleared at once. A candidate nobody can identify is UNKNOWN, and stays refused
* until the intent is older than the settled-result bound - the longest any start, cleanup included, runs.
*/
import { rm, stat } from "node:fs/promises";
import { join } from "node:path";
import { processMatchesPidFile, readProcessStartTime } from "../../utils/process-identity.js";
import { generationPaths } from "./host-daemon-paths.js";
import { HostEnsureRefusedError } from "./host-decision.js";
import { childStalledStopMaxMs } from "./host-stalled-evidence.js";
import { startupEnvelope } from "./host-startup-policy.js";
import { readJsonObject, writeJsonAtomic } from "./host-state-json.js";
import { STARTUP_ATTEMPT_FILE } from "./host-startup-wire.js";
const STARTUP_INTENT_FILE = "startup-intent.json";
const STARTUP_INTENT_VERSION = 1;
export function startupIntentPath(daemonDir) {
return join(daemonDir, STARTUP_INTENT_FILE);
}
/** Written (mode 0600, by rename) under the ensure lock, before the spawn. */
export function writeStartupIntent(daemonDir, intent) {
return writeJsonAtomic(startupIntentPath(daemonDir), { version: STARTUP_INTENT_VERSION, ...intent });
}
/** `unreadable` carries the file's age source, so even a torn intent expires. */
export async function readStartupIntent(daemonDir) {
const modified = await stat(startupIntentPath(daemonDir)).then((entry) => entry.mtimeMs, () => undefined);
if (modified === undefined)
return undefined;
const record = await readJsonObject(startupIntentPath(daemonDir));
const launcher = pidFileOf(record?.launcher);
const child = record?.child === undefined ? undefined : pidFileOf(record.child);
if (!record ||
record.version !== STARTUP_INTENT_VERSION ||
typeof record.attempt !== "string" ||
typeof record.instanceId !== "string" ||
typeof record.generation !== "number" ||
typeof record.writtenAt !== "number" ||
!launcher ||
child === null)
return { unreadable: true, writtenAt: modified };
return {
attempt: record.attempt,
instanceId: record.instanceId,
generation: record.generation,
launcher,
writtenAt: record.writtenAt,
...(child ? { child } : {}),
};
}
export function clearStartupIntent(daemonDir) {
return rm(startupIntentPath(daemonDir), { force: true });
}
/** The identity a supervisor recorded for `attempt` in its own generation directory, if it got that far. */
export async function readStartupAttemptRecord(generationDir, attempt) {
const record = await readJsonObject(join(generationDir, STARTUP_ATTEMPT_FILE));
if (record?.attempt !== attempt)
return undefined;
return pidFileOf(record) ?? undefined;
}
export async function reconcileStartupIntent(intent, options) {
if (intent === undefined)
return "none";
const expiredOr = (verdict) => options.now - intent.writtenAt >= options.expiryMs ? "expired" : verdict;
if ("unreadable" in intent)
return expiredOr("unknown");
const candidate = intent.child ?? (await options.attemptRecord(intent.instanceId, intent.attempt));
if (!candidate)
return expiredOr("unknown");
const live = await options.matches(candidate).catch(() => undefined);
if (live === undefined)
return expiredOr("unknown");
return live ? "candidate_live" : "candidate_gone";
}
/**
* Run under the ensure lock before a start: a leftover intent whose candidate is gone, or that expired, is
* cleared; one whose candidate may still run refuses this start and stays as evidence. Nothing is signalled.
*/
export async function settleStartupIntent(paths, socket, readStartTime = readProcessStartTime) {
const expiryMs = startupEnvelope(childStalledStopMaxMs()).settled;
const verdict = await reconcileStartupIntent(await readStartupIntent(paths.dir), {
matches: (record) => processMatchesPidFile(record, readStartTime),
attemptRecord: (instanceId, attempt) => readStartupAttemptRecord(generationPaths(paths, instanceId).dir, attempt),
expiryMs,
now: Date.now(),
});
if (verdict === "none")
return;
if (verdict === "candidate_gone" || verdict === "expired")
return clearStartupIntent(paths.dir);
const detail = verdict === "candidate_live"
? `a previous start of this endpoint is still running and never registered (${startupIntentPath(paths.dir)})`
: `a previous start of this endpoint cannot be identified; ${startupIntentPath(paths.dir)} is kept until its candidate is proven gone or ${expiryMs}ms after it was written`;
throw new HostEnsureRefusedError(socket, verdict === "candidate_live" ? "host_stalled" : "endpoint_occupied", undefined, detail);
}
function pidFileOf(value) {
if (typeof value !== "object" || value === null)
return null;
const { pid, processStartTime } = value;
if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0)
return null;
if (processStartTime !== null && typeof processStartTime !== "string")
return null;
return { pid, processStartTime };
}
//# sourceMappingURL=host-startup-intent.js.map