@luisarg/memory-auto 0.1.4 → 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/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +116 -2
- package/dist/index.js.map +1 -1
- package/package.json +8 -4
- package/skills/checkpoint-auto/SKILL.md +62 -0
package/dist/index.d.ts
CHANGED
|
@@ -12,6 +12,8 @@ export interface Config {
|
|
|
12
12
|
enabled: boolean;
|
|
13
13
|
}
|
|
14
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[];
|
|
15
17
|
export declare function apply(ctx: Context, config: Config): void;
|
|
16
18
|
//#endregion
|
|
17
19
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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;
|
|
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,6 +7,8 @@ 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
|
+
import { parse } from "yaml";
|
|
11
|
+
import { BUNDLED_SKILL_RANK } from "@deepseek-ai/dsh-skill";
|
|
10
12
|
//#region src/pure.ts
|
|
11
13
|
/**
|
|
12
14
|
* DSH memory plugin (adapted from the OpenCode memory plugin).
|
|
@@ -72,7 +74,7 @@ async function resolveProjectName(cwd) {
|
|
|
72
74
|
} catch {}
|
|
73
75
|
const pyprojectPath = join(cwd, "pyproject.toml");
|
|
74
76
|
if (existsSync(pyprojectPath)) try {
|
|
75
|
-
const m = (await readFile(pyprojectPath, "utf-8")).match(/\[project\][
|
|
77
|
+
const m = (await readFile(pyprojectPath, "utf-8")).match(/\[project\][^[]*?name\s*=\s*["']([^"']+)["']/);
|
|
76
78
|
if (m) return m[1];
|
|
77
79
|
} catch {}
|
|
78
80
|
const readmePath = join(cwd, "README.md");
|
|
@@ -537,6 +539,113 @@ async function digestSessionDSM(ctx, config, sessionId, directory, project, even
|
|
|
537
539
|
}
|
|
538
540
|
}
|
|
539
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
|
+
};
|
|
648
|
+
//#endregion
|
|
540
649
|
//#region src/plugin.ts
|
|
541
650
|
/**
|
|
542
651
|
* Harness wiring for `memory-auto`. Registers exactly these hooks:
|
|
@@ -562,6 +671,8 @@ const Config = Schema.object({
|
|
|
562
671
|
minTranscriptChars: Schema.number().default(200),
|
|
563
672
|
enabled: Schema.boolean().default(true)
|
|
564
673
|
});
|
|
674
|
+
/** Requires the harness LLM service: extraction runs in-process via ctx.llm. */
|
|
675
|
+
const inject = ["llm"];
|
|
565
676
|
/**
|
|
566
677
|
* Resolve the harness home the same way the harness does (`$DSH_HOME`, or
|
|
567
678
|
* `~/.dsh`). Paths must never depend on the launch cwd: DSH does not chdir.
|
|
@@ -596,6 +707,9 @@ function ensureFile(target, bundled, file) {
|
|
|
596
707
|
return true;
|
|
597
708
|
}
|
|
598
709
|
function apply(ctx, config) {
|
|
710
|
+
ctx.inject(["skills"], (ctx) => {
|
|
711
|
+
ctx.skills.registerProvider(() => skillsProvider);
|
|
712
|
+
});
|
|
599
713
|
if (!config.enabled) {
|
|
600
714
|
console.log("[memory-auto] disabled via config");
|
|
601
715
|
return;
|
|
@@ -752,6 +866,6 @@ function apply(ctx, config) {
|
|
|
752
866
|
console.log(`[memory-auto] active memoryPath=${memoryPath} serverDir=${serverDir} llm=${config.provider}/${config.model}`);
|
|
753
867
|
}
|
|
754
868
|
//#endregion
|
|
755
|
-
export { Config, apply, name };
|
|
869
|
+
export { Config, apply, inject, name };
|
|
756
870
|
|
|
757
871
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/pure.ts","../src/digest.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 * 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 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":";;;;;;;;;;;;;;;;;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,MAAM,KAAI,MADS,SAAS,eAAe,OAAO,EAAA,CACnC,MAAM,+CAA+C;EACpE,IAAI,GAAG,OAAO,EAAE;CAClB,QAAQ,CAER;CAGF,MAAM,aAAa,KAAK,KAAK,WAAW;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E,iBAAsB,KAAK,cAAc,KAAK,KAAK,MAAM,UAAU;IACrE,CAAC;GACH;EACF;CACF,CAAC;CAED,QAAQ,IAAI,mCAAmC,WAAW,aAAa,UAAU,OAAO,OAAO,SAAS,GAAG,OAAO,OAAO;AAC3H"}
|
|
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,U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G,QAAQ,SAAS,KAAK;KAAE,MAAM;KAAQ,SAAS;IAAE,CAAC;SACxF,QAAQ,IAAI,+CAA+C,KAAK;GACvE;EACF;EACA,OAAO,KAAK;CACd,CAAC;CAGD,IAAI,aAAa;EACf,aAAa;GACX,QAAQ,IAAI,+BAA+B,YAAY,KAAK,UAAU;GAEtE,KAAK,MAAM,CAAC,KAAK,QAAQ,aAAa;IAEpC,IAAI,CADO,OAAO,IAAI,GAChB,CAAC,EAAE,aAAa;IACtB,WAAW,GAAG,CAAC,CAAC,MAAM,SAAS;KAC7B,MAAM,aAAa,CAAC;MAAE,MAAM;MAAgB,MAAM,EAAE,MAAM,QAAQ,GAAG,EAAE;KAAE,CAAC;KAC1E,iBAAsB,KAAK,cAAc,KAAK,KAAK,MAAM,UAAU;IACrE,CAAC;GACH;EACF;CACF,CAAC;CAED,QAAQ,IAAI,mCAAmC,WAAW,aAAa,UAAU,OAAO,OAAO,SAAS,GAAG,OAAO,OAAO;AAC3H"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@luisarg/memory-auto",
|
|
3
|
-
"version": "0.1.
|
|
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": {
|
|
@@ -35,15 +36,18 @@
|
|
|
35
36
|
},
|
|
36
37
|
"dependencies": {
|
|
37
38
|
"@deepseek-ai/cordis": "4.0.2",
|
|
38
|
-
"@deepseek-ai/schemastery": "3.18.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
47
|
"typescript": "^7.0.2",
|
|
45
48
|
"tsdown": "^0.23.0",
|
|
46
49
|
"vitest": "^5.0.0",
|
|
47
|
-
"@deepseek-ai/dsh-llm": "0.1.
|
|
50
|
+
"@deepseek-ai/dsh-llm": "0.1.5-rc.2",
|
|
51
|
+
"@deepseek-ai/dsh-skill": "0.1.5-rc.2"
|
|
48
52
|
}
|
|
49
53
|
}
|
|
@@ -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.
|