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,369 @@
1
+ ---
2
+ name: ew-odyssey-defensive
3
+ prepare: odyssey-defensive
4
+ session-mode: inherited
5
+ ---
6
+
7
+ # Workflow: Odyssey Defensive
8
+
9
+ Read-only defensive-programming risk audit — business-anchor driven + local slicing + bidirectional propagation. Identify critical business sinks → backward-slice to defensive nodes → scan 8 defensive patterns → identify failure→value transformations → forward-propagate to sinks → classify exception semantics → score `R = S × P × B × H` → severity matrix report with full propagation chains → generalize defensive patterns.
10
+
11
+ Core judgment (§19):
12
+
13
+ > Defensive Code + Failure Suppression + Semantic Transformation + Critical Propagation = Defensive Programming Risk
14
+
15
+ ---
16
+
17
+ ## State Chain
18
+
19
+ ```
20
+ S_INTAKE → S_ANCHOR → S_SLICE → S_SCAN → S_PROPAGATE → S_REPORT → [back-half]
21
+ ```
22
+
23
+ Back-half: `S_GENERALIZE → S_DISCOVER → S_RECORD → END` (see [shared phases](odyssey-base.md) §Shared Back-Half).
24
+
25
+ **No S_FIX / S_CONFIRM** — this mode is read-only. Findings route to `--mode improve` (fix defensive defect) or `--mode debug` (root-cause).
26
+
27
+ ---
28
+
29
+ ## Boundary
30
+
31
+ **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.
32
+ **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.
33
+
34
+ ---
35
+
36
+ ## Target Resolution
37
+
38
+ | Input | Resolution |
39
+ |-------|-----------|
40
+ | File/dir path | Audit those files |
41
+ | `HEAD` / `staged` | `git diff HEAD` / `git diff --staged` — defensive patterns introduced/modified in diff |
42
+ | Phase number | state.json → changed files for that phase |
43
+ | PR number | `git diff main...HEAD` |
44
+
45
+ ---
46
+
47
+ ## Session Fields
48
+
49
+ ```json
50
+ { "target": "", "tier": "standard", "sink_depth": "all",
51
+ "anchors": {"critical_vars": [], "sink_layers": {"level_1": [], "level_2": [], "level_3": []}},
52
+ "scan_result": {"by_pattern": {}, "candidates": []},
53
+ "propagation": {"confirmed_chains": [], "risky_sinks": [], "q4_hidden": 0},
54
+ "audit_result": {"findings": [], "risk_matrix": {}},
55
+ "findings_count": {},
56
+ "generalization_stats": null }
57
+ ```
58
+
59
+ ---
60
+
61
+ ## evidence.ndjson Phases
62
+
63
+ `anchor|slice|scan|propagate|report|discovery|decision|self-iteration`
64
+
65
+ Phase-specific extension fields:
66
+
67
+ - `anchor`: `category` (critical_var|business_sink|data_flow), `var_name`, `importance` (high|medium|low)
68
+ - `slice`: `anchor_var`, `source_chain`, `passes_default` (bool), `passes_except` (bool), `auto_corrected` (bool), `multiple_sources` (bool)
69
+ - `scan`: `pattern` (broad_catch|exception_swallow|default|null_fallback|auto_correct|silent_convert|dup_constraint|dup_default), `file`, `line`, `original_failure_type`, `snippet`
70
+ - `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)
71
+ - `report`: `finding_ref`, `risk_level`, `remediation`
72
+
73
+ ---
74
+
75
+ ## phase_goals[]
76
+
77
+ | ID | Goal | done_when | phase | skip_when |
78
+ |----|------|-----------|-------|-----------|
79
+ | G1 | Anchors identified | critical_vars ≥1 AND sink_layers.level_1 ≥1 | S_ANCHOR | — |
80
+ | G2 | Slice completed | every critical_var has a source_chain | S_SLICE | — |
81
+ | G3 | Scan completed (all tier patterns) | all tier-required patterns scanned | S_SCAN | — |
82
+ | G4 | Propagation verified | every candidate has reaches_critical_sink + scores + exception_class | S_PROPAGATE | — |
83
+ | G5 | Report produced | risk_matrix with full propagation chains + scores | S_REPORT | — |
84
+ | G6 | Pattern generalized | patterns[] ≥1 | S_GENERALIZE | skip_generalize |
85
+ | G7 | Discoveries triaged | all hits classified | S_DISCOVER | skip_generalize |
86
+ | G8 | Learnings persisted | spec entries or no actionable | S_RECORD | — |
87
+
88
+ ---
89
+
90
+ ## understanding.md — 9 Sections
91
+
92
+ 1. Target & Scope & Tier
93
+ 2. Business Anchors (critical-variable table + sink layering)
94
+ 3. Local Business Flow (three-layer map: business-semantic ↔ software-component ↔ code-implementation)
95
+ 4. Defensive Nodes (8-pattern scan results, bucketed by pattern)
96
+ 5. Failure→Value Transformations (§7 six transformation types)
97
+ 6. Propagation Chains (forward chains + sink-hit verdicts + Q4 signals)
98
+ 7. Constraint & Default Consistency (§10 cross-module aggregation)
99
+ 8. Risk Matrix & Exception Classification (R=S×P×B×H scores + A/B/C/D + §14 standard report entries)
100
+ 9. Generalization & Discoveries & Learnings
101
+
102
+ Specs: `agent-memory wiki constraints --category coding` (defensive-programming patterns).
103
+
104
+ ---
105
+
106
+ ## State Machine — Transitions
107
+
108
+ ```
109
+ S_ANCHOR → S_SLICE : complete (anchors identified)
110
+ S_SLICE → S_SCAN : complete (source chains traced)
111
+ S_SCAN → S_PROPAGATE : all tier patterns scanned
112
+ S_PROPAGATE → S_REPORT : all candidates scored + sink verdict
113
+ S_REPORT → S_GENERALIZE : report produced, !skip_generalize
114
+ S_REPORT → S_RECORD : report produced, skip_generalize
115
+ ```
116
+
117
+ 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`.
118
+
119
+ ---
120
+
121
+ ## Actions
122
+
123
+ ### A_INTAKE extra
124
+
125
+ Tier resolution: parse `--tier` (default: standard) and `--sink-depth` (default: all). Record tier + applicable scan patterns + sink-layer focus to `session.json`.
126
+
127
+ ### A_ANCHOR
128
+
129
+ (§3 step — determine business-critical anchors.)
130
+
131
+ 1. Identify business-critical outputs (objective / constraint / decision / state / response / DB write / control quantity / model prediction / optimization result / ...).
132
+ 2. Build the **critical-variable table**: `| variable | business meaning | source | usage location | importance |`.
133
+ 3. **Sink layering** (§8 three-tier sinks):
134
+ - **Level 1 (high risk):** business decision / control command / objective function / constraint check / model training / optimization algorithm / core DB state / financial amount / security permission.
135
+ - **Level 2 (medium risk):** computation result / report output / intermediate model / API response / cache.
136
+ - **Level 3 (low risk):** log / UI display / temp file / debug info.
137
+ 4. Write `anchors.json` (critical_vars + sink_layers) + evidence phase=anchor. Update §2. Mark G1.
138
+
139
+ **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).
140
+
141
+ Commit: `"odyssey-defensive({slug}): ANCHOR — {N} anchors, {M} level-1 sinks"`
142
+
143
+ ### A_SLICE
144
+
145
+ (§4-§5 — recover local business flow + backward slice from critical results.)
146
+
147
+ 1. For each critical_var, recover its **local business flow** — three-layer map: business-semantic layer ↔ software-component layer ↔ code-implementation layer (e.g. `DesignManager → SimulationAdapter → ResultParser → Evaluator → Optimizer` ↔ `objective() → evaluate() → run_simulation() → solver.run()`).
148
+ 2. **Backward slice** from each critical_var, answering the 7 questions: (1) where does it originate? (2) does it pass a default value? (3) any type conversion? (4) any exception handling? (5) any auto-correction? (6) multiple possible sources? (7) intermediate-state substitution?
149
+ 3. Write evidence phase=slice (one source_chain per anchor) + §3 three-layer map. Mark G2.
150
+
151
+ **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.
152
+
153
+ Commit: `"odyssey-defensive({slug}): SLICE — {N} chains traced"`
154
+
155
+ ### A_SCAN
156
+
157
+ (§6 — scan defensive-code nodes. Full 8-pattern parallel agents; quick tier covers P1-P4 only.)
158
+
159
+ | # | Pattern | Scan signals (AST/Grep) | §ref |
160
+ |---|---------|-------------------------|------|
161
+ | P1 | broad_catch | `except:`, `except Exception:` | 6.1 |
162
+ | P2 | exception_swallow | `except ...: pass`, `except ...: return None`, `return {}`, `return 0` | 6.2 |
163
+ | P3 | default | `.get(k, v)`, `getattr(o, x, d)`, `v or default` | 6.3 |
164
+ | P4 | null_fallback | `if x is None: return None` / `return {}` | 6.4 |
165
+ | P5 | auto_correct | `max(x, lo)`, `min(x, hi)`, `min(max(x, lo), hi)` (clamp) | 6.5 |
166
+ | P6 | silent_convert | `try: x = float(x) except: x = 0` | 6.6 |
167
+ | P7 | dup_constraint | cross-module same variable, divergent constraints (`< 10`, `<= 12`, `>= 15`) | 6.7 |
168
+ | P8 | dup_default | cross-module same config, divergent defaults (`temperature = 25 / 20 / 293.15`) | 6.8 |
169
+
170
+ Spawn N parallel agents, one per pattern. Each scans the target files using the signals above (AST preferred; Grep fallback per W001). Each returns `[{pattern, file, line, original_failure_type, snippet, surrounding_context}]`.
171
+
172
+ P7/P8 require **cross-module aggregation**: full-repo grep for the same variable name → compare constraints/defaults across modules → flag unit / business-meaning / duplication / conflict inconsistencies (§10).
173
+
174
+ Merge all findings → evidence phase=scan. Write `scan_result.by_pattern` + `scan_result.candidates`. Update §4 (per-pattern buckets) + §7 (consistency). Mark G3.
175
+
176
+ **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).
177
+
178
+ Commit: `"odyssey-defensive({slug}): SCAN — {tier} tier, {N} candidates across {M} patterns"`
179
+
180
+ ### A_PROPAGATE
181
+
182
+ (§7-§10 — the core phase. Identify failure→value transformations → forward propagation → sink verdict → consistency → exception classification → risk scoring.)
183
+
184
+ 1. For each scan candidate, identify the **failure→value state transformation** (§7 six types):
185
+
186
+ | Transformation | Signature |
187
+ |---------------|-----------|
188
+ | Exception → None | exception swallowed → `None` propagates |
189
+ | Exception → Empty | exception → `{}` / `[]` |
190
+ | Exception → Numeric | exception → `0` (HIGH risk) |
191
+ | Missing → Default | missing key → `mass = 0` |
192
+ | Invalid → Corrected | `temperature = -100` → clamp → `0` |
193
+ | MultiErr → SingleState | ConvergenceError + FileNotFoundError + LicenseError + TypeError → `None` (异常语义坍缩) |
194
+
195
+ 2. **Forward propagation**: Defensive Node → Forward Propagation → does it reach a Critical Business Sink? (`Defensive Node ↓ Forward Propagation ↓ Critical Business Sink?`)
196
+
197
+ 3. **Sink verdict** (three-tier) + **Q4 signal** (§18): "can the downstream still know the upstream error occurred?" — `不能` (cannot) = high-risk signal, MUST be flagged.
198
+
199
+ 4. **Constraint/default consistency check** (§10): cross-module same variable — are units / business meaning / duplication / conflict inconsistent? Flag `Constraint Inconsistency` / `Default Inconsistency`.
200
+
201
+ 5. **Exception semantic classification** (§9): classify each swallowed exception as:
202
+
203
+ | Class | Examples | Recommended handling |
204
+ |------|----------|---------------------|
205
+ | A — business illegal | design var out-of-bounds, illegal input, geometric infeasible, rule conflict | reject / penalty / retry |
206
+ | B — numerical/algorithm | SolverConvergenceError, NumericalOverflow, SingularMatrix | retry / penalty / fallback solver |
207
+ | C — system environment | LicenseError, FileNotFoundError, PermissionError, OutOfMemory | NEVER silent degrade |
208
+ | D — program defect | TypeError, AttributeError, KeyError, IndexError | expose error, do NOT convert to normal result |
209
+
210
+ 6. **Risk scoring** `R = S × P × B × H` (§12):
211
+ - **S** = defensive-code severity (e.g. `except Exception: pass` = high)
212
+ - **P** = propagation range (local log = low; reaches optimizer = high)
213
+ - **B** = business criticality (level-3 sink = low; level-1 sink = high)
214
+ - **H** = error-hiding degree (downstream unaware = high)
215
+
216
+ Map to final level (§13):
217
+ - **Critical** — defensive logic directly alters a critical business decision (e.g. `Simulation Error → mass=0 → Optimization Objective`).
218
+ - **High** — error hidden and enters core computation but does not directly decide the business result.
219
+ - **Medium** — unreasonable fallback / default / duplicate constraint, but propagation limited.
220
+ - **Low** — local defensive code with near-zero impact on critical results (e.g. temp-file cleanup failure, log write failure).
221
+
222
+ Rule: only `reaches_critical_sink == true` may be High+; findings reaching only level-3 sinks default to Low.
223
+
224
+ 7. Write `propagation.confirmed_chains` + `propagation.risky_sinks` + `propagation.q4_hidden` count + evidence phase=propagate. Update §5 / §6 / §7 / §8. Mark G4.
225
+
226
+ **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).
227
+
228
+ Commit: `"odyssey-defensive({slug}): PROPAGATE — {N} chains, {M} reach critical sink, {K} Q4-hidden"`
229
+
230
+ ### A_REPORT
231
+
232
+ (§12-§14 — risk scoring formalized + standard report format.)
233
+
234
+ 1. Produce a finding per candidate using the **§14 standard report format**:
235
+
236
+ ```
237
+ DEF-NNN
238
+ Risk level: Critical | High | Medium | Low
239
+ Defensive location: file:line
240
+ Trigger pattern: broad_catch | exception_swallow | default | ...
241
+ Original failure: SimulationSystemError
242
+ State transform: Exception → {} → mass = 0
243
+ Full propagation: solver.run() → except Exception → return {} → result.get("mass", 0) → objective() → optimizer
244
+ Business impact: simulation error converted to mass=0; optimizer may pick the failed design as optimal.
245
+ Remediation: distinguish DesignInfeasibleError (penalty) vs SimulationSystemError (raise).
246
+ ```
247
+
248
+ 2. Build the **severity matrix** (Critical / High / Medium / Low) with file:line references, full propagation chains, Q4 signals, and remediation for every finding.
249
+ 3. Compute summary statistics: counts per level, per pattern, per exception class, Q4-hidden total.
250
+ 4. Write §8 (risk matrix + exception classification + standard report entries) + `session.json.audit_result` + `session.json.findings_count`. Evidence phase=report. Mark G5.
251
+
252
+ **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).
253
+
254
+ Commit: `"odyssey-defensive({slug}): REPORT — {C}C/{H}H/{M}M/{L}L matrix"`
255
+
256
+ ---
257
+
258
+ ## Generalize Source
259
+
260
+ Critical/High findings that propagate to a level-1 sink + cross-module duplicate defensive patterns (dup_constraint / dup_default) + recurring failure→value transformation signatures.
261
+
262
+ **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`.
263
+
264
+ ---
265
+
266
+ ## Knowledge Persistence (§9)
267
+
268
+ Include verified reusable findings in the Run summary and harvest the completed Session through Agent Memory closeout.
269
+
270
+ | Category | Content | Follow-up |
271
+ |----------|---------|-----------|
272
+ | Failure→Value transformation pattern | transformation signature + trigger + detection pattern + fix template | `stage spec → coding` |
273
+ | 异常语义坍缩 (exception semantic collapse) | multi-exception → single-state signature + business consequence + detection | `stage spec → coding` |
274
+ | Constraint/default inconsistency | variable + per-location values + unit/meaning conflict + resolution | `stage spec → arch` |
275
+ | Critical propagation chain | sink + chain + hiding mechanism + remediation strategy | `stage spec → debug` |
276
+
277
+ ---
278
+
279
+ ## Completion Summary
280
+
281
+ ```
282
+ --- DEFENSIVE ODYSSEY COMPLETE ---
283
+ Target: {target}
284
+ Tier: {tier}
285
+ Anchors: {N} critical vars, {M} level-1 sinks
286
+ Patterns: P1:{n1} P2:{n2} P3:{n3} P4:{n4} P5:{n5} P6:{n6} P7:{n7} P8:{n8}
287
+ Candidates: {N} defensive nodes
288
+ Chains: {N} propagated, {M} reach critical sink
289
+ Risk: {C}C / {H}H / {M}M / {L}L
290
+ Q4-hidden: {N} findings where downstream cannot detect upstream error
291
+ Exception: A:{a} B:{b} C:{c} D:{d}
292
+ Patterns: {count} ({by_layer})
293
+ Scan hits: {total} ({cross_layer_confirmed} confirmed)
294
+ Issues: {N} created
295
+ Decisions: {N} resolved, {M} pending, {K} deferred
296
+ Learnings: {N} persisted
297
+ Self-iter: {N} rounds across {M} stages
298
+ Cross-loops: {N}
299
+ Goals: {done}/{total} ({skipped} skipped)
300
+ ---
301
+ ```
302
+
303
+ ---
304
+
305
+ ## `-y` Decision Points
306
+
307
+ | Decision Point | Normal | `-y` |
308
+ |---------------|--------|------|
309
+ | A_ANCHOR critical-variable importance | request_user_input | auto-classify by semantic layer |
310
+ | A_SCAN false-positive dismissal | request_user_input | Dismiss only with recorded counter-evidence. Keep unresolved candidates as deferred. |
311
+ | A_PROPAGATE sink-hit ambiguity | request_user_input | auto-mark worst-case High |
312
+ | A_REPORT risk-level downgrade | request_user_input | Downgrade only with documented counter-evidence. Keep the current severity or risk level when the decision is deferred. |
313
+ | A_DISCOVER routing | request_user_input | Record a deferred discovery with evidence. Route issue creation and improve work through an explicit follow-up. |
314
+ | Ambiguous items | request_user_input | all `deferred` |
315
+
316
+ ---
317
+
318
+ ## Mode-Specific Phase Gates
319
+
320
+ - **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.
321
+ - **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).
322
+ - **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.
323
+ - **Report gate** (S_REPORT): severity matrix with §14 standard report entries + full propagation chains + remediation. §8 written. Read-only invariant verified (zero source modifications).
324
+
325
+ ---
326
+
327
+ ## Error Codes (defensive-specific)
328
+
329
+ | Code | Severity | Condition | Recovery |
330
+ |------|----------|-----------|----------|
331
+ | E001 | error | No target / scope provided | Provide target or -c |
332
+ | E002 | error | No critical vars / no level-1 sink found | Verify target has business-critical output |
333
+ | W001 | warning | AST tool unavailable | Fall back to Grep, note coverage gap |
334
+ | W002 | warning | Cross-module aggregation failed (no symbol table) | Local-only constraint/default check, note limitation |
335
+ | W003 | warning | Candidate undecidable for sink/score | Per-item `needs_review`, do not BLOCK |
336
+ | W004 | warning | Generalization 0 hits after full 3-layer scan | Advance to S_RECORD |
337
+ | W005 | warning | Pending decisions | Filter evidence phase=decision |
338
+
339
+ ---
340
+
341
+ ## Success Criteria (defensive-specific)
342
+
343
+ - [ ] Target resolved; tier + sink-depth determined; session + 4 output files + prior knowledge searched
344
+ - [ ] S_ANCHOR: critical-variable table + sink layering (§2) with ≥1 level-1 sink
345
+ - [ ] S_SLICE: per-critical-var source_chain + three-layer business-flow map (§3)
346
+ - [ ] S_SCAN: all tier-required 8 patterns scanned, bucketed per-pattern (§4/§7)
347
+ - [ ] S_PROPAGATE: every candidate has state transformation + sink verdict + Q4 signal + four-dimensional score + exception class (§5/§6/§8)
348
+ - [ ] S_REPORT: severity matrix + full propagation chains + remediation, in §14 standard report format (§8)
349
+ - [ ] understanding.md 9 sections written progressively (§1–§9)
350
+ - [ ] Read-only invariant maintained — zero source code modifications
351
+ - [ ] Multi-layer generalization + discovery triage (unless --skip-generalize)
352
+ - [ ] phase_goals derived, tracked, and hardened-audited; goal_mode injected via prepare goal:true
353
+ - [ ] Session resumable via -c; completion summary emitted
354
+
355
+ ---
356
+
357
+ ## Next Step Routing (defensive-specific)
358
+
359
+ | Condition | Next |
360
+ |-----------|------|
361
+ | Critical/High findings need fix | `/ew-odyssey <finding> --mode improve` |
362
+ | Root-cause debug needed | `/ew-odyssey <finding> --mode debug` |
363
+ | Deeper audit tier needed | `/ew-odyssey <target> --mode defensive --tier deep` |
364
+ | Discovery issues created | `Open the follow-up findings in the project issue tracker` |
365
+ | Document pattern | `Review the module and stage the reusable method via Agent Memory closeout` |
366
+ | Second opinion | `evolve delegate "<review prompt>" --mode analysis` |
367
+ | Related question | `Use an Evolve analyze step for the question` |
368
+ | Defensive pattern to persist | `stage spec → coding` |
369
+ | Pending decisions | Filter evidence phase=decision status=pending |
@@ -0,0 +1,270 @@
1
+ <!-- session-mode: inherited -->
2
+
3
+ # Workflow: Odyssey Improve (Codex)
4
+
5
+ 6-dimension runtime quality improvement — performance/security/architecture/reliability/observability/maintainability audit → diagnose → fix → generalize. Codex-adapted: uses `spawn_agents_on_csv`, `request_user_input`, `update_plan`.
6
+
7
+ ---
8
+
9
+ ## State Chain
10
+
11
+ ```
12
+ S_INTAKE → S_SURVEY → S_AUDIT → S_DIAGNOSE → S_FIX → S_VERIFY → [back-half]
13
+ ```
14
+
15
+ Back-half: `S_GENERALIZE → S_DISCOVER → S_RECORD → END` (see [shared Codex phases](odyssey-base-codex.md) Shared Back-Half).
16
+
17
+ ---
18
+
19
+ ## Boundary
20
+
21
+ **In scope:** Runtime quality improvement — performance/security/architecture/reliability/observability/maintainability audit → diagnose → fix → generalize. **Out of scope:** UI visual → `--mode ui` | New features → `--mode planex` | Single bug → `--mode debug` | Style review → `--mode review`. Zero-residual applies.
22
+
23
+ ---
24
+
25
+ ## Context
26
+
27
+ ### Target Resolution
28
+
29
+ | Input | Resolution |
30
+ |-------|-----------|
31
+ | Module/dir path | Audit that module |
32
+ | `HEAD` / `staged` | Review changes in diff |
33
+ | Feature area keyword | Resolve to related files |
34
+ | `--all` | Full project scan (use with caution) |
35
+
36
+ ### Dimensions (6)
37
+
38
+ 1. **performance** — hot paths, N+1, memory allocation, cache efficiency, bundle size, lazy loading
39
+ 2. **security** — OWASP Top 10, injection, auth bypass, data exposure, dependency vulns, secrets
40
+ 3. **architecture** — layer violations, circular deps, coupling, interface contracts, SRP
41
+ 4. **reliability** — error handling gaps, retry, timeout, graceful degradation, resource cleanup
42
+ 5. **observability** — logging coverage, metric gaps, trace propagation, error reporting, health checks
43
+ 6. **maintainability** — cyclomatic complexity, dead code, test coverage gaps, doc debt
44
+
45
+ ### Session Fields
46
+
47
+ ```json
48
+ { "target": "", "dimensions": [], "baseline_metrics": {},
49
+ "audit_result": {}, "diagnoses": [], "confirmation": null,
50
+ "generalization_stats": null }
51
+ ```
52
+
53
+ ### evidence.ndjson Phases
54
+
55
+ `survey|audit|diagnosis|fix|discovery|decision|self-iteration`
56
+
57
+ - `survey`: `category` (dependency|complexity|coverage|error_pattern), `detail`
58
+ - `audit`: `dimension`, `severity`, `measurement`
59
+ - `diagnosis`: `finding_ref`, `hypothesis`, `result`, `root_cause`
60
+ - `fix`: `finding_ref`, `change_summary`, `risk`
61
+
62
+ ### phase_goals[]
63
+
64
+ | ID | Goal | Phase | skip_when |
65
+ |----|------|-------|-----------|
66
+ | G1 | Survey completed | S_SURVEY | — |
67
+ | G2 | Audit completed | S_AUDIT | — |
68
+ | G3 | Diagnosis completed | S_DIAGNOSE | — |
69
+ | G4 | Zero remaining: all findings fixed and verified | S_VERIFY | skip_fix |
70
+ | G5 | Pattern generalized | S_GENERALIZE | skip_generalize |
71
+ | G6 | Discoveries triaged | S_DISCOVER | skip_generalize |
72
+ | G7 | Learnings persisted | S_RECORD | — |
73
+
74
+ ### understanding.md — 9 Sections
75
+
76
+ 1. Target & Baseline
77
+ 2. Current State Survey
78
+ 3. Audit Findings
79
+ 4. Root Cause Diagnosis
80
+ 5. Fix & Verification
81
+ 6. Generalization
82
+ 7. Discoveries
83
+ 8. Improvement Metrics (before/after)
84
+ 9. Engineering Learnings
85
+
86
+ ---
87
+
88
+ ## State Machine
89
+
90
+ ### Transitions
91
+
92
+ ```
93
+ S_SURVEY → S_AUDIT : complete
94
+ S_AUDIT → S_DIAGNOSE : critical/high findings exist
95
+ S_AUDIT → S_GENERALIZE : no critical/high, !skip_generalize
96
+ S_AUDIT → S_RECORD : no findings OR skip_generalize
97
+ S_DIAGNOSE → S_FIX : root causes identified, !skip_fix
98
+ S_DIAGNOSE → S_GENERALIZE : root causes identified, skip_fix, !skip_generalize
99
+ S_DIAGNOSE → S_RECORD : root causes identified, skip_fix, skip_generalize
100
+ S_DIAGNOSE → S_DIAGNOSE : hypotheses failed, retries < 3 → A_ESCALATE_DIAGNOSIS
101
+ S_DIAGNOSE → S_RECORD : retries >= 3 → INCONCLUSIVE
102
+ S_FIX → S_VERIFY : fix implemented
103
+ S_VERIFY → S_GENERALIZE : verified, !skip_generalize
104
+ S_VERIFY → S_RECORD : verified, skip_generalize
105
+ S_VERIFY → S_FIX : needs_rework
106
+ ```
107
+
108
+ ### Actions
109
+
110
+ **A_INTAKE extra** — Baseline capture: record current metrics (test pass rate, bundle size, dependency count, complexity hotspots) to `session.json.baseline_metrics`. `update_plan({ plan: [{ step: "G1: survey", status: "pending" }, { step: "G2: audit", status: "pending" }, { step: "G3: diagnose", status: "pending" }, { step: "G4: verify", status: "pending" }] })`(初始化 gate 清单)
111
+
112
+ **A_SURVEY** — (1) Dependency audit (package.json/lock), complexity scan (size/nesting), test coverage map, error handling scan (empty catch, unhandled promise). (2) CLI-assisted (optional): `evolve delegate --role analyze --mode analysis` for dependency health / complexity hotspots / coverage gaps / error patterns (`run_in_background: true`). (3) Evidence phase=survey. Update §2. `update_plan`(G1 → completed).
113
+
114
+ Commit: `"odyssey-improve({slug}): SURVEY — current state survey complete"`
115
+
116
+ **A_AUDIT** — 6-dimension parallel audit via CSV wave (or `--dimensions` subset).
117
+
118
+ Generate `audit-dimensions.csv`:
119
+
120
+ ```csv
121
+ id,dimension,focus,target_files,status,findings_json,error
122
+ "1","performance","hot paths, N+1, memory allocation, cache efficiency, bundle size, lazy loading","${target}","","",""
123
+ "2","security","OWASP Top 10, injection, auth bypass, data exposure, dependency vulns, secrets","${target}","","",""
124
+ "3","architecture","layer violations, circular deps, coupling, interface contracts, SRP","${target}","","",""
125
+ "4","reliability","error handling gaps, retry, timeout, graceful degradation, resource cleanup","${target}","","",""
126
+ "5","observability","logging coverage, metric gaps, trace propagation, error reporting, health checks","${target}","","",""
127
+ "6","maintainability","cyclomatic complexity, dead code, test coverage gaps, doc debt","${target}","","",""
128
+ ```
129
+
130
+ ```javascript
131
+ spawn_agents_on_csv({
132
+ csv_path: `${sessionFolder}/audit-dimensions.csv`,
133
+ id_column: "id",
134
+ instruction: "You are auditing code quality for a specific dimension. Read the 'dimension' and 'focus' columns. Scan target files in the 'target_files' column, identify issues. Return: findings_json as a JSON array [{title, severity, dimension, file, line, description, suggestion, measurement}]. Severity levels: critical, high, medium, low. Be thorough — check all files in scope for this dimension.",
135
+ max_concurrency: 6,
136
+ max_runtime_seconds: 3600,
137
+ output_csv_path: `${sessionFolder}/audit-results.csv`,
138
+ output_schema: { id, status: ["completed"|"failed"], findings_json, error }
139
+ })
140
+ ```
141
+
142
+ Merge results from all dimensions → evidence phase=audit. Write `session.json.audit_result`. Update §3 (findings by dimension + severity matrix). `update_plan`(G2 → completed).
143
+
144
+ **GATE: all-dimensions-audited** — all 6 dimensions (or `--dimensions` subset) completed with structured findings, merged into severity matrix, evidence phase=audit logged per dimension. Zero dimensions reviewed is BLOCKED (W002 partial from agent failure is a warning).
145
+
146
+ Commit: `"odyssey-improve({slug}): AUDIT — dimension audit complete"`
147
+
148
+ **A_DIAGNOSE** — Root cause analysis for critical/high findings — don't fix symptoms. (1) Group by dimension, prioritize by severity; for each: hypothesis → trace code path + git history → evidence phase=diagnosis. (2) Ambiguity → evidence phase=decision; Normal: `request_user_input` | `-y`: defer. (3) CLI-assisted for complex findings (`run_in_background: true`). (4) Write `session.json.diagnoses[]`. Update §4. `update_plan`(G3 → completed).
149
+
150
+ Commit: `"odyssey-improve({slug}): DIAGNOSE — root cause analysis complete"`
151
+
152
+ **A_ESCALATE_DIAGNOSIS** — `retries++`. < 3: `evolve delegate --role analyze`, new hypotheses, → S_DIAGNOSE. >= 3: Normal → `request_user_input` | `-y` → INCONCLUSIVE → S_RECORD.
153
+
154
+ **A_FIX** — (1) Exhaustive fix: ALL diagnosed issues by severity tier (critical → high → medium → low within fix_threshold), one dimension at a time. After each tier, re-verify **current tier's dimension only** (not all dimensions); new findings at same or higher severity append to current tier. Cross-dimension regression checks run once at S_VERIFY after all tiers. **No partial-tier advancement** — each tier fully addressed (fixed or individually classified) before advancing; blanket "pre-existing" skip forbidden. (2) For each fix: implement → evidence phase=fix. (3) Normal: `request_user_input` per-fix | `-y`: auto-proceed, record `deferred`.
155
+
156
+ Commit: `"odyssey-improve({slug}): FIX — {dimension} {tier} tier addressed"`
157
+
158
+ **A_VERIFY** — (1) Run tests covering modified areas. (2) Re-capture metrics, compare with `baseline_metrics`. (3) CLI-assisted: `evolve delegate --role review --mode analysis` (`run_in_background: true`). (4) `needs_rework` → S_FIX; `verified` → `update_plan`(G4 → completed). (5) Write `confirmation`. Update §5 (before/after metrics table).
159
+
160
+ **GATE: zero-remaining-verified** — every diagnosed finding is fixed and verified, individually classified (issue / decision), or skipped via `--skip-fix`; tests pass over modified areas; metrics re-captured and compared against `baseline_metrics`; no unaddressed actionable findings; before/after table written to understanding.md §8.
161
+
162
+ Commit: `"odyssey-improve({slug}): VERIFY — fix verification complete"`
163
+
164
+ ---
165
+
166
+ ## Generalize Source
167
+
168
+ Diagnosed root causes + applied fixes across all dimensions. **Discover routing:** `bug` → S_FIX; new critical → S_DIAGNOSE.
169
+
170
+ ---
171
+
172
+ ## Knowledge Persistence (§9)
173
+
174
+ Include verified reusable findings in the Run summary and harvest the completed Session through Agent Memory closeout.
175
+
176
+
177
+ A_RECORD extra: §8 improvement metrics — re-capture and build before/after comparison table from `baseline_metrics` vs current.
178
+
179
+ | Category | Content | Follow-up |
180
+ |----------|---------|-----------|
181
+ | Performance pattern | Bottleneck type + fix approach + measurement | `stage spec → coding` |
182
+ | Security rule | Vulnerability class + fix + prevention | `stage spec → debug` |
183
+ | Architecture constraint | Violation + correct boundary + check | `stage spec → arch` |
184
+ | Reliability pattern | Failure mode + handling strategy + verification | `stage spec → coding` |
185
+
186
+ ---
187
+
188
+ ## Completion Summary
189
+
190
+ ```
191
+ --- IMPROVE ODYSSEY COMPLETE ---
192
+ Target: {target}
193
+ Dimensions: {dimensions}
194
+ Findings: {critical}C / {high}H / {medium}M / {low}L
195
+ Diagnosed: {count}
196
+ Fixed: {count} ({verified} verified)
197
+ Metrics: {improved} improved / {regressed} regressed
198
+ Patterns: {count} ({by_layer})
199
+ Scan hits: {total} ({cross_layer_confirmed} confirmed)
200
+ Issues: {N} created
201
+ Decisions: {N} resolved, {M} pending, {K} deferred
202
+ Learnings: {N} persisted
203
+ Self-iter: {N} rounds across {M} stages
204
+ Cross-loops: {N}
205
+ Goals: {done}/{total} ({skipped} skipped)
206
+ ---
207
+ ```
208
+
209
+ ---
210
+
211
+ ## Mode `-y` Points
212
+
213
+ | Decision Point | Normal | `-y` |
214
+ |---------------|--------|------|
215
+ | A_FIX confirmation | `request_user_input` | auto-proceed `deferred` |
216
+ | A_DIAGNOSE ambiguity | `request_user_input` | best-effort `deferred` |
217
+ | A_ESCALATE 3-strike | `request_user_input` | auto INCONCLUSIVE |
218
+ | A_DISCOVER routing | `request_user_input` | auto create issue |
219
+ | Ambiguous items | `request_user_input` | all `deferred` |
220
+
221
+ ---
222
+
223
+ ## Phase Gates
224
+
225
+ - **Discovery gate** (SURVEY): evidence for the phase logged, understanding.md updated. Survey requires all scan types attempted.
226
+ - **Audit gate** (DIAGNOSE): all dimension agents completed, findings merged with severity classification. Zero dimensions reviewed is BLOCKED (W002 partial allowed).
227
+ - **FIX gate:** current severity tier fully addressed. Per-fix evidence phase=fix logged. Auto-commit per tier. No partial-tier advancement.
228
+ - **VERIFY gate:** tests pass; metrics re-captured; confirmation written, understanding.md updated, verify goal marked. needs_rework → route back to FIX.
229
+
230
+ ---
231
+
232
+ ## Error Codes
233
+
234
+ | Code | Severity | Condition | Recovery |
235
+ |------|----------|-----------|----------|
236
+ | E001 | error | No target provided | Provide target or -c |
237
+ | E002 | error | Target path not found | Check path |
238
+ | W001 | warning | No dependency manifest / no test coverage tool | Proceed with defaults |
239
+ | W002 | warning | Some dimension agents failed | Partial coverage accepted |
240
+ | W004 | warning | Generalization 0 hits after full 3-layer scan | Advance to S_RECORD |
241
+ | W005 | warning | Pending decisions | Filter evidence phase=decision |
242
+
243
+ ---
244
+
245
+ ## Success Criteria
246
+
247
+ - [ ] Target resolved; session + output files created; baseline metrics captured
248
+ - [ ] Survey completed with all scan types attempted (dependency, complexity, coverage, error handling)
249
+ - [ ] 6-dimension audit completed via `spawn_agents_on_csv` with structured findings + severity matrix
250
+ - [ ] understanding.md sections written progressively (§1-§9)
251
+ - [ ] Fix + verify (unless --skip-fix); zero-residual — every finding has concrete action
252
+ - [ ] Multi-layer generalization + discovery triage (unless --skip-generalize)
253
+ - [ ] phase_goals derived, tracked, and hardened-audited; goal_mode injected via prepare goal:true
254
+ - [ ] §8 improvement metrics: before/after comparison table from baseline_metrics
255
+ - [ ] Session resumable via -c; completion summary emitted
256
+
257
+ ---
258
+
259
+ ## Next Step Routing
260
+
261
+ | Condition | Next |
262
+ |-----------|------|
263
+ | Discovery issues created | `Open the follow-up findings in the project issue tracker` |
264
+ | Deeper debug needed | `$ew-odyssey <finding> --mode debug` |
265
+ | Formal review of changes | `$ew-odyssey <changed-files> --mode review` |
266
+ | UI-related findings | `$ew-odyssey <component> --mode ui` |
267
+ | Document pattern | `Review the module and stage the reusable method via Agent Memory closeout` |
268
+ | Second opinion | `evolve delegate "<review prompt>" --mode analysis` |
269
+ | Design/perf/arch pattern to persist | `stage spec → coding|arch` |
270
+ | Pending decisions | Filter evidence phase=decision status=pending |