@luisarg/memory-auto 0.1.3 → 0.1.5

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 CHANGED
@@ -38,16 +38,25 @@ Environment variables used at load time: `DSH_MEMORY_PATH`,
38
38
 
39
39
  ## Behavior
40
40
 
41
- - `session.created` — registers the session (project name resolution).
42
- - `session.disposed` / dispose path post-session digest of the transcript.
43
- - `agent/status` idle auto-capture gate: skips sessions without activity or
44
- with a checkpoint already delivered.
45
- - `tool.execute.after`-style event tracking detects `git commit*` and queues
46
- a commit checkpoint prompt for the running agent.
47
- - `experimental.session.compacting` pre-compaction capture (always fires when
48
- there is activity).
49
- - `agent/pre-step` delivers queued checkpoint prompts (the agent writes
50
- entries with the `store_*` MCP tools).
41
+ - `session/created` — registers the session and resolves the project name
42
+ (`openspec/` present directory basename; else `package.json` name; else
43
+ `pyproject.toml` `[project].name`; else first `#` heading of `README.md`;
44
+ else directory basename).
45
+ - `session/disposed` digests the transcript, skipping sessions with no
46
+ activity. A dispose-time `ctx.effect` batch-digests any session still
47
+ pending, using the tracked activity summary as a stand-in transcript.
48
+ - `agent/status` with status `idle` — runs the auto-capture gate
49
+ (`idleCheckpoint`): skips sessions without activity or already delivered, and
50
+ on the first idle of a session also digests the tracked activity summary.
51
+ - `session/event` — tracks activity and queues checkpoints:
52
+ - `tool/call` (also accepted as `tool_call`) whose `args.command` matches
53
+ `git commit` queues a commit checkpoint.
54
+ - `compaction/start` queues a pre-compaction checkpoint (fires whenever there
55
+ is activity, even if one was already delivered).
56
+ - `user/message` and `assistant/message` are recorded as tracked activity.
57
+ - `agent/pre-step` — delivers the queued checkpoint by pushing it onto
58
+ `payload.context` (or `payload.messages`), and the agent writes entries with
59
+ the `store_*` MCP tools.
51
60
 
52
61
  Extraction failures are retried with bounded backoff and logged; a failed
53
62
  digest never takes the agent down.
package/dist/index.d.ts CHANGED
@@ -1,9 +1,8 @@
1
1
  import Schema from "@deepseek-ai/schemastery";
2
2
  import { Context } from "@deepseek-ai/cordis";
3
-
4
3
  //#region src/plugin.d.ts
5
- declare const name = "memory-auto";
6
- interface Config {
4
+ export declare const name = "memory-auto";
5
+ export interface Config {
7
6
  memoryPath: string;
8
7
  serverDir: string;
9
8
  provider: string;
@@ -12,8 +11,9 @@ interface Config {
12
11
  minTranscriptChars: number;
13
12
  enabled: boolean;
14
13
  }
15
- declare const Config: Schema<Config>;
16
- declare function apply(ctx: Context, config: Config): void;
14
+ export declare const Config: Schema<Config>;
15
+ /** Requires the harness LLM service: extraction runs in-process via ctx.llm. */
16
+ export declare const inject: string[];
17
+ export declare function apply(ctx: Context, config: Config): void;
17
18
  //#endregion
18
- export { Config, apply, name };
19
19
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/plugin.ts"],"sourcesContent":[],"mappings":";;;;cAkBa,IAAA;UAEI,MAAA;EAFJ,UAAI,EAAA,MAAA;EAEA,SAAM,EAAA,MAAA;EAUV,QAAA,EAQX,MAAA;EA+Cc,KAAA,EAAA,MAAK;;;;;cAvDR,QAAQ,OAAO;iBAuDZ,KAAA,MAAW,iBAAiB"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/plugin.ts"],"mappings":";;;qBAgCa;iBAEI;EACf;EACA;EACA;EACA;EACA;EACA;EACA;;qBAGW,QAAQ,OAAO;;qBAWf;wBA4CG,MAAM,KAAK,SAAS,QAAQ"}
package/dist/index.js CHANGED
@@ -7,10 +7,56 @@ import { readFile } from "node:fs/promises";
7
7
  import { spawn } from "node:child_process";
8
8
  import readline from "node:readline";
9
9
  import { BlockAssembler, createUserMessage } from "@deepseek-ai/dsh-llm";
10
-
10
+ import { parse } from "yaml";
11
+ import { BUNDLED_SKILL_RANK } from "@deepseek-ai/dsh-skill";
11
12
  //#region src/pure.ts
13
+ /**
14
+ * DSH memory plugin (adapted from the OpenCode memory plugin).
15
+ *
16
+ * Pure helpers only: prompt builders, transcript chunking, JSON repair and
17
+ * entry validation. No I/O and no harness wiring — `plugin.ts` owns the hook
18
+ * registration and `digest.ts` owns the LLM call and vault writes.
19
+ */
12
20
  const CHECKPOINT_MARKER = "[memory-checkpoint]";
13
21
  /**
22
+ * Entry types the vault's MCP server can store via `store_*` tools. The
23
+ * extraction prompt is restricted to these so every produced entry has a
24
+ * write path (no `idea`/`context`/`source` — those have no store tool).
25
+ */
26
+ const EXTRACTABLE_TYPES = [
27
+ "decision",
28
+ "fact",
29
+ "learning",
30
+ "convention"
31
+ ];
32
+ /**
33
+ * Shared entry vocabulary: one definition list, used by BOTH the internal
34
+ * extraction prompt and the agent-facing checkpoint prompt. Keeping one source
35
+ * stops the two from drifting, which is how the checkpoint prompt ended up
36
+ * asking agents to write entries it never defined.
37
+ */
38
+ const ENTRY_TYPE_GLOSS = {
39
+ decision: "architectural or design choices that were made",
40
+ fact: "stable, verifiable statements about the project (versions, constraints)",
41
+ learning: "non-obvious lessons, debugging insights, or solutions found",
42
+ convention: "style rules, naming patterns, coding conventions agreed"
43
+ };
44
+ /** Content shape, quoted by both prompts. */
45
+ const ENTRY_CONTENT_RULE = "a single paragraph — no headings, no bullet lists, no markdown structure";
46
+ /**
47
+ * What "notable" means, shared by both prompts. The extraction model is told
48
+ * these rules; the agent writing checkpoints needs them just as much.
49
+ */
50
+ const ENTRY_SELECTION_RULES = [
51
+ "Skip trivia (greetings, \"ok\", \"thanks\", restating the request).",
52
+ "Prefer fewer, high-signal entries over many weak ones.",
53
+ "Do not record anything you cannot ground in this session's activity."
54
+ ];
55
+ /** Entry-type clauses as bullet lines, in EXTRACTABLE_TYPES order. */
56
+ function entryTypeBullets() {
57
+ return EXTRACTABLE_TYPES.map((t) => `- **${t}**: ${ENTRY_TYPE_GLOSS[t]}.`);
58
+ }
59
+ /**
14
60
  * Resolve the project name from a working directory.
15
61
  * Priority:
16
62
  * 1. OpenSpec presence: if `openspec/` exists, use the basename.
@@ -28,7 +74,7 @@ async function resolveProjectName(cwd) {
28
74
  } catch {}
29
75
  const pyprojectPath = join(cwd, "pyproject.toml");
30
76
  if (existsSync(pyprojectPath)) try {
31
- const m = (await readFile(pyprojectPath, "utf-8")).match(/\[project\][^\[]*?name\s*=\s*["']([^"']+)["']/);
77
+ const m = (await readFile(pyprojectPath, "utf-8")).match(/\[project\][^[]*?name\s*=\s*["']([^"']+)["']/);
32
78
  if (m) return m[1];
33
79
  } catch {}
34
80
  const readmePath = join(cwd, "README.md");
@@ -59,7 +105,13 @@ function buildCheckpointPrompt(state, activitySummary) {
59
105
  "Tracked activity:",
60
106
  activitySummary.trim() || "(none recorded)",
61
107
  "",
62
- "Write OKF entries for any notable decisions, facts, or learnings using the `store_*` MCP tools.",
108
+ "Write OKF entries for anything notable using the `store_*` MCP tools.",
109
+ "Entry types:",
110
+ ...entryTypeBullets(),
111
+ "",
112
+ `Set \`content\` to ${ENTRY_CONTENT_RULE}, and \`description\` to a one-sentence summary.`,
113
+ "Tag with lowercase-kebab tags (at least one, e.g. architecture/python/testing).",
114
+ ...ENTRY_SELECTION_RULES,
63
115
  "If nothing is notable, say so explicitly and exit."
64
116
  ].join("\n");
65
117
  }
@@ -89,22 +141,17 @@ function buildCommitCheckpointPrompt(state) {
89
141
  return [
90
142
  `${CHECKPOINT_MARKER} Memory capture after \`git commit\` in project \`${state.project}\`.`,
91
143
  "",
92
- "Review the staged/committed changes and write OKF entries for any notable decisions, facts, or learnings.",
144
+ "Review the staged/committed changes and write OKF entries through the `store_*` MCP tools.",
145
+ "Entry types:",
146
+ ...entryTypeBullets(),
147
+ "",
148
+ `Set \`content\` to ${ENTRY_CONTENT_RULE}, and \`description\` to a one-sentence summary.`,
149
+ "Tag with lowercase-kebab tags (at least one, e.g. architecture/python/testing).",
150
+ ...ENTRY_SELECTION_RULES,
93
151
  "If nothing is notable, say so explicitly and exit."
94
152
  ].join("\n");
95
153
  }
96
154
  /**
97
- * Entry types the vault's MCP server can store via `store_*` tools. The
98
- * extraction prompt is restricted to these so every produced entry has a
99
- * write path (no `idea`/`context`/`source` — those have no store tool).
100
- */
101
- const EXTRACTABLE_TYPES = [
102
- "decision",
103
- "fact",
104
- "learning",
105
- "convention"
106
- ];
107
- /**
108
155
  * Build the system + user messages for the in-process extraction call.
109
156
  * The system part instructs the model to return a JSON array restricted to
110
157
  * EXTRACTABLE_TYPES; the user part carries the transcript.
@@ -113,7 +160,7 @@ function buildExtractionPrompt(project, transcript, contextFiles = {}) {
113
160
  const sysParts = ["You are an assistant that extracts durable knowledge from a session transcript."];
114
161
  if (contextFiles.criticalFacts?.trim()) sysParts.push(`Always-loaded context: CRITICAL_FACTS.md\n${contextFiles.criticalFacts.trim()}`);
115
162
  if (contextFiles.claude?.trim()) sysParts.push(`Always-loaded context: _CLAUDE.md\n${contextFiles.claude.trim()}`);
116
- sysParts.push(`For the transcript of project \`${project}\`, identify:`, "- **Decisions**: architectural or design choices that were made.", "- **Facts**: stable, verifiable statements about the project (versions, conventions, constraints).", "- **Learnings**: non-obvious lessons, debugging insights, or solutions found.", "- **Conventions**: style rules, naming patterns, coding conventions agreed.", "", "Return a JSON array. Each element must have exactly:", " - \"entry_type\": one of \"decision\" | \"fact\" | \"learning\" | \"convention\"", " - \"content\": a single-paragraph statement (no headings, no lists)", " - \"description\": a one-sentence summary of `content` (queryable)", " - \"tags\": an array of lowercase-kebab tags (never empty if possible, at least 1 like architecture/python/testing)", " - \"confidence\": a number 0.0-1.0", " - \"openspec_change_id\": (optional) the change slug if the transcript names it", "", "Rules:", "- Skip trivial exchanges (greetings, \"ok\", \"thanks\", or anything with no project knowledge).", "- Prefer fewer, higher-signal entries over many weak ones.", "- Do not include anything not present in the transcript.", "", "Return only the JSON array. No prose, no markdown fences.");
163
+ sysParts.push(`For the transcript of project \`${project}\`, identify:`, ...entryTypeBullets(), "", "Return a JSON array. Each element must have exactly:", ` - "entry_type": one of ${EXTRACTABLE_TYPES.map((t) => `"${t}"`).join(" | ")}`, ` - "content": ${ENTRY_CONTENT_RULE}`, " - \"description\": a one-sentence summary of `content` (queryable)", " - \"tags\": an array of lowercase-kebab tags (never empty if possible, at least 1 like architecture/python/testing)", " - \"confidence\": a number 0.0-1.0", " - \"openspec_change_id\": (optional) the change slug if the transcript names it", "", "Rules:", ...ENTRY_SELECTION_RULES.map((r) => `- ${r}`), "", "Return only the JSON array. No prose, no markdown fences.");
117
164
  return {
118
165
  system: sysParts.join("\n"),
119
166
  user: `Project: ${project}\n\nTranscript:\n---\n${transcript}\n---`
@@ -213,7 +260,6 @@ function validateEntries(payload) {
213
260
  }
214
261
  return valid;
215
262
  }
216
-
217
263
  //#endregion
218
264
  //#region src/digest.ts
219
265
  const MIN_DIGEST_TRANSCRIPT_CHARS = 200;
@@ -233,9 +279,9 @@ function transcriptOfDSM(events) {
233
279
  return text ? `## assistant\n${text}` : null;
234
280
  }
235
281
  if (t === "tool/call" || t === "tool_call") {
236
- const name$1 = d.tool ?? d.name ?? "tool";
282
+ const name = d.tool ?? d.name ?? "tool";
237
283
  const args = d.args ?? d.arguments ?? {};
238
- return `## tool_call ${name$1}\n${JSON.stringify(args).slice(0, 1e3)}`;
284
+ return `## tool_call ${name}\n${JSON.stringify(args).slice(0, 1e3)}`;
239
285
  }
240
286
  if (t === "tool/result" || t === "tool_result") return `## tool_result\n${typeof d.output === "string" ? d.output : JSON.stringify(d).slice(0, 1e3)}`;
241
287
  if (t.startsWith("compaction")) return `## ${t}\n${JSON.stringify(d).slice(0, 500)}`;
@@ -387,13 +433,13 @@ function connectMcp(memoryPath, serverDir) {
387
433
  }).then(() => {
388
434
  if (closed) throw new Error("memory-vault-server closed during handshake");
389
435
  resolve({
390
- callTool: (name$1, args$1, timeoutMs = MCP_CALL_TIMEOUT_MS) => send("tools/call", {
391
- name: name$1,
392
- arguments: args$1
436
+ callTool: (name, args, timeoutMs = MCP_CALL_TIMEOUT_MS) => send("tools/call", {
437
+ name,
438
+ arguments: args
393
439
  }, timeoutMs).then((result) => {
394
440
  if (result?.isError) {
395
441
  const text = Array.isArray(result.content) ? result.content.map((c) => c?.text ?? "").join("") : JSON.stringify(result);
396
- throw new Error(`tool ${name$1} failed: ${text}`);
442
+ throw new Error(`tool ${name} failed: ${text}`);
397
443
  }
398
444
  return result;
399
445
  }),
@@ -427,7 +473,7 @@ async function writeEntries(client, project, entries) {
427
473
  content: e.content,
428
474
  ...e.description ? { description: e.description } : {},
429
475
  tags: e.tags,
430
- confidence: e.confidence,
476
+ ...e.entry_type === "fact" ? { confidence: e.confidence } : {},
431
477
  ...e.openspec_change_id ? { openspec_change_id: e.openspec_change_id } : {}
432
478
  });
433
479
  upserted += 1;
@@ -492,9 +538,129 @@ async function digestSessionDSM(ctx, config, sessionId, directory, project, even
492
538
  await client.close().catch(() => {});
493
539
  }
494
540
  }
495
-
541
+ //#endregion
542
+ //#region src/skills.ts
543
+ /**
544
+ * Bundled skill shipped in this package: `checkpoint-auto`, the contract of the
545
+ * automatic capture this plugin performs (triggers, the `[memory-checkpoint]`
546
+ * marker, the digest, and the knobs). The capture *procedure* it defers to
547
+ * lives in `@luisarg/memory-mcp`'s `checkpoint` skill, which is installed
548
+ * alongside this plugin.
549
+ *
550
+ * A provider rather than `ctx.skills.register()` on purpose. A registration
551
+ * lands at the runtime rank, which outranks a user's own skill directories,
552
+ * while BUNDLED_SKILL_RANK is the weakest rank in the local discovery table:
553
+ * shipping at the weakest rank means a user who drops their own skill of the
554
+ * same name into `~/.agents/skills` keeps winning. This is a default, not a
555
+ * takeover.
556
+ *
557
+ * Each SKILL.md stays the single source of its own name, description and
558
+ * usage guidance — the frontmatter is parsed here with the same `yaml`
559
+ * dependency the harness's own filesystem provider uses, so the exact file that
560
+ * ships in this package also works copied into a user skill root. Kept as a
561
+ * copy of the sibling provider in `@luisarg/memory-mcp`: the two packages
562
+ * publish independently, and a shared third package would add a release
563
+ * artifact to maintain for this much stable plumbing.
564
+ */
565
+ /** Provider name registered on `ctx.skills`. */
566
+ const SKILLS_PROVIDER = "memory-auto-skills";
567
+ /** Shipped skill directories, relative to the package root. */
568
+ const SKILL_NAMES = ["checkpoint-auto"];
569
+ const SKILLS_ROOT = new URL("../skills/", import.meta.url);
570
+ const INVOCATION = {
571
+ modelInvocable: true,
572
+ userInvocable: true
573
+ };
574
+ function skillUrl(name) {
575
+ return new URL(`${name}/SKILL.md`, SKILLS_ROOT);
576
+ }
577
+ function resourceBase(name) {
578
+ return {
579
+ kind: "directory",
580
+ path: fileURLToPath(new URL(`${name}/`, SKILLS_ROOT))
581
+ };
582
+ }
583
+ /** Split YAML frontmatter from the body, mirroring the harness filesystem provider. */
584
+ function splitFrontmatter(raw) {
585
+ const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(raw);
586
+ if (match === null) throw new Error("SKILL.md has no YAML frontmatter");
587
+ const parsed = parse(match[1]);
588
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new TypeError("SKILL.md frontmatter must be a YAML mapping");
589
+ return {
590
+ data: parsed,
591
+ body: raw.slice(match[0].length).trim()
592
+ };
593
+ }
594
+ function textField(data, key) {
595
+ const value = data[key];
596
+ return typeof value === "string" && value.length > 0 ? value : void 0;
597
+ }
598
+ /** Read one shipped skill, rejecting a file whose frontmatter disagrees with its directory. */
599
+ async function loadSkill(name) {
600
+ const { data, body } = splitFrontmatter(await readFile(skillUrl(name), "utf8"));
601
+ const declared = textField(data, "name");
602
+ if (declared !== name) throw new Error(`skills/${name}/SKILL.md declares name "${declared ?? "(none)"}"`);
603
+ const description = textField(data, "description");
604
+ if (description === void 0) throw new Error(`skills/${name}/SKILL.md has no description`);
605
+ const whenToUse = textField(data, "whenToUse");
606
+ return {
607
+ frontmatter: {
608
+ name,
609
+ description,
610
+ ...whenToUse === void 0 ? {} : { whenToUse }
611
+ },
612
+ body
613
+ };
614
+ }
615
+ /** Skills shipped as packaged Markdown assets. */
616
+ const skillsProvider = {
617
+ name: SKILLS_PROVIDER,
618
+ async list() {
619
+ return await Promise.all(SKILL_NAMES.map(async (name) => {
620
+ const { frontmatter } = await loadSkill(name);
621
+ return {
622
+ ...frontmatter,
623
+ path: fileURLToPath(skillUrl(name)),
624
+ invocation: INVOCATION,
625
+ source: "bundled",
626
+ provider: SKILLS_PROVIDER,
627
+ resourceBase: resourceBase(name),
628
+ rank: BUNDLED_SKILL_RANK,
629
+ locator: skillUrl(name)
630
+ };
631
+ }));
632
+ },
633
+ async get(candidate) {
634
+ const loaded = await loadSkill(candidate.name).catch(() => void 0);
635
+ if (loaded === void 0) return void 0;
636
+ const { frontmatter, body } = loaded;
637
+ return {
638
+ ...frontmatter,
639
+ path: fileURLToPath(skillUrl(candidate.name)),
640
+ invocation: INVOCATION,
641
+ source: "bundled",
642
+ provider: SKILLS_PROVIDER,
643
+ resourceBase: resourceBase(candidate.name),
644
+ content: body
645
+ };
646
+ }
647
+ };
496
648
  //#endregion
497
649
  //#region src/plugin.ts
650
+ /**
651
+ * Harness wiring for `memory-auto`. Registers exactly these hooks:
652
+ *
653
+ * - `session/created` resolve the project name for the session
654
+ * - `session/disposed` digest the transcript
655
+ * - `agent/status` (idle) auto-capture gate
656
+ * - `session/event` activity tracking; `tool/call` with a
657
+ * `git commit` command and `compaction/start`
658
+ * queue checkpoints
659
+ * - `agent/pre-step` deliver the queued checkpoint to the agent
660
+ * - `ctx.effect` dispose batch-digest sessions still pending
661
+ *
662
+ * The agent writes the entries; this plugin only prompts it.
663
+ */
498
664
  const name = "memory-auto";
499
665
  const Config = Schema.object({
500
666
  memoryPath: Schema.string().default(process.env.DSH_MEMORY_PATH ?? ""),
@@ -505,6 +671,8 @@ const Config = Schema.object({
505
671
  minTranscriptChars: Schema.number().default(200),
506
672
  enabled: Schema.boolean().default(true)
507
673
  });
674
+ /** Requires the harness LLM service: extraction runs in-process via ctx.llm. */
675
+ const inject = ["llm"];
508
676
  /**
509
677
  * Resolve the harness home the same way the harness does (`$DSH_HOME`, or
510
678
  * `~/.dsh`). Paths must never depend on the launch cwd: DSH does not chdir.
@@ -539,6 +707,9 @@ function ensureFile(target, bundled, file) {
539
707
  return true;
540
708
  }
541
709
  function apply(ctx, config) {
710
+ ctx.inject(["skills"], (ctx) => {
711
+ ctx.skills.registerProvider(() => skillsProvider);
712
+ });
542
713
  if (!config.enabled) {
543
714
  console.log("[memory-auto] disabled via config");
544
715
  return;
@@ -607,7 +778,9 @@ function apply(ctx, config) {
607
778
  return;
608
779
  }
609
780
  const dir = sessionDirs.get(sid) ?? "";
610
- await digestSessionDSM(ctx, digestConfig, sid, dir, await projectFor(dir), session?.events ?? []);
781
+ const proj = await projectFor(dir);
782
+ const evts = session?.events ?? [];
783
+ await digestSessionDSM(ctx, digestConfig, sid, dir, proj, evts);
611
784
  });
612
785
  ctx.on("agent/status", async (payload) => {
613
786
  const agent = payload?.agent;
@@ -619,10 +792,12 @@ function apply(ctx, config) {
619
792
  if (idleCheckpoint(st, summary(sid))) {
620
793
  console.log(`[memory-auto] idle checkpoint digest for ${sid}`);
621
794
  const dir = sessionDirs.get(sid) ?? "";
622
- await digestSessionDSM(ctx, digestConfig, sid, dir, await projectFor(dir), [{
795
+ const proj = await projectFor(dir);
796
+ const fakeEvents = [{
623
797
  type: "user/message",
624
798
  data: { text: summary(sid) }
625
- }]);
799
+ }];
800
+ await digestSessionDSM(ctx, digestConfig, sid, dir, proj, fakeEvents);
626
801
  }
627
802
  });
628
803
  ctx.on("session/event", async (session, event) => {
@@ -679,17 +854,18 @@ function apply(ctx, config) {
679
854
  for (const [sid, dir] of sessionDirs) {
680
855
  if (!states.get(sid)?.hasActivity) continue;
681
856
  projectFor(dir).then((proj) => {
682
- digestSessionDSM(ctx, digestConfig, sid, dir, proj, [{
857
+ const fakeEvents = [{
683
858
  type: "user/message",
684
859
  data: { text: summary(sid) }
685
- }]);
860
+ }];
861
+ digestSessionDSM(ctx, digestConfig, sid, dir, proj, fakeEvents);
686
862
  });
687
863
  }
688
864
  };
689
865
  });
690
866
  console.log(`[memory-auto] active memoryPath=${memoryPath} serverDir=${serverDir} llm=${config.provider}/${config.model}`);
691
867
  }
692
-
693
868
  //#endregion
694
- export { Config, apply, name };
869
+ export { Config, apply, inject, name };
870
+
695
871
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["sysParts: string[]","chunks: string[]","valid: ValidEntry[]","name","messages: Message[]","options: GenerateOptions","child: ChildProcess","msg: any","args","entries: ValidEntry[]","client: McpClient","Config: Schema<Config>","digestConfig: DigestConfig","sid: string | undefined"],"sources":["../src/pure.ts","../src/digest.ts","../src/plugin.ts"],"sourcesContent":["/**\n * DSH memory plugin (adapted from the OpenCode memory plugin).\n *\n * Implements session lifecycle hooks:\n * - session.created: project name resolution only (no memory auto-injection)\n * - session.idle: auto-capture gate (skip if no activity or already delivered)\n * - tool.execute.after: detect `git commit*` and queue a checkpoint\n * - tui.prompt.append: deliver queued checkpoint on next user message\n * - experimental.session.compacting: pre-compaction capture (always fires)\n * - session.end: invoke post-session digest\n * - /brain search|recall|profile: opt-in reads via MCP (2s health check)\n * - /checkpoint: manual structured review\n * - OpenCode version guard: warn on < 1.17.10, disable gracefully\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { join, basename } from \"node:path\";\n\n// ── Constants ────────────────────────────────────────────────────────────\n\nexport const MIN_OPENCODE_VERSION = \"1.17.10\";\nexport const MCP_UNREACHABLE =\n \"> ⚠️ Memory server unreachable — search cannot be completed.\";\nconst CHECKPOINT_MARKER = \"[memory-checkpoint]\";\n\n// ── Version guard ────────────────────────────────────────────────────────\n\n/** Compare two \"x.y.z\" semver strings. Returns negative/0/positive. */\nfunction compareSemver(a: string, b: string): number {\n const [a1, a2, a3] = a.split(\".\").map((n) => parseInt(n, 10) || 0);\n const [b1, b2, b3] = b.split(\".\").map((n) => parseInt(n, 10) || 0);\n if (a1 !== b1) return a1 - b1;\n if (a2 !== b2) return a2 - b2;\n return (a3 || 0) - (b3 || 0);\n}\n\nexport function isSupportedVersion(version: string): boolean {\n return compareSemver(version, MIN_OPENCODE_VERSION) >= 0;\n}\n\n// ── Project name resolution ──────────────────────────────────────────────\n\n/**\n * Resolve the project name from a working directory.\n * Priority:\n * 1. OpenSpec presence: if `openspec/` exists, use the basename.\n * 2. package.json -> name\n * 3. pyproject.toml -> [project] -> name\n * 4. README.md: first 5 lines, heading pattern `# <ProjectName>`\n * 5. Fallback: basename of working directory\n */\nexport async function resolveProjectName(cwd: string): Promise<string> {\n if (existsSync(join(cwd, \"openspec\"))) {\n return basename(cwd);\n }\n // package.json\n const pkgPath = join(cwd, \"package.json\");\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(await readFile(pkgPath, \"utf-8\"));\n if (typeof pkg.name === \"string\" && pkg.name.trim()) {\n return pkg.name.trim();\n }\n } catch {\n // ignore parse errors; try next strategy\n }\n }\n // pyproject.toml (minimal regex parse)\n const pyprojectPath = join(cwd, \"pyproject.toml\");\n if (existsSync(pyprojectPath)) {\n try {\n const text = await readFile(pyprojectPath, \"utf-8\");\n const m = text.match(/\\[project\\][^\\[]*?name\\s*=\\s*[\"']([^\"']+)[\"']/);\n if (m) return m[1];\n } catch {\n // ignore\n }\n }\n // README.md heading\n const readmePath = join(cwd, \"README.md\");\n if (existsSync(readmePath)) {\n try {\n const text = await readFile(readmePath, \"utf-8\");\n const head = text.split(\"\\n\").slice(0, 5);\n for (const line of head) {\n const m = line.match(/^#\\s+(.+)$/);\n if (m) return m[1].trim();\n }\n } catch {\n // ignore\n }\n }\n return basename(cwd);\n}\n\n// ── Checkpoint state ─────────────────────────────────────────────────────\n\nexport interface SessionState {\n project: string;\n hasActivity: boolean;\n checkpointDelivered: boolean;\n queuedCheckpoint: string | null;\n}\n\nexport function createSessionState(project: string): SessionState {\n return {\n project,\n hasActivity: false,\n checkpointDelivered: false,\n queuedCheckpoint: null,\n };\n}\n\n/**\n * Build the checkpoint prompt body. Pure function — exported for testing.\n */\nexport function buildCheckpointPrompt(state: SessionState, activitySummary: string): string {\n return [\n `${CHECKPOINT_MARKER} End-of-session memory capture for project \\`${state.project}\\`.`,\n \"\",\n \"Tracked activity:\",\n activitySummary.trim() || \"(none recorded)\",\n \"\",\n \"Write OKF entries for any notable decisions, facts, or learnings using the `store_*` MCP tools.\",\n \"If nothing is notable, say so explicitly and exit.\",\n ].join(\"\\n\");\n}\n\n/**\n * Decide whether to deliver a checkpoint on `session.idle`.\n * Returns the prompt to deliver, or null to skip.\n */\nexport function idleCheckpoint(\n state: SessionState,\n activitySummary: string,\n): string | null {\n if (!state.hasActivity) return null;\n if (state.checkpointDelivered) return null;\n state.checkpointDelivered = true;\n return buildCheckpointPrompt(state, activitySummary);\n}\n\n/**\n * Decide whether to fire on `experimental.session.compacting`.\n * Per spec: always fires when activity exists, even if checkpoint was delivered.\n */\nexport function compactingCheckpoint(\n state: SessionState,\n activitySummary: string,\n): string | null {\n if (!state.hasActivity) return null;\n return buildCheckpointPrompt(state, activitySummary);\n}\n\n// ── Git commit detection ─────────────────────────────────────────────────\n\nconst GIT_COMMIT_PATTERN = /git\\s+commit\\b/;\n\nexport function isGitCommit(command: string): boolean {\n return GIT_COMMIT_PATTERN.test(command);\n}\n\nexport function buildCommitCheckpointPrompt(state: SessionState): string {\n return [\n `${CHECKPOINT_MARKER} Memory capture after \\`git commit\\` in project \\`${state.project}\\`.`,\n \"\",\n \"Review the staged/committed changes and write OKF entries for any notable decisions, facts, or learnings.\",\n \"If nothing is notable, say so explicitly and exit.\",\n ].join(\"\\n\");\n}\n\n// ── In-process session digest (ctx.llm) ──────────────────────────────────\n\n/**\n * Entry types the vault's MCP server can store via `store_*` tools. The\n * extraction prompt is restricted to these so every produced entry has a\n * write path (no `idea`/`context`/`source` — those have no store tool).\n */\nexport const EXTRACTABLE_TYPES = ['decision', 'fact', 'learning', 'convention'] as const\nexport type ExtractableType = (typeof EXTRACTABLE_TYPES)[number]\n\n/** One validated OKF entry ready to be stored through the vault server. */\nexport interface ValidEntry {\n entry_type: ExtractableType\n content: string\n description: string\n tags: string[]\n confidence: number\n openspec_change_id: string | null\n}\n\n/** Optional vault context files to embed in the extraction prompt. */\nexport interface DigestContextFiles {\n criticalFacts?: string\n claude?: string\n}\n\n/**\n * Build the system + user messages for the in-process extraction call.\n * The system part instructs the model to return a JSON array restricted to\n * EXTRACTABLE_TYPES; the user part carries the transcript.\n */\nexport function buildExtractionPrompt(\n project: string,\n transcript: string,\n contextFiles: DigestContextFiles = {},\n): { system: string; user: string } {\n const sysParts: string[] = [\n 'You are an assistant that extracts durable knowledge from a session transcript.',\n ]\n if (contextFiles.criticalFacts?.trim()) {\n sysParts.push(`Always-loaded context: CRITICAL_FACTS.md\\n${contextFiles.criticalFacts.trim()}`)\n }\n if (contextFiles.claude?.trim()) {\n sysParts.push(`Always-loaded context: _CLAUDE.md\\n${contextFiles.claude.trim()}`)\n }\n sysParts.push(\n `For the transcript of project \\`${project}\\`, identify:`,\n '- **Decisions**: architectural or design choices that were made.',\n '- **Facts**: stable, verifiable statements about the project (versions, conventions, constraints).',\n '- **Learnings**: non-obvious lessons, debugging insights, or solutions found.',\n '- **Conventions**: style rules, naming patterns, coding conventions agreed.',\n '',\n 'Return a JSON array. Each element must have exactly:',\n ' - \"entry_type\": one of \"decision\" | \"fact\" | \"learning\" | \"convention\"',\n ' - \"content\": a single-paragraph statement (no headings, no lists)',\n ' - \"description\": a one-sentence summary of `content` (queryable)',\n ' - \"tags\": an array of lowercase-kebab tags (never empty if possible, at least 1 like architecture/python/testing)',\n ' - \"confidence\": a number 0.0-1.0',\n ' - \"openspec_change_id\": (optional) the change slug if the transcript names it',\n '',\n 'Rules:',\n '- Skip trivial exchanges (greetings, \"ok\", \"thanks\", or anything with no project knowledge).',\n '- Prefer fewer, higher-signal entries over many weak ones.',\n '- Do not include anything not present in the transcript.',\n '',\n 'Return only the JSON array. No prose, no markdown fences.',\n )\n return {\n system: sysParts.join('\\n'),\n user: `Project: ${project}\\n\\nTranscript:\\n---\\n${transcript}\\n---`,\n }\n}\n\n/**\n * Split an oversized transcript into overlapping chunks (mirrors the legacy\n * digest script: 25k chars per chunk, 1k overlap, at most `cap` chunks).\n */\nexport function chunkTranscript(text: string, maxLen = 50_000, chunkSize = 25_000, overlap = 1_000, cap = 3): string[] {\n if (text.length <= maxLen) return [text]\n const chunks: string[] = []\n let i = 0\n while (i < text.length) {\n chunks.push(text.slice(i, i + chunkSize))\n i += chunkSize - overlap\n if (chunks.length >= cap) break\n }\n return chunks\n}\n\n/** Best-effort repair of common LLM JSON output; returns parsed value or null. */\nexport function repairJson(text: string): unknown {\n const s = text.trim()\n // Strip code fences: ```json ... ```\n const fenced = s.replace(/^```(?:json)?\\s*/i, '').replace(/\\s*```$/, '').trim()\n // Trailing commas: `,]` / `,}` -> `]` / `}`\n const noTrailing = fenced.replace(/,(\\s*[\\]}])/g, '$1')\n const candidates = [s, fenced, noTrailing]\n // Single-quote to double-quote conversion only when no double quotes exist.\n if (noTrailing.includes(\"'\") && !noTrailing.includes('\"')) {\n candidates.push(convertSingleQuotes(noTrailing))\n }\n for (const c of candidates) {\n try {\n return JSON.parse(c)\n } catch {\n // try the next candidate\n }\n }\n return null\n}\n\nfunction convertSingleQuotes(text: string): string {\n let out = ''\n let inString = false\n let i = 0\n while (i < text.length) {\n const ch = text[i]\n if (inString && ch === '\\\\') {\n if (i + 1 < text.length && text[i + 1] === \"'\") {\n out += \"'\"\n i += 2\n continue\n }\n out += ch\n if (i + 1 < text.length) {\n out += text[i + 1]\n i += 2\n continue\n }\n i += 1\n continue\n }\n if (ch === \"'\") {\n inString = !inString\n out += '\"'\n i += 1\n continue\n }\n out += ch\n i += 1\n }\n return out\n}\n\n/**\n * Validate a parsed extraction payload into OKF entries. Unknown types,\n * empty content and malformed values are dropped; tags and confidence are\n * normalized. Returns the valid entries (possibly empty).\n */\nexport function validateEntries(payload: unknown): ValidEntry[] {\n if (!Array.isArray(payload)) return []\n const valid: ValidEntry[] = []\n for (const item of payload) {\n if (typeof item !== 'object' || item === null) continue\n const raw = item as Record<string, unknown>\n const entryType = raw.entry_type\n if (typeof entryType !== 'string' || !(EXTRACTABLE_TYPES as readonly string[]).includes(entryType)) continue\n const content = typeof raw.content === 'string' ? raw.content.trim() : ''\n if (!content) continue\n const tags = Array.isArray(raw.tags) ? raw.tags.filter((t): t is string => typeof t === 'string' && t.length > 0) : []\n let confidence = 1\n if (typeof raw.confidence === 'number' && Number.isFinite(raw.confidence)) {\n confidence = Math.max(0, Math.min(1, raw.confidence))\n }\n const description = typeof raw.description === 'string' ? raw.description.trim() : ''\n const changeId = typeof raw.openspec_change_id === 'string' && raw.openspec_change_id ? raw.openspec_change_id : null\n valid.push({\n entry_type: entryType as ExtractableType,\n content,\n description,\n tags,\n confidence,\n openspec_change_id: changeId,\n })\n }\n return valid\n}\n\n// The full hook wiring is exposed for testing; the actual OpenCode integration\n// is done in `register.ts` (the entry point the OpenCode runtime loads via\n// package.json \"main\"). This module intentionally has no default export:\n// opencode 1.18.x only loads plugin modules with a single export.\nexport const __testing = {\n createSessionState,\n isSupportedVersion,\n resolveProjectName,\n idleCheckpoint,\n compactingCheckpoint,\n isGitCommit,\n buildCheckpointPrompt,\n buildCommitCheckpointPrompt,\n};\n","import { spawn, type ChildProcess } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport readline from 'node:readline'\nimport { BlockAssembler, createUserMessage } from '@deepseek-ai/dsh-llm'\nimport type { FinishReason, GenerateOptions, Message } from '@deepseek-ai/dsh-llm'\nimport type { Context } from '@deepseek-ai/cordis'\nimport {\n buildExtractionPrompt,\n chunkTranscript,\n repairJson,\n validateEntries,\n type ValidEntry,\n} from './pure.js'\n\n// Post-session digest runner: in-process LLM extraction via the harness's own\n// `ctx.llm` service (no external CLI, no credentials of its own), followed by\n// OKF writes through the vault's MCP server over stdio (`store_*` tools keep\n// the Markdown source of truth and the SQLite FTS5 index in sync).\n\nconst MIN_DIGEST_TRANSCRIPT_CHARS = 200\nconst LLM_RETRIES = 3\nconst LLM_RETRY_DELAYS_MS = [2_000, 5_000]\nconst MCP_CALL_TIMEOUT_MS = 60_000\n\nfunction log(msg: string) {\n console.log(`[memory-auto] ${msg}`)\n}\n\nexport function transcriptOfDSM(events: any[]): string {\n // DSH SessionEvent -> transcript\n return (events ?? [])\n .map((ev: any) => {\n const t = ev?.type ?? ''\n const d = ev?.data ?? ev\n if (t === 'user/message' || t === 'user_message') {\n const text = typeof d.text === 'string' ? d.text : typeof d.content === 'string' ? d.content : JSON.stringify(d).slice(0, 500)\n return `## user\\n${text}`\n }\n if (t === 'assistant/message' || t === 'assistant_message') {\n const text = typeof d.text === 'string' ? d.text : typeof d.content === 'string' ? d.content : ''\n return text ? `## assistant\\n${text}` : null\n }\n if (t === 'tool/call' || t === 'tool_call') {\n const name = d.tool ?? d.name ?? 'tool'\n const args = d.args ?? d.arguments ?? {}\n return `## tool_call ${name}\\n${JSON.stringify(args).slice(0, 1000)}`\n }\n if (t === 'tool/result' || t === 'tool_result') {\n const out = typeof d.output === 'string' ? d.output : JSON.stringify(d).slice(0, 1000)\n return `## tool_result\\n${out}`\n }\n if (t.startsWith('compaction')) return `## ${t}\\n${JSON.stringify(d).slice(0, 500)}`\n return null\n })\n .filter((x): x is string => Boolean(x))\n .join('\\n\\n')\n}\n\n/** Translate a terminal stream finish into a thrown error, mirroring dsh's own summarizers. */\nfunction finishError(finish: FinishReason): Error | undefined {\n switch (finish.kind) {\n case 'error':\n case 'aborted': {\n const error = new Error(finish.failure.message) as Error & { code?: string }\n error.code = finish.failure.code\n return error\n }\n default:\n return undefined\n }\n}\n\nexport interface DigestConfig {\n memoryPath: string\n serverDir: string\n provider: string\n model: string\n maxTokens: number\n minTranscriptChars: number\n}\n\n/**\n * Run one extraction call through the harness's `ctx.llm` service: build the\n * prompt, stream, assemble, repair and validate the JSON entries.\n */\nexport async function extractEntriesWithLlm(\n ctx: Context,\n config: DigestConfig,\n project: string,\n transcript: string,\n contextFiles?: { criticalFacts?: string; claude?: string },\n signal?: AbortSignal,\n): Promise<ValidEntry[]> {\n const { system, user } = buildExtractionPrompt(project, transcript, contextFiles)\n const assembler = new BlockAssembler()\n const messages: Message[] = [\n createUserMessage({\n content: [{ type: 'text', text: user }],\n source: { kind: 'plugin', plugin: 'memory-auto' },\n }),\n ]\n const options: GenerateOptions = {\n provider: config.provider,\n model: config.model,\n messages,\n system,\n maxTokens: config.maxTokens,\n ...(signal === undefined ? {} : { signal }),\n }\n for await (const chunk of ctx.llm.stream(options)) assembler.push(chunk)\n const error = finishError(assembler.finish)\n if (error !== undefined) throw error\n const text = assembler\n .blocks()\n .filter((b) => b.type === 'text')\n .map((b) => b.text)\n .join('')\n const parsed = repairJson(text)\n return validateEntries(parsed)\n}\n\n/** Minimal MCP stdio client for the vault server (spawned via its launcher: uv, pip venv fallback). */\nexport interface McpClient {\n callTool(name: string, args: Record<string, unknown>, timeoutMs?: number): Promise<unknown>\n close(): Promise<void>\n}\n\nexport function connectMcp(memoryPath: string, serverDir: string): Promise<McpClient> {\n return new Promise((resolve, reject) => {\n // Single decision point: the server bundle's launcher.mjs picks `uv run`\n // or a pip-managed .venv. Legacy hand-made server dirs without a launcher\n // keep the old direct `uv run` spawn.\n const launcher = join(serverDir, 'launcher.mjs')\n const [command, args] = existsSync(launcher)\n ? [process.execPath, [launcher]]\n : ['uv', ['run', '--directory', serverDir, 'python', 'server.py']]\n const child: ChildProcess = spawn(\n command,\n args,\n {\n env: { ...process.env, MEMORY_PATH: memoryPath, UV_CACHE_DIR: process.env.UV_CACHE_DIR ?? '/tmp/uv-cache' },\n stdio: ['pipe', 'pipe', 'inherit'],\n },\n )\n const pending = new Map<number, { resolve: (v: unknown) => void; reject: (e: Error) => void; timer: NodeJS.Timeout }>()\n let nextId = 1\n let closed = false\n\n const failAll = (err: Error) => {\n for (const [, p] of pending) {\n clearTimeout(p.timer)\n p.reject(err)\n }\n pending.clear()\n }\n\n child.on('error', (err) => {\n closed = true\n failAll(new Error(`memory-vault-server spawn failed: ${err.message}`))\n reject(err)\n })\n child.on('exit', (code) => {\n if (closed) return\n closed = true\n failAll(new Error(`memory-vault-server exited unexpectedly (code ${code})`))\n reject(new Error(`memory-vault-server exited before initialize (code ${code})`))\n })\n\n const rl = readline.createInterface({ input: child.stdout!, crlfDelay: Infinity })\n rl.on('line', (line) => {\n let msg: any\n try {\n msg = JSON.parse(line)\n } catch {\n return\n }\n if (typeof msg?.id === 'number') {\n const p = pending.get(msg.id)\n if (!p) return\n pending.delete(msg.id)\n clearTimeout(p.timer)\n if (msg.error) p.reject(new Error(`MCP error: ${msg.error.message ?? JSON.stringify(msg.error)}`))\n else p.resolve(msg.result)\n }\n })\n\n const send = (method: string, params: unknown, timeoutMs: number = MCP_CALL_TIMEOUT_MS): Promise<unknown> =>\n new Promise((res, rej) => {\n if (closed || !child.stdin?.writable) {\n rej(new Error('memory-vault-server is not running'))\n return\n }\n const id = nextId++\n const timer = setTimeout(() => {\n pending.delete(id)\n rej(new Error(`MCP call ${method} timed out after ${timeoutMs}ms`))\n }, timeoutMs)\n pending.set(id, { resolve: res, reject: rej, timer })\n child.stdin!.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\\n')\n })\n\n const notify = (method: string, params: unknown) => {\n if (!closed && child.stdin?.writable) {\n child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method, params }) + '\\n')\n }\n }\n\n // initialize handshake (notifications are fire-and-forget: no id, no reply)\n void send('initialize', {\n protocolVersion: '2025-06-18',\n capabilities: {},\n clientInfo: { name: 'memory-auto', version: '0.1.0' },\n })\n .then(() => {\n notify('notifications/initialized', {})\n })\n .then(() => {\n if (closed) throw new Error('memory-vault-server closed during handshake')\n resolve({\n callTool: (name, args, timeoutMs = MCP_CALL_TIMEOUT_MS) =>\n send('tools/call', { name, arguments: args }, timeoutMs).then((result: any) => {\n if (result?.isError) {\n const text = Array.isArray(result.content) ? result.content.map((c: any) => c?.text ?? '').join('') : JSON.stringify(result)\n throw new Error(`tool ${name} failed: ${text}`)\n }\n return result\n }),\n close: async () => {\n if (closed) return\n closed = true\n for (const [, p] of pending) clearTimeout(p.timer)\n pending.clear()\n if (child.exitCode !== null) return\n child.kill()\n await new Promise((r) => child.once('exit', r))\n },\n })\n })\n .catch((err) => {\n closed = true\n child.kill()\n reject(err)\n })\n })\n}\n\n/**\n * Write validated OKF entries through the vault server's `store_*` tools,\n * which upsert both the Markdown file and the SQLite FTS5 index.\n */\nexport async function writeEntries(client: McpClient, project: string, entries: ValidEntry[]): Promise<{ upserted: number; failed: number }> {\n let upserted = 0\n let failed = 0\n for (const e of entries) {\n try {\n await client.callTool(`store_${e.entry_type}`, {\n project,\n content: e.content,\n ...(e.description ? { description: e.description } : {}),\n tags: e.tags,\n confidence: e.confidence,\n ...(e.openspec_change_id ? { openspec_change_id: e.openspec_change_id } : {}),\n })\n upserted += 1\n } catch (err) {\n failed += 1\n console.warn(`[memory-auto] store_${e.entry_type} failed:`, err instanceof Error ? err.message : err)\n }\n }\n return { upserted, failed }\n}\n\n/**\n * Full post-session digest: transcript -> ctx.llm extraction (with retries) ->\n * OKF writes via the vault MCP server. Never throws; logs the outcome.\n */\nexport async function digestSessionDSM(\n ctx: Context,\n config: DigestConfig,\n sessionId: string,\n directory: string,\n project: string,\n events: any[],\n signal?: AbortSignal,\n): Promise<void> {\n const header = `## context\\nproject: ${project}\\ndirectory: ${directory}\\n`\n const transcript = (header + transcriptOfDSM(events)).trim()\n if (!transcript) {\n log(`digest skip ${sessionId}: empty`)\n return\n }\n if (transcript.length < (config.minTranscriptChars ?? MIN_DIGEST_TRANSCRIPT_CHARS)) {\n log(`digest skip ${sessionId}: too short ${transcript.length}`)\n return\n }\n\n const chunks = chunkTranscript(transcript)\n const entries: ValidEntry[] = []\n for (const chunk of chunks) {\n let attempt = 0\n for (;;) {\n try {\n const got = await extractEntriesWithLlm(ctx, config, project, chunk, undefined, signal)\n entries.push(...got)\n break\n } catch (err) {\n attempt += 1\n if (attempt >= LLM_RETRIES || signal?.aborted) {\n console.warn(`[memory-auto] digest extraction failed after ${attempt} attempt(s):`, err instanceof Error ? err.message : err)\n break\n }\n const delay = LLM_RETRY_DELAYS_MS[attempt - 1] ?? 5_000\n log(`digest extraction retry ${attempt}/${LLM_RETRIES} in ${delay}ms`)\n await new Promise((r) => setTimeout(r, delay))\n }\n }\n if (signal?.aborted) break\n }\n\n if (entries.length === 0) {\n log(`digest ${sessionId}: no entries extracted`)\n return\n }\n\n let client: McpClient\n try {\n client = await connectMcp(config.memoryPath, config.serverDir)\n } catch (err) {\n console.warn(`[memory-auto] digest ${sessionId}: cannot reach vault server:`, err instanceof Error ? err.message : err)\n return\n }\n try {\n const { upserted, failed } = await writeEntries(client, project, entries)\n log(`digest ${sessionId}: ${upserted} upserted, ${failed} failed (${entries.length} extracted)`)\n } finally {\n await client.close().catch(() => {})\n }\n}\n","import { cpSync, existsSync, mkdirSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { dirname, isAbsolute, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport type { Context } from '@deepseek-ai/cordis'\nimport Schema from '@deepseek-ai/schemastery'\nimport {\n createSessionState,\n resolveProjectName,\n idleCheckpoint,\n compactingCheckpoint,\n isGitCommit,\n buildCheckpointPrompt,\n buildCommitCheckpointPrompt,\n type SessionState,\n} from './pure.js'\nimport { digestSessionDSM, type DigestConfig } from './digest.js'\n\nexport const name = 'memory-auto'\n\nexport interface Config {\n memoryPath: string\n serverDir: string\n provider: string\n model: string\n maxTokens: number\n minTranscriptChars: number\n enabled: boolean\n}\n\nexport const Config: Schema<Config> = Schema.object({\n memoryPath: Schema.string().default(process.env.DSH_MEMORY_PATH ?? ''),\n serverDir: Schema.string().default(process.env.DSH_MEMORY_SERVER_DIR ?? ''),\n provider: Schema.string().default('deepseek-official'),\n model: Schema.string().default('deepseek-v4-flash'),\n maxTokens: Schema.number().default(2048),\n minTranscriptChars: Schema.number().default(200),\n enabled: Schema.boolean().default(true),\n})\n\n/** Requires the harness LLM service: extraction runs in-process via ctx.llm. */\nexport const inject = ['llm']\n\n/**\n * Resolve the harness home the same way the harness does (`$DSH_HOME`, or\n * `~/.dsh`). Paths must never depend on the launch cwd: DSH does not chdir.\n */\nfunction dshHome(): string {\n const env = process.env.DSH_HOME?.trim()\n return env && env.length > 0 ? env : join(homedir(), '.dsh')\n}\n\n/** Absolute paths stay; empty/relative values resolve under the harness home. */\nfunction resolveUnderHome(value: string, fallbackSegment: string): string {\n const v = value.trim()\n if (v.length === 0) return join(dshHome(), fallbackSegment)\n return isAbsolute(v) ? v : join(dshHome(), v)\n}\n\nconst packageRoot = dirname(dirname(fileURLToPath(import.meta.url)))\n\n/** Copy the bundled dir into `target` when `key` is missing there. */\nfunction ensure(target: string, bundled: string, key: string): boolean {\n if (existsSync(join(target, key))) return false\n if (!existsSync(bundled)) return false\n mkdirSync(target, { recursive: true })\n cpSync(bundled, target, { recursive: true })\n return true\n}\n\n/** Copy one bundled file into `target` when missing (upgrades add files 0.1.1 → 0.1.2). */\nfunction ensureFile(target: string, bundled: string, file: string): boolean {\n const dest = join(target, file)\n if (existsSync(dest)) return false\n const src = join(bundled, file)\n if (!existsSync(src)) return false\n mkdirSync(target, { recursive: true })\n cpSync(src, dest)\n return true\n}\n\n// DSH session shape minimal\ntype DSHEvt = any\ntype DSHSession = { id: string; events: DSHEvt[]; cwd?: string }\n\nexport function apply(ctx: Context, config: Config) {\n if (!config.enabled) {\n console.log('[memory-auto] disabled via config')\n return\n }\n\n const memoryPath = resolveUnderHome(config.memoryPath, 'memory-vault')\n const serverDir = resolveUnderHome(config.serverDir, 'memory-vault-server')\n\n // Self-contained install: first boot copies the bundled server and vault\n // starter under the harness home when they are missing.\n if (ensure(serverDir, join(packageRoot, 'server'), 'server.py')) {\n console.log(`[memory-auto] installed memory-vault-server -> ${serverDir}`)\n }\n if (ensure(memoryPath, join(packageRoot, 'vault'), 'type-registry.yaml')) {\n console.log(`[memory-auto] installed vault starter -> ${memoryPath}`)\n }\n // launcher.mjs runs the server via uv or the pip-venv fallback; upgrades of\n // existing installs (server.py already present) still need the new files.\n const bundledServer = join(packageRoot, 'server')\n for (const file of ['launcher.mjs', 'requirements.txt']) {\n if (ensureFile(serverDir, bundledServer, file)) {\n console.log(`[memory-auto] installed ${file} -> ${serverDir}`)\n }\n }\n\n const digestConfig: DigestConfig = {\n memoryPath,\n serverDir,\n provider: config.provider,\n model: config.model,\n maxTokens: config.maxTokens,\n minTranscriptChars: config.minTranscriptChars,\n }\n\n if (!existsSync(join(serverDir, 'server.py'))) {\n console.warn(\n `[memory-auto] vault server not found at ${serverDir} and not bundled — the digest cannot write. ` +\n 'Set DSH_MEMORY_SERVER_DIR (or run `node scripts/bundle-assets.mjs` in a checkout).',\n )\n }\n if (!existsSync(join(memoryPath, 'type-registry.yaml'))) {\n console.warn(`[memory-auto] vault starter not found at ${memoryPath} — searches will fail until it exists.`)\n }\n\n const states = new Map<string, SessionState>()\n const activities = new Map<string, string[]>()\n const queued = new Map<string, string>()\n const sessionDirs = new Map<string, string>()\n const projectCache = new Map<string, string>()\n\n const ACTIVITY_MAX_LINES = 20\n const ACTIVITY_MAX_CHARS = 80\n\n const track = (sessionId: string, line: string) => {\n const st = states.get(sessionId)\n if (!st) return\n st.hasActivity = true\n const list = activities.get(sessionId) ?? []\n if (!list.includes(line)) {\n list.push(line)\n if (list.length > ACTIVITY_MAX_LINES) list.shift()\n activities.set(sessionId, list)\n }\n }\n\n const summary = (sid: string) => (activities.get(sid) ?? []).join('\\n')\n\n const projectFor = async (dir: string): Promise<string> => {\n const cached = projectCache.get(dir)\n if (cached) return cached\n const p = await resolveProjectName(dir || process.cwd())\n projectCache.set(dir, p)\n return p\n }\n\n // session/created -> init state\n ctx.on('session/created', async (session: DSHSession) => {\n const sid = (session as any)?.id ?? (session as any)?.sessionId\n const dir = (session as any)?.cwd ?? (session as any)?.directory ?? ''\n if (!sid) return\n const proj = await projectFor(dir)\n if (!states.has(sid)) {\n states.set(sid, createSessionState(proj))\n activities.set(sid, [])\n }\n sessionDirs.set(sid, dir)\n console.log(`[memory-auto] session created ${sid} project=${proj}`)\n })\n\n // session/disposed -> digest\n ctx.on('session/disposed', async (session: DSHSession) => {\n const sid = (session as any)?.id ?? (session as any)?.sessionId\n if (!sid) return\n const st = states.get(sid)\n if (!st) return\n if (!st.hasActivity) {\n console.log(`[memory-auto] digest skip ${sid}: no activity`)\n return\n }\n const dir = sessionDirs.get(sid) ?? ''\n const proj = await projectFor(dir)\n const evts: DSHEvt[] = (session as any)?.events ?? []\n await digestSessionDSM(ctx, digestConfig, sid, dir, proj, evts)\n })\n\n // agent/status idle -> in-session capture gate\n ctx.on('agent/status', async (payload: any) => {\n const agent = payload?.agent\n const status = payload?.status ?? payload?.agentStatus\n if (status !== 'idle') return\n const sid: string | undefined = agent?.sessionId ?? payload?.sessionId ?? agent?.id\n if (!sid) return\n const st = states.get(sid)\n if (!st) return\n const text = idleCheckpoint(st, summary(sid))\n if (text) {\n console.log(`[memory-auto] idle checkpoint digest for ${sid}`)\n const dir = sessionDirs.get(sid) ?? ''\n const proj = await projectFor(dir)\n const fakeEvents = [{ type: 'user/message', data: { text: summary(sid) } }]\n await digestSessionDSM(ctx, digestConfig, sid, dir, proj, fakeEvents)\n }\n })\n\n // session/event -> git commit detect + compaction start\n ctx.on('session/event', async (session: DSHSession, event: DSHEvt) => {\n const sid = (session as any)?.id ?? (session as any)?.sessionId ?? (event as any)?.sessionId\n if (!sid) return\n const t = event?.type ?? ''\n const d = event?.data ?? {}\n\n // compaction/start -> checkpoint injection (delivered on the next pre-step)\n if (t === 'compaction/start') {\n const st = states.get(sid)\n if (!st) return\n const txt = compactingCheckpoint(st, summary(sid))\n if (txt) {\n console.log(`[memory-auto] compaction checkpoint queued for ${sid}`)\n queued.set(sid, txt)\n }\n return\n }\n\n // tool/call -> git commit detection + activity track\n if (t === 'tool/call' || t === 'tool_call') {\n const cmd = d?.args?.command ?? d?.command ?? ''\n if (typeof cmd === 'string' && isGitCommit(cmd)) {\n const st = states.get(sid)\n if (st) {\n st.hasActivity = true\n queued.set(sid, buildCommitCheckpointPrompt(st))\n console.log(`[memory-auto] git commit queued for ${sid}`)\n }\n return\n }\n if (typeof cmd === 'string') {\n track(sid, `bash: ${cmd.trim().slice(0, ACTIVITY_MAX_CHARS)}`)\n }\n return\n }\n if (t === 'tool/result') {\n // ignore\n return\n }\n if (t === 'user/message' || t === 'assistant/message') {\n // track activity\n track(sid, `${t}: ${(d?.text ?? '').slice(0, ACTIVITY_MAX_CHARS)}`)\n }\n })\n\n // agent/pre-step Waterfall -> deliver queued checkpoint\n ctx.on('agent/pre-step', async (payload: any, next: any) => {\n const sid: string | undefined = payload?.agent?.sessionId ?? payload?.sessionId\n if (sid) {\n const q = queued.get(sid)\n if (q) {\n queued.delete(sid)\n // Best effort: append the checkpoint as user context\n if (Array.isArray(payload?.context)) payload.context.push(q)\n else if (Array.isArray(payload?.messages)) payload.messages.push({ role: 'user', content: q })\n else console.log(`[memory-auto] deliver queued checkpoint for ${sid}`)\n }\n }\n return next()\n })\n\n // dispose -> batch digest remaining sessions\n ctx.effect(() => {\n return () => {\n console.log(`[memory-auto] dispose batch ${sessionDirs.size} sessions`)\n // fire-and-forget digest for each remaining session\n for (const [sid, dir] of sessionDirs) {\n const st = states.get(sid)\n if (!st?.hasActivity) continue\n projectFor(dir).then((proj) => {\n const fakeEvents = [{ type: 'user/message', data: { text: summary(sid) } }]\n void digestSessionDSM(ctx, digestConfig, sid, dir, proj, fakeEvents)\n })\n }\n }\n })\n\n console.log(`[memory-auto] active memoryPath=${memoryPath} serverDir=${serverDir} llm=${config.provider}/${config.model}`)\n}\n"],"mappings":";;;;;;;;;;;AAwBA,MAAM,oBAAoB;;;;;;;;;;AA4B1B,eAAsB,mBAAmB,KAA8B;AACrE,KAAI,WAAW,KAAK,KAAK,WAAW,CAAC,CACnC,QAAO,SAAS,IAAI;CAGtB,MAAM,UAAU,KAAK,KAAK,eAAe;AACzC,KAAI,WAAW,QAAQ,CACrB,KAAI;EACF,MAAM,MAAM,KAAK,MAAM,MAAM,SA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C1D,MAAMA,MAA0B,SAAS,OAAO,aAAa,SAAS;AACtE,MAAI,KAAK;GACP,MAAM,IAAI,OAAO,IAAI,IAAI;AACzB,OAAI,GAAG;AACL,WAAO,OAAO,IAAI;AAElB,QAAI,MAAM,QAAQ,SAAS,QAAQ,CAAE,SAAQ,QAAQ,KAAK,EAAE;aACnD,MAAM,QAAQ,SAAS,SAAS,CAAE,SAAQ,SAAS,KAAK;KAAE,MAAM;KAAQ,SAAS;KAAG,CAAC;QACzF,SAAQ,IAAI,+CAA+C,MAAM;;;AAG1E,SAAO,MAAM;GACb;AAGF,KAAI,aAAa;AACf,eAAa;AACX,WAAQ,IAAI,+BAA+B,YAAY,KAAK,WAAW;AAEvE,QAAK,MAAM,CAAC,KAAK,QAAQ,aAAa;AAEpC,QAAI,CADO,OAAO,IAAI,IAAI,EACjB,YAAa;AACtB,eAAW,IAAI,CAAC,MAAM,SAAS;AAE7B,KAAK,iBAAiB,KAAK,cAAc,KAAK,KAAK,MADhC,CAAC;MAAE,MAAM;MAAgB,MAAM,EAAE,MAAM,QAAQ,IAAI,EAAE;MAAE,CAAC,CACP;MACpE;;;GAGN;AAEF,SAAQ,IAAI,mCAAmC,WAAW,aAAa,UAAU,OAAO,OAAO,SAAS,GAAG,OAAO,QAAQ"}
1
+ {"version":3,"file":"index.js","names":["parseYaml"],"sources":["../src/pure.ts","../src/digest.ts","../src/skills.ts","../src/plugin.ts"],"sourcesContent":["/**\n * DSH memory plugin (adapted from the OpenCode memory plugin).\n *\n * Pure helpers only: prompt builders, transcript chunking, JSON repair and\n * entry validation. No I/O and no harness wiring — `plugin.ts` owns the hook\n * registration and `digest.ts` owns the LLM call and vault writes.\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport { join, basename } from \"node:path\";\n\n// ── Constants ────────────────────────────────────────────────────────────\n\nexport const MIN_OPENCODE_VERSION = \"1.17.10\";\nexport const MCP_UNREACHABLE =\n \"> ⚠️ Memory server unreachable — search cannot be completed.\";\nconst CHECKPOINT_MARKER = \"[memory-checkpoint]\";\n\n/**\n * Entry types the vault's MCP server can store via `store_*` tools. The\n * extraction prompt is restricted to these so every produced entry has a\n * write path (no `idea`/`context`/`source` — those have no store tool).\n */\nexport const EXTRACTABLE_TYPES = ['decision', 'fact', 'learning', 'convention'] as const\nexport type ExtractableType = (typeof EXTRACTABLE_TYPES)[number]\n\n/**\n * Shared entry vocabulary: one definition list, used by BOTH the internal\n * extraction prompt and the agent-facing checkpoint prompt. Keeping one source\n * stops the two from drifting, which is how the checkpoint prompt ended up\n * asking agents to write entries it never defined.\n */\nconst ENTRY_TYPE_GLOSS: Record<ExtractableType, string> = {\n decision: \"architectural or design choices that were made\",\n fact: \"stable, verifiable statements about the project (versions, constraints)\",\n learning: \"non-obvious lessons, debugging insights, or solutions found\",\n convention: \"style rules, naming patterns, coding conventions agreed\",\n}\n\n/** Content shape, quoted by both prompts. */\nconst ENTRY_CONTENT_RULE =\n \"a single paragraph — no headings, no bullet lists, no markdown structure\"\n\n/**\n * What \"notable\" means, shared by both prompts. The extraction model is told\n * these rules; the agent writing checkpoints needs them just as much.\n */\nconst ENTRY_SELECTION_RULES = [\n \"Skip trivia (greetings, \\\"ok\\\", \\\"thanks\\\", restating the request).\",\n \"Prefer fewer, high-signal entries over many weak ones.\",\n \"Do not record anything you cannot ground in this session's activity.\",\n] as const\n\n/** Entry-type clauses as bullet lines, in EXTRACTABLE_TYPES order. */\nfunction entryTypeBullets(): string[] {\n return EXTRACTABLE_TYPES.map((t) => `- **${t}**: ${ENTRY_TYPE_GLOSS[t]}.`)\n}\n\n\n// ── Version guard ────────────────────────────────────────────────────────\n\n/** Compare two \"x.y.z\" semver strings. Returns negative/0/positive. */\nfunction compareSemver(a: string, b: string): number {\n const [a1, a2, a3] = a.split(\".\").map((n) => parseInt(n, 10) || 0);\n const [b1, b2, b3] = b.split(\".\").map((n) => parseInt(n, 10) || 0);\n if (a1 !== b1) return a1 - b1;\n if (a2 !== b2) return a2 - b2;\n return (a3 || 0) - (b3 || 0);\n}\n\nexport function isSupportedVersion(version: string): boolean {\n return compareSemver(version, MIN_OPENCODE_VERSION) >= 0;\n}\n\n// ── Project name resolution ──────────────────────────────────────────────\n\n/**\n * Resolve the project name from a working directory.\n * Priority:\n * 1. OpenSpec presence: if `openspec/` exists, use the basename.\n * 2. package.json -> name\n * 3. pyproject.toml -> [project] -> name\n * 4. README.md: first 5 lines, heading pattern `# <ProjectName>`\n * 5. Fallback: basename of working directory\n */\nexport async function resolveProjectName(cwd: string): Promise<string> {\n if (existsSync(join(cwd, \"openspec\"))) {\n return basename(cwd);\n }\n // package.json\n const pkgPath = join(cwd, \"package.json\");\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(await readFile(pkgPath, \"utf-8\"));\n if (typeof pkg.name === \"string\" && pkg.name.trim()) {\n return pkg.name.trim();\n }\n } catch {\n // ignore parse errors; try next strategy\n }\n }\n // pyproject.toml (minimal regex parse)\n const pyprojectPath = join(cwd, \"pyproject.toml\");\n if (existsSync(pyprojectPath)) {\n try {\n const text = await readFile(pyprojectPath, \"utf-8\");\n const m = text.match(/\\[project\\][^[]*?name\\s*=\\s*[\"']([^\"']+)[\"']/);\n if (m) return m[1];\n } catch {\n // ignore\n }\n }\n // README.md heading\n const readmePath = join(cwd, \"README.md\");\n if (existsSync(readmePath)) {\n try {\n const text = await readFile(readmePath, \"utf-8\");\n const head = text.split(\"\\n\").slice(0, 5);\n for (const line of head) {\n const m = line.match(/^#\\s+(.+)$/);\n if (m) return m[1].trim();\n }\n } catch {\n // ignore\n }\n }\n return basename(cwd);\n}\n\n// ── Checkpoint state ─────────────────────────────────────────────────────\n\nexport interface SessionState {\n project: string;\n hasActivity: boolean;\n checkpointDelivered: boolean;\n queuedCheckpoint: string | null;\n}\n\nexport function createSessionState(project: string): SessionState {\n return {\n project,\n hasActivity: false,\n checkpointDelivered: false,\n queuedCheckpoint: null,\n };\n}\n\n/**\n * Build the checkpoint prompt body. Pure function — exported for testing.\n */\nexport function buildCheckpointPrompt(state: SessionState, activitySummary: string): string {\n return [\n `${CHECKPOINT_MARKER} End-of-session memory capture for project \\`${state.project}\\`.`,\n \"\",\n \"Tracked activity:\",\n activitySummary.trim() || \"(none recorded)\",\n \"\",\n \"Write OKF entries for anything notable using the `store_*` MCP tools.\",\n \"Entry types:\",\n ...entryTypeBullets(),\n \"\",\n `Set \\`content\\` to ${ENTRY_CONTENT_RULE}, and \\`description\\` to a one-sentence summary.`,\n \"Tag with lowercase-kebab tags (at least one, e.g. architecture/python/testing).\",\n ...ENTRY_SELECTION_RULES,\n \"If nothing is notable, say so explicitly and exit.\",\n ].join(\"\\n\");\n}\n\n/**\n * Decide whether to deliver a checkpoint on `session.idle`.\n * Returns the prompt to deliver, or null to skip.\n */\nexport function idleCheckpoint(\n state: SessionState,\n activitySummary: string,\n): string | null {\n if (!state.hasActivity) return null;\n if (state.checkpointDelivered) return null;\n state.checkpointDelivered = true;\n return buildCheckpointPrompt(state, activitySummary);\n}\n\n/**\n * Decide whether to fire on `experimental.session.compacting`.\n * Per spec: always fires when activity exists, even if checkpoint was delivered.\n */\nexport function compactingCheckpoint(\n state: SessionState,\n activitySummary: string,\n): string | null {\n if (!state.hasActivity) return null;\n return buildCheckpointPrompt(state, activitySummary);\n}\n\n// ── Git commit detection ─────────────────────────────────────────────────\n\nconst GIT_COMMIT_PATTERN = /git\\s+commit\\b/;\n\nexport function isGitCommit(command: string): boolean {\n return GIT_COMMIT_PATTERN.test(command);\n}\n\nexport function buildCommitCheckpointPrompt(state: SessionState): string {\n return [\n `${CHECKPOINT_MARKER} Memory capture after \\`git commit\\` in project \\`${state.project}\\`.`,\n \"\",\n \"Review the staged/committed changes and write OKF entries through the `store_*` MCP tools.\",\n \"Entry types:\",\n ...entryTypeBullets(),\n \"\",\n `Set \\`content\\` to ${ENTRY_CONTENT_RULE}, and \\`description\\` to a one-sentence summary.`,\n \"Tag with lowercase-kebab tags (at least one, e.g. architecture/python/testing).\",\n ...ENTRY_SELECTION_RULES,\n \"If nothing is notable, say so explicitly and exit.\",\n ].join(\"\\n\");\n}\n\n// ── In-process session digest (ctx.llm) ──────────────────────────────────\n\n/** One validated OKF entry ready to be stored through the vault server. */\nexport interface ValidEntry {\n entry_type: ExtractableType\n content: string\n description: string\n tags: string[]\n confidence: number\n openspec_change_id: string | null\n}\n\n/** Optional vault context files to embed in the extraction prompt. */\nexport interface DigestContextFiles {\n criticalFacts?: string\n claude?: string\n}\n\n/**\n * Build the system + user messages for the in-process extraction call.\n * The system part instructs the model to return a JSON array restricted to\n * EXTRACTABLE_TYPES; the user part carries the transcript.\n */\nexport function buildExtractionPrompt(\n project: string,\n transcript: string,\n contextFiles: DigestContextFiles = {},\n): { system: string; user: string } {\n const sysParts: string[] = [\n 'You are an assistant that extracts durable knowledge from a session transcript.',\n ]\n if (contextFiles.criticalFacts?.trim()) {\n sysParts.push(`Always-loaded context: CRITICAL_FACTS.md\\n${contextFiles.criticalFacts.trim()}`)\n }\n if (contextFiles.claude?.trim()) {\n sysParts.push(`Always-loaded context: _CLAUDE.md\\n${contextFiles.claude.trim()}`)\n }\n sysParts.push(\n `For the transcript of project \\`${project}\\`, identify:`,\n ...entryTypeBullets(),\n '',\n 'Return a JSON array. Each element must have exactly:',\n ` - \"entry_type\": one of ${EXTRACTABLE_TYPES.map((t) => `\"${t}\"`).join(' | ')}`,\n ` - \"content\": ${ENTRY_CONTENT_RULE}`,\n ' - \"description\": a one-sentence summary of `content` (queryable)',\n ' - \"tags\": an array of lowercase-kebab tags (never empty if possible, at least 1 like architecture/python/testing)',\n ' - \"confidence\": a number 0.0-1.0',\n ' - \"openspec_change_id\": (optional) the change slug if the transcript names it',\n '',\n 'Rules:',\n ...ENTRY_SELECTION_RULES.map((r) => `- ${r}`),\n '',\n 'Return only the JSON array. No prose, no markdown fences.',\n )\n return {\n system: sysParts.join('\\n'),\n user: `Project: ${project}\\n\\nTranscript:\\n---\\n${transcript}\\n---`,\n }\n}\n\n/**\n * Split an oversized transcript into overlapping chunks (mirrors the legacy\n * digest script: 25k chars per chunk, 1k overlap, at most `cap` chunks).\n */\nexport function chunkTranscript(text: string, maxLen = 50_000, chunkSize = 25_000, overlap = 1_000, cap = 3): string[] {\n if (text.length <= maxLen) return [text]\n const chunks: string[] = []\n let i = 0\n while (i < text.length) {\n chunks.push(text.slice(i, i + chunkSize))\n i += chunkSize - overlap\n if (chunks.length >= cap) break\n }\n return chunks\n}\n\n/** Best-effort repair of common LLM JSON output; returns parsed value or null. */\nexport function repairJson(text: string): unknown {\n const s = text.trim()\n // Strip code fences: ```json ... ```\n const fenced = s.replace(/^```(?:json)?\\s*/i, '').replace(/\\s*```$/, '').trim()\n // Trailing commas: `,]` / `,}` -> `]` / `}`\n const noTrailing = fenced.replace(/,(\\s*[\\]}])/g, '$1')\n const candidates = [s, fenced, noTrailing]\n // Single-quote to double-quote conversion only when no double quotes exist.\n if (noTrailing.includes(\"'\") && !noTrailing.includes('\"')) {\n candidates.push(convertSingleQuotes(noTrailing))\n }\n for (const c of candidates) {\n try {\n return JSON.parse(c)\n } catch {\n // try the next candidate\n }\n }\n return null\n}\n\nfunction convertSingleQuotes(text: string): string {\n let out = ''\n let inString = false\n let i = 0\n while (i < text.length) {\n const ch = text[i]\n if (inString && ch === '\\\\') {\n if (i + 1 < text.length && text[i + 1] === \"'\") {\n out += \"'\"\n i += 2\n continue\n }\n out += ch\n if (i + 1 < text.length) {\n out += text[i + 1]\n i += 2\n continue\n }\n i += 1\n continue\n }\n if (ch === \"'\") {\n inString = !inString\n out += '\"'\n i += 1\n continue\n }\n out += ch\n i += 1\n }\n return out\n}\n\n/**\n * Validate a parsed extraction payload into OKF entries. Unknown types,\n * empty content and malformed values are dropped; tags and confidence are\n * normalized. Returns the valid entries (possibly empty).\n */\nexport function validateEntries(payload: unknown): ValidEntry[] {\n if (!Array.isArray(payload)) return []\n const valid: ValidEntry[] = []\n for (const item of payload) {\n if (typeof item !== 'object' || item === null) continue\n const raw = item as Record<string, unknown>\n const entryType = raw.entry_type\n if (typeof entryType !== 'string' || !(EXTRACTABLE_TYPES as readonly string[]).includes(entryType)) continue\n const content = typeof raw.content === 'string' ? raw.content.trim() : ''\n if (!content) continue\n const tags = Array.isArray(raw.tags) ? raw.tags.filter((t): t is string => typeof t === 'string' && t.length > 0) : []\n let confidence = 1\n if (typeof raw.confidence === 'number' && Number.isFinite(raw.confidence)) {\n confidence = Math.max(0, Math.min(1, raw.confidence))\n }\n const description = typeof raw.description === 'string' ? raw.description.trim() : ''\n const changeId = typeof raw.openspec_change_id === 'string' && raw.openspec_change_id ? raw.openspec_change_id : null\n valid.push({\n entry_type: entryType as ExtractableType,\n content,\n description,\n tags,\n confidence,\n openspec_change_id: changeId,\n })\n }\n return valid\n}\n\n// The full hook wiring is exposed for testing; the actual OpenCode integration\n// is done in `register.ts` (the entry point the OpenCode runtime loads via\n// package.json \"main\"). This module intentionally has no default export:\n// opencode 1.18.x only loads plugin modules with a single export.\nexport const __testing = {\n createSessionState,\n isSupportedVersion,\n resolveProjectName,\n idleCheckpoint,\n compactingCheckpoint,\n isGitCommit,\n buildCheckpointPrompt,\n buildCommitCheckpointPrompt,\n};\n","import { spawn, type ChildProcess } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport readline from 'node:readline'\nimport { BlockAssembler, createUserMessage } from '@deepseek-ai/dsh-llm'\nimport type { FinishReason, GenerateOptions, Message } from '@deepseek-ai/dsh-llm'\nimport type { Context } from '@deepseek-ai/cordis'\nimport {\n buildExtractionPrompt,\n chunkTranscript,\n repairJson,\n validateEntries,\n type ValidEntry,\n} from './pure.js'\n\n// Post-session digest runner: in-process LLM extraction via the harness's own\n// `ctx.llm` service (no external CLI, no credentials of its own), followed by\n// OKF writes through the vault's MCP server over stdio (`store_*` tools keep\n// the Markdown source of truth and the SQLite FTS5 index in sync).\n\nconst MIN_DIGEST_TRANSCRIPT_CHARS = 200\nconst LLM_RETRIES = 3\nconst LLM_RETRY_DELAYS_MS = [2_000, 5_000]\nconst MCP_CALL_TIMEOUT_MS = 60_000\n\nfunction log(msg: string) {\n console.log(`[memory-auto] ${msg}`)\n}\n\nexport function transcriptOfDSM(events: any[]): string {\n // DSH SessionEvent -> transcript\n return (events ?? [])\n .map((ev: any) => {\n const t = ev?.type ?? ''\n const d = ev?.data ?? ev\n if (t === 'user/message' || t === 'user_message') {\n const text = typeof d.text === 'string' ? d.text : typeof d.content === 'string' ? d.content : JSON.stringify(d).slice(0, 500)\n return `## user\\n${text}`\n }\n if (t === 'assistant/message' || t === 'assistant_message') {\n const text = typeof d.text === 'string' ? d.text : typeof d.content === 'string' ? d.content : ''\n return text ? `## assistant\\n${text}` : null\n }\n if (t === 'tool/call' || t === 'tool_call') {\n const name = d.tool ?? d.name ?? 'tool'\n const args = d.args ?? d.arguments ?? {}\n return `## tool_call ${name}\\n${JSON.stringify(args).slice(0, 1000)}`\n }\n if (t === 'tool/result' || t === 'tool_result') {\n const out = typeof d.output === 'string' ? d.output : JSON.stringify(d).slice(0, 1000)\n return `## tool_result\\n${out}`\n }\n if (t.startsWith('compaction')) return `## ${t}\\n${JSON.stringify(d).slice(0, 500)}`\n return null\n })\n .filter((x): x is string => Boolean(x))\n .join('\\n\\n')\n}\n\n/** Translate a terminal stream finish into a thrown error, mirroring dsh's own summarizers. */\nfunction finishError(finish: FinishReason): Error | undefined {\n switch (finish.kind) {\n case 'error':\n case 'aborted': {\n const error = new Error(finish.failure.message) as Error & { code?: string }\n error.code = finish.failure.code\n return error\n }\n default:\n return undefined\n }\n}\n\nexport interface DigestConfig {\n memoryPath: string\n serverDir: string\n provider: string\n model: string\n maxTokens: number\n minTranscriptChars: number\n}\n\n/**\n * Run one extraction call through the harness's `ctx.llm` service: build the\n * prompt, stream, assemble, repair and validate the JSON entries.\n */\nexport async function extractEntriesWithLlm(\n ctx: Context,\n config: DigestConfig,\n project: string,\n transcript: string,\n contextFiles?: { criticalFacts?: string; claude?: string },\n signal?: AbortSignal,\n): Promise<ValidEntry[]> {\n const { system, user } = buildExtractionPrompt(project, transcript, contextFiles)\n const assembler = new BlockAssembler()\n const messages: Message[] = [\n createUserMessage({\n content: [{ type: 'text', text: user }],\n source: { kind: 'plugin', plugin: 'memory-auto' },\n }),\n ]\n const options: GenerateOptions = {\n provider: config.provider,\n model: config.model,\n messages,\n system,\n maxTokens: config.maxTokens,\n ...(signal === undefined ? {} : { signal }),\n }\n for await (const chunk of ctx.llm.stream(options)) assembler.push(chunk)\n const error = finishError(assembler.finish)\n if (error !== undefined) throw error\n const text = assembler\n .blocks()\n .filter((b) => b.type === 'text')\n .map((b) => b.text)\n .join('')\n const parsed = repairJson(text)\n return validateEntries(parsed)\n}\n\n/** Minimal MCP stdio client for the vault server (spawned via its launcher: uv, pip venv fallback). */\nexport interface McpClient {\n callTool(name: string, args: Record<string, unknown>, timeoutMs?: number): Promise<unknown>\n close(): Promise<void>\n}\n\nexport function connectMcp(memoryPath: string, serverDir: string): Promise<McpClient> {\n return new Promise((resolve, reject) => {\n // Single decision point: the server bundle's launcher.mjs picks `uv run`\n // or a pip-managed .venv. Legacy hand-made server dirs without a launcher\n // keep the old direct `uv run` spawn.\n const launcher = join(serverDir, 'launcher.mjs')\n const [command, args] = existsSync(launcher)\n ? [process.execPath, [launcher]]\n : ['uv', ['run', '--directory', serverDir, 'python', 'server.py']]\n const child: ChildProcess = spawn(\n command,\n args,\n {\n env: { ...process.env, MEMORY_PATH: memoryPath, UV_CACHE_DIR: process.env.UV_CACHE_DIR ?? '/tmp/uv-cache' },\n stdio: ['pipe', 'pipe', 'inherit'],\n },\n )\n const pending = new Map<number, { resolve: (v: unknown) => void; reject: (e: Error) => void; timer: NodeJS.Timeout }>()\n let nextId = 1\n let closed = false\n\n const failAll = (err: Error) => {\n for (const [, p] of pending) {\n clearTimeout(p.timer)\n p.reject(err)\n }\n pending.clear()\n }\n\n child.on('error', (err) => {\n closed = true\n failAll(new Error(`memory-vault-server spawn failed: ${err.message}`))\n reject(err)\n })\n child.on('exit', (code) => {\n if (closed) return\n closed = true\n failAll(new Error(`memory-vault-server exited unexpectedly (code ${code})`))\n reject(new Error(`memory-vault-server exited before initialize (code ${code})`))\n })\n\n const rl = readline.createInterface({ input: child.stdout!, crlfDelay: Infinity })\n rl.on('line', (line) => {\n let msg: any\n try {\n msg = JSON.parse(line)\n } catch {\n return\n }\n if (typeof msg?.id === 'number') {\n const p = pending.get(msg.id)\n if (!p) return\n pending.delete(msg.id)\n clearTimeout(p.timer)\n if (msg.error) p.reject(new Error(`MCP error: ${msg.error.message ?? JSON.stringify(msg.error)}`))\n else p.resolve(msg.result)\n }\n })\n\n const send = (method: string, params: unknown, timeoutMs: number = MCP_CALL_TIMEOUT_MS): Promise<unknown> =>\n new Promise((res, rej) => {\n if (closed || !child.stdin?.writable) {\n rej(new Error('memory-vault-server is not running'))\n return\n }\n const id = nextId++\n const timer = setTimeout(() => {\n pending.delete(id)\n rej(new Error(`MCP call ${method} timed out after ${timeoutMs}ms`))\n }, timeoutMs)\n pending.set(id, { resolve: res, reject: rej, timer })\n child.stdin!.write(JSON.stringify({ jsonrpc: '2.0', id, method, params }) + '\\n')\n })\n\n const notify = (method: string, params: unknown) => {\n if (!closed && child.stdin?.writable) {\n child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method, params }) + '\\n')\n }\n }\n\n // initialize handshake (notifications are fire-and-forget: no id, no reply)\n void send('initialize', {\n protocolVersion: '2025-06-18',\n capabilities: {},\n clientInfo: { name: 'memory-auto', version: '0.1.0' },\n })\n .then(() => {\n notify('notifications/initialized', {})\n })\n .then(() => {\n if (closed) throw new Error('memory-vault-server closed during handshake')\n resolve({\n callTool: (name, args, timeoutMs = MCP_CALL_TIMEOUT_MS) =>\n send('tools/call', { name, arguments: args }, timeoutMs).then((result: any) => {\n if (result?.isError) {\n const text = Array.isArray(result.content) ? result.content.map((c: any) => c?.text ?? '').join('') : JSON.stringify(result)\n throw new Error(`tool ${name} failed: ${text}`)\n }\n return result\n }),\n close: async () => {\n if (closed) return\n closed = true\n for (const [, p] of pending) clearTimeout(p.timer)\n pending.clear()\n if (child.exitCode !== null) return\n child.kill()\n await new Promise((r) => child.once('exit', r))\n },\n })\n })\n .catch((err) => {\n closed = true\n child.kill()\n reject(err)\n })\n })\n}\n\n/**\n * Write validated OKF entries through the vault server's `store_*` tools,\n * which upsert both the Markdown file and the SQLite FTS5 index.\n */\nexport async function writeEntries(client: McpClient, project: string, entries: ValidEntry[]): Promise<{ upserted: number; failed: number }> {\n let upserted = 0\n let failed = 0\n for (const e of entries) {\n try {\n await client.callTool(`store_${e.entry_type}`, {\n project,\n content: e.content,\n ...(e.description ? { description: e.description } : {}),\n tags: e.tags,\n // Only store_fact accepts and persists confidence. Sending it for every\n // type silently discarded it, so send it where it actually lands.\n ...(e.entry_type === 'fact' ? { confidence: e.confidence } : {}),\n ...(e.openspec_change_id ? { openspec_change_id: e.openspec_change_id } : {}),\n })\n upserted += 1\n } catch (err) {\n failed += 1\n console.warn(`[memory-auto] store_${e.entry_type} failed:`, err instanceof Error ? err.message : err)\n }\n }\n return { upserted, failed }\n}\n\n/**\n * Full post-session digest: transcript -> ctx.llm extraction (with retries) ->\n * OKF writes via the vault MCP server. Never throws; logs the outcome.\n */\nexport async function digestSessionDSM(\n ctx: Context,\n config: DigestConfig,\n sessionId: string,\n directory: string,\n project: string,\n events: any[],\n signal?: AbortSignal,\n): Promise<void> {\n const header = `## context\\nproject: ${project}\\ndirectory: ${directory}\\n`\n const transcript = (header + transcriptOfDSM(events)).trim()\n if (!transcript) {\n log(`digest skip ${sessionId}: empty`)\n return\n }\n if (transcript.length < (config.minTranscriptChars ?? MIN_DIGEST_TRANSCRIPT_CHARS)) {\n log(`digest skip ${sessionId}: too short ${transcript.length}`)\n return\n }\n\n const chunks = chunkTranscript(transcript)\n const entries: ValidEntry[] = []\n for (const chunk of chunks) {\n let attempt = 0\n for (;;) {\n try {\n const got = await extractEntriesWithLlm(ctx, config, project, chunk, undefined, signal)\n entries.push(...got)\n break\n } catch (err) {\n attempt += 1\n if (attempt >= LLM_RETRIES || signal?.aborted) {\n console.warn(`[memory-auto] digest extraction failed after ${attempt} attempt(s):`, err instanceof Error ? err.message : err)\n break\n }\n const delay = LLM_RETRY_DELAYS_MS[attempt - 1] ?? 5_000\n log(`digest extraction retry ${attempt}/${LLM_RETRIES} in ${delay}ms`)\n await new Promise((r) => setTimeout(r, delay))\n }\n }\n if (signal?.aborted) break\n }\n\n if (entries.length === 0) {\n log(`digest ${sessionId}: no entries extracted`)\n return\n }\n\n let client: McpClient\n try {\n client = await connectMcp(config.memoryPath, config.serverDir)\n } catch (err) {\n console.warn(`[memory-auto] digest ${sessionId}: cannot reach vault server:`, err instanceof Error ? err.message : err)\n return\n }\n try {\n const { upserted, failed } = await writeEntries(client, project, entries)\n log(`digest ${sessionId}: ${upserted} upserted, ${failed} failed (${entries.length} extracted)`)\n } finally {\n await client.close().catch(() => {})\n }\n}\n","/**\n * Bundled skill shipped in this package: `checkpoint-auto`, the contract of the\n * automatic capture this plugin performs (triggers, the `[memory-checkpoint]`\n * marker, the digest, and the knobs). The capture *procedure* it defers to\n * lives in `@luisarg/memory-mcp`'s `checkpoint` skill, which is installed\n * alongside this plugin.\n *\n * A provider rather than `ctx.skills.register()` on purpose. A registration\n * lands at the runtime rank, which outranks a user's own skill directories,\n * while BUNDLED_SKILL_RANK is the weakest rank in the local discovery table:\n * shipping at the weakest rank means a user who drops their own skill of the\n * same name into `~/.agents/skills` keeps winning. This is a default, not a\n * takeover.\n *\n * Each SKILL.md stays the single source of its own name, description and\n * usage guidance — the frontmatter is parsed here with the same `yaml`\n * dependency the harness's own filesystem provider uses, so the exact file that\n * ships in this package also works copied into a user skill root. Kept as a\n * copy of the sibling provider in `@luisarg/memory-mcp`: the two packages\n * publish independently, and a shared third package would add a release\n * artifact to maintain for this much stable plumbing.\n */\nimport { readFile } from 'node:fs/promises'\nimport { fileURLToPath } from 'node:url'\nimport { parse as parseYaml } from 'yaml'\nimport {\n BUNDLED_SKILL_RANK,\n type SkillCandidate,\n type SkillDefinition,\n type SkillProvider,\n type SkillResourceBase,\n} from '@deepseek-ai/dsh-skill'\n\n/** Provider name registered on `ctx.skills`. */\nexport const SKILLS_PROVIDER = 'memory-auto-skills'\n\n/** Shipped skill directories, relative to the package root. */\nconst SKILL_NAMES = ['checkpoint-auto'] as const\n\nconst SKILLS_ROOT = new URL('../skills/', import.meta.url)\nconst INVOCATION = { modelInvocable: true, userInvocable: true } as const\n\ninterface Frontmatter {\n readonly name: string\n readonly description: string\n readonly whenToUse?: string\n}\n\nfunction skillUrl(name: string): URL {\n return new URL(`${name}/SKILL.md`, SKILLS_ROOT)\n}\n\nfunction resourceBase(name: string): SkillResourceBase {\n return { kind: 'directory', path: fileURLToPath(new URL(`${name}/`, SKILLS_ROOT)) }\n}\n\n/** Split YAML frontmatter from the body, mirroring the harness filesystem provider. */\nfunction splitFrontmatter(raw: string): { data: Record<string, unknown>; body: string } {\n const match = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?/.exec(raw)\n if (match === null) throw new Error('SKILL.md has no YAML frontmatter')\n const parsed: unknown = parseYaml(match[1])\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n throw new TypeError('SKILL.md frontmatter must be a YAML mapping')\n }\n return { data: parsed as Record<string, unknown>, body: raw.slice(match[0].length).trim() }\n}\n\nfunction textField(data: Record<string, unknown>, key: string): string | undefined {\n const value = data[key]\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\n/** Read one shipped skill, rejecting a file whose frontmatter disagrees with its directory. */\nasync function loadSkill(name: string): Promise<{ frontmatter: Frontmatter; body: string }> {\n const { data, body } = splitFrontmatter(await readFile(skillUrl(name), 'utf8'))\n const declared = textField(data, 'name')\n if (declared !== name) {\n throw new Error(`skills/${name}/SKILL.md declares name \"${declared ?? '(none)'}\"`)\n }\n const description = textField(data, 'description')\n if (description === undefined) throw new Error(`skills/${name}/SKILL.md has no description`)\n const whenToUse = textField(data, 'whenToUse')\n return {\n frontmatter: { name, description, ...whenToUse === undefined ? {} : { whenToUse } },\n body,\n }\n}\n\n/** Skills shipped as packaged Markdown assets. */\nexport const skillsProvider: SkillProvider = {\n name: SKILLS_PROVIDER,\n\n async list(): Promise<readonly SkillCandidate[]> {\n return await Promise.all(SKILL_NAMES.map(async (name) => {\n const { frontmatter } = await loadSkill(name)\n return {\n ...frontmatter,\n path: fileURLToPath(skillUrl(name)),\n invocation: INVOCATION,\n source: 'bundled',\n provider: SKILLS_PROVIDER,\n resourceBase: resourceBase(name),\n rank: BUNDLED_SKILL_RANK,\n locator: skillUrl(name),\n }\n }))\n },\n\n async get(candidate): Promise<SkillDefinition | undefined> {\n // A body that is no longer loadable resolves to `undefined`: the registry\n // passes that straight back to its caller, while throwing here would\n // surface a raw ENOENT as a tool error instead of \"no longer available\".\n const loaded = await loadSkill(candidate.name).catch(() => undefined)\n if (loaded === undefined) return undefined\n const { frontmatter, body } = loaded\n return {\n ...frontmatter,\n path: fileURLToPath(skillUrl(candidate.name)),\n invocation: INVOCATION,\n source: 'bundled',\n provider: SKILLS_PROVIDER,\n resourceBase: resourceBase(candidate.name),\n content: body,\n }\n },\n}\n","/**\n * Harness wiring for `memory-auto`. Registers exactly these hooks:\n *\n * - `session/created` resolve the project name for the session\n * - `session/disposed` digest the transcript\n * - `agent/status` (idle) auto-capture gate\n * - `session/event` activity tracking; `tool/call` with a\n * `git commit` command and `compaction/start`\n * queue checkpoints\n * - `agent/pre-step` deliver the queued checkpoint to the agent\n * - `ctx.effect` dispose batch-digest sessions still pending\n *\n * The agent writes the entries; this plugin only prompts it.\n */\nimport { cpSync, existsSync, mkdirSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { dirname, isAbsolute, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport type { Context } from '@deepseek-ai/cordis'\nimport Schema from '@deepseek-ai/schemastery'\nimport {\n createSessionState,\n resolveProjectName,\n idleCheckpoint,\n compactingCheckpoint,\n isGitCommit,\n buildCommitCheckpointPrompt,\n type SessionState,\n} from './pure.js'\nimport { digestSessionDSM, type DigestConfig } from './digest.js'\nimport { skillsProvider } from './skills.js'\n\nexport const name = 'memory-auto'\n\nexport interface Config {\n memoryPath: string\n serverDir: string\n provider: string\n model: string\n maxTokens: number\n minTranscriptChars: number\n enabled: boolean\n}\n\nexport const Config: Schema<Config> = Schema.object({\n memoryPath: Schema.string().default(process.env.DSH_MEMORY_PATH ?? ''),\n serverDir: Schema.string().default(process.env.DSH_MEMORY_SERVER_DIR ?? ''),\n provider: Schema.string().default('deepseek-official'),\n model: Schema.string().default('deepseek-v4-flash'),\n maxTokens: Schema.number().default(2048),\n minTranscriptChars: Schema.number().default(200),\n enabled: Schema.boolean().default(true),\n})\n\n/** Requires the harness LLM service: extraction runs in-process via ctx.llm. */\nexport const inject = ['llm']\n\n/**\n * Resolve the harness home the same way the harness does (`$DSH_HOME`, or\n * `~/.dsh`). Paths must never depend on the launch cwd: DSH does not chdir.\n */\nfunction dshHome(): string {\n const env = process.env.DSH_HOME?.trim()\n return env && env.length > 0 ? env : join(homedir(), '.dsh')\n}\n\n/** Absolute paths stay; empty/relative values resolve under the harness home. */\nfunction resolveUnderHome(value: string, fallbackSegment: string): string {\n const v = value.trim()\n if (v.length === 0) return join(dshHome(), fallbackSegment)\n return isAbsolute(v) ? v : join(dshHome(), v)\n}\n\nconst packageRoot = dirname(dirname(fileURLToPath(import.meta.url)))\n\n/** Copy the bundled dir into `target` when `key` is missing there. */\nfunction ensure(target: string, bundled: string, key: string): boolean {\n if (existsSync(join(target, key))) return false\n if (!existsSync(bundled)) return false\n mkdirSync(target, { recursive: true })\n cpSync(bundled, target, { recursive: true })\n return true\n}\n\n/** Copy one bundled file into `target` when missing (upgrades add files 0.1.1 → 0.1.2). */\nfunction ensureFile(target: string, bundled: string, file: string): boolean {\n const dest = join(target, file)\n if (existsSync(dest)) return false\n const src = join(bundled, file)\n if (!existsSync(src)) return false\n mkdirSync(target, { recursive: true })\n cpSync(src, dest)\n return true\n}\n\n// DSH session shape minimal\ntype DSHEvt = any\ntype DSHSession = { id: string; events: DSHEvt[]; cwd?: string }\n\nexport function apply(ctx: Context, config: Config) {\n // Registered before the `enabled` gate on purpose: this skill documents the\n // automatic capture *and* its knobs, which is how a session finds out that\n // capture is off and how to turn it back on. Injected rather than declared in\n // `inject` so a deployment without a skill catalog still gets capture.\n ctx.inject(['skills'], (ctx) => {\n ctx.skills.registerProvider(() => skillsProvider)\n })\n\n if (!config.enabled) {\n console.log('[memory-auto] disabled via config')\n return\n }\n\n const memoryPath = resolveUnderHome(config.memoryPath, 'memory-vault')\n const serverDir = resolveUnderHome(config.serverDir, 'memory-vault-server')\n\n // Self-contained install: first boot copies the bundled server and vault\n // starter under the harness home when they are missing.\n if (ensure(serverDir, join(packageRoot, 'server'), 'server.py')) {\n console.log(`[memory-auto] installed memory-vault-server -> ${serverDir}`)\n }\n if (ensure(memoryPath, join(packageRoot, 'vault'), 'type-registry.yaml')) {\n console.log(`[memory-auto] installed vault starter -> ${memoryPath}`)\n }\n // launcher.mjs runs the server via uv or the pip-venv fallback; upgrades of\n // existing installs (server.py already present) still need the new files.\n const bundledServer = join(packageRoot, 'server')\n for (const file of ['launcher.mjs', 'requirements.txt']) {\n if (ensureFile(serverDir, bundledServer, file)) {\n console.log(`[memory-auto] installed ${file} -> ${serverDir}`)\n }\n }\n\n const digestConfig: DigestConfig = {\n memoryPath,\n serverDir,\n provider: config.provider,\n model: config.model,\n maxTokens: config.maxTokens,\n minTranscriptChars: config.minTranscriptChars,\n }\n\n if (!existsSync(join(serverDir, 'server.py'))) {\n console.warn(\n `[memory-auto] vault server not found at ${serverDir} and not bundled — the digest cannot write. ` +\n 'Set DSH_MEMORY_SERVER_DIR (or run `node scripts/bundle-assets.mjs` in a checkout).',\n )\n }\n if (!existsSync(join(memoryPath, 'type-registry.yaml'))) {\n console.warn(`[memory-auto] vault starter not found at ${memoryPath} — searches will fail until it exists.`)\n }\n\n const states = new Map<string, SessionState>()\n const activities = new Map<string, string[]>()\n const queued = new Map<string, string>()\n const sessionDirs = new Map<string, string>()\n const projectCache = new Map<string, string>()\n\n const ACTIVITY_MAX_LINES = 20\n const ACTIVITY_MAX_CHARS = 80\n\n const track = (sessionId: string, line: string) => {\n const st = states.get(sessionId)\n if (!st) return\n st.hasActivity = true\n const list = activities.get(sessionId) ?? []\n if (!list.includes(line)) {\n list.push(line)\n if (list.length > ACTIVITY_MAX_LINES) list.shift()\n activities.set(sessionId, list)\n }\n }\n\n const summary = (sid: string) => (activities.get(sid) ?? []).join('\\n')\n\n const projectFor = async (dir: string): Promise<string> => {\n const cached = projectCache.get(dir)\n if (cached) return cached\n const p = await resolveProjectName(dir || process.cwd())\n projectCache.set(dir, p)\n return p\n }\n\n // session/created -> init state\n ctx.on('session/created', async (session: DSHSession) => {\n const sid = (session as any)?.id ?? (session as any)?.sessionId\n const dir = (session as any)?.cwd ?? (session as any)?.directory ?? ''\n if (!sid) return\n const proj = await projectFor(dir)\n if (!states.has(sid)) {\n states.set(sid, createSessionState(proj))\n activities.set(sid, [])\n }\n sessionDirs.set(sid, dir)\n console.log(`[memory-auto] session created ${sid} project=${proj}`)\n })\n\n // session/disposed -> digest\n ctx.on('session/disposed', async (session: DSHSession) => {\n const sid = (session as any)?.id ?? (session as any)?.sessionId\n if (!sid) return\n const st = states.get(sid)\n if (!st) return\n if (!st.hasActivity) {\n console.log(`[memory-auto] digest skip ${sid}: no activity`)\n return\n }\n const dir = sessionDirs.get(sid) ?? ''\n const proj = await projectFor(dir)\n const evts: DSHEvt[] = (session as any)?.events ?? []\n await digestSessionDSM(ctx, digestConfig, sid, dir, proj, evts)\n })\n\n // agent/status idle -> in-session capture gate\n ctx.on('agent/status', async (payload: any) => {\n const agent = payload?.agent\n const status = payload?.status ?? payload?.agentStatus\n if (status !== 'idle') return\n const sid: string | undefined = agent?.sessionId ?? payload?.sessionId ?? agent?.id\n if (!sid) return\n const st = states.get(sid)\n if (!st) return\n const text = idleCheckpoint(st, summary(sid))\n if (text) {\n console.log(`[memory-auto] idle checkpoint digest for ${sid}`)\n const dir = sessionDirs.get(sid) ?? ''\n const proj = await projectFor(dir)\n const fakeEvents = [{ type: 'user/message', data: { text: summary(sid) } }]\n await digestSessionDSM(ctx, digestConfig, sid, dir, proj, fakeEvents)\n }\n })\n\n // session/event -> git commit detect + compaction start\n ctx.on('session/event', async (session: DSHSession, event: DSHEvt) => {\n const sid = (session as any)?.id ?? (session as any)?.sessionId ?? (event as any)?.sessionId\n if (!sid) return\n const t = event?.type ?? ''\n const d = event?.data ?? {}\n\n // compaction/start -> checkpoint injection (delivered on the next pre-step)\n if (t === 'compaction/start') {\n const st = states.get(sid)\n if (!st) return\n const txt = compactingCheckpoint(st, summary(sid))\n if (txt) {\n console.log(`[memory-auto] compaction checkpoint queued for ${sid}`)\n queued.set(sid, txt)\n }\n return\n }\n\n // tool/call -> git commit detection + activity track\n if (t === 'tool/call' || t === 'tool_call') {\n const cmd = d?.args?.command ?? d?.command ?? ''\n if (typeof cmd === 'string' && isGitCommit(cmd)) {\n const st = states.get(sid)\n if (st) {\n st.hasActivity = true\n queued.set(sid, buildCommitCheckpointPrompt(st))\n console.log(`[memory-auto] git commit queued for ${sid}`)\n }\n return\n }\n if (typeof cmd === 'string') {\n track(sid, `bash: ${cmd.trim().slice(0, ACTIVITY_MAX_CHARS)}`)\n }\n return\n }\n if (t === 'tool/result') {\n // ignore\n return\n }\n if (t === 'user/message' || t === 'assistant/message') {\n // track activity\n track(sid, `${t}: ${(d?.text ?? '').slice(0, ACTIVITY_MAX_CHARS)}`)\n }\n })\n\n // agent/pre-step Waterfall -> deliver queued checkpoint\n ctx.on('agent/pre-step', async (payload: any, next: any) => {\n const sid: string | undefined = payload?.agent?.sessionId ?? payload?.sessionId\n if (sid) {\n const q = queued.get(sid)\n if (q) {\n queued.delete(sid)\n // Best effort: append the checkpoint as user context\n if (Array.isArray(payload?.context)) payload.context.push(q)\n else if (Array.isArray(payload?.messages)) payload.messages.push({ role: 'user', content: q })\n else console.log(`[memory-auto] deliver queued checkpoint for ${sid}`)\n }\n }\n return next()\n })\n\n // dispose -> batch digest remaining sessions\n ctx.effect(() => {\n return () => {\n console.log(`[memory-auto] dispose batch ${sessionDirs.size} sessions`)\n // fire-and-forget digest for each remaining session\n for (const [sid, dir] of sessionDirs) {\n const st = states.get(sid)\n if (!st?.hasActivity) continue\n projectFor(dir).then((proj) => {\n const fakeEvents = [{ type: 'user/message', data: { text: summary(sid) } }]\n void digestSessionDSM(ctx, digestConfig, sid, dir, proj, fakeEvents)\n })\n }\n }\n })\n\n console.log(`[memory-auto] active memoryPath=${memoryPath} serverDir=${serverDir} llm=${config.provider}/${config.model}`)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAiBA,MAAM,oBAAoB;;;;;;AAO1B,MAAa,oBAAoB;CAAC;CAAY;CAAQ;CAAY;AAAY;;;;;;;AAS9E,MAAM,mBAAoD;CACxD,UAAU;CACV,MAAM;CACN,UAAU;CACV,YAAY;AACd;;AAGA,MAAM,qBACJ;;;;;AAMF,MAAM,wBAAwB;CAC5B;CACA;CACA;AACF;;AAGA,SAAS,mBAA6B;CACpC,OAAO,kBAAkB,KAAK,MAAM,OAAO,EAAE,MAAM,iBAAiB,GAAG,EAAE;AAC3E;;;;;;;;;;AA6BA,eAAsB,mBAAmB,KAA8B;CACrE,IAAI,WAAW,KAAK,KAAK,UAAU,CAAC,GAClC,OAAO,SAAS,GAAG;CAGrB,MAAM,UAAU,KAAK,KAAK,cAAc;CACxC,IAAI,WAAW,OAAO,GACpB,IAAI;EACF,MAAM,MAAM,KAAK,MAAM,MAAM,SAAS,SAAS,OAAO,CAAC;EACvD,IAAI,OAAO,IAAI,SAAS,YAAY,IAAI,KAAK,KAAK,GAChD,OAAO,IAAI,KAAK,KAAK;CAEzB,QAAQ,CAER;CAGF,MAAM,gBAAgB,KAAK,KAAK,gBAAgB;CAChD,IAAI,WAAW,aAAa,GAC1B,IAAI;EAEF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package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@luisarg/memory-auto",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "type": "module",
5
5
  "description": "Auto-captura memoria DSH (idle, commit, compaction, dispose)",
6
6
  "repository": {
@@ -19,6 +19,7 @@
19
19
  "dist/",
20
20
  "cordis.patch.yml",
21
21
  "server/",
22
+ "skills/",
22
23
  "vault/"
23
24
  ],
24
25
  "dsh": {
@@ -30,20 +31,23 @@
30
31
  "build": "tsdown",
31
32
  "dev": "tsdown --watch",
32
33
  "test": "vitest run --passWithNoTests",
33
- "prepare": "tsdown && node ../../scripts/bundle-assets.mjs",
34
+ "prepare": "tsdown",
34
35
  "typecheck": "tsc --noEmit"
35
36
  },
36
37
  "dependencies": {
37
- "@deepseek-ai/cordis": "4.0.1",
38
- "@deepseek-ai/schemastery": "3.18.1"
38
+ "@deepseek-ai/cordis": "4.0.2",
39
+ "@deepseek-ai/schemastery": "3.18.2",
40
+ "yaml": "^2.4.2"
39
41
  },
40
42
  "peerDependencies": {
41
- "@deepseek-ai/dsh-llm": ">=0.0.1-rc.1 <0.1.0 || >=0.1.0-rc.1 <0.2.0-0"
43
+ "@deepseek-ai/dsh-llm": ">=0.0.1-rc.1 <0.1.0 || >=0.1.0-rc.1 <0.2.0-0",
44
+ "@deepseek-ai/dsh-skill": ">=0.0.1-rc.1 <0.1.0 || >=0.1.0-rc.1 <0.2.0-0"
42
45
  },
43
46
  "devDependencies": {
44
- "typescript": "^5.9.2",
45
- "tsdown": "^0.15.6",
46
- "vitest": "^3.2.7",
47
- "@deepseek-ai/dsh-llm": "0.1.0-rc.7"
47
+ "typescript": "^7.0.2",
48
+ "tsdown": "^0.23.0",
49
+ "vitest": "^5.0.0",
50
+ "@deepseek-ai/dsh-llm": "0.1.5-rc.2",
51
+ "@deepseek-ai/dsh-skill": "0.1.5-rc.2"
48
52
  }
49
53
  }
package/server/server.py CHANGED
@@ -1,8 +1,13 @@
1
1
  """MCP server exposing memory store tools via the Model Context Protocol.
2
2
 
3
- Eight tools (per openspec/specs/memory-mcp-server/spec.md):
3
+ Ten tools (per openspec/specs/memory-mcp-server/spec.md):
4
4
  search_memory, store_decision, store_fact, store_learning,
5
- store_convention, store_profile, export_memories, get_profile, ping.
5
+ store_convention, store_profile, store_source, export_memories,
6
+ get_profile, ping.
7
+
8
+ Note: `type-registry.yaml` also declares `context` and `idea`. They are valid
9
+ `entries.entry_type` values and legal filters here, but no `store_*` tool
10
+ creates them — nothing writes them today.
6
11
 
7
12
  All reads are explicit (no background polling). Server validates storage
8
13
  accessibility at startup.
@@ -190,7 +195,13 @@ def _tool_definitions() -> list[Tool]:
190
195
  return [
191
196
  Tool(
192
197
  name="search_memory",
193
- description="Search memory entries across projects. Omit project to search all projects.",
198
+ description=(
199
+ "Search memory entries across projects. Omit project to search all projects. "
200
+ "The query is tokenized and OR-matched (any term hits), ranked by relevance. "
201
+ "Tags are OR-matched too: passing ['ci','release'] returns entries with either tag. "
202
+ "Filters narrow the result set; at most 50 entries are returned. "
203
+ "Source entries are excluded unless entry_type='source' with no other filter."
204
+ ),
194
205
  inputSchema={
195
206
  "type": "object",
196
207
  "properties": {
@@ -203,78 +214,143 @@ def _tool_definitions() -> list[Tool]:
203
214
  ),
204
215
  Tool(
205
216
  name="store_decision",
206
- description="Store a decision entry",
217
+ description=(
218
+ "Store a decision: an architectural or design choice that was made and why. "
219
+ "Deduplicated by content hash, so re-storing the same text updates instead of "
220
+ "duplicating."
221
+ ),
207
222
  inputSchema={
208
223
  "type": "object",
209
224
  "required": ["project", "content"],
210
225
  "properties": {
211
226
  "project": {"type": "string"},
212
- "content": {"type": "string"},
213
- "description": {"type": "string"},
214
- "tags": {"type": "array", "items": {"type": "string"}},
227
+ "content": {
228
+ "type": "string",
229
+ "description": "One paragraph, no headings or bullet lists.",
230
+ },
231
+ "description": {
232
+ "type": "string",
233
+ "description": "One-sentence queryable summary; derived from content if omitted.",
234
+ },
235
+ "tags": {
236
+ "type": "array",
237
+ "items": {"type": "string"},
238
+ "description": "Lowercase-kebab tags, e.g. architecture/python/testing.",
239
+ },
215
240
  "openspec_change_id": {"type": "string"},
216
241
  },
217
242
  },
218
243
  ),
219
244
  Tool(
220
245
  name="store_fact",
221
- description="Store a fact entry",
246
+ description=(
247
+ "Store a fact: a stable, verifiable statement about the project (version, "
248
+ "constraint, path, endpoint). Deduplicated by content hash. Prefer one atomic "
249
+ "fact per call over a bundle of several."
250
+ ),
222
251
  inputSchema={
223
252
  "type": "object",
224
253
  "required": ["project", "content"],
225
254
  "properties": {
226
255
  "project": {"type": "string"},
227
- "content": {"type": "string"},
228
- "description": {"type": "string"},
229
- "tags": {"type": "array", "items": {"type": "string"}},
256
+ "content": {
257
+ "type": "string",
258
+ "description": "One paragraph, no headings or bullet lists.",
259
+ },
260
+ "description": {
261
+ "type": "string",
262
+ "description": "One-sentence queryable summary; derived from content if omitted.",
263
+ },
264
+ "tags": {
265
+ "type": "array",
266
+ "items": {"type": "string"},
267
+ "description": "Lowercase-kebab tags, e.g. architecture/python/testing.",
268
+ },
230
269
  "confidence": {"type": "number", "minimum": 0.0, "maximum": 1.0},
231
270
  },
232
271
  },
233
272
  ),
234
273
  Tool(
235
274
  name="store_learning",
236
- description="Store a learning entry",
275
+ description=(
276
+ "Store a learning: a non-obvious lesson, debugging insight, or solution found — "
277
+ "something that cost effort and would otherwise be rediscovered. Deduplicated by "
278
+ "content hash."
279
+ ),
237
280
  inputSchema={
238
281
  "type": "object",
239
282
  "required": ["project", "content"],
240
283
  "properties": {
241
284
  "project": {"type": "string"},
242
- "content": {"type": "string"},
243
- "description": {"type": "string"},
244
- "tags": {"type": "array", "items": {"type": "string"}},
285
+ "content": {
286
+ "type": "string",
287
+ "description": "One paragraph, no headings or bullet lists.",
288
+ },
289
+ "description": {
290
+ "type": "string",
291
+ "description": "One-sentence queryable summary; derived from content if omitted.",
292
+ },
293
+ "tags": {
294
+ "type": "array",
295
+ "items": {"type": "string"},
296
+ "description": "Lowercase-kebab tags, e.g. architecture/python/testing.",
297
+ },
245
298
  },
246
299
  },
247
300
  ),
248
301
  Tool(
249
302
  name="store_convention",
250
- description="Store a convention entry",
303
+ description=(
304
+ "Store a convention: an agreed style rule, naming pattern, or coding standard. "
305
+ "Deduplicated by content hash."
306
+ ),
251
307
  inputSchema={
252
308
  "type": "object",
253
309
  "required": ["project", "content"],
254
310
  "properties": {
255
311
  "project": {"type": "string"},
256
- "content": {"type": "string"},
257
- "description": {"type": "string"},
258
- "tags": {"type": "array", "items": {"type": "string"}},
312
+ "content": {
313
+ "type": "string",
314
+ "description": "One paragraph, no headings or bullet lists.",
315
+ },
316
+ "description": {
317
+ "type": "string",
318
+ "description": "One-sentence queryable summary; derived from content if omitted.",
319
+ },
320
+ "tags": {
321
+ "type": "array",
322
+ "items": {"type": "string"},
323
+ "description": "Lowercase-kebab tags, e.g. architecture/python/testing.",
324
+ },
259
325
  },
260
326
  },
261
327
  ),
262
328
  Tool(
263
329
  name="store_profile",
264
- description="Store or update a user profile entry for a project",
330
+ description=(
331
+ "Replace the tech profile for a project. One profile per project: the content "
332
+ "overwrites the previous one, it does not append. Pass the complete profile text."
333
+ ),
265
334
  inputSchema={
266
335
  "type": "object",
267
336
  "required": ["project", "content"],
268
337
  "properties": {
269
338
  "project": {"type": "string"},
270
- "content": {"type": "string"},
339
+ "content": {
340
+ "type": "string",
341
+ "description": "The full profile — replaces the stored one.",
342
+ },
271
343
  "tags": {"type": "array", "items": {"type": "string"}},
272
344
  },
273
345
  },
274
346
  ),
275
347
  Tool(
276
348
  name="store_source",
277
- description="Store a source reference (article, transcript, PDF, video, link)",
349
+ description=(
350
+ "Store an external source reference (article, transcript, PDF, video, link) under "
351
+ "raw/. Immutable: a later store with the same URL returns the existing entry, and "
352
+ "reusing a title slug with different content is rejected."
353
+ ),
278
354
  inputSchema={
279
355
  "type": "object",
280
356
  "required": ["url", "title", "description", "source_kind"],
@@ -294,7 +370,10 @@ def _tool_definitions() -> list[Tool]:
294
370
  ),
295
371
  Tool(
296
372
  name="export_memories",
297
- description="Export all memory entries for a project (no limit)",
373
+ description=(
374
+ "Export every stored entry for one project, newest first, with no result limit. "
375
+ "Use for a full project dump, not for lookups — search_memory is cheaper."
376
+ ),
298
377
  inputSchema={
299
378
  "type": "object",
300
379
  "required": ["project"],
@@ -306,7 +385,11 @@ def _tool_definitions() -> list[Tool]:
306
385
  ),
307
386
  Tool(
308
387
  name="get_profile",
309
- description="Retrieve the global tech profile for a project",
388
+ description=(
389
+ "Retrieve the stored tech profile for a project. Returns profile entries by "
390
+ "default; pass entry_type to query another type instead (then it is a "
391
+ "most-recent-first lookup capped at 10)."
392
+ ),
310
393
  inputSchema={
311
394
  "type": "object",
312
395
  "required": ["project"],
package/server/store.py CHANGED
@@ -770,12 +770,15 @@ class MemoryStore:
770
770
  project: str,
771
771
  entry_type: str | None = None,
772
772
  ) -> list[dict]:
773
- """Retrieve profile entries for a project."""
774
- sql = "SELECT * FROM entries WHERE project = ?"
775
- params: list = [project]
776
- if entry_type:
777
- sql += " AND entry_type = ?"
778
- params.append(entry_type)
773
+ """Retrieve the profile for a project.
774
+
775
+ Defaults to ``profile`` entries: the tool is named get_profile, so an
776
+ unfiltered call returning the 10 most recent rows of any type was a
777
+ silent wrong answer. Pass ``entry_type`` to use it as a recency query.
778
+ """
779
+ entry_type = entry_type or "profile"
780
+ sql = "SELECT * FROM entries WHERE project = ? AND entry_type = ?"
781
+ params: list = [project, entry_type]
779
782
  sql += " ORDER BY updated_at DESC LIMIT 10"
780
783
  rows = self.db.execute(sql, params).fetchall()
781
784
  return [dict(r) for r in rows]
@@ -0,0 +1,78 @@
1
+ #!/usr/bin/env python3
2
+ """Self-check: get_profile answers with the profile, not with recent noise.
3
+
4
+ Regression guard for the bug where an unfiltered get_profile returned the 10
5
+ most recently updated rows of ANY type, so a caller asking for the profile of a
6
+ busy project got unrelated decisions and facts.
7
+
8
+ Run: python3 memory-vault-server/test_get_profile.py
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import os
15
+ import shutil
16
+ import sys
17
+ import tempfile
18
+ from pathlib import Path
19
+
20
+ SERVER_DIR = Path(__file__).resolve().parent
21
+ REPO_VAULT = SERVER_DIR.parent / "memory-vault"
22
+ sys.path.insert(0, str(SERVER_DIR))
23
+
24
+
25
+ def main() -> int:
26
+ with tempfile.TemporaryDirectory() as tmp:
27
+ # store.py resolves the type registry from MEMORY_PATH at import time,
28
+ # so seed the throwaway vault before importing it.
29
+ vault = Path(tmp)
30
+ (vault / "projects").mkdir()
31
+ shutil.copy(REPO_VAULT / "type-registry.yaml", vault / "type-registry.yaml")
32
+ os.environ["MEMORY_PATH"] = str(vault)
33
+ import store as store_mod
34
+
35
+ s = store_mod.MemoryStore(storage_path=vault)
36
+ s.initialize()
37
+
38
+ s.upsert_profile(project="proj", content="PROFILE: python + sqlite")
39
+ # Written afterwards, so these outrank the profile in updated_at:
40
+ # the old code returned them and called it a profile.
41
+ s.upsert_entry("decision", "proj", "DECISION: use sqlite for storage")
42
+ s.upsert_entry("fact", "proj", "FACT: python 3.11 is required")
43
+
44
+ got = s.get_profile(project="proj")
45
+ assert len(got) == 1, f"expected only the profile row, got {len(got)}: {got}"
46
+ assert got[0]["entry_type"] == "profile", got[0]["entry_type"]
47
+ assert "PROFILE" in got[0]["content"], got[0]["content"]
48
+
49
+ # entry_type=None must behave exactly like the default.
50
+ assert s.get_profile(project="proj", entry_type=None) == got
51
+
52
+ # Explicit entry_type still works (and is now a plain recency lookup).
53
+ facts = s.get_profile(project="proj", entry_type="fact")
54
+ assert len(facts) == 1 and facts[0]["entry_type"] == "fact", facts
55
+
56
+ # A project with no profile yields nothing rather than unrelated rows.
57
+ s.upsert_entry("fact", "other", "FACT: unrelated project")
58
+ assert s.get_profile(project="other") == [], "profile leaked across projects"
59
+
60
+ # The MCP tool handler agrees (binds the tool default to the store fix).
61
+ # Needs the pinned `mcp` version from requirements.txt; skip when the
62
+ # ambient one is older instead of failing the whole check.
63
+ try:
64
+ import server
65
+
66
+ found = json.loads(server.handle_get_profile(s, {"project": "proj"}))
67
+ assert len(found) == 1 and found[0]["entry_type"] == "profile", found
68
+ except ImportError as exc:
69
+ print(f"skip: MCP handler assertion ({exc})")
70
+
71
+ s._db.close()
72
+
73
+ print("ok: get_profile returns the profile, not the most recent rows")
74
+ return 0
75
+
76
+
77
+ if __name__ == "__main__":
78
+ raise SystemExit(main())
@@ -0,0 +1,62 @@
1
+ ---
2
+ name: checkpoint-auto
3
+ description: >-
4
+ Explains and steers the automatic memory capture that the memory-auto plugin runs: the
5
+ git-commit, compaction and idle triggers, what an injected [memory-checkpoint] prompt
6
+ means, and the in-process digest that writes entries on its own. Use when the user asks
7
+ "what is [memory-checkpoint]", "why did you save that", "how does automatic memory
8
+ work", or wants to tune or disable it. Not the capture procedure itself — that is
9
+ /checkpoint.
10
+ whenToUse: "/checkpoint-auto — what the automatic capture does, and its knobs"
11
+ ---
12
+
13
+ # Automatic capture (memory-auto)
14
+
15
+ This plugin captures memory **without being asked**. This skill explains what it does and
16
+ how to steer it. The writing procedure itself lives in `/checkpoint` — same entry types,
17
+ same selection rules; load that one to actually write entries.
18
+
19
+ ## Triggers
20
+
21
+ | Trigger | Fires when |
22
+ |---|---|
23
+ | git commit | a tool call runs a git commit |
24
+ | Compaction | the session compacts and activity exists |
25
+ | Idle | the session goes idle with activity |
26
+
27
+ A trigger queues a checkpoint; it reaches the agent on the next step as injected user
28
+ context whose first line carries the marker `[memory-checkpoint]`.
29
+
30
+ ## The digest
31
+
32
+ Beyond prompting, `memory-auto` can digest the session itself: it calls the harness's own
33
+ LLM service (`ctx.llm` — the credentials the session already uses, no external CLI, no
34
+ stored keys) over the transcript and writes the resulting entries. Its activity shows up
35
+ as `[memory-auto] …` lines.
36
+
37
+ ## Duplicate avoidance
38
+
39
+ Automatic and manual capture write to the same vault. Always search before writing — that
40
+ is step 3 of `/checkpoint`. A manual `/checkpoint` right after an automatic one should
41
+ normally add nothing: say so instead of writing a second copy of the same thing.
42
+
43
+ ## Knobs
44
+
45
+ Configuration lives in the plugin's composition row (`cordis.patch.yml`, or the profile
46
+ patch), not in this skill:
47
+
48
+ | Field | Default | Effect |
49
+ |---|---|---|
50
+ | `enabled` | `true` | master switch for automatic capture |
51
+ | `provider` / `model` | `deepseek-official` / `deepseek-v4-flash` | LLM target for the in-process digest |
52
+ | `maxTokens` | `2048` | digest response budget |
53
+ | `minTranscriptChars` | `200` | sessions with less transcript than this are not digested |
54
+ | `memoryPath` / `serverDir` | env, else the harness home | where the vault and its server live |
55
+
56
+ Turning capture off is a config change (`enabled: false`), not a skill change. State what
57
+ you changed and where.
58
+
59
+ ## When a checkpoint prompt arrives without this skill's procedure
60
+
61
+ Follow the prompt's own instructions. It carries the entry vocabulary and the selection
62
+ rules precisely so it works with no skill loaded — do not improvise entry types.