Skip to content
Open
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
6 changes: 4 additions & 2 deletions docs/reference/goal-acceptance-observations.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 重试。写入结果不确定时继续遵循原有回执与恢复规则。
成功操作和未标记错误保持既有行为。
Expand Down
19 changes: 16 additions & 3 deletions loopx/cli_commands/todo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
)
Expand Down Expand Up @@ -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",
Expand Down
19 changes: 16 additions & 3 deletions loopx/cli_commands/todo_argument_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -437,14 +438,24 @@ 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)
)
if args.task_lease_expected_version is not None and not args.task_lease_idempotency_key:
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:
Expand Down Expand Up @@ -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"
Expand Down
9 changes: 9 additions & 0 deletions loopx/cli_commands/todo_registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -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=(
Expand Down
4 changes: 2 additions & 2 deletions loopx/control_plane/coordination/claim_execution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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,
Expand Down
17 changes: 16 additions & 1 deletion loopx/control_plane/coordination/local_authority.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand Down Expand Up @@ -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}
Expand All @@ -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
Expand Down
7 changes: 7 additions & 0 deletions loopx/control_plane/coordination/local_authority_runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down Expand Up @@ -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),
Expand Down
7 changes: 7 additions & 0 deletions loopx/control_plane/coordination/todo_claim.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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)) {
Expand All @@ -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) {
Expand Down Expand Up @@ -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);
Expand Down
5 changes: 4 additions & 1 deletion loopx/control_plane/goals/outcome_requirements.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
12 changes: 11 additions & 1 deletion loopx/control_plane/todos/markdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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")):
Expand Down
11 changes: 11 additions & 0 deletions loopx/control_plane/todos/mutation_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
)
Expand Down
5 changes: 4 additions & 1 deletion tests/control_plane/test_goal_outcome_diagnostics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Loading
Loading