mirror of
https://github.com/catlog22/Claude-Code-Workflow.git
synced 2026-03-07 16:41:06 +08:00
feat: Add role specifications for 三省六部 architecture
- Introduced role specifications for 尚书省 (shangshu), 刑部 (xingbu), and 中书省 (zhongshu) to facilitate task management and execution flow. - Implemented quality gates for each phase of the process to ensure compliance and quality assurance. - Established a coordinator role to manage the overall workflow and task distribution among the departments. - Created a team configuration file to define roles, responsibilities, and routing rules for task execution. - Added localization support for DeepWiki in both English and Chinese, enhancing accessibility for users.
This commit is contained in:
56
.claude/skills/skill-simplify/SKILL.md
Normal file
56
.claude/skills/skill-simplify/SKILL.md
Normal file
@@ -0,0 +1,56 @@
|
||||
---
|
||||
name: skill-simplify
|
||||
description: SKILL.md simplification with functional integrity verification. Analyze redundancy, optimize content, check no functionality lost. Triggers on "simplify skill", "optimize skill", "skill-simplify".
|
||||
allowed-tools: AskUserQuestion, Read, Write, Edit, Bash, Glob, Grep
|
||||
---
|
||||
|
||||
# Skill Simplify
|
||||
|
||||
Three-phase pipeline: analyze functional inventory, apply optimization rules, verify integrity.
|
||||
|
||||
**Phase Reference Documents** (read on-demand):
|
||||
|
||||
| Phase | Document | Purpose |
|
||||
|-------|----------|---------|
|
||||
| 1 | [phases/01-analysis.md](phases/01-analysis.md) | Extract functional inventory, identify redundancy, validate pseudo-code format |
|
||||
| 2 | [phases/02-optimize.md](phases/02-optimize.md) | Apply simplification rules, fix format issues |
|
||||
| 3 | [phases/03-check.md](phases/03-check.md) | Verify functional integrity, validate format |
|
||||
|
||||
## Input Processing
|
||||
|
||||
```javascript
|
||||
const targetPath = input.trim()
|
||||
const targetFile = targetPath.endsWith('.md') ? targetPath : `${targetPath}/SKILL.md`
|
||||
const originalContent = Read(targetFile)
|
||||
const originalLineCount = originalContent.split('\n').length
|
||||
```
|
||||
|
||||
## TodoWrite Pattern
|
||||
|
||||
```javascript
|
||||
TodoWrite({ todos: [
|
||||
{ content: `Phase 1: Analyzing ${targetFile}`, status: "in_progress", activeForm: "Extracting functional inventory" },
|
||||
{ content: "Phase 2: Optimize", status: "pending" },
|
||||
{ content: "Phase 3: Integrity Check", status: "pending" }
|
||||
]})
|
||||
```
|
||||
|
||||
## Core Rules
|
||||
|
||||
1. **Preserve ALL functional elements**: Code blocks with logic, agent calls, data structures, routing, error handling, input/output specs
|
||||
2. **Only reduce descriptive content**: Flowcharts, verbose comments, duplicate sections, examples that repeat logic
|
||||
3. **Never summarize algorithm logic**: If-else branches, function bodies, schemas must remain verbatim
|
||||
4. **Classify code blocks**: Distinguish `functional` (logic, routing, schemas) from `descriptive` (ASCII art, examples, display templates) — only descriptive blocks may be deleted
|
||||
5. **Merge equivalent variants**: Single/multi-perspective templates differing only by a parameter → one template with variant comment
|
||||
6. **Fix format issues**: Nested backtick template literals in code fences → convert to prose; hardcoded option lists → flag for dynamic generation; workflow handoff references → ensure execution steps present
|
||||
7. **Validate pseudo-code**: Check bracket matching, variable consistency, structural completeness
|
||||
8. **Quantitative verification**: Phase 3 counts must match Phase 1 counts for functional categories; descriptive block decreases are expected
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Error | Resolution |
|
||||
|-------|------------|
|
||||
| Target file not found | Report error, stop |
|
||||
| Check FAIL (missing functional elements) | Show delta, revert to original, report which elements lost |
|
||||
| Check WARN (descriptive decrease or merge) | Show delta with justification |
|
||||
| Format issues found | Report in check, fix in Phase 2 |
|
||||
224
.claude/skills/skill-simplify/phases/01-analysis.md
Normal file
224
.claude/skills/skill-simplify/phases/01-analysis.md
Normal file
@@ -0,0 +1,224 @@
|
||||
# Phase 1: Functional Analysis
|
||||
|
||||
Read target file, extract functional inventory with code block classification, identify redundancy, validate pseudo-code format, and produce optimization plan.
|
||||
|
||||
## Objective
|
||||
|
||||
- Build quantitative functional inventory with code block classification (baseline for Phase 3)
|
||||
- Identify redundancy categories with specific line ranges
|
||||
- Detect pseudo-code format issues
|
||||
- Produce optimization plan with estimated line savings
|
||||
|
||||
## Execution
|
||||
|
||||
### Step 1.1: Read & Measure Target
|
||||
|
||||
```javascript
|
||||
const originalContent = Read(targetFile)
|
||||
const lines = originalContent.split('\n')
|
||||
const originalLineCount = lines.length
|
||||
```
|
||||
|
||||
### Step 1.2: Extract Functional Inventory
|
||||
|
||||
Count and catalog every functional element. These counts are the **baseline** for Phase 3 verification.
|
||||
|
||||
```javascript
|
||||
const inventory = {
|
||||
// Code structures — with role classification
|
||||
codeBlocks: [], // { startLine, endLine, language, purpose, role: 'functional'|'descriptive' }
|
||||
agentCalls: [], // { line, agentType, description, mergeGroup?: string }
|
||||
dataStructures: [], // { line, name, type: 'object'|'array'|'schema' }
|
||||
|
||||
// Logic elements
|
||||
routingBranches: [], // { line, condition, outcomes[] }
|
||||
errorHandlers: [], // { line, errorType, resolution }
|
||||
conditionalLogic: [], // { line, condition, trueAction, falseAction }
|
||||
|
||||
// Interface elements
|
||||
askUserQuestions: [], // { line, questionCount, headers[], optionType: 'static'|'dynamic' }
|
||||
inputModes: [], // { line, mode, description }
|
||||
outputArtifacts: [], // { line, artifact, format }
|
||||
|
||||
// Structural elements
|
||||
todoWriteBlocks: [], // { line, phaseCount }
|
||||
phaseHandoffs: [], // { line, fromPhase, toPhase }
|
||||
skillInvocations: [], // { line, skillName, hasExecutionSteps: boolean }
|
||||
|
||||
// Reference elements
|
||||
tables: [], // { startLine, endLine, columns }
|
||||
schemas: [], // { line, schemaName, fields[] }
|
||||
|
||||
// Format issues
|
||||
formatIssues: [], // { line, type, description, severity: 'error'|'warning' }
|
||||
|
||||
// Totals (computed)
|
||||
counts: {}
|
||||
}
|
||||
```
|
||||
|
||||
**Extraction rules**:
|
||||
- **Code blocks**: Match ` ```language ... ``` ` pairs, record start/end/language/first-line-as-purpose
|
||||
- **Agent calls**: Match `Agent(`, `Task(`, `subagent_type=`, record type and prompt summary
|
||||
- **Data structures**: Match `const xxx = {`, `const xxx = [`, JSON schema objects
|
||||
- **Routing branches**: Match `if/else`, `switch/case`, ternary `? :` with meaningful branching
|
||||
- **Error handlers**: Match `catch`, error table rows `| Error |`, fallback patterns
|
||||
- **AskUserQuestion**: Match `AskUserQuestion({`, count questions array length
|
||||
- **Input modes**: Match `Mode 1/2/3`, `--flag`, argument parsing
|
||||
- **Output artifacts**: Match `Write(`, `Output:`, file path patterns in comments
|
||||
- **TodoWrite**: Match `TodoWrite({`, count todo items
|
||||
- **Phase handoffs**: Match `Read("phases/`, `Skill(`, `proceed_to_next_phase`
|
||||
- **Tables**: Match `| header |` markdown table blocks
|
||||
- **Schemas**: Match schema references, JSON structure definitions
|
||||
|
||||
### Step 1.2.1: Code Block Role Classification
|
||||
|
||||
For each code block, determine its role:
|
||||
|
||||
| Role | Criteria | Examples |
|
||||
|------|----------|---------|
|
||||
| `functional` | Contains algorithm logic, routing branches, conditional code, agent calls, schema definitions, data processing, AskUserQuestion, Skill invocations | `if/else`, `Agent({...})`, `const schema = {...}`, `Bash({...})` |
|
||||
| `descriptive` | Contains ASCII art, usage examples, display templates, illustrative good/bad comparisons, folder structure trees | `┌───┐`, `# Example usage`, `❌ Bad / ✅ Good`, `├── file.ts` |
|
||||
|
||||
**Classification rules**:
|
||||
- If block contains ANY of: `Agent(`, `Bash(`, `AskUserQuestion(`, `if (`, `switch`, `Skill(`, `Write(`, `Read(`, `TodoWrite(` → `functional`
|
||||
- If block language is `bash` and content is only example invocations (no logic) → `descriptive`
|
||||
- If block has no language tag and contains only ASCII box-drawing characters → `descriptive`
|
||||
- If block is labeled as "Example" in surrounding markdown heading → `descriptive`
|
||||
- **Default**: `functional` (conservative)
|
||||
|
||||
### Step 1.2.2: Pseudo-Code Format Validation
|
||||
|
||||
Scan all `functional` code blocks for format issues:
|
||||
|
||||
| Check | Detection | Severity |
|
||||
|-------|-----------|----------|
|
||||
| **Nested backticks** | Template literal `` ` `` inside ` ```javascript ``` ` code fence | warning |
|
||||
| **Unclosed brackets** | Unmatched `{`, `(`, `[` in code block | error |
|
||||
| **Undefined references** | `${variable}` where variable is never declared in the block or prior blocks | warning |
|
||||
| **Inconsistent indentation** | Mixed tabs/spaces or inconsistent nesting depth | warning |
|
||||
| **Dead code patterns** | Commented-out code blocks (`// if (`, `/* ... */` spanning 5+ lines) | warning |
|
||||
| **Missing return/output** | Function-like block with no return, Write, or console.log | warning |
|
||||
|
||||
```javascript
|
||||
inventory.formatIssues = validatePseudoCode(inventory.codeBlocks.filter(b => b.role === 'functional'))
|
||||
```
|
||||
|
||||
### Step 1.2.3: Compute Totals
|
||||
|
||||
```javascript
|
||||
inventory.counts = {
|
||||
codeBlocks: inventory.codeBlocks.length,
|
||||
functionalCodeBlocks: inventory.codeBlocks.filter(b => b.role === 'functional').length,
|
||||
descriptiveCodeBlocks: inventory.codeBlocks.filter(b => b.role === 'descriptive').length,
|
||||
agentCalls: inventory.agentCalls.length,
|
||||
dataStructures: inventory.dataStructures.length,
|
||||
routingBranches: inventory.routingBranches.length,
|
||||
errorHandlers: inventory.errorHandlers.length,
|
||||
conditionalLogic: inventory.conditionalLogic.length,
|
||||
askUserQuestions: inventory.askUserQuestions.length,
|
||||
inputModes: inventory.inputModes.length,
|
||||
outputArtifacts: inventory.outputArtifacts.length,
|
||||
todoWriteBlocks: inventory.todoWriteBlocks.length,
|
||||
phaseHandoffs: inventory.phaseHandoffs.length,
|
||||
skillInvocations: inventory.skillInvocations.length,
|
||||
tables: inventory.tables.length,
|
||||
schemas: inventory.schemas.length,
|
||||
formatIssues: inventory.formatIssues.length
|
||||
}
|
||||
```
|
||||
|
||||
### Step 1.3: Identify Redundancy Categories
|
||||
|
||||
Scan for each category, record specific line ranges:
|
||||
|
||||
```javascript
|
||||
const redundancyMap = {
|
||||
deletable: [], // { category, startLine, endLine, reason, estimatedSave }
|
||||
simplifiable: [], // { category, startLine, endLine, strategy, estimatedSave }
|
||||
mergeable: [], // { items: [{startLine, endLine}], mergeStrategy, estimatedSave }
|
||||
formatFixes: [], // { line, type, fix }
|
||||
languageUnify: [] // { line, currentLang, targetLang }
|
||||
}
|
||||
```
|
||||
|
||||
**Deletable** (remove entirely, no functional loss):
|
||||
|
||||
| Pattern | Detection |
|
||||
|---------|-----------|
|
||||
| Duplicate Overview | `## Overview` that restates frontmatter description |
|
||||
| ASCII flowchart | Flowchart that duplicates Phase Summary table or implementation structure |
|
||||
| "When to use" section | Usage guidance not needed for execution |
|
||||
| Best Practices section | Advisory content duplicating Core Rules |
|
||||
| Duplicate examples | Code examples that repeat logic shown elsewhere |
|
||||
| Folder structure duplicate | ASCII tree repeating Output Artifacts table |
|
||||
| "Next Phase" paragraphs | Prose between phases when TodoWrite handles flow |
|
||||
| Descriptive code blocks | Code blocks classified as `descriptive` whose content is covered by surrounding prose or tables |
|
||||
|
||||
**Simplifiable** (compress, preserve meaning):
|
||||
|
||||
| Pattern | Strategy |
|
||||
|---------|----------|
|
||||
| Verbose comments in code blocks | Reduce to single-line; keep only non-obvious logic comments |
|
||||
| Multi-line console.log | Compress to single template literal |
|
||||
| Wordy section intros | Remove "In this phase, we will..." preamble |
|
||||
| Exploration prompt bloat | Trim to essential instructions, remove generic advice |
|
||||
| Display-format code blocks | Convert code blocks that only define output format (console.log with template) to prose description |
|
||||
|
||||
**Mergeable** (combine related structures):
|
||||
|
||||
| Pattern | Strategy |
|
||||
|---------|----------|
|
||||
| Multiple similar AskUserQuestion calls | Extract shared function with mode parameter |
|
||||
| Repeated Option routing | Unify into single dispatch |
|
||||
| Sequential single-line operations | Combine into one code block |
|
||||
| TodoWrite full blocks x N | Template once + delta comments |
|
||||
| Duplicate error handling tables | Merge into single table |
|
||||
| Equivalent template variants | Single/multi-perspective templates → one template with variant comment |
|
||||
| Multiple output artifact tables | Merge into single combined table |
|
||||
|
||||
**Format fixes** (pseudo-code quality):
|
||||
|
||||
| Pattern | Fix |
|
||||
|---------|-----|
|
||||
| Nested backtick template literals | Convert surrounding code block to prose description, or use 4-backtick fence |
|
||||
| Hardcoded option lists | Add comment: `// Generate dynamically from {context source}` |
|
||||
| Workflow handoff without execution steps | Add execution steps referencing the target command's actual interface |
|
||||
| Unclosed brackets | Fix bracket matching |
|
||||
|
||||
**Language unification**:
|
||||
- Detect mixed Chinese/English in functional comments
|
||||
- Recommend consistent language (match majority)
|
||||
|
||||
### Step 1.4: Build Optimization Plan
|
||||
|
||||
```javascript
|
||||
const optimizationPlan = {
|
||||
targetFile,
|
||||
originalLineCount,
|
||||
estimatedReduction: redundancyMap.deletable.reduce((s, d) => s + d.estimatedSave, 0)
|
||||
+ redundancyMap.simplifiable.reduce((s, d) => s + d.estimatedSave, 0)
|
||||
+ redundancyMap.mergeable.reduce((s, d) => s + d.estimatedSave, 0),
|
||||
categories: {
|
||||
deletable: { count: redundancyMap.deletable.length, totalLines: '...' },
|
||||
simplifiable: { count: redundancyMap.simplifiable.length, totalLines: '...' },
|
||||
mergeable: { count: redundancyMap.mergeable.length, totalLines: '...' },
|
||||
formatFixes: { count: redundancyMap.formatFixes.length },
|
||||
languageUnify: { count: redundancyMap.languageUnify.length }
|
||||
},
|
||||
// Ordered: delete → merge → simplify → format
|
||||
operations: [
|
||||
...redundancyMap.deletable.map(d => ({ type: 'delete', ...d, priority: 1 })),
|
||||
...redundancyMap.mergeable.map(m => ({ type: 'merge', ...m, priority: 2 })),
|
||||
...redundancyMap.simplifiable.map(s => ({ type: 'simplify', ...s, priority: 3 })),
|
||||
...redundancyMap.formatFixes.map(f => ({ type: 'format', ...f, priority: 4 }))
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Display plan summary: category counts, estimated reduction percentage, sections NOT changed (functional core).
|
||||
|
||||
## Output
|
||||
|
||||
- **Variable**: `analysisResult = { inventory, redundancyMap, optimizationPlan, originalContent, originalLineCount }`
|
||||
- **TodoWrite**: Mark Phase 1 completed, Phase 2 in_progress
|
||||
107
.claude/skills/skill-simplify/phases/02-optimize.md
Normal file
107
.claude/skills/skill-simplify/phases/02-optimize.md
Normal file
@@ -0,0 +1,107 @@
|
||||
# Phase 2: Optimize
|
||||
|
||||
Apply simplification rules from analysisResult to produce optimized content. Write result to disk.
|
||||
|
||||
## Objective
|
||||
|
||||
- Execute all optimization operations in priority order (delete → merge → simplify → format)
|
||||
- Preserve every functional element identified in Phase 1 inventory
|
||||
- Fix pseudo-code format issues
|
||||
- Write optimized content back to target file
|
||||
|
||||
## Execution
|
||||
|
||||
### Step 2.1: Apply Operations in Order
|
||||
|
||||
Process `analysisResult.optimizationPlan.operations` sorted by priority:
|
||||
|
||||
**Priority 1 — Delete** (safest, highest impact):
|
||||
|
||||
| Target Pattern | Action |
|
||||
|----------------|--------|
|
||||
| Duplicate Overview section | Remove `## Overview` if it restates frontmatter `description` |
|
||||
| ASCII flowchart | Remove if Phase Summary table or implementation structure covers same info |
|
||||
| "When to use" / "Use Cases" section | Remove entirely |
|
||||
| Best Practices section | Remove if content duplicates Core Rules |
|
||||
| Duplicate folder structure | Remove ASCII tree if Output Artifacts table covers same info |
|
||||
| Redundant "Next Phase" prose | Remove when TodoWrite handles flow |
|
||||
| Standalone example sections | Remove if logic already demonstrated inline |
|
||||
| Descriptive code blocks | Remove if content covered by surrounding prose or tables |
|
||||
|
||||
**Priority 2 — Merge** (structural optimization):
|
||||
|
||||
| Target Pattern | Action |
|
||||
|----------------|--------|
|
||||
| Multiple similar AskUserQuestion blocks | Extract shared function with mode parameter |
|
||||
| Repeated Option A/B/C routing | Unify into single dispatch |
|
||||
| Sequential single-line bash commands | Combine into single code block |
|
||||
| TodoWrite full blocks x N | Template ONCE, subsequent as one-line comment |
|
||||
| Duplicate error handling across sections | Merge into single `## Error Handling` table |
|
||||
| Equivalent template variants | Single/multi templates → one template with `// For multi: add Perspective` comment |
|
||||
| Multiple output artifact tables | Merge into single combined table with Phase column |
|
||||
|
||||
**Priority 3 — Simplify** (compress descriptive content):
|
||||
|
||||
| Target Pattern | Action |
|
||||
|----------------|--------|
|
||||
| Verbose inline comments | Reduce to single-line; remove obvious restatements |
|
||||
| Display-format code blocks | Convert `console.log` with template literal to prose describing output format |
|
||||
| Wordy section introductions | Remove preamble sentences |
|
||||
| Exploration/agent prompt padding | Remove generic advice |
|
||||
| Success Criteria lists > 7 items | Trim to essential 5-7, remove obvious/generic |
|
||||
|
||||
**Priority 4 — Format fixes** (pseudo-code quality):
|
||||
|
||||
| Target Pattern | Action |
|
||||
|----------------|--------|
|
||||
| Nested backtick template literals | Convert code block to prose description, or use 4-backtick fence |
|
||||
| Hardcoded option lists | Replace with dynamic generation: describe source of options + generation logic |
|
||||
| Workflow handoff without execution steps | Add concrete steps referencing target command's interface (e.g., pipe to `ccw issue create`) |
|
||||
| Unclosed brackets | Fix bracket matching |
|
||||
| Undefined variable references | Add declaration or link to source |
|
||||
|
||||
### Step 2.2: Language Unification (if applicable)
|
||||
|
||||
```javascript
|
||||
if (analysisResult.redundancyMap.languageUnify.length > 0) {
|
||||
// Detect majority language, unify non-functional text
|
||||
// DO NOT change: variable names, function names, schema fields, error messages in code
|
||||
}
|
||||
```
|
||||
|
||||
### Step 2.3: Write Optimized Content
|
||||
|
||||
```javascript
|
||||
Write(targetFile, optimizedContent)
|
||||
const optimizedLineCount = optimizedContent.split('\n').length
|
||||
const reduction = originalLineCount - optimizedLineCount
|
||||
const reductionPct = Math.round(reduction / originalLineCount * 100)
|
||||
```
|
||||
|
||||
### Step 2.4: Preserve Optimization Record
|
||||
|
||||
```javascript
|
||||
const optimizationRecord = {
|
||||
deletedSections: [], // section names removed
|
||||
mergedGroups: [], // { from: [sections], to: description }
|
||||
simplifiedAreas: [], // { section, strategy }
|
||||
formatFixes: [], // { line, type, fix }
|
||||
linesBefore: originalLineCount,
|
||||
linesAfter: optimizedLineCount
|
||||
}
|
||||
```
|
||||
|
||||
## Key Rules
|
||||
|
||||
1. **Never modify functional code blocks** — only compress comments/whitespace within them
|
||||
2. **Descriptive code blocks may be deleted** if their content is covered by prose or tables
|
||||
3. **Never change function signatures, variable names, or schema fields**
|
||||
4. **Merge preserves all branches** — unified function must handle all original cases
|
||||
5. **When uncertain, keep original** — conservative approach prevents functional loss
|
||||
6. **Format fixes must not alter semantics** — only presentation changes
|
||||
|
||||
## Output
|
||||
|
||||
- **File**: Target file overwritten with optimized content
|
||||
- **Variable**: `optimizationRecord` (changes log for Phase 3)
|
||||
- **TodoWrite**: Mark Phase 2 completed, Phase 3 in_progress
|
||||
224
.claude/skills/skill-simplify/phases/03-check.md
Normal file
224
.claude/skills/skill-simplify/phases/03-check.md
Normal file
@@ -0,0 +1,224 @@
|
||||
# Phase 3: Integrity Check
|
||||
|
||||
Re-extract functional inventory from optimized file, compare against Phase 1 baseline, validate pseudo-code format. Report PASS/FAIL with detailed delta.
|
||||
|
||||
## Objective
|
||||
|
||||
- Re-run the same inventory extraction on optimized content
|
||||
- Compare counts using role-aware classification (functional vs descriptive)
|
||||
- Validate pseudo-code format issues are resolved
|
||||
- Report check result with actionable details
|
||||
- Revert if critical functional elements are missing
|
||||
|
||||
## Execution
|
||||
|
||||
### Step 3.1: Re-Extract Inventory from Optimized File
|
||||
|
||||
```javascript
|
||||
const optimizedContent = Read(targetFile)
|
||||
const optimizedLineCount = optimizedContent.split('\n').length
|
||||
|
||||
// Use SAME extraction logic as Phase 1 (including role classification)
|
||||
const afterInventory = extractFunctionalInventory(optimizedContent)
|
||||
```
|
||||
|
||||
### Step 3.2: Compare Inventories (Role-Aware)
|
||||
|
||||
```javascript
|
||||
const beforeCounts = analysisResult.inventory.counts
|
||||
const afterCounts = afterInventory.counts
|
||||
|
||||
const delta = {}
|
||||
let hasCriticalLoss = false
|
||||
let hasWarning = false
|
||||
|
||||
// CRITICAL: Functional elements that MUST NOT decrease
|
||||
const CRITICAL = ['functionalCodeBlocks', 'dataStructures', 'routingBranches',
|
||||
'errorHandlers', 'conditionalLogic', 'askUserQuestions',
|
||||
'inputModes', 'outputArtifacts', 'skillInvocations']
|
||||
|
||||
// MERGE_AWARE: May decrease due to valid merge operations — verify coverage
|
||||
const MERGE_AWARE = ['agentCalls', 'codeBlocks']
|
||||
|
||||
// EXPECTED_DECREASE: May decrease from merge/consolidation
|
||||
const EXPECTED_DECREASE = ['descriptiveCodeBlocks', 'todoWriteBlocks',
|
||||
'phaseHandoffs', 'tables', 'schemas']
|
||||
|
||||
for (const [key, before] of Object.entries(beforeCounts)) {
|
||||
const after = afterCounts[key] || 0
|
||||
const diff = after - before
|
||||
let category, status
|
||||
|
||||
if (CRITICAL.includes(key)) {
|
||||
category = 'critical'
|
||||
status = diff < 0 ? 'FAIL' : 'OK'
|
||||
if (diff < 0) hasCriticalLoss = true
|
||||
} else if (MERGE_AWARE.includes(key)) {
|
||||
category = 'merge_aware'
|
||||
// Decrease is WARN (needs justification), not FAIL
|
||||
status = diff < 0 ? 'WARN' : 'OK'
|
||||
if (diff < 0) hasWarning = true
|
||||
} else {
|
||||
category = 'expected'
|
||||
status = 'OK' // Descriptive decreases are expected
|
||||
}
|
||||
|
||||
delta[key] = { before, after, diff, category, status }
|
||||
}
|
||||
```
|
||||
|
||||
### Step 3.3: Deep Verification
|
||||
|
||||
**For CRITICAL categories with decrease** — identify exactly what was lost:
|
||||
|
||||
```javascript
|
||||
if (hasCriticalLoss) {
|
||||
const lostElements = {}
|
||||
for (const [key, d] of Object.entries(delta)) {
|
||||
if (d.status === 'FAIL') {
|
||||
const beforeItems = analysisResult.inventory[key]
|
||||
const afterItems = afterInventory[key]
|
||||
lostElements[key] = beforeItems.filter(beforeItem =>
|
||||
!afterItems.some(afterItem => matchesElement(beforeItem, afterItem))
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**For MERGE_AWARE categories with decrease** — verify merged coverage:
|
||||
|
||||
```javascript
|
||||
if (hasWarning) {
|
||||
for (const [key, d] of Object.entries(delta)) {
|
||||
if (d.category === 'merge_aware' && d.diff < 0) {
|
||||
// Check if merged template covers all original variants
|
||||
// e.g., single Agent template with "// For multi: add Perspective" covers both
|
||||
const beforeItems = analysisResult.inventory[key]
|
||||
const afterItems = afterInventory[key]
|
||||
const unmatched = beforeItems.filter(beforeItem =>
|
||||
!afterItems.some(afterItem => matchesElement(beforeItem, afterItem))
|
||||
)
|
||||
if (unmatched.length > 0) {
|
||||
// Check if unmatched items are covered by merge comments in remaining items
|
||||
const mergeComments = afterItems.flatMap(item => extractMergeComments(item))
|
||||
const trulyLost = unmatched.filter(item =>
|
||||
!mergeComments.some(comment => coversElement(comment, item))
|
||||
)
|
||||
if (trulyLost.length > 0) {
|
||||
delta[key].status = 'FAIL'
|
||||
hasCriticalLoss = true
|
||||
delta[key].trulyLost = trulyLost
|
||||
}
|
||||
// else: merge-covered, WARN is correct
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Step 3.4: Pseudo-Code Format Validation
|
||||
|
||||
```javascript
|
||||
const afterFormatIssues = validatePseudoCode(afterInventory.codeBlocks.filter(b => b.role === 'functional'))
|
||||
const beforeFormatCount = analysisResult.inventory.formatIssues.length
|
||||
const afterFormatCount = afterFormatIssues.length
|
||||
|
||||
const formatDelta = {
|
||||
before: beforeFormatCount,
|
||||
after: afterFormatCount,
|
||||
resolved: beforeFormatCount - afterFormatCount,
|
||||
newIssues: afterFormatIssues.filter(issue =>
|
||||
!analysisResult.inventory.formatIssues.some(orig => orig.line === issue.line && orig.type === issue.type)
|
||||
)
|
||||
}
|
||||
|
||||
// New format issues introduced by optimization = FAIL
|
||||
if (formatDelta.newIssues.length > 0) {
|
||||
hasCriticalLoss = true
|
||||
}
|
||||
```
|
||||
|
||||
**Pseudo-code validation checks**:
|
||||
|
||||
| Check | Detection | Action on Failure |
|
||||
|-------|-----------|-------------------|
|
||||
| Bracket matching | Count `{([` vs `})]` per code block | FAIL — fix or revert |
|
||||
| Variable consistency | `${var}` used but never declared | WARNING — note in report |
|
||||
| Structural completeness | Function body has entry but no exit (return/Write/output) | WARNING |
|
||||
| Nested backtick resolution | Backtick template literals inside code fences | WARNING if pre-existing, FAIL if newly introduced |
|
||||
| Schema field preservation | Schema fields in after match before | FAIL if fields lost |
|
||||
|
||||
### Step 3.5: Generate Check Report
|
||||
|
||||
```javascript
|
||||
const status = hasCriticalLoss ? 'FAIL' : (hasWarning ? 'WARN' : 'PASS')
|
||||
|
||||
const checkReport = {
|
||||
status,
|
||||
linesBefore: analysisResult.originalLineCount,
|
||||
linesAfter: optimizedLineCount,
|
||||
reduction: `${analysisResult.originalLineCount - optimizedLineCount} lines (-${Math.round((analysisResult.originalLineCount - optimizedLineCount) / analysisResult.originalLineCount * 100)}%)`,
|
||||
delta,
|
||||
formatDelta,
|
||||
lostElements: hasCriticalLoss ? lostElements : null
|
||||
}
|
||||
|
||||
// Display report table
|
||||
// | Category | Before | After | Delta | Status |
|
||||
// Show all categories, highlight FAIL/WARN rows
|
||||
// Show format issues summary if any
|
||||
```
|
||||
|
||||
### Step 3.6: Act on Result
|
||||
|
||||
```javascript
|
||||
if (status === 'FAIL') {
|
||||
Write(targetFile, analysisResult.originalContent)
|
||||
// Report: "Critical elements lost / new format issues introduced. Reverted."
|
||||
}
|
||||
|
||||
if (status === 'WARN') {
|
||||
// Report: "Decreases from merge/descriptive removal. Verify coverage."
|
||||
// Show merge justifications for MERGE_AWARE categories
|
||||
}
|
||||
|
||||
if (status === 'PASS') {
|
||||
// Report: "All functional elements preserved. Optimization successful."
|
||||
}
|
||||
```
|
||||
|
||||
## Element Matching Rules
|
||||
|
||||
How `matchesElement()` determines if a before-element exists in after-inventory:
|
||||
|
||||
| Element Type | Match Criteria |
|
||||
|-------------|---------------|
|
||||
| codeBlocks | Same language + first meaningful line (ignore whitespace/comments) |
|
||||
| agentCalls | Same agentType + similar prompt keywords (>60% overlap) |
|
||||
| dataStructures | Same variable name OR same field set |
|
||||
| routingBranches | Same condition expression (normalized) |
|
||||
| errorHandlers | Same error type/pattern |
|
||||
| conditionalLogic | Same condition + same outcome set |
|
||||
| askUserQuestions | Same question count + similar option labels |
|
||||
| inputModes | Same mode identifier |
|
||||
| outputArtifacts | Same file path pattern or artifact name |
|
||||
| skillInvocations | Same skill name |
|
||||
| todoWriteBlocks | Same phase names (order-independent) |
|
||||
| phaseHandoffs | Same target phase reference |
|
||||
| tables | Same column headers |
|
||||
| schemas | Same schema name or field set |
|
||||
|
||||
**Merge coverage check** (`coversElement()`):
|
||||
- Agent calls: Merged template contains `// For multi:` or `// Multi-perspective:` comment referencing the missing variant
|
||||
- Code blocks: Merged block contains comment noting the alternative was folded in
|
||||
|
||||
## Completion
|
||||
|
||||
```javascript
|
||||
TodoWrite({ todos: [
|
||||
{ content: `Phase 1: Analysis [${Object.keys(analysisResult.inventory.counts).length} categories]`, status: "completed" },
|
||||
{ content: `Phase 2: Optimize [${checkReport.reduction}]`, status: "completed" },
|
||||
{ content: `Phase 3: Check [${checkReport.status}] | Format: ${formatDelta.resolved} resolved, ${formatDelta.newIssues.length} new`, status: "completed" }
|
||||
]})
|
||||
```
|
||||
Reference in New Issue
Block a user