@jjh32456/longlive 0.0.0-stage → 1.8.12
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 +205 -0
- package/LICENSE +21 -0
- package/QUICKSTART.md +363 -0
- package/README.en.md +55 -0
- package/README.md +225 -2
- package/SPEC.md +211 -0
- package/build-info.json +1555 -0
- package/cordis.patch.yml +177 -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 +807 -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 +46 -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 +160 -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-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/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 +146 -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 +824 -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 +912 -0
- package/src/handoff/index.js +944 -0
- package/src/handoff/model.js +1010 -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 +657 -0
- package/src/identity/index.js +337 -0
- package/src/identity/inject-position.js +131 -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 +124 -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/audit-records.js +222 -0
- package/src/memory/auto-cards.js +441 -0
- package/src/memory/capture-host.js +228 -0
- package/src/memory/capture.js +457 -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/conclusion-distill.js +332 -0
- package/src/memory/conclusion-drafts.js +239 -0
- package/src/memory/conflicts.js +147 -0
- package/src/memory/consolidate.js +815 -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 +410 -0
- package/src/memory/forget.js +512 -0
- package/src/memory/frames-activation.js +247 -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 +362 -0
- package/src/memory/l2-gate.js +169 -0
- package/src/memory/lifecycle.js +107 -0
- package/src/memory/lock.js +121 -0
- package/src/memory/maintenance.js +785 -0
- package/src/memory/manifest.js +245 -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.js +963 -0
- package/src/memory/provenance.js +119 -0
- package/src/memory/recall-v2.js +206 -0
- package/src/memory/recall.js +256 -0
- package/src/memory/reconcile.js +265 -0
- package/src/memory/records.js +433 -0
- package/src/memory/reinforce.js +145 -0
- package/src/memory/retention.js +128 -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/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 +189 -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-fallback.mjs +235 -0
- package/src/recall/archive-search.mjs +425 -0
- package/src/recall/cards.mjs +202 -0
- package/src/recall/edges.js +379 -0
- package/src/recall/embedding.mjs +698 -0
- package/src/recall/entities.mjs +112 -0
- package/src/recall/explain.mjs +433 -0
- package/src/recall/force-policy.mjs +138 -0
- package/src/recall/index.js +1036 -0
- package/src/recall/inject-order.mjs +277 -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 +765 -0
- package/src/recall/shared-visibility.js +302 -0
- package/src/recall/time-normalizer.mjs +196 -0
- package/src/retention/config.js +106 -0
- package/src/retention/index.js +643 -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 +3146 -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,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,107 @@
|
|
|
1
|
+
// lifecycle.js — 1.8.11 记忆卡生命周期(独立于 status 的第二条轴)
|
|
2
|
+
//
|
|
3
|
+
// 契约(SPEC-1.8.11 D1 / 红队 E1):
|
|
4
|
+
// - 绝不读写 `status`;`status` 仍只有 active / locked / archived。
|
|
5
|
+
// - `lifecycle` 缺失 = 普通卡(不写默认值;迁移只写需要降级的卡)。
|
|
6
|
+
// - 只有两个值:canonical(现行口径)与 historical(历史口径)。
|
|
7
|
+
// - 排序:canonical rank=0 / 普通 rank=1 / historical rank=2。
|
|
8
|
+
//
|
|
9
|
+
// 写入用 frontmatter.js 的 updateExtras(text, { lifecycle })(未知键走 extras)。
|
|
10
|
+
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
|
|
14
|
+
export const LIFECYCLE_VALUES = Object.freeze(['canonical', 'historical']);
|
|
15
|
+
|
|
16
|
+
/** @typedef {'canonical'|'historical'} Lifecycle */
|
|
17
|
+
|
|
18
|
+
export function normalizeLifecycleValue(value) {
|
|
19
|
+
if (value == null) return null;
|
|
20
|
+
const text = String(value).trim().toLowerCase();
|
|
21
|
+
return LIFECYCLE_VALUES.includes(text) ? text : null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* 从卡片对象或 parseFrontmatter 结果里读 lifecycle。
|
|
26
|
+
* 兼容形状:{ lifecycle } / { extras:{ lifecycle } } / { fields:{ lifecycle } }。
|
|
27
|
+
* 非法值按 null(普通卡)处理,不抛——读路径必须 fail-open。
|
|
28
|
+
*/
|
|
29
|
+
export function readLifecycle(cardOrFrontmatter) {
|
|
30
|
+
if (!cardOrFrontmatter || typeof cardOrFrontmatter !== 'object') return null;
|
|
31
|
+
const direct = normalizeLifecycleValue(cardOrFrontmatter.lifecycle);
|
|
32
|
+
if (direct) return direct;
|
|
33
|
+
const extra = normalizeLifecycleValue(cardOrFrontmatter.extras?.lifecycle);
|
|
34
|
+
if (extra) return extra;
|
|
35
|
+
const field = normalizeLifecycleValue(cardOrFrontmatter.fields?.lifecycle);
|
|
36
|
+
if (field) return field;
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function isCanonical(card) {
|
|
41
|
+
return readLifecycle(card) === 'canonical';
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function isHistorical(card) {
|
|
45
|
+
return readLifecycle(card) === 'historical';
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// 显式历史查询词:只有用户真的在问「以前/旧版/被取代」时,才允许历史卡不降权。
|
|
49
|
+
// 单一实现(D9):recall/edges.js 与 memory/recall.js 都从这里取,不许两份正则。
|
|
50
|
+
const HISTORY_QUERY_RE = /以前|之前|旧版|旧口径|历史|被取代|原来的|早先|老版|上一版|作废/;
|
|
51
|
+
|
|
52
|
+
export function isHistoricalQuery(queryText) {
|
|
53
|
+
return HISTORY_QUERY_RE.test(String(queryText ?? ''));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* 排序键:canonical=0 / 普通=1 / historical=2。
|
|
58
|
+
* 接受卡片对象、路径字符串(配合 options.memoryRoot 解析相对路径)或 frontmatter。
|
|
59
|
+
*/
|
|
60
|
+
export function lifecycleRank(card, options = {}) {
|
|
61
|
+
const value = typeof card === 'string'
|
|
62
|
+
? readCardLifecycle(card, options)
|
|
63
|
+
: readLifecycle(card);
|
|
64
|
+
if (value === 'canonical') return 0;
|
|
65
|
+
if (value === 'historical') return 2;
|
|
66
|
+
return 1;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* 从整篇卡文本里只取 lifecycle 行。
|
|
71
|
+
* 不复用 memory/frontmatter.js 的 parseFrontmatter:那张解析器对 `scope_in:` 这类
|
|
72
|
+
* 块状列表会抛 E_FRONTMATTER_MULTILINE(记忆卡自己用,但召回 topics 卡普遍是块状),
|
|
73
|
+
* 读 lifecycle 不能让整张卡因为无关字段解析失败。这里只做「找 frontmatter 块 + 找一行」,
|
|
74
|
+
* 与 cards.mjs 的宽容解析口径一致。
|
|
75
|
+
*/
|
|
76
|
+
export function readLifecycleFromText(text) {
|
|
77
|
+
if (typeof text !== 'string') return null;
|
|
78
|
+
const src = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
|
|
79
|
+
const block = /^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(\r?\n|$)/.exec(src);
|
|
80
|
+
if (!block) return null;
|
|
81
|
+
const line = /^[ \t]*lifecycle[ \t]*:[ \t]*(.+?)[ \t]*$/m.exec(block[1]);
|
|
82
|
+
return line ? normalizeLifecycleValue(line[1]) : null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* 按路径读卡 lifecycle。读失败/文件不存在/坏 frontmatter 一律返回 null(fail-open),
|
|
87
|
+
* 绝不因为读卡失败把普通卡当成 historical。
|
|
88
|
+
* @param {string} cardPath 绝对路径,或相对 memoryRoot 的路径
|
|
89
|
+
* @param {{memoryRoot?: string}} options
|
|
90
|
+
*/
|
|
91
|
+
export function readCardLifecycle(cardPath, options = {}) {
|
|
92
|
+
if (typeof cardPath !== 'string' || cardPath.trim() === '') return null;
|
|
93
|
+
let file = cardPath;
|
|
94
|
+
if (!path.isAbsolute(file) && options.memoryRoot) {
|
|
95
|
+
file = path.resolve(options.memoryRoot, file);
|
|
96
|
+
}
|
|
97
|
+
try {
|
|
98
|
+
return readLifecycleFromText(fs.readFileSync(file, 'utf8'));
|
|
99
|
+
} catch {
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** 给渲染层用:历史卡要带一行标注,现行卡不标注。 */
|
|
105
|
+
export function lifecycleLabel(card) {
|
|
106
|
+
return isHistorical(card) ? '历史口径' : null;
|
|
107
|
+
}
|
|
@@ -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
|
+
}
|