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
@@ -1,6 +1,8 @@
1
1
  import fs from "node:fs"
2
2
  import path from "node:path"
3
3
 
4
+ import { runSkillAction, skillGateFromHostConfig } from "./skill-actions.mjs"
5
+
4
6
  // 后台复习的调度与有界(照 Hermes agent/background_review.py 的口径)
5
7
  // 机制:回合结束触发一次「要不要复习」的检查 → 达阈值才派发 → 一次一个 → 新回合可取消(握手 ≤2s)
6
8
  // 判定的三条(机制/触发/判定)都对齐 Hermes,第一版不加自造物。
@@ -45,6 +47,9 @@ export function createReviewScheduler({
45
47
  interrupt = null,
46
48
  thresholds = REVIEW_THRESHOLDS,
47
49
  now = () => Date.now(),
50
+ // 握手上限可注入:默认照 Hermes 2.0s;夹具用一个小值来证明「到点就放弃」,
51
+ // 不再拿墙钟当判据(满载时 Node24 实测 3.5s,会把语义正确的实现判红)。
52
+ cancelTimeoutMs = REVIEW_LIMITS.cancelTimeoutMs,
48
53
  // C③:**工具可用性前置**(照 Hermes)。mem 记 memory 工具、skills 记宿主 skill 工具;
49
54
  // 值只认 true(可用)/ false(明确不可用)/ null(未知 —— 也当不可用,fail-closed)。
50
55
  //
@@ -113,7 +118,7 @@ export function createReviewScheduler({
113
118
  const kind = inflightKind
114
119
  const timedOut = Symbol("timeout")
115
120
  let timer
116
- const timeout = new Promise((res) => { timer = setTimeout(() => res(timedOut), REVIEW_LIMITS.cancelTimeoutMs) })
121
+ const timeout = new Promise((res) => { timer = setTimeout(() => res(timedOut), cancelTimeoutMs) })
117
122
  const settled = await Promise.race([inFlight.then(() => "done").catch(() => "done"), timeout])
118
123
  clearTimeout(timer)
119
124
  const waitedMs = now() - t0
@@ -176,11 +181,33 @@ export function surfaceLine({ proposals = [], ignored = [] } = {}) {
176
181
  return parts.join(";")
177
182
  }
178
183
 
184
+ /**
185
+ * 一次后台复习的**一行摘要**(照 Hermes `agent/background_review.py::_action_lines` +
186
+ * `summarize_background_review_actions` 的口径:直接写入也要报,不是只有提案才说话)。
187
+ * 什么都没发生(没有写入/提案/拒绝/忽略)⇒ null(Hermes 同样返回空列表,不刷屏)。
188
+ */
189
+ export function backgroundReviewBead({ memoryWritten = 0, memoryStaged = 0, skillWritten = 0, skillStaged = 0, refused = 0, ignored = 0 } = {}) {
190
+ const bits = []
191
+ if (memoryWritten) bits.push(`记忆 +${memoryWritten}`)
192
+ if (memoryStaged) bits.push(`记忆提案 ${memoryStaged}`)
193
+ if (skillWritten) bits.push(`技能 +${skillWritten}`)
194
+ if (skillStaged) bits.push(`技能提案 ${skillStaged}`)
195
+ if (refused) bits.push(`拒绝 ${refused}`)
196
+ if (ignored) bits.push(`忽略 ${ignored}`)
197
+ if (!bits.length) return null
198
+ const tail = memoryStaged + skillStaged > 0 ? "(待批:oc-grow memory pending)" : ""
199
+ return `后台复习:${bits.join(" · ")}${tail}`
200
+ }
201
+
179
202
  // 触发源(对齐 Hermes agent/turn_finalizer.py):宿主 `session.idle` = 回合结束。
180
203
  // 每次回合结束都做一次「要不要复习」的检查;前台新回合先取消在跑的那次(握手 ≤2s)。
181
204
  // 复习本身以**宿主身份**跑在**受限 agent**(只读 plan)里 ⇒ 工具被限定,且发生在宿主会话体系内。
182
205
  export const REVIEW_AGENT = "plan"
183
206
 
207
+ // 后台复习浮出的那一行带这个机器标记(part.metadata.ocg)。消费者(召回查询段、会话索引、学习队列)
208
+ // 用它把「后台通知」和「用户真的说了什么」分开——不靠文本前缀猜。
209
+ export const REVIEW_SURFACE_MARK = "review-surface"
210
+
184
211
  export function createTurnEndHandler({ scheduler, review, sessionId = null } = {}) {
185
212
  if (!scheduler || typeof review !== "function") throw new TypeError("createTurnEndHandler 需要 scheduler 与 review")
186
213
  let lastResult = null
@@ -207,6 +234,11 @@ export function createTurnEndHandler({ scheduler, review, sessionId = null } = {
207
234
  async onUserTurnStart() {
208
235
  return scheduler.cancel("user-turn-start")
209
236
  },
237
+ // S1 通道④的触发源透传:宿主工具迭代(wire 按 callID 去重后)前进调度器计数。
238
+ // skill_manage 用过 ⇒ 重置(照 Hermes turn_iteration_prep)。
239
+ noteIteration(opts = {}) {
240
+ return scheduler.noteIteration(opts)
241
+ },
210
242
  lastResult() { return lastResult },
211
243
  lastKind() { return lastKind },
212
244
  }
@@ -214,11 +246,35 @@ export function createTurnEndHandler({ scheduler, review, sessionId = null } = {
214
246
 
215
247
  // ── 产出的解析与落地 ───────────────────────────────────────────────
216
248
  // 解析:我们自己在提示词里定了格式,所以像解析**契约**一样严格:只认三类行,其余忽略。
249
+ // 技能车道(S1 通道④):`skill: <json>` 单行——闭集只有 create/patch(§6 规则④:
250
+ // 无人值守归档/删除不在闭集 ⇒ 忽略+浮出,绝不落盘)。
251
+ export const SKILL_REVIEW_OPS = Object.freeze(["create", "patch"])
252
+
217
253
  export function parseReviewActions(text) {
218
254
  if (typeof text !== "string" || !text.trim()) return []
219
255
  const out = []
220
256
  for (const raw of text.split("\n")) {
221
257
  const line = raw.trim()
258
+ const sk = /^skill\s*:\s*(.+)$/i.exec(line)
259
+ if (sk) {
260
+ try {
261
+ const obj = JSON.parse(sk[1])
262
+ if (!obj || typeof obj !== "object" || Array.isArray(obj)) throw new Error("not an object")
263
+ out.push({
264
+ skill: true,
265
+ op: typeof obj.op === "string" ? obj.op.toLowerCase() : null,
266
+ name: typeof obj.name === "string" ? obj.name : null,
267
+ description: typeof obj.description === "string" ? obj.description : null,
268
+ content: typeof obj.content === "string" ? obj.content : null,
269
+ old_string: typeof obj.old_string === "string" ? obj.old_string : null,
270
+ new_string: typeof obj.new_string === "string" ? obj.new_string : null,
271
+ })
272
+ } catch {
273
+ // 坏 JSON 不许悄悄丢:记成 malformed 让落地口浮出(解析如契约般严格)
274
+ out.push({ skill: true, malformed: true, raw: sk[1].slice(0, 200) })
275
+ }
276
+ continue
277
+ }
222
278
  const m = /^(add|update|remove)\s*:\s*(.+)$/i.exec(line)
223
279
  if (!m) continue
224
280
  out.push({ op: m[1].toLowerCase(), text: m[2].trim() })
@@ -239,7 +295,9 @@ function stageProposal(pendingDir, op) {
239
295
 
240
296
  // 落地:新增直接写(受信任写入路径);改造/删除**只提案**(硬不变量)且提案必须浮出。
241
297
  export function applyReviewOutcome({ store, actions = [], kind = "memory", gateEnabled = false, entries = null } = {}) {
242
- const { direct, proposals, ignored, mustSurface } = classifyReviewOutcome({ actions, entries })
298
+ // 技能形状的动作走技能车道(applySkillReviewActions);memory 车道只吃 add/update/remove。
299
+ const memActions = (Array.isArray(actions) ? actions : []).filter((a) => a && a.skill !== true)
300
+ const { direct, proposals, ignored, mustSurface } = classifyReviewOutcome({ actions: memActions, entries })
243
301
  // A139:后台复习的写入**必须过写入闸门**(不再用 writeTrusted 旁路)。
244
302
  // 闸开时按 Hermes evaluate_gate:后台来源一律进待批。
245
303
  const pending = gateEnabled
@@ -259,3 +317,57 @@ export function applyReviewOutcome({ store, actions = [], kind = "memory", gateE
259
317
  const surface = (pending.length || ignored.length) ? surfaceLine({ proposals: pending, ignored }) : null
260
318
  return { written, staged, ignored, surface, mustSurface: mustSurface || ignored.length > 0 }
261
319
  }
320
+
321
+ /**
322
+ * 通道④的技能车道落地(S1):`skill: <json>` 动作 → `skill-actions` 动作层。
323
+ * 口径照 60- §5.1.1 的 W8 裁定:回合后通道只动 **agent-created** 技能、create/patch **直写**
324
+ * (闸关时;闸开进同一待批队列——闸门在动作层里自己认,不在这里分叉);
325
+ * 归档/删除不在闭集 ⇒ 忽略+浮出(无人值守删落盘必须红)。
326
+ *
327
+ * 拒绝面必须浮出:动 user-owned / 外部来源 / 校验不过,都带着认账回执进 refused,
328
+ * 浮出行点名「只动 agent-created」——误报已交付的变异会被 test/review-skill-channel4 弄红。
329
+ */
330
+ export async function applySkillReviewActions({ root, actions = [], identity = { origin: PROPOSAL_ORIGIN, agent: REVIEW_AGENT }, externalDirs = undefined, hostConfig = null } = {}) {
331
+ const skillActions = (Array.isArray(actions) ? actions : []).filter((a) => a && a.skill === true)
332
+ let written = 0
333
+ let staged = 0
334
+ const ignored = []
335
+ const refused = []
336
+ for (const a of skillActions) {
337
+ if (a.malformed) {
338
+ ignored.push({ op: "skill", raw: a.raw, reason: "malformed-json" })
339
+ continue
340
+ }
341
+ if (!SKILL_REVIEW_OPS.includes(a.op)) {
342
+ ignored.push({ op: a.op, name: a.name, reason: "unknown-op" })
343
+ continue
344
+ }
345
+ const gate = skillGateFromHostConfig({ hostConfig: hostConfig ?? {}, agent: identity?.agent ?? null, name: a.name ?? "" })
346
+ const r = await runSkillAction({
347
+ root,
348
+ identity,
349
+ action: a.op,
350
+ name: a.name,
351
+ description: a.description,
352
+ content: a.content,
353
+ old_string: a.old_string,
354
+ new_string: a.new_string,
355
+ hostPermission: gate.hostPermission,
356
+ agentSkillEnabled: gate.agentSkillEnabled,
357
+ ...(externalDirs !== undefined ? { externalDirs } : {}),
358
+ })
359
+ if (r.ok === false) refused.push({ op: a.op, name: a.name, error: r.error, receipt: r.receipt ?? null })
360
+ else if (r.staged) staged += 1
361
+ else written += 1
362
+ }
363
+ const surface = (ignored.length || refused.length)
364
+ ? [
365
+ "后台复习:技能面",
366
+ written ? `已写 ${written}` : null,
367
+ staged ? `待批 ${staged}` : null,
368
+ refused.length ? `被拒 ${refused.length}(${refused.map((f) => `${f.op}:${f.name ?? "?"}`).join("、")};只动 agent-created / 宿主闸)` : null,
369
+ ignored.length ? `忽略 ${ignored.length}(${ignored.map((i) => i.op).join("、")})` : null,
370
+ ].filter(Boolean).join(" ")
371
+ : null
372
+ return { written, staged, ignored, refused, surface, mustSurface: ignored.length > 0 || refused.length > 0 }
373
+ }
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) {