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.
@@ -18,9 +18,64 @@ import path from "node:path"
18
18
  import { withCommitLock } from "./lock.mjs"
19
19
  import { appendAudit } from "./audit.mjs"
20
20
  import { createMemoryStore, storeHashOf } from "./memories.mjs"
21
+ import { sha256 } from "./ids.mjs"
22
+ import { runSkillAction } from "./skill-actions.mjs"
23
+ import { snapshotSkills } from "./skill-backup.mjs"
24
+ import { readCreatedBy, SKILL_FILE, skillsDir } from "./skills.mjs"
21
25
 
22
26
  const OPS = ["add", "update", "remove", "batch"]
23
- const KINDS = ["memory", "user"]
27
+ const SKILL_OPS = ["create", "patch"]
28
+ const KINDS = ["memory", "user", "skills"]
29
+
30
+ const MAX_DIFF_LINES = 200
31
+
32
+ /** 行级 diff(够人读就行):公共前缀/后缀之外按行做 LCS,限幅避免大文件拖垮列表。 */
33
+ function lineDiff(oldText, newText) {
34
+ const a = String(oldText ?? "").split("\n")
35
+ const b = String(newText ?? "").split("\n")
36
+ let pre = 0
37
+ while (pre < a.length && pre < b.length && a[pre] === b[pre]) pre++
38
+ let suf = 0
39
+ while (suf < a.length - pre && suf < b.length - pre && a[a.length - 1 - suf] === b[b.length - 1 - suf]) suf++
40
+ const A = a.slice(pre, a.length - suf)
41
+ const B = b.slice(pre, b.length - suf)
42
+ const out = []
43
+ for (let i = 0; i < Math.min(pre, 3); i++) out.push(` ${a[i]}`)
44
+ if (pre > 3) out.push(` …(前 ${pre - 3} 行相同)`)
45
+ if (A.length * B.length <= 40000) {
46
+ const dp = Array.from({ length: A.length + 1 }, () => new Int32Array(B.length + 1))
47
+ for (let i = A.length - 1; i >= 0; i--) {
48
+ for (let j = B.length - 1; j >= 0; j--) {
49
+ dp[i][j] = A[i] === B[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1])
50
+ }
51
+ }
52
+ let i = 0
53
+ let j = 0
54
+ while (i < A.length && j < B.length) {
55
+ if (A[i] === B[j]) { out.push(` ${A[i]}`); i++; j++ }
56
+ else if (dp[i + 1][j] >= dp[i][j + 1]) out.push(`- ${A[i++]}`)
57
+ else out.push(`+ ${B[j++]}`)
58
+ }
59
+ while (i < A.length) out.push(`- ${A[i++]}`)
60
+ while (j < B.length) out.push(`+ ${B[j++]}`)
61
+ } else {
62
+ for (const line of A) out.push(`- ${line}`)
63
+ for (const line of B) out.push(`+ ${line}`)
64
+ }
65
+ if (suf > 0) out.push(` …(后 ${suf} 行相同)`)
66
+ return out.slice(0, MAX_DIFF_LINES).join("\n")
67
+ }
68
+
69
+ /** 技能提案的目标文件与「当初那份」的指纹(approve 时用来判过期)。 */
70
+ function skillTargetOf(L, name) {
71
+ const file = path.join(skillsDir(L.root), String(name), SKILL_FILE)
72
+ return {
73
+ file,
74
+ exists: fs.existsSync(file),
75
+ hash: fs.existsSync(file) ? sha256(fs.readFileSync(file)) : null,
76
+ createdBy: fs.existsSync(file) ? readCreatedBy(file) : null,
77
+ }
78
+ }
24
79
 
25
80
  /** 列出待批提案。origin 保留原值;后台来源标 `[auto]`(照 Hermes,人一眼能看出不是自己提的)。 */
26
81
  export function listPending(L) {
@@ -34,7 +89,7 @@ export function listPending(L) {
34
89
  unreadable = true
35
90
  }
36
91
  const origin = raw.origin ?? "unknown"
37
- return {
92
+ const entry = {
38
93
  file,
39
94
  unreadable,
40
95
  op: raw.op ?? null,
@@ -48,6 +103,35 @@ export function listPending(L) {
48
103
  ops: Array.isArray(raw.operations) ? raw.operations.length : null,
49
104
  stagedAt: raw.stagedAt ?? null,
50
105
  }
106
+ // S3:update/remove 的「批的是哪一条」必须能回答 —— 把人要看的**旧条目全文**取出来。
107
+ // 零命中/歧义如实标出,不挑一条当旧文(批准时 updateTrusted 仍会因歧义失败)。
108
+ if ((raw.kind ?? "memory") !== "skills" && (entry.op === "update" || entry.op === "remove")) {
109
+ const kind = raw.kind === "user" ? "user" : "memory"
110
+ const needle = String(raw.match ?? "")
111
+ let resident = []
112
+ try { resident = store.read({ kind }) ?? [] } catch { resident = [] }
113
+ const hits = needle ? resident.filter((e) => e.includes(needle)) : []
114
+ entry.matchHits = hits.length
115
+ entry.matchState = hits.length === 0 ? "not-found" : hits.length > 1 ? "ambiguous" : "ok"
116
+ entry.oldText = hits.length === 1 ? hits[0] : null
117
+ // 歧义时把命中的条目也带上:人得看出「该写成哪一条」才能改提案。
118
+ entry.oldCandidates = hits.length > 1 ? hits : null
119
+ }
120
+ if (raw.kind === "skills") {
121
+ const target = skillTargetOf(L, raw.name)
122
+ const oldText = target.exists ? fs.readFileSync(target.file, "utf8") : ""
123
+ const newText = raw.op === "create" ? raw.text ?? "" : oldText.replace(String(raw.match ?? ""), String(raw.text ?? ""))
124
+ Object.assign(entry, {
125
+ name: raw.name ?? null,
126
+ description: raw.description ?? null,
127
+ oldText,
128
+ newText,
129
+ diff: lineDiff(oldText, newText),
130
+ // 过期预判:人不用等批准才知道提案已经跟不上了
131
+ stale: raw.op === "create" ? target.exists : !target.exists || (raw.baseHash ? target.hash !== raw.baseHash : false),
132
+ })
133
+ }
134
+ return entry
51
135
  })
52
136
  }
53
137
 
@@ -70,8 +154,16 @@ export function resolvePendingRef(L, ref) {
70
154
  /** 提案本身必须完整——不完整的提案连"可被批准"都不算,报出来让人处置。 */
71
155
  function invalidReason(rec) {
72
156
  if (!rec || typeof rec !== "object") return "提案不是对象"
157
+ const kind = rec.kind ?? "memory"
158
+ if (!KINDS.includes(kind)) return `未知的库:${String(rec.kind)}(可用:${KINDS.join(" / ")})`
159
+ if (kind === "skills") {
160
+ if (!SKILL_OPS.includes(rec.op)) return `未知的技能 op:${String(rec.op)}(可用:${SKILL_OPS.join(" / ")})`
161
+ if (typeof rec.name !== "string" || !rec.name.trim()) return "技能提案缺少 name"
162
+ if (typeof rec.text !== "string" || !rec.text.trim()) return `${rec.op} 提案缺少非空 text`
163
+ if (rec.op === "patch" && (typeof rec.match !== "string" || !rec.match.trim())) return "patch 提案缺少 old_string(match)"
164
+ return null
165
+ }
73
166
  if (!OPS.includes(rec.op)) return `未知的 op:${String(rec.op)}(可用:${OPS.join(" / ")})`
74
- if (!KINDS.includes(rec.kind ?? "memory")) return `未知的库:${String(rec.kind)}(可用:${KINDS.join(" / ")})`
75
167
  if (rec.op === "add" || rec.op === "update") {
76
168
  if (typeof rec.text !== "string" || !rec.text.trim()) return `${rec.op} 提案缺少非空 text`
77
169
  }
@@ -86,6 +178,65 @@ function invalidReason(rec) {
86
178
  return null
87
179
  }
88
180
 
181
+ /**
182
+ * 技能提案:先判过期(源或所有权变了就不许覆盖),再在快照之后按已批准的技能写路径应用。
183
+ * 过期判据是**内容指纹**:create 要求目标仍不存在;patch 要求目标仍存在、内容仍是当初那份、所有权没变。
184
+ */
185
+ async function approveSkillPending(L, rec, file, who, pendingPath) {
186
+ const target = skillTargetOf(L, rec.name)
187
+ if (rec.op === "create" && target.exists) {
188
+ return { ok: false, reason: "stale", file, detail: `同名技能在待批期间出现:${path.relative(L.root, target.file)}` }
189
+ }
190
+ if (rec.op === "patch") {
191
+ if (!target.exists) return { ok: false, reason: "stale", file, detail: "目标技能在待批期间消失" }
192
+ if (rec.baseHash && target.hash !== rec.baseHash) return { ok: false, reason: "stale", file, detail: "目标内容在待批期间被改动" }
193
+ if (rec.createdBy && target.createdBy !== rec.createdBy) return { ok: false, reason: "stale", file, detail: `所有权从 ${rec.createdBy} 变成 ${target.createdBy}` }
194
+ }
195
+
196
+ // 跑前快照(照 curator 归档):批准写入也可回滚。
197
+ const snap = snapshotSkills(L.root, `approve:${rec.name}`)
198
+ if (!snap.ok) return { ok: false, reason: "snapshot-failed", file, detail: snap.error ?? "快照失败" }
199
+
200
+ const r = await runSkillAction({
201
+ root: L.root,
202
+ identity: { origin: "foreground", agent: null },
203
+ action: rec.op,
204
+ name: rec.name,
205
+ description: rec.description ?? undefined,
206
+ content: rec.op === "create" ? rec.text : undefined,
207
+ old_string: rec.op === "patch" ? rec.match : undefined,
208
+ new_string: rec.op === "patch" ? rec.text : undefined,
209
+ approved: { by: who }, // 人已经批准过;只剩执行(宿主 deny 仍压过)
210
+ })
211
+ if (!r.ok) {
212
+ // 应用失败:待批文件保留,人能重试或拒绝。
213
+ return { ok: false, reason: "apply-failed", file, detail: r.error ?? "技能写入失败" }
214
+ }
215
+ fs.rmSync(pendingPath, { force: true })
216
+ appendAudit(L, {
217
+ event: "approve",
218
+ file,
219
+ op: rec.op,
220
+ kind: "skills",
221
+ name: rec.name,
222
+ origin: rec.origin ?? "unknown",
223
+ approvedBy: who,
224
+ snapshot: snap.id ?? null,
225
+ generation: storeHashOf(L.root),
226
+ })
227
+ return {
228
+ ok: true,
229
+ file,
230
+ op: rec.op,
231
+ kind: "skills",
232
+ name: rec.name,
233
+ origin: rec.origin ?? "unknown",
234
+ approvedBy: who,
235
+ snapshot: snap.id ?? null,
236
+ pending: listPending(L).length,
237
+ }
238
+ }
239
+
89
240
  /**
90
241
  * 批准一条待批提案。
91
242
  *
@@ -95,7 +246,7 @@ function invalidReason(rec) {
95
246
  *
96
247
  * @returns {{ok:true, file, op, kind, origin, approvedBy, pending}} 或 {{ok:false, reason, ...}}
97
248
  */
98
- export function approvePending(L, ref, { approvedBy = null } = {}) {
249
+ export async function approvePending(L, ref, { approvedBy = null } = {}) {
99
250
  const found = resolvePendingRef(L, ref)
100
251
  if (!found.ok) return found
101
252
 
@@ -115,6 +266,9 @@ export function approvePending(L, ref, { approvedBy = null } = {}) {
115
266
  if (bad) return { ok: false, reason: "invalid", file: found.file, detail: bad }
116
267
 
117
268
  const kind = rec.kind ?? "memory"
269
+ // 技能提案:按 kind 分派到技能写路径(不是把批准器放宽成任意写入)。
270
+ if (kind === "skills") return await approveSkillPending(L, rec, found.file, who, pendingPath)
271
+
118
272
  const locked = withCommitLock(L.lock, ({ fencing, assertStillOwner }) => {
119
273
  try {
120
274
  if (rec.op === "add") store.writeTrusted({ kind, text: rec.text })
@@ -47,6 +47,9 @@ export function createReviewScheduler({
47
47
  interrupt = null,
48
48
  thresholds = REVIEW_THRESHOLDS,
49
49
  now = () => Date.now(),
50
+ // 握手上限可注入:默认照 Hermes 2.0s;夹具用一个小值来证明「到点就放弃」,
51
+ // 不再拿墙钟当判据(满载时 Node24 实测 3.5s,会把语义正确的实现判红)。
52
+ cancelTimeoutMs = REVIEW_LIMITS.cancelTimeoutMs,
50
53
  // C③:**工具可用性前置**(照 Hermes)。mem 记 memory 工具、skills 记宿主 skill 工具;
51
54
  // 值只认 true(可用)/ false(明确不可用)/ null(未知 —— 也当不可用,fail-closed)。
52
55
  //
@@ -115,7 +118,7 @@ export function createReviewScheduler({
115
118
  const kind = inflightKind
116
119
  const timedOut = Symbol("timeout")
117
120
  let timer
118
- const timeout = new Promise((res) => { timer = setTimeout(() => res(timedOut), REVIEW_LIMITS.cancelTimeoutMs) })
121
+ const timeout = new Promise((res) => { timer = setTimeout(() => res(timedOut), cancelTimeoutMs) })
119
122
  const settled = await Promise.race([inFlight.then(() => "done").catch(() => "done"), timeout])
120
123
  clearTimeout(timer)
121
124
  const waitedMs = now() - t0
@@ -178,11 +181,33 @@ export function surfaceLine({ proposals = [], ignored = [] } = {}) {
178
181
  return parts.join(";")
179
182
  }
180
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
+
181
202
  // 触发源(对齐 Hermes agent/turn_finalizer.py):宿主 `session.idle` = 回合结束。
182
203
  // 每次回合结束都做一次「要不要复习」的检查;前台新回合先取消在跑的那次(握手 ≤2s)。
183
204
  // 复习本身以**宿主身份**跑在**受限 agent**(只读 plan)里 ⇒ 工具被限定,且发生在宿主会话体系内。
184
205
  export const REVIEW_AGENT = "plan"
185
206
 
207
+ // 后台复习浮出的那一行带这个机器标记(part.metadata.ocg)。消费者(召回查询段、会话索引、学习队列)
208
+ // 用它把「后台通知」和「用户真的说了什么」分开——不靠文本前缀猜。
209
+ export const REVIEW_SURFACE_MARK = "review-surface"
210
+
186
211
  export function createTurnEndHandler({ scheduler, review, sessionId = null } = {}) {
187
212
  if (!scheduler || typeof review !== "function") throw new TypeError("createTurnEndHandler 需要 scheduler 与 review")
188
213
  let lastResult = null
@@ -59,6 +59,27 @@ export function fileForTarget(target) {
59
59
 
60
60
  export const DEFAULT_LIMITS = { memory: 2200, user: 1375 }
61
61
 
62
+ /**
63
+ * 生效上限:D/config.json 的 `memory.memory_char_limit` / `memory.user_char_limit`
64
+ * (与 Hermes config_defaults.py 同名同义)。
65
+ * 读不到 / 非法 / 非正数一律回默认——配置坏掉不许把正常写入判成超限(fail 到 Hermes 值)。
66
+ * 这是**唯一**的解析口径:store、批准、批量、CLI 与诊断都从这里取,不在各入口复制默认值。
67
+ */
68
+ export function resolveMemoryLimits(root) {
69
+ let cfg = null
70
+ try {
71
+ cfg = JSON.parse(fs.readFileSync(path.join(root, "config.json"), "utf8"))
72
+ } catch {
73
+ cfg = null
74
+ }
75
+ const mem = cfg && typeof cfg === "object" ? cfg.memory ?? {} : {}
76
+ const pick = (v, dflt) => {
77
+ const n = Number(v)
78
+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : dflt
79
+ }
80
+ return { memory: pick(mem.memory_char_limit, DEFAULT_LIMITS.memory), user: pick(mem.user_char_limit, DEFAULT_LIMITS.user) }
81
+ }
82
+
62
83
  const KINDS = ["memory", "user"]
63
84
  const FILES = { memory: "MEMORY.md", user: "USER.md" }
64
85
  const ORIGINS = ["foreground", "background", "unknown"]
@@ -175,7 +196,13 @@ function acquireLock(root, { timeoutMs = LOCK_TIMEOUT_MS } = {}) {
175
196
 
176
197
  export function createMemoryStore({ root, identity = null, limits = {}, enabled = {} } = {}) {
177
198
  if (!root) throw new Error("createMemoryStore 需要 root(即 D 目录)")
178
- const limitOf = (kind) => limits[kind] ?? DEFAULT_LIMITS[kind]
199
+ // 每次判定都重新解析(配置文件很小):长驻进程(插件)改了配置,下一次动作就生效,
200
+ // 不必重启宿主;显式入参(夹具/嵌入方)仍然优先。
201
+ const limitOf = (kind) => {
202
+ const explicit = Number(limits?.[kind])
203
+ if (Number.isFinite(explicit) && explicit > 0) return Math.floor(explicit)
204
+ return resolveMemoryLimits(root)[kind]
205
+ }
179
206
  const enabledOf = (kind) => enabled[kind] !== false
180
207
  // 身份**只认登记值**:调用方在每次动作里传的 origin 一律忽略(extra#4)。
181
208
  const originOf = () => {
@@ -247,6 +274,7 @@ export function createMemoryStore({ root, identity = null, limits = {}, enabled
247
274
  const overLimitError = (kind, used, limit) =>
248
275
  new Error(
249
276
  `写入会超过上限:当前 ${used} / 上限 ${limit} 字符(${kind})。` +
277
+ `这笔文字会一直占用常驻上下文(每次会话都随系统提示带上,按 token 计费)。` +
250
278
  `请在当轮整理后再写:合并或删减既有条目,或把详情移到别处。本次写入未落盘。`,
251
279
  )
252
280
 
@@ -21,6 +21,7 @@ import path from "node:path"
21
21
 
22
22
  import { createMemoryStore, findEntryIndex } from "./memories.mjs"
23
23
  import { decideWrite } from "./write-approval.mjs"
24
+ import { BACKGROUND_SUBSESSION_KINDS } from "./subsessions.mjs"
24
25
 
25
26
  /**
26
27
  * 动作是**封闭枚举**。加动作等于改工具契约——加 `approve` 就等于给了自批的口子。
@@ -61,7 +62,13 @@ export function identityFor({
61
62
  interactive = false,
62
63
  backgroundAgents = [],
63
64
  foregroundAgents = [],
65
+ // S0:OCG 自己派发的子会话按**子会话 id** 登记(core/subsessions.mjs),身份从那里来。
66
+ // 优先级最高:它是「谁派发的」的直接证据,比 agent 名与部署方名单都强。
67
+ backgroundKind = null,
64
68
  } = {}) {
69
+ if (typeof backgroundKind === "string" && BACKGROUND_SUBSESSION_KINDS.includes(backgroundKind)) {
70
+ return { origin: "background", agent: `ocg-${backgroundKind}` }
71
+ }
65
72
  if (agent && Array.isArray(backgroundAgents) && backgroundAgents.includes(agent)) {
66
73
  return { origin: "background", agent }
67
74
  }
@@ -36,7 +36,6 @@ export function layout(root) {
36
36
  learnOffset: p("state", "learn-queue.offset"),
37
37
  manifest: p("state", "manifest.json"),
38
38
  projects: p("state", "projects.json"),
39
- budget: p("state", "budget.json"),
40
39
  watermark: p("state", "watermark.json"),
41
40
  policy: p("state", "policy.json"),
42
41
  schema: p("state", "schema.json"),
@@ -0,0 +1,53 @@
1
+ // 首装点亮历史搜索:装完就该能用「查历史会话」,而不是让用户先学会跑一条 CLI。
2
+ // 判据(照 deferred-and-user-risks §6-P2):**已知默认位置存在 ⇒ 绑定一次**;
3
+ // 不存在就**不猜**、保持 not-configured,但把「未启用 + 怎么启用」说出口。
4
+ import fs from "node:fs"
5
+ import os from "node:os"
6
+ import path from "node:path"
7
+
8
+ import { repairHintFor, statusStore, syncStore } from "./session-index.mjs"
9
+
10
+ /**
11
+ * 宿主 opencode.db 的已知默认位置(不扫盘、不嗅探进程):
12
+ * `OCG_SESSION_SOURCE` 显式给了就用它;否则按平台默认数据目录列。
13
+ */
14
+ export function hostDbCandidates({ env = process.env, platform = process.platform, home = os.homedir() } = {}) {
15
+ const out = []
16
+ const explicit = env.OCG_SESSION_SOURCE || env.OPENCODE_DB
17
+ if (explicit) out.push(explicit)
18
+ const xdg = env.XDG_DATA_HOME || path.join(home, ".local", "share")
19
+ out.push(path.join(xdg, "opencode", "opencode.db"))
20
+ if (platform === "darwin") out.push(path.join(home, "Library", "Application Support", "opencode", "opencode.db"))
21
+ if (platform === "win32" && env.APPDATA) out.push(path.join(env.APPDATA, "opencode", "opencode.db"))
22
+ return [...new Set(out.map((p) => path.resolve(String(p))))]
23
+ }
24
+
25
+ /**
26
+ * 装完那一步:已绑定就不动;有默认库就绑一次;没有就如实说「未启用」。
27
+ * `sync` 是测试注入缝(默认走真 syncStore)。
28
+ */
29
+ export async function lightUpHistorySearch(root, { env = process.env, platform = process.platform, home = os.homedir(), sync = syncStore } = {}) {
30
+ const before = statusStore({ root })
31
+ if (before.state === "ok") return { state: "already", parts: before.counts?.parts ?? null, source: before.source ?? null }
32
+ const candidates = hostDbCandidates({ env, platform, home })
33
+ const found = candidates.find((p) => {
34
+ try {
35
+ return fs.statSync(p).isFile()
36
+ } catch {
37
+ return false
38
+ }
39
+ })
40
+ if (!found) return { state: "absent", hint: repairHintFor("not-configured"), candidates }
41
+ const r = await sync({ root, sourcePath: found })
42
+ if (!r?.ok) return { state: "failed", source: found, error: r?.error ?? "绑定失败", candidates }
43
+ return { state: "bound", source: found, parts: r.parts ?? null }
44
+ }
45
+
46
+ /** 人读一行:装完到底能不能查历史。 */
47
+ export function historySearchLine(area) {
48
+ if (!area) return null
49
+ if (area.state === "already") return null
50
+ if (area.state === "bound") return `历史搜索已启用:${area.source}${Number.isFinite(area.parts) ? `(${area.parts} 个片段)` : ""}`
51
+ if (area.state === "failed") return `历史搜索未启用:绑定 ${area.source} 失败(${area.error})`
52
+ return `历史搜索未启用(没找到宿主库):${area.hint}`
53
+ }
@@ -17,12 +17,23 @@ import { extractParts, openSource, probeShape } from "./session-source.mjs"
17
17
  import { buildMatchExpr, evaluateText, parseQuery, relaxAst, termMatches, tokensOf } from "./session-query.mjs"
18
18
 
19
19
  const CAPABILITY_STATES = new Set([
20
+ "not-configured",
21
+ "backfilling",
20
22
  "unsupported-schema",
21
23
  "source-missing",
22
24
  "source-unavailable",
23
25
  "permission-denied",
24
26
  ])
25
27
 
28
+ /**
29
+ * 历史检索的修复路径只有一条(三面共用同一句,避免各面漂移):
30
+ * 首次绑定=sync --source;换源/重建=rebuild --source。未配置不是错误配置,不猜源。
31
+ */
32
+ export function repairHintFor(state) {
33
+ if (!CAPABILITY_STATES.has(state)) return null
34
+ return "运行 `oc-grow session-index sync --source <opencode.db>` 绑定历史来源;换源或重建用 `oc-grow session-index rebuild --source <opencode.db>`。"
35
+ }
36
+
26
37
 
27
38
  export function openStore(root) {
28
39
  const dir = path.join(root, "index")
@@ -84,11 +95,20 @@ function metaSet(db, key, value) {
84
95
 
85
96
  const nowIso = (now) => new Date(now ?? Date.now()).toISOString()
86
97
 
98
+ // Bind source identity once, at the explicit sync/rebuild entry point.
99
+ // Existing relative bindings cannot be reconstructed from a later query cwd.
100
+ function canonicalSourcePath(file) {
101
+ if (!file) return file
102
+ const absolute = path.resolve(file)
103
+ try { return fs.realpathSync(absolute) } catch { return absolute }
104
+ }
105
+
87
106
  /**
88
107
  * 全量幂等 sync:只读抽取源 → 自家库 upsert + sweep(staging generation 完成后才删除)。
89
108
  * `extract` 是 DI 缝(中断/坏行夹具从这里注入),默认走 session-source 的逐 part 抽取。
90
109
  */
91
110
  export async function syncStore({ root, sourcePath, extract = null, now = null, includeToolOutput = false, scope_session_id = null } = {}) {
111
+ sourcePath = canonicalSourcePath(sourcePath)
92
112
  const store = openStore(root)
93
113
  try {
94
114
  const bound = metaGet(store.db, "source_path")
@@ -219,7 +239,26 @@ export async function syncStore({ root, sourcePath, extract = null, now = null,
219
239
  }
220
240
 
221
241
  function stateEnvelope(store) {
222
- const state = metaGet(store.db, "state") ?? "ok"
242
+ // 三态必须可辨(U1):未配置 ≠ 不可用 ≠ 有效无命中。
243
+ // · 从未绑定来源(无 source_path 且无一次成功对账)⇒ not-configured;
244
+ // · 已绑定但来源此刻读不到 ⇒ source-missing(缓存命中仍按 fail-open 返回,但标 stale);
245
+ // · 其余沿用 sync 落盘的 state。这里只做一次 stat,不打开宿主库、不猜源。
246
+ const recorded = metaGet(store.db, "state") ?? "ok"
247
+ const bound = metaGet(store.db, "source_path")
248
+ let state = recorded
249
+ if (!CAPABILITY_STATES.has(recorded)) {
250
+ if (!bound) state = metaGet(store.db, "as_of") ? recorded : "not-configured"
251
+ else if (!path.isAbsolute(bound)) state = "source-unavailable"
252
+ else {
253
+ try {
254
+ if (!fs.statSync(bound).isFile()) state = "source-unavailable"
255
+ else fs.accessSync(bound, fs.constants.R_OK)
256
+ } catch (e) {
257
+ state = e.code === "ENOENT" ? "source-missing"
258
+ : ["EACCES", "EPERM"].includes(e.code) ? "permission-denied" : "source-unavailable"
259
+ }
260
+ }
261
+ }
223
262
  const coverage = JSON.parse(metaGet(store.db, "coverage") ?? "{}")
224
263
  return {
225
264
  state,
@@ -356,6 +395,7 @@ export function searchStore({ root, query, limit = 20, session_id = null, role =
356
395
  coverage: env.coverage,
357
396
  as_of: env.as_of,
358
397
  stale,
398
+ ...(stale ? { repair_hint: repairHintFor(env.state) } : {}),
359
399
  count: hits.length,
360
400
  results: hits,
361
401
  message,
@@ -451,6 +491,7 @@ export function readStore({ root, session_id, message_id = null, part_id = null,
451
491
 
452
492
  /** 换源:显式 rebind 全量重建(两源 ID 不混——旧源行全部清掉)。 */
453
493
  export function rebindStore({ root, sourcePath } = {}) {
494
+ sourcePath = canonicalSourcePath(sourcePath)
454
495
  const store = openStore(root)
455
496
  try {
456
497
  const cleared = store.db.prepare("DELETE FROM parts").run().changes
@@ -9,6 +9,7 @@
9
9
  // 未识别 part 类型只计数不伪装。绝不把异常吞成 []。
10
10
  import fs from "node:fs"
11
11
  import { openDb } from "./sqlite-runtime.mjs"
12
+ import { REVIEW_SURFACE_MARK } from "./background-review.mjs"
12
13
 
13
14
  const REQUIRED = {
14
15
  session: ["id", "project_id", "directory", "title", "time_created"],
@@ -154,6 +155,12 @@ export function extractParts(src, { includeToolOutput = false, session_id = null
154
155
 
155
156
  const type = data && typeof data.type === "string" ? data.type : null
156
157
  if (type === "text" && typeof data.text === "string") {
158
+ // 后台复习浮出的通知也是 user text part;索引面必须与主模型/召回面同一口径(ignored + 标记),
159
+ // 否则它会被当成用户说过的话采集进索引,再被检索/复习当事实用。
160
+ if (data.ignored === true || data?.metadata?.ocg === REVIEW_SURFACE_MARK) {
161
+ counts.surface_skipped = (counts.surface_skipped ?? 0) + 1
162
+ continue
163
+ }
157
164
  counts.text += 1
158
165
  parts.push({
159
166
  part_id: row.part_id, message_id: row.message_id, session_id: row.m_session,
@@ -6,7 +6,7 @@
6
6
  // 查询核心/状态/过滤与 CLI 共用(src/core/session-index.mjs)——两面不各造一套。
7
7
  import { createHash } from "node:crypto"
8
8
 
9
- import { openStore, readStore, searchStore, statusStore } from "./session-index.mjs"
9
+ import { openStore, readStore, repairHintFor, searchStore, statusStore } from "./session-index.mjs"
10
10
  import { boundedRefresh } from "./session-freshness.mjs"
11
11
 
12
12
  /** 大 part 分块读的块长(字符);工具输出预算独立——budget.mjs 不参与,不丢原文。 */
@@ -70,6 +70,13 @@ export function createSessionTool({ root, sourcePath = null } = {}) {
70
70
  })
71
71
  if (!r.ok) return failure("discover", coreOf(root, r), r.error_code ?? "usage", r.message ?? null)
72
72
  const core = coreOf(root, r)
73
+ // 未配置/能力缺失且**没有缓存命中** ⇒ 失败信封(与「有效源零命中」必须可辨),
74
+ // 并给同一条修复路径;有缓存命中时走 fail-open(success=true + stale + as_of)。
75
+ if (!r.count && repairHintFor(core.state)) {
76
+ // 失败信封里两件事都要在:**为什么**(旧空集/未核对)与**怎么修**(同一条命令面路径)。
77
+ const hint = [r.message, repairHintFor(core.state)].filter(Boolean).join(" ")
78
+ return failure("discover", core, core.state, hint)
79
+ }
73
80
  let rows = r.results
74
81
  if (dedupe === "session") {
75
82
  const seen = new Set()
@@ -79,6 +86,7 @@ export function createSessionTool({ root, sourcePath = null } = {}) {
79
86
  const extra = { results: rows }
80
87
  if (!rows.length && r.message) extra.repair_hint = r.message
81
88
  if (r.stale) extra.stale = r.stale
89
+ if (r.repair_hint) extra.repair_hint = r.repair_hint
82
90
  if (r.incomplete) extra.incomplete = true
83
91
  if (r.index_corrupt) extra.index_corrupt = true
84
92
  return envelope("discover", core, extra)
@@ -21,6 +21,7 @@ import fs from "node:fs"
21
21
  import path from "node:path"
22
22
 
23
23
  import { appendAudit } from "./audit.mjs"
24
+ import { sha256 } from "./ids.mjs"
24
25
  import { layout } from "./paths.mjs"
25
26
  import {
26
27
  checkSkillLayout,
@@ -35,7 +36,7 @@ import {
35
36
  import { createMemoryStore } from "./memories.mjs"
36
37
  import { decideWrite } from "./write-approval.mjs"
37
38
  import { scanForThreats } from "./threats.mjs"
38
- import { recordSkillCreated, bumpSkillPatch, bumpSkillView, updateRecord } from "./skill-usage.mjs"
39
+ import { readUsage, recordSkillCreated, bumpSkillPatch, bumpSkillView, updateRecord } from "./skill-usage.mjs"
39
40
  import { archiveSkill } from "./skill-lifecycle.mjs"
40
41
 
41
42
  /** 动作是封闭枚举:加动作=改工具契约(照 memory-actions 的 extra#4 纪律,无 approve/apply)。 */
@@ -148,6 +149,7 @@ export async function runSkillAction({
148
149
  agentSkillEnabled = true,
149
150
  externalDirs = undefined,
150
151
  absorbedInto = null,
152
+ approved = null, // { by } ⇒ 人已经批准过这条提案,跳过写入门控(宿主 deny 仍然压过)
151
153
  } = {}) {
152
154
  if (!root) return fail(action, "缺少 root(D 目录)")
153
155
  if (!SKILL_ACTIONS.includes(action)) {
@@ -227,6 +229,12 @@ export async function runSkillAction({
227
229
  const umbrellaFile = skillFileOf(root, String(absorbedInto))
228
230
  if (!fs.existsSync(umbrellaFile)) return fail(action, `absorbed_into 的伞不存在:${String(absorbedInto)}`, { name })
229
231
  if (!fs.existsSync(location)) return fail(action, `技能不存在:${name}`, { name })
232
+ // pin 防归档(照 Hermes skill_manager_guards:pin 挡删除/归档,不挡 patch 与编辑)。
233
+ // 迁移点(archiveSkill)已有一道守卫,这里再判一次是为了给出**可见回执**——
234
+ // 工具面拒绝必须说明原因,不能只留下无声的 ok:false。
235
+ if (readUsage(root)[name]?.pinned) {
236
+ return { ok: false, action, error: `pinned 技能不归档:${name}(先取消 pin)`, receipt: receipt("未生效", { name, location, detail: "pinned" }) }
237
+ }
230
238
  // 保护三分(照 A41)+归档直写(2026-09-25 修正,照 Hermes curator 自动归档):
231
239
  // 无人值守归档**自动直写**(curator 叉以 plan 身份跑也一样),跑前快照兑底(restore/rollback 可回);
232
240
  // user-owned 仍拒动(curator 不碰不拥有的技能,adopt 后才可管)、external 只读红。
@@ -291,14 +299,21 @@ export async function runSkillAction({
291
299
  }
292
300
 
293
301
  // ── 闸门分流(照 memory-actions;技能面 destructive 恒 false,W8 裁定见文件头) ──
294
- const decision = decideWrite({
295
- root,
296
- subsystem: "skills",
297
- origin,
298
- destructive: false,
299
- interactive: typeof ask === "function",
300
- hostPermission,
301
- })
302
+ // 批准过的提案走受信任路径:人已经看过旧文与 diff,再问一次闸门只会把它送回待批队列。
303
+ // 宿主 deny 仍然压过一切(那不是我们的闸门,是宿主的权限面)。
304
+ const decision =
305
+ hostPermission === "deny"
306
+ ? "deny"
307
+ : approved?.by
308
+ ? "apply"
309
+ : decideWrite({
310
+ root,
311
+ subsystem: "skills",
312
+ origin,
313
+ destructive: false,
314
+ interactive: typeof ask === "function",
315
+ hostPermission,
316
+ })
302
317
  if (decision === "deny") {
303
318
  return { ok: false, action, error: "宿主权限闸拒绝了这次写入", receipt: receipt("未生效", { name, location, detail: "permission deny" }) }
304
319
  }
@@ -311,6 +326,10 @@ export async function runSkillAction({
311
326
  name,
312
327
  text: action === "create" ? body : new_string,
313
328
  match: action === "create" ? name : old_string,
329
+ // 批准时必须能回答两件事:批的是什么(description/正文)与「批的还是不是当初那份」(baseHash/createdBy)。
330
+ description: description ?? null,
331
+ baseHash: fs.existsSync(location) ? sha256(fs.readFileSync(location)) : null,
332
+ createdBy: fs.existsSync(location) ? readCreatedBy(location) : null,
314
333
  })
315
334
  return {
316
335
  ok: true,
@@ -61,6 +61,11 @@ export function archiveSkill(root, name, { now = new Date() } = {}) {
61
61
  return { ok: false, error: ext ? `外部来源技能只读:${ext}` : `技能不存在:${name}` }
62
62
  }
63
63
  if (ext) return { ok: false, error: `外部来源技能只读:${ext}` } // 同名外部件在 ⇒ 只读保护
64
+ // pin 防归档(照 Hermes tools/skill_manager_guards.py:pin 挡删除/归档,不挡 patch)——
65
+ // 守卫必须放在**搬迁点**上:生命周期计划虽已 `if (rec.pinned) continue`,但前台工具 /
66
+ // 后台通道 / 直接调用都不经那条计划,绕过它就等于 pin 只在一种入口生效。
67
+ const rec = readUsage(root)[name] ?? {}
68
+ if (rec.pinned) return { ok: false, error: `pinned 技能不归档:${name}(先 unpin)` }
64
69
  let dest = archiveDirOf(root, name)
65
70
  if (fs.existsSync(dest)) {
66
71
  // 照 Hermes:%Y%m%d%H%M%S 14 位纯数字后缀(restore 按这个形制找最新的时间戳副本)
@@ -180,13 +185,20 @@ export function applyLifecycleTransitions({ root, now = new Date(), dryRun = fal
180
185
  reactivated: 0,
181
186
  snapshot: null,
182
187
  entries: [],
188
+ // pinned 全旁路是**有意**的,但「为什么没动它」必须看得见(否则人只会看到计数里少了一项)。
189
+ skipped_pinned: [],
183
190
  }
184
191
  const plan = [] // {kind, name}
185
192
  for (const [name, rec] of Object.entries(all)) {
186
193
  out.checked++
187
- if (rec.pinned) continue // pinned 全旁路
188
194
  const dir = skillDirOf(root, name)
189
- if (!fs.existsSync(path.join(dir, SKILL_FILE))) continue // 不在 active 面(已归档/已删)
195
+ const present = fs.existsSync(path.join(dir, SKILL_FILE))
196
+ if (rec.pinned) {
197
+ // 只点名**还在 active 面**的:已归档/已删的技能报「跳过 pinned」是噪声(复核观察 4)。
198
+ if (present) out.skipped_pinned.push({ name, reason: "pinned" })
199
+ continue
200
+ }
201
+ if (!present) continue // 不在 active 面(已归档/已删)
190
202
  if (readCreatedBy(path.join(dir, SKILL_FILE)) !== "agent") continue // user-owned 保护以文件为准
191
203
  if (externalHit(name, externals)) continue // 外部同名件只读,不进入迁移计划
192
204
  const activityMs = parseTs(rec.last_activity_at)