diff --git a/docs/reference/goal-acceptance-observations.md b/docs/reference/goal-acceptance-observations.md index 345ee46471..cc0ff5ef8e 100644 --- a/docs/reference/goal-acceptance-observations.md +++ b/docs/reference/goal-acceptance-observations.md @@ -163,7 +163,9 @@ Goal 完成;要求/工作变化使依据过期,产物修改后须重新核 Native `goal-acceptance` and outcome-update `refresh-state` rejections retain their stable error code. A known outcome validation rule also supplies optional -`error_detail`, such as `source ref must be an opaque identifier`, in JSON and +`error_detail`, such as +`source ref must be an opaque identifier (ASCII letters/digits and . _ : @ -, no '/' paths or spaces)`, +in JSON and Markdown. This detail contains fixed rule text and validator-measured byte counts, never the rejected value or provider/IO context. Validation rejection writes nothing: after confirming that result, correct the document and retry @@ -183,7 +185,7 @@ other available Goals. 中文:原生 `goal-acceptance` 和成果更新 `refresh-state` 拒绝保留稳定错误码。 已知成果校验规则还会在 JSON 与 Markdown 中提供可选 `error_detail`,例如 -`source ref must be an opaque identifier`。详情只包含固定规则及校验器实测字节数,不回显被拒值或 +`source ref must be an opaque identifier (ASCII letters/digits and . _ : @ -, no '/' paths or spaces)`。详情只包含固定规则及校验器实测字节数,不回显被拒值或 provider/IO 上下文。校验拒绝不写入状态;确认这一结果后,修正文档并沿用原操作和 仍有效的 provider revision 重试。写入结果不确定时继续遵循原有回执与恢复规则。 成功操作和未标记错误保持既有行为。 diff --git a/loopx/cli_commands/todo.py b/loopx/cli_commands/todo.py index dd46614ffb..fb8a9e5aa9 100644 --- a/loopx/cli_commands/todo.py +++ b/loopx/cli_commands/todo.py @@ -521,6 +521,7 @@ def handle_todo_command( claim_operation_id=args.claim_operation_id, task_lease_idempotency_key=args.task_lease_idempotency_key, task_lease_expected_version=args.task_lease_expected_version, + ttl_seconds=args.ttl_seconds, **_todo_path_args(args), dry_run=bool(args.dry_run), ) @@ -560,10 +561,22 @@ def handle_todo_command( ] payload["instruction"] = ( "Continue the task. Use this original claim reference for progress " - "or completion; retain normal Turn settlement when applicable." + "or completion; pass --ttl-seconds on claim (1..86400) for long " + "(>45m) 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)." ) - # Normal callers need the accepted task reference, not lease - # counters or a second inline copy of the native receipt. + # Extract compact lease deadline/TTL scalars before removing + # internal lease CAS counters or a second copy of the receipt. + lease = payload.get("lease") + if isinstance(lease, dict): + expires_at = lease.get("expires_at") + if isinstance(expires_at, str) and expires_at: + payload["lease_expires_at"] = expires_at + acquire_ttl = lease.get("acquire_ttl_seconds") + if isinstance(acquire_ttl, int) and not isinstance(acquire_ttl, bool): + payload["lease_ttl_seconds"] = acquire_ttl for internal in ( "lease", "lease_changed", diff --git a/loopx/cli_commands/todo_argument_validation.py b/loopx/cli_commands/todo_argument_validation.py index 469b20f582..b612651ef1 100644 --- a/loopx/cli_commands/todo_argument_validation.py +++ b/loopx/cli_commands/todo_argument_validation.py @@ -46,6 +46,7 @@ ("--claimed-by", "claimed_by"), ("--task-lease-idempotency-key", "task_lease_idempotency_key"), ("--task-lease-expected-version", "task_lease_expected_version"), + ("--ttl-seconds", "ttl_seconds"), ("--bound-agent", "bound_agent"), ("--goal-bound", "goal_bound"), ("--blocks-agent", "blocks_agent"), @@ -153,8 +154,8 @@ "plan": frozenset({"text", "agent_id", "project"}), "project-markdown": frozenset({"state_file", "execute", "provider_revision", "project"}), "claim": frozenset({"role", "todo_id", "claimed_by", "agent_id", "state_file", - "claim_operation_id", "task_lease_idempotency_key", "task_lease_expected_version", - "project", "dry_run", "todo_thin"}), + "claim_operation_id", "ttl_seconds", "task_lease_idempotency_key", + "task_lease_expected_version", "project", "dry_run", "todo_thin"}), "update": frozenset(_TODO_UPDATE_MUTABLE_FIELDS) | frozenset({ "role", "todo_id", "agent_id", "state_file", "project", "dry_run", "authority_reason", "claim_operation_id", "update_operation_id", "update_expected_provider_revision", @@ -437,7 +438,7 @@ def validate_todo_claim_options(args: argparse.Namespace) -> None: if unsupported: raise TodoClaimArgumentError( "todo claim only accepts --todo-id, --claimed-by, --agent-id, optional --role, " - "--claim-operation-id, --task-lease-idempotency-key, " + "--claim-operation-id, --ttl-seconds, --task-lease-idempotency-key, " "--task-lease-expected-version, --project, --state-file, --dry-run, and --thin; unsupported: " + ", ".join(unsupported) ) @@ -445,6 +446,16 @@ def validate_todo_claim_options(args: argparse.Namespace) -> None: raise TodoClaimArgumentError( "--task-lease-expected-version requires --task-lease-idempotency-key" ) + if args.ttl_seconds is not None: + if args.ttl_seconds <= 0 or args.ttl_seconds > 86400: + raise ValueError("ttl seconds must be between 1 and 86400") + if args.task_lease_idempotency_key is None and ( + args.agent_id is None or args.agent_id != args.claimed_by + ): + raise ValueError( + "--ttl-seconds requires managed execution (--agent-id matching --claimed-by) " + "or --task-lease-idempotency-key" + ) def validate_todo_update_options(args: argparse.Namespace) -> None: @@ -718,6 +729,8 @@ def validate_shared_todo_options(args: argparse.Namespace) -> None: "--task-lease-idempotency-key and --task-lease-expected-version " "are supported only by todo claim, todo update, todo complete, and todo supersede" ) + if args.todo_command != "claim" and getattr(args, "ttl_seconds", None) is not None: + raise ValueError("--ttl-seconds is supported only by todo claim") if args.capability_binding_ref and args.todo_command != "add": raise ValueError( "--capability-binding-ref is immutable and supported only by todo add" diff --git a/loopx/cli_commands/todo_registration.py b/loopx/cli_commands/todo_registration.py index 0bec8edaf1..1b92fc0d48 100644 --- a/loopx/cli_commands/todo_registration.py +++ b/loopx/cli_commands/todo_registration.py @@ -307,6 +307,15 @@ def register_todo_command( # use claim_operation_id; do not advertise the host transport as task work. todo_parser.add_argument("--task-lease-idempotency-key", help=argparse.SUPPRESS) todo_parser.add_argument("--task-lease-expected-version", type=int, help=argparse.SUPPRESS) + todo_parser.add_argument( + "--ttl-seconds", + 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 " + "wakes, or renew via `task-lease renew` before expiry." + ), + ) todo_parser.add_argument( "--bound-agent", help=( diff --git a/loopx/control_plane/coordination/claim_execution.ts b/loopx/control_plane/coordination/claim_execution.ts index 04c2e2875e..da9dd22acf 100644 --- a/loopx/control_plane/coordination/claim_execution.ts +++ b/loopx/control_plane/coordination/claim_execution.ts @@ -99,7 +99,7 @@ export function maintainClaimExecution(head: JsonObject, input: ExecutionInput, * transfer grant). Expired execution is reclaimable without the old process; * acquisition still validates scope, eligibility and generation under one CAS. */ export async function prepareClaimExecution(head: JsonObject, - input: ExecutionInput & {operation_id: string; claimed_by: string}, + input: ExecutionInput & {operation_id: string; claimed_by: string; ttl_seconds?: number}, observeWorkspace?: ClaimWorkspaceObserver): Promise<{lease: LeaseRecord; changed: boolean; overlapAdvisories?: JsonObject[]}> { const index = indexCoordinationProjection(head, input.goal_id); const facts = canonicalTaskLeaseAcquireFacts(index, input.goal_id, input.todo_id, input.registered_agents, input.now); @@ -119,7 +119,7 @@ export async function prepareClaimExecution(head: JsonObject, const command = {owner: input.claimed_by, idempotency_key: `claim-${canonicalAuthoritySha256({goal_id: input.goal_id, todo_id: input.todo_id, owner: input.claimed_by, operation_id: input.operation_id})}`, - expected_version: current ? leaseVersion(current) : 0, ttl_seconds: normalizeTtl(null), + expected_version: current ? leaseVersion(current) : 0, ttl_seconds: normalizeTtl(input.ttl_seconds), write_scopes: writeScopes, ...(workspace ? {write_workspace: workspace} : {})}; const decision = evaluateTaskLeaseAcquireDecision({handoff_mode: String(head.handoff_mode), registered_agents: [...input.registered_agents], ...facts, diff --git a/loopx/control_plane/coordination/local_authority.py b/loopx/control_plane/coordination/local_authority.py index 5717d8331b..922d23dcfb 100644 --- a/loopx/control_plane/coordination/local_authority.py +++ b/loopx/control_plane/coordination/local_authority.py @@ -191,6 +191,7 @@ def claim_canonical_todo_if_promoted( operation_id: str | None = None, task_lease_idempotency_key: str | None = None, task_lease_expected_version: int | None = None, + ttl_seconds: int | None = None, manage_execution: bool = False, expected_provider_revision: str | None = None, expected_registry_sha256: str | None = None, @@ -202,6 +203,15 @@ def claim_canonical_todo_if_promoted( reviewed = expected_provider_revision is not None or expected_registry_sha256 is not None if reviewed and not (manage_execution and expected_provider_revision and expected_registry_sha256): raise ValueError("A reviewed managed claim requires both canonical revision and registry digest") + if ttl_seconds is not None and ( + isinstance(ttl_seconds, bool) + or not isinstance(ttl_seconds, int) + or ttl_seconds <= 0 + or ttl_seconds > 86400 + ): + raise ValueError("ttl seconds must be between 1 and 86400") + if ttl_seconds is not None and task_lease_idempotency_key is None and not manage_execution: + raise ValueError("ttl_seconds requires managed execution or task_lease_idempotency_key") with authority_registry_source(registry_path, routing_registry_witness=routing_registry_witness) as registry_source: registered = registered_agent_ids_from_registry(registry_path, goal_id) # This is only a candidate location. The lease owner observes physical @@ -229,6 +239,11 @@ def claim_canonical_todo_if_promoted( else f"todo-claim:{goal_id}:{todo_id}:{uuid4().hex}" ), **({"manage_execution": True} if manage_execution else {}), + **( + {"ttl_seconds": ttl_seconds} + if task_lease_idempotency_key is None and ttl_seconds is not None + else {} + ), **( {"expected_provider_revision": expected_provider_revision, "expected_registry_sha256": expected_registry_sha256} @@ -239,7 +254,7 @@ def claim_canonical_todo_if_promoted( { "idempotency_key": task_lease_idempotency_key, "expected_version": task_lease_expected_version, - "ttl_seconds": None, + "ttl_seconds": ttl_seconds, } if task_lease_idempotency_key is not None else None diff --git a/loopx/control_plane/coordination/local_authority_runtime.ts b/loopx/control_plane/coordination/local_authority_runtime.ts index 9889a97e27..b891036f9e 100644 --- a/loopx/control_plane/coordination/local_authority_runtime.ts +++ b/loopx/control_plane/coordination/local_authority_runtime.ts @@ -1057,6 +1057,12 @@ export async function claimLocalCoordinationTodo( } if (Object.hasOwn(input, "manage_execution") && !managed) throw new TypeError("Managed execution requires claim request v2"); + const hasTopLevelTtl = Object.hasOwn(input, "ttl_seconds") + && input.ttl_seconds !== undefined && input.ttl_seconds !== null; + if (hasTopLevelTtl && !managed) { + throw new TypeError("Managed execution TTL requires claim request v2"); + } + const topLevelTtl = hasTopLevelTtl ? normalizeTtl(input.ttl_seconds) : undefined; if (reviewed ? input.manage_execution !== true || typeof input.expected_registry_sha256 !== "string" : Object.hasOwn(input, "expected_registry_sha256")) throw new TypeError("A Todo claim review basis requires a reviewed managed claim"); @@ -1116,6 +1122,7 @@ export async function claimLocalCoordinationTodo( operation_id: requireAuthorityStoreId(input.operation_id, "operation id"), lease_request: leaseRequest, ...(input.manage_execution === undefined ? {} : {manage_execution: input.manage_execution as boolean}), + ...(topLevelTtl === undefined ? {} : {ttl_seconds: topLevelTtl}), ...(expectedRevision === undefined ? {} : {expected_provider_revision: expectedRevision}), dry_run: input.dry_run === true, now: claimObservedAt(input.observed_at), diff --git a/loopx/control_plane/coordination/todo_claim.ts b/loopx/control_plane/coordination/todo_claim.ts index 12e5a8b0ef..df0c18fea2 100644 --- a/loopx/control_plane/coordination/todo_claim.ts +++ b/loopx/control_plane/coordination/todo_claim.ts @@ -65,6 +65,7 @@ export interface CoordinationTodoClaimInput { readonly replan_obligation_id?: string; readonly lease_request?: CoordinationTodoClaimLeaseRequest | null; readonly manage_execution?: boolean; + readonly ttl_seconds?: number; /** Admission constraint on every attempt and replay, not a new business intent. */ readonly required_handoff_mode?: ExecutionHandoffMode; readonly dry_run: boolean; @@ -376,6 +377,8 @@ async function executeClaimAttempt( ? null : normalizeTodoAgent(rawInput.actor_agent_id, "actor_agent_id"), registered_agents: normalizeRegisteredTodoAgents(rawInput.registered_agents), lease_request: normalizeLeaseRequest(rawInput.lease_request), + ttl_seconds: rawInput.ttl_seconds === undefined || rawInput.ttl_seconds === null + ? undefined : normalizeTtl(rawInput.ttl_seconds), }; if (input.manage_execution !== undefined) requireAuthorityBoolean(input.manage_execution, "manage_execution"); if (input.required_handoff_mode !== undefined && !EXECUTION_HANDOFF_MODES.includes(input.required_handoff_mode)) { @@ -384,6 +387,9 @@ async function executeClaimAttempt( if (input.manage_execution && (input.lease_request != null || input.actor_agent_id !== input.claimed_by)) { throw new AuthorityStoreProtocolError("Managed execution requires the claiming actor and no explicit lease request"); } + if (input.ttl_seconds !== undefined && !input.manage_execution) { + throw new AuthorityStoreProtocolError("Managed execution TTL requires manage_execution and no explicit lease request"); + } requireAuthorityBoolean(input.dry_run, "dry_run"); requireAuthorityDate(input.now, "now"); } catch (error) { @@ -413,6 +419,7 @@ async function executeClaimAttempt( dry_run: input.dry_run, ...(leaseRequest === null ? {} : {lease_request: leaseRequest}), ...(input.manage_execution ? {manage_execution: true} : {}), + ...(input.ttl_seconds === undefined ? {} : {ttl_seconds: input.ttl_seconds}), ...(input.replan_obligation_id === undefined ? {} : {replan_obligation_id: input.replan_obligation_id}), }; const requestSha = canonicalAuthoritySha256(requestIdentity); diff --git a/loopx/control_plane/goals/outcome_requirements.ts b/loopx/control_plane/goals/outcome_requirements.ts index bfcb59154e..6790d72fbb 100644 --- a/loopx/control_plane/goals/outcome_requirements.ts +++ b/loopx/control_plane/goals/outcome_requirements.ts @@ -41,7 +41,10 @@ function text(value: unknown, label: string, max = 512): string { } function id(value: unknown, label: string): string { const result = text(value, label, 128); - requireValue(/^[A-Za-z0-9][A-Za-z0-9_.:@-]*$/.test(result), `${label} must be an opaque identifier`); + requireValue( + /^[A-Za-z0-9][A-Za-z0-9_.:@-]*$/.test(result), + `${label} must be an opaque identifier (ASCII letters/digits and . _ : @ -, no '/' paths or spaces)`, + ); return result; } function keys(row: JsonObject, required: string[], optional: string[] = []): void { diff --git a/loopx/control_plane/todos/markdown.py b/loopx/control_plane/todos/markdown.py index a5037a75bc..e5f0b53bb1 100644 --- a/loopx/control_plane/todos/markdown.py +++ b/loopx/control_plane/todos/markdown.py @@ -194,6 +194,16 @@ def cell(value: Any) -> str: return "\n".join(lines) +def _render_execution_managed_claim_lines(payload: dict[str, Any]) -> list[str]: + """Render compact managed-claim lease metadata alongside claim identity.""" + lines = ["", f"- claim_operation_id: `{payload['claim_operation_id']}`"] + if payload.get("lease_expires_at"): + lines.append(f"- lease_expires_at: `{payload['lease_expires_at']}`") + if payload.get("lease_ttl_seconds") is not None: + lines.append(f"- lease_ttl_seconds: `{payload['lease_ttl_seconds']}`") + return lines + + def render_todo_markdown(payload: dict[str, Any]) -> str: if payload.get("todo_detail_projection"): return _render_todo_detail(payload) @@ -370,7 +380,7 @@ def render_todo_markdown(payload: dict[str, Any]) -> str: lines.extend(["", str(payload["instruction"])]) lines.extend(_render_settlement_plan(payload["settlement_plan"])) if not payload.get("error") and payload.get("execution_managed"): - lines.extend(["", f"- claim_operation_id: `{payload['claim_operation_id']}`"]) + lines.extend(_render_execution_managed_claim_lines(payload)) if not payload.get("error"): lines.extend(render_settlement_progress_markdown(payload)) if not payload.get("error") and (payload.get("execution_managed") or payload.get("settlement_progress")): diff --git a/loopx/control_plane/todos/mutation_api.py b/loopx/control_plane/todos/mutation_api.py index e5f4da8db0..53048d1a81 100644 --- a/loopx/control_plane/todos/mutation_api.py +++ b/loopx/control_plane/todos/mutation_api.py @@ -313,6 +313,7 @@ def update_goal_todo( routing_registry_witness: dict[str, str] | None = None, task_lease_idempotency_key: str | None = None, task_lease_expected_version: int | None = None, + ttl_seconds: int | None = None, project: Path | None = None, state_file: Path | None = None, dry_run: bool = False, @@ -349,7 +350,16 @@ def update_goal_todo( raise ValueError( "--task-lease-expected-version requires --task-lease-idempotency-key" ) + if not claim_only and ttl_seconds is not None: + raise ValueError("ttl_seconds is supported only by todo claim") if claim_only: + if ttl_seconds is not None and ( + isinstance(ttl_seconds, bool) + or not isinstance(ttl_seconds, int) + or ttl_seconds <= 0 + or ttl_seconds > 86400 + ): + raise ValueError("ttl seconds must be between 1 and 86400") unsupported_claim_values = ( text, priority, clear_priority or None, status, note, validation_command, validation_command_json, validation_label, @@ -390,6 +400,7 @@ def update_goal_todo( routing_registry_witness=routing_registry_witness, task_lease_idempotency_key=task_lease_idempotency_key, task_lease_expected_version=task_lease_expected_version, + ttl_seconds=ttl_seconds, project=project, state_file=state_file, ) diff --git a/tests/control_plane/test_goal_outcome_diagnostics.py b/tests/control_plane/test_goal_outcome_diagnostics.py index 59ebd19bb1..27985fe0a4 100644 --- a/tests/control_plane/test_goal_outcome_diagnostics.py +++ b/tests/control_plane/test_goal_outcome_diagnostics.py @@ -40,7 +40,10 @@ def arguments(project, cli, entrypoint, document, operation): @pytest.mark.parametrize("entrypoint", ["refine", "refresh"]) @pytest.mark.parametrize(("source_ref", "detail"), [ - ("synthetic/private-ref", "source ref must be an opaque identifier"), + ( + "synthetic/private-ref", + "source ref must be an opaque identifier (ASCII letters/digits and . _ : @ -, no '/' paths or spaces)", + ), ("synthetic-private-ref ", "source ref must be bounded nonempty text"), ]) def test_native_rejection_then_corrected_same_operation(acceptance_goal, entrypoint, source_ref, detail): diff --git a/tests/control_plane/test_todo_claim_argument_recovery.py b/tests/control_plane/test_todo_claim_argument_recovery.py index 871640cd88..2a9ad438e3 100644 --- a/tests/control_plane/test_todo_claim_argument_recovery.py +++ b/tests/control_plane/test_todo_claim_argument_recovery.py @@ -795,5 +795,107 @@ def test_task_help_exposes_managed_reference_not_host_lease_flags(): result = subprocess.run([sys.executable, "-m", "loopx.cli", "todo", "claim", "--help"], cwd=REPO, capture_output=True, text=True, check=True) assert "--claim-operation-id" in result.stdout + assert "--ttl-seconds" in result.stdout assert "--task-lease-idempotency-key" not in result.stdout assert "--task-lease-expected-version" not in result.stdout + + +@pytest.mark.parametrize("thin", [False, True]) +def test_claim_ttl_seconds_bounds_visibility_and_replay_parity(claim_cli, thin): + _, run, snapshot, prefix, claim, _, _, _ = claim_cli + before = snapshot() + + for bad_ttl in (0, 86401): + rejected = run([ + *prefix, *claim, "--claimed-by", "peer-a", + "--ttl-seconds", str(bad_ttl), + *(["--thin"] if thin else []), + ], expected_exit=1) + assert rejected["ok"] is False + assert "1 and 86400" in rejected["error"] + assert snapshot() == before + + unmanaged = run([ + *prefix, "todo", "claim", "--goal-id", GOAL, "--todo-id", TODO, + "--claimed-by", "peer-a", "--ttl-seconds", "7200", + ], expected_exit=1) + assert unmanaged["ok"] is False + assert "--ttl-seconds requires managed execution" in unmanaged["error"] + assert snapshot() == before + + accepted = run([ + *prefix, *claim, "--claimed-by", "peer-a", + "--claim-operation-id", f"claim-long-{thin}", + "--ttl-seconds", "7200", + *(["--thin"] if thin else []), + ]) + assert accepted["ok"] is True and accepted["execution_managed"] is True + assert "lease" not in accepted + assert accepted["lease_ttl_seconds"] == 7200 + assert isinstance(accepted["lease_expires_at"], str) and accepted["lease_expires_at"].endswith("Z") + assert "--ttl-seconds" in accepted["instruction"] + assert "task-lease renew" in accepted["instruction"] + assert "--next-action" in accepted["instruction"] + + inspected = run([*prefix, "task-lease", "inspect", "--goal-id", GOAL, "--todo-id", TODO]) + assert inspected["active"] is True + assert inspected["lease"]["acquire_ttl_seconds"] == 7200 + assert inspected["lease"]["expires_at"] == accepted["lease_expires_at"] + + replayed = run([ + *prefix, *claim, "--claimed-by", "peer-a", + "--claim-operation-id", f"claim-long-{thin}", + "--ttl-seconds", "7200", + *(["--thin"] if thin else []), + ]) + assert replayed["ok"] is True and replayed["status"] == "replayed" + assert replayed["lease_ttl_seconds"] == 7200 + assert replayed["lease_expires_at"] == accepted["lease_expires_at"] + + mismatched = run([ + *prefix, *claim, "--claimed-by", "peer-a", + "--claim-operation-id", f"claim-long-{thin}", + "--ttl-seconds", "3600", + ], expected_exit=1) + assert mismatched["ok"] is False + assert mismatched["error_code"] == "coordination_operation_identity_mismatch" + + md = subprocess.run( + [ + sys.executable, "-m", "loopx.cli", + *prefix[:-2], "--format", "markdown", + *claim, "--claimed-by", "peer-a", + "--claim-operation-id", f"claim-long-{thin}", + "--ttl-seconds", "7200", + ], + cwd=REPO, capture_output=True, text=True, timeout=90, check=True, + ) + assert f"lease_expires_at: `{accepted['lease_expires_at']}`" in md.stdout + assert "lease_ttl_seconds: `7200`" in md.stdout + + +def test_claim_omitted_ttl_preserves_2700_default_and_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 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 + + # Release and verify explicit --task-lease-idempotency-key honors --ttl-seconds too. + released = run([ + *prefix, "task-lease", "release", "--goal-id", GOAL, "--todo-id", TODO, + "--owner", "peer-a", "--idempotency-key", inspected["lease"]["idempotency_key"], + "--expected-version", str(inspected["lease"]["version"]), + ]) + assert released["ok"] is True + explicit = run([ + *prefix, *claim, "--claimed-by", "peer-a", "--claim-operation-id", "claim-explicit-ttl", + "--task-lease-idempotency-key", "explicit-ttl-key", "--task-lease-expected-version", "1", + "--ttl-seconds", "5400", + ]) + assert explicit["ok"] is True + assert explicit["lease"]["acquire_ttl_seconds"] == 5400 diff --git a/tests/control_plane_ts/local_authority_runtime.test.ts b/tests/control_plane_ts/local_authority_runtime.test.ts index a9110392e2..2dcdd75562 100644 --- a/tests/control_plane_ts/local_authority_runtime.test.ts +++ b/tests/control_plane_ts/local_authority_runtime.test.ts @@ -1841,6 +1841,9 @@ test("managed execution fields cannot be ignored by older public transports", as const result = await runtime.claimLocalCoordinationTodo({schema_version: `loopx_local_coordination_todo_claim_request_v${v}`, manage_execution: true}, noStore); assert.match(String(result.reason), /requires claim request v2/); + const ttlResult = await runtime.claimLocalCoordinationTodo({schema_version: `loopx_local_coordination_todo_claim_request_v${v}`, + ttl_seconds: 7200}, noStore); + assert.match(String(ttlResult.reason), /Managed execution TTL requires claim request v2/); } for (const v of [0, 1, 2, 3, 4, 5]) { const result = await runtime.updateLocalCoordinationTodo({schema_version: `loopx_local_coordination_todo_update_request_v${v}`, diff --git a/tests/control_plane_ts/managed_claim_execution_conformance.ts b/tests/control_plane_ts/managed_claim_execution_conformance.ts index 54bda5ab23..e7d5f8444f 100644 --- a/tests/control_plane_ts/managed_claim_execution_conformance.ts +++ b/tests/control_plane_ts/managed_claim_execution_conformance.ts @@ -249,6 +249,45 @@ export function registerManagedClaimExecutionConformance(provider: string, facto assert.equal((await execute({...original, claim_operation_id: String(prepared.claim_operation_id)})).status, "applied"); } }); + test(`${provider} managed execution: explicit ttl_seconds controls expiry, final-third renewal, bounds and replay identity`, async t => { + const {store, request, progress} = await setup(t); + const before = await loaded(store); + for (const invalid of [0, 86401]) { + const rejected = await claim(store, {...request, operation_id: `bad-ttl-${invalid}`, ttl_seconds: invalid}); + assert.equal(rejected.status, "failed"); + assert.equal(rejected.reason_code, "invalid_coordination_todo_claim"); + assert.match(String(rejected.reason), /ttl seconds must be between 1 and 86400/); + assert.deepEqual(await loaded(store), before); + } + const longClaim = await claim(store, {...request, operation_id: "claim-long-ttl", ttl_seconds: 7200}); + assert.equal(longClaim.status, "applied", JSON.stringify(longClaim)); + const lease = longClaim.lease as JsonObject; + assert.equal(lease.acquire_ttl_seconds, 7200); + assert.equal(lease.expires_at, "2026-09-13T12:00:00Z"); + const unchangedReplay = await claim(store, { + ...request, operation_id: "claim-long-ttl", ttl_seconds: 7200, now: new Date("2026-09-13T10:30:00Z"), + }); + assert.equal(unchangedReplay.status, "replayed"); + assert.equal((unchangedReplay.lease as JsonObject).acquire_ttl_seconds, 7200); + const mismatchedReplay = await claim(store, { + ...request, operation_id: "claim-long-ttl", ttl_seconds: 3600, now: new Date("2026-09-13T10:30:00Z"), + }); + assert.equal(mismatchedReplay.status, "failed"); + assert.equal(mismatchedReplay.reason_code, "coordination_operation_identity_mismatch"); + // 10:31 is outside the final third of a 7200s lease (only 4440s left, > 2400s), so early update never renews; + // 11:25 (only 2100s <= 2400s left) renews with the same 7200s TTL. + assert.equal((await update(store, {...progress, claim_operation_id: "claim-long-ttl", + operation_id: "early-long-progress", now: new Date("2026-09-13T10:31:00Z")})).status, "applied"); + let current = await loaded(store); + assert.equal((current.head.leases as JsonObject[])[0]!.version, 1); + assert.equal((await update(store, {...progress, claim_operation_id: "claim-long-ttl", + operation_id: "late-long-progress", now: new Date("2026-09-13T11:25:00Z")})).status, "applied"); + current = await loaded(store); + const renewed = (current.head.leases as JsonObject[])[0]!; + assert.equal(renewed.version, 2); + assert.equal(renewed.acquire_ttl_seconds, 7200); + assert.equal(renewed.expires_at, "2026-09-13T13:25:00Z"); + }); test(`${provider} managed execution: changed identity requires reconciliation instead of claim adoption`, async t => { for (const change of [{owner: "agent-b"}, {lease_epoch: 2, version: 2}, {idempotency_key: "different-execution"}, {write_repository: "git:github.com/example/other"}, diff --git a/tests/test_cli_argument_diagnostics.py b/tests/test_cli_argument_diagnostics.py index 9c886f6909..fa353f10c5 100644 --- a/tests/test_cli_argument_diagnostics.py +++ b/tests/test_cli_argument_diagnostics.py @@ -556,7 +556,7 @@ def test_monitor_change_scope_requires_material_transition() -> None: "Continue the work.", ], "todo claim only accepts --todo-id, --claimed-by, --agent-id, optional --role, " - "--claim-operation-id, --task-lease-idempotency-key, " + "--claim-operation-id, --ttl-seconds, --task-lease-idempotency-key, " "--task-lease-expected-version, --project, --state-file, --dry-run, and --thin; unsupported: " "--decision-outcome, --next-agent-todo", ), @@ -598,6 +598,35 @@ def test_managed_claim_reference_is_retained_for_the_execution_owner(command, op assert args.claim_operation_id == operation_id +@pytest.mark.parametrize("command", ["add", "list", "update", "complete", "supersede"]) +def test_ttl_seconds_is_rejected_on_non_claim_todo_commands(command): + args = build_parser().parse_args([ + "todo", command, "--goal-id", "example-goal", "--ttl-seconds", "7200", + ]) + with pytest.raises(ValueError, match="--ttl-seconds is supported only by todo claim"): + validate_shared_todo_options(args) + + +@pytest.mark.parametrize("bad_ttl", [0, 86401]) +def test_todo_claim_rejects_out_of_range_ttl_seconds(bad_ttl): + args = build_parser().parse_args([ + "todo", "claim", "--goal-id", "example-goal", "--todo-id", "todo_example", + "--claimed-by", "codex-example", "--agent-id", "codex-example", + "--ttl-seconds", str(bad_ttl), + ]) + with pytest.raises(ValueError, match="ttl seconds must be between 1 and 86400"): + validate_todo_claim_options(args) + + +def test_todo_claim_ttl_seconds_requires_managed_or_explicit_lease(): + args = build_parser().parse_args([ + "todo", "claim", "--goal-id", "example-goal", "--todo-id", "todo_example", + "--claimed-by", "codex-example", "--ttl-seconds", "7200", + ]) + with pytest.raises(ValueError, match="--ttl-seconds requires managed execution"): + validate_todo_claim_options(args) + + @pytest.mark.parametrize( ("extra_args", "expected"), [