opencode-growth 0.1.2 → 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 +2 -1
  2. package/package.json +1 -1
  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
@@ -0,0 +1,467 @@
1
+ // 会话索引派生库(G4 S2a+S3a):自家 SQLite 原文快照为权威,全量幂等 sync(mark-and-sweep),
2
+ // 原文扫描版搜索,状态/续读。索引单位=part、阅读单位=message(A′)。
3
+ //
4
+ // 同步契约(GOAL §2 S2a 判据):
5
+ // · 快刷只作加速(S4),**完整对账 mark-and-sweep 才是完备边界**——staging generation
6
+ // 完成后才删除撤回;中断/坏行 ⇒ 旧索引逐行保留 + `stale/backfilling` 可见。
7
+ // · 幂等可重放:连续两次 sync 结果与计数完全一致。
8
+ // 失效语义(红线③ + fail-open):源 schema 损坏 ⇒ `unsupported-schema` 能力缺失可见,
9
+ // 绝不伪装「无匹配」;旧命中带 `stale` 保留,旧空集只说「缓存中未找到,当前源未核对」。
10
+ // store 绑定单一源路径:换源 sync 拒绝(source-mismatch),换源走显式 `rebindStore` 全量重建。
11
+ import fs from "node:fs"
12
+ import { createRequire } from "node:module"
13
+ import path from "node:path"
14
+
15
+ import { openDb } from "./sqlite-runtime.mjs"
16
+ import { extractParts, openSource, probeShape } from "./session-source.mjs"
17
+ import { buildMatchExpr, evaluateText, parseQuery, relaxAst, termMatches, tokensOf } from "./session-query.mjs"
18
+
19
+ const CAPABILITY_STATES = new Set([
20
+ "unsupported-schema",
21
+ "source-missing",
22
+ "source-unavailable",
23
+ "permission-denied",
24
+ ])
25
+
26
+
27
+ export function openStore(root) {
28
+ const dir = path.join(root, "index")
29
+ fs.mkdirSync(dir, { recursive: true })
30
+ const db = openDbSync(path.join(dir, "session-index.db"))
31
+ db.exec(`
32
+ CREATE TABLE IF NOT EXISTS parts (
33
+ part_id TEXT PRIMARY KEY NOT NULL,
34
+ message_id TEXT NOT NULL,
35
+ session_id TEXT NOT NULL,
36
+ project_id TEXT,
37
+ directory TEXT,
38
+ title TEXT,
39
+ role TEXT,
40
+ kind TEXT NOT NULL,
41
+ text TEXT NOT NULL,
42
+ time_created INTEGER,
43
+ message_time INTEGER,
44
+ seen_gen INTEGER NOT NULL
45
+ );
46
+ CREATE INDEX IF NOT EXISTS parts_session ON parts(session_id, message_time, message_id);
47
+ CREATE VIRTUAL TABLE IF NOT EXISTS parts_fts USING fts5(tokens, part_id UNINDEXED);
48
+ CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
49
+ `)
50
+ return {
51
+ db,
52
+ root,
53
+ close() { try { db.close() } catch { /* 已关 */ } },
54
+ }
55
+ }
56
+
57
+ // openDb 是 async(运行时探测);派生库的构造路径必须同步(openStore 被 CLI/工具双面调用)。
58
+ // 运行时探测只做一次并缓存:node:sqlite / bun:sqlite 的构造器都是同步的。
59
+ let _DbCtor = null
60
+ function openDbSync(file) {
61
+ if (_DbCtor) return new _DbCtor(file)
62
+ const req = createRequire(import.meta.url)
63
+ for (const spec of ["bun:sqlite", "node:sqlite"]) {
64
+ try {
65
+ const mod = req(spec)
66
+ const C = mod.DatabaseSync ?? mod.Database ?? mod.default?.Database ?? mod.default
67
+ if (typeof C === "function") {
68
+ _DbCtor = C
69
+ return new C(file)
70
+ }
71
+ } catch { /* 换下一个运行时 */ }
72
+ }
73
+ throw new Error("找不到可用的本地 SQLite(试过 bun:sqlite 与 node:sqlite)")
74
+ }
75
+
76
+ function metaGet(db, key) {
77
+ const row = db.prepare("SELECT value FROM meta WHERE key = ?").get(key)
78
+ return row ? row.value : null
79
+ }
80
+ function metaSet(db, key, value) {
81
+ db.prepare("INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value")
82
+ .run(key, String(value))
83
+ }
84
+
85
+ const nowIso = (now) => new Date(now ?? Date.now()).toISOString()
86
+
87
+ /**
88
+ * 全量幂等 sync:只读抽取源 → 自家库 upsert + sweep(staging generation 完成后才删除)。
89
+ * `extract` 是 DI 缝(中断/坏行夹具从这里注入),默认走 session-source 的逐 part 抽取。
90
+ */
91
+ export async function syncStore({ root, sourcePath, extract = null, now = null, includeToolOutput = false, scope_session_id = null } = {}) {
92
+ const store = openStore(root)
93
+ try {
94
+ const bound = metaGet(store.db, "source_path")
95
+ if (bound && sourcePath && bound !== sourcePath) {
96
+ return {
97
+ ok: false,
98
+ error_code: "source-mismatch",
99
+ state: metaGet(store.db, "state") ?? "ok",
100
+ error: `store 已绑定 ${bound},拒绝换源到 ${sourcePath}(换源走 rebind 全量重建)`,
101
+ }
102
+ }
103
+
104
+ // staging 开始:先落「backfilling」——之后任何中断都可见,旧索引不动。
105
+ metaSet(store.db, "state", "backfilling")
106
+ if (!bound && sourcePath) metaSet(store.db, "source_path", sourcePath)
107
+
108
+ let src
109
+ try {
110
+ src = await openSource(sourcePath)
111
+ } catch (e) {
112
+ metaSet(store.db, "state", e.code ?? "source-unavailable")
113
+ return { ok: false, error_code: e.code ?? "source-unavailable", state: e.code ?? "source-unavailable", error: e.message }
114
+ }
115
+
116
+ try {
117
+ const probe = probeShape(src)
118
+ if (!probe.ok) {
119
+ metaSet(store.db, "state", "unsupported-schema")
120
+ metaSet(store.db, "facts", JSON.stringify(probe.facts))
121
+ return {
122
+ ok: false,
123
+ error_code: "unsupported-schema",
124
+ state: "unsupported-schema",
125
+ facts: probe.facts,
126
+ error: `源形状认不出(unsupported-schema):${probe.facts.map((f) => `${f.code}:${f.detail}`).join(";")}`,
127
+ }
128
+ }
129
+
130
+ let ex
131
+ try {
132
+ ex = extract ? extract(src) : extractParts(src, { includeToolOutput, session_id: scope_session_id })
133
+ } catch (e) {
134
+ // 中断:state 保持 backfilling,旧索引逐行保留(还没动过一行)。
135
+ return { ok: false, error_code: "sync-interrupted", state: "backfilling", error: e.message }
136
+ }
137
+
138
+ const gen = Number(metaGet(store.db, "gen") ?? 0) + 1
139
+ const asOf = nowIso(now)
140
+ const segments = []
141
+ let staged = 0
142
+ let added = 0
143
+ let updated = 0
144
+ let removed = 0
145
+
146
+ try {
147
+ store.db.exec("BEGIN")
148
+ segments.push(0)
149
+ const upsert = store.db.prepare(`
150
+ INSERT INTO parts (part_id, message_id, session_id, project_id, directory, title,
151
+ role, kind, text, time_created, message_time, seen_gen)
152
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
153
+ ON CONFLICT(part_id) DO UPDATE SET
154
+ message_id = excluded.message_id, session_id = excluded.session_id,
155
+ project_id = excluded.project_id, directory = excluded.directory,
156
+ title = excluded.title, role = excluded.role, kind = excluded.kind,
157
+ text = excluded.text, time_created = excluded.time_created,
158
+ message_time = excluded.message_time, seen_gen = excluded.seen_gen
159
+ `)
160
+ for (const p of ex.parts) {
161
+ const exists = store.db.prepare("SELECT 1 FROM parts WHERE part_id = ?").get(p.part_id)
162
+ upsert.run(
163
+ p.part_id, p.message_id, p.session_id, p.project_id ?? null, p.directory ?? null,
164
+ p.title ?? null, p.role ?? null, p.kind, p.text, p.time_created ?? null,
165
+ p.message_time ?? null, gen,
166
+ )
167
+ // FTS 投影与原文同事务维护(三分不混:投影可裁剪、原文权威)
168
+ const row = store.db.prepare("SELECT rowid FROM parts WHERE part_id = ?").get(p.part_id)
169
+ store.db.prepare("DELETE FROM parts_fts WHERE rowid = ?").run(row.rowid)
170
+ store.db.prepare("INSERT INTO parts_fts(rowid, tokens, part_id) VALUES (?, ?, ?)")
171
+ .run(row.rowid, tokensOf(p.text), p.part_id)
172
+ if (exists) updated += 1
173
+ else added += 1
174
+ staged += 1
175
+ if (ex.parts.length > 0) segments.push(Number((staged / ex.parts.length).toFixed(4)))
176
+ }
177
+ // sweep:staging generation 完成后才删除撤回(FTS 投影同行撤)。
178
+ // scope_session_id=定向快刷:sweep 只撤该 session 的行(快刷只作加速,完整对账才是完备边界)。
179
+ const sweepScope = scope_session_id ? " AND session_id = ?" : ""
180
+ const sweepArgs = scope_session_id ? [gen, scope_session_id] : [gen]
181
+ store.db.prepare(`DELETE FROM parts_fts WHERE rowid IN (SELECT rowid FROM parts WHERE seen_gen < ?${sweepScope})`).run(...sweepArgs)
182
+ removed = store.db.prepare(`DELETE FROM parts WHERE seen_gen < ?${sweepScope}`).run(...sweepArgs).changes
183
+ const tally = store.db.prepare(`
184
+ SELECT COUNT(*) AS parts, COUNT(DISTINCT session_id) AS sessions, COUNT(DISTINCT message_id) AS messages
185
+ FROM parts
186
+ `).get()
187
+ const counts = { parts: tally.parts, sessions: tally.sessions, messages: tally.messages }
188
+ metaSet(store.db, "gen", gen)
189
+ metaSet(store.db, "state", "ok")
190
+ metaSet(store.db, "as_of", asOf)
191
+ metaSet(store.db, "last_sync_at", asOf)
192
+ metaSet(store.db, scope_session_id ? "last_fast_sync_at" : "last_full_reconcile_at", asOf)
193
+ metaSet(store.db, "counts", JSON.stringify(counts))
194
+ metaSet(store.db, "coverage", JSON.stringify({ ...counts, source_generation: gen }))
195
+ metaSet(store.db, "facts", JSON.stringify([]))
196
+ store.db.exec("COMMIT")
197
+ return {
198
+ ok: true,
199
+ state: "ok",
200
+ counts,
201
+ added,
202
+ updated,
203
+ removed,
204
+ segments,
205
+ as_of: asOf,
206
+ facts: ex.facts ?? [],
207
+ }
208
+ } catch (e) {
209
+ try { store.db.exec("ROLLBACK") } catch { /* 未开事务 */ }
210
+ // 坏行/写失败:事务回滚,旧索引逐行保留,state 停在 backfilling(如实)。
211
+ return { ok: false, error_code: "sync-failed", state: "backfilling", segments, error: e.message }
212
+ }
213
+ } finally {
214
+ await src.close()
215
+ }
216
+ } finally {
217
+ store.close()
218
+ }
219
+ }
220
+
221
+ function stateEnvelope(store) {
222
+ const state = metaGet(store.db, "state") ?? "ok"
223
+ const coverage = JSON.parse(metaGet(store.db, "coverage") ?? "{}")
224
+ return {
225
+ state,
226
+ coverage,
227
+ as_of: metaGet(store.db, "as_of"),
228
+ last_sync_at: metaGet(store.db, "last_sync_at"),
229
+ }
230
+ }
231
+
232
+ /**
233
+ * 原文扫描版搜索(S3a):LIKE 子串直扫自家快照,命中返回逐字原文 + 身份 + as_of。
234
+ * S2b 在此之上加保序段 bigram + AST + 原文后验(FTS 只出候选);本层是回退与最小闭环。
235
+ */
236
+ export function searchStore({ root, query, limit = 20, session_id = null, role = null, since = null, until = null, scanBudget = 50000, includeToolOutput = false, noRelax = false } = {}) {
237
+ const store = openStore(root)
238
+ try {
239
+ const env = stateEnvelope(store)
240
+ const stale = env.state !== "ok"
241
+ const q = String(query ?? "")
242
+ if (!q.trim()) {
243
+ return {
244
+ ok: false, error_code: "usage", state: env.state, coverage: env.coverage,
245
+ as_of: env.as_of, message: "需要查询词",
246
+ }
247
+ }
248
+ const ast = parseQuery(q)
249
+ const filters = []
250
+ const fArgs = []
251
+ if (session_id) { filters.push("session_id = ?"); fArgs.push(session_id) }
252
+ if (role) { filters.push("role = ?"); fArgs.push(role) }
253
+ if (since != null) { filters.push("time_created >= ?"); fArgs.push(Number.isFinite(Number(since)) ? Number(since) : Date.parse(since)) }
254
+ if (until != null) { filters.push("time_created <= ?"); fArgs.push(Number.isFinite(Number(until)) ? Number(until) : Date.parse(until)) }
255
+ if (!includeToolOutput) { filters.push("kind != 'tool-output'") }
256
+ const where = filters.length ? ` AND ${filters.join(" AND ")}` : ""
257
+ const cols = "part_id, message_id, session_id, project_id, directory, title, role, kind, text, time_created"
258
+ const max = Number(limit) > 0 ? Number(limit) : 20
259
+ let incomplete = false
260
+ let indexCorrupt = false
261
+ let workExamined = 0
262
+
263
+ const toHit = (r, matchedBy, route) => ({
264
+ session_id: r.session_id,
265
+ match_message_id: r.message_id,
266
+ match_part_id: r.part_id,
267
+ matched_role: r.role,
268
+ source_kind: r.kind === "tool-output" ? "tool-output" : "text-part",
269
+ project_id: r.project_id,
270
+ directory: r.directory,
271
+ title: r.title,
272
+ when: r.time_created != null ? new Date(r.time_created).toISOString() : null,
273
+ snippet: r.text.length > 200 ? `${r.text.slice(0, 200)}…` : r.text,
274
+ text: r.text,
275
+ matchedBy,
276
+ route,
277
+ })
278
+
279
+ const runTiers = (astNow, route) => {
280
+ const hits = []
281
+ const expr = buildMatchExpr(astNow)
282
+ if (expr) {
283
+ // ① FTS 只出候选 → 原文后验裁决(matchedBy=gram)
284
+ // 候选桶改为下方分页取(candIds 全量物化已废)
285
+ try {
286
+ // FTS 投影完整性:与原文行数不齐 ⇒ index-corrupt,阻断该路由走扫描兜底(绝不伪装空集)
287
+ const nParts = store.db.prepare("SELECT COUNT(*) AS n FROM parts").get().n
288
+ const nFts = store.db.prepare("SELECT COUNT(*) AS n FROM parts_fts").get().n
289
+ if (nParts !== nFts) indexCorrupt = true
290
+ else {
291
+ // 分页取候选(rowid 序=原序,语义逐字不变):命中满即停时不物化整个候选桶(容量判据 2 字 p95≤200ms)
292
+ const stmt = store.db.prepare("SELECT part_id FROM parts_fts WHERE parts_fts MATCH ? ORDER BY rowid LIMIT 512 OFFSET ?")
293
+ for (let off = 0; hits.length < max; off += 512) {
294
+ const chunk = stmt.all(expr, off)
295
+ if (!chunk.length) break
296
+ for (const { part_id: id } of chunk) {
297
+ if (hits.length >= max) break // 命中满即停:上限外的命中本就丢弃,输出不变(容量判据 2 字 p95≤200ms)
298
+ workExamined += 1
299
+ const r = store.db.prepare(`SELECT ${cols} FROM parts WHERE part_id = ?${where}`).get(id, ...fArgs)
300
+ if (r && evaluateText(r.text, astNow) && hits.length < max) hits.push(toHit(r, "gram", route))
301
+ }
302
+ }
303
+ }
304
+ } catch { indexCorrupt = true }
305
+ if (hits.length) return hits
306
+ }
307
+ if (!hits.length && (!expr || indexCorrupt)) {
308
+ // ② 无安全候选(1 字 CJK 等)或索引损坏:有界原文扫描(matchedBy=scan)
309
+ const budget = Number(scanBudget) > 0 ? Number(scanBudget) : 50000
310
+ const rows = store.db.prepare(`SELECT ${cols} FROM parts WHERE 1=1${where} ORDER BY time_created, part_id`).all(...fArgs)
311
+ let examined = 0
312
+ for (const r of rows) {
313
+ if (hits.length >= max) break // 同上:命中满即停
314
+ if (examined >= budget) { incomplete = true; break }
315
+ examined += 1
316
+ workExamined += 1
317
+ if (evaluateText(r.text, astNow) && hits.length < max) hits.push(toHit(r, "scan", route))
318
+ }
319
+ if (hits.length) return hits
320
+ }
321
+ if (!hits.length && astNow.op === "and" && astNow.positives.length === 1
322
+ && astNow.excludes.length === 0) {
323
+ // ③ 精确标题解析(Hermes 语义:子串不命中;matchedBy=title)
324
+ const term = astNow.positives[0]
325
+ if (term.kind !== "prefix") {
326
+ const sessions = store.db.prepare(
327
+ `SELECT DISTINCT session_id, title FROM parts WHERE title IS NOT NULL${where}`).all(...fArgs)
328
+ for (const s of sessions) {
329
+ if (s.title === term.text && hits.length < max) {
330
+ const anchor = store.db.prepare(
331
+ `SELECT ${cols} FROM parts WHERE session_id = ? ORDER BY time_created, part_id LIMIT 1`).get(s.session_id)
332
+ if (anchor) hits.push(toHit(anchor, "title", route))
333
+ }
334
+ }
335
+ }
336
+ }
337
+ return hits
338
+ }
339
+
340
+ let hits = runTiers(ast, "strict")
341
+ if (!hits.length && !noRelax) {
342
+ // 零命中自动放宽(gowxx 裁定①):AND→OR,保留排除词;命中显式标 route=relaxed
343
+ const relaxed = relaxAst(ast)
344
+ if (relaxed) hits = runTiers(relaxed, "relaxed")
345
+ }
346
+
347
+ let message
348
+ if (!hits.length) {
349
+ message = stale
350
+ ? "缓存中未找到,当前源未核对。"
351
+ : "缓存中未找到。可放宽:`alpha OR beta`、引号短语、NOT 排除、前缀 `deploy*`。"
352
+ }
353
+ return {
354
+ ok: true,
355
+ state: env.state,
356
+ coverage: env.coverage,
357
+ as_of: env.as_of,
358
+ stale,
359
+ count: hits.length,
360
+ results: hits,
361
+ message,
362
+ examined: workExamined,
363
+ ...(incomplete ? { incomplete: true } : {}),
364
+ ...(indexCorrupt ? { index_corrupt: true } : {}),
365
+ }
366
+ } finally {
367
+ store.close()
368
+ }
369
+ }
370
+
371
+ /** 状态:coverage + state 双维度,失效可见不撒谎。 */
372
+ export function statusStore({ root }) {
373
+ const store = openStore(root)
374
+ try {
375
+ const env = stateEnvelope(store)
376
+ const counts = JSON.parse(metaGet(store.db, "counts") ?? "{}")
377
+ const facts = JSON.parse(metaGet(store.db, "facts") ?? "[]")
378
+ return {
379
+ ok: true,
380
+ state: env.state,
381
+ capability_missing: CAPABILITY_STATES.has(env.state),
382
+ coverage: env.coverage,
383
+ counts,
384
+ source_path: metaGet(store.db, "source_path"),
385
+ bound: Boolean(metaGet(store.db, "source_path")),
386
+ as_of: env.as_of,
387
+ last_sync_at: env.last_sync_at,
388
+ last_fast_sync: metaGet(store.db, "last_fast_sync_at"),
389
+ last_full_reconcile: metaGet(store.db, "last_full_reconcile_at"),
390
+ pending: metaGet(store.db, "pending") === "1",
391
+ facts,
392
+ }
393
+ } finally {
394
+ store.close()
395
+ }
396
+ }
397
+
398
+ /** 从命中点续读:按身份取回窗口内的逐字原文(阅读单位=message,多 part 分列不拼接)。 */
399
+ export function readStore({ root, session_id, message_id = null, part_id = null, window = 5, position = null } = {}) {
400
+ const store = openStore(root)
401
+ try {
402
+ const env = stateEnvelope(store)
403
+ let anchor = null
404
+ if (part_id) {
405
+ anchor = store.db.prepare("SELECT * FROM parts WHERE part_id = ?").get(part_id)
406
+ if (!anchor) return { ok: false, error_code: "not-found", state: env.state, error: `没有这个 part:${part_id}` }
407
+ }
408
+ const mid = message_id ?? anchor?.message_id
409
+ if (!session_id && !mid) {
410
+ return { ok: false, error_code: "usage", state: env.state, error: "read 需要 --session 或 --message/--part" }
411
+ }
412
+ let sess = session_id
413
+ if (!sess && mid) {
414
+ const r = store.db.prepare("SELECT session_id FROM parts WHERE message_id = ? LIMIT 1").get(mid)
415
+ sess = r?.session_id
416
+ }
417
+ if (!sess) {
418
+ return { ok: false, error_code: "not-found", state: env.state, error: `没有这个 message:${mid}` }
419
+ }
420
+ const rows = store.db.prepare(`
421
+ SELECT part_id, message_id, session_id, role, kind, text, time_created, message_time
422
+ FROM parts
423
+ WHERE session_id = ?
424
+ ORDER BY message_time, message_id, time_created, part_id
425
+ `).all(sess)
426
+ // 窗口:以目标 message 为中心,前后各取 window 条 message。
427
+ const byMsg = new Map()
428
+ for (const r of rows) {
429
+ if (!byMsg.has(r.message_id)) byMsg.set(r.message_id, [])
430
+ byMsg.get(r.message_id).push(r)
431
+ }
432
+ const order = [...byMsg.keys()]
433
+ const center = mid ? order.indexOf(mid) : (position === "tail" ? Math.max(0, order.length - 1) : 0)
434
+ const lo = Math.max(0, center - Number(window))
435
+ const hi = Math.min(order.length, center + Number(window) + 1)
436
+ const messages = order.slice(lo, hi).map((id) => {
437
+ const parts = byMsg.get(id)
438
+ return {
439
+ message_id: id,
440
+ session_id: parts[0].session_id,
441
+ role: parts[0].role,
442
+ when: parts[0].message_time != null ? new Date(parts[0].message_time).toISOString() : null,
443
+ parts: parts.map((p) => ({ part_id: p.part_id, kind: p.kind, text: p.text })),
444
+ }
445
+ })
446
+ return { ok: true, state: env.state, as_of: env.as_of, messages }
447
+ } finally {
448
+ store.close()
449
+ }
450
+ }
451
+
452
+ /** 换源:显式 rebind 全量重建(两源 ID 不混——旧源行全部清掉)。 */
453
+ export function rebindStore({ root, sourcePath } = {}) {
454
+ const store = openStore(root)
455
+ try {
456
+ const cleared = store.db.prepare("DELETE FROM parts").run().changes
457
+ metaSet(store.db, "source_path", sourcePath)
458
+ metaSet(store.db, "state", "backfilling")
459
+ metaSet(store.db, "gen", 0)
460
+ return { ok: true, cleared, source_path: sourcePath }
461
+ } finally {
462
+ store.close()
463
+ }
464
+ }
465
+
466
+ // S4 调度器簿记用(pending 位的持久化面):只导出,不改上面任何锚点。
467
+ export { metaGet, metaSet }
@@ -0,0 +1,161 @@
1
+ // 会话查询核心(G4 S2b):查询 AST + 保序连续段 bigram 分词 + FTS 只出候选、**原文后验**为权威。
2
+ // 不复用 retrieve.mjs 的 search()(判据明确);与 S2a 的派生库(session-index.mjs)共用。
3
+ //
4
+ // 语义(黄金语料对检 Hermes session_search):
5
+ // · 多词默认 AND(FTS5 ANDs all terms by default);`OR` 显式放宽;`NOT`/`-` 排除;
6
+ // · 引号 `"..."`=连续原文短语(引号内空格不分词);尾 `*`=前缀;
7
+ // · CJK:保序连续段 bigram(不去重、不跨字界);1 字/无安全候选 ⇒ 有界原文扫描,标 matchedBy=scan;
8
+ // · 命中标 matchedBy:gram(FTS 候选+后验)/ scan(兜底)/ title(精确标题解析,子串不命中);
9
+ // · 零命中自动放宽(AND→OR,保留排除词)标 route=relaxed——gowxx 裁定①(有意增强,精确语义仍可见)。
10
+ const CJK_CHAR = /[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]/
11
+ const WORD_CHAR = /[a-z0-9_]/i
12
+
13
+ const escapeRe = (s) => String(s).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
14
+
15
+ /** 有序分词:拉丁词(小写)+ CJK 保序连续段 bigram(不去重、不跨字界);单字 CJK 标 cjk1。 */
16
+ export function tokenize(text) {
17
+ const out = []
18
+ let run = ""
19
+ let word = ""
20
+ const flushRun = () => {
21
+ if (!run) return
22
+ if (run.length === 1) out.push({ text: run, cjk1: true })
23
+ else for (let i = 0; i + 1 < run.length; i += 1) out.push({ text: run.slice(i, i + 2), cjk1: false })
24
+ run = ""
25
+ }
26
+ const flushWord = () => {
27
+ if (!word) return
28
+ out.push({ text: word.toLowerCase(), cjk1: false })
29
+ word = ""
30
+ }
31
+ for (const ch of String(text)) {
32
+ if (CJK_CHAR.test(ch)) { flushWord(); run += ch; continue }
33
+ flushRun()
34
+ if (WORD_CHAR.test(ch)) { word += ch; continue }
35
+ flushWord()
36
+ }
37
+ flushRun()
38
+ flushWord()
39
+ return out
40
+ }
41
+
42
+ /** 查询解析:引号短语 / 尾*前缀 / OR / NOT(或 -) / 默认 AND。 */
43
+ export function parseQuery(query) {
44
+ const q = String(query)
45
+ const segments = []
46
+ let buf = ""
47
+ let quoted = false
48
+ for (let i = 0; i < q.length; i += 1) {
49
+ const ch = q[i]
50
+ if (ch === '"') {
51
+ if (quoted && q[i + 1] === '"') { buf += '"'; i += 1; continue }
52
+ if (quoted) { segments.push({ text: buf, quoted: true }); buf = ""; quoted = false; continue }
53
+ if (buf.trim()) segments.push({ text: buf.trim(), quoted: false })
54
+ buf = ""
55
+ quoted = true
56
+ continue
57
+ }
58
+ if (!quoted && /\s/.test(ch)) {
59
+ if (buf.trim()) segments.push({ text: buf.trim(), quoted: false })
60
+ buf = ""
61
+ continue
62
+ }
63
+ buf += ch
64
+ }
65
+ if (buf.trim()) segments.push({ text: buf.trim(), quoted })
66
+
67
+ const positives = []
68
+ const excludes = []
69
+ const orBuckets = [[]]
70
+ let pendingNeg = false
71
+ for (const seg of segments) {
72
+ let text = seg.text
73
+ if (!seg.quoted && (text === "OR" || text === "or")) {
74
+ orBuckets.push([])
75
+ continue
76
+ }
77
+ let neg = pendingNeg
78
+ pendingNeg = false
79
+ if (!seg.quoted && (text === "NOT" || text === "not" || text === "-")) {
80
+ pendingNeg = true
81
+ continue
82
+ }
83
+ if (!seg.quoted && (text.startsWith("NOT ") || text.startsWith("not "))) {
84
+ neg = true
85
+ text = text.slice(4).trim()
86
+ } else if (!seg.quoted && text.startsWith("-") && text.length > 1) {
87
+ neg = true
88
+ text = text.slice(1)
89
+ }
90
+ let prefix = false
91
+ if (!seg.quoted && text.endsWith("*") && text.length > 1) {
92
+ prefix = true
93
+ text = text.slice(0, -1)
94
+ }
95
+ const tokens = tokenize(text)
96
+ const term = {
97
+ kind: seg.quoted ? "phrase" : prefix ? "prefix" : "term",
98
+ text,
99
+ tokens,
100
+ unsafe: tokens.length === 0 || tokens.some((t) => t.cjk1),
101
+ }
102
+ if (neg) excludes.push(term)
103
+ else orBuckets[orBuckets.length - 1].push(term)
104
+ }
105
+ const buckets = orBuckets.filter((b) => b.length > 0)
106
+ const op = buckets.length > 1 ? "or" : "and"
107
+ for (const b of buckets) positives.push(...b)
108
+ return { op, positives, excludes, raw: q }
109
+ }
110
+
111
+ /** 原文后验(权威):term 的原文形态必须真的出现在 text 里。 */
112
+ export function termMatches(text, term) {
113
+ const hay = String(text)
114
+ const low = hay.toLowerCase()
115
+ const needle = term.text.toLowerCase()
116
+ if (term.kind === "prefix") {
117
+ return new RegExp(`(^|[^a-z0-9_])${escapeRe(term.text)}`, "i").test(hay)
118
+ }
119
+ return low.includes(needle)
120
+ }
121
+
122
+ /** 整段文本对 AST 的判定(原文后验口径;AND 默认 / OR / NOT)。 */
123
+ export function evaluateText(text, ast) {
124
+ const anyPos = ast.positives.some((t) => termMatches(text, t))
125
+ const allPos = ast.positives.every((t) => termMatches(text, t))
126
+ const noExcl = ast.excludes.every((t) => !termMatches(text, t))
127
+ if (!noExcl) return false
128
+ return ast.op === "or" ? anyPos : allPos
129
+ }
130
+
131
+ const ftsQuote = (tok) => `"${String(tok).replace(/"/g, '""')}"`
132
+
133
+ /** FTS 候选表达式(只出候选;语义由 evaluateText 后验裁决)。无安全候选返回 null。 */
134
+ export function buildMatchExpr(ast) {
135
+ const parts = []
136
+ for (const t of ast.positives) {
137
+ if (t.unsafe) return null
138
+ const phrase = t.tokens.map((x) => ftsQuote(x.text)).join(" ")
139
+ parts.push(t.kind === "prefix" ? `${ftsQuote(t.tokens.map((x) => x.text).join(" "))}*` : ftsQuote(phrase))
140
+ }
141
+ for (const t of ast.excludes) {
142
+ if (t.unsafe) return null
143
+ const phrase = t.tokens.map((x) => ftsQuote(x.text)).join(" ")
144
+ parts.push(`NOT ${ftsQuote(phrase)}`)
145
+ }
146
+ if (parts.length === 0) return null
147
+ return ast.op === "or"
148
+ ? `(${parts.filter((p) => !p.startsWith("NOT ")).join(" OR ")}) ${parts.filter((p) => p.startsWith("NOT ")).join(" ")}`
149
+ : parts.join(" ")
150
+ }
151
+
152
+ /** 放宽级联(gowxx 裁定①):AND→OR(保留排除词)。单正词无可放宽 ⇒ null。 */
153
+ export function relaxAst(ast) {
154
+ if (ast.op !== "and" || ast.positives.length < 2) return null
155
+ return { op: "or", positives: ast.positives, excludes: ast.excludes, raw: ast.raw }
156
+ }
157
+
158
+ /** 受控原文生成 tokens 串(FTS 投影用;与查询侧同一分词器)。 */
159
+ export function tokensOf(text) {
160
+ return tokenize(text).map((t) => t.text).join(" ")
161
+ }