@jjh32456/dsh-longlive 1.6.8 → 1.8.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 +69 -1539
- package/LICENSE +1 -1
- package/QUICKSTART.md +33 -12
- package/README.en.md +17 -7
- package/README.md +29 -10
- package/SPEC.md +5 -5
- package/cordis.patch.yml +17 -12
- package/docs/ANSWER-GUARD.md +92 -0
- package/docs/ARCHITECTURE.md +3 -3
- package/docs/AUTO-RECALL-WIRING.md +1 -1
- package/docs/AUTO-RECALL.md +15 -9
- package/docs/CONFIG.md +143 -37
- package/docs/ERRORS.md +17 -5
- package/docs/FAQ.md +7 -7
- package/docs/FEATURES.md +66 -29
- package/docs/MIGRATION-1.6.0.md +2 -2
- package/docs/OPERATIONS.md +6 -6
- package/docs/PANEL-INTEGRATION.md +6 -0
- package/docs/PRIVACY.md +88 -0
- package/docs/QUICKSTART.md +5 -5
- package/docs/README.en.md +3 -2
- package/docs/RESIDENT-WATCHER.md +1 -1
- package/docs/SESSION-WATCH.md +6 -6
- package/docs/TROUBLESHOOTING.md +4 -4
- package/package.json +42 -117
- package/runbook.md +2 -2
- package/scripts/backfill-auto-cards.mjs +98 -0
- package/scripts/install-surgery-task.ps1 +5 -2
- package/scripts/lib/session-watch-fixture.mjs +1 -1
- package/scripts/longlive-doctor.mjs +6 -0
- package/scripts/migrate-180.mjs +163 -0
- package/scripts/recall-index-build.mjs +128 -0
- package/scripts/session-watch-drill.mjs +1 -1
- package/scripts/surgery-run.cmd +1 -1
- package/scripts/unattended-surgery.ps1 +5 -2
- package/scripts/verify-card-anchors.mjs +138 -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 +129 -18
- package/src/activity/model.js +11 -1
- package/src/activity/store.js +22 -3
- package/src/activity/thinking.js +176 -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 +235 -0
- package/src/adapters/registry.js +315 -0
- package/src/answer/audit.js +193 -0
- package/src/answer/evidence.js +30 -0
- package/src/answer/guard.js +1370 -0
- package/src/answer/index.js +1067 -0
- package/src/answer/query.js +111 -0
- package/src/answer/second-hop.mjs +101 -0
- package/src/auto-truncate.js +1 -1
- package/src/config.js +145 -48
- package/src/deps.js +6 -4
- package/src/features.js +158 -8
- package/src/identity/index.js +13 -5
- package/src/identity/inject-position.js +2 -2
- package/src/index.js +97 -7
- package/src/lifecycle/gap-clocks.js +328 -0
- package/src/lifecycle/index.js +269 -0
- package/src/memory/activity-capture.js +229 -0
- package/src/memory/anchors.js +194 -0
- package/src/memory/audit-records.js +222 -0
- package/src/memory/auto-cards.js +401 -0
- package/src/memory/capture.js +442 -0
- package/src/memory/card-anchors.js +203 -0
- package/src/memory/conflicts.js +106 -0
- package/src/memory/decay.js +311 -0
- package/src/memory/distill.js +471 -0
- package/src/memory/event-index.js +917 -0
- package/src/memory/evidence-chain.js +295 -0
- package/src/memory/evidence.js +145 -0
- package/src/memory/filter-runner.js +1 -1
- package/src/memory/filter.js +5 -1
- package/src/memory/forget-v2.js +410 -0
- package/src/memory/forget.js +71 -0
- package/src/memory/frames-activation.js +247 -0
- package/src/memory/fts-query.js +174 -0
- package/src/memory/governance.js +604 -0
- package/src/memory/index.js +1 -0
- package/src/memory/l2-gate.js +169 -0
- package/src/memory/lock.js +121 -0
- package/src/memory/migrate.js +139 -0
- package/src/memory/recall-v2.js +223 -0
- package/src/memory/recall.js +65 -2
- package/src/memory/records.js +425 -0
- package/src/memory/retention.js +128 -0
- package/src/memory/review.js +124 -0
- package/src/memory/trust.js +88 -0
- package/src/memory/version-chain.js +264 -0
- package/src/memory/wal.js +137 -0
- package/src/memory/working-frame.js +516 -0
- package/src/metrics/classify.mjs +5 -3
- package/src/metrics/index.mjs +21 -1
- package/src/metrics/prestep-latency.mjs +300 -0
- package/src/metrics/store.mjs +25 -0
- package/src/policy-profile.js +18 -3
- package/src/recall/anaphora.mjs +87 -0
- package/src/recall/cards.mjs +7 -0
- package/src/recall/embedding.mjs +8 -8
- package/src/recall/entities.mjs +112 -0
- package/src/recall/index.js +235 -19
- package/src/recall/inject-order.mjs +10 -8
- package/src/recall/privacy.mjs +1 -1
- package/src/recall/recall-core.mjs +116 -10
- package/src/recall/shared-visibility.js +302 -0
- package/src/recall/time-normalizer.mjs +196 -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 +176 -25
- package/src/router/background/agent-runner.mjs +1 -1
- package/src/router/background/anchor.mjs +1 -1
- package/src/router/background/audit.mjs +2 -2
- package/src/router/background/budget-ledger.mjs +2 -2
- package/src/router/background/host-sim.mjs +1 -1
- package/src/router/background/memory.mjs +4 -4
- package/src/router/background/queue.mjs +1 -1
- package/src/router/background/retry.mjs +1 -1
- package/src/router/background/router.mjs +1 -1
- package/src/router/background/stream.mjs +1 -1
- package/src/router/background/tool-policy.mjs +1 -1
- package/src/router/design-headings.json +5 -5
- package/src/router/face/config.mjs +1 -1
- package/src/router/face/identity.mjs +3 -3
- package/src/router/judge.mjs +8 -7
- package/src/router/policies/generic.json +21 -4
- package/src/router/route.js +109 -22
- package/src/router/router.mjs +10 -6
- package/src/router/routing-rules.json +260 -445
- package/src/router/run-sim.mjs +8 -8
- package/src/router/runtime.js +23 -12
- package/src/router/service/config.mjs +5 -5
- package/src/router/service/context.mjs +1 -1
- package/src/router/service/queue.mjs +1 -1
- package/src/router/shadow.mjs +4 -3
- package/src/surgery-recovery.js +2 -2
- package/src/tool-output.js +2 -2
- package/src/tools.js +39 -7
- package/src/truncate-visible.js +2 -2
- package/src/ui/actions.js +1312 -0
- package/src/ui/panel-api.js +367 -0
- package/src/ui/panel-auth.js +251 -0
- package/src/ui/panel-integrity.js +243 -0
- package/src/ui/routes-readonly.js +695 -0
- package/src/ui/routes.js +3 -0
- package/docs/DEV.md +0 -279
- package/docs/PRESENCE-BUS-WIRING.md +0 -491
- package/docs/PRESENCE-BUS.md +0 -694
- package/docs/SURGERY.md +0 -186
- package/scripts/mark-core-cards.mjs +0 -289
- package/scripts/pack.mjs +0 -392
- package/scripts/router-proposals.mjs +0 -386
- package/src/router/fixtures/M1.json +0 -16
- package/src/router/fixtures/M2.json +0 -16
- package/src/router/fixtures/M3.json +0 -20
- package/src/router/fixtures/M4.json +0 -20
- package/src/router/fixtures/M5.json +0 -45
- package/src/router/fixtures/M6.json +0 -53
- package/src/router/fixtures/M7.json +0 -46
- package/src/router/fixtures/S1.json +0 -20
- package/src/router/fixtures/S2.json +0 -23
- package/src/router/fixtures/S3.json +0 -20
- package/src/router/fixtures/S4.json +0 -34
- package/src/router/fixtures/S5.json +0 -43
- package/src/router/fixtures/S6.json +0 -47
- package/src/router/fixtures/T1.json +0 -23
- package/src/router/fixtures/T2.json +0 -16
- package/src/router/fixtures/T3.json +0 -19
- package/src/router/fixtures/T4.json +0 -16
- package/src/router/fixtures/X1.json +0 -17
- package/src/router/fixtures/X2.json +0 -20
- package/src/router/gen-design-headings.mjs +0 -107
- package/src/router/policies/owner-rulings-2026-11-03.json +0 -62
- package/test/activity-realtime.test.mjs +0 -959
- package/test/activity-stream.test.mjs +0 -512
- package/test/auto-recall.test.mjs +0 -474
- package/test/auto-truncate.test.mjs +0 -931
- package/test/autobind.test.mjs +0 -399
- package/test/bus.test.mjs +0 -1572
- package/test/cli-guard.test.mjs +0 -198
- package/test/conclusion.test.mjs +0 -408
- package/test/config-schema.test.mjs +0 -210
- package/test/d6-output.test.mjs +0 -194
- package/test/d6.test.mjs +0 -395
- package/test/deps.test.mjs +0 -342
- package/test/doctor-setup.test.mjs +0 -297
- package/test/embedding-recall.test.mjs +0 -347
- package/test/feature-flags.test.mjs +0 -585
- package/test/filter-shadow.test.mjs +0 -170
- package/test/fixtures/activity-append-child.mjs +0 -29
- package/test/fixtures/baseline-0.8.0-registration.json +0 -556
- package/test/fixtures/d6-header-tools.json +0 -1
- package/test/fixtures/lock-child.mjs +0 -67
- package/test/fixtures/pre-step-container.mjs +0 -100
- package/test/fixtures/privacy-memory/topics/pii-unmarked.md +0 -9
- package/test/fixtures/privacy-memory/topics/secret-local-only.md +0 -11
- package/test/fixtures/profile-session-longlive-config.json +0 -20
- package/test/fixtures/proposal-cas-child.mjs +0 -66
- package/test/host-engine-status.test.mjs +0 -307
- package/test/hot-truncate.test.mjs +0 -1349
- package/test/identity-card-marker.test.mjs +0 -307
- package/test/identity-router/run.mjs +0 -721
- package/test/integration-pre-step.test.mjs +0 -553
- package/test/live.test.mjs +0 -1023
- package/test/maintenance-schedule.test.mjs +0 -538
- package/test/memory.test.mjs +0 -2828
- package/test/metrics.test.mjs +0 -478
- package/test/orchestrator.test.mjs +0 -266
- package/test/p1_probe.mjs +0 -97
- package/test/packaging.test.mjs +0 -184
- package/test/portability.test.mjs +0 -343
- package/test/rc4-regressions.test.mjs +0 -562
- package/test/rc5-regressions.test.mjs +0 -197
- package/test/rc6-chinese.test.mjs +0 -394
- package/test/router-1100/apply-off.test.mjs +0 -175
- package/test/router-1100/budget-reconcile.test.mjs +0 -215
- package/test/router-1100/config-context.test.mjs +0 -211
- package/test/router-1100/helpers.mjs +0 -129
- package/test/router-1100/hint-envelope.test.mjs +0 -150
- package/test/router-1100/lock-crossproc.test.mjs +0 -206
- package/test/router-1100/proposal-cas-crossproc.test.mjs +0 -184
- package/test/router-1100/router-apply.test.mjs +0 -372
- package/test/router-1100/router-fixb.test.mjs +0 -602
- package/test/router-1100/router-proposals.test.mjs +0 -405
- package/test/router-1100/router-queue-lease-wal.test.mjs +0 -355
- package/test/router-1100/router-security-cr.test.mjs +0 -333
- package/test/router-1100/service-lifecycle.test.mjs +0 -220
- package/test/router-1100/tools-contract.test.mjs +0 -164
- package/test/router-1100/turn-reflect-tick.test.mjs +0 -89
- package/test/router-1100/v6-contract.test.mjs +0 -158
- package/test/router-1100/v6b-contract.test.mjs +0 -293
- package/test/router-1100/v6c-contract.test.mjs +0 -249
- package/test/router-1100/wal-rotation.test.mjs +0 -375
- package/test/router-1100/wp1-config.test.mjs +0 -170
- package/test/router-1100/wp1-default-off.test.mjs +0 -77
- package/test/router-1100/wp1-model-status.test.mjs +0 -90
- package/test/router-1100/wp1-status.test.mjs +0 -220
- package/test/router-1100/wp1-tools.test.mjs +0 -146
- package/test/router-1100/wp5-cli.test.mjs +0 -240
- package/test/router-1100/wp5-model-auto.test.mjs +0 -418
- package/test/router-1100/wp6-merge.test.mjs +0 -386
- package/test/router-1100/wp6-wake.test.mjs +0 -502
- package/test/router-background/audit.test.mjs +0 -37
- package/test/router-background/budget-ledger.test.mjs +0 -330
- package/test/router-background/cross-process.test.mjs +0 -222
- package/test/router-background/fixtures/cross-child.mjs +0 -85
- package/test/router-background/fixtures/real-shapes.mjs +0 -239
- package/test/router-background/router.test.mjs +0 -1076
- package/test/router-background/stream-retry.test.mjs +0 -358
- package/test/router-background/tool-agent.test.mjs +0 -384
- package/test/router-face/bridge.test.mjs +0 -169
- package/test/router-face/face.test.mjs +0 -316
- package/test/router-failclosed.test.mjs +0 -466
- package/test/router-identity.test.mjs +0 -384
- package/test/router-l1-l2.contract.test.mjs +0 -1075
- package/test/router-memory-tools.test.mjs +0 -262
- package/test/router-policy.test.mjs +0 -225
- package/test/router-runtime.test.mjs +0 -438
- package/test/router-shadow.test.mjs +0 -287
- package/test/router.test.mjs +0 -903
- package/test/run-rc.mjs +0 -315
- package/test/run.mjs +0 -2469
- package/test/safety-defaults.test.mjs +0 -181
- package/test/seeded-load.test.mjs +0 -436
- package/test/session-original.test.mjs +0 -338
- package/test/state-truth.test.mjs +0 -937
- package/test/surgery-recovery.test.mjs +0 -936
- package/test/t7_drive.mjs +0 -151
- package/test/tool-output.test.mjs +0 -393
- package/test/tool-schema.test.mjs +0 -177
- package/test/tools_contract.test.mjs +0 -716
- package/test/truncate-visible.test.mjs +0 -1150
- package/test/ui-flags.test.mjs +0 -477
- package/test/v4-hardening.test.mjs +0 -427
- package/test/version-consistency.test.mjs +0 -286
|
@@ -0,0 +1,516 @@
|
|
|
1
|
+
// src/memory/working-frame.js — v2.6.4 §14.2:连续性最小集(working-frame)
|
|
2
|
+
//
|
|
3
|
+
// 用途:同一话题的连续追问时,把「当前工作焦点」压成 ≤300 字的注入块,
|
|
4
|
+
// 放在 pre-step 注入顺序的 working 位:**[boot, shared, working, recall]**。
|
|
5
|
+
//
|
|
6
|
+
// 文件:<memoryRoot>/.longlive/working/<sessionId>.json(原子写 tmp→rename)
|
|
7
|
+
// <memoryRoot>/.longlive/working/archive/<sessionId>-<frameNo>.json(旧帧,不删)
|
|
8
|
+
// <memoryRoot>/.longlive/working/audit.jsonl(rollback / stale / topic-switch 审计)
|
|
9
|
+
//
|
|
10
|
+
// 时间纪律(复用 Gate-1 P1-2):
|
|
11
|
+
// * TTL 默认 30min(1800000ms),用**单调时钟**计算 elapsed:回拨/前跳都不改变 TTL;
|
|
12
|
+
// * 持久化 `wallWatermarkMs`;检测到墙钟回拨(now + 容差 < watermark)→ fail closed
|
|
13
|
+
// `E_CLOCK_ROLLBACK`(不注入 + 审计),绝不把过期帧当有效帧。
|
|
14
|
+
// * 过期 → 不注入、不删除,帧标 `state:"stale"`(审计可查)。
|
|
15
|
+
|
|
16
|
+
import crypto from 'node:crypto';
|
|
17
|
+
import fs from 'node:fs';
|
|
18
|
+
import path from 'node:path';
|
|
19
|
+
|
|
20
|
+
import { stableStringify } from '../codec.js';
|
|
21
|
+
import { acquireLease, releaseLease } from './lock.js';
|
|
22
|
+
import {
|
|
23
|
+
AUTO_TEXT_MARK,
|
|
24
|
+
insertionIndex,
|
|
25
|
+
isHumanMessage,
|
|
26
|
+
isInjectedMessage,
|
|
27
|
+
textOfMessage,
|
|
28
|
+
} from '../identity/inject-position.js';
|
|
29
|
+
import {
|
|
30
|
+
assertFrameReadable,
|
|
31
|
+
attachFrameSubject,
|
|
32
|
+
normalizeRoleSubject,
|
|
33
|
+
verifyProtectedFile,
|
|
34
|
+
writeProtectedJson,
|
|
35
|
+
} from '../role/writeprotect.js';
|
|
36
|
+
|
|
37
|
+
export const FRAME_SCHEMA = 'working-frame/v1';
|
|
38
|
+
export const FRAME_TTL_MS = 30 * 60 * 1000;
|
|
39
|
+
export const TOPIC_SIMILARITY_THRESHOLD = 0.35;
|
|
40
|
+
export const INJECTION_ORDER = Object.freeze(['boot', 'shared', 'working', 'recall']);
|
|
41
|
+
export const CLOCK_TOLERANCE_MS = 5000;
|
|
42
|
+
|
|
43
|
+
export class WorkingFrameError extends Error {
|
|
44
|
+
constructor(code, message, detail = undefined) {
|
|
45
|
+
super(message);
|
|
46
|
+
this.name = 'WorkingFrameError';
|
|
47
|
+
this.code = code;
|
|
48
|
+
if (detail !== undefined) this.detail = detail;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function workingDirOf(memoryRoot) {
|
|
53
|
+
const root = path.resolve(String(memoryRoot ?? ''));
|
|
54
|
+
return {
|
|
55
|
+
root,
|
|
56
|
+
dir: path.join(root, '.longlive', 'working'),
|
|
57
|
+
archiveDir: path.join(root, '.longlive', 'working', 'archive'),
|
|
58
|
+
audit: path.join(root, '.longlive', 'working', 'audit.jsonl'),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function framePathOf(memoryRoot, sessionId) {
|
|
63
|
+
return path.join(workingDirOf(memoryRoot).dir, `${safeSessionId(sessionId)}.json`);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function safeSessionId(sessionId) {
|
|
67
|
+
const original = String(sessionId ?? '');
|
|
68
|
+
const raw = original.replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 160);
|
|
69
|
+
if (raw === '') throw new WorkingFrameError('E_SESSION_ID', 'working-frame requires sessionId');
|
|
70
|
+
// EA-14: sanitization must not collide different sessions (sess@1 vs sess_1).
|
|
71
|
+
if (raw !== original) {
|
|
72
|
+
const digest = crypto.createHash('sha1').update(original, 'utf8').digest('hex').slice(0, 10);
|
|
73
|
+
return `${raw.slice(0, 140)}_${digest}`;
|
|
74
|
+
}
|
|
75
|
+
return raw;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function sha1Short(text) {
|
|
79
|
+
return crypto.createHash('sha1').update(String(text), 'utf8').digest('hex').slice(0, 12);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function nowMs(now) {
|
|
83
|
+
const value = typeof now === 'function' ? now() : new Date();
|
|
84
|
+
return value instanceof Date ? value.getTime() : Number(value);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function nowIso(now) {
|
|
88
|
+
return new Date(nowMs(now)).toISOString();
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function writeAtomic(file, content) {
|
|
92
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
93
|
+
const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
|
|
94
|
+
fs.writeFileSync(tmp, content, 'utf8');
|
|
95
|
+
fs.renameSync(tmp, file);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** CJK bigrams + ASCII words + version tokens. */
|
|
99
|
+
export function tokenizeFocus(value) {
|
|
100
|
+
const text = Array.isArray(value) ? value.join(' ') : String(value ?? '');
|
|
101
|
+
const tokens = new Set();
|
|
102
|
+
for (const word of text.toLowerCase().match(/[a-z0-9][a-z0-9_.-]*/g) ?? []) tokens.add(word);
|
|
103
|
+
for (const run of text.match(/[\u3400-\u4dbf\u4e00-\u9fff]+/g) ?? []) {
|
|
104
|
+
const chars = Array.from(run);
|
|
105
|
+
if (chars.length === 1) tokens.add(chars[0]);
|
|
106
|
+
for (let i = 0; i + 1 < chars.length; i += 1) tokens.add(chars[i] + chars[i + 1]);
|
|
107
|
+
}
|
|
108
|
+
return [...tokens];
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function jaccardSimilarity(left, right) {
|
|
112
|
+
const a = new Set(left);
|
|
113
|
+
const b = new Set(right);
|
|
114
|
+
if (a.size === 0 || b.size === 0) return 0;
|
|
115
|
+
let intersection = 0;
|
|
116
|
+
for (const token of a) if (b.has(token)) intersection += 1;
|
|
117
|
+
return intersection / (a.size + b.size - intersection);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Pre-step injection order: [boot, shared, working, recall].
|
|
122
|
+
* Blocks are {kind, text}; empty texts are dropped, unknown kinds dropped.
|
|
123
|
+
*/
|
|
124
|
+
|
|
125
|
+
/** Human-friendly focus entities from a question (EA-05 caller uses this). */
|
|
126
|
+
export function entitiesFromText(text, limit = 8) {
|
|
127
|
+
const normalized = String(text ?? '');
|
|
128
|
+
const out = [];
|
|
129
|
+
const seen = new Set();
|
|
130
|
+
const push = (value) => {
|
|
131
|
+
const token = String(value ?? '').trim();
|
|
132
|
+
if (token === '' || seen.has(token) || out.length >= limit) return;
|
|
133
|
+
seen.add(token);
|
|
134
|
+
out.push(token);
|
|
135
|
+
};
|
|
136
|
+
for (const run of normalized.match(/[㐀-䶿一-鿿]{2,8}/g) ?? []) push(run);
|
|
137
|
+
for (const word of normalized.match(/[A-Za-z][A-Za-z0-9._-]{1,30}/g) ?? []) push(word);
|
|
138
|
+
for (const version of normalized.match(/v?\d+(?:\.\d+){1,3}/g) ?? []) push(version);
|
|
139
|
+
return out;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* EA-05: real per-turn focus updater — extracts the last human message and records
|
|
144
|
+
* this turn's focus into the frame stack (so the NEXT turn can inject it).
|
|
145
|
+
*/
|
|
146
|
+
export function updateFrameFromMessages({ store, sessionId, messages, turn = 0 } = {}) {
|
|
147
|
+
const list = Array.isArray(messages) ? messages : [];
|
|
148
|
+
let human = null;
|
|
149
|
+
for (const message of list) {
|
|
150
|
+
if (isHumanMessage(message)) human = message;
|
|
151
|
+
}
|
|
152
|
+
const query = human ? textOfMessage(human) : '';
|
|
153
|
+
if (query.trim() === '') return { ok: false, code: 'E_NO_HUMAN_MESSAGE' };
|
|
154
|
+
const result = store.updateFocus({
|
|
155
|
+
sessionId,
|
|
156
|
+
entities: entitiesFromText(query),
|
|
157
|
+
anchors: [],
|
|
158
|
+
turn: Number.isInteger(turn) && turn >= 0 ? turn : 0,
|
|
159
|
+
query,
|
|
160
|
+
});
|
|
161
|
+
return { ...result, query };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* EA-04: insert the working-frame injection at the real order slot
|
|
166
|
+
* [boot, shared, working, recall] — before the auto-recall block, after boot/shared.
|
|
167
|
+
*/
|
|
168
|
+
export function insertWorkingMessage(messages, message) {
|
|
169
|
+
const list = Array.isArray(messages) ? [...messages] : [];
|
|
170
|
+
if (!message) return list;
|
|
171
|
+
const autoIndex = list.findIndex((entry) => {
|
|
172
|
+
if (!isInjectedMessage(entry)) return false;
|
|
173
|
+
const firstLine = textOfMessage(entry).trimStart().split('\n', 1)[0] ?? '';
|
|
174
|
+
return firstLine.startsWith(AUTO_TEXT_MARK);
|
|
175
|
+
});
|
|
176
|
+
if (autoIndex !== -1) {
|
|
177
|
+
list.splice(autoIndex, 0, message);
|
|
178
|
+
return list;
|
|
179
|
+
}
|
|
180
|
+
let lastInjected = -1;
|
|
181
|
+
for (let index = 0; index < list.length; index += 1) {
|
|
182
|
+
if (isInjectedMessage(list[index])) lastInjected = index;
|
|
183
|
+
}
|
|
184
|
+
if (lastInjected !== -1) {
|
|
185
|
+
list.splice(lastInjected + 1, 0, message);
|
|
186
|
+
return list;
|
|
187
|
+
}
|
|
188
|
+
list.splice(insertionIndex(list), 0, message);
|
|
189
|
+
return list;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export function composePreStepBlocks(blocks) {
|
|
193
|
+
const byKind = new Map();
|
|
194
|
+
for (const block of Array.isArray(blocks) ? blocks : []) {
|
|
195
|
+
if (!block || typeof block !== 'object') continue;
|
|
196
|
+
if (!INJECTION_ORDER.includes(block.kind)) continue;
|
|
197
|
+
if (typeof block.text !== 'string' || block.text.trim() === '') continue;
|
|
198
|
+
if (!byKind.has(block.kind)) byKind.set(block.kind, []);
|
|
199
|
+
byKind.get(block.kind).push(block.text.trim());
|
|
200
|
+
}
|
|
201
|
+
const out = [];
|
|
202
|
+
for (const kind of INJECTION_ORDER) {
|
|
203
|
+
for (const text of byKind.get(kind) ?? []) out.push({ kind, text });
|
|
204
|
+
}
|
|
205
|
+
return out;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function validateFrame(frame, sessionId) {
|
|
209
|
+
if (!frame || typeof frame !== 'object') throw new WorkingFrameError('E_FRAME_INVALID', 'frame must be an object');
|
|
210
|
+
if (frame.sessionId !== sessionId) throw new WorkingFrameError('E_FRAME_SESSION', 'frame.sessionId mismatch');
|
|
211
|
+
if (!Array.isArray(frame.focus?.entities)) throw new WorkingFrameError('E_FRAME_FOCUS', 'frame.focus.entities required');
|
|
212
|
+
if (!Array.isArray(frame.turnRange) || frame.turnRange.length !== 2) {
|
|
213
|
+
throw new WorkingFrameError('E_FRAME_TURN_RANGE', 'frame.turnRange required');
|
|
214
|
+
}
|
|
215
|
+
return frame;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Create the working-frame store.
|
|
220
|
+
*
|
|
221
|
+
* @param {object} options
|
|
222
|
+
* @param {string} options.memoryRoot
|
|
223
|
+
* @param {() => Date} [options.now]
|
|
224
|
+
* @param {() => number} [options.monoNow] monotonic clock seam (ms)
|
|
225
|
+
* @param {number} [options.ttlMs]
|
|
226
|
+
* @param {number} [options.clockToleranceMs]
|
|
227
|
+
*/
|
|
228
|
+
export function createWorkingFrameStore(options = {}) {
|
|
229
|
+
const memoryRoot = path.resolve(String(options.memoryRoot ?? ''));
|
|
230
|
+
if (memoryRoot === '') throw new WorkingFrameError('E_MEMORY_ROOT', 'working-frame requires memoryRoot');
|
|
231
|
+
const paths = workingDirOf(memoryRoot);
|
|
232
|
+
const now = typeof options.now === 'function' ? options.now : () => new Date();
|
|
233
|
+
const monoNow = typeof options.monoNow === 'function'
|
|
234
|
+
? options.monoNow
|
|
235
|
+
: () => {
|
|
236
|
+
const [seconds, nanoseconds] = process.hrtime();
|
|
237
|
+
return seconds * 1000 + nanoseconds / 1e6;
|
|
238
|
+
};
|
|
239
|
+
const ttlMs = Number.isInteger(options.ttlMs) && options.ttlMs > 0 ? options.ttlMs : FRAME_TTL_MS;
|
|
240
|
+
const tolerance = Number.isFinite(options.clockToleranceMs) && options.clockToleranceMs >= 0
|
|
241
|
+
? options.clockToleranceMs
|
|
242
|
+
: CLOCK_TOLERANCE_MS;
|
|
243
|
+
const bootMono = monoNow();
|
|
244
|
+
const bootWall = nowMs(now);
|
|
245
|
+
// §16.8 A/E:working/** 写保护(宿主独占写 + HMAC 侧车)+ 四元边界。
|
|
246
|
+
const frameSubject = normalizeRoleSubject(options.subject ?? {});
|
|
247
|
+
const frameActor = typeof options.actorKind === 'string' ? options.actorKind : 'host';
|
|
248
|
+
|
|
249
|
+
function effectiveWallMs() {
|
|
250
|
+
const elapsed = Number.isFinite(monoNow()) ? Math.max(0, monoNow() - bootMono) : 0;
|
|
251
|
+
return bootWall + elapsed;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function audit(event, detail) {
|
|
255
|
+
try {
|
|
256
|
+
fs.mkdirSync(path.dirname(paths.audit), { recursive: true });
|
|
257
|
+
fs.appendFileSync(paths.audit, `${JSON.stringify({ schema: 'working-frame-audit/v1', at: nowIso(now), event, ...detail })}\n`, 'utf8');
|
|
258
|
+
} catch {
|
|
259
|
+
/* audit is best effort */
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function clockGuard(frame) {
|
|
264
|
+
const wall = nowMs(now);
|
|
265
|
+
const watermark = Number(frame?.wallWatermarkMs ?? frame?.lastUsedAtMs ?? 0);
|
|
266
|
+
if (Number.isFinite(wall) && watermark > 0 && wall + tolerance < watermark) {
|
|
267
|
+
audit('clock.rollback', { sessionId: frame?.sessionId ?? null, wall, watermark });
|
|
268
|
+
throw new WorkingFrameError('E_CLOCK_ROLLBACK', `系统时钟回拨(now=${new Date(wall).toISOString()} < watermark=${new Date(watermark).toISOString()}),工作帧 fail closed。`, { wall, watermark });
|
|
269
|
+
}
|
|
270
|
+
return wall;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function load(sessionId) {
|
|
274
|
+
const id = safeSessionId(sessionId);
|
|
275
|
+
const file = framePathOf(memoryRoot, id);
|
|
276
|
+
const verified = verifyProtectedFile({ memoryRoot, file });
|
|
277
|
+
if (verified.absent) return { present: false, frame: null };
|
|
278
|
+
if (!verified.ok) {
|
|
279
|
+
return { present: true, frame: null, code: verified.code ?? 'E_INTEGRITY_TAMPER', message: verified.message };
|
|
280
|
+
}
|
|
281
|
+
try {
|
|
282
|
+
return { present: true, frame: JSON.parse(verified.text), code: null };
|
|
283
|
+
} catch {
|
|
284
|
+
return { present: true, frame: null, code: 'E_INTEGRITY_TAMPER', message: '受保护帧 JSON 解析失败' };
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
function clampFramePayload(input) {
|
|
289
|
+
const value = JSON.parse(JSON.stringify(input));
|
|
290
|
+
if (Array.isArray(value?.focus?.entities)) {
|
|
291
|
+
value.focus.entities = value.focus.entities.map((entity) => String(entity).slice(0, 200)).slice(0, 50);
|
|
292
|
+
}
|
|
293
|
+
if (Array.isArray(value?.focus?.anchors)) {
|
|
294
|
+
value.focus.anchors = value.focus.anchors.slice(0, 20).map((anchor) => {
|
|
295
|
+
const clone = JSON.parse(JSON.stringify(anchor ?? {}));
|
|
296
|
+
const walk = (node) => {
|
|
297
|
+
if (typeof node === 'string') return node.length > 2000 ? `${node.slice(0, 2000)}…[truncated]` : node;
|
|
298
|
+
if (Array.isArray(node)) return node.map(walk);
|
|
299
|
+
if (node && typeof node === 'object') { for (const key of Object.keys(node)) node[key] = walk(node[key]); }
|
|
300
|
+
return node;
|
|
301
|
+
};
|
|
302
|
+
return walk(clone);
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
return value;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function save(sessionId, frame) {
|
|
309
|
+
const id = safeSessionId(sessionId);
|
|
310
|
+
const clamped = clampFramePayload(frame);
|
|
311
|
+
const validated = validateFrame(clamped, id);
|
|
312
|
+
const value = attachFrameSubject(validated, { subject: frameSubject });
|
|
313
|
+
const serialized = JSON.stringify(value);
|
|
314
|
+
if (serialized.length > 512 * 1024) {
|
|
315
|
+
throw new WorkingFrameError('E_FRAME_TOO_LARGE', `工作帧超过 512KB 上限(${serialized.length} bytes),拒绝落盘。`);
|
|
316
|
+
}
|
|
317
|
+
const file = framePathOf(memoryRoot, id);
|
|
318
|
+
writeProtectedJson({ memoryRoot, file, value, actorKind: frameActor });
|
|
319
|
+
return { ok: true, path: file, frame: value };
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function newFrame({ sessionId, entities = [], anchors = [], turn = 0, frameNo = 1, prevFrameId = null }) {
|
|
323
|
+
const wall = nowMs(now);
|
|
324
|
+
return {
|
|
325
|
+
schema: FRAME_SCHEMA,
|
|
326
|
+
sessionId,
|
|
327
|
+
frameId: `wf-${sha1Short(`${sessionId}|${frameNo}|${wall}`)}`,
|
|
328
|
+
frameNo,
|
|
329
|
+
turnRange: [Number.isInteger(turn) ? turn : 0, Number.isInteger(turn) ? turn : 0],
|
|
330
|
+
focus: {
|
|
331
|
+
entities: [...new Set(entities.filter((entity) => typeof entity === 'string' && entity.trim() !== ''))].slice(0, 30),
|
|
332
|
+
anchors: Array.isArray(anchors) ? anchors.slice(0, 20) : [],
|
|
333
|
+
},
|
|
334
|
+
ttlMs,
|
|
335
|
+
lastUsedAtMs: wall,
|
|
336
|
+
lastUsedAt: new Date(wall).toISOString(),
|
|
337
|
+
updatedAt: new Date(wall).toISOString(),
|
|
338
|
+
wallWatermarkMs: wall,
|
|
339
|
+
state: 'active',
|
|
340
|
+
prevFrameId,
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
function archiveFrame(sessionId, frame) {
|
|
345
|
+
const id = safeSessionId(sessionId);
|
|
346
|
+
const file = path.join(paths.archiveDir, `${id}-frame-${frame.frameNo ?? 1}-${frame.frameId ?? sha1Short(stableStringify(frame))}.json`);
|
|
347
|
+
writeProtectedJson({
|
|
348
|
+
memoryRoot,
|
|
349
|
+
file,
|
|
350
|
+
value: attachFrameSubject({ ...frame, archivedAt: nowIso(now), state: 'archived' }, { subject: frameSubject }),
|
|
351
|
+
actorKind: frameActor,
|
|
352
|
+
});
|
|
353
|
+
audit('topic.switch.archive', { sessionId: id, frameId: frame.frameId ?? null, frameNo: frame.frameNo ?? null, file });
|
|
354
|
+
return file;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function isExpired(frame) {
|
|
358
|
+
if (!frame) return true;
|
|
359
|
+
const lastUsed = Number(frame.lastUsedAtMs ?? 0);
|
|
360
|
+
if (!Number.isFinite(lastUsed) || lastUsed <= 0) return true;
|
|
361
|
+
const effective = effectiveWallMs();
|
|
362
|
+
// EA-13: a FORWARD wall-clock jump must expire the frame, not silently stretch
|
|
363
|
+
// its lifetime. Backward jumps are handled by clockGuard (fail closed).
|
|
364
|
+
const realWall = nowMs(now);
|
|
365
|
+
if (Number.isFinite(realWall) && Number.isFinite(effective) && realWall > effective + tolerance) return true;
|
|
366
|
+
return effective - lastUsed > ttlMs;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function topicChanged(frame, queryOrEntities) {
|
|
370
|
+
const incoming = tokenizeFocus(queryOrEntities);
|
|
371
|
+
if (incoming.length === 0) return false;
|
|
372
|
+
// Topic switch is keyed on the frame's focus ENTITIES (anchors are evidence,
|
|
373
|
+
// not topic tokens). Switch only when the new turn shares no entity token and
|
|
374
|
+
// the Jaccard similarity is below threshold; a same-topic follow-up keeps the frame.
|
|
375
|
+
const entityTokens = tokenizeFocus(frame?.focus?.entities ?? []);
|
|
376
|
+
if (entityTokens.length === 0) return true;
|
|
377
|
+
let intersection = 0;
|
|
378
|
+
const entitySet = new Set(entityTokens);
|
|
379
|
+
for (const token of incoming) if (entitySet.has(token)) intersection += 1;
|
|
380
|
+
if (intersection > 0) return false;
|
|
381
|
+
return jaccardSimilarity(incoming, entityTokens) < TOPIC_SIMILARITY_THRESHOLD;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* Per-turn focus update. Same topic merges; expired/topic-switched frames go to archive
|
|
386
|
+
* (never deleted) and a new frame is opened.
|
|
387
|
+
*/
|
|
388
|
+
function updateFocus(input = {}) {
|
|
389
|
+
const leaseFile = `${framePathOf(memoryRoot, input.sessionId)}.lock`;
|
|
390
|
+
let lease;
|
|
391
|
+
try {
|
|
392
|
+
lease = acquireLease(leaseFile, { holder: `working-frame:${process.pid}`, ttlMs: 30_000 });
|
|
393
|
+
} catch (error) {
|
|
394
|
+
return { ok: false, code: 'E_FRAME_BUSY', message: `工作帧正在被另一写者更新(E_FRAME_BUSY):${error?.message ?? error}` };
|
|
395
|
+
}
|
|
396
|
+
try {
|
|
397
|
+
return updateFocusUnlocked(input);
|
|
398
|
+
} finally {
|
|
399
|
+
releaseLease(leaseFile, lease.holder);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function updateFocusUnlocked({ sessionId, entities = [], anchors = [], turn = 0, query = '' }) {
|
|
404
|
+
const loaded = load(sessionId);
|
|
405
|
+
const wall = nowMs(now);
|
|
406
|
+
// §16.8 A:帧被篡改/缺侧车 → fail closed,绝不把坏帧当有效帧继续写。
|
|
407
|
+
if (loaded.present && loaded.frame === null) {
|
|
408
|
+
return { ok: false, code: loaded.code ?? 'E_INTEGRITY_TAMPER', message: loaded.message ?? '帧完整性校验失败' };
|
|
409
|
+
}
|
|
410
|
+
if (!loaded.present) {
|
|
411
|
+
const frame = newFrame({ sessionId: safeSessionId(sessionId), entities, anchors, turn, frameNo: 1 });
|
|
412
|
+
save(sessionId, frame);
|
|
413
|
+
return { ok: true, switched: true, reason: 'new', frame };
|
|
414
|
+
}
|
|
415
|
+
const current = loaded.frame;
|
|
416
|
+
clockGuard(current);
|
|
417
|
+
const expired = isExpired(current);
|
|
418
|
+
// Topic switch considers BOTH the new question and this turn's extracted entities:
|
|
419
|
+
// a question that reuses the frame's focus entities stays on the same frame.
|
|
420
|
+
const switched = topicChanged(current, query !== '' ? [query, ...(Array.isArray(entities) ? entities : [])] : entities);
|
|
421
|
+
if (expired || switched) {
|
|
422
|
+
const archiveFile = archiveFrame(sessionId, current);
|
|
423
|
+
const frame = newFrame({
|
|
424
|
+
sessionId: safeSessionId(sessionId),
|
|
425
|
+
entities,
|
|
426
|
+
anchors,
|
|
427
|
+
turn,
|
|
428
|
+
frameNo: (current.frameNo ?? 1) + 1,
|
|
429
|
+
prevFrameId: current.frameId ?? null,
|
|
430
|
+
});
|
|
431
|
+
save(sessionId, frame);
|
|
432
|
+
return { ok: true, switched: true, reason: expired ? 'expired' : 'topic-switch', archiveFile, frame };
|
|
433
|
+
}
|
|
434
|
+
const mergedEntities = [...new Set([...(current.focus?.entities ?? []), ...entities])].slice(0, 30);
|
|
435
|
+
const mergedAnchors = [...(current.focus?.anchors ?? []), ...anchors];
|
|
436
|
+
const next = {
|
|
437
|
+
...current,
|
|
438
|
+
turnRange: [current.turnRange?.[0] ?? 0, Math.max(current.turnRange?.[1] ?? 0, Number.isInteger(turn) ? turn : 0)],
|
|
439
|
+
focus: { entities: mergedEntities, anchors: mergedAnchors.slice(0, 20) },
|
|
440
|
+
lastUsedAtMs: wall,
|
|
441
|
+
lastUsedAt: new Date(wall).toISOString(),
|
|
442
|
+
updatedAt: new Date(wall).toISOString(),
|
|
443
|
+
wallWatermarkMs: Math.max(Number(current.wallWatermarkMs ?? 0), wall),
|
|
444
|
+
state: 'active',
|
|
445
|
+
};
|
|
446
|
+
save(sessionId, next);
|
|
447
|
+
return { ok: true, switched: false, reason: 'merged', frame: next };
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** Injection decision: unexpired frame only; rollback fails closed; never delete. */
|
|
451
|
+
function frameForInjection({ sessionId, caller = null }) {
|
|
452
|
+
const loaded = load(sessionId);
|
|
453
|
+
if (!loaded.present) return { inject: false, code: 'E_NO_FRAME' };
|
|
454
|
+
if (loaded.frame === null) return { inject: false, code: loaded.code ?? 'E_INTEGRITY_TAMPER' };
|
|
455
|
+
const frame = loaded.frame;
|
|
456
|
+
if (caller !== null) {
|
|
457
|
+
try {
|
|
458
|
+
assertFrameReadable(frame, caller);
|
|
459
|
+
} catch (error) {
|
|
460
|
+
return { inject: false, code: error.code ?? 'E_FRAME_PRIVATE', message: error.message };
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
try {
|
|
464
|
+
clockGuard(frame);
|
|
465
|
+
} catch (error) {
|
|
466
|
+
return { inject: false, code: error.code, message: error.message };
|
|
467
|
+
}
|
|
468
|
+
if (isExpired(frame)) {
|
|
469
|
+
if (frame.state !== 'stale') {
|
|
470
|
+
try {
|
|
471
|
+
save(sessionId, { ...frame, state: 'stale', updatedAt: nowIso(now) });
|
|
472
|
+
} catch {
|
|
473
|
+
/* stale mark is best effort */
|
|
474
|
+
}
|
|
475
|
+
audit('frame.stale', { sessionId: safeSessionId(sessionId), frameId: frame.frameId ?? null });
|
|
476
|
+
}
|
|
477
|
+
return { inject: false, code: 'E_FRAME_EXPIRED', frame };
|
|
478
|
+
}
|
|
479
|
+
return { inject: true, frame, text: renderBlock(frame) };
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/** ≤300 chars block; truncated in that order: anchors → entities. */
|
|
483
|
+
function renderBlock(frame) {
|
|
484
|
+
const entities = (frame?.focus?.entities ?? []).slice(0, 8);
|
|
485
|
+
const anchorLines = (frame?.focus?.anchors ?? []).map((anchor) => anchor?.oneLine).filter(Boolean).slice(0, 4);
|
|
486
|
+
const turnRange = Array.isArray(frame?.turnRange) ? `${frame.turnRange[0]}-${frame.turnRange[1]}` : '?';
|
|
487
|
+
const parts = [`【工作帧】焦点:${entities.length > 0 ? entities.join('、') : '(无)'}(轮次 ${turnRange})`];
|
|
488
|
+
if (anchorLines.length > 0) parts.push(`锚点:${anchorLines.join(';')}`);
|
|
489
|
+
let text = parts.join(' · ');
|
|
490
|
+
if (text.length > 300) text = text.slice(0, 299) + '…';
|
|
491
|
+
return text;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
function archive(sessionId) {
|
|
495
|
+
const loaded = load(sessionId);
|
|
496
|
+
if (!loaded.present) return { ok: false, code: 'E_NO_FRAME' };
|
|
497
|
+
const file = archiveFrame(sessionId, loaded.frame);
|
|
498
|
+
return { ok: true, file };
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
return {
|
|
502
|
+
memoryRoot,
|
|
503
|
+
paths,
|
|
504
|
+
ttlMs,
|
|
505
|
+
effectiveWallMs,
|
|
506
|
+
load,
|
|
507
|
+
save,
|
|
508
|
+
updateFocus,
|
|
509
|
+
frameForInjection,
|
|
510
|
+
renderBlock,
|
|
511
|
+
isExpired,
|
|
512
|
+
topicChanged,
|
|
513
|
+
archive,
|
|
514
|
+
newFrame,
|
|
515
|
+
};
|
|
516
|
+
}
|
package/src/metrics/classify.mjs
CHANGED
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Layers:
|
|
5
5
|
* fixed system prompt + tool schemas + host-injected context
|
|
6
|
-
* (agent instructions, runtime context, skill catalog,
|
|
7
|
-
* memory, time context, developer/tool-registry messages)
|
|
6
|
+
* (agent instructions, runtime context, skill catalog, external
|
|
7
|
+
* memory plugin injection, time context, developer/tool-registry messages)
|
|
8
8
|
* recent real conversation inside the keepTurns window
|
|
9
9
|
* recall auto-recall injection (`【自动想起】`)
|
|
10
10
|
* conclusion boot card (`【开机卡】`) or a future board lastConclusion
|
|
@@ -14,6 +14,8 @@
|
|
|
14
14
|
* implemented, and the ledger must show that honestly.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
+
import { classificationPluginLabels } from '../adapters/registry.js';
|
|
18
|
+
|
|
17
19
|
export const RECALL_HEADER = '【自动想起】';
|
|
18
20
|
export const CONCLUSION_HEADER = '【开机卡】';
|
|
19
21
|
|
|
@@ -27,7 +29,7 @@ export const FIXED_SOURCE_KINDS = new Set([
|
|
|
27
29
|
'agent-instructions',
|
|
28
30
|
'runtime-context',
|
|
29
31
|
'skill-catalog',
|
|
30
|
-
|
|
32
|
+
...classificationPluginLabels(),
|
|
31
33
|
'time-context',
|
|
32
34
|
]);
|
|
33
35
|
|
package/src/metrics/index.mjs
CHANGED
|
@@ -25,7 +25,13 @@ import {
|
|
|
25
25
|
writeCalibration,
|
|
26
26
|
readLastConclusion,
|
|
27
27
|
ledgerPath,
|
|
28
|
+
readPrestepLedger,
|
|
29
|
+
readPrestepSummary,
|
|
28
30
|
} from './store.mjs';
|
|
31
|
+
import {
|
|
32
|
+
configurePrestepLatency,
|
|
33
|
+
finalizePrestepTurn,
|
|
34
|
+
} from './prestep-latency.mjs';
|
|
29
35
|
|
|
30
36
|
/** The message events whose Surface fold is the request. */
|
|
31
37
|
export function snapshotSessionEvents(session) {
|
|
@@ -88,13 +94,21 @@ export function registerMetrics(ctx, config, deps = {}) {
|
|
|
88
94
|
const memoryRoot = typeof deps.memoryRoot === 'string' && deps.memoryRoot.trim() !== ''
|
|
89
95
|
? deps.memoryRoot
|
|
90
96
|
: '';
|
|
97
|
+
// B3: pre-step latency attribution is gated by the same metrics switch; when the
|
|
98
|
+
// recorder is off every phase helper is a no-op (zero disk IO, zero behavior change).
|
|
99
|
+
const nowFn = typeof deps.now === 'function' ? deps.now : () => new Date();
|
|
100
|
+
configurePrestepLatency({
|
|
101
|
+
enabled: cfg.enabled === true && memoryRoot !== '' && ctx !== null && typeof ctx === 'object',
|
|
102
|
+
memoryRoot,
|
|
103
|
+
now: nowFn,
|
|
104
|
+
});
|
|
91
105
|
if (cfg.enabled !== true) return { enabled: false, reason: 'disabled' };
|
|
92
106
|
if (memoryRoot === '') return { enabled: false, reason: 'memory-root-unset' };
|
|
93
107
|
if (ctx === null || typeof ctx !== 'object' || typeof ctx.on !== 'function') {
|
|
94
108
|
return { enabled: false, reason: 'no-ctx' };
|
|
95
109
|
}
|
|
96
110
|
|
|
97
|
-
const now =
|
|
111
|
+
const now = nowFn;
|
|
98
112
|
const append = typeof deps.appendRow === 'function'
|
|
99
113
|
? deps.appendRow
|
|
100
114
|
: (row) => appendTurnRow(row, { memoryRoot });
|
|
@@ -111,6 +125,10 @@ export function registerMetrics(ctx, config, deps = {}) {
|
|
|
111
125
|
seen.add(key);
|
|
112
126
|
if (seen.size > 8192) seen.clear();
|
|
113
127
|
|
|
128
|
+
// B3 fallback: if no outer pre-step handler finalized this turn (e.g.
|
|
129
|
+
// answer-guard disabled), flush whatever phases were collected. Idempotent.
|
|
130
|
+
try { finalizePrestepTurn(sessionId, turn, { memoryRoot }); } catch { /* never breaks */ }
|
|
131
|
+
|
|
114
132
|
const events = snapshotSessionEvents(session);
|
|
115
133
|
if (!Array.isArray(events)) return;
|
|
116
134
|
|
|
@@ -177,6 +195,8 @@ export function registerMetrics(ctx, config, deps = {}) {
|
|
|
177
195
|
enabled: true,
|
|
178
196
|
memoryRoot,
|
|
179
197
|
ledgerPath: ledgerPath(memoryRoot),
|
|
198
|
+
prestepPath: readPrestepLedger({ memoryRoot, limit: 1 }).path,
|
|
199
|
+
prestepSummary: () => readPrestepSummary({ memoryRoot }),
|
|
180
200
|
config: cfg,
|
|
181
201
|
onSessionEvent,
|
|
182
202
|
dispose,
|