opencode-growth 0.1.1 → 0.1.59

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 (44) hide show
  1. package/README.md +60 -30
  2. package/package.json +3 -3
  3. package/src/adapter-opencode/curator-runner.mjs +254 -0
  4. package/src/adapter-opencode/index.mjs +305 -19
  5. package/src/adapter-opencode/install.mjs +63 -12
  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 +75 -21
  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 +74 -1
  13. package/src/cli/curator-cmd.mjs +147 -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 +172 -25
  17. package/src/cli/memory-cmd.mjs +165 -0
  18. package/src/cli/session-index-cmd.mjs +74 -0
  19. package/src/cli/skill-cmd.mjs +192 -0
  20. package/src/core/approve.mjs +155 -0
  21. package/src/core/audit.mjs +51 -0
  22. package/src/core/background-review.mjs +88 -1
  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 +186 -9
  27. package/src/core/memory-actions.mjs +73 -18
  28. package/src/core/session-freshness.mjs +201 -0
  29. package/src/core/session-index.mjs +467 -0
  30. package/src/core/session-query.mjs +161 -0
  31. package/src/core/session-source.mjs +202 -0
  32. package/src/core/session-tool.mjs +181 -0
  33. package/src/core/skill-actions.mjs +372 -0
  34. package/src/core/skill-backup.mjs +95 -0
  35. package/src/core/skill-lifecycle.mjs +265 -0
  36. package/src/core/skill-usage.mjs +119 -0
  37. package/src/core/skills.mjs +28 -2
  38. package/src/core/sqlite-runtime.mjs +35 -0
  39. package/src/core/write-approval.mjs +13 -9
  40. package/src/host/rest-client.mjs +70 -0
  41. package/src/provider/config.mjs +187 -0
  42. package/src/provider/openviking-rest.mjs +742 -0
  43. package/src/provider/runtime.mjs +417 -0
  44. package/src/provider/wiring.mjs +164 -0
package/src/core/home.mjs CHANGED
@@ -13,6 +13,8 @@
13
13
 
14
14
  const DIR_NAME = "opencode-growth"
15
15
  const ENV_VAR = "OCG_HOME"
16
+ /** 兼容覆盖用的历史变量名:装着这一份的人多半是被 shim 写的 `OCG_STORE`,它比 `OCG_HOME` 更具体。 */
17
+ const ENV_STORE = "OCG_STORE"
16
18
 
17
19
  const clean = (v) => (typeof v === "string" && v.trim() ? v.trim() : null)
18
20
 
@@ -32,30 +34,63 @@ export function platformDefaultHome({ platform = process.platform, env = {}, hom
32
34
  return home ? `${home}/.${DIR_NAME}` : null
33
35
  }
34
36
 
35
- /** 完整解析顺序:override → 环境变量 → 平台默认;拿不到 ⇒ null(不猜)。 */
36
- export function resolveStoreHome({ platform = process.platform, env = {}, homeDir = null, override = null } = {}) {
37
- const hi = clean(override)
38
- if (hi) return hi
39
- const fromEnv = clean(env?.[ENV_VAR])
40
- if (fromEnv) return fromEnv
41
- return platformDefaultHome({ platform, env, homeDir })
37
+ /**
38
+ * **三个入口共用的一条规则**(真实 CLI / 安装器 / 插件接线;照 Hermes `get_hermes_home`:
39
+ * 显式 override → 环境变量 → 平台默认,我们的环境变量多一个历史名):
40
+ *
41
+ * 显式 override(`--store`) > `$OCG_STORE`(兼容覆盖) > `$OCG_HOME` > 平台默认
42
+ *
43
+ * 为什么 `$OCG_STORE` 压过 `$OCG_HOME`:装好的宿主里 shim 会写 `OCG_STORE`,若被另一个
44
+ * 变量悄悄压过去,等于**把已装的那份库换掉**(数据正确性级)。优先级反过来就静默换库了。
45
+ *
46
+ * 返回值把「值哪来的」摊开,好让冲突**看得见**而不是被静默挑一个:
47
+ * · `source` ∈ `explicit` | `env` | `default` | `null`
48
+ * · `via` ∈ `override` | `OCG_STORE` | `OCG_HOME` | `platform-default` | `null`
49
+ * · `conflicts` = 被压过、且**指向不同路径**的那些候选(同值不算冲突)
50
+ *
51
+ * **零副作用**:本函数只做字符串解析,不建目录、不搬数据 —— 挑到哪个根就在哪个根干活。
52
+ */
53
+ export function resolveStoreRoot({ platform = process.platform, env = {}, homeDir = null, override = null } = {}) {
54
+ const candidates = [
55
+ { via: "override", value: clean(override) },
56
+ { via: ENV_STORE, value: clean(env?.[ENV_STORE]) },
57
+ { via: ENV_VAR, value: clean(env?.[ENV_VAR]) },
58
+ ]
59
+ const picked = candidates.findIndex((c) => c.value)
60
+ if (picked >= 0) {
61
+ const chosen = candidates[picked]
62
+ const conflicts = candidates
63
+ .slice(picked + 1)
64
+ .filter((c) => c.value && c.value !== chosen.value)
65
+ .map(({ via, value }) => ({ via, value }))
66
+ return {
67
+ store: chosen.value,
68
+ source: chosen.via === "override" ? "explicit" : "env",
69
+ via: chosen.via,
70
+ conflicts,
71
+ }
72
+ }
73
+ const dflt = platformDefaultHome({ platform, env, homeDir })
74
+ return { store: dflt, source: dflt ? "default" : null, via: dflt ? "platform-default" : null, conflicts: [] }
42
75
  }
43
76
 
77
+ /** 完整解析顺序:override → 环境变量 → 平台默认;拿不到 ⇒ null(不猜)。 */
78
+ export function resolveStoreHome(args = {}) {
79
+ return resolveStoreRoot(args).store
80
+ }
44
81
 
45
82
  /**
46
- * **安装器**用的解析(照 `docs/PENDING-STAGE4.md` §1:安装器与运行时同一规则;CLI 仍无默认)。
47
- * · 调用方给了 store ⇒ `source: "explicit"`
48
- * · 否则 `$OCG_HOME` ⇒ `source: "env"`
49
- * · 否则平台默认 ⇒ `source: "default"`
50
- * · 都拿不到 ⇒ `store: null`(调用方必须报错,不许猜)
51
- * 注意:**CLI 不调用本函数**——`oc-grow` 始终要求 `--store`/`$OCG_STORE`;
52
- * 运行时(插件)也不自己挑目录,它用安装器写进 shim 的那一个。
83
+ * **安装器**用的解析(照 `docs/PENDING-STAGE4.md` §1:安装器与运行时同一规则)。
84
+ * 只保留两键形状(`{store, source}`)给既有调用点与检查器;完整来源(谁压过谁)走 `resolveStoreRoot`。
53
85
  */
54
- export function resolveInstallStore({ override = null, platform = process.platform, env = {}, homeDir = null } = {}) {
55
- const hi = clean(override)
56
- if (hi) return { store: hi, source: "explicit" }
57
- const fromEnv = clean(env?.[ENV_VAR])
58
- if (fromEnv) return { store: fromEnv, source: "env" }
59
- const dflt = platformDefaultHome({ platform, env, homeDir })
60
- return { store: dflt, source: dflt ? "default" : null }
86
+ export function resolveInstallStore(args = {}) {
87
+ const { store, source } = resolveStoreRoot(args)
88
+ return { store, source }
61
89
  }
90
+
91
+
92
+ /**
93
+ * 旧口径的残留说明(已被上面的统一规则取代,留一行免得有人照旧注释去找不存在的第二份实现):
94
+ * · 曾写过「CLI 仍无默认、插件只认 `$OCG_STORE`」——那是**三套规则**,现在统一成 `resolveStoreRoot`。
95
+ * · 诚实边界:解析本身**不做任何迁移**;换根只会让工具在新根上干活,旧根的数据原地不动。
96
+ */
@@ -0,0 +1,298 @@
1
+ // 片 3(W16「学到了什么」时间线)payload 层 —— 照 56-设计稿-v2 §5.3/§5.4/§5.5。
2
+ //
3
+ // 产品主语(签核①):**当前对象图 + 已证实事件层**。nodes[] 只装当前对象(memory/skill),
4
+ // 候选与生命周期事件进 ocg.*;一切时间是 epoch 秒;未知 ≠ 零(null + unavailable)。
5
+ // 读路径纯只读:本模块不许出现任何写 API(判据 ③ 的写拒绝探针会抓住它)。
6
+ import fs from "node:fs"
7
+ import path from "node:path"
8
+ import { createHash } from "node:crypto"
9
+
10
+ import { ENTRY_DELIMITER } from "./memories.mjs"
11
+
12
+ const sha256 = (b) => createHash("sha256").update(b).digest("hex")
13
+ const toEpoch = (iso) => { const t = Date.parse(iso ?? ""); return Number.isFinite(t) ? Math.floor(t / 1000) : null }
14
+
15
+ /** journey 命令面(§5.5-⑤ 表驱动:只读,无任何写动作)。 */
16
+ export const JOURNEY_COMMANDS = Object.freeze([
17
+ { name: "journey", writes: false },
18
+ { name: "journey list", writes: false },
19
+ ])
20
+
21
+ const readText = (f) => { try { return fs.readFileSync(f, "utf8") } catch { return null } }
22
+ const fileSha = (f) => { const t = readText(f); return t === null ? null : sha256(Buffer.from(t)) }
23
+
24
+ /** 常驻条目 = ENTRY_DELIMITER 切块(照 Hermes:每个非空 chunk 一张卡);返回块文本 + 起始行号。 */
25
+ function residentChunks(file, rel) {
26
+ const raw = readText(file)
27
+ if (raw === null) return []
28
+ const out = []
29
+ let cursor = 0
30
+ for (const chunk of raw.split(ENTRY_DELIMITER)) {
31
+ // 行号 = 块内首个非空行在原文里的行(分隔符 \n§\n 自带两个换行,必须按原文位置数,不能数切片)
32
+ const idx = raw.indexOf(chunk, cursor)
33
+ const start = idx < 0 ? cursor : idx
34
+ cursor = start + Math.max(chunk.length, 1)
35
+ const m = /[^\n].*/.exec(chunk)
36
+ const lead = m ? m.index : 0
37
+ const line = raw.slice(0, start + lead).split("\n").length
38
+ const text = chunk.replace(/^\n+|\n+$/g, "")
39
+ if (text.trim()) out.push({ text, line, file: rel })
40
+ }
41
+ return out
42
+ }
43
+
44
+ function auditEvents(L) {
45
+ const out = []
46
+ let files = []
47
+ try { files = fs.readdirSync(L.audit).filter((f) => f.endsWith(".jsonl")).sort() } catch { return { out, unreadable: 0 } }
48
+ let unreadable = 0
49
+ for (const f of files) {
50
+ const abs = path.join(L.audit, f)
51
+ const raw = readText(abs)
52
+ if (raw === null) { unreadable += 1; continue }
53
+ const fsha = sha256(Buffer.from(raw))
54
+ let line = 0
55
+ for (const row of raw.split("\n")) {
56
+ line += 1
57
+ if (!row.trim()) continue
58
+ let rec
59
+ try { rec = JSON.parse(row) } catch { unreadable += 1; continue }
60
+ out.push({ rec, type: rec.event ?? "unknown", ts: toEpoch(rec.ts), source: { file: `audit/${f}`, line, sha256: fsha } })
61
+ }
62
+ }
63
+ return { out, unreadable }
64
+ }
65
+
66
+ /**
67
+ * 构造机读 payload(§5.3)。
68
+ * opts: { since=epoch|null(只过滤有时间证据的项), sinceLabel, now=epoch(确定时钟), run=运行绑定 }
69
+ */
70
+ export function buildJourney(L, { since = null, sinceLabel = null, now = null, run = null } = {}) {
71
+ const clock = now ?? Math.floor(Date.now() / 1000)
72
+ const hidden = { n: 0 }
73
+ const inWindow = (t) => (since == null ? true : t != null ? t >= since : true) // 未知时间单列,不隐藏
74
+ const take = (t) => { if (since != null && t != null && t < since) { hidden.n += 1; return false } return true }
75
+
76
+ // ── 当前对象图:常驻两库(未知时间 ⇒ timestamp=null)+ 技能 ──────────────
77
+ const nodes = []
78
+ const memCards = []
79
+ for (const [rel, memorySource] of [["memories/MEMORY.md", "memory"], ["memories/USER.md", "profile"]]) {
80
+ const abs = path.join(L.root, rel)
81
+ const fsha = fileSha(abs)
82
+ for (const c of residentChunks(abs, rel)) {
83
+ const label = c.text.split("\n")[0].trim()
84
+ const id = `memory:${rel}:${c.line}`
85
+ if (!take(null)) continue // 常驻条目永不因 --since 隐藏(take(null) 恒真,占位语义明确)
86
+ nodes.push({
87
+ id, label, kind: "memory", timestamp: null, category: "memory",
88
+ useCount: 0, state: "published", createdBy: "memory", pinned: false, memorySource,
89
+ source: { file: rel, line: c.line, timeBasis: "file_mtime", sha256: fsha },
90
+ })
91
+ memCards.push({ source: memorySource, timestamp: null, title: label, body: c.text })
92
+ }
93
+ }
94
+
95
+ const skillRoot = path.join(L.root, "skills")
96
+ let skillNames = []
97
+ try { skillNames = fs.readdirSync(skillRoot, { withFileTypes: true }).filter((e) => e.isDirectory() && fs.existsSync(path.join(skillRoot, e.name, "SKILL.md"))).map((e) => e.name).sort() } catch {}
98
+ for (const name of skillNames) {
99
+ const rel = `skills/${name}/SKILL.md`
100
+ const abs = path.join(L.root, rel)
101
+ let category = "skill"
102
+ const raw = readText(abs) ?? ""
103
+ const m = /^category:\s*(\S+)/m.exec(raw)
104
+ if (m) category = m[1]
105
+ // createdBy 是认账要素(S4 三分保护的判据之一):frontmatter 说了算,缺省才回退 agent——
106
+ // 真机演示撞过硬编码:frontmatter `created_by: user`、节点却写死 "agent",视图与记录矛盾。
107
+ const cbm = /^created_by:\s*(\S+)/m.exec(raw)
108
+ const createdBy = cbm ? cbm[1] : "agent"
109
+ let mtime = null
110
+ try { mtime = Math.floor(fs.statSync(abs).mtimeMs / 1000) } catch {}
111
+ if (!take(mtime)) continue
112
+ nodes.push({
113
+ id: `skill:${name}`, label: name, kind: "skill", timestamp: mtime, category,
114
+ useCount: null, state: "active", createdBy, pinned: false,
115
+ source: { file: rel, line: 1, timeBasis: "file_mtime", sha256: fileSha(abs) },
116
+ })
117
+ }
118
+
119
+ // ── 边:只装现有证据能证明的(常驻条目正文提到技能名 ⇒ memory→skill)────────
120
+ const edges = []
121
+ const nodeIds = new Set(nodes.map((n) => n.id))
122
+ for (const n of nodes.filter((x) => x.kind === "memory")) {
123
+ const card = memCards.find((c) => c.title === n.label) ?? { body: "" }
124
+ for (const s of nodes.filter((x) => x.kind === "skill")) {
125
+ if (card.body.includes(s.label) && nodeIds.has(n.id) && nodeIds.has(s.id)) edges.push({ source: n.id, target: s.id })
126
+ }
127
+ }
128
+
129
+ // ── clusters / stats(Hermes 语义:stats.nodes 只数技能;categories 不含 memory)──
130
+ const clustersMap = new Map()
131
+ for (const n of nodes) clustersMap.set(n.category, (clustersMap.get(n.category) ?? 0) + 1)
132
+ const clusters = [...clustersMap].map(([category, count]) => ({ category, count }))
133
+ const skillNodes = nodes.filter((n) => n.kind === "skill")
134
+ const memNodes = nodes.filter((n) => n.kind === "memory")
135
+ const stats = {
136
+ nodes: skillNodes.length,
137
+ memory_nodes: memNodes.length,
138
+ memory_skill_edges: edges.length,
139
+ learned_skills: skillNodes.length,
140
+ categories: [...new Set(skillNodes.map((n) => n.category))],
141
+ scope: "filtered_subgraph",
142
+ unavailable: ["used", "skill.useCount"],
143
+ }
144
+
145
+ // ── 已证实事件层:audit + 快照冻结 + 纠正捕获 ──────────────────────────
146
+ const events = []
147
+ let unboundEvents = 0
148
+ const { out: auditRows, unreadable } = auditEvents(L)
149
+ for (const a of auditRows) {
150
+ if (a.ts != null && !take(a.ts)) continue
151
+ let subjectRef = null
152
+ if (a.type === "forget" && a.rec.match) {
153
+ const hit = nodes.filter((n) => n.kind === "memory" && (memCards.find((c) => c.title === n.label)?.body ?? "").includes(a.rec.match))
154
+ if (hit.length === 1) subjectRef = { kind: "node", id: hit[0].id }
155
+ } else if (a.type === "publish" && a.rec.candidateId) {
156
+ subjectRef = { kind: "candidate", id: a.rec.candidateId }
157
+ } else if ((a.type === "skill-create" || a.type === "skill-patch") && a.rec.name) {
158
+ // 技能写事件绑到技能节点(同名唯一才绑;绑不上的照旧计 unbound)
159
+ const hit = nodes.filter((n) => n.kind === "skill" && n.label === a.rec.name)
160
+ if (hit.length === 1) subjectRef = { kind: "node", id: hit[0].id }
161
+ }
162
+ if (subjectRef === null) unboundEvents += 1
163
+ events.push({
164
+ id: `ev:${a.source.file}:${a.source.line}`, type: a.type, timestamp: a.ts,
165
+ subjectRef, source: a.source, actor: a.rec.approvedBy ?? null, sessionId: a.rec.sessionId ?? null,
166
+ })
167
+ }
168
+ // 快照冻结(命名 frozen,不叫 injected —— §5.4)
169
+ let snapFiles = []
170
+ const snapDir = path.join(L.root, "snapshots") // 真值:root/snapshots/<sessionID>.json(snapshot.mjs:35)
171
+ try { snapFiles = fs.readdirSync(snapDir).filter((f) => f.endsWith(".json")).sort() } catch {}
172
+ for (const f of snapFiles) {
173
+ const rel = `snapshots/${f}`
174
+ const rec = (() => { const t = readText(path.join(snapDir, f)); try { return JSON.parse(t) } catch { return null } })()
175
+ if (!rec) continue
176
+ const t = toEpoch(rec.frozenAt)
177
+ if (t != null && !take(t)) continue
178
+ events.push({
179
+ id: `ev:${rel}`, type: "frozen", timestamp: t,
180
+ subjectRef: rec.sessionID ? { kind: "session", id: rec.sessionID } : null,
181
+ source: { file: rel, sha256: fileSha(path.join(snapDir, f)) },
182
+ actor: null, sessionId: rec.sessionID ?? null,
183
+ })
184
+ }
185
+ // 纠正捕获(append-only 队列;行内自带正文 ⇒ 不计 unbound)
186
+ {
187
+ const raw = readText(L.learnQueue)
188
+ if (raw !== null) {
189
+ const fsha = sha256(Buffer.from(raw))
190
+ let line = 0
191
+ for (const row of raw.split("\n")) {
192
+ line += 1
193
+ if (!row.trim()) continue
194
+ let rec
195
+ try { rec = JSON.parse(row) } catch { continue }
196
+ const t = toEpoch(rec.ts ?? rec.at ?? rec.timestamp)
197
+ if (t != null && !take(t)) continue
198
+ events.push({
199
+ id: `ev:state/learn-queue.jsonl:${line}`, type: "capture", timestamp: t,
200
+ subjectRef: null, source: { file: "state/learn-queue.jsonl", line, sha256: fsha },
201
+ actor: null, sessionId: rec.sessionId ?? null,
202
+ })
203
+ }
204
+ }
205
+ }
206
+
207
+ // ── candidates 投影(不进 nodes)──────────────────────────────────────
208
+ const candidates = []
209
+ let candFiles = []
210
+ try { candFiles = fs.readdirSync(L.candidates).filter((f) => f.endsWith(".json")).sort() } catch {}
211
+ for (const f of candFiles) {
212
+ const rel = `candidates/${f}`
213
+ const rec = (() => { const t = readText(path.join(L.candidates, f)); try { return JSON.parse(t) } catch { return null } })()
214
+ if (!rec) continue
215
+ const created = toEpoch(rec.createdAt)
216
+ if (created != null && !take(created)) continue
217
+ candidates.push({
218
+ id: rec.id, createdAt: created, kind: rec.kind, status: rec.status,
219
+ review: { state: rec.review?.state ?? null, reviewedAt: toEpoch(rec.review?.reviewedAt), reviewedBy: rec.review?.reviewedBy ?? null },
220
+ evidenceIds: rec.evidenceIds ?? [], source: { file: rel },
221
+ })
222
+ }
223
+
224
+ // ── 待批计数 ────────────────────────────────────────────────────────
225
+ let pending = 0
226
+ try { pending = fs.readdirSync(path.join(L.root, "pending")).filter((f) => f.endsWith(".json")).length } catch {} // 真值:root/pending
227
+
228
+ const unknownTime = nodes.filter((n) => n.timestamp === null).length
229
+ const window = since == null ? "all" : (sinceLabel ?? `${(clock - since) / 86400}d`)
230
+ const ocgRun = { clock, args: run?.args ?? null, digest: run?.digest ?? fileSha(path.join(L.root, "memories", "MEMORY.md")), identity: run?.identity ?? "ocg" }
231
+
232
+ return {
233
+ nodes, edges, clusters, memory: memCards, stats,
234
+ ocg: {
235
+ schemaVersion: "1",
236
+ candidates, events, pending,
237
+ coverage: { unknownTime, unboundEvents, unreadableEvidence: unreadable },
238
+ window,
239
+ filter: { since, hidden: hidden.n },
240
+ run: ocgRun,
241
+ },
242
+ }
243
+ }
244
+
245
+ /** §5.5-② 全量核验(不是抽 3 条):逐节点核 source 的文件/行/label/hash。 */
246
+ export function verifyAllNodes(payload, root) {
247
+ const problems = []
248
+ let checked = 0
249
+ for (const n of payload.nodes ?? []) {
250
+ checked += 1
251
+ const abs = path.join(root, n.source?.file ?? "")
252
+ const raw = readText(abs)
253
+ if (raw === null) { problems.push(`${n.id}: 来源文件不存在 ${n.source?.file}`); continue }
254
+ const fsha = sha256(Buffer.from(raw))
255
+ if (n.source.sha256 !== fsha) problems.push(`${n.id}: hash 与磁盘不符`)
256
+ if (n.kind === "memory") {
257
+ const lineText = (raw.split("\n")[n.source.line - 1] ?? "").trim()
258
+ if (lineText !== n.label) problems.push(`${n.id}: label 与 ${n.source.file}:${n.source.line} 不符`)
259
+ } else if (n.kind === "skill") {
260
+ const dirName = path.basename(path.dirname(n.source.file))
261
+ if (dirName !== n.label) problems.push(`${n.id}: 技能名与目录不符(${dirName} ≠ ${n.label})`)
262
+ }
263
+ }
264
+ return { checked, problems, status: checked === 0 ? "zero-coverage" : problems.length ? "fail" : "ok" }
265
+ }
266
+
267
+ /** §5.5-④ 闸绑定本次运行:绑定核对 + 语义不变量(反例四连的靶子)。 */
268
+ export function journeyInvariants(payload, { run } = {}) {
269
+ const problems = []
270
+ // 绑定本次运行(时钟/参数/摘要/身份)——把本次证据换成旧 run 的合法 {} ⇒ 红
271
+ const r = payload.ocg?.run
272
+ if (!run || !r) { problems.push("缺运行绑定(run)—— 证据包必须绑定本次运行") }
273
+ else {
274
+ for (const k of ["clock", "digest", "identity"]) {
275
+ if (r[k] !== run[k]) problems.push(`run.${k} 与本次运行不符(${r[k]} ≠ ${run[k]})`)
276
+ }
277
+ if (JSON.stringify(r.args ?? null) !== JSON.stringify(run.args ?? null)) problems.push("run.args 与本次运行不符")
278
+ }
279
+ const unavailable = new Set(payload.stats?.unavailable ?? [])
280
+ for (const n of payload.nodes ?? []) {
281
+ if (n.kind === "skill") {
282
+ if (unavailable.has("skill.useCount") && n.useCount !== null) problems.push(`${n.id}: skill.useCount 是 UNKNOWN,不许用 0 冒充`)
283
+ if (!unavailable.has("skill.useCount") && n.useCount === null) problems.push(`${n.id}: useCount=null 但 unavailable 没点名`)
284
+ }
285
+ if (n.kind === "memory" && n.useCount !== 0) problems.push(`${n.id}: memory.useCount 必须是结构性默认 0`)
286
+ if (n.kind === "memory" && n.createdBy !== "memory") problems.push(`${n.id}: createdBy 不许拿批准人冒充`)
287
+ }
288
+ const ids = new Set((payload.nodes ?? []).map((n) => n.id))
289
+ for (const e of payload.edges ?? []) {
290
+ if (!ids.has(e.source)) problems.push(`边端点缺失:${e.source}`)
291
+ if (!ids.has(e.target)) problems.push(`边端点缺失:${e.target}`)
292
+ }
293
+ const skillCount = (payload.nodes ?? []).filter((n) => n.kind === "skill").length
294
+ if (payload.stats?.nodes !== skillCount) problems.push(`stats.nodes 只许数技能节点(${payload.stats?.nodes} ≠ ${skillCount})—— 混入 candidate/其它即红`)
295
+ if (payload.stats?.learned_skills !== skillCount) problems.push("stats.learned_skills 与技能节点数不符")
296
+ if ((payload.stats?.categories ?? []).includes("memory")) problems.push("stats.categories 不含 memory(Hermes 语义)")
297
+ return problems
298
+ }
package/src/core/lock.mjs CHANGED
@@ -21,6 +21,12 @@ function readOwner(lockPath) {
21
21
  }
22
22
 
23
23
  function tryAcquire(lockPath, meta) {
24
+ // 锁的父目录由锁自己保证存在:`<store>/state/` 在全新安装里是**按需创建**的
25
+ // (doctor 就是这么标它的),而 acquire 只会 mkdir 锁目录本身 ⇒ 真机上第一次写
26
+ // 会以 `ENOENT: mkdir …/state/commit.lock` 崩掉(实测 2026-09-23,`memory forget`
27
+ // 与待批批准都踩)。建锁的父目录不是"修复 store"(那是 main.mjs 刻意不做的),
28
+ // 它只是锁自己的地基。
29
+ fs.mkdirSync(path.dirname(lockPath), { recursive: true })
24
30
  try {
25
31
  fs.mkdirSync(lockPath)
26
32
  } catch (e) {
@@ -12,13 +12,14 @@ import { scanForThreats } from "./threats.mjs"
12
12
  // 这条来自 D16/W8 与契约 C03——把人手编辑静默丢弃,人不知道为什么。
13
13
  // 3. **origin 由启动器登记的会话身份决定**,调用方自报无效(extra#4):
14
14
  // 后台 `add` 直接写(D16 照 Hermes 的 `_background_delete_gate`),改/删强制暂存;
15
- // 身份不明则一律暂存。
15
+ // **闸关档(默认)不看来源直接生效;闸开档**身份不明 ⇒ 暂存(判定真源=`write-approval.decideWrite`,D73)。
16
16
  //
17
17
  // 并发与崩溃:**锁内重读-修改-原子替换**(写临时文件 + rename)。
18
18
  // 这条不是洁癖:G1 里已实测过"并发消费 → 1 条队列提炼出 2 个候选"。
19
19
  import fs from "node:fs"
20
20
  import { sha256 } from "./ids.mjs"
21
21
  import path from "node:path"
22
+ import { decideWrite } from "./write-approval.mjs"
22
23
 
23
24
  /** 与 Hermes 的 `ENTRY_DELIMITER` 逐字一致。改它等于换磁盘格式,必须先改契约。 */
24
25
  export const ENTRY_DELIMITER = "\n§\n"
@@ -82,6 +83,42 @@ export function findEntryIndex(entries, match) {
82
83
  return hits[0][1]
83
84
  }
84
85
 
86
+ /** 批量动作枚举(本仓原语名:add/update/remove;Hermes 叫 add/replace/remove)。 */
87
+ export const BATCH_ACTIONS = Object.freeze(["add", "update", "remove"])
88
+
89
+ /**
90
+ * **整批预扫**(照 Hermes `memory_tool_store.py:414-419` 的 pre-scan):把每一笔的**形态**
91
+ * 与**内容**先看一遍,任一不合格就以「第 N 项」为口径拒掉**整批**——扫描必须发生在任何落盘之前,
92
+ * 包括「暂存」那条路径(先暂存再查=坏内容已经写进待批文件,那也是一次落盘)。
93
+ * 导出它,是因为工具层的门控要先跑同一次扫描,两处必须是**同一个实现**。
94
+ */
95
+ export function scanBatchOps(operations) {
96
+ const ops = Array.isArray(operations) ? operations : []
97
+ if (!ops.length) throw new Error("operations 不能为空:批量至少要有一项(单条写请用 add/update/remove)")
98
+ ops.forEach((op, i) => {
99
+ const at = `第 ${i + 1} 项`
100
+ const act = op?.action
101
+ if (!BATCH_ACTIONS.includes(act)) throw new Error(`${at}:action 只能是 ${BATCH_ACTIONS.join(" / ")}(收到 ${JSON.stringify(act ?? null)})`)
102
+ // 一批只碰一个库:项里夹带 kind 一律拒(否则「以为写 MEMORY、其实写 USER」)
103
+ if (op?.kind !== undefined) {
104
+ throw new Error(`${at}:不许在项里指定 kind —— 一批只碰一个库,库由整批的 kind 决定`)
105
+ }
106
+ const text = op?.text
107
+ if (act !== "remove" && (typeof text !== "string" || !text.trim())) throw new Error(`${at}(${act}):text 不能为空`)
108
+ if (act !== "add" && (typeof op?.match !== "string" || !op.match.trim())) throw new Error(`${at}(${act}):match(内容子串)不能为空`)
109
+ if (act !== "remove") {
110
+ const hits = scanForThreats(text, { scope: "strict" })
111
+ if (hits.length) {
112
+ const e = new Error(`${at}:内容命中威胁模式 ${hits.join(", ")}(整批已拒,未落盘)`)
113
+ e.code = "THREAT_BLOCKED"
114
+ e.patterns = hits
115
+ throw e
116
+ }
117
+ }
118
+ })
119
+ return ops
120
+ }
121
+
85
122
  /** 解析:按**完整分隔符**切(Hermes 的原话:splits on the FULL delimiter so a bare "§" survives)。 */
86
123
  function parse(raw) {
87
124
  const text = String(raw).replace(/^\uFEFF/, "")
@@ -146,9 +183,35 @@ export function createMemoryStore({ root, identity = null, limits = {}, enabled
146
183
  return ORIGINS.includes(o) ? o : "unknown"
147
184
  }
148
185
 
149
- const readRaw = (kind) => {
186
+ /**
187
+ * 严格读(**变更路径**用)。照 `~/.hermes/hermes-agent/tools/memory_tool_store.py:432-447` 的
188
+ * `_read_raw_checked`:非法字节 / 读不到 ⇒ `ok:false`,**绝不把有损视图交出去写回**——
189
+ * 有损解码 + 一次保存 = 用户真实字节被永久替换(Hermes 修过的 #10878 / PR #10888,
190
+ * 正是我们这条 `readRaw → serialize → atomicWrite` 链)。
191
+ * 成功时剥前导 BOM(Hermes 用 `utf-8-sig`):保证"检查过的字节"与"写回的字节"同源。
192
+ */
193
+ const readRawChecked = (kind) => {
150
194
  const p = fileFor(root, kind)
151
- return fs.existsSync(p) ? fs.readFileSync(p, "utf8") : ""
195
+ if (!fs.existsSync(p)) return { ok: true, text: "" }
196
+ let buf
197
+ try {
198
+ buf = fs.readFileSync(p)
199
+ } catch (e) {
200
+ return { ok: false, why: `读不到 ${p}(${e.code ?? e.message})` }
201
+ }
202
+ let text
203
+ try {
204
+ text = new TextDecoder("utf-8", { fatal: true }).decode(buf)
205
+ } catch {
206
+ return { ok: false, why: `${p} 不是合法的 UTF-8` }
207
+ }
208
+ return { ok: true, text: text.replace(/^\uFEFF/, "") }
209
+ }
210
+
211
+ /** 容忍读(**只读路径**用:注入/状态/检索)。照 Hermes:读不回来就当空;它绝不允许参与写回。 */
212
+ const readRaw = (kind) => {
213
+ const r = readRawChecked(kind)
214
+ return r.ok ? r.text : ""
152
215
  }
153
216
 
154
217
  const read = ({ kind = "memory" } = {}) => {
@@ -193,7 +256,10 @@ export function createMemoryStore({ root, identity = null, limits = {}, enabled
193
256
  if (!enabledOf(kind)) throw new Error(`这个库已被关闭(disabled):${kind}`)
194
257
  const release = acquireLock(root)
195
258
  try {
196
- const before = parse(readRaw(kind))
259
+ // 变更路径一律走**严格读**:读不回来就拒写,一字不动(Hermes 的 `_read_raw_checked` 口径)。
260
+ const raw = readRawChecked(kind)
261
+ if (!raw.ok) throw new Error(`拒绝写回:${raw.why}——改回可读之前不会覆盖它`)
262
+ const before = parse(raw.text)
197
263
  const after = fn(before)
198
264
  const next = serialize(after)
199
265
  if (next.length > limitOf(kind)) throw overLimitError(kind, next.length, limitOf(kind))
@@ -259,9 +325,9 @@ export function createMemoryStore({ root, identity = null, limits = {}, enabled
259
325
  })
260
326
 
261
327
  /**
262
- * 对外的三个写入口:**先按登记身份决定要不要暂存**,再落到上面三个原语。
263
- * 后台:add 直接写(D16 照 Hermes 的 `_background_delete_gate`),改/删暂存。
264
- * 身份不明:一律暂存(extra#4)。
328
+ * 对外的三个写入口:**先过写入闸门**(判定交 `decideWrite`——只有一处真源),再落到上面三个原语。
329
+ * 闸关档(默认):不看来源,直接生效(D73 照 Hermes `write_approval.py:175`)。
330
+ * 闸开档:后台 / 身份不明 ⇒ 暂存;前台且有交互通道 ⇒ 内联问一次。
265
331
  *
266
332
  * 一律返回 promise:调用方(工具层/插件)要能统一 `try/catch` 与 `await`,
267
333
  * 而不是"有时同步抛、有时拒绝"。**锁内仍然是纯同步的**——`mutate` 里没有任何 `await`,
@@ -280,11 +346,102 @@ export function createMemoryStore({ root, identity = null, limits = {}, enabled
280
346
  }
281
347
  }
282
348
  const origin = originOf()
283
- const direct = origin === "foreground" || (origin === "background" && op === "add")
284
- if (direct) return run()
349
+ // **门控只有一处真源**:判定交给 `decideWrite`(照 Hermes 只有一个 `evaluate_gate`)。
350
+ // 这里曾经另写一套「只看 origin」的规则 ⇒ 同一个政策两份实现、口径必然漂移(2026-09-23 合并,D73):
351
+ // · store 面没有交互通道(`interactive:false`)⇒ 闸开时前台也只会 stage,不会 ask;
352
+ // · store 面没有宿主 permission 面(`hostPermission` 不传)⇒ 不会有 `deny`——
353
+ // 宿主的 `permission.ocg_memory_write=deny` 在插件层就被拦掉了,到不了这里;
354
+ // 万一哪天真有 deny 落到这里,下面的分支把它当"不写"处理(进待批,不是静默丢弃)。
355
+ const decision = decideWrite({
356
+ root,
357
+ subsystem: payload?.subsystem === "skills" ? "skills" : "memory",
358
+ origin,
359
+ destructive: op !== "add",
360
+ interactive: false,
361
+ })
362
+ if (decision === "apply") return run()
285
363
  return { staged: stage({ op, origin, kind: payload.kind ?? "memory", ...payload }) }
286
364
  }
287
365
 
366
+ /**
367
+ * 批量原子(G3;照 Hermes `apply_batch`/`_batch`,:397-470):
368
+ * ① 空批 ⇒ 拒(`scanBatchOps`);
369
+ * ② **先扫全批**(形态 + 威胁模式),任一坏弹整批拒;
370
+ * ③ 工作副本按序应用,任一项寻址失败 ⇒ 第 N 项点名、整批不写(`mutate` 只在 fn 正常返回后才落盘);
371
+ * ④ 非空库不许被这一批清空(单条 remove 才是有意清空的路);
372
+ * ⑤ 预算只看**最终态**(`mutate` 里那一次检查就是终态;中间态不检);
373
+ * ⑥ `dryRun` ⇒ 同一套检查、不落盘、回每项选中的整条老内容。
374
+ * **一批只碰一个库**(kind 由整批决定,项里不许再带)。
375
+ */
376
+ const batch = ({ kind = "memory", operations, dryRun = false } = {}) => {
377
+ if (!KINDS.includes(kind)) throw new Error(`未知的库:${kind}`)
378
+ if (!enabledOf(kind)) throw new Error(`这个库已被关闭(disabled):${kind}`)
379
+ const ops = scanBatchOps(operations)
380
+
381
+ /** 在给定条目集上按序应用;失败带「第 N 项」口径。 */
382
+ const apply = (entries) => {
383
+ const working = entries.slice()
384
+ const matched = []
385
+ ops.forEach((op, i) => {
386
+ const act = op.action
387
+ let prev = null
388
+ try {
389
+ if (act === "add") working.push(op.text.trim())
390
+ else {
391
+ const idx = findOne(working, op.match)
392
+ prev = working[idx]
393
+ if (act === "update") working[idx] = op.text.trim()
394
+ else working.splice(idx, 1)
395
+ }
396
+ } catch (e) {
397
+ throw new Error(`第 ${i + 1} 项(${act}):${e?.message ?? e}`)
398
+ }
399
+ matched.push(prev)
400
+ })
401
+ if (entries.length && !working.length) {
402
+ throw new Error(
403
+ `拒绝清空:这一批会把本来非空的 ${FILES[kind]} 删空。整批已拒,一字未写。` +
404
+ `要清空请用单条 remove(那才是有意清空的路),或保留至少一条。`,
405
+ )
406
+ }
407
+ return { working, matched }
408
+ }
409
+
410
+ if (dryRun) {
411
+ const raw = readRawChecked(kind)
412
+ if (!raw.ok) throw new Error(`拒绝解析:${raw.why}`)
413
+ const { working, matched } = apply(parse(raw.text))
414
+ const next = serialize(working)
415
+ if (next.length > limitOf(kind)) throw overLimitError(kind, next.length, limitOf(kind))
416
+ return { ok: true, kind, dryRun: true, applied: ops.length, matchedEntries: matched, used: next.length, limit: limitOf(kind), entries: working.length }
417
+ }
418
+
419
+ let matched = []
420
+ const after = mutate(kind, (entries) => {
421
+ const r = apply(entries)
422
+ matched = r.matched
423
+ return r.working
424
+ })
425
+ const used = serialize(after).length
426
+ return { ok: true, kind, dryRun: false, applied: ops.length, matchedEntries: matched, used, limit: limitOf(kind), entries: after.length }
427
+ }
428
+
429
+ /** 批量版门控:扫描(同实现)→ `decideWrite` → apply 或**整批**暂存。 */
430
+ const gateBatch = (payload = {}) => {
431
+ const kind = payload?.kind ?? "memory"
432
+ const ops = scanBatchOps(payload?.operations) // ← 先于门控:坏内容不许以「暂存」形式落盘
433
+ const origin = originOf()
434
+ const decision = decideWrite({
435
+ root,
436
+ subsystem: "memory",
437
+ origin,
438
+ destructive: ops.some((o) => o.action !== "add"),
439
+ interactive: false,
440
+ })
441
+ if (decision === "apply") return batch({ ...payload, kind })
442
+ return { staged: stage({ op: "batch", origin, kind, operations: ops, ...(payload?.subsystem ? { subsystem: payload.subsystem } : {}) }) }
443
+ }
444
+
288
445
  return {
289
446
  root,
290
447
  read,
@@ -298,9 +455,29 @@ export function createMemoryStore({ root, identity = null, limits = {}, enabled
298
455
  // mutate:锁内重读-改-写 + 限额检查 + 同目录临时文件 + rename 原子替换。
299
456
  // ⚠️ 不得暴露到模型动作面(memory-actions 的动作枚举里不许出现它)。
300
457
  writeTrusted: (payload = {}) => add(payload), // 与 add 同门:威胁扫描在里面,命中即拒
458
+ // 受信任改写(规格 §七 第三层,对称于上面两条):待批提案被**人批准**后由处置面调用,
459
+ // 与 writeTrusted/removeTrusted 同门(锁内重读-改-写 + 限额 + 原子替换 + 威胁扫描)。
460
+ // ⚠️ 同样不得暴露到模型动作面。
461
+ updateTrusted: (payload = {}) => update(payload),
301
462
  // 受信任删除(规格 §七 第三层,对称于 writeTrusted):不经入口门控、仍走 mutate(锁内重读-改-写 + 原子替换)。
302
463
  // ⚠️ 同样不得暴露到模型动作面。
303
464
  removeTrusted: (payload = {}) => remove(payload),
304
465
  paths: { file: (kind) => fileFor(root, kind), pendingDir: pendingDir(root) },
466
+ /**
467
+ * 暂存原语(门控里"暂存"那一半的**单一实现**)。给**已经做完判定**的调用方用(动作层),
468
+ * 也供直接调用方在自己判定为 stage 时使用;落点、文件形状、带 `origin` 的口径与 `gate` 内完全同一条路径。
469
+ * ⚠️ 与 writeTrusted 一族同理:它**只负责落待批**(不碰正文),不得暴露到模型动作面。
470
+ */
471
+ /**
472
+ * 批量原子(工具面):先过**同一条写入闸门**(判定只有 `decideWrite` 一处真源;
473
+ * 「破坏性」=这批里有非 add 的动作),闸开+后台/无通道 ⇒ 整批**一个**待批文件
474
+ * (半截暂存会让「批」这个语义失效)。扫描在门控之前(`scanBatchOps` 是同一个实现)。
475
+ */
476
+ batch: (payload = {}) => gateBatch(payload),
477
+ /** 受信任批量(内部:批准待批批量的处置面走它)。⚠️ 与 writeTrusted 一族同理,不得暴露到模型动作面。 */
478
+ batchTrusted: (payload = {}) => batch(payload),
479
+ stageProposal: (payload = {}) =>
480
+ // 多带的字段(如技能提案的 name)原样进待批记录——人要能批,记录就得说清在批什么。
481
+ stage({ ...payload, op: payload.op, origin: payload.origin ?? originOf(), kind: payload.kind ?? "memory", text: payload.text, match: payload.match }),
305
482
  }
306
483
  }