mini-trellis 0.2.0 → 0.2.2
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.
- package/README.md +124 -101
- package/dist/commands/doctor.d.ts.map +1 -1
- package/dist/commands/doctor.js +90 -7
- package/dist/commands/doctor.js.map +1 -1
- package/dist/commands/init.js +1 -1
- package/dist/commands/init.js.map +1 -1
- package/dist/commands/mem.d.ts +2 -0
- package/dist/commands/mem.d.ts.map +1 -1
- package/dist/commands/mem.js +85 -2
- package/dist/commands/mem.js.map +1 -1
- package/dist/commands/migrate.d.ts +8 -0
- package/dist/commands/migrate.d.ts.map +1 -1
- package/dist/commands/migrate.js +123 -4
- package/dist/commands/migrate.js.map +1 -1
- package/dist/commands/refresh.d.ts +1 -1
- package/dist/commands/refresh.d.ts.map +1 -1
- package/dist/commands/refresh.js +19 -1
- package/dist/commands/refresh.js.map +1 -1
- package/dist/configurators/shared.d.ts.map +1 -1
- package/dist/configurators/shared.js +2 -2
- package/dist/configurators/shared.js.map +1 -1
- package/dist/templates/codex/config.toml +5 -5
- package/dist/templates/codex/hooks.json +4 -1
- package/dist/templates/common/bundled-skills/mini-trellis-session-insight/SKILL.md +13 -7
- package/dist/templates/common/bundled-skills/mini-trellis-session-insight/references/cli-quick-reference.md +24 -11
- package/dist/templates/common/bundled-skills/mini-trellis-session-insight/references/triggering-patterns.md +18 -10
- package/dist/templates/common/commands/remember.md +18 -3
- package/dist/templates/common/skills/update-spec.md +5 -0
- package/dist/templates/markdown/agents.md +7 -1
- package/dist/templates/markdown/spec/guides/mini-memory.md.txt +15 -8
- package/dist/templates/opencode/lib/session-utils.js +11 -56
- package/dist/templates/opencode/plugins/session-start.js +3 -16
- package/dist/templates/pi/extensions/mini-trellis/index.ts.txt +22 -87
- package/dist/templates/shared-hooks/session-start.py +101 -68
- package/dist/templates/trellis/config.yaml +3 -3
- package/dist/templates/trellis/scripts/add_session.py +95 -9
- package/dist/templates/trellis/scripts/common/config.py +5 -5
- package/dist/utils/uninstall-scrubbers.d.ts +8 -0
- package/dist/utils/uninstall-scrubbers.d.ts.map +1 -1
- package/dist/utils/uninstall-scrubbers.js +66 -18
- package/dist/utils/uninstall-scrubbers.js.map +1 -1
- package/package.json +3 -3
- package/dist/templates/trellis/scripts/common/cli_adapter.py +0 -950
- package/dist/templates/trellis/scripts/common/task_context.py +0 -470
- package/dist/templates/trellis/scripts/common/task_queue.py +0 -188
- package/dist/templates/trellis/scripts/common/task_store.py +0 -1930
- package/dist/templates/trellis/scripts/common/task_utils.py +0 -498
|
@@ -29,43 +29,16 @@ function findRoot(start: string): string {
|
|
|
29
29
|
return start;
|
|
30
30
|
}
|
|
31
31
|
|
|
32
|
-
function
|
|
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
|
-
|
|
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
|
-
|
|
61
|
-
|
|
62
|
-
|
|
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
|
-
|
|
40
|
+
return 0;
|
|
67
41
|
}
|
|
68
|
-
return paths;
|
|
69
42
|
}
|
|
70
43
|
|
|
71
44
|
function readDeveloper(root: string): string | null {
|
|
@@ -103,53 +76,21 @@ 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
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
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 in \`.trellis/research/<topic>.md\` and lasting rules in \`.trellis/spec/\`.
|
|
89
|
+
A rejected approach that later work should not retry can be recorded and labeled rejected.
|
|
90
|
+
Record with \`python3 ./.trellis/scripts/add_session.py\`. Ordinary edits and unconfirmed
|
|
91
|
+
guesses are not new decisions. Do not create a git commit unless the user explicitly asks.
|
|
92
|
+
</session-context>` + (journal ? `\nJournal: ${journal}` : "") +
|
|
93
|
+
(specCount ? `\nSpec indexes: ${specCount} available.` : "");
|
|
153
94
|
}
|
|
154
95
|
|
|
155
96
|
export default function trellisExtension(pi: {
|
|
@@ -160,17 +101,11 @@ export default function trellisExtension(pi: {
|
|
|
160
101
|
}): void {
|
|
161
102
|
if (process.env.TRELLIS_SUBAGENT_CHILD === "1") return;
|
|
162
103
|
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
104
|
|
|
172
105
|
pi.on?.("before_agent_start", (event) => {
|
|
173
106
|
const cur = (event as { systemPrompt?: string }).systemPrompt ?? "";
|
|
107
|
+
const startup = buildStartupContext(root);
|
|
108
|
+
if (cur.includes(startup)) return { systemPrompt: cur };
|
|
174
109
|
return {
|
|
175
110
|
systemPrompt: [cur, startup].filter(Boolean).join("\n\n"),
|
|
176
111
|
};
|
|
@@ -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
|
-
|
|
73
|
-
|
|
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
|
-
|
|
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
|
|
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,39 +605,28 @@ 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
|
|
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
|
-
"Memory:
|
|
616
|
-
"
|
|
617
|
-
"`mini-trellis mem
|
|
618
|
-
"
|
|
619
|
-
"`.trellis/research
|
|
620
|
-
"
|
|
621
|
-
"
|
|
622
|
-
"
|
|
623
|
-
"create a git commit unless the user
|
|
613
|
+
"Memory: use `mini-trellis mem recall <query>` for prior decisions, rejected "
|
|
614
|
+
"approaches, and project rules. If the excerpt answers the question with its "
|
|
615
|
+
"source and conditions, cite it and stop; use `mini-trellis mem read <ref>` "
|
|
616
|
+
"only for missing context. Do not repeat a sufficient lookup.\n"
|
|
617
|
+
"Research lives in `.trellis/research/`; durable rules belong in `.trellis/spec/`.\n"
|
|
618
|
+
"Record a confirmed decision, a rejected approach worth not retrying, or a useful "
|
|
619
|
+
"handoff with `/mini-trellis:remember` or "
|
|
620
|
+
"`python3 ./.trellis/scripts/add_session.py`. The remember command has the write "
|
|
621
|
+
"steps. Do not record every turn, and do not create a git commit unless the user asks.\n"
|
|
624
622
|
)
|
|
625
623
|
|
|
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
624
|
if source == "compact":
|
|
639
625
|
output.write(
|
|
640
|
-
"This SessionStart
|
|
641
|
-
"
|
|
642
|
-
"
|
|
626
|
+
"This SessionStart follows compact. Details missing from the summary may "
|
|
627
|
+
"still be in local session history: use `mini-trellis mem recall <query>`, "
|
|
628
|
+
"then `mini-trellis mem read <ref>` for the original turns. Record durable "
|
|
629
|
+
"decisions that were not saved yet with `/mini-trellis:remember`.\n"
|
|
643
630
|
)
|
|
644
631
|
output.write("</guidelines>\n\n")
|
|
645
632
|
|
|
@@ -656,14 +643,38 @@ Context loaded. Use journal, spec, research, and `mini-trellis mem` on demand. R
|
|
|
656
643
|
+ tail
|
|
657
644
|
)
|
|
658
645
|
|
|
646
|
+
platform = _detect_platform(hook_input)
|
|
647
|
+
content_hash = hashlib.sha256(context_text.encode("utf-8")).hexdigest()[:24]
|
|
648
|
+
|
|
659
649
|
# Kiro (CLI trellis agent agentSpawn) adds a hook's stdout directly to the
|
|
660
650
|
# conversation context — no JSON envelope. Emit the bare overview text.
|
|
661
651
|
# Conditionally isolated: all other platforms keep the JSON path below.
|
|
662
652
|
if _detect_platform(hook_input) == "kiro":
|
|
663
653
|
print(context_text, flush=True)
|
|
654
|
+
_write_runtime_status(trellis_dir, platform, "ok", len(context_text), context_key=context_key, content_hash=content_hash, source=source)
|
|
655
|
+
return
|
|
656
|
+
|
|
657
|
+
# Missing identity fails open. compact/clear/resume always deliver again.
|
|
658
|
+
context_dir = trellis_dir / ".runtime" / "context" / (platform or "unknown")
|
|
659
|
+
status_path = None
|
|
660
|
+
if context_key:
|
|
661
|
+
context_hash = hashlib.sha256(context_key.encode("utf-8")).hexdigest()[:24]
|
|
662
|
+
status_path = context_dir / f"{context_hash}.json"
|
|
663
|
+
try:
|
|
664
|
+
previous = (
|
|
665
|
+
json.loads(status_path.read_text(encoding="utf-8"))
|
|
666
|
+
if status_path is not None
|
|
667
|
+
else {}
|
|
668
|
+
)
|
|
669
|
+
except (OSError, ValueError):
|
|
670
|
+
previous = {}
|
|
671
|
+
if not isinstance(previous, dict):
|
|
672
|
+
previous = {}
|
|
673
|
+
if source == "startup" and context_key and previous.get("source") == source and previous.get("content_hash") == content_hash:
|
|
674
|
+
_write_runtime_status(trellis_dir, platform, "deduped", output_chars=0, context_key=context_key, content_hash=content_hash, source=source)
|
|
675
|
+
print("{}", flush=True)
|
|
664
676
|
return
|
|
665
677
|
|
|
666
|
-
platform = _detect_platform(hook_input)
|
|
667
678
|
result: dict[str, object] = {
|
|
668
679
|
# Claude Code / Qoder / CodeBuddy / Droid / Gemini / Copilot / Trae /
|
|
669
680
|
# ZCode format.
|
|
@@ -672,17 +683,39 @@ Context loaded. Use journal, spec, research, and `mini-trellis mem` on demand. R
|
|
|
672
683
|
"additionalContext": context_text,
|
|
673
684
|
},
|
|
674
685
|
}
|
|
675
|
-
# Cursor
|
|
676
|
-
#
|
|
677
|
-
#
|
|
678
|
-
#
|
|
679
|
-
|
|
680
|
-
if platform != "zcode":
|
|
686
|
+
# Cursor and the other shared hosts use the top-level compatibility field.
|
|
687
|
+
# Codex's SessionStart contract accepts the nested shape above; leaving the
|
|
688
|
+
# extra field out there avoids an ambiguous duplicate. ZCode already had
|
|
689
|
+
# the same exception for its own parser.
|
|
690
|
+
if platform not in {"codex", "zcode"}:
|
|
681
691
|
result["additional_context"] = context_text
|
|
682
692
|
|
|
683
693
|
# Output JSON - stdout is already configured for UTF-8
|
|
684
694
|
print(json.dumps(result, ensure_ascii=False), flush=True)
|
|
695
|
+
_write_runtime_status(trellis_dir, platform, "ok", len(context_text), context_key=context_key, content_hash=content_hash, source=source)
|
|
696
|
+
try:
|
|
697
|
+
if status_path is not None:
|
|
698
|
+
status_path.parent.mkdir(parents=True, exist_ok=True)
|
|
699
|
+
temp = status_path.with_name(f".{status_path.name}.{os.getpid()}.tmp")
|
|
700
|
+
temp.write_text(
|
|
701
|
+
json.dumps({"source": source, "content_hash": content_hash}),
|
|
702
|
+
encoding="utf-8",
|
|
703
|
+
)
|
|
704
|
+
os.replace(temp, status_path)
|
|
705
|
+
except OSError:
|
|
706
|
+
pass
|
|
685
707
|
|
|
686
708
|
|
|
687
709
|
if __name__ == "__main__":
|
|
688
|
-
|
|
710
|
+
try:
|
|
711
|
+
_main_impl()
|
|
712
|
+
except Exception as exc:
|
|
713
|
+
project = os.environ.get("CLAUDE_PROJECT_DIR") or os.environ.get("CODEX_PROJECT_DIR")
|
|
714
|
+
project_path = Path(_normalize_windows_shell_path(project)).resolve() if project else _LAST_PROJECT_DIR
|
|
715
|
+
if project_path:
|
|
716
|
+
_write_runtime_status(
|
|
717
|
+
project_path / ".trellis" if project_path else Path(".trellis"),
|
|
718
|
+
_detect_platform({}), "error", error_category=type(exc).__name__,
|
|
719
|
+
)
|
|
720
|
+
print(f"mini-trellis SessionStart failed: {type(exc).__name__}", file=sys.stderr)
|
|
721
|
+
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
|
|
21
|
-
# - false: write files only; you decide when to
|
|
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
|
-
|
|
23
|
+
session_auto_commit: false
|
|
24
24
|
|
|
25
25
|
#-------------------------------------------------------------------------------
|
|
26
26
|
# Monorepo / Packages
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
Add a new session to journal file and update index.md.
|
|
5
5
|
|
|
6
6
|
Usage:
|
|
7
|
-
python3 add_session.py --title "Title" --commit "hash" --summary "Summary" [--
|
|
7
|
+
python3 add_session.py --title "Title" --commit "hash" --summary "Summary" [--topic .trellis/research/topic.md]
|
|
8
8
|
python3 add_session.py --title "Title" --branch "feat/my-branch"
|
|
9
9
|
|
|
10
10
|
# Pipe detailed content via stdin (use --stdin to opt in):
|
|
@@ -48,10 +48,12 @@ from __future__ import annotations
|
|
|
48
48
|
import argparse
|
|
49
49
|
import hashlib
|
|
50
50
|
import json
|
|
51
|
+
import os
|
|
51
52
|
import re
|
|
52
53
|
import sys
|
|
53
|
-
from datetime import datetime
|
|
54
|
+
from datetime import datetime, timezone
|
|
54
55
|
from pathlib import Path
|
|
56
|
+
from urllib.parse import quote
|
|
55
57
|
|
|
56
58
|
from common.paths import (
|
|
57
59
|
DIR_TASKS,
|
|
@@ -517,6 +519,29 @@ def render_marker(fingerprint: str) -> str:
|
|
|
517
519
|
return f"{MARKER_PREFIX} v={MARKER_VERSION} fp={fingerprint} -->"
|
|
518
520
|
|
|
519
521
|
|
|
522
|
+
def _append_topic_links(
|
|
523
|
+
summary: str,
|
|
524
|
+
topic_paths: list[str] | None,
|
|
525
|
+
link_base: Path | None = None,
|
|
526
|
+
repo_root: Path | None = None,
|
|
527
|
+
) -> str:
|
|
528
|
+
"""Append topic links, resolving them relative to the journal file.
|
|
529
|
+
|
|
530
|
+
The record fingerprint keeps project-relative paths stable, while the
|
|
531
|
+
rendered Markdown link must resolve from the journal's directory.
|
|
532
|
+
"""
|
|
533
|
+
if not topic_paths:
|
|
534
|
+
return summary
|
|
535
|
+
|
|
536
|
+
links: list[str] = []
|
|
537
|
+
for topic in topic_paths:
|
|
538
|
+
href = topic
|
|
539
|
+
if link_base is not None and repo_root is not None:
|
|
540
|
+
href = quote(Path(os.path.relpath(repo_root / topic, start=link_base)).as_posix())
|
|
541
|
+
links.append(f"[{topic}]({href})")
|
|
542
|
+
return summary + "\nTopics: " + ", ".join(links)
|
|
543
|
+
|
|
544
|
+
|
|
520
545
|
def render_legacy_marker(fingerprint: str) -> str:
|
|
521
546
|
"""The v1 marker form: no version tag. Read, never written."""
|
|
522
547
|
return f"{MARKER_PREFIX} fp={fingerprint} -->"
|
|
@@ -1197,6 +1222,7 @@ def add_session(
|
|
|
1197
1222
|
branch: str | None = None,
|
|
1198
1223
|
commit_subjects: list[str] | None = None,
|
|
1199
1224
|
idempotency_key: str | None = None,
|
|
1225
|
+
topic_paths: list[str] | None = None,
|
|
1200
1226
|
) -> int:
|
|
1201
1227
|
"""Add a new session, resuming an interrupted one instead of duplicating it."""
|
|
1202
1228
|
repo_root = get_repo_root()
|
|
@@ -1243,8 +1269,9 @@ def add_session(
|
|
|
1243
1269
|
index_file = dev_dir / "index.md"
|
|
1244
1270
|
today = datetime.now().strftime("%Y-%m-%d")
|
|
1245
1271
|
|
|
1272
|
+
record_summary = _append_topic_links(summary, topic_paths)
|
|
1246
1273
|
payload = _fingerprint_payload(
|
|
1247
|
-
developer, title,
|
|
1274
|
+
developer, title, record_summary, package, branch, evidence,
|
|
1248
1275
|
changes, extra_content, tests, next_steps, idempotency_key,
|
|
1249
1276
|
)
|
|
1250
1277
|
marker = render_marker(compute_record_fingerprint(payload))
|
|
@@ -1310,8 +1337,9 @@ def add_session(
|
|
|
1310
1337
|
journal_file, current_num, current_lines = get_latest_journal_info(dev_dir)
|
|
1311
1338
|
new_session = resolve_next_session(repo_root, dev_dir, index_file)
|
|
1312
1339
|
|
|
1340
|
+
rendered_summary = _append_topic_links(summary, topic_paths, dev_dir, repo_root)
|
|
1313
1341
|
session_content = generate_session_content(
|
|
1314
|
-
new_session, title, evidence,
|
|
1342
|
+
new_session, title, evidence, rendered_summary, today, marker, package, branch,
|
|
1315
1343
|
changes=changes, extra_content=extra_content, tests=tests,
|
|
1316
1344
|
next_steps=next_steps,
|
|
1317
1345
|
)
|
|
@@ -1413,12 +1441,12 @@ def add_session(
|
|
|
1413
1441
|
|
|
1414
1442
|
print("", file=sys.stderr)
|
|
1415
1443
|
print("========================================", file=sys.stderr)
|
|
1416
|
-
print(f"[OK]
|
|
1444
|
+
print(f"[OK] Journal session {new_session} and index recorded (topic content must be verified separately).", file=sys.stderr)
|
|
1417
1445
|
print("========================================", file=sys.stderr)
|
|
1418
1446
|
print("", file=sys.stderr)
|
|
1419
1447
|
print("Files updated:", file=sys.stderr)
|
|
1420
|
-
print(f" - {target_file.
|
|
1421
|
-
print(" -
|
|
1448
|
+
print(f" - {target_file.relative_to(repo_root).as_posix() if target_file else 'journal'}", file=sys.stderr)
|
|
1449
|
+
print(f" - {index_file.relative_to(repo_root).as_posix()}", file=sys.stderr)
|
|
1422
1450
|
|
|
1423
1451
|
# -------------------------------------------------------------------
|
|
1424
1452
|
# Index-recorded → committed
|
|
@@ -1478,8 +1506,12 @@ def main() -> int:
|
|
|
1478
1506
|
),
|
|
1479
1507
|
)
|
|
1480
1508
|
parser.add_argument("--summary", default="Session summary was not supplied.", help="Brief summary")
|
|
1509
|
+
parser.add_argument(
|
|
1510
|
+
"--topic", action="append", default=[], metavar="PATH",
|
|
1511
|
+
help="Existing spec/research Markdown to validate and link in the journal (repeatable); does not edit or verify its conclusions",
|
|
1512
|
+
)
|
|
1481
1513
|
parser.add_argument("--content-file", help="Path to file with detailed content")
|
|
1482
|
-
parser.add_argument("--package", help="Package name tag (e.g., cli,
|
|
1514
|
+
parser.add_argument("--package", help="Package name tag (e.g., cli, core)")
|
|
1483
1515
|
parser.add_argument("--branch", help="Branch name (auto-detected if omitted)")
|
|
1484
1516
|
parser.add_argument("--change", action="append", help="Main Changes bullet (repeatable)")
|
|
1485
1517
|
parser.add_argument("--test", action="append", help="Testing bullet (repeatable)")
|
|
@@ -1508,6 +1540,21 @@ def main() -> int:
|
|
|
1508
1540
|
|
|
1509
1541
|
# Load active task once — shared by package and branch resolution
|
|
1510
1542
|
repo_root = get_repo_root()
|
|
1543
|
+
topic_links: list[str] = []
|
|
1544
|
+
for topic in args.topic:
|
|
1545
|
+
try:
|
|
1546
|
+
candidate = (repo_root / topic).resolve(strict=True)
|
|
1547
|
+
relative = candidate.relative_to(repo_root.resolve()).as_posix()
|
|
1548
|
+
if (not relative.startswith((".trellis/spec/", ".trellis/research/"))
|
|
1549
|
+
or candidate.suffix.lower() != ".md"
|
|
1550
|
+
or not candidate.is_file()
|
|
1551
|
+
or not candidate.read_text(encoding="utf-8").strip()):
|
|
1552
|
+
raise ValueError("expected a non-empty spec/research Markdown file")
|
|
1553
|
+
except (OSError, ValueError, UnicodeError):
|
|
1554
|
+
print("Error: --topic must name a readable, non-empty spec/research Markdown inside this project; journal not written.", file=sys.stderr)
|
|
1555
|
+
return 1
|
|
1556
|
+
if relative not in topic_links:
|
|
1557
|
+
topic_links.append(relative)
|
|
1511
1558
|
current = get_current_task(repo_root)
|
|
1512
1559
|
task_data = load_task(repo_root / current) if current else None
|
|
1513
1560
|
|
|
@@ -1538,8 +1585,47 @@ def main() -> int:
|
|
|
1538
1585
|
branch=branch,
|
|
1539
1586
|
commit_subjects=args.commit_subject,
|
|
1540
1587
|
idempotency_key=args.idempotency_key,
|
|
1588
|
+
topic_paths=topic_links,
|
|
1541
1589
|
)
|
|
1542
1590
|
|
|
1543
1591
|
|
|
1592
|
+
def _write_recording_status(exit_code: int) -> None:
|
|
1593
|
+
"""Best-effort last completed attempt, with no note content or user identity.
|
|
1594
|
+
|
|
1595
|
+
Atomic replacement keeps concurrent diagnostics readable. The journal and
|
|
1596
|
+
index remain the source of truth; failure may leave a resumable checkpoint.
|
|
1597
|
+
"""
|
|
1598
|
+
try:
|
|
1599
|
+
trellis = get_repo_root() / DIR_WORKFLOW
|
|
1600
|
+
if not trellis.is_dir():
|
|
1601
|
+
return
|
|
1602
|
+
target = trellis / ".runtime" / "writes" / "latest.json"
|
|
1603
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
1604
|
+
payload: dict[str, object] = {
|
|
1605
|
+
"schema": 1,
|
|
1606
|
+
"last_write_at": datetime.now(timezone.utc).isoformat(),
|
|
1607
|
+
"last_status": "ok" if exit_code == 0 else "error",
|
|
1608
|
+
"last_exit_code": exit_code,
|
|
1609
|
+
}
|
|
1610
|
+
if exit_code != 0:
|
|
1611
|
+
payload["last_error_category"] = "recording-failed"
|
|
1612
|
+
if write_text_atomic(target, json.dumps(payload) + "\n"):
|
|
1613
|
+
return
|
|
1614
|
+
except OSError:
|
|
1615
|
+
pass
|
|
1616
|
+
print("mini-trellis: recording diagnostic write failed (state-write)", file=sys.stderr)
|
|
1617
|
+
|
|
1618
|
+
|
|
1619
|
+
def run_with_status() -> int:
|
|
1620
|
+
try:
|
|
1621
|
+
result = main()
|
|
1622
|
+
except Exception:
|
|
1623
|
+
_write_recording_status(1)
|
|
1624
|
+
raise
|
|
1625
|
+
# argparse's --help / invalid arguments exit before a recording attempt.
|
|
1626
|
+
_write_recording_status(result)
|
|
1627
|
+
return result
|
|
1628
|
+
|
|
1629
|
+
|
|
1544
1630
|
if __name__ == "__main__":
|
|
1545
|
-
sys.exit(
|
|
1631
|
+
sys.exit(run_with_status())
|
|
@@ -118,10 +118,10 @@ def get_max_journal_lines(repo_root: Path | None = None) -> int:
|
|
|
118
118
|
def get_session_auto_commit(repo_root: Path | None = None) -> bool:
|
|
119
119
|
"""Whether scripts should auto-stage + auto-commit session/task changes.
|
|
120
120
|
|
|
121
|
-
Governs
|
|
122
|
-
``task_store.py:_auto_commit_archive``.
|
|
121
|
+
Governs ``add_session.py:_auto_commit_workspace``.
|
|
123
122
|
|
|
124
|
-
|
|
123
|
+
Missing-key fallback: ``True`` for existing projects. New installations
|
|
124
|
+
explicitly set ``session_auto_commit: false`` in their config template.
|
|
125
125
|
Set ``session_auto_commit: false`` in ``.trellis/config.yaml`` to skip
|
|
126
126
|
auto-staging entirely; the journal/archive files are still written to
|
|
127
127
|
disk, but the user manages ``git add`` / ``git commit`` themselves.
|
|
@@ -313,7 +313,7 @@ def get_packages(repo_root: Path | None = None) -> dict[str, dict] | None:
|
|
|
313
313
|
or None if not configured (single-repo mode).
|
|
314
314
|
|
|
315
315
|
Example return:
|
|
316
|
-
{"cli": {"path": "packages/cli"}, "docs
|
|
316
|
+
{"cli": {"path": "packages/cli"}, "docs": {"path": "docs", "type": "submodule"}}
|
|
317
317
|
"""
|
|
318
318
|
config = _load_config(repo_root)
|
|
319
319
|
packages = config.get("packages")
|
|
@@ -345,7 +345,7 @@ def get_submodule_packages(repo_root: Path | None = None) -> dict[str, str]:
|
|
|
345
345
|
Empty dict if none configured.
|
|
346
346
|
|
|
347
347
|
Example return:
|
|
348
|
-
{"docs
|
|
348
|
+
{"docs": "docs"}
|
|
349
349
|
"""
|
|
350
350
|
packages = get_packages(repo_root)
|
|
351
351
|
if packages is None:
|
|
@@ -43,6 +43,14 @@ export declare function scrubOpencodePackageJson(content: string): ScrubResult;
|
|
|
43
43
|
* - drop arrays that become empty
|
|
44
44
|
*/
|
|
45
45
|
export declare function scrubPiSettings(content: string): ScrubResult;
|
|
46
|
+
/**
|
|
47
|
+
* Remove Trellis-only Pi entries while keeping mini-trellis and user config.
|
|
48
|
+
*
|
|
49
|
+
* `migrate` uses this before rewriting Pi settings. It drops the upstream
|
|
50
|
+
* extension path and the `pi-subagents` package Trellis installed, and leaves
|
|
51
|
+
* `enableSkillCommands`, `./skills`, prompts, and any other user entries.
|
|
52
|
+
*/
|
|
53
|
+
export declare function scrubLegacyTrellisPiSettings(content: string): ScrubResult;
|
|
46
54
|
/**
|
|
47
55
|
* Scrub `.codex/config.toml`.
|
|
48
56
|
*
|