@ghilteras/opencode-agent-memory 0.5.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -24,7 +24,7 @@ Think of it as a searchable sidecar to `AGENTS.md`. OpenCode supports [rules](ht
24
24
 
25
25
  ## Requirements
26
26
 
27
- - [OpenCode](https://opencode.ai/) v1.0.115 or later
27
+ - [OpenCode](https://opencode.ai/) **v2** — this version uses the OpenCode v2 plugin API and does **not** run on v1
28
28
 
29
29
  ## Installation
30
30
 
@@ -32,29 +32,33 @@ Add to your OpenCode config (`~/.config/opencode/opencode.json`):
32
32
 
33
33
  ```json
34
34
  {
35
- "plugin": ["@ghilteras/opencode-agent-memory@0.5.0"]
35
+ "plugins": ["@ghilteras/opencode-agent-memory@1.0.0"]
36
36
  }
37
37
  ```
38
38
 
39
- OpenCode fetches unpinned plugins from npm on each startup; pinned versions are cached and require a manual version bump to update.
39
+ Note OpenCode **v2** reads the `plugins` key (v1 used `plugin`). OpenCode fetches unpinned plugins from npm on each startup; pinned versions are cached and require a manual version bump to update.
40
40
 
41
41
  ## Journal
42
42
 
43
- The journal is **opt-in**. Enable it in `~/.config/opencode/agent-memory.json`:
43
+ The journal is **on by default** — the three tools are registered with no configuration required.
44
+
45
+ To turn it off, set `enabled: false` in `~/.config/opencode/agent-memory.json`:
44
46
 
45
47
  ```json
46
48
  {
47
49
  "journal": {
48
- "enabled": true
50
+ "enabled": false
49
51
  }
50
52
  }
51
53
  ```
52
54
 
53
- With the journal disabled the plugin registers **no tools**.
55
+ - An explicit disable (`"enabled": false`) is silent by design and registers **no tools**.
56
+ - A config that exists but is unreadable, malformed, or schema-invalid **fails closed**: it logs `[agent-memory] journal config <resolved path>: <reason>; journal tools will NOT be registered` and registers **no tools**.
57
+ - An **absent** config means the default: the tools register. (This changed in 1.0.0 — an absent config used to disable the journal.)
54
58
 
55
59
  ### Tools
56
60
 
57
- When the journal is enabled, the agent gets 3 tools:
61
+ The agent gets 3 tools:
58
62
 
59
63
  | Tool | Description |
60
64
  |------|-------------|
@@ -116,6 +120,15 @@ By default the transformers.js model cache lives in the default location (`~/.ca
116
120
  }
117
121
  ```
118
122
 
123
+ ## Upgrading to 1.0.0
124
+
125
+ **This release requires OpenCode v2.** The plugin was ported from the v1 plugin API to the v2 plugin API and will not load on v1. The config key is now `plugins` (v1 used `plugin`).
126
+
127
+ Two behaviour changes:
128
+
129
+ - **The journal tools are registered by default.** Previously you had to opt in through `agent-memory.json`; now an absent config means the tools are on, and you turn them off with `"enabled": false`.
130
+ - **Storage is unchanged.** Existing entries under `~/.config/opencode/journal/` and their `.embedding` sidecars stay readable; nothing is migrated or rewritten.
131
+
119
132
  ## Upgrading from 0.4.x
120
133
 
121
134
  Memory blocks and their tools (`memory_list`, `memory_set`, `memory_replace`) are **removed**. Blocks are no longer read, written, or injected into the system prompt; the plugin ships only the journal.
@@ -124,11 +137,11 @@ Existing `~/.config/opencode/memory/` and `.opencode/memory/` directories are **
124
137
 
125
138
  ## Compatibility & Troubleshooting
126
139
 
127
- - **Requires OpenCode v1.0.115+.**
140
+ - **Requires OpenCode v2.** This release uses the OpenCode v2 plugin API and does not run on v1.
128
141
  - **Restart after config changes.** Plugin config changes require a full OpenCode restart to take effect; editing the config file alone is not sufficient.
129
- - **Journal is opt-in.** You must explicitly enable it in `~/.config/opencode/agent-memory.json`; with it disabled the plugin registers no tools.
142
+ - **Journal is on by default.** Turn it off with `"enabled": false`; an explicit disable is silent, while a config that exists but is unreadable, malformed, or schema-invalid logs a warning and registers no tools (fail-closed).
130
143
  - **Local embeddings, no data leaves the machine.** Semantic search uses a locally cached transformers.js model; no external API calls are made for search or embedding.
131
- - **Known limitation (0.5.1): guidance-in-descriptions depends on an unverified premise.** 0.5.1 moved journal guidance from the injected system-prompt note into the three journal tool descriptions, so only agents allowed to call those tools should see it. That relies on opencode omitting a permission-denied tool from the definitions sent to the model. This is **unverified**: a `tool.definition` probe on the isolated instance fires before permission filtering, so it cannot confirm what the model actually receives. If the premise does not hold, an agent denied `journal_*` may still read the description text; `deny` still blocks execution, so there is no capability escalation and no data disclosure — the blast radius is the three tools' description strings.
144
+ - **Known limitation (since 0.5.1): guidance-in-descriptions depends on an unverified premise.** 0.5.1 moved journal guidance from the injected system-prompt note into the three journal tool descriptions, so only agents allowed to call those tools should see it. That relies on opencode omitting a permission-denied tool from the definitions sent to the model. This is **unverified**: a `tool.definition` probe on the isolated instance fires before permission filtering, so it cannot confirm what the model actually receives. If the premise does not hold, an agent denied `journal_*` may still read the description text; `deny` still blocks execution, so there is no capability escalation and no data disclosure — the blast radius is the three tools' description strings.
132
145
 
133
146
  ## Inspiration
134
147
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ghilteras/opencode-agent-memory",
3
- "version": "0.5.1",
3
+ "version": "1.0.0",
4
4
  "description": "Journal-only memory plugin for OpenCode: tagged, searchable, append-only journal with semantic search.",
5
5
  "author": "Angelo Pantano <ghilteras@protonmail.com>",
6
6
  "license": "MIT",
@@ -22,7 +22,7 @@
22
22
  },
23
23
  "dependencies": {
24
24
  "@huggingface/transformers": "^3.8.1",
25
- "@opencode-ai/plugin": "^1.0.115",
25
+ "@opencode/plugin": "^2.0.18",
26
26
  "js-yaml": "^4.1.0",
27
27
  "zod": "^4.1.13"
28
28
  },
@@ -41,27 +41,68 @@ async function mkTmpDir(): Promise<string> {
41
41
  }
42
42
 
43
43
  describe("loadConfig", () => {
44
- test("returns empty config when file does not exist", async () => {
44
+ test("classifies a missing file and returns an empty config", async () => {
45
45
  const dir = await mkTmpDir();
46
- const config = await loadConfig(dir);
47
- expect(config).toEqual({});
46
+ const loaded = await loadConfig(dir);
47
+ expect(loaded.status).toBe("missing");
48
+ expect(loaded.config).toEqual({});
48
49
  });
49
50
 
50
- test("returns parsed config when file is valid", async () => {
51
+ test("classifies an unreadable file and returns an empty config", async () => {
52
+ const dir = await mkTmpDir();
53
+ await fs.mkdir(path.join(dir, "agent-memory.json"));
54
+ const loaded = await loadConfig(dir);
55
+ expect(loaded.status).toBe("unreadable");
56
+ expect(loaded.config).toEqual({});
57
+ });
58
+
59
+ test("classifies malformed JSON and returns an empty config", async () => {
60
+ const dir = await mkTmpDir();
61
+ await fs.writeFile(path.join(dir, "agent-memory.json"), "not json{{{");
62
+ const loaded = await loadConfig(dir);
63
+ expect(loaded.status).toBe("malformed");
64
+ expect(loaded.config).toEqual({});
65
+ });
66
+
67
+ test("classifies schema-invalid JSON and returns an empty config", async () => {
51
68
  const dir = await mkTmpDir();
52
69
  await fs.writeFile(
53
70
  path.join(dir, "agent-memory.json"),
54
- JSON.stringify({ journal: { enabled: true } }),
71
+ JSON.stringify({ journal: { enabled: "yes" } }),
55
72
  );
56
- const config = await loadConfig(dir);
57
- expect(config.journal?.enabled).toBe(true);
73
+ const loaded = await loadConfig(dir);
74
+ expect(loaded.status).toBe("invalid");
75
+ expect(loaded.config).toEqual({});
58
76
  });
59
77
 
60
- test("returns empty config when file has invalid JSON", async () => {
78
+ test("rejects an unrecognized journal key instead of silently enabling", async () => {
61
79
  const dir = await mkTmpDir();
62
- await fs.writeFile(path.join(dir, "agent-memory.json"), "not json{{{");
63
- const config = await loadConfig(dir);
64
- expect(config).toEqual({});
80
+ await fs.writeFile(path.join(dir, "agent-memory.json"), JSON.stringify({ journal: { enabled_: false } }));
81
+ const loaded = await loadConfig(dir);
82
+ expect(loaded.status).toBe("invalid");
83
+ expect(loaded.config).toEqual({});
84
+ });
85
+
86
+ test("classifies valid disabled config without changing it", async () => {
87
+ const dir = await mkTmpDir();
88
+ await fs.writeFile(
89
+ path.join(dir, "agent-memory.json"),
90
+ JSON.stringify({ journal: { enabled: false } }),
91
+ );
92
+ const loaded = await loadConfig(dir);
93
+ expect(loaded.status).toBe("ok");
94
+ expect(loaded.config).toEqual({ journal: { enabled: false } });
95
+ });
96
+
97
+ test("classifies valid enabled config without changing it", async () => {
98
+ const dir = await mkTmpDir();
99
+ await fs.writeFile(
100
+ path.join(dir, "agent-memory.json"),
101
+ JSON.stringify({ journal: { enabled: true } }),
102
+ );
103
+ const loaded = await loadConfig(dir);
104
+ expect(loaded.status).toBe("ok");
105
+ expect(loaded.config).toEqual({ journal: { enabled: true } });
65
106
  });
66
107
 
67
108
  test("returns custom tags from config", async () => {
@@ -78,22 +119,12 @@ describe("loadConfig", () => {
78
119
  },
79
120
  }),
80
121
  );
81
- const config = await loadConfig(dir);
82
- expect(config.journal?.tags).toEqual([
122
+ const loaded = await loadConfig(dir);
123
+ expect(loaded.config.journal?.tags).toEqual([
83
124
  { name: "perf", description: "Performance optimization work" },
84
125
  { name: "debug", description: "Debugging sessions" },
85
126
  ]);
86
127
  });
87
-
88
- test("returns empty config when schema validation fails", async () => {
89
- const dir = await mkTmpDir();
90
- await fs.writeFile(
91
- path.join(dir, "agent-memory.json"),
92
- JSON.stringify({ journal: { enabled: "yes" } }),
93
- );
94
- const config = await loadConfig(dir);
95
- expect(config).toEqual({});
96
- });
97
128
  });
98
129
 
99
130
  describe("journal store", () => {
package/src/journal.ts CHANGED
@@ -16,28 +16,81 @@ const TagSchema = z.looseObject({
16
16
  const ConfigSchema = z.looseObject({
17
17
  cacheDir: z.string().optional(),
18
18
  journal: z
19
- .looseObject({
19
+ .object({
20
20
  enabled: z.boolean().optional(),
21
21
  tags: z.array(TagSchema).optional(),
22
- })
22
+ }).strict()
23
23
  .optional(),
24
24
  });
25
25
 
26
26
  export type AgentMemoryConfig = z.infer<typeof ConfigSchema>;
27
27
 
28
+ export type ConfigLoadStatus =
29
+ | "ok"
30
+ | "missing"
31
+ | "unreadable"
32
+ | "malformed"
33
+ | "invalid";
34
+
35
+ export type LoadedConfig = {
36
+ config: AgentMemoryConfig;
37
+ status: ConfigLoadStatus;
38
+ configPath: string;
39
+ reason?: string;
40
+ };
41
+
28
42
  export async function loadConfig(
29
43
  configDir?: string,
30
- ): Promise<AgentMemoryConfig> {
44
+ ): Promise<LoadedConfig> {
31
45
  const dir = configDir ?? path.join(os.homedir(), ".config", "opencode");
32
- const configPath = path.join(dir, "agent-memory.json");
46
+ const configPath = path.resolve(dir, "agent-memory.json");
47
+
48
+ let raw: string;
49
+ try {
50
+ raw = await fs.readFile(configPath, "utf-8");
51
+ } catch (error) {
52
+ const code = error instanceof Error && "code" in error
53
+ ? String(error.code)
54
+ : "unknown error";
55
+ if (code === "ENOENT") {
56
+ return {
57
+ config: {},
58
+ status: "missing",
59
+ configPath,
60
+ reason: "file is missing",
61
+ };
62
+ }
63
+ return {
64
+ config: {},
65
+ status: "unreadable",
66
+ configPath,
67
+ reason: `read failed (${code})`,
68
+ };
69
+ }
70
+
71
+ let value: unknown;
33
72
  try {
34
- const raw = await fs.readFile(configPath, "utf-8");
35
- const parsed = ConfigSchema.safeParse(JSON.parse(raw));
36
- if (!parsed.success) return {};
37
- return parsed.data;
73
+ value = JSON.parse(raw);
38
74
  } catch {
39
- return {};
75
+ return {
76
+ config: {},
77
+ status: "malformed",
78
+ configPath,
79
+ reason: "malformed JSON",
80
+ };
40
81
  }
82
+
83
+ const parsed = ConfigSchema.safeParse(value);
84
+ if (!parsed.success) {
85
+ return {
86
+ config: {},
87
+ status: "invalid",
88
+ configPath,
89
+ reason: "schema validation failed",
90
+ };
91
+ }
92
+
93
+ return { config: parsed.data, status: "ok", configPath };
41
94
  }
42
95
 
43
96
  export type JournalTag = {
@@ -451,4 +504,3 @@ export function createJournalStore(configDir?: string, cacheDir?: string): Journ
451
504
  },
452
505
  };
453
506
  }
454
-
@@ -1,53 +1,26 @@
1
- import { describe, expect, mock, test } from "bun:test";
1
+ import { afterEach, expect, mock, test } from "bun:test";
2
2
 
3
- // Mock journal module with journal DISABLED — the control path.
4
3
  mock.module("./journal", () => ({
5
- loadConfig: async () => ({
6
- journal: { enabled: false },
7
- }),
4
+ loadConfig: async () => ({ config: { journal: { enabled: false } }, status: "ok", configPath: "/tmp/disabled/agent-memory.json" }),
8
5
  createJournalStore: () => ({}),
9
6
  }));
7
+ mock.module("./embeddings", () => ({ warmupEmbedder: async () => {} }));
8
+ import plugin from "./plugin";
10
9
 
11
- // Mock embeddings to avoid model download
12
- mock.module("./embeddings", () => ({
13
- warmupEmbedder: async () => {},
14
- }));
15
-
16
- import { MemoryPlugin } from "./plugin";
17
- import type { PluginInput } from "@opencode-ai/plugin";
18
-
19
- const stubInput = { directory: "/tmp/test-plugin-disabled" } as unknown as PluginInput;
20
-
21
- describe("plugin disabled path", () => {
22
- test("registers zero tools when journal is disabled", async () => {
23
- const plugin = await MemoryPlugin(stubInput);
24
- // tool should be undefined or an empty object
25
- if (plugin.tool) {
26
- expect(Object.keys(plugin.tool)).toHaveLength(0);
27
- } else {
28
- expect(plugin.tool).toBeUndefined();
29
- }
30
- });
31
-
32
- test("produces no guidance text when disabled", async () => {
33
- const plugin = await MemoryPlugin(stubInput);
34
- // There should be no system transform hook injecting guidance
35
- expect(plugin["experimental.chat.system.transform"]).toBeUndefined();
36
- // Tool definitions (if any exist as empty object) must not contain
37
- // any description with journal guidance keywords
38
- if (plugin.tool) {
39
- for (const def of Object.values(plugin.tool)) {
40
- const desc = (def as { description?: string }).description ?? "";
41
- expect(desc).not.toMatch(/append-only|journal|search.*entry/i);
42
- }
43
- }
44
- });
10
+ afterEach(() => mock.restore());
45
11
 
46
- test("chat.message hook is still present when disabled", async () => {
47
- const plugin = await MemoryPlugin(stubInput);
48
- // The chat.message hook updates model/provider context — it should
49
- // still be present even when journal is disabled.
50
- expect(plugin["chat.message"]).toBeDefined();
51
- expect(typeof plugin["chat.message"]).toBe("function");
52
- });
12
+ test("explicit opt-out registers no tools and emits no warning", async () => {
13
+ const definitions: unknown[] = [];
14
+ const warn = console.warn;
15
+ let warnings = 0;
16
+ console.warn = () => { warnings++; };
17
+ try {
18
+ await plugin.setup({
19
+ location: { directory: "/tmp" },
20
+ session: { hook: async () => {} },
21
+ tool: { transform: async (callback: (editor: { add: (tool: unknown) => void }) => void) => callback({ add: (tool) => definitions.push(tool) }) },
22
+ } as any);
23
+ expect(definitions).toEqual([]);
24
+ expect(warnings).toBe(0);
25
+ } finally { console.warn = warn; }
53
26
  });
@@ -1,41 +1,124 @@
1
- import { describe, expect, mock, test } from "bun:test";
1
+ import { afterEach, describe, expect, mock, test } from "bun:test";
2
+ import type { LoadedConfig, JournalEntry } from "./journal";
2
3
 
3
- // Mock journal module so we don't hit the real filesystem for config/journal
4
+ let loadedConfig: LoadedConfig = { config: {}, status: "missing", configPath: "/tmp/test/agent-memory.json", reason: "file is missing" };
5
+ const writes: Array<Record<string, unknown>> = [];
4
6
  mock.module("./journal", () => ({
5
- loadConfig: async () => ({
6
- journal: { enabled: true },
7
+ loadConfig: async () => loadedConfig,
8
+ createJournalStore: () => ({
9
+ write: async (entry: Record<string, unknown>) => {
10
+ writes.push(entry);
11
+ return { id: "id-1", title: entry.title, created: new Date("2026-01-01T00:00:00.000Z") } as JournalEntry;
12
+ },
13
+ read: async () => { throw new Error("unused"); },
14
+ search: async () => ({ entries: [], total: 0, allTags: [] }),
7
15
  }),
8
- createJournalStore: () => ({}),
9
16
  }));
17
+ mock.module("./embeddings", () => ({ warmupEmbedder: async () => {} }));
10
18
 
11
- // Mock embeddings to avoid model download
12
- mock.module("./embeddings", () => ({
13
- warmupEmbedder: async () => {},
14
- }));
19
+ import plugin from "./plugin";
15
20
 
16
- import { MemoryPlugin } from "./plugin";
17
- import type { PluginInput } from "@opencode-ai/plugin";
21
+ function harness() {
22
+ const definitions = new Map<string, any>();
23
+ let contextHook: ((event: any) => void) | undefined;
24
+ let transform: ((editor: { add: (definition: any) => void; list: () => any[] }) => void) | undefined;
25
+ const context = {
26
+ location: { directory: "/tmp/project" },
27
+ session: { hook: async (name: string, callback: (event: any) => void) => { expect(name).toBe("context"); contextHook = callback; } },
28
+ tool: { transform: async (callback: typeof transform) => { transform = callback; callback!({ add: (definition) => definitions.set(definition.name, definition), list: () => [...definitions.values()] }); } },
29
+ } as any;
30
+ return { definitions, contextHook: () => contextHook, replay: () => transform!({ add: (definition) => definitions.set(definition.name, definition), list: () => [...definitions.values()] }), start: () => plugin.setup(context) };
31
+ }
18
32
 
19
- // Minimal stub: the plugin only reads `directory` from the input.
20
- const stubInput = { directory: "/tmp/test-plugin-regression" } as unknown as PluginInput;
33
+ afterEach(() => {
34
+ loadedConfig = { config: {}, status: "missing", configPath: "/tmp/test/agent-memory.json", reason: "file is missing" };
35
+ writes.length = 0;
36
+ });
21
37
 
22
- describe("plugin structure", () => {
23
- test("returns chat.message hook", async () => {
24
- const plugin = await MemoryPlugin(stubInput);
25
- expect(plugin["chat.message"]).toBeDefined();
26
- expect(typeof plugin["chat.message"]).toBe("function");
38
+ describe("v2 plugin registration", () => {
39
+ test("has a stable id and default-registers exactly the three journal tools", async () => {
40
+ expect(plugin.id).toBe("opencode-agent-memory");
41
+ const h = harness();
42
+ await h.start();
43
+ expect([...h.definitions.keys()].sort()).toEqual(["journal_read", "journal_search", "journal_write"]);
27
44
  });
28
45
 
29
- test("does NOT return experimental.chat.system.transform hook", async () => {
30
- const plugin = await MemoryPlugin(stubInput);
31
- expect(plugin["experimental.chat.system.transform"]).toBeUndefined();
46
+ test("registered write description suggests configured tag names without their descriptions", async () => {
47
+ loadedConfig = {
48
+ config: {
49
+ journal: {
50
+ tags: [
51
+ { name: "owner_approved", description: "Use for a choice made and its rationale." },
52
+ { name: "incident_followup", description: "Use for investigation notes and findings." },
53
+ ],
54
+ },
55
+ },
56
+ status: "ok",
57
+ configPath: "/tmp/test/agent-memory.json",
58
+ };
59
+
60
+ const h = harness();
61
+ await h.start();
62
+ const description = h.definitions.get("journal_write").description as string;
63
+
64
+ expect(description).toContain("Suggested tags: owner_approved, incident_followup.");
65
+ expect(description).not.toContain("Use for a choice made and its rationale.");
66
+ expect(description).not.toContain("Use for investigation notes and findings.");
67
+ });
68
+
69
+ test("transform replay does not duplicate tool registration", async () => {
70
+ const h = harness(); await h.start();
71
+ h.replay();
72
+ expect([...h.definitions.keys()].sort()).toEqual(["journal_read", "journal_search", "journal_write"]);
73
+ });
74
+
75
+ test("explicit false opts out without tools", async () => {
76
+ loadedConfig = { config: { journal: { enabled: false } }, status: "ok", configPath: "/tmp/test/agent-memory.json" };
77
+ const h = harness(); await h.start();
78
+ expect([...h.definitions.keys()]).toEqual([]);
79
+ });
80
+
81
+ test("invalid journal typo fails closed and warns", async () => {
82
+ loadedConfig = { config: {}, status: "invalid", configPath: "/tmp/test/agent-memory.json", reason: "schema validation failed" };
83
+ const warnings: unknown[][] = [];
84
+ const originalWarn = console.warn;
85
+ console.warn = (...args) => warnings.push(args);
86
+ try {
87
+ const h = harness(); await h.start();
88
+ expect([...h.definitions.keys()]).toEqual([]);
89
+ expect(warnings).toEqual([["[agent-memory] journal config /tmp/test/agent-memory.json: schema validation failed; journal tools will NOT be registered"]]);
90
+ } finally { console.warn = originalWarn; }
91
+ });
92
+
93
+ for (const status of ["unreadable", "malformed", "invalid"] as const) {
94
+ test(`fails closed on ${status} config`, async () => {
95
+ loadedConfig = { config: { journal: { enabled: true } }, status, configPath: "/tmp/test/agent-memory.json", reason: "bad config" };
96
+ const warnings: unknown[][] = [];
97
+ const originalWarn = console.warn;
98
+ console.warn = (...args) => warnings.push(args);
99
+ try {
100
+ const h = harness(); await h.start();
101
+ expect([...h.definitions.keys()]).toEqual([]);
102
+ expect(warnings).toEqual([["[agent-memory] journal config /tmp/test/agent-memory.json: bad config; journal tools will NOT be registered"]]);
103
+ } finally { console.warn = originalWarn; }
104
+ });
105
+ }
106
+
107
+ test("default absent config emits no warning", async () => {
108
+ const warnings: unknown[][] = [];
109
+ const originalWarn = console.warn;
110
+ console.warn = (...args) => warnings.push(args);
111
+ try { const h = harness(); await h.start(); expect(warnings).toEqual([]); }
112
+ finally { console.warn = originalWarn; }
32
113
  });
33
114
 
34
- test("registers journal tools when enabled", async () => {
35
- const plugin = await MemoryPlugin(stubInput);
36
- expect(plugin.tool).toBeDefined();
37
- expect(plugin.tool!["journal_write"]).toBeDefined();
38
- expect(plugin.tool!["journal_read"]).toBeDefined();
39
- expect(plugin.tool!["journal_search"]).toBeDefined();
115
+ test("captures model/provider per session for interleaved context events", async () => {
116
+ const h = harness(); await h.start();
117
+ const hook = h.contextHook()!;
118
+ hook({ sessionID: "session-a", model: { id: "model-a", providerID: "provider-a" } });
119
+ hook({ sessionID: "session-b", model: { id: "model-b", providerID: "provider-b" } });
120
+ hook({ sessionID: "session-a", model: { id: "model-a2", providerID: "provider-a2" } });
121
+ await h.definitions.get("journal_write").execute({ title: "Title", body: "Body" }, { agent: "agent", sessionID: "session-b" });
122
+ expect(writes[0]).toMatchObject({ model: "model-b", provider: "provider-b", sessionId: "session-b" });
40
123
  });
41
124
  });
package/src/plugin.ts CHANGED
@@ -1,53 +1,62 @@
1
- import type { Plugin, ToolDefinition } from "@opencode-ai/plugin";
2
-
3
- import {
4
- createJournalStore,
5
- loadConfig,
6
- } from "./journal";
7
- import {
8
- JournalRead,
9
- JournalSearch,
10
- JournalWrite,
11
- } from "./tools";
1
+ import { Plugin } from "@opencode/plugin";
2
+ import { createJournalStore, loadConfig } from "./journal";
3
+ import { JournalRead, JournalSearch, JournalWrite } from "./tools";
12
4
  import type { JournalContext } from "./tools";
13
5
  import { warmupEmbedder } from "./embeddings";
14
6
 
15
- export const MemoryPlugin: Plugin = async ({ directory }) => {
16
- // Journal: opt-in via ~/.config/opencode/agent-memory.json
17
- const config = await loadConfig();
18
- const journalEnabled = config.journal?.enabled === true;
19
-
20
- // Mutable state updated by chat.message hook
21
- const journalCtx: JournalContext = {
22
- directory,
23
- model: "",
24
- provider: "",
25
- };
7
+ export default Plugin.define({
8
+ id: "opencode-agent-memory",
9
+ async setup(ctx) {
10
+ const loadedConfig = await loadConfig();
11
+ const { config } = loadedConfig;
12
+ const configUsable = loadedConfig.status === "ok" || loadedConfig.status === "missing";
13
+ if (!configUsable) {
14
+ console.warn(`[agent-memory] journal config ${loadedConfig.configPath}: ${loadedConfig.reason ?? loadedConfig.status}; journal tools will NOT be registered`);
15
+ return;
16
+ }
26
17
 
27
- let journalTools: Record<string, ToolDefinition> = {};
18
+ if (config.journal?.enabled === false) return;
28
19
 
29
- if (journalEnabled) {
30
20
  const journalStore = createJournalStore(undefined, config.cacheDir);
31
- // Warmup the embedder in the background; pass configured cacheDir so the
32
- // first-init-wins singleton caches to the correct directory.
33
21
  void warmupEmbedder(config.cacheDir).catch(() => {});
34
- journalTools = {
35
- journal_write: JournalWrite(journalStore, journalCtx, config.journal?.tags),
36
- journal_read: JournalRead(journalStore),
37
- journal_search: JournalSearch(journalStore),
22
+ const contexts = new Map<string, JournalContext>();
23
+ const directory = ctx.location.directory;
24
+ const tools = [
25
+ JournalWrite(journalStore, {
26
+ directory,
27
+ get model() { return ""; },
28
+ get provider() { return ""; },
29
+ }, config.journal?.tags),
30
+ JournalRead(journalStore),
31
+ JournalSearch(journalStore),
32
+ ];
33
+
34
+ // Register a per-session capture; a write resolves its own session's model.
35
+ const writeTool = tools[0]!;
36
+ writeTool.execute = async (input, toolCtx) => {
37
+ const sessionContext = contexts.get(toolCtx.sessionID);
38
+ const modelContext: JournalContext = {
39
+ directory,
40
+ model: sessionContext?.model ?? "",
41
+ provider: sessionContext?.provider ?? "",
42
+ };
43
+ const contextual = JournalWrite(journalStore, modelContext, config.journal?.tags);
44
+ return contextual.execute(input, toolCtx);
38
45
  };
39
- }
40
46
 
41
- return {
42
- "chat.message": async (input, _output) => {
43
- if (input.model) {
44
- journalCtx.model = input.model.modelID;
45
- journalCtx.provider = input.model.providerID;
47
+ await ctx.session.hook("context", (input) => {
48
+ contexts.set(input.sessionID, {
49
+ directory,
50
+ model: input.model.id,
51
+ provider: input.model.providerID,
52
+ });
53
+ });
54
+ await ctx.tool.transform((editor) => {
55
+ // Transforms may be replayed; avoid duplicate registrations by effective tool name.
56
+ const registered = new Set(editor.list().map((tool) => tool.name));
57
+ for (const tool of tools) {
58
+ if (!registered.has(tool.name)) editor.add(tool as never);
46
59
  }
47
- },
48
-
49
- tool: {
50
- ...journalTools,
51
- },
52
- };
53
- };
60
+ });
61
+ },
62
+ });
package/src/tools.test.ts CHANGED
@@ -1,167 +1,115 @@
1
1
  import { describe, expect, test } from "bun:test";
2
-
3
2
  import { JournalRead, JournalSearch, JournalWrite } from "./tools";
4
3
  import type { JournalContext } from "./tools";
5
- import type { JournalStore, JournalTag } from "./journal";
6
-
7
- // Minimal mock store — tests only check description strings, not execute.
8
- const mockStore: JournalStore = {
9
- write: async () => {
10
- throw new Error("not implemented");
11
- },
12
- read: async () => {
13
- throw new Error("not implemented");
14
- },
15
- search: async () => {
16
- throw new Error("not implemented");
17
- },
18
- };
19
-
20
- const mockCtx: JournalContext = {
21
- directory: "/tmp/test",
22
- model: "test-model",
23
- provider: "test-provider",
4
+ import type { JournalEntry, JournalStore } from "./journal";
5
+
6
+ const context: JournalContext = { directory: "/tmp/project", model: "m", provider: "p" };
7
+ function entry(): JournalEntry {
8
+ return { id: "20260101-000000-000", title: "Title", project: "/tmp", model: "m", provider: "p", agent: "a", sessionId: "s", created: new Date("2026-01-01T00:00:00.000Z"), tags: ["tag"], body: "Body", filePath: "/tmp/entry.md" };
9
+ }
10
+ const baseStore: JournalStore = {
11
+ write: async () => entry(),
12
+ read: async () => entry(),
13
+ search: async () => ({ entries: [entry()], total: 1, allTags: ["tag"] }),
24
14
  };
25
15
 
26
- // ─── Tool description tests ───────────────────────────────────────────────
27
- // These assert semantic properties of the description strings: that guidance
28
- // content is present, that stale/hallucinated text is absent, and that structural
29
- // invariants hold. They use substring/regex assertions, so intra-sentence
30
- // rewording is tolerated; only content-level regressions trip them.
31
-
32
- const WRITE_DESC_NO_TAGS = JournalWrite(mockStore, mockCtx).description;
33
- const WRITE_DESC_WITH_TAGS = JournalWrite(mockStore, mockCtx, [
34
- { name: "perf", description: "Performance optimization" },
35
- { name: "debug", description: "Debugging sessions" },
36
- ]).description;
37
- const READ_DESC = JournalRead(mockStore).description;
38
- const SEARCH_TOOL = JournalSearch(mockStore);
39
- const SEARCH_DESC = SEARCH_TOOL.description;
40
-
41
- describe("journal_write description", () => {
42
- test("mentions append-only semantics", () => {
43
- expect(WRITE_DESC_NO_TAGS).toContain("append-only");
44
- });
45
-
46
- test("explains that entries cannot be edited", () => {
47
- expect(WRITE_DESC_NO_TAGS).toMatch(/never edit|cannot be (edited|modified)/i);
48
- });
49
-
50
- test("documents tag format", () => {
51
- expect(WRITE_DESC_NO_TAGS).toMatch(/tags/i);
52
- expect(WRITE_DESC_NO_TAGS).toMatch(/comma.separated/i);
53
- });
54
-
55
- test("contains no dynamic or timestamped content", () => {
56
- // A static description must not embed a date or ISO timestamp
57
- expect(WRITE_DESC_NO_TAGS).not.toMatch(/\d{4}-\d{2}-\d{2}T/);
58
- });
59
-
60
- test("mentions the journal is for recording insights", () => {
61
- expect(WRITE_DESC_NO_TAGS).toMatch(/insight|discovery|decision|observation/i);
62
- });
63
-
64
- test("does not include suggested tags when none provided", () => {
65
- expect(WRITE_DESC_NO_TAGS).not.toMatch(/suggested tags/i);
66
- });
67
-
68
- test("includes suggested tags when provided", () => {
69
- expect(WRITE_DESC_WITH_TAGS).toMatch(/suggested tags/i);
70
- expect(WRITE_DESC_WITH_TAGS).toContain("perf");
71
- expect(WRITE_DESC_WITH_TAGS).toContain("debug");
72
- });
73
-
74
- test("suggested tags are tag names only, not descriptions", () => {
75
- expect(WRITE_DESC_WITH_TAGS).toContain("perf");
76
- expect(WRITE_DESC_WITH_TAGS).toContain("debug");
77
- // Tag descriptions should NOT appear in the tool description
78
- expect(WRITE_DESC_WITH_TAGS).not.toContain("Performance optimization");
79
- expect(WRITE_DESC_WITH_TAGS).not.toContain("Debugging sessions");
80
- });
81
- });
82
-
83
- describe("journal_read description", () => {
84
- test("mentions reading a specific entry by ID", () => {
85
- expect(READ_DESC).toMatch(/by.*ID/i);
86
- });
87
-
88
- test("does not contain write-only guidance", () => {
89
- // Write-scoping guidance (append-only, cannot be edited) belongs only in
90
- // journal_write's description. An agent with read-but-not-write would
91
- // see this guidance without the ability to act on it.
92
- expect(READ_DESC).not.toMatch(/append.only|cannot be (edited|modified)/i);
93
- });
94
-
95
- test("contains no dynamic or timestamped content", () => {
96
- expect(READ_DESC).not.toMatch(/\d{4}-\d{2}-\d{2}T/);
97
- });
98
- });
99
-
100
- describe("journal_search description", () => {
101
- test("mentions searching semantically", () => {
102
- expect(SEARCH_DESC).toMatch(/semantic|similarity|meaning/i);
103
- });
104
-
105
- test("mentions that filters can be combined", () => {
106
- expect(SEARCH_DESC).toMatch(/filter/i);
107
- });
108
-
109
- test("documents the project filter argument", () => {
110
- // The project filter is documented via the tool's args schema, not the
111
- // description prose. Assert the arg exists so a schema regression is caught.
112
- expect(SEARCH_TOOL.args).toBeDefined();
113
- expect(SEARCH_TOOL.args!.project).toBeDefined();
114
- });
115
-
116
- test("mentions pagination (offset)", () => {
117
- expect(SEARCH_DESC).toMatch(/offset|paginate/i);
118
- });
119
-
120
- test("mentions the journal is global across projects", () => {
121
- expect(SEARCH_DESC).toMatch(/global.*project|across.*project/i);
122
- });
123
-
124
- test("advises searching before complex tasks", () => {
125
- expect(SEARCH_DESC).toMatch(/complex task|before start/i);
126
- });
127
-
128
- test("contains no dynamic or timestamped content", () => {
129
- expect(SEARCH_DESC).not.toMatch(/\d{4}-\d{2}-\d{2}T/);
16
+ function valid(schema: any, value: any): boolean {
17
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
18
+ if (schema.additionalProperties === false && Object.keys(value).some((key) => !(key in schema.properties))) return false;
19
+ if (schema.required?.some((key: string) => !(key in value))) return false;
20
+ for (const [key, field] of Object.entries<any>(schema.properties)) {
21
+ if (!(key in value)) continue;
22
+ const actual = value[key];
23
+ if (field.type === "string" && typeof actual !== "string") return false;
24
+ if (field.type === "integer" && (!Number.isInteger(actual) || actual < (field.minimum ?? -Infinity))) return false;
25
+ }
26
+ return true;
27
+ }
28
+
29
+ describe("v2 journal tools", () => {
30
+ test("preserves the recognizable names and descriptions", () => {
31
+ expect([JournalWrite(baseStore, context).name, JournalRead(baseStore).name, JournalSearch(baseStore).name]).toEqual(["journal_write", "journal_read", "journal_search"]);
32
+ expect(JournalWrite(baseStore, context).description).toContain("append-only");
33
+ expect(JournalRead(baseStore).description).toContain("by its ID");
34
+ expect(JournalSearch(baseStore).description).toContain("semantic similarity");
35
+ });
36
+
37
+ test("journal_write description preserves its behavioral guidance", () => {
38
+ const description = JournalWrite(baseStore, context).description;
39
+ expect(description).toMatch(/insights.*discoveries|discoveries.*decisions/i);
40
+ expect(description).toMatch(/insights.*technical discoveries.*design decisions.*observations/i);
41
+ expect(description).toMatch(/never edit old ones/i);
42
+ expect(description).toMatch(/comma-separated/i);
43
+ expect(description).not.toMatch(/\d{4}-\d{2}-\d{2}T/);
44
+ expect(description).not.toContain("Suggested tags:");
45
+ const tagged = JournalWrite(baseStore, context, [{ name: "focus", description: "private detail" }]).description;
46
+ expect(tagged).toContain("Suggested tags: focus.");
47
+ expect(tagged).not.toContain("private detail");
48
+ });
49
+
50
+ test("read and search descriptions retain their distinct contracts", () => {
51
+ const read = JournalRead(baseStore).description;
52
+ expect(read).not.toMatch(/append.only|cannot be (edited|modified)/i);
53
+ expect(read).not.toMatch(/\d{4}-\d{2}-\d{2}T/);
54
+ const search = JournalSearch(baseStore);
55
+ expect(search.description).toMatch(/filters are optional/i);
56
+ expect(search.description).toMatch(/global across all projects/i);
57
+ expect(search.input.properties).toHaveProperty("project");
58
+ expect(search.input.properties).toHaveProperty("offset");
59
+ expect(search.description).toMatch(/paginate/i);
60
+ });
61
+
62
+ test("descriptions are nonempty and do not name sibling tools", () => {
63
+ const descriptions = [JournalWrite(baseStore, context).description, JournalRead(baseStore).description, JournalSearch(baseStore).description];
64
+ expect(descriptions.every((description) => description.trim().length > 0)).toBe(true);
65
+ for (const [index, description] of descriptions.entries()) {
66
+ for (const [otherIndex, name] of ["journal_write", "journal_read", "journal_search"].entries()) {
67
+ if (index !== otherIndex) expect(description).not.toContain(name);
68
+ }
69
+ }
130
70
  });
131
- });
132
71
 
133
- // ─── Cross-tool invariants ───────────────────────────────────────────────────
134
-
135
- describe("cross-tool invariants", () => {
136
- test("no description mentions another journal tool by name", () => {
137
- const toolNames = ["journal_search", "journal_read", "journal_write"];
138
- for (const name of toolNames) {
139
- const desc =
140
- name === "journal_write"
141
- ? WRITE_DESC_NO_TAGS
142
- : name === "journal_read"
143
- ? READ_DESC
144
- : SEARCH_DESC;
145
- const others = toolNames.filter((n) => n !== name);
146
- for (const other of others) {
147
- expect(desc).not.toContain(other);
148
- }
72
+ test("uses JSON schemas, rejects malformed and unknown arguments", () => {
73
+ const write = JournalWrite(baseStore, context).input as any;
74
+ const read = JournalRead(baseStore).input as any;
75
+ const search = JournalSearch(baseStore).input as any;
76
+ expect(write.type).toBe("object");
77
+ expect(valid(write, { title: "t", body: "b" })).toBe(true);
78
+ expect(valid(write, { title: 4, body: "b" })).toBe(false);
79
+ expect(valid(write, { title: "t", body: "b", extra: true })).toBe(false);
80
+ expect(valid(read, {})).toBe(false);
81
+ expect(valid(read, { id: "id", extra: 1 })).toBe(false);
82
+ expect(valid(search, { limit: 0 })).toBe(false);
83
+ expect(valid(search, { offset: 1.5 })).toBe(false);
84
+ expect(valid(search, { unexpected: true })).toBe(false);
85
+ expect(valid(search, { tags: "a,b", limit: 2, offset: 0 })).toBe(true);
86
+ });
87
+
88
+ test("all execute methods return the v2 {content} result", async () => {
89
+ const writeResult = await JournalWrite(baseStore, context).execute({ title: "t", body: "b" }, { agent: "a", sessionID: "s" });
90
+ const readResult = await JournalRead(baseStore).execute({ id: "entry" }, {} as any);
91
+ const searchResult = await JournalSearch(baseStore).execute({}, {} as any);
92
+ for (const result of [writeResult, readResult, searchResult]) {
93
+ expect(Object.keys(result)).toEqual(["content"]);
94
+ expect(typeof result.content).toBe("string");
149
95
  }
96
+ expect(writeResult.content).toContain("Journal entry created:");
97
+ expect(readResult.content).toContain("Body");
98
+ expect(searchResult.content).toContain("Found 1 entries");
150
99
  });
151
100
 
152
- test("all descriptions are non-empty strings", () => {
153
- expect(typeof WRITE_DESC_NO_TAGS).toBe("string");
154
- expect(WRITE_DESC_NO_TAGS.length).toBeGreaterThan(0);
155
- expect(typeof READ_DESC).toBe("string");
156
- expect(READ_DESC.length).toBeGreaterThan(0);
157
- expect(typeof SEARCH_DESC).toBe("string");
158
- expect(SEARCH_DESC.length).toBeGreaterThan(0);
101
+ test("retains bounded tag inventory output formatting", async () => {
102
+ const populated: JournalStore = { ...baseStore, search: async () => ({ entries: [entry()], total: 1, allTags: ["alpha", "beta"] }) };
103
+ expect((await JournalSearch(populated).execute({}, {} as any)).content).toContain("Tags in use: alpha, beta");
104
+ const empty: JournalStore = { ...baseStore, search: async () => ({ entries: [], total: 0, allTags: [] }) };
105
+ expect((await JournalSearch(empty).execute({}, {} as any)).content).toBe("No journal entries found.");
106
+ const store: JournalStore = { ...baseStore, search: async () => ({ entries: [], total: 0, allTags: Array.from({ length: 21 }, (_, i) => `tag-${i}`) }) };
107
+ const result = await JournalSearch(store).execute({}, {} as any);
108
+ expect(result.content).toBe("No journal entries found.\nTags in use: 21 (filter with tags=...)");
159
109
  });
160
110
 
161
- test("no description contains the retired invitation phrase", () => {
162
- const retired = "record thoughts, discoveries, and decisions as you work";
163
- expect(WRITE_DESC_NO_TAGS).not.toContain(retired);
164
- expect(READ_DESC).not.toContain(retired);
165
- expect(SEARCH_DESC).not.toContain(retired);
111
+ test("journal_read formats metadata before the body", async () => {
112
+ const result = await JournalRead(baseStore).execute({ id: "entry" }, {} as any);
113
+ expect(result.content).toBe("title: Title\ncreated: 2026-01-01T00:00:00.000Z\nproject: /tmp\nmodel: m\nprovider: p\nagent: a\nsession: s\ntags: tag\n\nBody");
166
114
  });
167
115
  });
package/src/tools.ts CHANGED
@@ -1,5 +1,3 @@
1
- import { tool } from "@opencode-ai/plugin";
2
-
3
1
  import type { JournalStore, JournalTag } from "./journal";
4
2
 
5
3
  export type JournalContext = {
@@ -8,137 +6,102 @@ export type JournalContext = {
8
6
  provider: string;
9
7
  };
10
8
 
11
- export function JournalWrite(
12
- store: JournalStore,
13
- ctx: JournalContext,
14
- tags?: readonly JournalTag[],
15
- ) {
16
- const suggestedTags =
17
- tags && tags.length > 0
18
- ? ` Suggested tags: ${tags.map((t) => t.name).join(", ")}.`
19
- : "";
20
- return tool({
21
- description:
22
- "Write a new append-only journal entry. Use this to capture insights, technical discoveries, " +
23
- "design decisions, observations, or reflections. " +
24
- "Entries are append-only: you write new entries but never edit old ones. " +
25
- "Tags are optional comma-separated names, e.g. \"perf, debugging\"." +
26
- suggestedTags,
27
- args: {
28
- title: tool.schema.string(),
29
- body: tool.schema.string(),
30
- tags: tool.schema.string().optional(),
31
- },
32
- async execute(args, toolCtx) {
33
- const tags = args.tags
34
- ? args.tags
35
- .split(",")
36
- .map((t: string) => t.trim())
37
- .filter(Boolean)
38
- : undefined;
9
+ const MAX_TAGS_TO_LIST = 20;
39
10
 
40
- const entry = await store.write({
41
- title: args.title,
42
- body: args.body,
43
- project: ctx.directory,
44
- model: ctx.model,
45
- provider: ctx.provider,
46
- agent: toolCtx.agent,
47
- sessionId: toolCtx.sessionID,
48
- tags,
49
- });
50
-
51
- return `Journal entry created: ${entry.id}\n title: ${entry.title}\n created: ${entry.created.toISOString()}`;
52
- },
53
- });
11
+ function formatTagsInUse(allTags: readonly string[]): string {
12
+ if (allTags.length === 0) return "";
13
+ if (allTags.length > MAX_TAGS_TO_LIST) return `\nTags in use: ${allTags.length} (filter with tags=...)`;
14
+ return `\nTags in use: ${allTags.join(", ")}`;
54
15
  }
55
16
 
56
- export function JournalRead(store: JournalStore) {
57
- return tool({
58
- description:
59
- "Read a specific journal entry by its ID. Returns the full entry " +
60
- "including metadata and body.",
61
- args: {
62
- id: tool.schema.string(),
17
+ type JsonSchema = {
18
+ type: "object";
19
+ properties: Record<string, { type: string; description?: string; minimum?: number }>;
20
+ required?: string[];
21
+ additionalProperties: false;
22
+ };
23
+ type ToolDefinition = {
24
+ name: string;
25
+ description: string;
26
+ input: JsonSchema;
27
+ execute(input: Record<string, unknown>, context: { agent: string; sessionID: string }): Promise<{ content: string }>;
28
+ };
29
+
30
+ export function JournalWrite(store: JournalStore, ctx: JournalContext, tags?: readonly JournalTag[]): ToolDefinition {
31
+ const suggestedTags = tags?.length ? ` Suggested tags: ${tags.map((tag) => tag.name).join(", ")}.` : "";
32
+ return {
33
+ name: "journal_write",
34
+ description: "Write a new append-only journal entry. Use this to capture insights, technical discoveries, design decisions, observations, or reflections. Entries are append-only: you write new entries but never edit old ones. Tags are optional comma-separated names, e.g. \"perf, debugging\"." + suggestedTags,
35
+ input: {
36
+ type: "object",
37
+ properties: {
38
+ title: { type: "string", description: "Entry title" },
39
+ body: { type: "string", description: "Entry body" },
40
+ tags: { type: "string", description: "Optional comma-separated tag names" },
41
+ },
42
+ required: ["title", "body"],
43
+ additionalProperties: false,
44
+ },
45
+ async execute(input, toolCtx) {
46
+ const title = input.title as string;
47
+ const body = input.body as string;
48
+ const tags = typeof input.tags === "string" ? input.tags.split(",").map((tag) => tag.trim()).filter(Boolean) : undefined;
49
+ const entry = await store.write({ title, body, project: ctx.directory, model: ctx.model, provider: ctx.provider, agent: toolCtx.agent, sessionId: toolCtx.sessionID, tags });
50
+ return { content: `Journal entry created: ${entry.id}\n title: ${entry.title}\n created: ${entry.created.toISOString()}` };
63
51
  },
64
- async execute(args) {
65
- const entry = await store.read(args.id);
52
+ };
53
+ }
66
54
 
55
+ export function JournalRead(store: JournalStore): ToolDefinition {
56
+ return {
57
+ name: "journal_read",
58
+ description: "Read a specific journal entry by its ID. Returns the full entry including metadata and body.",
59
+ input: { type: "object", properties: { id: { type: "string", description: "Journal entry ID" } }, required: ["id"], additionalProperties: false },
60
+ async execute(input) {
61
+ const entry = await store.read(input.id as string);
67
62
  const meta = [
68
- `title: ${entry.title}`,
69
- `created: ${entry.created.toISOString()}`,
63
+ `title: ${entry.title}`, `created: ${entry.created.toISOString()}`,
70
64
  entry.project ? `project: ${entry.project}` : null,
71
65
  entry.model ? `model: ${entry.model}` : null,
72
66
  entry.provider ? `provider: ${entry.provider}` : null,
73
67
  entry.agent ? `agent: ${entry.agent}` : null,
74
68
  entry.sessionId ? `session: ${entry.sessionId}` : null,
75
- entry.tags.length > 0
76
- ? `tags: ${entry.tags.join(", ")}`
77
- : null,
78
- ]
79
- .filter(Boolean)
80
- .join("\n");
81
-
82
- return `${meta}\n\n${entry.body}`;
69
+ entry.tags.length ? `tags: ${entry.tags.join(", ")}` : null,
70
+ ].filter(Boolean).join("\n");
71
+ return { content: `${meta}\n\n${entry.body}` };
83
72
  },
84
- });
73
+ };
85
74
  }
86
75
 
87
- export function JournalSearch(store: JournalStore) {
88
- return tool({
89
- description:
90
- "Search journal entries using semantic similarity. Returns matching entries " +
91
- "sorted by relevance. All filters are optional and combined with AND logic. " +
92
- "Use with no arguments to list recent entries. Use offset to paginate. " +
93
- "Before starting complex tasks, search the journal for relevant past context. " +
94
- "The journal is global across all projects but each entry records which project it was written from.",
95
- args: {
96
- text: tool.schema.string().optional(),
97
- project: tool.schema.string().optional(),
98
- tags: tool.schema.string().optional(),
99
- limit: tool.schema.number().int().positive().optional(),
100
- offset: tool.schema.number().int().nonnegative().optional(),
76
+ export function JournalSearch(store: JournalStore): ToolDefinition {
77
+ return {
78
+ name: "journal_search",
79
+ description: "Search journal entries using semantic similarity. Returns matching entries sorted by relevance. All filters are optional and combined with AND logic. Use with no arguments to list recent entries. Use offset to paginate. Before starting complex tasks, search the journal for relevant past context. The journal is global across all projects but each entry records which project it was written from.",
80
+ input: {
81
+ type: "object",
82
+ properties: {
83
+ text: { type: "string", description: "Semantic search text" },
84
+ project: { type: "string", description: "Filter by project directory" },
85
+ tags: { type: "string", description: "Comma-separated tags; all must match" },
86
+ limit: { type: "integer", minimum: 1, description: "Maximum entries to return" },
87
+ offset: { type: "integer", minimum: 0, description: "Number of entries to skip" },
88
+ },
89
+ additionalProperties: false,
101
90
  },
102
- async execute(args) {
103
- const tags = args.tags
104
- ? args.tags
105
- .split(",")
106
- .map((t: string) => t.trim())
107
- .filter(Boolean)
108
- : undefined;
109
-
91
+ async execute(input) {
110
92
  const result = await store.search({
111
- text: args.text,
112
- project: args.project,
113
- tags,
114
- limit: args.limit,
115
- offset: args.offset,
93
+ text: input.text as string | undefined,
94
+ project: input.project as string | undefined,
95
+ tags: typeof input.tags === "string" ? input.tags.split(",").map((tag) => tag.trim()).filter(Boolean) : undefined,
96
+ limit: input.limit as number | undefined,
97
+ offset: input.offset as number | undefined,
116
98
  });
117
-
118
- if (result.entries.length === 0) {
119
- const tagsLine =
120
- result.allTags.length > 0
121
- ? `\nTags in use: ${result.allTags.join(", ")}`
122
- : "";
123
- return `No journal entries found.${tagsLine}`;
124
- }
125
-
126
- const offset = args.offset ?? 0;
99
+ const tagsLine = formatTagsInUse(result.allTags);
100
+ if (!result.entries.length) return { content: `No journal entries found.${tagsLine}` };
101
+ const offset = (input.offset as number | undefined) ?? 0;
127
102
  const header = `Found ${result.total} entries (showing ${offset + 1}–${offset + result.entries.length}):`;
128
- const tagsLine =
129
- result.allTags.length > 0
130
- ? `\nTags in use: ${result.allTags.join(", ")}`
131
- : "";
132
-
133
- const lines = result.entries.map((e) => {
134
- const tagStr =
135
- e.tags.length > 0
136
- ? ` [${e.tags.join(", ")}]`
137
- : "";
138
- return `${e.id}\n ${e.title}${tagStr}\n ${e.created.toISOString()}`;
139
- });
140
-
141
- return `${header}${tagsLine}\n\n${lines.join("\n\n")}`;
103
+ const lines = result.entries.map((entry) => `${entry.id}\n ${entry.title}${entry.tags.length ? ` [${entry.tags.join(", ")}]` : ""}\n ${entry.created.toISOString()}`);
104
+ return { content: `${header}${tagsLine}\n\n${lines.join("\n\n")}` };
142
105
  },
143
- });
106
+ };
144
107
  }