diff --git a/plugins/codex-pi-coordination/.codex-plugin/plugin.json b/plugins/codex-pi-coordination/.codex-plugin/plugin.json index be15d05..c137996 100644 --- a/plugins/codex-pi-coordination/.codex-plugin/plugin.json +++ b/plugins/codex-pi-coordination/.codex-plugin/plugin.json @@ -1,15 +1,15 @@ { "name": "codex-pi-coordination", - "version": "0.2.0", - "description": "Coordinate bounded implementation, research, review and validation tasks between Codex and Pi inside NVIDIA OpenShell.", + "version": "0.3.0", + "description": "Coordinate bounded tasks, saved Pi conversations and model capability discovery inside NVIDIA OpenShell.", "author": { "name": "Fakoli", "url": "https://github.com/fakoli" }, "interface": { "displayName": "Codex Pi Coordination", - "shortDescription": "Delegate scoped work to Pi and verify its return.", - "longDescription": "Codex owns task scope and acceptance. Pi works in a disposable OpenShell workspace and returns bounded artifacts, while a stdlib runner records actual command results and managed cleanup.", + "shortDescription": "Run scoped Pi tasks and continue saved work.", + "longDescription": "Codex owns scope, integration and acceptance. Pi executes fresh assignments in an owned OpenShell sandbox, optionally continuing a verified saved conversation. The runner retains bounded artifacts, actual checks and managed cleanup.", "developerName": "Fakoli", "category": "Productivity", "capabilities": [ diff --git a/plugins/codex-pi-coordination/README.md b/plugins/codex-pi-coordination/README.md index cd37d4c..600abde 100644 --- a/plugins/codex-pi-coordination/README.md +++ b/plugins/codex-pi-coordination/README.md @@ -26,8 +26,43 @@ Version-2 tasks may add `run_options`: an exact `provider`/`model` pair, `thinking` alone, or both. Omitted options inherit the profile. `auto`, `dynamic` and the literal `default` are refused; use omission for Default. Unsupported or silently clamped selections fail before the task prompt, without fallback. -Version-1 task inputs remain readable. All new runs use bounded native RPC with -`--no-session`; saved-session continuation remains future work (P1b). +Version-1 task inputs remain readable. Ordinary runs retain bounded native RPC +with `--no-session`. To keep one official Pi conversation across fresh, stopped +worker processes, use saved Run and Continue: + +```sh +python3 scripts/coordinate.py run first-task.json --save-session --output /private/evidence/first-run +``` + +Inspect the first return, integrate its approved changes through the repository +workflow, and commit the source for a new task manifest. Then continue from the +verified prior output with that new assignment and revision: + +```sh +python3 scripts/coordinate.py continue next-task.json --from /private/evidence/first-run --output /private/evidence/next-run +``` + +Saved runs require an explicit committed repository source. Continue preserves +the exact official session file, ID and workspace path, while each dispatch gets +fresh scope, options, budgets and artifacts. It checks the prior session hash +and history prefix and every workspace file/directory mode before switching +source. Stale, duplicate, missing or drifted checkpoints refuse before Pi starts; +the managed owner may start only to inspect that remote state. No latest-session +search, live attachment or silent fresh-session fallback occurs. Public task +versions 1/2 are unchanged; saved dispatches use native version 3. + +For one exact model's thinking choices, pair both selectors: + +```sh +python3 scripts/coordinate.py capabilities --provider configured-provider --model exact-model-id --output /private/evidence/selected-capabilities +``` + +This native version-3 metadata operation may select that model in its ephemeral +child, but sends no thinking setter, prompt, tool call or extension. It reports +the observed levels/thinking and profile-default compatibility. An unsupported +default does not block discovery; Run and Continue still require a supported +explicit or inherited thinking level. Omit all run options for the configured +default; capability discovery is optional, never a prerequisite for Default. See the [skill](skills/codex-pi-coordination/SKILL.md) and [task/profile contract](skills/codex-pi-coordination/references/task-contract.md). @@ -38,7 +73,7 @@ The extension provides `coordination_status`, `coordination_handoff` and `/coordination-status`. File tools stay inside the assigned workspace, writes name exact files, and tool/turn budgets stop further work. Declared verification argv runs after Pi exits. Task policy is not an OS sandbox: OpenShell remains -the isolation and lifecycle owner. Selection is confined to the ephemeral Pi +the isolation and lifecycle owner. Selection is confined to the dispatched Pi child; global provider/model settings stay unchanged. No background service, recursive Codex launch or automatic patch application is installed. @@ -52,7 +87,8 @@ evidence outside public plugin source. On execution failure, nonzero worker exit or timeout, the runner immediately enters managed OpenShell cleanup: verify identity, stop and record the readback. -It skips artifact download. Recover the latest failed run after confirmed stopped +It skips artifact download. Recover a saved failure, or the latest ephemeral +failure, after confirmed stopped custody using the same private profile and lock root: ```sh @@ -65,6 +101,25 @@ the bound results, and stops that instance. It runs no model or checks. `recovered_partial` preserves missing terminal results as unknown. Task delivery remains invalid and acceptance is not granted. Unknown stop blocks further work until supported `reconcile`; the original failed receipt is never rewritten. +For saved runs, recovery also reports `conversation_valid` separately. Failed +checks can leave a valid advanced conversation only when recovery verifies its +terminal session, workspace and stopped custody. Continue must reference that +valid recovery output with a new task; delivery remains failed. + +Use `reconcile --from FAILED_RUN --output NEW_DIRECTORY` for a saved workspace +transition. It can certify the exact unchanged prior tree and archive its +matching pending intent. A switched-new tree without verified terminal model +evidence remains unavailable for continuation; mixed or unknown state stays +held. The same command can inspect a successful saved run after an intervening +metadata or refused stale dispatch: it returns a fresh terminal checkpoint +readback without Pi or checks. `recover` remains failed-run-only, and inspection +still reports `delivery_valid: false`. It never restores files, rolls back a workspace, rewrites history or +replays a prompt. The existing no-argument `reconcile` only records independently +confirmed stopped owner custody. + +Sessions are limited to 16 MiB, checkpoint/control JSON to 1 MiB, and retained +remote material to an observed 1 GiB limit. These are checked bounds, not a hard +filesystem quota; overflow refuses further work without pruning prior runs. The native download has a timeout and post-download file/byte checks, not a hard pre-download storage quota. Use only an owner-qualified idle runtime. @@ -76,8 +131,10 @@ node --test tests/extension.test.mjs ``` These synthetic checks run in repository CI without a model or OpenShell -runtime. Native loading and real model task evidence require separate runtime -validation. +runtime. The saved two-edit journey and selected-model query still require separate +qualification through the installed OpenShell command. Anvil CLI/web admission, +current claims, integration, native checkout proofs and final approval also +require their own journey checks; plugin sandbox checks do not satisfy them. API reference: [Pi extension contract](https://github.com/earendil-works/pi/blob/v0.87.1/packages/coding-agent/docs/extensions.md). Anvil and ship-loop continue to own their scale and delivery workflows. diff --git a/plugins/codex-pi-coordination/extensions/coordination.js b/plugins/codex-pi-coordination/extensions/coordination.js index 3c1247b..18df00d 100644 --- a/plugins/codex-pi-coordination/extensions/coordination.js +++ b/plugins/codex-pi-coordination/extensions/coordination.js @@ -22,6 +22,7 @@ function boundedString(value, name, maximum = 16000) { function relativeFile(value) { boundedString(value, "relative file", 1024); + if (Buffer.from(value, "utf8").toString("utf8") !== value) fail("invalid_task", "Relative file contains invalid Unicode"); if (path.isAbsolute(value) || value.includes("\\") || /[\u00A0\u2000-\u200A\u202F\u205F\u3000]/.test(value) || value.split("/").some((part) => !part || part === "." || part === "..")) { fail("invalid_task", "File paths must be normalized workspace-relative paths"); } @@ -68,7 +69,7 @@ export function loadTask(taskPath, cwd) { fs.closeSync(descriptor); } const task = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(raw)); - if (!task || typeof task !== "object" || Array.isArray(task) || ![1, 2].includes(task.version) || !taskKinds.has(task.kind)) { + if (!task || typeof task !== "object" || Array.isArray(task) || ![1, 2, 3].includes(task.version) || !taskKinds.has(task.kind)) { fail("invalid_task", "Expected a supported versioned coordination task and kind"); } for (const key of ["run_id", "task_id"]) { @@ -79,7 +80,7 @@ export function loadTask(taskPath, cwd) { if (pattern.exec(value)?.[0] !== value) fail("invalid_task", `Invalid ${key}`); } if (task.version === 1 && "run_options" in task) fail("invalid_task", "Version 1 cannot contain run_options"); - if (task.version === 2) { + if ([2, 3].includes(task.version)) { const options = task.run_options; const levels = ["off", "minimal", "low", "medium", "high", "xhigh", "max"]; const identifierPattern = "[A-Za-z0-9][A-Za-z0-9_.:/-]{0,255}"; @@ -88,7 +89,7 @@ export function loadTask(taskPath, cwd) { // Each component may contain slashes; only the exact runtime catalog picks a pair. const qualifiedDefault = (value) => matchesIdentifier(value, `${identifierPattern}/${identifierPattern}`); if (!options || typeof options !== "object" || Array.isArray(options) || Object.keys(options).some((key) => !["provider", "model", "thinking"].includes(key)) || (("provider" in options) !== ("model" in options)) || ("provider" in options && (!identifier(options.provider) || !identifier(options.model))) || ("thinking" in options && !levels.includes(options.thinking))) fail("invalid_task", "Invalid version 2 run options"); - if (task.operation !== "run" || !task.runtime_defaults || Object.keys(task.runtime_defaults).sort().join(",") !== "model,thinking" || !qualifiedDefault(task.runtime_defaults.model) || !levels.includes(task.runtime_defaults.thinking)) fail("invalid_task", "Invalid version 2 runtime defaults"); + if (!(task.version === 2 ? task.operation === "run" : ["run", "continue"].includes(task.operation)) || !task.runtime_defaults || Object.keys(task.runtime_defaults).sort().join(",") !== "model,thinking" || !qualifiedDefault(task.runtime_defaults.model) || !levels.includes(task.runtime_defaults.thinking)) fail("invalid_task", "Invalid versioned runtime defaults"); } boundedString(task.instructions, "instructions", 48000); for (const key of ["workspace", "output_directory"]) { @@ -101,6 +102,16 @@ export function loadTask(taskPath, cwd) { if (contains(task.workspace, fs.realpathSync(taskPath)) || contains(task.workspace, task.output_directory) || contains(task.output_directory, task.workspace)) { fail("invalid_task", "Task and output controls must be outside the workspace; output must not contain it"); } + if (task.version === 3) { + const session = task.session; + if (!session || Object.keys(session).sort().join(",") !== "conversation_id,directory,file,prior,prior_sha256" || typeof session.conversation_id !== "string" || /^[0-9a-f]{32}$/.exec(session.conversation_id)?.[0] !== session.conversation_id) fail("invalid_task", "Invalid saved conversation descriptor"); + const dispatch = path.dirname(task.output_directory); + const directory = path.join(path.dirname(dispatch), "conversations", session.conversation_id); + if (path.basename(dispatch) !== task.run_id || session.directory !== directory || session.file !== path.join(directory, "session.jsonl") || task.workspace !== path.join(directory, "workspace")) fail("invalid_task", "Saved paths differ from owned dispatch"); + if (task.operation === "run" ? session.prior !== null || session.prior_sha256 !== null || session.conversation_id !== task.run_id : !session.prior || session.prior.conversation_id !== session.conversation_id || session.prior.run_id === task.run_id || typeof session.prior_sha256 !== "string" || /^[0-9a-f]{64}$/.exec(session.prior_sha256)?.[0] !== session.prior_sha256) fail("invalid_task", "Invalid previous saved dispatch"); + noSymlinks(path.dirname(dispatch), directory, false); + noSymlinks(directory, session.file, task.operation === "run"); + } if (!Array.isArray(task.allowed_tools) || task.allowed_tools.length > nativeTools.size || new Set(task.allowed_tools).size !== task.allowed_tools.length || task.allowed_tools.some((tool) => !nativeTools.has(tool))) { fail("invalid_task", "allowed_tools must contain unique supported native tools; shell execution is not supported"); } @@ -129,6 +140,14 @@ export function checkToolPath(task, toolName, input) { return candidate; } +function savedSessionIdentity(task, ctx) { + const manager = ctx.sessionManager; + const header = manager?.getHeader(); + const identity = { id: manager?.getSessionId(), file: manager?.getSessionFile(), cwd: manager?.getCwd(), version: header?.version }; + if (identity.version !== 3 || typeof identity.id !== "string" || /^[A-Za-z0-9_.-]{1,128}$/.exec(identity.id)?.[0] !== identity.id || identity.file !== task.session.file || identity.cwd !== task.workspace || header?.type !== "session" || header.id !== identity.id || header.cwd !== task.workspace || task.session.prior && identity.id !== task.session.prior.session?.id) fail("session_mismatch", "Official Pi session does not match the current saved assignment"); + return identity; +} + function toolResult(value) { return { content: [{ type: "text", text: JSON.stringify(value) }], details: value }; } @@ -158,8 +177,9 @@ export default function coordinationExtension(pi) { let turns = 0; let handedOff = false; let configurationRecorded = false; + let savedIdentity; const requested = () => pi.getFlag("coordination-task"); - const status = () => ({ active: Boolean(loaded), run_id: loaded?.task.run_id, task_id: loaded?.task.task_id, task_sha256: loaded?.taskSha256, tool_calls: toolCalls, turns, handed_off: handedOff, failure }); + const status = () => ({ active: Boolean(loaded), run_id: loaded?.task.run_id, task_id: loaded?.task.task_id, task_sha256: loaded?.taskSha256, tool_calls: toolCalls, turns, handed_off: handedOff, failure, ...(savedIdentity ? { session: savedIdentity } : {}) }); const record = (type, fields = {}) => { if (eventDescriptor !== undefined) fs.writeSync(eventDescriptor, JSON.stringify({ type, at: new Date().toISOString(), ...status(), ...fields }) + "\n"); }; @@ -211,7 +231,10 @@ export default function coordinationExtension(pi) { return; } try { + if (loaded) fail("task_reloaded", "A fresh dispatch requires a fresh Pi process"); loaded = loadTask(requested(), ctx.cwd); + toolCalls = 0; turns = 0; handedOff = false; configurationRecorded = false; + if (loaded.task.version === 3) savedIdentity = savedSessionIdentity(loaded.task, ctx); eventDescriptor = fs.openSync(path.join(loaded.task.output_directory, "extension-events.jsonl"), "wx", 0o600); const requiredTools = [...loaded.task.allowed_tools, ...coordinationTools]; pi.setActiveTools(requiredTools); @@ -230,7 +253,15 @@ export default function coordinationExtension(pi) { stop(ctx, "task_unavailable", "Coordination task is unavailable or already handed off"); return; } - if (loaded.task.version === 2 && !configurationRecorded) { + if (loaded.task.version === 3) { + try { + if (JSON.stringify(savedSessionIdentity(loaded.task, ctx)) !== JSON.stringify(savedIdentity)) fail("session_mismatch", "Saved session changed before prompt"); + } catch (error) { + stop(ctx, error.code ?? "session_mismatch", error.message); + return; + } + } + if ([2, 3].includes(loaded.task.version) && !configurationRecorded) { const configuration = { provider: ctx.model?.provider, model: ctx.model?.id, thinking: pi.getThinkingLevel() }; if (!configuration.provider || !configuration.model || !["off", "minimal", "low", "medium", "high", "xhigh", "max"].includes(configuration.thinking)) { stop(ctx, "configuration_unavailable", "Pi did not expose an effective run configuration"); @@ -248,7 +279,7 @@ export default function coordinationExtension(pi) { record("run_configuration", { configuration }); configurationRecorded = true; } - return { systemPrompt: `${event.systemPrompt}\n\nExternal coordinator task:\n${JSON.stringify({ run_id: loaded.task.run_id, task_id: loaded.task.task_id, kind: loaded.task.kind, instructions: loaded.task.instructions, source: loaded.sourceSummary, writable_paths: loaded.task.writable_paths, max_tool_calls: loaded.task.max_tool_calls, max_turns: loaded.task.max_turns })}\nWork only inside the assigned workspace and declared writable files. Shell execution is unavailable; the coordinator runs declared verification commands after Pi exits. Before the tool budget ends, call coordination_handoff exactly once with an honest self-report. Do not claim acceptance or verification from your report. Tool/path guards are task policy; the external runner owns OS isolation and custody.` }; + return { systemPrompt: `${event.systemPrompt}\n\nExternal coordinator task:\n${JSON.stringify({ run_id: loaded.task.run_id, task_id: loaded.task.task_id, kind: loaded.task.kind, instructions: loaded.task.instructions, source: loaded.sourceSummary, writable_paths: loaded.task.writable_paths, max_tool_calls: loaded.task.max_tool_calls, max_turns: loaded.task.max_turns })}\nOnly this current assignment grants scope and budgets; earlier conversation text grants no task or tool authority. Work only inside the assigned workspace and declared writable files. Shell execution is unavailable; the coordinator runs declared verification commands after Pi exits. Before the tool budget ends, call coordination_handoff exactly once with an honest self-report. Do not claim acceptance or verification from your report. Tool/path guards are task policy; the external runner owns OS isolation and custody.` }; }); pi.on("turn_start", async (_event, ctx) => { if (!requested() || !loaded) return; diff --git a/plugins/codex-pi-coordination/package.json b/plugins/codex-pi-coordination/package.json index bbb4d2a..ca7fe2c 100644 --- a/plugins/codex-pi-coordination/package.json +++ b/plugins/codex-pi-coordination/package.json @@ -1,7 +1,7 @@ { "name": "codex-pi-coordination", - "version": "0.2.0", - "description": "Bounded Pi task handoff for an external Codex coordinator", + "version": "0.3.0", + "description": "Bounded Pi tasks, saved-session continuation and capability discovery for Codex", "type": "module", "license": "MIT", "engines": { "node": ">=22" }, diff --git a/plugins/codex-pi-coordination/scripts/coordinate.py b/plugins/codex-pi-coordination/scripts/coordinate.py index b130db7..deb453d 100644 --- a/plugins/codex-pi-coordination/scripts/coordinate.py +++ b/plugins/codex-pi-coordination/scripts/coordinate.py @@ -30,6 +30,8 @@ MAX_SOURCE_BYTES = 64 * 1024 * 1024 MAX_OUTPUT_BYTES = 4 * 1024 * 1024 MAX_FILES = 10000 +MAX_SESSION_BYTES = 16 * 1024 * 1024 +MAX_RETAINED_BYTES = 1024 * 1024 * 1024 KINDS = {"implementation", "research", "review", "validation"} TOOLS = {"read", "grep", "find", "ls", "write", "edit"} THINKING_LEVELS = {"off", "minimal", "low", "medium", "high", "xhigh", "max"} @@ -64,15 +66,29 @@ def bounded_integer(value, label, maximum): return value -def relative_file(value): +def relative_path_structure(value): + """Validate spelling and safety without charging a transport namespace.""" if not isinstance(value, str) or not value or "\\" in value or "\x00" in value: raise ValueError("Expected a relative file path") + try: + value.encode("utf-8") + except UnicodeEncodeError: + raise ValueError("Relative file path contains invalid Unicode") from None + if re.search(r"[\u00A0\u2000-\u200A\u202F\u205F\u3000]", value): + raise ValueError("Relative file path requires Unicode-space normalization") path = PurePosixPath(value) if value == "." or path.is_absolute() or any(p in ("..", ".git") for p in path.parts) or str(path) != value: raise ValueError("Unsafe relative file path") return value +def relative_file(value): + value = relative_path_structure(value) + if len(value.encode("utf-16-le")) // 2 > 1024: + raise ValueError("Relative file path exceeds native bounds") + return value + + def validate_task(task): required = {"version", "task_id", "kind", "instructions", "writable_paths", "checks"} optional = {"repository", "revision", "max_tool_calls", "max_turns", "wall_seconds"} @@ -132,14 +148,14 @@ def validate_run_options(options): def safe_archive_files(raw): - """Git archives are data; reject links, devices, duplicates and traversal.""" + """Validate transport members; callers apply the native workspace limit.""" files, total = {}, 0 with tarfile.open(fileobj=io.BytesIO(raw)) as archive: for item in archive: if item.isdir(): - relative_file(item.name.rstrip("/")) + relative_path_structure(item.name.rstrip("/")) continue - name = relative_file(item.name) + name = relative_path_structure(item.name) total += item.size if not item.isfile() or name in files or total > MAX_SOURCE_BYTES or len(files) >= MAX_FILES: raise ValueError("Source archive exceeds bounds or contains unsafe members") @@ -165,7 +181,7 @@ def frozen_source(task): raw = subprocess.check_output(["git", "archive", "--format=tar", commit], cwd=repository, timeout=60) if len(raw) > MAX_SOURCE_BYTES + 16 * 1024 * 1024: raise ValueError("Source archive exceeds bounds") - files = safe_archive_files(raw) + files = {relative_file(name): data for name, data in safe_archive_files(raw).items()} with tarfile.open(fileobj=io.BytesIO(raw)) as archive: modes = {m.name: 0o755 if m.mode & 0o111 else 0o644 for m in archive if m.isfile()} return files, {"kind": "git", "commit": commit, "files": {p: digest(b) for p, b in files.items()}, "modes": modes} @@ -188,18 +204,278 @@ def snapshot(root): return files -def execute_to_log(argv, cwd, log, timeout, *, remote_owner=False, env=None): +def private_control_bytes(value): + raw = (json.dumps(value, sort_keys=True, ensure_ascii=True, separators=(",", ":")) + "\n").encode() + if len(raw) > 1024 * 1024: + raise ValueError("Conversation control exceeds 1 MiB") + return raw + + +def write_private_control(path, value): + raw = private_control_bytes(value) + descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o600) + with os.fdopen(descriptor, "wb") as stream: + stream.write(raw) + stream.flush() + os.fsync(stream.fileno()) + + +def refuse_path_links(path): + path = Path(path) + if not path.is_absolute(): + raise ValueError("Conversation paths must be absolute") + for parent in (path, *path.parents): + if parent.is_symlink(): + raise ValueError("Conversation path traverses a symbolic link") + + +def workspace_manifest(workspace): + refuse_path_links(workspace) + files = snapshot(workspace) + directories = {".": stat.S_IMODE(Path(workspace).stat().st_mode)} + for path in Path(workspace).rglob("*"): + if path.is_dir(): + directories[relative_file(path.relative_to(workspace).as_posix())] = stat.S_IMODE(path.stat().st_mode) + result = {"files": {name: {"sha256": digest(data), "mode": stat.S_IMODE((Path(workspace) / name).stat().st_mode)} for name, data in files.items()}, "directories": directories} + if len(directories) > MAX_FILES or any(mode > 0o777 for mode in directories.values()) or any(value["mode"] > 0o777 for value in result["files"].values()): + raise ValueError("Workspace directory or permission bounds exceeded") + private_control_bytes(result) + return result + + +def retained_storage_guard(parent): + refuse_path_links(parent) + total = 0 + for path in Path(parent).rglob("*"): + if path.is_symlink(): + raise ValueError("Retained material contains a symbolic link") + mode = path.stat().st_mode + if stat.S_ISREG(mode): + total += path.stat().st_size + elif not stat.S_ISDIR(mode): + raise ValueError("Retained material is not regular") + if total > MAX_RETAINED_BYTES: + raise ValueError("Retained material exceeds 1 GiB") + return total + + +def saved_session_snapshot(path, workspace, *, expected=None, prefix=None): + refuse_path_links(path) + descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)) + with os.fdopen(descriptor, "rb") as stream: + before = os.fstat(stream.fileno()) + if not stat.S_ISREG(before.st_mode) or not 0 < before.st_size <= MAX_SESSION_BYTES: + raise ValueError("Session must be a nonempty bounded regular file") + raw = stream.read(MAX_SESSION_BYTES + 1) + after = os.fstat(stream.fileno()) + if len(raw) != before.st_size or before.st_size != after.st_size or before.st_mtime_ns != after.st_mtime_ns or not raw.endswith(b"\n"): + raise ValueError("Session changed while reading or has an incomplete tail") + lines = raw[:-1].split(b"\n") + entries = [json.loads(line.decode("utf-8")) for line in lines] + header = entries[0] + if not isinstance(header, dict) or header.get("type") != "session" or header.get("version") != 3 or not isinstance(header.get("id"), str) or not re.fullmatch(r"[A-Za-z0-9_.-]{1,128}", header["id"]) or header.get("cwd") != str(workspace): + raise ValueError("Session header identity, version or cwd differs") + identifiers = set() + for entry in entries[1:]: + if not isinstance(entry, dict) or not isinstance(entry.get("type"), str) or entry["type"] == "session" or not isinstance(entry.get("id"), str) or not entry["id"] or entry["id"] in identifiers or "parentId" not in entry or entry["parentId"] is not None and entry["parentId"] not in identifiers: + raise ValueError("Session contains an invalid or incomplete entry") + identifiers.add(entry["id"]) + if not any(entry.get("type") == "message" and isinstance(entry.get("message"), dict) and entry["message"].get("role") == "assistant" for entry in entries[1:]): + raise ValueError("Saved session has no persisted assistant history") + result = {"id": header["id"], "file": str(path), "cwd": str(workspace), "bytes": len(raw), "sha256": digest(raw), "header_sha256": digest(lines[0])} + if expected is not None and result != expected: + raise ValueError("Session bytes or identity changed since checkpoint") + if prefix is not None and (len(raw) < prefix["bytes"] or digest(raw[:prefix["bytes"]]) != prefix["sha256"] or any(result[key] != prefix[key] for key in ("id", "file", "cwd", "header_sha256"))): + raise ValueError("Session replaced or rewrote its prior history") + return result + + +def saved_descriptor(task): + if task.get("version") != 3 or task.get("operation") not in {"run", "continue"}: + raise ValueError("Expected saved version 3 task") + session = task.get("session") + if not isinstance(session, dict) or set(session) != {"conversation_id", "directory", "file", "prior", "prior_sha256"} or not re.fullmatch(r"[0-9a-f]{32}", str(session["conversation_id"])): + raise ValueError("Invalid saved conversation descriptor") + dispatch = Path(task["output_directory"]).parent + directory = dispatch.parent / "conversations" / session["conversation_id"] + if not dispatch.is_absolute() or dispatch.name != task["run_id"] or session["directory"] != str(directory) or session["file"] != str(directory / "session.jsonl") or task["workspace"] != str(directory / "workspace"): + raise ValueError("Saved conversation paths differ from the owned dispatch") + if task["operation"] == "run": + if session["prior"] is not None or session["prior_sha256"] is not None or session["conversation_id"] != task["run_id"]: + raise ValueError("New saved run must reserve its own fresh conversation") + else: + prior = session["prior"] + if not isinstance(prior, dict) or prior.get("conversation_id") != session["conversation_id"] or not re.fullmatch(r"[0-9a-f]{32}", str(prior.get("run_id"))) or prior["run_id"] == task["run_id"] or digest(private_control_bytes(prior)) != session["prior_sha256"]: + raise ValueError("Invalid prior conversation checkpoint binding") + for path in (directory, dispatch, Path(task["workspace"]), Path(session["file"])): + refuse_path_links(path) + return session + + +def validate_native_task(task): + if not isinstance(task, dict) or type(task.get("version")) is not int or task["version"] not in (1, 2, 3): + raise ValueError("Unknown native task version") + if task["version"] != 3: + return + fields = {"version", "run_id", "task_id", "kind", "instructions", "workspace", "output_directory", "writable_paths", "allowed_tools", "max_tool_calls", "max_turns", "source", "checks", "operation", "run_options", "runtime_defaults"} + metadata = task.get("operation") == "capabilities_selected" + if set(task) != fields | ({"selected_model"} if metadata else {"session"}): + raise ValueError("Native version 3 fields differ from its explicit variant") + public = {key: task[key] for key in ("task_id", "kind", "instructions", "writable_paths", "checks", "max_tool_calls", "max_turns", "run_options")} + validate_task({"version": 2, **public}) + if metadata: + if task["writable_paths"] or task["checks"] or task["run_options"] or set(validate_run_options(task["selected_model"])) != {"provider", "model"}: + raise ValueError("Selected metadata cannot execute a task") + else: + saved_descriptor(task) + if task["source"].get("kind") != "git" or not re.fullmatch(r"[0-9a-f]{40,64}", str(task["source"].get("commit"))): + raise ValueError("Saved runs require an explicit committed source") + + +def prepare_saved_workspace(root, task): + session = saved_descriptor(task) + directory = Path(session["directory"]) + stable, staged = Path(task["workspace"]), root / "workspace" + retained_storage_guard(root.parent) + staged_manifest = workspace_manifest(staged) + if {name: value["sha256"] for name, value in staged_manifest["files"].items()} != task["source"]["files"] or {name: value["mode"] for name, value in staged_manifest["files"].items()} != task["source"]["modes"]: + raise ValueError("Staged source bytes or modes differ from approved source") + prior = session["prior"] + if prior is None: + directory.parent.mkdir(mode=0o700, exist_ok=True) + directory.mkdir(mode=0o700, exist_ok=False) + backup = None + else: + if (directory / "pending.json").exists(): + raise ValueError("Conversation transition requires reconciliation") + if read_json(directory / "checkpoint.json") != prior or digest((directory / "checkpoint.json").read_bytes()) != session["prior_sha256"]: + raise ValueError("Stale or duplicate continuation checkpoint") + saved_session_snapshot(Path(session["file"]), stable, expected=prior["session"]) + if workspace_manifest(stable) != prior["workspace"]: + raise ValueError("Prior workspace bytes or modes changed") + (directory / "retained").mkdir(mode=0o700, exist_ok=True) + backup = directory / "retained" / prior["run_id"] + if backup.exists(): + raise ValueError("Prior workspace backup already exists") + intent = {"version": 1, "conversation_id": session["conversation_id"], "run_id": task["run_id"], "task_sha256": digest((root / "task.json").read_bytes()), "prior_sha256": session["prior_sha256"], "old_workspace": prior["workspace"] if prior else None, "new_workspace": staged_manifest, "staged": str(staged), "stable": str(stable), "backup": str(backup) if backup else None} + write_private_control(directory / "pending.json", intent) + if backup is not None: + stable.rename(backup) + staged.rename(stable) + if workspace_manifest(stable) != staged_manifest: + raise ValueError("Activated workspace differs from staged source") + return session + + +def complete_saved_conversation(root, task, configuration, session_after): + session = saved_descriptor(task) + directory, workspace = Path(session["directory"]), Path(task["workspace"]) + prior = session["prior"] + observed = saved_session_snapshot(Path(session["file"]), workspace, expected=session_after, prefix=prior["session"] if prior else None) + if observed["id"] != configuration["session_id"] or observed["file"] != configuration["session_file"]: + raise ValueError("Terminal session differs from admitted RPC identity") + checkpoint = {"version": 1, "conversation_id": session["conversation_id"], "run_id": task["run_id"], "task_id": task["task_id"], "task_sha256": digest((root / "task.json").read_bytes()), "source_commit": task["source"]["commit"], "prior_run_id": prior["run_id"] if prior else None, "prior_checkpoint_sha256": session["prior_sha256"], "session": observed, "workspace": workspace_manifest(workspace)} + retained_storage_guard(root.parent) + checkpoint_path = directory / "checkpoint.json" + if prior is None: + if checkpoint_path.exists(): + raise ValueError("New conversation checkpoint already exists") + elif digest(checkpoint_path.read_bytes()) != session["prior_sha256"]: + raise ValueError("Conversation checkpoint changed during dispatch") + write_private_control(root / "results/conversation.json", checkpoint) + staged = directory / (task["run_id"] + ".checkpoint.json") + write_private_control(staged, checkpoint) + staged.replace(checkpoint_path) + (directory / "pending.json").rename(root / "transition-completed.json") + return {"checkpoint_sha256": digest(private_control_bytes(checkpoint)), "session_before": prior["session"] if prior else None, "session_after": observed, "prior_prefix_sha256": prior["session"]["sha256"] if prior else digest(b""), "continuable": True} + + +def verify_conversation(results, task, receipt): + session = saved_descriptor(task) + checkpoint = read_json(Path(results) / "conversation.json") + prior = session["prior"] + expected = {"version": 1, "conversation_id": session["conversation_id"], "run_id": task["run_id"], "task_id": task["task_id"], "task_sha256": digest(json.dumps(task).encode()), "source_commit": task["source"]["commit"], "prior_run_id": prior["run_id"] if prior else None, "prior_checkpoint_sha256": session["prior_sha256"]} + if set(checkpoint) != set(expected) | {"session", "workspace"} or any(checkpoint.get(key) != value for key, value in expected.items()): + raise ValueError("Conversation checkpoint task/source identity mismatch") + saved = checkpoint["session"] + configuration = receipt["configuration"] + if not isinstance(saved, dict) or set(saved) != {"id", "file", "cwd", "bytes", "sha256", "header_sha256"} or saved["id"] != configuration["session_id"] or saved["file"] != session["file"] or saved["cwd"] != task["workspace"] or type(saved["bytes"]) is not int or not 0 < saved["bytes"] <= MAX_SESSION_BYTES or any(not re.fullmatch(r"[0-9a-f]{64}", str(saved[key])) for key in ("sha256", "header_sha256")): + raise ValueError("Returned session does not bind the admitted identity") + if prior and (saved["bytes"] < prior["session"]["bytes"] or any(saved[key] != prior["session"][key] for key in ("id", "file", "cwd", "header_sha256"))): + raise ValueError("Returned session changed its prior identity") + manifest = checkpoint["workspace"] + if not isinstance(manifest, dict) or set(manifest) != {"files", "directories"} or any(not isinstance(manifest[key], dict) or len(manifest[key]) > MAX_FILES for key in manifest) or "." not in manifest["directories"]: + raise ValueError("Invalid terminal workspace manifest") + for name, value in manifest["files"].items(): + relative_file(name) + if not isinstance(value, dict) or set(value) != {"sha256", "mode"} or not re.fullmatch(r"[0-9a-f]{64}", str(value["sha256"])) or type(value["mode"]) is not int or not 0 <= value["mode"] <= 0o777: + raise ValueError("Invalid terminal file identity") + for name, mode in manifest["directories"].items(): + if name != ".": + relative_file(name) + if type(mode) is not int or not 0 <= mode <= 0o777 or name in manifest["files"]: + raise ValueError("Invalid terminal directory identity") + expected_conversation = {"checkpoint_sha256": digest(private_control_bytes(checkpoint)), "session_before": prior["session"] if prior else None, "session_after": saved, "prior_prefix_sha256": prior["session"]["sha256"] if prior else digest(b""), "continuable": True} + if receipt.get("conversation") != expected_conversation or receipt.get("extension", {}).get("session") != {"id": saved["id"], "file": saved["file"], "cwd": saved["cwd"], "version": 3}: + raise ValueError("Returned conversation differs from terminal worker/extension bindings") + return checkpoint + + +def inspect_saved_conversation(root, task, reconcile=False): + """Inspect a stopped dispatch's files; never invoke Pi, checks or rollback.""" + session = saved_descriptor(task) + directory, stable = Path(session["directory"]), Path(task["workspace"]) + retained_storage_guard(root.parent) + checkpoint = read_json(directory / "checkpoint.json") + current_session = saved_session_snapshot(Path(session["file"]), stable, expected=checkpoint["session"]) + pending = directory / "pending.json" + if checkpoint.get("run_id") == task["run_id"]: + if checkpoint != read_json(root / "results/conversation.json") or workspace_manifest(stable) != checkpoint["workspace"]: + raise ValueError("Completed conversation checkpoint changed") + if pending.exists(): + raise ValueError("Terminal checkpoint still has an unresolved transition") + return {"disposition": "terminal_checkpoint", "continuable": True, "checkpoint": checkpoint, "session": current_session} + if checkpoint != session["prior"] or digest((directory / "checkpoint.json").read_bytes()) != session["prior_sha256"]: + raise ValueError("Saved conversation no longer matches this dispatch") + if not pending.exists(): + if workspace_manifest(stable) != checkpoint["workspace"]: + raise ValueError("Retained old workspace changed") + return {"disposition": "unchanged_prior_checkpoint", "continuable": True, "checkpoint": checkpoint, "session": current_session} + intent = read_json(pending) + staged, backup = root / "workspace", directory / "retained" / checkpoint["run_id"] + expected = {"version": 1, "conversation_id": session["conversation_id"], "run_id": task["run_id"], "task_sha256": digest((root / "task.json").read_bytes()), "prior_sha256": session["prior_sha256"], "old_workspace": checkpoint["workspace"], "staged": str(staged), "stable": str(stable), "backup": str(backup)} + if set(intent) != set(expected) | {"new_workspace"} or any(intent[key] != value for key, value in expected.items()): + raise ValueError("Transition intent does not bind this saved dispatch") + if stable.exists() and not backup.exists() and staged.exists() and workspace_manifest(stable) == checkpoint["workspace"] and workspace_manifest(staged) == intent["new_workspace"]: + if reconcile: + destination = root / "transition-reconciled.json" + if destination.exists(): + raise ValueError("Transition reconciliation evidence already exists") + pending.rename(destination) + return {"disposition": "old_checkpoint_reconciled" if reconcile else "old_checkpoint_requires_reconcile", "continuable": bool(reconcile), "checkpoint": checkpoint, "session": current_session} + if stable.exists() and backup.exists() and not staged.exists() and workspace_manifest(stable) == intent["new_workspace"] and workspace_manifest(backup) == checkpoint["workspace"]: + return {"disposition": "new_workspace_dispatch_unresolved", "continuable": False, "checkpoint": checkpoint, "session": current_session} + raise ValueError("Partial or mixed saved workspace transition requires owner investigation") + + +def execute_to_log(argv, cwd, log, timeout, *, remote_owner=False, env=None, storage_parent=None): """Cap bytes and time. Remote descendants are stopped by the external owner.""" started = time.monotonic() + next_storage_check = started with Path(log).open("xb") as stream: process = subprocess.Popen(argv, cwd=cwd, stdout=stream, stderr=subprocess.STDOUT, env=env) try: while process.poll() is None: + if storage_parent is not None and time.monotonic() >= next_storage_check: + retained_storage_guard(storage_parent) + next_storage_check = time.monotonic() + 1 if time.monotonic() - started > timeout or Path(log).stat().st_size > MAX_OUTPUT_BYTES: raise TimeoutError("Command deadline or output limit exceeded") time.sleep(0.05) if Path(log).stat().st_size > MAX_OUTPUT_BYTES: raise ValueError("Command output limit exceeded") + if storage_parent is not None: + retained_storage_guard(storage_parent) return process.returncode finally: if not remote_owner and process.poll() is None: @@ -257,7 +533,7 @@ def inspect_extension_events(path, task, pi_events, task_sha256): if kinds[0] != "task_loaded" or kinds.count("task_loaded") != 1 or kinds.count("handoff") != 1 or kinds.count("agent_settled") != 1 or kinds.count("session_shutdown") != 1 or kinds[-2:] != ["agent_settled", "session_shutdown"]: raise ValueError("Incomplete or unordered extension lifecycle") allowed_kinds = {"task_loaded", "tool_call", "handoff", "agent_settled", "session_shutdown"} - if task["version"] == 2: + if task["version"] in (2, 3): allowed_kinds.add("run_configuration") if kinds.count("run_configuration") != 1 or kinds[1] != "run_configuration": raise ValueError("Missing or unordered extension run configuration") @@ -286,10 +562,18 @@ def inspect_extension_events(path, task, pi_events, task_sha256): if not 1 <= events[handoff_index]["turns"] <= pi_events["assistant_turns"] or any(event["turns"] != pi_events["assistant_turns"] for event in events[-2:]): raise ValueError("Extension turn accounting differs from Pi") result = {"event_log_sha256": digest(raw), "model": events[0].get("model"), "tool_calls": len(calls), "assistant_turns": pi_events["assistant_turns"]} - if task["version"] == 2: + if task["version"] in (2, 3): result["configuration"] = validate_run_options(events[1].get("configuration")) if set(result["configuration"]) != {"provider", "model", "thinking"}: raise ValueError("Incomplete extension run configuration") + if task.get("session"): + saved_descriptor(task) + session = events[0].get("session") + if not isinstance(session, dict) or set(session) != {"id", "file", "cwd", "version"} or session.get("version") != 3 or session.get("file") != task["session"]["file"] or session.get("cwd") != task["workspace"] or not re.fullmatch(r"[A-Za-z0-9_.-]{1,128}", str(session.get("id"))) or any(event.get("session") != session for event in events): + raise ValueError("Extension saved session identity changed") + if task["session"]["prior"] and session["id"] != task["session"]["prior"]["session"]["id"]: + raise ValueError("Extension resumed a different official session") + result["session"] = session return result @@ -302,7 +586,7 @@ def rpc_model(value): return {"provider": model_identifier(value.get("provider")), "id": model_identifier(value.get("id"))} -def rpc_data(command, data): +def rpc_data(command, data, session=None): """Discard model API objects, headers, URLs and free-form error messages.""" if command == "get_available_models": if not isinstance(data, dict) or not isinstance(data.get("models"), list) or len(data["models"]) > 1000: @@ -319,14 +603,16 @@ def rpc_data(command, data): if command == "get_state": if not isinstance(data, dict) or any(type(data.get(key)) is not bool for key in ("isStreaming", "isCompacting")) or type(data.get("pendingMessageCount")) is not int or data["pendingMessageCount"] < 0: raise ValueError("Invalid RPC state") - if data.get("sessionFile") is not None or not isinstance(data.get("sessionId"), str) or not re.fullmatch(r"[A-Za-z0-9_.-]{1,128}", data["sessionId"]): - raise ValueError("RPC must use an exact nonpersistent session") + expected_file = session["file"] if session else None + expected_id = session["prior"]["session"]["id"] if session and session["prior"] else None + if data.get("sessionFile") != expected_file or not isinstance(data.get("sessionId"), str) or not re.fullmatch(r"[A-Za-z0-9_.-]{1,128}", data["sessionId"]) or expected_id is not None and data["sessionId"] != expected_id: + raise ValueError("RPC session differs from the exact saved or ephemeral contract") thinking = data.get("thinkingLevel") if not isinstance(thinking, str) or thinking not in THINKING_LEVELS: raise ValueError("Invalid effective thinking level") return {"model": rpc_model(data.get("model")), "thinkingLevel": thinking, "isStreaming": data["isStreaming"], "isCompacting": data["isCompacting"], - "pendingMessageCount": data["pendingMessageCount"], "sessionId": data["sessionId"], "sessionFile": None} + "pendingMessageCount": data["pendingMessageCount"], "sessionId": data["sessionId"], "sessionFile": expected_file} if command == "set_model": return rpc_model(data) if command in {"set_thinking_level", "prompt"}: @@ -347,8 +633,10 @@ def configuration_event_record(value, request_id, command, arguments, previous_l class PiRpc: """One bounded stdlib RPC child; OpenShell remains its lifecycle owner.""" - def __init__(self, command, workspace, output, deadline, env): + def __init__(self, command, workspace, output, deadline, env, session=None): self.deadline, self.output = deadline, output + self.session = session + self.next_storage_check = 0 self.pending, self.responses, self.records = {}, {}, [] self.pending_arguments, self.configuration_events = {}, set() self.observed_thinking = None @@ -409,7 +697,7 @@ def consume(self, raw): if value.get("success") is not True: self.record({"type": "response", "id": request_id, "command": command, "success": False}) raise ValueError("Pi RPC command refused: " + command) - safe = rpc_data(command, value.get("data")) + safe = rpc_data(command, value.get("data"), self.session) if command == "get_state": if self.observed_thinking is not None and safe["thinkingLevel"] != self.observed_thinking: raise ValueError("RPC thinking changed without a bound configuration event") @@ -443,6 +731,13 @@ def consume(self, raw): raise ValueError("Pi event output exceeded") def pump(self): + if self.session: + if time.monotonic() >= self.next_storage_check: + retained_storage_guard(Path(self.session["directory"]).parent.parent) + self.next_storage_check = time.monotonic() + 1 + session_path = Path(self.session["file"]) + if session_path.is_symlink() or session_path.exists() and (not session_path.is_file() or session_path.stat().st_size > MAX_SESSION_BYTES) or self.session["prior"] is not None and not session_path.exists(): + raise ValueError("Saved session disappeared or exceeded observed bounds") remaining = self.deadline - time.monotonic() if remaining <= 0: raise ValueError("Pi RPC deadline exceeded") @@ -524,6 +819,20 @@ def desired_configuration(task, models): return {"provider": candidates[0]["provider"], "model": candidates[0]["id"], "thinking": requested.get("thinking", defaults["thinking"])} +def metadata_task(task): + return task.get("operation") in {"capabilities", "capabilities_selected"} + + +def selected_metadata_model(task, models): + selection = validate_run_options(task["selected_model"]) + if set(selection) != {"provider", "model"}: + raise ValueError("Selected metadata requires exactly provider and model") + matches = [model for model in models if model == {"provider": selection["provider"], "id": selection["model"]}] + if len(matches) != 1: + raise ValueError("Selected metadata model is unavailable or ambiguous") + return selection + + def require_rpc_idle(state, effective=None, session_id=None): if state["isStreaming"] or state["isCompacting"] or state["pendingMessageCount"] != 0: raise ValueError("Pi RPC is not idle with an empty queue") @@ -534,22 +843,37 @@ def require_rpc_idle(state, effective=None, session_id=None): def rpc_configuration_record(task, models, levels, effective, session_id, results): - task_run = task["operation"] == "run" - return {"version": 1, "operation": task["operation"], "requested": task["run_options"], + task_run = not metadata_task(task) + record = {"version": 1, "operation": task["operation"], "requested": task["run_options"], "defaults": task["runtime_defaults"], "available_models": models, "supported_thinking_levels": levels, "effective": effective, "session_id": session_id, "session_file": None, "prompt_sent": task_run, "settled": task_run, "shutdown": "stdin-eof", "rpc_log_sha256": digest((results / "rpc-events.jsonl").read_bytes()), "stderr_sha256": digest((results / "rpc/stderr.log").read_bytes())} + if task["operation"] == "capabilities_selected": + record.update(version=2, requested=task["selected_model"], + profile_default_supported=task["runtime_defaults"]["thinking"] in levels) + elif task.get("session"): + record.update(version=2, session_file=task["session"]["file"]) + return record def run_rpc(root, task, launch, deadline, env): - metadata = task["operation"] == "capabilities" - command = [*launch["pi_argv"], "--offline", "--no-session", "--no-extensions", "--no-skills", "--no-prompt-templates", "--no-context-files", "--no-approve", "--tools", "" if metadata else ",".join([*task["allowed_tools"], "coordination_status", "coordination_handoff"]), "--mode", "rpc"] + metadata = metadata_task(task) + selected_metadata = task["operation"] == "capabilities_selected" + session = saved_descriptor(task) if task.get("session") else None + session_arguments = ["--no-session"] + if session: + if session["prior"]: + saved_session_snapshot(Path(session["file"]), Path(task["workspace"]), expected=session["prior"]["session"]) + elif Path(session["file"]).exists(): + raise ValueError("New saved session file must be absent") + session_arguments = ["--session", session["file"], "--session-dir", session["directory"]] + command = [*launch["pi_argv"], "--offline", *session_arguments, "--no-extensions", "--no-skills", "--no-prompt-templates", "--no-context-files", "--no-approve", "--tools", "" if metadata else ",".join([*task["allowed_tools"], "coordination_status", "coordination_handoff"]), "--mode", "rpc"] if not metadata: command += ["--extension", str(root / "extension.js"), "--coordination-task", str(root / "task.json")] - rpc = PiRpc(command, root / "workspace", root / "results", deadline, env) + rpc = PiRpc(command, Path(task["workspace"]), root / "results", deadline, env, session=session) try: models_request = rpc.send("get_available_models") initial_request = rpc.send("get_state") @@ -557,17 +881,23 @@ def run_rpc(root, task, launch, deadline, env): initial = rpc.wait(initial_request) observed = require_rpc_idle(initial) effective = observed if metadata else desired_configuration(task, models) + if selected_metadata: + effective = {**selected_metadata_model(task, models), "thinking": observed["thinking"]} model_changed = initial["model"] != {"provider": effective["provider"], "id": effective["model"]} if model_changed: selected = rpc.call("set_model", provider=effective["provider"], modelId=effective["model"]) if selected != {"provider": effective["provider"], "id": effective["model"]}: raise ValueError("Pi selected a different model") levels = rpc.call("get_available_thinking_levels")["levels"] - if effective["thinking"] not in levels: + if not selected_metadata and effective["thinking"] not in levels: raise ValueError("Selected model does not support requested thinking") - if model_changed or initial["thinkingLevel"] != effective["thinking"]: + if not selected_metadata and (model_changed or initial["thinkingLevel"] != effective["thinking"]): rpc.call("set_thinking_level", level=effective["thinking"]) admitted = rpc.call("get_state") + if selected_metadata: + effective = {**selected_metadata_model(task, models), "thinking": admitted["thinkingLevel"]} + if effective["thinking"] not in levels: + raise ValueError("Selected metadata thinking is not supported") require_rpc_idle(admitted, effective, initial["sessionId"]) if not metadata: rpc.call("prompt", message=RPC_PROMPT) @@ -608,7 +938,7 @@ def verify_rpc_configuration(results, task): if set(record) != {"type", "id", "command", "success", "data"} or record["success"] is not True or not isinstance(record["id"], str) or record["id"] in responses: raise ValueError("Invalid RPC response binding") matched = [request for _position, request in requests if request["id"] == record["id"]] - if len(matched) != 1 or record["command"] != matched[0]["command"] or rpc_data(record["command"], record["data"]) != record["data"]: + if len(matched) != 1 or record["command"] != matched[0]["command"] or rpc_data(record["command"], record["data"], task.get("session")) != record["data"]: raise ValueError("RPC response differs from its safe request contract") if record["command"] == "get_state": thinking = record["data"]["thinkingLevel"] @@ -648,8 +978,11 @@ def data(number): raise ValueError("RPC metadata preflight missing") models, initial = data(0)["models"], data(1) observed = require_rpc_idle(initial) - metadata = task["operation"] == "capabilities" + metadata = metadata_task(task) + selected_metadata = task["operation"] == "capabilities_selected" effective = observed if metadata else desired_configuration(task, models) + if selected_metadata: + effective = {**selected_metadata_model(task, models), "thinking": observed["thinking"]} target_model = {"provider": effective["provider"], "id": effective["model"]} changed = initial["model"] != target_model expected = [("get_available_models", {}), ("get_state", {})] @@ -660,12 +993,16 @@ def data(number): levels_index = len(expected) expected.append(("get_available_thinking_levels", {})) levels = data(levels_index)["levels"] - if effective["thinking"] not in levels: + if not selected_metadata and effective["thinking"] not in levels: raise ValueError("RPC selected unsupported thinking") - if changed or initial["thinkingLevel"] != effective["thinking"]: + if not selected_metadata and (changed or initial["thinkingLevel"] != effective["thinking"]): expected.append(("set_thinking_level", {"level": effective["thinking"]})) admitted_index = len(expected) expected.append(("get_state", {})) + if selected_metadata: + effective = {**selected_metadata_model(task, models), "thinking": data(admitted_index)["thinkingLevel"]} + if effective["thinking"] not in levels: + raise ValueError("RPC selected metadata thinking is unsupported") if not metadata: expected += [("prompt", {"message_sha256": digest(RPC_PROMPT.encode())}), ("get_state", {})] if [(request["command"], request["arguments"]) for _index, request in requests] != expected: @@ -688,22 +1025,25 @@ def worker(root): """Runs only inside the caller-owned disposable OpenShell sandbox.""" root = Path(root).resolve(strict=True) task, launch = read_json(root / "task.json"), read_json(root / "launch.json") - workspace, output = root / "workspace", root / "results" + validate_native_task(task) + workspace, output = Path(task["workspace"]), root / "results" receipt = {"version": task["version"], "run_id": task["run_id"], "task_id": task["task_id"], "started_at": utc_now(), "outcome": "incomplete", "checks": []} write_new_json(root / "worker-started.json", receipt) deadline = time.monotonic() + launch["wall_seconds"] - before = snapshot(workspace) try: + if task.get("session"): + prepare_saved_workspace(root, task) + before = snapshot(workspace) if {p: digest(b) for p, b in before.items()} != task["source"]["files"]: raise ValueError("Exported source differs from frozen source") command = [*launch["pi_argv"], "--model", launch["model"], "--thinking", launch["thinking"], "--offline", "--no-session", "--no-extensions", "--no-skills", "--no-prompt-templates", "--no-context-files", "--no-approve", "--tools", ",".join([*task["allowed_tools"], "coordination_status", "coordination_handoff"]), "--extension", str(root / "extension.js"), "--coordination-task", str(root / "task.json"), "--mode", "json", "-p", "Complete the assigned coordination task. Use coordination_status to inspect it and coordination_handoff to return your work. Do not execute verification commands; the coordinator runs declared checks after your handoff."] env = os.environ.copy() env.update(launch["environment"]) env["PYTHONDONTWRITEBYTECODE"] = "1" - if task["version"] == 2: + if task["version"] in (2, 3): receipt["configuration"] = run_rpc(root, task, launch, deadline, env) receipt["pi_exit_code"] = 0 - if task["operation"] == "capabilities": + if metadata_task(task): if snapshot(workspace) != before: raise ValueError("Metadata discovery changed source") receipt["outcome"] = "capabilities" @@ -716,8 +1056,12 @@ def worker(root): raise ValueError("Pi exited unsuccessfully") receipt["events"] = inspect_events(output / "pi-events.jsonl", task["max_tool_calls"], task["max_turns"]) receipt["extension"] = inspect_extension_events(output / "extension-events.jsonl", task, receipt["events"], digest((root / "task.json").read_bytes())) - if task["version"] == 2 and receipt["extension"].get("configuration") != receipt["configuration"]["effective"]: + if task["version"] in (2, 3) and receipt["extension"].get("configuration") != receipt["configuration"]["effective"]: raise ValueError("Extension effective options differ from RPC admission") + if task.get("session"): + session_after = saved_session_snapshot(Path(task["session"]["file"]), workspace, prefix=task["session"]["prior"]["session"] if task["session"]["prior"] else None) + if receipt["extension"].get("session") != {"id": receipt["configuration"]["session_id"], "file": task["session"]["file"], "cwd": task["workspace"], "version": 3}: + raise ValueError("Extension saved-session identity differs from RPC") report = read_json(output / "model-report.json") if report.get("run_id") != task["run_id"] or report.get("task_id") != task["task_id"] or report.get("model_self_report") is not True or report.get("task_sha256") != digest((root / "task.json").read_bytes()): raise ValueError("Model handoff identity mismatch") @@ -732,7 +1076,7 @@ def worker(root): started = {"name": check["name"], "argv": check["argv"], "started_at": utc_now()} write_new_json(output / (check["name"] + ".started.json"), started) log = output / (check["name"] + ".log") - code = execute_to_log(check["argv"], workspace, log, min(check["timeout_seconds"], deadline - time.monotonic()), remote_owner=True, env=env) + code = execute_to_log(check["argv"], workspace, log, min(check["timeout_seconds"], deadline - time.monotonic()), remote_owner=True, env=env, storage_parent=root.parent if task.get("session") else None) result = {**started, "ended_at": utc_now(), "exit_code": code, "log_bytes": log.stat().st_size, "log_sha256": digest(log.read_bytes())} write_new_json(output / (check["name"] + ".result.json"), result) receipt["checks"].append(result) @@ -759,6 +1103,8 @@ def worker(root): patch.writelines(difflib.unified_diff(old.splitlines(True), new.splitlines(True), fromfile="a/" + name if name in before else "/dev/null", tofile="b/" + name if name in after else "/dev/null")) receipt["checks_passed"] = all(c["exit_code"] == 0 for c in receipt["checks"]) if receipt["checks"] else None receipt["model_status"] = report.get("status") + if task.get("session"): + receipt["conversation"] = complete_saved_conversation(root, task, receipt["configuration"], session_after) receipt["outcome"] = "returned" if report.get("status") == "completed" and receipt["checks_passed"] is not False and receipt["model_report_matches_changes"] else "failed" receipt["acceptance"] = "not_granted" receipt["artifact_sha256"] = {name: digest(data) for name, data in snapshot(output).items()} @@ -784,10 +1130,10 @@ def verify_return(results, task, source_files, run_id): raise ValueError("Returned artifact manifest differs from actual bytes") if receipt.get("version") != task["version"]: raise ValueError("Worker receipt version differs from task") - metadata = task.get("operation") == "capabilities" + metadata = metadata_task(task) if receipt.get("run_id") != run_id or receipt.get("task_id") != task["task_id"] or receipt.get("outcome") != ("capabilities" if metadata else "returned") or type(receipt.get("pi_exit_code")) is not int or receipt["pi_exit_code"] != 0 or receipt.get("acceptance") != "not_granted": raise ValueError("Worker identity or completion contract mismatch") - if task["version"] == 2: + if task["version"] in (2, 3): configuration = verify_rpc_configuration(results, task) if receipt.get("configuration") != configuration: raise ValueError("Worker configuration differs from the verified RPC return") @@ -806,7 +1152,7 @@ def verify_return(results, task, source_files, run_id): extension = inspect_extension_events(results / "extension-events.jsonl", task, events, digest(json.dumps(task).encode())) if receipt.get("extension") != extension: raise ValueError("Recorded extension lifecycle differs from returned log") - if task["version"] == 2 and extension.get("configuration") != configuration["effective"]: + if task["version"] in (2, 3) and extension.get("configuration") != configuration["effective"]: raise ValueError("Extension configuration differs from the verified RPC return") checks = receipt.get("checks") if not isinstance(checks, list) or len(checks) != len(task["checks"]): @@ -824,6 +1170,8 @@ def verify_return(results, task, source_files, run_id): if len(raw) != check["log_bytes"] or digest(raw) != check["log_sha256"]: raise ValueError("Check output differs from its receipt") verify_changes(results, actual, task, source_files, receipt, report) + if task.get("session"): + verify_conversation(results, task, receipt) return receipt @@ -1011,10 +1359,47 @@ def cleanup_owner(owner, profile, receipt, protected): receipt["protected_readback_error"] = str(error) -def run_task(task_file, profile_file, output, lock_root, *, capabilities_only=False): +def continuation_checkpoint(previous_directory, profile): + previous_directory = Path(previous_directory).absolute() + previous = read_json(previous_directory / "receipt.json") + recovered = previous.get("operation") == "recovery" + origin = Path(previous["recovered_from"]) if recovered and "recovered_from" in previous else previous_directory + original, task, files, hashes = recovery_inputs(origin, profile, allow_saved_success=True) + if task["version"] != 3 or not task.get("session") or previous.get("cleanup_complete") is not True or previous.get("protected_unchanged") is not True: + raise ValueError("Continue requires verified stopped saved-session custody") + if recovered: + if previous.get("recovery_valid") is not True or previous.get("original_artifact_sha256") != hashes or previous.get("failed_run_id") != task["run_id"]: + raise ValueError("Recovery does not bind the original saved dispatch") + evidence = verify_recovered_artifacts(previous_directory / "results", task, files) + checkpoint = previous.get("continuation_checkpoint") + inspection = read_json(previous_directory / "conversation-inspection.json") + if previous.get("conversation_valid") is not True or previous.get("inspection_sha256") != digest((previous_directory / "conversation-inspection.json").read_bytes()) or inspection.get("continuable") is not True or inspection.get("checkpoint") != checkpoint: + raise ValueError("Recovered conversation is not continuable") + if checkpoint != task["session"]["prior"]: + if evidence.get("conversation_valid") is not True or checkpoint != read_json(previous_directory / "results/conversation.json"): + raise ValueError("Recovered terminal checkpoint differs from evidence") + return checkpoint + else: + if original.get("delivery_valid") is not True: + raise ValueError("Recover the failed saved dispatch before continuing") + verify_return(previous_directory / "results", task, files, task["run_id"]) + checkpoint = read_json(previous_directory / "results/conversation.json") + return checkpoint + + +def run_task(task_file, profile_file, output, lock_root, *, capabilities_only=False, selected_model=None, save_session=False, previous_directory=None): + if selected_model is not None: + if not capabilities_only or set(validate_run_options(selected_model)) != {"provider", "model"}: + raise ValueError("Selected metadata requires exactly provider and model") task = validate_task({"version": 2, "task_id": "capabilities", "kind": "validation", "instructions": "Inspect configured runtime metadata without model work.", "writable_paths": [], "checks": [], "wall_seconds": 30} if capabilities_only else read_json(task_file)) profile = profile_settings(profile_file, require_qualified_model=True) files, source = frozen_source(task) + if capabilities_only and (save_session or previous_directory is not None): + raise ValueError("Metadata cannot create or continue a saved conversation") + saved = save_session or previous_directory is not None + if saved and source.get("kind") != "git": + raise ValueError("Saved dispatch requires an explicit committed source") + prior = continuation_checkpoint(previous_directory, profile) if previous_directory is not None else None output = Path(output).absolute() output.mkdir(parents=True, exist_ok=False) owner, run_id = OpenShellOwner(profile), uuid.uuid4().hex @@ -1024,6 +1409,13 @@ def run_task(task_file, profile_file, output, lock_root, *, capabilities_only=Fa remote = str(remote_parent / run_id) remote_archive = str(remote_parent.parent / ("codex-pi-" + run_id + ".tar")) native_task = {"version": 2, "run_id": run_id, "task_id": task["task_id"], "kind": task["kind"], "instructions": task["instructions"], "workspace": remote + "/workspace", "output_directory": remote + "/results", "writable_paths": task["writable_paths"], "allowed_tools": sorted(TOOLS if task["writable_paths"] else TOOLS - {"write", "edit"}), "max_tool_calls": task.get("max_tool_calls", 40), "max_turns": task.get("max_turns", 32), "source": source, "checks": task["checks"], "operation": "capabilities" if capabilities_only else "run", "run_options": task.get("run_options", {}), "runtime_defaults": {"model": profile["model"], "thinking": profile.get("thinking", "high")}} + if selected_model is not None: + native_task.update(version=3, operation="capabilities_selected", selected_model=selected_model) + if saved: + conversation_id = prior["conversation_id"] if prior else run_id + conversation_directory = str(remote_parent / "conversations" / conversation_id) + native_task.update(version=3, operation="continue" if prior else "run", workspace=conversation_directory + "/workspace", session={"conversation_id": conversation_id, "directory": conversation_directory, "file": conversation_directory + "/session.jsonl", "prior": prior, "prior_sha256": digest(private_control_bytes(prior)) if prior else None}) + validate_native_task(native_task) if len(json.dumps(native_task).encode()) > 1024 * 1024: raise ValueError("Exported task manifest exceeds 1 MiB") launch = {"pi_argv": profile["pi_argv"], "model": profile["model"], "thinking": profile.get("thinking", "high"), "environment": profile.get("environment", {}), "checks": task["checks"], "wall_seconds": task.get("wall_seconds", 600)} @@ -1036,7 +1428,7 @@ def run_task(task_file, profile_file, output, lock_root, *, capabilities_only=Fa info.size = len(data) info.mode = source["modes"].get(name.removeprefix("workspace/"), 0o600) if name.startswith("workspace/") else 0o600 archive.addfile(info, io.BytesIO(data)) - receipt = {"version": 2, "run_id": run_id, "task_id": task["task_id"], "kind": task["kind"], "started_at": utc_now(), "source": source, "input_sha256": digest(archive_path.read_bytes()), "remote_artifacts": remote + "/results", "cleanup_complete": False, "outcome": "incomplete"} + receipt = {"version": native_task["version"], "run_id": run_id, "task_id": task["task_id"], "kind": task["kind"], "started_at": utc_now(), "source": source, "input_sha256": digest(archive_path.read_bytes()), "remote_artifacts": remote + "/results", "cleanup_complete": False, "outcome": "incomplete"} write_new_json(output / "started.json", receipt) with exclusive_owner(profile, lock_root) as journal: if journal.exists() and not read_json(journal).get("cleanup_complete"): @@ -1096,14 +1488,14 @@ def save_journal(): return receipt -def recovery_inputs(failed_directory, profile): +def recovery_inputs(failed_directory, profile, *, allow_saved_success=False): """Read only the retained export, never the current repository or remote path.""" failed_directory = Path(failed_directory) if failed_directory.is_symlink() or not failed_directory.is_dir(): raise ValueError("Expected a regular failed-run directory") started = read_json(failed_directory / "started.json") original = read_json(failed_directory / "receipt.json") - if not isinstance(started, dict) or not isinstance(original, dict) or original.get("delivery_valid") is not False: + if not isinstance(started, dict) or not isinstance(original, dict) or original.get("delivery_valid") is not False and not (allow_saved_success and original.get("version") == 3 and original.get("delivery_valid") is True): raise ValueError("Only a retained unsuccessful delivery may be recovered") run_id = original.get("run_id") if not isinstance(run_id, str) or not re.fullmatch(r"[0-9a-f]{32}", run_id): @@ -1127,20 +1519,25 @@ def recovery_inputs(failed_directory, profile): if not isinstance(task, dict) or not isinstance(launch, dict): raise ValueError("Invalid retained task/launch") expected_keys = {"version", "run_id", "task_id", "kind", "instructions", "workspace", "output_directory", "writable_paths", "allowed_tools", "max_tool_calls", "max_turns", "source", "checks"} - if task.get("version") == 2: + if task.get("version") in (2, 3): expected_keys |= {"operation", "run_options", "runtime_defaults"} - if task.get("operation") != "run": + if task.get("version") == 3: + expected_keys.add("session") + if task.get("operation") not in ({"run", "continue"} if task.get("version") == 3 else {"run"}): raise ValueError("Only task execution evidence is recoverable") if set(task) != expected_keys: raise ValueError("Unexpected retained native task fields") public_task = {key: task[key] for key in ("version", "task_id", "kind", "instructions", "writable_paths", "checks", "max_tool_calls", "max_turns")} - if task["version"] == 2: + if task["version"] in (2, 3): + public_task["version"] = 2 public_task["run_options"] = task["run_options"] if task["runtime_defaults"] != {"model": launch.get("model"), "thinking": launch.get("thinking")}: raise ValueError("Retained runtime defaults differ from launch") validate_task(public_task) + validate_native_task(task) remote = str(PurePosixPath(profile.get("remote_parent", "/sandbox/codex-pi")) / run_id) - if task["run_id"] != run_id or task["task_id"] != original["task_id"] or task["kind"] != original["kind"] or task["source"] != original["source"] or task["workspace"] != remote + "/workspace" or task["output_directory"] != remote + "/results" or original["remote_artifacts"] != task["output_directory"]: + expected_workspace = task["session"]["directory"] + "/workspace" if task.get("session") else remote + "/workspace" + if task["run_id"] != run_id or task["task_id"] != original["task_id"] or task["kind"] != original["kind"] or task["source"] != original["source"] or task["workspace"] != expected_workspace or task["output_directory"] != remote + "/results" or original["remote_artifacts"] != task["output_directory"]: raise ValueError("Retained task/source/remote identity mismatch") if task["allowed_tools"] != sorted(TOOLS if task["writable_paths"] else TOOLS - {"write", "edit"}) or launch.get("checks") != task["checks"]: raise ValueError("Retained tools/check contract mismatch") @@ -1165,8 +1562,10 @@ def verify_recovered_artifacts(results, task, source_files): raise ValueError("Expected a regular recovered results directory") actual = snapshot(results) allowed = {"worker-receipt.json", "model-report.json", "pi-events.jsonl", "extension-events.jsonl", "changes.json", "changes.patch"} - if task["version"] == 2: + if task["version"] in (2, 3): allowed |= {"rpc-events.jsonl", "rpc/stderr.log", "rpc-configuration.json"} + if task.get("session"): + allowed.add("conversation.json") allowed.update(check["name"] + suffix for check in task["checks"] for suffix in (".started.json", ".result.json", ".log")) if any(name not in allowed and not name.startswith("changed-files/") for name in actual): raise ValueError("Unexpected recovered artifact") @@ -1179,7 +1578,7 @@ def verify_recovered_artifacts(results, task, source_files): raise ValueError("Recovered worker version differs from task") if "acceptance" in worker_receipt and worker_receipt["acceptance"] != "not_granted": raise ValueError("Recovered worker claims unauthorized acceptance") - if task["version"] == 2: + if task["version"] in (2, 3): for name in ("rpc-events.jsonl", "rpc/stderr.log"): if len(actual.get(name, b"")) > MAX_OUTPUT_BYTES: raise ValueError("Recovered RPC output exceeds limit") @@ -1234,7 +1633,7 @@ def verify_recovered_artifacts(results, task, source_files): if "extension" in worker_receipt: if events is None or "extension-events.jsonl" not in actual or worker_receipt["extension"] != inspect_extension_events(results / "extension-events.jsonl", task, events, task_hash): raise ValueError("Recovered extension binding mismatch") - if task["version"] == 2 and worker_receipt["extension"].get("configuration") != worker_receipt.get("configuration", {}).get("effective"): + if task["version"] in (2, 3) and worker_receipt["extension"].get("configuration") != worker_receipt.get("configuration", {}).get("effective"): raise ValueError("Recovered extension/RPC configuration differs") # An interrupted final JSONL write may be incomplete. Every complete extension # record that is present must still bind the retained task, even without a receipt. @@ -1302,20 +1701,28 @@ def verify_recovered_artifacts(results, task, source_files): raise ValueError("Recovered change bytes lack their source manifest") complete = all(key in worker_receipt for key in ("artifact_sha256", "events", "extension", "model_report_sha256", "pi_exit_code", "checks", "checks_passed", "model_status", "acceptance", "ended_at")) and has_changes and len(completed_results) == len(task["checks"]) if complete: - if task["version"] == 2 and "configuration" not in worker_receipt: + if task["version"] in (2, 3) and "configuration" not in worker_receipt: raise ValueError("Recovered terminal RPC configuration is missing") expected_outcome = "returned" if report.get("status") == "completed" and worker_receipt["checks_passed"] is not False and worker_receipt.get("model_report_matches_changes") is True else "failed" if worker_receipt["outcome"] != expected_outcome or worker_receipt["pi_exit_code"] != 0: raise ValueError("Recovered worker outcome contradicts terminal evidence") + conversation_valid = False + if task.get("session") and "conversation.json" in actual: + if complete: + verify_conversation(results, task, worker_receipt) + conversation_valid = True + elif "conversation" in worker_receipt: + raise ValueError("Incomplete worker cannot claim a continuable conversation") return {"evidence_status": "complete" if complete else "partial", "available_bindings_valid": True, + **({"conversation_valid": conversation_valid} if task.get("session") else {}), "worker_outcome": worker_receipt.get("outcome"), "checks": checks, "artifact_sha256": {name: digest(data) for name, data in actual.items()}, "provenance": "retained-input and available-record byte bindings; not independent issuer attestation"} -def recover_task(failed_directory, profile_file, output, lock_root): +def recover_task(failed_directory, profile_file, output, lock_root, *, reconcile_conversation=False): profile = profile_settings(profile_file) - original, task, source_files, original_hashes = recovery_inputs(failed_directory, profile) + original, task, source_files, original_hashes = recovery_inputs(failed_directory, profile, allow_saved_success=reconcile_conversation) output = Path(output).absolute() output.mkdir(parents=True, exist_ok=False) owner = OpenShellOwner(profile) @@ -1326,13 +1733,18 @@ def recover_task(failed_directory, profile_file, output, lock_root): "remote_artifacts": original["remote_artifacts"], "started_at": utc_now(), "cleanup_complete": False, "outcome": "incomplete", "recovery_valid": False, "delivery_valid": False, "task_delivery_valid": False, "acceptance": "not_granted"} + if task.get("session"): + receipt.update(version=2, recovered_from=str(Path(failed_directory).absolute()), conversation_valid=False) + elif reconcile_conversation: + raise ValueError("Conversation reconciliation requires a saved dispatch") with exclusive_owner(profile, lock_root) as journal: prior = read_json(journal) origin = prior.get("failed_run_id", prior.get("run_id")) input_hash = prior.get("failed_input_sha256", prior.get("input_sha256")) - if origin != original["run_id"] or input_hash != original["input_sha256"] or prior.get("task_id") != original["task_id"] or prior.get("delivery_valid") is True or prior.get("cleanup_complete") is not True: + legacy_mismatch = origin != original["run_id"] or input_hash != original["input_sha256"] or prior.get("task_id") != original["task_id"] or prior.get("delivery_valid") is True + if prior.get("cleanup_complete") is not True or (not task.get("session") and legacy_mismatch) or task.get("session") and prior.get("protected_unchanged") is not True: raise ValueError("Latest failed run does not have resolved owner custody") - if prior.get("operation") == "recovery" and prior.get("original_receipt_sha256") != original_hashes["receipt.json"]: + if not task.get("session") and prior.get("operation") == "recovery" and prior.get("original_receipt_sha256") != original_hashes["receipt.json"]: raise ValueError("Recovery origin receipt changed") expected = prior.get("sandbox_running", prior.get("sandbox_before", {})) stopped = prior.get("sandbox_after", {}) @@ -1357,6 +1769,21 @@ def save_journal(): owner.command("download", profile["sandbox_name"], receipt["remote_artifacts"], str(output / "results")) receipt["download_complete"] = True receipt["evidence"] = verify_recovered_artifacts(output / "results", task, source_files) + if task.get("session"): + # Execute only the retained, hash-bound runner's inspection function. + remote = str(PurePosixPath(original["remote_artifacts"]).parent) + payload = safe_archive_files((Path(failed_directory) / "inputs.tar").read_bytes()) + script = "import hashlib,json,pathlib,runpy,sys; p=pathlib.Path(sys.argv[1]); assert hashlib.sha256(p.read_bytes()).hexdigest()==sys.argv[2]; t=p.parent/'task.json'; assert hashlib.sha256(t.read_bytes()).hexdigest()==sys.argv[3]; m=runpy.run_path(str(p)); print(json.dumps(m['inspect_saved_conversation'](p.parent,json.loads(t.read_text()),sys.argv[4]=='true')))" + owner.verify() + inspected = owner.command("exec", profile["sandbox_name"], "--no-login-shell", "--no-tty", "--timeout", "60", "--", profile.get("python", "python3"), "-c", script, remote + "/coordinate.py", digest(payload["coordinate.py"]), digest(payload["task.json"]), "true" if reconcile_conversation else "false") + if len(inspected.stdout.encode()) > 1024 * 1024: + raise ValueError("Conversation inspection exceeds bound") + inspection = json.loads(inspected.stdout) + write_private_control(output / "conversation-inspection.json", inspection) + receipt["inspection_sha256"] = digest((output / "conversation-inspection.json").read_bytes()) + checkpoint = inspection.get("checkpoint") + if inspection.get("continuable") is True and (checkpoint == task["session"]["prior"] or receipt["evidence"].get("conversation_valid") is True and checkpoint == read_json(output / "results/conversation.json")): + receipt.update(conversation_valid=True, continuation_checkpoint=checkpoint) receipt["outcome"] = "recovered_" + receipt["evidence"]["evidence_status"] except BaseException as error: receipt["error"] = str(error) @@ -1366,6 +1793,9 @@ def save_journal(): cleanup_owner(owner, profile, receipt, protected) receipt["ended_at"] = utc_now() receipt["recovery_valid"] = receipt["cleanup_complete"] and receipt.get("protected_unchanged", False) and receipt.get("download_complete", False) and receipt.get("evidence", {}).get("available_bindings_valid", False) + if task.get("session"): + receipt["recovery_valid"] = receipt["recovery_valid"] and "inspection_sha256" in receipt and "error" not in receipt + receipt["conversation_valid"] = receipt["conversation_valid"] and receipt["recovery_valid"] and "error" not in receipt save_journal() write_new_json(output / "receipt.json", receipt) return receipt @@ -1379,12 +1809,21 @@ def main(argv=None): run.add_argument("--profile", type=Path, default=Path.home() / ".config/codex-pi-coordination/profile.json") run.add_argument("--output", type=Path, required=True) run.add_argument("--lock-root", type=Path, default=Path.home() / ".local/state/codex-pi-coordination") + run.add_argument("--save-session", action="store_true") + continuation = sub.add_parser("continue", help="Assign a fresh task to an exact saved Pi conversation") + continuation.add_argument("task", type=Path) + continuation.add_argument("--from", dest="previous_directory", type=Path, required=True) + continuation.add_argument("--profile", type=Path, default=Path.home() / ".config/codex-pi-coordination/profile.json") + continuation.add_argument("--output", type=Path, required=True) + continuation.add_argument("--lock-root", type=Path, default=Path.home() / ".local/state/codex-pi-coordination") configure = sub.add_parser("configure", help="Register an existing private profile as the default, without replacing one") configure.add_argument("--profile", type=Path, required=True) capabilities = sub.add_parser("capabilities", help="Inspect sanitized model capabilities without sending a prompt") capabilities.add_argument("--profile", type=Path, default=Path.home() / ".config/codex-pi-coordination/profile.json") capabilities.add_argument("--output", type=Path, required=True) capabilities.add_argument("--lock-root", type=Path, default=Path.home() / ".local/state/codex-pi-coordination") + capabilities.add_argument("--provider") + capabilities.add_argument("--model") recover = sub.add_parser("recover", help="Download evidence from the latest stopped failed run without rerunning it") recover.add_argument("failed_directory", type=Path) recover.add_argument("--profile", type=Path, default=Path.home() / ".config/codex-pi-coordination/profile.json") @@ -1395,18 +1834,29 @@ def main(argv=None): reconcile = sub.add_parser("reconcile", help="Reconcile unresolved custody only after the exact sandbox is Stopped") reconcile.add_argument("--profile", type=Path, default=Path.home() / ".config/codex-pi-coordination/profile.json") reconcile.add_argument("--lock-root", type=Path, default=Path.home() / ".local/state/codex-pi-coordination") + reconcile.add_argument("--from", dest="failed_directory", type=Path) + reconcile.add_argument("--output", type=Path) args = parser.parse_args(argv) try: if args.operation == "configure": print(json.dumps(configure_profile(args.profile))) return 0 if args.operation == "capabilities": - receipt = run_task(None, args.profile, args.output, args.lock_root, capabilities_only=True) + selected = None + if args.provider is not None or args.model is not None: + selected = {"provider": model_identifier(args.provider), "model": model_identifier(args.model)} + receipt = run_task(None, args.profile, args.output, args.lock_root, capabilities_only=True, selected_model=selected) print(json.dumps({"run_id": receipt["run_id"], "capabilities_valid": receipt["capabilities_valid"], "delivery_valid": False, "acceptance": "not_granted", "receipt": str(args.output / "receipt.json")})) return 0 if receipt["capabilities_valid"] else 1 if args.operation == "worker": return worker(args.root) if args.operation == "reconcile": + if args.failed_directory is not None or args.output is not None: + if args.failed_directory is None or args.output is None: + raise ValueError("Conversation reconciliation requires --from and --output together") + receipt = recover_task(args.failed_directory, args.profile, args.output, args.lock_root, reconcile_conversation=True) + print(json.dumps({"recovery_valid": receipt["recovery_valid"], "conversation_valid": receipt.get("conversation_valid", False), "delivery_valid": False, "acceptance": "not_granted", "receipt": str(args.output / "receipt.json")})) + return 0 if receipt["recovery_valid"] else 1 profile = profile_settings(args.profile) with exclusive_owner(profile, args.lock_root) as journal: prior = read_json(journal) @@ -1420,9 +1870,9 @@ def main(argv=None): return 0 if args.operation == "recover": receipt = recover_task(args.failed_directory, args.profile, args.output, args.lock_root) - print(json.dumps({"run_id": receipt["run_id"], "failed_run_id": receipt["failed_run_id"], "outcome": receipt["outcome"], "recovery_valid": receipt["recovery_valid"], "task_delivery_valid": False, "acceptance": "not_granted", "receipt": str(args.output / "receipt.json")})) + print(json.dumps({"run_id": receipt["run_id"], "failed_run_id": receipt["failed_run_id"], "outcome": receipt["outcome"], "recovery_valid": receipt["recovery_valid"], **({"conversation_valid": receipt["conversation_valid"]} if "conversation_valid" in receipt else {}), "task_delivery_valid": False, "acceptance": "not_granted", "receipt": str(args.output / "receipt.json")})) return 0 if receipt["recovery_valid"] else 1 - receipt = run_task(args.task, args.profile, args.output, args.lock_root) + receipt = run_task(args.task, args.profile, args.output, args.lock_root, save_session=getattr(args, "save_session", False), previous_directory=getattr(args, "previous_directory", None)) print(json.dumps({"run_id": receipt["run_id"], "outcome": receipt["outcome"], "delivery_valid": receipt["delivery_valid"], "receipt": str(args.output / "receipt.json")})) return 0 if receipt["delivery_valid"] else 1 except (OSError, ValueError, tarfile.TarError, subprocess.SubprocessError) as error: diff --git a/plugins/codex-pi-coordination/skills/codex-pi-coordination/SKILL.md b/plugins/codex-pi-coordination/skills/codex-pi-coordination/SKILL.md index 333678f..67fa7c9 100644 --- a/plugins/codex-pi-coordination/skills/codex-pi-coordination/SKILL.md +++ b/plugins/codex-pi-coordination/skills/codex-pi-coordination/SKILL.md @@ -1,6 +1,6 @@ --- name: codex-pi-coordination -description: Delegate scoped work from Codex to Pi in a caller-owned NVIDIA OpenShell sandbox, configure a default profile, discover model/thinking capabilities, inspect returned work, or recover the latest stopped failed run without rerunning it. Use for Codex-Pi collaboration or Pi/GLM assistance; model selection and acceptance remain with the coordinator. +description: Delegate scoped work from Codex to Pi in a caller-owned NVIDIA OpenShell sandbox, configure a default profile, discover exact-model thinking capabilities, continue an owned saved Pi conversation with a new assignment, inspect returned work, or recover a stopped failed run without replaying it. Use for Codex-Pi collaboration or Pi/GLM assistance; model selection and acceptance remain with the coordinator. --- # Codex and Pi coordination @@ -8,7 +8,7 @@ description: Delegate scoped work from Codex to Pi in a caller-owned NVIDIA Open Codex owns task scope, integration and acceptance. Pi performs one bounded assignment and returns work. Model selection comes from a private runtime profile or exact per-task options, including GLM when the configured Pi runtime -supports it. Selection affects only the ephemeral child; this workflow does not +supports it. Selection affects only the dispatched child; this workflow does not change routes, provider configuration or global model settings. ## Prepare @@ -58,7 +58,20 @@ This uses the same owned disposable lifecycle with zero prompts, tools or extensions. It reports actual idle model/thinking settings without applying profile defaults or sending configuration setters. `capabilities_valid` reports metadata and cleanup validity, never task delivery, real-edit qualification or -acceptance. +acceptance. Default Run needs no discovery step or model selection. + +To inspect a particular model, supply both selectors: + +```sh +python3 ../../scripts/coordinate.py capabilities --provider configured-provider --model exact-model-id --output /private/evidence/selected-capabilities +``` + +This selected-model query uses an ephemeral child with no prompt, tools or +extension. It may send an exact model setter, never a thinking setter. Inspect +supported levels, observed current thinking and profile-default compatibility. +Even if the profile default is unsupported, discovery can report the actual +levels; execution still requires an explicit supported choice or a supported +default. Metadata does not authorize a run or change provider/global settings. ## Run and inspect @@ -67,8 +80,8 @@ together for an exact selection; `thinking` may appear alone. Omitted fields inherit the profile. Default means omission, never the literal `default`. Reject `auto`, `dynamic`, unknown/ambiguous models and unsupported thinking; `max` requires actual support. There is no fallback or provider provisioning. -Version-1 inputs remain supported, but every new run uses native RPC and -`--no-session`. Saved-session continuation remains future work (P1b). +Version-1 inputs remain supported. Ordinary runs keep native RPC with +`--no-session`; saved mode is an explicit choice and uses native version 3. ```sh python3 ../../scripts/coordinate.py run task.json --output /private/evidence/new-run @@ -90,9 +103,44 @@ diagnostic output, not protocol. Pi's handoff is a self-report. `delivery_valid` means the bounded return/cleanup contract completed; it grants no acceptance, merge, deployment or proof of research truth. +## Save and continue a conversation + +Choose saved mode only when the task benefits from retained conversation. Both +dispatches need explicit committed repository sources: + +```sh +python3 ../../scripts/coordinate.py run first-task.json --save-session --output /private/evidence/first-run +``` + +Verify the returned work and stopped/protected custody. Integrate reviewed +changes through the repository workflow, commit them, and prepare a new task +manifest at that revision with its own scope, checks, options and budget: + +```sh +python3 ../../scripts/coordinate.py continue next-task.json --from /private/evidence/first-run --output /private/evidence/next-run +``` + +Use the verified prior output, never a guessed session path or partial ID. +The runner uses official `--session` and matching `--session-dir` with one stable +workspace path. It verifies the complete current-version session, full ID, +prior byte/hash/prefix bindings and full workspace file/directory modes. A fresh +process loads the current task/extension and resets counters and handoff state; +previous conversation text grants no current scope or claim authority. + +Each dispatch retains separate artifacts. Workspace replacement stages the new +committed source, records intent before renames and preserves the old tree. +Missing, stale, duplicate or drifted state refuses before Pi starts; checking +remote state may require starting and stopping the managed owner. Partial/mixed transitions +remain held; do not reset files, rewrite a session header, retry a prompt or +silently start a new conversation. A successful saved return alone does not +integrate changes or satisfy Anvil's native proof/approval gates. + +## Recover and reconcile + On a failed/nonzero OpenShell run or timeout, the runner immediately requests a managed stop and skips downloading artifacts. After confirmed stopped custody, -recover the latest failed run with its original profile and shared lock root: +recover a saved failure, or the latest ephemeral failure, with its original +profile and shared lock root: ```sh python3 ../../scripts/coordinate.py recover /private/evidence/failed-run --output /private/evidence/recovery @@ -100,18 +148,44 @@ python3 ../../scripts/coordinate.py recover /private/evidence/failed-run --outpu The runtime owner must have qualified the sandbox entrypoint as idle on restart. Recovery starts a fresh idle main instance, downloads only the bound prior -results, and stops it. It never launches Pi, a worker or verification checks. +results, and stops it. Saved recovery additionally runs the retained bounded +conversation inspector. It never launches Pi or reruns task verification checks. Inspect the separate recovery receipt and evidence status. `recovery_valid` and CLI exit zero mean retrieval and available bindings passed with stopped cleanup; task delivery stays invalid. `recovered_partial` leaves absent check exits and worker outcomes unknown. Preserve contradictory artifacts as a failed integrity gate. Never rewrite a failed receipt to use the successful-return verifier. +For a saved run, require the separate `conversation_valid` field before using +that recovery directory as Continue's `--from`. Failed checks can coexist with a +verified advanced conversation, but the task still failed. Missing acknowledgement, +partial history or incomplete terminal evidence never authorizes prompt replay. + +For an interrupted saved-workspace transition: + +```sh +python3 ../../scripts/coordinate.py reconcile --from /private/evidence/failed-run --output /private/evidence/reconciliation +``` + +This inspects the exact retained intent and may certify an unchanged old tree, +archiving that intent without changing workspace bytes. A fully switched new +tree without verified terminal evidence stays noncontinuable; mixed, missing or +foreign state stays held. There is no rollback or automatic restore. Inspect +`conversation_valid` separately from `recovery_valid` and CLI exit status. +The same `reconcile --from` form also inspects a successful saved run after +intervening metadata or a refused stale continuation. It verifies the terminal +checkpoint without Pi, checks or a workspace switch. `recover` still accepts +only failed runs; a successful inspection does not grant another delivery. + Require confirmed managed stop and unchanged protected resources. An exec timeout does not prove remote termination. Unknown custody blocks another run. After the exact sandbox is independently confirmed Stopped, `reconcile` records -that readback. Never delete a lock or receipt to make a retry appear fresh. -Preserve failed/partial artifacts; rework is a new assignment. +that readback using the no-argument command. This does not certify a saved +workspace transition. Never delete a lock or receipt to make a retry appear fresh. +Preserve failed/partial artifacts; rework is a new assignment. Observe the +16 MiB session, 1 MiB checkpoint/control and 1 GiB retained-remote limits. +Overflow refuses further work; do not truncate history or prune prior evidence. +These observed bounds are not a hard filesystem quota. ## Coordinate the next step @@ -125,8 +199,11 @@ Preserve failed/partial artifacts; rework is a new assignment. physical capacity; retain failed measurements. Follow-up work gets a new manifest with relevant prior artifacts and the current -revision; it does not resume a saved Pi conversation. Never retarget evidence or -infer authority for additional work. Reuse ship-loop for delivery and the target +revision. Use Continue only for a verified saved checkpoint; otherwise a new +Run is a separate conversation. Never retarget evidence or infer authority for +additional work. Keep synthetic tests distinct from the pending installed +OpenShell saved-run/continue and selected-model qualification. Anvil CLI/web +claims, native checkout proofs and approval journeys remain separate gates. Reuse ship-loop for delivery and the target repository's benchmark/journey commands. The plugin uses explicit task files and a native Pi extension; it launches no recursive agents, second Codex process or persistent broker. diff --git a/plugins/codex-pi-coordination/skills/codex-pi-coordination/references/task-contract.md b/plugins/codex-pi-coordination/skills/codex-pi-coordination/references/task-contract.md index 17afdf3..0cff722 100644 --- a/plugins/codex-pi-coordination/skills/codex-pi-coordination/references/task-contract.md +++ b/plugins/codex-pi-coordination/skills/codex-pi-coordination/references/task-contract.md @@ -28,7 +28,10 @@ dependencies; the extension has no npm dependencies. Examples below are syntheti Required: version, task_id, kind, instructions, writable_paths and checks. Repository/revision are optional together. Kinds: implementation, research, review, validation. Writable paths are exact relative files, not globs or -directories. Research may return `findings.md`; read-only review/validation may +directories. Each relative path is limited to 1,024 UTF-16 code units in both +Python and the extension. Malformed Unicode, Unicode spaces that would be +normalized, traversal and noncanonical spellings refuse before owner work; +paths are never silently rewritten. Research may return `findings.md`; read-only review/validation may use no writable files and report findings through the handoff tool. Commands are coordinator-authored argv, executed once after Pi exits; they share the overall deadline and retain actual logs and exit status. @@ -52,12 +55,15 @@ selected runtime/model advertises it. Version-2 task IDs match `[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}`. Version-1 user inputs keep their original fields and 80-character ID pattern `[A-Za-z0-9][A-Za-z0-9_.-]{0,79}`; they cannot contain `run_options`. New runs -normalize either input version into the current native contract. Historical -version-1 return/recovery artifacts keep their original interpretation. +normalize either input version into native version 2 for ephemeral work. +Saved Run/Continue and selected-model metadata use explicit native version-3 +variants; users still submit public version-1/2 tasks. Historical version-1/2 +return/recovery artifacts keep their original interpretation. Public assignments never supply `run_id`. Native artifacts carry a separate coordinator-generated run identity; the extension preserves its historical -128-character pattern `[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}` in both versions. +128-character pattern `[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}`; saved descriptors further +require the generated 32-character hexadecimal dispatch identity. The version-1 task-ID limit does not apply to that native field. Both ID fields must match their entire pattern, without trailing newlines. @@ -117,14 +123,19 @@ the runner skips artifact download. `receipt.json` retains `remote_artifacts` for the supported `recover` command after stopped custody is confirmed. Do not collect remote artifacts while failed work may still be active. The runtime owner handles retention. Remote runs remain for diagnosis; -preparation refuses when retained run data reaches 1 GiB. +preparation enforces a 1 GiB retained-material bound; saved workers also observe +it during Pi and trusted-check execution and before sealing a checkpoint. +Saved session files are limited to 16 MiB and checkpoint/control JSON to 1 MiB. +Overflow refuses delivery/continuation without truncating or pruning prior data. +The remote bound includes retained source, dispatch and conversation material; +it is an observed limit, not a hard filesystem quota or hostile-process guarantee. ## Native RPC execution and capabilities -Every new run starts an ephemeral `--no-session` native RPC child in the owned -OpenShell worker, with only the explicit coordination extension and scoped tools. -Saved-session continuation is future work (P1b); fresh runs do not resume an -interactive process or official conversation file. +An ordinary `run TASK --output NEW_DIRECTORY` starts an ephemeral `--no-session` +native RPC child in the owned OpenShell worker, with only the explicit +coordination extension and scoped tools. Saved Run and Continue use the official +session path described below; neither attaches to an interactive process. Before the single task prompt, the runner queries available models, selects an exact provider/model, queries `get_available_thinking_levels`, validates and @@ -166,7 +177,80 @@ setters and does not require profile defaults to be supported by the current mod Task runs still require exact supported options before their one prompt. Its CLI reports `capabilities_valid`; the receipt retains `delivery_valid: false` and `acceptance: not_granted`. Metadata discovery is separate from actual setup, -model execution and real-edit qualification. +model execution and real-edit qualification. Default Run does not require a +capability query. + +For selected-model metadata, supply an exact pair: + +```sh +python3 ../../scripts/coordinate.py capabilities --provider configured-provider --model exact-model-id --output /private/evidence/selected-capabilities +``` + +Missing, malformed, unavailable or duplicate selector matches refuse. Native +version 3 uses `operation: capabilities_selected`, separate from execution +options. It starts an ephemeral no-session child without tools or extensions, +queries initial state/catalog, sends official non-persistent `set_model` only +if needed, then obtains that model's thinking levels and exact idle readback. +It permits the narrowly correlated model-induced thinking event, but sends no +`set_thinking_level` and no prompt. Evidence retains the selected identity, +observed current thinking/levels and profile-default compatibility. Unsupported +profile thinking does not block this metadata query; ordinary Run/Continue +still refuse that default unless the task explicitly selects a supported level. +Observed metadata is not execution approval, a fallback choice or an invented +`auto`/`dynamic` capability. Existing no-option metadata remains native version 2 +and sends no setters. + +## Official saved Run and Continue + +```sh +python3 ../../scripts/coordinate.py run first-task.json --save-session --output /private/evidence/first-run +python3 ../../scripts/coordinate.py continue next-task.json --from /private/evidence/first-run --output /private/evidence/next-run +``` + +Before Continue, inspect and integrate the first approved return through the +repository workflow, commit it, and set the new task's explicit repository and +revision. Saved dispatches require committed Git source. The public task does +not carry a session path or executable. The host derives a native version-3 +`run` or `continue` variant with an owned conversation ID, stable workspace, +exact session file and prior checkpoint digest/run identity. Each dispatch has +new task/source hashes and separate controls/results. Anvil's outer request +must bind its current task, actor, claim and generation separately. + +The first saved run exclusively creates its conversation and requires the +session path to be absent. Pi receives exact absolute `--session FILE` and +matching `--session-dir DIRECTORY`, without `--no-session`. Continue requires +a bounded nonempty regular file containing complete JSONL, a current version-3 +header, full official ID, the stable cwd and persisted assistant history. +Missing/empty/header-only, malformed, partial, foreign, symlinked, migrated or +drifted history refuses before Pi starts. RPC and extension readbacks must match +the actual session ID/file/cwd. There is no latest-session lookup, partial-ID +match, `--continue`/`--resume` shortcut, fork, header rewrite or cwd shim. + +Before switching source, verify the complete old workspace bytes and all file +and directory modes against its terminal checkpoint, including check-created +files. Stage the new committed source separately with exact modes. Write an +intent naming old/staged/new manifests before any rename; preserve the old +workspace under its dispatch identity and move the staged source to the same +stable cwd. Duplicate/stale `--from` or a pending/mixed transition refuses. +No automatic rollback, deletion or reset resolves uncertain outcomes. + +A fresh Pi process loads only the current task and coordination extension. +Session-start/before-agent-start evidence binds official session ID, stable cwd, +dispatch and task hash; counters and handoff state restart for this dispatch. +The complete current assignment, source, writable scope, checks, options and +limits supply authority. Historical conversation content grants none of them. +Exact supported options and idle, noncompacting, empty-queue session state are +required before the single prompt; uncertain acknowledgement is never replayed. + +After settled handoff, idle readback, orderly exit and extension shutdown, run +the fresh checks and record terminal session/workspace bindings. Saved receipts +include before/after session byte lengths and hashes, unchanged header identity, +the prior-prefix hash, prior/current dispatch/task hashes, source revision and +the complete final workspace manifest. The checkpoint advances only with those +bindings. The returned source-change manifest remains separate and does not +turn check-created files into approved source changes. The saved conversation +file stays in owned remote storage; current dispatch events and model output +remain private evidence and must not be published. ## Return and trust @@ -181,13 +265,14 @@ New return evidence includes `rpc-events.jsonl` (sanitized control transcript), `rpc-configuration.json`. Check logs retain `.log`, including the valid name `pi-stderr`; started/result receipts and hash checks remain unchanged. The worker receipt's `configuration` binds requested options, profile defaults, -effective options, supported levels, ephemeral session ID, prompt admission, +effective options, supported levels, actual session ID/file variant, prompt admission, settlement, shutdown and RPC/stderr hashes. Input/task/source hashes bind this -evidence to the assignment. The version-2 extension's `run_configuration` event +evidence to the assignment. The extension's `run_configuration` event at the first `before_agent_start` records actual provider/model from its context and thinking from `pi.getThinkingLevel()`. `task_loaded.model` records startup state and does not prove the later RPC selection. Normal verification and -recovery decode v1/v2 explicitly; old evidence cannot acquire these new claims. +recovery decode native versions 1/2/3 explicitly; old evidence cannot acquire +new saved-session claims. `model-report.json` is Pi's task-bound self-report. `extension-events.jsonl` records task loading, budget/tool observations and lifecycle events. These are @@ -220,15 +305,20 @@ remain the process boundary. uses the normal `--profile` and `--lock-root` options. Keep the failed directory's `started.json`, `receipt.json` and `inputs.tar` unchanged. Recovery validates their hashes, safe archive members, task/source bindings and derived remote results -path before any lifecycle action. The latest owner journal must bind that failed -run and input with completed Stopped custody; a newer assignment, active owner, -identity drift or competing lock refuses. A worker that returned work but failed +path before any lifecycle action. For legacy ephemeral recovery, the latest +owner journal must bind that failed run and input with completed Stopped custody; +a newer assignment refuses. Saved recovery instead binds its independent +conversation checkpoint to fresh resolved Stopped custody, so an intervening +metadata or ephemeral run does not invalidate it. Active owners, identity drift +or competing locks refuse. A worker that returned work but failed cleanup may be recovered after reconciliation; an already-valid delivery may not. The owner must qualify the existing sandbox entrypoint as idle on restart. The runner starts a fresh Ready main instance and performs only a native download, -then verifies its identity, stops it and reads back protected resources. It does -not upload, exec, rerun Pi or rerun checks. For both normal runs and recovery, if a start fails before the fresh +then verifies its identity, stops it and reads back protected resources. +Legacy recovery does not exec a worker. Saved recovery may run the retained, +hash-bound conversation inspector to read checkpoint/session/workspace state; +it never launches Pi or reruns task checks. For both normal runs and recovery, if a start fails before the fresh instance is bound, an unexpected main is not stopped; custody remains unresolved. Unknown cleanup blocks another run until supported Stopped reconciliation. A retry retains the original failed-run identity even after recovery reconciliation. @@ -249,3 +339,45 @@ These checks occur after native download. The download timeout is not a hard pre-download byte or storage quota, and same-user hashes are not an independent issuer attestation. This is recovery from an exclusively owned trusted runtime, not arbitrary historical sandbox browsing or hostile-output containment. + + +For a failed saved dispatch, `conversation_valid` is a separate recovery field. +A failed trusted check can leave a verified advanced session/checkpoint while +`delivery_valid` and `task_delivery_valid` stay false. Only explicit successful +recovery with `conversation_valid: true` supplies a continuation checkpoint; +use that recovery output as `--from` with a newly approved task. Partial session +tails, missing acknowledgement, incomplete shutdown or ambiguous checkpoint +bindings leave continuation unavailable. An earlier valid conversation does not +justify replaying an uncertain task prompt. + +```sh +python3 ../../scripts/coordinate.py reconcile --from /private/evidence/failed-run --output /private/evidence/reconciliation +``` + +This saved-conversation variant requires both `--from` and a new `--output`. +After exact stopped custody, it inspects the retained transition intent and +session/checkpoint binding. An unchanged old tree with the exact staged source +can be certified by archiving its pending intent; workspace/session bytes are +not restored or rewritten. A completed-new tree without verified terminal +model evidence remains noncontinuable. Mixed, missing or foreign state refuses. +The existing no-argument `reconcile` remains a stopped-owner custody readback, +not conversation certification. Preserve all previous journal and dispatch +artifacts; neither path rolls back files, prunes evidence or reruns a prompt. + +`reconcile --from SUCCESSFUL_SAVED_RUN --output NEW_DIRECTORY` additionally +admits a successful native version-3 saved return for terminal inspection. +After an intervening metadata run or refused stale continuation, it verifies +the exact successful session, workspace and checkpoint and returns +`disposition: terminal_checkpoint`. No pending transition is permitted in this +case, and no Pi process, check, source switch or checkpoint advance occurs. +The separate inspection receipt keeps `delivery_valid: false` and +`acceptance: not_granted`; the original successful receipt stays immutable. +Ordinary `recover` remains failed-delivery-only, and successful ephemeral runs +cannot use this saved-conversation inspection variant. + +Synthetic process/file fixtures, installed command discovery, actual default +OpenShell two-edit/same-session qualification and selected-model metadata are +separate checks. The actual installed journeys remain delivery gates. Anvil +must separately validate CLI/web admission, fresh claim bindings, integration, +native checkout proofs, `needs_review` and approval. Plugin sandbox checks and +conversation validity confer no native acceptance, latency or fleet-scale claim. diff --git a/plugins/codex-pi-coordination/tests/extension.test.mjs b/plugins/codex-pi-coordination/tests/extension.test.mjs index a5f474a..74ef1fe 100644 --- a/plugins/codex-pi-coordination/tests/extension.test.mjs +++ b/plugins/codex-pi-coordination/tests/extension.test.mjs @@ -9,13 +9,17 @@ import extension, { checkToolPath, loadTask } from "../extensions/coordination.j function fixture(t, changes = {}) { const root = fs.mkdtempSync(path.join(os.tmpdir(), "coordination-extension-")); t.after(() => fs.rmSync(root, { recursive: true, force: true })); - const workspace = path.join(root, "workspace"); - const output = path.join(root, "output"); - fs.mkdirSync(workspace); - fs.mkdirSync(output); + const runId = changes.version === 3 ? changes.run_id ?? "a".repeat(32) : "run-01"; + const dispatch = changes.version === 3 ? path.join(root, "remote", runId) : root; + const conversation = path.join(root, "remote", "conversations", runId); + const workspace = changes.version === 3 ? path.join(conversation, "workspace") : path.join(root, "workspace"); + const output = changes.version === 3 ? path.join(dispatch, "results") : path.join(root, "output"); + fs.mkdirSync(workspace, { recursive: true }); + fs.mkdirSync(output, { recursive: true }); fs.writeFileSync(path.join(workspace, "input.txt"), "original\n"); - const taskPath = path.join(root, "task.json"); - const task = { version: 1, run_id: "run-01", task_id: "task-01", kind: "review", instructions: "Inspect the supplied input and report limitations.", workspace, output_directory: output, allowed_tools: ["read", "grep", "find", "ls"], writable_paths: [], max_tool_calls: 8, ...changes }; + const taskPath = path.join(dispatch, "task.json"); + const saved = changes.version === 3 ? { session: { conversation_id: runId, directory: conversation, file: path.join(conversation, "session.jsonl"), prior: null, prior_sha256: null } } : {}; + const task = { version: 1, run_id: runId, task_id: "task-01", kind: "review", instructions: "Inspect the supplied input and report limitations.", workspace, output_directory: output, allowed_tools: ["read", "grep", "find", "ls"], writable_paths: [], max_tool_calls: 8, ...saved, ...changes }; fs.writeFileSync(taskPath, JSON.stringify(task)); return { root, task, taskPath, workspace, output }; } @@ -26,6 +30,13 @@ function runtime(taskPath, cwd, allowedTools) { const commands = new Map(); let active = ["read", "grep", "find", "ls", "write", "edit", "bash", "coordination_status", "coordination_handoff"]; const ctx = { cwd, hasUI: false, model: { provider: "fixture-provider", id: "fixture-model" }, aborted: 0, shutdowns: 0, abort() { this.aborted += 1; }, shutdown() { this.shutdowns += 1; } }; + let task; + try { task = JSON.parse(fs.readFileSync(taskPath, "utf8")); } catch { task = {}; } + if (task.version === 3) { + ctx.sessionId = "official-fixture-session"; ctx.sessionFile = task.session.file; + ctx.header = { type: "session", version: 3, id: ctx.sessionId, cwd }; + ctx.sessionManager = { getHeader: () => ctx.header, getCwd: () => ctx.cwd, getSessionId: () => ctx.sessionId, getSessionFile: () => ctx.sessionFile }; + } const pi = { registerFlag() {}, getFlag: () => taskPath, registerTool: (tool) => tools.set(tool.name, tool), @@ -52,6 +63,80 @@ function runtime(taskPath, cwd, allowedTools) { const handoff = (changed_files = []) => ({ status: "completed", summary: "Inspected the provided fixture.", evidence: ["input.txt"], changed_files, limitations: ["Model self-report; external checks remain required."] }); const events = (f) => fs.readFileSync(path.join(f.output, "extension-events.jsonl"), "utf8").trim().split("\n").map(JSON.parse); +test("relative paths honor exact UTF-16 bounds before the first prompt", async (t) => { + const ascii = ("a".repeat(200) + "/").repeat(5); + const astral = ("\u{1f600}".repeat(50) + "/").repeat(10); + for (const version of [1, 2, 3]) { + const base = { version, ...(version >= 2 ? { operation: "run", run_options: {}, runtime_defaults: { model: "fixture-provider/fixture-model", thinking: "high" } } : {}) }; + for (const [name, valid] of [[ascii + "b".repeat(19), true], [ascii + "b".repeat(20), false], [astral + "b".repeat(14), true], [astral + "b".repeat(15), false], ["bad\ud800.txt", false], ["bad\udfff.txt", false]]) { + const f = fixture(t, { ...base, writable_paths: [name] }); + if (!valid) { + assert.throws(() => loadTask(f.taskPath, f.workspace), /relative file|Relative file/); + continue; + } + assert.equal(name.length, 1024); + fs.mkdirSync(path.dirname(path.join(f.workspace, name)), { recursive: true }); + const r = runtime(f.taskPath, f.workspace); + await r.emit("session_start"); + assert.ok((await r.emit("before_agent_start", { systemPrompt: "original" })).systemPrompt); + assert.equal(r.ctx.aborted, 0); + await r.emit("session_shutdown"); + } + } +}); + +test("saved dispatch binds official identity and fresh task at load and before prompt", async (t) => { + const base = { version: 3, operation: "run", run_options: { thinking: "low" }, runtime_defaults: { model: "fixture-provider/fixture-model", thinking: "high" }, instructions: "Current task overrides historical conversation authority." }; + const f = fixture(t, base); + const r = runtime(f.taskPath, f.workspace); r.ctx.thinking = "low"; + await r.emit("session_start"); + const prompt = await r.emit("before_agent_start", { systemPrompt: "Prior context" }); + assert.ok(prompt.systemPrompt.includes(base.instructions)); + assert.equal(events(f)[0].tool_calls, 0); + assert.equal(events(f)[0].turns, 0); + assert.equal(events(f)[0].handed_off, false); + assert.deepEqual(events(f)[0].session, { id: r.ctx.sessionId, file: f.task.session.file, cwd: f.workspace, version: 3 }); + await r.emit("session_shutdown"); + for (const change of [ctx => { ctx.sessionId = "foreign"; }, ctx => { ctx.sessionFile += ".foreign"; }, ctx => { ctx.header.version = 2; }, ctx => { ctx.header.cwd += "/foreign"; }]) { + const bad = fixture(t, base); const runtimeBad = runtime(bad.taskPath, bad.workspace); runtimeBad.ctx.thinking = "low"; + await runtimeBad.emit("session_start"); change(runtimeBad.ctx); + assert.equal(await runtimeBad.emit("before_agent_start", { systemPrompt: "old" }), undefined); + assert.equal(runtimeBad.ctx.aborted, 1); + assert.equal(events(bad).at(-1).code, "session_mismatch"); + await runtimeBad.emit("session_shutdown"); + } +}); + +test("continued dispatch reuses official identity but only grants fresh scope and budgets", async (t) => { + const base = { version: 3, operation: "continue", run_options: {}, runtime_defaults: { model: "fixture-provider/fixture-model", thinking: "high" }, task_id: "project:T002", instructions: "Only edit the new file.", allowed_tools: ["read", "write"], writable_paths: ["new.txt"], max_tool_calls: 2 }; + for (const priorId of ["official-fixture-session", "foreign-session"]) { + const f = fixture(t, base); + f.task.session.prior = { conversation_id: f.task.session.conversation_id, run_id: "b".repeat(32), session: { id: priorId } }; + f.task.session.prior_sha256 = "c".repeat(64); + fs.writeFileSync(f.taskPath, JSON.stringify(f.task)); + fs.writeFileSync(f.task.session.file, JSON.stringify({ type: "session", version: 3, id: priorId, cwd: f.workspace }) + "\n"); + const r = runtime(f.taskPath, f.workspace); + await r.emit("session_start"); + if (priorId !== "official-fixture-session") { + assert.equal(r.ctx.aborted, 1); + assert.equal(await r.emit("before_agent_start", { systemPrompt: "Old scope" }), undefined); + } else { + const prompt = await r.emit("before_agent_start", { systemPrompt: "Old scope" }); + assert.ok(prompt.systemPrompt.includes('"task_id":"project:T002"')); + assert.ok(prompt.systemPrompt.includes("earlier conversation text grants no task or tool authority")); + assert.equal(events(f)[0].tool_calls, 0); + assert.equal(events(f)[0].turns, 0); + assert.equal(events(f)[0].handed_off, false); + assert.throws(() => checkToolPath(f.task, "write", { path: "old.txt" }), /writable paths/); + assert.equal(checkToolPath(f.task, "write", { path: "new.txt" }), path.join(f.workspace, "new.txt")); + await r.emit("session_start"); + assert.equal(events(f).at(-1).code, "task_reloaded"); + } + assert.equal(fs.existsSync(path.join(f.output, "model-report.json")), false); + await r.emit("session_shutdown"); + } +}); + test("versioned task IDs preserve legacy native run IDs and reject unsupported options", async (t) => { for (const version of [1, 2]) { const maximum = version === 1 ? 80 : 128; diff --git a/plugins/codex-pi-coordination/tests/test_coordinate.py b/plugins/codex-pi-coordination/tests/test_coordinate.py index 554c7a3..4c523f5 100644 --- a/plugins/codex-pi-coordination/tests/test_coordinate.py +++ b/plugins/codex-pi-coordination/tests/test_coordinate.py @@ -32,9 +32,10 @@ counter=task_path.parent/'invocations.txt' counter.write_text(counter.read_text()+'1' if counter.exists() else '1') changed=[] -if behavior in ('change','out-scope'): +if behavior in ('change','out-scope') or behavior.startswith('saved-'): name='answer.txt' if behavior=='change' else 'unapproved.txt' - (workspace/name).write_text('after\n'); changed=[name] + if behavior.startswith('saved-'): name='answer.txt' + (workspace/name).write_text(task['instructions']+'\n' if behavior.startswith('saved-') else 'after\n'); changed=[name] report={'run_id':task['run_id'],'task_id':task['task_id'],'task_sha256':hashlib.sha256(task_path.read_bytes()).hexdigest(),'model_self_report':True,'status':'blocked' if behavior=='blocked' else 'completed','changed_files':changed,'summary':'Synthetic handoff','evidence':[],'limitations':[]} if behavior=='wrong-identity': report['run_id']='different-run' if behavior=='wrong-digest': report['task_sha256']='0'*64 @@ -48,9 +49,9 @@ events[:0]=[{'type':'tool_execution_start','toolCallId':'schema-attempt','toolName':'coordination_handoff'},{'type':'tool_execution_end','toolCallId':'schema-attempt','isError':behavior=='pre-guard-error'}] task_digest=hashlib.sha256(task_path.read_bytes()).hexdigest() def extension_event(kind, calls=1, turns=1, handed_off=True, **fields): - return {'type':kind,'at':'2000-01-01T00:00:00Z','active':True,'run_id':task['run_id'],'task_id':task['task_id'],'task_sha256':task_digest,'tool_calls':calls,'turns':turns,'handed_off':handed_off,**fields} + return {'type':kind,'at':'2000-01-01T00:00:00Z','active':True,'run_id':task['run_id'],'task_id':task['task_id'],'task_sha256':task_digest,'tool_calls':calls,'turns':turns,'handed_off':handed_off,**({'session':rpc_saved_identity} if task['version']==3 else {}),**fields} extension_events=[extension_event('task_loaded',0,0,False),extension_event('tool_call',handed_off=False,tool_name='coordination_handoff',tool_call_id='call-1'),extension_event('handoff',reported_status=report['status']),extension_event('agent_settled'),extension_event('session_shutdown')] -if task['version']==2: +if task['version'] in (2,3): extension_events.insert(1,extension_event('run_configuration',0,0,False,configuration=rpc_effective)) if behavior=='extension-refused': extension_events.insert(3,extension_event('refused',failure={'code':'task_unavailable','message':'No further tools'},code='task_unavailable')) if behavior=='extension-failure': extension_events[-1]['failure']={'code':'tool_budget_exhausted','message':'Budget exhausted'} @@ -74,18 +75,44 @@ def extension_event(kind, calls=1, turns=1, handed_off=True, **fields): ''' FAKE_RPC = 'PRINT_FIXTURE = ' + repr(FAKE_PI) + '\n' + r''' -import json, pathlib, sys, os +import json, pathlib, sys, os, uuid behavior = sys.argv[1] requests_file = pathlib.Path(__file__).with_suffix('.requests.jsonl') model = {'provider':'example','id':'model','headers':{'Authorization':'synthetic-private-marker'},'baseUrl':'https://synthetic.invalid/private'} thinking = 'high' levels = ['off','minimal','low','medium','high','xhigh','max'] if behavior=='off-only': thinking='off';levels=['off'] +session_path = pathlib.Path(sys.argv[sys.argv.index('--session')+1]) if '--session' in sys.argv else None +session_id = 'session-one' +entries = [] +if session_path: + assert '--no-session' not in sys.argv + assert str(session_path.parent) == sys.argv[sys.argv.index('--session-dir')+1] + if session_path.exists(): + entries = [json.loads(line) for line in session_path.read_text().splitlines()] + assert entries[0]['cwd'] == os.getcwd() + for entry in entries[1:]: + if entry['type']=='model_change': model={'provider':entry['provider'],'id':entry['modelId']} + if entry['type']=='thinking_level_change': thinking=entry['thinkingLevel'] + else: + entries=[{'type':'session','version':3,'id':str(uuid.uuid4()),'timestamp':'2000-01-01T00:00:00Z','cwd':os.getcwd()}] + session_id=entries[0]['id'] + assert not session_path.exists() or session_path.stat().st_size +def persist_entry(kind, **fields): + if not session_path: return + entry={'type':kind,'id':uuid.uuid4().hex[:8],'parentId':entries[-1].get('id') if len(entries)>1 else None,'timestamp':'2000-01-01T00:00:00Z',**fields} + entries.append(entry) + if session_path.exists(): + with session_path.open('a') as stream: stream.write(json.dumps(entry)+'\n') + elif any(item.get('message',{}).get('role')=='assistant' for item in entries): + with session_path.open('x') as stream: + for item in entries: stream.write(json.dumps(item)+'\n') held = None def change_thinking(level): global thinking if level == thinking: return thinking = level + persist_entry('thinking_level_change',thinkingLevel=level) event={'type':'thinking_level_changed','level':level,'private_metadata':'synthetic-private-marker'} if behavior=='malformed-configuration': event['level']=[] if behavior=='agent-before-prompt': event={'type':'agent_start'} @@ -113,24 +140,34 @@ def reply(request, data=None): if command=='get_available_models': if behavior=='unsolicited-configuration': print(json.dumps({'type':'thinking_level_changed','level':'low'}),flush=True) data={'models':[model,{'provider':'second','id':'model-two','headers':{'secret':'synthetic-private-marker'}}]} - if behavior=='out-of-order': held=(request,data);continue + if behavior=='selected-duplicate-model': data['models'].append(dict(data['models'][1])) + if behavior in ('out-of-order','selected-out-of-order'): held=(request,data);continue elif command=='get_state': - data={'model':model,'thinkingLevel':thinking,'sessionId':'session-one','sessionFile':None,'isStreaming':False,'isCompacting':False,'pendingMessageCount':0} + data={'model':model,'thinkingLevel':thinking,'sessionId':session_id,'sessionFile':str(session_path) if session_path else None,'isStreaming':False,'isCompacting':False,'pendingMessageCount':0} if behavior=='busy': data['pendingMessageCount']=1 + if behavior=='saved-wrong-id': data['sessionId']='foreign-session' + if behavior=='selected-wrong-model' and model['provider']=='second': data['model']={'provider':'foreign','id':'model'} + if behavior=='selected-wrong-level' and model['provider']=='second': data['thinkingLevel']='high' elif command=='get_available_thinking_levels': data={'levels':['low'] if behavior=='only-low' else levels} elif command=='set_model': model={'provider':request['provider'],'id':request['modelId']};data=model - change_thinking('low') + persist_entry('model_change',provider=model['provider'],modelId=model['id']) + if behavior.startswith('selected-') and model['provider']=='second': + levels=['off'];change_thinking('off') + else: change_thinking('low') elif command=='set_thinking_level': change_thinking('low' if behavior=='clamped' else request['level']);data=None elif command=='prompt': if behavior=='no-prompt-ack': continue reply(request) - namespace={'rpc_effective':{'provider':model['provider'],'model':model['id'],'thinking':thinking}} + namespace={'rpc_effective':{'provider':model['provider'],'model':model['id'],'thinking':thinking},'rpc_saved_identity':{'id':session_id,'file':str(session_path),'cwd':os.getcwd(),'version':3}} try: exec(PRINT_FIXTURE,namespace) except SystemExit as result: if result.code: raise - if behavior!='no-settlement': print(json.dumps({'type':'agent_settled'}),flush=True) + persist_entry('message',message={'role':'assistant','content':[{'type':'text','text':'Synthetic completed dispatch'}]}) + if behavior=='saved-partial-tail': + with session_path.open('a') as stream: stream.write('{') + if behavior not in ('no-settlement','saved-no-settlement'): print(json.dumps({'type':'agent_settled'}),flush=True) continue else: raise AssertionError(command) reply(request,data) @@ -182,6 +219,53 @@ def native_extension_load_results(cases): class ContractTests(unittest.TestCase): + def test_selected_metadata_requires_paired_valid_flags_before_owner(self): + for flags in (["--provider", "example"], ["--model", "model"], ["--provider", "bad provider", "--model", "model"]): + with self.subTest(flags=flags), tempfile.TemporaryDirectory() as directory, mock.patch.object(coordinate, "OpenShellOwner") as owner, contextlib.redirect_stderr(io.StringIO()): + output = Path(directory) / "output" + self.assertEqual(coordinate.main(["capabilities", "--output", str(output), *flags]), 1) + owner.assert_not_called() + self.assertFalse(output.exists()) + + def test_relative_path_utf16_boundary_matches_native_loader_before_owner(self): + ascii_prefix = ("a" * 200 + "/") * 5 + astral_prefix = ("\U0001f600" * 50 + "/") * 10 + paths = [(ascii_prefix + "b" * 19, True), (ascii_prefix + "b" * 20, False), + (astral_prefix + "b" * 14, True), (astral_prefix + "b" * 15, False), + ("bad\ud800.txt", False), ("bad\udfff.txt", False)] + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + workspace = root / "workspace"; workspace.mkdir() + output = root / "results"; output.mkdir() + cases = [] + for version in (1, 2, 3): + if version == 3: + dispatch = root / "remote" / ("a" * 32) + workspace = root / "remote/conversations" / ("a" * 32) / "workspace" + output = dispatch / "results" + workspace.mkdir(parents=True); output.mkdir(parents=True) + for path, expected in paths: + public = {**task_template(), "version": min(version, 2), "writable_paths": [path]} + task_path = root / f"public-{len(cases)}.json"; dump(task_path, public) + if expected: + self.assertEqual(coordinate.validate_task(public), public) + (workspace / path).parent.mkdir(parents=True, exist_ok=True) + else: + with self.assertRaises(ValueError): coordinate.validate_task(public) + with mock.patch.object(coordinate, "OpenShellOwner") as owner, contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(coordinate.main(["run", str(task_path), "--profile", str(root / "absent-profile"), "--output", str(root / "absent-output")]), 1) + owner.assert_not_called() + self.assertFalse((root / "absent-output").exists()) + native = {**public, "run_id": "run-one", "workspace": str(workspace), "output_directory": str(output), "allowed_tools": ["read", "write"], "max_tool_calls": 8} + if version in (2, 3): + native.update(operation="run", run_options={}, runtime_defaults={"model": "example/model", "thinking": "high"}) + if version == 3: + native.update(version=3, run_id="a" * 32, session={"conversation_id": "a" * 32, "directory": str(workspace.parent), "file": str(workspace.parent / "session.jsonl"), "prior": None, "prior_sha256": None}) + native_path = (dispatch if version == 3 else root) / f"native-{len(cases)}.json"; dump(native_path, native) + cases.append({"task": str(native_path), "cwd": str(workspace), "expected": expected}) + self.assertEqual(native_extension_load_results(cases), [case["expected"] for case in cases]) + self.assertEqual(list(output.iterdir()), []) + def test_python_versioned_task_boundary_matches_actual_extension(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) @@ -377,6 +461,16 @@ def test_archive_refuses_traversal_links_duplicates_and_size_overflow(self): with mock.patch.object(coordinate, "MAX_SOURCE_BYTES", 1), self.assertRaises(ValueError): coordinate.safe_archive_files(make_archive([("a", b"xx", tarfile.REGTYPE)])) + def test_archive_transport_prefix_does_not_consume_native_path_budget(self): + for name in [("a" * 200 + "/") * 5 + "b" * 19, ("\U0001f600" * 50 + "/") * 10 + "b" * 14]: + self.assertEqual(len(name.encode("utf-16-le")) // 2, 1024) + self.assertEqual(coordinate.relative_file(name), name) + prefixed = "workspace/" + name + self.assertEqual(coordinate.safe_archive_files(make_archive([(prefixed, b"read-only", tarfile.REGTYPE)])), {prefixed: b"read-only"}) + for name in ["workspace/../escape", "workspace//file", "workspace/.git/config", "workspace/./file", "workspace\\file"]: + with self.assertRaises(ValueError): + coordinate.safe_archive_files(make_archive([(name, b"bad", tarfile.REGTYPE)])) + def test_frozen_git_export_preserves_dirty_checkout_and_executable_mode(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) @@ -710,6 +804,53 @@ def requests(self, root): path = root / "fake-pi.requests.jsonl" return [json.loads(line) for line in path.read_text().splitlines()] if path.exists() else [] + def test_selected_metadata_queries_off_only_model_without_thinking_setter(self): + for behavior in ('selected-off', 'selected-out-of-order'): + root = self.prepare(name=behavior, behavior=behavior, metadata=True) + task = coordinate.read_json(root / "task.json") + task.update(version=3, operation="capabilities_selected", selected_model={"provider": "second", "model": "model-two"}) + task["runtime_defaults"]["thinking"] = "low"; dump(root / "task.json", task) + before = coordinate.snapshot(root / "workspace") + self.assertEqual(coordinate.worker(root), 0) + receipt = coordinate.verify_return(root / "results", task, before, "run-one") + configuration = receipt["configuration"] + self.assertEqual(configuration["effective"], {"provider": "second", "model": "model-two", "thinking": "off"}) + self.assertEqual(configuration["supported_thinking_levels"], ["off"]) + self.assertFalse(configuration["profile_default_supported"]) + self.assertEqual(configuration["requested"], task["selected_model"]) + self.assertEqual([r["type"] for r in self.requests(root)], ["get_available_models", "get_state", "set_model", "get_available_thinking_levels", "get_state"]) + self.assertEqual(coordinate.snapshot(root / "workspace"), before) + self.assertFalse((root / "results/extension-events.jsonl").exists()) + self.assertEqual((root / "results/pi-events.jsonl").read_bytes(), b"") + + def test_selected_metadata_refuses_catalog_readback_and_resealed_evidence(self): + for behavior in ('selected-duplicate-model', 'selected-wrong-model', 'selected-wrong-level', 'refused', 'selected-absent-model'): + root = self.prepare(name=behavior, behavior=behavior, metadata=True) + task = coordinate.read_json(root / "task.json") + task.update(version=3, operation="capabilities_selected", selected_model={"provider": "absent" if behavior == 'selected-absent-model' else "second", "model": "model-two"}) + dump(root / "task.json", task) + self.assertEqual(coordinate.worker(root), 1) + self.assertFalse(any(r['type'] in ('prompt', 'set_thinking_level') for r in self.requests(root))) + root = self.prepare(name="resealed-selected", behavior="selected-off", metadata=True) + task = coordinate.read_json(root / "task.json") + task.update(version=3, operation="capabilities_selected", selected_model={"provider": "second", "model": "model-two"}) + dump(root / "task.json", task) + self.assertEqual(coordinate.worker(root), 0) + output = root / "results" + configuration = coordinate.read_json(output / "rpc-configuration.json") + configuration["profile_default_supported"] = True; dump(output / "rpc-configuration.json", configuration) + receipt = coordinate.read_json(output / "worker-receipt.json") + receipt["configuration"] = configuration + receipt["artifact_sha256"] = {name: coordinate.digest(raw) for name, raw in coordinate.snapshot(output).items() if name != "worker-receipt.json"} + dump(output / "worker-receipt.json", receipt) + with self.assertRaises(ValueError): coordinate.verify_return(output, task, {"answer.txt": b"before\n"}, "run-one") + + def test_off_only_selected_run_requires_explicit_supported_thinking(self): + for thinking in ('low', 'off'): + root = self.prepare(name=thinking, behavior="selected-off", options={"provider": "second", "model": "model-two", "thinking": thinking}) + self.assertEqual(coordinate.worker(root), 0 if thinking == 'off' else 1) + self.assertEqual(sum(r['type'] == 'prompt' for r in self.requests(root)), 1 if thinking == 'off' else 0) + def test_default_and_exact_overrides_return_real_changes_with_private_metadata_removed(self): for index, options in enumerate([{}, {"thinking": "low"}, {"provider": "second", "model": "model-two", "thinking": "max"}]): with self.subTest(options=options): @@ -973,6 +1114,8 @@ def __init__(self, profile): super().__init__(profile) self.state = {"id": "sandbox-id", "name": "disposable", "phase": "Stopped", "main_process_instance_id": "old", "restart_count": 0} self.calls = []; test.instances.append(self) + if mode == "persistent" and hasattr(test, "last_owner_state"): + self.state = copy.deepcopy(test.last_owner_state) if mode == "initial-wrong-id": self.state["id"] = "other" if mode == "initial-ready": self.state["phase"] = "Ready" if mode == "reconciled": self.state["main_process_instance_id"] = "new-main" @@ -985,13 +1128,14 @@ def command(self, *args, timeout=60): if args[0] == "start": if mode == "start-no-change-error": raise subprocess.CalledProcessError(1, "synthetic unchanged start") self.state.update(phase="Ready", main_process_instance_id="new-main") + if mode == "persistent": self.state["main_process_instance_id"] += "-" + str(len(test.instances)) if mode == "start-error": raise subprocess.CalledProcessError(1, "synthetic start") elif args[0] == "upload": shutil.copyfile(args[-2], args[-1]) if mode == "replaced-after-upload": self.state["main_process_instance_id"] = "replacement" elif args[0] == "exec": if mode == "exec-error": raise subprocess.CalledProcessError(1, "synthetic exec") - subprocess.run(list(args[args.index("--") + 1:]), check=True, capture_output=True, timeout=timeout) + return subprocess.run(list(args[args.index("--") + 1:]), check=True, capture_output=True, text=True, timeout=timeout) elif args[0] == "download": if self.state["phase"] != "Ready": raise subprocess.CalledProcessError(1, "download requires running sandbox") @@ -1004,6 +1148,7 @@ def command(self, *args, timeout=60): elif args[0] == "stop": if mode == "stop-error": raise subprocess.CalledProcessError(1, "synthetic stop") self.state["phase"] = "Stopped" + if mode == "persistent": test.last_owner_state = copy.deepcopy(self.state) else: raise AssertionError(args) return subprocess.CompletedProcess(args, 0, "", "") return FakeOwner @@ -1235,6 +1380,35 @@ def test_legacy_bare_model_profile_reconciles_and_recovers_v1_without_execution( self.assertEqual(self.instances[-1].calls, ["start", "download", "stop"]) self.assertEqual(preserved, {path: path.read_bytes() for path in preserved}) + def test_archive_transport_long_readonly_paths_recover_v1_v2(self): + paths = [("a" * 200 + "/") * 5 + "b" * 19, ("\U0001f600" * 50 + "/") * 10 + "b" * 14] + for version in (1, 2): + with self.subTest(version=version): + run_id = format(version, "032x") + remote = Path(self.profile["remote_parent"]) / run_id + results = remote / "results"; results.mkdir(parents=True) + files = {name: b"read-only source" for name in paths} + source = {"kind": "git", "commit": "a" * 40, "files": {name: coordinate.digest(raw) for name, raw in files.items()}, "modes": {name: 0o644 for name in paths}} + native = {"version": version, "run_id": run_id, "task_id": "retained-task", "kind": "validation", "instructions": "Retained source-only task", "workspace": str(remote / "workspace"), "output_directory": str(results), "writable_paths": [], "allowed_tools": sorted(coordinate.TOOLS - {"write", "edit"}), "max_tool_calls": 10, "max_turns": 10, "source": source, "checks": []} + if version == 2: + native.update(operation="run", run_options={}, runtime_defaults={"model": "example/model", "thinking": "high"}) + launch = {"model": "example/model", "thinking": "high", "checks": []} + payload = {"task.json": json.dumps(native).encode(), "launch.json": json.dumps(launch).encode(), "coordinate.py": b"# retained worker", "extension.js": b"// retained extension", "package.json": b'{"type":"module"}', **{"workspace/" + name: raw for name, raw in files.items()}} + archive = make_archive([(name, raw, tarfile.REGTYPE) for name, raw in payload.items()]) + failed = self.root / f"long-{version}"; failed.mkdir(); (failed / "inputs.tar").write_bytes(archive) + stopped = {"id": "sandbox-id", "name": "disposable", "phase": "Stopped", "main_process_instance_id": "prior-main", "restart_count": 0} + original = {"version": version, "run_id": run_id, "task_id": "retained-task", "kind": "validation", "started_at": "2000-01-01T00:00:00Z", "source": source, "input_sha256": coordinate.digest(archive), "remote_artifacts": str(results), "delivery_valid": False, "cleanup_complete": True, "sandbox_running": {**stopped, "phase": "Ready"}, "sandbox_after": stopped} + dump(failed / "started.json", original); dump(failed / "receipt.json", original) + dump(results / "worker-receipt.json", {"version": version, "run_id": run_id, "task_id": "retained-task", "outcome": "incomplete", "pi_exit_code": 7}) + locks = self.root / "locks"; locks.mkdir(exist_ok=True); dump(locks / (coordinate.digest(b"sandbox-id") + ".json"), original) + preserved = coordinate.snapshot(failed) + with mock.patch.object(coordinate, "OpenShellOwner", self.recovery_factory()), mock.patch.object(coordinate, "execute_to_log", side_effect=AssertionError("No Pi or checks during recovery")), contextlib.redirect_stdout(io.StringIO()): + output = self.root / f"recovered-{version}" + self.assertEqual(coordinate.main(["recover", str(failed), "--profile", str(self.profile_path), "--output", str(output), "--lock-root", str(locks)]), 0) + self.assertTrue(coordinate.read_json(output / "receipt.json")["recovery_valid"]) + self.assertEqual(self.instances[-1].calls, ["start", "download", "stop"]) + self.assertEqual(coordinate.snapshot(failed), preserved) + def test_nonzero_check_recovers_without_reexecution_or_task_success(self): original = self.failed_run() before = {name: (self.root / 'out' / name).read_bytes() for name in ['receipt.json', 'inputs.tar', 'started.json']} @@ -1275,6 +1449,8 @@ def test_refuses_successful_input_before_lifecycle(self): self.run_fake() with self.assertRaisesRegex(ValueError, 'unsuccessful'): coordinate.recover_task(self.root / 'out', self.profile_path, self.root / 'recovered', self.root / 'locks') + with self.assertRaisesRegex(ValueError, 'unsuccessful'): + coordinate.recover_task(self.root / 'out', self.profile_path, self.root / 'inspected', self.root / 'locks', reconcile_conversation=True) self.assertEqual(len(self.instances), 1) def test_recovery_retry_keeps_original_identity_after_reconcile(self): @@ -1513,5 +1689,329 @@ def test_cli_reports_recovery_separately_from_delivery(self): self.assertEqual(summary['acceptance'], 'not_granted') +class SavedConversationTests(unittest.TestCase): + factory = OwnerTests.factory + + def setUp(self): + OwnerTests.setUp(self) + self.profile["pi_argv"][-1] = "saved-edit" + dump(self.profile_path, self.profile) + self.repository = self.root / "repository"; self.repository.mkdir() + subprocess.run(["git", "init", "-q", "-b", "main"], cwd=self.repository, check=True, timeout=10) + (self.repository / "answer.txt").write_text("before\n") + self.commit() + self.owner_patch = mock.patch.object(coordinate, "OpenShellOwner", self.factory("persistent")) + self.owner_patch.start(); self.addCleanup(self.owner_patch.stop) + self.stdout = contextlib.redirect_stdout(io.StringIO()); self.stdout.__enter__() + self.addCleanup(self.stdout.__exit__, None, None, None) + + def commit(self): + subprocess.run(["git", "add", "--all"], cwd=self.repository, check=True, timeout=10) + subprocess.run(["git", "-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "commit", "-qm", "Fixture revision"], cwd=self.repository, check=True, timeout=10) + return subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=self.repository, text=True, timeout=10).strip() + + def assignment(self, text, *, checks=None): + revision = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=self.repository, text=True, timeout=10).strip() + task = {**task_template(), "version": 2, "task_id": "project:T001", "instructions": text, "writable_paths": ["answer.txt"], "repository": str(self.repository), "revision": revision, "run_options": {"thinking": "low"}, "checks": checks or [{"name": "verify", "argv": [sys.executable, "-c", "from pathlib import Path; assert Path('answer.txt').read_text()==" + repr(text + '\n') + "; Path('check-created.txt').write_text('retained')"], "timeout_seconds": 5}]} + dump(self.task_path, task) + return task + + def test_saved_run_then_new_source_continue_keeps_official_id_and_history(self): + first_task = self.assignment("first edit") + first = coordinate.run_task(self.task_path, self.profile_path, self.root / "first", self.root / "locks", save_session=True) + self.assertTrue(first["delivery_valid"], first) + checkpoint = coordinate.read_json(self.root / "first/results/conversation.json") + session_path = Path(checkpoint["session"]["file"]) + before_session = session_path.read_bytes() + before_artifacts = coordinate.snapshot(self.root / "first") + self.assertIn("check-created.txt", checkpoint["workspace"]["files"]) + metadata = coordinate.run_task(None, self.profile_path, self.root / "metadata", self.root / "locks", capabilities_only=True, selected_model={"provider": "second", "model": "model-two"}) + self.assertTrue(metadata["capabilities_valid"], metadata) + self.assertEqual(session_path.read_bytes(), before_session) + (self.repository / "answer.txt").write_bytes((self.root / "first/results/changed-files/answer.txt").read_bytes()) + self.commit(); second_task = self.assignment("second edit") + self.assertNotEqual(first_task["revision"], second_task["revision"]) + second = coordinate.run_task(self.task_path, self.profile_path, self.root / "second", self.root / "locks", previous_directory=self.root / "first") + self.assertTrue(second["delivery_valid"], second) + second_checkpoint = coordinate.read_json(self.root / "second/results/conversation.json") + self.assertEqual(second_checkpoint["session"]["id"], checkpoint["session"]["id"]) + self.assertEqual(second_checkpoint["session"]["file"], str(session_path)) + self.assertTrue(session_path.read_bytes().startswith(before_session)) + self.assertGreater(len(session_path.read_bytes()), len(before_session)) + self.assertEqual((self.root / "second/results/changed-files/answer.txt").read_bytes(), b"second edit\n") + self.assertEqual(coordinate.snapshot(self.root / "first"), before_artifacts) + self.assertTrue(all(instance.calls.count("start") == instance.calls.count("stop") == 1 for instance in self.instances)) + self.assertEqual(second["acceptance"], "not_granted") + stale = coordinate.run_task(self.task_path, self.profile_path, self.root / "stale", self.root / "locks", previous_directory=self.root / "first") + self.assertFalse(stale["delivery_valid"]) + stale_remote = Path(stale["remote_artifacts"]).parent + self.assertFalse((stale_remote / "invocations.txt").exists()) + self.assertIn("Stale or duplicate", coordinate.read_json(stale_remote / "results/worker-receipt.json")["error"]) + self.assertEqual(coordinate.snapshot(self.root / "first"), before_artifacts) + # The successful checkpoint can be inspected after a newer refused + # dispatch changed the owner journal, without reexecuting either task. + second_artifacts = coordinate.snapshot(self.root / "second") + terminal_session = session_path.read_bytes() + terminal_workspace = coordinate.workspace_manifest(Path(second_checkpoint["session"]["cwd"])) + count = len(self.instances) + with self.assertRaisesRegex(ValueError, "unsuccessful delivery"): + coordinate.recover_task(self.root / "second", self.profile_path, self.root / "invalid-recovery", self.root / "locks") + self.assertEqual(len(self.instances), count) + self.assertEqual(coordinate.main(["reconcile", "--from", str(self.root / "second"), "--output", str(self.root / "inspected"), "--profile", str(self.profile_path), "--lock-root", str(self.root / "locks")]), 0) + inspection_receipt = coordinate.read_json(self.root / "inspected/receipt.json") + inspection = coordinate.read_json(self.root / "inspected/conversation-inspection.json") + self.assertTrue(inspection_receipt["recovery_valid"], inspection_receipt) + self.assertTrue(inspection_receipt["conversation_valid"], inspection_receipt) + self.assertFalse(inspection_receipt["delivery_valid"]) + self.assertEqual(inspection["disposition"], "terminal_checkpoint") + self.assertEqual(inspection["checkpoint"], second_checkpoint) + self.assertEqual(session_path.read_bytes(), terminal_session) + self.assertEqual(coordinate.workspace_manifest(Path(second_checkpoint["session"]["cwd"])), terminal_workspace) + self.assertEqual(coordinate.snapshot(self.root / "second"), second_artifacts) + self.assertEqual(len(self.instances), count + 1) + self.assertEqual(self.instances[-1].calls, ["start", "download", "exec", "stop"]) + self.assertEqual((Path(second["remote_artifacts"]).parent / "invocations.txt").read_text(), "1") + self.assertFalse((stale_remote / "invocations.txt").exists()) + + def first_saved(self, *, checks=None): + self.assignment("first edit", checks=checks) + first = coordinate.run_task(self.task_path, self.profile_path, self.root / "first", self.root / "locks", save_session=True) + remote = Path(first["remote_artifacts"]).parent + return first, remote, coordinate.read_json(remote / "task.json") + + def test_archive_transport_long_readonly_source_round_trips_continue(self): + paths = [("a" * 200 + "/") * 5 + "b" * 19, ("\U0001f600" * 50 + "/") * 10 + "b" * 14] + for name in paths: + path = self.repository / name; path.parent.mkdir(parents=True); path.write_bytes(b"read-only source") + self.commit() + first, _remote, native = self.first_saved() + self.assertTrue(first["delivery_valid"], first) + self.assertFalse(set(paths) & set(native["writable_paths"])) + (self.repository / "answer.txt").write_text("first edit\n"); self.commit(); self.assignment("second edit") + second = coordinate.run_task(self.task_path, self.profile_path, self.root / "second", self.root / "locks", previous_directory=self.root / "first") + self.assertTrue(second["delivery_valid"], second) + for name in paths: + self.assertEqual((Path(native["workspace"]) / name).read_bytes(), b"read-only source") + + def test_archive_source_1025_units_refuses_before_owner_for_both_public_versions(self): + for index, name in enumerate([("a" * 200 + "/") * 5 + "b" * 20, ("\U0001f600" * 50 + "/") * 10 + "b" * 15]): + path = self.repository / name; path.parent.mkdir(parents=True); path.write_bytes(b"overlong") + self.commit() + for version in (1, 2): + task = self.assignment("no execution"); task["version"] = version + if version == 1: + task.pop("run_options"); task["task_id"] = "legacy-task" + dump(self.task_path, task) + output = self.root / f"overlong-{index}-{version}" + with mock.patch.object(coordinate, "OpenShellOwner") as owner, self.assertRaisesRegex(ValueError, "native bounds"): + coordinate.run_task(self.task_path, self.profile_path, output, self.root / "locks", save_session=True) + owner.assert_not_called(); self.assertFalse(output.exists()) + path.unlink(); self.commit() + + def test_failed_checks_recover_advanced_conversation_without_replay(self): + failed, remote, native = self.first_saved(checks=[{"name": "failing", "argv": [sys.executable, "-c", "raise SystemExit(7)"], "timeout_seconds": 5}]) + self.assertFalse(failed["delivery_valid"]) + self.assertTrue(failed["cleanup_complete"]) + prior_bytes = coordinate.snapshot(self.root / "first") + with self.assertRaisesRegex(ValueError, "Recover the failed"): + coordinate.run_task(self.task_path, self.profile_path, self.root / "forbidden", self.root / "locks", previous_directory=self.root / "first") + coordinate.run_task(None, self.profile_path, self.root / "metadata", self.root / "locks", capabilities_only=True) + recovered = coordinate.recover_task(self.root / "first", self.profile_path, self.root / "recovered", self.root / "locks") + self.assertTrue(recovered["recovery_valid"], recovered) + self.assertTrue(recovered["conversation_valid"], recovered) + self.assertFalse(recovered["task_delivery_valid"]) + self.assertEqual(recovered["evidence"]["checks"][0]["exit_code"], 7) + self.assertEqual((remote / "invocations.txt").read_text(), "1") + self.assertEqual(coordinate.snapshot(self.root / "first"), prior_bytes) + (self.repository / "answer.txt").write_text("first edit\n"); self.commit() + self.assignment("second edit") + second = coordinate.run_task(self.task_path, self.profile_path, self.root / "second", self.root / "locks", previous_directory=self.root / "recovered") + self.assertTrue(second["delivery_valid"], second) + self.assertEqual(second["worker"]["conversation"]["session_after"]["id"], recovered["continuation_checkpoint"]["session"]["id"]) + + def test_session_and_full_workspace_drift_refuse_without_prompt(self): + first, remote, native = self.first_saved() + self.assertTrue(first["delivery_valid"], first) + session = Path(native["session"]["file"]); original = session.read_bytes() + header = json.loads(original.splitlines()[0]) + variants = [b"", original[:-1], b"{invalid}\n", json.dumps(header).encode() + b"\n", json.dumps({**header, "version": 2}).encode() + b"\n", json.dumps({**header, "cwd": "/foreign"}).encode() + b"\n", original + b'{"type":"message","id":"orphan","parentId":"missing"}\n'] + for index, raw in enumerate(variants): + with self.subTest(index=index): + session.write_bytes(raw) + refused = coordinate.run_task(self.task_path, self.profile_path, self.root / f"bad-{index}", self.root / "locks", previous_directory=self.root / "first") + self.assertFalse(refused["delivery_valid"]) + self.assertTrue(refused["cleanup_complete"]) + self.assertFalse((Path(refused["remote_artifacts"]).parent / "invocations.txt").exists()) + session.write_bytes(original) + session.unlink() + refused = coordinate.run_task(self.task_path, self.profile_path, self.root / "missing", self.root / "locks", previous_directory=self.root / "first") + self.assertFalse(refused["delivery_valid"]) + self.assertFalse(session.exists()) + self.assertFalse((Path(refused["remote_artifacts"]).parent / "invocations.txt").exists()) + session.write_bytes(original) + session.unlink(); session.symlink_to(remote / "task.json") + with self.assertRaisesRegex(ValueError, "symbolic link"): + coordinate.run_task(self.task_path, self.profile_path, self.root / "linked", self.root / "locks", previous_directory=self.root / "first") + session.unlink(); session.write_bytes(original) + created = Path(native["workspace"]) / "check-created.txt" + original_mode = created.stat().st_mode & 0o777 + for index, change in enumerate((lambda: created.write_text("changed"), lambda: created.chmod(original_mode ^ 0o100))): + change() + refused = coordinate.run_task(self.task_path, self.profile_path, self.root / f"workspace-{index}", self.root / "locks", previous_directory=self.root / "first") + self.assertFalse(refused["delivery_valid"]) + self.assertFalse((Path(refused["remote_artifacts"]).parent / "invocations.txt").exists()) + created.write_text("retained"); created.chmod(original_mode) + + def test_interrupted_workspace_transitions_are_inspected_without_rollback(self): + first, first_remote, native = self.first_saved() + self.assertTrue(first["delivery_valid"], first) + prior = coordinate.read_json(first_remote / "results/conversation.json") + original_tree = coordinate.workspace_manifest(Path(native["workspace"])) + # Separate isolated copies exercise each rename boundary without replaying Pi. + for boundary in (0, 1, 2): + with self.subTest(boundary=boundary), tempfile.TemporaryDirectory() as directory: + parent = Path(directory) / "remote"; parent.mkdir() + run_id = "b" * 32; conversation_id = native["session"]["conversation_id"] + dispatch = parent / run_id; (dispatch / "workspace").mkdir(parents=True) + (dispatch / "workspace/answer.txt").write_text("new source\n") + conversation = parent / "conversations" / conversation_id + shutil.copytree(Path(native["session"]["directory"]), conversation) + workspace = conversation / "workspace" + history = (conversation / "session.jsonl").read_bytes().splitlines() + header = json.loads(history[0]); header["cwd"] = str(workspace) + (conversation / "session.jsonl").write_bytes(json.dumps(header).encode() + b"\n" + b"\n".join(history[1:]) + b"\n") + checkpoint = copy.deepcopy(prior); checkpoint["session"] = coordinate.saved_session_snapshot(conversation / "session.jsonl", workspace) + (conversation / "checkpoint.json").write_bytes(coordinate.private_control_bytes(checkpoint)) + task = {**native, "run_id": run_id, "operation": "continue", "workspace": str(workspace), "output_directory": str(dispatch / "results"), "session": {"conversation_id": conversation_id, "directory": str(conversation), "file": str(conversation / "session.jsonl"), "prior": checkpoint, "prior_sha256": coordinate.digest(coordinate.private_control_bytes(checkpoint))}} + manifest = coordinate.workspace_manifest(dispatch / "workspace") + task["source"] = {**native["source"], "files": {k: v["sha256"] for k, v in manifest["files"].items()}, "modes": {k: v["mode"] for k, v in manifest["files"].items()}} + (dispatch / "task.json").write_bytes(json.dumps(task).encode()) + real_rename = Path.rename; renamed = [] + def interrupt_rename(path, target): + if len(renamed) == boundary: raise OSError("Synthetic rename interruption") + result = real_rename(path, target); renamed.append(str(path)); return result + with mock.patch.object(Path, "rename", interrupt_rename): + if boundary < 2: + with self.assertRaises(OSError): coordinate.prepare_saved_workspace(dispatch, task) + else: + coordinate.prepare_saved_workspace(dispatch, task) + self.assertTrue((conversation / "pending.json").is_file()) + if boundary == 0: + observed = coordinate.inspect_saved_conversation(dispatch, task) + self.assertFalse(observed["continuable"]) + reconciled = coordinate.inspect_saved_conversation(dispatch, task, reconcile=True) + self.assertTrue(reconciled["continuable"]) + self.assertEqual(coordinate.workspace_manifest(workspace), original_tree) + self.assertTrue((dispatch / "transition-reconciled.json").is_file()) + elif boundary == 1: + with self.assertRaises((ValueError, FileNotFoundError)): coordinate.inspect_saved_conversation(dispatch, task, reconcile=True) + self.assertFalse(workspace.exists()) + else: + observed = coordinate.inspect_saved_conversation(dispatch, task, reconcile=True) + self.assertFalse(observed["continuable"]) + self.assertEqual(observed["disposition"], "new_workspace_dispatch_unresolved") + self.assertEqual((workspace / "answer.txt").read_text(), "new source\n") + self.assertTrue((conversation / "pending.json").is_file()) + + def test_saved_controls_and_storage_limits_never_truncate(self): + first, remote, native = self.first_saved() + self.assertTrue(first["delivery_valid"], first) + session = Path(native["session"]["file"]); raw = session.read_bytes() + with mock.patch.object(coordinate, "MAX_SESSION_BYTES", len(raw) - 1), self.assertRaisesRegex(ValueError, "bounded regular"): + coordinate.saved_session_snapshot(session, Path(native["workspace"])) + with mock.patch.object(coordinate, "MAX_RETAINED_BYTES", 1), self.assertRaisesRegex(ValueError, "1 GiB"): + coordinate.retained_storage_guard(remote.parent) + self.assertEqual(session.read_bytes(), raw) + with self.assertRaisesRegex(ValueError, "1 MiB"): + coordinate.private_control_bytes({"too_large": "x" * (1024 * 1024)}) + with self.assertRaisesRegex(ValueError, "Unknown native"): + coordinate.validate_native_task({**native, "version": 4}) + + def test_reconcile_command_certifies_unchanged_old_checkpoint_without_replay(self): + first, first_remote, native = self.first_saved() + self.assertTrue(first["delivery_valid"], first) + stable = Path(native["workspace"]) + session_before = Path(native["session"]["file"]).read_bytes() + self.assignment("second edit") + execute = coordinate.execute_to_log + def interrupted_worker(argv, cwd, log, timeout, **options): + if "worker" not in argv: + return execute(argv, cwd, log, timeout, **options) + Path(log).write_bytes(b"Synthetic pre-rename interruption\n") + rename = Path.rename + def refuse_first_rename(path, destination): + if path == stable: raise OSError("Synthetic before-first-rename interruption") + return rename(path, destination) + with mock.patch.object(Path, "rename", refuse_first_rename): + return coordinate.worker(Path(argv[-1])) + with mock.patch.object(coordinate, "execute_to_log", interrupted_worker): + failed = coordinate.run_task(self.task_path, self.profile_path, self.root / "failed", self.root / "locks", previous_directory=self.root / "first") + self.assertFalse(failed["delivery_valid"]) + failed_remote = Path(failed["remote_artifacts"]).parent + self.assertFalse((failed_remote / "invocations.txt").exists()) + original_artifacts = coordinate.snapshot(self.root / "failed") + self.assertEqual(coordinate.main(["reconcile", "--from", str(self.root / "failed"), "--output", str(self.root / "reconciled"), "--profile", str(self.profile_path), "--lock-root", str(self.root / "locks")]), 0) + recovery = coordinate.read_json(self.root / "reconciled/receipt.json") + self.assertTrue(recovery["recovery_valid"], recovery) + self.assertTrue(recovery["conversation_valid"], recovery) + self.assertFalse(recovery["delivery_valid"]) + self.assertEqual(Path(native["session"]["file"]).read_bytes(), session_before) + self.assertEqual(coordinate.snapshot(self.root / "failed"), original_artifacts) + self.assertFalse((failed_remote / "invocations.txt").exists()) + second = coordinate.run_task(self.task_path, self.profile_path, self.root / "second", self.root / "locks", previous_directory=self.root / "reconciled") + self.assertTrue(second["delivery_valid"], second) + + def test_unacknowledged_unsettled_and_partial_saved_runs_cannot_continue(self): + for behavior in ("no-prompt-ack", "saved-no-settlement", "saved-partial-tail", "saved-wrong-id"): + with self.subTest(behavior=behavior): + self.profile["pi_argv"][-1] = behavior; dump(self.profile_path, self.profile) + task = self.assignment("attempted edit"); task["wall_seconds"] = 1; dump(self.task_path, task) + output = self.root / behavior + failed = coordinate.run_task(self.task_path, self.profile_path, output, self.root / "locks", save_session=True) + self.assertFalse(failed["delivery_valid"]) + self.assertTrue(failed["cleanup_complete"]) + remote = Path(failed["remote_artifacts"]).parent + self.assertFalse((remote / "results/verify.started.json").exists()) + calls = (remote / "invocations.txt").read_bytes() if (remote / "invocations.txt").exists() else b"" + recovery = coordinate.recover_task(output, self.profile_path, self.root / (behavior + "-recovery"), self.root / "locks") + self.assertFalse(recovery["conversation_valid"]) + self.assertFalse(recovery["recovery_valid"]) + self.assertEqual((remote / "invocations.txt").read_bytes() if (remote / "invocations.txt").exists() else b"", calls) + with self.assertRaises(ValueError): + coordinate.run_task(self.task_path, self.profile_path, self.root / (behavior + "-continue"), self.root / "locks", previous_directory=self.root / (behavior + "-recovery")) + + def test_unknown_saved_stop_refuses_continue_before_new_owner(self): + self.assignment("first edit") + with mock.patch.object(coordinate, "OpenShellOwner", self.factory("stop-error")): + first = coordinate.run_task(self.task_path, self.profile_path, self.root / "first", self.root / "locks", save_session=True) + self.assertFalse(first["cleanup_complete"]) + self.assertTrue(first["artifacts_verified"]) + self.assertFalse(first["delivery_valid"]) + count = len(self.instances) + with self.assertRaisesRegex(ValueError, "stopped saved-session"): + coordinate.run_task(self.task_path, self.profile_path, self.root / "second", self.root / "locks", previous_directory=self.root / "first") + self.assertEqual(len(self.instances), count) + + def test_checkpoint_failure_keeps_worker_nonzero_and_delivery_incomplete(self): + self.assignment("first edit") + execute = coordinate.execute_to_log + def failed_checkpoint(argv, cwd, log, timeout, **options): + if "worker" not in argv: + return execute(argv, cwd, log, timeout, **options) + Path(log).write_bytes(b"Synthetic checkpoint-write refusal\n") + with mock.patch.object(coordinate, "complete_saved_conversation", side_effect=OSError("Synthetic checkpoint-write refusal")): + return coordinate.worker(Path(argv[-1])) + with mock.patch.object(coordinate, "execute_to_log", failed_checkpoint): + first = coordinate.run_task(self.task_path, self.profile_path, self.root / "first", self.root / "locks", save_session=True) + self.assertFalse(first["delivery_valid"]) + self.assertTrue(first["cleanup_complete"]) + self.assertEqual(first["exec_exit_code"], 1) + remote = Path(first["remote_artifacts"]).parent + worker_receipt = coordinate.read_json(remote / "results/worker-receipt.json") + self.assertEqual(worker_receipt["outcome"], "incomplete") + self.assertTrue(worker_receipt["checks_passed"]) + self.assertFalse((remote / "results/conversation.json").exists()) + + if __name__ == "__main__": unittest.main()