@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,406 @@
|
|
|
1
|
+
// src/memory/recall-feedback.mjs — 召回反馈(D20):把「用上了 / 没用上」反馈写回卡强度。
|
|
2
|
+
//
|
|
3
|
+
// 契约来源:V0.5.2-MERGE-PLAN §4/§14 D20 行 / KICKOFF-PLAN §2-D / BATCH-D-BRIEF N11 规格。
|
|
4
|
+
// - up salience +0.5(clamp 0..5,只升);down strength −0.5(clamp 0..9),salience 一列不动;
|
|
5
|
+
// - down 还要更新 last_used;每轮 ≤2 条、可按 entryId 回滚;反馈账本 feedback.jsonl
|
|
6
|
+
// (≤2,000 行 / 180d);失败路径写 gate-log 事件 `hg.d20.fail`。
|
|
7
|
+
// - 工具入口 memory_feedback 的接线(tools.js)属 W7、本批不改(Q5 选 B);工具入口当前
|
|
8
|
+
// 不向模块传 config,因此无 memoryRoot 时按「未接线」抛 E_HG_RECALL_FEEDBACK_UNIMPLEMENTED,
|
|
9
|
+
// 保持 fail-closed 与 tools_contract C19b 口径。
|
|
10
|
+
//
|
|
11
|
+
// fail-closed:任一判定/写卡失败都不静默成功;未落盘前不得改卡。
|
|
12
|
+
|
|
13
|
+
import crypto from 'node:crypto';
|
|
14
|
+
import fs from 'node:fs';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
|
|
17
|
+
import { appendGateLog } from '../recall/gate-log.mjs';
|
|
18
|
+
import { parseFrontmatter, updateFrontmatter } from './frontmatter.js';
|
|
19
|
+
|
|
20
|
+
export const BATCH = 'D';
|
|
21
|
+
export const MODULE = 'memory/recall-feedback.mjs';
|
|
22
|
+
export const UNIMPLEMENTED_CODE = 'E_HG_RECALL_FEEDBACK_UNIMPLEMENTED';
|
|
23
|
+
export const SKELETON = Object.freeze({
|
|
24
|
+
version: '2.0.0',
|
|
25
|
+
failClosed: true,
|
|
26
|
+
batch: BATCH,
|
|
27
|
+
implemented: true,
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
/** 反馈账本相对 memoryRoot 的路径 */
|
|
31
|
+
export const FEEDBACK_REL = '.longlive/hardgate/feedback.jsonl';
|
|
32
|
+
/** 强度增量(计划冻结) */
|
|
33
|
+
export const SALIENCE_UP = 0.5;
|
|
34
|
+
export const SALIENCE_DOWN = -0.5;
|
|
35
|
+
/** salience 上限(计划冻结:cap 5) */
|
|
36
|
+
export const SALIENCE_MAX = 5;
|
|
37
|
+
/** 强度范围(与 memory_reinforce 口径一致) */
|
|
38
|
+
export const STRENGTH_MIN = 0;
|
|
39
|
+
export const STRENGTH_MAX = 9;
|
|
40
|
+
/** 账本上限 / 保留天数(计划冻结) */
|
|
41
|
+
export const MAX_ROWS = 2000;
|
|
42
|
+
export const RETENTION_DAYS = 180;
|
|
43
|
+
/** 每轮可应用条数上限(计划冻结) */
|
|
44
|
+
export const MAX_PER_ROUND = 2;
|
|
45
|
+
/** 工具名 */
|
|
46
|
+
export const TOOL_NAME = 'memory_feedback';
|
|
47
|
+
/** 失败门事件 */
|
|
48
|
+
export const GATE_EVENT = 'hg.d20.fail';
|
|
49
|
+
/** 账本 schema */
|
|
50
|
+
export const FEEDBACK_SCHEMA = 'hardgate-feedback/v1';
|
|
51
|
+
|
|
52
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
53
|
+
|
|
54
|
+
function failWithGate(root, code, message) {
|
|
55
|
+
try {
|
|
56
|
+
if (typeof root === 'string' && root !== '') {
|
|
57
|
+
appendGateLog(root, {
|
|
58
|
+
sessionId: null,
|
|
59
|
+
turn: 0,
|
|
60
|
+
gate: GATE_EVENT,
|
|
61
|
+
decision: 'fail',
|
|
62
|
+
reason: code,
|
|
63
|
+
evidence: [String(message ?? '').slice(0, 300)],
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
} catch {
|
|
67
|
+
/* gate-log must never mask the original failure */
|
|
68
|
+
}
|
|
69
|
+
const error = new Error(`${code}: ${message}`);
|
|
70
|
+
error.code = code;
|
|
71
|
+
error.gate = GATE_EVENT;
|
|
72
|
+
throw error;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function nowMsOf(now) {
|
|
76
|
+
if (now instanceof Date) return now.getTime();
|
|
77
|
+
if (typeof now === 'number' && Number.isFinite(now)) return now;
|
|
78
|
+
if (typeof now === 'string' && now.trim() !== '') {
|
|
79
|
+
const parsed = Date.parse(now);
|
|
80
|
+
if (Number.isFinite(parsed)) return parsed;
|
|
81
|
+
}
|
|
82
|
+
return Date.now();
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function isoOf(ms) {
|
|
86
|
+
return new Date(ms).toISOString();
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function sha1Short(value) {
|
|
90
|
+
return crypto.createHash('sha1').update(String(value), 'utf8').digest('hex').slice(0, 12);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function dayString(ms) {
|
|
94
|
+
return new Date(ms).toISOString().slice(0, 10);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function ledgerPath(root) {
|
|
98
|
+
return path.join(root, ...FEEDBACK_REL.split('/'));
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function round(value, digits = 2) {
|
|
102
|
+
const factor = 10 ** digits;
|
|
103
|
+
return Math.round(value * factor) / factor;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function clamp(value, min, max) {
|
|
107
|
+
return Math.min(max, Math.max(min, value));
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function resolveRoot(input, config) {
|
|
111
|
+
// 只认显式 memoryRoot(input)或显式配置(config.memoryRoot),不落「隐式默认记忆根」:
|
|
112
|
+
// tools.js:3095 的 memory_feedback 入口不传 config(Q5 选 B,接线留批 E/H),必须按
|
|
113
|
+
// 「未接线」fail-closed 抛 E_HG_RECALL_FEEDBACK_UNIMPLEMENTED(test C19b 口径)。
|
|
114
|
+
const direct = typeof input?.memoryRoot === 'string' ? input.memoryRoot.trim() : '';
|
|
115
|
+
if (direct !== '') return direct;
|
|
116
|
+
const fromConfig = typeof config?.memoryRoot === 'string' ? config.memoryRoot.trim() : '';
|
|
117
|
+
return fromConfig;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function readLedger(root) {
|
|
121
|
+
const file = ledgerPath(root);
|
|
122
|
+
if (!fs.existsSync(file)) return { file, rows: [], corrupt: [] };
|
|
123
|
+
const rows = [];
|
|
124
|
+
const corrupt = [];
|
|
125
|
+
for (const line of fs.readFileSync(file, 'utf8').split(/\r?\n/)) {
|
|
126
|
+
if (line.trim() === '') continue;
|
|
127
|
+
try {
|
|
128
|
+
const row = JSON.parse(line);
|
|
129
|
+
if (row === null || typeof row !== 'object') corrupt.push(line);
|
|
130
|
+
else rows.push(row);
|
|
131
|
+
} catch {
|
|
132
|
+
corrupt.push(line);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return { file, rows, corrupt };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function writeLedger(file, rows) {
|
|
139
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
140
|
+
const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
|
|
141
|
+
const body = rows.map((row) => JSON.stringify(row)).join('\n');
|
|
142
|
+
fs.writeFileSync(tmp, body === '' ? '' : `${body}\n`, 'utf8');
|
|
143
|
+
fs.renameSync(tmp, file);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function cardAbsolute(root, rel) {
|
|
147
|
+
const text = String(rel ?? '').trim();
|
|
148
|
+
if (text === '') return null;
|
|
149
|
+
const abs = path.resolve(root, text);
|
|
150
|
+
const base = path.resolve(root);
|
|
151
|
+
if (abs !== base && !abs.startsWith(base + path.sep)) return null;
|
|
152
|
+
return abs;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function readCard(root, rel) {
|
|
156
|
+
const abs = cardAbsolute(root, rel);
|
|
157
|
+
if (abs === null) failWithGate(root, 'E_HG_D20_CARD', `card path escapes memoryRoot: ${rel}`);
|
|
158
|
+
let stat;
|
|
159
|
+
try {
|
|
160
|
+
stat = fs.lstatSync(abs);
|
|
161
|
+
} catch {
|
|
162
|
+
failWithGate(root, 'E_HG_D20_CARD', `card not found: ${rel}`);
|
|
163
|
+
}
|
|
164
|
+
if (!stat.isFile()) failWithGate(root, 'E_HG_D20_CARD', `card is not a regular file: ${rel}`);
|
|
165
|
+
const original = fs.readFileSync(abs, 'utf8');
|
|
166
|
+
const parsed = parseFrontmatter(original);
|
|
167
|
+
if (parsed === null) failWithGate(root, 'E_HG_D20_CARD', `card has no frontmatter: ${rel}`);
|
|
168
|
+
const fields = parsed.fields ?? {};
|
|
169
|
+
const salience = Number.isFinite(Number(fields.salience)) ? Number(fields.salience) : 0;
|
|
170
|
+
const strength = Number.isFinite(Number(fields.strength)) ? Number(fields.strength) : 0;
|
|
171
|
+
return { abs, rel: String(rel ?? '').trim(), original, parsed, salience, strength };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function writeCard(root, card, updates) {
|
|
175
|
+
const next = updateFrontmatter(card.original, updates);
|
|
176
|
+
fs.mkdirSync(path.dirname(card.abs), { recursive: true });
|
|
177
|
+
const tmp = `${card.abs}.tmp-${process.pid}-${Date.now()}`;
|
|
178
|
+
fs.writeFileSync(tmp, next, 'utf8');
|
|
179
|
+
fs.renameSync(tmp, card.abs);
|
|
180
|
+
const readBack = fs.readFileSync(card.abs, 'utf8');
|
|
181
|
+
if (readBack !== next) failWithGate(root, 'E_HG_D20_VERIFY', `card write read-back mismatch: ${card.rel}`);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* 有效值 = 卡片 base(frontmatter 整数)+ feedback.jsonl 里未回滚的增量(按落盘顺序逐条 clamp)。
|
|
186
|
+
*
|
|
187
|
+
* 1.8.12 生产卡 frontmatter 强制 salience/strength 为 0..9 的整数(frontmatter.js
|
|
188
|
+
* parseSalience/parseStrength 抛 E_CARD_SALIENCE_INVALID),半分步长无法直接落卡;
|
|
189
|
+
* D20 因此以 feedback.jsonl 账本为权威有效值,卡片只写合法整数/日期(down 更新 last_used)。
|
|
190
|
+
*/
|
|
191
|
+
function effectiveValues(rows, card) {
|
|
192
|
+
let salience = card.salience;
|
|
193
|
+
let strength = card.strength;
|
|
194
|
+
const rolled = new Set(
|
|
195
|
+
rows.filter((row) => row.action === 'rollback' && typeof row.rollbackOf === 'string').map((row) => row.rollbackOf),
|
|
196
|
+
);
|
|
197
|
+
for (const row of rows) {
|
|
198
|
+
if (row.action === 'rollback' || row.card !== card.rel) continue;
|
|
199
|
+
if (rolled.has(row.entryId)) continue;
|
|
200
|
+
const field = row.field === 'strength' ? 'strength' : 'salience';
|
|
201
|
+
const before = Number(row.before?.[field]);
|
|
202
|
+
const after = Number(row.after?.[field]);
|
|
203
|
+
if (!Number.isFinite(before) || !Number.isFinite(after)) continue;
|
|
204
|
+
if (field === 'salience') salience = clamp(round(salience + (after - before), 2), 0, SALIENCE_MAX);
|
|
205
|
+
else strength = clamp(round(strength + (after - before), 2), STRENGTH_MIN, STRENGTH_MAX);
|
|
206
|
+
}
|
|
207
|
+
return { card: card.rel, base: { salience: card.salience, strength: card.strength }, salience, strength };
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function tryEffective(root, rows, rel) {
|
|
211
|
+
const abs = cardAbsolute(root, rel);
|
|
212
|
+
if (abs === null || !fs.existsSync(abs)) return null;
|
|
213
|
+
try {
|
|
214
|
+
return effectiveValues(rows, readCard(root, rel));
|
|
215
|
+
} catch {
|
|
216
|
+
return null;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function perRoundRows(rows, sessionId, turn) {
|
|
221
|
+
const sid = sessionId ?? null;
|
|
222
|
+
const tn = Number.isInteger(turn) ? turn : 0;
|
|
223
|
+
return rows.filter((row) => row.sessionId === sid && row.turn === tn && row.action !== 'rollback').length;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function appendRow(root, rows, row, atMs) {
|
|
227
|
+
const cutoff = atMs - RETENTION_DAYS * DAY_MS;
|
|
228
|
+
const kept = rows.filter((item) => {
|
|
229
|
+
const at = Date.parse(String(item?.at ?? ''));
|
|
230
|
+
return !(Number.isFinite(at) && at < cutoff);
|
|
231
|
+
});
|
|
232
|
+
kept.push(row);
|
|
233
|
+
const tail = kept.length > MAX_ROWS ? kept.slice(kept.length - MAX_ROWS) : kept;
|
|
234
|
+
writeLedger(ledgerPath(root), tail);
|
|
235
|
+
return tail;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function entryIdFor(row) {
|
|
239
|
+
return `fb-${sha1Short(`${row.card}|${row.action}|${row.at}|${row.sessionId ?? ''}|${row.turn ?? 0}`)}`;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function buildRow(root, input, card, action, field, before, after, atMs) {
|
|
243
|
+
const row = {
|
|
244
|
+
schema: FEEDBACK_SCHEMA,
|
|
245
|
+
entryId: '',
|
|
246
|
+
action,
|
|
247
|
+
card: card.rel,
|
|
248
|
+
field,
|
|
249
|
+
before: field === 'salience' ? { salience: before } : { strength: before },
|
|
250
|
+
after: field === 'salience' ? { salience: after } : { strength: after },
|
|
251
|
+
delta: round(action === 'up' ? SALIENCE_UP : SALIENCE_DOWN),
|
|
252
|
+
reason: typeof input.reason === 'string' ? input.reason : '被真实使用',
|
|
253
|
+
sessionId: typeof input.sessionId === 'string' ? input.sessionId : null,
|
|
254
|
+
turn: Number.isInteger(input.turn) ? input.turn : 0,
|
|
255
|
+
at: isoOf(atMs),
|
|
256
|
+
day: dayString(atMs),
|
|
257
|
+
};
|
|
258
|
+
row.entryId = entryIdFor(row);
|
|
259
|
+
return row;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* memory_feedback 工具的实现入口:记录一次召回反馈(up/down/rollback/status)。
|
|
264
|
+
* @param {{memoryRoot?: string, card?: string, cardPath?: string, action?: 'up'|'down'|'rollback'|'status',
|
|
265
|
+
* reason?: string, sessionId?: string, turn?: number, now?: unknown, entryId?: string}} input
|
|
266
|
+
* @param {object} [config]
|
|
267
|
+
*/
|
|
268
|
+
export function memoryFeedback(input = {}, config = {}) {
|
|
269
|
+
if (input === null || typeof input !== 'object') {
|
|
270
|
+
const error = new Error(`${UNIMPLEMENTED_CODE}: memoryFeedback input must be a plain object`);
|
|
271
|
+
error.code = UNIMPLEMENTED_CODE;
|
|
272
|
+
throw error;
|
|
273
|
+
}
|
|
274
|
+
const root = resolveRoot(input, config ?? {});
|
|
275
|
+
if (root === '') {
|
|
276
|
+
// 工具入口(tools.js)尚未接线传 config:如实按「未接线」fail-closed,不伪造成功。
|
|
277
|
+
const error = new Error(`${UNIMPLEMENTED_CODE}: memoryFeedback requires memoryRoot (tool entry not wired until W7)`);
|
|
278
|
+
error.code = UNIMPLEMENTED_CODE;
|
|
279
|
+
error.status = 'UNSET';
|
|
280
|
+
error.implemented = false;
|
|
281
|
+
error.gate = GATE_EVENT;
|
|
282
|
+
throw error;
|
|
283
|
+
}
|
|
284
|
+
const action = input.action === undefined ? 'up' : String(input.action);
|
|
285
|
+
try {
|
|
286
|
+
if (action === 'status') {
|
|
287
|
+
const { rows, corrupt } = readLedger(root);
|
|
288
|
+
const last = rows.length > 0 ? rows[rows.length - 1] : null;
|
|
289
|
+
return {
|
|
290
|
+
ok: true,
|
|
291
|
+
status: 'ok',
|
|
292
|
+
implemented: true,
|
|
293
|
+
rows: rows.length,
|
|
294
|
+
corrupt: corrupt.length,
|
|
295
|
+
lastAt: last?.at ?? null,
|
|
296
|
+
file: ledgerPath(root),
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
const cardRel = input.card ?? input.cardPath;
|
|
300
|
+
const atMs = nowMsOf(input.now);
|
|
301
|
+
const { rows } = readLedger(root);
|
|
302
|
+
|
|
303
|
+
if (action === 'rollback') {
|
|
304
|
+
const entryId = typeof input.entryId === 'string' ? input.entryId : '';
|
|
305
|
+
if (entryId === '') failWithGate(root, 'E_HG_D20_ENTRY', 'rollback requires entryId');
|
|
306
|
+
const target = rows.find((row) => row.entryId === entryId && row.action !== 'rollback');
|
|
307
|
+
if (target === undefined) failWithGate(root, 'E_HG_D20_ENTRY', `feedback entry not found: ${entryId}`);
|
|
308
|
+
if (rows.some((row) => row.action === 'rollback' && row.rollbackOf === entryId)) {
|
|
309
|
+
failWithGate(root, 'E_HG_D20_ROLLBACK', `feedback entry already rolled back: ${entryId}`);
|
|
310
|
+
}
|
|
311
|
+
const card = readCard(root, target.card);
|
|
312
|
+
const field = target.field === 'strength' ? 'strength' : 'salience';
|
|
313
|
+
const delta = Number(target.after?.[field]) - Number(target.before?.[field]);
|
|
314
|
+
if (!Number.isFinite(delta)) failWithGate(root, 'E_HG_D20_ROLLBACK', `entry ${entryId} has no restorable delta`);
|
|
315
|
+
const eff = effectiveValues(rows, card);
|
|
316
|
+
const beforeValue = field === 'strength' ? eff.strength : eff.salience;
|
|
317
|
+
const min = field === 'strength' ? STRENGTH_MIN : 0;
|
|
318
|
+
const max = field === 'strength' ? STRENGTH_MAX : SALIENCE_MAX;
|
|
319
|
+
const restored = clamp(round(beforeValue - delta, 2), min, max);
|
|
320
|
+
const row = {
|
|
321
|
+
schema: FEEDBACK_SCHEMA,
|
|
322
|
+
entryId: `fb-rb-${sha1Short(`${entryId}|${atMs}`)}`,
|
|
323
|
+
action: 'rollback',
|
|
324
|
+
card: target.card,
|
|
325
|
+
field,
|
|
326
|
+
rollbackOf: entryId,
|
|
327
|
+
before: { [field]: beforeValue },
|
|
328
|
+
after: { [field]: restored },
|
|
329
|
+
delta: round(-delta),
|
|
330
|
+
reason: typeof input.reason === 'string' ? input.reason : 'rollback',
|
|
331
|
+
sessionId: typeof input.sessionId === 'string' ? input.sessionId : null,
|
|
332
|
+
turn: Number.isInteger(input.turn) ? input.turn : 0,
|
|
333
|
+
at: isoOf(atMs),
|
|
334
|
+
day: dayString(atMs),
|
|
335
|
+
};
|
|
336
|
+
const kept = appendRow(root, rows, row, atMs);
|
|
337
|
+
return { ok: true, action, field, before: row.before, after: row.after, entryId: row.entryId, rollbackOf: entryId, perRound: perRoundRows(kept, row.sessionId, row.turn), total: kept.length };
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
if (action !== 'up' && action !== 'down') failWithGate(root, 'E_HG_D20_ACTION', `unknown feedback action: ${action}`);
|
|
341
|
+
const perRound = perRoundRows(rows, input.sessionId, input.turn);
|
|
342
|
+
if (perRound >= MAX_PER_ROUND) failWithGate(root, 'E_HG_D20_PER_ROUND', `per-round feedback limit ${MAX_PER_ROUND} reached (session=${input.sessionId ?? ''}, turn=${input.turn ?? 0})`);
|
|
343
|
+
const card = readCard(root, cardRel);
|
|
344
|
+
const field = action === 'up' ? 'salience' : 'strength';
|
|
345
|
+
const eff = effectiveValues(rows, card);
|
|
346
|
+
const before = field === 'salience' ? eff.salience : eff.strength;
|
|
347
|
+
let after;
|
|
348
|
+
if (field === 'salience') after = clamp(round(before + SALIENCE_UP, 2), 0, SALIENCE_MAX);
|
|
349
|
+
else after = clamp(round(before + SALIENCE_DOWN, 2), STRENGTH_MIN, STRENGTH_MAX);
|
|
350
|
+
// 卡面不写半分值:仅 down 按 Q4 更新 last_used(合法日期列),salience/strength 保持整数。
|
|
351
|
+
if (action === 'down') writeCard(root, card, { last_used: dayString(atMs) });
|
|
352
|
+
const row = buildRow(root, input, card, action, field, before, after, atMs);
|
|
353
|
+
const kept = appendRow(root, rows, row, atMs);
|
|
354
|
+
return {
|
|
355
|
+
ok: true,
|
|
356
|
+
action,
|
|
357
|
+
field,
|
|
358
|
+
before: row.before,
|
|
359
|
+
after: row.after,
|
|
360
|
+
entryId: row.entryId,
|
|
361
|
+
perRound: perRound + 1,
|
|
362
|
+
total: kept.length,
|
|
363
|
+
card: card.rel,
|
|
364
|
+
effective: field === 'salience' ? { salience: after, strength: eff.strength } : { salience: eff.salience, strength: after },
|
|
365
|
+
};
|
|
366
|
+
} catch (error) {
|
|
367
|
+
if (error?.gate === GATE_EVENT) throw error;
|
|
368
|
+
failWithGate(root, 'E_HG_D20_INTERNAL', error?.message ?? String(error));
|
|
369
|
+
return null;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/** 计划允许的导出别名之一(记录一次反馈)。 */
|
|
374
|
+
export function recordFeedback(input = {}, config = {}) {
|
|
375
|
+
return memoryFeedback(input, config);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/** 计划允许的导出别名之一(应用反馈到卡片强度)。 */
|
|
379
|
+
export function applyFeedback(input = {}, config = {}) {
|
|
380
|
+
return memoryFeedback(input, config);
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* 读反馈账本(坏行不得静默丢弃:corrupt 单独计数返回)。
|
|
385
|
+
* @param {{memoryRoot?: string}} input
|
|
386
|
+
*/
|
|
387
|
+
export function readFeedback(input = {}, config = {}) {
|
|
388
|
+
const root = resolveRoot(input, config ?? {});
|
|
389
|
+
if (root === '') failWithGate('', 'E_HG_D20_NO_ROOT', 'readFeedback requires memoryRoot');
|
|
390
|
+
const { rows, corrupt, file } = readLedger(root);
|
|
391
|
+
const effective = {};
|
|
392
|
+
const cards = [...new Set(rows.filter((row) => row.action !== 'rollback' && typeof row.card === 'string').map((row) => row.card))];
|
|
393
|
+
for (const rel of cards) {
|
|
394
|
+
const view = tryEffective(root, rows, rel);
|
|
395
|
+
if (view !== null) effective[rel] = view;
|
|
396
|
+
}
|
|
397
|
+
return { ok: true, rows, corrupt, total: rows.length, effective, file };
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/**
|
|
401
|
+
* 回滚一条反馈(校验 entry 存在、恢复 before 值、写审计行)。
|
|
402
|
+
* @param {{memoryRoot?: string, entryId: string, now?: unknown}} input
|
|
403
|
+
*/
|
|
404
|
+
export function rollbackFeedback(input = {}, config = {}) {
|
|
405
|
+
return memoryFeedback({ ...input, action: 'rollback' }, config);
|
|
406
|
+
}
|
|
@@ -0,0 +1,218 @@
|
|
|
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
|
+
// M11: 统一召回入口(brain.mjs)——空命中时给出候选线索,不改变 hits/证据门形状。
|
|
17
|
+
import { selectCards as brainSelectCards } from '../recall/brain.mjs';
|
|
18
|
+
|
|
19
|
+
export const RECALL_V2_SCHEMA = 'memory-recall-v2/v1';
|
|
20
|
+
export const FAST_ANSWER_MAX_CHARS = 300;
|
|
21
|
+
|
|
22
|
+
const VALUE_PATTERNS = Object.freeze([
|
|
23
|
+
{ type: 'version', re: /v?\d+\.\d+(?:\.\d+)?(?:-[A-Za-z0-9.]+)?/u },
|
|
24
|
+
{ type: 'path', re: /(?:[A-Za-z]:[\\/]|\/)[^\s,。;;))】\]]+|(?:[\w.-]+[\\/])+[\w.-]+\.(?:md|mjs|js|json|jsonl|ps1|tgz|txt|html)\b/u },
|
|
25
|
+
{ type: 'time', re: /\d{1,2}:\d{2}(?::\d{2})?|\d{4}-\d{2}-\d{2}/u },
|
|
26
|
+
{ type: 'number', re: /\d+(?:\.\d+)?\s*(?:MB|GB|KB|ms|秒|分钟|小时|条|轮|个|%|分)?/u },
|
|
27
|
+
]);
|
|
28
|
+
|
|
29
|
+
export const FAST_ANSWER_TARGETS = Object.freeze({
|
|
30
|
+
version: 0.9,
|
|
31
|
+
path: 0.9,
|
|
32
|
+
time: 0.85,
|
|
33
|
+
number: 0.8,
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
/** Detect the value type a question is asking for (or null => not fast eligible). */
|
|
37
|
+
export function questionValueType(question) {
|
|
38
|
+
const text = String(question ?? '');
|
|
39
|
+
if (/版本号?|version|tag/i.test(text)) return 'version';
|
|
40
|
+
if (/路径|文件(?:名|在哪)|放哪|在哪(?:个)?文件|哪个文件/i.test(text)) return 'path';
|
|
41
|
+
if (/几点|时间|日期|什么时候|哪天|多久|多少分钟|空窗/i.test(text)) return 'time';
|
|
42
|
+
if (/多少|几个|数量|大小|多大|多久|几轮|几条|百分比|%/.test(text)) return 'number';
|
|
43
|
+
// no explicit ask type: only allow a value literal present in the question
|
|
44
|
+
for (const { type, re } of VALUE_PATTERNS) if (re.test(text)) return type;
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function detectValueType(text) {
|
|
49
|
+
const value = String(text ?? '');
|
|
50
|
+
for (const { type, re } of VALUE_PATTERNS) if (re.test(value)) return type;
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function excerptValueMatches(questionType, excerpt) {
|
|
55
|
+
if (questionType === null) return false;
|
|
56
|
+
for (const { type, re } of VALUE_PATTERNS) {
|
|
57
|
+
if (type !== questionType) continue;
|
|
58
|
+
return re.test(String(excerpt ?? ''));
|
|
59
|
+
}
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Evidence gate: decide confidence / fast eligibility / fallback. Fail-safe: any
|
|
65
|
+
* uncertainty => model path, never a guessed fast answer.
|
|
66
|
+
*/
|
|
67
|
+
export function evidenceGate({ hits = [], question = '' } = {}) {
|
|
68
|
+
const list = Array.isArray(hits) ? hits : [];
|
|
69
|
+
if (list.length === 0) {
|
|
70
|
+
return { pass: false, confidence: 'none', fastEligible: false, code: 'E_NO_EVIDENCE', fallback: 'model', reason: 'no-hit' };
|
|
71
|
+
}
|
|
72
|
+
if (list.some((hit) => hit?.conflict === true) || list.some((hit) => hit?.anchor?.status === 'conflict')) {
|
|
73
|
+
return { pass: true, confidence: 'low', fastEligible: false, code: 'E_EVIDENCE_CONFLICT', fallback: 'model', reason: 'conflict' };
|
|
74
|
+
}
|
|
75
|
+
const questionType = questionValueType(question);
|
|
76
|
+
const withValue = list.filter((hit) => excerptValueMatches(questionType, hit?.quote ?? hit?.excerpt ?? ''));
|
|
77
|
+
if (list.length > 1) {
|
|
78
|
+
const top = Number(list[0]?.score ?? 0);
|
|
79
|
+
const second = Number(list[1]?.score ?? 0);
|
|
80
|
+
const close = Number.isFinite(top) && Number.isFinite(second) && Math.abs(top - second) < 0.1;
|
|
81
|
+
if (questionType !== null && withValue.length === 1 && !close) {
|
|
82
|
+
return { pass: true, confidence: 'high', fastEligible: true, code: null, fallback: null, reason: 'single-value-hit' };
|
|
83
|
+
}
|
|
84
|
+
return { pass: true, confidence: close ? 'low' : 'medium', fastEligible: false, code: close ? 'E_EVIDENCE_AMBIGUOUS' : null, fallback: 'model', reason: close ? 'ambiguous' : 'multi-hit' };
|
|
85
|
+
}
|
|
86
|
+
const only = list[0];
|
|
87
|
+
const anchorStatus = only?.anchor?.status ?? 'live';
|
|
88
|
+
if (anchorStatus !== 'live') {
|
|
89
|
+
return { pass: false, confidence: 'low', fastEligible: false, code: 'E_ANCHOR_NOT_LIVE', fallback: 'model', reason: 'stale-anchor' };
|
|
90
|
+
}
|
|
91
|
+
if (questionType !== null && withValue.length === 1) {
|
|
92
|
+
return { pass: true, confidence: 'high', fastEligible: true, code: null, fallback: null, reason: 'single-value-hit' };
|
|
93
|
+
}
|
|
94
|
+
return { pass: true, confidence: 'medium', fastEligible: false, code: null, fallback: 'model', reason: 'value-type-mismatch' };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Deterministic fast answer: quote + coordinate, no generation. */
|
|
98
|
+
export function buildFastAnswer({ question = '', hit = null, gate = null } = {}) {
|
|
99
|
+
if (!hit || (gate && gate.fastEligible !== true)) return null;
|
|
100
|
+
const quote = String(hit.quote ?? hit.excerpt ?? '').replace(/\s+/gu, ' ').trim();
|
|
101
|
+
if (quote === '') return null;
|
|
102
|
+
const anchor = hit.anchor ?? {};
|
|
103
|
+
const coordinateParts = [];
|
|
104
|
+
if (typeof hit.card === 'string') coordinateParts.push(hit.card);
|
|
105
|
+
if (typeof anchor.file === 'string') coordinateParts.push(anchor.file);
|
|
106
|
+
if (Number.isInteger(anchor.turn)) coordinateParts.push(`第 ${anchor.turn} 轮`);
|
|
107
|
+
const coordinate = coordinateParts.length > 0 ? coordinateParts.join(' · ') : '卡锚点';
|
|
108
|
+
const valueType = detectValueType(quote) ?? questionValueType(question);
|
|
109
|
+
const text = `${quote}(坐标:${coordinate})`.slice(0, FAST_ANSWER_MAX_CHARS);
|
|
110
|
+
return { text, quote, anchor, valueType, confidence: 'high', deterministic: true, question: String(question ?? '').slice(0, 120) };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Trim a card date (YYYY-MM-DD / ISO) to ms; null when absent. */
|
|
114
|
+
function dateMs(value) {
|
|
115
|
+
if (typeof value !== 'string' || value.trim() === '') return null;
|
|
116
|
+
const ms = Date.parse(value);
|
|
117
|
+
return Number.isFinite(ms) ? ms : null;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** memory_recall_v2 tool entry: multi-route recall + evidence gate + fast answer. */
|
|
121
|
+
export function recallV2(args = {}, config = {}) {
|
|
122
|
+
const rawQuery = args?.query;
|
|
123
|
+
if (typeof rawQuery !== 'string' || rawQuery.trim() === '') {
|
|
124
|
+
throw memoryError('E_RECALL_EMPTY_QUERY', 'memory_recall_v2 需要 query(自然语言或关键词)。');
|
|
125
|
+
}
|
|
126
|
+
const query = rawQuery.trim();
|
|
127
|
+
const topK = Math.max(1, Math.min(10, Number.isInteger(args?.topK) ? Number(args.topK) : 3));
|
|
128
|
+
const includeForgotten = args?.includeForgotten === true;
|
|
129
|
+
const project = typeof args?.project === 'string' && args.project.trim() !== '' ? args.project.trim() : null;
|
|
130
|
+
const sinceMs = dateMs(args?.since);
|
|
131
|
+
const untilMs = dateMs(args?.until);
|
|
132
|
+
const root = memoryRootFromConfig(config);
|
|
133
|
+
|
|
134
|
+
const recalled = memoryRecall({ query, topK: Math.max(topK, 5), status: includeForgotten ? 'any' : 'active' }, { memoryRoot: root });
|
|
135
|
+
const cards = new Map((scanCards(root) || []).map((card) => [card.rel, card]));
|
|
136
|
+
let hits = [];
|
|
137
|
+
for (const row of Array.isArray(recalled.results) ? recalled.results : []) {
|
|
138
|
+
if (row?.type === 'event') continue; // D2: event/AutoCard layer is cold archive, not recalled.
|
|
139
|
+
const card = cards.get(row.path);
|
|
140
|
+
const cardFields = card?.fields ?? {};
|
|
141
|
+
const cardStatus = cardFields.status ?? 'active';
|
|
142
|
+
if (!includeForgotten && (cardStatus === 'archived' || cardStatus === 'forgotten')) continue;
|
|
143
|
+
if (project !== null) {
|
|
144
|
+
const fields = cardFields;
|
|
145
|
+
const cardProject = typeof fields.project === 'string' ? fields.project : null;
|
|
146
|
+
if (cardProject !== null && cardProject !== project) continue;
|
|
147
|
+
}
|
|
148
|
+
const ms = dateMs(card?.fields?.date ?? card?.date);
|
|
149
|
+
if (sinceMs !== null && ms !== null && ms < sinceMs) continue;
|
|
150
|
+
if (untilMs !== null && ms !== null && ms > untilMs) continue;
|
|
151
|
+
const status = cardStatus;
|
|
152
|
+
hits.push({
|
|
153
|
+
card: row.path,
|
|
154
|
+
anchor: { kind: 'file', file: row.path, line: null, status: status === 'archived' || status === 'forgotten' ? 'stale' : 'live' },
|
|
155
|
+
quote: String(row.excerpt ?? '').replace(/\s+/gu, ' ').trim().slice(0, 240),
|
|
156
|
+
score: Number(row.score ?? 0),
|
|
157
|
+
});
|
|
158
|
+
if (hits.length >= topK) break;
|
|
159
|
+
}
|
|
160
|
+
// M11 委托 brain.mjs:本路零命中时,用统一召回入口的选卡结果补 didYouMean(只给线索,
|
|
161
|
+
// 不伪造 hits、不放宽证据门;brain 不可用/无命中时保持空数组,输出与改造前一致)。
|
|
162
|
+
let didYouMean = [];
|
|
163
|
+
if (hits.length === 0) {
|
|
164
|
+
try {
|
|
165
|
+
const candidates = brainSelectCards(root, query, { maxItems: 5 });
|
|
166
|
+
didYouMean = (Array.isArray(candidates?.items) ? candidates.items : [])
|
|
167
|
+
.map((item) => String(item.title ?? '')).filter((title) => title !== '').slice(0, 5);
|
|
168
|
+
} catch { /* 委托失败不改写召回结论 */ }
|
|
169
|
+
}
|
|
170
|
+
const gate = evidenceGate({ hits, question: query });
|
|
171
|
+
// 1.8.2 D2: no auto-card read; hits are curated cards only.
|
|
172
|
+
const curatedHits = hits.slice(0, Math.min(2, topK));
|
|
173
|
+
hits = [...curatedHits].slice(0, topK);
|
|
174
|
+
const finalGate = evidenceGate({ hits, question: query });
|
|
175
|
+
const fastAnswer = finalGate.fastEligible ? buildFastAnswer({ question: query, hit: hits[0], gate: finalGate }) : null;
|
|
176
|
+
// §16.8-D: every recall entry writes one unified read-audit row (行数=调用数).
|
|
177
|
+
try {
|
|
178
|
+
appendAuditRecord({
|
|
179
|
+
memoryRoot: root,
|
|
180
|
+
action: 'read',
|
|
181
|
+
recordId: hits.length > 0 ? hits.map((hit) => hit.card).join(',') : null,
|
|
182
|
+
readerTier: typeof args?.readerTier === 'string' && args.readerTier !== '' ? args.readerTier : 'agent',
|
|
183
|
+
questionId: 'unknown',
|
|
184
|
+
expectedTurns: null,
|
|
185
|
+
answerText: null,
|
|
186
|
+
extra: { entry: 'memory_recall_v2', count: hits.length, confidence: finalGate.confidence, fastAnswer: fastAnswer !== null },
|
|
187
|
+
});
|
|
188
|
+
} catch { /* read audit must never break recall */ }
|
|
189
|
+
return {
|
|
190
|
+
schema: RECALL_V2_SCHEMA,
|
|
191
|
+
ok: true,
|
|
192
|
+
query,
|
|
193
|
+
topK,
|
|
194
|
+
includeForgotten,
|
|
195
|
+
confidence: finalGate.confidence,
|
|
196
|
+
hits,
|
|
197
|
+
didYouMean,
|
|
198
|
+
slowPath: fastAnswer === null,
|
|
199
|
+
fastAnswer,
|
|
200
|
+
evidenceGate: finalGate,
|
|
201
|
+
fallback: finalGate.fallback,
|
|
202
|
+
...(hits.length === 0 ? { status: 'empty', code: 'E_NO_EVIDENCE', hint: '没有可引用证据:请直说未找到,不要猜。' } : { status: 'ok' }),
|
|
203
|
+
...(finalGate.code ? { code: finalGate.code } : {}),
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Adapter for pre-step recall results (items from recall-core) → evidence package fastAnswer. */
|
|
208
|
+
export function fastAnswerFromRecallItems({ question = '', items = [] } = {}) {
|
|
209
|
+
const hits = (Array.isArray(items) ? items : []).map((item) => ({
|
|
210
|
+
card: item.path,
|
|
211
|
+
anchor: { kind: 'file', file: item.path, line: null, status: 'live' },
|
|
212
|
+
quote: String(item.excerpt ?? item.title ?? '').replace(/\s+/gu, ' ').trim(),
|
|
213
|
+
score: Number(item.score ?? 0),
|
|
214
|
+
}));
|
|
215
|
+
const gate = evidenceGate({ hits, question });
|
|
216
|
+
if (!gate.fastEligible) return { fastAnswer: null, gate };
|
|
217
|
+
return { fastAnswer: buildFastAnswer({ question, hit: hits[0], gate }), gate };
|
|
218
|
+
}
|