@jjh32456/longlive 1.8.12 → 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 +232 -202
- package/QUICKSTART.md +10 -11
- package/README.en.md +13 -4
- package/README.md +42 -11
- package/SPEC.md +3 -3
- package/build-info.json +231 -121
- package/cordis.patch.yml +32 -1
- package/docs/ARCHITECTURE.md +1 -1
- package/docs/AUTO-RECALL.md +1 -1
- package/docs/CONFIG.md +41 -9
- package/docs/FAQ.md +7 -7
- package/docs/FEATURES.md +6 -6
- package/docs/OPERATIONS.md +1 -1
- package/docs/PANEL-INTEGRATION.md +1 -1
- package/docs/PRIVACY.md +5 -5
- package/docs/QUICKSTART.md +3 -3
- package/docs/README.en.md +4 -2
- package/docs/TROUBLESHOOTING.md +4 -4
- package/package.json +6 -3
- package/runbook.md +3 -3
- package/scripts/migrate-200.mjs +8 -0
- package/scripts/migrate-lifecycle.mjs +2 -2
- package/src/answer/claim-guard.mjs +234 -0
- package/src/backup.js +165 -1
- package/src/config.js +18 -7
- package/src/features.js +128 -5
- package/src/handoff/index.js +133 -0
- package/src/handoff/model.js +48 -0
- package/src/identity/handover.js +203 -15
- package/src/identity/inject-position.js +3 -1
- package/src/memory/a1-migration.js +72 -6
- 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/capture-host.js +71 -2
- package/src/memory/capture.js +45 -6
- package/src/memory/catchup.mjs +534 -0
- package/src/memory/conclusion-distill.js +51 -2
- package/src/memory/conclusion-drafts.js +7 -3
- package/src/memory/conflicts.js +915 -2
- package/src/memory/consolidate.js +20 -1
- package/src/memory/forget-v2.js +272 -2
- package/src/memory/forget.js +20 -1
- package/src/memory/frames-activation.js +3 -1
- package/src/memory/fts-query.js +2 -2
- package/src/memory/index.js +80 -7
- package/src/memory/land.mjs +743 -0
- package/src/memory/lifecycle.js +128 -0
- package/src/memory/maintenance.js +386 -22
- package/src/memory/memory-health.mjs +607 -0
- package/src/memory/migrate-200.js +1681 -0
- package/src/memory/migrate-lifecycle.js +3 -3
- package/src/memory/procedure-candidate.mjs +377 -0
- package/src/memory/procedure.js +20 -1
- package/src/memory/prospective-memory.mjs +362 -0
- package/src/memory/recall-feedback.mjs +406 -0
- package/src/memory/recall-v2.js +13 -1
- package/src/memory/recall.js +102 -1
- package/src/memory/reinforce.js +138 -2
- package/src/memory/retention.js +34 -0
- package/src/memory/turn-budget.mjs +290 -0
- package/src/memory/wake-bridge.mjs +2999 -0
- package/src/memory/working-frame.js +271 -8
- package/src/metrics/classify.mjs +3 -1
- package/src/recall/archive-config.mjs +130 -0
- package/src/recall/archive-fallback.mjs +174 -19
- package/src/recall/archive-search.mjs +3 -0
- package/src/recall/archive-state.mjs +588 -0
- package/src/recall/brain.mjs +501 -0
- package/src/recall/current-line.mjs +110 -0
- package/src/recall/edges.js +21 -2
- package/src/recall/explain.mjs +10 -0
- package/src/recall/gate-log.mjs +280 -0
- package/src/recall/gate-metrics.mjs +191 -0
- package/src/recall/index.js +322 -21
- package/src/recall/inject-order.mjs +3 -1
- package/src/recall/recall-core.mjs +47 -2
- package/src/recall/turn-budget-inject.mjs +154 -0
- package/src/retention/cold-gate.mjs +146 -0
- package/src/retention/config.js +58 -1
- package/src/retention/index.js +193 -35
- package/src/router/design-headings.json +10 -10
- package/src/tools.js +122 -6
package/src/features.js
CHANGED
|
@@ -49,6 +49,8 @@ import { apply as applyAutoRecall } from './recall/index.js';
|
|
|
49
49
|
import { startPrestepPhase } from './metrics/prestep-latency.mjs';
|
|
50
50
|
import { createBus, normalizeSessionId, shouldAckOnTurnEnd } from './bus/bus.mjs';
|
|
51
51
|
import { createMaintenanceScheduler } from './memory/maintenance.js';
|
|
52
|
+
import { registerDailyHealth } from './memory/memory-health.mjs';
|
|
53
|
+
import { registerHardgateWake } from './memory/wake-bridge.mjs';
|
|
52
54
|
import { registerRetention, retentionHealth } from './retention/index.js';
|
|
53
55
|
import { normalizeActivityConfig, registerActivityStream } from './activity/index.js';
|
|
54
56
|
import { registerRole } from './role/index.js';
|
|
@@ -67,7 +69,15 @@ import {
|
|
|
67
69
|
|
|
68
70
|
export const FEATURE_DEFAULTS = Object.freeze({
|
|
69
71
|
autoRecall: Object.freeze({ enabled: true, topK: 3, budgetTokens: 2000, everyNTurns: 6 }),
|
|
70
|
-
identityCard: Object.freeze({
|
|
72
|
+
identityCard: Object.freeze({
|
|
73
|
+
enabled: true,
|
|
74
|
+
path: '<memoryRoot>/STATE.md',
|
|
75
|
+
maxChars: 2233,
|
|
76
|
+
recentBudgetChars: 1161,
|
|
77
|
+
// M04(DESIGN §8 C / G-D7):开机卡承接 handoff 摘要;handoff 退役前由 identityCard
|
|
78
|
+
// 承接,显式 false 时开机卡不注入交接节(HANDOVER_SUMMARY_DISABLED)。
|
|
79
|
+
handoffSummary: true,
|
|
80
|
+
}),
|
|
71
81
|
presenceBus: Object.freeze({ enabled: true, pollMs: 3000 }),
|
|
72
82
|
sharedBrain: Object.freeze({
|
|
73
83
|
// 1.8.8 M3: 24h live window (time first, row guard second) + recap budget.
|
|
@@ -91,6 +101,10 @@ export const FEATURE_DEFAULTS = Object.freeze({
|
|
|
91
101
|
// 02-handoff: default OFF (hard constraint ① — 1.8.3 behaviour is unchanged
|
|
92
102
|
// unless the profile config row opts in with `handoff.enabled: true`).
|
|
93
103
|
handoff: Object.freeze({ enabled: false, dryRun: false }),
|
|
104
|
+
// H 批 hardgate 唤醒桥(N15):默认 OFF。这里只放「文档占位」,真正的 6 键归一化/
|
|
105
|
+
// 钳制在 src/memory/wake-bridge.mjs 的 normalizeWakeConfig(raw passthrough,与
|
|
106
|
+
// proactive/handoff 同法,不加 schemastery 节点——config schema 153 节点锁不变)。
|
|
107
|
+
hardgate: Object.freeze({ wake: Object.freeze({ enabled: false }) }),
|
|
94
108
|
});
|
|
95
109
|
|
|
96
110
|
function clampInt(value, fallback, min, max) {
|
|
@@ -119,8 +133,16 @@ export function normalizeFeatureConfig(config = {}) {
|
|
|
119
133
|
? value.autoMaintenance
|
|
120
134
|
: {};
|
|
121
135
|
const handoff = value.handoff && typeof value.handoff === 'object' ? value.handoff : {};
|
|
136
|
+
// H 批 hardgate 唤醒桥(N15):只读 raw `config.hardgate?.wake`,raw 透传给
|
|
137
|
+
// wake-bridge(同 F 批 archiveRoot 三键做法:这里不归一化、不加 schemastery 节点,
|
|
138
|
+
// config schema 153 节点锁不变;6/12 键默认值与钳制仍在
|
|
139
|
+
// wake-bridge.normalizeWakeConfig,注册 registerHardgateWake 时执行)。
|
|
140
|
+
const hardgate = value.hardgate && typeof value.hardgate === 'object' ? value.hardgate : {};
|
|
141
|
+
const wake = hardgate.wake && typeof hardgate.wake === 'object' && !Array.isArray(hardgate.wake)
|
|
142
|
+
? hardgate.wake
|
|
143
|
+
: null;
|
|
122
144
|
|
|
123
|
-
|
|
145
|
+
const normalized = {
|
|
124
146
|
autoRecall: {
|
|
125
147
|
enabled: bool(auto.enabled),
|
|
126
148
|
topK: clampInt(auto.topK, FEATURE_DEFAULTS.autoRecall.topK, 1, 10),
|
|
@@ -133,6 +155,13 @@ export function normalizeFeatureConfig(config = {}) {
|
|
|
133
155
|
enabled: bool(identity.enabled),
|
|
134
156
|
path: text(identity.path) ?? FEATURE_DEFAULTS.identityCard.path,
|
|
135
157
|
maxChars: clampInt(identity.maxChars, FEATURE_DEFAULTS.identityCard.maxChars, 120, 4000),
|
|
158
|
+
recentBudgetChars: clampInt(
|
|
159
|
+
identity.recentBudgetChars,
|
|
160
|
+
FEATURE_DEFAULTS.identityCard.recentBudgetChars,
|
|
161
|
+
120,
|
|
162
|
+
4000,
|
|
163
|
+
),
|
|
164
|
+
handoffSummary: bool(identity.handoffSummary),
|
|
136
165
|
createUserMessage: typeof identity.createUserMessage === 'function' ? identity.createUserMessage : undefined,
|
|
137
166
|
},
|
|
138
167
|
presenceBus: {
|
|
@@ -159,6 +188,11 @@ export function normalizeFeatureConfig(config = {}) {
|
|
|
159
188
|
// Optional block, additive only: absent → default OFF (zero hooks, zero IO).
|
|
160
189
|
handoff: normalizeHandoffConfig(handoff),
|
|
161
190
|
};
|
|
191
|
+
// H 批 hardgate 唤醒桥(N15,spec §5.5:314):只有 raw config 带 `hardgate.wake`
|
|
192
|
+
// 时才追加该键(值/键原样透传,浅拷贝防外部改写);不带该键时输出仍是上面那 6 键,
|
|
193
|
+
// 既有 defaults 快照(feature-flags deepEqual)逐字节不变。
|
|
194
|
+
if (wake) normalized.hardgate = { wake: { ...wake } };
|
|
195
|
+
return normalized;
|
|
162
196
|
}
|
|
163
197
|
|
|
164
198
|
/** Resolve `<memoryRoot>/STATE.md` and prove it stays inside the memory root. */
|
|
@@ -278,6 +312,8 @@ function registerIdentityCard(ctx, cfg, memoryRoot, warn) {
|
|
|
278
312
|
memoryRoot: memoryRoot ?? undefined,
|
|
279
313
|
statePath: cardPath ?? undefined,
|
|
280
314
|
maxChars: cfg.maxChars,
|
|
315
|
+
recentBudgetChars: cfg.recentBudgetChars,
|
|
316
|
+
handoffSummary: cfg.handoffSummary,
|
|
281
317
|
});
|
|
282
318
|
state.card = typeof card?.text === 'string' ? card.text : '';
|
|
283
319
|
} catch (error) {
|
|
@@ -755,9 +791,12 @@ export function registerFeatures(ctx, config = {}, options = {}) {
|
|
|
755
791
|
}
|
|
756
792
|
}
|
|
757
793
|
|
|
758
|
-
|
|
794
|
+
// M04:硬门 handler 恒注册(kill switch 也是注册态)。
|
|
795
|
+
// autoRecall.enabled=false 不再「不挂钩子」——apply() 里 handler 恒挂,交给 brain 走
|
|
796
|
+
// killswitch 分支:注入「硬门已被关闭(配置)」告警块 + gate-log decision=disabled。
|
|
797
|
+
{
|
|
759
798
|
const recallConfig = {
|
|
760
|
-
autoRecall:
|
|
799
|
+
autoRecall: cfg.autoRecall.enabled !== false,
|
|
761
800
|
maxItems: cfg.autoRecall.topK,
|
|
762
801
|
budget: cfg.autoRecall.budgetTokens,
|
|
763
802
|
everyNTurns: cfg.autoRecall.everyNTurns,
|
|
@@ -781,8 +820,23 @@ export function registerFeatures(ctx, config = {}, options = {}) {
|
|
|
781
820
|
if (rawAutoRecall.privacyPolicy !== undefined) recallConfig.privacyPolicy = rawAutoRecall.privacyPolicy;
|
|
782
821
|
const rawRecallLinks = config.recall && typeof config.recall === 'object' ? config.recall.links : null;
|
|
783
822
|
if (rawRecallLinks && typeof rawRecallLinks === 'object') recallConfig.links = rawRecallLinks;
|
|
823
|
+
// 2.0.0 W3b(M31/M32):冷档三键同走 raw 透传——archiveRoot / archiveStatePath /
|
|
824
|
+
// archiveFailOpen 只影响 recall 的归档兜底,不属于 normalizeFeatureConfig 的三块开关
|
|
825
|
+
// (feature-flags 的既有 deepEqual 锁死了那个输出形状;153 节点锁保持不变),
|
|
826
|
+
// recall 也不为它们声明 schemastery 节点。
|
|
827
|
+
const rawRecall = config.recall && typeof config.recall === 'object' ? config.recall : {};
|
|
828
|
+
if (typeof rawRecall.archiveRoot === 'string' && rawRecall.archiveRoot.trim() !== '') {
|
|
829
|
+
recallConfig.archiveRoot = rawRecall.archiveRoot;
|
|
830
|
+
}
|
|
831
|
+
if (typeof rawRecall.archiveStatePath === 'string' && rawRecall.archiveStatePath.trim() !== '') {
|
|
832
|
+
recallConfig.archiveStatePath = rawRecall.archiveStatePath;
|
|
833
|
+
}
|
|
834
|
+
if (rawRecall.archiveFailOpen !== undefined) recallConfig.archiveFailOpen = rawRecall.archiveFailOpen;
|
|
784
835
|
applyAutoRecall(ctx, recallConfig);
|
|
785
|
-
|
|
836
|
+
// The hardgate handler is always registered (kill switch is decided inside
|
|
837
|
+
// src/recall/index.js), but a killed recall is NOT an opt-in feature: the
|
|
838
|
+
// activation list and the startup log line stay byte-identical for flags-off.
|
|
839
|
+
if (cfg.autoRecall.enabled !== false) enabled.push('autoRecall');
|
|
786
840
|
}
|
|
787
841
|
|
|
788
842
|
if (cfg.presenceBus.enabled) {
|
|
@@ -816,6 +870,14 @@ export function registerFeatures(ctx, config = {}, options = {}) {
|
|
|
816
870
|
warn('[longlive] autoMaintenance 已开启但没有可解析的 memoryRoot — 已跳过');
|
|
817
871
|
} else {
|
|
818
872
|
try {
|
|
873
|
+
// 2.0.0 W3b(⑧):每日维护/启动探针要拿冷档根与 state 路径,同样走 raw 透传。
|
|
874
|
+
const rawRecallArchive = config.recall && typeof config.recall === 'object' ? config.recall : {};
|
|
875
|
+
const archiveRootRaw = typeof rawRecallArchive.archiveRoot === 'string' && rawRecallArchive.archiveRoot.trim() !== ''
|
|
876
|
+
? rawRecallArchive.archiveRoot
|
|
877
|
+
: null;
|
|
878
|
+
const archiveStatePathRaw = typeof rawRecallArchive.archiveStatePath === 'string' && rawRecallArchive.archiveStatePath.trim() !== ''
|
|
879
|
+
? rawRecallArchive.archiveStatePath
|
|
880
|
+
: null;
|
|
819
881
|
const scheduler = createMaintenanceScheduler({
|
|
820
882
|
memoryRoot,
|
|
821
883
|
config: {
|
|
@@ -823,6 +885,9 @@ export function registerFeatures(ctx, config = {}, options = {}) {
|
|
|
823
885
|
// Host-injected session root; never derive it from an implicit
|
|
824
886
|
// memory root or the current machine's home.
|
|
825
887
|
sessionsRoot: options.sessionsRoot ?? null,
|
|
888
|
+
// 冷档探针槽(archive-state 写入方)的输入;未配置则为 null → 槽 not_run。
|
|
889
|
+
archiveRoot: archiveRootRaw,
|
|
890
|
+
archiveStatePath: archiveStatePathRaw,
|
|
826
891
|
},
|
|
827
892
|
// Test seam only (CONFIG.md lists `now` as internal); never a
|
|
828
893
|
// deployment-facing setting.
|
|
@@ -849,6 +914,33 @@ export function registerFeatures(ctx, config = {}, options = {}) {
|
|
|
849
914
|
}
|
|
850
915
|
}
|
|
851
916
|
|
|
917
|
+
// D21(§14 接线):记忆体检每日 job —— 与 memory vault(memoryV2)同一个开关,
|
|
918
|
+
// 还要有 memoryRoot;单 timer(启动后轻量跑一次,此后每日本地午夜一次,同日重入跳过),
|
|
919
|
+
// 由 ctx.effect 释放;失败只落 health 文件 errorCodes + stderr,不写 gate 事件、不抛。
|
|
920
|
+
if (memoryV2On && memoryRoot) {
|
|
921
|
+
try {
|
|
922
|
+
const healthJob = registerDailyHealth({
|
|
923
|
+
memoryRoot,
|
|
924
|
+
now: config.now,
|
|
925
|
+
timers: config.timers,
|
|
926
|
+
logger: warn,
|
|
927
|
+
});
|
|
928
|
+
if (healthJob.enabled) {
|
|
929
|
+
healthJob.start();
|
|
930
|
+
if (typeof ctx.effect === 'function') {
|
|
931
|
+
try {
|
|
932
|
+
ctx.effect(() => () => healthJob.stop(), 'longlive.memory-health');
|
|
933
|
+
} catch {
|
|
934
|
+
/* a fake/simple ctx may not support effect; the timer still runs */
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
enabled.push('memoryHealth');
|
|
938
|
+
}
|
|
939
|
+
} catch (error) {
|
|
940
|
+
warn(`[longlive] memory-health 启动失败(${error?.code ?? error?.message ?? error})— 已跳过`);
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
|
|
852
944
|
// Startup health check is independent of whether the janitor is enabled:
|
|
853
945
|
// the panel can read the returned/status object, and an over-budget
|
|
854
946
|
// .longlive produces one visible warning instead of silently growing.
|
|
@@ -905,6 +997,37 @@ export function registerFeatures(ctx, config = {}, options = {}) {
|
|
|
905
997
|
warn(`[longlive] role 装配失败(${error?.code ?? error?.message ?? error})— 已跳过`);
|
|
906
998
|
}
|
|
907
999
|
}
|
|
1000
|
+
// H 批 hardgate 唤醒桥(N15):常驻钩子插在 role kernel 之后、内建 working-frame 注入之后
|
|
1001
|
+
// (pre-step {prepend:false})。它是「后台会话工厂」而不是审查器:能力探测(auto preset +
|
|
1002
|
+
// 0.2.3-alpha.2)失败一律 fail-closed(0 会话 0 重试),只写 gate-log/panel 让人能看见。
|
|
1003
|
+
// daily 对账 timer 由 wake-bridge 自己按 nextLocalMidnight 调度,独立于 autoMaintenance。
|
|
1004
|
+
if (memoryRoot && config?.hardgate && typeof config.hardgate === 'object' && config.hardgate.wake && typeof config.hardgate.wake === 'object') {
|
|
1005
|
+
try {
|
|
1006
|
+
const wakeHandle = registerHardgateWake(ctx, config.hardgate.wake, {
|
|
1007
|
+
memoryRoot,
|
|
1008
|
+
now: typeof config.now === 'function' ? config.now : undefined,
|
|
1009
|
+
timers: config.timers,
|
|
1010
|
+
env: process.env,
|
|
1011
|
+
warn,
|
|
1012
|
+
installToolPolicy: typeof config.hardgateWakeInstallToolPolicy === 'function' ? config.hardgateWakeInstallToolPolicy : undefined,
|
|
1013
|
+
});
|
|
1014
|
+
if (wakeHandle && typeof wakeHandle.dispose === 'function') {
|
|
1015
|
+
try {
|
|
1016
|
+
ctx.effect(() => () => wakeHandle.dispose(), 'longlive.hardgate-wake');
|
|
1017
|
+
} catch {
|
|
1018
|
+
/* a fake/simple ctx may not support effect; the handle still disposes on demand */
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
if (wakeHandle?.enabled) enabled.push('hardgate.wake');
|
|
1022
|
+
else if (wakeHandle?.registered === true) {
|
|
1023
|
+
// 钩子已装但能力暂缺:可见 warning,不在下一轮静默重试(drain 自带 enabled 门)。
|
|
1024
|
+
warn(`[longlive] hardgate.wake 未启用(${wakeHandle.code ?? 'capability-missing'}: ${wakeHandle.detail?.reason ?? 'unknown'})— fail-closed`);
|
|
1025
|
+
}
|
|
1026
|
+
} catch (error) {
|
|
1027
|
+
warn(`[longlive] hardgate.wake 装配失败(${error?.code ?? error?.message ?? error})— 已跳过`);
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
|
|
908
1031
|
if (enabled.length > 0 && logger && typeof logger.info === 'function') {
|
|
909
1032
|
logger.info(`[longlive] opt-in features: ${enabled.join(', ')}`);
|
|
910
1033
|
}
|
package/src/handoff/index.js
CHANGED
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
// the independent kill switch. `dryRun:true` selects/audits but never claims or
|
|
22
22
|
// injects, so a first enablement can be watched before the real switch.
|
|
23
23
|
|
|
24
|
+
import fs from 'node:fs';
|
|
24
25
|
import path from 'node:path';
|
|
25
26
|
|
|
26
27
|
import { isSubagentSession } from '../identity/index.js';
|
|
@@ -51,12 +52,14 @@ import {
|
|
|
51
52
|
contentHashOf,
|
|
52
53
|
buildCardDelta,
|
|
53
54
|
cardIdOf,
|
|
55
|
+
cardSubstantive,
|
|
54
56
|
hash8,
|
|
55
57
|
isActiveSessionId,
|
|
56
58
|
mergeLatestCard,
|
|
57
59
|
renderHandoffCard,
|
|
58
60
|
sanitizeCardFields,
|
|
59
61
|
selectCandidate,
|
|
62
|
+
summarizeHandoffCard,
|
|
60
63
|
} from './model.js';
|
|
61
64
|
import {
|
|
62
65
|
appendAudit,
|
|
@@ -239,6 +242,114 @@ function compactTrace(trace) {
|
|
|
239
242
|
}));
|
|
240
243
|
}
|
|
241
244
|
|
|
245
|
+
// ------------------------------------------------------------------ handoffSummary (M24)
|
|
246
|
+
|
|
247
|
+
function summaryFileName(atMs) {
|
|
248
|
+
const date = new Date(Number.isFinite(atMs) ? atMs : Date.now());
|
|
249
|
+
const day = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
|
|
250
|
+
return `${day}-handoff.md`;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* 把最新交接卡提炼成 1–2 行,落到 `<memoryRoot>/handover/<YYYY-MM-DD>-handoff.md`。
|
|
255
|
+
* 承接链路:handoff 生产侧 → handover 卡(markdown)→ identityCard「▍交接卡」节
|
|
256
|
+
* (A 批 M04 已实装读取侧)。只写摘要,不复制卡里其它字段。
|
|
257
|
+
*/
|
|
258
|
+
export function writeHandoffSummary(input = {}) {
|
|
259
|
+
const root = typeof input?.memoryRoot === 'string' && input.memoryRoot.trim() !== ''
|
|
260
|
+
? path.resolve(input.memoryRoot)
|
|
261
|
+
: '';
|
|
262
|
+
if (root === '') return { ok: false, code: 'E_HANDOFF_NO_MEMORY_ROOT', file: null, text: '' };
|
|
263
|
+
const nowMs = typeof input.now === 'number' && Number.isFinite(input.now)
|
|
264
|
+
? input.now
|
|
265
|
+
: (input.now instanceof Date && Number.isFinite(input.now.getTime()) ? input.now.getTime() : Date.now());
|
|
266
|
+
const summary = summarizeHandoffCard(input.card);
|
|
267
|
+
if (!summary.ok) return { ok: false, code: 'E_HANDOFF_SUMMARY_EMPTY', file: null, text: '', lines: [] };
|
|
268
|
+
const dir = path.join(root, 'handover');
|
|
269
|
+
const file = path.join(dir, summaryFileName(nowMs));
|
|
270
|
+
try {
|
|
271
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
272
|
+
const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
|
|
273
|
+
fs.writeFileSync(tmp, `${summary.text}\n`, 'utf8');
|
|
274
|
+
fs.renameSync(tmp, file);
|
|
275
|
+
} catch (error) {
|
|
276
|
+
return { ok: false, code: error?.code ?? 'E_HANDOFF_WRITE', file, text: summary.text, lines: summary.lines };
|
|
277
|
+
}
|
|
278
|
+
return { ok: true, file, text: summary.text, lines: summary.lines, chars: summary.chars };
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* 读取当前最新交接卡并返回 1–2 行 handoffSummary(只读;无卡/无实质内容如实返回空)。
|
|
283
|
+
* 主源:`<memoryRoot>/.longlive/bridge/*.handoff-card.json`;回退源:`<memoryRoot>/handover/*.json`
|
|
284
|
+
* (旧口径/夹具把卡直接落在 handover 目录;只接受 cardSubstantive 为真的卡)。
|
|
285
|
+
* 返回 { ok, code, text, summary, lines, chars, cardId, at, source }。
|
|
286
|
+
*/
|
|
287
|
+
export function handoffSummary(input = {}) {
|
|
288
|
+
const root = typeof input?.memoryRoot === 'string' && input.memoryRoot.trim() !== ''
|
|
289
|
+
? path.resolve(input.memoryRoot)
|
|
290
|
+
: '';
|
|
291
|
+
if (root === '') return { ok: false, code: 'E_HANDOFF_NO_MEMORY_ROOT', text: '', lines: [] };
|
|
292
|
+
const read = readLatestCards(root, { maxFiles: 64 });
|
|
293
|
+
let cards = read.ok
|
|
294
|
+
? (Array.isArray(read.cards) ? read.cards : []).filter((entry) => cardSubstantive(entry.card))
|
|
295
|
+
: [];
|
|
296
|
+
if (cards.length === 0) cards = readHandoverJsonCards(root);
|
|
297
|
+
if (cards.length === 0) return { ok: false, code: 'E_HANDOFF_SUMMARY_EMPTY', text: '', lines: [], cards: 0 };
|
|
298
|
+
const entry = cards[0];
|
|
299
|
+
const summary = summarizeHandoffCard(entry.card);
|
|
300
|
+
return {
|
|
301
|
+
ok: summary.ok,
|
|
302
|
+
code: summary.ok ? null : summary.code,
|
|
303
|
+
text: summary.text,
|
|
304
|
+
summary: summary.text,
|
|
305
|
+
lines: summary.lines,
|
|
306
|
+
chars: summary.chars,
|
|
307
|
+
cardId: entry.cardId,
|
|
308
|
+
at: entry.card?.at ?? null,
|
|
309
|
+
source: {
|
|
310
|
+
sessionId: entry.card?.source?.sessionId ?? null,
|
|
311
|
+
turn: entry.card?.turn ?? null,
|
|
312
|
+
},
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** handover 目录里的卡 JSON 回退源(mtime 降序,只留 cardSubstantive)。 */
|
|
317
|
+
function readHandoverJsonCards(root) {
|
|
318
|
+
const dir = path.join(root, 'handover');
|
|
319
|
+
let entries = [];
|
|
320
|
+
try {
|
|
321
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
322
|
+
} catch {
|
|
323
|
+
return [];
|
|
324
|
+
}
|
|
325
|
+
const cards = [];
|
|
326
|
+
for (const entry of entries) {
|
|
327
|
+
if (!entry.isFile() || !/\.json$/iu.test(entry.name) || entry.name.startsWith('.')) continue;
|
|
328
|
+
const file = path.join(dir, entry.name);
|
|
329
|
+
let stat;
|
|
330
|
+
try {
|
|
331
|
+
stat = fs.statSync(file);
|
|
332
|
+
} catch {
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
let card;
|
|
336
|
+
try {
|
|
337
|
+
card = JSON.parse(fs.readFileSync(file, 'utf8').replace(/^\uFEFF/, ''));
|
|
338
|
+
} catch {
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
if (!cardSubstantive(card)) continue;
|
|
342
|
+
cards.push({
|
|
343
|
+
card,
|
|
344
|
+
cardId: cardIdOf({ sessionId: card?.source?.sessionId, turn: card?.turn }),
|
|
345
|
+
file,
|
|
346
|
+
mtimeMs: stat.mtimeMs,
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
cards.sort((left, right) => right.mtimeMs - left.mtimeMs);
|
|
350
|
+
return cards;
|
|
351
|
+
}
|
|
352
|
+
|
|
242
353
|
// ------------------------------------------------------------------ stream
|
|
243
354
|
|
|
244
355
|
/**
|
|
@@ -285,6 +396,7 @@ export function createHandoffStream(options = {}) {
|
|
|
285
396
|
injected: 0,
|
|
286
397
|
skipped: 0,
|
|
287
398
|
skippedByCode: {},
|
|
399
|
+
gateSkip: 0,
|
|
288
400
|
claims: 0,
|
|
289
401
|
errors: 0,
|
|
290
402
|
lastError: null,
|
|
@@ -334,6 +446,21 @@ export function createHandoffStream(options = {}) {
|
|
|
334
446
|
});
|
|
335
447
|
}
|
|
336
448
|
|
|
449
|
+
// M23:交接质量门。垃圾/薄卡不产卡,只记审计事件(op='gate',code=E_HANDOFF_CARD_TOO_THIN)。
|
|
450
|
+
function auditGate(sessionId, turn, code, card) {
|
|
451
|
+
stats.gateSkip += 1;
|
|
452
|
+
return audit('gate', {
|
|
453
|
+
sessionId,
|
|
454
|
+
turn,
|
|
455
|
+
gate: 'handoff',
|
|
456
|
+
cardId: cardIdOf({ sessionId, turn }),
|
|
457
|
+
code,
|
|
458
|
+
goalChars: charLengthOf(card?.goal ?? ''),
|
|
459
|
+
decidedN: Array.isArray(card?.decided) ? card.decided.length : 0,
|
|
460
|
+
substantiveChars: card?.substantiveChars ?? 0,
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
|
|
337
464
|
// ---- producer -----------------------------------------------------------
|
|
338
465
|
|
|
339
466
|
function stateFor(sessionId) {
|
|
@@ -386,6 +513,8 @@ export function createHandoffStream(options = {}) {
|
|
|
386
513
|
if (merged.empty) return auditWriteSkip(state.sessionId, turn, 'E_HANDOFF_EMPTY', merged.card);
|
|
387
514
|
if (merged.trivial) return auditWriteSkip(state.sessionId, turn, 'E_HANDOFF_TRIVIAL', merged.card);
|
|
388
515
|
if (!merged.changed) return auditWriteSkip(state.sessionId, turn, 'E_HANDOFF_NO_DELTA', merged.card);
|
|
516
|
+
// M23(DESIGN §2 G 行 / §3):trivial 与薄卡一律不产卡;质量门必须先于写入。
|
|
517
|
+
if (!cardSubstantive(merged.card)) return auditGate(state.sessionId, turn, 'E_HANDOFF_CARD_TOO_THIN', merged.card);
|
|
389
518
|
// Bounded maintenance rides on the write path (N3/M4).
|
|
390
519
|
try { pruneCards(memoryRoot, { now: atMs, maxAgeMs }); } catch { /* best effort */ }
|
|
391
520
|
try { pruneClaims(memoryRoot, { now: atMs, maxAgeMs }); } catch { /* best effort */ }
|
|
@@ -403,6 +532,10 @@ export function createHandoffStream(options = {}) {
|
|
|
403
532
|
}
|
|
404
533
|
stats.writeOk += 1;
|
|
405
534
|
stats.cards = Math.max(stats.cards, 1);
|
|
535
|
+
// M24:承接 —— 卡写成后同步 1–2 行 handoffSummary,供 identityCard「▍交接卡」注入。
|
|
536
|
+
try {
|
|
537
|
+
writeHandoffSummary({ memoryRoot, card: merged.card, now: atMs });
|
|
538
|
+
} catch { /* 摘要承接是尽力而为,失败不影响卡本身 */ }
|
|
406
539
|
return audit('write', {
|
|
407
540
|
sessionId: state.sessionId,
|
|
408
541
|
turn,
|
package/src/handoff/model.js
CHANGED
|
@@ -286,6 +286,54 @@ export function cardSubstantive(card) {
|
|
|
286
286
|
return gateA && gateB && !trivial;
|
|
287
287
|
}
|
|
288
288
|
|
|
289
|
+
// ------------------------------------------------------------------ handoffSummary (M24)
|
|
290
|
+
|
|
291
|
+
/** handoffSummary:1–2 行、总长 ≤120 码点,供开机卡「▍交接卡」承接。 */
|
|
292
|
+
export const HANDOFF_SUMMARY_MAX_CHARS = 120;
|
|
293
|
+
export const HANDOFF_SUMMARY_MAX_LINES = 2;
|
|
294
|
+
/** 单行预算(留出「下一步:」等前缀)。 */
|
|
295
|
+
export const HANDOFF_SUMMARY_LINE_CHARS = 56;
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* 从最新交接卡提炼 1–2 行摘要(纯函数,不做 IO)。
|
|
299
|
+
* 行 1 = 目标;行 2 = 下一步 / 未决 / 最近结论(取其一)。没有可摘要内容时如实返回空。
|
|
300
|
+
*/
|
|
301
|
+
export function summarizeHandoffCard(card, options = {}) {
|
|
302
|
+
const maxChars = Number.isFinite(options.maxChars) ? Math.max(16, options.maxChars) : HANDOFF_SUMMARY_MAX_CHARS;
|
|
303
|
+
const lineChars = Number.isFinite(options.lineChars) ? Math.max(8, options.lineChars) : HANDOFF_SUMMARY_LINE_CHARS;
|
|
304
|
+
const lines = [];
|
|
305
|
+
const push = (line) => {
|
|
306
|
+
const text = clip(oneLine(line), lineChars);
|
|
307
|
+
if (text === '' || lines.length >= HANDOFF_SUMMARY_MAX_LINES) return;
|
|
308
|
+
lines.push(text);
|
|
309
|
+
};
|
|
310
|
+
const goal = oneLine(card?.goal ?? '');
|
|
311
|
+
if (goal !== '') push(goal);
|
|
312
|
+
const next = oneLine(card?.next ?? '');
|
|
313
|
+
const open = oneLine(card?.open ?? '');
|
|
314
|
+
const decided = Array.isArray(card?.decided)
|
|
315
|
+
? card.decided.map((item) => oneLine(item?.text ?? '')).filter((text) => text !== '')
|
|
316
|
+
: [];
|
|
317
|
+
if (next !== '') push(`下一步:${next}`);
|
|
318
|
+
else if (open !== '') push(`未决:${open}`);
|
|
319
|
+
else if (decided.length > 0) push(`已结论:${decided[decided.length - 1]}`);
|
|
320
|
+
// 清空超预算尾部(按总预算裁剪,不切半行)。
|
|
321
|
+
while (lines.length > 0 && charLength(lines.join('\n')) > maxChars) lines.pop();
|
|
322
|
+
const text = lines.join('\n');
|
|
323
|
+
return {
|
|
324
|
+
ok: lines.length > 0,
|
|
325
|
+
code: lines.length > 0 ? null : 'E_HANDOFF_SUMMARY_EMPTY',
|
|
326
|
+
lines,
|
|
327
|
+
text,
|
|
328
|
+
chars: charLength(text),
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/** 摘要的纯文本(memo 用别名;d7 允许 summarizeHandoff 这个名字)。 */
|
|
333
|
+
export function summarizeHandoff(card, options = {}) {
|
|
334
|
+
return summarizeHandoffCard(card, options).text;
|
|
335
|
+
}
|
|
336
|
+
|
|
289
337
|
function dedupeDecided(decided) {
|
|
290
338
|
const byKey = new Map();
|
|
291
339
|
for (const item of Array.isArray(decided) ? decided : []) {
|