@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,433 @@
|
|
|
1
|
+
// src/memory/records.js — M2-B 扩展 / v2.6.4 §14.1:records 数据治理最小集
|
|
2
|
+
//
|
|
3
|
+
// 每条机器断言(records.jsonl)在原有字段上增加:
|
|
4
|
+
// evidence[]{anchorId, sha256, excerptRef, verifiedAt} // 0..n,锚点引用
|
|
5
|
+
// sourceTier ∈ user|host|agent|plugin // 写入来源分层
|
|
6
|
+
// conflict/conflict_with[] // 同 subject 互斥断言标记
|
|
7
|
+
// state ∈ active|superseded|forgotten|archived|restored|unverified
|
|
8
|
+
//
|
|
9
|
+
// 铁律:
|
|
10
|
+
// * 旧 records 缺字段 → 读时默认 evidence=[] / sourceTier='agent' / state 由 status 推导,不崩;
|
|
11
|
+
// * 写时非法 sourceTier → 拒收 `E_SOURCE_TIER`(读时非法值降级 agent 并标记 tierDefaulted);
|
|
12
|
+
// * 同 subject 互斥(正反极性,或同 attribute 不同 value)→ 两条都标 conflict + conflict_with;
|
|
13
|
+
// 回忆候选返回 conflicts[],**不静默选一个**;
|
|
14
|
+
// * 读审计:每次 recall/evidence 调用写 `.longlive/recall/log.jsonl` 一行,含 recordId(行数=调用数)。
|
|
15
|
+
//
|
|
16
|
+
// 纯文件模块(不依赖 SQLite/宿主),可被 #17 只读路由与 M2-C 召回共用。
|
|
17
|
+
|
|
18
|
+
import crypto from 'node:crypto';
|
|
19
|
+
import fs from 'node:fs';
|
|
20
|
+
import path from 'node:path';
|
|
21
|
+
|
|
22
|
+
import { isNegativeConclusion } from './cards.js';
|
|
23
|
+
import { appendJsonLine } from '../util/append-store.js';
|
|
24
|
+
|
|
25
|
+
export const RECORDS_SCHEMA = 'records/v1';
|
|
26
|
+
export const SOURCE_TIERS = Object.freeze(['user', 'host', 'agent', 'plugin']);
|
|
27
|
+
export const RECORD_STATES = Object.freeze(['active', 'superseded', 'forgotten', 'archived', 'restored', 'unverified']);
|
|
28
|
+
export const DEFAULT_SOURCE_TIER = 'agent';
|
|
29
|
+
export const AUDIT_SCHEMA = 'recall-log/v1';
|
|
30
|
+
|
|
31
|
+
export class RecordsError extends Error {
|
|
32
|
+
constructor(code, message) {
|
|
33
|
+
super(message);
|
|
34
|
+
this.name = 'RecordsError';
|
|
35
|
+
this.code = code;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function recordsPathOf(memoryRoot) {
|
|
40
|
+
return path.join(path.resolve(String(memoryRoot ?? '')), '.longlive', 'records.jsonl');
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function recallLogPathOf(memoryRoot) {
|
|
44
|
+
return path.join(path.resolve(String(memoryRoot ?? '')), '.longlive', 'recall', 'log.jsonl');
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function sha256Hex(text) {
|
|
48
|
+
return crypto.createHash('sha256').update(text, 'utf8').digest('hex');
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** R1 anchorId 规则(确定性、索引重建后不变)。 */
|
|
52
|
+
export function anchorIdOf(anchor) {
|
|
53
|
+
if (!anchor || typeof anchor !== 'object') return null;
|
|
54
|
+
if (anchor.kind === 'file_line') {
|
|
55
|
+
return `anc_${sha256Hex(`file|${anchor.rel}|${anchor.lineStart ?? 1}`).slice(0, 16)}`;
|
|
56
|
+
}
|
|
57
|
+
return `anc_${sha256Hex(`${anchor.sessionId ?? ''}|${anchor.turn ?? ''}|${anchor.seqStart ?? ''}`).slice(0, 16)}`;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Build evidence[] entries from anchors (0..n). */
|
|
61
|
+
export function evidenceFromAnchors(anchors, { verifiedAt = null } = {}) {
|
|
62
|
+
if (!Array.isArray(anchors)) return [];
|
|
63
|
+
return anchors
|
|
64
|
+
.filter((anchor) => anchor && typeof anchor === 'object')
|
|
65
|
+
.map((anchor) => ({
|
|
66
|
+
anchorId: anchor.anchorId ?? anchorIdOf(anchor),
|
|
67
|
+
sha256: anchor.digest ?? anchor.fileSha ?? null,
|
|
68
|
+
excerptRef: anchor.kind === 'file_line'
|
|
69
|
+
? `file:${anchor.rel}:${anchor.lineStart ?? 1}-${anchor.lineEnd ?? anchor.lineStart ?? 1}`
|
|
70
|
+
: `session:${anchor.sessionId ?? ''}#turn${anchor.turn ?? ''}`,
|
|
71
|
+
verifiedAt,
|
|
72
|
+
}))
|
|
73
|
+
.filter((entry) => typeof entry.anchorId === 'string' && entry.anchorId !== '');
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Write-path validation: invalid tier throws (no silent write). */
|
|
77
|
+
export function assertSourceTier(value, fallback = DEFAULT_SOURCE_TIER) {
|
|
78
|
+
if (value === undefined || value === null || value === '') return fallback;
|
|
79
|
+
if (!SOURCE_TIERS.includes(value)) throw new RecordsError('E_SOURCE_TIER', `sourceTier 非法:${String(value)}(允许 ${SOURCE_TIERS.join('|')})`);
|
|
80
|
+
return value;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Read-path normalization: never throws, defaults are explicit. */
|
|
84
|
+
export function normalizeSourceTier(value, fallback = DEFAULT_SOURCE_TIER) {
|
|
85
|
+
if (SOURCE_TIERS.includes(value)) return { sourceTier: value, tierDefaulted: false };
|
|
86
|
+
return { sourceTier: fallback, tierDefaulted: value !== undefined && value !== null && value !== '' };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function normalizeState(row) {
|
|
90
|
+
if (RECORD_STATES.includes(row?.state)) return row.state;
|
|
91
|
+
const status = row?.status;
|
|
92
|
+
if (status === 'superseded' || status === 'forgotten' || status === 'archived' || status === 'restored') return status;
|
|
93
|
+
return 'active';
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Read-side normalization (backward compatible with 1.6.8 records). */
|
|
97
|
+
export const ANCHOR_ID_RE = /^anc_[0-9a-f]{16}$/;
|
|
98
|
+
export const SHA256_RE = /^[0-9a-f]{64}$/;
|
|
99
|
+
|
|
100
|
+
const MUTEX_VALUE_GROUPS = Object.freeze([
|
|
101
|
+
Object.freeze(['快速', '安全']),
|
|
102
|
+
Object.freeze(['allow', 'deny']),
|
|
103
|
+
Object.freeze(['允许', '禁止']),
|
|
104
|
+
Object.freeze(['启用', '禁用']),
|
|
105
|
+
]);
|
|
106
|
+
|
|
107
|
+
/** NFKC normalize: full-width digits/quotes/space folded (EA-03). */
|
|
108
|
+
export function normalizeText(value) {
|
|
109
|
+
return String(value ?? '').normalize('NFKC').replace(/[\u3000\s]+/g, ' ').trim();
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Structural validity of one evidence entry (EA-01: fake anchors are invalid). */
|
|
113
|
+
export function validateEvidenceEntry(entry) {
|
|
114
|
+
if (!entry || typeof entry !== 'object') return { valid: false, code: 'E_EVIDENCE_NOT_OBJECT' };
|
|
115
|
+
if (typeof entry.anchorId !== 'string' || !ANCHOR_ID_RE.test(entry.anchorId)) return { valid: false, code: 'E_ANCHOR_ID' };
|
|
116
|
+
if (typeof entry.sha256 !== 'string' || !SHA256_RE.test(entry.sha256)) return { valid: false, code: 'E_SHA256' };
|
|
117
|
+
if (typeof entry.excerptRef !== 'string' || entry.excerptRef.trim() === '') return { valid: false, code: 'E_EXCERPT_REF' };
|
|
118
|
+
return { valid: true, code: 'OK' };
|
|
119
|
+
}
|
|
120
|
+
export function normalizeRecord(row) {
|
|
121
|
+
const value = row && typeof row === 'object' ? row : {};
|
|
122
|
+
const tier = normalizeSourceTier(value.sourceTier);
|
|
123
|
+
const evidence = Array.isArray(value.evidence)
|
|
124
|
+
? value.evidence.filter((entry) => entry && typeof entry === 'object').map((entry) => {
|
|
125
|
+
const validity = validateEvidenceEntry(entry);
|
|
126
|
+
return {
|
|
127
|
+
anchorId: typeof entry.anchorId === 'string' ? entry.anchorId : null,
|
|
128
|
+
sha256: typeof entry.sha256 === 'string' ? entry.sha256 : null,
|
|
129
|
+
excerptRef: typeof entry.excerptRef === 'string' ? entry.excerptRef : null,
|
|
130
|
+
verifiedAt: entry.verifiedAt ?? null,
|
|
131
|
+
valid: validity.valid,
|
|
132
|
+
invalidCode: validity.valid ? null : validity.code,
|
|
133
|
+
};
|
|
134
|
+
})
|
|
135
|
+
: [];
|
|
136
|
+
return {
|
|
137
|
+
id: typeof value.id === 'string' ? value.id : null,
|
|
138
|
+
kind: typeof value.kind === 'string' ? value.kind : 'fact',
|
|
139
|
+
content: typeof value.content === 'string' ? value.content : '',
|
|
140
|
+
subject: typeof value.subject === 'string' && value.subject.trim() !== '' ? value.subject : null,
|
|
141
|
+
attribute: typeof value.attribute === 'string' ? value.attribute : null,
|
|
142
|
+
value: value.value !== undefined ? value.value : null,
|
|
143
|
+
project: value.project ?? null,
|
|
144
|
+
salience: Number.isInteger(value.salience) ? value.salience : 3,
|
|
145
|
+
importance: typeof value.importance === 'number' ? value.importance : 0.5,
|
|
146
|
+
state: normalizeState(value),
|
|
147
|
+
createdAt: value.createdAt ?? null,
|
|
148
|
+
lastUsed: value.lastUsed ?? null,
|
|
149
|
+
useCount: Number.isInteger(value.useCount) ? value.useCount : 0,
|
|
150
|
+
anchors: Array.isArray(value.anchors) ? value.anchors : [],
|
|
151
|
+
evidence,
|
|
152
|
+
sourceTier: tier.sourceTier,
|
|
153
|
+
tierDefaulted: tier.tierDefaulted,
|
|
154
|
+
conflict: value.conflict === true,
|
|
155
|
+
conflict_with: Array.isArray(value.conflict_with) ? value.conflict_with : [],
|
|
156
|
+
supersedes: Array.isArray(value.supersedes) ? value.supersedes : [],
|
|
157
|
+
supersededBy: value.supersededBy ?? null,
|
|
158
|
+
audit: value.audit && typeof value.audit === 'object' ? value.audit : {},
|
|
159
|
+
// C3 扩展:无证据 / 证据结构非法(伪造 anchorId/sha256/excerptRef)=> unverified。
|
|
160
|
+
unverified: evidence.length === 0 || evidence.some((entry) => entry.valid !== true),
|
|
161
|
+
evidenceValid: evidence.length > 0 && evidence.every((entry) => entry.valid === true),
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function subjectKey(record) {
|
|
166
|
+
const compact = (value) => normalizeText(value).toLowerCase().replace(/\s+/g, '');
|
|
167
|
+
const subject = record.subject;
|
|
168
|
+
if (subject && typeof subject === 'object') {
|
|
169
|
+
const entity = compact(subject.entity);
|
|
170
|
+
const attribute = compact(subject.attribute);
|
|
171
|
+
if (entity === '') return null;
|
|
172
|
+
return attribute === '' ? entity : entity + '::' + attribute;
|
|
173
|
+
}
|
|
174
|
+
const raw = subject ?? record.attribute ?? null;
|
|
175
|
+
const normalized = compact(raw);
|
|
176
|
+
return normalized === '' ? null : normalized;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function valueTokens(value) {
|
|
180
|
+
return String(value ?? '').match(/\d+(?:\.\d+)*|[A-Za-z]+/g) ?? [];
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function attributeOf(entry) {
|
|
184
|
+
if (typeof entry?.attribute === 'string' && entry.attribute.trim() !== '') return entry.attribute;
|
|
185
|
+
if (entry?.subject && typeof entry.subject === 'object' && typeof entry.subject.attribute === 'string') return entry.subject.attribute;
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function sameAttributeDifferentValue(a, b) {
|
|
190
|
+
const attrA = attributeOf(a);
|
|
191
|
+
const attrB = attributeOf(b);
|
|
192
|
+
if (typeof attrA !== 'string' || typeof attrB !== 'string') return false;
|
|
193
|
+
if (normalizeText(attrA).toLowerCase() !== normalizeText(attrB).toLowerCase()) return false;
|
|
194
|
+
const left = normalizeText(a.value ?? a.content).toLowerCase();
|
|
195
|
+
const right = normalizeText(b.value ?? b.content).toLowerCase();
|
|
196
|
+
return left !== right;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Mutex value groups (EA-03): same subject + one token from opposite members => conflict. */
|
|
200
|
+
function mutexValueConflict(a, b) {
|
|
201
|
+
const left = normalizeText(a.content + ' ' + (a.value ?? '')).toLowerCase();
|
|
202
|
+
const right = normalizeText(b.content + ' ' + (b.value ?? '')).toLowerCase();
|
|
203
|
+
for (const group of MUTEX_VALUE_GROUPS) {
|
|
204
|
+
const leftHas = group.filter((token) => left.includes(token.toLowerCase()));
|
|
205
|
+
const rightHas = group.filter((token) => right.includes(token.toLowerCase()));
|
|
206
|
+
if (leftHas.length === 0 || rightHas.length === 0) continue;
|
|
207
|
+
if (!leftHas.some((token) => rightHas.includes(token))) return true;
|
|
208
|
+
}
|
|
209
|
+
return false;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Detect mutually exclusive assertions (pure; no disk IO).
|
|
214
|
+
* Returns { conflicts:[{idA,idB,subject,why}], byId:Map<id,string[]> }.
|
|
215
|
+
*/
|
|
216
|
+
export function detectRecordConflicts(records) {
|
|
217
|
+
const list = (Array.isArray(records) ? records : []).filter((record) => record && typeof record.id === 'string'
|
|
218
|
+
&& record.state !== 'superseded' && record.state !== 'forgotten');
|
|
219
|
+
const bySubject = new Map();
|
|
220
|
+
for (const record of list) {
|
|
221
|
+
const key = subjectKey(record);
|
|
222
|
+
if (key === null) continue;
|
|
223
|
+
if (!bySubject.has(key)) bySubject.set(key, []);
|
|
224
|
+
bySubject.get(key).push(record);
|
|
225
|
+
}
|
|
226
|
+
const conflicts = [];
|
|
227
|
+
const byId = new Map();
|
|
228
|
+
for (const [subject, group] of bySubject) {
|
|
229
|
+
for (let i = 0; i < group.length; i += 1) {
|
|
230
|
+
for (let j = i + 1; j < group.length; j += 1) {
|
|
231
|
+
const a = group[i];
|
|
232
|
+
const b = group[j];
|
|
233
|
+
if (a.supersedes?.includes(b.id) || b.supersedes?.includes(a.id)) continue;
|
|
234
|
+
if (a.supersededBy === b.id || b.supersededBy === a.id) continue;
|
|
235
|
+
const opposite = isNegativeConclusion(normalizeText(a.content)) !== isNegativeConclusion(normalizeText(b.content));
|
|
236
|
+
const differentValue = sameAttributeDifferentValue(a, b);
|
|
237
|
+
const mutex = mutexValueConflict(a, b);
|
|
238
|
+
if (!opposite && !differentValue && !mutex) continue;
|
|
239
|
+
const why = opposite ? 'opposite-polarity' : (differentValue ? 'same-attribute-different-value' : 'mutex-value-group');
|
|
240
|
+
conflicts.push({ idA: a.id, idB: b.id, subject, why });
|
|
241
|
+
if (!byId.has(a.id)) byId.set(a.id, []);
|
|
242
|
+
if (!byId.has(b.id)) byId.set(b.id, []);
|
|
243
|
+
byId.get(a.id).push(b.id);
|
|
244
|
+
byId.get(b.id).push(a.id);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
return { conflicts, byId };
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** Read all records (read-only) and compute conflicts/unverified/state. */
|
|
252
|
+
export function listRecords({ memoryRoot, limit = 200 } = {}) {
|
|
253
|
+
const file = recordsPathOf(memoryRoot);
|
|
254
|
+
const items = [];
|
|
255
|
+
const bad = [];
|
|
256
|
+
let present = false;
|
|
257
|
+
let text = '';
|
|
258
|
+
try {
|
|
259
|
+
text = fs.readFileSync(file, 'utf8');
|
|
260
|
+
present = true;
|
|
261
|
+
} catch {
|
|
262
|
+
text = '';
|
|
263
|
+
}
|
|
264
|
+
for (const line of text.split('\n')) {
|
|
265
|
+
if (line.trim() === '') continue;
|
|
266
|
+
let row = null;
|
|
267
|
+
try {
|
|
268
|
+
row = JSON.parse(line);
|
|
269
|
+
} catch {
|
|
270
|
+
bad.push(line.slice(0, 120));
|
|
271
|
+
continue;
|
|
272
|
+
}
|
|
273
|
+
items.push(normalizeRecord(row));
|
|
274
|
+
}
|
|
275
|
+
const { conflicts, byId } = detectRecordConflicts(items);
|
|
276
|
+
for (const item of items) {
|
|
277
|
+
const ids = byId.get(item.id) ?? [];
|
|
278
|
+
item.conflict = ids.length > 0;
|
|
279
|
+
item.conflict_with = ids;
|
|
280
|
+
}
|
|
281
|
+
const limited = Number.isInteger(limit) && limit > 0 ? items.slice(-limit) : items;
|
|
282
|
+
return {
|
|
283
|
+
schema: RECORDS_SCHEMA,
|
|
284
|
+
present,
|
|
285
|
+
items: limited,
|
|
286
|
+
total: items.length,
|
|
287
|
+
conflicts,
|
|
288
|
+
unverified: items.filter((item) => item.unverified).length,
|
|
289
|
+
badLines: bad,
|
|
290
|
+
file,
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** Append one audit line (one per recall/evidence call). Never throws. */
|
|
295
|
+
export function appendRecallAudit({ memoryRoot, now = () => new Date(), query = '', recordId = null, recordIds = [], hit = false, conflicts = [], timings = null, source = 'records-query', extra = {} } = {}) {
|
|
296
|
+
const value = typeof now === 'function' ? now() : new Date();
|
|
297
|
+
const at = (value instanceof Date ? value : new Date(value)).toISOString();
|
|
298
|
+
const line = {
|
|
299
|
+
schema: AUDIT_SCHEMA,
|
|
300
|
+
at,
|
|
301
|
+
query: String(query ?? '').slice(0, 500),
|
|
302
|
+
hit: hit === true,
|
|
303
|
+
recordId: recordId ?? (recordIds.length > 0 ? recordIds[0] : null),
|
|
304
|
+
recordIds: Array.isArray(recordIds) ? recordIds.slice(0, 50) : [],
|
|
305
|
+
conflicts: Array.isArray(conflicts) ? conflicts.slice(0, 20) : [],
|
|
306
|
+
source,
|
|
307
|
+
timings: timings && typeof timings === 'object' ? timings : null,
|
|
308
|
+
...extra,
|
|
309
|
+
};
|
|
310
|
+
const file = recallLogPathOf(memoryRoot);
|
|
311
|
+
const written = appendJsonLine({
|
|
312
|
+
file,
|
|
313
|
+
row: line,
|
|
314
|
+
label: 'recall-log',
|
|
315
|
+
healthRoot: memoryRoot,
|
|
316
|
+
now: typeof now === 'function' ? now : undefined,
|
|
317
|
+
quarantineDir: path.join(path.resolve(String(memoryRoot ?? '')), '.longlive', 'quarantine'),
|
|
318
|
+
});
|
|
319
|
+
return { ok: written.ok, line, file, bytes: written.bytes, code: written.code, error: written.error };
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function queryTokens(query) {
|
|
323
|
+
const text = String(query ?? '').toLowerCase();
|
|
324
|
+
const tokens = new Set(text.match(/[a-z0-9]+|[\u3400-\u4dbf\u4e00-\u9fff]{2,4}/g) ?? []);
|
|
325
|
+
for (const run of text.match(/[\u3400-\u4dbf\u4e00-\u9fff]+/g) ?? []) {
|
|
326
|
+
const chars = Array.from(run);
|
|
327
|
+
for (let i = 0; i + 1 < chars.length; i += 1) tokens.add(chars[i] + chars[i + 1]);
|
|
328
|
+
}
|
|
329
|
+
return [...tokens];
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* Minimal records recall (basis for M2-C memory_recall_v2):
|
|
334
|
+
* keyword/bigram match over content, returns candidates + conflicts[] + unverified flags,
|
|
335
|
+
* and writes exactly one audit line per call (hit or not).
|
|
336
|
+
*/
|
|
337
|
+
export function queryRecords({ memoryRoot, query = '', limit = 10, now = () => new Date(), source = 'records-query' } = {}) {
|
|
338
|
+
const started = Date.now();
|
|
339
|
+
const listed = listRecords({ memoryRoot, limit: 500 });
|
|
340
|
+
const tokens = queryTokens(query);
|
|
341
|
+
const scored = listed.items
|
|
342
|
+
.filter((item) => item.state === 'active')
|
|
343
|
+
.map((item) => {
|
|
344
|
+
const haystack = `${item.content} ${item.subject ?? ''} ${item.kind}`.toLowerCase();
|
|
345
|
+
let score = 0;
|
|
346
|
+
for (const token of tokens) if (haystack.includes(token)) score += 1;
|
|
347
|
+
return { item, score };
|
|
348
|
+
})
|
|
349
|
+
.filter((entry) => tokens.length === 0 || entry.score > 0)
|
|
350
|
+
.sort((a, b) => b.score - a.score || String(b.item.createdAt ?? '').localeCompare(String(a.item.createdAt ?? '')));
|
|
351
|
+
const items = scored.slice(0, limit).map((entry) => entry.item);
|
|
352
|
+
const recordIds = items.map((item) => item.id).filter(Boolean);
|
|
353
|
+
const conflictIds = new Set([...items.flatMap((item) => item.conflict_with), ...items.map((item) => item.id)]);
|
|
354
|
+
const conflicts = listed.conflicts.filter((entry) => conflictIds.has(entry.idA) || conflictIds.has(entry.idB));
|
|
355
|
+
appendRecallAudit({
|
|
356
|
+
memoryRoot,
|
|
357
|
+
now,
|
|
358
|
+
query,
|
|
359
|
+
recordId: recordIds[0] ?? null,
|
|
360
|
+
recordIds,
|
|
361
|
+
hit: items.length > 0,
|
|
362
|
+
conflicts,
|
|
363
|
+
timings: { totalMs: Date.now() - started },
|
|
364
|
+
source,
|
|
365
|
+
});
|
|
366
|
+
return {
|
|
367
|
+
schema: RECORDS_SCHEMA,
|
|
368
|
+
query: String(query ?? ''),
|
|
369
|
+
items,
|
|
370
|
+
total: items.length,
|
|
371
|
+
conflicts,
|
|
372
|
+
unverified: items.filter((item) => item.unverified).length,
|
|
373
|
+
code: items.length > 0 ? 'OK' : 'E_RECORDS_NO_MATCH',
|
|
374
|
+
};
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/** Recompute evidence liveness; returns a copy marked unverified when evidence is gone. */
|
|
378
|
+
export function verifyRecordEvidence(record, verifyOne) {
|
|
379
|
+
const base = normalizeRecord(record);
|
|
380
|
+
const results = base.evidence.map((entry) => {
|
|
381
|
+
if (entry.valid !== true) return { ...entry, state: 'invalid' };
|
|
382
|
+
let state = 'missing';
|
|
383
|
+
try {
|
|
384
|
+
state = typeof verifyOne === 'function' ? verifyOne(entry) : 'missing';
|
|
385
|
+
} catch {
|
|
386
|
+
state = 'missing';
|
|
387
|
+
}
|
|
388
|
+
return { ...entry, state };
|
|
389
|
+
});
|
|
390
|
+
const unverified = base.evidence.length === 0 || results.some((entry) => entry.state !== 'live');
|
|
391
|
+
return { ...base, evidenceVerified: results, unverified };
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/** Derive excerptRef from an anchor object (session_turn / file_line). */
|
|
395
|
+
export function excerptRefOf(anchor) {
|
|
396
|
+
if (!anchor || typeof anchor !== 'object') return null;
|
|
397
|
+
if (anchor.kind === 'file_line') return 'file:' + anchor.rel + ':' + (anchor.lineStart ?? 1) + '-' + (anchor.lineEnd ?? anchor.lineStart ?? 1);
|
|
398
|
+
if (anchor.sessionId !== undefined && anchor.turn !== undefined) return 'session:' + anchor.sessionId + '#turn' + anchor.turn;
|
|
399
|
+
return null;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/** Write-path evidence evaluation (EA-01/EA-02): callers cannot self-declare verified. */
|
|
403
|
+
export function evaluateEvidenceForWrite(anchors, options = {}) {
|
|
404
|
+
const verifiedAt = options.verifiedAt ?? null;
|
|
405
|
+
const entries = (Array.isArray(anchors) ? anchors : []).map((anchor) => ({
|
|
406
|
+
anchorId: anchor?.anchorId ?? anchorIdOf(anchor),
|
|
407
|
+
sha256: anchor?.digest ?? anchor?.fileSha ?? null,
|
|
408
|
+
excerptRef: excerptRefOf(anchor),
|
|
409
|
+
verifiedAt,
|
|
410
|
+
}));
|
|
411
|
+
const checks = entries.map((entry) => {
|
|
412
|
+
const validity = validateEvidenceEntry(entry);
|
|
413
|
+
return { ...entry, valid: validity.valid, invalidCode: validity.valid ? null : validity.code };
|
|
414
|
+
});
|
|
415
|
+
const results = checks.map((entry) => {
|
|
416
|
+
if (entry.valid !== true) return { ...entry, state: 'invalid' };
|
|
417
|
+
let state = 'unverified';
|
|
418
|
+
try {
|
|
419
|
+
state = typeof options.verifyOne === 'function' ? options.verifyOne(entry) : 'unverified';
|
|
420
|
+
} catch {
|
|
421
|
+
state = 'missing';
|
|
422
|
+
}
|
|
423
|
+
return { ...entry, state };
|
|
424
|
+
});
|
|
425
|
+
return {
|
|
426
|
+
evidence: checks,
|
|
427
|
+
verified: checks.length > 0 && checks.every((entry) => entry.valid),
|
|
428
|
+
verifiedLive: results.length > 0 && results.every((entry) => entry.state === 'live'),
|
|
429
|
+
reasons: checks.filter((entry) => entry.valid !== true).map((entry) => entry.invalidCode),
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
export { sha256Hex };
|