@elvis1513/auto-coding-skill 4.1.3 → 4.1.6

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.
@@ -24,12 +24,7 @@ import uuid
24
24
  from pathlib import Path
25
25
  from typing import Iterator, Optional, List
26
26
 
27
- try:
28
- import yaml # type: ignore
29
- except Exception:
30
- yaml = None
31
-
32
- from core import APError, ensure_git_repo, copy_tree, run, load_yaml, find_config, run_shell, http_get_status
27
+ from core import APError, ensure_git_repo, copy_tree, run, load_yaml, find_config, run_shell, http_get_status, require_yaml
33
28
  from scaffold_templates import scaffold_groups, templates_for
34
29
 
35
30
 
@@ -51,7 +46,7 @@ _RECOMMENDED_FINAL_TOTAL_SECONDS = 180.0
51
46
  _WORKFLOW_MIGRATION_POLICY = Path("data/policies/workflow-migrations-v1.json")
52
47
  _FALLBACK_WORKFLOW_MIGRATION_POLICY = {
53
48
  "schema_version": 1,
54
- "managed_versions": {"agents": "4.1.3", "engineering": "4.1.3"},
49
+ "managed_versions": {"agents": "4.1.6", "engineering": "4.1.6"},
55
50
  "known_official_engineering_body_sha256": [
56
51
  "d1306cc626e8baf8c83c953b760fd771066de2bf125168eca3a7b7d6ff2b87a2",
57
52
  "305931c6edef770033a4f1970b00e5fb1c1728351856a173dbfa497daf563021",
@@ -178,13 +173,13 @@ def _evidence_log_path(repo: Path, cfg: dict) -> Path:
178
173
  return Path(repo, task_dir, f"{manifest['task_id']}.jsonl")
179
174
  if _bool_config(docs_cfg.get("track_evidence"), False) and _text(docs_cfg.get("evidence_log")):
180
175
  return Path(repo, _text(docs_cfg.get("evidence_log")))
181
- return Path(repo, ".local/auto-coding-skill/evidence.jsonl")
176
+ return _task_state_root(repo) / "evidence.jsonl"
182
177
 
183
178
 
184
179
  def _gate_profile_path(repo: Path, cfg: dict) -> Path:
185
180
  gate_cfg = _gate_cfg(cfg)
186
- rel = _text(gate_cfg.get("profile_log")) or ".local/auto-coding-skill/gate-profile.jsonl"
187
- return Path(repo, rel)
181
+ rel = _text(gate_cfg.get("profile_log"))
182
+ return Path(repo, rel) if rel else _task_state_root(repo) / "gate-profile.jsonl"
188
183
 
189
184
 
190
185
  def _record_evidence(repo: Path, cfg: dict, event: str, status: str, payload: Optional[dict] = None) -> None:
@@ -638,8 +633,8 @@ def _migrate_fast_development_defaults(cfg: dict, repo: Path) -> list[str]:
638
633
  if _text(workflow_cfg.get("completion")).lower() != "push":
639
634
  workflow_cfg["completion"] = "push"
640
635
  changed.append("workflow.completion")
641
- if _text(workflow_cfg.get("skill_version")) != "4.1.3":
642
- workflow_cfg["skill_version"] = "4.1.3"
636
+ if _text(workflow_cfg.get("skill_version")) != "4.1.6":
637
+ workflow_cfg["skill_version"] = "4.1.6"
643
638
  changed.append("workflow.skill_version")
644
639
 
645
640
  commands_cfg = cfg.setdefault("commands", {})
@@ -952,16 +947,16 @@ def cmd_upgrade(args: argparse.Namespace) -> None:
952
947
  if current_agents:
953
948
  archive_dir = repo / "docs" / "archive" / "workflow"
954
949
  archive_header = (
955
- "# Archived AGENTS.md before auto-coding-skill 4.1.3\n\n"
950
+ "# Archived AGENTS.md before auto-coding-skill 4.1.6\n\n"
956
951
  "This file is historical and non-authoritative. The root AGENTS.md is fully managed.\n"
957
952
  "Move any still-current project facts into docs/ENGINEERING.md or docs/project/,\n"
958
953
  "without copying workflow rules back into the root AGENTS.md.\n\n---\n\n"
959
954
  )
960
955
  archive_content = archive_header + current_agents
961
- archive = archive_dir / "AGENTS.pre-4.1.3.md"
956
+ archive = archive_dir / "AGENTS.pre-4.1.6.md"
962
957
  if archive.exists() and archive.read_text(encoding="utf-8") != archive_content:
963
958
  digest = hashlib.sha256(current_agents.encode("utf-8")).hexdigest()[:12]
964
- archive = archive_dir / f"AGENTS.pre-4.1.3-{digest}.md"
959
+ archive = archive_dir / f"AGENTS.pre-4.1.6-{digest}.md"
965
960
  if not archive.exists():
966
961
  add_action("policy", archive, "archive", "historical and non-authoritative")
967
962
  if write:
@@ -1606,9 +1601,7 @@ def _parse_frontmatter_markdown_text(text: str, path: Path) -> tuple[dict, str]:
1606
1601
  m = re.match(r"^---\s*\n(.*?)\n---\s*(\n|$)(.*)$", text, flags=re.DOTALL)
1607
1602
  if not m:
1608
1603
  raise APError(f"Markdown frontmatter not found: {path}")
1609
- if yaml is None:
1610
- raise APError("PyYAML not installed. Install dependencies with: pip install pyyaml requests")
1611
- data = yaml.safe_load(m.group(1)) or {}
1604
+ data = require_yaml().safe_load(m.group(1)) or {}
1612
1605
  return data, m.group(3)
1613
1606
 
1614
1607
 
@@ -1619,9 +1612,7 @@ def _read_frontmatter_markdown(path: Path) -> tuple[dict, str]:
1619
1612
 
1620
1613
 
1621
1614
  def _write_frontmatter_markdown(path: Path, data: dict, body: str) -> None:
1622
- if yaml is None:
1623
- raise APError("PyYAML not installed. Install dependencies with: pip install pyyaml requests")
1624
- dumped = yaml.safe_dump(data, allow_unicode=True, sort_keys=False).strip()
1615
+ dumped = require_yaml().safe_dump(data, allow_unicode=True, sort_keys=False).strip()
1625
1616
  path.write_text(f"---\n{dumped}\n---\n{body}", encoding="utf-8")
1626
1617
 
1627
1618
 
@@ -1662,6 +1653,7 @@ def _text(value: object) -> str:
1662
1653
 
1663
1654
 
1664
1655
  _TASK_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
1656
+ _DIRECT_CLAIM_ID_RE = re.compile(r"^[0-9a-f]{32}$")
1665
1657
 
1666
1658
 
1667
1659
  def _concurrency_cfg(cfg: dict) -> dict:
@@ -1732,6 +1724,123 @@ def _task_registry_path(repo: Path, task_id: str) -> Path:
1732
1724
  return _task_state_root(repo) / "tasks" / f"{_validate_task_id(task_id)}.json"
1733
1725
 
1734
1726
 
1727
+ def _direct_claim_path(repo: Path, claim_id: str) -> Path:
1728
+ value = _text(claim_id)
1729
+ if not _DIRECT_CLAIM_ID_RE.fullmatch(value):
1730
+ raise APError("Direct claim ID must be a 32-character lowercase hexadecimal token.")
1731
+ return _task_state_root(repo) / "direct-claims" / f"{value}.json"
1732
+
1733
+
1734
+ def _active_direct_claims(repo: Path) -> list[dict]:
1735
+ root = _task_state_root(repo) / "direct-claims"
1736
+ if not root.exists():
1737
+ return []
1738
+ active: list[dict] = []
1739
+ for path in sorted(root.glob("*.json")):
1740
+ payload = _read_json_object(path) or {}
1741
+ worktree = Path(_text(payload.get("worktree_path"))).resolve()
1742
+ valid_checkout = worktree.exists() and _text(payload.get("worktree_path"))
1743
+ if valid_checkout:
1744
+ try:
1745
+ valid_checkout = bool(
1746
+ _text(payload.get("base_sha")) == _resolve_commit(worktree, "HEAD")
1747
+ and _text(payload.get("branch")) == _current_branch(worktree)
1748
+ )
1749
+ except APError:
1750
+ valid_checkout = False
1751
+ if (
1752
+ int(payload.get("schema") or 0) != 1
1753
+ or _text(payload.get("state")) != "active"
1754
+ or not valid_checkout
1755
+ ):
1756
+ path.unlink(missing_ok=True)
1757
+ continue
1758
+ active.append(payload)
1759
+ return active
1760
+
1761
+
1762
+ def _create_direct_claim(repo: Path, cfg: dict, owned_paths: list[str], owner: str) -> dict:
1763
+ normalized = sorted({_normalize_owned_path(item) for item in owned_paths if _text(item)})
1764
+ if not normalized:
1765
+ raise APError("A direct claim requires at least one planned path.")
1766
+ if not _text(owner):
1767
+ raise APError("A direct claim requires --claim-owner or CODEX_THREAD_ID.")
1768
+ if _task_isolation(cfg) != "adaptive":
1769
+ raise APError("Direct claims are available only with concurrency.isolation=adaptive.")
1770
+ if _working_tree_paths(repo):
1771
+ raise APError("A direct claim must be created while the checkout is clean, before the first write.")
1772
+ if _has_registered_active_task(repo):
1773
+ raise APError("A registered active task already owns repository writes.")
1774
+ branch = _current_branch(repo)
1775
+ if not branch:
1776
+ raise APError("A direct claim requires a named current branch.")
1777
+ timeout_s = float(_concurrency_cfg(cfg).get("lock_timeout_sec") or 30)
1778
+ with (
1779
+ _repo_lock(repo, "integration", timeout_s=timeout_s),
1780
+ _repo_lock(repo, "task-registry", timeout_s=timeout_s),
1781
+ _repo_lock(repo, "direct-claim", timeout_s=timeout_s),
1782
+ ):
1783
+ if _working_tree_paths(repo):
1784
+ raise APError("Checkout changed while acquiring the direct claim; isolate instead.")
1785
+ if _has_registered_active_task(repo):
1786
+ raise APError("A registered active task acquired repository writes.")
1787
+ existing = _active_direct_claims(repo)
1788
+ other = [item for item in existing if _text(item.get("owner")) != _text(owner)]
1789
+ if other:
1790
+ raise APError(
1791
+ "Another direct writer already owns this checkout: "
1792
+ + ", ".join(_text(item.get("owner")) for item in other)
1793
+ )
1794
+ for item in existing:
1795
+ _direct_claim_path(repo, _text(item.get("claim_id"))).unlink(missing_ok=True)
1796
+ claim_id = uuid.uuid4().hex
1797
+ payload = {
1798
+ "schema": 1,
1799
+ "claim_id": claim_id,
1800
+ "state": "active",
1801
+ "owner": _text(owner),
1802
+ "base_sha": _resolve_commit(repo, "HEAD"),
1803
+ "branch": branch,
1804
+ "worktree_path": str(repo.resolve()),
1805
+ "owned_paths": normalized,
1806
+ "created_at": _now_iso(),
1807
+ }
1808
+ _write_json_object(_direct_claim_path(repo, claim_id), payload)
1809
+ return payload
1810
+
1811
+
1812
+ def _require_direct_claim(repo: Path, claim_id: str, planned_paths: list[str]) -> dict:
1813
+ if not _text(claim_id):
1814
+ raise APError(
1815
+ "--continue-direct requires --direct-claim from a clean pre-write classify --claim-direct."
1816
+ )
1817
+ payload = _read_json_object(_direct_claim_path(repo, claim_id)) or {}
1818
+ normalized = sorted({_normalize_owned_path(item) for item in planned_paths if _text(item)})
1819
+ if int(payload.get("schema") or 0) != 1 or _text(payload.get("state")) != "active":
1820
+ raise APError("Direct claim is missing, consumed, or invalid.")
1821
+ if normalized != sorted(payload.get("owned_paths") or []):
1822
+ raise APError("Continued direct paths must exactly match the clean pre-write direct claim.")
1823
+ if _text(payload.get("base_sha")) != _resolve_commit(repo, "HEAD"):
1824
+ raise APError("Direct claim base HEAD changed; use an isolated task instead.")
1825
+ if _text(payload.get("branch")) != _current_branch(repo):
1826
+ raise APError("Direct claim branch changed; use an isolated task instead.")
1827
+ if Path(_text(payload.get("worktree_path"))).resolve() != repo.resolve():
1828
+ raise APError("Direct claim belongs to another checkout.")
1829
+ actor = _text(os.environ.get("CODEX_THREAD_ID"))
1830
+ if actor and actor != _text(payload.get("owner")):
1831
+ raise APError("Direct claim belongs to another writer.")
1832
+ dirty = _working_tree_paths(repo)
1833
+ outside = [path for path in dirty if not _path_is_owned(path, normalized)]
1834
+ if outside:
1835
+ raise APError("Changes outside the clean direct claim:\n- " + "\n- ".join(outside))
1836
+ return payload
1837
+
1838
+
1839
+ def _consume_direct_claim(repo: Path, claim_id: str) -> None:
1840
+ if _text(claim_id):
1841
+ _direct_claim_path(repo, claim_id).unlink(missing_ok=True)
1842
+
1843
+
1735
1844
  def _has_registered_active_task(repo: Path) -> bool:
1736
1845
  registry = _task_state_root(repo) / "tasks"
1737
1846
  if not registry.exists():
@@ -4425,7 +4534,12 @@ def _classify_paths(paths: list[str]) -> dict:
4425
4534
  categories.add("db")
4426
4535
  if any(token in lower for token in ["api", "controller", "handler", "route", "server"]):
4427
4536
  categories.add("api")
4428
- if words & {"auth", "authentication", "authorization", "permission", "permissions", "role", "roles", "tenant", "security"}:
4537
+ if words & {
4538
+ "auth", "authentication", "authorization", "permission", "permissions",
4539
+ "role", "roles", "tenant", "security", "login", "session", "sessions",
4540
+ "token", "tokens", "jwt", "oauth", "oidc", "sso", "password", "passwords",
4541
+ "credential", "credentials",
4542
+ }:
4429
4543
  categories.add("auth")
4430
4544
  if words & {"payment", "payments", "billing", "invoice", "invoices", "checkout"}:
4431
4545
  categories.add("payment")
@@ -4489,6 +4603,43 @@ def _classify_intent(intent: str) -> list[str]:
4489
4603
  )
4490
4604
 
4491
4605
 
4606
+ def _high_confidence_intent_categories(intent: str) -> set[str]:
4607
+ value = _text(intent).lower()
4608
+ signals = {
4609
+ "db": [
4610
+ "migration", "schema", "ddl", "sql", "table structure", "database migration",
4611
+ "数据迁移", "数据库迁移", "表结构", "数据库结构",
4612
+ ],
4613
+ "auth": [
4614
+ "authorization", "permission", "security boundary", "token validation",
4615
+ "session validation", "access control", "鉴权", "权限", "安全边界",
4616
+ "令牌校验", "会话校验", "访问控制",
4617
+ ],
4618
+ "payment": [
4619
+ "settlement", "refund", "charge", "transaction", "billing", "ledger",
4620
+ "payment idempotency", "结算", "退款", "扣款", "交易", "账单", "资金", "支付幂等",
4621
+ ],
4622
+ "file_transfer": [
4623
+ "upload validation", "download authorization", "file validation", "path traversal",
4624
+ "上传校验", "下载权限", "文件校验", "路径穿越",
4625
+ ],
4626
+ "gateway": [
4627
+ "gateway config", "ingress config", "nginx config", "reverse proxy config",
4628
+ "网关配置", "入口配置", "反向代理配置",
4629
+ ],
4630
+ "prod_config": ["production config", "prod config", "生产配置"],
4631
+ "release_or_tooling": [
4632
+ "release pipeline", "deployment pipeline", "jenkins pipeline", "publish workflow",
4633
+ "发布流程", "部署流水线", "构建流水线", "发布工作流",
4634
+ ],
4635
+ }
4636
+ return {
4637
+ category
4638
+ for category, keywords in signals.items()
4639
+ if any(keyword in value for keyword in keywords)
4640
+ }
4641
+
4642
+
4492
4643
  def _resolve_task_kind(
4493
4644
  requested: str,
4494
4645
  paths: list[str],
@@ -4647,6 +4798,154 @@ def _agent_contract_shape() -> tuple[dict, list[str]]:
4647
4798
  )
4648
4799
 
4649
4800
 
4801
+ _ORCHESTRATION_SCHEMA_CACHE: Optional[dict] = None
4802
+
4803
+
4804
+ def _orchestration_schema() -> dict:
4805
+ global _ORCHESTRATION_SCHEMA_CACHE
4806
+ if _ORCHESTRATION_SCHEMA_CACHE is None:
4807
+ path = Path(__file__).resolve().parents[1] / _AGENT_CONTRACT_SCHEMA
4808
+ try:
4809
+ payload = json.loads(path.read_text(encoding="utf-8"))
4810
+ except (OSError, json.JSONDecodeError) as exc:
4811
+ raise APError(f"Cannot load orchestration contract schema: {path}: {exc}") from exc
4812
+ if not isinstance(payload, dict):
4813
+ raise APError(f"Orchestration contract schema must be an object: {path}")
4814
+ _ORCHESTRATION_SCHEMA_CACHE = payload
4815
+ return _ORCHESTRATION_SCHEMA_CACHE
4816
+
4817
+
4818
+ def _contract_ref(root: dict, ref: str) -> dict:
4819
+ if not ref.startswith("#/"):
4820
+ raise APError(f"Unsupported orchestration contract reference: {ref}")
4821
+ current: object = root
4822
+ for token in ref[2:].split("/"):
4823
+ token = token.replace("~1", "/").replace("~0", "~")
4824
+ if not isinstance(current, dict) or token not in current:
4825
+ raise APError(f"Broken orchestration contract reference: {ref}")
4826
+ current = current[token]
4827
+ if not isinstance(current, dict):
4828
+ raise APError(f"Orchestration contract reference is not an object: {ref}")
4829
+ return current
4830
+
4831
+
4832
+ def _contract_type_matches(value: object, expected: str) -> bool:
4833
+ return {
4834
+ "object": isinstance(value, dict),
4835
+ "array": isinstance(value, list),
4836
+ "string": isinstance(value, str),
4837
+ "boolean": isinstance(value, bool),
4838
+ "null": value is None,
4839
+ "integer": isinstance(value, int) and not isinstance(value, bool),
4840
+ "number": isinstance(value, (int, float)) and not isinstance(value, bool),
4841
+ }.get(expected, False)
4842
+
4843
+
4844
+ def _contract_equal(left: object, right: object) -> bool:
4845
+ if isinstance(left, bool) or isinstance(right, bool):
4846
+ return type(left) is type(right) and left == right
4847
+ return left == right
4848
+
4849
+
4850
+ def _validate_contract_fragment(fragment: dict, value: object, root: dict, path: str) -> None:
4851
+ if "$ref" in fragment:
4852
+ _validate_contract_fragment(_contract_ref(root, _text(fragment["$ref"])), value, root, path)
4853
+
4854
+ expected_types = fragment.get("type")
4855
+ if expected_types is not None:
4856
+ choices = expected_types if isinstance(expected_types, list) else [expected_types]
4857
+ if not all(isinstance(item, str) for item in choices) or not any(
4858
+ _contract_type_matches(value, item) for item in choices
4859
+ ):
4860
+ raise APError(f"Contract validation failed at {path}: expected type {choices}.")
4861
+
4862
+ if "const" in fragment and not _contract_equal(value, fragment["const"]):
4863
+ raise APError(f"Contract validation failed at {path}: expected constant {fragment['const']!r}.")
4864
+ if "enum" in fragment and not any(_contract_equal(value, item) for item in fragment["enum"]):
4865
+ raise APError(f"Contract validation failed at {path}: value is outside the allowed enum.")
4866
+
4867
+ if isinstance(value, str):
4868
+ if len(value) < int(fragment.get("minLength") or 0):
4869
+ raise APError(f"Contract validation failed at {path}: string is too short.")
4870
+ pattern = fragment.get("pattern")
4871
+ if pattern and not re.search(str(pattern), value):
4872
+ raise APError(f"Contract validation failed at {path}: string does not match {pattern!r}.")
4873
+
4874
+ if isinstance(value, list):
4875
+ if "maxItems" in fragment and len(value) > int(fragment["maxItems"]):
4876
+ raise APError(f"Contract validation failed at {path}: too many array items.")
4877
+ item_schema = fragment.get("items")
4878
+ if isinstance(item_schema, dict):
4879
+ for index, item in enumerate(value):
4880
+ _validate_contract_fragment(item_schema, item, root, f"{path}[{index}]")
4881
+
4882
+ if isinstance(value, dict):
4883
+ required = fragment.get("required") or []
4884
+ missing = [item for item in required if item not in value]
4885
+ if missing:
4886
+ raise APError(
4887
+ f"Contract validation failed at {path}: missing " + ", ".join(sorted(missing)) + "."
4888
+ )
4889
+ properties = fragment.get("properties") or {}
4890
+ if fragment.get("additionalProperties") is False:
4891
+ unexpected = sorted(set(value) - set(properties))
4892
+ if unexpected:
4893
+ raise APError(
4894
+ f"Contract validation failed at {path}: unexpected " + ", ".join(unexpected) + "."
4895
+ )
4896
+ for key, child in properties.items():
4897
+ if key in value and isinstance(child, dict):
4898
+ _validate_contract_fragment(child, value[key], root, f"{path}.{key}")
4899
+
4900
+ condition = fragment.get("if")
4901
+ if isinstance(condition, dict):
4902
+ try:
4903
+ _validate_contract_fragment(condition, value, root, path)
4904
+ except APError:
4905
+ pass
4906
+ else:
4907
+ then = fragment.get("then")
4908
+ if isinstance(then, dict):
4909
+ _validate_contract_fragment(then, value, root, path)
4910
+
4911
+ for child in fragment.get("allOf") or []:
4912
+ if isinstance(child, dict):
4913
+ _validate_contract_fragment(child, value, root, path)
4914
+
4915
+
4916
+ def _validate_orchestration_contract(kind: str, payload: dict) -> dict:
4917
+ definitions = {
4918
+ "assignment": "agentAssignment",
4919
+ "result": "agentResult",
4920
+ "agentPlan": "agentPlan",
4921
+ "classify": "classifyResult",
4922
+ }
4923
+ definition = definitions.get(kind)
4924
+ if not definition:
4925
+ raise APError(f"Unknown orchestration contract kind: {kind}")
4926
+ root = _orchestration_schema()
4927
+ _validate_contract_fragment(root["$defs"][definition], payload, root, "$")
4928
+
4929
+ role = _text(payload.get("role"))
4930
+ if kind == "assignment" and role == "reviewer":
4931
+ if _text(payload.get("node_id")) == _text(payload.get("owning_fixer")):
4932
+ raise APError("Reviewer assignment node_id must differ from owning_fixer.")
4933
+ if kind == "result":
4934
+ if role == "fixer":
4935
+ owned = [_normalize_owned_path(item) for item in payload.get("owned_paths") or []]
4936
+ outside = [
4937
+ path
4938
+ for path in payload.get("changed_paths") or []
4939
+ if not _path_is_owned(path, owned)
4940
+ ]
4941
+ if outside:
4942
+ raise APError("Fixer result changed_paths exceed owned_paths: " + ", ".join(outside))
4943
+ if role == "reviewer" and _text(payload.get("verdict")) in {"approved", "changes-requested"}:
4944
+ if not re.fullmatch(r"[0-9a-f]{64}", _text(payload.get("diff_fingerprint"))):
4945
+ raise APError("Reviewer result must bind its verdict to a non-empty diff fingerprint.")
4946
+ return payload
4947
+
4948
+
4650
4949
  def _validate_agent_plan(plan: dict) -> dict:
4651
4950
  required = {
4652
4951
  "contract_version",
@@ -4660,18 +4959,9 @@ def _validate_agent_plan(plan: dict) -> dict:
4660
4959
  "optional_roles",
4661
4960
  }
4662
4961
  missing = sorted(required - set(plan))
4663
- if missing or plan.get("contract_version") != _AGENT_CONTRACT_VERSION:
4664
- raise APError("Invalid agent plan contract: " + (", ".join(missing) or "version"))
4665
- if plan.get("contract_schema") != _AGENT_CONTRACT_SCHEMA:
4666
- raise APError("Invalid agent plan schema path.")
4667
- if plan.get("strategy") not in {"main-only", "orchestrated-subagents"}:
4668
- raise APError("Invalid agent plan strategy.")
4669
- if not all(
4670
- isinstance(stage, dict)
4671
- and {"id", "mode", "roles", "depends_on"} <= set(stage)
4672
- for stage in plan.get("stages") or []
4673
- ):
4674
- raise APError("Invalid agent plan stage contract.")
4962
+ if missing:
4963
+ raise APError("Invalid agent plan contract: " + ", ".join(missing))
4964
+ _validate_orchestration_contract("agentPlan", plan)
4675
4965
  return plan
4676
4966
 
4677
4967
 
@@ -4794,8 +5084,6 @@ def _mechanism_plan(
4794
5084
  required.append("task_lifecycle")
4795
5085
  if parallel_writers > 1:
4796
5086
  required.append("parallel_fixers")
4797
- else:
4798
- optional.append("parallel_fixers")
4799
5087
  if review_required:
4800
5088
  required.append("independent_review")
4801
5089
  else:
@@ -4815,7 +5103,8 @@ def _mechanism_plan(
4815
5103
  "lifecycle_required": "task_lifecycle" in ordered,
4816
5104
  "rule": (
4817
5105
  "run required mechanisms; select optional mechanisms only when expected value exceeds "
4818
- "coordination cost; do not run forbidden mechanisms unless the user explicitly overrides"
5106
+ "coordination cost; reclassify before changing writer count; do not run forbidden "
5107
+ "mechanisms unless the user explicitly overrides"
4819
5108
  ),
4820
5109
  }
4821
5110
 
@@ -4834,6 +5123,7 @@ def _resolve_execution_plan(
4834
5123
  parallel_writers: int = 1,
4835
5124
  requested_task_kind: str = "",
4836
5125
  continue_direct: bool = False,
5126
+ direct_claim_id: str = "",
4837
5127
  ) -> dict:
4838
5128
  impact = _impact_summary(
4839
5129
  cfg,
@@ -4851,6 +5141,7 @@ def _resolve_execution_plan(
4851
5141
  path_classification = _classify_paths(classification_inputs)
4852
5142
  path_categories = set(path_classification["categories"])
4853
5143
  intent_categories = _classify_intent(intent)
5144
+ high_confidence_intent_categories = _high_confidence_intent_categories(intent)
4854
5145
  merged_categories = path_categories | set(intent_categories)
4855
5146
  classification = _classification_for_categories(merged_categories, len(classification_inputs))
4856
5147
  categories = set(classification["categories"])
@@ -4901,8 +5192,10 @@ def _resolve_execution_plan(
4901
5192
  "release_or_tooling",
4902
5193
  }
4903
5194
  default_high_path_categories: set[str] = set()
5195
+ path_category_sets: list[set[str]] = []
4904
5196
  for path in classification_inputs:
4905
5197
  per_path = set(_classify_paths([path])["categories"])
5198
+ path_category_sets.append(per_path)
4906
5199
  default_high_path_categories.update(
4907
5200
  per_path & {"db", "gateway", "prod_config", "release_or_tooling"}
4908
5201
  )
@@ -4911,6 +5204,13 @@ def _resolve_execution_plan(
4911
5204
  per_path & {"auth", "payment", "file_transfer"}
4912
5205
  )
4913
5206
  intent_risk_candidates = sorted(set(intent_categories) & high_categories)
5207
+ all_planned_code_paths_are_ui = bool(path_category_sets) and all(
5208
+ "ui" in per_path or per_path <= {"docs", "test"}
5209
+ for per_path in path_category_sets
5210
+ )
5211
+ default_high_intent_categories = set(high_confidence_intent_categories)
5212
+ if all_planned_code_paths_are_ui:
5213
+ default_high_intent_categories.difference_update({"auth", "payment", "file_transfer"})
4914
5214
  high_signals: list[str] = []
4915
5215
  if task_kind == "change" and default_high_path_categories and not docs_or_tests_only:
4916
5216
  high_signals.append(
@@ -4918,6 +5218,10 @@ def _resolve_execution_plan(
4918
5218
  )
4919
5219
  if task_kind == "change" and "high-risk" in rule_profiles:
4920
5220
  high_signals.append("matched gate rule with profile=high-risk")
5221
+ if task_kind == "change" and default_high_intent_categories and not docs_or_tests_only:
5222
+ high_signals.append(
5223
+ "high-confidence risk intent: " + ", ".join(sorted(default_high_intent_categories))
5224
+ )
4921
5225
  if high_signals:
4922
5226
  detected_profile = "high-risk"
4923
5227
  profile_reasons.extend(high_signals)
@@ -4981,14 +5285,28 @@ def _resolve_execution_plan(
4981
5285
  dirty_outside_plan = [
4982
5286
  path for path in dirty_paths if not _path_is_owned(path, normalized_planned_paths)
4983
5287
  ] if normalized_planned_paths else list(dirty_paths)
4984
- active_writer = _has_registered_active_task(repo)
5288
+ registered_active_writer = _has_registered_active_task(repo)
4985
5289
  configured_isolation = _task_isolation(cfg)
4986
5290
  if continue_direct and task_kind != "change":
4987
5291
  raise APError("--continue-direct is valid only for task-kind=change")
4988
5292
  if continue_direct and not normalized_planned_paths:
4989
5293
  raise APError("--continue-direct requires every current task path via --planned-path")
5294
+ direct_claim = (
5295
+ _require_direct_claim(repo, direct_claim_id, normalized_planned_paths)
5296
+ if continue_direct
5297
+ else {}
5298
+ )
5299
+ runtime_actor = _text(os.environ.get("CODEX_THREAD_ID"))
5300
+ other_direct_claims = [
5301
+ item
5302
+ for item in _active_direct_claims(repo)
5303
+ if _text(item.get("claim_id")) != _text(direct_claim_id)
5304
+ and (not runtime_actor or _text(item.get("owner")) != runtime_actor)
5305
+ ]
5306
+ active_writer = bool(registered_active_writer or other_direct_claims)
4990
5307
  continued_direct = bool(
4991
5308
  continue_direct
5309
+ and direct_claim
4992
5310
  and configured_isolation == "adaptive"
4993
5311
  and writer_count == 1
4994
5312
  and not active_writer
@@ -5046,6 +5364,7 @@ def _resolve_execution_plan(
5046
5364
  "task_kind": task_kind,
5047
5365
  "intent_categories": intent_categories,
5048
5366
  "intent_risk_candidates": intent_risk_candidates,
5367
+ "high_confidence_intent_categories": sorted(high_confidence_intent_categories),
5049
5368
  "reasons": execution_reasons,
5050
5369
  "configured_profile": configured_profile,
5051
5370
  "requested_profile": requested_profile_value or None,
@@ -5100,6 +5419,11 @@ def cmd_classify(args: argparse.Namespace) -> None:
5100
5419
  intent_parts.append(path.read_text(encoding="utf-8"))
5101
5420
  except OSError as exc:
5102
5421
  raise APError(f"Cannot read --intent-file: {path}: {exc}") from exc
5422
+ claim_direct = bool(getattr(args, "claim_direct", False))
5423
+ continue_direct = bool(getattr(args, "continue_direct", False))
5424
+ direct_claim_id = _text(getattr(args, "direct_claim", ""))
5425
+ if claim_direct and continue_direct:
5426
+ raise APError("--claim-direct and --continue-direct are mutually exclusive.")
5103
5427
  plan = _resolve_execution_plan(
5104
5428
  cfg,
5105
5429
  repo,
@@ -5111,8 +5435,19 @@ def cmd_classify(args: argparse.Namespace) -> None:
5111
5435
  intent="\n".join(part for part in intent_parts if part),
5112
5436
  parallel_writers=int(getattr(args, "writers", 1) or 1),
5113
5437
  requested_task_kind=_text(getattr(args, "task_kind", "")),
5114
- continue_direct=bool(getattr(args, "continue_direct", False)),
5438
+ continue_direct=continue_direct,
5439
+ direct_claim_id=_text(getattr(args, "direct_claim", "")),
5115
5440
  )
5441
+ direct_claim: dict = {}
5442
+ if claim_direct:
5443
+ if plan["task_kind"] != "change" or plan["execution_mode"] != "direct":
5444
+ raise APError("--claim-direct requires a clean adaptive single-writer change plan.")
5445
+ direct_claim = _create_direct_claim(
5446
+ repo,
5447
+ cfg,
5448
+ list(plan.get("planned_files") or []),
5449
+ _actor_id(args, "claim_owner"),
5450
+ )
5116
5451
  risk = {"micro": "P3", "standard": "P2", "high-risk": "P1"}[plan["profile"]]
5117
5452
  commands: list[str] = []
5118
5453
  if plan["needs_dd"]:
@@ -5121,6 +5456,15 @@ def cmd_classify(args: argparse.Namespace) -> None:
5121
5456
  **plan,
5122
5457
  "risk": risk,
5123
5458
  "recommended_commands": commands,
5459
+ "direct_claim": (
5460
+ {
5461
+ "id": _text(direct_claim.get("claim_id")),
5462
+ "base_sha": _text(direct_claim.get("base_sha")),
5463
+ "owned_paths": list(direct_claim.get("owned_paths") or []),
5464
+ }
5465
+ if direct_claim
5466
+ else None
5467
+ ),
5124
5468
  }
5125
5469
  if args.json:
5126
5470
  print(json.dumps(result, ensure_ascii=False, indent=2))
@@ -5152,6 +5496,8 @@ def cmd_classify(args: argparse.Namespace) -> None:
5152
5496
  "[classify] forbidden="
5153
5497
  + (", ".join(result["mechanism_plan"]["forbidden"]) or "(none)")
5154
5498
  )
5499
+ if direct_claim:
5500
+ print(f"[classify] direct_claim={direct_claim['claim_id']}")
5155
5501
  for stage in result["agent_plan"]["stages"]:
5156
5502
  print(
5157
5503
  "[classify] agent_stage="
@@ -5165,6 +5511,39 @@ def cmd_classify(args: argparse.Namespace) -> None:
5165
5511
  _record_evidence(repo, cfg, "classify", "pass", result)
5166
5512
 
5167
5513
 
5514
+ def cmd_agent_contract_check(args: argparse.Namespace) -> None:
5515
+ repo = Path(args.repo).resolve()
5516
+ raw = _text(getattr(args, "payload", ""))
5517
+ source = _text(getattr(args, "file", ""))
5518
+ if source:
5519
+ if source == "-":
5520
+ raw = sys.stdin.read(1048577)
5521
+ else:
5522
+ path = Path(source)
5523
+ if not path.is_absolute():
5524
+ path = repo / path
5525
+ try:
5526
+ if path.stat().st_size > 1048576:
5527
+ raise APError("Agent contract payload is limited to 1 MiB.")
5528
+ raw = path.read_text(encoding="utf-8")
5529
+ except OSError as exc:
5530
+ raise APError(f"Cannot read agent contract payload: {path}: {exc}") from exc
5531
+ if len(raw.encode("utf-8")) > 1048576:
5532
+ raise APError("Agent contract payload is limited to 1 MiB.")
5533
+ try:
5534
+ payload = json.loads(raw)
5535
+ except json.JSONDecodeError as exc:
5536
+ raise APError(f"Agent contract payload is not valid JSON: {exc}") from exc
5537
+ if not isinstance(payload, dict):
5538
+ raise APError("Agent contract payload must be a JSON object.")
5539
+ _validate_orchestration_contract(args.kind, payload)
5540
+ result = {"valid": True, "kind": args.kind}
5541
+ if args.json:
5542
+ print(json.dumps(result, ensure_ascii=False, indent=2))
5543
+ else:
5544
+ print(f"[agent-contract-check] OK kind={args.kind}")
5545
+
5546
+
5168
5547
  def cmd_run(args: argparse.Namespace) -> None:
5169
5548
  """
5170
5549
  Run any configured gate command by name.
@@ -6846,6 +7225,7 @@ def cmd_task_start(args: argparse.Namespace) -> None:
6846
7225
  "writer as its own task ID; use --writers only with classify for planning."
6847
7226
  )
6848
7227
  continue_direct = bool(getattr(args, "continue_direct", False))
7228
+ direct_claim_id = _text(getattr(args, "direct_claim", ""))
6849
7229
  explicit_lifecycle = bool(
6850
7230
  getattr(args, "isolated", False)
6851
7231
  or getattr(args, "review_required", False)
@@ -6859,6 +7239,7 @@ def cmd_task_start(args: argparse.Namespace) -> None:
6859
7239
  parallel_writers=writer_count,
6860
7240
  requested_task_kind="change",
6861
7241
  continue_direct=continue_direct,
7242
+ direct_claim_id=direct_claim_id,
6862
7243
  )
6863
7244
  if continue_direct and preflight_plan["execution_mode"] != "direct":
6864
7245
  detail = ", ".join(preflight_plan["dirty_outside_plan"]) or "policy or active-writer conflict"
@@ -6889,6 +7270,16 @@ def cmd_task_start(args: argparse.Namespace) -> None:
6889
7270
  _repo_lock(repo, "integration", timeout_s=timeout_s),
6890
7271
  _repo_lock(repo, "task-registry", timeout_s=timeout_s),
6891
7272
  ):
7273
+ for claim in _active_direct_claims(repo):
7274
+ if _text(claim.get("claim_id")) == direct_claim_id:
7275
+ continue
7276
+ claim_paths = list(claim.get("owned_paths") or [])
7277
+ if _owned_paths_overlap(owned_paths, claim_paths):
7278
+ raise APError(
7279
+ "Owned paths overlap an active direct claim held by "
7280
+ f"{_text(claim.get('owner')) or '(unknown)'}: "
7281
+ + ", ".join(claim_paths)
7282
+ )
6892
7283
  if _read_json_object(_task_registry_path(repo, task_id)):
6893
7284
  raise APError(f"Task is already registered: {task_id}")
6894
7285
 
@@ -6938,6 +7329,7 @@ def cmd_task_start(args: argparse.Namespace) -> None:
6938
7329
  parallel_writers=writer_count,
6939
7330
  requested_task_kind="change",
6940
7331
  continue_direct=continue_direct,
7332
+ direct_claim_id=direct_claim_id,
6941
7333
  )
6942
7334
  if not plan["mechanism_plan"]["lifecycle_required"] and not explicit_lifecycle:
6943
7335
  raise APError(
@@ -7019,6 +7411,7 @@ def cmd_task_start(args: argparse.Namespace) -> None:
7019
7411
  "common_submodule_config": {},
7020
7412
  }
7021
7413
  _save_task_manifest(repo, manifest)
7414
+ _consume_direct_claim(repo, direct_claim_id)
7022
7415
  print(f"[task-start] task={task_id}")
7023
7416
  print("[task-start] execution_mode=direct")
7024
7417
  print(f"[task-start] branch={current_branch}")
@@ -7240,6 +7633,9 @@ def cmd_task_review(args: argparse.Namespace) -> None:
7240
7633
  raise APError("Independent review requires an explicit --reviewer identity.")
7241
7634
  if reviewer == _text(manifest.get("owner")):
7242
7635
  raise APError("Independent reviewer identity must differ from the task lifecycle owner.")
7636
+ writer = _text((manifest.get("writer_lease") or {}).get("holder"))
7637
+ if reviewer == writer:
7638
+ raise APError("Independent reviewer identity must differ from the current writer lease holder.")
7243
7639
  manifest["review"] = {
7244
7640
  "verdict": args.verdict,
7245
7641
  "diff_base": _text(manifest.get("base_sha")),
@@ -8195,11 +8591,22 @@ def main(argv: Optional[List[str]] = None) -> int:
8195
8591
  s.add_argument("--intent")
8196
8592
  s.add_argument("--intent-file")
8197
8593
  s.add_argument("--task-kind", choices=sorted(_REQUESTED_TASK_KINDS), default="auto")
8594
+ s.add_argument("--claim-direct", action="store_true")
8595
+ s.add_argument("--claim-owner")
8198
8596
  s.add_argument("--continue-direct", action="store_true")
8597
+ s.add_argument("--direct-claim")
8199
8598
  s.add_argument("--writers", type=int, default=1)
8200
8599
  s.add_argument("--json", action="store_true")
8201
8600
  s.set_defaults(func=cmd_classify)
8202
8601
 
8602
+ s = sp.add_parser("agent-contract-check")
8603
+ s.add_argument("--kind", choices=["assignment", "result", "agentPlan", "classify"], required=True)
8604
+ source = s.add_mutually_exclusive_group(required=True)
8605
+ source.add_argument("--file")
8606
+ source.add_argument("--payload")
8607
+ s.add_argument("--json", action="store_true")
8608
+ s.set_defaults(func=cmd_agent_contract_check)
8609
+
8203
8610
  s = sp.add_parser("validation-map-check")
8204
8611
  s.add_argument("--base")
8205
8612
  s.add_argument("--path", action="append")
@@ -8305,6 +8712,7 @@ def main(argv: Optional[List[str]] = None) -> int:
8305
8712
  s.add_argument("--isolated", action="store_true")
8306
8713
  s.add_argument("--review-required", action="store_true")
8307
8714
  s.add_argument("--continue-direct", action="store_true")
8715
+ s.add_argument("--direct-claim")
8308
8716
  s.add_argument(
8309
8717
  "--force-lifecycle",
8310
8718
  action="store_true",