diff --git a/.pylon/features.yaml b/.pylon/features.yaml index b3d41846bac..2ba7d3ef67d 100644 --- a/.pylon/features.yaml +++ b/.pylon/features.yaml @@ -215,17 +215,19 @@ decisions: owner: shared decision: hybridize pylon_refs: + - https://github.com/pylon-code/pylon/issues/557 - https://github.com/pylon-code/prime-agent/issues/11 - https://github.com/pylon-code/prime-agent/pull/14 - https://github.com/pylon-code/pylon/issues/114 - https://github.com/rynfar/comet/issues/5 upstream_refs: + - https://github.com/PrimeIntellect-ai/prime-agent/issues/1908 - https://github.com/PrimeIntellect-ai/prime-agent/pull/1756 - https://github.com/PrimeIntellect-ai/prime-agent/pull/1858 - https://github.com/PrimeIntellect-ai/prime-agent/pull/1864 - https://github.com/PrimeIntellect-ai/prime-agent/pull/1882 - fork_change: negotiated-authoritative-owned-session-cleanup-v1 - upstream_support: Prime through a903d4b6768f has recovery-aware reuse, owner-checked opens, bounded daemon-close bash draining, per-command abort ownership, client-owned sessions, and best-effort owner cleanup, but another host process cannot prove exact worker-generation and durable-descriptor absence after the owner connection disappears. + fork_change: negotiated-authoritative-owned-session-cleanup-v1-and-local-settlement-observation + upstream_support: Reviewed again 2026-09-18; upstream issue 1908 concerns PID-based session lease cleanup, not a public read-only settlement proof for prior caller-owned roots across socket namespaces. Prime through a903d4b6768f has recovery-aware reuse, owner-checked opens, bounded daemon-close bash draining, per-command abort ownership, client-owned sessions, and best-effort owner cleanup, but another host process cannot prove exact worker-generation and durable-descriptor absence after the owner connection disappears. revisit_when: - Prime upstream exposes an equivalent privacy-safe, capability-negotiated cleanup proof with durable descriptor-last retries. - Comet and Pylon can remove the fork capability without weakening crash cleanup or stock-Prime fallback behavior. diff --git a/.pylon/upstream-review.md b/.pylon/upstream-review.md index 2d2752b1aa6..9357423e67f 100644 --- a/.pylon/upstream-review.md +++ b/.pylon/upstream-review.md @@ -378,3 +378,14 @@ Follow-up: Task10 builds/packs the exact merged tree into a private prefix and r - Add an optional original timestamp to both custom append methods and pass it from every AgentSession custom-message write: delivered/queued messages, direct messages, session commands, Python state, harness digests, refinement and compaction outcomes. Calls that originate durable markers without a live message retain their existing current-time default. Invalid or lossy timestamps fail before publication. - No daemon command, event, response shape, protocol/schema revision, artifact recipe or capability changes. Historical files are not rewritten. An older custom record whose live and persisted timestamps already disagree remains unproved; Pylon must not relax history matching to accept it. New managed bytes are required for the correction. - Validation: 165 focused tests pass across the timestamp regression, session persistence/rollback, compaction and input queue. The regression deliberately advances the clock at the persistence boundary and verifies the exact live, pre-compaction tree, current context and reopened session messages. `npm run check` and required hosted checks accompany the PR. + +## 2026-09-18: legacy caller-owned settlement observation + +Decision: hybridize the existing descriptor-last cleanup invariant with a public, +read-only local SDK observation. Upstream #1908 requests PID-based lease sweeping; +it does not cover a host-private acquired receipt lacking a recovery handle and +old socket identity. Existing public replacement-client cleanup remains unchanged. +The SDK token gates the new local API; daemon wire shapes and stock behavior do +not change. Validation: focused malformed/private/path/registration cases and a real +isolated supervisor/owned-worker test prove registered before cleanup and settled +after exact owned cleanup and supervisor exit. Pylon delivery tracked in [pylon#557](https://github.com/pylon-code/pylon/issues/557). diff --git a/packages/coding-agent/.changes/legacy-owned-session-settlement.md b/packages/coding-agent/.changes/legacy-owned-session-settlement.md new file mode 100644 index 00000000000..5a6e6020b16 --- /dev/null +++ b/packages/coding-agent/.changes/legacy-owned-session-settlement.md @@ -0,0 +1 @@ +- Added read-only settlement observation for a local host retaining a proved caller-owned session receipt after restart. diff --git a/packages/coding-agent/docs/sdk.md b/packages/coding-agent/docs/sdk.md index dcbf977199e..599b1c8aea7 100644 --- a/packages/coding-agent/docs/sdk.md +++ b/packages/coding-agent/docs/sdk.md @@ -93,6 +93,26 @@ The contract proof contains only the feature/status, protocol identity, schema r Use `disposeOwnedSession({ timeoutMs })` when cleanup must be observable. Concurrent calls join one operation, and `timeoutMs` is one strict total deadline for reconnection, authoritative queries, completion, side-question aborts, and unsupported-peer finalization. Its fixed statuses are `completed`, `already_completed`, `replacement_settled`, `owner_mismatch`, `uncertain`, `transport_failure`, and `unsupported`; `uncertain` also reports whether the last authoritative state was `active` or `stopping`. `replacement_settled` means an authenticated supervisor with a different generation answered the read-only cleanup query with `settled` for the connection's previously proved opaque route. Cleanup never sends completion on a replacement or pending route without a current internal attach proof. Each strict cleanup request is transport-bound and is never replayed after reconnect. Public attachment proof remains absent throughout disposal. Results never return raw errors or environment identity. `dispose()` remains the legacy best-effort `Promise` API. +### Observing settlement after a host restart + +A local POSIX host retaining a prior `caller_owned_session_environment_cleanup_v1` +attachment proof may use the frozen SDK feature `owned_session_settlement_observation_v1` +and public `observeOwnedSessionSettlement({ agentDir, activeSessionId, contractProof })`. +Pass the exact canonical agent home and root route saved with that proof. This read-only +operation scans Prime's durable registration namespaces, including prior temporary socket +locations, without creating a daemon, claiming ownership, sending completion, or signaling +processes. It returns only the feature token and `settled`, `registered`, or `unavailable`. + +Only `settled` permits retirement of that exact legacy host receipt. A capable supervisor +persists registration before releasing its worker startup gate, retains it during recovery, +and removes it last after joining cleanup. This observation relies on that prior contract; +it is not a general orphan-process detector or authority for stock/descriptorless work, +copied state, or a different agent home. Missing, changing, malformed, oversized, aliased, +or nonprivate registries return `unavailable`. Existing registrations return `registered` +even if their socket and PID are gone. Retain quarantine in either case. Native Windows +is unsupported. Hosts must compare and remove their exact receipt atomically and must +continue using recovery-handle adoption for recoverable sessions. + ### Recoverable caller-owned daemon sessions Native detached-daemon hosts can opt into same-supervisor recovery with `recoverable_owned_session_adoption_v1`. The complete pre-create gate requires schema revision 30, the frozen package-root SDK tokens `recoverable_owned_session_adoption_v1` and `caller_owned_session_environment_cleanup_v1`, and connected hello offers for `daemon_recoverable_owned_session_adoption_v1`, `caller_owned_session_environment_cleanup_v1`, and `authoritative_owned_session_cleanup_v1`. If any proof is absent, select ACP before creating a native worker. This is a POSIX detached-daemon contract; it does not provide resident promotion, cross-host recovery, or recovery after supervisor process replacement. diff --git a/packages/coding-agent/package.json b/packages/coding-agent/package.json index 15593eb4287..91b7e541f96 100644 --- a/packages/coding-agent/package.json +++ b/packages/coding-agent/package.json @@ -38,8 +38,8 @@ "copy-assets": "shx mkdir -p dist/modes/interactive/theme && shx cp src/modes/interactive/theme/*.json dist/modes/interactive/theme/ && shx mkdir -p dist/modes/interactive/assets && shx cp src/modes/interactive/assets/*.png dist/modes/interactive/assets/ && shx mkdir -p dist/core/export-html/vendor && shx cp src/core/export-html/template.html src/core/export-html/template.css src/core/export-html/template.js dist/core/export-html/ && shx cp src/core/export-html/vendor/*.js dist/core/export-html/vendor/ && shx rm -rf dist/prime-agent-runtime && shx cp -r ../../prime-agent-runtime dist/prime-agent-runtime && shx rm -rf dist/skills && shx cp -r skills dist/skills", "copy-binary-assets": "shx cp package.json dist/ && shx cp README.md dist/ && shx cp CHANGELOG.md dist/ && shx mkdir -p dist/theme && shx cp src/modes/interactive/theme/*.json dist/theme/ && shx mkdir -p dist/assets && shx cp src/modes/interactive/assets/*.png dist/assets/ && shx mkdir -p dist/export-html/vendor && shx cp src/core/export-html/template.html dist/export-html/ && shx cp src/core/export-html/vendor/*.js dist/export-html/vendor/ && shx cp -r docs dist/ && shx cp -r examples dist/ && shx cp ../../node_modules/@silvia-odwyer/photon-node/photon_rs_bg.wasm dist/ && shx rm -rf dist/skills && shx cp -r skills dist/skills", "test": "vitest --run", - "test:ci": "tsx src/core/kernel/bootstrap-cli.ts && vitest --run --exclude test/daemon-supervisor-process.test.ts", - "test:process": "vitest --run test/daemon-supervisor-process.test.ts", + "test:ci": "tsx src/core/kernel/bootstrap-cli.ts && vitest --run --exclude test/daemon-supervisor-process.test.ts --exclude test/owned-session-settlement-process.test.ts", + "test:process": "vitest --run --no-file-parallelism test/daemon-supervisor-process.test.ts test/owned-session-settlement-process.test.ts", "test:process-stress": "vitest --run --tagsFilter process-stress test/daemon-supervisor-process.test.ts", "postinstall": "node postinstall.cjs", "prepublishOnly": "npm run clean && npm run build", diff --git a/packages/coding-agent/src/index.ts b/packages/coding-agent/src/index.ts index 61a2c27e81d..213304bd129 100644 --- a/packages/coding-agent/src/index.ts +++ b/packages/coding-agent/src/index.ts @@ -319,6 +319,11 @@ export { type RecoverableOwnedSessionCreateOptions, type RecoverableOwnedSessionCreation, } from "./modes/agent-connection/recoverable-owned-session.js"; +export { + OWNED_SESSION_SETTLEMENT_OBSERVATION_FEATURE, + type OwnedSessionSettlementObservation, + observeOwnedSessionSettlement, +} from "./modes/daemon/owned-session-settlement.js"; // Run modes for programmatic SDK usage export { ClientPromptStashStore, diff --git a/packages/coding-agent/src/modes/daemon/owned-session-settlement.ts b/packages/coding-agent/src/modes/daemon/owned-session-settlement.ts new file mode 100644 index 00000000000..0ebaddca02f --- /dev/null +++ b/packages/coding-agent/src/modes/daemon/owned-session-settlement.ts @@ -0,0 +1,160 @@ +import { createHash } from "node:crypto"; +import { constants } from "node:fs"; +import { lstat, open, readdir, realpath } from "node:fs/promises"; +import { isAbsolute, join } from "node:path"; +import { CALLER_OWNED_SESSION_ENVIRONMENT_CLEANUP_FEATURE } from "../../sdk-features.js"; +import type { DaemonOwnedSessionContractProof } from "../agent-connection/daemon-agent-connection.js"; +import type { DaemonWorkerDescriptor } from "./daemon-worker-protocol.js"; + +export const OWNED_SESSION_SETTLEMENT_OBSERVATION_FEATURE = "owned_session_settlement_observation_v1" as const; + +export interface OwnedSessionSettlementObservation { + readonly feature: typeof OWNED_SESSION_SETTLEMENT_OBSERVATION_FEATURE; + readonly status: "settled" | "registered" | "unavailable"; +} + +function validRegistration(value: unknown, scope: string): value is DaemonWorkerDescriptor { + if (!value || typeof value !== "object") return false; + const d = value as Partial; + return ( + (d.version === 1 || d.version === 2) && + typeof d.supervisorSocketPath === "string" && + isAbsolute(d.supervisorSocketPath) && + createHash("sha256").update(d.supervisorSocketPath).digest("hex").slice(0, 12) === scope && + typeof d.workerId === "string" && + d.workerId.length > 0 && + Number.isInteger(d.pid) && + (d.pid ?? 0) > 0 && + (d.processStartId === undefined || typeof d.processStartId === "string") && + (d.ownerClientId === undefined || typeof d.ownerClientId === "string") && + (d.callerOwnedEnvironmentContract === undefined || d.callerOwnedEnvironmentContract === true) && + typeof d.socketPath === "string" && + typeof d.authenticationToken === "string" && + typeof d.rootActiveSessionId === "string" && + d.rootActiveSessionId.length > 0 && + typeof d.createdAt === "string" && + typeof d.updatedAt === "string" && + Number.isInteger(d.consecutiveFailures) && + d.createCommand?.type === "create" + ); +} + +/** + * Read-only local-host recovery for a previously proved caller-owned root. + * Capable supervisors persist registration before releasing the worker startup gate, + * retain it across recovery, and remove it last after joining all cleanup. Inspect + * every socket namespace in the exact agent home: a legacy host may have lost its + * temporary socket path. This never adopts, completes, signals, or launches work. + * A proof from before the caller-owned contract cannot certify descriptorless work. + */ +export async function observeOwnedSessionSettlement(input: { + readonly agentDir: string; + readonly activeSessionId: string; + readonly contractProof: DaemonOwnedSessionContractProof; +}): Promise { + const result = (status: OwnedSessionSettlementObservation["status"]): OwnedSessionSettlementObservation => + Object.freeze({ feature: OWNED_SESSION_SETTLEMENT_OBSERVATION_FEATURE, status }); + const proof = input.contractProof; + if ( + !isAbsolute(input.agentDir) || + !input.activeSessionId || + input.activeSessionId.length > 256 || + proof?.feature !== CALLER_OWNED_SESSION_ENVIRONMENT_CLEANUP_FEATURE || + proof.status !== "attached" || + proof.daemon?.protocolName !== "prime-agent.daemon" || + !Number.isSafeInteger(proof.daemon.protocolVersion) || + proof.daemon.protocolVersion < 7 || + !Number.isSafeInteger(proof.daemon.schemaRevision) || + proof.daemon.schemaRevision < 0 || + !Number.isSafeInteger(proof.daemon.transportGeneration) || + proof.daemon.transportGeneration < 0 || + !proof.daemon.supervisorGeneration + ) + return result("unavailable"); + const uid = process.getuid?.(); + if (uid === undefined || process.platform === "win32") return result("unavailable"); + const deadline = Date.now() + 10_000; + let inspectedBytes = 0; + let inspectedFiles = 0; + try { + if ((await realpath(input.agentDir)) !== input.agentDir) return result("unavailable"); + const root = join(input.agentDir, "daemon-workers"); + const privateDirectory = async (path: string) => { + const info = await lstat(path); + if (!info.isDirectory() || info.isSymbolicLink() || info.uid !== uid || (info.mode & 0o077) !== 0) { + throw new Error("Unproved registry directory"); + } + return info; + }; + const rootIdentity = await privateDirectory(root); + const scopes = (await readdir(root)).sort(); + if (scopes.length > 2048) return result("unavailable"); + for (const scope of scopes) { + if (!/^[a-f0-9]{12}$/.test(scope) || Date.now() >= deadline) return result("unavailable"); + const directory = join(root, scope); + const identity = await privateDirectory(directory); + const names = (await readdir(directory)).sort(); + for (const name of names) { + if (!name.endsWith(".json")) continue; + if (++inspectedFiles > 16384 || Date.now() >= deadline) return result("unavailable"); + const file = await open( + join(directory, name), + constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK, + ); + try { + const before = await file.stat(); + inspectedBytes += before.size; + if ( + !before.isFile() || + before.uid !== uid || + (before.mode & 0o077) !== 0 || + before.size > 1024 * 1024 || + inspectedBytes > 64 * 1024 * 1024 + ) + return result("unavailable"); + const descriptor: unknown = JSON.parse( + await (async () => { + const buffer = Buffer.alloc(before.size + 1); + const { bytesRead } = await file.read(buffer, 0, buffer.length, 0); + if (bytesRead !== before.size) throw new Error("Changing registration"); + return buffer.subarray(0, bytesRead).toString("utf8"); + })(), + ); + const after = await file.stat(); + const linked = await lstat(join(directory, name)); + if ( + linked.isSymbolicLink() || + linked.dev !== before.dev || + linked.ino !== before.ino || + before.size !== after.size || + before.mtimeMs !== after.mtimeMs || + !validRegistration(descriptor, scope) + ) + return result("unavailable"); + if (descriptor.rootActiveSessionId === input.activeSessionId) return result("registered"); + } finally { + await file.close(); + } + } + const after = await privateDirectory(directory); + if ( + after.dev !== identity.dev || + after.ino !== identity.ino || + after.mtimeMs !== identity.mtimeMs || + JSON.stringify((await readdir(directory)).sort()) !== JSON.stringify(names) + ) + return result("unavailable"); + } + const after = await privateDirectory(root); + if ( + after.dev !== rootIdentity.dev || + after.ino !== rootIdentity.ino || + after.mtimeMs !== rootIdentity.mtimeMs || + JSON.stringify((await readdir(root)).sort()) !== JSON.stringify(scopes) + ) + return result("unavailable"); + return result(Date.now() >= deadline ? "unavailable" : "settled"); + } catch { + return result("unavailable"); + } +} diff --git a/packages/coding-agent/src/sdk-features.ts b/packages/coding-agent/src/sdk-features.ts index 423e57db49e..8fbb1bf0ae7 100644 --- a/packages/coding-agent/src/sdk-features.ts +++ b/packages/coding-agent/src/sdk-features.ts @@ -8,6 +8,7 @@ export const CALLER_OWNED_SESSION_ENVIRONMENT_CLEANUP_FEATURE = "caller_owned_se export const RECOVERABLE_OWNED_SESSION_ADOPTION_FEATURE = "recoverable_owned_session_adoption_v1" as const; export const PRIME_AGENT_SDK_FEATURES = Object.freeze([ + "owned_session_settlement_observation_v1", "bounded_daemon_ingress_v1", "negotiated_daemon_session_capabilities_v1", CALLER_OWNED_SESSION_ENVIRONMENT_CLEANUP_FEATURE, diff --git a/packages/coding-agent/test/daemon-client.test.ts b/packages/coding-agent/test/daemon-client.test.ts index ca87469a6b5..256f68ddf00 100644 --- a/packages/coding-agent/test/daemon-client.test.ts +++ b/packages/coding-agent/test/daemon-client.test.ts @@ -212,6 +212,7 @@ describe("DaemonClient", () => { it("exports the bounded-ingress SDK proof and validates finite byte limits", () => { const rootOptions: RootDaemonClientOptions = { maxInboundFrameBytes: 1 }; const rootFeatures: RootPrimeAgentSdkFeature[] = [ + "owned_session_settlement_observation_v1", "bounded_daemon_ingress_v1", "negotiated_daemon_session_capabilities_v1", "caller_owned_session_environment_cleanup_v1", diff --git a/packages/coding-agent/test/owned-session-settlement-process.test.ts b/packages/coding-agent/test/owned-session-settlement-process.test.ts new file mode 100644 index 00000000000..1089cb9f4f3 --- /dev/null +++ b/packages/coding-agent/test/owned-session-settlement-process.test.ts @@ -0,0 +1,120 @@ +import { spawn } from "node:child_process"; +import { once } from "node:events"; +import { watch } from "node:fs"; +import { mkdir, mkdtemp, realpath, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { expect, it } from "vitest"; +import { ENV_AGENT_DIR } from "../src/config.js"; +import { DaemonAgentConnection } from "../src/modes/agent-connection/daemon-agent-connection.js"; +import { DaemonClient } from "../src/modes/daemon/daemon-client.js"; +import { observeOwnedSessionSettlement } from "../src/modes/daemon/owned-session-settlement.js"; + +it.runIf(process.platform !== "win32")( + "matches real supervisor cleanup and remains authoritative after supervisor exit", + async () => { + const root = await realpath(await mkdtemp(join(tmpdir(), "prime-settlement-native-"))); + const agentDir = join(root, "agent"); + const socket = join(root, "d.sock"); + await mkdir(agentDir, { mode: 0o700 }); + const watcher = watch(root); + const ready = new Promise((resolveReady, reject) => { + watcher.on("change", (_event, name) => { + if (name?.toString() === "d.sock") resolveReady(); + }); + watcher.on("error", reject); + }); + const environment = Object.fromEntries( + Object.entries(process.env).flatMap(([name, value]) => + value !== undefined && + !name.startsWith("PRIME_AGENT_INTERNAL_") && + !name.startsWith("RLM_") && + !/TOKEN|KEY|SECRET|PASSWORD|CREDENTIAL|AUTH|COOKIE/i.test(name) + ? [[name, value]] + : [], + ), + ); + Object.assign(environment, { + HOME: root, + USERPROFILE: root, + [ENV_AGENT_DIR]: agentDir, + PI_OFFLINE: "1", + TSX_TSCONFIG_PATH: resolve(__dirname, "../../../tsconfig.json"), + }); + const child = spawn( + process.execPath, + [ + resolve(__dirname, "../../../node_modules/tsx/dist/cli.mjs"), + resolve(__dirname, "../src/cli.ts"), + "--mode", + "daemon", + "--daemon-socket", + socket, + "--offline", + ], + { cwd: root, env: environment, stdio: ["ignore", "pipe", "pipe"] }, + ); + let diagnostics = ""; + child.stdout.on("data", (chunk) => { + diagnostics += chunk.toString(); + }); + child.stderr.on("data", (chunk) => { + diagnostics += chunk.toString(); + }); + const exited = once(child, "exit"); + const client = new DaemonClient(socket); + try { + await Promise.race([ + ready, + exited.then(() => { + throw new Error(`Supervisor exited: ${diagnostics}`); + }), + ]); + watcher.close(); + await client.connect(10_000); + await client.waitForHello(10_000); + const config = { cwd: root, agentDir, noTools: true, noExtensions: true }; + const created = await client.request( + { + type: "create", + lifecycle: "client_owned", + noSession: true, + launchEnv: environment, + launchEnvMode: "replace", + config, + }, + 30_000, + ); + if (!created.success) throw new Error(created.error); + const summary = created.data as { activeSessionId: string }; + const connection = await DaemonAgentConnection.attach(client, summary.activeSessionId, { + ownedSession: true, + ownedSessionLaunchEnv: environment, + ownedSessionRecoveryConfig: config, + supportsExtensionUi: false, + }); + const contractProof = connection.getOwnedSessionContractProof(); + if (!contractProof) throw new Error("Missing actual owned attachment proof"); + const input = { agentDir, activeSessionId: summary.activeSessionId, contractProof }; + expect((await observeOwnedSessionSettlement(input)).status).toBe("registered"); + expect((await connection.disposeOwnedSession({ timeoutMs: 30_000 })).status).toBe("completed"); + // The live supervisor can still update registry metadata; join its exit before the stable scan. + const observer = new DaemonClient(socket); + await observer.connect(10_000); + try { + await observer.request({ type: "shutdown" }, 10_000); + } finally { + observer.close(); + } + await exited; + expect((await observeOwnedSessionSettlement(input)).status).toBe("settled"); + } finally { + watcher.close(); + client.close(); + if (child.exitCode === null && child.signalCode === null) child.kill("SIGTERM"); + await exited; + await rm(root, { recursive: true, force: true }); + } + }, + 90_000, +); diff --git a/packages/coding-agent/test/owned-session-settlement.test.ts b/packages/coding-agent/test/owned-session-settlement.test.ts new file mode 100644 index 00000000000..34ed185a6d5 --- /dev/null +++ b/packages/coding-agent/test/owned-session-settlement.test.ts @@ -0,0 +1,137 @@ +import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { chmod, mkdir, mkdtemp, realpath, rm, symlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import type { DaemonOwnedSessionContractProof } from "../src/modes/agent-connection/daemon-agent-connection.js"; +import { observeOwnedSessionSettlement } from "../src/modes/daemon/owned-session-settlement.js"; + +const roots: string[] = []; +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); +}); +const proof: DaemonOwnedSessionContractProof = { + feature: "caller_owned_session_environment_cleanup_v1", + status: "attached", + daemon: { + protocolName: "prime-agent.daemon", + protocolVersion: 7, + schemaRevision: 31, + supervisorGeneration: "previous-supervisor", + transportGeneration: 1, + }, +}; +const socket = "/private/prior-temp/daemon.sock"; +const scopeKey = (path: string) => createHash("sha256").update(path).digest("hex").slice(0, 12); +const registration = (id: string, supervisorSocketPath = socket) => ({ + version: 2, + rootActiveSessionId: id, + supervisorSocketPath, + workerId: "worker", + pid: 99999999, + socketPath: "/private/absent-worker.sock", + authenticationToken: "fixture", + createdAt: "2026-09-18", + updatedAt: "2026-09-18", + consecutiveFailures: 0, + createCommand: { type: "create" }, +}); +async function fixture() { + const agentDir = await realpath(await mkdtemp(join(tmpdir(), "prime-settlement-"))); + roots.push(agentDir); + const registry = join(agentDir, "daemon-workers"); + const scope = join(registry, scopeKey(socket)); + await mkdir(scope, { recursive: true, mode: 0o700 }); + const observe = () => + observeOwnedSessionSettlement({ agentDir, activeSessionId: "prior-root", contractProof: proof }); + const descriptor = async (id: string, name = "worker.json") => + writeFile(join(scope, name), JSON.stringify(registration(id)), { mode: 0o600 }); + return { agentDir, registry, scope, observe, descriptor }; +} + +describe.runIf(process.platform !== "win32")("previously proved caller-owned root settlement", () => { + it("proves absent registration across old socket scopes without mutating another worker", async () => { + const f = await fixture(); + await f.descriptor("another-root"); + expect(await f.observe()).toEqual({ feature: "owned_session_settlement_observation_v1", status: "settled" }); + }); + it("retains a matching durable registration even when its process and socket are absent", async () => { + const f = await fixture(); + await f.descriptor("prior-root"); + expect((await f.observe()).status).toBe("registered"); + }); + it("observes every socket namespace, including a prior temporary directory", async () => { + const f = await fixture(); + const other = join(f.registry, scopeKey("/private/older-temp/daemon.sock")); + await mkdir(other, { mode: 0o700 }); + await writeFile( + join(other, "old.json"), + JSON.stringify(registration("prior-root", "/private/older-temp/daemon.sock")), + { mode: 0o600 }, + ); + expect((await f.observe()).status).toBe("registered"); + }); + it("does not treat a missing registry as settlement", async () => { + const f = await fixture(); + await rm(f.registry, { recursive: true }); + expect((await f.observe()).status).toBe("unavailable"); + }); + it.each(["not json", "{}", '{"version":99,"rootActiveSessionId":"another-root"}'])( + "retains ambiguity for malformed registration %s", + async (content) => { + const f = await fixture(); + await writeFile(join(f.scope, "unknown.json"), content, { mode: 0o600 }); + expect((await f.observe()).status).toBe("unavailable"); + }, + ); + it("rejects an aliased home, registry scope, or descriptor", async () => { + const f = await fixture(); + const alias = `${f.agentDir}-alias`; + roots.push(alias); + await symlink(f.agentDir, alias); + expect( + (await observeOwnedSessionSettlement({ agentDir: alias, activeSessionId: "prior-root", contractProof: proof })) + .status, + ).toBe("unavailable"); + await symlink(f.scope, join(f.registry, "abcdef123456")); + expect((await f.observe()).status).toBe("unavailable"); + await rm(join(f.registry, "abcdef123456")); + await f.descriptor("another-root", "target"); + await symlink(join(f.scope, "target"), join(f.scope, "worker.json")); + expect((await f.observe()).status).toBe("unavailable"); + }); + it("rejects public registry and descriptor permissions", async () => { + const f = await fixture(); + await chmod(f.registry, 0o755); + expect((await f.observe()).status).toBe("unavailable"); + await chmod(f.registry, 0o700); + await f.descriptor("another-root"); + await chmod(join(f.scope, "worker.json"), 0o644); + expect((await f.observe()).status).toBe("unavailable"); + }); + it("rejects a FIFO registration without blocking on open", async () => { + const f = await fixture(); + execFileSync("mkfifo", [join(f.scope, "worker.json")]); + expect((await f.observe()).status).toBe("unavailable"); + }); + it("rejects a registration attributed to a different socket namespace", async () => { + const f = await fixture(); + await writeFile(join(f.scope, "worker.json"), JSON.stringify(registration("another-root", "/different.sock")), { + mode: 0o600, + }); + expect((await f.observe()).status).toBe("unavailable"); + }); + it("rejects an unproved attachment", async () => { + const f = await fixture(); + expect( + ( + await observeOwnedSessionSettlement({ + agentDir: f.agentDir, + activeSessionId: "prior-root", + contractProof: { ...proof, daemon: { ...proof.daemon, supervisorGeneration: "" } }, + }) + ).status, + ).toBe("unavailable"); + }); +}); diff --git a/scripts/pylon-prime-agent-release.test.mjs b/scripts/pylon-prime-agent-release.test.mjs index c14f62ca7c8..3d1650e48d9 100644 --- a/scripts/pylon-prime-agent-release.test.mjs +++ b/scripts/pylon-prime-agent-release.test.mjs @@ -325,7 +325,8 @@ test("requires canonical SHA-512 registry integrity for every locked package", ( test("smokes the exact caller-owned session SDK contract", () => { assert.deepEqual([...PYLON_RELEASE_EXPECTED_SDK_FEATURES], [ - "bounded_daemon_ingress_v1", + "owned_session_settlement_observation_v1", + "bounded_daemon_ingress_v1", "negotiated_daemon_session_capabilities_v1", "caller_owned_session_environment_cleanup_v1", "recoverable_owned_session_adoption_v1", diff --git a/scripts/smoke-pylon-prime-agent-release.mjs b/scripts/smoke-pylon-prime-agent-release.mjs index 6ae3fdf5f1c..b547fd8dad3 100644 --- a/scripts/smoke-pylon-prime-agent-release.mjs +++ b/scripts/smoke-pylon-prime-agent-release.mjs @@ -19,6 +19,7 @@ const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); const defaultArtifacts = join(root, ".npm", "pylon-release", "artifacts"); const MAX_DIAGNOSTICS = 64 * 1024; export const PYLON_RELEASE_EXPECTED_SDK_FEATURES = Object.freeze([ + "owned_session_settlement_observation_v1", "bounded_daemon_ingress_v1", "negotiated_daemon_session_capabilities_v1", "caller_owned_session_environment_cleanup_v1", @@ -330,6 +331,7 @@ if (${JSON.stringify(standalone)}) { const expected = ${JSON.stringify(PYLON_RELEASE_EXPECTED_SDK_FEATURES)}; if (!Object.isFrozen(sdk.PRIME_AGENT_SDK_FEATURES)) throw new Error("SDK feature tokens are not frozen."); if (JSON.stringify([...sdk.PRIME_AGENT_SDK_FEATURES]) !== JSON.stringify(expected)) throw new Error("Unexpected SDK feature tokens."); +if (typeof sdk.observeOwnedSessionSettlement !== "function") throw new Error("Missing public settlement observer."); if (typeof sdk.DaemonClient !== "function" || typeof sdk.DaemonAgentConnection !== "function") throw new Error("Missing daemon SDK constructors."); console.log(JSON.stringify({ features: [...sdk.PRIME_AGENT_SDK_FEATURES] })); `, @@ -353,7 +355,7 @@ async function smokePosixDaemon({ tempRoot, probesDir, cliEntry, fixture, expect const probePath = join(probesDir, "daemon-probe.mjs"); writeFileSync( probePath, - `${staticSdkImport()}import { writeFileSync } from "node:fs"; + `${staticSdkImport()}import { writeFileSync, realpathSync } from "node:fs"; const [socketPath, projectDir, agentDir, sessionDir, workerReceiptPath, expectedBuildId] = process.argv.slice(2); const expected = ${JSON.stringify(PYLON_RELEASE_EXPECTED_SDK_FEATURES)}; if (!Object.isFrozen(sdk.PRIME_AGENT_SDK_FEATURES) || JSON.stringify([...sdk.PRIME_AGENT_SDK_FEATURES]) !== JSON.stringify(expected)) throw new Error("Unexpected SDK feature contract."); @@ -383,6 +385,7 @@ async function connectEventually() { let client; let connection; let activeSessionId; +let ownedProof; let receipt = {}; let failure; try { @@ -442,11 +445,13 @@ try { snapshotTimeoutMs: 10_000 }), 20_000, "Daemon attach"); if (!connection.supportsNegotiatedCapability("correlated_prompt_lifecycle_v1")) throw new Error("Post-attach negotiated capability was not proved."); - const ownedProof = connection.getOwnedSessionContractProof(); + ownedProof = connection.getOwnedSessionContractProof(); if (ownedProof?.feature !== "caller_owned_session_environment_cleanup_v1" || ownedProof.status !== "attached") { throw new Error("Post-attach caller-owned environment contract was not proved."); } - receipt = { negotiated: true, ownedContract: true, activeSessionId, runtimeBuildId: client.hello.runtime.buildId }; + const registered = await sdk.observeOwnedSessionSettlement({ agentDir: realpathSync(agentDir), activeSessionId, contractProof: ownedProof }); + if (registered.status !== "registered") throw new Error("Live owned worker was not durably registered."); + receipt = { negotiated: true, ownedContract: true, activeSessionId, ownedProof, runtimeBuildId: client.hello.runtime.buildId }; } catch (error) { failure = error; } finally { @@ -552,6 +557,17 @@ console.log(JSON.stringify({ connected })); if (daemon.exitCode !== 0 || daemonOutput.overflow || daemonOutput.error) { throw new Error(`Installed daemon exited unexpectedly.\n${daemonOutput.stderr || daemonOutput.stdout}`); } + // Join the captured supervisor before requiring a stable durable-registry observation. + const settlementProbe = join(probesDir, "settlement-probe.mjs"); + writeFileSync(settlementProbe, `${staticSdkImport()}import { realpathSync } from "node:fs"; +const receipt = ${JSON.stringify(receipt)}; +const result = await sdk.observeOwnedSessionSettlement({ agentDir: realpathSync(${JSON.stringify(fixture.agentDir)}), activeSessionId: receipt.activeSessionId, contractProof: receipt.ownedProof }); +if (result.status !== "settled") throw new Error("Owned worker settlement was not observed after supervisor exit: " + result.status); +`); + const settlement = await collectChild(spawn(process.execPath, [settlementProbe], { + cwd: probesDir, env: fixture.env, stdio: ["ignore", "pipe", "pipe"], shell: false, + }), 15_000); + if (settlement.status !== 0) throw new Error(`Installed settlement observation failed.\n${settlement.stderr || settlement.stdout}`); } catch (error) { failure = error; } finally {