diff --git a/docs/quota-allocation.md b/docs/quota-allocation.md index 20e25c1b01..870ab8698f 100644 --- a/docs/quota-allocation.md +++ b/docs/quota-allocation.md @@ -344,6 +344,39 @@ caller appends the refresh receipt and rereads the chain; it must not offer a spend command before that point. Older guards without a persisted spend source retain the existing heartbeat default. +A rejected `refresh-state`, or an Agent's state-only maintenance update, also +returns `settlement_recovery` when a persisted Turn still owes closeout. Its +identity and progress come from the same typed receipt reader as guard recovery. +If the caller omits the Turn ID, the refresh can discover an autonomous replan +whose guard positively admitted work and recorded the original obligation and +effect. Later Turn admission still follows the guard's explicit closeout marker. +The TS `pending_closeout` read selects the candidate, validates the original +binding and evaluates receipts under one admitted owner and immutable snapshot; +Python only adapts CLI input and renders the returned recovery. This read mode +cannot be combined with settlement admission or latest-Run inference. +`ok: true` on a state update describes that update only; it does not settle the +nested original Turn. Follow `settlement_recovery.next_cli_actions`: before a +verified writeback this reenters the original bound guard; afterwards it offers +only the remaining spend. A stale replan basis still requires reading the +returned `replan_transition.context_recovery` and correcting the evidence-linked +packet before retry. No recovery read creates a Turn or debits quota. Missing +or conflicting receipt authority is reported as `settlement_recovery_error`, +never inferred as successful settlement. Setup with no admitted Turn, other +Agents' Turns, and already settled work do not produce pending recovery. + +`refresh-state` 被拒绝,或 Agent 只更新升级/维护状态时,若已有 Turn 尚欠结算, +响应会返回 `settlement_recovery`,身份与进度沿用 guard 恢复的 typed receipt reader。 +即使调用者漏传 Turn ID,只要原 guard 已明确准入自主重规划并记录义务和 effect, +刷新也能找回原轮次。后续 Turn 的准入仍依据 guard 明确记录的 closeout 标记。 +TS `pending_closeout` 在同一准入 owner、同一不可变快照下完成候选选择、原绑定校验 +及收据判断;Python 只适配 CLI 参数和展示,不再分两次读取决定恢复对象。这个只读 +模式不能与结算准入或最新 Run 推断混用。 +状态更新的 `ok: true` 只表示该更新成功,不代表嵌套的原 Turn 已结清。执行其中的 +`next_cli_actions`:写回验证前回到原绑定 guard,验证后只补剩余扣账。重规划依据 +过期仍须读取 `replan_transition.context_recovery`,修正证据关联的 packet 后再试。 +恢复读取不新建 Turn、不扣额;收据不可读或身份冲突会显示 `settlement_recovery_error`, +不能视为已结算。没有已准入 Turn 的设置工作、其它 Agent 和已结清工作不产生待恢复项。 + ## Minimal Contract The compact status shape can start with a small object: diff --git a/loopx/cli_commands/project_lifecycle_refresh_state.py b/loopx/cli_commands/project_lifecycle_refresh_state.py index e535120fbd..5d35857339 100644 --- a/loopx/cli_commands/project_lifecycle_refresh_state.py +++ b/loopx/cli_commands/project_lifecycle_refresh_state.py @@ -82,6 +82,7 @@ ) from ..control_plane.quota.cli_projection import compact_refresh_state_cli_payload from .refresh_settlement import settle_requested_refresh +from .refresh_recovery import attach_refresh_settlement_recovery def register_refresh_state_command( @@ -668,6 +669,7 @@ def handle_refresh_state_command( "error": str(exc), **({"error_code": exc.code, **getattr(exc, "payload", {})} if isinstance(getattr(exc, "code", None), str) else {}), } + attach_refresh_settlement_recovery(payload, args, registry_path, goal_ref) if isinstance(exc, ReplanWritebackRejected): transition = project_replan_writeback_rejection( exc, @@ -686,6 +688,10 @@ def handle_refresh_state_command( "current_context_id": recovery["replan_context"]["context_id"], "instruction": recovery["instruction"], **reference, } + settlement_recovery = payload.get("settlement_recovery") + if isinstance(settlement_recovery, dict) and transition["host_action"] == "write_typed_semantic_delta": + transition["host_action"] = "read_current_replan_context" + transition["next_cli_actions"] = settlement_recovery["next_cli_actions"] payload["replan_transition"] = transition if transition["next_cli_actions"]: payload["error"] += " Required transition: " + "; ".join( @@ -884,6 +890,7 @@ def handle_refresh_state_command( ) if not material_refresh_ready: settle_requested_refresh(payload, args, registry_path, goal_ref) + attach_refresh_settlement_recovery(payload, args, registry_path, goal_ref) print_payload(compact_refresh_state_cli_payload(payload) if fmt == "json" else payload, fmt, render_state_refresh_markdown) return 0 if payload.get("ok") else 1 if payload.get("explore_result") is not None: @@ -974,5 +981,6 @@ def handle_refresh_state_command( ), ) settle_requested_refresh(payload, args, registry_path, goal_ref) + attach_refresh_settlement_recovery(payload, args, registry_path, goal_ref) print_payload(compact_refresh_state_cli_payload(payload) if fmt == "json" else payload, fmt, render_state_refresh_markdown) return 0 if payload.get("ok") else 1 diff --git a/loopx/cli_commands/refresh_recovery.py b/loopx/cli_commands/refresh_recovery.py new file mode 100644 index 0000000000..064d1761fd --- /dev/null +++ b/loopx/cli_commands/refresh_recovery.py @@ -0,0 +1,71 @@ +"""Keep a rejected write or maintenance refresh attached to its owed Turn. + +The shared TS closeout reader selects persisted debt; this adapter only exposes +its exact readback and CLI continuation. It never admits or settles a Turn. +""" +from __future__ import annotations + +import argparse +from collections.abc import Mapping +from pathlib import Path +from typing import Any + +from ..control_plane.quota.settlement import attach_settlement_progress, read_heartbeat_settlement +from ..command_invocation import loopx_cli_argv +from ..install_contract import render_host_cli_command +from ..history import load_registry +from ..paths import resolve_runtime_root + + +def attach_refresh_settlement_recovery( + payload: dict[str, Any], args: argparse.Namespace, registry_path: Path, + goal_ref: Mapping[str, Any] | None, +) -> None: + """Expose existing debt without turning a state update into a write receipt.""" + if (args.dry_run or not args.agent_id or isinstance(payload.get("settlement_progress"), dict) + or "settlement_recovery" in payload or "settlement_recovery_error" in payload): + return + try: + runtime_root = resolve_runtime_root(load_registry(registry_path), args.runtime_root, + registry_path=registry_path) + # TS selects persisted debt and validates every caller-supplied binding + # against one immutable snapshot; Python supplies no latest-Run guess. + readback = read_heartbeat_settlement(runtime_root, goal_id=args.goal_id, + agent_id=args.agent_id, todo_id=args.todo_id, + replan_obligation_id=args.replan_obligation_id, turn_instance_id=args.turn_instance_id, + pending_closeout=True, include_record_bodies=False, + registry_path=registry_path, goal_ref=goal_ref) + if readback is None: + return + if readback.identity.failure is not None: + raise ValueError(readback.identity.failure.reason) + identity = readback.identity.value + if identity is None: + raise RuntimeError("original Turn settlement identity is unavailable") + recovery: dict[str, Any] = {"ok": True} + attach_settlement_progress(recovery, readback, registry_path=registry_path, + runtime_root=runtime_root, goal_ref=goal_ref) + recovery.pop("ok") + owed = recovery.get("settlement_owed") + # Select the complete CLI consumer explicitly: an unprofiled guard can + # return legacy unbound refresh templates. Replan guards recover their + # obligation from the Turn receipt (that flag is spend-only on quota). + command = render_host_cli_command([ + *loopx_cli_argv(), "--registry", str(registry_path), "--runtime-root", str(runtime_root), + "--format", "json", "quota", "should-run", + "--complete-turn", "--runtime-profile", "generic_cli", + "--goal-id", identity.goal_id, "--agent-id", identity.agent_id, + "--turn-instance-id", identity.turn_instance_id, + *(["--todo-id", identity.todo_id] if identity.todo_id else []), + *(["--goal-instance-id", str(goal_ref["goal_instance_id"])] if goal_ref is not None else []), + *[word for capability in args.available_capabilities or [] for word in ("--available-capability", capability)], + ]) + recovery.update(required=True, settlement_identity=identity.as_dict(), + next_cli_actions=[owed["command"] if isinstance(owed, dict) else command], + instruction="This response does not settle the original Turn. Follow its recovery with the same identity; " + "state-only updates and installation maintenance cannot replace accountable writeback.") + payload["settlement_recovery"] = recovery + except (OSError, RuntimeError, ValueError) as error: + # Preserve the original write result, including an already committed + # state update. An unavailable read is not evidence of no pending debt. + payload["settlement_recovery_error"] = str(error) diff --git a/loopx/control_plane/quota/prior_turn_closeout.ts b/loopx/control_plane/quota/prior_turn_closeout.ts index e468e2755e..723f548e78 100644 --- a/loopx/control_plane/quota/prior_turn_closeout.ts +++ b/loopx/control_plane/quota/prior_turn_closeout.ts @@ -12,6 +12,7 @@ import { EffectRuntimeRequestError } from "../effect_runtime_errors.ts"; import { jsonObject } from "../runtime_decode.ts"; import { heartbeatReceiptBinding, + heartbeatReceiptDetails, heartbeatReceiptFactFromEvent, selectEffectiveHeartbeatReceipt, type HeartbeatReceiptBinding, @@ -45,8 +46,18 @@ function candidate( }; } +function admitsAutonomousReplan(event: JsonObject, fact: HeartbeatReceiptFact): boolean { + if (fact.replan_obligation_id === null || fact.settlement_effect_id === null) return false; + const guard = heartbeatReceiptDetails(event); + return guard.semantic_replan_obligation_id === fact.replan_obligation_id + && guard.interaction_mode === "autonomous_replan" && guard.ok === true && guard.should_run === true + && guard.must_attempt_work === true && guard.delivery_allowed === false && guard.quiet_noop_allowed === false; +} + /** - * Select the prior must-attempt Turns that still require a host closeout. + * Select prior Turns eligible for closeout readback. Guard preflight requires + * an explicit closeout marker. Refresh recovery can also discover an admitted + * replan-only binding without making it a later Turn's admission prerequisite. * * Every prior Turn is identity-validated, so a conflicting receipt fails the * read instead of being hidden behind a newer Turn. Results are newest first @@ -63,8 +74,9 @@ export function selectCloseoutCandidates( goalId: string, agentId: string, excludeTurnInstanceId: string | null, + { includeAdmittedReplans } = { includeAdmittedReplans: false }, ): { candidates: PriorHostTurnCloseoutCandidate[]; turnsValidated: number } { - const perTurn = new Map(); + const perTurn = new Map(); const firstRecorded = new Map(); for (const event of receipts) { const fact = heartbeatReceiptFactFromEvent(event); @@ -74,16 +86,17 @@ export function selectCloseoutCandidates( firstRecorded.set(turnInstanceId, firstRecorded.size); } if (turnInstanceId === excludeTurnInstanceId) continue; + const entry = { fact, value: event }; const existing = perTurn.get(turnInstanceId); if (existing) { - existing.push(fact); + existing.push(entry); // Map insertion order is the append-order recency index. Moving an // existing Turn to the tail avoids an O(T) indexOf/splice for every // receipt while preserving "last receipt wins recency" exactly. perTurn.delete(turnInstanceId); perTurn.set(turnInstanceId, existing); } else { - perTurn.set(turnInstanceId, [fact]); + perTurn.set(turnInstanceId, [entry]); } } @@ -92,22 +105,17 @@ export function selectCloseoutCandidates( ? undefined : firstRecorded.get(excludeTurnInstanceId); let validated = 0; for (const turnInstanceId of [...perTurn.keys()].reverse()) { - const entries = (perTurn.get(turnInstanceId) ?? []).map((fact) => ({ - fact, - value: fact, - })); - const effective = selectEffectiveHeartbeatReceipt(goalId, agentId, entries); + const effective = selectEffectiveHeartbeatReceipt(goalId, agentId, perTurn.get(turnInstanceId)!); validated += 1; if (effective === null) continue; // Validate identities even outside the causal candidate set: filtering // must not conceal a conflicting persisted settlement binding. if (currentPosition !== undefined && firstRecorded.get(turnInstanceId)! >= currentPosition) continue; - // Closeout is opt-in on the persisted receipt, so older receipts from - // before this contract cannot become new recovery obligations. - if (!effective.closeout_required) continue; - const binding = heartbeatReceiptBinding(goalId, agentId, effective); + const fact = heartbeatReceiptFactFromEvent(effective); + if (!fact.closeout_required && !(includeAdmittedReplans && admitsAutonomousReplan(effective, fact))) continue; + const binding = heartbeatReceiptBinding(goalId, agentId, fact); if (binding === null) continue; - candidates.push(candidate(binding, turnInstanceId, effective)); + candidates.push(candidate(binding, turnInstanceId, fact)); } return {candidates, turnsValidated: validated}; } diff --git a/loopx/control_plane/quota/settlement.py b/loopx/control_plane/quota/settlement.py index 6a91a39556..389bda1c0f 100644 --- a/loopx/control_plane/quota/settlement.py +++ b/loopx/control_plane/quota/settlement.py @@ -233,13 +233,22 @@ def attach_settlement_progress( } # PowerShell quoting applies to every argument, even with an unquoted launcher. # Keep the argv for the composed CLI so it does not have to parse shell text. - if os.name == "nt": + if os.name == "nt" or route[0].lower().endswith(".ps1"): argv = shlex.split(command) owed.update(command=render_owed_host_command(argv), command_argv=argv) payload["settlement_owed"] = owed def render_settlement_progress_markdown(payload: dict[str, Any]) -> list[str]: + recovery = payload.get("settlement_recovery") + if isinstance(recovery, dict): + identity = recovery["settlement_identity"] + lines = [f"- Pending settlement: `{identity['turn_instance_id']}`", recovery["instruction"]] + for command in recovery["next_cli_actions"]: + lines.extend(["", "```sh", command, "```"]) + return lines + if payload.get("settlement_recovery_error"): + return [f"- Settlement recovery could not be read: {payload['settlement_recovery_error']}"] progress = payload.get("settlement_progress") if not isinstance(progress, dict): return [] @@ -457,6 +466,7 @@ def read_heartbeat_settlement( infer_turn_instance_id: bool = False, allow_unbound_binding: bool = False, resolve_original_binding: bool = False, + pending_closeout: bool = False, refresh_retry: dict[str, Any] | None = None, registry_path: Path | None = None, goal_ref: Mapping[str, Any] | None = None, @@ -483,6 +493,7 @@ def read_heartbeat_settlement( else {} ), **({"resolve_original_binding": True} if resolve_original_binding else {}), + **({"pending_closeout": True} if pending_closeout else {}), **({"refresh_retry": refresh_retry} if refresh_retry is not None else {}), **({"borrow_source_admission": True} if borrow_source_admission else {}), **( diff --git a/loopx/control_plane/quota/settlement_readback.ts b/loopx/control_plane/quota/settlement_readback.ts index d77a381bc3..827f1b0ee4 100644 --- a/loopx/control_plane/quota/settlement_readback.ts +++ b/loopx/control_plane/quota/settlement_readback.ts @@ -108,6 +108,7 @@ interface ReadbackRequest { infer_turn_instance_id: boolean; allow_unbound_binding: boolean; resolve_original_binding: boolean; + pending_closeout: boolean; borrow_source_admission: boolean; include_record_bodies: boolean; refresh_retry: RefreshRetryRequest | null; @@ -227,6 +228,13 @@ function decodeRequest( if (request.resolve_original_binding === true && request.infer_turn_instance_id) { throw new EffectRuntimeRequestError("original binding requires an explicit Turn identity"); } + if (request.pending_closeout !== undefined && typeof request.pending_closeout !== "boolean") { + throw new EffectRuntimeRequestError("pending_closeout must be a boolean"); + } + if (request.pending_closeout === true && (request.infer_turn_instance_id || request.allow_unbound_binding + || request.refresh_retry != null || request.heartbeat_reentry_guard != null || request.spend_precheck === true)) { + throw new EffectRuntimeRequestError("pending closeout is a read-only receipt recovery, not inference or settlement admission"); + } if ( request.borrow_source_admission !== undefined && typeof request.borrow_source_admission !== "boolean" @@ -281,6 +289,7 @@ function decodeRequest( infer_turn_instance_id: request.infer_turn_instance_id, allow_unbound_binding: request.allow_unbound_binding, resolve_original_binding: request.resolve_original_binding === true, + pending_closeout: request.pending_closeout === true, borrow_source_admission: request.borrow_source_admission === true, include_record_bodies: request.include_record_bodies !== false, refresh_retry: decodeRefreshRetry(request.refresh_retry), @@ -1100,7 +1109,8 @@ function owedPriorTurnFromSnapshot( request: ReadbackRequest, snapshot: QuotaSettlementReadbackSnapshot, agentId: string, - turnInstanceId: string, + turnInstanceId: string | null, + options?: { includeAdmittedReplans: boolean }, ): OwedPriorTurn | null { const receipts = heartbeatReceiptsFromEvents(snapshot.events, request.goal_id, agentId) .filter((event) => quotaOwnerOwnsProjection(request.owner, event.goal_ref)); @@ -1109,6 +1119,7 @@ function owedPriorTurnFromSnapshot( request.goal_id, agentId, turnInstanceId, + options, ); for (const selected of candidates) { // A committed monitor poll is its own exact no-spend closeout. This is the @@ -1132,6 +1143,7 @@ function owedPriorTurnFromSnapshot( infer_turn_instance_id: false, allow_unbound_binding: false, resolve_original_binding: false, + pending_closeout: false, refresh_retry: null, heartbeat_reentry_guard: null, }, @@ -1146,6 +1158,48 @@ function owedPriorTurnFromSnapshot( return null; } +/** Resolve pending recovery without another provider read or a latest-Run heuristic. */ +function readPendingCloseoutFromRequest( + request: ReadbackRequest, + snapshot: QuotaSettlementReadbackSnapshot, +): JsonObject { + const explicitAgentId = normalizeAgentId(request.agent_id); + if (explicitAgentId === null) { + throw new EffectRuntimeRequestError("pending closeout requires an explicit Agent"); + } + const notFound = {schema_version: QUOTA_SETTLEMENT_READBACK_RESULT_SCHEMA, found: false}; + const turn = request.turn_instance_id ?? owedPriorTurnFromSnapshot( + request, snapshot, explicitAgentId, null, { includeAdmittedReplans: true }, + )?.prior_turn_instance_id; + if (!turn) return notFound; + // Selection, original binding validation and receipt progress share this + // immutable snapshot and admitted owner. Maintenance Run classifications + // cannot conceal the guard's debt or select another Agent's work. + const result = readQuotaSettlementFromRequest({...request, turn_instance_id: turn, + pending_closeout: false, resolve_original_binding: true}, snapshot, false); + const identity = jsonObject(jsonObject(jsonObject(result.identity)?.result)?.value); + const admission = jsonObject(result.native_child_admission); + const originalReceipt = jsonObject(result.heartbeat_receipt); + const workAdmitted = originalReceipt !== null && + heartbeatReceiptFactFromEvent(originalReceipt).settlement_effect_id !== null && + (admission?.report_permission === "new_operation" || + admission?.report_permission === "existing_operation_only") && + (!identity?.replan_obligation_id || + jsonObject(result.semantic_replan_guard)?.selected_obligation_id === identity.replan_obligation_id); + const partialSettlement = [result.writeback, result.spend].some(step => + jsonObject(jsonObject(step)?.payload)?.ok === true); + // Binding a candidate is not work admission. Reuse the receipt owner's + // qualified work facts, while retaining verified partial commits even if + // the original guard did not admit new work. Identity failures stay visible. + if (identity !== null && !workAdmitted && !partialSettlement) return notFound; + if (jsonObject(jsonObject(result.settlement)?.payload)?.ok === true || + (identity?.todo_id && committedMonitorPollFromSnapshot(snapshot, { + goal_id: request.goal_id, agent_id: explicitAgentId, turn_instance_id: turn, + todo_id: String(identity.todo_id), + }, request.owner) !== null)) return notFound; + return result; +} + function readQuotaSettlementFromRequest( request: ReadbackRequest, snapshot: QuotaSettlementReadbackSnapshot, @@ -1161,6 +1215,7 @@ function readQuotaSettlementFromRequest( ); } const explicitAgentId = normalizeAgentId(request.agent_id); + if (request.pending_closeout) return readPendingCloseoutFromRequest(request, snapshot); // Only latest-Turn inference needs the full run history. Explicit readback // must use the existing Turn indexes before applying the Goal owner fence; // otherwise a batch over N Turns repeatedly scans all N receipts. diff --git a/skills/loopx-project/references/autonomous-execution.md b/skills/loopx-project/references/autonomous-execution.md index 06d9079736..44612dac19 100644 --- a/skills/loopx-project/references/autonomous-execution.md +++ b/skills/loopx-project/references/autonomous-execution.md @@ -174,6 +174,15 @@ returns. Do not reconstruct static refresh/spend commands from this skill. Accountable progress precedes its spend; uncertain effects require readback and recovery before retry. State-only refresh cannot replace accountable writeback. +After a rejected refresh or installation maintenance, inspect +`settlement_recovery` even when the state update reports `ok: true`. Execute its +`next_cli_actions` with the original Agent/Todo or replan/Turn identity. If the +rejection also returns `replan_transition.context_recovery`, read that current +basis and revise the evidence-linked packet before retrying its writeback. Do +not repeat the upgrade or treat a subsequent `surface_only` success as closing +the admitted work. A `settlement_recovery_error` leaves settlement unknown; +preserve the original write result and resolve the reported read failure. + The absence of an adapter run or an unchanged artifact does not waive settlement. Only setup metadata work with no admitted delivery may use a state-only refresh when needed. After admitted delivery, an optional state-only refresh follows its diff --git a/tests/control_plane/test_effective_turn_replan.py b/tests/control_plane/test_effective_turn_replan.py index abbbd002b9..0e449180e8 100644 --- a/tests/control_plane/test_effective_turn_replan.py +++ b/tests/control_plane/test_effective_turn_replan.py @@ -20,7 +20,10 @@ GOAL_ID, TODO_ID, _configure_selectable_alternative, + _heartbeat_receipt_count, _initialize_fixture_authority, + _run_generated_cli, + _spend_run_count, ALTERNATIVE_TODO_ID, ) from canonical_authority_fixture import isolate_sqlite_runtime @@ -407,6 +410,29 @@ def call(*args: str, expected_code: int = 0) -> dict: assert reread["autonomous_replan_obligation"].get("resolution_mode") != "receipt_bound_replan_settlement" assert reread["replan_action_packet"]["stride_control"]["required_on_periodic_review"] is True assert reread["replan_action_packet"]["stride_control"]["decision_value_review"] == value_review + replan_identity = reread["heartbeat_receipt"]["settlement_identity"] + receipt_count = _heartbeat_receipt_count(runtime, "stride-due-review") + spend_count = _spend_run_count(runtime) + refresh = ("refresh-state", "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, + "--no-global-sync", "--suppress-external-sinks") + maintenance = (*refresh, "--classification", "local_upgrade_status_updated", + "--delivery-outcome", "surface_only") + missing_turn = call(*refresh, "--replan-obligation-id", obligation["obligation_id"], + "--classification", "bounded_replan_progress", "--delivery-outcome", "outcome_progress", + expected_code=1) + assert "turn_instance_id" in missing_turn["error"] + surface = call(*maintenance, expected_code=1) + assert not surface["appended"] and "settlement_identity" not in surface + assert surface["replan_transition"]["reason_code"] == "stride_decision_required" + assert "settlement_recovery" in missing_turn, missing_turn + assert "settlement_recovery" in surface, surface + pending = missing_turn["settlement_recovery"] + assert pending == surface["settlement_recovery"] + assert surface["replan_transition"]["next_cli_actions"] == pending["next_cli_actions"] + assert pending["settlement_identity"] == replan_identity + assert pending["settlement_progress"]["next_step"] == "durable_writeback" + assert _heartbeat_receipt_count(runtime, "stride-due-review") == receipt_count + assert _spend_run_count(runtime) == spend_count rejected = call("refresh-state", "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, "--replan-obligation-id", obligation["obligation_id"], "--turn-instance-id", "stride-due-review", @@ -461,9 +487,6 @@ def call(*args: str, expected_code: int = 0) -> dict: state_path.write_text(state_path.read_text().replace( "Settle one standard Codex App delivery.", "Settle one standard delivery and verify the newly required source.")) - from tests.control_plane.test_quota_settlement_cli import _heartbeat_receipt_count, _spend_run_count - receipt_count = _heartbeat_receipt_count(runtime, "stride-due-review") - spend_count = _spend_run_count(runtime) rejected_reference = decision["reference_context_id"] if changed_context else "replan-context-" + "b" * 24 decision_path.write_text(json.dumps({**vision_packet, "stride_decision": {**decision, "reference_context_id": rejected_reference}})) @@ -479,11 +502,23 @@ def call(*args: str, expected_code: int = 0) -> dict: assert transition["reason_code"] == "stride_review_basis_mismatch" assert transition["host_action"] == "read_current_replan_context" assert transition["next_cli_actions"] == [] # No unbound repeat of the rejected write. + owed_recovery = foreign["settlement_recovery"] + assert owed_recovery == pending + recovered_code, recovered_turn = _run_generated_cli(pending["next_cli_actions"][0], + registry_path=registry, cwd=project) + assert recovered_code == 0, json.dumps(recovered_turn, indent=2) + assert recovered_turn["heartbeat_receipt"]["settlement_identity"] == owed_recovery["settlement_identity"] + assert _heartbeat_receipt_count(runtime, "stride-due-review") == receipt_count + assert _spend_run_count(runtime) == spend_count reference = transition["context_recovery"] # A rejected write must not eagerly import historical acceptance/evidence # into the model. Its exact write-time basis remains independently readable. if os.name == "posix": - assert len(json.dumps(foreign, ensure_ascii=False).encode()) < 4096 + # Preserve the old diagnostic budget; the additive original-Turn + # recovery has its own bounded allowance, not historical context. + assert len(json.dumps({key: value for key, value in foreign.items() if key != "settlement_recovery"}, ensure_ascii=False).encode()) < 4096 + assert len(json.dumps(owed_recovery, ensure_ascii=False).encode()) < 2048 + assert len(json.dumps(foreign, ensure_ascii=False).encode()) < 6144 from loopx.control_plane.turn_driver.decision_capture import read_context_capture_file saved, _, recovery = read_context_capture_file(reference["path"], reference["sha256"], private=True) assert saved.stat().st_mode & 0o077 == 0 @@ -521,13 +556,17 @@ def call(*args: str, expected_code: int = 0) -> dict: assert persisted["agent_vision"]["stride_decision"] == decision assert persisted["settlement_identity"]["schema_version"] == "quota_settlement_identity_v1" assert persisted["replan_obligation_id"] == obligation["obligation_id"] - assert persisted["settlement_identity"] == reread["heartbeat_receipt"]["settlement_identity"] + assert persisted["settlement_identity"] == replan_identity + after_write = call(*maintenance)["settlement_recovery"] + spend = after_write["settlement_owed"] + assert after_write["next_cli_actions"] == [spend["command"]] + assert spend["effect_id"] == replan_identity["effect_id"] for _ in range(2): - call("quota", "spend-slot", "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, - "--replan-obligation-id", obligation["obligation_id"], "--turn-instance-id", "stride-due-review", - "--slots", "1", "--source", "heartbeat", "--execute") + rc, spent = _run_generated_cli(spend["command"], registry_path=registry, cwd=project) + assert rc == 0 and spent["settlement_result"]["ok"], spent assert _spend_run_count(runtime) == spend_count + 1 assert _heartbeat_receipt_count(runtime, "stride-due-review") == receipt_count + assert "settlement_recovery" not in call(*maintenance) # Continue through real authority/history, rather than injecting a crafted # context. The next periodic review must see the accepted autonomous decision. diff --git a/tests/control_plane/test_refresh_settlement_recovery.py b/tests/control_plane/test_refresh_settlement_recovery.py new file mode 100644 index 0000000000..e1b583283b --- /dev/null +++ b/tests/control_plane/test_refresh_settlement_recovery.py @@ -0,0 +1,230 @@ +"""Maintenance and rejected writes cannot conceal an admitted Turn's debt.""" +from __future__ import annotations + +import json +import os +import shlex +import shutil +import subprocess +import sys +from contextlib import chdir, redirect_stdout +from io import StringIO +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from canonical_authority_fixture import isolate_sqlite_runtime +from test_quota_settlement_cli import ( + AGENT_ID, GOAL_ID, TODO_ID, TURN_ID, ALTERNATIVE_TODO_ID, + _heartbeat_receipt_count, _initialize_fixture_authority, _run_cli, + _run_generated_cli, _spend_run_count, _write_fixture, +) + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +@pytest.mark.parametrize("profile", ["codex_app_heartbeat", "codex_app_ssh_goal"]) +def test_unadmitted_explicit_turn_does_not_report_settlement_debt(tmp_path, monkeypatch, provider, profile): + isolate_sqlite_runtime(tmp_path, monkeypatch) + project, runtime, registry = _write_fixture(tmp_path) + _initialize_fixture_authority(project, runtime, provider=provider, handoff_mode="hard_lease", leases=[]) + binding = ["--goal-id", GOAL_ID, "--agent-id", AGENT_ID] + rc, guard = _run_cli(registry, runtime, "quota", "should-run", "--runtime-profile", profile, + *binding, "--todo-id", TODO_ID, "--turn-instance-id", TURN_ID, cwd=project) + assert rc == 0 and guard["execution_preparation"]["state"] == "claim_required", guard + assert not guard["normal_delivery_allowed"], guard + receipts = _heartbeat_receipt_count(runtime, TURN_ID) + refresh = ["refresh-state", *binding, "--classification", "local_upgrade_status_updated", + "--delivery-outcome", "surface_only", "--no-global-sync", "--suppress-external-sinks"] + # A bound candidate is not admitted work, even when the caller names it. + rc, refused = _run_cli(registry, runtime, *refresh, "--todo-id", TODO_ID, + "--turn-instance-id", TURN_ID, cwd=project) + assert rc == 1 and not refused["appended"], refused + assert "settlement_recovery" not in refused, refused + assert "settlement_recovery_error" not in refused, refused + for turn_args, expected_rc in [([], 0), (["--turn-instance-id", TURN_ID], 1)]: + rc, maintained = _run_cli(registry, runtime, *refresh, *turn_args, cwd=project) + # A Turn without its work binding remains a refused refresh. + assert rc == expected_rc and maintained["appended"] == (expected_rc == 0), maintained + assert "settlement_recovery" not in maintained, maintained + assert _heartbeat_receipt_count(runtime, TURN_ID) == receipts + assert _spend_run_count(runtime) == 0 + # Claiming and rechecking the same Turn can positively admit its work. + identity = guard["heartbeat_receipt"]["settlement_identity"] + rc, claimed = _run_cli(registry, runtime, "todo", "claim", *binding, + "--claimed-by", AGENT_ID, "--todo-id", TODO_ID, cwd=project) + assert rc == 0 and claimed["execution_managed"], claimed + rc, ready = _run_cli(registry, runtime, "quota", "should-run", "--runtime-profile", profile, + *binding, "--todo-id", TODO_ID, "--turn-instance-id", TURN_ID, cwd=project) + assert rc == 0 and ready["normal_delivery_allowed"], ready + assert ready["heartbeat_receipt"]["settlement_identity"] == identity + rc, maintained = _run_cli(registry, runtime, *refresh, cwd=project) + assert rc == 0 and maintained["settlement_recovery"]["settlement_identity"] == identity, maintained + assert _spend_run_count(runtime) == 0 + + +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +@pytest.mark.parametrize("profile,spend_source", [("codex_app_heartbeat", "heartbeat"), ("codex_app_ssh_goal", "visible-goal")]) +def test_rejected_write_and_upgrade_state_recover_original_turn_once(tmp_path, monkeypatch, provider, profile, spend_source): + isolate_sqlite_runtime(tmp_path, monkeypatch) + project, runtime, registry = _write_fixture(tmp_path) + _initialize_fixture_authority(project, runtime, provider=provider) + binding = ["--goal-id", GOAL_ID, "--agent-id", AGENT_ID] + refresh = ["refresh-state", *binding, "--no-global-sync", "--suppress-external-sinks"] + maintenance = [*refresh, "--classification", "local_upgrade_status_updated", "--delivery-outcome", "surface_only"] + rc, setup = _run_cli(registry, runtime, *maintenance, cwd=project) + assert rc == 0 and setup["ok"] and "settlement_recovery" not in setup, setup + rc, guard = _run_cli(registry, runtime, "quota", "should-run", "--runtime-profile", profile, *binding, + "--todo-id", TODO_ID, "--turn-instance-id", TURN_ID, cwd=project) + assert rc == 0 and guard["normal_delivery_allowed"], guard + identity = guard["heartbeat_receipt"]["settlement_identity"] + receipts = _heartbeat_receipt_count(runtime, TURN_ID) + + # The original incident omitted --turn-instance-id, then wrote surface_only. + rc, refused = _run_cli(registry, runtime, *refresh, "--todo-id", TODO_ID, + "--classification", "verified_delivery", "--delivery-outcome", "outcome_progress", cwd=project) + assert rc == 1 and not refused["appended"], refused + assert "turn_instance_id" in refused["error"] + recovery = refused["settlement_recovery"] + assert recovery["required"] and recovery["settlement_identity"] == identity + assert recovery["settlement_progress"]["next_step"] == "durable_writeback" + assert "settlement_owed" not in recovery + rc, surface = _run_cli(registry, runtime, *maintenance, cwd=project) + assert rc == 0 and surface["appended"], surface + assert surface["settlement_recovery"] == recovery + assert "settlement_identity" not in surface # This update is not a Turn writeback. + assert _spend_run_count(runtime) == 0 and _heartbeat_receipt_count(runtime, TURN_ID) == receipts + from loopx.state_refresh import render_state_refresh_markdown + assert TURN_ID in render_state_refresh_markdown(surface) + assert recovery["next_cli_actions"][0] in render_state_refresh_markdown(surface) + + # A conflicting selection is never silently repaired to a different work item. + rc, foreign = _run_cli(registry, runtime, *refresh, "--todo-id", ALTERNATIVE_TODO_ID, + "--turn-instance-id", TURN_ID, "--delivery-outcome", "outcome_progress", cwd=project) + assert rc == 1 and "settlement_recovery" not in foreign, foreign + assert "binding" in foreign["settlement_recovery_error"] + rc, other_agent = _run_cli(registry, runtime, "refresh-state", "--goal-id", GOAL_ID, + "--agent-id", "another-agent", "--classification", "other_lane_status", "--delivery-outcome", "surface_only", + "--no-global-sync", "--suppress-external-sinks", cwd=project) + assert "settlement_recovery" not in other_agent + + # Execute the emitted recovery, not a hand-constructed replacement identity. + rc, recovered = _run_generated_cli(recovery["next_cli_actions"][0], registry_path=registry, cwd=project) + assert rc == 0 and recovered["normal_delivery_allowed"], recovered + assert recovered["heartbeat_receipt"]["settlement_identity"] == identity + assert _heartbeat_receipt_count(runtime, TURN_ID) == receipts + command = next(action for action in recovered["interaction_contract"]["cli_channel"]["next_cli_actions"] + if "refresh-state" in shlex.split(action)) + command = command.replace("", "verified_delivery").replace("", "implementation").replace("", "outcome_progress") + command += " --format json --no-global-sync --suppress-external-sinks" + assert "--turn-instance-id" in shlex.split(command), command + assert "<" not in shlex.join(shlex.split(command)), command + # Interrupt the generated combined operation between writeback and debit. + # Maintenance must recover this partial commit without rewriting progress. + from loopx.cli import main + from loopx.cli_commands import refresh_settlement + def unavailable_child(argv, **kwargs): + assert "spend-slot" in argv and TURN_ID in argv + raise OSError("fixture interrupt before quota debit") + stdout = StringIO() + with monkeypatch.context() as fault, chdir(project), redirect_stdout(stdout): + fault.setattr(refresh_settlement, "subprocess", SimpleNamespace( + run=unavailable_child, TimeoutExpired=subprocess.TimeoutExpired)) + rc = main(shlex.split(command)[1:]) + written = json.loads(stdout.getvalue()) + assert rc == 1 and written["settlement_identity"] == identity, written + assert written["settlement_progress"]["next_step"] == "quota_spend" + + # Maintenance after a committed write offers only the owed debit, no replan. + rc, after_write = _run_cli(registry, runtime, *maintenance, cwd=project) + assert rc == 0, after_write + owed = after_write["settlement_recovery"]["settlement_owed"] + assert owed["effect_id"] == identity["effect_id"] + assert after_write["settlement_recovery"]["settlement_progress"]["quota_spend_source"] == spend_source + spend = after_write["settlement_recovery"]["next_cli_actions"][0] + assert spend == owed["command"] and "spend-slot" in spend + for _ in range(2): + rc, settled = _run_generated_cli(spend, registry_path=registry, cwd=project) + assert rc == 0 and settled["settlement_result"]["ok"], settled + assert {receipt["step_kind"] for receipt in settled["settlement_result"]["receipts"]} >= {"durable_writeback", "quota_spend"} + assert _spend_run_count(runtime) == 1 + rc, after_settlement = _run_cli(registry, runtime, *maintenance, cwd=project) + assert rc == 0 and "settlement_recovery" not in after_settlement, after_settlement + + +def test_unavailable_recovery_read_preserves_committed_state_result(tmp_path, monkeypatch): + isolate_sqlite_runtime(tmp_path, monkeypatch) + project, runtime, registry = _write_fixture(tmp_path) + _initialize_fixture_authority(project, runtime) + from loopx.cli import main + from loopx.cli_commands import refresh_recovery + def unavailable_read(*args, **kwargs): + raise RuntimeError("fixture closeout reader unavailable") + monkeypatch.setattr(refresh_recovery, "read_heartbeat_settlement", unavailable_read) + stdout = StringIO() + with chdir(project), redirect_stdout(stdout): + rc = main(["--registry", str(registry), "--runtime-root", str(runtime), "--format", "json", + "refresh-state", "--goal-id", GOAL_ID, "--agent-id", AGENT_ID, + "--classification", "local_upgrade_status_updated", "--delivery-outcome", "surface_only", + "--no-global-sync", "--suppress-external-sinks"]) + result = json.loads(stdout.getvalue()) + assert rc == 0 and result["appended"], result + assert result["settlement_recovery_error"] == "fixture closeout reader unavailable" + assert "settlement_recovery" not in result and _spend_run_count(runtime) == 0 + assert json.loads(Path(result["json_path"]).read_text())["classification"] == "local_upgrade_status_updated" + + +@pytest.mark.skipif(shutil.which("pwsh") is None, reason="PowerShell 7 is not installed") +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_returned_recovery_command_runs_verbatim_in_powershell(tmp_path, monkeypatch, provider): + isolate_sqlite_runtime(tmp_path, monkeypatch) + project, runtime, registry = _write_fixture(tmp_path / "owner's workspace") + _initialize_fixture_authority(project, runtime, provider=provider) + checkout = Path(__file__).resolve().parents[2] + launcher = tmp_path / "pinned release" / "loopx.ps1" + launcher.parent.mkdir() + shutil.copyfile(checkout / "scripts/loopx.ps1", launcher) + launcher.with_name("loopx-current-release.json").write_text(json.dumps({ + "release_root": str(checkout), "python": sys.executable, + }), encoding="utf-8") + environment = {**os.environ, "LOOPX_USAGE_PING": "0"} + environment.pop("LOOPX_CURRENT_RELEASE_FILE", None) + binding = ["--goal-id", GOAL_ID, "--agent-id", AGENT_ID] + rc, admitted = _run_cli(registry, runtime, "quota", "should-run", "--runtime-profile", + "codex_app_heartbeat", *binding, "--todo-id", TODO_ID, "--turn-instance-id", TURN_ID, + cwd=project) + assert rc == 0 and admitted["normal_delivery_allowed"], admitted + identity = admitted["heartbeat_receipt"]["settlement_identity"] + guard_count = _heartbeat_receipt_count(runtime, TURN_ID) + refresh = subprocess.run([sys.executable, "-m", "loopx.entrypoint", "--cli-bin", str(launcher), + "--registry", str(registry), "--runtime-root", str(runtime), "--format", "json", "refresh-state", + *binding, "--classification", "local_upgrade_status_updated", "--delivery-outcome", "surface_only", + "--no-global-sync", "--suppress-external-sinks"], cwd=project, env=environment, text=True, + capture_output=True, timeout=60) + assert refresh.returncode == 0, refresh.stderr + recovery = json.loads(refresh.stdout)["settlement_recovery"] + assert recovery["settlement_identity"] == identity + command, = recovery["next_cli_actions"] + def run_returned(command): + answer = subprocess.run([shutil.which("pwsh"), "-NoProfile", "-NonInteractive", + "-Command", command], cwd=project, env=environment, text=True, + capture_output=True, timeout=60) + assert answer.returncode == 0, answer.stderr + return json.loads(answer.stdout) + + recovered = run_returned(command) + if recovered.get("schema_version") == "context_capture_navigation_v1": + page = run_returned(recovered["recovery"]["command"]) + digest = page["sha256"] + raw = bytearray() + while True: + assert page["ok"] and page["sha256"] == digest and page["offset"] == len(raw) + raw.extend(page["content"].encode()) + if page["eof"]: + assert len(raw) == page["total_bytes"] + break + page = run_returned(page["next_command"]) + recovered = json.loads(raw) + assert recovered["heartbeat_receipt"]["settlement_identity"] == identity + assert _heartbeat_receipt_count(runtime, TURN_ID) == guard_count + assert _spend_run_count(runtime) == 0 diff --git a/tests/control_plane_ts/quota_settlement_readback.test.ts b/tests/control_plane_ts/quota_settlement_readback.test.ts index bcea7eb4c7..47e74e0911 100644 --- a/tests/control_plane_ts/quota_settlement_readback.test.ts +++ b/tests/control_plane_ts/quota_settlement_readback.test.ts @@ -12,7 +12,7 @@ import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import test from "node:test"; -import { settlementIdentity } from "../../loopx/control_plane/effect_program.ts"; +import { settlementIdentity, settlementIdentityPayload } from "../../loopx/control_plane/effect_program.ts"; import { createEffectRuntimeHandlers, dispatchEffectRuntimeMethod, @@ -28,6 +28,7 @@ import { QUOTA_SETTLEMENT_READBACK_REQUEST_SCHEMA, readQuotaSettlement, readQuotaSettlementSnapshot, + readQuotaSettlementFromSnapshot, } from "../../loopx/control_plane/quota/settlement_readback.ts"; import { PRIOR_HOST_TURN_CLOSEOUT_PREFLIGHT_REQUEST_SCHEMA, @@ -462,6 +463,155 @@ function request(runtimeRoot: string, overrides: Record = {}) { }; } +test("pending closeout survives maintenance and reads one original receipt snapshot", async t => { + for (const entry of [ + {state: "writeback_required"}, + {writeback: true, state: "spend_required"}, + {writeback: true, spend: true, remove: "quota_spend", state: "spend_receipt_required"}, + {writeback: true, spend: true, state: null}, + {monitor: true, state: null}, + {guard: false, state: null}, + {legacy: true, state: null}, + ]) await t.test(entry.state ?? "no debt", async () => { + const root = await fixture(entry); + try { + const log = join(root, "goals", goalId, "rollout-event-log.jsonl"); + const index = join(root, "goals", goalId, "runs", "index.jsonl"); + const events = (await readFile(log, "utf8")).trim().split("\n").filter(Boolean).map(line => JSON.parse(line)); + for (const event of events) if (event.event_kind === "quota_should_run") Object.assign(event.details, { + closeout_required: entry.legacy !== true, ok: true, should_run: true, + must_attempt_work: true, delivery_allowed: true, quiet_noop_allowed: false, + }); + await writeFile(log, events.filter(event => event.event_kind !== entry.remove).map(event => JSON.stringify(event)).join("\n") + "\n"); + await appendFile(index, JSON.stringify({goal_id: goalId, agent_id: agentId, + classification: "local_upgrade_status_updated", delivery_outcome: "surface_only"}) + "\n"); + const input = request(root, {pending_closeout: true, turn_instance_id: null, todo_id: null}); + const snapshot = await readQuotaSettlementSnapshot(root, goalId); + const result = readQuotaSettlementFromSnapshot(input, snapshot); + assert.equal(result.found, entry.state !== null); + if (entry.state !== null) { + assert.deepEqual((result.identity as any).result.value, settlementIdentityPayload(identity)); + assert.equal((result.progress as any).state, entry.state); + const mismatch = readQuotaSettlementFromSnapshot({...input, todo_id: "todo_foreign"}, snapshot); + assert.equal((mismatch.identity as any).payload.ok, false); + assert.match((mismatch.identity as any).result.failure.reason, /binding differs/); + } + assert.equal(readQuotaSettlementFromSnapshot({...input, agent_id: "another-agent"}, snapshot).found, false); + assert.deepEqual(await readQuotaSettlement(input), result); + // Candidate selection and exact readback use the already acquired snapshot. + await writeFile(log, "corrupt live history\n"); + assert.deepEqual(readQuotaSettlementFromSnapshot(input, snapshot), result); + await assert.rejects(readQuotaSettlement(input), /malformed/); + } finally {await rm(root, {recursive: true, force: true});} + }); +}); + +test("explicit pending recovery requires admitted work or verified partial settlement", async t => { + const denied = {ok: true, should_run: true, must_attempt_work: false, + delivery_allowed: false, quiet_noop_allowed: true}; + for (const entry of [ + {name: "claim required", guard: denied, state: null}, + {name: "incomplete modern admission", guard: {ok: true, should_run: true, delivery_allowed: true}, state: null}, + {name: "unknown legacy admission", guard: {}, state: null}, + {name: "verified writeback", guard: denied, writeback: true, state: "spend_required"}, + {name: "verified debit", guard: denied, spend: true, state: "writeback_required"}, + ]) await t.test(entry.name, async () => { + const root = await fixture({writeback: entry.writeback, spend: entry.spend}); + try { + const log = join(root, "goals", goalId, "rollout-event-log.jsonl"); + const events = (await readFile(log, "utf8")).trim().split("\n").map(line => JSON.parse(line)); + Object.assign(events[0].details, entry.guard); + const contents = events.map(event => JSON.stringify(event)).join("\n") + "\n"; + await writeFile(log, contents); + const input = request(root, {pending_closeout: true}); + const snapshot = await readQuotaSettlementSnapshot(root, goalId); + const result = readQuotaSettlementFromSnapshot(input, snapshot); + assert.equal(result.found, entry.state !== null); + if (entry.state !== null) { + assert.deepEqual((result.identity as any).result.value, settlementIdentityPayload(identity)); + assert.equal((result.progress as any).state, entry.state); + } + // A denied guard must not hide a conflicting caller binding. + const mismatch = readQuotaSettlementFromSnapshot({...input, todo_id: "todo_foreign"}, snapshot); + assert.equal((mismatch.identity as any).result.failure.kind, "identity_mismatch"); + assert.equal(await readFile(log, "utf8"), contents); + } finally {await rm(root, {recursive: true, force: true});} + }); +}); + +test("pending closeout recovers positively admitted replan work without creating a preflight obligation", async () => { + const root = await fixture(); + try { + const log = join(root, "goals", goalId, "rollout-event-log.jsonl"); + const events = (await readFile(log, "utf8")).trim().split("\n").map(line => JSON.parse(line)); + const obligation = "replan-0000000000000001"; + const bound = settlementIdentity({goal_id: goalId, agent_id: agentId, todo_id: null, + replan_obligation_id: obligation, turn_instance_id: turnId}); + const admitted = {closeout_required: false, replan_obligation_id: obligation, + semantic_replan_obligation_id: obligation, settlement_effect_id: bound.effect_id, + ok: true, should_run: true, must_attempt_work: true, delivery_allowed: false, + quiet_noop_allowed: false, interaction_mode: "autonomous_replan"}; + const writeGuard = async (details: Record) => { + events[0].details = details; + await writeFile(log, events.map(event => JSON.stringify(event)).join("\n") + "\n"); + }; + await writeGuard(admitted); + const input = request(root, {pending_closeout: true, turn_instance_id: null, todo_id: null}); + for (const query of [input, {...input, replan_obligation_id: obligation}, + {...input, turn_instance_id: turnId}, + {...input, turn_instance_id: turnId, replan_obligation_id: obligation}]) { + const readback = await readQuotaSettlement(query); + assert.equal(readback.found, true); + assert.deepEqual((readback.identity as any).result.value, settlementIdentityPayload(bound)); + } + assert.equal((await readQuotaSettlement({...input, agent_id: "another-agent"})).found, false); + const mismatched = await readQuotaSettlement({...input, replan_obligation_id: "replan-0000000000000002"}); + assert.equal((mismatched.identity as any).result.failure.kind, "identity_mismatch"); + const preflight = await preflightPriorHostTurnCloseout({ + ...input, schema_version: PRIOR_HOST_TURN_CLOSEOUT_PREFLIGHT_REQUEST_SCHEMA, + }); + assert.equal(preflight.reason, "no_prior_turn_requires_closeout"); + + for (const patch of [{should_run: false}, {must_attempt_work: undefined}, {quiet_noop_allowed: true}, + {interaction_mode: "control_plane_self_repair"}, {semantic_replan_obligation_id: "replan-0000000000000002"}, + {settlement_effect_id: undefined}, {replan_obligation_id: undefined, settlement_effect_id: undefined}]) { + await writeGuard({...admitted, ...patch}); + assert.equal((await readQuotaSettlement(input)).found, false, JSON.stringify(patch)); + const explicit = await readQuotaSettlement({...input, turn_instance_id: turnId}); + assert.ok(explicit.found === false || (explicit.identity as any).payload.ok === false, + `explicit recovery must not admit ${JSON.stringify(patch)}`); + } + await writeGuard({...admitted, settlement_effect_id: "another-effect"}); + const wrongEffect = await readQuotaSettlement(input); + assert.equal((wrongEffect.identity as any).result.failure.kind, "identity_mismatch"); + + for (const patch of [{infer_turn_instance_id: true}, {allow_unbound_binding: true}, + {refresh_retry: {}}, {heartbeat_reentry_guard: {}}, {spend_precheck: true}]) { + await assert.rejects(readQuotaSettlement({...input, ...patch}), /read-only receipt recovery/); + } + await assert.rejects(readQuotaSettlement({...input, pending_closeout: "yes"}), /must be a boolean/); + await assert.rejects(readQuotaSettlement({...input, agent_id: null}), /explicit Agent/); + } finally {await rm(root, {recursive: true, force: true});} +}); + +test("pending closeout cannot adopt another Goal instance's receipts", async () => { + const root = await fixture({goalRef: {goal_id: goalId, goal_instance_id: instanceA}}); + try { + const log = join(root, "goals", goalId, "rollout-event-log.jsonl"); + const event = JSON.parse((await readFile(log, "utf8")).trim()); + event.details.closeout_required = true; + await writeFile(log, JSON.stringify(event) + "\n"); + for (const turn of [null, turnId]) { + await withSourceAdmission(root, instanceB, instanceB, async binding => { + const result = await readQuotaSettlement(request(root, {...binding, pending_closeout: true, + turn_instance_id: turn, todo_id: null})); + if (turn === null) assert.equal(result.found, false); + else assert.equal((result.identity as any).payload.ok, false); + }); + } + } finally {await rm(root, {recursive: true, force: true});} +}); + function sourceGuardPath(registryPath: string): string { const digest = createHash("sha256").update(goalId, "utf8").digest("hex"); return join(