@elvis1513/auto-coding-skill 4.1.3 → 4.1.4

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.
package/README.md CHANGED
@@ -9,8 +9,9 @@ The Skill is a selectable guardrail, not a command sequence that must run for
9
9
  every task. The model skips machinery whose expected benefit does not exceed its
10
10
  cost; read-only work and obvious small clean-checkout changes normally stay direct.
11
11
 
12
- Version 4.1.3 closes classification bypasses and keeps current-task changes direct
13
- without weakening dirty-workspace isolation. Version 4.1.2 made mechanisms required,
12
+ Version 4.1.4 makes direct continuation provably pre-write, closes self-review and
13
+ risk-classification gaps, validates Agent contracts, and makes tag publication
14
+ idempotent. Version 4.1.3 closed classification bypasses. Version 4.1.2 made mechanisms required,
14
15
  model-selectable when beneficial, or forbidden for the current task. Version
15
16
  4.1.1 consolidated the 4.x delivery-first workflow into one canonical
16
17
  repository contract. Version 4.0 replaced the 3.x governance-first defaults with progressive
@@ -209,6 +210,19 @@ project-specific facts outside the managed ENGINEERING block. Root `AGENTS.md` i
209
210
  replaced as a whole; its previous content is archived under
210
211
  `docs/archive/workflow/` as historical, non-authoritative context.
211
212
 
213
+ ## What changed in 4.1.4
214
+
215
+ - Added clean pre-write direct claims so broad paths cannot adopt unknown existing
216
+ dirt after development starts.
217
+ - Prevented the current writer lease holder from approving its own diff and added
218
+ executable assignment/result contract validation.
219
+ - Escalated high-confidence database, authorization, settlement, gateway, and
220
+ production intents while keeping ordinary UI work lightweight.
221
+ - Made mechanism plans dependency-closed: parallel fixers require reclassification
222
+ with multiple writers and therefore require isolated worktrees.
223
+ - Published from matching `v*` tags with idempotent npm registry checks and a final
224
+ registry verification.
225
+
212
226
  ## What changed in 4.1.3
213
227
 
214
228
  - Made explicit task kinds fail closed: `none` is internal-only and terminal
@@ -13,33 +13,31 @@ Do not reconstruct or duplicate those rules from historical task documents.
13
13
 
14
14
  Normal delivery is:
15
15
 
16
- `analysis → decomposition → necessary design → development → one bounded final
17
- changed-scope gate → commit/push`.
16
+ `analysis → decomposition → necessary design → development → bounded gate → commit/push`.
18
17
 
19
18
  ## Select the minimum mechanism set
20
19
 
21
- Read-only questions need no workflow command. Obvious clean serial edits and
22
- terminal ledger maintenance may follow root `AGENTS.md` directly. When task kind,
23
- impact, risk, or concurrency is unclear, run:
20
+ Read-only questions need no workflow command. Clean serial edits and terminal
21
+ maintenance may follow `AGENTS.md` directly. When impact or concurrency is unclear, run:
24
22
 
25
23
  ```bash
26
24
  python3 docs/tools/autopipeline/ap.py classify --scope auto \
27
25
  --planned-path <PATH> --intent "<intent>" [--writers <N>] \
28
- [--task-kind read_only|change|terminal_maintenance]
26
+ [--task-kind read_only|change|terminal_maintenance] [--claim-direct]
29
27
  ```
30
28
 
31
29
  Run `mechanism_plan.required`. The model may select
32
30
  `optional_when_beneficial` only when expected value exceeds coordination cost.
33
31
  Do not run `forbidden` mechanisms unless the user explicitly overrides the plan.
34
- Reclassify only after material change. For already-direct work, add `--continue-direct`
35
- with every task path and reuse it on `task-start` if needed; unknown dirt isolates.
32
+ Reclassify before changing writer count. For uncertain direct work, create
33
+ `--claim-direct` while clean; continuation requires its ID and exact paths.
36
34
 
37
35
  Use the registered lifecycle only when classification requires isolation or
38
36
  fingerprinted review, or when the user explicitly requests it:
39
37
 
40
38
  ```bash
41
39
  python3 docs/tools/autopipeline/ap.py task-start T0001 \
42
- --owned-path src [--isolated] [--review-required] [--continue-direct] [--force-lifecycle]
40
+ --owned-path src [--isolated] [--review-required] [--continue-direct --direct-claim <ID>]
43
41
  # For review-required work, obtain the current fingerprint and approve it:
44
42
  python3 docs/tools/autopipeline/ap.py task-status T0001 --json
45
43
  python3 docs/tools/autopipeline/ap.py task-review T0001 \
@@ -49,9 +47,9 @@ python3 docs/tools/autopipeline/ap.py commit-push T0001 --msg "T0001: summary"
49
47
  python3 docs/tools/autopipeline/ap.py task-integrate T0001
50
48
  ```
51
49
 
52
- Each parallel writer uses a distinct task ID, registered worktree, writer lease,
53
- dependency SHAs, and non-overlapping `owned_paths`. The main agent alone runs the
54
- final gate, integrates, pushes, and cleans safely merged temporary branches.
50
+ Each parallel writer uses a task ID, worktree, lease, dependency SHAs, and distinct
51
+ `owned_paths`. Main integrates, gates, pushes, and cleans. Validate delegated JSON
52
+ with `agent-contract-check`; parallel fixers require reclassification with `--writers >1`.
55
53
 
56
54
  ## Close with the bounded routed gate
57
55
 
@@ -459,6 +459,7 @@
459
459
  "intent_provided",
460
460
  "intent_categories",
461
461
  "intent_risk_candidates",
462
+ "high_confidence_intent_categories",
462
463
  "task_kind",
463
464
  "profile",
464
465
  "categories",
@@ -492,6 +493,9 @@
492
493
  "intent_risk_candidates": {
493
494
  "$ref": "#/$defs/stringArray"
494
495
  },
496
+ "high_confidence_intent_categories": {
497
+ "$ref": "#/$defs/stringArray"
498
+ },
495
499
  "task_kind": {
496
500
  "enum": ["none", "read_only", "change", "terminal_maintenance"]
497
501
  },
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "schema_version": 1,
3
3
  "managed_versions": {
4
- "agents": "4.1.3",
5
- "engineering": "4.1.3"
4
+ "agents": "4.1.4",
5
+ "engineering": "4.1.4"
6
6
  },
7
7
  "known_official_agents_sha256": [
8
8
  "ebaaadab60327b3a4852948443d7191a4d48cb00bf4910038ab78c9149089373"
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  workflow:
3
- skill_version: "4.1.3"
3
+ skill_version: "4.1.4"
4
4
  mode: "dev"
5
5
  profile: "auto"
6
6
  completion: "push"
@@ -94,7 +94,7 @@ docs:
94
94
 
95
95
  # Engineering Configuration and Project Facts
96
96
 
97
- <!-- auto-coding-skill:managed-workflow:start version=4.1.3 -->
97
+ <!-- auto-coding-skill:managed-workflow:start version=4.1.4 -->
98
98
 
99
99
  Root `AGENTS.md` is the single shared behavioral protocol. The installed
100
100
  `SKILL.md` contains invocation guidance. This file is the single source for the
@@ -1,4 +1,4 @@
1
- <!-- auto-coding-skill:managed-agents:start version=4.1.3 -->
1
+ <!-- auto-coding-skill:managed-agents:start version=4.1.4 -->
2
2
  # Shared Engineering Protocol
3
3
 
4
4
  This file is fully managed by `auto-coding-skill`. Keep project-specific facts,
@@ -51,8 +51,8 @@ failure may continue in the same conversation/task without a second lifecycle.
51
51
 
52
52
  ## Git and parallel work
53
53
 
54
- - One writer in a clean checkout works directly without a lifecycle. On
55
- reclassification, `--continue-direct` requires every dirty path to be declared.
54
+ - One writer in a clean checkout works directly. If review may be needed, create a
55
+ claim before the first write; continuation requires that claim and exact paths.
56
56
  - Existing unrelated changes, another writer, or configured mandatory isolation
57
57
  requires a registered task branch/worktree.
58
58
  - Every delegated fixer or parallel writer owns a task ID/worktree, writer lease,
@@ -60,8 +60,7 @@ failure may continue in the same conversation/task without a second lifecycle.
60
60
  - Never let multiple writing agents share a checkout. Never restore, reset, stash,
61
61
  clean, overwrite, or commit unknown changes.
62
62
  - No diff means no commit, push, or temporary branch.
63
- - The main agent integrates in dependency order and removes only clean, safely
64
- merged temporary worktrees and branches.
63
+ - Main integrates in dependency order and removes only clean, merged temporary state.
65
64
  - Do not sync or upgrade while any registered task is active.
66
65
 
67
66
  ## Design, agents, and review
@@ -73,6 +72,8 @@ failure may continue in the same conversation/task without a second lifecycle.
73
72
  or key user-flow decisions.
74
73
  - Use read-only explorer/docs/browser agents only for independent questions.
75
74
  - Use parallel fixers only for bounded, dependency-free, non-overlapping units.
75
+ - Reclassify before parallel fixers; single-writer plans grant no implicit writes.
76
+ - Validate delegated assignment/result JSON with `agent-contract-check` before use.
76
77
  - Require fingerprinted review only for path/rule-confirmed high-risk,
77
78
  contract-crossing, parallel, or configured work; intent words are candidates only.
78
79
  - Review blocks only defects introduced or worsened in the promised scope.
@@ -51,7 +51,7 @@ _RECOMMENDED_FINAL_TOTAL_SECONDS = 180.0
51
51
  _WORKFLOW_MIGRATION_POLICY = Path("data/policies/workflow-migrations-v1.json")
52
52
  _FALLBACK_WORKFLOW_MIGRATION_POLICY = {
53
53
  "schema_version": 1,
54
- "managed_versions": {"agents": "4.1.3", "engineering": "4.1.3"},
54
+ "managed_versions": {"agents": "4.1.4", "engineering": "4.1.4"},
55
55
  "known_official_engineering_body_sha256": [
56
56
  "d1306cc626e8baf8c83c953b760fd771066de2bf125168eca3a7b7d6ff2b87a2",
57
57
  "305931c6edef770033a4f1970b00e5fb1c1728351856a173dbfa497daf563021",
@@ -178,13 +178,13 @@ def _evidence_log_path(repo: Path, cfg: dict) -> Path:
178
178
  return Path(repo, task_dir, f"{manifest['task_id']}.jsonl")
179
179
  if _bool_config(docs_cfg.get("track_evidence"), False) and _text(docs_cfg.get("evidence_log")):
180
180
  return Path(repo, _text(docs_cfg.get("evidence_log")))
181
- return Path(repo, ".local/auto-coding-skill/evidence.jsonl")
181
+ return _task_state_root(repo) / "evidence.jsonl"
182
182
 
183
183
 
184
184
  def _gate_profile_path(repo: Path, cfg: dict) -> Path:
185
185
  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)
186
+ rel = _text(gate_cfg.get("profile_log"))
187
+ return Path(repo, rel) if rel else _task_state_root(repo) / "gate-profile.jsonl"
188
188
 
189
189
 
190
190
  def _record_evidence(repo: Path, cfg: dict, event: str, status: str, payload: Optional[dict] = None) -> None:
@@ -638,8 +638,8 @@ def _migrate_fast_development_defaults(cfg: dict, repo: Path) -> list[str]:
638
638
  if _text(workflow_cfg.get("completion")).lower() != "push":
639
639
  workflow_cfg["completion"] = "push"
640
640
  changed.append("workflow.completion")
641
- if _text(workflow_cfg.get("skill_version")) != "4.1.3":
642
- workflow_cfg["skill_version"] = "4.1.3"
641
+ if _text(workflow_cfg.get("skill_version")) != "4.1.4":
642
+ workflow_cfg["skill_version"] = "4.1.4"
643
643
  changed.append("workflow.skill_version")
644
644
 
645
645
  commands_cfg = cfg.setdefault("commands", {})
@@ -952,16 +952,16 @@ def cmd_upgrade(args: argparse.Namespace) -> None:
952
952
  if current_agents:
953
953
  archive_dir = repo / "docs" / "archive" / "workflow"
954
954
  archive_header = (
955
- "# Archived AGENTS.md before auto-coding-skill 4.1.3\n\n"
955
+ "# Archived AGENTS.md before auto-coding-skill 4.1.4\n\n"
956
956
  "This file is historical and non-authoritative. The root AGENTS.md is fully managed.\n"
957
957
  "Move any still-current project facts into docs/ENGINEERING.md or docs/project/,\n"
958
958
  "without copying workflow rules back into the root AGENTS.md.\n\n---\n\n"
959
959
  )
960
960
  archive_content = archive_header + current_agents
961
- archive = archive_dir / "AGENTS.pre-4.1.3.md"
961
+ archive = archive_dir / "AGENTS.pre-4.1.4.md"
962
962
  if archive.exists() and archive.read_text(encoding="utf-8") != archive_content:
963
963
  digest = hashlib.sha256(current_agents.encode("utf-8")).hexdigest()[:12]
964
- archive = archive_dir / f"AGENTS.pre-4.1.3-{digest}.md"
964
+ archive = archive_dir / f"AGENTS.pre-4.1.4-{digest}.md"
965
965
  if not archive.exists():
966
966
  add_action("policy", archive, "archive", "historical and non-authoritative")
967
967
  if write:
@@ -1662,6 +1662,7 @@ def _text(value: object) -> str:
1662
1662
 
1663
1663
 
1664
1664
  _TASK_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
1665
+ _DIRECT_CLAIM_ID_RE = re.compile(r"^[0-9a-f]{32}$")
1665
1666
 
1666
1667
 
1667
1668
  def _concurrency_cfg(cfg: dict) -> dict:
@@ -1732,6 +1733,123 @@ def _task_registry_path(repo: Path, task_id: str) -> Path:
1732
1733
  return _task_state_root(repo) / "tasks" / f"{_validate_task_id(task_id)}.json"
1733
1734
 
1734
1735
 
1736
+ def _direct_claim_path(repo: Path, claim_id: str) -> Path:
1737
+ value = _text(claim_id)
1738
+ if not _DIRECT_CLAIM_ID_RE.fullmatch(value):
1739
+ raise APError("Direct claim ID must be a 32-character lowercase hexadecimal token.")
1740
+ return _task_state_root(repo) / "direct-claims" / f"{value}.json"
1741
+
1742
+
1743
+ def _active_direct_claims(repo: Path) -> list[dict]:
1744
+ root = _task_state_root(repo) / "direct-claims"
1745
+ if not root.exists():
1746
+ return []
1747
+ active: list[dict] = []
1748
+ for path in sorted(root.glob("*.json")):
1749
+ payload = _read_json_object(path) or {}
1750
+ worktree = Path(_text(payload.get("worktree_path"))).resolve()
1751
+ valid_checkout = worktree.exists() and _text(payload.get("worktree_path"))
1752
+ if valid_checkout:
1753
+ try:
1754
+ valid_checkout = bool(
1755
+ _text(payload.get("base_sha")) == _resolve_commit(worktree, "HEAD")
1756
+ and _text(payload.get("branch")) == _current_branch(worktree)
1757
+ )
1758
+ except APError:
1759
+ valid_checkout = False
1760
+ if (
1761
+ int(payload.get("schema") or 0) != 1
1762
+ or _text(payload.get("state")) != "active"
1763
+ or not valid_checkout
1764
+ ):
1765
+ path.unlink(missing_ok=True)
1766
+ continue
1767
+ active.append(payload)
1768
+ return active
1769
+
1770
+
1771
+ def _create_direct_claim(repo: Path, cfg: dict, owned_paths: list[str], owner: str) -> dict:
1772
+ normalized = sorted({_normalize_owned_path(item) for item in owned_paths if _text(item)})
1773
+ if not normalized:
1774
+ raise APError("A direct claim requires at least one planned path.")
1775
+ if not _text(owner):
1776
+ raise APError("A direct claim requires --claim-owner or CODEX_THREAD_ID.")
1777
+ if _task_isolation(cfg) != "adaptive":
1778
+ raise APError("Direct claims are available only with concurrency.isolation=adaptive.")
1779
+ if _working_tree_paths(repo):
1780
+ raise APError("A direct claim must be created while the checkout is clean, before the first write.")
1781
+ if _has_registered_active_task(repo):
1782
+ raise APError("A registered active task already owns repository writes.")
1783
+ branch = _current_branch(repo)
1784
+ if not branch:
1785
+ raise APError("A direct claim requires a named current branch.")
1786
+ timeout_s = float(_concurrency_cfg(cfg).get("lock_timeout_sec") or 30)
1787
+ with (
1788
+ _repo_lock(repo, "integration", timeout_s=timeout_s),
1789
+ _repo_lock(repo, "task-registry", timeout_s=timeout_s),
1790
+ _repo_lock(repo, "direct-claim", timeout_s=timeout_s),
1791
+ ):
1792
+ if _working_tree_paths(repo):
1793
+ raise APError("Checkout changed while acquiring the direct claim; isolate instead.")
1794
+ if _has_registered_active_task(repo):
1795
+ raise APError("A registered active task acquired repository writes.")
1796
+ existing = _active_direct_claims(repo)
1797
+ other = [item for item in existing if _text(item.get("owner")) != _text(owner)]
1798
+ if other:
1799
+ raise APError(
1800
+ "Another direct writer already owns this checkout: "
1801
+ + ", ".join(_text(item.get("owner")) for item in other)
1802
+ )
1803
+ for item in existing:
1804
+ _direct_claim_path(repo, _text(item.get("claim_id"))).unlink(missing_ok=True)
1805
+ claim_id = uuid.uuid4().hex
1806
+ payload = {
1807
+ "schema": 1,
1808
+ "claim_id": claim_id,
1809
+ "state": "active",
1810
+ "owner": _text(owner),
1811
+ "base_sha": _resolve_commit(repo, "HEAD"),
1812
+ "branch": branch,
1813
+ "worktree_path": str(repo.resolve()),
1814
+ "owned_paths": normalized,
1815
+ "created_at": _now_iso(),
1816
+ }
1817
+ _write_json_object(_direct_claim_path(repo, claim_id), payload)
1818
+ return payload
1819
+
1820
+
1821
+ def _require_direct_claim(repo: Path, claim_id: str, planned_paths: list[str]) -> dict:
1822
+ if not _text(claim_id):
1823
+ raise APError(
1824
+ "--continue-direct requires --direct-claim from a clean pre-write classify --claim-direct."
1825
+ )
1826
+ payload = _read_json_object(_direct_claim_path(repo, claim_id)) or {}
1827
+ normalized = sorted({_normalize_owned_path(item) for item in planned_paths if _text(item)})
1828
+ if int(payload.get("schema") or 0) != 1 or _text(payload.get("state")) != "active":
1829
+ raise APError("Direct claim is missing, consumed, or invalid.")
1830
+ if normalized != sorted(payload.get("owned_paths") or []):
1831
+ raise APError("Continued direct paths must exactly match the clean pre-write direct claim.")
1832
+ if _text(payload.get("base_sha")) != _resolve_commit(repo, "HEAD"):
1833
+ raise APError("Direct claim base HEAD changed; use an isolated task instead.")
1834
+ if _text(payload.get("branch")) != _current_branch(repo):
1835
+ raise APError("Direct claim branch changed; use an isolated task instead.")
1836
+ if Path(_text(payload.get("worktree_path"))).resolve() != repo.resolve():
1837
+ raise APError("Direct claim belongs to another checkout.")
1838
+ actor = _text(os.environ.get("CODEX_THREAD_ID"))
1839
+ if actor and actor != _text(payload.get("owner")):
1840
+ raise APError("Direct claim belongs to another writer.")
1841
+ dirty = _working_tree_paths(repo)
1842
+ outside = [path for path in dirty if not _path_is_owned(path, normalized)]
1843
+ if outside:
1844
+ raise APError("Changes outside the clean direct claim:\n- " + "\n- ".join(outside))
1845
+ return payload
1846
+
1847
+
1848
+ def _consume_direct_claim(repo: Path, claim_id: str) -> None:
1849
+ if _text(claim_id):
1850
+ _direct_claim_path(repo, claim_id).unlink(missing_ok=True)
1851
+
1852
+
1735
1853
  def _has_registered_active_task(repo: Path) -> bool:
1736
1854
  registry = _task_state_root(repo) / "tasks"
1737
1855
  if not registry.exists():
@@ -4425,7 +4543,12 @@ def _classify_paths(paths: list[str]) -> dict:
4425
4543
  categories.add("db")
4426
4544
  if any(token in lower for token in ["api", "controller", "handler", "route", "server"]):
4427
4545
  categories.add("api")
4428
- if words & {"auth", "authentication", "authorization", "permission", "permissions", "role", "roles", "tenant", "security"}:
4546
+ if words & {
4547
+ "auth", "authentication", "authorization", "permission", "permissions",
4548
+ "role", "roles", "tenant", "security", "login", "session", "sessions",
4549
+ "token", "tokens", "jwt", "oauth", "oidc", "sso", "password", "passwords",
4550
+ "credential", "credentials",
4551
+ }:
4429
4552
  categories.add("auth")
4430
4553
  if words & {"payment", "payments", "billing", "invoice", "invoices", "checkout"}:
4431
4554
  categories.add("payment")
@@ -4489,6 +4612,43 @@ def _classify_intent(intent: str) -> list[str]:
4489
4612
  )
4490
4613
 
4491
4614
 
4615
+ def _high_confidence_intent_categories(intent: str) -> set[str]:
4616
+ value = _text(intent).lower()
4617
+ signals = {
4618
+ "db": [
4619
+ "migration", "schema", "ddl", "sql", "table structure", "database migration",
4620
+ "数据迁移", "数据库迁移", "表结构", "数据库结构",
4621
+ ],
4622
+ "auth": [
4623
+ "authorization", "permission", "security boundary", "token validation",
4624
+ "session validation", "access control", "鉴权", "权限", "安全边界",
4625
+ "令牌校验", "会话校验", "访问控制",
4626
+ ],
4627
+ "payment": [
4628
+ "settlement", "refund", "charge", "transaction", "billing", "ledger",
4629
+ "payment idempotency", "结算", "退款", "扣款", "交易", "账单", "资金", "支付幂等",
4630
+ ],
4631
+ "file_transfer": [
4632
+ "upload validation", "download authorization", "file validation", "path traversal",
4633
+ "上传校验", "下载权限", "文件校验", "路径穿越",
4634
+ ],
4635
+ "gateway": [
4636
+ "gateway config", "ingress config", "nginx config", "reverse proxy config",
4637
+ "网关配置", "入口配置", "反向代理配置",
4638
+ ],
4639
+ "prod_config": ["production config", "prod config", "生产配置"],
4640
+ "release_or_tooling": [
4641
+ "release pipeline", "deployment pipeline", "jenkins pipeline", "publish workflow",
4642
+ "发布流程", "部署流水线", "构建流水线", "发布工作流",
4643
+ ],
4644
+ }
4645
+ return {
4646
+ category
4647
+ for category, keywords in signals.items()
4648
+ if any(keyword in value for keyword in keywords)
4649
+ }
4650
+
4651
+
4492
4652
  def _resolve_task_kind(
4493
4653
  requested: str,
4494
4654
  paths: list[str],
@@ -4647,6 +4807,154 @@ def _agent_contract_shape() -> tuple[dict, list[str]]:
4647
4807
  )
4648
4808
 
4649
4809
 
4810
+ _ORCHESTRATION_SCHEMA_CACHE: Optional[dict] = None
4811
+
4812
+
4813
+ def _orchestration_schema() -> dict:
4814
+ global _ORCHESTRATION_SCHEMA_CACHE
4815
+ if _ORCHESTRATION_SCHEMA_CACHE is None:
4816
+ path = Path(__file__).resolve().parents[1] / _AGENT_CONTRACT_SCHEMA
4817
+ try:
4818
+ payload = json.loads(path.read_text(encoding="utf-8"))
4819
+ except (OSError, json.JSONDecodeError) as exc:
4820
+ raise APError(f"Cannot load orchestration contract schema: {path}: {exc}") from exc
4821
+ if not isinstance(payload, dict):
4822
+ raise APError(f"Orchestration contract schema must be an object: {path}")
4823
+ _ORCHESTRATION_SCHEMA_CACHE = payload
4824
+ return _ORCHESTRATION_SCHEMA_CACHE
4825
+
4826
+
4827
+ def _contract_ref(root: dict, ref: str) -> dict:
4828
+ if not ref.startswith("#/"):
4829
+ raise APError(f"Unsupported orchestration contract reference: {ref}")
4830
+ current: object = root
4831
+ for token in ref[2:].split("/"):
4832
+ token = token.replace("~1", "/").replace("~0", "~")
4833
+ if not isinstance(current, dict) or token not in current:
4834
+ raise APError(f"Broken orchestration contract reference: {ref}")
4835
+ current = current[token]
4836
+ if not isinstance(current, dict):
4837
+ raise APError(f"Orchestration contract reference is not an object: {ref}")
4838
+ return current
4839
+
4840
+
4841
+ def _contract_type_matches(value: object, expected: str) -> bool:
4842
+ return {
4843
+ "object": isinstance(value, dict),
4844
+ "array": isinstance(value, list),
4845
+ "string": isinstance(value, str),
4846
+ "boolean": isinstance(value, bool),
4847
+ "null": value is None,
4848
+ "integer": isinstance(value, int) and not isinstance(value, bool),
4849
+ "number": isinstance(value, (int, float)) and not isinstance(value, bool),
4850
+ }.get(expected, False)
4851
+
4852
+
4853
+ def _contract_equal(left: object, right: object) -> bool:
4854
+ if isinstance(left, bool) or isinstance(right, bool):
4855
+ return type(left) is type(right) and left == right
4856
+ return left == right
4857
+
4858
+
4859
+ def _validate_contract_fragment(fragment: dict, value: object, root: dict, path: str) -> None:
4860
+ if "$ref" in fragment:
4861
+ _validate_contract_fragment(_contract_ref(root, _text(fragment["$ref"])), value, root, path)
4862
+
4863
+ expected_types = fragment.get("type")
4864
+ if expected_types is not None:
4865
+ choices = expected_types if isinstance(expected_types, list) else [expected_types]
4866
+ if not all(isinstance(item, str) for item in choices) or not any(
4867
+ _contract_type_matches(value, item) for item in choices
4868
+ ):
4869
+ raise APError(f"Contract validation failed at {path}: expected type {choices}.")
4870
+
4871
+ if "const" in fragment and not _contract_equal(value, fragment["const"]):
4872
+ raise APError(f"Contract validation failed at {path}: expected constant {fragment['const']!r}.")
4873
+ if "enum" in fragment and not any(_contract_equal(value, item) for item in fragment["enum"]):
4874
+ raise APError(f"Contract validation failed at {path}: value is outside the allowed enum.")
4875
+
4876
+ if isinstance(value, str):
4877
+ if len(value) < int(fragment.get("minLength") or 0):
4878
+ raise APError(f"Contract validation failed at {path}: string is too short.")
4879
+ pattern = fragment.get("pattern")
4880
+ if pattern and not re.search(str(pattern), value):
4881
+ raise APError(f"Contract validation failed at {path}: string does not match {pattern!r}.")
4882
+
4883
+ if isinstance(value, list):
4884
+ if "maxItems" in fragment and len(value) > int(fragment["maxItems"]):
4885
+ raise APError(f"Contract validation failed at {path}: too many array items.")
4886
+ item_schema = fragment.get("items")
4887
+ if isinstance(item_schema, dict):
4888
+ for index, item in enumerate(value):
4889
+ _validate_contract_fragment(item_schema, item, root, f"{path}[{index}]")
4890
+
4891
+ if isinstance(value, dict):
4892
+ required = fragment.get("required") or []
4893
+ missing = [item for item in required if item not in value]
4894
+ if missing:
4895
+ raise APError(
4896
+ f"Contract validation failed at {path}: missing " + ", ".join(sorted(missing)) + "."
4897
+ )
4898
+ properties = fragment.get("properties") or {}
4899
+ if fragment.get("additionalProperties") is False:
4900
+ unexpected = sorted(set(value) - set(properties))
4901
+ if unexpected:
4902
+ raise APError(
4903
+ f"Contract validation failed at {path}: unexpected " + ", ".join(unexpected) + "."
4904
+ )
4905
+ for key, child in properties.items():
4906
+ if key in value and isinstance(child, dict):
4907
+ _validate_contract_fragment(child, value[key], root, f"{path}.{key}")
4908
+
4909
+ condition = fragment.get("if")
4910
+ if isinstance(condition, dict):
4911
+ try:
4912
+ _validate_contract_fragment(condition, value, root, path)
4913
+ except APError:
4914
+ pass
4915
+ else:
4916
+ then = fragment.get("then")
4917
+ if isinstance(then, dict):
4918
+ _validate_contract_fragment(then, value, root, path)
4919
+
4920
+ for child in fragment.get("allOf") or []:
4921
+ if isinstance(child, dict):
4922
+ _validate_contract_fragment(child, value, root, path)
4923
+
4924
+
4925
+ def _validate_orchestration_contract(kind: str, payload: dict) -> dict:
4926
+ definitions = {
4927
+ "assignment": "agentAssignment",
4928
+ "result": "agentResult",
4929
+ "agentPlan": "agentPlan",
4930
+ "classify": "classifyResult",
4931
+ }
4932
+ definition = definitions.get(kind)
4933
+ if not definition:
4934
+ raise APError(f"Unknown orchestration contract kind: {kind}")
4935
+ root = _orchestration_schema()
4936
+ _validate_contract_fragment(root["$defs"][definition], payload, root, "$")
4937
+
4938
+ role = _text(payload.get("role"))
4939
+ if kind == "assignment" and role == "reviewer":
4940
+ if _text(payload.get("node_id")) == _text(payload.get("owning_fixer")):
4941
+ raise APError("Reviewer assignment node_id must differ from owning_fixer.")
4942
+ if kind == "result":
4943
+ if role == "fixer":
4944
+ owned = [_normalize_owned_path(item) for item in payload.get("owned_paths") or []]
4945
+ outside = [
4946
+ path
4947
+ for path in payload.get("changed_paths") or []
4948
+ if not _path_is_owned(path, owned)
4949
+ ]
4950
+ if outside:
4951
+ raise APError("Fixer result changed_paths exceed owned_paths: " + ", ".join(outside))
4952
+ if role == "reviewer" and _text(payload.get("verdict")) in {"approved", "changes-requested"}:
4953
+ if not re.fullmatch(r"[0-9a-f]{64}", _text(payload.get("diff_fingerprint"))):
4954
+ raise APError("Reviewer result must bind its verdict to a non-empty diff fingerprint.")
4955
+ return payload
4956
+
4957
+
4650
4958
  def _validate_agent_plan(plan: dict) -> dict:
4651
4959
  required = {
4652
4960
  "contract_version",
@@ -4660,18 +4968,9 @@ def _validate_agent_plan(plan: dict) -> dict:
4660
4968
  "optional_roles",
4661
4969
  }
4662
4970
  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.")
4971
+ if missing:
4972
+ raise APError("Invalid agent plan contract: " + ", ".join(missing))
4973
+ _validate_orchestration_contract("agentPlan", plan)
4675
4974
  return plan
4676
4975
 
4677
4976
 
@@ -4794,8 +5093,6 @@ def _mechanism_plan(
4794
5093
  required.append("task_lifecycle")
4795
5094
  if parallel_writers > 1:
4796
5095
  required.append("parallel_fixers")
4797
- else:
4798
- optional.append("parallel_fixers")
4799
5096
  if review_required:
4800
5097
  required.append("independent_review")
4801
5098
  else:
@@ -4815,7 +5112,8 @@ def _mechanism_plan(
4815
5112
  "lifecycle_required": "task_lifecycle" in ordered,
4816
5113
  "rule": (
4817
5114
  "run required mechanisms; select optional mechanisms only when expected value exceeds "
4818
- "coordination cost; do not run forbidden mechanisms unless the user explicitly overrides"
5115
+ "coordination cost; reclassify before changing writer count; do not run forbidden "
5116
+ "mechanisms unless the user explicitly overrides"
4819
5117
  ),
4820
5118
  }
4821
5119
 
@@ -4834,6 +5132,7 @@ def _resolve_execution_plan(
4834
5132
  parallel_writers: int = 1,
4835
5133
  requested_task_kind: str = "",
4836
5134
  continue_direct: bool = False,
5135
+ direct_claim_id: str = "",
4837
5136
  ) -> dict:
4838
5137
  impact = _impact_summary(
4839
5138
  cfg,
@@ -4851,6 +5150,7 @@ def _resolve_execution_plan(
4851
5150
  path_classification = _classify_paths(classification_inputs)
4852
5151
  path_categories = set(path_classification["categories"])
4853
5152
  intent_categories = _classify_intent(intent)
5153
+ high_confidence_intent_categories = _high_confidence_intent_categories(intent)
4854
5154
  merged_categories = path_categories | set(intent_categories)
4855
5155
  classification = _classification_for_categories(merged_categories, len(classification_inputs))
4856
5156
  categories = set(classification["categories"])
@@ -4901,8 +5201,10 @@ def _resolve_execution_plan(
4901
5201
  "release_or_tooling",
4902
5202
  }
4903
5203
  default_high_path_categories: set[str] = set()
5204
+ path_category_sets: list[set[str]] = []
4904
5205
  for path in classification_inputs:
4905
5206
  per_path = set(_classify_paths([path])["categories"])
5207
+ path_category_sets.append(per_path)
4906
5208
  default_high_path_categories.update(
4907
5209
  per_path & {"db", "gateway", "prod_config", "release_or_tooling"}
4908
5210
  )
@@ -4911,6 +5213,13 @@ def _resolve_execution_plan(
4911
5213
  per_path & {"auth", "payment", "file_transfer"}
4912
5214
  )
4913
5215
  intent_risk_candidates = sorted(set(intent_categories) & high_categories)
5216
+ all_planned_code_paths_are_ui = bool(path_category_sets) and all(
5217
+ "ui" in per_path or per_path <= {"docs", "test"}
5218
+ for per_path in path_category_sets
5219
+ )
5220
+ default_high_intent_categories = set(high_confidence_intent_categories)
5221
+ if all_planned_code_paths_are_ui:
5222
+ default_high_intent_categories.difference_update({"auth", "payment", "file_transfer"})
4914
5223
  high_signals: list[str] = []
4915
5224
  if task_kind == "change" and default_high_path_categories and not docs_or_tests_only:
4916
5225
  high_signals.append(
@@ -4918,6 +5227,10 @@ def _resolve_execution_plan(
4918
5227
  )
4919
5228
  if task_kind == "change" and "high-risk" in rule_profiles:
4920
5229
  high_signals.append("matched gate rule with profile=high-risk")
5230
+ if task_kind == "change" and default_high_intent_categories and not docs_or_tests_only:
5231
+ high_signals.append(
5232
+ "high-confidence risk intent: " + ", ".join(sorted(default_high_intent_categories))
5233
+ )
4921
5234
  if high_signals:
4922
5235
  detected_profile = "high-risk"
4923
5236
  profile_reasons.extend(high_signals)
@@ -4981,14 +5294,28 @@ def _resolve_execution_plan(
4981
5294
  dirty_outside_plan = [
4982
5295
  path for path in dirty_paths if not _path_is_owned(path, normalized_planned_paths)
4983
5296
  ] if normalized_planned_paths else list(dirty_paths)
4984
- active_writer = _has_registered_active_task(repo)
5297
+ registered_active_writer = _has_registered_active_task(repo)
4985
5298
  configured_isolation = _task_isolation(cfg)
4986
5299
  if continue_direct and task_kind != "change":
4987
5300
  raise APError("--continue-direct is valid only for task-kind=change")
4988
5301
  if continue_direct and not normalized_planned_paths:
4989
5302
  raise APError("--continue-direct requires every current task path via --planned-path")
5303
+ direct_claim = (
5304
+ _require_direct_claim(repo, direct_claim_id, normalized_planned_paths)
5305
+ if continue_direct
5306
+ else {}
5307
+ )
5308
+ runtime_actor = _text(os.environ.get("CODEX_THREAD_ID"))
5309
+ other_direct_claims = [
5310
+ item
5311
+ for item in _active_direct_claims(repo)
5312
+ if _text(item.get("claim_id")) != _text(direct_claim_id)
5313
+ and (not runtime_actor or _text(item.get("owner")) != runtime_actor)
5314
+ ]
5315
+ active_writer = bool(registered_active_writer or other_direct_claims)
4990
5316
  continued_direct = bool(
4991
5317
  continue_direct
5318
+ and direct_claim
4992
5319
  and configured_isolation == "adaptive"
4993
5320
  and writer_count == 1
4994
5321
  and not active_writer
@@ -5046,6 +5373,7 @@ def _resolve_execution_plan(
5046
5373
  "task_kind": task_kind,
5047
5374
  "intent_categories": intent_categories,
5048
5375
  "intent_risk_candidates": intent_risk_candidates,
5376
+ "high_confidence_intent_categories": sorted(high_confidence_intent_categories),
5049
5377
  "reasons": execution_reasons,
5050
5378
  "configured_profile": configured_profile,
5051
5379
  "requested_profile": requested_profile_value or None,
@@ -5100,6 +5428,11 @@ def cmd_classify(args: argparse.Namespace) -> None:
5100
5428
  intent_parts.append(path.read_text(encoding="utf-8"))
5101
5429
  except OSError as exc:
5102
5430
  raise APError(f"Cannot read --intent-file: {path}: {exc}") from exc
5431
+ claim_direct = bool(getattr(args, "claim_direct", False))
5432
+ continue_direct = bool(getattr(args, "continue_direct", False))
5433
+ direct_claim_id = _text(getattr(args, "direct_claim", ""))
5434
+ if claim_direct and continue_direct:
5435
+ raise APError("--claim-direct and --continue-direct are mutually exclusive.")
5103
5436
  plan = _resolve_execution_plan(
5104
5437
  cfg,
5105
5438
  repo,
@@ -5111,8 +5444,19 @@ def cmd_classify(args: argparse.Namespace) -> None:
5111
5444
  intent="\n".join(part for part in intent_parts if part),
5112
5445
  parallel_writers=int(getattr(args, "writers", 1) or 1),
5113
5446
  requested_task_kind=_text(getattr(args, "task_kind", "")),
5114
- continue_direct=bool(getattr(args, "continue_direct", False)),
5447
+ continue_direct=continue_direct,
5448
+ direct_claim_id=_text(getattr(args, "direct_claim", "")),
5115
5449
  )
5450
+ direct_claim: dict = {}
5451
+ if claim_direct:
5452
+ if plan["task_kind"] != "change" or plan["execution_mode"] != "direct":
5453
+ raise APError("--claim-direct requires a clean adaptive single-writer change plan.")
5454
+ direct_claim = _create_direct_claim(
5455
+ repo,
5456
+ cfg,
5457
+ list(plan.get("planned_files") or []),
5458
+ _actor_id(args, "claim_owner"),
5459
+ )
5116
5460
  risk = {"micro": "P3", "standard": "P2", "high-risk": "P1"}[plan["profile"]]
5117
5461
  commands: list[str] = []
5118
5462
  if plan["needs_dd"]:
@@ -5121,6 +5465,15 @@ def cmd_classify(args: argparse.Namespace) -> None:
5121
5465
  **plan,
5122
5466
  "risk": risk,
5123
5467
  "recommended_commands": commands,
5468
+ "direct_claim": (
5469
+ {
5470
+ "id": _text(direct_claim.get("claim_id")),
5471
+ "base_sha": _text(direct_claim.get("base_sha")),
5472
+ "owned_paths": list(direct_claim.get("owned_paths") or []),
5473
+ }
5474
+ if direct_claim
5475
+ else None
5476
+ ),
5124
5477
  }
5125
5478
  if args.json:
5126
5479
  print(json.dumps(result, ensure_ascii=False, indent=2))
@@ -5152,6 +5505,8 @@ def cmd_classify(args: argparse.Namespace) -> None:
5152
5505
  "[classify] forbidden="
5153
5506
  + (", ".join(result["mechanism_plan"]["forbidden"]) or "(none)")
5154
5507
  )
5508
+ if direct_claim:
5509
+ print(f"[classify] direct_claim={direct_claim['claim_id']}")
5155
5510
  for stage in result["agent_plan"]["stages"]:
5156
5511
  print(
5157
5512
  "[classify] agent_stage="
@@ -5165,6 +5520,39 @@ def cmd_classify(args: argparse.Namespace) -> None:
5165
5520
  _record_evidence(repo, cfg, "classify", "pass", result)
5166
5521
 
5167
5522
 
5523
+ def cmd_agent_contract_check(args: argparse.Namespace) -> None:
5524
+ repo = Path(args.repo).resolve()
5525
+ raw = _text(getattr(args, "payload", ""))
5526
+ source = _text(getattr(args, "file", ""))
5527
+ if source:
5528
+ if source == "-":
5529
+ raw = sys.stdin.read(1048577)
5530
+ else:
5531
+ path = Path(source)
5532
+ if not path.is_absolute():
5533
+ path = repo / path
5534
+ try:
5535
+ if path.stat().st_size > 1048576:
5536
+ raise APError("Agent contract payload is limited to 1 MiB.")
5537
+ raw = path.read_text(encoding="utf-8")
5538
+ except OSError as exc:
5539
+ raise APError(f"Cannot read agent contract payload: {path}: {exc}") from exc
5540
+ if len(raw.encode("utf-8")) > 1048576:
5541
+ raise APError("Agent contract payload is limited to 1 MiB.")
5542
+ try:
5543
+ payload = json.loads(raw)
5544
+ except json.JSONDecodeError as exc:
5545
+ raise APError(f"Agent contract payload is not valid JSON: {exc}") from exc
5546
+ if not isinstance(payload, dict):
5547
+ raise APError("Agent contract payload must be a JSON object.")
5548
+ _validate_orchestration_contract(args.kind, payload)
5549
+ result = {"valid": True, "kind": args.kind}
5550
+ if args.json:
5551
+ print(json.dumps(result, ensure_ascii=False, indent=2))
5552
+ else:
5553
+ print(f"[agent-contract-check] OK kind={args.kind}")
5554
+
5555
+
5168
5556
  def cmd_run(args: argparse.Namespace) -> None:
5169
5557
  """
5170
5558
  Run any configured gate command by name.
@@ -6846,6 +7234,7 @@ def cmd_task_start(args: argparse.Namespace) -> None:
6846
7234
  "writer as its own task ID; use --writers only with classify for planning."
6847
7235
  )
6848
7236
  continue_direct = bool(getattr(args, "continue_direct", False))
7237
+ direct_claim_id = _text(getattr(args, "direct_claim", ""))
6849
7238
  explicit_lifecycle = bool(
6850
7239
  getattr(args, "isolated", False)
6851
7240
  or getattr(args, "review_required", False)
@@ -6859,6 +7248,7 @@ def cmd_task_start(args: argparse.Namespace) -> None:
6859
7248
  parallel_writers=writer_count,
6860
7249
  requested_task_kind="change",
6861
7250
  continue_direct=continue_direct,
7251
+ direct_claim_id=direct_claim_id,
6862
7252
  )
6863
7253
  if continue_direct and preflight_plan["execution_mode"] != "direct":
6864
7254
  detail = ", ".join(preflight_plan["dirty_outside_plan"]) or "policy or active-writer conflict"
@@ -6889,6 +7279,16 @@ def cmd_task_start(args: argparse.Namespace) -> None:
6889
7279
  _repo_lock(repo, "integration", timeout_s=timeout_s),
6890
7280
  _repo_lock(repo, "task-registry", timeout_s=timeout_s),
6891
7281
  ):
7282
+ for claim in _active_direct_claims(repo):
7283
+ if _text(claim.get("claim_id")) == direct_claim_id:
7284
+ continue
7285
+ claim_paths = list(claim.get("owned_paths") or [])
7286
+ if _owned_paths_overlap(owned_paths, claim_paths):
7287
+ raise APError(
7288
+ "Owned paths overlap an active direct claim held by "
7289
+ f"{_text(claim.get('owner')) or '(unknown)'}: "
7290
+ + ", ".join(claim_paths)
7291
+ )
6892
7292
  if _read_json_object(_task_registry_path(repo, task_id)):
6893
7293
  raise APError(f"Task is already registered: {task_id}")
6894
7294
 
@@ -6938,6 +7338,7 @@ def cmd_task_start(args: argparse.Namespace) -> None:
6938
7338
  parallel_writers=writer_count,
6939
7339
  requested_task_kind="change",
6940
7340
  continue_direct=continue_direct,
7341
+ direct_claim_id=direct_claim_id,
6941
7342
  )
6942
7343
  if not plan["mechanism_plan"]["lifecycle_required"] and not explicit_lifecycle:
6943
7344
  raise APError(
@@ -7019,6 +7420,7 @@ def cmd_task_start(args: argparse.Namespace) -> None:
7019
7420
  "common_submodule_config": {},
7020
7421
  }
7021
7422
  _save_task_manifest(repo, manifest)
7423
+ _consume_direct_claim(repo, direct_claim_id)
7022
7424
  print(f"[task-start] task={task_id}")
7023
7425
  print("[task-start] execution_mode=direct")
7024
7426
  print(f"[task-start] branch={current_branch}")
@@ -7240,6 +7642,9 @@ def cmd_task_review(args: argparse.Namespace) -> None:
7240
7642
  raise APError("Independent review requires an explicit --reviewer identity.")
7241
7643
  if reviewer == _text(manifest.get("owner")):
7242
7644
  raise APError("Independent reviewer identity must differ from the task lifecycle owner.")
7645
+ writer = _text((manifest.get("writer_lease") or {}).get("holder"))
7646
+ if reviewer == writer:
7647
+ raise APError("Independent reviewer identity must differ from the current writer lease holder.")
7243
7648
  manifest["review"] = {
7244
7649
  "verdict": args.verdict,
7245
7650
  "diff_base": _text(manifest.get("base_sha")),
@@ -8195,11 +8600,22 @@ def main(argv: Optional[List[str]] = None) -> int:
8195
8600
  s.add_argument("--intent")
8196
8601
  s.add_argument("--intent-file")
8197
8602
  s.add_argument("--task-kind", choices=sorted(_REQUESTED_TASK_KINDS), default="auto")
8603
+ s.add_argument("--claim-direct", action="store_true")
8604
+ s.add_argument("--claim-owner")
8198
8605
  s.add_argument("--continue-direct", action="store_true")
8606
+ s.add_argument("--direct-claim")
8199
8607
  s.add_argument("--writers", type=int, default=1)
8200
8608
  s.add_argument("--json", action="store_true")
8201
8609
  s.set_defaults(func=cmd_classify)
8202
8610
 
8611
+ s = sp.add_parser("agent-contract-check")
8612
+ s.add_argument("--kind", choices=["assignment", "result", "agentPlan", "classify"], required=True)
8613
+ source = s.add_mutually_exclusive_group(required=True)
8614
+ source.add_argument("--file")
8615
+ source.add_argument("--payload")
8616
+ s.add_argument("--json", action="store_true")
8617
+ s.set_defaults(func=cmd_agent_contract_check)
8618
+
8203
8619
  s = sp.add_parser("validation-map-check")
8204
8620
  s.add_argument("--base")
8205
8621
  s.add_argument("--path", action="append")
@@ -8305,6 +8721,7 @@ def main(argv: Optional[List[str]] = None) -> int:
8305
8721
  s.add_argument("--isolated", action="store_true")
8306
8722
  s.add_argument("--review-required", action="store_true")
8307
8723
  s.add_argument("--continue-direct", action="store_true")
8724
+ s.add_argument("--direct-claim")
8308
8725
  s.add_argument(
8309
8726
  "--force-lifecycle",
8310
8727
  action="store_true",
@@ -24,6 +24,8 @@ def command(
24
24
  check: bool = True,
25
25
  input_text: str | None = None,
26
26
  ) -> subprocess.CompletedProcess[str]:
27
+ env = os.environ.copy()
28
+ env.setdefault("CODEX_THREAD_ID", "concurrency-test-owner")
27
29
  result = subprocess.run(
28
30
  list(args),
29
31
  cwd=cwd,
@@ -32,6 +34,7 @@ def command(
32
34
  input=input_text,
33
35
  capture_output=True,
34
36
  timeout=30,
37
+ env=env,
35
38
  )
36
39
  if check and result.returncode != 0:
37
40
  raise AssertionError(
@@ -188,6 +191,13 @@ class AutoCodingConcurrencyTests(unittest.TestCase):
188
191
  )
189
192
  return fingerprint
190
193
 
194
+ def claim_direct(self, repo: Path, *owned_paths: str) -> str:
195
+ args: list[str] = ["classify", "--task-kind", "change", "--claim-direct", "--json"]
196
+ for path in owned_paths:
197
+ args.extend(["--planned-path", path])
198
+ payload = json.loads(self.ap(repo, *args).stdout)
199
+ return payload["direct_claim"]["id"]
200
+
191
201
  def commit_push(self, repo: Path, task_id: str, message: str) -> subprocess.CompletedProcess[str]:
192
202
  self.approve_task(repo, task_id)
193
203
  return self.ap(repo, "commit-push", task_id, "--msg", message)
@@ -446,6 +456,7 @@ class AutoCodingConcurrencyTests(unittest.TestCase):
446
456
 
447
457
  def test_continue_direct_can_adopt_owned_changes_for_new_review_lifecycle(self) -> None:
448
458
  _, repo, remote = self.make_repo("adaptive", require_review=False)
459
+ claim = self.claim_direct(repo, "shared.txt")
449
460
  (repo / "shared.txt").write_text("continued direct\n", encoding="utf-8")
450
461
  started = self.ap(
451
462
  repo,
@@ -454,6 +465,8 @@ class AutoCodingConcurrencyTests(unittest.TestCase):
454
465
  "--owned-path",
455
466
  "shared.txt",
456
467
  "--continue-direct",
468
+ "--direct-claim",
469
+ claim,
457
470
  "--review-required",
458
471
  )
459
472
  self.assertIn("execution_mode=direct", started.stdout)
@@ -477,6 +490,7 @@ class AutoCodingConcurrencyTests(unittest.TestCase):
477
490
  self.assertIn("execution_mode=direct", pushed.stdout)
478
491
  self.assertEqual("continued direct", git_output(remote, "show", "refs/heads/dev:shared.txt"))
479
492
 
493
+ claim = self.claim_direct(repo, "shared.txt")
480
494
  (repo / "shared.txt").write_text("owned again\n", encoding="utf-8")
481
495
  (repo / "unrelated.txt").write_text("unknown\n", encoding="utf-8")
482
496
  rejected = self.ap(
@@ -486,6 +500,8 @@ class AutoCodingConcurrencyTests(unittest.TestCase):
486
500
  "--owned-path",
487
501
  "shared.txt",
488
502
  "--continue-direct",
503
+ "--direct-claim",
504
+ claim,
489
505
  "--review-required",
490
506
  check=False,
491
507
  )
@@ -493,6 +509,43 @@ class AutoCodingConcurrencyTests(unittest.TestCase):
493
509
  self.assertIn("unrelated.txt", rejected.stdout + rejected.stderr)
494
510
  self.assertFalse(self.registry_manifest_path(repo, "DIRECT-CONTINUE-BLOCKED").exists())
495
511
 
512
+ def test_reviewer_cannot_be_current_writer(self) -> None:
513
+ _, repo, _ = self.make_repo()
514
+ self.ap(
515
+ repo,
516
+ "task-start",
517
+ "SELF-REVIEW",
518
+ "--base",
519
+ "origin/dev",
520
+ "--owned-path",
521
+ "src",
522
+ "--isolated",
523
+ "--review-required",
524
+ "--writer",
525
+ "self-reviewer",
526
+ )
527
+ worktree = self.task_worktree(repo, "SELF-REVIEW")
528
+ payload = worktree / "src" / "payload.txt"
529
+ payload.parent.mkdir(parents=True, exist_ok=True)
530
+ payload.write_text("changed\n", encoding="utf-8")
531
+ status = json.loads(
532
+ self.ap(worktree, "task-status", "SELF-REVIEW", "--json").stdout
533
+ )["tasks"][0]
534
+ rejected = self.ap(
535
+ worktree,
536
+ "task-review",
537
+ "SELF-REVIEW",
538
+ "--verdict",
539
+ "approved",
540
+ "--diff-fingerprint",
541
+ status["current_diff_fingerprint"],
542
+ "--reviewer",
543
+ "self-reviewer",
544
+ check=False,
545
+ )
546
+ self.assertNotEqual(0, rejected.returncode)
547
+ self.assertIn("writer lease holder", rejected.stdout + rejected.stderr)
548
+
496
549
  def test_schema_one_task_status_fails_closed_with_migration_recovery(self) -> None:
497
550
  _, repo, _ = self.make_repo()
498
551
  self.start_task(repo, "LEGACY-SCHEMA")
@@ -3,6 +3,7 @@ from __future__ import annotations
3
3
 
4
4
  import argparse
5
5
  import json
6
+ import os
6
7
  import subprocess
7
8
  import sys
8
9
  import tempfile
@@ -277,7 +278,9 @@ class AutoCodingProfileTests(unittest.TestCase):
277
278
  )
278
279
  self.assertFalse(plan["mechanism_plan"]["lifecycle_required"])
279
280
  self.assertIn("read_only_subagents", plan["mechanism_plan"]["optional_when_beneficial"])
281
+ self.assertNotIn("parallel_fixers", plan["mechanism_plan"]["optional_when_beneficial"])
280
282
  self.assertIn("task_lifecycle", plan["mechanism_plan"]["forbidden"])
283
+ self.assertIn("parallel_fixers", plan["mechanism_plan"]["forbidden"])
281
284
 
282
285
  def test_intent_only_classifies_read_only_change_and_terminal_work(self) -> None:
283
286
  repo, cfg = self.make_repo()
@@ -360,6 +363,12 @@ class AutoCodingProfileTests(unittest.TestCase):
360
363
 
361
364
  def test_continue_direct_accepts_only_declared_current_task_dirt(self) -> None:
362
365
  repo, cfg = self.make_repo()
366
+ claim = ap._create_direct_claim(
367
+ repo,
368
+ cfg,
369
+ ["src/widget.py"],
370
+ os.environ.get("CODEX_THREAD_ID") or "profile-test-owner",
371
+ )
363
372
  target = repo / "src" / "widget.py"
364
373
  target.parent.mkdir(parents=True, exist_ok=True)
365
374
  target.write_text("task change\n", encoding="utf-8")
@@ -371,20 +380,32 @@ class AutoCodingProfileTests(unittest.TestCase):
371
380
  cfg,
372
381
  planned_paths=["src/widget.py"],
373
382
  continue_direct=True,
383
+ direct_claim_id=claim["claim_id"],
374
384
  )
375
385
  self.assertEqual("direct", continued["execution_mode"])
376
386
  self.assertTrue(continued["continued_direct"])
377
387
  self.assertEqual([], continued["dirty_outside_plan"])
378
388
 
379
389
  (repo / "unrelated.txt").write_text("other writer\n", encoding="utf-8")
380
- blocked = self.plan(
381
- repo,
382
- cfg,
383
- planned_paths=["src/widget.py"],
384
- continue_direct=True,
385
- )
386
- self.assertEqual("isolated", blocked["execution_mode"])
387
- self.assertEqual(["unrelated.txt"], blocked["dirty_outside_plan"])
390
+ with self.assertRaises(APError) as context:
391
+ self.plan(
392
+ repo,
393
+ cfg,
394
+ planned_paths=["src/widget.py"],
395
+ continue_direct=True,
396
+ direct_claim_id=claim["claim_id"],
397
+ )
398
+ self.assertIn("outside the clean direct claim", str(context.exception))
399
+
400
+ def test_continue_direct_requires_a_clean_pre_write_claim(self) -> None:
401
+ repo, cfg = self.make_repo()
402
+ (repo / "unknown.txt").write_text("pre-existing user change\n", encoding="utf-8")
403
+ with self.assertRaises(APError) as context:
404
+ ap._create_direct_claim(repo, cfg, ["."], "profile-test-owner")
405
+ self.assertIn("before the first write", str(context.exception))
406
+ with self.assertRaises(APError) as context:
407
+ self.plan(repo, cfg, planned_paths=["."], continue_direct=True)
408
+ self.assertIn("requires --direct-claim", str(context.exception))
388
409
 
389
410
  def test_risk_intent_is_candidate_while_paths_and_rules_control_escalation(self) -> None:
390
411
  repo, cfg = self.make_repo()
@@ -419,6 +440,38 @@ class AutoCodingProfileTests(unittest.TestCase):
419
440
  order = self.plan(repo, cfg, planned_paths=["backend/orders/sort_order.py"])
420
441
  self.assertNotIn("payment", order["categories"])
421
442
 
443
+ def test_high_confidence_intent_and_backend_login_escalate_without_ui_false_positive(self) -> None:
444
+ repo, cfg = self.make_repo()
445
+ for intent, category in [
446
+ ("修改数据库迁移", "db"),
447
+ ("修改后端鉴权权限", "auth"),
448
+ ("修改支付结算逻辑", "payment"),
449
+ ("修改生产网关配置", "gateway"),
450
+ ]:
451
+ with self.subTest(intent=intent):
452
+ plan = self.plan(repo, cfg, intent=intent)
453
+ self.assertEqual("high-risk", plan["profile"])
454
+ self.assertTrue(plan["review_required"])
455
+ self.assertIn(category, plan["high_confidence_intent_categories"])
456
+
457
+ backend_login = self.plan(
458
+ repo,
459
+ cfg,
460
+ planned_paths=["backend/login_handler.go"],
461
+ intent="修复登录处理",
462
+ )
463
+ self.assertEqual("high-risk", backend_login["profile"])
464
+ self.assertTrue(backend_login["review_required"])
465
+
466
+ login_ui = self.plan(
467
+ repo,
468
+ cfg,
469
+ planned_paths=["frontend/LoginPage.tsx"],
470
+ intent="修复登录页面跳转",
471
+ )
472
+ self.assertEqual("standard", login_ui["profile"])
473
+ self.assertFalse(login_ui["review_required"])
474
+
422
475
  def test_generated_agent_strategies_match_contract_schema(self) -> None:
423
476
  schema = json.loads(
424
477
  (REPO_ROOT / "src" / "auto-coding-skill" / "data" / "contracts" / "orchestration-v1.schema.json")
@@ -434,6 +487,50 @@ class AutoCodingProfileTests(unittest.TestCase):
434
487
  with self.subTest(kwargs=kwargs):
435
488
  plan = self.plan(repo, cfg, **kwargs)
436
489
  self.assertIn(plan["agent_plan"]["strategy"], allowed)
490
+ ap._validate_orchestration_contract("classify", plan)
491
+
492
+ def test_agent_assignment_and_result_contracts_are_machine_enforced(self) -> None:
493
+ fingerprint = "a" * 64
494
+ assignment = {
495
+ "contract_version": 1,
496
+ "node_id": "reviewer-1",
497
+ "task_id": "T001",
498
+ "role": "reviewer",
499
+ "base_sha": "HEAD",
500
+ "scope": "review owned diff",
501
+ "depends_on": [],
502
+ "acceptance": ["review current fingerprint"],
503
+ "diff_base": "HEAD~1",
504
+ "diff_head": "HEAD",
505
+ "diff_fingerprint": fingerprint,
506
+ "owning_fixer": "fixer-1",
507
+ }
508
+ ap._validate_orchestration_contract("assignment", assignment)
509
+ self_review = dict(assignment, node_id="fixer-1")
510
+ with self.assertRaises(APError):
511
+ ap._validate_orchestration_contract("assignment", self_review)
512
+
513
+ result = {
514
+ "contract_version": 1,
515
+ "node_id": "reviewer-1",
516
+ "role": "reviewer",
517
+ "task_id": "T001",
518
+ "base_sha": "HEAD~1",
519
+ "status": "completed",
520
+ "summary": "reviewed",
521
+ "depends_on": [],
522
+ "owned_paths": [],
523
+ "changed_paths": [],
524
+ "diff_fingerprint": fingerprint,
525
+ "evidence": ["diff reviewed"],
526
+ "findings": [],
527
+ "verdict": "approved",
528
+ "risks": [],
529
+ "next_owner": "main",
530
+ }
531
+ ap._validate_orchestration_contract("result", result)
532
+ with self.assertRaises(APError):
533
+ ap._validate_orchestration_contract("result", dict(result, diff_fingerprint=""))
437
534
 
438
535
  def test_validation_routes_collect_all_commands_and_reject_unmapped_code(self) -> None:
439
536
  repo, cfg = self.make_repo()
@@ -219,7 +219,9 @@ function testMinimalSyncConvergesWithinBudget() {
219
219
  const files = listProjectFiles(repo);
220
220
  const lines = files.reduce((total, file) => total + fs.readFileSync(file, "utf8").split(/\r?\n/).length, 0);
221
221
  assert(files.length <= 23, `minimal scaffold file budget exceeded: ${files.length}`);
222
- assert(lines <= 10800, `minimal scaffold line budget exceeded: ${lines}`);
222
+ // Deterministic direct-claim and orchestration-contract guards replace model-only
223
+ // assertions in 4.1.4; keep a measured ceiling without forcing opaque code.
224
+ assert(lines <= 11200, `minimal scaffold line budget exceeded: ${lines}`);
223
225
  const engineering = fs.readFileSync(path.join(repo, "docs", "ENGINEERING.md"), "utf8");
224
226
  assert(engineering.includes("profile: \"auto\""), "engineering should enable adaptive profiles");
225
227
  assert(engineering.includes("isolation: \"adaptive\""), "engineering should default to adaptive clean-branch/worktree isolation");
@@ -733,7 +735,7 @@ function testManagedEngineeringSyncIsControlledAndIdempotent() {
733
735
 
734
736
  const engineering = path.join(repo, "docs", "ENGINEERING.md");
735
737
  const initial = fs.readFileSync(engineering, "utf8");
736
- const startPattern = /<!-- auto-coding-skill:managed-workflow:start version=4\.1\.3 -->/;
738
+ const startPattern = /<!-- auto-coding-skill:managed-workflow:start version=4\.1\.4 -->/;
737
739
  const endMarker = "<!-- auto-coding-skill:managed-workflow:end -->";
738
740
  assert(startPattern.test(initial), "new projects should include a versioned managed workflow marker");
739
741
  assert(initial.includes(endMarker), "new projects should include the managed workflow end marker");
@@ -752,7 +754,7 @@ function testManagedEngineeringSyncIsControlledAndIdempotent() {
752
754
  const dryRun = run("node", [cli, "sync", "--projects", repo, "--dry-run", "--json"]);
753
755
  const dryResult = JSON.parse(dryRun.stdout).results[0];
754
756
  assert(dryResult.managedWorkflow.state === "stale", `dry-run should expose stale workflow state: ${dryRun.stdout}`);
755
- assert(dryResult.managedWorkflow.version === "4.1.3", "dry-run should expose the target workflow version");
757
+ assert(dryResult.managedWorkflow.version === "4.1.4", "dry-run should expose the target workflow version");
756
758
  assert(dryResult.actions.some(item => item.action === "would-update" && item.path === "docs/ENGINEERING.md"), "dry-run should plan the managed body update");
757
759
  assert(fs.readFileSync(engineering, "utf8") === customized, "dry-run must not write ENGINEERING.md");
758
760
 
@@ -762,14 +764,14 @@ function testManagedEngineeringSyncIsControlledAndIdempotent() {
762
764
  const updatedEnd = updated.indexOf(endMarker) + endMarker.length;
763
765
  assert(updated.slice(0, updatedStart) === outsideBefore, "sync must preserve frontmatter and content before the managed block byte-for-byte");
764
766
  assert(updated.slice(updatedEnd) === outsideAfter, "sync must preserve content after the managed block byte-for-byte");
765
- assert(updated.includes("version=4.1.3"), "sync should install the current managed workflow version");
767
+ assert(updated.includes("version=4.1.4"), "sync should install the current managed workflow version");
766
768
  assert(updated.includes("The frontmatter contract is:"), "sync should refresh stale managed workflow content");
767
769
 
768
770
  fillRequiredAccess(repo);
769
771
  const status = run("node", [cli, "status", "--projects", repo, "--json"]);
770
772
  const statusResult = JSON.parse(status.stdout).results[0];
771
773
  assert(statusResult.managedWorkflow.state === "current", `status should expose current managed workflow state: ${status.stdout}`);
772
- assert(statusResult.managedWorkflow.version === "4.1.3", "status should expose the installed managed workflow version");
774
+ assert(statusResult.managedWorkflow.version === "4.1.4", "status should expose the installed managed workflow version");
773
775
 
774
776
  const beforeSecondSync = fs.readFileSync(engineering, "utf8");
775
777
  const second = run("node", [cli, "sync", "--projects", repo, "--json"]);
@@ -797,7 +799,7 @@ function testLegacyEngineeringMigrationPreservesExistingBody() {
797
799
  assert(dryResult.actions.find(item => item.path === "docs/ENGINEERING.md")?.detail.includes("preserved-custom"), "custom legacy action should be labeled preserved-custom");
798
800
  run("node", [cli, "sync", "--projects", repo]);
799
801
  const migrated = fs.readFileSync(engineering, "utf8");
800
- assert(migrated.includes("version=4.1.3"), "legacy migration should insert the current managed workflow");
802
+ assert(migrated.includes("version=4.1.4"), "legacy migration should insert the current managed workflow");
801
803
  assert(migrated.includes(legacyNote), "legacy migration must preserve the complete existing body");
802
804
  const migratedStart = migrated.indexOf("<!-- auto-coding-skill:managed-workflow:start");
803
805
  const migratedEnd = migrated.indexOf(endMarker) + endMarker.length;
@@ -901,7 +903,7 @@ function testManagedAgentsMigrationReplacesWholeFileAndArchivesPreviousRules() {
901
903
  run("node", [cli, "sync", "--projects", repo]);
902
904
  const agents = path.join(repo, "AGENTS.md");
903
905
  const initial = fs.readFileSync(agents, "utf8");
904
- assert(initial.includes("managed-agents:start version=4.1.3"), "new projects should receive the versioned root AGENTS block");
906
+ assert(initial.includes("managed-agents:start version=4.1.4"), "new projects should receive the versioned root AGENTS block");
905
907
 
906
908
  const custom = [
907
909
  "# Project rules",
@@ -920,12 +922,12 @@ function testManagedAgentsMigrationReplacesWholeFileAndArchivesPreviousRules() {
920
922
 
921
923
  run("node", [cli, "sync", "--projects", repo]);
922
924
  const migrated = fs.readFileSync(agents, "utf8");
923
- assert(migrated.includes("managed-agents:start version=4.1.3"), "AGENTS migration should install the current managed block");
925
+ assert(migrated.includes("managed-agents:start version=4.1.4"), "AGENTS migration should install the current managed block");
924
926
  assert(!migrated.includes("Preserve this repository-specific rule exactly."), "root AGENTS must contain no project-specific tail");
925
927
  assert(!migrated.includes("must execute `commands.gate_full`"), "known official conflicting rule should be removed");
926
928
  const canonical = fs.readFileSync(path.join(repoRoot, "cli", "assets", "skill", "data", "templates", "bridges", "AGENTS.md"), "utf8");
927
929
  assert(migrated === canonical, "root AGENTS must be byte-identical to the packaged canonical file");
928
- const archive = path.join(repo, "docs", "archive", "workflow", "AGENTS.pre-4.1.3.md");
930
+ const archive = path.join(repo, "docs", "archive", "workflow", "AGENTS.pre-4.1.4.md");
929
931
  assert(fs.readFileSync(archive, "utf8").includes("Preserve this repository-specific rule exactly."), "previous AGENTS content must be archived once");
930
932
  const stable = fs.readFileSync(agents);
931
933
  run("node", [cli, "sync", "--projects", repo]);
@@ -984,7 +986,7 @@ function testEngineeringFrameworkAllowsProjectFactsButRejectsDuplicateWorkflow()
984
986
  const migrationResult = JSON.parse(migration.stdout).results[0];
985
987
  assert(migrationResult.managedWorkflow.state === "stale", "known duplicate sections should use controlled migration");
986
988
  assert(migrationResult.managedWorkflow.migrations.includes("engineering-section-delivery-flow"), "known section migration should be explicit");
987
- assert(migrationResult.actions.some(item => item.action === "would-archive" && item.path.includes("ENGINEERING.pre-4.1.3")), "controlled section cleanup should archive the previous ENGINEERING file");
989
+ assert(migrationResult.actions.some(item => item.action === "would-archive" && item.path.includes("ENGINEERING.pre-4.1.4")), "controlled section cleanup should archive the previous ENGINEERING file");
988
990
  run("node", [cli, "sync", "--projects", repo]);
989
991
  assert(!fs.readFileSync(engineering, "utf8").includes("Known obsolete workflow"), "known duplicate workflow section should be removed");
990
992
 
@@ -996,16 +998,20 @@ function testEngineeringFrameworkAllowsProjectFactsButRejectsDuplicateWorkflow()
996
998
  }
997
999
 
998
1000
  function testReleaseVersionMarkersStayInSync() {
999
- const expected = "4.1.3";
1001
+ const expected = "4.1.4";
1000
1002
  const pkg = JSON.parse(fs.readFileSync(path.join(repoRoot, "package.json"), "utf8"));
1001
1003
  const lock = JSON.parse(fs.readFileSync(path.join(repoRoot, "package-lock.json"), "utf8"));
1002
1004
  const policy = JSON.parse(fs.readFileSync(
1003
1005
  path.join(repoRoot, "src", "auto-coding-skill", "data", "policies", "workflow-migrations-v1.json"),
1004
1006
  "utf8",
1005
1007
  ));
1006
- assert(pkg.version === expected, "package version must match the 4.1.3 release");
1008
+ assert(pkg.version === expected, "package version must match the 4.1.4 release");
1007
1009
  assert(lock.version === expected && lock.packages[""].version === expected, "package-lock versions must match");
1008
1010
  assert(policy.managed_versions.engineering === expected && policy.managed_versions.agents === expected, "managed workflow versions must match");
1011
+ const publishWorkflow = fs.readFileSync(path.join(repoRoot, ".github", "workflows", "npm-publish.yml"), "utf8");
1012
+ assert(publishWorkflow.includes("tags:\n - \"v*\""), "npm publish must run from version tag pushes");
1013
+ assert(publishWorkflow.includes("Verify release identity"), "npm publish must bind the tag to package version");
1014
+ assert(publishWorkflow.includes("Check npm registry") && publishWorkflow.includes("Verify npm publication"), "npm publish must be idempotent and registry-verified");
1009
1015
  for (const rel of [
1010
1016
  "src/auto-coding-skill/data/templates/ENGINEERING.md",
1011
1017
  "src/auto-coding-skill/data/templates/bridges/AGENTS.md",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@elvis1513/auto-coding-skill",
3
- "version": "4.1.3",
3
+ "version": "4.1.4",
4
4
  "description": "CLI installer for a delivery-first .agents workflow with adaptive Git isolation, routed changed-scope validation, risk-based review, push completion, and safe cleanup.",
5
5
  "type": "module",
6
6
  "bin": {