@elvis1513/auto-coding-skill 4.1.9 → 4.2.1

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,6 +2,8 @@
2
2
  from __future__ import annotations
3
3
 
4
4
  import argparse
5
+ import contextlib
6
+ import io
5
7
  import json
6
8
  import os
7
9
  import subprocess
@@ -94,6 +96,25 @@ class AutoCodingProfileTests(unittest.TestCase):
94
96
  },
95
97
  }
96
98
 
99
+ @staticmethod
100
+ def reviewer_assignment(**overrides: object) -> dict:
101
+ assignment = {
102
+ "contract_version": 1,
103
+ "node_id": "reviewer-1",
104
+ "task_id": "T001",
105
+ "role": "reviewer",
106
+ "base_sha": "HEAD",
107
+ "scope": "review owned diff",
108
+ "depends_on": ["fixer-1"],
109
+ "acceptance": ["review current fingerprint"],
110
+ "diff_base": "HEAD~1",
111
+ "diff_head": "HEAD",
112
+ "diff_fingerprint": "a" * 64,
113
+ "owning_fixer": "fixer-1",
114
+ }
115
+ assignment.update(overrides)
116
+ return assignment
117
+
97
118
  def make_repo(self, change_path: str | None = None, config: dict | None = None) -> tuple[Path, dict]:
98
119
  temp = tempfile.TemporaryDirectory(prefix="autocoding-profile-")
99
120
  self.addCleanup(temp.cleanup)
@@ -361,6 +382,107 @@ class AutoCodingProfileTests(unittest.TestCase):
361
382
  self.assertIn("parallel_fixers", parallel["mechanism_plan"]["required"])
362
383
  self.assertEqual("orchestrated-subagents", parallel["agent_plan"]["strategy"])
363
384
 
385
+ def test_working_tree_snapshot_covers_clean_unstaged_staged_and_untracked_paths(self) -> None:
386
+ repo, _ = self.make_repo()
387
+ unstaged = repo / "tracked unstaged.txt"
388
+ staged = repo / "tracked-staged.txt"
389
+ unstaged.write_text("baseline\n", encoding="utf-8")
390
+ staged.write_text("baseline\n", encoding="utf-8")
391
+ run(repo, "git", "add", "tracked unstaged.txt", "tracked-staged.txt")
392
+ run(repo, "git", "commit", "-qm", "add status fixtures")
393
+
394
+ self.assertEqual([], ap._working_tree_paths(repo))
395
+
396
+ unstaged.write_text("unstaged change\n", encoding="utf-8")
397
+ staged.write_text("staged change\n", encoding="utf-8")
398
+ run(repo, "git", "add", "tracked-staged.txt")
399
+ (repo / "untracked path.txt").write_text("untracked\n", encoding="utf-8")
400
+ (repo / "untracked\nline.txt").write_text("untracked newline\n", encoding="utf-8")
401
+
402
+ self.assertEqual(
403
+ [
404
+ "tracked unstaged.txt",
405
+ "tracked-staged.txt",
406
+ "untracked\nline.txt",
407
+ "untracked path.txt",
408
+ ],
409
+ ap._working_tree_paths(repo),
410
+ )
411
+
412
+ def test_working_tree_snapshot_includes_both_staged_rename_endpoints(self) -> None:
413
+ repo, _ = self.make_repo()
414
+ source = repo / "old name.txt"
415
+ source.write_text("stable\n", encoding="utf-8")
416
+ run(repo, "git", "add", "old name.txt")
417
+ run(repo, "git", "commit", "-qm", "add rename fixture")
418
+
419
+ run(repo, "git", "mv", "old name.txt", "new name.txt")
420
+
421
+ self.assertEqual(
422
+ ["new name.txt", "old name.txt"],
423
+ ap._working_tree_paths(repo),
424
+ )
425
+
426
+ def test_working_tree_snapshot_fails_closed_on_git_error_or_malformed_output(self) -> None:
427
+ repo, _ = self.make_repo()
428
+ failed = subprocess.CompletedProcess(
429
+ args=["git", "status"],
430
+ returncode=128,
431
+ stdout="",
432
+ stderr="fatal: status unavailable",
433
+ )
434
+ with mock.patch.object(ap, "run", return_value=failed):
435
+ with self.assertRaises(APError) as context:
436
+ ap._working_tree_paths(repo)
437
+ self.assertIn("refusing a direct execution plan", str(context.exception))
438
+ self.assertIn("status unavailable", str(context.exception))
439
+
440
+ malformed = subprocess.CompletedProcess(
441
+ args=["git", "status"],
442
+ returncode=0,
443
+ stdout="1 malformed\0",
444
+ stderr="",
445
+ )
446
+ with mock.patch.object(ap, "run", return_value=malformed):
447
+ with self.assertRaises(APError) as context:
448
+ ap._working_tree_paths(repo)
449
+ self.assertIn("Cannot parse Git working tree status", str(context.exception))
450
+
451
+ def test_writer_registries_fail_closed_when_json_is_corrupt(self) -> None:
452
+ repo, cfg = self.make_repo()
453
+ task_registry = ap._task_state_root(repo) / "tasks" / "T001.json"
454
+ task_registry.parent.mkdir(parents=True, exist_ok=True)
455
+ task_registry.write_text("{broken", encoding="utf-8")
456
+ with self.assertRaises(APError) as context:
457
+ self.plan(repo, cfg, planned_paths=["src/widget.py"])
458
+ self.assertIn("Task registry is unreadable", str(context.exception))
459
+
460
+ task_registry.unlink()
461
+ claim_registry = (
462
+ ap._task_state_root(repo) / "direct-claims" / ("a" * 32 + ".json")
463
+ )
464
+ claim_registry.parent.mkdir(parents=True, exist_ok=True)
465
+ claim_registry.write_text("{broken", encoding="utf-8")
466
+ with self.assertRaises(APError) as context:
467
+ self.plan(repo, cfg, planned_paths=["src/widget.py"])
468
+ self.assertIn("Direct claim registry is unreadable", str(context.exception))
469
+
470
+ def test_same_owner_direct_claim_is_rejected_and_not_implicitly_exempted(self) -> None:
471
+ repo, cfg = self.make_repo()
472
+ claim = ap._create_direct_claim(repo, cfg, ["src/widget.py"], "same-owner")
473
+ claim_path = ap._direct_claim_path(repo, claim["claim_id"])
474
+
475
+ plan = self.plan(repo, cfg, planned_paths=["src/widget.py"])
476
+ self.assertTrue(plan["active_writer"])
477
+ self.assertEqual("isolated", plan["execution_mode"])
478
+ self.assertTrue(claim_path.exists())
479
+ self.assertEqual(claim["claim_id"], json.loads(claim_path.read_text())["claim_id"])
480
+
481
+ with self.assertRaises(APError) as context:
482
+ ap._create_direct_claim(repo, cfg, ["src/widget.py"], "same-owner")
483
+ self.assertIn(claim["claim_id"], str(context.exception))
484
+ self.assertTrue(claim_path.exists())
485
+
364
486
  def test_continue_direct_accepts_only_declared_current_task_dirt(self) -> None:
365
487
  repo, cfg = self.make_repo()
366
488
  claim = ap._create_direct_claim(
@@ -532,6 +654,131 @@ class AutoCodingProfileTests(unittest.TestCase):
532
654
  with self.assertRaises(APError):
533
655
  ap._validate_orchestration_contract("result", dict(result, diff_fingerprint=""))
534
656
 
657
+ def test_reviewer_result_template_has_complete_contract_and_verdict_mappings(self) -> None:
658
+ assignment = self.reviewer_assignment()
659
+ required_fields = {
660
+ "contract_version",
661
+ "node_id",
662
+ "role",
663
+ "task_id",
664
+ "base_sha",
665
+ "status",
666
+ "summary",
667
+ "depends_on",
668
+ "owned_paths",
669
+ "changed_paths",
670
+ "diff_fingerprint",
671
+ "evidence",
672
+ "findings",
673
+ "verdict",
674
+ "risks",
675
+ "next_owner",
676
+ }
677
+ for verdict, status, next_owner in [
678
+ ("approved", "completed", "main"),
679
+ ("changes-requested", "completed", "fixer-1"),
680
+ ("blocked", "blocked", "main"),
681
+ ]:
682
+ with self.subTest(verdict=verdict):
683
+ result = ap._reviewer_result_template(assignment, verdict)
684
+ self.assertEqual(required_fields, set(result))
685
+ self.assertEqual("reviewer", result["role"])
686
+ self.assertEqual("reviewer-1", result["node_id"])
687
+ self.assertEqual("T001", result["task_id"])
688
+ self.assertEqual("HEAD", result["base_sha"])
689
+ self.assertEqual(["fixer-1"], result["depends_on"])
690
+ self.assertEqual([], result["owned_paths"])
691
+ self.assertEqual([], result["changed_paths"])
692
+ self.assertEqual("a" * 64, result["diff_fingerprint"])
693
+ self.assertEqual(verdict, result["verdict"])
694
+ self.assertEqual(status, result["status"])
695
+ self.assertEqual(next_owner, result["next_owner"])
696
+ ap._validate_orchestration_contract("result", result)
697
+
698
+ def test_reviewer_result_template_rejects_wrong_role_self_review_and_empty_fingerprint(self) -> None:
699
+ invalid_assignments = [
700
+ self.reviewer_assignment(role="explorer"),
701
+ self.reviewer_assignment(node_id="fixer-1"),
702
+ self.reviewer_assignment(diff_fingerprint=""),
703
+ ]
704
+ for assignment in invalid_assignments:
705
+ with self.subTest(assignment=assignment):
706
+ with self.assertRaises(APError):
707
+ ap._reviewer_result_template(assignment, "approved")
708
+
709
+ def test_agent_result_template_command_reads_assignment_and_prints_json(self) -> None:
710
+ repo, _ = self.make_repo()
711
+ assignment_path = repo / "reviewer-assignment.json"
712
+ assignment_path.write_text(
713
+ json.dumps(self.reviewer_assignment()),
714
+ encoding="utf-8",
715
+ )
716
+ output = io.StringIO()
717
+ with contextlib.redirect_stdout(output):
718
+ ap.cmd_agent_result_template(
719
+ argparse.Namespace(
720
+ repo=str(repo),
721
+ file=str(assignment_path),
722
+ payload="",
723
+ verdict="changes-requested",
724
+ )
725
+ )
726
+
727
+ result = json.loads(output.getvalue())
728
+ self.assertEqual("reviewer", result["role"])
729
+ self.assertEqual("changes-requested", result["verdict"])
730
+ self.assertEqual("completed", result["status"])
731
+ self.assertEqual("fixer-1", result["next_owner"])
732
+ self.assertEqual(16, len(result))
733
+
734
+ def test_contract_validation_collects_missing_unexpected_type_pattern_and_conditionals(self) -> None:
735
+ result = ap._reviewer_result_template(self.reviewer_assignment(), "approved")
736
+ result.pop("next_owner")
737
+ result.update(
738
+ {
739
+ "node_id": [],
740
+ "changed_paths": ["src/unauthorized.py"],
741
+ "diff_fingerprint": "not-a-fingerprint",
742
+ "verdict": "ready-for-review",
743
+ "unexpected_field": True,
744
+ }
745
+ )
746
+
747
+ with self.assertRaises(APError) as context:
748
+ ap._validate_orchestration_contract("result", result)
749
+
750
+ message = str(context.exception)
751
+ self.assertIn("missing next_owner", message)
752
+ self.assertIn("unexpected unexpected_field", message)
753
+ self.assertIn("$.node_id: expected type", message)
754
+ self.assertIn("$.diff_fingerprint: string does not match", message)
755
+ self.assertIn("$.changed_paths: too many array items", message)
756
+ self.assertIn("$.verdict: value is outside the allowed enum", message)
757
+
758
+ def test_contract_if_branches_do_not_apply_other_role_requirements(self) -> None:
759
+ fixer_assignment = {
760
+ "contract_version": 1,
761
+ "node_id": "fixer-1",
762
+ "task_id": "T001",
763
+ "role": "fixer",
764
+ "base_sha": "HEAD",
765
+ "scope": "implement one change",
766
+ "depends_on": [],
767
+ "acceptance": ["tests pass"],
768
+ "execution_mode": "isolated",
769
+ "owned_paths": ["src/**"],
770
+ }
771
+ with self.assertRaises(APError) as context:
772
+ ap._validate_orchestration_contract("assignment", fixer_assignment)
773
+
774
+ message = str(context.exception)
775
+ self.assertIn("task_branch", message)
776
+ self.assertIn("worktree_path", message)
777
+ self.assertNotIn("diff_base", message)
778
+ self.assertNotIn("diff_head", message)
779
+ self.assertNotIn("diff_fingerprint", message)
780
+ self.assertNotIn("owning_fixer", message)
781
+
535
782
  def test_validation_routes_collect_all_commands_and_reject_unmapped_code(self) -> None:
536
783
  repo, cfg = self.make_repo()
537
784
  cfg["commands"] = {"one": "true", "two": "true"}
@@ -638,6 +885,44 @@ class AutoCodingProfileTests(unittest.TestCase):
638
885
  self.assertFalse(plan["needs_jenkins"])
639
886
  self.assertFalse(plan["needs_target"])
640
887
 
888
+ def test_focused_and_deep_review_policies_share_reviewer_with_bounded_attempt(self) -> None:
889
+ cfg = base_config()
890
+ cfg["risk"] = {
891
+ "rules": [
892
+ {
893
+ "name": "focused-sensitive-change",
894
+ "paths": ["src/sensitive/**"],
895
+ "profile": "high-risk",
896
+ }
897
+ ]
898
+ }
899
+ repo, cfg = self.make_repo(config=cfg)
900
+ focused = self.plan(repo, cfg, planned_paths=["src/sensitive/value.py"])
901
+ deep = self.plan(repo, cfg, planned_paths=["backend/auth/service.py"])
902
+
903
+ for plan, depth, timeout in [
904
+ (focused, "focused", 90),
905
+ (deep, "deep", 300),
906
+ ]:
907
+ with self.subTest(depth=depth):
908
+ self.assertTrue(plan["review_required"])
909
+ self.assertEqual(depth, plan["review_depth"])
910
+ self.assertEqual("reviewer", plan["review_agent"])
911
+ self.assertEqual(timeout, plan["review_timeout_seconds"])
912
+ self.assertEqual(1, plan["review_analysis_attempt_limit"])
913
+ self.assertEqual("reviewer", plan["agent_plan"]["policies"]["review_agent"])
914
+ self.assertEqual(
915
+ timeout,
916
+ plan["agent_plan"]["policies"]["review_timeout_seconds"],
917
+ )
918
+ self.assertEqual(
919
+ 1,
920
+ plan["agent_plan"]["policies"]["review_analysis_attempt_limit"],
921
+ )
922
+ constraints = " ".join(plan["agent_plan"]["constraints"]).lower()
923
+ self.assertIn("timeout is blocked", constraints)
924
+ self.assertIn("reuse the same analysis", constraints)
925
+
641
926
  def test_ui_api_reports_capabilities_without_auto_dispatch(self) -> None:
642
927
  repo, cfg = self.make_repo("src/api/settings-page.tsx")
643
928
  plan = self.plan(repo, cfg)
@@ -646,6 +931,148 @@ class AutoCodingProfileTests(unittest.TestCase):
646
931
  self.assertEqual("main-only", plan["agent_plan"]["strategy"])
647
932
  self.assertEqual(["main"], plan["agent_plan"]["stages"][0]["roles"])
648
933
 
934
+ def test_ui_classification_uses_segments_and_extensions_not_substrings(self) -> None:
935
+ for path in [
936
+ ".env.components",
937
+ "docker-compose.components.yml",
938
+ "config/component-overrides.yml",
939
+ "backend/component_service.go",
940
+ ]:
941
+ with self.subTest(path=path):
942
+ self.assertNotIn("ui", ap._classify_paths([path])["categories"])
943
+
944
+ for path in [
945
+ "frontend/src/app.ts",
946
+ "src/components/Button.ts",
947
+ "src/views/Home.js",
948
+ "src/Button.tsx",
949
+ "miniapp/pages/home/index.ts",
950
+ ]:
951
+ with self.subTest(path=path):
952
+ self.assertIn("ui", ap._classify_paths([path])["categories"])
953
+
954
+ repo, cfg = self.make_repo()
955
+ plan = self.plan(repo, cfg, planned_paths=[".env.components"])
956
+ self.assertFalse(plan["needs_browser"])
957
+
958
+ def test_exact_cross_module_high_risk_rename_is_mechanical_but_reviewed(self) -> None:
959
+ repo, cfg = self.make_repo()
960
+ source = repo / "backend" / "auth" / "policy.py"
961
+ source.parent.mkdir(parents=True)
962
+ source.write_text("POLICY = 'stable'\n", encoding="utf-8")
963
+ run(repo, "git", "add", str(source.relative_to(repo)))
964
+ run(repo, "git", "commit", "-qm", "add auth policy")
965
+ destination = repo / "account" / "auth" / "policy.py"
966
+ destination.parent.mkdir(parents=True)
967
+ run(repo, "git", "mv", str(source.relative_to(repo)), str(destination.relative_to(repo)))
968
+
969
+ plan = self.plan(repo, cfg)
970
+
971
+ self.assertEqual(
972
+ ["account/auth/policy.py", "backend/auth/policy.py"],
973
+ plan["changed_files"],
974
+ )
975
+ self.assertTrue(plan["cross_module"])
976
+ self.assertEqual("high-risk", plan["profile"])
977
+ self.assertEqual("mechanical", plan["change_nature"])
978
+ self.assertTrue(plan["review_required"])
979
+ self.assertFalse(plan["design_required"])
980
+
981
+ extra = repo / "account" / "auth" / "new_policy.py"
982
+ extra.write_text("POLICY = 'new'\n", encoding="utf-8")
983
+ mixed = self.plan(repo, cfg)
984
+ self.assertEqual("unknown", mixed["change_nature"])
985
+ self.assertTrue(mixed["design_required"])
986
+
987
+ def test_semantic_or_unknown_cross_module_high_risk_change_keeps_design(self) -> None:
988
+ repo, cfg = self.make_repo()
989
+ source = repo / "backend" / "auth" / "policy.py"
990
+ source.parent.mkdir(parents=True)
991
+ source.write_text("POLICY = 'stable'\n", encoding="utf-8")
992
+ run(repo, "git", "add", str(source.relative_to(repo)))
993
+ run(repo, "git", "commit", "-qm", "add auth policy")
994
+ destination = repo / "account" / "auth" / "policy.py"
995
+ destination.parent.mkdir(parents=True)
996
+ run(repo, "git", "mv", str(source.relative_to(repo)), str(destination.relative_to(repo)))
997
+ destination.write_text("POLICY = 'changed'\n", encoding="utf-8")
998
+
999
+ semantic = self.plan(repo, cfg, intent="改变鉴权策略行为和模块职责")
1000
+ self.assertEqual("semantic", semantic["change_nature"])
1001
+ self.assertTrue(semantic["review_required"])
1002
+ self.assertTrue(semantic["design_required"])
1003
+
1004
+ clean_repo, clean_cfg = self.make_repo()
1005
+ unknown = self.plan(
1006
+ clean_repo,
1007
+ clean_cfg,
1008
+ planned_paths=["backend/auth/policy.py", "account/auth/policy.py"],
1009
+ )
1010
+ self.assertEqual("unknown", unknown["change_nature"])
1011
+ self.assertTrue(unknown["review_required"])
1012
+ self.assertTrue(unknown["design_required"])
1013
+
1014
+ def test_failed_git_rename_probe_stays_conservative(self) -> None:
1015
+ repo, _ = self.make_repo()
1016
+ failed = subprocess.CompletedProcess(
1017
+ args=["git", "diff"],
1018
+ returncode=128,
1019
+ stdout="",
1020
+ stderr="fatal: diff unavailable",
1021
+ )
1022
+ with (
1023
+ mock.patch.object(ap, "_effective_change_base", return_value=""),
1024
+ mock.patch.object(ap, "run", return_value=failed),
1025
+ ):
1026
+ self.assertFalse(
1027
+ ap._pure_exact_git_rename(
1028
+ repo,
1029
+ "",
1030
+ ["backend/auth/policy.py", "account/auth/policy.py"],
1031
+ )
1032
+ )
1033
+
1034
+ def test_explicit_design_rule_wins_over_mechanical_change(self) -> None:
1035
+ cfg = base_config()
1036
+ cfg["risk"] = {
1037
+ "rules": [
1038
+ {
1039
+ "name": "auth-design",
1040
+ "paths": ["**/auth/**"],
1041
+ "profile": "high-risk",
1042
+ "design": "required",
1043
+ }
1044
+ ]
1045
+ }
1046
+ repo, cfg = self.make_repo(config=cfg)
1047
+ plan = self.plan(
1048
+ repo,
1049
+ cfg,
1050
+ planned_paths=["backend/auth/policy.py", "account/auth/policy.py"],
1051
+ intent="机械同步,不改变行为",
1052
+ )
1053
+ self.assertEqual("mechanical", plan["change_nature"])
1054
+ self.assertTrue(plan["review_required"])
1055
+ self.assertTrue(plan["design_required"])
1056
+
1057
+ def test_semantic_or_negated_intent_overrides_mechanical_words(self) -> None:
1058
+ repo, cfg = self.make_repo()
1059
+ paths = ["backend/auth/policy.py", "account/auth/policy.py"]
1060
+ for intent in [
1061
+ "mechanical sync that changes behavior",
1062
+ "rename only while changing the API contract",
1063
+ "机械同步但修改鉴权契约",
1064
+ ]:
1065
+ with self.subTest(intent=intent):
1066
+ plan = self.plan(repo, cfg, planned_paths=paths, intent=intent)
1067
+ self.assertEqual("semantic", plan["change_nature"])
1068
+ self.assertTrue(plan["design_required"])
1069
+
1070
+ for intent in ["not mechanical", "不是机械变更"]:
1071
+ with self.subTest(intent=intent):
1072
+ plan = self.plan(repo, cfg, planned_paths=paths, intent=intent)
1073
+ self.assertEqual("unknown", plan["change_nature"])
1074
+ self.assertTrue(plan["design_required"])
1075
+
649
1076
  def test_terminal_ledger_maintenance_creates_no_lifecycle_plan(self) -> None:
650
1077
  repo, cfg = self.make_repo()
651
1078
  plan = self.plan(repo, cfg, planned_paths=["docs/tasks/closure-log.md"])
@@ -706,9 +1133,9 @@ class AutoCodingProfileTests(unittest.TestCase):
706
1133
  def test_legacy_rule_commands_never_run_in_automatic_gate(self) -> None:
707
1134
  cfg = base_config()
708
1135
  repo, cfg = self.make_repo("src/sensitive/value.py", cfg)
709
- quick_marker = repo / "quick-ran"
710
- full_marker = repo / "full-ran"
711
- build_marker = repo / "build-ran"
1136
+ quick_marker = repo.parent / "quick-ran"
1137
+ full_marker = repo.parent / "full-ran"
1138
+ build_marker = repo.parent / "build-ran"
712
1139
  cfg["commands"] = {
713
1140
  "gate_changed": f"touch {quick_marker}",
714
1141
  "gate_full": f"touch {full_marker}",
@@ -757,6 +1184,37 @@ class AutoCodingProfileTests(unittest.TestCase):
757
1184
  self.assertNotIn("light-gate", rendered)
758
1185
  self.assertNotIn("structure-check", rendered)
759
1186
 
1187
+ def test_classify_text_output_exposes_workspace_and_writer_snapshot(self) -> None:
1188
+ repo, _ = self.make_repo("path with spaces.txt")
1189
+ output = io.StringIO()
1190
+ args = argparse.Namespace(
1191
+ repo=str(repo),
1192
+ scope="auto",
1193
+ profile="",
1194
+ mode="dev",
1195
+ base="",
1196
+ planned_path=[],
1197
+ intent="",
1198
+ intent_file="",
1199
+ task_kind="auto",
1200
+ claim_direct=False,
1201
+ claim_owner="",
1202
+ continue_direct=False,
1203
+ direct_claim="",
1204
+ writers=1,
1205
+ json=False,
1206
+ )
1207
+ with mock.patch.object(ap, "_record_evidence"):
1208
+ with contextlib.redirect_stdout(output):
1209
+ ap.cmd_classify(args)
1210
+
1211
+ rendered = output.getvalue()
1212
+ self.assertIn(f"[classify] repo={repo.resolve()}", rendered)
1213
+ self.assertIn("[classify] workspace_dirty=true", rendered)
1214
+ self.assertIn('[classify] dirty_paths=["path with spaces.txt"]', rendered)
1215
+ self.assertIn("[classify] active_writer=false", rendered)
1216
+ self.assertIn("[classify] review_analysis_attempt_limit=0", rendered)
1217
+
760
1218
  def test_custom_full_on_path_does_not_expand_local_gate(self) -> None:
761
1219
  cfg = base_config()
762
1220
  cfg["gate"]["full_on"] = {"paths": ["src/sensitive/**"]}
@@ -798,6 +1256,30 @@ class AutoCodingProfileTests(unittest.TestCase):
798
1256
  with self.assertRaises(APError):
799
1257
  ap.cmd_structure_check(args)
800
1258
 
1259
+ def test_structure_scan_excludes_non_authoritative_agent_history_and_metadata(self) -> None:
1260
+ repo, _ = self.make_repo()
1261
+ files = {
1262
+ ".agents/archive/old.py": "old = True\n",
1263
+ ".agents/agents/custom.toml": "model = 'test'\n",
1264
+ ".agents/managed-install.json": "{}\n",
1265
+ ".agents/custom/check.py": "active = True\n",
1266
+ "src/app.py": "active = True\n",
1267
+ }
1268
+ for relative, content in files.items():
1269
+ target = repo / relative
1270
+ target.parent.mkdir(parents=True, exist_ok=True)
1271
+ target.write_text(content, encoding="utf-8")
1272
+ run(repo, "git", "add", "-A")
1273
+ run(repo, "git", "commit", "-qm", "add structure fixtures")
1274
+
1275
+ candidates = ap._structure_paths_for_scope(repo, "full", "", {})
1276
+
1277
+ self.assertIn(".agents/custom/check.py", candidates)
1278
+ self.assertIn("src/app.py", candidates)
1279
+ self.assertNotIn(".agents/archive/old.py", candidates)
1280
+ self.assertNotIn(".agents/agents/custom.toml", candidates)
1281
+ self.assertNotIn(".agents/managed-install.json", candidates)
1282
+
801
1283
  def test_doctor_validates_profile_values(self) -> None:
802
1284
  cfg = base_config()
803
1285
  cfg["workflow"]["profile"] = "extreme"
@@ -0,0 +1,84 @@
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import signal
6
+ import subprocess
7
+ import sys
8
+ import tempfile
9
+ import unittest
10
+ from pathlib import Path
11
+ from unittest import mock
12
+
13
+
14
+ REPO_ROOT = Path(__file__).resolve().parents[2]
15
+ SCRIPT_DIR = REPO_ROOT / "src" / "auto-coding-skill" / "scripts"
16
+ sys.path.insert(0, str(SCRIPT_DIR))
17
+
18
+ import core # noqa: E402
19
+
20
+
21
+ class RunShellTests(unittest.TestCase):
22
+ def test_run_shell_uses_non_login_bash_and_inherits_environment(self) -> None:
23
+ process = mock.Mock()
24
+ process.wait.return_value = 0
25
+ cwd = Path("/tmp/run-shell-test")
26
+ with mock.patch.object(core.subprocess, "Popen", return_value=process) as popen:
27
+ core.run_shell("sentinel", cwd=cwd)
28
+
29
+ popen.assert_called_once_with(
30
+ ["bash", "-c", "sentinel"],
31
+ cwd=str(cwd),
32
+ text=True,
33
+ start_new_session=True,
34
+ )
35
+
36
+ def test_run_shell_preserves_caller_path(self) -> None:
37
+ with tempfile.TemporaryDirectory(prefix="autocoding-shell-") as temp_name:
38
+ root = Path(temp_name)
39
+ bin_dir = root / "bin"
40
+ bin_dir.mkdir()
41
+ sentinel = bin_dir / "path-sentinel"
42
+ sentinel.write_text("#!/bin/sh\nprintf inherited > \"$1\"\n", encoding="utf-8")
43
+ sentinel.chmod(0o755)
44
+ result = root / "result.txt"
45
+ profile_marker = root / "login-profile-ran"
46
+ (root / ".bash_profile").write_text(
47
+ f"export PATH=/usr/bin:/bin\n/usr/bin/touch '{profile_marker}'\n",
48
+ encoding="utf-8",
49
+ )
50
+ inherited_path = f"{bin_dir}{os.pathsep}{os.environ.get('PATH', '')}"
51
+ with mock.patch.dict(
52
+ os.environ,
53
+ {"HOME": str(root), "PATH": inherited_path},
54
+ clear=False,
55
+ ):
56
+ core.run_shell(f"path-sentinel '{result}'", cwd=root, timeout_s=5)
57
+
58
+ self.assertEqual("inherited", result.read_text(encoding="utf-8"))
59
+ self.assertFalse(profile_marker.exists())
60
+
61
+ def test_run_shell_timeout_terminates_then_kills_process_group(self) -> None:
62
+ process = mock.Mock(pid=4321)
63
+ process.wait.side_effect = [
64
+ subprocess.TimeoutExpired(cmd="slow", timeout=1),
65
+ subprocess.TimeoutExpired(cmd="slow", timeout=2),
66
+ 0,
67
+ ]
68
+ with (
69
+ mock.patch.object(core.subprocess, "Popen", return_value=process),
70
+ mock.patch.object(core.os, "killpg") as killpg,
71
+ ):
72
+ with self.assertRaises(core.APError) as context:
73
+ core.run_shell("slow", timeout_s=1)
74
+
75
+ self.assertIn("timed out after 1.0s", str(context.exception))
76
+ self.assertEqual(
77
+ [mock.call(4321, signal.SIGTERM), mock.call(4321, signal.SIGKILL)],
78
+ killpg.call_args_list,
79
+ )
80
+ self.assertEqual(3, process.wait.call_count)
81
+
82
+
83
+ if __name__ == "__main__":
84
+ unittest.main()