self-evolving-workflow 0.0.0-stage → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/LICENSE +27 -0
  2. package/README.md +90 -2
  3. package/dist/agent-memory-prompts.d.ts +13 -0
  4. package/dist/agent-memory-prompts.js +55 -0
  5. package/dist/cli.d.ts +2 -0
  6. package/dist/cli.js +6 -0
  7. package/dist/closeout.d.ts +105 -0
  8. package/dist/closeout.js +479 -0
  9. package/dist/code.d.ts +39 -0
  10. package/dist/code.js +124 -0
  11. package/dist/common.d.ts +9 -0
  12. package/dist/common.js +42 -0
  13. package/dist/context-envelope.d.ts +59 -0
  14. package/dist/context-envelope.js +23 -0
  15. package/dist/host-adapters.d.ts +34 -0
  16. package/dist/host-adapters.js +151 -0
  17. package/dist/http.d.ts +3 -0
  18. package/dist/http.js +90 -0
  19. package/dist/index.d.ts +16 -0
  20. package/dist/index.js +13 -0
  21. package/dist/knowledge-cli.d.ts +183 -0
  22. package/dist/knowledge-cli.js +654 -0
  23. package/dist/knowledge-reads.d.ts +71 -0
  24. package/dist/knowledge-reads.js +193 -0
  25. package/dist/memory.d.ts +97 -0
  26. package/dist/memory.js +250 -0
  27. package/dist/retrospective.d.ts +57 -0
  28. package/dist/retrospective.js +248 -0
  29. package/dist/search.d.ts +36 -0
  30. package/dist/search.js +112 -0
  31. package/dist/skill-addition.d.ts +25 -0
  32. package/dist/skill-addition.js +89 -0
  33. package/dist/skill-design.d.ts +96 -0
  34. package/dist/skill-design.js +226 -0
  35. package/dist/skill-replay.d.ts +55 -0
  36. package/dist/skill-replay.js +451 -0
  37. package/dist/skill-route.d.ts +30 -0
  38. package/dist/skill-route.js +75 -0
  39. package/dist/transcript-evidence.d.ts +3 -0
  40. package/dist/transcript-evidence.js +58 -0
  41. package/dist/upstream/chunker.d.ts +24 -0
  42. package/dist/upstream/chunker.js +96 -0
  43. package/dist/upstream/file-protocol.d.ts +45 -0
  44. package/dist/upstream/file-protocol.js +117 -0
  45. package/dist/upstream/frontmatter.d.ts +47 -0
  46. package/dist/upstream/frontmatter.js +86 -0
  47. package/dist/upstream/graph-search.d.ts +33 -0
  48. package/dist/upstream/graph-search.js +67 -0
  49. package/dist/upstream/l1-extraction.d.ts +26 -0
  50. package/dist/upstream/l1-extraction.js +405 -0
  51. package/dist/upstream/llm.d.ts +8 -0
  52. package/dist/upstream/llm.js +1 -0
  53. package/dist/upstream/merge.d.ts +50 -0
  54. package/dist/upstream/merge.js +153 -0
  55. package/dist/upstream/prompts.d.ts +53 -0
  56. package/dist/upstream/prompts.js +185 -0
  57. package/dist/upstream/search-utils.d.ts +34 -0
  58. package/dist/upstream/search-utils.js +55 -0
  59. package/dist/upstream/slug.d.ts +26 -0
  60. package/dist/upstream/slug.js +103 -0
  61. package/dist/upstream/template.d.ts +29 -0
  62. package/dist/upstream/template.js +80 -0
  63. package/dist/upstream/tokenize.d.ts +4 -0
  64. package/dist/upstream/tokenize.js +29 -0
  65. package/dist/wiki-change.d.ts +76 -0
  66. package/dist/wiki-change.js +299 -0
  67. package/dist/wiki-entry.d.ts +26 -0
  68. package/dist/wiki-entry.js +93 -0
  69. package/dist/wiki-ingest.d.ts +12 -0
  70. package/dist/wiki-ingest.js +126 -0
  71. package/dist/wiki-migration.d.ts +16 -0
  72. package/dist/wiki-migration.js +268 -0
  73. package/dist/wiki-tokens.d.ts +1 -0
  74. package/dist/wiki-tokens.js +46 -0
  75. package/dist/wiki.d.ts +103 -0
  76. package/dist/wiki.js +330 -0
  77. package/dist/workflow-cli.d.ts +2 -0
  78. package/dist/workflow-cli.js +258 -0
  79. package/dist/workflow-install.d.ts +36 -0
  80. package/dist/workflow-install.js +148 -0
  81. package/dist/workflow-knowledge.d.ts +16 -0
  82. package/dist/workflow-knowledge.js +24 -0
  83. package/dist/workflow-mcp.d.ts +2 -0
  84. package/dist/workflow-mcp.js +144 -0
  85. package/dist/workflow-names.d.ts +4 -0
  86. package/dist/workflow-names.js +18 -0
  87. package/dist/workflow-runtime.d.ts +622 -0
  88. package/dist/workflow-runtime.js +627 -0
  89. package/dist/workflow-skills.d.ts +48 -0
  90. package/dist/workflow-skills.js +141 -0
  91. package/package.json +76 -4
  92. package/skills/ew-odyssey/SKILL.md +237 -0
  93. package/skills/ew-odyssey/references/audit-artifacts.md +7 -0
  94. package/skills/ew-odyssey/references/odyssey-base-codex.md +3 -0
  95. package/skills/ew-odyssey/references/odyssey-base.md +278 -0
  96. package/skills/ew-odyssey/references/odyssey-debug.codex.md +305 -0
  97. package/skills/ew-odyssey/references/odyssey-debug.md +283 -0
  98. package/skills/ew-odyssey/references/odyssey-defensive.codex.md +395 -0
  99. package/skills/ew-odyssey/references/odyssey-defensive.md +369 -0
  100. package/skills/ew-odyssey/references/odyssey-improve.codex.md +270 -0
  101. package/skills/ew-odyssey/references/odyssey-improve.md +248 -0
  102. package/skills/ew-odyssey/references/odyssey-planex.codex.md +352 -0
  103. package/skills/ew-odyssey/references/odyssey-planex.md +312 -0
  104. package/skills/ew-odyssey/references/odyssey-review.codex.md +283 -0
  105. package/skills/ew-odyssey/references/odyssey-review.md +251 -0
  106. package/skills/ew-odyssey/references/odyssey-security.md +249 -0
  107. package/skills/ew-odyssey/references/odyssey-ui.codex.md +294 -0
  108. package/skills/ew-odyssey/references/odyssey-ui.md +250 -0
  109. package/skills/ew-odyssey/references/prepare/odyssey-debug.md +105 -0
  110. package/skills/ew-odyssey/references/prepare/odyssey-defensive.md +121 -0
  111. package/skills/ew-odyssey/references/prepare/odyssey-improve.md +93 -0
  112. package/skills/ew-odyssey/references/prepare/odyssey-planex.md +104 -0
  113. package/skills/ew-odyssey/references/prepare/odyssey-review.md +98 -0
  114. package/skills/ew-odyssey/references/prepare/odyssey-security.md +94 -0
  115. package/skills/ew-odyssey/references/prepare/odyssey-ui.md +87 -0
  116. package/skills/ew-orchestrate/SKILL.md +236 -0
  117. package/skills/ew-orchestrate/references/auto-policy.md +165 -0
  118. package/skills/ew-orchestrate/references/companion-route.md +52 -0
  119. package/skills/ew-orchestrate/references/ew-orchestrate.md +27 -0
  120. package/skills/ew-orchestrate/references/goal.md +53 -0
  121. package/skills/ew-orchestrate/references/knowledge-route.md +163 -0
  122. package/skills/ew-orchestrate/references/orchestrator-run-loop.md +36 -0
  123. package/skills/ew-orchestrate/references/planning.md +137 -0
  124. package/skills/ew-orchestrate/steps/ew-analyze/SKILL.md +62 -0
  125. package/skills/ew-orchestrate/steps/ew-analyze/references/boundary-grill.md +50 -0
  126. package/skills/ew-orchestrate/steps/ew-analyze/references/issue-gaps-analyze.md +59 -0
  127. package/skills/ew-orchestrate/steps/ew-analyze/references/prepare.md +42 -0
  128. package/skills/ew-orchestrate/steps/ew-analyze/references/workflow.md +401 -0
  129. package/skills/ew-orchestrate/steps/ew-brainstorm/SKILL.md +32 -0
  130. package/skills/ew-orchestrate/steps/ew-companion/SKILL.md +9 -0
  131. package/skills/ew-orchestrate/steps/ew-execute/SKILL.md +71 -0
  132. package/skills/ew-orchestrate/steps/ew-execute/references/prepare.md +69 -0
  133. package/skills/ew-orchestrate/steps/ew-execute/references/workflow.md +373 -0
  134. package/skills/ew-orchestrate/steps/ew-plan/SKILL.md +102 -0
  135. package/skills/ew-orchestrate/steps/ew-plan/references/boundary-grill.md +50 -0
  136. package/skills/ew-orchestrate/steps/ew-plan/references/prepare.md +51 -0
  137. package/skills/ew-orchestrate/steps/ew-plan/references/tdd.md +53 -0
  138. package/skills/ew-orchestrate/steps/ew-plan/references/workflow.md +278 -0
  139. package/skills/ew-orchestrate/steps/ew-review/SKILL.md +44 -0
  140. package/skills/ew-orchestrate/steps/ew-review/references/odyssey-base-codex.md +3 -0
  141. package/skills/ew-orchestrate/steps/ew-review/references/prepare.md +76 -0
  142. package/skills/ew-orchestrate/steps/ew-review/references/workflow.md +283 -0
  143. package/skills/ew-skill-design/SKILL.md +28 -0
  144. package/skills/ew-skill-design/references/package-contract.md +28 -0
  145. package/skills/ew-skill-design/references/validation.md +7 -0
  146. package/skills/team-swarm/SKILL.md +231 -0
  147. package/skills/team-swarm/references/mcp-coordination.md +10 -0
  148. package/skills/team-swarm/roles/analyst/role.md +181 -0
  149. package/skills/team-swarm/roles/ant/role.md +149 -0
  150. package/skills/team-swarm/roles/coordinator/commands/converge.md +154 -0
  151. package/skills/team-swarm/roles/coordinator/commands/init-swarm.md +134 -0
  152. package/skills/team-swarm/roles/coordinator/commands/iterate.md +202 -0
  153. package/skills/team-swarm/roles/coordinator/role.md +228 -0
  154. package/skills/team-swarm/roles/scorer/role.md +150 -0
  155. package/skills/team-swarm/scripts/aco.py +646 -0
  156. package/skills/team-swarm/scripts/pheromone.py +144 -0
  157. package/skills/team-swarm/scripts/scoring.py +111 -0
  158. package/skills/team-swarm/scripts/test_aco.py +606 -0
  159. package/skills/team-swarm/specs/ant-output-schema.md +127 -0
  160. package/skills/team-swarm/specs/convergence-criteria.md +108 -0
  161. package/skills/team-swarm/specs/pheromone-schema.md +125 -0
  162. package/skills/team-swarm/specs/swarm-config-template.json +71 -0
  163. package/skills/team-swarm/specs/swarm-protocol.md +123 -0
  164. package/skills/workflow-closeout/SKILL.md +10 -0
  165. package/skills/workflow-evolve/SKILL.md +79 -0
  166. package/skills/workflow-evolve/references/agy-gate.md +27 -0
  167. package/skills/workflow-evolve/references/auto-loop.md +20 -0
  168. package/skills/workflow-evolve/references/history-review.md +14 -0
  169. package/skills/workflow-evolve/scripts/codex-memory-replay.mjs +76 -0
  170. package/skills/workflow-evolve/scripts/codex-replay.mjs +1 -0
  171. package/skills/workflow-evolve/scripts/evolve-loop.mjs +259 -0
  172. package/skills/workflow-evolve/scripts/memory-codex-mcp.mjs +124 -0
  173. package/workflows/index.json +23 -0
@@ -0,0 +1,283 @@
1
+ ---
2
+ name: ew-odyssey-debug
3
+ prepare: odyssey-debug
4
+ session-mode: inherited
5
+ ---
6
+
7
+ # Workflow: Odyssey Debug
8
+
9
+ ## State Chain
10
+
11
+ ```
12
+ S_INTAKE → S_ARCHAEOLOGY → S_EXPLORE → S_DIAGNOSE → S_FIX → S_CONFIRM → [back-half]
13
+ ```
14
+
15
+ Back-half: `S_GENERALIZE → S_DISCOVER → S_RECORD → END` (see [shared phases](odyssey-base.md)).
16
+
17
+ ---
18
+
19
+ ## Boundary
20
+
21
+ **In scope:** Single bug/issue full loop — symptom → root cause → fix → confirm → generalize.
22
+ **Out of scope:** Features → `--mode planex` | Quality review → `--mode review` | UI → `--mode ui` | Architecture → `/ew-orchestrate --goal plan`
23
+
24
+ ---
25
+
26
+ ## `--template <name>`
27
+
28
+ Template strategies are defined in [the selected mode preparation](prepare/odyssey-debug.md) §Input Interpretation — that is the canonical wording.
29
+
30
+ ---
31
+
32
+ ## Target Resolution
33
+
34
+ Issue description parsed from `<intent>`.
35
+
36
+ ---
37
+
38
+ ## Session Fields
39
+
40
+ ```json
41
+ { "issue": "", "diagnosis_retries": 0, "root_cause": null, "confirmation": null,
42
+ "patterns": [], "generalization_stats": null }
43
+ ```
44
+
45
+ ---
46
+
47
+ ## evidence.ndjson Phases
48
+
49
+ `archaeology|explore|diagnosis|discovery|decision|self-iteration`
50
+
51
+ - `archaeology`: `sha`, `author`, `date`, `message`, `relevance`
52
+ - `explore`: `category` (call_chain|recent_change|error_gap|similar_pattern), `detail`
53
+ - `diagnosis`: `hypothesis`, `result` (confirmed|disproved|inconclusive)
54
+ - `discovery`: `file`, `line`, `classification` (safe|risk|bug), `action` (fix|issue|decision|skip)
55
+ - `decision`: `question`, `options`, `context`, `status` (pending|resolved|deferred), `resolution`
56
+ - `self-iteration`: `stage`, `round`, `assessment`, `expansion`
57
+
58
+ ---
59
+
60
+ ## explore.json
61
+
62
+ ```json
63
+ {"call_chains": [], "recent_changes": [], "error_gaps": [], "similar_patterns": [], "cli_tool": "", "timestamp": ""}
64
+ ```
65
+
66
+ ---
67
+
68
+ ## phase_goals[]
69
+
70
+ | ID | Goal | done_when | phase | skip_when |
71
+ |----|------|-----------|-------|-----------|
72
+ | G1 | Root cause identified | phase=diagnosis result=confirmed | S_DIAGNOSE | — |
73
+ | G2 | Explore context gathered | explore.json ≥1 category | S_EXPLORE | — |
74
+ | G3 | Fix applied and confirmed | confirmation.overall == confirmed | S_CONFIRM | skip_fix |
75
+ | G4 | Pattern generalized | patterns[] ≥1 entry | S_GENERALIZE | skip_generalize |
76
+ | G5 | Discoveries triaged | all scan hits classified | S_DISCOVER | skip_generalize |
77
+ | G6 | Learnings persisted | spec entries created OR none actionable | S_RECORD | — |
78
+
79
+ ---
80
+
81
+ ## understanding.md — 9 Sections
82
+
83
+ 1. Issue & Scope
84
+ 2. Archaeology
85
+ 3. Exploration
86
+ 4. Hypotheses
87
+ 5. Root Cause
88
+ 6. Fix & Confirmation
89
+ 7. Generalization
90
+ 8. Discoveries
91
+ 9. Learnings
92
+
93
+ ---
94
+
95
+ ## State Machine — Transitions
96
+
97
+ ```
98
+ S_ARCHAEOLOGY → S_EXPLORE : complete
99
+ S_EXPLORE → S_DIAGNOSE : complete
100
+ S_DIAGNOSE → S_FIX : confirmed, !skip_fix
101
+ S_DIAGNOSE → S_GENERALIZE : confirmed, skip_fix, !skip_generalize
102
+ S_DIAGNOSE → S_RECORD : confirmed, skip_fix, skip_generalize
103
+ S_DIAGNOSE → S_DIAGNOSE : all hypotheses failed, retries < 3 → A_ESCALATE_DIAGNOSIS
104
+ S_DIAGNOSE → S_RECORD : retries >= 3 → INCONCLUSIVE
105
+ S_FIX → S_CONFIRM : fix implemented
106
+ S_CONFIRM → S_GENERALIZE : confirmed, !skip_generalize
107
+ S_CONFIRM → S_RECORD : confirmed, skip_generalize
108
+ S_CONFIRM → S_FIX : needs_rework
109
+ ```
110
+
111
+ ---
112
+
113
+ ## Actions
114
+
115
+ ### A_ARCHAEOLOGY
116
+
117
+ 2 parallel Agents:
118
+ - **Timeline**: `git log --oneline -20 -- {files}`
119
+ - **Blame**: top 3 files `git blame -L {region}`
120
+
121
+ Evidence phase=archaeology.
122
+
123
+ `evolve delegate --role analyze --mode analysis` (`run_in_background: true`):
124
+ - PURPOSE: review recent modifications related to {issue}
125
+ - EXPECTED: JSON `[{commit_sha, risk_level, analysis, could_cause_issue, explanation}]`
126
+
127
+ Update §2 (Archaeology).
128
+
129
+ If an archaeology agent fails, log W003 and proceed with available results.
130
+
131
+ ### A_EXPLORE
132
+
133
+ Skip if no CLI tools (W006).
134
+
135
+ `evolve delegate --role explore --mode analysis` (`run_in_background: true`):
136
+ - PURPOSE: call chains, recent changes, error gaps, similar patterns
137
+ - EXPECTED: JSON `{call_chains, recent_changes, error_gaps, similar_patterns}`
138
+
139
+ Write `explore.json` + evidence phase=explore. Update §3 (Exploration). Mark G2.
140
+
141
+ **GATE: discovery-complete** — archaeology/explore evidence logged, understanding.md §2-§3 updated, G2 marked (W003 partial / W006 skip acceptable).
142
+
143
+ ### A_DIAGNOSE
144
+
145
+ 1. Generate hypotheses from evidence, ranked [HIGH]/[MEDIUM]/[LOW] → §4.
146
+ 2. Test each hypothesis → evidence phase=diagnosis.
147
+ 3. Ambiguity → evidence phase=decision:
148
+ - Normal: request_user_input
149
+ - `-y`: defer
150
+ 4. Confirmed → `session.json.root_cause` + §5 (Root Cause). Mark G1.
151
+
152
+ **GATE: diagnosis-confirmed** — all hypotheses tested with evidence, root cause confirmed with reproduction or code/log evidence (or INCONCLUSIVE after 3-strike), understanding.md §4-§5 written. Zero hypotheses tested is BLOCKED.
153
+
154
+ ### A_ESCALATE_DIAGNOSIS
155
+
156
+ `diagnosis_retries++`.
157
+
158
+ - **retries < 3**: `evolve delegate --role analyze`, generate new hypotheses, → S_DIAGNOSE.
159
+ - **retries >= 3**:
160
+ - Normal: request_user_input
161
+ - `-y`: INCONCLUSIVE → S_RECORD
162
+
163
+ ### A_FIX
164
+
165
+ 1. Present root cause + proposed fix.
166
+ - Normal: request_user_input
167
+ - `-y`: auto proceed
168
+ 2. Implement fix, evidence phase=decision.
169
+
170
+ ### A_CONFIRM
171
+
172
+ 1. Run covering tests.
173
+ 2. `evolve delegate --role review --mode analysis` (`run_in_background: true`):
174
+ - EXPECTED: JSON `{verdict, findings [{severity, description, suggestion}], regression_risk}`
175
+ 3. `session.json.confirmation`:
176
+ ```json
177
+ {"test_result": "", "cli_review": {}, "overall": "confirmed|needs_rework"}
178
+ ```
179
+ 4. Update §6 (Fix & Confirmation).
180
+ - `needs_rework` → S_FIX
181
+ - `confirmed` → mark G3
182
+
183
+ **GATE: fix-confirmed** — fix implemented and tests pass, CLI review done, `confirmation.overall` set, understanding.md §6 written, G3 marked. `needs_rework` routes back to FIX; skippable only when `skip_fix == true`.
184
+
185
+ ---
186
+
187
+ ## Generalize Source
188
+
189
+ Confirmed root cause + applied fix.
190
+
191
+ **Thoroughness floor:** ALL 3 layers (syntax/semantic/structural) must be attempted and logged.
192
+
193
+ **Discover routing:** `bug` → back to S_FIX; new bug → S_DIAGNOSE.
194
+
195
+ ---
196
+
197
+ ## Knowledge Persistence (§9)
198
+
199
+ Include verified reusable findings in the Run summary and harvest the completed Session through Agent Memory closeout.
200
+
201
+
202
+ | Category | Content | Follow-up |
203
+ |----------|---------|-----------|
204
+ | Recurring root cause pattern | Type + triggers + fix + detection | `stage spec → debug` |
205
+ | Non-obvious workaround | Problem + steps + why obvious fix fails | `stage spec → learning` |
206
+ | Architecture boundary violation | Violation + correct boundary + verification | `stage spec → arch` |
207
+ | Reusable generalization pattern | Signature + risk + fix template + scope | `stage spec → coding` |
208
+
209
+ ---
210
+
211
+ ## Completion Summary
212
+
213
+ ```
214
+ --- DEBUG ODYSSEY COMPLETE ---
215
+ Issue: {issue}
216
+ Root cause: {root_cause.hypothesis}
217
+ Fix: {applied|skipped|inconclusive}
218
+ Patterns: {patterns_extracted} ({by_layer})
219
+ Scan hits: {total_hits} ({cross_layer_confirmed} confirmed)
220
+ Issues: {N} created
221
+ Decisions: {N} resolved, {M} pending, {K} deferred
222
+ Learnings: {N} persisted
223
+ Self-iter: {N} rounds across {M} stages
224
+ Goals: {done}/{total} ({skipped} skipped)
225
+ ---
226
+ ```
227
+
228
+ ---
229
+
230
+ ## `-y` Decision Points
231
+
232
+ | Decision Point | Normal | `-y` |
233
+ |---------------|--------|------|
234
+ | A_DIAGNOSE ambiguity | request_user_input | deferred |
235
+ | A_ESCALATE 3-strike | request_user_input | INCONCLUSIVE |
236
+ | A_FIX direction | request_user_input | auto proceed |
237
+
238
+ ---
239
+
240
+ ## Mode-Specific Phase Gates
241
+
242
+ - **Discovery gate** (ARCHAEOLOGY/EXPLORE): evidence for the phase logged, understanding.md updated, discovery goal marked. Archaeology partial via W003 acceptable; explore W006 skip acceptable.
243
+ - **Audit gate** (DIAGNOSE): all hypotheses tested or confirmed, findings merged with severity classification. Zero dimensions reviewed is BLOCKED (W002 partial allowed).
244
+ - **FIX gate:** current severity tier fully addressed. Per-fix evidence phase=fix logged. Auto-commit per tier.
245
+ - **CONFIRM gate:** tests pass; `remaining_actionable == 0` and new findings == 0; confirmation written, understanding.md updated, verify goal marked. needs_rework → route back to FIX.
246
+
247
+ ---
248
+
249
+ ## Error Codes (debug-specific)
250
+
251
+ | Code | Severity | Condition | Recovery |
252
+ |------|----------|-----------|----------|
253
+ | E001 | error | No issue, no session | Provide issue or -c |
254
+ | W003 | warning | Archaeology agent or delegate failure | Proceed with available results |
255
+ | W006 | warning | No CLI tools | Skip explore |
256
+
257
+ ---
258
+
259
+ ## Success Criteria (debug-specific)
260
+
261
+ - [ ] Session + 4 output files + prior knowledge searched
262
+ - [ ] Archaeology + CLI review → evidence
263
+ - [ ] CLI exploration → explore.json
264
+ - [ ] Hypotheses tested, root cause with evidence refs
265
+ - [ ] understanding.md 9 sections progressive
266
+ - [ ] Fix + confirmed (unless --skip-fix)
267
+ - [ ] Generalization + scan (unless --skip-generalize)
268
+ - [ ] Discoveries classified; unfixed findings individually justified
269
+ - [ ] phase_goals + goal audit + resumable via -c
270
+ - [ ] Completion summary
271
+
272
+ ---
273
+
274
+ ## Next Step Routing (debug-specific)
275
+
276
+ | Condition | Next |
277
+ |-----------|------|
278
+ | Discovery issues | `Open the follow-up findings in the project issue tracker` |
279
+ | Document pattern | `Review the module and stage the reusable method via Agent Memory closeout` |
280
+ | Formal review | `/ew-odyssey <changed-files> --mode review` |
281
+ | Second opinion | `evolve delegate "<review prompt>" --mode analysis` |
282
+ | Related question | `Use an Evolve analyze step for the question` |
283
+ | Pending decisions | Filter evidence phase=decision status=pending |
@@ -0,0 +1,395 @@
1
+ <!-- session-mode: inherited -->
2
+
3
+ # Workflow: Odyssey Defensive (Codex)
4
+
5
+ Codex-adapted: uses `spawn_agents_on_csv`, `request_user_input`, `update_plan`.
6
+
7
+ Core judgment (§19):
8
+
9
+ > Defensive Code + Failure Suppression + Semantic Transformation + Critical Propagation = Defensive Programming Risk
10
+
11
+ ## State Chain
12
+
13
+ ```
14
+ S_INTAKE → S_ANCHOR → S_SLICE → S_SCAN → S_PROPAGATE → S_REPORT → [back-half]
15
+ ```
16
+
17
+ Back-half: `S_GENERALIZE → S_DISCOVER → S_RECORD → END` (see [shared Codex phases](odyssey-base-codex.md)).
18
+
19
+ **No S_FIX / S_CONFIRM** — this mode is read-only. Findings route to `--mode improve` (fix defensive defect) or `--mode debug` (root-cause).
20
+
21
+ ---
22
+
23
+ ## Boundary
24
+
25
+ **In scope:** Business-anchor identification → local business-flow recovery → backward slicing → 8-pattern defensive-node scan → failure→value transformation identification → forward propagation to business sinks → constraint/default consistency check → exception semantic classification → risk scoring → severity matrix with full propagation chains → generalize defensive patterns.
26
+ **Out of scope:** Fixing defensive defects → `--mode improve` | Root-cause debug → `--mode debug` | Multi-dimensional general review → `--mode review` | Security vulnerability audit → `--mode security` | UI visual optimization → `--mode ui`. Read-only invariant applies: NEVER modify source code.
27
+
28
+ ---
29
+
30
+ ## Target Resolution
31
+
32
+ | Input | Resolution |
33
+ |-------|-----------|
34
+ | File/dir path | Audit those files |
35
+ | `HEAD` / `staged` | `git diff HEAD` / `git diff --staged` — defensive patterns introduced/modified in diff |
36
+ | Phase number | state.json → changed files for that phase |
37
+ | PR number | `git diff main...HEAD` |
38
+
39
+ ---
40
+
41
+ ## Session Fields
42
+
43
+ ```json
44
+ { "target": "", "tier": "standard", "sink_depth": "all",
45
+ "anchors": {"critical_vars": [], "sink_layers": {"level_1": [], "level_2": [], "level_3": []}},
46
+ "scan_result": {"by_pattern": {}, "candidates": []},
47
+ "propagation": {"confirmed_chains": [], "risky_sinks": [], "q4_hidden": 0},
48
+ "audit_result": {"findings": [], "risk_matrix": {}},
49
+ "findings_count": {},
50
+ "generalization_stats": null }
51
+ ```
52
+
53
+ ---
54
+
55
+ ## evidence.ndjson Phases
56
+
57
+ `anchor|slice|scan|propagate|report|discovery|decision|self-iteration`
58
+
59
+ Phase-specific extension fields:
60
+
61
+ - `anchor`: `category` (critical_var|business_sink|data_flow), `var_name`, `importance` (high|medium|low)
62
+ - `slice`: `anchor_var`, `source_chain`, `passes_default` (bool), `passes_except` (bool), `auto_corrected` (bool), `multiple_sources` (bool)
63
+ - `scan`: `pattern` (broad_catch|exception_swallow|default|null_fallback|auto_correct|silent_convert|dup_constraint|dup_default), `file`, `line`, `original_failure_type`, `snippet`
64
+ - `propagate`: `finding_ref`, `state_transform` (Exception→None|Exception→Empty|Exception→Numeric|Missing→Default|Invalid→Corrected|MultiErr→SingleState), `sink_layer` (1|2|3), `sink_name`, `reaches_critical_sink` (bool), `q4_downstream_aware` (bool), `scores` {S, P, B, H}, `risk_level` (Critical|High|Medium|Low), `exception_class` (A|B|C|D)
65
+ - `report`: `finding_ref`, `risk_level`, `remediation`
66
+
67
+ ---
68
+
69
+ ## phase_goals[]
70
+
71
+ | ID | Goal | done_when | phase | skip_when |
72
+ |----|------|-----------|-------|-----------|
73
+ | G1 | Anchors identified | critical_vars ≥1 AND sink_layers.level_1 ≥1 | S_ANCHOR | — |
74
+ | G2 | Slice completed | every critical_var has a source_chain | S_SLICE | — |
75
+ | G3 | Scan completed (all tier patterns) | all tier-required patterns scanned | S_SCAN | — |
76
+ | G4 | Propagation verified | every candidate has reaches_critical_sink + scores + exception_class | S_PROPAGATE | — |
77
+ | G5 | Report produced | risk_matrix with full propagation chains + scores | S_REPORT | — |
78
+ | G6 | Pattern generalized | patterns[] ≥1 | S_GENERALIZE | skip_generalize |
79
+ | G7 | Discoveries triaged | all hits classified | S_DISCOVER | skip_generalize |
80
+ | G8 | Learnings persisted | spec entries or no actionable | S_RECORD | — |
81
+
82
+ `update_plan({ plan: [{ step: "G1: anchor", status: "pending" }, { step: "G2: slice", status: "pending" }, { step: "G3: scan", status: "pending" }, { step: "G4: propagate", status: "pending" }, { step: "G5: report", status: "pending" }, { step: "G6: generalize", status: "pending" }, { step: "G7: discover", status: "pending" }, { step: "G8: record", status: "pending" }] })`(按上方 gate 表初始化 G1-G8 步骤清单)
83
+
84
+ ---
85
+
86
+ ## understanding.md — 9 Sections
87
+
88
+ 1. Target & Scope & Tier
89
+ 2. Business Anchors (critical-variable table + sink layering)
90
+ 3. Local Business Flow (three-layer map: business-semantic ↔ software-component ↔ code-implementation)
91
+ 4. Defensive Nodes (8-pattern scan results, bucketed by pattern)
92
+ 5. Failure→Value Transformations (§7 six transformation types)
93
+ 6. Propagation Chains (forward chains + sink-hit verdicts + Q4 signals)
94
+ 7. Constraint & Default Consistency (§10 cross-module aggregation)
95
+ 8. Risk Matrix & Exception Classification (R=S×P×B×H scores + A/B/C/D + §14 standard report entries)
96
+ 9. Generalization & Discoveries & Learnings
97
+
98
+ Specs: `agent-memory wiki constraints --category coding` (defensive-programming patterns).
99
+
100
+ ---
101
+
102
+ ## State Machine — Transitions
103
+
104
+ ```
105
+ S_ANCHOR → S_SLICE : complete (anchors identified)
106
+ S_SLICE → S_SCAN : complete (source chains traced)
107
+ S_SCAN → S_PROPAGATE : all tier patterns scanned
108
+ S_PROPAGATE → S_REPORT : all candidates scored + sink verdict
109
+ S_REPORT → S_GENERALIZE : report produced, !skip_generalize
110
+ S_REPORT → S_RECORD : report produced, skip_generalize
111
+ ```
112
+
113
+ Discover routes: sibling module with same defensive anti-pattern → S_SCAN (re-scan expanded scope, loops < max_loops); newly discovered critical propagation chain → evidence phase=decision, recommend `--mode improve`.
114
+
115
+ ---
116
+
117
+ ## Actions
118
+
119
+ ### A_INTAKE extra
120
+
121
+ Tier resolution: parse `--tier` (default: standard) and `--sink-depth` (default: all). Record tier + applicable scan patterns + sink-layer focus to `session.json`.
122
+
123
+ ### A_ANCHOR
124
+
125
+ (§3 step — determine business-critical anchors.)
126
+
127
+ Generate `anchors.csv` with one row per candidate critical variable (discovered via architecture doc + entry-point scan):
128
+
129
+ ```csv
130
+ id,variable,meaning,source,usage_location,importance,sink_layer,target,deps,status,findings_json,error
131
+ "1","objective","优化目标","仿真结果","optimizer","high","1","{target}","","","",""
132
+ "2","mass","质量","仿真结果","objective/constraint","high","1","{target}","","","",""
133
+ "3","log_path","日志路径","配置","logging","low","3","{target}","","","",""
134
+ ```
135
+
136
+ ```javascript
137
+ spawn_agents_on_csv({
138
+ csv_path: `${sessionFolder}/anchors.csv`,
139
+ id_column: "id",
140
+ instruction: "You are identifying business-critical anchors for a defensive-programming audit. Read 'variable', 'meaning', 'source', 'usage_location' columns. Classify 'importance' (high|medium|low) by whether an error in this variable would change the final decision. Assign 'sink_layer' (1=business decision/objective/constraint/control/financial/security; 2=computation result/report/API response/cache; 3=log/UI/temp/debug). Return findings_json as JSON: [{variable, importance, sink_layer, justification}].",
141
+ max_concurrency: 4,
142
+ max_runtime_seconds: 3600,
143
+ output_csv_path: `${sessionFolder}/anchors-results.csv`,
144
+ output_schema: { id, status: ["completed"|"failed"], findings_json, error }
145
+ })
146
+ ```
147
+
148
+ Aggregate results → build critical-variable table + sink layering (§8 three-tier):
149
+ - **Level 1 (high risk):** business decision / control command / objective function / constraint check / model training / optimization algorithm / core DB state / financial amount / security permission.
150
+ - **Level 2 (medium risk):** computation result / report output / intermediate model / API response / cache.
151
+ - **Level 3 (low risk):** log / UI display / temp file / debug info.
152
+
153
+ Write `anchors.json` (critical_vars + sink_layers) + evidence phase=anchor. Update §2. Mark G1. `update_plan`(G1 → completed)
154
+
155
+ **GATE: anchor-identified** — critical_vars ≥1 AND sink_layers.level_1 ≥1. Evidence phase=anchor logged. §2 updated. BLOCKED if no critical vars / no level-1 sink (E002).
156
+
157
+ Commit: `"odyssey-defensive({slug}): ANCHOR — {N} anchors, {M} level-1 sinks"`
158
+
159
+ ### A_SLICE
160
+
161
+ (§4-§5 — recover local business flow + backward slice from critical results.)
162
+
163
+ `evolve delegate --role analyze --mode analysis` (`run_in_background: true`):
164
+ - PURPOSE: for each critical_var, recover the three-layer business-flow map (business-semantic ↔ software-component ↔ code-implementation) and backward-slice its source, answering the 7 questions (origin / default / type conversion / exception handling / auto-correction / multiple sources / intermediate-state substitution).
165
+ - EXPECTED: JSON `{critical_var, three_layer_map, source_chain: [{step, passes_default, passes_except, auto_corrected, multiple_sources}], answers_to_7_questions}`
166
+
167
+ Write evidence phase=slice (one source_chain per anchor) + §3 three-layer map. Mark G2. `update_plan`(G2 → completed)
168
+
169
+ **GATE: slice-complete** — every critical_var has a source_chain; §3 three-layer map written. Slice failure logged as W (tool unavailable) does NOT BLOCK — SCAN results may back-fill the chain.
170
+
171
+ Commit: `"odyssey-defensive({slug}): SLICE — {N} chains traced"`
172
+
173
+ ### A_SCAN
174
+
175
+ (§6 — scan defensive-code nodes. Full 8-pattern parallel agents; quick tier covers P1-P4 only.)
176
+
177
+ Generate `defensive-patterns.csv` with 8 pattern rows:
178
+
179
+ ```csv
180
+ id,pattern,focus,scan_signals,target,deps,status,findings_json,error
181
+ "1","broad_catch","Broad/bare exception clauses that collapse multiple failure types into one handler","except: ; except Exception:","{target}","","","",""
182
+ "2","exception_swallow","Exception handlers that discard the error and return a normal-looking value (pass/None/{}/0)","except ...: pass ; except ...: return None ; except ...: return {} ; except ...: return 0","{target}","","","",""
183
+ "3","default","Default-value accessors that mask missing data as a valid value",".get(k, v) ; getattr(o, x, d) ; v or default","{target}","","","",""
184
+ "4","null_fallback","None-check early returns that propagate None/empty downstream","if x is None: return None ; if x is None: return {}","{target}","","","",""
185
+ "5","auto_correct","Clamp/min-max auto-correction that converts invalid values into plausible ones","max(x, lo) ; min(x, hi) ; min(max(x, lo), hi)","{target}","","","",""
186
+ "6","silent_convert","Try/except type conversion that falls back to a numeric on failure","try: x = float(x) except: x = 0","{target}","","","",""
187
+ "7","dup_constraint","Cross-module same variable with divergent constraints","grep same var name across modules ; compare < <= >= > thresholds","{target}","","","",""
188
+ "8","dup_default","Cross-module same config with divergent defaults","grep same config key across modules ; compare default values (e.g. temperature=25/20/293.15)","{target}","","","",""
189
+ ```
190
+
191
+ ```javascript
192
+ spawn_agents_on_csv({
193
+ csv_path: `${sessionFolder}/defensive-patterns.csv`,
194
+ id_column: "id",
195
+ instruction: "You are scanning code for a specific defensive-programming pattern. Read 'pattern' and 'scan_signals' columns for your detection target. Read 'target' for the files to scan. Use AST analysis (preferred) or Grep (fallback) with the scan_signals. For P7/P8, aggregate cross-module: grep the same variable/config name across the whole repo and compare constraints/defaults. Return findings_json as a JSON array: [{pattern, file, line, original_failure_type, snippet, surrounding_context}]. For broad_catch/exception_swallow, infer original_failure_type from the try-body. For dup_constraint/dup_default, list every divergent location.",
196
+ max_concurrency: 8,
197
+ max_runtime_seconds: 3600,
198
+ output_csv_path: `${sessionFolder}/defensive-patterns-results.csv`,
199
+ output_schema: { id, status: ["completed"|"failed"], findings_json, error }
200
+ })
201
+ ```
202
+
203
+ For quick tier, run only rows 1-4 (P1-P4).
204
+
205
+ Merge all findings → evidence phase=scan. Write `scan_result.by_pattern` + `scan_result.candidates`. Update §4 (per-pattern buckets) + §7 (consistency). Mark G3. `update_plan`(G3 → completed)
206
+
207
+ **GATE: scan-complete** — all tier-required scan patterns completed with structured findings, merged per-pattern. Evidence phase=scan logged per pattern. Tier-required pattern not attempted is BLOCKED (W001 AST unavailable / W002 cross-module aggregation failure are warnings, not blocks).
208
+
209
+ Commit: `"odyssey-defensive({slug}): SCAN — {tier} tier, {N} candidates across {M} patterns"`
210
+
211
+ ### A_PROPAGATE
212
+
213
+ (§7-§10 — the core phase. Identify failure→value transformations → forward propagation → sink verdict → consistency → exception classification → risk scoring.)
214
+
215
+ Generate `propagation.csv` with one row per scan candidate:
216
+
217
+ ```csv
218
+ id,finding_ref,defensive_node,state_transform_candidates,sink_candidates,sink_layers,target,deps,status,findings_json,error
219
+ "1","P2:simulation_adapter.py:128","except Exception → return {}","Exception→Empty;Exception→Numeric","objective();optimizer()","1","{target}","","","",""
220
+ "2","P3:result_parser.py:45","result.get('mass', 0)","Missing→Default","objective()","1","{target}","","","",""
221
+ ```
222
+
223
+ ```javascript
224
+ spawn_agents_on_csv({
225
+ csv_path: `${sessionFolder}/propagation.csv`,
226
+ id_column: "id",
227
+ instruction: "You are propagating a defensive node forward to determine business impact. Read 'defensive_node', 'state_transform_candidates', 'sink_candidates', 'sink_layers'. For each: (1) identify the failure→value state transformation (Exception→None | Exception→Empty | Exception→Numeric | Missing→Default | Invalid→Corrected | MultiErr→SingleState). (2) forward-propagate: does it reach a Critical Business Sink? (3) answer Q4: can the downstream still know the upstream error occurred? (true/false). (4) classify the swallowed exception: A=business illegal, B=numerical/algorithm, C=system environment, D=program defect. (5) score R=S×P×B×H: S=defensive-code severity, P=propagation range, B=business criticality (level-1 sink=high), H=error-hiding degree (Q4 false=high). (6) assign risk_level: Critical=directly alters critical decision; High=hidden error enters core computation; Medium=limited unreasonable fallback; Low=near-zero critical impact. Only reaches_critical_sink=true may be High+. Return findings_json: [{finding_ref, state_transform, sink_layer, sink_name, reaches_critical_sink, q4_downstream_aware, scores:{S,P,B,H}, risk_level, exception_class}].",
228
+ max_concurrency: 4,
229
+ max_runtime_seconds: 3600,
230
+ output_csv_path: `${sessionFolder}/propagation-results.csv`,
231
+ output_schema: { id, status: ["completed"|"failed"], findings_json, error }
232
+ })
233
+ ```
234
+
235
+ Cross-module constraint/default consistency check (§10): for P7/P8 candidates, verify units / business meaning / duplication / conflict across locations; flag `Constraint Inconsistency` / `Default Inconsistency`.
236
+
237
+ Exception semantic classification reference (§9):
238
+
239
+ | Class | Examples | Recommended |
240
+ |-------|----------|-------------|
241
+ | A — business illegal | design var out-of-bounds, illegal input, infeasible, rule conflict | reject / penalty / retry |
242
+ | B — numerical/algorithm | SolverConvergenceError, NumericalOverflow, SingularMatrix | retry / penalty / fallback solver |
243
+ | C — system environment | LicenseError, FileNotFoundError, PermissionError, OutOfMemory | NEVER silent degrade |
244
+ | D — program defect | TypeError, AttributeError, KeyError, IndexError | expose, do NOT convert to normal |
245
+
246
+ Risk-level mapping (§13): Critical = directly alters a critical business decision; High = hidden error enters core computation; Medium = limited unreasonable fallback/default/duplicate constraint; Low = near-zero critical impact (temp-file cleanup failure, log write failure). Risk-scoring rule: only `reaches_critical_sink == true` may be High+; findings reaching only level-3 sinks default to Low.
247
+
248
+ **Q4 signal** (§18): for every finding reaching a sink, answer "can the downstream still know the upstream error occurred?" — `不能` (cannot) = high-risk signal, MUST be flagged in the report and the completion summary `q4_hidden` count.
249
+
250
+ Write `propagation.confirmed_chains` + `propagation.risky_sinks` + `propagation.q4_hidden` count + evidence phase=propagate. Update §5 / §6 / §7 / §8. Mark G4. `update_plan`(G4 → completed)
251
+
252
+ **GATE: propagation-verified** — every scan candidate has `reaches_critical_sink` verdict + failure→value transformation type + Q4 signal + four-dimensional score (S/P/B/H) + risk level + exception class (A/B/C/D). No-score / no-sink-verdict candidate is BLOCKED (W003 per-item `needs_review` acceptable only when truly undecidable, with a per-item reason).
253
+
254
+ Commit: `"odyssey-defensive({slug}): PROPAGATE — {N} chains, {M} reach critical sink, {K} Q4-hidden"`
255
+
256
+ ### A_REPORT
257
+
258
+ (§12-§14 — risk scoring formalized + standard report format. Local aggregation, no parallel agents.)
259
+
260
+ 1. Produce a finding per candidate using the **§14 standard report format**:
261
+
262
+ ```
263
+ DEF-NNN
264
+ Risk level: Critical | High | Medium | Low
265
+ Defensive location: file:line
266
+ Trigger pattern: broad_catch | exception_swallow | default | ...
267
+ Original failure: SimulationSystemError
268
+ State transform: Exception → {} → mass = 0
269
+ Full propagation: solver.run() → except Exception → return {} → result.get("mass", 0) → objective() → optimizer
270
+ Business impact: simulation error converted to mass=0; optimizer may pick the failed design as optimal.
271
+ Remediation: distinguish DesignInfeasibleError (penalty) vs SimulationSystemError (raise).
272
+ ```
273
+
274
+ 2. Build the **severity matrix** (Critical / High / Medium / Low) with file:line references, full propagation chains, Q4 signals, and remediation for every finding.
275
+ 3. Compute summary statistics: counts per level, per pattern, per exception class, Q4-hidden total.
276
+ 4. Write §8 (risk matrix + exception classification + standard report entries) + `session.json.audit_result` + `session.json.findings_count`. Evidence phase=report. Mark G5. `update_plan`(G5 → completed)
277
+
278
+ **GATE: report-produced** — severity matrix with §14 standard report entries for every finding; summary statistics computed; §8 written; `audit_result` populated; read-only invariant verified (zero source modifications in session).
279
+
280
+ Commit: `"odyssey-defensive({slug}): REPORT — {C}C/{H}H/{M}M/{L}L matrix"`
281
+
282
+ ---
283
+
284
+ ## Generalize Source
285
+
286
+ Critical/High findings that propagate to a level-1 sink + cross-module duplicate defensive patterns (dup_constraint / dup_default) + recurring failure→value transformation signatures.
287
+
288
+ **Discover routing:** sibling module with the same defensive anti-pattern → S_SCAN (re-scan expanded scope); newly discovered critical propagation chain → evidence phase=decision, recommend `--mode improve`; needs root-cause → `--mode debug`.
289
+
290
+ ---
291
+
292
+ ## Knowledge Persistence (§9)
293
+
294
+ Include verified reusable findings in the Run summary and harvest the completed Session through Agent Memory closeout.
295
+
296
+ | Category | Content | Follow-up |
297
+ |----------|---------|-----------|
298
+ | Failure→Value transformation pattern | transformation signature + trigger + detection pattern + fix template | `stage spec → coding` |
299
+ | 异常语义坍缩 (exception semantic collapse) | multi-exception → single-state signature + business consequence + detection | `stage spec → coding` |
300
+ | Constraint/default inconsistency | variable + per-location values + unit/meaning conflict + resolution | `stage spec → arch` |
301
+ | Critical propagation chain | sink + chain + hiding mechanism + remediation strategy | `stage spec → debug` |
302
+
303
+ ---
304
+
305
+ ## Completion Summary
306
+
307
+ ```
308
+ --- DEFENSIVE ODYSSEY COMPLETE ---
309
+ Target: {target}
310
+ Tier: {tier}
311
+ Anchors: {N} critical vars, {M} level-1 sinks
312
+ Patterns: P1:{n1} P2:{n2} P3:{n3} P4:{n4} P5:{n5} P6:{n6} P7:{n7} P8:{n8}
313
+ Candidates: {N} defensive nodes
314
+ Chains: {N} propagated, {M} reach critical sink
315
+ Risk: {C}C / {H}H / {M}M / {L}L
316
+ Q4-hidden: {N} findings where downstream cannot detect upstream error
317
+ Exception: A:{a} B:{b} C:{c} D:{d}
318
+ Patterns: {count} ({by_layer})
319
+ Scan hits: {total} ({cross_layer_confirmed} confirmed)
320
+ Issues: {N} created
321
+ Decisions: {N} resolved, {M} pending, {K} deferred
322
+ Learnings: {N} persisted
323
+ Self-iter: {N} rounds across {M} stages
324
+ Cross-loops: {N}
325
+ Goals: {done}/{total} ({skipped} skipped)
326
+ ---
327
+ ```
328
+
329
+ ---
330
+
331
+ ## `-y` Decision Points
332
+
333
+ | Decision Point | Normal | `-y` |
334
+ |---------------|--------|------|
335
+ | A_ANCHOR critical-variable importance | `request_user_input` | auto-classify by semantic layer |
336
+ | A_SCAN false-positive dismissal | `request_user_input` | auto-dismiss with evidence `deferred` |
337
+ | A_PROPAGATE sink-hit ambiguity | `request_user_input` | auto-mark worst-case High |
338
+ | A_REPORT risk-level downgrade | `request_user_input` | auto with documented rationale |
339
+ | A_DISCOVER routing | `request_user_input` | auto create issue + recommend improve |
340
+ | Ambiguous items | `request_user_input` | all `deferred` |
341
+
342
+ ---
343
+
344
+ ## Mode-Specific Phase Gates
345
+
346
+ - **Anchor gate** (S_ANCHOR): critical_vars ≥1 AND level-1 sink present. Evidence phase=anchor logged. §2 updated. BLOCKED if no critical vars / no level-1 sink.
347
+ - **Scan gate** (S_SCAN): all tier-required patterns completed. Per-pattern evidence logged. Findings merged per-pattern. Tier-required pattern missing is BLOCKED (W001/W002 partial allowed).
348
+ - **Propagation gate** (S_PROPAGATE): every candidate has reaches_critical_sink + four-dimensional score + state transformation + Q4 signal + exception class. No-score candidate = BLOCKED or per-item W003.
349
+ - **Report gate** (S_REPORT): severity matrix with §14 standard report entries + full propagation chains + remediation. §8 written. Read-only invariant verified (zero source modifications).
350
+
351
+ ---
352
+
353
+ ## Error Codes (defensive-specific)
354
+
355
+ | Code | Severity | Condition | Recovery |
356
+ |------|----------|-----------|----------|
357
+ | E001 | error | No target / scope provided | Provide target or -c |
358
+ | E002 | error | No critical vars / no level-1 sink found | Verify target has business-critical output |
359
+ | W001 | warning | AST tool unavailable | Fall back to Grep, note coverage gap |
360
+ | W002 | warning | Cross-module aggregation failed (no symbol table) | Local-only constraint/default check, note limitation |
361
+ | W003 | warning | Candidate undecidable for sink/score | Per-item `needs_review`, do not BLOCK |
362
+ | W004 | warning | Generalization 0 hits after full 3-layer scan | Advance to S_RECORD |
363
+ | W005 | warning | Pending decisions | Filter evidence phase=decision |
364
+
365
+ ---
366
+
367
+ ## Success Criteria (defensive-specific)
368
+
369
+ - [ ] Target resolved; tier + sink-depth determined; session + 4 output files + prior knowledge searched
370
+ - [ ] S_ANCHOR: critical-variable table + sink layering (§2) with ≥1 level-1 sink
371
+ - [ ] S_SLICE: per-critical-var source_chain + three-layer business-flow map (§3)
372
+ - [ ] S_SCAN: all tier-required 8 patterns scanned, bucketed per-pattern (§4/§7)
373
+ - [ ] S_PROPAGATE: every candidate has state transformation + sink verdict + Q4 signal + four-dimensional score + exception class (§5/§6/§8)
374
+ - [ ] S_REPORT: severity matrix + full propagation chains + remediation, in §14 standard report format (§8)
375
+ - [ ] understanding.md 9 sections written progressively (§1–§9)
376
+ - [ ] Read-only invariant maintained — zero source code modifications
377
+ - [ ] Multi-layer generalization + discovery triage (unless --skip-generalize)
378
+ - [ ] phase_goals derived, tracked, and hardened-audited; goal_mode injected via prepare goal:true
379
+ - [ ] Session resumable via -c; completion summary emitted
380
+
381
+ ---
382
+
383
+ ## Next Step Routing (defensive-specific)
384
+
385
+ | Condition | Next |
386
+ |-----------|------|
387
+ | Critical/High findings need fix | `$ew-odyssey <finding> --mode improve` |
388
+ | Root-cause debug needed | `$ew-odyssey <finding> --mode debug` |
389
+ | Deeper audit tier needed | `$ew-odyssey <target> --mode defensive --tier deep` |
390
+ | Discovery issues created | `Open the follow-up findings in the project issue tracker` |
391
+ | Document pattern | `Review the module and stage the reusable method via Agent Memory closeout` |
392
+ | Second opinion | `evolve delegate "<review prompt>" --mode analysis` |
393
+ | Related question | `Use an Evolve analyze step for the question` |
394
+ | Defensive pattern to persist | `stage spec → coding` |
395
+ | Pending decisions | Filter evidence phase=decision status=pending |