@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,668 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// scripts/archive-digest-build.mjs — M2-A 旧记忆归档摘要构建(archive digest)
|
|
3
|
+
//
|
|
4
|
+
// 把「热截断」与「可见截断」切掉的旧正文,摘成本地只读索引,供
|
|
5
|
+
// `src/recall/archive-search.mjs#searchArchive` 查询。输入只读,输出原子写。
|
|
6
|
+
//
|
|
7
|
+
// node scripts/archive-digest-build.mjs \
|
|
8
|
+
// --memory-root <dir> [--sessions-root <dir>] [--out <dir>] \
|
|
9
|
+
// [--incremental] [--dry-run] [--json]
|
|
10
|
+
//
|
|
11
|
+
// 输入:<memory-root>/.longlive/hot-truncate/*.jsonl
|
|
12
|
+
// <sessions-root>/**/session.v4.jsonl.zstd.archive/*.zstd
|
|
13
|
+
// 输出:<out>/{index.jsonl,manifest.json};--out 默认 = <memory-root>/.longlive/archive-digest
|
|
14
|
+
//
|
|
15
|
+
// 增量策略(幂等、与全量构建等价):输入按固定顺序排列;只有「从头开始、路径与
|
|
16
|
+
// sha256 都没变」的前缀文件复用上次索引行,遇到第一个变化(改/增/删/重排)后,
|
|
17
|
+
// 其后全部重新解析。这样去重结果与全量构建逐字节一致(去重依赖输入顺序)。
|
|
18
|
+
|
|
19
|
+
import crypto from 'node:crypto';
|
|
20
|
+
import fs from 'node:fs';
|
|
21
|
+
import os from 'node:os';
|
|
22
|
+
import path from 'node:path';
|
|
23
|
+
import { pathToFileURL } from 'node:url';
|
|
24
|
+
|
|
25
|
+
import { splitFrames, decompressFrame } from '../src/codec.js';
|
|
26
|
+
import {
|
|
27
|
+
ARCHIVE_DIGEST_SCHEMA,
|
|
28
|
+
ARCHIVE_DIGEST_DIR,
|
|
29
|
+
ARCHIVE_INDEX_FILE,
|
|
30
|
+
ARCHIVE_MANIFEST_FILE,
|
|
31
|
+
foldWhitespace,
|
|
32
|
+
tokenizeQuery,
|
|
33
|
+
} from '../src/recall/archive-search.mjs';
|
|
34
|
+
|
|
35
|
+
const HOT_TRUNCATE_SUBDIR = path.join('.longlive', 'hot-truncate');
|
|
36
|
+
const ARCHIVE_DIR_SUFFIX = '.archive';
|
|
37
|
+
const ARCHIVE_FILE_SUFFIX = '.zstd';
|
|
38
|
+
const MAX_WALK_DEPTH = 8;
|
|
39
|
+
|
|
40
|
+
// ---------------------------------------------------------------------------
|
|
41
|
+
// 小工具
|
|
42
|
+
// ---------------------------------------------------------------------------
|
|
43
|
+
|
|
44
|
+
function sha256Hex(input) {
|
|
45
|
+
const hash = crypto.createHash('sha256');
|
|
46
|
+
hash.update(typeof input === 'string' ? Buffer.from(input, 'utf8') : input);
|
|
47
|
+
return hash.digest('hex');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function briefError(error) {
|
|
51
|
+
const message = error && typeof error.message === 'string' ? error.message : String(error);
|
|
52
|
+
return message.length > 300 ? `${message.slice(0, 300)}…` : message;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function dshHome() {
|
|
56
|
+
const raw = process.env.DSH_HOME;
|
|
57
|
+
if (typeof raw === 'string' && raw.trim() !== '') return path.resolve(raw.trim());
|
|
58
|
+
return path.join(os.homedir(), '.dsh');
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function defaultMemoryRoot() {
|
|
62
|
+
for (const envName of ['DSH_LONGLIVE_MEMORY_ROOT', 'DSH_MEM']) {
|
|
63
|
+
const value = process.env[envName];
|
|
64
|
+
if (typeof value === 'string' && value.trim() !== '') return path.resolve(value.trim());
|
|
65
|
+
}
|
|
66
|
+
return path.join(dshHome(), 'longlive-memory');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function defaultSessionsRoot() {
|
|
70
|
+
return path.join(dshHome(), 'sessions');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// ---------------------------------------------------------------------------
|
|
74
|
+
// 输入发现
|
|
75
|
+
// ---------------------------------------------------------------------------
|
|
76
|
+
|
|
77
|
+
/** <memoryRoot>/.longlive/hot-truncate/*.jsonl(按文件名排序,保证构建确定)。 */
|
|
78
|
+
export function discoverHotTruncateInputs(memoryRoot) {
|
|
79
|
+
const dir = path.join(path.resolve(memoryRoot), HOT_TRUNCATE_SUBDIR);
|
|
80
|
+
let entries;
|
|
81
|
+
try {
|
|
82
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
83
|
+
} catch {
|
|
84
|
+
return [];
|
|
85
|
+
}
|
|
86
|
+
return entries
|
|
87
|
+
.filter((entry) => entry.isFile() && entry.name.endsWith('.jsonl'))
|
|
88
|
+
.map((entry) => path.join(dir, entry.name))
|
|
89
|
+
.sort();
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** <sessionsRoot>/**\\session.v4.jsonl.zstd.archive/*.zstd(只下钻到 .archive 目录,只读)。 */
|
|
93
|
+
export function discoverArchiveInputs(sessionsRoot) {
|
|
94
|
+
if (typeof sessionsRoot !== 'string' || sessionsRoot.trim() === '') return [];
|
|
95
|
+
const root = path.resolve(sessionsRoot.trim());
|
|
96
|
+
if (!fs.existsSync(root)) return [];
|
|
97
|
+
const out = [];
|
|
98
|
+
const walk = (dir, depth) => {
|
|
99
|
+
if (depth > MAX_WALK_DEPTH) return;
|
|
100
|
+
let entries;
|
|
101
|
+
try {
|
|
102
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
103
|
+
} catch {
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
for (const entry of entries) {
|
|
107
|
+
if (!entry.isDirectory()) continue;
|
|
108
|
+
const full = path.join(dir, entry.name);
|
|
109
|
+
if (entry.name.endsWith(ARCHIVE_DIR_SUFFIX)) {
|
|
110
|
+
let files;
|
|
111
|
+
try {
|
|
112
|
+
files = fs.readdirSync(full, { withFileTypes: true });
|
|
113
|
+
} catch {
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
for (const file of files) {
|
|
117
|
+
if (file.isFile() && file.name.endsWith(ARCHIVE_FILE_SUFFIX)) out.push(path.join(full, file.name));
|
|
118
|
+
}
|
|
119
|
+
} else {
|
|
120
|
+
walk(full, depth + 1);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
walk(root, 0);
|
|
125
|
+
return out.sort();
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** 归档输入在前、热截断在后;各自按路径排序。去重依赖这个顺序,不要随意改。 */
|
|
129
|
+
export function discoverInputs({ memoryRoot, sessionsRoot }) {
|
|
130
|
+
const inputs = [];
|
|
131
|
+
for (const filePath of discoverArchiveInputs(sessionsRoot)) inputs.push({ path: filePath, kind: 'archive' });
|
|
132
|
+
for (const filePath of discoverHotTruncateInputs(memoryRoot)) inputs.push({ path: filePath, kind: 'hot-truncate' });
|
|
133
|
+
return inputs;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// ---------------------------------------------------------------------------
|
|
137
|
+
// 输入解析
|
|
138
|
+
// ---------------------------------------------------------------------------
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* 会话日志归档(多帧 zstd):frame0 = session header,其后每帧是一批事件。
|
|
142
|
+
* 逐帧解压、逐行 JSON.parse,不把整个快照 join 成一个大字符串(大归档省内存)。
|
|
143
|
+
*/
|
|
144
|
+
export function parseArchiveBuffer(buffer) {
|
|
145
|
+
const frames = splitFrames(buffer);
|
|
146
|
+
if (frames.length === 0) throw new Error('archive has no zstd frames');
|
|
147
|
+
const headerText = decompressFrame(buffer.subarray(frames[0].start, frames[0].end));
|
|
148
|
+
const headerLines = headerText.split('\n').filter((line) => line.length > 0);
|
|
149
|
+
if (headerLines.length !== 1) throw new Error(`archive header frame must hold exactly 1 line, got ${headerLines.length}`);
|
|
150
|
+
let header;
|
|
151
|
+
try {
|
|
152
|
+
header = JSON.parse(headerLines[0]);
|
|
153
|
+
} catch (error) {
|
|
154
|
+
throw new Error(`archive header is not JSON: ${briefError(error)}`);
|
|
155
|
+
}
|
|
156
|
+
if (!header || header.type !== 'session') throw new Error('archive header is not a session header');
|
|
157
|
+
if (header.version !== 4) throw new Error(`unsupported archive header version ${header.version}`);
|
|
158
|
+
|
|
159
|
+
const events = [];
|
|
160
|
+
let expectedSeq = 0;
|
|
161
|
+
for (let frameNo = 1; frameNo < frames.length; frameNo += 1) {
|
|
162
|
+
const frame = frames[frameNo];
|
|
163
|
+
const text = decompressFrame(buffer.subarray(frame.start, frame.end));
|
|
164
|
+
for (const line of text.split('\n')) {
|
|
165
|
+
if (line === '') continue;
|
|
166
|
+
let event;
|
|
167
|
+
try {
|
|
168
|
+
event = JSON.parse(line);
|
|
169
|
+
} catch (error) {
|
|
170
|
+
throw new Error(`archive frame ${frameNo}: event line is not JSON: ${briefError(error)}`);
|
|
171
|
+
}
|
|
172
|
+
if (!event || typeof event !== 'object') throw new Error(`archive frame ${frameNo}: event is not an object`);
|
|
173
|
+
if (event.seq !== expectedSeq) throw new Error(`archive event seq ${event.seq} at index ${expectedSeq} (not contiguous from 0)`);
|
|
174
|
+
expectedSeq += 1;
|
|
175
|
+
events.push(event);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
return { header, events, frameCount: frames.length };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** 热截断 JSONL:header 行 + 原始事件行 + footer 行。坏行计数但不打断(写入中的文件容忍)。 */
|
|
182
|
+
export function parseHotTruncateBuffer(buffer, filePath = '') {
|
|
183
|
+
const lines = String(buffer ?? '').split('\n');
|
|
184
|
+
let header = null;
|
|
185
|
+
let sawFooter = false;
|
|
186
|
+
let parseErrors = 0;
|
|
187
|
+
const events = [];
|
|
188
|
+
for (const raw of lines) {
|
|
189
|
+
const line = raw.trim();
|
|
190
|
+
if (line === '') continue;
|
|
191
|
+
let item;
|
|
192
|
+
try {
|
|
193
|
+
item = JSON.parse(line);
|
|
194
|
+
} catch {
|
|
195
|
+
parseErrors += 1;
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
if (item && item.kind === 'hot-truncate/header') {
|
|
199
|
+
if (header === null) header = item;
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
if (item && item.kind === 'hot-truncate/footer') {
|
|
203
|
+
sawFooter = true;
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
if (item && typeof item === 'object' && Number.isInteger(item.seq)) events.push(item);
|
|
207
|
+
else parseErrors += 1;
|
|
208
|
+
}
|
|
209
|
+
if (!header) throw new Error(`hot-truncate file has no header: ${filePath}`);
|
|
210
|
+
if (typeof header.sessionId !== 'string' || header.sessionId === '') {
|
|
211
|
+
throw new Error(`hot-truncate header has no sessionId: ${filePath}`);
|
|
212
|
+
}
|
|
213
|
+
return { header, events, parseErrors, sawFooter };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function messageContentBlocks(event) {
|
|
217
|
+
const data = event && typeof event.data === 'object' && event.data !== null ? event.data : null;
|
|
218
|
+
const candidates = [data?.content, data?.message?.content, event?.message?.content];
|
|
219
|
+
for (const candidate of candidates) {
|
|
220
|
+
if (Array.isArray(candidate)) return candidate;
|
|
221
|
+
}
|
|
222
|
+
return null;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** 从事件流里抽 user/assistant 的正文文本(只要 content[].type==='text',跳过 reasoning/tool-call)。 */
|
|
226
|
+
export function extractEntries({ events, sessionId, sourceSha, sourcePath }) {
|
|
227
|
+
const entries = [];
|
|
228
|
+
let turn = null;
|
|
229
|
+
for (const event of events) {
|
|
230
|
+
if (!event || typeof event !== 'object') continue;
|
|
231
|
+
if (event.type === 'turn/start') {
|
|
232
|
+
const value = event.data?.turn ?? event.turn;
|
|
233
|
+
if (Number.isInteger(value)) turn = value;
|
|
234
|
+
continue;
|
|
235
|
+
}
|
|
236
|
+
if (event.type !== 'user/message' && event.type !== 'assistant/message') continue;
|
|
237
|
+
const blocks = messageContentBlocks(event);
|
|
238
|
+
if (!blocks) continue;
|
|
239
|
+
const textParts = [];
|
|
240
|
+
for (const block of blocks) {
|
|
241
|
+
if (block && block.type === 'text' && typeof block.text === 'string' && block.text.trim() !== '') textParts.push(block.text);
|
|
242
|
+
}
|
|
243
|
+
if (textParts.length === 0) continue;
|
|
244
|
+
const folded = foldWhitespace(textParts.join('\n'));
|
|
245
|
+
if (folded === '') continue;
|
|
246
|
+
const eventTurn = Number.isInteger(event.turn)
|
|
247
|
+
? event.turn
|
|
248
|
+
: Number.isInteger(event.data?.turn)
|
|
249
|
+
? event.data.turn
|
|
250
|
+
: turn;
|
|
251
|
+
entries.push({
|
|
252
|
+
p: sourcePath,
|
|
253
|
+
s: sessionId,
|
|
254
|
+
seq: Number.isInteger(event.seq) ? event.seq : null,
|
|
255
|
+
turn: Number.isInteger(eventTurn) ? eventTurn : null,
|
|
256
|
+
ts: Number.isFinite(event.time) ? event.time : null,
|
|
257
|
+
t: folded,
|
|
258
|
+
h: sourceSha,
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
return entries;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// ---------------------------------------------------------------------------
|
|
265
|
+
// 输出写入(tmp → rename,重复构建幂等)
|
|
266
|
+
// ---------------------------------------------------------------------------
|
|
267
|
+
|
|
268
|
+
function writeIndexLines({ lines, indexPath, dryRun }) {
|
|
269
|
+
const hash = crypto.createHash('sha256');
|
|
270
|
+
let bytes = 0;
|
|
271
|
+
if (dryRun) {
|
|
272
|
+
for (const line of lines) {
|
|
273
|
+
const buf = Buffer.from(`${line}\n`, 'utf8');
|
|
274
|
+
hash.update(buf);
|
|
275
|
+
bytes += buf.length;
|
|
276
|
+
}
|
|
277
|
+
return { bytes, sha256: hash.digest('hex'), written: false };
|
|
278
|
+
}
|
|
279
|
+
fs.mkdirSync(path.dirname(indexPath), { recursive: true });
|
|
280
|
+
const tmp = `${indexPath}.tmp-${process.pid}-${Date.now()}`;
|
|
281
|
+
const fd = fs.openSync(tmp, 'w');
|
|
282
|
+
try {
|
|
283
|
+
for (const line of lines) {
|
|
284
|
+
const buf = Buffer.from(`${line}\n`, 'utf8');
|
|
285
|
+
fs.writeSync(fd, buf);
|
|
286
|
+
hash.update(buf);
|
|
287
|
+
bytes += buf.length;
|
|
288
|
+
}
|
|
289
|
+
fs.fsyncSync(fd);
|
|
290
|
+
} catch (error) {
|
|
291
|
+
try {
|
|
292
|
+
fs.closeSync(fd);
|
|
293
|
+
} catch {
|
|
294
|
+
// ignore
|
|
295
|
+
}
|
|
296
|
+
try {
|
|
297
|
+
fs.unlinkSync(tmp);
|
|
298
|
+
} catch {
|
|
299
|
+
// ignore
|
|
300
|
+
}
|
|
301
|
+
throw error;
|
|
302
|
+
}
|
|
303
|
+
fs.closeSync(fd);
|
|
304
|
+
fs.renameSync(tmp, indexPath);
|
|
305
|
+
return { bytes, sha256: hash.digest('hex'), written: true };
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function writeJsonAtomic(filePath, value) {
|
|
309
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
310
|
+
const tmp = `${filePath}.tmp-${process.pid}-${Date.now()}`;
|
|
311
|
+
const text = `${JSON.stringify(value, null, 2)}\n`;
|
|
312
|
+
fs.writeFileSync(tmp, text);
|
|
313
|
+
try {
|
|
314
|
+
fs.renameSync(tmp, filePath);
|
|
315
|
+
} catch (error) {
|
|
316
|
+
try {
|
|
317
|
+
fs.unlinkSync(tmp);
|
|
318
|
+
} catch {
|
|
319
|
+
// ignore
|
|
320
|
+
}
|
|
321
|
+
throw error;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// ---------------------------------------------------------------------------
|
|
326
|
+
// 构建
|
|
327
|
+
// ---------------------------------------------------------------------------
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* 扫描输入、摘要、写索引。任何输入文件失败只记入 manifest(error 字段),不中断整体。
|
|
331
|
+
* @returns {Promise<object>} receipt
|
|
332
|
+
*/
|
|
333
|
+
export async function buildArchiveDigest(options = {}) {
|
|
334
|
+
const started = Date.now();
|
|
335
|
+
if (typeof options.memoryRoot !== 'string' || options.memoryRoot.trim() === '') {
|
|
336
|
+
throw new Error('buildArchiveDigest: memoryRoot is required');
|
|
337
|
+
}
|
|
338
|
+
const memoryRoot = path.resolve(options.memoryRoot.trim());
|
|
339
|
+
const sessionsRoot = typeof options.sessionsRoot === 'string' && options.sessionsRoot.trim() !== ''
|
|
340
|
+
? path.resolve(options.sessionsRoot.trim())
|
|
341
|
+
: defaultSessionsRoot();
|
|
342
|
+
const outDir = typeof options.outDir === 'string' && options.outDir.trim() !== ''
|
|
343
|
+
? path.resolve(options.outDir.trim())
|
|
344
|
+
: path.join(memoryRoot, '.longlive', ARCHIVE_DIGEST_DIR);
|
|
345
|
+
const incremental = options.incremental === true;
|
|
346
|
+
const dryRun = options.dryRun === true;
|
|
347
|
+
const indexPath = path.join(outDir, ARCHIVE_INDEX_FILE);
|
|
348
|
+
const manifestPath = path.join(outDir, ARCHIVE_MANIFEST_FILE);
|
|
349
|
+
|
|
350
|
+
const inputs = discoverInputs({ memoryRoot, sessionsRoot });
|
|
351
|
+
const stats = {
|
|
352
|
+
inputs: inputs.length,
|
|
353
|
+
archives: inputs.filter((input) => input.kind === 'archive').length,
|
|
354
|
+
hotTruncate: inputs.filter((input) => input.kind === 'hot-truncate').length,
|
|
355
|
+
inputsParsed: 0,
|
|
356
|
+
inputsReused: 0,
|
|
357
|
+
inputsFailed: 0,
|
|
358
|
+
eventsScanned: 0,
|
|
359
|
+
textEvents: 0,
|
|
360
|
+
duplicatesDropped: 0,
|
|
361
|
+
entryCount: 0,
|
|
362
|
+
};
|
|
363
|
+
|
|
364
|
+
// ---- 上次索引(增量) -----------------------------------------------------
|
|
365
|
+
let prev = null;
|
|
366
|
+
let prevUsable = false;
|
|
367
|
+
if (incremental) {
|
|
368
|
+
try {
|
|
369
|
+
prev = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
|
|
370
|
+
} catch {
|
|
371
|
+
prev = null;
|
|
372
|
+
}
|
|
373
|
+
if (prev && prev.schema === ARCHIVE_DIGEST_SCHEMA && typeof prev.indexSha256 === 'string' && fs.existsSync(indexPath)) {
|
|
374
|
+
try {
|
|
375
|
+
prevUsable = sha256Hex(fs.readFileSync(indexPath)) === prev.indexSha256;
|
|
376
|
+
} catch {
|
|
377
|
+
prevUsable = false;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
const prevInputsList = prevUsable && Array.isArray(prev.inputs) ? prev.inputs : [];
|
|
382
|
+
|
|
383
|
+
let oldGroups = null;
|
|
384
|
+
let oldGroupsLoaded = false;
|
|
385
|
+
const loadOldGroups = () => {
|
|
386
|
+
if (oldGroupsLoaded) return oldGroups;
|
|
387
|
+
oldGroupsLoaded = true;
|
|
388
|
+
const groups = new Map();
|
|
389
|
+
let text;
|
|
390
|
+
try {
|
|
391
|
+
text = fs.readFileSync(indexPath, 'utf8');
|
|
392
|
+
} catch {
|
|
393
|
+
oldGroups = null;
|
|
394
|
+
return oldGroups;
|
|
395
|
+
}
|
|
396
|
+
for (const line of text.split('\n')) {
|
|
397
|
+
if (line === '') continue;
|
|
398
|
+
let entry;
|
|
399
|
+
try {
|
|
400
|
+
entry = JSON.parse(line);
|
|
401
|
+
} catch {
|
|
402
|
+
oldGroups = null;
|
|
403
|
+
return oldGroups;
|
|
404
|
+
}
|
|
405
|
+
if (!entry || typeof entry.p !== 'string' || typeof entry.s !== 'string' || typeof entry.t !== 'string') {
|
|
406
|
+
oldGroups = null;
|
|
407
|
+
return oldGroups;
|
|
408
|
+
}
|
|
409
|
+
const list = groups.get(entry.p);
|
|
410
|
+
if (list) list.push(line);
|
|
411
|
+
else groups.set(entry.p, [line]);
|
|
412
|
+
}
|
|
413
|
+
oldGroups = groups;
|
|
414
|
+
return oldGroups;
|
|
415
|
+
};
|
|
416
|
+
|
|
417
|
+
// ---- 主扫描 / 合并 -------------------------------------------------------
|
|
418
|
+
const lines = [];
|
|
419
|
+
const seen = new Set();
|
|
420
|
+
const writtenByPath = new Map();
|
|
421
|
+
const inputRecords = [];
|
|
422
|
+
let reuseMode = incremental && prevUsable;
|
|
423
|
+
|
|
424
|
+
const addEntryLine = (line, entry) => {
|
|
425
|
+
const key = `${entry.s}\u0000${sha256Hex(entry.t)}`;
|
|
426
|
+
if (seen.has(key)) return false;
|
|
427
|
+
seen.add(key);
|
|
428
|
+
lines.push(line);
|
|
429
|
+
writtenByPath.set(entry.p, (writtenByPath.get(entry.p) || 0) + 1);
|
|
430
|
+
return true;
|
|
431
|
+
};
|
|
432
|
+
|
|
433
|
+
let inputIndex = 0;
|
|
434
|
+
for (const input of inputs) {
|
|
435
|
+
// 复用以「位置」为准,不按路径查:上一个清单里第 i 个输入必须还是同一个文件,
|
|
436
|
+
// 否则(前面增/删/改/重排)前缀链已断,不能复用。
|
|
437
|
+
const prevInput = prevUsable ? prevInputsList[inputIndex] : null;
|
|
438
|
+
inputIndex += 1;
|
|
439
|
+
let buffer;
|
|
440
|
+
let sha256;
|
|
441
|
+
let bytes;
|
|
442
|
+
let mtimeMs;
|
|
443
|
+
try {
|
|
444
|
+
const stat = fs.statSync(input.path);
|
|
445
|
+
buffer = fs.readFileSync(input.path);
|
|
446
|
+
sha256 = sha256Hex(buffer);
|
|
447
|
+
bytes = stat.size;
|
|
448
|
+
mtimeMs = stat.mtimeMs;
|
|
449
|
+
} catch (error) {
|
|
450
|
+
stats.inputsFailed += 1;
|
|
451
|
+
inputRecords.push({ path: input.path, kind: input.kind, error: briefError(error) });
|
|
452
|
+
reuseMode = false; // 读不到 = 前缀链断开
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
if (reuseMode && prevInput && prevInput.path === input.path && prevInput.sha256 === sha256 && Number.isInteger(prevInput.entries)) {
|
|
457
|
+
const groups = loadOldGroups();
|
|
458
|
+
const reusedLines = groups ? groups.get(input.path) || [] : null;
|
|
459
|
+
if (reusedLines && reusedLines.length === prevInput.entries) {
|
|
460
|
+
let added = 0;
|
|
461
|
+
for (const line of reusedLines) {
|
|
462
|
+
let entry;
|
|
463
|
+
try {
|
|
464
|
+
entry = JSON.parse(line);
|
|
465
|
+
} catch {
|
|
466
|
+
entry = null;
|
|
467
|
+
}
|
|
468
|
+
if (!entry) {
|
|
469
|
+
added = -1;
|
|
470
|
+
break;
|
|
471
|
+
}
|
|
472
|
+
if (addEntryLine(line, entry)) added += 1;
|
|
473
|
+
}
|
|
474
|
+
if (added >= 0) {
|
|
475
|
+
stats.inputsReused += 1;
|
|
476
|
+
stats.eventsScanned += Number.isInteger(prevInput.events) ? prevInput.events : 0;
|
|
477
|
+
stats.textEvents += Number.isInteger(prevInput.textEvents) ? prevInput.textEvents : 0;
|
|
478
|
+
inputRecords.push({
|
|
479
|
+
path: input.path,
|
|
480
|
+
kind: input.kind,
|
|
481
|
+
sha256,
|
|
482
|
+
bytes,
|
|
483
|
+
mtimeMs,
|
|
484
|
+
events: Number.isInteger(prevInput.events) ? prevInput.events : 0,
|
|
485
|
+
textEvents: Number.isInteger(prevInput.textEvents) ? prevInput.textEvents : 0,
|
|
486
|
+
entries: added,
|
|
487
|
+
reused: true,
|
|
488
|
+
});
|
|
489
|
+
continue;
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
// 有输入需要重解析(改/增/删/重排)→ 前缀链断开,其后一律重解析;
|
|
494
|
+
// 否则「前面新增一个文件、后面同名旧文件被复用」会漏掉新去重关系。
|
|
495
|
+
reuseMode = false;
|
|
496
|
+
|
|
497
|
+
let parsed;
|
|
498
|
+
try {
|
|
499
|
+
if (input.kind === 'archive') {
|
|
500
|
+
const archive = parseArchiveBuffer(buffer);
|
|
501
|
+
if (typeof archive.header.id !== 'string' || archive.header.id === '') throw new Error('archive header has no session id');
|
|
502
|
+
parsed = { sessionId: archive.header.id, events: archive.events, extra: { frameCount: archive.frameCount } };
|
|
503
|
+
} else {
|
|
504
|
+
const hot = parseHotTruncateBuffer(buffer, input.path);
|
|
505
|
+
parsed = { sessionId: hot.header.sessionId, events: hot.events, extra: { parseErrors: hot.parseErrors, sawFooter: hot.sawFooter } };
|
|
506
|
+
}
|
|
507
|
+
} catch (error) {
|
|
508
|
+
stats.inputsFailed += 1;
|
|
509
|
+
inputRecords.push({ path: input.path, kind: input.kind, sha256, bytes, mtimeMs, error: briefError(error) });
|
|
510
|
+
continue;
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
const entries = extractEntries({
|
|
514
|
+
events: parsed.events,
|
|
515
|
+
sessionId: parsed.sessionId,
|
|
516
|
+
sourceSha: sha256,
|
|
517
|
+
sourcePath: input.path,
|
|
518
|
+
});
|
|
519
|
+
let added = 0;
|
|
520
|
+
for (const entry of entries) {
|
|
521
|
+
if (addEntryLine(JSON.stringify(entry), entry)) added += 1;
|
|
522
|
+
}
|
|
523
|
+
stats.inputsParsed += 1;
|
|
524
|
+
stats.eventsScanned += parsed.events.length;
|
|
525
|
+
stats.textEvents += entries.length;
|
|
526
|
+
inputRecords.push({
|
|
527
|
+
path: input.path,
|
|
528
|
+
kind: input.kind,
|
|
529
|
+
sha256,
|
|
530
|
+
bytes,
|
|
531
|
+
mtimeMs,
|
|
532
|
+
sessionId: parsed.sessionId,
|
|
533
|
+
events: parsed.events.length,
|
|
534
|
+
textEvents: entries.length,
|
|
535
|
+
entries: added,
|
|
536
|
+
reused: false,
|
|
537
|
+
...parsed.extra,
|
|
538
|
+
});
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
stats.entryCount = lines.length;
|
|
542
|
+
stats.duplicatesDropped = Math.max(0, stats.textEvents - stats.entryCount);
|
|
543
|
+
|
|
544
|
+
const indexResult = writeIndexLines({ lines, indexPath, dryRun });
|
|
545
|
+
const manifest = {
|
|
546
|
+
schema: ARCHIVE_DIGEST_SCHEMA,
|
|
547
|
+
builtAt: new Date().toISOString(),
|
|
548
|
+
memoryRoot,
|
|
549
|
+
sessionsRoot,
|
|
550
|
+
outDir,
|
|
551
|
+
incremental,
|
|
552
|
+
indexSha256: indexResult.sha256,
|
|
553
|
+
indexBytes: indexResult.bytes,
|
|
554
|
+
entryCount: stats.entryCount,
|
|
555
|
+
inputs: inputRecords,
|
|
556
|
+
stats: { ...stats, elapsedMs: Date.now() - started },
|
|
557
|
+
};
|
|
558
|
+
if (!dryRun) writeJsonAtomic(manifestPath, manifest);
|
|
559
|
+
|
|
560
|
+
return {
|
|
561
|
+
schema: ARCHIVE_DIGEST_SCHEMA,
|
|
562
|
+
memoryRoot,
|
|
563
|
+
sessionsRoot,
|
|
564
|
+
outDir,
|
|
565
|
+
dryRun,
|
|
566
|
+
incremental,
|
|
567
|
+
index: {
|
|
568
|
+
path: indexPath,
|
|
569
|
+
bytes: indexResult.bytes,
|
|
570
|
+
sha256: indexResult.sha256,
|
|
571
|
+
entryCount: stats.entryCount,
|
|
572
|
+
written: indexResult.written,
|
|
573
|
+
},
|
|
574
|
+
manifest: { path: manifestPath, written: !dryRun },
|
|
575
|
+
inputs: inputRecords,
|
|
576
|
+
stats: { ...stats, elapsedMs: Date.now() - started },
|
|
577
|
+
};
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
// ---------------------------------------------------------------------------
|
|
581
|
+
// CLI
|
|
582
|
+
// ---------------------------------------------------------------------------
|
|
583
|
+
|
|
584
|
+
const USAGE = `用法: node scripts/archive-digest-build.mjs [选项]
|
|
585
|
+
--memory-root <dir> 长活记忆根(读 .longlive/hot-truncate/*.jsonl)
|
|
586
|
+
--sessions-root <dir> 会话日志根(默认 <DSH_HOME>/sessions)
|
|
587
|
+
--out <dir> 输出目录(默认 <memory-root>/.longlive/archive-digest)
|
|
588
|
+
--incremental 复用 sha256 未变的前缀输入(与全量构建等价)
|
|
589
|
+
--dry-run 只扫描统计,不写任何文件
|
|
590
|
+
--json 以 JSON 打印 receipt
|
|
591
|
+
--help 显示本帮助`;
|
|
592
|
+
|
|
593
|
+
function parseCliArgs(argv) {
|
|
594
|
+
const args = {
|
|
595
|
+
memoryRoot: '',
|
|
596
|
+
sessionsRoot: '',
|
|
597
|
+
outDir: '',
|
|
598
|
+
incremental: false,
|
|
599
|
+
dryRun: false,
|
|
600
|
+
json: false,
|
|
601
|
+
help: false,
|
|
602
|
+
};
|
|
603
|
+
const valueFlags = new Map([
|
|
604
|
+
['--memory-root', 'memoryRoot'],
|
|
605
|
+
['--sessions-root', 'sessionsRoot'],
|
|
606
|
+
['--out', 'outDir'],
|
|
607
|
+
]);
|
|
608
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
609
|
+
const arg = argv[i];
|
|
610
|
+
if (valueFlags.has(arg)) {
|
|
611
|
+
const value = argv[i + 1];
|
|
612
|
+
if (typeof value !== 'string' || value === '') throw new Error(`${arg} needs a value`);
|
|
613
|
+
args[valueFlags.get(arg)] = value;
|
|
614
|
+
i += 1;
|
|
615
|
+
continue;
|
|
616
|
+
}
|
|
617
|
+
if (arg === '--incremental') args.incremental = true;
|
|
618
|
+
else if (arg === '--dry-run') args.dryRun = true;
|
|
619
|
+
else if (arg === '--json') args.json = true;
|
|
620
|
+
else if (arg === '--help' || arg === '-h') args.help = true;
|
|
621
|
+
else throw new Error(`unknown argument: ${arg}`);
|
|
622
|
+
}
|
|
623
|
+
return args;
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
function printHuman(receipt) {
|
|
627
|
+
const { stats } = receipt;
|
|
628
|
+
console.log(`[archive-digest-build] out=${receipt.outDir}`);
|
|
629
|
+
console.log(`[archive-digest-build] inputs=${stats.inputs} (archive=${stats.archives} hot-truncate=${stats.hotTruncate}) ` +
|
|
630
|
+
`parsed=${stats.inputsParsed} reused=${stats.inputsReused} failed=${stats.inputsFailed}`);
|
|
631
|
+
console.log(`[archive-digest-build] events=${stats.eventsScanned} textEvents=${stats.textEvents} ` +
|
|
632
|
+
`entries=${stats.entryCount} duplicatesDropped=${stats.duplicatesDropped}`);
|
|
633
|
+
console.log(`[archive-digest-build] index bytes=${receipt.index.bytes} sha256=${receipt.index.sha256} ` +
|
|
634
|
+
`written=${receipt.index.written} elapsed=${stats.elapsedMs}ms`);
|
|
635
|
+
if (receipt.dryRun) console.log('[archive-digest-build] dry-run: nothing written');
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
async function main(argv = process.argv.slice(2)) {
|
|
639
|
+
const args = parseCliArgs(argv);
|
|
640
|
+
if (args.help) {
|
|
641
|
+
console.log(USAGE);
|
|
642
|
+
return 0;
|
|
643
|
+
}
|
|
644
|
+
const memoryRoot = path.resolve(args.memoryRoot !== '' ? args.memoryRoot : defaultMemoryRoot());
|
|
645
|
+
const sessionsRoot = path.resolve(args.sessionsRoot !== '' ? args.sessionsRoot : defaultSessionsRoot());
|
|
646
|
+
const receipt = await buildArchiveDigest({
|
|
647
|
+
memoryRoot,
|
|
648
|
+
sessionsRoot,
|
|
649
|
+
outDir: args.outDir,
|
|
650
|
+
incremental: args.incremental,
|
|
651
|
+
dryRun: args.dryRun,
|
|
652
|
+
});
|
|
653
|
+
if (args.json) console.log(JSON.stringify(receipt, null, 2));
|
|
654
|
+
else printHuman(receipt);
|
|
655
|
+
return 0;
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
const isMain = typeof process.argv[1] === 'string' && process.argv[1] !== ''
|
|
659
|
+
&& pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url;
|
|
660
|
+
|
|
661
|
+
if (isMain) {
|
|
662
|
+
main().then((code) => {
|
|
663
|
+
process.exitCode = code;
|
|
664
|
+
}).catch((error) => {
|
|
665
|
+
console.error(`[archive-digest-build] FAILED: ${error?.stack ?? error}`);
|
|
666
|
+
process.exitCode = 1;
|
|
667
|
+
});
|
|
668
|
+
}
|