@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,235 @@
|
|
|
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
|
+
}
|
|
108
|
+
|
|
109
|
+
// ---------------------------------------------------------------------------
|
|
110
|
+
// 批 C(M20):historical 迁移(写生命周期轴 + 可选归档移动)
|
|
111
|
+
// ---------------------------------------------------------------------------
|
|
112
|
+
|
|
113
|
+
/** 把 lifecycle:historical 写进 frontmatter(只动这一行,不动正文与其它字段)。 */
|
|
114
|
+
function withHistoricalFrontmatter(text) {
|
|
115
|
+
const src = typeof text === 'string' ? text : '';
|
|
116
|
+
const block = /^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(\r?\n|$)/.exec(src);
|
|
117
|
+
if (!block) return `---\nlifecycle: historical\n---\n\n${src}`;
|
|
118
|
+
if (/^[ \t]*lifecycle[ \t]*:/m.test(block[1])) {
|
|
119
|
+
return src.replace(/^([ \t]*lifecycle[ \t]*:[ \t]*).+$/m, '$1historical');
|
|
120
|
+
}
|
|
121
|
+
return `---\n${block[1]}\nlifecycle: historical\n---\n${src.slice(block[0].length)}`;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function resolveCardFile(memoryRoot, rel) {
|
|
125
|
+
if (typeof rel !== 'string' || rel.trim() === '') return null;
|
|
126
|
+
return path.isAbsolute(rel) ? rel : path.resolve(String(memoryRoot), rel);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* 标记单张卡为 historical(幂等;已是 historical 则 written:false)。
|
|
131
|
+
* 绝不改 status,绝不删正文;写失败抛错,不静默成功。
|
|
132
|
+
*/
|
|
133
|
+
export function markCardHistorical(memoryRoot, rel, { now = new Date() } = {}) {
|
|
134
|
+
const file = resolveCardFile(memoryRoot, rel);
|
|
135
|
+
if (!file) throw Object.assign(new Error('E_LIFECYCLE_PATH'), { code: 'E_LIFECYCLE_PATH' });
|
|
136
|
+
if (readLifecycleFromText(safeRead(file)) === 'historical') {
|
|
137
|
+
return { ok: true, written: false, rel, lifecycle: 'historical' };
|
|
138
|
+
}
|
|
139
|
+
const src = safeRead(file);
|
|
140
|
+
if (src === null) throw Object.assign(new Error('E_LIFECYCLE_SOURCE_MISSING'), { code: 'E_LIFECYCLE_SOURCE_MISSING' });
|
|
141
|
+
const next = withHistoricalFrontmatter(src);
|
|
142
|
+
const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
|
|
143
|
+
fs.writeFileSync(tmp, next, 'utf8');
|
|
144
|
+
fs.renameSync(tmp, file);
|
|
145
|
+
return { ok: true, written: true, rel, lifecycle: 'historical', at: (now instanceof Date ? now : new Date(now)).toISOString() };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function safeRead(file) {
|
|
149
|
+
try {
|
|
150
|
+
return fs.readFileSync(file, 'utf8');
|
|
151
|
+
} catch {
|
|
152
|
+
return null;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* 迁移入口(批 C):把给定卡片或「带取代标记的卡」标为 historical。
|
|
158
|
+
*
|
|
159
|
+
* - cards: 显式相对路径列表(夹具/维护链用)
|
|
160
|
+
* - autoDetect: true 时扫描 topics/ 下 frontmatter 含 superseded_by / replaced_by 的卡
|
|
161
|
+
* - archive: true 时移动到 topics/archive/<YYYY-MM>/(不删内容;INDEX 重建由 archive.mjs 负责)
|
|
162
|
+
*
|
|
163
|
+
* 默认只写 lifecycle 字段,不动文件位置——历史过滤(默认召回/注入不含 historical)
|
|
164
|
+
* 由已有的 recall / trust 路径读取该字段生效。
|
|
165
|
+
*/
|
|
166
|
+
export function migrateHistorical({
|
|
167
|
+
memoryRoot,
|
|
168
|
+
now = new Date(),
|
|
169
|
+
cards = null,
|
|
170
|
+
autoDetect = true,
|
|
171
|
+
archive = false,
|
|
172
|
+
} = {}) {
|
|
173
|
+
const root = typeof memoryRoot === 'string' && memoryRoot.trim() !== '' ? path.resolve(memoryRoot) : null;
|
|
174
|
+
if (!root) return { ok: false, reason: 'no-memory-root' };
|
|
175
|
+
const at = now instanceof Date ? now : new Date(now ?? Date.now());
|
|
176
|
+
const month = `${at.getFullYear()}-${String(at.getMonth() + 1).padStart(2, '0')}`;
|
|
177
|
+
const candidates = new Set();
|
|
178
|
+
if (Array.isArray(cards)) {
|
|
179
|
+
for (const rel of cards) if (typeof rel === 'string' && rel.trim() !== '') candidates.add(rel.replace(/\\/g, '/'));
|
|
180
|
+
}
|
|
181
|
+
if (autoDetect === true && candidates.size === 0) {
|
|
182
|
+
const topics = path.join(root, 'topics');
|
|
183
|
+
const walk = (dir) => {
|
|
184
|
+
let entries = [];
|
|
185
|
+
try {
|
|
186
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
187
|
+
} catch {
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
for (const entry of entries) {
|
|
191
|
+
const abs = path.join(dir, entry.name);
|
|
192
|
+
if (entry.isDirectory()) {
|
|
193
|
+
if (entry.name === 'archive') continue;
|
|
194
|
+
walk(abs);
|
|
195
|
+
} else if (entry.name.endsWith('.md')) {
|
|
196
|
+
const text = safeRead(abs);
|
|
197
|
+
if (text === null) continue;
|
|
198
|
+
if (/^[ \t]*(superseded_by|replaced_by)[ \t]*:/m.test(text)) {
|
|
199
|
+
candidates.add(path.relative(root, abs).replace(/\\/g, '/'));
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
walk(topics);
|
|
205
|
+
}
|
|
206
|
+
const report = { ok: true, scanned: candidates.size, migrated: 0, moved: 0, written: [], moved_to: [], errors: [] };
|
|
207
|
+
for (const rel of candidates) {
|
|
208
|
+
try {
|
|
209
|
+
let targetRel = rel;
|
|
210
|
+
if (archive === true) {
|
|
211
|
+
const toRel = `topics/archive/${month}/${path.basename(rel)}`;
|
|
212
|
+
const fromAbs = path.resolve(root, rel);
|
|
213
|
+
const toAbs = path.resolve(root, toRel);
|
|
214
|
+
if (!fs.existsSync(fromAbs)) throw Object.assign(new Error('E_LIFECYCLE_SOURCE_MISSING'), { code: 'E_LIFECYCLE_SOURCE_MISSING' });
|
|
215
|
+
fs.mkdirSync(path.dirname(toAbs), { recursive: true });
|
|
216
|
+
if (fs.existsSync(toAbs)) throw Object.assign(new Error('E_LIFECYCLE_TARGET_EXISTS'), { code: 'E_LIFECYCLE_TARGET_EXISTS' });
|
|
217
|
+
// 先写历史字段,再移动:移动后不会留下未标 historical 的旧卡。
|
|
218
|
+
const marked = markCardHistorical(root, rel, { now: at });
|
|
219
|
+
fs.renameSync(fromAbs, toAbs);
|
|
220
|
+
targetRel = toRel;
|
|
221
|
+
report.moved += 1;
|
|
222
|
+
report.moved_to.push({ from: rel, to: toRel, written: marked.written });
|
|
223
|
+
} else {
|
|
224
|
+
const marked = markCardHistorical(root, rel, { now: at });
|
|
225
|
+
report.written.push({ rel, written: marked.written });
|
|
226
|
+
}
|
|
227
|
+
report.migrated += 1;
|
|
228
|
+
} catch (error) {
|
|
229
|
+
report.errors.push({ rel, code: String(error?.code ?? error?.message ?? error) });
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
if (report.errors.length > 0) report.ok = false;
|
|
233
|
+
report.at = (at instanceof Date ? at : new Date()).toISOString();
|
|
234
|
+
return report;
|
|
235
|
+
}
|
|
@@ -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
|
+
}
|