@jjh32456/dsh-longlive 1.6.7 → 1.8.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 +70 -1508
- package/LICENSE +1 -1
- package/QUICKSTART.md +34 -13
- package/README.en.md +18 -7
- package/README.md +34 -9
- package/SPEC.md +5 -5
- package/cordis.patch.yml +23 -9
- package/docs/ANSWER-GUARD.md +92 -0
- package/docs/ARCHITECTURE.md +4 -3
- package/docs/AUTO-RECALL-WIRING.md +1 -1
- package/docs/AUTO-RECALL.md +15 -9
- package/docs/CONFIG.md +168 -35
- package/docs/ERRORS.md +17 -5
- package/docs/FAQ.md +7 -7
- package/docs/FEATURES.md +96 -28
- package/docs/MIGRATION-1.6.0.md +2 -2
- package/docs/OPERATIONS.md +6 -6
- package/docs/PANEL-INTEGRATION.md +6 -0
- package/docs/PRIVACY.md +88 -0
- package/docs/QUICKSTART.md +5 -5
- package/docs/README.en.md +4 -2
- package/docs/RESIDENT-WATCHER.md +1 -1
- package/docs/SESSION-WATCH.md +6 -6
- package/docs/TROUBLESHOOTING.md +4 -4
- package/package.json +47 -117
- package/runbook.md +2 -2
- package/scripts/backfill-auto-cards.mjs +98 -0
- package/scripts/install-surgery-task.ps1 +5 -2
- package/scripts/lib/session-watch-fixture.mjs +1 -1
- package/scripts/longlive-doctor.mjs +6 -0
- package/scripts/migrate-180.mjs +163 -0
- package/scripts/recall-index-build.mjs +128 -0
- package/scripts/session-watch-drill.mjs +1 -1
- package/scripts/surgery-run.cmd +1 -1
- package/scripts/unattended-surgery.ps1 +5 -2
- package/scripts/verify-card-anchors.mjs +138 -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 +760 -0
- package/src/activity/model.js +351 -0
- package/src/activity/store.js +644 -0
- package/src/activity/thinking.js +176 -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 +235 -0
- package/src/adapters/registry.js +315 -0
- package/src/answer/audit.js +193 -0
- package/src/answer/evidence.js +30 -0
- package/src/answer/guard.js +1370 -0
- package/src/answer/index.js +1067 -0
- package/src/answer/query.js +111 -0
- package/src/answer/second-hop.mjs +101 -0
- package/src/auto-truncate.js +1 -1
- package/src/config.js +171 -47
- package/src/deps.js +6 -4
- package/src/features.js +182 -6
- package/src/heartbeat.js +156 -23
- package/src/identity/handover.js +52 -1
- package/src/identity/index.js +13 -5
- package/src/identity/inject-position.js +2 -2
- package/src/index.js +97 -7
- package/src/lifecycle/gap-clocks.js +328 -0
- package/src/lifecycle/index.js +269 -0
- package/src/live.js +22 -2
- package/src/memory/activity-capture.js +229 -0
- package/src/memory/anchors.js +194 -0
- package/src/memory/audit-records.js +222 -0
- package/src/memory/auto-cards.js +401 -0
- package/src/memory/capture.js +442 -0
- package/src/memory/card-anchors.js +203 -0
- package/src/memory/conflicts.js +106 -0
- package/src/memory/decay.js +311 -0
- package/src/memory/distill.js +471 -0
- package/src/memory/event-index.js +917 -0
- package/src/memory/evidence-chain.js +295 -0
- package/src/memory/evidence.js +145 -0
- package/src/memory/filter-runner.js +1 -1
- package/src/memory/filter.js +5 -1
- package/src/memory/forget-v2.js +410 -0
- package/src/memory/forget.js +71 -0
- package/src/memory/frames-activation.js +247 -0
- package/src/memory/fts-query.js +174 -0
- package/src/memory/governance.js +604 -0
- package/src/memory/index.js +1 -0
- package/src/memory/l2-gate.js +169 -0
- package/src/memory/lock.js +121 -0
- package/src/memory/migrate.js +139 -0
- package/src/memory/recall-v2.js +223 -0
- package/src/memory/recall.js +65 -2
- package/src/memory/records.js +425 -0
- package/src/memory/retention.js +128 -0
- package/src/memory/review.js +124 -0
- package/src/memory/trust.js +88 -0
- package/src/memory/version-chain.js +264 -0
- package/src/memory/wal.js +137 -0
- package/src/memory/working-frame.js +516 -0
- package/src/metrics/classify.mjs +5 -3
- package/src/metrics/index.mjs +21 -1
- package/src/metrics/prestep-latency.mjs +300 -0
- package/src/metrics/store.mjs +25 -0
- package/src/policy-profile.js +18 -3
- package/src/recall/anaphora.mjs +87 -0
- package/src/recall/cards.mjs +7 -0
- package/src/recall/embedding.mjs +8 -8
- package/src/recall/entities.mjs +112 -0
- package/src/recall/index.js +235 -19
- package/src/recall/inject-order.mjs +10 -8
- package/src/recall/privacy.mjs +105 -16
- package/src/recall/recall-core.mjs +116 -10
- package/src/recall/shared-visibility.js +302 -0
- package/src/recall/time-normalizer.mjs +196 -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 +176 -25
- package/src/router/background/agent-runner.mjs +1 -1
- package/src/router/background/anchor.mjs +1 -1
- package/src/router/background/audit.mjs +2 -2
- package/src/router/background/budget-ledger.mjs +2 -2
- package/src/router/background/host-sim.mjs +1 -1
- package/src/router/background/memory.mjs +4 -4
- package/src/router/background/queue.mjs +1 -1
- package/src/router/background/retry.mjs +1 -1
- package/src/router/background/router.mjs +1 -1
- package/src/router/background/stream.mjs +1 -1
- package/src/router/background/tool-policy.mjs +1 -1
- package/src/router/design-headings.json +5 -5
- package/src/router/face/config.mjs +1 -1
- package/src/router/face/identity.mjs +3 -3
- package/src/router/judge.mjs +8 -7
- package/src/router/policies/generic.json +21 -4
- package/src/router/route.js +109 -22
- package/src/router/router.mjs +10 -6
- package/src/router/routing-rules.json +260 -445
- package/src/router/run-sim.mjs +8 -8
- package/src/router/runtime.js +23 -12
- package/src/router/service/board.mjs +95 -15
- package/src/router/service/config.mjs +5 -5
- package/src/router/service/context.mjs +1 -1
- package/src/router/service/hint.mjs +14 -0
- package/src/router/service/queue.mjs +1 -1
- package/src/router/service/service.mjs +27 -11
- package/src/router/shadow.mjs +4 -3
- package/src/surgery-recovery.js +2 -2
- package/src/tool-output.js +2 -2
- package/src/tools.js +39 -7
- package/src/truncate-visible.js +2 -2
- package/src/ui/actions.js +1312 -0
- package/src/ui/panel-api.js +367 -0
- package/src/ui/panel-auth.js +251 -0
- package/src/ui/panel-integrity.js +243 -0
- package/src/ui/routes-readonly.js +695 -0
- package/src/ui/routes.js +3 -0
- package/docs/DEV.md +0 -279
- package/docs/PRESENCE-BUS-WIRING.md +0 -491
- package/docs/PRESENCE-BUS.md +0 -694
- package/docs/SURGERY.md +0 -186
- package/scripts/mark-core-cards.mjs +0 -289
- package/scripts/pack.mjs +0 -392
- package/scripts/router-proposals.mjs +0 -386
- package/src/router/fixtures/M1.json +0 -16
- package/src/router/fixtures/M2.json +0 -16
- package/src/router/fixtures/M3.json +0 -20
- package/src/router/fixtures/M4.json +0 -20
- package/src/router/fixtures/M5.json +0 -45
- package/src/router/fixtures/M6.json +0 -53
- package/src/router/fixtures/M7.json +0 -46
- package/src/router/fixtures/S1.json +0 -20
- package/src/router/fixtures/S2.json +0 -23
- package/src/router/fixtures/S3.json +0 -20
- package/src/router/fixtures/S4.json +0 -34
- package/src/router/fixtures/S5.json +0 -43
- package/src/router/fixtures/S6.json +0 -47
- package/src/router/fixtures/T1.json +0 -23
- package/src/router/fixtures/T2.json +0 -16
- package/src/router/fixtures/T3.json +0 -19
- package/src/router/fixtures/T4.json +0 -16
- package/src/router/fixtures/X1.json +0 -17
- package/src/router/fixtures/X2.json +0 -20
- package/src/router/gen-design-headings.mjs +0 -107
- package/src/router/policies/owner-rulings-2026-11-03.json +0 -62
- package/test/auto-recall.test.mjs +0 -474
- package/test/auto-truncate.test.mjs +0 -931
- package/test/autobind.test.mjs +0 -385
- package/test/bus.test.mjs +0 -1572
- package/test/cli-guard.test.mjs +0 -198
- package/test/conclusion.test.mjs +0 -408
- package/test/config-schema.test.mjs +0 -204
- package/test/d6-output.test.mjs +0 -194
- package/test/d6.test.mjs +0 -395
- package/test/deps.test.mjs +0 -342
- package/test/doctor-setup.test.mjs +0 -297
- package/test/embedding-recall.test.mjs +0 -347
- package/test/feature-flags.test.mjs +0 -568
- package/test/filter-shadow.test.mjs +0 -170
- package/test/fixtures/baseline-0.8.0-registration.json +0 -556
- package/test/fixtures/d6-header-tools.json +0 -1
- package/test/fixtures/lock-child.mjs +0 -67
- package/test/fixtures/pre-step-container.mjs +0 -100
- package/test/fixtures/privacy-memory/topics/pii-unmarked.md +0 -9
- package/test/fixtures/privacy-memory/topics/secret-local-only.md +0 -11
- package/test/fixtures/profile-session-longlive-config.json +0 -20
- package/test/fixtures/proposal-cas-child.mjs +0 -66
- package/test/host-engine-status.test.mjs +0 -307
- package/test/hot-truncate.test.mjs +0 -1349
- package/test/identity-card-marker.test.mjs +0 -307
- package/test/identity-router/run.mjs +0 -721
- package/test/integration-pre-step.test.mjs +0 -553
- package/test/live.test.mjs +0 -1020
- package/test/maintenance-schedule.test.mjs +0 -538
- package/test/memory.test.mjs +0 -2828
- package/test/metrics.test.mjs +0 -478
- package/test/orchestrator.test.mjs +0 -266
- package/test/p1_probe.mjs +0 -97
- package/test/packaging.test.mjs +0 -182
- package/test/portability.test.mjs +0 -343
- package/test/rc4-regressions.test.mjs +0 -562
- package/test/rc5-regressions.test.mjs +0 -197
- package/test/rc6-chinese.test.mjs +0 -394
- package/test/router-1100/apply-off.test.mjs +0 -175
- package/test/router-1100/budget-reconcile.test.mjs +0 -215
- package/test/router-1100/config-context.test.mjs +0 -211
- package/test/router-1100/helpers.mjs +0 -129
- package/test/router-1100/hint-envelope.test.mjs +0 -150
- package/test/router-1100/lock-crossproc.test.mjs +0 -206
- package/test/router-1100/proposal-cas-crossproc.test.mjs +0 -184
- package/test/router-1100/router-apply.test.mjs +0 -372
- package/test/router-1100/router-fixb.test.mjs +0 -602
- package/test/router-1100/router-proposals.test.mjs +0 -405
- package/test/router-1100/router-queue-lease-wal.test.mjs +0 -355
- package/test/router-1100/router-security-cr.test.mjs +0 -333
- package/test/router-1100/service-lifecycle.test.mjs +0 -220
- package/test/router-1100/tools-contract.test.mjs +0 -164
- package/test/router-1100/turn-reflect-tick.test.mjs +0 -89
- package/test/router-1100/v6-contract.test.mjs +0 -158
- package/test/router-1100/v6b-contract.test.mjs +0 -293
- package/test/router-1100/v6c-contract.test.mjs +0 -249
- package/test/router-1100/wal-rotation.test.mjs +0 -375
- package/test/router-1100/wp1-config.test.mjs +0 -170
- package/test/router-1100/wp1-default-off.test.mjs +0 -77
- package/test/router-1100/wp1-model-status.test.mjs +0 -90
- package/test/router-1100/wp1-status.test.mjs +0 -220
- package/test/router-1100/wp1-tools.test.mjs +0 -146
- package/test/router-1100/wp5-cli.test.mjs +0 -240
- package/test/router-1100/wp5-model-auto.test.mjs +0 -418
- package/test/router-1100/wp6-merge.test.mjs +0 -386
- package/test/router-1100/wp6-wake.test.mjs +0 -502
- package/test/router-background/audit.test.mjs +0 -37
- package/test/router-background/budget-ledger.test.mjs +0 -330
- package/test/router-background/cross-process.test.mjs +0 -222
- package/test/router-background/fixtures/cross-child.mjs +0 -85
- package/test/router-background/fixtures/real-shapes.mjs +0 -239
- package/test/router-background/router.test.mjs +0 -1044
- package/test/router-background/stream-retry.test.mjs +0 -358
- package/test/router-background/tool-agent.test.mjs +0 -384
- package/test/router-face/bridge.test.mjs +0 -169
- package/test/router-face/face.test.mjs +0 -316
- package/test/router-failclosed.test.mjs +0 -466
- package/test/router-identity.test.mjs +0 -384
- package/test/router-l1-l2.contract.test.mjs +0 -1075
- package/test/router-memory-tools.test.mjs +0 -262
- package/test/router-policy.test.mjs +0 -225
- package/test/router-runtime.test.mjs +0 -438
- package/test/router-shadow.test.mjs +0 -287
- package/test/router.test.mjs +0 -903
- package/test/run-rc.mjs +0 -299
- package/test/run.mjs +0 -2469
- package/test/safety-defaults.test.mjs +0 -179
- package/test/seeded-load.test.mjs +0 -436
- package/test/session-original.test.mjs +0 -338
- package/test/surgery-recovery.test.mjs +0 -936
- package/test/t7_drive.mjs +0 -151
- package/test/tool-output.test.mjs +0 -393
- package/test/tool-schema.test.mjs +0 -177
- package/test/tools_contract.test.mjs +0 -716
- package/test/truncate-visible.test.mjs +0 -1150
- package/test/ui-flags.test.mjs +0 -477
- package/test/v4-hardening.test.mjs +0 -427
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
// src/memory/l2-gate.js — M2-D:L1/L2/L3 保真闸 + 保护谓词(fail-safe)
|
|
2
|
+
//
|
|
3
|
+
// 设计依据 MEMORY-RECALL-V2-PROPOSAL §4.1.1/§4.2.1/§4.2.2:
|
|
4
|
+
// * L1 精确(原话/数字/版本/路径/时间):摘要不保证逐字,但必须保留锚点回读入口;
|
|
5
|
+
// * L2 要点(who/what/when/decision/why):重要事件蒸馏后必须 100% 可直接答,
|
|
6
|
+
// 一般事件 ≥90%;不达标就“不要蒸馏”(保持原文粒度),宁多留不误蒸;
|
|
7
|
+
// * L3 大意:深时记忆不许空白。
|
|
8
|
+
// * 保护谓词(fail-safe 闭):protected(x) = kind∈forbid || salience==5 ||
|
|
9
|
+
// status==locked || inProtectedJson(x) || l2GatePass !== true;
|
|
10
|
+
// **只有显式 l2GatePass===true 才放行**,false/undefined/缺字段/缺 manifest 全 protect。
|
|
11
|
+
//
|
|
12
|
+
// 本模块只做纯判定(无 LLM、无网络);写盘由 distill.js / decay.js 负责。
|
|
13
|
+
|
|
14
|
+
import { readProtectionManifest } from './retention.js';
|
|
15
|
+
|
|
16
|
+
export const FORBID_KINDS = Object.freeze([
|
|
17
|
+
'incident', 'decision', 'release', 'rule', 'preference', 'milestone', 'lifecycle', 'noise', 'unknown',
|
|
18
|
+
]);
|
|
19
|
+
export const ALLOW_KINDS = Object.freeze(['daily']);
|
|
20
|
+
|
|
21
|
+
/** Project vocabulary used by extraction/judging (kept in one place; no inference). */
|
|
22
|
+
export const CAUSAL_WORDS = Object.freeze(['因为', '所以', '由于', '原因', '导致', '为了', '因此', 'why']);
|
|
23
|
+
export const EMOTION_WORDS = Object.freeze(['担心', '着急', '急', '哭', '高兴', '兴奋', '难过', '焦虑', '累', '疲惫', '紧迫', '开心', '生气', '害怕', '放心']);
|
|
24
|
+
export const DECISION_WORDS = Object.freeze(['决定', '拍板', '定为', '冻结', '解冻', '取消', '改成', '发布', '完成', '上线', '回滚', '修好', '确认', '通过', '不许', '必须', '禁止']);
|
|
25
|
+
export const INCIDENT_WORDS = Object.freeze(['事故', '崩溃', '失败', '超窗', '卡死', 'ECONNRESET', 'truncat', '异常', '报错', '损坏']);
|
|
26
|
+
export const RULE_WORDS = Object.freeze(['纪律', '铁律', '规矩', '必须', '禁止', '不许']);
|
|
27
|
+
export const RELEASE_WORDS = Object.freeze(['发布', '版本', 'tag', 'npm', 'GitHub', 'commit', 'release', 'v1.', 'v2.', 'v3.']);
|
|
28
|
+
export const PREFERENCE_WORDS = Object.freeze(['偏好', '习惯', '喜欢', '不要', '讨厌', '爱吃']);
|
|
29
|
+
export const NOISE_WORDS = Object.freeze(['重复', '副本', '空操作', 'noop']);
|
|
30
|
+
|
|
31
|
+
export class FidelityGateError extends Error {
|
|
32
|
+
constructor(code, message, details = {}) {
|
|
33
|
+
super(message);
|
|
34
|
+
this.name = 'FidelityGateError';
|
|
35
|
+
this.code = code;
|
|
36
|
+
this.status = code === 'E_DISTILL_PROTECTED' ? 403 : 422;
|
|
37
|
+
this.details = details;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function normalizeForMatch(value) {
|
|
42
|
+
return String(value ?? '')
|
|
43
|
+
.normalize('NFKC')
|
|
44
|
+
.toLowerCase()
|
|
45
|
+
.replace(/[\s\u3000]+/g, ' ')
|
|
46
|
+
.replace(/[,。;:!?、,.!?;:…—–\-_/\\()()[\]{}"'"'`]+/g, '')
|
|
47
|
+
.trim();
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function isForbiddenKind(kind) {
|
|
51
|
+
if (kind === undefined || kind === null || String(kind).trim() === '') return true;
|
|
52
|
+
return FORBID_KINDS.includes(String(kind));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Rule-based candidate kind (§4.2.1); human may confirm later. Unknown text => daily candidate. */
|
|
56
|
+
export function classifyKindV2(text) {
|
|
57
|
+
const value = String(text ?? '');
|
|
58
|
+
const has = (words) => words.some((word) => value.includes(word));
|
|
59
|
+
if (has(NOISE_WORDS) && value.trim().length < 40) return 'noise';
|
|
60
|
+
if (has(INCIDENT_WORDS)) return 'incident';
|
|
61
|
+
if (has(RULE_WORDS)) return 'rule';
|
|
62
|
+
if (has(RELEASE_WORDS)) return 'release';
|
|
63
|
+
if (has(DECISION_WORDS)) return 'decision';
|
|
64
|
+
if (has(PREFERENCE_WORDS)) return 'preference';
|
|
65
|
+
if (value.trim() === '') return 'unknown';
|
|
66
|
+
return 'daily';
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function matchRequirement(field, requirement, text, normalized) {
|
|
70
|
+
if (requirement === undefined || requirement === null) return true; // 未要求,不计入
|
|
71
|
+
if (typeof requirement === 'function') return requirement(text) === true;
|
|
72
|
+
if (requirement === true) {
|
|
73
|
+
if (field === 'why') return CAUSAL_WORDS.some((word) => normalized.includes(normalizeForMatch(word)));
|
|
74
|
+
if (field === 'emotion') return EMOTION_WORDS.some((word) => normalized.includes(normalizeForMatch(word)));
|
|
75
|
+
return normalized.length > 0;
|
|
76
|
+
}
|
|
77
|
+
const list = Array.isArray(requirement) ? requirement : [requirement];
|
|
78
|
+
return list.some((value) => typeof value === 'string'
|
|
79
|
+
&& value !== ''
|
|
80
|
+
&& normalized.includes(normalizeForMatch(value)));
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* judgeL2(distillText, requiredFields) -> {level:'pass'|'partial'|'fail', hits, total, fields}
|
|
85
|
+
* requiredFields 形如 {who:['用户A'], what:['发布'], when:['2026-11-06'], decision:['1.6.8'], why:true}。
|
|
86
|
+
* 只有“有要求”的字段计入分母(null/undefined 跳过);每字段任一要求命中即 HIT。
|
|
87
|
+
*/
|
|
88
|
+
export function judgeL2(text, requiredFields = {}) {
|
|
89
|
+
const normalized = normalizeForMatch(text);
|
|
90
|
+
const fields = {};
|
|
91
|
+
let hits = 0;
|
|
92
|
+
let total = 0;
|
|
93
|
+
for (const [field, requirement] of Object.entries(requiredFields && typeof requiredFields === 'object' ? requiredFields : {})) {
|
|
94
|
+
if (requirement === undefined || requirement === null) continue;
|
|
95
|
+
total += 1;
|
|
96
|
+
const hit = matchRequirement(field, requirement, String(text ?? ''), normalized);
|
|
97
|
+
if (hit) hits += 1;
|
|
98
|
+
fields[field] = { hit, requirement };
|
|
99
|
+
}
|
|
100
|
+
const level = total === 0 ? 'pass' : hits === total ? 'pass' : hits > 0 ? 'partial' : 'fail';
|
|
101
|
+
return { level, hits, total, fields };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Pure protection predicate (§4.2.1 fail-safe). An entity is distillable only when:
|
|
106
|
+
* kind=allow, salience<5, status!=locked, manifest present, and an explicit
|
|
107
|
+
* l2GatePass===true exists (entity or its manifest entry) with no default-protect block.
|
|
108
|
+
*/
|
|
109
|
+
export function protectionOf(entity = {}, { manifest = null } = {}) {
|
|
110
|
+
const reasons = [];
|
|
111
|
+
const kind = entity?.kind;
|
|
112
|
+
if (isForbiddenKind(kind)) reasons.push(kind ? `kind=${kind}` : 'kind-missing');
|
|
113
|
+
if (Number(entity?.salience) >= 5) reasons.push('salience-5');
|
|
114
|
+
if (String(entity?.status ?? 'active') === 'locked') reasons.push('locked');
|
|
115
|
+
const currentManifest = manifest && typeof manifest === 'object' ? manifest : readProtectionManifest(entity?.memoryRoot ?? '');
|
|
116
|
+
if (currentManifest?.present !== true) {
|
|
117
|
+
reasons.push('manifest-missing');
|
|
118
|
+
} else {
|
|
119
|
+
const id = String(entity?.id ?? entity?.rel ?? entity?.path ?? '');
|
|
120
|
+
const hit = Array.isArray(currentManifest.entries)
|
|
121
|
+
? currentManifest.entries.find((entry) => entry.id === id)
|
|
122
|
+
: null;
|
|
123
|
+
if (hit) {
|
|
124
|
+
if (hit.l2GatePass !== true) reasons.push('protected-entry');
|
|
125
|
+
} else if (currentManifest.defaultProtected === true) {
|
|
126
|
+
reasons.push('default-protected');
|
|
127
|
+
} else if (entity?.l2GatePass !== true) {
|
|
128
|
+
reasons.push('l2GatePass-not-true');
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return { protected: reasons.length > 0, reasons };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export function assertDistillable(entity, options = {}) {
|
|
135
|
+
const verdict = protectionOf(entity, options);
|
|
136
|
+
if (verdict.protected) {
|
|
137
|
+
throw new FidelityGateError(
|
|
138
|
+
'E_DISTILL_PROTECTED',
|
|
139
|
+
`保护谓词拒绝蒸馏:${entity?.id ?? entity?.rel ?? 'unknown'}(${verdict.reasons.join(',')})— 保持原文粒度,宁多留不误蒸`,
|
|
140
|
+
verdict,
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
return { ok: true, verdict };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* L2 gate verdict for a distill attempt. Important (protected) events must pass
|
|
148
|
+
* 100%; ordinary events fail the gate only on 'fail' (partial is allowed).
|
|
149
|
+
*/
|
|
150
|
+
export function assertL2Gate({ record, text, requiredFields, important = false }) {
|
|
151
|
+
if (!requiredFields) return { ok: true, skipped: true, level: null };
|
|
152
|
+
const judged = judgeL2(text, requiredFields);
|
|
153
|
+
if (judged.level === 'pass') return { ok: true, verdict: judged };
|
|
154
|
+
if (important) {
|
|
155
|
+
throw new FidelityGateError(
|
|
156
|
+
'E_DISTILL_L2_GATE',
|
|
157
|
+
`重要事件 L2 判定 ${judged.level}(${judged.hits}/${judged.total})→ 禁止蒸馏,保持原文粒度`,
|
|
158
|
+
{ id: record?.id ?? null, judged },
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
if (judged.level === 'fail') {
|
|
162
|
+
throw new FidelityGateError(
|
|
163
|
+
'E_DISTILL_L2_GATE',
|
|
164
|
+
`L2 判定 fail(${judged.hits}/${judged.total})→ 本次不蒸馏,保持 L2 原文`,
|
|
165
|
+
{ id: record?.id ?? null, judged },
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
return { ok: true, verdict: judged };
|
|
169
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// src/memory/lock.js — M2-B / §2.4 / §5.3:跨进程写锁(lease)
|
|
2
|
+
//
|
|
3
|
+
// 语义抽自 `src/memory/maintenance.js` 的 O_EXCL 抢占:锁文件本身即租约
|
|
4
|
+
// `{holder, pid, acquiredAt, expiresAt}`;O_EXCL 创建保证跨进程唯一。
|
|
5
|
+
// * 同一 holder 重复 acquire → 幂等返回(已持有);
|
|
6
|
+
// * 过期租约(expiresAt < now)→ 允许接管(staleTakenOver:true);
|
|
7
|
+
// * 活跃租约被别人持有 → `E_LOCKED`(不无限重试、不双写)。
|
|
8
|
+
// 用于:journal/records 追加、boot.json/shutdown.json、索引构建与 captureTurn。
|
|
9
|
+
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
|
|
13
|
+
export const DEFAULT_LOCK_TTL_MS = 10 * 60 * 1000;
|
|
14
|
+
|
|
15
|
+
export class LockError extends Error {
|
|
16
|
+
constructor(code, message, detail = undefined) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.name = 'LockError';
|
|
19
|
+
this.code = code;
|
|
20
|
+
if (detail !== undefined) this.detail = detail;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function readLease(file) {
|
|
25
|
+
try {
|
|
26
|
+
const value = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
27
|
+
if (!value || typeof value !== 'object') return null;
|
|
28
|
+
return value;
|
|
29
|
+
} catch {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function nowMs(now) {
|
|
35
|
+
const value = typeof now === 'function' ? now() : new Date();
|
|
36
|
+
return value instanceof Date ? value.getTime() : Number(value);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Acquire a lease. Returns { ok:true, holder, acquiredAt, expiresAt, staleTakenOver }
|
|
41
|
+
* or throws LockError E_LOCKED with the current holder.
|
|
42
|
+
*/
|
|
43
|
+
export function acquireLease(lockFile, options = {}) {
|
|
44
|
+
const file = path.resolve(String(lockFile));
|
|
45
|
+
const holder = typeof options.holder === 'string' && options.holder !== '' ? options.holder : `pid-${process.pid}`;
|
|
46
|
+
const ttlMs = Number.isInteger(options.ttlMs) && options.ttlMs > 0 ? options.ttlMs : DEFAULT_LOCK_TTL_MS;
|
|
47
|
+
const now = options.now;
|
|
48
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
49
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
50
|
+
const acquiredAt = nowMs(now);
|
|
51
|
+
const lease = { holder, pid: process.pid, acquiredAt, expiresAt: acquiredAt + ttlMs };
|
|
52
|
+
try {
|
|
53
|
+
const fd = fs.openSync(file, 'wx');
|
|
54
|
+
try {
|
|
55
|
+
fs.writeFileSync(fd, `${JSON.stringify(lease)}\n`, 'utf8');
|
|
56
|
+
} finally {
|
|
57
|
+
fs.closeSync(fd);
|
|
58
|
+
}
|
|
59
|
+
return { ok: true, holder, acquiredAt, expiresAt: lease.expiresAt, lockFile: file, staleTakenOver: attempt > 0 };
|
|
60
|
+
} catch (error) {
|
|
61
|
+
if (error?.code !== 'EEXIST') throw new LockError('E_LOCK_IO', `无法创建锁文件:${error?.message ?? error}`);
|
|
62
|
+
const current = readLease(file);
|
|
63
|
+
const currentAt = Number(current?.expiresAt ?? 0);
|
|
64
|
+
if (current && current.holder === holder) {
|
|
65
|
+
return { ok: true, holder, acquiredAt: Number(current.acquiredAt) || acquiredAt, expiresAt: currentAt, lockFile: file, alreadyHeld: true };
|
|
66
|
+
}
|
|
67
|
+
if (!current || !Number.isFinite(currentAt) || currentAt < nowMs(now)) {
|
|
68
|
+
// stale / corrupt lease: take it over exactly once
|
|
69
|
+
try {
|
|
70
|
+
fs.rmSync(file, { force: true });
|
|
71
|
+
} catch {
|
|
72
|
+
/* raced with another taker; loop retries once */
|
|
73
|
+
}
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
throw new LockError('E_LOCKED', `写锁被 ${current.holder} 持有(pid=${current.pid})`, {
|
|
77
|
+
holder: current.holder,
|
|
78
|
+
pid: current.pid,
|
|
79
|
+
expiresAt: currentAt,
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
throw new LockError('E_LOCKED', '写锁竞争失败(stale takeover 两次均被抢先)');
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Release only if the recorded holder matches (never steal someone else's lease). */
|
|
87
|
+
export function releaseLease(lockFile, holder) {
|
|
88
|
+
const file = path.resolve(String(lockFile));
|
|
89
|
+
const current = readLease(file);
|
|
90
|
+
if (!current) return { ok: true, released: false, reason: 'no-lease' };
|
|
91
|
+
if (current.holder !== holder) {
|
|
92
|
+
return { ok: false, released: false, reason: 'not-holder', holder: current.holder };
|
|
93
|
+
}
|
|
94
|
+
fs.rmSync(file, { force: true });
|
|
95
|
+
return { ok: true, released: true };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function leaseStatus(lockFile, options = {}) {
|
|
99
|
+
const file = path.resolve(String(lockFile));
|
|
100
|
+
const current = readLease(file);
|
|
101
|
+
if (!current) return { present: false };
|
|
102
|
+
const expiresAt = Number(current.expiresAt ?? 0);
|
|
103
|
+
return {
|
|
104
|
+
present: true,
|
|
105
|
+
holder: current.holder,
|
|
106
|
+
pid: current.pid,
|
|
107
|
+
acquiredAt: current.acquiredAt,
|
|
108
|
+
expiresAt,
|
|
109
|
+
expired: Number.isFinite(expiresAt) ? expiresAt < nowMs(options.now) : true,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Run `fn` while holding the lease; always releases when we acquired it. */
|
|
114
|
+
export function withLease(lockFile, options, fn) {
|
|
115
|
+
const awaited = acquireLease(lockFile, options);
|
|
116
|
+
try {
|
|
117
|
+
return fn(awaited);
|
|
118
|
+
} finally {
|
|
119
|
+
if (!awaited.alreadyHeld) releaseLease(lockFile, awaited.holder);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
// src/memory/migrate.js — 1.8.0 / v2.8 §16.6(A1 分片):records.jsonl → claims.jsonl 迁移
|
|
2
|
+
//
|
|
3
|
+
// 规则(写死):
|
|
4
|
+
// * 旧记录 sourceTier 缺失 → host(v2.8 迁移口径);subject 缺失 → {entity: record.id};
|
|
5
|
+
// evidence 空;state 缺失 → active;隐式 evidence=[];legacy:true + audit.migratedFrom。
|
|
6
|
+
// * 迁移不增不减:records 行数 === 迁移后 claims 行数(同一批旧数据)。
|
|
7
|
+
// * 幂等:同 id 的 claim 已存在 → skip(重复 apply 条数不变)。
|
|
8
|
+
// * 不物理删除:apply 前把 records.jsonl 备份到 `.longlive/backups/`(sha256 记录)。
|
|
9
|
+
// * 默认 dry-run;--apply 才写。
|
|
10
|
+
|
|
11
|
+
import crypto from 'node:crypto';
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
|
|
15
|
+
import { claimFromLegacyRecord, claimsPathOf, readClaimsForHost } from './governance.js';
|
|
16
|
+
|
|
17
|
+
export function migrateBackupPath(memoryRoot, now = () => new Date()) {
|
|
18
|
+
const stamp = (now instanceof Date ? now : new Date()).toISOString().replace(/[:.]/g, '-');
|
|
19
|
+
return path.join(path.resolve(String(memoryRoot)), '.longlive', 'backups', `records-${stamp}.jsonl.bak`);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function sha256Buf(buf) {
|
|
23
|
+
return crypto.createHash('sha256').update(buf).digest('hex');
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Migrate legacy records.jsonl into claims.jsonl.
|
|
28
|
+
* @param {object} options
|
|
29
|
+
* @param {string} options.memoryRoot
|
|
30
|
+
* @param {boolean} [options.apply] default false (dry-run)
|
|
31
|
+
* @param {() => Date} [options.now]
|
|
32
|
+
* @returns {object} receipt
|
|
33
|
+
*/
|
|
34
|
+
export function migrateRecordsToClaims({ memoryRoot, apply = false, now = () => new Date() } = {}) {
|
|
35
|
+
const root = path.resolve(String(memoryRoot));
|
|
36
|
+
const recordsFile = path.join(root, '.longlive', 'records.jsonl');
|
|
37
|
+
const claimsFile = claimsPathOf(root);
|
|
38
|
+
const receipt = {
|
|
39
|
+
schema: 'migrate-records-v180/v1',
|
|
40
|
+
memoryRoot: root,
|
|
41
|
+
mode: apply ? 'apply' : 'dry-run',
|
|
42
|
+
recordsFile,
|
|
43
|
+
claimsFile,
|
|
44
|
+
recordsPresent: false,
|
|
45
|
+
recordsTotal: 0,
|
|
46
|
+
mapped: 0,
|
|
47
|
+
duplicates: 0,
|
|
48
|
+
unmappable: [],
|
|
49
|
+
skippedExisting: 0,
|
|
50
|
+
appended: 0,
|
|
51
|
+
recordsSha256: null,
|
|
52
|
+
backup: null,
|
|
53
|
+
beforeClaims: 0,
|
|
54
|
+
afterClaims: 0,
|
|
55
|
+
countMatched: false,
|
|
56
|
+
code: null,
|
|
57
|
+
exitCode: 0,
|
|
58
|
+
};
|
|
59
|
+
let text = '';
|
|
60
|
+
try {
|
|
61
|
+
text = fs.readFileSync(recordsFile, 'utf8');
|
|
62
|
+
receipt.recordsPresent = true;
|
|
63
|
+
} catch {
|
|
64
|
+
text = '';
|
|
65
|
+
}
|
|
66
|
+
const rows = [];
|
|
67
|
+
for (const line of text.split('\n')) {
|
|
68
|
+
if (line.trim() === '') continue;
|
|
69
|
+
try {
|
|
70
|
+
rows.push(JSON.parse(line));
|
|
71
|
+
} catch {
|
|
72
|
+
receipt.unmappable.push({ reason: 'E_JSON', line: line.slice(0, 120) });
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
receipt.recordsTotal = rows.length;
|
|
76
|
+
receipt.recordsSha256 = receipt.recordsPresent ? sha256Buf(Buffer.from(text, 'utf8')) : null;
|
|
77
|
+
// §16.6 / P0-2:没有可迁移记录不是成功 no-op。空/缺 records 必须显式
|
|
78
|
+
// E_NOTHING_TO_MIGRATE(CLI exit 2),countMatched 不得为 true(假绿)。
|
|
79
|
+
if (!receipt.recordsPresent || receipt.recordsTotal === 0) {
|
|
80
|
+
receipt.code = 'E_NOTHING_TO_MIGRATE';
|
|
81
|
+
receipt.exitCode = 2;
|
|
82
|
+
receipt.countMatched = false;
|
|
83
|
+
return receipt;
|
|
84
|
+
}
|
|
85
|
+
const existing = readClaimsForHost({ memoryRoot: root }).items;
|
|
86
|
+
const existingIds = new Set(existing.map((claim) => claim.id));
|
|
87
|
+
receipt.beforeClaims = existing.length;
|
|
88
|
+
const claims = [];
|
|
89
|
+
const seen = new Set();
|
|
90
|
+
for (const row of rows) {
|
|
91
|
+
try {
|
|
92
|
+
const claim = claimFromLegacyRecord(row);
|
|
93
|
+
if (seen.has(claim.id)) {
|
|
94
|
+
receipt.duplicates += 1;
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
seen.add(claim.id);
|
|
98
|
+
claims.push(claim);
|
|
99
|
+
receipt.mapped += 1;
|
|
100
|
+
} catch (error) {
|
|
101
|
+
receipt.unmappable.push({ reason: error?.code ?? 'E_MAP', message: String(error?.message ?? error) });
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
for (const claim of claims) {
|
|
105
|
+
if (existingIds.has(claim.id)) receipt.skippedExisting += 1;
|
|
106
|
+
}
|
|
107
|
+
if (apply && receipt.recordsPresent) {
|
|
108
|
+
fs.mkdirSync(path.dirname(migrateBackupPath(root, now())), { recursive: true });
|
|
109
|
+
const backupFile = migrateBackupPath(root, now());
|
|
110
|
+
// 备份 + 落盘都要 fsync(迁移期间崩溃不产生半行)。
|
|
111
|
+
fs.copyFileSync(recordsFile, backupFile);
|
|
112
|
+
try {
|
|
113
|
+
const bfd = fs.openSync(backupFile, 'r');
|
|
114
|
+
fs.fsyncSync(bfd);
|
|
115
|
+
fs.closeSync(bfd);
|
|
116
|
+
} catch { /* best effort */ }
|
|
117
|
+
receipt.backup = { path: backupFile, sha256: receipt.recordsSha256 };
|
|
118
|
+
fs.mkdirSync(path.dirname(claimsFile), { recursive: true });
|
|
119
|
+
const fd = fs.openSync(claimsFile, 'a');
|
|
120
|
+
try {
|
|
121
|
+
for (const claim of claims) {
|
|
122
|
+
if (existingIds.has(claim.id)) continue;
|
|
123
|
+
fs.writeSync(fd, `${JSON.stringify(claim)}\n`, null, 'utf8');
|
|
124
|
+
fs.fsyncSync(fd);
|
|
125
|
+
existingIds.add(claim.id);
|
|
126
|
+
receipt.appended += 1;
|
|
127
|
+
}
|
|
128
|
+
} finally {
|
|
129
|
+
fs.closeSync(fd);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
const after = readClaimsForHost({ memoryRoot: root }).items;
|
|
133
|
+
receipt.afterClaims = after.length;
|
|
134
|
+
// count consistency: every legacy record has exactly one claim (new ones or pre-existing)
|
|
135
|
+
const legacyClaimIds = new Set(claims.map((claim) => claim.id));
|
|
136
|
+
const presentLegacy = after.filter((claim) => legacyClaimIds.has(claim.id)).length;
|
|
137
|
+
receipt.countMatched = presentLegacy === claims.length;
|
|
138
|
+
return receipt;
|
|
139
|
+
}
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
// src/memory/recall-v2.js — M2-C:多路召回+证据门+确定性快答通道(memory_recall_v2)
|
|
2
|
+
//
|
|
3
|
+
// 两段式第一段(§3.2):检索 ≤1s,返回带锚点/引文的 hits + confidence + speed 字段;
|
|
4
|
+
// 证据门(§3.3.2):
|
|
5
|
+
// * 无命中 => confidence 'none',不回退猜测(E_NO_EVIDENCE)
|
|
6
|
+
// * 多命中/分数接近/冲突 => 降级 model 路径,fastAnswer=null
|
|
7
|
+
// * 唯一高置信命中 + 值类型匹配(版本/路径/时间/数字)=> 快答通道:
|
|
8
|
+
// 答案=原文引用+坐标,**不生成**;fail-safe:任何不确定都回退模型
|
|
9
|
+
//
|
|
10
|
+
// 本模块只读;fastAnswer 是确定性拼装,可逐字节复现。
|
|
11
|
+
|
|
12
|
+
import { memoryError, memoryRootFromConfig } from './paths.js';
|
|
13
|
+
import { memoryRecall } from './recall.js';
|
|
14
|
+
import { scanCards } from './index.js';
|
|
15
|
+
import { appendAuditRecord } from './audit-records.js';
|
|
16
|
+
import { searchAutoCards } from './auto-cards.js';
|
|
17
|
+
|
|
18
|
+
export const RECALL_V2_SCHEMA = 'memory-recall-v2/v1';
|
|
19
|
+
export const FAST_ANSWER_MAX_CHARS = 300;
|
|
20
|
+
|
|
21
|
+
const VALUE_PATTERNS = Object.freeze([
|
|
22
|
+
{ type: 'version', re: /v?\d+\.\d+(?:\.\d+)?(?:-[A-Za-z0-9.]+)?/u },
|
|
23
|
+
{ type: 'path', re: /(?:[A-Za-z]:[\\/]|\/)[^\s,。;;))】\]]+|(?:[\w.-]+[\\/])+[\w.-]+\.(?:md|mjs|js|json|jsonl|ps1|tgz|txt|html)\b/u },
|
|
24
|
+
{ type: 'time', re: /\d{1,2}:\d{2}(?::\d{2})?|\d{4}-\d{2}-\d{2}/u },
|
|
25
|
+
{ type: 'number', re: /\d+(?:\.\d+)?\s*(?:MB|GB|KB|ms|秒|分钟|小时|条|轮|个|%|分)?/u },
|
|
26
|
+
]);
|
|
27
|
+
|
|
28
|
+
export const FAST_ANSWER_TARGETS = Object.freeze({
|
|
29
|
+
version: 0.9,
|
|
30
|
+
path: 0.9,
|
|
31
|
+
time: 0.85,
|
|
32
|
+
number: 0.8,
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
/** Detect the value type a question is asking for (or null => not fast eligible). */
|
|
36
|
+
export function questionValueType(question) {
|
|
37
|
+
const text = String(question ?? '');
|
|
38
|
+
if (/版本号?|version|tag/i.test(text)) return 'version';
|
|
39
|
+
if (/路径|文件(?:名|在哪)|放哪|在哪(?:个)?文件|哪个文件/i.test(text)) return 'path';
|
|
40
|
+
if (/几点|时间|日期|什么时候|哪天|多久|多少分钟|空窗/i.test(text)) return 'time';
|
|
41
|
+
if (/多少|几个|数量|大小|多大|多久|几轮|几条|百分比|%/.test(text)) return 'number';
|
|
42
|
+
// no explicit ask type: only allow a value literal present in the question
|
|
43
|
+
for (const { type, re } of VALUE_PATTERNS) if (re.test(text)) return type;
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function detectValueType(text) {
|
|
48
|
+
const value = String(text ?? '');
|
|
49
|
+
for (const { type, re } of VALUE_PATTERNS) if (re.test(value)) return type;
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function excerptValueMatches(questionType, excerpt) {
|
|
54
|
+
if (questionType === null) return false;
|
|
55
|
+
for (const { type, re } of VALUE_PATTERNS) {
|
|
56
|
+
if (type !== questionType) continue;
|
|
57
|
+
return re.test(String(excerpt ?? ''));
|
|
58
|
+
}
|
|
59
|
+
return false;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Evidence gate: decide confidence / fast eligibility / fallback. Fail-safe: any
|
|
64
|
+
* uncertainty => model path, never a guessed fast answer.
|
|
65
|
+
*/
|
|
66
|
+
export function evidenceGate({ hits = [], question = '' } = {}) {
|
|
67
|
+
const list = Array.isArray(hits) ? hits : [];
|
|
68
|
+
if (list.length === 0) {
|
|
69
|
+
return { pass: false, confidence: 'none', fastEligible: false, code: 'E_NO_EVIDENCE', fallback: 'model', reason: 'no-hit' };
|
|
70
|
+
}
|
|
71
|
+
if (list.some((hit) => hit?.conflict === true) || list.some((hit) => hit?.anchor?.status === 'conflict')) {
|
|
72
|
+
return { pass: true, confidence: 'low', fastEligible: false, code: 'E_EVIDENCE_CONFLICT', fallback: 'model', reason: 'conflict' };
|
|
73
|
+
}
|
|
74
|
+
const questionType = questionValueType(question);
|
|
75
|
+
const withValue = list.filter((hit) => excerptValueMatches(questionType, hit?.quote ?? hit?.excerpt ?? ''));
|
|
76
|
+
if (list.length > 1) {
|
|
77
|
+
const top = Number(list[0]?.score ?? 0);
|
|
78
|
+
const second = Number(list[1]?.score ?? 0);
|
|
79
|
+
const close = Number.isFinite(top) && Number.isFinite(second) && Math.abs(top - second) < 0.1;
|
|
80
|
+
if (questionType !== null && withValue.length === 1 && !close) {
|
|
81
|
+
return { pass: true, confidence: 'high', fastEligible: true, code: null, fallback: null, reason: 'single-value-hit' };
|
|
82
|
+
}
|
|
83
|
+
return { pass: true, confidence: close ? 'low' : 'medium', fastEligible: false, code: close ? 'E_EVIDENCE_AMBIGUOUS' : null, fallback: 'model', reason: close ? 'ambiguous' : 'multi-hit' };
|
|
84
|
+
}
|
|
85
|
+
const only = list[0];
|
|
86
|
+
const anchorStatus = only?.anchor?.status ?? 'live';
|
|
87
|
+
if (anchorStatus !== 'live') {
|
|
88
|
+
return { pass: false, confidence: 'low', fastEligible: false, code: 'E_ANCHOR_NOT_LIVE', fallback: 'model', reason: 'stale-anchor' };
|
|
89
|
+
}
|
|
90
|
+
if (questionType !== null && withValue.length === 1) {
|
|
91
|
+
return { pass: true, confidence: 'high', fastEligible: true, code: null, fallback: null, reason: 'single-value-hit' };
|
|
92
|
+
}
|
|
93
|
+
return { pass: true, confidence: 'medium', fastEligible: false, code: null, fallback: 'model', reason: 'value-type-mismatch' };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Deterministic fast answer: quote + coordinate, no generation. */
|
|
97
|
+
export function buildFastAnswer({ question = '', hit = null, gate = null } = {}) {
|
|
98
|
+
if (!hit || (gate && gate.fastEligible !== true)) return null;
|
|
99
|
+
const quote = String(hit.quote ?? hit.excerpt ?? '').replace(/\s+/gu, ' ').trim();
|
|
100
|
+
if (quote === '') return null;
|
|
101
|
+
const anchor = hit.anchor ?? {};
|
|
102
|
+
const coordinateParts = [];
|
|
103
|
+
if (typeof hit.card === 'string') coordinateParts.push(hit.card);
|
|
104
|
+
if (typeof anchor.file === 'string') coordinateParts.push(anchor.file);
|
|
105
|
+
if (Number.isInteger(anchor.turn)) coordinateParts.push(`第 ${anchor.turn} 轮`);
|
|
106
|
+
const coordinate = coordinateParts.length > 0 ? coordinateParts.join(' · ') : '卡锚点';
|
|
107
|
+
const valueType = detectValueType(quote) ?? questionValueType(question);
|
|
108
|
+
const text = `${quote}(坐标:${coordinate})`.slice(0, FAST_ANSWER_MAX_CHARS);
|
|
109
|
+
return { text, quote, anchor, valueType, confidence: 'high', deterministic: true, question: String(question ?? '').slice(0, 120) };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Trim a card date (YYYY-MM-DD / ISO) to ms; null when absent. */
|
|
113
|
+
function dateMs(value) {
|
|
114
|
+
if (typeof value !== 'string' || value.trim() === '') return null;
|
|
115
|
+
const ms = Date.parse(value);
|
|
116
|
+
return Number.isFinite(ms) ? ms : null;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** memory_recall_v2 tool entry: multi-route recall + evidence gate + fast answer. */
|
|
120
|
+
export function recallV2(args = {}, config = {}) {
|
|
121
|
+
const rawQuery = args?.query;
|
|
122
|
+
if (typeof rawQuery !== 'string' || rawQuery.trim() === '') {
|
|
123
|
+
throw memoryError('E_RECALL_EMPTY_QUERY', 'memory_recall_v2 需要 query(自然语言或关键词)。');
|
|
124
|
+
}
|
|
125
|
+
const query = rawQuery.trim();
|
|
126
|
+
const topK = Math.max(1, Math.min(10, Number.isInteger(args?.topK) ? Number(args.topK) : 3));
|
|
127
|
+
const includeForgotten = args?.includeForgotten === true;
|
|
128
|
+
const project = typeof args?.project === 'string' && args.project.trim() !== '' ? args.project.trim() : null;
|
|
129
|
+
const sinceMs = dateMs(args?.since);
|
|
130
|
+
const untilMs = dateMs(args?.until);
|
|
131
|
+
const root = memoryRootFromConfig(config);
|
|
132
|
+
|
|
133
|
+
const recalled = memoryRecall({ query, topK: Math.max(topK, 5), status: includeForgotten ? 'any' : 'active' }, { memoryRoot: root });
|
|
134
|
+
const cards = new Map((scanCards(root) || []).map((card) => [card.rel, card]));
|
|
135
|
+
let hits = [];
|
|
136
|
+
for (const row of Array.isArray(recalled.results) ? recalled.results : []) {
|
|
137
|
+
if (row?.type === 'event') continue; // AutoCards are appended below, after curated cards.
|
|
138
|
+
const card = cards.get(row.path);
|
|
139
|
+
const cardFields = card?.fields ?? {};
|
|
140
|
+
const cardStatus = cardFields.status ?? 'active';
|
|
141
|
+
if (!includeForgotten && (cardStatus === 'archived' || cardStatus === 'forgotten')) continue;
|
|
142
|
+
if (project !== null) {
|
|
143
|
+
const fields = cardFields;
|
|
144
|
+
const cardProject = typeof fields.project === 'string' ? fields.project : null;
|
|
145
|
+
if (cardProject !== null && cardProject !== project) continue;
|
|
146
|
+
}
|
|
147
|
+
const ms = dateMs(card?.fields?.date ?? card?.date);
|
|
148
|
+
if (sinceMs !== null && ms !== null && ms < sinceMs) continue;
|
|
149
|
+
if (untilMs !== null && ms !== null && ms > untilMs) continue;
|
|
150
|
+
const status = cardStatus;
|
|
151
|
+
hits.push({
|
|
152
|
+
card: row.path,
|
|
153
|
+
anchor: { kind: 'file', file: row.path, line: null, status: status === 'archived' || status === 'forgotten' ? 'stale' : 'live' },
|
|
154
|
+
quote: String(row.excerpt ?? '').replace(/\s+/gu, ' ').trim().slice(0, 240),
|
|
155
|
+
score: Number(row.score ?? 0),
|
|
156
|
+
});
|
|
157
|
+
if (hits.length >= topK) break;
|
|
158
|
+
}
|
|
159
|
+
const gate = evidenceGate({ hits, question: query });
|
|
160
|
+
// 1.8.0 AutoCards: at most one event card supplements up to two curated hits;
|
|
161
|
+
// the original turn coordinate and a session_original hint travel with it.
|
|
162
|
+
const autoHits = searchAutoCards({ memoryRoot: root, query, limit: 3 }).slice(0, 1).map((card) => ({
|
|
163
|
+
card: `auto:${card.cardId}`,
|
|
164
|
+
cardId: card.cardId,
|
|
165
|
+
eventId: card.eventId,
|
|
166
|
+
kind: 'auto-card',
|
|
167
|
+
anchor: { kind: 'session_turn', ...card.anchor, status: 'live' },
|
|
168
|
+
quote: String(card.title ?? '').replace(/\s+/gu, ' ').trim().slice(0, 240),
|
|
169
|
+
score: 1,
|
|
170
|
+
originalHint: `可读原文 session_original(turn=${card.anchor.turn})`,
|
|
171
|
+
original: {
|
|
172
|
+
sessionId: card.anchor.sessionId,
|
|
173
|
+
turn: card.anchor.turn,
|
|
174
|
+
how: `session_original(turn=${card.anchor.turn})`,
|
|
175
|
+
},
|
|
176
|
+
}));
|
|
177
|
+
const curatedHits = hits.slice(0, Math.min(2, topK));
|
|
178
|
+
hits = [...curatedHits, ...autoHits].slice(0, topK);
|
|
179
|
+
const finalGate = evidenceGate({ hits, question: query });
|
|
180
|
+
const fastAnswer = finalGate.fastEligible ? buildFastAnswer({ question: query, hit: hits[0], gate: finalGate }) : null;
|
|
181
|
+
// §16.8-D: every recall entry writes one unified read-audit row (行数=调用数).
|
|
182
|
+
try {
|
|
183
|
+
appendAuditRecord({
|
|
184
|
+
memoryRoot: root,
|
|
185
|
+
action: 'read',
|
|
186
|
+
recordId: hits.length > 0 ? hits.map((hit) => hit.card).join(',') : null,
|
|
187
|
+
readerTier: typeof args?.readerTier === 'string' && args.readerTier !== '' ? args.readerTier : 'agent',
|
|
188
|
+
questionId: 'unknown',
|
|
189
|
+
expectedTurns: null,
|
|
190
|
+
answerText: null,
|
|
191
|
+
extra: { entry: 'memory_recall_v2', count: hits.length, confidence: finalGate.confidence, fastAnswer: fastAnswer !== null },
|
|
192
|
+
});
|
|
193
|
+
} catch { /* read audit must never break recall */ }
|
|
194
|
+
return {
|
|
195
|
+
schema: RECALL_V2_SCHEMA,
|
|
196
|
+
ok: true,
|
|
197
|
+
query,
|
|
198
|
+
topK,
|
|
199
|
+
includeForgotten,
|
|
200
|
+
confidence: finalGate.confidence,
|
|
201
|
+
hits,
|
|
202
|
+
didYouMean: [],
|
|
203
|
+
slowPath: fastAnswer === null,
|
|
204
|
+
fastAnswer,
|
|
205
|
+
evidenceGate: finalGate,
|
|
206
|
+
fallback: finalGate.fallback,
|
|
207
|
+
...(hits.length === 0 ? { status: 'empty', code: 'E_NO_EVIDENCE', hint: '没有可引用证据:请直说未找到,不要猜。' } : { status: 'ok' }),
|
|
208
|
+
...(finalGate.code ? { code: finalGate.code } : {}),
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** Adapter for pre-step recall results (items from recall-core) → evidence package fastAnswer. */
|
|
213
|
+
export function fastAnswerFromRecallItems({ question = '', items = [] } = {}) {
|
|
214
|
+
const hits = (Array.isArray(items) ? items : []).map((item) => ({
|
|
215
|
+
card: item.path,
|
|
216
|
+
anchor: { kind: 'file', file: item.path, line: null, status: 'live' },
|
|
217
|
+
quote: String(item.excerpt ?? item.title ?? '').replace(/\s+/gu, ' ').trim(),
|
|
218
|
+
score: Number(item.score ?? 0),
|
|
219
|
+
}));
|
|
220
|
+
const gate = evidenceGate({ hits, question });
|
|
221
|
+
if (!gate.fastEligible) return { fastAnswer: null, gate };
|
|
222
|
+
return { fastAnswer: buildFastAnswer({ question, hit: hits[0], gate }), gate };
|
|
223
|
+
}
|