@@ -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.