@log0u7/opencode-memory 0.1.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/CHANGELOG.md ADDED
@@ -0,0 +1,27 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [0.1.0] - 2026-09-18
11
+
12
+ ### Changed
13
+
14
+ - Trunk-based workflow: `main` is the only branch (PRs required, protected by rulesets); `dev` removed.
15
+
16
+ ### Added
17
+
18
+ - Coverage gate in CI: 90% lines/functions, 80% branches (`pnpm test:coverage` locally).
19
+ - Dependabot group coupling vitest with @vitest/* (coverage provider) so major bumps arrive together.
20
+ - CONTRIBUTING.md documents the mandatory test-first flow and the solo-maintainer merge preference.
21
+ - CONTRIBUTING.md documents the Dependabot dependency PR routine (criteria, maintainer approval, workflow-file merge options).
22
+ - Project scaffold: Apache-2.0 license, CI (biome + typecheck + vitest + gitleaks, Node 22/24 matrix), npm publish via trusted publishing, issue and PR templates, Dependabot, lefthook pre-commit.
23
+
24
+ ### Fixed
25
+
26
+ - Install docs register the scoped plugin name in `opencode.json` (an unscoped spec would attempt to install a nonexistent npm package).
27
+ - CI gitleaks job no longer fails on Dependabot pull requests (push-only).
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 log0u7
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,71 @@
1
+ # opencode-memory
2
+
3
+ [![CI](https://github.com/log0u7/opencode-memory/actions/workflows/ci.yml/badge.svg)](https://github.com/log0u7/opencode-memory/actions/workflows/ci.yml)
4
+ [![npm](https://img.shields.io/npm/v/@log0u7/opencode-memory)](https://www.npmjs.com/package/@log0u7/opencode-memory)
5
+ [![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)
6
+
7
+ Working memory for [OpenCode](https://opencode.ai): a shared SQLite store that all sessions on a machine read and write, so decisions, facts, and compaction summaries survive session boundaries.
8
+
9
+ Every session gets four tools (`memory_save`, `memory_search`, `memory_list`, `memory_forget`). Entries are scoped per project worktree (plus a `global` scope), searched with SQLite FTS5 (BM25 ranking with a recency boost). 100% local, no cloud, no API keys.
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ npm install -g @log0u7/opencode-memory
15
+ ```
16
+
17
+ Then register the plugin in `opencode.json`:
18
+
19
+ ```json
20
+ {
21
+ "plugin": ["@log0u7/opencode-memory"]
22
+ }
23
+ ```
24
+
25
+ Restart OpenCode. That is it: the store lives at `~/.local/share/opencode-memory/memory.db` (honors `XDG_DATA_HOME`).
26
+
27
+ Note (npm 12): the package ships no lifecycle install scripts and needs no `allowScripts` / allowlist on install.
28
+
29
+ ## Usage
30
+
31
+ Nothing to do manually: the model is instructed to search memory at task start and save durable facts as they emerge. You can drive it explicitly:
32
+
33
+ ```
34
+ memory_save(kind="decision", title="Use WAL mode", body="...", tags=["db"])
35
+ memory_search("postgres migration strategy")
36
+ memory_list()
37
+ memory_forget(id="...")
38
+ ```
39
+
40
+ ### Tools
41
+
42
+ | Tool | Args | Description |
43
+ |---|---|---|
44
+ | `memory_save` | `kind`, `title`, `body`, `scope?`, `tags?`, `expires_at?` | Save an entry. Default scope is the session worktree. |
45
+ | `memory_search` | `query`, `scope?`, `limit?` | Hybrid search: FTS5 BM25 + recency boost. |
46
+ | `memory_list` | `scope?`, `limit?` | Recent entries, newest first. |
47
+ | `memory_forget` | `id` or `query` | Delete one entry by id, or all matching a query. |
48
+
49
+ Entry `kind` is free-form; conventions that work well: `decision`, `fact`, `preference`, `gotcha`, `compaction`.
50
+
51
+ ### Notes
52
+
53
+ - All sessions on the machine share one store (WAL mode, concurrent-safe).
54
+ - Entries that look like secrets (`sk-…`, `ghp_…`, `xoxb-…`) are refused.
55
+ - On session compaction, the plugin asks the compaction prompt to emit durable decisions so the model can persist them.
56
+
57
+ ## Development
58
+
59
+ Requires Node >= 22 (mise: `mise install`) and pnpm (corepack).
60
+
61
+ ```sh
62
+ pnpm install
63
+ pnpm verify # biome + typecheck + vitest
64
+ pnpm build:check # tsc build + pack dry-run
65
+ ```
66
+
67
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for the workflow.
68
+
69
+ ## License
70
+
71
+ [Apache-2.0](LICENSE)
@@ -0,0 +1,15 @@
1
+ /**
2
+ * OpenCode Memory Plugin
3
+ *
4
+ * Shared working memory for all OpenCode sessions on a machine.
5
+ *
6
+ * @packageDocumentation
7
+ */
8
+ declare const pluginModule: {
9
+ id: string;
10
+ server: import("@opencode-ai/plugin").Plugin;
11
+ };
12
+ export default pluginModule;
13
+ export type { Entry, EntryInput, EntryKind } from "./types/entry.js";
14
+ export { MemoryPlugin } from "./plugin.js";
15
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AASH,QAAA,MAAM,YAAY;;;CAGQ,CAAC;eAEZ,YAAY;AAE3B,YAAY,EAAE,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAErE,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * OpenCode Memory Plugin
3
+ *
4
+ * Shared working memory for all OpenCode sessions on a machine.
5
+ *
6
+ * @packageDocumentation
7
+ */
8
+ import { MemoryPlugin } from "./plugin.js";
9
+ const pluginModule = {
10
+ id: "@log0u7/opencode-memory",
11
+ server: MemoryPlugin,
12
+ };
13
+ export default pluginModule;
14
+ export { MemoryPlugin } from "./plugin.js";
15
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAO3C,MAAM,YAAY,GAAG;IACnB,EAAE,EAAE,yBAAyB;IAC7B,MAAM,EAAE,YAAY;CACI,CAAC;AAE3B,eAAe,YAAY,CAAC;AAI5B,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC"}
@@ -0,0 +1,7 @@
1
+ import { type SqliteConn } from "./sqlite.js";
2
+ export type MemoryDb = {
3
+ conn: SqliteConn;
4
+ close(): void;
5
+ };
6
+ export declare function openMemoryDb(path: string): MemoryDb;
7
+ //# sourceMappingURL=db.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"db.d.ts","sourceRoot":"","sources":["../../src/lib/db.ts"],"names":[],"mappings":"AAGA,OAAO,EAAc,KAAK,UAAU,EAAE,MAAM,aAAa,CAAC;AAE1D,MAAM,MAAM,QAAQ,GAAG;IACrB,IAAI,EAAE,UAAU,CAAC;IACjB,KAAK,IAAI,IAAI,CAAC;CACf,CAAC;AA8BF,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,QAAQ,CAWnD"}
package/dist/lib/db.js ADDED
@@ -0,0 +1,41 @@
1
+ import { mkdirSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+ import { openSqlite } from "./sqlite.js";
4
+ const SCHEMA = `
5
+ CREATE TABLE IF NOT EXISTS entries (
6
+ id TEXT PRIMARY KEY,
7
+ scope TEXT NOT NULL,
8
+ kind TEXT NOT NULL,
9
+ title TEXT NOT NULL,
10
+ body TEXT NOT NULL,
11
+ tags TEXT NOT NULL DEFAULT '[]',
12
+ created_at INTEGER NOT NULL,
13
+ updated_at INTEGER NOT NULL,
14
+ expires_at INTEGER
15
+ );
16
+ CREATE VIRTUAL TABLE IF NOT EXISTS entries_fts USING fts5(
17
+ title, body, tags,
18
+ content='entries', content_rowid='rowid'
19
+ );
20
+ CREATE TRIGGER IF NOT EXISTS entries_ai AFTER INSERT ON entries BEGIN
21
+ INSERT INTO entries_fts(rowid, title, body, tags) VALUES (new.rowid, new.title, new.body, new.tags);
22
+ END;
23
+ CREATE TRIGGER IF NOT EXISTS entries_ad AFTER DELETE ON entries BEGIN
24
+ INSERT INTO entries_fts(entries_fts, rowid, title, body, tags) VALUES ('delete', old.rowid, old.title, old.body, old.tags);
25
+ END;
26
+ CREATE TRIGGER IF NOT EXISTS entries_au AFTER UPDATE ON entries BEGIN
27
+ INSERT INTO entries_fts(entries_fts, rowid, title, body, tags) VALUES ('delete', old.rowid, old.title, old.body, old.tags);
28
+ INSERT INTO entries_fts(rowid, title, body, tags) VALUES (new.rowid, new.title, new.body, new.tags);
29
+ END;
30
+ `;
31
+ export function openMemoryDb(path) {
32
+ if (path !== ":memory:") {
33
+ mkdirSync(dirname(path), { recursive: true });
34
+ }
35
+ const conn = openSqlite(path);
36
+ conn.run("PRAGMA journal_mode = WAL");
37
+ conn.run("PRAGMA busy_timeout = 5000");
38
+ conn.exec(SCHEMA);
39
+ return { conn, close: () => conn.close() };
40
+ }
41
+ //# sourceMappingURL=db.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"db.js","sourceRoot":"","sources":["../../src/lib/db.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AACpC,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,OAAO,EAAE,UAAU,EAAmB,MAAM,aAAa,CAAC;AAO1D,MAAM,MAAM,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;CA0Bd,CAAC;AAEF,MAAM,UAAU,YAAY,CAAC,IAAY;IACvC,IAAI,IAAI,KAAK,UAAU,EAAE,CAAC;QACxB,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IAChD,CAAC;IAED,MAAM,IAAI,GAAG,UAAU,CAAC,IAAI,CAAC,CAAC;IAC9B,IAAI,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;IACtC,IAAI,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC;IACvC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAElB,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,KAAK,EAAE,EAAE,CAAC;AAC7C,CAAC"}
@@ -0,0 +1,9 @@
1
+ export interface SqliteConn {
2
+ all<T = unknown>(sql: string, params?: unknown[]): T[];
3
+ get<T = unknown>(sql: string, params?: unknown[]): T | null;
4
+ run(sql: string, params?: unknown[]): void;
5
+ exec(sql: string): void;
6
+ close(): void;
7
+ }
8
+ export declare function openSqlite(path: string): SqliteConn;
9
+ //# sourceMappingURL=sqlite.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sqlite.d.ts","sourceRoot":"","sources":["../../src/lib/sqlite.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,UAAU;IACzB,GAAG,CAAC,CAAC,GAAG,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,EAAE,GAAG,CAAC,EAAE,CAAC;IACvD,GAAG,CAAC,CAAC,GAAG,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,EAAE,GAAG,CAAC,GAAG,IAAI,CAAC;IAC5D,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IAC3C,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,KAAK,IAAI,IAAI,CAAC;CACf;AAqED,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,UAAU,CAanD"}
@@ -0,0 +1,54 @@
1
+ function createPreparedConn(db) {
2
+ return {
3
+ all(sql, params) {
4
+ const stmt = db.prepare(sql);
5
+ return stmt.all(...(params ?? []));
6
+ },
7
+ get(sql, params) {
8
+ const stmt = db.prepare(sql);
9
+ return stmt.get(...(params ?? [])) ?? null;
10
+ },
11
+ run(sql, params) {
12
+ const stmt = db.prepare(sql);
13
+ stmt.run(...(params ?? []));
14
+ },
15
+ exec(sql) {
16
+ db.exec(sql);
17
+ },
18
+ close() {
19
+ db.close();
20
+ },
21
+ };
22
+ }
23
+ function createBunConn(db) {
24
+ return {
25
+ all(sql, params) {
26
+ return db.query(sql).all(...(params ?? []));
27
+ },
28
+ get(sql, params) {
29
+ return db.query(sql).get(...(params ?? [])) ?? null;
30
+ },
31
+ run(sql, params) {
32
+ db.run(sql, params ?? []);
33
+ },
34
+ exec(sql) {
35
+ db.run(sql);
36
+ },
37
+ close() {
38
+ db.close();
39
+ },
40
+ };
41
+ }
42
+ // Open a sqlite connection with the runtime's bundled engine: bun:sqlite when
43
+ // running inside OpenCode (Bun), node:sqlite when running under Node (tests, CI).
44
+ export function openSqlite(path) {
45
+ const globalRuntime = globalThis;
46
+ if (globalRuntime.Bun) {
47
+ return createBunConn(new globalRuntime.Bun.sqlite.Database(path));
48
+ }
49
+ // node:sqlite ships with Node >= 22.5; require keeps non-node runtimes from
50
+ // failing at module load and gives tests a clear error if the engine is absent.
51
+ const { DatabaseSync } = require("node:sqlite");
52
+ return createPreparedConn(new DatabaseSync(path));
53
+ }
54
+ //# sourceMappingURL=sqlite.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sqlite.js","sourceRoot":"","sources":["../../src/lib/sqlite.ts"],"names":[],"mappings":"AA8BA,SAAS,kBAAkB,CAAC,EAAsB;IAChD,OAAO;QACL,GAAG,CAAc,GAAW,EAAE,MAAkB;YAC9C,MAAM,IAAI,GAAG,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;YAC7B,OAAO,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,IAAI,EAAE,CAAC,CAAQ,CAAC;QAC5C,CAAC;QACD,GAAG,CAAc,GAAW,EAAE,MAAkB;YAC9C,M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M,UAAU,UAAU,CAAC,IAAY;IACrC,MAAM,aAAa,GAAG,UAErB,CAAC;IAEF,IAAI,aAAa,CAAC,GAAG,EAAE,CAAC;QACtB,OAAO,aAAa,CAAC,IAAI,aAAa,CAAC,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC;IACpE,CAAC;IAED,4EAA4E;IAC5E,gFAAgF;IAChF,MAAM,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC,aAAa,CAAsB,CAAC;IACrE,OAAO,kBAAkB,CAAC,IAAI,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC;AACpD,CAAC"}
@@ -0,0 +1,26 @@
1
+ import type { MemoryDb } from "./db.js";
2
+ import type { Entry, EntryInput } from "../types/entry.js";
3
+ export declare class SecretDetectedError extends Error {
4
+ constructor();
5
+ }
6
+ export declare function validateEntry(input: EntryInput): void;
7
+ export declare function save(db: MemoryDb, input: EntryInput, options?: {
8
+ now?: number;
9
+ }): Entry;
10
+ export declare function search(db: MemoryDb, query: {
11
+ query: string;
12
+ scope: string;
13
+ limit?: number;
14
+ now?: number;
15
+ }): Entry[];
16
+ export declare function list(db: MemoryDb, query: {
17
+ scope: string;
18
+ limit?: number;
19
+ now?: number;
20
+ }): Entry[];
21
+ export declare function forget(db: MemoryDb, target: {
22
+ id: string;
23
+ } | {
24
+ query: string;
25
+ }): number;
26
+ //# sourceMappingURL=store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/lib/store.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACxC,OAAO,KAAK,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAY3D,qBAAa,mBAAoB,SAAQ,KAAK;IAC5C,cAGC;CACF;AAED,wBAAgB,aAAa,CAAC,KAAK,EAAE,UAAU,GAAG,IAAI,CAiBrD;AAED,wBAAgB,IAAI,CAAC,EAAE,EAAE,QAAQ,EAAE,KAAK,EAAE,UAAU,EAAE,OAAO,GAAE;IAAE,GAAG,CAAC,EAAE,MAAM,CAAA;CAAO,GAAG,KAAK,CA+B3F;AAED,wBAAgB,MAAM,CACpB,EAAE,EAAE,QAAQ,EACZ,KAAK,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,MAAM,CAAA;CAAE,GACpE,KAAK,EAAE,CAcT;AAED,wBAAgB,IAAI,CAClB,EAAE,EAAE,QAAQ,EACZ,KAAK,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,MAAM,CAAA;CAAE,GACrD,KAAK,EAAE,CAaT;AAED,wBAAgB,MAAM,CAAC,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE;IAAE,EAAE,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,GAAG,MAAM,CAavF"}
@@ -0,0 +1,119 @@
1
+ import { randomUUID } from "node:crypto";
2
+ const TITLE_MAX = 120;
3
+ const BODY_MAX = 8000;
4
+ const TAGS_MAX = 12;
5
+ const SECRET_PATTERNS = [
6
+ /\bsk-[A-Za-z0-9_-]{20,}\b/,
7
+ /\bghp_[A-Za-z0-9]{30,}\b/,
8
+ /\bxoxb-\d{10,}-\d{10,}\b/,
9
+ ];
10
+ export class SecretDetectedError extends Error {
11
+ constructor() {
12
+ super("entry body looks like a credential; secrets must never be stored in memory");
13
+ this.name = "SecretDetectedError";
14
+ }
15
+ }
16
+ export function validateEntry(input) {
17
+ if (input.title.length === 0 || input.title.length > TITLE_MAX) {
18
+ throw new TypeError(`title must be 1..${TITLE_MAX} characters`);
19
+ }
20
+ if (input.body.length > BODY_MAX) {
21
+ throw new TypeError(`body must be at most ${BODY_MAX} characters`);
22
+ }
23
+ if (input.tags.length > TAGS_MAX) {
24
+ throw new TypeError(`at most ${TAGS_MAX} tags allowed`);
25
+ }
26
+ if (SECRET_PATTERNS.some((pattern) => pattern.test(input.body) || input.tags.some((t) => pattern.test(t)))) {
27
+ throw new SecretDetectedError();
28
+ }
29
+ }
30
+ export function save(db, input, options = {}) {
31
+ validateEntry(input);
32
+ const now = options.now ?? Date.now();
33
+ const id = randomUUID();
34
+ db.conn.run("INSERT INTO entries (id, scope, kind, title, body, tags, created_at, updated_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", [
35
+ id,
36
+ input.scope,
37
+ input.kind,
38
+ input.title,
39
+ input.body,
40
+ JSON.stringify(input.tags),
41
+ now,
42
+ now,
43
+ input.expires_at,
44
+ ]);
45
+ return {
46
+ id,
47
+ scope: input.scope,
48
+ kind: input.kind,
49
+ title: input.title,
50
+ body: input.body,
51
+ tags: input.tags,
52
+ created_at: now,
53
+ updated_at: now,
54
+ expires_at: input.expires_at,
55
+ };
56
+ }
57
+ export function search(db, query) {
58
+ const limit = query.limit ?? 10;
59
+ const now = query.now ?? Date.now();
60
+ return db.conn
61
+ .all(`SELECT e.* FROM entries_fts JOIN entries e ON e.rowid = entries_fts.rowid
62
+ WHERE entries_fts MATCH ? AND (e.scope = ? OR e.scope = 'global')
63
+ AND (e.expires_at IS NULL OR e.expires_at > ?)
64
+ ORDER BY bm25(entries_fts) ASC, e.updated_at DESC
65
+ LIMIT ?`, [escapeFtsQuery(query.query), query.scope, now, limit])
66
+ .map(rowToEntry);
67
+ }
68
+ export function list(db, query) {
69
+ const limit = query.limit ?? 20;
70
+ const now = query.now ?? Date.now();
71
+ return db.conn
72
+ .all(`SELECT * FROM entries
73
+ WHERE (scope = ? OR scope = 'global') AND (expires_at IS NULL OR expires_at > ?)
74
+ ORDER BY updated_at DESC, id ASC
75
+ LIMIT ?`, [query.scope, now, limit])
76
+ .map(rowToEntry);
77
+ }
78
+ export function forget(db, target) {
79
+ if ("id" in target) {
80
+ db.conn.run("DELETE FROM entries WHERE id = ?", [target.id]);
81
+ return db.conn.get("SELECT changes() AS changes")?.changes ?? 0;
82
+ }
83
+ db.conn.run(`DELETE FROM entries WHERE id IN (
84
+ SELECT e.id FROM entries_fts JOIN entries e ON e.rowid = entries_fts.rowid WHERE entries_fts MATCH ?
85
+ )`, [escapeFtsQuery(target.query)]);
86
+ return db.conn.get("SELECT changes() AS changes")?.changes ?? 0;
87
+ }
88
+ function rowToEntry(row) {
89
+ return {
90
+ id: row.id,
91
+ scope: row.scope,
92
+ kind: row.kind,
93
+ title: row.title,
94
+ body: row.body,
95
+ tags: parseTags(row.tags),
96
+ created_at: row.created_at,
97
+ updated_at: row.updated_at,
98
+ expires_at: row.expires_at,
99
+ };
100
+ }
101
+ function parseTags(raw) {
102
+ try {
103
+ const parsed = JSON.parse(raw);
104
+ return Array.isArray(parsed) ? parsed.filter((t) => typeof t === "string") : [];
105
+ }
106
+ catch {
107
+ return [];
108
+ }
109
+ }
110
+ // FTS5 queries treat punctuation as operators; wrap each whitespace-separated
111
+ // token in double quotes so arbitrary user/model input stays a literal search.
112
+ function escapeFtsQuery(raw) {
113
+ return raw
114
+ .split(/\s+/)
115
+ .filter(Boolean)
116
+ .map((token) => `"${token.replaceAll('"', '""')}"`)
117
+ .join(" ");
118
+ }
119
+ //# sourceMappingURL=store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/lib/store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAKzC,MAAM,SAAS,GAAG,GAAG,CAAC;AACtB,MAAM,QAAQ,GAAG,IAAI,CAAC;AACtB,MAAM,QAAQ,GAAG,EAAE,CAAC;AAEpB,MAAM,eAAe,GAAG;IACtB,2BAA2B;IAC3B,0BAA0B;IAC1B,0BAA0B;CAC3B,CAAC;AAEF,MAAM,OAAO,mBAAoB,SAAQ,KAAK;IAC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CAAC;IAC/F,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,EAAE,CAAC;IACZ,CAAC;AACH,CAAC;AAED,8EAA8E;AAC9E,+EAA+E;AAC/E,SAAS,cAAc,CAAC,GAAW;IACjC,OAAO,GAAG;SACP,KAAK,CAAC,KAAK,CAAC;SACZ,MAAM,CAAC,OAAO,CAAC;SACf,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,KAAK,CAAC,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC;SAClD,IAAI,CAAC,GAAG,CAAC,CAAC;AACf,CAAC"}
@@ -0,0 +1,3 @@
1
+ import type { Plugin } from "@opencode-ai/plugin";
2
+ export declare const MemoryPlugin: Plugin;
3
+ //# sourceMappingURL=plugin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAS,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAwBzD,eAAO,MAAM,YAAY,EAAE,MA6H1B,CAAC"}
package/dist/plugin.js ADDED
@@ -0,0 +1,149 @@
1
+ import { openMemoryDb } from "./lib/db.js";
2
+ import { forget, list, save, search, SecretDetectedError } from "./lib/store.js";
3
+ import { tool } from "@opencode-ai/plugin";
4
+ const SYSTEM_GUIDANCE = `You have persistent working memory shared with all OpenCode sessions on this machine.
5
+ At the start of a non-trivial task, run memory_search for relevant decisions and facts about this project.
6
+ When you make a durable decision or learn a lasting fact, call memory_save (kinds: decision, fact, preference, gotcha).
7
+ Never store credentials, tokens, or API keys in memory; the store refuses them.`;
8
+ const COMPACTION_CONTEXT = "The session is being compacted. After compaction, call memory_save for every durable decision still relevant " +
9
+ "(kind=decision) and any newly learned facts (kind=fact), so other sessions keep this knowledge.";
10
+ function defaultDbPath() {
11
+ const dataHome = process.env.XDG_DATA_HOME ?? `${process.env.HOME ?? ""}/.local/share`;
12
+ return `${dataHome}/opencode-memory/memory.db`;
13
+ }
14
+ export const MemoryPlugin = async (_input, options) => {
15
+ let db = null;
16
+ const getDb = () => {
17
+ if (!db) {
18
+ db = openMemoryDb(dbPath(options));
19
+ }
20
+ return db;
21
+ };
22
+ const hooks = {
23
+ tool: {
24
+ memory_save: tool({
25
+ description: "Save a durable entry to shared working memory (decisions, facts, preferences, gotchas). Never store credentials.",
26
+ args: {
27
+ kind: tool.schema
28
+ .string()
29
+ .describe("Entry type, e.g. decision, fact, preference, gotcha"),
30
+ title: tool.schema.string().describe("Short title (max 120 chars)"),
31
+ body: tool.schema.string().describe("Entry content (max 8000 chars)"),
32
+ scope: tool.schema
33
+ .string()
34
+ .optional()
35
+ .describe("Scope key; defaults to this session's worktree"),
36
+ tags: tool.schema.array(tool.schema.string()).optional().describe("Optional tags"),
37
+ expires_at: tool.schema.number().optional().describe("Optional epoch ms expiry"),
38
+ },
39
+ execute: (args, context) => run(() => {
40
+ const entry = save(getDb(), {
41
+ scope: args.scope ?? context.worktree,
42
+ kind: args.kind,
43
+ title: args.title,
44
+ body: args.body,
45
+ tags: args.tags ?? [],
46
+ expires_at: args.expires_at ?? null,
47
+ });
48
+ return `saved ${entry.id} (${entry.scope})`;
49
+ }),
50
+ }),
51
+ memory_search: tool({
52
+ description: "Search shared working memory (all sessions on this machine). Results include this project's scope and global entries.",
53
+ args: {
54
+ query: tool.schema.string().describe("Free-text query"),
55
+ scope: tool.schema
56
+ .string()
57
+ .optional()
58
+ .describe("Scope key; defaults to this session's worktree"),
59
+ limit: tool.schema.number().optional().describe("Max results (default 10)"),
60
+ },
61
+ execute: (args, context) => run(() => {
62
+ const hits = search(getDb(), {
63
+ query: args.query,
64
+ scope: args.scope ?? context.worktree,
65
+ ...(args.limit !== undefined ? { limit: args.limit } : {}),
66
+ });
67
+ if (hits.length === 0) {
68
+ return "no matching memory entries";
69
+ }
70
+ return JSON.stringify(hits, null, 2);
71
+ }),
72
+ }),
73
+ memory_list: tool({
74
+ description: "List recent memory entries for a scope (default: this session's worktree), newest first.",
75
+ args: {
76
+ scope: tool.schema
77
+ .string()
78
+ .optional()
79
+ .describe("Scope key; defaults to this session's worktree"),
80
+ limit: tool.schema.number().optional().describe("Max results (default 20)"),
81
+ },
82
+ execute: (args, context) => run(() => {
83
+ const entries = list(getDb(), {
84
+ scope: args.scope ?? context.worktree,
85
+ ...(args.limit !== undefined ? { limit: args.limit } : {}),
86
+ });
87
+ if (entries.length === 0) {
88
+ return "no memory entries";
89
+ }
90
+ return JSON.stringify(entries, null, 2);
91
+ }),
92
+ }),
93
+ memory_forget: tool({
94
+ description: "Delete memory entries by id, or all entries matching a query.",
95
+ args: {
96
+ id: tool.schema.string().optional().describe("Entry id to delete"),
97
+ query: tool.schema.string().optional().describe("Delete every entry matching this query"),
98
+ },
99
+ execute: (args, _context) => run(() => {
100
+ if (args.id !== undefined) {
101
+ const deleted = forget(getDb(), { id: args.id });
102
+ return `deleted ${deleted} entr${deleted === 1 ? "y" : "ies"}`;
103
+ }
104
+ if (args.query !== undefined) {
105
+ const deleted = forget(getDb(), { query: args.query });
106
+ return `deleted ${deleted} entr${deleted === 1 ? "y" : "ies"}`;
107
+ }
108
+ return "provide id or query";
109
+ }),
110
+ }),
111
+ },
112
+ };
113
+ return {
114
+ ...hooks,
115
+ "experimental.chat.system.transform": async (_input, output) => {
116
+ output.system.push(SYSTEM_GUIDANCE);
117
+ },
118
+ "experimental.session.compacting": async (_input, output) => {
119
+ output.context.push(COMPACTION_CONTEXT);
120
+ },
121
+ dispose: async () => {
122
+ db?.close();
123
+ db = null;
124
+ },
125
+ };
126
+ };
127
+ // Tool results are shown to the model: caught errors become readable text, so
128
+ // a rejected save is guidance instead of a crashed tool call.
129
+ async function run(fn) {
130
+ try {
131
+ return fn();
132
+ }
133
+ catch (error) {
134
+ if (error instanceof SecretDetectedError) {
135
+ return "refused: the content looks like a credential; secrets must never be stored in memory";
136
+ }
137
+ if (error instanceof Error) {
138
+ return `error: ${error.message}`;
139
+ }
140
+ throw error;
141
+ }
142
+ }
143
+ function dbPath(options) {
144
+ if (typeof options?.dbPath === "string" && options.dbPath.length > 0) {
145
+ return options.dbPath;
146
+ }
147
+ return defaultDbPath();
148
+ }
149
+ //# sourceMappingURL=plugin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plugin.js","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAiB,MAAM,aAAa,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACjF,OAAO,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAC;AAM3C,MAAM,eAAe,GAAG;;;gFAGwD,CAAC;AAEjF,MAAM,kBAAkB,GACtB,+GAA+G;IAC/G,iGAAiG,CAAC;AAEpG,SAAS,aAAa;IACpB,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,aAAa,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,IAAI,IAAI,EAAE,eAAe,CAAC;IACvF,OAAO,GAAG,QAAQ,4BAA4B,CAAC;AACjD,CAAC;AAED,MAAM,CAAC,MAAM,YAAY,GAAW,KAAK,EAAE,MAAM,EAAE,OAAuB,EAAE,EAAE;IAC5E,IAAI,EAAE,GAAoB,IAAI,CAAC;IAE/B,MAAM,KAAK,GAAG,GAAa,EAAE;QAC3B,IAAI,CAAC,EAAE,EAAE,CAAC;YACR,EAAE,GAAG,YAAY,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC;QACrC,CAAC;QACD,OAAO,EAAE,CAAC;IACZ,CAAC,CAAC;IAEF,MAAM,KAAK,GAAU;QACnB,IAAI,EAAE;YACJ,WAAW,EAAE,IAAI,CAAC;gBAChB,WAAW,EACT,kHAAkH;gBACpH,IAAI,EAAE;oBACJ,IAAI,EAAE,IAAI,CAAC,MAAM;yBACd,MAAM,EAAE;yBACR,QAAQ,CAAC,qDA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AAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACrE,OAAO,OAAO,CAAC,MAAM,CAAC;IACxB,CAAC;IACD,OAAO,aAAa,EAAE,CAAC;AACzB,CAAC"}
@@ -0,0 +1,21 @@
1
+ export type EntryKind = "decision" | "fact" | "preference" | "gotcha" | "compaction" | string;
2
+ export type Entry = {
3
+ id: string;
4
+ scope: string;
5
+ kind: EntryKind;
6
+ title: string;
7
+ body: string;
8
+ tags: string[];
9
+ created_at: number;
10
+ updated_at: number;
11
+ expires_at: number | null;
12
+ };
13
+ export type EntryInput = {
14
+ scope: string;
15
+ kind: EntryKind;
16
+ title: string;
17
+ body: string;
18
+ tags: string[];
19
+ expires_at: number | null;
20
+ };
21
+ //# sourceMappingURL=entry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"entry.d.ts","sourceRoot":"","sources":["../../src/types/entry.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,SAAS,GAAG,UAAU,GAAG,MAAM,GAAG,YAAY,GAAG,QAAQ,GAAG,YAAY,GAAG,MAAM,CAAC;AAE9F,MAAM,MAAM,KAAK,GAAG;IAClB,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,SAAS,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3B,CAAC;AAEF,MAAM,MAAM,UAAU,GAAG;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,SAAS,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3B,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=entry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"entry.js","sourceRoot":"","sources":["../../src/types/entry.ts"],"names":[],"mappings":""}
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@log0u7/opencode-memory",
3
+ "version": "0.1.0",
4
+ "description": "Working memory for OpenCode: shared SQLite store with hybrid search, shared across all sessions on a machine.",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/log0u7/opencode-memory.git"
10
+ },
11
+ "main": "./dist/index.js",
12
+ "types": "./dist/index.d.ts",
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "default": "./dist/index.js"
17
+ },
18
+ "./server": {
19
+ "types": "./dist/index.d.ts",
20
+ "default": "./dist/index.js"
21
+ }
22
+ },
23
+ "oc-plugin": [
24
+ "server"
25
+ ],
26
+ "files": [
27
+ "dist",
28
+ "README.md",
29
+ "LICENSE",
30
+ "CHANGELOG.md"
31
+ ],
32
+ "scripts": {
33
+ "build": "tsc -p tsconfig.json",
34
+ "build:check": "pnpm run build && pnpm pack --dry-run",
35
+ "check": "biome check .",
36
+ "format": "biome format --write .",
37
+ "typecheck": "tsc --noEmit",
38
+ "test": "vitest run",
39
+ "test:watch": "vitest",
40
+ "test:coverage": "vitest run --coverage",
41
+ "verify": "pnpm run check && pnpm run typecheck && pnpm run test",
42
+ "prepare": "lefthook install"
43
+ },
44
+ "packageManager": "pnpm@11.0.0",
45
+ "engines": {
46
+ "node": ">=22.0.0"
47
+ },
48
+ "devDependencies": {
49
+ "@biomejs/biome": "2.5.13",
50
+ "@opencode-ai/plugin": "1.18.30",
51
+ "@types/node": "^22.0.0",
52
+ "@vitest/coverage-v8": "^5.0.1",
53
+ "lefthook": "2.1.12",
54
+ "typescript": "7.0.2",
55
+ "vitest": "^5.0.0"
56
+ }
57
+ }