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
27 changes: 21 additions & 6 deletions docs/reference/canonical-lease-renew.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,13 +117,22 @@ redirected paths and a non-worktree root fail closed. Verified machine discovery
currently supports macOS, Linux and Windows; other hosts retain ordinary
leases. No workspace path or machine identifier is stored directly: only
opaque digests and the existing public repository identity enter the private
authority record.
authority record. Worktree probes read the checkout named by the caller from
disk. Parent Git commands, including hooks, cannot redirect these probes
through inherited repository paths or temporary Git configuration.

Renewal preserves this identity. Acquire retries must use the same worktree,
scopes and execution key; an alias resolving to the same worktree is valid.
To change directories or return to ordinary exclusion, release your current
lease with its version and acquire a new execution key without
`--write-worktree`. Other holders need not release their grants to admit an
scopes and execution key. For an active worktree-bound managed claim, the
delivery guard and claim must verify the caller's checkout before returning
current execution authority. Updates and completion using that claim reference
require the same checkout while the grant is active. Subdirectories and aliases
of the original checkout are valid. A different or unverifiable checkout
returns `lease_workspace_divergence`. Use `todo receipt` to read claim history
from any checkout with access to the provider.
To move work to a different checkout, release the current lease with its
version, then claim from the new checkout with a new operation ID. For
standalone acquisition, use a new execution key and pass the new checkout to
`--write-worktree`, or omit that flag to return to ordinary exclusion. Other holders need not release their grants to admit an
isolated code editor. Existing records and historical receipts are retained;
no foreign ownership, shared-runtime permission or merge authority changes.

Expand Down Expand Up @@ -166,8 +175,14 @@ checkout 的冲突、同一 Todo 的执行归属仍拒绝;软链接、Git 管
不再要求双方都先释放、重新绑定 worktree。Todo 实例 lease、CAS、TTL、重放、
续租及生命周期写入仍按原规则保护。共享运行状态、远端分支和合并权限不由
此模式授予;未提供经验证的调用者 worktree 时,普通独占规则保持不变。
已绑定 worktree 的受管认领在租约有效时,执行检查、认领、引用该认领的进度更新和完成
都必须验证调用者位于原 checkout。原 checkout 的子目录和别名有效。换到其他
checkout 或无法验证时返回 `lease_workspace_divergence`。有权限读取 provider 的
调用者可以在其他目录用 `todo receipt` 查询历史认领。换工作区时,按读回版本释放后,
在新 checkout 用新 operation ID 认领。
如需恢复普通独占,按读回版本释放自己的 lease,再用新的执行 key、不带
`--write-worktree` 重新取得;无需修改其他角色的 lease。
`--write-worktree` 重新取得;无需修改其他角色的 lease。工作区探测读取调用者
指定目录的实际 Git 信息,父 Git 命令(包括 hook)的仓库路径和临时配置不会改变探测目标。

## Operate the current lease

Expand Down
6 changes: 5 additions & 1 deletion loopx/control_plane/agents/workspace_guard.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from ...repository_identity import (
normalize_repository_identity,
resolve_project_identity,
workspace_git_environment,
)
from ..todos.contract import normalize_todo_claimed_by, normalize_todo_task_repository
from .delivery_workspace import (
Expand Down Expand Up @@ -47,6 +48,7 @@ def _git_command_output(path: Path, *args: str) -> str | None:
stderr=subprocess.DEVNULL,
text=True, encoding="utf-8", errors="replace",
timeout=1.5,
env=workspace_git_environment(),
)
except (OSError, subprocess.TimeoutExpired):
return None
Expand All @@ -61,9 +63,10 @@ def _git_worktree_root(path: Path) -> Path | None:
if not output:
return None
try:
return Path(output).expanduser().resolve()
root = Path(output).expanduser().resolve()
except OSError:
return None
return root if _is_same_or_child_path(path, root) else None


def _git_common_dir(root: Path) -> Path | None:
Expand Down Expand Up @@ -139,6 +142,7 @@ def _git_origin_is_absent(path: Path) -> bool:
["git", "-C", str(path), "config", "--get", "remote.origin.url"],
check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
timeout=1.5,
env=workspace_git_environment(),
)
except (OSError, subprocess.TimeoutExpired):
return False
Expand Down
20 changes: 17 additions & 3 deletions loopx/control_plane/coordination/claim_execution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import {indexCoordinationProjection} from "./coordination_projection.ts";
import {canonicalTaskLease, canonicalTaskLeaseAcquireFacts} from "./task_lease_state.ts";
import {coordinationTodoWriteScopes} from "./todo_write_scopes.ts";
import {leaseEpoch, leaseVersion, leaseIsActive, normalizeTtl, type LeaseRecord} from "../work_items/task_lease_acquire.ts";
import {sameLeaseWorkspace, type LeaseWorkspace} from "../work_items/task_lease_workspace.ts";
import {LEASE_WORKSPACE_DIVERGENCE, matchesObservedLeaseWorkspace, sameLeaseWorkspace,
type LeaseWorkspace} from "../work_items/task_lease_workspace.ts";
import {leaseWriteRepository} from "../work_items/task_lease_repository.ts";
import {evaluateTaskLeaseAcquireDecision, materializeTaskLeaseAcquire} from "../work_items/task_lease_acquire_decision.ts";
import {decideTaskLeaseLifecycle, materializeTaskLeaseLifecycle} from "../work_items/task_lease_lifecycle_decision.ts";
Expand All @@ -24,7 +25,13 @@ export function claimExecutionReference(id: unknown, key: unknown, version: unkn
type ExecutionInput = {goal_id: string; todo_id: string; actor_agent_id: string | null;
registered_agents: readonly string[]; now: Date};

export type ClaimWorkspaceObserver = (writeScopes: readonly string[]) => Promise<LeaseWorkspace>;
export type ClaimWorkspaceObserver = (writeScopes?: readonly string[]) => Promise<LeaseWorkspace>;

export class ClaimWorkspaceMismatch extends AuthorityStoreProtocolError {
constructor() {
super(LEASE_WORKSPACE_DIVERGENCE.reason);
}
}

/** A diagnostic distinction, never permission to renew or adopt another grant. */
export class ClaimExecutionUnavailable extends AuthorityStoreProtocolError {
Expand All @@ -38,7 +45,8 @@ export class ClaimExecutionUnavailable extends AuthorityStoreProtocolError {
/** Resolve only this accepted execution. No acquisition, adoption of a newer
* generation, or write retry is hidden behind a progress/completion request. */
export async function claimExecutionProof(store: AuthorityStore, head: JsonObject,
input: ExecutionInput, operationId: string, allowReleasedCloseout = false): Promise<{lease_idempotency_key: string; lease_expected_version: number} | null> {
input: ExecutionInput, operationId: string, observeWorkspace?: ClaimWorkspaceObserver,
allowReleasedCloseout = false): Promise<{lease_idempotency_key: string; lease_expected_version: number} | null> {
const receipt = await store.readReceipt(operationId);
if (receipt.status !== "found" || receipt.receipts.length !== 1) {
throw new ClaimExecutionUnavailable("Original task claim unavailable; recover that claim before writing");
Expand Down Expand Up @@ -73,6 +81,9 @@ export async function claimExecutionProof(store: AuthorityStore, head: JsonObjec
throw new ClaimExecutionUnavailable("Original task execution changed; reconcile task ownership before a new claim",
current.status === "active");
}
if (active && !await matchesObservedLeaseWorkspace(current.write_workspace, observeWorkspace)) {
throw new ClaimWorkspaceMismatch();
}
return {lease_idempotency_key: String(current.idempotency_key), lease_expected_version: leaseVersion(current)};
}

Expand Down Expand Up @@ -106,6 +117,9 @@ export async function prepareClaimExecution(head: JsonObject,
const current = facts.current;
if (current && leaseIsActive(current, input.now)) {
if (current.owner !== input.claimed_by) throw new AuthorityStoreProtocolError("Task is occupied by another actor");
if (!await matchesObservedLeaseWorkspace(current.write_workspace, observeWorkspace)) {
throw new ClaimWorkspaceMismatch();
}
const renewed = maintainClaimExecution(head, input, current);
return {lease: renewed ?? current, changed: renewed !== null};
}
Expand Down
4 changes: 2 additions & 2 deletions loopx/control_plane/coordination/lease_acquisition_proof.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {sameLeaseWorkspace} from "../work_items/task_lease_workspace.ts";
import {LEASE_WORKSPACE_DIVERGENCE, sameLeaseWorkspace} from "../work_items/task_lease_workspace.ts";
/** Historical acquisition and current permission are different facts. Both
* standalone acquire and atomic claim/acquire return this current proof. */
import type {JsonObject} from "../effect_program.ts";
Expand Down Expand Up @@ -59,7 +59,7 @@ export async function currentLeaseAcquisitionProof<S extends string>(store: Auth
return failed("idempotency_key_reuse", "acquire receipt belongs to a retired execution; use a new execution key", details);
}
if (!sameLeaseWorkspace(current.write_workspace, original.write_workspace)) return failed(
"lease_workspace_divergence", "current worktree identity differs from its acquisition receipt", details);
LEASE_WORKSPACE_DIVERGENCE.code, "current worktree identity differs from its acquisition receipt", details);
const repositoryRejection = leaseWriteRepository(current.write_repository) !== leaseWriteRepository(original.write_repository)
? "lease_repository_divergence" : leaseRepositoryRejection(facts.todo, current);
if (repositoryRejection !== null) return failed(repositoryRejection,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -536,7 +536,7 @@ function claimWorkspaceObserver(worktree: unknown): ClaimWorkspaceObserver | und
}
return async writeScopes => {
try {
return await observeLeaseWorktree(worktree, path =>
return await observeLeaseWorktree(worktree, writeScopes === undefined ? undefined : path =>
evaluateTaskLeaseWriteScopesOverlap({left: [...writeScopes], right: [path]}).overlap === true);
} catch (error) {
throw new Error(error instanceof LeaseWorktreeObservationError ? error.message
Expand Down
12 changes: 11 additions & 1 deletion loopx/control_plane/coordination/todo_claim.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {prepareClaimExecution, type ClaimWorkspaceObserver} from "./claim_execution.ts";
import {ClaimWorkspaceMismatch, prepareClaimExecution, type ClaimWorkspaceObserver} from "./claim_execution.ts";
import {LEASE_WORKSPACE_DIVERGENCE, matchesObservedLeaseWorkspace} from "../work_items/task_lease_workspace.ts";
import {retiredHandoffModeRejection, HANDOFF_MODE_RETIRED_REASON,
EXECUTION_HANDOFF_MODES, type ExecutionHandoffMode} from "./handoff_mode_policy.ts";
import {AUTHORITY_SOURCE_CHANGED, uncheckedAuthoritySource, type AuthoritySourceCheck} from "./authority_source.ts";
Expand Down Expand Up @@ -456,6 +457,13 @@ async function executeClaimAttempt(
result = await currentLeaseAcquisitionProof(store, {...input, owner: input.claimed_by,
idempotency_key: key, required_handoff_mode: "hard_lease"}, result,
(code, reason, detail = {}) => failure(code, reason, detail, "decision_rejection"));
if (result.execution_managed === true && (result.status === "replayed" || result.status === "recovered")) {
const current = canonicalAuthorityObject(result.lease, "current task lease");
if (!await matchesObservedLeaseWorkspace(current.write_workspace, observeWorkspace)) {
return failure(LEASE_WORKSPACE_DIVERGENCE.code, LEASE_WORKSPACE_DIVERGENCE.reason,
{todo_id: input.todo_id, original_receipt: result.original_receipt}, "decision_rejection");
}
}
} catch (error) {
return failure("invalid_coordination_task_lease", error instanceof Error ? error.message : "invalid canonical task lease",
{original_receipt: result.original_receipt});
Expand Down Expand Up @@ -665,6 +673,8 @@ async function executeClaimAttempt(
);
}
} catch (error) {
if (error instanceof ClaimWorkspaceMismatch) return failure(LEASE_WORKSPACE_DIVERGENCE.code, error.message,
{todo_id: input.todo_id}, "decision_rejection");
return failure(
"invalid_coordination_task_lease",
error instanceof Error ? error.message : "invalid canonical task lease",
Expand Down
6 changes: 4 additions & 2 deletions loopx/control_plane/coordination/todo_terminal_lifecycle.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {claimExecutionReference, claimExecutionProof, type ClaimWorkspaceObserver} from "./claim_execution.ts";
import {ClaimWorkspaceMismatch, claimExecutionReference, claimExecutionProof, type ClaimWorkspaceObserver} from "./claim_execution.ts";
import {LEASE_WORKSPACE_DIVERGENCE} from "../work_items/task_lease_workspace.ts";
import {claimExecutionRecovery} from "./claim_execution_recovery.ts";
import {executeCoordinationTodoClaim} from "./todo_claim.ts";
import {HANDOFF_MODE_RETIRED_REASON} from "./handoff_mode_policy.ts";
Expand Down Expand Up @@ -867,8 +868,9 @@ export async function executeCoordinationTodoTerminalLifecycle(
}
const claimReference = input.claim_operation_id;
if (claimReference !== undefined) {
try { input = {...input, ...await claimExecutionProof(store, head.head, input, claimReference, input.requested_no_followup), claim_operation_id: undefined}; }
try { input = {...input, ...await claimExecutionProof(store, head.head, input, claimReference, observeWorkspace, input.requested_no_followup), claim_operation_id: undefined}; }
catch (error) {
if (error instanceof ClaimWorkspaceMismatch) return terminalFailure(LEASE_WORKSPACE_DIVERGENCE.code, error.message);
const recovery = input.command === "complete" ? await claimExecutionRecovery(store,
{...input, claim_operation_id: claimReference, expected_provider_revision: head.provider_revision},
"complete", error, authoritySourcesCurrent, observeWorkspace) : undefined;
Expand Down
6 changes: 4 additions & 2 deletions loopx/control_plane/coordination/todo_update.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {claimExecutionProof, maintainClaimExecution, type ClaimWorkspaceObserver} from "./claim_execution.ts";
import {ClaimWorkspaceMismatch, claimExecutionProof, maintainClaimExecution, type ClaimWorkspaceObserver} from "./claim_execution.ts";
import {LEASE_WORKSPACE_DIVERGENCE} from "../work_items/task_lease_workspace.ts";
import {claimExecutionRecovery} from "./claim_execution_recovery.ts";
import {canonicalTaskLease} from "./task_lease_state.ts";
import {AUTHORITY_SOURCE_CHANGED, uncheckedAuthoritySource, type AuthoritySourceCheck} from "./authority_source.ts";
Expand Down Expand Up @@ -222,8 +223,9 @@ export async function executeCoordinationTodoUpdate(
if (isFailure(target)) return target;
const claimReference = input.claim_operation_id;
if (claimReference !== undefined) {
try { input = {...input, ...await claimExecutionProof(store, head.head, input, claimReference), claim_operation_id: undefined}; }
try { input = {...input, ...await claimExecutionProof(store, head.head, input, claimReference, observeWorkspace), claim_operation_id: undefined}; }
catch (error) {
if (error instanceof ClaimWorkspaceMismatch) return rejection(LEASE_WORKSPACE_DIVERGENCE.code, error.message);
const recovery = await claimExecutionRecovery(store, {...input, claim_operation_id: claimReference,
caller_expected_provider_revision: input.expected_provider_revision,
expected_provider_revision: head.provider_revision}, "update", error, authoritySourcesCurrent, observeWorkspace);
Expand Down
7 changes: 6 additions & 1 deletion loopx/control_plane/quota/execution_preparation.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ def project_selected_todo_execution_preparation(
goal_id: str,
selected_todo: Mapping[str, Any],
agent_id: str | None,
workspace_path: Path | None = None,
) -> dict[str, Any] | None:
"""Read the selected Todo's canonical lease and project one preparation step.

Expand All @@ -52,7 +53,8 @@ def project_selected_todo_execution_preparation(
"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},
"goal_id": goal_id,
"workspace_path": str((workspace_path or Path.cwd()).absolute())},
"todo_id": todo_id},
timeout=LOCAL_COORDINATION_TODO_LIST_TIMEOUT_SECONDS,
)
Expand Down Expand Up @@ -83,6 +85,7 @@ def project_selected_todo_execution_preparation(
"status": status if status in {"active", "released"} else "unknown",
"active": lease_is_active(dict(lease)),
**({"owner": lease["owner"]} if normalize_todo_claimed_by(lease.get("owner")) else {}),
**({"workspace_matches": lease["workspace_matches"] is True} if "workspace_matches" in lease else {}),
"lease_proof": {"idempotency_key": lease.get("idempotency_key"),
"expected_version": lease.get("version")},
})
Expand Down Expand Up @@ -121,6 +124,7 @@ def apply_selected_todo_execution_preparation(
runtime_root: str | Path | None,
goal_id: str,
agent_id: str | None,
workspace_path: Path | None = None,
obligation: dict[str, Any] | None = None,
recommendation: dict[str, Any] | None = None,
receipt_bound: bool = False,
Expand All @@ -146,6 +150,7 @@ def apply_selected_todo_execution_preparation(
goal_id=goal_id,
selected_todo=selected,
agent_id=agent_id,
workspace_path=workspace_path,
)
# Existing receipt-bound recovery predates this projection and may be
# reconstructed without canonical lease authority in synthetic/legacy
Expand Down
1 change: 1 addition & 0 deletions loopx/control_plane/quota/should_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -688,6 +688,7 @@ def build_quota_should_run(
turn_instance_id=turn_instance_id,
include_agent_todo_detail=include_agent_todo_detail,
runtime_root=runtime_root,
workspace_path=workspace_path,
goal_ref=goal_ref,
scheduler_state_read_observer=_app_scheduler_state_read_observer(
direct_sources, app_scheduler_state_observer,
Expand Down
2 changes: 2 additions & 0 deletions loopx/control_plane/quota/should_run_packet.py
Original file line number Diff line number Diff line change
Expand Up @@ -1691,6 +1691,7 @@ def _build_quota_should_run_payload(
turn_instance_id: str | None = None,
include_agent_todo_detail: bool = False,
runtime_root: str | Path | None = None,
workspace_path: Path | None = None,
goal_ref: Mapping[str, object] | None = None,
scheduler_state_read_observer: (
Callable[[Mapping[str, Any]], None] | None
Expand Down Expand Up @@ -1718,6 +1719,7 @@ def _build_quota_should_run_payload(
runtime_root=_interaction_runtime_root(runtime_root, prepared.status_payload),
goal_id=prepared.safe_goal_id,
agent_id=quota_decision_agent_id(payload) or prepared.requested_agent_id,
workspace_path=workspace_path,
obligation=(
payload["execution_obligation"]
if isinstance(payload.get("execution_obligation"), dict)
Expand Down
Loading
Loading