Skip to content

#1 Persistent memory for AI coding agents based on real-world benchmarks

fix(dsh): preserve config and forward daemon credentials (#1606)

Rohit Ghumare70517d2bdf30
diff --git a/docs/dsh.md b/docs/dsh.md
new file mode 100644
index 00000000..da8f6ef8
--- /dev/null
+++ b/docs/dsh.md
@@ -0,0 +1,37 @@
+# DeepSeek Harness
+
+Tested with DeepSeek Harness (`dsh`) 0.2.1-rc.2.
+
+Start AgentMemory, then connect the MCP tools:
+
+```bash
+npx @agentmemory/agentmemory
+# In another terminal:
+npx @agentmemory/agentmemory connect dsh
+```
+
+The adapter writes the home-level `$DSH_HOME/cordis.patch.yml`, shared by all Harness profiles. `DSH_HOME` defaults to `~/.dsh`. Existing plugins are preserved. Use `--force` to refresh an existing AgentMemory entry after upgrading.
+
+## Automatic capture
+
+The hooks bridge is optional and is not included in the stock Harness installation. Install it and its protocol dependency in every profile you use before enabling hooks. For the tested `headless` profile:
+
+```bash
+dsh plugin --profile headless add @deepseek-ai/[email protected]
+dsh plugin --profile headless add @deepseek-ai/[email protected]
+npx @agentmemory/agentmemory connect dsh --with-hooks
+```
+
+Replace `headless` with your profile name. Restart Harness after setup. Without the bridge package, MCP tools can work while automatic capture remains inactive; inspect Harness startup logs for plugin-load errors.
+
+The tested bridge removes secret environment variables before launching hook scripts. Local capture therefore needs the daemon's saved credentials in the same home directory, normally `~/.agentmemory/secret`. Remote capture with an environment-only bearer token is not supported by this bridge version; use the MCP tools for that setup.
+
+The generated `$DSH_HOME/agentmemory.hooks.json` uses bundled AgentMemory hook scripts. Re-run `npx @agentmemory/agentmemory connect dsh --with-hooks --force` after upgrading AgentMemory to refresh their paths.
+
+## Custom server and authentication
+
+Set `AGENTMEMORY_URL` and, when needed, `AGENTMEMORY_SECRET` in the environment that launches Harness. The MCP entry evaluates these variables at Harness startup through its `!!js` configuration syntax. Credentials are not copied into the patch file.
+
+Without an explicit URL, the server defaults to `http://localhost:3111`. Local MCP connections can discover the daemon's saved credentials. Remote servers need their matching bearer token in `AGENTMEMORY_SECRET`.
+
+Ask the agent to save a distinct test fact and recall it in a new session. With hooks enabled, also confirm the session and prompt appear in the AgentMemory viewer; successful MCP calls alone do not verify automatic capture.
diff --git a/src/cli/connect/dsh.ts b/src/cli/connect/dsh.ts
index 4f2979fa..5c997595 100644
--- a/src/cli/connect/dsh.ts
+++ b/src/cli/connect/dsh.ts
@@ -2,6 +2,7 @@ import { existsSync, mkdirSync, readFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import * as p from "@clack/prompts";
+import { isMap, isSeq, parseDocument } from "yaml";
import type { ConnectAdapter, ConnectOptions, ConnectResult } from "./types.js";
import {
backupFile,
@@ -26,7 +27,7 @@ function dshHome(): string {
return process.env["DSH_HOME"] || join(homedir(), ".dsh");
}
-// Harness env values are literal strings; no ${VAR:-default} interpolation.
+// Harness evaluates !!js before scrubbing secrets from the MCP child env.
const MCP_BLOCK = `- insert:
- id: agentmemory
name: '@deepseek-ai/dsh-mcp-client'
@@ -36,7 +37,8 @@ const MCP_BLOCK = `- insert:
command: npx
args: ['-y', '@agentmemory/mcp']
env:
- AGENTMEMORY_URL: http://localhost:3111
+ AGENTMEMORY_URL: !!js process.env.AGENTMEMORY_URL || 'http://localhost:3111'
+ AGENTMEMORY_SECRET: !!js process.env.AGENTMEMORY_SECRET || ''
`;
const MCP_MARKER = "serverName: agentmemory";
@@ -51,25 +53,55 @@ function hooksBlock(hooksConfigPath: string): string {
`;
}
-// Drop the managed top-level block containing `marker`.
-function stripBlock(content: string, marker: string): string {
- if (!content.includes(marker)) return content;
- const lines = content.split("\n");
- const markerIdx = lines.findIndex((l) => l.includes(marker));
- let start = markerIdx;
- while (start > 0 && !lines[start].startsWith("- ")) start--;
- let end = markerIdx + 1;
- while (end < lines.length && !lines[end].startsWith("- ")) end++;
- return lines
- .slice(0, start)
- .concat(lines.slice(end))
- .join("\n")
- .replace(/\n+$/, "\n");
+function parsePatch(content: string) {
+ const doc = parseDocument(content);
+ if (doc.contents === null) doc.contents = doc.createNode([]);
+ if (doc.errors.length || !isSeq(doc.contents)) {
+ throw new Error("Cannot update dsh cordis.patch.yml: expected a valid YAML sequence.");
+ }
+ return { doc, operations: doc.contents };
}
-function appendBlock(content: string, block: string): string {
- const base = content.replace(/\n+$/, "\n");
- return base.trim() ? `${base}\n${block}` : block;
+function isManaged(entry: unknown, marker: string): boolean {
+ if (!isMap(entry)) return false;
+ return marker === MCP_MARKER
+ ? entry.get("name") === "@deepseek-ai/dsh-mcp-client" && entry.getIn(["config", "serverName"]) === "agentmemory"
+ : entry.get("name") === "@deepseek-ai/dsh-hooks-claude-code" && entry.get("id") === "agentmemory-hooks";
+}
+
+function hasBlock(content: string, marker: string): boolean {
+ return parsePatch(content).operations.items.some((operation) => {
+ const entries = isMap(operation) ? operation.get("insert", true) : null;
+ return isSeq(entries) && entries.items.some((entry) => isManaged(entry, marker));
+ });
+}
+
+function upsertBlock(content: string, marker: string, block: string): string {
+ const { doc, operations } = parsePatch(content);
+ const addition = parsePatch(block).operations;
+ const replacement = addition.getIn([0, "insert", 0], true);
+ let replaced = false;
+ for (let i = 0; i < operations.items.length; i++) {
+ const operation = operations.items[i];
+ if (!isMap(operation)) continue;
+ const entries = operation.get("insert", true);
+ if (!isSeq(entries)) continue;
+ let removed = false;
+ for (let j = 0; j < entries.items.length; j++) {
+ if (!isManaged(entries.items[j], marker)) continue;
+ if (!replaced) {
+ entries.set(j, replacement);
+ replaced = true;
+ } else {
+ entries.delete(j--);
+ removed = true;
+ }
+ }
+ if (removed && entries.items.length === 0) operations.delete(i--);
+ }
+ if (!replaced) operations.items.push(...addition.items);
+ operations.flow = false;
+ return doc.toString();
}
function installHooksFile(home: string): string {
@@ -84,7 +116,7 @@ function installHooksFile(home: string): string {
export const adapter: ConnectAdapter = {
name: "dsh",
displayName: "DeepSeek Harness",
- docs: "https://github.com/rohitg00/agentmemory#other-agents",
+ docs: "https://github.com/rohitg00/agentmemory/blob/main/docs/dsh.md",
protocolNote:
"→ Using MCP via $DSH_HOME/cordis.patch.yml (the home-level patch layer every profile loads). Tools appear as mcp__agentmemory__*. Pass --with-hooks to also wire auto-capture through Harness's Claude Code hook bridge.",
category: "native",
@@ -99,8 +131,11 @@ export const adapter: ConnectAdapter = {
: "";
const wantHooks = opts.withHooks === true;
- const hasMcp = existing.includes(MCP_MARKER);
- const hasHooks = existing.includes(HOOKS_MARKER);
+ if (wantHooks) {
+ p.log.info(`Hooks require @deepseek-ai/dsh-hooks-claude-code and @deepseek-ai/dsh-hook-protocol in each profile, plus locally discoverable credentials. Setup: ${this.docs}`);
+ }
+ const hasMcp = hasBlock(existing, MCP_MARKER);
+ const hasHooks = hasBlock(existing, HOOKS_MARKER);
if (hasMcp && (!wantHooks || hasHooks) && !opts.force) {
logAlreadyWired(this.displayName, configPath);
@@ -122,20 +157,18 @@ export const adapter: ConnectAdapter = {
mkdirSync(dirname(configPath), { recursive: true });
}
- let next = stripBlock(existing, MCP_MARKER);
- next = appendBlock(next, MCP_BLOCK);
+ let next = hasMcp && !opts.force ? existing : upsertBlock(existing, MCP_MARKER, MCP_BLOCK);
- if (wantHooks) {
+ if (wantHooks && (!hasHooks || opts.force)) {
const hooksPath = installHooksFile(home);
- next = stripBlock(next, HOOKS_MARKER);
- next = appendBlock(next, hooksBlock(hooksPath));
+ next = upsertBlock(next, HOOKS_MARKER, hooksBlock(hooksPath));
p.log.info(`Hook manifest: ${hooksPath}`);
}
writeTextAtomic(configPath, next);
const written = readFileSync(configPath, "utf-8");
- if (!written.includes(MCP_MARKER) || (wantHooks && !written.includes(HOOKS_MARKER))) {
+ if (!hasBlock(written, MCP_MARKER) || (wantHooks && !hasBlock(written, HOOKS_MARKER))) {
p.log.error(
`Verification failed: ${configPath} did not contain the agentmemory rows after write.`,
);
diff --git a/test/connect-dsh.test.ts b/test/connect-dsh.test.ts
index 3ffcbbb2..d0de0abd 100644
--- a/test/connect-dsh.test.ts
+++ b/test/connect-dsh.test.ts
@@ -9,6 +9,7 @@ import {
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { parseDocument } from "yaml";
// DeepSeek Harness adapter: appends an @deepseek-ai/dsh-mcp-client row to
// the home-level $DSH_HOME/cordis.patch.yml, the machine-local patch layer
@@ -66,8 +67,28 @@ describe("connect: DeepSeek Harness", () => {
expect(patch).toContain("name: '@deepseek-ai/dsh-mcp-client'");
expect(patch).toContain("serverName: agentmemory");
expect(patch).toContain("transport: stdio");
- expect(patch).toContain("args: ['-y', '@agentmemory/mcp']");
- expect(patch).toContain("AGENTMEMORY_URL: http://localhost:3111");
+ expect(parseDocument(patch).toJS()[0].insert[0].config.args).toEqual(["-y", "@agentmemory/mcp"]);
+ expect(patch).toContain("AGENTMEMORY_URL:");
+ });
+
+ it("forwards the selected daemon and secret at dsh boot without storing credentials", async () => {
+ const { adapter } = await import("../src/cli/connect/dsh.js");
+ await adapter.install({ dryRun: false, force: false });
+ const patch = readFileSync(join(home, ".dsh", "cordis.patch.yml"), "utf-8");
+ // dsh evaluates !!js values before constructing the scrubbed MCP child env.
+ const doc = parseDocument(patch, {
+ customTags: [{ tag: "tag:yaml.org,2002:js", resolve: (value: string) =>
+ new Function("process", `return (${value})`)({ env: {
+ AGENTMEMORY_URL: "http://127.0.0.1:43111",
+ AGENTMEMORY_SECRET: "test-secret-not-for-config",
+ } }) }],
+ });
+ expect(doc.errors).toEqual([]);
+ expect(doc.toJS()[0].insert[0].config.env).toEqual({
+ AGENTMEMORY_URL: "http://127.0.0.1:43111",
+ AGENTMEMORY_SECRET: "test-secret-not-for-config",
+ });
+ expect(patch).not.toContain("test-secret-not-for-config");
});
it("preserves existing patch rows when appending", async () => {
@@ -85,6 +106,21 @@ describe("connect: DeepSeek Harness", () => {
expect(patch).toContain("serverName: agentmemory");
});
+ it.each([
+ "[{id: hmr, disabled: true}]\n",
+ "---\n- id: hmr\n disabled: true\n...\n",
+ ])("preserves a valid YAML document when installing: %s", async (existing) => {
+ const dir = join(home, ".dsh");
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, "cordis.patch.yml"), existing);
+ const { adapter } = await import("../src/cli/connect/dsh.js");
+ await adapter.install({ dryRun: false, force: false });
+ const doc = parseDocument(readFileSync(join(dir, "cordis.patch.yml"), "utf-8"));
+ expect(doc.errors).toEqual([]);
+ expect(doc.toJS()[0]).toEqual({ id: "hmr", disabled: true });
+ expect(doc.toJS()[1].insert[0].config.serverName).toBe("agentmemory");
+ });
+
it("is idempotent without --force", async () => {
mkdirSync(join(home, ".dsh"), { recursive: true });
const { adapter } = await import("../src/cli/connect/dsh.js");
@@ -95,6 +131,59 @@ describe("connect: DeepSeek Harness", () => {
expect(patch.match(/serverName: agentmemory/g)).toHaveLength(1);
});
+ it.each([
+ "# Example: serverName: agentmemory\n",
+ "- insert:\n - name: '@deepseek-ai/dsh-mcp-client'\n config:\n serverName: agentmemory-other\n",
+ ])("does not mistake a comment or another server for an installation: %s", async (existing) => {
+ const dir = join(home, ".dsh");
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, "cordis.patch.yml"), existing);
+ const { adapter } = await import("../src/cli/connect/dsh.js");
+ const result = await adapter.install({ dryRun: false, force: false });
+ expect(result.kind).toBe("installed");
+ const rows = parseDocument(readFileSync(join(dir, "cordis.patch.yml"), "utf-8")).toJS();
+ expect(rows.flatMap((row: { insert: unknown[] }) => row.insert).filter(
+ (entry: { config?: { serverName?: string } }) => entry.config?.serverName === "agentmemory",
+ )).toHaveLength(1);
+ });
+
+ it("recognizes a quoted server name without overwriting its custom configuration", async () => {
+ const dir = join(home, ".dsh");
+ mkdirSync(dir, { recursive: true });
+ const existing = "- insert:\n - name: '@deepseek-ai/dsh-mcp-client'\n config:\n serverName: 'agentmemory'\n command: custom-mcp\n";
+ writeFileSync(join(dir, "cordis.patch.yml"), existing);
+ const { adapter } = await import("../src/cli/connect/dsh.js");
+ const result = await adapter.install({ dryRun: false, force: false });
+ expect(result.kind).toBe("already-wired");
+ expect(readFileSync(join(dir, "cordis.patch.yml"), "utf-8")).toBe(existing);
+ });
+
+ it("adding hooks preserves an existing customized MCP server unless forced", async () => {
+ const dir = join(home, ".dsh");
+ mkdirSync(dir, { recursive: true });
+ const server = { name: "@deepseek-ai/dsh-mcp-client", config: {
+ serverName: "agentmemory", command: "custom-mcp", env: { AGENTMEMORY_URL: "https://memory.example.com" },
+ } };
+ writeFileSync(join(dir, "cordis.patch.yml"), JSON.stringify([{ insert: [server] }]));
+ const { adapter } = await import("../src/cli/connect/dsh.js");
+ const result = await adapter.install({ dryRun: false, force: false, withHooks: true });
+ expect(result.kind).toBe("installed");
+ const rows = parseDocument(readFileSync(join(dir, "cordis.patch.yml"), "utf-8")).toJS();
+ expect(rows[0].insert[0]).toEqual(server);
+ expect(rows[1].insert[0].id).toBe("agentmemory-hooks");
+ });
+
+ it.each(["- insert: [\n", "plugins: {}\n"])("rejects invalid patches without modifying them: %s", async (existing) => {
+ const dir = join(home, ".dsh");
+ mkdirSync(dir, { recursive: true });
+ const configPath = join(dir, "cordis.patch.yml");
+ writeFileSync(configPath, existing);
+ const { adapter } = await import("../src/cli/connect/dsh.js");
+ await expect(adapter.install({ dryRun: false, force: true, withHooks: true })).rejects.toThrow("valid YAML sequence");
+ expect(readFileSync(configPath, "utf-8")).toBe(existing);
+ expect(existsSync(join(dir, "agentmemory.hooks.json"))).toBe(false);
+ });
+
it("--force replaces the existing row instead of duplicating", async () => {
mkdirSync(join(home, ".dsh"), { recursive: true });
const { adapter } = await import("../src/cli/connect/dsh.js");
@@ -106,6 +195,75 @@ describe("connect: DeepSeek Harness", () => {
expect(patch.match(/- insert:/g)).toHaveLength(1);
});
+ it("--force preserves sibling plugins in the same insert operation", async () => {
+ const dir = join(home, ".dsh");
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, "cordis.patch.yml"), `# Personal plugins
+- insert:
+ - id: agentmemory
+ name: '@deepseek-ai/dsh-mcp-client'
+ config:
+ serverName: agentmemory
+ # Keep my formatter
+ - id: formatter
+ name: my-formatter
+ config:
+ enabled: true
+ before: assistant
+`);
+ const { adapter } = await import("../src/cli/connect/dsh.js");
+ await adapter.install({ dryRun: false, force: true });
+ const patch = readFileSync(join(dir, "cordis.patch.yml"), "utf-8");
+ expect(patch).toContain("id: formatter");
+ expect(patch).toContain("name: my-formatter");
+ expect(patch).toContain("# Keep my formatter");
+ expect(patch).toContain("before: assistant");
+ expect(patch.match(/serverName: agentmemory/g)).toHaveLength(1);
+ const rows = parseDocument(patch).toJS();
+ expect(rows).toHaveLength(1);
+ expect(rows[0].insert.map((entry: { id: string }) => entry.id)).toEqual(["agentmemory", "formatter"]);
+ });
+
+ it.each([
+ { id: "agentmemory", name: "@deepseek-ai/dsh-mcp-client", config: { serverName: "agentmemory", command: "old-command" } },
+ { id: "agentmemory-hooks", name: "@deepseek-ai/dsh-hooks-claude-code", config: { configPath: "old-hooks.json" } },
+ ])("--force preserves the sole $id entry's operation and position", async (entry) => {
+ const dir = join(home, ".dsh");
+ mkdirSync(dir, { recursive: true });
+ const configPath = join(dir, "cordis.patch.yml");
+ const operation = { insert: [entry], before: "assistant", root: "workspace" };
+ writeFileSync(configPath, JSON.stringify([operation, { id: "hmr", disabled: true }]));
+ const { adapter } = await import("../src/cli/connect/dsh.js");
+
+ for (let i = 0; i < 2; i++) {
+ await adapter.install({ dryRun: false, force: true, withHooks: entry.id === "agentmemory-hooks" });
+ const doc = parseDocument(readFileSync(configPath, "utf-8"));
+ expect(doc.errors).toEqual([]);
+ const rows = doc.toJS();
+ expect(rows[0]).toMatchObject({ before: "assistant", root: "workspace", insert: [{ id: entry.id, name: entry.name }] });
+ expect(rows[0].insert).toHaveLength(1);
+ expect(rows[0].insert[0].config).not.toEqual(entry.config);
+ expect(rows[1]).toEqual({ id: "hmr", disabled: true });
+ }
+ });
+
+ it("removes duplicate managed entries without deleting unrelated empty operations", async () => {
+ const dir = join(home, ".dsh");
+ mkdirSync(dir, { recursive: true });
+ const configPath = join(dir, "cordis.patch.yml");
+ const entry = { name: "@deepseek-ai/dsh-mcp-client", config: { serverName: "agentmemory" } };
+ const emptyOperation = { insert: [], before: "untouched" };
+ writeFileSync(configPath, JSON.stringify([emptyOperation, { insert: [entry, entry], before: "assistant" }, { insert: [entry] }]));
+ const { adapter } = await import("../src/cli/connect/dsh.js");
+ await adapter.install({ dryRun: false, force: true });
+ const rows = parseDocument(readFileSync(configPath, "utf-8")).toJS();
+ expect(rows).toHaveLength(2);
+ expect(rows[0]).toEqual(emptyOperation);
+ expect(rows[1].before).toBe("assistant");
+ expect(rows[1].insert).toHaveLength(1);
+ expect(rows[1].insert[0].config.command).toBe("npx");
+ });
+
it("dry-run mutates nothing", async () => {
mkdirSync(join(home, ".dsh"), { recursive: true });
const { adapter } = await import("../src/cli/connect/dsh.js");
@@ -138,7 +296,7 @@ describe("connect: DeepSeek Harness", () => {
const patch = readFileSync(join(home, ".dsh", "cordis.patch.yml"), "utf-8");
expect(patch).toContain("id: agentmemory-hooks");
expect(patch).toContain("name: '@deepseek-ai/dsh-hooks-claude-code'");
- expect(patch).toContain(`configPath: ${JSON.stringify(hooksPath)}`);
+ expect(parseDocument(patch).toJS()[1].insert[0].config.configPath).toBe(hooksPath);
// MCP row still present alongside.
expect(patch).toContain("serverName: agentmemory");
});