diff --git a/docs/plans/context-architecture-protocols-plan.md b/docs/plans/context-architecture-protocols-plan.md new file mode 100644 index 00000000..c5a9156a --- /dev/null +++ b/docs/plans/context-architecture-protocols-plan.md @@ -0,0 +1,786 @@ +# Implementation Plan: Context Architecture Optimization (Protocol Partitioning) + +> Generated by `/PACT:plan-mode` on 2026-01-15 +> Status: PENDING APPROVAL +> **Last Updated**: 2026-01-15 (Second peer review feedback incorporated — agent files scope added) + + + +## Summary + +Optimize PACT framework context loading by: +1. **Compressing CLAUDE.md** from 306 lines to ~100-110 lines (preserving phase principles) +2. **Partitioning pact-protocols.md** (1,085 lines) into 8 focused protocol files +3. **Updating commands** to @-reference only the specific protocols they need +4. **Updating agent files** (7 specialists) with targeted @-refs to new protocol files + +**Why protocol partitioning over skills**: PACT is a deterministic, structured workflow where we know exactly when each protocol is needed. Explicit @-references provide predictable, controlled loading that aligns with PACT's structured nature. Skills (auto-discovery) are better suited for optional, contextual guidance. + +**Framework-wide impact**: All 8 PACT commands benefit. The heaviest commands (`orchestrate`, `plan-mode`) see ~55% reductions. All commands benefit from 67% smaller CLAUDE.md. Expected savings: ~55% reduction in typical orchestration context load. + +**Supersedes**: +- PR #68 draft plan +- `context-architecture-skills-plan.md` (skills approach reconsidered) + +--- + +## Specialist Perspectives + +### 📋 Preparation Phase +**Effort**: Low-Medium + +#### Research Completed +- [x] Anthropic context engineering guidance reviewed ([source](https://www.anthropic.com/research/building-effective-agents)) +- [x] CLAUDE.md size guidelines established (working assumption: < 60 lines ideal, < 300 max — derived from context engineering principles, not explicit Anthropic documentation) +- [x] Current context load measured (CLAUDE.md ~4K, pact-protocols.md ~10K tokens; estimated via ~10 tokens/line approximation) +- [x] Skills vs @-references trade-offs analyzed +- [x] PACT workflow determinism assessed (favors explicit references) +- [x] Agent files audited for protocol references (**21 refs found across 7 files** — require updates) +- [x] rePACT.md dependencies verified (self-contained, no @-refs needed) + +#### Questions Resolved +- **Skills vs Protocols**: Protocol partitioning preferred for PACT's deterministic workflows +- **Algedonic location**: Keep separate algedonic.md file (already concise, safety-critical) +- **VSM distribution**: Keep vsm-glossary.md as central reference +- **rePACT dependencies**: Command has conceptual references ("see Autonomy Charter", "Apply S2 coordination") but these are inline explanatory text, NOT @-file references. No changes needed. +- **Agent file dependencies**: All 7 specialist agent files contain @-refs to `pact-protocols.md` for workflow handoffs and S1 Autonomy. These require targeted updates after partitioning. + +--- + +### 🏗️ Architecture Phase +**Effort**: Medium + +#### Components Affected +| Component | Change Type | Impact | +|-----------|-------------|--------| +| `CLAUDE.md` | Compress | 306 → ~100-110 lines | +| `protocols/pact-protocols.md` | Partition | 1,085 → ~180 lines (lean index) | +| `protocols/delegation.md` | New | ~145 lines | +| `protocols/s4-checkpoints.md` | New | ~140 lines | +| `protocols/variety-management.md` | New | ~60 lines | +| `protocols/s2-coordination.md` | New | ~110 lines | +| `protocols/s3-audit.md` | New | ~60 lines | +| `protocols/s3s4-tension.md` | New | ~65 lines | +| `protocols/workflow-protocols.md` | New | ~105 lines | +| `protocols/phase-guidance.md` | New | ~100 lines | +| `commands/PACT/orchestrate.md` | Modify | Replace monolithic @-ref with targeted @-refs | +| `commands/PACT/plan-mode.md` | Modify | Replace monolithic @-ref with targeted @-refs | +| `agents/pact-*.md` (7 files) | Modify | Update @pact-protocols refs to targeted protocol files | + +#### Design Approach + +**Protocol Partitioning Architecture**: + +``` +┌─────────────────────────────────────────────────────────────┐ +│ CLAUDE.md (~100-110 lines) │ +│ Always loaded: Mission, S5 Policy, Phase Principles, │ +│ Specialist list, Command list │ +└─────────────────────────────────────────────────────────────┘ + │ + │ Commands @-reference only what they need + ▼ +┌─────────────────────────────────────────────────────────────┐ +│ Partitioned Protocol Files │ +│ │ +│ pact-protocols.md (~180 lines) │ +│ └─ Lean index + S1 Autonomy + Cross-Cutting Concerns │ +│ │ +│ delegation.md (~145 lines) │ +│ └─ S5 Policy, Tool checkpoint, app code definition │ +│ │ +│ s4-checkpoints.md (~140 lines) │ +│ └─ S4 checkpoint protocol, environment model │ +│ │ +│ variety-management.md (~60 lines) │ +│ └─ Variety scoring, workflow selection, strategies │ +│ │ +│ s2-coordination.md (~110 lines) │ +│ └─ Pre-parallel checks, conflict resolution │ +│ │ +│ s3-audit.md (~60 lines) │ +│ └─ Continuous audit, RED/YELLOW/GREEN signals │ +│ │ +│ s3s4-tension.md (~65 lines) │ +│ └─ Tension detection, resolution protocol │ +│ │ +│ workflow-protocols.md (~105 lines) │ +│ └─ plan-mode, imPACT, comPACT protocol summaries │ +│ │ +│ phase-guidance.md (~100 lines) │ +│ └─ Test Engagement, Phase Handoffs, Backend/DB Boundary │ +│ │ +│ algedonic.md (~235 lines) — unchanged │ +│ └─ Emergency bypass, HALT/ALERT signals │ +└─────────────────────────────────────────────────────────────┘ + │ + │ Commands load only relevant protocols + ▼ +┌─────────────────────────────────────────────────────────────┐ +│ orchestrate.md │ +│ └─ @delegation, @variety-management, @s4-checkpoints, │ +│ @s2-coordination, @s3-audit, @phase-guidance, @algedonic│ +│ │ +│ plan-mode.md │ +│ └─ @variety-management, @workflow-protocols │ +│ │ +│ imPACT.md │ +│ └─ @algedonic, @workflow-protocols │ +│ │ +│ comPACT.md │ +│ └─ @workflow-protocols (optional, for protocol reference) │ +└─────────────────────────────────────────────────────────────┘ +``` + +#### Key Decisions +| Decision | Options | Recommendation | Rationale | +|----------|---------|----------------|-----------| +| Approach | Skills (auto-discovery) vs Protocols (@-refs) | Protocol partitioning | PACT is deterministic; explicit control preferred | +| Protocol count | 6 files vs 8 files | 8 focused files | Complete content accounting shows 8 needed for target index size | +| CLAUDE.md size | ~85 vs ~100-110 lines | ~100-110 lines | Preserves phase principles that guide behavior | +| pact-protocols.md | ~100 vs ~180 lines | ~180 lines (lean index) | Realistic after complete content accounting | +| Algedonic | Partition vs keep whole | Keep whole | Safety-critical, already concise, well-isolated | + +#### Interface Contracts + +**Targeted @-Reference Pattern**: + +```markdown +# Current (loads entire 1,085-line file every time): +See @~/.claude/protocols/pact-protocols.md for S4 Checkpoint Protocol. + +# New (loads only ~140-line file when needed): +See @~/.claude/protocols/s4-checkpoints.md for the checkpoint protocol. +``` + +**Protocol File Mapping** (what each command needs): + +| Command | Protocols Needed | +|---------|------------------| +| `orchestrate.md` | delegation, variety-management, s4-checkpoints, s2-coordination, s3-audit, phase-guidance, algedonic | +| `plan-mode.md` | variety-management, workflow-protocols | +| `imPACT.md` | algedonic, workflow-protocols | +| `comPACT.md` | workflow-protocols (optional) | +| `rePACT.md` | None (self-contained with inline guidance) | + +**Estimated Load per Command**: + +| Command | Current @-refs Load | New @-refs Load | Reduction | +|---------|---------------------|-----------------|-----------| +| orchestrate | ~1,320 lines | ~715 lines | **46%** | +| plan-mode | ~1,085 lines | ~165 lines | **85%** | +| imPACT | ~235 lines | ~340 lines | -45% (adds workflow-protocols for context) | + +--- + +### 💻 Code Phase +**Effort**: Medium + +> **Note**: This is AI tooling (.claude/ files), not application code. Per delegation rules, the orchestrator may implement these changes directly. No specialist delegation required. + +#### Complete Content Accounting + +Every section of `pact-protocols.md` (1,085 lines) is mapped to its destination: + +| Source Section | Lines | Destination | Notes | +|----------------|-------|-------------|-------| +| Header + VSM Quick Reference | 1-10 | `pact-protocols.md` (index) | Keep as intro | +| S5 Policy Layer (Governance) | 13-145 | `delegation.md` | Includes Non-Negotiables, Delegation Enforcement, Policy Checkpoints, S5 Authority, S5 Decision Framing | +| S4 Checkpoint Protocol | 148-217 | `s4-checkpoints.md` | Includes Trigger Points, Questions, Outcomes, Format | +| S4 Environment Model | 220-291 | `s4-checkpoints.md` | Combined with S4 Checkpoint | +| S3/S4 Tension Detection | 294-356 | `s3s4-tension.md` | Includes Indicators, Detection Phrases, Resolution | +| S2 Coordination Layer | 359-465 | `s2-coordination.md` | Includes Pre-Parallel Check, Conflict Resolution, Anti-Oscillation | +| S1 Autonomy & Recursion | 468-540 | `pact-protocols.md` (index) | Keep inline (~72 lines) - referenced by multiple protocols | +| S3* Continuous Audit | 543-601 | `s3-audit.md` | Includes Audit Modes, Signals, S2 Coordination | +| Algedonic Signals | 604-644 | `algedonic.md` | Already separate (~40 line summary here, full file exists) | +| Variety Management | 647-706 | `variety-management.md` | Includes Dimensions, Score, Strategies | +| PACT Workflow Family | 709-718 | `pact-protocols.md` (index) | Keep inline (~9 lines) - overview table | +| plan-mode Protocol | 721-754 | `workflow-protocols.md` | Protocol summary | +| imPACT Protocol | 757-773 | `workflow-protocols.md` | Protocol summary | +| comPACT Protocol | 776-832 | `workflow-protocols.md` | Protocol summary | +| Phase Handoffs | 835-842 | `phase-guidance.md` | Universal guidance | +| Backend ↔ Database Boundary | 846-858 | `phase-guidance.md` | Specialist coordination | +| Test Engagement | 861-941 | `phase-guidance.md` | CODE→TEST handoff | +| Cross-Cutting Concerns | 945-954 | `pact-protocols.md` (index) | Keep inline (~9 lines) - brief checklist | +| Architecture Review | 957-963 | `pact-protocols.md` (index) | Keep inline (~6 lines) - brief | +| Documentation Locations | 967-1069 | `pact-protocols.md` (index) | Keep inline (~102 lines) - reference table | +| Session Continuity | 1073-1079 | `pact-protocols.md` (index) | Keep inline (~6 lines) | +| Related | 1082-1086 | `pact-protocols.md` (index) | Keep inline (~4 lines) | + +**Summary**: +- Content partitioned to new files: ~785 lines (8 files) +- Content remaining in index: ~180 lines +- Content in separate algedonic.md: ~235 lines (unchanged) +- Total accounted: 1,085 lines ✓ + +#### Cross-Reference Inventory + +Internal references within `pact-protocols.md` that need updating after partitioning: + +| Location | Current Reference | New Reference | Notes | +|----------|-------------------|---------------|-------| +| Line 7 | `@~/.claude/reference/vsm-glossary.md` | Keep as-is | External reference | +| Line 212 | "see Variety Management" | `@variety-management.md` | Cross-protocol ref | +| Line 349-355 | S3/S4 tension refs S4 Checkpoints | `@s4-checkpoints.md` | Cross-protocol ref | +| Line 435-436 | "see CODE → TEST Handoff", "see Phase Handoffs" | `@phase-guidance.md` | Cross-protocol ref | +| Line 488 | "see S2 Coordination" | `@s2-coordination.md` | Cross-protocol ref | +| Line 539 | `@~/.claude/commands/PACT/rePACT.md` | Keep as-is | External reference | +| Line 586 | "unlike algedonic signals—see below" | `@algedonic.md` | Cross-protocol ref | +| Line 610 | `@~/.claude/protocols/algedonic.md` | Keep as-is | External reference | +| Line 694 | "/PACT:rePACT" | Keep as-is | Command reference | +| Line 696 | "S3*" reference | `@s3-audit.md` | Cross-protocol ref | +| Line 969 | "filesystem-context" skill | Keep as-is | External reference | + +**Total internal cross-references requiring updates**: 7 + +#### Agent Files Cross-Reference Inventory + +All 7 specialist agent files reference `pact-protocols.md`. After partitioning, these need targeted updates: + +| Agent File | Reference Purpose | Current @-ref | New @-ref | +|------------|-------------------|---------------|-----------| +| `pact-architect.md` | Cross-Agent Coordination | `@pact-protocols.md` | `@phase-guidance.md` | +| `pact-architect.md` | S1 Autonomy & Recursion | `@pact-protocols.md` | `@pact-protocols.md` (unchanged — stays in index) | +| `pact-backend-coder.md` | Cross-Agent Coordination | `@pact-protocols.md` | `@phase-guidance.md` | +| `pact-backend-coder.md` | S1 Autonomy & Recursion | `@pact-protocols.md` | `@pact-protocols.md` (unchanged) | +| `pact-frontend-coder.md` | Cross-Agent Coordination | `@pact-protocols.md` | `@phase-guidance.md` | +| `pact-frontend-coder.md` | S1 Autonomy & Recursion | `@pact-protocols.md` | `@pact-protocols.md` (unchanged) | +| `pact-database-engineer.md` | Cross-Agent Coordination | `@pact-protocols.md` | `@phase-guidance.md` | +| `pact-database-engineer.md` | S1 Autonomy & Recursion | `@pact-protocols.md` | `@pact-protocols.md` (unchanged) | +| `pact-test-engineer.md` | Cross-Agent Coordination | `@pact-protocols.md` | `@phase-guidance.md` | +| `pact-test-engineer.md` | S1 Autonomy & Recursion | `@pact-protocols.md` | `@pact-protocols.md` (unchanged) | +| `pact-preparer.md` | Cross-Agent Coordination | `@pact-protocols.md` | `@phase-guidance.md` | +| `pact-preparer.md` | S1 Autonomy & Recursion | `@pact-protocols.md` | `@pact-protocols.md` (unchanged) | +| `pact-preparer.md` | S4 Environment Model | `@pact-protocols.md` | `@s4-checkpoints.md` | +| `pact-n8n.md` | Cross-Agent Coordination | `@pact-protocols.md` | `@phase-guidance.md` | +| `pact-n8n.md` | S1 Autonomy & Recursion | `@pact-protocols.md` | `@pact-protocols.md` (unchanged) | + +**Summary**: +- 7 refs need updating to `@phase-guidance.md` (Cross-Agent Coordination) +- 7 refs remain as `@pact-protocols.md` (S1 Autonomy stays in lean index) +- 1 ref needs updating to `@s4-checkpoints.md` (pact-preparer's Environment Model ref) +- All `@algedonic.md` refs: No change needed (already separate file) + +**Total agent file cross-references requiring updates**: 8 (7 to phase-guidance + 1 to s4-checkpoints) + +**Grand total cross-references requiring updates**: 15 (7 internal + 8 agent files) + +#### Files to Create + +| File | Content Source | Est. Lines | +|------|----------------|------------| +| `.claude/protocols/delegation.md` | pact-protocols.md lines 13-145 | ~145 | +| `.claude/protocols/s4-checkpoints.md` | pact-protocols.md lines 148-291 | ~140 | +| `.claude/protocols/variety-management.md` | pact-protocols.md lines 647-706 | ~60 | +| `.claude/protocols/s2-coordination.md` | pact-protocols.md lines 359-465 | ~110 | +| `.claude/protocols/s3-audit.md` | pact-protocols.md lines 543-601 | ~60 | +| `.claude/protocols/s3s4-tension.md` | pact-protocols.md lines 294-356 | ~65 | +| `.claude/protocols/workflow-protocols.md` | pact-protocols.md lines 721-832 | ~105 | +| `.claude/protocols/phase-guidance.md` | pact-protocols.md lines 835-941 | ~100 | + +#### Files to Modify + +| File | Changes | +|------|---------| +| `CLAUDE.md` | Compress from 306 → ~100-110 lines (preserve phase principles) | +| `.claude/protocols/pact-protocols.md` | Reduce to ~180-line lean index | +| `.claude/commands/PACT/orchestrate.md` | Replace single @pact-protocols with targeted @-refs | +| `.claude/commands/PACT/plan-mode.md` | Replace @pact-protocols with @variety-management, @workflow-protocols | +| `.claude/commands/PACT/imPACT.md` | Add @workflow-protocols reference | +| `.claude/agents/pact-architect.md` | Update Cross-Agent Coordination ref → @phase-guidance.md | +| `.claude/agents/pact-backend-coder.md` | Update Cross-Agent Coordination ref → @phase-guidance.md | +| `.claude/agents/pact-frontend-coder.md` | Update Cross-Agent Coordination ref → @phase-guidance.md | +| `.claude/agents/pact-database-engineer.md` | Update Cross-Agent Coordination ref → @phase-guidance.md | +| `.claude/agents/pact-test-engineer.md` | Update Cross-Agent Coordination ref → @phase-guidance.md | +| `.claude/agents/pact-preparer.md` | Update Cross-Agent Coordination ref → @phase-guidance.md, S4 Environment Model ref → @s4-checkpoints.md | +| `.claude/agents/pact-n8n.md` | Update Cross-Agent Coordination ref → @phase-guidance.md | +| `pact-plugin/protocols/` | Mirror partitioned files for plugin distribution | +| `pact-plugin/agents/` | Mirror agent file updates for plugin distribution | + +#### Protocol File Structure + +Each partitioned protocol file follows this structure: + +```markdown +# {Protocol Name} + +> **Purpose**: One-line description +> **Used by**: List of commands that @-reference this file +> **See also**: Related protocol files (with @-refs) + +--- + +## {Content sections extracted from pact-protocols.md} + +... +``` + +#### CLAUDE.md Proposed Structure (~100-110 lines) + +```markdown +# MISSION (7 lines) +Mission statement, motto, VSM note + +## S5 POLICY (18 lines) +Non-negotiables table (4 rows), policy checkpoints summary (6 lines) +→ "See @~/.claude/protocols/delegation.md for enforcement details" +→ "See @~/.claude/protocols/algedonic.md for emergency bypass" + +## INSTRUCTIONS (6 lines) +Core directives (read CLAUDE.md, apply PACT, delegate, update) + +## GUIDELINES (15 lines) +Context management, git workflow, S3/S4 modes (brief) +→ "See @~/.claude/protocols/s3s4-tension.md for tension resolution" + +## PACT PHASES (20 lines) +Phase names with 2-3 key principles each (preserved from current) +→ PREPARE: Documentation First, Context Gathering, Dependency Mapping +→ ARCHITECT: Single Responsibility, Loose Coupling, Interface Segregation +→ CODE: Clean Code, DRY, KISS, Error Handling, Security Mindset +→ TEST: Coverage, Edge Cases, Integration, Regression Prevention + +## SPECIALIST AGENTS (10 lines) +Agent list with emoji identifiers + +## ORCHESTRATION COMMANDS (15 lines) +Command list with one-line descriptions +→ "See @~/.claude/protocols/variety-management.md for workflow selection" +→ "See @~/.claude/protocols/workflow-protocols.md for protocol details" + +## DOCUMENTATION LOCATIONS (8 lines) +Phase → Output Location table (condensed) + +## PROTOCOL REFERENCE (12 lines) +Quick index of partitioned protocol files with trigger phrases: +- delegation.md → "Before Edit/Write on any file" +- s4-checkpoints.md → "At phase boundaries" +- variety-management.md → "Task assessment, workflow selection" +- s2-coordination.md → "Before parallel agent invocation" +- s3-audit.md → "During CODE phase for quality signals" +- s3s4-tension.md → "When detecting operational vs strategic conflict" +- workflow-protocols.md → "For plan-mode, imPACT, comPACT details" +- phase-guidance.md → "For handoffs, test engagement, boundaries" +- algedonic.md → "Emergency escalation to user" +``` + +#### pact-protocols.md New Structure (~180 lines) + +```markdown +# PACT Protocols (Lean Index) + +> **Purpose**: Central index for PACT protocol documentation. +> **Note**: Protocol content has been partitioned into focused files for targeted loading. + +## Protocol Files + +| Protocol | File | Trigger | +|----------|------|---------| +| Delegation Enforcement | @delegation.md | Before Edit/Write on app code | +| S4 Checkpoints | @s4-checkpoints.md | At phase boundaries | +| Variety Management | @variety-management.md | Task assessment, workflow selection | +| S2 Coordination | @s2-coordination.md | Parallel agent coordination | +| S3* Audit | @s3-audit.md | CODE phase quality signals | +| S3/S4 Tension | @s3s4-tension.md | Mode conflict resolution | +| Workflow Protocols | @workflow-protocols.md | plan-mode, imPACT, comPACT | +| Phase Guidance | @phase-guidance.md | Handoffs, test engagement | +| Algedonic Signals | @algedonic.md | Emergency escalation | + +## S1 Autonomy Charter (~72 lines) +[Keep inline - referenced by multiple protocols] + +## PACT Workflow Family (~9 lines) +[Keep inline - overview table] + +## Cross-Cutting Concerns (~9 lines) +[Keep inline - brief checklist] + +## Architecture Review (~6 lines) +[Keep inline - brief] + +## Documentation Locations (~70 lines, condensed from ~102) +[Keep inline - reference table, compressed] + +## Session Continuity (~6 lines) +[Keep inline] + +## Related (~4 lines) +[Keep inline] +``` + +#### Implementation Sequence + +1. `feat(protocols): create delegation.md from pact-protocols.md` — Extract S5 Policy Layer +2. `feat(protocols): create s4-checkpoints.md from pact-protocols.md` — Extract S4 content + Environment Model +3. `feat(protocols): create variety-management.md from pact-protocols.md` — Extract variety content +4. `feat(protocols): create s2-coordination.md from pact-protocols.md` — Extract S2 content +5. `feat(protocols): create s3-audit.md from pact-protocols.md` — Extract S3* content +6. `feat(protocols): create s3s4-tension.md from pact-protocols.md` — Extract tension content +7. `feat(protocols): create workflow-protocols.md from pact-protocols.md` — Extract plan-mode, imPACT, comPACT +8. `feat(protocols): create phase-guidance.md from pact-protocols.md` — Extract handoffs, test engagement, boundaries +9. `refactor(protocols): convert pact-protocols.md to lean index (~180 lines)` — Update internal cross-refs +10. `refactor(claude): compress CLAUDE.md to ~100-110 lines` — Preserve phase principles +11. `refactor(commands): update orchestrate.md with targeted @-refs` — Replace monolithic ref +12. `refactor(commands): update plan-mode.md with targeted @-refs` — Replace monolithic ref +13. `refactor(commands): update imPACT.md with @workflow-protocols` — Add protocol ref +14. `refactor(agents): update all 7 agent files with targeted @-refs` — Update Cross-Agent Coordination + S4 Environment Model refs +15. `chore(plugin): sync partitioned protocols and agents to pact-plugin/` — Mirror for distribution + +--- + +### 🧪 Test Phase +**Effort**: Medium-High (5-6 hours manual validation) + +#### Test Scenarios + +| Scenario | Type | Priority | +|----------|------|----------| +| Content preservation verification (checklist) | Verification | P0 | +| Cross-reference resolution (all 15 refs: 7 internal + 8 agent) | Verification | P0 | +| Agent file @-ref resolution (all 7 agent files load correct protocols) | Verification | P0 | +| `/PACT:orchestrate` loads correct protocols at each phase | Integration | P0 | +| Delegation enforcement on app code edit | Functional | P0 | +| Algedonic HALT signal bypasses to user | Functional | P0 | +| Tool Checkpoint Protocol fires before Edit/Write | Functional | P0 | +| `/PACT:plan-mode` loads variety-management, workflow-protocols | Integration | P0 | +| `/PACT:imPACT` loads algedonic, workflow-protocols | Integration | P1 | +| S3/S4 tension protocol accessible via targeted @-ref | Functional | P1 | +| S4 checkpoint protocol accessible at phase boundaries | Functional | P1 | +| `/PACT:comPACT` works with optional workflow-protocols ref | Integration | P2 | +| `/PACT:rePACT` works without protocol refs | Integration | P2 | +| Plugin sync matches .claude/ structure | Verification | P2 | + +#### Coverage Targets +- Critical path (P0): 100% — Must pass for merge +- Core workflows (P1): 100% — Should pass for merge +- Edge cases (P2): Best effort — May defer + +#### Content Preservation Verification + +Create `docs/testing/partition-verification.md` during implementation: + +```markdown +# Protocol Partitioning Verification Checklist + +## Section Coverage +| Original Section | Destination File | Lines | Verified | +|------------------|------------------|-------|----------| +| S5 Policy Layer | delegation.md | 13-145 | [ ] | +| S4 Checkpoint Protocol | s4-checkpoints.md | 148-217 | [ ] | +| ... (all sections from Content Accounting table) | + +## Content Integrity +- [ ] Every H2 section from original has corresponding location +- [ ] Every code example preserved +- [ ] Every table preserved +- [ ] All @-references updated or preserved correctly + +## Cross-Reference Resolution +| Ref # | Original | Updated To | Verified | +|-------|----------|------------|----------| +| 1 | "see Variety Management" | @variety-management.md | [ ] | +| 2 | S3/S4 refs S4 Checkpoints | @s4-checkpoints.md | [ ] | +| ... (all 7 cross-references) | + +## Summary +- Sections verified: X of Y +- Cross-refs verified: X of 7 +- Content gaps: [none / list] +``` + +#### Validation Approach + +**Tier 1: Static Verification (1 hour)** +- File existence checks (8 new files) +- Line count validation (sum ≥ original) +- @-reference resolution (verify all 7 updated refs work) +- Section heading mapping (checklist) + +**Tier 2: Behavioral Verification (2.5-3 hours)** +- Execute `/PACT:orchestrate` on sample task +- Execute `/PACT:plan-mode` on sample task +- Test delegation enforcement (attempt Edit on .ts file) +- Test algedonic escalation (simulate HALT condition) +- Verify protocol content appears in agent responses + +**Tier 3: Regression Verification (1.5-2 hours)** +- Compare pre/post behavior on sample tasks +- Verify edge cases still work +- Plugin sync validation (`diff -rq .claude/protocols pact-plugin/protocols`) + +#### Regression Baseline + +Before implementation, capture: +- [ ] Output of `/PACT:orchestrate` on "add pagination endpoint" task +- [ ] Output of `/PACT:plan-mode` on "implement user auth" task +- [ ] Delegation enforcement behavior (attempt to edit app code) +- [ ] Decision log format produced by CODE phase + +After implementation, compare and document any differences. + +#### Acceptance Criteria + +- [ ] All 8 new protocol files exist and are syntactically valid +- [ ] pact-protocols.md reduced to 150-200 lines (lean index) +- [ ] Compressed CLAUDE.md is 95-115 lines +- [ ] Compressed CLAUDE.md contains phase principles (PREPARE, ARCHITECT, CODE, TEST) +- [ ] Compressed CLAUDE.md contains SACROSANCT policy table +- [ ] Compressed CLAUDE.md contains delegation enforcement summary +- [ ] All 15 cross-references updated correctly (7 internal + 8 agent file refs) +- [ ] All 7 agent files updated with correct targeted @-refs +- [ ] `/PACT:orchestrate` executes without errors +- [ ] `/PACT:plan-mode` executes without errors +- [ ] Tool Checkpoint Protocol triggers on application code +- [ ] Algedonic HALT scenario escalates to user +- [ ] Content preservation checklist: 100% sections verified +- [ ] Plugin sync: `diff` shows only expected differences (protocols and agents) + +--- + +## Rollback Strategy + +### Rollback Triggers +- Any P0 test fails after implementation +- More than 2 P1 tests fail +- Critical user-reported issues within 48 hours of merge +- Content preservation checklist shows gaps + +### Rollback Procedures + +| Stage | Action | +|-------|--------| +| **Before merge** | Abandon PR, no rollback needed | +| **After merge, before release** | `git revert ` | +| **After plugin distribution** | 1) Revert in repo, 2) Publish corrected pact-plugin, 3) Communicate if impact significant | + +### Rollback Verification +After rollback: +- [ ] `pact-protocols.md` is original 1,085 lines +- [ ] `CLAUDE.md` is original 306 lines +- [ ] All 7 agent files restored to original @pact-protocols.md refs +- [ ] No orphaned protocol files in .claude/protocols/ +- [ ] Plugin sync reverted (protocols and agents) + +--- + +## Synthesized Implementation Roadmap + +### Phase Sequence + +``` +Phase 1: Create Protocol Files (Low Risk) +├── delegation.md +├── s4-checkpoints.md +├── variety-management.md +├── s2-coordination.md +├── s3-audit.md +├── s3s4-tension.md +├── workflow-protocols.md +└── phase-guidance.md + │ + ▼ CHECKPOINT: Verify content extraction complete (checklist) + │ +Phase 2: Update pact-protocols.md (Low Risk) +├── Convert to ~180-line lean index +└── Update all 7 cross-references + │ + ▼ CHECKPOINT: Verify index references resolve correctly + │ +Phase 3: Compress CLAUDE.md (Medium Risk) +├── Restructure to ~100-110 lines +├── Preserve phase principles +└── Add protocol reference guide with trigger phrases + │ + ▼ CHECKPOINT: Run full P0 test suite + │ +Phase 4: Update Commands (Medium Risk) +├── orchestrate.md (targeted @-refs) +├── plan-mode.md (targeted @-refs) +└── imPACT.md (add @workflow-protocols) + │ + ▼ CHECKPOINT: Command validation + │ +Phase 5: Update Agent Files (Low Risk) +├── All 7 agent files: Cross-Agent Coordination → @phase-guidance.md +└── pact-preparer.md: S4 Environment Model → @s4-checkpoints.md + │ + ▼ CHECKPOINT: Agent file @-ref validation + regression comparison + │ +Phase 6: Plugin Sync (Low Risk) +├── Mirror protocols to pact-plugin/protocols/ +└── Mirror agent updates to pact-plugin/agents/ + │ + ▼ Final PR review +``` + +### Commit Sequence (Proposed) + +1. `feat(protocols): partition S5 policy layer into delegation.md` +2. `feat(protocols): partition S4 checkpoint protocol into s4-checkpoints.md` +3. `feat(protocols): partition variety management into variety-management.md` +4. `feat(protocols): partition S2 coordination into s2-coordination.md` +5. `feat(protocols): partition S3* audit into s3-audit.md` +6. `feat(protocols): partition S3/S4 tension into s3s4-tension.md` +7. `feat(protocols): partition workflow protocols (plan-mode, imPACT, comPACT)` +8. `feat(protocols): partition phase guidance (handoffs, test engagement)` +9. `refactor(protocols): convert pact-protocols.md to lean index` +10. `refactor(claude): compress CLAUDE.md to ~100-110 lines` +11. `refactor(commands): update orchestrate.md with targeted protocol refs` +12. `refactor(commands): update plan-mode.md with targeted protocol refs` +13. `refactor(commands): update imPACT.md with workflow-protocols ref` +14. `refactor(agents): update all 7 agent files with targeted @-refs` +15. `chore(plugin): sync partitioned protocols and agents to pact-plugin/` + +--- + +## Cross-Cutting Concerns + +| Concern | Status | Notes | +|---------|--------|-------| +| Security | ✅ Ready | Delegation enforcement and algedonic signals preserved | +| Performance | ✅ Focus | ~55% context reduction for heavy commands | +| Predictability | ✅ Improved | Deterministic @-refs vs skill auto-discovery | +| Maintainability | ✅ Improved | Smaller, focused files easier to update | +| Rollback Safety | ✅ Added | Explicit rollback triggers and procedures | + +--- + +## Open Questions + +### Require User Decision + +None — approach validated through discussion and peer review. + +### Require Further Research + +- [ ] **Documentation Locations section**: Currently ~102 lines; can be compressed to ~70 lines during implementation +- [ ] **Optimal protocol granularity**: 8 files proposed; may consolidate if testing reveals unnecessary splits + +--- + +## Risk Assessment + +| Risk | Likelihood | Impact | Mitigation | +|------|------------|--------|------------| +| Content lost in partitioning | Low | High | Content accounting table + verification checklist | +| Cross-references break | Low (was Medium) | Medium | Cross-reference inventory with explicit mapping | +| Commands miss needed protocols | Low | Medium | Protocol file mapping table | +| Plugin sync drift | Low | Medium | Mirror protocols in same PR; diff verification | +| CLAUDE.md too compressed | Low (was Medium) | Medium | Revised target ~100-110 lines; phase principles preserved | +| Regression in behavior | Low | Medium | Baseline capture + post-implementation comparison | + +--- + +## Scope Assessment + +- **Overall Complexity**: Medium (Variety Score: 8) +- **Estimated Files**: 8 new protocol files, 12 modified files (5 original + 7 agent files) +- **Specialists Required**: None (AI tooling — orchestrator may implement directly) +- **External Dependencies**: No — internal refactoring only +- **Estimated Time**: 6-7 hours implementation + 5-6 hours validation + +--- + +## PACT Framework Coverage + +This plan addresses context management across the **entire PACT framework**. + +### Complete Command Inventory + +| Command | Lines | Current @-Protocol Load | New @-Protocol Load | Plan Action | +|---------|-------|-------------------------|---------------------|-------------| +| **orchestrate.md** | 480 | ~1,320 lines | ~715 lines | ✅ Targeted @-refs | +| **plan-mode.md** | 441 | ~1,085 lines | ~165 lines | ✅ Targeted @-refs | +| **imPACT.md** | ~100 | ~235 lines | ~340 lines | ✅ Add workflow-protocols | +| **rePACT.md** | 250 | 0 | 0 | ⚪ No changes needed (verified) | +| **comPACT.md** | 190 | 0 | ~105 (optional) | ⚪ Optional workflow-protocols ref | +| **peer-review.md** | 27 | 0 | 0 | ⚪ No changes needed | +| **wrap-up.md** | 35 | 0 | 0 | ⚪ No changes needed | +| **log-changes.md** | 27 | 0 | 0 | ⚪ No changes needed | + +### rePACT Dependency Verification + +**Finding**: `rePACT.md` contains conceptual references to protocols ("Apply S2 coordination", "see Autonomy Charter") but these are **inline explanatory text**, not @-file references. The command is self-contained with its protocol details inline. **No changes needed** — verified correct. + +### Agent Files Audit + +**Finding**: Grep search of `.claude/agents/` for `@.*pact-protocols|@.*protocols/` returned **21 matches across 7 agent files**. Each agent references `pact-protocols.md` for Cross-Agent Coordination and S1 Autonomy rules. Additionally, `pact-preparer.md` references the S4 Environment Model. **8 cross-references require updates** (7 to @phase-guidance.md, 1 to @s4-checkpoints.md). See "Agent Files Cross-Reference Inventory" section for full mapping. + +### Universal Benefit: CLAUDE.md Compression + +| Entry Point | Current CLAUDE.md | After Compression | Savings | +|-------------|-------------------|-------------------|---------| +| All commands | 306 lines (~4K tokens) | ~100-110 lines (~1.3K tokens) | **67%** | + +### Per-Command Context Load (Before/After) + +| Command | Current Total | After Plan | Reduction | +|---------|---------------|------------|-----------| +| **orchestrate** | ~2,100 lines | ~1,300 lines | **38%** | +| **plan-mode** | ~1,830 lines | ~720 lines | **61%** | +| **imPACT** | ~640 lines | ~555 lines | **13%** | +| **comPACT** | ~496 lines | ~315 lines | **36%** | +| **rePACT** | ~556 lines | ~360 lines | **35%** | +| **peer-review** | ~333 lines | ~137 lines | **59%** | +| **wrap-up** | ~341 lines | ~145 lines | **57%** | +| **log-changes** | ~333 lines | ~137 lines | **59%** | + +*Note: Totals include CLAUDE.md + command file + @-referenced protocol files.* + +--- + +## Token Savings Analysis + +| Scenario | Current Load | After Refactor | Savings | +|----------|--------------|----------------|---------| +| Session start (CLAUDE.md) | ~4K | ~1.3K | 67% | +| /PACT:orchestrate invocation | ~15K | ~8K | 47% | +| /PACT:plan-mode invocation | ~12K | ~3K | 75% | +| /PACT:comPACT invocation | ~2K | ~1.5K | 25% | +| Typical full orchestration | ~45K | ~22K | **51%** | + +--- + +## Comparison: Protocol Partitioning vs Skills + +| Aspect | Skills (Superseded Plan) | Protocol Partitioning (This Plan) | +|--------|--------------------------|-----------------------------------| +| **Loading behavior** | Claude decides when to load | Deterministic, controlled | +| **Predictability** | Variable (auto-discovery) | Consistent (explicit @-refs) | +| **Fit for PACT** | Suboptimal (PACT is structured) | Optimal (matches PACT's determinism) | +| **Implementation** | New skill files + frontmatter | Partition existing content | +| **Risk** | False positive/negative loading | None (explicit control) | +| **Estimated savings** | ~73% | ~51% | + +**Trade-off**: Protocol partitioning sacrifices ~22% potential savings for predictability, verifiability, and alignment with PACT's structured workflow nature. + +--- + +## Related Context + +- **Issue**: #64 - Context Architecture Review +- **Supersedes**: PR #68 draft plan, `context-architecture-skills-plan.md` +- **Research Basis**: [Anthropic Context Engineering Guide](https://www.anthropic.com/research/building-effective-agents), PACT workflow analysis +- **Peer Review**: Incorporated feedback from pact-architect, pact-preparer, pact-test-engineer (2026-01-15) + +--- + +## Next Steps + +After approval: +``` +/PACT:orchestrate implement protocol partitioning context architecture optimization per approved plan +``` + +The orchestrator will reference this plan during execution. Since this is AI tooling (not application code), the orchestrator may implement changes directly without delegating to specialist coders. diff --git a/docs/plans/context-architecture-skills-plan.md b/docs/plans/context-architecture-skills-plan.md new file mode 100644 index 00000000..9ac49fe0 --- /dev/null +++ b/docs/plans/context-architecture-skills-plan.md @@ -0,0 +1,485 @@ +# Implementation Plan: Context Architecture Optimization (Skills-Based) + +> Generated by `/PACT:plan-mode` on 2026-01-15 +> Status: SUPERSEDED +> **Superseded by**: `context-architecture-protocols-plan.md` (protocol partitioning approach preferred over skills) + + + +## Summary + +Implement skills-based lazy loading for the PACT framework by compressing CLAUDE.md from 306 lines to ~85 lines and creating three new protocol skills (`pact-delegation`, `pact-orchestration-modes`, `pact-variety-assessment`) to replace monolithic pact-protocols.md loading. + +**Framework-wide impact**: This refactoring benefits all 8 PACT commands, not just `/PACT:orchestrate`. The heaviest commands (`orchestrate`, `plan-mode`) see 67-71% reductions, while all commands benefit from 72% smaller CLAUDE.md at session start. Expected savings: ~73% reduction in typical orchestration context load (~45K → ~12K tokens). + +**Supersedes**: PR #68 draft plan (protocol-file approach replaced by skills-based approach per Anthropic research) + +--- + +## Specialist Perspectives + +### 📋 Preparation Phase +**Effort**: Low-Medium + +#### Research Completed +- [x] Anthropic context engineering guidance reviewed +- [x] CLAUDE.md best practices documented (< 60 lines ideal, < 300 max) +- [x] Skills lazy-loading behavior understood (metadata at startup, full on activation) +- [x] Current context load measured (CLAUDE.md ~4K, pact-protocols.md ~10K tokens) + +#### Remaining Gaps (Acceptable Risk) +- [ ] Skill auto-activation keyword patterns — validate during implementation +- [ ] Cross-skill dependency handling — test during Phase 5 + +#### Questions Resolved +- **Content classification**: Architect provided detailed partitioning (see Architecture Phase) +- **Algedonic location**: Keep separate algedonic.md file (already concise, safety-critical) +- **VSM distribution**: Keep vsm-glossary.md as central reference; skills link to it + +--- + +### 🏗️ Architecture Phase +**Effort**: Medium + +#### Components Affected +| Component | Change Type | Impact | +|-----------|-------------|--------| +| `CLAUDE.md` | Compress | 306 → ~85 lines | +| `pact-protocols.md` | Reduce | 1,086 → ~300 lines (keep S1/S2/S3* only) | +| `commands/PACT/orchestrate.md` | Modify | Remove @protocol refs, add skill invocations | +| `commands/PACT/plan-mode.md` | Modify | Remove @protocol refs, add skill invocations | +| `commands/PACT/imPACT.md` | Modify | Remove @protocol refs | +| `skills/pact-delegation/` | New | ~120 lines | +| `skills/pact-orchestration-modes/` | New | ~180 lines | +| `skills/pact-variety-assessment/` | New | ~150 lines | + +#### Design Approach + +**Three-Skill Architecture**: + +``` +┌─────────────────────────────────────────────────────────────┐ +│ CLAUDE.md (~85 lines) │ +│ Always loaded: Mission, S5 Policy, Specialist list, │ +│ Command list, Skill activation guide │ +└─────────────────────────────────────────────────────────────┘ + │ + │ References by name (lazy-load on demand) + ▼ +┌─────────────────────────────────────────────────────────────┐ +│ Protocol Skills │ +│ │ +│ pact-delegation (~120 lines) │ +│ └─ Tool checkpoint, app code definition, recovery │ +│ │ +│ pact-orchestration-modes (~180 lines) │ +│ └─ S3/S4 modes, checkpoints, tensions, temporal horizons │ +│ │ +│ pact-variety-assessment (~150 lines) │ +│ └─ Variety scoring, workflow selection, strategies │ +└─────────────────────────────────────────────────────────────┘ + │ + │ Auto-activated by keywords in commands + ▼ +┌─────────────────────────────────────────────────────────────┐ +│ Commands (loaded on invocation) │ +│ └─ No @pact-protocols refs; reference skills by name │ +└─────────────────────────────────────────────────────────────┘ +``` + +#### Key Decisions +| Decision | Options | Recommendation | Rationale | +|----------|---------|----------------|-----------| +| Skill count | 3 focused vs 4-5 fine-grained | 3 skills | Clear boundaries, targeted loading, simpler maintenance | +| CLAUDE.md size | 60-80 vs 80-100 lines | ~85 lines | Balance between compression and safety-critical content | +| Algedonic handling | In CLAUDE.md vs skill vs separate | Keep algedonic.md | Already concise, safety-critical, well-isolated | +| Protocol residue | Delete vs lean file | Lean (~300 lines) | Keep S1/S2/S3* for specialized cases | + +#### Interface Contracts + +**Skill Discovery Mechanism**: + +Skills in Claude Code are auto-discovered based on their `description` frontmatter. Claude reads all skill descriptions at session start and activates the relevant skill when conversation context matches. + +**Command Text Pattern** (how commands trigger skills): +```markdown +# Current (loads entire 1,086-line file): +See @~/.claude/protocols/pact-protocols.md for S4 Checkpoint Protocol. + +# New (triggers skill discovery via keywords): +When performing S4 checkpoints, apply the S4 Checkpoint Protocol. +``` + +The new text contains "S4 checkpoint" which matches `pact-orchestration-modes` description, causing Claude to load only that ~180-line skill. + +**Trigger Keywords by Skill** (embedded in description): +| Skill | Keywords in Description | +|-------|-------------------------| +| `pact-delegation` | delegate, Edit, Write, application code, tool checkpoint, recovery | +| `pact-orchestration-modes` | S3, S4, checkpoint, tension, phase transition, temporal horizon | +| `pact-variety-assessment` | variety, complexity, comPACT, orchestrate, plan-mode, workflow selection | + +**Best Practice**: Commands should use natural language containing trigger keywords rather than explicit "invoke skill X" instructions. This allows Claude's discovery mechanism to work naturally. + +--- + +### 💻 Code Phase +**Effort**: Medium + +> **Note**: This is AI tooling (.claude/ files), not application code. Per delegation rules, the orchestrator may implement these changes directly. No specialist delegation required. + +#### Files to Create +| File | Purpose | Est. Lines | +|------|---------|------------| +| `.claude/skills/pact-delegation/SKILL.md` | Delegation enforcement, tool checkpoint, recovery | ~120 | +| `.claude/skills/pact-orchestration-modes/SKILL.md` | S3/S4 modes, checkpoints, temporal horizons | ~180 | +| `.claude/skills/pact-variety-assessment/SKILL.md` | Variety scoring, workflow selection | ~150 | + +#### Skill Specifications (Frontmatter & Discovery) + +Skills are discovered through their `description` field, not @-references. Claude reads skill descriptions at session start and auto-activates based on context matching. + +**pact-delegation**: +```yaml +--- +name: pact-delegation +description: | + Delegation enforcement rules and tool checkpoint protocol for PACT orchestrators. + Use when: about to edit application code, using Edit/Write tools, determining + what constitutes application code, or recovering from delegation violations. + Triggers on: delegate, Edit, Write, application code, tool checkpoint, recovery, + specialist agents, code ownership. +--- +``` + +**pact-orchestration-modes**: +```yaml +--- +name: pact-orchestration-modes +description: | + S3/S4 operational modes, checkpoints, and tension resolution for PACT orchestration. + Use when: transitioning between phases, performing S4 checkpoints, detecting S3/S4 + tension, assessing temporal horizons, or managing mode transitions. + Triggers on: S3, S4, checkpoint, tension, phase transition, temporal horizon, + inside-now, outside-future, mode, operational control, strategic intelligence. +--- +``` + +**pact-variety-assessment**: +```yaml +--- +name: pact-variety-assessment +description: | + Variety scoring rubric and workflow selection for PACT task complexity assessment. + Use when: starting a new task, selecting between comPACT/orchestrate/plan-mode, + assessing task complexity, or applying variety attenuators/amplifiers. + Triggers on: variety, complexity, comPACT, orchestrate, plan-mode, workflow + selection, novelty, scope, uncertainty, risk, attenuate, amplify. +--- +``` + +#### How Skill Discovery Replaces @-References + +**Current pattern** (loads entire file): +```markdown +See @~/.claude/protocols/pact-protocols.md for S4 Checkpoint Protocol. +``` + +**New pattern** (triggers skill discovery): +```markdown +When performing S4 checkpoints, apply the S4 Checkpoint Protocol. +``` + +Claude's skill discovery matches "S4 checkpoint" against `pact-orchestration-modes` description and loads only that skill (~180 lines vs ~1,086 lines). + +**Key insight**: We remove explicit @-references and use natural language that contains the trigger keywords defined in skill descriptions. Claude handles the discovery automatically. + +#### Files to Modify +| File | Changes | +|------|---------| +| `CLAUDE.md` | Compress from 306 → ~85 lines per structure below | +| `.claude/protocols/pact-protocols.md` | Reduce from 1,086 → ~300 lines (keep S1/S2/S3* only) | +| `.claude/commands/PACT/orchestrate.md` | Remove @pact-protocols refs, add skill references | +| `.claude/commands/PACT/plan-mode.md` | Remove @pact-protocols ref, add skill references | +| `.claude/commands/PACT/imPACT.md` | Remove @algedonic ref (keep algedonic.md reference) | +| `pact-plugin/skills/` | Mirror new skills for plugin distribution | + +#### CLAUDE.md Proposed Structure (~85 lines) + +```markdown +# MISSION (7 lines) +Mission statement, motto + +## S5 POLICY (12 lines) +Non-negotiables table (4 rows), policy checkpoint summary +→ "Invoke pact-delegation skill for enforcement details" + +## INSTRUCTIONS (6 lines) +Core directives + +## GUIDELINES (12 lines) +Context management, git workflow, communication + +## PACT PHASES (8 lines) +Phase names + one-liner principles +→ "Invoke domain skills for detailed phase guidance" + +## SPECIALIST AGENTS (10 lines) +Agent list with emoji identifiers + +## ORCHESTRATION COMMANDS (12 lines) +Command list with one-line descriptions +→ "Invoke pact-variety-assessment skill to select workflow" + +## DOCUMENTATION LOCATIONS (8 lines) +Phase → Output Location table + +## SKILL ACTIVATION GUIDE (10 lines) +When to invoke each protocol skill +``` + +#### Implementation Sequence +1. `feat(skills): create pact-delegation skill` — Extract delegation content +2. `feat(skills): create pact-orchestration-modes skill` — Extract S3/S4 content +3. `feat(skills): create pact-variety-assessment skill` — Extract variety content +4. `refactor(claude): compress CLAUDE.md to ~85 lines` — Restructure with skill refs +5. `refactor(protocols): reduce pact-protocols.md to ~300 lines` — Keep S1/S2/S3* only +6. `refactor(commands): update orchestrate.md skill references` — Remove @protocol loads +7. `refactor(commands): update plan-mode.md skill references` — Remove @protocol loads +8. `refactor(commands): update imPACT.md references` — Minor cleanup +9. `chore(plugin): sync new skills to pact-plugin/` — Mirror for distribution + +--- + +### 🧪 Test Phase +**Effort**: Medium (4-6 hours manual validation) + +#### Test Scenarios +| Scenario | Type | Priority | +|----------|------|----------| +| `/PACT:orchestrate` invokes correct skills | Integration | P0 | +| `/PACT:comPACT` loads delegation skill | Integration | P0 | +| Delegation enforcement on app code edit | Functional | P0 | +| Algedonic HALT signal bypasses to user | Functional | P0 | +| Tool Checkpoint Protocol fires before Edit/Write | Functional | P0 | +| `/PACT:plan-mode` activates variety skill | Integration | P1 | +| `/PACT:imPACT` loads triage guidance | Integration | P1 | +| S3/S4 mode detection in responses | Functional | P1 | +| `/PACT:rePACT` nested skill loading | Edge case | P2 | +| Multiple skills loaded in single command | Edge case | P2 | + +#### Coverage Targets +- Critical path (P0): 100% — Must pass for merge +- Core workflows (P1): 100% — Should pass for merge +- Edge cases (P2): Best effort — May defer + +#### Validation Approach + +**Phase 1: Smoke Testing (1-2 hours)** +- Execute each PACT command once +- Verify skill-specific guidance appears +- Check delegation enforcement + +**Phase 2: Comprehensive Validation (3-4 hours)** +- All P0/P1 scenarios +- Before/after comparison for lost guidance +- Edge case testing + +#### Acceptance Criteria +- [ ] All new skill files exist and are syntactically valid +- [ ] Compressed CLAUDE.md contains delegation enforcement rules +- [ ] Compressed CLAUDE.md contains SACROSANCT policy +- [ ] `/PACT:orchestrate` executes without errors +- [ ] `/PACT:comPACT` executes without errors +- [ ] Tool Checkpoint Protocol triggers on application code +- [ ] Algedonic HALT scenario escalates to user +- [ ] No command produces "skill not found" errors + +--- + +## Synthesized Implementation Roadmap + +### Phase Sequence + +``` +Phase 1: Create Skills (Low Risk) +├── pact-delegation/SKILL.md +├── pact-orchestration-modes/SKILL.md +└── pact-variety-assessment/SKILL.md + │ + ▼ Smoke test skill activation + │ +Phase 2: Compress CLAUDE.md (Medium Risk) +├── Restructure to ~85 lines +└── Add skill activation guide + │ + ▼ Validate delegation/algedonic preserved + │ +Phase 3: Update Commands (Medium Risk) +├── orchestrate.md +├── plan-mode.md +└── imPACT.md + │ + ▼ Full command validation + │ +Phase 4: Lean Protocol (Low Risk) +└── Reduce pact-protocols.md to ~300 lines + │ + ▼ Comprehensive validation + │ +Phase 5: Plugin Sync (Low Risk) +└── Mirror to pact-plugin/ + │ + ▼ Final PR review +``` + +### Commit Sequence (Proposed) + +> **Note**: This sequence represents the intended final git history order, **not** the execution order. Phases 1-3 may have parallel work streams. + +1. `feat(skills): create pact-delegation skill with tool checkpoint protocol` — Delegation enforcement content +2. `feat(skills): create pact-orchestration-modes skill with S3/S4 guidance` — Operational modes content +3. `feat(skills): create pact-variety-assessment skill with scoring rubric` — Variety management content +4. `refactor(claude): compress CLAUDE.md from 306 to ~85 lines` — Core restructuring +5. `refactor(protocols): reduce pact-protocols.md to S1/S2/S3* sections (~300 lines)` — Protocol cleanup +6. `refactor(commands): update PACT commands to reference skills instead of protocols` — Command updates +7. `chore(plugin): sync new skills to pact-plugin/ directory` — Distribution sync +8. `docs: update context architecture documentation` — Document new structure + +--- + +## Cross-Cutting Concerns + +| Concern | Status | Notes | +|---------|--------|-------| +| Security | ✅ Ready | Delegation enforcement and algedonic signals preserved in accessible locations | +| Performance | ✅ Focus | ~73% token reduction: ~45K → ~12K per orchestration | +| Accessibility | N/A | Not frontend work | +| Observability | ⚠️ Monitor | Track skill activation patterns during validation | + +--- + +## Open Questions + +### Require User Decision + +None — all key decisions resolved during synthesis. + +### Require Further Research + +- [ ] **Skill auto-activation reliability**: Validate trigger keywords work as expected during Phase 1 +- [ ] **Cross-skill dependencies**: Test if `pact-variety-assessment` correctly informs orchestration mode selection during Phase 3 + +--- + +## Risk Assessment + +| Risk | Likelihood | Impact | Mitigation | +|------|------------|--------|------------| +| Skill auto-activation fails | Medium | High | Careful keyword selection; fallback instructions in CLAUDE.md | +| Critical guidance lost in compression | Low | High | Before/after comparison; keep delegation/algedonic explicit | +| Commands break after @ref removal | Medium | Medium | Staged rollout; test each command after update | +| Plugin sync drift | Low | Medium | Mirror skills in same PR; verify with diff | +| Content duplication across skills | Low | Low | Clear ownership; cross-references not duplication | + +--- + +## Scope Assessment + +- **Overall Complexity**: Medium (Variety Score: 9) +- **Estimated Files**: 3 new skill files, 6 modified files +- **Specialists Required**: None (AI tooling — orchestrator may implement directly) +- **External Dependencies**: No — internal refactoring only + +--- + +## PACT Framework Coverage + +This plan addresses context management across the **entire PACT framework**, not just `/PACT:orchestrate`. + +### Complete Command Inventory + +| Command | Lines | @-Protocol References | Plan Action | +|---------|-------|----------------------|-------------| +| **orchestrate.md** | 480 | 6× pact-protocols + 1× algedonic | ✅ Remove @refs, add skill invocations | +| **plan-mode.md** | 441 | 1× pact-protocols | ✅ Remove @refs, add skill invocations | +| **imPACT.md** | ~100 | 2× algedonic | ✅ Simplify algedonic refs | +| **rePACT.md** | 250 | None (self-contained) | ⚪ No changes needed | +| **comPACT.md** | 190 | None (self-contained) | ⚪ No changes needed | +| **peer-review.md** | 27 | None (self-contained) | ⚪ No changes needed | +| **wrap-up.md** | 35 | None (refs skill) | ⚪ No changes needed | +| **log-changes.md** | 27 | None (self-contained) | ⚪ No changes needed | + +**Key insight**: Only three commands (`orchestrate`, `plan-mode`, `imPACT`) have @-protocol references that cause heavy context loading. The remaining five commands are already lightweight and self-contained. + +### Universal Benefit: CLAUDE.md Compression + +The CLAUDE.md compression (306 → ~85 lines) benefits **every command and every session**: + +| Entry Point | Current CLAUDE.md | After Compression | Savings | +|-------------|-------------------|-------------------|---------| +| All commands | 306 lines (~4K tokens) | ~85 lines (~1K tokens) | **72%** | + +### Per-Command Context Load (Before/After) + +| Command | Current Total | After Plan | Reduction | +|---------|---------------|------------|-----------| +| **orchestrate** | ~2,100 lines | ~700 lines | **67%** | +| **plan-mode** | ~1,830 lines | ~530 lines | **71%** | +| **imPACT** | ~640 lines | ~320 lines | **50%** | +| **comPACT** | ~496 lines | ~275 lines | **45%** | +| **rePACT** | ~556 lines | ~335 lines | **40%** | +| **peer-review** | ~333 lines | ~112 lines | **66%** | +| **wrap-up** | ~341 lines | ~120 lines | **65%** | +| **log-changes** | ~333 lines | ~112 lines | **66%** | + +*Note: Totals include CLAUDE.md + command file + any @-referenced protocol files.* + +### Why Lightweight Commands Still Benefit + +Commands like `comPACT`, `rePACT`, and `peer-review` have no @-protocol references, but they still load CLAUDE.md at session start. The 72% reduction in CLAUDE.md size means: +- More context budget available for actual task work +- Reduced risk of hitting context limits during extended sessions +- Faster session initialization + +--- + +## Token Savings Analysis + +| Scenario | Current Load | After Refactor | Savings | +|----------|--------------|----------------|---------| +| Session start (CLAUDE.md) | ~4K | ~1K | 75% | +| /PACT:orchestrate invocation | +15K (protocols) | +2K (targeted skills) | 87% | +| /PACT:comPACT invocation | ~2K (no protocols) | ~1K | 50% | +| /PACT:plan-mode invocation | +10K (protocols) | +2K (targeted skills) | 80% | +| Typical full orchestration | ~45K | ~12K | **73%** | + +--- + +## Related Context + +- **Issue**: #64 - Context Architecture Review +- **Supersedes**: PR #68 draft plan (protocol-file approach) +- **Research Basis**: Anthropic Context Engineering Guide, Skill Authoring Best Practices + +--- + +## Next Steps + +After approval: +``` +/PACT:orchestrate implement skills-based context architecture optimization per approved plan +``` + +The orchestrator will reference this plan during execution. Since this is AI tooling (not application code), the orchestrator may implement changes directly without delegating to specialist coders.