opencode-growth 0.1.59 → 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.
@@ -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)
@@ -105,7 +105,8 @@ export function hostConfigFor({ root, existing = {} } = {}) {
105
105
  }
106
106
 
107
107
  const merged = paths.includes(ours) ? paths.slice() : [...paths, ours]
108
- const skills = { ...(urls.length ? { urls } : {}), paths: merged }
108
+ const skills = { ...(rawSkills && typeof rawSkills === "object" && !Array.isArray(rawSkills) ? rawSkills : {}),
109
+ ...(urls.length ? { urls } : {}), paths: merged }
109
110
 
110
111
  // §0 第 5 条接线(C42):让宿主对**我们的写入权限**要求询问。
111
112
  // 键必须与插件 `ask()` 发出的名字同源(WRITE_PERMISSION_NAME),否则策略从不匹配 ⇒ 静默放行。
package/src/index.mjs CHANGED
@@ -26,6 +26,5 @@ export {
26
26
  DEFAULT_PREVIEW_TTL_MS,
27
27
  DEFAULT_POLICY_VERSION,
28
28
  } from "./core/review.mjs"
29
- export { DEFAULT_BUDGET, normalizeBudget, estimateTokens } from "./core/budget.mjs"
30
29
  export { appendAudit, readAudit } from "./core/audit.mjs"
31
30
  export { withCommitLock, lockInfo } from "./core/lock.mjs"
@@ -1,64 +0,0 @@
1
- // Read-path budgets (R2 §2.5, §4): count / per-entry characters / total tokens.
2
- //
3
- // Two rules this module exists to make explicit:
4
- // 1. Over-limit means *dropped whole*. A truncated body can lose "only in staging" or a
5
- // negation and change the meaning of what was learned, so nothing here ever slices text.
6
- // 2. The total budget is measured on the **wrapped** text (envelope + attributes + body),
7
- // never on bodies alone — otherwise the wrapper silently eats the budget.
8
-
9
- export const DEFAULT_BUDGET = Object.freeze({
10
- maxEntries: 12, // how many entries may be injected at once
11
- maxCharsPerEntry: 1200, // per-entry character ceiling (the rendered entry, envelope-free)
12
- totalTokens: 3000, // ceiling for the whole injected text, envelope included
13
- })
14
-
15
- /** Refuse nonsense instead of clamping it: a silently clamped budget is a silent behaviour change. */
16
- export function normalizeBudget(input = {}) {
17
- const out = { ...DEFAULT_BUDGET }
18
- const unknown = Object.keys(input).filter((k) => !(k in DEFAULT_BUDGET))
19
- if (unknown.length) throw new Error(`unknown budget key(s): ${unknown.join(", ")}`)
20
- for (const key of Object.keys(DEFAULT_BUDGET)) {
21
- const value = input[key]
22
- if (value === undefined) continue
23
- if (!Number.isInteger(value) || value < 0) {
24
- throw new Error(`budget.${key} must be a non-negative integer, got ${JSON.stringify(value)}`)
25
- }
26
- out[key] = value
27
- }
28
- return out
29
- }
30
-
31
- /** Wide ranges: CJK, kana, hangul, full-width punctuation, emoji. */
32
- function isWide(cp) {
33
- return (
34
- (cp >= 0x2e80 && cp <= 0x9fff) ||
35
- (cp >= 0xac00 && cp <= 0xd7a3) ||
36
- (cp >= 0xf900 && cp <= 0xfaff) ||
37
- (cp >= 0xfe30 && cp <= 0xfe4f) ||
38
- (cp >= 0xff00 && cp <= 0xff60) ||
39
- (cp >= 0xffe0 && cp <= 0xffe6) ||
40
- (cp >= 0x1f300 && cp <= 0x1faff)
41
- )
42
- }
43
-
44
- /**
45
- * Conservative **estimate**, never a measurement.
46
- *
47
- * No tokenizer is available offline and the real prompt-cache/token accounting is still an
48
- * unverified item in the design, so the read path must not pretend to know exact token counts.
49
- * Wide characters (CJK and friends) are counted at a full token each — character counts are
50
- * never a valid token count for Chinese; every other run of non-space characters is charged
51
- * one token per three characters, which over-counts plain ASCII rather than under-counting it.
52
- */
53
- export function estimateTokens(text) {
54
- const source = String(text ?? "")
55
- let wide = 0
56
- let narrow = 0
57
- for (const ch of source) {
58
- const cp = ch.codePointAt(0)
59
- if (cp === 0x20 || cp === 0x09 || cp === 0x0a || cp === 0x0d) continue
60
- if (isWide(cp)) wide += 1
61
- else narrow += 1
62
- }
63
- return wide + Math.ceil(narrow / 3)
64
- }
@@ -1,127 +0,0 @@
1
- // 检索层:把常驻/会话原文按需召回,**返回逐字原文**(不摘要、不重排)。
2
- //
3
- // 对齐依据(读 Hermes 源码得到,非猜测):
4
- // · `hermes_state_common.py:720` 建 `messages_fts USING fts5(...)`;`:840` 另建 `... tokenize='trigram'`
5
- // · `hermes_state_fts.py:32-37`:**trigram 每个查询词要 ≥3 字符 ⇒ 中文 1–2 字查不到**(CJK 上 session_search 的主要失效面),
6
- // 所以 Hermes 用自带的可加载 tokenizer `cjk_unicode61`(`native/fts5_cjk/`,约 250 行)——
7
- // 把**最长的 CJK 连续串重发成重叠字符 bigram**(Lucene CJKAnalyzer 语义),其余交给 unicode61;
8
- // FTS5 的短语语义把"连续 bigram"变成**精确子串匹配**(下到 2 字)。
9
- // · `hermes_state_fts.py:112` 明确是**best-effort 加载**:加载不了就退回 trigram(能力缺失要可见,不能假装)。
10
- //
11
- // 我们的等价做法:**不引入编译型 tokenizer**(插件里装不了、也不该让宿主去编译),
12
- // 改成在 **JS 侧做同一套 bigram 变换**,写进一个独立的 `grams` 列,FTS5 用自带的 `unicode61`。
13
- // 语义与 Hermes 对齐:≥2 字的 CJK 查询走 bigram 精确子串;**1 字** CJK 用 bigram 表达不出来(Hermes 同病),
14
- // 故显式走子串回退并**如实标注**(见 `search()` 返回行里的 `matchedBy`),不假装是索引命中。
15
- import fs from "node:fs"
16
- import path from "node:path"
17
-
18
- const CJK = /[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\u3040-\u30ff\uac00-\ud7af]/
19
-
20
- /** 打开本地 SQLite:宿主是 Bun(`bun:sqlite`),测试跑 Node(`node:sqlite`)。找不到就明确失败。 */
21
- async function openDb(file) {
22
- for (const spec of ["bun:sqlite", "node:sqlite"]) {
23
- try {
24
- const mod = await import(spec)
25
- const C = mod.DatabaseSync ?? mod.Database ?? mod.default?.Database ?? mod.default
26
- if (typeof C === "function") return new C(file)
27
- } catch { /* 换下一个运行时 */ }
28
- }
29
- throw new Error("找不到可用的本地 SQLite(试过 bun:sqlite 与 node:sqlite)")
30
- }
31
-
32
- /** CJK 连续串 ⇒ 重叠 bigram;其余(拉丁词、数字)原样保留。 */
33
- export function bigrams(text) {
34
- const out = []
35
- const runs = String(text ?? "").match(/\S+/g) ?? []
36
- for (const tok of runs) {
37
- if (!CJK.test(tok)) { out.push(tok.toLowerCase()); continue }
38
- // 以 CJK 为单位切段:CJK 段做重叠 bigram,非 CJK 段原样
39
- let buf = ""
40
- const flush = () => { if (buf) { out.push(buf.toLowerCase()); buf = "" } }
41
- const chars = [...tok]
42
- for (const ch of chars) {
43
- if (CJK.test(ch)) buf += ch
44
- else { flush() /* 非 CJK 片段先落 */ }
45
- }
46
- flush()
47
- // 单独对整串做重叠 bigram(混合串也这么做,长度 ≥2 才有 bigram)
48
- const cjkOnly = chars.filter((c) => CJK.test(c))
49
- for (let i = 0; i + 1 < cjkOnly.length; i += 1) out.push(cjkOnly[i] + cjkOnly[i + 1])
50
- }
51
- return [...new Set(out)]
52
- }
53
-
54
- /** 查询变换:与写入同一套;返回 { match, fallback }。 */
55
- export function queryPlan(query) {
56
- const q = String(query ?? "").trim()
57
- const cjkChars = [...q].filter((c) => CJK.test(c))
58
- // 1 个 CJK 字:bigram 表达不出来 ⇒ 子串回退(Hermes 的 trigram/bigram 同样下不到 1 字)
59
- if (cjkChars.length === 1 && q.length === 1) return { match: null, fallback: q }
60
- const grams = bigrams(q)
61
- if (!grams.length) return { match: null, fallback: q }
62
- // 用短语(引号)表达"连续"⇒ 精确子串语义(与 Hermes 的 FTS5 短语语义一致)
63
- return { match: grams.map((g) => `"${g.replace(/"/g, '""')}"`).join(" "), fallback: q }
64
- }
65
-
66
- export async function createRetriever({ root } = {}) {
67
- if (!root) throw new Error("createRetriever 需要 root(D 目录)")
68
- const dir = path.join(root, "index")
69
- fs.mkdirSync(dir, { recursive: true })
70
- const db = await openDb(path.join(dir, "retrieve.db"))
71
-
72
- db.exec(`
73
- CREATE TABLE IF NOT EXISTS docs (
74
- id TEXT PRIMARY KEY,
75
- text TEXT NOT NULL,
76
- source TEXT,
77
- indexed_at TEXT NOT NULL
78
- );
79
- CREATE VIRTUAL TABLE IF NOT EXISTS docs_fts USING fts5(grams, id UNINDEXED, tokenize='unicode61');
80
- `)
81
-
82
- return {
83
- /** 建索引:只存原文(text 逐字保留)+ 由原文派生的 bigram 列。 */
84
- async index({ id, text, source = null } = {}) {
85
- if (!id || typeof text !== "string") throw new Error("index 需要 { id, text }")
86
- const grams = bigrams(text).join(" ")
87
- db.exec("BEGIN")
88
- try {
89
- db.prepare("INSERT INTO docs(id, text, source, indexed_at) VALUES(?,?,?,datetime('now')) " +
90
- "ON CONFLICT(id) DO UPDATE SET text=excluded.text, source=excluded.source, indexed_at=excluded.indexed_at")
91
- .run(String(id), text, source)
92
- db.prepare("DELETE FROM docs_fts WHERE id = ?").run(String(id))
93
- db.prepare("INSERT INTO docs_fts(grams, id) VALUES(?,?)").run(grams, String(id))
94
- db.exec("COMMIT")
95
- } catch (e) { db.exec("ROLLBACK"); throw e }
96
- return { id: String(id), grams: grams ? grams.split(" ").length : 0 }
97
- },
98
-
99
- async remove({ id } = {}) {
100
- db.prepare("DELETE FROM docs_fts WHERE id = ?").run(String(id))
101
- return { removed: db.prepare("DELETE FROM docs WHERE id = ?").run(String(id)).changes }
102
- },
103
-
104
- /** 检索:命中返回**原文**(`text` 逐字来自 docs.text)。 */
105
- async search({ query, limit = 5 } = {}) {
106
- const plan = queryPlan(query)
107
- const rows = []
108
- if (plan.match) {
109
- try {
110
- const stmt = db.prepare(
111
- "SELECT d.id, d.text, d.source FROM docs_fts f JOIN docs d ON d.id = f.id " +
112
- "WHERE docs_fts MATCH ? ORDER BY rank LIMIT ?")
113
- for (const r of stmt.all(plan.match, Number(limit))) rows.push({ ...r, matchedBy: "fts-bigram" })
114
- } catch { /* 查询语法异常 ⇒ 落到子串回退,不假装命中 */ }
115
- }
116
- if (!rows.length && plan.fallback) {
117
- const stmt = db.prepare(
118
- "SELECT id, text, source FROM docs WHERE instr(lower(text), lower(?)) > 0 LIMIT ?")
119
- for (const r of stmt.all(plan.fallback, Number(limit)))
120
- rows.push({ ...r, matchedBy: "substring-fallback" })
121
- }
122
- return rows
123
- },
124
-
125
- async close() { db.close() },
126
- }
127
- }