@nurix/etna 0.18.15 → 0.18.16

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 +11 -16
  2. package/data/harness-index.json +1 -1
  3. package/data/harnesses/code/CLAUDE.md +71 -57
  4. package/data/harnesses/code/agents/{spec-mode.md → lld-mode.md} +12 -12
  5. package/data/harnesses/code/agents/maintenance.md +2 -31
  6. package/data/harnesses/code/harness.json +2 -2
  7. package/data/harnesses/code/hooks/hooks.json +0 -23
  8. package/data/harnesses/code/rules/testing.md +25 -0
  9. package/data/harnesses/code/skills/brainstorm/SKILL.md +1 -1
  10. package/data/harnesses/code/skills/brainstorm/exit-artifacts.md +2 -2
  11. package/data/harnesses/code/skills/documentation/SKILL.md +2 -2
  12. package/data/harnesses/code/skills/documentation/references/templates.md +10 -77
  13. package/data/harnesses/etna/CLAUDE.md +11 -12
  14. package/data/harnesses/etna/agents/{spec-mode.md → lld-mode.md} +12 -12
  15. package/data/harnesses/etna/agents/maintenance.md +2 -31
  16. package/data/harnesses/etna/harness.json +2 -2
  17. package/data/harnesses/etna/hooks/hooks.json +0 -23
  18. package/data/harnesses/etna/rules/testing.md +25 -0
  19. package/data/harnesses/etna/skills/brainstorm/SKILL.md +1 -1
  20. package/data/harnesses/etna/skills/brainstorm/exit-artifacts.md +2 -2
  21. package/data/harnesses/etna/skills/documentation/SKILL.md +2 -2
  22. package/data/harnesses/etna/skills/documentation/references/templates.md +10 -77
  23. package/data/harnesses/mobile/CLAUDE.md +78 -55
  24. package/data/harnesses/mobile/agents/{spec-mode.md → lld-mode.md} +12 -12
  25. package/data/harnesses/mobile/agents/maintenance.md +2 -31
  26. package/data/harnesses/mobile/harness.json +2 -2
  27. package/data/harnesses/mobile/hooks/hooks.json +0 -23
  28. package/data/harnesses/mobile/rules/testing.md +25 -0
  29. package/data/harnesses/mobile/skills/brainstorm/SKILL.md +1 -1
  30. package/data/harnesses/mobile/skills/brainstorm/exit-artifacts.md +2 -2
  31. package/data/harnesses/mobile/skills/documentation/SKILL.md +2 -2
  32. package/data/harnesses/mobile/skills/documentation/references/templates.md +10 -77
  33. package/package.json +1 -1
  34. package/data/harnesses/code/hooks/lib/redact.mjs +0 -35
  35. package/data/harnesses/code/hooks/prompt-recall.mjs +0 -155
  36. package/data/harnesses/code/hooks/session-reflect.mjs +0 -285
  37. package/data/harnesses/code/skills/distiller/SKILL.md +0 -90
  38. package/data/harnesses/code/skills/distiller/references/docs-mode.md +0 -299
  39. package/data/harnesses/code/skills/distiller/references/method.md +0 -94
  40. package/data/harnesses/etna/hooks/lib/redact.mjs +0 -35
  41. package/data/harnesses/etna/hooks/prompt-recall.mjs +0 -155
  42. package/data/harnesses/etna/hooks/session-reflect.mjs +0 -285
  43. package/data/harnesses/etna/skills/distiller/SKILL.md +0 -90
  44. package/data/harnesses/etna/skills/distiller/references/docs-mode.md +0 -299
  45. package/data/harnesses/etna/skills/distiller/references/method.md +0 -94
  46. package/data/harnesses/mobile/hooks/lib/redact.mjs +0 -35
  47. package/data/harnesses/mobile/hooks/prompt-recall.mjs +0 -155
  48. package/data/harnesses/mobile/hooks/session-reflect.mjs +0 -285
  49. package/data/harnesses/mobile/skills/distiller/SKILL.md +0 -90
  50. package/data/harnesses/mobile/skills/distiller/references/docs-mode.md +0 -299
  51. package/data/harnesses/mobile/skills/distiller/references/method.md +0 -94
@@ -58,5 +58,5 @@ Append a changelog entry at `docs/history/changelog/YYYY-MM-DD-brainstorm-{slug}
58
58
 
59
59
  **Keep `docs/brainstorm/{topic}/` — never delete it.** The exit artifacts now carry the distilled
60
60
  conclusions, but the record stays committed as their provenance: a traceable source for every published
61
- headline, the seed the next `/brainstorm start` on this topic resumes from, and a high-surprisal input the
62
- `distiller` ingests. Retire a topic's folder by hand only when the design line is truly dead.
61
+ headline, and the seed the next `/brainstorm start` on this topic resumes from. Retire a topic's folder
62
+ by hand only when the design line is truly dead.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: documentation
3
- description: Template & generator library for technical docs — the skill agents call to produce a doc from a template. Use to (1) document a feature or module, (2) create or update a changelog entry, (3) document data flows or Redux state, (4) add to protected files, (5) record an architecture decision (ADR), (6) create or update the project root README, (7) create or update a plan, (8) derive a feature doc's `owns:` frontmatter (the code-path globs it owns) from code, (9) scaffold a standard doc (README, structure.md, CHANGELOG, backlog, memory) from its template, or (10) co-author any technical doc. Baselining / reconciling a repo's docs to the installed harness version is the **`maintenance` agent (baseline mode)** (which calls this skill for each template) — this skill does not orchestrate baseline. Triggers on "document this", "create docs", "update changelog", "add to protected files", "ADR", "architecture decision", "root README", "plan", "feature doc".
3
+ description: Template & generator library for technical docs — the skill agents call to produce a doc from a template. Use to (1) document a feature or module (the feature doc is the feature's LLD — low-level design — written in LLD Mode), (2) create or update a changelog entry, (3) document data flows or Redux state, (4) add to protected files, (5) record an architecture decision (ADR), (6) create or update the project root README, (7) create or update a plan, (8) derive a feature doc's `owns:` frontmatter (the code-path globs it owns) from code, (9) scaffold a standard doc (README, structure.md, CHANGELOG, backlog, memory) from its template, or (10) co-author any technical doc. Baselining / reconciling a repo's docs to the installed harness version is the **`maintenance` agent (baseline mode)** (which calls this skill for each template) — this skill does not orchestrate baseline. Triggers on "document this", "create docs", "update changelog", "add to protected files", "ADR", "architecture decision", "root README", "plan", "feature doc", "LLD".
4
4
  ---
5
5
 
6
6
  # Technical Documentation Skill
@@ -22,7 +22,7 @@ User request
22
22
  │
23
23
  ├─ "Baseline/reconcile docs" ──────▶ maintenance agent (baseline mode) (it calls this skill per template)
24
24
  │
25
- ├─ "Document feature/module" ──────▶ Module Template
25
+ ├─ "Document feature/module (LLD)" ▶ Module Template
26
26
  │
27
27
  ├─ "Create/update changelog" ──────▶ Changelog Template
28
28
  │
@@ -112,7 +112,7 @@ Plan (Status: Draft) → Implementation → Feature Doc or Architecture Update
112
112
 
113
113
  ## Folder Rules
114
114
 
115
- - `docs/features/`: Living reference for implemented features. Each feature doc **carries** the `owns:` / `module:` / `keywords:` / `status:` frontmatter — `owns:` declares the code-path globs it owns (the only ownership key), `module:` is an optional bounded-context label, `keywords:` are discovery terms, `status:` is `active`/`draft`/`deprecated`. The SessionStart hook unions every feature's `owns:` globs into the injected ownership index. (An optional `anchors:` block — a qmd drift tripwire, see §3 — is a separate tooling key a doc may additionally carry.)
115
+ - `docs/features/`: Living reference for implemented features. Each feature doc **carries** the `owns:` / `module:` / `keywords:` / `status:` frontmatter — `owns:` declares the code-path globs it owns (the only ownership key), `module:` is an optional bounded-context label, `keywords:` are discovery terms, `status:` is `active`/`draft`/`deprecated`. The SessionStart hook unions every feature's `owns:` globs into the injected ownership index.
116
116
  - `docs/architecture/`: System-wide patterns and the cross-module steering layer (domain model, glossary, non-goals, references, ADRs). A module's cross-cutting prose lives here (or in a browse-folder `Readme.md`). Update when cross-cutting concerns change.
117
117
  - `docs/operations/`: How-to procedures for setup, development, and deployment. Update when workflows change.
118
118
  - `docs/history/plans/`: Historical. Must have `Status:` field. Never modify after completion.
@@ -131,21 +131,10 @@ Plan (Status: Draft) → Implementation → Feature Doc or Architecture Update
131
131
 
132
132
  ---
133
133
 
134
- ## 3. Code-Path Ownership & Anchors
134
+ ## 3. Code-Path Ownership
135
135
 
136
136
  **Ownership.** A feature doc is the canonical reference for the code paths in its **`owns:` frontmatter** — the only ownership key. To find what a doc owns, read its `owns:` globs; to find the doc for a path, match the path against the injected ownership index (the union of every feature's `owns:` globs), narrower glob wins. See **Frontmatter Derivation** in `SKILL.md` for turning code into `owns:` globs.
137
137
 
138
- **Anchors (optional tooling key).** A doc may additionally carry an `anchors:` block — a qmd drift tripwire, orthogonal to ownership:
139
-
140
- ```yaml
141
- ---
142
- anchors:
143
- - "qmd query: feature-name persistence shape"
144
- ---
145
- ```
146
-
147
- `anchors` is an optional list of qmd queries (or `#docid`s) that re-resolve to the code a doc abstracts as it moves. It is a drift tripwire, never a contract — an anchor that returns nothing IS the drift signal, and nothing auto-rewrites from an anchor result. It is read on demand by the maintenance anchor-drift check, never injected, and inert when qmd is absent.
148
-
149
138
  ---
150
139
 
151
140
  ## 4. Scaffold Files (create if missing)
@@ -241,14 +230,6 @@ description: Shared knowledge accumulated across agent sessions. All agents shou
241
230
  - **Spec version:** v{harness-version}
242
231
  <!-- v{harness-version} resolves to the installed harness version — read it from `.claude/harness.json` (`version`) / `docs/structure.md` frontmatter (`harness-version`); never hardcode a literal version here. -->
243
232
 
244
- ## Knowledge Tiers
245
-
246
- Memory is a gradient — volume falls, signal rises, one hop down each tier. Tiers describe themselves here even before they fill:
247
-
248
- - **Inbox** (`docs/memory/inbox/`) — per-actor queue of session lessons, written by the `session-reflect` hook at session end and consumed by the distiller on digestion. Transient by design, rarely read directly.
249
- - **Fact-cards** (`docs/memory/facts/`) — distilled, provenance-linked atomic facts, written by the distiller (`facts` mode) from inbox entries and resurfaced at prompt time by the `prompt-recall` hook.
250
- - **This index** — the curated read tier: the learnings list below, distilled from the colder tiers and hand-appended.
251
-
252
233
  ## Learnings
253
234
 
254
235
  {Agents append learnings here as they discover gotchas, patterns, and architecture notes}
@@ -278,15 +259,13 @@ Append entries below, oldest at bottom. Format:
278
259
  Memory file initialized during documentation baseline.
279
260
  ```
280
261
 
281
- > The per-actor memory **inbox** (`docs/memory/inbox/`) is _not_ a baseline scaffold — the `session-reflect` hook creates it mechanically on the first reflected session. See **§11 Memory inbox entry** for its format.
282
-
283
262
  ---
284
263
 
285
- ## 5. Feature Documentation (docs/features/{feature}.md)
264
+ ## 5. Feature Documentation — the LLD (docs/features/{feature}.md)
286
265
 
287
- Use for: every feature in `docs/features/`. The same file persists from design (Status: Draft) through implementation to live reference (Status: Active). Sections fill in as the feature matures — no template swap.
266
+ Use for: every feature in `docs/features/`. The feature doc is the feature's **LLD (low-level design)**: the same file persists from design (Status: Draft, written in LLD Mode) through implementation to live reference (Status: Active). Sections fill in as the feature matures — no template swap.
288
267
 
289
- The four research-derived sections (**Affected Modules**, **Conventions to Follow**, **Current Behavior**, **Ownership Conflicts**) map 1:1 to spec-mode's return shape. The orchestrator drops spec-mode's findings into those slots without restructuring.
268
+ The four research-derived sections (**Affected Modules**, **Conventions to Follow**, **Current Behavior**, **Ownership Conflicts**) map 1:1 to the `lld-mode` agent's return shape. The orchestrator drops its findings into those slots without restructuring.
290
269
 
291
270
  ```yaml
292
271
  ---
@@ -294,8 +273,6 @@ owns: ["src/feature/**", "src/other/file.ts"] # required — code-path globs t
294
273
  module: billing # optional — single bounded-context label; omit if cross-cutting
295
274
  keywords: [invoice, pdf] # required — discovery terms
296
275
  status: active # required — active | draft | deprecated
297
- anchors: # optional extra — a qmd drift tripwire; see §3
298
- - "qmd query: wire envelope invariants"
299
276
  ---
300
277
  ```
301
278
 
@@ -332,22 +309,22 @@ High-level shape of the solution. ASCII diagram if it helps. Implementation spec
332
309
 
333
310
  ## Affected Modules
334
311
 
335
- (From spec-mode research) Files, routes, components, slices this feature involves. Group by module.
312
+ (From lld-mode research) Files, routes, components, slices this feature involves. Group by module.
336
313
 
337
314
  | Module | Path | Role in this feature |
338
315
  |--------|------|----------------------|
339
316
 
340
317
  ## Conventions to Follow
341
318
 
342
- (From spec-mode research) Naming patterns, structural patterns, doc-fit heuristics confirmed for the area being touched. Cite the source file(s) where the convention is established.
319
+ (From lld-mode research) Naming patterns, structural patterns, doc-fit heuristics confirmed for the area being touched. Cite the source file(s) where the convention is established.
343
320
 
344
321
  ## Current Behavior
345
322
 
346
- (From spec-mode research) How the relevant part of the system works *today*, before this feature lands. Without this baseline the design intent is hard to evaluate.
323
+ (From lld-mode research) How the relevant part of the system works *today*, before this feature lands. Without this baseline the design intent is hard to evaluate.
347
324
 
348
325
  ## Ownership Conflicts
349
326
 
350
- (From spec-mode research) Existing feature docs whose `owns:` globs overlap with the projected scope. Resolve before the plan starts — leave nothing unresolved.
327
+ (From lld-mode research) Existing feature docs whose `owns:` globs overlap with the projected scope. Resolve before the plan starts — leave nothing unresolved.
351
328
 
352
329
  | Conflicting doc | Overlapping path(s) | Resolution |
353
330
  |-----------------|---------------------|------------|
@@ -426,7 +403,7 @@ Sections fill in across the feature's lifecycle. No template swap — they accum
426
403
  | When | Sections written | Source |
427
404
  | --- | --- | --- |
428
405
  | Status: Draft (design) | Goal, Goals & Non-Goals, Background, Approach, Open Questions, Risks | User interview |
429
- | Status: Draft (research) | Affected Modules, Conventions to Follow, Current Behavior, Ownership Conflicts | spec-mode agent |
406
+ | Status: Draft (research) | Affected Modules, Conventions to Follow, Current Behavior, Ownership Conflicts | lld-mode agent |
430
407
  | Status: Draft → Active (implementation lands) | Architecture, Key Functions, State, Redux, Files; `owns:` globs confirmed against real code | Main agent (from actual code) |
431
408
 
432
409
  Resolved Open Questions can be summarized into Background; unresolved ones stay visible.
@@ -807,47 +784,3 @@ The full surface lives in [`{path/to/public-index}`]({path/to/public-index}).
807
784
  The baseline audit **does** scaffold the project root README when missing. The risk this template guards against — template-shaped placeholders that look abandoned — is mitigated by the writing rules above: fill every section with concrete details from the repo (real package manager from the lockfile, real scripts, real layout, real status). Skip sections that genuinely don't apply rather than leaving stubs.
808
785
 
809
786
  **Never overwrite an existing root README** during a baseline. If one is present — even sparse or outdated — leave it untouched. Treat updates to a pre-existing root README as a separate, explicit request.
810
-
811
- ---
812
-
813
- ## 11. Memory inbox entry (docs/memory/inbox/{actor}.md)
814
-
815
- Use for: the capture tier of the knowledge gradient — the durable lessons of each session (corrections, root-caused failures, decisions with rationale, discovered constraints), reflected by the `session-reflect` hook at session end. It is the raw input to distillation: `distiller facts` digests entries into fact-cards and **consumes** them, so the file holds exactly what is undigested.
816
-
817
- ### File grain
818
-
819
- One file **per actor**: `docs/memory/inbox/{actor}.md`. `actor` is `git config user.name` lowercased and kebab-slugged; fall back to `$USER`, then `agent`. Two actors write to different files, so the inbox is **append-only without merge conflicts** — no shared file to contend over, no lock, no last-writer-wins.
820
-
821
- ### File header
822
-
823
- Written once, on the first entry:
824
-
825
- ```
826
- # Memory inbox — {actor}
827
- Session lessons awaiting distillation — appended by the session-reflect hook, consumed by `distiller facts`.
828
- ```
829
-
830
- ### Entry shape
831
-
832
- One block per reflected session, at most 6 bullets. Each bullet is one complete, self-contained sentence tagged `[project]` (true of the repo or its tooling) or `[user]` (true of the user) — the tag routes it at distillation: project facts → `docs/memory/facts/`, user facts → user-level memory.
833
-
834
- ```
835
- ## YYYY-MM-DD HH:MM · session <id> · {repo}@{branch}
836
- - [project] <one self-contained sentence, names and identifiers spelled out>
837
- - [user] <one self-contained sentence>
838
- ```
839
-
840
- ### Examples
841
-
842
- ```
843
- ## 2026-06-08 22:26 · session bc06c4fc · etna@dev
844
- - [project] The read_network_requests Chrome CDP tool only captures after its first call — arm it, trigger traffic, then read.
845
- - [user] jane-doe prefers minimal fixes over defensive machinery; fail loudly instead of engineering around a problem.
846
- ```
847
-
848
- ### Rules
849
-
850
- - **Hooks append, the distiller consumes.** A digested entry block is deleted by `distiller facts`; nothing else edits or reorders the file. A human may hand-append a lesson in the same shape — it rides the same queue.
851
- - **Sessions are deduped by id.** The reflect hook skips a session whose id already appears in the file (SessionEnd re-fires on resume).
852
- - **Secrets are redacted on write.** The privacy filter replaces secret shapes with `[redacted:{kind}]` (e.g. `[redacted:api-key]`, `[redacted:bearer]`, `[redacted:pem]`) before any line is appended — never paste a raw token in by hand either.
853
- - **Don't curate here.** Promotion to fact-cards and `docs/memory/main.md` happens at distillation; the inbox stays a transient queue.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nurix/etna",
3
- "version": "0.18.15",
3
+ "version": "0.18.16",
4
4
  "description": "Bootstrap a project with a Nurix harness — copies the harness's CLAUDE.md, skills, agents, rules, and hooks directly into the project from a bundled payload (no marketplace fetch, no network).",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,35 +0,0 @@
1
- // harness/code/hooks/lib/redact.mjs — shared privacy filter: redacts secret shapes before ledger append.
2
-
3
- // Patterns ordered most-specific first; each replaces a match with [redacted:{kind}].
4
- const RULES = [
5
- // PEM private/public key blocks (multiline).
6
- { kind: "pem", re: /-----BEGIN[\s\S]*?-----END[^-]*-----/g },
7
- // OpenAI / Anthropic-style keys (sk-..., sk-ant-...).
8
- { kind: "api-key", re: /\bsk-(?:ant-)?[A-Za-z0-9_-]{8,}\b/g },
9
- // AWS access key IDs.
10
- { kind: "aws-key", re: /\bAKIA[0-9A-Z]{16}\b/g },
11
- // Bearer tokens in Authorization context.
12
- { kind: "bearer", re: /\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/gi },
13
- // password= / passwd= / secret= / token= / api_key= style assignments (= or :).
14
- {
15
- kind: "credential",
16
- re: /\b(?:password|passwd|pwd|secret|token|api[_-]?key|access[_-]?key|client[_-]?secret)\b\s*[:=]\s*["']?[^\s"'&)\]},;[]{3,}/gi,
17
- },
18
- // Generic long hex/base64 token ONLY in a key-value credential context.
19
- {
20
- kind: "credential",
21
- re: /\b(?:key|auth|cred|credential|signature|sig)\b\s*[:=]\s*["']?[A-Za-z0-9+/=_-]{32,}/gi,
22
- },
23
- ];
24
-
25
- // Redact secret shapes in arbitrary text; returns a string with placeholders.
26
- function redact(text) {
27
- if (text == null) return "";
28
- let out = String(text);
29
- for (const rule of RULES) {
30
- out = out.replace(rule.re, `[redacted:${rule.kind}]`);
31
- }
32
- return out;
33
- }
34
-
35
- export { redact };
@@ -1,155 +0,0 @@
1
- // plugins/code/hooks/prompt-recall.mjs — UserPromptSubmit hook: surface fact-cards relevant to the prompt via qmd BM25; stdout is injected as context.
2
-
3
- import fs from "node:fs";
4
- import os from "node:os";
5
- import path from "node:path";
6
- import { execFileSync } from "node:child_process";
7
-
8
- const MIN_PROMPT_CHARS = 24;
9
- const MIN_SCORE = 0.45;
10
- const MAX_CARDS = 3;
11
- const MAX_STATEMENT_CHARS = 300;
12
- const MAX_KEYWORDS = 8;
13
-
14
- const STOPWORDS = new Set(
15
- "a an and are as at be but by can could do does for from has have how i in is it its me my of on or our should so that the their then there these this to was we what when where which who why will with would you your".split(
16
- " ",
17
- ),
18
- );
19
-
20
- // Read all of stdin synchronously; returns "" if nothing is piped.
21
- function readStdin() {
22
- try {
23
- return fs.readFileSync(0, "utf8");
24
- } catch (e) {
25
- return "";
26
- }
27
- }
28
-
29
- // Resolve the project root: CLAUDE_PROJECT_DIR env, else payload cwd, else process cwd.
30
- function resolveProjectDir(payload) {
31
- return process.env.CLAUDE_PROJECT_DIR || (payload && payload.cwd) || process.cwd();
32
- }
33
-
34
- // Map a qmd://collection/relpath hit URI to the card file under docs/memory/facts/.
35
- function cardPath(factsDir, fileUri) {
36
- return path.join(factsDir, String(fileUri || "").replace(/^qmd:\/\/[^/]+\//, ""));
37
- }
38
-
39
- // A card's atomic statement: the body after frontmatter, whitespace-flattened and clipped.
40
- function cardStatement(file) {
41
- try {
42
- const body = fs
43
- .readFileSync(file, "utf8")
44
- .replace(/^---\n[\s\S]*?\n---\n?/, "")
45
- .replace(/\s+/g, " ")
46
- .trim();
47
- return body.length > MAX_STATEMENT_CHARS ? body.slice(0, MAX_STATEMENT_CHARS) + "…" : body;
48
- } catch (e) {
49
- return "";
50
- }
51
- }
52
-
53
- // Run one qmd search mode against the facts collection; [] on any failure — recall is strictly optional.
54
- function qmdHits(mode, query, collection) {
55
- try {
56
- const out = JSON.parse(
57
- execFileSync("qmd", [mode, query, "--format", "json", "-n", String(MAX_CARDS + 2), "-c", collection], {
58
- encoding: "utf8",
59
- timeout: 10000,
60
- stdio: ["ignore", "pipe", "ignore"],
61
- }),
62
- );
63
- return Array.isArray(out) ? out : [];
64
- } catch (e) {
65
- return [];
66
- }
67
- }
68
-
69
- // Main: search the facts collection for the prompt and emit unseen high-score cards.
70
- function main() {
71
- if (process.env.ETNA_REFLECT) return;
72
-
73
- const raw = readStdin();
74
- let payload = {};
75
- try {
76
- payload = raw ? JSON.parse(raw) : {};
77
- } catch (e) {
78
- payload = {};
79
- }
80
-
81
- const prompt = String(payload.prompt || "").trim();
82
- if (!prompt || prompt.startsWith("/") || prompt.length < MIN_PROMPT_CHARS) return;
83
-
84
- const projectDir = resolveProjectDir(payload);
85
- const factsDir = path.join(projectDir, "docs", "memory", "facts");
86
- let hasCards = false;
87
- try {
88
- hasCards = fs.readdirSync(factsDir).some((f) => f.endsWith(".md"));
89
- } catch (e) {
90
- return;
91
- }
92
- if (!hasCards) return;
93
-
94
- // BM25 keywords first (fast, strict-AND), vector similarity as the natural-language
95
- // fallback (~1s warm) — `qmd query` (LLM expansion + rerank) is too slow to block a prompt.
96
- const collection = `${path.basename(projectDir)}-facts`;
97
- const keywords = Array.from(
98
- new Set(
99
- prompt
100
- .toLowerCase()
101
- .replace(/[^a-z0-9\s_./-]/g, " ")
102
- .split(/\s+/)
103
- .filter((w) => w.length > 2 && !STOPWORDS.has(w)),
104
- ),
105
- )
106
- .slice(0, MAX_KEYWORDS)
107
- .join(" ");
108
- let hits = keywords ? qmdHits("search", keywords, collection) : [];
109
- if (!hits.length) hits = qmdHits("vsearch", prompt.replace(/\s+/g, " ").slice(0, 300), collection);
110
- if (!hits.length) return;
111
-
112
- // Inject each card at most once per session.
113
- const sessionKey = String(payload.session_id || "any").replace(/[^a-zA-Z0-9-]/g, "");
114
- const stateFile = path.join(os.tmpdir(), `etna-recall-${sessionKey}.txt`);
115
- let seen = [];
116
- try {
117
- seen = fs.readFileSync(stateFile, "utf8").split("\n").filter(Boolean);
118
- } catch (e) {
119
- seen = [];
120
- }
121
-
122
- const fresh = hits
123
- .filter((h) => h && h.score >= MIN_SCORE && h.file && !seen.includes(h.file))
124
- .slice(0, MAX_CARDS);
125
- const lines = [];
126
- for (const hit of fresh) {
127
- const statement = cardStatement(cardPath(factsDir, hit.file));
128
- if (statement) {
129
- lines.push(`- ${statement} [${String(hit.file).replace(/^qmd:\/\/[^/]+\//, "docs/memory/facts/")}]`);
130
- }
131
- }
132
- if (!lines.length) return;
133
-
134
- try {
135
- fs.appendFileSync(stateFile, fresh.map((h) => h.file).join("\n") + "\n", "utf8");
136
- } catch (e) {
137
- // Dedupe state is best-effort; a re-injection is harmless.
138
- }
139
-
140
- process.stdout.write(
141
- `<memory-recall>\nProject memory possibly relevant to this prompt (distilled fact-cards):\n${lines.join("\n")}\n</memory-recall>\n`,
142
- );
143
- }
144
-
145
- try {
146
- main();
147
- } catch (e) {
148
- try {
149
- process.stderr.write(`prompt-recall hook: ${e && e.message ? e.message : e}\n`);
150
- } catch (e2) {
151
- // Nothing more we can do.
152
- }
153
- } finally {
154
- process.exit(0);
155
- }
@@ -1,285 +0,0 @@
1
- // plugins/code/hooks/session-reflect.mjs — SessionEnd hook: reflect the session into durable lessons (headless haiku pass) appended to the actor's memory inbox.
2
-
3
- import fs from "node:fs";
4
- import os from "node:os";
5
- import path from "node:path";
6
- import { execFileSync, spawn } from "node:child_process";
7
- import { fileURLToPath } from "node:url";
8
- import { redact } from "./lib/redact.mjs";
9
-
10
- // ESM has no __filename; derive it from this module's URL for the detached worker re-spawn.
11
- const __filename = fileURLToPath(import.meta.url);
12
-
13
- // A session below all three thresholds carries no lesson worth a model call.
14
- const MIN_TURNS = 8;
15
- const MAX_MESSAGE_CHARS = 1500;
16
- const MAX_DIGEST_CHARS = 80000;
17
- const MAX_LESSONS = 6;
18
-
19
- // Read all of stdin synchronously; returns "" if nothing is piped.
20
- function readStdin() {
21
- try {
22
- return fs.readFileSync(0, "utf8");
23
- } catch (e) {
24
- return "";
25
- }
26
- }
27
-
28
- // Resolve the project root: CLAUDE_PROJECT_DIR env, else payload cwd, else process cwd.
29
- function resolveProjectDir(payload) {
30
- return process.env.CLAUDE_PROJECT_DIR || (payload && payload.cwd) || process.cwd();
31
- }
32
-
33
- // Run a git command in projectDir; returns trimmed stdout or fallback on any error.
34
- function git(projectDir, args, fallback) {
35
- try {
36
- return execFileSync("git", ["-C", projectDir, ...args], {
37
- encoding: "utf8",
38
- stdio: ["ignore", "pipe", "ignore"],
39
- }).trim() || fallback;
40
- } catch (e) {
41
- return fallback;
42
- }
43
- }
44
-
45
- // Slug a raw actor name into kebab-case ASCII.
46
- function slugActor(name) {
47
- return String(name || "")
48
- .toLowerCase()
49
- .replace(/[^a-z0-9]+/g, "-")
50
- .replace(/^-+|-+$/g, "");
51
- }
52
-
53
- // Determine the actor: git user.name (slugged) → $USER → "agent".
54
- function resolveActor(projectDir) {
55
- const fromGit = slugActor(git(projectDir, ["config", "user.name"], ""));
56
- if (fromGit) return fromGit;
57
- const fromEnv = slugActor(process.env.USER || "");
58
- if (fromEnv) return fromEnv;
59
- return "agent";
60
- }
61
-
62
- // Truncate a single line to n chars with an ellipsis marker.
63
- function clip(text, n) {
64
- const clean = String(text || "").replace(/\s+/g, " ").trim();
65
- return clean.length > n ? clean.slice(0, n) + "…" : clean;
66
- }
67
-
68
- // Extract plain text from a message whose content is a string or content-block array.
69
- function extractText(msg) {
70
- if (!msg || !msg.content) return "";
71
- if (typeof msg.content === "string") return msg.content;
72
- if (Array.isArray(msg.content)) {
73
- return msg.content
74
- .filter((b) => b && b.type === "text" && typeof b.text === "string")
75
- .map((b) => b.text)
76
- .join(" ");
77
- }
78
- return "";
79
- }
80
-
81
- // Strip harness-injected wrappers so only what the user actually typed survives.
82
- function stripInjected(text) {
83
- return String(text || "")
84
- .replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, "")
85
- .replace(/<(local-command-caveat|local-command-stdout|local-command-stderr|command-name|command-message|command-args|command-contents)>[\s\S]*?<\/\1>/g, "")
86
- .trim();
87
- }
88
-
89
- // Scan an assistant message's tool_use blocks for edited files and git commits.
90
- function collectToolUse(msg, summary) {
91
- if (!msg || !Array.isArray(msg.content)) return;
92
- for (const block of msg.content) {
93
- if (!block || block.type !== "tool_use") continue;
94
- const name = block.name || "";
95
- const input = block.input || {};
96
- if (/^(Edit|Write|MultiEdit|NotebookEdit)$/.test(name) && input.file_path) {
97
- summary.files.add(input.file_path);
98
- }
99
- if (name === "Bash" && typeof input.command === "string" && /\bgit\s+commit\b/.test(input.command)) {
100
- summary.sawCommit = true;
101
- }
102
- }
103
- }
104
-
105
- // Walk the JSONL transcript once: turn/edit/commit counts plus a USER/ASSISTANT text digest.
106
- function digestTranscript(transcriptPath) {
107
- const out = { turns: 0, files: new Set(), sawCommit: false, lines: [] };
108
- if (!transcriptPath || !fs.existsSync(transcriptPath)) return out;
109
- for (const line of fs.readFileSync(transcriptPath, "utf8").split("\n")) {
110
- if (!line.trim()) continue;
111
- let row;
112
- try {
113
- row = JSON.parse(line);
114
- } catch (e) {
115
- continue;
116
- }
117
- if (row.isSidechain) continue;
118
- const msg = row && row.message ? row.message : row;
119
- const role = (msg && msg.role) || row.type;
120
- if (role === "user") {
121
- const text = stripInjected(extractText(msg));
122
- if (!text || text.startsWith("Caveat: The messages below")) continue;
123
- out.lines.push("USER: " + clip(text, MAX_MESSAGE_CHARS));
124
- } else if (role === "assistant") {
125
- out.turns += 1;
126
- collectToolUse(msg, out);
127
- const text = extractText(msg);
128
- if (text) out.lines.push("ASSISTANT: " + clip(text, MAX_MESSAGE_CHARS));
129
- }
130
- }
131
- return out;
132
- }
133
-
134
- // Compute the per-actor inbox file path.
135
- function inboxPath(projectDir, actor) {
136
- const dir = path.join(projectDir, "docs", "memory", "inbox");
137
- return { dir, file: path.join(dir, `${actor}.md`) };
138
- }
139
-
140
- // True when this session already wrote an inbox entry (SessionEnd re-fires on resume).
141
- function alreadyReflected(file, sessionId) {
142
- try {
143
- return Boolean(sessionId) && fs.existsSync(file) && fs.readFileSync(file, "utf8").includes(`session ${sessionId}`);
144
- } catch (e) {
145
- return false;
146
- }
147
- }
148
-
149
- // Build the inbox file header block.
150
- function inboxHeader(actor) {
151
- return `# Memory inbox — ${actor}\nSession lessons awaiting distillation — appended by the session-reflect hook, consumed by \`distiller facts\`.\n`;
152
- }
153
-
154
- // The full output contract sits AFTER the transcript — with it only up front, the model
155
- // continues the conversation in the transcript instead of reflecting on it.
156
- const PROMPT_HEADER = [
157
- "You are a memory reflector. Below is the transcript of a FINISHED coding session,",
158
- "delimited by <transcript> tags. Do not reply to it or continue it — you will be asked",
159
- "to extract durable lessons from it after the closing tag.",
160
- "",
161
- "<transcript>",
162
- "",
163
- ].join("\n");
164
-
165
- const PROMPT_FOOTER = [
166
- "",
167
- "</transcript>",
168
- "",
169
- "The session above is over. Extract ONLY durable lessons a future session in this",
170
- "repository would benefit from knowing:",
171
- "- corrections or preferences the user stated",
172
- "- failures whose root cause was found, with the fix",
173
- "- decisions made, with their rationale",
174
- "- discovered constraints or non-obvious facts about the project or its tooling",
175
- "Rules:",
176
- "- Most sessions contain none. If nothing qualifies, output exactly: NONE",
177
- `- Otherwise output at most ${MAX_LESSONS} bullets and nothing else — no preamble, no headers.`,
178
- '- Each bullet starts with "- [project]" (true of this repo or its tooling) or "- [user]" (true of this user).',
179
- "- Each bullet is one complete, self-contained sentence with names and identifiers spelled out.",
180
- "- Routine work (commits made, files edited, tasks completed) is NOT a lesson. Never include secrets.",
181
- ].join("\n");
182
-
183
- // Hook mode: stash the payload and hand off to a detached worker so session exit is never delayed.
184
- function hook() {
185
- const raw = readStdin();
186
- let payload = {};
187
- try {
188
- payload = raw ? JSON.parse(raw) : {};
189
- } catch (e) {
190
- payload = {};
191
- }
192
- if (!payload.transcript_path) return;
193
-
194
- const stash = {
195
- projectDir: resolveProjectDir(payload),
196
- transcriptPath: payload.transcript_path,
197
- sessionId: payload.session_id || "",
198
- };
199
- const stashFile = path.join(os.tmpdir(), `etna-reflect-${stash.sessionId || process.pid}.json`);
200
- fs.writeFileSync(stashFile, JSON.stringify(stash), "utf8");
201
- spawn(process.execPath, [__filename, "--worker", stashFile], { detached: true, stdio: "ignore" }).unref();
202
- }
203
-
204
- // Worker mode: filter, digest, run the reflection model, append surviving lessons to the inbox.
205
- function worker(stashFile) {
206
- let stash;
207
- try {
208
- stash = JSON.parse(fs.readFileSync(stashFile, "utf8"));
209
- } finally {
210
- try {
211
- fs.rmSync(stashFile, { force: true });
212
- } catch (e) {
213
- // Stale stash files are harmless.
214
- }
215
- }
216
-
217
- const { projectDir, transcriptPath, sessionId } = stash;
218
- const digest = digestTranscript(transcriptPath);
219
- if (digest.turns < MIN_TURNS && digest.files.size === 0 && !digest.sawCommit) return;
220
-
221
- const actor = resolveActor(projectDir);
222
- const { dir, file } = inboxPath(projectDir, actor);
223
- if (alreadyReflected(file, sessionId)) return;
224
-
225
- let text = redact(digest.lines.join("\n"));
226
- if (text.length > MAX_DIGEST_CHARS) {
227
- text = text.slice(0, 8000) + "\n[... middle of session elided ...]\n" + text.slice(-(MAX_DIGEST_CHARS - 8000));
228
- }
229
-
230
- const output = execFileSync("claude", ["-p", "--model", "haiku"], {
231
- input: PROMPT_HEADER + text + PROMPT_FOOTER,
232
- encoding: "utf8",
233
- cwd: os.tmpdir(),
234
- env: Object.assign({}, process.env, { ETNA_REFLECT: "1" }),
235
- timeout: 240000,
236
- maxBuffer: 4 * 1024 * 1024,
237
- stdio: ["pipe", "pipe", "ignore"],
238
- });
239
-
240
- const lessons = output
241
- .split("\n")
242
- .map((l) => l.trim())
243
- .filter((l) => /^- \[(project|user)\]\s+\S/.test(l))
244
- .slice(0, MAX_LESSONS)
245
- .map((l) => redact(l));
246
- if (!lessons.length) return;
247
-
248
- const repo = path.basename(projectDir);
249
- const branch = git(projectDir, ["rev-parse", "--abbrev-ref", "HEAD"], "-");
250
- const now = new Date();
251
- const pad = (n) => String(n).padStart(2, "0");
252
- const stamp = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}`;
253
-
254
- fs.mkdirSync(dir, { recursive: true });
255
- if (alreadyReflected(file, sessionId)) return;
256
- const exists = fs.existsSync(file);
257
- const block =
258
- (exists ? "\n" : inboxHeader(actor) + "\n") +
259
- `## ${stamp} · session ${sessionId || "unknown"} · ${repo}@${branch}\n` +
260
- lessons.join("\n") +
261
- "\n";
262
- fs.appendFileSync(file, block, "utf8");
263
- }
264
-
265
- function main() {
266
- if (process.env.ETNA_REFLECT) return;
267
- const workerIdx = process.argv.indexOf("--worker");
268
- if (workerIdx !== -1) {
269
- worker(process.argv[workerIdx + 1]);
270
- } else {
271
- hook();
272
- }
273
- }
274
-
275
- try {
276
- main();
277
- } catch (e) {
278
- try {
279
- process.stderr.write(`session-reflect hook: ${e && e.message ? e.message : e}\n`);
280
- } catch (e2) {
281
- // Nothing more we can do.
282
- }
283
- } finally {
284
- process.exit(0);
285
- }