opencode-growth 0.1.2 → 0.1.74

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.
Files changed (48) hide show
  1. package/README.md +72 -13
  2. package/package.json +1 -1
  3. package/src/adapter-opencode/curator-runner.mjs +257 -0
  4. package/src/adapter-opencode/index.mjs +309 -19
  5. package/src/adapter-opencode/install.mjs +329 -52
  6. package/src/adapter-opencode/journey-tool.mjs +57 -0
  7. package/src/adapter-opencode/memory-tool.mjs +57 -5
  8. package/src/adapter-opencode/provider-tools.mjs +237 -0
  9. package/src/adapter-opencode/review-runner.mjs +180 -37
  10. package/src/adapter-opencode/session-search-tool.mjs +66 -0
  11. package/src/adapter-opencode/skill-tool.mjs +221 -0
  12. package/src/cli/commands.mjs +98 -5
  13. package/src/cli/curator-cmd.mjs +149 -0
  14. package/src/cli/journey-cmd.mjs +61 -0
  15. package/src/cli/journey-view.mjs +174 -0
  16. package/src/cli/main.mjs +173 -26
  17. package/src/cli/memory-cmd.mjs +165 -0
  18. package/src/cli/session-index-cmd.mjs +87 -0
  19. package/src/cli/skill-cmd.mjs +194 -0
  20. package/src/core/approve.mjs +295 -0
  21. package/src/core/audit.mjs +51 -0
  22. package/src/core/background-review.mjs +114 -2
  23. package/src/core/home.mjs +56 -21
  24. package/src/core/journey.mjs +298 -0
  25. package/src/core/lock.mjs +6 -0
  26. package/src/core/memories.mjs +215 -10
  27. package/src/core/memory-actions.mjs +73 -18
  28. package/src/core/paths.mjs +0 -1
  29. package/src/core/session-freshness.mjs +201 -0
  30. package/src/core/session-index.mjs +508 -0
  31. package/src/core/session-query.mjs +161 -0
  32. package/src/core/session-source.mjs +209 -0
  33. package/src/core/session-tool.mjs +189 -0
  34. package/src/core/skill-actions.mjs +391 -0
  35. package/src/core/skill-backup.mjs +95 -0
  36. package/src/core/skill-lifecycle.mjs +277 -0
  37. package/src/core/skill-usage.mjs +119 -0
  38. package/src/core/skills.mjs +30 -3
  39. package/src/core/sqlite-runtime.mjs +35 -0
  40. package/src/core/write-approval.mjs +13 -9
  41. package/src/host/rest-client.mjs +70 -0
  42. package/src/index.mjs +0 -1
  43. package/src/provider/config.mjs +187 -0
  44. package/src/provider/openviking-rest.mjs +742 -0
  45. package/src/provider/runtime.mjs +417 -0
  46. package/src/provider/wiring.mjs +164 -0
  47. package/src/core/budget.mjs +0 -64
  48. package/src/core/retrieve.mjs +0 -127
@@ -14,7 +14,7 @@
14
14
  // 而失败的样子是「模型说没有这个工具」——工具静默不存在(S5 探针的教训)。
15
15
  // 2. **`skills.paths` 得有人写**:宿主原生支持从任意目录扫技能(实测 `opencode debug skill`
16
16
  // 正反例),但那份配置不会自己出现。
17
- import { resolveInstallStore } from "../core/home.mjs"
17
+ import { resolveStoreRoot } from "../core/home.mjs"
18
18
  import { homedir } from "node:os"
19
19
 
20
20
  const safeHomedir = () => { try { return homedir() || null } catch { return null } }
@@ -24,6 +24,11 @@ import path from "node:path"
24
24
  import { fileURLToPath } from "node:url"
25
25
 
26
26
  import { hostConfigFor, skillsDir } from "../core/skills.mjs"
27
+ import { WRITE_PERMISSION_NAME, layout } from "../core/paths.mjs"
28
+
29
+ // 回执语义版本:2 = 回执即归属账本(命令逐文件哈希、permission 键也在册)。
30
+ // 没有这个字段的旧回执一律视为「声明未经证明」——宁可留残留,也不按它的声明撤用户的东西。
31
+ export const OWNERSHIP_VERSION = 2
27
32
 
28
33
  export const ADAPTER_FILE = "ocg-growth.js"
29
34
 
@@ -110,7 +115,7 @@ function atomicWrite(file, text) {
110
115
  * 把 `D/skills/` 并进宿主的 `opencode.json`。
111
116
  * **坏 JSON 一律报错停下、原样留着**——覆盖它等于把人家的配置删了。
112
117
  */
113
- export function installSkillsConfig({ configDir, store } = {}) {
118
+ export function installSkillsConfig({ configDir, store, dryRun = false } = {}) {
114
119
  const file = path.join(configDir, "opencode", "opencode.json")
115
120
  const existed = fs.existsSync(file)
116
121
  let existing = {}
@@ -122,12 +127,31 @@ export function installSkillsConfig({ configDir, store } = {}) {
122
127
  throw new Error(`宿主的配置不是合法 JSON,未做任何改动(${file}):${err?.message ?? err}`)
123
128
  }
124
129
  if (!existing || typeof existing !== "object" || Array.isArray(existing)) {
125
- throw new Error(`宿主的配置不是对象,未做任何改动(${file})`)
130
+ throw new Error(`宿主的配置必须是 JSON 对象,未做任何改动(${file})`)
126
131
  }
127
132
  }
133
+ const skillsPath = skillsDir(store)
134
+ // 宿主 skills 与 permission 同一族:存在但既不是对象也不是字符串数组时,合并分支
135
+ // (core/skills.mjs:99-109 只兼容对象与旧版数组形态)会把用户写的原值整棵换成
136
+ // `{paths:[D/skills]}`。那条路径静默且不可恢复 ⇒ 与 permission 一样先拒绝、零写入。
137
+ const rawSkills = existing?.skills
138
+ if (rawSkills !== undefined && !(Array.isArray(rawSkills) || (rawSkills && typeof rawSkills === "object"))) {
139
+ throw new Error(`宿主 skills 必须是 JSON 对象或字符串数组,已保留原配置且未做任何改动(${file})`)
140
+ }
141
+ const previousPaths = Array.isArray(existing?.skills) ? existing.skills : existing?.skills?.paths
142
+ // 回执要说的不是「我们通常会写什么」,而是**这一次真的新增了什么**:
143
+ // 预存同值不算新增;permission 键预存(哪怕值是 allow/deny)也不算我们的。
144
+ const rawPerm = existing?.permission
145
+ const permWritable = rawPerm && typeof rawPerm === "object" && !Array.isArray(rawPerm)
146
+ if (rawPerm !== undefined && !permWritable) {
147
+ throw new Error(`宿主 permission 必须是 JSON 对象,已保留原配置且未做任何改动(${file})`)
148
+ }
149
+ const configKeysAdded = []
150
+ if (!(Array.isArray(previousPaths) && previousPaths.includes(skillsPath))) configKeysAdded.push("skills.paths")
151
+ if (!(permWritable && rawPerm[WRITE_PERMISSION_NAME] !== undefined)) configKeysAdded.push(`permission.${WRITE_PERMISSION_NAME}`)
128
152
  const next = hostConfigFor({ root: store, existing })
129
- atomicWrite(file, JSON.stringify(next, null, 2) + "\n")
130
- return { file, skillsPath: skillsDir(store), created: !existed }
153
+ if (!dryRun) atomicWrite(file, JSON.stringify(next, null, 2) + "\n")
154
+ return { file, skillsPath, configKeysAdded, created: dryRun ? null : !existed, wouldCreate: !existed }
131
155
  }
132
156
 
133
157
  /** 安装器与 doctor 共用的路径解析(同一规则,避免两处各算各的)。 */
@@ -155,14 +179,19 @@ export function readManifest(store) {
155
179
 
156
180
  const sha256 = (file) => createHash("sha256").update(fs.readFileSync(file)).digest("hex")
157
181
 
158
- export function writeManifest({ store, paths, version, configKeysAdded, storeSource = "explicit" }) {
182
+ export function writeManifest({ store, paths, version, configKeysAdded, commands = {}, pendingRemoval = [], storeSource = "explicit", storeVia = null, storeConflicts = [] }) {
159
183
  const m = {
160
184
  tool: "oc-grow",
161
185
  version: version ?? null,
186
+ ownershipVersion: OWNERSHIP_VERSION,
162
187
  store,
163
- // 这个 D 是怎么来的:explicit(调用方给了)| env($OCG_HOME)| default(平台默认 home)。
164
- // 口径见 `docs/PENDING-STAGE4.md` §1;审计时要能一眼看出落点是选的还是默认的。
188
+ // 这个 D 是怎么来的:explicit(调用方给了)| env($OCG_STORE / $OCG_HOME)| default(平台默认 home)。
189
+ // 口径见 `docs/PENDING-STAGE4.md` §1 + `src/core/home.mjs::resolveStoreRoot`(三入口同一条规则);
190
+ // `storeVia` 进一步点名**是哪个变量**,`storeConflicts` 是被压过、且指向别的路径的候选
191
+ // (审计时要能一眼看出:落点是选的还是默认的,以及有没有人配了另一个库却被压过去)。
165
192
  storeSource,
193
+ storeVia,
194
+ storeConflicts,
166
195
  configDir: paths.configDir,
167
196
  pluginDir: paths.pluginDir,
168
197
  shim: paths.shim,
@@ -170,12 +199,79 @@ export function writeManifest({ store, paths, version, configKeysAdded, storeSou
170
199
  configFile: paths.configFile,
171
200
  skillsPath: paths.skillsPath,
172
201
  configKeysAdded: configKeysAdded ?? [],
202
+ // 命令面同一个口径:记下**实际写进去的那份内容**的哈希,才能只撤自己写的那些。
203
+ commands: commands ?? {},
204
+ // 半卸:这一轮该撤、但因为内容已变(或读不到)而保留的东西。留着回执,第二次才还认得。
205
+ pendingRemoval: pendingRemoval ?? [],
173
206
  installedAt: new Date().toISOString(),
174
207
  }
175
208
  atomicWrite(manifestPath(store), JSON.stringify(m, null, 2) + "\n")
176
209
  return m
177
210
  }
178
211
 
212
+ // Compare physical destinations, including missing leaves beneath an existing real parent.
213
+ // Only ENOENT is a missing leaf; permission/I/O failures never become an equality claim.
214
+ function physicalPath(value) {
215
+ if (typeof value !== "string" || !value) return null
216
+ let current = path.resolve(value)
217
+ const tail = []
218
+ for (;;) {
219
+ try { return path.join(fs.realpathSync(current), ...tail.reverse()) }
220
+ catch (err) {
221
+ if (err?.code !== "ENOENT") return null
222
+ const parent = path.dirname(current)
223
+ if (parent === current) return null
224
+ tail.push(path.basename(current))
225
+ current = parent
226
+ }
227
+ }
228
+ }
229
+ function samePath(a, b) {
230
+ const left = physicalPath(a), right = physicalPath(b)
231
+ return left !== null && right !== null && left === right
232
+ }
233
+
234
+ // A receipt owns these exact destinations, not every matching name on another host.
235
+ function manifestMatches(mf, store, paths) {
236
+ return mf?.tool === "oc-grow" && Object.entries({ store, configDir: paths.configDir, shim: paths.shim,
237
+ configFile: paths.configFile, skillsPath: paths.skillsPath }).every(([key, value]) => samePath(mf[key], value))
238
+ }
239
+
240
+ // Explicit recovery is stricter than the legacy no-receipt/no-op path. It cannot guess,
241
+ // fall back, retarget a host, or borrow another live store's receipt.
242
+ function readRecoveryReceipt(file, store, configDir) {
243
+ let mf
244
+ try { mf = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(fs.readFileSync(file))) }
245
+ catch (err) { throw new Error(`显式回执缺失、不可读或不是合法 JSON,未做任何改动(${file}):${err.message}`) }
246
+ const object = value => value !== null && typeof value === "object" && !Array.isArray(value)
247
+ const hash = value => typeof value === "string" && /^[a-f0-9]{64}$/.test(value)
248
+ const keys = ["skills.paths", `permission.${WRITE_PERMISSION_NAME}`]
249
+ const fields = ["store", "configDir", "pluginDir", "shim", "configFile", "skillsPath"]
250
+ if (!object(mf) || mf.tool !== "oc-grow" || mf.ownershipVersion !== OWNERSHIP_VERSION
251
+ || !fields.every(key => typeof mf[key] === "string" && path.isAbsolute(mf[key]) && path.resolve(mf[key]) === mf[key])
252
+ || !(mf.shimSha256 === null || hash(mf.shimSha256))
253
+ || !object(mf.commands) || !Object.entries(mf.commands).every(([name, digest]) => Object.hasOwn(commandTemplates(), name) && hash(digest))
254
+ || !Array.isArray(mf.configKeysAdded) || !mf.configKeysAdded.every(key => keys.includes(key))) {
255
+ throw new Error(`显式回执的工具、归属版本、路径或哈希清单不受支持,未做任何改动(${file})`)
256
+ }
257
+ const expected = resolveInstallPaths({ store: mf.store, configDir: mf.configDir })
258
+ if (!fields.every(key => samePath(mf[key], expected[key]))) {
259
+ throw new Error(`显式回执的目标路径越过登记落点,未做任何改动(${file})`)
260
+ }
261
+ if (configDir !== null && !samePath(configDir, mf.configDir)) {
262
+ throw new Error(`显式回执登记的配置根与 --config 不同,未做任何改动(${file}):${mf.configDir}`)
263
+ }
264
+ if (!samePath(store, mf.store)) {
265
+ let oldMissing = false
266
+ try { fs.lstatSync(mf.store) } catch (err) { oldMissing = err?.code === "ENOENT" }
267
+ const movedReceipt = path.basename(file) === "install-manifest.json" && samePath(file, manifestPath(store))
268
+ if (!oldMissing || !movedReceipt) {
269
+ throw new Error(`显式回执不属于本 store;迁址恢复仅接受旧 store 已不存在且位于新 store 内的原 install-manifest.json,未做任何改动(${file})`)
270
+ }
271
+ }
272
+ return mf
273
+ }
274
+
179
275
  /**
180
276
  * 卸载:**只撤我们写的东西**。
181
277
  * · shim:按回执记的路径删(不存在也当成功 ⇒ 幂等)
@@ -184,52 +280,123 @@ export function writeManifest({ store, paths, version, configKeysAdded, storeSou
184
280
  * · 回执:撤完删除(下次再跑就是"没装过",仍然 exit 0)
185
281
  * 不做的事:不碰宿主目录里的其它文件、不删 D 里的记忆(那是数据,要人显式决定)。
186
282
  */
187
- export function uninstallAll({ store, configDir = null } = {}) {
283
+ export function uninstallAll({ store, configDir = null, from = null } = {}) {
188
284
  if (!store) throw new Error("uninstallAll 需要 store(D 目录)")
189
- const mf = readManifest(store)
190
- const paths = resolveInstallPaths({ store, configDir: configDir ?? mf?.configDir ?? null })
285
+ if (from !== null && (typeof from !== "string" || !from.trim())) throw new Error("--from 需要一份明确的回执文件")
286
+ const receiptFile = from === null ? manifestPath(store) : path.resolve(from)
287
+ const mf = from === null ? readManifest(store) : readRecoveryReceipt(receiptFile, store, configDir)
288
+ const registered = from !== null || (mf?.tool === "oc-grow" && samePath(mf.store, store) && typeof mf.configDir === "string")
289
+ const paths = resolveInstallPaths({ store: from === null ? store : mf.store, configDir: configDir ?? (registered ? mf.configDir : null) })
191
290
  const removed = []
192
291
  const notes = []
292
+ const retained = []
293
+ const finish = () => ({ ...paths, store, receiptFile, registeredStore: registered ? mf.store : null, removed, notes, retained, report: [
294
+ retained.length
295
+ ? (removed.length ? `撤掉了 ${removed.length} 项,另有 ${retained.length} 项保留(内容已变或读不到,不撤):`
296
+ : `归属已登记,${retained.length} 项保留(内容已变或读不到,不撤):`)
297
+ : removed.length ? `撤掉了 ${removed.length} 项:`
298
+ : "没有需要撤的东西(幂等)",
299
+ ...removed.map((x) => ` · ${x}`),
300
+ ...retained.map((x) => ` ! ${x}`),
301
+ ...notes.map((x) => ` - ${x}`),
302
+ "D 里的记忆/快照/待批**没有被删**(那是数据,删不删由你决定)。",
303
+ ] })
304
+ if (!registered) {
305
+ notes.push("没有本 store 的有效安装回执,归属未登记 ⇒ 全部保留")
306
+ return finish()
307
+ }
308
+ const versioned = Number(mf.ownershipVersion) >= OWNERSHIP_VERSION
309
+ if (!manifestMatches(mf, from === null ? store : mf.store, paths)) {
310
+ // 逃生口:把回执记的落点原样印出来,人可以直接照它处理,而不是猜我们写在哪儿。
311
+ throw new Error("安装登记回执与本次配置根或目标路径不一致,未做任何改动"
312
+ + `(回执记:configDir=${mf.configDir ?? "?"} shim=${mf.shim ?? "?"} configFile=${mf.configFile ?? "?"} skillsPath=${mf.skillsPath ?? "?"})`)
313
+ }
193
314
 
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}`)
315
+ // Physical aliases establish identity; removal still uses the original recorded string.
316
+ paths.skillsPath = mf.skillsPath
317
+ notes.push(`回执来源:${receiptFile}(原登记 store:${mf.store};只撤原登记落点)`)
201
318
 
319
+ // Validate the complete host config before deleting even the first owned file.
320
+ let cfg = null
202
321
  if (fs.existsSync(paths.configFile)) {
203
322
  const raw = fs.readFileSync(paths.configFile, "utf8")
204
- let cfg
205
323
  try { cfg = JSON.parse(raw) } catch (err) {
206
324
  throw new Error(`宿主配置不是合法 JSON,未做任何改动(${paths.configFile}):${err?.message ?? err}`)
207
325
  }
326
+ if (!cfg || typeof cfg !== "object" || Array.isArray(cfg)) throw new Error("宿主配置必须是 JSON 对象,未做任何改动")
327
+ }
328
+
329
+ // 权限键的撤回必须与「这次真的删掉了 shim」同源判定:半卸或读不到时 shim 仍会被宿主加载,
330
+ // 此时撤掉它的确认规则,等于给仍在运行的写入路径静默摘闸。只有三种形态是「这次不存在了」:
331
+ // 本次删除、本来就不存在、从未写入(旧回执的 shimSha256 为 null)。
332
+ let shimGone = !mf.shimSha256
333
+ if (fs.existsSync(paths.shim)) {
334
+ let digest = null
335
+ try { digest = sha256(paths.shim) } catch { digest = null } // 目录 / 不可读 ⇒ 无法确认,按保留处理
336
+ if (mf.shimSha256 && digest && digest === mf.shimSha256) { fs.unlinkSync(paths.shim); removed.push(paths.shim); shimGone = true }
337
+ else { notes.push(`保留(shim 内容已变、不可读或没有登记哈希):${paths.shim}`); retained.push(paths.shim) }
338
+ }
339
+ else { notes.push(`shim 不存在(已撤过):${paths.shim}`); shimGone = true }
340
+
341
+ // 命令面:只撤回执登记过、且内容仍与登记值相同的那几个文件。
342
+ const cmd = removeCommands({ configDir: paths.configDir, owned: versioned ? (mf.commands ?? null) : null })
343
+ for (const f of cmd.removed) removed.push(f)
344
+ for (const f of cmd.kept) {
345
+ notes.push(`保留(命令不是我们写的,或已被改过):${f}`)
346
+ retained.push(f)
347
+ }
348
+
349
+ if (cfg) {
350
+ let cfgChanged = false
208
351
  const want = paths.skillsPath
209
352
  const list = cfg?.skills?.paths
210
- if (Array.isArray(list) && want && list.includes(want)) {
211
- const nextList = list.filter((x) => x !== want) // 按值删,只删我们那条
353
+ if (versioned && mf.configKeysAdded?.includes("skills.paths") && Array.isArray(list) && want && list.includes(want)) {
354
+ const nextList = list.slice()
355
+ nextList.splice(list.indexOf(want), 1) // 回执只登记一次新增;用户追加的同值项保留
212
356
  if (nextList.length) cfg.skills.paths = nextList
213
357
  else {
214
358
  delete cfg.skills.paths
215
359
  if (cfg.skills && Object.keys(cfg.skills).length === 0) delete cfg.skills
216
360
  }
217
- atomicWrite(paths.configFile, JSON.stringify(cfg, null, 2) + "\n")
218
361
  removed.push(`${paths.configFile} 里的 skills.paths: ${want}`)
362
+ cfgChanged = true
219
363
  } else {
220
- notes.push("配置里没有我们追加的那条 skills path(用户可能已自行改过)⇒ 未动配置")
364
+ notes.push(versioned
365
+ ? "技能路径未登记为新增或已被用户改过 ⇒ 保留配置"
366
+ : "回执没有归属版本(旧版本写的)⇒ 它的新增声明未经证明,配置一律保留")
367
+ }
368
+ const permKey = `permission.${WRITE_PERMISSION_NAME}`
369
+ if (versioned && mf.configKeysAdded?.includes(permKey) && cfg.permission?.[WRITE_PERMISSION_NAME] === "ask" && shimGone) {
370
+ delete cfg.permission[WRITE_PERMISSION_NAME]
371
+ if (Object.keys(cfg.permission).length === 0) delete cfg.permission
372
+ removed.push(`${paths.configFile} 里的 ${permKey}`)
373
+ cfgChanged = true
374
+ } else if (versioned && mf.configKeysAdded?.includes(permKey) && cfg.permission?.[WRITE_PERMISSION_NAME] !== "ask") {
375
+ notes.push(`权限键已被用户改过 ⇒ 保留 ${permKey}`)
376
+ } else if (versioned && mf.configKeysAdded?.includes(permKey)) {
377
+ notes.push(`shim 仍在(本次未能确认删除)⇒ 保留 permission.${WRITE_PERMISSION_NAME},仍在运行的 shim 不会失去写入确认(${paths.shim})`)
221
378
  }
379
+ // 没改动就不重写(否则用户的 4 空格排版会被我们规范成 2 空格,且看起来像"动了配置")。
380
+ if (cfgChanged) atomicWrite(paths.configFile, JSON.stringify(cfg, null, 2) + "\n")
222
381
  } else {
223
382
  notes.push(`宿主配置不存在:${paths.configFile}`)
224
383
  }
225
384
 
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
- ] }
385
+ // 外来同名文件只报告,不给回执续命;只有自身残留(或旧回执无法确认的项)才留回执。
386
+ const pendingRemoval = retained.filter(f => f === paths.shim || !versioned || mf.commands?.[path.basename(f)])
387
+ if (pendingRemoval.length) {
388
+ // 已撤、已不存在或已由用户改变的配置项不再有撤回授权,不能跨半卸周期复活旧声明。
389
+ const configKeysAdded = (Array.isArray(mf.configKeysAdded) ? mf.configKeysAdded : [])
390
+ .filter(k => k !== "skills.paths" && k !== `permission.${WRITE_PERMISSION_NAME}`)
391
+ const commands = Object.fromEntries(Object.entries(mf.commands ?? {}).filter(([name]) =>
392
+ Object.keys(commandTemplates()).includes(name) && cmd.kept.includes(path.join(commandDirFor(paths.configDir), name))))
393
+ const mf2 = { ...mf, configKeysAdded, commands,
394
+ shimSha256: fs.existsSync(paths.shim) ? mf.shimSha256 : null,
395
+ pendingRemoval, pendingAt: new Date().toISOString() }
396
+ atomicWrite(receiptFile, JSON.stringify(mf2, null, 2) + "\n")
397
+ notes.push(`回执保留在 ${receiptFile},并记下这次没撤的 ${pendingRemoval.length} 项`)
398
+ } else if (fs.existsSync(receiptFile)) { fs.unlinkSync(receiptFile); removed.push(receiptFile) }
399
+ return finish()
233
400
  }
234
401
 
235
402
  /**
@@ -237,22 +404,65 @@ export function uninstallAll({ store, configDir = null } = {}) {
237
404
  * `dryRun` 只报告不落盘(先看它打算干什么)。
238
405
  */
239
406
  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() })
407
+ // **三入口同一条规则**(`docs/PENDING-STAGE4.md` §1,函数在 `src/core/home.mjs`):
408
+ // 调用方没给 store ⇒ 显式 > `$OCG_STORE`(兼容覆盖) > `$OCG_HOME` > 平台默认。
409
+ // 拿不到唯一根仍然报错(fail closed,不猜);解析零副作用,不会把别的根的数据搬过来。
410
+ const resolved = store
411
+ ? { store, source: "explicit", via: "override", conflicts: [] }
412
+ : resolveStoreRoot({ env: process.env, homeDir: safeHomedir() })
244
413
  if (!resolved.store) throw new Error("installAll 需要 store(D 目录):既没显式给,也解析不出唯一的数据 home")
245
414
  store = resolved.store
246
415
  const storeSource = resolved.source
247
- const paths = resolveInstallPaths({ store, configDir })
416
+ let paths = resolveInstallPaths({ store, configDir })
417
+ const previousManifest = readManifest(store)
418
+ if (previousManifest?.tool === "oc-grow" && typeof previousManifest.store === "string" && typeof previousManifest.configDir === "string") {
419
+ if (!samePath(previousManifest.store, store) || !samePath(previousManifest.configDir, paths.configDir)) {
420
+ throw new Error("安装回执已登记另一 store 或配置根,未做任何改动;请先按原回执卸载,再安装新落点(需要显式恢复时使用 uninstall --from <manifest>)")
421
+ }
422
+ // Reinstalling through an alias reuses the original spellings, not a second skills path.
423
+ if (manifestMatches(previousManifest, store, paths) && Number(previousManifest.ownershipVersion) >= OWNERSHIP_VERSION) {
424
+ store = previousManifest.store
425
+ paths = resolveInstallPaths({ store, configDir: previousManifest.configDir })
426
+ }
427
+ }
248
428
  const cfgDir = paths.configDir
249
429
  const pluginDir = paths.pluginDir
250
430
  const report = []
251
431
 
432
+ // 预览与执行先走同一条只读预检;损坏配置时,目录、插件与回执也不得部分写入。
433
+ const gatePlan = seedStoreConfig(store, { dryRun: true })
434
+ if (gatePlan.skipped) throw new Error(gatePlan.skipped)
435
+ const cfgPlan = installSkillsConfig({ configDir: cfgDir, store, dryRun: true })
436
+ // 只有「按同一套归属语义写下」的回执才可以把声明带进新回执;旧回执的 configKeysAdded
437
+ // 是硬编码的,采信它等于替旧版本把用户的东西认成我们的。
438
+ const previousOwned = manifestMatches(previousManifest, store, paths) && Number(previousManifest.ownershipVersion) >= OWNERSHIP_VERSION
439
+ const configKeysAdded = [...new Set([
440
+ ...(previousOwned && Array.isArray(previousManifest.configKeysAdded) ? previousManifest.configKeysAdded : []),
441
+ ...cfgPlan.configKeysAdded,
442
+ ])]
443
+
252
444
  const dirs = ["memories", "snapshots", "pending", "skills"]
253
445
  report.push(`D 目录:${store}(${dirs.join(" / ")})`)
254
446
  if (!dryRun) for (const d of dirs) fs.mkdirSync(path.join(store, d), { recursive: true })
255
447
 
448
+ // 写入闸门的**默认值写进 store 配置**(照 Hermes:`config_defaults.py:1291,1455` 把
449
+ // `memory/skills.write_approval` 的默认 `false` 落到配置里 ⇒ 用户看得见、能直接改)。
450
+ // 只看不改:用户已经写过的值**一律保留**(一个被显式打开的闸门不该被重装悄悄关掉)。
451
+ // 常驻两库:**按需创建**只在全新 store 上建空文件(装完即可编辑),已有内容一律不动;
452
+ // 已初始化后缺文件是用户意图,只诊断不重建(doctor 面见 commands.mjs:119-130)。
453
+ const resident = ensureResidentFiles(layout(store), { dryRun })
454
+ if (resident.created.length) report.push(`常驻库:已建空文件 ${resident.created.join(" / ")}(永不写内容,装完即可直接编辑)`)
455
+ if (resident.wouldCreate.length) report.push(`常驻库:dry-run 将建空文件 ${resident.wouldCreate.join(" / ")}(当前未写)`)
456
+ if (resident.kept.length) report.push(`常驻库:已有内容保留 ${resident.kept.join(" / ")}(逐字节不动)`)
457
+ if (resident.missing.length) report.push(`常驻库:${resident.missing.join(" / ")} 缺失——store 已初始化,按你的意图不重建;doctor 会提示,需要就自己新建`)
458
+
459
+ const gate = dryRun ? gatePlan : seedStoreConfig(store)
460
+ report.push(
461
+ gate.action === "keep"
462
+ ? `写入闸门:${gate.file} 配置已有,逐键保留`
463
+ : `写入闸门:${gate.file} ${dryRun ? "将" : "已"}${gate.action === "create" ? "新增" : "补缺"}默认配置 ${gate.plannedAdded.join(" / ")}(默认关=写入直接生效;已有值保持不动)`,
464
+ )
465
+
256
466
  const shim = path.join(pluginDir, ADAPTER_FILE)
257
467
  report.push(`插件文件:${shim}(.js —— 实测 .mjs 宿主不加载,且是静默的)`)
258
468
  report.push('宿主依赖:shim 里 import "zod"(按文件位置解析);拿不到则退回适配器自查')
@@ -260,12 +470,16 @@ export function installAll({ store, configDir = null, queuePath = null, dryRun =
260
470
 
261
471
  const cfgFile = path.join(cfgDir, "opencode", "opencode.json")
262
472
  report.push(`技能路径:${cfgFile} 的 skills.paths += ${skillsDir(store)}`)
263
- const cfgOut = dryRun ? null : installSkillsConfig({ configDir: cfgDir, store })
473
+ const cfgOut = dryRun ? cfgPlan : installSkillsConfig({ configDir: cfgDir, store })
264
474
  report.push(`命令面:${commandDirFor(cfgDir)}/ocg-{pending,approve,reject}.md(卸载按值撤;用户自己的命令不动)`)
265
- if (!dryRun) installCommands({ configDir: cfgDir })
475
+ const cmdOut = installCommands({ configDir: cfgDir, dryRun })
476
+ for (const f of cmdOut.kept) report.push(`命令面:${f} 已存在且不是我们的 ⇒ 保留原文件`)
477
+ const commands = previousOwned && previousManifest.commands && typeof previousManifest.commands === "object"
478
+ ? { ...previousManifest.commands, ...cmdOut.owned } : { ...cmdOut.owned }
266
479
  if (!dryRun) {
267
480
  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 })
481
+ writeManifest({ store, paths, version, configKeysAdded, commands, storeSource,
482
+ storeVia: resolved.via ?? null, storeConflicts: resolved.conflicts ?? [] })
269
483
  report.push(`回执:${manifestPath(store)}(装了什么、写进哪个键,可机器核对)`)
270
484
  }
271
485
 
@@ -283,11 +497,59 @@ export function installAll({ store, configDir = null, queuePath = null, dryRun =
283
497
  configFile: cfgFile,
284
498
  skillsPath: skillsDir(store),
285
499
  created: cfgOut?.created ?? null,
500
+ wouldCreate: cfgOut.wouldCreate,
501
+ storeConfig: gate,
502
+ resident,
286
503
  report,
287
504
  }
288
505
  }
289
506
 
290
507
 
508
+ // ── store 级配置的默认值(照 Hermes 的 config_defaults)────────────────────────
509
+ //
510
+ // 为什么要有这一步:闸门的落点是 `D/config.json`,而**闸关是"读不到"与"写了 false"的同一个结果**——
511
+ // 也就是说,装完不写它,用户根本看不见这个开关存在。Hermes 把默认值写进配置(`config_defaults.py:1291`),
512
+ // 我们照做:**只补缺、不覆盖**。
513
+ export function seedStoreConfig(store, { dryRun = false } = {}) {
514
+ const file = path.join(store, "config.json")
515
+ const existed = fs.existsSync(file)
516
+ let cfg = {}
517
+ if (existed) {
518
+ try {
519
+ let raw
520
+ try { raw = JSON.parse(fs.readFileSync(file, "utf8")) }
521
+ catch (err) { throw new Error(`D 的 config.json 不是合法 JSON(${file}):${err.message}`) }
522
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error(`D 的 config.json 必须是 JSON 对象(${file})`)
523
+ cfg = raw
524
+ } catch (err) {
525
+ // 解析不了就**一个字节都不动**(闸门自己的容错是"读不到 ⇒ 当关",但"当关"不等于"可以重写它")
526
+ return { file, existed, action: "skip", plannedAdded: [], added: [], skipped: `现有 config.json 解析失败(${err.message}),保留原文件` }
527
+ }
528
+ }
529
+ const added = []
530
+ for (const subsystem of ["memory", "skills"]) {
531
+ const cur = cfg[subsystem]
532
+ const ok = cur && typeof cur === "object" && !Array.isArray(cur)
533
+ if (ok && "write_approval" in cur) continue
534
+ // 子树存在但形状不对时**不许**用 {} 兜底重建:那会把用户写的原值整棵丢掉,
535
+ // 而回执里没有 pre-image、卸载也不恢复 ⇒ 内容不可挽回。口径与宿主 permission 守卫同源:
536
+ // 先拒绝、一个字节都不动(dry-run 与真实执行都停在同一处,所以报告不会再宣称「补缺」)。
537
+ if (cur !== undefined && !ok) {
538
+ return { file, existed, action: "skip", plannedAdded: [], added: [],
539
+ skipped: `D 的 config.json 的 ${subsystem} 必须是 JSON 对象(${file}),保留原文件` }
540
+ }
541
+ cfg[subsystem] = { ...(ok ? cur : {}), write_approval: false }
542
+ added.push(`${subsystem}.write_approval`)
543
+ }
544
+ if (added.length && !dryRun) {
545
+ fs.mkdirSync(path.dirname(file), { recursive: true })
546
+ fs.writeFileSync(file, JSON.stringify(cfg, null, 2) + "\n")
547
+ }
548
+ const action = !existed ? "create" : added.length ? "fill-missing" : "keep"
549
+ return { file, existed, action, plannedAdded: added.slice(), added: dryRun ? [] : added, skipped: null }
550
+ }
551
+
552
+
291
553
  // ── 常驻两库文件的创建规则(用户 2026-09-20 拍板)──────────────────────────────
292
554
  // ① 全新 store(无初始化标记)⇒ 缺则建**空文件**(装完即可编辑 ✓)
293
555
  // 永久规则:**永不写内容**(常驻层按 § 切条目,任何说明行都会被当成一条记忆 ✗)
@@ -296,7 +558,7 @@ export function installAll({ store, configDir = null, queuePath = null, dryRun =
296
558
  const STORE_INIT_MARKER = ".ocg-store-initialized"
297
559
  export const storeInitMarker = (L) => path.join(L.root, STORE_INIT_MARKER)
298
560
 
299
- export function ensureResidentFiles(L) {
561
+ export function ensureResidentFiles(L, { dryRun = false } = {}) {
300
562
  const dir = path.join(L.root, "memories")
301
563
  // 「已初始化」= 有标记 **或** 已经有任何一个库文件 —— 后者意味着这是别人/用户自己建过的库,
302
564
  // 此时**只补建缺失的另一个也不做** ✗:只用一个库(例如只用 MEMORY.md)是合法意图 ✓。
@@ -306,11 +568,14 @@ export function ensureResidentFiles(L) {
306
568
  const kept = []
307
569
  const missing = []
308
570
 
571
+ const wouldCreate = []
309
572
  for (const name of ["MEMORY.md", "USER.md"]) {
310
573
  const file = path.join(dir, name)
311
574
  if (fs.existsSync(file)) {
312
575
  kept.push(name)
313
576
  } else if (!initialized) {
577
+ // 唯一会创建的分支:全新 store。dry-run 只报告,一个字节都不写。
578
+ if (dryRun) { wouldCreate.push(name); continue }
314
579
  fs.mkdirSync(dir, { recursive: true })
315
580
  fs.writeFileSync(file, "")
316
581
  created.push(name)
@@ -319,8 +584,8 @@ export function ensureResidentFiles(L) {
319
584
  }
320
585
  }
321
586
 
322
- if (!initialized) fs.writeFileSync(storeInitMarker(L), "first-install\n")
323
- return { created, kept, missing, initialized }
587
+ if (!initialized && !dryRun) fs.writeFileSync(storeInitMarker(L), "first-install\n")
588
+ return { created, kept, missing, initialized, wouldCreate }
324
589
  }
325
590
 
326
591
  // ── 命令面(subgoal②「待批三件齐全」之一) ────────────────────────────────────
@@ -345,43 +610,55 @@ export function commandTemplates() {
345
610
  return {
346
611
  "ocg-pending.md": mk(
347
612
  "列出 opencode-growth 的待批记忆提案",
348
- "请调用 memory 工具(action=pending)列出当前待批提案,并逐条说明来源([auto] = 后台复习提出)。不要自行批准或拒绝。",
613
+ "列出待批提案:在终端运行 oc-grow --store <D> memory pending(也可以让会话调用 memory 工具、action=pending)。逐条说明来源([auto] = 后台复习提出)。不要自行批准或拒绝。",
349
614
  ),
350
615
  "ocg-approve.md": mk(
351
616
  "批准一条待批记忆提案(需要参数)",
352
- "批准待批提案 $ARGUMENTS:在终端运行 oc-grow memory approve $ARGUMENTS(批准有副作用,只走命令行,不由模型执行)。",
617
+ "批准待批提案 $ARGUMENTS:在终端运行 oc-grow --store <D> memory approve $ARGUMENTS --as <你的名字>(批准有副作用、必须署名,只走命令行,不由模型执行)。",
353
618
  ),
354
619
  "ocg-reject.md": mk(
355
620
  "拒绝一条待批记忆提案(需要参数)",
356
- "拒绝待批提案 $ARGUMENTS:删掉对应的 D/pending/<file> 即可(删除即拒绝)。",
621
+ "拒绝待批提案 $ARGUMENTS:删掉对应的 D/pending/<file> 即可(删除即拒绝)。不知道文件名先跑 oc-grow --store <D> memory pending。",
357
622
  ),
358
623
  }
359
624
  }
360
625
 
361
626
  /** 写命令模板,返回真正写入的路径。 */
362
- export function installCommands({ configDir } = {}) {
627
+ export function installCommands({ configDir, dryRun = false } = {}) {
363
628
  const dir = commandDirFor(configDir)
364
- fs.mkdirSync(dir, { recursive: true })
629
+ if (!dryRun) fs.mkdirSync(dir, { recursive: true })
365
630
  const written = []
631
+ const kept = []
632
+ const owned = {}
366
633
  for (const [name, body] of Object.entries(commandTemplates())) {
367
634
  const f = path.join(dir, name)
368
- atomicWrite(f, body)
635
+ let current = null
636
+ try { current = fs.existsSync(f) ? fs.readFileSync(f, "utf8") : null } catch { kept.push(f); continue }
637
+ // 已经有同名文件:只有内容与我们的模板逐字相同才算「我们的」,否则是用户的,一个字节都不动。
638
+ if (current !== null && current !== body) { kept.push(f); continue }
639
+ if (!dryRun) atomicWrite(f, body)
369
640
  written.push(f)
641
+ owned[name] = createHash("sha256").update(body).digest("hex")
370
642
  }
371
- return { dir, written }
643
+ return { dir, written, kept, owned, dryRun }
372
644
  }
373
645
 
374
646
  /** 卸载命令:按值撤(只删带标记的),返回 removed / kept。 */
375
- export function removeCommands({ configDir } = {}) {
647
+ export function removeCommands({ configDir, owned = null } = {}) {
376
648
  const dir = commandDirFor(configDir)
377
649
  const removed = []
378
650
  const kept = []
379
651
  if (!fs.existsSync(dir)) return { dir, removed, kept }
380
- for (const name of fs.readdirSync(dir)) {
652
+ // 只认清单里的三个名字 + 回执记的哈希:用户的同名文件、以及用户复制出去的副本都不动。
653
+ for (const name of Object.keys(commandTemplates())) {
381
654
  const f = path.join(dir, name)
382
- let text = ""
655
+ if (!fs.existsSync(f)) continue
656
+ const recorded = owned?.[name] ?? null
657
+ if (!recorded) { kept.push(f); continue }
658
+ let text = null
383
659
  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)
660
+ const same = createHash("sha256").update(text).digest("hex") === recorded
661
+ if (same) { fs.rmSync(f); removed.push(f) } else kept.push(f)
385
662
  }
386
663
  return { dir, removed, kept }
387
664
  }
@@ -0,0 +1,57 @@
1
+ // journey 的**会话内入口**(签署⑬:同一份 payload,多客户端)。
2
+ //
3
+ // 形制照 memory-tool.mjs(tool/z 由宿主注入、tool() 实测是恒等函数);payload 构造
4
+ // 直接复用 core/journey.mjs 的 buildJourney + journey-view 的 applyFilters/filterHintLines
5
+ // ——与 CLI `journey --json` 同一个构造器,「同一份」由构造同源保证,不做二次序列化。
6
+ //
7
+ // 只读:不写 store 一个字节(§5.5-③/⑤ 的写入拒绝探针同款判据)。
8
+ import { buildJourney } from "../core/journey.mjs"
9
+ import { applyFilters, parseSince, filterHintLines } from "../cli/journey-view.mjs"
10
+ import { layout } from "../core/paths.mjs"
11
+
12
+ export const JOURNEY_TOOL_DESCRIPTION = [
13
+ "看 ocg 的 journey 时间线(它记住了什么、什么时候进来的、哪条被撤回)。",
14
+ "默认全量;since 显式给(7d / 24h / ISO 时间)才过滤,隐藏项会明说、并给看全量的入口。",
15
+ "输出 output 是机读 payload 的 JSON(与命令行 `oc-grow journey --json` 的 data 同一份)。",
16
+ ].join("")
17
+
18
+ export function registerJourneyTool({ tool, z, root } = {}) {
19
+ if (!z?.string) throw new Error("registerJourneyTool 需要宿主给的 z")
20
+ if (!root) throw new Error("registerJourneyTool 需要 root(D 目录)")
21
+ // 真机形状(2026-09-24 trace 实测 hasTool:false):宿主不注入 tool 工厂;tool() 源码即恒等 ⇒ 缺省等价
22
+ const wrap = typeof tool === "function" ? tool : (d) => d
23
+
24
+ return wrap({
25
+ description: JOURNEY_TOOL_DESCRIPTION,
26
+ args: {
27
+ since: z.string().optional().describe("只过滤有时间证据的项(7d / 24h / ISO 时间);不给就是全量"),
28
+ },
29
+ async execute(args) { // 真机宿主(Bun)要求 execute 返回 thenable:w0(()=>X(Q)).then(...)
30
+ const now = Math.floor(Date.now() / 1000)
31
+ let sinceInfo = null
32
+ if (args?.since !== undefined && args?.since !== null) {
33
+ sinceInfo = parseSince(String(args.since), now)
34
+ if (!sinceInfo) {
35
+ return { title: "journey 参数不对", output: `--since 只接 7d / 24h / ISO 时间,拿到:${args.since}`, metadata: { ok: false } }
36
+ }
37
+ }
38
+ const run = {
39
+ clock: now,
40
+ args: ["journey", "tool", ...(sinceInfo ? [`--since=${args.since}`] : [])],
41
+ digest: null, // buildJourney 自己算文件摘要(与 CLI 同源)
42
+ identity: "ocg-session",
43
+ }
44
+ const L = layout(root)
45
+ const payload0 = buildJourney(L, { since: sinceInfo?.since ?? null, sinceLabel: sinceInfo?.label ?? null, now, run })
46
+ const payload = applyFilters(payload0, { kind: null, state: null })
47
+ const hint = filterHintLines(payload, sinceInfo).join("\n")
48
+ return {
49
+ title: sinceInfo ? `journey · 已过滤 ${sinceInfo.label}` : "journey · 全量",
50
+ output: JSON.stringify(payload),
51
+ hint,
52
+ data: payload,
53
+ metadata: { ok: true, since: sinceInfo?.label ?? null, nodes: (payload.nodes ?? []).length },
54
+ }
55
+ },
56
+ })
57
+ }