mini-trellis 0.1.1 → 0.2.1

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 (51) hide show
  1. package/README.md +108 -94
  2. package/dist/cli/index.d.ts.map +1 -1
  3. package/dist/cli/index.js +32 -0
  4. package/dist/cli/index.js.map +1 -1
  5. package/dist/commands/doctor.d.ts +18 -0
  6. package/dist/commands/doctor.d.ts.map +1 -0
  7. package/dist/commands/doctor.js +197 -0
  8. package/dist/commands/doctor.js.map +1 -0
  9. package/dist/commands/init.d.ts.map +1 -1
  10. package/dist/commands/init.js +34 -8
  11. package/dist/commands/init.js.map +1 -1
  12. package/dist/commands/mem.d.ts +2 -0
  13. package/dist/commands/mem.d.ts.map +1 -1
  14. package/dist/commands/mem.js +85 -2
  15. package/dist/commands/mem.js.map +1 -1
  16. package/dist/commands/refresh.d.ts +24 -0
  17. package/dist/commands/refresh.d.ts.map +1 -0
  18. package/dist/commands/refresh.js +180 -0
  19. package/dist/commands/refresh.js.map +1 -0
  20. package/dist/configurators/shared.d.ts.map +1 -1
  21. package/dist/configurators/shared.js +15 -2
  22. package/dist/configurators/shared.js.map +1 -1
  23. package/dist/templates/codex/config.toml +7 -15
  24. package/dist/templates/codex/hooks.json +4 -1
  25. package/dist/templates/common/bundled-skills/mini-trellis-session-insight/SKILL.md +13 -7
  26. package/dist/templates/common/bundled-skills/mini-trellis-session-insight/references/cli-quick-reference.md +24 -11
  27. package/dist/templates/common/bundled-skills/mini-trellis-session-insight/references/triggering-patterns.md +18 -10
  28. package/dist/templates/common/commands/remember.md +17 -3
  29. package/dist/templates/common/skills/update-spec.md +4 -0
  30. package/dist/templates/extract.d.ts +2 -0
  31. package/dist/templates/extract.d.ts.map +1 -1
  32. package/dist/templates/extract.js +21 -0
  33. package/dist/templates/extract.js.map +1 -1
  34. package/dist/templates/markdown/agents.md +9 -1
  35. package/dist/templates/markdown/spec/guides/mini-memory.md.txt +15 -8
  36. package/dist/templates/opencode/lib/session-utils.js +13 -58
  37. package/dist/templates/opencode/plugins/session-start.js +6 -10
  38. package/dist/templates/pi/extensions/mini-trellis/index.ts.txt +27 -78
  39. package/dist/templates/shared-hooks/session-start.py +108 -64
  40. package/dist/templates/trellis/config.yaml +3 -3
  41. package/dist/templates/trellis/scripts/add_session.py +95 -9
  42. package/dist/templates/trellis/scripts/common/config.py +4 -3
  43. package/dist/utils/managed-manifest.d.ts +12 -0
  44. package/dist/utils/managed-manifest.d.ts.map +1 -0
  45. package/dist/utils/managed-manifest.js +48 -0
  46. package/dist/utils/managed-manifest.js.map +1 -0
  47. package/dist/utils/managed-merge.d.ts +17 -0
  48. package/dist/utils/managed-merge.d.ts.map +1 -0
  49. package/dist/utils/managed-merge.js +101 -0
  50. package/dist/utils/managed-merge.js.map +1 -0
  51. package/package.json +4 -4
@@ -7,16 +7,7 @@ import { debugLog } from "./trellis-context.js"
7
7
 
8
8
  const PYTHON_CMD = platform() === "win32" ? "python" : "python3"
9
9
 
10
- const FIRST_REPLY_NOTICE = `<first-reply-notice>
11
- On the first visible assistant reply in this session, briefly acknowledge that mini-trellis SessionStart context loaded.
12
- Choose the acknowledgment language in this order:
13
- 1. Use the language of the user's current request (the user message that triggered this reply).
14
- 2. If that request has no clear natural language, use an explicitly established project communication language.
15
- 3. If neither provides a language, output the language-neutral fallback exactly: \`mini-trellis SessionStart ✓\`.
16
- Continue directly with the user's request after the acknowledgment.
17
- The acknowledgment must not alter the language used for the remainder of the response.
18
- This notice is one-shot: do not repeat it after the first visible assistant reply in this session.
19
- </first-reply-notice>`
10
+ const MAX_CONTEXT_CHARS = 4000
20
11
 
21
12
  function loadTrellisConfig(directory, contextKey = null) {
22
13
  const scriptPath = join(directory, ".trellis", "scripts", "get_context.py")
@@ -122,27 +113,6 @@ function resolveSpecScope(config) {
122
113
  return null
123
114
  }
124
115
 
125
- function collectResearchTopics(directory) {
126
- const researchDir = join(directory, ".trellis", "research")
127
- if (!existsSync(researchDir)) return []
128
- try {
129
- return readdirSync(researchDir, { withFileTypes: true })
130
- .filter(entry => {
131
- if (entry.name.startsWith(".") || entry.name.toLowerCase() === "readme.md") return false
132
- if (entry.name === "archive") return false
133
- // A topic is a note, or a directory: `mini-trellis migrate` folds each
134
- // Trellis task into one so its evidence sits next to its notes.
135
- if (entry.isDirectory()) return true
136
- return entry.isFile() && entry.name.toLowerCase().endsWith(".md")
137
- })
138
- .map(entry => ({ name: entry.name, dir: entry.isDirectory() }))
139
- .sort((a, b) => a.name.localeCompare(b.name))
140
- .map(topic => `.trellis/research/${topic.name}${topic.dir ? "/" : ""}`)
141
- } catch {
142
- return []
143
- }
144
- }
145
-
146
116
  function collectSpecIndexPaths(directory, allowedPkgs) {
147
117
  const specDir = join(directory, ".trellis", "spec")
148
118
  const paths = []
@@ -221,7 +191,7 @@ function runGit(directory, args) {
221
191
  }
222
192
  }
223
193
 
224
- function buildCompactCurrentState(ctx, specIndexPaths, researchTopics) {
194
+ function buildCompactCurrentState(ctx, specIndexPaths) {
225
195
  const directory = ctx.directory
226
196
  const lines = []
227
197
  lines.push(`Developer: ${readDeveloper(directory)}`)
@@ -254,11 +224,7 @@ function buildCompactCurrentState(ctx, specIndexPaths, researchTopics) {
254
224
  lines.push(`Spec indexes: ${specIndexPaths.length} available.`)
255
225
  }
256
226
 
257
- if (researchTopics.length > 0) {
258
- lines.push(`Research notes: ${researchTopics.length} in .trellis/research/.`)
259
- } else {
260
- lines.push("Research notes: none yet. Write .trellis/research/<topic>.md.")
261
- }
227
+ lines.push("Research: use `mini-trellis mem recall <query>` when relevant.")
262
228
 
263
229
  return lines.join("\n")
264
230
  }
@@ -272,14 +238,12 @@ export function buildSessionContext(ctx, platformInput = null) {
272
238
  const config = loadTrellisConfig(directory, contextKey)
273
239
  const allowedPkgs = resolveSpecScope(config)
274
240
  const paths = collectSpecIndexPaths(directory, allowedPkgs)
275
- const researchTopics = collectResearchTopics(directory)
276
241
 
277
242
  const parts = []
278
243
 
279
244
  parts.push(`<session-context>
280
245
  mini-trellis SessionStart context. Orient from journal, spec, and research.
281
246
  </session-context>`)
282
- parts.push(FIRST_REPLY_NOTICE)
283
247
 
284
248
  const legacyWarning = checkLegacySpec(directory, config)
285
249
  if (legacyWarning) {
@@ -287,34 +251,21 @@ mini-trellis SessionStart context. Orient from journal, spec, and research.
287
251
  }
288
252
 
289
253
  parts.push("<current-state>")
290
- parts.push(buildCompactCurrentState(ctx, paths, researchTopics))
254
+ parts.push(buildCompactCurrentState(ctx, paths))
291
255
  parts.push("</current-state>")
292
256
 
293
257
  parts.push("<guidelines>")
294
258
  parts.push(
295
259
  "Memory: journal is git-durable session notes (`/mini-trellis:remember` or " +
296
- "`python3 ./.trellis/scripts/add_session.py`). Cross-session dialogue is " +
297
- "`mini-trellis mem list|search|context|extract`.\n" +
260
+ "`python3 ./.trellis/scripts/add_session.py`). For relevant prior knowledge, use " +
261
+ "`mini-trellis mem recall <query>`, then `mini-trellis mem read <ref>` for context.\n" +
298
262
  "Research lives in `.trellis/research/<topic>.md`, or in " +
299
263
  "`.trellis/research/<topic>/` when a topic brings evidence files with it; " +
300
264
  "promote durable boundaries into `.trellis/spec/` as short markdown.\n"
265
+ + "Record confirmed decisions, useful research findings, and session/compact endings. Do not record every turn or create a git commit unless the user asks.\n"
266
+ + "Keep confirmed rules short and faithful; leave unconfirmed scope, exceptions, and implementation choices open or label them as inference, not part of the contract.\n"
301
267
  )
302
268
 
303
- if (paths.length > 0) {
304
- parts.push("## Spec indexes (read on demand)")
305
- for (const p of paths) {
306
- parts.push(`- ${p}`)
307
- }
308
- parts.push("")
309
- }
310
-
311
- if (researchTopics.length > 0) {
312
- parts.push("## Research notes (read on demand)")
313
- for (const p of researchTopics) {
314
- parts.push(`- ${p}`)
315
- }
316
- parts.push("")
317
- }
318
269
 
319
270
  parts.push("</guidelines>")
320
271
 
@@ -322,7 +273,11 @@ mini-trellis SessionStart context. Orient from journal, spec, and research.
322
273
  Context loaded. Use journal, spec, research, and \`mini-trellis mem\` on demand. Remember at session end or after compact.
323
274
  </ready>`)
324
275
 
325
- return parts.join("\n\n")
276
+ const context = parts.join("\n\n")
277
+ if (context.length <= MAX_CONTEXT_CHARS) return context
278
+ const tail = context.slice(-300)
279
+ return context.slice(0, MAX_CONTEXT_CHARS - tail.length - 80) +
280
+ "\n[mini-trellis context truncated; read files on demand]\n" + tail
326
281
  }
327
282
 
328
283
  function getTrellisMetadata(metadata) {
@@ -13,16 +13,9 @@ import {
13
13
  MESSAGES_TRANSFORM_HOOK,
14
14
  platformInputFromMessages,
15
15
  prependEphemeralText,
16
- transcriptHasAssistantMessage,
17
16
  } from "../lib/context-visibility.js"
18
17
  import { buildSessionContext } from "../lib/session-utils.js"
19
18
 
20
- const FIRST_REPLY_NOTICE_RE = /<first-reply-notice>[\s\S]*?<\/first-reply-notice>\s*/g
21
-
22
- function stripFirstReplyNotice(context) {
23
- return context.replace(FIRST_REPLY_NOTICE_RE, "")
24
- }
25
-
26
19
  // OpenCode 1.2.x expects plugins to be factory functions (see inject-subagent-context.js comment).
27
20
  export default async ({ directory }) => {
28
21
  const ctx = new TrellisContext(directory)
@@ -51,9 +44,12 @@ export default async ({ directory }) => {
51
44
  return
52
45
  }
53
46
 
54
- let context = buildSessionContext(ctx, platformInput)
55
- if (transcriptHasAssistantMessage(messages)) {
56
- context = stripFirstReplyNotice(context)
47
+ const context = buildSessionContext(ctx, platformInput)
48
+ if (messages?.some(message =>
49
+ message?.parts?.some(part =>
50
+ part?.synthetic === true && part.text === context))) {
51
+ debugLog("session", "Skipping - same SessionStart content already injected")
52
+ return
57
53
  }
58
54
  debugLog("session", "Built context, length:", context.length)
59
55
  prependEphemeralText(messages, context)
@@ -29,43 +29,16 @@ function findRoot(start: string): string {
29
29
  return start;
30
30
  }
31
31
 
32
- function collectResearchTopics(root: string): string[] {
33
- const researchDir = join(root, ".trellis", "research");
34
- if (!exists(researchDir)) return [];
35
- try {
36
- return readdirSync(researchDir, { withFileTypes: true })
37
- .filter((entry) => {
38
- if (entry.name.startsWith(".") || entry.name.toLowerCase() === "readme.md") return false;
39
- if (entry.name === "archive") return false;
40
- // A topic is a note, or a directory: `mini-trellis migrate` folds each
41
- // Trellis task into one so its evidence sits next to its notes.
42
- if (entry.isDirectory()) return true;
43
- return entry.isFile() && entry.name.toLowerCase().endsWith(".md");
44
- })
45
- .map((entry) => ({ name: entry.name, dir: entry.isDirectory() }))
46
- .sort((a, b) => a.name.localeCompare(b.name))
47
- .map((topic) => `.trellis/research/${topic.name}${topic.dir ? "/" : ""}`);
48
- } catch {
49
- return [];
50
- }
51
- }
52
-
53
- function collectSpecIndexPaths(root: string): string[] {
32
+ function countSpecIndexes(root: string): number {
54
33
  const specDir = join(root, ".trellis", "spec");
55
- const paths: string[] = [];
56
- const guidesIndex = join(specDir, "guides", "index.md");
57
- if (exists(guidesIndex)) paths.push(".trellis/spec/guides/index.md");
58
- if (!exists(specDir)) return paths;
34
+ if (!exists(specDir)) return 0;
59
35
  try {
60
- for (const sub of readdirSync(specDir).sort()) {
61
- if (sub.startsWith(".") || sub === "guides") continue;
62
- const indexFile = join(specDir, sub, "index.md");
63
- if (exists(indexFile)) paths.push(`.trellis/spec/${sub}/index.md`);
64
- }
36
+ return readdirSync(specDir).filter((name) =>
37
+ exists(join(specDir, name, "index.md")),
38
+ ).length;
65
39
  } catch {
66
- // ignore
40
+ return 0;
67
41
  }
68
- return paths;
69
42
  }
70
43
 
71
44
  function readDeveloper(root: string): string | null {
@@ -103,44 +76,26 @@ function activeJournal(root: string): string | null {
103
76
  }
104
77
 
105
78
  function buildStartupContext(root: string): string {
106
- const spec = collectSpecIndexPaths(root);
107
- const research = collectResearchTopics(root);
108
79
  const journal = activeJournal(root);
109
- const lines: string[] = [
110
- "<session-context>",
111
- "mini-trellis SessionStart context. Orient from journal, spec, and research.",
112
- "</session-context>",
113
- "",
114
- "<current-state>",
115
- ];
116
- if (journal) lines.push(`Journal: ${journal}`);
117
- if (spec.length) lines.push(`Spec indexes: ${spec.length} available.`);
118
- lines.push(
119
- research.length
120
- ? `Research notes: ${research.length} in .trellis/research/.`
121
- : "Research notes: none yet. Write .trellis/research/<topic>.md.",
122
- );
123
- lines.push("</current-state>", "", "<guidelines>");
124
- lines.push(
125
- "Memory: journal is git-durable session notes (`/mini-trellis-remember` or `python3 ./.trellis/scripts/add_session.py`). Cross-session dialogue is `mini-trellis mem list|search|context|extract`.",
126
- "Research lives in `.trellis/research/<topic>.md`, or in `.trellis/research/<topic>/` when a topic brings evidence files with it; promote durable boundaries into `.trellis/spec/` as short markdown.",
127
- );
128
- if (spec.length) {
129
- lines.push("", "## Spec indexes (read on demand)");
130
- for (const p of spec) lines.push(`- ${p}`);
131
- }
132
- if (research.length) {
133
- lines.push("", "## Research notes (read on demand)");
134
- for (const p of research) lines.push(`- ${p}`);
135
- }
136
- lines.push(
137
- "</guidelines>",
138
- "",
139
- "<ready>",
140
- "Context loaded. Use journal, spec, research, and `mini-trellis mem` on demand. Remember at session end or after compact.",
141
- "</ready>",
142
- );
143
- return lines.join("\n");
80
+ const specCount = countSpecIndexes(root);
81
+ return `<session-context>
82
+ mini-trellis memory is available on demand. Do not announce this hook.
83
+ Use \`mini-trellis mem recall <query>\` for relevant prior decisions or conventions;
84
+ include the affected path/identifier when useful. Unrelated edits need no history lookup.
85
+ Use \`mini-trellis mem read <ref>\` only if an excerpt lacks needed context or qualifiers.
86
+ Reuse evidence already in the current context; recall again after compact or when a
87
+ source changes or disappears. Never treat stale or missing sources as current rules.
88
+ Keep confirmed decisions and useful findings in \`.trellis/research/<topic>.md\`;
89
+ update the existing topic, and promote lasting contracts into \`.trellis/spec/\`.
90
+ Keep confirmed rules short and faithful; leave unconfirmed scope, exceptions, and
91
+ implementation choices open or label them as inference, not part of the contract.
92
+ New notes follow the user's language; updates keep the file's language. Preserve identifiers.
93
+ Record meaningful session outcomes with \`python3 ./.trellis/scripts/add_session.py\`.
94
+ Journal entries should link to the topic instead of duplicating it. Ordinary edits and
95
+ unconfirmed or rejected suggestions are not new durable decisions. Report write failures.
96
+ Do not create a git commit unless the user explicitly asks.
97
+ </session-context>` + (journal ? `\nJournal: ${journal}` : "") +
98
+ (specCount ? `\nSpec indexes: ${specCount} available.` : "");
144
99
  }
145
100
 
146
101
  export default function trellisExtension(pi: {
@@ -151,17 +106,11 @@ export default function trellisExtension(pi: {
151
106
  }): void {
152
107
  if (process.env.TRELLIS_SUBAGENT_CHILD === "1") return;
153
108
  const root = findRoot(process.cwd() || homedir());
154
- const startup = buildStartupContext(root);
155
-
156
- pi.on?.("session_start", (_event, ctx) => {
157
- ctx?.ui?.notify?.(
158
- "mini-trellis context is available. Use /mini-trellis-remember to persist journal notes.",
159
- "info",
160
- );
161
- });
162
109
 
163
110
  pi.on?.("before_agent_start", (event) => {
164
111
  const cur = (event as { systemPrompt?: string }).systemPrompt ?? "";
112
+ const startup = buildStartupContext(root);
113
+ if (cur.includes(startup)) return { systemPrompt: cur };
165
114
  return {
166
115
  systemPrompt: [cur, startup].filter(Boolean).join("\n\n"),
167
116
  };
@@ -10,11 +10,14 @@ import warnings
10
10
  warnings.filterwarnings("ignore")
11
11
 
12
12
  import json
13
+ import hashlib
13
14
  import os
14
15
  import re
15
16
  import shlex
16
17
  import subprocess
17
18
  import sys
19
+ from datetime import datetime, timezone
20
+ import tempfile
18
21
  from io import StringIO
19
22
  from pathlib import Path
20
23
 
@@ -67,17 +70,10 @@ def _normalize_windows_shell_path(path_str: str) -> str:
67
70
  return path_str
68
71
 
69
72
 
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>"""
73
+ MAX_CONTEXT_CHARS = 4000
80
74
 
75
+ RUNTIME_STATUS_VERSION = 1
76
+ _LAST_PROJECT_DIR: Path | None = None
81
77
 
82
78
  # Force UTF-8 on stdin/stdout/stderr on Windows. Default codepage there is
83
79
  # cp936 / cp1252 / etc. — non-ASCII content (Chinese task names, prd snippets)
@@ -182,6 +178,7 @@ def _detect_platform(input_data: dict) -> str | None:
182
178
  env_map = {
183
179
  "ZCODE_PROJECT_DIR": "zcode",
184
180
  "CURSOR_PROJECT_DIR": "cursor",
181
+ "CODEX_PROJECT_DIR": "codex",
185
182
  "CODEBUDDY_PROJECT_DIR": "codebuddy",
186
183
  "FACTORY_PROJECT_DIR": "droid",
187
184
  "GEMINI_PROJECT_DIR": "gemini",
@@ -489,32 +486,9 @@ def _collect_spec_index_paths(trellis_dir: Path, allowed_pkgs: set | None) -> li
489
486
  return paths
490
487
 
491
488
 
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.name == "archive":
502
- continue
503
- # A topic is a note, or a directory: `mini-trellis migrate` folds
504
- # each Trellis task into one so its evidence sits next to its notes.
505
- if path.is_file() and path.suffix.lower() == ".md":
506
- topics.append(f".trellis/research/{path.name}")
507
- elif path.is_dir():
508
- topics.append(f".trellis/research/{path.name}/")
509
- except OSError:
510
- return []
511
- return topics
512
-
513
-
514
489
  def _build_compact_current_state(
515
490
  trellis_dir: Path,
516
491
  spec_index_paths: list[str],
517
- research_topics: list[str],
518
492
  ) -> str:
519
493
  repo_root = trellis_dir.parent
520
494
  lines: list[str] = []
@@ -540,15 +514,34 @@ def _build_compact_current_state(
540
514
  if spec_index_paths:
541
515
  lines.append(f"Spec indexes: {len(spec_index_paths)} available.")
542
516
 
543
- if research_topics:
544
- lines.append(f"Research notes: {len(research_topics)} in .trellis/research/.")
545
- else:
546
- lines.append("Research notes: none yet. Write .trellis/research/<topic>.md.")
517
+ lines.append("Research: use `mini-trellis mem recall <query>` when relevant.")
547
518
 
548
519
  return "\n".join(lines)
549
520
 
550
521
 
551
- def main():
522
+ def _write_runtime_status(trellis_dir: Path, platform: str | None, status: str, output_chars: int = 0, error_category: str | None = None, context_key: str | None = None, content_hash: str | None = None, source: str | None = None) -> None:
523
+ """Write bounded diagnostic metadata; injected text is never persisted."""
524
+ try:
525
+ host = {"claude": "claude-code", "droid": "factory"}.get(platform or "", platform or "unknown")
526
+ target = trellis_dir / ".runtime" / "hooks" / f"{host}.json"
527
+ target.parent.mkdir(parents=True, exist_ok=True)
528
+ payload = {"schema": 1, "platform": host, "last_hook_at": datetime.now(timezone.utc).isoformat(), "last_status": status, "last_output_chars": max(0, int(output_chars))}
529
+ if error_category: payload["last_error_category"] = error_category
530
+ if content_hash: payload["last_content_hash"] = content_hash
531
+ if source: payload["last_source"] = source
532
+ with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=target.parent,
533
+ prefix=".hook-", delete=False) as handle:
534
+ temp = Path(handle.name)
535
+ handle.write(json.dumps(payload, sort_keys=True) + "\n")
536
+ try:
537
+ os.replace(temp, target)
538
+ finally:
539
+ temp.unlink(missing_ok=True)
540
+ except (OSError, TypeError, ValueError):
541
+ print("mini-trellis: hook diagnostic write failed (state-write)", file=sys.stderr)
542
+
543
+
544
+ def _main_impl():
552
545
  if should_skip_injection():
553
546
  sys.exit(0)
554
547
 
@@ -562,6 +555,7 @@ def main():
562
555
  # Try platform-specific env vars, hook cwd, fallback to cwd
563
556
  project_dir_env_vars = [
564
557
  "CLAUDE_PROJECT_DIR",
558
+ "CODEX_PROJECT_DIR",
565
559
  "QODER_PROJECT_DIR",
566
560
  "CODEBUDDY_PROJECT_DIR",
567
561
  "FACTORY_PROJECT_DIR",
@@ -582,6 +576,8 @@ def main():
582
576
  project_dir = Path(_normalize_windows_shell_path(hook_input.get("cwd", "."))).resolve()
583
577
 
584
578
  trellis_dir = project_dir / ".trellis"
579
+ global _LAST_PROJECT_DIR
580
+ _LAST_PROJECT_DIR = project_dir
585
581
  context_key = _resolve_context_key(trellis_dir, hook_input)
586
582
  _persist_context_key_for_bash(context_key)
587
583
 
@@ -595,7 +591,6 @@ def main():
595
591
  output = StringIO()
596
592
 
597
593
  spec_index_paths = _collect_spec_index_paths(trellis_dir, allowed_pkgs)
598
- research_topics = _collect_research_topics(trellis_dir)
599
594
  source = hook_input.get("source") if isinstance(hook_input.get("source"), str) else ""
600
595
 
601
596
  output.write("""<session-context>
@@ -603,8 +598,6 @@ mini-trellis SessionStart context. Orient from journal, spec, and research.
603
598
  </session-context>
604
599
 
605
600
  """)
606
- output.write(FIRST_REPLY_NOTICE)
607
- output.write("\n\n")
608
601
 
609
602
  # Legacy migration warning
610
603
  legacy_warning = _check_legacy_spec(trellis_dir, is_mono, packages)
@@ -612,31 +605,29 @@ mini-trellis SessionStart context. Orient from journal, spec, and research.
612
605
  output.write(f"<migration-warning>\n{legacy_warning}\n</migration-warning>\n\n")
613
606
 
614
607
  output.write("<current-state>\n")
615
- output.write(_build_compact_current_state(trellis_dir, spec_index_paths, research_topics))
608
+ output.write(_build_compact_current_state(trellis_dir, spec_index_paths))
616
609
  output.write("\n</current-state>\n\n")
617
610
 
618
611
  output.write("<guidelines>\n")
619
612
  output.write(
620
613
  "Memory: journal is git-durable session notes (`/mini-trellis:remember` or "
621
- "`python3 ./.trellis/scripts/add_session.py`). Cross-session dialogue is "
622
- "`mini-trellis mem list|search|context|extract`.\n"
614
+ "`python3 ./.trellis/scripts/add_session.py`). For relevant prior knowledge, use "
615
+ "`mini-trellis mem recall <query>`. If the excerpt already answers the question "
616
+ "with its source and conditions, cite it and stop; use `mini-trellis mem read <ref>` "
617
+ "only for missing context or qualifiers. Do not repeat a sufficient lookup.\n"
623
618
  "Research lives in `.trellis/research/<topic>.md`, or in "
624
619
  "`.trellis/research/<topic>/` when a topic brings evidence files with it; "
625
620
  "promote durable boundaries into `.trellis/spec/` as short markdown.\n\n"
621
+ "Record when a decision is confirmed, a research finding is worth keeping, "
622
+ "or the session/compact is ending. Keep confirmed rules short and faithful; "
623
+ "leave unconfirmed scope, exceptions, and implementation choices open or label "
624
+ "them as inference, not part of the contract. Update the existing topic first, read back "
625
+ "the changed rule, then run add_session.py with `--topic <actual-path>` so the "
626
+ "journal links the file. Verify the journal too; journal-only or topic-only "
627
+ "writes are partial and must be reported as such. Do not record every turn, "
628
+ "and do not create a git commit unless the user explicitly asks.\n\n"
626
629
  )
627
630
 
628
- if spec_index_paths:
629
- output.write("## Spec indexes (read on demand)\n")
630
- for p in spec_index_paths:
631
- output.write(f"- {p}\n")
632
- output.write("\n")
633
-
634
- if research_topics:
635
- output.write("## Research notes (read on demand)\n")
636
- for p in research_topics:
637
- output.write(f"- {p}\n")
638
- output.write("\n")
639
-
640
631
  if source == "compact":
641
632
  output.write(
642
633
  "This SessionStart was triggered by compact. If durable decisions "
@@ -650,15 +641,46 @@ Context loaded. Use journal, spec, research, and `mini-trellis mem` on demand. R
650
641
  </ready>""")
651
642
 
652
643
  context_text = output.getvalue()
644
+ if len(context_text) > MAX_CONTEXT_CHARS:
645
+ tail = context_text[-300:]
646
+ context_text = (
647
+ context_text[: MAX_CONTEXT_CHARS - len(tail) - 80]
648
+ + "\n[mini-trellis context truncated; read files on demand]\n"
649
+ + tail
650
+ )
651
+
652
+ platform = _detect_platform(hook_input)
653
+ content_hash = hashlib.sha256(context_text.encode("utf-8")).hexdigest()[:24]
653
654
 
654
655
  # Kiro (CLI trellis agent agentSpawn) adds a hook's stdout directly to the
655
656
  # conversation context — no JSON envelope. Emit the bare overview text.
656
657
  # Conditionally isolated: all other platforms keep the JSON path below.
657
658
  if _detect_platform(hook_input) == "kiro":
658
659
  print(context_text, flush=True)
660
+ _write_runtime_status(trellis_dir, platform, "ok", len(context_text), context_key=context_key, content_hash=content_hash, source=source)
661
+ return
662
+
663
+ # Missing identity fails open. compact/clear/resume always deliver again.
664
+ context_dir = trellis_dir / ".runtime" / "context" / (platform or "unknown")
665
+ status_path = None
666
+ if context_key:
667
+ context_hash = hashlib.sha256(context_key.encode("utf-8")).hexdigest()[:24]
668
+ status_path = context_dir / f"{context_hash}.json"
669
+ try:
670
+ previous = (
671
+ json.loads(status_path.read_text(encoding="utf-8"))
672
+ if status_path is not None
673
+ else {}
674
+ )
675
+ except (OSError, ValueError):
676
+ previous = {}
677
+ if not isinstance(previous, dict):
678
+ previous = {}
679
+ if source == "startup" and context_key and previous.get("source") == source and previous.get("content_hash") == content_hash:
680
+ _write_runtime_status(trellis_dir, platform, "deduped", output_chars=0, context_key=context_key, content_hash=content_hash, source=source)
681
+ print("{}", flush=True)
659
682
  return
660
683
 
661
- platform = _detect_platform(hook_input)
662
684
  result: dict[str, object] = {
663
685
  # Claude Code / Qoder / CodeBuddy / Droid / Gemini / Copilot / Trae /
664
686
  # ZCode format.
@@ -667,17 +689,39 @@ Context loaded. Use journal, spec, research, and `mini-trellis mem` on demand. R
667
689
  "additionalContext": context_text,
668
690
  },
669
691
  }
670
- # Cursor sessionStart format (top-level snake_case per Cursor docs).
671
- # ZCode reads BOTH `hookSpecificOutput.additionalContext` and top-level
672
- # `additional_context` without deduplication, so emitting both keys would
673
- # duplicate the context in the conversation. Keep the previous shared output
674
- # shape for every other platform.
675
- if platform != "zcode":
692
+ # Cursor and the other shared hosts use the top-level compatibility field.
693
+ # Codex's SessionStart contract accepts the nested shape above; leaving the
694
+ # extra field out there avoids an ambiguous duplicate. ZCode already had
695
+ # the same exception for its own parser.
696
+ if platform not in {"codex", "zcode"}:
676
697
  result["additional_context"] = context_text
677
698
 
678
699
  # Output JSON - stdout is already configured for UTF-8
679
700
  print(json.dumps(result, ensure_ascii=False), flush=True)
701
+ _write_runtime_status(trellis_dir, platform, "ok", len(context_text), context_key=context_key, content_hash=content_hash, source=source)
702
+ try:
703
+ if status_path is not None:
704
+ status_path.parent.mkdir(parents=True, exist_ok=True)
705
+ temp = status_path.with_name(f".{status_path.name}.{os.getpid()}.tmp")
706
+ temp.write_text(
707
+ json.dumps({"source": source, "content_hash": content_hash}),
708
+ encoding="utf-8",
709
+ )
710
+ os.replace(temp, status_path)
711
+ except OSError:
712
+ pass
680
713
 
681
714
 
682
715
  if __name__ == "__main__":
683
- main()
716
+ try:
717
+ _main_impl()
718
+ except Exception as exc:
719
+ project = os.environ.get("CLAUDE_PROJECT_DIR") or os.environ.get("CODEX_PROJECT_DIR")
720
+ project_path = Path(_normalize_windows_shell_path(project)).resolve() if project else _LAST_PROJECT_DIR
721
+ if project_path:
722
+ _write_runtime_status(
723
+ project_path / ".trellis" if project_path else Path(".trellis"),
724
+ _detect_platform({}), "error", error_category=type(exc).__name__,
725
+ )
726
+ print(f"mini-trellis SessionStart failed: {type(exc).__name__}", file=sys.stderr)
727
+ raise
@@ -17,10 +17,10 @@ max_journal_lines: 2000
17
17
  #-------------------------------------------------------------------------------
18
18
 
19
19
  # Auto-commit journal/index after add_session.py.
20
- # - true (default): auto-stage and auto-commit journal files
21
- # - false: write files only; you decide when to git add / commit
20
+ # - true: auto-stage and auto-commit journal files
21
+ # - false (new-install default): write files only; you decide when to commit
22
22
  #
23
- # session_auto_commit: true
23
+ session_auto_commit: false
24
24
 
25
25
  #-------------------------------------------------------------------------------
26
26
  # Monorepo / Packages