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,708 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Session context generation (default + record modes).
4
+
5
+ Provides:
6
+ get_context_json - JSON output for default mode
7
+ get_context_text - Text output for default mode
8
+ get_context_record_json - JSON for record mode
9
+ get_context_text_record - Text for record mode
10
+ output_json - Print JSON
11
+ output_text - Print text
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import sys
18
+ from pathlib import Path
19
+
20
+ from .config import get_git_packages
21
+ from .git import run_git
22
+ from .packages_context import get_packages_section
23
+ from .tasks import iter_active_tasks, load_task, get_all_statuses, children_progress
24
+ from .paths import (
25
+ DIR_SCRIPTS,
26
+ DIR_SPEC,
27
+ DIR_TASKS,
28
+ DIR_WORKFLOW,
29
+ DIR_WORKSPACE,
30
+ count_lines,
31
+ get_active_journal_file,
32
+ get_current_task,
33
+ get_current_task_source,
34
+ get_developer,
35
+ get_repo_root,
36
+ get_tasks_dir,
37
+ )
38
+
39
+
40
+ # =============================================================================
41
+ # Helpers
42
+ # =============================================================================
43
+
44
+ _POLYREPO_IGNORED_DIRS = {
45
+ "node_modules",
46
+ "target",
47
+ "dist",
48
+ "build",
49
+ "out",
50
+ "bin",
51
+ "obj",
52
+ "vendor",
53
+ "coverage",
54
+ "tmp",
55
+ "__pycache__",
56
+ }
57
+ _POLYREPO_SCAN_MAX_DEPTH = 2
58
+ _POLYREPO_SCAN_MAX_REPOS = 8
59
+ _GIT_PROBE_TIMEOUT_SECONDS = 2.0
60
+
61
+
62
+ def _is_git_worktree(path: Path) -> bool:
63
+ """Return True when path is inside a Git worktree."""
64
+ rc, out, _ = run_git(
65
+ ["rev-parse", "--is-inside-work-tree"],
66
+ cwd=path,
67
+ timeout=_GIT_PROBE_TIMEOUT_SECONDS,
68
+ )
69
+ return rc == 0 and out.strip().lower() == "true"
70
+
71
+
72
+ def _parse_recent_commits(log_output: str) -> list[dict]:
73
+ """Parse `git log --oneline` output into structured commit entries."""
74
+ commits = []
75
+ for line in log_output.splitlines():
76
+ if not line.strip():
77
+ continue
78
+ parts = line.split(" ", 1)
79
+ if len(parts) >= 2:
80
+ commits.append({"hash": parts[0], "message": parts[1]})
81
+ elif len(parts) == 1:
82
+ commits.append({"hash": parts[0], "message": ""})
83
+ return commits
84
+
85
+
86
+ def _collect_git_repo_info(name: str, rel_path: str, repo_dir: Path) -> dict | None:
87
+ """Collect Git status for one known repository directory."""
88
+ if not (repo_dir / ".git").exists():
89
+ return None
90
+
91
+ status_rc, status_out, _ = run_git(
92
+ ["status", "--porcelain"],
93
+ cwd=repo_dir,
94
+ timeout=_GIT_PROBE_TIMEOUT_SECONDS,
95
+ )
96
+ if status_rc != 0:
97
+ return None
98
+ changes = len([line for line in status_out.splitlines() if line.strip()])
99
+
100
+ _, branch_out, _ = run_git(
101
+ ["branch", "--show-current"],
102
+ cwd=repo_dir,
103
+ timeout=_GIT_PROBE_TIMEOUT_SECONDS,
104
+ )
105
+ branch = branch_out.strip() or "unknown"
106
+
107
+ _, log_out, _ = run_git(
108
+ ["log", "--oneline", "-5"],
109
+ cwd=repo_dir,
110
+ timeout=_GIT_PROBE_TIMEOUT_SECONDS,
111
+ )
112
+
113
+ return {
114
+ "name": name,
115
+ "path": rel_path,
116
+ "branch": branch,
117
+ "isClean": changes == 0,
118
+ "uncommittedChanges": changes,
119
+ "recentCommits": _parse_recent_commits(log_out),
120
+ }
121
+
122
+
123
+ def _collect_root_git_info(repo_root: Path) -> dict:
124
+ """Collect root Git info without pretending a non-Git root is clean."""
125
+ if not _is_git_worktree(repo_root):
126
+ return {
127
+ "isRepo": False,
128
+ "branch": "",
129
+ "isClean": False,
130
+ "uncommittedChanges": 0,
131
+ "recentCommits": [],
132
+ }
133
+
134
+ _, branch_out, _ = run_git(
135
+ ["branch", "--show-current"],
136
+ cwd=repo_root,
137
+ timeout=_GIT_PROBE_TIMEOUT_SECONDS,
138
+ )
139
+ branch = branch_out.strip() or "unknown"
140
+
141
+ status_rc, status_out, _ = run_git(
142
+ ["status", "--porcelain"],
143
+ cwd=repo_root,
144
+ timeout=_GIT_PROBE_TIMEOUT_SECONDS,
145
+ )
146
+ status_lines = [line for line in status_out.splitlines() if line.strip()]
147
+
148
+ _, short_out, _ = run_git(
149
+ ["status", "--short"],
150
+ cwd=repo_root,
151
+ timeout=_GIT_PROBE_TIMEOUT_SECONDS,
152
+ )
153
+
154
+ _, log_out, _ = run_git(
155
+ ["log", "--oneline", "-5"],
156
+ cwd=repo_root,
157
+ timeout=_GIT_PROBE_TIMEOUT_SECONDS,
158
+ )
159
+
160
+ return {
161
+ "isRepo": True,
162
+ "branch": branch,
163
+ "isClean": status_rc == 0 and len(status_lines) == 0,
164
+ "uncommittedChanges": len(status_lines),
165
+ "statusShort": short_out.splitlines(),
166
+ "recentCommits": _parse_recent_commits(log_out),
167
+ }
168
+
169
+
170
+ def _discover_child_git_repos(repo_root: Path) -> list[tuple[str, str]]:
171
+ """Discover child Git repositories using the init-time polyrepo heuristic."""
172
+ found: list[str] = []
173
+ overflow = False
174
+
175
+ def is_candidate_dir(path: Path) -> bool:
176
+ name = path.name
177
+ return not name.startswith(".") and name not in _POLYREPO_IGNORED_DIRS
178
+
179
+ def scan(rel_dir: Path, depth: int) -> None:
180
+ nonlocal overflow
181
+ if overflow:
182
+ return
183
+ if depth >= _POLYREPO_SCAN_MAX_DEPTH:
184
+ return
185
+ abs_dir = repo_root / rel_dir
186
+ try:
187
+ children = sorted(abs_dir.iterdir(), key=lambda p: p.name)
188
+ except OSError:
189
+ return
190
+
191
+ for child in children:
192
+ if not child.is_dir() or not is_candidate_dir(child):
193
+ continue
194
+
195
+ child_rel = (
196
+ rel_dir / child.name if rel_dir != Path(".") else Path(child.name)
197
+ )
198
+ if (child / ".git").exists():
199
+ if len(found) >= _POLYREPO_SCAN_MAX_REPOS:
200
+ overflow = True
201
+ return
202
+ found.append(child_rel.as_posix())
203
+ continue
204
+ scan(child_rel, depth + 1)
205
+
206
+ scan(Path("."), 0)
207
+ if overflow:
208
+ print(
209
+ "warning: found more than "
210
+ f"{_POLYREPO_SCAN_MAX_REPOS} child Git repositories; "
211
+ "skipping automatic Git status collection. Configure explicit "
212
+ "packages entries with path and git: true in .trellis/config.yaml.",
213
+ file=sys.stderr,
214
+ )
215
+ return []
216
+ if len(found) < 2:
217
+ return []
218
+ return [(path.replace("/", "_"), path) for path in sorted(found)]
219
+
220
+
221
+ def _collect_package_git_info(
222
+ repo_root: Path,
223
+ discover_unconfigured: bool = False,
224
+ ) -> list[dict]:
225
+ """Collect Git status for independent package repositories.
226
+
227
+ Packages marked with ``git: true`` in config.yaml are authoritative.
228
+ When the Trellis root is not a Git repo and no configured package repos are
229
+ available, optionally fall back to the bounded polyrepo child scan.
230
+
231
+ Returns:
232
+ List of dicts with keys: name, path, branch, isClean,
233
+ uncommittedChanges, recentCommits.
234
+ Empty list if no git-repo packages are configured.
235
+ """
236
+ git_pkgs = get_git_packages(repo_root)
237
+ result = []
238
+ for pkg_name, pkg_path in git_pkgs.items():
239
+ pkg_dir = repo_root / pkg_path
240
+ info = _collect_git_repo_info(pkg_name, pkg_path, pkg_dir)
241
+ if info is not None:
242
+ result.append(info)
243
+
244
+ if result or not discover_unconfigured:
245
+ return result
246
+
247
+ discovered = []
248
+ for pkg_name, pkg_path in _discover_child_git_repos(repo_root):
249
+ info = _collect_git_repo_info(pkg_name, pkg_path, repo_root / pkg_path)
250
+ if info is not None:
251
+ discovered.append(info)
252
+ return discovered
253
+
254
+
255
+ def _append_root_git_context(lines: list[str], root_git_info: dict) -> None:
256
+ """Append root Git status without misleading non-Git roots."""
257
+ lines.append("## GIT STATUS")
258
+ if not root_git_info["isRepo"]:
259
+ lines.append("Root is not a Git repository.")
260
+ lines.append("Run Git commands from the package repository paths listed below.")
261
+ else:
262
+ lines.append(f"Branch: {root_git_info['branch']}")
263
+ if root_git_info["isClean"]:
264
+ lines.append("Working directory: Clean")
265
+ else:
266
+ lines.append(
267
+ f"Working directory: {root_git_info['uncommittedChanges']} "
268
+ "uncommitted change(s)"
269
+ )
270
+ lines.append("")
271
+ lines.append("Changes:")
272
+ for line in root_git_info.get("statusShort", [])[:10]:
273
+ lines.append(line)
274
+ lines.append("")
275
+
276
+ lines.append("## RECENT COMMITS")
277
+ if not root_git_info["isRepo"]:
278
+ lines.append(
279
+ "Root has no Git commit history because it is not a Git repository."
280
+ )
281
+ elif root_git_info["recentCommits"]:
282
+ for commit in root_git_info["recentCommits"]:
283
+ lines.append(f"{commit['hash']} {commit['message']}")
284
+ else:
285
+ lines.append("(no commits)")
286
+ lines.append("")
287
+
288
+
289
+ def _append_package_git_context(lines: list[str], package_git_info: list[dict]) -> None:
290
+ """Append Git status and recent commits for package repositories."""
291
+ for pkg in package_git_info:
292
+ lines.append(f"## GIT STATUS ({pkg['name']}: {pkg['path']})")
293
+ lines.append(f"Branch: {pkg['branch']}")
294
+ if pkg["isClean"]:
295
+ lines.append("Working directory: Clean")
296
+ else:
297
+ lines.append(
298
+ f"Working directory: {pkg['uncommittedChanges']} uncommitted change(s)"
299
+ )
300
+ lines.append("")
301
+ lines.append(f"## RECENT COMMITS ({pkg['name']}: {pkg['path']})")
302
+ if pkg["recentCommits"]:
303
+ for commit in pkg["recentCommits"]:
304
+ lines.append(f"{commit['hash']} {commit['message']}")
305
+ else:
306
+ lines.append("(no commits)")
307
+ lines.append("")
308
+
309
+
310
+ # =============================================================================
311
+ # JSON Output
312
+ # =============================================================================
313
+
314
+ def get_context_json(repo_root: Path | None = None) -> dict:
315
+ """Get context as a dictionary.
316
+
317
+ Args:
318
+ repo_root: Repository root path. Defaults to auto-detected.
319
+
320
+ Returns:
321
+ Context dictionary.
322
+ """
323
+ if repo_root is None:
324
+ repo_root = get_repo_root()
325
+
326
+ developer = get_developer(repo_root)
327
+ tasks_dir = get_tasks_dir(repo_root)
328
+ journal_file = get_active_journal_file(repo_root)
329
+
330
+ journal_lines = 0
331
+ journal_relative = ""
332
+ if journal_file and developer:
333
+ journal_lines = count_lines(journal_file)
334
+ journal_relative = (
335
+ f"{DIR_WORKFLOW}/{DIR_WORKSPACE}/{developer}/{journal_file.name}"
336
+ )
337
+
338
+ root_git_info = _collect_root_git_info(repo_root)
339
+
340
+ # Tasks
341
+ tasks = [
342
+ {
343
+ "dir": t.dir_name,
344
+ "name": t.name,
345
+ "status": t.status,
346
+ "children": list(t.children),
347
+ "parent": t.parent,
348
+ }
349
+ for t in iter_active_tasks(tasks_dir)
350
+ ]
351
+
352
+ # Package git repos (independent sub-repositories)
353
+ pkg_git_info = _collect_package_git_info(
354
+ repo_root,
355
+ discover_unconfigured=not root_git_info["isRepo"],
356
+ )
357
+
358
+ result = {
359
+ "developer": developer or "",
360
+ "git": {
361
+ "isRepo": root_git_info["isRepo"],
362
+ "branch": root_git_info["branch"],
363
+ "isClean": root_git_info["isClean"],
364
+ "uncommittedChanges": root_git_info["uncommittedChanges"],
365
+ "recentCommits": root_git_info["recentCommits"],
366
+ },
367
+ "tasks": {
368
+ "active": tasks,
369
+ "directory": f"{DIR_WORKFLOW}/{DIR_TASKS}",
370
+ },
371
+ "journal": {
372
+ "file": journal_relative,
373
+ "lines": journal_lines,
374
+ "nearLimit": journal_lines > 1800,
375
+ },
376
+ }
377
+
378
+ if pkg_git_info:
379
+ result["packageGit"] = pkg_git_info
380
+
381
+ return result
382
+
383
+
384
+ def output_json(repo_root: Path | None = None) -> None:
385
+ """Output context in JSON format.
386
+
387
+ Args:
388
+ repo_root: Repository root path. Defaults to auto-detected.
389
+ """
390
+ context = get_context_json(repo_root)
391
+ print(json.dumps(context, indent=2, ensure_ascii=False))
392
+
393
+
394
+ # =============================================================================
395
+ # Text Output
396
+ # =============================================================================
397
+
398
+ def get_context_text(repo_root: Path | None = None) -> str:
399
+ """Get context as formatted text.
400
+
401
+ Args:
402
+ repo_root: Repository root path. Defaults to auto-detected.
403
+
404
+ Returns:
405
+ Formatted text output.
406
+ """
407
+ if repo_root is None:
408
+ repo_root = get_repo_root()
409
+
410
+ lines = []
411
+ lines.append("========================================")
412
+ lines.append("SESSION CONTEXT")
413
+ lines.append("========================================")
414
+ lines.append("")
415
+
416
+ developer = get_developer(repo_root)
417
+
418
+ # Developer section
419
+ lines.append("## DEVELOPER")
420
+ if not developer:
421
+ lines.append(
422
+ f"ERROR: Not initialized. Run: python3 ./{DIR_WORKFLOW}/{DIR_SCRIPTS}/init_developer.py <name>"
423
+ )
424
+ return "\n".join(lines)
425
+
426
+ lines.append(f"Name: {developer}")
427
+ lines.append("")
428
+
429
+ root_git_info = _collect_root_git_info(repo_root)
430
+ _append_root_git_context(lines, root_git_info)
431
+
432
+ # Package git repos — independent sub-repositories
433
+ _append_package_git_context(
434
+ lines,
435
+ _collect_package_git_info(
436
+ repo_root,
437
+ discover_unconfigured=not root_git_info["isRepo"],
438
+ ),
439
+ )
440
+
441
+ # Current task
442
+ lines.append("## CURRENT TASK")
443
+ current_task = get_current_task(repo_root)
444
+ if current_task:
445
+ current_task_dir = repo_root / current_task
446
+ source_type, context_key, _ = get_current_task_source(repo_root)
447
+ lines.append(f"Path: {current_task}")
448
+ lines.append(
449
+ f"Source: {source_type}" + (f":{context_key}" if context_key else "")
450
+ )
451
+
452
+ ct = load_task(current_task_dir)
453
+ if ct:
454
+ lines.append(f"Name: {ct.name}")
455
+ lines.append(f"Status: {ct.status}")
456
+ lines.append(f"Created: {ct.raw.get('createdAt', 'unknown')}")
457
+ if ct.description:
458
+ lines.append(f"Description: {ct.description}")
459
+
460
+ # Check for prd.md
461
+ prd_file = current_task_dir / "prd.md"
462
+ if prd_file.is_file():
463
+ lines.append("")
464
+ lines.append("[!] This task has prd.md - read it for task details")
465
+ else:
466
+ lines.append("(none)")
467
+ lines.append("")
468
+
469
+ # Active tasks
470
+ lines.append("## ACTIVE TASKS")
471
+ tasks_dir = get_tasks_dir(repo_root)
472
+ task_count = 0
473
+
474
+ # Collect all task data for hierarchy display
475
+ all_tasks = {t.dir_name: t for t in iter_active_tasks(tasks_dir)}
476
+ all_statuses = {name: t.status for name, t in all_tasks.items()}
477
+
478
+ def _print_task_tree(name: str, indent: int = 0) -> None:
479
+ nonlocal task_count
480
+ t = all_tasks[name]
481
+ progress = children_progress(t.children, all_statuses)
482
+ prefix = " " * indent
483
+ lines.append(f"{prefix}- {name}/ ({t.status}){progress} @{t.assignee or '-'}")
484
+ task_count += 1
485
+ for child in t.children:
486
+ if child in all_tasks:
487
+ _print_task_tree(child, indent + 1)
488
+
489
+ for dir_name in sorted(all_tasks.keys()):
490
+ if not all_tasks[dir_name].parent:
491
+ _print_task_tree(dir_name)
492
+
493
+ if task_count == 0:
494
+ lines.append("(no active tasks)")
495
+ lines.append(f"Total: {task_count} active task(s)")
496
+ lines.append("")
497
+
498
+ # My tasks
499
+ lines.append("## MY TASKS (Assigned to me)")
500
+ my_task_count = 0
501
+
502
+ for t in all_tasks.values():
503
+ if t.assignee == developer and t.status != "done":
504
+ progress = children_progress(t.children, all_statuses)
505
+ lines.append(f"- [{t.priority}] {t.title} ({t.status}){progress}")
506
+ my_task_count += 1
507
+
508
+ if my_task_count == 0:
509
+ lines.append("(no tasks assigned to you)")
510
+ lines.append("")
511
+
512
+ # Journal file
513
+ lines.append("## JOURNAL FILE")
514
+ journal_file = get_active_journal_file(repo_root)
515
+ if journal_file:
516
+ journal_lines = count_lines(journal_file)
517
+ relative = f"{DIR_WORKFLOW}/{DIR_WORKSPACE}/{developer}/{journal_file.name}"
518
+ lines.append(f"Active file: {relative}")
519
+ lines.append(f"Line count: {journal_lines} / 2000")
520
+ if journal_lines > 1800:
521
+ lines.append("[!] WARNING: Approaching 2000 line limit!")
522
+ else:
523
+ lines.append("No journal file found")
524
+ lines.append("")
525
+
526
+ # Packages
527
+ packages_text = get_packages_section(repo_root)
528
+ if packages_text:
529
+ lines.append(packages_text)
530
+ lines.append("")
531
+
532
+ # Paths
533
+ lines.append("## PATHS")
534
+ lines.append(f"Workspace: {DIR_WORKFLOW}/{DIR_WORKSPACE}/{developer}/")
535
+ lines.append(f"Tasks: {DIR_WORKFLOW}/{DIR_TASKS}/")
536
+ lines.append(f"Spec: {DIR_WORKFLOW}/{DIR_SPEC}/")
537
+ lines.append("")
538
+
539
+ lines.append("========================================")
540
+
541
+ return "\n".join(lines)
542
+
543
+
544
+ # =============================================================================
545
+ # Record Mode
546
+ # =============================================================================
547
+
548
+ def get_context_record_json(repo_root: Path | None = None) -> dict:
549
+ """Get record-mode context as a dictionary.
550
+
551
+ Focused on: my active tasks, git status, current task.
552
+ """
553
+ if repo_root is None:
554
+ repo_root = get_repo_root()
555
+
556
+ developer = get_developer(repo_root)
557
+ tasks_dir = get_tasks_dir(repo_root)
558
+
559
+ root_git_info = _collect_root_git_info(repo_root)
560
+
561
+ # My tasks (single pass — collect statuses and filter by assignee)
562
+ all_tasks_list = list(iter_active_tasks(tasks_dir))
563
+ all_statuses = {t.dir_name: t.status for t in all_tasks_list}
564
+
565
+ my_tasks = []
566
+ for t in all_tasks_list:
567
+ if t.assignee == developer:
568
+ done = sum(
569
+ 1 for c in t.children
570
+ if all_statuses.get(c) in ("completed", "done")
571
+ )
572
+ my_tasks.append({
573
+ "dir": t.dir_name,
574
+ "title": t.title,
575
+ "status": t.status,
576
+ "priority": t.priority,
577
+ "children": list(t.children),
578
+ "childrenDone": done,
579
+ "parent": t.parent,
580
+ "meta": t.meta,
581
+ })
582
+
583
+ # Current task
584
+ current_task_info = None
585
+ current_task = get_current_task(repo_root)
586
+ if current_task:
587
+ source_type, context_key, _ = get_current_task_source(repo_root)
588
+ ct = load_task(repo_root / current_task)
589
+ if ct:
590
+ current_task_info = {
591
+ "path": current_task,
592
+ "name": ct.name,
593
+ "status": ct.status,
594
+ "source": source_type,
595
+ "contextKey": context_key,
596
+ }
597
+
598
+ # Package git repos
599
+ pkg_git_info = _collect_package_git_info(
600
+ repo_root,
601
+ discover_unconfigured=not root_git_info["isRepo"],
602
+ )
603
+
604
+ result = {
605
+ "developer": developer or "",
606
+ "git": {
607
+ "isRepo": root_git_info["isRepo"],
608
+ "branch": root_git_info["branch"],
609
+ "isClean": root_git_info["isClean"],
610
+ "uncommittedChanges": root_git_info["uncommittedChanges"],
611
+ "recentCommits": root_git_info["recentCommits"],
612
+ },
613
+ "myTasks": my_tasks,
614
+ "currentTask": current_task_info,
615
+ }
616
+
617
+ if pkg_git_info:
618
+ result["packageGit"] = pkg_git_info
619
+
620
+ return result
621
+
622
+
623
+ def get_context_text_record(repo_root: Path | None = None) -> str:
624
+ """Get context as formatted text for record-session mode.
625
+
626
+ Focused output: MY ACTIVE TASKS first (with [!!!] emphasis),
627
+ then GIT STATUS, RECENT COMMITS, CURRENT TASK.
628
+ """
629
+ if repo_root is None:
630
+ repo_root = get_repo_root()
631
+
632
+ lines: list[str] = []
633
+ lines.append("========================================")
634
+ lines.append("SESSION CONTEXT (RECORD MODE)")
635
+ lines.append("========================================")
636
+ lines.append("")
637
+
638
+ developer = get_developer(repo_root)
639
+ if not developer:
640
+ lines.append(
641
+ f"ERROR: Not initialized. Run: python3 ./{DIR_WORKFLOW}/{DIR_SCRIPTS}/init_developer.py <name>"
642
+ )
643
+ return "\n".join(lines)
644
+
645
+ # MY ACTIVE TASKS — first and prominent
646
+ lines.append(f"## [!!!] MY ACTIVE TASKS (Assigned to {developer})")
647
+ lines.append("[!] Review whether any should be archived before recording this session.")
648
+ lines.append("")
649
+
650
+ tasks_dir = get_tasks_dir(repo_root)
651
+ my_task_count = 0
652
+
653
+ # Single pass — collect all tasks and filter by assignee
654
+ all_statuses = get_all_statuses(tasks_dir)
655
+
656
+ for t in iter_active_tasks(tasks_dir):
657
+ if t.assignee == developer:
658
+ progress = children_progress(t.children, all_statuses)
659
+ lines.append(f"- [{t.priority}] {t.title} ({t.status}){progress} — {t.dir_name}")
660
+ my_task_count += 1
661
+
662
+ if my_task_count == 0:
663
+ lines.append("(no active tasks assigned to you)")
664
+ lines.append("")
665
+
666
+ root_git_info = _collect_root_git_info(repo_root)
667
+ _append_root_git_context(lines, root_git_info)
668
+
669
+ # Package git repos — independent sub-repositories
670
+ _append_package_git_context(
671
+ lines,
672
+ _collect_package_git_info(
673
+ repo_root,
674
+ discover_unconfigured=not root_git_info["isRepo"],
675
+ ),
676
+ )
677
+
678
+ # CURRENT TASK
679
+ lines.append("## CURRENT TASK")
680
+ current_task = get_current_task(repo_root)
681
+ if current_task:
682
+ source_type, context_key, _ = get_current_task_source(repo_root)
683
+ lines.append(f"Path: {current_task}")
684
+ lines.append(
685
+ f"Source: {source_type}" + (f":{context_key}" if context_key else "")
686
+ )
687
+ ct = load_task(repo_root / current_task)
688
+ if ct:
689
+ lines.append(f"Name: {ct.name}")
690
+ lines.append(f"Status: {ct.status}")
691
+ else:
692
+ lines.append("(none)")
693
+ lines.append("")
694
+
695
+ lines.append("========================================")
696
+
697
+ return "\n".join(lines)
698
+
699
+
700
+ def output_text(repo_root: Path | None = None) -> None:
701
+ """Output context in text format.
702
+
703
+ Args:
704
+ repo_root: Repository root path. Defaults to auto-detected.
705
+ """
706
+ if repo_root is None:
707
+ repo_root = get_repo_root()
708
+ print(get_context_text(repo_root))