@elvis1513/auto-coding-skill 4.2.2 → 4.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,6 +5,7 @@
5
5
  from __future__ import annotations
6
6
 
7
7
  import argparse
8
+ import ast
8
9
  import base64
9
10
  import contextlib
10
11
  import hashlib
@@ -84,7 +85,7 @@ _FINAL_GATE_CACHE_ALGORITHM = "final-gate-v1"
84
85
  _WORKFLOW_MIGRATION_POLICY = Path("data/policies/workflow-migrations-v1.json")
85
86
  _FALLBACK_WORKFLOW_MIGRATION_POLICY = {
86
87
  "schema_version": 1,
87
- "managed_versions": {"agents": "4.2.2", "engineering": "4.2.2"},
88
+ "managed_versions": {"agents": "4.2.4", "engineering": "4.2.4"},
88
89
  "known_official_engineering_body_sha256": [
89
90
  "d1306cc626e8baf8c83c953b760fd771066de2bf125168eca3a7b7d6ff2b87a2",
90
91
  "305931c6edef770033a4f1970b00e5fb1c1728351856a173dbfa497daf563021",
@@ -989,7 +990,11 @@ def _converged_engineering_document(repo: Path, template_path: Path) -> str:
989
990
  value = current_structure.get(key)
990
991
  if isinstance(value, int) and not isinstance(value, bool):
991
992
  converged["structure"][key] = value
992
- for key in ("require_reuse_search", "block_new_responsibility_in_large_file"):
993
+ for key in (
994
+ "require_reuse_search",
995
+ "block_new_responsibility_in_large_file",
996
+ "block_warnings",
997
+ ):
993
998
  value = current_structure.get(key)
994
999
  if isinstance(value, bool):
995
1000
  converged["structure"][key] = value
@@ -1143,8 +1148,8 @@ def _migrate_fast_development_defaults(cfg: dict, repo: Path) -> list[str]:
1143
1148
  if _text(workflow_cfg.get("completion")).lower() != "push":
1144
1149
  workflow_cfg["completion"] = "push"
1145
1150
  changed.append("workflow.completion")
1146
- if _text(workflow_cfg.get("skill_version")) != "4.2.2":
1147
- workflow_cfg["skill_version"] = "4.2.2"
1151
+ if _text(workflow_cfg.get("skill_version")) != "4.2.4":
1152
+ workflow_cfg["skill_version"] = "4.2.4"
1148
1153
  changed.append("workflow.skill_version")
1149
1154
 
1150
1155
  commands_cfg = cfg.setdefault("commands", {})
@@ -1457,16 +1462,16 @@ def cmd_upgrade(args: argparse.Namespace) -> None:
1457
1462
  if current_agents:
1458
1463
  archive_dir = repo / "docs" / "archive" / "workflow"
1459
1464
  archive_header = (
1460
- "# Archived AGENTS.md before auto-coding-skill 4.2.2\n\n"
1465
+ "# Archived AGENTS.md before auto-coding-skill 4.2.4\n\n"
1461
1466
  "This file is historical and non-authoritative. The root AGENTS.md is fully managed.\n"
1462
1467
  "Move any still-current project facts into docs/ENGINEERING.md or docs/project/,\n"
1463
1468
  "without copying workflow rules back into the root AGENTS.md.\n\n---\n\n"
1464
1469
  )
1465
1470
  archive_content = archive_header + current_agents
1466
- archive = archive_dir / "AGENTS.pre-4.2.2.md"
1471
+ archive = archive_dir / "AGENTS.pre-4.2.4.md"
1467
1472
  if archive.exists() and archive.read_text(encoding="utf-8") != archive_content:
1468
1473
  digest = hashlib.sha256(current_agents.encode("utf-8")).hexdigest()[:12]
1469
- archive = archive_dir / f"AGENTS.pre-4.2.2-{digest}.md"
1474
+ archive = archive_dir / f"AGENTS.pre-4.2.4-{digest}.md"
1470
1475
  if not archive.exists():
1471
1476
  add_action("policy", archive, "archive", "historical and non-authoritative")
1472
1477
  if write:
@@ -4138,16 +4143,27 @@ _TEXT_SOURCE_FILENAMES = {
4138
4143
  "tsconfig.json",
4139
4144
  }
4140
4145
  _FUNCTION_START_RE = re.compile(
4141
- r"^\s*(?:export\s+)?(?:async\s+)?(?:def|function|func)\s+[A-Za-z_][\w]*\b"
4146
+ r"^\s*(?:export\s+)?(?:async\s+)?(?:def|function)\s+[A-Za-z_][\w]*\b"
4147
+ r"|^\s*func\s+(?:\([^)]*\)\s*)?[A-Za-z_][\w]*\b"
4142
4148
  r"|^\s*(?:public|private|protected|static|final|async|\s)+\s*[\w<>\[\], ?]+\s+[A-Za-z_]\w*\s*\([^;]*\)\s*\{"
4143
- r"|^\s*(?:export\s+)?(?:const|let|var)\s+[A-Za-z_]\w*\s*=\s*(?:async\s*)?\([^)]*\)\s*=>"
4149
+ r"|^\s*(?:export\s+)?(?:const|let|var)\s+[A-Za-z_]\w*\s*=\s*(?:async\s+)?"
4150
+ r"(?:\([^)]*\)|[A-Za-z_]\w*)\s*(?::\s*[^=]+)?=>"
4151
+ )
4152
+ _ARROW_DECLARATION_RE = re.compile(
4153
+ r"^\s*(?:export\s+)?(?:const|let|var)\s+[A-Za-z_]\w*\s*=\s*(?:async\s+)?"
4144
4154
  )
4155
+ _ARROW_FUNCTION_BODY_RE = re.compile(r"=>\s*(?::\s*[^=]+)?\{")
4145
4156
  _IMPORT_PATTERNS = [
4146
4157
  re.compile(r"^\s*import\s+(?:.+?\s+from\s+)?[\"']([^\"']+)[\"']"),
4147
4158
  re.compile(r"\brequire\(\s*[\"']([^\"']+)[\"']\s*\)"),
4148
4159
  re.compile(r"\bimport\(\s*[\"']([^\"']+)[\"']\s*\)"),
4149
4160
  re.compile(r"^\s*from\s+([A-Za-z_][\w.]*)\s+import\b"),
4150
- re.compile(r"^\s*import\s+([A-Za-z_][\w.]*)(?:\s+as\s+\w+)?\s*$"),
4161
+ re.compile(
4162
+ r"^\s*import\s+(?:static\s+)?"
4163
+ r"([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*(?:\.\*)?)"
4164
+ r"(?:\s+as\s+[A-Za-z_]\w*)?\s*;?\s*"
4165
+ r"(?://.*|/\*.*)?$"
4166
+ ),
4151
4167
  re.compile(r"^\s*import\s+[\"']([^\"']+)[\"']\s*$"),
4152
4168
  re.compile(r"^\s*[\"']([^\"']+/[^\"']*)[\"']\s*$"),
4153
4169
  ]
@@ -4349,19 +4365,657 @@ def _added_lines_by_path(repo: Path, base_ref: str = "") -> dict[str, int]:
4349
4365
  return added
4350
4366
 
4351
4367
 
4352
- def _function_size_warnings(path: str, lines: list[str], threshold: int) -> list[str]:
4368
+ def _ensure_structure_deadline(deadline: Optional[float]) -> None:
4369
+ if deadline is not None and time.monotonic() >= deadline:
4370
+ raise APError("Final changed-scope gate timed out during structure check.")
4371
+
4372
+
4373
+ def _looks_like_regex_start(line: str, index: int) -> bool:
4374
+ prefix = line[:index].rstrip()
4375
+ if not prefix:
4376
+ return True
4377
+ if prefix.endswith(("=", "(", "[", "{", ",", ":", ";", "!", "?", "=>")):
4378
+ return True
4379
+ return bool(re.search(r"\b(?:return|case|throw|yield)\s*$", prefix))
4380
+
4381
+
4382
+ def _python_function_end(
4383
+ lines: list[str],
4384
+ start: int,
4385
+ threshold: int,
4386
+ deadline: Optional[float],
4387
+ ) -> tuple[int, bool]:
4388
+ """Best-effort range for temporarily invalid Python during an edit."""
4389
+ indent = len(lines[start]) - len(lines[start].lstrip())
4390
+ limit = min(len(lines), start + threshold + 1)
4391
+ body_start: Optional[int] = None
4392
+ for index in range(start, limit):
4393
+ if (index - start) % 32 == 0:
4394
+ _ensure_structure_deadline(deadline)
4395
+ header = re.search(r"\)\s*(?:->\s*.*?)?\s*:", lines[index])
4396
+ if not header:
4397
+ continue
4398
+ tail = lines[index][header.end() :].strip()
4399
+ if tail and not tail.startswith("#"):
4400
+ return index + 1, False
4401
+ body_start = index + 1
4402
+ break
4403
+ if body_start is None:
4404
+ return limit, limit < len(lines)
4405
+
4406
+ end = body_start
4407
+ for index in range(body_start, limit):
4408
+ if (index - body_start) % 32 == 0:
4409
+ _ensure_structure_deadline(deadline)
4410
+ stripped = lines[index].strip()
4411
+ if not stripped or stripped.startswith("#"):
4412
+ continue
4413
+ current_indent = len(lines[index]) - len(lines[index].lstrip())
4414
+ if current_indent <= indent:
4415
+ return end, False
4416
+ end = index + 1
4417
+ return limit if limit < len(lines) else end, limit < len(lines)
4418
+
4419
+
4420
+ def _python_function_ranges(
4421
+ lines: list[str],
4422
+ threshold: int,
4423
+ deadline: Optional[float],
4424
+ ) -> list[tuple[int, int, bool]]:
4425
+ _ensure_structure_deadline(deadline)
4426
+ try:
4427
+ tree = ast.parse("\n".join(lines))
4428
+ except (SyntaxError, ValueError):
4429
+ ranges = []
4430
+ for start, line in enumerate(lines):
4431
+ if not re.match(r"^\s*(?:async\s+)?def\s+[A-Za-z_]\w*\b", line):
4432
+ continue
4433
+ end, truncated = _python_function_end(lines, start, threshold, deadline)
4434
+ ranges.append((start, end, truncated))
4435
+ return ranges
4436
+
4437
+ _ensure_structure_deadline(deadline)
4438
+ ranges = []
4439
+ for node in ast.walk(tree):
4440
+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
4441
+ continue
4442
+ start = max(0, int(node.lineno) - 1)
4443
+ end = int(getattr(node, "end_lineno", 0) or node.lineno)
4444
+ ranges.append((start, end, False))
4445
+ return sorted(ranges)
4446
+
4447
+
4448
+ def _find_arrow_locations(
4449
+ lines: list[str],
4450
+ start: int,
4451
+ deadline: Optional[float],
4452
+ ) -> list[tuple[int, int]]:
4453
+ """Find a declaration's top-level arrow candidates with exact columns."""
4454
+ state = "code"
4455
+ escaped = False
4456
+ regex_char_class = False
4457
+ paren_depth = 0
4458
+ bracket_depth = 0
4459
+ brace_depth = 0
4460
+ angle_depth = 0
4461
+ locations: list[tuple[int, int]] = []
4462
+ indent = len(lines[start]) - len(lines[start].lstrip())
4463
+ limit = min(len(lines), start + 200)
4464
+ equals = lines[start].find("=")
4465
+ for line_index in range(start, limit):
4466
+ if (line_index - start) % 32 == 0:
4467
+ _ensure_structure_deadline(deadline)
4468
+ line = lines[line_index]
4469
+ if line_index > start:
4470
+ stripped = line.strip()
4471
+ current_indent = len(line) - len(line.lstrip())
4472
+ if stripped and current_indent <= indent and not (
4473
+ paren_depth or bracket_depth or brace_depth or angle_depth
4474
+ ):
4475
+ return locations
4476
+ char_index = equals + 1 if line_index == start and equals >= 0 else 0
4477
+ while char_index < len(line):
4478
+ char = line[char_index]
4479
+ next_char = line[char_index + 1] if char_index + 1 < len(line) else ""
4480
+ if state == "block_comment":
4481
+ if char == "*" and next_char == "/":
4482
+ state = "code"
4483
+ char_index += 2
4484
+ continue
4485
+ char_index += 1
4486
+ continue
4487
+ if state == "regex":
4488
+ if escaped:
4489
+ escaped = False
4490
+ elif char == "\\":
4491
+ escaped = True
4492
+ elif char == "[":
4493
+ regex_char_class = True
4494
+ elif char == "]":
4495
+ regex_char_class = False
4496
+ elif char == "/" and not regex_char_class:
4497
+ state = "code"
4498
+ char_index += 1
4499
+ continue
4500
+ if state in {"single_quote", "double_quote", "backtick"}:
4501
+ quote = {"single_quote": "'", "double_quote": '"', "backtick": "`"}[state]
4502
+ if escaped:
4503
+ escaped = False
4504
+ elif char == "\\":
4505
+ escaped = True
4506
+ elif char == quote:
4507
+ state = "code"
4508
+ char_index += 1
4509
+ continue
4510
+ if char == "/" and next_char == "/":
4511
+ break
4512
+ if char == "/" and next_char == "*":
4513
+ state = "block_comment"
4514
+ char_index += 2
4515
+ continue
4516
+ if char == "/" and _looks_like_regex_start(line, char_index):
4517
+ state = "regex"
4518
+ regex_char_class = False
4519
+ escaped = False
4520
+ char_index += 1
4521
+ continue
4522
+ if char in {"'", '"', "`"}:
4523
+ state = {"'": "single_quote", '"': "double_quote", "`": "backtick"}[char]
4524
+ escaped = False
4525
+ elif char == "(":
4526
+ paren_depth += 1
4527
+ elif char == ")":
4528
+ paren_depth = max(0, paren_depth - 1)
4529
+ elif char == "[":
4530
+ bracket_depth += 1
4531
+ elif char == "]":
4532
+ bracket_depth = max(0, bracket_depth - 1)
4533
+ elif char == "<" and not (paren_depth or bracket_depth or brace_depth):
4534
+ angle_depth += 1
4535
+ elif char == ">" and angle_depth and not (paren_depth or bracket_depth or brace_depth):
4536
+ angle_depth -= 1
4537
+ elif char == "{":
4538
+ brace_depth += 1
4539
+ elif char == "}":
4540
+ brace_depth = max(0, brace_depth - 1)
4541
+ elif char == "=" and next_char == ">":
4542
+ if not (paren_depth or bracket_depth or brace_depth or angle_depth):
4543
+ locations.append((line_index, char_index))
4544
+ char_index += 2
4545
+ continue
4546
+ elif char == ";" and not (paren_depth or bracket_depth or brace_depth or angle_depth):
4547
+ return locations
4548
+ char_index += 1
4549
+ if line_index > start:
4550
+ stripped = line.strip()
4551
+ current_indent = len(line) - len(line.lstrip())
4552
+ if stripped and current_indent <= indent and not (paren_depth or bracket_depth or brace_depth or angle_depth):
4553
+ return locations
4554
+ return locations
4555
+
4556
+
4557
+ def _arrow_body_kind(lines: list[str], arrow_location: tuple[int, int]) -> str:
4558
+ arrow_line, arrow_column = arrow_location
4559
+ for line_index in range(arrow_line, min(len(lines), arrow_line + 20)):
4560
+ text = lines[line_index][arrow_column + 2 :] if line_index == arrow_line else lines[line_index]
4561
+ stripped = text.strip()
4562
+ if not stripped or stripped.startswith(("//", "/*", "*")):
4563
+ continue
4564
+ return "block" if stripped.startswith("{") else "expression"
4565
+ return "expression"
4566
+
4567
+
4568
+ def _looks_like_return_type_brace(line: str, index: int) -> bool:
4569
+ prefix = line[:index].rstrip()
4570
+ return bool(re.search(r"\b(?:struct|interface)\s*$", prefix))
4571
+
4572
+
4573
+ def _brace_function_end(
4574
+ lines: list[str],
4575
+ start: int,
4576
+ threshold: int,
4577
+ deadline: Optional[float],
4578
+ arrow_location: Optional[tuple[int, int]] = None,
4579
+ suffix: str = "",
4580
+ ) -> Optional[tuple[int, bool]]:
4581
+ depth = 0
4582
+ opened = False
4583
+ state = "code"
4584
+ escaped = False
4585
+ regex_char_class = False
4586
+ paren_depth = 0
4587
+ bracket_depth = 0
4588
+ type_brace_depth = 0
4589
+ arrow_seen = arrow_location is None
4590
+ typescript_declaration = arrow_location is None and suffix in {".ts", ".tsx"}
4591
+ ts_phase = "before_params"
4592
+ ts_pre_angle_depth = ts_pre_brace_depth = 0
4593
+ ts_type_angle_depth = ts_type_paren_depth = ts_type_bracket_depth = 0
4594
+ ts_type_brace_depth = 0
4595
+ ts_type_expects_operand = True
4596
+ limit = min(len(lines), start + threshold + 1)
4597
+
4598
+ for line_index in range(start, limit):
4599
+ if (line_index - start) % 32 == 0:
4600
+ _ensure_structure_deadline(deadline)
4601
+ line = lines[line_index]
4602
+ char_index = 0
4603
+ while char_index < len(line):
4604
+ char = line[char_index]
4605
+ next_char = line[char_index + 1] if char_index + 1 < len(line) else ""
4606
+
4607
+ if state == "block_comment":
4608
+ if char == "*" and next_char == "/":
4609
+ state = "code"
4610
+ char_index += 2
4611
+ continue
4612
+ char_index += 1
4613
+ continue
4614
+ if state == "regex":
4615
+ if escaped:
4616
+ escaped = False
4617
+ elif char == "\\":
4618
+ escaped = True
4619
+ elif char == "[":
4620
+ regex_char_class = True
4621
+ elif char == "]":
4622
+ regex_char_class = False
4623
+ elif char == "/" and not regex_char_class:
4624
+ state = "code"
4625
+ char_index += 1
4626
+ continue
4627
+ if state in {"single_quote", "double_quote"}:
4628
+ if escaped:
4629
+ escaped = False
4630
+ elif char == "\\":
4631
+ escaped = True
4632
+ elif (state == "single_quote" and char == "'") or (
4633
+ state == "double_quote" and char == '"'
4634
+ ):
4635
+ state = "code"
4636
+ char_index += 1
4637
+ continue
4638
+ if state == "backtick":
4639
+ if escaped:
4640
+ escaped = False
4641
+ elif char == "\\":
4642
+ escaped = True
4643
+ elif char == "`":
4644
+ state = "code"
4645
+ char_index += 1
4646
+ continue
4647
+
4648
+ if char == "/" and next_char == "/":
4649
+ break
4650
+ if char == "/" and next_char == "*":
4651
+ state = "block_comment"
4652
+ char_index += 2
4653
+ continue
4654
+ if char == "/" and _looks_like_regex_start(line, char_index):
4655
+ state = "regex"
4656
+ regex_char_class = False
4657
+ escaped = False
4658
+ char_index += 1
4659
+ continue
4660
+ if char == "=" and next_char == ">":
4661
+ if arrow_location == (line_index, char_index):
4662
+ arrow_seen = True
4663
+ if typescript_declaration and ts_phase == "return_type":
4664
+ ts_type_expects_operand = True
4665
+ char_index += 2
4666
+ continue
4667
+ if typescript_declaration and not opened:
4668
+ if char in {"'", '"', "`"}:
4669
+ state = {"'": "single_quote", '"': "double_quote", "`": "backtick"}[char]
4670
+ escaped = False
4671
+ if ts_phase == "return_type":
4672
+ ts_type_expects_operand = False
4673
+ char_index += 1
4674
+ continue
4675
+ if ts_phase == "before_params":
4676
+ if ts_pre_brace_depth > 0:
4677
+ if char == "{":
4678
+ ts_pre_brace_depth += 1
4679
+ elif char == "}":
4680
+ ts_pre_brace_depth -= 1
4681
+ elif char == "<":
4682
+ ts_pre_angle_depth += 1
4683
+ elif char == ">":
4684
+ ts_pre_angle_depth = max(0, ts_pre_angle_depth - 1)
4685
+ elif char == "{":
4686
+ ts_pre_brace_depth = 1
4687
+ elif char == "(" and ts_pre_angle_depth == 0:
4688
+ ts_phase = "params"
4689
+ paren_depth = 1
4690
+ elif ts_phase == "params":
4691
+ if char == "(":
4692
+ paren_depth += 1
4693
+ elif char == ")":
4694
+ paren_depth = max(0, paren_depth - 1)
4695
+ if paren_depth == 0:
4696
+ ts_phase = "after_params"
4697
+ elif ts_phase == "after_params":
4698
+ if char == ":":
4699
+ ts_phase = "return_type"
4700
+ ts_type_expects_operand = True
4701
+ elif char == "{":
4702
+ opened = True
4703
+ depth = 1
4704
+ elif char == ";":
4705
+ return None
4706
+ elif ts_type_brace_depth > 0:
4707
+ if char == "{":
4708
+ ts_type_brace_depth += 1
4709
+ elif char == "}":
4710
+ ts_type_brace_depth -= 1
4711
+ if ts_type_brace_depth == 0:
4712
+ ts_type_expects_operand = False
4713
+ elif char == "{":
4714
+ if (
4715
+ ts_type_angle_depth
4716
+ or ts_type_paren_depth
4717
+ or ts_type_bracket_depth
4718
+ or ts_type_expects_operand
4719
+ ):
4720
+ ts_type_brace_depth = 1
4721
+ ts_type_expects_operand = False
4722
+ else:
4723
+ opened = True
4724
+ depth = 1
4725
+ elif char == "<":
4726
+ ts_type_angle_depth += 1
4727
+ ts_type_expects_operand = True
4728
+ elif char == ">":
4729
+ ts_type_angle_depth = max(0, ts_type_angle_depth - 1)
4730
+ ts_type_expects_operand = False
4731
+ elif char == "(":
4732
+ ts_type_paren_depth += 1
4733
+ ts_type_expects_operand = True
4734
+ elif char == ")":
4735
+ ts_type_paren_depth = max(0, ts_type_paren_depth - 1)
4736
+ ts_type_expects_operand = False
4737
+ elif char == "[":
4738
+ ts_type_bracket_depth += 1
4739
+ ts_type_expects_operand = True
4740
+ elif char == "]":
4741
+ ts_type_bracket_depth = max(0, ts_type_bracket_depth - 1)
4742
+ ts_type_expects_operand = False
4743
+ elif char in "|&?:,.=":
4744
+ ts_type_expects_operand = True
4745
+ elif char.isalpha() or char in {"_", "$"}:
4746
+ word_match = re.match(r"[A-Za-z_$][\w$]*", line[char_index:])
4747
+ word = word_match.group(0) if word_match else char
4748
+ ts_type_expects_operand = word in {
4749
+ "abstract", "asserts", "extends", "in", "infer", "is",
4750
+ "keyof", "new", "readonly", "typeof", "unique",
4751
+ }
4752
+ char_index += len(word)
4753
+ continue
4754
+ elif char.isdigit():
4755
+ ts_type_expects_operand = False
4756
+ elif char == ";" and not (
4757
+ ts_type_angle_depth or ts_type_paren_depth or ts_type_bracket_depth
4758
+ ):
4759
+ return None
4760
+ char_index += 1
4761
+ continue
4762
+ if char == "'":
4763
+ state = "single_quote"
4764
+ escaped = False
4765
+ elif char == '"':
4766
+ state = "double_quote"
4767
+ escaped = False
4768
+ elif char == "`":
4769
+ state = "backtick"
4770
+ escaped = False
4771
+ elif not opened and char == "(":
4772
+ paren_depth += 1
4773
+ elif not opened and char == ")":
4774
+ paren_depth = max(0, paren_depth - 1)
4775
+ elif not opened and char == "[":
4776
+ bracket_depth += 1
4777
+ elif not opened and char == "]":
4778
+ bracket_depth = max(0, bracket_depth - 1)
4779
+ elif char == "{":
4780
+ if not opened:
4781
+ if not arrow_seen:
4782
+ char_index += 1
4783
+ continue
4784
+ if arrow_location is None and (paren_depth > 0 or bracket_depth > 0):
4785
+ char_index += 1
4786
+ continue
4787
+ if type_brace_depth > 0:
4788
+ type_brace_depth += 1
4789
+ char_index += 1
4790
+ continue
4791
+ if arrow_location is None and _looks_like_return_type_brace(line, char_index):
4792
+ type_brace_depth = 1
4793
+ char_index += 1
4794
+ continue
4795
+ opened = True
4796
+ depth += 1
4797
+ elif char == "}" and not opened and type_brace_depth > 0:
4798
+ type_brace_depth -= 1
4799
+ elif char == "}" and opened:
4800
+ depth -= 1
4801
+ if depth == 0:
4802
+ return line_index + 1, False
4803
+ char_index += 1
4804
+ if limit < len(lines):
4805
+ return limit, True
4806
+ return None
4807
+
4808
+
4809
+ _EXPRESSION_CONTINUATION_SUFFIXES = (
4810
+ "?", ":", ".", ",", "+", "-", "*", "/", "%", "&&", "||", "??", "=>",
4811
+ )
4812
+ _EXPRESSION_CONTINUATION_PREFIXES = (
4813
+ ".", "?.", "+", "-", "*", "/", "%", "&&", "||", "??", "?", ":", ",",
4814
+ )
4815
+ _JSX_TAG_RE = re.compile(r"</?>|</?[A-Za-z][A-Za-z0-9_.:-]*(?:\s[^<>]*?)?/?>")
4816
+
4817
+
4818
+ def _expression_arrow_end(
4819
+ lines: list[str],
4820
+ start: int,
4821
+ arrow_location: tuple[int, int],
4822
+ threshold: int,
4823
+ deadline: Optional[float],
4824
+ suffix: str,
4825
+ ) -> tuple[int, bool]:
4826
+ indent = len(lines[start]) - len(lines[start].lstrip())
4827
+ limit = min(len(lines), start + threshold + 1)
4828
+ state = "code"
4829
+ escaped = False
4830
+ regex_char_class = False
4831
+ paren_depth = bracket_depth = brace_depth = 0
4832
+ jsx_mode = False
4833
+ jsx_depth = 0
4834
+ saw_jsx_tag = False
4835
+ arrow_line, arrow_column = arrow_location
4836
+
4837
+ for line_index in range(arrow_line, limit):
4838
+ if (line_index - arrow_line) % 32 == 0:
4839
+ _ensure_structure_deadline(deadline)
4840
+ line = lines[line_index]
4841
+ char_index = arrow_column + 2 if line_index == arrow_line else 0
4842
+ visible: list[str] = []
4843
+ top_level_semicolon = False
4844
+ while char_index < len(line):
4845
+ char = line[char_index]
4846
+ next_char = line[char_index + 1] if char_index + 1 < len(line) else ""
4847
+ if state == "block_comment":
4848
+ if char == "*" and next_char == "/":
4849
+ state = "code"
4850
+ char_index += 2
4851
+ continue
4852
+ char_index += 1
4853
+ continue
4854
+ if state == "regex":
4855
+ if escaped:
4856
+ escaped = False
4857
+ elif char == "\\":
4858
+ escaped = True
4859
+ elif char == "[":
4860
+ regex_char_class = True
4861
+ elif char == "]":
4862
+ regex_char_class = False
4863
+ elif char == "/" and not regex_char_class:
4864
+ state = "code"
4865
+ char_index += 1
4866
+ continue
4867
+ if state in {"single_quote", "double_quote", "backtick"}:
4868
+ quote = {"single_quote": "'", "double_quote": '"', "backtick": "`"}[state]
4869
+ if escaped:
4870
+ escaped = False
4871
+ elif char == "\\":
4872
+ escaped = True
4873
+ elif char == quote:
4874
+ state = "code"
4875
+ char_index += 1
4876
+ continue
4877
+ if char == "/" and next_char == "/":
4878
+ break
4879
+ if char == "/" and next_char == "*":
4880
+ state = "block_comment"
4881
+ char_index += 2
4882
+ continue
4883
+ if char == "/" and _looks_like_regex_start(line, char_index):
4884
+ state = "regex"
4885
+ regex_char_class = False
4886
+ escaped = False
4887
+ visible.append(" ")
4888
+ char_index += 1
4889
+ continue
4890
+ if char in {"'", '"', "`"}:
4891
+ state = {"'": "single_quote", '"': "double_quote", "`": "backtick"}[char]
4892
+ escaped = False
4893
+ visible.append(" ")
4894
+ else:
4895
+ visible.append(char)
4896
+ if char == "(":
4897
+ paren_depth += 1
4898
+ elif char == ")":
4899
+ paren_depth = max(0, paren_depth - 1)
4900
+ elif char == "[":
4901
+ bracket_depth += 1
4902
+ elif char == "]":
4903
+ bracket_depth = max(0, bracket_depth - 1)
4904
+ elif char == "{":
4905
+ brace_depth += 1
4906
+ elif char == "}":
4907
+ brace_depth = max(0, brace_depth - 1)
4908
+ elif char == ";" and not (paren_depth or bracket_depth or brace_depth):
4909
+ top_level_semicolon = True
4910
+ char_index += 1
4911
+
4912
+ code = "".join(visible).strip()
4913
+ if suffix in {".jsx", ".tsx"} and not jsx_mode and code.startswith("<") and not code.startswith(("<=", "<<")):
4914
+ jsx_mode = True
4915
+ if jsx_mode:
4916
+ for match in _JSX_TAG_RE.finditer(code):
4917
+ token = match.group(0)
4918
+ saw_jsx_tag = True
4919
+ if token.startswith("</"):
4920
+ jsx_depth = max(0, jsx_depth - 1)
4921
+ elif token not in {"</>"} and not token.endswith("/>"):
4922
+ jsx_depth += 1
4923
+
4924
+ if paren_depth or bracket_depth or brace_depth or jsx_depth > 0:
4925
+ continue
4926
+ if top_level_semicolon:
4927
+ return line_index + 1, False
4928
+ if jsx_mode and saw_jsx_tag:
4929
+ return line_index + 1, False
4930
+
4931
+ next_index = line_index + 1
4932
+ while next_index < len(lines) and not lines[next_index].strip():
4933
+ next_index += 1
4934
+ if next_index >= len(lines):
4935
+ return line_index + 1, False
4936
+ next_text = lines[next_index].strip()
4937
+ next_indent = len(lines[next_index]) - len(lines[next_index].lstrip())
4938
+ if code.endswith(_EXPRESSION_CONTINUATION_SUFFIXES):
4939
+ continue
4940
+ if next_indent > indent:
4941
+ continue
4942
+ if next_text.startswith(_EXPRESSION_CONTINUATION_PREFIXES):
4943
+ continue
4944
+ if jsx_mode and next_text.startswith(("</", ">")):
4945
+ continue
4946
+ return line_index + 1, False
4947
+
4948
+ return limit, limit < len(lines)
4949
+
4950
+
4951
+ def _function_size_warnings(
4952
+ path: str,
4953
+ lines: list[str],
4954
+ threshold: int,
4955
+ deadline: Optional[float] = None,
4956
+ ) -> list[str]:
4353
4957
  if threshold <= 0:
4354
4958
  return []
4355
- starts: list[int] = []
4356
- for index, line in enumerate(lines):
4357
- if _FUNCTION_START_RE.search(line):
4358
- starts.append(index)
4959
+ suffix = Path(path).suffix.lower()
4960
+ if suffix == ".py":
4961
+ ranges = _python_function_ranges(lines, threshold, deadline)
4962
+ else:
4963
+ candidates: dict[int, list[Optional[tuple[int, int]]]] = {}
4964
+ claimed_arrow_lines: set[int] = set()
4965
+ for index, line in enumerate(lines):
4966
+ if index % 256 == 0:
4967
+ _ensure_structure_deadline(deadline)
4968
+ if _ARROW_DECLARATION_RE.search(line):
4969
+ arrow_locations = _find_arrow_locations(lines, index, deadline)
4970
+ if arrow_locations:
4971
+ candidates[index] = list(arrow_locations)
4972
+ claimed_arrow_lines.update(location[0] for location in arrow_locations)
4973
+ continue
4974
+ if Path(path).name == "Jenkinsfile":
4975
+ if re.match(r"^\s*def\s+[A-Za-z_]\w*\s*\(", line):
4976
+ candidates[index] = [None]
4977
+ elif _FUNCTION_START_RE.search(line):
4978
+ candidates[index] = [None]
4979
+ elif index not in claimed_arrow_lines:
4980
+ arrow_matches = list(_ARROW_FUNCTION_BODY_RE.finditer(line))
4981
+ if arrow_matches:
4982
+ candidates[index] = [(index, match.start()) for match in arrow_matches]
4983
+
4984
+ ranges = []
4985
+ for start, arrow_locations in sorted(candidates.items()):
4986
+ _ensure_structure_deadline(deadline)
4987
+ candidate_ranges: list[tuple[int, bool]] = []
4988
+ for arrow_location in arrow_locations:
4989
+ if arrow_location is not None and _arrow_body_kind(lines, arrow_location) == "expression":
4990
+ candidate_ranges.append(
4991
+ _expression_arrow_end(
4992
+ lines, start, arrow_location, threshold, deadline, suffix
4993
+ )
4994
+ )
4995
+ continue
4996
+ result = _brace_function_end(
4997
+ lines,
4998
+ start,
4999
+ threshold,
5000
+ deadline,
5001
+ arrow_location=arrow_location,
5002
+ suffix=suffix,
5003
+ )
5004
+ if result is not None:
5005
+ candidate_ranges.append(result)
5006
+ if candidate_ranges:
5007
+ end, truncated = max(candidate_ranges, key=lambda item: (item[0], item[1]))
5008
+ ranges.append((start, end, truncated))
5009
+
4359
5010
  warnings: list[str] = []
4360
- for pos, start in enumerate(starts):
4361
- end = starts[pos + 1] if pos + 1 < len(starts) else len(lines)
5011
+ for start, end, truncated in ranges:
4362
5012
  size = end - start
4363
- if size > threshold:
4364
- warnings.append(f"{path}:{start + 1} function-like block has {size} lines (warn>{threshold})")
5013
+ if size <= threshold:
5014
+ continue
5015
+ qualifier = "at least " if truncated else ""
5016
+ warnings.append(
5017
+ f"{path}:{start + 1} function-like block has {qualifier}{size} lines (warn>{threshold})"
5018
+ )
4365
5019
  return warnings
4366
5020
 
4367
5021
 
@@ -5013,6 +5667,7 @@ def cmd_structure_check(args: argparse.Namespace) -> None:
5013
5667
  cfg = _load_cfg(repo)
5014
5668
  requested_scope = str(getattr(args, "scope", "") or "").strip().lower()
5015
5669
  base_ref = str(getattr(args, "base", "") or "")
5670
+ deadline = getattr(args, "deadline", None)
5016
5671
  selected_scope = _select_structure_scope(cfg, repo, requested_scope, base_ref)
5017
5672
 
5018
5673
  structure_cfg = _structure_cfg(cfg)
@@ -5025,6 +5680,9 @@ def cmd_structure_check(args: argparse.Namespace) -> None:
5025
5680
  warn_function_lines = _int_config(structure_cfg.get("max_function_lines_warn"), 120)
5026
5681
  max_added_to_large = _int_config(structure_cfg.get("max_added_lines_to_large_file"), 80)
5027
5682
  block_large_growth = _bool_config(structure_cfg.get("block_new_responsibility_in_large_file"), True)
5683
+ block_warnings = enforcement == "blocking" and _bool_config(
5684
+ structure_cfg.get("block_warnings"), False
5685
+ )
5028
5686
  layer_cfg = _layer_rules_config(structure_cfg)
5029
5687
  block_layer_violations = _bool_config(layer_cfg.get("block"), True)
5030
5688
 
@@ -5036,12 +5694,14 @@ def cmd_structure_check(args: argparse.Namespace) -> None:
5036
5694
  inspected = 0
5037
5695
 
5038
5696
  for path in paths:
5697
+ _ensure_structure_deadline(deadline)
5039
5698
  lines = _read_text_lines(repo, path)
5040
5699
  if lines is None:
5041
5700
  continue
5042
5701
  inspected += 1
5043
5702
  line_count = len(lines)
5044
5703
  accepted_debt = _is_structure_accepted_debt(path, structure_cfg)
5704
+ block_path_size_warnings = block_warnings and not accepted_debt
5045
5705
  if block_file_lines > 0 and line_count > block_file_lines:
5046
5706
  message = f"{path} has {line_count} lines (block>{block_file_lines}); split responsibilities before adding more work"
5047
5707
  if accepted_debt:
@@ -5049,7 +5709,11 @@ def cmd_structure_check(args: argparse.Namespace) -> None:
5049
5709
  else:
5050
5710
  blocking.append(message)
5051
5711
  elif warn_file_lines > 0 and line_count > warn_file_lines:
5052
- warnings.append(f"{path} has {line_count} lines (warn>{warn_file_lines}); prefer extraction before extending it")
5712
+ message = (
5713
+ f"{path} has {line_count} lines (warn>{warn_file_lines}); "
5714
+ "prefer extraction before extending it"
5715
+ )
5716
+ (blocking if block_path_size_warnings else warnings).append(message)
5053
5717
 
5054
5718
  added_lines = added_by_path.get(path, 0)
5055
5719
  if (
@@ -5065,8 +5729,15 @@ def cmd_structure_check(args: argparse.Namespace) -> None:
5065
5729
  "extract a module/helper or document why this is intentionally co-located"
5066
5730
  )
5067
5731
 
5068
- warnings.extend(_function_size_warnings(path, lines, warn_function_lines))
5732
+ function_warnings = _function_size_warnings(
5733
+ path,
5734
+ lines,
5735
+ warn_function_lines,
5736
+ deadline=deadline,
5737
+ )
5738
+ (blocking if block_path_size_warnings else warnings).extend(function_warnings)
5069
5739
  boundary_issues = _structure_boundary_issues(path, lines, structure_cfg)
5740
+ _ensure_structure_deadline(deadline)
5070
5741
  if block_layer_violations:
5071
5742
  blocking.extend(boundary_issues)
5072
5743
  else:
@@ -5091,6 +5762,7 @@ def cmd_structure_check(args: argparse.Namespace) -> None:
5091
5762
  result = {
5092
5763
  "scope": selected_scope,
5093
5764
  "enforcement": enforcement,
5765
+ "block_warnings": block_warnings,
5094
5766
  "inspected_files": inspected,
5095
5767
  "blocking": blocking,
5096
5768
  "warnings": warnings,
@@ -5136,6 +5808,7 @@ def _run_structure_check_for_gate(
5136
5808
  scope=selected_scope,
5137
5809
  base=base_ref,
5138
5810
  json=False,
5811
+ deadline=deadline,
5139
5812
  )
5140
5813
  )
5141
5814
  return ["structure_check"]
@@ -7293,6 +7966,13 @@ def cmd_doctor(args: argparse.Namespace) -> None:
7293
7966
  enforcement = _text(structure_cfg.get("enforcement")).lower()
7294
7967
  if enforcement and enforcement not in {"advisory", "blocking"}:
7295
7968
  validation_errors.append("structure.enforcement must be advisory or blocking")
7969
+ raw_block_warnings = structure_cfg.get("block_warnings")
7970
+ if "block_warnings" in structure_cfg and not isinstance(raw_block_warnings, bool):
7971
+ validation_errors.append("structure.block_warnings must be a boolean")
7972
+ elif raw_block_warnings is True and enforcement != "blocking":
7973
+ advisories.append(
7974
+ "structure.block_warnings has no effect unless structure.enforcement=blocking"
7975
+ )
7296
7976
  gate_cfg = _gate_cfg(cfg)
7297
7977
  if "full_on" in gate_cfg:
7298
7978
  validation_errors.append("gate.full_on is legacy automatic full escalation; run ap.py upgrade")