| name | suggest-scc-fixes |
| description | Analyzes the latest SCC compliance report and generates detailed Python code suggestions for fixing the most critical issue. |
suggest-scc-fixes
What this skill does
Focused fix generation for SCC compliance issues:
- Finds latest compliance report in
ai_artifacts/compliance_checks/scc/
- Identifies the MOST CRITICAL issue (highest priority)
- Generates detailed fix with:
- Exact Python code to implement
- File locations and line numbers
- Test cases for the fix
- Implementation notes
- Saves to
ai_artifacts/compliance_checks/scc/suggested_scc_fixes.md
Key optimization: Focuses on ONE critical issue at a time to avoid context overflow.
Usage
/suggest-scc-fixes
Automatically finds latest report and generates fix for top priority issue.
Pre-flight: Read .claude/skills/gotchas.md
REQUIRED before generating fix suggestions. Pay special attention to gotchas #1 (no proprietary data tables in suggested code) and #2 (no proprietary source attributions).
Post-run: If you discover a new gotcha during fix generation (a regex pattern that silently misses IDs, a code pattern that looks correct but violates the spec, or a compliance report format change that breaks extraction), append it to .claude/skills/gotchas.md with the same numbered format.
Context Optimization Strategy
Why focus on one issue:
- Reading full compliance report: ~10K tokens
- Analyzing all issues: ~30K tokens
- Generating fixes for all: ~50K+ tokens
- Total naive approach: 90K+ tokens
Optimized approach:
- Extract issue list only: ~2K tokens
- Focus on #1 critical issue: ~5K tokens
- Generate one detailed fix: ~10K tokens
- Total optimized: ~20K tokens (78% reduction)
To fix multiple issues: Run skill multiple times (one issue per run)
Implementation
Run this script
import re
import os
import glob
import subprocess
from datetime import datetime
reports = glob.glob("ai_artifacts/compliance_checks/scc/compliance_report_*.md")
if not reports:
print("No compliance report found. Run /check-scc-compliance first.")
exit(0)
latest_report = max(reports, key=os.path.getmtime)
print(f"Using: {latest_report}")
with open(latest_report) as _f:
report_content = _f.read()
critical_match = re.search(r'### .*CRITICAL(.*?)(?=\n### |\n## |\Z)', report_content, re.DOTALL)
critical_section = critical_match.group(1) if critical_match else report_content
first_issue_match = re.search(
r'1\.\s+\*\*\[?(RULE-[A-Z]+-\d{3}|IMPL-(?:[A-Z]+-)?\d{3}|CTRL-\d{3})\]?\*\*[:\s]+(.+?)(?:\n|$)',
critical_section
)
if not first_issue_match:
val_section = re.search(r'## 1\. Validation Gaps.*?\n(.*?)(?=\n## |\Z)', report_content, re.DOTALL)
if val_section:
first_issue_match = re.search(
r'### (RULE-[A-Z]+-\d{3}|IMPL-(?:[A-Z]+-)?\d{3}):\s+(.+?)(?:\n|$)',
val_section.group(1)
)
if not first_issue_match:
print("No critical issues found in report!")
print()
exit()
issue_id = first_issue_match.group()
issue_title = first_issue_match.group().strip()
()
():
= re.search(,
text, re.DOTALL)
.group().strip()
issue_block_match = re.search(
,
report_content, re.DOTALL
)
issue_details = issue_block_match.group() issue_block_match
issue_info = {
: issue_id,
: issue_title,
: extract_field(issue_details, ),
: extract_field(issue_details, ),
: extract_field(issue_details, ),
: extract_field(issue_details, ),
: extract_field(issue_details, ),
: extract_field(issue_details, ),
}
issue_info[] == :
status = extract_field(issue_details, )
note = extract_field(issue_details, )
issue_info[] =
note != :
issue_info[] = note
file_path =
line_num =
issue_info[] != :
file_match = re.(, issue_info[])
file_match:
file_path = file_match.group()
line_num = (file_match.group())
search_terms = [issue_info[]]
issue_info.get(, ) (issue_info):
search_terms.extend([, , ])
issue_info.get(, ).lower():
search_terms.extend([, , ])
issue_info.get(, ).lower():
search_terms.extend([, ])
:
keywords = [w w issue_info[].split() (w) > w[].isupper()]
search_terms.extend(keywords[:])
scc_files = [, ,
, ]
grep_results = []
term search_terms:
sf scc_files:
:
result = subprocess.run([, , term, sf], capture_output=, text=)
result.stdout.strip():
line result.stdout.strip().split():
grep_results.append()
Exception:
grep_results line_num :
first_hit = grep_results[]
parts = first_hit.split()
(parts) >= :
file_path = parts[]
:
line_num = (parts[])
ValueError:
line_num:
(file_path) f:
lines = f.readlines()
start = (, line_num - )
context = .join(lines[start:start + ])
()
:
(file_path) f:
context = .join(f.readlines()[:])
()
()
():
spec_content:
search_term
rule_match = re.search(, spec_content)
rule_match:
rule_id_found = rule_match.group()
cea_match = re.search(, spec_content)
cea_match:
rule_id_found
search_term
():
spec_path =
spec_content =
:
rule_id_local = _issue_info[]
result = subprocess.run([, , , , spec_path],
capture_output=, text=)
spec_content = result.stdout.strip() result.stdout.strip()
Exception:
spec_content =
_issue_info[] (_issue_info):
spec_ref = extract_spec_reference(spec_content, ) spec_content \
_issue_info[].lower() _issue_info[]:
spec_ref = extract_spec_reference(spec_content, ) spec_content \
What: Add 4-line header validation at the start of read() method.
Why: This is required by {spec_ref} in the SCC specification.
Spec Reference: See ai_artifacts/specs/scc/scc_specs_summary.md -> Section 1.1 "File Header"
-> [RULE-FMT-001] and [IMPL-FMT-001] for complete validation requirements.
'''
else:
rule_id_local = _issue_info['id']
spec_ref = extract_spec_reference(spec_content, rule_id_local) if spec_content else rule_id_local
code_locations = ""
if grep_results:
code_locations = "\n".join(f" - `{hit}`" for hit in grep_results[:5])
else:
code_locations = f" - `{_issue_info.get('file', 'pycaption/scc/__init__.py')}` (search for related code)"
return f'''
Fix Required
Relevant code locations (from grep):
{code_locations}
Current behavior: {_issue_info["current"]}
Expected behavior: {_issue_info["expected"]}
Approach:
- Open the file(s) listed above at the indicated lines
- Identify the code handling this feature
- Modify to match the expected behavior per {spec_ref}
- Add validation if the issue is about missing checks
Why: This is required by {spec_ref} in the SCC specification.
- Severity: {_issue_info.get("severity", "UNKNOWN")} (per spec compliance level)
- Impact: {_issue_info.get("impact", "May cause interoperability issues or incorrect caption rendering")}
Spec Reference: See ai_artifacts/specs/scc/scc_specs_summary.md -> Search for [{rule_id_local}]
for complete specification details, validation criteria, and test patterns.
'''
def generate_test_cases(_issue_info):
if 'RU4' in _issue_info['title'] or '94a7' in str(_issue_info):
return '''
def test_ru4_control_code_correct_hex():
from pycaption.scc import SCCReader
scc_content = """Scenarist_SCC V1.0
00:00:00:00\t9427 9427 94ad 94ad
"""
reader = SCCReader()
caption_set = reader.read(scc_content)
assert caption_set is not None
'''
elif 'header' in _issue_info['title'].lower():
return '''
def test_header_validation_rejects_invalid():
from pycaption.scc import SCCReader
from pycaption.exceptions import CaptionReadNoCaptions
import pytest
reader = SCCReader()
invalid_scc = """scenarist_scc v1.0
00:00:00:00\t9420 9420
"""
with pytest.raises(CaptionReadNoCaptions, match="Invalid SCC file"):
reader.read(invalid_scc)
valid_scc = """Scenarist_SCC V1.0
00:00:00:00\t9420 9420
"""
result = reader.read(valid_scc)
assert result is not None
'''
else:
return f'''
def test_{_issue_info["id"].lower().replace("-", "_")}():
from pycaption.scc import SCCReader
scc_content = """Scenarist_SCC V1.0
00:00:00:00\t9420 9420
"""
reader = SCCReader()
result = reader.read(scc_content)
assert result is not None
'''
def generate_implementation_notes(_issue_info):
notes = []
rule_id_local = _issue_info['id']
if _issue_info['severity'] == 'MUST':
notes.append(f"**MUST-level requirement**: This is mandatory per **{rule_id_local}** in the CEA-608/SCC specification.")
elif _issue_info['severity'] == 'SHOULD':
notes.append(f"**SHOULD-level requirement**: Recommended by **{rule_id_local}** for best practices and compatibility.")
if 'interoperability' in _issue_info.get('impact', '').lower():
notes.append("**Interoperability impact**: Required for compatibility with industry-standard tools.")
notes.append(f"**Specification reference**:")
notes.append(f" - Primary: `ai_artifacts/specs/scc/scc_specs_summary.md` -> Search for `[{rule_id_local}]`")
return '\n'.join(f'- {note}' if not note.startswith(' ') else note for note in notes)
def estimate_complexity(_issue_info):
if any(word in _issue_info.get('fix', '').lower() for word in ['change', 'character', 'single']):
return "Low (simple change)"
elif any(word in _issue_info.get('fix', '').lower() for word in ['add', 'line', 'validation']):
return "Medium (add code)"
else:
return "High (complex implementation)"
def estimate_time(_issue_info):
fix_text = _issue_info.get('fix', '').lower()
if 'character' in fix_text or '30 second' in fix_text:
return "< 1 minute"
elif 'line' in fix_text or '5 minute' in fix_text:
return "5-10 minutes"
else:
return "15-30 minutes"
===== Step 5: Generate Report =====
fix_content = f"""# SCC Compliance Fix Suggestions
Generated: {datetime.now().strftime("%Y-%m-%d")}
Source Report: {latest_report}
Focus: Most Critical Issue Only
Issue Being Fixed
Issue ID: {issue_info['id']}
Title: {issue_info['title']}
Severity: {issue_info['severity']}
Priority: CRITICAL (Issue #1)
Current State: {issue_info['current']}
Required: {issue_info['expected']}
Impact: {issue_info['impact']}
Specification Context: This issue violates {issue_info['id']} in the SCC/CEA-608 specification.
See ai_artifacts/specs/scc/scc_specs_summary.md for complete specification text.
Proposed Fix
Location
File: {file_path}
Line: {line_num if line_num else 'N/A'}
Implementation
{generate_code_fix(issue_info, context)}
Testing
Test Cases Required
{generate_test_cases(issue_info)}
Verification Steps
- Apply the fix above
- Run tests:
pytest tests/test_scc.py -v
- Verify against spec:
- Open
ai_artifacts/specs/scc/scc_specs_summary.md
- Search for
[{issue_info['id']}]
- Confirm fix meets all requirements
- Test with real SCC file (if applicable)
- Check interoperability: Verify output works with standard tools
Specification Details
Rule: {issue_info['id']}
Level: {issue_info['severity']} (mandatory compliance)
Location in Spec: ai_artifacts/specs/scc/scc_specs_summary.md
Additional Notes
{generate_implementation_notes(issue_info)}
Next Steps
After fixing this issue:
- Mark {issue_info['id']} as resolved
- Run
/suggest-scc-fixes again for next critical issue
- Re-run
/check-scc-compliance to verify fix and get updated report
- Review full spec section in
ai_artifacts/specs/scc/scc_specs_summary.md if needed
Generated by: suggest-scc-fixes skill
Fix complexity: {estimate_complexity(issue_info)}
Estimated time: {estimate_time(issue_info)}
Spec-backed: All fixes reference specification requirements
"""
os.makedirs("ai_artifacts/compliance_checks/scc", exist_ok=True)
with open("ai_artifacts/compliance_checks/scc/suggested_scc_fixes.md", 'w') as _f:
_f.write(fix_content)
print(f"""
Fix suggestion generated!
Issue: {issue_info['id']} - {issue_info['title']}
Saved to: ai_artifacts/compliance_checks/scc/suggested_scc_fixes.md
Summary:
Severity: {issue_info['severity']}
File: {file_path}
Complexity: {estimate_complexity(issue_info)}
Time: {estimate_time(issue_info)}
Next Steps:
- Review the suggested fix in the report
- Apply the code changes
- Run the test cases
- Run /suggest-scc-fixes again for next issue
""")
---
## Success Criteria
- **Context-efficient** - Uses ~20K tokens (vs 90K+ for all issues)
- **Focused** - One issue at a time with complete fix
- **Actionable** - Exact code, not generic advice
- **Testable** - Includes test cases
- **Iterative** - Run multiple times for multiple issues
- **Fast** - Completes in ~1-2 minutes
---
## Important Notes
**Why one issue at a time:**
- Keeps context window manageable
- Allows detailed, specific fixes
- User can review and apply incrementally
- Can re-run for next issue after first is fixed
**Priority order:**
1. First run: Fix issue #1 (most critical)
2. Second run: Fix issue #2 (next critical)
3. Continue until all critical issues resolved
**Error handling:**
- No report found -> Tell user to run check-scc-compliance
- No issues found -> Celebrate! All compliant
- Can't parse issue -> Use generic template