@elvis1513/auto-coding-skill 4.2.0 → 4.2.2

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.
@@ -10,13 +10,18 @@ import contextlib
10
10
  import hashlib
11
11
  import datetime as _dt
12
12
  import fnmatch
13
+ import io
13
14
  import json
14
15
  import os
15
16
  import posixpath
16
17
  import re
18
+ import shutil
19
+ import signal
17
20
  import socket
21
+ import subprocess
18
22
  import sys
19
23
  import time
24
+ import tomllib
20
25
  import urllib.parse
21
26
  import urllib.error
22
27
  import urllib.request
@@ -29,7 +34,7 @@ from install_integrity import verify_managed_install
29
34
  from scaffold_templates import MANAGED_FRAMEWORK_DOCS, scaffold_groups, templates_for
30
35
 
31
36
 
32
- _JENKINS_CRUMB_CACHE: dict[str, dict[str, str]] = {}
37
+ _JENKINS_CRUMB_CACHE: dict[tuple[str, str], dict[str, str]] = {}
33
38
  _INVALID_PLACEHOLDERS = {"N/A", "TODO", "TBD", "CHANGEME", "CHANGE_ME", "FILL_ME", "FILL-ME", "PLACEHOLDER", "XXX", "NULL", "~"}
34
39
  _GENERATED_NOISE_PATTERNS = [
35
40
  ".local/auto-coding-skill/**",
@@ -42,6 +47,36 @@ _GENERATED_NOISE_PATTERNS = [
42
47
  ]
43
48
  _AGENT_CONTRACT_VERSION = 1
44
49
  _AGENT_CONTRACT_SCHEMA = "data/contracts/orchestration-v1.schema.json"
50
+ _FOCUSED_REVIEW_TIMEOUT_SECONDS = 90
51
+ _DEEP_REVIEW_TIMEOUT_SECONDS = 300
52
+ _REVIEW_RUNTIME_FIELDS = (
53
+ "runtime_state",
54
+ "runtime_started_at",
55
+ "runtime_finished_at",
56
+ "runtime_result_path",
57
+ "runtime_exit_code",
58
+ "runtime_command_sha256",
59
+ "runtime_receipt_path",
60
+ )
61
+ _REVIEW_OUTPUT_MAX_BYTES = 1024 * 1024
62
+ _DEEP_REVIEW_CATEGORIES = {
63
+ "api",
64
+ "auth",
65
+ "db",
66
+ "file_transfer",
67
+ "gateway",
68
+ "payment",
69
+ "prod_config",
70
+ }
71
+
72
+
73
+ class _ReviewerRuntimeTimeout(RuntimeError):
74
+ """Raised after the supervised Reviewer process group has been stopped."""
75
+
76
+ def __init__(self, stdout: str = "", stderr: str = "") -> None:
77
+ super().__init__("Reviewer runtime exceeded its assignment deadline.")
78
+ self.stdout = stdout
79
+ self.stderr = stderr
45
80
  _RECOMMENDED_FINAL_COMMAND_SECONDS = 120.0
46
81
  _RECOMMENDED_FINAL_TOTAL_SECONDS = 180.0
47
82
  _FINAL_GATE_CACHE_SCHEMA = 1
@@ -49,7 +84,7 @@ _FINAL_GATE_CACHE_ALGORITHM = "final-gate-v1"
49
84
  _WORKFLOW_MIGRATION_POLICY = Path("data/policies/workflow-migrations-v1.json")
50
85
  _FALLBACK_WORKFLOW_MIGRATION_POLICY = {
51
86
  "schema_version": 1,
52
- "managed_versions": {"agents": "4.2.0", "engineering": "4.2.0"},
87
+ "managed_versions": {"agents": "4.2.2", "engineering": "4.2.2"},
53
88
  "known_official_engineering_body_sha256": [
54
89
  "d1306cc626e8baf8c83c953b760fd771066de2bf125168eca3a7b7d6ff2b87a2",
55
90
  "305931c6edef770033a4f1970b00e5fb1c1728351856a173dbfa497daf563021",
@@ -250,27 +285,101 @@ def _run_configured_command(
250
285
  return True
251
286
 
252
287
 
253
- def _jenkins_basic_auth_headers(cfg: dict) -> dict:
288
+ def _jenkins_access_cfg(cfg: dict, component: str) -> dict:
289
+ access = cfg.get("access") or {}
290
+ jenkins = access.get("jenkins") or {}
291
+ value = jenkins.get(component) or {}
292
+ return value if isinstance(value, dict) else {}
293
+
294
+
295
+ def _configured_jenkins_components(cfg: dict) -> list[str]:
296
+ return [
297
+ component
298
+ for component in ("frontend", "backend")
299
+ if any(
300
+ _is_explicit_fill(value)
301
+ for value in _jenkins_access_cfg(cfg, component).values()
302
+ )
303
+ ]
304
+
305
+
306
+ def _require_http_url(field: str, value: object) -> str:
307
+ raw = _text(value).rstrip("/")
308
+ parsed = urllib.parse.urlparse(raw)
309
+ if not _is_explicit_fill(raw) or parsed.scheme not in {"http", "https"} or not parsed.netloc:
310
+ raise APError(f"Missing or invalid {field}; fill an http/https URL in docs/ENGINEERING.md.")
311
+ return raw
312
+
313
+
314
+ def _resolve_jenkins_component(
315
+ cfg: dict,
316
+ requested: str = "",
317
+ explicit_job_url: str = "",
318
+ ) -> str:
319
+ component = _text(requested).lower()
320
+ configured = _configured_jenkins_components(cfg)
321
+ if component:
322
+ if component not in {"frontend", "backend"}:
323
+ raise APError("Jenkins component must be frontend or backend.")
324
+ if component not in configured:
325
+ raise APError(f"Missing access.jenkins.{component} configuration.")
326
+ return component
327
+ explicit = _text(explicit_job_url).rstrip("/")
328
+ if explicit:
329
+ matches = [
330
+ candidate
331
+ for candidate in configured
332
+ if _text(_jenkins_access_cfg(cfg, candidate).get("url")).rstrip("/") == explicit
333
+ ]
334
+ if len(matches) == 1:
335
+ return matches[0]
336
+ if len(configured) == 1:
337
+ return configured[0]
338
+ if len(configured) > 1:
339
+ identities: set[tuple[str, str, str]] = set()
340
+ for candidate in configured:
341
+ lane = _jenkins_access_cfg(cfg, candidate)
342
+ try:
343
+ secret = _resolve_secret(f"access.jenkins.{candidate}", lane, "password")
344
+ except APError:
345
+ break
346
+ identities.add(
347
+ (
348
+ _text(lane.get("url")).rstrip("/"),
349
+ _text(lane.get("username")),
350
+ secret,
351
+ )
352
+ )
353
+ if len(identities) == 1:
354
+ return configured[0]
355
+ raise APError(
356
+ "Multiple access.jenkins endpoints are configured; pass --component frontend or backend."
357
+ )
358
+ return ""
359
+
360
+
361
+ def _jenkins_auth_config(cfg: dict, component: str = "") -> tuple[str, dict, str, str]:
362
+ if component:
363
+ lane = _jenkins_access_cfg(cfg, component)
364
+ if not _is_explicit_fill(lane.get("username")):
365
+ raise APError(f"Missing access.jenkins.{component}.username.")
366
+ return f"access.jenkins.{component}", lane, "username", "password"
367
+
254
368
  jenkins_cfg = (cfg.get("jenkins") or {})
255
369
  credential_pairs = [
256
370
  ("api_user", "api_password"),
257
371
  ("ui_username", "ui_password"),
258
372
  ]
259
373
  errors: list[str] = []
260
-
261
374
  for user_field, secret_field in credential_pairs:
262
375
  user = _text(jenkins_cfg.get(user_field))
263
- if not _is_explicit_fill(user):
264
- continue
265
- try:
266
- secret = _resolve_secret("jenkins", jenkins_cfg, secret_field)
267
- except APError as exc:
268
- errors.append(str(exc))
269
- continue
270
- raw = f"{user}:{secret}".encode("utf-8")
271
- auth = base64.b64encode(raw).decode("ascii")
272
- return {"Authorization": f"Basic {auth}"}
273
-
376
+ if _is_explicit_fill(user):
377
+ try:
378
+ _resolve_secret("jenkins", jenkins_cfg, secret_field)
379
+ except APError as exc:
380
+ errors.append(str(exc))
381
+ continue
382
+ return "jenkins", jenkins_cfg, user_field, secret_field
274
383
  detail = "\n- " + "\n- ".join(errors) if errors else ""
275
384
  raise APError(
276
385
  "Missing Jenkins API credentials. Configure jenkins.api_user with "
@@ -280,6 +389,15 @@ def _jenkins_basic_auth_headers(cfg: dict) -> dict:
280
389
  )
281
390
 
282
391
 
392
+ def _jenkins_basic_auth_headers(cfg: dict, component: str = "") -> dict:
393
+ section_name, section_cfg, user_field, secret_field = _jenkins_auth_config(cfg, component)
394
+ user = _text(section_cfg.get(user_field))
395
+ secret = _resolve_secret(section_name, section_cfg, secret_field)
396
+ raw = f"{user}:{secret}".encode("utf-8")
397
+ auth = base64.b64encode(raw).decode("ascii")
398
+ return {"Authorization": f"Basic {auth}"}
399
+
400
+
283
401
  def _http_error_body(exc: urllib.error.HTTPError) -> str:
284
402
  try:
285
403
  return exc.read().decode("utf-8", errors="replace").strip()
@@ -302,13 +420,14 @@ def _basic_auth_header(username: str, password: str) -> dict[str, str]:
302
420
  return {"Authorization": f"Basic {auth}"}
303
421
 
304
422
 
305
- def _jenkins_root_url(cfg: dict, job_url: str = "") -> str:
423
+ def _jenkins_root_url(cfg: dict, job_url: str = "", component: str = "") -> str:
306
424
  jenkins_cfg = (cfg.get("jenkins") or {})
307
- base_url = str(jenkins_cfg.get("base_url") or "").strip().rstrip("/")
425
+ lane_url = _text(_jenkins_access_cfg(cfg, component).get("url")) if component else ""
426
+ base_url = "" if component else str(jenkins_cfg.get("base_url") or "").strip().rstrip("/")
308
427
  if base_url:
309
428
  return base_url
310
429
 
311
- source = str(job_url or jenkins_cfg.get("job_url") or "").strip().rstrip("/")
430
+ source = str(job_url or lane_url or jenkins_cfg.get("job_url") or "").strip().rstrip("/")
312
431
  if not source:
313
432
  return ""
314
433
  if "/job/" in source:
@@ -316,23 +435,30 @@ def _jenkins_root_url(cfg: dict, job_url: str = "") -> str:
316
435
  return source
317
436
 
318
437
 
319
- def _jenkins_crumb_api_url(cfg: dict, job_url: str = "") -> str:
320
- root = _jenkins_root_url(cfg, job_url=job_url)
438
+ def _jenkins_crumb_api_url(cfg: dict, job_url: str = "", component: str = "") -> str:
439
+ root = _jenkins_root_url(cfg, job_url=job_url, component=component)
321
440
  if not root:
322
441
  return ""
323
442
  return root.rstrip("/") + "/crumbIssuer/api/json"
324
443
 
325
444
 
326
- def _jenkins_crumb_headers(cfg: dict, job_url: str = "", timeout_s: int = 15) -> dict:
327
- crumb_url = _jenkins_crumb_api_url(cfg, job_url=job_url)
445
+ def _jenkins_crumb_headers(
446
+ cfg: dict,
447
+ job_url: str = "",
448
+ timeout_s: int = 15,
449
+ component: str = "",
450
+ ) -> dict:
451
+ crumb_url = _jenkins_crumb_api_url(cfg, job_url=job_url, component=component)
328
452
  if not crumb_url:
329
453
  return {}
330
- cached = _JENKINS_CRUMB_CACHE.get(crumb_url)
454
+ _, auth_cfg, user_field, _ = _jenkins_auth_config(cfg, component)
455
+ cache_key = (crumb_url, _text(auth_cfg.get(user_field)))
456
+ cached = _JENKINS_CRUMB_CACHE.get(cache_key)
331
457
  if cached:
332
458
  return dict(cached)
333
459
 
334
460
  headers = {"Accept": "application/json"}
335
- headers.update(_jenkins_basic_auth_headers(cfg))
461
+ headers.update(_jenkins_basic_auth_headers(cfg, component))
336
462
  req = urllib.request.Request(crumb_url, headers=headers, method="GET")
337
463
  try:
338
464
  with urllib.request.urlopen(req, timeout=timeout_s) as resp:
@@ -359,13 +485,19 @@ def _jenkins_crumb_headers(cfg: dict, job_url: str = "", timeout_s: int = 15) ->
359
485
  return {}
360
486
 
361
487
  crumb_headers = {field: crumb}
362
- _JENKINS_CRUMB_CACHE[crumb_url] = crumb_headers
488
+ _JENKINS_CRUMB_CACHE[cache_key] = crumb_headers
363
489
  return dict(crumb_headers)
364
490
 
365
491
 
366
- def _jenkins_api_get_json(url: str, cfg: dict, timeout_s: int = 15, allow_404: bool = False) -> Optional[dict]:
492
+ def _jenkins_api_get_json(
493
+ url: str,
494
+ cfg: dict,
495
+ timeout_s: int = 15,
496
+ allow_404: bool = False,
497
+ component: str = "",
498
+ ) -> Optional[dict]:
367
499
  headers = {"Accept": "application/json"}
368
- headers.update(_jenkins_basic_auth_headers(cfg))
500
+ headers.update(_jenkins_basic_auth_headers(cfg, component))
369
501
  req = urllib.request.Request(url, headers=headers, method="GET")
370
502
  try:
371
503
  with urllib.request.urlopen(req, timeout=timeout_s) as resp:
@@ -375,7 +507,12 @@ def _jenkins_api_get_json(url: str, cfg: dict, timeout_s: int = 15, allow_404: b
375
507
  if exc.code == 404 and allow_404:
376
508
  return None
377
509
  if exc.code == 403:
378
- crumb_headers = _jenkins_crumb_headers(cfg, job_url=url, timeout_s=timeout_s)
510
+ crumb_headers = _jenkins_crumb_headers(
511
+ cfg,
512
+ job_url=url,
513
+ timeout_s=timeout_s,
514
+ component=component,
515
+ )
379
516
  if crumb_headers:
380
517
  retry_headers = dict(headers)
381
518
  retry_headers.update(crumb_headers)
@@ -483,12 +620,21 @@ def _jenkins_branch_job_urls(root_job_url: str, branch_name: str) -> List[str]:
483
620
  return urls
484
621
 
485
622
 
486
- def _resolve_jenkins_job_url(cfg: dict, job_name: str = "", job_url: str = "") -> str:
623
+ def _resolve_jenkins_job_url(
624
+ cfg: dict,
625
+ job_name: str = "",
626
+ job_url: str = "",
627
+ component: str = "",
628
+ ) -> str:
487
629
  jenkins_cfg = (cfg.get("jenkins") or {})
488
630
  explicit_url = str(job_url or "").strip()
489
631
  requested_name = str(job_name or "").strip()
490
- configured_url = str(jenkins_cfg.get("job_url") or "").strip()
491
- base_url = str(jenkins_cfg.get("base_url") or "").strip()
632
+ configured_url = (
633
+ _text(_jenkins_access_cfg(cfg, component).get("url"))
634
+ if component
635
+ else str(jenkins_cfg.get("job_url") or "").strip()
636
+ )
637
+ base_url = _jenkins_root_url(cfg, component=component)
492
638
 
493
639
  if explicit_url:
494
640
  return explicit_url.rstrip("/")
@@ -497,13 +643,13 @@ def _resolve_jenkins_job_url(cfg: dict, job_name: str = "", job_url: str = "") -
497
643
  return _jenkins_job_url_from_name(base_url, requested_name)
498
644
  raise APError(
499
645
  f"Cannot resolve Jenkins job URL for job '{requested_name}'. "
500
- "Pass --job-url, or fill jenkins.base_url in docs/ENGINEERING.md."
646
+ "Pass --job-url, or fill the selected Jenkins endpoint in docs/ENGINEERING.md."
501
647
  )
502
648
  if configured_url:
503
649
  return configured_url.rstrip("/")
504
650
  raise APError(
505
- "Missing Jenkins job location. Fill jenkins.job_url in docs/ENGINEERING.md, "
506
- "or pass --job-url / --job-name explicitly."
651
+ "Missing Jenkins job location. Fill access.jenkins.<component>.url or "
652
+ "legacy jenkins.job_url, or pass --job-url / --job-name explicitly."
507
653
  )
508
654
 
509
655
 
@@ -515,6 +661,7 @@ def _resolve_jenkins_job_candidates(
515
661
  job_url: str = "",
516
662
  multibranch_root_job: str = "",
517
663
  branch_name: str = "",
664
+ component: str = "",
518
665
  ) -> List[str]:
519
666
  jenkins_cfg = (cfg.get("jenkins") or {})
520
667
  effective_branch = str(branch_name or "").strip()
@@ -526,25 +673,36 @@ def _resolve_jenkins_job_candidates(
526
673
 
527
674
  explicit_url = str(job_url or "").strip()
528
675
  explicit_name = str(job_name or "").strip()
529
- configured_url = str(jenkins_cfg.get("job_url") or "").strip()
676
+ configured_url = (
677
+ _text(_jenkins_access_cfg(cfg, component).get("url"))
678
+ if component
679
+ else str(jenkins_cfg.get("job_url") or "").strip()
680
+ )
530
681
 
531
682
  if effective_branch:
532
683
  if explicit_url:
533
684
  return _jenkins_branch_job_urls(explicit_url, effective_branch)
534
685
  if effective_root:
535
- base_url = str(jenkins_cfg.get("base_url") or "").strip()
686
+ base_url = _jenkins_root_url(cfg, component=component)
536
687
  return _jenkins_branch_job_urls(_jenkins_job_url_from_name(base_url, effective_root), effective_branch)
537
688
  if explicit_name:
538
- base_url = str(jenkins_cfg.get("base_url") or "").strip()
689
+ base_url = _jenkins_root_url(cfg, component=component)
539
690
  return _jenkins_branch_job_urls(_jenkins_job_url_from_name(base_url, explicit_name), effective_branch)
540
691
  if configured_url:
541
692
  return _jenkins_branch_job_urls(configured_url, effective_branch)
542
693
  raise APError(
543
694
  "Missing Jenkins multibranch root job location. Pass --job-url / --job-name together with "
544
- "--branch-name, or pass --multibranch-root-job with jenkins.base_url."
695
+ "--branch-name, or pass --multibranch-root-job with a configured Jenkins endpoint."
545
696
  )
546
697
 
547
- return [_resolve_jenkins_job_url(cfg, job_name=job_name, job_url=job_url)]
698
+ return [
699
+ _resolve_jenkins_job_url(
700
+ cfg,
701
+ job_name=job_name,
702
+ job_url=job_url,
703
+ component=component,
704
+ )
705
+ ]
548
706
 
549
707
 
550
708
  def _jenkins_build_api_url(job_url: str, build_number: int) -> str:
@@ -774,7 +932,14 @@ def _converged_engineering_document(repo: Path, template_path: Path) -> str:
774
932
  ("concurrency", "delete_remote_branch"),
775
933
  ("validation", "max_command_seconds"),
776
934
  ("validation", "max_total_seconds"),
935
+ ("structure", "enabled"),
936
+ ("structure", "enforcement"),
777
937
  ("structure", "architecture_standard"),
938
+ ("structure", "layer_rules", "enabled"),
939
+ ("structure", "layer_rules", "block"),
940
+ ("optimization", "completion_policy"),
941
+ ("optimization", "require_baseline_for_global_review"),
942
+ ("optimization", "report_accepted_debt_as_findings"),
778
943
  ("docs", "api_docs_required"),
779
944
  ]
780
945
  for field_path in preserve_scalar_paths:
@@ -812,6 +977,22 @@ def _converged_engineering_document(repo: Path, template_path: Path) -> str:
812
977
  _mapping(current_cfg.get("risk")).get("rules")
813
978
  )
814
979
  current_structure = _mapping(current_cfg.get("structure"))
980
+ for key in ("exclude", "allow_large_files", "reusable_tool_dirs"):
981
+ if isinstance(current_structure.get(key), list):
982
+ converged["structure"][key] = _string_list(current_structure.get(key))
983
+ for key in (
984
+ "max_file_lines_warn",
985
+ "max_file_lines_block",
986
+ "max_function_lines_warn",
987
+ "max_added_lines_to_large_file",
988
+ ):
989
+ value = current_structure.get(key)
990
+ if isinstance(value, int) and not isinstance(value, bool):
991
+ converged["structure"][key] = value
992
+ for key in ("require_reuse_search", "block_new_responsibility_in_large_file"):
993
+ value = current_structure.get(key)
994
+ if isinstance(value, bool):
995
+ converged["structure"][key] = value
815
996
  converged["structure"]["accepted_debt_paths"] = _string_list(
816
997
  current_structure.get("accepted_debt_paths")
817
998
  )
@@ -962,8 +1143,8 @@ def _migrate_fast_development_defaults(cfg: dict, repo: Path) -> list[str]:
962
1143
  if _text(workflow_cfg.get("completion")).lower() != "push":
963
1144
  workflow_cfg["completion"] = "push"
964
1145
  changed.append("workflow.completion")
965
- if _text(workflow_cfg.get("skill_version")) != "4.2.0":
966
- workflow_cfg["skill_version"] = "4.2.0"
1146
+ if _text(workflow_cfg.get("skill_version")) != "4.2.2":
1147
+ workflow_cfg["skill_version"] = "4.2.2"
967
1148
  changed.append("workflow.skill_version")
968
1149
 
969
1150
  commands_cfg = cfg.setdefault("commands", {})
@@ -1276,16 +1457,16 @@ def cmd_upgrade(args: argparse.Namespace) -> None:
1276
1457
  if current_agents:
1277
1458
  archive_dir = repo / "docs" / "archive" / "workflow"
1278
1459
  archive_header = (
1279
- "# Archived AGENTS.md before auto-coding-skill 4.2.0\n\n"
1460
+ "# Archived AGENTS.md before auto-coding-skill 4.2.2\n\n"
1280
1461
  "This file is historical and non-authoritative. The root AGENTS.md is fully managed.\n"
1281
1462
  "Move any still-current project facts into docs/ENGINEERING.md or docs/project/,\n"
1282
1463
  "without copying workflow rules back into the root AGENTS.md.\n\n---\n\n"
1283
1464
  )
1284
1465
  archive_content = archive_header + current_agents
1285
- archive = archive_dir / "AGENTS.pre-4.2.0.md"
1466
+ archive = archive_dir / "AGENTS.pre-4.2.2.md"
1286
1467
  if archive.exists() and archive.read_text(encoding="utf-8") != archive_content:
1287
1468
  digest = hashlib.sha256(current_agents.encode("utf-8")).hexdigest()[:12]
1288
- archive = archive_dir / f"AGENTS.pre-4.2.0-{digest}.md"
1469
+ archive = archive_dir / f"AGENTS.pre-4.2.2-{digest}.md"
1289
1470
  if not archive.exists():
1290
1471
  add_action("policy", archive, "archive", "historical and non-authoritative")
1291
1472
  if write:
@@ -2066,9 +2247,38 @@ def _active_direct_claims(repo: Path) -> list[dict]:
2066
2247
  return []
2067
2248
  active: list[dict] = []
2068
2249
  for path in sorted(root.glob("*.json")):
2069
- payload = _read_json_object(path) or {}
2070
- worktree = Path(_text(payload.get("worktree_path"))).resolve()
2071
- valid_checkout = worktree.exists() and _text(payload.get("worktree_path"))
2250
+ payload = _read_json_object(path)
2251
+ if payload is None:
2252
+ raise APError(
2253
+ f"Direct claim registry is unreadable or invalid JSON: {path}. "
2254
+ "Refusing to assume the checkout has no active writer."
2255
+ )
2256
+ try:
2257
+ schema = int(payload.get("schema") or 0)
2258
+ except (TypeError, ValueError) as exc:
2259
+ raise APError(f"Direct claim registry has an invalid schema: {path}") from exc
2260
+ claim_id = _text(payload.get("claim_id"))
2261
+ worktree_value = _text(payload.get("worktree_path"))
2262
+ owned_paths = payload.get("owned_paths")
2263
+ if (
2264
+ schema != 1
2265
+ or _text(payload.get("state")) != "active"
2266
+ or claim_id != path.stem
2267
+ or not _DIRECT_CLAIM_ID_RE.fullmatch(claim_id)
2268
+ or not _text(payload.get("owner"))
2269
+ or not _text(payload.get("base_sha"))
2270
+ or not _text(payload.get("branch"))
2271
+ or not worktree_value
2272
+ or not isinstance(owned_paths, list)
2273
+ or not owned_paths
2274
+ or not all(isinstance(item, str) and _text(item) for item in owned_paths)
2275
+ ):
2276
+ raise APError(
2277
+ f"Direct claim registry is malformed: {path}. "
2278
+ "Refusing to assume the checkout has no active writer."
2279
+ )
2280
+ worktree = Path(worktree_value).resolve()
2281
+ valid_checkout = worktree.exists()
2072
2282
  if valid_checkout:
2073
2283
  try:
2074
2284
  valid_checkout = bool(
@@ -2077,11 +2287,7 @@ def _active_direct_claims(repo: Path) -> list[dict]:
2077
2287
  )
2078
2288
  except APError:
2079
2289
  valid_checkout = False
2080
- if (
2081
- int(payload.get("schema") or 0) != 1
2082
- or _text(payload.get("state")) != "active"
2083
- or not valid_checkout
2084
- ):
2290
+ if not valid_checkout:
2085
2291
  path.unlink(missing_ok=True)
2086
2292
  continue
2087
2293
  active.append(payload)
@@ -2114,23 +2320,25 @@ def _create_direct_claim(repo: Path, cfg: dict, owned_paths: list[str], owner: s
2114
2320
  if _has_registered_active_task(repo):
2115
2321
  raise APError("A registered active task acquired repository writes.")
2116
2322
  existing = _active_direct_claims(repo)
2117
- other = [item for item in existing if _text(item.get("owner")) != _text(owner)]
2118
- if other:
2323
+ base_sha = _resolve_commit(repo, "HEAD")
2324
+ worktree_path = str(repo.resolve())
2325
+ if existing:
2119
2326
  raise APError(
2120
2327
  "Another direct writer already owns this checkout: "
2121
- + ", ".join(_text(item.get("owner")) for item in other)
2328
+ + ", ".join(
2329
+ f"{_text(item.get('owner'))}:{_text(item.get('claim_id'))}"
2330
+ for item in existing
2331
+ )
2122
2332
  )
2123
- for item in existing:
2124
- _direct_claim_path(repo, _text(item.get("claim_id"))).unlink(missing_ok=True)
2125
2333
  claim_id = uuid.uuid4().hex
2126
2334
  payload = {
2127
2335
  "schema": 1,
2128
2336
  "claim_id": claim_id,
2129
2337
  "state": "active",
2130
2338
  "owner": _text(owner),
2131
- "base_sha": _resolve_commit(repo, "HEAD"),
2339
+ "base_sha": base_sha,
2132
2340
  "branch": branch,
2133
- "worktree_path": str(repo.resolve()),
2341
+ "worktree_path": worktree_path,
2134
2342
  "owned_paths": normalized,
2135
2343
  "created_at": _now_iso(),
2136
2344
  }
@@ -2175,8 +2383,19 @@ def _has_registered_active_task(repo: Path) -> bool:
2175
2383
  if not registry.exists():
2176
2384
  return False
2177
2385
  for path in sorted(registry.glob("*.json")):
2178
- payload = _read_json_object(path) or {}
2179
- if _text(payload.get("state")) not in {"", "integrated", "cleanup-pending"}:
2386
+ payload = _read_json_object(path)
2387
+ if payload is None:
2388
+ raise APError(
2389
+ f"Task registry is unreadable or invalid JSON: {path}. "
2390
+ "Refusing to assume the checkout has no active writer."
2391
+ )
2392
+ state = _text(payload.get("state"))
2393
+ if not state:
2394
+ raise APError(
2395
+ f"Task registry has no state: {path}. "
2396
+ "Refusing to assume the checkout has no active writer."
2397
+ )
2398
+ if state not in {"integrated", "cleanup-pending"}:
2180
2399
  return True
2181
2400
  return False
2182
2401
 
@@ -2293,6 +2512,7 @@ def _validate_task_manifest(repo: Path, manifest: dict, expected_task_id: str =
2293
2512
  "pending",
2294
2513
  "approved",
2295
2514
  "changes-requested",
2515
+ "blocked",
2296
2516
  }:
2297
2517
  raise APError(f"Task {task_id} has an invalid review contract.")
2298
2518
  review_required = manifest.get("review_required", schema < 3)
@@ -2307,6 +2527,13 @@ def _validate_task_manifest(repo: Path, manifest: dict, expected_task_id: str =
2307
2527
  effective_profile = _text(manifest.get("effective_profile"))
2308
2528
  if effective_profile and effective_profile not in (_WORKFLOW_PROFILES - {"auto"}):
2309
2529
  raise APError(f"Task {task_id} has an invalid effective_profile.")
2530
+ review_depth = _text(manifest.get("review_depth"))
2531
+ if review_depth and review_depth not in {"none", "focused", "deep"}:
2532
+ raise APError(f"Task {task_id} has an invalid review_depth.")
2533
+ if "review_timeout_seconds" in manifest:
2534
+ timeout_value = manifest.get("review_timeout_seconds")
2535
+ if isinstance(timeout_value, bool) or not isinstance(timeout_value, int) or timeout_value < 0:
2536
+ raise APError(f"Task {task_id} has an invalid review_timeout_seconds.")
2310
2537
  if "design_required" in manifest and not isinstance(manifest.get("design_required"), bool):
2311
2538
  raise APError(f"Task {task_id} has an invalid design_required flag.")
2312
2539
  if "scope_history" in manifest and not isinstance(manifest.get("scope_history"), list):
@@ -2388,22 +2615,57 @@ def _checked_git_z_paths(repo: Path, command: list[str], context: str) -> list[s
2388
2615
 
2389
2616
 
2390
2617
  def _working_tree_paths(repo: Path) -> list[str]:
2391
- paths: set[str] = set()
2392
- paths.update(
2393
- _git_z_paths(
2394
- repo,
2395
- ["git", "diff", "--no-renames", "--name-only", "-z", "--diff-filter=ACDMRTUXB"],
2396
- )
2618
+ """Return one fail-closed Git status snapshot, including both rename endpoints."""
2619
+ result = run(
2620
+ [
2621
+ "git",
2622
+ "status",
2623
+ "--porcelain=v2",
2624
+ "-z",
2625
+ "--untracked-files=all",
2626
+ "--no-renames",
2627
+ ],
2628
+ cwd=repo,
2629
+ check=False,
2397
2630
  )
2398
- paths.update(
2399
- _git_z_paths(
2400
- repo,
2401
- ["git", "diff", "--cached", "--no-renames", "--name-only", "-z", "--diff-filter=ACDMRTUXB"],
2631
+ if result.returncode != 0:
2632
+ raise APError(
2633
+ "Cannot inspect working tree status; refusing a direct execution plan: "
2634
+ + (result.stderr.strip() or result.stdout.strip() or "git status failed")
2402
2635
  )
2403
- )
2404
- paths.update(
2405
- _git_z_paths(repo, ["git", "ls-files", "--others", "--exclude-standard", "-z"])
2406
- )
2636
+ paths: set[str] = set()
2637
+ entries = result.stdout.split("\0")
2638
+ index = 0
2639
+ while index < len(entries):
2640
+ entry = entries[index]
2641
+ index += 1
2642
+ if not entry:
2643
+ continue
2644
+ record_type = entry[:1]
2645
+ if record_type == "1":
2646
+ fields = entry.split(" ", 8)
2647
+ path = fields[8] if len(fields) == 9 else ""
2648
+ elif record_type == "2":
2649
+ fields = entry.split(" ", 9)
2650
+ path = fields[9] if len(fields) == 10 else ""
2651
+ if index >= len(entries) or not entries[index]:
2652
+ raise APError(
2653
+ "Cannot parse renamed Git path; refusing a direct execution plan."
2654
+ )
2655
+ paths.add(entries[index])
2656
+ index += 1
2657
+ elif record_type == "u":
2658
+ fields = entry.split(" ", 10)
2659
+ path = fields[10] if len(fields) == 11 else ""
2660
+ elif entry.startswith("? "):
2661
+ path = entry[2:]
2662
+ else:
2663
+ path = ""
2664
+ if not path:
2665
+ raise APError(
2666
+ "Cannot parse Git working tree status; refusing a direct execution plan."
2667
+ )
2668
+ paths.add(path)
2407
2669
  return sorted(path.replace("\\", "/") for path in paths if path)
2408
2670
 
2409
2671
 
@@ -2920,16 +3182,25 @@ def _reconcile_task_risk(repo: Path, cfg: dict, manifest: dict) -> None:
2920
3182
  )
2921
3183
  review_required = bool(manifest.get("review_required") or plan.get("review_required"))
2922
3184
  design_required = bool(manifest.get("design_required") or plan.get("design_required"))
3185
+ review_depth, review_timeout_seconds = _normalized_task_review_policy(
3186
+ review_required,
3187
+ manifest.get("review_depth"),
3188
+ plan.get("review_depth"),
3189
+ )
2923
3190
  escalated = (
2924
3191
  effective_profile != old_profile
2925
3192
  or review_required != bool(manifest.get("review_required"))
2926
3193
  or design_required != bool(manifest.get("design_required"))
3194
+ or review_depth != (_text(manifest.get("review_depth")) or "none")
3195
+ or review_timeout_seconds != int(manifest.get("review_timeout_seconds") or 0)
2927
3196
  )
2928
3197
  if not escalated:
2929
3198
  return
2930
3199
  manifest["effective_profile"] = effective_profile
2931
3200
  manifest["review_required"] = review_required
2932
3201
  manifest["design_required"] = design_required
3202
+ manifest["review_depth"] = review_depth
3203
+ manifest["review_timeout_seconds"] = review_timeout_seconds
2933
3204
  _invalidate_task_review(manifest, "actual changed paths raised task risk; review again")
2934
3205
  _clear_final_gate_receipt(repo)
2935
3206
  _save_task_manifest(repo, manifest)
@@ -3187,6 +3458,8 @@ _DEFAULT_FULL_PATH_PATTERNS = [
3187
3458
  "compose*.yaml",
3188
3459
  "docs/ENGINEERING.md",
3189
3460
  "docs/tools/autopipeline/**",
3461
+ "package.json",
3462
+ "**/package.json",
3190
3463
  "package-lock.json",
3191
3464
  "pnpm-lock.yaml",
3192
3465
  "yarn.lock",
@@ -3358,10 +3631,14 @@ def _default_base_ref(repo: Path) -> str:
3358
3631
  return upstream[0] if upstream else ""
3359
3632
 
3360
3633
 
3634
+ def _effective_change_base(repo: Path, base_ref: str = "") -> str:
3635
+ manifest = _active_task_manifest(repo)
3636
+ return base_ref or (_text(manifest.get("base_sha")) if manifest else "") or _default_base_ref(repo)
3637
+
3638
+
3361
3639
  def _changed_files(repo: Path, base_ref: str = "") -> list[str]:
3362
3640
  paths: list[str] = []
3363
- manifest = _active_task_manifest(repo)
3364
- effective_base = base_ref or (_text(manifest.get("base_sha")) if manifest else "") or _default_base_ref(repo)
3641
+ effective_base = _effective_change_base(repo, base_ref)
3365
3642
  if effective_base:
3366
3643
  paths.extend(_git_lines(repo, ["git", "diff", "--no-renames", "--name-only", "--diff-filter=ACDMRTUXB", f"{effective_base}...HEAD"]))
3367
3644
  paths.extend(_git_lines(repo, ["git", "diff", "--no-renames", "--name-only", "--diff-filter=ACDMRTUXB"]))
@@ -3601,6 +3878,25 @@ def _select_gate_scope(cfg: dict, requested_scope: str, paths: list[str]) -> tup
3601
3878
  return "changed", [reason], matching_rules
3602
3879
 
3603
3880
 
3881
+ def _select_structure_scope(
3882
+ cfg: dict,
3883
+ repo: Path,
3884
+ requested_scope: str,
3885
+ base_ref: str,
3886
+ ) -> str:
3887
+ """Keep repository-wide structure scans explicit while honoring them."""
3888
+ requested = _text(requested_scope).lower()
3889
+ if requested == "full":
3890
+ return "full"
3891
+ impact = _impact_summary(
3892
+ cfg,
3893
+ repo,
3894
+ requested_scope=requested,
3895
+ base_ref=base_ref,
3896
+ )
3897
+ return str(impact["selected_scope"])
3898
+
3899
+
3604
3900
  def _impact_summary(
3605
3901
  cfg: dict,
3606
3902
  repo: Path,
@@ -3756,6 +4052,9 @@ def _run_git_diff_check(repo: Path, cfg: dict) -> None:
3756
4052
 
3757
4053
  _DEFAULT_STRUCTURE_ALLOW_PATTERNS = [
3758
4054
  ".git/**",
4055
+ ".agents/archive/**",
4056
+ ".agents/agents/**",
4057
+ ".agents/managed-install.json",
3759
4058
  ".agents/skills/**",
3760
4059
  ".next/**",
3761
4060
  ".nuxt/**",
@@ -3987,10 +4286,17 @@ def _is_structure_candidate(path: str, structure_cfg: dict) -> bool:
3987
4286
 
3988
4287
  def _structure_paths_for_scope(repo: Path, scope: str, base_ref: str, structure_cfg: dict) -> list[str]:
3989
4288
  if scope == "full":
3990
- paths = _tracked_files(repo)
4289
+ paths = _unique_paths(
4290
+ _tracked_files(repo)
4291
+ + _git_lines(repo, ["git", "ls-files", "--others", "--exclude-standard"])
4292
+ )
3991
4293
  else:
3992
4294
  paths = _changed_files(repo, base_ref=base_ref)
3993
- return [path for path in paths if _is_structure_candidate(path, structure_cfg)]
4295
+ return [
4296
+ path
4297
+ for path in paths
4298
+ if (repo / path).is_file() and _is_structure_candidate(path, structure_cfg)
4299
+ ]
3994
4300
 
3995
4301
 
3996
4302
  def _read_text_lines(repo: Path, path: str) -> Optional[list[str]]:
@@ -4706,9 +5012,8 @@ def cmd_structure_check(args: argparse.Namespace) -> None:
4706
5012
  ensure_git_repo(repo)
4707
5013
  cfg = _load_cfg(repo)
4708
5014
  requested_scope = str(getattr(args, "scope", "") or "").strip().lower()
4709
- impact = _impact_summary(cfg, repo, requested_scope=requested_scope, base_ref=str(getattr(args, "base", "") or ""))
4710
- selected_scope = str(impact["selected_scope"])
4711
5015
  base_ref = str(getattr(args, "base", "") or "")
5016
+ selected_scope = _select_structure_scope(cfg, repo, requested_scope, base_ref)
4712
5017
 
4713
5018
  structure_cfg = _structure_cfg(cfg)
4714
5019
  optimization_cfg = _optimization_cfg(cfg)
@@ -4805,11 +5110,25 @@ def cmd_structure_check(args: argparse.Namespace) -> None:
4805
5110
  print(f"[structure-check] OK scope={selected_scope} inspected={inspected} warnings={len(warnings)}")
4806
5111
 
4807
5112
 
4808
- def _run_structure_check_for_gate(repo: Path, cfg: dict, selected_scope: str, base_ref: str) -> list[str]:
5113
+ def _run_structure_check_for_gate(
5114
+ repo: Path,
5115
+ cfg: dict,
5116
+ selected_scope: str,
5117
+ base_ref: str,
5118
+ *,
5119
+ deadline: Optional[float] = None,
5120
+ command_timeout_s: Optional[float] = None,
5121
+ ) -> list[str]:
4809
5122
  if not _structure_gate_enabled(cfg):
4810
5123
  return []
4811
5124
  if _configured_command(cfg, "structure_check"):
4812
- _run_configured_command(repo, cfg, "structure_check")
5125
+ timeout_s = command_timeout_s
5126
+ if deadline is not None:
5127
+ remaining = deadline - time.monotonic()
5128
+ if remaining <= 0:
5129
+ raise APError("Final changed-scope gate budget exhausted before structure check.")
5130
+ timeout_s = min(timeout_s, remaining) if timeout_s is not None else remaining
5131
+ _run_configured_command(repo, cfg, "structure_check", timeout_s=timeout_s)
4813
5132
  return ["structure_check"]
4814
5133
  cmd_structure_check(
4815
5134
  argparse.Namespace(
@@ -5132,7 +5451,7 @@ def _classify_paths(paths: list[str]) -> dict:
5132
5451
  categories.add("gateway")
5133
5452
  if "production" in words or "prod" in words and "config" in words or ".env.prod" in lower:
5134
5453
  categories.add("prod_config")
5135
- if any(token in lower for token in ["page", "component", "view", "frontend", "miniapp", ".tsx", ".jsx", ".vue", ".scss", ".css"]):
5454
+ if _is_ui_path(path):
5136
5455
  categories.add("ui")
5137
5456
  if any(token in lower for token in ["test", "spec", "__tests__"]):
5138
5457
  categories.add("test")
@@ -5143,6 +5462,17 @@ def _classify_paths(paths: list[str]) -> dict:
5143
5462
  return _classification_for_categories(categories, len(paths))
5144
5463
 
5145
5464
 
5465
+ _UI_PATH_SEGMENTS = {"frontend", "miniapp", "page", "pages", "component", "components", "view", "views"}
5466
+ _UI_FILE_SUFFIXES = {".css", ".jsx", ".scss", ".tsx", ".vue"}
5467
+
5468
+
5469
+ def _is_ui_path(path: str) -> bool:
5470
+ """Classify UI paths by exact directory semantics or UI-only extensions."""
5471
+ normalized = path.replace("\\", "/").strip("/").lower()
5472
+ directories = [part for part in normalized.split("/")[:-1] if part]
5473
+ return Path(normalized).suffix.lower() in _UI_FILE_SUFFIXES or any(part in _UI_PATH_SEGMENTS for part in directories)
5474
+
5475
+
5146
5476
  def _classification_for_categories(categories: set[str], file_count: int) -> dict:
5147
5477
  return {
5148
5478
  "categories": sorted(categories),
@@ -5223,6 +5553,79 @@ def _high_confidence_intent_categories(intent: str) -> set[str]:
5223
5553
  }
5224
5554
 
5225
5555
 
5556
+ _MECHANICAL_CHANGE_SIGNALS = (
5557
+ "mechanical", "rename only", "move only", "pure rename", "pure move", "no behavior change",
5558
+ "without behavior change", "behavior unchanged", "source of truth unchanged", "contract unchanged",
5559
+ "仅改名", "只改名", "仅移动", "只移动", "不改变行为", "行为不变", "机械同步", "机械变更", "契约不变", "事实源不变",
5560
+ )
5561
+ _SEMANTIC_CHANGE_SIGNALS = (
5562
+ "semantic change", "change behavior", "behavior change", "new behavior", "architecture change", "contract change", "schema change",
5563
+ "语义变更", "行为变更", "改变行为", "新增行为", "架构变更", "契约变更", "模式变更",
5564
+ )
5565
+
5566
+
5567
+ def _intent_change_nature(intent: str) -> str:
5568
+ value = _text(intent).lower()
5569
+ if not value:
5570
+ return "unknown"
5571
+ semantic_value = re.sub(r"\b(?:not\s+(?:a\s+)?|non[- ]?|isn't\s+)mechanical\b|(?:不是|并非|非)机械(?:变更|同步)?", " ", value)
5572
+ mechanical = [] if semantic_value != value else [signal for signal in _MECHANICAL_CHANGE_SIGNALS if signal in value]
5573
+ for signal in mechanical:
5574
+ semantic_value = semantic_value.replace(signal, " ")
5575
+ for pattern in [r"\bno\s+.{0,16}\bbehavior\s+change\b", r"不改变.{0,16}行为"]:
5576
+ if re.search(pattern, semantic_value):
5577
+ mechanical.append(pattern)
5578
+ semantic_value = re.sub(pattern, " ", semantic_value)
5579
+ if any(signal in semantic_value for signal in _SEMANTIC_CHANGE_SIGNALS) or re.search(
5580
+ r"\b(?:change|changes|changed|changing|modify|modifies|modified|modifying|alter|alters|altered|altering|update|updates|updated|updating)\b.{0,40}\b(?:behaviors?|semantics?|architecture|contracts?|schemas?)\b"
5581
+ r"|\b(?:behaviors?|semantics?|architecture|contracts?|schemas?)\b.{0,24}\b(?:change|changes|changed|changing)\b|(?:修改|调整|改变|新增|更新).{0,32}(?:行为|语义|架构|契约|模式)|(?:行为|语义|架构|契约|模式).{0,16}(?:变化|变更|调整)", semantic_value
5582
+ ):
5583
+ return "semantic"
5584
+ if mechanical:
5585
+ return "mechanical"
5586
+ return "unknown"
5587
+
5588
+
5589
+ def _pure_exact_git_rename(repo: Path, base_ref: str, changed_paths: list[str]) -> bool:
5590
+ common = ["--name-status", "-z", "-M100%", "--diff-filter=ACDMRTUXB"]
5591
+ commands = [["git", "diff", *common], ["git", "diff", "--cached", *common]]
5592
+ effective_base = _effective_change_base(repo, base_ref)
5593
+ if effective_base:
5594
+ commands.insert(0, ["git", "diff", *common, f"{effective_base}...HEAD"])
5595
+ entries: list[tuple[str, tuple[str, ...]]] = []
5596
+ for command in commands:
5597
+ result = run(command, cwd=repo, check=False)
5598
+ if result.returncode != 0:
5599
+ return False
5600
+ tokens = [token for token in result.stdout.split("\0") if token]
5601
+ index = 0
5602
+ while index < len(tokens):
5603
+ status = tokens[index]
5604
+ width = 2 if status[:1] in {"R", "C"} else 1
5605
+ paths = tokens[index + 1 : index + 1 + width]
5606
+ if len(paths) != width:
5607
+ return False
5608
+ entries.append((status, tuple(path.replace("\\", "/") for path in paths)))
5609
+ index += width + 1
5610
+ renamed = {path for status, paths in entries if status == "R100" for path in paths}
5611
+ changed = {path.replace("\\", "/") for path in changed_paths if _text(path)}
5612
+ return bool(entries) and all(status == "R100" for status, _ in entries) and renamed == changed
5613
+
5614
+
5615
+ def _classify_change_nature(
5616
+ repo: Path,
5617
+ *,
5618
+ base_ref: str,
5619
+ changed_paths: list[str],
5620
+ intent: str,
5621
+ inspect_git: bool,
5622
+ ) -> str:
5623
+ intent_nature = _intent_change_nature(intent)
5624
+ if intent_nature != "semantic" and inspect_git and changed_paths and _pure_exact_git_rename(repo, base_ref, changed_paths):
5625
+ return "mechanical"
5626
+ return intent_nature
5627
+
5628
+
5226
5629
  def _resolve_task_kind(
5227
5630
  requested: str,
5228
5631
  paths: list[str],
@@ -5323,6 +5726,7 @@ def _recommended_agents(
5323
5726
  *,
5324
5727
  parallel_writers: int = 1,
5325
5728
  review_required: bool = False,
5729
+ review_policy: Optional[dict] = None,
5326
5730
  ) -> list[str]:
5327
5731
  roles: list[str] = []
5328
5732
  for stage in _agent_execution_plan(
@@ -5331,6 +5735,7 @@ def _recommended_agents(
5331
5735
  classification,
5332
5736
  parallel_writers=parallel_writers,
5333
5737
  review_required=review_required,
5738
+ review_policy=review_policy,
5334
5739
  )["stages"]:
5335
5740
  for role in stage["roles"]:
5336
5741
  if role != "main" and role not in roles:
@@ -5358,6 +5763,11 @@ def _agent_contract_shape() -> tuple[dict, list[str]]:
5358
5763
  "diff_head",
5359
5764
  "diff_fingerprint",
5360
5765
  "owning_fixer",
5766
+ "review_depth",
5767
+ "timeout_seconds",
5768
+ "issued_at",
5769
+ "deadline_at",
5770
+ "scope_revision",
5361
5771
  ],
5362
5772
  },
5363
5773
  [
@@ -5430,9 +5840,19 @@ def _contract_equal(left: object, right: object) -> bool:
5430
5840
  return left == right
5431
5841
 
5432
5842
 
5433
- def _validate_contract_fragment(fragment: dict, value: object, root: dict, path: str) -> None:
5843
+ def _contract_validation_errors(
5844
+ fragment: dict,
5845
+ value: object,
5846
+ root: dict,
5847
+ path: str,
5848
+ ) -> list[str]:
5849
+ errors: list[str] = []
5434
5850
  if "$ref" in fragment:
5435
- _validate_contract_fragment(_contract_ref(root, _text(fragment["$ref"])), value, root, path)
5851
+ errors.extend(
5852
+ _contract_validation_errors(
5853
+ _contract_ref(root, _text(fragment["$ref"])), value, root, path
5854
+ )
5855
+ )
5436
5856
 
5437
5857
  expected_types = fragment.get("type")
5438
5858
  if expected_types is not None:
@@ -5440,60 +5860,67 @@ def _validate_contract_fragment(fragment: dict, value: object, root: dict, path:
5440
5860
  if not all(isinstance(item, str) for item in choices) or not any(
5441
5861
  _contract_type_matches(value, item) for item in choices
5442
5862
  ):
5443
- raise APError(f"Contract validation failed at {path}: expected type {choices}.")
5863
+ errors.append(f"{path}: expected type {choices}")
5864
+ return errors
5444
5865
 
5445
5866
  if "const" in fragment and not _contract_equal(value, fragment["const"]):
5446
- raise APError(f"Contract validation failed at {path}: expected constant {fragment['const']!r}.")
5447
- if "enum" in fragment and not any(_contract_equal(value, item) for item in fragment["enum"]):
5448
- raise APError(f"Contract validation failed at {path}: value is outside the allowed enum.")
5867
+ errors.append(f"{path}: expected constant {fragment['const']!r}")
5868
+ if "enum" in fragment and not any(
5869
+ _contract_equal(value, item) for item in fragment["enum"]
5870
+ ):
5871
+ errors.append(f"{path}: value is outside the allowed enum")
5449
5872
 
5450
5873
  if isinstance(value, str):
5451
5874
  if len(value) < int(fragment.get("minLength") or 0):
5452
- raise APError(f"Contract validation failed at {path}: string is too short.")
5875
+ errors.append(f"{path}: string is too short")
5453
5876
  pattern = fragment.get("pattern")
5454
5877
  if pattern and not re.search(str(pattern), value):
5455
- raise APError(f"Contract validation failed at {path}: string does not match {pattern!r}.")
5878
+ errors.append(f"{path}: string does not match {pattern!r}")
5879
+
5880
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
5881
+ if "minimum" in fragment and value < fragment["minimum"]:
5882
+ errors.append(f"{path}: number is below minimum {fragment['minimum']}")
5883
+ if "maximum" in fragment and value > fragment["maximum"]:
5884
+ errors.append(f"{path}: number exceeds maximum {fragment['maximum']}")
5456
5885
 
5457
5886
  if isinstance(value, list):
5458
5887
  if "maxItems" in fragment and len(value) > int(fragment["maxItems"]):
5459
- raise APError(f"Contract validation failed at {path}: too many array items.")
5888
+ errors.append(f"{path}: too many array items")
5460
5889
  item_schema = fragment.get("items")
5461
5890
  if isinstance(item_schema, dict):
5462
5891
  for index, item in enumerate(value):
5463
- _validate_contract_fragment(item_schema, item, root, f"{path}[{index}]")
5892
+ errors.extend(
5893
+ _contract_validation_errors(item_schema, item, root, f"{path}[{index}]")
5894
+ )
5464
5895
 
5465
5896
  if isinstance(value, dict):
5466
5897
  required = fragment.get("required") or []
5467
- missing = [item for item in required if item not in value]
5898
+ missing = sorted(item for item in required if item not in value)
5468
5899
  if missing:
5469
- raise APError(
5470
- f"Contract validation failed at {path}: missing " + ", ".join(sorted(missing)) + "."
5471
- )
5900
+ errors.append(f"{path}: missing " + ", ".join(missing))
5472
5901
  properties = fragment.get("properties") or {}
5473
5902
  if fragment.get("additionalProperties") is False:
5474
5903
  unexpected = sorted(set(value) - set(properties))
5475
5904
  if unexpected:
5476
- raise APError(
5477
- f"Contract validation failed at {path}: unexpected " + ", ".join(unexpected) + "."
5478
- )
5905
+ errors.append(f"{path}: unexpected " + ", ".join(unexpected))
5479
5906
  for key, child in properties.items():
5480
5907
  if key in value and isinstance(child, dict):
5481
- _validate_contract_fragment(child, value[key], root, f"{path}.{key}")
5908
+ errors.extend(
5909
+ _contract_validation_errors(child, value[key], root, f"{path}.{key}")
5910
+ )
5482
5911
 
5483
5912
  condition = fragment.get("if")
5484
- if isinstance(condition, dict):
5485
- try:
5486
- _validate_contract_fragment(condition, value, root, path)
5487
- except APError:
5488
- pass
5489
- else:
5490
- then = fragment.get("then")
5491
- if isinstance(then, dict):
5492
- _validate_contract_fragment(then, value, root, path)
5913
+ if isinstance(condition, dict) and not _contract_validation_errors(
5914
+ condition, value, root, path
5915
+ ):
5916
+ then = fragment.get("then")
5917
+ if isinstance(then, dict):
5918
+ errors.extend(_contract_validation_errors(then, value, root, path))
5493
5919
 
5494
5920
  for child in fragment.get("allOf") or []:
5495
5921
  if isinstance(child, dict):
5496
- _validate_contract_fragment(child, value, root, path)
5922
+ errors.extend(_contract_validation_errors(child, value, root, path))
5923
+ return errors
5497
5924
 
5498
5925
 
5499
5926
  def _validate_orchestration_contract(kind: str, payload: dict) -> dict:
@@ -5507,28 +5934,269 @@ def _validate_orchestration_contract(kind: str, payload: dict) -> dict:
5507
5934
  if not definition:
5508
5935
  raise APError(f"Unknown orchestration contract kind: {kind}")
5509
5936
  root = _orchestration_schema()
5510
- _validate_contract_fragment(root["$defs"][definition], payload, root, "$")
5937
+ errors = _contract_validation_errors(root["$defs"][definition], payload, root, "$")
5511
5938
 
5512
5939
  role = _text(payload.get("role"))
5513
5940
  if kind == "assignment" and role == "reviewer":
5514
5941
  if _text(payload.get("node_id")) == _text(payload.get("owning_fixer")):
5515
- raise APError("Reviewer assignment node_id must differ from owning_fixer.")
5942
+ errors.append("$.node_id: reviewer must differ from owning_fixer")
5943
+ timing_fields = ("issued_at", "deadline_at", "timeout_seconds")
5944
+ timing_values = [payload.get(field) for field in timing_fields]
5945
+ if any(value is not None for value in timing_values):
5946
+ if not all(value is not None for value in timing_values):
5947
+ errors.append("$: reviewer timing fields must be supplied together")
5948
+ else:
5949
+ try:
5950
+ issued_at = _parse_iso_timestamp(payload.get("issued_at"), "issued_at")
5951
+ deadline_at = _parse_iso_timestamp(payload.get("deadline_at"), "deadline_at")
5952
+ timeout_seconds = int(payload.get("timeout_seconds"))
5953
+ expected_timeout = {
5954
+ "focused": _FOCUSED_REVIEW_TIMEOUT_SECONDS,
5955
+ "deep": _DEEP_REVIEW_TIMEOUT_SECONDS,
5956
+ }.get(_text(payload.get("review_depth")))
5957
+ if expected_timeout is not None and timeout_seconds != expected_timeout:
5958
+ errors.append(
5959
+ "$.timeout_seconds: must match the fixed "
5960
+ f"{_text(payload.get('review_depth'))} review budget {expected_timeout}"
5961
+ )
5962
+ if deadline_at <= issued_at:
5963
+ errors.append("$.deadline_at: must be after issued_at")
5964
+ elif int((deadline_at - issued_at).total_seconds()) != timeout_seconds:
5965
+ errors.append("$.deadline_at: interval must equal timeout_seconds")
5966
+ except (APError, TypeError, ValueError) as exc:
5967
+ errors.append(f"$: invalid reviewer timing contract: {exc}")
5516
5968
  if kind == "result":
5517
- if role == "fixer":
5969
+ owned_paths = payload.get("owned_paths")
5970
+ changed_paths = payload.get("changed_paths")
5971
+ if role == "fixer" and isinstance(owned_paths, list) and isinstance(changed_paths, list):
5518
5972
  owned = [_normalize_owned_path(item) for item in payload.get("owned_paths") or []]
5519
5973
  outside = [
5520
5974
  path
5521
5975
  for path in payload.get("changed_paths") or []
5976
+ if isinstance(path, str)
5522
5977
  if not _path_is_owned(path, owned)
5523
5978
  ]
5524
5979
  if outside:
5525
- raise APError("Fixer result changed_paths exceed owned_paths: " + ", ".join(outside))
5980
+ errors.append(
5981
+ "$.changed_paths: fixer paths exceed owned_paths: " + ", ".join(outside)
5982
+ )
5526
5983
  if role == "reviewer" and _text(payload.get("verdict")) in {"approved", "changes-requested"}:
5527
5984
  if not re.fullmatch(r"[0-9a-f]{64}", _text(payload.get("diff_fingerprint"))):
5528
- raise APError("Reviewer result must bind its verdict to a non-empty diff fingerprint.")
5985
+ errors.append(
5986
+ "$.diff_fingerprint: reviewer verdict must bind to a 64-character fingerprint"
5987
+ )
5988
+ errors = list(dict.fromkeys(errors))
5989
+ if errors:
5990
+ raise APError("Contract validation failed:\n- " + "\n- ".join(errors))
5529
5991
  return payload
5530
5992
 
5531
5993
 
5994
+ def _reviewer_result_template(assignment: dict, verdict: str) -> dict:
5995
+ """Build a complete Reviewer result without guessing review evidence or findings."""
5996
+ _validate_orchestration_contract("assignment", assignment)
5997
+ if _text(assignment.get("role")) != "reviewer":
5998
+ raise APError("Reviewer result templates require a reviewer assignment.")
5999
+ normalized_verdict = _text(verdict).lower()
6000
+ if normalized_verdict not in {"approved", "changes-requested", "blocked"}:
6001
+ raise APError(
6002
+ "Reviewer result verdict must be approved, changes-requested, or blocked."
6003
+ )
6004
+ fingerprint = _text(assignment.get("diff_fingerprint"))
6005
+ if not re.fullmatch(r"[0-9a-f]{64}", fingerprint):
6006
+ raise APError(
6007
+ "Reviewer result templates require a non-empty 64-character diff fingerprint."
6008
+ )
6009
+ status = "blocked" if normalized_verdict == "blocked" else "completed"
6010
+ next_owner = (
6011
+ _text(assignment.get("owning_fixer"))
6012
+ if normalized_verdict == "changes-requested"
6013
+ else "main"
6014
+ )
6015
+ summaries = {
6016
+ "approved": "Review completed with no blocking findings.",
6017
+ "changes-requested": "Review completed with changes requested.",
6018
+ "blocked": "Review could not be completed.",
6019
+ }
6020
+ result = {
6021
+ "contract_version": _AGENT_CONTRACT_VERSION,
6022
+ "node_id": _text(assignment.get("node_id")),
6023
+ "role": "reviewer",
6024
+ "task_id": _text(assignment.get("task_id")),
6025
+ "base_sha": _text(assignment.get("base_sha")),
6026
+ "status": status,
6027
+ "summary": summaries[normalized_verdict],
6028
+ "depends_on": list(assignment.get("depends_on") or []),
6029
+ "owned_paths": [],
6030
+ "changed_paths": [],
6031
+ "diff_fingerprint": fingerprint,
6032
+ "evidence": [],
6033
+ "findings": [],
6034
+ "verdict": normalized_verdict,
6035
+ "risks": [],
6036
+ "next_owner": next_owner,
6037
+ }
6038
+ return _validate_orchestration_contract("result", result)
6039
+
6040
+
6041
+ def _normalize_reviewer_runtime_result(assignment: dict, payload: dict) -> dict:
6042
+ """Normalize presentation fields while refusing assignment-binding spoofing."""
6043
+ if not isinstance(payload, dict):
6044
+ raise APError("Reviewer runtime output must be one JSON object.")
6045
+ verdict = _text(payload.get("verdict")).lower()
6046
+ if verdict not in {"approved", "changes-requested", "blocked"}:
6047
+ raise APError(
6048
+ "Reviewer runtime output must include verdict=approved, changes-requested, or blocked."
6049
+ )
6050
+ result = _reviewer_result_template(assignment, verdict)
6051
+ binding_fields = {
6052
+ "contract_version": result["contract_version"],
6053
+ "node_id": result["node_id"],
6054
+ "role": result["role"],
6055
+ "task_id": result["task_id"],
6056
+ "base_sha": result["base_sha"],
6057
+ "diff_fingerprint": result["diff_fingerprint"],
6058
+ }
6059
+ mismatched = [
6060
+ field
6061
+ for field, expected in binding_fields.items()
6062
+ if field in payload and payload.get(field) != expected
6063
+ ]
6064
+ if mismatched:
6065
+ raise APError(
6066
+ "Reviewer runtime result does not match its assignment: "
6067
+ + ", ".join(mismatched)
6068
+ )
6069
+ if "summary" in payload:
6070
+ if not isinstance(payload["summary"], str):
6071
+ raise APError("Reviewer runtime result summary must be a string.")
6072
+ result["summary"] = payload["summary"]
6073
+ for field in ("evidence", "findings", "risks"):
6074
+ if field not in payload:
6075
+ continue
6076
+ value = payload[field]
6077
+ if not isinstance(value, list) or not all(isinstance(item, str) for item in value):
6078
+ raise APError(f"Reviewer runtime result {field} must be an array of strings.")
6079
+ result[field] = value
6080
+ return _validate_orchestration_contract("result", result)
6081
+
6082
+
6083
+ def _reviewer_agent_instructions(worktree: Path) -> str:
6084
+ candidates = [
6085
+ worktree / ".agents" / "agents" / "reviewer.toml",
6086
+ _skill_root().parent.parent / "agents" / "reviewer.toml",
6087
+ ]
6088
+ for path in candidates:
6089
+ try:
6090
+ payload = tomllib.loads(path.read_text(encoding="utf-8"))
6091
+ except FileNotFoundError:
6092
+ continue
6093
+ except (OSError, tomllib.TOMLDecodeError) as exc:
6094
+ raise APError(f"Cannot load managed Reviewer Agent config: {path}: {exc}") from exc
6095
+ instructions = _text(payload.get("developer_instructions"))
6096
+ if instructions:
6097
+ return instructions
6098
+ return (
6099
+ "Act as an independent read-only code reviewer. Review only the supplied "
6100
+ "assignment and return one JSON object with an approved, changes-requested, "
6101
+ "or blocked verdict. Do not modify files."
6102
+ )
6103
+
6104
+
6105
+ def _codex_reviewer_command(
6106
+ worktree: Path,
6107
+ assignment_path: Path,
6108
+ result_path: Path,
6109
+ ) -> list[str]:
6110
+ codex = shutil.which("codex")
6111
+ if not codex:
6112
+ raise APError(
6113
+ "The supervised Reviewer runtime requires the Codex CLI on PATH. "
6114
+ "Install Codex or run review-assignment and use another deadline-capable host."
6115
+ )
6116
+ instructions = _reviewer_agent_instructions(worktree)
6117
+ prompt = (
6118
+ f"Review the exact assignment at {assignment_path}. "
6119
+ "Stay inside its diff, identity, and deadline. Use "
6120
+ "`python3 docs/tools/autopipeline/ap.py agent-result-template --file "
6121
+ f"{assignment_path} --verdict <approved|changes-requested|blocked>` when useful. "
6122
+ "Return only one JSON object as the final response; do not modify files."
6123
+ )
6124
+ return [
6125
+ codex,
6126
+ "-a",
6127
+ "never",
6128
+ "exec",
6129
+ "--ephemeral",
6130
+ "--ignore-user-config",
6131
+ "-C",
6132
+ str(worktree),
6133
+ "-s",
6134
+ "read-only",
6135
+ "-c",
6136
+ 'model_reasoning_effort="xhigh"',
6137
+ "-c",
6138
+ "developer_instructions=" + json.dumps(instructions, ensure_ascii=False),
6139
+ "-o",
6140
+ str(result_path),
6141
+ prompt,
6142
+ ]
6143
+
6144
+
6145
+ def _terminate_reviewer_process(process: subprocess.Popen[str]) -> tuple[str, str]:
6146
+ if process.poll() is None:
6147
+ try:
6148
+ if os.name == "posix":
6149
+ os.killpg(process.pid, signal.SIGTERM)
6150
+ else:
6151
+ process.terminate()
6152
+ except ProcessLookupError:
6153
+ pass
6154
+ try:
6155
+ stdout, stderr = process.communicate(timeout=2)
6156
+ except subprocess.TimeoutExpired:
6157
+ try:
6158
+ if os.name == "posix":
6159
+ os.killpg(process.pid, signal.SIGKILL)
6160
+ else:
6161
+ process.kill()
6162
+ except ProcessLookupError:
6163
+ pass
6164
+ stdout, stderr = process.communicate()
6165
+ return stdout or "", stderr or ""
6166
+
6167
+
6168
+ def _run_supervised_reviewer_process(
6169
+ command: list[str],
6170
+ *,
6171
+ cwd: Path,
6172
+ env: dict[str, str],
6173
+ timeout_seconds: float,
6174
+ ) -> subprocess.CompletedProcess[str]:
6175
+ if timeout_seconds <= 0:
6176
+ raise _ReviewerRuntimeTimeout()
6177
+ process = subprocess.Popen(
6178
+ command,
6179
+ cwd=str(cwd),
6180
+ env=env,
6181
+ stdin=subprocess.DEVNULL,
6182
+ stdout=subprocess.PIPE,
6183
+ stderr=subprocess.PIPE,
6184
+ text=True,
6185
+ start_new_session=True,
6186
+ )
6187
+ try:
6188
+ stdout, stderr = process.communicate(timeout=timeout_seconds)
6189
+ except subprocess.TimeoutExpired as exc:
6190
+ stdout, stderr = _terminate_reviewer_process(process)
6191
+ raise _ReviewerRuntimeTimeout(stdout, stderr) from exc
6192
+ return subprocess.CompletedProcess(
6193
+ command,
6194
+ int(process.returncode or 0),
6195
+ stdout or "",
6196
+ stderr or "",
6197
+ )
6198
+
6199
+
5532
6200
  def _validate_agent_plan(plan: dict) -> dict:
5533
6201
  required = {
5534
6202
  "contract_version",
@@ -5548,6 +6216,53 @@ def _validate_agent_plan(plan: dict) -> dict:
5548
6216
  return plan
5549
6217
 
5550
6218
 
6219
+ def _review_execution_policy(
6220
+ *,
6221
+ review_required: bool,
6222
+ categories: set[str],
6223
+ cross_module: bool,
6224
+ parallel_writers: int,
6225
+ ) -> dict:
6226
+ if not review_required:
6227
+ return {
6228
+ "depth": "none",
6229
+ "agent": "",
6230
+ "timeout_seconds": 0,
6231
+ "analysis_attempt_limit": 0,
6232
+ }
6233
+ deep = bool(
6234
+ cross_module
6235
+ or parallel_writers > 1
6236
+ or categories & _DEEP_REVIEW_CATEGORIES
6237
+ )
6238
+ return {
6239
+ "depth": "deep" if deep else "focused",
6240
+ "agent": "reviewer",
6241
+ "timeout_seconds": (
6242
+ _DEEP_REVIEW_TIMEOUT_SECONDS if deep else _FOCUSED_REVIEW_TIMEOUT_SECONDS
6243
+ ),
6244
+ "analysis_attempt_limit": 1,
6245
+ }
6246
+
6247
+
6248
+ def _normalized_task_review_policy(
6249
+ review_required: bool,
6250
+ *depth_candidates: object,
6251
+ ) -> tuple[str, int]:
6252
+ if not review_required:
6253
+ return "none", 0
6254
+ depth_rank = {"none": 0, "focused": 1, "deep": 2}
6255
+ depth = "focused"
6256
+ for candidate in depth_candidates:
6257
+ normalized = _text(candidate).lower()
6258
+ if depth_rank.get(normalized, 0) > depth_rank[depth]:
6259
+ depth = normalized
6260
+ timeout_seconds = (
6261
+ _DEEP_REVIEW_TIMEOUT_SECONDS if depth == "deep" else _FOCUSED_REVIEW_TIMEOUT_SECONDS
6262
+ )
6263
+ return depth, timeout_seconds
6264
+
6265
+
5551
6266
  def _agent_execution_plan(
5552
6267
  profile: str,
5553
6268
  categories: set[str],
@@ -5555,10 +6270,12 @@ def _agent_execution_plan(
5555
6270
  *,
5556
6271
  parallel_writers: int = 1,
5557
6272
  review_required: bool = False,
6273
+ review_policy: Optional[dict] = None,
5558
6274
  optional_roles: Optional[list[str]] = None,
5559
6275
  ) -> dict:
5560
6276
  assignment_contract, result_contract = _agent_contract_shape()
5561
6277
  optional_roles = list(dict.fromkeys(optional_roles or []))
6278
+ review_policy = dict(review_policy or {})
5562
6279
  # Optional roles are candidates, never automatic stages. The model selects
5563
6280
  # them only when expected benefit exceeds coordination cost.
5564
6281
  discovery_roles: list[str] = []
@@ -5570,6 +6287,12 @@ def _agent_execution_plan(
5570
6287
  "dependency_policy": "integrate-before-dependent-start",
5571
6288
  "review_feedback_owner": "owning-fixer" if review_required else "main",
5572
6289
  "review_binding": "diff-fingerprint-when-required",
6290
+ "review_depth": _text(review_policy.get("depth")) or "none",
6291
+ "review_agent": _text(review_policy.get("agent")),
6292
+ "review_timeout_seconds": int(review_policy.get("timeout_seconds") or 0),
6293
+ "review_analysis_attempt_limit": int(
6294
+ review_policy.get("analysis_attempt_limit") or 0
6295
+ ),
5573
6296
  "lifecycle_owner": "main",
5574
6297
  "gate_owner": "main",
5575
6298
  }
@@ -5579,6 +6302,11 @@ def _agent_execution_plan(
5579
6302
  "Never run two writers in one worktree.",
5580
6303
  "The main agent runs one final changed-scope gate, pushes, and cleans only temporary branches actually created.",
5581
6304
  ]
6305
+ if review_required:
6306
+ constraints.append(
6307
+ "Run one bounded review analysis over the supplied diff and relevant evidence; "
6308
+ "a timeout is blocked, never approved, and JSON formatting repair must reuse the same analysis."
6309
+ )
5582
6310
 
5583
6311
  if parallel_writers <= 1 and not discovery_roles and not review_required:
5584
6312
  stages = [{"id": "delivery", "mode": "serial", "roles": ["main"], "depends_on": []}]
@@ -5604,7 +6332,7 @@ def _agent_execution_plan(
5604
6332
  delivery_roles = ["fixer", "main"]
5605
6333
  delivery_mode = "parallel-isolated"
5606
6334
  if review_required:
5607
- delivery_roles.append("reviewer")
6335
+ delivery_roles.append(_text(review_policy.get("agent")) or "reviewer")
5608
6336
  stages.append(
5609
6337
  {
5610
6338
  "id": "delivery",
@@ -5687,7 +6415,8 @@ def _mechanism_plan(
5687
6415
  "rule": (
5688
6416
  "run required mechanisms; select optional mechanisms only when expected value exceeds "
5689
6417
  "coordination cost; reclassify before changing writer count; do not run forbidden "
5690
- "mechanisms unless the user explicitly overrides"
6418
+ "mechanisms unless the user explicitly overrides; direct/worktree decisions apply only "
6419
+ "to the reported workspace snapshot and require reclassification if it changes"
5691
6420
  ),
5692
6421
  }
5693
6422
 
@@ -5721,6 +6450,13 @@ def _resolve_execution_plan(
5721
6450
  )
5722
6451
  classification_inputs = [*paths, *normalized_planned_paths]
5723
6452
  task_kind = _resolve_task_kind(requested_task_kind, classification_inputs, intent)
6453
+ change_nature = _classify_change_nature(
6454
+ repo,
6455
+ base_ref=base_ref,
6456
+ changed_paths=paths,
6457
+ intent=intent,
6458
+ inspect_git=changed_paths is None,
6459
+ )
5724
6460
  path_classification = _classify_paths(classification_inputs)
5725
6461
  path_categories = set(path_classification["categories"])
5726
6462
  intent_categories = _classify_intent(intent)
@@ -5861,8 +6597,15 @@ def _resolve_execution_plan(
5861
6597
  )
5862
6598
  design_required = bool(
5863
6599
  task_kind == "change"
5864
- and (rule_design or (effective_profile == "high-risk" and cross_module))
5865
- )
6600
+ and (
6601
+ rule_design
6602
+ or (
6603
+ effective_profile == "high-risk"
6604
+ and cross_module
6605
+ and change_nature != "mechanical"
6606
+ )
6607
+ )
6608
+ )
5866
6609
  dirty_paths = _working_tree_paths(repo)
5867
6610
  workspace_dirty = bool(dirty_paths)
5868
6611
  dirty_outside_plan = [
@@ -5879,12 +6622,10 @@ def _resolve_execution_plan(
5879
6622
  if continue_direct
5880
6623
  else {}
5881
6624
  )
5882
- runtime_actor = _text(os.environ.get("CODEX_THREAD_ID"))
5883
6625
  other_direct_claims = [
5884
6626
  item
5885
6627
  for item in _active_direct_claims(repo)
5886
6628
  if _text(item.get("claim_id")) != _text(direct_claim_id)
5887
- and (not runtime_actor or _text(item.get("owner")) != runtime_actor)
5888
6629
  ]
5889
6630
  active_writer = bool(registered_active_writer or other_direct_claims)
5890
6631
  continued_direct = bool(
@@ -5922,12 +6663,19 @@ def _resolve_execution_plan(
5922
6663
  cross_module=cross_module,
5923
6664
  profile=effective_profile,
5924
6665
  )
6666
+ review_policy = _review_execution_policy(
6667
+ review_required=review_required,
6668
+ categories=categories,
6669
+ cross_module=cross_module,
6670
+ parallel_writers=writer_count,
6671
+ )
5925
6672
  agent_plan = _agent_execution_plan(
5926
6673
  effective_profile,
5927
6674
  categories,
5928
6675
  classification,
5929
6676
  parallel_writers=writer_count,
5930
6677
  review_required=review_required,
6678
+ review_policy=review_policy,
5931
6679
  optional_roles=optional_agents,
5932
6680
  )
5933
6681
  mechanism_plan = _mechanism_plan(
@@ -5944,6 +6692,7 @@ def _resolve_execution_plan(
5944
6692
  "planned_files": normalized_planned_paths,
5945
6693
  "classification_files": classification_inputs,
5946
6694
  "intent_provided": bool(_text(intent)),
6695
+ "change_nature": change_nature,
5947
6696
  "task_kind": task_kind,
5948
6697
  "intent_categories": intent_categories,
5949
6698
  "intent_risk_candidates": intent_risk_candidates,
@@ -5958,6 +6707,7 @@ def _resolve_execution_plan(
5958
6707
  "effective_mode": effective_mode,
5959
6708
  "execution_mode": execution_mode,
5960
6709
  "terminal_maintenance": terminal_maintenance,
6710
+ "repo": str(repo),
5961
6711
  "workspace_dirty": workspace_dirty,
5962
6712
  "dirty_paths": dirty_paths,
5963
6713
  "dirty_outside_plan": dirty_outside_plan,
@@ -5966,6 +6716,10 @@ def _resolve_execution_plan(
5966
6716
  "parallel_writers": writer_count,
5967
6717
  "cross_module": cross_module,
5968
6718
  "review_required": review_required,
6719
+ "review_depth": review_policy["depth"],
6720
+ "review_agent": review_policy["agent"],
6721
+ "review_timeout_seconds": review_policy["timeout_seconds"],
6722
+ "review_analysis_attempt_limit": review_policy["analysis_attempt_limit"],
5969
6723
  "design_required": design_required,
5970
6724
  "selected_scope": selected_scope,
5971
6725
  "categories": sorted(categories),
@@ -5980,6 +6734,7 @@ def _resolve_execution_plan(
5980
6734
  classification,
5981
6735
  parallel_writers=writer_count,
5982
6736
  review_required=review_required,
6737
+ review_policy=review_policy,
5983
6738
  ),
5984
6739
  "optional_agents": optional_agents,
5985
6740
  "agent_plan": agent_plan,
@@ -6056,9 +6811,24 @@ def cmd_classify(args: argparse.Namespace) -> None:
6056
6811
  print(f"[classify] task_kind={result['task_kind']}")
6057
6812
  print(f"[classify] profile={result['profile']}")
6058
6813
  print(f"[classify] effective_mode={result['effective_mode']}")
6814
+ print(f"[classify] repo={result['repo']}")
6815
+ print(f"[classify] workspace_dirty={str(result['workspace_dirty']).lower()}")
6816
+ print(
6817
+ "[classify] dirty_paths="
6818
+ + json.dumps(result["dirty_paths"], ensure_ascii=False, separators=(",", ":"))
6819
+ )
6820
+ print(f"[classify] active_writer={str(result['active_writer']).lower()}")
6059
6821
  print(f"[classify] execution_mode={result['execution_mode']}")
6060
6822
  print(f"[classify] review_required={str(result['review_required']).lower()}")
6823
+ print(f"[classify] review_depth={result['review_depth']}")
6824
+ print(f"[classify] review_agent={result['review_agent'] or '(none)'}")
6825
+ print(f"[classify] review_timeout_seconds={result['review_timeout_seconds']}")
6826
+ print(
6827
+ "[classify] review_analysis_attempt_limit="
6828
+ f"{result['review_analysis_attempt_limit']}"
6829
+ )
6061
6830
  print(f"[classify] design_required={str(result['design_required']).lower()}")
6831
+ print(f"[classify] change_nature={result['change_nature']}")
6062
6832
  print(f"[classify] selected_scope={result['selected_scope']}")
6063
6833
  print("[classify] categories=" + (", ".join(result["categories"]) or "(none)"))
6064
6834
  print("[classify] agents=" + (", ".join(result["recommended_agents"]) or "(main agent only)"))
@@ -6094,8 +6864,7 @@ def cmd_classify(args: argparse.Namespace) -> None:
6094
6864
  _record_evidence(repo, cfg, "classify", "pass", result)
6095
6865
 
6096
6866
 
6097
- def cmd_agent_contract_check(args: argparse.Namespace) -> None:
6098
- repo = Path(args.repo).resolve()
6867
+ def _agent_contract_payload(repo: Path, args: argparse.Namespace) -> dict:
6099
6868
  raw = _text(getattr(args, "payload", ""))
6100
6869
  source = _text(getattr(args, "file", ""))
6101
6870
  if source:
@@ -6119,6 +6888,12 @@ def cmd_agent_contract_check(args: argparse.Namespace) -> None:
6119
6888
  raise APError(f"Agent contract payload is not valid JSON: {exc}") from exc
6120
6889
  if not isinstance(payload, dict):
6121
6890
  raise APError("Agent contract payload must be a JSON object.")
6891
+ return payload
6892
+
6893
+
6894
+ def cmd_agent_contract_check(args: argparse.Namespace) -> None:
6895
+ repo = Path(args.repo).resolve()
6896
+ payload = _agent_contract_payload(repo, args)
6122
6897
  _validate_orchestration_contract(args.kind, payload)
6123
6898
  result = {"valid": True, "kind": args.kind}
6124
6899
  if args.json:
@@ -6127,6 +6902,13 @@ def cmd_agent_contract_check(args: argparse.Namespace) -> None:
6127
6902
  print(f"[agent-contract-check] OK kind={args.kind}")
6128
6903
 
6129
6904
 
6905
+ def cmd_agent_result_template(args: argparse.Namespace) -> None:
6906
+ repo = Path(args.repo).resolve()
6907
+ assignment = _agent_contract_payload(repo, args)
6908
+ result = _reviewer_result_template(assignment, args.verdict)
6909
+ print(json.dumps(result, ensure_ascii=False, indent=2))
6910
+
6911
+
6130
6912
  def cmd_run(args: argparse.Namespace) -> None:
6131
6913
  """
6132
6914
  Run any configured gate command by name.
@@ -6190,6 +6972,16 @@ def cmd_light_gate(args: argparse.Namespace) -> None:
6190
6972
  deadline=deadline,
6191
6973
  command_timeout_s=budget["command_seconds"],
6192
6974
  )
6975
+ executed.extend(
6976
+ _run_structure_check_for_gate(
6977
+ repo,
6978
+ cfg,
6979
+ selected_scope,
6980
+ _text(getattr(args, "base", "")),
6981
+ deadline=deadline,
6982
+ command_timeout_s=budget["command_seconds"],
6983
+ )
6984
+ )
6193
6985
 
6194
6986
  _run_git_diff_check(repo, cfg)
6195
6987
  if time.monotonic() > deadline:
@@ -6271,25 +7063,30 @@ def cmd_runtime_down(args: argparse.Namespace) -> None:
6271
7063
  print("[runtime-down] OK")
6272
7064
 
6273
7065
 
6274
- def cmd_wait_health(args: argparse.Namespace) -> None:
6275
- repo = Path(args.repo).resolve()
6276
- cfg = _load_cfg(repo)
6277
- scope = args.scope
6278
- if scope == "runtime":
6279
- runtime_cfg = (cfg.get("runtime") or {})
6280
- url = _join_url(str(runtime_cfg.get("health_base_url") or ""), str(runtime_cfg.get("health_path") or ""))
6281
- timeout_s = int(runtime_cfg.get("startup_timeout_sec") or 120)
6282
- else:
6283
- target_cfg = (cfg.get("target_env") or {})
6284
- jenkins_cfg = (cfg.get("jenkins") or {})
6285
- base_url = str(target_cfg.get("health_base_url") or "")
6286
- path = str(target_cfg.get("health_path") or "")
6287
- url = _join_url(
6288
- base_url,
6289
- path,
6290
- )
6291
- timeout_s = int(jenkins_cfg.get("deploy_timeout_sec") or 1800)
7066
+ def _target_endpoint_config(
7067
+ cfg: dict,
7068
+ component: str,
7069
+ ) -> tuple[str, dict, str, str, str]:
7070
+ access = cfg.get("access") or {}
7071
+ project = access.get("project") or {}
7072
+ lane = project.get(component) or {}
7073
+ if isinstance(lane, dict) and any(_is_explicit_fill(value) for value in lane.values()):
7074
+ base_url = _require_http_url(f"access.project.{component}.url", lane.get("url"))
7075
+ return f"access.project.{component}", lane, base_url, "username", "password"
7076
+ legacy = cfg.get("target_env") or {}
7077
+ base_field = f"{component}_base_url"
7078
+ base_url = _require_http_url(f"target_env.{base_field}", legacy.get(base_field))
7079
+ return (
7080
+ "target_env",
7081
+ legacy,
7082
+ base_url,
7083
+ f"{component}_username",
7084
+ f"{component}_password",
7085
+ )
7086
+
6292
7087
 
7088
+ def _wait_for_health_url(scope: str, url: str, timeout_s: int) -> None:
7089
+ _require_http_url(f"{scope} health URL", url)
6293
7090
  deadline = time.time() + timeout_s
6294
7091
  last_error = "(none)"
6295
7092
  while time.time() < deadline:
@@ -6305,50 +7102,94 @@ def cmd_wait_health(args: argparse.Namespace) -> None:
6305
7102
  raise APError(f"Health check timeout for {scope}: {url}\nLast result: {last_error}")
6306
7103
 
6307
7104
 
7105
+ def cmd_wait_health(args: argparse.Namespace) -> None:
7106
+ repo = Path(args.repo).resolve()
7107
+ cfg = _load_cfg(repo)
7108
+ scope = args.scope
7109
+ requested_timeout = int(getattr(args, "timeout_sec", 0) or 0)
7110
+ if scope == "runtime":
7111
+ runtime_cfg = cfg.get("runtime") or {}
7112
+ base_url = _require_http_url("runtime.health_base_url", runtime_cfg.get("health_base_url"))
7113
+ url = _join_url(base_url, runtime_cfg.get("health_path"))
7114
+ timeout_s = requested_timeout or int(runtime_cfg.get("startup_timeout_sec") or 120)
7115
+ else:
7116
+ target_cfg = cfg.get("target_env") or {}
7117
+ explicit_path = _text(getattr(args, "path", ""))
7118
+ legacy_base = _text(target_cfg.get("health_base_url"))
7119
+ legacy_path = _text(target_cfg.get("health_path"))
7120
+ if explicit_path:
7121
+ component = _text(getattr(args, "component", "")) or "backend"
7122
+ _, _, base_url, _, _ = _target_endpoint_config(cfg, component)
7123
+ url = _join_url(base_url, explicit_path)
7124
+ elif legacy_base and legacy_path:
7125
+ base_url = _require_http_url("target_env.health_base_url", legacy_base)
7126
+ url = _join_url(base_url, legacy_path)
7127
+ else:
7128
+ raise APError(
7129
+ "Target health check requires --component and --path for access.project, "
7130
+ "or legacy target_env.health_base_url plus target_env.health_path."
7131
+ )
7132
+ timeout_s = requested_timeout or int((cfg.get("jenkins") or {}).get("deploy_timeout_sec") or 120)
7133
+ _wait_for_health_url(scope, url, timeout_s)
7134
+
7135
+
6308
7136
  def cmd_verify_target(args: argparse.Namespace) -> None:
6309
7137
  repo = Path(args.repo).resolve()
6310
7138
  cfg = _load_cfg(repo)
6311
- target_cfg = (cfg.get("target_env") or {})
7139
+ requested = {
7140
+ "backend": list(args.backend_path or []),
7141
+ "frontend": list(args.frontend_path or []),
7142
+ }
7143
+ target_cfg = cfg.get("target_env") or {}
7144
+ legacy_health_base = _text(target_cfg.get("health_base_url"))
7145
+ legacy_health_path = _text(target_cfg.get("health_path"))
7146
+ if not any(requested.values()) and not (legacy_health_base and legacy_health_path):
7147
+ raise APError(
7148
+ "verify-target requires --backend-path or --frontend-path when no legacy target health check is configured."
7149
+ )
7150
+
7151
+ planned_checks: list[tuple[str, str, dict[str, str]]] = []
7152
+ for component in ("backend", "frontend"):
7153
+ paths = requested[component]
7154
+ if not paths:
7155
+ continue
7156
+ section_name, section_cfg, base_url, user_field, secret_field = _target_endpoint_config(
7157
+ cfg,
7158
+ component,
7159
+ )
7160
+ headers: dict[str, str] = {}
7161
+ if bool(getattr(args, f"{component}_basic_auth")):
7162
+ username = _text(section_cfg.get(user_field))
7163
+ if not _is_explicit_fill(username):
7164
+ raise APError(f"Missing {section_name}.{user_field} for basic auth.")
7165
+ password = _resolve_secret(section_name, section_cfg, secret_field)
7166
+ headers = _basic_auth_header(username, password)
7167
+ for path in paths:
7168
+ url = _join_url(base_url, path)
7169
+ _require_http_url(f"{component} target URL", url)
7170
+ planned_checks.append((component, url, headers))
7171
+
7172
+ health_url = ""
7173
+ if legacy_health_base or legacy_health_path:
7174
+ if not (legacy_health_base and legacy_health_path):
7175
+ raise APError(
7176
+ "Legacy target health config requires both target_env.health_base_url and target_env.health_path."
7177
+ )
7178
+ health_base = _require_http_url("target_env.health_base_url", legacy_health_base)
7179
+ health_url = _join_url(health_base, legacy_health_path)
6312
7180
 
6313
- cmd_wait_health(argparse.Namespace(repo=str(repo), scope="target"))
7181
+ if health_url:
7182
+ timeout_s = int((cfg.get("jenkins") or {}).get("deploy_timeout_sec") or 120)
7183
+ _wait_for_health_url("target", health_url, timeout_s)
6314
7184
 
6315
7185
  checks: List[str] = []
6316
-
6317
- backend_base = str(target_cfg.get("backend_base_url") or "").strip().rstrip("/")
6318
- frontend_base = str(target_cfg.get("frontend_base_url") or "").strip().rstrip("/")
6319
-
6320
- backend_headers: dict[str, str] = {}
6321
- frontend_headers: dict[str, str] = {}
6322
- if args.backend_basic_auth:
6323
- user = str(target_cfg.get("backend_username") or "").strip()
6324
- if not user:
6325
- raise APError("Missing target_env.backend_username for backend basic auth.")
6326
- password = _resolve_secret("target_env", target_cfg, "backend_password")
6327
- backend_headers = _basic_auth_header(user, password)
6328
- if args.frontend_basic_auth:
6329
- user = str(target_cfg.get("frontend_username") or "").strip()
6330
- if not user:
6331
- raise APError("Missing target_env.frontend_username for frontend basic auth.")
6332
- password = _resolve_secret("target_env", target_cfg, "frontend_password")
6333
- frontend_headers = _basic_auth_header(user, password)
6334
-
6335
- for path in args.backend_path or []:
6336
- if not backend_base:
6337
- raise APError("Missing target_env.backend_base_url for backend path verification.")
6338
- url = _join_url(backend_base, path)
6339
- status, body = _http_get(url, headers=backend_headers, timeout_s=10)
6340
- if not (200 <= status < 400):
6341
- raise APError(f"Backend target verification failed: {url} -> {status}\n{body[:400]}")
6342
- checks.append(f"backend:{url}->{status}")
6343
-
6344
- for path in args.frontend_path or []:
6345
- if not frontend_base:
6346
- raise APError("Missing target_env.frontend_base_url for frontend path verification.")
6347
- url = _join_url(frontend_base, path)
6348
- status, body = _http_get(url, headers=frontend_headers, timeout_s=10)
7186
+ for component, url, headers in planned_checks:
7187
+ status, body = _http_get(url, headers=headers, timeout_s=10)
6349
7188
  if not (200 <= status < 400):
6350
- raise APError(f"Frontend target verification failed: {url} -> {status}\n{body[:400]}")
6351
- checks.append(f"frontend:{url}->{status}")
7189
+ raise APError(
7190
+ f"{component.title()} target verification failed: {url} -> {status}\n{body[:400]}"
7191
+ )
7192
+ checks.append(f"{component}:{url}->{status}")
6352
7193
 
6353
7194
  summary = ", ".join(checks) if checks else "health-only"
6354
7195
  _record_evidence(repo, cfg, "verify_target", "pass", {"summary": summary, "checks": checks})
@@ -6366,6 +7207,28 @@ def cmd_verify_jenkins(args: argparse.Namespace) -> None:
6366
7207
  if not jenkinsfile.exists():
6367
7208
  raise APError(f"Jenkinsfile not found: {jenkinsfile}")
6368
7209
 
7210
+ configured_components = _configured_jenkins_components(cfg)
7211
+ if configured_components:
7212
+ requested = _text(getattr(args, "component", "all")).lower() or "all"
7213
+ selected = ("frontend", "backend") if requested == "all" else (requested,)
7214
+ checked: list[str] = []
7215
+ for component in selected:
7216
+ lane = _jenkins_access_cfg(cfg, component)
7217
+ _require_http_url(f"access.jenkins.{component}.url", lane.get("url"))
7218
+ if not _is_explicit_fill(lane.get("username")):
7219
+ raise APError(f"Missing access.jenkins.{component}.username.")
7220
+ _resolve_secret(f"access.jenkins.{component}", lane, "password")
7221
+ checked.append(component)
7222
+ _record_evidence(
7223
+ repo,
7224
+ cfg,
7225
+ "verify_jenkins",
7226
+ "pass",
7227
+ {"jenkinsfile": str(jenkinsfile), "components": checked},
7228
+ )
7229
+ print(f"[verify-jenkins] OK: {jenkinsfile} components={','.join(checked)}")
7230
+ return
7231
+
6369
7232
  required = [
6370
7233
  ("jenkins.base_url", jenkins_cfg.get("base_url")),
6371
7234
  ("jenkins.job_url", jenkins_cfg.get("job_url")),
@@ -6622,6 +7485,16 @@ def cmd_verify_jenkins_build(args: argparse.Namespace) -> None:
6622
7485
  repo = Path(args.repo).resolve()
6623
7486
  cfg = _load_cfg(repo)
6624
7487
  jenkins_cfg = (cfg.get("jenkins") or {})
7488
+ component = _resolve_jenkins_component(
7489
+ cfg,
7490
+ _text(getattr(args, "component", "")),
7491
+ _text(args.job_url),
7492
+ )
7493
+ if component:
7494
+ lane = _jenkins_access_cfg(cfg, component)
7495
+ _require_http_url(f"access.jenkins.{component}.url", lane.get("url"))
7496
+ _jenkins_auth_config(cfg, component)
7497
+ _resolve_secret(f"access.jenkins.{component}", lane, "password")
6625
7498
  git_ref = str(args.git_ref or "HEAD").strip()
6626
7499
  candidate_job_urls = _resolve_jenkins_job_candidates(
6627
7500
  cfg,
@@ -6631,6 +7504,7 @@ def cmd_verify_jenkins_build(args: argparse.Namespace) -> None:
6631
7504
  job_url=args.job_url,
6632
7505
  multibranch_root_job=args.multibranch_root_job,
6633
7506
  branch_name=args.branch_name,
7507
+ component=component,
6634
7508
  )
6635
7509
  build_number = args.build_number
6636
7510
  max_builds = int(args.max_builds or 20)
@@ -6644,6 +7518,7 @@ def cmd_verify_jenkins_build(args: argparse.Namespace) -> None:
6644
7518
  args.multibranch_root_job
6645
7519
  or args.job_name
6646
7520
  or args.job_url
7521
+ or (_jenkins_access_cfg(cfg, component).get("url") if component else "")
6647
7522
  or jenkins_cfg.get("job_url")
6648
7523
  or ""
6649
7524
  ).strip()
@@ -6659,7 +7534,12 @@ def cmd_verify_jenkins_build(args: argparse.Namespace) -> None:
6659
7534
  payload = None
6660
7535
  for candidate_job_url in candidate_job_urls:
6661
7536
  api_url = _jenkins_build_api_url(candidate_job_url, int(build_number))
6662
- payload = _jenkins_api_get_json(api_url, cfg, allow_404=True)
7537
+ payload = _jenkins_api_get_json(
7538
+ api_url,
7539
+ cfg,
7540
+ allow_404=True,
7541
+ component=component,
7542
+ )
6663
7543
  if payload is not None:
6664
7544
  break
6665
7545
  if payload is not None and not payload.get("building"):
@@ -6705,7 +7585,12 @@ def cmd_verify_jenkins_build(args: argparse.Namespace) -> None:
6705
7585
  matched = None
6706
7586
  for candidate_job_url in candidate_job_urls:
6707
7587
  api_url = _jenkins_builds_api_url(candidate_job_url, max_builds)
6708
- payload = _jenkins_api_get_json(api_url, cfg, allow_404=True)
7588
+ payload = _jenkins_api_get_json(
7589
+ api_url,
7590
+ cfg,
7591
+ allow_404=True,
7592
+ component=component,
7593
+ )
6709
7594
  if payload is None:
6710
7595
  continue
6711
7596
  builds = payload.get("builds") or []
@@ -7955,6 +8840,11 @@ def cmd_task_start(args: argparse.Namespace) -> None:
7955
8840
  "only when classify requires isolation/review or the user explicitly requests it."
7956
8841
  )
7957
8842
  review_required = bool(getattr(args, "review_required", False) or plan["review_required"])
8843
+ review_depth, review_timeout_seconds = _normalized_task_review_policy(
8844
+ review_required,
8845
+ plan.get("review_depth"),
8846
+ getattr(args, "review_depth", ""),
8847
+ )
7958
8848
  registry_dir = _task_state_root(repo) / "tasks"
7959
8849
  other_active = any(
7960
8850
  _text((payload or {}).get("state"))
@@ -8009,6 +8899,8 @@ def cmd_task_start(args: argparse.Namespace) -> None:
8009
8899
  "scope_revision": 1,
8010
8900
  "effective_profile": plan["profile"],
8011
8901
  "design_required": bool(plan["design_required"]),
8902
+ "review_depth": review_depth,
8903
+ "review_timeout_seconds": review_timeout_seconds,
8012
8904
  "scope_history": [],
8013
8905
  "depends_on": depends_on,
8014
8906
  "prerequisite_shas": prerequisite_shas,
@@ -8094,6 +8986,8 @@ def cmd_task_start(args: argparse.Namespace) -> None:
8094
8986
  "scope_revision": 1,
8095
8987
  "effective_profile": plan["profile"],
8096
8988
  "design_required": bool(plan["design_required"]),
8989
+ "review_depth": review_depth,
8990
+ "review_timeout_seconds": review_timeout_seconds,
8097
8991
  "scope_history": [],
8098
8992
  "depends_on": depends_on,
8099
8993
  "prerequisite_shas": prerequisite_shas,
@@ -8168,18 +9062,49 @@ def _task_status_payload(repo: Path, manifest: dict) -> dict:
8168
9062
  remote = _text(manifest.get("remote")) or "origin"
8169
9063
  target = _text(manifest.get("target_branch"))
8170
9064
  remote_ref = f"refs/remotes/{remote}/{target}"
8171
- merged = bool(
9065
+ base_sha = _text(manifest.get("base_sha"))
9066
+ has_task_commits = bool(
8172
9067
  tip
9068
+ and base_sha
9069
+ and tip != base_sha
9070
+ and run(
9071
+ ["git", "merge-base", "--is-ancestor", base_sha, tip],
9072
+ cwd=repo,
9073
+ check=False,
9074
+ ).returncode
9075
+ == 0
9076
+ )
9077
+ merged = bool(
9078
+ has_task_commits
8173
9079
  and _git_ref_exists(repo, remote_ref)
8174
9080
  and run(["git", "merge-base", "--is-ancestor", tip, remote_ref], cwd=repo, check=False).returncode == 0
8175
9081
  )
9082
+ review = manifest.get("review") or {}
9083
+ deadline_at = _text(review.get("deadline_at"))
9084
+ review_seconds_remaining: Optional[int] = None
9085
+ review_deadline_expired = False
9086
+ if deadline_at:
9087
+ try:
9088
+ remaining = (
9089
+ _parse_iso_timestamp(deadline_at, "deadline_at")
9090
+ - _dt.datetime.now(_dt.timezone.utc)
9091
+ ).total_seconds()
9092
+ seconds = int(remaining)
9093
+ review_seconds_remaining = max(0, seconds)
9094
+ review_deadline_expired = remaining < 0
9095
+ except APError:
9096
+ review_deadline_expired = True
9097
+ review_seconds_remaining = 0
8176
9098
  return {
8177
9099
  **manifest,
8178
9100
  "worktree_exists": worktree.exists(),
8179
9101
  "dirty": bool(_git_status(worktree)) if worktree.exists() else False,
8180
9102
  "local_branch_exists": bool(tip),
8181
9103
  "tip": tip,
9104
+ "has_task_commits": has_task_commits,
8182
9105
  "merged_into_target": merged,
9106
+ "review_deadline_expired": review_deadline_expired,
9107
+ "review_seconds_remaining": review_seconds_remaining,
8183
9108
  "current_diff_fingerprint": _task_review_fingerprint(worktree, manifest)
8184
9109
  if worktree.exists()
8185
9110
  else "",
@@ -8210,7 +9135,9 @@ def cmd_task_status(args: argparse.Namespace) -> None:
8210
9135
  print(
8211
9136
  f"[task-status] task={status['task_id']} state={status.get('state')} "
8212
9137
  f"branch={status.get('task_branch')} worktree={status.get('worktree_path')} "
8213
- f"dirty={str(status['dirty']).lower()} merged={str(status['merged_into_target']).lower()}"
9138
+ f"dirty={str(status['dirty']).lower()} commits="
9139
+ f"{str(status['has_task_commits']).lower()} "
9140
+ f"merged={str(status['merged_into_target']).lower()}"
8214
9141
  )
8215
9142
 
8216
9143
 
@@ -8337,6 +9264,13 @@ def cmd_task_scope_add(args: argparse.Namespace) -> None:
8337
9264
  manifest["design_required"] = bool(
8338
9265
  manifest.get("design_required") or plan.get("design_required")
8339
9266
  )
9267
+ review_depth, review_timeout_seconds = _normalized_task_review_policy(
9268
+ bool(manifest["review_required"]),
9269
+ manifest.get("review_depth"),
9270
+ plan.get("review_depth"),
9271
+ )
9272
+ manifest["review_depth"] = review_depth
9273
+ manifest["review_timeout_seconds"] = review_timeout_seconds
8340
9274
  manifest["claimed_paths"] = []
8341
9275
  history = list(manifest.get("scope_history") or [])
8342
9276
  history.append(
@@ -8389,6 +9323,543 @@ def cmd_task_scope_add(args: argparse.Namespace) -> None:
8389
9323
  )
8390
9324
 
8391
9325
 
9326
+ def _parse_iso_timestamp(value: object, field: str) -> _dt.datetime:
9327
+ raw = _text(value)
9328
+ try:
9329
+ parsed = _dt.datetime.fromisoformat(raw.replace("Z", "+00:00"))
9330
+ except ValueError as exc:
9331
+ raise APError(f"Invalid {field} timestamp in review assignment: {raw!r}.") from exc
9332
+ if parsed.tzinfo is None:
9333
+ raise APError(f"Review assignment {field} must include a timezone.")
9334
+ return parsed.astimezone(_dt.timezone.utc)
9335
+
9336
+
9337
+ def _task_review_policy(cfg: dict, worktree: Path, manifest: dict) -> tuple[str, int]:
9338
+ changed_paths = _task_changed_paths_from_base(worktree, _text(manifest.get("base_sha")))
9339
+ plan = _resolve_execution_plan(
9340
+ cfg,
9341
+ worktree,
9342
+ changed_paths=changed_paths,
9343
+ planned_paths=list(manifest.get("owned_paths") or []),
9344
+ requested_task_kind="change",
9345
+ )
9346
+ return _normalized_task_review_policy(
9347
+ True,
9348
+ manifest.get("review_depth"),
9349
+ plan.get("review_depth"),
9350
+ )
9351
+
9352
+
9353
+ def cmd_review_assignment(args: argparse.Namespace) -> None:
9354
+ repo = Path(args.repo).resolve()
9355
+ ensure_git_repo(repo)
9356
+ cfg = _load_cfg(repo)
9357
+ task_id = _validate_task_id(args.task_id)
9358
+ control_repo, worktree, _ = _task_lifecycle_context(repo, cfg, task_id)
9359
+ timeout_s = float(_concurrency_cfg(cfg).get("lock_timeout_sec") or 30)
9360
+ with _repo_lock(control_repo, f"task-{task_id}", timeout_s=timeout_s):
9361
+ manifest = _load_task_manifest(control_repo, task_id)
9362
+ lifecycle_actor = _text(os.environ.get("CODEX_THREAD_ID"))
9363
+ if not lifecycle_actor or lifecycle_actor != _text(manifest.get("owner")):
9364
+ raise APError("Only the task lifecycle owner may issue a review assignment.")
9365
+ if _text(manifest.get("state")) not in {"active", "pushed", "integration-raced"}:
9366
+ raise APError(f"Task {task_id} is not reviewable in state={manifest.get('state')}.")
9367
+ if not bool(manifest.get("review_required")):
9368
+ raise APError(f"Task {task_id} does not require an independent review assignment.")
9369
+ if not worktree.exists():
9370
+ raise APError(f"Task worktree is missing: {worktree}")
9371
+ worktree_cfg = _load_cfg(worktree)
9372
+ unowned = _task_unowned_paths(worktree, worktree_cfg, manifest)
9373
+ if unowned:
9374
+ raise APError("Changes outside task owned_paths:\n- " + "\n- ".join(unowned))
9375
+ changed_paths = _task_changed_paths_from_base(
9376
+ worktree,
9377
+ _text(manifest.get("base_sha")),
9378
+ )
9379
+ owned_paths = [
9380
+ path
9381
+ for path in changed_paths
9382
+ if _path_is_owned(path, list(manifest.get("owned_paths") or []))
9383
+ ]
9384
+ if not owned_paths:
9385
+ raise APError("Cannot issue a review assignment before the task has an owned diff.")
9386
+ reviewer = _text(args.reviewer)
9387
+ if not reviewer or any(char in reviewer for char in "\0\r\n"):
9388
+ raise APError("Reviewer identity is empty or contains invalid characters.")
9389
+ owner = _text(manifest.get("owner"))
9390
+ owning_fixer = _text((manifest.get("writer_lease") or {}).get("holder")) or owner
9391
+ if reviewer in {owner, owning_fixer}:
9392
+ raise APError("Independent reviewer must differ from lifecycle owner and owning fixer.")
9393
+ fingerprint = _task_review_fingerprint(worktree, manifest, worktree_cfg)
9394
+ depth, review_timeout = _task_review_policy(worktree_cfg, worktree, manifest)
9395
+ issued = _dt.datetime.now(_dt.timezone.utc).replace(microsecond=0)
9396
+ deadline = issued + _dt.timedelta(seconds=review_timeout)
9397
+ assignment = {
9398
+ "contract_version": _AGENT_CONTRACT_VERSION,
9399
+ "node_id": reviewer,
9400
+ "task_id": task_id,
9401
+ "role": "reviewer",
9402
+ "base_sha": _text(manifest.get("base_sha")),
9403
+ "scope": f"Review the task-owned diff for {task_id}",
9404
+ "depends_on": [owning_fixer],
9405
+ "acceptance": [
9406
+ "Review only the assigned stable diff and supplied evidence.",
9407
+ "Return the complete 16-field reviewer result bound to diff_fingerprint.",
9408
+ ],
9409
+ "diff_base": _text(manifest.get("base_sha")),
9410
+ "diff_head": _resolve_commit(worktree, "HEAD"),
9411
+ "diff_fingerprint": fingerprint,
9412
+ "owning_fixer": owning_fixer,
9413
+ "review_depth": depth,
9414
+ "timeout_seconds": review_timeout,
9415
+ "issued_at": issued.isoformat(),
9416
+ "deadline_at": deadline.isoformat(),
9417
+ "scope_revision": int(manifest.get("scope_revision") or 1),
9418
+ }
9419
+ _validate_orchestration_contract("assignment", assignment)
9420
+ assignment_path = (
9421
+ _task_state_root(control_repo)
9422
+ / "reviews"
9423
+ / f"{task_id}-{fingerprint}.assignment.json"
9424
+ )
9425
+ prior_review = manifest.get("review") or {}
9426
+ if (
9427
+ _text(prior_review.get("diff_fingerprint")) == fingerprint
9428
+ and (
9429
+ _text(prior_review.get("verdict"))
9430
+ in {"approved", "changes-requested", "blocked"}
9431
+ or _text(prior_review.get("runtime_state"))
9432
+ or _text(prior_review.get("runtime_receipt_path"))
9433
+ )
9434
+ ):
9435
+ raise APError(
9436
+ "The single review attempt for this diff fingerprint is already complete or consumed."
9437
+ )
9438
+ existing_assignment = _read_json_object(assignment_path)
9439
+ if existing_assignment:
9440
+ _validate_orchestration_contract("assignment", existing_assignment)
9441
+ expected_fields = {
9442
+ "task_id": task_id,
9443
+ "base_sha": assignment["base_sha"],
9444
+ "diff_base": assignment["diff_base"],
9445
+ "diff_head": assignment["diff_head"],
9446
+ "diff_fingerprint": fingerprint,
9447
+ "owning_fixer": owning_fixer,
9448
+ "scope_revision": assignment["scope_revision"],
9449
+ }
9450
+ mismatched = [
9451
+ field
9452
+ for field, expected in expected_fields.items()
9453
+ if existing_assignment.get(field) != expected
9454
+ ]
9455
+ if mismatched:
9456
+ raise APError(
9457
+ "Existing review assignment does not match current task state: "
9458
+ + ", ".join(mismatched)
9459
+ )
9460
+ if _text(existing_assignment.get("node_id")) != reviewer:
9461
+ raise APError(
9462
+ "This diff fingerprint already has a reviewer assignment; "
9463
+ "the single review attempt cannot be reassigned."
9464
+ )
9465
+ existing_deadline = _parse_iso_timestamp(
9466
+ existing_assignment.get("deadline_at"),
9467
+ "deadline_at",
9468
+ )
9469
+ if _dt.datetime.now(_dt.timezone.utc) > existing_deadline:
9470
+ raise APError(
9471
+ "Review attempt timed out and is blocked for this diff fingerprint; "
9472
+ "do not renew it without a semantic diff/scope change or explicit user authorization."
9473
+ )
9474
+ assignment = existing_assignment
9475
+ depth = _text(assignment.get("review_depth"))
9476
+ review_timeout = int(assignment.get("timeout_seconds") or 0)
9477
+ elif (
9478
+ _text(prior_review.get("diff_fingerprint")) == fingerprint
9479
+ and _text(prior_review.get("deadline_at"))
9480
+ ):
9481
+ if _text(prior_review.get("reviewer")) != reviewer:
9482
+ raise APError(
9483
+ "This diff fingerprint already has a reviewer assignment; "
9484
+ "the single review attempt cannot be reassigned."
9485
+ )
9486
+ issued = _parse_iso_timestamp(prior_review.get("issued_at"), "issued_at")
9487
+ deadline = _parse_iso_timestamp(prior_review.get("deadline_at"), "deadline_at")
9488
+ if _dt.datetime.now(_dt.timezone.utc) > deadline:
9489
+ raise APError(
9490
+ "Review attempt timed out and is blocked for this diff fingerprint; "
9491
+ "do not renew it without a semantic diff/scope change or explicit user authorization."
9492
+ )
9493
+ assignment["issued_at"] = issued.isoformat()
9494
+ assignment["deadline_at"] = deadline.isoformat()
9495
+ assignment["timeout_seconds"] = int((deadline - issued).total_seconds())
9496
+ _validate_orchestration_contract("assignment", assignment)
9497
+ _write_json_object(assignment_path, assignment)
9498
+ depth = _text(assignment.get("review_depth"))
9499
+ review_timeout = int(assignment.get("timeout_seconds") or 0)
9500
+ else:
9501
+ _write_json_object(assignment_path, assignment)
9502
+ manifest["review_depth"] = depth
9503
+ manifest["review_timeout_seconds"] = review_timeout
9504
+ review_state = {
9505
+ "verdict": "pending",
9506
+ "diff_base": assignment["diff_base"],
9507
+ "diff_head": assignment["diff_head"],
9508
+ "diff_fingerprint": fingerprint,
9509
+ "reviewer": reviewer,
9510
+ "reviewed_at": "",
9511
+ "reason": "review assignment issued",
9512
+ "assignment_path": str(assignment_path),
9513
+ "issued_at": assignment["issued_at"],
9514
+ "deadline_at": assignment["deadline_at"],
9515
+ }
9516
+ if _text(prior_review.get("diff_fingerprint")) == fingerprint:
9517
+ for field in _REVIEW_RUNTIME_FIELDS:
9518
+ if field in prior_review:
9519
+ review_state[field] = prior_review[field]
9520
+ manifest["review"] = review_state
9521
+ _save_task_manifest(control_repo, manifest)
9522
+ if bool(getattr(args, "json", False)):
9523
+ print(
9524
+ json.dumps(
9525
+ {"assignment_path": str(assignment_path), "assignment": assignment},
9526
+ ensure_ascii=False,
9527
+ indent=2,
9528
+ )
9529
+ )
9530
+ else:
9531
+ print(f"[review-assignment] task={task_id} reviewer={reviewer} depth={depth}")
9532
+ print(f"[review-assignment] timeout_seconds={review_timeout}")
9533
+ print(f"[review-assignment] assignment={assignment_path}")
9534
+
9535
+
9536
+ def _write_private_json(path: Path, payload: dict) -> None:
9537
+ _write_json_object(path, payload)
9538
+ try:
9539
+ path.chmod(0o600)
9540
+ except OSError as exc:
9541
+ raise APError(f"Cannot protect Git-local review state: {path}: {exc}") from exc
9542
+
9543
+
9544
+ def _review_runtime_paths(
9545
+ control_repo: Path,
9546
+ task_id: str,
9547
+ fingerprint: str,
9548
+ ) -> tuple[Path, Path]:
9549
+ root = _task_state_root(control_repo) / "reviews"
9550
+ stem = f"{_validate_task_id(task_id)}-{fingerprint}"
9551
+ return root / f"{stem}.result.json", root / f"{stem}.run.json"
9552
+
9553
+
9554
+ def _review_command_sha256(command: list[str]) -> str:
9555
+ digest = hashlib.sha256()
9556
+ for argument in command:
9557
+ digest.update(argument.encode("utf-8", errors="surrogateescape"))
9558
+ digest.update(b"\0")
9559
+ return digest.hexdigest()
9560
+
9561
+
9562
+ def _bounded_reviewer_output(value: str, label: str) -> str:
9563
+ encoded = value.encode("utf-8", errors="replace")
9564
+ if len(encoded) > _REVIEW_OUTPUT_MAX_BYTES:
9565
+ raise APError(f"Reviewer {label} exceeded {_REVIEW_OUTPUT_MAX_BYTES} bytes; refusing oversized output.")
9566
+ return value
9567
+
9568
+
9569
+ def _read_bounded_reviewer_output(path: Path) -> str:
9570
+ try:
9571
+ with path.open("rb") as handle:
9572
+ payload = handle.read(_REVIEW_OUTPUT_MAX_BYTES + 1)
9573
+ except OSError as exc:
9574
+ raise APError(f"Cannot read Reviewer result: {path}: {exc}") from exc
9575
+ if len(payload) > _REVIEW_OUTPUT_MAX_BYTES:
9576
+ raise APError(f"Reviewer result exceeded {_REVIEW_OUTPUT_MAX_BYTES} bytes; refusing oversized output.")
9577
+ return payload.decode("utf-8", errors="strict")
9578
+
9579
+
9580
+ def _review_result_file_sha256(path: Path) -> str:
9581
+ try:
9582
+ with path.open("rb") as handle:
9583
+ payload = handle.read(_REVIEW_OUTPUT_MAX_BYTES + 1)
9584
+ except OSError as exc:
9585
+ raise APError(f"Cannot hash Reviewer result: {path}: {exc}") from exc
9586
+ if len(payload) > _REVIEW_OUTPUT_MAX_BYTES:
9587
+ raise APError(f"Reviewer result exceeded {_REVIEW_OUTPUT_MAX_BYTES} bytes; refusing oversized output.")
9588
+ return hashlib.sha256(payload).hexdigest()
9589
+
9590
+
9591
+ def _update_review_runtime(
9592
+ control_repo: Path,
9593
+ task_id: str,
9594
+ fingerprint: str,
9595
+ *,
9596
+ updates: dict,
9597
+ receipt_path: Path,
9598
+ receipt_updates: dict,
9599
+ ) -> dict:
9600
+ cfg = _load_cfg(control_repo)
9601
+ timeout_s = float(_concurrency_cfg(cfg).get("lock_timeout_sec") or 30)
9602
+ with _repo_lock(control_repo, f"task-{task_id}", timeout_s=timeout_s):
9603
+ manifest = _load_task_manifest(control_repo, task_id)
9604
+ review = dict(manifest.get("review") or {})
9605
+ if _text(review.get("diff_fingerprint")) != fingerprint:
9606
+ raise APError("Reviewer runtime assignment became stale while the process was running.")
9607
+ review.update(updates)
9608
+ manifest["review"] = review
9609
+ receipt = _read_json_object(receipt_path) or {}
9610
+ receipt.update(receipt_updates)
9611
+ _write_private_json(receipt_path, receipt)
9612
+ _save_task_manifest(control_repo, manifest)
9613
+ return manifest
9614
+
9615
+
9616
+ def _blocked_reviewer_runtime_result(
9617
+ assignment: dict,
9618
+ reason: str,
9619
+ evidence: list[str],
9620
+ ) -> dict:
9621
+ result = _reviewer_result_template(assignment, "blocked")
9622
+ result["summary"] = reason
9623
+ result["evidence"] = evidence
9624
+ return _validate_orchestration_contract("result", result)
9625
+
9626
+
9627
+ def cmd_review_run(args: argparse.Namespace) -> None:
9628
+ repo = Path(args.repo).resolve()
9629
+ ensure_git_repo(repo)
9630
+ cfg = _load_cfg(repo)
9631
+ task_id = _validate_task_id(args.task_id)
9632
+ reviewer = _text(args.reviewer)
9633
+ with contextlib.redirect_stdout(io.StringIO()):
9634
+ cmd_review_assignment(
9635
+ argparse.Namespace(
9636
+ repo=str(repo),
9637
+ task_id=task_id,
9638
+ reviewer=reviewer,
9639
+ json=False,
9640
+ )
9641
+ )
9642
+
9643
+ control_repo, worktree, _ = _task_lifecycle_context(repo, cfg, task_id)
9644
+ manifest = _load_task_manifest(control_repo, task_id)
9645
+ review = manifest.get("review") or {}
9646
+ assignment_path = Path(_text(review.get("assignment_path"))).resolve()
9647
+ assignment = _read_json_object(assignment_path)
9648
+ if not assignment:
9649
+ raise APError("Review assignment file is missing or invalid.")
9650
+ _validate_orchestration_contract("assignment", assignment)
9651
+ fingerprint = _text(assignment.get("diff_fingerprint"))
9652
+ result_path, receipt_path = _review_runtime_paths(control_repo, task_id, fingerprint)
9653
+
9654
+ command_override = _text(getattr(args, "runner_command_json", ""))
9655
+ if command_override:
9656
+ try:
9657
+ command_value = json.loads(command_override)
9658
+ except json.JSONDecodeError as exc:
9659
+ raise APError("--runner-command-json must be a JSON array of argv strings.") from exc
9660
+ if not isinstance(command_value, list) or not command_value or not all(
9661
+ isinstance(item, str) and item for item in command_value
9662
+ ):
9663
+ raise APError("--runner-command-json must be a non-empty JSON array of argv strings.")
9664
+ command = command_value
9665
+ else:
9666
+ command = _codex_reviewer_command(worktree, assignment_path, result_path)
9667
+ command_sha256 = _review_command_sha256(command)
9668
+ started_at = _now_iso()
9669
+ receipt = {
9670
+ "schema": 1,
9671
+ "task_id": task_id,
9672
+ "reviewer": reviewer,
9673
+ "diff_fingerprint": fingerprint,
9674
+ "assignment_path": str(assignment_path),
9675
+ "result_path": str(result_path),
9676
+ "command_sha256": command_sha256,
9677
+ "status": "starting",
9678
+ "started_at": started_at,
9679
+ "finished_at": "",
9680
+ "exit_code": None,
9681
+ }
9682
+ timeout_s = float(_concurrency_cfg(_load_cfg(control_repo)).get("lock_timeout_sec") or 30)
9683
+ with _repo_lock(control_repo, f"task-{task_id}", timeout_s=timeout_s):
9684
+ manifest = _load_task_manifest(control_repo, task_id)
9685
+ current_review = dict(manifest.get("review") or {})
9686
+ if _text(current_review.get("diff_fingerprint")) != fingerprint:
9687
+ raise APError("Review assignment became stale before Reviewer runtime start.")
9688
+ if _text(current_review.get("runtime_state")) or receipt_path.exists():
9689
+ raise APError(
9690
+ "The supervised Reviewer runtime has already started for this diff fingerprint."
9691
+ )
9692
+ deadline = _parse_iso_timestamp(assignment.get("deadline_at"), "deadline_at")
9693
+ if _dt.datetime.now(_dt.timezone.utc) >= deadline:
9694
+ raise APError("Review assignment deadline expired before Reviewer runtime start.")
9695
+ _write_private_json(receipt_path, receipt)
9696
+ current_review.update(
9697
+ {
9698
+ "runtime_state": "starting",
9699
+ "runtime_started_at": started_at,
9700
+ "runtime_finished_at": "",
9701
+ "runtime_result_path": str(result_path),
9702
+ "runtime_exit_code": None,
9703
+ "runtime_command_sha256": command_sha256,
9704
+ "runtime_receipt_path": str(receipt_path),
9705
+ }
9706
+ )
9707
+ manifest["review"] = current_review
9708
+ _save_task_manifest(control_repo, manifest)
9709
+
9710
+ env = os.environ.copy()
9711
+ env.pop("CODEX_THREAD_ID", None)
9712
+ env.update(
9713
+ {
9714
+ "AUTOCODING_REVIEW_ASSIGNMENT": str(assignment_path),
9715
+ "AUTOCODING_REVIEW_RESULT": str(result_path),
9716
+ "AUTOCODING_REVIEW_DEADLINE": _text(assignment.get("deadline_at")),
9717
+ "AUTOCODING_REVIEW_TIMEOUT_SECONDS": str(int(assignment.get("timeout_seconds") or 0)),
9718
+ }
9719
+ )
9720
+ deadline = _parse_iso_timestamp(assignment.get("deadline_at"), "deadline_at")
9721
+ remaining = (deadline - _dt.datetime.now(_dt.timezone.utc)).total_seconds()
9722
+ try:
9723
+ completed = _run_supervised_reviewer_process(
9724
+ command,
9725
+ cwd=worktree,
9726
+ env=env,
9727
+ timeout_seconds=remaining,
9728
+ )
9729
+ except _ReviewerRuntimeTimeout as exc:
9730
+ finished_at = _now_iso()
9731
+ result = _blocked_reviewer_runtime_result(
9732
+ assignment,
9733
+ "Reviewer runtime reached its fixed deadline and was terminated.",
9734
+ ["runtime_timeout=true"],
9735
+ )
9736
+ _write_private_json(result_path, result)
9737
+ _update_review_runtime(
9738
+ control_repo,
9739
+ task_id,
9740
+ fingerprint,
9741
+ updates={
9742
+ "verdict": "blocked",
9743
+ "reason": "reviewer runtime timeout",
9744
+ "runtime_state": "timed-out",
9745
+ "runtime_finished_at": finished_at,
9746
+ "runtime_exit_code": None,
9747
+ },
9748
+ receipt_path=receipt_path,
9749
+ receipt_updates={
9750
+ "status": "timed-out",
9751
+ "finished_at": finished_at,
9752
+ "exit_code": None,
9753
+ },
9754
+ )
9755
+ print(json.dumps(result, ensure_ascii=False, indent=2))
9756
+ raise APError("Reviewer runtime timed out and was terminated; review is blocked.") from exc
9757
+
9758
+ finished_at = _now_iso()
9759
+ if completed.returncode != 0:
9760
+ result = _blocked_reviewer_runtime_result(
9761
+ assignment,
9762
+ "Reviewer runtime exited unsuccessfully.",
9763
+ [f"runner_exit_code={completed.returncode}"],
9764
+ )
9765
+ _write_private_json(result_path, result)
9766
+ _update_review_runtime(
9767
+ control_repo,
9768
+ task_id,
9769
+ fingerprint,
9770
+ updates={
9771
+ "verdict": "blocked",
9772
+ "reason": "reviewer runtime failed",
9773
+ "runtime_state": "failed",
9774
+ "runtime_finished_at": finished_at,
9775
+ "runtime_exit_code": completed.returncode,
9776
+ },
9777
+ receipt_path=receipt_path,
9778
+ receipt_updates={
9779
+ "status": "failed",
9780
+ "finished_at": finished_at,
9781
+ "exit_code": completed.returncode,
9782
+ },
9783
+ )
9784
+ print(json.dumps(result, ensure_ascii=False, indent=2))
9785
+ raise APError(
9786
+ f"Reviewer runtime failed with exit code {completed.returncode}; review is blocked."
9787
+ )
9788
+
9789
+ try:
9790
+ stdout = _bounded_reviewer_output(completed.stdout, "stdout")
9791
+ _bounded_reviewer_output(completed.stderr, "stderr")
9792
+ raw = _read_bounded_reviewer_output(result_path) if result_path.exists() else stdout
9793
+ payload = json.loads(raw)
9794
+ result = _normalize_reviewer_runtime_result(assignment, payload)
9795
+ except (APError, json.JSONDecodeError, UnicodeDecodeError) as exc:
9796
+ result = _blocked_reviewer_runtime_result(
9797
+ assignment,
9798
+ "Reviewer runtime returned an invalid result.",
9799
+ ["result_contract_valid=false"],
9800
+ )
9801
+ _write_private_json(result_path, result)
9802
+ _update_review_runtime(
9803
+ control_repo,
9804
+ task_id,
9805
+ fingerprint,
9806
+ updates={
9807
+ "verdict": "blocked",
9808
+ "reason": "invalid reviewer runtime result",
9809
+ "runtime_state": "failed",
9810
+ "runtime_finished_at": finished_at,
9811
+ "runtime_exit_code": completed.returncode,
9812
+ },
9813
+ receipt_path=receipt_path,
9814
+ receipt_updates={
9815
+ "status": "result-invalid",
9816
+ "finished_at": finished_at,
9817
+ "exit_code": completed.returncode,
9818
+ },
9819
+ )
9820
+ print(json.dumps(result, ensure_ascii=False, indent=2))
9821
+ raise APError(f"Reviewer runtime result is invalid; review is blocked: {exc}") from exc
9822
+
9823
+ _write_private_json(result_path, result)
9824
+ result_sha256 = _review_result_file_sha256(result_path)
9825
+ runtime_state = "blocked" if result["verdict"] == "blocked" else "completed"
9826
+ _update_review_runtime(
9827
+ control_repo,
9828
+ task_id,
9829
+ fingerprint,
9830
+ updates={
9831
+ "verdict": "blocked" if result["verdict"] == "blocked" else "pending",
9832
+ "reason": "reviewer reported blocked" if result["verdict"] == "blocked" else "",
9833
+ "runtime_state": runtime_state,
9834
+ "runtime_finished_at": finished_at,
9835
+ "runtime_exit_code": completed.returncode,
9836
+ },
9837
+ receipt_path=receipt_path,
9838
+ receipt_updates={
9839
+ "status": runtime_state,
9840
+ "finished_at": finished_at,
9841
+ "exit_code": completed.returncode,
9842
+ "verdict": result["verdict"],
9843
+ "result_sha256": result_sha256,
9844
+ },
9845
+ )
9846
+ if result["verdict"] == "blocked":
9847
+ print(json.dumps(result, ensure_ascii=False, indent=2))
9848
+ raise APError("Reviewer returned blocked; task-review was not recorded.")
9849
+
9850
+ with contextlib.redirect_stdout(io.StringIO()):
9851
+ cmd_task_review(
9852
+ argparse.Namespace(
9853
+ repo=str(repo),
9854
+ task_id=task_id,
9855
+ verdict=result["verdict"],
9856
+ diff_fingerprint=fingerprint,
9857
+ reviewer=reviewer,
9858
+ )
9859
+ )
9860
+ print(json.dumps(result, ensure_ascii=False, indent=2))
9861
+
9862
+
8392
9863
  def cmd_task_review(args: argparse.Namespace) -> None:
8393
9864
  repo = Path(args.repo).resolve()
8394
9865
  ensure_git_repo(repo)
@@ -8426,7 +9897,137 @@ def cmd_task_review(args: argparse.Namespace) -> None:
8426
9897
  writer = _text((manifest.get("writer_lease") or {}).get("holder"))
8427
9898
  if reviewer == writer:
8428
9899
  raise APError("Independent reviewer identity must differ from the current writer lease holder.")
8429
- manifest["review"] = {
9900
+ assigned_review = manifest.get("review") or {}
9901
+ if bool(manifest.get("review_required")) and not all(
9902
+ _text(assigned_review.get(field))
9903
+ for field in ("assignment_path", "reviewer", "diff_fingerprint", "deadline_at")
9904
+ ):
9905
+ raise APError(
9906
+ "Review-required tasks must use review-assignment before task-review."
9907
+ )
9908
+ assigned_reviewer = _text(assigned_review.get("reviewer"))
9909
+ if assigned_reviewer and reviewer != assigned_reviewer:
9910
+ raise APError(
9911
+ f"Review verdict reviewer mismatch: assigned={assigned_reviewer}, supplied={reviewer}."
9912
+ )
9913
+ assigned_fingerprint = _text(assigned_review.get("diff_fingerprint"))
9914
+ if assigned_fingerprint and assigned_fingerprint != fingerprint:
9915
+ raise APError("Review assignment is stale; issue a new assignment for the current diff.")
9916
+ assigned_head = _text(assigned_review.get("diff_head"))
9917
+ current_head = _resolve_commit(worktree, "HEAD")
9918
+ if assigned_head and assigned_head != current_head:
9919
+ raise APError("Review assignment HEAD is stale for the current task.")
9920
+ assignment_path = _text(assigned_review.get("assignment_path"))
9921
+ assignment: Optional[dict] = None
9922
+ if assignment_path:
9923
+ expected_assignment_path = (
9924
+ _task_state_root(control_repo)
9925
+ / "reviews"
9926
+ / f"{task_id}-{fingerprint}.assignment.json"
9927
+ ).resolve()
9928
+ if Path(assignment_path).resolve() != expected_assignment_path:
9929
+ raise APError("Review assignment path does not match Git-local task state.")
9930
+ assignment = _read_json_object(expected_assignment_path)
9931
+ if not assignment:
9932
+ raise APError("Review assignment file is missing or invalid.")
9933
+ _validate_orchestration_contract("assignment", assignment)
9934
+ expected_assignment_fields = {
9935
+ "task_id": task_id,
9936
+ "base_sha": _text(manifest.get("base_sha")),
9937
+ "diff_base": _text(manifest.get("base_sha")),
9938
+ "diff_head": current_head,
9939
+ "diff_fingerprint": fingerprint,
9940
+ "node_id": reviewer,
9941
+ "owning_fixer": _text((manifest.get("writer_lease") or {}).get("holder")),
9942
+ "issued_at": _text(assigned_review.get("issued_at")),
9943
+ "deadline_at": _text(assigned_review.get("deadline_at")),
9944
+ }
9945
+ mismatched = [
9946
+ field
9947
+ for field, expected in expected_assignment_fields.items()
9948
+ if assignment.get(field) != expected
9949
+ ]
9950
+ if mismatched:
9951
+ raise APError(
9952
+ "Review assignment does not match the recorded task state: "
9953
+ + ", ".join(mismatched)
9954
+ )
9955
+ if int(assignment.get("scope_revision") or 0) != int(
9956
+ manifest.get("scope_revision") or 1
9957
+ ):
9958
+ raise APError("Review assignment scope revision is stale.")
9959
+ runtime_state = _text(assigned_review.get("runtime_state"))
9960
+ if runtime_state:
9961
+ if runtime_state != "completed":
9962
+ raise APError(
9963
+ f"Reviewer runtime state={runtime_state} cannot be recorded by task-review."
9964
+ )
9965
+ if assignment is None:
9966
+ raise APError("Reviewer runtime result has no validated assignment.")
9967
+ if assigned_review.get("runtime_exit_code") != 0:
9968
+ raise APError("Reviewer runtime did not exit successfully.")
9969
+ expected_result_path, expected_receipt_path = _review_runtime_paths(
9970
+ control_repo,
9971
+ task_id,
9972
+ fingerprint,
9973
+ )
9974
+ result_path = Path(_text(assigned_review.get("runtime_result_path"))).resolve()
9975
+ receipt_path = Path(_text(assigned_review.get("runtime_receipt_path"))).resolve()
9976
+ if result_path != expected_result_path.resolve():
9977
+ raise APError("Reviewer runtime result path does not match Git-local task state.")
9978
+ if receipt_path != expected_receipt_path.resolve():
9979
+ raise APError("Reviewer runtime receipt path does not match Git-local task state.")
9980
+ try:
9981
+ result_payload = json.loads(_read_bounded_reviewer_output(result_path))
9982
+ except (json.JSONDecodeError, UnicodeDecodeError) as exc:
9983
+ raise APError("Reviewer runtime result file is invalid JSON.") from exc
9984
+ if not isinstance(result_payload, dict):
9985
+ raise APError("Reviewer runtime result file must contain one JSON object.")
9986
+ _validate_orchestration_contract("result", result_payload)
9987
+ normalized_result = _normalize_reviewer_runtime_result(assignment, result_payload)
9988
+ if result_payload != normalized_result:
9989
+ raise APError("Reviewer runtime result file is not the canonical bound result.")
9990
+ if _text(result_payload.get("verdict")) != _text(args.verdict):
9991
+ raise APError(
9992
+ "Reviewer runtime verdict does not match the requested task-review verdict."
9993
+ )
9994
+ receipt = _read_json_object(receipt_path)
9995
+ if not receipt:
9996
+ raise APError("Reviewer runtime receipt is missing or invalid.")
9997
+ expected_receipt = {
9998
+ "task_id": task_id,
9999
+ "reviewer": reviewer,
10000
+ "diff_fingerprint": fingerprint,
10001
+ "result_path": str(expected_result_path),
10002
+ "status": "completed",
10003
+ "verdict": _text(args.verdict),
10004
+ "result_sha256": _review_result_file_sha256(result_path),
10005
+ }
10006
+ receipt_mismatches = [
10007
+ field
10008
+ for field, expected in expected_receipt.items()
10009
+ if receipt.get(field) != expected
10010
+ ]
10011
+ if receipt_mismatches:
10012
+ raise APError(
10013
+ "Reviewer runtime receipt does not bind the recorded result: "
10014
+ + ", ".join(receipt_mismatches)
10015
+ )
10016
+ deadline_at = _text(assigned_review.get("deadline_at"))
10017
+ completed_at = _dt.datetime.now(_dt.timezone.utc)
10018
+ if (
10019
+ _text(assigned_review.get("runtime_state")) == "completed"
10020
+ and _text(assigned_review.get("runtime_finished_at"))
10021
+ ):
10022
+ completed_at = _parse_iso_timestamp(
10023
+ assigned_review.get("runtime_finished_at"),
10024
+ "runtime_finished_at",
10025
+ )
10026
+ if deadline_at and completed_at > _parse_iso_timestamp(deadline_at, "deadline_at"):
10027
+ raise APError(
10028
+ "Review assignment deadline expired; the single review attempt is blocked."
10029
+ )
10030
+ review_state = {
8430
10031
  "verdict": args.verdict,
8431
10032
  "diff_base": _text(manifest.get("base_sha")),
8432
10033
  "diff_head": _resolve_commit(worktree, "HEAD"),
@@ -8434,7 +10035,16 @@ def cmd_task_review(args: argparse.Namespace) -> None:
8434
10035
  "reviewer": reviewer,
8435
10036
  "reviewed_at": _now_iso(),
8436
10037
  "reason": "",
10038
+ "assignment_path": assignment_path,
10039
+ "issued_at": _text(assigned_review.get("issued_at")),
10040
+ "deadline_at": deadline_at,
10041
+ "review_depth": _text(manifest.get("review_depth")),
10042
+ "review_timeout_seconds": int(manifest.get("review_timeout_seconds") or 0),
8437
10043
  }
10044
+ for field in _REVIEW_RUNTIME_FIELDS:
10045
+ if field in assigned_review:
10046
+ review_state[field] = assigned_review[field]
10047
+ manifest["review"] = review_state
8438
10048
  _save_task_manifest(control_repo, manifest)
8439
10049
  print(f"[task-review] task={task_id} verdict={args.verdict} fingerprint={fingerprint}")
8440
10050
 
@@ -9458,6 +11068,20 @@ def main(argv: Optional[List[str]] = None) -> int:
9458
11068
  s.add_argument("--json", action="store_true")
9459
11069
  s.set_defaults(func=cmd_agent_contract_check)
9460
11070
 
11071
+ s = sp.add_parser(
11072
+ "agent-result-template",
11073
+ help="Generate a complete reviewer result from a validated assignment",
11074
+ )
11075
+ source = s.add_mutually_exclusive_group(required=True)
11076
+ source.add_argument("--file")
11077
+ source.add_argument("--payload")
11078
+ s.add_argument(
11079
+ "--verdict",
11080
+ choices=["approved", "changes-requested", "blocked"],
11081
+ required=True,
11082
+ )
11083
+ s.set_defaults(func=cmd_agent_result_template)
11084
+
9461
11085
  s = sp.add_parser("validation-map-check")
9462
11086
  s.add_argument("--base")
9463
11087
  s.add_argument("--path", action="append")
@@ -9507,12 +11131,17 @@ def main(argv: Optional[List[str]] = None) -> int:
9507
11131
 
9508
11132
  s = sp.add_parser("wait-health")
9509
11133
  s.add_argument("--scope", choices=["runtime", "target", "prod"], default="runtime")
11134
+ s.add_argument("--component", choices=["frontend", "backend"], default="backend")
11135
+ s.add_argument("--path")
11136
+ s.add_argument("--timeout-sec", type=int)
9510
11137
  s.set_defaults(func=cmd_wait_health)
9511
11138
 
9512
11139
  s = sp.add_parser("verify-jenkins")
11140
+ s.add_argument("--component", choices=["all", "frontend", "backend"], default="all")
9513
11141
  s.set_defaults(func=cmd_verify_jenkins)
9514
11142
 
9515
11143
  s = sp.add_parser("verify-jenkins-build")
11144
+ s.add_argument("--component", choices=["frontend", "backend"])
9516
11145
  s.add_argument("--git-ref")
9517
11146
  s.add_argument("--job-name")
9518
11147
  s.add_argument("--job-url")
@@ -9562,6 +11191,7 @@ def main(argv: Optional[List[str]] = None) -> int:
9562
11191
  s.add_argument("--writers", type=int, default=1)
9563
11192
  s.add_argument("--isolated", action="store_true")
9564
11193
  s.add_argument("--review-required", action="store_true")
11194
+ s.add_argument("--review-depth", choices=["focused", "deep"])
9565
11195
  s.add_argument("--continue-direct", action="store_true")
9566
11196
  s.add_argument("--direct-claim")
9567
11197
  s.add_argument(
@@ -9589,6 +11219,25 @@ def main(argv: Optional[List[str]] = None) -> int:
9589
11219
  s.add_argument("--json", action="store_true")
9590
11220
  s.set_defaults(func=cmd_task_scope_add)
9591
11221
 
11222
+ s = sp.add_parser(
11223
+ "review-assignment",
11224
+ help="Generate and persist a deadline-bound reviewer assignment for a registered task",
11225
+ )
11226
+ s.add_argument("task_id")
11227
+ s.add_argument("--reviewer", required=True)
11228
+ s.add_argument("--json", action="store_true")
11229
+ s.set_defaults(func=cmd_review_assignment)
11230
+
11231
+ s = sp.add_parser(
11232
+ "review-run",
11233
+ help="Run the independent Codex Reviewer under the assignment's fixed runtime deadline",
11234
+ )
11235
+ s.add_argument("task_id")
11236
+ s.add_argument("--reviewer", required=True)
11237
+ s.add_argument("--json", action="store_true")
11238
+ s.add_argument("--runner-command-json", help=argparse.SUPPRESS)
11239
+ s.set_defaults(func=cmd_review_run)
11240
+
9592
11241
  s = sp.add_parser("task-submodule-sync")
9593
11242
  s.add_argument("task_id")
9594
11243
  s.set_defaults(func=cmd_task_submodule_sync)