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
@@ -0,0 +1,237 @@
1
+ #!/usr/bin/env node
2
+
3
+ // compile.mjs -- Assemble compiled/ output from skill fragments and platform wrappers.
4
+ // Usage:
5
+ // node skill/build/compile.mjs # build compiled/ directory
6
+ // node skill/build/compile.mjs --validate # validate fragment references only
7
+ // node skill/build/compile.mjs --watch # rebuild on changes (basic poll)
8
+
9
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, statSync, watchFile } from "node:fs";
10
+ import path from "node:path";
11
+
12
+ const ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", "..");
13
+ const SKILL_DIR = path.join(ROOT, "skill");
14
+ const FRAGMENTS_DIR = path.join(SKILL_DIR, "fragments");
15
+ const SKILLS_DIR = path.join(SKILL_DIR, "skills");
16
+ const MANIFEST_PATH = path.join(SKILL_DIR, "build", "manifest.json");
17
+ const COMPILED_DIR = path.join(ROOT, "compiled");
18
+ const MANAGED_MARKER = "managed_by: agent-threader";
19
+
20
+ function loadManifest() {
21
+ if (!existsSync(MANIFEST_PATH)) {
22
+ console.error(` ERROR: manifest not found: ${MANIFEST_PATH}`);
23
+ process.exit(1);
24
+ }
25
+
26
+ const raw = readFileSync(MANIFEST_PATH, "utf8");
27
+ const manifest = JSON.parse(raw);
28
+ const skills = manifest?.skills;
29
+
30
+ if (!skills || typeof skills !== "object" || Array.isArray(skills)) {
31
+ console.error(" ERROR: manifest.json must contain an object at skills");
32
+ process.exit(1);
33
+ }
34
+
35
+ return manifest;
36
+ }
37
+
38
+ function getSkillEntries(manifest) {
39
+ return Object.entries(manifest.skills);
40
+ }
41
+
42
+ function extractIncludes(raw) {
43
+ return [...new Set([...raw.matchAll(/\{\{include:([\w/.-]+)\}\}/g)].map(([, ref]) => ref))];
44
+ }
45
+
46
+ // ─── Fragment inclusion ──────────────────────────────────────────────────────
47
+
48
+ function resolveIncludes(content, baseDir) {
49
+ return content.replace(/\{\{include:([\w/.-]+)\}\}/g, (_match, ref) => {
50
+ const fragPath = path.join(FRAGMENTS_DIR, ref);
51
+ if (!existsSync(fragPath)) {
52
+ console.warn(` WARNING: fragment not found: ${ref}`);
53
+ return `<!-- MISSING FRAGMENT: ${ref} -->`;
54
+ }
55
+ const fragContent = readFileSync(fragPath, "utf8").trim();
56
+ // Recursively resolve nested includes
57
+ return resolveIncludes(fragContent, path.dirname(fragPath));
58
+ });
59
+ }
60
+
61
+ function compileSkill(skillName, sourceRelPath) {
62
+ const skillSrc = path.join(SKILL_DIR, sourceRelPath);
63
+ if (!existsSync(skillSrc)) {
64
+ console.error(` ERROR: skill source not found: ${skillSrc}`);
65
+ process.exit(1);
66
+ }
67
+ const raw = readFileSync(skillSrc, "utf8");
68
+ const compiled = resolveIncludes(raw, path.dirname(skillSrc));
69
+ return `<!-- ${MANAGED_MARKER} -->\n${compiled}`;
70
+ }
71
+
72
+ // ─── Validation mode ─────────────────────────────────────────────────────────
73
+
74
+ function validateFragmentRefs() {
75
+ let errors = 0;
76
+ const manifest = loadManifest();
77
+ const skillEntries = getSkillEntries(manifest);
78
+
79
+ for (const [skillName, skillConfig] of skillEntries) {
80
+ if (!skillConfig || typeof skillConfig !== "object") {
81
+ console.error(` INVALID: ${skillName} manifest entry must be an object`);
82
+ errors++;
83
+ continue;
84
+ }
85
+
86
+ const source = skillConfig.source;
87
+ const declaredFragments = Array.isArray(skillConfig.fragments) ? skillConfig.fragments : [];
88
+
89
+ if (typeof source !== "string" || source.length === 0) {
90
+ console.error(` INVALID: ${skillName} must declare a non-empty source path`);
91
+ errors++;
92
+ continue;
93
+ }
94
+
95
+ const skillSrc = path.join(SKILL_DIR, source);
96
+ if (!existsSync(skillSrc)) {
97
+ console.error(` MISSING: ${skillName} source -> ${source}`);
98
+ errors++;
99
+ continue;
100
+ }
101
+
102
+ const raw = readFileSync(skillSrc, "utf8");
103
+ const referenced = extractIncludes(raw);
104
+
105
+ for (const ref of referenced) {
106
+ const fragPath = path.join(FRAGMENTS_DIR, ref);
107
+ if (!existsSync(fragPath)) {
108
+ console.error(` MISSING: ${skillName} include -> ${ref}`);
109
+ errors++;
110
+ }
111
+ if (!declaredFragments.includes(ref)) {
112
+ console.error(` UNDECLARED: ${skillName} includes ${ref} but manifest does not declare it`);
113
+ errors++;
114
+ }
115
+ }
116
+
117
+ for (const ref of declaredFragments) {
118
+ const fragPath = path.join(FRAGMENTS_DIR, ref);
119
+ if (!existsSync(fragPath)) {
120
+ console.error(` MISSING: ${skillName} declared fragment -> ${ref}`);
121
+ errors++;
122
+ }
123
+ if (!referenced.includes(ref)) {
124
+ console.error(` UNUSED: ${skillName} declares ${ref} but source does not include it`);
125
+ errors++;
126
+ }
127
+ }
128
+ }
129
+
130
+ if (errors > 0) {
131
+ console.error(`\nValidation failed: ${errors} issue(s).`);
132
+ process.exit(1);
133
+ }
134
+ console.log("Manifest and fragment references are valid.");
135
+ }
136
+
137
+ // ─── Emit helpers ────────────────────────────────────────────────────────────
138
+
139
+ function emit(filePath, content) {
140
+ mkdirSync(path.dirname(filePath), { recursive: true });
141
+ writeFileSync(filePath, content, "utf8");
142
+ console.log(` wrote: ${path.relative(ROOT, filePath)}`);
143
+ }
144
+
145
+ // ─── Platform emitters ───────────────────────────────────────────────────────
146
+
147
+ function emitClaude(skillName, compiledContent) {
148
+ emit(path.join(COMPILED_DIR, "claude", skillName, "SKILL.md"), compiledContent);
149
+ }
150
+
151
+ function emitCursor(skillName, compiledContent) {
152
+ // Cursor rule (.mdc)
153
+ const ruleContent = [
154
+ `---`,
155
+ `description: "${skillName} skill"`,
156
+ `globs: []`,
157
+ `alwaysApply: false`,
158
+ `---`,
159
+ ``,
160
+ compiledContent,
161
+ ].join("\n");
162
+ emit(path.join(COMPILED_DIR, "cursor", "rules", `${skillName}.mdc`), ruleContent);
163
+ // Cursor skill
164
+ emit(path.join(COMPILED_DIR, "cursor", "skills", skillName, "SKILL.md"), compiledContent);
165
+ }
166
+
167
+ function emitWindsurf(skillName, compiledContent) {
168
+ // Windsurf rule
169
+ emit(path.join(COMPILED_DIR, "windsurf", "rules", `${skillName}.md`), compiledContent);
170
+ // Windsurf skill
171
+ emit(path.join(COMPILED_DIR, "windsurf", "skills", skillName, "SKILL.md"), compiledContent);
172
+ }
173
+
174
+ function emitOpencode(skillName, compiledContent) {
175
+ emit(path.join(COMPILED_DIR, "opencode", `${skillName}.md`), compiledContent);
176
+ }
177
+
178
+ function emitCodex(skillName, compiledContent) {
179
+ emit(path.join(COMPILED_DIR, "codex", skillName, "SKILL.md"), compiledContent);
180
+ }
181
+
182
+ // ─── Main build ──────────────────────────────────────────────────────────────
183
+
184
+ function build() {
185
+ console.log("==> Compiling skills...");
186
+ const manifest = loadManifest();
187
+ const skillEntries = getSkillEntries(manifest);
188
+
189
+ for (const [skillName, skillConfig] of skillEntries) {
190
+ const source = skillConfig?.source;
191
+ if (typeof source !== "string" || source.length === 0) {
192
+ console.error(` ERROR: ${skillName} must declare a non-empty source path in manifest`);
193
+ process.exit(1);
194
+ }
195
+ console.log(` ${skillName}:`);
196
+ const compiled = compileSkill(skillName, source);
197
+
198
+ emitClaude(skillName, compiled);
199
+ emitCursor(skillName, compiled);
200
+ emitWindsurf(skillName, compiled);
201
+ emitOpencode(skillName, compiled);
202
+ emitCodex(skillName, compiled);
203
+ }
204
+
205
+ console.log("==> Done.");
206
+ }
207
+
208
+ // ─── CLI ─────────────────────────────────────────────────────────────────────
209
+
210
+ const args = process.argv.slice(2);
211
+
212
+ if (args.includes("--validate")) {
213
+ validateFragmentRefs();
214
+ } else if (args.includes("--watch")) {
215
+ build();
216
+ console.log("\nWatching for changes...");
217
+ const watchDirs = [FRAGMENTS_DIR, SKILLS_DIR];
218
+ for (const dir of watchDirs) {
219
+ if (!existsSync(dir)) continue;
220
+ const files = readdirSync(dir, { recursive: true });
221
+ for (const file of files) {
222
+ const fullPath = path.join(dir, file);
223
+ if (statSync(fullPath).isFile()) {
224
+ watchFile(fullPath, { interval: 1000 }, () => {
225
+ console.log(`\nChange detected: ${path.relative(ROOT, fullPath)}`);
226
+ build();
227
+ });
228
+ }
229
+ }
230
+ }
231
+ watchFile(MANIFEST_PATH, { interval: 1000 }, () => {
232
+ console.log(`\nChange detected: ${path.relative(ROOT, MANIFEST_PATH)}`);
233
+ build();
234
+ });
235
+ } else {
236
+ build();
237
+ }
@@ -0,0 +1,21 @@
1
+ {
2
+ "version": "1",
3
+ "skills": {
4
+ "agent-threader": {
5
+ "source": "skills/agent-threader/agent-threader.md",
6
+ "fragments": [
7
+ "domain/architecture-overview.md",
8
+ "domain/contracts.md",
9
+ "domain/pbh-healing.md",
10
+ "domain/verification-safety.md",
11
+ "domain/adapter-model.md",
12
+ "domain/state-resume.md",
13
+ "meta/schemas-reference.md",
14
+ "meta/templates-reference.md",
15
+ "common/model-selection.md",
16
+ "common/portability-rules.md",
17
+ "common/workflow.md"
18
+ ]
19
+ }
20
+ }
21
+ }
@@ -0,0 +1,11 @@
1
+ ### Self-Healing: Model Selection Rule
2
+
3
+ When the user requests a self-healing runner, ask which models to use before generating code:
4
+
5
+ - **Worker CLI and model** -- runs the inner loop (can be fast/cheap)
6
+ - **Healer CLI and model** -- runs the outer diagnosis loop (should be more capable)
7
+
8
+ If the user does not specify, state the defaults explicitly before proceeding:
9
+
10
+ - Worker: the CLI the user is already using, default model
11
+ - Healer: same CLI family, stronger model tier
@@ -0,0 +1,16 @@
1
+ ### Portability Rules
2
+
3
+ Platform wrappers may adapt:
4
+
5
+ - invocation command and flags
6
+ - prompt transport (`stdin`, argument, or PTY)
7
+ - approval handling and setup notes
8
+
9
+ Platform wrappers MUST preserve:
10
+
11
+ - contract field names and sentinel strings
12
+ - parser behavior
13
+ - PBH defaults and convergence rules
14
+ - state transitions and resume semantics
15
+
16
+ Platform wrappers MUST NOT redefine architecture, contracts, or healing policy.
@@ -0,0 +1,12 @@
1
+ ### Workflow
2
+
3
+ 1. Define the unit of work (component, story, work package, ticket, file).
4
+ 2. Create the manifest (`manifest.v2` JSON).
5
+ 3. Write shared context and per-task prompts.
6
+ 4. Define the completion contract in the prompt (instruct the worker to emit `<<<TASK_RESULT_V2>>>`).
7
+ 5. Choose the CLI adapter (`agent`, `opencode`, `claude`).
8
+ 6. Build the orchestrator (use `templates/` as starting point).
9
+ 7. Run sequential first, add concurrency after contracts and parsing are stable.
10
+ 8. Add verification gates (build, test, lint, smoke).
11
+ 9. Add healing only after the base loop works (`--heal auto`).
12
+ 10. Resume with `--resume` after interruptions.
@@ -0,0 +1,42 @@
1
+ ### Adapter Model
2
+
3
+ Adapters are the only place where CLI-specific behavior lives. The orchestrator core never calls CLIs directly -- it goes through `CliAdapter.execute`.
4
+
5
+ ### Adapter Responsibilities
6
+
7
+ - Construct the concrete CLI invocation (command, flags, working directory).
8
+ - Decide whether prompt delivery uses stdin, argv, or PTY interaction.
9
+ - Manage PTY or expect requirements for interactive CLIs.
10
+ - Capture combined stdout and stderr to the execution log.
11
+ - Return execution artifacts to the orchestrator.
12
+ - Delegate contract parsing and schema validation to the shared parser utilities.
13
+
14
+ ### Orchestrator Boundary
15
+
16
+ The orchestrator must:
17
+
18
+ - Never call CLIs directly except through `CliAdapter.execute`.
19
+ - Never parse raw logs without going through parser and validator modules.
20
+ - Never assume exit code alone means success.
21
+ - Remain CLI-agnostic outside the adapter boundary.
22
+
23
+ ### Reference Adapters
24
+
25
+ Initial adapters: `agent`, `opencode`, `claude`. All share one orchestrator contract model.
26
+
27
+ ### Interactive CLI Handling
28
+
29
+ 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.
30
+
31
+ ### CliAdapter Interface
32
+
33
+ ```typescript
34
+ interface CliAdapter {
35
+ id: string;
36
+ capabilities: { stdinPrompt: boolean; argPrompt: boolean; pty: boolean; interactive: boolean };
37
+ prepare(task, ctx): PreparedInvocation;
38
+ execute(invocation, ctx): Promise<ExecutionArtifact>;
39
+ extractResult(artifact, ctx): Promise<TaskResultV2 | ParserFailure>;
40
+ healthcheck(ctx): Promise<AdapterHealth>;
41
+ }
42
+ ```
@@ -0,0 +1,36 @@
1
+ ### Architecture Overview
2
+
3
+ The v2 system has five moving parts:
4
+
5
+ 1. **Manifest** -- declares work items, dependencies, timeouts, and verification profiles.
6
+ 2. **Orchestrator** -- owns scheduling, parsing, verification, checkpointing, healing, and retry policy. The orchestrator is the single source of truth for task status.
7
+ 3. **Adapters** -- CLI-specific execution layers (`agent`, `opencode`, `claude`) that the orchestrator calls through a uniform `CliAdapter` interface.
8
+ 4. **Worker** -- the model invocation that performs task work and emits a `task_result.v2` JSON contract fenced by `<<<TASK_RESULT_V2>>>` sentinels.
9
+ 5. **Healer** -- the model invocation that diagnoses fixable failures and emits a `heal_decision.v2` JSON contract fenced by `<<<HEAL_DECISION_V2>>>` sentinels.
10
+
11
+ ### Control Flow
12
+
13
+ ```text
14
+ Manifest
15
+ -> Orchestrator
16
+ -> Adapter -> Worker
17
+ -> Parser and Schema Validator
18
+ -> Verification Gates
19
+ -> State Checkpoint
20
+ -> Healer (at batch checkpoints when policy requires)
21
+ -> Patch Validation and Application
22
+ -> Resume or Escalate
23
+ ```
24
+
25
+ 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.
26
+
27
+ ### Canonical Source Tree
28
+
29
+ ```text
30
+ agent-threader/
31
+ SKILL.md -- skill entrypoint
32
+ SPEC.md -- normative architecture specification
33
+ schemas/ -- JSON schemas for all contracts
34
+ templates/ -- TypeScript scaffolding (types, parser, orchestrator utilities)
35
+ platforms/ -- thin wrappers for Codex, Cursor, Claude, Windsurf
36
+ ```
@@ -0,0 +1,31 @@
1
+ ### Contracts
2
+
3
+ All public contracts are JSON, versioned (`"2.0"`), and schema-validated. Machine-readable schemas live in `schemas/`.
4
+
5
+ ### manifest.v2
6
+
7
+ Declares tasks with required fields: `id`, `prompt_ref`, `depends_on`, `timeout_sec`, `verify_profile`. Optional: `context_refs`, `priority`, `retry_policy`, `metadata`.
8
+
9
+ Tasks are topologically sorted by `depends_on`. Lower `priority` values run first. A task cannot start until all dependencies are `DONE`.
10
+
11
+ ### task_result.v2
12
+
13
+ Emitted by the worker inside `<<<TASK_RESULT_V2>>>` / `<<<END_TASK_RESULT_V2>>>` sentinels.
14
+
15
+ Required fields: `contract_version`, `task_id`, `status` (DONE | BLOCKED | FAILED | CONTRACT_ERROR), `summary`.
16
+
17
+ Optional: `changed_files`, `writes[]` (with `path`, `op`, `encoding`, `content` or `content_ref`), `evidence` (commands, log_refs, notes), `failure_class`.
18
+
19
+ ### heal_decision.v2
20
+
21
+ Emitted by the healer inside `<<<HEAL_DECISION_V2>>>` / `<<<END_HEAL_DECISION_V2>>>` sentinels.
22
+
23
+ Required fields: `contract_version`, `scope` (task | batch | epoch), `decision` (RETRY | ESCALATE | NOT_FIXABLE), `failure_class`, `root_cause`, `patches[]`.
24
+
25
+ Patch targets: `shared_context`, `task_prompt`, `runtime_patch`, `contract_hint`. Each patch has `target`, `operation` (replace | append | merge), and `content`.
26
+
27
+ Optional: `learned_rule`, `escalations[]`, `retry_policy` (`reset_tasks`, `retry_window`).
28
+
29
+ ### state.v2
30
+
31
+ 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.
@@ -0,0 +1,47 @@
1
+ ### Progressive Batch Healing (PBH)
2
+
3
+ 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.
4
+
5
+ ### Scheduling Modes
6
+
7
+ | Mode | Meaning |
8
+ | --- | --- |
9
+ | `auto` | PBH with adaptive growth and shrink. **Default.** |
10
+ | `off` | Healing disabled. |
11
+ | `task` | Heal only the single failed task. Window size is always 1. |
12
+ | `batch` | Heal at fixed batch checkpoints. Default fixed size is 5. |
13
+ | `epoch` | Attempt all pending tasks before healing. |
14
+
15
+ ### PBH Defaults
16
+
17
+ - `heal.schedule = auto`
18
+ - `batch.strategy = fibonacci` (sequence: 1, 2, 3, 5, 8, 13, ...)
19
+ - `failure_threshold = 0.2`
20
+ - `max_worker_attempts_per_task = 2`
21
+ - `max_heal_rounds_per_window = 2`
22
+ - `max_total_heal_rounds = 8`
23
+ - `signature_repeat_limit = 2`
24
+
25
+ ### PBH Behavior
26
+
27
+ - Zero failures in a window: advance to the next larger batch size.
28
+ - Failure rate > 0 but <= threshold: run healer once, retry the same window.
29
+ - Failure rate > threshold: shrink one batch level, isolate repeated signatures.
30
+ - Same signature repeats after healing: escalate that task.
31
+ - No convergence (failing set unchanged across rounds): abort the run.
32
+
33
+ ### Healable vs Non-Healable
34
+
35
+ Healable: `prompt_gap`, `missing_paths`, `weak_contract`, `contract_error`, `output_format`, `timeout`, `transient_infra`.
36
+
37
+ Non-healable: `blocked_external`, `real_bug`.
38
+
39
+ `build_error`, `test_error`, `smoke_error` may be healable when evidence points to prompt or configuration rather than a genuine product defect.
40
+
41
+ ### Convergence
42
+
43
+ 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.
44
+
45
+ ### Healer Authority
46
+
47
+ 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.
@@ -0,0 +1,34 @@
1
+ ### State, Resume, and Convergence
2
+
3
+ ### Atomic State Writes
4
+
5
+ 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.
6
+
7
+ ### Resume Semantics
8
+
9
+ - `DONE` tasks are skipped on resume if `manifest_digest` still matches.
10
+ - If `manifest_digest` changes, the orchestrator warns or forces reconciliation.
11
+ - `ESCALATED` tasks are not retried automatically.
12
+ - `FAILED` and `BLOCKED` tasks are eligible only if retry policy allows.
13
+
14
+ Reconciliation handles: tasks removed since last run, tasks added, tasks whose `prompt_ref`, `depends_on`, or `verify_profile` changed.
15
+
16
+ ### Failure Signature Generation
17
+
18
+ Stable failure signatures follow this algorithm:
19
+
20
+ 1. Start with the normalized failure class.
21
+ 2. Extract the primary stable signal from parser output, verification logs, or error codes.
22
+ 3. Remove timestamps, absolute paths, task IDs, and unstable numbers.
23
+ 4. Lowercase and collapse whitespace.
24
+ 5. Truncate to a stable maximum length.
25
+
26
+ Format: `<failure_class>:<normalized_signal>` (e.g., `build_error:missing_cn_import`).
27
+
28
+ ### Escalation Rules
29
+
30
+ 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.
31
+
32
+ Per-run: escalate when `max_total_heal_rounds` is exhausted without convergence, or continuing would only repeat the same failure set.
33
+
34
+ Escalated tasks remain in state for reporting. Aborted runs record `run_status: ABORTED` with a non-empty `abort_reason`.
@@ -0,0 +1,33 @@
1
+ ### Verification and Safety Model
2
+
3
+ ### Verification Ownership
4
+
5
+ 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.
6
+
7
+ ### Verification Layers
8
+
9
+ | Layer | Timing | Purpose |
10
+ | --- | --- | --- |
11
+ | Post-parse validation | After parsing worker output | Contract integrity, candidate writes, path safety |
12
+ | Post-write build/test | After writes are applied | Build, test, lint, or type failures caused by the change |
13
+ | Final smoke/browser | After build and test pass | Runtime behavior, UI behavior, custom project checks |
14
+
15
+ ### Allowed Write Path
16
+
17
+ 1. Worker emits `writes[]` in `task_result.v2`.
18
+ 2. Orchestrator validates those writes.
19
+ 3. Orchestrator applies those writes.
20
+ 4. Orchestrator verifies the result.
21
+
22
+ ### Required Write Safeguards
23
+
24
+ - Path normalization (writes cannot escape workspace root).
25
+ - Protected-file denylist.
26
+ - Shrinkage detection: reject replacement when original > 100 bytes and replacement < 50% of original size (unless explicitly allowed).
27
+ - Optional `sha256_before` precondition validation.
28
+ - Backup before write.
29
+ - Rollback on verification failure.
30
+
31
+ ### Healer Patch Safety
32
+
33
+ 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.
@@ -0,0 +1,13 @@
1
+ ### Schemas
2
+
3
+ Machine-readable JSON schemas (JSON Schema 2020-12) live in `schemas/`:
4
+
5
+ | Schema | Contract |
6
+ | --- | --- |
7
+ | `manifest.v2.json` | Task manifest: tasks with deps, timeouts, verify profiles |
8
+ | `verify_profile.v2.json` | Operator-defined verification profiles with steps and rollback flag |
9
+ | `task_result.v2.json` | Worker output: task_id, status, summary, optional writes and evidence |
10
+ | `heal_decision.v2.json` | Healer output: decision, patches, learned_rule |
11
+ | `state.v2.json` | Persistent run state: run_status, policy, per-task state, healing_rounds |
12
+
13
+ These schemas are the machine-readable authority. The orchestrator validates all contracts against them before state mutation.
@@ -0,0 +1,11 @@
1
+ ### Templates
2
+
3
+ Reference implementation skeletons live in `templates/`:
4
+
5
+ | File | Contents |
6
+ | --- | --- |
7
+ | `types.ts` | TypeScript type definitions for all v2 contracts: `ManifestV2`, `TaskResultV2`, `HealDecisionV2`, `StateV2`, `CliAdapter` interface, failure classes, PBH fibonacci sequence, default policy |
8
+ | `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 |
9
+ | `orchestrator.ts` | Shared runtime utilities: `writeAtomicJson` (temp file + rename) and `stableFailureSignature` (normalizes failure fingerprints) |
10
+
11
+ These templates are starting points for downstream runner implementations. Copy them into your project and extend as needed.
@@ -0,0 +1,100 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "heal_decision.v2.json",
4
+ "title": "Heal Decision v2",
5
+ "description": "Healer output contract. Emitted inside <<<HEAL_DECISION_V2>>> fences.",
6
+ "type": "object",
7
+ "required": ["contract_version", "scope", "decision", "failure_class", "root_cause", "patches"],
8
+ "properties": {
9
+ "contract_version": {
10
+ "type": "string",
11
+ "const": "2.0"
12
+ },
13
+ "scope": {
14
+ "type": "string",
15
+ "enum": ["task", "batch", "epoch"],
16
+ "description": "Advisory healer view of the current healing level."
17
+ },
18
+ "decision": {
19
+ "type": "string",
20
+ "enum": ["RETRY", "ESCALATE", "NOT_FIXABLE"]
21
+ },
22
+ "failure_class": {
23
+ "type": "string",
24
+ "minLength": 1,
25
+ "description": "Normalized failure class the healer is addressing."
26
+ },
27
+ "root_cause": {
28
+ "type": "string",
29
+ "minLength": 1,
30
+ "description": "One-sentence diagnosis of the repeated issue."
31
+ },
32
+ "patches": {
33
+ "type": "array",
34
+ "items": { "$ref": "#/$defs/patch" },
35
+ "description": "Allowed patch operations."
36
+ },
37
+ "learned_rule": {
38
+ "type": "string",
39
+ "description": "Reusable rule recorded by the orchestrator for future runs."
40
+ },
41
+ "escalations": {
42
+ "type": "array",
43
+ "items": {
44
+ "type": "object",
45
+ "required": ["task_id", "reason"],
46
+ "properties": {
47
+ "task_id": { "type": "string" },
48
+ "reason": { "type": "string" }
49
+ },
50
+ "additionalProperties": false
51
+ },
52
+ "description": "Explicit per-task escalation records."
53
+ },
54
+ "retry_policy": { "$ref": "#/$defs/retry_policy" }
55
+ },
56
+ "additionalProperties": false,
57
+ "$defs": {
58
+ "patch": {
59
+ "type": "object",
60
+ "required": ["target", "operation"],
61
+ "properties": {
62
+ "target": {
63
+ "type": "string",
64
+ "enum": ["shared_context", "task_prompt", "runtime_patch", "contract_hint"]
65
+ },
66
+ "operation": {
67
+ "type": "string",
68
+ "enum": ["replace", "append", "merge"]
69
+ },
70
+ "path": {
71
+ "type": "string",
72
+ "description": "Required for shared_context and task_prompt file replacements."
73
+ },
74
+ "task_id": {
75
+ "type": "string",
76
+ "description": "Required when target is task_prompt."
77
+ },
78
+ "content": {
79
+ "description": "Patch payload. String for text replacements, object for runtime merge content."
80
+ }
81
+ },
82
+ "additionalProperties": false
83
+ },
84
+ "retry_policy": {
85
+ "type": "object",
86
+ "properties": {
87
+ "reset_tasks": {
88
+ "type": "array",
89
+ "items": { "type": "string" },
90
+ "description": "Tasks to reset to pending for retry."
91
+ },
92
+ "retry_window": {
93
+ "type": "string",
94
+ "enum": ["same_window", "shrink_window", "next_epoch"]
95
+ }
96
+ },
97
+ "additionalProperties": false
98
+ }
99
+ }
100
+ }