Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions docs/reference/protocols/turn-envelope-v0.md
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,34 @@ the original admission's lease proof after a renewal in that same generation.
The submitted version must be between the admitted and current versions,
inclusive, and the lease must still match the original admission. Ordinary
refresh without the option still requires the current proof.

An unfinished prepared Turn can also resume after lease expiry through the
ordinary managed claim and its original `quota should-run`. For local File and
SQLite authority, a fresh eligible guard checks the same Agent's current lease
under the canonical maintenance fence and appends a `lease_takeover` receipt.
The original admission, workspace obligation, quota source and settlement effect
stay unchanged. The append records both generations and current Todo/acceptance
digests; it does not accept an old result. The current holder reads current
requirements, dependencies and artifact revisions, reuses only still-valid
evidence and runs affected validation before completion or writeback. Stale keys,
competing holders, unavailable authority and stopped work remain fenced. Existing
writeback/spend effects are recovered exactly once; takeover cannot reopen a
closeout that has started. Explicit administrative no-spend closeout remains
available when no business result can be recovered.

中文:未交账的原轮次在租约过期后,可通过普通领取和原 `quota should-run` 接续。
本地 File/SQLite 权威源在维护锁下核验同一 Agent 的当前有效租约,追加
`lease_takeover` 回执,保留原准入、工作区义务、额度来源与结算身份,并记录两代
租约及当前任务、验收摘要。接管不代表旧成果自动通过:当前持有人核对需求、依赖和
产物版本,只复用仍有效的证据,完成受影响检查后交账。旧 key、其他持有人、权威源
不可用和停止状态继续受到保护;已开始的交账只能恢复欠缺步骤,不能重开或重复扣账。
没有可复用业务成果时,仍可显式执行不扣账的中断关闭。

This requires no saved automation prompt migration and adds no user confirmation.
It does not attach Codex App to a background lease-renewal timer: automatic
renewal remains scoped to the existing supervised live-host process.
中文:该流程不需要迁移已有自动化提示词,也不增加用户确认。它没有为 Codex App
增加后台续租计时器;自动续租仍限于现有可信宿主进程监督路径。
When `--delivery-workspace-path` names the producing worktree, the combined
operation also runs the owed command there, using the originating CLI's
implementation. The normal workspace and settlement guards still apply; a
Expand Down
7 changes: 5 additions & 2 deletions loopx/control_plane/quota/execution_loss_closeout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,10 +172,13 @@ export async function observeFencedExecution(root: string, identity: ReturnType<
const writerMatches = todo.claimed_by === identity.agent_id && lease.owner === identity.agent_id
&& todo.done !== true && leaseRepositoryRejection(todo, lease) === null
&& canonicalLeaseTodoFact(todo)?.excluded_agents.includes(identity.agent_id) === false;
const active = writerMatches && leaseIsActive(lease, now);
// Same-owner recovery can re-enter the original guard. That path records a
// fenced takeover before any new validation/writeback; this observation alone
// never admits work or accepts a result. Competing ownership still holds.
if (writerMatches) return null;
return {original_prepared_epoch: prepared.prepared_lease_epoch, current_lease_epoch: lease.lease_epoch,
current_lease_version: lease.version, current_owner: lease.owner,
current_control_writer_active: active, can_reclaim_control_writer: writerMatches && !active};
current_control_writer_active: false, can_reclaim_control_writer: false};
}

function optionalAssignedReplan(receipt: JsonObject): boolean {
Expand Down
4 changes: 2 additions & 2 deletions loopx/control_plane/quota/execution_preparation.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,14 +70,14 @@ def project_selected_todo_execution_preparation(


def _read_execution_snapshot(
runtime_root: str | Path, goal_id: str, todo_id: str,
runtime_root: str | Path, goal_id: str, todo_id: str, *, include_takeover_basis: bool = False,
) -> dict[str, Any] | None:
response = effect_runtime_result(
"todo.read",
{"schema_version": "todo_read_request_v0", "kind": "execution_preparation_source",
"source": {"runtime_root": str(Path(runtime_root).expanduser().resolve(strict=False)),
"goal_id": goal_id},
"todo_id": todo_id},
"todo_id": todo_id, **({"include_takeover_basis": True} if include_takeover_basis else {})},
timeout=LOCAL_COORDINATION_TODO_LIST_TIMEOUT_SECONDS,
)
snapshot = (
Expand Down
52 changes: 46 additions & 6 deletions loopx/control_plane/quota/heartbeat_receipt.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from __future__ import annotations

import json
from collections.abc import Callable, Mapping
from collections.abc import Callable, Mapping, Sequence
from contextlib import ExitStack
from functools import lru_cache
from pathlib import Path

Expand Down Expand Up @@ -85,7 +86,7 @@ def _heartbeat_receipt_events(
]


def heartbeat_receipt_request_subject(event: Mapping[str, object] | None) -> dict | None:
def heartbeat_receipt_request_subject(event: Mapping[str, object] | None) -> dict[str, object] | None:
"""Transport the original request's path-free identity from scalar event details."""
details = (event or {}).get("details")
if not isinstance(details, Mapping) or "request_id" not in details:
Expand Down Expand Up @@ -119,7 +120,7 @@ def _receipt_selection(


def _select_receipt_facts(
events: list[Mapping[str, object]],
events: Sequence[Mapping[str, object]],
) -> tuple[int | None, tuple[SettlementBindingKind, str, str] | None]:
# Keep unknown details in the reader. Only the shared identity owner's raw
# fields enter this pure projection/cache; no receipt or source is cached.
Expand Down Expand Up @@ -767,15 +768,42 @@ def requalify_bound_heartbeat_receipt(
from .settlement import read_heartbeat_settlement

log_path = rollout_event_log_path(runtime_root, goal_id)
with exclusive_cross_runtime_file_lock(log_path, operation="requalify_heartbeat_work"):
with ExitStack() as locks:
locks.enter_context(exclusive_cross_runtime_file_lock(log_path, operation="requalify_heartbeat_work"))
original, _ = _effective_heartbeat_receipt(_heartbeat_receipt_events(
load_rollout_events(log_path), goal_id=goal_id, agent_id=agent_id,
turn_instance_id=turn_instance_id, goal_ref=goal_ref,
))
original_details_value = original.get("details") if original else None
original_details = original_details_value if isinstance(original_details_value, Mapping) else {}
# Snapshot only the changed-generation path. The TS receipt owner alone
# decides eligibility. A nonblocking maintenance fence avoids reversing
# the ordinary maintenance -> receipt lock order while keeping the source
# unchanged through the append below.
guard_details = dict(details)
guard_details.pop("lease_takeover_source", None)
if (todo_id and original_details.get("prepared_lease_key_sha256")
and details.get("prepared_lease_key_sha256")
and (original_details.get("prepared_lease_key_sha256") != details.get("prepared_lease_key_sha256")
or original_details.get("prepared_lease_epoch") != details.get("prepared_lease_epoch"))):
from ..coordination.shadow_management import (
require_shadow_primary_write_allowed, shadow_maintenance_lock_target,
)
from ..runtime.time import now_local_iso
from .execution_preparation import _read_execution_snapshot

locks.enter_context(exclusive_cross_runtime_file_lock(
shadow_maintenance_lock_target(runtime_root, goal_id), timeout_seconds=0,
operation="requalify_heartbeat_work",
))
require_shadow_primary_write_allowed(runtime_root, goal_id)
snapshot = _read_execution_snapshot(runtime_root, goal_id, todo_id, include_takeover_basis=True)
if snapshot is not None:
guard_details["lease_takeover_source"] = {**snapshot, "observed_at": now_local_iso(timespec="microseconds")}
readback = read_heartbeat_settlement(
runtime_root, goal_id=goal_id, agent_id=agent_id, todo_id=todo_id,
turn_instance_id=turn_instance_id, replan_obligation_id=replan_obligation_id,
registry_path=registry_path, goal_ref=goal_ref, heartbeat_reentry_guard=details,
registry_path=registry_path, goal_ref=goal_ref, heartbeat_reentry_guard=guard_details,
)
if original is None or readback is None or readback.identity.value is None:
raise ValueError("work requalification requires the original admitted settlement identity")
Expand All @@ -796,11 +824,12 @@ def requalify_bound_heartbeat_receipt(
summary = {
"review_guard_upgrade": "same-Turn review guard upgraded without rebinding",
"lease_readiness": "same-Turn lease readiness recorded without readmission",
"lease_takeover": "current holder resumed the original Turn; validate saved results against current requirements",
}.get(receipt_revision, "same-Turn work admission requalified without rebinding")
corrected = build_rollout_event(
goal_id=goal_id, goal_ref=goal_ref, event_kind="quota_should_run",
agent_id=agent_id, todo_id=todo_id, run_id=turn_instance_id,
status=str(original.get("status") or status) if receipt_revision == "lease_readiness" else status,
status=str(original.get("status") or status) if receipt_revision in {"lease_readiness", "lease_takeover"} else status,
summary=summary,
source_event_id=event_id, caused_by=event_id, details=dict(qualified_details),
)
Expand Down Expand Up @@ -828,6 +857,17 @@ def heartbeat_receipt_view(
}
if details.get("closeout_required") is True:
receipt["closeout_required"] = True
if details.get("takeover_original_event_id"):
receipt["lease_takeover"] = {
"original_receipt_event_id": details["takeover_original_event_id"],
"original_lease_epoch": details.get("takeover_original_epoch"),
"current_lease_epoch": details.get("prepared_lease_epoch"),
"evidence_policy": (
"Current ownership resumed the original Turn, not acceptance of old results. "
"Read current requirements, dependencies and artifact revisions; reuse only evidence "
"that remains valid, run affected validation, then settle this original identity once."
),
}
todo_id = str(details.get("todo_id") or "").strip()
replan_obligation_id = normalize_todo_replan_obligation_id(
details.get("replan_obligation_id")
Expand Down
88 changes: 87 additions & 1 deletion loopx/control_plane/quota/heartbeat_receipt_identity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ import { BARE_SHA256_PATTERN } from "../content_digest.ts";
import { jsonObject, requireJsonObject } from "../runtime_decode.ts";
import {nativeChildReportAdmission} from "../capabilities/native_child_admission.ts";
import type {ReceiptBoundReplayPhase} from "./settlement_phase.ts";
import {createHash} from "node:crypto";
import {isDeepStrictEqual} from "node:util";
import {canonicalAuthoritySha256} from "../coordination/authority_store_codec.ts";
import {leaseRepositoryRejection} from "../work_items/task_lease_repository.ts";
import {parseTodoTimestampMicros} from "../runtime_timestamp.ts";

const TODO_ID_PATTERN = /^todo_[a-z0-9_-]{3,64}$/;
const REPLAN_OBLIGATION_ID_PATTERN = /^replan-[a-f0-9]{16}$/;
Expand Down Expand Up @@ -302,6 +307,87 @@ export function isHeartbeatLeaseReadiness(event: JsonObject): boolean {
return heartbeatReceiptDetails(event).settlement_receipt_revision === "lease_readiness";
}

/** A fresh guard and fenced canonical snapshot qualify a new writer, not old
* test results. The original admission stays reachable through receipt lineage. */
function heartbeatLeaseTakeover(original: JsonObject, current: JsonObject,
identity: SettlementIdentity, previous: HeartbeatPreparedLease,
prepared: HeartbeatPreparedLease | null): JsonObject {
const reject = (): never => {throw receiptIdentityConflict(
"work requalification must preserve this Turn's original task lease generation unless a fenced current holder qualifies takeover");};
const source = jsonObject(current.lease_takeover_source);
const basis = jsonObject(source?.takeover_basis), todo = jsonObject(basis?.todo);
const leases = source?.leases;
const lease = Array.isArray(leases) && leases.length === 1 ? jsonObject(leases[0]) : null;
const old = heartbeatReceiptDetails(original);
if (!source || !basis || !todo || !lease || !prepared ||
typeof original.event_id !== "string" || !original.event_id ||
previous.prepared_lease_epoch === undefined || prepared.prepared_lease_epoch === undefined ||
source.goal_id !== identity.goal_id || source.todo_id !== identity.todo_id ||
source.handoff_mode !== "hard_lease" || !["file_v0", "sqlite_v0"].includes(String(source.source_authority)) ||
source.decision_read_from_provider !== true || source.legacy_fallback_used !== false ||
typeof source.provider_revision !== "string" || !source.provider_revision ||
typeof basis.acceptance_sha256 !== "string" || !BARE_SHA256_PATTERN.test(basis.acceptance_sha256) ||
todo.todo_id !== identity.todo_id || todo.role !== "agent" || todo.task_class !== "advancement_task" ||
todo.status !== "open" || todo.done === true || todo.archive_state !== "active" ||
todo.claimed_by !== identity.agent_id ||
(Array.isArray(todo.excluded_agents) && todo.excluded_agents.includes(identity.agent_id)) ||
lease.todo_id !== identity.todo_id || lease.owner !== identity.agent_id || lease.status !== "active" ||
leaseRepositoryRejection(todo, lease) !== null ||
typeof lease.idempotency_key !== "string" || !lease.idempotency_key ||
lease.version !== prepared.prepared_lease_version || lease.lease_epoch !== prepared.prepared_lease_epoch ||
prepared.prepared_lease_version <= previous.prepared_lease_version ||
prepared.prepared_lease_epoch <= previous.prepared_lease_epoch ||
prepared.prepared_lease_key_sha256 === previous.prepared_lease_key_sha256 ||
createHash("sha256").update(lease.idempotency_key).digest("hex") !== prepared.prepared_lease_key_sha256 ||
heartbeatPreparedWorkAdmission(original, identity) === null ||
normalizeHeartbeatReplanObligationId(old.semantic_replan_obligation_id) !== null ||
normalizeHeartbeatReplanObligationId(current.semantic_replan_obligation_id) !== null) return reject();
const clock = (value: unknown): bigint | null => typeof value === "string" ? parseTodoTimestampMicros(value, true) : null;
const at = clock(source.observed_at), admitted = clock(original.recorded_at),
acquired = clock(lease.acquired_at), updated = clock(lease.updated_at), expires = clock(lease.expires_at);
if (at === null || admitted === null || acquired === null || updated === null || expires === null ||
admitted > acquired || acquired > updated || updated > at || expires <= at) return reject();
return {append: true, details: {...old, ...prepared, settlement_receipt_revision: "lease_takeover",
takeover_original_event_id: original.event_id,
takeover_original_key_sha256: previous.prepared_lease_key_sha256,
takeover_original_version: previous.prepared_lease_version,
takeover_original_epoch: previous.prepared_lease_epoch,
takeover_owner: identity.agent_id, takeover_observed_at: source.observed_at,
takeover_expires_at: lease.expires_at, takeover_provider_revision: source.provider_revision,
takeover_todo_sha256: canonicalAuthoritySha256(todo), takeover_acceptance_sha256: basis.acceptance_sha256}};
}

/** Reject broken or rewritten takeover lineage during cold settlement reads. */
export function validateHeartbeatTakeoverParent(event: JsonObject, parent: JsonObject,
identity: SettlementIdentity): void {
const details = heartbeatReceiptDetails(event);
if (details.settlement_receipt_revision !== "lease_takeover") return;
const old = heartbeatPreparedWorkAdmission(parent, identity), current = heartbeatPreparedLease(details);
const fields = {takeover_original_event_id: details.takeover_original_event_id,
takeover_original_key_sha256: details.takeover_original_key_sha256,
takeover_original_version: details.takeover_original_version, takeover_original_epoch: details.takeover_original_epoch,
takeover_owner: details.takeover_owner, takeover_observed_at: details.takeover_observed_at,
takeover_expires_at: details.takeover_expires_at, takeover_provider_revision: details.takeover_provider_revision,
takeover_todo_sha256: details.takeover_todo_sha256, takeover_acceptance_sha256: details.takeover_acceptance_sha256};
const time = (value: unknown): bigint | null => typeof value === "string" ? parseTodoTimestampMicros(value, true) : null;
const at = time(details.takeover_observed_at), expires = time(details.takeover_expires_at), recorded = time(event.recorded_at);
if (!old || !current || old.prepared_lease_epoch === undefined ||
current.prepared_lease_epoch === undefined || current.prepared_lease_epoch <= old.prepared_lease_epoch ||
current.prepared_lease_version <= old.prepared_lease_version ||
current.prepared_lease_key_sha256 === old.prepared_lease_key_sha256 ||
details.takeover_original_event_id !== parent.event_id || details.takeover_owner !== identity.agent_id ||
details.takeover_original_key_sha256 !== old.prepared_lease_key_sha256 ||
details.takeover_original_version !== old.prepared_lease_version ||
details.takeover_original_epoch !== old.prepared_lease_epoch ||
!isDeepStrictEqual(details, {...heartbeatReceiptDetails(parent), ...current,
settlement_receipt_revision: "lease_takeover", ...fields}) ||
![details.takeover_todo_sha256, details.takeover_acceptance_sha256].every(value => typeof value === "string" && BARE_SHA256_PATTERN.test(value)) ||
typeof details.takeover_provider_revision !== "string" || !details.takeover_provider_revision ||
at === null || expires === null || recorded === null || expires <= at || recorded < at) {
throw receiptIdentityConflict("lease takeover does not preserve original admission and verified current ownership");
}
}

/** Reentry can qualify work on the original binding, never replace its authority.
* The caller commits this append-only projection under the receipt-log lock. */
export function heartbeatWorkRequalification(
Expand Down Expand Up @@ -338,7 +424,7 @@ export function heartbeatWorkRequalification(
(previous.prepared_lease_epoch === undefined
? preparedLease.prepared_lease_version !== previous.prepared_lease_version
: preparedLease.prepared_lease_epoch !== previous.prepared_lease_epoch))) {
throw receiptIdentityConflict("work requalification must preserve this Turn's original task lease generation");
return heartbeatLeaseTakeover(original, currentDetails, identity, previous, preparedLease);
}
if (nativeChildReportAdmission(oldDetails, original.status, identity.effect_id, phase, false, originalReplan)
.report_permission === "new_operation") {
Expand Down
Loading
Loading