mini-trellis 0.1.0

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 (186) hide show
  1. package/COPYRIGHT +20 -0
  2. package/LICENSE +235 -0
  3. package/README.md +66 -0
  4. package/bin/mini-trellis.js +3 -0
  5. package/dist/cli/index.d.ts +3 -0
  6. package/dist/cli/index.d.ts.map +1 -0
  7. package/dist/cli/index.js +153 -0
  8. package/dist/cli/index.js.map +1 -0
  9. package/dist/commands/init.d.ts +19 -0
  10. package/dist/commands/init.d.ts.map +1 -0
  11. package/dist/commands/init.js +401 -0
  12. package/dist/commands/init.js.map +1 -0
  13. package/dist/commands/mem.d.ts +30 -0
  14. package/dist/commands/mem.d.ts.map +1 -0
  15. package/dist/commands/mem.js +412 -0
  16. package/dist/commands/mem.js.map +1 -0
  17. package/dist/commands/migrate.d.ts +40 -0
  18. package/dist/commands/migrate.d.ts.map +1 -0
  19. package/dist/commands/migrate.js +272 -0
  20. package/dist/commands/migrate.js.map +1 -0
  21. package/dist/commands/uninstall.d.ts +11 -0
  22. package/dist/commands/uninstall.d.ts.map +1 -0
  23. package/dist/commands/uninstall.js +135 -0
  24. package/dist/commands/uninstall.js.map +1 -0
  25. package/dist/commands/upgrade.d.ts +28 -0
  26. package/dist/commands/upgrade.d.ts.map +1 -0
  27. package/dist/commands/upgrade.js +84 -0
  28. package/dist/commands/upgrade.js.map +1 -0
  29. package/dist/configurators/claude.d.ts +3 -0
  30. package/dist/configurators/claude.d.ts.map +1 -0
  31. package/dist/configurators/claude.js +62 -0
  32. package/dist/configurators/claude.js.map +1 -0
  33. package/dist/configurators/codex.d.ts +3 -0
  34. package/dist/configurators/codex.d.ts.map +1 -0
  35. package/dist/configurators/codex.js +21 -0
  36. package/dist/configurators/codex.js.map +1 -0
  37. package/dist/configurators/index.d.ts +24 -0
  38. package/dist/configurators/index.d.ts.map +1 -0
  39. package/dist/configurators/index.js +80 -0
  40. package/dist/configurators/index.js.map +1 -0
  41. package/dist/configurators/opencode.d.ts +2 -0
  42. package/dist/configurators/opencode.d.ts.map +1 -0
  43. package/dist/configurators/opencode.js +62 -0
  44. package/dist/configurators/opencode.js.map +1 -0
  45. package/dist/configurators/pi.d.ts +2 -0
  46. package/dist/configurators/pi.d.ts.map +1 -0
  47. package/dist/configurators/pi.js +18 -0
  48. package/dist/configurators/pi.js.map +1 -0
  49. package/dist/configurators/shared.d.ts +147 -0
  50. package/dist/configurators/shared.d.ts.map +1 -0
  51. package/dist/configurators/shared.js +377 -0
  52. package/dist/configurators/shared.js.map +1 -0
  53. package/dist/configurators/workflow.d.ts +15 -0
  54. package/dist/configurators/workflow.d.ts.map +1 -0
  55. package/dist/configurators/workflow.js +46 -0
  56. package/dist/configurators/workflow.js.map +1 -0
  57. package/dist/constants/paths.d.ts +74 -0
  58. package/dist/constants/paths.d.ts.map +1 -0
  59. package/dist/constants/paths.js +83 -0
  60. package/dist/constants/paths.js.map +1 -0
  61. package/dist/constants/version.d.ts +9 -0
  62. package/dist/constants/version.d.ts.map +1 -0
  63. package/dist/constants/version.js +15 -0
  64. package/dist/constants/version.js.map +1 -0
  65. package/dist/index.d.ts +9 -0
  66. package/dist/index.d.ts.map +1 -0
  67. package/dist/index.js +9 -0
  68. package/dist/index.js.map +1 -0
  69. package/dist/templates/claude/index.d.ts +11 -0
  70. package/dist/templates/claude/index.d.ts.map +1 -0
  71. package/dist/templates/claude/index.js +17 -0
  72. package/dist/templates/claude/index.js.map +1 -0
  73. package/dist/templates/claude/settings.json +40 -0
  74. package/dist/templates/codex/config.toml +39 -0
  75. package/dist/templates/codex/hooks.json +15 -0
  76. package/dist/templates/codex/index.d.ts +11 -0
  77. package/dist/templates/codex/index.d.ts.map +1 -0
  78. package/dist/templates/codex/index.js +22 -0
  79. package/dist/templates/codex/index.js.map +1 -0
  80. package/dist/templates/common/bundled-skills/mini-trellis-session-insight/SKILL.md +37 -0
  81. package/dist/templates/common/bundled-skills/mini-trellis-session-insight/references/cli-quick-reference.md +36 -0
  82. package/dist/templates/common/bundled-skills/mini-trellis-session-insight/references/triggering-patterns.md +93 -0
  83. package/dist/templates/common/commands/remember.md +22 -0
  84. package/dist/templates/common/index.d.ts +48 -0
  85. package/dist/templates/common/index.d.ts.map +1 -0
  86. package/dist/templates/common/index.js +104 -0
  87. package/dist/templates/common/index.js.map +1 -0
  88. package/dist/templates/common/skills/update-spec.md +16 -0
  89. package/dist/templates/extract.d.ts +40 -0
  90. package/dist/templates/extract.d.ts.map +1 -0
  91. package/dist/templates/extract.js +106 -0
  92. package/dist/templates/extract.js.map +1 -0
  93. package/dist/templates/markdown/agents.md +15 -0
  94. package/dist/templates/markdown/index.d.ts +10 -0
  95. package/dist/templates/markdown/index.d.ts.map +1 -0
  96. package/dist/templates/markdown/index.js +18 -0
  97. package/dist/templates/markdown/index.js.map +1 -0
  98. package/dist/templates/markdown/research-readme.md +9 -0
  99. package/dist/templates/markdown/spec/guides/index.md.txt +5 -0
  100. package/dist/templates/markdown/spec/guides/mini-memory.md.txt +30 -0
  101. package/dist/templates/markdown/workspace-index.md +23 -0
  102. package/dist/templates/opencode/lib/context-visibility.js +148 -0
  103. package/dist/templates/opencode/lib/session-utils.js +394 -0
  104. package/dist/templates/opencode/lib/trellis-context.js +627 -0
  105. package/dist/templates/opencode/package.json +5 -0
  106. package/dist/templates/opencode/plugins/session-start.js +65 -0
  107. package/dist/templates/pi/extensions/mini-trellis/index.ts.txt +170 -0
  108. package/dist/templates/pi/index.d.ts +4 -0
  109. package/dist/templates/pi/index.d.ts.map +1 -0
  110. package/dist/templates/pi/index.js +9 -0
  111. package/dist/templates/pi/index.js.map +1 -0
  112. package/dist/templates/pi/settings.json +9 -0
  113. package/dist/templates/shared-hooks/index.d.ts +13 -0
  114. package/dist/templates/shared-hooks/index.d.ts.map +1 -0
  115. package/dist/templates/shared-hooks/index.js +26 -0
  116. package/dist/templates/shared-hooks/index.js.map +1 -0
  117. package/dist/templates/shared-hooks/session-start.py +676 -0
  118. package/dist/templates/template-utils.d.ts +26 -0
  119. package/dist/templates/template-utils.d.ts.map +1 -0
  120. package/dist/templates/template-utils.js +64 -0
  121. package/dist/templates/template-utils.js.map +1 -0
  122. package/dist/templates/trellis/config.yaml +34 -0
  123. package/dist/templates/trellis/gitattributes.txt +9 -0
  124. package/dist/templates/trellis/gitignore.txt +32 -0
  125. package/dist/templates/trellis/index.d.ts +8 -0
  126. package/dist/templates/trellis/index.d.ts.map +1 -0
  127. package/dist/templates/trellis/index.js +16 -0
  128. package/dist/templates/trellis/index.js.map +1 -0
  129. package/dist/templates/trellis/scripts/__init__.py +5 -0
  130. package/dist/templates/trellis/scripts/add_session.py +1545 -0
  131. package/dist/templates/trellis/scripts/common/__init__.py +94 -0
  132. package/dist/templates/trellis/scripts/common/active_task.py +855 -0
  133. package/dist/templates/trellis/scripts/common/cli_adapter.py +950 -0
  134. package/dist/templates/trellis/scripts/common/config.py +482 -0
  135. package/dist/templates/trellis/scripts/common/developer.py +192 -0
  136. package/dist/templates/trellis/scripts/common/git.py +203 -0
  137. package/dist/templates/trellis/scripts/common/git_context.py +106 -0
  138. package/dist/templates/trellis/scripts/common/io.py +160 -0
  139. package/dist/templates/trellis/scripts/common/log.py +45 -0
  140. package/dist/templates/trellis/scripts/common/packages_context.py +238 -0
  141. package/dist/templates/trellis/scripts/common/paths.py +543 -0
  142. package/dist/templates/trellis/scripts/common/safe_commit.py +322 -0
  143. package/dist/templates/trellis/scripts/common/session_context.py +708 -0
  144. package/dist/templates/trellis/scripts/common/task_context.py +470 -0
  145. package/dist/templates/trellis/scripts/common/task_queue.py +188 -0
  146. package/dist/templates/trellis/scripts/common/task_store.py +1930 -0
  147. package/dist/templates/trellis/scripts/common/task_utils.py +498 -0
  148. package/dist/templates/trellis/scripts/common/tasks.py +122 -0
  149. package/dist/templates/trellis/scripts/common/trellis_config.py +239 -0
  150. package/dist/templates/trellis/scripts/common/types.py +110 -0
  151. package/dist/templates/trellis/scripts/common/workflow_phase.py +242 -0
  152. package/dist/templates/trellis/scripts/get_context.py +16 -0
  153. package/dist/templates/trellis/scripts/init_developer.py +51 -0
  154. package/dist/types/ai-tools.d.ts +30 -0
  155. package/dist/types/ai-tools.d.ts.map +1 -0
  156. package/dist/types/ai-tools.js +89 -0
  157. package/dist/types/ai-tools.js.map +1 -0
  158. package/dist/utils/atomic-write.d.ts +12 -0
  159. package/dist/utils/atomic-write.d.ts.map +1 -0
  160. package/dist/utils/atomic-write.js +30 -0
  161. package/dist/utils/atomic-write.js.map +1 -0
  162. package/dist/utils/cwd-guard.d.ts +38 -0
  163. package/dist/utils/cwd-guard.d.ts.map +1 -0
  164. package/dist/utils/cwd-guard.js +62 -0
  165. package/dist/utils/cwd-guard.js.map +1 -0
  166. package/dist/utils/file-writer.d.ts +36 -0
  167. package/dist/utils/file-writer.d.ts.map +1 -0
  168. package/dist/utils/file-writer.js +204 -0
  169. package/dist/utils/file-writer.js.map +1 -0
  170. package/dist/utils/managed-paths.d.ts +5 -0
  171. package/dist/utils/managed-paths.d.ts.map +1 -0
  172. package/dist/utils/managed-paths.js +51 -0
  173. package/dist/utils/managed-paths.js.map +1 -0
  174. package/dist/utils/managed-removal.d.ts +42 -0
  175. package/dist/utils/managed-removal.d.ts.map +1 -0
  176. package/dist/utils/managed-removal.js +223 -0
  177. package/dist/utils/managed-removal.js.map +1 -0
  178. package/dist/utils/posix.d.ts +13 -0
  179. package/dist/utils/posix.d.ts.map +1 -0
  180. package/dist/utils/posix.js +15 -0
  181. package/dist/utils/posix.js.map +1 -0
  182. package/dist/utils/uninstall-scrubbers.d.ts +66 -0
  183. package/dist/utils/uninstall-scrubbers.d.ts.map +1 -0
  184. package/dist/utils/uninstall-scrubbers.js +417 -0
  185. package/dist/utils/uninstall-scrubbers.js.map +1 -0
  186. package/package.json +80 -0
@@ -0,0 +1,676 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ Session Start Hook - Inject structured context
5
+ """
6
+ from __future__ import annotations
7
+
8
+ # IMPORTANT: Suppress all warnings FIRST
9
+ import warnings
10
+ warnings.filterwarnings("ignore")
11
+
12
+ import json
13
+ import os
14
+ import re
15
+ import shlex
16
+ import subprocess
17
+ import sys
18
+ from io import StringIO
19
+ from pathlib import Path
20
+
21
+
22
+ def _normalize_windows_shell_path(path_str: str) -> str:
23
+ """Normalize Unix-style shell paths to real Windows paths.
24
+
25
+ On Windows, shells like Git Bash / MSYS2 / Cygwin may report paths like
26
+ `/d/Users/...` or `/cygdrive/d/Users/...`. `Path.resolve()` will misinterpret
27
+ these as `D:/d/Users...` on drive D: (or similar), breaking repo root
28
+ detection.
29
+
30
+ This function is intentionally conservative: it only rewrites patterns that
31
+ unambiguously represent a drive letter mount.
32
+ """
33
+ if not isinstance(path_str, str) or not path_str:
34
+ return path_str
35
+
36
+ # Only relevant on Windows; keep other platforms untouched.
37
+ if not sys.platform.startswith("win"):
38
+ return path_str
39
+
40
+ p = path_str.strip()
41
+
42
+ # Already a Windows drive path (C:\... or C:/...)
43
+ if re.match(r"^[A-Za-z]:[\/]", p):
44
+ return p
45
+
46
+ # MSYS/Git-Bash style: /c/Users/... or /d/Work/...
47
+ m = re.match(r"^/([A-Za-z])/(.*)", p)
48
+ if m:
49
+ drive, rest = m.group(1).upper(), m.group(2)
50
+ rest = rest.replace('/', '\\')
51
+ return f"{drive}:\\{rest}"
52
+
53
+ # Cygwin style: /cygdrive/c/Users/...
54
+ m = re.match(r"^/cygdrive/([A-Za-z])/(.*)", p)
55
+ if m:
56
+ drive, rest = m.group(1).upper(), m.group(2)
57
+ rest = rest.replace('/', '\\')
58
+ return f"{drive}:\\{rest}"
59
+
60
+ # WSL mounted drive (sometimes leaked into env): /mnt/c/Users/...
61
+ m = re.match(r"^/mnt/([A-Za-z])/(.*)", p)
62
+ if m:
63
+ drive, rest = m.group(1).upper(), m.group(2)
64
+ rest = rest.replace('/', '\\')
65
+ return f"{drive}:\\{rest}"
66
+
67
+ return path_str
68
+
69
+
70
+ FIRST_REPLY_NOTICE = """<first-reply-notice>
71
+ On the first visible assistant reply in this session, briefly acknowledge that mini-trellis SessionStart context loaded.
72
+ Choose the acknowledgment language in this order:
73
+ 1. Use the language of the user's current request (the user message that triggered this reply).
74
+ 2. If that request has no clear natural language, use an explicitly established project communication language.
75
+ 3. If neither provides a language, output the language-neutral fallback exactly: `mini-trellis SessionStart ✓`.
76
+ Continue directly with the user's request after the acknowledgment.
77
+ The acknowledgment must not alter the language used for the remainder of the response.
78
+ This notice is one-shot: do not repeat it after the first visible assistant reply in this session.
79
+ </first-reply-notice>"""
80
+
81
+
82
+ # Force UTF-8 on stdin/stdout/stderr on Windows. Default codepage there is
83
+ # cp936 / cp1252 / etc. — non-ASCII content (Chinese task names, prd snippets)
84
+ # both in stdin (hook payload from host CLI) and stdout (our emitted blocks)
85
+ # raises UnicodeDecodeError / UnicodeEncodeError. Equivalent to `python -X utf8`
86
+ # but applied per-stream so we don't depend on host CLI's command wiring.
87
+ if sys.platform.startswith("win"):
88
+ import io as _io
89
+ for _stream_name in ("stdin", "stdout", "stderr"):
90
+ _stream = getattr(sys, _stream_name, None)
91
+ if _stream is None:
92
+ continue
93
+ if hasattr(_stream, "reconfigure"):
94
+ try:
95
+ _stream.reconfigure(encoding="utf-8", errors="replace") # type: ignore[union-attr]
96
+ except Exception:
97
+ pass # Optional Windows stream setup; keep hook startup non-fatal.
98
+ elif hasattr(_stream, "detach"):
99
+ try:
100
+ setattr(sys, _stream_name, _io.TextIOWrapper(_stream.detach(), encoding="utf-8", errors="replace"))
101
+ except Exception:
102
+ pass # Optional Windows stream setup; keep hook startup non-fatal.
103
+
104
+
105
+
106
+ def should_skip_injection() -> bool:
107
+ """Check if any platform's non-interactive flag is set, or if Trellis
108
+ hooks are explicitly disabled via TRELLIS_HOOKS=0 / TRELLIS_DISABLE_HOOKS=1.
109
+ """
110
+ if os.environ.get("TRELLIS_HOOKS") == "0":
111
+ return True
112
+ if os.environ.get("TRELLIS_DISABLE_HOOKS") == "1":
113
+ return True
114
+ non_interactive_vars = [
115
+ "CLAUDE_NON_INTERACTIVE",
116
+ "QODER_NON_INTERACTIVE",
117
+ "CODEBUDDY_NON_INTERACTIVE",
118
+ "FACTORY_NON_INTERACTIVE",
119
+ "CURSOR_NON_INTERACTIVE",
120
+ "GEMINI_NON_INTERACTIVE",
121
+ "KIRO_NON_INTERACTIVE",
122
+ "COPILOT_NON_INTERACTIVE",
123
+ "TRAE_NON_INTERACTIVE",
124
+ "ZCODE_NON_INTERACTIVE",
125
+ ]
126
+ return any(os.environ.get(var) == "1" for var in non_interactive_vars)
127
+
128
+
129
+ def read_file(path: Path, fallback: str = "") -> str:
130
+ try:
131
+ return path.read_text(encoding="utf-8")
132
+ except (FileNotFoundError, PermissionError):
133
+ return fallback
134
+
135
+
136
+ def _repo_relative(repo_root: Path, path: Path) -> str:
137
+ try:
138
+ return path.relative_to(repo_root).as_posix()
139
+ except ValueError:
140
+ return str(path)
141
+
142
+
143
+ def _run_git(repo_root: Path, args: list[str]) -> str:
144
+ try:
145
+ result = subprocess.run(
146
+ ["git", *args],
147
+ capture_output=True,
148
+ text=True,
149
+ encoding="utf-8",
150
+ errors="replace",
151
+ timeout=3,
152
+ cwd=str(repo_root),
153
+ )
154
+ except (subprocess.TimeoutExpired, FileNotFoundError, PermissionError):
155
+ return ""
156
+ if result.returncode != 0:
157
+ return ""
158
+ return result.stdout.strip()
159
+
160
+
161
+ def _format_git_state(repo_root: Path) -> str:
162
+ branch = _run_git(repo_root, ["branch", "--show-current"]) or "(detached)"
163
+ dirty_lines = [
164
+ line for line in _run_git(repo_root, ["status", "--porcelain"]).splitlines()
165
+ if line.strip()
166
+ ]
167
+ dirty_text = "clean" if not dirty_lines else f"dirty {len(dirty_lines)} paths"
168
+ return f"Git: branch {branch}; {dirty_text}."
169
+
170
+
171
+ def _detect_platform(input_data: dict) -> str | None:
172
+ if isinstance(input_data.get("cursor_version"), str):
173
+ return "cursor"
174
+ # CLAUDE_PROJECT_DIR is a compatibility alias that several hosts set
175
+ # alongside their own variable — CodeBuddy, ZCode and Trae all do. It must
176
+ # therefore be checked LAST, or every one of them is detected as claude and
177
+ # the context key becomes `claude_<their-session-id>`. That key does not
178
+ # match the session file `task.py start` wrote under the host's real name,
179
+ # so every turn reports no_task while the pointer exists on disk.
180
+ # Observed on CodeBuddy IDE 4.10.4: session file `codebuddy_ae54840e….json`
181
+ # alongside marker `update-check-claude_ae54840e….marker`, same id.
182
+ env_map = {
183
+ "ZCODE_PROJECT_DIR": "zcode",
184
+ "CURSOR_PROJECT_DIR": "cursor",
185
+ "CODEBUDDY_PROJECT_DIR": "codebuddy",
186
+ "FACTORY_PROJECT_DIR": "droid",
187
+ "GEMINI_PROJECT_DIR": "gemini",
188
+ "QODER_PROJECT_DIR": "qoder",
189
+ "KIRO_PROJECT_DIR": "kiro",
190
+ "COPILOT_PROJECT_DIR": "copilot",
191
+ "TRAE_PROJECT_DIR": "trae",
192
+ # Last: the shared alias, only meaningful once no vendor key matched.
193
+ "CLAUDE_PROJECT_DIR": "claude",
194
+ }
195
+ for env_name, platform in env_map.items():
196
+ if os.environ.get(env_name):
197
+ return platform
198
+ script_parts = set(Path(sys.argv[0]).parts)
199
+ if ".claude" in script_parts:
200
+ return "claude"
201
+ if ".cursor" in script_parts:
202
+ return "cursor"
203
+ if ".codex" in script_parts:
204
+ return "codex"
205
+ if ".gemini" in script_parts:
206
+ return "gemini"
207
+ if ".qoder" in script_parts:
208
+ return "qoder"
209
+ if ".codebuddy" in script_parts:
210
+ return "codebuddy"
211
+ if ".factory" in script_parts:
212
+ return "droid"
213
+ if ".kiro" in script_parts:
214
+ return "kiro"
215
+ if ".trae" in script_parts:
216
+ return "trae"
217
+ if ".zcode" in script_parts:
218
+ return "zcode"
219
+ return None
220
+
221
+
222
+ def _resolve_context_key(trellis_dir: Path, input_data: dict) -> str | None:
223
+ scripts_dir = trellis_dir / "scripts"
224
+ if str(scripts_dir) not in sys.path:
225
+ sys.path.insert(0, str(scripts_dir))
226
+ from common.active_task import resolve_context_key # type: ignore[import-not-found]
227
+
228
+ return resolve_context_key(input_data, platform=_detect_platform(input_data))
229
+
230
+
231
+ def _persist_context_key_for_bash(context_key: str | None) -> None:
232
+ """Expose Trellis session identity to later Claude Code Bash commands.
233
+
234
+ Claude Code SessionStart hooks can append exports to CLAUDE_ENV_FILE; those
235
+ variables are then available to Bash tools in the same conversation. Without
236
+ this bridge, `task.py start` has hook stdin during SessionStart but no
237
+ session identity when the AI later runs it as a normal shell command.
238
+
239
+ CLAUDE_ENV_FILE is user-owned (conda init, proxy settings, ...) and the host
240
+ shell sources it for every command, so an unconditional append grows it
241
+ without bound — one line per SessionStart forever. Skip the write when the
242
+ *last* existing TRELLIS_CONTEXT_ID export already assigns this value. Last
243
+ wins in shell, so only the final assignment describes the effective state:
244
+ "the value appears somewhere in the file" would wrongly skip after a switch
245
+ A -> B -> A, leaving the shell on B.
246
+ """
247
+ if not context_key:
248
+ return
249
+ env_file = os.environ.get("CLAUDE_ENV_FILE")
250
+ if not env_file:
251
+ return
252
+ export_line = f"export TRELLIS_CONTEXT_ID={shlex.quote(context_key)}"
253
+ try:
254
+ if _last_context_key_export(env_file) == export_line:
255
+ return
256
+ with open(env_file, "a", encoding="utf-8") as handle:
257
+ handle.write(f"{export_line}\n")
258
+ except OSError:
259
+ pass # Optional shell bridge; keep session-start non-fatal.
260
+
261
+
262
+ def _last_context_key_export(env_file: str) -> str | None:
263
+ """Return the last `export TRELLIS_CONTEXT_ID=` line in env_file, if any.
264
+
265
+ A missing file means "no previous export" (the caller then creates it).
266
+ `errors="replace"` matters: a user env file with non-UTF-8 bytes would
267
+ otherwise raise UnicodeDecodeError, which is a ValueError — not an OSError —
268
+ and would escape the caller's non-fatal guard.
269
+ """
270
+ last_export = None
271
+ try:
272
+ with open(env_file, "r", encoding="utf-8", errors="replace") as handle:
273
+ for raw_line in handle:
274
+ stripped = raw_line.strip()
275
+ if stripped.startswith("export TRELLIS_CONTEXT_ID="):
276
+ last_export = stripped
277
+ except FileNotFoundError:
278
+ return None
279
+ return last_export
280
+
281
+
282
+ def run_script(script_path: Path, context_key: str | None = None) -> str:
283
+ try:
284
+ if script_path.suffix == ".py":
285
+ # Add PYTHONIOENCODING to force UTF-8 in subprocess
286
+ env = os.environ.copy()
287
+ env["PYTHONIOENCODING"] = "utf-8"
288
+ if context_key:
289
+ env["TRELLIS_CONTEXT_ID"] = context_key
290
+ cmd = [sys.executable, "-W", "ignore", str(script_path)]
291
+ else:
292
+ env = os.environ.copy()
293
+ if context_key:
294
+ env["TRELLIS_CONTEXT_ID"] = context_key
295
+ cmd = [str(script_path)]
296
+
297
+ result = subprocess.run(
298
+ cmd,
299
+ capture_output=True,
300
+ text=True,
301
+ encoding="utf-8",
302
+ errors="replace",
303
+ timeout=5,
304
+ cwd=script_path.parent.parent.parent,
305
+ env=env,
306
+ )
307
+ return result.stdout if result.returncode == 0 else "No context available"
308
+ except (subprocess.TimeoutExpired, FileNotFoundError, PermissionError):
309
+ return "No context available"
310
+
311
+
312
+ def _load_trellis_config(trellis_dir: Path, input_data: dict) -> tuple:
313
+ """Load Trellis config for session-start decisions.
314
+
315
+ Returns:
316
+ (is_mono, packages_dict, spec_scope, task_pkg, default_pkg)
317
+ """
318
+ scripts_dir = trellis_dir / "scripts"
319
+ if str(scripts_dir) not in sys.path:
320
+ sys.path.insert(0, str(scripts_dir))
321
+
322
+ try:
323
+ from common.config import get_default_package, get_packages, get_spec_scope, is_monorepo # type: ignore[import-not-found]
324
+ from common.paths import get_current_task # type: ignore[import-not-found]
325
+
326
+ repo_root = trellis_dir.parent
327
+ is_mono = is_monorepo(repo_root)
328
+ packages = get_packages(repo_root) or {}
329
+ scope = get_spec_scope(repo_root)
330
+
331
+ # Get active task's package
332
+ task_pkg = None
333
+ current = get_current_task(
334
+ repo_root,
335
+ input_data,
336
+ platform=_detect_platform(input_data),
337
+ )
338
+ if current:
339
+ task_json = repo_root / current / "task.json"
340
+ if task_json.is_file():
341
+ try:
342
+ data = json.loads(task_json.read_text(encoding="utf-8"))
343
+ if isinstance(data, dict):
344
+ tp = data.get("package")
345
+ if isinstance(tp, str) and tp:
346
+ task_pkg = tp
347
+ except (json.JSONDecodeError, OSError):
348
+ pass # Optional package metadata; fall back to default scope.
349
+
350
+ default_pkg = get_default_package(repo_root)
351
+ return is_mono, packages, scope, task_pkg, default_pkg
352
+ except Exception:
353
+ return False, {}, None, None, None
354
+
355
+
356
+ def _check_legacy_spec(trellis_dir: Path, is_mono: bool, packages: dict) -> str | None:
357
+ """Check for legacy spec directory structure in monorepo.
358
+
359
+ Returns warning message if legacy structure detected, None otherwise.
360
+ """
361
+ if not is_mono or not packages:
362
+ return None
363
+
364
+ spec_dir = trellis_dir / "spec"
365
+ if not spec_dir.is_dir():
366
+ return None
367
+
368
+ # Check for legacy flat spec dirs (spec/backend/, spec/frontend/ with index.md)
369
+ has_legacy = False
370
+ for legacy_name in ("backend", "frontend"):
371
+ legacy_dir = spec_dir / legacy_name
372
+ if legacy_dir.is_dir() and (legacy_dir / "index.md").is_file():
373
+ has_legacy = True
374
+ break
375
+
376
+ if not has_legacy:
377
+ return None
378
+
379
+ # Check which packages are missing spec/<pkg>/ directory
380
+ missing = [
381
+ name for name in sorted(packages.keys())
382
+ if not (spec_dir / name).is_dir()
383
+ ]
384
+
385
+ if not missing:
386
+ return None # All packages have spec dirs
387
+
388
+ if len(missing) == len(packages):
389
+ return (
390
+ f"[!] Legacy spec structure detected: found `spec/backend/` or `spec/frontend/` "
391
+ f"but no package-scoped `spec/<package>/` directories.\n"
392
+ f"Monorepo packages: {', '.join(sorted(packages.keys()))}\n"
393
+ f"Please reorganize: `spec/backend/` -> `spec/<package>/backend/`"
394
+ )
395
+ return (
396
+ f"[!] Partial spec migration detected: packages {', '.join(missing)} "
397
+ f"still missing `spec/<pkg>/` directory.\n"
398
+ f"Please complete migration for all packages."
399
+ )
400
+
401
+
402
+ def _resolve_spec_scope(
403
+ is_mono: bool,
404
+ packages: dict,
405
+ scope,
406
+ task_pkg: str | None,
407
+ default_pkg: str | None,
408
+ ) -> set | None:
409
+ """Resolve which packages should have their specs injected.
410
+
411
+ Returns:
412
+ Set of package names to include, or None for full scan.
413
+ """
414
+ if not is_mono or not packages:
415
+ return None # Single-repo: full scan
416
+
417
+ if scope is None:
418
+ return None # No scope configured: full scan
419
+
420
+ if isinstance(scope, str) and scope == "active_task":
421
+ if task_pkg and task_pkg in packages:
422
+ return {task_pkg}
423
+ if default_pkg and default_pkg in packages:
424
+ return {default_pkg}
425
+ return None # Fallback to full scan
426
+
427
+ if isinstance(scope, list):
428
+ valid = set()
429
+ for entry in scope:
430
+ if entry in packages:
431
+ valid.add(entry)
432
+ else:
433
+ print(
434
+ f"Warning: spec_scope contains unknown package: {entry}, ignoring",
435
+ file=sys.stderr,
436
+ )
437
+
438
+ if valid:
439
+ # Warn if active task is out of scope
440
+ if task_pkg and task_pkg not in valid:
441
+ print(
442
+ f"Warning: active task package '{task_pkg}' is out of configured spec_scope",
443
+ file=sys.stderr,
444
+ )
445
+ return valid
446
+
447
+ # All entries invalid: fallback chain
448
+ print(
449
+ "Warning: all spec_scope entries invalid, falling back to task/default/full",
450
+ file=sys.stderr,
451
+ )
452
+ if task_pkg and task_pkg in packages:
453
+ return {task_pkg}
454
+ if default_pkg and default_pkg in packages:
455
+ return {default_pkg}
456
+ return None # Full scan
457
+
458
+ return None # Unknown scope type: full scan
459
+
460
+
461
+ def _collect_spec_index_paths(trellis_dir: Path, allowed_pkgs: set | None) -> list[str]:
462
+ paths: list[str] = []
463
+ guides_index = trellis_dir / "spec" / "guides" / "index.md"
464
+ if guides_index.is_file():
465
+ paths.append(".trellis/spec/guides/index.md")
466
+
467
+ spec_dir = trellis_dir / "spec"
468
+ if not spec_dir.is_dir():
469
+ return paths
470
+
471
+ for sub in sorted(spec_dir.iterdir()):
472
+ if not sub.is_dir() or sub.name.startswith(".") or sub.name == "guides":
473
+ continue
474
+
475
+ index_file = sub / "index.md"
476
+ if index_file.is_file():
477
+ paths.append(f".trellis/spec/{sub.name}/index.md")
478
+ continue
479
+
480
+ if allowed_pkgs is not None and sub.name not in allowed_pkgs:
481
+ continue
482
+ for nested in sorted(sub.iterdir()):
483
+ if not nested.is_dir():
484
+ continue
485
+ nested_index = nested / "index.md"
486
+ if nested_index.is_file():
487
+ paths.append(f".trellis/spec/{sub.name}/{nested.name}/index.md")
488
+
489
+ return paths
490
+
491
+
492
+ def _collect_research_topics(trellis_dir: Path) -> list[str]:
493
+ research_dir = trellis_dir / "research"
494
+ if not research_dir.is_dir():
495
+ return []
496
+ topics: list[str] = []
497
+ try:
498
+ for path in sorted(research_dir.iterdir()):
499
+ if path.name.startswith(".") or path.name.lower() == "readme.md":
500
+ continue
501
+ if path.is_file() and path.suffix.lower() == ".md":
502
+ topics.append(f".trellis/research/{path.name}")
503
+ except OSError:
504
+ return []
505
+ return topics
506
+
507
+
508
+ def _build_compact_current_state(
509
+ trellis_dir: Path,
510
+ spec_index_paths: list[str],
511
+ research_topics: list[str],
512
+ ) -> str:
513
+ repo_root = trellis_dir.parent
514
+ lines: list[str] = []
515
+
516
+ try:
517
+ from common.paths import get_active_journal_file, get_developer, count_lines # type: ignore[import-not-found]
518
+ except Exception:
519
+ get_active_journal_file = None # type: ignore[assignment]
520
+ get_developer = None # type: ignore[assignment]
521
+ count_lines = None # type: ignore[assignment]
522
+
523
+ developer = get_developer(repo_root) if get_developer else None
524
+ lines.append(f"Developer: {developer or '(not initialized)'}")
525
+ lines.append(_format_git_state(repo_root))
526
+
527
+ if get_active_journal_file and count_lines:
528
+ journal = get_active_journal_file(repo_root)
529
+ if journal:
530
+ lines.append(
531
+ f"Journal: {_repo_relative(repo_root, journal)}, {count_lines(journal)} / 2000 lines."
532
+ )
533
+
534
+ if spec_index_paths:
535
+ lines.append(f"Spec indexes: {len(spec_index_paths)} available.")
536
+
537
+ if research_topics:
538
+ lines.append(f"Research notes: {len(research_topics)} in .trellis/research/.")
539
+ else:
540
+ lines.append("Research notes: none yet. Write .trellis/research/<topic>.md.")
541
+
542
+ return "\n".join(lines)
543
+
544
+
545
+ def main():
546
+ if should_skip_injection():
547
+ sys.exit(0)
548
+
549
+ try:
550
+ hook_input = json.loads(sys.stdin.read())
551
+ if not isinstance(hook_input, dict):
552
+ hook_input = {}
553
+ except (json.JSONDecodeError, ValueError):
554
+ hook_input = {}
555
+
556
+ # Try platform-specific env vars, hook cwd, fallback to cwd
557
+ project_dir_env_vars = [
558
+ "CLAUDE_PROJECT_DIR",
559
+ "QODER_PROJECT_DIR",
560
+ "CODEBUDDY_PROJECT_DIR",
561
+ "FACTORY_PROJECT_DIR",
562
+ "CURSOR_PROJECT_DIR",
563
+ "GEMINI_PROJECT_DIR",
564
+ "KIRO_PROJECT_DIR",
565
+ "COPILOT_PROJECT_DIR",
566
+ "TRAE_PROJECT_DIR",
567
+ "ZCODE_PROJECT_DIR",
568
+ ]
569
+ project_dir = None
570
+ for var in project_dir_env_vars:
571
+ val = os.environ.get(var)
572
+ if val:
573
+ project_dir = Path(_normalize_windows_shell_path(val)).resolve()
574
+ break
575
+ if project_dir is None:
576
+ project_dir = Path(_normalize_windows_shell_path(hook_input.get("cwd", "."))).resolve()
577
+
578
+ trellis_dir = project_dir / ".trellis"
579
+ context_key = _resolve_context_key(trellis_dir, hook_input)
580
+ _persist_context_key_for_bash(context_key)
581
+
582
+ # Load config for scope filtering and legacy detection
583
+ is_mono, packages, scope_config, task_pkg, default_pkg = _load_trellis_config(
584
+ trellis_dir,
585
+ hook_input,
586
+ )
587
+ allowed_pkgs = _resolve_spec_scope(is_mono, packages, scope_config, task_pkg, default_pkg)
588
+
589
+ output = StringIO()
590
+
591
+ spec_index_paths = _collect_spec_index_paths(trellis_dir, allowed_pkgs)
592
+ research_topics = _collect_research_topics(trellis_dir)
593
+ source = hook_input.get("source") if isinstance(hook_input.get("source"), str) else ""
594
+
595
+ output.write("""<session-context>
596
+ mini-trellis SessionStart context. Orient from journal, spec, and research.
597
+ </session-context>
598
+
599
+ """)
600
+ output.write(FIRST_REPLY_NOTICE)
601
+ output.write("\n\n")
602
+
603
+ # Legacy migration warning
604
+ legacy_warning = _check_legacy_spec(trellis_dir, is_mono, packages)
605
+ if legacy_warning:
606
+ output.write(f"<migration-warning>\n{legacy_warning}\n</migration-warning>\n\n")
607
+
608
+ output.write("<current-state>\n")
609
+ output.write(_build_compact_current_state(trellis_dir, spec_index_paths, research_topics))
610
+ output.write("\n</current-state>\n\n")
611
+
612
+ output.write("<guidelines>\n")
613
+ output.write(
614
+ "Memory: journal is git-durable session notes (`/mini-trellis:remember` or "
615
+ "`python3 ./.trellis/scripts/add_session.py`). Cross-session dialogue is "
616
+ "`mini-trellis mem list|search|context|extract`.\n"
617
+ "Research lives in `.trellis/research/<topic>.md`; promote durable "
618
+ "boundaries into `.trellis/spec/` as short markdown.\n\n"
619
+ )
620
+
621
+ if spec_index_paths:
622
+ output.write("## Spec indexes (read on demand)\n")
623
+ for p in spec_index_paths:
624
+ output.write(f"- {p}\n")
625
+ output.write("\n")
626
+
627
+ if research_topics:
628
+ output.write("## Research notes (read on demand)\n")
629
+ for p in research_topics:
630
+ output.write(f"- {p}\n")
631
+ output.write("\n")
632
+
633
+ if source == "compact":
634
+ output.write(
635
+ "This SessionStart was triggered by compact. If durable decisions "
636
+ "or research from the compacted window are not in journal yet, "
637
+ "run `/mini-trellis:remember` before continuing.\n"
638
+ )
639
+ output.write("</guidelines>\n\n")
640
+
641
+ output.write("""<ready>
642
+ Context loaded. Use journal, spec, research, and `mini-trellis mem` on demand. Remember at session end or after compact.
643
+ </ready>""")
644
+
645
+ context_text = output.getvalue()
646
+
647
+ # Kiro (CLI trellis agent agentSpawn) adds a hook's stdout directly to the
648
+ # conversation context — no JSON envelope. Emit the bare overview text.
649
+ # Conditionally isolated: all other platforms keep the JSON path below.
650
+ if _detect_platform(hook_input) == "kiro":
651
+ print(context_text, flush=True)
652
+ return
653
+
654
+ platform = _detect_platform(hook_input)
655
+ result: dict[str, object] = {
656
+ # Claude Code / Qoder / CodeBuddy / Droid / Gemini / Copilot / Trae /
657
+ # ZCode format.
658
+ "hookSpecificOutput": {
659
+ "hookEventName": "SessionStart",
660
+ "additionalContext": context_text,
661
+ },
662
+ }
663
+ # Cursor sessionStart format (top-level snake_case per Cursor docs).
664
+ # ZCode reads BOTH `hookSpecificOutput.additionalContext` and top-level
665
+ # `additional_context` without deduplication, so emitting both keys would
666
+ # duplicate the context in the conversation. Keep the previous shared output
667
+ # shape for every other platform.
668
+ if platform != "zcode":
669
+ result["additional_context"] = context_text
670
+
671
+ # Output JSON - stdout is already configured for UTF-8
672
+ print(json.dumps(result, ensure_ascii=False), flush=True)
673
+
674
+
675
+ if __name__ == "__main__":
676
+ main()
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Shared utilities for platform template modules.
3
+ * Eliminates boilerplate across qoder/, codebuddy/, droid/, cursor/, gemini/, kiro/ index.ts files.
4
+ */
5
+ export interface AgentTemplate {
6
+ name: string;
7
+ content: string;
8
+ }
9
+ export interface HookTemplate {
10
+ targetPath: string;
11
+ content: string;
12
+ }
13
+ export interface TemplateReader {
14
+ readTemplate: (relativePath: string) => string;
15
+ listFiles: (dir: string) => string[];
16
+ listMdAgents: (dir?: string) => AgentTemplate[];
17
+ listJsonAgents: (dir?: string) => AgentTemplate[];
18
+ getSettings: (filename?: string) => HookTemplate;
19
+ getConfig: (filename: string) => string;
20
+ }
21
+ /**
22
+ * Create a template reader bound to the caller's directory.
23
+ * Usage: `const { readTemplate, listMdAgents, getSettings } = createTemplateReader(import.meta.url);`
24
+ */
25
+ export declare function createTemplateReader(importMetaUrl: string): TemplateReader;
26
+ //# sourceMappingURL=template-utils.d.ts.map