@jjh32456/longlive 0.0.0-stage → 2.0.0
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.
- package/CHANGELOG.md +235 -0
- package/LICENSE +21 -0
- package/QUICKSTART.md +362 -0
- package/README.en.md +64 -0
- package/README.md +256 -2
- package/SPEC.md +211 -0
- package/build-info.json +1665 -0
- package/cordis.patch.yml +208 -0
- package/docs/A1-MIGRATION.md +75 -0
- package/docs/ANSWER-GUARD.md +92 -0
- package/docs/ARCHITECTURE.md +128 -0
- package/docs/AUTO-RECALL-WIRING.md +115 -0
- package/docs/AUTO-RECALL.md +237 -0
- package/docs/CONCEPTS.md +143 -0
- package/docs/CONFIG.md +839 -0
- package/docs/ERRORS.md +271 -0
- package/docs/FAQ.md +186 -0
- package/docs/FEATURES.md +579 -0
- package/docs/INDEX-FRESHNESS.md +21 -0
- package/docs/METRICS.md +244 -0
- package/docs/MIGRATION-1.6.0.md +220 -0
- package/docs/OPERATIONS.md +439 -0
- package/docs/PANEL-INTEGRATION.md +190 -0
- package/docs/PRIVACY.md +88 -0
- package/docs/QUICKSTART.md +155 -0
- package/docs/RAW-INDEX-POLICY.md +7 -0
- package/docs/README.en.md +48 -0
- package/docs/RESIDENT-WATCHER.md +90 -0
- package/docs/SESSION-WATCH.md +214 -0
- package/docs/TOOLS.md +184 -0
- package/docs/TROUBLESHOOTING.md +329 -0
- package/icon.svg +11 -0
- package/lib/client.js +436 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +163 -4
- package/runbook.md +343 -0
- package/scripts/archive-digest-build.mjs +668 -0
- package/scripts/auto-truncate-run.ps1 +752 -0
- package/scripts/backfill-auto-cards.mjs +98 -0
- package/scripts/edges-build.mjs +1003 -0
- package/scripts/index-maintain.mjs +39 -0
- package/scripts/index-reconcile.mjs +49 -0
- package/scripts/index-status.mjs +28 -0
- package/scripts/install-resident-watcher.ps1 +15 -0
- package/scripts/install-session-watch.ps1 +332 -0
- package/scripts/install-surgery-task.ps1 +174 -0
- package/scripts/lib/auto-truncate-run.ps1 +512 -0
- package/scripts/lib/session-watch-fixture.mjs +207 -0
- package/scripts/longlive-doctor.mjs +578 -0
- package/scripts/metrics-read.mjs +79 -0
- package/scripts/metrics-sample.mjs +215 -0
- package/scripts/migrate-180.mjs +163 -0
- package/scripts/migrate-200.mjs +8 -0
- package/scripts/migrate-a1-legacy.mjs +62 -0
- package/scripts/migrate-lifecycle.mjs +157 -0
- package/scripts/pack.mjs +392 -0
- package/scripts/recall-index-build.mjs +128 -0
- package/scripts/recall-links-build.mjs +420 -0
- package/scripts/rescore-cards.mjs +36 -0
- package/scripts/resident-watcher-status.ps1 +15 -0
- package/scripts/resident-watcher.ps1 +643 -0
- package/scripts/session-watch-drill.mjs +553 -0
- package/scripts/session-watch-status.ps1 +146 -0
- package/scripts/session-watch.mjs +1367 -0
- package/scripts/surgery-inspect.mjs +122 -0
- package/scripts/surgery-run.cmd +34 -0
- package/scripts/truncate-cli.mjs +279 -0
- package/scripts/unattended-surgery.ps1 +1019 -0
- package/scripts/uninstall-resident-watcher.ps1 +15 -0
- package/scripts/uninstall-session-watch.ps1 +192 -0
- package/scripts/verify-card-anchors.mjs +138 -0
- package/scripts/watch-loop.ps1 +916 -0
- package/src/actions/audit.js +125 -0
- package/src/actions/evidence.js +122 -0
- package/src/actions/fs.js +162 -0
- package/src/activity/index.js +873 -0
- package/src/activity/model.js +351 -0
- package/src/activity/store.js +786 -0
- package/src/activity/summary.js +180 -0
- package/src/activity/thinking.js +191 -0
- package/src/adapters/constants.js +11 -0
- package/src/adapters/engram/data/aliases.json +51 -0
- package/src/adapters/engram/data/policy.json +8 -0
- package/src/adapters/engram/data/routing-rules.json +546 -0
- package/src/adapters/engram/index.js +278 -0
- package/src/adapters/registry.js +315 -0
- package/src/answer/audit.js +238 -0
- package/src/answer/claim-guard.mjs +234 -0
- package/src/answer/evidence.js +30 -0
- package/src/answer/guard.js +1370 -0
- package/src/answer/index.js +1086 -0
- package/src/answer/query.js +111 -0
- package/src/answer/second-hop.mjs +101 -0
- package/src/auto-truncate-status.js +164 -0
- package/src/auto-truncate.js +1181 -0
- package/src/autoprocedure/candidate.js +342 -0
- package/src/autoprocedure/config.js +122 -0
- package/src/autoprocedure/evidence.js +345 -0
- package/src/autoprocedure/index.js +83 -0
- package/src/autoprocedure/ledger.js +329 -0
- package/src/autoprocedure/lint.js +232 -0
- package/src/autoprocedure/llm.js +409 -0
- package/src/autoprocedure/locks.js +102 -0
- package/src/autoprocedure/paths.js +39 -0
- package/src/autoprocedure/privacy.js +87 -0
- package/src/autoprocedure/rules.js +288 -0
- package/src/autoprocedure/runtime.js +718 -0
- package/src/autoprocedure/session-reader.js +328 -0
- package/src/backup.js +310 -0
- package/src/bus/bus.mjs +1446 -0
- package/src/codec.js +269 -0
- package/src/compaction/cut-engine.js +44 -0
- package/src/compaction/engine-core.js +1237 -0
- package/src/compaction/entry.js +228 -0
- package/src/compaction.js +230 -0
- package/src/conclusion.js +366 -0
- package/src/config.js +835 -0
- package/src/d6/runtime.js +517 -0
- package/src/d6/surface.js +181 -0
- package/src/deps.js +189 -0
- package/src/engine-status.js +141 -0
- package/src/features.js +1035 -0
- package/src/handoff/index.js +1077 -0
- package/src/handoff/model.js +1058 -0
- package/src/handoff/store.js +1233 -0
- package/src/heartbeat.js +385 -0
- package/src/home.js +16 -0
- package/src/host-version.js +280 -0
- package/src/hot-truncate-diag.js +98 -0
- package/src/identity/card-marker.js +281 -0
- package/src/identity/handover.js +845 -0
- package/src/identity/index.js +337 -0
- package/src/identity/inject-position.js +133 -0
- package/src/identity/writeback.js +344 -0
- package/src/identity.js +118 -0
- package/src/index.js +647 -0
- package/src/lifecycle/gap-clocks.js +364 -0
- package/src/lifecycle/index.js +269 -0
- package/src/lifecycle/proactive.js +1426 -0
- package/src/live-target.js +212 -0
- package/src/live.js +1603 -0
- package/src/log-rotation.js +153 -0
- package/src/memory/a1-migration.js +190 -0
- package/src/memory/activity-capture.js +229 -0
- package/src/memory/anchor-fallback.js +116 -0
- package/src/memory/anchors.js +194 -0
- package/src/memory/archive-cold-state.mjs +794 -0
- package/src/memory/archive-staging.mjs +305 -0
- package/src/memory/archive.mjs +415 -0
- package/src/memory/audit-records.js +222 -0
- package/src/memory/auto-cards.js +441 -0
- package/src/memory/capture-host.js +297 -0
- package/src/memory/capture.js +496 -0
- package/src/memory/card-anchors.js +203 -0
- package/src/memory/card-priority.js +110 -0
- package/src/memory/cards.js +425 -0
- package/src/memory/catchup.mjs +534 -0
- package/src/memory/conclusion-distill.js +381 -0
- package/src/memory/conclusion-drafts.js +243 -0
- package/src/memory/conflicts.js +1060 -0
- package/src/memory/consolidate.js +834 -0
- package/src/memory/decay.js +311 -0
- package/src/memory/distill.js +485 -0
- package/src/memory/event-index.js +1826 -0
- package/src/memory/evidence-chain.js +295 -0
- package/src/memory/evidence.js +213 -0
- package/src/memory/filter-runner.js +555 -0
- package/src/memory/filter.js +1035 -0
- package/src/memory/forget-v2.js +680 -0
- package/src/memory/forget.js +531 -0
- package/src/memory/frames-activation.js +249 -0
- package/src/memory/frontmatter.js +454 -0
- package/src/memory/fts-query.js +342 -0
- package/src/memory/governance.js +604 -0
- package/src/memory/index-freshness.js +234 -0
- package/src/memory/index.js +435 -0
- package/src/memory/l2-gate.js +169 -0
- package/src/memory/land.mjs +743 -0
- package/src/memory/lifecycle.js +235 -0
- package/src/memory/lock.js +121 -0
- package/src/memory/maintenance.js +1149 -0
- package/src/memory/manifest.js +245 -0
- package/src/memory/memory-health.mjs +607 -0
- package/src/memory/migrate-200.js +1681 -0
- package/src/memory/migrate-lifecycle.js +1808 -0
- package/src/memory/migrate.js +139 -0
- package/src/memory/paths.js +229 -0
- package/src/memory/procedure-candidate.mjs +377 -0
- package/src/memory/procedure.js +982 -0
- package/src/memory/prospective-memory.mjs +362 -0
- package/src/memory/provenance.js +119 -0
- package/src/memory/recall-feedback.mjs +406 -0
- package/src/memory/recall-v2.js +218 -0
- package/src/memory/recall.js +357 -0
- package/src/memory/reconcile.js +265 -0
- package/src/memory/records.js +433 -0
- package/src/memory/reinforce.js +281 -0
- package/src/memory/retention.js +162 -0
- package/src/memory/review.js +124 -0
- package/src/memory/state.js +279 -0
- package/src/memory/tiers.js +168 -0
- package/src/memory/topic-phrases.js +73 -0
- package/src/memory/trust.js +97 -0
- package/src/memory/turn-budget.mjs +290 -0
- package/src/memory/version-chain.js +264 -0
- package/src/memory/wake-bridge.mjs +2999 -0
- package/src/memory/wal.js +137 -0
- package/src/memory/working-frame.js +779 -0
- package/src/metrics/classify.mjs +191 -0
- package/src/metrics/estimate.mjs +108 -0
- package/src/metrics/index.mjs +204 -0
- package/src/metrics/measure.mjs +462 -0
- package/src/metrics/prestep-latency.mjs +307 -0
- package/src/metrics/store.mjs +264 -0
- package/src/original.js +294 -0
- package/src/policy/threshold-policy.js +224 -0
- package/src/policy-profile.js +463 -0
- package/src/recall/anaphora.mjs +87 -0
- package/src/recall/archive-config.mjs +130 -0
- package/src/recall/archive-fallback.mjs +390 -0
- package/src/recall/archive-search.mjs +428 -0
- package/src/recall/archive-state.mjs +588 -0
- package/src/recall/brain.mjs +501 -0
- package/src/recall/cards.mjs +202 -0
- package/src/recall/current-line.mjs +110 -0
- package/src/recall/edges.js +398 -0
- package/src/recall/embedding.mjs +698 -0
- package/src/recall/entities.mjs +112 -0
- package/src/recall/explain.mjs +443 -0
- package/src/recall/force-policy.mjs +138 -0
- package/src/recall/gate-log.mjs +280 -0
- package/src/recall/gate-metrics.mjs +191 -0
- package/src/recall/index.js +1337 -0
- package/src/recall/inject-order.mjs +279 -0
- package/src/recall/link-recall.mjs +183 -0
- package/src/recall/links.mjs +696 -0
- package/src/recall/privacy.mjs +208 -0
- package/src/recall/recall-core.mjs +810 -0
- package/src/recall/shared-visibility.js +302 -0
- package/src/recall/time-normalizer.mjs +196 -0
- package/src/recall/turn-budget-inject.mjs +154 -0
- package/src/retention/cold-gate.mjs +146 -0
- package/src/retention/config.js +163 -0
- package/src/retention/index.js +801 -0
- package/src/role/activation.js +191 -0
- package/src/role/attention.js +318 -0
- package/src/role/base.js +36 -0
- package/src/role/channels.js +423 -0
- package/src/role/index.js +425 -0
- package/src/role/interfaces.js +115 -0
- package/src/role/personality.js +370 -0
- package/src/role/readers.js +151 -0
- package/src/role/relationships.js +477 -0
- package/src/role/store.js +202 -0
- package/src/role/writeprotect.js +373 -0
- package/src/router/aliases.json +182 -0
- package/src/router/background/agent-runner.mjs +239 -0
- package/src/router/background/anchor.mjs +323 -0
- package/src/router/background/audit.mjs +337 -0
- package/src/router/background/budget-ledger.mjs +648 -0
- package/src/router/background/host-sim.mjs +451 -0
- package/src/router/background/index.mjs +81 -0
- package/src/router/background/memory.mjs +63 -0
- package/src/router/background/mock-llm.mjs +203 -0
- package/src/router/background/queue.mjs +224 -0
- package/src/router/background/retry.mjs +255 -0
- package/src/router/background/router.mjs +1459 -0
- package/src/router/background/stream.mjs +276 -0
- package/src/router/background/tool-policy.mjs +255 -0
- package/src/router/design-headings.json +221 -0
- package/src/router/face/config.mjs +155 -0
- package/src/router/face/context.mjs +284 -0
- package/src/router/face/face.mjs +466 -0
- package/src/router/face/identity.mjs +130 -0
- package/src/router/face/index.mjs +65 -0
- package/src/router/face/journal.mjs +119 -0
- package/src/router/face/llm.mjs +252 -0
- package/src/router/face/outbox.mjs +153 -0
- package/src/router/face/paths.mjs +54 -0
- package/src/router/judge.mjs +987 -0
- package/src/router/policies/generic.json +131 -0
- package/src/router/route.js +1766 -0
- package/src/router/router.mjs +535 -0
- package/src/router/routing-rules.json +816 -0
- package/src/router/run-sim.mjs +530 -0
- package/src/router/runtime.js +569 -0
- package/src/router/service/apply.mjs +1218 -0
- package/src/router/service/board.mjs +712 -0
- package/src/router/service/caller.mjs +131 -0
- package/src/router/service/config.mjs +361 -0
- package/src/router/service/context.mjs +314 -0
- package/src/router/service/hint.mjs +668 -0
- package/src/router/service/lease.mjs +494 -0
- package/src/router/service/live.mjs +251 -0
- package/src/router/service/lock.mjs +550 -0
- package/src/router/service/merge.mjs +255 -0
- package/src/router/service/model-resolve.mjs +350 -0
- package/src/router/service/paths.mjs +168 -0
- package/src/router/service/proposals.mjs +1461 -0
- package/src/router/service/queue.mjs +477 -0
- package/src/router/service/reconcile.mjs +271 -0
- package/src/router/service/service.mjs +2998 -0
- package/src/router/service/sources.mjs +352 -0
- package/src/router/service/status.mjs +520 -0
- package/src/router/service/store.mjs +476 -0
- package/src/router/service/ticklock.mjs +239 -0
- package/src/router/service/tokens.mjs +95 -0
- package/src/router/service/tools.mjs +248 -0
- package/src/router/service/wake.mjs +544 -0
- package/src/router/service/wal.mjs +685 -0
- package/src/router/shadow.mjs +821 -0
- package/src/surgery-recovery.js +1909 -0
- package/src/tool-output.js +485 -0
- package/src/tools.js +3262 -0
- package/src/truncate-visible.js +2416 -0
- package/src/truncate.js +999 -0
- package/src/ui/actions.js +1312 -0
- package/src/ui/flags.js +259 -0
- package/src/ui/panel-api.js +371 -0
- package/src/ui/panel-auth.js +251 -0
- package/src/ui/panel-integrity.js +243 -0
- package/src/ui/routes-readonly.js +759 -0
- package/src/ui/routes.js +284 -0
- package/src/util/append-store.js +368 -0
- package/src/util/local-day.js +30 -0
- package/src/util/redact.js +227 -0
- package/src/util/stale-locks.js +148 -0
- package/src/version.js +99 -0
- package/test/fixtures/pre-step-container.mjs +100 -0
- package/test/p1_probe.mjs +97 -0
|
@@ -0,0 +1,1826 @@
|
|
|
1
|
+
// src/memory/event-index.js — M2-A:统一 memory event 模型 + 事件索引(SQLite FTS5)
|
|
2
|
+
//
|
|
3
|
+
// 依据提案 §1.1 / §2.2 / §9.1(v2.6.3)与 FTS5-MEMGAP-EVIDENCE(任务):
|
|
4
|
+
// * L1 事件索引是 L0 会话日志的**派生**:可整体删除后仅凭 L0 重建(硬验收);
|
|
5
|
+
// * 主查询入口 = SQLite FTS5(node:sqlite 内置,本机 3.53.4 / FTS5=1);
|
|
6
|
+
// * 双表:`events_fts` = trigram(raw_text) 覆盖中文 ≥3 字子串/版本号/ID/日期;
|
|
7
|
+
// `events_terms` = unicode61(term_text 预分词 bigram + aliases) 补 2 字 CJK;
|
|
8
|
+
// * 单写管道:一条 EventRecord 在同一个事务里写 events + events_fts + events_terms,
|
|
9
|
+
// 并追加派生 JSONL 审计层 `events.audit.jsonl`(可导出/diff/迁移);
|
|
10
|
+
// * 幂等:同一 (id, digest) 重放不产生新行;会话副本按 visible-messages digest 去重。
|
|
11
|
+
//
|
|
12
|
+
// 本模块只读 L0(绝不写 .dsh/sessions),所有落盘都在 <memoryRoot>/.longlive/index/。
|
|
13
|
+
|
|
14
|
+
import { createRequire } from 'node:module';
|
|
15
|
+
import crypto from 'node:crypto';
|
|
16
|
+
import fs from 'node:fs';
|
|
17
|
+
import os from 'node:os';
|
|
18
|
+
import path from 'node:path';
|
|
19
|
+
|
|
20
|
+
import { decompressFrame, deriveMessagesDigest, parseSession, splitFrames, stableStringify } from '../codec.js';
|
|
21
|
+
import { appendJsonLine } from '../util/append-store.js';
|
|
22
|
+
import { extractTerms, termTextOf, aliasesOf, buildFtsCandidates } from './fts-query.js';
|
|
23
|
+
import { makeSessionTurnAnchor, turnDigest } from './anchors.js';
|
|
24
|
+
|
|
25
|
+
const require = createRequire(import.meta.url);
|
|
26
|
+
let sqliteModule = null;
|
|
27
|
+
|
|
28
|
+
/** Lazy node:sqlite loader: keeps the module loadable on hosts without it. */
|
|
29
|
+
function sqlite() {
|
|
30
|
+
if (sqliteModule === null) sqliteModule = require('node:sqlite');
|
|
31
|
+
return sqliteModule;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// S8: import 放在 SQLite loader 之后(ESM 合法),与同文件顶部 S1 的
|
|
35
|
+
// append-store import 错开,降低两个补丁在同一文件同一区域的文本冲突。
|
|
36
|
+
import { extractTopicPhrases } from './topic-phrases.js';
|
|
37
|
+
import { DEFAULT_TIERING, TIER_SCHEMA, resolveTierPolicy, buildTierHint, isBusyError } from './tiers.js';
|
|
38
|
+
|
|
39
|
+
export const INDEX_DIRNAME = 'index';
|
|
40
|
+
export const EVENTS_DB = 'events.db';
|
|
41
|
+
export const EVENTS_AUDIT = 'events.audit.jsonl';
|
|
42
|
+
export const FRAMES_DIR = 'frames';
|
|
43
|
+
export const BUILD_STATE = 'build-state.json';
|
|
44
|
+
export const EVENT_SCHEMA = 'events/v1';
|
|
45
|
+
// S8: 2 = 新增 topic_phrases_json(向后兼容:老库自动 ALTER,老记录读成 [])。
|
|
46
|
+
export const INDEX_SCHEMA_VERSION = 3;
|
|
47
|
+
|
|
48
|
+
const SCHEMA = `
|
|
49
|
+
CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT);
|
|
50
|
+
CREATE TABLE IF NOT EXISTS events (
|
|
51
|
+
id TEXT PRIMARY KEY,
|
|
52
|
+
session_id TEXT NOT NULL,
|
|
53
|
+
turn INTEGER NOT NULL,
|
|
54
|
+
seq_start INTEGER,
|
|
55
|
+
seq_end INTEGER,
|
|
56
|
+
time_start INTEGER,
|
|
57
|
+
time_end INTEGER,
|
|
58
|
+
project TEXT,
|
|
59
|
+
kind TEXT,
|
|
60
|
+
summary TEXT,
|
|
61
|
+
topics_json TEXT,
|
|
62
|
+
terms_json TEXT,
|
|
63
|
+
topic_phrases_json TEXT,
|
|
64
|
+
tier TEXT,
|
|
65
|
+
counts_json TEXT,
|
|
66
|
+
anchors_json TEXT,
|
|
67
|
+
digest TEXT NOT NULL,
|
|
68
|
+
built_at INTEGER,
|
|
69
|
+
source TEXT
|
|
70
|
+
);
|
|
71
|
+
CREATE INDEX IF NOT EXISTS idx_events_session_turn ON events(session_id, turn);
|
|
72
|
+
CREATE INDEX IF NOT EXISTS idx_events_kind ON events(kind);
|
|
73
|
+
CREATE INDEX IF NOT EXISTS idx_events_time ON events(time_end);
|
|
74
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS events_fts USING fts5(id UNINDEXED, raw_text, tokenize='trigram');
|
|
75
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS events_terms USING fts5(id UNINDEXED, term_text, aliases, tokenize='unicode61');
|
|
76
|
+
`;
|
|
77
|
+
|
|
78
|
+
export class IndexError extends Error {
|
|
79
|
+
constructor(code, message, detail = undefined) {
|
|
80
|
+
super(message);
|
|
81
|
+
this.name = 'IndexError';
|
|
82
|
+
this.code = code;
|
|
83
|
+
if (detail !== undefined) this.detail = detail;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function indexPaths(memoryRoot) {
|
|
88
|
+
const root = path.resolve(String(memoryRoot ?? ''));
|
|
89
|
+
const dir = path.join(root, '.longlive', INDEX_DIRNAME);
|
|
90
|
+
return {
|
|
91
|
+
root,
|
|
92
|
+
dir,
|
|
93
|
+
db: path.join(dir, EVENTS_DB),
|
|
94
|
+
audit: path.join(dir, EVENTS_AUDIT),
|
|
95
|
+
framesDir: path.join(dir, FRAMES_DIR),
|
|
96
|
+
buildState: path.join(dir, BUILD_STATE),
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function nowIso(now) {
|
|
101
|
+
const value = now();
|
|
102
|
+
return (value instanceof Date ? value : new Date(value)).toISOString();
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function sha256Hex(text) {
|
|
106
|
+
return crypto.createHash('sha256').update(text, 'utf8').digest('hex');
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function textPartsToText(parts) {
|
|
110
|
+
if (typeof parts === 'string') return parts.trim();
|
|
111
|
+
if (!Array.isArray(parts)) return '';
|
|
112
|
+
return parts
|
|
113
|
+
.filter((block) => block?.type === 'text' && typeof block.text === 'string')
|
|
114
|
+
.map((block) => block.text)
|
|
115
|
+
.join('\n')
|
|
116
|
+
.trim();
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* P1-2: assistant steps carry their text under `data.message.content`
|
|
121
|
+
* ({role, content:[reasoning, text, tool-call…]}), while user messages carry it
|
|
122
|
+
* under `data.content`. Reading only `data.content` made every assistant text
|
|
123
|
+
* empty, so summary/terms/topicPhrases never saw what the assistant said.
|
|
124
|
+
* Reasoning blocks are still dropped: only `type === 'text'` blocks count.
|
|
125
|
+
* `data.content` stays as the fallback so legacy events and older fixtures keep
|
|
126
|
+
* working unchanged.
|
|
127
|
+
*/
|
|
128
|
+
function assistantTextOf(event) {
|
|
129
|
+
const fromStep = textPartsToText(event?.data?.message?.content);
|
|
130
|
+
if (fromStep !== '') return fromStep;
|
|
131
|
+
const legacy = event?.data?.content;
|
|
132
|
+
return Array.isArray(legacy) ? textPartsToText(legacy) : '';
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function textOf(event) {
|
|
136
|
+
if (event?.type === 'assistant/message') return assistantTextOf(event);
|
|
137
|
+
// User messages keep the exact historical extraction (array of blocks only).
|
|
138
|
+
const parts = event?.data?.content;
|
|
139
|
+
if (!Array.isArray(parts)) return '';
|
|
140
|
+
return textPartsToText(parts);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function classifyKind(corpus, counts) {
|
|
144
|
+
const text = String(corpus ?? '');
|
|
145
|
+
if (/(决定|拍板|裁定|结论|选型|方案|定稿|通过)/.test(text)) return 'conclusion';
|
|
146
|
+
if (/(事故|故障|报错|失败|回归|broken|error|crash)/i.test(text)) return 'incident';
|
|
147
|
+
if (/(计划|下一步|待办|排期|里程碑)/.test(text)) return 'plan';
|
|
148
|
+
if (counts.toolCalls > 0) return 'ops';
|
|
149
|
+
return 'chat';
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function rawTextFor(record) {
|
|
153
|
+
const parts = [
|
|
154
|
+
`[${record.kind}] ${record.summary}`,
|
|
155
|
+
Array.isArray(record.terms) ? record.terms.join(' ') : '',
|
|
156
|
+
Array.isArray(record.topics) ? record.topics.join(' ') : '',
|
|
157
|
+
Array.isArray(record.topicPhrases) ? record.topicPhrases.join(' ') : '',
|
|
158
|
+
record.project ?? '',
|
|
159
|
+
];
|
|
160
|
+
return parts.filter((part) => typeof part === 'string' && part !== '').join('\n').slice(0, 20000);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function parseRow(row) {
|
|
164
|
+
if (!row) return null;
|
|
165
|
+
return {
|
|
166
|
+
id: row.id,
|
|
167
|
+
sessionId: row.session_id,
|
|
168
|
+
turn: row.turn,
|
|
169
|
+
seqStart: row.seq_start,
|
|
170
|
+
seqEnd: row.seq_end,
|
|
171
|
+
timeStart: row.time_start,
|
|
172
|
+
timeEnd: row.time_end,
|
|
173
|
+
project: row.project,
|
|
174
|
+
kind: row.kind,
|
|
175
|
+
summary: row.summary,
|
|
176
|
+
topics: safeJson(row.topics_json, []),
|
|
177
|
+
terms: safeJson(row.terms_json, []),
|
|
178
|
+
topicPhrases: safeJson(row.topic_phrases_json, []),
|
|
179
|
+
counts: safeJson(row.counts_json, {}),
|
|
180
|
+
anchors: safeJson(row.anchors_json, []),
|
|
181
|
+
digest: row.digest,
|
|
182
|
+
builtAt: row.built_at,
|
|
183
|
+
source: row.source,
|
|
184
|
+
tier: row.tier ?? null,
|
|
185
|
+
...(typeof row.rank === 'number' ? { rank: row.rank } : {}),
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function safeJson(text, fallback) {
|
|
190
|
+
if (text === null || text === undefined || text === '') return fallback;
|
|
191
|
+
try {
|
|
192
|
+
return JSON.parse(text);
|
|
193
|
+
} catch {
|
|
194
|
+
return fallback;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function validateRecord(record) {
|
|
199
|
+
if (!record || typeof record !== 'object') throw new IndexError('E_EVENT_INVALID', 'event must be an object');
|
|
200
|
+
if (typeof record.id !== 'string' || record.id === '') throw new IndexError('E_EVENT_ID', 'event.id required');
|
|
201
|
+
if (typeof record.sessionId !== 'string' || record.sessionId === '') {
|
|
202
|
+
throw new IndexError('E_EVENT_SESSION', 'event.sessionId required');
|
|
203
|
+
}
|
|
204
|
+
if (!Number.isInteger(record.turn) || record.turn < 0) throw new IndexError('E_EVENT_TURN', 'event.turn required');
|
|
205
|
+
if (typeof record.digest !== 'string' || !/^[0-9a-f]{64}$/.test(record.digest)) {
|
|
206
|
+
throw new IndexError('E_EVENT_DIGEST', 'event.digest required (sha256 hex)');
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Open (and lazily create) the event index.
|
|
212
|
+
*
|
|
213
|
+
* @param {object} options
|
|
214
|
+
* @param {string} options.memoryRoot
|
|
215
|
+
* @param {() => Date} [options.now]
|
|
216
|
+
* @param {string} [options.dbPath] override for tests
|
|
217
|
+
*/
|
|
218
|
+
/**
|
|
219
|
+
* v3 §5.5/§6.4:只读扫描路径(1–2 字兜底)+ tier 谓词(同型改造,M9/MINOR-3)。
|
|
220
|
+
* Read-only event search used by memory_recall/status surfaces. Opens the DB
|
|
221
|
+
* with `readOnly: true` when supported; never creates the index or changes WAL.
|
|
222
|
+
*/
|
|
223
|
+
export function searchEventsReadOnly({ memoryRoot = '', query = '', limit = 5, tier = 'auto', currentSessionId = '', sessionId = '', kind = '', tiering = DEFAULT_TIERING, nowMs = Date.now() } = {}) {
|
|
224
|
+
const root = path.resolve(String(memoryRoot ?? ''));
|
|
225
|
+
if (root === '') return { ok: false, code: 'E_MEMORY_ROOT', rows: [] };
|
|
226
|
+
const paths = indexPaths(root);
|
|
227
|
+
if (!fs.existsSync(paths.db)) return { ok: false, code: 'E_EVENTS_INDEX_MISSING', rows: [] };
|
|
228
|
+
const q = String(query ?? '').trim().toLowerCase();
|
|
229
|
+
if (q === '') return { ok: true, rows: [], strategy: 'empty-query' };
|
|
230
|
+
const { warmCutoff, hotCutoff, warmDays } = tierCutoffs(nowMs, tiering);
|
|
231
|
+
const suppressedCap = Math.max(1, Math.min(1000, Number(tiering?.suppressedCap ?? DEFAULT_TIERING.suppressedCap) || DEFAULT_TIERING.suppressedCap));
|
|
232
|
+
const mode = String(tiering?.mode ?? DEFAULT_TIERING.mode);
|
|
233
|
+
let db = null;
|
|
234
|
+
try {
|
|
235
|
+
const { DatabaseSync } = sqlite();
|
|
236
|
+
try {
|
|
237
|
+
db = new DatabaseSync(paths.db, { readOnly: true });
|
|
238
|
+
} catch {
|
|
239
|
+
db = new DatabaseSync(paths.db);
|
|
240
|
+
}
|
|
241
|
+
db.exec('PRAGMA busy_timeout = 2000');
|
|
242
|
+
let busyTimeoutMs = 2000;
|
|
243
|
+
try { const row = db.prepare('PRAGMA busy_timeout').get(); if (Number.isFinite(Number(row?.timeout))) busyTimeoutMs = Number(row.timeout); } catch { /* older sqlite */ }
|
|
244
|
+
// v4 §6.5-2 / Z7:off 不读 meta(只探列)
|
|
245
|
+
let state;
|
|
246
|
+
if (mode === 'off') {
|
|
247
|
+
// MINOR-1(round1):off 的列探测失败也不许解释成"无列"(M5 的读失败语义同样适用)。
|
|
248
|
+
let hasTierColumn = false;
|
|
249
|
+
try {
|
|
250
|
+
hasTierColumn = db.prepare('PRAGMA table_info(events)').all().some((c) => c.name === 'tier');
|
|
251
|
+
} catch (error) {
|
|
252
|
+
const busy = isBusyError(error);
|
|
253
|
+
return {
|
|
254
|
+
ok: false,
|
|
255
|
+
code: busy ? 'E_INDEX_QUERY_BUSY' : 'E_INDEX_QUERY_FAILED',
|
|
256
|
+
retryable: busy,
|
|
257
|
+
detail: { where: 'table_info', errcode: error?.errcode ?? null, errstr: error?.errstr ?? String(error?.message ?? error) },
|
|
258
|
+
rows: [],
|
|
259
|
+
stats: { strategy: 'readonly-scan', busyTimeoutMs },
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
state = { ok: true, hasTierColumn, passAtMs: null, passAtRaw: null, labelsSource: null };
|
|
263
|
+
} else {
|
|
264
|
+
state = readTierState(db, { nowMs, tiering });
|
|
265
|
+
}
|
|
266
|
+
if (state.ok === false) {
|
|
267
|
+
return { ok: false, code: state.code, retryable: Boolean(state.retryable), detail: state.detail, rows: [], stats: { strategy: 'readonly-scan', busyTimeoutMs } };
|
|
268
|
+
}
|
|
269
|
+
const policy = resolveTierPolicy({
|
|
270
|
+
mode: tiering.mode,
|
|
271
|
+
requested: tier,
|
|
272
|
+
hasTierColumn: state.hasTierColumn,
|
|
273
|
+
passAtMs: state.passAtMs,
|
|
274
|
+
labelsSource: state.labelsSource,
|
|
275
|
+
maxStaleHours: tiering.maxStaleHours ?? DEFAULT_TIERING.maxStaleHours,
|
|
276
|
+
nowMs,
|
|
277
|
+
hasReader: Boolean(currentSessionId),
|
|
278
|
+
});
|
|
279
|
+
if (policy.error) return { ok: false, code: policy.error, rows: [], message: `tier request rejected: ${tier}` };
|
|
280
|
+
const reader = currentSessionId ? String(currentSessionId) : null;
|
|
281
|
+
const sessionFilter = String(sessionId ?? '').trim();
|
|
282
|
+
const kindFilter = String(kind ?? '').trim();
|
|
283
|
+
const columns = state.hasTierColumn
|
|
284
|
+
? ['id', 'session_id', 'turn', 'kind', 'summary', 'terms_json', 'anchors_json', 'digest', 'time_end', 'tier']
|
|
285
|
+
: ['id', 'session_id', 'turn', 'kind', 'summary', 'terms_json', 'anchors_json', 'digest', 'time_end'];
|
|
286
|
+
const selectCols = state.hasTierColumn
|
|
287
|
+
? 'id, session_id, turn, kind, summary, terms_json, anchors_json, digest, time_end, tier'
|
|
288
|
+
: 'id, session_id, turn, kind, summary, terms_json, anchors_json, digest, time_end';
|
|
289
|
+
const rows = db.prepare(`SELECT ${selectCols} FROM events`).all();
|
|
290
|
+
const terms = q.split(/\s+/u).filter(Boolean);
|
|
291
|
+
const scored = [];
|
|
292
|
+
let matchedTotal = 0;
|
|
293
|
+
let visibleCount = 0;
|
|
294
|
+
for (const row of rows) {
|
|
295
|
+
let termsList = [];
|
|
296
|
+
try { termsList = JSON.parse(row.terms_json ?? '[]'); } catch { /* corrupt row */ }
|
|
297
|
+
const haystack = `${row.summary ?? ''} ${Array.isArray(termsList) ? termsList.join(' ') : ''}`.toLowerCase();
|
|
298
|
+
let score = 0;
|
|
299
|
+
for (const term of terms) {
|
|
300
|
+
if (haystack.includes(term)) score += 1;
|
|
301
|
+
if (String(row.summary ?? '').toLowerCase().includes(term)) score += 2;
|
|
302
|
+
}
|
|
303
|
+
if (score <= 0) continue;
|
|
304
|
+
if (sessionFilter && !String(row.session_id ?? '').includes(sessionFilter)) continue;
|
|
305
|
+
if (kindFilter && String(row.kind ?? '') !== kindFilter) continue;
|
|
306
|
+
matchedTotal += 1; // v4 §6.11:过滤 session/kind 后、tier 前
|
|
307
|
+
const tierValue = state.hasTierColumn ? (row.tier ?? null) : null;
|
|
308
|
+
if (policy.filtering && !rowVisible(tierValue, row.session_id, row.time_end, policy, { warmCutoff, hotCutoff, reader })) {
|
|
309
|
+
continue; // 被挡:不占 20 行窗口
|
|
310
|
+
}
|
|
311
|
+
visibleCount += 1;
|
|
312
|
+
let anchors = [];
|
|
313
|
+
try { anchors = JSON.parse(row.anchors_json ?? '[]'); } catch { /* corrupt */ }
|
|
314
|
+
scored.push({
|
|
315
|
+
id: row.id,
|
|
316
|
+
sessionId: row.session_id,
|
|
317
|
+
turn: row.turn,
|
|
318
|
+
kind: row.kind,
|
|
319
|
+
summary: row.summary ?? '',
|
|
320
|
+
terms: Array.isArray(termsList) ? termsList : [],
|
|
321
|
+
anchor: Array.isArray(anchors) ? anchors[0] ?? null : null,
|
|
322
|
+
tier: tierValue,
|
|
323
|
+
timeEnd: row.time_end ?? null,
|
|
324
|
+
score,
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
scored.sort((a, b) => b.score - a.score || String(a.id).localeCompare(String(b.id)));
|
|
328
|
+
const suppressed = Math.max(0, matchedTotal - visibleCount);
|
|
329
|
+
const capped = suppressed > suppressedCap;
|
|
330
|
+
const coldSuppressed = policy.filtering ? Math.min(suppressedCap, suppressed) : 0;
|
|
331
|
+
// ★ M-A6:同 searchEventsFts——off 不读 meta ⇒ 这组字段缺席。
|
|
332
|
+
const tierMetaFields = mode === 'off' ? {} : {
|
|
333
|
+
tierPassAt: state.passAtRaw,
|
|
334
|
+
tierStale: Boolean(policy.stale),
|
|
335
|
+
tierLabelsUsable: Boolean(policy.labelsUsable),
|
|
336
|
+
tierLabelsSource: state.labelsSource,
|
|
337
|
+
};
|
|
338
|
+
const fields = {
|
|
339
|
+
tierFilter: policy.tierFilter ?? null,
|
|
340
|
+
tierApplied: Boolean(policy.filtering),
|
|
341
|
+
suppressedBasis: policy.suppressedBasis ?? null,
|
|
342
|
+
coldSuppressed,
|
|
343
|
+
coldSuppressedCapped: capped,
|
|
344
|
+
suppressedCountStrategy: policy.filtering ? 'scan' : null,
|
|
345
|
+
...tierMetaFields,
|
|
346
|
+
queryDegraded: false,
|
|
347
|
+
queryDegradedCode: null,
|
|
348
|
+
warmDays,
|
|
349
|
+
};
|
|
350
|
+
const hint = buildTierHint({ ...fields, hits: scored.length, suppressedCap });
|
|
351
|
+
return {
|
|
352
|
+
ok: true,
|
|
353
|
+
rows: scored.slice(0, Math.max(1, Math.min(20, Number(limit) || 5))),
|
|
354
|
+
strategy: 'readonly-scan',
|
|
355
|
+
matched: scored.length,
|
|
356
|
+
matchedTotal,
|
|
357
|
+
visibleCount,
|
|
358
|
+
...fields,
|
|
359
|
+
hint,
|
|
360
|
+
stats: { strategy: 'readonly-scan', countStrategy: policy.filtering ? 'scan' : null, columns, scan: { columns }, matchedTotal, visibleCount, busyTimeoutMs },
|
|
361
|
+
};
|
|
362
|
+
} catch (error) {
|
|
363
|
+
return { ok: false, code: error?.code ?? 'E_EVENTS_READ', message: String(error?.message ?? error), rows: [] };
|
|
364
|
+
} finally {
|
|
365
|
+
try { db?.close(); } catch { /* best effort */ }
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function tierCutoffs(nowMs, tiering) {
|
|
370
|
+
const warmDays = Number(tiering?.warmDays ?? DEFAULT_TIERING.warmDays);
|
|
371
|
+
const hotDays = Number(tiering?.hotDays ?? DEFAULT_TIERING.hotDays);
|
|
372
|
+
return { warmDays, warmCutoff: nowMs - warmDays * 86400000, hotCutoff: nowMs - hotDays * 86400000 };
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/** 附录 B:三套谓词(label / time / label-explicit);cutoff 内联避免绑定顺序坑。 */
|
|
376
|
+
function tierPredicate(policy, { warmCutoff, hotCutoff, reader }) {
|
|
377
|
+
if (!policy.filtering) return { sql: '', binds: [] };
|
|
378
|
+
if (policy.sqlKind === 'label') {
|
|
379
|
+
const binds = [];
|
|
380
|
+
let sql = "e.tier IN ('hot','warm')";
|
|
381
|
+
if (reader) { sql += ' OR e.session_id = ?'; binds.push(reader); }
|
|
382
|
+
if (reader) { sql += ` OR (e.tier IS NULL AND (e.time_end >= ${warmCutoff} OR e.session_id = ?))`; binds.push(reader); } else { sql += ` OR (e.tier IS NULL AND e.time_end >= ${warmCutoff})`; }
|
|
383
|
+
return { sql: ` AND (${sql})`, binds };
|
|
384
|
+
}
|
|
385
|
+
if (policy.sqlKind === 'time') {
|
|
386
|
+
const binds = [];
|
|
387
|
+
let sql = `e.time_end >= ${warmCutoff}`;
|
|
388
|
+
if (reader) { sql += ' OR e.session_id = ?'; binds.push(reader); }
|
|
389
|
+
return { sql: ` AND (${sql})`, binds };
|
|
390
|
+
}
|
|
391
|
+
// label-explicit(附录 B ③;hot 叠 overlay,warm/cold 不叠)
|
|
392
|
+
const wanted = String(policy.requested);
|
|
393
|
+
const binds = [wanted, wanted];
|
|
394
|
+
let sql = `e.tier = ? OR (e.tier IS NULL AND ? = CASE WHEN e.time_end >= ${hotCutoff} THEN 'hot' WHEN e.time_end >= ${warmCutoff} THEN 'warm' ELSE 'cold' END)`;
|
|
395
|
+
if (policy.overlay && reader) { sql += ' OR e.session_id = ?'; binds.push(reader); }
|
|
396
|
+
return { sql: ` AND (${sql})`, binds };
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/** JS 侧同义词(只读扫描路径用;与 tierPredicate 的语义一一对应)。 */
|
|
400
|
+
function rowVisible(tierValue, sessionId, timeEnd, policy, { warmCutoff, hotCutoff, reader }) {
|
|
401
|
+
const t = timeEnd ?? null;
|
|
402
|
+
const isReader = reader !== null && String(sessionId) === reader;
|
|
403
|
+
const computed = t !== null && t >= hotCutoff ? 'hot' : (t !== null && t >= warmCutoff ? 'warm' : 'cold');
|
|
404
|
+
if (policy.sqlKind === 'label') return ['hot', 'warm'].includes(tierValue) || isReader || (tierValue === null && (computed !== 'cold' || isReader));
|
|
405
|
+
if (policy.sqlKind === 'time') return computed !== 'cold' || isReader;
|
|
406
|
+
const explicit = String(policy.requested);
|
|
407
|
+
if (tierValue === explicit) return true;
|
|
408
|
+
if (tierValue === null && computed === explicit) return true;
|
|
409
|
+
if (policy.overlay && isReader) return true;
|
|
410
|
+
return false;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* FTS5 fast path over the same derived index (v3 §6.4 重写版):
|
|
415
|
+
* - busy_timeout=2000 on the read-only handle;
|
|
416
|
+
* - per-attempt error recording (no `catch { rows=[] }`);
|
|
417
|
+
* - all-attempts-failed => ok:false (never a fake empty);
|
|
418
|
+
* - same-attempt double COUNT for coldSuppressed (M10).
|
|
419
|
+
*/
|
|
420
|
+
// __countFault: 仅测试用的内部注入位(M-A4 / Y10;不经配置、不进工具面,§2.2-11 显式例外)。
|
|
421
|
+
export function searchEventsFts({ memoryRoot = '', query = '', limit = 8, sessionId = '', kind = '', tier = 'auto', currentSessionId = '', tiering = DEFAULT_TIERING, nowMs = Date.now(), __countFault = false } = {}) {
|
|
422
|
+
const root = path.resolve(String(memoryRoot ?? ''));
|
|
423
|
+
if (!root) return { ok: false, code: 'E_MEMORY_ROOT', rows: [] };
|
|
424
|
+
const paths = indexPaths(root);
|
|
425
|
+
if (!fs.existsSync(paths.db)) return { ok: false, code: 'E_EVENTS_INDEX_MISSING', rows: [] };
|
|
426
|
+
const q = String(query ?? '').trim();
|
|
427
|
+
if (!q) return { ok: true, rows: [], strategy: 'empty-query' };
|
|
428
|
+
const cap = Math.max(1, Math.min(100, Number(limit) || 8));
|
|
429
|
+
const suppressedCap = Math.max(1, Math.min(1000, Number(tiering?.suppressedCap ?? DEFAULT_TIERING.suppressedCap) || DEFAULT_TIERING.suppressedCap));
|
|
430
|
+
const sessionFilter = String(sessionId ?? '').trim();
|
|
431
|
+
const kindFilter = String(kind ?? '').trim();
|
|
432
|
+
const extra = [];
|
|
433
|
+
const tailBinds = [];
|
|
434
|
+
if (sessionFilter) {
|
|
435
|
+
const escaped = sessionFilter.replace(/[!%_]/g, (ch) => `!${ch}`);
|
|
436
|
+
extra.push("e.session_id LIKE ? ESCAPE '!'");
|
|
437
|
+
tailBinds.push(`%${escaped}%`);
|
|
438
|
+
}
|
|
439
|
+
if (kindFilter) { extra.push('e.kind = ?'); tailBinds.push(kindFilter); }
|
|
440
|
+
const tail = extra.length ? ` AND ${extra.join(' AND ')}` : '';
|
|
441
|
+
const textLength = [...q].length;
|
|
442
|
+
const attempts = [];
|
|
443
|
+
if (textLength >= 3) attempts.push({ strategy: 'trigram', table: 'events_fts' });
|
|
444
|
+
attempts.push({ strategy: 'terms', table: 'events_terms' });
|
|
445
|
+
const term = `"${q.replace(/"/g, '""')}"`;
|
|
446
|
+
const { warmCutoff, hotCutoff, warmDays } = tierCutoffs(nowMs, tiering);
|
|
447
|
+
const mode = String(tiering?.mode ?? DEFAULT_TIERING.mode);
|
|
448
|
+
let db = null;
|
|
449
|
+
try {
|
|
450
|
+
const { DatabaseSync } = sqlite();
|
|
451
|
+
try {
|
|
452
|
+
db = new DatabaseSync(paths.db, { readOnly: true });
|
|
453
|
+
} catch {
|
|
454
|
+
db = new DatabaseSync(paths.db);
|
|
455
|
+
}
|
|
456
|
+
db.exec('PRAGMA busy_timeout = 2000');
|
|
457
|
+
let busyTimeoutMs = 2000;
|
|
458
|
+
try { const row = db.prepare('PRAGMA busy_timeout').get(); if (Number.isFinite(Number(row?.timeout))) busyTimeoutMs = Number(row.timeout); } catch { /* older sqlite */ }
|
|
459
|
+
// ★ M5/Z7:off 不读 meta(只探列);显式 tier 在 off 下仍按 A7b 抛/生效
|
|
460
|
+
let state;
|
|
461
|
+
if (mode === 'off') {
|
|
462
|
+
// MINOR-1(round1):off 的列探测失败也不许解释成"无列"(M5 的读失败语义同样适用)。
|
|
463
|
+
let hasTierColumn = false;
|
|
464
|
+
try {
|
|
465
|
+
hasTierColumn = db.prepare('PRAGMA table_info(events)').all().some((c) => c.name === 'tier');
|
|
466
|
+
} catch (error) {
|
|
467
|
+
const busy = isBusyError(error);
|
|
468
|
+
return {
|
|
469
|
+
ok: false,
|
|
470
|
+
code: busy ? 'E_INDEX_QUERY_BUSY' : 'E_INDEX_QUERY_FAILED',
|
|
471
|
+
retryable: busy,
|
|
472
|
+
detail: { where: 'table_info', errcode: error?.errcode ?? null, errstr: error?.errstr ?? String(error?.message ?? error) },
|
|
473
|
+
rows: [],
|
|
474
|
+
tierFilter: null,
|
|
475
|
+
queryDegraded: false,
|
|
476
|
+
stats: { strategy: 'none', busyTimeoutMs, attempts: [] },
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
state = { ok: true, hasTierColumn, passAtMs: null, passAtRaw: null, labelsSource: null };
|
|
480
|
+
} else {
|
|
481
|
+
state = readTierState(db, { nowMs, tiering });
|
|
482
|
+
}
|
|
483
|
+
if (state.ok === false) {
|
|
484
|
+
// v4 §6.5-3:绝不解释成 no-tier-column / no-pass-meta,绝不静默切 time-fallback
|
|
485
|
+
return {
|
|
486
|
+
ok: false,
|
|
487
|
+
code: state.code,
|
|
488
|
+
retryable: Boolean(state.retryable),
|
|
489
|
+
detail: state.detail,
|
|
490
|
+
message: `tier state unavailable: ${state.code}`,
|
|
491
|
+
rows: [],
|
|
492
|
+
tierFilter: null,
|
|
493
|
+
queryDegraded: false,
|
|
494
|
+
stats: { strategy: 'none', busyTimeoutMs, attempts: [] },
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
const policy = resolveTierPolicy({
|
|
498
|
+
mode: tiering.mode,
|
|
499
|
+
requested: tier,
|
|
500
|
+
hasTierColumn: state.hasTierColumn,
|
|
501
|
+
passAtMs: state.passAtMs,
|
|
502
|
+
labelsSource: state.labelsSource,
|
|
503
|
+
maxStaleHours: tiering.maxStaleHours ?? DEFAULT_TIERING.maxStaleHours,
|
|
504
|
+
nowMs,
|
|
505
|
+
hasReader: Boolean(currentSessionId),
|
|
506
|
+
});
|
|
507
|
+
if (policy.error) {
|
|
508
|
+
return { ok: false, code: policy.error, rows: [], message: `tier request rejected: ${tier}`, tierFilter: null, stats: { strategy: 'none', busyTimeoutMs, attempts: [] } };
|
|
509
|
+
}
|
|
510
|
+
const reader = currentSessionId ? String(currentSessionId) : null;
|
|
511
|
+
const tp = tierPredicate(policy, { warmCutoff, hotCutoff, reader });
|
|
512
|
+
const selectCols = state.hasTierColumn
|
|
513
|
+
? 'e.id, e.session_id, e.turn, e.kind, e.summary, e.time_end, e.tier'
|
|
514
|
+
: 'e.id, e.session_id, e.turn, e.kind, e.summary, e.time_end'; // ★ M4:无列库 SELECT 里没有 tier
|
|
515
|
+
const columnsFor = state.hasTierColumn
|
|
516
|
+
? ['e.id', 'e.session_id', 'e.turn', 'e.kind', 'e.summary', 'e.time_end', 'e.tier']
|
|
517
|
+
: ['e.id', 'e.session_id', 'e.turn', 'e.kind', 'e.summary', 'e.time_end'];
|
|
518
|
+
const selectSql = (a) => `SELECT ${selectCols} FROM ${a.table} f JOIN events e ON e.id = f.id WHERE ${a.table} MATCH ?${tail}${tp.sql} ORDER BY bm25(${a.table}) LIMIT ?`;
|
|
519
|
+
const countSql = (a, withPred) => `SELECT COUNT(*) AS n FROM ${a.table} f JOIN events e ON e.id = f.id WHERE ${a.table} MATCH ?${tail}${withPred ? tp.sql : ''}`;
|
|
520
|
+
let rows = [];
|
|
521
|
+
const attemptErrors = [];
|
|
522
|
+
let strategy = 'none';
|
|
523
|
+
let successCount = 0;
|
|
524
|
+
for (const attempt of attempts) {
|
|
525
|
+
try {
|
|
526
|
+
const got = db.prepare(selectSql(attempt)).all(term, ...tailBinds, ...tp.binds, cap);
|
|
527
|
+
successCount += 1;
|
|
528
|
+
strategy = attempt.strategy;
|
|
529
|
+
if (got.length > 0) { rows = got; break; } // ★ 命中路径不变(不影响计数)
|
|
530
|
+
strategy = `${attempt.strategy}-empty`;
|
|
531
|
+
} catch (error) {
|
|
532
|
+
attemptErrors.push({ strategy: attempt.strategy, code: error?.code ?? null, errcode: error?.errcode ?? null, busy: isBusyError(error) });
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
// ★ M-A6:off 不读 meta(Z7),因此这组字段"省略"而不是伪造 stale:true;
|
|
536
|
+
// 口径写死为"省略"(round4 M-A6 二选一),C8/Z8 的 off 分支按缺席断言。
|
|
537
|
+
const tierMetaFields = mode === 'off' ? {} : {
|
|
538
|
+
tierPassAt: state.passAtRaw,
|
|
539
|
+
tierStale: Boolean(policy.stale),
|
|
540
|
+
tierLabelsUsable: Boolean(policy.labelsUsable),
|
|
541
|
+
tierLabelsSource: state.labelsSource,
|
|
542
|
+
};
|
|
543
|
+
const baseFields = {
|
|
544
|
+
tierFilter: policy.tierFilter ?? null,
|
|
545
|
+
tierApplied: Boolean(policy.filtering),
|
|
546
|
+
suppressedBasis: policy.suppressedBasis ?? null,
|
|
547
|
+
coldSuppressed: 0,
|
|
548
|
+
coldSuppressedCapped: false,
|
|
549
|
+
suppressedCountStrategy: null,
|
|
550
|
+
...tierMetaFields,
|
|
551
|
+
queryDegraded: attemptErrors.length > 0,
|
|
552
|
+
queryDegradedCode: attemptErrors[0]?.code ?? null,
|
|
553
|
+
warmDays,
|
|
554
|
+
};
|
|
555
|
+
// §6.5-5:rows===0 且所有 attempt 都抛错 => ok:false(绝不假空)
|
|
556
|
+
if (rows.length === 0 && successCount === 0) {
|
|
557
|
+
const busy = attemptErrors.length > 0 && attemptErrors.every((e) => e.busy);
|
|
558
|
+
return {
|
|
559
|
+
ok: false,
|
|
560
|
+
code: busy ? 'E_INDEX_QUERY_BUSY' : 'E_INDEX_QUERY_FAILED',
|
|
561
|
+
retryable: busy,
|
|
562
|
+
message: `FTS query failed (${attemptErrors.map((e) => `${e.strategy}:${e.code}`).join(', ')})`,
|
|
563
|
+
detail: { attemptErrors },
|
|
564
|
+
rows: [],
|
|
565
|
+
...baseFields,
|
|
566
|
+
stats: { strategy, busyTimeoutMs, attempts: [] },
|
|
567
|
+
};
|
|
568
|
+
}
|
|
569
|
+
// ★★ B1-①:计数与命中路径彻底解耦——逐 attempt 独立 total/visible,按 hidden 取 argmax。
|
|
570
|
+
let coldSuppressed = 0;
|
|
571
|
+
let capped = false;
|
|
572
|
+
let countStrategy = null;
|
|
573
|
+
let countTotal = null;
|
|
574
|
+
let countVisible = null;
|
|
575
|
+
let countMs = 0;
|
|
576
|
+
const attemptStats = [];
|
|
577
|
+
if (policy.filtering) {
|
|
578
|
+
const countStarted = Date.now();
|
|
579
|
+
let bestHidden = -1;
|
|
580
|
+
for (const attempt of attempts) {
|
|
581
|
+
const st = { strategy: attempt.strategy, columns: columnsFor.slice(), predicate: policy.sqlKind ?? 'none', total: null, visible: null, hidden: null, error: null };
|
|
582
|
+
attemptStats.push(st);
|
|
583
|
+
try {
|
|
584
|
+
if (__countFault) throw Object.assign(new Error('injected count fault (test only)'), { code: 'E_INJECTED_COUNT_FAULT' });
|
|
585
|
+
const total = Number(db.prepare(countSql(attempt, false)).get(term, ...tailBinds)?.n ?? 0);
|
|
586
|
+
const visible = Number(db.prepare(countSql(attempt, true)).get(term, ...tailBinds, ...tp.binds)?.n ?? 0);
|
|
587
|
+
st.total = total;
|
|
588
|
+
st.visible = visible;
|
|
589
|
+
st.hidden = Math.max(0, total - visible);
|
|
590
|
+
if (st.hidden > bestHidden) {
|
|
591
|
+
bestHidden = st.hidden;
|
|
592
|
+
countStrategy = attempt.strategy;
|
|
593
|
+
countTotal = total;
|
|
594
|
+
countVisible = visible;
|
|
595
|
+
}
|
|
596
|
+
} catch (error) {
|
|
597
|
+
const busy = isBusyError(error);
|
|
598
|
+
st.error = { code: error?.code ?? null, errcode: error?.errcode ?? null, busy };
|
|
599
|
+
attemptErrors.push({ strategy: `${attempt.strategy}-count`, code: error?.code ?? null, errcode: error?.errcode ?? null, busy });
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
countMs = Date.now() - countStarted;
|
|
603
|
+
if (bestHidden >= 0) {
|
|
604
|
+
capped = bestHidden > suppressedCap;
|
|
605
|
+
coldSuppressed = Math.min(suppressedCap, bestHidden);
|
|
606
|
+
} else {
|
|
607
|
+
coldSuppressed = null; // 全部 COUNT 失败 => 无法统计(不是 0)
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
const degraded = attemptErrors.length > 0;
|
|
611
|
+
const fields = {
|
|
612
|
+
...baseFields,
|
|
613
|
+
coldSuppressed,
|
|
614
|
+
coldSuppressedCapped: capped,
|
|
615
|
+
suppressedCountStrategy: countStrategy,
|
|
616
|
+
queryDegraded: degraded,
|
|
617
|
+
queryDegradedCode: degraded
|
|
618
|
+
? (attemptErrors.some((e) => e.busy) ? 'E_INDEX_QUERY_BUSY' : 'E_INDEX_QUERY_FAILED')
|
|
619
|
+
: null,
|
|
620
|
+
};
|
|
621
|
+
const hint = buildTierHint({ ...fields, hits: rows.length, suppressedCap });
|
|
622
|
+
return {
|
|
623
|
+
ok: true,
|
|
624
|
+
strategy,
|
|
625
|
+
matched: rows.length,
|
|
626
|
+
rows: rows.map((row) => ({
|
|
627
|
+
id: row.id,
|
|
628
|
+
sessionId: row.session_id,
|
|
629
|
+
turn: row.turn,
|
|
630
|
+
kind: row.kind,
|
|
631
|
+
summary: row.summary ?? '',
|
|
632
|
+
tier: state.hasTierColumn ? (row.tier ?? null) : null, // ★ M4:映射条件化
|
|
633
|
+
timeEnd: row.time_end ?? null,
|
|
634
|
+
})),
|
|
635
|
+
...fields,
|
|
636
|
+
hint,
|
|
637
|
+
stats: { strategy, countStrategy, countTotal, countVisible, countMs, busyTimeoutMs, attempts: attemptStats },
|
|
638
|
+
};
|
|
639
|
+
} catch (error) {
|
|
640
|
+
return { ok: false, code: error?.code ?? 'E_EVENTS_READ', message: String(error?.message ?? error), rows: [] };
|
|
641
|
+
} finally {
|
|
642
|
+
try { db?.close(); } catch { /* best effort */ }
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
// ===== v3 附录 A.1–A.4(逐字转写;仅把 countMainBackups 导出给红队断言用) =====
|
|
647
|
+
const MIGRATION_PHASE = Object.freeze({
|
|
648
|
+
BEGIN: 'begin', RESCAN: 'rescan', BACKUP: 'backup',
|
|
649
|
+
SCHEMA: 'schema', ALTER: 'alter', BACKFILL: 'backfill', META: 'meta', COMMIT: 'commit',
|
|
650
|
+
});
|
|
651
|
+
|
|
652
|
+
function safeClose(db) {
|
|
653
|
+
try { db.close(); } catch { /* already closed */ }
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
/** M4:只数"主备份",-wal/-shm 是同一组的一部分,不算独立份数。 */
|
|
657
|
+
export function countMainBackups(dbPath) {
|
|
658
|
+
const dir = path.dirname(dbPath);
|
|
659
|
+
const prefix = `${path.basename(dbPath)}.bak-`;
|
|
660
|
+
let count = 0;
|
|
661
|
+
try {
|
|
662
|
+
for (const name of fs.readdirSync(dir)) {
|
|
663
|
+
if (!name.startsWith(prefix)) continue;
|
|
664
|
+
if (name.endsWith('-wal') || name.endsWith('-shm')) continue;
|
|
665
|
+
let info = null;
|
|
666
|
+
try { info = fs.statSync(path.join(dir, name)); } catch { info = null; } // EPERM/ENOENT -> 不算
|
|
667
|
+
if (info !== null && info.isFile()) count += 1; // ★ M3
|
|
668
|
+
}
|
|
669
|
+
} catch { /* unreadable dir -> 0 */ }
|
|
670
|
+
return count;
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/**
|
|
674
|
+
* MINOR-9(round1):同一毫秒的两次迁移不得互相覆盖备份——主备份名已存在(普通文件)
|
|
675
|
+
* 时加序号;目录占位是故障(A5-①),不绕开,交给 copyFileSync 抛 EISDIR。
|
|
676
|
+
*/
|
|
677
|
+
function backupPathFor(dbPath, now) {
|
|
678
|
+
const base = `${dbPath}.bak-${nowIso(now).replace(/[:.]/g, '-')}`;
|
|
679
|
+
let candidate = base;
|
|
680
|
+
for (let index = 1; index <= 99; index += 1) {
|
|
681
|
+
let info = null;
|
|
682
|
+
try { info = fs.lstatSync(candidate); } catch { info = null; }
|
|
683
|
+
if (info === null) return candidate; // 名字空闲
|
|
684
|
+
if (info.isDirectory()) return candidate; // 目录占位:保持"备份失败"语义(A5-①)
|
|
685
|
+
candidate = `${base}-${index}`; // 同毫秒已有一份主备份
|
|
686
|
+
}
|
|
687
|
+
return `${base}-${Date.now()}`;
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
/** M2:调用方必须已持写锁(BEGIN IMMEDIATE);-shm 不备份。失败时清掉已写文件。 */
|
|
691
|
+
function createIndexBackup(dbPath, now, migrationDiag) {
|
|
692
|
+
const backupPath = backupPathFor(dbPath, now);
|
|
693
|
+
const written = [backupPath]; // ★ MINOR-3:先登记再拷贝,partial 也能被清
|
|
694
|
+
try {
|
|
695
|
+
fs.copyFileSync(dbPath, backupPath); // 持锁 ⇒ 一致快照
|
|
696
|
+
const wal = `${dbPath}-wal`;
|
|
697
|
+
if (fs.existsSync(wal) && fs.statSync(wal).size > 0) {
|
|
698
|
+
written.push(`${backupPath}-wal`);
|
|
699
|
+
fs.copyFileSync(wal, `${backupPath}-wal`);
|
|
700
|
+
}
|
|
701
|
+
migrationDiag({ event: 'backup-created', dbPath, backupPath, bytes: fs.statSync(backupPath).size });
|
|
702
|
+
return { path: backupPath, files: written.slice() };
|
|
703
|
+
} catch (error) {
|
|
704
|
+
// 目录占位时 rmSync 会抛 EISDIR 并被吞掉 ⇒ 目录保留(A5-① 的"目录仍存在"断言)。
|
|
705
|
+
for (const file of written) { try { fs.rmSync(file, { force: true }); } catch { /* ignore */ } }
|
|
706
|
+
migrationDiag({ event: 'backup-failed', dbPath, backupPath, code: error?.code ?? null });
|
|
707
|
+
throw error;
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
/**
|
|
712
|
+
* MINOR-8(round4):restore 会覆盖主库 + -wal 并删除 -shm。若其它进程/句柄仍持有该库,
|
|
713
|
+
* 它们看到的是旧 inode / 旧 WAL —— restore 之后这些读者必须重新 open(宿主场景:重启或
|
|
714
|
+
* 下一次工具调用)。本轮只在同进程 live 句柄上验证(A5b),跨进程语义未测(设计 §16-13)。
|
|
715
|
+
*/
|
|
716
|
+
function restoreIndexBackup(db, backup, dbPath) {
|
|
717
|
+
safeClose(db);
|
|
718
|
+
fs.copyFileSync(backup.path, dbPath);
|
|
719
|
+
const backupWal = `${backup.path}-wal`;
|
|
720
|
+
if (fs.existsSync(backupWal)) fs.copyFileSync(backupWal, `${dbPath}-wal`);
|
|
721
|
+
else { try { fs.rmSync(`${dbPath}-wal`, { force: true }); } catch { /* ignore */ } }
|
|
722
|
+
// -shm 是瞬态索引:删掉,SQLite 下次 open 自动重建(A9 验证)
|
|
723
|
+
try { fs.rmSync(`${dbPath}-shm`, { force: true }); } catch { /* ignore */ }
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
function removeIndexBackup(backup) {
|
|
727
|
+
for (const file of backup.files) { try { fs.rmSync(file, { force: true }); } catch { /* ignore */ } }
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
function setMetaRaw(target, key, value) {
|
|
731
|
+
target
|
|
732
|
+
.prepare("INSERT INTO meta(k, v) VALUES(?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v")
|
|
733
|
+
.run(key, String(value));
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
function backfillTierColumn(db, now, warmDays = DEFAULT_TIERING.warmDays) {
|
|
737
|
+
const cutoff = now().getTime() - warmDays * 86400000;
|
|
738
|
+
db.prepare(`
|
|
739
|
+
UPDATE events SET tier = CASE
|
|
740
|
+
WHEN session_id IN (
|
|
741
|
+
SELECT session_id FROM events GROUP BY session_id HAVING MAX(time_end) >= ?
|
|
742
|
+
) THEN 'warm'
|
|
743
|
+
ELSE 'cold'
|
|
744
|
+
END
|
|
745
|
+
WHERE tier IS NULL
|
|
746
|
+
`).run(cutoff);
|
|
747
|
+
const left = db.prepare('SELECT COUNT(*) AS n FROM events WHERE tier IS NULL').get().n;
|
|
748
|
+
if (left !== 0) {
|
|
749
|
+
throw new IndexError('E_TIER_LABEL_INVALID', `tier backfill left ${left} rows NULL`, { left });
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
function migrateEventIndex(db, ctx) {
|
|
754
|
+
const { dbPath, now, migrationDiag, setMetaRaw: setMetaImpl, backfillTierColumn: backfill } = ctx;
|
|
755
|
+
|
|
756
|
+
// ★★ H2:以下状态全部声明在 try 之前;catch 只读不声明 ★★
|
|
757
|
+
let began = false;
|
|
758
|
+
let phase = MIGRATION_PHASE.BEGIN;
|
|
759
|
+
let preVersion = null;
|
|
760
|
+
let backup = null;
|
|
761
|
+
let restored = false;
|
|
762
|
+
|
|
763
|
+
try {
|
|
764
|
+
// ① M2(v4):这里不再 checkpoint——写锁下 主库 + 非空 -wal 就是一致快照,
|
|
765
|
+
// 且迁移写入只进 WAL(事务 ROLLBACK ⇒ 主库字节不动)⇒ 可逐字节还原。
|
|
766
|
+
// ② 先拿锁,再备份(M2):持写锁 ⇒ 备份期间无并发提交
|
|
767
|
+
db.exec('BEGIN IMMEDIATE');
|
|
768
|
+
began = true;
|
|
769
|
+
phase = MIGRATION_PHASE.RESCAN;
|
|
770
|
+
|
|
771
|
+
// ③ 事务内重探测(挡"两个进程各持旧探测结果")
|
|
772
|
+
const liveCols = db.prepare('PRAGMA table_info(events)').all();
|
|
773
|
+
const liveHasTier = liveCols.length === 0 ? true : liveCols.some((c) => c.name === 'tier');
|
|
774
|
+
const liveHasTP = liveCols.length === 0 ? true : liveCols.some((c) => c.name === 'topic_phrases_json');
|
|
775
|
+
preVersion = Number(db.prepare('PRAGMA user_version').get()?.user_version ?? 0);
|
|
776
|
+
|
|
777
|
+
// ④ 备份
|
|
778
|
+
phase = MIGRATION_PHASE.BACKUP;
|
|
779
|
+
backup = createIndexBackup(dbPath, now, migrationDiag);
|
|
780
|
+
|
|
781
|
+
// ⑤ DDL(顺序钉死)
|
|
782
|
+
phase = MIGRATION_PHASE.SCHEMA;
|
|
783
|
+
db.exec(SCHEMA);
|
|
784
|
+
phase = MIGRATION_PHASE.ALTER;
|
|
785
|
+
if (!liveHasTP) db.exec('ALTER TABLE events ADD COLUMN topic_phrases_json TEXT');
|
|
786
|
+
if (!liveHasTier) db.exec('ALTER TABLE events ADD COLUMN tier TEXT');
|
|
787
|
+
db.exec('CREATE INDEX IF NOT EXISTS idx_events_tier ON events(tier)');
|
|
788
|
+
|
|
789
|
+
phase = MIGRATION_PHASE.BACKFILL;
|
|
790
|
+
if (!liveHasTier) backfill(db, now);
|
|
791
|
+
|
|
792
|
+
phase = MIGRATION_PHASE.META;
|
|
793
|
+
db.exec(`PRAGMA user_version = ${INDEX_SCHEMA_VERSION}`);
|
|
794
|
+
setMetaImpl(db, 'schema', `${EVENT_SCHEMA}/${INDEX_SCHEMA_VERSION}`);
|
|
795
|
+
setMetaImpl(db, 'schema_version', String(INDEX_SCHEMA_VERSION));
|
|
796
|
+
setMetaImpl(db, 'tier_schema', TIER_SCHEMA);
|
|
797
|
+
setMetaImpl(db, 'tier_pass_at', nowIso(now));
|
|
798
|
+
setMetaImpl(db, 'tier_labels_source', 'backfill'); // MINOR-3/4:回填标签不被 filter 信任
|
|
799
|
+
// 观察①(round1 判词 §6):applied_migrations 只写不读——迁移判据是 user_version +
|
|
800
|
+
// 事务内列重探 + meta.schema(单源实现,设计未要求读取;见 NOTES 观察①)。
|
|
801
|
+
setMetaImpl(db, 'applied_migrations', JSON.stringify([TIER_SCHEMA]));
|
|
802
|
+
setMetaImpl(db, 'last_migration_backup', backup.path);
|
|
803
|
+
setMetaImpl(db, 'last_migration_at', nowIso(now));
|
|
804
|
+
|
|
805
|
+
phase = MIGRATION_PHASE.COMMIT;
|
|
806
|
+
db.exec('COMMIT');
|
|
807
|
+
began = false;
|
|
808
|
+
migrationDiag({ event: 'migration-applied', dbPath, backupPath: backup.path, version: INDEX_SCHEMA_VERSION });
|
|
809
|
+
return { backupPath: backup.path, restored: false };
|
|
810
|
+
} catch (error) {
|
|
811
|
+
// ⑥ 回滚:只在自己 BEGIN 之后
|
|
812
|
+
if (began) { try { db.exec('ROLLBACK'); } catch { /* already rolled back */ } }
|
|
813
|
+
began = false;
|
|
814
|
+
|
|
815
|
+
// ⑦ restore 判定:只读 try 外声明的变量(H2 的错误在此被永久消除)
|
|
816
|
+
let liveVersion = NaN;
|
|
817
|
+
try { liveVersion = Number(db.prepare('PRAGMA user_version').get()?.user_version ?? NaN); } catch { /* ignore */ }
|
|
818
|
+
const versionNotAdvanced = !Number.isFinite(liveVersion)
|
|
819
|
+
|| preVersion === null || liveVersion <= preVersion;
|
|
820
|
+
if (backup !== null && versionNotAdvanced) {
|
|
821
|
+
try { restoreIndexBackup(db, backup, dbPath); restored = true; } catch (restoreError) {
|
|
822
|
+
migrationDiag({ event: 'restore-failed', dbPath, code: restoreError?.code ?? null });
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
// ⑧ M3:restore 成功 ⇒ 备份与 live 等价,立即删(失败重试不增长);否则保留并标注
|
|
826
|
+
if (restored) removeIndexBackup(backup);
|
|
827
|
+
safeClose(db);
|
|
828
|
+
|
|
829
|
+
// ⑨ 错误码只在事务外封装一次(H2 核心)
|
|
830
|
+
const code = phase === MIGRATION_PHASE.BEGIN ? 'E_INDEX_MIGRATION_BUSY'
|
|
831
|
+
: phase === MIGRATION_PHASE.BACKUP ? 'E_INDEX_MIGRATION_BACKUP'
|
|
832
|
+
: 'E_INDEX_MIGRATION';
|
|
833
|
+
// MINOR-10(round1):补回 1.8.3 的 migration-failed 可审计行(只含阶段/错误码,不含正文)。
|
|
834
|
+
migrationDiag({
|
|
835
|
+
event: 'migration-failed', dbPath, phase, code,
|
|
836
|
+
restored, backupRetained: backup !== null && !restored,
|
|
837
|
+
cause: error?.code ?? String(error),
|
|
838
|
+
});
|
|
839
|
+
throw new IndexError(code, `event index migration failed at ${phase}: ${error?.message ?? error}`, {
|
|
840
|
+
dbPath,
|
|
841
|
+
phase,
|
|
842
|
+
preVersion,
|
|
843
|
+
liveVersion: Number.isFinite(liveVersion) ? liveVersion : null,
|
|
844
|
+
backupPath: backup?.path ?? null,
|
|
845
|
+
backupFiles: backup?.files ?? null,
|
|
846
|
+
restored,
|
|
847
|
+
backupRetained: backup !== null && !restored,
|
|
848
|
+
retryable: phase === MIGRATION_PHASE.BEGIN,
|
|
849
|
+
cause: error?.code ?? String(error),
|
|
850
|
+
});
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
/**
|
|
855
|
+
* MAJOR-1(round1 判词):非迁移 open 不得在"已是最新的库"上拿写锁。
|
|
856
|
+
* - 全新库(无 events 表):SCHEMA + tier 索引 + 版本/meta 必须写(不存在可跳过的"最新"态);
|
|
857
|
+
* - 已有 events 表:只补探测到的真实缺项,且补建一律 busy_timeout=0 —— 长写锁
|
|
858
|
+
* (A12:20 s)下补建立即 BUSY 并跳过(记诊断 schema-repair-skipped),open 本身
|
|
859
|
+
* 不等待、不失败;全一致时这里一条写语句都不发(真·只读打开)。
|
|
860
|
+
* - 只有"非 BUSY"的补建失败才抛 E_INDEX_OPEN/E_INDEX_OPEN_BUSY(1.8.3 失败面不放大)。
|
|
861
|
+
*/
|
|
862
|
+
function ensureCurrentSchema(db, { dbPath, migrationDiag, setMetaRaw: setMetaImpl, probe = {} }) {
|
|
863
|
+
const hasEventsTable = probe.hasEventsTable === true;
|
|
864
|
+
const header = `${EVENT_SCHEMA}/${INDEX_SCHEMA_VERSION}`;
|
|
865
|
+
const repairs = [];
|
|
866
|
+
if (!hasEventsTable) {
|
|
867
|
+
repairs.push({ what: 'schema', run: () => {
|
|
868
|
+
db.exec(SCHEMA);
|
|
869
|
+
db.exec('CREATE INDEX IF NOT EXISTS idx_events_tier ON events(tier)');
|
|
870
|
+
} });
|
|
871
|
+
} else if (probe.hasTierIndex !== true) {
|
|
872
|
+
repairs.push({ what: 'tier-index', run: () => db.exec('CREATE INDEX IF NOT EXISTS idx_events_tier ON events(tier)') });
|
|
873
|
+
}
|
|
874
|
+
if (probe.userVersion !== INDEX_SCHEMA_VERSION) {
|
|
875
|
+
repairs.push({ what: 'user-version', run: () => db.exec(`PRAGMA user_version = ${INDEX_SCHEMA_VERSION}`) });
|
|
876
|
+
}
|
|
877
|
+
if (probe.metaSchema !== header) {
|
|
878
|
+
repairs.push({ what: 'meta-schema', run: () => {
|
|
879
|
+
setMetaImpl(db, 'schema', header);
|
|
880
|
+
setMetaImpl(db, 'schema_version', String(INDEX_SCHEMA_VERSION));
|
|
881
|
+
setMetaImpl(db, 'tier_schema', TIER_SCHEMA);
|
|
882
|
+
} });
|
|
883
|
+
}
|
|
884
|
+
if (repairs.length === 0) return; // ★ 已是最新:零写语句、零写锁(A12)
|
|
885
|
+
const waitForWriter = !hasEventsTable; // 建新库可以等锁;修复已有库绝不等待
|
|
886
|
+
try {
|
|
887
|
+
if (!waitForWriter) db.exec('PRAGMA busy_timeout = 0');
|
|
888
|
+
for (const repair of repairs) {
|
|
889
|
+
try {
|
|
890
|
+
repair.run();
|
|
891
|
+
} catch (error) {
|
|
892
|
+
if (!waitForWriter && isBusyError(error)) {
|
|
893
|
+
migrationDiag({ event: 'schema-repair-skipped', dbPath, what: repair.what, cause: error?.errcode ?? error?.code ?? null });
|
|
894
|
+
continue; // 长写锁:跳过补建,open 照常成功
|
|
895
|
+
}
|
|
896
|
+
throw error;
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
} catch (error) {
|
|
900
|
+
safeClose(db);
|
|
901
|
+
const busy = isBusyError(error);
|
|
902
|
+
throw new IndexError(busy ? 'E_INDEX_OPEN_BUSY' : 'E_INDEX_OPEN', `event index open (schema) failed: ${error?.message ?? error}`, {
|
|
903
|
+
dbPath, cause: error?.code ?? String(error),
|
|
904
|
+
retryable: busy,
|
|
905
|
+
phase: 'ensure-schema',
|
|
906
|
+
});
|
|
907
|
+
} finally {
|
|
908
|
+
try { db.exec('PRAGMA busy_timeout = 5000'); } catch { /* db already closed on the error path */ }
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
/** v4 §6.5-2:三值判别式——"查不到"(ok:true)与"读失败"(ok:false)绝不混。 */
|
|
913
|
+
export function readTierState(db, { nowMs = Date.now(), tiering = DEFAULT_TIERING } = {}) {
|
|
914
|
+
let hasTierColumn = false;
|
|
915
|
+
try {
|
|
916
|
+
hasTierColumn = db.prepare('PRAGMA table_info(events)').all().some((c) => c.name === 'tier');
|
|
917
|
+
} catch (error) {
|
|
918
|
+
const busy = isBusyError(error);
|
|
919
|
+
return {
|
|
920
|
+
ok: false,
|
|
921
|
+
code: busy ? 'E_INDEX_QUERY_BUSY' : 'E_INDEX_QUERY_FAILED',
|
|
922
|
+
retryable: busy,
|
|
923
|
+
detail: { where: 'table_info', errcode: error?.errcode ?? null, errstr: error?.errstr ?? String(error?.message ?? error) },
|
|
924
|
+
};
|
|
925
|
+
}
|
|
926
|
+
try {
|
|
927
|
+
const get = (key) => db.prepare('SELECT v FROM meta WHERE k = ?').get(key)?.v ?? null;
|
|
928
|
+
const passAtRaw = get('tier_pass_at');
|
|
929
|
+
const parsed = passAtRaw === null ? NaN : Date.parse(passAtRaw);
|
|
930
|
+
return {
|
|
931
|
+
ok: true,
|
|
932
|
+
hasTierColumn,
|
|
933
|
+
passAtMs: Number.isFinite(parsed) ? parsed : null,
|
|
934
|
+
passAtRaw,
|
|
935
|
+
labelsSource: get('tier_labels_source'),
|
|
936
|
+
tierSchema: get('tier_schema'),
|
|
937
|
+
nowMs,
|
|
938
|
+
tiering,
|
|
939
|
+
};
|
|
940
|
+
} catch (error) {
|
|
941
|
+
const busy = isBusyError(error);
|
|
942
|
+
return {
|
|
943
|
+
ok: false,
|
|
944
|
+
code: busy ? 'E_INDEX_QUERY_BUSY' : 'E_INDEX_QUERY_FAILED',
|
|
945
|
+
retryable: busy,
|
|
946
|
+
detail: { where: 'meta', errcode: error?.errcode ?? null, errstr: error?.errstr ?? String(error?.message ?? error) },
|
|
947
|
+
};
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
// ── 模块级内核:db / setMeta 全是形参(照抄到模块作用域也不会 ReferenceError)──
|
|
952
|
+
export function applyTierLabelsInner(db, setMeta, { labels, counts, nowMs, passAt }) {
|
|
953
|
+
// MAJOR-3(round1):BEGIN 也必须在 try 内——写锁下 BEGIN 的 BUSY 要映射成
|
|
954
|
+
// E_TIER_BUSY(retryable),不能把裸 ERR_SQLITE_ERROR/errcode=5 漏给调用方。
|
|
955
|
+
let began = false;
|
|
956
|
+
try {
|
|
957
|
+
db.exec('BEGIN IMMEDIATE');
|
|
958
|
+
began = true;
|
|
959
|
+
db.exec('CREATE TEMP TABLE IF NOT EXISTS tier_stage (id TEXT PRIMARY KEY, tier TEXT)');
|
|
960
|
+
db.exec('DELETE FROM tier_stage');
|
|
961
|
+
const ins = db.prepare('INSERT INTO tier_stage(id, tier) VALUES(?, ?)');
|
|
962
|
+
for (const [id, tier] of labels) ins.run(id, tier); // MINOR-2:单事务单循环
|
|
963
|
+
db.exec(`UPDATE events SET tier = (SELECT tier FROM tier_stage WHERE tier_stage.id = events.id)
|
|
964
|
+
WHERE id IN (SELECT id FROM tier_stage)`);
|
|
965
|
+
setMeta('tier_pass_at', new Date(passAt).toISOString());
|
|
966
|
+
setMeta('tier_labels_source', 'pass');
|
|
967
|
+
setMeta('tier_schema', TIER_SCHEMA);
|
|
968
|
+
setMeta('tier_counts', JSON.stringify(counts));
|
|
969
|
+
setMeta('tier_pass_ms', String(Math.max(0, nowMs - passAt)));
|
|
970
|
+
db.exec('COMMIT');
|
|
971
|
+
began = false;
|
|
972
|
+
} catch (error) {
|
|
973
|
+
if (began) { try { db.exec('ROLLBACK'); } catch { /* already rolled back */ } }
|
|
974
|
+
const busy = isBusyError(error);
|
|
975
|
+
throw new IndexError(busy ? 'E_TIER_BUSY' : 'E_TIER_WRITE',
|
|
976
|
+
`tier labels write failed: ${error?.message ?? error}`, {
|
|
977
|
+
cause: error?.code ?? String(error), retryable: busy,
|
|
978
|
+
});
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
export function openEventIndex(options = {}) {
|
|
983
|
+
const memoryRoot = path.resolve(String(options.memoryRoot ?? ''));
|
|
984
|
+
if (memoryRoot === '') throw new IndexError('E_MEMORY_ROOT', 'memoryRoot required');
|
|
985
|
+
const now = typeof options.now === 'function' ? options.now : () => new Date();
|
|
986
|
+
const paths = indexPaths(memoryRoot);
|
|
987
|
+
fs.mkdirSync(paths.dir, { recursive: true });
|
|
988
|
+
fs.mkdirSync(paths.framesDir, { recursive: true });
|
|
989
|
+
const dbPath = options.dbPath ? path.resolve(options.dbPath) : paths.db;
|
|
990
|
+
const dbExisted = fs.existsSync(dbPath);
|
|
991
|
+
const { DatabaseSync } = sqlite();
|
|
992
|
+
const migrationDiag = (row) => {
|
|
993
|
+
try {
|
|
994
|
+
const dir = path.join(memoryRoot, '.longlive', 'diagnostics');
|
|
995
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
996
|
+
fs.appendFileSync(path.join(dir, 'event-index-migration.jsonl'),
|
|
997
|
+
`${JSON.stringify({ schema: 'event-index-migration/v1', at: nowIso(now), ...row })}\n`, 'utf8');
|
|
998
|
+
} catch { /* diagnostics must never mask the real error */ }
|
|
999
|
+
};
|
|
1000
|
+
let db;
|
|
1001
|
+
try {
|
|
1002
|
+
db = new DatabaseSync(dbPath);
|
|
1003
|
+
db.exec('PRAGMA journal_mode = WAL');
|
|
1004
|
+
db.exec('PRAGMA busy_timeout = 5000');
|
|
1005
|
+
} catch (error) {
|
|
1006
|
+
migrationDiag({ event: 'open-failed', dbPath, code: error?.code ?? null, message: String(error?.message ?? error) });
|
|
1007
|
+
throw new IndexError('E_INDEX_UNAVAILABLE', `event index open failed: ${error?.message ?? error}`, {
|
|
1008
|
+
dbPath, cause: error?.code ?? String(error),
|
|
1009
|
+
});
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
let needsMigration = false;
|
|
1013
|
+
// MAJOR-1(round1):迁移判定与 open 分离——下方探测全只读;探测结果同时决定
|
|
1014
|
+
// "非迁移 open 还需不需要写"(已最新的库不得再拿写锁)。
|
|
1015
|
+
// A brand-new/empty DB will get the current SCHEMA (which already has the
|
|
1016
|
+
// column), so only an existing events table can be genuinely missing it.
|
|
1017
|
+
const schemaProbe = {
|
|
1018
|
+
hasEventsTable: false,
|
|
1019
|
+
hasTopicPhrases: true,
|
|
1020
|
+
hasTier: true, // v3 A.3: same default-true guard as hasTopicPhrases
|
|
1021
|
+
hasTierIndex: false,
|
|
1022
|
+
userVersion: 0,
|
|
1023
|
+
metaSchema: null,
|
|
1024
|
+
};
|
|
1025
|
+
try {
|
|
1026
|
+
const eventsTable = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='events'").get();
|
|
1027
|
+
if (eventsTable) {
|
|
1028
|
+
schemaProbe.hasEventsTable = true;
|
|
1029
|
+
const columns = db.prepare('PRAGMA table_info(events)').all();
|
|
1030
|
+
schemaProbe.hasTopicPhrases = columns.some((column) => column.name === 'topic_phrases_json');
|
|
1031
|
+
schemaProbe.hasTier = columns.some((column) => column.name === 'tier');
|
|
1032
|
+
schemaProbe.userVersion = Number(db.prepare('PRAGMA user_version').get()?.user_version ?? 0);
|
|
1033
|
+
const hasMeta = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='meta'").get();
|
|
1034
|
+
schemaProbe.metaSchema = hasMeta ? (db.prepare("SELECT v FROM meta WHERE k = 'schema'").get()?.v ?? null) : null;
|
|
1035
|
+
schemaProbe.hasTierIndex = Boolean(db.prepare("SELECT name FROM sqlite_master WHERE type='index' AND name='idx_events_tier'").get());
|
|
1036
|
+
needsMigration = dbExisted && (!schemaProbe.hasTopicPhrases || !schemaProbe.hasTier || schemaProbe.userVersion < INDEX_SCHEMA_VERSION
|
|
1037
|
+
|| schemaProbe.metaSchema === `${EVENT_SCHEMA}/1` || schemaProbe.metaSchema === null);
|
|
1038
|
+
}
|
|
1039
|
+
} catch (error) {
|
|
1040
|
+
db.close();
|
|
1041
|
+
migrationDiag({ event: 'inspect-failed', dbPath, code: error?.code ?? null, message: String(error?.message ?? error) });
|
|
1042
|
+
throw new IndexError('E_INDEX_UNAVAILABLE', `event index schema inspection failed: ${error?.message ?? error}`, {
|
|
1043
|
+
dbPath, cause: error?.code ?? String(error),
|
|
1044
|
+
});
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
if (needsMigration) {
|
|
1048
|
+
// 观察②(round1 判词 §6):返回值不再挂死变量——迁移结果只用于诊断,handle 不暴露。
|
|
1049
|
+
migrateEventIndex(db, { dbPath, now, migrationDiag, setMetaRaw, backfillTierColumn });
|
|
1050
|
+
} else {
|
|
1051
|
+
ensureCurrentSchema(db, { dbPath, migrationDiag, setMetaRaw, probe: schemaProbe });
|
|
1052
|
+
}
|
|
1053
|
+
let closed = false;
|
|
1054
|
+
|
|
1055
|
+
function getMeta(key) {
|
|
1056
|
+
const row = db.prepare('SELECT v FROM meta WHERE k = ?').get(key);
|
|
1057
|
+
return row ? row.v : null;
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
function setMeta(key, value) {
|
|
1061
|
+
db.prepare('INSERT INTO meta(k, v) VALUES(?, ?) ON CONFLICT(k) DO UPDATE SET v = excluded.v')
|
|
1062
|
+
.run(key, String(value));
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
/** v4 M1:handle 方法(闭包内 db/setMeta),落点即 :662 的返回对象字面量。
|
|
1066
|
+
* M-A1(round4):写成箭头属性而不是具名函数,静态 grep 只会命中带 db 形参的内核。 */
|
|
1067
|
+
const applyTierLabels = (args) => applyTierLabelsInner(db, setMeta, args);
|
|
1068
|
+
|
|
1069
|
+
function appendAudit(record, action) {
|
|
1070
|
+
const line = {
|
|
1071
|
+
schema: 'events-audit/v1',
|
|
1072
|
+
id: record.id,
|
|
1073
|
+
sessionId: record.sessionId,
|
|
1074
|
+
turn: record.turn,
|
|
1075
|
+
digest: record.digest,
|
|
1076
|
+
kind: record.kind ?? null,
|
|
1077
|
+
anchors: record.anchors ?? [],
|
|
1078
|
+
builtAt: record.builtAt ?? Date.parse(nowIso(now)),
|
|
1079
|
+
source: record.source ?? 'rebuild',
|
|
1080
|
+
action,
|
|
1081
|
+
};
|
|
1082
|
+
// S1: append 失败不再静默 — append-store 统一加锁/fsync/坏行隔离,并记
|
|
1083
|
+
// logger.warn + 计数(write-health)。本审计层仍是派生数据:失败不阻断 upsert。
|
|
1084
|
+
return appendJsonLine({
|
|
1085
|
+
file: paths.audit,
|
|
1086
|
+
row: line,
|
|
1087
|
+
label: 'events.audit',
|
|
1088
|
+
healthRoot: paths.root,
|
|
1089
|
+
now,
|
|
1090
|
+
quarantineDir: path.join(paths.root, '.longlive', 'quarantine'),
|
|
1091
|
+
});
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
function upsertEvent(record, options2 = {}) {
|
|
1095
|
+
validateRecord(record);
|
|
1096
|
+
const existing = db.prepare('SELECT digest FROM events WHERE id = ?').get(record.id);
|
|
1097
|
+
if (existing && existing.digest === record.digest) {
|
|
1098
|
+
return { inserted: false, duplicated: true, id: record.id };
|
|
1099
|
+
}
|
|
1100
|
+
if (existing && existing.digest !== record.digest) {
|
|
1101
|
+
// Same id, different content: never overwrite silently. The conflict is
|
|
1102
|
+
// audited and the caller must treat it as a rejected write.
|
|
1103
|
+
appendAudit({ ...record, source: record.source ?? options2.source ?? 'upsert', anchors: record.anchors ?? [] }, 'id-digest-conflict');
|
|
1104
|
+
return { inserted: false, conflict: true, code: 'E_ID_DIGEST_CONFLICT', id: record.id };
|
|
1105
|
+
}
|
|
1106
|
+
const builtAt = Number.isInteger(record.builtAt) ? record.builtAt : Date.parse(nowIso(now));
|
|
1107
|
+
const source = record.source ?? options2.source ?? 'rebuild';
|
|
1108
|
+
const rawText = rawTextFor(record);
|
|
1109
|
+
const termText = termTextOf([record.summary, ...(record.topics ?? []), ...(record.terms ?? []), ...(record.topicPhrases ?? [])].join('\n')).slice(0, 12000);
|
|
1110
|
+
const aliases = [...new Set([...(aliasesOf(record.summary ?? '')), ...(record.aliases ?? [])])].join(' ').slice(0, 4000);
|
|
1111
|
+
const anchors = record.anchors ?? [];
|
|
1112
|
+
try {
|
|
1113
|
+
db.exec('BEGIN IMMEDIATE');
|
|
1114
|
+
db.prepare(`
|
|
1115
|
+
INSERT INTO events
|
|
1116
|
+
(id, session_id, turn, seq_start, seq_end, time_start, time_end, project, kind,
|
|
1117
|
+
summary, topics_json, terms_json, topic_phrases_json, counts_json, anchors_json, digest, built_at, source)
|
|
1118
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
1119
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
1120
|
+
session_id = excluded.session_id, turn = excluded.turn,
|
|
1121
|
+
seq_start = excluded.seq_start, seq_end = excluded.seq_end,
|
|
1122
|
+
time_start = excluded.time_start, time_end = excluded.time_end,
|
|
1123
|
+
project = excluded.project, kind = excluded.kind, summary = excluded.summary,
|
|
1124
|
+
topics_json = excluded.topics_json, terms_json = excluded.terms_json,
|
|
1125
|
+
topic_phrases_json = excluded.topic_phrases_json,
|
|
1126
|
+
counts_json = excluded.counts_json, anchors_json = excluded.anchors_json,
|
|
1127
|
+
digest = excluded.digest, built_at = excluded.built_at, source = excluded.source
|
|
1128
|
+
`).run(
|
|
1129
|
+
record.id, record.sessionId, record.turn,
|
|
1130
|
+
record.seqStart ?? null, record.seqEnd ?? null,
|
|
1131
|
+
record.timeStart ?? null, record.timeEnd ?? null,
|
|
1132
|
+
record.project ?? null, record.kind ?? null,
|
|
1133
|
+
record.summary ?? null,
|
|
1134
|
+
JSON.stringify(record.topics ?? []),
|
|
1135
|
+
JSON.stringify(record.terms ?? []),
|
|
1136
|
+
JSON.stringify(record.topicPhrases ?? []),
|
|
1137
|
+
JSON.stringify(record.counts ?? {}),
|
|
1138
|
+
JSON.stringify(anchors),
|
|
1139
|
+
record.digest, builtAt, source,
|
|
1140
|
+
);
|
|
1141
|
+
db.prepare('DELETE FROM events_fts WHERE id = ?').run(record.id);
|
|
1142
|
+
db.prepare('DELETE FROM events_terms WHERE id = ?').run(record.id);
|
|
1143
|
+
db.prepare('INSERT INTO events_fts(id, raw_text) VALUES(?, ?)').run(record.id, rawText);
|
|
1144
|
+
db.prepare('INSERT INTO events_terms(id, term_text, aliases) VALUES(?, ?, ?)').run(record.id, termText, aliases);
|
|
1145
|
+
db.exec('COMMIT');
|
|
1146
|
+
} catch (error) {
|
|
1147
|
+
try { db.exec('ROLLBACK'); } catch { /* BEGIN itself may have failed (BUSY) */ }
|
|
1148
|
+
throw new IndexError('E_INDEX_WRITE', `event index write failed: ${error.message}`, { id: record.id });
|
|
1149
|
+
}
|
|
1150
|
+
appendAudit({ ...record, builtAt, source, anchors }, existing ? 'update' : 'insert');
|
|
1151
|
+
setMeta('last_write_at', nowIso(now));
|
|
1152
|
+
setMeta('schema', `${EVENT_SCHEMA}/${INDEX_SCHEMA_VERSION}`);
|
|
1153
|
+
return { inserted: true, id: record.id };
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
function runCandidates(table, candidates, limit, kind) {
|
|
1157
|
+
for (const candidate of candidates) {
|
|
1158
|
+
let rows;
|
|
1159
|
+
try {
|
|
1160
|
+
const sql = kind
|
|
1161
|
+
? `SELECT e.*, bm25(${table}) AS rank FROM ${table} JOIN events e ON e.id = ${table}.id WHERE ${table} MATCH ? AND e.kind = ? ORDER BY rank LIMIT ?`
|
|
1162
|
+
: `SELECT e.*, bm25(${table}) AS rank FROM ${table} JOIN events e ON e.id = ${table}.id WHERE ${table} MATCH ? ORDER BY rank LIMIT ?`;
|
|
1163
|
+
rows = kind
|
|
1164
|
+
? db.prepare(sql).all(candidate.match, kind, limit)
|
|
1165
|
+
: db.prepare(sql).all(candidate.match, limit);
|
|
1166
|
+
} catch {
|
|
1167
|
+
continue; // FTS syntax errors are expected for hostile input: try next candidate
|
|
1168
|
+
}
|
|
1169
|
+
if (rows.length > 0) return { rows: rows.map(parseRow), strategy: `${table}:${candidate.label}` };
|
|
1170
|
+
}
|
|
1171
|
+
return null;
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
/**
|
|
1175
|
+
* Query the index. Never throws for hostile queries: candidate chain + try/catch,
|
|
1176
|
+
*全失败返回 { ok:true, rows:[], code:'E_FTS_NO_MATCH' }。
|
|
1177
|
+
*/
|
|
1178
|
+
function search(query, opts = {}) {
|
|
1179
|
+
const limit = Number.isInteger(opts.limit) ? Math.min(Math.max(opts.limit, 1), 100) : 10;
|
|
1180
|
+
const kind = typeof opts.kind === 'string' && opts.kind !== '' ? opts.kind : undefined;
|
|
1181
|
+
const candidates = buildFtsCandidates(query);
|
|
1182
|
+
const tried = [];
|
|
1183
|
+
if (candidates.normalized === '') {
|
|
1184
|
+
return { ok: true, schema: EVENT_SCHEMA, query: '', normalized: '', rows: [], code: 'E_FTS_EMPTY_QUERY', strategy: null, tried: [] };
|
|
1185
|
+
}
|
|
1186
|
+
for (const candidate of candidates.raw) tried.push(`events_fts:${candidate.label}`);
|
|
1187
|
+
const rawHit = runCandidates('events_fts', candidates.raw, limit, kind);
|
|
1188
|
+
if (rawHit) {
|
|
1189
|
+
return { ok: true, schema: EVENT_SCHEMA, query: String(query), normalized: candidates.normalized, rows: rawHit.rows, strategy: rawHit.strategy, tried };
|
|
1190
|
+
}
|
|
1191
|
+
for (const candidate of candidates.terms) tried.push(`events_terms:${candidate.label}`);
|
|
1192
|
+
const termHit = runCandidates('events_terms', candidates.terms, limit, kind);
|
|
1193
|
+
if (termHit) {
|
|
1194
|
+
return { ok: true, schema: EVENT_SCHEMA, query: String(query), normalized: candidates.normalized, rows: termHit.rows, strategy: termHit.strategy, tried };
|
|
1195
|
+
}
|
|
1196
|
+
return { ok: true, schema: EVENT_SCHEMA, query: String(query), normalized: candidates.normalized, rows: [], code: 'E_FTS_NO_MATCH', strategy: null, tried };
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
function listEvents(opts = {}) {
|
|
1200
|
+
const limit = Number.isInteger(opts.limit) ? Math.min(Math.max(opts.limit, 1), 500) : 20;
|
|
1201
|
+
const offset = Number.isInteger(opts.offset) && opts.offset > 0 ? opts.offset : 0;
|
|
1202
|
+
const kind = typeof opts.kind === 'string' && opts.kind !== '' ? opts.kind : null;
|
|
1203
|
+
const rows = kind
|
|
1204
|
+
? db.prepare('SELECT * FROM events WHERE kind = ? ORDER BY time_end DESC, id ASC LIMIT ? OFFSET ?').all(kind, limit, offset)
|
|
1205
|
+
: db.prepare('SELECT * FROM events ORDER BY time_end DESC, id ASC LIMIT ? OFFSET ?').all(limit, offset);
|
|
1206
|
+
return rows.map(parseRow);
|
|
1207
|
+
}
|
|
1208
|
+
|
|
1209
|
+
function count(opts = {}) {
|
|
1210
|
+
const kind = typeof opts.kind === 'string' && opts.kind !== '' ? opts.kind : null;
|
|
1211
|
+
const row = kind
|
|
1212
|
+
? db.prepare('SELECT COUNT(*) AS n FROM events WHERE kind = ?').get(kind)
|
|
1213
|
+
: db.prepare('SELECT COUNT(*) AS n FROM events').get();
|
|
1214
|
+
return row.n;
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
/** Read one EventRecord by id (AutoCard source-of-truth check). */
|
|
1218
|
+
function getEvent(id) {
|
|
1219
|
+
if (typeof id !== 'string' || id === '') return null;
|
|
1220
|
+
const row = db.prepare('SELECT * FROM events WHERE id = ?').get(id);
|
|
1221
|
+
return row ? parseRow(row) : null;
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
function deleteSession(sessionId) {
|
|
1225
|
+
const rows = db.prepare('SELECT id FROM events WHERE session_id = ?').all(sessionId);
|
|
1226
|
+
db.exec('BEGIN IMMEDIATE');
|
|
1227
|
+
try {
|
|
1228
|
+
for (const row of rows) {
|
|
1229
|
+
db.prepare('DELETE FROM events_fts WHERE id = ?').run(row.id);
|
|
1230
|
+
db.prepare('DELETE FROM events_terms WHERE id = ?').run(row.id);
|
|
1231
|
+
}
|
|
1232
|
+
db.prepare('DELETE FROM events WHERE session_id = ?').run(sessionId);
|
|
1233
|
+
db.exec('COMMIT');
|
|
1234
|
+
} catch (error) {
|
|
1235
|
+
db.exec('ROLLBACK');
|
|
1236
|
+
throw new IndexError('E_INDEX_DELETE', `session delete failed: ${error.message}`, { sessionId });
|
|
1237
|
+
}
|
|
1238
|
+
return { ok: true, removed: rows.length };
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
function stats() {
|
|
1242
|
+
const sizeOf = (file) => {
|
|
1243
|
+
try {
|
|
1244
|
+
return fs.statSync(file).size;
|
|
1245
|
+
} catch {
|
|
1246
|
+
return 0;
|
|
1247
|
+
}
|
|
1248
|
+
};
|
|
1249
|
+
return {
|
|
1250
|
+
schema: EVENT_SCHEMA,
|
|
1251
|
+
schemaVersion: INDEX_SCHEMA_VERSION,
|
|
1252
|
+
dbPath,
|
|
1253
|
+
// WAL means the main db file stays small until checkpoint: report the family.
|
|
1254
|
+
dbBytes: sizeOf(dbPath) + sizeOf(`${dbPath}-wal`) + sizeOf(`${dbPath}-shm`),
|
|
1255
|
+
events: count(),
|
|
1256
|
+
ftsRows: db.prepare('SELECT COUNT(*) AS n FROM events_fts').get().n,
|
|
1257
|
+
termRows: db.prepare('SELECT COUNT(*) AS n FROM events_terms').get().n,
|
|
1258
|
+
sessions: (() => {
|
|
1259
|
+
const row = db.prepare('SELECT COUNT(DISTINCT session_id) AS n FROM events').get();
|
|
1260
|
+
return row.n;
|
|
1261
|
+
})(),
|
|
1262
|
+
kinds: Object.fromEntries(db.prepare('SELECT kind, COUNT(*) AS n FROM events GROUP BY kind').all().map((row) => [row.kind, row.n])),
|
|
1263
|
+
lastWriteAt: getMeta('last_write_at'),
|
|
1264
|
+
};
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
function close() {
|
|
1268
|
+
if (closed) return;
|
|
1269
|
+
closed = true;
|
|
1270
|
+
db.close();
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
return { memoryRoot, paths, dbPath, upsertEvent, deleteSession, search, listEvents, count, getEvent, stats, getMeta, setMeta, applyTierLabels, close };
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
/** One-line summary: user first message kept whole (240 chars) + assistant tail 160. */
|
|
1277
|
+
function summaryOf(userTexts, assistantTexts, topicPhrases = []) {
|
|
1278
|
+
// P1-2: real turns contain assistant steps whose text block is '' (reasoning +
|
|
1279
|
+
// tool-call only). Taking `[0]` / `[last]` blindly kept an empty head and made
|
|
1280
|
+
// the "→ assistant tail" part disappear even after the text extraction fix.
|
|
1281
|
+
const firstNonEmpty = (list) => (list.find((text) => typeof text === 'string' && text !== '') ?? '');
|
|
1282
|
+
const lastNonEmpty = () => {
|
|
1283
|
+
for (let index = assistantTexts.length - 1; index >= 0; index -= 1) {
|
|
1284
|
+
const text = assistantTexts[index];
|
|
1285
|
+
if (typeof text === 'string' && text !== '') return text;
|
|
1286
|
+
}
|
|
1287
|
+
return '';
|
|
1288
|
+
};
|
|
1289
|
+
const head = firstNonEmpty(userTexts) || firstNonEmpty(assistantTexts);
|
|
1290
|
+
const tail = lastNonEmpty();
|
|
1291
|
+
const parts = [
|
|
1292
|
+
String(head).replace(/\s+/g, ' ').trim().slice(0, 240),
|
|
1293
|
+
tail === '' ? '' : `→ ${String(tail).replace(/\s+/g, ' ').trim().slice(0, 160)}`,
|
|
1294
|
+
].filter((part) => part !== '');
|
|
1295
|
+
const summary = parts.join(' ').slice(0, 480);
|
|
1296
|
+
return summary;
|
|
1297
|
+
}
|
|
1298
|
+
|
|
1299
|
+
/** Deduped topicPhrases: user-marked phrases first, then turn-wide phrases. */
|
|
1300
|
+
function topicPhrasesOf(userTexts, assistantTexts) {
|
|
1301
|
+
const userPhrases = extractTopicPhrases(userTexts, { limit: 8 });
|
|
1302
|
+
const allPhrases = extractTopicPhrases([...userTexts, ...assistantTexts], { limit: 12 });
|
|
1303
|
+
const out = [];
|
|
1304
|
+
const seen = new Set();
|
|
1305
|
+
for (const phrase of [...userPhrases, ...allPhrases]) {
|
|
1306
|
+
if (seen.has(phrase)) continue;
|
|
1307
|
+
seen.add(phrase);
|
|
1308
|
+
out.push(phrase);
|
|
1309
|
+
}
|
|
1310
|
+
return out.slice(0, 12);
|
|
1311
|
+
}
|
|
1312
|
+
|
|
1313
|
+
/** Extract per-turn EventRecords from a parsed session. */
|
|
1314
|
+
export function extractTurns(header, events, frames = [], texts = []) {
|
|
1315
|
+
const sessionId = typeof header?.id === 'string' && header.id !== ''
|
|
1316
|
+
? header.id
|
|
1317
|
+
: (typeof header?.sessionId === 'string' && header.sessionId !== '' ? header.sessionId : null);
|
|
1318
|
+
if (sessionId === null) throw new IndexError('E_SESSION_ID', 'session header carries no id');
|
|
1319
|
+
const project = typeof header?.cwd === 'string' ? header.cwd : null;
|
|
1320
|
+
|
|
1321
|
+
// Map seq -> frame index (frame 0 carries the header line).
|
|
1322
|
+
const seqToFrame = new Map();
|
|
1323
|
+
let lineNo = 0;
|
|
1324
|
+
(Array.isArray(texts) ? texts : []).forEach((text, frameIndex) => {
|
|
1325
|
+
for (const line of String(text).split('\n')) {
|
|
1326
|
+
if (line === '') continue;
|
|
1327
|
+
if (lineNo === 0) {
|
|
1328
|
+
lineNo = 1;
|
|
1329
|
+
continue;
|
|
1330
|
+
}
|
|
1331
|
+
seqToFrame.set(lineNo - 1, frameIndex);
|
|
1332
|
+
lineNo += 1;
|
|
1333
|
+
}
|
|
1334
|
+
});
|
|
1335
|
+
|
|
1336
|
+
let currentTurn = 0;
|
|
1337
|
+
const groups = new Map();
|
|
1338
|
+
for (const event of events) {
|
|
1339
|
+
const turn = Number(event?.data?.turn);
|
|
1340
|
+
if (Number.isInteger(turn) && turn >= 0) currentTurn = turn;
|
|
1341
|
+
if (!groups.has(currentTurn)) groups.set(currentTurn, []);
|
|
1342
|
+
groups.get(currentTurn).push(event);
|
|
1343
|
+
}
|
|
1344
|
+
|
|
1345
|
+
const out = [];
|
|
1346
|
+
for (const [turn, list] of [...groups.entries()].sort((a, b) => a[0] - b[0])) {
|
|
1347
|
+
const seqStart = list[0].seq;
|
|
1348
|
+
const seqEnd = list[list.length - 1].seq;
|
|
1349
|
+
const times = list.map((event) => Number(event?.time)).filter((value) => Number.isFinite(value));
|
|
1350
|
+
const userTexts = [];
|
|
1351
|
+
const assistantTexts = [];
|
|
1352
|
+
let toolCalls = 0;
|
|
1353
|
+
for (const event of list) {
|
|
1354
|
+
if (event.type === 'user/message' && event?.data?.source?.kind === 'user') userTexts.push(textOf(event));
|
|
1355
|
+
else if (event.type === 'assistant/message') assistantTexts.push(textOf(event));
|
|
1356
|
+
else if (event.type === 'tool/call') toolCalls += 1;
|
|
1357
|
+
}
|
|
1358
|
+
const corpus = [...userTexts, ...assistantTexts].filter((text) => text !== '').join('\n');
|
|
1359
|
+
const counts = { userMsgs: userTexts.length, assistantMsgs: assistantTexts.length, toolCalls };
|
|
1360
|
+
const kind = classifyKind(corpus, counts);
|
|
1361
|
+
// S8: 主题短语先从用户消息抽(引号/书名号/内容块/实体后缀),再从整轮补;
|
|
1362
|
+
// 老记录没有 topicPhrases,读取端按 [] 回落。
|
|
1363
|
+
const topicPhrases = topicPhrasesOf(userTexts, assistantTexts);
|
|
1364
|
+
const summary = summaryOf(userTexts, assistantTexts, topicPhrases);
|
|
1365
|
+
const terms = extractTerms(corpus, [sessionId, ...topicPhrases]);
|
|
1366
|
+
const topics = [...new Set([...topicPhrases, ...terms.filter((term) => /[\u3400-\u4dbf\u4e00-\u9fff]/.test(term))])].slice(0, 5);
|
|
1367
|
+
const digest = turnDigest(events, seqStart, seqEnd);
|
|
1368
|
+
const anchor = makeSessionTurnAnchor({ sessionId, turn, seqStart, seqEnd, digest, status: 'live' });
|
|
1369
|
+
const frameIndexes = [...new Set(list.map((event) => seqToFrame.get(event.seq)).filter((value) => Number.isInteger(value)))];
|
|
1370
|
+
out.push({
|
|
1371
|
+
id: `evt:${sessionId}:${turn}`,
|
|
1372
|
+
sessionId,
|
|
1373
|
+
turn,
|
|
1374
|
+
seqStart,
|
|
1375
|
+
seqEnd,
|
|
1376
|
+
timeStart: times.length > 0 ? Math.min(...times) : null,
|
|
1377
|
+
timeEnd: times.length > 0 ? Math.max(...times) : null,
|
|
1378
|
+
project,
|
|
1379
|
+
kind,
|
|
1380
|
+
topics,
|
|
1381
|
+
terms,
|
|
1382
|
+
topicPhrases,
|
|
1383
|
+
summary,
|
|
1384
|
+
counts,
|
|
1385
|
+
anchors: [anchor],
|
|
1386
|
+
digest,
|
|
1387
|
+
frameIndexes,
|
|
1388
|
+
rawText: rawTextFor({ kind, summary, terms, topics, topicPhrases, project }),
|
|
1389
|
+
source: 'rebuild',
|
|
1390
|
+
});
|
|
1391
|
+
}
|
|
1392
|
+
return out;
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
/** Recursively discover DSH session logs under the given roots. */
|
|
1396
|
+
export function discoverSessionLogs(roots) {
|
|
1397
|
+
const out = [];
|
|
1398
|
+
const stack = (Array.isArray(roots) ? roots : [roots])
|
|
1399
|
+
.filter((root) => typeof root === 'string' && root !== '')
|
|
1400
|
+
.map((root) => path.resolve(root));
|
|
1401
|
+
const seen = new Set();
|
|
1402
|
+
while (stack.length > 0) {
|
|
1403
|
+
const dir = stack.pop();
|
|
1404
|
+
if (seen.has(dir)) continue;
|
|
1405
|
+
seen.add(dir);
|
|
1406
|
+
let entries = [];
|
|
1407
|
+
try {
|
|
1408
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
1409
|
+
} catch {
|
|
1410
|
+
continue;
|
|
1411
|
+
}
|
|
1412
|
+
for (const entry of entries) {
|
|
1413
|
+
const full = path.join(dir, entry.name);
|
|
1414
|
+
if (entry.isDirectory()) {
|
|
1415
|
+
stack.push(full);
|
|
1416
|
+
} else if (entry.isFile() && entry.name === 'session.v4.jsonl.zstd') {
|
|
1417
|
+
out.push({ file: full, sessionId: path.basename(dir) });
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
return out.sort((a, b) => a.file.localeCompare(b.file));
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1424
|
+
function defaultSessionRoots() {
|
|
1425
|
+
const dshHome = typeof process.env.DSH_HOME === 'string' && process.env.DSH_HOME.trim() !== ''
|
|
1426
|
+
? path.resolve(process.env.DSH_HOME.trim())
|
|
1427
|
+
: path.join(os.homedir(), '.dsh');
|
|
1428
|
+
return [path.join(dshHome, 'sessions')];
|
|
1429
|
+
}
|
|
1430
|
+
|
|
1431
|
+
/** Remove every derived index artifact (used by the delete-rebuild acceptance). */
|
|
1432
|
+
export function deleteIndex(memoryRoot) {
|
|
1433
|
+
const paths = indexPaths(memoryRoot);
|
|
1434
|
+
const removed = [];
|
|
1435
|
+
for (const file of [paths.db, `${paths.db}-wal`, `${paths.db}-shm`, paths.audit, paths.buildState]) {
|
|
1436
|
+
try {
|
|
1437
|
+
fs.rmSync(file, { force: true });
|
|
1438
|
+
removed.push(file);
|
|
1439
|
+
} catch {
|
|
1440
|
+
/* best effort */
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
try {
|
|
1444
|
+
fs.rmSync(paths.framesDir, { recursive: true, force: true });
|
|
1445
|
+
removed.push(paths.framesDir);
|
|
1446
|
+
} catch {
|
|
1447
|
+
/* best effort */
|
|
1448
|
+
}
|
|
1449
|
+
return { ok: true, removed };
|
|
1450
|
+
}
|
|
1451
|
+
|
|
1452
|
+
/**
|
|
1453
|
+
* Build (or incrementally extend) the event index from L0 session logs.
|
|
1454
|
+
* L0 is opened read-only; every write stays under <memoryRoot>/.longlive/index/.
|
|
1455
|
+
*/
|
|
1456
|
+
export function buildIndexFromSessions(options = {}) {
|
|
1457
|
+
const memoryRoot = path.resolve(String(options.memoryRoot ?? ''));
|
|
1458
|
+
if (memoryRoot === '') throw new IndexError('E_MEMORY_ROOT', 'memoryRoot required');
|
|
1459
|
+
const now = typeof options.now === 'function' ? options.now : () => new Date();
|
|
1460
|
+
const started = Date.now();
|
|
1461
|
+
const sessionRoots = Array.isArray(options.sessionRoots) && options.sessionRoots.length > 0
|
|
1462
|
+
? options.sessionRoots
|
|
1463
|
+
: defaultSessionRoots();
|
|
1464
|
+
const limitSessions = Number.isInteger(options.limitSessions) && options.limitSessions > 0
|
|
1465
|
+
? options.limitSessions
|
|
1466
|
+
: Number.POSITIVE_INFINITY;
|
|
1467
|
+
if (options.rebuild === true) deleteIndex(memoryRoot);
|
|
1468
|
+
|
|
1469
|
+
const paths = indexPaths(memoryRoot);
|
|
1470
|
+
const index = openEventIndex({ memoryRoot, now, ...(options.dbPath ? { dbPath: options.dbPath } : {}) });
|
|
1471
|
+
const logs = discoverSessionLogs(sessionRoots).slice(0, limitSessions);
|
|
1472
|
+
const built = [];
|
|
1473
|
+
const duplicates = [];
|
|
1474
|
+
const errors = [];
|
|
1475
|
+
let inserted = 0;
|
|
1476
|
+
let skipped = 0;
|
|
1477
|
+
let eventsIndexed = 0;
|
|
1478
|
+
const seenSessionDigests = new Map();
|
|
1479
|
+
|
|
1480
|
+
for (const log of logs) {
|
|
1481
|
+
try {
|
|
1482
|
+
const buf = fs.readFileSync(log.file);
|
|
1483
|
+
const parsed = parseSession(buf);
|
|
1484
|
+
const stats = fs.statSync(log.file);
|
|
1485
|
+
const sessionId = typeof parsed.header?.id === 'string' && parsed.header.id !== ''
|
|
1486
|
+
? parsed.header.id
|
|
1487
|
+
: log.sessionId;
|
|
1488
|
+
const sessionDigest = deriveMessagesDigest(parsed.header, parsed.events).sha256;
|
|
1489
|
+
const duplicateOf = seenSessionDigests.get(sessionDigest);
|
|
1490
|
+
if (duplicateOf !== undefined) {
|
|
1491
|
+
duplicates.push({ sessionId, duplicateOf, file: log.file });
|
|
1492
|
+
continue;
|
|
1493
|
+
}
|
|
1494
|
+
seenSessionDigests.set(sessionDigest, sessionId);
|
|
1495
|
+
const records = extractTurns(parsed.header, parsed.events, parsed.frames, parsed.texts);
|
|
1496
|
+
let sessionInserted = 0;
|
|
1497
|
+
for (const record of records) {
|
|
1498
|
+
record.builtAt = now().getTime();
|
|
1499
|
+
record.source = options.source ?? 'rebuild';
|
|
1500
|
+
const result = index.upsertEvent(record, { source: record.source });
|
|
1501
|
+
if (result.inserted) {
|
|
1502
|
+
inserted += 1;
|
|
1503
|
+
sessionInserted += 1;
|
|
1504
|
+
} else {
|
|
1505
|
+
skipped += 1;
|
|
1506
|
+
}
|
|
1507
|
+
eventsIndexed += 1;
|
|
1508
|
+
}
|
|
1509
|
+
fs.writeFileSync(path.join(paths.framesDir, `${sessionId}.json`), `${JSON.stringify({
|
|
1510
|
+
schema: 'frames/v1',
|
|
1511
|
+
sessionId,
|
|
1512
|
+
sessionDigest,
|
|
1513
|
+
logBytes: buf.length,
|
|
1514
|
+
logMtimeMs: stats.mtimeMs,
|
|
1515
|
+
logSha256: crypto.createHash('sha256').update(buf).digest('hex'),
|
|
1516
|
+
frames: parsed.frames.length,
|
|
1517
|
+
turns: records.map((record) => ({
|
|
1518
|
+
turn: record.turn,
|
|
1519
|
+
seqStart: record.seqStart,
|
|
1520
|
+
seqEnd: record.seqEnd,
|
|
1521
|
+
frames: record.frameIndexes,
|
|
1522
|
+
})),
|
|
1523
|
+
}, null, 2)}\n`, 'utf8');
|
|
1524
|
+
built.push({
|
|
1525
|
+
sessionId,
|
|
1526
|
+
dirSessionId: log.sessionId,
|
|
1527
|
+
headerId: sessionId,
|
|
1528
|
+
turns: records.length,
|
|
1529
|
+
inserted: sessionInserted,
|
|
1530
|
+
bytes: buf.length,
|
|
1531
|
+
logBytes: buf.length,
|
|
1532
|
+
logMtimeMs: stats.mtimeMs,
|
|
1533
|
+
lastSeq: parsed.events.length - 1,
|
|
1534
|
+
lastTurn: records.length > 0 ? records[records.length - 1].turn : -1,
|
|
1535
|
+
header: { id: parsed.header?.id ?? null, cwd: parsed.header?.cwd ?? null },
|
|
1536
|
+
sessionDigest,
|
|
1537
|
+
file: log.file,
|
|
1538
|
+
});
|
|
1539
|
+
} catch (error) {
|
|
1540
|
+
errors.push({ file: log.file, code: error?.code ?? 'E_SESSION_PARSE', message: String(error?.message ?? error) });
|
|
1541
|
+
}
|
|
1542
|
+
}
|
|
1543
|
+
|
|
1544
|
+
const buildState = {
|
|
1545
|
+
schema: 'events-build-state/v1',
|
|
1546
|
+
builtAt: nowIso(now),
|
|
1547
|
+
schemaVersion: INDEX_SCHEMA_VERSION,
|
|
1548
|
+
memoryRoot,
|
|
1549
|
+
sessions: built.map((entry) => ({
|
|
1550
|
+
sessionId: entry.sessionId,
|
|
1551
|
+
dirSessionId: entry.dirSessionId ?? entry.sessionId,
|
|
1552
|
+
headerId: entry.headerId,
|
|
1553
|
+
turns: entry.turns,
|
|
1554
|
+
bytes: entry.bytes,
|
|
1555
|
+
logBytes: entry.logBytes,
|
|
1556
|
+
logMtimeMs: entry.logMtimeMs,
|
|
1557
|
+
lastSeq: entry.lastSeq,
|
|
1558
|
+
lastTurn: entry.lastTurn,
|
|
1559
|
+
header: entry.header,
|
|
1560
|
+
sessionDigest: entry.sessionDigest,
|
|
1561
|
+
})),
|
|
1562
|
+
duplicates,
|
|
1563
|
+
errors,
|
|
1564
|
+
stats: {
|
|
1565
|
+
sessionsScanned: logs.length,
|
|
1566
|
+
sessionsBuilt: built.length,
|
|
1567
|
+
duplicateSessions: duplicates.length,
|
|
1568
|
+
turns: eventsIndexed,
|
|
1569
|
+
inserted,
|
|
1570
|
+
skipped,
|
|
1571
|
+
errors: errors.length,
|
|
1572
|
+
durationMs: Date.now() - started,
|
|
1573
|
+
},
|
|
1574
|
+
generatedAt: nowIso(now),
|
|
1575
|
+
};
|
|
1576
|
+
fs.writeFileSync(paths.buildState, `${JSON.stringify(buildState, null, 2)}\n`, 'utf8');
|
|
1577
|
+
index.setMeta('build_state_at', buildState.builtAt);
|
|
1578
|
+
const finalStats = index.stats();
|
|
1579
|
+
index.close();
|
|
1580
|
+
return { ok: true, memoryRoot, paths, ...buildState.stats, duplicateSessions: duplicates.length, dbBytes: finalStats.dbBytes, built: built.length };
|
|
1581
|
+
}
|
|
1582
|
+
|
|
1583
|
+
/** Panel read-only route #11 reader: list indexed events; undefined when no index. */
|
|
1584
|
+
export function createEventsIndexReader(options = {}) {
|
|
1585
|
+
const memoryRoot = path.resolve(String(options.memoryRoot ?? ''));
|
|
1586
|
+
const now = typeof options.now === 'function' ? options.now : () => new Date();
|
|
1587
|
+
const paths = indexPaths(memoryRoot);
|
|
1588
|
+
if (!fs.existsSync(paths.db)) return undefined;
|
|
1589
|
+
return function eventsReader(query = {}) {
|
|
1590
|
+
const index = openEventIndex({ memoryRoot, now });
|
|
1591
|
+
try {
|
|
1592
|
+
const limit = Number.isInteger(query.limit) ? Math.min(Math.max(query.limit, 1), 200) : 20;
|
|
1593
|
+
const offset = Number.isInteger(query.offset) && query.offset > 0 ? query.offset : 0;
|
|
1594
|
+
const kind = typeof query.kind === 'string' && query.kind !== '' ? query.kind : undefined;
|
|
1595
|
+
const rows = index.listEvents({ limit, offset, kind });
|
|
1596
|
+
return {
|
|
1597
|
+
schema: EVENT_SCHEMA,
|
|
1598
|
+
events: rows,
|
|
1599
|
+
total: index.count({ kind }),
|
|
1600
|
+
limit,
|
|
1601
|
+
offset,
|
|
1602
|
+
generatedAt: now().toISOString(),
|
|
1603
|
+
};
|
|
1604
|
+
} finally {
|
|
1605
|
+
index.close();
|
|
1606
|
+
}
|
|
1607
|
+
};
|
|
1608
|
+
}
|
|
1609
|
+
|
|
1610
|
+
|
|
1611
|
+
/**
|
|
1612
|
+
* Parse appended tail frames (no session header line) starting at startSeq.
|
|
1613
|
+
* Host appends whole zstd frames, so (previous logBytes → new EOF) is frame aligned.
|
|
1614
|
+
*/
|
|
1615
|
+
export function parseSessionTail(buf, options = {}) {
|
|
1616
|
+
const startSeq = Number.isInteger(options.startSeq) ? options.startSeq : 0;
|
|
1617
|
+
const frames = splitFrames(buf);
|
|
1618
|
+
const texts = frames.map((frame) => decompressFrame(buf.subarray(frame.start, frame.end)));
|
|
1619
|
+
const events = [];
|
|
1620
|
+
for (const text of texts) {
|
|
1621
|
+
for (const line of String(text).split('\n')) {
|
|
1622
|
+
if (line === '') continue;
|
|
1623
|
+
let event = null;
|
|
1624
|
+
try {
|
|
1625
|
+
event = JSON.parse(line);
|
|
1626
|
+
} catch (error) {
|
|
1627
|
+
throw new IndexError('E_TAIL_PARSE', 'tail line is not JSON: ' + error.message);
|
|
1628
|
+
}
|
|
1629
|
+
events.push(event);
|
|
1630
|
+
}
|
|
1631
|
+
}
|
|
1632
|
+
events.forEach((event, index) => {
|
|
1633
|
+
if (event.seq !== startSeq + index) {
|
|
1634
|
+
throw new IndexError('E_TAIL_SEQ', 'tail seq ' + event.seq + ' (expected ' + (startSeq + index) + '); log rewritten, not appended');
|
|
1635
|
+
}
|
|
1636
|
+
});
|
|
1637
|
+
return { frames, texts, events };
|
|
1638
|
+
}
|
|
1639
|
+
|
|
1640
|
+
function readFromOffset(file, offset) {
|
|
1641
|
+
const fd = fs.openSync(file, 'r');
|
|
1642
|
+
try {
|
|
1643
|
+
const size = fs.fstatSync(fd).size;
|
|
1644
|
+
if (offset >= size) return Buffer.alloc(0);
|
|
1645
|
+
const buf = Buffer.alloc(size - offset);
|
|
1646
|
+
fs.readSync(fd, buf, 0, size - offset, offset);
|
|
1647
|
+
return buf;
|
|
1648
|
+
} finally {
|
|
1649
|
+
fs.closeSync(fd);
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
1652
|
+
|
|
1653
|
+
/**
|
|
1654
|
+
* Incremental build: unchanged logs are skipped; appended logs read ONLY the new
|
|
1655
|
+
* tail frames (from build-state.logBytes) and index just the new turns. Any doubt
|
|
1656
|
+
* (shrunk file, non-frame-aligned tail, tail starting mid-turn) falls back to a
|
|
1657
|
+
* full re-parse of that session — digest skip in upsertEvent stays as the safety net.
|
|
1658
|
+
*/
|
|
1659
|
+
export function buildIndexIncremental(options = {}) {
|
|
1660
|
+
const memoryRoot = path.resolve(String(options.memoryRoot ?? ''));
|
|
1661
|
+
if (memoryRoot === '') throw new IndexError('E_MEMORY_ROOT', 'memoryRoot required');
|
|
1662
|
+
const now = typeof options.now === 'function' ? options.now : () => new Date();
|
|
1663
|
+
const started = Date.now();
|
|
1664
|
+
const sessionRoots = Array.isArray(options.sessionRoots) && options.sessionRoots.length > 0
|
|
1665
|
+
? options.sessionRoots
|
|
1666
|
+
: defaultSessionRoots();
|
|
1667
|
+
const paths = indexPaths(memoryRoot);
|
|
1668
|
+
let previousState = null;
|
|
1669
|
+
try {
|
|
1670
|
+
previousState = JSON.parse(fs.readFileSync(paths.buildState, 'utf8'));
|
|
1671
|
+
} catch {
|
|
1672
|
+
previousState = null;
|
|
1673
|
+
}
|
|
1674
|
+
if (!previousState || !Array.isArray(previousState.sessions)) {
|
|
1675
|
+
const full = buildIndexFromSessions({
|
|
1676
|
+
memoryRoot,
|
|
1677
|
+
sessionRoots,
|
|
1678
|
+
now,
|
|
1679
|
+
...(options.limitSessions ? { limitSessions: options.limitSessions } : {}),
|
|
1680
|
+
});
|
|
1681
|
+
return { ok: true, mode: 'full-fallback', ...full };
|
|
1682
|
+
}
|
|
1683
|
+
const index = openEventIndex({ memoryRoot, now, ...(options.dbPath ? { dbPath: options.dbPath } : {}) });
|
|
1684
|
+
const logs = discoverSessionLogs(sessionRoots).slice(0, Number.isInteger(options.limitSessions) ? options.limitSessions : Number.POSITIVE_INFINITY);
|
|
1685
|
+
const stateBySession = new Map(previousState.sessions.map((entry) => [entry.dirSessionId ?? entry.sessionId, { ...entry }]));
|
|
1686
|
+
const duplicates = Array.isArray(previousState.duplicates) ? [...previousState.duplicates] : [];
|
|
1687
|
+
const errors = [];
|
|
1688
|
+
const stats = {
|
|
1689
|
+
sessionsScanned: logs.length,
|
|
1690
|
+
sessionsUnchanged: 0,
|
|
1691
|
+
sessionsAppended: 0,
|
|
1692
|
+
sessionsRebuilt: 0,
|
|
1693
|
+
sessionsNew: 0,
|
|
1694
|
+
turns: 0,
|
|
1695
|
+
inserted: 0,
|
|
1696
|
+
skipped: 0,
|
|
1697
|
+
errors: 0,
|
|
1698
|
+
};
|
|
1699
|
+
|
|
1700
|
+
const rebuildOne = (log, stat) => {
|
|
1701
|
+
const buf = fs.readFileSync(log.file);
|
|
1702
|
+
const parsed = parseSession(buf);
|
|
1703
|
+
const headerId = typeof parsed.header?.id === 'string' && parsed.header.id !== '' ? parsed.header.id : log.sessionId;
|
|
1704
|
+
index.deleteSession(headerId);
|
|
1705
|
+
const records = extractTurns(parsed.header, parsed.events, parsed.frames, parsed.texts);
|
|
1706
|
+
let inserted = 0;
|
|
1707
|
+
for (const record of records) {
|
|
1708
|
+
record.builtAt = now().getTime();
|
|
1709
|
+
record.source = 'incremental-rebuild';
|
|
1710
|
+
const result = index.upsertEvent(record, { source: record.source });
|
|
1711
|
+
if (result.inserted) inserted += 1;
|
|
1712
|
+
}
|
|
1713
|
+
stateBySession.set(log.sessionId, {
|
|
1714
|
+
sessionId: headerId,
|
|
1715
|
+
dirSessionId: log.sessionId,
|
|
1716
|
+
headerId,
|
|
1717
|
+
turns: records.length,
|
|
1718
|
+
bytes: buf.length,
|
|
1719
|
+
logBytes: buf.length,
|
|
1720
|
+
logMtimeMs: stat.mtimeMs,
|
|
1721
|
+
lastSeq: parsed.events.length - 1,
|
|
1722
|
+
lastTurn: records.length > 0 ? records[records.length - 1].turn : -1,
|
|
1723
|
+
header: { id: parsed.header?.id ?? null, cwd: parsed.header?.cwd ?? null },
|
|
1724
|
+
sessionDigest: deriveMessagesDigest(parsed.header, parsed.events).sha256,
|
|
1725
|
+
});
|
|
1726
|
+
stats.turns += records.length;
|
|
1727
|
+
stats.inserted += inserted;
|
|
1728
|
+
stats.skipped += records.length - inserted;
|
|
1729
|
+
return { records, inserted };
|
|
1730
|
+
};
|
|
1731
|
+
|
|
1732
|
+
for (const log of logs) {
|
|
1733
|
+
let stat = null;
|
|
1734
|
+
try {
|
|
1735
|
+
stat = fs.statSync(log.file);
|
|
1736
|
+
} catch {
|
|
1737
|
+
continue;
|
|
1738
|
+
}
|
|
1739
|
+
const stateEntry = stateBySession.get(log.sessionId);
|
|
1740
|
+
if (stateEntry && stateEntry.logBytes === stat.size && stateEntry.logMtimeMs === stat.mtimeMs) {
|
|
1741
|
+
stats.sessionsUnchanged += 1;
|
|
1742
|
+
continue;
|
|
1743
|
+
}
|
|
1744
|
+
if (!stateEntry) {
|
|
1745
|
+
try {
|
|
1746
|
+
rebuildOne(log, stat);
|
|
1747
|
+
stats.sessionsNew += 1;
|
|
1748
|
+
} catch (error) {
|
|
1749
|
+
errors.push({ file: log.file, code: error?.code ?? 'E_INCREMENTAL', message: String(error?.message ?? error) });
|
|
1750
|
+
}
|
|
1751
|
+
continue;
|
|
1752
|
+
}
|
|
1753
|
+
if (stat.size < stateEntry.logBytes) {
|
|
1754
|
+
try {
|
|
1755
|
+
rebuildOne(log, stat);
|
|
1756
|
+
stats.sessionsRebuilt += 1;
|
|
1757
|
+
} catch (error) {
|
|
1758
|
+
errors.push({ file: log.file, code: error?.code ?? 'E_INCREMENTAL', message: String(error?.message ?? error) });
|
|
1759
|
+
}
|
|
1760
|
+
continue;
|
|
1761
|
+
}
|
|
1762
|
+
try {
|
|
1763
|
+
const tailBuf = readFromOffset(log.file, stateEntry.logBytes);
|
|
1764
|
+
if (tailBuf.length === 0) {
|
|
1765
|
+
stats.sessionsUnchanged += 1;
|
|
1766
|
+
continue;
|
|
1767
|
+
}
|
|
1768
|
+
const tail = parseSessionTail(tailBuf, { startSeq: stateEntry.lastSeq + 1 });
|
|
1769
|
+
const firstTurn = Number(tail.events[0]?.data?.turn);
|
|
1770
|
+
if (!Number.isInteger(firstTurn) || firstTurn <= (stateEntry.lastTurn ?? -1)) {
|
|
1771
|
+
rebuildOne(log, stat);
|
|
1772
|
+
stats.sessionsRebuilt += 1;
|
|
1773
|
+
continue;
|
|
1774
|
+
}
|
|
1775
|
+
const header = { id: stateEntry.headerId ?? log.sessionId, cwd: stateEntry.header?.cwd ?? null };
|
|
1776
|
+
const records = extractTurns(header, tail.events, tail.frames, tail.texts);
|
|
1777
|
+
let inserted = 0;
|
|
1778
|
+
for (const record of records) {
|
|
1779
|
+
record.builtAt = now().getTime();
|
|
1780
|
+
record.source = 'incremental-tail';
|
|
1781
|
+
const result = index.upsertEvent(record, { source: record.source });
|
|
1782
|
+
if (result.inserted) inserted += 1;
|
|
1783
|
+
}
|
|
1784
|
+
stateBySession.set(log.sessionId, {
|
|
1785
|
+
...stateEntry,
|
|
1786
|
+
turns: (stateEntry.turns ?? 0) + records.length,
|
|
1787
|
+
logBytes: stat.size,
|
|
1788
|
+
logMtimeMs: stat.mtimeMs,
|
|
1789
|
+
lastSeq: tail.events[tail.events.length - 1].seq,
|
|
1790
|
+
lastTurn: records.length > 0 ? records[records.length - 1].turn : stateEntry.lastTurn,
|
|
1791
|
+
});
|
|
1792
|
+
stats.sessionsAppended += 1;
|
|
1793
|
+
stats.turns += records.length;
|
|
1794
|
+
stats.inserted += inserted;
|
|
1795
|
+
stats.skipped += records.length - inserted;
|
|
1796
|
+
} catch {
|
|
1797
|
+
try {
|
|
1798
|
+
rebuildOne(log, stat);
|
|
1799
|
+
stats.sessionsRebuilt += 1;
|
|
1800
|
+
} catch (error2) {
|
|
1801
|
+
errors.push({ file: log.file, code: error2?.code ?? 'E_INCREMENTAL', message: String(error2?.message ?? error2) });
|
|
1802
|
+
}
|
|
1803
|
+
}
|
|
1804
|
+
}
|
|
1805
|
+
|
|
1806
|
+
stats.errors = errors.length;
|
|
1807
|
+
const buildState = {
|
|
1808
|
+
schema: 'events-build-state/v1',
|
|
1809
|
+
builtAt: nowIso(now),
|
|
1810
|
+
schemaVersion: INDEX_SCHEMA_VERSION,
|
|
1811
|
+
memoryRoot,
|
|
1812
|
+
mode: 'incremental',
|
|
1813
|
+
sessions: [...stateBySession.values()].sort((a, b) => a.sessionId.localeCompare(b.sessionId)),
|
|
1814
|
+
duplicates,
|
|
1815
|
+
errors,
|
|
1816
|
+
stats,
|
|
1817
|
+
durationMs: Date.now() - started,
|
|
1818
|
+
};
|
|
1819
|
+
fs.writeFileSync(paths.buildState, JSON.stringify(buildState, null, 2) + '\n', 'utf8');
|
|
1820
|
+
index.setMeta('build_state_at', buildState.builtAt);
|
|
1821
|
+
const finalStats = index.stats();
|
|
1822
|
+
index.close();
|
|
1823
|
+
return { ok: true, mode: 'incremental', memoryRoot, paths, ...stats, dbBytes: finalStats.dbBytes, durationMs: Date.now() - started };
|
|
1824
|
+
}
|
|
1825
|
+
|
|
1826
|
+
export { stableStringify };
|