mini-trellis 0.2.0 → 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 (30) hide show
  1. package/README.md +100 -105
  2. package/dist/commands/doctor.d.ts.map +1 -1
  3. package/dist/commands/doctor.js +80 -5
  4. package/dist/commands/doctor.js.map +1 -1
  5. package/dist/commands/init.js +1 -1
  6. package/dist/commands/init.js.map +1 -1
  7. package/dist/commands/mem.d.ts +2 -0
  8. package/dist/commands/mem.d.ts.map +1 -1
  9. package/dist/commands/mem.js +85 -2
  10. package/dist/commands/mem.js.map +1 -1
  11. package/dist/configurators/shared.d.ts.map +1 -1
  12. package/dist/configurators/shared.js +2 -2
  13. package/dist/configurators/shared.js.map +1 -1
  14. package/dist/templates/codex/config.toml +5 -5
  15. package/dist/templates/codex/hooks.json +4 -1
  16. package/dist/templates/common/bundled-skills/mini-trellis-session-insight/SKILL.md +13 -7
  17. package/dist/templates/common/bundled-skills/mini-trellis-session-insight/references/cli-quick-reference.md +24 -11
  18. package/dist/templates/common/bundled-skills/mini-trellis-session-insight/references/triggering-patterns.md +18 -10
  19. package/dist/templates/common/commands/remember.md +17 -3
  20. package/dist/templates/common/skills/update-spec.md +4 -0
  21. package/dist/templates/markdown/agents.md +7 -1
  22. package/dist/templates/markdown/spec/guides/mini-memory.md.txt +15 -8
  23. package/dist/templates/opencode/lib/session-utils.js +6 -51
  24. package/dist/templates/opencode/plugins/session-start.js +3 -16
  25. package/dist/templates/pi/extensions/mini-trellis/index.ts.txt +27 -87
  26. package/dist/templates/shared-hooks/session-start.py +99 -60
  27. package/dist/templates/trellis/config.yaml +3 -3
  28. package/dist/templates/trellis/scripts/add_session.py +95 -9
  29. package/dist/templates/trellis/scripts/common/config.py +4 -3
  30. package/package.json +3 -3
@@ -6,25 +6,32 @@
6
6
 
7
7
  | Layer | Path | Role |
8
8
  |-------|------|------|
9
- | Journal | `.trellis/workspace/<dev>/journal-*.md` | Git-durable session notes |
9
+ | Journal | `.trellis/workspace/<dev>/journal-*.md` | Per-developer session notes |
10
10
  | Research | `.trellis/research/<topic>.md` | Topic inbox. `README.md` is not a topic |
11
11
  | Spec | `.trellis/spec/**/index.md`, then linked files | Durable contracts. Short markdown |
12
- | Dialogue | `mini-trellis mem list\|search\|context\|extract` | Cross-session chat |
12
+ | Recall | `mini-trellis mem recall "<query>"` | Project Markdown and cross-session dialogue |
13
13
 
14
14
  ## SessionStart contract
15
15
 
16
- - Inject the active journal path, spec **index** paths, and research topic files.
17
- - Do **not** list individual spec articles — only `index.md`.
18
- - Do **not** inject `.trellis/research/archive/`.
19
- - Compact source: remind the user to run remember (`/mini-trellis:remember`, `/mini-trellis-remember` on Pi, `$mini-trellis-remember` on Codex) if durable notes from the compacted window are missing.
16
+ - Deliver a short memory entry and the active journal path; do not enumerate research topics or inject their bodies.
17
+ - Retrieve relevant rules and research on demand with `mini-trellis mem recall "<query>"`. Use `mini-trellis mem read "<ref>"` only when excerpts lack necessary context or conditions.
18
+ - Archived research remains searchable and is marked archived; it is not injected at startup.
19
+ - After compact, restore the short entry and remember any confirmed conclusions that have not been saved.
20
20
 
21
21
  ## Remember
22
22
 
23
+ Save confirmed decisions and reusable findings in the relevant spec/research topic, updating an existing topic when possible. Check the saved content, then record a short journal entry linking to it:
24
+
25
+ Keep confirmed rules short and faithful. Unconfirmed scope, exceptions, and implementation choices stay open or are labeled as inference, not added to the contract.
26
+
23
27
  ```bash
24
28
  python3 ./.trellis/scripts/add_session.py \
25
29
  --title "Short title" \
26
30
  --commit - \
27
- --summary "What happened, what was decided, what to reuse"
31
+ --summary "What happened, what was decided, what to reuse" \
32
+ --topic .trellis/research/example.md
28
33
  ```
29
34
 
30
- If the session produced reusable research, write `.trellis/research/<topic>.md`. Promote a note into `.trellis/spec/` only if the boundary still holds, then link it from the matching `index.md`. Cold research: `git mv` into `.trellis/research/archive/`.
35
+ Use the actual topic path; omit `--topic` for a handoff without a topic. The script writes journal/index and a relative topic link; it does not edit the topic. Verify the files before reporting completion. Skip ordinary changes and unconfirmed ideas. New notes follow the discussion language; updates keep the original document's language.
36
+
37
+ Promote durable boundaries into `.trellis/spec/` and link them from the matching `index.md`. Cold research can move into `.trellis/research/archive/`.
@@ -9,10 +9,6 @@ const PYTHON_CMD = platform() === "win32" ? "python" : "python3"
9
9
 
10
10
  const MAX_CONTEXT_CHARS = 4000
11
11
 
12
- const FIRST_REPLY_NOTICE = `<first-reply-notice>
13
- On the first visible assistant reply, briefly acknowledge that mini-trellis SessionStart context loaded, then continue with the user's request. Use the user's language; otherwise say \`mini-trellis SessionStart ✓\`. This is one-shot and must not be repeated.
14
- </first-reply-notice>`
15
-
16
12
  function loadTrellisConfig(directory, contextKey = null) {
17
13
  const scriptPath = join(directory, ".trellis", "scripts", "get_context.py")
18
14
  if (!existsSync(scriptPath)) {
@@ -117,27 +113,6 @@ function resolveSpecScope(config) {
117
113
  return null
118
114
  }
119
115
 
120
- function collectResearchTopics(directory) {
121
- const researchDir = join(directory, ".trellis", "research")
122
- if (!existsSync(researchDir)) return []
123
- try {
124
- return readdirSync(researchDir, { withFileTypes: true })
125
- .filter(entry => {
126
- if (entry.name.startsWith(".") || entry.name.toLowerCase() === "readme.md") return false
127
- if (entry.name === "archive") return false
128
- // A topic is a note, or a directory: `mini-trellis migrate` folds each
129
- // Trellis task into one so its evidence sits next to its notes.
130
- if (entry.isDirectory()) return true
131
- return entry.isFile() && entry.name.toLowerCase().endsWith(".md")
132
- })
133
- .map(entry => ({ name: entry.name, dir: entry.isDirectory() }))
134
- .sort((a, b) => a.name.localeCompare(b.name))
135
- .map(topic => `.trellis/research/${topic.name}${topic.dir ? "/" : ""}`)
136
- } catch {
137
- return []
138
- }
139
- }
140
-
141
116
  function collectSpecIndexPaths(directory, allowedPkgs) {
142
117
  const specDir = join(directory, ".trellis", "spec")
143
118
  const paths = []
@@ -216,7 +191,7 @@ function runGit(directory, args) {
216
191
  }
217
192
  }
218
193
 
219
- function buildCompactCurrentState(ctx, specIndexPaths, researchTopics) {
194
+ function buildCompactCurrentState(ctx, specIndexPaths) {
220
195
  const directory = ctx.directory
221
196
  const lines = []
222
197
  lines.push(`Developer: ${readDeveloper(directory)}`)
@@ -249,11 +224,7 @@ function buildCompactCurrentState(ctx, specIndexPaths, researchTopics) {
249
224
  lines.push(`Spec indexes: ${specIndexPaths.length} available.`)
250
225
  }
251
226
 
252
- if (researchTopics.length > 0) {
253
- lines.push(`Research notes: ${researchTopics.length} in .trellis/research/.`)
254
- } else {
255
- lines.push("Research notes: none yet. Write .trellis/research/<topic>.md.")
256
- }
227
+ lines.push("Research: use `mini-trellis mem recall <query>` when relevant.")
257
228
 
258
229
  return lines.join("\n")
259
230
  }
@@ -267,14 +238,12 @@ export function buildSessionContext(ctx, platformInput = null) {
267
238
  const config = loadTrellisConfig(directory, contextKey)
268
239
  const allowedPkgs = resolveSpecScope(config)
269
240
  const paths = collectSpecIndexPaths(directory, allowedPkgs)
270
- const researchTopics = collectResearchTopics(directory)
271
241
 
272
242
  const parts = []
273
243
 
274
244
  parts.push(`<session-context>
275
245
  mini-trellis SessionStart context. Orient from journal, spec, and research.
276
246
  </session-context>`)
277
- parts.push(FIRST_REPLY_NOTICE)
278
247
 
279
248
  const legacyWarning = checkLegacySpec(directory, config)
280
249
  if (legacyWarning) {
@@ -282,35 +251,21 @@ mini-trellis SessionStart context. Orient from journal, spec, and research.
282
251
  }
283
252
 
284
253
  parts.push("<current-state>")
285
- parts.push(buildCompactCurrentState(ctx, paths, researchTopics))
254
+ parts.push(buildCompactCurrentState(ctx, paths))
286
255
  parts.push("</current-state>")
287
256
 
288
257
  parts.push("<guidelines>")
289
258
  parts.push(
290
259
  "Memory: journal is git-durable session notes (`/mini-trellis:remember` or " +
291
- "`python3 ./.trellis/scripts/add_session.py`). Cross-session dialogue is " +
292
- "`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" +
293
262
  "Research lives in `.trellis/research/<topic>.md`, or in " +
294
263
  "`.trellis/research/<topic>/` when a topic brings evidence files with it; " +
295
264
  "promote durable boundaries into `.trellis/spec/` as short markdown.\n"
296
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"
297
267
  )
298
268
 
299
- if (paths.length > 0) {
300
- parts.push("## Spec indexes (read on demand)")
301
- for (const p of paths) {
302
- parts.push(`- ${p}`)
303
- }
304
- parts.push("")
305
- }
306
-
307
- if (researchTopics.length > 0) {
308
- parts.push("## Research notes (read on demand)")
309
- for (const p of researchTopics) {
310
- parts.push(`- ${p}`)
311
- }
312
- parts.push("")
313
- }
314
269
 
315
270
  parts.push("</guidelines>")
316
271
 
@@ -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,19 +44,13 @@ export default async ({ directory }) => {
51
44
  return
52
45
  }
53
46
 
47
+ const context = buildSessionContext(ctx, platformInput)
54
48
  if (messages?.some(message =>
55
49
  message?.parts?.some(part =>
56
- part?.synthetic === true &&
57
- typeof part.text === "string" &&
58
- part.text.includes("<session-context>")))) {
59
- debugLog("session", "Skipping - SessionStart context already injected")
50
+ part?.synthetic === true && part.text === context))) {
51
+ debugLog("session", "Skipping - same SessionStart content already injected")
60
52
  return
61
53
  }
62
-
63
- let context = buildSessionContext(ctx, platformInput)
64
- if (transcriptHasAssistantMessage(messages)) {
65
- context = stripFirstReplyNotice(context)
66
- }
67
54
  debugLog("session", "Built context, length:", context.length)
68
55
  prependEphemeralText(messages, context)
69
56
  } catch (error) {
@@ -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,53 +76,26 @@ function activeJournal(root: string): string | null {
103
76
  }
104
77
 
105
78
  function buildStartupContext(root: string): string {
106
- const MAX_CONTEXT_CHARS = 4000;
107
- const spec = collectSpecIndexPaths(root);
108
- const research = collectResearchTopics(root);
109
79
  const journal = activeJournal(root);
110
- const lines: string[] = [
111
- "<session-context>",
112
- "mini-trellis SessionStart context. Orient from journal, spec, and research.",
113
- "</session-context>",
114
- "",
115
- "<current-state>",
116
- ];
117
- if (journal) lines.push(`Journal: ${journal}`);
118
- if (spec.length) lines.push(`Spec indexes: ${spec.length} available.`);
119
- lines.push(
120
- research.length
121
- ? `Research notes: ${research.length} in .trellis/research/.`
122
- : "Research notes: none yet. Write .trellis/research/<topic>.md.",
123
- );
124
- lines.push("</current-state>", "", "<guidelines>");
125
- lines.push(
126
- "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`.",
127
- "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.",
128
- "Record confirmed decisions, useful research findings, and session/compact endings. Do not record every turn or create a git commit unless the user asks.",
129
- );
130
- if (spec.length) {
131
- lines.push("", "## Spec indexes (read on demand)");
132
- for (const p of spec) lines.push(`- ${p}`);
133
- }
134
- if (research.length) {
135
- lines.push("", "## Research notes (read on demand)");
136
- for (const p of research) lines.push(`- ${p}`);
137
- }
138
- lines.push(
139
- "</guidelines>",
140
- "",
141
- "<ready>",
142
- "Context loaded. Use journal, spec, research, and `mini-trellis mem` on demand. Remember at session end or after compact.",
143
- "</ready>",
144
- );
145
- const context = lines.join("\n");
146
- if (context.length <= MAX_CONTEXT_CHARS) return context;
147
- const tail = context.slice(-300);
148
- return (
149
- context.slice(0, MAX_CONTEXT_CHARS - tail.length - 80) +
150
- "\n[mini-trellis context truncated; read files on demand]\n" +
151
- tail
152
- );
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.` : "");
153
99
  }
154
100
 
155
101
  export default function trellisExtension(pi: {
@@ -160,17 +106,11 @@ export default function trellisExtension(pi: {
160
106
  }): void {
161
107
  if (process.env.TRELLIS_SUBAGENT_CHILD === "1") return;
162
108
  const root = findRoot(process.cwd() || homedir());
163
- const startup = buildStartupContext(root);
164
-
165
- pi.on?.("session_start", (_event, ctx) => {
166
- ctx?.ui?.notify?.(
167
- "mini-trellis context is available. Use /mini-trellis-remember to persist journal notes.",
168
- "info",
169
- );
170
- });
171
109
 
172
110
  pi.on?.("before_agent_start", (event) => {
173
111
  const cur = (event as { systemPrompt?: string }).systemPrompt ?? "";
112
+ const startup = buildStartupContext(root);
113
+ if (cur.includes(startup)) return { systemPrompt: cur };
174
114
  return {
175
115
  systemPrompt: [cur, startup].filter(Boolean).join("\n\n"),
176
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
 
@@ -69,10 +72,8 @@ def _normalize_windows_shell_path(path_str: str) -> str:
69
72
 
70
73
  MAX_CONTEXT_CHARS = 4000
71
74
 
72
- FIRST_REPLY_NOTICE = """<first-reply-notice>
73
- On the first visible assistant reply, briefly acknowledge that mini-trellis SessionStart context loaded, then continue with the user's request. Use the user's language; otherwise say `mini-trellis SessionStart ✓`. This is one-shot and must not be repeated.
74
- </first-reply-notice>"""
75
-
75
+ RUNTIME_STATUS_VERSION = 1
76
+ _LAST_PROJECT_DIR: Path | None = None
76
77
 
77
78
  # Force UTF-8 on stdin/stdout/stderr on Windows. Default codepage there is
78
79
  # cp936 / cp1252 / etc. — non-ASCII content (Chinese task names, prd snippets)
@@ -177,6 +178,7 @@ def _detect_platform(input_data: dict) -> str | None:
177
178
  env_map = {
178
179
  "ZCODE_PROJECT_DIR": "zcode",
179
180
  "CURSOR_PROJECT_DIR": "cursor",
181
+ "CODEX_PROJECT_DIR": "codex",
180
182
  "CODEBUDDY_PROJECT_DIR": "codebuddy",
181
183
  "FACTORY_PROJECT_DIR": "droid",
182
184
  "GEMINI_PROJECT_DIR": "gemini",
@@ -484,32 +486,9 @@ def _collect_spec_index_paths(trellis_dir: Path, allowed_pkgs: set | None) -> li
484
486
  return paths
485
487
 
486
488
 
487
- def _collect_research_topics(trellis_dir: Path) -> list[str]:
488
- research_dir = trellis_dir / "research"
489
- if not research_dir.is_dir():
490
- return []
491
- topics: list[str] = []
492
- try:
493
- for path in sorted(research_dir.iterdir()):
494
- if path.name.startswith(".") or path.name.lower() == "readme.md":
495
- continue
496
- if path.name == "archive":
497
- continue
498
- # A topic is a note, or a directory: `mini-trellis migrate` folds
499
- # each Trellis task into one so its evidence sits next to its notes.
500
- if path.is_file() and path.suffix.lower() == ".md":
501
- topics.append(f".trellis/research/{path.name}")
502
- elif path.is_dir():
503
- topics.append(f".trellis/research/{path.name}/")
504
- except OSError:
505
- return []
506
- return topics
507
-
508
-
509
489
  def _build_compact_current_state(
510
490
  trellis_dir: Path,
511
491
  spec_index_paths: list[str],
512
- research_topics: list[str],
513
492
  ) -> str:
514
493
  repo_root = trellis_dir.parent
515
494
  lines: list[str] = []
@@ -535,15 +514,34 @@ def _build_compact_current_state(
535
514
  if spec_index_paths:
536
515
  lines.append(f"Spec indexes: {len(spec_index_paths)} available.")
537
516
 
538
- if research_topics:
539
- lines.append(f"Research notes: {len(research_topics)} in .trellis/research/.")
540
- else:
541
- lines.append("Research notes: none yet. Write .trellis/research/<topic>.md.")
517
+ lines.append("Research: use `mini-trellis mem recall <query>` when relevant.")
542
518
 
543
519
  return "\n".join(lines)
544
520
 
545
521
 
546
- 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():
547
545
  if should_skip_injection():
548
546
  sys.exit(0)
549
547
 
@@ -557,6 +555,7 @@ def main():
557
555
  # Try platform-specific env vars, hook cwd, fallback to cwd
558
556
  project_dir_env_vars = [
559
557
  "CLAUDE_PROJECT_DIR",
558
+ "CODEX_PROJECT_DIR",
560
559
  "QODER_PROJECT_DIR",
561
560
  "CODEBUDDY_PROJECT_DIR",
562
561
  "FACTORY_PROJECT_DIR",
@@ -577,6 +576,8 @@ def main():
577
576
  project_dir = Path(_normalize_windows_shell_path(hook_input.get("cwd", "."))).resolve()
578
577
 
579
578
  trellis_dir = project_dir / ".trellis"
579
+ global _LAST_PROJECT_DIR
580
+ _LAST_PROJECT_DIR = project_dir
580
581
  context_key = _resolve_context_key(trellis_dir, hook_input)
581
582
  _persist_context_key_for_bash(context_key)
582
583
 
@@ -590,7 +591,6 @@ def main():
590
591
  output = StringIO()
591
592
 
592
593
  spec_index_paths = _collect_spec_index_paths(trellis_dir, allowed_pkgs)
593
- research_topics = _collect_research_topics(trellis_dir)
594
594
  source = hook_input.get("source") if isinstance(hook_input.get("source"), str) else ""
595
595
 
596
596
  output.write("""<session-context>
@@ -598,8 +598,6 @@ mini-trellis SessionStart context. Orient from journal, spec, and research.
598
598
  </session-context>
599
599
 
600
600
  """)
601
- output.write(FIRST_REPLY_NOTICE)
602
- output.write("\n\n")
603
601
 
604
602
  # Legacy migration warning
605
603
  legacy_warning = _check_legacy_spec(trellis_dir, is_mono, packages)
@@ -607,34 +605,29 @@ mini-trellis SessionStart context. Orient from journal, spec, and research.
607
605
  output.write(f"<migration-warning>\n{legacy_warning}\n</migration-warning>\n\n")
608
606
 
609
607
  output.write("<current-state>\n")
610
- 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))
611
609
  output.write("\n</current-state>\n\n")
612
610
 
613
611
  output.write("<guidelines>\n")
614
612
  output.write(
615
613
  "Memory: journal is git-durable session notes (`/mini-trellis:remember` or "
616
- "`python3 ./.trellis/scripts/add_session.py`). Cross-session dialogue is "
617
- "`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"
618
618
  "Research lives in `.trellis/research/<topic>.md`, or in "
619
619
  "`.trellis/research/<topic>/` when a topic brings evidence files with it; "
620
620
  "promote durable boundaries into `.trellis/spec/` as short markdown.\n\n"
621
621
  "Record when a decision is confirmed, a research finding is worth keeping, "
622
- "or the session/compact is ending. Do not record every turn, and do not "
623
- "create a git commit unless the user explicitly asks.\n\n"
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"
624
629
  )
625
630
 
626
- if spec_index_paths:
627
- output.write("## Spec indexes (read on demand)\n")
628
- for p in spec_index_paths:
629
- output.write(f"- {p}\n")
630
- output.write("\n")
631
-
632
- if research_topics:
633
- output.write("## Research notes (read on demand)\n")
634
- for p in research_topics:
635
- output.write(f"- {p}\n")
636
- output.write("\n")
637
-
638
631
  if source == "compact":
639
632
  output.write(
640
633
  "This SessionStart was triggered by compact. If durable decisions "
@@ -656,14 +649,38 @@ Context loaded. Use journal, spec, research, and `mini-trellis mem` on demand. R
656
649
  + tail
657
650
  )
658
651
 
652
+ platform = _detect_platform(hook_input)
653
+ content_hash = hashlib.sha256(context_text.encode("utf-8")).hexdigest()[:24]
654
+
659
655
  # Kiro (CLI trellis agent agentSpawn) adds a hook's stdout directly to the
660
656
  # conversation context — no JSON envelope. Emit the bare overview text.
661
657
  # Conditionally isolated: all other platforms keep the JSON path below.
662
658
  if _detect_platform(hook_input) == "kiro":
663
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)
664
682
  return
665
683
 
666
- platform = _detect_platform(hook_input)
667
684
  result: dict[str, object] = {
668
685
  # Claude Code / Qoder / CodeBuddy / Droid / Gemini / Copilot / Trae /
669
686
  # ZCode format.
@@ -672,17 +689,39 @@ Context loaded. Use journal, spec, research, and `mini-trellis mem` on demand. R
672
689
  "additionalContext": context_text,
673
690
  },
674
691
  }
675
- # Cursor sessionStart format (top-level snake_case per Cursor docs).
676
- # ZCode reads BOTH `hookSpecificOutput.additionalContext` and top-level
677
- # `additional_context` without deduplication, so emitting both keys would
678
- # duplicate the context in the conversation. Keep the previous shared output
679
- # shape for every other platform.
680
- 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"}:
681
697
  result["additional_context"] = context_text
682
698
 
683
699
  # Output JSON - stdout is already configured for UTF-8
684
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
685
713
 
686
714
 
687
715
  if __name__ == "__main__":
688
- 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