@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 +23 -10
- package/package.json +2 -2
- package/src/journal.test.ts +54 -23
- package/src/journal.ts +62 -10
- package/src/plugin-disabled.test.ts +19 -46
- package/src/plugin.test.ts +110 -27
- package/src/plugin.ts +52 -43
- package/src/tools.test.ts +101 -153
- package/src/tools.ts +79 -116
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/)
|
|
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
|
-
"
|
|
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 **
|
|
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":
|
|
50
|
+
"enabled": false
|
|
49
51
|
}
|
|
50
52
|
}
|
|
51
53
|
```
|
|
52
54
|
|
|
53
|
-
|
|
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
|
-
|
|
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.
|
|
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
|
|
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.
|
|
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
|
|
25
|
+
"@opencode/plugin": "^2.0.18",
|
|
26
26
|
"js-yaml": "^4.1.0",
|
|
27
27
|
"zod": "^4.1.13"
|
|
28
28
|
},
|
package/src/journal.test.ts
CHANGED
|
@@ -41,27 +41,68 @@ async function mkTmpDir(): Promise<string> {
|
|
|
41
41
|
}
|
|
42
42
|
|
|
43
43
|
describe("loadConfig", () => {
|
|
44
|
-
test("
|
|
44
|
+
test("classifies a missing file and returns an empty config", async () => {
|
|
45
45
|
const dir = await mkTmpDir();
|
|
46
|
-
const
|
|
47
|
-
expect(
|
|
46
|
+
const loaded = await loadConfig(dir);
|
|
47
|
+
expect(loaded.status).toBe("missing");
|
|
48
|
+
expect(loaded.config).toEqual({});
|
|
48
49
|
});
|
|
49
50
|
|
|
50
|
-
test("
|
|
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:
|
|
71
|
+
JSON.stringify({ journal: { enabled: "yes" } }),
|
|
55
72
|
);
|
|
56
|
-
const
|
|
57
|
-
expect(
|
|
73
|
+
const loaded = await loadConfig(dir);
|
|
74
|
+
expect(loaded.status).toBe("invalid");
|
|
75
|
+
expect(loaded.config).toEqual({});
|
|
58
76
|
});
|
|
59
77
|
|
|
60
|
-
test("
|
|
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"),
|
|
63
|
-
const
|
|
64
|
-
expect(
|
|
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
|
|
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
|
-
.
|
|
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<
|
|
44
|
+
): Promise<LoadedConfig> {
|
|
31
45
|
const dir = configDir ?? path.join(os.homedir(), ".config", "opencode");
|
|
32
|
-
const configPath = path.
|
|
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
|
-
|
|
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 {
|
|
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
|
-
|
|
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
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
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
|
});
|
package/src/plugin.test.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
12
|
-
mock.module("./embeddings", () => ({
|
|
13
|
-
warmupEmbedder: async () => {},
|
|
14
|
-
}));
|
|
19
|
+
import plugin from "./plugin";
|
|
15
20
|
|
|
16
|
-
|
|
17
|
-
|
|
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
|
-
|
|
20
|
-
|
|
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
|
|
23
|
-
test("
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
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("
|
|
30
|
-
|
|
31
|
-
|
|
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("
|
|
35
|
-
const
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
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
|
|
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
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
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
|
-
|
|
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
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
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
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
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
|
-
|
|
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 {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
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
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
expect(
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
expect(
|
|
52
|
-
expect(
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
expect(
|
|
58
|
-
});
|
|
59
|
-
|
|
60
|
-
test("
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
expect(
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
expect(
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
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
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
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("
|
|
153
|
-
|
|
154
|
-
expect(
|
|
155
|
-
|
|
156
|
-
expect(
|
|
157
|
-
|
|
158
|
-
|
|
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("
|
|
162
|
-
const
|
|
163
|
-
expect(
|
|
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
|
-
|
|
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
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
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
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
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
|
-
|
|
65
|
-
|
|
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
|
|
76
|
-
|
|
77
|
-
|
|
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
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
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(
|
|
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:
|
|
112
|
-
project:
|
|
113
|
-
tags,
|
|
114
|
-
limit:
|
|
115
|
-
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
|
|
119
|
-
|
|
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
|
|
129
|
-
|
|
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
|
}
|