@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.
@@ -8,9 +8,7 @@ import copy
8
8
  from datetime import datetime, timezone
9
9
  import hashlib
10
10
  import json
11
- import os
12
11
  import re
13
- import shutil
14
12
  import subprocess
15
13
  import sys
16
14
  from pathlib import Path
@@ -750,6 +748,7 @@ def _update(args: argparse.Namespace, task_dir: Path, data: dict, state: dict) -
750
748
  raise TaskWorkflowError("TASK_PHASE_IMPLEMENTATION_NOT_AUTHORIZED", "Task Implementation and Test Verification Phase requires a current implementation authorization")
751
749
  if data.get("status") != "in_progress":
752
750
  raise TaskWorkflowError("TASK_PHASE_IMPLEMENTATION_NOT_STARTED", "enter in_progress with task.py start before accepting implementation")
751
+ _assert_delegated_resources_closed(task_dir, data)
753
752
  if current == PHASE_IDS[4]:
754
753
  _require_current_omissions(task_dir, state)
755
754
  readiness = _required_implementation_error(data, state)
@@ -1066,9 +1065,6 @@ def design_preflight(task_dir: Path, state: dict, outcome: str | None, ref: str
1066
1065
  }
1067
1066
 
1068
1067
 
1069
- DELEGATION_DEPENDENCIES = {"pennix-lifecycle", "paseo", "git"}
1070
-
1071
-
1072
1068
  def _git_output(args: list[str], cwd: Path) -> str:
1073
1069
  code, output, error = run_git(args, cwd=cwd)
1074
1070
  if code != 0:
@@ -1102,300 +1098,6 @@ def _paseo_list(args: list[str], cwd: Path, code: str) -> list[dict]:
1102
1098
  return value
1103
1099
 
1104
1100
 
1105
- def _delegation_binding(repo_root: Path, child_dir: Path, child_data: dict, result_path: str) -> dict:
1106
- if not isinstance(result_path, str) or Path(result_path).is_absolute() or ".." in Path(result_path).parts or not result_path.startswith(".trellis/delegated-results/"):
1107
- raise TaskWorkflowError("TASK_DELEGATE_CONTRACT_INVALID", "result path must stay under .trellis/delegated-results/")
1108
- try:
1109
- contract_path = (child_dir / "prd.md").resolve(strict=True)
1110
- contract_path.relative_to(child_dir.resolve())
1111
- role_path = (repo_root / ".trellis/agents/delegated-worktree-primary-agent.md").resolve(strict=True)
1112
- role_path.relative_to((repo_root / ".trellis/agents").resolve())
1113
- if not contract_path.is_file() or not role_path.is_file() or contract_path.stat().st_size + role_path.stat().st_size > 1048576:
1114
- raise ValueError("delegated contract and role must be regular files within the size budget")
1115
- contract = contract_path.read_bytes()
1116
- role = role_path.read_bytes()
1117
- except (OSError, ValueError) as error:
1118
- raise TaskWorkflowError("TASK_DELEGATE_CONTRACT_INVALID", str(error)) from error
1119
- if not contract.strip() or not role.strip():
1120
- raise TaskWorkflowError("TASK_DELEGATE_CONTRACT_INVALID", "child PRD and delegated role must be nonempty")
1121
- return {
1122
- "contract_sha256": hashlib.sha256(contract).hexdigest(),
1123
- "role_sha256": hashlib.sha256(role).hexdigest(),
1124
- "branch": _required_text(child_data.get("branch"), "child branch"),
1125
- "base_commit": _git_output(["rev-parse", "--verify", "--end-of-options", f"{_required_text(child_data.get('base_branch'), 'child base_branch')}^{{commit}}"], repo_root),
1126
- "result_path": result_path,
1127
- }
1128
-
1129
-
1130
- def cmd_delegate_bind(args: argparse.Namespace) -> int:
1131
- try:
1132
- repo_root = get_repo_root().resolve()
1133
- child_dir = _task_dir(args.child_task)
1134
- child, _ = _load(child_dir)
1135
- if not isinstance(child.get("parent"), str) or not child["parent"].strip():
1136
- raise TaskWorkflowError("TASK_DELEGATE_PARENT_LINK_INVALID", "child task has no parent link")
1137
- parent_dir = _task_dir(child["parent"])
1138
- parent, meta = _load(parent_dir)
1139
- if child_dir.name not in parent.get("children", []) or not implementation_start_ready(parent, parent_dir):
1140
- raise TaskWorkflowError("TASK_DELEGATE_IMPLEMENTATION_NOT_AUTHORIZED", "bind only a linked child within current parent implementation authorization")
1141
- state = _state(meta)
1142
- authorization = state["implementation_authorization"]
1143
- result_path = args.result_path or f".trellis/delegated-results/{child_dir.name}.md"
1144
- binding = _delegation_binding(repo_root, child_dir, child, result_path)
1145
- binding.update({"authorization_ref": authorization["approval_ref"], "parent_contract_revision": authorization["contract_revision"], "task_route_revision": state["task_route_revision"]})
1146
- meta.setdefault("delegation_authorizations", {})[child_dir.name] = binding
1147
- _save(parent_dir / FILE_TASK_JSON, parent)
1148
- print(json.dumps(binding, ensure_ascii=False))
1149
- return 0
1150
- except TaskWorkflowError as error:
1151
- print(f"{error.code}: {error}", file=sys.stderr)
1152
- return 1
1153
-
1154
-
1155
- def cmd_delegate_start(args: argparse.Namespace) -> int:
1156
- try:
1157
- repo_root = get_repo_root().resolve()
1158
- child_dir = _task_dir(args.child_task)
1159
- child_data, _ = _load(child_dir)
1160
- parent_ref = child_data.get("parent")
1161
- if not isinstance(parent_ref, str) or not parent_ref.strip():
1162
- raise TaskWorkflowError("TASK_DELEGATE_PARENT_LINK_INVALID", "child task has no parent link")
1163
- parent_dir = _task_dir(parent_ref)
1164
- lock_dirs = sorted((parent_dir, child_dir), key=str)
1165
- with _task_lock(lock_dirs[0]), _task_lock(lock_dirs[1]):
1166
- parent_data, parent_meta = _load(parent_dir)
1167
- child_data, child_meta = _load(child_dir)
1168
- if child_data.get("parent") != parent_dir.name or child_dir.name not in parent_data.get("children", []):
1169
- raise TaskWorkflowError("TASK_DELEGATE_PARENT_LINK_INVALID", "parent and child task links do not match")
1170
- from .task_continuity import assert_task_mutation_allowed
1171
-
1172
- assert_task_mutation_allowed(repo_root, parent_dir, parent_data)
1173
- if child_data.get("status") not in {"planning", "in_progress"}:
1174
- raise TaskWorkflowError("TASK_DELEGATE_CHILD_TERMINAL", "only a planning or in-progress child task can be delegated")
1175
- if parent_data.get("status") != "in_progress" or not implementation_start_ready(parent_data, parent_dir):
1176
- raise TaskWorkflowError("TASK_DELEGATE_IMPLEMENTATION_NOT_AUTHORIZED", "parent task is not at an authorized Task Implementation and Test Verification Phase entry")
1177
-
1178
- state = _state(parent_meta)
1179
- admission = state.get("route_dependency_admission")
1180
- if not isinstance(admission, dict):
1181
- raise TaskWorkflowError("TASK_DELEGATE_ADMISSION_REQUIRED", "parent task has no current route dependency admission")
1182
- dependencies = admission.get("dependencies", [])
1183
- if (
1184
- admission.get("admission_state") != "ready"
1185
- or admission.get("task_route_revision") != state.get("task_route_revision")
1186
- or not DELEGATION_DEPENDENCIES.issubset(set(dependencies))
1187
- or not admission.get("evidence_refs")
1188
- ):
1189
- raise TaskWorkflowError("TASK_DELEGATE_ADMISSION_REQUIRED", "route dependency admission must be current, ready, evidenced, and include Pennix Lifecycle, Paseo, and Git")
1190
-
1191
- contract_path = child_dir / "prd.md"
1192
- try:
1193
- resolved_contract = contract_path.resolve(strict=True)
1194
- resolved_contract.relative_to(child_dir.resolve())
1195
- contract_bytes = resolved_contract.read_bytes()
1196
- contract = contract_bytes.decode("utf-8")
1197
- except (OSError, UnicodeError, ValueError) as error:
1198
- raise TaskWorkflowError("TASK_DELEGATE_CONTRACT_INVALID", f"child task prd.md is unavailable: {error}") from error
1199
- if not contract.strip():
1200
- raise TaskWorkflowError("TASK_DELEGATE_CONTRACT_INVALID", "child task prd.md is empty")
1201
-
1202
- branch_value = child_data.get("branch")
1203
- base_value = child_data.get("base_branch")
1204
- if not isinstance(branch_value, str) or not isinstance(base_value, str):
1205
- raise TaskWorkflowError("TASK_DELEGATE_GIT_INVALID", "child task branch and base_branch must be set")
1206
- branch = _required_text(branch_value, "child task branch")
1207
- base_branch = _required_text(base_value, "child task base_branch")
1208
- if branch == base_branch:
1209
- raise TaskWorkflowError("TASK_DELEGATE_GIT_INVALID", "child task branch and base_branch must differ")
1210
- _git_output(["check-ref-format", "--branch", branch], repo_root)
1211
- _git_output(["check-ref-format", "--branch", base_branch], repo_root)
1212
- top_level = Path(_git_output(["rev-parse", "--show-toplevel"], repo_root)).resolve()
1213
- if top_level != repo_root:
1214
- raise TaskWorkflowError("TASK_DELEGATE_GIT_INVALID", "Trellis repository root does not match the Git checkout")
1215
- base_commit = _git_output(["rev-parse", "--verify", "--end-of-options", f"{base_branch}^{{commit}}"], repo_root)
1216
- branch_exists, _, _ = run_git(["show-ref", "--verify", "--quiet", f"refs/heads/{branch}"], cwd=repo_root)
1217
- if branch_exists not in {0, 1}:
1218
- raise TaskWorkflowError("TASK_DELEGATE_GIT_INVALID", "could not check whether the child task branch already exists")
1219
-
1220
- if shutil.which("paseo") is None:
1221
- raise TaskWorkflowError("TASK_DELEGATE_PASEO_UNAVAILABLE", "Paseo CLI is not available on PATH")
1222
- try:
1223
- version = subprocess.run(["paseo", "--version"], cwd=repo_root, capture_output=True, text=True, encoding="utf-8")
1224
- except OSError as error:
1225
- raise TaskWorkflowError("TASK_DELEGATE_PASEO_UNAVAILABLE", f"could not run Paseo: {error}") from error
1226
- if version.returncode != 0:
1227
- raise TaskWorkflowError("TASK_DELEGATE_PASEO_UNAVAILABLE", (version.stderr or version.stdout).strip() or "Paseo CLI preflight failed")
1228
- _paseo_list(["agent", "ls", "--all", "--global", "--background", "--json"], repo_root, "TASK_DELEGATE_PASEO_UNAVAILABLE")
1229
- role_path = repo_root / ".trellis" / "agents" / "delegated-worktree-primary-agent.md"
1230
- try:
1231
- role = role_path.read_text(encoding="utf-8")
1232
- except (OSError, UnicodeError) as error:
1233
- raise TaskWorkflowError("TASK_DELEGATE_ROLE_MISSING", f"delegated worktree role is unavailable: {error}") from error
1234
-
1235
- authorization = state.get("implementation_authorization")
1236
- if not isinstance(authorization, dict) or not isinstance(authorization.get("approval_ref"), str):
1237
- raise TaskWorkflowError("TASK_DELEGATE_AUTHORIZATION_INVALID", "current implementation authorization is invalid")
1238
- contract_digest = hashlib.sha256(contract_bytes).hexdigest()
1239
- bindings = parent_meta.get("delegation_authorizations", {})
1240
- binding = bindings.get(child_dir.name) if isinstance(bindings, dict) else None
1241
- if not isinstance(binding, dict):
1242
- raise TaskWorkflowError("TASK_DELEGATE_CONTRACT_NOT_BOUND", "freeze this child through delegate-bind before dispatch")
1243
- actual = _delegation_binding(repo_root, child_dir, child_data, binding.get("result_path", ""))
1244
- if any(binding.get(key) != value for key, value in actual.items()) or actual["contract_sha256"] != contract_digest or actual["role_sha256"] != hashlib.sha256(role.encode("utf-8")).hexdigest() or binding.get("authorization_ref") != authorization["approval_ref"] or binding.get("parent_contract_revision") != authorization["contract_revision"] or binding.get("task_route_revision") != state["task_route_revision"]:
1245
- raise TaskWorkflowError("TASK_DELEGATE_STALE_CONTRACT", "child PRD, role, Git base, output path, or parent authorization changed; review and bind the child again")
1246
- prompt_bytes = len((role + contract).encode("utf-8"))
1247
- if prompt_bytes > (24000 if os.name == "nt" else 96000):
1248
- raise TaskWorkflowError("TASK_DELEGATE_PROMPT_TOO_LARGE", "delegated prompt exceeds the native Paseo argv budget; narrow the contract before creating resources")
1249
- previous = child_meta.get("delegated_worktree_execution_record")
1250
- reuse_workspace = False
1251
- workspace_id = None
1252
- worktree = None
1253
- if previous is not None:
1254
- if not isinstance(previous, dict):
1255
- raise TaskWorkflowError("TASK_DELEGATE_RECONCILIATION_REQUIRED", "existing execution mapping is invalid; reconcile it before starting another run")
1256
- if previous.get("authorization_ref") == authorization["approval_ref"]:
1257
- raise TaskWorkflowError("TASK_DELEGATE_REAUTHORIZATION_REQUIRED", "reconcile the prior execution and record fresh implementation authorization before retrying")
1258
- if (
1259
- previous.get("parent_task_id") != parent_dir.name
1260
- or previous.get("parent_task_route_revision") != state["task_route_revision"]
1261
- or previous.get("implementation_contract_sha256") != contract_digest
1262
- or previous.get("branch") != branch
1263
- ):
1264
- raise TaskWorkflowError("TASK_DELEGATE_RECONCILIATION_REQUIRED", "the prior execution belongs to a different route, contract, or branch; create a newly authorized child task")
1265
- previous_workspace_id = previous.get("workspace_id")
1266
- previous_worktree_path = previous.get("worktree_path")
1267
- if not isinstance(previous_workspace_id, str) or not previous_workspace_id.strip() or not isinstance(previous_worktree_path, str) or not previous_worktree_path.strip():
1268
- raise TaskWorkflowError("TASK_DELEGATE_RECONCILIATION_REQUIRED", "the prior execution mapping is incomplete; reconcile the Paseo workspace and worktree before retrying")
1269
- previous_worktree = Path(previous_worktree_path).expanduser().resolve()
1270
- agents = _paseo_list([
1271
- "agent", "ls", "--all", "--global", "--background", "--json",
1272
- "--label", f"trellis.task_id={previous.get('label_task_id', child_dir.name)}",
1273
- ], repo_root, "TASK_DELEGATE_RECONCILIATION_REQUIRED")
1274
- for agent in agents:
1275
- agent_id = agent.get("id")
1276
- if agent.get("status") != "closed":
1277
- raise TaskWorkflowError("TASK_DELEGATE_RECONCILIATION_REQUIRED", "a Paseo agent for this child task is not confirmed closed")
1278
- if agent_id == previous.get("agent_id"):
1279
- agent_cwd = agent.get("cwd")
1280
- if not isinstance(agent_cwd, str) or Path(agent_cwd).expanduser().resolve() != previous_worktree:
1281
- raise TaskWorkflowError("TASK_DELEGATE_RECONCILIATION_REQUIRED", "the recorded Paseo agent does not match the mapped worktree")
1282
- if previous.get("agent_id") and not any(agent.get("id") == previous.get("agent_id") for agent in agents):
1283
- raise TaskWorkflowError("TASK_DELEGATE_RECONCILIATION_REQUIRED", "the recorded Paseo agent is not present for reconciliation")
1284
- workspaces = _paseo_list(["workspace", "ls", "--background", "--json"], repo_root, "TASK_DELEGATE_RECONCILIATION_REQUIRED")
1285
- workspace_row = next((item for item in workspaces if item.get("workspaceId") == previous_workspace_id), None)
1286
- if workspace_row is not None:
1287
- workspace_cwd = workspace_row.get("cwd")
1288
- if not isinstance(workspace_cwd, str) or Path(workspace_cwd).expanduser().resolve() != previous_worktree or not previous_worktree.is_dir():
1289
- raise TaskWorkflowError("TASK_DELEGATE_RECONCILIATION_REQUIRED", "the recorded Paseo workspace does not match its existing worktree")
1290
- worktree = previous_worktree
1291
- worktree_root = Path(_git_output(["rev-parse", "--show-toplevel"], worktree)).resolve()
1292
- common_dir = Path(_git_output(["rev-parse", "--git-common-dir"], repo_root))
1293
- worktree_common_dir = Path(_git_output(["rev-parse", "--git-common-dir"], worktree))
1294
- common_dir = (common_dir if common_dir.is_absolute() else repo_root / common_dir).resolve()
1295
- worktree_common_dir = (worktree_common_dir if worktree_common_dir.is_absolute() else worktree / worktree_common_dir).resolve()
1296
- if (
1297
- worktree_root != worktree
1298
- or worktree_common_dir != common_dir
1299
- or _git_output(["branch", "--show-current"], worktree) != branch
1300
- or _git_output(["rev-parse", "HEAD"], worktree) != base_commit
1301
- or _git_output(["status", "--porcelain", "--untracked-files=all"], worktree)
1302
- ):
1303
- raise TaskWorkflowError("TASK_DELEGATE_RECONCILIATION_REQUIRED", "the prior worktree is not clean at the authorized branch and Git base; preserve and reconcile it before retrying")
1304
- workspace_id = previous_workspace_id
1305
- reuse_workspace = True
1306
- else:
1307
- if previous_worktree.exists() or branch_exists == 0:
1308
- raise TaskWorkflowError("TASK_DELEGATE_RECONCILIATION_REQUIRED", "the prior workspace is unavailable but its worktree or branch remains; reconcile it before rebuilding")
1309
- elif branch_exists == 0:
1310
- raise TaskWorkflowError("TASK_DELEGATE_GIT_INVALID", f"child task branch already exists: {branch}")
1311
-
1312
- record = {
1313
- "parent_task_id": parent_dir.name,
1314
- "parent_task_route_revision": state["task_route_revision"],
1315
- "authorization_ref": authorization["approval_ref"],
1316
- "implementation_contract_ref": "prd.md",
1317
- "implementation_contract_sha256": contract_digest,
1318
- "branch": branch,
1319
- "base_commit": base_commit,
1320
- "workspace_id": workspace_id,
1321
- "worktree_path": str(worktree) if worktree else None,
1322
- "agent_id": None,
1323
- "label_task_id": child_dir.name,
1324
- "role_sha256": actual["role_sha256"],
1325
- "result_path": actual["result_path"],
1326
- "status": "starting",
1327
- "started_at": datetime.now(timezone.utc).isoformat(),
1328
- }
1329
- if previous is not None:
1330
- child_meta.setdefault("delegated_worktree_execution_history", []).append(previous)
1331
- child_meta["delegated_worktree_execution_record"] = record
1332
- _save(child_dir / FILE_TASK_JSON, child_data)
1333
-
1334
- try:
1335
- if not reuse_workspace:
1336
- workspace = _paseo_json([
1337
- "workspace", "create", "--isolation", "worktree", "--path", str(repo_root),
1338
- "--mode", "branch-off", "--worktree-slug", child_dir.name,
1339
- "--new-branch", branch, "--base", base_commit,
1340
- "--title", child_data.get("title") or child_dir.name, "--json",
1341
- ], repo_root, "TASK_DELEGATE_WORKSPACE_FAILED")
1342
- if not isinstance(workspace, dict):
1343
- raise TaskWorkflowError("TASK_DELEGATE_WORKSPACE_FAILED", "Paseo returned an invalid workspace response")
1344
- workspace_id = workspace.get("workspaceId")
1345
- worktree_path = workspace.get("cwd")
1346
- if not isinstance(workspace_id, str) or not workspace_id.strip() or not isinstance(worktree_path, str) or not worktree_path.strip():
1347
- raise TaskWorkflowError("TASK_DELEGATE_WORKSPACE_FAILED", "Paseo workspace response lacks workspaceId or cwd")
1348
- worktree = Path(worktree_path).expanduser()
1349
- if not worktree.is_absolute():
1350
- worktree = repo_root / worktree
1351
- worktree = worktree.resolve()
1352
- record.update({"workspace_id": workspace_id, "worktree_path": str(worktree), "status": "workspace_created"})
1353
- _save(child_dir / FILE_TASK_JSON, child_data)
1354
- if not isinstance(worktree, Path) or not isinstance(workspace_id, str):
1355
- raise TaskWorkflowError("TASK_DELEGATE_WORKSPACE_FAILED", "Paseo workspace mapping is incomplete")
1356
- worktree_root = Path(_git_output(["rev-parse", "--show-toplevel"], worktree)).resolve()
1357
- common_dir = Path(_git_output(["rev-parse", "--git-common-dir"], repo_root))
1358
- worktree_common_dir = Path(_git_output(["rev-parse", "--git-common-dir"], worktree))
1359
- common_dir = (common_dir if common_dir.is_absolute() else repo_root / common_dir).resolve()
1360
- worktree_common_dir = (worktree_common_dir if worktree_common_dir.is_absolute() else worktree / worktree_common_dir).resolve()
1361
- if worktree_root != worktree or worktree_common_dir != common_dir:
1362
- raise TaskWorkflowError("TASK_DELEGATE_WORKSPACE_FAILED", "Paseo workspace is not a worktree of the task repository")
1363
- if _git_output(["branch", "--show-current"], worktree) != branch or _git_output(["rev-parse", "HEAD"], worktree) != base_commit:
1364
- raise TaskWorkflowError("TASK_DELEGATE_WORKSPACE_FAILED", "Paseo worktree branch or base does not match the child task")
1365
-
1366
- prompt = (
1367
- "Follow the delegated worktree role below. The child task's prd.md is the sole task-specific implementation contract; "
1368
- "the parent authorization and Git baseline are execution metadata. Do not accept task phases or change task lifecycle state.\n\n"
1369
- f"Parent task: {parent_dir.name}\nParent route revision: {state['task_route_revision']}\n"
1370
- f"Authorized contract: prd.md\nBranch: {branch}\nBase commit: {base_commit}\n\n"
1371
- f"Assigned result artifact: {actual['result_path']}\n"
1372
- f"{role}\n\n## Child task prd.md\n{contract}"
1373
- )
1374
- agent = _paseo_json([
1375
- "run", "--workspace", workspace_id, "--no-wait", "--json",
1376
- "--title", child_data.get("title") or child_dir.name,
1377
- "--label", f"trellis.task_id={child_dir.name}",
1378
- "--label", f"trellis.parent_task_id={parent_dir.name}", prompt,
1379
- ], repo_root, "TASK_DELEGATE_AGENT_START_FAILED")
1380
- if not isinstance(agent, dict):
1381
- raise TaskWorkflowError("TASK_DELEGATE_AGENT_START_FAILED", "Paseo returned an invalid agent response")
1382
- agent_id = agent.get("agentId")
1383
- if not isinstance(agent_id, str) or not agent_id.strip():
1384
- raise TaskWorkflowError("TASK_DELEGATE_AGENT_START_FAILED", "Paseo run response lacks agentId")
1385
- record.update({"agent_id": agent_id, "status": "running"})
1386
- _save(child_dir / FILE_TASK_JSON, child_data)
1387
- except TaskWorkflowError as error:
1388
- record["status"] = "reconciliation_required"
1389
- record["last_error"] = {"code": error.code, "reason": str(error)}
1390
- _save(child_dir / FILE_TASK_JSON, child_data)
1391
- raise
1392
-
1393
- print(json.dumps(record, ensure_ascii=False))
1394
- return 0
1395
- except TaskWorkflowError as error:
1396
- print(f"{error.code}: {error}", file=sys.stderr)
1397
- return 1
1398
-
1399
1101
  def cmd_cancel_task(args: argparse.Namespace) -> int:
1400
1102
  try:
1401
1103
  task_dir = _task_dir(args.task_dir)
@@ -1559,6 +1261,14 @@ def _validate_child_dispositions(
1559
1261
  raise TaskWorkflowError("TASK_PHASE_CLOSEOUT_REQUIRED", f"child task link is inconsistent: {child_id}")
1560
1262
  if choice == "integrated" and child_data.get("status") != "completed":
1561
1263
  raise TaskWorkflowError("TASK_PHASE_CLOSEOUT_REQUIRED", f"child task is not completed and integrated: {child_id}")
1264
+ if choice == "integrated":
1265
+ from .worktree_delegation import resolve_record
1266
+ delegated = resolve_record(get_repo_root(), child_dir, child_data)
1267
+ if delegated and delegated.get("binding", {}).get("format_version") == 3 and (
1268
+ delegated.get("status") != "retired"
1269
+ or delegated.get("closure_evidence", {}).get("disposition") != "integrated"
1270
+ or not delegated.get("owner_acceptance")):
1271
+ raise TaskWorkflowError("TASK_PHASE_CLOSEOUT_REQUIRED", f"child source is retained but not owner-accepted: {child_id}")
1562
1272
  if choice == "cancelled" and child_data.get("status") != "cancelled":
1563
1273
  raise TaskWorkflowError("TASK_PHASE_CLOSEOUT_REQUIRED", f"child task must be cancelled through its own flow: {child_id}")
1564
1274
  return choices
@@ -1640,6 +1350,23 @@ def _assert_delegated_record_closed(task_id: str, record) -> None:
1640
1350
  if record is None:
1641
1351
  return
1642
1352
  if isinstance(record, dict) and record.get("status") == "retired" and isinstance(record.get("closure_evidence"), dict):
1353
+ if record.get("binding", {}).get("format_version") == 2 and record.get("agent_id") and (
1354
+ record["closure_evidence"].get("observation", {}).get("agent", {}).get("status") != "closed"):
1355
+ raise TaskWorkflowError("TASK_PHASE_RESOURCE_ACTIVE", f"legacy Agent for {task_id} must be closed natively, then refreshed with retained reconciliation")
1356
+ if record.get("binding", {}).get("format_version") == 3:
1357
+ evidence = record["closure_evidence"]
1358
+ closure = evidence.get("native_closure", {})
1359
+ absent = (evidence.get("native_agent_absent") is True and not record.get("agent_id")
1360
+ and evidence.get("agent_scan", {}).get("complete") is True
1361
+ and evidence.get("agent_scan", {}).get("pages", 0) > 0)
1362
+ if record.get("intent") or record.get("safety_intent") or record.get("closure_recheck_pending") or (
1363
+ not evidence.get("resource_absent") and not absent and (
1364
+ closure.get("observation", {}).get("agent", {}).get("status") != "closed"
1365
+ or closure.get("observation", {}).get("agent", {}).get("activeTurn")
1366
+ or closure.get("queue", {}).get("items") != []
1367
+ or closure.get("background", {}).get("items") != []
1368
+ or closure.get("inputs_resolved") is not True)):
1369
+ raise TaskWorkflowError("TASK_PHASE_RESOURCE_ACTIVE", f"delegated runtime/inputs for {task_id} are not confirmed closed")
1643
1370
  return
1644
1371
  if isinstance(record, dict) and "binding" in record:
1645
1372
  raise TaskWorkflowError("TASK_PHASE_RESOURCE_ACTIVE", f"protocol v1 delegation for {task_id} must be explicitly reconciled before closing or moving")