diff --git a/docs/reference/canonical-lease-renew.md b/docs/reference/canonical-lease-renew.md index f0cd49f27c..052263ff9e 100644 --- a/docs/reference/canonical-lease-renew.md +++ b/docs/reference/canonical-lease-renew.md @@ -93,61 +93,59 @@ loopx --registry registry.json task-lease acquire \ ``` The TypeScript entrypoint verifies the caller's Git root, origin against the -Todo's repository, machine identity and filesystem identity. This selects -cooperative code editing: overlapping relative file scopes return -`integration_overlap_advisories` identifying the other Todo and paths, so their -owners can coordinate and validate the combined changes before merge. The -other grant may describe a different checkout or omit workspace identity; an -unknown legacy grant no longer blocks the verified code editor. The advisory -does not attest the other editor's isolation or rewrite its grant. This is -cooperative code-edit coordination, not a filesystem access-control mechanism. +Todo's repository, machine identity and filesystem identity. Lease acquisition +enforces Todo execution ownership (`todo_lease_conflict`) and same physical +checkout/worktree exclusivity (`workspace_lease_conflict`); per-path +`write_scope_conflict` blocks and `integration_overlap_advisories` are retired. +Independent worktrees on separate checkouts may execute different Todos +concurrently without blocking on declared path globs, while shared checkouts +are serialized. This selects cooperative code-edit coordination, not a +filesystem access-control mechanism. It does not authorize changing shared runtime data, Git administration, remote -branches, or merging. Use ordinary exclusive leases for those operations. +branches, or merging. Accepted origin URLs use the same repository identity rules as Todo declarations: explicit default transport ports (including SSH `:22` and Git `:9418`) do not create another repository, while nondefault ports remain distinct. Origins with passwords or unsafe path segments are rejected before lease acquisition. -Known same-checkout aliases and the same Todo retain existing exclusion, even +Known same-checkout aliases and the same Todo retain execution exclusion, even if retained repository metadata differs for that physical checkout. -Requests without a verified caller workspace retain ordinary exclusive scope -checks, including against unknown legacy grants. Repository mismatch, +Repository mismatch, redirected paths and a non-worktree root fail closed. Verified machine discovery -currently supports macOS, Linux and Windows; other hosts retain ordinary +currently supports macOS, Linux and Windows; other hosts retain Todo-level leases. No workspace path or machine identifier is stored directly: only 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 +To change directories or reset workspace identity, release your current +lease with its version and acquire a new execution key with the updated flags. +Other holders in distinct worktrees 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. -**Behavior change:** worktree mode no longer requires both holders to have -verified sibling-worktree identities. File overlap is an integration advisory -unless the retained identity positively identifies the same physical checkout. -The Todo lease still fences the execution instance, exact retries, renewal and -lifecycle writes; code-file exclusivity is not that instance fence. +**Behavior change:** lease conflict checks enforce Todo ownership and same +physical checkout exclusivity (`workspace_lease_conflict`). Per-path +`write_scopes` conflict blocking and `integration_overlap_advisories` have been +retired. The Todo lease still fences the execution instance, exact retries, +renewal and lifecycle writes; path-glob overlap is not a cross-worktree blocker. ## 仓库相对路径的冲突边界 新的 canonical 租约从权威 Todo 的 `task_repository` 冻结 -`lease.write_repository`,不接受调用者覆盖,也不从 CLI 当前目录猜测。同一 Goal -内,普通独占模式只有双方都是已知且不同的仓库,才隔离同名相对路径;大小写别名仍互斥。 -完整 head 扫描、owner 资格、TTL、generation、CAS 与回执身份保持原规则,空 scope -仍不产生写冲突。旧记录缺少该字段或为 null 时保持未知,普通独占模式保守互斥,读回和续租不 -回填;合法退役后的新执行才冻结当前仓库。损坏身份拒绝执行,续租、转交和释放 -保留冻结值与原历史回执。当前执行证明、领取重放与 inspect 拒绝已知仓库漂移 -(`lease_repository_divergence`);清理仍凭精确 owner/key/version,不能借 metadata -编辑替换已有执行契约。 - -JSON 与 Markdown 读回同一仓库字段或未知状态。这只是 Goal 内逻辑仓库互斥, -不识别物理目录、软链接别名,也不是跨 Goal 锁;不新增配置、promotion 或自动 -委派。CLI 与 native provider 检查已覆盖该边界,完整前端/Lark 协作旅程仍需单独交付。 +`lease.write_repository`,不接受调用者覆盖,也不从 CLI 当前目录猜测。 +同一 Goal 内,租约互斥以 Todo 归属(`todo_lease_conflict`)与同一物理 +checkout / Git worktree 独占(`workspace_lease_conflict`)为准,不再按静态路径 +glob 重叠阻塞不同 Todo 或跨 worktree 的并发执行。 +完整 head 扫描、owner 资格、TTL、generation、CAS 与回执身份保持原规则。 +损坏仓库身份拒绝执行,续租、转交和释放保留冻结值与原历史回执;当前执行证明、 +领取重放与 `inspect` 拒绝已知仓库漂移(`lease_repository_divergence`); +清理仍凭精确 owner/key/version,不能借 metadata 编辑替换已有执行契约。 + +JSON 与 Markdown 读回同一仓库字段或未知状态。这是物理 checkout 与 Todo 级协调, +不作为 OS 级文件系统沙盒,也不是跨 Goal 锁。CLI 与 native provider 检查已覆盖该边界,完整前端/Lark 协作旅程仍需单独交付。 独立 worktree 的 origin URL 与 Todo 声明使用同一仓库身份规则:显式默认端口 (包括 SSH `:22` 和 Git `:9418`)不产生另一个仓库身份,非默认端口仍须匹配。 @@ -156,18 +154,17 @@ JSON 与 Markdown 读回同一仓库字段或未知状态。这只是 Goal 内 ### 独立 worktree 的协作代码编辑 在独立 Git worktree 根目录使用上方 `--write-worktree "$PWD"`。TS 入口验证 -调用者的仓库、物理目录和主机身份;代码文件的 scope 重叠只返回 -`integration_overlap_advisories`,供集成、评审与合并时协调。对方旧 lease -缺少 worktree 身份也不阻塞,且不会被改写或被推断成已隔离。已确认同一物理 -checkout 的冲突、同一 Todo 的执行归属仍拒绝;软链接、Git 管理目录和仓库不匹配 -仍在入口拒绝。 - -这是 worktree 模式的行为变更:文件范围从跨 checkout 的执行锁改为集成提示, -不再要求双方都先释放、重新绑定 worktree。Todo 实例 lease、CAS、TTL、重放、 -续租及生命周期写入仍按原规则保护。共享运行状态、远端分支和合并权限不由 -此模式授予;未提供经验证的调用者 worktree 时,普通独占规则保持不变。 -如需恢复普通独占,按读回版本释放自己的 lease,再用新的执行 key、不带 -`--write-worktree` 重新取得;无需修改其他角色的 lease。 +调用者的仓库、物理目录和主机身份;已确认同一物理 checkout 的冲突仍返回 +`workspace_lease_conflict` 并拒绝获取,不同 Git worktree 之间的不同 Todo 可并发获取, +不再生成逐路径 `write_scope_conflict` 或 `integration_overlap_advisories`。 +软链接、Git 管理目录和仓库不匹配仍在入口拒绝。 + +这是并发租约模型的行为简化:将写锁收敛回 Todo 归属 + 物理 worktree 独占, +不再要求独立 worktree 为静态 path glob 做跨 checkout 阻塞或生成集成提示列表。 +Todo 实例 lease、CAS、TTL、重放、续租及生命周期写入仍按原规则保护;共享运行状态、 +远端分支和合并权限不由工作区隔离本身授予。 +如需变更目录或切换 worktree,按读回版本释放自己的 lease,再用新的执行 key +重新取得;无需干扰其他 worktree 的持有人。 ## Operate the current lease diff --git a/docs/reference/required-work-context.md b/docs/reference/required-work-context.md index 8f896959e4..c339b687cc 100644 --- a/docs/reference/required-work-context.md +++ b/docs/reference/required-work-context.md @@ -208,14 +208,10 @@ whole Goal/Todo narrative, source availability/revisions and read routes. Detail history and optional authoring recipes remain expandable from the same capture. Current narrative sources and their provenance precede other sources, including large scoped preferences; both retain their complete selected values. -During an unbound Todo choice, including during workspace repair, the initial -read keeps the candidate identities and selection command. It points to long -candidate write scopes in the original capture when those scopes matter to the -choice. The guard for the same Turn supplies the current scopes before delivery. -When a selected Todo needs an ordinary managed claim, the initial read keeps -the claim and continuation instructions. Read long requested scopes at -`/selected_todo/required_write_scopes` when needed for preparation. Use the -same-Turn guard's complete current scopes after the claim and before delivery. +Todo `required_write_scopes` are omitted from default quota summaries, +capability gates, action portfolios, and `selected_todo` projections so initial +decision context stays compact without truncation pointers. Canonical Todo +reads (`todo list`) retain the full declared scopes when explicitly inspected. The preference source's complete `current` view also stays in the initial read: corrections, retirement/expiry and empty replacements retain their provenance, revision and advisory authority. This captured pre-work view does not replace the @@ -339,13 +335,14 @@ large for one page, the linked remainder contains its full details and the suggested alternatives. The selection commands use the original Turn identity. Native ready decisions from `quota should-run` and saved `quota context-project` -can link two reads when Goal or Todo scope details push controls past the serialized +can link two reads when boundary detail pushes controls past the serialized first page budget. When those controls fit, the ordinary reader keeps its cursor. Read `first_read_command` for the decision, stop conditions and required reads. If `remaining_read_command` is present, follow it and its cursor before work, even when the opening reports EOF. The remainder supplies deferred Goal write -scopes, checkpointed approval entries and the selected Todo's requested write -scopes. The opening shows the current approval counts and active scope summary. +scopes, checkpointed `active_write_scope`, and checkpointed approval entries. +The opening keeps only the current approval counts (`active_count` and +`inactive_count`), while Goal wildcard subpaths fold automatically. The remainder can refer to other fully observed, unchanged fields. If the observation is lost, its same-capture fallback restores the full remainder. @@ -380,8 +377,8 @@ presentation changes neither admission nor the explicit off view. 控制信息超出序列化后的首页预算,导航可给出两段读取。控制信息能放进首页时,沿用普通游标。 先用 `first_read_command` 取得决策、停止条件和必读项。如果给出 `remaining_read_command`,即使首段已到 EOF,也要在开工前沿该命令及其游标读完。 -续读提供延后交付的 Goal 写入范围、已记录的审批条目及选中 Todo 的请求写入范围。 -两段绑定同一份捕获。首段保留当前审批数量和生效范围摘要。 +续读提供延后交付的 Goal 写入范围、checkpointed `active_write_scope` 与已记录的 +审批条目。两段绑定同一份捕获;首段仅保留当前审批数量摘要,并自动折叠 Goal 通配符子路径。 续读可引用其他已完整送达且未变化的字段。观察失效时,从同一捕获恢复完整续段。 准入检查要求先切换到独立工作树时,首读保留迁移指引和当前决策控制信息。 @@ -561,17 +558,6 @@ The native hook executes only a preparation bound to a captured Turn. An ordinary claim recommendation remains available to its caller; reading one or reading an original receipt does not trigger an automatic claim. -A successful managed `todo claim --thin` JSON reply can show peer worktree -overlap advice with `write_scope_count` in place of long path lists. It keeps -the other Todo, owner and overlap reason. Run `integration_overlap_detail_command` -to read the complete advice under `receipts[].result.integration_overlap_advisories` -for that claim operation. The command uses `todo receipt --thin --format json` -to return the receipt identity and historical advice without copying the -claimant's lease. The response includes `thin: true`. This read remains -available after a lease changes. Omit `--thin` to read the entire receipt. -Use `task-lease inspect` for a current grant. An ordinary claim reply retains -the full path lists. - For a selected Todo, preparation reads the canonical Todo and leases at one checked provider revision. The internal read returns only that Todo's status, assignment and lease facts. Unrelated Todo bodies stay with the provider diff --git a/examples/control_plane/task-lease-runtime-smoke.py b/examples/control_plane/task-lease-runtime-smoke.py index d15d2aac86..3058613cb6 100644 --- a/examples/control_plane/task-lease-runtime-smoke.py +++ b/examples/control_plane/task-lease-runtime-smoke.py @@ -74,12 +74,14 @@ def write_fixture(root: Path, provider: str) -> tuple[Path, Path]: encoding="utf-8", ) worker = project.parent / "worker" + worker_b = project.parent / "worker-b" for args in [ ("init", "--initial-branch", "main"), ("remote", "add", "origin", "https://example.invalid/loopx/lease-fixture.git"), ("-c", "user.name=LoopX Fixture", "-c", "user.email=fixture@example.invalid", "commit", "--allow-empty", "-m", "fixture"), ("worktree", "add", "-b", "worker", str(worker)), + ("worktree", "add", "-b", "worker-b", str(worker_b)), ]: subprocess.run(["git", "-C", str(project), *args], check=True, capture_output=True, text=True) projection = build_todo_runtime_shadow_projection( @@ -132,7 +134,7 @@ def command( def cli( registry_path: Path, *args: str, check: bool = True ) -> subprocess.CompletedProcess[str]: - if args[0] == "acquire": + if args[0] == "acquire" and "--write-worktree" not in args: args = (*args, "--write-worktree", str(registry_path.parents[2] / "worker")) return command(registry_path, "task-lease", *args, check=check) @@ -241,6 +243,8 @@ def exercise_provider(provider: str) -> None: "120", "--write-scope", "docs/**", + "--write-worktree", + str(registry_path.parents[2] / "worker-b"), ) ) assert same_goal_different_scope["ok"] is True, same_goal_different_scope @@ -264,7 +268,7 @@ def exercise_provider(provider: str) -> None: ) assert conflict.returncode == 1, conflict.stdout conflict_payload = payload(conflict) - assert conflict_payload["error_code"] == "write_scope_conflict", ( + assert conflict_payload["error_code"] == "workspace_lease_conflict", ( conflict_payload ) assert conflict_payload["conflicts"][0]["todo_id"] == TODO_A, conflict_payload diff --git a/loopx/boundary_authority.py b/loopx/boundary_authority.py index eb6b885f09..3333203cca 100644 --- a/loopx/boundary_authority.py +++ b/loopx/boundary_authority.py @@ -1,6 +1,7 @@ from __future__ import annotations from datetime import datetime, timezone +from pathlib import Path from typing import Any from .control_plane.runtime.time import parse_timestamp as _parse_timestamp @@ -161,17 +162,26 @@ def normalize_checkpointed_boundary_authority_entries( return entries -def _compact_checkpointed_boundary_authority_summary(value: Any) -> dict[str, Any] | None: +def _compact_checkpointed_boundary_authority_summary( + value: Any, + *, + goal_repo: str | Path | None = None, +) -> dict[str, Any] | None: if not isinstance(value, dict): return None + from .control_plane.coordination.configuration import fold_write_scope_subpaths + def _count(raw: Any) -> int: try: return max(0, int(raw or 0)) except (TypeError, ValueError): return 0 - active_scopes = normalize_required_write_scopes(value.get("active_write_scope")) + active_scopes = fold_write_scope_subpaths( + normalize_required_write_scopes(value.get("active_write_scope")), + goal_repo=goal_repo, + ) if not active_scopes and "active_count" not in value and "inactive_count" not in value: return None return { @@ -182,12 +192,21 @@ def _count(raw: Any) -> int: } -def checkpointed_boundary_authority_summary(coordination: dict[str, Any] | None) -> dict[str, Any] | None: +def checkpointed_boundary_authority_summary( + coordination: dict[str, Any] | None, + *, + goal_repo: str | Path | None = None, +) -> dict[str, Any] | None: if not isinstance(coordination, dict): return None + from .control_plane.coordination.configuration import fold_write_scope_subpaths + checkpointed_authority = coordination.get("checkpointed_boundary_authority") if isinstance(checkpointed_authority, dict): - compact_summary = _compact_checkpointed_boundary_authority_summary(checkpointed_authority) + compact_summary = _compact_checkpointed_boundary_authority_summary( + checkpointed_authority, + goal_repo=goal_repo, + ) if compact_summary is not None and "entries" not in checkpointed_authority: return compact_summary checkpointed_authority = checkpointed_authority.get("entries") @@ -202,6 +221,7 @@ def checkpointed_boundary_authority_summary(coordination: dict[str, Any] | None) for scope in normalize_required_write_scopes(entry.get("write_scope")): if scope not in active_scopes: active_scopes.append(scope) + active_scopes = fold_write_scope_subpaths(active_scopes, goal_repo=goal_repo) return { "schema_version": CHECKPOINTED_BOUNDARY_AUTHORITY_SCHEMA_VERSION, "active_count": len(active_entries), diff --git a/loopx/capabilities/explore/todo_branch_plan.py b/loopx/capabilities/explore/todo_branch_plan.py index 308a4ff799..3abd9ca304 100644 --- a/loopx/capabilities/explore/todo_branch_plan.py +++ b/loopx/capabilities/explore/todo_branch_plan.py @@ -445,13 +445,7 @@ def build_explore_todo_branch_plan( scopes = _required_write_scopes(candidate) resource_lane = str(candidate.get("resource_lane") or "") conflict_with = "" - if scopes: - for selected_todo_id, existing_scopes in selected_scopes: - if _scopes_overlap(scopes, existing_scopes): - conflict_with = selected_todo_id - hazards.append(f"write_scope_conflict:{selected_todo_id}") - break - elif not allow_unscoped_parallel and selected: + if not scopes and not allow_unscoped_parallel and selected: conflict_with = selected[0]["todo_id"] hazards.append("unscoped_parallel_disabled") @@ -586,7 +580,7 @@ def build_explore_todo_branch_plan( "rejected_candidates": rejected[: max(0, normalized_width * 3)], "resource_portfolio": resource_portfolio_with_selection(resource_portfolio, selected), "hazard_model": { - "write_scope_conflicts": "skip speculative branch when declared write scopes overlap", + "write_scope_conflicts": "retired from hard scheduling exclusion; leases isolate by Todo ownership and workspace checkout", "shared_dependencies": ( "shared_artifact:* and shared_implementation:* capabilities are read-only " "dependency labels, not write mutexes; mutable shared builds must remain in " diff --git a/loopx/cli_commands/todo.py b/loopx/cli_commands/todo.py index fb8a9e5aa9..b864c7aa81 100644 --- a/loopx/cli_commands/todo.py +++ b/loopx/cli_commands/todo.py @@ -7,7 +7,6 @@ from operator import itemgetter from pathlib import Path -from ..cli_runtime import report_json_text from ..command_invocation import cli_option_args, loopx_cli_argv from ..control_plane.agents.workspace_guard import capture_delivery_workspace from ..control_plane.capability_hooks import PostWritebackHookRegistration @@ -152,67 +151,6 @@ def _thin_claim_projection(payload: dict[str, object], route: Sequence[str]) -> } -def _thin_claim_overlap_advisories(payload: dict[str, object], route: Sequence[str]) -> None: - """Link long peer scope lists to the immutable claim receipt.""" - advisories = payload.get("integration_overlap_advisories") - goal_id = payload.get("goal_id") - operation_id = payload.get("claim_operation_id") - if ( - not isinstance(goal_id, str) or not goal_id - or not isinstance(operation_id, str) or not operation_id - or not isinstance(advisories, list) or not advisories - or any(not isinstance(row, dict) or not isinstance(row.get("write_scopes"), list) - for row in advisories) - ): - return - compact = { - "integration_overlap_advisories": [ - {**{key: value for key, value in row.items() if key != "write_scopes"}, - "write_scope_count": len(row["write_scopes"])} - for row in advisories - ], - "integration_overlap_detail_command": shlex.join([ - *route, "todo", "receipt", "--goal-id", goal_id, "--operation-id", operation_id, "--thin", - ]), - } - original = {"integration_overlap_advisories": advisories} - if len(report_json_text(compact).encode("utf-8")) < len(report_json_text(original).encode("utf-8")): - payload.update(compact) - - -def _thin_claim_receipt(payload: dict[str, object], goal_id: str, operation_id: str) -> None: - """Project historical overlap advice from the exact canonical claim receipt.""" - if payload.get("status") == "found": - records = payload.get("receipts") - receipt = records[0] if isinstance(records, list) and len(records) == 1 else None - result = receipt.get("result") if isinstance(receipt, dict) else None - if ( - not isinstance(receipt, dict) - or receipt.get("schema_version") != "loopx_coordination_todo_claim_receipt_v0" - or receipt.get("goal_id") != goal_id - or receipt.get("operation_id") != operation_id - or not isinstance(result, dict) - or result.get("claim_operation_id") != operation_id - or result.get("execution_managed") is not True - or not isinstance(result.get("todo_id"), str) - or not result["todo_id"] - or not isinstance(result.get("integration_overlap_advisories"), list) - ): - raise ValueError( - "todo receipt --thin requires an exact managed claim receipt with overlap advice. " - "Omit --thin for the full receipt." - ) - payload["receipts"] = [{ - **receipt, - "result": { - "claim_operation_id": operation_id, - "todo_id": result["todo_id"], - "integration_overlap_advisories": result["integration_overlap_advisories"], - }, - }] - payload["thin"] = True - - def handle_todo_command( args: argparse.Namespace, *, @@ -282,8 +220,6 @@ def handle_todo_command( ) elif args.todo_command == "receipt": validate_todo_receipt_options(args) - if args.todo_thin and output_format != "json": - raise ValueError("todo receipt --thin requires --format json") runtime_root = resolve_runtime_root( load_registry(registry_path), runtime_root_arg ) @@ -310,8 +246,6 @@ def handle_todo_command( "command": "receipt", **result, } - if args.todo_thin: - _thin_claim_receipt(payload, args.goal_id, args.operation_id) elif args.todo_command == "result-read": validate_todo_result_read_options(args) registry = load_registry(registry_path) @@ -586,8 +520,6 @@ def handle_todo_command( payload.pop(internal, None) if args.todo_thin: _thin_claim_projection(payload, route) - if output_format == "json": - _thin_claim_overlap_advisories(payload, route) elif args.todo_command == "update": validate_todo_update_options(args) update_operation = partial( diff --git a/loopx/cli_commands/todo_argument_validation.py b/loopx/cli_commands/todo_argument_validation.py index b612651ef1..286e18fdfd 100644 --- a/loopx/cli_commands/todo_argument_validation.py +++ b/loopx/cli_commands/todo_argument_validation.py @@ -149,7 +149,7 @@ # field owner; other lifecycle commands retain full help until centralized. TODO_ACTION_FIELDS = { "list": frozenset({"role", "todo_id", "status", "agent_id", "todo_limit", "todo_thin", "todo_summary", "include_archived", "state_file", "project", "dry_run"}), - "receipt": frozenset({"operation_id", "todo_thin"}), + "receipt": frozenset({"operation_id"}), "result-read": frozenset({"todo_id"}), "plan": frozenset({"text", "agent_id", "project"}), "project-markdown": frozenset({"state_file", "execute", "provider_revision", "project"}), @@ -325,7 +325,7 @@ def validate_todo_list_options(args: argparse.Namespace) -> None: def validate_todo_receipt_options(args: argparse.Namespace) -> None: _validate_todo_option_subset( args, TODO_ACTION_FIELDS["receipt"], - "todo receipt only accepts --goal-id, --operation-id, --thin, and --format; unsupported: ", + "todo receipt only accepts --goal-id, --operation-id, and --format; unsupported: ", ) if not args.operation_id: raise ValueError("todo receipt requires --operation-id") diff --git a/loopx/configure_goal.py b/loopx/configure_goal.py index 4ac5f6c14b..f707391f79 100644 --- a/loopx/configure_goal.py +++ b/loopx/configure_goal.py @@ -266,11 +266,15 @@ def _settings_summary(goal: dict[str, Any]) -> dict[str, Any]: "explore_graph": compact_explore_graph_policy(goal.get("explore_graph"), orchestration.get("explore_harness")), "orchestration": orchestration, "waiting_on": goal.get("waiting_on"), - "write_scope": normalize_goal_write_scope(coordination.get("write_scope") or []) + "write_scope": normalize_goal_write_scope( + coordination.get("write_scope") or [], + goal_repo=goal.get("repo"), + ) or [], **shadow.coordination_shadow_summaries(goal), "checkpointed_boundary_authority": checkpointed_boundary_authority_summary( - coordination + coordination, + goal_repo=goal.get("repo"), ), "registered_agents": registered_agents, "peer_task_coordination": deepcopy( @@ -1272,15 +1276,24 @@ def configure_goal( if clear_write_scope: coordination["write_scope"] = [] elif write_scope is not None: + goal_repo = goal.get("repo") if replace_write_scope: - coordination["write_scope"] = write_scope + coordination["write_scope"] = ( + normalize_goal_write_scope(write_scope, goal_repo=goal_repo) or [] + ) else: existing_write_scope = ( - normalize_goal_write_scope(coordination.get("write_scope") or []) + normalize_goal_write_scope( + coordination.get("write_scope") or [], + goal_repo=goal_repo, + ) or [] ) coordination["write_scope"] = ( - normalize_goal_write_scope([*existing_write_scope, *write_scope]) + normalize_goal_write_scope( + [*existing_write_scope, *write_scope], + goal_repo=goal_repo, + ) or [] ) if clear_boundary_authority: diff --git a/loopx/control_plane/agents/workspace_guard.py b/loopx/control_plane/agents/workspace_guard.py index 52a88eb38c..ef18428536 100644 --- a/loopx/control_plane/agents/workspace_guard.py +++ b/loopx/control_plane/agents/workspace_guard.py @@ -393,10 +393,10 @@ def _peer_work_requires_isolated_workspace( ) if not isinstance(candidate, dict): return False - if candidate.get("required_write_scopes"): - return True if str(candidate.get("task_class") or "").strip().lower() == "continuous_monitor": return False + if isinstance(candidate.get("task_repository"), str) and candidate["task_repository"].strip(): + return True action_kind = str(candidate.get("action_kind") or "").strip().lower() return action_kind in PEER_WRITE_ACTION_KINDS or action_kind.startswith( tuple(f"{prefix}_" for prefix in PEER_WRITE_ACTION_KINDS) diff --git a/loopx/control_plane/coordination/claim_execution.ts b/loopx/control_plane/coordination/claim_execution.ts index da9dd22acf..d5da0c48b9 100644 --- a/loopx/control_plane/coordination/claim_execution.ts +++ b/loopx/control_plane/coordination/claim_execution.ts @@ -110,17 +110,18 @@ export async function prepareClaimExecution(head: JsonObject, return {lease: renewed ?? current, changed: renewed !== null}; } const todo = index.todos.get(input.todo_id)!; - const writeScopes = coordinationTodoWriteScopes(todo); + const declaredScopes = coordinationTodoWriteScopes(todo); // Only declared repository code work can use the code-edit isolation mode. - // Shared-state and historical callers retain their conservative exclusion. + // Stop collecting per-path write_scopes on new leases by default while still + // enforcing symlink isolation and same-checkout exclusivity. const workspace = observeWorkspace && todo.task_domain === "code" && - typeof todo.task_repository === "string" && writeScopes.length > 0 - ? await observeWorkspace(writeScopes) : null; + typeof todo.task_repository === "string" && todo.task_repository.length > 0 + ? await observeWorkspace(declaredScopes) : null; 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(input.ttl_seconds), - write_scopes: writeScopes, ...(workspace ? {write_workspace: workspace} : {})}; + write_scopes: [] as string[], ...(workspace ? {write_workspace: workspace} : {})}; const decision = evaluateTaskLeaseAcquireDecision({handoff_mode: String(head.handoff_mode), registered_agents: [...input.registered_agents], ...facts, // Claim admission has already authorized this assignment. Acquire and the diff --git a/loopx/control_plane/coordination/configuration.py b/loopx/control_plane/coordination/configuration.py index 42047c6a5d..8fdf410707 100644 --- a/loopx/control_plane/coordination/configuration.py +++ b/loopx/control_plane/coordination/configuration.py @@ -2,8 +2,10 @@ from __future__ import annotations -from collections.abc import Mapping +from collections.abc import Mapping, Sequence from dataclasses import dataclass +from pathlib import Path, PurePosixPath +import posixpath from typing import Any from .coordination_state_contract_generated import LOCAL_AUTHORITY_SHADOW_CONFIG_SCHEMA @@ -12,8 +14,192 @@ RUNTIME_SHADOW_CONFIG_SCHEMA_VERSION = "loopx_coordination_runtime_shadow_config_v0" -def normalize_goal_write_scope(values: list[str] | None) -> list[str] | None: - """Split comma-delimited goal scopes and preserve first-seen order. +_CREDENTIAL_SCOPE_SEGMENTS = frozenset( + { + ".aws", + ".docker", + ".git-credentials", + ".gnupg", + ".kube", + ".netrc", + ".npmrc", + ".ssh", + "credentials", + "secrets", + } +) +_CREDENTIAL_FILE_SUFFIXES = (".key", ".p12", ".pem", ".pfx") + + +def _clean_scope_for_folding(value: str) -> str: + text = value.strip() + while "//" in text: + text = text.replace("//", "/") + while text.startswith("./") and text != "./**": + text = text[2:] + if text == "./**": + return "**" + if len(text) > 1 and text.endswith("/"): + text = text.rstrip("/") + return text + + +def _has_glob_metacharacters(text: str) -> bool: + return any(ch in text for ch in ("*", "?", "[", "]")) + + +def _repo_variants(goal_repo: str | Path | None) -> tuple[str, ...]: + if goal_repo is None: + return () + raw = str(goal_repo).strip() + if not raw: + return () + variants: list[str] = [] + raw_posix = PurePosixPath(raw).as_posix().rstrip("/") + if raw_posix: + variants.append(raw_posix) + try: + resolved = Path(raw).expanduser().resolve(strict=False).as_posix().rstrip("/") + except OSError: + resolved = "" + if resolved and resolved not in variants: + variants.append(resolved) + return tuple(variants) + + +def _is_sensitive_or_unfoldable(clean: str, repo_prefixes: tuple[str, ...]) -> tuple[bool, bool]: + """Return (unfoldable, is_external_abs) for a cleaned scope token.""" + + if not clean or ";" in clean or clean.startswith("~"): + return True, False + parts = [part for part in clean.split("/") if part] + if ".." in parts: + return True, False + for segment in parts: + lowered = segment.lower() + if lowered in _CREDENTIAL_SCOPE_SEGMENTS or lowered.endswith(_CREDENTIAL_FILE_SUFFIXES): + return True, False + if clean.startswith("/"): + if clean == "/**": + return False, False + in_repo = any(clean == repo or clean.startswith(f"{repo}/") for repo in repo_prefixes) + return False, not in_repo + return False, False + + +def _to_repo_relative(clean: str, repo_prefixes: tuple[str, ...]) -> str: + if clean == "/**": + return "**" + for repo in repo_prefixes: + if clean == repo: + return "**" + prefix = f"{repo}/" + if clean.startswith(prefix): + rel = clean[len(prefix) :] + return rel or "**" + return clean + + +def _prefix_covers(parent_stem: str, candidate: str) -> bool: + """Return True when ``parent_stem/**`` strictly covers ``candidate``.""" + + if parent_stem == "**": + return True + target = candidate[:-3] if candidate.endswith("/**") else candidate + if target.endswith("/*"): + target = target[:-2] + if target == ".": + return parent_stem == "**" + return target == parent_stem or target.startswith(f"{parent_stem}/") + + +def fold_write_scope_subpaths( + values: Sequence[str], + *, + goal_repo: str | Path | None = None, +) -> list[str]: + """Collapse redundant subpaths covered by ``/**``, ``**``, or ``dir/**``. + + Preserves explicit cross-repository external paths and credential + directories, and avoids mutating kept scope spellings. + """ + + deduped: list[str] = [] + seen_clean: set[str] = set() + for raw in values: + text = str(raw).strip() + if not text: + continue + clean = _clean_scope_for_folding(text) + dedupe_key = clean if clean not in ("**", "/**") else text + if dedupe_key in seen_clean: + continue + seen_clean.add(dedupe_key) + deduped.append(text) + if len(deduped) <= 1: + return deduped + + repo_prefixes = _repo_variants(goal_repo) + parsed: list[tuple[str, str, bool, bool, str]] = [] + for text in deduped: + clean = _clean_scope_for_folding(text) + unfoldable, is_external_abs = _is_sensitive_or_unfoldable(clean, repo_prefixes) + rel = clean if (unfoldable or is_external_abs) else _to_repo_relative(clean, repo_prefixes) + parsed.append((text, clean, unfoldable, is_external_abs, rel)) + + folded: list[str] = [] + for idx, (text, clean, unfoldable, is_external_abs, rel) in enumerate(parsed): + if unfoldable: + folded.append(text) + continue + covered = False + for jdx, (_other_text, other_clean, other_unfoldable, other_external_abs, other_rel) in enumerate(parsed): + if idx == jdx or other_unfoldable: + continue + if is_external_abs: + # External absolute paths are never folded under repo root; + # they fold only under another explicit external parent `dir/**`. + if not other_external_abs or not other_clean.endswith("/**"): + continue + other_stem = posixpath.normpath(other_clean[:-3]) + if not other_stem or other_stem == "/" or _has_glob_metacharacters(other_stem): + continue + if clean != other_clean and _prefix_covers(other_stem, clean): + covered = True + break + continue + + if other_external_abs: + continue + if other_rel == "**": + if rel != "**" or jdx < idx: + covered = True + break + continue + if not other_rel.endswith("/**"): + continue + other_stem = other_rel[:-3].rstrip("/") + if not other_stem or _has_glob_metacharacters(other_stem): + continue + if rel == other_rel: + if jdx < idx: + covered = True + break + continue + if _prefix_covers(other_stem, rel): + covered = True + break + if not covered: + folded.append(text) + return folded + + +def normalize_goal_write_scope( + values: list[str] | None, + *, + goal_repo: str | Path | None = None, +) -> list[str] | None: + """Split comma-delimited goal scopes, preserve order, and fold redundant subpaths. Goal configuration intentionally accepts a wider token vocabulary than a Todo's ``required_write_scopes`` contract, so its stricter normalizer is @@ -28,9 +214,10 @@ def normalize_goal_write_scope(values: list[str] | None) -> list[str] | None: scope = part.strip() if scope and scope not in scopes: scopes.append(scope) - return scopes + return fold_write_scope_subpaths(scopes, goal_repo=goal_repo) + -__all__ = ["normalize_goal_write_scope"] +__all__ = ["fold_write_scope_subpaths", "normalize_goal_write_scope"] @dataclass(frozen=True) class CoordinationRuntimeShadowConfig: @@ -151,8 +338,9 @@ def apply_coordination_runtime_shadow_change( if not enable_file and not clear: return - coordination = ( - goal.get("coordination") if isinstance(goal.get("coordination"), dict) else {} + raw_coordination = goal.get("coordination") + coordination: dict[str, Any] = ( + raw_coordination if isinstance(raw_coordination, dict) else {} ) if clear: coordination.pop("runtime_shadow", None) diff --git a/loopx/control_plane/coordination/task_lease_acquire.ts b/loopx/control_plane/coordination/task_lease_acquire.ts index ee75a4789f..38bd135fd7 100644 --- a/loopx/control_plane/coordination/task_lease_acquire.ts +++ b/loopx/control_plane/coordination/task_lease_acquire.ts @@ -117,8 +117,8 @@ export async function executeCanonicalTaskLeaseAcquire(store: AuthorityStore, ra return failed(decision.code, decision.code === "handoff_mode_retired" ? "Legacy ownership cannot grant new execution; release retained leases and review handoff-mode plan-migration/migrate before acquiring again." : `canonical task lease acquire rejected: ${decision.code}`, { - ...(decision.code === "write_scope_conflict" ? {recommended_action: - "Coordinate shared writes with the listed holders. For isolated code edits, use your own separate Git worktree and acquire with --write-worktree; file overlaps become integration advisories. A known same-checkout collision remains rejected. Never take over a foreign lease or use code-edit mode for shared runtime state."} : {}), + ...(decision.code === "workspace_lease_conflict" ? {recommended_action: + "Use an independent Git worktree and acquire with --write-worktree, or release your conflicting lease; two active leases cannot share one physical checkout. Never take over a foreign lease."} : {}), handoff_mode: mode, expected_version: input.expected_version, actual_version: leaseVersion(facts.current), ...(facts.todo ? {todo_status: facts.todo.status, claimed_by: facts.todo.claimed_by, excluded_agents: [...facts.todo.excluded_agents]} : {}), ...ownConflictRecovery, diff --git a/loopx/control_plane/coordination/todo_claim.ts b/loopx/control_plane/coordination/todo_claim.ts index df0c18fea2..e9215c6373 100644 --- a/loopx/control_plane/coordination/todo_claim.ts +++ b/loopx/control_plane/coordination/todo_claim.ts @@ -33,7 +33,6 @@ import { normalizeIdempotencyKey, normalizeTtl, } from "../work_items/task_lease_acquire.ts"; -import {coordinationTodoWriteScopes} from "./todo_write_scopes.ts"; export const COORDINATION_TODO_CLAIM_RESULT_SCHEMA = "loopx_coordination_todo_claim_result_v0"; @@ -616,8 +615,7 @@ async function executeClaimAttempt( leaseIdempotent = !leaseChanged; overlapAdvisories = prepared.overlapAdvisories ?? []; } else if (handoffMode === "hard_lease" && leaseRequest !== null) { - // Validate required scopes before planning; a caller cannot omit a required conflict. - const writeScopes = coordinationTodoWriteScopes(todo); + const writeScopes: string[] = []; const facts = canonicalTaskLeaseAcquireFacts(projection, input.goal_id, input.todo_id, input.registered_agents, input.now); const decision = evaluateTaskLeaseAcquireDecision({handoff_mode: handoffMode, registered_agents: [...input.registered_agents], ...facts, diff --git a/loopx/control_plane/quota/adaptive_children.ts b/loopx/control_plane/quota/adaptive_children.ts index 1c67c632af..5eba5836d1 100644 --- a/loopx/control_plane/quota/adaptive_children.ts +++ b/loopx/control_plane/quota/adaptive_children.ts @@ -121,24 +121,12 @@ export function admitAdaptiveChildren(value: unknown): JsonObject | null { if (admitted.length < 2) return null; const primary = admitted[0]; const selected: JsonObject[] = []; - const writeLanes = [primary]; for (let index = 1; index < admitted.length; index += 1) { const lane = admitted[index]; if (selected.length >= maxChildren) { blocked.push(...admitted.slice(index).map((row) => blockedLane(row, ["capacity_deferred"]))); break; } - const conflict = writeLanes.find( - (existing) => - existing.scopes.length && - lane.scopes.length && - existing.effectiveRepository === lane.effectiveRepository && - evaluateQuotaSchedulingWriteScopesOverlap({ left: existing.scopes, right: lane.scopes }).overlap, - ); - if (conflict) { - blocked.push({ ...blockedLane(lane, ["write_scope_conflict"]), conflicts_with_todo_id: conflict.id }); - continue; - } const item = lane.item; const brief: JsonObject = { todo_id: lane.id, @@ -166,7 +154,6 @@ export function admitAdaptiveChildren(value: unknown): JsonObject | null { execution_kind: "ephemeral_child", child_brief: brief, }); - writeLanes.push(lane); } if (!selected.length) return null; return { diff --git a/loopx/control_plane/quota/goal_boundary.py b/loopx/control_plane/quota/goal_boundary.py index b7cd6cb0a2..4a2901b165 100644 --- a/loopx/control_plane/quota/goal_boundary.py +++ b/loopx/control_plane/quota/goal_boundary.py @@ -158,6 +158,7 @@ def _registry_boundary_projection(goal: Mapping[str, Any]) -> dict[str, Any]: coordination: dict[str, Any] = ( coordination_value if isinstance(coordination_value, dict) else {} ) + goal_repo = goal.get("repo") write_scope_value = coordination.get("write_scope") write_scope = write_scope_value if isinstance(write_scope_value, list) else [] normalized_write_scope: list[str] = [] @@ -165,7 +166,10 @@ def _registry_boundary_projection(goal: Mapping[str, Any]) -> dict[str, Any]: scope = str(value).strip() if scope and scope not in normalized_write_scope: normalized_write_scope.append(scope) - boundary_authority = checkpointed_boundary_authority_summary(coordination) + boundary_authority = checkpointed_boundary_authority_summary( + coordination, + goal_repo=goal_repo, + ) if boundary_authority: for scope in normalize_required_write_scopes( boundary_authority.get("active_write_scope") @@ -174,7 +178,12 @@ def _registry_boundary_projection(goal: Mapping[str, Any]) -> dict[str, Any]: normalized_write_scope.append(scope) boundary["checkpointed_boundary_authority"] = boundary_authority if normalized_write_scope: - boundary["write_scope"] = normalized_write_scope + from ..coordination.configuration import fold_write_scope_subpaths + + boundary["write_scope"] = fold_write_scope_subpaths( + normalized_write_scope, + goal_repo=goal_repo, + ) available_capabilities = declared_available_capabilities(goal) if available_capabilities: boundary["available_capabilities"] = available_capabilities diff --git a/loopx/control_plane/quota/progressive_context.ts b/loopx/control_plane/quota/progressive_context.ts index e918cda866..4e3d3ddc88 100644 --- a/loopx/control_plane/quota/progressive_context.ts +++ b/loopx/control_plane/quota/progressive_context.ts @@ -426,9 +426,12 @@ function compactObservedSelection(ordinary: ReadSelection[], selected: ReadSelec * bodies again. A coalesced parent can span both parts; keep only the coverage * shared by the verified reduced selection and the ordinary remainder. */ function withLinkedObservedRemainder(observed: JsonObject | undefined, - initial: ReturnType | undefined): JsonObject | undefined { - if (!observed || !initial?.linked_opening_detail || !initial.remaining - || Object.hasOwn(observed.reused as JsonObject, initial.linked_opening_detail)) return observed; + initial: ReturnType | undefined, + details?: readonly string[]): JsonObject | undefined { + const requiredDetails = details?.length ? details + : (initial?.linked_opening_detail ? [initial.linked_opening_detail] : []); + if (!observed || !initial?.linked_opening_detail || !initial.remaining || !requiredDetails.length + || requiredDetails.every(detail => Object.hasOwn(observed.reused as JsonObject, detail))) return observed; const ordinary = initial.plan.selections as ReadSelection[]; const selected = observedSelection(ordinary, observed); if (selected === undefined) return observed; @@ -750,7 +753,7 @@ export function prepareProgressiveContextDelivery(request: JsonObject, legacyFie const initial = request.include_initial_read_plan === true && groups ? nativeContextReadPlan(required.context, pointers, groups, openingSplit) : undefined; const observed = observe && pointers.length - ? withLinkedObservedRemainder(observedFirstRead(codec, pointers, exactBody), initial) : undefined; + ? withLinkedObservedRemainder(observedFirstRead(codec, pointers, exactBody), initial, openingSplit?.details) : undefined; const {operation: _operation, source_edits: _edits, source_number_tokens: _numbers, ...source} = request; return contextProjectionChanges(source, {context: required.context, delivery, projected: required.projected, ...(observed ? {observed_first_read: observed} : {}), @@ -773,60 +776,73 @@ function prepareInitialOpening(context: JsonObject, groups: ReturnType(); + const details: string[] = []; + let linkedDetail: string | undefined; if (cli?.selection_required === true && groups.opening.includes(candidate)) { // This Todo is a recommendation. The current operation is selection; // keep its route and permission controls ahead of the candidate's details. - const controls = ["selection_required", "selection_policy_ref", "selection_command", + const selectionControls = ["selection_required", "selection_policy_ref", "selection_command", "next_cli_actions", "spend_allowed_now", "spend_after_validation", "spend_policy"] .map(field => pointer(["interaction_contract", "cli_channel", field])); - for (const control of [...controls, "/action_portfolio/selection_policy", + for (const control of [...selectionControls, "/action_portfolio/selection_policy", "/action_portfolio/suggested_actions"]) { const index = groups.remaining.indexOf(control); if (index >= 0) groups.opening.push(...groups.remaining.splice(index, 1)); } - return {controls: new Map([[candidate, []]]), details: [candidate], linkedDetail: candidate}; + controls.set(candidate, []); + details.push(candidate); + linkedDetail = candidate; } - if (!scope) return undefined; - const parent = scope.slice(0, -1), detail = scope.at(-1)!; - const body = jsonObject(at(context, parent)), boundary = pointer(parent); - const controls = new Map(); - const details: string[] = []; - let linkedDetail: string | undefined; - if (groups.opening.includes(boundary) && body && Array.isArray(body[detail]) && body[detail].length) { - const boundaryControls = Object.keys(body).filter(key => key !== detail).map(key => pointer([...parent, key])); - linkedDetail = pointer(scope); - details.push(linkedDetail); - controls.set(boundary, boundaryControls); - const checkpointPath = [...parent, "checkpointed_boundary_authority"]; - const checkpoint = jsonObject(at(context, checkpointPath)); - if (checkpoint?.schema_version === "checkpointed_boundary_authority_v0" - && Array.isArray(checkpoint.active_write_scope) && Number.isSafeInteger(checkpoint.active_count) - && Number.isSafeInteger(checkpoint.inactive_count) && Array.isArray(checkpoint.entries) - && checkpoint.entries.length) { - // Keep the current approval summary in the opening. Read the exact - // entries and write scope from the same capture before work. - const checkpointIndex = boundaryControls.indexOf(pointer(checkpointPath)); - boundaryControls.splice(checkpointIndex, 1, ...Object.keys(checkpoint).filter(key => key !== "entries") - .map(key => pointer([...checkpointPath, key]))); - details.push(pointer([...checkpointPath, "entries"])); + const parent = scope ? scope.slice(0, -1) : groups.opening + .map(field => field.slice(1).split("/").map(part => part.replace(/~1/g, "/").replace(/~0/g, "~"))) + .find(path => path.length === 1 && jsonObject(jsonObject(at(context, path))?.checkpointed_boundary_authority) != null); + if (parent) { + const detail = scope?.at(-1); + const body = jsonObject(at(context, parent)), boundary = pointer(parent); + if (groups.opening.includes(boundary) && body) { + const deferWriteScope = Boolean(scope && detail && Array.isArray(body[detail]) && body[detail].length); + const checkpointPath = [...parent, "checkpointed_boundary_authority"]; + const checkpoint = jsonObject(at(context, checkpointPath)); + const activeWriteScopes = checkpoint?.active_write_scope; + const checkpointEntries = checkpoint?.entries; + const hasCheckpoint = checkpoint?.schema_version === "checkpointed_boundary_authority_v0" + && (activeWriteScopes === undefined || Array.isArray(activeWriteScopes)) + && Number.isSafeInteger(checkpoint.active_count) + && Number.isSafeInteger(checkpoint.inactive_count); + const hasActiveScopes = hasCheckpoint && Array.isArray(activeWriteScopes) && activeWriteScopes.length > 0; + const hasCheckpointEntries = hasCheckpoint && Array.isArray(checkpointEntries) && checkpointEntries.length > 0; + if (deferWriteScope || hasActiveScopes || hasCheckpointEntries) { + const boundaryControls = Object.keys(body) + .filter(key => !(deferWriteScope && key === detail)) + .map(key => pointer([...parent, key])); + if (deferWriteScope) details.push(pointer(scope!)); + if (hasActiveScopes || hasCheckpointEntries) { + // Keep only approval summary counts on page 0; read active_write_scope and + // entries on demand from the same capture. + const checkpointIndex = boundaryControls.indexOf(pointer(checkpointPath)); + if (checkpointIndex >= 0) { + boundaryControls.splice( + checkpointIndex, + 1, + ...Object.keys(checkpoint) + .filter(key => key !== "entries" && key !== "active_write_scope") + .map(key => pointer([...checkpointPath, key])), + ); + } + if (hasActiveScopes) details.push(pointer([...checkpointPath, "active_write_scope"])); + if (hasCheckpointEntries) details.push(pointer([...checkpointPath, "entries"])); + } + controls.set(boundary, boundaryControls); + if (!linkedDetail) linkedDetail = deferWriteScope ? pointer(scope!) : details[0]; + // Current readiness belongs with the decision. Reorder only the new pinned + // reader, so an explicit historical initial-read cursor still replays. + const preparation = groups.remaining.indexOf("/interaction_contract/cli_channel/execution_preparation"); + if (preparation >= 0) groups.opening.push(...groups.remaining.splice(preparation, 1)); + } } } - const selected = jsonObject(context.selected_todo), requested = "required_write_scopes"; - const scopes = selected?.[requested]; - if (groups.opening.includes(candidate) && selected?.schema_version === "quota_selected_todo_v0" - && Array.isArray(scopes) && scopes.length && scopes.every(value => typeof value === "string" && value)) { - controls.set(candidate, Object.keys(selected).filter(key => key !== requested) - .map(key => pointer(["selected_todo", key]))); - // Current requested scopes need this read even when the Goal's exact - // write scope can carry forward from an earlier observation. - linkedDetail = pointer(["selected_todo", requested]); - details.push(linkedDetail); - } if (!linkedDetail) return undefined; - // Current readiness belongs with the decision. Reorder only the new pinned - // reader, so an explicit historical initial-read cursor still replays. - const preparation = groups.remaining.indexOf("/interaction_contract/cli_channel/execution_preparation"); - if (preparation >= 0) groups.opening.push(...groups.remaining.splice(preparation, 1)); return {controls, details, linkedDetail}; } diff --git a/loopx/control_plane/quota/projection_repair.py b/loopx/control_plane/quota/projection_repair.py index a811061db7..41b02a8411 100644 --- a/loopx/control_plane/quota/projection_repair.py +++ b/loopx/control_plane/quota/projection_repair.py @@ -1,6 +1,7 @@ from __future__ import annotations from .effective_action import EffectiveAction +from pathlib import Path from typing import Any from ...state_projection import actions_are_projection_aligned, is_user_wait_text @@ -179,6 +180,47 @@ def _write_scope_coverage( return [covered[index:index + width] for index in range(0, len(covered), width)] +def _goal_boundary_covers_repo_root( + allowed_scopes: list[str], + *, + goal_repo: str | Path | None = None, +) -> bool: + if not allowed_scopes: + return False + repo_roots: set[str] = set() + if goal_repo is not None: + raw_repo = str(goal_repo).strip() + if raw_repo: + repo_roots.add(Path(raw_repo).as_posix().rstrip("/")) + try: + repo_roots.add(Path(raw_repo).expanduser().resolve(strict=False).as_posix().rstrip("/")) + except OSError: + pass + for raw in allowed_scopes: + clean = str(raw).strip() + if clean in {"**", "./**", "/**", ".", "./"}: + return True + norm = clean.rstrip("/") + if norm in repo_roots or (clean.endswith("/**") and clean[:-3].rstrip("/") in repo_roots): + return True + return False + + +def _lookup_raw_todo( + raw_summary: dict[str, Any] | None, + todo_id: Any, +) -> dict[str, Any] | None: + if not isinstance(raw_summary, dict) or not isinstance(todo_id, str) or not todo_id: + return None + for value in raw_summary.values(): + if not isinstance(value, list): + continue + for item in value: + if isinstance(item, dict) and item.get("todo_id") == todo_id: + return item + return None + + def build_boundary_projection_repair_hint( goal_boundary: dict[str, Any] | None, agent_todo_summary: dict[str, Any] | None, @@ -186,6 +228,8 @@ def build_boundary_projection_repair_hint( candidate_should_run: bool, capability_gate: dict[str, Any] | None = None, selected_todo: dict[str, Any] | None = None, + raw_agent_todo_summary: dict[str, Any] | None = None, + goal_repo: str | Path | None = None, ) -> dict[str, Any] | None: if not candidate_should_run or not isinstance(agent_todo_summary, dict): return None @@ -215,14 +259,31 @@ def build_boundary_projection_repair_hint( break if not selected: return None + raw_match = _lookup_raw_todo(raw_agent_todo_summary, selected.get("todo_id")) + if raw_match: + selected = {**raw_match, **selected, + **({"required_write_scopes": raw_match["required_write_scopes"]} + if "required_write_scopes" not in selected and "required_write_scopes" in raw_match else {}), + **({"task_repository": raw_match["task_repository"]} + if not selected.get("task_repository") and raw_match.get("task_repository") else {})} + task_repository = selected.get("task_repository") + if isinstance(task_repository, str) and task_repository.strip(): + return None required_scopes = normalize_required_write_scopes( selected.get("required_write_scopes") ) if not required_scopes: return None boundary = goal_boundary if isinstance(goal_boundary, dict) else {} - allowed_scopes = normalize_required_write_scopes(boundary.get("write_scope")) + raw_allowed = [ + str(value).strip() + for value in (boundary.get("write_scope") or []) + if isinstance(value, str) and str(value).strip() + ] + if _goal_boundary_covers_repo_root(raw_allowed, goal_repo=goal_repo): + return None + allowed_scopes = normalize_required_write_scopes(raw_allowed) active_coverage = _write_scope_coverage(required_scopes, [allowed_scopes])[0] missing_scopes = [scope for scope, covered in zip(required_scopes, active_coverage) if not covered] if not missing_scopes: diff --git a/loopx/control_plane/quota/selected_todo_projection.py b/loopx/control_plane/quota/selected_todo_projection.py index 0bcc7e3a70..aa60a59227 100644 --- a/loopx/control_plane/quota/selected_todo_projection.py +++ b/loopx/control_plane/quota/selected_todo_projection.py @@ -19,7 +19,6 @@ "capability_binding_ref", "task_repository", "continuation_policy", - "required_write_scopes", "required_capabilities", "claimed_by", "bound_agent", diff --git a/loopx/control_plane/quota/should_run.py b/loopx/control_plane/quota/should_run.py index 02694ed368..61ab4f60af 100644 --- a/loopx/control_plane/quota/should_run.py +++ b/loopx/control_plane/quota/should_run.py @@ -346,6 +346,7 @@ def _apply_selected_todo_guards( current_path=workspace_path, local_workspace=local_workspace, ) + raw_todos = prepared.item.get("agent_todos") if isinstance(prepared.item, dict) else None boundary_projection_repair = build_boundary_projection_repair_hint( {**goal_boundary, "write_scope": [ *goal_boundary.get("write_scope", []), @@ -355,6 +356,8 @@ def _apply_selected_todo_guards( candidate_should_run=bool(route.should_run), capability_gate=prepared.capability_gate, selected_todo=selected_todo, + raw_agent_todo_summary=raw_todos if isinstance(raw_todos, dict) else None, + goal_repo=prepared.item.get("repo") if isinstance(prepared.item, dict) else None, ) if not workspace_guard and not boundary_projection_repair: return route diff --git a/loopx/control_plane/quota/task_orchestration_admission.py b/loopx/control_plane/quota/task_orchestration_admission.py index df457b259b..0b8b5ea529 100644 --- a/loopx/control_plane/quota/task_orchestration_admission.py +++ b/loopx/control_plane/quota/task_orchestration_admission.py @@ -34,6 +34,31 @@ def _optional_text(value: Any) -> str | None: return str(value or "").strip() or None +def _raw_write_scopes_by_todo_id(summary: Any) -> dict[str, list[str]]: + """Recover raw required_write_scopes when summary items omit them by default.""" + if not isinstance(summary, dict): + return {} + by_id: dict[str, list[str]] = {} + for key in ( + "first_open_items", + "active_next_action_items", + "items", + "backlog_items", + ): + rows = summary.get(key) + if not isinstance(rows, list): + continue + for row in rows: + if not isinstance(row, dict) or "required_write_scopes" not in row: + continue + todo_id = _optional_text(row.get("todo_id")) + if todo_id and todo_id not in by_id: + by_id[todo_id] = normalize_required_write_scopes( + row.get("required_write_scopes") + ) + return by_id + + def build_adaptive_task_orchestration_contract( *, agent_id: str, @@ -48,8 +73,15 @@ def build_adaptive_task_orchestration_contract( parent_goal_id: str | None, max_children: int, ) -> dict[str, Any] | None: + raw_scopes_by_id = _raw_write_scopes_by_todo_id(raw_agent_todo_summary) items = [] for item in _source_items(agent_todo_source_items, raw_agent_todo_summary): + todo_id = _optional_text(item.get("todo_id")) + raw_scopes = ( + item.get("required_write_scopes") + if "required_write_scopes" in item + else raw_scopes_by_id.get(todo_id or "") + ) items.append( { **{ @@ -87,7 +119,7 @@ def build_adaptive_task_orchestration_contract( ), "repository_declared": bool(item.get("task_repository")), "required_write_scopes": normalize_required_write_scopes( - item.get("required_write_scopes") + raw_scopes ), "required_capabilities": normalize_required_capabilities( item.get("required_capabilities") diff --git a/loopx/control_plane/quota/turn_envelope.ts b/loopx/control_plane/quota/turn_envelope.ts index 20dd18d001..779ab1aa8c 100644 --- a/loopx/control_plane/quota/turn_envelope.ts +++ b/loopx/control_plane/quota/turn_envelope.ts @@ -1331,52 +1331,49 @@ function readyWriteScope(context: JsonObject): ReusableExactBody | undefined { /** Work preparation retains current controls and keeps long scope lists at their exact source addresses. */ function progressivePreparationScopes(payload: JsonObject): PreparationScopeDetail[] { + const boundary = jsonObject(payload.goal_boundary); + const cba = jsonObject(boundary?.checkpointed_boundary_authority); + const hasActiveApprovalScopes = cba?.schema_version === "checkpointed_boundary_authority_v0" && + Array.isArray(cba.active_write_scope) && cba.active_write_scope.some(s => typeof s === "string" && s.length > 0); const interaction = jsonObject(payload.interaction_contract); const cli = jsonObject(interaction?.cli_channel); const preparation = jsonObject(cli?.execution_preparation); - if (interaction?.schema_version !== INTERACTION_CONTRACT_SCHEMA_VERSION || - payload.should_run !== true || - jsonObject(interaction.agent_channel)?.delivery_allowed !== false || - cli?.spend_allowed_now !== false || cli.spend_after_validation !== false) return []; const obligation = jsonObject(payload.execution_obligation); - const repair = payload.effective_action === EffectiveAction.AGENT_WORKSPACE_REPAIR && + const repair = interaction?.schema_version === INTERACTION_CONTRACT_SCHEMA_VERSION && + payload.should_run === true && + jsonObject(interaction.agent_channel)?.delivery_allowed === false && + cli?.spend_allowed_now === false && cli.spend_after_validation === false && + payload.effective_action === EffectiveAction.AGENT_WORKSPACE_REPAIR && interaction.mode === EffectiveAction.AGENT_WORKSPACE_REPAIR && payload.workspace_repair_allowed === true && payload.normal_delivery_allowed === false && payload.recovery_delivery_allowed === false && obligation?.kind === EffectiveAction.AGENT_WORKSPACE_REPAIR && obligation.contract === "agent_workspace_guard" && obligation.must_attempt_work === true && obligation.delivery_allowed === false; - if (!repair && payload.effective_action !== EffectiveAction.NORMAL_RUN) return []; - const selecting = hasUnboundActionSelection(cli); + const prepEligible = interaction?.schema_version === INTERACTION_CONTRACT_SCHEMA_VERSION && + payload.should_run === true && + jsonObject(interaction.agent_channel)?.delivery_allowed === false && + cli?.spend_allowed_now === false && cli.spend_after_validation === false && + (repair || payload.effective_action === EffectiveAction.NORMAL_RUN); + const selecting = prepEligible && hasUnboundActionSelection(cli); const selected = jsonObject(payload.selected_todo); - const claiming = cli.selection_required !== true && payload.normal_delivery_allowed === false && + const claiming = prepEligible && cli?.selection_required !== true && payload.normal_delivery_allowed === false && preparation?.schema_version === EXECUTION_PREPARATION_SCHEMA_VERSION && preparation.state === "claim_required" && preparation.delivery_allowed === false && typeof selected?.todo_id === "string" && preparation.todo_id === selected.todo_id && jsonObject(preparation.claim)?.host_execution_allowed === true; - if (!repair && !selecting && !claiming) return []; - const boundary = jsonObject(payload.goal_boundary); + if (!repair && !selecting && !claiming && !hasActiveApprovalScopes) return []; // The recovery pointer and its guidance also cost bytes. Leave short lists inline. const longScope = (value: unknown) => Array.isArray(value) && value.every(scope => typeof scope === "string") && Buffer.byteLength(JSON.stringify(value)) >= 1024; const scopes: PreparationScopeDetail[] = []; - if (boundary && !Object.hasOwn(boundary, "write_scope_pointer") && longScope(boundary.write_scope)) scopes.push({ + if ((repair || selecting || claiming) && boundary && !Object.hasOwn(boundary, "write_scope_pointer") && longScope(boundary.write_scope)) scopes.push({ path: ["goal_boundary", "write_scope"], marker_path: ["goal_boundary", "write_scope_pointer"], instruction: repair ? "If workspace repair needs the Goal's write scopes, select /goal_boundary/write_scope from the source below. " : "If work preparation needs the Goal's write scopes, select the pointer in goal_boundary.write_scope_pointer from the source below. ", }); - if (selected?.schema_version === "quota_selected_todo_v0" && - typeof selected.todo_id === "string" && longScope(selected.required_write_scopes)) scopes.push({ - path: ["selected_todo", "required_write_scopes"], - instruction: "If this preparation needs the Todo's requested write scopes, select /selected_todo/required_write_scopes from the source below. ", - }); - const suggestions = jsonObject(payload.action_portfolio)?.suggested_actions; - if (selecting && Array.isArray(suggestions)) suggestions.forEach((value, index) => { - const candidate = jsonObject(value); - if (typeof candidate?.todo_id !== "string" || !longScope(candidate.required_write_scopes)) return; - const path = ["action_portfolio", "suggested_actions", index, "required_write_scopes"]; - scopes.push({path, - instruction: `If choosing a candidate depends on its requested write scopes, select /${path.join("/")} from the source below. `, - }); + if (hasActiveApprovalScopes) scopes.push({ + path: ["goal_boundary", "checkpointed_boundary_authority", "active_write_scope"], + instruction: "If this turn depends on checkpointed approved write scopes, select /goal_boundary/checkpointed_boundary_authority/active_write_scope from the source below. ", }); const finalScope = scopes.at(-1); if (finalScope) finalScope.instruction += repair diff --git a/loopx/control_plane/todos/context_projection.ts b/loopx/control_plane/todos/context_projection.ts index f920604fac..812a93a5e9 100644 --- a/loopx/control_plane/todos/context_projection.ts +++ b/loopx/control_plane/todos/context_projection.ts @@ -206,7 +206,7 @@ const SUMMARY_FIELDS = [ "goal_acceptance_guard", "schema_version", "todo_id", "content_revision", "role", "status", "priority", "title", "archive_state", "source_section", "task_class", "action_kind", "task_domain", "capability_binding_ref", "task_repository", - "continuation_policy", "removed_continuation_policy", "required_write_scopes", "required_capabilities", "target_capabilities", + "continuation_policy", "removed_continuation_policy", "required_capabilities", "target_capabilities", "decision_scope", "required_decision_scopes", "decision_outcome", "decision_scope_outcomes", "claimed_by", "bound_agent", "goal_bound", "blocks_agent", "excluded_agents", "global_gate", "unblocks_todo_id", "resume_when", "resume_monitor_generation", "resume_condition", "resume_ready", @@ -249,7 +249,7 @@ function compactSummaryRecord(item: JsonObject, body: unknown): JsonObject { } const normalized: JsonObject = { task_domain: /^[a-z][a-z0-9_.-]{0,63}$/.test(token("task_domain").toLowerCase()) ? token("task_domain").toLowerCase() : null, - required_write_scopes: writeScopes(Array.isArray(row.required_write_scopes) ? row.required_write_scopes : token("required_write_scopes")), task_repository: repository, + task_repository: repository, decision_scope: readScope(row.decision_scope), required_decision_scopes: readScopes(row.required_decision_scopes), decision_outcome: outcome(token("decision_outcome")), decision_scope_outcomes: outcomes, excluded_agents: readExcludedAgents(row.excluded_agents), diff --git a/loopx/control_plane/todos/quota_selection.ts b/loopx/control_plane/todos/quota_selection.ts index 86c7ee34a1..77d5e2d0dd 100644 --- a/loopx/control_plane/todos/quota_selection.ts +++ b/loopx/control_plane/todos/quota_selection.ts @@ -781,7 +781,7 @@ function successionWarning(value: JsonObject, ref: (path: Path) => JsonObject, const projected: JsonObject = {index: copy("index"), text: copy("text")}; for (const name of [ "schema_version", "todo_id", "role", "status", "priority", "title", "archive_state", "source_section", - "task_class", "action_kind", "task_domain", "task_repository", "continuation_policy", "required_write_scopes", + "task_class", "action_kind", "task_domain", "task_repository", "continuation_policy", "required_capabilities", "target_capabilities", "decision_scope", "required_decision_scopes", "claimed_by", "blocks_agent", "excluded_agents", "unblocks_todo_id", "resume_when", "resume_monitor_generation", "resume_condition", "resume_ready", "no_followup", "successor_todo_ids", "target_key", "cadence", "next_due_at", @@ -791,7 +791,7 @@ function successionWarning(value: JsonObject, ref: (path: Path) => JsonObject, "route_continuation_reason", "route_id", "route_key", "completed_at", "updated_at", "superseded_by", "completion_continuation", "completion_recovery", "completion_turn_key", "done", "succession_tracked", "recommended_action", ]) if (row[name] != null) projected[name] = copy(name); - for (const [name, normalized] of [["required_write_scopes", writeScopes(row.required_write_scopes)], + for (const [name, normalized] of [ ["decision_scope", readScope(row.decision_scope)], ["required_decision_scopes", readScopes(row.required_decision_scopes)]] as const) { if (normalized && (!Array.isArray(normalized) || normalized.length)) projected[name] = normalized; else delete projected[name]; diff --git a/loopx/control_plane/todos/quota_summary.py b/loopx/control_plane/todos/quota_summary.py index f71bf0a812..b21d498e2d 100644 --- a/loopx/control_plane/todos/quota_summary.py +++ b/loopx/control_plane/todos/quota_summary.py @@ -42,7 +42,6 @@ "task_repository", "continuation_policy", "required_capabilities", - "required_write_scopes", "missing_capabilities", "claimed_by", "bound_agent", @@ -132,7 +131,6 @@ "global_gate", "unblocks_todo_id", "required_capabilities", - "required_write_scopes", "missing_capabilities", "resume_ready", "next_due_at", diff --git a/loopx/control_plane/work_items/action_portfolio.ts b/loopx/control_plane/work_items/action_portfolio.ts index 1d56a9ee57..8b14c793f4 100644 --- a/loopx/control_plane/work_items/action_portfolio.ts +++ b/loopx/control_plane/work_items/action_portfolio.ts @@ -118,11 +118,8 @@ function suggestedActionProjection(candidate: ActionCandidate): JsonObject { for (const field of ["priority", "action_kind", "continuation_hint"] as const) { if (candidate[field] !== undefined) projected[field] = candidate[field]; } - for (const field of [ - "required_capabilities", - "required_write_scopes", - ] as const) { - if (candidate[field] !== undefined) projected[field] = candidate[field]; + if (candidate.required_capabilities !== undefined) { + projected.required_capabilities = candidate.required_capabilities; } if (candidate.claim_required_before_work === true) { projected.claim_required_before_work = true; diff --git a/loopx/control_plane/work_items/planning_inventory.ts b/loopx/control_plane/work_items/planning_inventory.ts index 3bd254bc8d..33c16c893f 100644 --- a/loopx/control_plane/work_items/planning_inventory.ts +++ b/loopx/control_plane/work_items/planning_inventory.ts @@ -137,10 +137,18 @@ function candidate(value: unknown, label: string): Candidate { `${label}.successor_todo_ids`, ).map((item, index) => todoId(item, `${label}.successor_todo_ids[${index}]`)); } - for (const field of ["required_capabilities", "required_write_scopes"] as const) { - if (raw[field] !== null && raw[field] !== undefined) { - decoded[field] = requireStringArray(raw[field], `${label}.${field}`); - } + if (raw.required_capabilities !== null && raw.required_capabilities !== undefined) { + decoded.required_capabilities = requireStringArray( + raw.required_capabilities, + `${label}.required_capabilities`, + ); + } + if (raw.required_write_scopes !== null && raw.required_write_scopes !== undefined) { + const scopes = requireStringArray( + raw.required_write_scopes, + `${label}.required_write_scopes`, + ); + if (raw.include_write_scopes === true) decoded.required_write_scopes = scopes; } if (raw.resume_ready !== null && raw.resume_ready !== undefined) { if (typeof raw.resume_ready !== "boolean") { diff --git a/loopx/control_plane/work_items/task_lease_acquire.ts b/loopx/control_plane/work_items/task_lease_acquire.ts index 360d7a7208..8784dc8646 100644 --- a/loopx/control_plane/work_items/task_lease_acquire.ts +++ b/loopx/control_plane/work_items/task_lease_acquire.ts @@ -531,7 +531,7 @@ const VALIDATION_FAILURE_CODES = new Set([ "invalid_idempotency_key", ...PERMISSION_DENIED_CODES, "todo_lease_conflict", - "write_scope_conflict", + "workspace_lease_conflict", "lease_generation_exhausted", "authority_source_changed", "corrupt_lease", diff --git a/loopx/control_plane/work_items/task_lease_acquire_decision.ts b/loopx/control_plane/work_items/task_lease_acquire_decision.ts index fb381a7af8..4ba77519d2 100644 --- a/loopx/control_plane/work_items/task_lease_acquire_decision.ts +++ b/loopx/control_plane/work_items/task_lease_acquire_decision.ts @@ -730,20 +730,17 @@ export function decideTaskLeaseAcquire(input: AcquireDecisionInput): AcquireDeci if (workspace && workspace.repository.toLowerCase() !== repository?.toLowerCase()) { return acquireDecisionResult("rejected", "lease_workspace_repository_mismatch"); } - const advisoryIndexes: number[] = [], conflictIndexes: number[] = []; + const conflictIndexes: number[] = []; for (const [index, other] of input.other_leases.entries()) { if (!other.active || !other.effective) continue; - const sameCheckout = workspace !== null && sameLeaseCheckout(workspace, other.write_workspace); - if ((!sameCheckout && !repositoryScopesMayOverlap(repository, other.write_repository)) || - !writeScopesOverlap(command.write_scopes, other.write_scopes)) continue; - // Verified code-edit mode coordinates integration, rather than requesting - // cross-checkout file exclusivity. Unknown legacy workspaces stay unknown; - // neither their records nor their execution ownership are changed. - if (workspace && !sameCheckout) advisoryIndexes.push(index); - else conflictIndexes.push(index); + // Lease isolation is keyed on Todo ownership plus same physical checkout/worktree + // exclusivity; per-path write_scopes conflicts are retired. + if (workspace !== null && sameLeaseCheckout(workspace, other.write_workspace)) { + conflictIndexes.push(index); + } } if (conflictIndexes.length > 0) { - return acquireDecisionResult("conflict", "write_scope_conflict", { + return acquireDecisionResult("conflict", "workspace_lease_conflict", { conflictIndexes, }); } @@ -751,7 +748,7 @@ export function decideTaskLeaseAcquire(input: AcquireDecisionInput): AcquireDeci return acquireDecisionResult("rejected", "lease_generation_exhausted"); } return acquireDecisionResult("apply", "lease_acquire", { - advisoryIndexes, + advisoryIndexes: [], nextLease: { present: true, active: true, diff --git a/loopx/pi_goal_mode/README.md b/loopx/pi_goal_mode/README.md index 49cca9033e..0c203a7089 100644 --- a/loopx/pi_goal_mode/README.md +++ b/loopx/pi_goal_mode/README.md @@ -35,7 +35,7 @@ into a LoopX-governed visible goal loop. current owner; the model cannot substitute either authority. Mutation calls require a non-empty host-verified bound `agentId` and the host-issued `task_lease_v0` capability. Typed - conflict and CAS payloads (for example `write_scope_conflict` and + conflict and CAS payloads (for example `workspace_lease_conflict` and `lease_cas_mismatch`) are preserved as the tool result. - **Goal loop** — on every `agent_settled`, the extension probes `loopx quota should-run --runtime-profile generic_cli` for the bound goal. diff --git a/tests/control_plane/adaptive_child_admission_characterization.json b/tests/control_plane/adaptive_child_admission_characterization.json index 576b41111d..d4f93893c7 100644 --- a/tests/control_plane/adaptive_child_admission_characterization.json +++ b/tests/control_plane/adaptive_child_admission_characterization.json @@ -38,19 +38,19 @@ "crossings": {} }, "scope_conflicts_capacity": { - "admission_json": "{\"schema_version\":\"task_orchestration_contract_v2\",\"mode\":\"adaptive\",\"coordinator_agent_id\":\"agent-a\",\"assignment_key\":\"f6db8a86012bc876c639625a88b608eab16d19204da3adda941c49de913e6c6a\",\"activation_required\":false,\"activation_allowed\":true,\"strategy_owner\":\"task_coordinator\",\"max_children\":1,\"primary_todo_id\":\"todo_primary\",\"child_brief_defaults\":{\"schema_version\":\"subagent_control_plane_handoff_v0\",\"parent_goal_id\":\"goal_synthetic\",\"authority_artifact\":\"quota_should_run.goal_boundary\",\"latest_state_ref\":\"quota_should_run.action_signature.source_hash\",\"quota_gate_snapshot\":\"admitted_by_task_orchestration_contract\",\"context_policy\":{\"selection_owner\":\"task_coordinator\",\"default\":\"fresh\",\"allowed\":[\"fresh\",\"forked_snapshot\",\"resume\"]},\"expected_output\":\"public_safe_evidence\",\"execution_policy\":{\"timeout\":\"bounded_by_host_turn\",\"cancel\":\"task_coordinator_or_host_timeout\"},\"child_guard_policy\":\"prevention_first_v0\",\"validation_policy\":\"child reports evidence; parent runs declared todo gate\",\"acceptance\":[\"report completed scope and evidence\",\"report validation result and residual risk\",\"do not write LoopX state or spend quota\"],\"writeback_spend_contract\":\"child reports evidence only; task coordinator accepts evidence, writes state, and spends once\"},\"eligible_child_lanes\":[{\"todo_id\":\"todo_child\",\"task_domain\":\"code\",\"execution_kind\":\"ephemeral_child\",\"child_brief\":{\"todo_id\":\"todo_child\",\"objective\":\"Inspect synthetic child\",\"action_kind\":\"inspect\",\"task_domain\":\"code\",\"required_capabilities\":[],\"task_repository\":null,\"required_write_scopes\":[\"tests/**\"],\"workspace_isolation\":\"independent_git_worktree\",\"continuation_policy\":null,\"target_key\":null}}],\"blocked_lanes\":[{\"todo_id\":\"todo_glob\",\"task_domain\":\"code\",\"reason_codes\":[\"write_scope_conflict\"],\"conflicts_with_todo_id\":\"todo_primary\"},{\"todo_id\":\"todo_docs\",\"task_domain\":\"code\",\"reason_codes\":[\"capacity_deferred\"]},{\"todo_id\":\"todo_overflow\",\"task_domain\":\"code\",\"reason_codes\":[\"capacity_deferred\"]}],\"writeback_owner\":\"task_coordinator\",\"coordinator_obligation\":\"choose whether admitted child lanes shorten the critical path; review returned evidence, then write accepted state/todos and spend once\"}", - "quota_fields_json": "{\"task_orchestration_contract\":{\"schema_version\":\"task_orchestration_contract_v2\",\"mode\":\"adaptive\",\"coordinator_agent_id\":\"agent-a\",\"assignment_key\":\"f6db8a86012bc876c639625a88b608eab16d19204da3adda941c49de913e6c6a\",\"activation_required\":false,\"activation_allowed\":true,\"strategy_owner\":\"task_coordinator\",\"max_children\":1,\"primary_todo_id\":\"todo_primary\",\"child_brief_defaults\":{\"schema_version\":\"subagent_control_plane_handoff_v0\",\"parent_goal_id\":\"goal_synthetic\",\"authority_artifact\":\"quota_should_run.goal_boundary\",\"latest_state_ref\":\"quota_should_run.action_signature.source_hash\",\"quota_gate_snapshot\":\"admitted_by_task_orchestration_contract\",\"context_policy\":{\"selection_owner\":\"task_coordinator\",\"default\":\"fresh\",\"allowed\":[\"fresh\",\"forked_snapshot\",\"resume\"]},\"expected_output\":\"public_safe_evidence\",\"execution_policy\":{\"timeout\":\"bounded_by_host_turn\",\"cancel\":\"task_coordinator_or_host_timeout\"},\"child_guard_policy\":\"prevention_first_v0\",\"validation_policy\":\"child reports evidence; parent runs declared todo gate\",\"acceptance\":[\"report completed scope and evidence\",\"report validation result and residual risk\",\"do not write LoopX state or spend quota\"],\"writeback_spend_contract\":\"child reports evidence only; task coordinator accepts evidence, writes state, and spends once\"},\"eligible_child_lanes\":[{\"todo_id\":\"todo_child\",\"task_domain\":\"code\",\"execution_kind\":\"ephemeral_child\",\"child_brief\":{\"todo_id\":\"todo_child\",\"objective\":\"Inspect synthetic child\",\"action_kind\":\"inspect\",\"task_domain\":\"code\",\"required_capabilities\":[],\"task_repository\":null,\"required_write_scopes\":[\"tests/**\"],\"workspace_isolation\":\"independent_git_worktree\",\"continuation_policy\":null,\"target_key\":null}}],\"blocked_lanes\":[{\"todo_id\":\"todo_glob\",\"task_domain\":\"code\",\"reason_codes\":[\"write_scope_conflict\"],\"conflicts_with_todo_id\":\"todo_primary\"},{\"todo_id\":\"todo_docs\",\"task_domain\":\"code\",\"reason_codes\":[\"capacity_deferred\"]},{\"todo_id\":\"todo_overflow\",\"task_domain\":\"code\",\"reason_codes\":[\"capacity_deferred\"]}],\"writeback_owner\":\"task_coordinator\",\"coordinator_obligation\":\"choose whether admitted child lanes shorten the critical path; review returned evidence, then write accepted state/todos and spend once\"},\"work_lane_contract\":{\"schema_version\":\"work_lane_contract_v1\",\"lane\":\"task_orchestration\",\"next_lane\":\"peer_evidence_review\",\"obligation\":\"coordinate_task_bundle\",\"must_attempt_work\":true,\"reason_codes\":[\"eligible_child_lanes\"],\"monitor_policy\":\"material_transition_only\",\"action\":\"choose whether admitted child lanes shorten the critical path; review returned evidence, then write accepted state/todos and spend once\",\"eligible_peer_lane_count\":1}}", - "markdown": "# LoopX Quota Should Run\n\n- projection: \ud83d\udd34 no projection envelope; freshness and coverage unknown\n- ok: `None`\n- goal_id: `None`\n- decision: `None`\n- should_run: `None`\n- normal_delivery_allowed: `None`\n- recovery_delivery_allowed: `None`\n- self_repair_allowed: `None`\n- effective_action: `None`\n- actionable_by_codex: `None`\n- state: `None`\n- waiting_on: `None`\n- status: `None`\n- task_orchestration: mode=adaptive activation_required=False lanes=1 blocked_lanes=3 writeback_owner=task_coordinator\n- task_orchestration_admission: activation_allowed=True\n- task_orchestration_blockers: capacity_deferred, write_scope_conflict\n- work_lane_contract: lane=task_orchestration next=peer_evidence_review obligation=coordinate_task_bundle must_attempt_work=True\n- work_lane_reason_codes: eligible_child_lanes\n- work_lane_monitor_policy: material_transition_only\n- work_lane_action: choose whether admitted child lanes shorten the critical path; review returned evidence, then write accepted state/todos and spend once", + "admission_json": "{\"schema_version\":\"task_orchestration_contract_v2\",\"mode\":\"adaptive\",\"coordinator_agent_id\":\"agent-a\",\"assignment_key\":\"f6db8a86012bc876c639625a88b608eab16d19204da3adda941c49de913e6c6a\",\"activation_required\":false,\"activation_allowed\":true,\"strategy_owner\":\"task_coordinator\",\"max_children\":1,\"primary_todo_id\":\"todo_primary\",\"child_brief_defaults\":{\"schema_version\":\"subagent_control_plane_handoff_v0\",\"parent_goal_id\":\"goal_synthetic\",\"authority_artifact\":\"quota_should_run.goal_boundary\",\"latest_state_ref\":\"quota_should_run.action_signature.source_hash\",\"quota_gate_snapshot\":\"admitted_by_task_orchestration_contract\",\"context_policy\":{\"selection_owner\":\"task_coordinator\",\"default\":\"fresh\",\"allowed\":[\"fresh\",\"forked_snapshot\",\"resume\"]},\"expected_output\":\"public_safe_evidence\",\"execution_policy\":{\"timeout\":\"bounded_by_host_turn\",\"cancel\":\"task_coordinator_or_host_timeout\"},\"child_guard_policy\":\"prevention_first_v0\",\"validation_policy\":\"child reports evidence; parent runs declared todo gate\",\"acceptance\":[\"report completed scope and evidence\",\"report validation result and residual risk\",\"do not write LoopX state or spend quota\"],\"writeback_spend_contract\":\"child reports evidence only; task coordinator accepts evidence, writes state, and spends once\"},\"eligible_child_lanes\":[{\"todo_id\":\"todo_glob\",\"task_domain\":\"code\",\"execution_kind\":\"ephemeral_child\",\"child_brief\":{\"todo_id\":\"todo_glob\",\"objective\":\"Inspect synthetic glob\",\"action_kind\":\"inspect\",\"task_domain\":\"code\",\"required_capabilities\":[],\"task_repository\":null,\"required_write_scopes\":[\"src/core/*.py\"],\"workspace_isolation\":\"independent_git_worktree\",\"continuation_policy\":null,\"target_key\":null}}],\"blocked_lanes\":[{\"todo_id\":\"todo_child\",\"task_domain\":\"code\",\"reason_codes\":[\"capacity_deferred\"]},{\"todo_id\":\"todo_docs\",\"task_domain\":\"code\",\"reason_codes\":[\"capacity_deferred\"]},{\"todo_id\":\"todo_overflow\",\"task_domain\":\"code\",\"reason_codes\":[\"capacity_deferred\"]}],\"writeback_owner\":\"task_coordinator\",\"coordinator_obligation\":\"choose whether admitted child lanes shorten the critical path; review returned evidence, then write accepted state/todos and spend once\"}", + "quota_fields_json": "{\"task_orchestration_contract\":{\"schema_version\":\"task_orchestration_contract_v2\",\"mode\":\"adaptive\",\"coordinator_agent_id\":\"agent-a\",\"assignment_key\":\"f6db8a86012bc876c639625a88b608eab16d19204da3adda941c49de913e6c6a\",\"activation_required\":false,\"activation_allowed\":true,\"strategy_owner\":\"task_coordinator\",\"max_children\":1,\"primary_todo_id\":\"todo_primary\",\"child_brief_defaults\":{\"schema_version\":\"subagent_control_plane_handoff_v0\",\"parent_goal_id\":\"goal_synthetic\",\"authority_artifact\":\"quota_should_run.goal_boundary\",\"latest_state_ref\":\"quota_should_run.action_signature.source_hash\",\"quota_gate_snapshot\":\"admitted_by_task_orchestration_contract\",\"context_policy\":{\"selection_owner\":\"task_coordinator\",\"default\":\"fresh\",\"allowed\":[\"fresh\",\"forked_snapshot\",\"resume\"]},\"expected_output\":\"public_safe_evidence\",\"execution_policy\":{\"timeout\":\"bounded_by_host_turn\",\"cancel\":\"task_coordinator_or_host_timeout\"},\"child_guard_policy\":\"prevention_first_v0\",\"validation_policy\":\"child reports evidence; parent runs declared todo gate\",\"acceptance\":[\"report completed scope and evidence\",\"report validation result and residual risk\",\"do not write LoopX state or spend quota\"],\"writeback_spend_contract\":\"child reports evidence only; task coordinator accepts evidence, writes state, and spends once\"},\"eligible_child_lanes\":[{\"todo_id\":\"todo_glob\",\"task_domain\":\"code\",\"execution_kind\":\"ephemeral_child\",\"child_brief\":{\"todo_id\":\"todo_glob\",\"objective\":\"Inspect synthetic glob\",\"action_kind\":\"inspect\",\"task_domain\":\"code\",\"required_capabilities\":[],\"task_repository\":null,\"required_write_scopes\":[\"src/core/*.py\"],\"workspace_isolation\":\"independent_git_worktree\",\"continuation_policy\":null,\"target_key\":null}}],\"blocked_lanes\":[{\"todo_id\":\"todo_child\",\"task_domain\":\"code\",\"reason_codes\":[\"capacity_deferred\"]},{\"todo_id\":\"todo_docs\",\"task_domain\":\"code\",\"reason_codes\":[\"capacity_deferred\"]},{\"todo_id\":\"todo_overflow\",\"task_domain\":\"code\",\"reason_codes\":[\"capacity_deferred\"]}],\"writeback_owner\":\"task_coordinator\",\"coordinator_obligation\":\"choose whether admitted child lanes shorten the critical path; review returned evidence, then write accepted state/todos and spend once\"},\"work_lane_contract\":{\"schema_version\":\"work_lane_contract_v1\",\"lane\":\"task_orchestration\",\"next_lane\":\"peer_evidence_review\",\"obligation\":\"coordinate_task_bundle\",\"must_attempt_work\":true,\"reason_codes\":[\"eligible_child_lanes\"],\"monitor_policy\":\"material_transition_only\",\"action\":\"choose whether admitted child lanes shorten the critical path; review returned evidence, then write accepted state/todos and spend once\",\"eligible_peer_lane_count\":1}}", + "markdown": "# LoopX Quota Should Run\n\n- projection: \ud83d\udd34 no projection envelope; freshness and coverage unknown\n- ok: `None`\n- goal_id: `None`\n- decision: `None`\n- should_run: `None`\n- normal_delivery_allowed: `None`\n- recovery_delivery_allowed: `None`\n- self_repair_allowed: `None`\n- effective_action: `None`\n- actionable_by_codex: `None`\n- state: `None`\n- waiting_on: `None`\n- status: `None`\n- task_orchestration: mode=adaptive activation_required=False lanes=1 blocked_lanes=3 writeback_owner=task_coordinator\n- task_orchestration_admission: activation_allowed=True\n- task_orchestration_blockers: capacity_deferred\n- work_lane_contract: lane=task_orchestration next=peer_evidence_review obligation=coordinate_task_bundle must_attempt_work=True\n- work_lane_reason_codes: eligible_child_lanes\n- work_lane_monitor_policy: material_transition_only\n- work_lane_action: choose whether admitted child lanes shorten the critical path; review returned evidence, then write accepted state/todos and spend once", "crossings": { - "quota.task_orchestration.write_scope_overlap": 2 + "quota.task_orchestration.admit": 1 } }, "first_conflict": { - "admission_json": "{\"schema_version\":\"task_orchestration_contract_v2\",\"mode\":\"adaptive\",\"coordinator_agent_id\":\"agent-a\",\"assignment_key\":\"06dc7351754663890b279c0df86637b3659906a8793c919f1fe310dd8ee94f51\",\"activation_required\":false,\"activation_allowed\":true,\"strategy_owner\":\"task_coordinator\",\"max_children\":2,\"primary_todo_id\":\"todo_primary\",\"child_brief_defaults\":{\"schema_version\":\"subagent_control_plane_handoff_v0\",\"parent_goal_id\":\"goal_synthetic\",\"authority_artifact\":\"quota_should_run.goal_boundary\",\"latest_state_ref\":\"quota_should_run.action_signature.source_hash\",\"quota_gate_snapshot\":\"admitted_by_task_orchestration_contract\",\"context_policy\":{\"selection_owner\":\"task_coordinator\",\"default\":\"fresh\",\"allowed\":[\"fresh\",\"forked_snapshot\",\"resume\"]},\"expected_output\":\"public_safe_evidence\",\"execution_policy\":{\"timeout\":\"bounded_by_host_turn\",\"cancel\":\"task_coordinator_or_host_timeout\"},\"child_guard_policy\":\"prevention_first_v0\",\"validation_policy\":\"child reports evidence; parent runs declared todo gate\",\"acceptance\":[\"report completed scope and evidence\",\"report validation result and residual risk\",\"do not write LoopX state or spend quota\"],\"writeback_spend_contract\":\"child reports evidence only; task coordinator accepts evidence, writes state, and spends once\"},\"eligible_child_lanes\":[{\"todo_id\":\"todo_child\",\"task_domain\":\"code\",\"execution_kind\":\"ephemeral_child\",\"child_brief\":{\"todo_id\":\"todo_child\",\"objective\":\"Inspect synthetic child\",\"action_kind\":\"inspect\",\"task_domain\":\"code\",\"required_capabilities\":[],\"task_repository\":null,\"required_write_scopes\":[\"src/b/**\"],\"workspace_isolation\":\"independent_git_worktree\",\"continuation_policy\":null,\"target_key\":null}}],\"blocked_lanes\":[{\"todo_id\":\"todo_both\",\"task_domain\":\"code\",\"reason_codes\":[\"write_scope_conflict\"],\"conflicts_with_todo_id\":\"todo_primary\"}],\"writeback_owner\":\"task_coordinator\",\"coordinator_obligation\":\"choose whether admitted child lanes shorten the critical path; review returned evidence, then write accepted state/todos and spend once\"}", - "quota_fields_json": "{\"task_orchestration_contract\":{\"schema_version\":\"task_orchestration_contract_v2\",\"mode\":\"adaptive\",\"coordinator_agent_id\":\"agent-a\",\"assignment_key\":\"06dc7351754663890b279c0df86637b3659906a8793c919f1fe310dd8ee94f51\",\"activation_required\":false,\"activation_allowed\":true,\"strategy_owner\":\"task_coordinator\",\"max_children\":2,\"primary_todo_id\":\"todo_primary\",\"child_brief_defaults\":{\"schema_version\":\"subagent_control_plane_handoff_v0\",\"parent_goal_id\":\"goal_synthetic\",\"authority_artifact\":\"quota_should_run.goal_boundary\",\"latest_state_ref\":\"quota_should_run.action_signature.source_hash\",\"quota_gate_snapshot\":\"admitted_by_task_orchestration_contract\",\"context_policy\":{\"selection_owner\":\"task_coordinator\",\"default\":\"fresh\",\"allowed\":[\"fresh\",\"forked_snapshot\",\"resume\"]},\"expected_output\":\"public_safe_evidence\",\"execution_policy\":{\"timeout\":\"bounded_by_host_turn\",\"cancel\":\"task_coordinator_or_host_timeout\"},\"child_guard_policy\":\"prevention_first_v0\",\"validation_policy\":\"child reports evidence; parent runs declared todo gate\",\"acceptance\":[\"report completed scope and evidence\",\"report validation result and residual risk\",\"do not write LoopX state or spend quota\"],\"writeback_spend_contract\":\"child reports evidence only; task coordinator accepts evidence, writes state, and spends once\"},\"eligible_child_lanes\":[{\"todo_id\":\"todo_child\",\"task_domain\":\"code\",\"execution_kind\":\"ephemeral_child\",\"child_brief\":{\"todo_id\":\"todo_child\",\"objective\":\"Inspect synthetic child\",\"action_kind\":\"inspect\",\"task_domain\":\"code\",\"required_capabilities\":[],\"task_repository\":null,\"required_write_scopes\":[\"src/b/**\"],\"workspace_isolation\":\"independent_git_worktree\",\"continuation_policy\":null,\"target_key\":null}}],\"blocked_lanes\":[{\"todo_id\":\"todo_both\",\"task_domain\":\"code\",\"reason_codes\":[\"write_scope_conflict\"],\"conflicts_with_todo_id\":\"todo_primary\"}],\"writeback_owner\":\"task_coordinator\",\"coordinator_obligation\":\"choose whether admitted child lanes shorten the critical path; review returned evidence, then write accepted state/todos and spend once\"},\"work_lane_contract\":{\"schema_version\":\"work_lane_contract_v1\",\"lane\":\"task_orchestration\",\"next_lane\":\"peer_evidence_review\",\"obligation\":\"coordinate_task_bundle\",\"must_attempt_work\":true,\"reason_codes\":[\"eligible_child_lanes\"],\"monitor_policy\":\"material_transition_only\",\"action\":\"choose whether admitted child lanes shorten the critical path; review returned evidence, then write accepted state/todos and spend once\",\"eligible_peer_lane_count\":1}}", - "markdown": "# LoopX Quota Should Run\n\n- projection: \ud83d\udd34 no projection envelope; freshness and coverage unknown\n- ok: `None`\n- goal_id: `None`\n- decision: `None`\n- should_run: `None`\n- normal_delivery_allowed: `None`\n- recovery_delivery_allowed: `None`\n- self_repair_allowed: `None`\n- effective_action: `None`\n- actionable_by_codex: `None`\n- state: `None`\n- waiting_on: `None`\n- status: `None`\n- task_orchestration: mode=adaptive activation_required=False lanes=1 blocked_lanes=1 writeback_owner=task_coordinator\n- task_orchestration_admission: activation_allowed=True\n- task_orchestration_blockers: write_scope_conflict\n- work_lane_contract: lane=task_orchestration next=peer_evidence_review obligation=coordinate_task_bundle must_attempt_work=True\n- work_lane_reason_codes: eligible_child_lanes\n- work_lane_monitor_policy: material_transition_only\n- work_lane_action: choose whether admitted child lanes shorten the critical path; review returned evidence, then write accepted state/todos and spend once", + "admission_json": "{\"schema_version\":\"task_orchestration_contract_v2\",\"mode\":\"adaptive\",\"coordinator_agent_id\":\"agent-a\",\"assignment_key\":\"06dc7351754663890b279c0df86637b3659906a8793c919f1fe310dd8ee94f51\",\"activation_required\":false,\"activation_allowed\":true,\"strategy_owner\":\"task_coordinator\",\"max_children\":2,\"primary_todo_id\":\"todo_primary\",\"child_brief_defaults\":{\"schema_version\":\"subagent_control_plane_handoff_v0\",\"parent_goal_id\":\"goal_synthetic\",\"authority_artifact\":\"quota_should_run.goal_boundary\",\"latest_state_ref\":\"quota_should_run.action_signature.source_hash\",\"quota_gate_snapshot\":\"admitted_by_task_orchestration_contract\",\"context_policy\":{\"selection_owner\":\"task_coordinator\",\"default\":\"fresh\",\"allowed\":[\"fresh\",\"forked_snapshot\",\"resume\"]},\"expected_output\":\"public_safe_evidence\",\"execution_policy\":{\"timeout\":\"bounded_by_host_turn\",\"cancel\":\"task_coordinator_or_host_timeout\"},\"child_guard_policy\":\"prevention_first_v0\",\"validation_policy\":\"child reports evidence; parent runs declared todo gate\",\"acceptance\":[\"report completed scope and evidence\",\"report validation result and residual risk\",\"do not write LoopX state or spend quota\"],\"writeback_spend_contract\":\"child reports evidence only; task coordinator accepts evidence, writes state, and spends once\"},\"eligible_child_lanes\":[{\"todo_id\":\"todo_child\",\"task_domain\":\"code\",\"execution_kind\":\"ephemeral_child\",\"child_brief\":{\"todo_id\":\"todo_child\",\"objective\":\"Inspect synthetic child\",\"action_kind\":\"inspect\",\"task_domain\":\"code\",\"required_capabilities\":[],\"task_repository\":null,\"required_write_scopes\":[\"src/b/**\"],\"workspace_isolation\":\"independent_git_worktree\",\"continuation_policy\":null,\"target_key\":null}},{\"todo_id\":\"todo_both\",\"task_domain\":\"code\",\"execution_kind\":\"ephemeral_child\",\"child_brief\":{\"todo_id\":\"todo_both\",\"objective\":\"Inspect synthetic both\",\"action_kind\":\"inspect\",\"task_domain\":\"code\",\"required_capabilities\":[],\"task_repository\":null,\"required_write_scopes\":[\"src/**\"],\"workspace_isolation\":\"independent_git_worktree\",\"continuation_policy\":null,\"target_key\":null}}],\"blocked_lanes\":[],\"writeback_owner\":\"task_coordinator\",\"coordinator_obligation\":\"choose whether admitted child lanes shorten the critical path; review returned evidence, then write accepted state/todos and spend once\"}", + "quota_fields_json": "{\"task_orchestration_contract\":{\"schema_version\":\"task_orchestration_contract_v2\",\"mode\":\"adaptive\",\"coordinator_agent_id\":\"agent-a\",\"assignment_key\":\"06dc7351754663890b279c0df86637b3659906a8793c919f1fe310dd8ee94f51\",\"activation_required\":false,\"activation_allowed\":true,\"strategy_owner\":\"task_coordinator\",\"max_children\":2,\"primary_todo_id\":\"todo_primary\",\"child_brief_defaults\":{\"schema_version\":\"subagent_control_plane_handoff_v0\",\"parent_goal_id\":\"goal_synthetic\",\"authority_artifact\":\"quota_should_run.goal_boundary\",\"latest_state_ref\":\"quota_should_run.action_signature.source_hash\",\"quota_gate_snapshot\":\"admitted_by_task_orchestration_contract\",\"context_policy\":{\"selection_owner\":\"task_coordinator\",\"default\":\"fresh\",\"allowed\":[\"fresh\",\"forked_snapshot\",\"resume\"]},\"expected_output\":\"public_safe_evidence\",\"execution_policy\":{\"timeout\":\"bounded_by_host_turn\",\"cancel\":\"task_coordinator_or_host_timeout\"},\"child_guard_policy\":\"prevention_first_v0\",\"validation_policy\":\"child reports evidence; parent runs declared todo gate\",\"acceptance\":[\"report completed scope and evidence\",\"report validation result and residual risk\",\"do not write LoopX state or spend quota\"],\"writeback_spend_contract\":\"child reports evidence only; task coordinator accepts evidence, writes state, and spends once\"},\"eligible_child_lanes\":[{\"todo_id\":\"todo_child\",\"task_domain\":\"code\",\"execution_kind\":\"ephemeral_child\",\"child_brief\":{\"todo_id\":\"todo_child\",\"objective\":\"Inspect synthetic child\",\"action_kind\":\"inspect\",\"task_domain\":\"code\",\"required_capabilities\":[],\"task_repository\":null,\"required_write_scopes\":[\"src/b/**\"],\"workspace_isolation\":\"independent_git_worktree\",\"continuation_policy\":null,\"target_key\":null}},{\"todo_id\":\"todo_both\",\"task_domain\":\"code\",\"execution_kind\":\"ephemeral_child\",\"child_brief\":{\"todo_id\":\"todo_both\",\"objective\":\"Inspect synthetic both\",\"action_kind\":\"inspect\",\"task_domain\":\"code\",\"required_capabilities\":[],\"task_repository\":null,\"required_write_scopes\":[\"src/**\"],\"workspace_isolation\":\"independent_git_worktree\",\"continuation_policy\":null,\"target_key\":null}}],\"blocked_lanes\":[],\"writeback_owner\":\"task_coordinator\",\"coordinator_obligation\":\"choose whether admitted child lanes shorten the critical path; review returned evidence, then write accepted state/todos and spend once\"},\"work_lane_contract\":{\"schema_version\":\"work_lane_contract_v1\",\"lane\":\"task_orchestration\",\"next_lane\":\"peer_evidence_review\",\"obligation\":\"coordinate_task_bundle\",\"must_attempt_work\":true,\"reason_codes\":[\"eligible_child_lanes\"],\"monitor_policy\":\"material_transition_only\",\"action\":\"choose whether admitted child lanes shorten the critical path; review returned evidence, then write accepted state/todos and spend once\",\"eligible_peer_lane_count\":2}}", + "markdown": "# LoopX Quota Should Run\n\n- projection: \ud83d\udd34 no projection envelope; freshness and coverage unknown\n- ok: `None`\n- goal_id: `None`\n- decision: `None`\n- should_run: `None`\n- normal_delivery_allowed: `None`\n- recovery_delivery_allowed: `None`\n- self_repair_allowed: `None`\n- effective_action: `None`\n- actionable_by_codex: `None`\n- state: `None`\n- waiting_on: `None`\n- status: `None`\n- task_orchestration: mode=adaptive activation_required=False lanes=2 blocked_lanes=0 writeback_owner=task_coordinator\n- task_orchestration_admission: activation_allowed=True\n- work_lane_contract: lane=task_orchestration next=peer_evidence_review obligation=coordinate_task_bundle must_attempt_work=True\n- work_lane_reason_codes: eligible_child_lanes\n- work_lane_monitor_policy: material_transition_only\n- work_lane_action: choose whether admitted child lanes shorten the critical path; review returned evidence, then write accepted state/todos and spend once", "crossings": { - "quota.task_orchestration.write_scope_overlap": 2 + "quota.task_orchestration.admit": 1 } }, "case_sensitive_scope": { diff --git a/tests/control_plane/test_canonical_claim_execution_proof.py b/tests/control_plane/test_canonical_claim_execution_proof.py index 3b5f321996..a915922b5f 100644 --- a/tests/control_plane/test_canonical_claim_execution_proof.py +++ b/tests/control_plane/test_canonical_claim_execution_proof.py @@ -48,7 +48,7 @@ def cli(command, *args, expected_exit=0): first = cli(["todo", "claim"], *request) assert first["status"] == "applied" assert first["lease"]["version"] == first["lease"]["lease_epoch"] == 1 - assert first["lease"]["write_scopes"] == ["src/**"] + assert first["lease"]["write_scopes"] == [] renewed = cli(["task-lease", "renew"], *lease_args, "--expected-version", "1", "--ttl-seconds", "600") replay = cli(["todo", "claim"], *request) assert replay["status"] == "replayed" diff --git a/tests/control_plane/test_canonical_lease_scopes.py b/tests/control_plane/test_canonical_lease_scopes.py index 4e3328b459..e56b7eeee8 100644 --- a/tests/control_plane/test_canonical_lease_scopes.py +++ b/tests/control_plane/test_canonical_lease_scopes.py @@ -95,7 +95,7 @@ def test_retained_alias_declaration_can_be_claimed(scope_goal): "--agent-id", "agent-a", "--claim-operation-id", "alias-claim", "--task-lease-idempotency-key", "alias-claim", "--task-lease-expected-version", "0") assert claimed["ok"] - assert cli("task-lease", "inspect", "--todo-id", "todo_scope_a")["lease"]["write_scopes"] == ["src/main.ts"] + assert cli("task-lease", "inspect", "--todo-id", "todo_scope_a")["lease"]["write_scopes"] == [] assert cli("todo", "list", "--todo-id", "todo_scope_a")["todo"]["required_write_scopes"] == ALIASES @@ -109,11 +109,11 @@ def test_authored_alias_declaration_can_be_claimed_without_revision(scope_goal): "--claim-operation-id", "authored-claim", "--task-lease-idempotency-key", "authored-claim", "--task-lease-expected-version", "0") assert claimed["ok"] - assert cli("task-lease", "inspect", "--todo-id", todo_id)["lease"]["write_scopes"] == ["src/main.ts"] + assert cli("task-lease", "inspect", "--todo-id", todo_id)["lease"]["write_scopes"] == [] assert cli("todo", "list", "--todo-id", todo_id)["todo"]["required_write_scopes"] == ALIASES -def test_case_aliases_remain_exclusive_write_scopes(scope_goal): +def test_case_aliases_admit_separate_todo_leases(scope_goal): cli, current = scope_goal acquire = ("task-lease", "acquire", "--todo-id", "todo_scope_a", "--owner", "agent-a", "--idempotency-key", "case-a", "--expected-version", "0", "--write-scope", "src/Main.ts") @@ -121,28 +121,22 @@ def test_case_aliases_remain_exclusive_write_scopes(scope_goal): assert cli(*acquire)["idempotent"] changed = cli(*acquire[:-1], "src/main.ts", expected_exit=1) assert changed["error_code"] == "coordination_operation_identity_mismatch" - before = current() - rejected = cli("task-lease", "acquire", "--todo-id", "todo_scope_b", "--owner", "agent-b", - "--idempotency-key", "case-b", "--expected-version", "0", "--write-scope", "src/main.ts", - expected_exit=1) - assert rejected["error_code"] == "write_scope_conflict" - assert current() == before + admitted = cli("task-lease", "acquire", "--todo-id", "todo_scope_b", "--owner", "agent-b", + "--idempotency-key", "case-b", "--expected-version", "0", "--write-scope", "src/main.ts") + assert admitted["acquired"] and admitted["lease"]["write_scopes"] == ["src/main.ts"] @pytest.mark.parametrize("first_scope,second_scope", [ ("src/**/*.ts", "src/main.ts"), ("src/main.ts", "src/**/*.ts"), ]) -def test_recursive_glob_conflicts_with_direct_child_scope(scope_goal, first_scope, second_scope): - cli, current = scope_goal +def test_recursive_glob_and_child_scope_admit_separate_todo_leases(scope_goal, first_scope, second_scope): + cli, _ = scope_goal cli("task-lease", "acquire", "--todo-id", "todo_scope_a", "--owner", "agent-a", "--idempotency-key", "recursive-a", "--expected-version", "0", "--write-scope", first_scope) - before = current() - rejected = cli("task-lease", "acquire", "--todo-id", "todo_scope_b", "--owner", "agent-b", - "--idempotency-key", "recursive-b", "--expected-version", "0", "--write-scope", second_scope, - expected_exit=1) - assert rejected["error_code"] == "write_scope_conflict" - assert current() == before + admitted = cli("task-lease", "acquire", "--todo-id", "todo_scope_b", "--owner", "agent-b", + "--idempotency-key", "recursive-b", "--expected-version", "0", "--write-scope", second_scope) + assert admitted["acquired"] and admitted["lease"]["write_scopes"] == [second_scope] @pytest.mark.parametrize("first_scope,second_scope", [ @@ -163,17 +157,14 @@ def test_recursive_glob_conflicts_with_direct_child_scope(scope_goal, first_scop ("src/[!Σ]S.ts", "src/SSS.ts"), ("src/SSS.ts", "src/[!Σ]S.ts"), ]) -def test_unicode_case_aliases_remain_exclusive_write_scopes(scope_goal, first_scope, second_scope): - cli, current = scope_goal +def test_unicode_case_aliases_admit_separate_todo_leases(scope_goal, first_scope, second_scope): + cli, _ = scope_goal acquired = cli("task-lease", "acquire", "--todo-id", "todo_scope_a", "--owner", "agent-a", "--idempotency-key", "unicode-a", "--expected-version", "0", "--write-scope", first_scope) assert acquired["lease"]["write_scopes"] == [first_scope] - before = current() - rejected = cli("task-lease", "acquire", "--todo-id", "todo_scope_b", "--owner", "agent-b", - "--idempotency-key", "unicode-b", "--expected-version", "0", "--write-scope", second_scope, - expected_exit=1) - assert rejected["error_code"] == "write_scope_conflict" - assert current() == before + admitted = cli("task-lease", "acquire", "--todo-id", "todo_scope_b", "--owner", "agent-b", + "--idempotency-key", "unicode-b", "--expected-version", "0", "--write-scope", second_scope) + assert admitted["acquired"] and admitted["lease"]["write_scopes"] == [second_scope] @pytest.mark.parametrize("first_scope,second_scope", [ @@ -193,8 +184,8 @@ def test_unicode_case_aliases_remain_exclusive_write_scopes(scope_goal, first_sc ("src/[!Σ]S.ts", "src/SSS.ts"), ("src/SSS.ts", "src/[!Σ]S.ts"), ]) -def test_unicode_case_aliases_conflict_at_atomic_todo_claim(scope_goal, first_scope, second_scope): - cli, current = scope_goal +def test_unicode_case_aliases_claim_independently_at_todo_claim(scope_goal, first_scope, second_scope): + cli, _ = scope_goal repository = "git:github.com/example/project" def add_todo(label, scope): @@ -207,15 +198,14 @@ def add_todo(label, scope): "--claim-operation-id", "unicode-claim-a", "--task-lease-idempotency-key", "unicode-claim-a", "--task-lease-expected-version", "0") assert claimed["ok"] - assert cli("task-lease", "inspect", "--todo-id", first)["lease"]["write_scopes"] == [first_scope] + assert cli("task-lease", "inspect", "--todo-id", first)["lease"]["write_scopes"] == [] second = add_todo("b", second_scope) - before = current() - rejected = cli("todo", "claim", "--todo-id", second, "--claimed-by", "agent-b", "--agent-id", "agent-b", + second_claim = cli("todo", "claim", "--todo-id", second, "--claimed-by", "agent-b", "--agent-id", "agent-b", "--claim-operation-id", "unicode-claim-b", "--task-lease-idempotency-key", "unicode-claim-b", - "--task-lease-expected-version", "0", expected_exit=1) - assert rejected["error_code"] == "write_scope_conflict" - assert current() == before + "--task-lease-expected-version", "0") + assert second_claim["ok"] + assert cli("task-lease", "inspect", "--todo-id", second)["lease"]["write_scopes"] == [] @pytest.mark.parametrize("scope,target", [ @@ -226,23 +216,22 @@ def add_todo(label, scope): ("src/[ς].ts", "src/Σ.ts"), ("src/[ß].ts", "src/SS.ts"), ]) -def test_glob_class_members_keep_exclusive_scope_coverage(scope_goal, scope, target): - cli, current = scope_goal +def test_glob_class_members_keep_stored_spelling_without_lease_conflict(scope_goal, scope, target): + cli, _ = scope_goal first = cli("task-lease", "acquire", "--todo-id", "todo_scope_a", "--owner", "agent-a", "--idempotency-key", "class-a", "--write-scope", scope, "--expected-version", "0") assert first["lease"]["write_scopes"] == [scope] - before = current() - rejected = cli("task-lease", "acquire", "--todo-id", "todo_scope_b", "--owner", "agent-b", - "--idempotency-key", "class-b", "--write-scope", target, "--expected-version", "0", expected_exit=1) - assert rejected["error_code"] == "write_scope_conflict" and current() == before + second = cli("task-lease", "acquire", "--todo-id", "todo_scope_b", "--owner", "agent-b", + "--idempotency-key", "class-b", "--write-scope", target, "--expected-version", "0") + assert second["acquired"] and second["lease"]["write_scopes"] == [target] @pytest.mark.parametrize("scope,target", [ ("src/[ς].ts", "src/Σ.ts"), ("src/[ß].ts", "src/SS.ts"), ]) -def test_unicode_glob_class_aliases_conflict_at_atomic_todo_claim(scope_goal, scope, target): - cli, current = scope_goal +def test_unicode_glob_class_aliases_claim_independently_at_todo_claim(scope_goal, scope, target): + cli, _ = scope_goal repository = "git:github.com/example/project" def add_todo(label, write_scope): @@ -257,16 +246,15 @@ def add_todo(label, write_scope): "--task-lease-idempotency-key", "unicode-class-claim-a", "--task-lease-expected-version", "0") assert claimed["ok"] - assert cli("task-lease", "inspect", "--todo-id", first)["lease"]["write_scopes"] == [scope] + assert cli("task-lease", "inspect", "--todo-id", first)["lease"]["write_scopes"] == [] second = add_todo("b", target) - before = current() - rejected = cli("todo", "claim", "--todo-id", second, "--claimed-by", "agent-b", "--agent-id", "agent-b", + second_claim = cli("todo", "claim", "--todo-id", second, "--claimed-by", "agent-b", "--agent-id", "agent-b", "--claim-operation-id", "unicode-class-claim-b", "--task-lease-idempotency-key", "unicode-class-claim-b", - "--task-lease-expected-version", "0", expected_exit=1) - assert rejected["error_code"] == "write_scope_conflict" - assert current() == before + "--task-lease-expected-version", "0") + assert second_claim["ok"] + assert cli("task-lease", "inspect", "--todo-id", second)["lease"]["write_scopes"] == [] def test_case_folded_negated_glob_class_excludes_case_variant(scope_goal): @@ -345,11 +333,13 @@ def acquire(todo_id, label, scope, expected_exit=0): before_retry = current() acquire(first, "a", first_scope) assert current() == before_retry - assert cli("task-lease", "inspect", "--todo-id", first)["lease"]["write_scopes"] == [first_scope] + assert cli("task-lease", "inspect", "--todo-id", first)["lease"]["write_scopes"] == ( + [first_scope] if entrypoint == "acquire" else [] + ) before = current() - result = acquire(second, "b", second_scope, expected_exit=1 if conflict else 0) - if conflict: - assert result["error_code"] == "write_scope_conflict" - assert current() == before - else: - assert cli("task-lease", "inspect", "--todo-id", second)["lease"]["write_scopes"] == [second_scope] + result = acquire(second, "b", second_scope, expected_exit=0) + assert result["ok"] + assert cli("task-lease", "inspect", "--todo-id", second)["lease"]["write_scopes"] == ( + [second_scope] if entrypoint == "acquire" else [] + ) + assert current()["todos"] == before["todos"] or entrypoint == "claim" diff --git a/tests/control_plane/test_context_first_read.py b/tests/control_plane/test_context_first_read.py index c233c53f65..528e419ea3 100644 --- a/tests/control_plane/test_context_first_read.py +++ b/tests/control_plane/test_context_first_read.py @@ -315,16 +315,11 @@ def test_initial_read_keeps_supporting_index_obligations_and_recovers_its_full_l @pytest.mark.parametrize("workspace_repair", [True, False], ids=["needs-worktree", "independent-worktree"]) -def test_unbound_candidate_scopes_are_only_expanded_on_request(tmp_path, monkeypatch, decision, workspace_repair): +def test_cba_active_write_scope_stays_on_demand_while_summary_counts_stay_on_page_zero(tmp_path, monkeypatch, decision, workspace_repair): from test_codex_context_lifecycle import setup setup(tmp_path, monkeypatch) - long_scopes = [f"src/area-{index:03d}/implementation/entrypoints/**" for index in range(355)] - short_scope = ["docs/reference/**"] - candidates = [ - {"todo_id": "todo_current", "text": "Repair the source entrypoint.", "required_write_scopes": long_scopes}, - {"todo_id": "todo_alternative", "text": "Verify the documentation.", "required_write_scopes": short_scope}, - ] + active_scopes = [f"src/area-{index:03d}/implementation/entrypoints/**" for index in range(60)] turn = "workspace-selection-fixture" mode = "agent_workspace_repair" if workspace_repair else "normal_run" obligation = "agent_workspace_guard" if workspace_repair else "work_lane_contract" @@ -335,11 +330,19 @@ def test_unbound_candidate_scopes_are_only_expanded_on_request(tmp_path, monkeyp heartbeat_receipt={"turn_instance_id": turn, "settlement_binding_owed": True}, execution_obligation={"kind": mode if workspace_repair else obligation, "contract": obligation, "must_attempt_work": True, "delivery_allowed": False}) - decision["selected_todo"].update(schema_version="quota_selected_todo_v0", required_write_scopes=long_scopes) + decision["selected_todo"].pop("required_write_scopes", None) + decision["goal_boundary"]["checkpointed_boundary_authority"] = { + "schema_version": "checkpointed_boundary_authority_v0", + "active_count": 60, + "inactive_count": 2, + "active_write_scope": active_scopes, + "entries": [{"status": "active", "decision": "approve", "write_scope": [s]} for s in active_scopes], + } contract = decision["interaction_contract"] contract["mode"] = mode contract["agent_channel"].update(delivery_allowed=False, must_attempt=True, - work_context={"instruction": "Relocate before delivering.", "sources": []}) + work_context={"instruction": "Relocate before delivering.", + "sources": [{"source": "goal_state", "content": {"text": "Keep goal context readable. " * 250}}]}) contract["cli_channel"] = { "selection_required": True, "next_cli_actions": [], "spend_allowed_now": False, "spend_after_validation": False, @@ -350,6 +353,10 @@ def test_unbound_candidate_scopes_are_only_expanded_on_request(tmp_path, monkeyp "candidate_discovery_args": "todo list --goal-id fixture --status open"}, } policy = {"mode": "explicit_turn_binding", "decision_owner": "agent", "requires_explicit_turn_binding": True} + candidates = [ + {"todo_id": "todo_current", "text": "Repair the source entrypoint."}, + {"todo_id": "todo_alternative", "text": "Verify the documentation."}, + ] decision["action_portfolio"] = {"selection_policy": policy, "suggested_actions": candidates} capture = tmp_path / "decision.json" original = json.dumps(decision).encode() @@ -370,32 +377,28 @@ def test_unbound_candidate_scopes_are_only_expanded_on_request(tmp_path, monkeyp assert opening["/goal_boundary/stop_condition"] == decision["goal_boundary"]["stop_condition"] assert opening["/execution_obligation"] == decision["execution_obligation"] assert opening["/interaction_contract/agent_channel/delivery_allowed"] is False - selection = opening["/interaction_contract/cli_channel/selection_command"] - original_selection = contract["cli_channel"]["selection_command"] - assert selection["candidate_discovery_args"] == original_selection["candidate_discovery_args"] - command_words = shlex.split(selection["command_args_template"]) - original_words = shlex.split(original_selection["command_args_template"]) - assert command_words[:len(original_words)] == original_words - assert opening["/interaction_contract/cli_channel/spend_allowed_now"] is False assert opening["/action_portfolio/selection_policy"] == policy - projected = opening["/action_portfolio/suggested_actions"] - assert projected == [{key: value for key, value in candidates[0].items() if key != "required_write_scopes"}, - candidates[1]] - assert "required_write_scopes" not in opening["/selected_todo"] - pointer = "/action_portfolio/suggested_actions/0/required_write_scopes" - recommended_scope = "/selected_todo/required_write_scopes" - assert pointer in opening["/context_details/instruction"] - assert recommended_scope in opening["/context_details/instruction"] - assert page["total_bytes"] < len(json.dumps(long_scopes).encode()) - template = opening["/context_details/command_template"] - _, detail = read_selection(template.replace("", pointer) + f" --select {recommended_scope}") - assert detail[pointer] == detail[recommended_scope] == long_scopes + assert opening["/action_portfolio/suggested_actions"] == candidates + assert "/selected_todo" not in opening + cba_prefix = "/goal_boundary/checkpointed_boundary_authority" + assert opening[cba_prefix + "/active_count"] == 60 + assert opening[cba_prefix + "/inactive_count"] == 2 + assert cba_prefix + "/active_write_scope" not in opening + assert cba_prefix + "/entries" not in opening + assert page["total_bytes"] < len(json.dumps(active_scopes).encode()) + 5000 + assert "remaining_read_command" in view + _, remaining = read_selection(view["remaining_read_command"]) + assert remaining[cba_prefix + "/entries"] == decision["goal_boundary"]["checkpointed_boundary_authority"]["entries"] + assert remaining.get(cba_prefix + "/active_write_scope") == active_scopes or ( + "/context_details/command_template" in remaining and + read_selection(remaining["/context_details/command_template"].replace("", cba_prefix + "/active_write_scope"))[1][cba_prefix + "/active_write_scope"] == active_scopes + ) assert capture.read_bytes() == original assert not registry.exists() and not runtime.exists() @pytest.mark.parametrize("provider", ["file", "sqlite"]) -def test_claim_preparation_keeps_requested_write_scopes_on_demand(tmp_path, monkeypatch, provider): +def test_claim_preparation_keeps_required_write_scopes_off_quota_surface(tmp_path, monkeypatch, provider): from test_quota_settlement_cli import ( AGENT_ID, GOAL_ID, TODO_ID, _configure_repository_write_todo, _heartbeat_receipt_count, _initialize_fixture_authority, _initialize_git_checkout, _run_cli, _spend_run_count, _write_fixture, @@ -440,20 +443,17 @@ def cli(*args): preparation = channel["execution_preparation"] assert preparation["state"] == "claim_required" and preparation["delivery_allowed"] is False assert preparation["claim"]["host_execution_allowed"] - assert raw["selected_todo"]["required_write_scopes"] == scopes + assert "required_write_scopes" not in raw["selected_todo"] + assert cli("todo", "list", "--goal-id", GOAL_ID, "--todo-id", TODO_ID)["todo"]["required_write_scopes"] == scopes view = cli(*guard, *native) - page, opening = read_selection(view["first_read_command"]) + _, opening = read_selection(view["first_read_command"]) state_pointer = "/interaction_contract/cli_channel/execution_preparation" - scope_pointer = "/selected_todo/required_write_scopes" assert opening[state_pointer] == preparation assert opening["/normal_delivery_allowed"] is False assert opening["/interaction_contract/cli_channel/spend_after_validation"] is False assert opening["/selected_todo"]["todo_id"] == TODO_ID - assert "required_write_scopes" not in opening["/selected_todo"], page["total_bytes"] - assert scope_pointer in opening["/context_details/instruction"] - _, detail = read_selection(opening["/context_details/command_template"].replace("", scope_pointer)) - assert detail[scope_pointer] == scopes + assert "required_write_scopes" not in opening["/selected_todo"] assert _heartbeat_receipt_count(runtime, turn) == 1 claim = cli(*preparation["claim"]["cli_args"]) @@ -461,7 +461,7 @@ def cli(*args): ready = cli(*guard, *native) _, opening = read_selection(ready["first_read_command"]) assert opening["/normal_delivery_allowed"] is True and opening[state_pointer]["state"] == "ready" - assert opening["/selected_todo"]["required_write_scopes"] == scopes + assert "required_write_scopes" not in opening["/selected_todo"] assert opening["/heartbeat_receipt"]["settlement_identity"] == raw["heartbeat_receipt"]["settlement_identity"] assert _spend_run_count(runtime) == 0 @@ -942,13 +942,19 @@ def read(command): raw = path.read_bytes() source = json.loads(raw) if requested_scopes: - assert source["selected_todo"]["required_write_scopes"] == requested_scopes + assert "required_write_scopes" not in source["selected_todo"] pages, opening = read(view["first_read_command"]) - if page_budget == 16000: - # A paged body is not itself a reason to add a second reader. The - # ordinary first page fits the scope, selected Todo and read controls. - assert "remaining_read_command" not in view and len(pages) > 1 - assert opening["/goal_boundary/write_scope"] == scopes + if page_budget == 16000 or (warm and requested_scopes and "remaining_read_command" not in view): + # A self-contained or warm-reused body whose first page already carries the + # opening controls needs no second reader while keeping the selected Todo and controls. + assert "remaining_read_command" not in view + if page_budget == 16000: + assert len(pages) > 1 + assert opening["/goal_boundary/write_scope"] == scopes + else: + assert len(pages) >= 1 + assert set(pages[0]["previously_delivered_fields"]) == {body_pointer, "/goal_boundary/write_scope"} + assert "/goal_boundary/write_scope" not in opening assert opening["/selected_todo/todo_id"] == TODO_ID assert TODO_ID in pages[0]["content"] and "required_reads" in pages[0]["content"] assert "execution_preparation" in pages[0]["content"] @@ -978,20 +984,19 @@ def read(command): if checkpoint_count: assert opening[authority + "/active_count"] == checkpoint_count // 2 assert opening[authority + "/inactive_count"] == checkpoint_count // 2 - assert opening[authority + "/active_write_scope"] == [scopes[0]] + assert authority + "/active_write_scope" not in opening assert authority + "/entries" not in opening if warm: deliver(journal, event, pages) pages, remaining = read(view["remaining_read_command"]) assert len(pages) > 1 - if requested_scopes: - assert remaining["/selected_todo/required_write_scopes"] == requested_scopes if not (warm and requested_scopes): assert remaining["/goal_boundary/write_scope"] == scopes if checkpoint_count: entries = source["goal_boundary"]["checkpointed_boundary_authority"]["entries"] assert len(entries) == checkpoint_count + assert remaining[authority + "/active_write_scope"] == [scopes[0]] assert remaining[authority + "/entries"] == entries _, remainder_ref = read_context_read_reference(pages[0]["reference_file"]) assert remainder_ref["sha256"] == source_ref["sha256"] diff --git a/tests/control_plane/test_coordination_configuration.py b/tests/control_plane/test_coordination_configuration.py index 10c0ca4789..28c9da0e6b 100644 --- a/tests/control_plane/test_coordination_configuration.py +++ b/tests/control_plane/test_coordination_configuration.py @@ -1,6 +1,9 @@ from __future__ import annotations -from loopx.control_plane.coordination.configuration import normalize_goal_write_scope +from loopx.control_plane.coordination.configuration import ( + fold_write_scope_subpaths, + normalize_goal_write_scope, +) def test_goal_write_scope_normalization_preserves_configuration_semantics() -> None: @@ -9,3 +12,27 @@ def test_goal_write_scope_normalization_preserves_configuration_semantics() -> N assert normalize_goal_write_scope( [" docs/**, tests/** ", "docs/**", "src/**;generated/**", ""] ) == ["docs/**", "tests/**", "src/**;generated/**"] + + +def test_fold_write_scope_subpaths_collapses_redundancy_and_preserves_boundaries() -> None: + scopes = [ + "**", + "src/**", + "src/sub/file.ts", + "/repos/example/loopx/docs/**", + "/repos/other/**", + "/repos/other/sub/**", + "~/.ssh/**", + "config/.aws/**", + "deploy/secrets/token.pem", + ] + assert fold_write_scope_subpaths(scopes, goal_repo="/repos/example/loopx") == [ + "**", + "/repos/other/**", + "~/.ssh/**", + "config/.aws/**", + "deploy/secrets/token.pem", + ] + assert fold_write_scope_subpaths( + ["src/**", "src/a/b.ts", "src/sub/**", "docs/*.md", "docs/**"], + ) == ["src/**", "docs/**"] diff --git a/tests/control_plane/test_goal_boundary_resolution.py b/tests/control_plane/test_goal_boundary_resolution.py index 786caf37b4..84905c021a 100644 --- a/tests/control_plane/test_goal_boundary_resolution.py +++ b/tests/control_plane/test_goal_boundary_resolution.py @@ -242,6 +242,32 @@ def test_goal_boundary_appends_only_active_checkpointed_write_scopes() -> None: assert authority["active_write_scope"] == ["tests/**", "loopx/**"] +def test_cba_folds_internally_without_cross_folding_against_goal_write_scope() -> None: + active_broad = build_checkpointed_boundary_authority_entry( + write_scopes=["docs/**"], + source="operator_gate_resume_contract_v0:active", + recorded_at="2026-07-01T00:00:00+00:00", + ) + active_nested = build_checkpointed_boundary_authority_entry( + write_scopes=["docs/guide/intro.md", "tests/unit/**"], + source="operator_gate_resume_contract_v0:active-nested", + recorded_at="2026-07-01T00:00:00+00:00", + ) + boundary = goal_boundary( + { + "coordination": { + "write_scope": ["**"], + "checkpointed_boundary_authority": [active_broad, active_nested], + } + } + ) + + assert boundary is not None + assert boundary["write_scope"] == ["**"] + authority = boundary["checkpointed_boundary_authority"] + assert authority["active_write_scope"] == ["docs/**", "tests/unit/**"] + + @pytest.mark.parametrize("field", ["expires_at", "fresh_until"]) @pytest.mark.parametrize("value", [ "not-an-iso-timestamp", "2026-02-30T00:00:00Z", 0, 20990101, False, [], {}, diff --git a/tests/control_plane/test_goal_local_write_admission.py b/tests/control_plane/test_goal_local_write_admission.py index 1e9830118e..bb2c5699d0 100644 --- a/tests/control_plane/test_goal_local_write_admission.py +++ b/tests/control_plane/test_goal_local_write_admission.py @@ -167,16 +167,13 @@ def test_real_cli_local_write_guard_replay_and_causal_settlement( rc, outside = _run_cli(registry, runtime, *guard_args, cwd=tmp_path) assert rc == 0 and outside["normal_delivery_allowed"] is True, outside assert not outside.get("workspace_guard"), outside - assert outside["selected_todo"]["required_write_scopes"] == todos[0]["required_write_scopes"] + assert "required_write_scopes" not in outside["selected_todo"] hint = outside["interaction_contract"]["cli_channel"]["delivery_workspace_causality"]["refresh"] assert "--delivery-workspace-path" in hint assert _spend_run_count(runtime) == 0 rc, guard = _run_cli(registry, runtime, *guard_args, cwd=project) assert rc == 0 and guard["normal_delivery_allowed"] is True, guard - assert ( - guard["selected_todo"]["required_write_scopes"] - == todos[0]["required_write_scopes"] - ) + assert "required_write_scopes" not in guard["selected_todo"] rc, replay = _run_cli(registry, runtime, *guard_args, cwd=project) assert ( rc == 0 diff --git a/tests/control_plane/test_quota_action_portfolio.py b/tests/control_plane/test_quota_action_portfolio.py index 33c6e63b5c..7af58b79f4 100644 --- a/tests/control_plane/test_quota_action_portfolio.py +++ b/tests/control_plane/test_quota_action_portfolio.py @@ -232,9 +232,7 @@ def test_sticky_primary_exposes_bounded_agent_selection_on_every_hot_path() -> N assert portfolio["suggested_actions"][1]["required_capabilities"] == [ "fallback_runner" ] - assert portfolio["suggested_actions"][1]["required_write_scopes"] == [ - "artifacts/fallback/**" - ] + assert "required_write_scopes" not in portfolio["suggested_actions"][1] assert packet["interaction_contract"]["agent_channel"][ "action_portfolio_ref" ] == "$.action_portfolio" @@ -267,9 +265,7 @@ def test_sticky_primary_exposes_bounded_agent_selection_on_every_hot_path() -> N assert compact["capability_gate"] == packet["capability_gate"] compact_candidates = compact["agent_todo_summary"]["first_executable_items"] assert compact_candidates[1]["required_capabilities"] == ["fallback_runner"] - assert compact_candidates[1]["required_write_scopes"] == [ - "artifacts/fallback/**" - ] + assert "required_write_scopes" not in compact_candidates[1] effect_turn = interpret_quota_should_run_packet(packet) assert effect_turn.observation.action_portfolio == portfolio diff --git a/tests/control_plane/test_quota_authority_settlement_journey.py b/tests/control_plane/test_quota_authority_settlement_journey.py index 6d6e0c259c..76ce10fd93 100644 --- a/tests/control_plane/test_quota_authority_settlement_journey.py +++ b/tests/control_plane/test_quota_authority_settlement_journey.py @@ -364,7 +364,6 @@ def _workspace_repair_source(tmp_path, provider, goal_scopes=None, todo_scopes=N ]) def test_workspace_repair_opening_keeps_action_and_recovers_scopes(tmp_path, monkeypatch, provider, native): goal_path = "/goal_boundary/write_scope" - todo_path = "/selected_todo/required_write_scopes" goal_scopes = ["src/**"] + [f"docs/area-{i:03d}/reference/specifications/**" for i in range(300)] todo_scopes = [f"src/area-{i:03d}/implementations/shared/**" for i in range(300)] project, runtime, registry = _workspace_repair_source(tmp_path, provider, goal_scopes, todo_scopes) @@ -372,7 +371,7 @@ def test_workspace_repair_opening_keeps_action_and_recovers_scopes(tmp_path, mon code, plain = _guard(project, runtime, registry, turn_id=turn) assert code == 0 and plain["effective_action"] == "agent_workspace_repair" assert plain["goal_boundary"]["write_scope"] == goal_scopes - assert plain["selected_todo"]["required_write_scopes"] == todo_scopes + assert "required_write_scopes" not in plain["selected_todo"] assert cli._heartbeat_receipt_count(runtime, turn) == 1 identity = plain["heartbeat_receipt"]["settlement_identity"] repair_action = plain["interaction_contract"]["agent_channel"]["primary_action"] @@ -426,7 +425,7 @@ def selection(command): assert initial["/goal_boundary/stop_condition"] == plain["goal_boundary"]["stop_condition"] assert initial["/heartbeat_receipt/settlement_identity"] == identity assert initial["/interaction_contract/agent_channel/delivery_allowed"] is False - assert goal_path not in initial and todo_path not in initial + assert goal_path not in initial assert initial["/goal_boundary/write_scope_pointer"] == goal_path detail = initial["/context_details/unread_context_index/source"] template = shlex.split(initial["/context_details/command_template"]) @@ -438,8 +437,8 @@ def selection(command): code, rejected = cli._run_cli(registry, runtime, *delivered_reader[delivered_reader.index("quota"):], "--select", goal_path, cwd=project) assert code != 0 and rejected["diagnostic_code"] == "context_selection_missing_pointer" - _, exact = selection(shlex.join([*template[:-1], goal_path, "--select", todo_path])) - assert exact[goal_path] == goal_scopes and exact[todo_path] == todo_scopes + _, exact = selection(shlex.join([*template[:-1], goal_path])) + assert exact[goal_path] == goal_scopes assert cli._heartbeat_receipt_count(runtime, turn) == 1 workspace = tmp_path / "repair-worktree" diff --git a/tests/control_plane/test_quota_settlement_cli.py b/tests/control_plane/test_quota_settlement_cli.py index c8d0668982..97d2e07f64 100644 --- a/tests/control_plane/test_quota_settlement_cli.py +++ b/tests/control_plane/test_quota_settlement_cli.py @@ -6287,8 +6287,6 @@ def test_selection_added_after_pending_guard_reports_final_boundary( AGENT_ID, "--text", "Validate the new canonical task", - "--task-repository", - "git:github.com/example/read-only-settlement-fixture", "--required-write-scope", "loopx/**", ) diff --git a/tests/control_plane/test_task_lease_cli.py b/tests/control_plane/test_task_lease_cli.py index 6d65b932b7..b5b899beb5 100644 --- a/tests/control_plane/test_task_lease_cli.py +++ b/tests/control_plane/test_task_lease_cli.py @@ -106,11 +106,11 @@ def release(task, owner, key, version): assert replay["lease"] == current denied = acquire(task_b, "agent-b", "same-checkout", 0, first, exit_code=1) - assert denied["error_code"] == "write_scope_conflict" + assert denied["error_code"] == "workspace_lease_conflict" assert "recovery" not in denied assert denied["conflicts"][0]["todo_id"] == task_a own_denied = acquire(task_c, "agent-a", "own-same-checkout", 0, first, exit_code=1) - assert own_denied["error_code"] == "write_scope_conflict" + assert own_denied["error_code"] == "workspace_lease_conflict" assert [row["todo_id"] for row in own_denied["conflicts"]] == [task_a] assert own_denied["own_conflicting_lease"] == { "todo_id": task_a, @@ -168,7 +168,7 @@ def emitted(step): from loopx.cli_commands.task_lease import render_task_lease_markdown rendered = render_task_lease_markdown(own_denied) assert "inspect_own_conflicting_lease" in rendered - assert task_a in rendered and "write_scope_conflict" in rendered + assert task_a in rendered and "workspace_lease_conflict" in rendered markdown = subprocess.run([sys.executable, "-m", "loopx.cli", "--registry", str(registry), "--runtime-root", str(runtime), "task-lease", "acquire", "--goal-id", goal, "--todo-id", task_c, "--owner", "agent-a", "--idempotency-key", "own-same-checkout", "--expected-version", "0", @@ -178,12 +178,12 @@ def emitted(step): assert "Traceback" not in markdown.stderr assert cli("inspect", task_a)["lease"] == current independent = acquire(task_b, "agent-b", "separate-checkout", 0, second) - assert any(row["todo_id"] == task_a for row in independent["integration_overlap_advisories"]) + assert "integration_overlap_advisories" not in independent assert independent["lease"]["write_workspace"]["worktree"] != admitted["lease"]["write_workspace"]["worktree"] - mixed = cli("acquire", task_c, "--owner", "agent-a", "--idempotency-key", "mixed-conflict", - "--expected-version", "0", "--write-scope", "src/**", exit_code=1) - assert {row["todo_id"] for row in mixed["conflicts"]} == {task_a, task_b} - assert mixed["foreign_conflict_count"] == 1 + without_worktree = cli("acquire", task_c, "--owner", "agent-a", "--idempotency-key", "without-worktree", + "--expected-version", "0", "--write-scope", "src/**") + assert without_worktree["acquired"] + assert release(task_c, "agent-a", "without-worktree", without_worktree["lease"]["version"])["released"] denied = acquire(task_a, "agent-b", "wrong-owner", 0, first, exit_code=1) assert not denied["ok"] denied = cli("renew", task_a, "--owner", "agent-a", "--idempotency-key", "with-dependencies", diff --git a/tests/control_plane/test_task_orchestration_admission.py b/tests/control_plane/test_task_orchestration_admission.py index 46609dc8da..1f5e84b93b 100644 --- a/tests/control_plane/test_task_orchestration_admission.py +++ b/tests/control_plane/test_task_orchestration_admission.py @@ -252,16 +252,10 @@ def test_admission_serializes_overlapping_write_scopes() -> None: assert contract is not None assert [lane["todo_id"] for lane in contract["eligible_child_lanes"]] == [ - "todo_independent" - ] - assert contract["blocked_lanes"] == [ - { - "todo_id": "todo_conflict", - "task_domain": "code", - "reason_codes": ["write_scope_conflict"], - "conflicts_with_todo_id": "todo_primary", - } + "todo_conflict", + "todo_independent", ] + assert contract["blocked_lanes"] == [] def _scope_contract( @@ -304,16 +298,10 @@ def test_admission_serializes_case_alias_write_scopes() -> None: assert contract is not None assert [lane["todo_id"] for lane in contract["eligible_child_lanes"]] == [ - "todo_independent" - ] - assert contract["blocked_lanes"] == [ - { - "todo_id": "todo_case_alias", - "task_domain": "code", - "reason_codes": ["write_scope_conflict"], - "conflicts_with_todo_id": "todo_primary", - } + "todo_case_alias", + "todo_independent", ] + assert contract["blocked_lanes"] == [] def test_admission_keeps_scheduling_subtree_containment_without_a_trailing_slash() -> None: @@ -328,16 +316,10 @@ def test_admission_keeps_scheduling_subtree_containment_without_a_trailing_slash assert contract is not None assert [lane["todo_id"] for lane in contract["eligible_child_lanes"]] == [ - "todo_independent" - ] - assert contract["blocked_lanes"] == [ - { - "todo_id": "todo_below", - "task_domain": "code", - "reason_codes": ["write_scope_conflict"], - "conflicts_with_todo_id": "todo_primary", - } + "todo_below", + "todo_independent", ] + assert contract["blocked_lanes"] == [] def test_admission_leaves_sibling_files_independent() -> None: @@ -402,16 +384,10 @@ def test_admission_serializes_implicit_and_explicit_goal_repository_scopes() -> assert contract is not None assert [lane["todo_id"] for lane in contract["eligible_child_lanes"]] == [ - "todo_independent" - ] - assert contract["blocked_lanes"] == [ - { - "todo_id": "todo_same_repository", - "task_domain": "code", - "reason_codes": ["write_scope_conflict"], - "conflicts_with_todo_id": "todo_primary", - } + "todo_same_repository", + "todo_independent", ] + assert contract["blocked_lanes"] == [] def test_admission_fails_closed_when_configured_domains_are_all_invalid() -> None: diff --git a/tests/control_plane/test_todo_claim_argument_recovery.py b/tests/control_plane/test_todo_claim_argument_recovery.py index 2a9ad438e3..36a9aa6018 100644 --- a/tests/control_plane/test_todo_claim_argument_recovery.py +++ b/tests/control_plane/test_todo_claim_argument_recovery.py @@ -124,7 +124,7 @@ def test_one_packet_repairs_all_grammar_errors_and_preserves_route(claim_cli, th after = snapshot() assert after[0][0]["claimed_by"] == "peer-a" assert applied["lease"]["version"] == 1 - assert applied["lease"]["write_scopes"] == ["src/**"] + assert applied["lease"]["write_scopes"] == [] receipt = run(receipt_args) assert receipt["status"] == "found" assert receipt["operation_id"] == operation diff --git a/tests/control_plane/test_todo_list_thin.py b/tests/control_plane/test_todo_list_thin.py index 1a99bce1e2..b2a6ed6197 100644 --- a/tests/control_plane/test_todo_list_thin.py +++ b/tests/control_plane/test_todo_list_thin.py @@ -588,4 +588,4 @@ def test_cli_rejects_thin_outside_todo_list(tmp_path: Path) -> None: assert result.returncode == 1, result.stdout payload = json.loads(result.stdout) - assert payload["error"] == "--thin is supported only by todo list, todo receipt, todo claim" + assert payload["error"] == "--thin is supported only by todo list, todo claim" diff --git a/tests/control_plane/test_workspace_git_fact_reads.py b/tests/control_plane/test_workspace_git_fact_reads.py index 2302fae5f6..77ab67fc04 100644 --- a/tests/control_plane/test_workspace_git_fact_reads.py +++ b/tests/control_plane/test_workspace_git_fact_reads.py @@ -131,7 +131,12 @@ def test_goal_repository_fallback_resolves_each_worktree_once(workspaces, monkey calls = observe_reads(monkeypatch) assert owner.build_agent_workspace_guard( {"repo": str(canonical)}, {"agent_id": "peer", "registered_agents": ["lead", "peer"]}, - selected_todo={"required_write_scopes": ["src/**"]}, current_path=nested, + selected_todo={"required_write_scopes": ["src/**"]}, current_path=canonical, + ) is None + assert calls == [] + assert owner.build_agent_workspace_guard( + {"repo": str(canonical)}, {"agent_id": "peer", "registered_agents": ["lead", "peer"]}, + selected_todo={"action_kind": "implement"}, current_path=nested, ) is None assert sum(args == ("rev-parse", "--show-toplevel") for _, args in calls) == 2 diff --git a/tests/control_plane/test_write_scope_coverage.py b/tests/control_plane/test_write_scope_coverage.py index 174663af2a..3ecc6ae548 100644 --- a/tests/control_plane/test_write_scope_coverage.py +++ b/tests/control_plane/test_write_scope_coverage.py @@ -223,3 +223,38 @@ def test_real_cli_preserves_class_authority_and_expired_hints(tmp_path, monkeypa ["expired-scope-fixture"] if mode == "expired_missing" and required == "src/a.ts" else [] ) assert _spend_run_count(runtime) == 0 + + +def test_projection_repair_skips_when_goal_covers_repo_or_task_binds_repository(scope_transport) -> None: + assert projection_repair.build_boundary_projection_repair_hint( + {"write_scope": ["**"]}, + {}, + candidate_should_run=True, + selected_todo={"todo_id": "todo_a", "required_write_scopes": ["unlisted/**"]}, + ) is None + assert projection_repair.build_boundary_projection_repair_hint( + {"write_scope": ["/repos/example/loopx/**"]}, + {}, + candidate_should_run=True, + selected_todo={"todo_id": "todo_a", "required_write_scopes": ["unlisted/**"]}, + goal_repo="/repos/example/loopx", + ) is None + assert projection_repair.build_boundary_projection_repair_hint( + {"write_scope": ["docs/**"]}, + {}, + candidate_should_run=True, + selected_todo={ + "todo_id": "todo_a", + "task_repository": "git:github.com/example/repo", + "required_write_scopes": ["src/**"], + }, + ) is None + assert scope_transport == [] + raw_fallback = projection_repair.build_boundary_projection_repair_hint( + {"write_scope": ["docs/**"]}, + {}, + candidate_should_run=True, + selected_todo={"todo_id": "todo_narrow"}, + raw_agent_todo_summary={"items": [{"todo_id": "todo_narrow", "required_write_scopes": ["src/**"]}]}, + ) + assert raw_fallback is not None and raw_fallback["missing_write_scopes"] == ["src/**"] diff --git a/tests/control_plane_ts/action_portfolio.test.ts b/tests/control_plane_ts/action_portfolio.test.ts index 796b19b065..bf2f9444ac 100644 --- a/tests/control_plane_ts/action_portfolio.test.ts +++ b/tests/control_plane_ts/action_portfolio.test.ts @@ -285,7 +285,6 @@ test("action portfolio exposes one recommendation and bounded selectable alterna text: "Run the primary slice.", priority: "P0", required_capabilities: ["capability_todo_primary001"], - required_write_scopes: ["artifacts/todo_primary001/**"], continuation_hint: "Continue todo_primary001 from its latest validated boundary.", selection_role: "recommended", }, @@ -294,7 +293,6 @@ test("action portfolio exposes one recommendation and bounded selectable alterna text: "Run fallback one.", priority: "P1", required_capabilities: ["capability_todo_fallback001"], - required_write_scopes: ["artifacts/todo_fallback001/**"], continuation_hint: "Continue todo_fallback001 from its latest validated boundary.", selection_role: "alternative", }, @@ -303,7 +301,6 @@ test("action portfolio exposes one recommendation and bounded selectable alterna text: "Run fallback two.", priority: "P2", required_capabilities: ["capability_todo_fallback002"], - required_write_scopes: ["artifacts/todo_fallback002/**"], continuation_hint: "Continue todo_fallback002 from its latest validated boundary.", selection_role: "alternative", }, @@ -407,7 +404,6 @@ test("pending selection qualifies only after current hard-lane arbitration", () text: successor.text, priority: successor.priority, required_capabilities: successor.required_capabilities, - required_write_scopes: successor.required_write_scopes, continuation_hint: successor.continuation_hint, selection_binding: "pending_action_selection", }); diff --git a/tests/control_plane_ts/authority_store_conformance.ts b/tests/control_plane_ts/authority_store_conformance.ts index b7c172bead..50411282fa 100644 --- a/tests/control_plane_ts/authority_store_conformance.ts +++ b/tests/control_plane_ts/authority_store_conformance.ts @@ -1579,7 +1579,7 @@ export function registerAuthorityStoreConformance( assert.equal(claimedTodo.claimed_by, "agent-a"); assert.equal(lease.owner, "agent-a"); assert.equal(lease.idempotency_key, "turn:atomic-ownership"); - assert.deepEqual(lease.write_scopes, ["loopx/control_plane/**"]); + assert.deepEqual(lease.write_scopes, []); assert.equal((await executeCoordinationTodoClaim(store, request)).status, "replayed"); const idempotent = await executeCoordinationTodoClaim(store, { diff --git a/tests/control_plane_ts/claim_contention_conformance.ts b/tests/control_plane_ts/claim_contention_conformance.ts index c4f555274f..67e8c5fab4 100644 --- a/tests/control_plane_ts/claim_contention_conformance.ts +++ b/tests/control_plane_ts/claim_contention_conformance.ts @@ -96,12 +96,12 @@ export function registerClaimContentionConformance(provider: string, factory: Au await barrier; })); const results = await Promise.all(requests.map((request, i) => claim(stores[i], request))); - assert.equal(results.filter(r => r.status === "applied").length, scenario === "independent" ? 2 : 1, + assert.equal(results.filter(r => r.status === "applied").length, scenario === "same-todo" ? 1 : 2, JSON.stringify(results)); - if (scenario !== "independent") { + if (scenario === "same-todo") { const loser = results.findIndex(r => r.status !== "applied"); assert.equal(results[loser].status, "failed", JSON.stringify(results[loser])); - assert.equal(results[loser].reason_code, scenario === "same-todo" ? "claim_owner_mismatch" : "write_scope_conflict"); + assert.equal(results[loser].reason_code, "claim_owner_mismatch"); assert.equal((await store.readReceipt(requests[loser].operation_id)).status, "missing"); } for (let i = 0; i < results.length; i++) if (results[i].status === "applied") { @@ -110,7 +110,7 @@ export function registerClaimContentionConformance(provider: string, factory: Au assert.equal((await claim(stores[i], requests[i])).status, "replayed"); assert.deepEqual(await store.readReceipt(requests[i].operation_id), receipt); } - assert.equal(arrivals, scenario === "independent" ? 3 : 2); + assert.equal(arrivals, scenario === "same-todo" ? 2 : 3); const final = await store.loadAuthority(); if (final.status !== "loaded") throw new Error("missing final authority"); const winners = requests.filter((_, i) => results[i].status === "applied"); diff --git a/tests/control_plane_ts/lease_acquisition_conformance.ts b/tests/control_plane_ts/lease_acquisition_conformance.ts index d47c8b400b..9c1b76c778 100644 --- a/tests/control_plane_ts/lease_acquisition_conformance.ts +++ b/tests/control_plane_ts/lease_acquisition_conformance.ts @@ -254,11 +254,16 @@ export function registerLeaseAcquisitionConformance(provider: string, factory: A }); for (const dimension of ["live", "archived", "excluded", "claim", "deregistered", "expired"] as const) { - test(`${provider} complete scope scan adjudicates ${dimension} holder beyond display limits`, async t => { - const {store, request, fixture} = await setup(t, "native", (p, _target, conflict) => { + test(`${provider} complete scope scan adjudicates ${dimension} same-checkout holder beyond display limits`, async t => { + const checkout = {host: "1".repeat(64), common_directory: "2".repeat(64), + worktree: "3".repeat(64), repository: "git:github.com/team/a"}; + const {store, request, fixture} = await setup(t, "native", (p, target, conflict) => { + (p.todos as JsonObject[]).find(r => r.todo_id === target)!.task_repository = checkout.repository; const todo = (p.todos as JsonObject[]).find(r => r.todo_id === conflict)!; const lease = (p.leases as JsonObject[]).find(r => r.todo_id === conflict)!; lease.write_scopes = ["lease-admission/shared/**"]; + lease.write_workspace = checkout; + lease.write_repository = checkout.repository; if (dimension === "archived") todo.archive_state = "archive"; if (dimension === "excluded") todo.excluded_agents = ["agent-b"]; if (dimension === "claim") todo.claimed_by = "agent-a"; @@ -266,9 +271,9 @@ export function registerLeaseAcquisitionConformance(provider: string, factory: A if (dimension === "expired") lease.expires_at = "2026-09-13T10:00:00Z"; }); const before = await loaded(store); - const result = await acquire(store, request); + const result = await acquire(store, {...request, write_workspace: checkout}); if (dimension === "live") { - assert.equal(result.reason_code, "write_scope_conflict"); + assert.equal(result.reason_code, "workspace_lease_conflict"); assert.equal((result.conflicts as JsonObject[])[0]!.todo_id, fixture.acquisition.conflict_todo_id); assert.deepEqual(await loaded(store), before); } else assert.equal(result.status, "applied", JSON.stringify(result)); @@ -321,29 +326,27 @@ export function registerLeaseAcquisitionConformance(provider: string, factory: A assert.equal((result.lease as JsonObject).version, 1); }); - for (const [kind, repository, frozen, allowed] of [ - ["different", "git:github.com/team/a", "git:github.com/team/b", true], - ["same", "git:github.com/team/a", "git:github.com/team/a", false], - ["case-alias", "git:github.com/Team/A", "git:github.com/team/a", false], - ["legacy-holder", "git:github.com/team/a", null, false], - ["unknown-requester", null, "git:github.com/team/b", false], + for (const [kind, repository, frozen] of [ + ["different", "git:github.com/team/a", "git:github.com/team/b"], + ["same", "git:github.com/team/a", "git:github.com/team/a"], + ["case-alias", "git:github.com/Team/A", "git:github.com/team/a"], + ["legacy-holder", "git:github.com/team/a", null], + ["unknown-requester", null, "git:github.com/team/b"], ] as const) { - test(`${provider} repository namespace ${kind} retains complete-scan admission`, async t => { + test(`${provider} repository namespace ${kind} acquires without per-path write_scope_conflict`, async t => { const {store, request} = await setup(t, "native", (p, target, conflict) => { (p.todos as JsonObject[]).find(r => r.todo_id === target)!.task_repository = repository; - // Even a known current Todo cannot backfill an old unknown grant. (p.todos as JsonObject[]).find(r => r.todo_id === conflict)!.task_repository = "git:github.com/team/b"; const holder = (p.leases as JsonObject[]).find(r => r.todo_id === conflict)!; holder.write_scopes = ["lease-admission/shared/**"]; if (frozen !== null) holder.write_repository = frozen; }); - const before = await loaded(store), result = await acquire(store, request); - if (allowed) { - assert.equal(result.status, "applied", JSON.stringify(result)); + const result = await acquire(store, request); + assert.equal(result.status, "applied", JSON.stringify(result)); + if (repository !== null) { assert.equal((result.lease as JsonObject).write_repository, repository); } else { - assert.equal(result.reason_code, "write_scope_conflict", JSON.stringify(result)); - assert.deepEqual(await loaded(store), before); + assert.equal((result.lease as JsonObject).write_repository, undefined); } }); } @@ -365,7 +368,7 @@ export function registerLeaseAcquisitionConformance(provider: string, factory: A lease_request: {idempotency_key: "repository-b", expected_version: 0, ttl_seconds: 600}, dry_run: false, now: request.now}); assert.equal(second.status, "applied", JSON.stringify(second)); assert.equal((second.lease as JsonObject).write_repository, "git:github.com/team/b"); - assert.deepEqual((second.lease as JsonObject).write_scopes, ["tests/**"]); + assert.deepEqual((second.lease as JsonObject).write_scopes, []); const maintenance = {...request, operation: "renew" as const, expected_version: 1}; const renewed = await mutate(store, maintenance); assert.equal(renewed.status, "applied"); diff --git a/tests/control_plane_ts/local_authority_runtime.test.ts b/tests/control_plane_ts/local_authority_runtime.test.ts index 2dcdd75562..d6b00ee1b6 100644 --- a/tests/control_plane_ts/local_authority_runtime.test.ts +++ b/tests/control_plane_ts/local_authority_runtime.test.ts @@ -1497,7 +1497,7 @@ test("provider-first atomic claim replays current execution and rejects expired assert.equal(lease.schema_version, "task_lease_v0"); assert.equal(lease.owner, "agent-a"); assert.equal(lease.idempotency_key, "turn:claim-with-lease"); - assert.deepEqual(lease.write_scopes, ["loopx/control_plane/**"]); + assert.deepEqual(lease.write_scopes, []); assert.equal(lease.version, 1); assert.equal(lease.lease_epoch, 1); diff --git a/tests/control_plane_ts/managed_claim_execution_conformance.ts b/tests/control_plane_ts/managed_claim_execution_conformance.ts index e7d5f8444f..72573fe97d 100644 --- a/tests/control_plane_ts/managed_claim_execution_conformance.ts +++ b/tests/control_plane_ts/managed_claim_execution_conformance.ts @@ -116,27 +116,31 @@ export function registerManagedClaimExecutionConformance(provider: string, facto } }); test(`${provider} managed execution: terminal advice does not replace explicit proof or bypass task blockers`, async t => { - for (const scenario of ["explicit-proof", "foreign-holder", "excluded", "blocked", "overlapping-work"]) { + for (const scenario of ["explicit-proof", "foreign-holder", "excluded", "blocked", "independent-todo"]) { const {store, request} = await setup(t); let original = {...completion(request), claim_operation_id: undefined} as Parameters[1]; if (scenario === "explicit-proof") original = {...original, lease_idempotency_key: "unproven-key"}; if (scenario === "foreign-holder") { assert.equal((await claim(store, {...request, actor_agent_id: "agent-b", claimed_by: "agent-b"})).status, "applied"); } - if (["excluded", "blocked", "overlapping-work"].includes(scenario)) { + if (["excluded", "blocked", "independent-todo"].includes(scenario)) { const head = await loaded(store); const todo = (head.head.todos as JsonObject[])[0]!; const change = scenario === "excluded" ? {...todo, excluded_agents: ["agent-a"]} : scenario === "blocked" ? {...todo, status: "blocked"} - : {...todo, todo_id: "todo_other", text: "Independent work occupying the same scope"}; + : {...todo, todo_id: "todo_other", text: "Independent work without hard write_scope conflict"}; assert.equal((await store.commitAuthority(prepareCoordinationProjectionCommit({goal_id: request.goal_id, operation_id: "prepare-blocker", expected_provider_revision: head.provider_revision, projection: head.head, mutations: [{kind: "todo_upsert", todo: change}]}))).status, "applied"); - if (scenario === "overlapping-work") assert.equal((await claim(store, {...request, todo_id: "todo_other", + if (scenario === "independent-todo") assert.equal((await claim(store, {...request, todo_id: "todo_other", actor_agent_id: "agent-b", claimed_by: "agent-b", operation_id: "occupy-scope"})).status, "applied"); } const before = await loaded(store); const result = await complete(store, original); assert.equal(result.status, "failed", scenario); - assert.notEqual((result.recovery as JsonObject | undefined)?.action, "claim_task", scenario); + if (scenario === "independent-todo") { + assert.equal((result.recovery as JsonObject | undefined)?.action, "claim_task", scenario); + } else { + assert.notEqual((result.recovery as JsonObject | undefined)?.action, "claim_task", scenario); + } if (scenario === "explicit-proof") assert.equal(result.recovery, undefined); assert.deepEqual(await loaded(store), before, scenario); } @@ -175,7 +179,7 @@ export function registerManagedClaimExecutionConformance(provider: string, facto const accepted = await claim(store, request); assert.equal(accepted.status, "applied", JSON.stringify(accepted)); const original = accepted.lease as JsonObject; - assert.deepEqual(original.write_scopes, ["src/**"]); + assert.deepEqual(original.write_scopes, []); assert.equal(original.expires_at, "2026-09-13T10:45:00Z"); assert.equal(accepted.claim_operation_id, "claim-a"); assert.equal((await update(store, progress)).status, "applied"); diff --git a/tests/control_plane_ts/task_lease_directory_scopes.test.ts b/tests/control_plane_ts/task_lease_directory_scopes.test.ts index f979d60f98..3a981f8438 100644 --- a/tests/control_plane_ts/task_lease_directory_scopes.test.ts +++ b/tests/control_plane_ts/task_lease_directory_scopes.test.ts @@ -70,7 +70,7 @@ test("directory matching retains stored spelling and existing authority boundari ttl_seconds: 60, write_scopes: ["src/components/*.ts"]}, }; const original = structuredClone(request); - assert.equal(evaluateTaskLeaseAcquireDecision(request).code, "write_scope_conflict"); + assert.equal(evaluateTaskLeaseAcquireDecision(request).outcome, "apply"); const differentRepository = structuredClone(request); differentRepository.todo.task_repository = "git:github.com/example/other"; assert.equal(evaluateTaskLeaseAcquireDecision(differentRepository).outcome, "apply"); @@ -78,12 +78,12 @@ test("directory matching retains stored spelling and existing authority boundari inactive.other_leases[0].active = false; assert.equal(evaluateTaskLeaseAcquireDecision(inactive).outcome, "apply"); const sameCheckout = {...request, command: {...request.command, write_workspace: workspace}}; - assert.equal(evaluateTaskLeaseAcquireDecision(sameCheckout).code, "write_scope_conflict"); + assert.equal(evaluateTaskLeaseAcquireDecision(sameCheckout).code, "workspace_lease_conflict"); const independent = {...request, command: {...request.command, write_workspace: {...workspace, worktree: "4".repeat(64)}}}; - const advisory = evaluateTaskLeaseAcquireDecision(independent); - assert.equal(advisory.outcome, "apply"); - assert.deepEqual(advisory.overlap_advisory_indexes, [0]); + const separate = evaluateTaskLeaseAcquireDecision(independent); + assert.equal(separate.outcome, "apply"); + assert.equal(separate.overlap_advisory_indexes, undefined); assert.deepEqual(request, original); assert.deepEqual(comparisonWriteScopes(["src/"]), ["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..04070fa010 100644 --- a/tests/control_plane_ts/task_lease_workspace.test.ts +++ b/tests/control_plane_ts/task_lease_workspace.test.ts @@ -145,34 +145,34 @@ function request(other: unknown = {...workspace, worktree: "4".repeat(64)}) { other_leases: [{todo_id: "todo_b", active: true, effective: true, write_repository: repo as string | null, write_scopes: ["src/**"], write_workspace: other}], command: {owner: "agent-a", idempotency_key: "work-a", ttl_seconds: 60, expected_version: 0, write_scopes: ["src/main.ts"], write_workspace: workspace}}; } -test("verified code-edit worktrees treat file overlaps as integration advisories", () => { +test("verified code-edit worktrees enforce same-checkout exclusivity and admit separate worktrees", () => { const result = evaluateTaskLeaseAcquireDecision(request()); assert.equal(result.outcome, "apply"); - assert.deepEqual(result.overlap_advisory_indexes, [0]); + assert.equal(result.overlap_advisory_indexes, undefined); assert.deepEqual(result.next_lease?.write_workspace, workspace); for (const other of [null, {...workspace, host: "5".repeat(64)}, {...workspace, common_directory: "6".repeat(64), worktree: "7".repeat(64)}]) { const input = request(other); if (other === null) input.other_leases[0].write_repository = null; - const advisory = evaluateTaskLeaseAcquireDecision(input); - assert.equal(advisory.outcome, "apply"); - assert.deepEqual(advisory.overlap_advisory_indexes, [0]); + const separate = evaluateTaskLeaseAcquireDecision(input); + assert.equal(separate.outcome, "apply"); + assert.equal(separate.overlap_advisory_indexes, undefined); assert.deepEqual(input.other_leases[0].write_workspace, other); } for (const other of [workspace, {...workspace, common_directory: "6".repeat(64)}]) { - assert.equal(evaluateTaskLeaseAcquireDecision(request(other)).code, "write_scope_conflict"); + assert.equal(evaluateTaskLeaseAcquireDecision(request(other)).code, "workspace_lease_conflict"); assert.equal(sameLeaseCheckout(workspace, other), true); } }); -test("ordinary exclusive grants retain overlap rejection without worktree mode", () => { +test("unrelated Todos without a shared physical checkout are not blocked on write_scopes", () => { for (const other of [null, workspace]) { const input = request(other); const exclusive = {...input, command: {...input.command, write_workspace: null}}; - assert.equal(evaluateTaskLeaseAcquireDecision(exclusive).code, "write_scope_conflict"); + assert.equal(evaluateTaskLeaseAcquireDecision(exclusive).outcome, "apply"); } }); -test("lexical scope aliases cannot bypass an ordinary exclusive lease", () => { +test("lexical scope aliases do not block separate Todo leases while keeping stored spellings", () => { const now = new Date("2030-01-01T00:00:00Z"); const projection = indexCoordinationProjection({ goal_id: "goal-a", @@ -207,12 +207,12 @@ test("lexical scope aliases cannot bypass an ordinary exclusive lease", () => { }, }); - assert.equal(decision.code, "write_scope_conflict"); + assert.equal(decision.code, "lease_acquire"); assert.deepEqual(facts.other_leases[0].write_scopes, ["src/main.ts"]); assert.deepEqual(projection.leases.get("todo_holder")?.write_scopes, ["src/./main.ts"]); }); -test("malformed retained scopes conservatively conflict without rewriting history", () => { +test("malformed retained scopes stay readable without blocking distinct Todos", () => { for (const holderScope of ["../legacy", "src\\legacy"]) { const now = new Date("2030-01-01T00:00:00Z"); const projection = indexCoordinationProjection({ @@ -248,7 +248,7 @@ test("malformed retained scopes conservatively conflict without rewriting histor }, }); - assert.equal(decision.code, "write_scope_conflict"); + assert.equal(decision.code, "lease_acquire"); assert.deepEqual(facts.other_leases[0].write_scopes, ["**"]); assert.deepEqual(projection.leases.get("todo_holder")?.write_scopes, [holderScope]); } @@ -386,7 +386,7 @@ test("a known same-checkout collision wins over changed repository metadata", () const other = {...workspace, repository: "git:github.com/example/other"}; const input = request(other); input.other_leases[0].write_repository = other.repository; - assert.equal(evaluateTaskLeaseAcquireDecision(input).code, "write_scope_conflict"); + assert.equal(evaluateTaskLeaseAcquireDecision(input).code, "workspace_lease_conflict"); }); test("worktree identity cannot weaken Todo ownership or repository identity", () => { const input = request(); @@ -424,7 +424,7 @@ test("PostgreSQL retains worktree identity and overlap receipts across reload", assert.equal(legacy.status, "applied"); const first = await executeCanonicalTaskLeaseAcquire(store, command); assert.equal(first.status, "applied"); - assert.equal((first.integration_overlap_advisories as unknown[]).length, 1); + assert.equal(first.integration_overlap_advisories, undefined); const reopened = new PostgreSqlAuthorityStore(database, options); const replay = await executeCanonicalTaskLeaseAcquire(reopened, command); assert.deepEqual(replay.original_receipt, first.original_receipt); @@ -432,7 +432,7 @@ test("PostgreSQL retains worktree identity and overlap receipts across reload", const second = await executeCanonicalTaskLeaseAcquire(reopened, {...command, todo_id: "todo_beta", idempotency_key: "beta", write_workspace: {...workspace, worktree: "4".repeat(64)}}); assert.equal(second.status, "applied"); - assert.equal((second.integration_overlap_advisories as unknown[]).length, 2); + assert.equal(second.integration_overlap_advisories, undefined); const retained = await executeCanonicalTaskLeaseAcquire(reopened, legacyCommand); assert.deepEqual(retained.original_receipt, legacy.original_receipt); assert.deepEqual(retained.lease, legacy.lease); diff --git a/tests/control_plane_ts/todo_summary_projection.test.ts b/tests/control_plane_ts/todo_summary_projection.test.ts index daeacaa471..911c5ac300 100644 --- a/tests/control_plane_ts/todo_summary_projection.test.ts +++ b/tests/control_plane_ts/todo_summary_projection.test.ts @@ -243,7 +243,7 @@ test("summary display normalizes declarations and the last scoped outcome wins i const projected = projectTodoSummaryDisplay({items: [{record}]})[0]!; assert.equal(projected.task_domain, "engineering"); assert.equal(projected.task_repository, "git:example.com/team/project"); - assert.deepEqual(projected.required_write_scopes, ["docs/**"]); + assert.equal(projected.required_write_scopes, undefined); assert.deepEqual(projected.required_decision_scopes, [{schema_version: "decision_scope_v0", ...scope}]); assert.deepEqual(projected.decision_scope_outcomes, [{schema_version: "todo_decision_scope_outcome_v0", outcome: "reject", decision_scope: {schema_version: "decision_scope_v0", ...scope}, source_todo_id: "todo_second"}]); diff --git a/tests/control_plane_ts/todo_update.test.ts b/tests/control_plane_ts/todo_update.test.ts index 9c0ec50843..508e9fe248 100644 --- a/tests/control_plane_ts/todo_update.test.ts +++ b/tests/control_plane_ts/todo_update.test.ts @@ -1320,13 +1320,15 @@ test("inactive history keeps unsupported lifecycle edits fenced without inventin } }); -for (const blocker of ["scope", "acceptance"]) test(`recovery respects ${blocker} acquisition admission`, async () => { +for (const blocker of ["blocked", "acceptance"]) test(`recovery respects ${blocker} acquisition admission`, async () => { const {store, request} = await seeded({required_write_scopes: ["src/**"]}); const head = await store.loadAuthority(); if (head.status !== "loaded") assert.fail("missing fixture"); + const baseTodo = (head.head.todos as Record[])[0]!; + const updatedTodo = blocker === "blocked" ? {...baseTodo, status: "blocked"} : baseTodo; const other = todo({todo_id: "todo_other", claimed_by: "agent-b"}); - const todos = [...head.head.todos as Record[], other]; - await store.commitAuthority({operation_id: "scope-conflict", expected_provider_revision: head.provider_revision, + const todos = [updatedTodo, other]; + await store.commitAuthority({operation_id: "acquire-blocker", expected_provider_revision: head.provider_revision, events: [], receipts: [], next_projection: {...head.head, handoff_mode: "hard_lease", todos, todo_read_model: {schema_version: TODO_DOMAIN_READ_RECORD_SCHEMA, todo_count: 2, records_sha256: canonicalAuthoritySha256(todos), contract_fields: [...TODO_DOMAIN_RECORD_CONTRACT.fields]}, @@ -1334,7 +1336,7 @@ for (const blocker of ["scope", "acceptance"]) test(`recovery respects ${blocker {todo_id: "todo_a", owner: "agent-a", idempotency_key: "released-key", version: 2, lease_epoch: 1, status: "released", expires_at: "2026-09-06T00:00:00Z", write_scopes: []}, {todo_id: "todo_other", owner: "agent-b", idempotency_key: "foreign-active-key", version: 1, - lease_epoch: 1, status: "active", expires_at: "2026-09-06T00:00:00Z", write_scopes: blocker === "scope" ? ["src/file.ts"] : []}, + lease_epoch: 1, status: "active", expires_at: "2026-09-06T00:00:00Z", write_scopes: ["src/file.ts"]}, ]}}); if (blocker === "acceptance") { const current = await store.loadAuthority(); @@ -1350,8 +1352,30 @@ for (const blocker of ["scope", "acceptance"]) test(`recovery respects ${blocker const result = await executeCoordinationTodoUpdate(store, {...request, planning_intent: {unblocks_todo_id: "todo_other"}}); const recovery = result.recovery as Record; assert.equal(recovery.action, "resolve_acquire_rejection"); - assert.equal(recovery.reason_code, blocker === "scope" ? "write_scope_conflict" : "goal_acceptance_unbound"); + assert.equal(recovery.reason_code, blocker === "blocked" ? "todo_not_open" : "goal_acceptance_unbound"); assert.equal(recovery.acquire, undefined); assert.equal(JSON.stringify(result).includes("foreign-active-key"), false); assert.deepEqual(await store.loadAuthority(), before); }); + +test("recovery no longer raises write_scope_conflict from overlapping other_leases scopes", async () => { + const {store, request} = await seeded({required_write_scopes: ["src/**"]}); + const head = await store.loadAuthority(); + if (head.status !== "loaded") assert.fail("missing fixture"); + const other = todo({todo_id: "todo_other", claimed_by: "agent-b"}); + const todos = [...head.head.todos as Record[], other]; + await store.commitAuthority({operation_id: "overlapping-other-lease", expected_provider_revision: head.provider_revision, + events: [], receipts: [], next_projection: {...head.head, handoff_mode: "hard_lease", todos, + todo_read_model: {schema_version: TODO_DOMAIN_READ_RECORD_SCHEMA, todo_count: 2, + records_sha256: canonicalAuthoritySha256(todos), contract_fields: [...TODO_DOMAIN_RECORD_CONTRACT.fields]}, + leases: [ + {todo_id: "todo_a", owner: "agent-a", idempotency_key: "released-key", version: 2, + lease_epoch: 1, status: "released", expires_at: "2026-09-06T00:00:00Z", write_scopes: []}, + {todo_id: "todo_other", owner: "agent-b", idempotency_key: "foreign-active-key", version: 1, + lease_epoch: 1, status: "active", expires_at: "2026-09-06T00:00:00Z", write_scopes: ["src/file.ts"]}, + ]}}); + const result = await executeCoordinationTodoUpdate(store, {...request, planning_intent: {unblocks_todo_id: "todo_other"}}); + const recovery = result.recovery as Record; + assert.equal(recovery.action, "claim_task"); + assert.equal(recovery.reason_code, undefined); +}); diff --git a/tests/pi_goal_loop_runtime.test.mjs b/tests/pi_goal_loop_runtime.test.mjs index 974ce530ad..c3c2936b4b 100644 --- a/tests/pi_goal_loop_runtime.test.mjs +++ b/tests/pi_goal_loop_runtime.test.mjs @@ -1506,13 +1506,13 @@ test("inspect is read-only and preserves a compact typed receipt", async () => { }) -test("non-zero write-scope and CAS failures stay typed and omit private paths", async () => { +test("non-zero workspace-lease and CAS failures stay typed and omit private paths", async () => { const conflict = { ok: false, schema_version: "task_lease_v0", action: "acquire", - error: "write scope overlaps another active task lease", - error_code: "write_scope_conflict", + error: "write workspace collides with another active task lease", + error_code: "workspace_lease_conflict", conflicts: [{ todo_id: "todo_beta", owner: "agent-other", @@ -1537,7 +1537,7 @@ test("non-zero write-scope and CAS failures stay typed and omit private paths", async () => ({ stdout: JSON.stringify(conflict), returncode: 1 }), taskLeaseAuthority(), ) - assert.equal(second.error_code, "write_scope_conflict") + assert.equal(second.error_code, "workspace_lease_conflict") assert.deepEqual(second.conflicts, [{ todo_id: "todo_beta", owner: "agent-other", write_scopes: ["src/**"] }]) assert.equal(JSON.stringify(second).includes("lease_path"), false) diff --git a/tests/test_explore_resource_portfolio.py b/tests/test_explore_resource_portfolio.py index 1307470bae..5add37323e 100644 --- a/tests/test_explore_resource_portfolio.py +++ b/tests/test_explore_resource_portfolio.py @@ -109,17 +109,23 @@ def _todo( } -def _assert_resource_fill(plan: dict[str, object], *, selected_key: str) -> None: +def _assert_resource_fill( + plan: dict[str, object], + *, + selected_key: str, + allow_shared_scope: bool = False, +) -> None: selected = plan[selected_key] selected_ids = { todo_id for branch in selected for todo_id in branch.get("todo_ids", [branch.get("todo_id")]) } + expected_second = "todo_short_conflict" if allow_shared_scope else "todo_short_backfill" assert selected_ids == { "todo_long_backfill", "todo_short_primary", - "todo_short_backfill", + expected_second, } portfolio = plan["resource_portfolio"] assert portfolio["analysis_only"] is True @@ -141,10 +147,11 @@ def _assert_resource_fill(plan: dict[str, object], *, selected_key: str) -> None } assert statuses["todo_monitor"] == "excluded_non_exploration_lane" assert statuses["todo_long_blocked_dependency"] == "invalidated_dependency" - assert statuses["todo_short_conflict"] == "rejected_hazard" + if not allow_shared_scope: + assert statuses["todo_short_conflict"] == "rejected_hazard" -def test_todo_plan_backfills_each_resource_lane_after_dependency_and_scope_rejections() -> None: +def test_todo_plan_backfills_each_resource_lane_without_write_scope_blocks() -> None: plan = build_explore_todo_branch_plan( goal_id="synthetic-resource-portfolio", todos=TODOS, @@ -157,7 +164,7 @@ def test_todo_plan_backfills_each_resource_lane_after_dependency_and_scope_rejec assert plan["orchestration_gate"]["state"] == "analysis_only" assert plan["selection_budget"] == 5 - _assert_resource_fill(plan, selected_key="selected_branches") + _assert_resource_fill(plan, selected_key="selected_branches", allow_shared_scope=True) long_branch = next( branch for branch in plan["selected_branches"] if branch["todo_id"] == "todo_long_backfill" ) diff --git a/tests/test_task_lease_worktree.py b/tests/test_task_lease_worktree.py index 4a9dfec8d9..c0c5b22df8 100644 --- a/tests/test_task_lease_worktree.py +++ b/tests/test_task_lease_worktree.py @@ -1,6 +1,5 @@ """Real sibling Git worktrees and the public lease CLI on both canonical providers.""" import json -import shlex import subprocess import sys from pathlib import Path @@ -94,16 +93,16 @@ def acquire(key, path, expected=0, scope="src/**"): assert "write_workspace" in first["lease"] assert first["lease"]["write_repository"] == repository assert first["lease"]["write_workspace"]["repository"] == repository - assert first["integration_overlap_advisories"][0]["todo_id"] == "todo_worktree_d" + assert "integration_overlap_advisories" not in first assert cli("inspect", "d")["lease"] == legacy["lease"] assert str(tmp_path) not in json.dumps(first["lease"]) conflict = acquire("c", alias, expected=1) - assert conflict["error_code"] == "write_scope_conflict" + assert conflict["error_code"] == "workspace_lease_conflict" assert conflict["conflicts"][0]["owner"] == "agent-a" assert "--write-worktree" in conflict["recommended_action"] - assert acquire("e", None, expected=1)["error_code"] == "write_scope_conflict" + assert acquire("e", None)["acquired"] is True second = acquire("b", Path("../b")) - assert {row["todo_id"] for row in second["integration_overlap_advisories"]} == {"todo_worktree_a", "todo_worktree_d"} + assert "integration_overlap_advisories" not in second assert second["lease"]["write_workspace"] != first["lease"]["write_workspace"] replay = acquire("a", alias) assert replay["original_receipt"] == first["original_receipt"] @@ -187,77 +186,27 @@ def claim(key, operation, *options, expected=0): git("remote", "set-url", "origin", "https://github.com/example/project.git") (b / "nested").mkdir() monkeypatch.chdir(b / "nested") - overlap = { - "todo_id": "todo_ordinary_a", "owner": "agent-a", "write_scopes": peer_scopes, - "reason": "independent_worktree_integration_overlap", - } if large_peer_scope: preview = claim("b", "preview-b", "--thin", "--dry-run") - assert preview["integration_overlap_advisories"] == [overlap] + assert "integration_overlap_advisories" not in preview assert "integration_overlap_detail_command" not in preview accepted = claim("b", "claim-b", "--thin") assert accepted["execution_managed"] - if large_peer_scope: - assert accepted["integration_overlap_advisories"] == [{ - "todo_id": "todo_ordinary_a", "owner": "agent-a", "write_scope_count": len(peer_scopes), - "reason": "independent_worktree_integration_overlap", - }] - command = shlex.split(accepted["integration_overlap_detail_command"]) - assert command[-7:] == ["todo", "receipt", "--goal-id", goal, "--operation-id", "claim-b", "--thin"] - observed = subprocess.run(command, capture_output=True, text=True, timeout=30, check=True) - detail = json.loads(observed.stdout) - assert detail["ok"] and detail["status"] == "found" - assert detail["thin"] is True - assert detail["provider_revision"] == accepted["provider_revision"] - original = subprocess.run(command[:-1], capture_output=True, text=True, timeout=30, check=True) - full_receipt = json.loads(original.stdout)["receipts"][0] - detail_receipt = detail["receipts"][0] - assert detail_receipt == {**full_receipt, "result": { - "claim_operation_id": "claim-b", - "todo_id": "todo_ordinary_b", - "integration_overlap_advisories": [overlap], - }} - assert full_receipt["result"]["lease"]["owner"] == "agent-b" - assert len(observed.stdout.encode("utf-8")) < len(original.stdout.encode("utf-8")) - else: - assert accepted["integration_overlap_advisories"] == [overlap] - assert "integration_overlap_detail_command" not in accepted + assert "integration_overlap_advisories" not in accepted + assert "integration_overlap_detail_command" not in accepted second = cli(["task-lease", "inspect"], "b")["lease"] assert "write_workspace" in first assert first["write_workspace"] != second["write_workspace"] + assert second["write_scopes"] == [] assert str(tmp_path) not in json.dumps(second) assert cli(["todo", "list"], "b")["todo"]["claimed_by"] == "agent-b" replay = claim("b", "claim-b") assert replay["status"] == "replayed" - assert replay["integration_overlap_advisories"] == [overlap] + assert "integration_overlap_advisories" not in replay assert cli(["task-lease", "inspect"], "b")["lease"] == second released = cli(["task-lease", "release"], "b", "--owner", "agent-b", "--idempotency-key", second["idempotency_key"], "--expected-version", str(second["version"])) assert released["released"] - if large_peer_scope: - observed = subprocess.run(command, capture_output=True, text=True, timeout=30, check=True) - late = json.loads(observed.stdout) - assert released["provider_revision"] != detail["provider_revision"] - assert late == detail - original = subprocess.run(command[:-1], capture_output=True, text=True, timeout=30, check=True) - assert json.loads(original.stdout)["receipts"][0] == full_receipt - missing = subprocess.run( - [*command[:-2], "missing-claim", "--thin"], capture_output=True, text=True, timeout=30, check=True, - ) - assert json.loads(missing.stdout)["status"] == "missing" - subprocess.run([ - *command[:-7], "todo", "add", "--goal-id", goal, "--role", "agent", - "--text", "A different operation", "--operation-id", "add-task", - ], capture_output=True, text=True, timeout=30, check=True) - original_add = subprocess.run( - [*command[:-2], "add-task"], capture_output=True, text=True, timeout=30, check=True, - ) - assert json.loads(original_add.stdout)["status"] == "found" - rejected = subprocess.run( - [*command[:-2], "add-task", "--thin"], capture_output=True, text=True, timeout=30, - ) - assert rejected.returncode == 1 - assert "requires an exact managed claim receipt" in json.loads(rejected.stdout)["error"] assert claim("b", "claim-b", expected=1)["ok"] is False assert not cli(["task-lease", "inspect"], "b")["active"] @@ -336,10 +285,7 @@ def snapshot(): monkeypatch.chdir(a) ordinary_preview = claim("a", "independent-preview", preview=True) assert ordinary_preview["status"] == "planned" - assert ordinary_preview["integration_overlap_advisories"] == [{ - "todo_id": "todo_expiry_b", "owner": "agent-b", "write_scopes": ["src/**"], - "reason": "independent_worktree_integration_overlap", - }] + assert "integration_overlap_advisories" not in ordinary_preview refused = run(attempt, expected=1) assert refused["error_code"] == "claim_execution_unavailable" assert snapshot() == original, "recovery previews cannot acquire or renew either execution" @@ -347,7 +293,8 @@ def snapshot(): assert recovery["action"] == "claim_task", recovery assert recovery["execution_authority_granted"] is False prepared = run([*recovery["claim"]["cli_args"], "--claim-operation-id", "explicit-recovery"], route=False) - assert prepared["integration_overlap_advisories"] == ordinary_preview["integration_overlap_advisories"] + assert prepared["execution_managed"] + assert "integration_overlap_advisories" not in prepared assert run(attempt, expected=1)["recovery"]["action"] == "reconcile_lease_owner" retry = [prepared["claim_operation_id"] if arg == "expired-original" else arg for arg in attempt] assert run(retry)["ok"]