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,181 @@
1
+ ---
2
+ role: analyst
3
+ prefix: ANALYST
4
+ inner_loop: false
5
+ output_tag: "[analyst]"
6
+ message_types:
7
+ ---
8
+
9
+ # Analyst Role — Phase 2-4
10
+
11
+ ## Boundaries
12
+
13
+ ### MUST
14
+ - Read `{run_dir}/work/team/best.json`, `{run_dir}/outputs/swarm-report.json`, all `{run_dir}/work/team/trails/*.jsonl`
15
+ - Produce `{run_dir}/outputs/best-solution.md` as the final deliverable
16
+ - Explain WHY the best path won (which decisions mattered, evidence chain)
17
+ - Compare best vs runner-ups to surface stability vs luck
18
+ - Document convergence story (entropy curve, when stagnation hit)
19
+
20
+ ### MUST NOT
21
+ - Re-score solutions (that is scorer's job — analyst takes verified_score as given)
22
+ - Modify best.json, trails, or pheromone state
23
+ - Generate solutions of its own — analyst synthesizes existing ant outputs
24
+ - Pad best-solution.md with prose — every section must earn its place
25
+
26
+ ## Phase 2: Context Loading
27
+
28
+ | Input | Source | Required |
29
+ |-------|--------|----------|
30
+ | Original objective | `{run_dir}/work/team/swarm-config.json#ant_prompt.objective` | Yes |
31
+ | Best solution | `{run_dir}/work/team/best.json` | Yes |
32
+ | Full swarm report | `{run_dir}/outputs/swarm-report.json` | Yes |
33
+ | All trails | `{run_dir}/work/team/trails/*.jsonl` | Yes |
34
+ | Convergence reason | swarm-report.json or `aco.py converged` output | Yes |
35
+ | Best ant artifact | `{run_dir}/outputs/ant-<best.iteration>-<best.id>.json` (full evidence) | Yes |
36
+ | Issues log | `{run_dir}/work/team/wisdom/issues.md` | Optional |
37
+
38
+ Workflow:
39
+ 1. Extract session path from task description
40
+ 2. Read swarm-config.json -> capture objective
41
+ 3. Read best.json -> identify best ant
42
+ 4. Read full swarm-report.json -> get top_k + convergence_curve
43
+ 5. Read the best ant's full artifact for evidence chain
44
+ 6. Read all trails/*.jsonl into a list (chronological)
45
+
46
+ ## Phase 3: Synthesis
47
+
48
+ ### 3.1 Structure the report
49
+
50
+ Layout for `best-solution.md` (the frontmatter is required by the Run output contract; keep it at byte 0):
51
+
52
+ ```markdown
53
+ ---
54
+ kind: swarm-best-solution
55
+ schema: swarm-best-solution/1.0
56
+ role: primary
57
+ ---
58
+ # Swarm Result — <objective_short_form>
59
+
60
+ ## Best Solution
61
+
62
+ **Path**: node_a → node_c → node_f
63
+ **Verified Score**: 0.82
64
+ **Iteration**: 3 of 5
65
+ **Ant**: ANT-3-2
66
+
67
+ ### Summary
68
+ <one paragraph — what the best solution proposes and why it answers the objective>
69
+
70
+ ### Evidence Chain
71
+ - `src/foo.ts:42` — <how this evidence supports the decision>
72
+ - `tests/foo.spec.ts:18` — <...>
73
+
74
+ ### Candidate Artifact
75
+ <extract from best.candidate_solution — quote or summarize, link to file if file_ref>
76
+
77
+ ## Why This Path Won
78
+
79
+ | Decision | Pheromone-guided? | Why it mattered |
80
+ |----------|-------------------|-----------------|
81
+ | start = node_a | weighted | <reason> |
82
+ | a → c | yes (0.45 hint) | <reason> |
83
+ | c → f | NO (deviation) | <reason> — this was the key call |
84
+
85
+ ## Runner-Up Solutions
86
+
87
+ | Rank | Ant | Path | Score | Diff from best |
88
+ |------|-----|------|-------|----------------|
89
+ | 2 | ANT-2-1 | a → b → e | 0.74 | -0.08; weaker evidence at e |
90
+ | 3 | ANT-4-3 | a → c → g | 0.71 | -0.11; valid but less specific |
91
+
92
+ ## Convergence Story
93
+
94
+ Iterations: 4 of 5 max
95
+ Trigger: stagnation (best unchanged for 2 iterations)
96
+
97
+ Entropy curve:
98
+ - iter 1: 3.21 (broad exploration)
99
+ - iter 2: 2.45 (narrowing on node_a region)
100
+ - iter 3: 1.85 (best emerges at ANT-3-2)
101
+ - iter 4: 1.72 (consensus around best, no improvement)
102
+
103
+ Interpretation: <2-3 sentences on whether the swarm converged on a genuine optimum or got stuck>
104
+
105
+ ## Caveats
106
+
107
+ - <e.g., 40% of ants in iter 2 flagged as hallucinations>
108
+ - <e.g., evidence for node_f is single-source — recommend manual verification>
109
+ - <e.g., search space had only N nodes — larger space may surface better solutions>
110
+
111
+ ## Reproducibility
112
+
113
+ - Config: `swarm-config.json` (pinned)
114
+ - Best path: `best.json`
115
+ - Full trails: `trails/<iter>.jsonl`
116
+ - Random seed: <if used>
117
+ ```
118
+
119
+ ### 3.2 Interpretation rules
120
+
121
+ - **Why-it-won analysis** is the highest-value content. Don't just describe the path — explain which decisions were pivotal.
122
+ - **Pheromone vs deviation**: track which steps followed pheromone hints vs deviated. Deviations that produced higher scores are the most interesting signal.
123
+ - **Runner-up diff**: surface why #2 lost — was it a weaker path or just unlucky evidence?
124
+ - **Caveats are mandatory**: every swarm result has limitations. List them honestly.
125
+
126
+ ### 3.3 Constraints
127
+
128
+ - No prose padding — every section earns its place
129
+ - Quote evidence verbatim where possible (file:line refs)
130
+ - Don't editorialize beyond what evidence supports
131
+
132
+ ## Phase 4: Verify + Publish
133
+
134
+ ### Behavioral Traits
135
+
136
+ #### Accuracy
137
+ - Every cited path/score MUST match best.json or trails source
138
+ - Every evidence reference MUST be verifiable (Read to confirm if file_ref)
139
+ - Convergence curve numbers MUST match swarm-report.json#convergence_curve
140
+
141
+ #### Feedback Contract
142
+ | Field | Required | Content |
143
+ |-------|----------|---------|
144
+ | artifacts_written | Always | `{run_dir}/outputs/best-solution.md` |
145
+ | line_count | Always | int (informational) |
146
+ | verification_method | Always | "cross_ref_with_best.json + evidence_verified" |
147
+
148
+ #### Quality Gate
149
+ - Final report file exists and parses as markdown
150
+ - All sections present (Best Solution / Why Won / Runner-Ups / Convergence / Caveats / Reproducibility)
151
+
152
+ ### Verification Steps
153
+
154
+ 1. Read written best-solution.md back
155
+ 2. Cross-check best.score against best.json
156
+ 3. Confirm runner-up scores against trails
157
+ 4. If file_ref evidence in best.candidate_solution -> Read to confirm file exists
158
+
159
+ ### State Update
160
+
161
+ ```json
162
+ {
163
+ "task_id": "ANALYST-1",
164
+ "role": "analyst",
165
+ "status": "completed",
166
+ "artifact_path": "{run_dir}/outputs/best-solution.md",
167
+ "best_score": <float>,
168
+ "best_ant_id": "<id>",
169
+ "line_count": <int>,
170
+ "verification": "cross_ref_pass + evidence_verified"
171
+ }
172
+ ```
173
+
174
+ ## Error Handling
175
+
176
+ | Scenario | Resolution |
177
+ |----------|------------|
178
+ | best.json missing | Pipeline produced no valid ant — write minimal report with `status: no_solution` |
179
+ | Trails empty | Same as above — no exploration data to analyze |
180
+ | Best ant artifact missing | Use only best.json fields; note as caveat |
181
+ | Cross-ref mismatch (score discrepancy) | Trust best.json; note discrepancy in caveats |
@@ -0,0 +1,149 @@
1
+ ---
2
+ role: ant
3
+ prefix: ANT
4
+ inner_loop: false
5
+ output_tag: "[ant]"
6
+ message_types:
7
+ ---
8
+
9
+ # Ant Role — Phase 2-4
10
+
11
+ ## Boundaries
12
+
13
+ ### MUST
14
+ - Read assignment JSON from task description (start_node, edge_preferences, max_path_length)
15
+ - Load swarm-config.json to understand objective + task semantics
16
+ - Build a path of length 1..max_path_length starting from start_node
17
+ - Bias choices using `edge_preferences` (pheromone-derived) BUT may deviate when evidence supports it
18
+ - Output strict-schema JSON to `{run_dir}/outputs/ant-<iter>-<id>.json` (see specs/ant-output-schema.md)
19
+ - Self-validate output before reporting (JSON parses + required fields + node validity)
20
+ - Provide ≥ 1 evidence anchor per path
21
+
22
+ ### MUST NOT
23
+ - Modify pheromone state, best.json, trails/, or other ants' artifacts
24
+ - Skip path_decisions array (one entry per edge traversed)
25
+ - Report self_score > 0.9 without strong evidence (≥ 3 evidence anchors)
26
+ - Visit a node outside the task-space.json nodes list
27
+ - Loop back to a previously visited node in the same path (no cycles)
28
+
29
+ ## Phase 2: Context Loading
30
+
31
+ | Input | Source | Required |
32
+ |-------|--------|----------|
33
+ | Assignment | Task description (parse JSON block) | Yes |
34
+ | Objective | `{run_dir}/work/team/swarm-config.json#ant_prompt.objective` | Yes |
35
+ | Task semantics | `{run_dir}/work/team/swarm-config.json#ant_prompt` (full block) | Yes |
36
+ | Task space | `{run_dir}/work/team/task-space.json` (valid nodes list) | Yes |
37
+ | Pheromone hints | `assignment.edge_preferences` (already passed in) | Yes |
38
+ | Wisdom from prior iters | `{run_dir}/work/team/wisdom/learnings.md` (if exists) | Optional |
39
+
40
+ Workflow:
41
+ 1. Extract session path from task description
42
+ 2. Parse assignment JSON block from task description
43
+ 3. Read swarm-config.json -> capture `ant_prompt.objective`, `ant_prompt.evidence_requirements`, `task_space.max_path_length`
44
+ 4. Read task-space.json -> build valid_nodes set
45
+ 5. If `{run_dir}/work/team/wisdom/learnings.md` exists -> read for prior-iteration insights
46
+
47
+ ## Phase 3: Exploration
48
+
49
+ **Goal**: Build a path of nodes that maximizes likelihood of achieving the objective. The objective is task-defined (find buggy code, find best refactor target, etc.); ant is task-agnostic infrastructure.
50
+
51
+ Workflow:
52
+
53
+ ### 3.1 Initialize path
54
+ - `path = [assignment.start_node]`
55
+ - `path_decisions = []`
56
+ - `visited = {start_node}`
57
+ - `current = start_node`
58
+
59
+ ### 3.2 Per-step exploration loop (until len(path) reaches max_path_length OR ant decides to stop early)
60
+
61
+ For each step:
62
+
63
+ 1. **Compute candidate neighbors**: all nodes in task_space NOT in `visited`
64
+ 2. **Build choice weights**:
65
+ - For each candidate c: `weight = edge_preferences.get("<current>::<c>", baseline) * heuristic(c)`
66
+ - `heuristic(c)` = ant's own evidence-based judgment (1.0 if no opinion)
67
+ 3. **Investigate top candidates** using available tools:
68
+ - Tool selection: Read, Grep, Glob for code-based task spaces; or CLI delegate `--mode analysis` for richer analysis
69
+ - Gather evidence about each top candidate before committing
70
+ 4. **Choose next node**: weighted-random OR argmax (when high confidence)
71
+ 5. **Record decision**:
72
+ ```json
73
+ {
74
+ "from": "<current>",
75
+ "to": "<chosen>",
76
+ "rationale": "<one-line>",
77
+ "guided_by": "pheromone | heuristic | evidence",
78
+ "pheromone_weight": <edge_preferences value>,
79
+ "deviation_from_hint": <bool — true if chosen != argmax(edge_preferences)>
80
+ }
81
+ ```
82
+ 6. **Append to path**, update `visited`, `current = chosen`
83
+ 7. **Early-stop check**: if evidence shows objective achieved OR no productive next step exists -> stop
84
+
85
+ ### 3.3 Self-evaluate
86
+
87
+ After path is built:
88
+
89
+ 1. **self_score** (0..1): how well does this path satisfy the objective?
90
+ - Use `ant_prompt.evidence_requirements` as rubric
91
+ - Be conservative — penalize for missing evidence, weak rationale
92
+ 2. **self_confidence** (0..1): how sure of the self_score?
93
+ - Low confidence if evidence is sparse or contradictory
94
+ 3. **candidate_solution**: extract the actual deliverable along the path
95
+ - `type` ∈ {string, object, file_ref}
96
+ - `summary` — one-line
97
+ - `content` — actual artifact OR a path to a file written by the ant
98
+
99
+ ### 3.4 Compose artifact JSON
100
+
101
+ Build the full artifact matching specs/ant-output-schema.md. All required fields populated.
102
+
103
+ ## Phase 4: Verify + Publish
104
+
105
+ ### Behavioral Traits
106
+
107
+ #### Accuracy — outputs must be verifiable
108
+ - Every node in `path` MUST exist in task-space.json
109
+ - Every `path_decisions[i].from` MUST equal `path[i]` and `to` MUST equal `path[i+1]`
110
+ - Evidence references (e.g., `file:line`) MUST be valid (Read to confirm if file_ref)
111
+
112
+ #### Feedback Contract
113
+ | Field | Required | Content |
114
+ |-------|----------|---------|
115
+ | files_produced | If ant wrote any | `[artifact_path]` at minimum |
116
+ | artifacts_written | Always | `{run_dir}/outputs/ant-<iter>-<id>.json` |
117
+ | verification_method | Always | "schema_validated + node_validity_checked" |
118
+
119
+ #### Quality Gate
120
+ - Schema validation pass = REQUIRED before reporting completed
121
+ - Fails -> retry Phase 3 once (max 1 retry to bound cost)
122
+ - Still fails -> report `partial_completion` with `validation_errors` in state data
123
+
124
+ ### Verification Steps
125
+
126
+ 1. **Schema validation**:
127
+ - Parse the JSON via Read
128
+ - Confirm all required fields from specs/ant-output-schema.md
129
+ - Confirm numeric ranges (self_score, self_confidence ∈ [0,1])
130
+ - Confirm `len(path_decisions) == len(path) - 1`
131
+ 2. **Node validity**: every node in path ∈ task_space.json#nodes
132
+ 3. **Evidence check**: at least 1 evidence anchor present; if file_ref, Read to confirm existence
133
+ 4. **Write artifact**: `Write({run_dir}/outputs/ant-<iter>-<id>.json, <json_string>)`
134
+ 5. **Re-read to confirm write**: Read it back, parse, sanity check
135
+
136
+ ### State Update
137
+
138
+ Report the completed assignment with evolve team report after re-reading the artifact. See the coordination guide for the exact flags.
139
+
140
+ ## Error Handling
141
+
142
+ | Scenario | Resolution |
143
+ |----------|------------|
144
+ | Assignment JSON malformed | Report error to coordinator via send_message, STOP |
145
+ | start_node not in task_space | Report error (config mismatch), STOP |
146
+ | No valid neighbors at step 1 | Build single-node path, self_score = 0, report |
147
+ | Schema validation fails twice | Report `partial_completion` with errors list |
148
+ | Evidence requirements unsatisfiable | Lower self_score; document blocker in artifact `notes` field |
149
+ | Tool calls fail (Read/Grep) | Note in artifact `notes`; reduce self_confidence; proceed with available info |
@@ -0,0 +1,154 @@
1
+
2
+ > **Agent timeout**: `spawn_agent` 异步执行且无内置超时 — 除明确短任务外一律 `spawn_agent` 后立即 `wait_agent({ timeout_ms: 3600000 })`(上限 1 小时)阻塞等待,绝不依赖 30000 默认值;`timed_out: true` 且 Agent 未完成时再次 `wait_agent` 续等,不丢弃。批量场景使用 `spawn_agents_on_csv({ max_runtime_seconds: 3600, ... })`。
3
+ # Command: converge
4
+
5
+ ## Workflow
6
+
7
+ ### Step 1: Call aco.py report
8
+
9
+ ```
10
+ Bash: python <skill_root>/scripts/aco.py --session {run_dir}/work/team --run-dir <run_dir> report
11
+ ```
12
+
13
+ Parse stdout JSON. Expected:
14
+ ```json
15
+ {
16
+ "_meta": {"kind": "swarm-report", "schema": "swarm-report/1.0", "role": "attachment"},
17
+ "status": "ok",
18
+ "best": { ant_id, iteration, path, score, candidate_solution, evidence, ... },
19
+ "top_k": [<top 5 trails>],
20
+ "convergence_curve": [{iteration, entropy, tau_max, tau_mean}, ...],
21
+ "final_pheromone_stats": {...},
22
+ "iterations_completed": <int>
23
+ }
24
+ ```
25
+
26
+ Save the complete stdout JSON, including `_meta`, to `{run_dir}/outputs/swarm-report.json` (raw data for analyst). Do not wrap, strip, or replace the metadata.
27
+
28
+ ### Step 2: Spawn analyst worker
29
+
30
+ ```
31
+ spawn_agent({
32
+ subagent_type: "team-worker",
33
+ description: "Spawn analyst for swarm synthesis",
34
+ team_name: "swarm",
35
+ name: "analyst",
36
+ run_in_background: true,
37
+ prompt: `## Role Assignment
38
+ role: analyst
39
+ role_spec: <skill_root>/roles/analyst/role.md
40
+ session: <session_path>
41
+ session_id: <run-id>
42
+ run_dir: <exact run_dir from the birth packet or team-session.json.run.run_dir>
43
+ team_name: swarm
44
+ requirement: synthesize swarm results into human-readable best-solution.md
45
+ inner_loop: false
46
+
47
+ ## Context
48
+ Report data: {run_dir}/outputs/swarm-report.json
49
+ Best solution: {run_dir}/work/team/best.json
50
+ All trails: {run_dir}/work/team/trails/*.jsonl
51
+ Original objective: <config.ant_prompt.objective>
52
+
53
+ ## Progress Milestones
54
+ Record synthesis and verification in the Run summary.
55
+ })
56
+ ```
57
+
58
+ STOP. Resume on analyst callback.
59
+
60
+ ### Step 3: On analyst callback
61
+
62
+ Give `{run_dir}/outputs/best-solution.md` the `kind: swarm-best-solution`, `schema: swarm-best-solution/1.0`, and `role: primary` YAML frontmatter. Seal with `evolve run complete` and fix any output contract errors it reports.
63
+
64
+ If missing -> request_user_input (skip synthesis / retry analyst).
65
+
66
+ ### Step 3.5: Run lifecycle completion
67
+
68
+ ```
69
+ +- Run lifecycle completion:
70
+ | - Read run_id from team-session.json.run.run_id
71
+ | - Write {run_dir}/report.md with frontmatter per run-mode-lite.md Complete §1 (verdict/summary/constraints/decisions/concerns; constraints/decisions = {text,status} objects, id auto-derived)
72
+ | - Before requesting completion, merge-write team status="completed", converged_at=<iso8601>, convergence_reason=<triggered_by>, preserving run; log the final state_update now. If completion is blocked, leave it unsealed and merge-write status="paused" with the blocker.
73
+ | - If self-started, use the complete fenced `evolve run complete ... --advance` (and `evolve session complete` when the chain is terminal) from run-mode-lite.md; if dispatched, return to the claim-holding orchestrator
74
+ | - If complete fails: fix the blocking gate and retry once; still failing -> do NOT archive/clean - keep the team active (status=paused) and report the blocking gate
75
+ ```
76
+
77
+ ### Step 4: Build completion summary
78
+
79
+ ```
80
+ [coordinator] ============================================
81
+ [coordinator] SWARM CONVERGED
82
+ [coordinator]
83
+ [coordinator] Iterations: <iterations_completed> / <max_iterations>
84
+ [coordinator] Trigger: <triggered_by[0]>
85
+ [coordinator] Total ants spawned: <iterations * n_ants>
86
+ [coordinator]
87
+ [coordinator] Best Solution:
88
+ [coordinator] ant_id: <best.ant_id>
89
+ [coordinator] iteration: <best.iteration>
90
+ [coordinator] path: <best.path joined with " -> ">
91
+ [coordinator] verified_score: <best.score>
92
+ [coordinator] summary: <best.candidate_solution.summary>
93
+ [coordinator]
94
+ [coordinator] Convergence curve (entropy):
95
+ [coordinator] iter 1: <e1> iter 2: <e2> iter 3: <e3> ...
96
+ [coordinator]
97
+ [coordinator] Deliverables:
98
+ [coordinator] - {run_dir}/outputs/best-solution.md (analyst synthesis)
99
+ [coordinator] - {run_dir}/outputs/swarm-report.json (raw data)
100
+ [coordinator] - best.json (canonical best)
101
+ [coordinator] - trails/*.jsonl (full exploration log)
102
+ [coordinator]
103
+ [coordinator] Session: <session_path>
104
+ [coordinator] ============================================
105
+ ```
106
+
107
+ ### Step 5: Preserve completed state
108
+
109
+ The final team state and state_update were written before completion in Step 3.5. After sealing, inspect the frozen state read-only; do not update team-session.json or append Run-local logs.
110
+
111
+ ### Step 6: Completion action (interactive)
112
+
113
+ ```
114
+ request_user_input({
115
+ questions: [{
116
+ question: "Swarm pipeline complete. What would you like to do?",
117
+ header: "Completion",
118
+ multiSelect: false,
119
+ options: [
120
+ { label: "Archive & Clean (Recommended)", description: "Archive session, delete team" },
121
+ { label: "Keep Active", description: "Keep team available for inspection; follow-up work requires a fresh Run" },
122
+ { label: "Export Best Solution", description: "Copy best-solution.md to target path" },
123
+ { label: "Run Another Round", description: "Start a fresh Run for K more iterations, optionally seeded from frozen pheromone" }
124
+ ]
125
+ }]
126
+ })
127
+ ```
128
+
129
+ ### Action Handlers
130
+
131
+ | Choice | Steps |
132
+ |--------|-------|
133
+ | Archive & Clean | TeamDelete; output final summary; preserve the sealed Run directory and evidence |
134
+ | Keep Active | Keep the live team for read-only inspection; output fresh-Run follow-up instructions; do not change completed team state |
135
+ | Export Best Solution | request_user_input(target path); copy best-solution.md + best.json; then Archive & Clean |
136
+ | Run Another Round | request_user_input(additional K); follow the fresh-Run handoff below; never reset or iterate in the completed Run |
137
+
138
+ ### Fresh-Run handoff for another round
139
+
140
+ - Completion above seals the old Run. Never write its `work/team`, `outputs/`, report, counters, or pheromone again, including changing its completed team state to paused. Keep Active preserves the live team for inspection only; it does not reopen the Run.
141
+ - For an orchestrator-dispatched Run, return the requested K and exact old locator to the completion owner and wait for a new birth packet. Do not create a competing Run or continue under the old locator.
142
+ - For a self-started Run, use Run Mode Lite Create with fresh receipt-derived authority. If the prior Session is terminal/completed, open a new Session; otherwise the owner inserts and dispatches a new chain step. Do not reuse the completed step or Run ID.
143
+ - Resolve a distinct new `session_id` / `run_id` / `run_dir` before any follow-up write. Initialize a new `work/team/team-session.json` via init-swarm.md with the new public locator and reset round-local counters there only.
144
+ - If retaining pheromone is requested, read the old frozen config/task-space/pheromone as seed inputs and copy only compatible inputs into the new Run's coordination directory after initialization; record their exact source locator. Set the new iteration cap to K. Do not copy old outputs, trails, scores, worker liveness, or completion state as new-round evidence. Spawn new ants through Phase 3 iterate.md only after the new locator and seed/config are verified.
145
+ - If allocation or seed validation fails, keep the old Run immutable and report the blocker; never fall back to iterating there.
146
+
147
+ ## Failure Cases
148
+
149
+ | Failure | Action |
150
+ |---------|--------|
151
+ | `aco.py report` fails | Stop before analyst dispatch; keep Run unsealed and team paused, record stderr, repair the script/state, then retry `report`. Do not substitute an untyped manual report for required `outputs/swarm-report.json`. |
152
+ | Analyst worker crashes | Retry once. If synthesizing a minimal best-solution.md from best.json is explicitly chosen, include the required `swarm-best-solution/1.0` primary YAML frontmatter for completion. |
153
+ | best.json missing | Pipeline ran but no successful ant - report failure, keep session for inspection |
154
+ | Run Another Round chosen but max_iterations already at limit | request_user_input to raise the cap before continuing |
@@ -0,0 +1,134 @@
1
+ # Command: init-swarm
2
+
3
+ ## Inputs
4
+
5
+ - `swarm-config.json` from Phase 1 (in memory until the exact Run directory is resolved)
6
+ - canonical `session_id` from the birth packet or self-start receipt (not a separate `TS-*` locator)
7
+ - `skill_root` = directory containing the active `team-swarm/SKILL.md` (do not assume project cwd or a particular mirror)
8
+
9
+ ## Workflow
10
+
11
+ ### Step 0: Resolve Run authority
12
+
13
+ Perform the coordinator role's **Run Lifecycle Integration** before creating `work/team` or writing config. Obtain the exact `session_id`, `run_id`, and `run_dir` from the birth packet or receipt; do not infer a Run path from a local sidecar.
14
+
15
+ ### Step 1: Resolve paths
16
+
17
+ ```
18
+ run_dir = <exact path returned by Run birth packet or team-session.json.run.run_dir>
19
+ skill_root = <resolved directory containing this SKILL.md>
20
+ session_path = Path(run_dir) / "work" / "team"
21
+ # Do not prepend pwd to run_dir: it may already be absolute.
22
+ ```
23
+
24
+ ### Step 2: Create session directory tree
25
+
26
+ ```
27
+ mkdir -p <session_path>/{pheromone/history,trails,scores,artifacts,wisdom,.msg}
28
+ ```
29
+
30
+ ### Step 3: Write swarm-config.json
31
+
32
+ Write the Phase 1-generated config to `<session_path>/swarm-config.json`.
33
+
34
+ Validate before write:
35
+ - `task_space.nodes` OR `task_space.auto_discover_from` present
36
+ - `swarm.n_ants` >= 2 (single-ant defeats swarm purpose)
37
+ - `convergence.max_iterations` >= 1
38
+
39
+ ### Step 4: Create team
40
+
41
+ ```
42
+ TeamCreate({ name: "swarm" })
43
+ ```
44
+
45
+ ### Step 5: Write role-binding.json
46
+
47
+ ```json
48
+ {
49
+ "ant": "<skill_root>/roles/ant/role.md",
50
+ "scorer": "<skill_root>/roles/scorer/role.md",
51
+ "analyst": "<skill_root>/roles/analyst/role.md"
52
+ }
53
+ ```
54
+
55
+ Saved at `<session_path>/role-binding.json` — workers resolve their role.md from this file.
56
+
57
+ ### Step 6: Call aco.py init
58
+
59
+ ```
60
+ Bash: python <skill_root>/scripts/aco.py --session <session_path> --run-dir <run_dir> init
61
+ ```
62
+
63
+ Parse stdout JSON. On `status: "error"`:
64
+ - exit_code 2 -> config validation error -> request_user_input to fix
65
+ - exit_code 1 -> runtime error -> log to issues.md + retry once
66
+
67
+ On success, capture:
68
+ - `n_nodes` — search space size
69
+ - `n_edges` — initial edge count
70
+ - `pheromone_path` — confirm written
71
+
72
+ ### Step 7: Initialize team-session.json
73
+
74
+ ```json
75
+ {
76
+ "session_id": "<run-id>",
77
+ "task_description": "<user task>",
78
+ "status": "active",
79
+ "team_name": "swarm",
80
+ "skill": "team-swarm",
81
+ "iteration": 0,
82
+ "max_iterations": <config.convergence.max_iterations>,
83
+ "n_ants_per_iter": <config.swarm.n_ants>,
84
+ "config_path": "swarm-config.json",
85
+ "pheromone_path": "pheromone/current.json",
86
+ "roles": ["coordinator", "ant", "scorer", "analyst"],
87
+ "scoring_mode": "<config.scoring.mode>",
88
+ "active_workers": [],
89
+ "completed_iterations": [],
90
+ "completion_action": "interactive",
91
+ "created_at": "<iso8601>",
92
+ "updated_at": "<iso8601>",
93
+ "run": { "session_id": "<canonical-session-id>", "run_id": "<run-id>", "run_dir": "<run-dir>" }
94
+ }
95
+ ```
96
+
97
+ ### Step 8: Initialize wisdom files
98
+
99
+ Create empty wisdom files with headers:
100
+ - `wisdom/learnings.md` — cross-iteration insights
101
+ - `wisdom/decisions.md` — config refinements made mid-pipeline
102
+ - `wisdom/issues.md` — errors and hallucinations log
103
+
104
+ ### Step 9: Log initialization state_update
105
+
106
+ Save the phase summary in team-session.json.
107
+
108
+ ### Step 10: Proceed to Phase 3 (iterate.md)
109
+
110
+ Do NOT spawn any workers in this command. First spawn happens in iterate.md step 4.
111
+
112
+ ## Success Criteria
113
+
114
+ - `{run_dir}/work/team/swarm-config.json` exists and validates
115
+ - `{run_dir}/work/team/pheromone/current.json` exists with `iteration: 0`
116
+ - `{run_dir}/work/team/task-space.json` exists with `n_nodes > 0`
117
+ - team-session.json initialized with `iteration: 0`
118
+
119
+ ## Failure Recovery
120
+
121
+ | Failure | Action |
122
+ |---------|--------|
123
+ | Config invalid | request_user_input, regenerate, retry |
124
+ | `aco.py init` runtime error | Log to issues.md, retry once, then request_user_input (abort/refine) |
125
+ | Directory creation fails | Check disk space / permissions, retry |
126
+ | TeamCreate fails | Resolve the exact `run_id` / `run_dir`, inspect its one `work/team/team-session.json`, and offer resume only if lifecycle reconciliation verifies a matching active/paused `team-swarm` session; otherwise fail closed |
127
+
128
+ ### TeamCreate Conflict Recovery Contract
129
+
130
+ 1. Start from the birth-packet `run_id` / `run_dir`. Do not scan sibling Runs and do not treat an arbitrary existing team name as a resumable match.
131
+ 2. Inspect the exact team session and reconcile canonical Run status, broker-backed live agents, non-terminal tasks, and ordered activity timestamps through the runtime lifecycle adapter.
132
+ 3. Offer **Resume** only when the exact candidate is a verified matching `team-swarm` session with lifecycle `active` or `paused`. If health is `stale_candidate`, show the evidence and require an explicit operator choice; never convert stale health into cleanup eligibility.
133
+ 4. If exact locator evidence is absent, mismatched, `unknown`, or `inconsistent`, fail closed. Locator-less legacy discovery must use ranked candidates plus request_user_input and must never choose array index 0 implicitly.
134
+ 5. Do not offer a generic "clean or resume" action. `abandoned` requires a separate explicit audited transition after all liveness/activity checks, and cleanup requires a second confirmation that removes only team coordination state, never Run authority or outputs.