Skip to content

Commit 0782615

Browse files
squne121claude
andcommitted
fix(#410): address PR #411 iter-3 review (cwd-aware regression_gate, pytest option parser, quote-aware command-sub, C13 schema validation, behavioral tests)
- classify_result accepts and threads cwd to _is_regression_gate_command (B1) - replace broken `for i in range(...)` with while-loop pytest option parser (B2) - has_command_substitution scans only unquoted segments (quoted literals false positives fixed) (B3) - C13 validates scope_class / classification / decision enums + cross-field consistency (skipped→scope_class, regression_gate+go→expected_pass etc.) (B4) - rewrite weak tests using behavioral verification with tmp_path fixtures; add cwd-threading + option-parser + quoted-literal tests (B5) - summary init dict always includes expected_pass / skipped (NB1) Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
1 parent f9565e3 commit 0782615

2 files changed

Lines changed: 371 additions & 19 deletions

File tree

‎.claude/skills/issue-contract-review/scripts/baseline_vc_preflight.py‎

Lines changed: 115 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -357,7 +357,7 @@ def _is_regression_gate_command(command: str, cwd: Optional[str] = None) -> bool
357357
For pytest commands, requires an existing positional path argument.
358358
Args:
359359
command: command string to check
360-
cwd: working directory (defaults to Path.cwd())
360+
cwd: working directory (defaults to Path.cwd() if None)
361361
362362
Returns True if command is a regression gate command, False otherwise.
363363
"""
@@ -410,21 +410,32 @@ def _is_regression_gate_command(command: str, cwd: Optional[str] = None) -> bool
410410
if pytest_idx == -1:
411411
return False
412412

413-
# Collect positional arguments after pytest (skip options starting with -)
413+
# B2: Collect positional arguments after pytest (skip options and their values)
414414
positional_args = []
415-
for i in range(pytest_idx + 1, len(unwrapped)):
415+
i = pytest_idx + 1
416+
n = len(unwrapped)
417+
while i < n:
416418
arg = unwrapped[i]
417-
# Skip option flags (-k, -v, etc.)
419+
# Options that take a separate value
420+
if arg in ("-k", "-m", "-p", "-W", "--rootdir", "--basetemp", "--maxfail", "--tb",
421+
"--lf-name", "--cache-dir", "-c", "-o"):
422+
i += 2 # skip flag and its argument
423+
continue
424+
# Other flags without arguments
418425
if arg.startswith("-"):
419-
# Skip the flag and its argument if it takes one
420-
if arg in ("-k", "-m"):
421-
i += 1
426+
i += 1
422427
continue
428+
# arg is a positional candidate
423429
positional_args.append(arg)
430+
i += 1
424431

425-
# B3: Check if any positional argument exists and is a valid path
432+
# B2: Check if any positional argument exists and is a valid path
426433
for arg in positional_args:
427-
test_path = Path(cwd) / arg
434+
# Handle both relative and absolute paths
435+
if Path(arg).is_absolute():
436+
test_path = Path(arg)
437+
else:
438+
test_path = Path(cwd) / arg
428439
if test_path.exists():
429440
return True
430441

@@ -449,16 +460,34 @@ def _is_negated_search_command(command: str) -> bool:
449460

450461
def has_command_substitution(command: str) -> bool:
451462
"""
452-
B2: Detect command substitution patterns: $(...), `...`, ${...}
463+
B3: Detect command substitution patterns: $(...), `...`, ${...}
464+
ONLY in unquoted segments.
453465
454-
Returns True if the command contains command substitution, False otherwise.
455-
Avoids false positives by not checking inside single-quoted segments.
466+
Single-quoted segments are excluded — they are literals to subprocess.
456467
"""
457-
# Simple check for command substitution patterns
458-
if "$(" in command or "`" in command or "${" in command:
459-
# For the implementation, a simple substring check is acceptable
460-
# (avoiding false positives inside single quotes is a future refinement)
461-
return True
468+
# Scan the original command character by character, tracking quote state.
469+
# Single-quoted content is literal, double-quoted content may have substitution.
470+
in_single = False
471+
in_double = False
472+
i = 0
473+
while i < len(command):
474+
ch = command[i]
475+
if ch == "'" and not in_double:
476+
in_single = not in_single
477+
i += 1
478+
continue
479+
if ch == '"' and not in_single:
480+
in_double = not in_double
481+
i += 1
482+
continue
483+
# Only check for substitution outside of single quotes
484+
if not in_single:
485+
# $(...) or ${...} or backtick
486+
if ch == '$' and i + 1 < len(command) and command[i + 1] in ('(', '{'):
487+
return True
488+
if ch == '`':
489+
return True
490+
i += 1
462491
return False
463492

464493

@@ -467,10 +496,18 @@ def classify_result(
467496
stdout: str,
468497
stderr: str,
469498
command: str,
499+
cwd: Optional[str] = None,
470500
) -> Tuple[str, str, str, Optional[str], str]:
471501
"""
472502
VC 実行結果を分類。
473503
504+
Args:
505+
exit_code: command exit code
506+
stdout: command standard output
507+
stderr: command standard error
508+
command: original command string
509+
cwd: working directory (threaded to _is_regression_gate_command)
510+
474511
戻り値: (classification, category, decision, fix_hint, scope_class)
475512
classification: expected_fail | unexpected_pass | blocked | human_judgment | expected_pass | skipped
476513
category: file_not_found_expected | expected_baseline_fail | unexpected_pass |
@@ -495,7 +532,7 @@ def classify_result(
495532

496533
# AC4: regression_gate prefix detection AFTER static checks
497534
# If it's a regression gate, apply special rules
498-
if _is_regression_gate_command(command):
535+
if _is_regression_gate_command(command, cwd=cwd):
499536
if exit_code == 0:
500537
return "expected_pass", "regression_gate", "go", None, "regression_gate"
501538
else:
@@ -630,6 +667,65 @@ def compute_confidence(category: str) -> str:
630667
return "low"
631668

632669

670+
def check_c13_vc_preflight_decision_consistency(classifications: List[Dict[str, Any]]) -> Tuple[bool, List[str]]:
671+
"""
672+
B4: Validate classifications for schema consistency.
673+
674+
Checks:
675+
- All required fields present (classification, scope_class, decision)
676+
- Enum values valid
677+
- Cross-field consistency (e.g., skipped requires scope_class pr_review_only or runtime_only)
678+
679+
Returns: (is_valid, list_of_failures)
680+
"""
681+
VALID_SCOPE_CLASSES = {"baseline_fail_expected", "regression_gate", "pr_review_only", "runtime_only"}
682+
VALID_CLASSIFICATIONS = {"expected_fail", "expected_pass", "unexpected_pass", "blocked", "human_judgment", "skipped"}
683+
VALID_DECISIONS = {"go", "blocked", "human_judgment"}
684+
685+
failures = []
686+
687+
for i, item in enumerate(classifications):
688+
prefix = f"classifications[{i}]"
689+
690+
# Required fields
691+
if "classification" not in item:
692+
failures.append(f"{prefix}: missing classification")
693+
if "scope_class" not in item:
694+
failures.append(f"{prefix}: missing scope_class")
695+
if "decision" not in item:
696+
failures.append(f"{prefix}: missing decision")
697+
698+
# Enum validation
699+
if "scope_class" in item and item["scope_class"] not in VALID_SCOPE_CLASSES:
700+
failures.append(f"{prefix}: invalid scope_class '{item['scope_class']}' (valid: {VALID_SCOPE_CLASSES})")
701+
if "classification" in item and item["classification"] not in VALID_CLASSIFICATIONS:
702+
failures.append(f"{prefix}: invalid classification '{item['classification']}' (valid: {VALID_CLASSIFICATIONS})")
703+
if "decision" in item and item["decision"] not in VALID_DECISIONS:
704+
failures.append(f"{prefix}: invalid decision '{item['decision']}' (valid: {VALID_DECISIONS})")
705+
706+
# Cross-field consistency rules
707+
if "classification" in item and "scope_class" in item:
708+
# skipped requires scope_class pr_review_only or runtime_only
709+
if item["classification"] == "skipped" and item["scope_class"] not in {"pr_review_only", "runtime_only"}:
710+
failures.append(f"{prefix}: skipped requires scope_class pr_review_only or runtime_only")
711+
712+
# regression_gate consistency
713+
if "scope_class" in item and item["scope_class"] == "regression_gate":
714+
if "decision" in item and "classification" in item:
715+
if item["decision"] == "go" and item["classification"] != "expected_pass":
716+
failures.append(f"{prefix}: regression_gate + go requires classification expected_pass")
717+
if item["decision"] == "blocked" and item["classification"] != "blocked":
718+
failures.append(f"{prefix}: regression_gate + blocked requires classification blocked")
719+
720+
# Skipped routing metadata
721+
if "classification" in item and item["classification"] == "skipped":
722+
for k in ("verification_owner", "deferred_reason", "runtime_verification_required"):
723+
if k not in item:
724+
failures.append(f"{prefix}: skipped requires {k}")
725+
726+
return len(failures) == 0, failures
727+
728+
633729
def generate_contract_review_fragment(status: str, results: List[Dict[str, Any]]) -> Dict[str, Any]:
634730
"""
635731
B8: JSON results を CONTRACT_REVIEW_RESULT_V1.checks.vc_preflight に対応する YAML fragment に変換.
@@ -907,7 +1003,7 @@ def main() -> int:
9071003
)
9081004

9091005
classification, category, decision, fix_hint, scope_class = classify_result(
910-
exit_code, stdout, stderr, command
1006+
exit_code, stdout, stderr, command, cwd=args.cwd
9111007
)
9121008

9131009
verification_owner = None

0 commit comments

Comments
 (0)