opencode-growth 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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,52 @@
1
+ # opencode-growth
2
+
3
+ Cross-project memory for OpenCode — **memory / capability / preference / fact** — with
4
+ evidence, review and withdrawal.
5
+
6
+ > **Status: P0 in progress.** The storage/manifest/identity foundation, the injection (read)
7
+ > path, withdrawal-on-read, the review/publish protocol and the CLI exist. What is still
8
+ > missing before this is usable: the host adapter (S5/S6) that talks to a real OpenCode
9
+ > session. See `STATUS.md` for what each slice promises, and `ENFORCEMENT.md` for which
10
+ > guarantees are actually protected by a test.
11
+ >
12
+ > Try it against a scratch store:
13
+ >
14
+ > ```bash
15
+ > oc-grow --store /tmp/ocg status # what is in effect
16
+ > oc-grow --store /tmp/ocg doctor # can this store do its job? (exits 5 if not)
17
+ > oc-grow --store /tmp/ocg --help
18
+ > ```
19
+
20
+ ## What it is meant to do
21
+
22
+ Remember the corrections a user makes, reuse them in the right scope, be able to explain
23
+ where each one came from and which version was used, and be able to withdraw one that
24
+ turned out wrong — with bounded extra cost.
25
+
26
+ ## What it deliberately does not do
27
+
28
+ - It does not call model APIs out of band. Every LLM step happens inside an OpenCode
29
+ session (a headless `opencode run` driven by an external scheduler, or a restricted
30
+ child session created via `session.create`).
31
+ - It does not need OpenViking or any external memory service. The default backend is a
32
+ human-readable Markdown tree with a rebuildable index.
33
+ - It does not touch OpenCode's source, and it does not assume Hermes is present.
34
+
35
+ ## Layout
36
+
37
+ ```
38
+ src/core/ storage, manifest, identity, candidates, writer, audit, lock
39
+ src/core/render.mjs injection / read path (blocks, budgets, eviction reasons)
40
+ src/core/context.mjs context epochs, frozen per-session snapshots, `context show`
41
+ src/index.mjs public entry
42
+ test/ invariant tests (node --test)
43
+ ```
44
+
45
+ Read the design before changing anything: the invariants in `src/core/manifest.mjs` and
46
+ `src/core/writer.mjs` are the whole point of the kit.
47
+
48
+ ## Tests
49
+
50
+ ```bash
51
+ node --test test/
52
+ ```
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env node
2
+ // `oc-grow` — the CLI entry declared in package.json bin. All logic lives in src/cli.
3
+ import process from "node:process"
4
+ import { run } from "../src/cli/main.mjs"
5
+
6
+ try {
7
+ // `run` is async because some commands (learning a correction) spawn a process. Awaiting a
8
+ // non-promise is harmless, so every existing sychronous command keeps working unchanged.
9
+ process.exitCode = await run(process.argv.slice(2), process.env)
10
+ } catch (err) {
11
+ // An unexpected throw is not a refusal: make it loud and non-zero, never a silent 0.
12
+ process.stderr.write(`INTERNAL: ${err?.stack ?? err}\n`)
13
+ process.exitCode = 70
14
+ }
package/package.json ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "name": "opencode-growth",
3
+ "version": "0.1.0",
4
+ "description": "OpenCode growth kit: cross-project memory (memory / capability / preference / fact) with evidence and withdrawal.",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "engines": {
8
+ "node": ">=22.18.0"
9
+ },
10
+ "bin": {
11
+ "oc-grow": "./bin/oc-grow.mjs"
12
+ },
13
+ "exports": {
14
+ ".": "./src/index.mjs",
15
+ "./adapter/opencode": "./src/adapter-opencode/index.mjs"
16
+ },
17
+ "scripts": {
18
+ "test": "node --test test/"
19
+ },
20
+ "files": [
21
+ "src",
22
+ "bin",
23
+ "README.md",
24
+ "LICENSE"
25
+ ],
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/GOWxx/opencode-growth.git"
29
+ },
30
+ "bugs": {
31
+ "url": "https://github.com/GOWxx/opencode-growth/issues"
32
+ },
33
+ "homepage": "https://github.com/GOWxx/opencode-growth#readme",
34
+ "author": "gowxx"
35
+ }
@@ -0,0 +1,300 @@
1
+ // The OpenCode plugin adapter (S6): injection and explicit-correction capture.
2
+ //
3
+ // The host calls this as a plugin factory. Everything about the hook shape comes from what was
4
+ // measured in spikes/001–003, not from documentation:
5
+ //
6
+ // "experimental.chat.system.transform": async (input, output) => { output.system.push(...) }
7
+ // input carries sessionID; output.system is a mutable array of system-prompt parts; and the
8
+ // hook fires THREE times per run. So appending must be idempotent — the same bytes, once.
9
+ //
10
+ // Two rules shape the code:
11
+ //
12
+ // 1. A plugin must never break its host. If the store is missing, unreadable, or simply not
13
+ // configured, the hooks do nothing. Silence beats an exception inside someone else's
14
+ // process, and an adapter that throws would take the user's editor session down with it.
15
+ //
16
+ // 2. Capture does not learn here. A child session started from an event callback is killed by
17
+ // the parent's exit teardown (measured, 0 tokens, MessageAbortedError). So capture appends
18
+ // a request to a queue and returns; the external scheduler runs the headless learning
19
+ // pass. Nothing in this file can publish anything.
20
+ import fs from "node:fs"
21
+ import path from "node:path"
22
+
23
+ import { layout } from "../core/paths.mjs"
24
+ import { resolveProject } from "../core/identity.mjs"
25
+ import { frozenBlockFor, BLOCK_MARKER } from "../core/snapshot.mjs"
26
+ import { createMemoryStore } from "../core/memories.mjs"
27
+ import { appendAudit } from "../core/audit.mjs"
28
+ import { createReviewPipeline } from "./review-runner.mjs"
29
+ import { registerMemoryTool } from "./memory-tool.mjs"
30
+
31
+ /** 冻结块的稳定标识。用来把"本次 run 已经注入过"与"还没"分开——hook 每次 run 触发三次,
32
+ * 不判重就会把同样的字节付三遍钱。 */
33
+ const ENVELOPE_MARKER = BLOCK_MARKER
34
+
35
+ /**
36
+ * Is this user message an explicit correction worth learning from?
37
+ *
38
+ * A heuristic, and honestly so: it looks for the user telling the agent it was wrong, or
39
+ * asking it to remember something. It deliberately does not try to detect implied
40
+ * corrections — the design's whole point is that capture needs a signal, not a guess.
41
+ * Expect this list to grow from real corrections rather than from imagination.
42
+ */
43
+ const CORRECTION_SIGNALS = [
44
+ /^\s*(no[,.!]?\s|nope\b|actually\b|wrong\b|incorrect\b|that's not\b|that is not\b)/i,
45
+ /^\s*(remember|note that|from now on|keep in mind)\b/i,
46
+ /^\s*(don'?t|do not|never)\s/i,
47
+ /(不对|错了|不是这样|应该|改成|记住|别再|以后都?用|不要)/,
48
+ /(this repo|本项目|我们这里|这里)\s*(不|别|要)/,
49
+ ]
50
+
51
+ export function isExplicitCorrection(text) {
52
+ const t = String(text ?? "").trim()
53
+ if (!t || t.length > 4000) return false
54
+ return CORRECTION_SIGNALS.some((re) => re.test(t))
55
+ }
56
+
57
+ function appendQueueLine(queuePath, entry) {
58
+ fs.mkdirSync(path.dirname(queuePath), { recursive: true })
59
+ // Append-only: two corrections are two entries, and a crash mid-append can at worst leave a
60
+ // torn last line, which the consumer skips.
61
+ fs.appendFileSync(queuePath, JSON.stringify(entry) + "\n")
62
+ }
63
+
64
+ function resolveProjectId(storeDir, directory) {
65
+ try {
66
+ const L = layout(storeDir)
67
+ fs.mkdirSync(L.state, { recursive: true })
68
+ const project = resolveProject(directory, L.projects)
69
+ return project?.projectId ?? null
70
+ } catch {
71
+ return null
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Build the hooks. `store` may be null — that is the "not configured" case, not an error.
77
+ * Exported separately from the plugin factory so the behaviour above is testable without an
78
+ * OpenCode host.
79
+ *
80
+ * `client` is the host's API handle. It is not optional in practice: the factory's `directory`
81
+ * argument is NOT reliably the session's directory. Measured on 1.18.30, the host invokes the
82
+ * factory more than once with different directories (the project, then its own cwd), and the
83
+ * hook that actually fires can belong to the instance built for the wrong one. Scoping
84
+ * injection to that value silently injected nothing. The session's own `directory` — read from
85
+ * `client.session.get(...).data.directory` — is the authoritative answer.
86
+ */
87
+ // 回合结束的接线(后台复习的触发源)。宿主在回合结束时发 `session.idle`。
88
+ // 两条纪律:①只有 idle 才动,别的事件一律不碰;②适配器的故障绝不允许浮到宿主进程里。
89
+ export function createIdleWire({ handler } = {}) {
90
+ if (!handler || typeof handler.onIdle !== "function") {
91
+ return async () => ({ handled: false, reason: "no-handler" })
92
+ }
93
+ return async (arg = {}) => {
94
+ const event = arg?.event ?? null
95
+ if (!event) return { handled: false, reason: "no-event" }
96
+ const USER_TURN_EVENTS = ["message.updated", "message.part.updated"]
97
+ const isIdleEvent = event.type === "session.idle"
98
+ const isUserTurnEvent = USER_TURN_EVENTS.includes(event.type)
99
+ if (!isIdleEvent && !isUserTurnEvent) return { handled: false, reason: "not-idle" }
100
+ // 事件里的会话 id 必须传下去:流水线按会话记账(缺参时它会如实返回 no-session,
101
+ // 于是"看起来接上了、其实一次都没派发"——A138 就是这么发生的)。
102
+ const sessionId =
103
+ event?.properties?.sessionID ?? event?.sessionId ?? event?.sessionID ?? null
104
+ // 用户的**新回合开始** ⇒ 掐掉在跑的后台复习(照 Hermes:前台优先)。宿主事件形状按实测取,
105
+ // 取不到就跳过(这只是取消,漏一次不会造成错误状态,只会让前台多等一会儿)。
106
+ const isUserTurn =
107
+ isUserTurnEvent &&
108
+ (event?.properties?.info?.role ?? event?.properties?.message?.role ?? event?.properties?.role) === "user"
109
+ if (isUserTurn && typeof handler.onUserTurnStart === "function") {
110
+ const info = event?.properties?.info ?? event?.properties?.message ?? null
111
+ const userMsg = {
112
+ messageId: info?.id ?? event?.properties?.messageID ?? event?.properties?.id ?? null,
113
+ createdAt: info?.time?.created ?? event?.properties?.time?.created ?? null,
114
+ }
115
+ try {
116
+ await handler.onUserTurnStart(sessionId, userMsg)
117
+ } catch {
118
+ return { handled: false, reason: "handler-error" }
119
+ }
120
+ return { handled: true, what: "user-turn-start" }
121
+ }
122
+ if (!isIdleEvent) return { handled: false, reason: "not-a-user-turn" }
123
+ try {
124
+ await handler.onIdle(sessionId)
125
+ } catch {
126
+ return { handled: false, reason: "handler-error" }
127
+ }
128
+ return { handled: true, what: "turn-end" }
129
+ }
130
+ }
131
+
132
+ export function createAdapter({
133
+ reviewHandler = null,
134
+ store = null,
135
+ directory = process.cwd(),
136
+ queuePath = null,
137
+ client = null,
138
+ toolDef = null,
139
+ binding = null,
140
+ } = {}) {
141
+ const storeDir = store && String(store).trim() ? String(store) : null
142
+ // C① 实例自证:这个适配器**绑在哪个 D、哪个目录、值是哪来的**。
143
+ // 多配置根/多实例并存时,靠这个说清"我刚才写的到底进哪个 store",而不是靠猜。
144
+ const bindInfo = Object.freeze({
145
+ store: storeDir,
146
+ directory: String(directory ?? ""),
147
+ source: binding?.source ?? (storeDir ? "env" : "none"),
148
+ foregroundAgents: binding?.foregroundAgents ?? null,
149
+ interactive: binding?.interactive ?? null,
150
+ queuePath: queuePath ?? null,
151
+ })
152
+ const resolvedQueue = queuePath
153
+ ?? process.env.OCG_QUEUE
154
+ ?? (storeDir ? path.join(storeDir, "state", "learn-queue.jsonl") : null)
155
+
156
+ // One API call per session, not one per fire (the hook fires three times per run).
157
+ const sessionDirs = new Map()
158
+ // 回合结束 → 后台复习的触发(未配置 handler 时静默)
159
+ const idleWire = reviewHandler ? createIdleWire({ handler: reviewHandler }) : null
160
+
161
+ async function directoryForSession(sessionId) {
162
+ if (!client?.session?.get || !sessionId) return null
163
+ if (sessionDirs.has(sessionId)) return sessionDirs.get(sessionId)
164
+ let dir = null
165
+ try {
166
+ const res = await client.session.get({ path: { id: sessionId } })
167
+ const found = res?.data?.directory
168
+ if (typeof found === "string" && found.trim()) dir = found
169
+ } catch {
170
+ // **不回退**(审计 A20):拿不到会话自己的目录时,答案只能是 null。
171
+ // 原来这里回退到工厂的 directory —— 而工厂可能属于**另一个**实例/目录,
172
+ // 于是 A 项目的记录会被算进 B 会话的账。宁可不知道,也不要猜错。
173
+ }
174
+ sessionDirs.set(sessionId, dir)
175
+ return dir
176
+ }
177
+
178
+ return {
179
+ /** C① 实例自证:这个适配器绑在哪个 D / 哪个目录 / 值哪来的(多实例并存时可核对)。 */
180
+ binding: () => bindInfo,
181
+ // 工具只在真的拿到了定义时挂上——没有定义时不占位,免得给宿主一个空工具。
182
+ ...(toolDef ? { tool: { memory: toolDef } } : {}),
183
+ "experimental.chat.system.transform": async (input, output) => {
184
+ if (!storeDir || !output || !Array.isArray(output.system)) return
185
+ if (output.system.some((part) => typeof part === "string" && part.includes(ENVELOPE_MARKER))) {
186
+ // Already injected for this run. The hook fires three times per run; appending again
187
+ // would pay for the same bytes twice in every prompt.
188
+ return
189
+ }
190
+ try {
191
+ const sessionId = input?.sessionID ? String(input.sessionID) : null
192
+ if (!sessionId) return
193
+ // **无条件注入**:不按项目、可见性、agent 做条件。
194
+ // 不是偷懒——实测 `transform` 的 input 只有 {sessionID, model},两次调用的 keys 完全相同,
195
+ // **根本区分不了主调用与标题生成**。条件只能来自"会话 + 冻结"这两件我们知道的事。
196
+ const frozen = await frozenBlockFor({ root: storeDir, sessionID: sessionId })
197
+ if (!frozen.text) return
198
+ output.system.push(frozen.text)
199
+ } catch {
200
+ // Never surface an adapter fault to the host. A memory block that breaks the editor is
201
+ // worse than a memory block that is missing.
202
+ }
203
+ },
204
+
205
+ event: async ({ event } = {}) => {
206
+ if (idleWire) await idleWire({ event })
207
+ try {
208
+ const text = event?.properties?.text ?? event?.properties?.message?.text ?? null
209
+ if (!text || !isExplicitCorrection(text)) return
210
+ if (!resolvedQueue) return
211
+ const sessionId = event?.properties?.sessionID ?? event?.sessionID ?? null
212
+ // The message id, so the eventual candidate can be traced back to the utterance that
213
+ // prompted it. Read from every shape OpenCode was seen to use rather than one guess; a
214
+ // missing id is recorded as null, never invented (audit A16).
215
+ const messageId =
216
+ event?.properties?.messageID ??
217
+ event?.properties?.message?.id ??
218
+ event?.properties?.part?.messageID ??
219
+ null
220
+ appendQueueLine(resolvedQueue, {
221
+ state: "pending",
222
+ capturedAt: new Date().toISOString(),
223
+ sessionId,
224
+ messageId,
225
+ projectId: storeDir ? resolveProjectId(storeDir, await directoryForSession(sessionId)) : null,
226
+ excerpt: String(text).slice(0, 400),
227
+ origin: "opencode-capture",
228
+ })
229
+ // Deliberately nothing else: no spawn, no candidate, no publish. The scheduler owns
230
+ // what happens next, because an in-session child would be killed by the parent's exit.
231
+ } catch {
232
+ // Same rule as above: capture failing must not break the host.
233
+ }
234
+ },
235
+ }
236
+ }
237
+
238
+ /**
239
+ * The plugin entry OpenCode loads. The store is configuration, not something to guess: without
240
+ * `OCG_STORE` the adapter is inert rather than picking a directory of its own.
241
+ */
242
+ export const OcgGrowth = async ({ directory, client, z, tool } = {}) => {
243
+ // C① **绑定时刻**定值:这一份实例认定自己的 D 与身份名单。
244
+ // 之后进程里再有人动环境变量,也改不动已经绑好的这个实例(多配置根串用类问题的根)。
245
+ const bindInfo = Object.freeze({
246
+ store: process.env.OCG_STORE?.trim() ? String(process.env.OCG_STORE).trim() : null,
247
+ directory: String(directory ?? ""),
248
+ source: process.env.OCG_STORE?.trim() ? "env" : "none",
249
+ foregroundAgents: (process.env.OCG_FOREGROUND_AGENTS ?? "").split(",").map((x) => x.trim()).filter(Boolean),
250
+ interactive: process.env.OCG_INTERACTIVE === "1",
251
+ queuePath: process.env.OCG_QUEUE ?? null,
252
+ })
253
+ const storeDir = bindInfo.store
254
+ // 工具注册要拿到宿主的 zod(实测:宿主装在 <XDG_CONFIG_HOME>/opencode/node_modules/)。
255
+ // 宿主依赖也可以由装好的插件 shim **注入**进来(那份 shim 就在能解析到它的目录里)。
256
+ // 但**拿不到只是少一个能力**,不该让注入/冻结一起挂掉——所以失败就退回没有工具。
257
+ let toolDef = null
258
+ if (storeDir) {
259
+ const reg = await registerMemoryTool({
260
+ root: storeDir, z, tool,
261
+ foregroundAgents: bindInfo.foregroundAgents, // 绑定时刻的值,别在调用时才读环境
262
+ interactive: bindInfo.interactive,
263
+ })
264
+ if (reg && !reg.__error) toolDef = reg
265
+ }
266
+ // 回合结束触发后台复习:只在真配了 store 且宿主给了 client 时接线(否则静默)
267
+ // A131:决策条目落进**既有审计面**(`core/audit.mjs` 的按月 jsonl),不另造一套账。
268
+ // 排障:真机链上"审计一条都没有"可能是 storeDir 根本没解析出来 ⇒ 初始化时先如实记一笔
269
+ if (process.env.OCG_REVIEW_TRACE === "1") {
270
+ try {
271
+ const f = process.env.OCG_TRACE_FILE || "/tmp/ocg-review-trace.log"
272
+ fs.appendFileSync(f, JSON.stringify({ ts: Date.now(), step: "plugin-init", storeDir: storeDir ?? null, auditSink: Boolean(storeDir) }) + "\n")
273
+ } catch { /* 留痕失败不影响主流程 */ }
274
+ }
275
+ const reviewAudit = storeDir ? (event) => {
276
+ try { appendAudit(layout(storeDir), event) } catch (e) {
277
+ // 记账失败**不许**把宿主弄崩,但也**不许**静默丢掉——留一行痕迹,出事时能查(V7 真机链教训)。
278
+ try {
279
+ const ad = path.join(storeDir, "audit")
280
+ fs.mkdirSync(ad, { recursive: true })
281
+ fs.appendFileSync(path.join(ad, "sink-errors.log"), `${new Date().toISOString()} ${String(e?.message ?? e)}\n`)
282
+ } catch { /* 连痕迹都写不了就只能放弃 */ }
283
+ }
284
+ } : null
285
+ const reviewHandler = storeDir && client
286
+ ? createReviewPipeline({
287
+ client,
288
+ // **后台复习的身份必须登记**:它不是"不明来源",而是我们自己的后台通道。
289
+ // 不登记的话(实测 V7 真机链抓到):它落的每一条都会以 origin=unknown 进待批,
290
+ // 既不会标 [auto](人看不出这是后台提的),也和 Hermes 的语义不符
291
+ // (照 Hermes:后台 add 直写、后台改/删才只提案)。
292
+ store: createMemoryStore({ root: storeDir, identity: { origin: "background", agent: "ocg-background-review" } }),
293
+ audit: reviewAudit,
294
+ // C③:我们自己知道记忆工具注册没注册(= Hermes 的 `"memory" in valid_tool_names` 的等价物);
295
+ // skills 那一半看宿主工具表(拿不到就算未知,交给调度器默认并在决策条目里标出来)。
296
+ toolsAvailable: { memory: toolDef ? true : false },
297
+ })
298
+ : null
299
+ return createAdapter({ store: storeDir, directory: directory ?? process.cwd(), client, toolDef, reviewHandler, binding: bindInfo, queuePath: bindInfo.queuePath })
300
+ }