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 +202 -0
- package/README.md +52 -0
- package/bin/oc-grow.mjs +14 -0
- package/package.json +35 -0
- package/src/adapter-opencode/index.mjs +300 -0
- package/src/adapter-opencode/install.mjs +387 -0
- package/src/adapter-opencode/memory-tool.mjs +170 -0
- package/src/adapter-opencode/review-runner.mjs +369 -0
- package/src/cli/commands.mjs +421 -0
- package/src/cli/envelope.mjs +64 -0
- package/src/cli/main.mjs +245 -0
- package/src/core/audit.mjs +40 -0
- package/src/core/background-review.mjs +261 -0
- package/src/core/budget.mjs +64 -0
- package/src/core/candidate.mjs +96 -0
- package/src/core/home.mjs +61 -0
- package/src/core/identity.mjs +100 -0
- package/src/core/ids.mjs +22 -0
- package/src/core/lock.mjs +107 -0
- package/src/core/memories.mjs +306 -0
- package/src/core/memory-actions.mjs +222 -0
- package/src/core/paths.mjs +81 -0
- package/src/core/retrieve.mjs +127 -0
- package/src/core/review.mjs +238 -0
- package/src/core/skills.mjs +191 -0
- package/src/core/snapshot.mjs +119 -0
- package/src/core/threats.mjs +50 -0
- package/src/core/write-approval.mjs +74 -0
- package/src/core/writer.mjs +168 -0
- package/src/index.mjs +31 -0
- package/src/learn/consume.mjs +152 -0
- package/src/learn/headless.mjs +364 -0
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
// Installing the adapter into an OpenCode host (S6;安装入口在 S7 part B 接上)。
|
|
2
|
+
//
|
|
3
|
+
// The loadable artifact MUST be a `.js` file. That is not a guess: installing the identical
|
|
4
|
+
// plugin as `.mjs` produced no load at all (`module_loaded` never fired, injection silently
|
|
5
|
+
// absent), and renaming the same bytes to `.js` produced the full lifecycle —
|
|
6
|
+
// `module_loaded → factory_called → transform_fired(system len 1→2) → pushed_ok`.
|
|
7
|
+
// A silent no-load is the worst failure mode for a plugin, so the installer writes `.js` and
|
|
8
|
+
// the tests pin it.
|
|
9
|
+
//
|
|
10
|
+
// 这一片补上两件实测出来的事:
|
|
11
|
+
//
|
|
12
|
+
// 1. **宿主依赖要在 shim 里 import**:`zod` 按**文件位置**解析(宿主把它装在
|
|
13
|
+
// `<config>/opencode/node_modules/`)。在仓库 `src/` 里 import 同一个包**会失败**,
|
|
14
|
+
// 而失败的样子是「模型说没有这个工具」——工具静默不存在(S5 探针的教训)。
|
|
15
|
+
// 2. **`skills.paths` 得有人写**:宿主原生支持从任意目录扫技能(实测 `opencode debug skill`
|
|
16
|
+
// 正反例),但那份配置不会自己出现。
|
|
17
|
+
import { resolveInstallStore } from "../core/home.mjs"
|
|
18
|
+
import { homedir } from "node:os"
|
|
19
|
+
|
|
20
|
+
const safeHomedir = () => { try { return homedir() || null } catch { return null } }
|
|
21
|
+
import { createHash } from "node:crypto"
|
|
22
|
+
import fs from "node:fs"
|
|
23
|
+
import path from "node:path"
|
|
24
|
+
import { fileURLToPath } from "node:url"
|
|
25
|
+
|
|
26
|
+
import { hostConfigFor, skillsDir } from "../core/skills.mjs"
|
|
27
|
+
|
|
28
|
+
export const ADAPTER_FILE = "ocg-growth.js"
|
|
29
|
+
|
|
30
|
+
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
|
31
|
+
export const ADAPTER_MODULE = path.join(HERE, "index.mjs")
|
|
32
|
+
|
|
33
|
+
/** 宿主的配置根:`$XDG_CONFIG_HOME`,退回 `$HOME/.config`,Windows 上还有 `%APPDATA%`。 */
|
|
34
|
+
export function defaultConfigDir(env = process.env) {
|
|
35
|
+
const base = env.XDG_CONFIG_HOME || (env.HOME ? path.join(env.HOME, ".config") : env.APPDATA)
|
|
36
|
+
if (!base) throw new Error("找不到配置根:既没有 $XDG_CONFIG_HOME 也没有 $HOME —— 请显式给 --config")
|
|
37
|
+
return base
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* 宿主扫描的插件目录,**官方复数在前**。
|
|
42
|
+
*
|
|
43
|
+
* 依据(源码实测,2026-09-20):`packages/opencode/src/config/plugin.ts:21`
|
|
44
|
+
* `Glob.scan("{plugin,plugins}/*.{ts,js}", { dot: true, symlink: true })`
|
|
45
|
+
* ⇒ 两条目录**都会被扫**(`.ts` 也收、点文件也收、符号链接跟随)。
|
|
46
|
+
* 因此:**只写一条**(官方复数),绝不双写——同名会被加载两次;单数只作兼容探测用。
|
|
47
|
+
* 另据官方文档:全局插件目录是 `~/.config/opencode/plugins/`(复数)。
|
|
48
|
+
*/
|
|
49
|
+
export function pluginDirsFor(configDir) {
|
|
50
|
+
return [path.join(configDir, "opencode", "plugins"), path.join(configDir, "opencode", "plugin")]
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 生成宿主加载的那份 shim 的**文本**(写盘是调用方的事,便于测试与 dry-run)。
|
|
55
|
+
*
|
|
56
|
+
* 为什么包一层而不是裸 re-export:要把宿主的 `zod` 交到适配器手上。
|
|
57
|
+
* 为什么 `zod` 必须在这份文件里 import:解析基线是**文件位置**(见文件头的实测)。
|
|
58
|
+
* 为什么拿不到也不抛:插件在别人进程里崩掉,代价与"少一个能力"完全不对等。
|
|
59
|
+
*/
|
|
60
|
+
export function shimSource({ store = null, queuePath = null, module: mod = ADAPTER_MODULE } = {}) {
|
|
61
|
+
const lines = [
|
|
62
|
+
"// Generated by oc-grow — do not edit.",
|
|
63
|
+
"// 1) 必须叫 .js:实测同样内容的 .mjs 宿主不加载,而且是**静默**的。",
|
|
64
|
+
"// 2) zod 必须在这份文件里 import:宿主依赖按**文件位置**解析,",
|
|
65
|
+
"// 在仓库 src/ 里 import 同一个包会失败 —— 那时记忆工具会静默不存在。",
|
|
66
|
+
`import { OcgGrowth as ocgGrowth } from ${JSON.stringify(mod)}`,
|
|
67
|
+
"",
|
|
68
|
+
]
|
|
69
|
+
if (store) lines.push(`process.env.OCG_STORE ||= ${JSON.stringify(String(store))}`)
|
|
70
|
+
if (queuePath) lines.push(`process.env.OCG_QUEUE ||= ${JSON.stringify(String(queuePath))}`)
|
|
71
|
+
if (store || queuePath) lines.push("")
|
|
72
|
+
lines.push(
|
|
73
|
+
"let z = null",
|
|
74
|
+
"try {",
|
|
75
|
+
' const mod = await import("zod")',
|
|
76
|
+
" z = mod.z ?? mod.default",
|
|
77
|
+
"} catch {",
|
|
78
|
+
" // 拿不到宿主那份 zod 也没关系:适配器会自己去找;再不行就不挂记忆工具,",
|
|
79
|
+
" // 注入与冻结照常(少一个能力,好过整片挂掉)。",
|
|
80
|
+
"}",
|
|
81
|
+
"",
|
|
82
|
+
"export const OcgGrowth = (input) => ocgGrowth({ ...(input ?? {}), z })",
|
|
83
|
+
"",
|
|
84
|
+
)
|
|
85
|
+
return lines.join("\n")
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Write the host-loadable plugin file. Returns what it wrote and where.
|
|
90
|
+
* `pluginDir` is the host's plugin directory (e.g. `<config>/opencode/plugin`).
|
|
91
|
+
*/
|
|
92
|
+
export function installAdapter({ pluginDir, store = null, queuePath = null } = {}) {
|
|
93
|
+
if (!pluginDir) throw new Error("installAdapter needs pluginDir")
|
|
94
|
+
fs.mkdirSync(pluginDir, { recursive: true })
|
|
95
|
+
|
|
96
|
+
const target = path.join(pluginDir, ADAPTER_FILE)
|
|
97
|
+
fs.writeFileSync(target, shimSource({ store, queuePath }))
|
|
98
|
+
return { file: target, module: ADAPTER_MODULE, store: store ?? null, queuePath: queuePath ?? null }
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** 原子写:先写同目录临时文件再 rename —— 半截配置会让宿主起不来。 */
|
|
102
|
+
function atomicWrite(file, text) {
|
|
103
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
104
|
+
const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`
|
|
105
|
+
fs.writeFileSync(tmp, text)
|
|
106
|
+
fs.renameSync(tmp, file)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* 把 `D/skills/` 并进宿主的 `opencode.json`。
|
|
111
|
+
* **坏 JSON 一律报错停下、原样留着**——覆盖它等于把人家的配置删了。
|
|
112
|
+
*/
|
|
113
|
+
export function installSkillsConfig({ configDir, store } = {}) {
|
|
114
|
+
const file = path.join(configDir, "opencode", "opencode.json")
|
|
115
|
+
const existed = fs.existsSync(file)
|
|
116
|
+
let existing = {}
|
|
117
|
+
if (existed) {
|
|
118
|
+
const raw = fs.readFileSync(file, "utf8")
|
|
119
|
+
try {
|
|
120
|
+
existing = JSON.parse(raw)
|
|
121
|
+
} catch (err) {
|
|
122
|
+
throw new Error(`宿主的配置不是合法 JSON,未做任何改动(${file}):${err?.message ?? err}`)
|
|
123
|
+
}
|
|
124
|
+
if (!existing || typeof existing !== "object" || Array.isArray(existing)) {
|
|
125
|
+
throw new Error(`宿主的配置不是对象,未做任何改动(${file})`)
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
const next = hostConfigFor({ root: store, existing })
|
|
129
|
+
atomicWrite(file, JSON.stringify(next, null, 2) + "\n")
|
|
130
|
+
return { file, skillsPath: skillsDir(store), created: !existed }
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** 安装器与 doctor 共用的路径解析(同一规则,避免两处各算各的)。 */
|
|
134
|
+
export function resolveInstallPaths({ store, configDir = null } = {}) {
|
|
135
|
+
const cfgDir = configDir ?? defaultConfigDir()
|
|
136
|
+
const pluginDir = pluginDirsFor(cfgDir)[0] // 官方复数
|
|
137
|
+
return {
|
|
138
|
+
configDir: cfgDir,
|
|
139
|
+
pluginDir,
|
|
140
|
+
shim: path.join(pluginDir, ADAPTER_FILE),
|
|
141
|
+
configFile: path.join(cfgDir, "opencode", "opencode.json"),
|
|
142
|
+
skillsPath: store ? skillsDir(store) : null,
|
|
143
|
+
store: store ?? null,
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** 回执路径:写在我们**自己的** home(D)里,不污染宿主目录(Hermes 的 update receipts 同形)。 */
|
|
148
|
+
export const manifestPath = (store) => path.join(store, "install-manifest.json")
|
|
149
|
+
|
|
150
|
+
export function readManifest(store) {
|
|
151
|
+
const f = manifestPath(store)
|
|
152
|
+
if (!fs.existsSync(f)) return null
|
|
153
|
+
try { return JSON.parse(fs.readFileSync(f, "utf8")) } catch { return null }
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const sha256 = (file) => createHash("sha256").update(fs.readFileSync(file)).digest("hex")
|
|
157
|
+
|
|
158
|
+
export function writeManifest({ store, paths, version, configKeysAdded, storeSource = "explicit" }) {
|
|
159
|
+
const m = {
|
|
160
|
+
tool: "oc-grow",
|
|
161
|
+
version: version ?? null,
|
|
162
|
+
store,
|
|
163
|
+
// 这个 D 是怎么来的:explicit(调用方给了)| env($OCG_HOME)| default(平台默认 home)。
|
|
164
|
+
// 口径见 `docs/PENDING-STAGE4.md` §1;审计时要能一眼看出落点是选的还是默认的。
|
|
165
|
+
storeSource,
|
|
166
|
+
configDir: paths.configDir,
|
|
167
|
+
pluginDir: paths.pluginDir,
|
|
168
|
+
shim: paths.shim,
|
|
169
|
+
shimSha256: fs.existsSync(paths.shim) ? sha256(paths.shim) : null,
|
|
170
|
+
configFile: paths.configFile,
|
|
171
|
+
skillsPath: paths.skillsPath,
|
|
172
|
+
configKeysAdded: configKeysAdded ?? [],
|
|
173
|
+
installedAt: new Date().toISOString(),
|
|
174
|
+
}
|
|
175
|
+
atomicWrite(manifestPath(store), JSON.stringify(m, null, 2) + "\n")
|
|
176
|
+
return m
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* 卸载:**只撤我们写的东西**。
|
|
181
|
+
* · shim:按回执记的路径删(不存在也当成功 ⇒ 幂等)
|
|
182
|
+
* · 配置:**按值匹配**撤掉我们追加的 `skills.paths` 条目;用户其它字段一律不动
|
|
183
|
+
* (若 `skills.paths` 因此为空、且 `skills` 里再无别的键,才连 `skills` 一起撤)
|
|
184
|
+
* · 回执:撤完删除(下次再跑就是"没装过",仍然 exit 0)
|
|
185
|
+
* 不做的事:不碰宿主目录里的其它文件、不删 D 里的记忆(那是数据,要人显式决定)。
|
|
186
|
+
*/
|
|
187
|
+
export function uninstallAll({ store, configDir = null } = {}) {
|
|
188
|
+
if (!store) throw new Error("uninstallAll 需要 store(D 目录)")
|
|
189
|
+
const mf = readManifest(store)
|
|
190
|
+
const paths = resolveInstallPaths({ store, configDir: configDir ?? mf?.configDir ?? null })
|
|
191
|
+
const removed = []
|
|
192
|
+
const notes = []
|
|
193
|
+
|
|
194
|
+
if (fs.existsSync(paths.shim)) { fs.unlinkSync(paths.shim); removed.push(paths.shim) }
|
|
195
|
+
else notes.push(`shim 不存在(已撤过):${paths.shim}`)
|
|
196
|
+
|
|
197
|
+
// 命令面:**按值撤**(只删带我们标记的模板;用户自己的命令一律不动)
|
|
198
|
+
const cmd = removeCommands({ configDir: paths.configDir })
|
|
199
|
+
for (const f of cmd.removed) removed.push(f)
|
|
200
|
+
for (const f of cmd.kept) notes.push(`保留(不是我们写的):${f}`)
|
|
201
|
+
|
|
202
|
+
if (fs.existsSync(paths.configFile)) {
|
|
203
|
+
const raw = fs.readFileSync(paths.configFile, "utf8")
|
|
204
|
+
let cfg
|
|
205
|
+
try { cfg = JSON.parse(raw) } catch (err) {
|
|
206
|
+
throw new Error(`宿主配置不是合法 JSON,未做任何改动(${paths.configFile}):${err?.message ?? err}`)
|
|
207
|
+
}
|
|
208
|
+
const want = paths.skillsPath
|
|
209
|
+
const list = cfg?.skills?.paths
|
|
210
|
+
if (Array.isArray(list) && want && list.includes(want)) {
|
|
211
|
+
const nextList = list.filter((x) => x !== want) // 按值删,只删我们那条
|
|
212
|
+
if (nextList.length) cfg.skills.paths = nextList
|
|
213
|
+
else {
|
|
214
|
+
delete cfg.skills.paths
|
|
215
|
+
if (cfg.skills && Object.keys(cfg.skills).length === 0) delete cfg.skills
|
|
216
|
+
}
|
|
217
|
+
atomicWrite(paths.configFile, JSON.stringify(cfg, null, 2) + "\n")
|
|
218
|
+
removed.push(`${paths.configFile} 里的 skills.paths: ${want}`)
|
|
219
|
+
} else {
|
|
220
|
+
notes.push("配置里没有我们追加的那条 skills path(用户可能已自行改过)⇒ 未动配置")
|
|
221
|
+
}
|
|
222
|
+
} else {
|
|
223
|
+
notes.push(`宿主配置不存在:${paths.configFile}`)
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
if (fs.existsSync(manifestPath(store))) { fs.unlinkSync(manifestPath(store)); removed.push(manifestPath(store)) }
|
|
227
|
+
return { store, ...paths, removed, notes, report: [
|
|
228
|
+
removed.length ? `撤掉了 ${removed.length} 项:` : "没有需要撤的东西(幂等)",
|
|
229
|
+
...removed.map((x) => ` · ${x}`),
|
|
230
|
+
...notes.map((x) => ` - ${x}`),
|
|
231
|
+
"D 里的记忆/快照/待批**没有被删**(那是数据,删不删由你决定)。",
|
|
232
|
+
] }
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* 一次装好:D 的目录、宿主的插件文件、宿主的技能路径。
|
|
237
|
+
* `dryRun` 只报告不落盘(先看它打算干什么)。
|
|
238
|
+
*/
|
|
239
|
+
export function installAll({ store, configDir = null, queuePath = null, dryRun = false } = {}) {
|
|
240
|
+
// **安装器与运行时同一规则**(`docs/PENDING-STAGE4.md` §1,函数在 `src/core/home.mjs`):
|
|
241
|
+
// 调用方没给 store ⇒ 平台默认 home(`$OCG_HOME` 优先)。拿不到唯一根仍然报错(fail closed,不猜)。
|
|
242
|
+
// 注意 CLI(`oc-grow install`)不依赖这条默认:它始终要求 `--store`/`$OCG_STORE`。
|
|
243
|
+
const resolved = store ? { store, source: "explicit" } : resolveInstallStore({ env: process.env, homeDir: safeHomedir() })
|
|
244
|
+
if (!resolved.store) throw new Error("installAll 需要 store(D 目录):既没显式给,也解析不出唯一的数据 home")
|
|
245
|
+
store = resolved.store
|
|
246
|
+
const storeSource = resolved.source
|
|
247
|
+
const paths = resolveInstallPaths({ store, configDir })
|
|
248
|
+
const cfgDir = paths.configDir
|
|
249
|
+
const pluginDir = paths.pluginDir
|
|
250
|
+
const report = []
|
|
251
|
+
|
|
252
|
+
const dirs = ["memories", "snapshots", "pending", "skills"]
|
|
253
|
+
report.push(`D 目录:${store}(${dirs.join(" / ")})`)
|
|
254
|
+
if (!dryRun) for (const d of dirs) fs.mkdirSync(path.join(store, d), { recursive: true })
|
|
255
|
+
|
|
256
|
+
const shim = path.join(pluginDir, ADAPTER_FILE)
|
|
257
|
+
report.push(`插件文件:${shim}(.js —— 实测 .mjs 宿主不加载,且是静默的)`)
|
|
258
|
+
report.push('宿主依赖:shim 里 import "zod"(按文件位置解析);拿不到则退回适配器自查')
|
|
259
|
+
if (!dryRun) installAdapter({ pluginDir, store, queuePath })
|
|
260
|
+
|
|
261
|
+
const cfgFile = path.join(cfgDir, "opencode", "opencode.json")
|
|
262
|
+
report.push(`技能路径:${cfgFile} 的 skills.paths += ${skillsDir(store)}`)
|
|
263
|
+
const cfgOut = dryRun ? null : installSkillsConfig({ configDir: cfgDir, store })
|
|
264
|
+
report.push(`命令面:${commandDirFor(cfgDir)}/ocg-{pending,approve,reject}.md(卸载按值撤;用户自己的命令不动)`)
|
|
265
|
+
if (!dryRun) installCommands({ configDir: cfgDir })
|
|
266
|
+
if (!dryRun) {
|
|
267
|
+
const version = (() => { try { return JSON.parse(fs.readFileSync(path.join(HERE, "..", "..", "package.json"), "utf8")).version } catch { return null } })()
|
|
268
|
+
writeManifest({ store, paths, version, configKeysAdded: ["skills.paths"], storeSource })
|
|
269
|
+
report.push(`回执:${manifestPath(store)}(装了什么、写进哪个键,可机器核对)`)
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
report.push(
|
|
273
|
+
dryRun
|
|
274
|
+
? "dry-run:以上都只是计划,一个字节都没写"
|
|
275
|
+
: "装好了。改配置要**重启宿主**才生效(实测:配置不热重载)。",
|
|
276
|
+
)
|
|
277
|
+
|
|
278
|
+
return {
|
|
279
|
+
store,
|
|
280
|
+
configDir: cfgDir,
|
|
281
|
+
pluginDir,
|
|
282
|
+
shim,
|
|
283
|
+
configFile: cfgFile,
|
|
284
|
+
skillsPath: skillsDir(store),
|
|
285
|
+
created: cfgOut?.created ?? null,
|
|
286
|
+
report,
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
// ── 常驻两库文件的创建规则(用户 2026-09-20 拍板)──────────────────────────────
|
|
292
|
+
// ① 全新 store(无初始化标记)⇒ 缺则建**空文件**(装完即可编辑 ✓)
|
|
293
|
+
// 永久规则:**永不写内容**(常驻层按 § 切条目,任何说明行都会被当成一条记忆 ✗)
|
|
294
|
+
// ② 库已初始化、但文件被删 ⇒ 那是**用户(或别人)的意图** ⇒ **绝不自动重建** ✗,
|
|
295
|
+
// 只在报告面提示,由用户决定 ——「不做处理,按用户意见处理」。
|
|
296
|
+
const STORE_INIT_MARKER = ".ocg-store-initialized"
|
|
297
|
+
export const storeInitMarker = (L) => path.join(L.root, STORE_INIT_MARKER)
|
|
298
|
+
|
|
299
|
+
export function ensureResidentFiles(L) {
|
|
300
|
+
const dir = path.join(L.root, "memories")
|
|
301
|
+
// 「已初始化」= 有标记 **或** 已经有任何一个库文件 —— 后者意味着这是别人/用户自己建过的库,
|
|
302
|
+
// 此时**只补建缺失的另一个也不做** ✗:只用一个库(例如只用 MEMORY.md)是合法意图 ✓。
|
|
303
|
+
const initialized = fs.existsSync(storeInitMarker(L))
|
|
304
|
+
|| ["MEMORY.md", "USER.md"].some((n) => fs.existsSync(path.join(dir, n)))
|
|
305
|
+
const created = []
|
|
306
|
+
const kept = []
|
|
307
|
+
const missing = []
|
|
308
|
+
|
|
309
|
+
for (const name of ["MEMORY.md", "USER.md"]) {
|
|
310
|
+
const file = path.join(dir, name)
|
|
311
|
+
if (fs.existsSync(file)) {
|
|
312
|
+
kept.push(name)
|
|
313
|
+
} else if (!initialized) {
|
|
314
|
+
fs.mkdirSync(dir, { recursive: true })
|
|
315
|
+
fs.writeFileSync(file, "")
|
|
316
|
+
created.push(name)
|
|
317
|
+
} else {
|
|
318
|
+
missing.push(name) // 用户删过 ⇒ 尊重意图,不重建
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
if (!initialized) fs.writeFileSync(storeInitMarker(L), "first-install\n")
|
|
323
|
+
return { created, kept, missing, initialized }
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
// ── 命令面(subgoal②「待批三件齐全」之一) ────────────────────────────────────
|
|
327
|
+
//
|
|
328
|
+
// 宿主原生支持从配置目录加载命令(源码 `packages/opencode/src/config/config.ts:473`
|
|
329
|
+
// `ConfigCommand.load(dir)`)。我们**不新造实体**:把 Hermes 的
|
|
330
|
+
// `/memory pending|approve|reject` 对到这层,安装时写模板、卸载时**按值撤**。
|
|
331
|
+
//
|
|
332
|
+
// 「按值撤」=每个模板首行是我们的标记,卸载只删**带这个标记**的文件,
|
|
333
|
+
// 用户自己写的命令一个字节都不动(与 skills.paths 的按值撤同一口径)。
|
|
334
|
+
export const COMMAND_MARKER = "<!-- ocg-growth command -->"
|
|
335
|
+
|
|
336
|
+
/** 宿主命令目录:`<configDir>/opencode/command/`。 */
|
|
337
|
+
export function commandDirFor(configDir) {
|
|
338
|
+
if (!configDir) throw new Error("commandDirFor 需要 configDir")
|
|
339
|
+
return path.join(configDir, "opencode", "command")
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** 三条命令模板:列 / 批 / 拒。正文不使用反引号(避免外层模板字符串冲突)。 */
|
|
343
|
+
export function commandTemplates() {
|
|
344
|
+
const mk = (desc, body) => [COMMAND_MARKER, "---", "description: " + desc, "---", "", body, ""].join("\n")
|
|
345
|
+
return {
|
|
346
|
+
"ocg-pending.md": mk(
|
|
347
|
+
"列出 opencode-growth 的待批记忆提案",
|
|
348
|
+
"请调用 memory 工具(action=pending)列出当前待批提案,并逐条说明来源([auto] = 后台复习提出)。不要自行批准或拒绝。",
|
|
349
|
+
),
|
|
350
|
+
"ocg-approve.md": mk(
|
|
351
|
+
"批准一条待批记忆提案(需要参数)",
|
|
352
|
+
"批准待批提案 $ARGUMENTS:在终端运行 oc-grow memory approve $ARGUMENTS(批准有副作用,只走命令行,不由模型执行)。",
|
|
353
|
+
),
|
|
354
|
+
"ocg-reject.md": mk(
|
|
355
|
+
"拒绝一条待批记忆提案(需要参数)",
|
|
356
|
+
"拒绝待批提案 $ARGUMENTS:删掉对应的 D/pending/<file> 即可(删除即拒绝)。",
|
|
357
|
+
),
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/** 写命令模板,返回真正写入的路径。 */
|
|
362
|
+
export function installCommands({ configDir } = {}) {
|
|
363
|
+
const dir = commandDirFor(configDir)
|
|
364
|
+
fs.mkdirSync(dir, { recursive: true })
|
|
365
|
+
const written = []
|
|
366
|
+
for (const [name, body] of Object.entries(commandTemplates())) {
|
|
367
|
+
const f = path.join(dir, name)
|
|
368
|
+
atomicWrite(f, body)
|
|
369
|
+
written.push(f)
|
|
370
|
+
}
|
|
371
|
+
return { dir, written }
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** 卸载命令:按值撤(只删带标记的),返回 removed / kept。 */
|
|
375
|
+
export function removeCommands({ configDir } = {}) {
|
|
376
|
+
const dir = commandDirFor(configDir)
|
|
377
|
+
const removed = []
|
|
378
|
+
const kept = []
|
|
379
|
+
if (!fs.existsSync(dir)) return { dir, removed, kept }
|
|
380
|
+
for (const name of fs.readdirSync(dir)) {
|
|
381
|
+
const f = path.join(dir, name)
|
|
382
|
+
let text = ""
|
|
383
|
+
try { text = fs.readFileSync(f, "utf8") } catch { kept.push(f); continue }
|
|
384
|
+
if (text.startsWith(COMMAND_MARKER)) { fs.rmSync(f); removed.push(f) } else kept.push(f)
|
|
385
|
+
}
|
|
386
|
+
return { dir, removed, kept }
|
|
387
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
// 记忆工具的**定义**(M1-S5)。
|
|
2
|
+
//
|
|
3
|
+
// 这里只负责把动作层包成宿主认的形状;**宿主的 `tool` / `z` 是注入进来的**,
|
|
4
|
+
// 不是 import 来的。两个原因:
|
|
5
|
+
// 1. 单测里不需要真 zod(拿结构断言就够:动作是枚举、**没有 origin 这个字段**);
|
|
6
|
+
// 2. 宿主依赖只在真的要注册时解析——模块本身仍能被普通 node 直接 import。
|
|
7
|
+
//
|
|
8
|
+
// 实测(隔离环境 + 本地插件文件):
|
|
9
|
+
// · 从**插件文件**里 `import "zod"` 成功、`import "@opencode-ai/plugin"` 也成功——
|
|
10
|
+
// 但后者**不需要**:源码里 `tool()` 就是 `(input) => input`。少一条依赖少一处会断的地方。
|
|
11
|
+
// · zod 由宿主装在 `<XDG_CONFIG_HOME>/opencode/node_modules/`,即插件目录的上一级。
|
|
12
|
+
// 从仓库 `src/` 里做同一个 import **会失败**——同一进程、不同解析基线。
|
|
13
|
+
// (这是真实宿主探针抓出来的:工具静默没挂上,而 fail-soft 让整件事看起来"正常"。)
|
|
14
|
+
import fs from "node:fs"
|
|
15
|
+
import path from "node:path"
|
|
16
|
+
import { pathToFileURL } from "node:url"
|
|
17
|
+
|
|
18
|
+
import { MEMORY_ACTIONS, identityFor, runMemoryAction } from "../core/memory-actions.mjs"
|
|
19
|
+
|
|
20
|
+
/** 宿主的 `tool()` 实测就是恒等函数(`packages/plugin/src/tool.ts`:`return input`)。 */
|
|
21
|
+
const identityTool = (def) => def
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* 无人值守的 agent 名单。**部署者配置的东西,不是模型能碰的**——
|
|
25
|
+
* 它就是 extra#4 说的"由启动器与插件登记的会话身份"。
|
|
26
|
+
*/
|
|
27
|
+
export const DEFAULT_BACKGROUND_AGENTS = ["ocg-learn"]
|
|
28
|
+
|
|
29
|
+
export const MEMORY_TOOL_DESCRIPTION = [
|
|
30
|
+
"读取与维护跨项目长期记忆(两个库:memory=事实与偏好,user=用户画像)。",
|
|
31
|
+
"add:追加一条;update:按内容子串**唯一命中**地改写;remove:按内容子串**唯一命中**地删除;",
|
|
32
|
+
"list:查看当前内容与用量;pending:查看待批提案。",
|
|
33
|
+
"注意:改/删在对话里会先请你确认;无人值守的会话里只会排进待批,不会直接生效。",
|
|
34
|
+
].join("")
|
|
35
|
+
|
|
36
|
+
/** 把动作结果渲染成一段模型和人都读得懂的话。 */
|
|
37
|
+
export function renderResult(r) {
|
|
38
|
+
if (!r || typeof r !== "object") return "记忆操作没有返回结果。"
|
|
39
|
+
if (r.ok === false) return `记忆操作未完成:${r.error ?? r.reason ?? "未知原因"}`
|
|
40
|
+
if (r.staged) return `已排入待批(${r.action}):${r.file}。它在有人确认前不会生效。`
|
|
41
|
+
switch (r.action) {
|
|
42
|
+
case "list": {
|
|
43
|
+
const k = r.kinds?.[r.kind] ?? {}
|
|
44
|
+
return [
|
|
45
|
+
`【${r.kind}】${r.entries.length} 条 · ${k.used ?? "?"}/${k.limit ?? "?"} 字符${k.overLimit ? "(已超限,仅警告,未丢弃)" : ""}`,
|
|
46
|
+
...r.entries.map((e, i) => `${i + 1}. ${e}`),
|
|
47
|
+
].join("\n")
|
|
48
|
+
}
|
|
49
|
+
case "pending":
|
|
50
|
+
if (!r.pending.length) return "没有待批提案。"
|
|
51
|
+
return ["待批提案:", ...r.pending.map((p, i) => `${i + 1}. [${p.origin}] ${p.op} ${p.kind}${p.match ? ` match=${p.match}` : ""}${p.text ? ` text=${p.text}` : ""}`)].join("\n")
|
|
52
|
+
case "add":
|
|
53
|
+
return `已记下(第 ${r.entries} 条)· 当前 ${r.used}/${r.limit} 字符`
|
|
54
|
+
default:
|
|
55
|
+
return `已完成 ${r.action} · 当前 ${r.entries} 条`
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* 造一个宿主认的工具定义。`tool`/`z` 由调用方给(插件里是真货,单测里是替身)。
|
|
61
|
+
*/
|
|
62
|
+
export function buildMemoryTool({
|
|
63
|
+
tool,
|
|
64
|
+
z,
|
|
65
|
+
root,
|
|
66
|
+
backgroundAgents = DEFAULT_BACKGROUND_AGENTS,
|
|
67
|
+
foregroundAgents = (process.env.OCG_FOREGROUND_AGENTS ?? "").split(",").map((x) => x.trim()).filter(Boolean),
|
|
68
|
+
// **部署方的声明**:这个会话面真的有人能回答确认框吗?
|
|
69
|
+
// 实测无头 `run` 里 `ctx.ask` 会立刻返回(没人看过),所以「有 ask」不能当证据。
|
|
70
|
+
interactive = process.env.OCG_INTERACTIVE === "1",
|
|
71
|
+
} = {}) {
|
|
72
|
+
if (typeof tool !== "function") throw new Error("buildMemoryTool 需要宿主给的 tool 工厂")
|
|
73
|
+
if (!z?.enum || !z?.string) throw new Error("buildMemoryTool 需要宿主给的 z")
|
|
74
|
+
if (!root) throw new Error("buildMemoryTool 需要 root(D 目录)")
|
|
75
|
+
|
|
76
|
+
return tool({
|
|
77
|
+
description: MEMORY_TOOL_DESCRIPTION,
|
|
78
|
+
args: {
|
|
79
|
+
action: z.enum(MEMORY_ACTIONS).describe("要做什么"),
|
|
80
|
+
kind: z.enum(["memory", "user"]).optional().describe("哪个库,默认 memory"),
|
|
81
|
+
text: z.string().optional().describe("add/update 的正文"),
|
|
82
|
+
match: z.string().optional().describe("update/remove 的内容子串(必须唯一命中)"),
|
|
83
|
+
// 注意这里**没有** origin / agent / sessionID:
|
|
84
|
+
// 身份由宿主给的 ctx 与部署者的名单决定,模型无从申报(extra#4)。
|
|
85
|
+
},
|
|
86
|
+
async execute(args, ctx) {
|
|
87
|
+
// agent 来自宿主的 ToolContext(会话自己的 agent),不是参数;模型改不了它。
|
|
88
|
+
const ask = typeof ctx?.ask === "function" ? (input) => ctx.ask(input) : null
|
|
89
|
+
const identity = identityFor({
|
|
90
|
+
agent: ctx?.agent ?? null,
|
|
91
|
+
hasAsk: Boolean(ask),
|
|
92
|
+
interactive,
|
|
93
|
+
backgroundAgents,
|
|
94
|
+
foregroundAgents,
|
|
95
|
+
})
|
|
96
|
+
const r = await runMemoryAction({
|
|
97
|
+
root,
|
|
98
|
+
identity,
|
|
99
|
+
action: args?.action,
|
|
100
|
+
kind: args?.kind ?? "memory",
|
|
101
|
+
text: args?.text,
|
|
102
|
+
match: args?.match,
|
|
103
|
+
ask,
|
|
104
|
+
})
|
|
105
|
+
return {
|
|
106
|
+
title: r.ok === false ? "记忆操作未完成" : r.staged ? "已排入待批" : "记忆已更新",
|
|
107
|
+
output: renderResult(r),
|
|
108
|
+
metadata: { ok: r.ok !== false, staged: Boolean(r.staged), action: r.action ?? null, origin: r.origin ?? null },
|
|
109
|
+
}
|
|
110
|
+
},
|
|
111
|
+
})
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* 在插件里注册:**动态** import 宿主依赖,失败了不炸掉整个插件
|
|
116
|
+
* (拿不到工具只是少一个能力,不该让注入/冻结一起挂掉)。
|
|
117
|
+
*
|
|
118
|
+
* 两个实测事实决定了这段的形状:
|
|
119
|
+
*
|
|
120
|
+
* 1. **`@opencode-ai/plugin` 的 `tool()` 就是个恒等函数**(源码 `tool.ts`:`return input`)。
|
|
121
|
+
* 所以根本不需要 import 它——不 import 就少一条会断的依赖。宿主真正要的是
|
|
122
|
+
* `{description, args(zod), execute}` 这个形状。
|
|
123
|
+
* 2. **`zod` 由宿主装在 `<XDG_CONFIG_HOME>/opencode/node_modules/`**,也就是**插件目录的上一级**。
|
|
124
|
+
* 从插件文件里 `import("zod")` 能成,从仓库的 `src/` 里**不能**——同一个进程、不同的解析基线。
|
|
125
|
+
* 所以这里先试原地 import,失败就**显式去找宿主装的那份**(按几个已知的配置根)。
|
|
126
|
+
*/
|
|
127
|
+
async function loadZod() {
|
|
128
|
+
try {
|
|
129
|
+
const m = await import("zod")
|
|
130
|
+
const z = m?.z ?? m?.default?.z ?? m?.default
|
|
131
|
+
if (typeof z?.object === "function") return z
|
|
132
|
+
} catch {
|
|
133
|
+
/* 解析基线不对,往下走 */
|
|
134
|
+
}
|
|
135
|
+
const roots = [
|
|
136
|
+
process.env.XDG_CONFIG_HOME,
|
|
137
|
+
process.env.APPDATA,
|
|
138
|
+
process.env.HOME ? path.join(process.env.HOME, ".config") : null,
|
|
139
|
+
].filter(Boolean)
|
|
140
|
+
for (const root of roots) {
|
|
141
|
+
for (const rel of ["opencode/node_modules/zod/index.cjs", "opencode/node_modules/zod/index.js"]) {
|
|
142
|
+
const p = path.join(root, rel)
|
|
143
|
+
try {
|
|
144
|
+
if (!fs.existsSync(p)) continue
|
|
145
|
+
const m = await import(pathToFileURL(p).href)
|
|
146
|
+
const z = m?.z ?? m?.default?.z ?? m?.default
|
|
147
|
+
if (typeof z?.object === "function") return z
|
|
148
|
+
} catch {
|
|
149
|
+
/* 换下一个 */
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return null
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export async function registerMemoryTool({ root, z = null, tool = null, backgroundAgents = DEFAULT_BACKGROUND_AGENTS, foregroundAgents = undefined, interactive = undefined } = {}) {
|
|
157
|
+
try {
|
|
158
|
+
const resolvedZ = z ?? (await loadZod())
|
|
159
|
+
if (!resolvedZ) return { __error: "记忆工具未能注册:拿不到宿主的 zod(会在插件目录或宿主配置根里找)" }
|
|
160
|
+
// C①:**绑定时刻的值**优先(由插件工厂传给我们的那份),拿不到才回退读环境——
|
|
161
|
+
// 免得"进程里后来有人改了环境变量"把已经建好的实例行为改掉(多配置根串用类问题的根)。
|
|
162
|
+
return buildMemoryTool({
|
|
163
|
+
tool: tool ?? identityTool, z: resolvedZ, root, backgroundAgents,
|
|
164
|
+
...(foregroundAgents !== undefined ? { foregroundAgents } : {}),
|
|
165
|
+
...(interactive !== undefined ? { interactive } : {}),
|
|
166
|
+
})
|
|
167
|
+
} catch (err) {
|
|
168
|
+
return { __error: `记忆工具未能注册:${err?.message ?? err}` }
|
|
169
|
+
}
|
|
170
|
+
}
|