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
18 changes: 18 additions & 0 deletions docs/reference/canonical-lease-renew.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,17 @@ execution authority.

For a new execution on an open, eligible Todo with no prior lease:

Omitting `--ttl-seconds` now uses **3 hours (10800 seconds)** instead of
45 minutes for managed `todo claim` and task-lease acquire/renew/transfer.
Explicit values remain bounded to 1..86400 seconds. Upgrading does not extend
existing leases or rewrite receipts. When replaying an older standalone lease
operation, pass its recorded TTL explicitly so the changed default does not
alter the original intent. Renew before expiry or release promptly when work ends: a longer default
also delays recovery from an abandoned holder.

未指定 `--ttl-seconds` 时,默认租约由 45 分钟改为 **3 小时**;显式时长仍为
1..86400 秒。升级不修改已有租约或原操作回执。长任务仍须到期前续租,完成后及时释放。

```bash
loopx --registry registry.json task-lease acquire \
--goal-id example-goal --todo-id todo_work --owner agent-a \
Expand All @@ -35,6 +46,13 @@ ignores ineligible holders. Standalone acquisition records explicitly requested
scopes. New managed claims keep the Todo's declared paths in the Todo detail
and acquire without a per-path list.

If the original Turn already admitted execution, expiry or release enters
execution-loss recovery. A new claim supplies only the control-writer proof
needed to close that original Turn without spending quota; it cannot resume
the old execution. Re-enter the original guard, follow its closeout preview,
and require a fresh admitted Turn before more delivery. A first claim on a
Turn that has not admitted execution still uses ordinary preparation.

## Repository-relative scope identity

New canonical acquisitions freeze the Todo's normalized `task_repository` as
Expand Down
2 changes: 1 addition & 1 deletion loopx/cli_commands/task_lease.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ def register_task_lease_command(
parser.add_argument(
"--ttl-seconds",
type=int,
help="Lease TTL in seconds. Defaults to 45 minutes and is capped at 24 hours.",
help="Lease TTL in seconds. Defaults to 3 hours and is capped at 24 hours.",
)
parser.add_argument(
"--write-scope",
Expand Down
2 changes: 1 addition & 1 deletion loopx/cli_commands/todo.py
Original file line number Diff line number Diff line change
Expand Up @@ -537,7 +537,7 @@ def handle_todo_command(
payload["instruction"] = (
"Continue the task. Use this original claim reference for progress "
"or completion; pass --ttl-seconds on claim (1..86400) for long "
"(>45m) execution wakes or renew via `loopx task-lease renew` "
"(>3h) execution wakes or renew via `loopx task-lease renew` "
"before lease_expires_at, and retain normal Turn settlement "
"(omitting --next-action on completed-Todo semantic_closeout "
"refresh-state)."
Expand Down
2 changes: 1 addition & 1 deletion loopx/cli_commands/todo_registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,7 @@ def register_todo_command(
type=int,
help=(
"For todo claim, optional lease TTL in seconds (1..86400; default "
"2700 = 45m). Pass a higher TTL on claim for long (>45m) execution "
"10800 = 3h). Pass a higher TTL on claim for long (>3h) execution "
"wakes, or renew via `task-lease renew` before expiry."
),
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
import { normalizeRegisteredTodoAgents, normalizeTodoAgent } from "./todo_agents.ts";
import {normalizeTodoRepository} from "../todos/work_requirements.ts";
import {leaseWriteRepository, leaseRepositoryRejection} from "../work_items/task_lease_repository.ts";
import {DEFAULT_TASK_LEASE_TTL_SECONDS} from "../work_items/task_lease_record.ts";

export const COORDINATION_TODO_TERMINAL_DECISION_REQUEST_SCHEMA =
"loopx_coordination_todo_terminal_decision_request_v0";
Expand Down Expand Up @@ -533,7 +534,7 @@ function terminalFence(
version,
lease_epoch: epoch,
write_scopes: [],
acquire_ttl_seconds: 2700,
acquire_ttl_seconds: DEFAULT_TASK_LEASE_TTL_SECONDS,
},
});
}
Expand Down
15 changes: 13 additions & 2 deletions loopx/control_plane/quota/execution_loss_closeout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,11 +157,22 @@ export async function observeFencedExecution(root: string, identity: ReturnType<
if (!todo || todo.status !== "open" || todo.role !== "agent" || todo.task_class !== "advancement_task"
|| todo.archive_state !== "active" || !rawLease) return null;
const lease = canonicalTaskLease(rawLease, identity.goal_id, identity.todo_id);
if (!fencesPreparedGeneration(prepared, lease)) return null;
// Expiry/release already ends the original execution. A fresh managed claim
// may establish the administrative writer, but must never be advertised as
// preparation to resume that execution. The commit still requires a newer
// generation and independently verifies it under the writer fence.
const now = new Date();
const originalLost = lease.lease_epoch === prepared.prepared_lease_epoch
&& typeof lease.version === "number" && Number.isSafeInteger(lease.version)
&& lease.version >= prepared.prepared_lease_version
&& typeof lease.idempotency_key === "string"
&& createHash("sha256").update(lease.idempotency_key).digest("hex") === prepared.prepared_lease_key_sha256
&& !leaseIsActive(lease, now);
if (!originalLost && !fencesPreparedGeneration(prepared, lease)) return null;
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, new Date());
const active = writerMatches && leaseIsActive(lease, now);
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};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -671,7 +671,7 @@ export function reduceUnsettledHostTurnRecovery(value: unknown): JsonObject {
if (writerRequired) obligation.reason = "the original execution lease is fenced and the current control-writer proof is unavailable";
obligation.recommended_action = executionLoss.current_control_writer_active === true
? "Use the original Turn and current control-writer proof for execution-loss closeout without debit. Verify the closeout before fresh work."
: "The original execution lease generation was replaced. Obtain authorized control-writer proof for the same Todo before execution-loss closeout. The replacement cannot resume the original business execution.";
: "The original execution lease is no longer available. Obtain authorized control-writer proof for the same Todo before execution-loss closeout. The replacement cannot resume the original business execution.";
}
return {
schema_version: UNSETTLED_HOST_TURN_RECOVERY_RESULT_SCHEMA,
Expand Down
2 changes: 1 addition & 1 deletion loopx/control_plane/work_items/task_lease.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
read_lease as read_lease,
)

DEFAULT_TASK_LEASE_TTL_SECONDS = 45 * 60
DEFAULT_TASK_LEASE_TTL_SECONDS = 3 * 60 * 60
MAX_TASK_LEASE_TTL_SECONDS = 24 * 60 * 60
IDEMPOTENCY_KEY_PATTERN = re.compile(r"^[A-Za-z0-9_.:@/-]{1,160}$")

Expand Down
5 changes: 2 additions & 3 deletions loopx/control_plane/work_items/task_lease_acquire.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,12 @@ import {
} from "../coordination/local_authority_shadow_outbox.ts";
import { TASK_LEASE_ACQUIRE_REQUEST_SCHEMA, TASK_LEASE_CANONICAL_ACQUIRE_REQUEST_SCHEMA } from "../coordination/coordination_state_contract.generated.ts";
import { BARE_SHA256_PATTERN } from "../content_digest.ts";
import {TASK_LEASE_SCHEMA_VERSION, TaskLeaseAcquireError, type LeaseRecord} from "./task_lease_record.ts";
import {TASK_LEASE_SCHEMA_VERSION, DEFAULT_TASK_LEASE_TTL_SECONDS, TaskLeaseAcquireError, type LeaseRecord} from "./task_lease_record.ts";
export {TASK_LEASE_SCHEMA_VERSION, TaskLeaseAcquireError, leaseInteger, leaseVersion,
leaseEpoch, leaseIsActive, type LeaseRecord} from "./task_lease_record.ts";

export const TASK_LEASE_ACQUIRE_REQUEST_SCHEMA_VERSION =
TASK_LEASE_ACQUIRE_REQUEST_SCHEMA;
const DEFAULT_TTL_SECONDS = 45 * 60;
const MAX_TTL_SECONDS = 24 * 60 * 60;
type FileState = "file" | "missing";
export type TodoFactField =
Expand Down Expand Up @@ -192,7 +191,7 @@ export function requireWriteScopes(value: unknown): string[] {

export function normalizeTtl(value: unknown): number {
const ttl = value === null || value === undefined
? DEFAULT_TTL_SECONDS
? DEFAULT_TASK_LEASE_TTL_SECONDS
: optionalInteger(value, "ttl_seconds");
if (ttl === null || ttl <= 0 || ttl > MAX_TTL_SECONDS) {
throw new TaskLeaseAcquireError(
Expand Down
1 change: 1 addition & 0 deletions loopx/control_plane/work_items/task_lease_record.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type {JsonObject} from "../effect_program.ts";
import {parseIsoTimestamp} from "../runtime_timestamp.ts";

export const TASK_LEASE_SCHEMA_VERSION = "task_lease_v0";
export const DEFAULT_TASK_LEASE_TTL_SECONDS = 3 * 60 * 60;

export interface LeaseRecord extends JsonObject {
schema_version?: unknown;
Expand Down
2 changes: 1 addition & 1 deletion loopx/pi_goal_mode/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ loopx_task_lease({
todoId: "todo_ab12cd34ef56",
idempotencyKey: "pi-turn-42",
writeScopes: ["loopx/**"],
ttlSeconds: 2700
ttlSeconds: 10800
})
```

Expand Down
28 changes: 28 additions & 0 deletions tests/control_plane/test_execution_loss_closeout_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -783,3 +783,31 @@ def test_original_turn_reentry_projects_execution_loss_without_repeating_work(
assert code == 0 and replay["idempotent_replay"] and not replay["appended"], replay
assert _receipt_lines(context) == before
_assert_no_completion_or_debit(context)


@pytest.mark.parametrize("provider", ["file", "sqlite"])
def test_original_lease_loss_claims_only_for_closeout(tmp_path, monkeypatch, capsys, provider):
context = _fixture(tmp_path, monkeypatch, capsys, provider, source_profile=False, replace=False)
original = context["original_lease"]
code, released = context["cli"]("task-lease", "release", "--goal-id", context["goal_id"],
"--todo-id", context["todo"], "--owner", OWNER, "--idempotency-key", original["idempotency_key"],
"--expected-version", str(original["version"]))
assert code == 0, released
code, recovery = context["cli"](*_guard_args(context))
assert code == 0, recovery
assert recovery.get("unsettled_host_turn_recovery", {}).get("repair") == "execution_loss_closeout"
assert recovery["normal_delivery_allowed"] is False
channel = recovery["interaction_contract"]["cli_channel"]
claims = [shlex.split(command) for command in channel["next_cli_actions"] if "todo claim" in command]
assert len(claims) == 1
code, claimed = context["cli"](*claims[0][claims[0].index("todo"):])
assert code == 0, claimed
code, ready = context["cli"](*_guard_args(context))
assert code == 0, ready
assert ready["normal_delivery_allowed"] is False
preview = _projected_preview_args(ready["interaction_contract"]["cli_channel"], _lease(context))
code, result = context["cli"](*preview)
assert code == 0 and result["would_close_without_spend"], result
code, closed = context["cli"](*preview[:-1])
assert code == 0 and closed["settlement_progress"]["no_spend"], closed
_assert_no_completion_or_debit(context)
5 changes: 5 additions & 0 deletions tests/control_plane/test_task_lease.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,11 @@ def test_normalize_ttl_seconds_rejects_out_of_range(ttl: int) -> None:
assert error.value.code == "invalid_ttl"


def test_task_lease_default_is_three_hours_with_explicit_override() -> None:
assert normalize_ttl_seconds(None) == 10800
assert normalize_ttl_seconds(2700) == 2700


@pytest.mark.parametrize("key", ["", "contains space", "bad$key"])
def test_normalize_idempotency_key_rejects_non_token(key: str) -> None:
with pytest.raises(TaskLeaseError) as error:
Expand Down
6 changes: 3 additions & 3 deletions tests/control_plane/test_todo_claim_argument_recovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -874,16 +874,16 @@ def test_claim_ttl_seconds_bounds_visibility_and_replay_parity(claim_cli, thin):
assert "lease_ttl_seconds: `7200`" in md.stdout


def test_claim_omitted_ttl_preserves_2700_default_and_explicit_lease_ttl(claim_cli):
def test_claim_omitted_ttl_uses_three_hours_and_preserves_explicit_lease_ttl(claim_cli):
_, run, _, prefix, claim, _, _, _ = claim_cli
default_claim = run([
*prefix, *claim, "--claimed-by", "peer-a", "--claim-operation-id", "claim-default-ttl",
])
assert default_claim["ok"] is True and default_claim["execution_managed"] is True
assert default_claim["lease_ttl_seconds"] == 2700
assert default_claim["lease_ttl_seconds"] == 10800
assert isinstance(default_claim["lease_expires_at"], str) and default_claim["lease_expires_at"]
inspected = run([*prefix, "task-lease", "inspect", "--goal-id", GOAL, "--todo-id", TODO])
assert inspected["lease"]["acquire_ttl_seconds"] == 2700
assert inspected["lease"]["acquire_ttl_seconds"] == 10800

# Release and verify explicit --task-lease-idempotency-key honors --ttl-seconds too.
released = run([
Expand Down
26 changes: 26 additions & 0 deletions tests/control_plane_ts/canonical_task_lease_renew.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ import {TASK_LEASE_CANONICAL_ACQUIRE_REQUEST_SCHEMA, TASK_LEASE_ACQUIRE_REQUEST_
TASK_LEASE_CANONICAL_CLAIM_TRANSFER_REQUEST_SCHEMA} from "../../loopx/control_plane/coordination/coordination_state_contract.generated.ts";
import {shadowManagementStatePath} from "../../loopx/control_plane/coordination/shadow_management.ts";
import {atomicWriteJson} from "../../loopx/control_plane/effect_runtime_io.ts";
import {observeFencedExecution} from "../../loopx/control_plane/quota/execution_loss_closeout.ts";
import {settlementIdentity} from "../../loopx/control_plane/effect_program.ts";

const NOW = new Date("2026-09-13T10:05:00Z");
const CHILD = fileURLToPath(new URL("./canonical_task_lease_renew_process.ts", import.meta.url));
Expand Down Expand Up @@ -108,6 +110,30 @@ for (const provider of ["file", "sqlite"] as const) {
expected_version: 1, ttl_seconds: 600, write_scopes: ["src/**"], authority: request.authority};
}
const acquireNow = new Date("2026-09-13T10:11:00Z");
providerTest(`${provider} original expiry projects administrative recovery, never delivery`, async t => {
const {runtime, goal, lease} = await fixture(t, provider);
const identity = settlementIdentity({goal_id: goal, agent_id: "agent-a", todo_id: "todo_renew",
turn_instance_id: "original-turn"});
const details = {todo_id: "todo_renew", settlement_effect_id: identity.effect_id,
closeout_required: true, prepared_lease_required: true, ok: true, should_run: true,
must_attempt_work: true, delivery_allowed: true, quiet_noop_allowed: false,
prepared_lease_key_sha256: createHash("sha256").update(lease.idempotency_key).digest("hex"),
prepared_lease_version: lease.version, prepared_lease_epoch: lease.lease_epoch};
const receipt = {schema_version: "loopx_rollout_event_v0", event_kind: "quota_should_run",
event_id: "original-admission", goal_id: goal, agent_id: "agent-a", run_id: "original-turn",
recorded_at: "2026-09-13T10:01:00Z", status: "normal_run", details};
t.mock.timers.enable({apis: ["Date"], now: NOW});
assert.equal(await observeFencedExecution(runtime, identity, receipt), null);
t.mock.timers.setTime(new Date(lease.expires_at).valueOf());
const lost = await observeFencedExecution(runtime, identity, receipt);
assert.equal(lost?.can_reclaim_control_writer, true);
assert.equal(lost?.current_control_writer_active, false);
assert.equal(lost?.original_prepared_epoch, lost?.current_lease_epoch);
for (const patch of [{prepared_lease_key_sha256: "a".repeat(64)},
{prepared_lease_version: lease.version + 1}, {delivery_allowed: false}]) {
assert.equal(await observeFencedExecution(runtime, identity, {...receipt, details: {...details, ...patch}}), null);
}
});
providerTest(`${provider} malformed receipt scopes cannot become a root wildcard`, async t => {
const {store, request, lease, goal} = await fixture(t, provider);
const command = {...acquireRequest(request), write_scopes: ["**"]};
Expand Down
8 changes: 8 additions & 0 deletions tests/control_plane_ts/task_lease_acquire.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,18 @@ import test from "node:test";

import {
executeTaskLeaseAcquire,
normalizeTtl,
TASK_LEASE_ACQUIRE_REQUEST_SCHEMA_VERSION,
} from "../../loopx/control_plane/work_items/task_lease_acquire.ts";
import {TASK_LEASE_CANONICAL_ACQUIRE_REQUEST_SCHEMA} from "../../loopx/control_plane/coordination/coordination_state_contract.generated.ts";

test("omitted task lease TTL is three hours while explicit bounds remain unchanged", () => {
assert.equal(normalizeTtl(undefined), 10800);
assert.equal(normalizeTtl(null), 10800);
for (const seconds of [1, 600, 2700, 86400]) assert.equal(normalizeTtl(seconds), seconds);
for (const seconds of [0, -1, 86401]) assert.throws(() => normalizeTtl(seconds));
});

function request(runtimeRoot: string, schemaVersion: string) {
return {
schema_version: schemaVersion,
Expand Down
Loading