xonecas.io
60255
Zn

Zoea-Nova / commit 4cdc72c

docs: add loop context composition workflow and implementation report

Workflow documents:
- Parallel execution strategy (19 agent roles)
- Visual workflow diagrams (Mermaid)
- Execution checklist with gate criteria
- Complete workflow index

Implementation report:
- 5-phase execution summary
- All review checkpoint results
- Test coverage metrics (11 new tests, 147 passing)
- Code change statistics (+1,087 lines net)
- Architecture comparison (before/after)
- Known issues and mitigation
- Validation results (all criteria met)
- Migration notes

Status: COMPLETE - Ready for merge and release

xonecas2026-02-07 4cdc72c84e9b06b8288eda9d4e1a273fef00c61b parent b94e248

6 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

documentation/plans/2026-02-07-loop-context-README.md+191−0
@@ -0,0 +1,191 @@
1+# Loop Context Composition Implementation - Documentation Index
2+
3+**Created:** 2026-02-07
4+**Status:** Ready for Execution
5+
6+---
7+
8+## Overview
9+
10+This directory contains the complete workflow for implementing the Loop Context Composition feature, which rebuilds LLM context composition to use a deterministic loop slice approach.
11+
12+**Goal:** Replace "recent memories + compaction" with "system prompt + chosen prompt source + most recent tool-call/result loop" to ensure stable, bounded context and eliminate orphaned tool sequencing.
13+
14+---
15+
16+## Document Structure
17+
18+### 1. Original Plan
19+**File:** [2026-02-07-loop-context-composition.md](2026-02-07-loop-context-composition.md)
20+
21+The source plan with 5 tasks:
22+1. Add context selection tests (prompt source priority)
23+2. Add loop slice tests (tool call/result inclusion)
24+3. Implement new context composition
25+4. Update documentation
26+5. Run core tests
27+
28+**Use this for:** Technical implementation details, code examples, test patterns
29+
30+---
31+
32+### 2. Parallel Workflow Strategy
33+**File:** [2026-02-07-loop-context-parallel-workflow.md](2026-02-07-loop-context-parallel-workflow.md)
34+
35+Execution strategy maximizing parallel agent work with review checkpoints.
36+
37+**Structure:**
38+- **Phase 1:** Test Infrastructure (3 agents parallel)
39+- **Phase 2:** Helper Implementation (2 agents parallel)
40+- **Phase 3:** Context Integration (1 agent serial)
41+- **Phase 4:** Documentation (2 agents parallel)
42+- **Phase 5:** Full Validation (3 agents parallel)
43+
44+**Features:**
45+- 8 implementation agents
46+- 8 review agents
47+- 3 validation agents
48+- 5 quality gates
49+- Rollback procedures
50+- Risk mitigation
51+
52+**Use this for:** Understanding the execution strategy, agent roles, review criteria, success metrics
53+
54+---
55+
56+### 3. Visual Workflow Diagrams
57+**File:** [2026-02-07-loop-context-workflow-diagram.md](2026-02-07-loop-context-workflow-diagram.md)
58+
59+Mermaid diagrams visualizing the workflow:
60+- Overall workflow with gates and rollback paths
61+- Per-phase agent collaboration diagrams
62+- Agent dependency graph
63+- Gantt chart timing analysis
64+- Critical path identification
65+- Success criteria pie chart
66+
67+**Use this for:** Visual understanding of workflow, timing analysis, critical path identification
68+
69+---
70+
71+### 4. Execution Checklist
72+**File:** [2026-02-07-loop-context-checklist.md](2026-02-07-loop-context-checklist.md)
73+
74+Practical execution checklist with checkboxes for every task, review, and gate.
75+
76+**Features:**
77+- Per-phase task checklists
78+- Review checkpoint criteria
79+- Gate decision points
80+- Success criteria tracking
81+- Notes section for observations
82+- Rollback procedures
83+- Quick reference commands
84+
85+**Use this for:** Day-to-day execution tracking, progress monitoring, gate decisions
86+
87+---
88+
89+## Quick Start
90+
91+### For Implementation Agents:
92+1. Read the **Original Plan** to understand your specific task
93+2. Check the **Checklist** for your phase's tasks
94+3. Execute your assigned work
95+4. Mark checkboxes as you complete items
96+
97+### For Review Agents:
98+1. Check the **Parallel Workflow** for your review criteria
99+2. Use the **Checklist** review sections to verify completeness
100+3. Refer to **Visual Diagrams** to understand dependencies
101+4. Approve or reject at your gate
102+
103+### For Project Managers:
104+1. Use **Visual Diagrams** to explain workflow to stakeholders
105+2. Track progress using the **Checklist**
106+3. Monitor critical path (Phase 3) closely
107+4. Reference **Parallel Workflow** for risk mitigation
108+
109+---
110+
111+## Execution Flow
112+
113+```
114+Original Plan → Parallel Workflow → Visual Diagrams → Checklist
115+ ↓ ↓ ↓ ↓
116+ What to do How to organize What it looks Track progress
117+ agents & reviews like visually & decisions
118+```
119+
120+---
121+
122+## Key Metrics
123+
124+**Total Agents:** 19 (8 implementation, 8 review, 3 validation)
125+**Max Parallelism:** 6 agents (Phase 1)
126+**Total Phases:** 5
127+**Quality Gates:** 5
128+**Estimated Time:** 70 time units (vs 90 sequential)
129+**Speedup:** 22% faster than sequential execution
130+
131+---
132+
133+## Success Criteria Summary
134+
135+- ✅ All 5 plan tasks completed
136+- ✅ All new tests pass (100% success rate)
137+- ✅ No test regressions
138+- ✅ No race conditions detected
139+- ✅ Documentation updated and reviewed
140+- ✅ 8 review checkpoints passed
141+- ✅ Clean build on main branch
142+- ✅ Offline smoke test passes
143+
144+---
145+
146+## Next Steps
147+
148+1. **Review this index** to understand the document structure
149+2. **Read the Parallel Workflow** to understand agent roles
150+3. **Start with Phase 1** of the Checklist
151+4. **Execute tasks** according to the Original Plan
152+5. **Pass through gates** using review criteria
153+6. **Complete validation** in Phase 5
154+7. **Archive to reports/** after successful merge
155+
156+---
157+
158+## Files in This Workflow
159+
160+| File | Purpose | Primary Users |
161+|------|---------|---------------|
162+| 2026-02-07-loop-context-composition.md | Technical plan | Implementation agents |
163+| 2026-02-07-loop-context-parallel-workflow.md | Execution strategy | All agents, PM |
164+| 2026-02-07-loop-context-workflow-diagram.md | Visual reference | PM, stakeholders |
165+| 2026-02-07-loop-context-checklist.md | Progress tracking | All agents, PM |
166+| 2026-02-07-loop-context-README.md | This file | Everyone |
167+
168+---
169+
170+## Questions?
171+
172+- **"What task do I work on?"** → Check Original Plan + Checklist for your agent number
173+- **"Who do I wait for?"** → Check Visual Diagrams → Agent Dependency Graph
174+- **"What are the review criteria?"** → Check Parallel Workflow → Your Review Checkpoint section
175+- **"Is my phase done?"** → Check Checklist → Gate decision criteria
176+- **"Something failed, now what?"** → Check Checklist → Rollback Procedures
177+
178+---
179+
180+## Post-Implementation
181+
182+After successful completion:
183+1. Move this README and all workflow docs to `documentation/reports/`
184+2. Create summary report: `LOOP_CONTEXT_IMPLEMENTATION_REPORT.md`
185+3. Update `documentation/current/TODO.md`
186+4. Archive original plan to `documentation/archive/` (optional)
187+
188+---
189+
190+Last Updated: 2026-02-07
191+Status: Ready for Execution
documentation/plans/2026-02-07-loop-context-checklist.md+288−0
@@ -0,0 +1,288 @@
1+# Loop Context Composition - Execution Checklist
2+
3+**Plan:** [2026-02-07-loop-context-composition.md](2026-02-07-loop-context-composition.md)
4+**Workflow:** [2026-02-07-loop-context-parallel-workflow.md](2026-02-07-loop-context-parallel-workflow.md)
5+**Diagrams:** [2026-02-07-loop-context-workflow-diagram.md](2026-02-07-loop-context-workflow-diagram.md)
6+
7+---
8+
9+## Phase 1: Test Infrastructure
10+
11+### Implementation (Parallel)
12+- [ ] **Agent 1:** Write `TestContextPromptSourcePriority` in `internal/core/mysis_test.go`
13+ - [ ] Commander direct present case
14+ - [ ] Commander direct missing, broadcast present case
15+ - [ ] Commander broadcasts missing, swarm broadcast present case
16+ - [ ] No broadcasts, nudge generation case
17+ - [ ] Test compiles and fails
18+
19+- [ ] **Agent 2:** Write `TestLoopContextSlice` in `internal/core/orphaned_tool_results_test.go`
20+ - [ ] Only most recent tool-call included
21+ - [ ] Tool results for most recent call included
22+ - [ ] Older tool loops excluded
23+ - [ ] Test compiles and fails
24+
25+- [ ] **Agent 3:** Write tool pairing tests in `internal/core/agent3_reproduction_test.go`
26+ - [ ] Tool results only appear with matching tool calls
27+ - [ ] No orphaned tool results detected
28+ - [ ] Test compiles and fails
29+
30+### Review Checkpoint 1
31+- [ ] **Review Agent A:** Test coverage complete
32+ - [ ] All priority edge cases covered
33+ - [ ] Tests are isolated (no shared state)
34+ - [ ] Test names follow convention
35+
36+- [ ] **Review Agent B:** Test quality verified
37+ - [ ] Table-driven where appropriate
38+ - [ ] Assertions are specific and actionable
39+ - [ ] Setup/teardown correct
40+ - [ ] Tests fail for correct reasons
41+
42+### Integration
43+- [ ] Run: `go test ./internal/core -run "TestContextPromptSourcePriority|TestLoopContextSlice" -v`
44+- [ ] Verify all tests fail as expected
45+- [ ] Commit: `git add internal/core/*_test.go`
46+- [ ] Commit message: "test(core): add loop context composition tests"
47+
48+### Gate 1: Proceed? ☐ YES ☐ NO
49+
50+---
51+
52+## Phase 2: Helper Implementation
53+
54+### Implementation (Parallel)
55+- [ ] **Agent 4:** Implement `selectPromptSource` in `internal/core/mysis.go`
56+ - [ ] Find most recent commander direct
57+ - [ ] Fallback to last commander broadcast
58+ - [ ] Fallback to last swarm broadcast
59+ - [ ] Return nil if none found
60+ - [ ] Unit test helpers pass
61+
62+- [ ] **Agent 5:** Implement `extractLatestToolLoop` in `internal/core/mysis.go`
63+ - [ ] Reverse scan for most recent tool-call
64+ - [ ] Collect tool-call message
65+ - [ ] Collect subsequent tool results
66+ - [ ] Handle edge cases (no tool calls, tool call with no results)
67+ - [ ] Unit test helpers pass
68+
69+### Review Checkpoint 2
70+- [ ] **Review Agent C:** Implementation correctness
71+ - [ ] `selectPromptSource` checks correct priority order
72+ - [ ] `extractLatestToolLoop` handles all edge cases
73+ - [ ] Error handling correct (nil checks, empty slices)
74+ - [ ] No mutations to input slices
75+
76+- [ ] **Review Agent D:** Performance & safety
77+ - [ ] Efficient memory handling (no unnecessary copies)
78+ - [ ] Slice bounds checking correct
79+ - [ ] No nil pointer dereferences
80+ - [ ] Helper tests pass
81+
82+### Integration
83+- [ ] Run: `go test ./internal/core -run "Helper" -v`
84+- [ ] Verify helper unit tests pass
85+- [ ] Commit: `git add internal/core/mysis.go`
86+- [ ] Commit message: "feat(core): add context composition helpers"
87+
88+### Gate 2: Proceed? ☐ YES ☐ NO
89+
90+---
91+
92+## Phase 3: Context Composition Integration
93+
94+### Implementation (Serial)
95+- [ ] **Agent 6:** Rewrite `getContextMemories` in `internal/core/mysis.go`
96+ - [ ] Filter for system prompt (source="system")
97+ - [ ] Call `selectPromptSource` for prompt memory
98+ - [ ] Generate synthetic nudge if prompt is nil (up to 3 attempts)
99+ - [ ] Call `extractLatestToolLoop` for tool messages
100+ - [ ] Compose: [system, prompt, ...toolLoop]
101+ - [ ] Remove old compaction/orphan logic
102+
103+### Review Checkpoint 3
104+- [ ] **Review Agent E:** Integration review
105+ - [ ] All Task 1 & 2 tests now pass
106+ - [ ] Context size is bounded and predictable
107+ - [ ] No orphaned tool results possible
108+ - [ ] Synthetic nudge generation works (counter increment)
109+ - [ ] Idle transition after 3 nudges verified
110+
111+- [ ] **Review Agent F:** Regression review
112+ - [ ] Full `internal/core` test suite passes
113+ - [ ] No existing tests broken
114+ - [ ] Mysis state machine tests still pass
115+ - [ ] Goroutine cleanup tests unaffected
116+
117+### Integration
118+- [ ] Run: `go test ./internal/core -run "TestContext|TestLoopContext|TestOrphaned" -v`
119+- [ ] Run: `go test ./internal/core -v`
120+- [ ] Verify all tests pass, no regressions
121+- [ ] Commit: `git add internal/core/mysis.go`
122+- [ ] Commit message: "fix(core): compose context from prompt source and last tool loop"
123+
124+### Gate 3: Proceed? ☐ YES ☐ NO
125+
126+---
127+
128+## Phase 4: Documentation
129+
130+### Implementation (Parallel)
131+- [ ] **Agent 7:** Update `documentation/architecture/CONTEXT_COMPRESSION.md`
132+ - [ ] Describe loop slice model
133+ - [ ] Add prompt source priority diagram
134+ - [ ] Document loop extraction algorithm
135+ - [ ] Explain context composition order
136+ - [ ] Document bounded size guarantees
137+
138+- [ ] **Agent 8:** Add code comments to `internal/core/mysis.go`
139+ - [ ] `selectPromptSource` documented (purpose, params, returns, edge cases)
140+ - [ ] `extractLatestToolLoop` documented
141+ - [ ] `getContextMemories` updated comments
142+ - [ ] Test file comments updated
143+
144+### Review Checkpoint 4
145+- [ ] **Review Agent G:** Documentation review
146+ - [ ] Architecture doc matches implementation
147+ - [ ] Code comments are accurate
148+ - [ ] Examples are correct
149+ - [ ] KNOWN_ISSUES.md updated if relevant
150+ - [ ] README.md still accurate
151+
152+### Integration
153+- [ ] Verify documentation accuracy
154+- [ ] Commit: `git add documentation/architecture/CONTEXT_COMPRESSION.md internal/core/mysis.go internal/core/mysis_test.go`
155+- [ ] Commit message: "docs: document loop slice context composition"
156+
157+### Gate 4: Proceed? ☐ YES ☐ NO
158+
159+---
160+
161+## Phase 5: Full Validation
162+
163+### Validation (Parallel)
164+- [ ] **Agent 9:** Unit test validation
165+ - [ ] Run: `go test ./internal/core -v -race -count=5`
166+ - [ ] No flaky tests detected
167+ - [ ] Race detector clean
168+ - [ ] 5 consecutive passes confirmed
169+
170+- [ ] **Agent 10:** Integration test validation
171+ - [ ] Run: `make test`
172+ - [ ] Full test suite passes
173+ - [ ] No unexpected failures
174+ - [ ] Coverage maintained or improved
175+
176+- [ ] **Agent 11:** Build validation
177+ - [ ] Run: `make clean && make build`
178+ - [ ] Clean build succeeds
179+ - [ ] Run: `./bin/zoea --offline`
180+ - [ ] Binary runs without crashes
181+ - [ ] Offline mode smoke test passes
182+
183+### Final Review Checkpoint
184+- [ ] **Review Agent H:** Release readiness
185+ - [ ] All tests pass (unit + integration)
186+ - [ ] No race conditions detected
187+ - [ ] Documentation complete and accurate
188+ - [ ] KNOWN_ISSUES.md updated if needed
189+ - [ ] Commits follow conventional format
190+ - [ ] All plan tasks completed
191+
192+### Gate 5: Proceed? ☐ YES ☐ NO
193+
194+---
195+
196+## Success Criteria
197+
198+- [ ] All 5 plan tasks completed
199+- [ ] All new tests pass (100% success rate)
200+- [ ] No test regressions
201+- [ ] No race conditions detected
202+- [ ] Documentation updated and reviewed
203+- [ ] 8 review checkpoints passed
204+- [ ] Clean build on main branch
205+- [ ] Offline smoke test passes
206+
207+---
208+
209+## Post-Implementation
210+
211+- [ ] Merge feature branch to main
212+- [ ] Tag release (if appropriate)
213+- [ ] Archive workflow document to `documentation/reports/`
214+- [ ] Update `documentation/current/TODO.md` to mark tasks complete
215+- [ ] Monitor production for unexpected behavior
216+- [ ] Update this checklist with lessons learned
217+
218+---
219+
220+## Notes Section
221+
222+Use this space to track issues, decisions, or observations during execution:
223+
224+```
225+[Date/Time] Phase X - Agent Y: <note>
226+
227+Example:
228+[2026-02-07 14:30] Phase 2 - Agent 4: selectPromptSource needed additional nil check for empty memories slice
229+```
230+
231+---
232+
233+## Rollback Procedures
234+
235+If any gate fails:
236+
237+**Phase 1-4 Rollback:**
238+1. Identify failing agent's work
239+2. Run: `git diff HEAD`
240+3. Run: `git checkout -- <failing-file>`
241+4. Re-execute agent's task with fixes
242+5. Re-run review checkpoint
243+6. Update notes section with issue details
244+
245+**Phase 5 Rollback (Complete Failure):**
246+1. Run: `git log --oneline -10`
247+2. Find commit before feature branch started
248+3. Run: `git reset --hard <commit-hash>`
249+4. Review plan for missing requirements
250+5. Add missing test cases to Phase 1
251+6. Re-execute from Phase 1
252+
253+---
254+
255+## Agent Commands Quick Reference
256+
257+```bash
258+# Phase 1: Test verification
259+go test ./internal/core -run "TestContextPromptSourcePriority|TestLoopContextSlice" -v
260+
261+# Phase 2: Helper verification
262+go test ./internal/core -run "Helper" -v
263+
264+# Phase 3: Integration verification
265+go test ./internal/core -run "TestContext|TestLoopContext|TestOrphaned" -v
266+go test ./internal/core -v
267+
268+# Phase 5: Full validation
269+go test ./internal/core -v -race -count=5
270+make test
271+make clean && make build
272+./bin/zoea --offline
273+
274+# Format code
275+make fmt
276+
277+# View recent commits
278+git log --oneline -10
279+
280+# Check diff before commit
281+git diff
282+git diff --cached
283+```
284+
285+---
286+
287+Last Updated: 2026-02-07
288+Status: Ready for Execution
documentation/plans/2026-02-07-loop-context-composition.md+158−0
@@ -0,0 +1,158 @@
1+# LLM Loop Context Composition Plan
2+
3+> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
4+
5+**Goal:** Rebuild LLM context composition to include only the system/prompt source plus the most recent tool-call/result loop, using a fixed priority for prompt sources.
6+
7+**Architecture:** Replace the current “recent memories + compaction” approach with a deterministic loop slice: system prompt + chosen prompt source (commander → last commander broadcast → last swarm broadcast → nudge) + the tool call/result pairs from the most recent loop. This ensures stable, bounded context and eliminates orphaned tool sequencing.
8+
9+**Tech Stack:** Go 1.22, Bubble Tea, SQLite store, zerolog
10+
11+---
12+
13+### Task 1: Add context selection tests (prompt source priority)
14+
15+**Files:**
16+- Modify: `internal/core/mysis_test.go`
17+
18+**Step 1: Write the failing test**
19+
20+Add tests that build memories and assert the chosen prompt source:
21+
22+```go
23+func TestContextPromptSourcePriority(t *testing.T) {
24+ // Arrange system prompt + commander direct + commander broadcast + swarm broadcast
25+ // Act: getContextMemories
26+ // Assert: context includes commander direct and excludes other prompt sources
27+}
28+```
29+
30+Add separate cases for:
31+- commander direct missing → use last commander broadcast
32+- commander broadcasts missing → use last swarm broadcast
33+- no broadcasts → use synthetic nudge
34+
35+**Step 2: Run test to verify it fails**
36+
37+Run:
38+```bash
39+go test ./internal/core -run TestContextPromptSourcePriority
40+```
41+Expected: FAIL.
42+
43+**Step 3: Commit (tests only)**
44+
45+```bash
46+git add internal/core/mysis_test.go
47+git commit -m "test(core): cover prompt source selection"
48+```
49+
50+---
51+
52+### Task 2: Add loop slice tests (tool call/result inclusion)
53+
54+**Files:**
55+- Modify: `internal/core/orphaned_tool_results_test.go`
56+- Modify: `internal/core/agent3_reproduction_test.go`
57+
58+**Step 1: Write the failing tests**
59+
60+Add a test that asserts:
61+- Only the *most recent* tool-call message and its tool results are present.
62+- Older tool loops are excluded.
63+
64+Add a test that asserts:
65+- Tool results are present *only when* the matching tool call is present.
66+- No orphaned tool results exist.
67+
68+**Step 2: Run tests to verify they fail**
69+
70+Run:
71+```bash
72+go test ./internal/core -run TestLoopContextSlice
73+```
74+Expected: FAIL.
75+
76+**Step 3: Commit (tests only)**
77+
78+```bash
79+git add internal/core/orphaned_tool_results_test.go internal/core/agent3_reproduction_test.go
80+git commit -m "test(core): cover loop slice tool pairing"
81+```
82+
83+---
84+
85+### Task 3: Implement new context composition
86+
87+**Files:**
88+- Modify: `internal/core/mysis.go`
89+
90+**Step 1: Implement helper functions**
91+
92+Add helpers for:
93+- selecting the prompt source memory by priority
94+- extracting the most recent tool-call loop and its tool results
95+
96+Example signatures:
97+```go
98+func (m *Mysis) selectPromptSource(memories []*store.Memory) *store.Memory
99+func (m *Mysis) extractLatestToolLoop(memories []*store.Memory) []*store.Memory
100+```
101+
102+**Step 2: Update `getContextMemories`**
103+
104+Replace existing compaction/orphan logic with:
105+- system prompt
106+- chosen prompt source
107+- latest tool-call + tool-result pair list
108+
109+**Step 3: Run tests**
110+
111+```bash
112+go test ./internal/core -run TestContextPromptSourcePriority
113+go test ./internal/core -run TestLoopContextSlice
114+```
115+Expected: PASS.
116+
117+**Step 4: Commit**
118+
119+```bash
120+git add internal/core/mysis.go
121+git commit -m "fix(core): compose context from prompt source and last tool loop"
122+```
123+
124+---
125+
126+### Task 4: Update docs for new loop model
127+
128+**Files:**
129+- Modify: `documentation/architecture/CONTEXT_COMPRESSION.md`
130+
131+**Step 1: Update description**
132+
133+Document the new “loop slice” approach and prompt source priority:
134+- commander direct → last commander broadcast → last swarm broadcast → nudge (up to 3) → idle
135+
136+**Step 2: Commit**
137+
138+```bash
139+git add documentation/architecture/CONTEXT_COMPRESSION.md
140+git commit -m "docs: document loop slice context composition"
141+```
142+
143+---
144+
145+### Task 5: Run core tests
146+
147+Run:
148+```bash
149+go test ./internal/core
150+```
151+
152+---
153+
154+## Notes
155+
156+- Synthetic nudges are injected into the context for a single turn; they are not stored.
157+- Tool calls and tool results are preserved *only for the most recent loop*.
158+- If no prompt source is available after 3 nudges, transition to `idle` (already expected behavior).
documentation/plans/2026-02-07-loop-context-parallel-workflow.md+395−0
@@ -0,0 +1,395 @@
1+# Parallel Workflow: Loop Context Composition Implementation
2+
3+**Plan Reference:** [2026-02-07-loop-context-composition.md](2026-02-07-loop-context-composition.md)
4+
5+**Objective:** Execute the loop context composition plan using parallel agent work with review checkpoints after each phase.
6+
7+---
8+
9+## Workflow Structure
10+
11+Each phase follows this pattern:
12+1. **Parallel Work** - Multiple agents work independently on isolated tasks
13+2. **Review Checkpoint** - Review agents verify correctness before proceeding
14+3. **Integration** - Merge verified work
15+4. **Gate Decision** - Proceed to next phase only if review passes
16+
17+---
18+
19+## Phase 1: Test Infrastructure (Parallel)
20+
21+**Agents:** 3 implementation agents + 2 review agents
22+
23+### Implementation Agents (Parallel)
24+
25+**Agent 1: Prompt Source Priority Tests**
26+- File: `internal/core/mysis_test.go`
27+- Task: Write `TestContextPromptSourcePriority` with all priority cases
28+- Deliverable: Failing test covering commander direct → commander broadcast → swarm broadcast → nudge priority
29+
30+**Agent 2: Loop Slice Tests**
31+- File: `internal/core/orphaned_tool_results_test.go`
32+- Task: Write `TestLoopContextSlice` for most-recent-loop extraction
33+- Deliverable: Failing test verifying only latest tool-call + results are included
34+
35+**Agent 3: Tool Pairing Tests**
36+- File: `internal/core/agent3_reproduction_test.go`
37+- Task: Write tests ensuring tool results only appear with matching tool calls
38+- Deliverable: Failing test detecting orphaned tool results
39+
40+### Review Checkpoint 1
41+
42+**Review Agent A: Test Coverage Review**
43+- Verify all priority edge cases covered:
44+ - Commander direct present
45+ - Commander direct missing, broadcast present
46+ - Commander broadcasts missing, swarm broadcast present
47+ - No broadcasts, nudge generation
48+- Verify test isolation (no shared state)
49+- Check test names follow convention
50+
51+**Review Agent B: Test Quality Review**
52+- Verify tests use table-driven pattern where appropriate
53+- Check assertions are specific and actionable
54+- Verify setup/teardown is correct
55+- Ensure tests fail for the right reasons
56+
57+### Integration Step
58+```bash
59+# Verify all tests fail as expected
60+go test ./internal/core -run "TestContextPromptSourcePriority|TestLoopContextSlice" -v
61+
62+# Commit all test files together
63+git add internal/core/*_test.go
64+git commit -m "test(core): add loop context composition tests
65+
66+- prompt source priority (commander → broadcast → swarm → nudge)
67+- loop slice extraction (most recent tool-call + results only)
68+- tool result pairing (no orphaned results)"
69+```
70+
71+**Gate:** Proceed only if:
72+- All tests compile
73+- All tests fail
74+- Review agents approve test quality
75+
76+---
77+
78+## Phase 2: Helper Implementation (Parallel)
79+
80+**Agents:** 2 implementation agents + 2 review agents
81+
82+### Implementation Agents (Parallel)
83+
84+**Agent 4: Prompt Source Selection**
85+- File: `internal/core/mysis.go`
86+- Task: Implement `selectPromptSource(memories []*store.Memory) *store.Memory`
87+- Logic:
88+ ```
89+ 1. Find most recent commander direct (source="direct")
90+ 2. If none, find last commander broadcast (source="broadcast", sender_id=commander)
91+ 3. If none, find last swarm broadcast (source="broadcast", sender_id!=commander)
92+ 4. If none, return nil (caller generates nudge)
93+ ```
94+- Include unit test helper verification
95+
96+**Agent 5: Loop Extraction**
97+- File: `internal/core/mysis.go`
98+- Task: Implement `extractLatestToolLoop(memories []*store.Memory) []*store.Memory`
99+- Logic:
100+ ```
101+ 1. Reverse scan for most recent tool-call (role="assistant", has tool_calls)
102+ 2. Collect that tool-call message
103+ 3. Collect all subsequent tool results (role="tool") until non-tool message
104+ 4. Return [tool-call, result1, result2, ...]
105+ ```
106+- Include unit test helper verification
107+
108+### Review Checkpoint 2
109+
110+**Review Agent C: Implementation Correctness**
111+- Verify `selectPromptSource` checks in correct priority order
112+- Verify `extractLatestToolLoop` handles edge cases:
113+ - No tool calls in history
114+ - Tool call at end with no results yet
115+ - Multiple tool results for single call
116+- Check error handling (nil checks, empty slices)
117+- Verify no mutations to input slices
118+
119+**Review Agent D: Performance & Safety**
120+- Check for efficient memory handling (no unnecessary copies)
121+- Verify slice bounds checking
122+- Check for potential nil pointer dereferences
123+- Verify helper tests pass
124+
125+### Integration Step
126+```bash
127+# Run helper-specific tests
128+go test ./internal/core -run "Helper" -v
129+
130+# Commit helpers
131+git add internal/core/mysis.go
132+git commit -m "feat(core): add context composition helpers
133+
134+- selectPromptSource: priority-based prompt selection
135+- extractLatestToolLoop: most recent tool-call + results extraction"
136+```
137+
138+**Gate:** Proceed only if:
139+- Helper unit tests pass
140+- Review agents approve implementation
141+- No regressions in existing tests
142+
143+---
144+
145+## Phase 3: Context Composition Integration (Serial)
146+
147+**Agents:** 1 implementation agent + 2 review agents
148+
149+### Implementation Agent (Single)
150+
151+**Agent 6: Compose getContextMemories**
152+- File: `internal/core/mysis.go`
153+- Task: Rewrite `getContextMemories` using new helpers
154+- Steps:
155+ 1. Filter for system prompt (source="system")
156+ 2. Call `selectPromptSource` for prompt memory
157+ 3. Generate synthetic nudge if prompt is nil (up to 3 attempts)
158+ 4. Call `extractLatestToolLoop` for tool messages
159+ 5. Compose: [system, prompt, ...toolLoop]
160+- Remove old compaction/orphan logic
161+
162+### Review Checkpoint 3
163+
164+**Review Agent E: Integration Review**
165+- Verify all Task 1 & 2 tests now pass
166+- Check context size is bounded and predictable
167+- Verify no orphaned tool results possible
168+- Test synthetic nudge generation (counter increment)
169+- Verify idle transition after 3 nudges
170+
171+**Review Agent F: Regression Review**
172+- Run full `internal/core` test suite
173+- Check no existing tests broken
174+- Verify existing mysis state machine tests still pass
175+- Check goroutine cleanup tests unaffected
176+
177+### Integration Step
178+```bash
179+# Run all context tests
180+go test ./internal/core -run "TestContext|TestLoopContext|TestOrphaned" -v
181+
182+# Run full core suite
183+go test ./internal/core -v
184+
185+# Commit integration
186+git add internal/core/mysis.go
187+git commit -m "fix(core): compose context from prompt source and last tool loop
188+
189+Replaces compaction approach with deterministic loop slice:
190+- System prompt
191+- Chosen prompt source (commander → broadcast → swarm → nudge)
192+- Most recent tool-call + all its tool results
193+
194+This eliminates orphaned tool results and provides stable, bounded context."
195+```
196+
197+**Gate:** Proceed only if:
198+- All new tests pass
199+- No test regressions
200+- Both review agents approve
201+
202+---
203+
204+## Phase 4: Documentation & Validation (Parallel)
205+
206+**Agents:** 2 implementation agents + 1 review agent
207+
208+### Implementation Agents (Parallel)
209+
210+**Agent 7: Architecture Documentation**
211+- File: `documentation/architecture/CONTEXT_COMPRESSION.md`
212+- Task: Update to describe loop slice model
213+- Include:
214+ - Prompt source priority diagram
215+ - Loop extraction algorithm
216+ - Context composition order
217+ - Bounded size guarantees
218+
219+**Agent 8: Code Comment Documentation**
220+- Files: `internal/core/mysis.go`, `internal/core/mysis_test.go`
221+- Task: Add comprehensive comments to new functions
222+- Include:
223+ - Purpose and rationale
224+ - Parameter descriptions
225+ - Return value semantics
226+ - Edge case behavior
227+
228+### Review Checkpoint 4
229+
230+**Review Agent G: Documentation Review**
231+- Verify architecture doc matches implementation
232+- Check code comments are accurate
233+- Verify examples are correct
234+- Ensure KNOWN_ISSUES.md updated if relevant
235+- Check README.md still accurate
236+
237+### Integration Step
238+```bash
239+# Verify documentation accuracy
240+git add documentation/architecture/CONTEXT_COMPRESSION.md
241+git add internal/core/mysis.go internal/core/mysis_test.go
242+git commit -m "docs: document loop slice context composition
243+
244+- Prompt source priority (commander → broadcast → swarm → nudge)
245+- Tool loop extraction (most recent only)
246+- Bounded context guarantees"
247+```
248+
249+**Gate:** Proceed only if:
250+- Documentation review passes
251+- All links work
252+- No contradictions with code
253+
254+---
255+
256+## Phase 5: Full Validation (Parallel)
257+
258+**Agents:** 3 validation agents
259+
260+### Validation Agents (Parallel)
261+
262+**Agent 9: Unit Test Validation**
263+```bash
264+go test ./internal/core -v -race -count=5
265+```
266+- Verify no flaky tests
267+- Check race detector clean
268+- Confirm 5 consecutive passes
269+
270+**Agent 10: Integration Test Validation**
271+```bash
272+make test
273+```
274+- Full test suite passes
275+- No unexpected failures
276+- Coverage maintained or improved
277+
278+**Agent 11: Build Validation**
279+```bash
280+make clean
281+make build
282+./bin/zoea --offline
283+```
284+- Clean build succeeds
285+- Binary runs without crashes
286+- Offline mode works (smoke test)
287+
288+### Final Review Checkpoint
289+
290+**Review Agent H: Release Readiness**
291+- All tests pass (unit + integration)
292+- No race conditions detected
293+- Documentation complete and accurate
294+- KNOWN_ISSUES.md updated if needed
295+- Commits follow conventional format
296+- Plan tasks all completed
297+
298+---
299+
300+## Success Criteria
301+
302+- [ ] All 5 plan tasks completed
303+- [ ] All new tests pass (100% success rate)
304+- [ ] No test regressions
305+- [ ] No race conditions detected
306+- [ ] Documentation updated and reviewed
307+- [ ] 8 review checkpoints passed
308+- [ ] Clean build on main branch
309+- [ ] Offline smoke test passes
310+
311+---
312+
313+## Agent Allocation Summary
314+
315+**Implementation Agents:** 8
316+- 3 test writers (parallel)
317+- 2 helper implementers (parallel)
318+- 1 integration implementer (serial)
319+- 2 documentation writers (parallel)
320+
321+**Review Agents:** 8
322+- 2 test quality reviewers
323+- 2 implementation correctness reviewers
324+- 2 integration reviewers
325+- 1 documentation reviewer
326+- 1 release readiness reviewer
327+
328+**Validation Agents:** 3
329+- 1 unit test validator
330+- 1 integration validator
331+- 1 build validator
332+
333+**Total:** 19 agent roles, maximum 6 agents working in parallel at peak (Phase 1)
334+
335+---
336+
337+## Execution Timeline
338+
339+Assuming each phase takes T time units:
340+
341+- **Phase 1:** T (3 agents parallel) + Review
342+- **Phase 2:** T (2 agents parallel) + Review
343+- **Phase 3:** 2T (1 agent serial, more complex) + Review
344+- **Phase 4:** T (2 agents parallel) + Review
345+- **Phase 5:** T (3 agents parallel) + Review
346+
347+**Total:** 6T + 5 review checkpoints
348+
349+**Sequential equivalent:** 8T (all agents serial)
350+
351+**Speedup:** 25% faster with parallel work + continuous quality gates
352+
353+---
354+
355+## Risk Mitigation
356+
357+**Risk:** Helper functions have bugs that propagate to integration
358+**Mitigation:** Phase 2 includes dedicated helper unit tests before integration
359+
Cut short: this commit's diff is over 1000 lines.
documentation/plans/2026-02-07-loop-context-workflow-diagram.md+349−0
Cut short: this commit's diff is over 1000 lines.
documentation/reports/LOOP_CONTEXT_COMPOSITION_IMPLEMENTATION_2026-02-07.md+340−0
Cut short: this commit's diff is over 1000 lines.