thumbgate 0.9.10

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 (364) hide show
  1. package/.claude-plugin/README.md +134 -0
  2. package/.claude-plugin/bundle/icon.png +0 -0
  3. package/.claude-plugin/bundle/icon.svg +18 -0
  4. package/.claude-plugin/bundle/server/index.js +24 -0
  5. package/.claude-plugin/marketplace.json +36 -0
  6. package/.claude-plugin/plugin.json +21 -0
  7. package/.well-known/mcp/server-card.json +231 -0
  8. package/LICENSE +21 -0
  9. package/README.md +375 -0
  10. package/adapters/README.md +9 -0
  11. package/adapters/amp/skills/thumbgate-feedback/SKILL.md +22 -0
  12. package/adapters/chatgpt/INSTALL.md +83 -0
  13. package/adapters/chatgpt/openapi.yaml +1281 -0
  14. package/adapters/claude/.mcp.json +14 -0
  15. package/adapters/codex/config.toml +9 -0
  16. package/adapters/gemini/function-declarations.json +224 -0
  17. package/adapters/mcp/server-stdio.js +788 -0
  18. package/adapters/opencode/opencode.json +15 -0
  19. package/bin/cli.js +1484 -0
  20. package/bin/memory.sh +64 -0
  21. package/bin/obsidian-sync.sh +20 -0
  22. package/bin/postinstall.js +37 -0
  23. package/config/build-metadata.json +4 -0
  24. package/config/e2e-critical-flows.json +45 -0
  25. package/config/gate-templates.json +77 -0
  26. package/config/gates/claim-verification.json +29 -0
  27. package/config/gates/computer-use.json +39 -0
  28. package/config/gates/default.json +117 -0
  29. package/config/github-about.json +25 -0
  30. package/config/mcp-allowlists.json +135 -0
  31. package/config/model-tiers.json +33 -0
  32. package/config/partner-routing.json +132 -0
  33. package/config/policy-bundles/constrained-v1.json +64 -0
  34. package/config/policy-bundles/default-v1.json +91 -0
  35. package/config/rubrics/default-v1.json +52 -0
  36. package/config/skill-packs/react-testing.json +23 -0
  37. package/config/skill-packs/stripe-integration/references/api-spec.json +1 -0
  38. package/config/skill-packs/stripe-integration/references/webhook-guide.md +3 -0
  39. package/config/skill-specs/pr-reviewer.json +9 -0
  40. package/config/skill-specs/release-status.json +9 -0
  41. package/config/skill-specs/ticket-triage.json +9 -0
  42. package/config/subagent-profiles.json +32 -0
  43. package/config/tessl-tiles.json +29 -0
  44. package/config/thumbgate-settings.managed.json +12 -0
  45. package/openapi/openapi.yaml +1281 -0
  46. package/package.json +283 -0
  47. package/plugins/amp-skill/INSTALL.md +52 -0
  48. package/plugins/amp-skill/SKILL.md +64 -0
  49. package/plugins/claude-codex-bridge/.claude-plugin/plugin.json +22 -0
  50. package/plugins/claude-codex-bridge/.mcp.json +12 -0
  51. package/plugins/claude-codex-bridge/INSTALL.md +43 -0
  52. package/plugins/claude-codex-bridge/README.md +46 -0
  53. package/plugins/claude-codex-bridge/scripts/codex-bridge.js +288 -0
  54. package/plugins/claude-codex-bridge/skills/adversarial-review/SKILL.md +24 -0
  55. package/plugins/claude-codex-bridge/skills/result/SKILL.md +22 -0
  56. package/plugins/claude-codex-bridge/skills/review/SKILL.md +28 -0
  57. package/plugins/claude-codex-bridge/skills/second-pass/SKILL.md +27 -0
  58. package/plugins/claude-codex-bridge/skills/setup/SKILL.md +21 -0
  59. package/plugins/claude-codex-bridge/skills/status/SKILL.md +19 -0
  60. package/plugins/claude-skill/INSTALL.md +55 -0
  61. package/plugins/claude-skill/SKILL.md +46 -0
  62. package/plugins/codex-profile/.codex-plugin/plugin.json +43 -0
  63. package/plugins/codex-profile/.mcp.json +12 -0
  64. package/plugins/codex-profile/AGENTS.md +20 -0
  65. package/plugins/codex-profile/INSTALL.md +66 -0
  66. package/plugins/codex-profile/README.md +37 -0
  67. package/plugins/cursor-marketplace/.cursor-plugin/plugin.json +23 -0
  68. package/plugins/cursor-marketplace/CHANGELOG.md +30 -0
  69. package/plugins/cursor-marketplace/LICENSE +21 -0
  70. package/plugins/cursor-marketplace/README.md +124 -0
  71. package/plugins/cursor-marketplace/agents/reliability-reviewer.md +31 -0
  72. package/plugins/cursor-marketplace/assets/logo-400x400.png +0 -0
  73. package/plugins/cursor-marketplace/commands/capture-feedback.md +33 -0
  74. package/plugins/cursor-marketplace/commands/check-gates.md +25 -0
  75. package/plugins/cursor-marketplace/commands/show-lessons.md +27 -0
  76. package/plugins/cursor-marketplace/hooks/hooks.json +10 -0
  77. package/plugins/cursor-marketplace/mcp.json +12 -0
  78. package/plugins/cursor-marketplace/rules/feedback-capture.mdc +34 -0
  79. package/plugins/cursor-marketplace/rules/pre-action-gates.mdc +30 -0
  80. package/plugins/cursor-marketplace/rules/session-continuity.mdc +28 -0
  81. package/plugins/cursor-marketplace/scripts/gate-check.sh +11 -0
  82. package/plugins/cursor-marketplace/skills/capture-feedback/SKILL.md +47 -0
  83. package/plugins/cursor-marketplace/skills/prevention-rules/SKILL.md +31 -0
  84. package/plugins/cursor-marketplace/skills/recall-context/SKILL.md +30 -0
  85. package/plugins/cursor-marketplace/skills/search-lessons/SKILL.md +33 -0
  86. package/plugins/gemini-extension/INSTALL.md +92 -0
  87. package/plugins/gemini-extension/gemini_prompt.txt +14 -0
  88. package/plugins/gemini-extension/tool_contract.json +45 -0
  89. package/plugins/opencode-profile/INSTALL.md +57 -0
  90. package/public/assets/instagram-card.png +0 -0
  91. package/public/assets/tiktok-agent-memory.mp4 +0 -0
  92. package/public/blog.html +400 -0
  93. package/public/dashboard.html +1093 -0
  94. package/public/guide.html +317 -0
  95. package/public/index.html +1014 -0
  96. package/public/learn/agent-harness-pattern.html +180 -0
  97. package/public/learn/ai-agent-persistent-memory.html +202 -0
  98. package/public/learn/learn.css +45 -0
  99. package/public/learn/mcp-pre-action-gates-explained.html +172 -0
  100. package/public/learn/stop-ai-agent-force-push.html +134 -0
  101. package/public/learn/vibe-coding-safety-net.html +142 -0
  102. package/public/learn.html +213 -0
  103. package/public/lessons.html +650 -0
  104. package/public/vercel.json +8 -0
  105. package/scripts/__pycache__/train_from_feedback.cpython-312.pyc +0 -0
  106. package/scripts/a2ui-engine.js +73 -0
  107. package/scripts/access-anomaly-detector.js +12 -0
  108. package/scripts/adk-consolidator.js +266 -0
  109. package/scripts/agent-readiness.js +220 -0
  110. package/scripts/agent-security-hardening.js +227 -0
  111. package/scripts/agentic-data-pipeline.js +847 -0
  112. package/scripts/analytics-report.js +328 -0
  113. package/scripts/analytics-window.js +158 -0
  114. package/scripts/async-job-runner.js +1001 -0
  115. package/scripts/audit-trail.js +398 -0
  116. package/scripts/auto-promote-gates.js +299 -0
  117. package/scripts/auto-wire-hooks.js +312 -0
  118. package/scripts/autonomous-sales-agent.js +39 -0
  119. package/scripts/autoresearch-runner.js +216 -0
  120. package/scripts/background-agent-governance.js +237 -0
  121. package/scripts/behavioral-extraction.js +97 -0
  122. package/scripts/belief-update.js +84 -0
  123. package/scripts/billing.js +2438 -0
  124. package/scripts/bot-detector.js +50 -0
  125. package/scripts/budget-guard.js +173 -0
  126. package/scripts/build-claude-mcpb.js +189 -0
  127. package/scripts/build-metadata.js +97 -0
  128. package/scripts/check-congruence.js +322 -0
  129. package/scripts/cli-feedback.js +135 -0
  130. package/scripts/cli-telemetry.js +87 -0
  131. package/scripts/cloudflare-dynamic-sandbox.js +315 -0
  132. package/scripts/code-reasoning.js +350 -0
  133. package/scripts/codegraph-context.js +466 -0
  134. package/scripts/commercial-offer.js +56 -0
  135. package/scripts/computer-use-firewall.js +250 -0
  136. package/scripts/context-engine.js +694 -0
  137. package/scripts/contextfs.js +1287 -0
  138. package/scripts/conversation-context.js +119 -0
  139. package/scripts/creator-campaigns.js +239 -0
  140. package/scripts/daemon-manager.js +108 -0
  141. package/scripts/daily-digest.js +11 -0
  142. package/scripts/dashboard-render-spec.js +395 -0
  143. package/scripts/dashboard.js +1058 -0
  144. package/scripts/data-governance.js +173 -0
  145. package/scripts/delegation-runtime.js +900 -0
  146. package/scripts/deploy-gcp.sh +44 -0
  147. package/scripts/deploy-policy.js +263 -0
  148. package/scripts/disagreement-mining.js +315 -0
  149. package/scripts/dispatch-brief.js +159 -0
  150. package/scripts/distribution-surfaces.js +44 -0
  151. package/scripts/dpo-optimizer.js +209 -0
  152. package/scripts/ephemeral-agent-store.js +219 -0
  153. package/scripts/eval-harness.js +56 -0
  154. package/scripts/evolution-state.js +241 -0
  155. package/scripts/experiment-tracker.js +267 -0
  156. package/scripts/export-databricks-bundle.js +242 -0
  157. package/scripts/export-dpo-pairs.js +345 -0
  158. package/scripts/export-kto-pairs.js +310 -0
  159. package/scripts/export-training.js +448 -0
  160. package/scripts/failure-diagnostics.js +558 -0
  161. package/scripts/feedback-attribution.js +313 -0
  162. package/scripts/feedback-fallback.js +111 -0
  163. package/scripts/feedback-history-distiller.js +391 -0
  164. package/scripts/feedback-inbox-read.js +162 -0
  165. package/scripts/feedback-loop.js +1887 -0
  166. package/scripts/feedback-paths.js +145 -0
  167. package/scripts/feedback-quality.js +139 -0
  168. package/scripts/feedback-root-consolidator.js +238 -0
  169. package/scripts/feedback-schema.js +426 -0
  170. package/scripts/feedback-session.js +286 -0
  171. package/scripts/feedback-to-memory.js +185 -0
  172. package/scripts/feedback-to-rules.js +163 -0
  173. package/scripts/filesystem-search.js +404 -0
  174. package/scripts/funnel-analytics.js +35 -0
  175. package/scripts/gate-satisfy.js +42 -0
  176. package/scripts/gate-stats.js +116 -0
  177. package/scripts/gate-templates.js +70 -0
  178. package/scripts/gates-engine.js +816 -0
  179. package/scripts/generate-paperbanana-diagrams.sh +99 -0
  180. package/scripts/generate-pretool-hook.sh +40 -0
  181. package/scripts/github-about.js +350 -0
  182. package/scripts/github-outreach.js +65 -0
  183. package/scripts/gtm-revenue-loop.js +520 -0
  184. package/scripts/hallucination-detector.js +226 -0
  185. package/scripts/hf-papers.js +317 -0
  186. package/scripts/history-distiller.js +200 -0
  187. package/scripts/hook-auto-capture.sh +95 -0
  188. package/scripts/hook-stop-pr-thread-check.sh +68 -0
  189. package/scripts/hook-stop-self-score.sh +51 -0
  190. package/scripts/hook-stop-verify-deploy.sh +31 -0
  191. package/scripts/hook-thumbgate-cache-updater.js +48 -0
  192. package/scripts/hook-verify-before-done.sh +20 -0
  193. package/scripts/hosted-config.js +170 -0
  194. package/scripts/hybrid-feedback-context.js +676 -0
  195. package/scripts/install-mcp.js +159 -0
  196. package/scripts/intent-router.js +392 -0
  197. package/scripts/internal-agent-bootstrap.js +490 -0
  198. package/scripts/jsonl-watcher.js +155 -0
  199. package/scripts/lesson-db.js +613 -0
  200. package/scripts/lesson-inference.js +315 -0
  201. package/scripts/lesson-retrieval.js +95 -0
  202. package/scripts/lesson-rotation.js +137 -0
  203. package/scripts/lesson-search.js +644 -0
  204. package/scripts/lesson-synthesis.js +196 -0
  205. package/scripts/license.js +50 -0
  206. package/scripts/local-model-profile.js +383 -0
  207. package/scripts/markdown-escape.js +12 -0
  208. package/scripts/marketing-experiment.js +671 -0
  209. package/scripts/mcp-config.js +149 -0
  210. package/scripts/mcp-policy.js +99 -0
  211. package/scripts/memalign-recall.js +111 -0
  212. package/scripts/memory-firewall.js +222 -0
  213. package/scripts/memory-migration.js +296 -0
  214. package/scripts/meta-policy.js +194 -0
  215. package/scripts/metered-billing.js +16 -0
  216. package/scripts/model-tier-router.js +301 -0
  217. package/scripts/money-watcher.js +71 -0
  218. package/scripts/multi-hop-recall.js +240 -0
  219. package/scripts/natural-language-harness.js +330 -0
  220. package/scripts/obsidian-export.js +712 -0
  221. package/scripts/operational-dashboard.js +103 -0
  222. package/scripts/operational-summary.js +93 -0
  223. package/scripts/optimize-context.js +17 -0
  224. package/scripts/org-dashboard.js +201 -0
  225. package/scripts/partner-orchestration.js +146 -0
  226. package/scripts/per-step-scoring.js +165 -0
  227. package/scripts/perplexity-marketing.js +466 -0
  228. package/scripts/pii-scanner.js +153 -0
  229. package/scripts/plan-gate.js +154 -0
  230. package/scripts/post-everywhere.js +308 -0
  231. package/scripts/post-to-x-retry.sh +22 -0
  232. package/scripts/post-to-x.js +369 -0
  233. package/scripts/pr-manager.js +236 -0
  234. package/scripts/predictive-insights.js +356 -0
  235. package/scripts/principle-extractor.js +162 -0
  236. package/scripts/pro-features.js +40 -0
  237. package/scripts/pro-local-dashboard.js +174 -0
  238. package/scripts/problem-detail.js +53 -0
  239. package/scripts/product-feedback.js +134 -0
  240. package/scripts/profile-router.js +245 -0
  241. package/scripts/prompt-dlp.js +221 -0
  242. package/scripts/prompt-guard.js +83 -0
  243. package/scripts/prove-adapters.js +863 -0
  244. package/scripts/prove-attribution.js +365 -0
  245. package/scripts/prove-automation.js +653 -0
  246. package/scripts/prove-autoresearch.js +304 -0
  247. package/scripts/prove-claim-verification.js +277 -0
  248. package/scripts/prove-cloudflare-sandbox.js +163 -0
  249. package/scripts/prove-data-pipeline.js +410 -0
  250. package/scripts/prove-data-quality.js +227 -0
  251. package/scripts/prove-evolution.js +352 -0
  252. package/scripts/prove-harnesses.js +287 -0
  253. package/scripts/prove-intelligence.js +259 -0
  254. package/scripts/prove-lancedb.js +371 -0
  255. package/scripts/prove-local-intelligence.js +342 -0
  256. package/scripts/prove-loop-closure.js +263 -0
  257. package/scripts/prove-predictive-insights.js +357 -0
  258. package/scripts/prove-runtime.js +350 -0
  259. package/scripts/prove-seo-gsd.js +234 -0
  260. package/scripts/prove-settings.js +279 -0
  261. package/scripts/prove-subway-upgrades.js +277 -0
  262. package/scripts/prove-tessl.js +229 -0
  263. package/scripts/prove-training-export.js +327 -0
  264. package/scripts/prove-workflow-contract.js +116 -0
  265. package/scripts/prove-xmemory.js +332 -0
  266. package/scripts/publish-decision.js +133 -0
  267. package/scripts/pulse.js +80 -0
  268. package/scripts/rate-limiter.js +125 -0
  269. package/scripts/reddit-dm-outreach.js +182 -0
  270. package/scripts/reddit-monitor-cron.sh +26 -0
  271. package/scripts/reflector-agent.js +221 -0
  272. package/scripts/reminder-engine.js +132 -0
  273. package/scripts/revenue-status.js +472 -0
  274. package/scripts/risk-scorer.js +458 -0
  275. package/scripts/rlaif-self-audit.js +129 -0
  276. package/scripts/rubric-engine.js +230 -0
  277. package/scripts/schedule-manager.js +251 -0
  278. package/scripts/secret-scanner.js +414 -0
  279. package/scripts/self-heal.js +147 -0
  280. package/scripts/self-healing-check.js +188 -0
  281. package/scripts/semantic-layer.js +98 -0
  282. package/scripts/seo-gsd.js +1153 -0
  283. package/scripts/settings-hierarchy.js +214 -0
  284. package/scripts/shieldcortex-memory-firewall-runner.mjs +53 -0
  285. package/scripts/skill-exporter.js +262 -0
  286. package/scripts/skill-generator.js +446 -0
  287. package/scripts/skill-materializer.js +134 -0
  288. package/scripts/skill-packs.js +136 -0
  289. package/scripts/skill-proposer.js +99 -0
  290. package/scripts/skill-quality-tracker.js +284 -0
  291. package/scripts/slo-alert-engine.js +14 -0
  292. package/scripts/slow-loop.js +72 -0
  293. package/scripts/social-analytics/db/schema.sql +32 -0
  294. package/scripts/social-analytics/digest.js +256 -0
  295. package/scripts/social-analytics/generate-instagram-card.js +97 -0
  296. package/scripts/social-analytics/instagram-thumbgate-post.js +73 -0
  297. package/scripts/social-analytics/mcp-server.js +289 -0
  298. package/scripts/social-analytics/normalizer.js +580 -0
  299. package/scripts/social-analytics/notify.js +162 -0
  300. package/scripts/social-analytics/poll-all.js +107 -0
  301. package/scripts/social-analytics/pollers/github.js +195 -0
  302. package/scripts/social-analytics/pollers/instagram.js +253 -0
  303. package/scripts/social-analytics/pollers/linkedin.js +330 -0
  304. package/scripts/social-analytics/pollers/plausible.js +247 -0
  305. package/scripts/social-analytics/pollers/reddit.js +306 -0
  306. package/scripts/social-analytics/pollers/threads.js +233 -0
  307. package/scripts/social-analytics/pollers/tiktok.js +203 -0
  308. package/scripts/social-analytics/pollers/x.js +227 -0
  309. package/scripts/social-analytics/pollers/youtube.js +304 -0
  310. package/scripts/social-analytics/pollers/zernio.js +180 -0
  311. package/scripts/social-analytics/publish-instagram-thumbgate.js +85 -0
  312. package/scripts/social-analytics/publishers/devto.js +122 -0
  313. package/scripts/social-analytics/publishers/instagram.js +317 -0
  314. package/scripts/social-analytics/publishers/linkedin.js +294 -0
  315. package/scripts/social-analytics/publishers/reddit.js +390 -0
  316. package/scripts/social-analytics/publishers/threads.js +275 -0
  317. package/scripts/social-analytics/publishers/tiktok.js +217 -0
  318. package/scripts/social-analytics/publishers/x.js +259 -0
  319. package/scripts/social-analytics/publishers/youtube.js +223 -0
  320. package/scripts/social-analytics/publishers/zernio.js +209 -0
  321. package/scripts/social-analytics/run-digest.js +34 -0
  322. package/scripts/social-analytics/store.js +257 -0
  323. package/scripts/social-analytics/utm.js +143 -0
  324. package/scripts/social-pipeline.js +2628 -0
  325. package/scripts/social-quality-gate.js +18 -0
  326. package/scripts/social-reply-monitor.js +445 -0
  327. package/scripts/status-dashboard.js +155 -0
  328. package/scripts/statusline-lesson.js +16 -0
  329. package/scripts/statusline-tower.js +8 -0
  330. package/scripts/statusline.sh +116 -0
  331. package/scripts/stripe-live-status.js +115 -0
  332. package/scripts/subagent-profiles.js +79 -0
  333. package/scripts/sync-gh-secrets-from-env.sh +70 -0
  334. package/scripts/sync-github-about.js +52 -0
  335. package/scripts/sync-version.js +451 -0
  336. package/scripts/synthetic-dpo.js +234 -0
  337. package/scripts/telemetry-analytics.js +821 -0
  338. package/scripts/tessl-export.js +371 -0
  339. package/scripts/test-coverage.js +120 -0
  340. package/scripts/thompson-sampling.js +417 -0
  341. package/scripts/thumbgate-search.js +189 -0
  342. package/scripts/tool-kpi-tracker.js +12 -0
  343. package/scripts/tool-registry.js +811 -0
  344. package/scripts/train_from_feedback.py +910 -0
  345. package/scripts/user-profile.js +78 -0
  346. package/scripts/validate-feedback.js +580 -0
  347. package/scripts/validate-workflow-contract.js +287 -0
  348. package/scripts/vector-store.js +198 -0
  349. package/scripts/verification-loop.js +291 -0
  350. package/scripts/verify-obsidian-setup.sh +269 -0
  351. package/scripts/verify-run.js +269 -0
  352. package/scripts/webhook-delivery.js +62 -0
  353. package/scripts/weekly-auto-post.js +124 -0
  354. package/scripts/workflow-runs.js +154 -0
  355. package/scripts/workflow-sprint-intake.js +475 -0
  356. package/scripts/workspace-evolver.js +374 -0
  357. package/scripts/x-autonomous-marketing.js +139 -0
  358. package/scripts/xmemory-lite.js +405 -0
  359. package/skills/agent-memory/SKILL.md +97 -0
  360. package/skills/solve-architecture-autonomy/SKILL.md +17 -0
  361. package/skills/solve-architecture-autonomy/tool.js +33 -0
  362. package/skills/thumbgate/SKILL.md +114 -0
  363. package/skills/thumbgate-feedback/SKILL.md +49 -0
  364. package/src/api/server.js +4208 -0
@@ -0,0 +1,1001 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const { spawnSync } = require('child_process');
6
+
7
+ const { captureFeedback, analyzeFeedback, getFeedbackPaths, readJSONL } = require('./feedback-loop');
8
+ const { runVerificationLoop } = require('./verification-loop');
9
+ const { createExperiment } = require('./experiment-tracker');
10
+ const { recommendEvolutionTarget } = require('./workspace-evolver');
11
+
12
+ const JOB_LOG_FILENAME = 'job-log.jsonl';
13
+ const JOB_CONTROL_FILENAME = 'job-control.json';
14
+ const JOB_STATE_DIRNAME = 'jobs';
15
+
16
+ const RESUMABLE_STATUSES = new Set(['paused', 'running', 'resume_requested']);
17
+ const TERMINAL_STATUSES = new Set(['completed', 'failed', 'cancelled']);
18
+ const CONTROL_ACTIONS = new Set(['pause', 'cancel', 'resume']);
19
+
20
+ function ensureDir(dirPath) {
21
+ if (!fs.existsSync(dirPath)) {
22
+ fs.mkdirSync(dirPath, { recursive: true });
23
+ }
24
+ }
25
+
26
+ function nowIso() {
27
+ return new Date().toISOString();
28
+ }
29
+
30
+ function generateJobId() {
31
+ return `job_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
32
+ }
33
+
34
+ function readJson(filePath) {
35
+ if (!fs.existsSync(filePath)) return null;
36
+ try {
37
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
38
+ } catch {
39
+ return null;
40
+ }
41
+ }
42
+
43
+ function writeJson(filePath, value) {
44
+ ensureDir(path.dirname(filePath));
45
+ fs.writeFileSync(filePath, JSON.stringify(value, null, 2) + '\n', 'utf8');
46
+ }
47
+
48
+ function appendJSONL(filePath, record) {
49
+ ensureDir(path.dirname(filePath));
50
+ fs.appendFileSync(filePath, `${JSON.stringify(record)}\n`);
51
+ }
52
+
53
+ function getJobRuntimePaths(jobId) {
54
+ const { FEEDBACK_DIR } = getFeedbackPaths();
55
+ const jobsDir = path.join(FEEDBACK_DIR, JOB_STATE_DIRNAME);
56
+ const jobDir = jobId ? path.join(jobsDir, jobId) : null;
57
+ return {
58
+ feedbackDir: FEEDBACK_DIR,
59
+ jobsDir,
60
+ jobDir,
61
+ statePath: jobDir ? path.join(jobDir, 'state.json') : null,
62
+ controlPath: jobDir ? path.join(jobDir, JOB_CONTROL_FILENAME) : null,
63
+ logPath: path.join(FEEDBACK_DIR, JOB_LOG_FILENAME),
64
+ };
65
+ }
66
+
67
+ /**
68
+ * Recall relevant context before executing a task.
69
+ * Pulls recent feedback analysis and prevention rules for the given domain.
70
+ *
71
+ * @param {object} params
72
+ * @param {string[]} [params.tags] - Domain tags to filter context
73
+ * @returns {object} { approvalRate, riskDomains, recommendations }
74
+ */
75
+ function recallContext(params) {
76
+ const analysis = analyzeFeedback();
77
+ const { MEMORY_LOG_PATH } = getFeedbackPaths();
78
+ const memories = readJSONL(MEMORY_LOG_PATH);
79
+ const errorMemories = memories.filter((memory) => memory.category === 'error');
80
+
81
+ const tags = Array.isArray(params.tags) ? params.tags : [];
82
+ let riskDomains = [];
83
+
84
+ if (analysis.boostedRisk && Array.isArray(analysis.boostedRisk.highRiskDomains)) {
85
+ riskDomains = analysis.boostedRisk.highRiskDomains
86
+ .filter((domain) => !tags.length || tags.some((tag) => domain.key.includes(tag)))
87
+ .map((domain) => ({ domain: domain.key, riskRate: domain.riskRate }));
88
+ }
89
+
90
+ return {
91
+ totalFeedback: analysis.total,
92
+ approvalRate: analysis.approvalRate,
93
+ recentRate: analysis.recentRate,
94
+ riskDomains,
95
+ preventionRuleCount: errorMemories.length,
96
+ recommendations: Array.isArray(analysis.recommendations) ? analysis.recommendations.slice(0, 5) : [],
97
+ };
98
+ }
99
+
100
+ function normalizeStages(job) {
101
+ if (Array.isArray(job.stages) && job.stages.length > 0) {
102
+ return job.stages.map((stage, index) => ({
103
+ ...(typeof stage === 'object' && stage ? stage : { context: String(stage || '') }),
104
+ name: stage && stage.name ? stage.name : `stage_${index + 1}`,
105
+ }));
106
+ }
107
+
108
+ if (typeof job.taskFn === 'function') {
109
+ return [{ name: 'task', taskFn: job.taskFn }];
110
+ }
111
+
112
+ return [{
113
+ name: 'task',
114
+ context: typeof job.context === 'string' ? job.context : '',
115
+ }];
116
+ }
117
+
118
+ function serializeStage(stage) {
119
+ const serialized = { name: stage.name };
120
+ if (typeof stage.context === 'string') serialized.context = stage.context;
121
+ if (typeof stage.appendContext === 'string') serialized.appendContext = stage.appendContext;
122
+ if (typeof stage.command === 'string') serialized.command = stage.command;
123
+ if (typeof stage.workingDirectory === 'string') serialized.workingDirectory = stage.workingDirectory;
124
+ return serialized;
125
+ }
126
+
127
+ function serializeJobForState(job) {
128
+ const stages = normalizeStages(job).map(serializeStage);
129
+ return {
130
+ id: job.id || null,
131
+ tags: Array.isArray(job.tags) ? job.tags : [],
132
+ skill: job.skill || null,
133
+ partnerProfile: job.partnerProfile || null,
134
+ autoImprove: job.autoImprove !== false,
135
+ jobFilePath: job.jobFilePath || null,
136
+ stages,
137
+ };
138
+ }
139
+
140
+ function readJobState(jobId) {
141
+ if (!jobId) return null;
142
+ return readJson(getJobRuntimePaths(jobId).statePath);
143
+ }
144
+
145
+ function writeJobState(state) {
146
+ const paths = getJobRuntimePaths(state.jobId);
147
+ ensureDir(paths.jobDir);
148
+ writeJson(paths.statePath, state);
149
+ return state;
150
+ }
151
+
152
+ function listJobStates(options = {}) {
153
+ const { jobsDir } = getJobRuntimePaths();
154
+ if (!fs.existsSync(jobsDir)) return [];
155
+
156
+ const statuses = Array.isArray(options.statuses) && options.statuses.length > 0
157
+ ? new Set(options.statuses)
158
+ : null;
159
+
160
+ const results = fs.readdirSync(jobsDir)
161
+ .map((entry) => readJson(path.join(jobsDir, entry, 'state.json')))
162
+ .filter(Boolean)
163
+ .filter((entry) => !statuses || statuses.has(entry.status))
164
+ .sort((left, right) => {
165
+ const leftTs = Date.parse(left.updatedAt || left.startedAt || left.createdAt || 0);
166
+ const rightTs = Date.parse(right.updatedAt || right.startedAt || right.createdAt || 0);
167
+ return rightTs - leftTs;
168
+ });
169
+
170
+ const limit = Number(options.limit || 0);
171
+ return limit > 0 ? results.slice(0, limit) : results;
172
+ }
173
+
174
+ function readJobControl(jobId) {
175
+ if (!jobId) return null;
176
+ return readJson(getJobRuntimePaths(jobId).controlPath);
177
+ }
178
+
179
+ function clearJobControl(jobId) {
180
+ if (!jobId) return;
181
+ const { controlPath } = getJobRuntimePaths(jobId);
182
+ if (controlPath && fs.existsSync(controlPath)) {
183
+ fs.unlinkSync(controlPath);
184
+ }
185
+ }
186
+
187
+ function requestJobControl(jobId, action, metadata = {}) {
188
+ if (!jobId) throw new Error('requestJobControl requires jobId');
189
+ if (!CONTROL_ACTIONS.has(action)) {
190
+ throw new Error(`Unsupported control action: ${action}`);
191
+ }
192
+
193
+ const requestedAt = nowIso();
194
+ const control = {
195
+ jobId,
196
+ action,
197
+ metadata: metadata || {},
198
+ requestedAt,
199
+ };
200
+ const { controlPath } = getJobRuntimePaths(jobId);
201
+ writeJson(controlPath, control);
202
+
203
+ if (action === 'resume') {
204
+ const state = readJobState(jobId);
205
+ if (state && !TERMINAL_STATUSES.has(state.status)) {
206
+ writeJobState({
207
+ ...state,
208
+ status: 'resume_requested',
209
+ updatedAt: requestedAt,
210
+ });
211
+ }
212
+ }
213
+
214
+ return control;
215
+ }
216
+
217
+ function buildExecutionSummary(state) {
218
+ return {
219
+ totalStages: state.totalStages || 0,
220
+ completedStages: Array.isArray(state.stageHistory) ? state.stageHistory.length : 0,
221
+ nextStageIndex: state.nextStageIndex || 0,
222
+ currentStage: state.currentStage || null,
223
+ checkpointCount: Array.isArray(state.checkpoints) ? state.checkpoints.length : 0,
224
+ jobFilePath: state.jobFilePath || null,
225
+ };
226
+ }
227
+
228
+ function buildResult({ state, recall, verification, feedback, improvementExperiment }) {
229
+ const startedAtMs = Date.parse(state.startedAt || state.createdAt || nowIso());
230
+ const durationMs = Number.isFinite(startedAtMs)
231
+ ? Math.max(0, Date.now() - startedAtMs)
232
+ : 0;
233
+
234
+ return {
235
+ jobId: state.jobId,
236
+ status: state.status,
237
+ phases: {
238
+ recall: {
239
+ approvalRate: recall.approvalRate,
240
+ preventionRuleCount: recall.preventionRuleCount,
241
+ riskDomains: recall.riskDomains,
242
+ },
243
+ execution: buildExecutionSummary(state),
244
+ verification: verification ? {
245
+ accepted: verification.accepted,
246
+ attempts: verification.attempts,
247
+ score: verification.finalVerification ? verification.finalVerification.score : 0,
248
+ partnerProfile: verification.partnerStrategy.profile,
249
+ verificationMode: verification.partnerStrategy.verificationMode,
250
+ reward: verification.partnerReward.reward,
251
+ } : null,
252
+ feedback: feedback ? {
253
+ accepted: feedback.accepted,
254
+ status: feedback.status,
255
+ } : null,
256
+ evolution: improvementExperiment ? {
257
+ experimentId: improvementExperiment.id,
258
+ mutationType: improvementExperiment.mutationType,
259
+ } : null,
260
+ },
261
+ durationMs,
262
+ timestamp: nowIso(),
263
+ };
264
+ }
265
+
266
+ function appendJobLog(result) {
267
+ appendJSONL(getJobRuntimePaths(result.jobId).logPath, result);
268
+ }
269
+
270
+ function readJobLog(limit) {
271
+ const entries = readJSONL(getJobRuntimePaths().logPath);
272
+ return limit ? entries.slice(-limit) : entries;
273
+ }
274
+
275
+ function getJobStats() {
276
+ const entries = readJobLog();
277
+ if (entries.length === 0) {
278
+ return {
279
+ totalJobs: 0,
280
+ completed: 0,
281
+ failed: 0,
282
+ paused: 0,
283
+ cancelled: 0,
284
+ avgDurationMs: 0,
285
+ avgAttempts: 0,
286
+ };
287
+ }
288
+
289
+ const completed = entries.filter((entry) => entry.status === 'completed').length;
290
+ const failed = entries.filter((entry) => entry.status === 'failed').length;
291
+ const paused = entries.filter((entry) => entry.status === 'paused').length;
292
+ const cancelled = entries.filter((entry) => entry.status === 'cancelled').length;
293
+ const totalDuration = entries.reduce((sum, entry) => sum + (entry.durationMs || 0), 0);
294
+ const totalAttempts = entries.reduce((sum, entry) => {
295
+ return sum + ((entry.phases && entry.phases.verification && entry.phases.verification.attempts) || 0);
296
+ }, 0);
297
+
298
+ return {
299
+ totalJobs: entries.length,
300
+ completed,
301
+ failed,
302
+ paused,
303
+ cancelled,
304
+ successRate: Math.round((completed / entries.length) * 1000) / 1000,
305
+ avgDurationMs: Math.round(totalDuration / entries.length),
306
+ avgAttempts: Math.round((totalAttempts / Math.max(entries.length, 1)) * 100) / 100,
307
+ };
308
+ }
309
+
310
+ function shellConfig(command) {
311
+ if (process.platform === 'win32') {
312
+ return {
313
+ command: process.env.ComSpec || 'cmd.exe',
314
+ args: ['/d', '/s', '/c', command],
315
+ };
316
+ }
317
+
318
+ return {
319
+ command: process.env.SHELL || '/bin/sh',
320
+ args: ['-lc', command],
321
+ };
322
+ }
323
+
324
+ function normalizeStageResult(result, currentContext) {
325
+ if (typeof result === 'string') {
326
+ return { context: result };
327
+ }
328
+
329
+ if (result == null) {
330
+ return { context: currentContext };
331
+ }
332
+
333
+ if (typeof result !== 'object') {
334
+ return { context: String(result) };
335
+ }
336
+
337
+ return {
338
+ ...result,
339
+ context: typeof result.context === 'string' ? result.context : undefined,
340
+ appendContext: typeof result.appendContext === 'string' ? result.appendContext : undefined,
341
+ };
342
+ }
343
+
344
+ function applyStageContext(currentContext, stageResult) {
345
+ if (typeof stageResult.context === 'string') {
346
+ return stageResult.context;
347
+ }
348
+
349
+ if (typeof stageResult.appendContext === 'string') {
350
+ return [currentContext, stageResult.appendContext].filter(Boolean).join('\n');
351
+ }
352
+
353
+ return currentContext;
354
+ }
355
+
356
+ function runCommandStage(stage) {
357
+ const shell = shellConfig(stage.command);
358
+ const result = spawnSync(shell.command, shell.args, {
359
+ cwd: stage.workingDirectory || process.cwd(),
360
+ env: process.env,
361
+ encoding: 'utf8',
362
+ stdio: 'pipe',
363
+ });
364
+
365
+ if (result.status !== 0) {
366
+ const stderr = (result.stderr || '').trim();
367
+ const stdout = (result.stdout || '').trim();
368
+ const error = new Error([
369
+ `Stage "${stage.name}" command failed`,
370
+ stderr || stdout || `exit ${result.status}`,
371
+ ].join(': '));
372
+ error.code = 'JOB_STAGE_FAILED';
373
+ error.stdout = result.stdout || '';
374
+ error.stderr = result.stderr || '';
375
+ throw error;
376
+ }
377
+
378
+ const stdout = (result.stdout || '').trim();
379
+ return stdout ? { context: stdout } : {};
380
+ }
381
+
382
+ function createExecutionController(jobId, recall, sharedState) {
383
+ return {
384
+ jobId,
385
+ recall,
386
+ checkpoint(label, data = {}) {
387
+ const latest = readJobState(jobId) || sharedState;
388
+ const timestamp = nowIso();
389
+ const checkpoint = {
390
+ label: label || `checkpoint_${(latest.checkpoints || []).length + 1}`,
391
+ stageIndex: latest.nextStageIndex || 0,
392
+ timestamp,
393
+ ...data,
394
+ };
395
+ const updated = {
396
+ ...latest,
397
+ checkpoints: [...(latest.checkpoints || []), checkpoint],
398
+ updatedAt: timestamp,
399
+ };
400
+ if (typeof data.context === 'string') {
401
+ updated.currentContext = data.context;
402
+ }
403
+ writeJobState(updated);
404
+ Object.assign(sharedState, updated);
405
+ return checkpoint;
406
+ },
407
+ getState() {
408
+ return readJobState(jobId) || sharedState;
409
+ },
410
+ readControl() {
411
+ return readJobControl(jobId);
412
+ },
413
+ requestPause(metadata = {}) {
414
+ return requestJobControl(jobId, 'pause', metadata);
415
+ },
416
+ requestCancel(metadata = {}) {
417
+ return requestJobControl(jobId, 'cancel', metadata);
418
+ },
419
+ shouldPause() {
420
+ const control = readJobControl(jobId);
421
+ return Boolean(control && control.action === 'pause');
422
+ },
423
+ throwIfCancelled() {
424
+ const control = readJobControl(jobId);
425
+ if (control && control.action === 'cancel') {
426
+ const error = new Error('Job cancelled');
427
+ error.code = 'JOB_CANCELLED';
428
+ throw error;
429
+ }
430
+ },
431
+ };
432
+ }
433
+
434
+ function maybeFinishFromControl(jobId, state, recall) {
435
+ const control = readJobControl(jobId);
436
+ if (!control) return null;
437
+
438
+ if (control.action === 'resume') {
439
+ clearJobControl(jobId);
440
+ const resumed = writeJobState({
441
+ ...state,
442
+ status: 'running',
443
+ updatedAt: nowIso(),
444
+ resumedAt: nowIso(),
445
+ });
446
+ Object.assign(state, resumed);
447
+ return null;
448
+ }
449
+
450
+ if (control.action === 'pause') {
451
+ const pausedState = writeJobState({
452
+ ...state,
453
+ status: 'paused',
454
+ updatedAt: nowIso(),
455
+ pausedAt: nowIso(),
456
+ stopReason: 'pause_requested',
457
+ });
458
+ clearJobControl(jobId);
459
+ const result = buildResult({
460
+ state: pausedState,
461
+ recall,
462
+ verification: null,
463
+ feedback: null,
464
+ improvementExperiment: null,
465
+ });
466
+ appendJobLog(result);
467
+ return result;
468
+ }
469
+
470
+ if (control.action === 'cancel') {
471
+ const cancelledState = writeJobState({
472
+ ...state,
473
+ status: 'cancelled',
474
+ updatedAt: nowIso(),
475
+ endedAt: nowIso(),
476
+ stopReason: 'cancel_requested',
477
+ });
478
+ clearJobControl(jobId);
479
+ const result = buildResult({
480
+ state: cancelledState,
481
+ recall,
482
+ verification: null,
483
+ feedback: null,
484
+ improvementExperiment: null,
485
+ });
486
+ appendJobLog(result);
487
+ return result;
488
+ }
489
+
490
+ return null;
491
+ }
492
+
493
+ function maybeQueueImprovementExperiment(job, state, recall, failure) {
494
+ if (job.autoImprove === false) return null;
495
+
496
+ const recommendations = Array.isArray(recall.recommendations) ? recall.recommendations.slice(0, 2) : [];
497
+ const recommendedTarget = recommendEvolutionTarget({
498
+ failureType: failure ? failure.type : null,
499
+ tags: Array.isArray(job.tags) ? job.tags : [],
500
+ });
501
+ let summary = 'Improve the job prompt or stage plan to reduce runtime failures.';
502
+ let mutation = {
503
+ source: 'async-job-runner',
504
+ jobId: state.jobId,
505
+ jobFilePath: state.jobFilePath || null,
506
+ stage: state.currentStage || null,
507
+ recommendations,
508
+ recommendedTarget,
509
+ evolutionCommand: `node scripts/workspace-evolver.js --run --target=${recommendedTarget} --primary="npm test" --holdout="npm run self-heal:check"`,
510
+ };
511
+
512
+ if (failure && failure.type === 'verification') {
513
+ const firstViolation = failure.verification.finalVerification
514
+ && Array.isArray(failure.verification.finalVerification.violations)
515
+ ? failure.verification.finalVerification.violations[0]
516
+ : null;
517
+ summary = firstViolation && firstViolation.avoidRule
518
+ ? firstViolation.avoidRule
519
+ : 'Improve the output so it avoids known mistake patterns.';
520
+ mutation = {
521
+ ...mutation,
522
+ failureType: 'verification',
523
+ attempts: failure.verification.attempts,
524
+ violationPattern: firstViolation ? firstViolation.pattern : null,
525
+ avoidRule: firstViolation ? firstViolation.avoidRule : null,
526
+ };
527
+ } else if (failure && failure.type === 'execution') {
528
+ summary = failure.error && failure.error.message
529
+ ? failure.error.message
530
+ : 'A stage failed before verification.';
531
+ mutation = {
532
+ ...mutation,
533
+ failureType: 'execution',
534
+ errorCode: failure.error && failure.error.code ? failure.error.code : null,
535
+ errorMessage: failure.error && failure.error.message ? failure.error.message : 'unknown execution error',
536
+ };
537
+ }
538
+
539
+ try {
540
+ return createExperiment({
541
+ name: `job:${state.jobId}:${failure ? failure.type : 'followup'}`,
542
+ hypothesis: [summary, ...recommendations].filter(Boolean).join(' '),
543
+ mutationType: 'prompt',
544
+ mutation,
545
+ });
546
+ } catch {
547
+ return null;
548
+ }
549
+ }
550
+
551
+ function runStage(stage, recall, currentContext, controller) {
552
+ if (typeof stage.taskFn === 'function') {
553
+ return normalizeStageResult(stage.taskFn({
554
+ recall,
555
+ currentContext,
556
+ controller,
557
+ stage,
558
+ state: controller.getState(),
559
+ }), currentContext);
560
+ }
561
+
562
+ if (typeof stage.run === 'function') {
563
+ return normalizeStageResult(stage.run({
564
+ recall,
565
+ currentContext,
566
+ controller,
567
+ stage,
568
+ state: controller.getState(),
569
+ }), currentContext);
570
+ }
571
+
572
+ if (typeof stage.command === 'string') {
573
+ return normalizeStageResult(runCommandStage(stage), currentContext);
574
+ }
575
+
576
+ if (typeof stage.context === 'string') {
577
+ return { context: stage.context };
578
+ }
579
+
580
+ if (typeof stage.appendContext === 'string') {
581
+ return { appendContext: stage.appendContext };
582
+ }
583
+
584
+ return { context: currentContext };
585
+ }
586
+
587
+ function resumeJob(jobId, job = null, options = {}) {
588
+ const state = readJobState(jobId);
589
+ if (!state) {
590
+ throw new Error(`No persisted state found for job ${jobId}`);
591
+ }
592
+
593
+ if (state.jobFilePath) {
594
+ return runJobFromFile(state.jobFilePath, { ...options, resume: true });
595
+ }
596
+
597
+ if (job) {
598
+ return executeJob({ ...job, id: jobId }, { ...options, resume: true, previousState: state });
599
+ }
600
+
601
+ if (state.jobSpec && Array.isArray(state.jobSpec.stages) && state.jobSpec.stages.length > 0) {
602
+ return executeJob({ ...state.jobSpec, id: jobId }, { ...options, resume: true, previousState: state });
603
+ }
604
+
605
+ throw new Error(`Job ${jobId} cannot be resumed automatically without a job file or serializable stages`);
606
+ }
607
+
608
+ /**
609
+ * Execute a single job through the full pipeline: recall → stages → verify → feedback.
610
+ *
611
+ * @param {object} job
612
+ * @returns {object} Job execution result
613
+ */
614
+ function executeJob(job, options = {}) {
615
+ const started = Date.now();
616
+ const normalizedJob = {
617
+ ...job,
618
+ id: job.id || generateJobId(),
619
+ tags: Array.isArray(job.tags) ? job.tags : [],
620
+ autoImprove: job.autoImprove !== false,
621
+ stages: normalizeStages(job),
622
+ };
623
+ const previousState = options.previousState || readJobState(normalizedJob.id);
624
+ const shouldResume = Boolean(
625
+ previousState
626
+ && RESUMABLE_STATUSES.has(previousState.status)
627
+ && (options.resume === true || normalizedJob.autoResume !== false)
628
+ );
629
+
630
+ const recall = recallContext({ tags: normalizedJob.tags });
631
+ let currentContext = shouldResume ? (previousState.currentContext || '') : '';
632
+ let nextStageIndex = shouldResume ? (previousState.nextStageIndex || 0) : 0;
633
+
634
+ const state = writeJobState({
635
+ jobId: normalizedJob.id,
636
+ status: 'running',
637
+ createdAt: previousState && previousState.createdAt ? previousState.createdAt : nowIso(),
638
+ startedAt: previousState && previousState.startedAt ? previousState.startedAt : nowIso(),
639
+ resumedAt: shouldResume ? nowIso() : null,
640
+ updatedAt: nowIso(),
641
+ endedAt: null,
642
+ tags: normalizedJob.tags,
643
+ skill: normalizedJob.skill || null,
644
+ partnerProfile: normalizedJob.partnerProfile || null,
645
+ autoImprove: normalizedJob.autoImprove,
646
+ totalStages: normalizedJob.stages.length,
647
+ nextStageIndex,
648
+ currentStage: normalizedJob.stages[nextStageIndex] ? normalizedJob.stages[nextStageIndex].name : 'verification',
649
+ currentContext,
650
+ checkpoints: previousState && Array.isArray(previousState.checkpoints) ? previousState.checkpoints : [],
651
+ stageHistory: previousState && Array.isArray(previousState.stageHistory) ? previousState.stageHistory : [],
652
+ jobFilePath: normalizedJob.jobFilePath || (previousState ? previousState.jobFilePath : null) || null,
653
+ jobSpec: previousState && previousState.jobSpec ? previousState.jobSpec : serializeJobForState(normalizedJob),
654
+ lastError: null,
655
+ stopReason: null,
656
+ improvementExperimentId: previousState ? previousState.improvementExperimentId || null : null,
657
+ });
658
+ const controller = createExecutionController(normalizedJob.id, recall, state);
659
+
660
+ const preRunResult = maybeFinishFromControl(normalizedJob.id, state, recall);
661
+ if (preRunResult) return preRunResult;
662
+
663
+ for (let index = nextStageIndex; index < normalizedJob.stages.length; index += 1) {
664
+ const stage = normalizedJob.stages[index];
665
+ writeJobState({
666
+ ...state,
667
+ status: 'running',
668
+ updatedAt: nowIso(),
669
+ nextStageIndex: index,
670
+ currentStage: stage.name,
671
+ currentContext,
672
+ });
673
+
674
+ const stageControlResult = maybeFinishFromControl(normalizedJob.id, readJobState(normalizedJob.id), recall);
675
+ if (stageControlResult) return stageControlResult;
676
+
677
+ try {
678
+ controller.throwIfCancelled();
679
+ const stageResult = runStage(stage, recall, currentContext, controller);
680
+ currentContext = applyStageContext(currentContext, stageResult);
681
+
682
+ const updatedState = writeJobState({
683
+ ...(readJobState(normalizedJob.id) || state),
684
+ status: 'running',
685
+ updatedAt: nowIso(),
686
+ nextStageIndex: index + 1,
687
+ currentStage: normalizedJob.stages[index + 1] ? normalizedJob.stages[index + 1].name : 'verification',
688
+ currentContext,
689
+ stageHistory: [
690
+ ...((readJobState(normalizedJob.id) || state).stageHistory || []),
691
+ {
692
+ name: stage.name,
693
+ index,
694
+ completedAt: nowIso(),
695
+ metadata: stageResult.metadata || null,
696
+ },
697
+ ],
698
+ });
699
+ Object.assign(state, updatedState);
700
+
701
+ controller.checkpoint(stageResult.checkpointLabel || `stage:${stage.name}`, {
702
+ stageIndex: index,
703
+ context: currentContext,
704
+ metadata: stageResult.metadata || null,
705
+ });
706
+
707
+ const postStageResult = maybeFinishFromControl(normalizedJob.id, readJobState(normalizedJob.id), recall);
708
+ if (postStageResult) return postStageResult;
709
+ } catch (error) {
710
+ const failedState = writeJobState({
711
+ ...(readJobState(normalizedJob.id) || state),
712
+ status: error && error.code === 'JOB_CANCELLED' ? 'cancelled' : 'failed',
713
+ updatedAt: nowIso(),
714
+ endedAt: nowIso(),
715
+ currentContext,
716
+ lastError: {
717
+ message: error && error.message ? error.message : 'unknown execution error',
718
+ code: error && error.code ? error.code : 'JOB_STAGE_FAILED',
719
+ },
720
+ });
721
+
722
+ const improvementExperiment = error && error.code === 'JOB_CANCELLED'
723
+ ? null
724
+ : maybeQueueImprovementExperiment(normalizedJob, failedState, recall, {
725
+ type: 'execution',
726
+ error,
727
+ });
728
+
729
+ if (improvementExperiment) {
730
+ failedState.improvementExperimentId = improvementExperiment.id;
731
+ writeJobState(failedState);
732
+ }
733
+
734
+ clearJobControl(normalizedJob.id);
735
+
736
+ const feedback = error && error.code === 'JOB_CANCELLED'
737
+ ? null
738
+ : captureFeedback({
739
+ signal: 'down',
740
+ context: `Job ${normalizedJob.id} failed during stage "${failedState.currentStage || 'unknown'}"`,
741
+ whatWentWrong: error && error.message ? error.message : 'Stage execution failed',
742
+ whatToChange: 'Resume from the last checkpoint after updating the failed stage or command',
743
+ tags: [...normalizedJob.tags, 'async-job-runner', 'execution-loop'],
744
+ skill: normalizedJob.skill || 'async-job-runner',
745
+ });
746
+
747
+ const result = buildResult({
748
+ state: failedState,
749
+ recall,
750
+ verification: null,
751
+ feedback,
752
+ improvementExperiment,
753
+ });
754
+ appendJobLog(result);
755
+ return result;
756
+ }
757
+ }
758
+
759
+ const verification = runVerificationLoop({
760
+ context: currentContext,
761
+ tags: normalizedJob.tags,
762
+ skill: normalizedJob.skill,
763
+ partnerProfile: normalizedJob.partnerProfile,
764
+ onRetry: normalizedJob.onRetry,
765
+ maxRetries: normalizedJob.maxRetries,
766
+ });
767
+
768
+ const improvementExperiment = verification.accepted
769
+ ? null
770
+ : maybeQueueImprovementExperiment(normalizedJob, state, recall, {
771
+ type: 'verification',
772
+ verification,
773
+ });
774
+
775
+ const feedback = captureFeedback({
776
+ signal: verification.accepted ? 'up' : 'down',
777
+ context: verification.accepted
778
+ ? `Job ${normalizedJob.id} passed verification after ${verification.attempts} attempt(s)`
779
+ : `Job ${normalizedJob.id} failed verification after ${verification.attempts} attempt(s): ${(verification.finalVerification.violations || []).map((violation) => violation.pattern).join('; ')}`,
780
+ whatWorked: verification.accepted ? 'Verification loop accepted output' : undefined,
781
+ whatWentWrong: !verification.accepted ? `Failed ${verification.attempts} verification attempts` : undefined,
782
+ whatToChange: !verification.accepted ? 'Improve output to avoid known mistake patterns' : undefined,
783
+ tags: [...normalizedJob.tags, 'verification-loop'],
784
+ skill: normalizedJob.skill || 'async-job-runner',
785
+ });
786
+
787
+ const terminalState = writeJobState({
788
+ ...(readJobState(normalizedJob.id) || state),
789
+ status: verification.accepted ? 'completed' : 'failed',
790
+ updatedAt: nowIso(),
791
+ endedAt: nowIso(),
792
+ currentStage: null,
793
+ nextStageIndex: normalizedJob.stages.length,
794
+ currentContext,
795
+ improvementExperimentId: improvementExperiment ? improvementExperiment.id : null,
796
+ verification: {
797
+ accepted: verification.accepted,
798
+ attempts: verification.attempts,
799
+ score: verification.finalVerification ? verification.finalVerification.score : 0,
800
+ },
801
+ });
802
+
803
+ clearJobControl(normalizedJob.id);
804
+ const result = buildResult({
805
+ state: terminalState,
806
+ recall,
807
+ verification,
808
+ feedback,
809
+ improvementExperiment,
810
+ });
811
+ appendJobLog(result);
812
+ return result;
813
+ }
814
+
815
+ function runJobFromFile(jobFilePath, options = {}) {
816
+ const resolvedPath = path.resolve(jobFilePath);
817
+ const spec = readJson(resolvedPath);
818
+ if (!spec) {
819
+ throw new Error(`Unable to read job file: ${resolvedPath}`);
820
+ }
821
+
822
+ const derivedId = spec.id || path.basename(resolvedPath, path.extname(resolvedPath));
823
+ return executeJob({
824
+ ...spec,
825
+ id: derivedId,
826
+ jobFilePath: resolvedPath,
827
+ autoResume: options.autoResume !== false,
828
+ }, options);
829
+ }
830
+
831
+ function runHarness(harnessId, inputs = {}, options = {}) {
832
+ const { runHarness: executeHarness } = require('./natural-language-harness');
833
+ return executeHarness(harnessId, inputs, options);
834
+ }
835
+
836
+ function resumeManagedJobs(options = {}) {
837
+ const states = listJobStates({
838
+ statuses: ['paused', 'running', 'resume_requested'],
839
+ }).filter((state) => Boolean(state.jobFilePath));
840
+
841
+ const limit = Number(options.limit || 0);
842
+ const selected = limit > 0 ? states.slice(0, limit) : states;
843
+ const results = selected.map((state) => runJobFromFile(state.jobFilePath, { ...options, resume: true }));
844
+
845
+ return {
846
+ total: results.length,
847
+ completed: results.filter((result) => result.status === 'completed').length,
848
+ failed: results.filter((result) => result.status === 'failed').length,
849
+ paused: results.filter((result) => result.status === 'paused').length,
850
+ cancelled: results.filter((result) => result.status === 'cancelled').length,
851
+ results,
852
+ timestamp: nowIso(),
853
+ };
854
+ }
855
+
856
+ /**
857
+ * Run multiple jobs sequentially through the pipeline.
858
+ *
859
+ * @param {object[]} jobs
860
+ * @returns {object}
861
+ */
862
+ function runBatch(jobs) {
863
+ const results = [];
864
+
865
+ for (const job of jobs) {
866
+ results.push(executeJob(job));
867
+ }
868
+
869
+ return {
870
+ completed: results.filter((result) => result.status === 'completed').length,
871
+ failed: results.filter((result) => result.status === 'failed').length,
872
+ paused: results.filter((result) => result.status === 'paused').length,
873
+ cancelled: results.filter((result) => result.status === 'cancelled').length,
874
+ total: results.length,
875
+ results,
876
+ timestamp: nowIso(),
877
+ };
878
+ }
879
+
880
+ module.exports = {
881
+ recallContext,
882
+ executeJob,
883
+ runBatch,
884
+ appendJobLog,
885
+ readJobLog,
886
+ getJobStats,
887
+ readJobState,
888
+ listJobStates,
889
+ readJobControl,
890
+ requestJobControl,
891
+ clearJobControl,
892
+ runJobFromFile,
893
+ runHarness,
894
+ resumeJob,
895
+ resumeManagedJobs,
896
+ getJobRuntimePaths,
897
+ JOB_LOG_FILENAME,
898
+ JOB_CONTROL_FILENAME,
899
+ JOB_STATE_DIRNAME,
900
+ };
901
+
902
+ if (require.main === module) {
903
+ const args = {};
904
+ process.argv.slice(2).forEach((arg) => {
905
+ if (!arg.startsWith('--')) return;
906
+ const [key, ...rest] = arg.slice(2).split('=');
907
+ args[key] = rest.length > 0 ? rest.join('=') : true;
908
+ });
909
+
910
+ if (args.pause) {
911
+ console.log(JSON.stringify(requestJobControl(args.pause, 'pause'), null, 2));
912
+ process.exit(0);
913
+ }
914
+
915
+ if (args.cancel) {
916
+ console.log(JSON.stringify(requestJobControl(args.cancel, 'cancel'), null, 2));
917
+ process.exit(0);
918
+ }
919
+
920
+ if (args.resume) {
921
+ const result = resumeJob(args.resume);
922
+ console.log(JSON.stringify(result, null, 2));
923
+ process.exit(['failed', 'cancelled'].includes(result.status) ? 1 : 0);
924
+ }
925
+
926
+ if (args['resume-managed']) {
927
+ const result = resumeManagedJobs({ limit: Number(args.limit || 0) });
928
+ console.log(JSON.stringify(result, null, 2));
929
+ process.exit(result.failed > 0 || result.cancelled > 0 ? 1 : 0);
930
+ }
931
+
932
+ if (args['list-harnesses']) {
933
+ const { listHarnesses } = require('./natural-language-harness');
934
+ console.log(JSON.stringify({ harnesses: listHarnesses({ tag: args.tag }) }, null, 2));
935
+ process.exit(0);
936
+ }
937
+
938
+ if (args['run-harness']) {
939
+ let inputs = {};
940
+ if (args['harness-inputs']) {
941
+ try {
942
+ inputs = JSON.parse(args['harness-inputs']);
943
+ } catch (error) {
944
+ console.error(`Invalid --harness-inputs JSON: ${error.message}`);
945
+ process.exit(1);
946
+ }
947
+ }
948
+
949
+ const result = runHarness(args['run-harness'], inputs, {
950
+ jobId: args['job-id'],
951
+ });
952
+ console.log(JSON.stringify(result, null, 2));
953
+ process.exit(['failed', 'cancelled'].includes(result.status) ? 1 : 0);
954
+ }
955
+
956
+ if (args['run-file']) {
957
+ const result = runJobFromFile(args['run-file']);
958
+ console.log(JSON.stringify(result, null, 2));
959
+ process.exit(['failed', 'cancelled'].includes(result.status) ? 1 : 0);
960
+ }
961
+
962
+ if (args.run) {
963
+ const result = executeJob({
964
+ context: args.context || '',
965
+ tags: (args.tags || '').split(',').filter(Boolean),
966
+ skill: args.skill,
967
+ maxRetries: Number(args.retries || 3),
968
+ });
969
+ console.log(JSON.stringify(result, null, 2));
970
+ process.exit(['failed', 'cancelled'].includes(result.status) ? 1 : 0);
971
+ }
972
+
973
+ if (args.jobs) {
974
+ console.log(JSON.stringify(listJobStates({ limit: Number(args.limit || 20) }), null, 2));
975
+ process.exit(0);
976
+ }
977
+
978
+ if (args.stats) {
979
+ console.log(JSON.stringify(getJobStats(), null, 2));
980
+ process.exit(0);
981
+ }
982
+
983
+ if (args.log) {
984
+ const limit = Number(args.limit || 20);
985
+ console.log(JSON.stringify(readJobLog(limit), null, 2));
986
+ process.exit(0);
987
+ }
988
+
989
+ console.log(`Usage:
990
+ node scripts/async-job-runner.js --run --context="..." --tags=testing --skill=executor
991
+ node scripts/async-job-runner.js --run-file=./job.json
992
+ node scripts/async-job-runner.js --list-harnesses [--tag=verification]
993
+ node scripts/async-job-runner.js --run-harness=repo-full-verification --harness-inputs='{"verificationCommand":"npm run verify:full"}' [--job-id=verify-job]
994
+ node scripts/async-job-runner.js --resume=<jobId>
995
+ node scripts/async-job-runner.js --resume-managed [--limit=5]
996
+ node scripts/async-job-runner.js --pause=<jobId>
997
+ node scripts/async-job-runner.js --cancel=<jobId>
998
+ node scripts/async-job-runner.js --jobs [--limit=10]
999
+ node scripts/async-job-runner.js --stats
1000
+ node scripts/async-job-runner.js --log --limit=10`);
1001
+ }