@neural-node-labs/xcoder-dna 0.0.0-stage → 1.4.2

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 (406) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +132 -2
  3. package/dist/agents/agent-catalog.d.ts +87 -0
  4. package/dist/agents/agent-catalog.js +159 -0
  5. package/dist/agents/agent-registry.d.ts +76 -0
  6. package/dist/agents/agent-registry.js +189 -0
  7. package/dist/agents/ai-chat-debate.d.ts +36 -0
  8. package/dist/agents/ai-chat-debate.js +300 -0
  9. package/dist/agents/ai-chat-report-writer.d.ts +7 -0
  10. package/dist/agents/ai-chat-report-writer.js +100 -0
  11. package/dist/agents/duplicate-detector.d.ts +41 -0
  12. package/dist/agents/duplicate-detector.js +65 -0
  13. package/dist/agents/genesis-agent.d.ts +61 -0
  14. package/dist/agents/genesis-agent.js +340 -0
  15. package/dist/agents/samurai-agent.d.ts +53 -0
  16. package/dist/agents/samurai-agent.js +279 -0
  17. package/dist/agents/sub-agent.d.ts +56 -0
  18. package/dist/agents/sub-agent.js +353 -0
  19. package/dist/backlog/backlog-requirement-validator.d.ts +10 -0
  20. package/dist/backlog/backlog-requirement-validator.js +60 -0
  21. package/dist/backlog/backlog-store.d.ts +29 -0
  22. package/dist/backlog/backlog-store.js +148 -0
  23. package/dist/backlog/po-agent.d.ts +16 -0
  24. package/dist/backlog/po-agent.js +121 -0
  25. package/dist/backlog/types.d.ts +25 -0
  26. package/dist/backlog/types.js +4 -0
  27. package/dist/bench/run.d.ts +11 -0
  28. package/dist/bench/run.js +185 -0
  29. package/dist/bench/types.d.ts +50 -0
  30. package/dist/bench/types.js +1 -0
  31. package/dist/cli/delegate.d.ts +90 -0
  32. package/dist/cli/delegate.js +220 -0
  33. package/dist/cli/swarm.d.ts +10 -0
  34. package/dist/cli/swarm.js +100 -0
  35. package/dist/cli/task.d.ts +14 -0
  36. package/dist/cli/task.js +121 -0
  37. package/dist/cli/wbc-arg.d.ts +6 -0
  38. package/dist/cli/wbc-arg.js +40 -0
  39. package/dist/cli/wbc.d.ts +45 -0
  40. package/dist/cli/wbc.js +98 -0
  41. package/dist/commands/license.d.ts +9 -0
  42. package/dist/commands/license.js +140 -0
  43. package/dist/commands/release.d.ts +44 -0
  44. package/dist/commands/release.js +180 -0
  45. package/dist/commands/test.d.ts +50 -0
  46. package/dist/commands/test.js +385 -0
  47. package/dist/config/env-guard.d.ts +35 -0
  48. package/dist/config/env-guard.js +100 -0
  49. package/dist/config/env-snapshot.d.ts +18 -0
  50. package/dist/config/env-snapshot.js +30 -0
  51. package/dist/config/loadConfig.d.ts +82 -0
  52. package/dist/config/loadConfig.js +249 -0
  53. package/dist/config/secure-mode.d.ts +29 -0
  54. package/dist/config/secure-mode.js +63 -0
  55. package/dist/config/user-config.d.ts +39 -0
  56. package/dist/config/user-config.js +202 -0
  57. package/dist/engine/reasoning-engine.d.ts +21 -0
  58. package/dist/engine/reasoning-engine.js +59 -0
  59. package/dist/events/bus.d.ts +22 -0
  60. package/dist/events/bus.js +18 -0
  61. package/dist/index.d.ts +87 -0
  62. package/dist/index.js +88 -0
  63. package/dist/indexing/ignoreRules.d.ts +1 -0
  64. package/dist/indexing/ignoreRules.js +53 -0
  65. package/dist/instance-swarm/instance-swarm-orchestrator.d.ts +57 -0
  66. package/dist/instance-swarm/instance-swarm-orchestrator.js +204 -0
  67. package/dist/instance-swarm/protocol-name-resolver.d.ts +23 -0
  68. package/dist/instance-swarm/protocol-name-resolver.js +64 -0
  69. package/dist/license/gate.d.ts +31 -0
  70. package/dist/license/gate.js +188 -0
  71. package/dist/license/http-client.d.ts +43 -0
  72. package/dist/license/http-client.js +195 -0
  73. package/dist/license/manager.d.ts +39 -0
  74. package/dist/license/manager.js +175 -0
  75. package/dist/license/receipt.d.ts +27 -0
  76. package/dist/license/receipt.js +108 -0
  77. package/dist/license/state-codec.d.ts +72 -0
  78. package/dist/license/state-codec.js +218 -0
  79. package/dist/license/state-paths.d.ts +17 -0
  80. package/dist/license/state-paths.js +64 -0
  81. package/dist/license/store.d.ts +44 -0
  82. package/dist/license/store.js +223 -0
  83. package/dist/license/trust-anchor.d.ts +24 -0
  84. package/dist/license/trust-anchor.js +74 -0
  85. package/dist/license/types.d.ts +34 -0
  86. package/dist/license/types.js +19 -0
  87. package/dist/llm/budget.d.ts +23 -0
  88. package/dist/llm/budget.js +58 -0
  89. package/dist/llm/client.d.ts +53 -0
  90. package/dist/llm/client.js +122 -0
  91. package/dist/llm/factory.d.ts +14 -0
  92. package/dist/llm/factory.js +32 -0
  93. package/dist/orchestrator/defect-logger.d.ts +31 -0
  94. package/dist/orchestrator/defect-logger.js +101 -0
  95. package/dist/orchestrator/defect-manager.d.ts +118 -0
  96. package/dist/orchestrator/defect-manager.js +338 -0
  97. package/dist/orchestrator/defect-migration.d.ts +14 -0
  98. package/dist/orchestrator/defect-migration.js +174 -0
  99. package/dist/orchestrator/defect-store.d.ts +48 -0
  100. package/dist/orchestrator/defect-store.js +76 -0
  101. package/dist/orchestrator/healing.d.ts +14 -0
  102. package/dist/orchestrator/healing.js +11 -0
  103. package/dist/orchestrator/interactive-steering.d.ts +64 -0
  104. package/dist/orchestrator/interactive-steering.js +107 -0
  105. package/dist/orchestrator/interrupt-handler.d.ts +30 -0
  106. package/dist/orchestrator/interrupt-handler.js +70 -0
  107. package/dist/orchestrator/lesson-manager.d.ts +25 -0
  108. package/dist/orchestrator/lesson-manager.js +122 -0
  109. package/dist/orchestrator/progress-summary.d.ts +15 -0
  110. package/dist/orchestrator/progress-summary.js +106 -0
  111. package/dist/orchestrator/reasoning-score.d.ts +49 -0
  112. package/dist/orchestrator/reasoning-score.js +117 -0
  113. package/dist/orchestrator/swarm.d.ts +36 -0
  114. package/dist/orchestrator/swarm.js +77 -0
  115. package/dist/orchestrator/task-factory.d.ts +15 -0
  116. package/dist/orchestrator/task-factory.js +176 -0
  117. package/dist/orchestrator/validation-gate.d.ts +23 -0
  118. package/dist/orchestrator/validation-gate.js +155 -0
  119. package/dist/protocol/react-contract.d.ts +136 -0
  120. package/dist/protocol/react-contract.js +698 -0
  121. package/dist/protocol/wks-protocol-manager.d.ts +22 -0
  122. package/dist/protocol/wks-protocol-manager.js +72 -0
  123. package/dist/sdlc-runtime/conversation-runner.d.ts +8 -0
  124. package/dist/sdlc-runtime/conversation-runner.js +64 -0
  125. package/dist/sdlc-runtime/dag-utils.d.ts +15 -0
  126. package/dist/sdlc-runtime/dag-utils.js +67 -0
  127. package/dist/sdlc-runtime/defect-integration.d.ts +7 -0
  128. package/dist/sdlc-runtime/defect-integration.js +99 -0
  129. package/dist/sdlc-runtime/execution-loop.d.ts +38 -0
  130. package/dist/sdlc-runtime/execution-loop.js +274 -0
  131. package/dist/sdlc-runtime/lesson-recorder.d.ts +9 -0
  132. package/dist/sdlc-runtime/lesson-recorder.js +27 -0
  133. package/dist/sdlc-runtime/plan-initializer.d.ts +47 -0
  134. package/dist/sdlc-runtime/plan-initializer.js +135 -0
  135. package/dist/sdlc-runtime/progress-persister.d.ts +10 -0
  136. package/dist/sdlc-runtime/progress-persister.js +34 -0
  137. package/dist/sdlc-runtime/protocol-loader.d.ts +10 -0
  138. package/dist/sdlc-runtime/protocol-loader.js +21 -0
  139. package/dist/sdlc-runtime/reporting.d.ts +24 -0
  140. package/dist/sdlc-runtime/reporting.js +68 -0
  141. package/dist/sdlc-runtime/run-task.d.ts +81 -0
  142. package/dist/sdlc-runtime/run-task.js +210 -0
  143. package/dist/sdlc-runtime/sdlc-orchestrator.d.ts +59 -0
  144. package/dist/sdlc-runtime/sdlc-orchestrator.js +170 -0
  145. package/dist/sdlc-runtime/sdlc-skill.d.ts +44 -0
  146. package/dist/sdlc-runtime/sdlc-skill.js +148 -0
  147. package/dist/sdlc-runtime/steering-handler.d.ts +14 -0
  148. package/dist/sdlc-runtime/steering-handler.js +51 -0
  149. package/dist/sdlc-runtime/trace-recorder.d.ts +10 -0
  150. package/dist/sdlc-runtime/trace-recorder.js +7 -0
  151. package/dist/security/index.d.ts +16 -0
  152. package/dist/security/index.js +12 -0
  153. package/dist/security/input-screen.d.ts +30 -0
  154. package/dist/security/input-screen.js +75 -0
  155. package/dist/security/tool-call-guard.d.ts +16 -0
  156. package/dist/security/tool-call-guard.js +174 -0
  157. package/dist/security/untrusted-content.d.ts +34 -0
  158. package/dist/security/untrusted-content.js +63 -0
  159. package/dist/skills/advanced-dfir/SKILL.md +85 -0
  160. package/dist/skills/advanced-pentest-lab/SKILL.md +88 -0
  161. package/dist/skills/analyst/SKILL.md +55 -0
  162. package/dist/skills/architect/SKILL.md +54 -0
  163. package/dist/skills/aws/SKILL.md +92 -0
  164. package/dist/skills/azure/SKILL.md +90 -0
  165. package/dist/skills/bylaw-context.d.ts +45 -0
  166. package/dist/skills/bylaw-context.js +61 -0
  167. package/dist/skills/bylaw-review.d.ts +20 -0
  168. package/dist/skills/bylaw-review.js +101 -0
  169. package/dist/skills/conversation/SKILL.md +29 -0
  170. package/dist/skills/design-patterns/SKILL.md +190 -0
  171. package/dist/skills/devops/SKILL.md +55 -0
  172. package/dist/skills/directives.d.ts +20 -0
  173. package/dist/skills/directives.js +313 -0
  174. package/dist/skills/docker/SKILL.md +76 -0
  175. package/dist/skills/docker-expert/SKILL.md +56 -0
  176. package/dist/skills/enterprise-systems-analyst/SKILL.md +83 -0
  177. package/dist/skills/enterprise-systems-analyst/references/crm.md +41 -0
  178. package/dist/skills/enterprise-systems-analyst/references/erp.md +40 -0
  179. package/dist/skills/enterprise-systems-analyst/references/financial-systems.md +35 -0
  180. package/dist/skills/enterprise-systems-analyst/references/hcm.md +38 -0
  181. package/dist/skills/enterprise-systems-analyst/references/mrp.md +37 -0
  182. package/dist/skills/enterprise-systems-analyst/references/scm.md +32 -0
  183. package/dist/skills/ethical-hacking-methodology/SKILL.md +119 -0
  184. package/dist/skills/externalSkillLoader.d.ts +25 -0
  185. package/dist/skills/externalSkillLoader.js +65 -0
  186. package/dist/skills/externalSkillRegistry.d.ts +33 -0
  187. package/dist/skills/externalSkillRegistry.js +94 -0
  188. package/dist/skills/filesystem-management/SKILL.md +61 -0
  189. package/dist/skills/first-run-seed.d.ts +26 -0
  190. package/dist/skills/first-run-seed.js +75 -0
  191. package/dist/skills/git-vcs/SKILL.md +84 -0
  192. package/dist/skills/kafka/SKILL.md +89 -0
  193. package/dist/skills/kubernetes/SKILL.md +93 -0
  194. package/dist/skills/kubernetes-expert/SKILL.md +54 -0
  195. package/dist/skills/openshift/SKILL.md +93 -0
  196. package/dist/skills/pentester/SKILL.md +59 -0
  197. package/dist/skills/performance-tester/SKILL.md +57 -0
  198. package/dist/skills/playwright-ui-tester/SKILL.md +67 -0
  199. package/dist/skills/programmer/SKILL.md +58 -0
  200. package/dist/skills/project-scaffolding/SKILL.md +133 -0
  201. package/dist/skills/qa-engineer/SKILL.md +91 -0
  202. package/dist/skills/rca/SKILL.md +58 -0
  203. package/dist/skills/redhat/SKILL.md +92 -0
  204. package/dist/skills/rosa/SKILL.md +80 -0
  205. package/dist/skills/scrum-framework/SKILL.md +74 -0
  206. package/dist/skills/scrum-framework/references/artifacts_and_quality.md +79 -0
  207. package/dist/skills/scrum-framework/references/roles_and_events.md +105 -0
  208. package/dist/skills/scrum-master-agent/SKILL.md +74 -0
  209. package/dist/skills/scrum-master-agent/references/behaviors.md +56 -0
  210. package/dist/skills/sdlc-skill.d.ts +1 -0
  211. package/dist/skills/sdlc-skill.js +4 -0
  212. package/dist/skills/secops/SKILL.md +52 -0
  213. package/dist/skills/secure-architect.bylaws.d.ts +68 -0
  214. package/dist/skills/secure-architect.bylaws.js +525 -0
  215. package/dist/skills/seed-skills.d.ts +48 -0
  216. package/dist/skills/seed-skills.js +213 -0
  217. package/dist/skills/skill-authoring/SKILL.md +123 -0
  218. package/dist/skills/skill-header.d.ts +51 -0
  219. package/dist/skills/skill-header.js +163 -0
  220. package/dist/skills/skill-path-guard.d.ts +41 -0
  221. package/dist/skills/skill-path-guard.js +95 -0
  222. package/dist/skills/skillRouter.d.ts +51 -0
  223. package/dist/skills/skillRouter.js +90 -0
  224. package/dist/skills/skills-root.d.ts +64 -0
  225. package/dist/skills/skills-root.js +168 -0
  226. package/dist/skills/software-architect/SKILL.md +77 -0
  227. package/dist/skills/software-engineer/SKILL.md +74 -0
  228. package/dist/skills/solid-principles/SKILL.md +94 -0
  229. package/dist/skills/task-planning/SKILL.md +115 -0
  230. package/dist/skills/tester/SKILL.md +54 -0
  231. package/dist/skills/ubuntu/SKILL.md +87 -0
  232. package/dist/skills/ui-ux-design/SKILL.md +114 -0
  233. package/dist/skills/workspace-context/SKILL.md +103 -0
  234. package/dist/sprint/controller.d.ts +37 -0
  235. package/dist/sprint/controller.js +220 -0
  236. package/dist/sprint/dag-builder.d.ts +14 -0
  237. package/dist/sprint/dag-builder.js +105 -0
  238. package/dist/sprint/reporter.d.ts +11 -0
  239. package/dist/sprint/reporter.js +97 -0
  240. package/dist/sprint/state-store.d.ts +10 -0
  241. package/dist/sprint/state-store.js +71 -0
  242. package/dist/sprint/types.d.ts +24 -0
  243. package/dist/sprint/types.js +4 -0
  244. package/dist/store/file-version-store.d.ts +24 -0
  245. package/dist/store/file-version-store.js +73 -0
  246. package/dist/store/task-store.d.ts +90 -0
  247. package/dist/store/task-store.js +166 -0
  248. package/dist/task-ingest/architect-detailer.d.ts +43 -0
  249. package/dist/task-ingest/architect-detailer.js +141 -0
  250. package/dist/task-ingest/detail-schema.d.ts +9 -0
  251. package/dist/task-ingest/detail-schema.js +195 -0
  252. package/dist/task-ingest/detailed-run.d.ts +36 -0
  253. package/dist/task-ingest/detailed-run.js +108 -0
  254. package/dist/task-ingest/extract-id.d.ts +9 -0
  255. package/dist/task-ingest/extract-id.js +24 -0
  256. package/dist/task-ingest/index.d.ts +23 -0
  257. package/dist/task-ingest/index.js +14 -0
  258. package/dist/task-ingest/ingest.d.ts +45 -0
  259. package/dist/task-ingest/ingest.js +163 -0
  260. package/dist/task-ingest/list-ingested.d.ts +13 -0
  261. package/dist/task-ingest/list-ingested.js +30 -0
  262. package/dist/task-ingest/pending-filter.d.ts +30 -0
  263. package/dist/task-ingest/pending-filter.js +59 -0
  264. package/dist/task-ingest/scanner.d.ts +56 -0
  265. package/dist/task-ingest/scanner.js +216 -0
  266. package/dist/task-ingest/source-reader.d.ts +25 -0
  267. package/dist/task-ingest/source-reader.js +93 -0
  268. package/dist/task-ingest/spec-builder.d.ts +34 -0
  269. package/dist/task-ingest/spec-builder.js +89 -0
  270. package/dist/task-ingest/wbs-extract.d.ts +50 -0
  271. package/dist/task-ingest/wbs-extract.js +226 -0
  272. package/dist/task-ingest/wbs-parser.d.ts +36 -0
  273. package/dist/task-ingest/wbs-parser.js +170 -0
  274. package/dist/tools/apiTestTool.d.ts +37 -0
  275. package/dist/tools/apiTestTool.js +128 -0
  276. package/dist/tools/ast-tools.d.ts +183 -0
  277. package/dist/tools/ast-tools.js +853 -0
  278. package/dist/tools/browse-tool.d.ts +105 -0
  279. package/dist/tools/browse-tool.js +394 -0
  280. package/dist/tools/credential.d.ts +17 -0
  281. package/dist/tools/credential.js +32 -0
  282. package/dist/tools/dependency-graph.d.ts +23 -0
  283. package/dist/tools/dependency-graph.js +164 -0
  284. package/dist/tools/edit-tool.d.ts +34 -0
  285. package/dist/tools/edit-tool.js +95 -0
  286. package/dist/tools/file-header-manager.d.ts +27 -0
  287. package/dist/tools/file-header-manager.js +153 -0
  288. package/dist/tools/fs-tools.d.ts +154 -0
  289. package/dist/tools/fs-tools.js +337 -0
  290. package/dist/tools/git-tools.d.ts +79 -0
  291. package/dist/tools/git-tools.js +348 -0
  292. package/dist/tools/github-tool.d.ts +48 -0
  293. package/dist/tools/github-tool.js +147 -0
  294. package/dist/tools/globTool.d.ts +20 -0
  295. package/dist/tools/globTool.js +34 -0
  296. package/dist/tools/grepTool.d.ts +19 -0
  297. package/dist/tools/grepTool.js +44 -0
  298. package/dist/tools/index-freshness.d.ts +58 -0
  299. package/dist/tools/index-freshness.js +196 -0
  300. package/dist/tools/index-glob.d.ts +48 -0
  301. package/dist/tools/index-glob.js +175 -0
  302. package/dist/tools/load-skill-tool.d.ts +15 -0
  303. package/dist/tools/load-skill-tool.js +114 -0
  304. package/dist/tools/patch-tools.d.ts +58 -0
  305. package/dist/tools/patch-tools.js +153 -0
  306. package/dist/tools/playwright-tool.d.ts +66 -0
  307. package/dist/tools/playwright-tool.js +121 -0
  308. package/dist/tools/project-detect.d.ts +20 -0
  309. package/dist/tools/project-detect.js +87 -0
  310. package/dist/tools/prompt-guidance.d.ts +22 -0
  311. package/dist/tools/prompt-guidance.js +23 -0
  312. package/dist/tools/schedule-audit.d.ts +50 -0
  313. package/dist/tools/schedule-audit.js +124 -0
  314. package/dist/tools/schedule-validation.d.ts +67 -0
  315. package/dist/tools/schedule-validation.js +210 -0
  316. package/dist/tools/scheduleTool.d.ts +62 -0
  317. package/dist/tools/scheduleTool.js +313 -0
  318. package/dist/tools/search-tools.d.ts +27 -0
  319. package/dist/tools/search-tools.js +78 -0
  320. package/dist/tools/sed-tool.d.ts +66 -0
  321. package/dist/tools/sed-tool.js +402 -0
  322. package/dist/tools/shell-result.d.ts +11 -0
  323. package/dist/tools/shell-result.js +1 -0
  324. package/dist/tools/shell-tool.d.ts +45 -0
  325. package/dist/tools/shell-tool.js +141 -0
  326. package/dist/tools/siteCrawlerTool.d.ts +32 -0
  327. package/dist/tools/siteCrawlerTool.js +205 -0
  328. package/dist/tools/tool-registry.d.ts +67 -0
  329. package/dist/tools/tool-registry.js +606 -0
  330. package/dist/tools/validate-tool.d.ts +23 -0
  331. package/dist/tools/validate-tool.js +201 -0
  332. package/dist/tools/workspace-index.d.ts +46 -0
  333. package/dist/tools/workspace-index.js +173 -0
  334. package/dist/types.d.ts +222 -0
  335. package/dist/types.js +7 -0
  336. package/dist/updater/index.d.ts +14 -0
  337. package/dist/updater/index.js +120 -0
  338. package/dist/util/banner.d.ts +25 -0
  339. package/dist/util/banner.js +140 -0
  340. package/dist/util/command-suggester.d.ts +6 -0
  341. package/dist/util/command-suggester.js +25 -0
  342. package/dist/util/confirm-interrupt.d.ts +10 -0
  343. package/dist/util/confirm-interrupt.js +31 -0
  344. package/dist/util/continue-trigger.d.ts +11 -0
  345. package/dist/util/continue-trigger.js +20 -0
  346. package/dist/util/env-info.d.ts +18 -0
  347. package/dist/util/env-info.js +37 -0
  348. package/dist/util/file-access-log.d.ts +35 -0
  349. package/dist/util/file-access-log.js +140 -0
  350. package/dist/util/footer-manager.d.ts +124 -0
  351. package/dist/util/footer-manager.js +195 -0
  352. package/dist/util/footer-renderer.d.ts +67 -0
  353. package/dist/util/footer-renderer.js +319 -0
  354. package/dist/util/footer-state.d.ts +34 -0
  355. package/dist/util/footer-state.js +18 -0
  356. package/dist/util/footer-text.d.ts +51 -0
  357. package/dist/util/footer-text.js +74 -0
  358. package/dist/util/ids.d.ts +1 -0
  359. package/dist/util/ids.js +4 -0
  360. package/dist/util/levenshtein.d.ts +6 -0
  361. package/dist/util/levenshtein.js +34 -0
  362. package/dist/util/logger.d.ts +10 -0
  363. package/dist/util/logger.js +41 -0
  364. package/dist/util/logs.d.ts +80 -0
  365. package/dist/util/logs.js +135 -0
  366. package/dist/util/output-handler.d.ts +89 -0
  367. package/dist/util/output-handler.js +193 -0
  368. package/dist/util/output-interceptor.d.ts +18 -0
  369. package/dist/util/output-interceptor.js +49 -0
  370. package/dist/util/output-paths.d.ts +43 -0
  371. package/dist/util/output-paths.js +121 -0
  372. package/dist/util/package-json.d.ts +6 -0
  373. package/dist/util/package-json.js +36 -0
  374. package/dist/util/process-kill.d.ts +27 -0
  375. package/dist/util/process-kill.js +148 -0
  376. package/dist/util/protocol-error-logger.d.ts +33 -0
  377. package/dist/util/protocol-error-logger.js +73 -0
  378. package/dist/util/redact.d.ts +25 -0
  379. package/dist/util/redact.js +119 -0
  380. package/dist/util/scroll-region-guard.d.ts +33 -0
  381. package/dist/util/scroll-region-guard.js +63 -0
  382. package/dist/util/spinner.d.ts +15 -0
  383. package/dist/util/spinner.js +49 -0
  384. package/dist/util/terminal-output.d.ts +34 -0
  385. package/dist/util/terminal-output.js +1 -0
  386. package/dist/util/terminal-silent.d.ts +6 -0
  387. package/dist/util/terminal-silent.js +20 -0
  388. package/dist/util/terminal.d.ts +56 -0
  389. package/dist/util/terminal.js +124 -0
  390. package/dist/util/text-sanitize.d.ts +8 -0
  391. package/dist/util/text-sanitize.js +45 -0
  392. package/dist/util/thinking-spinner.d.ts +27 -0
  393. package/dist/util/thinking-spinner.js +189 -0
  394. package/dist/util/tool-error-logger.d.ts +33 -0
  395. package/dist/util/tool-error-logger.js +77 -0
  396. package/dist/util/tty.d.ts +13 -0
  397. package/dist/util/tty.js +16 -0
  398. package/dist/util/xcoder-paths.d.ts +56 -0
  399. package/dist/util/xcoder-paths.js +63 -0
  400. package/dist/version.d.ts +2 -0
  401. package/dist/version.js +5 -0
  402. package/dist/worker-agent/to-subtask-node.d.ts +35 -0
  403. package/dist/worker-agent/to-subtask-node.js +41 -0
  404. package/dist/worker-agent/worker-orchestrator.d.ts +104 -0
  405. package/dist/worker-agent/worker-orchestrator.js +201 -0
  406. package/package.json +43 -3
@@ -0,0 +1,67 @@
1
+ /** Hard bounds applied to every scheduled job. */
2
+ export declare const SCHEDULE_LIMITS: Readonly<{
3
+ /** Longest accepted job id. */
4
+ maxJobIdLength: 64;
5
+ /** Longest accepted cron expression (5 short fields + separators). */
6
+ maxCronExprLength: 128;
7
+ /** Longest accepted command line. */
8
+ maxCommandLength: 4096;
9
+ /** Largest accepted one-off delay: 7 days. */
10
+ maxDelaySeconds: 604800;
11
+ /** Maximum number of concurrently live scheduled jobs per workspace. */
12
+ maxLiveJobs: 50;
13
+ /** How many characters of the command the audit trail may retain. */
14
+ commandPreviewLength: 24;
15
+ }>;
16
+ /** Discriminated union so callers must handle rejection explicitly. */
17
+ export type ValidationResult<T> = {
18
+ readonly ok: true;
19
+ readonly value: T;
20
+ } | {
21
+ readonly ok: false;
22
+ readonly field: string;
23
+ readonly reason: string;
24
+ };
25
+ /** A validated schedule request, narrowed by `operation`. */
26
+ export type ScheduleRequest = {
27
+ readonly operation: "create_cron";
28
+ readonly id: string;
29
+ readonly cronExpr: string;
30
+ readonly command: string;
31
+ } | {
32
+ readonly operation: "create_once";
33
+ readonly delaySeconds: number;
34
+ readonly command: string;
35
+ } | {
36
+ readonly operation: "list";
37
+ } | {
38
+ readonly operation: "remove";
39
+ readonly id: string;
40
+ };
41
+ /**
42
+ * Raised by the schedule implementation when a caller bypasses the registry and
43
+ * hands it unvalidated input. Carries the offending field and the rule that
44
+ * rejected it — never the value itself.
45
+ */
46
+ export declare class ScheduleValidationError extends Error {
47
+ readonly field: string;
48
+ readonly rule: string;
49
+ constructor(field: string, rule: string);
50
+ }
51
+ /**
52
+ * Job ids become schtasks task names and crontab markers, so they are held to a
53
+ * deliberately narrow alphabet: leading alphanumeric, then alphanumerics,
54
+ * underscore and hyphen. No spaces, no dots, no path separators, no newlines.
55
+ */
56
+ export declare function validateJobId(id: unknown): ValidationResult<string>;
57
+ export declare function validateCronExpr(cronExpr: unknown): ValidationResult<string>;
58
+ export declare function validateCommand(command: unknown): ValidationResult<string>;
59
+ export declare function validateDelaySeconds(delaySeconds: unknown): ValidationResult<number>;
60
+ /**
61
+ * The single entry point. Validates the whole `schedule` tool input and returns
62
+ * a fully-typed, fully-checked request — or a rejection naming the field
63
+ * responsible. Called from the tool-call guard (TB1), the tool registry
64
+ * (TB2/TB3) and the schedule implementation itself (TB4), so a direct importer
65
+ * that skips the registry is still covered.
66
+ */
67
+ export declare function validateScheduleRequest(input: unknown): ValidationResult<ScheduleRequest>;
@@ -0,0 +1,210 @@
1
+ // xcoder:version 1 | xcoder:task task-b34338 | xcoder:updated 2026-11-05T12:42:05.142Z | xcoder:subtask code-st-6f0a98
2
+ /**
3
+ * Pure, I/O-free validation of every model-supplied `schedule` field.
4
+ *
5
+ * defect1.md: "untrusted command or delaySeconds values can cause arbitrary
6
+ * command execution through shell/PowerShell interpolation". The fix is
7
+ * structural, not a hardened escaper: nothing the model supplies is ever
8
+ * spliced into a shell string without first passing through here, and the
9
+ * renderers in scheduleTool.ts then build the OS payload from validated parts
10
+ * only (POSIX: one marker line + one job line; Windows: base64, which has no
11
+ * quoting metacharacters at all).
12
+ *
13
+ * This module deliberately has NO child_process import and NO filesystem
14
+ * access, so it is safe to call from the tool-call guard (TB1) as well as from
15
+ * the tool registry (TB2) and the tool implementation itself (TB4).
16
+ *
17
+ * Fail-closed: every validator returns a ValidationResult and never throws.
18
+ * Rejection reasons never echo the offending command (PRM-03 / CORE-07).
19
+ */
20
+ import { isDenied } from "./shell-tool.js";
21
+ /** Hard bounds applied to every scheduled job. */
22
+ export const SCHEDULE_LIMITS = Object.freeze({
23
+ /** Longest accepted job id. */
24
+ maxJobIdLength: 64,
25
+ /** Longest accepted cron expression (5 short fields + separators). */
26
+ maxCronExprLength: 128,
27
+ /** Longest accepted command line. */
28
+ maxCommandLength: 4096,
29
+ /** Largest accepted one-off delay: 7 days. */
30
+ maxDelaySeconds: 604_800,
31
+ /** Maximum number of concurrently live scheduled jobs per workspace. */
32
+ maxLiveJobs: 50,
33
+ /** How many characters of the command the audit trail may retain. */
34
+ commandPreviewLength: 24,
35
+ });
36
+ /**
37
+ * Raised by the schedule implementation when a caller bypasses the registry and
38
+ * hands it unvalidated input. Carries the offending field and the rule that
39
+ * rejected it — never the value itself.
40
+ */
41
+ export class ScheduleValidationError extends Error {
42
+ field;
43
+ rule;
44
+ constructor(field, rule) {
45
+ super(`invalid schedule field "${field}": ${rule}`);
46
+ this.name = "ScheduleValidationError";
47
+ this.field = field;
48
+ this.rule = rule;
49
+ }
50
+ }
51
+ const fail = (field, reason) => ({ ok: false, field, reason });
52
+ const pass = (value) => ({ ok: true, value });
53
+ // ── id ──────────────────────────────────────────────────────────────
54
+ const ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
55
+ /**
56
+ * Job ids become schtasks task names and crontab markers, so they are held to a
57
+ * deliberately narrow alphabet: leading alphanumeric, then alphanumerics,
58
+ * underscore and hyphen. No spaces, no dots, no path separators, no newlines.
59
+ */
60
+ export function validateJobId(id) {
61
+ if (typeof id !== "string" || id.length === 0) {
62
+ return fail("id", "must be a non-empty string");
63
+ }
64
+ if (id.length > SCHEDULE_LIMITS.maxJobIdLength) {
65
+ return fail("id", `must be at most ${SCHEDULE_LIMITS.maxJobIdLength} characters`);
66
+ }
67
+ if (!ID_RE.test(id)) {
68
+ return fail("id", "must match /^[A-Za-z0-9][A-Za-z0-9_-]*$/");
69
+ }
70
+ return pass(id);
71
+ }
72
+ // ── cronExpr ──────────────────────────────────────────────────────────
73
+ /**
74
+ * One cron field: digits/letters plus the cron connective punctuation
75
+ * (`*` `?` `/` `,` `-` `#`). Whitespace, quotes, backslashes, percent signs and
76
+ * shell metacharacters are all outside this class, which is what stops a cron
77
+ * expression from ever terminating the job line it is rendered into.
78
+ */
79
+ const CRON_FIELD_RE = /^[0-9A-Za-z*?\/,#-]+$/;
80
+ export function validateCronExpr(cronExpr) {
81
+ if (typeof cronExpr !== "string" || cronExpr.trim().length === 0) {
82
+ return fail("cronExpr", "must be a non-empty string");
83
+ }
84
+ if (cronExpr.length > SCHEDULE_LIMITS.maxCronExprLength) {
85
+ return fail("cronExpr", `must be at most ${SCHEDULE_LIMITS.maxCronExprLength} characters`);
86
+ }
87
+ const fields = cronExpr.trim().split(/\s+/);
88
+ if (fields.length !== 5) {
89
+ return fail("cronExpr", "must have exactly 5 whitespace-separated fields (minute hour day-of-month month day-of-week)");
90
+ }
91
+ for (const field of fields) {
92
+ if (!CRON_FIELD_RE.test(field)) {
93
+ return fail("cronExpr", "contains a character that is not valid in a cron field");
94
+ }
95
+ }
96
+ return pass(fields.join(" "));
97
+ }
98
+ // ── command ───────────────────────────────────────────────────────────
99
+ /**
100
+ * A command may contain printable ASCII and tabs only.
101
+ *
102
+ * Every control character is refused, which is what kills the defect at the
103
+ * source: a newline in `command` used to let one marker emit two crontab job
104
+ * lines — the second one unattributable, and therefore impossible to revoke
105
+ * with removeScheduled(). A tab is allowed because it is not a line
106
+ * terminator; CR, LF and NUL are not.
107
+ */
108
+ const PRINTABLE_7BIT_RE = /^[\t\x20-\x7E]+$/;
109
+ export function validateCommand(command) {
110
+ if (typeof command !== "string" || command.trim().length === 0) {
111
+ return fail("command", "must be a non-empty string");
112
+ }
113
+ if (command.length > SCHEDULE_LIMITS.maxCommandLength) {
114
+ return fail("command", `must be at most ${SCHEDULE_LIMITS.maxCommandLength} characters`);
115
+ }
116
+ if (!PRINTABLE_7BIT_RE.test(command)) {
117
+ return fail("command", "must contain only printable ASCII and tabs (no CR, LF, NUL or other control characters)");
118
+ }
119
+ // Cron treats an unescaped percent sign as a command/stdin separator, and
120
+ // lifting that rule through an opaque string is exactly the subtlety that
121
+ // produced this defect. A literal percent therefore needs a script file.
122
+ if (command.includes("%")) {
123
+ return fail("command", "must not contain a percent sign (cron interprets it as a command separator)");
124
+ }
125
+ // Reuse the existing destructive-pattern denylist rather than maintaining a
126
+ // second, subtly different copy (design tradeoff T7).
127
+ const denied = isDenied(command);
128
+ if (denied !== null) {
129
+ return fail("command", denied);
130
+ }
131
+ return pass(command);
132
+ }
133
+ // ── delaySeconds ──────────────────────────────────────────────────
134
+ export function validateDelaySeconds(delaySeconds) {
135
+ if (typeof delaySeconds !== "number" || !Number.isFinite(delaySeconds) || !Number.isInteger(delaySeconds)) {
136
+ return fail("delaySeconds", "must be an integer");
137
+ }
138
+ if (delaySeconds < 0 || delaySeconds > SCHEDULE_LIMITS.maxDelaySeconds) {
139
+ return fail("delaySeconds", `must be between 0 and ${SCHEDULE_LIMITS.maxDelaySeconds}`);
140
+ }
141
+ return pass(delaySeconds);
142
+ }
143
+ // ── whole request ────────────────────────────────────────────────────
144
+ const SUPPORTED_OPERATIONS = ["create_cron", "create_once", "list", "remove"];
145
+ function nonEmptyString(value) {
146
+ return typeof value === "string" && value.length > 0;
147
+ }
148
+ /**
149
+ * The single entry point. Validates the whole `schedule` tool input and returns
150
+ * a fully-typed, fully-checked request — or a rejection naming the field
151
+ * responsible. Called from the tool-call guard (TB1), the tool registry
152
+ * (TB2/TB3) and the schedule implementation itself (TB4), so a direct importer
153
+ * that skips the registry is still covered.
154
+ */
155
+ export function validateScheduleRequest(input) {
156
+ if (input === null || typeof input !== "object" || Array.isArray(input)) {
157
+ return fail("input", "must be an object");
158
+ }
159
+ const obj = input;
160
+ const operation = obj.operation;
161
+ if (typeof operation !== "string" || operation.length === 0) {
162
+ return fail("operation", `is required. Expected one of: ${SUPPORTED_OPERATIONS.join(", ")}.`);
163
+ }
164
+ switch (operation) {
165
+ case "create_cron": {
166
+ const missing = ["id", "cronExpr", "command"].filter((f) => !nonEmptyString(obj[f]));
167
+ if (missing.length > 0) {
168
+ return fail(missing[0], `"schedule" "create_cron" requires fields: ${missing.map((f) => `"${f}"`).join(", ")}`);
169
+ }
170
+ const id = validateJobId(obj.id);
171
+ if (!id.ok)
172
+ return id;
173
+ const cronExpr = validateCronExpr(obj.cronExpr);
174
+ if (!cronExpr.ok)
175
+ return cronExpr;
176
+ const command = validateCommand(obj.command);
177
+ if (!command.ok)
178
+ return command;
179
+ return pass({ operation, id: id.value, cronExpr: cronExpr.value, command: command.value });
180
+ }
181
+ case "create_once": {
182
+ if (obj.delaySeconds === undefined || obj.delaySeconds === null) {
183
+ return fail("delaySeconds", `"schedule" "create_once" requires fields: "delaySeconds"`);
184
+ }
185
+ if (!nonEmptyString(obj.command)) {
186
+ return fail("command", `"schedule" "create_once" requires fields: "command"`);
187
+ }
188
+ const delaySeconds = validateDelaySeconds(obj.delaySeconds);
189
+ if (!delaySeconds.ok)
190
+ return delaySeconds;
191
+ const command = validateCommand(obj.command);
192
+ if (!command.ok)
193
+ return command;
194
+ return pass({ operation, delaySeconds: delaySeconds.value, command: command.value });
195
+ }
196
+ case "list":
197
+ return pass({ operation });
198
+ case "remove": {
199
+ if (!nonEmptyString(obj.id)) {
200
+ return fail("id", `"schedule" "remove" requires field: "id"`);
201
+ }
202
+ const id = validateJobId(obj.id);
203
+ if (!id.ok)
204
+ return id;
205
+ return pass({ operation, id: id.value });
206
+ }
207
+ default:
208
+ return fail("operation", `unknown schedule operation "${operation}". Expected: ${SUPPORTED_OPERATIONS.join(", ")}.`);
209
+ }
210
+ }
@@ -0,0 +1,62 @@
1
+ export interface ScheduledJob {
2
+ id: string;
3
+ cronExpr: string;
4
+ command: string;
5
+ }
6
+ /**
7
+ * Renders the crontab payload for one job.
8
+ *
9
+ * defect1.md: the previous version spliced `${cronExpr} ${command}` into a
10
+ * template string, so a newline in `command` produced TWO crontab job lines
11
+ * from ONE marker. The injected line carried no marker, so removeScheduled()
12
+ * could never revoke it — unattributable persistence. There is no escaping
13
+ * here at all: instead the renderer refuses to emit anything containing a line
14
+ * terminator, so one job is always exactly two lines.
15
+ */
16
+ export declare function renderPosixJob(job: ScheduledJob): string;
17
+ /**
18
+ * Builds the `schtasks /TR` value for a command.
19
+ *
20
+ * defect1.md: the previous version embedded the command in a
21
+ * `powershell -Command "..."` string and escaped only the double quote, which
22
+ * is not a valid escaping rule for that quoting context (F2). Here the script
23
+ * is passed as base64 through PowerShell's stock `-EncodedCommand`, so the
24
+ * `-Command` quoting context is never entered at all and there is nothing left
25
+ * to escape: the alphabet of a base64 string contains no metacharacters.
26
+ */
27
+ export declare function buildWindowsTaskRun(command: string): string;
28
+ /**
29
+ * Registers a recurring job: cron on POSIX, a translated Windows Task Scheduler
30
+ * task on win32, tagged with an id for later listing/removal.
31
+ *
32
+ * Validates every field at the module boundary (TB4) before touching the OS, so
33
+ * a caller that imports this directly — bypassing both the tool-call guard and
34
+ * the tool registry — is still protected. Rejections throw
35
+ * ScheduleValidationError; the registry catches it to keep its {ok, output}
36
+ * contract.
37
+ *
38
+ * `workspaceRoot` is optional and defaults to the process cwd, which keeps
39
+ * `scheduleCron.length === 3` (asserted by scheduleTool.test.ts) intact.
40
+ */
41
+ export declare function scheduleCron(id: string, cronExpr: string, command: string, workspaceRoot?: string): Promise<{
42
+ id: string;
43
+ cronExpr: string;
44
+ }>;
45
+ /**
46
+ * Schedules a one-off command to run after `delaySeconds`, surviving beyond the
47
+ * current process.
48
+ *
49
+ * Both the delay and the command are validated first. Neither platform
50
+ * interpolates the command into a shell quoting context in a way a newline
51
+ * could exploit: POSIX passes the command as a positional parameter to bash
52
+ * (never as script text), Windows passes it as a base64 -EncodedCommand.
53
+ */
54
+ export declare function scheduleOnce(delaySeconds: number, command: string, workspaceRoot?: string): Promise<{
55
+ scheduledFor: string;
56
+ }>;
57
+ export declare function listScheduled(): Promise<ScheduledJob[]>;
58
+ /** Removes a job. The id is validated first so it cannot be used to address
59
+ * a task name or crontab marker outside this tool's namespace. */
60
+ export declare function removeScheduled(id: string, workspaceRoot?: string): Promise<{
61
+ removed: boolean;
62
+ }>;
@@ -0,0 +1,313 @@
1
+ // xcoder:version 2 | xcoder:task task-b34338 | xcoder:updated 2026-11-05T12:43:53.167Z | xcoder:subtask code-st-6f0a98
2
+ import { spawn, execFile } from "node:child_process";
3
+ import { promisify } from "node:util";
4
+ import { SCHEDULE_LIMITS, ScheduleValidationError, validateCommand, validateCronExpr, validateDelaySeconds, validateJobId, } from "./schedule-validation.js";
5
+ import { buildAuditRecord, countLiveJobs, recordScheduleEvent } from "./schedule-audit.js";
6
+ const execFileP = promisify(execFile);
7
+ const MARKER_PREFIX = "# xcoder-schedule:";
8
+ const WIN_TASK_PREFIX = "xcoder_"; // schtasks task names: keep it simple/safe, no spaces or special chars
9
+ /** Maximum characters of a Windows command line handed to `schtasks /TR`. */
10
+ const MAX_WINDOWS_ARG_LENGTH = 8191;
11
+ const isWindows = process.platform === "win32";
12
+ // ── Validation helpers (fail closed, never echo the offending value) ───────
13
+ function requireValidId(id) {
14
+ const result = validateJobId(id);
15
+ if (!result.ok)
16
+ throw new ScheduleValidationError(result.field, result.reason);
17
+ return result.value;
18
+ }
19
+ function requireValidCronExpr(cronExpr) {
20
+ const result = validateCronExpr(cronExpr);
21
+ if (!result.ok)
22
+ throw new ScheduleValidationError(result.field, result.reason);
23
+ return result.value;
24
+ }
25
+ function requireValidCommand(command) {
26
+ const result = validateCommand(command);
27
+ if (!result.ok)
28
+ throw new ScheduleValidationError(result.field, result.reason);
29
+ return result.value;
30
+ }
31
+ function requireValidDelay(delaySeconds) {
32
+ const result = validateDelaySeconds(delaySeconds);
33
+ if (!result.ok)
34
+ throw new ScheduleValidationError(result.field, result.reason);
35
+ return result.value;
36
+ }
37
+ /**
38
+ * Renders the crontab payload for one job.
39
+ *
40
+ * defect1.md: the previous version spliced `${cronExpr} ${command}` into a
41
+ * template string, so a newline in `command` produced TWO crontab job lines
42
+ * from ONE marker. The injected line carried no marker, so removeScheduled()
43
+ * could never revoke it — unattributable persistence. There is no escaping
44
+ * here at all: instead the renderer refuses to emit anything containing a line
45
+ * terminator, so one job is always exactly two lines.
46
+ */
47
+ export function renderPosixJob(job) {
48
+ const id = requireValidId(job.id);
49
+ const cronExpr = requireValidCronExpr(job.cronExpr);
50
+ const command = requireValidCommand(job.command);
51
+ const markerLine = `${MARKER_PREFIX}${id}`;
52
+ const jobLine = `${cronExpr} ${command}`;
53
+ // Belt-and-braces: validation above already guarantees this, but the whole
54
+ // point of the fix is that no renderer can ever emit an extra line.
55
+ for (const line of [markerLine, jobLine]) {
56
+ if (/[\r\n\0]/.test(line)) {
57
+ throw new ScheduleValidationError("command", "rendered crontab line must not contain a line terminator");
58
+ }
59
+ }
60
+ return `${markerLine}\n${jobLine}\n`;
61
+ }
62
+ /**
63
+ * Builds the `schtasks /TR` value for a command.
64
+ *
65
+ * defect1.md: the previous version embedded the command in a
66
+ * `powershell -Command "..."` string and escaped only the double quote, which
67
+ * is not a valid escaping rule for that quoting context (F2). Here the script
68
+ * is passed as base64 through PowerShell's stock `-EncodedCommand`, so the
69
+ * `-Command` quoting context is never entered at all and there is nothing left
70
+ * to escape: the alphabet of a base64 string contains no metacharacters.
71
+ */
72
+ export function buildWindowsTaskRun(command) {
73
+ const validated = requireValidCommand(command);
74
+ const encoded = Buffer.from(validated, "utf16le").toString("base64");
75
+ const run = `powershell.exe -NoProfile -NonInteractive -EncodedCommand ${encoded}`;
76
+ if (run.length > MAX_WINDOWS_ARG_LENGTH) {
77
+ throw new ScheduleValidationError("command", `encoded Task Scheduler action exceeds ${MAX_WINDOWS_ARG_LENGTH} characters`);
78
+ }
79
+ return run;
80
+ }
81
+ /** One-off PowerShell script: same base64 transport, so no quoting rules apply. */
82
+ function buildWindowsDelayedScript(delaySeconds, command) {
83
+ return `Start-Sleep -Seconds ${delaySeconds}; ${command}`;
84
+ }
85
+ // ─── POSIX (cron) implementation ────────────────────────────────────────────
86
+ async function readCrontab() {
87
+ try {
88
+ const { stdout } = await execFileP("crontab", ["-l"]);
89
+ return stdout;
90
+ }
91
+ catch {
92
+ return ""; // no crontab yet for this user
93
+ }
94
+ }
95
+ async function writeCrontab(content) {
96
+ await new Promise((resolve, reject) => {
97
+ const child = spawn("crontab", ["-"]);
98
+ child.stdin.write(content);
99
+ child.stdin.end();
100
+ child.on("close", (code) => (code === 0 ? resolve() : reject(new Error(`crontab write failed (exit ${code})`))));
101
+ });
102
+ }
103
+ /** Enforces the live-job cap BEFORE anything is written to the scheduler. */
104
+ async function assertWithinJobBudget(workspaceRoot) {
105
+ const live = await countLiveJobs(workspaceRoot);
106
+ if (live >= SCHEDULE_LIMITS.maxLiveJobs) {
107
+ throw new Error(`refusing to schedule: this workspace already has ${live} live job(s), the maximum is ${SCHEDULE_LIMITS.maxLiveJobs}. ` +
108
+ `Remove one with the "schedule" tool's "remove" operation first.`);
109
+ }
110
+ }
111
+ async function scheduleCronPosix(id, cronExpr, command) {
112
+ const current = await readCrontab();
113
+ const block = renderPosixJob({ id, cronExpr, command });
114
+ const separator = current === "" || current.endsWith("\n") ? "" : "\n";
115
+ await writeCrontab(current + separator + block);
116
+ return { id, cronExpr };
117
+ }
118
+ async function listScheduledPosix() {
119
+ const content = await readCrontab();
120
+ const lines = content.split("\n");
121
+ const jobs = [];
122
+ for (let i = 0; i < lines.length; i++) {
123
+ if (lines[i].startsWith(MARKER_PREFIX)) {
124
+ const id = lines[i].slice(MARKER_PREFIX.length);
125
+ const jobLine = lines[i + 1] ?? "";
126
+ const match = jobLine.match(/^(\S+\s+\S+\s+\S+\s+\S+\s+\S+)\s+(.*)$/);
127
+ if (match)
128
+ jobs.push({ id, cronExpr: match[1], command: match[2] });
129
+ }
130
+ }
131
+ return jobs;
132
+ }
133
+ async function removeScheduledPosix(id) {
134
+ const content = await readCrontab();
135
+ const lines = content.split("\n");
136
+ const out = [];
137
+ let skipNext = false;
138
+ let removed = false;
139
+ for (const line of lines) {
140
+ if (skipNext) {
141
+ skipNext = false;
142
+ continue;
143
+ }
144
+ if (line === `${MARKER_PREFIX}${id}`) {
145
+ skipNext = true;
146
+ removed = true;
147
+ continue;
148
+ }
149
+ out.push(line);
150
+ }
151
+ await writeCrontab(out.join("\n"));
152
+ return { removed };
153
+ }
154
+ function cronToSchtasks(cronExpr) {
155
+ const parts = cronExpr.trim().split(/\s+/);
156
+ if (parts.length !== 5) {
157
+ throw new Error(`Cron expression "${cronExpr}" doesn't have 5 fields — can't translate to Windows Task Scheduler.`);
158
+ }
159
+ const [min, hour, dom, month, dow] = parts;
160
+ // Every N minutes: "*/N * * * *"
161
+ const everyNMinutes = min.match(/^\*\/(\d+)$/);
162
+ if (everyNMinutes && hour === "*" && dom === "*" && month === "*" && dow === "*") {
163
+ return { sc: "MINUTE", extraArgs: ["/MO", everyNMinutes[1]] };
164
+ }
165
+ // Every N hours at minute M: "M */N * * *"
166
+ const everyNHours = hour.match(/^\*\/(\d+)$/);
167
+ if (/^\d+$/.test(min) && everyNHours && dom === "*" && month === "*" && dow === "*") {
168
+ return { sc: "HOURLY", extraArgs: ["/MO", everyNHours[1]] };
169
+ }
170
+ // Daily at a fixed time: "M H * * *"
171
+ if (/^\d+$/.test(min) && /^\d+$/.test(hour) && dom === "*" && month === "*" && dow === "*") {
172
+ return { sc: "DAILY", extraArgs: ["/ST", `${hour.padStart(2, "0")}:${min.padStart(2, "0")}`] };
173
+ }
174
+ // Weekly on a specific day at a fixed time: "M H * * D" (D = 0-6, Sun-Sat)
175
+ if (/^\d+$/.test(min) && /^\d+$/.test(hour) && dom === "*" && month === "*" && /^[0-6]$/.test(dow)) {
176
+ const days = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
177
+ return {
178
+ sc: "WEEKLY",
179
+ extraArgs: ["/D", days[Number(dow)], "/ST", `${hour.padStart(2, "0")}:${min.padStart(2, "0")}`],
180
+ };
181
+ }
182
+ // Monthly on a specific day-of-month at a fixed time: "M H D * *"
183
+ if (/^\d+$/.test(min) && /^\d+$/.test(hour) && /^\d+$/.test(dom) && month === "*" && dow === "*") {
184
+ return {
185
+ sc: "MONTHLY",
186
+ extraArgs: ["/D", dom, "/ST", `${hour.padStart(2, "0")}:${min.padStart(2, "0")}`],
187
+ };
188
+ }
189
+ throw new Error(`Cron expression "${cronExpr}" isn't one of the patterns translated to Windows Task Scheduler ` +
190
+ `(supported: "*/N * * * *", "M */N * * *", "M H * * *", "M H * * D", "M H D * *"). ` +
191
+ `Run this under WSL for full cron syntax support instead.`);
192
+ }
193
+ function winTaskName(id) {
194
+ return `${WIN_TASK_PREFIX}${id.replace(/[^a-zA-Z0-9_-]/g, "_")}`;
195
+ }
196
+ async function scheduleCronWin(id, cronExpr, command) {
197
+ const { sc, extraArgs } = cronToSchtasks(cronExpr);
198
+ const taskName = winTaskName(id);
199
+ // The action is built from base64, so the command never lands in a
200
+ // PowerShell `-Command` quoting context (defect1.md F2).
201
+ const tr = buildWindowsTaskRun(command);
202
+ await execFileP("schtasks", ["/Create", "/F", "/TN", taskName, "/SC", sc, ...extraArgs, "/TR", tr]);
203
+ return { id, cronExpr };
204
+ }
205
+ async function listScheduledWin() {
206
+ try {
207
+ const { stdout } = await execFileP("schtasks", ["/Query", "/FO", "CSV", "/V"]);
208
+ const lines = stdout.split("\n").filter(Boolean);
209
+ if (lines.length < 2)
210
+ return [];
211
+ const header = parseCsvLine(lines[0]);
212
+ const taskNameIdx = header.indexOf("TaskName");
213
+ const scheduleIdx = header.indexOf("Schedule Type");
214
+ const nextRunIdx = header.indexOf("Next Run Time");
215
+ const jobs = [];
216
+ for (const line of lines.slice(1)) {
217
+ const cols = parseCsvLine(line);
218
+ const taskPath = cols[taskNameIdx] ?? "";
219
+ const shortName = taskPath.split("\\").pop() ?? "";
220
+ if (!shortName.startsWith(WIN_TASK_PREFIX))
221
+ continue;
222
+ const id = shortName.slice(WIN_TASK_PREFIX.length);
223
+ jobs.push({
224
+ id,
225
+ cronExpr: cols[scheduleIdx] ?? "unknown",
226
+ command: `(see: schtasks /Query /TN "${taskPath}" /V /FO LIST - next run: ${cols[nextRunIdx] ?? "unknown"})`,
227
+ });
228
+ }
229
+ return jobs;
230
+ }
231
+ catch {
232
+ return [];
233
+ }
234
+ }
235
+ function parseCsvLine(line) {
236
+ // schtasks' CSV output is simple enough (no embedded commas within quoted values we care
237
+ // about parsing) that a basic quoted-field split covers it.
238
+ return line.split(",").map((c) => c.replace(/^"|"$/g, "").trim());
239
+ }
240
+ async function removeScheduledWin(id) {
241
+ try {
242
+ await execFileP("schtasks", ["/Delete", "/F", "/TN", winTaskName(id)]);
243
+ return { removed: true };
244
+ }
245
+ catch {
246
+ return { removed: false };
247
+ }
248
+ }
249
+ // ─── Public API (dispatches to the right platform implementation) ──────────
250
+ /**
251
+ * Registers a recurring job: cron on POSIX, a translated Windows Task Scheduler
252
+ * task on win32, tagged with an id for later listing/removal.
253
+ *
254
+ * Validates every field at the module boundary (TB4) before touching the OS, so
255
+ * a caller that imports this directly — bypassing both the tool-call guard and
256
+ * the tool registry — is still protected. Rejections throw
257
+ * ScheduleValidationError; the registry catches it to keep its {ok, output}
258
+ * contract.
259
+ *
260
+ * `workspaceRoot` is optional and defaults to the process cwd, which keeps
261
+ * `scheduleCron.length === 3` (asserted by scheduleTool.test.ts) intact.
262
+ */
263
+ export async function scheduleCron(id, cronExpr, command, workspaceRoot = process.cwd()) {
264
+ const validId = requireValidId(id);
265
+ const validCron = requireValidCronExpr(cronExpr);
266
+ const validCommand = requireValidCommand(command);
267
+ await assertWithinJobBudget(workspaceRoot);
268
+ const result = isWindows
269
+ ? await scheduleCronWin(validId, validCron, validCommand)
270
+ : await scheduleCronPosix(validId, validCron, validCommand);
271
+ await recordScheduleEvent(workspaceRoot, buildAuditRecord({ op: "create_cron", id: validId, cronExpr: validCron, command: validCommand }));
272
+ return result;
273
+ }
274
+ /**
275
+ * Schedules a one-off command to run after `delaySeconds`, surviving beyond the
276
+ * current process.
277
+ *
278
+ * Both the delay and the command are validated first. Neither platform
279
+ * interpolates the command into a shell quoting context in a way a newline
280
+ * could exploit: POSIX passes the command as a positional parameter to bash
281
+ * (never as script text), Windows passes it as a base64 -EncodedCommand.
282
+ */
283
+ export async function scheduleOnce(delaySeconds, command, workspaceRoot = process.cwd()) {
284
+ const delay = requireValidDelay(delaySeconds);
285
+ const validCommand = requireValidCommand(command);
286
+ if (isWindows) {
287
+ const script = buildWindowsDelayedScript(delay, validCommand);
288
+ const encoded = Buffer.from(script, "utf16le").toString("base64");
289
+ const child = spawn("powershell.exe", ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded], { detached: true, stdio: "ignore", windowsHide: true });
290
+ child.unref();
291
+ }
292
+ else {
293
+ // $1 = delay, $2 = command. The command is a single argv element, so it
294
+ // cannot terminate the script and start a second one.
295
+ const child = spawn("bash", ["-c", 'sleep "$1" && exec bash -c "$2"', "xcoder-schedule", String(delay), validCommand], { detached: true, stdio: "ignore" });
296
+ child.unref();
297
+ }
298
+ await recordScheduleEvent(workspaceRoot, buildAuditRecord({ op: "create_once", id: `once-${Date.now()}`, command: validCommand }));
299
+ return { scheduledFor: new Date(Date.now() + delay * 1000).toISOString() };
300
+ }
301
+ export async function listScheduled() {
302
+ return isWindows ? listScheduledWin() : listScheduledPosix();
303
+ }
304
+ /** Removes a job. The id is validated first so it cannot be used to address
305
+ * a task name or crontab marker outside this tool's namespace. */
306
+ export async function removeScheduled(id, workspaceRoot = process.cwd()) {
307
+ const validId = requireValidId(id);
308
+ const result = isWindows ? await removeScheduledWin(validId) : await removeScheduledPosix(validId);
309
+ if (result.removed) {
310
+ await recordScheduleEvent(workspaceRoot, buildAuditRecord({ op: "remove", id: validId, command: "" }));
311
+ }
312
+ return result;
313
+ }