@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,845 @@
|
|
|
1
|
+
// identity-router v0 — 开机卡(open card)核心
|
|
2
|
+
//
|
|
3
|
+
// 纯函数优先:解析 / 选卡 / 截断 / 拼装都不碰全局状态,方便单测。
|
|
4
|
+
// 只有 collectOpenCard / readTextFile / listHandoverCards 做只读文件 IO。
|
|
5
|
+
//
|
|
6
|
+
// 数据来源只允许两处(v0 硬边界,见 DESIGN.md):
|
|
7
|
+
// <memoryRoot>/STATE.md
|
|
8
|
+
// <memoryRoot>/handover/*.md
|
|
9
|
+
// 绝不写 memoryRoot。
|
|
10
|
+
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import { dshHome } from '../home.js';
|
|
14
|
+
import { DEFAULT_MEMORY_DIRNAME } from '../memory/paths.js';
|
|
15
|
+
|
|
16
|
+
/** 默认记忆根:<DSH home>/longlive-memory,与 memory_* 工具同一条解析链。
|
|
17
|
+
* 可用 config.memoryRoot / DSH_IDENTITY_MEMORY_ROOT / DSH_LONGLIVE_MEMORY_ROOT 覆盖。 */
|
|
18
|
+
export const DEFAULT_MEMORY_ROOT = path.join(dshHome(), DEFAULT_MEMORY_DIRNAME);
|
|
19
|
+
|
|
20
|
+
/** 开机卡默认上限(按 Unicode 码点计,一个汉字 = 1)。 */
|
|
21
|
+
export const DEFAULT_MAX_CHARS = 800;
|
|
22
|
+
|
|
23
|
+
/** STATE.md 里要抓的三节(精确名,允许末尾括号注释)。 */
|
|
24
|
+
export const STATE_SECTIONS = Object.freeze({
|
|
25
|
+
where: '我在哪',
|
|
26
|
+
waiting: '在等什么',
|
|
27
|
+
recent: '最近三件',
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
/** 卡片里缺失内容时的占位,不编造。 */
|
|
31
|
+
export const MISSING_TEXT = '(STATE.md 里没有这一节)';
|
|
32
|
+
|
|
33
|
+
/** 文件读不到时的统一返回,不抛异常。 */
|
|
34
|
+
const EMPTY_READ = Object.freeze({ ok: false, text: '', error: 'ENOENT' });
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* 统一换行并去掉 BOM。BOM 是这台机器上踩过的坑:带 BOM 的 JSON 会被宿主拒绝,
|
|
38
|
+
* 文本卡虽然宽松,但解析标题时 BOM 会粘在第一个 '#' 前面。
|
|
39
|
+
* @param {unknown} input
|
|
40
|
+
* @returns {string}
|
|
41
|
+
*/
|
|
42
|
+
export function normalizeText(input) {
|
|
43
|
+
if (typeof input !== 'string') return '';
|
|
44
|
+
return input.replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n');
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* 按 Unicode 码点计数,避免把 emoji / 代理对算成两个字。
|
|
49
|
+
* @param {unknown} input
|
|
50
|
+
* @returns {number}
|
|
51
|
+
*/
|
|
52
|
+
export function charLength(input) {
|
|
53
|
+
return Array.from(typeof input === 'string' ? input : String(input ?? '')).length;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* 按码点截断;超长时保留 max-1 个字符再加省略号,返回值长度恒 <= max。
|
|
58
|
+
* @param {unknown} input
|
|
59
|
+
* @param {number} max
|
|
60
|
+
* @returns {{text: string, truncated: boolean}}
|
|
61
|
+
*/
|
|
62
|
+
export function truncateChars(input, max) {
|
|
63
|
+
const text = typeof input === 'string' ? input : String(input ?? '');
|
|
64
|
+
const chars = Array.from(text);
|
|
65
|
+
const limit = Number.isFinite(max) ? Math.max(0, Math.floor(max)) : 0;
|
|
66
|
+
if (chars.length <= limit) return { text, truncated: false };
|
|
67
|
+
if (limit <= 0) return { text: '', truncated: true };
|
|
68
|
+
const body = chars.slice(0, limit - 1).join('').replace(/\s+$/u, '');
|
|
69
|
+
return { text: `${body}…`, truncated: true };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* 标题归一化:去掉 markdown 强调、前导编号、末尾括号注释与标点,压缩空白。
|
|
74
|
+
* 目的:`## 我在哪(2026-11-03 更新)` 能匹配 `我在哪`,但 `我现在在哪` 不能。
|
|
75
|
+
* @param {unknown} input
|
|
76
|
+
* @returns {string}
|
|
77
|
+
*/
|
|
78
|
+
export function normalizeHeading(input) {
|
|
79
|
+
let title = normalizeText(input).trim();
|
|
80
|
+
title = title.replace(/^\s*#{1,6}\s*/, '');
|
|
81
|
+
title = title.replace(/\*\*|__|`/g, '');
|
|
82
|
+
title = title.replace(/^\s*(?:\d+[.、)]|[一二三四五六七八九十]+、)\s*/, '');
|
|
83
|
+
// 允许嵌套一层括号,循环剥掉末尾的「(...)」「(...)」。
|
|
84
|
+
for (let i = 0; i < 3; i += 1) {
|
|
85
|
+
const next = title.replace(/\s*[((][^()()]*[))]\s*$/u, '').trim();
|
|
86
|
+
if (next === title) break;
|
|
87
|
+
title = next;
|
|
88
|
+
}
|
|
89
|
+
title = title.replace(/[::]\s*$/u, '').trim();
|
|
90
|
+
return title.replace(/\s+/gu, ' ').toLowerCase();
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* 解析 ATX 标题;代码围栏里的 `##` 不算标题(STATE.md 里有命令块)。
|
|
95
|
+
* @param {unknown} markdown
|
|
96
|
+
* @returns {Array<{level:number,title:string,line:number,content:string}>}
|
|
97
|
+
*/
|
|
98
|
+
export function extractSections(markdown) {
|
|
99
|
+
const lines = normalizeText(markdown).split('\n');
|
|
100
|
+
const sections = [];
|
|
101
|
+
let current = null;
|
|
102
|
+
let fence = null;
|
|
103
|
+
|
|
104
|
+
for (let index = 0; index < lines.length; index += 1) {
|
|
105
|
+
const line = lines[index];
|
|
106
|
+
const fenceMatch = /^\s{0,3}(`{3,}|~{3,})/.exec(line);
|
|
107
|
+
if (fenceMatch) {
|
|
108
|
+
const mark = fenceMatch[1][0];
|
|
109
|
+
if (fence === null) fence = mark;
|
|
110
|
+
else if (fence === mark) fence = null;
|
|
111
|
+
if (current) current.lines.push(line);
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
if (fence !== null) {
|
|
115
|
+
if (current) current.lines.push(line);
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const heading = /^(#{1,6})[ \t]+(.+?)[ \t]*$/.exec(line);
|
|
120
|
+
if (heading) {
|
|
121
|
+
const title = heading[2].replace(/[ \t]+#+[ \t]*$/u, '').trim();
|
|
122
|
+
current = { level: heading[1].length, title, line: index + 1, lines: [] };
|
|
123
|
+
sections.push(current);
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if (current) current.lines.push(line);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
return sections.map((section) => ({
|
|
130
|
+
level: section.level,
|
|
131
|
+
title: section.title,
|
|
132
|
+
line: section.line,
|
|
133
|
+
content: section.lines.join('\n').trim(),
|
|
134
|
+
}));
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* 找一节。同名多份时优先 level 2(`##`),再按出现顺序取第一份。
|
|
139
|
+
* @param {Array<{level:number,title:string,content:string,line:number}>} sections
|
|
140
|
+
* @param {string} wanted
|
|
141
|
+
* @returns {{level:number,title:string,content:string,line:number}|null}
|
|
142
|
+
*/
|
|
143
|
+
export function findSection(sections, wanted) {
|
|
144
|
+
if (!Array.isArray(sections)) return null;
|
|
145
|
+
const key = normalizeHeading(wanted);
|
|
146
|
+
const matches = sections.filter((section) => normalizeHeading(section?.title) === key);
|
|
147
|
+
if (matches.length === 0) return null;
|
|
148
|
+
return matches.slice().sort((a, b) => {
|
|
149
|
+
if (a.level === 2 && b.level !== 2) return -1;
|
|
150
|
+
if (b.level === 2 && a.level !== 2) return 1;
|
|
151
|
+
return a.line - b.line;
|
|
152
|
+
})[0];
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* 把一节 markdown 压成适合塞进 800 字的短文本。
|
|
157
|
+
* 去掉代码块、表格分隔线、链接地址,保留要点与编号。
|
|
158
|
+
* @param {unknown} markdown
|
|
159
|
+
* @returns {string}
|
|
160
|
+
*/
|
|
161
|
+
export function cleanMarkdown(markdown) {
|
|
162
|
+
const lines = normalizeText(markdown).split('\n');
|
|
163
|
+
const out = [];
|
|
164
|
+
let fence = null;
|
|
165
|
+
|
|
166
|
+
for (const rawLine of lines) {
|
|
167
|
+
const line = rawLine.trimEnd();
|
|
168
|
+
const fenceMatch = /^\s{0,3}(`{3,}|~{3,})/.exec(line);
|
|
169
|
+
if (fenceMatch) {
|
|
170
|
+
const mark = fenceMatch[1][0];
|
|
171
|
+
if (fence === null) fence = mark;
|
|
172
|
+
else if (fence === mark) fence = null;
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
if (fence !== null) continue;
|
|
176
|
+
|
|
177
|
+
let text = line.trim();
|
|
178
|
+
if (text === '') continue;
|
|
179
|
+
if (/^<!--.*-->$/u.test(text)) continue;
|
|
180
|
+
if (/^[-*_]{3,}$/u.test(text)) continue;
|
|
181
|
+
if (/^\|?[\s:|-]+\|[\s:|-]*$/u.test(text) && text.includes('|')) continue;
|
|
182
|
+
|
|
183
|
+
text = text
|
|
184
|
+
.replace(/^>\s?/u, '')
|
|
185
|
+
.replace(/^#{2,6}\s+/u, '')
|
|
186
|
+
.replace(/^[-*+]\s+/u, '- ')
|
|
187
|
+
.replace(/^\d+[.)]\s+/u, (match) => match.replace(/[.)]/u, '. '))
|
|
188
|
+
.replace(/!\[([^\]]*)\]\([^)]*\)/gu, '$1')
|
|
189
|
+
.replace(/\[([^\]]+)\]\([^)]*\)/gu, '$1')
|
|
190
|
+
.replace(/\*\*|__|`/g, '')
|
|
191
|
+
.replace(/\s+/gu, ' ')
|
|
192
|
+
.trim();
|
|
193
|
+
|
|
194
|
+
if (text === '') continue;
|
|
195
|
+
out.push(text);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
return out.join('\n');
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* 取一节并截断到预算。
|
|
203
|
+
* @param {Array<{level:number,title:string,content:string,line:number}>} sections
|
|
204
|
+
* @param {string} wanted
|
|
205
|
+
* @param {number} maxChars
|
|
206
|
+
* @returns {{text:string, found:boolean, truncated:boolean}}
|
|
207
|
+
*/
|
|
208
|
+
export function compactSection(sections, wanted, maxChars) {
|
|
209
|
+
const section = findSection(sections, wanted);
|
|
210
|
+
if (!section || section.content.trim() === '') {
|
|
211
|
+
return { text: MISSING_TEXT, found: false, truncated: false };
|
|
212
|
+
}
|
|
213
|
+
const cleaned = cleanMarkdown(section.content);
|
|
214
|
+
if (cleaned === '') return { text: MISSING_TEXT, found: false, truncated: false };
|
|
215
|
+
const cut = truncateChars(cleaned, maxChars);
|
|
216
|
+
return { text: cut.text, found: true, truncated: cut.truncated };
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* 「最近三件」按条渲染:先尽量放整条,预算不够时允许放一条不完整的并标 partial。
|
|
221
|
+
* 返回的 items 是完整条数;itemsStarted 是实际起笔的条数(含被截断的那条)。
|
|
222
|
+
* @param {Array<{level:number,title:string,content:string,line:number}>} sections
|
|
223
|
+
* @param {string} wanted
|
|
224
|
+
* @param {number} maxChars
|
|
225
|
+
* @returns {{text:string,chars:number,items:number,totalItems:number,itemsStarted:number,
|
|
226
|
+
* partial:boolean,cut:boolean,truncated:boolean,budget:number,found:boolean}}
|
|
227
|
+
*/
|
|
228
|
+
export function renderRecentSection(sections, wanted, maxChars) {
|
|
229
|
+
const budget = Number.isFinite(maxChars) ? Math.max(0, Math.floor(maxChars)) : 0;
|
|
230
|
+
const section = findSection(sections, wanted);
|
|
231
|
+
if (!section || section.content.trim() === '') {
|
|
232
|
+
return {
|
|
233
|
+
text: MISSING_TEXT,
|
|
234
|
+
chars: charLength(MISSING_TEXT),
|
|
235
|
+
items: 0,
|
|
236
|
+
totalItems: 0,
|
|
237
|
+
itemsStarted: 0,
|
|
238
|
+
partial: false,
|
|
239
|
+
cut: false,
|
|
240
|
+
truncated: false,
|
|
241
|
+
budget,
|
|
242
|
+
found: false,
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
const cleaned = cleanMarkdown(section.content);
|
|
246
|
+
if (cleaned === '') {
|
|
247
|
+
return {
|
|
248
|
+
text: MISSING_TEXT,
|
|
249
|
+
chars: charLength(MISSING_TEXT),
|
|
250
|
+
items: 0,
|
|
251
|
+
totalItems: 0,
|
|
252
|
+
itemsStarted: 0,
|
|
253
|
+
partial: false,
|
|
254
|
+
cut: false,
|
|
255
|
+
truncated: false,
|
|
256
|
+
budget,
|
|
257
|
+
found: false,
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
const items = cleaned.split('\n');
|
|
261
|
+
const totalItems = items.length;
|
|
262
|
+
if (charLength(cleaned) <= budget) {
|
|
263
|
+
return {
|
|
264
|
+
text: cleaned,
|
|
265
|
+
chars: charLength(cleaned),
|
|
266
|
+
items: totalItems,
|
|
267
|
+
totalItems,
|
|
268
|
+
itemsStarted: totalItems,
|
|
269
|
+
partial: false,
|
|
270
|
+
cut: false,
|
|
271
|
+
truncated: false,
|
|
272
|
+
budget,
|
|
273
|
+
found: true,
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
let out = '';
|
|
278
|
+
let complete = 0;
|
|
279
|
+
let partial = false;
|
|
280
|
+
for (let index = 0; index < items.length; index += 1) {
|
|
281
|
+
const item = items[index];
|
|
282
|
+
const separator = index === 0 ? '' : '\n';
|
|
283
|
+
const candidate = out + separator + item;
|
|
284
|
+
if (charLength(candidate) <= budget) {
|
|
285
|
+
out = candidate;
|
|
286
|
+
complete += 1;
|
|
287
|
+
continue;
|
|
288
|
+
}
|
|
289
|
+
const remaining = budget - charLength(out + separator);
|
|
290
|
+
if (remaining > 0) {
|
|
291
|
+
const piece = truncateChars(item, remaining);
|
|
292
|
+
out = out + separator + piece.text;
|
|
293
|
+
partial = true;
|
|
294
|
+
}
|
|
295
|
+
break;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
return {
|
|
299
|
+
text: out,
|
|
300
|
+
chars: charLength(out),
|
|
301
|
+
items: complete,
|
|
302
|
+
totalItems,
|
|
303
|
+
itemsStarted: partial ? complete + 1 : complete,
|
|
304
|
+
partial,
|
|
305
|
+
cut: true,
|
|
306
|
+
truncated: true,
|
|
307
|
+
budget,
|
|
308
|
+
found: true,
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* 从文件名里取日期(`YYYY-MM-DD-...`)。取不到返回 null。
|
|
314
|
+
* @param {unknown} name
|
|
315
|
+
* @returns {number|null}
|
|
316
|
+
*/
|
|
317
|
+
export function dateFromHandoverName(name) {
|
|
318
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})(?:[-_. ]|$)/u.exec(String(name ?? ''));
|
|
319
|
+
if (!match) return null;
|
|
320
|
+
const year = Number(match[1]);
|
|
321
|
+
const month = Number(match[2]);
|
|
322
|
+
const day = Number(match[3]);
|
|
323
|
+
if (month < 1 || month > 12 || day < 1 || day > 31) return null;
|
|
324
|
+
const value = new Date(year, month - 1, day).getTime();
|
|
325
|
+
return Number.isFinite(value) ? value : null;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* 交接卡排序:文件名日期优先(这是卡片自称的日期),同日期按 mtime,再按名称。
|
|
330
|
+
* 空日期(不合命名规范)排在最后,只按 mtime。
|
|
331
|
+
* @param {Array<{name:string,mtimeMs?:number}>} entries
|
|
332
|
+
* @returns {Array<{name:string,mtimeMs?:number}>}
|
|
333
|
+
*/
|
|
334
|
+
export function sortHandoverCards(entries) {
|
|
335
|
+
if (!Array.isArray(entries)) return [];
|
|
336
|
+
return entries
|
|
337
|
+
.filter((entry) => entry && typeof entry.name === 'string' && /\.md$/iu.test(entry.name))
|
|
338
|
+
.slice()
|
|
339
|
+
.sort((a, b) => {
|
|
340
|
+
const dateA = dateFromHandoverName(a.name);
|
|
341
|
+
const dateB = dateFromHandoverName(b.name);
|
|
342
|
+
if (dateA !== null && dateB !== null && dateA !== dateB) return dateB - dateA;
|
|
343
|
+
if (dateA !== null && dateB === null) return -1;
|
|
344
|
+
if (dateA === null && dateB !== null) return 1;
|
|
345
|
+
const mtimeA = Number(a.mtimeMs) || 0;
|
|
346
|
+
const mtimeB = Number(b.mtimeMs) || 0;
|
|
347
|
+
if (mtimeA !== mtimeB) return mtimeB - mtimeA;
|
|
348
|
+
return a.name.localeCompare(b.name, 'zh-CN');
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* 多张里取最新一张。
|
|
354
|
+
* @param {Array<{name:string,mtimeMs?:number}>} entries
|
|
355
|
+
* @returns {{name:string,mtimeMs?:number}|null}
|
|
356
|
+
*/
|
|
357
|
+
export function selectLatestHandover(entries) {
|
|
358
|
+
const sorted = sortHandoverCards(entries);
|
|
359
|
+
return sorted.length > 0 ? sorted[0] : null;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* 只读读取文本文件,永不抛。
|
|
364
|
+
* @param {string} filePath
|
|
365
|
+
* @returns {{ok:boolean,text:string,error?:string}}
|
|
366
|
+
*/
|
|
367
|
+
export function readTextFile(filePath) {
|
|
368
|
+
if (typeof filePath !== 'string' || filePath.trim() === '') return { ...EMPTY_READ };
|
|
369
|
+
try {
|
|
370
|
+
const text = fs.readFileSync(filePath, 'utf8');
|
|
371
|
+
return { ok: true, text: normalizeText(text) };
|
|
372
|
+
} catch (error) {
|
|
373
|
+
return { ok: false, text: '', error: error?.code ?? 'EREAD' };
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* 列出 handover 目录下的 .md 文件。目录不存在返回 []。
|
|
379
|
+
* @param {string} handoverDir
|
|
380
|
+
* @returns {Array<{name:string,path:string,mtimeMs:number}>}
|
|
381
|
+
*/
|
|
382
|
+
export function listHandoverCards(handoverDir) {
|
|
383
|
+
if (typeof handoverDir !== 'string' || handoverDir.trim() === '') return [];
|
|
384
|
+
let entries;
|
|
385
|
+
try {
|
|
386
|
+
entries = fs.readdirSync(handoverDir, { withFileTypes: true });
|
|
387
|
+
} catch {
|
|
388
|
+
return [];
|
|
389
|
+
}
|
|
390
|
+
const cards = [];
|
|
391
|
+
for (const entry of entries) {
|
|
392
|
+
if (!entry.isFile() || !/\.md$/iu.test(entry.name) || entry.name.startsWith('.')) continue;
|
|
393
|
+
const fullPath = path.join(handoverDir, entry.name);
|
|
394
|
+
let stat;
|
|
395
|
+
try {
|
|
396
|
+
stat = fs.statSync(fullPath);
|
|
397
|
+
} catch {
|
|
398
|
+
continue;
|
|
399
|
+
}
|
|
400
|
+
cards.push({ name: entry.name, path: fullPath, mtimeMs: stat.mtimeMs });
|
|
401
|
+
}
|
|
402
|
+
return cards;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/**
|
|
406
|
+
* 交接卡文件名 → 卡片里显示的短标签:去 .md、去开头日期、下划线转空格。
|
|
407
|
+
* @param {unknown} name
|
|
408
|
+
* @returns {string}
|
|
409
|
+
*/
|
|
410
|
+
export function handoverLabel(name) {
|
|
411
|
+
return String(name ?? '')
|
|
412
|
+
.replace(/\.md$/iu, '')
|
|
413
|
+
.replace(/^\d{4}-\d{2}-\d{2}[-_ ]?/u, '')
|
|
414
|
+
.replace(/_/gu, ' ')
|
|
415
|
+
.trim();
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/**
|
|
419
|
+
* 交接卡摘要:优先取「一句话 / 摘要 / 结论」这一节,否则取标题后的开头。
|
|
420
|
+
* @param {unknown} markdown
|
|
421
|
+
* @param {number} maxChars
|
|
422
|
+
* @returns {{text:string,title:string,truncated:boolean}}
|
|
423
|
+
*/
|
|
424
|
+
export function summarizeHandover(markdown, maxChars) {
|
|
425
|
+
const text = normalizeText(markdown);
|
|
426
|
+
if (text.trim() === '') return { text: '', title: '', truncated: false };
|
|
427
|
+
const sections = extractSections(text);
|
|
428
|
+
const titleSection = sections.find((section) => section.level === 1);
|
|
429
|
+
const title = (titleSection?.title ?? '').trim();
|
|
430
|
+
|
|
431
|
+
const preferredNames = ['一句话', '摘要', '结论', '现状锚点'];
|
|
432
|
+
let body = '';
|
|
433
|
+
for (const name of preferredNames) {
|
|
434
|
+
const found = findSection(sections, name);
|
|
435
|
+
if (found && found.content.trim() !== '') {
|
|
436
|
+
body = cleanMarkdown(found.content);
|
|
437
|
+
break;
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
if (body === '') {
|
|
441
|
+
// 没有小结节:取一级标题自己的正文(通常在第一个 ## 之前),再退到全文。
|
|
442
|
+
body = cleanMarkdown(titleSection?.content ?? '');
|
|
443
|
+
if (body === '') body = cleanMarkdown(text);
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
const prefix = title ? `《${title}》` : '';
|
|
447
|
+
const joined = [prefix, body].filter(Boolean).join(':');
|
|
448
|
+
const cut = truncateChars(joined, maxChars);
|
|
449
|
+
return { text: cut.text, title, truncated: cut.truncated };
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/**
|
|
453
|
+
* 解析 STATE.md:返回各节原文与命中情况,不决定展示顺序。
|
|
454
|
+
* @param {unknown} markdown
|
|
455
|
+
* @returns {{title:string,sections:Array,found:Record<string,boolean>}}
|
|
456
|
+
*/
|
|
457
|
+
export function parseState(markdown) {
|
|
458
|
+
const text = normalizeText(markdown);
|
|
459
|
+
const sections = extractSections(text);
|
|
460
|
+
const h1 = sections.find((section) => section.level === 1);
|
|
461
|
+
const found = {};
|
|
462
|
+
for (const [key, name] of Object.entries(STATE_SECTIONS)) {
|
|
463
|
+
found[key] = Boolean(findSection(sections, name)?.content?.trim());
|
|
464
|
+
}
|
|
465
|
+
return { title: h1?.title ?? '', sections, found };
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/**
|
|
469
|
+
* 记忆根解析:显式 config > 各环境变量 > <DSH home>/longlive-memory。
|
|
470
|
+
* 环境变量顺序与 src/memory/paths.js 一致:DSH_IDENTITY_MEMORY_ROOT(本模块旧名)
|
|
471
|
+
* → DSH_LONGLIVE_MEMORY_ROOT → DSH_MEM,避免身份卡和 memory_* 读到两棵树。
|
|
472
|
+
* @param {{memoryRoot?: string}} [config]
|
|
473
|
+
* @param {Record<string,string|undefined>} [env]
|
|
474
|
+
* @returns {string}
|
|
475
|
+
*/
|
|
476
|
+
export function resolveMemoryRoot(config = {}, env = process.env) {
|
|
477
|
+
const explicit = config?.memoryRoot;
|
|
478
|
+
if (typeof explicit === 'string' && explicit.trim() !== '') return path.resolve(explicit.trim());
|
|
479
|
+
const fromEnv = env?.DSH_IDENTITY_MEMORY_ROOT || env?.DSH_LONGLIVE_MEMORY_ROOT || env?.DSH_MEM;
|
|
480
|
+
if (typeof fromEnv === 'string' && fromEnv.trim() !== '') return path.resolve(fromEnv.trim());
|
|
481
|
+
return path.resolve(DEFAULT_MEMORY_ROOT);
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/**
|
|
485
|
+
* 把总预算按权重分给各节;保证每节至少 24 字(能放下一行占位)。
|
|
486
|
+
* @param {Array<{key:string,weight:number}>} parts
|
|
487
|
+
* @param {number} total
|
|
488
|
+
* @returns {Record<string,number>}
|
|
489
|
+
*/
|
|
490
|
+
export function allocateBudget(parts, total) {
|
|
491
|
+
const weights = parts.reduce((sum, part) => sum + part.weight, 0);
|
|
492
|
+
const budgets = {};
|
|
493
|
+
let used = 0;
|
|
494
|
+
for (const part of parts) {
|
|
495
|
+
const value = Math.max(24, Math.floor((total * part.weight) / weights));
|
|
496
|
+
budgets[part.key] = value;
|
|
497
|
+
used += value;
|
|
498
|
+
}
|
|
499
|
+
// 超出的从最大的那一节扣,避免最后整体截断把交接卡整个切掉。
|
|
500
|
+
let overflow = used - total;
|
|
501
|
+
while (overflow > 0) {
|
|
502
|
+
const largest = parts
|
|
503
|
+
.slice()
|
|
504
|
+
.sort((a, b) => budgets[b.key] - budgets[a.key])[0];
|
|
505
|
+
if (!largest || budgets[largest.key] <= 24) break;
|
|
506
|
+
budgets[largest.key] -= 1;
|
|
507
|
+
overflow -= 1;
|
|
508
|
+
}
|
|
509
|
+
return budgets;
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/**
|
|
513
|
+
* R6.2: 「状态卡写于 X 分钟前」——X 是 STATE.md mtime 与 now 的差,不是卡片
|
|
514
|
+
* 生成时间,也不是会话开始时间。拿不到 mtime 时返回 ''(宁可不写,不编造)。
|
|
515
|
+
* @param {unknown} ageMs
|
|
516
|
+
* @returns {string}
|
|
517
|
+
*/
|
|
518
|
+
export function stateCardAgeText(ageMs) {
|
|
519
|
+
if (typeof ageMs !== 'number' || !Number.isFinite(ageMs)) return '';
|
|
520
|
+
const minutes = Math.max(0, Math.round(ageMs / 60000));
|
|
521
|
+
return `状态卡写于 ${minutes} 分钟前`;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/**
|
|
525
|
+
* Resolve the STATE.md age in ms from explicit inputs, falling back to stat()
|
|
526
|
+
* on `statePath`. Missing/unknown age returns null — the card then omits the
|
|
527
|
+
* sentence instead of inventing a number.
|
|
528
|
+
*/
|
|
529
|
+
function resolveStateAgeMs(input, safeNow) {
|
|
530
|
+
if (typeof input.stateAgeMs === 'number' && Number.isFinite(input.stateAgeMs)) {
|
|
531
|
+
return Math.max(0, input.stateAgeMs);
|
|
532
|
+
}
|
|
533
|
+
let mtimeMs = typeof input.stateMtimeMs === 'number' && Number.isFinite(input.stateMtimeMs)
|
|
534
|
+
? input.stateMtimeMs
|
|
535
|
+
: null;
|
|
536
|
+
if (mtimeMs === null && typeof input.statePath === 'string' && input.statePath.trim() !== '') {
|
|
537
|
+
try {
|
|
538
|
+
mtimeMs = fs.statSync(input.statePath).mtimeMs;
|
|
539
|
+
} catch {
|
|
540
|
+
mtimeMs = null;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
if (mtimeMs === null) return null;
|
|
544
|
+
return Math.max(0, safeNow.getTime() - mtimeMs);
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
/**
|
|
548
|
+
* 生成开机卡。纯函数:所有输入显式传入,方便覆盖缺失/超长/中文路径等边界。
|
|
549
|
+
* @param {{
|
|
550
|
+
* stateText?: string|null,
|
|
551
|
+
* handover?: {name?:string,text?:string}|null,
|
|
552
|
+
* maxChars?: number,
|
|
553
|
+
* now?: Date|number|string,
|
|
554
|
+
* statePath?: string,
|
|
555
|
+
* stateMtimeMs?: number,
|
|
556
|
+
* stateAgeMs?: number,
|
|
557
|
+
* handoverPath?: string,
|
|
558
|
+
* }} [input]
|
|
559
|
+
* @returns {{
|
|
560
|
+
* text:string, chars:number, truncated:boolean, warnings:string[],
|
|
561
|
+
* found:Record<string,boolean>, handoverName:string|null,
|
|
562
|
+
* stateAgeMinutes:number|null,
|
|
563
|
+
* }}
|
|
564
|
+
*/
|
|
565
|
+
export function buildOpenCard(input = {}) {
|
|
566
|
+
const maxChars = Number.isFinite(input.maxChars) && input.maxChars > 0
|
|
567
|
+
? Math.floor(input.maxChars)
|
|
568
|
+
: DEFAULT_MAX_CHARS;
|
|
569
|
+
// M04(G-D7 承接):handoffSummary=false 时开机卡不注入「▍交接卡」节(显式降级,
|
|
570
|
+
// 不静默);默认 true,开机卡形状与 A-min 完全一致。
|
|
571
|
+
const handoffSummaryEnabled = input.handoffSummary !== false;
|
|
572
|
+
const now = input.now instanceof Date
|
|
573
|
+
? input.now
|
|
574
|
+
: new Date(input.now ?? Date.now());
|
|
575
|
+
const safeNow = Number.isFinite(now.getTime()) ? now : new Date();
|
|
576
|
+
const stateAgeMs = resolveStateAgeMs(input, safeNow);
|
|
577
|
+
const stateAgeMinutes = stateAgeMs === null ? null : Math.max(0, Math.round(stateAgeMs / 60000));
|
|
578
|
+
const warnings = [];
|
|
579
|
+
const stateText = typeof input.stateText === 'string' ? normalizeText(input.stateText) : '';
|
|
580
|
+
if (input.stateText === null || input.stateText === undefined) warnings.push('STATE_MISSING');
|
|
581
|
+
else if (stateText.trim() === '') warnings.push('STATE_EMPTY');
|
|
582
|
+
|
|
583
|
+
const parsed = parseState(stateText);
|
|
584
|
+
if (!parsed.found.where) warnings.push(`SECTION_MISSING:${STATE_SECTIONS.where}`);
|
|
585
|
+
if (!parsed.found.waiting) warnings.push(`SECTION_MISSING:${STATE_SECTIONS.waiting}`);
|
|
586
|
+
if (!parsed.found.recent) warnings.push(`SECTION_MISSING:${STATE_SECTIONS.recent}`);
|
|
587
|
+
|
|
588
|
+
const handoverText = typeof input.handover?.text === 'string'
|
|
589
|
+
? normalizeText(input.handover.text)
|
|
590
|
+
: '';
|
|
591
|
+
const handoverName = typeof input.handover?.name === 'string' && input.handover.name.trim() !== ''
|
|
592
|
+
? input.handover.name.trim()
|
|
593
|
+
: null;
|
|
594
|
+
if (!handoffSummaryEnabled) warnings.push('HANDOVER_SUMMARY_DISABLED');
|
|
595
|
+
else if (!input.handover) warnings.push('HANDOVER_MISSING');
|
|
596
|
+
else if (handoverText.trim() === '') warnings.push('HANDOVER_EMPTY');
|
|
597
|
+
|
|
598
|
+
const ageText = stateCardAgeText(stateAgeMs);
|
|
599
|
+
const header = `【开机卡】${formatCardTime(safeNow)}${ageText === '' ? '' : ` · ${ageText}`}`;
|
|
600
|
+
const headings = {
|
|
601
|
+
where: '▍我在哪',
|
|
602
|
+
waiting: '▍在等什么',
|
|
603
|
+
recent: '▍最近三件',
|
|
604
|
+
handover: '▍交接卡',
|
|
605
|
+
};
|
|
606
|
+
const overhead = charLength(header)
|
|
607
|
+
+ Object.entries(headings)
|
|
608
|
+
.filter(([key]) => handoffSummaryEnabled || key !== 'handover')
|
|
609
|
+
.reduce((sum, [, value]) => sum + charLength(value), 0)
|
|
610
|
+
+ 10;
|
|
611
|
+
const usable = Math.max(80, maxChars - overhead);
|
|
612
|
+
|
|
613
|
+
// 固定预算模式(A-min):调用方显式给各节预算时不再按权重分配。
|
|
614
|
+
// 这是 DESIGN v0.5.1 §8 C 的口径:recent 1,161 / where 336 / waiting 274 / handover 397。
|
|
615
|
+
const fixed = {};
|
|
616
|
+
for (const [key, value] of Object.entries({
|
|
617
|
+
where: input.whereBudgetChars,
|
|
618
|
+
waiting: input.waitingBudgetChars,
|
|
619
|
+
recent: input.recentBudgetChars,
|
|
620
|
+
handover: input.handoverChars,
|
|
621
|
+
})) {
|
|
622
|
+
if (Number.isFinite(value) && value > 0) fixed[key] = Math.floor(value);
|
|
623
|
+
}
|
|
624
|
+
const budgetSource = Object.keys(fixed).length > 0 ? 'fixed' : 'dynamic';
|
|
625
|
+
const layout = { maxChars, overhead, usable, budgetSource };
|
|
626
|
+
|
|
627
|
+
let budgets;
|
|
628
|
+
if (budgetSource === 'fixed') {
|
|
629
|
+
if (Number.isFinite(fixed.recent)) {
|
|
630
|
+
// recent 是唯一新增的配置键,其余三节从剩余预算按权重分。
|
|
631
|
+
const rest = Math.max(72, usable - fixed.recent);
|
|
632
|
+
const restBudgets = allocateBudget([
|
|
633
|
+
{ key: 'where', weight: 1.1 },
|
|
634
|
+
{ key: 'waiting', weight: 0.9 },
|
|
635
|
+
{ key: 'handover', weight: 1.3 },
|
|
636
|
+
], rest);
|
|
637
|
+
budgets = {
|
|
638
|
+
where: fixed.where ?? restBudgets.where,
|
|
639
|
+
waiting: fixed.waiting ?? restBudgets.waiting,
|
|
640
|
+
recent: fixed.recent,
|
|
641
|
+
handover: fixed.handover ?? restBudgets.handover,
|
|
642
|
+
};
|
|
643
|
+
} else {
|
|
644
|
+
budgets = allocateBudget([
|
|
645
|
+
{ key: 'where', weight: 1.1 },
|
|
646
|
+
{ key: 'waiting', weight: 0.9 },
|
|
647
|
+
{ key: 'recent', weight: 1.1 },
|
|
648
|
+
{ key: 'handover', weight: 1.3 },
|
|
649
|
+
], usable);
|
|
650
|
+
for (const key of ['where', 'waiting', 'recent', 'handover']) {
|
|
651
|
+
if (Number.isFinite(fixed[key])) budgets[key] = fixed[key];
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
const sum = budgets.where + budgets.waiting + budgets.recent + budgets.handover;
|
|
655
|
+
if (sum > usable) {
|
|
656
|
+
const overflow = sum - usable;
|
|
657
|
+
const next = budgets.handover - overflow;
|
|
658
|
+
if (next >= 24) budgets.handover = next;
|
|
659
|
+
else {
|
|
660
|
+
budgets.handover = 24;
|
|
661
|
+
warnings.push('FIXED_BUDGET_OVERFLOW');
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
} else {
|
|
665
|
+
budgets = allocateBudget([
|
|
666
|
+
{ key: 'where', weight: 1.1 },
|
|
667
|
+
{ key: 'waiting', weight: 0.9 },
|
|
668
|
+
{ key: 'recent', weight: 1.1 },
|
|
669
|
+
{ key: 'handover', weight: 1.3 },
|
|
670
|
+
], usable);
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
const where = compactSection(parsed.sections, STATE_SECTIONS.where, budgets.where);
|
|
674
|
+
const waiting = compactSection(parsed.sections, STATE_SECTIONS.waiting, budgets.waiting);
|
|
675
|
+
const recent = renderRecentSection(parsed.sections, STATE_SECTIONS.recent, budgets.recent);
|
|
676
|
+
|
|
677
|
+
if (!handoffSummaryEnabled) {
|
|
678
|
+
budgets.handover = 0;
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
let handoverBody;
|
|
682
|
+
let handoverTitle = '';
|
|
683
|
+
if (!handoffSummaryEnabled) {
|
|
684
|
+
// 显式关闭交接摘要:不读交接卡内容,也不产生截断警告(只有 DISABLED 一条)。
|
|
685
|
+
handoverBody = { text: '', truncated: false };
|
|
686
|
+
} else if (handoverText.trim() === '') {
|
|
687
|
+
handoverBody = { text: '(没有找到交接卡)', truncated: false };
|
|
688
|
+
} else {
|
|
689
|
+
const summary = summarizeHandover(handoverText, budgets.handover);
|
|
690
|
+
handoverTitle = summary.title.trim();
|
|
691
|
+
handoverBody = { text: summary.text, truncated: summary.truncated };
|
|
692
|
+
}
|
|
693
|
+
if (handoverBody.truncated) warnings.push('HANDOVER_SECTION_TRUNCATED');
|
|
694
|
+
|
|
695
|
+
const lines = [
|
|
696
|
+
header,
|
|
697
|
+
headings.where,
|
|
698
|
+
where.text,
|
|
699
|
+
headings.waiting,
|
|
700
|
+
waiting.text,
|
|
701
|
+
headings.recent,
|
|
702
|
+
recent.text,
|
|
703
|
+
...(handoffSummaryEnabled
|
|
704
|
+
? [
|
|
705
|
+
headings.handover,
|
|
706
|
+
handoverName && handoverTitle === '' ? `《${handoverLabel(handoverName)}》` : '',
|
|
707
|
+
handoverBody.text,
|
|
708
|
+
]
|
|
709
|
+
: []),
|
|
710
|
+
].filter((line) => line !== '');
|
|
711
|
+
|
|
712
|
+
const joined = lines.join('\n');
|
|
713
|
+
const cut = truncateChars(joined, maxChars);
|
|
714
|
+
const sectionTruncated = where.truncated || waiting.truncated || recent.truncated || handoverBody.truncated;
|
|
715
|
+
if (cut.truncated) warnings.push('CARD_TRUNCATED');
|
|
716
|
+
else if (sectionTruncated) warnings.push('SECTION_TRUNCATED');
|
|
717
|
+
|
|
718
|
+
return {
|
|
719
|
+
text: cut.text,
|
|
720
|
+
chars: charLength(cut.text),
|
|
721
|
+
truncated: cut.truncated || sectionTruncated,
|
|
722
|
+
warnings,
|
|
723
|
+
found: { ...parsed.found, handover: handoffSummaryEnabled && handoverText.trim() !== '' },
|
|
724
|
+
handoverName,
|
|
725
|
+
stateAgeMinutes,
|
|
726
|
+
layout,
|
|
727
|
+
sections: {
|
|
728
|
+
where: { chars: charLength(where.text), cut: where.truncated, budget: budgets.where },
|
|
729
|
+
waiting: { chars: charLength(waiting.text), cut: waiting.truncated, budget: budgets.waiting },
|
|
730
|
+
recent: {
|
|
731
|
+
chars: recent.chars,
|
|
732
|
+
cut: recent.cut,
|
|
733
|
+
budget: budgets.recent,
|
|
734
|
+
items: recent.items,
|
|
735
|
+
totalItems: recent.totalItems,
|
|
736
|
+
itemsStarted: recent.itemsStarted,
|
|
737
|
+
partial: recent.partial,
|
|
738
|
+
},
|
|
739
|
+
handover: {
|
|
740
|
+
chars: handoffSummaryEnabled ? charLength(handoverBody.text) : 0,
|
|
741
|
+
cut: handoffSummaryEnabled ? handoverBody.truncated : false,
|
|
742
|
+
budget: budgets.handover,
|
|
743
|
+
},
|
|
744
|
+
},
|
|
745
|
+
};
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
/**
|
|
749
|
+
* 本地时间 `YYYY-MM-DD HH:mm`,卡片头用。
|
|
750
|
+
* @param {Date} date
|
|
751
|
+
* @returns {string}
|
|
752
|
+
*/
|
|
753
|
+
export function formatCardTime(date) {
|
|
754
|
+
const pad = (value) => String(value).padStart(2, '0');
|
|
755
|
+
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} `
|
|
756
|
+
+ `${pad(date.getHours())}:${pad(date.getMinutes())}`;
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
/**
|
|
760
|
+
* 读 STATE + 最新一张非空 handover,生成开机卡。只读,不抛。
|
|
761
|
+
* 最新卡片为空时向旧卡回退,并留下 HANDOVER_LATEST_EMPTY 警告。
|
|
762
|
+
* @param {{
|
|
763
|
+
* memoryRoot?: string,
|
|
764
|
+
* statePath?: string,
|
|
765
|
+
* handoverDir?: string,
|
|
766
|
+
* handoverPath?: string,
|
|
767
|
+
* maxChars?: number,
|
|
768
|
+
* now?: Date|number|string,
|
|
769
|
+
* env?: Record<string,string|undefined>,
|
|
770
|
+
* }} [options]
|
|
771
|
+
* @returns {ReturnType<typeof buildOpenCard> & {
|
|
772
|
+
* statePath:string, handoverPath:string|null, errors:string[],
|
|
773
|
+
* }}
|
|
774
|
+
*/
|
|
775
|
+
export function collectOpenCard(options = {}) {
|
|
776
|
+
const memoryRoot = resolveMemoryRoot(options, options.env ?? process.env);
|
|
777
|
+
const statePath = options.statePath
|
|
778
|
+
? path.resolve(options.statePath)
|
|
779
|
+
: path.join(memoryRoot, 'STATE.md');
|
|
780
|
+
const handoverDir = options.handoverDir
|
|
781
|
+
? path.resolve(options.handoverDir)
|
|
782
|
+
: path.join(memoryRoot, 'handover');
|
|
783
|
+
|
|
784
|
+
const errors = [];
|
|
785
|
+
const stateRead = readTextFile(statePath);
|
|
786
|
+
if (!stateRead.ok) errors.push(`STATE_READ_FAILED:${stateRead.error}`);
|
|
787
|
+
// R6.2: the open card must say how old the state card is. Read the mtime
|
|
788
|
+
// once here; a missing file leaves it unknown and the sentence is omitted.
|
|
789
|
+
let stateMtimeMs = null;
|
|
790
|
+
try {
|
|
791
|
+
stateMtimeMs = fs.statSync(statePath).mtimeMs;
|
|
792
|
+
} catch {
|
|
793
|
+
stateMtimeMs = null;
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
let handover = null;
|
|
797
|
+
let handoverPath = null;
|
|
798
|
+
const explicit = options.handoverPath ? path.resolve(options.handoverPath) : null;
|
|
799
|
+
|
|
800
|
+
if (explicit) {
|
|
801
|
+
const read = readTextFile(explicit);
|
|
802
|
+
if (read.ok && read.text.trim() !== '') {
|
|
803
|
+
handover = { name: path.basename(explicit), text: read.text };
|
|
804
|
+
handoverPath = explicit;
|
|
805
|
+
} else {
|
|
806
|
+
errors.push(`HANDOVER_READ_FAILED:${read.error ?? 'EMPTY'}`);
|
|
807
|
+
}
|
|
808
|
+
} else {
|
|
809
|
+
const sorted = sortHandoverCards(listHandoverCards(handoverDir));
|
|
810
|
+
for (const entry of sorted) {
|
|
811
|
+
const read = readTextFile(entry.path);
|
|
812
|
+
if (!read.ok) {
|
|
813
|
+
errors.push(`HANDOVER_READ_FAILED:${read.error}`);
|
|
814
|
+
continue;
|
|
815
|
+
}
|
|
816
|
+
if (read.text.trim() === '') continue;
|
|
817
|
+
handover = { name: entry.name, text: read.text };
|
|
818
|
+
handoverPath = entry.path;
|
|
819
|
+
if (entry !== sorted[0]) errors.push('HANDOVER_LATEST_EMPTY');
|
|
820
|
+
break;
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
const card = buildOpenCard({
|
|
825
|
+
stateText: stateRead.ok ? stateRead.text : null,
|
|
826
|
+
handover,
|
|
827
|
+
maxChars: options.maxChars,
|
|
828
|
+
now: options.now,
|
|
829
|
+
statePath,
|
|
830
|
+
stateMtimeMs,
|
|
831
|
+
handoverPath: handoverPath ?? undefined,
|
|
832
|
+
whereBudgetChars: options.whereBudgetChars,
|
|
833
|
+
waitingBudgetChars: options.waitingBudgetChars,
|
|
834
|
+
recentBudgetChars: options.recentBudgetChars,
|
|
835
|
+
handoverChars: options.handoverChars,
|
|
836
|
+
});
|
|
837
|
+
|
|
838
|
+
return {
|
|
839
|
+
...card,
|
|
840
|
+
warnings: [...card.warnings, ...errors],
|
|
841
|
+
statePath,
|
|
842
|
+
handoverPath,
|
|
843
|
+
errors,
|
|
844
|
+
};
|
|
845
|
+
}
|