@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,362 @@
|
|
|
1
|
+
// src/memory/prospective-memory.mjs — 前瞻记忆(D15):从对话/任务里抽承诺与待办,落 prospective.jsonl。
|
|
2
|
+
//
|
|
3
|
+
// 契约来源:V0.5.2-MERGE-PLAN §4/§14 D15 行 / KICKOFF-PLAN §2-D / BATCH-D-BRIEF M 规格。
|
|
4
|
+
// 触发词:「以后 / 明天 / 下次 / 答应 / 记得 / 回头」+ 任务/时间线索;
|
|
5
|
+
// 落盘:prospective.jsonl(≤500 条 / 90d;done 保留 30d;expired 只标记不删);
|
|
6
|
+
// 注入:每轮到期 ≤3 条、每条 ≤120 字;落盘前必须脱敏(机器路径/密钥);
|
|
7
|
+
// 失败路径:写 gate-log 事件 `hg.d15.fail`,不静默吞账。
|
|
8
|
+
//
|
|
9
|
+
// 设计边界:本模块只做抽取/脱敏/落盘/选到期,不直接注入;注入接线在 recall/index.js。
|
|
10
|
+
|
|
11
|
+
import crypto from 'node:crypto';
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
|
|
15
|
+
import { appendGateLog } from '../recall/gate-log.mjs';
|
|
16
|
+
|
|
17
|
+
export const BATCH = 'D';
|
|
18
|
+
export const MODULE = 'memory/prospective-memory.mjs';
|
|
19
|
+
export const UNIMPLEMENTED_CODE = 'E_HG_PROSPECTIVE_UNIMPLEMENTED';
|
|
20
|
+
export const SKELETON = Object.freeze({
|
|
21
|
+
version: '2.0.0',
|
|
22
|
+
failClosed: true,
|
|
23
|
+
batch: BATCH,
|
|
24
|
+
implemented: true,
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
/** 前瞻记忆账本相对 memoryRoot 的路径 */
|
|
28
|
+
export const PROSPECTIVE_REL = '.longlive/hardgate/prospective.jsonl';
|
|
29
|
+
/** 触发词(计划冻结集合) */
|
|
30
|
+
export const TRIGGER_WORDS = Object.freeze(['以后', '明天', '下次', '答应', '记得', '回头']);
|
|
31
|
+
/** 时间线索(触发词之外的另一半条件;计划口径:触发词+时间线索才抽取) */
|
|
32
|
+
export const TIME_WORDS = Object.freeze([
|
|
33
|
+
'明天', '以后', '下次', '回头', '周末', '之前', '今晚', '下周', '上午', '下午',
|
|
34
|
+
'晚上', '今天', '改天', '晚些', '之后', '届时', '月底', '本周',
|
|
35
|
+
]);
|
|
36
|
+
/** 账本上限(计划冻结) */
|
|
37
|
+
export const MAX_ITEMS = 500;
|
|
38
|
+
/** 保留天数(计划冻结) */
|
|
39
|
+
export const RETENTION_DAYS = 90;
|
|
40
|
+
/** done 条目保留天数(计划冻结) */
|
|
41
|
+
export const DONE_RETENTION_DAYS = 30;
|
|
42
|
+
/** 每轮注入上限(计划冻结:≤3 条;每条 ≤120 字) */
|
|
43
|
+
export const MAX_DUE_PER_ROUND = 3;
|
|
44
|
+
export const MAX_DUE_CHARS = 120;
|
|
45
|
+
/** 失败门事件 */
|
|
46
|
+
export const GATE_EVENT = 'hg.d15.fail';
|
|
47
|
+
/** 到期窗口:24h 内到期的条目才进注入 */
|
|
48
|
+
export const DUE_HORIZON_MS = 24 * 60 * 60 * 1000;
|
|
49
|
+
|
|
50
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
51
|
+
|
|
52
|
+
function failWithGate(root, code, message) {
|
|
53
|
+
try {
|
|
54
|
+
if (typeof root === 'string' && root !== '') {
|
|
55
|
+
appendGateLog(root, {
|
|
56
|
+
sessionId: null,
|
|
57
|
+
turn: 0,
|
|
58
|
+
gate: GATE_EVENT,
|
|
59
|
+
decision: 'fail',
|
|
60
|
+
reason: code,
|
|
61
|
+
evidence: [String(message ?? '').slice(0, 300)],
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
} catch {
|
|
65
|
+
/* gate-log must never mask the original failure */
|
|
66
|
+
}
|
|
67
|
+
const error = new Error(`${code}: ${message}`);
|
|
68
|
+
error.code = code;
|
|
69
|
+
error.gate = GATE_EVENT;
|
|
70
|
+
throw error;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function nowMsOf(now) {
|
|
74
|
+
if (now instanceof Date) return now.getTime();
|
|
75
|
+
if (typeof now === 'number' && Number.isFinite(now)) return now;
|
|
76
|
+
if (typeof now === 'string' && now.trim() !== '') {
|
|
77
|
+
const parsed = Date.parse(now);
|
|
78
|
+
if (Number.isFinite(parsed)) return parsed;
|
|
79
|
+
}
|
|
80
|
+
return Date.now();
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function isoOf(ms) {
|
|
84
|
+
return new Date(ms).toISOString();
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function clip(text, max) {
|
|
88
|
+
const value = String(text ?? '').replace(/\s+/g, ' ').trim();
|
|
89
|
+
if (value.length <= max) return value;
|
|
90
|
+
return `${value.slice(0, max - 1)}…`;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function sha256Hex(value) {
|
|
94
|
+
return crypto.createHash('sha256').update(String(value), 'utf8').digest('hex');
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function dayString(ms) {
|
|
98
|
+
return new Date(ms).toISOString().slice(0, 10);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** 机器路径 / 常见密钥形态脱敏(不做统计口径处理,只替换字面量)。 */
|
|
102
|
+
export function redactMachinePaths(text, options = {}) {
|
|
103
|
+
void options;
|
|
104
|
+
if (typeof text !== 'string' || text === '') return '';
|
|
105
|
+
let out = text;
|
|
106
|
+
// Windows 盘符路径:C:\a\b、D:/a/b
|
|
107
|
+
out = out.replace(/(?:[A-Za-z]:[\\/])[^\s"'`,。;、,;::()()\[\]【】]*/g, '[redacted]');
|
|
108
|
+
// UNC 路径:\\server\share\...
|
|
109
|
+
out = out.replace(/\\\\[^\s\\/"'`,。;、,;::()()\[\]【】]+\\[^\s"'`,。;、,;::()()\[\]【】]*/g, '[redacted]');
|
|
110
|
+
// POSIX 路径:~/、/home/、/Users/、/mnt/
|
|
111
|
+
out = out.replace(/(?:~\/|\/home\/|\/Users\/|\/mnt\/)[^\s"'`,。;、,;::()()\[\]【】]*/g, '[redacted]');
|
|
112
|
+
// 常见 token 形态
|
|
113
|
+
out = out.replace(/\b(?:sk|pk|ghp|xoxb|glpat)-[A-Za-z0-9_-]{8,}\b/g, '[redacted]');
|
|
114
|
+
return out;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** 计划允许的脱敏别名。 */
|
|
118
|
+
export function redact(text, options = {}) {
|
|
119
|
+
return redactMachinePaths(text, options);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function ledgerPath(root) {
|
|
123
|
+
return path.join(root, ...PROSPECTIVE_REL.split('/'));
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function readLedger(file, root) {
|
|
127
|
+
if (!fs.existsSync(file)) return [];
|
|
128
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
129
|
+
const rows = [];
|
|
130
|
+
for (const line of text.split(/\r?\n/)) {
|
|
131
|
+
if (line.trim() === '') continue;
|
|
132
|
+
let row;
|
|
133
|
+
try {
|
|
134
|
+
row = JSON.parse(line);
|
|
135
|
+
} catch {
|
|
136
|
+
failWithGate(root, 'E_HG_D15_LEDGER_CORRUPT', `prospective ledger has corrupt JSON line: ${line.slice(0, 120)}`);
|
|
137
|
+
}
|
|
138
|
+
if (row === null || typeof row !== 'object') {
|
|
139
|
+
failWithGate(root, 'E_HG_D15_LEDGER_CORRUPT', `prospective ledger row is not an object: ${line.slice(0, 120)}`);
|
|
140
|
+
}
|
|
141
|
+
rows.push(row);
|
|
142
|
+
}
|
|
143
|
+
return rows;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function writeLedger(file, rows) {
|
|
147
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
148
|
+
const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
|
|
149
|
+
const body = rows.map((row) => JSON.stringify(row)).join('\n');
|
|
150
|
+
fs.writeFileSync(tmp, body === '' ? '' : `${body}\n`, 'utf8');
|
|
151
|
+
fs.renameSync(tmp, file);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function atTime(baseMs, dayShift, hour, minute = 0) {
|
|
155
|
+
const date = new Date(baseMs);
|
|
156
|
+
date.setHours(hour, minute, 0, 0);
|
|
157
|
+
if (dayShift !== 0) date.setDate(date.getDate() + dayShift);
|
|
158
|
+
return date;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function nextWeekday(baseMs, weekday, hour) {
|
|
162
|
+
const date = new Date(baseMs);
|
|
163
|
+
date.setHours(hour, 0, 0, 0);
|
|
164
|
+
const diff = (weekday - date.getDay() + 7) % 7;
|
|
165
|
+
if (diff === 0 && date.getTime() <= baseMs) date.setDate(date.getDate() + 7);
|
|
166
|
+
else date.setDate(date.getDate() + diff);
|
|
167
|
+
return date;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** 依据时间线索算 due;没有可判定时间线索 → null(计划:下次/回头/以后 可为 null)。 */
|
|
171
|
+
function dueForLine(line, baseMs) {
|
|
172
|
+
if (/周末|之前/.test(line) && /周末|之前/.test(line)) {
|
|
173
|
+
return nextWeekday(baseMs, 6, 9).toISOString();
|
|
174
|
+
}
|
|
175
|
+
if (/下周/.test(line)) return nextWeekday(baseMs, 1, 9).toISOString();
|
|
176
|
+
if (/明天/.test(line)) return atTime(baseMs, 1, 9).toISOString();
|
|
177
|
+
if (/今晚/.test(line)) return atTime(baseMs, 0, 21).toISOString();
|
|
178
|
+
if (/之后|改天|晚些|届时/.test(line)) return atTime(baseMs, 2, 9).toISOString();
|
|
179
|
+
if (/月底/.test(line)) {
|
|
180
|
+
const date = new Date(baseMs);
|
|
181
|
+
date.setHours(9, 0, 0, 0);
|
|
182
|
+
date.setMonth(date.getMonth() + 1, 0);
|
|
183
|
+
if (date.getTime() <= baseMs) date.setMonth(date.getMonth() + 1, 0);
|
|
184
|
+
return date.toISOString();
|
|
185
|
+
}
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function normalizeItem(item, options, baseMs) {
|
|
190
|
+
if (item === null || typeof item !== 'object') return null;
|
|
191
|
+
const rawText = typeof item.text === 'string' ? item.text : '';
|
|
192
|
+
const text = clip(redactMachinePaths(rawText), MAX_DUE_CHARS);
|
|
193
|
+
if (text === '') return null;
|
|
194
|
+
const sessionId = typeof item.sessionId === 'string' ? item.sessionId : (typeof options.sessionId === 'string' ? options.sessionId : null);
|
|
195
|
+
const turn = Number.isInteger(item.turn) ? item.turn : (Number.isInteger(options.turn) ? options.turn : 0);
|
|
196
|
+
const id = typeof item.id === 'string' && item.id !== ''
|
|
197
|
+
? item.id
|
|
198
|
+
: `pm-${sha256Hex(`${sessionId ?? ''}|${turn}|${text}`).slice(0, 16)}`;
|
|
199
|
+
let due = null;
|
|
200
|
+
if (typeof item.due === 'string' && item.due !== '') {
|
|
201
|
+
const parsed = Date.parse(item.due);
|
|
202
|
+
if (Number.isFinite(parsed)) due = isoOf(parsed);
|
|
203
|
+
}
|
|
204
|
+
const triggerWord = typeof item.triggerWord === 'string' ? item.triggerWord : null;
|
|
205
|
+
const createdAt = typeof item.createdAt === 'string' && Number.isFinite(Date.parse(item.createdAt))
|
|
206
|
+
? isoOf(Date.parse(item.createdAt))
|
|
207
|
+
: isoOf(baseMs);
|
|
208
|
+
return {
|
|
209
|
+
schema: 'hardgate-prospective/v1',
|
|
210
|
+
id,
|
|
211
|
+
text,
|
|
212
|
+
due,
|
|
213
|
+
triggerWord,
|
|
214
|
+
createdAt,
|
|
215
|
+
sessionId,
|
|
216
|
+
turn,
|
|
217
|
+
status: item.status === 'done' || item.status === 'expired' ? item.status : 'open',
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** 从一段文本抽取前瞻条目(承诺/待办)。 */
|
|
222
|
+
export function extractProspective(text, options = {}) {
|
|
223
|
+
if (typeof text !== 'string' || text.trim() === '') return [];
|
|
224
|
+
const baseMs = nowMsOf(options.now);
|
|
225
|
+
const sessionId = typeof options.sessionId === 'string' ? options.sessionId : null;
|
|
226
|
+
const turn = Number.isInteger(options.turn) ? options.turn : 0;
|
|
227
|
+
const items = [];
|
|
228
|
+
for (const rawLine of text.split(/\r?\n/)) {
|
|
229
|
+
const line = rawLine.trim();
|
|
230
|
+
if (line === '') continue;
|
|
231
|
+
const triggerWord = TRIGGER_WORDS.find((word) => line.includes(word)) ?? null;
|
|
232
|
+
if (triggerWord === null) continue;
|
|
233
|
+
const hasTimeWord = TIME_WORDS.some((word) => line.includes(word));
|
|
234
|
+
if (!hasTimeWord) continue;
|
|
235
|
+
const redactedText = clip(redactMachinePaths(line), MAX_DUE_CHARS);
|
|
236
|
+
if (redactedText === '') continue;
|
|
237
|
+
const item = normalizeItem({
|
|
238
|
+
text: redactedText,
|
|
239
|
+
due: dueForLine(line, baseMs),
|
|
240
|
+
triggerWord,
|
|
241
|
+
createdAt: isoOf(baseMs),
|
|
242
|
+
sessionId,
|
|
243
|
+
turn,
|
|
244
|
+
}, options, baseMs);
|
|
245
|
+
if (item !== null) items.push(item);
|
|
246
|
+
}
|
|
247
|
+
return items;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** 计划允许的导出别名之一(与 extractProspective 等价)。 */
|
|
251
|
+
export function extractTasks(text, options = {}) {
|
|
252
|
+
return extractProspective(text, options);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** 计划允许的导出别名之一(与 extractProspective 等价)。 */
|
|
256
|
+
export function scanProspective(text, options = {}) {
|
|
257
|
+
return extractProspective(text, options);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** 追加候选到 prospective.jsonl(去重 / 条数上限 / done 保留期 / 原子写)。 */
|
|
261
|
+
export function appendProspective(input = {}) {
|
|
262
|
+
const memoryRoot = typeof input?.memoryRoot === 'string' ? input.memoryRoot : '';
|
|
263
|
+
const root = memoryRoot;
|
|
264
|
+
try {
|
|
265
|
+
if (root === '') failWithGate('', 'E_HG_D15_NO_ROOT', 'appendProspective requires memoryRoot');
|
|
266
|
+
const items = Array.isArray(input?.items) ? input.items : null;
|
|
267
|
+
if (items === null) failWithGate(root, 'E_HG_D15_BAD_ITEMS', 'appendProspective requires items array');
|
|
268
|
+
const baseMs = nowMsOf(input?.now);
|
|
269
|
+
const file = ledgerPath(root);
|
|
270
|
+
const before = readLedger(file, root);
|
|
271
|
+
const seen = new Set(before.map((row) => row.id));
|
|
272
|
+
const added = [];
|
|
273
|
+
for (const raw of items) {
|
|
274
|
+
const item = normalizeItem(raw, input ?? {}, baseMs);
|
|
275
|
+
if (item === null) continue;
|
|
276
|
+
if (seen.has(item.id)) continue;
|
|
277
|
+
seen.add(item.id);
|
|
278
|
+
added.push(item);
|
|
279
|
+
}
|
|
280
|
+
const merged = [...before, ...added];
|
|
281
|
+
const kept = trimLedger(merged, baseMs);
|
|
282
|
+
writeLedger(file, kept);
|
|
283
|
+
return { ok: true, added: added.length, total: kept.length, file, items: added };
|
|
284
|
+
} catch (error) {
|
|
285
|
+
if (error?.gate === GATE_EVENT) throw error;
|
|
286
|
+
failWithGate(root, 'E_HG_D15_APPEND_FAILED', error?.message ?? String(error));
|
|
287
|
+
return null;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function trimLedger(rows, baseMs) {
|
|
292
|
+
const cutoffDone = baseMs - DONE_RETENTION_DAYS * DAY_MS;
|
|
293
|
+
const cutoffAll = baseMs - RETENTION_DAYS * DAY_MS;
|
|
294
|
+
const kept = [];
|
|
295
|
+
for (const row of rows) {
|
|
296
|
+
const created = Date.parse(String(row?.createdAt ?? ''));
|
|
297
|
+
// done 超 30d 清出;expired 只标记不删(只受 500 条上限裁剪);其余超 90d 裁最旧
|
|
298
|
+
if (row?.status === 'done' && Number.isFinite(created) && created < cutoffDone) continue;
|
|
299
|
+
if (row?.status !== 'done' && row?.status !== 'expired'
|
|
300
|
+
&& Number.isFinite(created) && created < cutoffAll) continue;
|
|
301
|
+
kept.push(row);
|
|
302
|
+
}
|
|
303
|
+
if (kept.length <= MAX_ITEMS) return kept;
|
|
304
|
+
return kept.slice(kept.length - MAX_ITEMS);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** 选出本轮到期条目(≤3 条 / 每条 ≤120 字;过期未完成标 expired 不返回)。 */
|
|
308
|
+
export function selectDueProspective(input = {}) {
|
|
309
|
+
const memoryRoot = typeof input?.memoryRoot === 'string' ? input.memoryRoot : '';
|
|
310
|
+
const root = memoryRoot;
|
|
311
|
+
try {
|
|
312
|
+
if (root === '') failWithGate('', 'E_HG_D15_NO_ROOT', 'selectDueProspective requires memoryRoot');
|
|
313
|
+
const baseMs = nowMsOf(input?.now);
|
|
314
|
+
const file = ledgerPath(root);
|
|
315
|
+
const rows = readLedger(file, root);
|
|
316
|
+
const horizon = baseMs + DUE_HORIZON_MS;
|
|
317
|
+
const out = [];
|
|
318
|
+
let changed = false;
|
|
319
|
+
for (const row of rows) {
|
|
320
|
+
if (row?.status !== 'open') continue;
|
|
321
|
+
const dueMs = typeof row.due === 'string' ? Date.parse(row.due) : Number.NaN;
|
|
322
|
+
if (!Number.isFinite(dueMs)) continue;
|
|
323
|
+
if (dueMs < baseMs) {
|
|
324
|
+
row.status = 'expired';
|
|
325
|
+
row.expiredAt = isoOf(baseMs);
|
|
326
|
+
changed = true;
|
|
327
|
+
continue;
|
|
328
|
+
}
|
|
329
|
+
if (dueMs > horizon) continue;
|
|
330
|
+
out.push({ ...row, text: clip(row.text, MAX_DUE_CHARS) });
|
|
331
|
+
}
|
|
332
|
+
if (changed) writeLedger(file, rows);
|
|
333
|
+
out.sort((left, right) => (Date.parse(left.due) - Date.parse(right.due))
|
|
334
|
+
|| String(left.id).localeCompare(String(right.id)));
|
|
335
|
+
return { ok: true, items: out.slice(0, MAX_DUE_PER_ROUND), total: out.length, file };
|
|
336
|
+
} catch (error) {
|
|
337
|
+
if (error?.gate === GATE_EVENT) throw error;
|
|
338
|
+
failWithGate(root, 'E_HG_D15_SELECT_FAILED', error?.message ?? String(error));
|
|
339
|
+
return null;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** 便于上层判断账期(纯函数)。 */
|
|
344
|
+
export function prospectiveAgeDays(item, now = undefined) {
|
|
345
|
+
const baseMs = nowMsOf(now);
|
|
346
|
+
const created = Date.parse(String(item?.createdAt ?? ''));
|
|
347
|
+
if (!Number.isFinite(created)) return null;
|
|
348
|
+
return Math.max(0, (baseMs - created) / DAY_MS);
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** 供面板/测试读取账本(只读;坏行由 readLedger 走 fail-closed)。 */
|
|
352
|
+
export function readProspective(input = {}) {
|
|
353
|
+
const root = typeof input?.memoryRoot === 'string' ? input.memoryRoot : '';
|
|
354
|
+
if (root === '') failWithGate('', 'E_HG_D15_NO_ROOT', 'readProspective requires memoryRoot');
|
|
355
|
+
const file = ledgerPath(root);
|
|
356
|
+
const rows = readLedger(file, root);
|
|
357
|
+
return { ok: true, rows, total: rows.length, file };
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
export function dayStringOf(ms) {
|
|
361
|
+
return dayString(nowMsOf(ms));
|
|
362
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// Card provenance: who wrote a memory card, in which turn, and when.
|
|
2
|
+
//
|
|
3
|
+
// B3 adds three frontmatter keys to every card written by this package:
|
|
4
|
+
//
|
|
5
|
+
// source_session: <session id> who wrote it (or `manual` / `unknown`)
|
|
6
|
+
// source_turn: <integer> which turn of that session
|
|
7
|
+
// written_at: <ISO-8601 UTC> when the card was written
|
|
8
|
+
//
|
|
9
|
+
// They are *extras* (unknown keys) to the card format, so they live after the
|
|
10
|
+
// fixed fields and survive `updateFrontmatter`. The rules are deliberately
|
|
11
|
+
// conservative:
|
|
12
|
+
//
|
|
13
|
+
// * an existing value is never rewritten ("已有则保留");
|
|
14
|
+
// * a value we cannot know honestly is written as `unknown` (or `manual` when
|
|
15
|
+
// the caller is a human editing the store), never invented;
|
|
16
|
+
// * values are single-line, because the frontmatter format is single-line.
|
|
17
|
+
//
|
|
18
|
+
// The module only builds the values; it does not know which cards exist. The
|
|
19
|
+
// conflict/manifest layers consume the same keys through `readProvenance`.
|
|
20
|
+
|
|
21
|
+
import { memoryError } from './paths.js';
|
|
22
|
+
|
|
23
|
+
/** Frontmatter keys owned by this module, in the order a new card writes them. */
|
|
24
|
+
export const SOURCE_KEYS = Object.freeze(['source_session', 'source_turn', 'written_at']);
|
|
25
|
+
|
|
26
|
+
/** No caller identity was available. A real value must never be guessed. */
|
|
27
|
+
export const UNKNOWN_SESSION = 'unknown';
|
|
28
|
+
export const UNKNOWN_TURN = 'unknown';
|
|
29
|
+
/** A human used the tool directly (no session/turn exists). */
|
|
30
|
+
export const MANUAL_SESSION = 'manual';
|
|
31
|
+
|
|
32
|
+
const MAX_SESSION_CHARS = 200;
|
|
33
|
+
|
|
34
|
+
function singleLine(key, value) {
|
|
35
|
+
const text = String(value ?? '').replace(/[\r\n]+/g, ' ').trim();
|
|
36
|
+
if (text === '') return '';
|
|
37
|
+
if (text.length > MAX_SESSION_CHARS) {
|
|
38
|
+
throw memoryError('E_BAD_ARGUMENT', `frontmatter 字段 ${key} 过长(>${MAX_SESSION_CHARS} 字符)`);
|
|
39
|
+
}
|
|
40
|
+
return text;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Normalize a session id; empty/absent becomes null, never a made-up id. */
|
|
44
|
+
export function normalizeSessionId(value) {
|
|
45
|
+
if (typeof value !== 'string') return null;
|
|
46
|
+
const text = singleLine('source_session', value);
|
|
47
|
+
return text === '' ? null : text;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Normalize a turn: a non-negative integer, or null. Strings of digits work. */
|
|
51
|
+
export function normalizeTurn(value) {
|
|
52
|
+
if (typeof value === 'number') {
|
|
53
|
+
return Number.isInteger(value) && value >= 0 ? String(value) : null;
|
|
54
|
+
}
|
|
55
|
+
if (typeof value === 'string') {
|
|
56
|
+
const text = value.trim();
|
|
57
|
+
if (!/^\d+$/.test(text)) return null;
|
|
58
|
+
const number = Number(text);
|
|
59
|
+
return Number.isSafeInteger(number) ? String(number) : null;
|
|
60
|
+
}
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function isoAt(at) {
|
|
65
|
+
const date = at instanceof Date ? at : new Date(at ?? Date.now());
|
|
66
|
+
if (Number.isNaN(date.getTime())) {
|
|
67
|
+
throw memoryError('E_BAD_ARGUMENT', `written_at 需要合法时间,收到 ${JSON.stringify(at)}`);
|
|
68
|
+
}
|
|
69
|
+
return date.toISOString();
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Build the three values for a new write.
|
|
74
|
+
*
|
|
75
|
+
* `sessionId`/`turn` are optional; when the caller cannot provide them the
|
|
76
|
+
* stamp stays honest with `unknown`. `at` controls `written_at`.
|
|
77
|
+
*/
|
|
78
|
+
export function sourceStamp({ sessionId = null, turn = null, at = new Date() } = {}) {
|
|
79
|
+
return {
|
|
80
|
+
source_session: normalizeSessionId(sessionId) ?? UNKNOWN_SESSION,
|
|
81
|
+
source_turn: normalizeTurn(turn) ?? UNKNOWN_TURN,
|
|
82
|
+
written_at: isoAt(at),
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Merge a stamp into existing extras without changing any value that is
|
|
88
|
+
* already there. Existing keys keep their insertion order; missing keys are
|
|
89
|
+
* appended in SOURCE_KEYS order.
|
|
90
|
+
*/
|
|
91
|
+
export function stampExtras(existing = {}, { sessionId = null, turn = null, at = new Date() } = {}) {
|
|
92
|
+
const extras = { ...(existing && typeof existing === 'object' ? existing : {}) };
|
|
93
|
+
const fresh = sourceStamp({ sessionId, turn, at });
|
|
94
|
+
for (const key of SOURCE_KEYS) {
|
|
95
|
+
const current = extras[key];
|
|
96
|
+
if (typeof current === 'string' && current.trim() !== '') continue;
|
|
97
|
+
extras[key] = fresh[key];
|
|
98
|
+
}
|
|
99
|
+
return extras;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Read provenance out of parsed extras. Missing values stay null. */
|
|
103
|
+
export function readProvenance(extras = {}) {
|
|
104
|
+
const session = typeof extras?.source_session === 'string' && extras.source_session.trim() !== ''
|
|
105
|
+
? extras.source_session.trim()
|
|
106
|
+
: null;
|
|
107
|
+
const turn = typeof extras?.source_turn === 'string' && extras.source_turn.trim() !== ''
|
|
108
|
+
? extras.source_turn.trim()
|
|
109
|
+
: null;
|
|
110
|
+
const writtenAt = typeof extras?.written_at === 'string' && extras.written_at.trim() !== ''
|
|
111
|
+
? extras.written_at.trim()
|
|
112
|
+
: null;
|
|
113
|
+
return {
|
|
114
|
+
session,
|
|
115
|
+
turn,
|
|
116
|
+
written_at: writtenAt,
|
|
117
|
+
complete: session !== null && turn !== null && writtenAt !== null,
|
|
118
|
+
};
|
|
119
|
+
}
|