From 1fd35e98d617ce71b2311bf44cc83f98cbc5c3fd Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:05:19 +0800 Subject: [PATCH 1/2] Bind current managed claims to their worktree Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- docs/reference/canonical-lease-renew.md | 20 ++++-- .../coordination/claim_execution.ts | 20 +++++- .../coordination/lease_acquisition_proof.ts | 4 +- .../coordination/local_authority_runtime.ts | 2 +- .../control_plane/coordination/todo_claim.ts | 12 +++- .../coordination/todo_terminal_lifecycle.ts | 6 +- .../control_plane/coordination/todo_update.ts | 6 +- .../quota/execution_preparation.py | 7 +- loopx/control_plane/quota/should_run.py | 1 + .../control_plane/quota/should_run_packet.py | 2 + loopx/control_plane/todos/read_transaction.ts | 11 ++- .../work_items/execution_preparation.ts | 9 ++- .../work_items/task_lease_workspace.ts | 44 +++++++++--- .../test_quota_execution_preparation.py | 67 +++++++++++++++++++ .../managed_claim_execution_conformance.ts | 41 +++++++++--- 15 files changed, 210 insertions(+), 42 deletions(-) diff --git a/docs/reference/canonical-lease-renew.md b/docs/reference/canonical-lease-renew.md index f0cd49f27c..b39db1b213 100644 --- a/docs/reference/canonical-lease-renew.md +++ b/docs/reference/canonical-lease-renew.md @@ -120,10 +120,17 @@ opaque digests and the existing public repository identity enter the private authority record. 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. @@ -166,6 +173,11 @@ 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。 diff --git a/loopx/control_plane/coordination/claim_execution.ts b/loopx/control_plane/coordination/claim_execution.ts index 04c2e2875e..340de71f71 100644 --- a/loopx/control_plane/coordination/claim_execution.ts +++ b/loopx/control_plane/coordination/claim_execution.ts @@ -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"; @@ -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; +export type ClaimWorkspaceObserver = (writeScopes?: readonly string[]) => Promise; + +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 { @@ -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"); @@ -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)}; } @@ -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}; } diff --git a/loopx/control_plane/coordination/lease_acquisition_proof.ts b/loopx/control_plane/coordination/lease_acquisition_proof.ts index 280888f173..d2fc21c3c1 100644 --- a/loopx/control_plane/coordination/lease_acquisition_proof.ts +++ b/loopx/control_plane/coordination/lease_acquisition_proof.ts @@ -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"; @@ -59,7 +59,7 @@ export async function currentLeaseAcquisitionProof(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, diff --git a/loopx/control_plane/coordination/local_authority_runtime.ts b/loopx/control_plane/coordination/local_authority_runtime.ts index defde2dcb7..4a563c5e1f 100644 --- a/loopx/control_plane/coordination/local_authority_runtime.ts +++ b/loopx/control_plane/coordination/local_authority_runtime.ts @@ -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 diff --git a/loopx/control_plane/coordination/todo_claim.ts b/loopx/control_plane/coordination/todo_claim.ts index 6f5dc5e383..60b96bda8b 100644 --- a/loopx/control_plane/coordination/todo_claim.ts +++ b/loopx/control_plane/coordination/todo_claim.ts @@ -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"; @@ -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}); @@ -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", diff --git a/loopx/control_plane/coordination/todo_terminal_lifecycle.ts b/loopx/control_plane/coordination/todo_terminal_lifecycle.ts index 155078d400..bb9e82bc9f 100644 --- a/loopx/control_plane/coordination/todo_terminal_lifecycle.ts +++ b/loopx/control_plane/coordination/todo_terminal_lifecycle.ts @@ -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"; @@ -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; diff --git a/loopx/control_plane/coordination/todo_update.ts b/loopx/control_plane/coordination/todo_update.ts index d7335372a2..c1cc70b37c 100644 --- a/loopx/control_plane/coordination/todo_update.ts +++ b/loopx/control_plane/coordination/todo_update.ts @@ -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"; @@ -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); diff --git a/loopx/control_plane/quota/execution_preparation.py b/loopx/control_plane/quota/execution_preparation.py index 9382711dc6..75bc4ef8e3 100644 --- a/loopx/control_plane/quota/execution_preparation.py +++ b/loopx/control_plane/quota/execution_preparation.py @@ -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. @@ -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, ) @@ -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")}, }) @@ -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, @@ -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 diff --git a/loopx/control_plane/quota/should_run.py b/loopx/control_plane/quota/should_run.py index 02694ed368..8945872f68 100644 --- a/loopx/control_plane/quota/should_run.py +++ b/loopx/control_plane/quota/should_run.py @@ -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, diff --git a/loopx/control_plane/quota/should_run_packet.py b/loopx/control_plane/quota/should_run_packet.py index b5f7c0e8df..254f53f834 100644 --- a/loopx/control_plane/quota/should_run_packet.py +++ b/loopx/control_plane/quota/should_run_packet.py @@ -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 @@ -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) diff --git a/loopx/control_plane/todos/read_transaction.ts b/loopx/control_plane/todos/read_transaction.ts index bcd04563f7..ae0925d541 100644 --- a/loopx/control_plane/todos/read_transaction.ts +++ b/loopx/control_plane/todos/read_transaction.ts @@ -15,6 +15,7 @@ import {sealProjectionEnvelope, PROJECTION_ENVELOPE_SEAL_REQUEST} from "../proje import {canonicalAuthoritySha256, canonicalAuthorityJson} from "../coordination/authority_store_codec.ts"; import {decodeTodoReadSource} from "./read_codec.ts"; import {projectTodoQuotaPlanning} from "./quota_selection.ts"; +import {matchesObservedLeaseWorkspace, observeLeaseWorktree} from "../work_items/task_lease_workspace.ts"; import type {LocalAuthorityProviderDependencies} from "../coordination/local_authority_provider.ts"; const includesArchivedRows = (query: JsonObject): boolean => @@ -238,9 +239,13 @@ export async function readExecutionPreparationSource(input: JsonObject, dependen if (canonical.status !== "loaded") return unavailable; const todo = originalRecords(canonical.todos).find(row => row.todo_id === todoId); if (!todo) return unavailable; - const leases = originalRecords(canonical.leases).filter(row => row.todo_id === todoId) - .map(({todo_id, schema_version, status, owner, expires_at, idempotency_key, version}) => - ({todo_id, schema_version, status, owner, expires_at, idempotency_key, version})); + const workspacePath = source.workspace_path; + const observe = typeof workspacePath === "string" ? () => observeLeaseWorktree(workspacePath) : undefined; + const leases = await Promise.all(originalRecords(canonical.leases).filter(row => row.todo_id === todoId) + .map(async ({todo_id, schema_version, status, owner, expires_at, idempotency_key, version, write_workspace}) => + ({todo_id, schema_version, status, owner, expires_at, idempotency_key, version, + ...(status !== "active" || write_workspace == null ? {} : + {workspace_matches: await matchesObservedLeaseWorkspace(write_workspace, observe)})}))); return {schema_version: TODO_READ_RESULT, execution_preparation_source: { goal_id: goalId, todo_id: todoId, handoff_mode: canonical.handoff_mode, source_authority: canonical.source_authority, provider_revision: canonical.provider_revision, diff --git a/loopx/control_plane/work_items/execution_preparation.ts b/loopx/control_plane/work_items/execution_preparation.ts index 30c1f4ce17..096b735748 100644 --- a/loopx/control_plane/work_items/execution_preparation.ts +++ b/loopx/control_plane/work_items/execution_preparation.ts @@ -2,6 +2,7 @@ import {HANDOFF_MODES} from "../coordination/handoff_mode_vocabulary.ts"; import {HANDOFF_MODE_RETIRED_REASON, retiredHandoffModeRejection} from "../coordination/handoff_mode_policy.ts"; import type {JsonObject} from "../effect_program.ts"; import {EffectRuntimeRequestError} from "../effect_runtime_errors.ts"; +import {LEASE_WORKSPACE_DIVERGENCE} from "./task_lease_workspace.ts"; import { optionalNonEmptyString, requireBoolean, @@ -37,7 +38,9 @@ function leaseFact(value: unknown, label: string): JsonObject { proof = {idempotency_key: key, expected_version: version}; } return {status, active, ...(owner === null ? {} : {owner}), - ...(proof === undefined ? {} : {lease_proof: proof})}; + ...(proof === undefined ? {} : {lease_proof: proof}), + ...(lease.workspace_matches === undefined ? {} : + {workspace_matches: requireBoolean(lease.workspace_matches, `${label}.workspace_matches`)})}; } function claimAction(goalId: string, todoId: string, agentId: string): JsonObject { @@ -124,6 +127,10 @@ export function projectExecutionPreparation(value: unknown): JsonObject { reason_code: "active_lease_owned_by_other_agent", ...(owner ? {owner} : {}), reason: "The selected Todo has an active lease owned by another agent; do not take over its execution."}; } + if (active[0].workspace_matches === false) { + return {...base, state: "blocked_by_conflict", delivery_allowed: false, + reason_code: LEASE_WORKSPACE_DIVERGENCE.code, reason: LEASE_WORKSPACE_DIVERGENCE.reason}; + } return {...base, state: "ready", delivery_allowed: true, reason_code: "matching_active_task_lease", // Capture the admitted generation once. Recovery must not borrow a diff --git a/loopx/control_plane/work_items/task_lease_workspace.ts b/loopx/control_plane/work_items/task_lease_workspace.ts index cb4b605ca0..34670767f1 100644 --- a/loopx/control_plane/work_items/task_lease_workspace.ts +++ b/loopx/control_plane/work_items/task_lease_workspace.ts @@ -18,6 +18,11 @@ export interface LeaseWorkspace extends JsonObject { worktree: string; repository: string; } +export const LEASE_WORKSPACE_DIVERGENCE = { + code: "lease_workspace_divergence", + reason: "Cannot verify this caller is in the active task lease's worktree. Continue in its original worktree or release the lease before making a new claim.", +}; + const run = promisify(execFile); const digest = (value: string) => createHash("sha256").update(value).digest("hex"); @@ -77,6 +82,15 @@ export function sameLeaseWorkspace(left: unknown, right: unknown): boolean { a.common_directory === b.common_directory && a.worktree === b.worktree && a.repository === b.repository; } +/** Absent bindings retain ordinary exclusion. Bound grants require an observed match. */ +export async function matchesObservedLeaseWorkspace(retained: unknown, + observe: (() => Promise) | undefined): Promise { + if (retained == null) return true; + if (observe === undefined) return false; + try { return sameLeaseWorkspace(retained, await observe()); } + catch { return false; } +} + /** A known physical checkout collision still rejects cooperative code editing. */ export function sameLeaseCheckout(left: unknown, right: unknown): boolean { const a = leaseWorkspace(left), b = leaseWorkspace(right); @@ -99,17 +113,7 @@ async function machineIdentity(): Promise { return undefined; } -export async function observeLeaseWorktree(path: string, overlaps: (path: string) => boolean): Promise { - if (!isAbsolute(path)) throw new LeaseWorktreeObservationError("worktree observation requires an absolute caller path"); - const cwd = await realpath(path); - const git = async (...args: string[]) => (await run("git", ["-C", cwd, ...args], - {timeout: 5000, maxBuffer: 4 * 1024 * 1024, env: {...process.env, GIT_OPTIONAL_LOCKS: "0"}})).stdout.trim(); - const root = await realpath(await git("rev-parse", "--show-toplevel")); - const directory = await realpath(await git("rev-parse", "--absolute-git-dir")); - const common = await realpath(resolve(cwd, await git("rev-parse", "--git-common-dir"))); - if (root !== cwd || directory === common || !(await stat(resolve(root, ".git"))).isFile()) { - throw new LeaseWorktreeObservationError("--write-worktree requires the root of an independent Git worktree"); - } +async function requireLocalWorktreeScopes(root: string, overlaps: (path: string) => boolean): Promise { // Code-edit leases must not describe shared Git administration or paths // redirected out of the checkout. Direct in-scope file links remain local. if (overlaps(".git")) throw new LeaseWorktreeObservationError("worktree scopes cannot include Git administration"); @@ -139,6 +143,24 @@ export async function observeLeaseWorktree(path: string, overlaps: (path: string } } } +} + +/** With scopes, validate a new grant at its root. Identity-only reads also accept a subdirectory. */ +export async function observeLeaseWorktree(path: string, overlaps?: (path: string) => boolean): Promise { + if (!isAbsolute(path)) throw new LeaseWorktreeObservationError("worktree observation requires an absolute caller path"); + const cwd = await realpath(path); + const git = async (...args: string[]) => (await run("git", ["-C", cwd, ...args], + {timeout: 5000, maxBuffer: 4 * 1024 * 1024, env: {...process.env, GIT_OPTIONAL_LOCKS: "0"}})).stdout.trim(); + const root = await realpath(await git("rev-parse", "--show-toplevel")); + const directory = await realpath(await git("rev-parse", "--absolute-git-dir")); + const common = await realpath(resolve(cwd, await git("rev-parse", "--git-common-dir"))); + const fromRoot = relative(root, cwd); + const outsideRoot = fromRoot === ".." || fromRoot.startsWith(`..${sep}`) || isAbsolute(fromRoot); + if (outsideRoot || overlaps !== undefined && fromRoot !== "" || directory === common || + !(await stat(resolve(root, ".git"))).isFile()) { + throw new LeaseWorktreeObservationError("--write-worktree requires the root of an independent Git worktree"); + } + if (overlaps !== undefined) await requireLocalWorktreeScopes(root, overlaps); const remote = await git("remote", "get-url", "origin"); const scp = /^[^@/:]+@([^/:]+):(.+)$/u.exec(remote); const url = scp ? new URL(`ssh://${scp[1]}/${scp[2]}`) : new URL(remote); diff --git a/tests/control_plane/test_quota_execution_preparation.py b/tests/control_plane/test_quota_execution_preparation.py index faae79e1e2..f7ac4e6d95 100644 --- a/tests/control_plane/test_quota_execution_preparation.py +++ b/tests/control_plane/test_quota_execution_preparation.py @@ -126,6 +126,7 @@ def _run( context_delivery: str = "off", goal_suffix: str = "", write_scopes: list[str] | None = None, + workspace: Path | None = None, ): isolate_sqlite_runtime(tmp_path, monkeypatch) runtime = tmp_path / "runtime" @@ -167,6 +168,7 @@ def _run( "--context-delivery", context_delivery, *guard_args, registry_path=registry, runtime_root=runtime, + cwd=workspace, ) assert code == 0, json.dumps(packet, ensure_ascii=False, indent=2) return packet @@ -224,6 +226,71 @@ def test_matching_active_lease_preserves_delivery(tmp_path, monkeypatch, provide assert packet["interaction_contract"]["agent_channel"]["delivery_allowed"] is True +@pytest.mark.skipif(sys.platform not in {"darwin", "linux"}, reason="independent worktree fixture requires POSIX Git") +@pytest.mark.parametrize("provider", ["file", "sqlite"]) +def test_active_managed_claim_stays_with_its_original_worktree(tmp_path, monkeypatch, provider): + project = tmp_path / "repo" + project.mkdir() + + def git(*args): + subprocess.run(["git", "-C", str(project), *args], check=True, capture_output=True) + + git("init") + git("-c", "user.name=Fixture", "-c", "user.email=fixture@example.com", "commit", + "--allow-empty", "-m", "fixture") + git("remote", "add", "origin", "https://github.com/example/project.git") + original, sibling = tmp_path / "original", tmp_path / "sibling" + git("worktree", "add", "-b", "original", str(original)) + git("worktree", "add", "-b", "sibling", str(sibling)) + child = original / "nested" + child.mkdir() + todo = {**_todo(), "task_domain": "code", "task_repository": "git:github.com/example/project", + "required_write_scopes": ["src/**"]} + prepared = _run(tmp_path, monkeypatch, provider, [], todos=[todo], write_scopes=["src/**"], workspace=child) + assert prepared.get("execution_preparation", {}).get("state") == "claim_required", prepared.get("reason") + + def cli(workspace, *args): + return run_json_cli_result(*args, registry_path=tmp_path / "registry.json", + runtime_root=tmp_path / "runtime", cwd=workspace) + + claim = ["todo", "claim", "--goal-id", GOAL, "--todo-id", TODO, + "--agent-id", AGENT, "--claimed-by", AGENT, "--claim-operation-id"] + code, committed = cli(child, *claim, "original-claim") + assert code == 0 and committed["execution_managed"], committed + runtime = tmp_path / "runtime" + before = read_canonical_todos_if_promoted(runtime_root=runtime, goal_id=GOAL, include_leases=True) + assert before["leases"][0]["write_workspace"]["repository"] == todo["task_repository"] + + guard = ["quota", "should-run", "--goal-id", GOAL, "--agent-id", AGENT] + code, ready = cli(child, *guard) + assert code == 0 and ready["execution_preparation"]["state"] == "ready", ready + gate_code, blocked = cli(sibling, *guard) + new_code, new_claim = cli(sibling, *claim, "different-worktree") + replay_code, replay = cli(sibling, *claim, "original-claim") + assert (gate_code, blocked["normal_delivery_allowed"], new_code, replay_code) == (0, False, 1, 1) + assert blocked["execution_preparation"]["reason_code"] == "lease_workspace_divergence" + assert not blocked["interaction_contract"]["agent_channel"]["delivery_allowed"] + assert new_claim["error_code"] == replay["error_code"] == "lease_workspace_divergence" + code, unavailable = cli(tmp_path, *claim, "original-claim") + assert code == 1 and unavailable["error_code"] == "lease_workspace_divergence" + update = ["todo", "update", "--goal-id", GOAL, "--todo-id", TODO, "--agent-id", AGENT, + "--note", "Validated work", "--update-operation-id", "save-progress", + "--claim-operation-id", "original-claim"] + code, rejected = cli(sibling, *update) + assert code == 1 and rejected["error_code"] == "lease_workspace_divergence", rejected + assert read_canonical_todos_if_promoted(runtime_root=runtime, goal_id=GOAL, include_leases=True) == before + code, historical = cli(sibling, "todo", "receipt", "--goal-id", GOAL, "--operation-id", "original-claim") + assert code == 0 and historical["status"] == "found" + assert historical["receipts"][0]["result"]["lease"] == before["leases"][0] + alias = tmp_path / "original-alias" + alias.symlink_to(original, target_is_directory=True) + code, retry = cli(alias, *claim, "original-claim") + assert code == 0 and retry["status"] == "replayed" + assert read_canonical_todos_if_promoted(runtime_root=runtime, goal_id=GOAL, include_leases=True) == before + code, saved = cli(child, *update) + assert code == 0 and saved["status"] == "applied", saved + + @pytest.mark.parametrize("provider", ["file", "sqlite"]) def test_execution_preparation_transports_only_the_selected_provider_facts( tmp_path, monkeypatch, provider, diff --git a/tests/control_plane_ts/managed_claim_execution_conformance.ts b/tests/control_plane_ts/managed_claim_execution_conformance.ts index a73afda9d9..96d15b68ce 100644 --- a/tests/control_plane_ts/managed_claim_execution_conformance.ts +++ b/tests/control_plane_ts/managed_claim_execution_conformance.ts @@ -46,8 +46,8 @@ export function registerManagedClaimExecutionConformance(provider: string, facto clear_claim: false, validation_declaration: null, validation_receipt: null, completion_policy_request: null, dry_run: false, now: request.now}; } - test(`${provider} managed execution: worktree observation uses canonical code scopes only for new execution`, async t => { - const {store, request} = await setup(t); + test(`${provider} managed execution: current claims require the original checkout`, async t => { + const {store, request, progress} = await setup(t); const before = await loaded(store); const todo = (before.head.todos as JsonObject[])[0]!; const repository = "git:github.com/example/project"; @@ -55,20 +55,39 @@ export function registerManagedClaimExecutionConformance(provider: string, facto operation_id: "declare-code", expected_provider_revision: before.provider_revision, projection: before.head, mutations: [{kind: "todo_upsert", todo: {...todo, task_domain: "code", task_repository: repository}}]}))).status, "applied"); const workspace = {host: "1".repeat(64), common_directory: "2".repeat(64), worktree: "3".repeat(64), repository}; - const observed: string[][] = []; - const accepted = await claim(store, request, undefined, async scopes => { - observed.push([...scopes]); return workspace; - }); + const observed: (readonly string[] | undefined)[] = []; + const observe = async (scopes?: readonly string[]) => { + observed.push(scopes); + return workspace; + }; + const accepted = await claim(store, request, undefined, observe); assert.equal(accepted.status, "applied", JSON.stringify(accepted)); assert.deepEqual(observed, [["src/**"]]); assert.deepEqual((accepted.lease as JsonObject).write_workspace, workspace); const current = await loaded(store); - const unexpected = async () => {throw new Error("Recovery must retain the accepted execution, not acquire another workspace");}; - assert.equal((await claim(store, request, undefined, unexpected)).status, "replayed"); + const other = async () => ({...workspace, worktree: "4".repeat(64)}); + const next = {...request, operation_id: "continue-current-execution", + now: new Date(request.now.valueOf() + 31 * 60_000)}; + const blockedReplay = await claim(store, request, undefined, other); + assert.equal(blockedReplay.reason_code, "lease_workspace_divergence"); + assert.ok(blockedReplay.original_receipt); + assert.equal((await claim(store, request)).reason_code, "lease_workspace_divergence"); + assert.equal((await claim(store, next, undefined, other)).reason_code, "lease_workspace_divergence"); + assert.equal((await update(store, progress, undefined, other)).reason_code, + "lease_workspace_divergence"); + assert.equal((await complete(store, completion(request), undefined, undefined, undefined, other)).reason_code, + "lease_workspace_divergence"); + assert.deepEqual(await loaded(store), current); + assert.equal((await store.readReceipt(next.operation_id)).status, "missing"); + assert.equal((await claim(store, request, undefined, observe)).status, "replayed"); assert.deepEqual(await loaded(store), current); - const continuation = await claim(store, {...request, operation_id: "continue-current-execution"}, undefined, unexpected); - assert.equal(continuation.status, "no_change"); - assert.deepEqual((continuation.lease as JsonObject).write_workspace, workspace); + const renewed = await claim(store, next, undefined, observe); + assert.equal(renewed.status, "applied"); + assert.equal((renewed.lease as JsonObject).version, Number((accepted.lease as JsonObject).version) + 1); + assert.deepEqual((renewed.lease as JsonObject).write_workspace, workspace); + assert.equal((await update(store, progress, undefined, observe)).status, "applied"); + assert.equal((await complete(store, completion(request), undefined, undefined, undefined, observe)).status, "applied"); + assert.deepEqual(observed, [["src/**"], undefined, undefined, undefined, undefined]); }); test(`${provider} managed execution: a failed worktree observation cannot grant or assign work`, async t => { const {store, request} = await setup(t); From 4a636c57005c8edd655b0b04a5c144ff401670ba Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:49:00 +0800 Subject: [PATCH 2/2] Resolve worktree facts independently of the parent Git command Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- docs/reference/canonical-lease-renew.md | 7 +++++-- loopx/control_plane/agents/workspace_guard.py | 6 +++++- .../work_items/task_lease_workspace.ts | 10 ++++++++- loopx/doctor_git.py | 12 +++-------- loopx/repository_identity.py | 13 ++++++++++++ .../test_quota_execution_preparation.py | 15 ++++++++++++- .../test_workspace_git_fact_reads.py | 17 +++++++++++++++ .../task_lease_workspace.test.ts | 21 +++++++++++++++++++ 8 files changed, 87 insertions(+), 14 deletions(-) diff --git a/docs/reference/canonical-lease-renew.md b/docs/reference/canonical-lease-renew.md index b39db1b213..14c36731c9 100644 --- a/docs/reference/canonical-lease-renew.md +++ b/docs/reference/canonical-lease-renew.md @@ -117,7 +117,9 @@ 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. For an active worktree-bound managed claim, the @@ -179,7 +181,8 @@ checkout 或无法验证时返回 `lease_workspace_divergence`。有权限读取 调用者可以在其他目录用 `todo receipt` 查询历史认领。换工作区时,按读回版本释放后, 在新 checkout 用新 operation ID 认领。 如需恢复普通独占,按读回版本释放自己的 lease,再用新的执行 key、不带 -`--write-worktree` 重新取得;无需修改其他角色的 lease。 +`--write-worktree` 重新取得;无需修改其他角色的 lease。工作区探测读取调用者 +指定目录的实际 Git 信息,父 Git 命令(包括 hook)的仓库路径和临时配置不会改变探测目标。 ## Operate the current lease diff --git a/loopx/control_plane/agents/workspace_guard.py b/loopx/control_plane/agents/workspace_guard.py index 52a88eb38c..9278edaa83 100644 --- a/loopx/control_plane/agents/workspace_guard.py +++ b/loopx/control_plane/agents/workspace_guard.py @@ -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 ( @@ -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 @@ -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: @@ -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 diff --git a/loopx/control_plane/work_items/task_lease_workspace.ts b/loopx/control_plane/work_items/task_lease_workspace.ts index 34670767f1..c8eb22a85b 100644 --- a/loopx/control_plane/work_items/task_lease_workspace.ts +++ b/loopx/control_plane/work_items/task_lease_workspace.ts @@ -24,6 +24,11 @@ export const LEASE_WORKSPACE_DIVERGENCE = { }; const run = promisify(execFile); +// Git hooks can carry path and temporary config overrides for their parent checkout. +const WORKSPACE_GIT_OVERRIDES = new Set([ + "GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", + "GIT_IMPLICIT_WORK_TREE", "GIT_CONFIG", "GIT_CONFIG_COUNT", "GIT_CONFIG_PARAMETERS", +]); const digest = (value: string) => createHash("sha256").update(value).digest("hex"); /** Only these locally authored, path-free diagnostics may cross the CLI boundary. */ @@ -149,8 +154,11 @@ async function requireLocalWorktreeScopes(root: string, overlaps: (path: string) export async function observeLeaseWorktree(path: string, overlaps?: (path: string) => boolean): Promise { if (!isAbsolute(path)) throw new LeaseWorktreeObservationError("worktree observation requires an absolute caller path"); const cwd = await realpath(path); + const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => + !WORKSPACE_GIT_OVERRIDES.has(name.toUpperCase()))); + env.GIT_OPTIONAL_LOCKS = "0"; const git = async (...args: string[]) => (await run("git", ["-C", cwd, ...args], - {timeout: 5000, maxBuffer: 4 * 1024 * 1024, env: {...process.env, GIT_OPTIONAL_LOCKS: "0"}})).stdout.trim(); + {timeout: 5000, maxBuffer: 4 * 1024 * 1024, env})).stdout.trim(); const root = await realpath(await git("rev-parse", "--show-toplevel")); const directory = await realpath(await git("rev-parse", "--absolute-git-dir")); const common = await realpath(resolve(cwd, await git("rev-parse", "--git-common-dir"))); diff --git a/loopx/doctor_git.py b/loopx/doctor_git.py index d5f201a53f..6ab13819f4 100644 --- a/loopx/doctor_git.py +++ b/loopx/doctor_git.py @@ -12,6 +12,8 @@ from typing import Any from urllib.parse import urlsplit +from .repository_identity import workspace_git_environment + # Keep the historical exports and caller patch points, but select the OS # transport only when used. Decisions and deadlines remain with the caller. _PROCESS_RUNTIME_EXPORTS = ("terminate_process_tree",) @@ -73,14 +75,6 @@ class GitRevisionRelation(str, Enum): UNKNOWN = "unknown" -def _source_git_environment() -> dict[str, str]: - env = dict(os.environ) - # A caller (for example a Git hook) may target an unrelated checkout. - for key in ("GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE"): - env.pop(key, None) - return env - - def _retire_owned_probe(process: subprocess.Popen[str]) -> None: """Stop the query's own process group, then drop its pipes unread. @@ -130,7 +124,7 @@ def _run_git( text=True, encoding="utf-8", errors="replace", - env=_source_git_environment(), + env=workspace_git_environment(), start_new_session=os.name == "posix", ) except OSError: diff --git a/loopx/repository_identity.py b/loopx/repository_identity.py index 050a0c0a54..a38e26be73 100644 --- a/loopx/repository_identity.py +++ b/loopx/repository_identity.py @@ -1,5 +1,6 @@ from __future__ import annotations +import os import re import subprocess from pathlib import Path @@ -52,6 +53,17 @@ def normalize_repository_identity(remote_url_or_identity: str) -> str: return f"git:{host}/{path}" +def workspace_git_environment() -> dict[str, str]: + """Keep a parent Git command's checkout and config out of path-based probes.""" + env = dict(os.environ) + for name in ( + "GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR", "GIT_INDEX_FILE", + "GIT_IMPLICIT_WORK_TREE", "GIT_CONFIG", "GIT_CONFIG_COUNT", "GIT_CONFIG_PARAMETERS", + ): + env.pop(name, None) + return env + + def _origin_remote(project: Path, git_bin: str) -> str: try: completed = subprocess.run( @@ -60,6 +72,7 @@ def _origin_remote(project: Path, git_bin: str) -> str: check=False, text=True, encoding="utf-8", errors="replace", timeout=10, + env=workspace_git_environment(), ) except (OSError, subprocess.TimeoutExpired) as exc: raise ValueError("project origin remote could not be read") from exc diff --git a/tests/control_plane/test_quota_execution_preparation.py b/tests/control_plane/test_quota_execution_preparation.py index f7ac4e6d95..f41a9b8fa5 100644 --- a/tests/control_plane/test_quota_execution_preparation.py +++ b/tests/control_plane/test_quota_execution_preparation.py @@ -228,7 +228,10 @@ def test_matching_active_lease_preserves_delivery(tmp_path, monkeypatch, provide @pytest.mark.skipif(sys.platform not in {"darwin", "linux"}, reason="independent worktree fixture requires POSIX Git") @pytest.mark.parametrize("provider", ["file", "sqlite"]) -def test_active_managed_claim_stays_with_its_original_worktree(tmp_path, monkeypatch, provider): +@pytest.mark.parametrize("inherit_git_context", [False, True], ids=["clean_git", "inherited_git"]) +def test_active_managed_claim_stays_with_its_original_worktree( + tmp_path, monkeypatch, provider, inherit_git_context, +): project = tmp_path / "repo" project.mkdir() @@ -244,6 +247,16 @@ def git(*args): git("worktree", "add", "-b", "sibling", str(sibling)) child = original / "nested" child.mkdir() + if inherit_git_context: + # A Git hook can launch LoopX in a different checkout while retaining + # the parent command's repository selection. + git_directory = subprocess.check_output( + ["git", "-C", str(sibling), "rev-parse", "--absolute-git-dir"], text=True, + ).strip() + monkeypatch.setenv("GIT_DIR", git_directory) + monkeypatch.setenv("GIT_WORK_TREE", str(sibling)) + monkeypatch.setenv("GIT_COMMON_DIR", str(project / ".git")) + todo = {**_todo(), "task_domain": "code", "task_repository": "git:github.com/example/project", "required_write_scopes": ["src/**"]} prepared = _run(tmp_path, monkeypatch, provider, [], todos=[todo], write_scopes=["src/**"], workspace=child) diff --git a/tests/control_plane/test_workspace_git_fact_reads.py b/tests/control_plane/test_workspace_git_fact_reads.py index 2302fae5f6..e03bd0aec8 100644 --- a/tests/control_plane/test_workspace_git_fact_reads.py +++ b/tests/control_plane/test_workspace_git_fact_reads.py @@ -66,6 +66,23 @@ def test_capture_resolves_nested_root_once_but_reads_all_original_facts(workspac assert owner.capture_delivery_workspace(canonical)["workspace_kind"] == "canonical_checkout" +def test_delivery_snapshot_uses_requested_checkout_inside_git_hook(workspaces, monkeypatch): + canonical, peer, nested = workspaces + git(peer, "commit", "-q", "--allow-empty", "-m", "Peer delivery") + expected = owner.capture_delivery_workspace(nested) + assert expected["workspace_kind"] == "independent_git_worktree" + assert expected["workspace_revision_digest"] != owner.capture_delivery_workspace(canonical)["workspace_revision_digest"] + + monkeypatch.setenv("GIT_DIR", str(canonical / ".git")) + monkeypatch.setenv("GIT_WORK_TREE", str(canonical)) + monkeypatch.setenv("GIT_COMMON_DIR", str(canonical / ".git")) + monkeypatch.setenv("GIT_CONFIG_COUNT", "1") + monkeypatch.setenv("GIT_CONFIG_KEY_0", "remote.origin.url") + monkeypatch.setenv("GIT_CONFIG_VALUE_0", "https://github.com/example/parent.git") + + assert owner.capture_delivery_workspace(nested) == expected + + def test_single_agent_guidance_does_not_impose_multi_peer_workspace_gate(workspaces): canonical, peer, _ = workspaces todo = {"task_repository": "git:github.com/example/workspace", "required_write_scopes": ["src/**"]} diff --git a/tests/control_plane_ts/task_lease_workspace.test.ts b/tests/control_plane_ts/task_lease_workspace.test.ts index c08905499a..fb675fcbda 100644 --- a/tests/control_plane_ts/task_lease_workspace.test.ts +++ b/tests/control_plane_ts/task_lease_workspace.test.ts @@ -48,6 +48,27 @@ test("observed Git origins use the Todo repository identity contract", { assert.equal(decision.outcome, "apply"); }); } + await t.test("observe the requested checkout in a parent Git environment", async t => { + git("-C", main, "config", "remote.origin.url", "https://github.com/example/project.git"); + const expected = await observeLeaseWorktree(worktree, overlaps); + const parentEnvironment = { + GIT_DIR: join(main, ".git"), + GIT_WORK_TREE: main, + GIT_COMMON_DIR: join(main, ".git"), + GIT_CONFIG_COUNT: "1", + GIT_CONFIG_KEY_0: "remote.origin.url", + GIT_CONFIG_VALUE_0: "https://github.com/example/parent.git", + }; + const previous = Object.keys(parentEnvironment).map(key => [key, process.env[key]] as const); + t.after(() => { + for (const [key, value] of previous) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + }); + Object.assign(process.env, parentEnvironment); + assert.deepEqual(await observeLeaseWorktree(worktree, overlaps), expected); + }); for (const origin of [ "https://fixture:fixture@github.com/example/project.git", "https://github.com/example/../project.git",