agent-toolkit-cli 1.11.0__py3-none-win_amd64.whl

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 (438) hide show
  1. agent_toolkit/__init__.py +4 -0
  2. agent_toolkit/__main__.py +5 -0
  3. agent_toolkit/_paths.py +145 -0
  4. agent_toolkit/bin/.gitkeep +0 -0
  5. agent_toolkit/bin/agent-toolkit.exe +0 -0
  6. agent_toolkit/cli/__init__.py +0 -0
  7. agent_toolkit/cli/__main__.py +5 -0
  8. agent_toolkit/cli/build.py +278 -0
  9. agent_toolkit/cli/completion.py +297 -0
  10. agent_toolkit/cli/context_budget.py +455 -0
  11. agent_toolkit/cli/devcompanion.py +923 -0
  12. agent_toolkit/cli/devcompanion_queue.py +235 -0
  13. agent_toolkit/cli/diff.py +176 -0
  14. agent_toolkit/cli/doctor.py +1052 -0
  15. agent_toolkit/cli/insights.py +771 -0
  16. agent_toolkit/cli/install.py +706 -0
  17. agent_toolkit/cli/main.py +171 -0
  18. agent_toolkit/cli/mcp.py +537 -0
  19. agent_toolkit/cli/memory.py +739 -0
  20. agent_toolkit/cli/plugin.py +224 -0
  21. agent_toolkit/cli/project.py +459 -0
  22. agent_toolkit/cli/release.py +178 -0
  23. agent_toolkit/cli/skills.py +461 -0
  24. agent_toolkit/cli/uninstall.py +166 -0
  25. agent_toolkit/cli/update.py +298 -0
  26. agent_toolkit/cli/workspace.py +1713 -0
  27. agent_toolkit/compiler/hook_registry.py +110 -0
  28. agent_toolkit/compiler/loader.py +338 -0
  29. agent_toolkit/compiler/mcp_registry.py +87 -0
  30. agent_toolkit/compiler/model.py +182 -0
  31. agent_toolkit/compiler/provenance.py +140 -0
  32. agent_toolkit/compiler/registry_emit.py +263 -0
  33. agent_toolkit/compiler/target_registry.py +122 -0
  34. agent_toolkit/compiler/targets/__init__.py +1 -0
  35. agent_toolkit/compiler/targets/agent_plugins.py +160 -0
  36. agent_toolkit/compiler/targets/base.py +229 -0
  37. agent_toolkit/compiler/targets/claude_code.py +241 -0
  38. agent_toolkit/compiler/targets/codex.py +261 -0
  39. agent_toolkit/compiler/targets/copilot.py +275 -0
  40. agent_toolkit/compiler/targets/cursor.py +207 -0
  41. agent_toolkit/compiler/targets/gemini_cli.py +213 -0
  42. agent_toolkit/compiler/targets/muse_code.py +113 -0
  43. agent_toolkit/compiler/targets/opencode.py +204 -0
  44. agent_toolkit/compiler/targets/pi.py +263 -0
  45. agent_toolkit/compiler/targets/windsurf.py +267 -0
  46. agent_toolkit/compiler/tool_mapping.py +83 -0
  47. agent_toolkit/data/.gitignore +4 -0
  48. agent_toolkit/data/__init__.py +1 -0
  49. agent_toolkit/data/agents/agentic-security-reviewer/AGENT.md +60 -0
  50. agent_toolkit/data/agents/architect/AGENT.md +30 -0
  51. agent_toolkit/data/agents/assistant/AGENT.md +59 -0
  52. agent_toolkit/data/agents/build-error-resolver/AGENT.md +30 -0
  53. agent_toolkit/data/agents/client-workflow-bootstrap/AGENT.md +60 -0
  54. agent_toolkit/data/agents/code-reviewer/AGENT.md +49 -0
  55. agent_toolkit/data/agents/database-reviewer/AGENT.md +44 -0
  56. agent_toolkit/data/agents/docs-lookup/AGENT.md +28 -0
  57. agent_toolkit/data/agents/e2e-runner/AGENT.md +38 -0
  58. agent_toolkit/data/agents/performance-optimizer/AGENT.md +52 -0
  59. agent_toolkit/data/agents/planner/AGENT.md +41 -0
  60. agent_toolkit/data/agents/refactor-cleaner/AGENT.md +43 -0
  61. agent_toolkit/data/agents/reference-lookup/AGENT.md +33 -0
  62. agent_toolkit/data/agents/security-reviewer/AGENT.md +47 -0
  63. agent_toolkit/data/agents/tdd-guide/AGENT.md +58 -0
  64. agent_toolkit/data/agents/tech-assistant/AGENT.md +11 -0
  65. agent_toolkit/data/agents/typescript-reviewer/AGENT.md +61 -0
  66. agent_toolkit/data/capabilities/hooks/README.md +6 -0
  67. agent_toolkit/data/capabilities/hooks/pre-commit-validate.yaml +26 -0
  68. agent_toolkit/data/capabilities/hooks/scripts/pre-commit-validate.sh +41 -0
  69. agent_toolkit/data/capabilities/hooks/scripts/session-start-context.sh +11 -0
  70. agent_toolkit/data/capabilities/hooks/session-start-context.yaml +23 -0
  71. agent_toolkit/data/capabilities/targets/registry.yaml +90 -0
  72. agent_toolkit/data/capabilities/upstream.lock +118 -0
  73. agent_toolkit/data/catalogs/agent-catalog.yaml +81 -0
  74. agent_toolkit/data/catalogs/loop-catalog.yaml +55 -0
  75. agent_toolkit/data/catalogs/skill-catalog.yaml +520 -0
  76. agent_toolkit/data/catalogs/skills-layout.json +391 -0
  77. agent_toolkit/data/distributions/products.yaml +190 -0
  78. agent_toolkit/data/distributions/targets/claude-code.yaml +47 -0
  79. agent_toolkit/data/distributions/targets/cursor.yaml +42 -0
  80. agent_toolkit/data/distributions/targets/opencode.yaml +55 -0
  81. agent_toolkit/data/loops/changelog-drafter/loop.yaml +40 -0
  82. agent_toolkit/data/loops/ci-sweeper/loop.yaml +53 -0
  83. agent_toolkit/data/loops/daily-triage/loop.yaml +47 -0
  84. agent_toolkit/data/loops/dep-sweeper/loop.yaml +46 -0
  85. agent_toolkit/data/loops/issue-triage/loop.yaml +40 -0
  86. agent_toolkit/data/loops/oss-daily-briefing/loop.yaml +65 -0
  87. agent_toolkit/data/loops/oss-pr-monitor/loop.yaml +86 -0
  88. agent_toolkit/data/loops/oss-triage/loop.yaml +67 -0
  89. agent_toolkit/data/loops/post-merge-cleanup/loop.yaml +44 -0
  90. agent_toolkit/data/loops/pr-babysitter/loop.yaml +46 -0
  91. agent_toolkit/data/mcp/registry/chrome-devtools.yaml +61 -0
  92. agent_toolkit/data/mcp/registry/clickup.yaml +48 -0
  93. agent_toolkit/data/mcp/registry/figma.yaml +44 -0
  94. agent_toolkit/data/mcp/registry/github.yaml +52 -0
  95. agent_toolkit/data/mcp/registry/linear.yaml +47 -0
  96. agent_toolkit/data/mcp/registry/notion.yaml +48 -0
  97. agent_toolkit/data/mcp/registry/slack.yaml +46 -0
  98. agent_toolkit/data/mcp/templates/chrome-devtools/README.md +57 -0
  99. agent_toolkit/data/mcp/templates/chrome-devtools/config.template.json +6 -0
  100. agent_toolkit/data/mcp/templates/clickup/README.md +45 -0
  101. agent_toolkit/data/mcp/templates/clickup/config.template.json +8 -0
  102. agent_toolkit/data/mcp/templates/clickup/wrapper.sh +23 -0
  103. agent_toolkit/data/mcp/templates/figma/README.md +54 -0
  104. agent_toolkit/data/mcp/templates/figma/config.template.json +9 -0
  105. agent_toolkit/data/mcp/templates/github/README.md +16 -0
  106. agent_toolkit/data/mcp/templates/github/config.template.json +15 -0
  107. agent_toolkit/data/mcp/templates/github/wrapper.sh +6 -0
  108. agent_toolkit/data/mcp/templates/linear/README.md +49 -0
  109. agent_toolkit/data/mcp/templates/linear/config.template.json +10 -0
  110. agent_toolkit/data/mcp/templates/notion/README.md +7 -0
  111. agent_toolkit/data/mcp/templates/notion/config.template.json +8 -0
  112. agent_toolkit/data/mcp/templates/notion/wrapper.sh +23 -0
  113. agent_toolkit/data/mcp/templates/slack/README.md +8 -0
  114. agent_toolkit/data/mcp/templates/slack/config.template.json +9 -0
  115. agent_toolkit/data/mcp/templates/slack/wrapper.sh +23 -0
  116. agent_toolkit/data/packs/README.md +66 -0
  117. agent_toolkit/data/packs/agentic-security/README.md +19 -0
  118. agent_toolkit/data/packs/agentic-security/config.yaml +25 -0
  119. agent_toolkit/data/packs/architecture/README.md +22 -0
  120. agent_toolkit/data/packs/architecture/config.yaml +27 -0
  121. agent_toolkit/data/packs/code-quality/README.md +19 -0
  122. agent_toolkit/data/packs/code-quality/config.yaml +21 -0
  123. agent_toolkit/data/packs/delivery-discipline/README.md +19 -0
  124. agent_toolkit/data/packs/delivery-discipline/config.yaml +42 -0
  125. agent_toolkit/data/packs/design-engineering/README.md +19 -0
  126. agent_toolkit/data/packs/design-engineering/config.yaml +41 -0
  127. agent_toolkit/data/packs/engineering-workflow/README.md +21 -0
  128. agent_toolkit/data/packs/engineering-workflow/config.yaml +57 -0
  129. agent_toolkit/data/packs/oss-maintenance/README.md +245 -0
  130. agent_toolkit/data/packs/oss-maintenance/config.yaml +75 -0
  131. agent_toolkit/data/profiles/claude-code/CLAUDE.md +110 -0
  132. agent_toolkit/data/profiles/claude-code/agents/assistant.md +59 -0
  133. agent_toolkit/data/profiles/claude-code/agents/build-error-resolver.md +30 -0
  134. agent_toolkit/data/profiles/claude-code/agents/client-workflow-bootstrap.md +60 -0
  135. agent_toolkit/data/profiles/claude-code/agents/contribution-planner.md +39 -0
  136. agent_toolkit/data/profiles/claude-code/agents/database-reviewer.md +44 -0
  137. agent_toolkit/data/profiles/claude-code/agents/docs-lookup.md +28 -0
  138. agent_toolkit/data/profiles/claude-code/agents/e2e-runner.md +38 -0
  139. agent_toolkit/data/profiles/claude-code/agents/performance-optimizer.md +52 -0
  140. agent_toolkit/data/profiles/claude-code/agents/planner.md +41 -0
  141. agent_toolkit/data/profiles/claude-code/agents/refactor-cleaner.md +43 -0
  142. agent_toolkit/data/profiles/claude-code/agents/reference-lookup.md +33 -0
  143. agent_toolkit/data/profiles/claude-code/agents/security-reviewer.md +47 -0
  144. agent_toolkit/data/profiles/claude-code/agents/tdd-guide.md +58 -0
  145. agent_toolkit/data/profiles/claude-code/agents/typescript-reviewer.md +61 -0
  146. agent_toolkit/data/profiles/claude-code/settings.json +86 -0
  147. agent_toolkit/data/profiles/copilot/copilot-instructions.md +15 -0
  148. agent_toolkit/data/profiles/cursor/README.md +33 -0
  149. agent_toolkit/data/profiles/cursor/rules/architect.mdc +23 -0
  150. agent_toolkit/data/profiles/cursor/rules/assistant.mdc +61 -0
  151. agent_toolkit/data/profiles/cursor/rules/build-error-resolver.mdc +20 -0
  152. agent_toolkit/data/profiles/cursor/rules/code-reviewer.mdc +21 -0
  153. agent_toolkit/data/profiles/cursor/rules/database-reviewer.mdc +29 -0
  154. agent_toolkit/data/profiles/cursor/rules/docs-lookup.mdc +15 -0
  155. agent_toolkit/data/profiles/cursor/rules/e2e-runner.mdc +30 -0
  156. agent_toolkit/data/profiles/cursor/rules/performance-optimizer.mdc +27 -0
  157. agent_toolkit/data/profiles/cursor/rules/planner.mdc +28 -0
  158. agent_toolkit/data/profiles/cursor/rules/refactor-cleaner.mdc +26 -0
  159. agent_toolkit/data/profiles/cursor/rules/reference-lookup.mdc +20 -0
  160. agent_toolkit/data/profiles/cursor/rules/security-reviewer.mdc +20 -0
  161. agent_toolkit/data/profiles/cursor/rules/tdd-guide.mdc +26 -0
  162. agent_toolkit/data/profiles/cursor/rules/typescript-reviewer.mdc +28 -0
  163. agent_toolkit/data/profiles/muse-code/README.md +35 -0
  164. agent_toolkit/data/profiles/opencode/README.md +44 -0
  165. agent_toolkit/data/profiles/opencode/agents/architect.md +30 -0
  166. agent_toolkit/data/profiles/opencode/agents/assistant.md +96 -0
  167. agent_toolkit/data/profiles/opencode/agents/build-error-resolver.md +31 -0
  168. agent_toolkit/data/profiles/opencode/agents/client-workflow-bootstrap.md +66 -0
  169. agent_toolkit/data/profiles/opencode/agents/code-reviewer.md +47 -0
  170. agent_toolkit/data/profiles/opencode/agents/contribution-planner.md +44 -0
  171. agent_toolkit/data/profiles/opencode/agents/database-reviewer.md +43 -0
  172. agent_toolkit/data/profiles/opencode/agents/docs-lookup.md +28 -0
  173. agent_toolkit/data/profiles/opencode/agents/e2e-runner.md +33 -0
  174. agent_toolkit/data/profiles/opencode/agents/performance-optimizer.md +34 -0
  175. agent_toolkit/data/profiles/opencode/agents/planner.md +27 -0
  176. agent_toolkit/data/profiles/opencode/agents/refactor-cleaner.md +27 -0
  177. agent_toolkit/data/profiles/opencode/agents/reference-lookup.md +27 -0
  178. agent_toolkit/data/profiles/opencode/agents/security-reviewer.md +27 -0
  179. agent_toolkit/data/profiles/opencode/agents/tdd-guide.md +27 -0
  180. agent_toolkit/data/profiles/opencode/agents/typescript-reviewer.md +30 -0
  181. agent_toolkit/data/profiles/opencode/opencode.json +3 -0
  182. agent_toolkit/data/profiles/pi/skills/architect/skill.md +5 -0
  183. agent_toolkit/data/profiles/pi/skills/assistant/skill.md +3 -0
  184. agent_toolkit/data/profiles/pi/skills/code-reviewer/skill.md +5 -0
  185. agent_toolkit/data/profiles/pi/skills/planner/skill.md +3 -0
  186. agent_toolkit/data/profiles/pi/skills/security-reviewer/skill.md +3 -0
  187. agent_toolkit/data/profiles/windsurf/memories/global_rules.md +114 -0
  188. agent_toolkit/data/profiles/windsurf/rules/architect.mdc +23 -0
  189. agent_toolkit/data/profiles/windsurf/rules/assistant.mdc +61 -0
  190. agent_toolkit/data/profiles/windsurf/rules/build-error-resolver.mdc +20 -0
  191. agent_toolkit/data/profiles/windsurf/rules/code-reviewer.mdc +21 -0
  192. agent_toolkit/data/profiles/windsurf/rules/database-reviewer.mdc +29 -0
  193. agent_toolkit/data/profiles/windsurf/rules/docs-lookup.mdc +15 -0
  194. agent_toolkit/data/profiles/windsurf/rules/e2e-runner.mdc +30 -0
  195. agent_toolkit/data/profiles/windsurf/rules/performance-optimizer.mdc +27 -0
  196. agent_toolkit/data/profiles/windsurf/rules/planner.mdc +28 -0
  197. agent_toolkit/data/profiles/windsurf/rules/refactor-cleaner.mdc +26 -0
  198. agent_toolkit/data/profiles/windsurf/rules/reference-lookup.mdc +20 -0
  199. agent_toolkit/data/profiles/windsurf/rules/security-reviewer.mdc +20 -0
  200. agent_toolkit/data/profiles/windsurf/rules/tdd-guide.mdc +26 -0
  201. agent_toolkit/data/profiles/windsurf/rules/typescript-reviewer.mdc +28 -0
  202. agent_toolkit/data/skills/accessibility/review/SKILL.md +116 -0
  203. agent_toolkit/data/skills/accessibility/review/references/a11y-checklist.md +25 -0
  204. agent_toolkit/data/skills/accessibility/review/references/a11y-findings-template.md +56 -0
  205. agent_toolkit/data/skills/accessibility/review/references/research.md +47 -0
  206. agent_toolkit/data/skills/agentic-security/mcp-audit/SKILL.md +116 -0
  207. agent_toolkit/data/skills/agentic-security/mcp-audit/references/mcp-audit-template.md +51 -0
  208. agent_toolkit/data/skills/agentic-security/owasp-agentic-review/SKILL.md +73 -0
  209. agent_toolkit/data/skills/agentic-security/owasp-agentic-review/references/owasp-agentic-template.md +32 -0
  210. agent_toolkit/data/skills/agentic-security/supply-chain-audit/SKILL.md +142 -0
  211. agent_toolkit/data/skills/agentic-security/threat-modeling/SKILL.md +100 -0
  212. agent_toolkit/data/skills/agentic-security/threat-modeling/references/threat-model-template.md +55 -0
  213. agent_toolkit/data/skills/architecture/c4-model/SKILL.md +49 -0
  214. agent_toolkit/data/skills/cloud/aws-well-architected-review/SKILL.md +37 -0
  215. agent_toolkit/data/skills/cloud/cloud-design-patterns/SKILL.md +38 -0
  216. agent_toolkit/data/skills/core/assistant/SKILL.md +216 -0
  217. agent_toolkit/data/skills/core/assistant/references/AGENTS_TEMPLATE.md +0 -0
  218. agent_toolkit/data/skills/core/assistant/references/ORCHESTRATION.md +0 -0
  219. agent_toolkit/data/skills/core/assistant/references/REPO_INSPECTION.md +0 -0
  220. agent_toolkit/data/skills/core/dev-companion/SKILL.md +65 -0
  221. agent_toolkit/data/skills/core/dev-companion/references/LOOP_GUARDRAILS.md +0 -0
  222. agent_toolkit/data/skills/core/onboarding/SKILL.md +122 -0
  223. agent_toolkit/data/skills/core/output-handshake/SKILL.md +26 -0
  224. agent_toolkit/data/skills/core/pr-fallback/SKILL.md +35 -0
  225. agent_toolkit/data/skills/core/pr-fallback/references/pr-body-default.md +0 -0
  226. agent_toolkit/data/skills/core/project/SKILL.md +89 -0
  227. agent_toolkit/data/skills/core/workspace/SKILL.md +103 -0
  228. agent_toolkit/data/skills/core/workspace-knowledge-sync/SKILL.md +140 -0
  229. agent_toolkit/data/skills/data/dbt-validation/SKILL.md +41 -0
  230. agent_toolkit/data/skills/data/snowflake-validation/SKILL.md +38 -0
  231. agent_toolkit/data/skills/delivery/adr/SKILL.md +56 -0
  232. agent_toolkit/data/skills/delivery/adr/references/default-template.md +35 -0
  233. agent_toolkit/data/skills/delivery/adr/references/example-001-graphql-adoption.md +66 -0
  234. agent_toolkit/data/skills/delivery/agreement/SKILL.md +24 -0
  235. agent_toolkit/data/skills/delivery/agreement/references/default-template.md +17 -0
  236. agent_toolkit/data/skills/delivery/agreement/references/example-api-versioning.md +29 -0
  237. agent_toolkit/data/skills/delivery/bug/SKILL.md +26 -0
  238. agent_toolkit/data/skills/delivery/bug/references/default-template.md +26 -0
  239. agent_toolkit/data/skills/delivery/bug/references/example-search-filter-bug.md +58 -0
  240. agent_toolkit/data/skills/delivery/decision-log/SKILL.md +28 -0
  241. agent_toolkit/data/skills/delivery/decision-log/references/default-template.md +17 -0
  242. agent_toolkit/data/skills/delivery/decision-log/references/example-repository-pattern.md +27 -0
  243. agent_toolkit/data/skills/delivery/development-workflow/SKILL.md +34 -0
  244. agent_toolkit/data/skills/delivery/development-workflow/references/default-workflow-checklist.md +44 -0
  245. agent_toolkit/data/skills/delivery/epic/SKILL.md +22 -0
  246. agent_toolkit/data/skills/delivery/epic/references/default-template.md +26 -0
  247. agent_toolkit/data/skills/delivery/epic/references/example-unified-dashboard.md +40 -0
  248. agent_toolkit/data/skills/delivery/incident/SKILL.md +24 -0
  249. agent_toolkit/data/skills/delivery/incident/references/default-template.md +29 -0
  250. agent_toolkit/data/skills/delivery/incident/references/example-payment-outage.md +62 -0
  251. agent_toolkit/data/skills/delivery/management-unit-assessment/SKILL.md +104 -0
  252. agent_toolkit/data/skills/delivery/management-unit-assessment/references/default-template.md +24 -0
  253. agent_toolkit/data/skills/delivery/management-unit-assessment/references/example-team-assessment.md +126 -0
  254. agent_toolkit/data/skills/delivery/meeting-minutes/SKILL.md +25 -0
  255. agent_toolkit/data/skills/delivery/meeting-minutes/references/default-template.md +22 -0
  256. agent_toolkit/data/skills/delivery/meeting-minutes/references/example-weekly-sync.md +72 -0
  257. agent_toolkit/data/skills/delivery/planning/SKILL.md +31 -0
  258. agent_toolkit/data/skills/delivery/planning/references/default-template.md +25 -0
  259. agent_toolkit/data/skills/delivery/planning/references/example-sprint-planning.md +62 -0
  260. agent_toolkit/data/skills/delivery/prd/SKILL.md +46 -0
  261. agent_toolkit/data/skills/delivery/prd/references/default-template.md +31 -0
  262. agent_toolkit/data/skills/delivery/prd/references/example-unified-api.md +71 -0
  263. agent_toolkit/data/skills/delivery/project-assessment/SKILL.md +90 -0
  264. agent_toolkit/data/skills/delivery/project-assessment/references/default-template.md +26 -0
  265. agent_toolkit/data/skills/delivery/project-assessment/references/example-platform-assessment.md +122 -0
  266. agent_toolkit/data/skills/delivery/project-assessment-evidence/SKILL.md +88 -0
  267. agent_toolkit/data/skills/delivery/project-assessment-evidence/references/default-template.md +24 -0
  268. agent_toolkit/data/skills/delivery/project-assessment-evidence/references/example-evidence-map.md +46 -0
  269. agent_toolkit/data/skills/delivery/spike/SKILL.md +24 -0
  270. agent_toolkit/data/skills/delivery/spike/references/default-template.md +29 -0
  271. agent_toolkit/data/skills/delivery/spike/references/example-graphql-federation.md +79 -0
  272. agent_toolkit/data/skills/delivery/task/SKILL.md +21 -0
  273. agent_toolkit/data/skills/delivery/task/references/default-template.md +21 -0
  274. agent_toolkit/data/skills/delivery/task/references/example-nav-system.md +33 -0
  275. agent_toolkit/data/skills/delivery/technical-unit-assessment/SKILL.md +58 -0
  276. agent_toolkit/data/skills/delivery/technical-unit-assessment/references/default-template.md +26 -0
  277. agent_toolkit/data/skills/delivery/technical-unit-assessment/references/example-frontend-assessment.md +112 -0
  278. agent_toolkit/data/skills/delivery/technical-unit-assessment/references/indicator-groups.md +65 -0
  279. agent_toolkit/data/skills/delivery/trd/SKILL.md +49 -0
  280. agent_toolkit/data/skills/delivery/trd/references/default-template.md +31 -0
  281. agent_toolkit/data/skills/delivery/trd/references/example-api-migration.md +122 -0
  282. agent_toolkit/data/skills/delivery/user-story/SKILL.md +21 -0
  283. agent_toolkit/data/skills/delivery/user-story/references/default-template.md +21 -0
  284. agent_toolkit/data/skills/delivery/user-story/references/example-advanced-filtering.md +37 -0
  285. agent_toolkit/data/skills/delivery/work-item/SKILL.md +31 -0
  286. agent_toolkit/data/skills/delivery/work-item/references/default-template.md +21 -0
  287. agent_toolkit/data/skills/delivery/work-item/references/example-routing-dashboard.md +23 -0
  288. agent_toolkit/data/skills/delivery/workflow-client-bootstrap/SKILL.md +148 -0
  289. agent_toolkit/data/skills/delivery/workflow-client-bootstrap/questions.yaml +165 -0
  290. agent_toolkit/data/skills/delivery/workflow-generic-project/SKILL.md +79 -0
  291. agent_toolkit/data/skills/design/design-assessment/SKILL.md +150 -0
  292. agent_toolkit/data/skills/design/design-assessment/references/design-scorecard-template.md +78 -0
  293. agent_toolkit/data/skills/design/design-improvement/SKILL.md +167 -0
  294. agent_toolkit/data/skills/design/design-improvement/references/improvement-plan-template.md +113 -0
  295. agent_toolkit/data/skills/design/figma/LICENSE.txt +2 -0
  296. agent_toolkit/data/skills/design/figma/NOTICE.txt +25 -0
  297. agent_toolkit/data/skills/design/figma/SKILL.md +98 -0
  298. agent_toolkit/data/skills/design/figma/references/figma-mcp-config.md +82 -0
  299. agent_toolkit/data/skills/design/figma/references/figma-tools-and-prompts.md +34 -0
  300. agent_toolkit/data/skills/design/figma-code-connect-components/LICENSE.txt +2 -0
  301. agent_toolkit/data/skills/design/figma-code-connect-components/NOTICE.txt +18 -0
  302. agent_toolkit/data/skills/design/figma-code-connect-components/SKILL.md +354 -0
  303. agent_toolkit/data/skills/design/figma-code-connect-components/references/mapping-checklist.md +7 -0
  304. agent_toolkit/data/skills/design/figma-code-connect-components/scripts/normalize_node_id.py +25 -0
  305. agent_toolkit/data/skills/design/figma-create-design-system-rules/LICENSE.txt +2 -0
  306. agent_toolkit/data/skills/design/figma-create-design-system-rules/NOTICE.txt +19 -0
  307. agent_toolkit/data/skills/design/figma-create-design-system-rules/SKILL.md +554 -0
  308. agent_toolkit/data/skills/design/figma-create-design-system-rules/references/rule-template.md +15 -0
  309. agent_toolkit/data/skills/design/figma-create-design-system-rules/scripts/check_agents_md.sh +9 -0
  310. agent_toolkit/data/skills/design/figma-create-new-file/LICENSE.txt +2 -0
  311. agent_toolkit/data/skills/design/figma-create-new-file/NOTICE.txt +17 -0
  312. agent_toolkit/data/skills/design/figma-create-new-file/SKILL.md +72 -0
  313. agent_toolkit/data/skills/design/figma-implement-design/LICENSE.txt +2 -0
  314. agent_toolkit/data/skills/design/figma-implement-design/NOTICE.txt +19 -0
  315. agent_toolkit/data/skills/design/figma-implement-design/SKILL.md +268 -0
  316. agent_toolkit/data/skills/design/frontend-design/LICENSE.txt +177 -0
  317. agent_toolkit/data/skills/design/frontend-design/SKILL.md +82 -0
  318. agent_toolkit/data/skills/design/frontend-design/UPSTREAM.md +14 -0
  319. agent_toolkit/data/skills/design/frontend-design-review/LICENSE +21 -0
  320. agent_toolkit/data/skills/design/frontend-design-review/SKILL.md +194 -0
  321. agent_toolkit/data/skills/design/frontend-design-review/references/pattern-examples.md +21 -0
  322. agent_toolkit/data/skills/design/frontend-design-review/references/quick-checklist.md +38 -0
  323. agent_toolkit/data/skills/design/frontend-design-review/references/review-output-format.md +68 -0
  324. agent_toolkit/data/skills/design/frontend-design-review/references/review-type-modifiers.md +31 -0
  325. agent_toolkit/data/skills/design/web-design-guidelines/SKILL.md +78 -0
  326. agent_toolkit/data/skills/design/web-design-guidelines/references/LICENSE +21 -0
  327. agent_toolkit/data/skills/design/web-design-guidelines/references/web-interface-guidelines.md +180 -0
  328. agent_toolkit/data/skills/forge/gh-address-comments/LICENSE.txt +202 -0
  329. agent_toolkit/data/skills/forge/gh-address-comments/NOTICE.txt +20 -0
  330. agent_toolkit/data/skills/forge/gh-address-comments/SKILL.md +72 -0
  331. agent_toolkit/data/skills/forge/gh-address-comments/scripts/fetch_comments.py +239 -0
  332. agent_toolkit/data/skills/forge/gh-contribution-planner/SKILL.md +160 -0
  333. agent_toolkit/data/skills/forge/gh-contribution-planner/scripts/inspect_contributions.py +818 -0
  334. agent_toolkit/data/skills/forge/gh-fix-ci/LICENSE.txt +201 -0
  335. agent_toolkit/data/skills/forge/gh-fix-ci/NOTICE.txt +20 -0
  336. agent_toolkit/data/skills/forge/gh-fix-ci/SKILL.md +74 -0
  337. agent_toolkit/data/skills/forge/gh-fix-ci/scripts/inspect_pr_checks.py +509 -0
  338. agent_toolkit/data/skills/forge/github-cli-workflow/SKILL.md +49 -0
  339. agent_toolkit/data/skills/forge/gitlab-cli-workflow/SKILL.md +44 -0
  340. agent_toolkit/data/skills/forge/workflow-client-bootstrap/SKILL.md +14 -0
  341. agent_toolkit/data/skills/forge/workflow-generic-project/SKILL.md +14 -0
  342. agent_toolkit/data/skills/forge/worktree/SKILL.md +113 -0
  343. agent_toolkit/data/skills/integrations/clickup-cli/SKILL.md +78 -0
  344. agent_toolkit/data/skills/integrations/clickup-cli/references/docs-management.md +57 -0
  345. agent_toolkit/data/skills/integrations/clickup-cli/references/task-management.md +131 -0
  346. agent_toolkit/data/skills/integrations/clickup-cli/references/time-tracking.md +38 -0
  347. agent_toolkit/data/skills/integrations/linear/LICENSE.txt +202 -0
  348. agent_toolkit/data/skills/integrations/linear/NOTICE.txt +23 -0
  349. agent_toolkit/data/skills/integrations/linear/SKILL.md +134 -0
  350. agent_toolkit/data/skills/integrations/mcp/SKILL.md +88 -0
  351. agent_toolkit/data/skills/integrations/slack-assistant/SKILL.md +138 -0
  352. agent_toolkit/data/skills/integrations/slack-cli/SKILL.md +109 -0
  353. agent_toolkit/data/skills/integrations/slack-cli/references/INSTALLATION.md +42 -0
  354. agent_toolkit/data/skills/loops/loop-runner/SKILL.md +92 -0
  355. agent_toolkit/data/skills/ops/docs-generator/SKILL.md +120 -0
  356. agent_toolkit/data/skills/ops/llm-cost-advisor/SKILL.md +87 -0
  357. agent_toolkit/data/skills/ops/swarm/SKILL.md +108 -0
  358. agent_toolkit/data/skills/ops/swarm-handoff/SKILL.md +112 -0
  359. agent_toolkit/data/skills/ops/swarm-observer/SKILL.md +102 -0
  360. agent_toolkit/data/skills/ops/triage/SKILL.md +119 -0
  361. agent_toolkit/data/skills/quality/codeql/SKILL.md +106 -0
  362. agent_toolkit/data/skills/quality/codeql/references/codeql-queries.md +43 -0
  363. agent_toolkit/data/skills/quality/megalinter/SKILL.md +162 -0
  364. agent_toolkit/data/skills/quality/megalinter/references/megalinter-images.md +36 -0
  365. agent_toolkit/data/skills/quality/megalinter/references/megalinter-license.md +41 -0
  366. agent_toolkit/data/skills/quality/megalinter/references/megalinter-targets.md +66 -0
  367. agent_toolkit/data/skills/tooling/chrome-devtools/SKILL.md +146 -0
  368. agent_toolkit/data/skills/tooling/herdr/SKILL.md +109 -0
  369. agent_toolkit/data/skills/tooling/inventory/SKILL.md +81 -0
  370. agent_toolkit/data/skills/tooling/jupyter-notebook/LICENSE.txt +201 -0
  371. agent_toolkit/data/skills/tooling/jupyter-notebook/NOTICE.txt +27 -0
  372. agent_toolkit/data/skills/tooling/jupyter-notebook/SKILL.md +145 -0
  373. agent_toolkit/data/skills/tooling/jupyter-notebook/assets/experiment-template.ipynb +117 -0
  374. agent_toolkit/data/skills/tooling/jupyter-notebook/assets/tutorial-template.ipynb +115 -0
  375. agent_toolkit/data/skills/tooling/jupyter-notebook/references/experiment-patterns.md +10 -0
  376. agent_toolkit/data/skills/tooling/jupyter-notebook/references/notebook-structure.md +17 -0
  377. agent_toolkit/data/skills/tooling/jupyter-notebook/references/quality-checklist.md +11 -0
  378. agent_toolkit/data/skills/tooling/jupyter-notebook/references/tutorial-patterns.md +9 -0
  379. agent_toolkit/data/skills/tooling/jupyter-notebook/scripts/new_notebook.py +132 -0
  380. agent_toolkit/data/skills/tooling/mermaid/SKILL.md +36 -0
  381. agent_toolkit/data/skills/tooling/playwright-cli/LICENSE.txt +201 -0
  382. agent_toolkit/data/skills/tooling/playwright-cli/NOTICE.txt +29 -0
  383. agent_toolkit/data/skills/tooling/playwright-cli/SKILL.md +154 -0
  384. agent_toolkit/data/skills/tooling/playwright-cli/references/cli.md +116 -0
  385. agent_toolkit/data/skills/tooling/playwright-cli/references/workflows.md +98 -0
  386. agent_toolkit/data/skills/tooling/playwright-cli/scripts/executable_playwright_cli.sh +25 -0
  387. agent_toolkit/data_cache.py +79 -0
  388. agent_toolkit/data_sync.py +144 -0
  389. agent_toolkit/installer/__init__.py +0 -0
  390. agent_toolkit/installer/merge.py +59 -0
  391. agent_toolkit/installer/receipt.py +89 -0
  392. agent_toolkit/installer/sources.py +92 -0
  393. agent_toolkit/installer/tracking.py +63 -0
  394. agent_toolkit/launcher.py +69 -0
  395. agent_toolkit/loop/__init__.py +0 -0
  396. agent_toolkit/loop/budget.py +107 -0
  397. agent_toolkit/loop/gh_gate.py +923 -0
  398. agent_toolkit/loop/loop-gh-gate +923 -0
  399. agent_toolkit/loop/pack.py +65 -0
  400. agent_toolkit/loop/runner.py +2722 -0
  401. agent_toolkit/runner/__init__.py +0 -0
  402. agent_toolkit/runner/dispatcher.py +163 -0
  403. agent_toolkit/runner/policy.py +356 -0
  404. agent_toolkit/runner/providers/__init__.py +21 -0
  405. agent_toolkit/runner/providers/anthropic_provider.py +109 -0
  406. agent_toolkit/runner/providers/base.py +53 -0
  407. agent_toolkit/runner/providers/ollama_provider.py +108 -0
  408. agent_toolkit/runner/providers/openai_provider.py +103 -0
  409. agent_toolkit/runner/providers/opencode_provider.py +127 -0
  410. agent_toolkit/swarm/__init__.py +5 -0
  411. agent_toolkit/swarm/approvals.py +121 -0
  412. agent_toolkit/swarm/backends/__init__.py +596 -0
  413. agent_toolkit/swarm/budget.py +83 -0
  414. agent_toolkit/swarm/cli.py +2448 -0
  415. agent_toolkit/swarm/config.py +351 -0
  416. agent_toolkit/swarm/handoff.py +174 -0
  417. agent_toolkit/swarm/models.py +230 -0
  418. agent_toolkit/swarm/prompts.py +177 -0
  419. agent_toolkit/swarm/recipes.py +304 -0
  420. agent_toolkit/swarm/runner.py +267 -0
  421. agent_toolkit/swarm/state.py +93 -0
  422. agent_toolkit/swarm/store.py +148 -0
  423. agent_toolkit/swarm/worktree.py +105 -0
  424. agent_toolkit/templates/workspace/.gitignore +19 -0
  425. agent_toolkit/templates/workspace/AGENTS.md +82 -0
  426. agent_toolkit/templates/workspace/knowledge/README.md +22 -0
  427. agent_toolkit/templates/workspace/knowledge/learnings/general.md +3 -0
  428. agent_toolkit/templates/workspace/knowledge/todos/pending.md +7 -0
  429. agent_toolkit/templates/workspace/packs/README.md +24 -0
  430. agent_toolkit/templates/workspace/personas/architect.md +12 -0
  431. agent_toolkit/templates/workspace/personas/implementer.md +12 -0
  432. agent_toolkit/templates/workspace/personas/researcher.md +12 -0
  433. agent_toolkit/templates/workspace/personas/reviewer.md +12 -0
  434. agent_toolkit_cli-1.11.0.dist-info/METADATA +363 -0
  435. agent_toolkit_cli-1.11.0.dist-info/RECORD +438 -0
  436. agent_toolkit_cli-1.11.0.dist-info/WHEEL +4 -0
  437. agent_toolkit_cli-1.11.0.dist-info/entry_points.txt +4 -0
  438. agent_toolkit_cli-1.11.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,2722 @@
1
+ #!/usr/bin/env python3
2
+ # /// script
3
+ # requires-python = ">=3.10"
4
+ # dependencies = []
5
+ # ///
6
+ """
7
+ bin/loop — Loop engineering CLI for AI Workspace.
8
+
9
+ A "loop" is a recurring AI-driven process with durable state, safety gates,
10
+ and cost budgets. Inspired by loop engineering principles (Cobus Greyling,
11
+ Boris Cherny, Peter Steinberger, Addy Osmani — 2026).
12
+
13
+ Usage:
14
+ loop init <pattern> Scaffold a loop from a starter template
15
+ loop run <loop> [options] Execute a loop run
16
+ loop list List detected loops (same as run resolution)
17
+ loop status [loop] Show loop status (all, or one)
18
+ loop audit [loop] Summarize past runs (success rate, cost)
19
+ loop cost <loop> Estimate cost for one run
20
+ loop schedule <loop> Install systemd/launchd timer
21
+ loop sync Regenerate knowledge todos from completed runs
22
+ loop help Show this help
23
+
24
+ loop run options:
25
+ --force Bypass max_runs_per_day only (not wall/token budgets)
26
+ --quiet Suppress live runner output and trace progress lines
27
+ --pack PATH Apply loop overrides (enabled/cadence/budget) from pack YAML
28
+ --runner NAME Force a runner (default: auto, or $AGENT_TOOLKIT_LOOP_RUNNER)
29
+
30
+ Runners (auto tries in order until one is available):
31
+ auto Try harness → claude → opencode → cursor → copilot → codex → muse → queue
32
+ harness agentic-workstation / dots-ai-devcompanion runner (HARNESS_RUNNER_DIR)
33
+ claude Claude Code CLI (`claude --print`)
34
+ opencode OpenCode CLI (`opencode run`)
35
+ cursor Cursor Agent CLI (`cursor-agent` / `agent` / `cursor` --print)
36
+ copilot GitHub Copilot CLI (`copilot -p`)
37
+ codex OpenAI Codex CLI (`codex exec`)
38
+ muse Muse CLI (`muse exec`)
39
+ queue Queue via agent-toolkit devcompanion (async worker)
40
+ skeleton Write plan.md only (no LLM)
41
+
42
+ Environment:
43
+ AGENT_TOOLKIT_LOOP_RUNNER Default --runner when the flag is omitted (e.g. claude)
44
+ AGENT_TOOLKIT_WORKSPACE Workspace root override (also: HARNESS_DIR)
45
+ HARNESS_RUNNER_DIR Path to dots-ai-devcompanion runner package (harness)
46
+ HARNESS_DC_HOME Devcompanion queue home (queue runner / harness jobs)
47
+ CURSOR_API_KEY Auth for Cursor Agent CLI (cursor runner)
48
+ COPILOT_GITHUB_TOKEN Auth for Copilot CLI (also: GH_TOKEN / GITHUB_TOKEN)
49
+ OPENAI_API_KEY / CODEX_API_KEY
50
+ Auth for Codex CLI (codex runner)
51
+ """
52
+
53
+ from __future__ import annotations
54
+
55
+ import sys as _sys_win
56
+
57
+ # Windows: force UTF-8 output so Unicode chars (── ✓ ✗) don't crash
58
+ if _sys_win.platform == "win32":
59
+ try:
60
+ _sys_win.stdout.reconfigure(encoding="utf-8", errors="replace") # type: ignore
61
+ _sys_win.stderr.reconfigure(encoding="utf-8", errors="replace") # type: ignore
62
+ except Exception:
63
+ pass
64
+
65
+ import hashlib
66
+ import json
67
+ import os
68
+ import platform
69
+ import re
70
+ import shutil
71
+ import signal
72
+ import subprocess
73
+ import sys
74
+ from datetime import datetime, timezone
75
+ from pathlib import Path
76
+ from typing import Any
77
+
78
+ # ── cancellation ──────────────────────────────────────────────────────────────
79
+
80
+ _CANCELLED = False
81
+ _PROGRESS_QUIET = False
82
+
83
+ # Explicit + auto runner selection (--runner / AGENT_TOOLKIT_LOOP_RUNNER)
84
+ RUNNER_AUTO = "auto"
85
+ RUNNER_NAMES = (
86
+ "harness",
87
+ "claude",
88
+ "opencode",
89
+ "cursor",
90
+ "copilot",
91
+ "codex",
92
+ "muse",
93
+ "queue",
94
+ "skeleton",
95
+ )
96
+ RUNNER_ALIASES = {
97
+ "devcompanion": "queue",
98
+ "dc": "queue",
99
+ "agent-toolkit": "harness",
100
+ "cursor-agent": "cursor",
101
+ "github-copilot": "copilot",
102
+ "openai-codex": "codex",
103
+ "muse-code": "muse",
104
+ }
105
+
106
+
107
+ class _TraceTailer:
108
+ """Print trace.jsonl events as they are appended during a run."""
109
+
110
+ def __init__(self, trace_file: Path, *, max_tokens: int | None = None) -> None:
111
+ self._trace_file = trace_file
112
+ self._offset = 0
113
+ self._stop = False
114
+ self._max_tokens = max_tokens
115
+ self.tokens_used = 0
116
+ self.budget_exhausted = False
117
+
118
+ def poll(self) -> None:
119
+ if not self._trace_file.exists():
120
+ return
121
+ data = self._trace_file.read_text(encoding="utf-8")
122
+ if len(data) <= self._offset:
123
+ return
124
+ chunk = data[self._offset :]
125
+ self._offset = len(data)
126
+ for line in chunk.splitlines():
127
+ line = line.strip()
128
+ if not line:
129
+ continue
130
+ try:
131
+ event = json.loads(line)
132
+ except json.JSONDecodeError:
133
+ continue
134
+ self._emit(event)
135
+
136
+ def _emit(self, event: dict[str, Any]) -> None:
137
+ kind = event.get("kind", "")
138
+ if kind in ("run_start", "run_end", "worktree_created", "queued"):
139
+ log(f"trace:{kind}")
140
+ elif kind == "repo":
141
+ log(f"repo: {event.get('name', event.get('path', '?'))}")
142
+ elif kind == "token_usage":
143
+ total = event.get("total_tokens") or event.get("total")
144
+ if total is not None:
145
+ self.tokens_used = max(self.tokens_used, int(total))
146
+ cost = event.get("cost_usd")
147
+ if cost is not None:
148
+ log(f"tokens: {total} (~${cost})")
149
+ elif total is not None:
150
+ log(f"tokens: {total}")
151
+ if self._max_tokens is not None and self.tokens_used >= self._max_tokens:
152
+ self.budget_exhausted = True
153
+ elif kind in ("prompt", "completion"):
154
+ self.tokens_used += int(event.get("prompt_tokens", 0) or 0)
155
+ self.tokens_used += int(event.get("completion_tokens", 0) or 0)
156
+ if self._max_tokens is not None and self.tokens_used >= self._max_tokens:
157
+ self.budget_exhausted = True
158
+ elif kind == "progress":
159
+ current = event.get("current")
160
+ total = event.get("total")
161
+ label = event.get("label", "progress")
162
+ if current is not None and total is not None:
163
+ log(f"{label}: {current}/{total}")
164
+ else:
165
+ log(f"{label}: {event.get('message', '')}")
166
+
167
+ def stop(self) -> None:
168
+ self._stop = True
169
+
170
+
171
+ def _run_with_live_output(
172
+ cmd: list[str],
173
+ *,
174
+ input_text: str,
175
+ cwd: str,
176
+ env: dict[str, str],
177
+ trace_file: Path | None = None,
178
+ timeout: int = 900,
179
+ max_tokens: int | None = None,
180
+ ) -> subprocess.CompletedProcess[str]:
181
+ """Run a subprocess, streaming stdout/stderr unless --quiet."""
182
+ if _PROGRESS_QUIET:
183
+ return subprocess.run(
184
+ cmd,
185
+ input=input_text,
186
+ capture_output=True,
187
+ text=True,
188
+ cwd=cwd,
189
+ timeout=timeout,
190
+ env=env,
191
+ )
192
+
193
+ import threading
194
+ import time
195
+
196
+ tailer = _TraceTailer(trace_file, max_tokens=max_tokens) if trace_file else None
197
+ proc = subprocess.Popen(
198
+ cmd,
199
+ stdin=subprocess.PIPE,
200
+ stdout=subprocess.PIPE,
201
+ stderr=subprocess.STDOUT,
202
+ text=True,
203
+ cwd=cwd,
204
+ env=env,
205
+ )
206
+ assert proc.stdin is not None and proc.stdout is not None
207
+ proc.stdin.write(input_text)
208
+ proc.stdin.close()
209
+
210
+ lines: list[str] = []
211
+
212
+ def _pump() -> None:
213
+ for line in iter(proc.stdout.readline, ""):
214
+ lines.append(line)
215
+ print(f"{dim('[runner]')} {line.rstrip()}", flush=True)
216
+
217
+ def _tail() -> None:
218
+ while proc.poll() is None and not _CANCELLED:
219
+ if tailer:
220
+ tailer.poll()
221
+ if tailer.budget_exhausted:
222
+ warn(
223
+ f"Token budget exhausted ({tailer.tokens_used:,} tokens); "
224
+ "terminating runner"
225
+ )
226
+ proc.kill()
227
+ break
228
+ time.sleep(0.25)
229
+ if tailer:
230
+ tailer.poll()
231
+
232
+ pump_thread = threading.Thread(target=_pump, daemon=True)
233
+ tail_thread = threading.Thread(target=_tail, daemon=True)
234
+ pump_thread.start()
235
+ tail_thread.start()
236
+ try:
237
+ proc.wait(timeout=timeout)
238
+ except subprocess.TimeoutExpired:
239
+ proc.kill()
240
+ raise
241
+ if tailer and tailer.budget_exhausted:
242
+ raise subprocess.TimeoutExpired(cmd, timeout)
243
+ pump_thread.join(timeout=1)
244
+ tail_thread.join(timeout=1)
245
+ stdout = "".join(lines)
246
+ return subprocess.CompletedProcess(cmd, proc.returncode or 0, stdout, "")
247
+
248
+
249
+ def _handle_sig(signum: int, _frame) -> None:
250
+ global _CANCELLED
251
+ if _CANCELLED:
252
+ sys.exit(1)
253
+ _CANCELLED = True
254
+ print(file=sys.stderr)
255
+ warn("Received signal — cancelling (press again to force exit)")
256
+
257
+
258
+ signal.signal(signal.SIGINT, _handle_sig)
259
+ signal.signal(signal.SIGTERM, _handle_sig)
260
+
261
+
262
+ # ── paths ─────────────────────────────────────────────────────────────────────
263
+
264
+
265
+ def _find_toolkit_root() -> Path:
266
+ """Locate toolkit data (bundled loops/profiles). Prefer shared toolkit_root()."""
267
+ try:
268
+ from agent_toolkit._paths import toolkit_root
269
+
270
+ return toolkit_root()
271
+ except Exception:
272
+ pass
273
+ try:
274
+ pkg_data = Path(__file__).resolve().parent.parent / "data"
275
+ if pkg_data.is_dir() and (pkg_data / "loops").is_dir():
276
+ return pkg_data
277
+ except Exception:
278
+ pass
279
+ here = Path(__file__).resolve().parent
280
+ for candidate in [here.parent.parent.parent, here.parent.parent, here.parent]:
281
+ if (candidate / "loops").is_dir():
282
+ return candidate
283
+ return Path.cwd()
284
+
285
+
286
+ def workspace_root() -> Path:
287
+ """User workspace root for loop instances (#200 / #207)."""
288
+ from agent_toolkit._paths import find_workspace_root
289
+
290
+ ws = find_workspace_root()
291
+ if ws is not None:
292
+ return ws
293
+ for env in ("AGENT_TOOLKIT_ROOT", "AI_WORKSPACE"):
294
+ val = os.environ.get(env, "").strip()
295
+ if val:
296
+ return Path(val).expanduser().resolve()
297
+ return Path.cwd()
298
+
299
+
300
+ def loops_dir() -> Path:
301
+ """User-created loop instances live under workspace/loops/ (#200)."""
302
+ return workspace_root() / "loops"
303
+
304
+
305
+ def toolkit_loops_dir() -> Path:
306
+ """Bundled reference templates under toolkit data/loops/."""
307
+ return _find_toolkit_root() / "loops"
308
+
309
+
310
+ # Back-compat aliases (recomputed each access via functions preferred)
311
+ WORKSPACE_ROOT = Path.cwd() # placeholder; prefer workspace_root()
312
+ LOOPS_DIR = Path.cwd() / "loops"
313
+ TEMPLATES_DIR = Path.cwd() / "loops"
314
+ WORKTREES_HOME = Path(
315
+ os.environ.get("HARNESS_WORKTREES_DIR", "")
316
+ or Path.home() / ".local" / "share" / "agent-toolkit" / "worktrees"
317
+ )
318
+
319
+ # Devcompanion queue paths (shared with bin/devcompanion)
320
+ _DC_HOME = Path(
321
+ os.environ.get("HARNESS_DC_HOME")
322
+ or Path.home() / ".local" / "share" / "agent-toolkit" / "dev-companion"
323
+ )
324
+ _QUEUE_PENDING = _DC_HOME / "queue" / "pending"
325
+ _QUEUE_DONE = _DC_HOME / "queue" / "done"
326
+ _QUEUE_FAILED = _DC_HOME / "queue" / "failed"
327
+
328
+ # ── colors ────────────────────────────────────────────────────────────────────
329
+
330
+ _USE_COLOR = sys.stdout.isatty() and not os.environ.get("NO_COLOR")
331
+
332
+
333
+ def _c(code: str, text: str) -> str:
334
+ return f"\033[{code}m{text}\033[0m" if _USE_COLOR else text
335
+
336
+
337
+ def blue(t: str) -> str:
338
+ return _c("1;34", t)
339
+
340
+
341
+ def green(t: str) -> str:
342
+ return _c("1;32", t)
343
+
344
+
345
+ def yellow(t: str) -> str:
346
+ return _c("1;33", t)
347
+
348
+
349
+ def red(t: str) -> str:
350
+ return _c("1;31", t)
351
+
352
+
353
+ def dim(t: str) -> str:
354
+ return _c("0;37", t)
355
+
356
+
357
+ def log(msg: str) -> None:
358
+ print(f"{blue('[loop]')} {msg}")
359
+
360
+
361
+ def ok(msg: str) -> None:
362
+ print(f"{green('[loop]')} {msg}")
363
+
364
+
365
+ def warn(msg: str) -> None:
366
+ print(f"{yellow('[loop]')} {msg}", file=sys.stderr)
367
+
368
+
369
+ def err(msg: str) -> None:
370
+ print(f"{red('[loop]')} {msg}", file=sys.stderr)
371
+
372
+
373
+ # ── helpers ───────────────────────────────────────────────────────────────────
374
+
375
+
376
+ def utc_now() -> str:
377
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
378
+
379
+
380
+ def run_id() -> str:
381
+ ts = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
382
+ import uuid
383
+
384
+ return f"{ts}-{uuid.uuid4().hex[:6]}"
385
+
386
+
387
+ def parse_md_frontmatter(md_path: Path) -> dict[str, Any]:
388
+ """Parse YAML frontmatter from any markdown file."""
389
+ if not md_path.exists():
390
+ return {}
391
+
392
+ text = md_path.read_text(encoding="utf-8")
393
+ lines = text.splitlines()
394
+ if not lines or lines[0].strip() != "---":
395
+ return {}
396
+
397
+ end = next((i for i, line in enumerate(lines[1:], 1) if line.strip() == "---"), None)
398
+ if end is None:
399
+ return {}
400
+
401
+ yaml_block = "\n".join(lines[1:end])
402
+ try:
403
+ import yaml # type: ignore
404
+
405
+ return yaml.safe_load(yaml_block) or {}
406
+ except ImportError:
407
+ return _parse_simple_yaml(yaml_block)
408
+
409
+
410
+ def parse_loop_md(loop_dir: Path) -> dict[str, Any]:
411
+ """Parse loop config from LOOP.md frontmatter or loop.yaml."""
412
+ loop_md = loop_dir / "LOOP.md"
413
+ loop_yaml = loop_dir / "loop.yaml"
414
+ if loop_md.exists():
415
+ return parse_md_frontmatter(loop_md)
416
+ if loop_yaml.exists():
417
+ text = loop_yaml.read_text()
418
+ return _parse_simple_yaml(text)
419
+ return {}
420
+
421
+
422
+ def _parse_simple_yaml(text: str) -> dict[str, Any]:
423
+ """Minimal YAML parser for loop frontmatter (no PyYAML required)."""
424
+ result: dict[str, Any] = {}
425
+ current_key: str | None = None
426
+ list_items: list[str] = []
427
+ in_budget = False
428
+ budget: dict[str, Any] = {}
429
+
430
+ for line in text.splitlines():
431
+ stripped = line.strip()
432
+ if not stripped or stripped.startswith("#"):
433
+ continue
434
+
435
+ if stripped == "budget:":
436
+ in_budget = True
437
+ current_key = "budget"
438
+ continue
439
+
440
+ if in_budget and line.startswith(" ") and ":" in stripped:
441
+ k, _, v = stripped.partition(":")
442
+ try:
443
+ budget[k.strip()] = int(v.strip())
444
+ except ValueError:
445
+ budget[k.strip()] = v.strip()
446
+ continue
447
+ else:
448
+ in_budget = False
449
+ if "budget" in result and isinstance(result.get("budget"), dict):
450
+ pass
451
+ elif current_key == "budget":
452
+ result["budget"] = budget
453
+ budget = {}
454
+
455
+ if stripped.startswith("- ") and current_key:
456
+ list_items.append(stripped[2:].strip().strip('"').strip("'"))
457
+ result[current_key] = list_items[:]
458
+ continue
459
+ elif ":" in stripped and not stripped.startswith("-"):
460
+ if current_key and isinstance(result.get(current_key), list):
461
+ list_items = []
462
+ k, _, v = stripped.partition(":")
463
+ current_key = k.strip()
464
+ val = v.strip().strip('"').strip("'")
465
+ if val:
466
+ result[current_key] = val
467
+ else:
468
+ list_items = []
469
+ result[current_key] = list_items
470
+
471
+ if current_key == "budget":
472
+ result["budget"] = budget
473
+
474
+ return result
475
+
476
+
477
+ def parse_state_md(loop_dir: Path) -> dict[str, Any]:
478
+ """Parse STATE.md frontmatter."""
479
+ return parse_md_frontmatter(loop_dir / "STATE.md")
480
+
481
+
482
+ def write_state_md(loop_dir: Path, state: dict[str, Any]) -> None:
483
+ """Write STATE.md with updated frontmatter.
484
+
485
+ List/string values that contain '#' or ':' are quoted so PyYAML / the
486
+ simple parser cannot treat PR numbers like ``#136`` as comments.
487
+ """
488
+ state_md = loop_dir / "STATE.md"
489
+
490
+ def _fmt_scalar(v: Any) -> str:
491
+ if v is None:
492
+ return ""
493
+ if isinstance(v, bool):
494
+ return "true" if v else "false"
495
+ if isinstance(v, (int, float)):
496
+ return str(v)
497
+ # Always JSON-quote strings so PyYAML cannot coerce true/null/dates.
498
+ return json.dumps(str(v), ensure_ascii=False)
499
+
500
+ lines = ["---"]
501
+ for k, v in state.items():
502
+ if isinstance(v, list):
503
+ lines.append(f"{k}:")
504
+ for item in v:
505
+ lines.append(f" - {_fmt_scalar(item)}")
506
+ elif isinstance(v, dict):
507
+ lines.append(f"{k}:")
508
+ for dk, dv in v.items():
509
+ lines.append(f" {dk}: {_fmt_scalar(dv)}")
510
+ else:
511
+ lines.append(f"{k}: {_fmt_scalar(v)}")
512
+ lines.append("---")
513
+ lines.append("")
514
+ state_md.write_text("\n".join(lines), encoding="utf-8")
515
+
516
+
517
+ def list_loops() -> list[Path]:
518
+ """Return user loop instances under workspace/loops/ (#201).
519
+
520
+ Prefers directories with LOOP.md (init output). Also accepts loop.yaml for
521
+ compatibility. Bundled templates are not listed here — use list_templates().
522
+ """
523
+ if not loops_dir().is_dir():
524
+ return []
525
+ return sorted(
526
+ [
527
+ d
528
+ for d in loops_dir().iterdir()
529
+ if d.is_dir() and ((d / "LOOP.md").exists() or (d / "loop.yaml").exists())
530
+ ]
531
+ )
532
+
533
+
534
+ def list_templates() -> list[Path]:
535
+ """Return available loop templates (workspace overrides + bundled) (#200/#202)."""
536
+ results: list[Path] = []
537
+ seen: set[str] = set()
538
+
539
+ ws = workspace_root()
540
+ user_flat = ws / "templates" / "loops"
541
+ if user_flat.is_dir():
542
+ for f in sorted(user_flat.glob("*.yaml")):
543
+ results.append(f)
544
+ seen.add(f.stem)
545
+ for d in sorted(user_flat.iterdir()):
546
+ if d.is_dir() and (d / "loop.yaml").exists() and d.name not in seen:
547
+ results.append(d / "loop.yaml")
548
+ seen.add(d.name)
549
+
550
+ bundled = toolkit_loops_dir()
551
+ if bundled.is_dir():
552
+ for d in sorted(bundled.iterdir()):
553
+ if d.is_dir() and (d / "loop.yaml").exists() and d.name not in seen:
554
+ results.append(d / "loop.yaml")
555
+ seen.add(d.name)
556
+ for f in sorted(bundled.glob("*.yaml")):
557
+ if f.stem not in seen:
558
+ results.append(f)
559
+ seen.add(f.stem)
560
+ return results
561
+
562
+
563
+ def resolve_template(pattern: str) -> Path | None:
564
+ """Resolve a loop template path (#200 / #202).
565
+
566
+ Order:
567
+ 1. ``$WORKSPACE/templates/loops/<pattern>.yaml``
568
+ 2. ``$WORKSPACE/templates/loops/<pattern>/loop.yaml``
569
+ 3. Bundled ``data/loops/<pattern>/loop.yaml``
570
+ 4. Bundled flat ``data/loops/<pattern>.yaml``
571
+ """
572
+ ws = workspace_root()
573
+ candidates = [
574
+ ws / "templates" / "loops" / f"{pattern}.yaml",
575
+ ws / "templates" / "loops" / pattern / "loop.yaml",
576
+ toolkit_loops_dir() / pattern / "loop.yaml",
577
+ toolkit_loops_dir() / f"{pattern}.yaml",
578
+ ]
579
+ for path in candidates:
580
+ if path.is_file():
581
+ return path
582
+ return None
583
+
584
+
585
+ def resolve_loop_dir(name: str) -> Path | None:
586
+ """Resolve a runnable loop directory (#201).
587
+
588
+ Prefer user instance ``$WORKSPACE/loops/<name>/`` (LOOP.md or loop.yaml).
589
+ Fall back to bundled toolkit ``loops/<name>/`` when present.
590
+ """
591
+ user = loops_dir() / name
592
+ if user.is_dir() and ((user / "LOOP.md").exists() or (user / "loop.yaml").exists()):
593
+ return user
594
+ bundled = toolkit_loops_dir() / name
595
+ if bundled.is_dir() and ((bundled / "LOOP.md").exists() or (bundled / "loop.yaml").exists()):
596
+ return bundled
597
+ return None
598
+
599
+
600
+ # ── autonomy / prompt assembly ────────────────────────────────────────────────
601
+
602
+
603
+ def _as_str_list(value: Any) -> list[str]:
604
+ if value is None:
605
+ return []
606
+ if isinstance(value, list):
607
+ return [str(x) for x in value]
608
+ if isinstance(value, str) and value.strip():
609
+ return [value.strip()]
610
+ return []
611
+
612
+
613
+ def _parse_attribution_config(meta: dict[str, Any]) -> dict[str, Any]:
614
+ """Parse LOOP.md / loop.yaml ``attribution`` field.
615
+
616
+ Default: enabled. Accepts ``false``, ``true``, or a mapping with
617
+ ``enabled`` / ``template``.
618
+ """
619
+ raw = meta.get("attribution", True)
620
+ if raw is False or raw is None:
621
+ return {"enabled": False, "template": ""}
622
+ if raw is True:
623
+ return {"enabled": True, "template": ""}
624
+ if isinstance(raw, (int, float)):
625
+ return {"enabled": bool(raw), "template": ""}
626
+ if isinstance(raw, str):
627
+ low = raw.strip().lower()
628
+ if low in {"0", "false", "no", "off", "disabled"}:
629
+ return {"enabled": False, "template": ""}
630
+ if low in {"1", "true", "yes", "on", "enabled"}:
631
+ return {"enabled": True, "template": ""}
632
+ return {"enabled": True, "template": raw}
633
+ if isinstance(raw, dict):
634
+ enabled_raw = raw.get("enabled", True)
635
+ if isinstance(enabled_raw, str):
636
+ enabled = enabled_raw.strip().lower() not in {"0", "false", "no", "off"}
637
+ else:
638
+ enabled = bool(enabled_raw)
639
+ template = str(raw.get("template") or "")
640
+ return {"enabled": enabled, "template": template}
641
+ return {"enabled": True, "template": ""}
642
+
643
+
644
+ def _load_request_body(loop_dir: Path, meta: dict[str, Any], loop_name: str) -> str:
645
+ """Prefer request.md; fall back to LOOP.md goal / generic execute line."""
646
+ request_md = loop_dir / "request.md"
647
+ if request_md.exists():
648
+ body = request_md.read_text(encoding="utf-8").strip()
649
+ if body:
650
+ return body
651
+ if meta.get("request"):
652
+ return str(meta["request"]).strip()
653
+ goal = meta.get("goal")
654
+ if goal:
655
+ return f"Execute the '{loop_name}' loop.\n\nGoal: {goal}"
656
+ return f"Execute the '{loop_name}' loop."
657
+
658
+
659
+ def _autonomy_contract(meta: dict[str, Any], loop_dir: Path) -> str:
660
+ """Hard constraints injected into every runner prompt (not honor-system only)."""
661
+ tier = str(meta.get("tier", "L1")).upper()
662
+ allow = _as_str_list(meta.get("allowlist"))
663
+ deny = _as_str_list(meta.get("deny"))
664
+ verifier = meta.get("verifier") or "(none — treat all mutating actions as escalations)"
665
+ state = parse_state_md(loop_dir)
666
+ pending = _as_str_list(state.get("pending"))
667
+ escalations = _as_str_list(state.get("escalations"))
668
+
669
+ lines = [
670
+ "## Autonomy contract (HARD — violate = human_escalation)",
671
+ f"- Tier: {tier}",
672
+ f"- Allowlist (may do without asking): {', '.join(allow) if allow else '(empty — no mutations)'}",
673
+ f"- Deny (never do): {', '.join(deny) if deny else '(none listed)'}",
674
+ f"- Verifier for mutating actions: {verifier}",
675
+ "",
676
+ "Tier rules:",
677
+ ]
678
+ if tier.startswith("L1") or tier == "1":
679
+ lines.append(
680
+ "- L1 report-only: READ and write plan.md/report.md/STATE.md only. "
681
+ "Do NOT comment, label, assign, merge, close, push, commit, or approve."
682
+ )
683
+ elif tier.startswith("L2") or tier == "2":
684
+ lines.append(
685
+ "- L2 assisted: only allowlisted mutations (typically comment/label/assign). "
686
+ "Never merge/close/push/commit/approve. Unsure → escalate, do not act."
687
+ )
688
+ else:
689
+ lines.append(
690
+ "- L3 unattended: only allowlisted mutations. Deny list is absolute. "
691
+ "Human PRs: comment only — never merge/close. Unsure → escalate."
692
+ )
693
+ lines.append(
694
+ f"- HARD GATE: `gh` is wrapped by `bin/loop-gh-gate`. merge/close require a "
695
+ f"verifier receipt under `{loop_dir.name}/runs/<id>/verifier-receipts/`."
696
+ )
697
+
698
+ lines += [
699
+ "",
700
+ "Hard gate (enforced by PATH shim — not honor-system):",
701
+ "- Mutating `gh` commands are intercepted. Denied actions exit with code 78 "
702
+ "(from the intercepted `gh` process).",
703
+ "- For merge/close: an *independent* verifier must write a receipt JSON "
704
+ "(do NOT self-approve as the maker):",
705
+ " `$OUTPUT_DIR/verifier-receipts/<slug>.json` with keys:",
706
+ " `action`, `repo` (owner/name), `number`, `approved` (true), "
707
+ f'`verifier` ("{verifier}"), `rationale`, `ts` (ISO8601 Z).',
708
+ "- When `LOOP_GATE_RECEIPT_SECRET` is set, receipts must include "
709
+ "`sig` (HMAC-SHA256 hex of the canonical JSON payload).",
710
+ "- Receipts require exact repo + number + verifier match and expire after 1 hour.",
711
+ ]
712
+
713
+ attr = _parse_attribution_config(meta)
714
+ if attr["enabled"]:
715
+ lines += [
716
+ "- Comment/review attribution (default ON): outbound `gh` comment/review "
717
+ "bodies are prefixed with `> 🤖 AI-assisted …` by the hard gate if missing. "
718
+ "Do not invent a different disclaimer; the gate injects the canonical one. "
719
+ "Set `attribution: false` (or `attribution.enabled: false`) in LOOP.md to disable.",
720
+ ]
721
+ else:
722
+ lines += [
723
+ "- Comment/review attribution: DISABLED for this loop (`attribution.enabled: false`).",
724
+ ]
725
+
726
+ lines += [
727
+ "",
728
+ "Before finishing:",
729
+ f"1. Update `{loop_dir / 'STATE.md'}` frontmatter `pending:` and `escalations:` "
730
+ "(replace with current lists; use empty lists if clear). "
731
+ "Quote every list item that contains `#` (PR/issue numbers), e.g. "
732
+ '`- "owner/repo#123 — reason"`.',
733
+ "2. Write plan.md and report.md under the output directory.",
734
+ "3. If exiting with human_escalation, put the reason in escalations and report.md.",
735
+ ]
736
+ if pending:
737
+ lines += ["", "Carried pending from last run:"] + [f"- {p}" for p in pending]
738
+ if escalations:
739
+ lines += ["", "Open escalations:"] + [f"- {e}" for e in escalations]
740
+ return "\n".join(lines)
741
+
742
+
743
+ def _build_runner_prompt(
744
+ loop_dir: Path,
745
+ meta: dict[str, Any],
746
+ loop_name: str,
747
+ run_dir: Path,
748
+ ) -> str:
749
+ request = _load_request_body(loop_dir, meta, loop_name)
750
+ contract = _autonomy_contract(meta, loop_dir)
751
+ return (
752
+ "You are executing an autonomous loop run in an agent-toolkit workspace.\n"
753
+ f"Workspace root: {workspace_root()}\n"
754
+ f"Loop directory: {loop_dir}\n"
755
+ f"Output directory: {run_dir}\n\n"
756
+ f"{contract}\n\n"
757
+ "---\n\n"
758
+ f"{request}\n\n"
759
+ "---\n\n"
760
+ f"Write your final report to {run_dir}/report.md and your plan to "
761
+ f"{run_dir}/plan.md. Work from the workspace root shown above."
762
+ )
763
+
764
+
765
+ # ── built-in runners ──────────────────────────────────────────────────────────
766
+
767
+
768
+ def _gate_script() -> Path:
769
+ return Path(__file__).resolve().parent / "loop-gh-gate"
770
+
771
+
772
+ def _runner_env(run_dir: Path, meta: dict[str, Any]) -> dict[str, str]:
773
+ """Env for runners: PATH-first `gh` shim enforcing allowlist/deny/receipts.
774
+
775
+ Fails closed: if the gate cannot be installed, raises RuntimeError so the
776
+ run aborts rather than dispatching with an ungated `gh`.
777
+ """
778
+ import runpy
779
+
780
+ gate_path = _gate_script()
781
+ if not gate_path.exists():
782
+ raise RuntimeError(f"loop-gh-gate missing at {gate_path} — refusing ungated run")
783
+
784
+ try:
785
+ mod = runpy.run_path(str(gate_path))
786
+ tier = str(meta.get("tier", "L1"))
787
+ allow = _as_str_list(meta.get("allowlist"))
788
+ deny = _as_str_list(meta.get("deny"))
789
+ verifier = str(meta.get("verifier") or "")
790
+ attr = _parse_attribution_config(meta)
791
+ loop_name = str(meta.get("name") or run_dir.parent.parent.name)
792
+ # Prefer keyword args when the gate supports attribution; fall back for
793
+ # older copied loop-gh-gate binaries that only accept the classic kwargs.
794
+ install_kwargs: dict[str, Any] = {
795
+ "tier": tier,
796
+ "allowlist": allow,
797
+ "deny": deny,
798
+ "verifier": verifier,
799
+ "gate_script": gate_path,
800
+ "attribution_enabled": bool(attr["enabled"]),
801
+ "loop_name": loop_name,
802
+ "attribution_template": str(attr.get("template") or ""),
803
+ }
804
+ try:
805
+ env = mod["install_gh_shim"](run_dir, **install_kwargs)
806
+ except TypeError:
807
+ for key in (
808
+ "attribution_enabled",
809
+ "loop_name",
810
+ "attribution_template",
811
+ ):
812
+ install_kwargs.pop(key, None)
813
+ env = mod["install_gh_shim"](run_dir, **install_kwargs)
814
+ attr_label = "on" if attr["enabled"] else "off"
815
+ log(
816
+ f"Hard gate active: gh shim → allow=[{', '.join(allow) or '∅'}] "
817
+ f"deny=[{', '.join(deny) or '∅'}] attribution={attr_label}"
818
+ )
819
+ return env
820
+ except Exception as exc: # noqa: BLE001
821
+ raise RuntimeError(f"failed to install gh gate ({exc}) — refusing ungated run") from exc
822
+
823
+
824
+ def _install_gate_into_environ(run_dir: Path, meta: dict[str, Any]) -> dict[str, str]:
825
+ """Install the gh gate and apply its env to this process (and return a copy)."""
826
+ env = _runner_env(run_dir, meta)
827
+ # Mediate every subsequent child (agent-toolkit runner, etc.).
828
+ for key, value in env.items():
829
+ if key.startswith("LOOP_GATE_") or key == "PATH":
830
+ os.environ[key] = value
831
+ return env
832
+
833
+
834
+ def _try_claude_runner(
835
+ prompt: str,
836
+ run_dir: Path,
837
+ meta: dict[str, Any] | None = None,
838
+ *,
839
+ trace_file: Path | None = None,
840
+ wall_timeout: int | None = None,
841
+ max_tokens: int | None = None,
842
+ ) -> bool:
843
+ """Invoke `claude --print` as a built-in runner for Claude Code users."""
844
+ claude_bin = shutil.which("claude")
845
+ if not claude_bin:
846
+ return False
847
+
848
+ from agent_toolkit.loop.budget import DEFAULT_WALL_SECONDS
849
+
850
+ timeout = wall_timeout if wall_timeout is not None else DEFAULT_WALL_SECONDS
851
+ env = _install_gate_into_environ(run_dir, meta or {})
852
+ try:
853
+ result = _run_with_live_output(
854
+ [claude_bin, "--print", "--allowedTools", "Bash,Read,Write,Edit,Glob,Grep"],
855
+ input_text=prompt,
856
+ cwd=str(workspace_root()),
857
+ env=env,
858
+ trace_file=trace_file or (run_dir / "trace.jsonl"),
859
+ timeout=timeout,
860
+ max_tokens=max_tokens,
861
+ )
862
+ except subprocess.TimeoutExpired:
863
+ warn(f"claude runner hit budget limit (wall={timeout}s or max_tokens)")
864
+ return False
865
+
866
+ if result.returncode == 0:
867
+ report_md = run_dir / "report.md"
868
+ if not report_md.exists() and result.stdout.strip():
869
+ report_md.write_text(result.stdout, encoding="utf-8")
870
+ ok("claude runner completed")
871
+ return True
872
+
873
+ # Claude Code writes auth/error output to stdout, not stderr — show both.
874
+ error_output = (result.stderr + result.stdout).strip()[:400]
875
+ warn(f"claude runner exited {result.returncode}: {error_output or '(no output)'}")
876
+ if result.returncode == 1 and not error_output:
877
+ warn(" Hint: Claude Code may not be authenticated — run: claude /login")
878
+ return False
879
+
880
+
881
+ def _try_opencode_runner(
882
+ prompt: str,
883
+ run_dir: Path,
884
+ meta: dict[str, Any] | None = None,
885
+ *,
886
+ trace_file: Path | None = None,
887
+ wall_timeout: int | None = None,
888
+ max_tokens: int | None = None,
889
+ ) -> bool:
890
+ """Invoke `opencode run` as a headless runner."""
891
+ opencode_bin = shutil.which("opencode")
892
+ if not opencode_bin:
893
+ return False
894
+
895
+ from agent_toolkit.loop.budget import DEFAULT_WALL_SECONDS
896
+
897
+ timeout = wall_timeout if wall_timeout is not None else DEFAULT_WALL_SECONDS
898
+ env = _install_gate_into_environ(run_dir, meta or {})
899
+ try:
900
+ result = _run_with_live_output(
901
+ [opencode_bin, "run", "--print-logs"],
902
+ input_text=prompt,
903
+ cwd=str(workspace_root()),
904
+ env=env,
905
+ trace_file=trace_file or (run_dir / "trace.jsonl"),
906
+ timeout=timeout,
907
+ max_tokens=max_tokens,
908
+ )
909
+ except subprocess.TimeoutExpired:
910
+ warn(f"opencode runner hit budget limit (wall={timeout}s or max_tokens)")
911
+ return False
912
+
913
+ if result.returncode == 0:
914
+ report_md = run_dir / "report.md"
915
+ if not report_md.exists() and result.stdout.strip():
916
+ report_md.write_text(result.stdout, encoding="utf-8")
917
+ ok("opencode runner completed")
918
+ return True
919
+
920
+ error_output = (result.stderr + result.stdout).strip()[:400]
921
+ warn(f"opencode runner exited {result.returncode}: {error_output or '(no output)'}")
922
+ return False
923
+
924
+
925
+ def _resolve_cursor_cli_bin() -> str | None:
926
+ """Locate Cursor Agent CLI (`cursor-agent`, then `agent`, then `cursor`)."""
927
+ for name in ("cursor-agent", "agent", "cursor"):
928
+ found = shutil.which(name)
929
+ if found:
930
+ return found
931
+ return None
932
+
933
+
934
+ def _try_cursor_runner(
935
+ prompt: str,
936
+ run_dir: Path,
937
+ meta: dict[str, Any] | None = None,
938
+ *,
939
+ trace_file: Path | None = None,
940
+ wall_timeout: int | None = None,
941
+ max_tokens: int | None = None,
942
+ ) -> bool:
943
+ """Invoke Cursor Agent CLI headless (`--print`) as a loop runner (#223).
944
+
945
+ Official headless form: ``agent -p --force --trust`` (also shipped as
946
+ ``cursor-agent``). See https://cursor.com/docs/cli/headless
947
+ """
948
+ cursor_bin = _resolve_cursor_cli_bin()
949
+ if not cursor_bin:
950
+ return False
951
+
952
+ from agent_toolkit.loop.budget import DEFAULT_WALL_SECONDS
953
+
954
+ timeout = wall_timeout if wall_timeout is not None else DEFAULT_WALL_SECONDS
955
+ env = _install_gate_into_environ(run_dir, meta or {})
956
+ # Prompt as CLI arg (print mode); --force applies edits; --trust skips
957
+ # workspace trust prompts in headless environments.
958
+ cmd = [
959
+ cursor_bin,
960
+ "--print",
961
+ "--force",
962
+ "--trust",
963
+ "--output-format",
964
+ "text",
965
+ prompt,
966
+ ]
967
+ try:
968
+ result = _run_with_live_output(
969
+ cmd,
970
+ input_text="",
971
+ cwd=str(workspace_root()),
972
+ env=env,
973
+ trace_file=trace_file or (run_dir / "trace.jsonl"),
974
+ timeout=timeout,
975
+ max_tokens=max_tokens,
976
+ )
977
+ except subprocess.TimeoutExpired:
978
+ warn(f"cursor runner hit budget limit (wall={timeout}s or max_tokens)")
979
+ return False
980
+
981
+ if result.returncode == 0:
982
+ report_md = run_dir / "report.md"
983
+ if not report_md.exists() and result.stdout.strip():
984
+ report_md.write_text(result.stdout, encoding="utf-8")
985
+ ok("cursor runner completed")
986
+ return True
987
+
988
+ error_output = (result.stderr + result.stdout).strip()[:400]
989
+ warn(f"cursor runner exited {result.returncode}: {error_output or '(no output)'}")
990
+ if result.returncode != 0 and not error_output:
991
+ warn(" Hint: Cursor Agent CLI may not be authenticated — run: agent login")
992
+ return False
993
+
994
+
995
+ def _resolve_copilot_cli_bin() -> str | None:
996
+ """Locate GitHub Copilot CLI (`copilot`).
997
+
998
+ Prefers the standalone ``copilot`` binary (programmatic ``-p`` mode).
999
+ Does not use legacy ``gh copilot suggest``, which is not a free-form agent.
1000
+ """
1001
+ return shutil.which("copilot")
1002
+
1003
+
1004
+ def _try_copilot_runner(
1005
+ prompt: str,
1006
+ run_dir: Path,
1007
+ meta: dict[str, Any] | None = None,
1008
+ *,
1009
+ trace_file: Path | None = None,
1010
+ wall_timeout: int | None = None,
1011
+ max_tokens: int | None = None,
1012
+ ) -> bool:
1013
+ """Invoke GitHub Copilot CLI headless (``copilot -p``) as a loop runner (#224).
1014
+
1015
+ See https://docs.github.com/en/copilot/how-tos/copilot-cli/automate-copilot-cli/run-cli-programmatically
1016
+ """
1017
+ copilot_bin = _resolve_copilot_cli_bin()
1018
+ if not copilot_bin:
1019
+ return False
1020
+
1021
+ from agent_toolkit.loop.budget import DEFAULT_WALL_SECONDS
1022
+
1023
+ timeout = wall_timeout if wall_timeout is not None else DEFAULT_WALL_SECONDS
1024
+ env = _install_gate_into_environ(run_dir, meta or {})
1025
+ # -p: non-interactive prompt; -s: silent (response only); --no-ask-user /
1026
+ # --allow-all: unattended tool use (gh mutations still go through loop-gh-gate).
1027
+ cmd = [
1028
+ copilot_bin,
1029
+ "-p",
1030
+ prompt,
1031
+ "-s",
1032
+ "--no-ask-user",
1033
+ "--allow-all",
1034
+ ]
1035
+ try:
1036
+ result = _run_with_live_output(
1037
+ cmd,
1038
+ input_text="",
1039
+ cwd=str(workspace_root()),
1040
+ env=env,
1041
+ trace_file=trace_file or (run_dir / "trace.jsonl"),
1042
+ timeout=timeout,
1043
+ max_tokens=max_tokens,
1044
+ )
1045
+ except subprocess.TimeoutExpired:
1046
+ warn(f"copilot runner hit budget limit (wall={timeout}s or max_tokens)")
1047
+ return False
1048
+
1049
+ if result.returncode == 0:
1050
+ report_md = run_dir / "report.md"
1051
+ if not report_md.exists() and result.stdout.strip():
1052
+ report_md.write_text(result.stdout, encoding="utf-8")
1053
+ ok("copilot runner completed")
1054
+ return True
1055
+
1056
+ error_output = (result.stderr + result.stdout).strip()[:400]
1057
+ warn(f"copilot runner exited {result.returncode}: {error_output or '(no output)'}")
1058
+ if result.returncode != 0 and not error_output:
1059
+ warn(
1060
+ " Hint: Copilot CLI may not be authenticated — set COPILOT_GITHUB_TOKEN or run: copilot"
1061
+ )
1062
+ return False
1063
+
1064
+
1065
+ def _try_codex_runner(
1066
+ prompt: str,
1067
+ run_dir: Path,
1068
+ meta: dict[str, Any] | None = None,
1069
+ *,
1070
+ trace_file: Path | None = None,
1071
+ wall_timeout: int | None = None,
1072
+ max_tokens: int | None = None,
1073
+ ) -> bool:
1074
+ """Invoke OpenAI Codex CLI headless (``codex exec``) as a loop runner (#225).
1075
+
1076
+ See https://developers.openai.com/codex/noninteractive
1077
+ """
1078
+ codex_bin = shutil.which("codex")
1079
+ if not codex_bin:
1080
+ return False
1081
+
1082
+ from agent_toolkit.loop.budget import DEFAULT_WALL_SECONDS
1083
+
1084
+ timeout = wall_timeout if wall_timeout is not None else DEFAULT_WALL_SECONDS
1085
+ env = _install_gate_into_environ(run_dir, meta or {})
1086
+ report_md = run_dir / "report.md"
1087
+ # ``codex exec -`` reads the full prompt from stdin; workspace-write + never
1088
+ # ask keeps loops unattended; ``-o`` captures the final agent message.
1089
+ cmd = [
1090
+ codex_bin,
1091
+ "exec",
1092
+ "--ask-for-approval",
1093
+ "never",
1094
+ "--sandbox",
1095
+ "workspace-write",
1096
+ "--output-last-message",
1097
+ str(report_md),
1098
+ "-",
1099
+ ]
1100
+ try:
1101
+ result = _run_with_live_output(
1102
+ cmd,
1103
+ input_text=prompt,
1104
+ cwd=str(workspace_root()),
1105
+ env=env,
1106
+ trace_file=trace_file or (run_dir / "trace.jsonl"),
1107
+ timeout=timeout,
1108
+ max_tokens=max_tokens,
1109
+ )
1110
+ except subprocess.TimeoutExpired:
1111
+ warn(f"codex runner hit budget limit (wall={timeout}s or max_tokens)")
1112
+ return False
1113
+
1114
+ if result.returncode == 0:
1115
+ if not report_md.exists() and result.stdout.strip():
1116
+ report_md.write_text(result.stdout, encoding="utf-8")
1117
+ ok("codex runner completed")
1118
+ return True
1119
+
1120
+ error_output = (result.stderr + result.stdout).strip()[:400]
1121
+ warn(f"codex runner exited {result.returncode}: {error_output or '(no output)'}")
1122
+ if result.returncode != 0 and not error_output:
1123
+ warn(" Hint: Codex CLI may not be authenticated — set OPENAI_API_KEY / CODEX_API_KEY")
1124
+ return False
1125
+
1126
+
1127
+ def _try_muse_runner(
1128
+ prompt: str,
1129
+ run_dir: Path,
1130
+ meta: dict[str, Any] | None = None,
1131
+ *,
1132
+ trace_file: Path | None = None,
1133
+ wall_timeout: int | None = None,
1134
+ max_tokens: int | None = None,
1135
+ ) -> bool:
1136
+ """Invoke Muse CLI headless (``muse exec``) as a loop runner.
1137
+
1138
+ See https://developer.meta.com/ai/products/muse-code/
1139
+ Muse uses Agent Skills spec: ``~/.config/muse/skills`` (user) and ``.agents/skills``.
1140
+ """
1141
+ muse_bin = shutil.which("muse")
1142
+ if not muse_bin:
1143
+ return False
1144
+
1145
+ from agent_toolkit.loop.budget import DEFAULT_WALL_SECONDS
1146
+
1147
+ timeout = wall_timeout if wall_timeout is not None else DEFAULT_WALL_SECONDS
1148
+ env = _install_gate_into_environ(run_dir, meta or {})
1149
+
1150
+ # Write prompt to file to avoid shell quoting limits (muse exec supports --prompt-file)
1151
+ prompt_file = run_dir / "prompt.md"
1152
+ try:
1153
+ prompt_file.write_text(prompt, encoding="utf-8")
1154
+ except OSError:
1155
+ # Fallback: pass prompt directly if file write fails
1156
+ prompt_file = None
1157
+
1158
+ if prompt_file is not None and prompt_file.exists():
1159
+ cmd = [muse_bin, "exec", "--yolo", "--prompt-file", str(prompt_file)]
1160
+ else:
1161
+ cmd = [muse_bin, "exec", "--yolo", prompt]
1162
+
1163
+ try:
1164
+ result = _run_with_live_output(
1165
+ cmd,
1166
+ input_text="",
1167
+ cwd=str(workspace_root()),
1168
+ env=env,
1169
+ trace_file=trace_file or (run_dir / "trace.jsonl"),
1170
+ timeout=timeout,
1171
+ max_tokens=max_tokens,
1172
+ )
1173
+ except subprocess.TimeoutExpired:
1174
+ warn(f"muse runner hit budget limit (wall={timeout}s or max_tokens)")
1175
+ return False
1176
+
1177
+ if result.returncode == 0:
1178
+ report_md = run_dir / "report.md"
1179
+ if not report_md.exists() and result.stdout.strip():
1180
+ report_md.write_text(result.stdout, encoding="utf-8")
1181
+ ok("muse runner completed")
1182
+ return True
1183
+
1184
+ error_output = (result.stderr + result.stdout).strip()[:400]
1185
+ warn(f"muse runner exited {result.returncode}: {error_output or '(no output)'}")
1186
+ if result.returncode != 0 and not error_output:
1187
+ warn(" Hint: Muse CLI may not be authenticated — run: muse auth login or set MUSE_API_KEY")
1188
+ return False
1189
+
1190
+
1191
+ def _queue_via_devcompanion(
1192
+ request: str,
1193
+ run_dir: Path,
1194
+ loop_name: str,
1195
+ rid: str,
1196
+ meta: dict[str, Any] | None = None,
1197
+ *,
1198
+ wall_timeout: int | None = None,
1199
+ ) -> bool:
1200
+ """Queue the loop run as a devcompanion job for async processing.
1201
+
1202
+ The job will be picked up by the systemd worker (dev-companion-worker)
1203
+ or via `devcompanion run-once`. Returns True if queued successfully.
1204
+
1205
+ This avoids the subprocess-in-subprocess problem when running `loop run`
1206
+ from within an interactive LLM session (opencode, claude, etc.).
1207
+ """
1208
+ # Install gate into this process and persist gate metadata for the worker.
1209
+ gate_meta: dict[str, Any] = {}
1210
+ if meta is not None:
1211
+ env = _install_gate_into_environ(run_dir, meta)
1212
+ gate_meta = {
1213
+ "tier": str(meta.get("tier", "L1")),
1214
+ "allowlist": _as_str_list(meta.get("allowlist")),
1215
+ "deny": _as_str_list(meta.get("deny")),
1216
+ "verifier": str(meta.get("verifier") or ""),
1217
+ "run_dir": str(run_dir),
1218
+ "real_gh": env.get("LOOP_GATE_REAL_GH", ""),
1219
+ }
1220
+
1221
+ job_id = f"loop-{loop_name}-{rid}"
1222
+ job = {
1223
+ "id": job_id,
1224
+ "created_at": utc_now(),
1225
+ "request": request,
1226
+ "repo_path": str(workspace_root()),
1227
+ "loop_run_dir": str(run_dir),
1228
+ "llm": True,
1229
+ "limits": {
1230
+ "timeout_sec": wall_timeout or 1800,
1231
+ "max_steps": 25,
1232
+ },
1233
+ "actions_allowed": ["plan_only"],
1234
+ "loop_gate": gate_meta,
1235
+ }
1236
+
1237
+ job_file = _QUEUE_PENDING / f"{job_id}.job"
1238
+ try:
1239
+ job_file.parent.mkdir(parents=True, exist_ok=True)
1240
+ job_file.write_text(json.dumps(job, indent=2) + "\n", encoding="utf-8")
1241
+ log(f"Queued as devcompanion job: {job_id}")
1242
+ log(f" Job file : {job_file}")
1243
+ log(f" Run dir : {run_dir}")
1244
+ log(" Next step : the worker (systemd timer every 5m) will pick it up")
1245
+ log(" Or run : devcompanion run-once to process immediately")
1246
+ log(" Check : devcompanion status")
1247
+ return True
1248
+ except OSError as e:
1249
+ warn(f"Could not queue devcompanion job: {e}")
1250
+ return False
1251
+
1252
+
1253
+ # ── commands ──────────────────────────────────────────────────────────────────
1254
+
1255
+
1256
+ def cmd_init(args: list[str]) -> int:
1257
+ """Scaffold a new loop from a starter template (#200)."""
1258
+ if not args or args[0] in ("-h", "--help"):
1259
+ err("Usage: agent-toolkit loop init <pattern> [--name <custom-name>]")
1260
+ print("\nAvailable patterns:")
1261
+ for t in list_templates():
1262
+ label = t.parent.name if t.name == "loop.yaml" else t.stem
1263
+ print(f" {label}")
1264
+ return 0 if args and args[0] in ("-h", "--help") else 1
1265
+
1266
+ pattern = args[0]
1267
+ loop_name = pattern
1268
+ i = 1
1269
+ while i < len(args):
1270
+ if args[i] == "--name" and i + 1 < len(args):
1271
+ loop_name = args[i + 1]
1272
+ i += 2
1273
+ else:
1274
+ i += 1
1275
+
1276
+ template_file = resolve_template(pattern)
1277
+ if template_file is None:
1278
+ err(f"Template '{pattern}' not found.")
1279
+ print("\nAvailable patterns:")
1280
+ for t in list_templates():
1281
+ label = t.parent.name if t.name == "loop.yaml" else t.stem
1282
+ print(f" {label}")
1283
+ return 1
1284
+
1285
+ text = template_file.read_text(encoding="utf-8")
1286
+ name_match = re.search(r"^name:\s+(\S+)", text, re.MULTILINE)
1287
+ if loop_name == pattern and name_match:
1288
+ loop_name = name_match.group(1)
1289
+
1290
+ loop_dir = loops_dir() / loop_name
1291
+ if loop_dir.exists():
1292
+ warn(f"Loop '{loop_name}' already exists at {loop_dir}")
1293
+ return 1
1294
+
1295
+ loop_dir.mkdir(parents=True)
1296
+ (loop_dir / "runs").mkdir()
1297
+
1298
+ # Body of frontmatter: drop full-line comments from template YAML
1299
+ fm_lines = [
1300
+ line for line in text.splitlines() if line.strip() and not line.lstrip().startswith("#")
1301
+ ]
1302
+ # Ensure name matches instance directory
1303
+ rewritten: list[str] = []
1304
+ saw_name = False
1305
+ for line in fm_lines:
1306
+ if re.match(r"^name:\s+", line):
1307
+ rewritten.append(f"name: {loop_name}")
1308
+ saw_name = True
1309
+ else:
1310
+ rewritten.append(line)
1311
+ if not saw_name:
1312
+ rewritten.insert(0, f"name: {loop_name}")
1313
+
1314
+ (loop_dir / "LOOP.md").write_text(
1315
+ "---\n" + "\n".join(rewritten) + "\n---\n\n"
1316
+ f"# {loop_name.replace('-', ' ').title()} Loop\n\n"
1317
+ "<!-- Describe the goal, constraints, and escalation rules here. -->\n",
1318
+ encoding="utf-8",
1319
+ )
1320
+
1321
+ write_state_md(
1322
+ loop_dir,
1323
+ {
1324
+ "last_run": "never",
1325
+ "last_run_status": "not_run",
1326
+ "last_run_id": "",
1327
+ "runs_today": 0,
1328
+ "pending": [],
1329
+ "escalations": [],
1330
+ },
1331
+ )
1332
+
1333
+ rel = loop_dir.relative_to(workspace_root())
1334
+ ok(f"Initialized loop '{loop_name}' at {rel}")
1335
+ print(f"\n Edit {rel}/LOOP.md to customize.")
1336
+ print(f" Then run: agent-toolkit loop run {loop_name}")
1337
+ return 0
1338
+
1339
+
1340
+ def _normalize_runner_name(raw: str | None) -> str:
1341
+ """Return a canonical runner name or raise ValueError."""
1342
+ if raw is None or not str(raw).strip():
1343
+ return RUNNER_AUTO
1344
+ name = str(raw).strip().lower().replace("_", "-")
1345
+ name = RUNNER_ALIASES.get(name, name)
1346
+ if name == RUNNER_AUTO:
1347
+ return RUNNER_AUTO
1348
+ if name not in RUNNER_NAMES:
1349
+ known = ", ".join((RUNNER_AUTO,) + RUNNER_NAMES)
1350
+ raise ValueError(f"Unknown runner '{raw}'. Choose one of: {known}")
1351
+ return name
1352
+
1353
+
1354
+ def _parse_run_args(args: list[str]) -> tuple[str, bool, bool, Path | None, str]:
1355
+ """Parse loop run argv into (loop_name, force, quiet, pack_path, runner)."""
1356
+ force = "--force" in args
1357
+ quiet = "--quiet" in args
1358
+ pack_path: Path | None = None
1359
+ runner_flag: str | None = None
1360
+ positional: list[str] = []
1361
+ i = 0
1362
+ while i < len(args):
1363
+ if args[i] == "--pack" and i + 1 < len(args):
1364
+ pack_path = Path(args[i + 1]).expanduser()
1365
+ i += 2
1366
+ continue
1367
+ if args[i] == "--runner" and i + 1 < len(args):
1368
+ runner_flag = args[i + 1]
1369
+ i += 2
1370
+ continue
1371
+ if args[i].startswith("--runner="):
1372
+ runner_flag = args[i].split("=", 1)[1]
1373
+ i += 1
1374
+ continue
1375
+ if args[i].startswith("-"):
1376
+ i += 1
1377
+ continue
1378
+ positional.append(args[i])
1379
+ i += 1
1380
+
1381
+ env_runner = os.environ.get("AGENT_TOOLKIT_LOOP_RUNNER", "").strip() or None
1382
+ runner = _normalize_runner_name(runner_flag if runner_flag is not None else env_runner)
1383
+ return positional[0] if positional else "", force, quiet, pack_path, runner
1384
+
1385
+
1386
+ def _run_harness_runner_with_timeout(
1387
+ runner_mod: Any,
1388
+ job_file: Path,
1389
+ run_dir: Path,
1390
+ wall_timeout: int,
1391
+ ) -> None:
1392
+ """Invoke harness runner with a wall-clock timeout."""
1393
+ import threading
1394
+
1395
+ exc_holder: list[BaseException] = []
1396
+
1397
+ def _target() -> None:
1398
+ try:
1399
+ runner_mod.main(["--job", str(job_file), "--out", str(run_dir)])
1400
+ except BaseException as exc: # noqa: BLE001
1401
+ exc_holder.append(exc)
1402
+
1403
+ thread = threading.Thread(target=_target, daemon=True)
1404
+ thread.start()
1405
+ thread.join(timeout=wall_timeout)
1406
+ if thread.is_alive():
1407
+ raise subprocess.TimeoutExpired(["harness-runner", str(job_file)], wall_timeout)
1408
+ if exc_holder:
1409
+ raise exc_holder[0]
1410
+
1411
+
1412
+ def _load_harness_runner_mod() -> Any | None:
1413
+ runner_dir = Path(
1414
+ os.environ.get("HARNESS_RUNNER_DIR", "")
1415
+ or Path.home() / ".local" / "share" / "agent-toolkit" / "runner"
1416
+ )
1417
+ if not runner_dir.is_dir():
1418
+ return None
1419
+ if str(runner_dir) not in sys.path:
1420
+ sys.path.insert(0, str(runner_dir))
1421
+ try:
1422
+ import dots_ai_devcompanion_runner as r # type: ignore
1423
+
1424
+ return r
1425
+ except ImportError:
1426
+ return None
1427
+
1428
+
1429
+ def _try_harness_runner(
1430
+ prompt: str,
1431
+ run_dir: Path,
1432
+ rid: str,
1433
+ meta: dict[str, Any],
1434
+ *,
1435
+ wall_timeout: int,
1436
+ ) -> tuple[bool, bool]:
1437
+ """Run harness/devcompanion-runner. Returns (handled, budget_exhausted)."""
1438
+ runner_mod = _load_harness_runner_mod()
1439
+ if runner_mod is None:
1440
+ return False, False
1441
+ _install_gate_into_environ(run_dir, meta)
1442
+ try:
1443
+ job_file = run_dir / "job.json"
1444
+ job_file.write_text(
1445
+ json.dumps(
1446
+ {
1447
+ "id": rid,
1448
+ "created_at": utc_now(),
1449
+ "request": prompt,
1450
+ "loop_gate": {
1451
+ "tier": str(meta.get("tier", "L1")),
1452
+ "allowlist": _as_str_list(meta.get("allowlist")),
1453
+ "deny": _as_str_list(meta.get("deny")),
1454
+ "verifier": str(meta.get("verifier") or ""),
1455
+ "run_dir": str(run_dir),
1456
+ },
1457
+ "limits": {"timeout_sec": wall_timeout},
1458
+ }
1459
+ ),
1460
+ encoding="utf-8",
1461
+ )
1462
+ _run_harness_runner_with_timeout(runner_mod, job_file, run_dir, wall_timeout)
1463
+ return True, False
1464
+ except subprocess.TimeoutExpired:
1465
+ warn(f"Run exceeded max_wall_seconds ({wall_timeout}s)")
1466
+ return True, True
1467
+ except Exception as e:
1468
+ err(f"Runner error: {e}")
1469
+ return True, False
1470
+
1471
+
1472
+ def _write_skeleton_plan(
1473
+ plan_md: Path,
1474
+ *,
1475
+ loop_name: str,
1476
+ rid: str,
1477
+ tier: str,
1478
+ meta: dict[str, Any],
1479
+ reason: str,
1480
+ ) -> None:
1481
+ plan_md.write_text(
1482
+ f"# Loop Run: {loop_name}\n\n"
1483
+ f"**Run ID**: {rid} \n"
1484
+ f"**Tier**: {tier} \n"
1485
+ f"**Started**: {utc_now()} \n\n"
1486
+ "## Goal\n\n"
1487
+ f"{meta.get('goal', '(no goal defined in LOOP.md)')}\n\n"
1488
+ "## Status\n\n"
1489
+ f"⚠ {reason}\n\n"
1490
+ "Options:\n"
1491
+ " 1. `agent-toolkit loop run <loop> --runner claude` (Claude Code CLI in PATH)\n"
1492
+ " 2. `--runner opencode` / `cursor` / `copilot` / `codex` / `muse`\n"
1493
+ " 3. `--runner harness` with `HARNESS_RUNNER_DIR` set\n"
1494
+ " 4. `--runner queue` for async devcompanion processing\n"
1495
+ "See: `agent-toolkit loop help`\n",
1496
+ encoding="utf-8",
1497
+ )
1498
+
1499
+
1500
+ def _dispatch_loop_runner(
1501
+ runner: str,
1502
+ *,
1503
+ prompt: str,
1504
+ run_dir: Path,
1505
+ rid: str,
1506
+ loop_name: str,
1507
+ meta: dict[str, Any],
1508
+ trace_file: Path,
1509
+ wall_timeout: int,
1510
+ token_limit: int | None,
1511
+ plan_md: Path,
1512
+ tier: str,
1513
+ ) -> tuple[bool, bool]:
1514
+ """Dispatch to the selected runner.
1515
+
1516
+ Returns ``(queued, budget_exhausted)``.
1517
+ Raises ``RuntimeError`` for gate failures (caller maps to exit 2).
1518
+ Raises ``ValueError`` when an explicit runner is unavailable.
1519
+ """
1520
+ kwargs = dict(
1521
+ trace_file=trace_file,
1522
+ wall_timeout=wall_timeout,
1523
+ max_tokens=token_limit,
1524
+ )
1525
+
1526
+ def _one(name: str) -> bool | None:
1527
+ """Return True if handled, False if unavailable, None if failed after attempt."""
1528
+ if name == "harness":
1529
+ handled, _budget = _try_harness_runner(
1530
+ prompt, run_dir, rid, meta, wall_timeout=wall_timeout
1531
+ )
1532
+ return handled
1533
+ if name == "claude":
1534
+ if not shutil.which("claude"):
1535
+ return False
1536
+ return True if _try_claude_runner(prompt, run_dir, meta, **kwargs) else None
1537
+ if name == "opencode":
1538
+ if not shutil.which("opencode"):
1539
+ return False
1540
+ return True if _try_opencode_runner(prompt, run_dir, meta, **kwargs) else None
1541
+ if name == "cursor":
1542
+ if _resolve_cursor_cli_bin() is None:
1543
+ return False
1544
+ return True if _try_cursor_runner(prompt, run_dir, meta, **kwargs) else None
1545
+ if name == "copilot":
1546
+ if _resolve_copilot_cli_bin() is None:
1547
+ return False
1548
+ return True if _try_copilot_runner(prompt, run_dir, meta, **kwargs) else None
1549
+ if name == "codex":
1550
+ if not shutil.which("codex"):
1551
+ return False
1552
+ return True if _try_codex_runner(prompt, run_dir, meta, **kwargs) else None
1553
+ if name == "muse":
1554
+ if not shutil.which("muse"):
1555
+ return False
1556
+ return True if _try_muse_runner(prompt, run_dir, meta, **kwargs) else None
1557
+ if name == "queue":
1558
+ return (
1559
+ True
1560
+ if _queue_via_devcompanion(
1561
+ prompt, run_dir, loop_name, rid, meta, wall_timeout=wall_timeout
1562
+ )
1563
+ else False
1564
+ )
1565
+ if name == "skeleton":
1566
+ _write_skeleton_plan(
1567
+ plan_md,
1568
+ loop_name=loop_name,
1569
+ rid=rid,
1570
+ tier=tier,
1571
+ meta=meta,
1572
+ reason="Skeleton runner requested (--runner skeleton).",
1573
+ )
1574
+ return True
1575
+ return False
1576
+
1577
+ queued = False
1578
+ budget_exhausted = False
1579
+
1580
+ if runner == RUNNER_AUTO:
1581
+ # Preserve prior semantics: if harness package is present, use it and
1582
+ # do not fall through to CLI runners on failure.
1583
+ if _load_harness_runner_mod() is not None:
1584
+ _handled, budget_exhausted = _try_harness_runner(
1585
+ prompt, run_dir, rid, meta, wall_timeout=wall_timeout
1586
+ )
1587
+ return False, budget_exhausted
1588
+ for name in ("claude", "opencode", "cursor", "copilot", "codex", "muse", "queue"):
1589
+ result = _one(name)
1590
+ if result is True:
1591
+ if name == "queue":
1592
+ queued = True
1593
+ log(
1594
+ "Loop dispatched to devcompanion queue — "
1595
+ "worker will process asynchronously."
1596
+ )
1597
+ return queued, budget_exhausted
1598
+ # False = missing; None = attempted and failed → try next
1599
+ continue
1600
+ warn("No runner found — writing skeleton plan.md")
1601
+ if not _PROGRESS_QUIET:
1602
+ log("step: prepare skeleton plan")
1603
+ _write_skeleton_plan(
1604
+ plan_md,
1605
+ loop_name=loop_name,
1606
+ rid=rid,
1607
+ tier=tier,
1608
+ meta=meta,
1609
+ reason="No runner found.",
1610
+ )
1611
+ if not _PROGRESS_QUIET:
1612
+ log("step: skeleton plan written (no LLM runner available)")
1613
+ trace_file.write_text(
1614
+ trace_file.read_text(encoding="utf-8")
1615
+ + json.dumps(
1616
+ {
1617
+ "ts": utc_now(),
1618
+ "kind": "progress",
1619
+ "label": "skeleton",
1620
+ "message": "plan.md written",
1621
+ }
1622
+ )
1623
+ + "\n",
1624
+ encoding="utf-8",
1625
+ )
1626
+ return False, False
1627
+
1628
+ # Explicit runner — do not silently fall through.
1629
+ log(f"Using runner: {runner}")
1630
+ if runner == "harness":
1631
+ if _load_harness_runner_mod() is None:
1632
+ raise ValueError(
1633
+ "harness runner unavailable — set HARNESS_RUNNER_DIR to the "
1634
+ "dots-ai-devcompanion runner package"
1635
+ )
1636
+ _handled, budget_exhausted = _try_harness_runner(
1637
+ prompt, run_dir, rid, meta, wall_timeout=wall_timeout
1638
+ )
1639
+ return False, budget_exhausted
1640
+
1641
+ result = _one(runner)
1642
+ if result is False:
1643
+ hints = {
1644
+ "claude": "install Claude Code CLI (`claude` on PATH)",
1645
+ "opencode": "install OpenCode (`opencode` on PATH)",
1646
+ "cursor": "install Cursor Agent CLI (`cursor-agent` / `agent` on PATH); set CURSOR_API_KEY",
1647
+ "copilot": "install GitHub Copilot CLI (`copilot` on PATH); set COPILOT_GITHUB_TOKEN",
1648
+ "codex": "install Codex CLI (`codex` on PATH); set OPENAI_API_KEY or CODEX_API_KEY",
1649
+ "muse": "install Muse CLI (`muse` on PATH); run: muse auth login",
1650
+ "queue": "ensure workspace queue dirs are writable (HARNESS_DC_HOME / workspace)",
1651
+ }
1652
+ raise ValueError(
1653
+ f"runner '{runner}' is not available — {hints.get(runner, 'check installation')}"
1654
+ )
1655
+ if result is None:
1656
+ raise ValueError(f"runner '{runner}' started but exited unsuccessfully")
1657
+ if runner == "queue":
1658
+ queued = True
1659
+ log("Loop dispatched to devcompanion queue — worker will process asynchronously.")
1660
+ return queued, budget_exhausted
1661
+
1662
+
1663
+ def cmd_run(args: list[str]) -> int:
1664
+ """Execute one loop run.
1665
+
1666
+ Usage: loop run <loop-name> [--force] [--quiet] [--pack PATH] [--runner NAME]
1667
+ """
1668
+ global _PROGRESS_QUIET
1669
+
1670
+ usage = (
1671
+ "Usage: loop run <loop-name> [--force] [--quiet] [--pack PATH] [--runner NAME]\n"
1672
+ " --runner auto|harness|claude|opencode|cursor|copilot|codex|muse|queue|skeleton\n"
1673
+ " (default: auto, or $AGENT_TOOLKIT_LOOP_RUNNER)\n"
1674
+ "See: agent-toolkit loop help"
1675
+ )
1676
+ if not args:
1677
+ err(usage)
1678
+ return 1
1679
+
1680
+ try:
1681
+ loop_name, force, quiet, pack_path, runner = _parse_run_args(args)
1682
+ except ValueError as exc:
1683
+ err(str(exc))
1684
+ return 1
1685
+ _PROGRESS_QUIET = quiet
1686
+ if not loop_name:
1687
+ err(usage)
1688
+ return 1
1689
+
1690
+ loop_dir = resolve_loop_dir(loop_name)
1691
+ if loop_dir is None:
1692
+ err(f"Loop '{loop_name}' not found. Run: agent-toolkit loop init {loop_name}")
1693
+ return 1
1694
+
1695
+ meta = parse_loop_md(loop_dir)
1696
+
1697
+ if pack_path is not None:
1698
+ from agent_toolkit.loop.pack import (
1699
+ apply_loop_pack_overrides,
1700
+ load_pack,
1701
+ resolve_pack_path,
1702
+ )
1703
+
1704
+ resolved = resolve_pack_path(pack_path, workspace_root())
1705
+ if resolved is None:
1706
+ err(f"Pack not found: {pack_path}")
1707
+ return 1
1708
+ pack_data = load_pack(resolved)
1709
+ meta = apply_loop_pack_overrides(meta, pack_data, loop_name)
1710
+ if meta.get("enabled") is False:
1711
+ warn(f"Loop '{loop_name}' disabled in pack {resolved.name}. Skipping.")
1712
+ return 0
1713
+ log(f"Pack overrides loaded from {resolved}")
1714
+
1715
+ from agent_toolkit.loop.budget import (
1716
+ max_tokens_limit,
1717
+ soft_token_precheck,
1718
+ token_budget_exceeded,
1719
+ tokens_from_trace,
1720
+ wall_timeout_seconds,
1721
+ )
1722
+
1723
+ tier = meta.get("tier", "L1")
1724
+ budget = meta.get("budget", {})
1725
+ if not isinstance(budget, dict):
1726
+ budget = {}
1727
+ max_runs = int(budget.get("max_runs_per_day", 10))
1728
+ wall_timeout = wall_timeout_seconds(budget)
1729
+ token_limit = max_tokens_limit(budget)
1730
+
1731
+ # Load current state
1732
+ state_md = loop_dir / "STATE.md"
1733
+ state = {
1734
+ "last_run": "never",
1735
+ "last_run_status": "not_run",
1736
+ "last_run_id": "",
1737
+ "runs_today": 0,
1738
+ "pending": [],
1739
+ "escalations": [],
1740
+ }
1741
+ if state_md.exists():
1742
+ loaded = parse_state_md(loop_dir)
1743
+ state.update(loaded)
1744
+
1745
+ # Budget gate: check runs_today
1746
+ runs_today = int(state.get("runs_today", 0) or 0)
1747
+ last_run_ts = state.get("last_run", "never")
1748
+ if last_run_ts not in (None, "never", ""):
1749
+ try:
1750
+ # PyYAML may parse ISO timestamps as datetime objects
1751
+ if hasattr(last_run_ts, "isoformat"):
1752
+ last_dt = (
1753
+ last_run_ts if last_run_ts.tzinfo else last_run_ts.replace(tzinfo=timezone.utc)
1754
+ )
1755
+ else:
1756
+ last_dt = datetime.fromisoformat(str(last_run_ts).replace("Z", "+00:00"))
1757
+ today = datetime.now(timezone.utc).date()
1758
+ if last_dt.date() != today:
1759
+ runs_today = 0 # Reset on new day
1760
+ except (ValueError, TypeError, AttributeError):
1761
+ runs_today = 0
1762
+
1763
+ if runs_today >= max_runs and not force:
1764
+ warn(f"Budget: max_runs_per_day ({max_runs}) reached for today. Skipping.")
1765
+ warn(" Re-run with: agent-toolkit loop run <loop> --force")
1766
+ return 0
1767
+ if force and runs_today >= max_runs:
1768
+ warn(f"Budget gate bypassed via --force (runs_today={runs_today}, max={max_runs})")
1769
+
1770
+ precheck_msg = soft_token_precheck(state, budget)
1771
+ if precheck_msg:
1772
+ warn(f"Budget: {precheck_msg}")
1773
+
1774
+ log(
1775
+ f"Budget: max_wall_seconds={wall_timeout}, "
1776
+ f"max_tokens={token_limit if token_limit is not None else 'unset'}"
1777
+ )
1778
+
1779
+ # Create run directory
1780
+ rid = run_id()
1781
+ run_dir = loop_dir / "runs" / rid
1782
+ run_dir.mkdir(parents=True)
1783
+
1784
+ log(f"Starting run {rid} for '{loop_name}' (tier={tier})")
1785
+ log(f"Run artifacts: {run_dir.relative_to(workspace_root())}")
1786
+ allow = _as_str_list(meta.get("allowlist"))
1787
+ deny = _as_str_list(meta.get("deny"))
1788
+ log(
1789
+ f"Autonomy: allow=[{', '.join(allow) or '∅'}] "
1790
+ f"deny=[{', '.join(deny) or '∅'}] "
1791
+ f"verifier={meta.get('verifier') or 'none'}"
1792
+ )
1793
+
1794
+ # Write initial trace entry with AGENTS.md spec hash
1795
+ agents_md = workspace_root() / "AGENTS.md"
1796
+ agents_md_hash = (
1797
+ hashlib.sha256(agents_md.read_bytes()).hexdigest()[:12] if agents_md.exists() else "?"
1798
+ )
1799
+
1800
+ trace_file = run_dir / "trace.jsonl"
1801
+ trace_file.write_text(
1802
+ json.dumps(
1803
+ {
1804
+ "ts": utc_now(),
1805
+ "kind": "run_start",
1806
+ "run_id": rid,
1807
+ "tier": tier,
1808
+ "allowlist": allow,
1809
+ "deny": deny,
1810
+ "verifier": meta.get("verifier"),
1811
+ "agents_md_hash": agents_md_hash,
1812
+ "force": force,
1813
+ "runner": runner,
1814
+ "max_wall_seconds": wall_timeout,
1815
+ "max_tokens": token_limit,
1816
+ }
1817
+ )
1818
+ + "\n",
1819
+ encoding="utf-8",
1820
+ )
1821
+
1822
+ # Create git worktree (if in a git repo)
1823
+ worktree_path: Path | None = None
1824
+ if (
1825
+ subprocess.run(
1826
+ ["git", "-C", str(workspace_root()), "rev-parse", "--git-dir"],
1827
+ capture_output=True,
1828
+ ).returncode
1829
+ == 0
1830
+ ):
1831
+ worktree_base = WORKTREES_HOME / loop_name / rid
1832
+ worktree_base.mkdir(parents=True, exist_ok=True)
1833
+ result = subprocess.run(
1834
+ ["git", "-C", str(workspace_root()), "worktree", "add", str(worktree_base), "HEAD"],
1835
+ capture_output=True,
1836
+ text=True,
1837
+ )
1838
+ if result.returncode == 0:
1839
+ worktree_path = worktree_base
1840
+ log(f"Worktree: {worktree_path}")
1841
+ trace_file.write_text(
1842
+ trace_file.read_text(encoding="utf-8")
1843
+ + json.dumps(
1844
+ {"ts": utc_now(), "kind": "worktree_created", "path": str(worktree_path)}
1845
+ )
1846
+ + "\n",
1847
+ encoding="utf-8",
1848
+ )
1849
+ else:
1850
+ warn(f"Could not create worktree (non-fatal): {result.stderr.strip()}")
1851
+
1852
+ # Check cancellation before dispatching
1853
+ if _CANCELLED:
1854
+ warn("Run cancelled before dispatch")
1855
+ finalize_run(loop_dir, run_dir, rid, worktree_path, trace_file, "cancelled")
1856
+ return 1
1857
+
1858
+ # Dispatch to selected runner (auto chain or --runner NAME)
1859
+ plan_md = run_dir / "plan.md"
1860
+ prompt = _build_runner_prompt(loop_dir, meta, loop_name, run_dir)
1861
+ # Persist the exact prompt for audit / autonomy debugging
1862
+ (run_dir / "prompt.md").write_text(prompt, encoding="utf-8")
1863
+
1864
+ queued = False
1865
+ budget_exhausted = False
1866
+ try:
1867
+ queued, budget_exhausted = _dispatch_loop_runner(
1868
+ runner,
1869
+ prompt=prompt,
1870
+ run_dir=run_dir,
1871
+ rid=rid,
1872
+ loop_name=loop_name,
1873
+ meta=meta,
1874
+ trace_file=trace_file,
1875
+ wall_timeout=wall_timeout,
1876
+ token_limit=token_limit,
1877
+ plan_md=plan_md,
1878
+ tier=tier,
1879
+ )
1880
+ except ValueError as runner_exc:
1881
+ err(str(runner_exc))
1882
+ finalize_run(loop_dir, run_dir, rid, worktree_path, trace_file, "runner_unavailable")
1883
+ return 1
1884
+ except RuntimeError as gate_exc:
1885
+ err(str(gate_exc))
1886
+ finalize_run(loop_dir, run_dir, rid, worktree_path, trace_file, "gate_failed")
1887
+ return 2
1888
+
1889
+ tokens_used = tokens_from_trace(trace_file)
1890
+ if token_budget_exceeded(tokens_used, budget):
1891
+ budget_exhausted = True
1892
+ warn(f"Run exceeded max_tokens ({token_limit:,}); recorded {tokens_used:,} in trace")
1893
+
1894
+ if budget_exhausted:
1895
+ trace_file.write_text(
1896
+ trace_file.read_text(encoding="utf-8")
1897
+ + json.dumps(
1898
+ {
1899
+ "ts": utc_now(),
1900
+ "kind": "budget_exhausted",
1901
+ "tokens_used": tokens_used,
1902
+ "max_wall_seconds": wall_timeout,
1903
+ "max_tokens": token_limit,
1904
+ }
1905
+ )
1906
+ + "\n",
1907
+ encoding="utf-8",
1908
+ )
1909
+
1910
+ # Update state — preserve pending/escalations/notes the agent wrote (or prior)
1911
+ if budget_exhausted:
1912
+ run_status = "partial (budget_exhausted)"
1913
+ else:
1914
+ run_status = "queued" if queued else "completed"
1915
+ post = parse_state_md(loop_dir) if state_md.exists() else {}
1916
+ new_state: dict[str, Any] = {
1917
+ "last_run": utc_now(),
1918
+ "last_run_status": run_status,
1919
+ "last_run_id": rid,
1920
+ "runs_today": runs_today + 1,
1921
+ "last_run_tokens": tokens_used,
1922
+ }
1923
+ # Prefer agent-updated lists when present; otherwise keep prior
1924
+ for key in ("pending", "escalations", "notes"):
1925
+ if key in post and post[key] is not None:
1926
+ new_state[key] = post[key]
1927
+ elif key in state and state[key] is not None:
1928
+ new_state[key] = state[key]
1929
+ elif key in ("pending", "escalations"):
1930
+ new_state[key] = []
1931
+ if queued:
1932
+ queued_pending = list(_as_str_list(new_state.get("pending")))
1933
+ queued_pending.append(f"devcompanion:loop-{loop_name}-{rid}")
1934
+ new_state["pending"] = queued_pending
1935
+ write_state_md(loop_dir, new_state)
1936
+
1937
+ # For queued runs, add trace entry and clean up worktree
1938
+ if queued:
1939
+ trace_file.write_text(
1940
+ trace_file.read_text(encoding="utf-8")
1941
+ + json.dumps({"ts": utc_now(), "kind": "queued", "job_id": f"loop-{loop_name}-{rid}"})
1942
+ + "\n",
1943
+ encoding="utf-8",
1944
+ )
1945
+ # Clean up worktree — the devcompanion worker runs independently
1946
+ if worktree_path and worktree_path.is_dir():
1947
+ subprocess.run(
1948
+ [
1949
+ "git",
1950
+ "-C",
1951
+ str(workspace_root()),
1952
+ "worktree",
1953
+ "remove",
1954
+ str(worktree_path),
1955
+ "--force",
1956
+ ],
1957
+ capture_output=True,
1958
+ )
1959
+ ok(f"Run {rid} queued for async processing. State: {run_status}")
1960
+ ok(" Check later with: devcompanion status")
1961
+ return 0
1962
+
1963
+ # Cleanup worktree on inline completion
1964
+ if worktree_path and worktree_path.is_dir():
1965
+ subprocess.run(
1966
+ [
1967
+ "git",
1968
+ "-C",
1969
+ str(workspace_root()),
1970
+ "worktree",
1971
+ "remove",
1972
+ str(worktree_path),
1973
+ "--force",
1974
+ ],
1975
+ capture_output=True,
1976
+ )
1977
+
1978
+ finalize_run(
1979
+ loop_dir,
1980
+ run_dir,
1981
+ rid,
1982
+ worktree_path,
1983
+ trace_file,
1984
+ "budget_exhausted" if budget_exhausted else "completed",
1985
+ )
1986
+ return 1 if budget_exhausted else 0
1987
+
1988
+
1989
+ def finalize_run(
1990
+ loop_dir: Path,
1991
+ run_dir: Path,
1992
+ rid: str,
1993
+ worktree_path: Path | None,
1994
+ trace_file: Path,
1995
+ status: str,
1996
+ ) -> None:
1997
+ """Clean up worktree, finalize trace, and close the loop."""
1998
+ global _CANCELLED
1999
+ if _CANCELLED and status != "cancelled":
2000
+ status = "cancelled"
2001
+
2002
+ # Cleanup worktree
2003
+ if worktree_path and worktree_path.is_dir():
2004
+ subprocess.run(
2005
+ [
2006
+ "git",
2007
+ "-C",
2008
+ str(workspace_root()),
2009
+ "worktree",
2010
+ "remove",
2011
+ str(worktree_path),
2012
+ "--force",
2013
+ ],
2014
+ capture_output=True,
2015
+ )
2016
+
2017
+ # Finalize trace
2018
+ trace_file.write_text(
2019
+ trace_file.read_text(encoding="utf-8")
2020
+ + json.dumps({"ts": utc_now(), "kind": "run_end", "status": status})
2021
+ + "\n",
2022
+ encoding="utf-8",
2023
+ )
2024
+
2025
+ if status == "completed":
2026
+ # Loop closure: extract learning events from trace and sync to knowledge
2027
+ _close_loop(run_dir, rid)
2028
+ ok(f"Run {rid} complete. Artifacts at: {run_dir.relative_to(workspace_root())}")
2029
+ else:
2030
+ warn(f"Run {rid} finished with status: {status}")
2031
+
2032
+
2033
+ def _close_loop(run_dir: Path, rid: str) -> None:
2034
+ """Extract learning/decision events from trace and sync to knowledge."""
2035
+ trace_file = run_dir / "trace.jsonl"
2036
+ if not trace_file.exists():
2037
+ return
2038
+
2039
+ added = 0
2040
+ for line in trace_file.read_text(encoding="utf-8").splitlines():
2041
+ try:
2042
+ event = json.loads(line)
2043
+ except json.JSONDecodeError:
2044
+ continue
2045
+ if event.get("kind") == "decision" and event.get("tag") == "learning":
2046
+ content = event.get("content", "")
2047
+ if content:
2048
+ add_script = workspace_root() / "bin" / "assistant-memory"
2049
+ if add_script.exists():
2050
+ subprocess.run(
2051
+ [
2052
+ sys.executable,
2053
+ str(add_script),
2054
+ "add",
2055
+ "--type",
2056
+ "learning",
2057
+ "--from-loop",
2058
+ rid,
2059
+ content,
2060
+ ],
2061
+ capture_output=True,
2062
+ )
2063
+ added += 1
2064
+ if event.get("kind") == "run_start":
2065
+ event.get("run_id", rid)
2066
+
2067
+ if added:
2068
+ ok(f"Synced {added} learning event(s) from run {rid} to knowledge base")
2069
+
2070
+
2071
+ def cmd_status(args: list[str]) -> int:
2072
+ """Show loop status."""
2073
+ target = args[0] if args else None
2074
+ if target:
2075
+ loops = [resolve_loop_dir(target)]
2076
+ else:
2077
+ loops = list_loops()
2078
+ # No user instances yet — show bundled templates so uvx/pip installs
2079
+ # still discover the 10 reference loops (validate.yml uvx job).
2080
+ if not loops:
2081
+ bundled = toolkit_loops_dir()
2082
+ if bundled.is_dir():
2083
+ loops = [
2084
+ d
2085
+ for d in sorted(bundled.iterdir())
2086
+ if d.is_dir() and ((d / "loop.yaml").exists() or (d / "LOOP.md").exists())
2087
+ ]
2088
+
2089
+ if not loops:
2090
+ print("No loops found. Run: agent-toolkit loop init <pattern>")
2091
+ return 0
2092
+
2093
+ print("")
2094
+ print(blue("── Loop Status ──────────────────────────────────────────"))
2095
+ for loop_dir in loops:
2096
+ if not loop_dir.exists():
2097
+ err(f"Loop '{loop_dir.name}' not found.")
2098
+ continue
2099
+ meta = parse_loop_md(loop_dir)
2100
+ tier = meta.get("tier", "?")
2101
+ cadence = meta.get("cadence", "?")
2102
+ runs = list(sorted((loop_dir / "runs").glob("*"))) if (loop_dir / "runs").is_dir() else []
2103
+ state_file = loop_dir / "STATE.md"
2104
+ last_status = "not_run"
2105
+ if state_file.exists():
2106
+ # Read STATE.md directly (parse_loop_md would read LOOP.md)
2107
+ state_text = state_file.read_text(encoding="utf-8")
2108
+ lines = state_text.splitlines()
2109
+ # Extract frontmatter
2110
+ if lines and lines[0].strip() == "---":
2111
+ end = next(
2112
+ (i for i, line in enumerate(lines[1:], 1) if line.strip() == "---"), None
2113
+ )
2114
+ if end:
2115
+ for line in lines[1:end]:
2116
+ if line.strip().startswith("last_run_status:"):
2117
+ last_status = line.split(":", 1)[1].strip()
2118
+ break
2119
+ print(
2120
+ f" {dim(loop_dir.name):<35} tier={tier} cadence={cadence} "
2121
+ f"runs={len(runs)} last={last_status}"
2122
+ )
2123
+ print("")
2124
+ return 0
2125
+
2126
+
2127
+ def cmd_audit(args: list[str]) -> int:
2128
+ """Summarize past runs."""
2129
+ target = args[0] if args else None
2130
+ loops = [resolve_loop_dir(target)] if target else list_loops()
2131
+
2132
+ print("")
2133
+ print(blue("── Loop Audit ───────────────────────────────────────────"))
2134
+ for loop_dir in loops:
2135
+ if not loop_dir.exists():
2136
+ continue
2137
+ runs_dir = loop_dir / "runs"
2138
+ if not runs_dir.is_dir():
2139
+ continue
2140
+ runs = sorted(runs_dir.iterdir())
2141
+ if not runs:
2142
+ print(f"\n {loop_dir.name}: no runs yet")
2143
+ continue
2144
+
2145
+ completed = 0
2146
+ failed = 0
2147
+ total_tokens = 0
2148
+
2149
+ for run in runs:
2150
+ trace = run / "trace.jsonl"
2151
+ if not trace.exists():
2152
+ continue
2153
+ for line in trace.read_text(encoding="utf-8").splitlines():
2154
+ try:
2155
+ event = json.loads(line)
2156
+ if event.get("kind") == "run_end":
2157
+ if event.get("status") == "completed":
2158
+ completed += 1
2159
+ else:
2160
+ failed += 1
2161
+ if event.get("kind") in ("prompt", "completion"):
2162
+ total_tokens += event.get("prompt_tokens", 0)
2163
+ total_tokens += event.get("completion_tokens", 0)
2164
+ except json.JSONDecodeError:
2165
+ pass
2166
+
2167
+ total = completed + failed
2168
+ rate = f"{completed / total * 100:.0f}%" if total else "—"
2169
+ print(
2170
+ f"\n {dim(loop_dir.name)}\n"
2171
+ f" runs={total} success={completed} failed={failed} "
2172
+ f"rate={rate} tokens≈{total_tokens:,}"
2173
+ )
2174
+
2175
+ print("")
2176
+ return 0
2177
+
2178
+
2179
+ def cmd_cost(args: list[str]) -> int:
2180
+ """Estimate cost for one run."""
2181
+ if not args:
2182
+ err("Usage: loop cost <loop-name>")
2183
+ return 1
2184
+
2185
+ loop_name = args[0]
2186
+ loop_dir = resolve_loop_dir(loop_name)
2187
+ if loop_dir is None:
2188
+ err(f"Loop '{loop_name}' not found. Run: agent-toolkit loop init {loop_name}")
2189
+ return 1
2190
+ meta = parse_loop_md(loop_dir) if loop_dir.exists() else {}
2191
+
2192
+ tier = meta.get("tier", "L1")
2193
+ budget = meta.get("budget", {})
2194
+ max_tokens = budget.get("max_tokens", "?")
2195
+ cadence = meta.get("cadence", "?")
2196
+
2197
+ cost_tiers = {
2198
+ "daily-triage": ("low", "~$0.01-0.05"),
2199
+ "issue-triage": ("low", "~$0.01-0.05"),
2200
+ "changelog-drafter": ("low", "~$0.01-0.05"),
2201
+ "post-merge-cleanup": ("low", "~$0.01-0.05"),
2202
+ "dep-sweeper": ("medium", "~$0.05-0.20"),
2203
+ "pr-babysitter": ("high", "~$0.20-1.00/run"),
2204
+ "ci-sweeper": ("very-high", "~$0.50-2.00/run"),
2205
+ }
2206
+ tier_label, est = cost_tiers.get(loop_name, ("unknown", "—"))
2207
+
2208
+ print(f"\n Loop: {loop_name}")
2209
+ print(f" Tier: {tier}")
2210
+ print(f" Cadence: {cadence}")
2211
+ print(f" Budget max_tokens: {max_tokens}")
2212
+ print(f" Cost tier: {tier_label}")
2213
+ print(f" Estimated per run: {est}")
2214
+ print("")
2215
+ return 0
2216
+
2217
+
2218
+ def cmd_schedule(args: list[str]) -> int:
2219
+ """Install or manage OS-level timer for a loop."""
2220
+ list_mode = "--list" in args
2221
+ remove_mode = "--remove" in args
2222
+ status_mode = "--status" in args
2223
+ dry_run = "--dry-run" in args
2224
+ cron_override = None
2225
+
2226
+ # Extract --cron value
2227
+ for i, a in enumerate(args):
2228
+ if a == "--cron" and i + 1 < len(args):
2229
+ cron_override = args[i + 1]
2230
+ break
2231
+ if a.startswith("--cron="):
2232
+ cron_override = a.split("=", 1)[1]
2233
+ break
2234
+
2235
+ # --list: show all scheduled loops
2236
+ if list_mode:
2237
+ return _schedule_list()
2238
+ if status_mode:
2239
+ return _schedule_status()
2240
+
2241
+ # --remove: remove schedule for a loop
2242
+ if remove_mode:
2243
+ loop_name = next((a for a in args if not a.startswith("-") and a != "schedule"), None)
2244
+ if not loop_name:
2245
+ err("Usage: agent-toolkit loop schedule <name> --remove")
2246
+ return 1
2247
+ return _schedule_remove(loop_name, dry_run)
2248
+
2249
+ # schedule <name>: install timer
2250
+ loop_name = next((a for a in args if not a.startswith("-") and a != "schedule"), None)
2251
+ if not loop_name:
2252
+ err("Usage: agent-toolkit loop schedule <name> [--cron EXPR] [--dry-run]")
2253
+ return 1
2254
+
2255
+ loop_dir = resolve_loop_dir(loop_name)
2256
+ if loop_dir is None:
2257
+ err(f"Loop '{loop_name}' not found. Run: agent-toolkit loop init {loop_name}")
2258
+ return 1
2259
+ if not loop_dir.is_dir():
2260
+ err(f"Loop not found: {loop_name} (run 'agent-toolkit loop init {loop_name}' first)")
2261
+ return 1
2262
+
2263
+ loopyaml = loop_dir / "LOOP.md"
2264
+ if not loopyaml.exists():
2265
+ err(f"LOOP.md not found in {loop_dir}")
2266
+ return 1
2267
+
2268
+ loop_cfg = parse_loop_md(loopyaml)
2269
+ cron = cron_override or loop_cfg.get("schedule", "daily")
2270
+
2271
+ if dry_run:
2272
+ log(f"[DRY-RUN] Would schedule: {loop_name}")
2273
+ log(f" Cron: {cron}")
2274
+ return _schedule_dry_run(loop_name, cron)
2275
+
2276
+ return _schedule_install(loop_name, cron)
2277
+
2278
+
2279
+ def _schedule_dry_run(loop_name: str, cron: str) -> int:
2280
+ """Print timer files without installing."""
2281
+ system = platform.system()
2282
+ harness_dir = workspace_root()
2283
+ loop_cmd = f"{harness_dir}/bin/loop run {loop_name}"
2284
+
2285
+ print(f"\n{blue('[loop]')} Would schedule: {loop_name}")
2286
+ print(f" Cron: {cron}")
2287
+ print(f" Command: {loop_cmd}")
2288
+ print()
2289
+
2290
+ if system == "Linux":
2291
+ svc = _systemd_service(loop_name, loop_cmd)
2292
+ timer = _systemd_timer(loop_name, cron)
2293
+ print(dim("--- systemd service (would create) ---"))
2294
+ print(svc)
2295
+ print(dim("--- systemd timer (would create) ---"))
2296
+ print(timer)
2297
+ print(dim(f"Would enable: systemctl --user enable agent-toolkit-{loop_name}.timer"))
2298
+ print(dim(f"Would start: systemctl --user start agent-toolkit-{loop_name}.timer"))
2299
+ elif system == "Darwin":
2300
+ plist = _launchd_plist(loop_name, cron)
2301
+ print(dim("--- launchd plist (would create) ---"))
2302
+ print(plist)
2303
+ print(
2304
+ dim(
2305
+ f"Would load: launchctl load ~/Library/LaunchAgents/com.agent-toolkit.{loop_name}.plist"
2306
+ )
2307
+ )
2308
+ else:
2309
+ print(yellow(f"Manual scheduling required on {system}:"))
2310
+ print(f" {loop_cmd}")
2311
+ print(f" Schedule: {cron}")
2312
+ print()
2313
+
2314
+ return 0
2315
+
2316
+
2317
+ def _schedule_install(loop_name: str, cron: str) -> int:
2318
+ """Install systemd timer (Linux) or launchd plist (macOS)."""
2319
+ system = platform.system()
2320
+ harness_dir = workspace_root()
2321
+ loop_cmd = f"{harness_dir}/bin/loop run {loop_name}"
2322
+
2323
+ if system == "Linux":
2324
+ systemd_user = Path.home() / ".config" / "systemd" / "user"
2325
+ systemd_user.mkdir(parents=True, exist_ok=True)
2326
+
2327
+ svc_path = systemd_user / f"agent-toolkit-{loop_name}.service"
2328
+ timer_path = systemd_user / f"agent-toolkit-{loop_name}.timer"
2329
+
2330
+ svc_path.write_text(_systemd_service(loop_name, loop_cmd), encoding="utf-8")
2331
+ timer_path.write_text(_systemd_timer(loop_name, cron), encoding="utf-8")
2332
+
2333
+ ok(f"Created: {svc_path}")
2334
+ ok(f"Created: {timer_path}")
2335
+
2336
+ # Enable and start
2337
+ try:
2338
+ subprocess.run(
2339
+ ["systemctl", "--user", "enable", f"agent-toolkit-{loop_name}.timer"],
2340
+ capture_output=True,
2341
+ text=True,
2342
+ check=False,
2343
+ )
2344
+ subprocess.run(
2345
+ ["systemctl", "--user", "start", f"agent-toolkit-{loop_name}.timer"],
2346
+ capture_output=True,
2347
+ text=True,
2348
+ check=False,
2349
+ )
2350
+ ok(f"Enabled and started: agent-toolkit-{loop_name}.timer")
2351
+ except Exception as e:
2352
+ warn(f"Could not enable timer: {e}")
2353
+ ok(
2354
+ "Timer files created manually — enable with: systemctl --user enable agent-toolkit-{loop_name}.timer"
2355
+ )
2356
+
2357
+ return 0
2358
+
2359
+ elif system == "Darwin":
2360
+ launchd_dir = Path.home() / "Library" / "LaunchAgents"
2361
+ launchd_dir.mkdir(parents=True, exist_ok=True)
2362
+
2363
+ plist_path = launchd_dir / f"com.agent-toolkit.{loop_name}.plist"
2364
+ plist_path.write_text(_launchd_plist(loop_name, cron), encoding="utf-8")
2365
+
2366
+ ok(f"Created: {plist_path}")
2367
+
2368
+ try:
2369
+ subprocess.run(
2370
+ ["launchctl", "load", str(plist_path)],
2371
+ capture_output=True,
2372
+ text=True,
2373
+ check=False,
2374
+ )
2375
+ ok(f"Loaded: com.agent-toolkit.{loop_name}")
2376
+ except Exception as e:
2377
+ warn(f"Could not load plist: {e}")
2378
+ ok(
2379
+ f"Plist created — load with: launchctl load ~/Library/LaunchAgents/com.agent-toolkit.{loop_name}.plist"
2380
+ )
2381
+
2382
+ return 0
2383
+
2384
+ else:
2385
+ print(f"\n{yellow('Manual scheduling required on ' + system + ':')}")
2386
+ print(f" Command: {loop_cmd}")
2387
+ print(f" Schedule: {cron}")
2388
+ print()
2389
+ return 0
2390
+
2391
+
2392
+ def _schedule_list() -> int:
2393
+ """List all scheduled loops."""
2394
+ system = platform.system()
2395
+ loops = []
2396
+ if system == "Linux":
2397
+ systemd_user = Path.home() / ".config" / "systemd" / "user"
2398
+ for p in sorted(systemd_user.glob("agent-toolkit-*.timer")):
2399
+ name = p.stem.replace("agent-toolkit-", "").replace(".timer", "")
2400
+ loops.append(name)
2401
+ elif system == "Darwin":
2402
+ launchd_dir = Path.home() / "Library" / "LaunchAgents"
2403
+ for p in sorted(launchd_dir.glob("com.agent-toolkit.*.plist")):
2404
+ name = p.stem.replace("com.agent-toolkit.", "")
2405
+ loops.append(name)
2406
+
2407
+ if not loops:
2408
+ print(dim("No scheduled loops found."))
2409
+ return 0
2410
+
2411
+ print(f"\n{blue('[loop]')} Scheduled loops:")
2412
+ for name in loops:
2413
+ enabled = _schedule_enabled(name)
2414
+ enabled_str = green("enabled") if enabled else yellow("disabled")
2415
+ print(f" {name:30s} {enabled_str}")
2416
+ print()
2417
+ return 0
2418
+
2419
+
2420
+ def _schedule_status() -> int:
2421
+ """Check schedule health."""
2422
+ system = platform.system()
2423
+ issues = []
2424
+ if system == "Linux":
2425
+ systemd_user = Path.home() / ".config" / "systemd" / "user"
2426
+ for p in sorted(systemd_user.glob("agent-toolkit-*.timer")):
2427
+ name = p.stem.replace("agent-toolkit-", "").replace(".timer", "")
2428
+ # Check if timer is active
2429
+ result = subprocess.run(
2430
+ ["systemctl", "--user", "is-active", f"agent-toolkit-{name}.timer"],
2431
+ capture_output=True,
2432
+ text=True,
2433
+ check=False,
2434
+ )
2435
+ status = result.stdout.strip()
2436
+ if status != "active":
2437
+ issues.append(f"{name}: {status}")
2438
+ elif system == "Darwin":
2439
+ launchd_dir = Path.home() / "Library" / "LaunchAgents"
2440
+ for p in sorted(launchd_dir.glob("com.agent-toolkit.*.plist")):
2441
+ name = p.stem.replace("com.agent-toolkit.", "")
2442
+ result = subprocess.run(
2443
+ ["launchctl", "list", f"com.agent-toolkit.{name}"],
2444
+ capture_output=True,
2445
+ text=True,
2446
+ check=False,
2447
+ )
2448
+ if result.returncode != 0:
2449
+ issues.append(f"{name}: not loaded")
2450
+
2451
+ if issues:
2452
+ print(f"\n{yellow('[loop]')} Schedule issues:")
2453
+ for issue in issues:
2454
+ print(f" {yellow('!')} {issue}")
2455
+ print()
2456
+ else:
2457
+ ok("All schedules healthy.")
2458
+ return 0
2459
+
2460
+
2461
+ def _schedule_remove(loop_name: str, dry_run: bool) -> int:
2462
+ """Remove schedule for a loop."""
2463
+ system = platform.system()
2464
+ if system == "Linux":
2465
+ systemd_user = Path.home() / ".config" / "systemd" / "user"
2466
+ svc = systemd_user / f"agent-toolkit-{loop_name}.service"
2467
+ timer = systemd_user / f"agent-toolkit-{loop_name}.timer"
2468
+
2469
+ if dry_run:
2470
+ log(f"[DRY-RUN] Would remove: {svc}")
2471
+ log(f"[DRY-RUN] Would remove: {timer}")
2472
+ return 0
2473
+
2474
+ # Stop and disable first
2475
+ subprocess.run(
2476
+ ["systemctl", "--user", "stop", f"agent-toolkit-{loop_name}.timer"],
2477
+ capture_output=True,
2478
+ text=True,
2479
+ check=False,
2480
+ )
2481
+ subprocess.run(
2482
+ ["systemctl", "--user", "disable", f"agent-toolkit-{loop_name}.timer"],
2483
+ capture_output=True,
2484
+ text=True,
2485
+ check=False,
2486
+ )
2487
+ svc.unlink(missing_ok=True)
2488
+ timer.unlink(missing_ok=True)
2489
+ ok(f"Removed schedule: {loop_name}")
2490
+
2491
+ elif system == "Darwin":
2492
+ plist = Path.home() / "Library" / "LaunchAgents" / f"com.agent-toolkit.{loop_name}.plist"
2493
+ if dry_run:
2494
+ log(f"[DRY-RUN] Would remove: {plist}")
2495
+ return 0
2496
+
2497
+ subprocess.run(
2498
+ ["launchctl", "unload", str(plist)],
2499
+ capture_output=True,
2500
+ text=True,
2501
+ check=False,
2502
+ )
2503
+ plist.unlink(missing_ok=True)
2504
+ ok(f"Removed schedule: {loop_name}")
2505
+
2506
+ else:
2507
+ warn(f"Manual removal required on {system}.")
2508
+
2509
+ return 0
2510
+
2511
+
2512
+ def _schedule_enabled(loop_name: str) -> bool:
2513
+ """Check if a loop timer is enabled."""
2514
+ system = platform.system()
2515
+ if system == "Linux":
2516
+ result = subprocess.run(
2517
+ ["systemctl", "--user", "is-enabled", f"agent-toolkit-{loop_name}.timer"],
2518
+ capture_output=True,
2519
+ text=True,
2520
+ check=False,
2521
+ )
2522
+ return result.stdout.strip() == "enabled"
2523
+ elif system == "Darwin":
2524
+ plist = Path.home() / "Library" / "LaunchAgents" / f"com.agent-toolkit.{loop_name}.plist"
2525
+ if not plist.exists():
2526
+ return False
2527
+ result = subprocess.run(
2528
+ ["launchctl", "list", f"com.agent-toolkit.{loop_name}"],
2529
+ capture_output=True,
2530
+ text=True,
2531
+ check=False,
2532
+ )
2533
+ return result.returncode == 0
2534
+ return False
2535
+
2536
+
2537
+ def _systemd_service(loop_name: str, exec_cmd: str) -> str:
2538
+ """Generate systemd service file content."""
2539
+ return f"""[Unit]
2540
+ Description=agent-toolkit loop: {loop_name}
2541
+ After=network-online.target
2542
+
2543
+ [Service]
2544
+ Type=oneshot
2545
+ ExecStart={exec_cmd}
2546
+ StandardOutput=journal
2547
+ StandardError=journal
2548
+ """
2549
+
2550
+
2551
+ def _systemd_timer(loop_name: str, cron: str) -> str:
2552
+ """Generate systemd timer file content."""
2553
+ on_calendar = cron
2554
+ # Convert common patterns to systemd OnCalendar format
2555
+ if cron == "hourly":
2556
+ on_calendar = "*-*-* *:00:00"
2557
+ elif cron == "daily":
2558
+ on_calendar = "*-*-* 09:00:00"
2559
+ elif cron == "weekly":
2560
+ on_calendar = "Mon *-*-* 09:00:00"
2561
+
2562
+ return f"""[Unit]
2563
+ Description=agent-toolkit loop timer: {loop_name}
2564
+
2565
+ [Timer]
2566
+ OnCalendar={on_calendar}
2567
+ Persistent=true
2568
+
2569
+ [Install]
2570
+ WantedBy=timers.target
2571
+ """
2572
+
2573
+
2574
+ def _launchd_plist(loop_name: str, cron: str) -> str:
2575
+ """Generate launchd plist content."""
2576
+ interval = 86400 # daily default
2577
+ if cron == "hourly":
2578
+ interval = 3600
2579
+ elif cron == "weekly":
2580
+ interval = 604800
2581
+
2582
+ return f"""<?xml version="1.0" encoding="UTF-8"?>
2583
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
2584
+ <plist version="1.0">
2585
+ <dict>
2586
+ <key>Label</key>
2587
+ <string>com.agent-toolkit.{loop_name}</string>
2588
+ <key>ProgramArguments</key>
2589
+ <array>
2590
+ <string>{workspace_root()}/bin/loop</string>
2591
+ <string>run</string>
2592
+ <string>{loop_name}</string>
2593
+ </array>
2594
+ <key>StartInterval</key>
2595
+ <integer>{interval}</integer>
2596
+ <key>RunAtLoad</key>
2597
+ <false/>
2598
+ </dict>
2599
+ </plist>
2600
+ """
2601
+
2602
+
2603
+ def cmd_list(args: list[str]) -> int:
2604
+ """List detected loops (same places `loop run <name>` searches)."""
2605
+ # Same resolution as `run`/`status`: workspace instances first, then bundled fallback
2606
+ loops = list_loops()
2607
+ bundled_fallback = False
2608
+ if not loops:
2609
+ bundled = toolkit_loops_dir()
2610
+ if bundled.is_dir():
2611
+ loops = [
2612
+ d
2613
+ for d in sorted(bundled.iterdir())
2614
+ if d.is_dir() and ((d / "loop.yaml").exists() or (d / "LOOP.md").exists())
2615
+ ]
2616
+ bundled_fallback = True
2617
+
2618
+ if not loops:
2619
+ print("No loops found. Run: agent-toolkit loop init <pattern>")
2620
+ return 0
2621
+
2622
+ ws = workspace_root()
2623
+ bundled_dir = toolkit_loops_dir()
2624
+ print("")
2625
+ print(blue("── Loops (detected) ─────────────────────────────────────"))
2626
+ for loop_dir in loops:
2627
+ try:
2628
+ rel = loop_dir.relative_to(ws)
2629
+ source = "workspace"
2630
+ except ValueError:
2631
+ try:
2632
+ rel = loop_dir.relative_to(bundled_dir)
2633
+ source = "bundled"
2634
+ except ValueError:
2635
+ rel = loop_dir
2636
+ source = "bundled" if bundled_fallback else "workspace"
2637
+ meta = parse_loop_md(loop_dir) if (loop_dir / "LOOP.md").exists() else {}
2638
+ tier = meta.get("tier", "?") if isinstance(meta, dict) else "?"
2639
+ cadence = meta.get("cadence", "?") if isinstance(meta, dict) else "?"
2640
+ print(
2641
+ f" {loop_dir.name:<30} {dim(f'source={source}'):<18} tier={tier} cadence={cadence} {dim(str(rel.parent))}"
2642
+ )
2643
+ print("")
2644
+ return 0
2645
+
2646
+
2647
+ def cmd_sync() -> int:
2648
+ """Regenerate knowledge todos from completed loop runs."""
2649
+ knowledge_todos = workspace_root() / "knowledge" / "todos" / "pending.md"
2650
+ if not loops_dir().is_dir():
2651
+ return 0
2652
+
2653
+ entries = []
2654
+ for loop_dir in sorted(loops_dir().iterdir()):
2655
+ if not (loop_dir / "STATE.md").exists():
2656
+ continue
2657
+ state = parse_state_md(loop_dir)
2658
+ escalations = state.get("escalations", []) or []
2659
+ for esc in escalations:
2660
+ entries.append(f"- [ ] [loop-escalation] {loop_dir.name}: {esc}")
2661
+
2662
+ if entries and knowledge_todos.exists():
2663
+ existing = knowledge_todos.read_text(encoding="utf-8")
2664
+ header = "<!-- loop-escalations -->"
2665
+ block = "\n".join(entries) + "\n"
2666
+ if header in existing:
2667
+ existing = re.sub(
2668
+ r"<!-- loop-escalations -->.*?<!-- /loop-escalations -->",
2669
+ f"{header}\n{block}<!-- /loop-escalations -->",
2670
+ existing,
2671
+ flags=re.DOTALL,
2672
+ )
2673
+ else:
2674
+ existing += f"\n{header}\n{block}<!-- /loop-escalations -->\n"
2675
+ knowledge_todos.write_text(existing, encoding="utf-8")
2676
+ ok(
2677
+ f"Synced {len(entries)} escalation(s) to {knowledge_todos.relative_to(workspace_root())}"
2678
+ )
2679
+
2680
+ return 0
2681
+
2682
+
2683
+ # ── main ──────────────────────────────────────────────────────────────────────
2684
+
2685
+
2686
+ def main() -> None:
2687
+ argv = sys.argv[1:]
2688
+ if not argv or argv[0] in ("-h", "--help", "help"):
2689
+ print(__doc__)
2690
+ sys.exit(0)
2691
+
2692
+ command = argv[0]
2693
+ rest = argv[1:]
2694
+
2695
+ match command:
2696
+ case "init":
2697
+ sys.exit(cmd_init(rest))
2698
+ case "run":
2699
+ sys.exit(cmd_run(rest))
2700
+ case "status":
2701
+ sys.exit(cmd_status(rest))
2702
+ case "audit":
2703
+ sys.exit(cmd_audit(rest))
2704
+ case "cost":
2705
+ sys.exit(cmd_cost(rest))
2706
+ case "schedule":
2707
+ sys.exit(cmd_schedule(rest))
2708
+ case "sync":
2709
+ sys.exit(cmd_sync())
2710
+ case "list" | "ls":
2711
+ sys.exit(cmd_list(rest))
2712
+ case "templates":
2713
+ for t in list_templates():
2714
+ print(f" {t.stem}")
2715
+ case _:
2716
+ err(f"Unknown command: {command}")
2717
+ print("Run 'agent-toolkit loop help' for usage.")
2718
+ sys.exit(1)
2719
+
2720
+
2721
+ if __name__ == "__main__":
2722
+ main()