@elvis1513/auto-coding-skill 2.0.3 → 2.0.5

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.
@@ -7,8 +7,10 @@ from __future__ import annotations
7
7
  import argparse
8
8
  import base64
9
9
  import datetime as _dt
10
+ import fnmatch
10
11
  import json
11
12
  import os
13
+ import re
12
14
  import time
13
15
  import urllib.parse
14
16
  import urllib.error
@@ -467,6 +469,7 @@ def cmd_gen_summary(args: argparse.Namespace) -> None:
467
469
 
468
470
  ## 4. 质量证据
469
471
  - 本地轻量校验:light_gate or quick_test/test/build / api docs / jenkins / diff-check — TODO
472
+ - 结构检查:structure-check — TODO
470
473
  - Jenkins Build:TODO
471
474
  - 目标环境验证:TODO
472
475
  - 闭环记录:TODO
@@ -638,12 +641,658 @@ def _resolve_secret(section_name: str, section_cfg: dict, field: str) -> str:
638
641
  )
639
642
 
640
643
 
644
+ _GATE_SCOPES = {"auto", "changed", "standard", "full"}
645
+ _DOC_PATH_PATTERNS = ["*.md", "docs/**"]
646
+ _DEFAULT_FULL_PATH_PATTERNS = [
647
+ ".agents/**",
648
+ ".claude/**",
649
+ ".github/workflows/**",
650
+ "Jenkinsfile",
651
+ "Jenkinsfile.*",
652
+ "Dockerfile",
653
+ "**/Dockerfile",
654
+ "docker-compose*.yml",
655
+ "docker-compose*.yaml",
656
+ "compose*.yml",
657
+ "compose*.yaml",
658
+ "docs/ENGINEERING.md",
659
+ "docs/tools/autopipeline/**",
660
+ "package-lock.json",
661
+ "pnpm-lock.yaml",
662
+ "yarn.lock",
663
+ "bun.lockb",
664
+ "go.mod",
665
+ "go.sum",
666
+ "Cargo.lock",
667
+ "pom.xml",
668
+ "build.gradle",
669
+ "build.gradle.kts",
670
+ "settings.gradle",
671
+ "settings.gradle.kts",
672
+ ]
673
+
674
+
675
+ def _gate_cfg(cfg: dict) -> dict:
676
+ gate_cfg = cfg.get("gate") or {}
677
+ return gate_cfg if isinstance(gate_cfg, dict) else {}
678
+
679
+
680
+ def _as_list(value: object) -> list:
681
+ if value is None:
682
+ return []
683
+ if isinstance(value, list):
684
+ return value
685
+ return [value]
686
+
687
+
688
+ def _command_name(ref: object) -> str:
689
+ raw = _text(ref)
690
+ if raw.startswith("commands."):
691
+ raw = raw.split(".", 1)[1]
692
+ return raw
693
+
694
+
695
+ def _configured_command(cfg: dict, name: str) -> str:
696
+ commands = cfg.get("commands") or {}
697
+ return _text(commands.get(name))
698
+
699
+
700
+ def _run_first_configured_command(repo: Path, cfg: dict, names: list[str]) -> str:
701
+ for name in names:
702
+ command_name = _command_name(name)
703
+ if command_name and _configured_command(cfg, command_name):
704
+ _run_configured_command(repo, cfg, command_name)
705
+ return command_name
706
+ return ""
707
+
708
+
709
+ def _run_configured_command_list(repo: Path, cfg: dict, names: list) -> list[str]:
710
+ executed: list[str] = []
711
+ missing: list[str] = []
712
+ for name_ref in names:
713
+ name = _command_name(name_ref)
714
+ if not name:
715
+ continue
716
+ if _configured_command(cfg, name):
717
+ _run_configured_command(repo, cfg, name)
718
+ executed.append(name)
719
+ else:
720
+ missing.append(name)
721
+ if missing and not executed:
722
+ raise APError("Gate rule references missing commands: " + ", ".join(missing))
723
+ return executed
724
+
725
+
726
+ def _path_matches(path: str, patterns: list) -> bool:
727
+ normalized = path.replace("\\", "/").lstrip("./")
728
+ for pattern_ref in patterns:
729
+ pattern = _text(pattern_ref).replace("\\", "/").lstrip("./")
730
+ if not pattern:
731
+ continue
732
+ if fnmatch.fnmatch(normalized, pattern):
733
+ return True
734
+ if "/" not in pattern and fnmatch.fnmatch(Path(normalized).name, pattern):
735
+ return True
736
+ return False
737
+
738
+
739
+ def _unique_paths(paths: list[str]) -> list[str]:
740
+ seen = set()
741
+ out = []
742
+ for path in paths:
743
+ normalized = path.replace("\\", "/").strip()
744
+ if not normalized or normalized in seen:
745
+ continue
746
+ seen.add(normalized)
747
+ out.append(normalized)
748
+ return sorted(out)
749
+
750
+
751
+ def _git_lines(repo: Path, cmd: list[str]) -> list[str]:
752
+ try:
753
+ result = run(cmd, cwd=repo, check=False)
754
+ except APError:
755
+ return []
756
+ if result.returncode != 0:
757
+ return []
758
+ return [line.strip() for line in result.stdout.splitlines() if line.strip()]
759
+
760
+
761
+ def _default_base_ref(repo: Path) -> str:
762
+ upstream = _git_lines(repo, ["git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"])
763
+ return upstream[0] if upstream else ""
764
+
765
+
766
+ def _changed_files(repo: Path, base_ref: str = "") -> list[str]:
767
+ paths: list[str] = []
768
+ effective_base = base_ref or _default_base_ref(repo)
769
+ if effective_base:
770
+ paths.extend(_git_lines(repo, ["git", "diff", "--name-only", "--diff-filter=ACMRTUXB", f"{effective_base}...HEAD"]))
771
+ paths.extend(_git_lines(repo, ["git", "diff", "--name-only", "--diff-filter=ACMRTUXB"]))
772
+ paths.extend(_git_lines(repo, ["git", "diff", "--cached", "--name-only", "--diff-filter=ACMRTUXB"]))
773
+ paths.extend(_git_lines(repo, ["git", "ls-files", "--others", "--exclude-standard"]))
774
+ return _unique_paths(paths)
775
+
776
+
777
+ def _docs_only(paths: list[str]) -> bool:
778
+ return bool(paths) and all(_path_matches(path, _DOC_PATH_PATTERNS) for path in paths)
779
+
780
+
781
+ def _gate_rules(gate_cfg: dict) -> list[dict]:
782
+ rules = gate_cfg.get("rules") or []
783
+ return [rule for rule in rules if isinstance(rule, dict)]
784
+
785
+
786
+ def _matching_gate_rules(paths: list[str], gate_cfg: dict) -> list[dict]:
787
+ matches = []
788
+ for rule in _gate_rules(gate_cfg):
789
+ patterns = _as_list(rule.get("paths"))
790
+ if patterns and any(_path_matches(path, patterns) for path in paths):
791
+ matches.append(rule)
792
+ return matches
793
+
794
+
795
+ def _gate_full_patterns(gate_cfg: dict) -> list:
796
+ full_on = gate_cfg.get("full_on") or {}
797
+ patterns = list(_DEFAULT_FULL_PATH_PATTERNS)
798
+ if isinstance(full_on, dict):
799
+ patterns.extend(_as_list(full_on.get("paths")))
800
+ else:
801
+ patterns.extend(_as_list(full_on))
802
+ return patterns
803
+
804
+
805
+ def _has_changed_gate(cfg: dict, gate_cfg: dict, paths: list[str]) -> bool:
806
+ if _configured_command(cfg, "gate_changed"):
807
+ return True
808
+ for rule in _matching_gate_rules(paths, gate_cfg):
809
+ if _as_list(rule.get("commands")):
810
+ return True
811
+ return False
812
+
813
+
814
+ def _select_gate_scope(cfg: dict, requested_scope: str, paths: list[str]) -> tuple[str, list[str], list[dict]]:
815
+ gate_cfg = _gate_cfg(cfg)
816
+ scope = (requested_scope or _text(gate_cfg.get("default_scope")) or "standard").lower()
817
+ if scope not in _GATE_SCOPES:
818
+ raise APError("gate scope must be one of: " + ", ".join(sorted(_GATE_SCOPES)))
819
+
820
+ matching_rules = _matching_gate_rules(paths, gate_cfg)
821
+ reasons: list[str] = []
822
+
823
+ if scope != "auto":
824
+ return scope, [f"requested scope: {scope}"], matching_rules
825
+
826
+ if not paths:
827
+ fallback = _text(gate_cfg.get("no_change_scope")) or "standard"
828
+ if fallback not in {"changed", "standard", "full"}:
829
+ fallback = "standard"
830
+ return fallback, ["no changed files detected"], matching_rules
831
+
832
+ rule_scopes = {_text(rule.get("scope")).lower() for rule in matching_rules if _text(rule.get("scope"))}
833
+ if "full" in rule_scopes:
834
+ return "full", ["matched gate rule with scope=full"], matching_rules
835
+ if "standard" in rule_scopes:
836
+ return "standard", ["matched gate rule with scope=standard"], matching_rules
837
+
838
+ if any(_path_matches(path, _gate_full_patterns(gate_cfg)) for path in paths):
839
+ return "full", ["changed files match full-gate patterns"], matching_rules
840
+
841
+ if _docs_only(paths):
842
+ return "changed", ["docs-only change"], matching_rules
843
+
844
+ if _has_changed_gate(cfg, gate_cfg, paths):
845
+ return "changed", ["matched changed-gate command or rule"], matching_rules
846
+
847
+ fallback = _text(gate_cfg.get("fallback_scope")) or "standard"
848
+ if fallback not in {"changed", "standard", "full"}:
849
+ fallback = "standard"
850
+ if fallback == "changed" and _text(gate_cfg.get("full_on_unknown")).lower() in {"1", "true", "yes", "on"}:
851
+ fallback = "full"
852
+ reasons.append("no changed-gate command/rule matched")
853
+ return fallback, reasons, matching_rules
854
+
855
+
856
+ def _impact_summary(cfg: dict, repo: Path, requested_scope: str, base_ref: str = "") -> dict:
857
+ paths = _changed_files(repo, base_ref=base_ref)
858
+ scope, reasons, matching_rules = _select_gate_scope(cfg, requested_scope, paths)
859
+ return {
860
+ "requested_scope": requested_scope or _text(_gate_cfg(cfg).get("default_scope")) or "standard",
861
+ "selected_scope": scope,
862
+ "reasons": reasons,
863
+ "changed_files": paths,
864
+ "matched_rules": [_text(rule.get("name")) or "(unnamed)" for rule in matching_rules],
865
+ }
866
+
867
+
868
+ def _print_impact(summary: dict, as_json: bool = False) -> None:
869
+ if as_json:
870
+ print(json.dumps(summary, ensure_ascii=False, indent=2))
871
+ return
872
+ print(f"[impact] requested_scope={summary['requested_scope']}")
873
+ print(f"[impact] selected_scope={summary['selected_scope']}")
874
+ for reason in summary.get("reasons") or []:
875
+ print(f"[impact] reason: {reason}")
876
+ for rule in summary.get("matched_rules") or []:
877
+ print(f"[impact] matched_rule: {rule}")
878
+ files = summary.get("changed_files") or []
879
+ if files:
880
+ for path in files:
881
+ print(f"[impact] changed: {path}")
882
+ else:
883
+ print("[impact] changed: (none)")
884
+
885
+
886
+ def _run_changed_gate(repo: Path, cfg: dict, paths: list[str], matching_rules: list[dict]) -> list[str]:
887
+ executed: list[str] = []
888
+ for rule in matching_rules:
889
+ executed.extend(_run_configured_command_list(repo, cfg, _as_list(rule.get("commands"))))
890
+ if executed:
891
+ return executed
892
+
893
+ fallback_commands = ["gate_changed"]
894
+ if _docs_only(paths):
895
+ fallback_commands.append("docs_check")
896
+ command = _run_first_configured_command(repo, cfg, fallback_commands)
897
+ if command:
898
+ return [command]
899
+
900
+ if _docs_only(paths):
901
+ print("[gate] docs-only change with no changed-gate command configured; running built-in post checks only.")
902
+ return ["docs_only_builtin"]
903
+
904
+ fallback = _run_first_configured_command(repo, cfg, ["quick_test", "test", "build"])
905
+ if fallback:
906
+ return [fallback]
907
+
908
+ raise APError(
909
+ "Changed gate has no configured command. Add commands.gate_changed or matching gate.rules commands, "
910
+ "or run light-gate --scope standard/full."
911
+ )
912
+
913
+
914
+ def _run_standard_gate(repo: Path, cfg: dict) -> list[str]:
915
+ command = _run_first_configured_command(repo, cfg, ["gate_standard", "light_gate", "quick_test", "test", "build"])
916
+ if not command:
917
+ raise APError(
918
+ "Standard gate is under-configured. Add commands.gate_standard, commands.light_gate, "
919
+ "commands.quick_test, commands.test, or commands.build."
920
+ )
921
+ return [command]
922
+
923
+
924
+ def _run_full_gate(repo: Path, cfg: dict) -> list[str]:
925
+ command = _run_first_configured_command(repo, cfg, ["gate_full", "full_gate", "gate_standard", "light_gate", "test", "build"])
926
+ if not command:
927
+ raise APError(
928
+ "Full gate is under-configured. Add commands.gate_full, commands.full_gate, commands.test, "
929
+ "commands.build, or commands.light_gate."
930
+ )
931
+ return [command]
932
+
933
+
641
934
  def _run_git_diff_check(repo: Path, cfg: dict) -> None:
642
935
  print("[diff-check] git diff --check")
643
936
  run(["git", "diff", "--check"], cwd=repo)
644
937
  print("[diff-check] OK")
645
938
 
646
939
 
940
+ _DEFAULT_STRUCTURE_ALLOW_PATTERNS = [
941
+ ".git/**",
942
+ ".agents/skills/**",
943
+ ".claude/skills/**",
944
+ ".next/**",
945
+ ".nuxt/**",
946
+ ".svelte-kit/**",
947
+ ".turbo/**",
948
+ "coverage/**",
949
+ "dist/**",
950
+ "build/**",
951
+ "out/**",
952
+ "target/**",
953
+ "vendor/**",
954
+ "node_modules/**",
955
+ "generated/**",
956
+ "**/generated/**",
957
+ "**/__generated__/**",
958
+ "docs/tools/autopipeline/**",
959
+ "**/*.generated.*",
960
+ "**/*.gen.*",
961
+ "**/*.min.js",
962
+ "**/*.bundle.js",
963
+ "**/*.map",
964
+ "package-lock.json",
965
+ "pnpm-lock.yaml",
966
+ "yarn.lock",
967
+ "bun.lockb",
968
+ "go.sum",
969
+ "Cargo.lock",
970
+ ]
971
+ _TEXT_SOURCE_EXTENSIONS = {
972
+ ".bash",
973
+ ".c",
974
+ ".cc",
975
+ ".cfg",
976
+ ".conf",
977
+ ".cpp",
978
+ ".cs",
979
+ ".css",
980
+ ".go",
981
+ ".gradle",
982
+ ".graphql",
983
+ ".h",
984
+ ".hpp",
985
+ ".html",
986
+ ".java",
987
+ ".js",
988
+ ".json",
989
+ ".jsx",
990
+ ".kt",
991
+ ".kts",
992
+ ".less",
993
+ ".m",
994
+ ".md",
995
+ ".mm",
996
+ ".php",
997
+ ".properties",
998
+ ".py",
999
+ ".rb",
1000
+ ".rs",
1001
+ ".scala",
1002
+ ".scss",
1003
+ ".sh",
1004
+ ".sql",
1005
+ ".swift",
1006
+ ".toml",
1007
+ ".ts",
1008
+ ".tsx",
1009
+ ".vue",
1010
+ ".xml",
1011
+ ".yaml",
1012
+ ".yml",
1013
+ ".zsh",
1014
+ }
1015
+ _TEXT_SOURCE_FILENAMES = {
1016
+ "Dockerfile",
1017
+ "Jenkinsfile",
1018
+ "Makefile",
1019
+ "go.mod",
1020
+ "package.json",
1021
+ "requirements.txt",
1022
+ "pyproject.toml",
1023
+ "tsconfig.json",
1024
+ }
1025
+ _FUNCTION_START_RE = re.compile(
1026
+ r"^\s*(?:export\s+)?(?:async\s+)?(?:def|function|func)\s+[A-Za-z_][\w]*\b"
1027
+ r"|^\s*(?:public|private|protected|static|final|async|\s)+\s*[\w<>\[\], ?]+\s+[A-Za-z_]\w*\s*\([^;]*\)\s*\{"
1028
+ r"|^\s*(?:export\s+)?(?:const|let|var)\s+[A-Za-z_]\w*\s*=\s*(?:async\s*)?\([^)]*\)\s*=>"
1029
+ )
1030
+
1031
+
1032
+ def _structure_cfg(cfg: dict) -> dict:
1033
+ value = cfg.get("structure") or {}
1034
+ return value if isinstance(value, dict) else {}
1035
+
1036
+
1037
+ def _optimization_cfg(cfg: dict) -> dict:
1038
+ value = cfg.get("optimization") or {}
1039
+ return value if isinstance(value, dict) else {}
1040
+
1041
+
1042
+ def _bool_config(value: object, default: bool = False) -> bool:
1043
+ if value is None:
1044
+ return default
1045
+ if isinstance(value, bool):
1046
+ return value
1047
+ raw = _text(value).lower()
1048
+ if not raw:
1049
+ return default
1050
+ if raw in {"1", "true", "yes", "on"}:
1051
+ return True
1052
+ if raw in {"0", "false", "no", "off"}:
1053
+ return False
1054
+ return default
1055
+
1056
+
1057
+ def _int_config(value: object, default: int) -> int:
1058
+ try:
1059
+ return int(value)
1060
+ except Exception:
1061
+ return default
1062
+
1063
+
1064
+ def _tracked_files(repo: Path) -> list[str]:
1065
+ return _unique_paths(_git_lines(repo, ["git", "ls-files"]))
1066
+
1067
+
1068
+ def _structure_allow_patterns(structure_cfg: dict) -> list:
1069
+ patterns = list(_DEFAULT_STRUCTURE_ALLOW_PATTERNS)
1070
+ patterns.extend(_as_list(structure_cfg.get("allow_large_files")))
1071
+ patterns.extend(_as_list(structure_cfg.get("exclude")))
1072
+ return patterns
1073
+
1074
+
1075
+ def _structure_accepted_debt_patterns(structure_cfg: dict) -> list:
1076
+ return _as_list(structure_cfg.get("accepted_debt_paths"))
1077
+
1078
+
1079
+ def _is_structure_accepted_debt(path: str, structure_cfg: dict) -> bool:
1080
+ return _path_matches(path, _structure_accepted_debt_patterns(structure_cfg))
1081
+
1082
+
1083
+ def _is_structure_candidate(path: str, structure_cfg: dict) -> bool:
1084
+ normalized = path.replace("\\", "/").lstrip("./")
1085
+ if _path_matches(normalized, _structure_allow_patterns(structure_cfg)):
1086
+ return False
1087
+ name = Path(normalized).name
1088
+ suffix = Path(normalized).suffix.lower()
1089
+ return suffix in _TEXT_SOURCE_EXTENSIONS or name in _TEXT_SOURCE_FILENAMES
1090
+
1091
+
1092
+ def _structure_paths_for_scope(repo: Path, scope: str, base_ref: str, structure_cfg: dict) -> list[str]:
1093
+ if scope == "full":
1094
+ paths = _tracked_files(repo)
1095
+ else:
1096
+ paths = _changed_files(repo, base_ref=base_ref)
1097
+ return [path for path in paths if _is_structure_candidate(path, structure_cfg)]
1098
+
1099
+
1100
+ def _read_text_lines(repo: Path, path: str) -> Optional[list[str]]:
1101
+ file_path = repo / path
1102
+ if not file_path.exists() or not file_path.is_file():
1103
+ return None
1104
+ try:
1105
+ return file_path.read_text(encoding="utf-8").splitlines()
1106
+ except UnicodeDecodeError:
1107
+ return None
1108
+ except OSError:
1109
+ return None
1110
+
1111
+
1112
+ def _parse_numstat_line(line: str) -> tuple[str, int]:
1113
+ parts = line.split("\t", 2)
1114
+ if len(parts) < 3:
1115
+ return "", 0
1116
+ added_raw, _, path = parts
1117
+ if added_raw == "-":
1118
+ return "", 0
1119
+ try:
1120
+ added = int(added_raw)
1121
+ except ValueError:
1122
+ return "", 0
1123
+ return path.replace("\\", "/").strip(), added
1124
+
1125
+
1126
+ def _added_lines_by_path(repo: Path, base_ref: str = "") -> dict[str, int]:
1127
+ added: dict[str, int] = {}
1128
+ commands: list[list[str]] = []
1129
+ effective_base = base_ref or _default_base_ref(repo)
1130
+ if effective_base:
1131
+ commands.append(["git", "diff", "--numstat", f"{effective_base}...HEAD"])
1132
+ commands.extend([
1133
+ ["git", "diff", "--numstat"],
1134
+ ["git", "diff", "--cached", "--numstat"],
1135
+ ])
1136
+
1137
+ for cmd in commands:
1138
+ for line in _git_lines(repo, cmd):
1139
+ path, count = _parse_numstat_line(line)
1140
+ if path:
1141
+ added[path] = added.get(path, 0) + count
1142
+
1143
+ for path in _git_lines(repo, ["git", "ls-files", "--others", "--exclude-standard"]):
1144
+ lines = _read_text_lines(repo, path)
1145
+ if lines is not None:
1146
+ added[path] = added.get(path, 0) + len(lines)
1147
+ return added
1148
+
1149
+
1150
+ def _function_size_warnings(path: str, lines: list[str], threshold: int) -> list[str]:
1151
+ if threshold <= 0:
1152
+ return []
1153
+ starts: list[int] = []
1154
+ for index, line in enumerate(lines):
1155
+ if _FUNCTION_START_RE.search(line):
1156
+ starts.append(index)
1157
+ warnings: list[str] = []
1158
+ for pos, start in enumerate(starts):
1159
+ end = starts[pos + 1] if pos + 1 < len(starts) else len(lines)
1160
+ size = end - start
1161
+ if size > threshold:
1162
+ warnings.append(f"{path}:{start + 1} function-like block has {size} lines (warn>{threshold})")
1163
+ return warnings
1164
+
1165
+
1166
+ def _configured_structure_docs(cfg: dict) -> dict[str, str]:
1167
+ docs_cfg = cfg.get("docs") or {}
1168
+ return {
1169
+ "docs.health_baseline": _text(docs_cfg.get("health_baseline")),
1170
+ "docs.optimization_backlog": _text(docs_cfg.get("optimization_backlog")),
1171
+ "docs.structure_standard": _text(docs_cfg.get("structure_standard")),
1172
+ }
1173
+
1174
+
1175
+ def _structure_gate_enabled(cfg: dict) -> bool:
1176
+ if _configured_command(cfg, "structure_check"):
1177
+ return True
1178
+ structure_cfg = cfg.get("structure")
1179
+ if not isinstance(structure_cfg, dict):
1180
+ return False
1181
+ return _bool_config(structure_cfg.get("enabled"), default=True)
1182
+
1183
+
1184
+ def _print_limited(label: str, items: list[str], max_items: int = 60) -> None:
1185
+ if not items:
1186
+ return
1187
+ print(label)
1188
+ for item in items[:max_items]:
1189
+ print(f"- {item}")
1190
+ remaining = len(items) - max_items
1191
+ if remaining > 0:
1192
+ print(f"- ... {remaining} more")
1193
+
1194
+
1195
+ def cmd_structure_check(args: argparse.Namespace) -> None:
1196
+ repo = Path(args.repo).resolve()
1197
+ ensure_git_repo(repo)
1198
+ cfg = _load_cfg(repo)
1199
+ requested_scope = str(getattr(args, "scope", "") or "").strip().lower()
1200
+ impact = _impact_summary(cfg, repo, requested_scope=requested_scope, base_ref=str(getattr(args, "base", "") or ""))
1201
+ selected_scope = str(impact["selected_scope"])
1202
+ base_ref = str(getattr(args, "base", "") or "")
1203
+
1204
+ structure_cfg = _structure_cfg(cfg)
1205
+ optimization_cfg = _optimization_cfg(cfg)
1206
+ warn_file_lines = _int_config(structure_cfg.get("max_file_lines_warn"), 800)
1207
+ block_file_lines = _int_config(structure_cfg.get("max_file_lines_block"), 1500)
1208
+ warn_function_lines = _int_config(structure_cfg.get("max_function_lines_warn"), 120)
1209
+ max_added_to_large = _int_config(structure_cfg.get("max_added_lines_to_large_file"), 80)
1210
+ block_large_growth = _bool_config(structure_cfg.get("block_new_responsibility_in_large_file"), True)
1211
+
1212
+ paths = _structure_paths_for_scope(repo, selected_scope, base_ref, structure_cfg)
1213
+ added_by_path = _added_lines_by_path(repo, base_ref=base_ref) if selected_scope != "full" else {}
1214
+
1215
+ blocking: list[str] = []
1216
+ warnings: list[str] = []
1217
+ inspected = 0
1218
+
1219
+ for path in paths:
1220
+ lines = _read_text_lines(repo, path)
1221
+ if lines is None:
1222
+ continue
1223
+ inspected += 1
1224
+ line_count = len(lines)
1225
+ accepted_debt = _is_structure_accepted_debt(path, structure_cfg)
1226
+ if block_file_lines > 0 and line_count > block_file_lines:
1227
+ message = f"{path} has {line_count} lines (block>{block_file_lines}); split responsibilities before adding more work"
1228
+ if accepted_debt:
1229
+ warnings.append(message + " [accepted_debt_paths]")
1230
+ else:
1231
+ blocking.append(message)
1232
+ elif warn_file_lines > 0 and line_count > warn_file_lines:
1233
+ warnings.append(f"{path} has {line_count} lines (warn>{warn_file_lines}); prefer extraction before extending it")
1234
+
1235
+ added_lines = added_by_path.get(path, 0)
1236
+ if (
1237
+ block_large_growth
1238
+ and selected_scope != "full"
1239
+ and warn_file_lines > 0
1240
+ and max_added_to_large > 0
1241
+ and line_count > warn_file_lines
1242
+ and added_lines > max_added_to_large
1243
+ ):
1244
+ blocking.append(
1245
+ f"{path} adds {added_lines} lines to an already large file ({line_count} lines); "
1246
+ "extract a module/helper or document why this is intentionally co-located"
1247
+ )
1248
+
1249
+ warnings.extend(_function_size_warnings(path, lines, warn_function_lines))
1250
+
1251
+ missing_docs: list[str] = []
1252
+ for key, rel_path in _configured_structure_docs(cfg).items():
1253
+ if rel_path and not Path(repo, rel_path).exists():
1254
+ missing_docs.append(f"{key} missing on disk: {rel_path}")
1255
+ require_baseline = _bool_config(optimization_cfg.get("require_baseline_for_global_review"), True)
1256
+ if missing_docs and selected_scope == "full" and require_baseline:
1257
+ blocking.extend(missing_docs)
1258
+ else:
1259
+ warnings.extend(missing_docs)
1260
+
1261
+ result = {
1262
+ "scope": selected_scope,
1263
+ "inspected_files": inspected,
1264
+ "blocking": blocking,
1265
+ "warnings": warnings,
1266
+ }
1267
+ if getattr(args, "json", False):
1268
+ print(json.dumps(result, ensure_ascii=False, indent=2))
1269
+ else:
1270
+ _print_limited("[structure-check] blocking", blocking)
1271
+ _print_limited("[structure-check] warnings", warnings)
1272
+
1273
+ if blocking:
1274
+ raise APError(f"structure-check failed with {len(blocking)} blocking issue(s)")
1275
+
1276
+ print(f"[structure-check] OK scope={selected_scope} inspected={inspected} warnings={len(warnings)}")
1277
+
1278
+
1279
+ def _run_structure_check_for_gate(repo: Path, cfg: dict, selected_scope: str, base_ref: str) -> list[str]:
1280
+ if not _structure_gate_enabled(cfg):
1281
+ return []
1282
+ if _configured_command(cfg, "structure_check"):
1283
+ _run_configured_command(repo, cfg, "structure_check")
1284
+ return ["structure_check"]
1285
+ cmd_structure_check(
1286
+ argparse.Namespace(
1287
+ repo=str(repo),
1288
+ scope=selected_scope,
1289
+ base=base_ref,
1290
+ json=False,
1291
+ )
1292
+ )
1293
+ return ["structure_check"]
1294
+
1295
+
647
1296
  def cmd_run(args: argparse.Namespace) -> None:
648
1297
  """
649
1298
  Run any configured gate command by name.
@@ -671,38 +1320,37 @@ def cmd_light_gate(args: argparse.Namespace) -> None:
671
1320
  repo = Path(args.repo).resolve()
672
1321
  cmd_doctor(argparse.Namespace(repo=str(repo)))
673
1322
  cfg = _load_cfg(repo)
674
- commands = (cfg.get("commands") or {})
675
-
676
- executed: List[str] = []
677
- missing: List[str] = []
678
-
679
- if str(commands.get("light_gate") or "").strip():
680
- _run_configured_command(repo, cfg, "light_gate")
681
- executed.append("light_gate")
682
- elif str(commands.get("quick_test") or "").strip():
683
- _run_configured_command(repo, cfg, "quick_test")
684
- executed.append("quick_test")
685
- elif str(commands.get("test") or "").strip():
686
- _run_configured_command(repo, cfg, "test")
687
- executed.append("test")
688
- elif str(commands.get("build") or "").strip():
689
- _run_configured_command(repo, cfg, "build")
690
- executed.append("build")
1323
+ requested_scope = str(getattr(args, "scope", "") or "").strip().lower()
1324
+ impact = _impact_summary(cfg, repo, requested_scope=requested_scope, base_ref=str(getattr(args, "base", "") or ""))
1325
+ if getattr(args, "explain", False):
1326
+ _print_impact(impact)
1327
+
1328
+ selected_scope = str(impact["selected_scope"])
1329
+ paths = list(impact.get("changed_files") or [])
1330
+ matching_rules = _matching_gate_rules(paths, _gate_cfg(cfg))
1331
+ executed: list[str] = []
1332
+ executed.extend(_run_structure_check_for_gate(repo, cfg, selected_scope, str(getattr(args, "base", "") or "")))
1333
+
1334
+ if selected_scope == "changed":
1335
+ executed.extend(_run_changed_gate(repo, cfg, paths, matching_rules))
1336
+ elif selected_scope == "full":
1337
+ executed.extend(_run_full_gate(repo, cfg))
691
1338
  else:
692
- missing.append("commands.light_gate or commands.quick_test or commands.test or commands.build")
693
-
694
- if missing:
695
- raise APError(
696
- "Light gate is under-configured. Missing required commands: "
697
- + ", ".join(missing)
698
- + ". Edit docs/ENGINEERING.md frontmatter."
699
- )
1339
+ executed.extend(_run_standard_gate(repo, cfg))
700
1340
 
701
1341
  _run_git_diff_check(repo, cfg)
702
1342
  cmd_verify_api_docs(argparse.Namespace(repo=str(repo)))
703
1343
  cmd_verify_jenkins(argparse.Namespace(repo=str(repo)))
704
1344
  executed.extend(["diff_check", "verify_api_docs", "verify_jenkins"])
705
- print("[light-gate] OK: " + ", ".join(executed))
1345
+ print(f"[light-gate] OK scope={selected_scope}: " + ", ".join(executed))
1346
+
1347
+
1348
+ def cmd_impact(args: argparse.Namespace) -> None:
1349
+ repo = Path(args.repo).resolve()
1350
+ cfg = _load_cfg(repo)
1351
+ scope = str(args.scope or "").strip().lower()
1352
+ summary = _impact_summary(cfg, repo, requested_scope=scope, base_ref=str(args.base or ""))
1353
+ _print_impact(summary, as_json=bool(args.json))
706
1354
 
707
1355
 
708
1356
  def cmd_runtime_up(args: argparse.Namespace) -> None:
@@ -858,12 +1506,19 @@ def cmd_doctor(args: argparse.Namespace) -> None:
858
1506
  if not str(project_cfg.get("name") or "").strip():
859
1507
  missing.append("project.name")
860
1508
  if not (
861
- str(commands.get("light_gate") or "").strip()
1509
+ str(commands.get("gate_changed") or "").strip()
1510
+ or str(commands.get("gate_standard") or "").strip()
1511
+ or str(commands.get("gate_full") or "").strip()
1512
+ or str(commands.get("full_gate") or "").strip()
1513
+ or str(commands.get("light_gate") or "").strip()
862
1514
  or str(commands.get("quick_test") or "").strip()
863
1515
  or str(commands.get("test") or "").strip()
864
1516
  or str(commands.get("build") or "").strip()
865
1517
  ):
866
- missing.append("commands.light_gate or commands.quick_test or commands.test or commands.build")
1518
+ missing.append(
1519
+ "commands.gate_changed/gate_standard/gate_full, commands.light_gate, "
1520
+ "commands.quick_test, commands.test, or commands.build"
1521
+ )
867
1522
  _require_explicit_field(missing, "target_env.name", target_cfg.get("name"))
868
1523
  _require_explicit_field(missing, "target_env.frontend_base_url", target_cfg.get("frontend_base_url"))
869
1524
  _require_explicit_field(missing, "target_env.frontend_username", target_cfg.get("frontend_username"))
@@ -1072,6 +1727,7 @@ def cmd_record_closure(args: argparse.Namespace) -> None:
1072
1727
  verification_text = "; ".join(verification_items) if verification_items else "TODO"
1073
1728
  follow_up = str(args.follow_up or "").strip() or "none"
1074
1729
  jenkins_build = str(args.jenkins or "").strip() or "TODO"
1730
+ structure_check = str(getattr(args, "structure_check", "") or "").strip() or "TODO"
1075
1731
 
1076
1732
  lines = [
1077
1733
  f"## {task_id} — {title} — {timestamp}",
@@ -1080,6 +1736,7 @@ def cmd_record_closure(args: argparse.Namespace) -> None:
1080
1736
  f"- Jenkins Build: {jenkins_build}",
1081
1737
  f"- Target Env: {target_env}",
1082
1738
  f"- Verification: {verification_text}",
1739
+ f"- Structure Check: {structure_check}",
1083
1740
  f"- Result: {args.result}",
1084
1741
  f"- Follow-up: {follow_up}",
1085
1742
  ]
@@ -1108,6 +1765,7 @@ def _record_commit_push_closure(
1108
1765
  verification: List[str],
1109
1766
  result: str,
1110
1767
  follow_up: str,
1768
+ structure_check: str,
1111
1769
  ) -> None:
1112
1770
  cmd_record_closure(
1113
1771
  argparse.Namespace(
@@ -1120,6 +1778,7 @@ def _record_commit_push_closure(
1120
1778
  verification=verification,
1121
1779
  result=result,
1122
1780
  follow_up=follow_up,
1781
+ structure_check=structure_check,
1123
1782
  initial_commit=args.initial_commit,
1124
1783
  jenkins_failure=args.jenkins_failure,
1125
1784
  fix_commit=args.fix_commit,
@@ -1136,12 +1795,14 @@ def cmd_commit_push(args: argparse.Namespace) -> None:
1136
1795
  target_cfg = (cfg.get("target_env") or {})
1137
1796
 
1138
1797
  msg = args.msg
1798
+ structure_check_status = "skipped"
1139
1799
 
1140
1800
  if args.require_runtime_health:
1141
1801
  cmd_wait_health(argparse.Namespace(repo=str(repo), scope="runtime"))
1142
1802
 
1143
1803
  if mode in {"dev", "verify"} or args.require_light_gate:
1144
1804
  cmd_light_gate(argparse.Namespace(repo=str(repo)))
1805
+ structure_check_status = "passed via light-gate" if _structure_gate_enabled(cfg) else "skipped (structure disabled)"
1145
1806
 
1146
1807
  if args.require_jenkins:
1147
1808
  cmd_verify_jenkins(argparse.Namespace(repo=str(repo)))
@@ -1164,6 +1825,7 @@ def cmd_commit_push(args: argparse.Namespace) -> None:
1164
1825
  verification=dev_verification,
1165
1826
  result=args.result or "DEV-CLOSED",
1166
1827
  follow_up=args.follow_up or "Run verify mode when Jenkins and target-environment evidence is required.",
1828
+ structure_check=args.structure_check or structure_check_status,
1167
1829
  )
1168
1830
 
1169
1831
  run(["git", "add", "-A"], cwd=repo)
@@ -1214,6 +1876,7 @@ def cmd_commit_push(args: argparse.Namespace) -> None:
1214
1876
  verification=verification,
1215
1877
  result=args.result or "PASS",
1216
1878
  follow_up=args.follow_up or "none",
1879
+ structure_check=args.structure_check or structure_check_status,
1217
1880
  )
1218
1881
  run(["git", "add", "-A"], cwd=repo)
1219
1882
  closure_diff = run(["git", "diff", "--cached", "--name-only"], cwd=repo).stdout.strip()
@@ -1230,6 +1893,7 @@ def cmd_commit_push(args: argparse.Namespace) -> None:
1230
1893
  verification=args.verification or [],
1231
1894
  result=args.result or "PARTIAL",
1232
1895
  follow_up=args.follow_up or "none",
1896
+ structure_check=args.structure_check or structure_check_status,
1233
1897
  )
1234
1898
  print(f"[commit-push] OK - mode={mode}")
1235
1899
 
@@ -1256,7 +1920,22 @@ def main(argv: Optional[List[str]] = None) -> int:
1256
1920
  s.add_argument("name")
1257
1921
  s.set_defaults(func=cmd_run)
1258
1922
 
1923
+ s = sp.add_parser("impact")
1924
+ s.add_argument("--scope", choices=sorted(_GATE_SCOPES), default="")
1925
+ s.add_argument("--base")
1926
+ s.add_argument("--json", action="store_true")
1927
+ s.set_defaults(func=cmd_impact)
1928
+
1929
+ s = sp.add_parser("structure-check")
1930
+ s.add_argument("--scope", choices=sorted(_GATE_SCOPES), default="")
1931
+ s.add_argument("--base")
1932
+ s.add_argument("--json", action="store_true")
1933
+ s.set_defaults(func=cmd_structure_check)
1934
+
1259
1935
  s = sp.add_parser("light-gate")
1936
+ s.add_argument("--scope", choices=sorted(_GATE_SCOPES), default="")
1937
+ s.add_argument("--base")
1938
+ s.add_argument("--explain", action="store_true")
1260
1939
  s.set_defaults(func=cmd_light_gate)
1261
1940
 
1262
1941
  s = sp.add_parser("doctor")
@@ -1305,6 +1984,7 @@ def main(argv: Optional[List[str]] = None) -> int:
1305
1984
  s.add_argument("--jenkins")
1306
1985
  s.add_argument("--target-env")
1307
1986
  s.add_argument("--verification", action="append")
1987
+ s.add_argument("--structure-check")
1308
1988
  s.add_argument("--result", choices=["DEV-CLOSED", "PASS", "FAIL", "PARTIAL"], required=True)
1309
1989
  s.add_argument("--follow-up")
1310
1990
  s.add_argument("--initial-commit")
@@ -1338,6 +2018,7 @@ def main(argv: Optional[List[str]] = None) -> int:
1338
2018
  s.add_argument("--jenkins-build")
1339
2019
  s.add_argument("--target-env")
1340
2020
  s.add_argument("--verification", action="append")
2021
+ s.add_argument("--structure-check")
1341
2022
  s.add_argument("--result", choices=["DEV-CLOSED", "PASS", "FAIL", "PARTIAL"])
1342
2023
  s.add_argument("--follow-up")
1343
2024
  s.add_argument("--initial-commit")