agent-threader 2.0.5

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 (172) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +126 -0
  3. package/compiled/claude/agent-threader/SKILL.md +361 -0
  4. package/compiled/codex/agent-threader/SKILL.md +361 -0
  5. package/compiled/cursor/rules/agent-threader.mdc +367 -0
  6. package/compiled/cursor/skills/agent-threader/SKILL.md +361 -0
  7. package/compiled/opencode/agent-threader.md +361 -0
  8. package/compiled/windsurf/rules/agent-threader.md +361 -0
  9. package/compiled/windsurf/skills/agent-threader/SKILL.md +361 -0
  10. package/dist/cli/commands/doctor.d.ts +6 -0
  11. package/dist/cli/commands/doctor.d.ts.map +1 -0
  12. package/dist/cli/commands/doctor.js +7 -0
  13. package/dist/cli/commands/doctor.js.map +1 -0
  14. package/dist/cli/commands/explain-error.d.ts +12 -0
  15. package/dist/cli/commands/explain-error.d.ts.map +1 -0
  16. package/dist/cli/commands/explain-error.js +23 -0
  17. package/dist/cli/commands/explain-error.js.map +1 -0
  18. package/dist/cli/commands/init-state.d.ts +6 -0
  19. package/dist/cli/commands/init-state.d.ts.map +1 -0
  20. package/dist/cli/commands/init-state.js +10 -0
  21. package/dist/cli/commands/init-state.js.map +1 -0
  22. package/dist/cli/commands/logs.d.ts +6 -0
  23. package/dist/cli/commands/logs.d.ts.map +1 -0
  24. package/dist/cli/commands/logs.js +9 -0
  25. package/dist/cli/commands/logs.js.map +1 -0
  26. package/dist/cli/commands/parse-heal.d.ts +6 -0
  27. package/dist/cli/commands/parse-heal.d.ts.map +1 -0
  28. package/dist/cli/commands/parse-heal.js +5 -0
  29. package/dist/cli/commands/parse-heal.js.map +1 -0
  30. package/dist/cli/commands/parse-result.d.ts +6 -0
  31. package/dist/cli/commands/parse-result.d.ts.map +1 -0
  32. package/dist/cli/commands/parse-result.js +5 -0
  33. package/dist/cli/commands/parse-result.js.map +1 -0
  34. package/dist/cli/commands/status.d.ts +6 -0
  35. package/dist/cli/commands/status.d.ts.map +1 -0
  36. package/dist/cli/commands/status.js +5 -0
  37. package/dist/cli/commands/status.js.map +1 -0
  38. package/dist/cli/commands/validate-manifest.d.ts +6 -0
  39. package/dist/cli/commands/validate-manifest.d.ts.map +1 -0
  40. package/dist/cli/commands/validate-manifest.js +5 -0
  41. package/dist/cli/commands/validate-manifest.js.map +1 -0
  42. package/dist/cli/index.d.ts +6 -0
  43. package/dist/cli/index.d.ts.map +1 -0
  44. package/dist/cli/index.js +360 -0
  45. package/dist/cli/index.js.map +1 -0
  46. package/dist/cli/output-formatter.d.ts +6 -0
  47. package/dist/cli/output-formatter.d.ts.map +1 -0
  48. package/dist/cli/output-formatter.js +19 -0
  49. package/dist/cli/output-formatter.js.map +1 -0
  50. package/dist/index.d.ts +3 -0
  51. package/dist/index.d.ts.map +1 -0
  52. package/dist/index.js +5 -0
  53. package/dist/index.js.map +1 -0
  54. package/dist/lib/adapters/types.d.ts +40 -0
  55. package/dist/lib/adapters/types.d.ts.map +1 -0
  56. package/dist/lib/adapters/types.js +3 -0
  57. package/dist/lib/adapters/types.js.map +1 -0
  58. package/dist/lib/contracts/schema-validator.d.ts +15 -0
  59. package/dist/lib/contracts/schema-validator.d.ts.map +1 -0
  60. package/dist/lib/contracts/schema-validator.js +63 -0
  61. package/dist/lib/contracts/schema-validator.js.map +1 -0
  62. package/dist/lib/contracts/types.d.ts +91 -0
  63. package/dist/lib/contracts/types.d.ts.map +1 -0
  64. package/dist/lib/contracts/types.js +15 -0
  65. package/dist/lib/contracts/types.js.map +1 -0
  66. package/dist/lib/contracts/validate-manifest.d.ts +16 -0
  67. package/dist/lib/contracts/validate-manifest.d.ts.map +1 -0
  68. package/dist/lib/contracts/validate-manifest.js +123 -0
  69. package/dist/lib/contracts/validate-manifest.js.map +1 -0
  70. package/dist/lib/diagnostics/doctor.d.ts +17 -0
  71. package/dist/lib/diagnostics/doctor.d.ts.map +1 -0
  72. package/dist/lib/diagnostics/doctor.js +131 -0
  73. package/dist/lib/diagnostics/doctor.js.map +1 -0
  74. package/dist/lib/errors/explain-error.d.ts +10 -0
  75. package/dist/lib/errors/explain-error.d.ts.map +1 -0
  76. package/dist/lib/errors/explain-error.js +73 -0
  77. package/dist/lib/errors/explain-error.js.map +1 -0
  78. package/dist/lib/errors/types.d.ts +16 -0
  79. package/dist/lib/errors/types.d.ts.map +1 -0
  80. package/dist/lib/errors/types.js +50 -0
  81. package/dist/lib/errors/types.js.map +1 -0
  82. package/dist/lib/index.d.ts +29 -0
  83. package/dist/lib/index.d.ts.map +1 -0
  84. package/dist/lib/index.js +25 -0
  85. package/dist/lib/index.js.map +1 -0
  86. package/dist/lib/orchestrator/batch-strategy.d.ts +9 -0
  87. package/dist/lib/orchestrator/batch-strategy.d.ts.map +1 -0
  88. package/dist/lib/orchestrator/batch-strategy.js +34 -0
  89. package/dist/lib/orchestrator/batch-strategy.js.map +1 -0
  90. package/dist/lib/orchestrator/healing-policy.d.ts +47 -0
  91. package/dist/lib/orchestrator/healing-policy.d.ts.map +1 -0
  92. package/dist/lib/orchestrator/healing-policy.js +104 -0
  93. package/dist/lib/orchestrator/healing-policy.js.map +1 -0
  94. package/dist/lib/orchestrator/index.d.ts +11 -0
  95. package/dist/lib/orchestrator/index.d.ts.map +1 -0
  96. package/dist/lib/orchestrator/index.js +11 -0
  97. package/dist/lib/orchestrator/index.js.map +1 -0
  98. package/dist/lib/orchestrator/patch-validation.d.ts +9 -0
  99. package/dist/lib/orchestrator/patch-validation.d.ts.map +1 -0
  100. package/dist/lib/orchestrator/patch-validation.js +58 -0
  101. package/dist/lib/orchestrator/patch-validation.js.map +1 -0
  102. package/dist/lib/orchestrator/scheduling.d.ts +12 -0
  103. package/dist/lib/orchestrator/scheduling.d.ts.map +1 -0
  104. package/dist/lib/orchestrator/scheduling.js +74 -0
  105. package/dist/lib/orchestrator/scheduling.js.map +1 -0
  106. package/dist/lib/orchestrator/write-safety.d.ts +14 -0
  107. package/dist/lib/orchestrator/write-safety.d.ts.map +1 -0
  108. package/dist/lib/orchestrator/write-safety.js +44 -0
  109. package/dist/lib/orchestrator/write-safety.js.map +1 -0
  110. package/dist/lib/parser/parse-heal.d.ts +12 -0
  111. package/dist/lib/parser/parse-heal.d.ts.map +1 -0
  112. package/dist/lib/parser/parse-heal.js +9 -0
  113. package/dist/lib/parser/parse-heal.js.map +1 -0
  114. package/dist/lib/parser/parse-result.d.ts +12 -0
  115. package/dist/lib/parser/parse-result.d.ts.map +1 -0
  116. package/dist/lib/parser/parse-result.js +9 -0
  117. package/dist/lib/parser/parse-result.js.map +1 -0
  118. package/dist/lib/parser/parser.d.ts +8 -0
  119. package/dist/lib/parser/parser.d.ts.map +1 -0
  120. package/dist/lib/parser/parser.js +167 -0
  121. package/dist/lib/parser/parser.js.map +1 -0
  122. package/dist/lib/state/init-state.d.ts +15 -0
  123. package/dist/lib/state/init-state.d.ts.map +1 -0
  124. package/dist/lib/state/init-state.js +50 -0
  125. package/dist/lib/state/init-state.js.map +1 -0
  126. package/dist/lib/state/logs.d.ts +19 -0
  127. package/dist/lib/state/logs.d.ts.map +1 -0
  128. package/dist/lib/state/logs.js +25 -0
  129. package/dist/lib/state/logs.js.map +1 -0
  130. package/dist/lib/state/state.d.ts +7 -0
  131. package/dist/lib/state/state.d.ts.map +1 -0
  132. package/dist/lib/state/state.js +72 -0
  133. package/dist/lib/state/state.js.map +1 -0
  134. package/dist/lib/state/status.d.ts +22 -0
  135. package/dist/lib/state/status.d.ts.map +1 -0
  136. package/dist/lib/state/status.js +34 -0
  137. package/dist/lib/state/status.js.map +1 -0
  138. package/dist/lib/state/types.d.ts +55 -0
  139. package/dist/lib/state/types.d.ts.map +1 -0
  140. package/dist/lib/state/types.js +14 -0
  141. package/dist/lib/state/types.js.map +1 -0
  142. package/install-local.sh +239 -0
  143. package/install.sh +36 -0
  144. package/package.json +55 -0
  145. package/site/CNAME +1 -0
  146. package/site/index.html +141 -0
  147. package/site/install.sh +36 -0
  148. package/site/style.css +319 -0
  149. package/skill/SKILL.md +127 -0
  150. package/skill/SPEC.md +1189 -0
  151. package/skill/build/compile.mjs +237 -0
  152. package/skill/build/manifest.json +21 -0
  153. package/skill/fragments/common/model-selection.md +11 -0
  154. package/skill/fragments/common/portability-rules.md +16 -0
  155. package/skill/fragments/common/workflow.md +12 -0
  156. package/skill/fragments/domain/adapter-model.md +42 -0
  157. package/skill/fragments/domain/architecture-overview.md +36 -0
  158. package/skill/fragments/domain/contracts.md +31 -0
  159. package/skill/fragments/domain/pbh-healing.md +47 -0
  160. package/skill/fragments/domain/state-resume.md +34 -0
  161. package/skill/fragments/domain/verification-safety.md +33 -0
  162. package/skill/fragments/meta/schemas-reference.md +13 -0
  163. package/skill/fragments/meta/templates-reference.md +11 -0
  164. package/skill/schemas/heal_decision.v2.json +100 -0
  165. package/skill/schemas/manifest.v2.json +91 -0
  166. package/skill/schemas/state.v2.json +183 -0
  167. package/skill/schemas/task_result.v2.json +104 -0
  168. package/skill/schemas/verify_profile.v2.json +61 -0
  169. package/skill/skills/agent-threader/agent-threader.md +85 -0
  170. package/skill/templates/orchestrator.ts +38 -0
  171. package/skill/templates/parser.ts +384 -0
  172. package/skill/templates/types.ts +282 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Barrett Sonntag
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,126 @@
1
+ # AgentThreader
2
+
3
+ Portable skill and companion CLI for manifest-driven agentic CLI orchestration with structured contracts, resumable state, orchestrator-owned verification, and bounded self-healing.
4
+
5
+ ## Project Structure
6
+
7
+ ```
8
+ agent-threader/
9
+ src/
10
+ lib/ # Reusable library (no CLI concerns)
11
+ contracts/ # Contract types, schema validators, manifest validation
12
+ parser/ # Sentinel extraction, JSON repair, contract parsing
13
+ state/ # State load/write/init, status queries, log queries
14
+ orchestrator/ # Scheduling, batch strategy, healing policy, write safety
15
+ adapters/ # Adapter interfaces and shared utilities
16
+ errors/ # Typed error hierarchy
17
+ index.ts # Library barrel export
18
+ cli/ # Thin CLI wrappers (presentation only)
19
+ commands/ # One file per CLI command
20
+ index.ts # Commander.js entry point
21
+ output-formatter.ts # JSON, table, key-value formatters
22
+ index.ts # Package entry re-exporting lib + OutputFormatter
23
+ skill/
24
+ SKILL.md # Skill entrypoint
25
+ SPEC.md # Normative v2 architecture specification
26
+ schemas/ # JSON schemas for all contracts
27
+ templates/ # TypeScript scaffolding (types, parser, orchestrator)
28
+ build/
29
+ manifest.json # Skill registry and fragment declarations
30
+ compile.mjs # Fragment-resolving compiler (7 IDE targets)
31
+ fragments/
32
+ common/ # Shared rules (workflow, model selection, portability)
33
+ domain/ # Deep domain knowledge (architecture, healing, contracts)
34
+ meta/ # Skill system metadata (schemas ref, templates ref)
35
+ skills/
36
+ agent-threader/
37
+ agent-threader.md # Composed skill source with {{include:...}}
38
+ compiled/ # Machine-generated IDE-specific outputs
39
+ platforms/ # Thin translation layers for Codex, Cursor, Claude, Windsurf
40
+ site/ # GitHub Pages site and hosted bootstrap installer
41
+ install.sh # Hosted bootstrap installer for curl-based setup
42
+ install-local.sh # Full local installer for clone-based development
43
+ ```
44
+
45
+ ## Core Design
46
+
47
+ The architecture separates concerns cleanly:
48
+
49
+ - the manifest declares work
50
+ - the orchestrator owns scheduling, verification, checkpointing, and healing
51
+ - adapters invoke specific CLIs through a uniform interface
52
+ - workers and healers emit fenced JSON contracts
53
+ - parsers and schemas validate output before state changes
54
+
55
+ ## Key Contracts
56
+
57
+ - `manifest.v2`
58
+ - `verify_profile.v2`
59
+ - `task_result.v2`
60
+ - `heal_decision.v2`
61
+ - `state.v2`
62
+
63
+ See [SPEC.md](./skill/SPEC.md) for the full contract and runtime rules.
64
+
65
+ ## Setup
66
+
67
+ ### Remote bootstrap installer
68
+
69
+ ```bash
70
+ bash <(curl -fsSL https://agentthreader.com/install.sh) --all
71
+ bash <(curl -fsSL https://agentthreader.com/install.sh) --cursor
72
+ npx --yes agent-threader@latest --help
73
+ ```
74
+
75
+ The hosted bootstrap script installs the published `agent-threader` package globally and then delegates to the packaged `install-local.sh` to copy the compiled skills into your selected tools.
76
+
77
+ Use `npx` when you want one-off CLI usage without global install:
78
+
79
+ ```bash
80
+ npx --yes agent-threader@latest validate-manifest ./manifest.json --json
81
+ ```
82
+
83
+ ### Local clone-based setup
84
+
85
+ ```bash
86
+ bash install-local.sh # Auto-detect tools and install
87
+ bash install-local.sh --all # Install for all five tools
88
+ bash install-local.sh --cursor # Install for Cursor only
89
+ ```
90
+
91
+ ## Development
92
+
93
+ ```bash
94
+ npm install # Install dependencies
95
+ npm run build # Compile TypeScript CLI
96
+ npm run compile # Compile skills to all IDE targets
97
+ npm run compile:validate # Validate manifest vs source includes
98
+ npm run compile:watch # Recompile on change
99
+ bash install-local.sh # Build, compile, link CLI, and install skills locally
100
+ ```
101
+
102
+ ## CLI Commands
103
+
104
+ ```bash
105
+ agent-threader validate-manifest <path> # Alias: validate
106
+ agent-threader init-state <manifest-path> # Alias: init
107
+ agent-threader parse-result <log-path> # Alias: parse
108
+ agent-threader parse-heal <log-path> # Alias: heal
109
+ agent-threader status [state-path] # Alias: st
110
+ agent-threader logs [state-path] # Alias: history
111
+ agent-threader doctor # Alias: diag
112
+ agent-threader explain [code] # Alias: why
113
+ ```
114
+
115
+ All commands support `--json` for machine-readable output.
116
+
117
+ ## Release Automation
118
+
119
+ The release workflow in `.github/workflows/release.yml` expects:
120
+
121
+ - `AGENT_TOKEN` - GitHub token with permission to push release commits and tags
122
+ - `AGENT_NPM_TOKEN` - npm automation token used as `NODE_AUTH_TOKEN` for publish
123
+
124
+ ## License
125
+
126
+ MIT. See [LICENSE](./LICENSE).
@@ -0,0 +1,361 @@
1
+ <!-- managed_by: agent-threader -->
2
+ ---
3
+ name: agent-threader
4
+ version: "2.0"
5
+ description: "AgentThreader -- build or review manifest-driven agentic CLI orchestration with structured JSON contracts, schema-validated parsing, resumable state, dependency-aware scheduling, bounded self-healing, and orchestrator-owned verification."
6
+ ---
7
+
8
+ # AgentThreader
9
+
10
+ ## When To Use This Skill
11
+
12
+ Use this skill when manual chat execution no longer scales and the right answer is a repeatable runner around an agentic CLI.
13
+
14
+ Matching requests include:
15
+
16
+ - batch prompt runners over tasks, manifests, components, stories, or tickets
17
+ - looping an agentic CLI (`agent`, `opencode`, `claude`) across many items
18
+ - resumable or checkpointed agent loops with per-task logs
19
+ - self-healing outer loops that diagnose failures and patch prompts
20
+ - overnight or unattended batch runs with verification gates
21
+ - stage-based workflows where items pass through multiple prompt phases
22
+ - log triage followed by targeted recheck runs
23
+
24
+ ## Architecture
25
+
26
+ ### Architecture Overview
27
+
28
+ The v2 system has five moving parts:
29
+
30
+ 1. **Manifest** -- declares work items, dependencies, timeouts, and verification profiles.
31
+ 2. **Orchestrator** -- owns scheduling, parsing, verification, checkpointing, healing, and retry policy. The orchestrator is the single source of truth for task status.
32
+ 3. **Adapters** -- CLI-specific execution layers (`agent`, `opencode`, `claude`) that the orchestrator calls through a uniform `CliAdapter` interface.
33
+ 4. **Worker** -- the model invocation that performs task work and emits a `task_result.v2` JSON contract fenced by `<<<TASK_RESULT_V2>>>` sentinels.
34
+ 5. **Healer** -- the model invocation that diagnoses fixable failures and emits a `heal_decision.v2` JSON contract fenced by `<<<HEAL_DECISION_V2>>>` sentinels.
35
+
36
+ ### Control Flow
37
+
38
+ ```text
39
+ Manifest
40
+ -> Orchestrator
41
+ -> Adapter -> Worker
42
+ -> Parser and Schema Validator
43
+ -> Verification Gates
44
+ -> State Checkpoint
45
+ -> Healer (at batch checkpoints when policy requires)
46
+ -> Patch Validation and Application
47
+ -> Resume or Escalate
48
+ ```
49
+
50
+ Worker and healer outputs are candidate data until the orchestrator validates and commits them to state. Exit code alone is never treated as task success.
51
+
52
+ ### Canonical Source Tree
53
+
54
+ ```text
55
+ agent-threader/
56
+ SKILL.md -- skill entrypoint
57
+ SPEC.md -- normative architecture specification
58
+ schemas/ -- JSON schemas for all contracts
59
+ templates/ -- TypeScript scaffolding (types, parser, orchestrator utilities)
60
+ platforms/ -- thin wrappers for Codex, Cursor, Claude, Windsurf
61
+ ```
62
+
63
+ ---
64
+
65
+ ## Contracts
66
+
67
+ ### Contracts
68
+
69
+ All public contracts are JSON, versioned (`"2.0"`), and schema-validated. Machine-readable schemas live in `schemas/`.
70
+
71
+ ### manifest.v2
72
+
73
+ Declares tasks with required fields: `id`, `prompt_ref`, `depends_on`, `timeout_sec`, `verify_profile`. Optional: `context_refs`, `priority`, `retry_policy`, `metadata`.
74
+
75
+ Tasks are topologically sorted by `depends_on`. Lower `priority` values run first. A task cannot start until all dependencies are `DONE`.
76
+
77
+ ### task_result.v2
78
+
79
+ Emitted by the worker inside `<<<TASK_RESULT_V2>>>` / `<<<END_TASK_RESULT_V2>>>` sentinels.
80
+
81
+ Required fields: `contract_version`, `task_id`, `status` (DONE | BLOCKED | FAILED | CONTRACT_ERROR), `summary`.
82
+
83
+ Optional: `changed_files`, `writes[]` (with `path`, `op`, `encoding`, `content` or `content_ref`), `evidence` (commands, log_refs, notes), `failure_class`.
84
+
85
+ ### heal_decision.v2
86
+
87
+ Emitted by the healer inside `<<<HEAL_DECISION_V2>>>` / `<<<END_HEAL_DECISION_V2>>>` sentinels.
88
+
89
+ Required fields: `contract_version`, `scope` (task | batch | epoch), `decision` (RETRY | ESCALATE | NOT_FIXABLE), `failure_class`, `root_cause`, `patches[]`.
90
+
91
+ Patch targets: `shared_context`, `task_prompt`, `runtime_patch`, `contract_hint`. Each patch has `target`, `operation` (replace | append | merge), and `content`.
92
+
93
+ Optional: `learned_rule`, `escalations[]`, `retry_policy` (`reset_tasks`, `retry_window`).
94
+
95
+ ### state.v2
96
+
97
+ Persistent run state with: `run_id`, `run_status` (RUNNING | COMPLETED | ABORTED), `policy`, per-task state (status, attempts, failure signatures, history), and `healing_rounds[]`. Written atomically via temp file + rename.
98
+
99
+ ---
100
+
101
+ ## Healing Model
102
+
103
+ ### Progressive Batch Healing (PBH)
104
+
105
+ PBH is the default healing strategy. It starts with a small healing window, grows when stable, shrinks when unstable, and stops when automation is no longer justified.
106
+
107
+ ### Scheduling Modes
108
+
109
+ | Mode | Meaning |
110
+ | --- | --- |
111
+ | `auto` | PBH with adaptive growth and shrink. **Default.** |
112
+ | `off` | Healing disabled. |
113
+ | `task` | Heal only the single failed task. Window size is always 1. |
114
+ | `batch` | Heal at fixed batch checkpoints. Default fixed size is 5. |
115
+ | `epoch` | Attempt all pending tasks before healing. |
116
+
117
+ ### PBH Defaults
118
+
119
+ - `heal.schedule = auto`
120
+ - `batch.strategy = fibonacci` (sequence: 1, 2, 3, 5, 8, 13, ...)
121
+ - `failure_threshold = 0.2`
122
+ - `max_worker_attempts_per_task = 2`
123
+ - `max_heal_rounds_per_window = 2`
124
+ - `max_total_heal_rounds = 8`
125
+ - `signature_repeat_limit = 2`
126
+
127
+ ### PBH Behavior
128
+
129
+ - Zero failures in a window: advance to the next larger batch size.
130
+ - Failure rate > 0 but <= threshold: run healer once, retry the same window.
131
+ - Failure rate > threshold: shrink one batch level, isolate repeated signatures.
132
+ - Same signature repeats after healing: escalate that task.
133
+ - No convergence (failing set unchanged across rounds): abort the run.
134
+
135
+ ### Healable vs Non-Healable
136
+
137
+ Healable: `prompt_gap`, `missing_paths`, `weak_contract`, `contract_error`, `output_format`, `timeout`, `transient_infra`.
138
+
139
+ Non-healable: `blocked_external`, `real_bug`.
140
+
141
+ `build_error`, `test_error`, `smoke_error` may be healable when evidence points to prompt or configuration rather than a genuine product defect.
142
+
143
+ ### Convergence
144
+
145
+ Healing converges when at least one of: total failing count drops, repeated signature count drops, or a broad failure class narrows to a local issue. Healing is non-convergent when the same set persists, same signatures repeat, or budget is exhausted.
146
+
147
+ ### Healer Authority
148
+
149
+ The healer may emit bounded runtime patches (`timeout_sec`, `concurrency`, `current_batch_size`) validated by the orchestrator against operator limits. The healer must not modify `heal.schedule`, `batch.strategy`, verification commands, protected-file rules, parser behavior, or model identity.
150
+
151
+ ---
152
+
153
+ ## Verification and Safety
154
+
155
+ ### Verification and Safety Model
156
+
157
+ ### Verification Ownership
158
+
159
+ Verification always belongs to the orchestrator. It runs after successful parse and before final task success. The worker may report evidence, but does not own pass/fail classification.
160
+
161
+ ### Verification Layers
162
+
163
+ | Layer | Timing | Purpose |
164
+ | --- | --- | --- |
165
+ | Post-parse validation | After parsing worker output | Contract integrity, candidate writes, path safety |
166
+ | Post-write build/test | After writes are applied | Build, test, lint, or type failures caused by the change |
167
+ | Final smoke/browser | After build and test pass | Runtime behavior, UI behavior, custom project checks |
168
+
169
+ ### Allowed Write Path
170
+
171
+ 1. Worker emits `writes[]` in `task_result.v2`.
172
+ 2. Orchestrator validates those writes.
173
+ 3. Orchestrator applies those writes.
174
+ 4. Orchestrator verifies the result.
175
+
176
+ ### Required Write Safeguards
177
+
178
+ - Path normalization (writes cannot escape workspace root).
179
+ - Protected-file denylist.
180
+ - Shrinkage detection: reject replacement when original > 100 bytes and replacement < 50% of original size (unless explicitly allowed).
181
+ - Optional `sha256_before` precondition validation.
182
+ - Backup before write.
183
+ - Rollback on verification failure.
184
+
185
+ ### Healer Patch Safety
186
+
187
+ Healer patches follow the same validation model. The healer is forbidden from editing product source files directly, disabling verification, bypassing protected-file rules, or changing healing schedule mid-run.
188
+
189
+ ---
190
+
191
+ ## Adapter Model
192
+
193
+ ### Adapter Model
194
+
195
+ Adapters are the only place where CLI-specific behavior lives. The orchestrator core never calls CLIs directly -- it goes through `CliAdapter.execute`.
196
+
197
+ ### Adapter Responsibilities
198
+
199
+ - Construct the concrete CLI invocation (command, flags, working directory).
200
+ - Decide whether prompt delivery uses stdin, argv, or PTY interaction.
201
+ - Manage PTY or expect requirements for interactive CLIs.
202
+ - Capture combined stdout and stderr to the execution log.
203
+ - Return execution artifacts to the orchestrator.
204
+ - Delegate contract parsing and schema validation to the shared parser utilities.
205
+
206
+ ### Orchestrator Boundary
207
+
208
+ The orchestrator must:
209
+
210
+ - Never call CLIs directly except through `CliAdapter.execute`.
211
+ - Never parse raw logs without going through parser and validator modules.
212
+ - Never assume exit code alone means success.
213
+ - Remain CLI-agnostic outside the adapter boundary.
214
+
215
+ ### Reference Adapters
216
+
217
+ Initial adapters: `agent`, `opencode`, `claude`. All share one orchestrator contract model.
218
+
219
+ ### Interactive CLI Handling
220
+
221
+ For interactive CLIs, prompt rescue logic and TTY heuristics are adapter-local. Interactive adapters should implement ANSI stripping, bounded idle detection, finite rescue attempts, and explicit completion detection.
222
+
223
+ ### CliAdapter Interface
224
+
225
+ ```typescript
226
+ interface CliAdapter {
227
+ id: string;
228
+ capabilities: { stdinPrompt: boolean; argPrompt: boolean; pty: boolean; interactive: boolean };
229
+ prepare(task, ctx): PreparedInvocation;
230
+ execute(invocation, ctx): Promise<ExecutionArtifact>;
231
+ extractResult(artifact, ctx): Promise<TaskResultV2 | ParserFailure>;
232
+ healthcheck(ctx): Promise<AdapterHealth>;
233
+ }
234
+ ```
235
+
236
+ ---
237
+
238
+ ## State and Resume
239
+
240
+ ### State, Resume, and Convergence
241
+
242
+ ### Atomic State Writes
243
+
244
+ Mandatory. The orchestrator writes state via a temporary file followed by atomic rename on the same filesystem. State is checkpointed after every task attempt and every healing round.
245
+
246
+ ### Resume Semantics
247
+
248
+ - `DONE` tasks are skipped on resume if `manifest_digest` still matches.
249
+ - If `manifest_digest` changes, the orchestrator warns or forces reconciliation.
250
+ - `ESCALATED` tasks are not retried automatically.
251
+ - `FAILED` and `BLOCKED` tasks are eligible only if retry policy allows.
252
+
253
+ Reconciliation handles: tasks removed since last run, tasks added, tasks whose `prompt_ref`, `depends_on`, or `verify_profile` changed.
254
+
255
+ ### Failure Signature Generation
256
+
257
+ Stable failure signatures follow this algorithm:
258
+
259
+ 1. Start with the normalized failure class.
260
+ 2. Extract the primary stable signal from parser output, verification logs, or error codes.
261
+ 3. Remove timestamps, absolute paths, task IDs, and unstable numbers.
262
+ 4. Lowercase and collapse whitespace.
263
+ 5. Truncate to a stable maximum length.
264
+
265
+ Format: `<failure_class>:<normalized_signal>` (e.g., `build_error:missing_cn_import`).
266
+
267
+ ### Escalation Rules
268
+
269
+ Per-task: escalate when a task repeats the same signature `signature_repeat_limit` times after healing, or when a non-healable failure exhausts retry policy.
270
+
271
+ Per-run: escalate when `max_total_heal_rounds` is exhausted without convergence, or continuing would only repeat the same failure set.
272
+
273
+ Escalated tasks remain in state for reporting. Aborted runs record `run_status: ABORTED` with a non-empty `abort_reason`.
274
+
275
+ ---
276
+
277
+ ## Normative Specification
278
+
279
+ The full architecture, contracts, schemas, and behavioral rules are defined in `SPEC.md`. That document is the single source of truth. Read it when you need the end-to-end control flow, complete schema field definitions, or edge-case behavioral rules.
280
+
281
+ ## Canonical Source Of Truth
282
+
283
+ ### Schemas
284
+
285
+ Machine-readable JSON schemas (JSON Schema 2020-12) live in `schemas/`:
286
+
287
+ | Schema | Contract |
288
+ | --- | --- |
289
+ | `manifest.v2.json` | Task manifest: tasks with deps, timeouts, verify profiles |
290
+ | `verify_profile.v2.json` | Operator-defined verification profiles with steps and rollback flag |
291
+ | `task_result.v2.json` | Worker output: task_id, status, summary, optional writes and evidence |
292
+ | `heal_decision.v2.json` | Healer output: decision, patches, learned_rule |
293
+ | `state.v2.json` | Persistent run state: run_status, policy, per-task state, healing_rounds |
294
+
295
+ These schemas are the machine-readable authority. The orchestrator validates all contracts against them before state mutation.
296
+
297
+ ### Templates
298
+
299
+ Reference implementation skeletons live in `templates/`:
300
+
301
+ | File | Contents |
302
+ | --- | --- |
303
+ | `types.ts` | TypeScript type definitions for all v2 contracts: `ManifestV2`, `TaskResultV2`, `HealDecisionV2`, `StateV2`, `CliAdapter` interface, failure classes, PBH fibonacci sequence, default policy |
304
+ | `parser.ts` | Shared parser and validator: sentinel extraction (last block wins), JSON repair (strip markdown fences, trailing commas, JS comments), task result and heal decision validation, failure signature generation |
305
+ | `orchestrator.ts` | Shared runtime utilities: `writeAtomicJson` (temp file + rename) and `stableFailureSignature` (normalizes failure fingerprints) |
306
+
307
+ These templates are starting points for downstream runner implementations. Copy them into your project and extend as needed.
308
+
309
+ ---
310
+
311
+ ## Model Selection
312
+
313
+ ### Self-Healing: Model Selection Rule
314
+
315
+ When the user requests a self-healing runner, ask which models to use before generating code:
316
+
317
+ - **Worker CLI and model** -- runs the inner loop (can be fast/cheap)
318
+ - **Healer CLI and model** -- runs the outer diagnosis loop (should be more capable)
319
+
320
+ If the user does not specify, state the defaults explicitly before proceeding:
321
+
322
+ - Worker: the CLI the user is already using, default model
323
+ - Healer: same CLI family, stronger model tier
324
+
325
+ ---
326
+
327
+ ## Portability
328
+
329
+ ### Portability Rules
330
+
331
+ Platform wrappers may adapt:
332
+
333
+ - invocation command and flags
334
+ - prompt transport (`stdin`, argument, or PTY)
335
+ - approval handling and setup notes
336
+
337
+ Platform wrappers MUST preserve:
338
+
339
+ - contract field names and sentinel strings
340
+ - parser behavior
341
+ - PBH defaults and convergence rules
342
+ - state transitions and resume semantics
343
+
344
+ Platform wrappers MUST NOT redefine architecture, contracts, or healing policy.
345
+
346
+ ---
347
+
348
+ ## Workflow
349
+
350
+ ### Workflow
351
+
352
+ 1. Define the unit of work (component, story, work package, ticket, file).
353
+ 2. Create the manifest (`manifest.v2` JSON).
354
+ 3. Write shared context and per-task prompts.
355
+ 4. Define the completion contract in the prompt (instruct the worker to emit `<<<TASK_RESULT_V2>>>`).
356
+ 5. Choose the CLI adapter (`agent`, `opencode`, `claude`).
357
+ 6. Build the orchestrator (use `templates/` as starting point).
358
+ 7. Run sequential first, add concurrency after contracts and parsing are stable.
359
+ 8. Add verification gates (build, test, lint, smoke).
360
+ 9. Add healing only after the base loop works (`--heal auto`).
361
+ 10. Resume with `--resume` after interruptions.