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,1713 @@
1
+ """
2
+ workspace — AI workspace scaffolding, session context, and persona management.
3
+
4
+ Usage:
5
+ agent-toolkit workspace <subcommand> [args]
6
+
7
+ Subcommands:
8
+ init [--dir PATH] [--name NAME] Scaffold a new harness workspace
9
+ context [--workspace PATH] Output a session state snapshot
10
+ sync [--workspace PATH] Sync loop escalations into todos
11
+ use-persona <name> Activate a work mode persona
12
+ handoff <name> Transition to another persona (validates rules)
13
+ history [count] Show recent persona transitions
14
+ personas List available personas
15
+ load <pack.yaml> Load a context pack
16
+ load --profile <name> Load a composable profile (pack + persona)
17
+ profiles List available profiles
18
+ validate [surface] Validate workspace schema integrity
19
+ budget [--pack NAME] [--profile NAME] Analyze context footprint
20
+ budget --json [--pack NAME] [--profile NAME] Machine-readable output
21
+
22
+ Options:
23
+ --help Show this help message
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import os
29
+ import re
30
+ import subprocess
31
+ import sys
32
+ import sys as _sys
33
+ from datetime import datetime, timezone
34
+ from pathlib import Path
35
+
36
+ if _sys.platform == "win32":
37
+ try:
38
+ _sys.stdout.reconfigure(encoding="utf-8", errors="replace")
39
+ _sys.stderr.reconfigure(encoding="utf-8", errors="replace")
40
+ except Exception:
41
+ pass
42
+
43
+
44
+ # ---------------------------------------------------------------------------
45
+ # Color helpers
46
+ # ---------------------------------------------------------------------------
47
+
48
+ _USE_COLOR = sys.stdout.isatty() and not os.environ.get("NO_COLOR")
49
+
50
+
51
+ def _c(code: str, text: str) -> str:
52
+ return f"\033[{code}m{text}\033[0m" if _USE_COLOR else text
53
+
54
+
55
+ def _blue(t: str) -> str:
56
+ return _c("1;34", t)
57
+
58
+
59
+ def _green(t: str) -> str:
60
+ return _c("1;32", t)
61
+
62
+
63
+ def _yellow(t: str) -> str:
64
+ return _c("1;33", t)
65
+
66
+
67
+ def _cyan(t: str) -> str:
68
+ return _c("0;36", t)
69
+
70
+
71
+ def _dim(t: str) -> str:
72
+ return _c("0;37", t)
73
+
74
+
75
+ # ---------------------------------------------------------------------------
76
+ # Workspace root detection
77
+ # ---------------------------------------------------------------------------
78
+
79
+
80
+ def _find_workspace(override: str | None = None) -> Path | None:
81
+ """Locate workspace root via env, override, or walking up from CWD."""
82
+ from agent_toolkit._paths import find_workspace_root
83
+
84
+ return find_workspace_root(override=override)
85
+
86
+
87
+ # ---------------------------------------------------------------------------
88
+ # File helpers
89
+ # ---------------------------------------------------------------------------
90
+
91
+
92
+ def _write(path: Path, content: str) -> None:
93
+ path.parent.mkdir(parents=True, exist_ok=True)
94
+ path.write_text(content, encoding="utf-8")
95
+
96
+
97
+ def _read(path: Path) -> str:
98
+ return path.read_text(encoding="utf-8") if path.exists() else ""
99
+
100
+
101
+ def _require_workspace(override: str | None = None) -> Path | None:
102
+ ws = _find_workspace(override)
103
+ if ws is None:
104
+ print("Error: workspace not found.", file=sys.stderr)
105
+ print(
106
+ "Set AGENT_TOOLKIT_WORKSPACE or run from inside a workspace directory.", file=sys.stderr
107
+ )
108
+ return ws
109
+
110
+
111
+ def _parse_frontmatter_text(content: str) -> dict:
112
+ """Parse YAML frontmatter from markdown text."""
113
+ from agent_toolkit.loop.runner import _parse_simple_yaml
114
+
115
+ lines = content.splitlines()
116
+ if not lines or lines[0].strip() != "---":
117
+ return {}
118
+ end = next((i for i, line in enumerate(lines[1:], 1) if line.strip() == "---"), None)
119
+ if end is None:
120
+ return {}
121
+ yaml_block = "\n".join(lines[1:end])
122
+ try:
123
+ import yaml # type: ignore
124
+
125
+ loaded = yaml.safe_load(yaml_block)
126
+ return loaded if isinstance(loaded, dict) else {}
127
+ except ImportError:
128
+ return _parse_simple_yaml(yaml_block)
129
+
130
+
131
+ def _parse_yaml_file(path: Path) -> dict:
132
+ """Parse a YAML file (PyYAML when available, else minimal parser)."""
133
+ from agent_toolkit.loop.runner import _parse_simple_yaml
134
+
135
+ text = path.read_text(encoding="utf-8")
136
+ try:
137
+ import yaml # type: ignore
138
+
139
+ loaded = yaml.safe_load(text)
140
+ return loaded if isinstance(loaded, dict) else {}
141
+ except ImportError:
142
+ return _parse_simple_yaml(text)
143
+
144
+
145
+ def _persona_path(ws: Path, name: str) -> Path:
146
+ return ws / "personas" / f"{name}.md"
147
+
148
+
149
+ def _load_persona_meta(ws: Path, name: str) -> dict | None:
150
+ path = _persona_path(ws, name)
151
+ if not path.exists():
152
+ return None
153
+ return _parse_frontmatter_text(path.read_text(encoding="utf-8"))
154
+
155
+
156
+ def _append_persona_history(ws: Path, line: str) -> None:
157
+ history = ws / ".persona-history"
158
+ with history.open("a", encoding="utf-8") as fh:
159
+ fh.write(line + "\n")
160
+
161
+
162
+ def _utc_timestamp() -> str:
163
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
164
+
165
+
166
+ def _format_persona_constraints(persona_name: str, meta: dict) -> str:
167
+ allow = meta.get("allow") or []
168
+ deny = meta.get("deny") or []
169
+ handoffs = meta.get("handoffs") or []
170
+ output_fmt = meta.get("output_format", "")
171
+
172
+ lines = [" <persona-constraints>", f" persona: {persona_name}"]
173
+ if allow:
174
+ lines.append(f" allow: [{', '.join(str(x) for x in allow)}]")
175
+ if deny:
176
+ lines.append(f" deny: [{', '.join(str(x) for x in deny)}]")
177
+ if output_fmt:
178
+ lines.append(f" output_format: {output_fmt}")
179
+ if handoffs:
180
+ lines.append(" handoffs:")
181
+ for h in handoffs:
182
+ if not isinstance(h, dict):
183
+ continue
184
+ when = h.get("when", "")
185
+ to = h.get("to", "")
186
+ lines.append(f' - when: "{when}"')
187
+ lines.append(f" to: {to}")
188
+ lines.append(" </persona-constraints>")
189
+ return "\n".join(lines)
190
+
191
+
192
+ def _pack_notes(ws: Path, pack_ref: str) -> str:
193
+ """Return notes field from an active pack, if any."""
194
+ pack_path = Path(pack_ref)
195
+ if not pack_path.is_absolute():
196
+ pack_path = ws / pack_ref
197
+ if not pack_path.exists():
198
+ return ""
199
+ data = _parse_yaml_file(pack_path)
200
+ notes = data.get("notes")
201
+ if isinstance(notes, str) and notes.strip():
202
+ return notes.strip()
203
+ return ""
204
+
205
+
206
+ def _resolve_pack_file(ws: Path, pack_arg: str) -> Path | None:
207
+ """Resolve a pack path relative to workspace root."""
208
+ candidate = Path(pack_arg)
209
+ if candidate.is_absolute():
210
+ return candidate if candidate.is_file() else None
211
+ for rel in (pack_arg, f"packs/{pack_arg}", f"packs/{pack_arg}.yaml"):
212
+ path = ws / rel
213
+ if path.is_file():
214
+ return path
215
+ return None
216
+
217
+
218
+ def _pack_rel_path(ws: Path, pack_path: Path) -> str:
219
+ try:
220
+ return str(pack_path.relative_to(ws))
221
+ except ValueError:
222
+ return str(pack_path)
223
+
224
+
225
+ # ---------------------------------------------------------------------------
226
+ # Templates
227
+ # ---------------------------------------------------------------------------
228
+
229
+ _AGENTS_MD_TEMPLATE = """\
230
+ # AGENTS.md — AI Workspace Orchestrator
231
+
232
+ > Generated by: agent-toolkit workspace init
233
+ > Customize this file to reflect your team's workflows and tools.
234
+
235
+ **Purpose**: Session that orchestrates multi-repository work.
236
+
237
+ ## Work Context
238
+
239
+ - **Repos**: ./projects/ symlinks · ./repos/ cloned on-demand
240
+ - **Knowledge**: ./knowledge/ — persistent memory across sessions
241
+ - **Personas**: ./personas/ — focused work modes
242
+ - **Packs**: ./packs/ — context bundles per client/project
243
+
244
+ ## Available Commands
245
+
246
+ ```
247
+ agent-toolkit workspace context # Print session snapshot
248
+ agent-toolkit workspace sync # Sync loop escalations into todos
249
+ agent-toolkit memory add --type <t> # Add learning/process/todo
250
+ agent-toolkit memory search <query> # Search knowledge base
251
+ agent-toolkit memory inject # Output context block for session
252
+ agent-toolkit memory todo # List pending todos
253
+ agent-toolkit project clone <org/repo> # Clone a repo and symlink it
254
+ agent-toolkit project list # List indexed projects
255
+ agent-toolkit project scan # Check project/repo consistency
256
+ ```
257
+
258
+ ## Operating Rules
259
+
260
+ - Run `agent-toolkit workspace context` at session start
261
+ - Run `agent-toolkit memory search <topic>` before asking known questions
262
+ - Save discoveries: `agent-toolkit memory add --type learning "..."`
263
+ - Queue background work: `agent-toolkit devcompanion queue <project>`
264
+ """
265
+
266
+ _KNOWLEDGE_README = """\
267
+ # Knowledge Base
268
+
269
+ Persistent memory across sessions. Add entries with:
270
+
271
+ ```
272
+ agent-toolkit memory add --type learning "Always run tests before committing"
273
+ agent-toolkit memory add --type process "How to deploy: ..."
274
+ agent-toolkit memory add --type todo "Investigate slow query in reports"
275
+ ```
276
+
277
+ ## Structure
278
+
279
+ - `learnings/general.md` — factual session learnings
280
+ - `processes/<topic>.md` — how-to procedures
281
+ - `todos/pending.md` — pending follow-ups
282
+ """
283
+
284
+ _LEARNINGS_GENERAL = """\
285
+ # General Learnings
286
+
287
+ <!-- Add new entries with: agent-toolkit memory add --type learning "..." -->
288
+
289
+ | Date | Learning | Context |
290
+ |------|----------|---------|
291
+ """
292
+
293
+ _TODOS_PENDING = """\
294
+ # Pending Todos
295
+
296
+ <!-- Add pending items with date added -->
297
+ <!-- agent-toolkit memory add --type todo "description" -->
298
+ """
299
+
300
+ _PACKS_README = """\
301
+ # Packs
302
+
303
+ Context bundles for switching between clients or projects.
304
+
305
+ Create a YAML file here:
306
+
307
+ ```yaml
308
+ # packs/my-client.yaml
309
+ name: my-client
310
+ description: Context for my-client engagement
311
+ projects:
312
+ - my-client-api
313
+ - my-client-frontend
314
+ notes: |
315
+ Key contacts: ...
316
+ ```
317
+
318
+ Load with: `agent-toolkit workspace load packs/my-client.yaml`
319
+
320
+ Snapshot with: `agent-toolkit workspace context`
321
+ """
322
+
323
+ _PERSONA_IMPLEMENTER = """\
324
+ ---
325
+ allow:
326
+ - write_files
327
+ - run_tests
328
+ - run_build
329
+ - create_commits
330
+ deny:
331
+ - merge_prs
332
+ - deploy_production
333
+ output_format: code_first
334
+ handoffs:
335
+ - when: "implementation complete, needs review"
336
+ to: reviewer
337
+ ---
338
+
339
+ # Implementer Persona
340
+
341
+ > Bias toward action. Write code, run tests, create commits.
342
+
343
+ ## Focus
344
+
345
+ - Write clean, idiomatic code following project conventions
346
+ - Run tests to verify changes work
347
+ - Create commits with clear messages
348
+ - Ask only when genuinely blocked
349
+
350
+ ## Constraints
351
+
352
+ - **Do not** merge PRs or deploy to production
353
+ - Handoff to **reviewer** when implementation is complete
354
+ """
355
+
356
+ _PERSONA_REVIEWER = """\
357
+ ---
358
+ allow:
359
+ - read_files
360
+ - run_tests
361
+ - post_comments
362
+ - approve_prs
363
+ deny:
364
+ - write_files
365
+ - create_commits
366
+ output_format: critique_and_feedback
367
+ handoffs:
368
+ - when: "review complete, changes needed"
369
+ to: implementer
370
+ - when: "security concerns found"
371
+ to: architect
372
+ ---
373
+
374
+ # Reviewer Persona
375
+
376
+ > Analyze and critique. No changes — feedback only.
377
+
378
+ ## Focus
379
+
380
+ - Read code carefully for correctness, clarity, and security
381
+ - Run tests to verify coverage
382
+ - Post clear, actionable feedback
383
+ - Approve PRs when quality bar is met
384
+
385
+ ## Constraints
386
+
387
+ - **Do not** write or modify files
388
+ - **Do not** create commits
389
+ - Handoff to **implementer** when changes are needed
390
+ """
391
+
392
+ _PERSONA_RESEARCHER = """\
393
+ ---
394
+ allow:
395
+ - read_files
396
+ - search_web
397
+ - read_docs
398
+ deny:
399
+ - write_files
400
+ - create_commits
401
+ - run_tests
402
+ output_format: summary_and_findings
403
+ handoffs:
404
+ - when: "research complete, ready to implement"
405
+ to: implementer
406
+ - when: "architectural decision needed"
407
+ to: architect
408
+ ---
409
+
410
+ # Researcher Persona
411
+
412
+ > Explore and summarize. No implementation.
413
+
414
+ ## Focus
415
+
416
+ - Read codebases to understand structure and patterns
417
+ - Search documentation and references
418
+ - Produce clear summaries of findings
419
+ - Identify options with tradeoffs
420
+
421
+ ## Constraints
422
+
423
+ - **Do not** modify any files
424
+ - **Do not** run tests or builds
425
+ - Handoff to **implementer** or **architect** when done
426
+ """
427
+
428
+ _PERSONA_ARCHITECT = """\
429
+ ---
430
+ allow:
431
+ - read_files
432
+ - write_docs
433
+ - create_adrs
434
+ - design_schemas
435
+ deny:
436
+ - write_application_code
437
+ - create_commits
438
+ output_format: design_document
439
+ handoffs:
440
+ - when: "design finalized, ready to build"
441
+ to: implementer
442
+ - when: "security review needed"
443
+ to: reviewer
444
+ ---
445
+
446
+ # Architect Persona
447
+
448
+ > System design, tradeoffs, ADRs.
449
+
450
+ ## Focus
451
+
452
+ - Analyze system design and architectural tradeoffs
453
+ - Write ADRs (Architecture Decision Records)
454
+ - Design schemas, APIs, and data models
455
+ - Evaluate technical options at the system level
456
+
457
+ ## Constraints
458
+
459
+ - **Do not** write application code
460
+ - Write design documents and ADRs, not implementation
461
+ - Handoff to **implementer** when design is finalized
462
+ """
463
+
464
+ _GITIGNORE = """\
465
+ # Cloned repos (managed by agent-toolkit project clone)
466
+ repos/
467
+ # Project symlinks (managed by agent-toolkit project clone/add)
468
+ projects/
469
+ # Active state files
470
+ .active-persona
471
+ .active-pack
472
+ .active-profile
473
+ .active-skills
474
+ .active-loops
475
+ .persona-history
476
+ """
477
+
478
+
479
+ # ---------------------------------------------------------------------------
480
+ # Subcommands
481
+ # ---------------------------------------------------------------------------
482
+
483
+
484
+ def cmd_init(args: list[str]) -> int:
485
+ """Scaffold a new harness workspace."""
486
+ target_dir = Path.cwd()
487
+ name = ""
488
+ i = 0
489
+ while i < len(args):
490
+ match args[i]:
491
+ case "--dir" if i + 1 < len(args):
492
+ target_dir = Path(args[i + 1]).expanduser().resolve()
493
+ i += 2
494
+ case "--name" if i + 1 < len(args):
495
+ name = args[i + 1]
496
+ i += 2
497
+ case "--help" | "-h":
498
+ print("Usage: agent-toolkit workspace init [--dir PATH] [--name NAME]")
499
+ return 0
500
+ case _:
501
+ print(f"Unknown option: {args[i]}", file=sys.stderr)
502
+ return 1
503
+
504
+ if name:
505
+ target_dir = target_dir / name
506
+
507
+ target_dir.mkdir(parents=True, exist_ok=True)
508
+ created: list[str] = []
509
+
510
+ def _create(rel: str, content: str) -> None:
511
+ path = target_dir / rel
512
+ if not path.exists():
513
+ _write(path, content)
514
+ created.append(rel)
515
+ else:
516
+ print(f" {_yellow('skip')} {rel} (already exists)")
517
+
518
+ # Core files
519
+ _create("AGENTS.md", _AGENTS_MD_TEMPLATE)
520
+ _create(".gitignore", _GITIGNORE)
521
+
522
+ # Knowledge
523
+ _create("knowledge/README.md", _KNOWLEDGE_README)
524
+ _create("knowledge/learnings/general.md", _LEARNINGS_GENERAL)
525
+ _create("knowledge/todos/pending.md", _TODOS_PENDING)
526
+
527
+ # Packs
528
+ _create("packs/README.md", _PACKS_README)
529
+
530
+ # Personas
531
+ _create("personas/implementer.md", _PERSONA_IMPLEMENTER)
532
+ _create("personas/reviewer.md", _PERSONA_REVIEWER)
533
+ _create("personas/researcher.md", _PERSONA_RESEARCHER)
534
+ _create("personas/architect.md", _PERSONA_ARCHITECT)
535
+
536
+ # Directories (gitignored, so just ensure they exist)
537
+ for d in ("projects", "repos"):
538
+ (target_dir / d).mkdir(exist_ok=True)
539
+ gitkeep = target_dir / d / ".gitkeep"
540
+ if not gitkeep.exists():
541
+ gitkeep.touch()
542
+ created.append(f"{d}/.gitkeep")
543
+
544
+ print(f"\n{_green('Workspace initialized:')} {target_dir}\n")
545
+ for rel in created:
546
+ print(f" {_green('++')} {rel}")
547
+ print()
548
+ print("Next steps:")
549
+ print(f" cd {target_dir}")
550
+ print(" agent-toolkit workspace context")
551
+ print(" agent-toolkit project clone owner/my-repo")
552
+ print()
553
+ return 0
554
+
555
+
556
+ def _approx_size(path: Path) -> int:
557
+ """Return approximate byte size for a file or directory."""
558
+ if not path.exists():
559
+ return 0
560
+ if path.is_file():
561
+ return path.stat().st_size
562
+ total = 0
563
+ for entry in path.rglob("*"):
564
+ if entry.is_file():
565
+ total += entry.stat().st_size
566
+ return total
567
+
568
+
569
+ def _knowledge_summary(ws: Path, knowledge: Path) -> dict:
570
+ """Summarise knowledge/ learnings, todos, and processes."""
571
+ result: dict = {"learnings": 0, "todos": 0, "processes": 0}
572
+ for key, sub in [
573
+ ("learnings", "learnings"),
574
+ ("todos", "todos"),
575
+ ("processes", "processes"),
576
+ ]:
577
+ subdir = knowledge / sub
578
+ if subdir.is_dir():
579
+ result[key] = sum(1 for _ in subdir.rglob("*") if _.is_file())
580
+ return result
581
+
582
+
583
+ def _print_context_json(
584
+ ws: Path,
585
+ now: datetime,
586
+ active_pack_file: Path,
587
+ active_persona_file: Path,
588
+ knowledge: Path,
589
+ agents_md: Path,
590
+ spec_hash: str | None,
591
+ ) -> None:
592
+ import json
593
+
594
+ pack_path = None
595
+ pack_size = None
596
+ if active_pack_file.exists():
597
+ pack_ref = active_pack_file.read_text(encoding="utf-8").strip()
598
+ pack_path = pack_ref
599
+ pack_abs = Path(pack_ref)
600
+ if not pack_abs.is_absolute():
601
+ pack_abs = ws / pack_ref
602
+ if pack_abs.exists():
603
+ pack_size = _approx_size(pack_abs)
604
+
605
+ persona_name = None
606
+ persona_size = None
607
+ if active_persona_file.exists():
608
+ persona_name = active_persona_file.read_text(encoding="utf-8").strip()
609
+ persona_abs = ws / "personas" / f"{persona_name}.md"
610
+ if persona_abs.exists():
611
+ persona_size = _approx_size(persona_abs)
612
+
613
+ ks = _knowledge_summary(ws, knowledge)
614
+
615
+ manifest = {
616
+ "workspace": str(ws),
617
+ "timestamp": now.isoformat(),
618
+ "sources": {
619
+ "pack": {"path": pack_path, "size_bytes": pack_size} if pack_path else None,
620
+ "persona": {
621
+ "name": persona_name,
622
+ "size_bytes": persona_size,
623
+ }
624
+ if persona_name
625
+ else None,
626
+ "knowledge": ks,
627
+ },
628
+ }
629
+ if spec_hash is not None:
630
+ manifest["spec"] = f"AGENTS.md@{spec_hash}"
631
+
632
+ print(json.dumps(manifest, indent=2, default=str))
633
+
634
+
635
+ def _print_context_explain(
636
+ ws: Path,
637
+ active_pack_file: Path,
638
+ active_persona_file: Path,
639
+ knowledge: Path,
640
+ agents_md: Path,
641
+ ) -> None:
642
+ print()
643
+ print(_cyan("── Composition Sources ────────────────────────────────────"))
644
+
645
+ if active_pack_file.exists():
646
+ pack_ref = active_pack_file.read_text(encoding="utf-8").strip()
647
+ pack_abs = Path(pack_ref)
648
+ if not pack_abs.is_absolute():
649
+ pack_abs = ws / pack_ref
650
+ pack_exists = pack_abs.exists()
651
+ size_str = ""
652
+ if pack_exists:
653
+ psize = _approx_size(pack_abs)
654
+ if psize >= 1024:
655
+ size_str = f" ({psize // 1024} KB)"
656
+ else:
657
+ size_str = f" ({psize} B)"
658
+ status = _green("found") if pack_exists else _yellow("missing")
659
+ print(f" pack : [{status}] {pack_ref}{size_str}")
660
+ if pack_exists:
661
+ data = _parse_yaml_file(pack_abs)
662
+ desc = data.get("description")
663
+ if desc:
664
+ print(f" {_dim(str(desc))}")
665
+ projects = data.get("projects")
666
+ if isinstance(projects, list) and projects:
667
+ print(f" projects: {', '.join(str(p) for p in projects)}")
668
+ else:
669
+ print(_dim(" pack : (none active)"))
670
+
671
+ if active_persona_file.exists():
672
+ persona_name = active_persona_file.read_text(encoding="utf-8").strip()
673
+ persona_abs = ws / "personas" / f"{persona_name}.md"
674
+ persona_exists = persona_abs.exists()
675
+ psize = _approx_size(persona_abs) if persona_exists else 0
676
+ size_str = ""
677
+ if persona_exists:
678
+ if psize >= 1024:
679
+ size_str = f" ({psize // 1024} KB)"
680
+ else:
681
+ size_str = f" ({psize} B)"
682
+ status = _green("found") if persona_exists else _yellow("missing")
683
+ print(f" persona : [{status}] {persona_name}{size_str}")
684
+ else:
685
+ print(_dim(" persona : (none active)"))
686
+
687
+ ks = _knowledge_summary(ws, knowledge)
688
+ if knowledge.is_dir():
689
+ ksize = _approx_size(knowledge)
690
+ if ksize >= 1024:
691
+ ksize_str = f" ({ksize // 1024} KB)"
692
+ else:
693
+ ksize_str = f" ({ksize} B)"
694
+ else:
695
+ ksize_str = ""
696
+ print(
697
+ f" knowledge : {_green('present') if knowledge.is_dir() else _yellow('missing')}"
698
+ f"{ksize_str} (learnings={ks['learnings']}, todos={ks['todos']}, processes={ks['processes']})"
699
+ )
700
+
701
+ if agents_md.exists():
702
+ agents_size = _approx_size(agents_md)
703
+ if agents_size >= 1024:
704
+ asize_str = f" ({agents_size // 1024} KB)"
705
+ else:
706
+ asize_str = f" ({agents_size} B)"
707
+ print(f" AGENTS.md : {_green('found')}{asize_str}")
708
+ else:
709
+ print(_dim(" AGENTS.md : (none)"))
710
+
711
+ print()
712
+ print(_dim(" Budget analysis: see #335"))
713
+ print()
714
+
715
+
716
+ def cmd_context(args: list[str]) -> int:
717
+ """Output a session state snapshot."""
718
+
719
+ workspace_path: str | None = None
720
+ explain = False
721
+ json_out = False
722
+ i = 0
723
+ while i < len(args):
724
+ match args[i]:
725
+ case "--workspace" if i + 1 < len(args):
726
+ workspace_path = args[i + 1]
727
+ i += 2
728
+ case "--explain":
729
+ explain = True
730
+ i += 1
731
+ case "--json":
732
+ json_out = True
733
+ i += 1
734
+ case "--help" | "-h":
735
+ print(
736
+ "Usage: agent-toolkit workspace context [--workspace PATH] [--explain] [--json]"
737
+ )
738
+ print()
739
+ print("Options:")
740
+ print(" --workspace PATH Path to workspace root")
741
+ print(" --explain Show composition sources with paths and sizes")
742
+ print(" --json Output JSON (implies --explain for tooling)")
743
+ return 0
744
+ case _:
745
+ print(f"Unknown option: {args[i]}", file=sys.stderr)
746
+ return 1
747
+
748
+ ws = _find_workspace(workspace_path)
749
+ if ws is None:
750
+ print("Error: workspace not found.", file=sys.stderr)
751
+ print(
752
+ "Set AGENT_TOOLKIT_WORKSPACE or run from inside a workspace directory.", file=sys.stderr
753
+ )
754
+ return 1
755
+
756
+ now = datetime.now(timezone.utc)
757
+ knowledge = ws / "knowledge"
758
+ projects_dir = ws / "projects"
759
+ loops_dir = ws / "loops"
760
+ ws / "packs"
761
+ active_pack_file = ws / ".active-pack"
762
+ active_persona_file = ws / ".active-persona"
763
+ agents_md = ws / "AGENTS.md"
764
+
765
+ if json_out:
766
+ import hashlib
767
+
768
+ spec_hash = None
769
+ if agents_md.exists():
770
+ spec_hash = hashlib.sha256(agents_md.read_bytes()).hexdigest()[:12]
771
+ _print_context_json(
772
+ ws,
773
+ now,
774
+ active_pack_file,
775
+ active_persona_file,
776
+ knowledge,
777
+ agents_md,
778
+ spec_hash,
779
+ )
780
+ return 0
781
+
782
+ print()
783
+ print(_blue("=== AI Workspace — Session Context ==="))
784
+ print()
785
+ print(f"Date : {now.strftime('%Y-%m-%d %H:%M UTC')}")
786
+ print(f"Workspace : {ws}")
787
+ print()
788
+
789
+ # Git branch
790
+ try:
791
+ result = subprocess.run(
792
+ ["git", "-C", str(ws), "rev-parse", "--abbrev-ref", "HEAD"],
793
+ capture_output=True,
794
+ text=True,
795
+ timeout=5,
796
+ )
797
+ if result.returncode == 0:
798
+ print(f"Branch : {result.stdout.strip()}")
799
+ print()
800
+ except Exception:
801
+ pass
802
+
803
+ # Projects
804
+ print(_blue("── Projects ──────────────────────────────────────────────"))
805
+ project_count = 0
806
+ if projects_dir.is_dir():
807
+ for link in sorted(projects_dir.iterdir()):
808
+ if link.is_symlink():
809
+ target = link.resolve()
810
+ status = _green("ok") if target.exists() else _yellow("broken")
811
+ print(f" [{status}] {link.name:30s} -> {link.readlink()}")
812
+ project_count += 1
813
+ if project_count == 0:
814
+ print(_dim(" (no projects indexed — run: agent-toolkit project clone owner/repo)"))
815
+ else:
816
+ print(_dim(" (projects/ directory not found)"))
817
+ print()
818
+
819
+ # Pending todos
820
+ print(_blue("── Pending Todos ──────────────────────────────────────────"))
821
+ todos_path = knowledge / "todos" / "pending.md"
822
+ if todos_path.exists():
823
+ content = todos_path.read_text(encoding="utf-8")
824
+ unchecked = [line for line in content.splitlines() if line.startswith("- [ ]")]
825
+ if unchecked:
826
+ for item in unchecked[:10]:
827
+ print(f" {item}")
828
+ if len(unchecked) > 10:
829
+ print(_dim(f" ... and {len(unchecked) - 10} more"))
830
+ else:
831
+ print(_dim(" (no pending todos)"))
832
+ else:
833
+ print(_dim(" (no todos file)"))
834
+ print()
835
+
836
+ # Recent learnings
837
+ print(_blue("── Recent Learnings ───────────────────────────────────────"))
838
+ learnings_path = knowledge / "learnings" / "general.md"
839
+ if learnings_path.exists():
840
+ content = learnings_path.read_text(encoding="utf-8")
841
+ rows = [line for line in content.splitlines() if re.match(r"^\| \d{4}", line)]
842
+ if rows:
843
+ for row in rows[:3]:
844
+ print(f" {row}")
845
+ else:
846
+ print(_dim(" (no learnings recorded yet)"))
847
+ else:
848
+ print(_dim(" (no learnings file)"))
849
+ print()
850
+
851
+ # Loop status summary
852
+ if loops_dir.is_dir():
853
+ print(_blue("── Loop Status ────────────────────────────────────────────"))
854
+ loop_names = sorted(d.name for d in loops_dir.iterdir() if d.is_dir())
855
+ if loop_names:
856
+ for loop_name in loop_names:
857
+ state_file = loops_dir / loop_name / "STATE.md"
858
+ last_run = "(no STATE.md)"
859
+ if state_file.exists():
860
+ content = state_file.read_text(encoding="utf-8")
861
+ # Look for last run date in STATE.md
862
+ for line in content.splitlines():
863
+ m = re.search(r"(\d{4}-\d{2}-\d{2})", line)
864
+ if m:
865
+ last_run = m.group(1)
866
+ break
867
+ print(f" {loop_name:35s} last: {last_run}")
868
+ else:
869
+ print(_dim(" (no loops configured)"))
870
+ print()
871
+
872
+ # Active pack
873
+ if active_pack_file.exists():
874
+ pack = active_pack_file.read_text(encoding="utf-8").strip()
875
+ print(_blue("── Active Pack ────────────────────────────────────────────"))
876
+ print(f" {pack}")
877
+ notes = _pack_notes(ws, pack)
878
+ if notes:
879
+ print()
880
+ for line in notes.splitlines():
881
+ print(f" {line}")
882
+ print()
883
+
884
+ # Active persona
885
+ if active_persona_file.exists():
886
+ persona = active_persona_file.read_text(encoding="utf-8").strip()
887
+ print(_blue("── Active Persona ─────────────────────────────────────────"))
888
+ print(f" Persona: {persona}")
889
+ print()
890
+ meta = _load_persona_meta(ws, persona)
891
+ if meta:
892
+ print(_format_persona_constraints(persona, meta))
893
+ print()
894
+
895
+ # Active skills (from profile load)
896
+ active_skills_file = ws / ".active-skills"
897
+ if active_skills_file.exists():
898
+ skills_text = active_skills_file.read_text(encoding="utf-8").strip()
899
+ if skills_text:
900
+ skills_list = [s.strip() for s in skills_text.splitlines() if s.strip()]
901
+ if skills_list:
902
+ print(_blue("── Active Skills ─────────────────────────────────────────"))
903
+ for s in skills_list:
904
+ print(f" - {s}")
905
+ print()
906
+
907
+ # Active loops (from profile load)
908
+ active_loops_file = ws / ".active-loops"
909
+ if active_loops_file.exists():
910
+ loops_text = active_loops_file.read_text(encoding="utf-8").strip()
911
+ if loops_text:
912
+ loops_list = [ln.strip() for ln in loops_text.splitlines() if ln.strip()]
913
+ if loops_list:
914
+ print(_blue("── Active Loops ──────────────────────────────────────────"))
915
+ for ln in loops_list:
916
+ print(f" - {ln}")
917
+ print()
918
+
919
+ # AGENTS.md hash
920
+ if agents_md.exists():
921
+ import hashlib
922
+
923
+ spec_hash = hashlib.sha256(agents_md.read_bytes()).hexdigest()[:12]
924
+ print(f"Spec : AGENTS.md@{spec_hash}")
925
+ print()
926
+
927
+ if explain:
928
+ _print_context_explain(
929
+ ws,
930
+ active_pack_file,
931
+ active_persona_file,
932
+ knowledge,
933
+ agents_md,
934
+ )
935
+
936
+ print(_blue("──────────────────────────────────────────────────────────"))
937
+ print()
938
+ return 0
939
+
940
+
941
+ def cmd_sync(args: list[str]) -> int:
942
+ """Sync loop escalations into knowledge/todos/pending.md."""
943
+ workspace_path: str | None = None
944
+ i = 0
945
+ while i < len(args):
946
+ match args[i]:
947
+ case "--workspace" if i + 1 < len(args):
948
+ workspace_path = args[i + 1]
949
+ i += 2
950
+ case "--help" | "-h":
951
+ print("Usage: agent-toolkit workspace sync [--workspace PATH]")
952
+ return 0
953
+ case _:
954
+ print(f"Unknown option: {args[i]}", file=sys.stderr)
955
+ return 1
956
+
957
+ ws = _find_workspace(workspace_path)
958
+ if ws is None:
959
+ print("Error: workspace not found.", file=sys.stderr)
960
+ print(
961
+ "Set AGENT_TOOLKIT_WORKSPACE or run from inside a workspace directory.", file=sys.stderr
962
+ )
963
+ return 1
964
+
965
+ loops_dir = ws / "loops"
966
+ todos_path = ws / "knowledge" / "todos" / "pending.md"
967
+
968
+ if not loops_dir.is_dir():
969
+ print(_dim("No loops/ directory found — nothing to sync."))
970
+ return 0
971
+
972
+ today = datetime.now().date().isoformat()
973
+ todos_content = _read(todos_path)
974
+ new_todos: list[str] = []
975
+
976
+ for loop_dir in sorted(loops_dir.iterdir()):
977
+ if not loop_dir.is_dir():
978
+ continue
979
+ # Scan for escalation markers in reports and STATE.md
980
+ for candidate in ["report.md", "STATE.md", "request.md"]:
981
+ report = loop_dir / candidate
982
+ if not report.exists():
983
+ continue
984
+ content = report.read_text(encoding="utf-8")
985
+ for line in content.splitlines():
986
+ if any(
987
+ marker in line.lower()
988
+ for marker in ["escalat", "action required", "todo:", "follow-up:"]
989
+ ):
990
+ # Extract the meaningful part
991
+ clean = line.strip().lstrip("#").lstrip("-").lstrip(">").strip()
992
+ if len(clean) < 10:
993
+ continue
994
+ todo_line = f"- [ ] {today} - [loop:{loop_dir.name}] {clean}"
995
+ # Avoid duplicates
996
+ if todo_line not in todos_content and todo_line not in new_todos:
997
+ new_todos.append(todo_line)
998
+
999
+ if not new_todos:
1000
+ print(_dim("No escalations found in loop reports."))
1001
+ return 0
1002
+
1003
+ # Append new todos
1004
+ todos_path.parent.mkdir(parents=True, exist_ok=True)
1005
+ marker = "<!-- Add pending items with date added -->"
1006
+ if marker in todos_content:
1007
+ idx = todos_content.index(marker) + len(marker)
1008
+ insert = "\n" + "\n".join(new_todos)
1009
+ new_content = todos_content[:idx] + insert + todos_content[idx:]
1010
+ else:
1011
+ new_content = todos_content + "\n" + "\n".join(new_todos) + "\n"
1012
+
1013
+ _write(todos_path, new_content)
1014
+ print(_green(f"Synced {len(new_todos)} escalation(s) into knowledge/todos/pending.md"))
1015
+ for t in new_todos:
1016
+ print(f" {t}")
1017
+ return 0
1018
+
1019
+
1020
+ def cmd_use_persona(args: list[str]) -> int:
1021
+ """Activate a persona work mode."""
1022
+ workspace_path: str | None = None
1023
+ i = 0
1024
+ while i < len(args):
1025
+ match args[i]:
1026
+ case "--workspace" if i + 1 < len(args):
1027
+ workspace_path = args[i + 1]
1028
+ i += 2
1029
+ case "--help" | "-h":
1030
+ print("Usage: agent-toolkit workspace use-persona <name> [--workspace PATH]")
1031
+ return 0
1032
+ case _:
1033
+ break
1034
+
1035
+ if i >= len(args):
1036
+ print("Usage: agent-toolkit workspace use-persona <name>", file=sys.stderr)
1037
+ return 1
1038
+
1039
+ persona = args[i]
1040
+ ws = _require_workspace(workspace_path)
1041
+ if ws is None:
1042
+ return 1
1043
+
1044
+ persona_file = _persona_path(ws, persona)
1045
+ if not persona_file.exists():
1046
+ print(f"Persona not found: {persona}", file=sys.stderr)
1047
+ cmd_personas([])
1048
+ return 1
1049
+
1050
+ active_file = ws / ".active-persona"
1051
+ from_persona = active_file.read_text(encoding="utf-8").strip() if active_file.exists() else ""
1052
+ ts = _utc_timestamp()
1053
+ if from_persona and from_persona != persona:
1054
+ _append_persona_history(ws, f"{ts} transition: {from_persona} → {persona}")
1055
+ elif not from_persona:
1056
+ _append_persona_history(ws, f"{ts} activate: → {persona}")
1057
+
1058
+ _write(active_file, persona + "\n")
1059
+ print(_green(f"Activated persona: {persona}"))
1060
+ return 0
1061
+
1062
+
1063
+ def cmd_handoff(args: list[str]) -> int:
1064
+ """Transition from active persona to another (validates handoff rules)."""
1065
+ workspace_path: str | None = None
1066
+ i = 0
1067
+ while i < len(args):
1068
+ match args[i]:
1069
+ case "--workspace" if i + 1 < len(args):
1070
+ workspace_path = args[i + 1]
1071
+ i += 2
1072
+ case "--help" | "-h":
1073
+ print("Usage: agent-toolkit workspace handoff <name> [--workspace PATH]")
1074
+ return 0
1075
+ case _:
1076
+ break
1077
+
1078
+ if i >= len(args):
1079
+ print("Usage: agent-toolkit workspace handoff <name>", file=sys.stderr)
1080
+ return 1
1081
+
1082
+ to_persona = args[i]
1083
+ ws = _require_workspace(workspace_path)
1084
+ if ws is None:
1085
+ return 1
1086
+
1087
+ active_file = ws / ".active-persona"
1088
+ if not active_file.exists():
1089
+ print(
1090
+ "No active persona to handoff from. Use 'workspace use-persona <name>' first.",
1091
+ file=sys.stderr,
1092
+ )
1093
+ return 1
1094
+
1095
+ from_persona = active_file.read_text(encoding="utf-8").strip()
1096
+ if not _persona_path(ws, to_persona).exists():
1097
+ print(f"Target persona not found: {to_persona}", file=sys.stderr)
1098
+ cmd_personas([])
1099
+ return 1
1100
+
1101
+ meta = _load_persona_meta(ws, from_persona) or {}
1102
+ handoffs = meta.get("handoffs") or []
1103
+ allowed = {h.get("to") for h in handoffs if isinstance(h, dict) and h.get("to")}
1104
+ if allowed and to_persona not in allowed:
1105
+ allowed_str = ", ".join(sorted(allowed))
1106
+ print(
1107
+ f"Invalid handoff from '{from_persona}' to '{to_persona}'. "
1108
+ f"Allowed targets: {allowed_str}",
1109
+ file=sys.stderr,
1110
+ )
1111
+ return 1
1112
+
1113
+ ts = _utc_timestamp()
1114
+ _append_persona_history(ws, f"{ts} handoff: {from_persona} → {to_persona}")
1115
+ _write(active_file, to_persona + "\n")
1116
+ print(_green(f"Handoff: {from_persona} → {to_persona}"))
1117
+ return 0
1118
+
1119
+
1120
+ def cmd_history(args: list[str]) -> int:
1121
+ """Show recent persona transitions."""
1122
+ workspace_path: str | None = None
1123
+ count = 10
1124
+ i = 0
1125
+ while i < len(args):
1126
+ match args[i]:
1127
+ case "--workspace" if i + 1 < len(args):
1128
+ workspace_path = args[i + 1]
1129
+ i += 2
1130
+ case "--help" | "-h":
1131
+ print("Usage: agent-toolkit workspace history [count] [--workspace PATH]")
1132
+ return 0
1133
+ case arg if arg.isdigit():
1134
+ count = int(arg)
1135
+ i += 1
1136
+ case _:
1137
+ print(f"Unknown option: {args[i]}", file=sys.stderr)
1138
+ return 1
1139
+
1140
+ ws = _require_workspace(workspace_path)
1141
+ if ws is None:
1142
+ return 1
1143
+
1144
+ history_file = ws / ".persona-history"
1145
+ if not history_file.exists():
1146
+ print("No persona transitions recorded yet.")
1147
+ return 0
1148
+
1149
+ lines = history_file.read_text(encoding="utf-8").splitlines()
1150
+ recent = lines[-count:] if count else lines
1151
+ print(f"Recent persona transitions (last {len(recent)}):")
1152
+ print()
1153
+ for line in recent:
1154
+ print(f" {line}")
1155
+ return 0
1156
+
1157
+
1158
+ def cmd_personas(args: list[str]) -> int:
1159
+ """List available personas."""
1160
+ workspace_path: str | None = None
1161
+ i = 0
1162
+ while i < len(args):
1163
+ match args[i]:
1164
+ case "--workspace" if i + 1 < len(args):
1165
+ workspace_path = args[i + 1]
1166
+ i += 2
1167
+ case "--help" | "-h":
1168
+ print("Usage: agent-toolkit workspace personas [--workspace PATH]")
1169
+ return 0
1170
+ case _:
1171
+ print(f"Unknown option: {args[i]}", file=sys.stderr)
1172
+ return 1
1173
+
1174
+ ws = _require_workspace(workspace_path)
1175
+ if ws is None:
1176
+ return 1
1177
+
1178
+ personas_dir = ws / "personas"
1179
+ print(_blue("── Available Personas ─────────────────────────────────────"))
1180
+ if not personas_dir.is_dir():
1181
+ print(_dim(" (no personas directory)"))
1182
+ print()
1183
+ return 0
1184
+
1185
+ found = False
1186
+ for path in sorted(personas_dir.glob("*.md")):
1187
+ found = True
1188
+ name = path.stem
1189
+ meta = _parse_frontmatter_text(path.read_text(encoding="utf-8"))
1190
+ allow = meta.get("allow") or []
1191
+ deny = meta.get("deny") or []
1192
+ output_fmt = meta.get("output_format", "")
1193
+ allow_s = ", ".join(str(x) for x in allow) if allow else "-"
1194
+ deny_s = ", ".join(str(x) for x in deny) if deny else "-"
1195
+ fmt_s = output_fmt or "-"
1196
+ print(f" {name:20s} allow=[{allow_s}] deny=[{deny_s}] format={fmt_s}")
1197
+
1198
+ if not found:
1199
+ print(_dim(" (no personas defined)"))
1200
+ print()
1201
+ print("Usage: agent-toolkit workspace use-persona <name>")
1202
+ return 0
1203
+
1204
+
1205
+ def cmd_load(args: list[str]) -> int:
1206
+ """Load a context pack or composable profile."""
1207
+ workspace_path: str | None = None
1208
+ profile_name: str | None = None
1209
+ pack_arg: str | None = None
1210
+ i = 0
1211
+ while i < len(args):
1212
+ match args[i]:
1213
+ case "--workspace" if i + 1 < len(args):
1214
+ workspace_path = args[i + 1]
1215
+ i += 2
1216
+ case "--profile" if i + 1 < len(args):
1217
+ profile_name = args[i + 1]
1218
+ i += 2
1219
+ case "--help" | "-h":
1220
+ print("Usage: agent-toolkit workspace load <pack-path> | --profile <name>")
1221
+ return 0
1222
+ case arg if not arg.startswith("-"):
1223
+ pack_arg = arg
1224
+ i += 1
1225
+ case _:
1226
+ print(f"Unknown option: {args[i]}", file=sys.stderr)
1227
+ return 1
1228
+
1229
+ ws = _require_workspace(workspace_path)
1230
+ if ws is None:
1231
+ return 1
1232
+
1233
+ if profile_name:
1234
+ return _load_profile(ws, profile_name)
1235
+ if not pack_arg:
1236
+ print("Usage: agent-toolkit workspace load <pack-path> | --profile <name>", file=sys.stderr)
1237
+ return 1
1238
+ return _load_pack(ws, pack_arg)
1239
+
1240
+
1241
+ def _load_pack(ws: Path, pack_arg: str) -> int:
1242
+ pack_path = _resolve_pack_file(ws, pack_arg)
1243
+ if pack_path is None:
1244
+ print(f"Pack not found: {pack_arg}", file=sys.stderr)
1245
+ packs_dir = ws / "packs"
1246
+ if packs_dir.is_dir():
1247
+ available = sorted(
1248
+ str(p.relative_to(ws)) for p in packs_dir.rglob("*.yaml") if p.is_file()
1249
+ )
1250
+ if available:
1251
+ print("\nAvailable packs:", file=sys.stderr)
1252
+ for item in available:
1253
+ print(f" {item}", file=sys.stderr)
1254
+ return 1
1255
+
1256
+ rel = _pack_rel_path(ws, pack_path)
1257
+ _write(ws / ".active-pack", rel + "\n")
1258
+ data = _parse_yaml_file(pack_path)
1259
+ print(_green(f"Loaded pack: {rel}"))
1260
+ desc = data.get("description")
1261
+ if desc:
1262
+ print(f" {desc}")
1263
+ return 0
1264
+
1265
+
1266
+ def _load_profile(ws: Path, profile_name: str) -> int:
1267
+ profile_path = ws / "profiles" / f"{profile_name}.yaml"
1268
+ if not profile_path.exists():
1269
+ print(f"Profile not found: {profile_name}", file=sys.stderr)
1270
+ print(f"Looked in: {profile_path}", file=sys.stderr)
1271
+ return 1
1272
+
1273
+ data = _parse_yaml_file(profile_path)
1274
+ _write(ws / ".active-profile", profile_name + "\n")
1275
+ print(_green(f"Profile loaded: {profile_name}"))
1276
+ desc = data.get("description")
1277
+ if desc:
1278
+ print(f" {desc}")
1279
+
1280
+ pack_ref = data.get("pack")
1281
+ if pack_ref:
1282
+ pack_path = _resolve_pack_file(ws, str(pack_ref))
1283
+ if pack_path is None:
1284
+ print(f" (pack '{pack_ref}' not found — skipped)", file=sys.stderr)
1285
+ else:
1286
+ rel = _pack_rel_path(ws, pack_path)
1287
+ _write(ws / ".active-pack", rel + "\n")
1288
+ print(_green(f" Pack: {rel}"))
1289
+
1290
+ persona = data.get("persona")
1291
+ if persona:
1292
+ if not _persona_path(ws, str(persona)).exists():
1293
+ print(f" (persona '{persona}' not found — skipped)", file=sys.stderr)
1294
+ else:
1295
+ active_file = ws / ".active-persona"
1296
+ from_persona = (
1297
+ active_file.read_text(encoding="utf-8").strip() if active_file.exists() else ""
1298
+ )
1299
+ ts = _utc_timestamp()
1300
+ if from_persona and from_persona != persona:
1301
+ _append_persona_history(ws, f"{ts} profile: {from_persona} → {persona}")
1302
+ elif not from_persona:
1303
+ _append_persona_history(ws, f"{ts} profile: → {persona}")
1304
+ _write(active_file, str(persona) + "\n")
1305
+ print(_green(f" Persona: {persona}"))
1306
+
1307
+ skills = data.get("skills")
1308
+ if isinstance(skills, list) and skills:
1309
+ _write(ws / ".active-skills", "\n".join(str(s) for s in skills) + "\n")
1310
+ print(_green(f" Skills: {', '.join(str(s) for s in skills)}"))
1311
+
1312
+ loops = data.get("loops")
1313
+ if isinstance(loops, list) and loops:
1314
+ _write(ws / ".active-loops", "\n".join(str(ln) for ln in loops) + "\n")
1315
+ print(_green(f" Loops: {', '.join(str(ln) for ln in loops)}"))
1316
+
1317
+ return 0
1318
+
1319
+
1320
+ def cmd_profiles(args: list[str]) -> int:
1321
+ """List available profiles."""
1322
+ workspace_path: str | None = None
1323
+ i = 0
1324
+ while i < len(args):
1325
+ match args[i]:
1326
+ case "--workspace" if i + 1 < len(args):
1327
+ workspace_path = args[i + 1]
1328
+ i += 2
1329
+ case "--help" | "-h":
1330
+ print("Usage: agent-toolkit workspace profiles [--workspace PATH]")
1331
+ return 0
1332
+ case _:
1333
+ print(f"Unknown option: {args[i]}", file=sys.stderr)
1334
+ return 1
1335
+
1336
+ ws = _require_workspace(workspace_path)
1337
+ if ws is None:
1338
+ return 1
1339
+
1340
+ profiles_dir = ws / "profiles"
1341
+ print(_blue("── Available Profiles ─────────────────────────────────────"))
1342
+ if not profiles_dir.is_dir():
1343
+ print(_dim(" (no profiles/ directory)"))
1344
+ print()
1345
+ return 0
1346
+
1347
+ found = False
1348
+ for path in sorted(profiles_dir.glob("*.yaml")):
1349
+ found = True
1350
+ data = _parse_yaml_file(path)
1351
+ name = data.get("name") or path.stem
1352
+ pack = data.get("pack") or "-"
1353
+ persona = data.get("persona") or "-"
1354
+ desc = data.get("description") or ""
1355
+ skills = data.get("skills")
1356
+ loops = data.get("loops")
1357
+ print(f" {name:25s} pack={pack} persona={persona}")
1358
+ if isinstance(skills, list) and skills:
1359
+ print(_dim(f" skills: {', '.join(str(s) for s in skills)}"))
1360
+ if isinstance(loops, list) and loops:
1361
+ print(_dim(f" loops: {', '.join(str(ln) for ln in loops)}"))
1362
+ if desc:
1363
+ print(_dim(f" {desc}"))
1364
+
1365
+ if not found:
1366
+ print(_dim(" (no profiles defined)"))
1367
+ print()
1368
+ print("Usage: agent-toolkit workspace load --profile <name>")
1369
+ return 0
1370
+
1371
+
1372
+ def _validate_packs(ws: Path) -> list[str]:
1373
+ errors: list[str] = []
1374
+ packs_dir = ws / "packs"
1375
+ if not packs_dir.is_dir():
1376
+ return errors
1377
+ for path in sorted(packs_dir.rglob("*.yaml")):
1378
+ try:
1379
+ data = _parse_yaml_file(path)
1380
+ except Exception as exc:
1381
+ errors.append(f"{path.name}: invalid YAML ({exc})")
1382
+ continue
1383
+ if not isinstance(data, dict):
1384
+ errors.append(f"{path.name}: root must be a mapping")
1385
+ continue
1386
+ for field in ("name", "description"):
1387
+ if not data.get(field):
1388
+ errors.append(f"{path.name}: missing required field '{field}'")
1389
+ return errors
1390
+
1391
+
1392
+ def _validate_loops(ws: Path) -> list[str]:
1393
+ errors: list[str] = []
1394
+ loops_dir = ws / "loops"
1395
+ if not loops_dir.is_dir():
1396
+ return errors
1397
+ for loop_dir in sorted(loops_dir.iterdir()):
1398
+ if not loop_dir.is_dir():
1399
+ continue
1400
+ loop_md = loop_dir / "LOOP.md"
1401
+ if not loop_md.exists():
1402
+ continue
1403
+ meta = _parse_frontmatter_text(loop_md.read_text(encoding="utf-8"))
1404
+ if not meta:
1405
+ errors.append(f"{loop_dir.name}/LOOP.md: missing or invalid frontmatter")
1406
+ continue
1407
+ for field in ("name", "tier", "cadence", "request"):
1408
+ if not meta.get(field):
1409
+ errors.append(f"{loop_dir.name}/LOOP.md: missing required field '{field}'")
1410
+ return errors
1411
+
1412
+
1413
+ def _validate_personas(ws: Path) -> list[str]:
1414
+ errors: list[str] = []
1415
+ personas_dir = ws / "personas"
1416
+ if not personas_dir.is_dir():
1417
+ return errors
1418
+ for path in sorted(personas_dir.glob("*.md")):
1419
+ meta = _parse_frontmatter_text(path.read_text(encoding="utf-8"))
1420
+ if not meta:
1421
+ errors.append(f"{path.name}: missing or invalid YAML frontmatter")
1422
+ continue
1423
+ for field in ("allow", "deny"):
1424
+ val = meta.get(field)
1425
+ if val is not None and not isinstance(val, list):
1426
+ errors.append(f"{path.name}: '{field}' must be a list")
1427
+ return errors
1428
+
1429
+
1430
+ def _validate_profiles(ws: Path) -> list[str]:
1431
+ errors: list[str] = []
1432
+ profiles_dir = ws / "profiles"
1433
+ if not profiles_dir.is_dir():
1434
+ return errors
1435
+ for path in sorted(profiles_dir.glob("*.yaml")):
1436
+ try:
1437
+ data = _parse_yaml_file(path)
1438
+ except Exception as exc:
1439
+ errors.append(f"{path.name}: invalid YAML ({exc})")
1440
+ continue
1441
+ if not isinstance(data, dict):
1442
+ errors.append(f"{path.name}: root must be a mapping")
1443
+ continue
1444
+ if not data.get("name") and not path.stem:
1445
+ errors.append(f"{path.name}: missing required field 'name'")
1446
+ pack_ref = data.get("pack")
1447
+ if pack_ref and _resolve_pack_file(ws, str(pack_ref)) is None:
1448
+ errors.append(f"{path.name}: referenced pack '{pack_ref}' not found")
1449
+ persona = data.get("persona")
1450
+ if persona and not _persona_path(ws, str(persona)).exists():
1451
+ errors.append(f"{path.name}: referenced persona '{persona}' not found")
1452
+ skills = data.get("skills")
1453
+ if skills is not None:
1454
+ if not isinstance(skills, list):
1455
+ errors.append(f"{path.name}: 'skills' must be a list of strings")
1456
+ else:
1457
+ for idx, s in enumerate(skills):
1458
+ if not isinstance(s, str) or not s.strip():
1459
+ errors.append(f"{path.name}: skills[{idx}] must be a non-empty string")
1460
+ print(
1461
+ f" {_yellow('⚠')} {path.name}: profile key 'skills' is schema-supported but currently not applied by the toolkit loader.",
1462
+ file=sys.stderr,
1463
+ )
1464
+ loops = data.get("loops")
1465
+ if loops is not None:
1466
+ if not isinstance(loops, list):
1467
+ errors.append(f"{path.name}: 'loops' must be a list of strings")
1468
+ else:
1469
+ for idx, ln in enumerate(loops):
1470
+ if not isinstance(ln, str) or not ln.strip():
1471
+ errors.append(f"{path.name}: loops[{idx}] must be a non-empty string")
1472
+ print(
1473
+ f" {_yellow('⚠')} {path.name}: profile key 'loops' is schema-supported but currently not applied by the toolkit loader.",
1474
+ file=sys.stderr,
1475
+ )
1476
+
1477
+ allowed_keys = {"name", "description", "pack", "persona", "skills", "loops"}
1478
+ for k in data.keys():
1479
+ if k not in allowed_keys:
1480
+ errors.append(f"{path.name}: unknown profile key '{k}'")
1481
+ return errors
1482
+
1483
+
1484
+ def _validate_knowledge(ws: Path) -> list[str]:
1485
+ errors: list[str] = []
1486
+ knowledge = ws / "knowledge"
1487
+ if not knowledge.is_dir():
1488
+ errors.append("knowledge/: directory not found")
1489
+ return errors
1490
+ for sub in ("learnings", "todos", "processes"):
1491
+ if not (knowledge / sub).is_dir():
1492
+ errors.append(f"knowledge/{sub}/: required directory missing")
1493
+ return errors
1494
+
1495
+
1496
+ def _validate_jobs(ws: Path) -> list[str]:
1497
+ errors: list[str] = []
1498
+ jobs_dir = ws / "templates" / "jobs"
1499
+ if not jobs_dir.is_dir():
1500
+ return errors
1501
+ for path in sorted(jobs_dir.glob("*.yaml")):
1502
+ try:
1503
+ data = _parse_yaml_file(path)
1504
+ except Exception as exc:
1505
+ errors.append(f"{path.name}: invalid YAML ({exc})")
1506
+ continue
1507
+ if not isinstance(data, dict):
1508
+ errors.append(f"{path.name}: root must be a mapping")
1509
+ continue
1510
+ for field in ("name", "request"):
1511
+ if not data.get(field):
1512
+ errors.append(f"{path.name}: missing required field '{field}'")
1513
+ return errors
1514
+
1515
+
1516
+ _SURFACES = {
1517
+ "packs": _validate_packs,
1518
+ "loops": _validate_loops,
1519
+ "personas": _validate_personas,
1520
+ "profiles": _validate_profiles,
1521
+ "knowledge": _validate_knowledge,
1522
+ "jobs": _validate_jobs,
1523
+ }
1524
+
1525
+
1526
+ def cmd_validate(args: list[str]) -> int:
1527
+ """Validate workspace schema integrity."""
1528
+ workspace_path: str | None = None
1529
+ surface = "all"
1530
+ i = 0
1531
+ while i < len(args):
1532
+ match args[i]:
1533
+ case "--workspace" if i + 1 < len(args):
1534
+ workspace_path = args[i + 1]
1535
+ i += 2
1536
+ case "--help" | "-h":
1537
+ print("Usage: agent-toolkit workspace validate [surface] [--workspace PATH]")
1538
+ print("Surfaces: all, packs, loops, personas, profiles, knowledge, jobs")
1539
+ print(
1540
+ "Note: profile validation may warn about schema-supported keys that the Toolkit does not currently apply."
1541
+ )
1542
+ return 0
1543
+ case arg if not arg.startswith("-"):
1544
+ surface = arg
1545
+ i += 1
1546
+ case _:
1547
+ print(f"Unknown option: {args[i]}", file=sys.stderr)
1548
+ return 1
1549
+
1550
+ ws = _require_workspace(workspace_path)
1551
+ if ws is None:
1552
+ return 1
1553
+
1554
+ if surface != "all" and surface not in _SURFACES:
1555
+ print(f"Unknown surface: {surface}", file=sys.stderr)
1556
+ print(
1557
+ "Valid surfaces: all, packs, loops, personas, profiles, knowledge, jobs",
1558
+ file=sys.stderr,
1559
+ )
1560
+ return 1
1561
+
1562
+ print()
1563
+ print("Context Validation")
1564
+ print("------------------")
1565
+
1566
+ surfaces = list(_SURFACES.keys()) if surface == "all" else [surface]
1567
+ all_errors: list[str] = []
1568
+ for name in surfaces:
1569
+ print(_blue(f"Validating {name}/ ..."))
1570
+ errors = _SURFACES[name](ws)
1571
+ if errors:
1572
+ for err in errors:
1573
+ print(f" {_yellow('✗')} {err}", file=sys.stderr)
1574
+ all_errors.extend(errors)
1575
+ else:
1576
+ print(f" {_green('✓')} {name}/ OK")
1577
+
1578
+ print()
1579
+ if all_errors:
1580
+ print(f" {_yellow(str(len(all_errors)))} violation(s) found.", file=sys.stderr)
1581
+ return 1
1582
+ print(f" {_green('All context files valid.')}")
1583
+ print()
1584
+ return 0
1585
+
1586
+
1587
+ # ---------------------------------------------------------------------------
1588
+ # Entry point
1589
+ # ---------------------------------------------------------------------------
1590
+
1591
+
1592
+ def _cmd_budget(args: list[str]) -> int:
1593
+ """Analyze context-budget footprint for a pack, profile, or full workspace."""
1594
+ from agent_toolkit.cli.context_budget import analyze_workspace
1595
+
1596
+ pack_ref: str | None = None
1597
+ profile_ref: str | None = None
1598
+ json_out = False
1599
+ i = 0
1600
+ while i < len(args):
1601
+ match args[i]:
1602
+ case "--pack" if i + 1 < len(args):
1603
+ pack_ref = args[i + 1]
1604
+ i += 2
1605
+ case "--profile" if i + 1 < len(args):
1606
+ profile_ref = args[i + 1]
1607
+ i += 2
1608
+ case "--json":
1609
+ json_out = True
1610
+ i += 1
1611
+ case "--help" | "-h":
1612
+ print(
1613
+ "Usage: agent-toolkit workspace budget [--pack NAME] [--profile NAME] [--json]"
1614
+ )
1615
+ return 0
1616
+ case _:
1617
+ print(f"Unknown option: {args[i]}", file=sys.stderr)
1618
+ return 1
1619
+
1620
+ ws = _require_workspace()
1621
+ if ws is None:
1622
+ return 1
1623
+
1624
+ result = analyze_workspace(ws, pack_ref=pack_ref, profile_ref=profile_ref)
1625
+
1626
+ if json_out:
1627
+ import json
1628
+
1629
+ print(json.dumps(result.to_dict(), indent=2))
1630
+ return 0
1631
+
1632
+ print()
1633
+ print(_blue("Context Budget Analysis"))
1634
+ print(_blue("-----------------------"))
1635
+ print()
1636
+ print(f" Workspace : {result.workspace}")
1637
+ print(f" Target : {result.target}")
1638
+ print(f" Footprint : {result.total_chars:,} chars (~{result.total_tokens:,} tokens)")
1639
+ print(f" Risk : {_color_for_risk(result.risk)}")
1640
+ print()
1641
+
1642
+ if result.sections:
1643
+ print(_dim(" Breakdown:"))
1644
+ print()
1645
+ for s in result.sections:
1646
+ indent = " "
1647
+ print(f"{indent}{s.label:<40} {s.chars:>7,} chars ~{s.estimated_tokens:>6,} tokens")
1648
+ print()
1649
+
1650
+ if result.warnings:
1651
+ print(_yellow(" Warnings:"))
1652
+ for w in result.warnings:
1653
+ print(f" - {w}")
1654
+ print()
1655
+
1656
+ if result.suggestions:
1657
+ print(_cyan(" Suggestions:"))
1658
+ for s in result.suggestions:
1659
+ print(f" - {s}")
1660
+ print()
1661
+
1662
+ return 0
1663
+
1664
+
1665
+ def _color_for_risk(risk: str) -> str:
1666
+ if risk == "HIGH":
1667
+ return _c("1;31", risk)
1668
+ if risk == "MEDIUM":
1669
+ return _yellow(risk)
1670
+ return _green(risk)
1671
+
1672
+
1673
+ # ---------------------------------------------------------------------------
1674
+ # Entry point (continued)
1675
+ # ---------------------------------------------------------------------------
1676
+
1677
+
1678
+ def cmd_workspace(args: list[str]) -> int:
1679
+ """Router for workspace subcommands."""
1680
+ if not args or args[0] in ("-h", "--help", "help"):
1681
+ print(__doc__)
1682
+ return 0
1683
+
1684
+ sub = args[0]
1685
+ rest = args[1:]
1686
+
1687
+ match sub:
1688
+ case "init":
1689
+ return cmd_init(rest)
1690
+ case "context":
1691
+ return cmd_context(rest)
1692
+ case "sync":
1693
+ return cmd_sync(rest)
1694
+ case "use-persona":
1695
+ return cmd_use_persona(rest)
1696
+ case "handoff":
1697
+ return cmd_handoff(rest)
1698
+ case "history":
1699
+ return cmd_history(rest)
1700
+ case "personas":
1701
+ return cmd_personas(rest)
1702
+ case "load":
1703
+ return cmd_load(rest)
1704
+ case "profiles":
1705
+ return cmd_profiles(rest)
1706
+ case "validate":
1707
+ return cmd_validate(rest)
1708
+ case "budget":
1709
+ return _cmd_budget(rest)
1710
+ case _:
1711
+ print(f"Unknown workspace subcommand: {sub}", file=sys.stderr)
1712
+ print("Run 'agent-toolkit workspace --help' for usage.", file=sys.stderr)
1713
+ return 1