opencode-growth 0.1.59 → 0.1.75

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.
@@ -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,10 +179,11 @@ 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", storeVia = null, storeConflicts = [] }) {
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
188
  // 这个 D 是怎么来的:explicit(调用方给了)| env($OCG_STORE / $OCG_HOME)| default(平台默认 home)。
164
189
  // 口径见 `docs/PENDING-STAGE4.md` §1 + `src/core/home.mjs::resolveStoreRoot`(三入口同一条规则);
@@ -174,12 +199,79 @@ export function writeManifest({ store, paths, version, configKeysAdded, storeSou
174
199
  configFile: paths.configFile,
175
200
  skillsPath: paths.skillsPath,
176
201
  configKeysAdded: configKeysAdded ?? [],
202
+ // 命令面同一个口径:记下**实际写进去的那份内容**的哈希,才能只撤自己写的那些。
203
+ commands: commands ?? {},
204
+ // 半卸:这一轮该撤、但因为内容已变(或读不到)而保留的东西。留着回执,第二次才还认得。
205
+ pendingRemoval: pendingRemoval ?? [],
177
206
  installedAt: new Date().toISOString(),
178
207
  }
179
208
  atomicWrite(manifestPath(store), JSON.stringify(m, null, 2) + "\n")
180
209
  return m
181
210
  }
182
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
+
183
275
  /**
184
276
  * 卸载:**只撤我们写的东西**。
185
277
  * · shim:按回执记的路径删(不存在也当成功 ⇒ 幂等)
@@ -188,52 +280,123 @@ export function writeManifest({ store, paths, version, configKeysAdded, storeSou
188
280
  * · 回执:撤完删除(下次再跑就是"没装过",仍然 exit 0)
189
281
  * 不做的事:不碰宿主目录里的其它文件、不删 D 里的记忆(那是数据,要人显式决定)。
190
282
  */
191
- export function uninstallAll({ store, configDir = null } = {}) {
283
+ export function uninstallAll({ store, configDir = null, from = null } = {}) {
192
284
  if (!store) throw new Error("uninstallAll 需要 store(D 目录)")
193
- const mf = readManifest(store)
194
- 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) })
195
290
  const removed = []
196
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
+ }
197
314
 
198
- if (fs.existsSync(paths.shim)) { fs.unlinkSync(paths.shim); removed.push(paths.shim) }
199
- else notes.push(`shim 不存在(已撤过):${paths.shim}`)
200
-
201
- // 命令面:**按值撤**(只删带我们标记的模板;用户自己的命令一律不动)
202
- const cmd = removeCommands({ configDir: paths.configDir })
203
- for (const f of cmd.removed) removed.push(f)
204
- 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};只撤原登记落点)`)
205
318
 
319
+ // Validate the complete host config before deleting even the first owned file.
320
+ let cfg = null
206
321
  if (fs.existsSync(paths.configFile)) {
207
322
  const raw = fs.readFileSync(paths.configFile, "utf8")
208
- let cfg
209
323
  try { cfg = JSON.parse(raw) } catch (err) {
210
324
  throw new Error(`宿主配置不是合法 JSON,未做任何改动(${paths.configFile}):${err?.message ?? err}`)
211
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
212
351
  const want = paths.skillsPath
213
352
  const list = cfg?.skills?.paths
214
- if (Array.isArray(list) && want && list.includes(want)) {
215
- 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) // 回执只登记一次新增;用户追加的同值项保留
216
356
  if (nextList.length) cfg.skills.paths = nextList
217
357
  else {
218
358
  delete cfg.skills.paths
219
359
  if (cfg.skills && Object.keys(cfg.skills).length === 0) delete cfg.skills
220
360
  }
221
- atomicWrite(paths.configFile, JSON.stringify(cfg, null, 2) + "\n")
222
361
  removed.push(`${paths.configFile} 里的 skills.paths: ${want}`)
362
+ cfgChanged = true
223
363
  } else {
224
- notes.push("配置里没有我们追加的那条 skills path(用户可能已自行改过)⇒ 未动配置")
364
+ notes.push(versioned
365
+ ? "技能路径未登记为新增或已被用户改过 ⇒ 保留配置"
366
+ : "回执没有归属版本(旧版本写的)⇒ 它的新增声明未经证明,配置一律保留")
225
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})`)
378
+ }
379
+ // 没改动就不重写(否则用户的 4 空格排版会被我们规范成 2 空格,且看起来像"动了配置")。
380
+ if (cfgChanged) atomicWrite(paths.configFile, JSON.stringify(cfg, null, 2) + "\n")
226
381
  } else {
227
382
  notes.push(`宿主配置不存在:${paths.configFile}`)
228
383
  }
229
384
 
230
- if (fs.existsSync(manifestPath(store))) { fs.unlinkSync(manifestPath(store)); removed.push(manifestPath(store)) }
231
- return { store, ...paths, removed, notes, report: [
232
- removed.length ? `撤掉了 ${removed.length} 项:` : "没有需要撤的东西(幂等)",
233
- ...removed.map((x) => ` · ${x}`),
234
- ...notes.map((x) => ` - ${x}`),
235
- "D 里的记忆/快照/待批**没有被删**(那是数据,删不删由你决定)。",
236
- ] }
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()
237
400
  }
238
401
 
239
402
  /**
@@ -250,11 +413,34 @@ export function installAll({ store, configDir = null, queuePath = null, dryRun =
250
413
  if (!resolved.store) throw new Error("installAll 需要 store(D 目录):既没显式给,也解析不出唯一的数据 home")
251
414
  store = resolved.store
252
415
  const storeSource = resolved.source
253
- 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
+ }
254
428
  const cfgDir = paths.configDir
255
429
  const pluginDir = paths.pluginDir
256
430
  const report = []
257
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
+
258
444
  const dirs = ["memories", "snapshots", "pending", "skills"]
259
445
  report.push(`D 目录:${store}(${dirs.join(" / ")})`)
260
446
  if (!dryRun) for (const d of dirs) fs.mkdirSync(path.join(store, d), { recursive: true })
@@ -262,11 +448,19 @@ export function installAll({ store, configDir = null, queuePath = null, dryRun =
262
448
  // 写入闸门的**默认值写进 store 配置**(照 Hermes:`config_defaults.py:1291,1455` 把
263
449
  // `memory/skills.write_approval` 的默认 `false` 落到配置里 ⇒ 用户看得见、能直接改)。
264
450
  // 只看不改:用户已经写过的值**一律保留**(一个被显式打开的闸门不该被重装悄悄关掉)。
265
- const gate = seedStoreConfig(store, { dryRun })
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)
266
460
  report.push(
267
- gate.added.length
268
- ? `写入闸门:${gate.file} 补默认值 ${gate.added.join(" / ")}(默认关=写入直接生效;想改成"每次要你批"就把它改成 true)`
269
- : `写入闸门:${gate.file} 已有配置,保持不动${gate.skipped ? `(${gate.skipped})` : ""}`,
461
+ gate.action === "keep"
462
+ ? `写入闸门:${gate.file} 配置已有,逐键保留`
463
+ : `写入闸门:${gate.file} ${dryRun ? "将" : "已"}${gate.action === "create" ? "新增" : "补缺"}默认配置 ${gate.plannedAdded.join(" / ")}(默认关=写入直接生效;已有值保持不动)`,
270
464
  )
271
465
 
272
466
  const shim = path.join(pluginDir, ADAPTER_FILE)
@@ -276,12 +470,15 @@ export function installAll({ store, configDir = null, queuePath = null, dryRun =
276
470
 
277
471
  const cfgFile = path.join(cfgDir, "opencode", "opencode.json")
278
472
  report.push(`技能路径:${cfgFile} 的 skills.paths += ${skillsDir(store)}`)
279
- const cfgOut = dryRun ? null : installSkillsConfig({ configDir: cfgDir, store })
473
+ const cfgOut = dryRun ? cfgPlan : installSkillsConfig({ configDir: cfgDir, store })
280
474
  report.push(`命令面:${commandDirFor(cfgDir)}/ocg-{pending,approve,reject}.md(卸载按值撤;用户自己的命令不动)`)
281
- 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 }
282
479
  if (!dryRun) {
283
480
  const version = (() => { try { return JSON.parse(fs.readFileSync(path.join(HERE, "..", "..", "package.json"), "utf8")).version } catch { return null } })()
284
- writeManifest({ store, paths, version, configKeysAdded: ["skills.paths"], storeSource,
481
+ writeManifest({ store, paths, version, configKeysAdded, commands, storeSource,
285
482
  storeVia: resolved.via ?? null, storeConflicts: resolved.conflicts ?? [] })
286
483
  report.push(`回执:${manifestPath(store)}(装了什么、写进哪个键,可机器核对)`)
287
484
  }
@@ -300,6 +497,9 @@ export function installAll({ store, configDir = null, queuePath = null, dryRun =
300
497
  configFile: cfgFile,
301
498
  skillsPath: skillsDir(store),
302
499
  created: cfgOut?.created ?? null,
500
+ wouldCreate: cfgOut.wouldCreate,
501
+ storeConfig: gate,
502
+ resident,
303
503
  report,
304
504
  }
305
505
  }
@@ -312,15 +512,18 @@ export function installAll({ store, configDir = null, queuePath = null, dryRun =
312
512
  // 我们照做:**只补缺、不覆盖**。
313
513
  export function seedStoreConfig(store, { dryRun = false } = {}) {
314
514
  const file = path.join(store, "config.json")
515
+ const existed = fs.existsSync(file)
315
516
  let cfg = {}
316
- if (fs.existsSync(file)) {
517
+ if (existed) {
317
518
  try {
318
- const raw = JSON.parse(fs.readFileSync(file, "utf8"))
319
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("形状不是对象")
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})`)
320
523
  cfg = raw
321
524
  } catch (err) {
322
525
  // 解析不了就**一个字节都不动**(闸门自己的容错是"读不到 ⇒ 当关",但"当关"不等于"可以重写它")
323
- return { file, added: [], skipped: `现有 config.json 解析失败(${err.message}),保留原文件` }
526
+ return { file, existed, action: "skip", plannedAdded: [], added: [], skipped: `现有 config.json 解析失败(${err.message}),保留原文件` }
324
527
  }
325
528
  }
326
529
  const added = []
@@ -328,6 +531,13 @@ export function seedStoreConfig(store, { dryRun = false } = {}) {
328
531
  const cur = cfg[subsystem]
329
532
  const ok = cur && typeof cur === "object" && !Array.isArray(cur)
330
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
+ }
331
541
  cfg[subsystem] = { ...(ok ? cur : {}), write_approval: false }
332
542
  added.push(`${subsystem}.write_approval`)
333
543
  }
@@ -335,7 +545,8 @@ export function seedStoreConfig(store, { dryRun = false } = {}) {
335
545
  fs.mkdirSync(path.dirname(file), { recursive: true })
336
546
  fs.writeFileSync(file, JSON.stringify(cfg, null, 2) + "\n")
337
547
  }
338
- return { file, added: dryRun ? [] : added, skipped: null }
548
+ const action = !existed ? "create" : added.length ? "fill-missing" : "keep"
549
+ return { file, existed, action, plannedAdded: added.slice(), added: dryRun ? [] : added, skipped: null }
339
550
  }
340
551
 
341
552
 
@@ -347,7 +558,7 @@ export function seedStoreConfig(store, { dryRun = false } = {}) {
347
558
  const STORE_INIT_MARKER = ".ocg-store-initialized"
348
559
  export const storeInitMarker = (L) => path.join(L.root, STORE_INIT_MARKER)
349
560
 
350
- export function ensureResidentFiles(L) {
561
+ export function ensureResidentFiles(L, { dryRun = false } = {}) {
351
562
  const dir = path.join(L.root, "memories")
352
563
  // 「已初始化」= 有标记 **或** 已经有任何一个库文件 —— 后者意味着这是别人/用户自己建过的库,
353
564
  // 此时**只补建缺失的另一个也不做** ✗:只用一个库(例如只用 MEMORY.md)是合法意图 ✓。
@@ -357,11 +568,14 @@ export function ensureResidentFiles(L) {
357
568
  const kept = []
358
569
  const missing = []
359
570
 
571
+ const wouldCreate = []
360
572
  for (const name of ["MEMORY.md", "USER.md"]) {
361
573
  const file = path.join(dir, name)
362
574
  if (fs.existsSync(file)) {
363
575
  kept.push(name)
364
576
  } else if (!initialized) {
577
+ // 唯一会创建的分支:全新 store。dry-run 只报告,一个字节都不写。
578
+ if (dryRun) { wouldCreate.push(name); continue }
365
579
  fs.mkdirSync(dir, { recursive: true })
366
580
  fs.writeFileSync(file, "")
367
581
  created.push(name)
@@ -370,8 +584,8 @@ export function ensureResidentFiles(L) {
370
584
  }
371
585
  }
372
586
 
373
- if (!initialized) fs.writeFileSync(storeInitMarker(L), "first-install\n")
374
- return { created, kept, missing, initialized }
587
+ if (!initialized && !dryRun) fs.writeFileSync(storeInitMarker(L), "first-install\n")
588
+ return { created, kept, missing, initialized, wouldCreate }
375
589
  }
376
590
 
377
591
  // ── 命令面(subgoal②「待批三件齐全」之一) ────────────────────────────────────
@@ -410,29 +624,41 @@ export function commandTemplates() {
410
624
  }
411
625
 
412
626
  /** 写命令模板,返回真正写入的路径。 */
413
- export function installCommands({ configDir } = {}) {
627
+ export function installCommands({ configDir, dryRun = false } = {}) {
414
628
  const dir = commandDirFor(configDir)
415
- fs.mkdirSync(dir, { recursive: true })
629
+ if (!dryRun) fs.mkdirSync(dir, { recursive: true })
416
630
  const written = []
631
+ const kept = []
632
+ const owned = {}
417
633
  for (const [name, body] of Object.entries(commandTemplates())) {
418
634
  const f = path.join(dir, name)
419
- 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)
420
640
  written.push(f)
641
+ owned[name] = createHash("sha256").update(body).digest("hex")
421
642
  }
422
- return { dir, written }
643
+ return { dir, written, kept, owned, dryRun }
423
644
  }
424
645
 
425
646
  /** 卸载命令:按值撤(只删带标记的),返回 removed / kept。 */
426
- export function removeCommands({ configDir } = {}) {
647
+ export function removeCommands({ configDir, owned = null } = {}) {
427
648
  const dir = commandDirFor(configDir)
428
649
  const removed = []
429
650
  const kept = []
430
651
  if (!fs.existsSync(dir)) return { dir, removed, kept }
431
- for (const name of fs.readdirSync(dir)) {
652
+ // 只认清单里的三个名字 + 回执记的哈希:用户的同名文件、以及用户复制出去的副本都不动。
653
+ for (const name of Object.keys(commandTemplates())) {
432
654
  const f = path.join(dir, name)
433
- 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
434
659
  try { text = fs.readFileSync(f, "utf8") } catch { kept.push(f); continue }
435
- 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)
436
662
  }
437
663
  return { dir, removed, kept }
438
664
  }
@@ -16,6 +16,7 @@ import path from "node:path"
16
16
  import { pathToFileURL } from "node:url"
17
17
 
18
18
  import { MEMORY_ACTIONS, identityFor, runMemoryAction } from "../core/memory-actions.mjs"
19
+ import { backgroundSubsessionKind } from "../core/subsessions.mjs"
19
20
 
20
21
  /** 宿主的 `tool()` 实测就是恒等函数(`packages/plugin/src/tool.ts`:`return input`)。 */
21
22
  const identityTool = (def) => def
@@ -116,6 +117,7 @@ export function buildMemoryTool({
116
117
  interactive,
117
118
  backgroundAgents,
118
119
  foregroundAgents,
120
+ backgroundKind: backgroundSubsessionKind(ctx?.sessionID),
119
121
  })
120
122
  const r = await runMemoryAction({
121
123
  operations: Array.isArray(args?.operations) && args.operations.length ? args.operations : undefined,
@@ -1,5 +1,6 @@
1
- // S3 · ③层工具面(照 Hermes 六件:viking_search / viking_read / viking_browse /
2
- // viking_remember / viking_forget / viking_add_resource)。
1
+ // S3 · ③层工具面(照 Hermes 的六件 schema;**注册五件**:viking_search / viking_read /
2
+ // viking_browse / viking_remember / viking_forget)。`viking_add_resource` 的资源索引面
3
+ // 未实现(恒返 gap)⇒ 0.1.75 起**不注册**:模型工具表里不放空壳。
3
4
  //
4
5
  // 对齐口径(锁版本 b9d5e4d1):
5
6
  // - **名称/描述/参数逐字照 H** `_TOOL_SCHEMAS`(:390-450 的六个 schema 常量)
@@ -10,8 +11,9 @@
10
11
  // - 批读上限照 H `:70-71`:一次最多 3 个 URI;多 URI 时 full 单条限 2500 字符
11
12
  // - 工具面**只在 provider 在场时**注册(与 H 同:插件没启用就没有这些工具)
12
13
  //
13
- // 我们的缺口**如实返回**(不假装成功):`add_resource` 走临时上传/资源索引,我们的适配器
14
- // 尚未实现该面 ⇒ 返回 `{ok:false, gap}`(沿用 provider `update/remove` 的既有先例)。
14
+ // 缺口如实记录而不是注册空壳:`viking_add_resource` 需要 temp_upload + 资源提交/清理,
15
+ // 是独立的产品功能。astrA 评审的推翻条件:同候选包能经已配置 provider 正常导入受支持来源、
16
+ // 拿回资源回执并查回内容,才按真实支持范围重新注册。
15
17
  import { RECALL_FENCE } from "../provider/runtime.mjs"
16
18
 
17
19
  /** 一次读取的批量上限(照 H `:70`)。 */
@@ -168,36 +170,6 @@ export function buildProviderTools({ provider, z, tool = null } = {}) {
168
170
  },
169
171
  })
170
172
 
171
- tools.viking_add_resource = mk({
172
- description:
173
- "Add a remote URL or local file/directory to the OpenViking knowledge base. Remote resources must be public http(s), git, " +
174
- "or ssh URLs. Local files are uploaded first using OpenViking temp_upload. The system automatically parses, indexes, and " +
175
- "generates summaries.",
176
- parameters: {
177
- url: z.string().describe("Remote URL or local file/directory path to add."),
178
- reason: z.string().optional().describe("Why this resource is relevant (improves search)."),
179
- to: z.string().optional().describe("Optional target viking:// URI for the resource."),
180
- parent: z.string().optional().describe("Optional parent viking:// URI. Cannot be used with to."),
181
- instruction: z.string().optional().describe("Optional processing instruction for semantic extraction."),
182
- wait: z.boolean().optional().describe("Whether to wait for processing to complete."),
183
- timeout: z.number().optional().describe("Timeout in seconds when wait is true."),
184
- },
185
- async execute(input = {}) {
186
- const url = String(input.url ?? "").trim()
187
- if (!url) return { output: JSON.stringify({ ok: false, error: "url is required" }), metadata: { ok: false } }
188
- // 实现缺口(如实返回,不假装成功):我们的适配器只覆盖「记忆条目」面,
189
- // 资源索引面(temp_upload / resources add)未实现 —— 与 update/remove 同款先例。
190
- return {
191
- output: JSON.stringify({
192
- ok: false,
193
- gap: "viking_add_resource 未实现:资源索引面(temp_upload / 资源新增)不在本适配器的能力面内",
194
- url,
195
- }),
196
- metadata: { ok: false, state: "gap" },
197
- }
198
- },
199
- })
200
-
201
173
  return tools
202
174
  }
203
175
 
@@ -229,9 +201,11 @@ async function readUri(provider, uri, level, maxCharsOverride) {
229
201
  }
230
202
 
231
203
  /** 工具名清单(注册侧与测试用;与 H `_OPENVIKING_RECALL_TOOL_NAMES` 区分:只读三件不回灌)。 */
232
- export const PROVIDER_TOOL_NAMES = ["viking_search", "viking_read", "viking_browse", "viking_remember", "viking_forget", "viking_add_resource"]
204
+ export const PROVIDER_TOOL_NAMES = ["viking_search", "viking_read", "viking_browse", "viking_remember", "viking_forget"]
205
+ /** 未实现、因此**不注册**的工具名(缺口写进文档;别把它当能力面)。 */
206
+ export const PROVIDER_HIDDEN_TOOL_NAMES = ["viking_add_resource"]
233
207
  /** 只读三件:结果不许再喂回记忆面(照 H 的 recall-tool 名单)。 */
234
208
  export const PROVIDER_RECALL_TOOL_NAMES = ["viking_search", "viking_read", "viking_browse"]
235
209
 
236
210
  /** 供注册侧使用的字符串 schema 形(z 缺席时的降级说明用,不参与真机注册)。 */
237
- export const PROVIDER_SCHEMA_FALLBACK_NOTE = `${PROVIDER_TOOLS_SOURCE}(六件:${PROVIDER_TOOL_NAMES.join(" / ")};围栏 ${RECALL_FENCE.open})`
211
+ export const PROVIDER_SCHEMA_FALLBACK_NOTE = `${PROVIDER_TOOLS_SOURCE}(五件:${PROVIDER_TOOL_NAMES.join(" / ")};未实现不注册:${PROVIDER_HIDDEN_TOOL_NAMES.join(" / ")};围栏 ${RECALL_FENCE.open})`