@pennixrv/trellis 0.7.2-beta.11 → 0.7.2-beta.16

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 (307) hide show
  1. package/dist/commands/init.d.ts.map +1 -1
  2. package/dist/commands/init.js +11 -13
  3. package/dist/commands/init.js.map +1 -1
  4. package/dist/commands/teamwork/batch-reservation.d.ts.map +1 -1
  5. package/dist/commands/teamwork/batch-reservation.js +16 -8
  6. package/dist/commands/teamwork/batch-reservation.js.map +1 -1
  7. package/dist/commands/teamwork/batch.d.ts +1 -0
  8. package/dist/commands/teamwork/batch.d.ts.map +1 -1
  9. package/dist/commands/teamwork/batch.js +112 -1
  10. package/dist/commands/teamwork/batch.js.map +1 -1
  11. package/dist/commands/teamwork/coordinator.d.ts +3 -0
  12. package/dist/commands/teamwork/coordinator.d.ts.map +1 -1
  13. package/dist/commands/teamwork/coordinator.js +21 -3
  14. package/dist/commands/teamwork/coordinator.js.map +1 -1
  15. package/dist/commands/teamwork/foreground-wait.d.ts +4 -1
  16. package/dist/commands/teamwork/foreground-wait.d.ts.map +1 -1
  17. package/dist/commands/teamwork/foreground-wait.js +8 -1
  18. package/dist/commands/teamwork/foreground-wait.js.map +1 -1
  19. package/dist/commands/teamwork/index.d.ts.map +1 -1
  20. package/dist/commands/teamwork/index.js +1 -0
  21. package/dist/commands/teamwork/index.js.map +1 -1
  22. package/dist/commands/update.d.ts.map +1 -1
  23. package/dist/commands/update.js +23 -10
  24. package/dist/commands/update.js.map +1 -1
  25. package/dist/commands/workflow.d.ts.map +1 -1
  26. package/dist/commands/workflow.js +5 -7
  27. package/dist/commands/workflow.js.map +1 -1
  28. package/dist/configurators/codebuddy.d.ts +1 -8
  29. package/dist/configurators/codebuddy.d.ts.map +1 -1
  30. package/dist/configurators/codebuddy.js +2 -12
  31. package/dist/configurators/codebuddy.js.map +1 -1
  32. package/dist/configurators/codex.d.ts +0 -36
  33. package/dist/configurators/codex.d.ts.map +1 -1
  34. package/dist/configurators/codex.js +2 -99
  35. package/dist/configurators/codex.js.map +1 -1
  36. package/dist/configurators/copilot.d.ts +1 -12
  37. package/dist/configurators/copilot.d.ts.map +1 -1
  38. package/dist/configurators/copilot.js +2 -20
  39. package/dist/configurators/copilot.js.map +1 -1
  40. package/dist/configurators/cursor.d.ts +1 -8
  41. package/dist/configurators/cursor.d.ts.map +1 -1
  42. package/dist/configurators/cursor.js +2 -12
  43. package/dist/configurators/cursor.js.map +1 -1
  44. package/dist/configurators/droid.d.ts +1 -8
  45. package/dist/configurators/droid.d.ts.map +1 -1
  46. package/dist/configurators/droid.js +2 -12
  47. package/dist/configurators/droid.js.map +1 -1
  48. package/dist/configurators/dsh.d.ts +1 -21
  49. package/dist/configurators/dsh.d.ts.map +1 -1
  50. package/dist/configurators/dsh.js +4 -37
  51. package/dist/configurators/dsh.js.map +1 -1
  52. package/dist/configurators/gemini.d.ts +1 -16
  53. package/dist/configurators/gemini.d.ts.map +1 -1
  54. package/dist/configurators/gemini.js +3 -21
  55. package/dist/configurators/gemini.js.map +1 -1
  56. package/dist/configurators/grok.d.ts +1 -12
  57. package/dist/configurators/grok.d.ts.map +1 -1
  58. package/dist/configurators/grok.js +2 -18
  59. package/dist/configurators/grok.js.map +1 -1
  60. package/dist/configurators/kimi.d.ts +1 -21
  61. package/dist/configurators/kimi.d.ts.map +1 -1
  62. package/dist/configurators/kimi.js +2 -38
  63. package/dist/configurators/kimi.js.map +1 -1
  64. package/dist/configurators/kiro.d.ts +1 -9
  65. package/dist/configurators/kiro.d.ts.map +1 -1
  66. package/dist/configurators/kiro.js +1 -9
  67. package/dist/configurators/kiro.js.map +1 -1
  68. package/dist/configurators/omp.d.ts.map +1 -1
  69. package/dist/configurators/omp.js +1 -5
  70. package/dist/configurators/omp.js.map +1 -1
  71. package/dist/configurators/pi.d.ts.map +1 -1
  72. package/dist/configurators/pi.js +2 -5
  73. package/dist/configurators/pi.js.map +1 -1
  74. package/dist/configurators/qoder.d.ts +1 -10
  75. package/dist/configurators/qoder.d.ts.map +1 -1
  76. package/dist/configurators/qoder.js +3 -15
  77. package/dist/configurators/qoder.js.map +1 -1
  78. package/dist/configurators/reasonix.d.ts +1 -12
  79. package/dist/configurators/reasonix.d.ts.map +1 -1
  80. package/dist/configurators/reasonix.js +3 -22
  81. package/dist/configurators/reasonix.js.map +1 -1
  82. package/dist/configurators/shared.d.ts +1 -24
  83. package/dist/configurators/shared.d.ts.map +1 -1
  84. package/dist/configurators/shared.js +5 -184
  85. package/dist/configurators/shared.js.map +1 -1
  86. package/dist/configurators/snow.d.ts +1 -20
  87. package/dist/configurators/snow.d.ts.map +1 -1
  88. package/dist/configurators/snow.js +2 -25
  89. package/dist/configurators/snow.js.map +1 -1
  90. package/dist/configurators/trae.d.ts +1 -14
  91. package/dist/configurators/trae.d.ts.map +1 -1
  92. package/dist/configurators/trae.js +3 -19
  93. package/dist/configurators/trae.js.map +1 -1
  94. package/dist/configurators/zcode.d.ts +1 -13
  95. package/dist/configurators/zcode.d.ts.map +1 -1
  96. package/dist/configurators/zcode.js +2 -18
  97. package/dist/configurators/zcode.js.map +1 -1
  98. package/dist/migrations/manifests/0.5.0-beta.5.json +1 -212
  99. package/dist/migrations/manifests/0.7.2-beta.11.json +9 -0
  100. package/dist/migrations/manifests/0.7.2-beta.12.json +9 -0
  101. package/dist/migrations/manifests/0.7.2-beta.13.json +9 -0
  102. package/dist/migrations/manifests/0.7.2-beta.14.json +9 -0
  103. package/dist/migrations/manifests/0.7.2-beta.15.json +9 -0
  104. package/dist/migrations/manifests/0.7.2-beta.16.json +9 -0
  105. package/dist/migrations/retired-native-paths.d.ts +109 -0
  106. package/dist/migrations/retired-native-paths.d.ts.map +1 -0
  107. package/dist/migrations/retired-native-paths.js +263 -0
  108. package/dist/migrations/retired-native-paths.js.map +1 -0
  109. package/dist/templates/claude/index.d.ts +1 -16
  110. package/dist/templates/claude/index.d.ts.map +1 -1
  111. package/dist/templates/claude/index.js +5 -32
  112. package/dist/templates/claude/index.js.map +1 -1
  113. package/dist/templates/claude/settings.json +0 -22
  114. package/dist/templates/codebuddy/index.d.ts +2 -3
  115. package/dist/templates/codebuddy/index.d.ts.map +1 -1
  116. package/dist/templates/codebuddy/index.js +2 -3
  117. package/dist/templates/codebuddy/index.js.map +1 -1
  118. package/dist/templates/codebuddy/settings.json +0 -10
  119. package/dist/templates/codex/config.toml +2 -19
  120. package/dist/templates/codex/hooks/session-start.py +1 -1
  121. package/dist/templates/codex/hooks.json +0 -12
  122. package/dist/templates/codex/index.d.ts +0 -5
  123. package/dist/templates/codex/index.d.ts.map +1 -1
  124. package/dist/templates/codex/index.js +0 -13
  125. package/dist/templates/codex/index.js.map +1 -1
  126. package/dist/templates/common/bundled-skills/trellis-meta/SKILL.md +7 -7
  127. package/dist/templates/common/bundled-skills/trellis-meta/references/customize-local/change-agents.md +9 -51
  128. package/dist/templates/common/bundled-skills/trellis-meta/references/customize-local/change-context-loading.md +3 -15
  129. package/dist/templates/common/bundled-skills/trellis-meta/references/customize-local/change-hooks.md +1 -2
  130. package/dist/templates/common/bundled-skills/trellis-meta/references/local-architecture/context-injection.md +4 -9
  131. package/dist/templates/common/bundled-skills/trellis-meta/references/local-architecture/generated-files.md +2 -2
  132. package/dist/templates/common/bundled-skills/trellis-meta/references/local-architecture/overview.md +1 -1
  133. package/dist/templates/common/bundled-skills/trellis-meta/references/local-architecture/spec-system.md +1 -1
  134. package/dist/templates/common/bundled-skills/trellis-meta/references/platform-files/agents.md +9 -79
  135. package/dist/templates/common/bundled-skills/trellis-meta/references/platform-files/hooks-and-settings.md +2 -4
  136. package/dist/templates/common/bundled-skills/trellis-meta/references/platform-files/overview.md +3 -6
  137. package/dist/templates/common/bundled-skills/trellis-meta/references/platform-files/platform-map.md +24 -103
  138. package/dist/templates/common/bundled-skills/trellis-meta/references/platform-files/skills-and-commands.md +1 -1
  139. package/dist/templates/common/bundled-skills/trellis-session-insight/SKILL.md +1 -1
  140. package/dist/templates/common/bundled-skills/trellis-teamwork/SKILL.md +1 -1
  141. package/dist/templates/common/bundled-skills/trellis-teamwork/references/teammate-processes.md +21 -1
  142. package/dist/templates/common/bundled-skills/trellis-teamwork/references/teamwork-plan-construction.md +7 -0
  143. package/dist/templates/copilot/hooks/session-start.py +1 -1
  144. package/dist/templates/cursor/hooks.json +0 -7
  145. package/dist/templates/cursor/index.d.ts +1 -11
  146. package/dist/templates/cursor/index.d.ts.map +1 -1
  147. package/dist/templates/cursor/index.js +2 -10
  148. package/dist/templates/cursor/index.js.map +1 -1
  149. package/dist/templates/droid/index.d.ts +2 -3
  150. package/dist/templates/droid/index.d.ts.map +1 -1
  151. package/dist/templates/droid/index.js +2 -3
  152. package/dist/templates/droid/index.js.map +1 -1
  153. package/dist/templates/droid/settings.json +0 -10
  154. package/dist/templates/dsh/DSH.md +2 -33
  155. package/dist/templates/dsh/index.d.ts +1 -19
  156. package/dist/templates/dsh/index.d.ts.map +1 -1
  157. package/dist/templates/dsh/index.js +2 -21
  158. package/dist/templates/dsh/index.js.map +1 -1
  159. package/dist/templates/gemini/index.d.ts +1 -11
  160. package/dist/templates/gemini/index.d.ts.map +1 -1
  161. package/dist/templates/gemini/index.js +2 -10
  162. package/dist/templates/gemini/index.js.map +1 -1
  163. package/dist/templates/kiro/index.d.ts +1 -13
  164. package/dist/templates/kiro/index.d.ts.map +1 -1
  165. package/dist/templates/kiro/index.js +1 -13
  166. package/dist/templates/kiro/index.js.map +1 -1
  167. package/dist/templates/markdown/agents.md +6 -3
  168. package/dist/templates/omp/extensions/trellis/index.ts.txt +11 -51
  169. package/dist/templates/omp/index.d.ts +0 -2
  170. package/dist/templates/omp/index.d.ts.map +1 -1
  171. package/dist/templates/omp/index.js +1 -4
  172. package/dist/templates/omp/index.js.map +1 -1
  173. package/dist/templates/opencode/lib/trellis-context.js +12 -321
  174. package/dist/templates/opencode/plugins/inject-shell-session-context.js +93 -0
  175. package/dist/templates/opencode/plugins/inject-workflow-state.js +4 -10
  176. package/dist/templates/opencode/plugins/session-start.js +2 -6
  177. package/dist/templates/pi/extensions/trellis/index.ts.txt +8 -1432
  178. package/dist/templates/pi/index.d.ts +1 -2
  179. package/dist/templates/pi/index.d.ts.map +1 -1
  180. package/dist/templates/pi/index.js +2 -5
  181. package/dist/templates/pi/index.js.map +1 -1
  182. package/dist/templates/qoder/index.d.ts +2 -3
  183. package/dist/templates/qoder/index.d.ts.map +1 -1
  184. package/dist/templates/qoder/index.js +2 -3
  185. package/dist/templates/qoder/index.js.map +1 -1
  186. package/dist/templates/shared-hooks/guard-teamwork-wait.py +110 -12
  187. package/dist/templates/shared-hooks/index.d.ts +2 -56
  188. package/dist/templates/shared-hooks/index.d.ts.map +1 -1
  189. package/dist/templates/shared-hooks/index.js +3 -70
  190. package/dist/templates/shared-hooks/index.js.map +1 -1
  191. package/dist/templates/shared-hooks/inject-spec-context.py +6 -35
  192. package/dist/templates/shared-hooks/inject-workflow-state.py +3 -77
  193. package/dist/templates/shared-hooks/session-start.py +1 -1
  194. package/dist/templates/snow/SNOW.md +6 -18
  195. package/dist/templates/snow/hooks/write-trellis-context.py +51 -133
  196. package/dist/templates/snow/index.d.ts +2 -21
  197. package/dist/templates/snow/index.d.ts.map +1 -1
  198. package/dist/templates/snow/index.js +3 -24
  199. package/dist/templates/snow/index.js.map +1 -1
  200. package/dist/templates/template-utils.d.ts +1 -2
  201. package/dist/templates/template-utils.d.ts.map +1 -1
  202. package/dist/templates/template-utils.js +1 -11
  203. package/dist/templates/template-utils.js.map +1 -1
  204. package/dist/templates/trae/index.d.ts +2 -3
  205. package/dist/templates/trae/index.d.ts.map +1 -1
  206. package/dist/templates/trae/index.js +2 -3
  207. package/dist/templates/trae/index.js.map +1 -1
  208. package/dist/templates/trellis/config.yaml +7 -36
  209. package/dist/templates/trellis/scripts/common/config.py +1 -36
  210. package/dist/templates/trellis/scripts/common/git_context.py +3 -4
  211. package/dist/templates/trellis/scripts/common/task_context.py +3 -3
  212. package/dist/templates/trellis/scripts/common/task_store.py +1 -77
  213. package/dist/templates/trellis/scripts/common/workflow_phase.py +3 -36
  214. package/dist/templates/trellis/scripts/common/workflow_selection.py +12 -2
  215. package/dist/templates/trellis/scripts/task.py +2 -2
  216. package/dist/templates/trellis/workflow.md +1 -7
  217. package/dist/templates/zcode/config.json +0 -10
  218. package/dist/templates/zcode/index.d.ts +3 -22
  219. package/dist/templates/zcode/index.d.ts.map +1 -1
  220. package/dist/templates/zcode/index.js +3 -24
  221. package/dist/templates/zcode/index.js.map +1 -1
  222. package/dist/types/ai-tools.d.ts +0 -4
  223. package/dist/types/ai-tools.d.ts.map +1 -1
  224. package/dist/types/ai-tools.js +4 -109
  225. package/dist/types/ai-tools.js.map +1 -1
  226. package/dist/utils/ablation-store.d.ts.map +1 -1
  227. package/dist/utils/ablation-store.js +24 -0
  228. package/dist/utils/ablation-store.js.map +1 -1
  229. package/dist/utils/asset-backup.d.ts.map +1 -1
  230. package/dist/utils/asset-backup.js +3 -0
  231. package/dist/utils/asset-backup.js.map +1 -1
  232. package/dist/utils/retired-native-assets.d.ts +16 -0
  233. package/dist/utils/retired-native-assets.d.ts.map +1 -0
  234. package/dist/utils/retired-native-assets.js +234 -0
  235. package/dist/utils/retired-native-assets.js.map +1 -0
  236. package/dist/utils/uninstall-scrubbers.d.ts.map +1 -1
  237. package/dist/utils/uninstall-scrubbers.js +1 -1
  238. package/dist/utils/uninstall-scrubbers.js.map +1 -1
  239. package/package.json +2 -2
  240. package/dist/templates/claude/agents/trellis-check.md +0 -115
  241. package/dist/templates/claude/agents/trellis-implement.md +0 -110
  242. package/dist/templates/claude/agents/trellis-research.md +0 -137
  243. package/dist/templates/codebuddy/agents/trellis-check.md +0 -115
  244. package/dist/templates/codebuddy/agents/trellis-implement.md +0 -110
  245. package/dist/templates/codebuddy/agents/trellis-research.md +0 -137
  246. package/dist/templates/codex/agents/trellis-check.toml +0 -56
  247. package/dist/templates/codex/agents/trellis-implement.toml +0 -37
  248. package/dist/templates/codex/agents/trellis-research.toml +0 -78
  249. package/dist/templates/cursor/agents/trellis-check.md +0 -114
  250. package/dist/templates/cursor/agents/trellis-implement.md +0 -109
  251. package/dist/templates/cursor/agents/trellis-research.md +0 -136
  252. package/dist/templates/droid/droids/trellis-check.md +0 -107
  253. package/dist/templates/droid/droids/trellis-implement.md +0 -102
  254. package/dist/templates/droid/droids/trellis-research.md +0 -137
  255. package/dist/templates/dsh/agents/trellis-check.md +0 -99
  256. package/dist/templates/dsh/agents/trellis-implement.md +0 -106
  257. package/dist/templates/dsh/agents/trellis-research.md +0 -134
  258. package/dist/templates/gemini/agents/trellis-check.md +0 -107
  259. package/dist/templates/gemini/agents/trellis-implement.md +0 -102
  260. package/dist/templates/gemini/agents/trellis-research.md +0 -136
  261. package/dist/templates/grok/agents/trellis-check.md +0 -105
  262. package/dist/templates/grok/agents/trellis-implement.md +0 -116
  263. package/dist/templates/grok/agents/trellis-research.md +0 -146
  264. package/dist/templates/grok/index.d.ts +0 -16
  265. package/dist/templates/grok/index.d.ts.map +0 -1
  266. package/dist/templates/grok/index.js +0 -19
  267. package/dist/templates/grok/index.js.map +0 -1
  268. package/dist/templates/kimi/agents/trellis-check.md +0 -103
  269. package/dist/templates/kimi/agents/trellis-implement.md +0 -115
  270. package/dist/templates/kimi/agents/trellis-research.md +0 -144
  271. package/dist/templates/kimi/index.d.ts +0 -20
  272. package/dist/templates/kimi/index.d.ts.map +0 -1
  273. package/dist/templates/kimi/index.js +0 -23
  274. package/dist/templates/kimi/index.js.map +0 -1
  275. package/dist/templates/kiro/agents/trellis-check.json +0 -26
  276. package/dist/templates/kiro/agents/trellis-implement.json +0 -26
  277. package/dist/templates/kiro/agents/trellis-research.json +0 -30
  278. package/dist/templates/omp/agents/trellis-check.md +0 -41
  279. package/dist/templates/omp/agents/trellis-implement.md +0 -45
  280. package/dist/templates/omp/agents/trellis-research.md +0 -30
  281. package/dist/templates/opencode/agents/trellis-check.md +0 -122
  282. package/dist/templates/opencode/agents/trellis-implement.md +0 -118
  283. package/dist/templates/opencode/agents/trellis-research.md +0 -145
  284. package/dist/templates/opencode/plugins/inject-subagent-context.js +0 -569
  285. package/dist/templates/pi/agents/trellis-check.md +0 -37
  286. package/dist/templates/pi/agents/trellis-implement.md +0 -42
  287. package/dist/templates/pi/agents/trellis-research.md +0 -25
  288. package/dist/templates/qoder/agents/trellis-check.md +0 -108
  289. package/dist/templates/qoder/agents/trellis-implement.md +0 -103
  290. package/dist/templates/qoder/agents/trellis-research.md +0 -137
  291. package/dist/templates/reasonix/agents/trellis-check.md +0 -36
  292. package/dist/templates/reasonix/agents/trellis-implement.md +0 -41
  293. package/dist/templates/reasonix/index.d.ts +0 -13
  294. package/dist/templates/reasonix/index.d.ts.map +0 -1
  295. package/dist/templates/reasonix/index.js +0 -16
  296. package/dist/templates/reasonix/index.js.map +0 -1
  297. package/dist/templates/shared-hooks/inject-subagent-context.py +0 -1217
  298. package/dist/templates/snow/agents/trellis-check.md +0 -135
  299. package/dist/templates/snow/agents/trellis-implement.md +0 -153
  300. package/dist/templates/snow/agents/trellis-research.md +0 -114
  301. package/dist/templates/snow/hooks/beforeSubAgentStart.json +0 -15
  302. package/dist/templates/trae/agents/trellis-check.md +0 -108
  303. package/dist/templates/trae/agents/trellis-implement.md +0 -103
  304. package/dist/templates/trae/agents/trellis-research.md +0 -137
  305. package/dist/templates/zcode/agents/trellis-check.md +0 -109
  306. package/dist/templates/zcode/agents/trellis-implement.md +0 -111
  307. package/dist/templates/zcode/agents/trellis-research.md +0 -133
@@ -1,1217 +0,0 @@
1
- #!/usr/bin/env python3
2
- # -*- coding: utf-8 -*-
3
- """
4
- Multi-Platform Sub-Agent Context Injection Hook
5
-
6
- Injects task-specific context when sub-agents (implement, check, research) are spawned.
7
-
8
- Core Design Philosophy:
9
- - Hook is responsible for injecting all context, subagent works autonomously with complete info
10
- - Each agent has a dedicated jsonl file defining its context
11
- - No resume needed, no segmentation, behavior controlled by code not prompt
12
-
13
- Trigger: PreToolUse (before Task tool call)
14
-
15
- Context Source: Trellis active task resolver points to task directory
16
- - implement.jsonl - Implement agent dedicated context
17
- - check.jsonl - Check agent dedicated context
18
- - prd.md - Requirements document
19
- - design.md - Technical design for complex tasks
20
- - implement.md - Execution plan for complex tasks
21
- - codex-review-output.txt - Code Review results
22
- """
23
- from __future__ import annotations
24
-
25
- # IMPORTANT: Suppress all warnings FIRST
26
- import warnings
27
- warnings.filterwarnings("ignore")
28
-
29
- import json
30
- import os
31
- import sys
32
- from pathlib import Path
33
- from typing import Any
34
-
35
- # Hook hosts send UTF-8 JSON regardless of the process locale.
36
- _stdin_reconfigure = getattr(sys.stdin, "reconfigure", None)
37
- if callable(_stdin_reconfigure):
38
- try:
39
- _stdin_reconfigure(encoding="utf-8", errors="replace")
40
- except (OSError, ValueError):
41
- pass
42
-
43
- # IMPORTANT: Force stdout to use UTF-8 on Windows
44
- # This fixes UnicodeEncodeError when outputting non-ASCII characters
45
- if sys.platform.startswith("win"):
46
- import io as _io
47
- if hasattr(sys.stdout, "reconfigure"):
48
- sys.stdout.reconfigure(encoding="utf-8", errors="replace") # type: ignore[union-attr]
49
- elif hasattr(sys.stdout, "detach"):
50
- sys.stdout = _io.TextIOWrapper(sys.stdout.detach(), encoding="utf-8", errors="replace") # type: ignore[union-attr]
51
-
52
-
53
- # =============================================================================
54
- # Path Constants (change here to rename directories)
55
- # =============================================================================
56
-
57
- DIR_WORKFLOW = ".trellis"
58
- DIR_SPEC = "spec"
59
- FILE_TASK_JSON = "task.json"
60
-
61
- # =============================================================================
62
- # Subagent Constants (change here to rename subagent types)
63
- # =============================================================================
64
-
65
- AGENT_IMPLEMENT = "trellis-implement"
66
- AGENT_CHECK = "trellis-check"
67
- AGENT_RESEARCH = "trellis-research"
68
-
69
- # Agents that require a task directory
70
- AGENTS_REQUIRE_TASK = (AGENT_IMPLEMENT, AGENT_CHECK)
71
- # All supported agents
72
- AGENTS_ALL = (AGENT_IMPLEMENT, AGENT_CHECK, AGENT_RESEARCH)
73
-
74
-
75
- def find_repo_root(start_path: str) -> str | None:
76
- """
77
- Find git repo root from start_path upwards
78
-
79
- Returns:
80
- Repo root path, or None if not found
81
- """
82
- current = Path(start_path).resolve()
83
- while current != current.parent:
84
- if (current / ".git").exists():
85
- return str(current)
86
- current = current.parent
87
- return None
88
-
89
-
90
- def _detect_platform(input_data: dict) -> str | None:
91
- if _hook_event_name(input_data) == "SubagentStart":
92
- return "codex"
93
- if isinstance(input_data.get("cursor_version"), str):
94
- return "cursor"
95
- # CLAUDE_PROJECT_DIR is a compatibility alias that several hosts set
96
- # alongside their own variable — CodeBuddy, ZCode and Trae all do. It must
97
- # therefore be checked LAST, or every one of them is detected as claude and
98
- # the context key becomes `claude_<their-session-id>`. That key does not
99
- # match the session file `task.py start` wrote under the host's real name,
100
- # so the sub-agent starts with no task context while the pointer exists on
101
- # disk. Same fix as inject-workflow-state.py and session-start.py; this
102
- # third copy was missed when those two were corrected.
103
- env_map = {
104
- "ZCODE_PROJECT_DIR": "zcode",
105
- "CURSOR_PROJECT_DIR": "cursor",
106
- "CODEBUDDY_PROJECT_DIR": "codebuddy",
107
- "FACTORY_PROJECT_DIR": "droid",
108
- "GEMINI_PROJECT_DIR": "gemini",
109
- "QODER_PROJECT_DIR": "qoder",
110
- "KIRO_PROJECT_DIR": "kiro",
111
- "COPILOT_PROJECT_DIR": "copilot",
112
- "TRAE_PROJECT_DIR": "trae",
113
- # Last: the shared alias, only meaningful once no vendor key matched.
114
- "CLAUDE_PROJECT_DIR": "claude",
115
- }
116
- for env_name, platform in env_map.items():
117
- if os.environ.get(env_name):
118
- return platform
119
- script_parts = set(Path(sys.argv[0]).parts)
120
- if ".claude" in script_parts:
121
- return "claude"
122
- if ".cursor" in script_parts:
123
- return "cursor"
124
- if ".gemini" in script_parts:
125
- return "gemini"
126
- if ".qoder" in script_parts:
127
- return "qoder"
128
- if ".codebuddy" in script_parts:
129
- return "codebuddy"
130
- if ".factory" in script_parts:
131
- return "droid"
132
- if ".kiro" in script_parts:
133
- return "kiro"
134
- if ".zcode" in script_parts:
135
- return "zcode"
136
- return None
137
-
138
-
139
- def get_current_task(
140
- repo_root: str,
141
- input_data: dict,
142
- *,
143
- platform: str | None = None,
144
- allow_single_session_fallback: bool = True,
145
- allow_environment_context: bool = True,
146
- require_existing: bool = False,
147
- ) -> str | None:
148
- """Resolve current task directory through the unified active task resolver."""
149
- scripts_dir = Path(repo_root) / DIR_WORKFLOW / "scripts"
150
- if str(scripts_dir) not in sys.path:
151
- sys.path.insert(0, str(scripts_dir))
152
- try:
153
- from common.active_task import resolve_active_task # type: ignore[import-not-found]
154
- except Exception:
155
- return None
156
-
157
- active = resolve_active_task(
158
- Path(repo_root),
159
- input_data,
160
- platform=platform or _detect_platform(input_data),
161
- allow_single_session_fallback=allow_single_session_fallback,
162
- allow_environment_context=allow_environment_context,
163
- )
164
- if require_existing and active.stale:
165
- return None
166
- return active.task_path
167
-
168
-
169
- # =============================================================================
170
- # Context Injection Limits (issue #441)
171
- #
172
- # Notice text and behavior mirrored byte-for-byte in the Pi TS extension
173
- # (templates/pi/extensions/trellis/index.ts.txt). Changing wording here
174
- # requires changing it there too.
175
- # =============================================================================
176
-
177
- DEFAULT_MAX_FILE_BYTES = 32768
178
- DEFAULT_MAX_ARTIFACT_BYTES = 65536
179
- DEFAULT_MAX_TOTAL_BYTES = 131072
180
-
181
- DEFAULT_LIMITS: dict[str, int] = {
182
- "max_file_bytes": DEFAULT_MAX_FILE_BYTES,
183
- "max_artifact_bytes": DEFAULT_MAX_ARTIFACT_BYTES,
184
- "max_total_bytes": DEFAULT_MAX_TOTAL_BYTES,
185
- }
186
-
187
-
188
- def _get_limits(repo_root: str) -> dict[str, int]:
189
- """Load context-injection byte limits from config.yaml, with safe fallback."""
190
- scripts_dir = Path(repo_root) / DIR_WORKFLOW / "scripts"
191
- if str(scripts_dir) not in sys.path:
192
- sys.path.insert(0, str(scripts_dir))
193
- try:
194
- from common.config import get_context_injection_limits # type: ignore[import-not-found]
195
-
196
- return get_context_injection_limits(Path(repo_root))
197
- except Exception:
198
- return dict(DEFAULT_LIMITS)
199
-
200
-
201
- def truncate_utf8(data: bytes, cap: int) -> bytes:
202
- """Truncate ``data`` to at most ``cap`` bytes without splitting a UTF-8
203
- multi-byte sequence.
204
-
205
- ``cap <= 0`` means "no limit" — returns ``data`` unchanged.
206
- """
207
- if cap <= 0 or len(data) <= cap:
208
- return data
209
-
210
- truncated = data[:cap]
211
- i = len(truncated)
212
- # Back off over continuation bytes (10xxxxxx) to find the lead byte.
213
- while i > 0 and (truncated[i - 1] & 0xC0) == 0x80:
214
- i -= 1
215
- if i == 0:
216
- return b""
217
-
218
- lead = truncated[i - 1]
219
- if lead & 0x80:
220
- if (lead & 0xE0) == 0xC0:
221
- seq_len = 2
222
- elif (lead & 0xF0) == 0xE0:
223
- seq_len = 3
224
- elif (lead & 0xF8) == 0xF0:
225
- seq_len = 4
226
- else:
227
- seq_len = 1
228
- # Cut before the lead byte when its full sequence didn't fit;
229
- # otherwise the trailing sequence is complete — keep it whole.
230
- if (i - 1) + seq_len > len(truncated):
231
- return truncated[: i - 1]
232
-
233
- return truncated
234
-
235
-
236
- class _Budget:
237
- """Tracks the running total of bytes emitted into the sub-agent context."""
238
-
239
- def __init__(self, max_total_bytes: int) -> None:
240
- self.max_total_bytes = max_total_bytes
241
- self.used = 0
242
-
243
- def has_room(self, size: int) -> bool:
244
- if self.max_total_bytes <= 0:
245
- return True
246
- return self.used + size <= self.max_total_bytes
247
-
248
- def add(self, size: int) -> None:
249
- self.used += size
250
-
251
-
252
- def _real_path_contained(base_real: str, target_real: str) -> bool:
253
- """Whether an already-realpath'd target sits under an already-realpath'd base.
254
-
255
- ValueError on Windows when the two sit on different drives; that is
256
- outside the base by definition, so it fails closed.
257
- """
258
- try:
259
- return os.path.commonpath([base_real, target_real]) == base_real
260
- except ValueError:
261
- return False
262
-
263
-
264
- def _read_file_bytes(base_path: str, file_path: str) -> bytes | None:
265
- """Read raw file bytes, return None if file doesn't exist."""
266
- full_path = os.path.join(base_path, file_path)
267
- try:
268
- root_real = os.path.realpath(base_path)
269
- # `.trellis` may itself be a symlink into a store outside the repo
270
- # (#567); its real location is a second legitimate containment base.
271
- workflow_real = os.path.realpath(os.path.join(base_path, ".trellis"))
272
- full_real = os.path.realpath(full_path)
273
- if not _real_path_contained(root_real, full_real) and not (
274
- _real_path_contained(workflow_real, full_real)
275
- ):
276
- return None
277
- except OSError:
278
- return None
279
- if os.path.exists(full_path) and os.path.isfile(full_path):
280
- try:
281
- with open(full_path, "rb") as f:
282
- return f.read()
283
- except Exception:
284
- return None
285
- return None
286
-
287
-
288
- def _truncate_notice(path: str, cap: int) -> str:
289
- return f"\n[Trellis: truncated at {cap} bytes — read {path} for the full content]"
290
-
291
-
292
- def _is_binary_content(data: bytes) -> bool:
293
- """Return True when raw bytes should not be decoded into model context."""
294
- if b"\x00" in data:
295
- return True
296
- try:
297
- data.decode("utf-8", errors="strict")
298
- except UnicodeDecodeError:
299
- return True
300
- return False
301
-
302
-
303
- def _binary_notice(path: str, size: int, reason: str) -> str:
304
- return (
305
- f"[Trellis: not inlined (binary file) — "
306
- f"{path} ({size} bytes): {reason}]"
307
- )
308
-
309
-
310
- def _index_notice(path: str, size: int, reason: str) -> str:
311
- return (
312
- f"[Trellis: not inlined (total context limit reached) — "
313
- f"{path} ({size} bytes): {reason}]"
314
- )
315
-
316
-
317
- def _budgeted_block(
318
- budget: _Budget,
319
- header: str,
320
- plain_path: str,
321
- content: str,
322
- reason: str,
323
- size_for_index: int,
324
- ) -> str:
325
- """Return an inlined ``=== header ===`` block, or degrade to an index
326
- notice once the total context budget is exhausted."""
327
- block = f"=== {header} ===\n{content}"
328
- block_bytes = len(block.encode("utf-8"))
329
- if not budget.has_room(block_bytes):
330
- notice = _index_notice(plain_path, size_for_index, reason)
331
- budget.add(len(notice.encode("utf-8")))
332
- return notice
333
- budget.add(block_bytes)
334
- return block
335
-
336
-
337
- def _materialize_file(
338
- base_path: str,
339
- file_path: str,
340
- reason: str,
341
- limits: dict[str, int],
342
- budget: _Budget,
343
- ) -> str | None:
344
- """Read a JSONL-referenced file, apply the per-file cap, then budget it."""
345
- data = _read_file_bytes(base_path, file_path)
346
- if data is None:
347
- return None
348
-
349
- size = len(data)
350
- if _is_binary_content(data):
351
- notice = _binary_notice(file_path, size, reason)
352
- budget.add(len(notice.encode("utf-8")))
353
- return notice
354
-
355
- cap = limits["max_file_bytes"]
356
- truncated_bytes = truncate_utf8(data, cap)
357
- content = truncated_bytes.decode("utf-8", errors="replace")
358
- if len(truncated_bytes) < size:
359
- content += _truncate_notice(file_path, cap)
360
-
361
- return _budgeted_block(budget, file_path, file_path, content, reason, size)
362
-
363
-
364
- def _materialize_directory(
365
- base_path: str,
366
- dir_path: str,
367
- reason: str,
368
- limits: dict[str, int],
369
- budget: _Budget,
370
- max_files: int = 20,
371
- ) -> list[str]:
372
- """Read all .md files in a directory, applying the same per-file and
373
- total caps as a single-file JSONL entry."""
374
- full_path = os.path.join(base_path, dir_path)
375
- if not os.path.exists(full_path) or not os.path.isdir(full_path):
376
- return []
377
-
378
- blocks: list[str] = []
379
- try:
380
- md_files = sorted(
381
- f
382
- for f in os.listdir(full_path)
383
- if f.endswith(".md") and os.path.isfile(os.path.join(full_path, f))
384
- )
385
- for filename in md_files[:max_files]:
386
- relative_path = os.path.join(dir_path, filename)
387
- block = _materialize_file(base_path, relative_path, reason, limits, budget)
388
- if block:
389
- blocks.append(block)
390
- except Exception:
391
- pass
392
-
393
- return blocks
394
-
395
-
396
- def read_jsonl_entries(base_path: str, jsonl_path: str) -> list[dict]:
397
- """
398
- Parse all file/directory entries referenced in a jsonl context file.
399
-
400
- Schema:
401
- {"file": "path/to/file.md", "reason": "..."}
402
- {"file": "path/to/dir/", "type": "directory", "reason": "..."}
403
- {"_example": "..."} # legacy placeholder — skipped (no `file` field)
404
-
405
- Rows without a ``file`` field (e.g. the placeholder line older Trellis
406
- versions wrote at ``task.py create`` time) are skipped silently. If the
407
- resulting entry list is empty, a stderr warning is emitted so the operator
408
- can debug missing context.
409
-
410
- Returns:
411
- [{"file": path, "type": "file" | "directory", "reason": reason}, ...]
412
- """
413
- full_path = os.path.join(base_path, jsonl_path)
414
- if not os.path.exists(full_path):
415
- print(
416
- f"[inject-subagent-context] WARN: {jsonl_path} not found — "
417
- f"sub-agent will receive only task artifacts",
418
- file=sys.stderr,
419
- )
420
- return []
421
-
422
- entries: list[dict] = []
423
- saw_real_entry = False
424
- try:
425
- with open(full_path, "r", encoding="utf-8") as f:
426
- for line in f:
427
- line = line.strip()
428
- if not line:
429
- continue
430
- try:
431
- item = json.loads(line)
432
- file_path = item.get("file") or item.get("path")
433
-
434
- if not file_path:
435
- # Seed / comment row — skip silently
436
- continue
437
-
438
- saw_real_entry = True
439
- entries.append(
440
- {
441
- "file": file_path,
442
- "type": item.get("type", "file"),
443
- "reason": item.get("reason") or "-",
444
- }
445
- )
446
- except json.JSONDecodeError:
447
- continue
448
- except Exception:
449
- pass
450
-
451
- if not saw_real_entry:
452
- print(
453
- f"[inject-subagent-context] WARN: {jsonl_path} has no curated "
454
- f"entries (only seed / empty) — sub-agent will receive only "
455
- f"task artifacts. See workflow.md planning artifact guidance.",
456
- file=sys.stderr,
457
- )
458
-
459
- return entries
460
-
461
-
462
- def _materialize_jsonl_entries(
463
- base_path: str, jsonl_path: str, limits: dict[str, int], budget: _Budget
464
- ) -> list[str]:
465
- """Materialize every entry in a jsonl context file into context blocks,
466
- applying per-file and total budget caps."""
467
- blocks: list[str] = []
468
- for entry in read_jsonl_entries(base_path, jsonl_path):
469
- if entry["type"] == "directory":
470
- blocks.extend(
471
- _materialize_directory(
472
- base_path, entry["file"], entry["reason"], limits, budget
473
- )
474
- )
475
- else:
476
- block = _materialize_file(
477
- base_path, entry["file"], entry["reason"], limits, budget
478
- )
479
- if block:
480
- blocks.append(block)
481
- return blocks
482
-
483
-
484
- def get_agent_context(
485
- repo_root: str,
486
- task_dir: str,
487
- agent_type: str,
488
- limits: dict[str, int],
489
- budget: _Budget,
490
- ) -> str:
491
- """
492
- Get context from {agent_type}.jsonl for the specified agent.
493
- Only reads implement.jsonl or check.jsonl (the two JSONL files the task system creates).
494
- """
495
- agent_jsonl = f"{task_dir}/{agent_type}.jsonl"
496
- blocks = _materialize_jsonl_entries(repo_root, agent_jsonl, limits, budget)
497
- if not blocks:
498
- # Zero curated context reaches the model silently otherwise — the
499
- # stderr WARN above never enters any session (#573). Put the fact in
500
- # the prompt itself so the sub-agent compensates instead of assuming
501
- # the spec context was complete.
502
- return (
503
- f"[Trellis] {agent_jsonl} has no curated entries, so no spec/research "
504
- "context was injected. Before working, read the guidelines relevant "
505
- "to the code you will touch under .trellis/spec/, and treat the task "
506
- "artifacts below as the only prepared context."
507
- )
508
- return "\n\n".join(blocks)
509
-
510
-
511
- def _materialize_artifact(
512
- base_path: str,
513
- file_path: str,
514
- header_label: str,
515
- reason: str,
516
- limits: dict[str, int],
517
- budget: _Budget,
518
- ) -> str | None:
519
- """Read a task artifact (prd/design/implement.md), apply the per-artifact
520
- cap, then budget it."""
521
- data = _read_file_bytes(base_path, file_path)
522
- if data is None:
523
- return None
524
-
525
- size = len(data)
526
- cap = limits["max_artifact_bytes"]
527
- truncated_bytes = truncate_utf8(data, cap)
528
- content = truncated_bytes.decode("utf-8", errors="replace")
529
- if len(truncated_bytes) < size:
530
- content += _truncate_notice(file_path, cap)
531
-
532
- return _budgeted_block(budget, header_label, file_path, content, reason, size)
533
-
534
-
535
- def get_implement_context(repo_root: str, task_dir: str) -> str:
536
- """
537
- Complete context for Implement Agent
538
-
539
- Read order:
540
- 1. All files in implement.jsonl (spec/research manifests)
541
- 2. prd.md (requirements)
542
- 3. design.md if present (technical design)
543
- 4. implement.md if present (execution plan)
544
- """
545
- limits = _get_limits(repo_root)
546
- budget = _Budget(limits["max_total_bytes"])
547
- context_parts = []
548
-
549
- # 1. Read implement.jsonl
550
- base_context = get_agent_context(repo_root, task_dir, "implement", limits, budget)
551
- if base_context:
552
- context_parts.append(base_context)
553
-
554
- # 2. Requirements document
555
- prd_block = _materialize_artifact(
556
- repo_root,
557
- f"{task_dir}/prd.md",
558
- f"{task_dir}/prd.md (Requirements)",
559
- "Requirements document",
560
- limits,
561
- budget,
562
- )
563
- if prd_block:
564
- context_parts.append(prd_block)
565
-
566
- # 3. Technical design for complex tasks
567
- design_block = _materialize_artifact(
568
- repo_root,
569
- f"{task_dir}/design.md",
570
- f"{task_dir}/design.md (Technical Design)",
571
- "Technical design document",
572
- limits,
573
- budget,
574
- )
575
- if design_block:
576
- context_parts.append(design_block)
577
-
578
- # 4. Execution plan for complex tasks
579
- implement_plan_block = _materialize_artifact(
580
- repo_root,
581
- f"{task_dir}/implement.md",
582
- f"{task_dir}/implement.md (Execution Plan)",
583
- "Execution plan document",
584
- limits,
585
- budget,
586
- )
587
- if implement_plan_block:
588
- context_parts.append(implement_plan_block)
589
-
590
- return "\n\n".join(context_parts)
591
-
592
-
593
- def get_check_context(repo_root: str, task_dir: str) -> str:
594
- """
595
- Context for Check Agent: check.jsonl + task artifacts.
596
- """
597
- limits = _get_limits(repo_root)
598
- budget = _Budget(limits["max_total_bytes"])
599
- context_parts = []
600
-
601
- base_context = get_agent_context(repo_root, task_dir, "check", limits, budget)
602
- if base_context:
603
- context_parts.append(base_context)
604
-
605
- prd_block = _materialize_artifact(
606
- repo_root,
607
- f"{task_dir}/prd.md",
608
- f"{task_dir}/prd.md (Requirements)",
609
- "Requirements document",
610
- limits,
611
- budget,
612
- )
613
- if prd_block:
614
- context_parts.append(prd_block)
615
-
616
- design_block = _materialize_artifact(
617
- repo_root,
618
- f"{task_dir}/design.md",
619
- f"{task_dir}/design.md (Technical Design)",
620
- "Technical design document",
621
- limits,
622
- budget,
623
- )
624
- if design_block:
625
- context_parts.append(design_block)
626
-
627
- implement_plan_block = _materialize_artifact(
628
- repo_root,
629
- f"{task_dir}/implement.md",
630
- f"{task_dir}/implement.md (Execution Plan)",
631
- "Execution plan document",
632
- limits,
633
- budget,
634
- )
635
- if implement_plan_block:
636
- context_parts.append(implement_plan_block)
637
-
638
- return "\n\n".join(context_parts)
639
-
640
-
641
- def get_finish_context(repo_root: str, task_dir: str) -> str:
642
- """
643
- Context for Finish phase: reuses check.jsonl + prd.md
644
- (Finish is a final check, same context source.)
645
- """
646
- return get_check_context(repo_root, task_dir)
647
-
648
-
649
-
650
- def build_implement_prompt(original_prompt: str, context: str) -> str:
651
- """Build complete prompt for Implement"""
652
- return f"""<!-- trellis-hook-injected -->
653
- # Implement Agent Task
654
-
655
- You are the Implement Agent in the Multi-Agent Pipeline.
656
-
657
- ## Your Context
658
-
659
- All the information you need has been prepared for you:
660
-
661
- {context}
662
-
663
- ---
664
-
665
- ## Your Task
666
-
667
- {original_prompt}
668
-
669
- ---
670
-
671
- ## Workflow
672
-
673
- 1. **Understand specs** - All dev specs are injected above, understand them
674
- 2. **Understand task artifacts** - Read requirements, technical design if present, and execution plan if present
675
- 3. **Implement feature** - Implement following specs and task artifacts
676
- 4. **Self-check** - Ensure code quality against check specs
677
-
678
- ## Important Constraints
679
-
680
- - Do NOT execute git commit, only code modifications
681
- - Follow all dev specs injected above
682
- - Report list of modified/created files when done"""
683
-
684
-
685
- def build_check_prompt(original_prompt: str, context: str) -> str:
686
- """Build complete prompt for Check"""
687
- return f"""<!-- trellis-hook-injected -->
688
- # Check Agent Task
689
-
690
- You are the Check Agent in the Multi-Agent Pipeline (code and cross-layer checker).
691
-
692
- ## Your Context
693
-
694
- All check specs and dev specs you need:
695
-
696
- {context}
697
-
698
- ---
699
-
700
- ## Your Task
701
-
702
- {original_prompt}
703
-
704
- ---
705
-
706
- ## Workflow
707
-
708
- 1. **Get changes** - Run `git diff --name-only` and `git diff` to get code changes
709
- 2. **Check against specs** - Check item by item against specs above
710
- 3. **Self-fix** - Fix issues directly, don't just report
711
- 4. **Run verification** - Run project's lint and typecheck commands
712
-
713
- ## Important Constraints
714
-
715
- - Fix issues yourself, don't just report
716
- - Must execute complete checklist in check specs
717
- - Pay special attention to impact radius analysis (L1-L5)"""
718
-
719
-
720
- def build_finish_prompt(original_prompt: str, context: str) -> str:
721
- """Build complete prompt for Finish (final check before PR)"""
722
- return f"""<!-- trellis-hook-injected -->
723
- # Finish Agent Task
724
-
725
- You are performing the final check before creating a PR.
726
-
727
- ## Your Context
728
-
729
- Finish checklist and requirements:
730
-
731
- {context}
732
-
733
- ---
734
-
735
- ## Your Task
736
-
737
- {original_prompt}
738
-
739
- ---
740
-
741
- ## Workflow
742
-
743
- 1. **Review changes** - Run `git diff --name-only` to see all changed files
744
- 2. **Verify task artifacts** - Check requirements in prd.md and, when present, design.md / implement.md
745
- 3. **Spec sync** - Analyze whether changes introduce new patterns, contracts, or conventions
746
- - If new pattern/convention found: read target spec file → update it → update index.md if needed
747
- - If infra/cross-layer change: follow the 7-section mandatory template from update-spec.md
748
- - If pure code fix with no new patterns: skip this step
749
- 4. **Run final checks** - Execute lint and typecheck
750
- 5. **Confirm ready** - Ensure code is ready for PR
751
-
752
- ## Important Constraints
753
-
754
- - You MAY update spec files when gaps are detected (use update-spec.md as guide)
755
- - MUST read the target spec file BEFORE editing (avoid duplicating existing content)
756
- - Do NOT update specs for trivial changes (typos, formatting, obvious fixes)
757
- - If critical CODE issues found, report them clearly (fix specs, not code)
758
- - Verify all acceptance criteria in prd.md are met
759
- - Verify design.md and implement.md constraints when those files are present"""
760
-
761
-
762
-
763
- def get_research_context(repo_root: str, task_dir: str | None) -> str:
764
- """
765
- Context for Research Agent — project structure overview for spec directories.
766
-
767
- `task_dir` kept for signature parity with get_implement_context / get_check_context
768
- so the dispatcher can call them uniformly.
769
- """
770
- _ = task_dir
771
- context_parts = []
772
-
773
- # 1. Project structure overview (dynamically discover spec directories)
774
- spec_path = f"{DIR_WORKFLOW}/{DIR_SPEC}"
775
- spec_root = Path(repo_root) / DIR_WORKFLOW / DIR_SPEC
776
-
777
- # Build spec tree dynamically
778
- tree_lines = [f"{spec_path}/"]
779
- if spec_root.is_dir():
780
- pkg_dirs = sorted(d for d in spec_root.iterdir() if d.is_dir())
781
- for i, pkg_dir in enumerate(pkg_dirs):
782
- is_last = i == len(pkg_dirs) - 1
783
- prefix = "└── " if is_last else "├── "
784
- layers = sorted(d.name for d in pkg_dir.iterdir() if d.is_dir())
785
- layer_info = f" ({', '.join(layers)})" if layers else ""
786
- tree_lines.append(f"{prefix}{pkg_dir.name}/{layer_info}")
787
-
788
- spec_tree = "\n".join(tree_lines)
789
-
790
- project_structure = f"""## Project Spec Directory Structure
791
-
792
- ```
793
- {spec_tree}
794
- ```
795
-
796
- To get structured package info, run: `python3 ./{DIR_WORKFLOW}/scripts/get_context.py --mode packages`
797
-
798
- ## Search Tips
799
-
800
- - Spec files: `{spec_path}/**/*.md`
801
- - Code search: Use Glob and Grep tools
802
- - Tech solutions: Use mcp__exa__web_search_exa or mcp__exa__get_code_context_exa"""
803
-
804
- context_parts.append(project_structure)
805
-
806
- return "\n\n".join(context_parts)
807
-
808
-
809
- def build_research_prompt(original_prompt: str, context: str) -> str:
810
- """Build complete prompt for Research"""
811
- return f"""# Research Agent Task
812
-
813
- You are the Research Agent in the Multi-Agent Pipeline (search researcher).
814
-
815
- ## Core Principle
816
-
817
- **You do one thing: find and explain information.**
818
-
819
- You are a documenter, not a reviewer.
820
-
821
- ## Project Info
822
-
823
- {context}
824
-
825
- ---
826
-
827
- ## Your Task
828
-
829
- {original_prompt}
830
-
831
- ---
832
-
833
- ## Workflow
834
-
835
- 1. **Understand query** - Determine search type (internal/external) and scope
836
- 2. **Plan search** - List search steps for complex queries
837
- 3. **Execute search** - Execute multiple independent searches in parallel
838
- 4. **Organize results** - Output structured report
839
-
840
- ## Search Tools
841
-
842
- | Tool | Purpose |
843
- |------|---------|
844
- | Glob | Search by filename pattern |
845
- | Grep | Search by content |
846
- | Read | Read file content |
847
- | mcp__exa__web_search_exa | External web search |
848
- | mcp__exa__get_code_context_exa | External code/doc search |
849
-
850
- ## Strict Boundaries
851
-
852
- **Only allowed**: Describe what exists, where it is, how it works
853
-
854
- **Forbidden** (unless explicitly asked):
855
- - Suggest improvements
856
- - Criticize implementation
857
- - Recommend refactoring
858
- - Modify any files
859
-
860
- ## Report Format
861
-
862
- Provide structured search results including:
863
- - List of files found (with paths)
864
- - Code pattern analysis (if applicable)
865
- - Related spec documents
866
- - External references (if any)"""
867
-
868
-
869
- def _string_value(value: Any) -> str:
870
- if isinstance(value, str):
871
- stripped = value.strip()
872
- return stripped
873
- return ""
874
-
875
-
876
- def _hook_event_name(input_data: dict) -> str:
877
- """Return a hook event name from the documented snake/camel-case fields."""
878
- return _string_value(
879
- input_data.get("hook_event_name") or input_data.get("hookEventName")
880
- )
881
-
882
-
883
- def _codex_subagent_type(input_data: dict) -> str:
884
- """Return a Trellis Codex agent type only for a native start event."""
885
- if _hook_event_name(input_data) != "SubagentStart":
886
- return ""
887
- agent_type = _string_value(
888
- input_data.get("agent_type") or input_data.get("agentType")
889
- )
890
- return agent_type if agent_type in AGENTS_ALL else ""
891
-
892
-
893
- def build_codex_subagent_context(
894
- subagent_type: str,
895
- task_dir: str,
896
- context: str,
897
- ) -> str:
898
- """Build developer context for a native, already-dispatched Codex role."""
899
- role = subagent_type.removeprefix("trellis-")
900
- return f"""<!-- trellis-hook-injected -->
901
- # Trellis Native {role.title()} Subagent
902
-
903
- You are the dispatched `{subagent_type}` role for this task. Perform that role
904
- directly; do not follow main-session dispatch or wait instructions, and do not
905
- spawn another Trellis subagent.
906
-
907
- Active task: {task_dir}
908
-
909
- ## Curated Context
910
-
911
- {context}"""
912
-
913
-
914
- def _handle_codex_subagent_start(input_data: dict) -> None:
915
- """Emit Codex developer context for a recognised native Trellis subagent.
916
-
917
- The event supplies the parent session id. Disabling the generic
918
- single-session fallback is essential here: native starts must never borrow
919
- a task from another Codex window when that parent id is absent or stale.
920
- """
921
- subagent_type = _codex_subagent_type(input_data)
922
- parent_session_id = _string_value(input_data.get("session_id"))
923
- if not subagent_type or not parent_session_id:
924
- return
925
-
926
- # Payload cwd first, then our own — some hosts (CodeBuddy IDE 4.10.4)
927
- # report "/" for every hook event. See inject-workflow-state.py.
928
- repo_root = None
929
- for candidate in (_string_value(input_data.get("cwd")), os.getcwd()):
930
- if not candidate:
931
- continue
932
- repo_root = find_repo_root(candidate)
933
- if repo_root:
934
- break
935
- if not repo_root:
936
- return
937
-
938
- task_dir = get_current_task(
939
- repo_root,
940
- {"session_id": parent_session_id},
941
- platform="codex",
942
- allow_single_session_fallback=False,
943
- allow_environment_context=False,
944
- require_existing=True,
945
- )
946
- if not task_dir:
947
- return
948
-
949
- if subagent_type in AGENTS_REQUIRE_TASK:
950
- task_dir_full = Path(repo_root) / task_dir
951
- if not task_dir_full.is_dir():
952
- return
953
-
954
- if subagent_type == AGENT_IMPLEMENT:
955
- context = get_implement_context(repo_root, task_dir)
956
- elif subagent_type == AGENT_CHECK:
957
- context = get_check_context(repo_root, task_dir)
958
- else:
959
- context = get_research_context(repo_root, task_dir)
960
-
961
- if not context:
962
- return
963
-
964
- output = {
965
- "hookSpecificOutput": {
966
- "hookEventName": "SubagentStart",
967
- "additionalContext": build_codex_subagent_context(
968
- subagent_type, task_dir, context
969
- ),
970
- }
971
- }
972
- print(json.dumps(output, ensure_ascii=False))
973
-
974
-
975
- def _extract_subagent_name(value: Any) -> str:
976
- """Extract a sub-agent name from common platform encodings.
977
-
978
- Cursor's native Task args encode custom sub-agents as a protobuf oneof,
979
- which can appear in hook JSON as either ``{"custom": {"name": "..."}}``
980
- or ``{"type": {"case": "custom", "value": {"name": "..."}}}``.
981
- """
982
- direct = _string_value(value)
983
- if direct:
984
- return direct
985
-
986
- if not isinstance(value, dict):
987
- return ""
988
-
989
- for key in ("name", "subagent_type_name", "subagentTypeName"):
990
- direct = _string_value(value.get(key))
991
- if direct:
992
- return direct
993
-
994
- custom = value.get("custom")
995
- if isinstance(custom, dict):
996
- custom_name = _string_value(custom.get("name"))
997
- if custom_name:
998
- return custom_name
999
-
1000
- oneof = value.get("type")
1001
- if isinstance(oneof, dict):
1002
- case_name = _string_value(oneof.get("case"))
1003
- if case_name == "custom":
1004
- nested_value = oneof.get("value")
1005
- if isinstance(nested_value, dict):
1006
- custom_name = _string_value(nested_value.get("name"))
1007
- if custom_name:
1008
- return custom_name
1009
- if case_name:
1010
- return case_name
1011
-
1012
- case_name = _string_value(value.get("case"))
1013
- if case_name == "custom":
1014
- nested_value = value.get("value")
1015
- if isinstance(nested_value, dict):
1016
- custom_name = _string_value(nested_value.get("name"))
1017
- if custom_name:
1018
- return custom_name
1019
- if case_name:
1020
- return case_name
1021
-
1022
- for agent_name in AGENTS_ALL:
1023
- if agent_name in value:
1024
- return agent_name
1025
-
1026
- return ""
1027
-
1028
-
1029
- def _extract_subagent_type(tool_input: dict) -> str:
1030
- for key in (
1031
- "subagent_type",
1032
- "subagentType",
1033
- "subagent_type_name",
1034
- "subagentTypeName",
1035
- "subagent_name",
1036
- "subagentName",
1037
- "agent_type",
1038
- "agentType",
1039
- "name",
1040
- ):
1041
- agent_name = _extract_subagent_name(tool_input.get(key))
1042
- if agent_name:
1043
- return agent_name
1044
- return ""
1045
-
1046
-
1047
- def _parse_hook_input(input_data: dict) -> tuple[str, str, dict]:
1048
- """Parse hook input across different platform formats.
1049
-
1050
- Returns (subagent_type, original_prompt, tool_input).
1051
- Handles:
1052
- - Claude Code / Qoder / Droid: tool_name=Task|Agent, tool_input.subagent_type
1053
- - CodeBuddy: tool_name=task (IDE) or Task (CLI), tool_input.subagent_name
1054
- - Cursor: tool_name=Task|Subagent, tool_input.subagent_type
1055
- - Copilot CLI: toolName=task (camelCase key, lowercase value)
1056
- - ZCode: toolName=Agent, toolInput/tool_input.subagent_type
1057
- - Gemini CLI: tool_name IS the agent name (BeforeTool matcher already filtered)
1058
- - Kiro: agentSpawn hook, agent_name field at top level
1059
- """
1060
- tool_input = input_data.get("tool_input", {})
1061
- if not isinstance(tool_input, dict):
1062
- tool_input = input_data.get("toolInput", {})
1063
- if not isinstance(tool_input, dict):
1064
- tool_input = {}
1065
-
1066
- # Standard format: Task/Agent tool with subagent_type
1067
- tool_name = input_data.get("tool_name", "") or input_data.get("toolName", "")
1068
- if tool_name.lower() in ("task", "agent", "subagent"):
1069
- return (
1070
- _extract_subagent_type(tool_input),
1071
- tool_input.get("prompt", ""),
1072
- tool_input,
1073
- )
1074
-
1075
- # Kiro: agentSpawn hook passes agent_name at top level
1076
- agent_name = input_data.get("agent_name", "")
1077
- if agent_name:
1078
- return agent_name, tool_input.get("prompt", input_data.get("prompt", "")), tool_input
1079
-
1080
- # Gemini CLI: BeforeTool where tool_name IS the agent name
1081
- # (matcher already ensured it's one of our agents)
1082
- if tool_name in AGENTS_ALL:
1083
- return tool_name, tool_input.get("prompt", ""), tool_input
1084
-
1085
- # Copilot CLI: toolName field (camelCase), value might be the agent name
1086
- tool_name_camel = input_data.get("toolName", "")
1087
- if tool_name_camel in AGENTS_ALL:
1088
- return tool_name_camel, input_data.get("toolArgs", ""), tool_input
1089
-
1090
- return "", "", tool_input
1091
-
1092
-
1093
- def main():
1094
- if os.environ.get("TRELLIS_HOOKS") == "0" or os.environ.get("TRELLIS_DISABLE_HOOKS") == "1":
1095
- sys.exit(0)
1096
-
1097
- try:
1098
- input_data = json.load(sys.stdin)
1099
- except json.JSONDecodeError:
1100
- sys.exit(0)
1101
- if not isinstance(input_data, dict):
1102
- sys.exit(0)
1103
-
1104
- if _hook_event_name(input_data) == "SubagentStart":
1105
- try:
1106
- _handle_codex_subagent_start(input_data)
1107
- except Exception:
1108
- # A native context hook must never prevent Codex from spawning the
1109
- # requested child when its runtime state is unavailable or stale.
1110
- pass
1111
- sys.exit(0)
1112
-
1113
- subagent_type, original_prompt, tool_input = _parse_hook_input(input_data)
1114
- cwd = input_data.get("cwd", os.getcwd())
1115
-
1116
- # Only handle subagent types we care about
1117
- if subagent_type not in AGENTS_ALL:
1118
- sys.exit(0)
1119
-
1120
- # Find repo root
1121
- repo_root = find_repo_root(cwd)
1122
- if not repo_root:
1123
- sys.exit(0)
1124
-
1125
- # Get current task directory (research doesn't require it)
1126
- task_dir = get_current_task(
1127
- repo_root,
1128
- input_data,
1129
- allow_single_session_fallback=True,
1130
- )
1131
-
1132
- # implement/check need task directory
1133
- if subagent_type in AGENTS_REQUIRE_TASK:
1134
- if not task_dir:
1135
- sys.exit(0)
1136
- # Contain the pointer before reading anything through it. `task.py` now
1137
- # refuses to store a ref that leaves the repo, but a session file
1138
- # written before that fix can still hold one, and `trellis update`
1139
- # does not rewrite session files — so a poisoned pointer outlives the
1140
- # upgrade that closed the writer. This is the last hop before the
1141
- # task's prd.md/design.md reach the model prompt, so it checks again.
1142
- try:
1143
- root_real = os.path.realpath(repo_root)
1144
- # `.trellis` may itself be a symlink into a store outside the
1145
- # repo (#567); its real location is a second legitimate base.
1146
- workflow_real = os.path.realpath(os.path.join(repo_root, ".trellis"))
1147
- task_dir_full = os.path.realpath(os.path.join(repo_root, task_dir))
1148
- if not _real_path_contained(root_real, task_dir_full) and not (
1149
- _real_path_contained(workflow_real, task_dir_full)
1150
- ):
1151
- sys.exit(0)
1152
- except OSError:
1153
- sys.exit(0)
1154
- if not os.path.exists(task_dir_full):
1155
- sys.exit(0)
1156
-
1157
- # Check for [finish] marker in prompt (check agent with finish context)
1158
- is_finish_phase = "[finish]" in original_prompt.lower()
1159
-
1160
- # Get context and build prompt based on subagent type
1161
- if subagent_type == AGENT_IMPLEMENT:
1162
- assert task_dir is not None # validated above
1163
- context = get_implement_context(repo_root, task_dir)
1164
- new_prompt = build_implement_prompt(original_prompt, context)
1165
- elif subagent_type == AGENT_CHECK:
1166
- assert task_dir is not None # validated above
1167
- if is_finish_phase:
1168
- # Finish phase: use finish context (lighter, focused on final verification)
1169
- context = get_finish_context(repo_root, task_dir)
1170
- new_prompt = build_finish_prompt(original_prompt, context)
1171
- else:
1172
- # Regular check phase: use check context (full specs for self-fix loop)
1173
- context = get_check_context(repo_root, task_dir)
1174
- new_prompt = build_check_prompt(original_prompt, context)
1175
- elif subagent_type == AGENT_RESEARCH:
1176
- # Research can work without task directory
1177
- context = get_research_context(repo_root, task_dir)
1178
- new_prompt = build_research_prompt(original_prompt, context)
1179
- else:
1180
- sys.exit(0)
1181
-
1182
- if not context:
1183
- sys.exit(0)
1184
-
1185
- # Return updated input. Most platforms ignore unrecognized fields, so we
1186
- # include multiple formats. ZCode is stricter; live probing confirmed the
1187
- # nested Claude-compatible shape below reaches the sub-agent prompt.
1188
- updated = {**tool_input, "prompt": new_prompt}
1189
- if _detect_platform(input_data) == "zcode":
1190
- output = {
1191
- "hookSpecificOutput": {
1192
- "hookEventName": "PreToolUse",
1193
- "permissionDecision": "allow",
1194
- "updatedInput": updated,
1195
- }
1196
- }
1197
- else:
1198
- output = {
1199
- # Claude Code / Qoder / CodeBuddy / Droid format
1200
- "hookSpecificOutput": {
1201
- "hookEventName": "PreToolUse",
1202
- "permissionDecision": "allow",
1203
- "updatedInput": updated,
1204
- },
1205
- # Cursor format
1206
- "permission": "allow",
1207
- "updated_input": updated,
1208
- # Gemini format
1209
- "updatedInput": updated,
1210
- }
1211
-
1212
- print(json.dumps(output, ensure_ascii=False))
1213
- sys.exit(0)
1214
-
1215
-
1216
- if __name__ == "__main__":
1217
- main()