@pennixrv/trellis 0.7.2-beta.29 → 0.7.2-beta.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,295 +1,119 @@
1
1
  """Versioned controller-only worktree delegation; Paseo owns native resources."""
2
2
  from __future__ import annotations
3
3
 
4
- import hashlib
4
+ import contextlib
5
5
  import json
6
6
  import os
7
7
  from pathlib import Path
8
- import re
9
8
  import shutil
10
9
  import subprocess
11
10
  import uuid
12
- from typing import NoReturn
13
11
 
14
- from .io import read_json_checked, write_json, write_text_atomic
15
12
  from .paths import get_repo_root
16
13
 
17
- MAX_BYTES = 256 * 1024
18
- SAFE_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
19
-
20
-
21
- def fail(message: str) -> NoReturn:
22
- from .task_workflow import TaskWorkflowError
23
- raise TaskWorkflowError("TASK_DELEGATE_WITHHELD", message)
24
-
25
-
26
- def digest(value) -> str:
27
- data = value if isinstance(value, bytes) else json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()
28
- return hashlib.sha256(data).hexdigest()
29
-
30
-
31
- def read(path: Path) -> dict:
32
- if path.is_symlink() or not path.is_file() or path.stat().st_size > MAX_BYTES:
33
- fail(f"invalid bounded regular JSON file: {path}")
34
- value, reason = read_json_checked(path)
35
- if value is None:
36
- fail(f"cannot read {path}: {reason}")
37
- return value
38
-
39
-
40
- def save(path: Path, value: dict):
41
- path.parent.mkdir(parents=True, exist_ok=True)
42
- if path.is_symlink() or not write_json(path, value):
43
- fail(f"could not atomically save {path}; preserve current state")
44
-
45
-
46
- def runtime_path(root: Path, task_id: str) -> Path:
47
- if not SAFE_ID.fullmatch(task_id):
48
- fail("unsafe task identity")
49
- path = root / ".trellis/.runtime/delegation" / task_id / "record.json"
50
- if path.resolve() != path.absolute():
51
- fail("redirected delegation runtime")
52
- return path
53
-
54
-
55
- def resolve_record(root: Path, task_dir: Path, data: dict):
56
- """One resolver for current runtime and historical task-meta consumers."""
57
- path = runtime_path(root, task_dir.name)
58
- return read(path) if path.exists() else data.get("meta", {}).get("delegated_worktree_execution_record")
59
-
60
-
61
- def git(root: Path, *args: str) -> str:
62
- result = subprocess.run(["git", *args], cwd=root, capture_output=True, text=True, encoding="utf8", timeout=30)
63
- if result.returncode:
64
- fail(f"Git identity/check failed: {args[0]}")
65
- return result.stdout.strip()
66
-
67
-
68
- def identity(root: Path) -> dict:
69
- root = root.resolve(strict=True)
70
- if Path(git(root, "rev-parse", "--show-toplevel")).resolve() != root:
71
- fail("target must be the exact checkout root")
72
- return {"checkout": str(root), "common_dir": str(Path(git(root, "rev-parse", "--path-format=absolute", "--git-common-dir")).resolve())}
73
-
74
-
75
- def task_inputs(child_dir: Path, *, require_authorization: bool = True):
76
- from .task_workflow import _load, _task_dir, _state, implementation_start_ready, TaskWorkflowError
77
- from .task_continuity import assert_task_mutation_allowed
78
- child, _ = _load(child_dir)
79
- if not child.get("parent"):
80
- fail("child must be linked to an authorized controller task")
81
- parent_dir = _task_dir(child["parent"])
82
- parent, meta = _load(parent_dir)
83
- if child.get("status") not in {"planning", "in_progress"}:
84
- raise TaskWorkflowError("TASK_DELEGATE_CHILD_TERMINAL", "child task is terminal")
85
- if child_dir.name not in parent.get("children", []):
86
- fail("child links or lifecycle are invalid")
87
- assert_task_mutation_allowed(get_repo_root(), parent_dir, parent)
88
- assert_task_mutation_allowed(get_repo_root(), child_dir, child)
89
- if require_authorization and (parent.get("status") != "in_progress" or not implementation_start_ready(parent, parent_dir)):
90
- raise TaskWorkflowError("TASK_DELEGATE_IMPLEMENTATION_NOT_AUTHORIZED", "current parent implementation authorization required")
91
- return child, parent, _state(meta), parent_dir
92
-
93
-
94
- def file_ref(task_dir: Path, ref: str) -> Path:
95
- if not isinstance(ref, str) or not ref or Path(ref).is_absolute():
96
- fail("metadata reference must be a nonempty relative path")
97
- path = task_dir / ref
98
- try:
99
- path.resolve(strict=True).relative_to(task_dir.resolve())
100
- except (ValueError, OSError):
101
- fail("metadata reference must stay in the child task")
102
- if path.resolve() != path.absolute() or not path.is_file() or path.stat().st_size > MAX_BYTES:
103
- fail("metadata reference must be a bounded regular file")
104
- return path
105
-
106
-
107
- def freeze(root: Path, child_dir: Path, target: Path, branch: str | None, integration: str, settings_ref: str, requirements_ref: str, base_commit: str | None = None) -> dict:
108
- child, parent, state, _ = task_inputs(child_dir)
109
- target_identity = identity(target)
110
- settings_path, requirements_path = file_ref(child_dir, settings_ref), file_ref(child_dir, requirements_ref)
111
- settings, requirements = read(settings_path), read(requirements_path)
112
- if settings.get("version") != 1 or settings.get("provider") != "codex" or settings.get("mode") != "full-access" or not settings.get("model") or not settings.get("effort"):
113
- fail("settings v1 require explicit codex/model/effort/full-access; resolve defaults through capability first")
114
- if set(settings) - {"version", "provider", "model", "effort", "mode", "daemon_home", "sandbox", "approval", "reviewer", "context"}:
115
- fail("unknown settings field")
116
- if any(settings.get(k, "native_default") != "native_default" for k in ["sandbox", "approval", "reviewer", "context"]):
117
- fail("bottom-level permissions and context must retain native defaults")
118
- fields = {"version", "required_rules", "required_skills", "required_tools", "checks", "resources", "allowed_paths", "forbidden_paths", "setup_ref", "teamwork_permission"}
119
- if requirements.get("version") != 1 or set(requirements) - fields or not isinstance(requirements.get("allowed_paths"), list) or not requirements["allowed_paths"]:
120
- fail("requirements v1 and nonempty allowed_paths required")
121
- for key in fields - {"version", "setup_ref", "teamwork_permission"}:
122
- if key in requirements and (not isinstance(requirements[key], list) or any(not isinstance(item, str) or not item or "\0" in item for item in requirements[key])):
123
- fail(f"requirements {key} must contain nonempty strings")
124
- if requirements.get("teamwork_permission", "none") not in {"none", "read_only"}:
125
- fail("Teamwork may only be absent or read_only")
126
- if "setup_ref" in requirements:
127
- file_ref(child_dir, requirements["setup_ref"])
128
- if not isinstance(branch, str) or not branch:
129
- fail("child execution branch must be set through the native task interface")
130
- for ref in [settings_ref, requirements_ref, "prd.md"]:
131
- file_ref(child_dir, ref)
132
- git(target, "check-ref-format", "--branch", branch)
133
- git(target, "check-ref-format", "--branch", integration)
134
- if branch == integration:
135
- fail("execution branch must differ from integration branch")
136
- base = base_commit or git(target, "rev-parse", "--verify", "--end-of-options", f"{integration}^{{commit}}")
137
- git(target, "merge-base", "--is-ancestor", base, integration)
138
- role = file_ref(root, ".trellis/agents/delegated-worktree-primary-agent.md")
139
- node_method = file_ref(root, ".trellis/agents/worktree-delegation-node.md")
140
- authorization = state["implementation_authorization"]
141
- binding = {"format_version": 2, "parent_task_id": parent["id"], "child_task_id": child["id"], "parent_route_revision": state["task_route_revision"], "parent_contract_revision": authorization["contract_revision"], "approval_ref": authorization["approval_ref"], "target_locator": str(target), "integration_branch": integration, "execution_branch": branch, "base_commit": base, "contract_sha256": digest(file_ref(child_dir, "prd.md").read_bytes()), "role_sha256": digest(role.read_bytes()), "node_method_sha256": digest(node_method.read_bytes()), "setup_sha256": digest(file_ref(child_dir, requirements["setup_ref"]).read_bytes()) if requirements.get("setup_ref") else None, "settings_sha256": digest(settings_path.read_bytes()), "requirements_sha256": digest(requirements_path.read_bytes()), "settings_ref": settings_ref, "requirements_ref": requirements_ref}
142
- binding["binding_revision"] = digest(binding)
143
- return {"binding": binding, "target_identity": target_identity, "settings": settings, "requirements": requirements}
144
-
14
+ from . import worktree_delegation_contract as contract
15
+ from .worktree_delegation_contract import (
16
+ assert_worktree as assert_worktree,
17
+ attach_package as attach_package,
18
+ checkout_claim as checkout_claim,
19
+ clean_result as clean_result,
20
+ current as current,
21
+ digest as digest,
22
+ fail as fail,
23
+ file_ref as file_ref,
24
+ freeze as freeze,
25
+ git as git,
26
+ git_paths as git_paths,
27
+ identity as identity,
28
+ package_admission as package_admission,
29
+ read as read,
30
+ resolve_record as resolve_record,
31
+ reuse_source as reuse_source,
32
+ runtime_path as runtime_path,
33
+ save as save,
34
+ source_clean as source_clean,
35
+ task_inputs as task_inputs,
36
+ MAX_BYTES as MAX_BYTES,
37
+ SAFE_ID as SAFE_ID,
38
+ )
39
+
40
+
41
+ from .worktree_delegation_transport import adapter as adapter, inspection_pages as inspection_pages
42
+ from .worktree_delegation_messages import (
43
+ agent_payload as agent_payload,
44
+ candidate as candidate,
45
+ candidate_input as candidate_input,
46
+ close_native as close_native,
47
+ native_lifecycle as native_lifecycle,
48
+ owner_takeover as owner_takeover,
49
+ projection as projection,
50
+ refresh_delivery as refresh_delivery,
51
+ send_input as send_input,
52
+ )
53
+
54
+
55
+ @contextlib.contextmanager
56
+ def controller_transaction(root: Path):
57
+ """Release only the layout lock around RPC; durable intents remain authoritative."""
58
+ from .task_move import layout_lock, require_settled_layout
59
+ lock = layout_lock(root)
60
+ lock.__enter__()
61
+
62
+ def rpc(record, operation, payload):
63
+ nonlocal lock
64
+ path = runtime_path(root, record["control_task_name"])
65
+ safety = operation in {"inspect", "observe", "interrupt", "queue", "withdraw", "timeline",
66
+ "background", "stop-background", "archive-agent", "close-agent", "wait"}
67
+ from .task_workflow import _task_dir
68
+ child_dir = _task_dir(record["control_task_name"])
69
+ latest, _ = current(root, child_dir, require_authorization=not safety)
70
+ identity_keys = ("binding", "attempt_id", "workspace_id", "agent_id", "worktree_path")
71
+ if any(latest.get(key) != record.get(key) for key in identity_keys):
72
+ fail("controller mapping changed before RPC; do not overwrite it")
73
+ if not safety and latest.get("status") == "retired":
74
+ fail("retired package cannot allocate resources or send inputs")
75
+ if latest.get("cancel_requested"):
76
+ record["cancel_requested"] = True
77
+ if not safety and record.get("cancel_requested"):
78
+ fail("cancellation is pending; no additional business inputs may be sent")
79
+ expected = {key: record.get(key) for key in identity_keys}
80
+ save(path, record)
81
+ lock.__exit__(None, None, None)
82
+ lock = None
83
+ try:
84
+ observed = adapter(record, operation, payload)
85
+ finally:
86
+ lock = layout_lock(root)
87
+ lock.__enter__()
88
+ require_settled_layout(root)
89
+ latest = read(path)
90
+ if (any(latest.get(key) != value for key, value in expected.items())
91
+ or latest.get("status") == "retired" and record.get("status") != "retired"):
92
+ latest.setdefault("late_receipts", []).append({"operation": operation, "observation": observed})
93
+ save(path, latest)
94
+ fail("resource mapping changed during RPC; late receipt preserved without granting writes")
95
+ for key, value in latest.items():
96
+ if record.get(key) != value:
97
+ record[key] = value
98
+ record["last_rpc_receipt"] = {"operation": operation, "observation": observed}
99
+ save(path, record)
100
+ return observed
145
101
 
146
- def adapter(record: dict, operation: str, payload: dict):
147
- request = {"version": 1, "operation": operation, "attempt_id": record.get("attempt_id"), "binding_revision": record.get("binding", {}).get("binding_revision"), "daemon_selector": {"home": record["settings"].get("daemon_home")} if record["settings"].get("daemon_home") else {}, "payload": payload}
148
- if record.get("daemon_identity"):
149
- request["daemon_selector"]["server_id"] = record["daemon_identity"]["server_id"]
150
102
  try:
151
- # A regular temp file bounds what the controller reads even if a broken
152
- # adapter emits excessive output. Never execute candidate-report commands.
153
- import tempfile
154
- with tempfile.TemporaryFile() as output, tempfile.TemporaryFile() as errors:
155
- result = subprocess.run(["trellis-paseo-adapter"], input=json.dumps(request).encode(), stdout=output, stderr=errors, timeout=3700 if operation == "wait" else 120)
156
- output.seek(0)
157
- raw = output.read(MAX_BYTES + 1)
158
- value = json.loads(raw) if len(raw) <= MAX_BYTES else None
159
- except (OSError, subprocess.TimeoutExpired, ValueError):
160
- fail("adapter unavailable or outcome unknown; preserve intent and reconcile; install/check trellis-paseo-adapter through Lifecycle")
161
- if not isinstance(value, dict) or value.get("version") != 1 or value.get("operation") != operation or value.get("attempt_id") != request["attempt_id"] or value.get("binding_revision") != request["binding_revision"]:
162
- fail("adapter response identity/shape unknown; preserve intent and reconcile")
163
- if result.returncode or value.get("ok") is not True or not isinstance(value.get("observations"), dict):
164
- fail(f"adapter {value.get('error', {}).get('category', 'outcome_unknown')}; inspect native resources before retry")
165
- observed = value["observations"]
166
- if record.get("daemon_identity") and observed.get("identity") != record["daemon_identity"]:
167
- fail("daemon identity changed; reconcile before continuing")
168
- return observed
169
-
170
-
171
- def inspection_pages(record: dict, payload: dict):
172
- cursor, seen, identity = None, set(), None
173
- while True:
174
- observed = adapter(record, "inspect", {**payload, "page_size": 100, **({"cursor": cursor} if cursor else {})})
175
- page = observed.get("page_info")
176
- if not isinstance(page, dict) or type(page.get("complete")) is not bool or "next_cursor" not in page:
177
- fail("adapter inspection pagination is unavailable or incomplete; update the optional adapter")
178
- following = page["next_cursor"]
179
- if (following is not None and (not isinstance(following, str) or not following or following in seen)
180
- or page["complete"] != (following is None) or not isinstance(observed.get("agents"), list)):
181
- fail("adapter inspection pagination is inconsistent; preserve native resources")
182
- if identity is not None and observed.get("identity") != identity:
183
- fail("daemon identity changed during inspection")
184
- identity = observed.get("identity")
185
- yield observed
186
- if following is None:
187
- return
188
- seen.add(following)
189
- cursor = following
190
-
191
-
192
- def current(root: Path, child_dir: Path, *, require_authorization: bool = True) -> tuple[dict, Path]:
193
- path = runtime_path(root, child_dir.name)
194
- record = read(path)
195
- b = record["binding"]
196
- if not require_authorization:
197
- child, parent, _, _ = task_inputs(child_dir, require_authorization=False)
198
- if record.get("control_project_id") != digest(str(root).encode()) or b.get("parent_task_id") != parent["id"] or b.get("child_task_id") != child["id"] or b.get("binding_revision") != digest({k: v for k, v in b.items() if k != "binding_revision"}) or identity(Path(b["target_locator"])) != record.get("target_identity"):
199
- fail("existing controller/target binding identity does not match; preserve resources")
200
- return record, path
201
- if b.get("format_version") != 2:
202
- fail("incomplete legacy binding; inspect/interrupt and retain the old attempt before rebinding")
203
- frozen = freeze(root, child_dir, Path(b["target_locator"]), b["execution_branch"], b["integration_branch"], b["settings_ref"], b["requirements_ref"], b["base_commit"])
204
- if frozen != {k: record[k] for k in frozen}:
205
- fail("frozen input or target identity changed; preserve current attempt and rebind only after closure")
206
- return record, path
207
-
208
-
209
- def assert_worktree(record: dict):
210
- tree = Path(record["worktree_path"])
211
- actual = identity(tree)
212
- if actual["common_dir"] != record["target_identity"]["common_dir"] or git(tree, "branch", "--show-current") != record["binding"]["execution_branch"]:
213
- fail("native worktree identity does not match current binding")
214
- git(tree, "merge-base", "--is-ancestor", record["binding"]["base_commit"], "HEAD")
215
- return tree
216
-
217
-
218
- def projection(root: Path, child_dir: Path, record: dict, path: Path):
219
- b = record["binding"]
220
- sources = {"role": file_ref(root, ".trellis/agents/delegated-worktree-primary-agent.md"), "node_method": file_ref(root, ".trellis/agents/worktree-delegation-node.md"), "contract": file_ref(child_dir, "prd.md")}
221
- if record["requirements"].get("setup_ref"):
222
- sources["setup"] = file_ref(child_dir, record["requirements"]["setup_ref"])
223
- if b.get("format_version") != 2 or not SAFE_ID.fullmatch(record["attempt_id"]):
224
- fail("complete frozen binding and safe attempt identity required")
225
- snapshots = {}
226
- directory = path.parent / "inputs" / record["attempt_id"]
227
- if directory.resolve() != directory.absolute():
228
- fail("redirected frozen input directory")
229
- directory.mkdir(parents=True, exist_ok=True)
230
- for name, source in sources.items():
231
- content = source.read_bytes()
232
- if len(content) > MAX_BYTES or digest(content) != b[f"{name}_sha256"]:
233
- fail("approved source input changed before projection; preserve the attempt")
234
- snapshot = directory / f"{name}.md"
235
- if snapshot.exists() or snapshot.is_symlink():
236
- if snapshot.is_symlink() or not snapshot.is_file() or snapshot.stat().st_size > MAX_BYTES or digest(snapshot.read_bytes()) != b[f"{name}_sha256"]:
237
- fail("frozen input snapshot changed; preserve the attempt")
238
- elif not write_text_atomic(snapshot, content.decode("utf8"), newline=""):
239
- fail("could not save frozen input snapshot")
240
- snapshots[f"{name}_ref"] = str(snapshot)
241
- context = {"version": 1, "control_root": str(root), "control_task": str(child_dir), "record_ref": str(path), "attempt_id": record["attempt_id"], "binding_revision": b["binding_revision"], "binding": b, "workspace_id": record.get("workspace_id"), "agent_id": record.get("agent_id"), "target": record.get("worktree_path"), "execution_permission": record.get("execution_permission", "preparation"), **snapshots, "requirements": record["requirements"], "settings": record["settings"], "ready_path": str(Path(record["worktree_path"]) / ".trellis-delegation" / record["attempt_id"] / "ready.json"), "result_path": str(Path(record["worktree_path"]) / ".trellis-delegation" / record["attempt_id"] / "result.json")}
242
- save(path.with_name("context.json"), context)
243
- return path.with_name("context.json")
244
-
245
-
246
- def candidate(record: dict, name: str, *, current_head=True):
247
- tree = assert_worktree(record)
248
- directory = tree / ".trellis-delegation" / record["attempt_id"]
249
- path = directory / f"{name}.json"
250
- if directory.resolve() != directory or (tree / ".trellis-delegation").is_symlink():
251
- fail("redirected candidate directory")
252
- if directory.exists() and any(p.name not in {"ready.json", "result.json", "blocked.json"} or p.is_symlink() or not p.is_file() or p.stat().st_size > MAX_BYTES for p in directory.iterdir()):
253
- fail("candidate directory contains unexpected data; preserve it")
254
- if not path.exists():
255
- return None
256
- value = read(path)
257
- b = record["binding"]
258
- expected = {"version": 1, "kind": name, "attempt_id": record["attempt_id"], "binding_revision": b["binding_revision"], "base_commit": b["base_commit"], "workspace_id": record["workspace_id"], "agent_id": record["agent_id"]}
259
- if any(value.get(k) != v for k, v in expected.items()) or (current_head and value.get("head_commit") != git(tree, "rev-parse", "HEAD")) or "acceptance" in value:
260
- fail("candidate identity/head/authority does not match the current attempt")
261
- if not isinstance(value.get("observations"), dict) or not isinstance(value.get("limitations"), list):
262
- fail("candidate observations/limitations are malformed")
263
- return value
264
-
265
-
266
- def clean_result(record: dict, result: dict):
267
- tree = assert_worktree(record)
268
- base, head = record["binding"]["base_commit"], result["head_commit"]
269
- changed = git(tree, "diff", "--name-only", base, head).splitlines()
270
- commits = git(tree, "rev-list", f"{base}..{head}").splitlines()
271
- if set(changed) != set(result.get("changed_paths", [])) or set(commits) != set(result.get("source_commits", [])):
272
- fail("result commits/paths do not match native Git")
273
- import fnmatch
274
- req = record["requirements"]
275
- if any(p.startswith((".trellis-delegation/", ".trellis/tasks/", ".trellis/.runtime/")) or not any(fnmatch.fnmatchcase(p, a) for a in req["allowed_paths"]) or any(fnmatch.fnmatchcase(p, f) for f in req.get("forbidden_paths", [])) for p in changed):
276
- fail("source changes exceed the authorized paths")
277
- # No hidden committed runtime files, even if a later commit deletes them.
278
- for commit in commits:
279
- if git(tree, "diff-tree", "--no-commit-id", "--name-only", "-r", "-m", commit, "--", ".trellis-delegation", ".trellis/tasks", ".trellis/.runtime"):
280
- fail("source history modifies protected controller/runtime facts")
281
- dirty = git(tree, "status", "--porcelain", "--untracked-files=all").splitlines()
282
- allowed = {f"?? .trellis-delegation/{record['attempt_id']}/{name}.json" for name in ["ready", "result", "blocked"]}
283
- if any(line not in allowed for line in dirty):
284
- fail("source worktree has unpreserved changes")
285
- if not isinstance(result.get("checks"), list) or not isinstance(result.get("remaining"), list):
286
- fail("result checks/remaining required")
287
- return changed
103
+ require_settled_layout(root)
104
+ yield rpc
105
+ finally:
106
+ if lock is not None:
107
+ lock.__exit__(None, None, None)
288
108
 
289
109
 
290
- def prepare_agent(root: Path, child_dir: Path, record: dict, path: Path):
110
+ def prepare_agent(root: Path, child_dir: Path, record: dict, path: Path, *, rpc=None):
111
+ rpc = rpc or adapter
112
+ modern = record["binding"].get("format_version") == 3
113
+ if modern and not record.get("agent_id"):
114
+ record["agent_id"] = str(uuid.uuid4())
291
115
  context = projection(root, child_dir, record, path)
292
- role = Path(read(context)["role_ref"]).read_text(encoding="utf8")
116
+ role = Path(read(path.with_name("context.json"))["role_ref"]).read_text(encoding="utf8")
293
117
  if role.startswith("---\n"):
294
118
  role = role.split("\n---\n", 1)[1].lstrip("\n")
295
119
  codegraph = "codegraph" in record["requirements"].get("required_tools", [])
@@ -299,16 +123,26 @@ def prepare_agent(root: Path, child_dir: Path, record: dict, path: Path):
299
123
  tool_payload = {"codegraph_command": str(Path(tool).resolve(strict=True))} if tool else {}
300
124
  record["intent"] = "prepare-agent"
301
125
  save(path, record)
302
- agent = adapter(record, "prepare-agent", {"workspace_id": record["workspace_id"], "cwd": record["worktree_path"], "model": record["settings"]["model"], "effort": record["settings"]["effort"], "role": role, "context": str(context), "prompt": f"prepare:读取 {context},只准备并提交 ready.json;当前 agent_id 映射由主控落盘,身份不完整时只报告阻断。", "codegraph": codegraph, **tool_payload, "labels": {"trellis.control": record["control_project_id"], "trellis.child": record["binding"]["child_task_id"], "trellis.attempt": record["attempt_id"]}})["agent"]
126
+ creation = {"agent_id": record["agent_id"]} if modern else {"prompt": f"prepare:读取 {context},只准备并提交 ready.json;当前 agent_id 映射由主控落盘,身份不完整时只报告阻断。"}
127
+ agent = rpc(record, "prepare-agent", {"workspace_id": record["workspace_id"], "cwd": record["worktree_path"], "model": record["settings"]["model"], "effort": record["settings"]["effort"], "role": role, "context": str(context), **creation, "codegraph": codegraph, **tool_payload, "labels": {"trellis.control": record["control_project_id"], "trellis.child": record["binding"]["child_task_id"], "trellis.attempt": record["attempt_id"]}})["agent"]
303
128
  if not agent or not agent.get("id") or agent.get("workspaceId") != record["workspace_id"]:
304
129
  fail("agent creation outcome unknown; preserve intent")
130
+ if modern and agent["id"] != record["agent_id"]:
131
+ fail("created agent does not match its preallocated identity")
305
132
  record.update({"agent_id": agent["id"], "status": "running", "intent": None})
306
133
  save(path, record)
307
134
  projection(root, child_dir, record, path)
135
+ if modern:
136
+ if record.get("cancel_requested"):
137
+ close_native(record, path, cancel=True, rpc=rpc)
138
+ else:
139
+ send_input(root, child_dir, record, path, "prepare", rpc=rpc)
308
140
 
309
141
 
310
- def recover(root: Path, child_dir: Path, record: dict, path: Path, args):
311
- if not record.get("attempt_id") or not record.get("intent"):
142
+ def recover(root: Path, child_dir: Path, record: dict, path: Path, args, *, rpc=None):
143
+ rpc = rpc or adapter
144
+ modern = record["binding"].get("format_version") == 3
145
+ if not record.get("attempt_id") or (not record.get("intent") and not modern):
312
146
  fail("recovery requires an unresolved attempt intent")
313
147
  workspace_id = args.workspace_id or record.get("workspace_id")
314
148
  if not workspace_id:
@@ -316,11 +150,11 @@ def recover(root: Path, child_dir: Path, record: dict, path: Path, args):
316
150
  agent_id = args.agent_id or record.get("agent_id")
317
151
  payload = {"target": record["binding"]["target_locator"], "workspace_id": workspace_id}
318
152
  if agent_id:
319
- observed = adapter(record, "inspect", {**payload, "agent_id": agent_id})
153
+ observed = rpc(record, "inspect", {**payload, "agent_id": agent_id})
320
154
  else:
321
155
  observed = None
322
156
  found = []
323
- for page in inspection_pages(record, payload):
157
+ for page in inspection_pages(record, payload, rpc=rpc):
324
158
  if observed is None:
325
159
  observed = {key: value for key, value in page.items() if key not in {"agents", "page_info"}}
326
160
  found.extend(a for a in page["agents"] if a and a.get("labels", {}).get("trellis.attempt") == record["attempt_id"])
@@ -331,7 +165,8 @@ def recover(root: Path, child_dir: Path, record: dict, path: Path, args):
331
165
  if len(spaces) != 1 or spaces[0].get("id") != workspace_id or not spaces[0].get("workspaceDirectory"):
332
166
  fail("native workspace identity is unverified")
333
167
  adopted = {**record, "workspace_id": workspace_id, "worktree_path": str(Path(spaces[0]["workspaceDirectory"]).resolve())}
334
- assert_worktree(adopted)
168
+ if not modern:
169
+ assert_worktree(adopted)
335
170
  if record.get("workspace_id") and (record["workspace_id"] != workspace_id or record["worktree_path"] != adopted["worktree_path"]):
336
171
  fail("recovery cannot switch existing workspace mappings")
337
172
  if agent_id:
@@ -353,7 +188,35 @@ def recover(root: Path, child_dir: Path, record: dict, path: Path, args):
353
188
  fail("unknown agent creation must be mapped before any new agent is created")
354
189
  else:
355
190
  adopted["status"] = "workspace_created"
356
- evidence = {"observation": observed, "intent": record["intent"]}
191
+ evidence = {"observation": observed, "intent": record.get("intent")}
192
+ if modern:
193
+ if record.get("status") == "retired":
194
+ adopted.update({"status": "retired", "execution_permission": "none"})
195
+ if not agent_id:
196
+ fail("modern recovery requires the exact preallocated native agent identity")
197
+ if not args.execute:
198
+ return {"status": "ready", "recovery": evidence, "adopted": adopted}
199
+ if not args.reason or not args.approval_ref:
200
+ fail("explicit recovery reason and existing approval reference required")
201
+ if record.get("daemon_identity") != observed.get("identity"):
202
+ adopted.setdefault("instance_history", []).append(record.get("daemon_identity"))
203
+ adopted["daemon_identity"] = observed["identity"]
204
+ adopted.setdefault("recovery_receipts", []).append({**evidence, "reason": args.reason,
205
+ "approval_ref": args.approval_ref})
206
+ save(path, adopted)
207
+ if record.get("intent") == "send_pending":
208
+ refresh_delivery(adopted, path, rpc=rpc)
209
+ message_id = record["send_pending"]["client_message_id"]
210
+ item = next(item for item in adopted.get("inputs", []) if item["id"] == message_id)
211
+ if item.get("delivery") not in {"queued", "consumed", "withdrawn"}:
212
+ fail("unknown send remains unproven; do not replay or erase the intent")
213
+ elif record.get("intent") not in {None, "prepare-agent", "prepare-workspace", "reuse-agent"}:
214
+ fail("native stopping intent requires queue/background closure, not delivery assertions")
215
+ adopted["intent"] = None
216
+ adopted.pop("send_pending", None)
217
+ save(path, adopted)
218
+ projection(root, child_dir, adopted, path)
219
+ return adopted
357
220
  if record["intent"] in {"send_pending", "interrupt_pending", "prepare-agent"} and (not agent_id or record["intent"] != "prepare-agent"):
358
221
  if not args.delivery_evidence_ref:
359
222
  fail("controller-owned native delivery/interrupt evidence required; idle alone cannot resolve unknown delivery")
@@ -373,11 +236,29 @@ def wait_for_node(args):
373
236
  from .task_workflow import _task_dir, _task_lock
374
237
  from .task_move import layout_lock, require_settled_layout
375
238
  root = get_repo_root().resolve()
239
+ with controller_transaction(root) as rpc:
240
+ child_dir = _task_dir(args.child_task)
241
+ record_path = runtime_path(root, child_dir.name)
242
+ if record_path.exists() and read(record_path)["binding"].get("format_version") == 3:
243
+ record, path = current(root, child_dir, require_authorization=False)
244
+ record["control_task_name"] = child_dir.name
245
+ if not record.get("agent_id") or record["status"] == "retired":
246
+ fail("wait requires a current mapped agent")
247
+ observed = rpc(record, "wait", {**agent_payload(record), "timeout_ms": args.timeout_ms})
248
+ refresh_delivery(record, path, rpc=rpc)
249
+ ready = candidate(record, "ready", current_head=False)
250
+ if (ready and ready.get("missing") == [] and not record.get("intent")
251
+ and not record.get("cancel_requested")
252
+ and not any(item["stage"] != "prepare" for item in record.get("inputs", []))):
253
+ send_input(root, child_dir, record, path, "execute", rpc=rpc)
254
+ reports = {kind: candidate(record, kind, current_head=False) for kind in ("ready", "result", "blocked")}
255
+ print(json.dumps({"record": record, "observations": observed, "candidates": reports}, ensure_ascii=False))
256
+ return 0
376
257
  with layout_lock(root):
377
258
  require_settled_layout(root)
378
259
  child_dir = _task_dir(args.child_task)
379
260
  with _task_lock(child_dir):
380
- task_inputs(child_dir)
261
+ contract.task_inputs(child_dir)
381
262
  record, _ = current(root, child_dir)
382
263
  if not record.get("agent_id") or record["status"] == "retired":
383
264
  fail("wait requires a current mapped agent")
@@ -387,7 +268,7 @@ def wait_for_node(args):
387
268
  require_settled_layout(root)
388
269
  child_dir = _task_dir(args.child_task)
389
270
  with _task_lock(child_dir):
390
- task_inputs(child_dir)
271
+ contract.task_inputs(child_dir)
391
272
  latest, _ = current(root, child_dir)
392
273
  if any(latest.get(k) != record.get(k) for k in ["binding", "attempt_id", "agent_id", "workspace_id", "worktree_path"]) or latest["status"] == "retired":
393
274
  fail("wait target changed; inspect current binding instead of using stale observations")
@@ -397,17 +278,17 @@ def wait_for_node(args):
397
278
 
398
279
 
399
280
  def run(args):
400
- from .task_workflow import _task_dir, _task_lock
281
+ from .task_workflow import _task_dir
401
282
  root = get_repo_root().resolve()
402
- child_dir = _task_dir(args.child_task)
403
- with _task_lock(child_dir):
283
+ with controller_transaction(root) as rpc:
284
+ child_dir = _task_dir(args.child_task)
404
285
  path = runtime_path(root, child_dir.name)
405
286
  operation = args.command.removeprefix("delegate-")
406
287
  if operation == "inspect":
407
288
  from .task_workflow import _load
408
289
 
409
290
  child, _ = _load(child_dir)
410
- if child.get("status") in {"completed", "cancelled"}:
291
+ if child.get("status") in {"completed", "cancelled"} and not path.exists():
411
292
  record = resolve_record(root, child_dir, child)
412
293
  print(json.dumps({"record": record, "historical": True,
413
294
  "observations": {}, "candidates": {}}, ensure_ascii=False))
@@ -415,41 +296,70 @@ def run(args):
415
296
  if operation == "bind":
416
297
  if getattr(args, "result_path", None):
417
298
  fail("legacy --result-path cannot start protocol v1; reconcile old attempts first")
418
- child, _, _, _ = task_inputs(child_dir)
299
+ child, _, _, _ = contract.task_inputs(child_dir)
419
300
  previous = resolve_record(root, child_dir, child)
420
301
  if previous and previous.get("status") != "retired":
421
302
  fail("an existing attempt is not retired; inspect/reconcile instead of rebinding")
422
303
  if not args.target_repo or not args.integration_branch or not args.settings_ref or not args.requirements_ref:
423
304
  fail("explicit --target-repo, --integration-branch, --settings-ref and --requirements-ref required")
424
- record = freeze(root, child_dir, Path(args.target_repo).resolve(), child.get("branch"), args.integration_branch, args.settings_ref, args.requirements_ref)
305
+ record = freeze(root, child_dir, Path(args.target_repo).resolve(), child.get("branch"), args.integration_branch, args.settings_ref, args.requirements_ref,
306
+ target_mode=getattr(args, "target_mode", "worktree"))
307
+ attach_package(child_dir, record, args.package_ref, getattr(args, "package_id", None))
308
+ if getattr(args, "reuse_task", None):
309
+ source, source_path = reuse_source(root, args.reuse_task, record)
310
+ record["reuse_source"] = {"task": args.reuse_task, "record_ref": str(source_path),
311
+ "attempt_id": source["attempt_id"],
312
+ "binding_revision": source["binding"]["binding_revision"]}
425
313
  record.update({"status": "bound", "control_project_id": digest(str(root).encode()), "execution_permission": "preparation"})
426
314
  if previous:
427
- save(path.with_name(f"retired-{previous['attempt_id']}.json"), previous)
315
+ previous_id = previous.get("attempt_id") or previous["binding"]["binding_revision"]
316
+ save(path.with_name(f"retired-{previous_id}.json"), previous)
317
+ record["control_task_name"] = child_dir.name
428
318
  save(path, record)
429
319
  else:
430
- safety_control = operation in {"inspect", "observe", "interrupt"} or (operation == "reconcile" and not args.recover and args.disposition == "retained")
431
- _, _, state, _ = task_inputs(child_dir, require_authorization=not safety_control)
320
+ safety_control = operation in {"inspect", "observe", "interrupt"} or (operation == "reconcile" and (args.recover or args.disposition == "retained"))
321
+ _, _, state, _ = contract.task_inputs(child_dir, require_authorization=not safety_control)
432
322
  if operation == "start":
433
323
  admission = state.get("route_dependency_admission") or {}
434
324
  if admission.get("admission_state") != "ready":
435
325
  from .task_workflow import TaskWorkflowError
436
326
  raise TaskWorkflowError("TASK_DELEGATE_ADMISSION_REQUIRED", "current route dependency admission is not ready")
437
327
  record, path = current(root, child_dir, require_authorization=not safety_control)
328
+ record["control_task_name"] = child_dir.name
438
329
  b = record["binding"]
439
330
  if operation == "start":
331
+ if record.get("cancel_requested") or record.get("quarantined"):
332
+ fail("cancelled preparation cannot resume; close and retain its existing resources")
333
+ if b.get("format_version") != 3:
334
+ fail("legacy attempts support safe observation/closeout only; retire before a new approved binding")
335
+ if record["status"] == "running" and record.get("agent_id") and not record.get("intent"):
336
+ package_admission(root, child_dir, record, path)
337
+ if not record.get("inputs"):
338
+ send_input(root, child_dir, record, path, "prepare", rpc=rpc)
339
+ else:
340
+ refresh_delivery(record, path, rpc=rpc)
341
+ ready = candidate(record, "ready")
342
+ if ready and ready.get("missing") == [] and not any(item["stage"] != "prepare" for item in record["inputs"]):
343
+ send_input(root, child_dir, record, path, "execute", rpc=rpc)
344
+ print(json.dumps(record, ensure_ascii=False))
345
+ return 0
440
346
  if record["status"] == "workspace_created" and not record.get("intent"):
441
347
  assert_worktree(record)
442
- prepare_agent(root, child_dir, record, path)
348
+ package_admission(root, child_dir, record, path)
349
+ prepare_agent(root, child_dir, record, path, rpc=rpc)
443
350
  print(json.dumps(record, ensure_ascii=False))
444
351
  return 0
445
352
  if record["status"] != "bound":
446
353
  fail("attempt already exists; use inspect/observe/reconcile without creating another writer")
447
- _, _, state, _ = task_inputs(child_dir)
354
+ _, _, state, _ = contract.task_inputs(child_dir)
448
355
  admission = state.get("route_dependency_admission") or {}
449
356
  if admission.get("admission_state") != "ready" or admission.get("task_route_revision") != state["task_route_revision"] or not admission.get("evidence_refs") or not {"pennix-lifecycle", "paseo", "git"}.issubset(admission.get("dependencies", [])):
450
357
  fail("current evidenced Lifecycle/Paseo/Git admission is required")
451
- observed = adapter(record, "capability", {"cwd": b["target_locator"]})
358
+ package_admission(root, child_dir, record, path, allocate=True)
359
+ observed = rpc(record, "capability", {"cwd": b["target_locator"]})
452
360
  record["daemon_identity"] = observed["identity"]
361
+ if observed.get("features") != {"queue": True, "queue_management": True, "background_work": True, "runtime_close": True}:
362
+ fail("native queue, withdrawal, background-work and runtime-only close capabilities are required")
453
363
  models = observed.get("models", [])
454
364
  modes = observed.get("modes", [])
455
365
  if isinstance(models, dict):
@@ -462,13 +372,13 @@ def run(args):
462
372
  options = selected.get("thinkingOptions", [])
463
373
  if not any(o.get("id") == record["settings"]["effort"] for o in options):
464
374
  fail("requested effort is not supported by the selected model")
465
- for existing in inspection_pages(record, {"target": b["target_locator"]}):
375
+ for existing in inspection_pages(record, {"target": b["target_locator"]}, rpc=rpc):
466
376
  if existing.get("lifecycle", {}).get("autoArchiveAfterMerge") is not False:
467
377
  fail("native autoArchiveAfterMerge must be explicitly disabled before delegation; preserve worktrees until owner closeout")
468
378
  for agent in existing["agents"]:
469
- if agent and agent.get("status") not in {"closed", "idle"} and agent.get("cwd") and Path(agent["cwd"]).exists() and identity(Path(agent["cwd"]))["common_dir"] == record["target_identity"]["common_dir"] and git(Path(agent["cwd"]), "branch", "--show-current") == b["execution_branch"]:
379
+ if agent and agent.get("status") != "closed" and agent.get("cwd") and Path(agent["cwd"]).exists() and identity(Path(agent["cwd"]))["common_dir"] == record["target_identity"]["common_dir"] and git(Path(agent["cwd"]), "branch", "--show-current") == b["execution_branch"]:
470
380
  fail("another target writer is active; reconcile before starting")
471
- if subprocess.run(["git", "show-ref", "--verify", "--quiet", f"refs/heads/{b['execution_branch']}"], cwd=b["target_locator"]).returncode != 1:
381
+ if b.get("target_mode") != "directory" and not record.get("reuse_source") and subprocess.run(["git", "show-ref", "--verify", "--quiet", f"refs/heads/{b['execution_branch']}"], cwd=b["target_locator"]).returncode != 1:
472
382
  fail("execution branch already exists; do not create or reset it")
473
383
  for other in (root / ".trellis/.runtime/delegation").glob("*/record.json"):
474
384
  if other != path:
@@ -476,25 +386,100 @@ def run(args):
476
386
  if item.get("target_identity") == record["target_identity"] and item.get("binding", {}).get("execution_branch") == b["execution_branch"] and item.get("status") not in {"bound", "retired"}:
477
387
  fail("another controller record owns this target branch")
478
388
  record.update({"attempt_id": uuid.uuid4().hex, "status": "starting", "intent": "prepare-workspace"})
389
+ if record.get("reuse_source"):
390
+ reference = record["reuse_source"]
391
+ source, source_path = reuse_source(root, reference["task"], record)
392
+ if (str(source_path) != reference["record_ref"] or source["attempt_id"] != reference["attempt_id"]
393
+ or source["binding"]["binding_revision"] != reference["binding_revision"]):
394
+ fail("previous accepted package changed after the explicit reuse binding")
395
+ record.update({"agent_id": source["agent_id"], "workspace_id": source["workspace_id"],
396
+ "worktree_path": source["worktree_path"], "intent": "reuse-agent"})
397
+ if git(Path(record["worktree_path"]), "rev-parse", "HEAD") != b["base_commit"]:
398
+ fail("reused checkout is not at the new approved starting HEAD")
399
+ source_clean(record, path)
400
+ checkout_claim(record, path)
401
+ save(path, record)
402
+ source["reused_by"] = {"record_ref": str(path), "attempt_id": record["attempt_id"],
403
+ "binding_revision": b["binding_revision"]}
404
+ save(source_path, source)
405
+ projection(root, child_dir, record, path)
406
+ agent = rpc(record, "reuse-agent", {**agent_payload(record), "workspace_id": record["workspace_id"],
407
+ "previous_attempt_id": reference["attempt_id"],
408
+ "model": record["settings"]["model"], "effort": record["settings"]["effort"],
409
+ "labels": {"trellis.control": record["control_project_id"], "trellis.child": b["child_task_id"],
410
+ "trellis.attempt": record["attempt_id"]}})["agent"]
411
+ if agent.get("id") != record["agent_id"] or agent.get("workspaceId") != record["workspace_id"]:
412
+ fail("native reuse outcome is unknown; preserve the new binding and intent")
413
+ record.update({"status": "running", "intent": None})
414
+ save(path, record)
415
+ send_input(root, child_dir, record, path, "prepare", rpc=rpc)
416
+ print(json.dumps(record, ensure_ascii=False))
417
+ return 0
418
+ if b.get("target_mode") == "directory":
419
+ tree = Path(b["target_locator"])
420
+ if git(tree, "rev-parse", "HEAD") != b["base_commit"]:
421
+ fail("directory entry requires the exact approved HEAD")
422
+ source_clean(record, path)
423
+ checkout_claim(record, path)
479
424
  save(path, record)
480
- workspace = adapter(record, "prepare-workspace", {"target": b["target_locator"], "branch": b["execution_branch"], "base_commit": b["base_commit"], "title": f"trellis-{record['attempt_id']}"})["workspace"]
425
+ workspace = rpc(record, "prepare-workspace", {"target": b["target_locator"], "target_mode": b.get("target_mode", "worktree"), "branch": b["execution_branch"], "base_commit": b["base_commit"], "title": f"trellis-{record['attempt_id']}"})["workspace"]
481
426
  if not isinstance(workspace, dict) or not workspace.get("id") or not workspace.get("workspaceDirectory"):
482
427
  fail("workspace creation outcome unknown; preserve intent")
483
- record.update({"workspace_id": workspace["id"], "worktree_path": str(Path(workspace["workspaceDirectory"]).resolve()), "status": "workspace_created"})
428
+ record.update({"workspace_id": workspace["id"], "worktree_path": str(Path(workspace["workspaceDirectory"]).resolve()),
429
+ "status": "workspace_created", "intent": None})
484
430
  save(path, record)
485
431
  assert_worktree(record)
486
- prepare_agent(root, child_dir, record, path)
432
+ if b.get("target_mode") != "directory":
433
+ checkout_claim(record, path)
434
+ save(path, record)
435
+ if record.get("cancel_requested"):
436
+ print(json.dumps(record, ensure_ascii=False))
437
+ return 0
438
+ package_admission(root, child_dir, record, path)
439
+ prepare_agent(root, child_dir, record, path, rpc=rpc)
487
440
  elif operation in {"inspect", "observe", "interrupt"}:
441
+ if b.get("format_version") == 3 and operation == "interrupt":
442
+ if not record.get("agent_id") or record.get("intent") in {"prepare-workspace", "prepare-agent"}:
443
+ if record.get("intent"):
444
+ record.update({"cancel_requested": True, "quarantined": True, "execution_permission": "none"})
445
+ save(path, record)
446
+ print(json.dumps(record, ensure_ascii=False))
447
+ return 0
448
+ fail("no mapped agent to interrupt; retain an unstarted binding")
449
+ was_retired = record.get("status") == "retired"
450
+ if was_retired:
451
+ if record.get("reused_by"):
452
+ fail("native Agent was transferred to another approved package; use its current owner")
453
+ observed = rpc(record, "inspect", {"agent_id": record["agent_id"]})
454
+ matches = [agent for agent in observed.get("agents", []) if agent.get("id") == record["agent_id"]]
455
+ if (len(matches) != 1 or matches[0].get("labels", {}).get("trellis.attempt") != record["attempt_id"]
456
+ or matches[0].get("labels", {}).get("trellis.control") != record["control_project_id"]):
457
+ fail("historical resource is no longer owned by this attempt")
458
+ checkout_claim(record, path)
459
+ record["closure_recheck_pending"] = True
460
+ save(path, record)
461
+ close_native(record, path, cancel=True, rpc=rpc)
462
+ if was_retired:
463
+ checkout_claim(record, path, release=True)
464
+ record["closure_evidence"]["native_closure"] = record["native_closure"]
465
+ record.pop("closure_recheck_pending", None)
466
+ save(path, record)
467
+ print(json.dumps(record, ensure_ascii=False))
468
+ return 0
488
469
  if operation == "interrupt":
470
+ if not record.get("agent_id"):
471
+ fail("no mapped agent to interrupt; retain an unstarted binding without creating a cancel intent")
489
472
  if record.get("intent"):
490
473
  fail("resolve prior intent before interrupt; native emergency cancellation remains available")
491
474
  record["intent"] = "interrupt_pending"
492
475
  save(path, record)
493
- observations = adapter(record, "interrupt" if operation == "interrupt" else "observe" if record.get("agent_id") else "inspect", {"agent_id": record["agent_id"], "cwd": record["worktree_path"]} if record.get("agent_id") else {"target": b["target_locator"], **({"workspace_id": record["workspace_id"]} if record.get("workspace_id") else {})})
476
+ observations = rpc(record, "interrupt" if operation == "interrupt" else "observe" if record.get("agent_id") else "inspect", {"agent_id": record["agent_id"], "cwd": record["worktree_path"]} if record.get("agent_id") else {"target": b["target_locator"], **({"workspace_id": record["workspace_id"]} if record.get("workspace_id") else {})})
494
477
  if operation == "interrupt":
495
478
  record.setdefault("interrupt_receipts", []).append(observations)
496
479
  record["intent"] = None
497
480
  save(path, record)
481
+ if b.get("format_version") == 3 and record.get("agent_id"):
482
+ refresh_delivery(record, path, rpc=rpc)
498
483
  reports = {name: candidate(record, name, current_head=False) for name in ["ready", "result", "blocked"]} if record.get("worktree_path") else {}
499
484
  print(json.dumps({"record": record, "observations": observations, "candidates": reports}, ensure_ascii=False))
500
485
  return 0
@@ -503,54 +488,150 @@ def run(args):
503
488
  fail("execute/followup requires a current running attempt; retired attempts cannot send")
504
489
  if record.get("intent"):
505
490
  fail("prior creation/send outcome unresolved; inspect and reconcile first")
506
- observed = adapter(record, "observe", {"agent_id": record["agent_id"], "cwd": record["worktree_path"]})["agent"]
507
- runtime = observed.get("runtimeInfo") or {}
508
- if observed.get("activeTurn") or observed.get("status") != "idle" or runtime.get("modeId") != "full-access" or runtime.get("model") != record["settings"]["model"] or runtime.get("thinkingOptionId") != record["settings"]["effort"]:
509
- fail("agent is active or settings are unverified/drifted")
510
- ready = candidate(record, "ready", current_head=operation == "execute")
511
- if not ready or ready.get("missing") != []:
512
- fail("current ready candidate with no missing requirements required")
513
- record["ready_evidence"] = ready
514
- record["execution_permission"] = "implementation"
515
- context = projection(root, child_dir, record, path)
516
- message = f"{operation}:重新读取 {context},按当前绑定与许可完成本包并提交 result.json。"
517
- if operation == "followup":
518
- message += file_ref(child_dir, args.instructions_ref).read_text(encoding="utf8")
519
- record["intent"] = "send_pending"
520
- record["send_pending"] = {"client_message_id": str(uuid.uuid4()), "sha256": digest(message.encode())}
521
- save(path, record)
522
- receipt = adapter(record, operation, {"agent_id": record["agent_id"], "cwd": record["worktree_path"], "prompt": message, "client_message_id": record["send_pending"]["client_message_id"]})
523
- record.setdefault("followup_receipts", []).append({**record.pop("send_pending"), **receipt})
524
- record["intent"] = None
525
- save(path, record)
491
+ if b.get("format_version") == 3:
492
+ refresh_delivery(record, path, rpc=rpc)
493
+ if operation == "execute":
494
+ if any(item["stage"] != "prepare" for item in record.get("inputs", [])):
495
+ fail("initial execution input already exists; use a new authorized followup")
496
+ source_clean(record, path)
497
+ instructions = file_ref(child_dir, args.instructions_ref).read_text(encoding="utf8") if operation == "followup" else ""
498
+ send_input(root, child_dir, record, path, operation, instructions, rpc=rpc)
499
+ print(json.dumps(record, ensure_ascii=False))
500
+ return 0
501
+ fail("legacy inputs have no message-scoped contract; retain before rebinding")
526
502
  elif operation == "reconcile":
527
503
  if args.recover:
528
- print(json.dumps(recover(root, child_dir, record, path, args), ensure_ascii=False))
504
+ print(json.dumps(recover(root, child_dir, record, path, args, rpc=rpc), ensure_ascii=False))
529
505
  return 0
530
506
  if record.get("status") == "retired":
507
+ if b.get("format_version") == 3 and getattr(args, "owner_result_ref", None):
508
+ print(json.dumps(owner_takeover(record, path, child_dir, args, rpc=rpc), ensure_ascii=False))
509
+ return 0
510
+ legacy_refresh = (b.get("format_version") == 2 and args.disposition == "retained"
511
+ and record.get("agent_id")
512
+ and record.get("closure_evidence", {}).get("observation", {}).get("agent", {}).get("status") != "closed")
513
+ if not legacy_refresh:
514
+ print(json.dumps(record, ensure_ascii=False)); return 0
515
+ if record.get("status") == "bound" and not any(record.get(key) for key in ["intent", "attempt_id", "workspace_id", "agent_id"]):
516
+ if args.disposition != "retained":
517
+ fail("unstarted binding can only be retained, not accepted as integrated")
518
+ evidence = {"disposition": "retained", "resource_absent": True}
519
+ if not args.execute:
520
+ print(json.dumps({"status": "ready", "evidence": evidence}, ensure_ascii=False)); return 0
521
+ if not args.reason or not args.approval_ref:
522
+ fail("explicit reason and existing approval reference required")
523
+ record.update({"status": "retired", "closure_evidence": {**evidence, "reason": args.reason, "approval_ref": args.approval_ref}})
524
+ save(path, record)
531
525
  print(json.dumps(record, ensure_ascii=False)); return 0
526
+ if record.get("intent"):
527
+ fail("unresolved native intent requires explicit recovery before retirement")
532
528
  if not record.get("agent_id"):
529
+ if b.get("format_version") == 3 and args.disposition == "retained" and record.get("workspace_id"):
530
+ pages = 0
531
+ observed_identity = None
532
+ for page in inspection_pages(record, {"target": b["target_locator"],
533
+ "workspace_id": record["workspace_id"]}, rpc=rpc):
534
+ pages += 1
535
+ observed_identity = page["identity"]
536
+ if any(agent.get("labels", {}).get("trellis.attempt") == record["attempt_id"]
537
+ and agent.get("labels", {}).get("trellis.control") == record["control_project_id"]
538
+ for agent in page["agents"]):
539
+ fail("an attempt Agent exists; map its exact identity before resource closure")
540
+ tree = Path(record["worktree_path"])
541
+ evidence = {"disposition": "retained", "native_agent_absent": True,
542
+ "agent_scan": {"complete": True, "pages": pages, "identity": observed_identity},
543
+ "preserved_worktree": str(tree), "source_state": "present" if tree.exists() else "missing",
544
+ "head_commit": git(tree, "rev-parse", "HEAD") if tree.exists() else None,
545
+ "git_status": git(tree, "status", "--porcelain", "--untracked-files=all") if tree.exists() else None}
546
+ if not args.execute:
547
+ print(json.dumps({"status": "ready", "evidence": evidence}, ensure_ascii=False))
548
+ return 0
549
+ if not args.reason or not args.approval_ref or not args.writer_evidence_ref:
550
+ fail("workspace-only retention requires explicit approval and external-writer evidence")
551
+ evidence["writer_evidence"] = file_ref(child_dir, args.writer_evidence_ref).read_text(encoding="utf8")
552
+ checkout_claim(record, path, release=True)
553
+ record.update({"status": "retired", "closure_evidence": {**evidence, "reason": args.reason,
554
+ "approval_ref": args.approval_ref}})
555
+ save(path, record)
556
+ print(json.dumps(record, ensure_ascii=False))
557
+ return 0
533
558
  fail("partial creation requires explicit native resource mapping before retirement; preserve intent")
534
- observation = adapter(record, "observe", {"agent_id": record["agent_id"], "cwd": record["worktree_path"]})
559
+ observation = rpc(record, "observe", {"agent_id": record["agent_id"], "cwd": record["worktree_path"]})
535
560
  agent = observation["agent"]
536
561
  if not agent or agent.get("activeTurn") or agent.get("status") not in {"idle", "closed"}:
537
562
  fail("native writer is active or unknown")
538
- result = candidate(record, "result")
563
+ if record.get("status") == "retired" and agent.get("status") != "closed":
564
+ fail("historical Agent must be closed natively before refreshing its closure evidence")
565
+ if b.get("format_version") == 3:
566
+ refresh_delivery(record, path, rpc=rpc)
567
+ if record["queue_evidence"]["items"]:
568
+ fail("queued inputs remain; finish or explicitly interrupt them before reconciliation")
569
+ if args.disposition == "integrated":
570
+ native_lifecycle(record, rpc=rpc)
571
+ if record.get("quarantined") or not record.get("inputs"):
572
+ fail("quarantined or inputless attempt cannot be accepted as integrated")
573
+ for item in record["inputs"]:
574
+ report = candidate(record, "ready" if item["stage"] == "prepare" else "result",
575
+ current_head=False, input_id=item["id"])
576
+ if not report:
577
+ fail("every consumed input batch needs its own candidate before acceptance")
578
+ if item["stage"] != "prepare":
579
+ git(Path(record["worktree_path"]), "merge-base", "--is-ancestor",
580
+ report["head_commit"], "HEAD")
581
+ clean_result(record, report, path)
582
+ result = candidate(record, "result") if args.disposition == "integrated" else None
539
583
  if not result and args.disposition != "retained":
540
584
  fail("bounded result and preserved source evidence required before retirement")
541
585
  if result:
542
- clean_result(record, result)
586
+ clean_result(record, result, path)
587
+ if result.get("remaining"):
588
+ fail("unresolved result work remains; retain or request an authorized followup")
543
589
  if args.disposition == "integrated":
544
590
  if result is None:
545
591
  fail("integrated closure requires a result")
546
592
  git(Path(b["target_locator"]), "merge-base", "--is-ancestor", result["head_commit"], b["integration_branch"])
547
- tree = assert_worktree(record)
548
- evidence = {"result": result, "observation": observation, "disposition": args.disposition, "preserved_worktree": str(tree), "head_commit": git(tree, "rev-parse", "HEAD"), "git_status": git(tree, "status", "--porcelain", "--untracked-files=all")}
593
+ tree = assert_worktree(record) if args.disposition == "integrated" else Path(record["worktree_path"])
594
+ if args.disposition == "retained" and tree.exists() and identity(tree)["common_dir"] != record["target_identity"]["common_dir"]:
595
+ fail("retained checkout belongs to a different Git repository; preserve the native mapping")
596
+ evidence = {"result": result, "observation": observation, "disposition": args.disposition,
597
+ "preserved_worktree": str(tree), "source_state": "present" if tree.exists() else "missing",
598
+ "head_commit": git(tree, "rev-parse", "HEAD") if tree.exists() else None,
599
+ "git_status": git(tree, "status", "--porcelain", "--untracked-files=all") if tree.exists() else None}
600
+ if b.get("format_version") == 3 and result:
601
+ evidence["acceptance_candidate"] = {"version": 1, "attempt_id": record["attempt_id"],
602
+ "binding_revision": b["binding_revision"],
603
+ "head_commit": result["head_commit"], "result_revision": digest(result)}
549
604
  if not args.execute:
550
605
  print(json.dumps({"status": "ready", "evidence": evidence}, ensure_ascii=False)); return 0
551
606
  if not args.reason or not args.approval_ref or not args.writer_evidence_ref:
552
607
  fail("reason, approval-ref and controller-owned writer-evidence-ref required; idle/cancel alone do not prove background writers stopped")
553
608
  evidence["writer_evidence"] = file_ref(child_dir, args.writer_evidence_ref).read_text(encoding="utf8")
609
+ if record.get("status") == "retired":
610
+ record["prior_closure_evidence"] = record.get("closure_evidence")
611
+ record["prior_result_evidence"] = record.get("result_evidence")
612
+ if b.get("format_version") == 3:
613
+ owner_acceptance = None
614
+ if result:
615
+ acceptance_ref = getattr(args, "acceptance_ref", None)
616
+ acceptance = read(file_ref(child_dir, acceptance_ref))
617
+ expected = evidence["acceptance_candidate"]
618
+ if acceptance != expected:
619
+ fail("owner acceptance must identify the exact current result candidate")
620
+ owner_acceptance = {**expected, "source_commits": result["source_commits"],
621
+ "acceptance_ref": acceptance_ref}
622
+ evidence["native_closure"] = close_native(record, path, cancel=False, rpc=rpc)
623
+ if result:
624
+ final_result = candidate(record, "result")
625
+ if final_result != result:
626
+ fail("source candidate changed during native closure; preserve its claim for owner review")
627
+ clean_result(record, result, path)
628
+ git(Path(b["target_locator"]), "merge-base", "--is-ancestor",
629
+ result["head_commit"], b["integration_branch"])
630
+ if owner_acceptance is not None:
631
+ record["owner_acceptance"] = owner_acceptance
632
+ checkout_claim(record, path, release=True)
633
+ evidence["result_revision"] = digest(result) if result else None
634
+ evidence.pop("result", None)
554
635
  record.update({"status": "retired", "intent": None, "result_evidence": result, "closure_evidence": {**evidence, "reason": args.reason, "approval_ref": args.approval_ref}})
555
636
  save(path, record)
556
637
  else:
@@ -564,15 +645,21 @@ def node_context() -> dict | None:
564
645
  if not raw:
565
646
  return None
566
647
  context = read(Path(raw))
648
+ if context.get("kind") == "delegation_agent_locator":
649
+ if context.get("version") != 1 or context.get("agent_id") != os.environ.get("PASEO_AGENT_ID"):
650
+ fail("stable agent locator does not match the native agent")
651
+ context = read(Path(context["context_ref"]))
567
652
  record = read(Path(context["record_ref"]))
568
- if context.get("version") != 1 or record.get("status") == "retired" or context.get("attempt_id") != record.get("attempt_id") or context.get("binding_revision") != record.get("binding", {}).get("binding_revision") or context.get("agent_id") != os.environ.get("PASEO_AGENT_ID") or not context.get("agent_id") or git(Path.cwd(), "rev-parse", "--show-toplevel") != str(Path(context.get("target", "")).resolve()):
653
+ if context.get("version") not in {1, 2} or record.get("status") == "retired" or record.get("cancel_requested") or record.get("quarantined") or context.get("attempt_id") != record.get("attempt_id") or context.get("binding_revision") != record.get("binding", {}).get("binding_revision") or context.get("agent_id") != os.environ.get("PASEO_AGENT_ID") or not context.get("agent_id") or git(Path.cwd(), "rev-parse", "--show-toplevel") != str(Path(context.get("target", "")).resolve()):
569
654
  fail("delegated context/resource/cwd is missing, stale or mismatched; do not enter ordinary controller workflow")
570
655
  assert_worktree(record)
571
656
  if context.get("execution_permission") != record.get("execution_permission") or context.get("binding") != record.get("binding") or context.get("target") != record.get("worktree_path"):
572
657
  fail("delegated execution projection is stale")
573
- control = Path(context["control_task"])
574
- child = read(control / "task.json")
575
658
  from .task_utils import resolve_task_dir
659
+ control = resolve_task_dir(Path(context["control_task"]).name, Path(context["control_root"]))
660
+ if control is None:
661
+ fail("current delegated task is missing")
662
+ child = read(control / "task.json")
576
663
  parent_dir = resolve_task_dir(child["parent"], Path(context["control_root"]))
577
664
  if parent_dir is None:
578
665
  fail("current parent task is missing")
@@ -585,7 +672,7 @@ def node_context() -> dict | None:
585
672
  from .task_workflow import implementation_start_ready
586
673
  if not implementation_start_ready(parent, parent_dir):
587
674
  fail("parent implementation contract is no longer current")
588
- if b.get("format_version") != 2:
675
+ if b.get("format_version") not in {2, 3}:
589
676
  fail("incomplete legacy binding; stop and ask the controller to retain/rebind")
590
677
  inputs = [(control, "prd.md", "contract"), (control, b["settings_ref"], "settings"), (control, b["requirements_ref"], "requirements"), (Path(context["control_root"]), ".trellis/agents/delegated-worktree-primary-agent.md", "role"), (Path(context["control_root"]), ".trellis/agents/worktree-delegation-node.md", "node_method")]
591
678
  if record["requirements"].get("setup_ref"):