@elvis1513/auto-coding-skill 4.2.0 → 4.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,11 +2,15 @@
2
2
  from __future__ import annotations
3
3
 
4
4
  import argparse
5
+ import base64
6
+ import contextlib
7
+ import io
5
8
  import json
6
9
  import os
7
10
  import subprocess
8
11
  import sys
9
12
  import tempfile
13
+ import tomllib
10
14
  import unittest
11
15
  from pathlib import Path
12
16
  from unittest import mock
@@ -94,6 +98,25 @@ class AutoCodingProfileTests(unittest.TestCase):
94
98
  },
95
99
  }
96
100
 
101
+ @staticmethod
102
+ def reviewer_assignment(**overrides: object) -> dict:
103
+ assignment = {
104
+ "contract_version": 1,
105
+ "node_id": "reviewer-1",
106
+ "task_id": "T001",
107
+ "role": "reviewer",
108
+ "base_sha": "HEAD",
109
+ "scope": "review owned diff",
110
+ "depends_on": ["fixer-1"],
111
+ "acceptance": ["review current fingerprint"],
112
+ "diff_base": "HEAD~1",
113
+ "diff_head": "HEAD",
114
+ "diff_fingerprint": "a" * 64,
115
+ "owning_fixer": "fixer-1",
116
+ }
117
+ assignment.update(overrides)
118
+ return assignment
119
+
97
120
  def make_repo(self, change_path: str | None = None, config: dict | None = None) -> tuple[Path, dict]:
98
121
  temp = tempfile.TemporaryDirectory(prefix="autocoding-profile-")
99
122
  self.addCleanup(temp.cleanup)
@@ -361,6 +384,107 @@ class AutoCodingProfileTests(unittest.TestCase):
361
384
  self.assertIn("parallel_fixers", parallel["mechanism_plan"]["required"])
362
385
  self.assertEqual("orchestrated-subagents", parallel["agent_plan"]["strategy"])
363
386
 
387
+ def test_working_tree_snapshot_covers_clean_unstaged_staged_and_untracked_paths(self) -> None:
388
+ repo, _ = self.make_repo()
389
+ unstaged = repo / "tracked unstaged.txt"
390
+ staged = repo / "tracked-staged.txt"
391
+ unstaged.write_text("baseline\n", encoding="utf-8")
392
+ staged.write_text("baseline\n", encoding="utf-8")
393
+ run(repo, "git", "add", "tracked unstaged.txt", "tracked-staged.txt")
394
+ run(repo, "git", "commit", "-qm", "add status fixtures")
395
+
396
+ self.assertEqual([], ap._working_tree_paths(repo))
397
+
398
+ unstaged.write_text("unstaged change\n", encoding="utf-8")
399
+ staged.write_text("staged change\n", encoding="utf-8")
400
+ run(repo, "git", "add", "tracked-staged.txt")
401
+ (repo / "untracked path.txt").write_text("untracked\n", encoding="utf-8")
402
+ (repo / "untracked\nline.txt").write_text("untracked newline\n", encoding="utf-8")
403
+
404
+ self.assertEqual(
405
+ [
406
+ "tracked unstaged.txt",
407
+ "tracked-staged.txt",
408
+ "untracked\nline.txt",
409
+ "untracked path.txt",
410
+ ],
411
+ ap._working_tree_paths(repo),
412
+ )
413
+
414
+ def test_working_tree_snapshot_includes_both_staged_rename_endpoints(self) -> None:
415
+ repo, _ = self.make_repo()
416
+ source = repo / "old name.txt"
417
+ source.write_text("stable\n", encoding="utf-8")
418
+ run(repo, "git", "add", "old name.txt")
419
+ run(repo, "git", "commit", "-qm", "add rename fixture")
420
+
421
+ run(repo, "git", "mv", "old name.txt", "new name.txt")
422
+
423
+ self.assertEqual(
424
+ ["new name.txt", "old name.txt"],
425
+ ap._working_tree_paths(repo),
426
+ )
427
+
428
+ def test_working_tree_snapshot_fails_closed_on_git_error_or_malformed_output(self) -> None:
429
+ repo, _ = self.make_repo()
430
+ failed = subprocess.CompletedProcess(
431
+ args=["git", "status"],
432
+ returncode=128,
433
+ stdout="",
434
+ stderr="fatal: status unavailable",
435
+ )
436
+ with mock.patch.object(ap, "run", return_value=failed):
437
+ with self.assertRaises(APError) as context:
438
+ ap._working_tree_paths(repo)
439
+ self.assertIn("refusing a direct execution plan", str(context.exception))
440
+ self.assertIn("status unavailable", str(context.exception))
441
+
442
+ malformed = subprocess.CompletedProcess(
443
+ args=["git", "status"],
444
+ returncode=0,
445
+ stdout="1 malformed\0",
446
+ stderr="",
447
+ )
448
+ with mock.patch.object(ap, "run", return_value=malformed):
449
+ with self.assertRaises(APError) as context:
450
+ ap._working_tree_paths(repo)
451
+ self.assertIn("Cannot parse Git working tree status", str(context.exception))
452
+
453
+ def test_writer_registries_fail_closed_when_json_is_corrupt(self) -> None:
454
+ repo, cfg = self.make_repo()
455
+ task_registry = ap._task_state_root(repo) / "tasks" / "T001.json"
456
+ task_registry.parent.mkdir(parents=True, exist_ok=True)
457
+ task_registry.write_text("{broken", encoding="utf-8")
458
+ with self.assertRaises(APError) as context:
459
+ self.plan(repo, cfg, planned_paths=["src/widget.py"])
460
+ self.assertIn("Task registry is unreadable", str(context.exception))
461
+
462
+ task_registry.unlink()
463
+ claim_registry = (
464
+ ap._task_state_root(repo) / "direct-claims" / ("a" * 32 + ".json")
465
+ )
466
+ claim_registry.parent.mkdir(parents=True, exist_ok=True)
467
+ claim_registry.write_text("{broken", encoding="utf-8")
468
+ with self.assertRaises(APError) as context:
469
+ self.plan(repo, cfg, planned_paths=["src/widget.py"])
470
+ self.assertIn("Direct claim registry is unreadable", str(context.exception))
471
+
472
+ def test_same_owner_direct_claim_is_rejected_and_not_implicitly_exempted(self) -> None:
473
+ repo, cfg = self.make_repo()
474
+ claim = ap._create_direct_claim(repo, cfg, ["src/widget.py"], "same-owner")
475
+ claim_path = ap._direct_claim_path(repo, claim["claim_id"])
476
+
477
+ plan = self.plan(repo, cfg, planned_paths=["src/widget.py"])
478
+ self.assertTrue(plan["active_writer"])
479
+ self.assertEqual("isolated", plan["execution_mode"])
480
+ self.assertTrue(claim_path.exists())
481
+ self.assertEqual(claim["claim_id"], json.loads(claim_path.read_text())["claim_id"])
482
+
483
+ with self.assertRaises(APError) as context:
484
+ ap._create_direct_claim(repo, cfg, ["src/widget.py"], "same-owner")
485
+ self.assertIn(claim["claim_id"], str(context.exception))
486
+ self.assertTrue(claim_path.exists())
487
+
364
488
  def test_continue_direct_accepts_only_declared_current_task_dirt(self) -> None:
365
489
  repo, cfg = self.make_repo()
366
490
  claim = ap._create_direct_claim(
@@ -532,6 +656,243 @@ class AutoCodingProfileTests(unittest.TestCase):
532
656
  with self.assertRaises(APError):
533
657
  ap._validate_orchestration_contract("result", dict(result, diff_fingerprint=""))
534
658
 
659
+ def test_reviewer_result_template_has_complete_contract_and_verdict_mappings(self) -> None:
660
+ assignment = self.reviewer_assignment()
661
+ required_fields = {
662
+ "contract_version",
663
+ "node_id",
664
+ "role",
665
+ "task_id",
666
+ "base_sha",
667
+ "status",
668
+ "summary",
669
+ "depends_on",
670
+ "owned_paths",
671
+ "changed_paths",
672
+ "diff_fingerprint",
673
+ "evidence",
674
+ "findings",
675
+ "verdict",
676
+ "risks",
677
+ "next_owner",
678
+ }
679
+ for verdict, status, next_owner in [
680
+ ("approved", "completed", "main"),
681
+ ("changes-requested", "completed", "fixer-1"),
682
+ ("blocked", "blocked", "main"),
683
+ ]:
684
+ with self.subTest(verdict=verdict):
685
+ result = ap._reviewer_result_template(assignment, verdict)
686
+ self.assertEqual(required_fields, set(result))
687
+ self.assertEqual("reviewer", result["role"])
688
+ self.assertEqual("reviewer-1", result["node_id"])
689
+ self.assertEqual("T001", result["task_id"])
690
+ self.assertEqual("HEAD", result["base_sha"])
691
+ self.assertEqual(["fixer-1"], result["depends_on"])
692
+ self.assertEqual([], result["owned_paths"])
693
+ self.assertEqual([], result["changed_paths"])
694
+ self.assertEqual("a" * 64, result["diff_fingerprint"])
695
+ self.assertEqual(verdict, result["verdict"])
696
+ self.assertEqual(status, result["status"])
697
+ self.assertEqual(next_owner, result["next_owner"])
698
+ ap._validate_orchestration_contract("result", result)
699
+
700
+ def test_reviewer_runtime_normalizes_presentation_fields_but_binds_identity(self) -> None:
701
+ assignment = self.reviewer_assignment()
702
+ result = ap._normalize_reviewer_runtime_result(
703
+ assignment,
704
+ {
705
+ "verdict": "approved",
706
+ "summary": "focused review complete",
707
+ "evidence": ["diff inspected"],
708
+ },
709
+ )
710
+ self.assertEqual("reviewer-1", result["node_id"])
711
+ self.assertEqual("a" * 64, result["diff_fingerprint"])
712
+ self.assertEqual(["fixer-1"], result["depends_on"])
713
+ self.assertEqual("focused review complete", result["summary"])
714
+
715
+ with self.assertRaisesRegex(APError, "does not match its assignment"):
716
+ ap._normalize_reviewer_runtime_result(
717
+ assignment,
718
+ {
719
+ "verdict": "approved",
720
+ "diff_fingerprint": "b" * 64,
721
+ },
722
+ )
723
+
724
+ def test_codex_reviewer_command_is_ephemeral_read_only_and_uses_managed_instructions(self) -> None:
725
+ repo, _ = self.make_repo()
726
+ assignment_path = repo / "assignment.json"
727
+ result_path = repo / "result.json"
728
+ with mock.patch.object(ap.shutil, "which", return_value="/usr/local/bin/codex"):
729
+ command = ap._codex_reviewer_command(repo, assignment_path, result_path)
730
+
731
+ self.assertEqual("/usr/local/bin/codex", command[0])
732
+ self.assertIn("--ephemeral", command)
733
+ self.assertIn("--ignore-user-config", command)
734
+ self.assertIn("read-only", command)
735
+ self.assertIn('model_reasoning_effort="xhigh"', command)
736
+ developer_override = next(
737
+ item for item in command if item.startswith("developer_instructions=")
738
+ )
739
+ tomllib.loads(developer_override)
740
+ self.assertEqual(str(result_path), command[command.index("-o") + 1])
741
+
742
+ def test_reviewer_process_timeout_terminates_its_process_group(self) -> None:
743
+ repo, _ = self.make_repo()
744
+ process = mock.MagicMock()
745
+ process.pid = 4321
746
+ process.poll.return_value = None
747
+ process.communicate.side_effect = [
748
+ subprocess.TimeoutExpired(cmd=["fake-reviewer"], timeout=0.01),
749
+ ("partial", "stopped"),
750
+ ]
751
+ with (
752
+ mock.patch.object(ap.subprocess, "Popen", return_value=process) as popen,
753
+ mock.patch.object(ap.os, "killpg") as killpg,
754
+ ):
755
+ with self.assertRaises(ap._ReviewerRuntimeTimeout):
756
+ ap._run_supervised_reviewer_process(
757
+ ["fake-reviewer", "; touch must-not-run"],
758
+ cwd=repo,
759
+ env={"PATH": os.environ.get("PATH", "")},
760
+ timeout_seconds=0.01,
761
+ )
762
+
763
+ self.assertEqual(["fake-reviewer", "; touch must-not-run"], popen.call_args.args[0])
764
+ self.assertTrue(popen.call_args.kwargs["start_new_session"])
765
+ self.assertEqual(mock.call(4321, ap.signal.SIGTERM), killpg.call_args)
766
+
767
+ def test_reviewer_assignment_timing_contract_and_fixed_budgets(self) -> None:
768
+ issued_at = "2026-07-16T00:00:00+00:00"
769
+ assignment = self.reviewer_assignment(
770
+ review_depth="focused",
771
+ timeout_seconds=90,
772
+ issued_at=issued_at,
773
+ deadline_at="2026-07-16T00:01:30+00:00",
774
+ scope_revision=1,
775
+ )
776
+ self.assertEqual(
777
+ assignment,
778
+ ap._validate_orchestration_contract("assignment", assignment),
779
+ )
780
+ self.assertEqual(("focused", 90), ap._normalized_task_review_policy(True))
781
+ self.assertEqual(
782
+ ("deep", 300),
783
+ ap._normalized_task_review_policy(True, "focused", "deep"),
784
+ )
785
+ self.assertEqual(("none", 0), ap._normalized_task_review_policy(False, "deep"))
786
+
787
+ invalid_contracts = [
788
+ self.reviewer_assignment(
789
+ review_depth="focused",
790
+ timeout_seconds=0,
791
+ issued_at=issued_at,
792
+ deadline_at="2026-07-16T00:01:30+00:00",
793
+ ),
794
+ self.reviewer_assignment(
795
+ review_depth="focused",
796
+ timeout_seconds=90,
797
+ issued_at="2026-07-16T00:00:00",
798
+ deadline_at="2026-07-16T00:01:30",
799
+ ),
800
+ self.reviewer_assignment(
801
+ review_depth="focused",
802
+ timeout_seconds=90,
803
+ issued_at=issued_at,
804
+ deadline_at="2026-07-16T00:01:00+00:00",
805
+ ),
806
+ ]
807
+ for payload in invalid_contracts:
808
+ with self.subTest(payload=payload):
809
+ with self.assertRaises(APError):
810
+ ap._validate_orchestration_contract("assignment", payload)
811
+
812
+ def test_reviewer_result_template_rejects_wrong_role_self_review_and_empty_fingerprint(self) -> None:
813
+ invalid_assignments = [
814
+ self.reviewer_assignment(role="explorer"),
815
+ self.reviewer_assignment(node_id="fixer-1"),
816
+ self.reviewer_assignment(diff_fingerprint=""),
817
+ ]
818
+ for assignment in invalid_assignments:
819
+ with self.subTest(assignment=assignment):
820
+ with self.assertRaises(APError):
821
+ ap._reviewer_result_template(assignment, "approved")
822
+
823
+ def test_agent_result_template_command_reads_assignment_and_prints_json(self) -> None:
824
+ repo, _ = self.make_repo()
825
+ assignment_path = repo / "reviewer-assignment.json"
826
+ assignment_path.write_text(
827
+ json.dumps(self.reviewer_assignment()),
828
+ encoding="utf-8",
829
+ )
830
+ output = io.StringIO()
831
+ with contextlib.redirect_stdout(output):
832
+ ap.cmd_agent_result_template(
833
+ argparse.Namespace(
834
+ repo=str(repo),
835
+ file=str(assignment_path),
836
+ payload="",
837
+ verdict="changes-requested",
838
+ )
839
+ )
840
+
841
+ result = json.loads(output.getvalue())
842
+ self.assertEqual("reviewer", result["role"])
843
+ self.assertEqual("changes-requested", result["verdict"])
844
+ self.assertEqual("completed", result["status"])
845
+ self.assertEqual("fixer-1", result["next_owner"])
846
+ self.assertEqual(16, len(result))
847
+
848
+ def test_contract_validation_collects_missing_unexpected_type_pattern_and_conditionals(self) -> None:
849
+ result = ap._reviewer_result_template(self.reviewer_assignment(), "approved")
850
+ result.pop("next_owner")
851
+ result.update(
852
+ {
853
+ "node_id": [],
854
+ "changed_paths": ["src/unauthorized.py"],
855
+ "diff_fingerprint": "not-a-fingerprint",
856
+ "verdict": "ready-for-review",
857
+ "unexpected_field": True,
858
+ }
859
+ )
860
+
861
+ with self.assertRaises(APError) as context:
862
+ ap._validate_orchestration_contract("result", result)
863
+
864
+ message = str(context.exception)
865
+ self.assertIn("missing next_owner", message)
866
+ self.assertIn("unexpected unexpected_field", message)
867
+ self.assertIn("$.node_id: expected type", message)
868
+ self.assertIn("$.diff_fingerprint: string does not match", message)
869
+ self.assertIn("$.changed_paths: too many array items", message)
870
+ self.assertIn("$.verdict: value is outside the allowed enum", message)
871
+
872
+ def test_contract_if_branches_do_not_apply_other_role_requirements(self) -> None:
873
+ fixer_assignment = {
874
+ "contract_version": 1,
875
+ "node_id": "fixer-1",
876
+ "task_id": "T001",
877
+ "role": "fixer",
878
+ "base_sha": "HEAD",
879
+ "scope": "implement one change",
880
+ "depends_on": [],
881
+ "acceptance": ["tests pass"],
882
+ "execution_mode": "isolated",
883
+ "owned_paths": ["src/**"],
884
+ }
885
+ with self.assertRaises(APError) as context:
886
+ ap._validate_orchestration_contract("assignment", fixer_assignment)
887
+
888
+ message = str(context.exception)
889
+ self.assertIn("task_branch", message)
890
+ self.assertIn("worktree_path", message)
891
+ self.assertNotIn("diff_base", message)
892
+ self.assertNotIn("diff_head", message)
893
+ self.assertNotIn("diff_fingerprint", message)
894
+ self.assertNotIn("owning_fixer", message)
895
+
535
896
  def test_validation_routes_collect_all_commands_and_reject_unmapped_code(self) -> None:
536
897
  repo, cfg = self.make_repo()
537
898
  cfg["commands"] = {"one": "true", "two": "true"}
@@ -585,6 +946,32 @@ class AutoCodingProfileTests(unittest.TestCase):
585
946
  ap._final_gate_budget(cfg)
586
947
  self.assertIn("cannot exceed validation.max_total_seconds", str(context.exception))
587
948
 
949
+ def test_final_changed_scope_gate_runs_blocking_structure_check(self) -> None:
950
+ cfg = base_config()
951
+ cfg["structure"] = {
952
+ "enabled": True,
953
+ "enforcement": "blocking",
954
+ "max_file_lines_warn": 0,
955
+ "max_file_lines_block": 1,
956
+ "max_function_lines_warn": 0,
957
+ "layer_rules": {"enabled": False},
958
+ }
959
+ cfg["optimization"] = {"require_baseline_for_global_review": False}
960
+ repo, _ = self.make_repo("src/too-large.py", cfg)
961
+ (repo / "src" / "too-large.py").write_text("one\ntwo\n", encoding="utf-8")
962
+
963
+ with self.assertRaisesRegex(APError, "structure-check failed"):
964
+ ap.cmd_light_gate(
965
+ argparse.Namespace(
966
+ repo=str(repo),
967
+ scope="changed",
968
+ profile="",
969
+ mode="dev",
970
+ base="",
971
+ explain=False,
972
+ )
973
+ )
974
+
588
975
  def test_route_timeout_uses_smallest_matching_budget(self) -> None:
589
976
  cfg = base_config()
590
977
  cfg["commands"] = {"one": "true", "two": "true"}
@@ -638,6 +1025,44 @@ class AutoCodingProfileTests(unittest.TestCase):
638
1025
  self.assertFalse(plan["needs_jenkins"])
639
1026
  self.assertFalse(plan["needs_target"])
640
1027
 
1028
+ def test_focused_and_deep_review_policies_share_reviewer_with_bounded_attempt(self) -> None:
1029
+ cfg = base_config()
1030
+ cfg["risk"] = {
1031
+ "rules": [
1032
+ {
1033
+ "name": "focused-sensitive-change",
1034
+ "paths": ["src/sensitive/**"],
1035
+ "profile": "high-risk",
1036
+ }
1037
+ ]
1038
+ }
1039
+ repo, cfg = self.make_repo(config=cfg)
1040
+ focused = self.plan(repo, cfg, planned_paths=["src/sensitive/value.py"])
1041
+ deep = self.plan(repo, cfg, planned_paths=["backend/auth/service.py"])
1042
+
1043
+ for plan, depth, timeout in [
1044
+ (focused, "focused", 90),
1045
+ (deep, "deep", 300),
1046
+ ]:
1047
+ with self.subTest(depth=depth):
1048
+ self.assertTrue(plan["review_required"])
1049
+ self.assertEqual(depth, plan["review_depth"])
1050
+ self.assertEqual("reviewer", plan["review_agent"])
1051
+ self.assertEqual(timeout, plan["review_timeout_seconds"])
1052
+ self.assertEqual(1, plan["review_analysis_attempt_limit"])
1053
+ self.assertEqual("reviewer", plan["agent_plan"]["policies"]["review_agent"])
1054
+ self.assertEqual(
1055
+ timeout,
1056
+ plan["agent_plan"]["policies"]["review_timeout_seconds"],
1057
+ )
1058
+ self.assertEqual(
1059
+ 1,
1060
+ plan["agent_plan"]["policies"]["review_analysis_attempt_limit"],
1061
+ )
1062
+ constraints = " ".join(plan["agent_plan"]["constraints"]).lower()
1063
+ self.assertIn("timeout is blocked", constraints)
1064
+ self.assertIn("reuse the same analysis", constraints)
1065
+
641
1066
  def test_ui_api_reports_capabilities_without_auto_dispatch(self) -> None:
642
1067
  repo, cfg = self.make_repo("src/api/settings-page.tsx")
643
1068
  plan = self.plan(repo, cfg)
@@ -646,6 +1071,148 @@ class AutoCodingProfileTests(unittest.TestCase):
646
1071
  self.assertEqual("main-only", plan["agent_plan"]["strategy"])
647
1072
  self.assertEqual(["main"], plan["agent_plan"]["stages"][0]["roles"])
648
1073
 
1074
+ def test_ui_classification_uses_segments_and_extensions_not_substrings(self) -> None:
1075
+ for path in [
1076
+ ".env.components",
1077
+ "docker-compose.components.yml",
1078
+ "config/component-overrides.yml",
1079
+ "backend/component_service.go",
1080
+ ]:
1081
+ with self.subTest(path=path):
1082
+ self.assertNotIn("ui", ap._classify_paths([path])["categories"])
1083
+
1084
+ for path in [
1085
+ "frontend/src/app.ts",
1086
+ "src/components/Button.ts",
1087
+ "src/views/Home.js",
1088
+ "src/Button.tsx",
1089
+ "miniapp/pages/home/index.ts",
1090
+ ]:
1091
+ with self.subTest(path=path):
1092
+ self.assertIn("ui", ap._classify_paths([path])["categories"])
1093
+
1094
+ repo, cfg = self.make_repo()
1095
+ plan = self.plan(repo, cfg, planned_paths=[".env.components"])
1096
+ self.assertFalse(plan["needs_browser"])
1097
+
1098
+ def test_exact_cross_module_high_risk_rename_is_mechanical_but_reviewed(self) -> None:
1099
+ repo, cfg = self.make_repo()
1100
+ source = repo / "backend" / "auth" / "policy.py"
1101
+ source.parent.mkdir(parents=True)
1102
+ source.write_text("POLICY = 'stable'\n", encoding="utf-8")
1103
+ run(repo, "git", "add", str(source.relative_to(repo)))
1104
+ run(repo, "git", "commit", "-qm", "add auth policy")
1105
+ destination = repo / "account" / "auth" / "policy.py"
1106
+ destination.parent.mkdir(parents=True)
1107
+ run(repo, "git", "mv", str(source.relative_to(repo)), str(destination.relative_to(repo)))
1108
+
1109
+ plan = self.plan(repo, cfg)
1110
+
1111
+ self.assertEqual(
1112
+ ["account/auth/policy.py", "backend/auth/policy.py"],
1113
+ plan["changed_files"],
1114
+ )
1115
+ self.assertTrue(plan["cross_module"])
1116
+ self.assertEqual("high-risk", plan["profile"])
1117
+ self.assertEqual("mechanical", plan["change_nature"])
1118
+ self.assertTrue(plan["review_required"])
1119
+ self.assertFalse(plan["design_required"])
1120
+
1121
+ extra = repo / "account" / "auth" / "new_policy.py"
1122
+ extra.write_text("POLICY = 'new'\n", encoding="utf-8")
1123
+ mixed = self.plan(repo, cfg)
1124
+ self.assertEqual("unknown", mixed["change_nature"])
1125
+ self.assertTrue(mixed["design_required"])
1126
+
1127
+ def test_semantic_or_unknown_cross_module_high_risk_change_keeps_design(self) -> None:
1128
+ repo, cfg = self.make_repo()
1129
+ source = repo / "backend" / "auth" / "policy.py"
1130
+ source.parent.mkdir(parents=True)
1131
+ source.write_text("POLICY = 'stable'\n", encoding="utf-8")
1132
+ run(repo, "git", "add", str(source.relative_to(repo)))
1133
+ run(repo, "git", "commit", "-qm", "add auth policy")
1134
+ destination = repo / "account" / "auth" / "policy.py"
1135
+ destination.parent.mkdir(parents=True)
1136
+ run(repo, "git", "mv", str(source.relative_to(repo)), str(destination.relative_to(repo)))
1137
+ destination.write_text("POLICY = 'changed'\n", encoding="utf-8")
1138
+
1139
+ semantic = self.plan(repo, cfg, intent="改变鉴权策略行为和模块职责")
1140
+ self.assertEqual("semantic", semantic["change_nature"])
1141
+ self.assertTrue(semantic["review_required"])
1142
+ self.assertTrue(semantic["design_required"])
1143
+
1144
+ clean_repo, clean_cfg = self.make_repo()
1145
+ unknown = self.plan(
1146
+ clean_repo,
1147
+ clean_cfg,
1148
+ planned_paths=["backend/auth/policy.py", "account/auth/policy.py"],
1149
+ )
1150
+ self.assertEqual("unknown", unknown["change_nature"])
1151
+ self.assertTrue(unknown["review_required"])
1152
+ self.assertTrue(unknown["design_required"])
1153
+
1154
+ def test_failed_git_rename_probe_stays_conservative(self) -> None:
1155
+ repo, _ = self.make_repo()
1156
+ failed = subprocess.CompletedProcess(
1157
+ args=["git", "diff"],
1158
+ returncode=128,
1159
+ stdout="",
1160
+ stderr="fatal: diff unavailable",
1161
+ )
1162
+ with (
1163
+ mock.patch.object(ap, "_effective_change_base", return_value=""),
1164
+ mock.patch.object(ap, "run", return_value=failed),
1165
+ ):
1166
+ self.assertFalse(
1167
+ ap._pure_exact_git_rename(
1168
+ repo,
1169
+ "",
1170
+ ["backend/auth/policy.py", "account/auth/policy.py"],
1171
+ )
1172
+ )
1173
+
1174
+ def test_explicit_design_rule_wins_over_mechanical_change(self) -> None:
1175
+ cfg = base_config()
1176
+ cfg["risk"] = {
1177
+ "rules": [
1178
+ {
1179
+ "name": "auth-design",
1180
+ "paths": ["**/auth/**"],
1181
+ "profile": "high-risk",
1182
+ "design": "required",
1183
+ }
1184
+ ]
1185
+ }
1186
+ repo, cfg = self.make_repo(config=cfg)
1187
+ plan = self.plan(
1188
+ repo,
1189
+ cfg,
1190
+ planned_paths=["backend/auth/policy.py", "account/auth/policy.py"],
1191
+ intent="机械同步,不改变行为",
1192
+ )
1193
+ self.assertEqual("mechanical", plan["change_nature"])
1194
+ self.assertTrue(plan["review_required"])
1195
+ self.assertTrue(plan["design_required"])
1196
+
1197
+ def test_semantic_or_negated_intent_overrides_mechanical_words(self) -> None:
1198
+ repo, cfg = self.make_repo()
1199
+ paths = ["backend/auth/policy.py", "account/auth/policy.py"]
1200
+ for intent in [
1201
+ "mechanical sync that changes behavior",
1202
+ "rename only while changing the API contract",
1203
+ "机械同步但修改鉴权契约",
1204
+ ]:
1205
+ with self.subTest(intent=intent):
1206
+ plan = self.plan(repo, cfg, planned_paths=paths, intent=intent)
1207
+ self.assertEqual("semantic", plan["change_nature"])
1208
+ self.assertTrue(plan["design_required"])
1209
+
1210
+ for intent in ["not mechanical", "不是机械变更"]:
1211
+ with self.subTest(intent=intent):
1212
+ plan = self.plan(repo, cfg, planned_paths=paths, intent=intent)
1213
+ self.assertEqual("unknown", plan["change_nature"])
1214
+ self.assertTrue(plan["design_required"])
1215
+
649
1216
  def test_terminal_ledger_maintenance_creates_no_lifecycle_plan(self) -> None:
650
1217
  repo, cfg = self.make_repo()
651
1218
  plan = self.plan(repo, cfg, planned_paths=["docs/tasks/closure-log.md"])
@@ -757,6 +1324,37 @@ class AutoCodingProfileTests(unittest.TestCase):
757
1324
  self.assertNotIn("light-gate", rendered)
758
1325
  self.assertNotIn("structure-check", rendered)
759
1326
 
1327
+ def test_classify_text_output_exposes_workspace_and_writer_snapshot(self) -> None:
1328
+ repo, _ = self.make_repo("path with spaces.txt")
1329
+ output = io.StringIO()
1330
+ args = argparse.Namespace(
1331
+ repo=str(repo),
1332
+ scope="auto",
1333
+ profile="",
1334
+ mode="dev",
1335
+ base="",
1336
+ planned_path=[],
1337
+ intent="",
1338
+ intent_file="",
1339
+ task_kind="auto",
1340
+ claim_direct=False,
1341
+ claim_owner="",
1342
+ continue_direct=False,
1343
+ direct_claim="",
1344
+ writers=1,
1345
+ json=False,
1346
+ )
1347
+ with mock.patch.object(ap, "_record_evidence"):
1348
+ with contextlib.redirect_stdout(output):
1349
+ ap.cmd_classify(args)
1350
+
1351
+ rendered = output.getvalue()
1352
+ self.assertIn(f"[classify] repo={repo.resolve()}", rendered)
1353
+ self.assertIn("[classify] workspace_dirty=true", rendered)
1354
+ self.assertIn('[classify] dirty_paths=["path with spaces.txt"]', rendered)
1355
+ self.assertIn("[classify] active_writer=false", rendered)
1356
+ self.assertIn("[classify] review_analysis_attempt_limit=0", rendered)
1357
+
760
1358
  def test_custom_full_on_path_does_not_expand_local_gate(self) -> None:
761
1359
  cfg = base_config()
762
1360
  cfg["gate"]["full_on"] = {"paths": ["src/sensitive/**"]}
@@ -798,6 +1396,30 @@ class AutoCodingProfileTests(unittest.TestCase):
798
1396
  with self.assertRaises(APError):
799
1397
  ap.cmd_structure_check(args)
800
1398
 
1399
+ def test_structure_scan_excludes_non_authoritative_agent_history_and_metadata(self) -> None:
1400
+ repo, _ = self.make_repo()
1401
+ files = {
1402
+ ".agents/archive/old.py": "old = True\n",
1403
+ ".agents/agents/custom.toml": "model = 'test'\n",
1404
+ ".agents/managed-install.json": "{}\n",
1405
+ ".agents/custom/check.py": "active = True\n",
1406
+ "src/app.py": "active = True\n",
1407
+ }
1408
+ for relative, content in files.items():
1409
+ target = repo / relative
1410
+ target.parent.mkdir(parents=True, exist_ok=True)
1411
+ target.write_text(content, encoding="utf-8")
1412
+ run(repo, "git", "add", "-A")
1413
+ run(repo, "git", "commit", "-qm", "add structure fixtures")
1414
+
1415
+ candidates = ap._structure_paths_for_scope(repo, "full", "", {})
1416
+
1417
+ self.assertIn(".agents/custom/check.py", candidates)
1418
+ self.assertIn("src/app.py", candidates)
1419
+ self.assertNotIn(".agents/archive/old.py", candidates)
1420
+ self.assertNotIn(".agents/agents/custom.toml", candidates)
1421
+ self.assertNotIn(".agents/managed-install.json", candidates)
1422
+
801
1423
  def test_doctor_validates_profile_values(self) -> None:
802
1424
  cfg = base_config()
803
1425
  cfg["workflow"]["profile"] = "extreme"
@@ -969,6 +1591,231 @@ class AutoCodingProfileTests(unittest.TestCase):
969
1591
  ap.cmd_doctor(argparse.Namespace(repo=str(repo)))
970
1592
  ap.cmd_verify_api_docs(argparse.Namespace(repo=str(repo)))
971
1593
 
1594
+ def test_root_and_nested_package_json_are_high_risk_and_require_review(self) -> None:
1595
+ repo, cfg = self.make_repo()
1596
+ for path in ["package.json", "frontend/admin/package.json"]:
1597
+ with self.subTest(path=path):
1598
+ plan = self.plan(
1599
+ repo,
1600
+ cfg,
1601
+ planned_paths=[path],
1602
+ requested_task_kind="change",
1603
+ )
1604
+ self.assertEqual("high-risk", plan["profile"])
1605
+ self.assertTrue(plan["review_required"])
1606
+ self.assertIn("release_or_tooling", plan["categories"])
1607
+
1608
+ def test_explicit_full_structure_scope_inspects_clean_tracked_files(self) -> None:
1609
+ cfg = base_config()
1610
+ cfg["structure"] = {
1611
+ "enabled": True,
1612
+ "enforcement": "advisory",
1613
+ "max_file_lines_warn": 0,
1614
+ "max_file_lines_block": 0,
1615
+ "max_function_lines_warn": 0,
1616
+ "layer_rules": {"enabled": False},
1617
+ }
1618
+ cfg["optimization"] = {"require_baseline_for_global_review": False}
1619
+ repo, _ = self.make_repo("src/app.py", cfg)
1620
+ run(repo, "git", "add", "-A")
1621
+ run(repo, "git", "commit", "-qm", "add tracked structure fixture")
1622
+
1623
+ output = io.StringIO()
1624
+ with mock.patch.object(ap, "_record_evidence"), contextlib.redirect_stdout(output):
1625
+ ap.cmd_structure_check(
1626
+ argparse.Namespace(repo=str(repo), scope="full", base="", json=True)
1627
+ )
1628
+
1629
+ result = json.loads(output.getvalue())
1630
+ self.assertEqual("full", result["scope"])
1631
+ self.assertGreaterEqual(result["inspected_files"], 1)
1632
+
1633
+ def test_verify_jenkins_accepts_access_schema_and_uses_selected_identity(self) -> None:
1634
+ repo, cfg = self.make_repo()
1635
+ (repo / "Jenkinsfile").write_text("pipeline {}\n", encoding="utf-8")
1636
+
1637
+ with mock.patch.object(ap, "_record_evidence"):
1638
+ ap.cmd_verify_jenkins(argparse.Namespace(repo=str(repo), component="all"))
1639
+
1640
+ header = ap._jenkins_basic_auth_headers(cfg, component="backend")["Authorization"]
1641
+ decoded = base64.b64decode(header.removeprefix("Basic ")).decode("utf-8")
1642
+ self.assertEqual("back:back-pass", decoded)
1643
+
1644
+ def test_jenkins_component_is_ambiguous_with_two_access_endpoints(self) -> None:
1645
+ cfg = base_config()
1646
+ with self.assertRaisesRegex(APError, "Multiple access.jenkins endpoints"):
1647
+ ap._resolve_jenkins_component(cfg)
1648
+
1649
+ cfg["access"]["jenkins"]["backend"] = dict(cfg["access"]["jenkins"]["frontend"])
1650
+ self.assertEqual("frontend", ap._resolve_jenkins_component(cfg))
1651
+
1652
+ def test_verify_jenkins_build_uses_one_selected_access_component(self) -> None:
1653
+ repo, _ = self.make_repo()
1654
+ args = argparse.Namespace(
1655
+ repo=str(repo),
1656
+ component="backend",
1657
+ git_ref="HEAD",
1658
+ job_name=None,
1659
+ job_url=None,
1660
+ multibranch_root_job=None,
1661
+ branch_name=None,
1662
+ build_number=7,
1663
+ max_builds=20,
1664
+ timeout_sec=1,
1665
+ poll_sec=1,
1666
+ allow_no_deploy=True,
1667
+ )
1668
+ payload = {
1669
+ "number": 7,
1670
+ "result": "SUCCESS",
1671
+ "building": False,
1672
+ "description": "deployed",
1673
+ "url": "https://jenkins-back.test/7/",
1674
+ }
1675
+ with (
1676
+ mock.patch.object(ap, "_jenkins_api_get_json", return_value=payload) as api_get,
1677
+ mock.patch.object(ap, "_record_evidence"),
1678
+ ):
1679
+ ap.cmd_verify_jenkins_build(args)
1680
+
1681
+ self.assertEqual("backend", api_get.call_args.kwargs["component"])
1682
+ self.assertIn("https://jenkins-back.test/7/api/json", api_get.call_args.args[0])
1683
+
1684
+ def test_verify_jenkins_preserves_legacy_configuration(self) -> None:
1685
+ cfg = base_config()
1686
+ cfg["access"]["jenkins"] = {}
1687
+ cfg["jenkins"] = {
1688
+ "base_url": "https://legacy-jenkins.test",
1689
+ "job_url": "https://legacy-jenkins.test/job/backend",
1690
+ "trigger_branch": "dev",
1691
+ "image_repository": "registry.test/project/backend",
1692
+ "image_tag_strategy": "commit",
1693
+ "deploy_env": "production",
1694
+ "api_user": "legacy-user",
1695
+ "api_password": "legacy-pass",
1696
+ }
1697
+ cfg["target_env"] = {
1698
+ "health_base_url": "https://legacy-target.test",
1699
+ "health_path": "/healthz",
1700
+ }
1701
+ repo, _ = self.make_repo(config=cfg)
1702
+ (repo / "Jenkinsfile").write_text("pipeline {}\n", encoding="utf-8")
1703
+
1704
+ with mock.patch.object(ap, "_record_evidence"):
1705
+ ap.cmd_verify_jenkins(argparse.Namespace(repo=str(repo), component="all"))
1706
+
1707
+ self.assertEqual("", ap._resolve_jenkins_component(cfg))
1708
+ header = ap._jenkins_basic_auth_headers(cfg)["Authorization"]
1709
+ decoded = base64.b64decode(header.removeprefix("Basic ")).decode("utf-8")
1710
+ self.assertEqual("legacy-user:legacy-pass", decoded)
1711
+
1712
+ def test_jenkins_crumb_cache_is_scoped_by_identity(self) -> None:
1713
+ cfg = base_config()
1714
+ cfg["access"]["jenkins"]["frontend"].update(
1715
+ {"url": "https://jenkins.test/job/frontend", "username": "front-user"}
1716
+ )
1717
+ cfg["access"]["jenkins"]["backend"].update(
1718
+ {"url": "https://jenkins.test/job/backend", "username": "back-user"}
1719
+ )
1720
+
1721
+ def response(crumb: str) -> mock.MagicMock:
1722
+ value = mock.MagicMock()
1723
+ value.__enter__.return_value.read.return_value = json.dumps(
1724
+ {"crumbRequestField": "Jenkins-Crumb", "crumb": crumb}
1725
+ ).encode("utf-8")
1726
+ return value
1727
+
1728
+ ap._JENKINS_CRUMB_CACHE.clear()
1729
+ self.addCleanup(ap._JENKINS_CRUMB_CACHE.clear)
1730
+ with mock.patch.object(
1731
+ ap.urllib.request,
1732
+ "urlopen",
1733
+ side_effect=[response("crumb-front"), response("crumb-back")],
1734
+ ) as urlopen:
1735
+ frontend = ap._jenkins_crumb_headers(cfg, component="frontend")
1736
+ backend = ap._jenkins_crumb_headers(cfg, component="backend")
1737
+
1738
+ self.assertEqual({"Jenkins-Crumb": "crumb-front"}, frontend)
1739
+ self.assertEqual({"Jenkins-Crumb": "crumb-back"}, backend)
1740
+ self.assertEqual(2, urlopen.call_count)
1741
+ self.assertEqual(2, len(ap._JENKINS_CRUMB_CACHE))
1742
+
1743
+ def test_verify_target_uses_access_project_urls_without_legacy_wait(self) -> None:
1744
+ repo, _ = self.make_repo()
1745
+ args = argparse.Namespace(
1746
+ repo=str(repo),
1747
+ backend_path=["/healthz"],
1748
+ frontend_path=["/"],
1749
+ backend_basic_auth=False,
1750
+ frontend_basic_auth=False,
1751
+ )
1752
+ with (
1753
+ mock.patch.object(ap, "_http_get", return_value=(200, "ok")) as http_get,
1754
+ mock.patch.object(ap, "_wait_for_health_url") as wait_health,
1755
+ mock.patch.object(ap, "_record_evidence"),
1756
+ ):
1757
+ ap.cmd_verify_target(args)
1758
+
1759
+ self.assertEqual(
1760
+ ["https://project-back.test/healthz", "https://project-front.test/"],
1761
+ [call.args[0] for call in http_get.call_args_list],
1762
+ )
1763
+ wait_health.assert_not_called()
1764
+
1765
+ def test_verify_target_missing_access_url_fails_before_network(self) -> None:
1766
+ cfg = base_config()
1767
+ cfg["access"]["project"]["backend"]["url"] = ""
1768
+ repo, _ = self.make_repo(config=cfg)
1769
+ args = argparse.Namespace(
1770
+ repo=str(repo),
1771
+ backend_path=["/healthz"],
1772
+ frontend_path=None,
1773
+ backend_basic_auth=False,
1774
+ frontend_basic_auth=False,
1775
+ )
1776
+ with (
1777
+ mock.patch.object(ap, "_http_get") as http_get,
1778
+ mock.patch.object(ap, "http_get_status") as get_status,
1779
+ mock.patch.object(ap.time, "sleep") as sleep,
1780
+ ):
1781
+ with self.assertRaisesRegex(APError, "access.project.backend.url"):
1782
+ ap.cmd_verify_target(args)
1783
+
1784
+ http_get.assert_not_called()
1785
+ get_status.assert_not_called()
1786
+ sleep.assert_not_called()
1787
+
1788
+ def test_verify_target_preserves_legacy_endpoint_and_health_preflight(self) -> None:
1789
+ cfg = base_config()
1790
+ cfg["access"]["project"] = {}
1791
+ cfg["jenkins"] = {"deploy_timeout_sec": 7}
1792
+ cfg["target_env"] = {
1793
+ "backend_base_url": "https://legacy-target.test/api",
1794
+ "backend_username": "legacy-user",
1795
+ "backend_password": "legacy-pass",
1796
+ "health_base_url": "https://legacy-target.test",
1797
+ "health_path": "/healthz",
1798
+ }
1799
+ repo, _ = self.make_repo(config=cfg)
1800
+ args = argparse.Namespace(
1801
+ repo=str(repo),
1802
+ backend_path=["/ready"],
1803
+ frontend_path=None,
1804
+ backend_basic_auth=False,
1805
+ frontend_basic_auth=False,
1806
+ )
1807
+ with (
1808
+ mock.patch.object(ap, "_wait_for_health_url") as wait_health,
1809
+ mock.patch.object(ap, "_http_get", return_value=(200, "ok")) as http_get,
1810
+ mock.patch.object(ap, "_record_evidence"),
1811
+ ):
1812
+ ap.cmd_verify_target(args)
1813
+
1814
+ wait_health.assert_called_once_with(
1815
+ "target", "https://legacy-target.test/healthz", 7
1816
+ )
1817
+ self.assertEqual("https://legacy-target.test/api/ready", http_get.call_args.args[0])
1818
+
972
1819
  def test_dev_closure_rejects_owner_acceptance_pass(self) -> None:
973
1820
  with self.assertRaises(APError):
974
1821
  ap._validate_closure_result("dev", "PASS")