@jjh32456/dsh-longlive 1.6.7 → 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 +70 -1508
- package/LICENSE +1 -1
- package/QUICKSTART.md +34 -13
- package/README.en.md +18 -7
- package/README.md +34 -9
- package/SPEC.md +5 -5
- package/cordis.patch.yml +23 -9
- package/docs/ANSWER-GUARD.md +92 -0
- package/docs/ARCHITECTURE.md +4 -3
- package/docs/AUTO-RECALL-WIRING.md +1 -1
- package/docs/AUTO-RECALL.md +15 -9
- package/docs/CONFIG.md +168 -35
- package/docs/ERRORS.md +17 -5
- package/docs/FAQ.md +7 -7
- package/docs/FEATURES.md +96 -28
- 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 +4 -2
- package/docs/RESIDENT-WATCHER.md +1 -1
- package/docs/SESSION-WATCH.md +6 -6
- package/docs/TROUBLESHOOTING.md +4 -4
- package/package.json +47 -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 +760 -0
- package/src/activity/model.js +351 -0
- package/src/activity/store.js +644 -0
- 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 +171 -47
- package/src/deps.js +6 -4
- package/src/features.js +182 -6
- package/src/heartbeat.js +156 -23
- package/src/identity/handover.js +52 -1
- 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/live.js +22 -2
- 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 +105 -16
- 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/board.mjs +95 -15
- package/src/router/service/config.mjs +5 -5
- package/src/router/service/context.mjs +1 -1
- package/src/router/service/hint.mjs +14 -0
- package/src/router/service/queue.mjs +1 -1
- package/src/router/service/service.mjs +27 -11
- 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/auto-recall.test.mjs +0 -474
- package/test/auto-truncate.test.mjs +0 -931
- package/test/autobind.test.mjs +0 -385
- 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 -204
- 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 -568
- package/test/filter-shadow.test.mjs +0 -170
- 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 -1020
- 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 -182
- 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 -1044
- 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 -299
- package/test/run.mjs +0 -2469
- package/test/safety-defaults.test.mjs +0 -179
- package/test/seeded-load.test.mjs +0 -436
- package/test/session-original.test.mjs +0 -338
- 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
|
@@ -1,1150 +0,0 @@
|
|
|
1
|
-
// @local/dsh-longlive — visible-conversation truncation tests
|
|
2
|
-
//
|
|
3
|
-
// These fixtures are tiny synthetic logs written under TMP. The one exception is
|
|
4
|
-
// N4, which copies an existing session log read-only (never writes into
|
|
5
|
-
// ~/.dsh/sessions) and falls back to a synthetic 46,8xx-event log when the
|
|
6
|
-
// machine has none; everything else stays fake. The cases pin the contract:
|
|
7
|
-
// * dryRun writes nothing;
|
|
8
|
-
// * writing needs the exact confirm word;
|
|
9
|
-
// * the cut is a whole-turn boundary and seq is renumbered 0..n-1;
|
|
10
|
-
// * the retained events keep their data field-for-field;
|
|
11
|
-
// * the archive is a valid log containing exactly the dropped prefix;
|
|
12
|
-
// * a torn/partial write and a crash after rename are both recoverable;
|
|
13
|
-
// * a read-back mismatch after the rename itself restores the original bytes;
|
|
14
|
-
// * the first user-authored message survives its dropped turn;
|
|
15
|
-
// * path extraction is linear time and semantically identical to the 0.7.6
|
|
16
|
-
// regular expression it replaced (N1–N5).
|
|
17
|
-
|
|
18
|
-
import fs from 'node:fs';
|
|
19
|
-
import os from 'node:os';
|
|
20
|
-
import path from 'node:path';
|
|
21
|
-
import crypto from 'node:crypto';
|
|
22
|
-
import { isDeepStrictEqual } from 'node:util';
|
|
23
|
-
|
|
24
|
-
import {
|
|
25
|
-
parseSession,
|
|
26
|
-
encodeSession,
|
|
27
|
-
assertContiguous,
|
|
28
|
-
deriveMessagesDigest,
|
|
29
|
-
} from '../src/codec.js';
|
|
30
|
-
import {
|
|
31
|
-
truncateVisibleSession,
|
|
32
|
-
planVisibleTruncation,
|
|
33
|
-
buildVisibleTruncated,
|
|
34
|
-
recoverInflight,
|
|
35
|
-
readInflight,
|
|
36
|
-
inflightPathFor,
|
|
37
|
-
archiveDirFor,
|
|
38
|
-
matchPathStrings,
|
|
39
|
-
extractPaths,
|
|
40
|
-
VISIBLE_CONFIRM_WORD,
|
|
41
|
-
INFLIGHT_FILENAME,
|
|
42
|
-
ERROR_CODES,
|
|
43
|
-
} from '../src/truncate-visible.js';
|
|
44
|
-
import { truncateVisibleTool, truncateTool, TOOLS, LIVE_GUARD_CODES, LIVE_ESCAPE_CONFIRM_WORD } from '../src/tools.js';
|
|
45
|
-
import { ensureBackup } from '../src/backup.js';
|
|
46
|
-
import { CONFIRM_WORD } from '../src/truncate.js';
|
|
47
|
-
|
|
48
|
-
// The manual tools refuse to write the session this app has loaded. A test run
|
|
49
|
-
// is never the loaded session: pin a synthetic id so every fixture (whose ids
|
|
50
|
-
// are `session-visible-*`) is "some other session". Tests that need an unknown
|
|
51
|
-
// caller delete this variable and restore it in a finally block.
|
|
52
|
-
if (!process.env.DSH_SESSION_ID) process.env.DSH_SESSION_ID = 'session-suite-runner';
|
|
53
|
-
|
|
54
|
-
function sha256(buf) {
|
|
55
|
-
return crypto.createHash('sha256').update(buf).digest('hex');
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
function buildFixture({ id, turns = 20, title = '可见截断测试', checkpointAt = 0 }) {
|
|
59
|
-
const events = [];
|
|
60
|
-
const surface = [];
|
|
61
|
-
const base = Date.now() - 60_000;
|
|
62
|
-
const push = (event) => {
|
|
63
|
-
event.seq = events.length;
|
|
64
|
-
event.time = base + events.length;
|
|
65
|
-
events.push(event);
|
|
66
|
-
if (event.surfaceOp === 'append') surface.push(event.seq);
|
|
67
|
-
};
|
|
68
|
-
push({
|
|
69
|
-
type: 'system/message',
|
|
70
|
-
surfaceOp: 'append',
|
|
71
|
-
data: { message: { role: 'system', id: 'system-1', source: { kind: 'system-prompt' }, content: [{ type: 'text', text: '测试用系统提示' }] } },
|
|
72
|
-
});
|
|
73
|
-
if (title) push({ type: 'session/title', data: { title, messageSeqs: [], source: { kind: 'user' } } });
|
|
74
|
-
for (let t = 1; t <= turns; t += 1) {
|
|
75
|
-
push({ type: 'turn/start', data: { turn: t } });
|
|
76
|
-
push({ type: 'step/start', data: { turn: t, step: 1 } });
|
|
77
|
-
push({
|
|
78
|
-
type: 'user/message',
|
|
79
|
-
surfaceOp: 'append',
|
|
80
|
-
data: {
|
|
81
|
-
turn: t, step: 1, role: 'user', id: `user-${t}`,
|
|
82
|
-
content: [{ type: 'text', text: `第 ${t} 个问题` }],
|
|
83
|
-
source: { kind: 'user', clientTimeZone: 'Asia/Shanghai' },
|
|
84
|
-
},
|
|
85
|
-
});
|
|
86
|
-
push({
|
|
87
|
-
type: 'assistant/message',
|
|
88
|
-
surfaceOp: 'append',
|
|
89
|
-
data: {
|
|
90
|
-
turn: t, step: 1, stream: [],
|
|
91
|
-
message: {
|
|
92
|
-
role: 'assistant', id: `assistant-call-${t}`,
|
|
93
|
-
source: { kind: 'model', provider: 'deepseek-official', model: 'deepseek-chat' },
|
|
94
|
-
content: [{ type: 'tool-call', id: `call-${t}`, name: 'demo', arguments: '{"n":1}' }],
|
|
95
|
-
},
|
|
96
|
-
},
|
|
97
|
-
});
|
|
98
|
-
push({ type: 'tool/call', data: { turn: t, step: 1, callId: `call-${t}`, name: 'demo', arguments: '{"n":1}' } });
|
|
99
|
-
push({
|
|
100
|
-
type: 'tool/result',
|
|
101
|
-
surfaceOp: 'append',
|
|
102
|
-
sourceEventSeqs: [events.length - 1],
|
|
103
|
-
data: {
|
|
104
|
-
turn: t, step: 1,
|
|
105
|
-
message: {
|
|
106
|
-
role: 'tool', source: { kind: 'tool', callId: `call-${t}` }, toolCallId: `call-${t}`,
|
|
107
|
-
content: [{ type: 'text', text: '{"ok":true}' }], isError: false, id: `result-${t}`,
|
|
108
|
-
},
|
|
109
|
-
},
|
|
110
|
-
});
|
|
111
|
-
push({
|
|
112
|
-
type: 'assistant/message',
|
|
113
|
-
surfaceOp: 'append',
|
|
114
|
-
data: {
|
|
115
|
-
turn: t, step: 1, stream: [],
|
|
116
|
-
message: {
|
|
117
|
-
role: 'assistant', id: `assistant-${t}`,
|
|
118
|
-
source: { kind: 'model', provider: 'deepseek-official', model: 'deepseek-chat' },
|
|
119
|
-
content: [{ type: 'text', text: `第 ${t} 个回答` }],
|
|
120
|
-
},
|
|
121
|
-
},
|
|
122
|
-
});
|
|
123
|
-
if (checkpointAt && t === checkpointAt) {
|
|
124
|
-
// A compaction checkpoint replaces the visible surface so far, exactly
|
|
125
|
-
// like a real log. The log truncator may cut only inside the shadowed
|
|
126
|
-
// span, so a fixture that wants a *successful* truncateSession() cut
|
|
127
|
-
// needs one of these (V13 does; the visible-truncation cases do not).
|
|
128
|
-
const compactionId = 'ckpt-1';
|
|
129
|
-
const startSeq = surface[0];
|
|
130
|
-
const endSeq = surface[surface.length - 1];
|
|
131
|
-
push({ type: 'compaction/start', data: { compactionId, turn: t } });
|
|
132
|
-
push({
|
|
133
|
-
type: 'compaction/summary',
|
|
134
|
-
data: {
|
|
135
|
-
compactionId, turn: t, summary: '(压缩摘要)',
|
|
136
|
-
shadowedRange: { start: startSeq, end: endSeq },
|
|
137
|
-
shadowedSeqs: [...surface],
|
|
138
|
-
},
|
|
139
|
-
});
|
|
140
|
-
push({
|
|
141
|
-
type: 'user/message',
|
|
142
|
-
surfaceOp: { op: 'replace', startSeq, endSeq },
|
|
143
|
-
sourceEventSeqs: [...surface],
|
|
144
|
-
data: {
|
|
145
|
-
turn: t, step: 1, role: 'user', id: `checkpoint-${t}`,
|
|
146
|
-
content: [{ type: 'text', text: '(压缩摘要)' }],
|
|
147
|
-
source: { kind: 'compact-checkpoint', compactionId },
|
|
148
|
-
},
|
|
149
|
-
});
|
|
150
|
-
push({ type: 'compaction/end', data: { compactionId, turn: t } });
|
|
151
|
-
surface.length = 0;
|
|
152
|
-
surface.push(events.length - 1);
|
|
153
|
-
}
|
|
154
|
-
push({ type: 'step/end', data: { turn: t, step: 1 } });
|
|
155
|
-
// Real host logs always carry a turn-end reason object. Keeping the fixture
|
|
156
|
-
// honest is what lets V14/V15 prove that truncation adds the missing one on
|
|
157
|
-
// its synthetic head instead of relying on unrealistic input.
|
|
158
|
-
push({ type: 'turn/end', data: { turn: t, reason: { kind: 'completed' } } });
|
|
159
|
-
}
|
|
160
|
-
return {
|
|
161
|
-
header: {
|
|
162
|
-
type: 'session', version: 4, id, createdAt: base,
|
|
163
|
-
cwd: 'C:\\fixtures', isSeeded: false, delegationDepth: 0,
|
|
164
|
-
},
|
|
165
|
-
events,
|
|
166
|
-
};
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
export function writeFixture(base, name, options = {}) {
|
|
170
|
-
const { header, events } = buildFixture({ id: `session-visible-${name}`, ...options });
|
|
171
|
-
const file = path.join(base, 'home', 'sessions', 'scope-fixtures', name, 'session.v4.jsonl.zstd');
|
|
172
|
-
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
173
|
-
fs.writeFileSync(file, encodeSession(header, events));
|
|
174
|
-
return { file, header, events };
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
function readParsed(file) {
|
|
178
|
-
return parseSession(fs.readFileSync(file));
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
function fileSha(file) {
|
|
182
|
-
return sha256(fs.readFileSync(file));
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
function inflightRecord({ file, backup, beforeBuf, beforeSha, built }) {
|
|
186
|
-
return {
|
|
187
|
-
version: 1,
|
|
188
|
-
kind: 'session-truncate-visible',
|
|
189
|
-
target: file,
|
|
190
|
-
archivePath: `${file}.archive/test.jsonl.zstd`,
|
|
191
|
-
backupPath: backup.file,
|
|
192
|
-
backupSha256: beforeSha,
|
|
193
|
-
beforeSha256: beforeSha,
|
|
194
|
-
beforeSize: beforeBuf.length,
|
|
195
|
-
expectedSha256: built.sha256,
|
|
196
|
-
expectedSize: built.bytes,
|
|
197
|
-
expectedEvents: built.events.length,
|
|
198
|
-
expectedMessages: built.messages,
|
|
199
|
-
tmpPath: `${file}.truncate-visible.tmp-test`,
|
|
200
|
-
phase: 'prepared',
|
|
201
|
-
startedAt: new Date().toISOString(),
|
|
202
|
-
keepTurns: 5,
|
|
203
|
-
keepTokens: 1_000_000,
|
|
204
|
-
cutTurn: 16,
|
|
205
|
-
cutSeq: 122,
|
|
206
|
-
droppedEvents: 0,
|
|
207
|
-
droppedMessages: 0,
|
|
208
|
-
keptEvents: built.retainedEvents,
|
|
209
|
-
keptMessages: built.retainedMessages,
|
|
210
|
-
platform: process.platform,
|
|
211
|
-
pid: process.pid,
|
|
212
|
-
};
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
// ------------------------------------------------------- 0.7.6 oracle + corpus
|
|
216
|
-
//
|
|
217
|
-
// `LEGACY_PATH_RE` is a frozen copy of the pattern `extractPaths` used up to
|
|
218
|
-
// 0.7.6. It is test-only: src/ no longer contains it, because it backtracked
|
|
219
|
-
// exponentially on long separator runs. N5 uses it purely as a differential
|
|
220
|
-
// oracle, on strings small enough for it to finish.
|
|
221
|
-
|
|
222
|
-
const LEGACY_PATH_RE = /(?:[A-Za-z]:[\\/]|\/)(?:[^"'<>\s|:*?]+[\\/])*[^"'<>\s|:*?]+\.(?:js|mjs|cjs|ts|tsx|jsx|json|md|txt|log|ps1|psm1|py|yml|yaml|zst|html|css|toml|ini|cfg|zip|png|jpg|jpeg|wav|mp3)/g;
|
|
223
|
-
|
|
224
|
-
function legacyMatchStrings(text) {
|
|
225
|
-
return text.match(LEGACY_PATH_RE) ?? [];
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
function walkStrings(value, out = []) {
|
|
229
|
-
if (value == null) return out;
|
|
230
|
-
if (typeof value === 'string') { out.push(value); return out; }
|
|
231
|
-
if (Array.isArray(value)) { for (const item of value) walkStrings(item, out); return out; }
|
|
232
|
-
if (typeof value === 'object') { for (const item of Object.values(value)) walkStrings(item, out); }
|
|
233
|
-
return out;
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
function separatorCount(text, limit = Number.POSITIVE_INFINITY) {
|
|
237
|
-
let count = 0;
|
|
238
|
-
for (let i = 0; i < text.length; i += 1) {
|
|
239
|
-
const code = text.charCodeAt(i);
|
|
240
|
-
if (code === 0x2f || code === 0x5c) {
|
|
241
|
-
count += 1;
|
|
242
|
-
if (count >= limit) return count;
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
return count;
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
function legacyExtractPaths(droppedEvents, max = 8) {
|
|
249
|
-
const counts = new Map();
|
|
250
|
-
for (const event of droppedEvents) {
|
|
251
|
-
for (const text of walkStrings(event.data)) {
|
|
252
|
-
for (const raw of legacyMatchStrings(text)) {
|
|
253
|
-
const normalized = raw.replace(/\\\\/g, '\\').replace(/\\/g, '/');
|
|
254
|
-
if (normalized.length < 5 || normalized.length > 180) continue;
|
|
255
|
-
const key = normalized.toLowerCase();
|
|
256
|
-
counts.set(key, { path: normalized, count: (counts.get(key)?.count ?? 0) + 1 });
|
|
257
|
-
}
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
return [...counts.values()]
|
|
261
|
-
.sort((a, b) => b.count - a.count || a.path.localeCompare(b.path))
|
|
262
|
-
.slice(0, max)
|
|
263
|
-
.map((item) => item.path);
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
// Hand-picked strings around every branch of the grammar: drive prefixes, bare
|
|
267
|
-
// slashes, quotes/whitespace/`:`/`|`/`*`/`?` terminators, extension order
|
|
268
|
-
// (`.json` ends at `.js`), empty bodies, multibyte text.
|
|
269
|
-
const CURATED_PATH_SAMPLES = [
|
|
270
|
-
'', '/', 'a', '/a.js', '/a.json', '/a.jsx', '/a.JSON', '/a.mjs', '/a.jpeg', '/a.jpg', '/a.png',
|
|
271
|
-
'/a b.js', '/a"b.js', '/a<b.js', '/a|b.js', '/a*b.js', '/a?b.js', '/a:b.js', '/a\tb.js',
|
|
272
|
-
'/a\nb.js', '/.js', '/..js', '/a/', '/a/b/c.md', '/a//b.md', '/a\\b.md', 'C:\\a\\b.js',
|
|
273
|
-
'C:/a/b.js', 'c:\\x', 'C:\\', 'C:/', 'C:a/b.js', '::C:\\a.js', 'xC:\\a.js', 'x C:\\a.js',
|
|
274
|
-
'/a.js/b.md', '/a.js/b.md5', '/x/a.js.y', '/x/a.b.c.js', '/x/a.b.c', '//server/share/a.js',
|
|
275
|
-
String.raw`\\server\share\a.js`, String.raw`\\?\C:\a.js`, 'see /tmp/a.js and C:\\x\\b.json now',
|
|
276
|
-
'https://example.com/a.js', '/a.js?x=1', '/a.js#frag', '"/a.js"', "('/a.js')", '/a.js,',
|
|
277
|
-
'/a.js;', '/a.js)', '/a.js]', '/a.js}', '/a.js\\', '/a.js|', '/汉字/文件.js', '/漢字.js',
|
|
278
|
-
'/a.js/very/long/path/that/has/a/file.md', '/ab.js', '////a.js', '/a/.js', '/a/./b.js',
|
|
279
|
-
'/a/../b.js', '\\\\a\\b.js', '/\\/a.js', 'C:\\a\\b', 'x.js', '.js', 'a.js', 'a/b.js',
|
|
280
|
-
'/tmp/x.jpg.png', '/tmp/.hidden.md', '/tmp/a..js', '/tmp/a. .js', 'D:\\Users\\x\\.dsh\\a.zst',
|
|
281
|
-
];
|
|
282
|
-
|
|
283
|
-
// Deterministic pseudo-random corpus (LCG, no Math.random) over an alphabet that
|
|
284
|
-
// mixes separators, dots, extension letters and the characters that end a path.
|
|
285
|
-
function generatePathCorpus(count) {
|
|
286
|
-
let state = 0x5eed1234;
|
|
287
|
-
const next = () => {
|
|
288
|
-
state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
|
|
289
|
-
return state / 0x1_0000_0000;
|
|
290
|
-
};
|
|
291
|
-
const alphabet = '/\\.:abjsm1 "|*?<>-\tqdWZ_\u00e9\u6c49';
|
|
292
|
-
const extensions = ['js', 'mjs', 'json', 'md', 'txt', 'png', 'jpeg', 'exe', 'JS', 'j', 'json5'];
|
|
293
|
-
const junk = ['a', 'bb', 'Z', '0', '_', '-', '.', ' ', '"', ':', '|', '\u6c49'];
|
|
294
|
-
const corpus = [];
|
|
295
|
-
while (corpus.length < count) {
|
|
296
|
-
let text = '';
|
|
297
|
-
if (next() < 0.3) text += 'C:';
|
|
298
|
-
const parts = 1 + Math.floor(next() * 6);
|
|
299
|
-
for (let p = 0; p < parts; p += 1) {
|
|
300
|
-
const roll = next();
|
|
301
|
-
if (roll < 0.3) text += '/';
|
|
302
|
-
else if (roll < 0.4) text += '\\';
|
|
303
|
-
else if (roll < 0.5) text += '.';
|
|
304
|
-
else if (roll < 0.8) text += extensions[Math.floor(next() * extensions.length)];
|
|
305
|
-
else text += junk[Math.floor(next() * junk.length)];
|
|
306
|
-
if (next() < 0.2) text += '.';
|
|
307
|
-
}
|
|
308
|
-
if (separatorCount(text, 11) > 10) continue;
|
|
309
|
-
corpus.push(text);
|
|
310
|
-
}
|
|
311
|
-
// A few pure-random strings too, for combinations the generator never builds.
|
|
312
|
-
for (let n = 0; n < 1_000; n += 1) {
|
|
313
|
-
const length = 1 + Math.floor(next() * 18);
|
|
314
|
-
let text = '';
|
|
315
|
-
for (let i = 0; i < length; i += 1) text += alphabet[Math.floor(next() * alphabet.length)];
|
|
316
|
-
if (separatorCount(text, 11) > 10) continue;
|
|
317
|
-
corpus.push(text);
|
|
318
|
-
}
|
|
319
|
-
return corpus;
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
// Find a large, settled session log to copy read-only. Never used for anything
|
|
323
|
-
// but a copy: the original is only opened with fs.readFileSync/statSync.
|
|
324
|
-
function findRealSessionLog(minBytes = 5 * 1024 * 1024) {
|
|
325
|
-
const sessionsRoot = path.join(os.homedir(), '.dsh', 'sessions');
|
|
326
|
-
let scopes;
|
|
327
|
-
try { scopes = fs.readdirSync(sessionsRoot, { withFileTypes: true }); } catch { return null; }
|
|
328
|
-
const candidates = [];
|
|
329
|
-
for (const scope of scopes) {
|
|
330
|
-
if (!scope.isDirectory()) continue;
|
|
331
|
-
let entries;
|
|
332
|
-
try {
|
|
333
|
-
entries = fs.readdirSync(path.join(sessionsRoot, scope.name), { withFileTypes: true });
|
|
334
|
-
} catch { continue; }
|
|
335
|
-
for (const entry of entries) {
|
|
336
|
-
if (!entry.isDirectory()) continue;
|
|
337
|
-
const file = path.join(sessionsRoot, scope.name, entry.name, 'session.v4.jsonl.zstd');
|
|
338
|
-
let stat;
|
|
339
|
-
try { stat = fs.statSync(file); } catch { continue; }
|
|
340
|
-
if (!stat.isFile() || stat.size < minBytes) continue;
|
|
341
|
-
candidates.push({ file, size: stat.size, mtimeMs: stat.mtimeMs, name: entry.name });
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
|
-
if (!candidates.length) return null;
|
|
345
|
-
const known = candidates.find((item) => item.name.includes('0ba78a91'));
|
|
346
|
-
if (known) return known;
|
|
347
|
-
// Prefer a log nobody is writing right now, then the biggest one.
|
|
348
|
-
const settled = candidates
|
|
349
|
-
.filter((item) => Date.now() - item.mtimeMs > 10 * 60_000)
|
|
350
|
-
.sort((a, b) => b.size - a.size);
|
|
351
|
-
return settled[0] ?? null;
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
export function runVisibleTruncateSuite({ runCase, assert, TMP }) {
|
|
355
|
-
const base = fs.mkdtempSync(path.join(TMP, 'visible-'));
|
|
356
|
-
|
|
357
|
-
// 0.8.0-rc.11 fixtures need to tamper with texts / references without
|
|
358
|
-
// changing the event count (which would invalidate seq-based references).
|
|
359
|
-
// Patching happens before encoding, so every seq stays authoritative.
|
|
360
|
-
function writePatchedFixture(name, options, patch) {
|
|
361
|
-
const { header, events } = buildFixture({ id: `session-visible-${name}`, ...options });
|
|
362
|
-
patch(events, header);
|
|
363
|
-
const file = path.join(base, 'home', 'sessions', 'scope-fixtures', name, 'session.v4.jsonl.zstd');
|
|
364
|
-
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
365
|
-
fs.writeFileSync(file, encodeSession(header, events));
|
|
366
|
-
return { file, header, events };
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
runCase('V1', 'visible dry-run 不改文件、不写归档/回滚记录', () => {
|
|
370
|
-
const { file } = writeFixture(base, 'dry');
|
|
371
|
-
const before = fileSha(file);
|
|
372
|
-
const result = truncateVisibleSession(file, {
|
|
373
|
-
dryRun: true, keepTurns: 5, keepTokens: 1_000_000, recentWriteWindowMs: 0,
|
|
374
|
-
});
|
|
375
|
-
assert(result.needed === true, 'dry-run must find a boundary');
|
|
376
|
-
assert(result.status === 'planned', `status ${result.status}`);
|
|
377
|
-
assert(result.cut.turn === 16, `cut turn ${result.cut.turn}, expected 16`);
|
|
378
|
-
assert(result.keptTurnCount === 5, `kept ${result.keptTurnCount}`);
|
|
379
|
-
assert(fileSha(file) === before, 'dry-run changed the log bytes');
|
|
380
|
-
assert(!fs.existsSync(archiveDirFor(file)), 'dry-run created an archive directory');
|
|
381
|
-
assert(!fs.existsSync(inflightPathFor(file)), 'dry-run created an inflight record');
|
|
382
|
-
assert(!fs.existsSync(path.join(path.dirname(file), 'truncate-visible.json')), 'dry-run wrote a ledger');
|
|
383
|
-
assert(result.message.includes('预演'), 'report must say 预演');
|
|
384
|
-
return `cut turn ${result.cut.turn}, kept ${result.keptTurnCount}`;
|
|
385
|
-
});
|
|
386
|
-
|
|
387
|
-
runCase('V2', 'visible 写盘必须精确确认词', () => {
|
|
388
|
-
const { file } = writeFixture(base, 'confirm');
|
|
389
|
-
const before = fileSha(file);
|
|
390
|
-
let direct = null;
|
|
391
|
-
try {
|
|
392
|
-
truncateVisibleSession(file, {
|
|
393
|
-
dryRun: false, confirm: 'TRUNCATE', keepTurns: 5, keepTokens: 1_000_000, recentWriteWindowMs: 0,
|
|
394
|
-
});
|
|
395
|
-
} catch (error) {
|
|
396
|
-
direct = error;
|
|
397
|
-
}
|
|
398
|
-
assert(direct && direct.code === ERROR_CODES.CONFIRM_REQUIRED, `direct code ${direct?.code}`);
|
|
399
|
-
assert(fileSha(file) === before, 'refused write changed the file');
|
|
400
|
-
|
|
401
|
-
const viaTool = truncateVisibleTool({
|
|
402
|
-
sessionPath: file, dryRun: false, confirm: 'truncate-visible',
|
|
403
|
-
keepTurns: 5, keepTokens: 1_000_000,
|
|
404
|
-
}, { home: path.join(base, 'home'), recentWriteWindowMs: 0 });
|
|
405
|
-
assert(viaTool.ok === false, 'tool accepted a bad confirm word');
|
|
406
|
-
assert(viaTool.code === 'CONFIRM_REQUIRED', `tool code ${viaTool.code}`);
|
|
407
|
-
assert(viaTool.message.includes(VISIBLE_CONFIRM_WORD), 'tool error must name the confirm word');
|
|
408
|
-
return 'both direct and tool paths refuse';
|
|
409
|
-
});
|
|
410
|
-
|
|
411
|
-
runCase('V3', 'visible 真截断:seq 连续、保留段逐字段一致、归档含被删前缀', () => {
|
|
412
|
-
const { file } = writeFixture(base, 'real');
|
|
413
|
-
const beforeParsed = readParsed(file);
|
|
414
|
-
const beforeSha = fileSha(file);
|
|
415
|
-
const result = truncateVisibleSession(file, {
|
|
416
|
-
dryRun: false, confirm: VISIBLE_CONFIRM_WORD,
|
|
417
|
-
keepTurns: 5, keepTokens: 1_000_000, recentWriteWindowMs: 0,
|
|
418
|
-
});
|
|
419
|
-
assert(result.applied === true, 'write did not land');
|
|
420
|
-
assert(result.after.bytes < result.before.bytes, 'rewrite did not shrink the file');
|
|
421
|
-
assert(result.after.messages < result.before.messages, 'rewrite did not reduce message count');
|
|
422
|
-
assert(!fs.existsSync(inflightPathFor(file)), 'inflight record survived a successful write');
|
|
423
|
-
assert(fs.existsSync(result.archivePath), 'archive file is missing');
|
|
424
|
-
assert(fs.existsSync(result.backupPath), 'backup file is missing');
|
|
425
|
-
|
|
426
|
-
const afterParsed = readParsed(file);
|
|
427
|
-
assertContiguous(afterParsed.events);
|
|
428
|
-
afterParsed.events.forEach((event, index) => {
|
|
429
|
-
assert(event.seq === index, `event ${index} has seq ${event.seq}`);
|
|
430
|
-
});
|
|
431
|
-
const digest = deriveMessagesDigest(afterParsed.header, afterParsed.events);
|
|
432
|
-
assert(digest.count === result.after.messages, `digest ${digest.count} != report ${result.after.messages}`);
|
|
433
|
-
|
|
434
|
-
const originalKept = beforeParsed.events.slice(result.cut.startSeq);
|
|
435
|
-
const rewrittenKept = afterParsed.events.slice(afterParsed.events.length - originalKept.length);
|
|
436
|
-
assert(originalKept.length === rewrittenKept.length, 'retained length changed');
|
|
437
|
-
for (let i = 0; i < originalKept.length; i += 1) {
|
|
438
|
-
const expected = structuredClone(originalKept[i].data);
|
|
439
|
-
if (expected && typeof expected === 'object' && typeof expected.turn === 'number') {
|
|
440
|
-
expected.turn += 2 - result.cut.turn;
|
|
441
|
-
}
|
|
442
|
-
assert(isDeepStrictEqual(rewrittenKept[i].data, expected),
|
|
443
|
-
`retained event ${i} data changed: ${JSON.stringify(rewrittenKept[i].data)} != ${JSON.stringify(expected)}`);
|
|
444
|
-
assert(rewrittenKept[i].type === originalKept[i].type, `retained event ${i} type changed`);
|
|
445
|
-
assert(rewrittenKept[i].time === originalKept[i].time, `retained event ${i} time changed`);
|
|
446
|
-
}
|
|
447
|
-
assert(rewrittenKept[0].type === 'turn/start', 'cut did not land on a turn/start');
|
|
448
|
-
const withRefs = rewrittenKept.filter((event) => Array.isArray(event.sourceEventSeqs));
|
|
449
|
-
assert(withRefs.length > 0, 'fixture lost its tool/result sourceEventSeqs');
|
|
450
|
-
for (const event of withRefs) {
|
|
451
|
-
for (const ref of event.sourceEventSeqs) {
|
|
452
|
-
assert(ref < event.seq, `sourceEventSeqs ${ref} is not earlier than seq ${event.seq}`);
|
|
453
|
-
assert(afterParsed.events[ref]?.type === 'tool/call', `sourceEventSeqs ${ref} does not point at tool/call`);
|
|
454
|
-
}
|
|
455
|
-
}
|
|
456
|
-
|
|
457
|
-
const archiveParsed = readParsed(result.archivePath);
|
|
458
|
-
assert(archiveParsed.events.length === result.cut.startSeq,
|
|
459
|
-
`archive has ${archiveParsed.events.length} events, expected ${result.cut.startSeq}`);
|
|
460
|
-
for (let i = 0; i < archiveParsed.events.length; i += 1) {
|
|
461
|
-
assert(isDeepStrictEqual(archiveParsed.events[i].data, beforeParsed.events[i].data),
|
|
462
|
-
`archive event ${i} data differs from the original`);
|
|
463
|
-
assert(archiveParsed.events[i].type === beforeParsed.events[i].type, `archive event ${i} type differs`);
|
|
464
|
-
}
|
|
465
|
-
assert(fileSha(file) === result.after.sha256, 'read-back sha differs from report');
|
|
466
|
-
assert(beforeSha !== result.after.sha256, 'sha did not change');
|
|
467
|
-
return `bytes ${result.before.bytes} -> ${result.after.bytes}, messages ${result.before.messages} -> ${result.after.messages}`;
|
|
468
|
-
});
|
|
469
|
-
|
|
470
|
-
runCase('V4', 'visible 保留首条真人消息并插入归档卡', () => {
|
|
471
|
-
const { file } = writeFixture(base, 'carry');
|
|
472
|
-
const result = truncateVisibleSession(file, {
|
|
473
|
-
dryRun: false, confirm: VISIBLE_CONFIRM_WORD,
|
|
474
|
-
keepTurns: 5, keepTokens: 1_000_000, recentWriteWindowMs: 0,
|
|
475
|
-
});
|
|
476
|
-
const parsed = readParsed(file);
|
|
477
|
-
assert(parsed.events[0].type === 'turn/start', 'synthetic head turn is not first');
|
|
478
|
-
assert(parsed.events[1].type === 'step/start', 'synthetic head step is not second');
|
|
479
|
-
assert(parsed.events[2].type === 'system/message', 'head is not inside the synthetic turn');
|
|
480
|
-
assert(parsed.events[5].type === 'user/message', 'archive card is not first surface message after the head turn');
|
|
481
|
-
assert(parsed.events[5].data.source.kind === 'archive-card', 'archive card source kind');
|
|
482
|
-
const card = parsed.events[5].data.content[0].text;
|
|
483
|
-
assert(card.startsWith('[已归档 '), `card does not start with [已归档: ${card.slice(0, 40)}`);
|
|
484
|
-
assert(card.includes('当时在做:'), 'card has no 当时在做');
|
|
485
|
-
assert(card.includes('原文归档:'), 'card has no 原文归档');
|
|
486
|
-
const carry = parsed.events[6].data.content[0].text;
|
|
487
|
-
assert(carry.startsWith('[会话起点 · 已归档]'), 'first-user carry marker missing');
|
|
488
|
-
assert(carry.includes('第 1 个问题'), 'first-user text missing');
|
|
489
|
-
assert(result.firstUserMessage.carried === true, 'report did not mark the first user message carried');
|
|
490
|
-
return `card ${card.split('\n').length} lines`;
|
|
491
|
-
});
|
|
492
|
-
|
|
493
|
-
runCase('V5', 'visible 边界:12 轮/80K token 取更靠后,且不切 sub-turn', () => {
|
|
494
|
-
const { file } = writeFixture(base, 'boundary');
|
|
495
|
-
const parsed = readParsed(file);
|
|
496
|
-
const planTurns = planVisibleTruncation(parsed, { keepTurns: 5, keepTokens: 1_000_000 });
|
|
497
|
-
assert(planTurns.cutTurn === 16, `keepTurns plan cut ${planTurns.cutTurn}`);
|
|
498
|
-
assert(planTurns.keptTurnCount === 5, `keepTurns kept ${planTurns.keptTurnCount}`);
|
|
499
|
-
|
|
500
|
-
const planTokens = planVisibleTruncation(parsed, { keepTurns: 1, keepTokens: 1 });
|
|
501
|
-
assert(planTokens.cutTurn === 20, `token plan cut ${planTokens.cutTurn}`);
|
|
502
|
-
assert(planTokens.keptTurnCount === 1, `token plan kept ${planTokens.keptTurnCount}`);
|
|
503
|
-
|
|
504
|
-
const none = planVisibleTruncation(parsed, { keepTurns: 100, keepTokens: 1_000_000_000 });
|
|
505
|
-
assert(none.needed === false, 'a 100-turn keep request must be a no-op');
|
|
506
|
-
return `turn cut ${planTurns.cutTurn}, token cut ${planTokens.cutTurn}`;
|
|
507
|
-
});
|
|
508
|
-
|
|
509
|
-
runCase('V6', 'visible 崩溃恢复:写一半可回滚、rename 后可判定完成', () => {
|
|
510
|
-
const { file } = writeFixture(base, 'crash');
|
|
511
|
-
const beforeBuf = fs.readFileSync(file);
|
|
512
|
-
const beforeSha = sha256(beforeBuf);
|
|
513
|
-
const beforeParsed = parseSession(beforeBuf);
|
|
514
|
-
const plan = planVisibleTruncation(beforeParsed, { keepTurns: 5, keepTokens: 1_000_000 });
|
|
515
|
-
const built = buildVisibleTruncated(beforeParsed, plan, {
|
|
516
|
-
now: Date.now(), archivePath: `${file}.archive/test.jsonl.zstd`,
|
|
517
|
-
});
|
|
518
|
-
const backup = ensureBackup(file, {
|
|
519
|
-
date: new Date(), sourceBuf: beforeBuf, sha256: beforeSha, size: beforeBuf.length,
|
|
520
|
-
});
|
|
521
|
-
const record = inflightRecord({ file, backup, beforeBuf, beforeSha, built });
|
|
522
|
-
|
|
523
|
-
// A torn write: half the new buffer and a record that says "prepared".
|
|
524
|
-
fs.writeFileSync(file, built.buffer.subarray(0, Math.floor(built.buffer.length / 2)));
|
|
525
|
-
fs.writeFileSync(inflightPathFor(file), JSON.stringify(record, null, 2));
|
|
526
|
-
assert(readInflight(file)?.target === file, 'inflight record is not readable');
|
|
527
|
-
const rolled = recoverInflight(file);
|
|
528
|
-
assert(rolled.status === 'rolled-back', `torn recovery status ${rolled.status}`);
|
|
529
|
-
assert(fileSha(file) === beforeSha, 'torn recovery did not restore the original bytes');
|
|
530
|
-
assert(!fs.existsSync(inflightPathFor(file)), 'torn recovery left the record');
|
|
531
|
-
|
|
532
|
-
// A crash after rename: the target already has the new bytes.
|
|
533
|
-
fs.writeFileSync(file, built.buffer);
|
|
534
|
-
fs.writeFileSync(inflightPathFor(file), JSON.stringify(record, null, 2));
|
|
535
|
-
const completed = recoverInflight(file);
|
|
536
|
-
assert(completed.status === 'completed', `post-rename recovery status ${completed.status}`);
|
|
537
|
-
assert(fileSha(file) === built.sha256, 'post-rename recovery changed the new bytes');
|
|
538
|
-
assert(!fs.existsSync(inflightPathFor(file)), 'post-rename recovery left the record');
|
|
539
|
-
|
|
540
|
-
// A crash before the rename: the target is still the old bytes.
|
|
541
|
-
fs.writeFileSync(file, beforeBuf);
|
|
542
|
-
fs.writeFileSync(inflightPathFor(file), JSON.stringify(record, null, 2));
|
|
543
|
-
const clean = recoverInflight(file);
|
|
544
|
-
assert(clean.status === 'clean', `pre-rename recovery status ${clean.status}`);
|
|
545
|
-
assert(fileSha(file) === beforeSha, 'pre-rename recovery changed the old bytes');
|
|
546
|
-
assert(!fs.existsSync(inflightPathFor(file)), 'pre-rename recovery left the record');
|
|
547
|
-
return 'rolled-back / completed / clean all reached';
|
|
548
|
-
});
|
|
549
|
-
|
|
550
|
-
runCase('V7', 'visible 故障注入:rename 后校验失败会恢复备份', () => {
|
|
551
|
-
const { file } = writeFixture(base, 'fault');
|
|
552
|
-
const before = fileSha(file);
|
|
553
|
-
let error = null;
|
|
554
|
-
try {
|
|
555
|
-
truncateVisibleSession(file, {
|
|
556
|
-
dryRun: false, confirm: VISIBLE_CONFIRM_WORD,
|
|
557
|
-
keepTurns: 5, keepTokens: 1_000_000, recentWriteWindowMs: 0,
|
|
558
|
-
faultAt: 'after-rename',
|
|
559
|
-
});
|
|
560
|
-
} catch (caught) {
|
|
561
|
-
error = caught;
|
|
562
|
-
}
|
|
563
|
-
assert(error && error.code === ERROR_CODES.FAULT_INJECTED, `fault code ${error?.code}`);
|
|
564
|
-
assert(error.result?.restored === true, 'fault path did not report a restore');
|
|
565
|
-
assert(fileSha(file) === before, 'fault path did not restore the original bytes');
|
|
566
|
-
assert(!fs.existsSync(inflightPathFor(file)), 'fault path left the inflight record');
|
|
567
|
-
return 'restored after injected fault';
|
|
568
|
-
});
|
|
569
|
-
|
|
570
|
-
runCase('V8', '手动工具拒绝写当前会话:两条截断工具入口拒绝,dry-run 仍可预演', () => {
|
|
571
|
-
const { file } = writeFixture(base, 'tool-live');
|
|
572
|
-
const currentId = 'session-visible-tool-live';
|
|
573
|
-
const before = fileSha(file);
|
|
574
|
-
const binds = [];
|
|
575
|
-
const autoHeartbeat = { bind: (sid) => { binds.push(sid); return true; } };
|
|
576
|
-
const saved = process.env.DSH_SESSION_ID;
|
|
577
|
-
delete process.env.DSH_SESSION_ID; // exercise the explicit config identity path
|
|
578
|
-
try {
|
|
579
|
-
const cfg = { home: path.join(base, 'home'), recentWriteWindowMs: 0, currentSessionId: currentId, autoHeartbeat };
|
|
580
|
-
|
|
581
|
-
// A dry run is a plan, not a write: the live guard must not fire.
|
|
582
|
-
const planned = truncateVisibleTool({
|
|
583
|
-
sessionPath: file, keepTurns: 5, keepTokens: 1_000_000,
|
|
584
|
-
}, cfg);
|
|
585
|
-
assert(planned.ok === true && planned.status === 'planned', `planned ${planned.status}`);
|
|
586
|
-
assert(planned.message.includes('预演'), 'tool dry-run report missing 预演');
|
|
587
|
-
assert(planned.rollback === null, 'dry-run must not claim a rollback command');
|
|
588
|
-
|
|
589
|
-
const refused = truncateVisibleTool({
|
|
590
|
-
sessionPath: file, dryRun: false, confirm: VISIBLE_CONFIRM_WORD,
|
|
591
|
-
keepTurns: 5, keepTokens: 1_000_000,
|
|
592
|
-
}, cfg);
|
|
593
|
-
assert(refused.ok === false && refused.status === 'error', `written ${refused.status}`);
|
|
594
|
-
assert(refused.code === LIVE_GUARD_CODES.TARGET_IS_LIVE_SESSION, `code ${refused.code}`);
|
|
595
|
-
assert(refused.message.includes('currently loaded by this app'), `message ${refused.message}`);
|
|
596
|
-
assert(refused.message.includes('app is stopped'), 'message does not say to stop the app');
|
|
597
|
-
assert(fileSha(file) === before, 'refusal changed the session bytes');
|
|
598
|
-
assert(!fs.existsSync(archiveDirFor(file)), 'refusal created an archive dir');
|
|
599
|
-
assert(!fs.existsSync(inflightPathFor(file)), 'refusal left an inflight record');
|
|
600
|
-
assert(binds.length > 0 && binds[0] === currentId, `identity chain did not bind (${binds.join(',')})`);
|
|
601
|
-
|
|
602
|
-
// The log-level tool (truncateSession) shares the same live guard.
|
|
603
|
-
const refusedLog = truncateTool({
|
|
604
|
-
sessionPath: file, dryRun: false, confirm: CONFIRM_WORD, keepEvents: 10,
|
|
605
|
-
}, cfg);
|
|
606
|
-
assert(refusedLog.ok === false && refusedLog.code === LIVE_GUARD_CODES.TARGET_IS_LIVE_SESSION,
|
|
607
|
-
`log tool code ${refusedLog.code}`);
|
|
608
|
-
assert(fileSha(file) === before, 'log tool refusal changed the session bytes');
|
|
609
|
-
return 'both tools refused; bytes, archive dir and inflight tree unchanged';
|
|
610
|
-
} finally {
|
|
611
|
-
process.env.DSH_SESSION_ID = saved;
|
|
612
|
-
}
|
|
613
|
-
});
|
|
614
|
-
|
|
615
|
-
runCase('V9', '其他会话 + 精确确认词:允许截断并给出回滚命令;schema 含 allowLive', () => {
|
|
616
|
-
const { file } = writeFixture(base, 'tool-other');
|
|
617
|
-
const before = fileSha(file);
|
|
618
|
-
const written = truncateVisibleTool({
|
|
619
|
-
sessionPath: file, dryRun: false, confirm: VISIBLE_CONFIRM_WORD,
|
|
620
|
-
keepTurns: 5, keepTokens: 1_000_000,
|
|
621
|
-
}, {
|
|
622
|
-
home: path.join(base, 'home'), recentWriteWindowMs: 0,
|
|
623
|
-
currentSessionId: 'session-visible-somebody-else',
|
|
624
|
-
});
|
|
625
|
-
assert(written.ok === true && written.status === 'truncated', `written ${written.status}`);
|
|
626
|
-
assert(fileSha(file) !== before, 'allowed write did not change the session bytes');
|
|
627
|
-
assert(written.message.includes('已截断'), 'tool write report missing 已截断');
|
|
628
|
-
assert(written.rollback.includes('Copy-Item') || written.rollback.includes('cp -f'),
|
|
629
|
-
'tool write report has no rollback command');
|
|
630
|
-
|
|
631
|
-
const tool = TOOLS.find((entry) => entry.name === 'session_truncate_visible');
|
|
632
|
-
assert(tool, 'session_truncate_visible is not in TOOLS');
|
|
633
|
-
for (const key of ['sessionPath', 'sessionId', 'session', 'keepTurns', 'keepTokens', 'dryRun', 'confirm', 'allowLive']) {
|
|
634
|
-
assert(tool.parameters[key], `parameter ${key} missing`);
|
|
635
|
-
}
|
|
636
|
-
assert(tool.parameters.confirm.description.includes(VISIBLE_CONFIRM_WORD), 'confirm description');
|
|
637
|
-
assert(tool.parameters.allowLive.description.includes(LIVE_ESCAPE_CONFIRM_WORD),
|
|
638
|
-
'allowLive description does not name the escape word');
|
|
639
|
-
const logTool = TOOLS.find((entry) => entry.name === 'session_truncate');
|
|
640
|
-
assert(logTool && logTool.parameters.allowLive, 'session_truncate has no allowLive parameter');
|
|
641
|
-
return `rollback: ${written.rollback.slice(0, 60)}`;
|
|
642
|
-
});
|
|
643
|
-
|
|
644
|
-
runCase('V11', '当前会话 id 未知:写路径 fail-closed 拒绝,dry-run 仍可预演', () => {
|
|
645
|
-
const { file } = writeFixture(base, 'tool-unknown');
|
|
646
|
-
const before = fileSha(file);
|
|
647
|
-
const saved = process.env.DSH_SESSION_ID;
|
|
648
|
-
delete process.env.DSH_SESSION_ID;
|
|
649
|
-
try {
|
|
650
|
-
const cfg = { home: path.join(base, 'home'), recentWriteWindowMs: 0 };
|
|
651
|
-
const planned = truncateVisibleTool({
|
|
652
|
-
sessionPath: file, keepTurns: 5, keepTokens: 1_000_000,
|
|
653
|
-
}, cfg);
|
|
654
|
-
assert(planned.ok === true && planned.status === 'planned', `dry-run became ${planned.status}`);
|
|
655
|
-
|
|
656
|
-
const refused = truncateVisibleTool({
|
|
657
|
-
sessionPath: file, dryRun: false, confirm: VISIBLE_CONFIRM_WORD,
|
|
658
|
-
keepTurns: 5, keepTokens: 1_000_000,
|
|
659
|
-
}, cfg);
|
|
660
|
-
assert(refused.ok === false && refused.code === LIVE_GUARD_CODES.CURRENT_ID_UNKNOWN,
|
|
661
|
-
`code ${refused.code}`);
|
|
662
|
-
assert(refused.message.includes('refusing to write'), 'unknown-id message does not refuse');
|
|
663
|
-
assert(fileSha(file) === before, 'unknown-id refusal changed the bytes');
|
|
664
|
-
assert(!fs.existsSync(archiveDirFor(file)), 'unknown-id refusal created an archive dir');
|
|
665
|
-
return 'unknown caller refused, dry-run still planned';
|
|
666
|
-
} finally {
|
|
667
|
-
process.env.DSH_SESSION_ID = saved;
|
|
668
|
-
}
|
|
669
|
-
});
|
|
670
|
-
|
|
671
|
-
runCase('V12', 'allowLive 逃生口:缺 I-KNOW-THIS-CORRUPTS 拒绝,带它才放行', () => {
|
|
672
|
-
const { file } = writeFixture(base, 'tool-escape');
|
|
673
|
-
const before = fileSha(file);
|
|
674
|
-
const cfg = {
|
|
675
|
-
home: path.join(base, 'home'), recentWriteWindowMs: 0,
|
|
676
|
-
currentSessionId: 'session-visible-tool-escape',
|
|
677
|
-
};
|
|
678
|
-
const noEscape = truncateVisibleTool({
|
|
679
|
-
sessionPath: file, dryRun: false, confirm: VISIBLE_CONFIRM_WORD, allowLive: true,
|
|
680
|
-
keepTurns: 5, keepTokens: 1_000_000,
|
|
681
|
-
}, cfg);
|
|
682
|
-
assert(noEscape.ok === false && noEscape.code === LIVE_GUARD_CODES.ESCAPE_CONFIRM_REQUIRED,
|
|
683
|
-
`code ${noEscape.code}`);
|
|
684
|
-
assert(fileSha(file) === before, 'escape refusal changed the bytes');
|
|
685
|
-
|
|
686
|
-
const allowed = truncateVisibleTool({
|
|
687
|
-
sessionPath: file, dryRun: false, confirm: LIVE_ESCAPE_CONFIRM_WORD, allowLive: true,
|
|
688
|
-
keepTurns: 5, keepTokens: 1_000_000,
|
|
689
|
-
}, cfg);
|
|
690
|
-
assert(allowed.ok === true && allowed.status === 'truncated', `escape write ${allowed.status}`);
|
|
691
|
-
assert(fileSha(file) !== before, 'escape write did not change the bytes');
|
|
692
|
-
return 'refused without the escape word; applied with it';
|
|
693
|
-
});
|
|
694
|
-
|
|
695
|
-
runCase('V13', 'truncateTool allowLive 逃生口:缺词/无 allowLive 都拒绝,带词才真正写入', () => {
|
|
696
|
-
// Permanent regression for src/tools.js:691. The log tool's escape path is
|
|
697
|
-
// the one the 0.7.2 fix repaired: before it, the escape word was forwarded
|
|
698
|
-
// to truncateSession() as `confirm`, so the core refused and allowLive
|
|
699
|
-
// could never write. V12 covers only the visible tool; this case fails if
|
|
700
|
-
// line 691 is changed back to `args.confirm`.
|
|
701
|
-
const { file } = writeFixture(base, 'tool-log-escape', { checkpointAt: 17 });
|
|
702
|
-
const before = fileSha(file);
|
|
703
|
-
const cfg = {
|
|
704
|
-
home: path.join(base, 'home'), recentWriteWindowMs: 0,
|
|
705
|
-
currentSessionId: 'session-visible-tool-log-escape',
|
|
706
|
-
};
|
|
707
|
-
// Exercise the explicit config identity chain: with $DSH_SESSION_ID set to
|
|
708
|
-
// the suite runner, the "own session" refusal would not fire.
|
|
709
|
-
const saved = process.env.DSH_SESSION_ID;
|
|
710
|
-
delete process.env.DSH_SESSION_ID;
|
|
711
|
-
try {
|
|
712
|
-
const noEscape = truncateTool({
|
|
713
|
-
sessionPath: file, dryRun: false, confirm: CONFIRM_WORD, allowLive: true, keepEvents: 40,
|
|
714
|
-
}, cfg);
|
|
715
|
-
assert(noEscape.ok === false && noEscape.code === LIVE_GUARD_CODES.ESCAPE_CONFIRM_REQUIRED,
|
|
716
|
-
`allowLive without the escape word -> ${noEscape.ok}/${noEscape.code}`);
|
|
717
|
-
assert(fileSha(file) === before, 'escape-word refusal changed the bytes');
|
|
718
|
-
|
|
719
|
-
const plain = truncateTool({
|
|
720
|
-
sessionPath: file, dryRun: false, confirm: CONFIRM_WORD, keepEvents: 40,
|
|
721
|
-
}, cfg);
|
|
722
|
-
assert(plain.ok === false && plain.code === LIVE_GUARD_CODES.TARGET_IS_LIVE_SESSION,
|
|
723
|
-
`own live session without allowLive -> ${plain.ok}/${plain.code}`);
|
|
724
|
-
assert(fileSha(file) === before, 'live-session refusal changed the bytes');
|
|
725
|
-
|
|
726
|
-
const allowed = truncateTool({
|
|
727
|
-
sessionPath: file, dryRun: false, confirm: LIVE_ESCAPE_CONFIRM_WORD, allowLive: true, keepEvents: 40,
|
|
728
|
-
}, cfg);
|
|
729
|
-
assert(allowed.ok === true, `escape write refused: ${allowed.code} ${allowed.message}`);
|
|
730
|
-
assert(allowed.status === 'truncated', `escape write status ${allowed.status}`);
|
|
731
|
-
assert(allowed.dryRun === false, 'escape write did not report a real write');
|
|
732
|
-
assert(allowed.afterEvents < allowed.beforeEvents,
|
|
733
|
-
`escape write did not shrink the log (${allowed.beforeEvents} -> ${allowed.afterEvents})`);
|
|
734
|
-
assert(fileSha(file) !== before, 'escape write did not change the bytes');
|
|
735
|
-
assert(allowed.backupFile && fs.existsSync(allowed.backupFile), 'escape write left no backup');
|
|
736
|
-
return `escape word writes through the core (${allowed.beforeEvents} -> ${allowed.afterEvents} events)`;
|
|
737
|
-
} finally {
|
|
738
|
-
process.env.DSH_SESSION_ID = saved;
|
|
739
|
-
}
|
|
740
|
-
});
|
|
741
|
-
|
|
742
|
-
runCase('V10', 'visible 读回校验失败:rename 成功但读回字节不符时回滚并报 POST_VERIFY', () => {
|
|
743
|
-
const { file } = writeFixture(base, 'readback');
|
|
744
|
-
const beforeBuf = fs.readFileSync(file);
|
|
745
|
-
const beforeSha = sha256(beforeBuf);
|
|
746
|
-
const tool = TOOLS.find((entry) => entry.name === 'session_truncate_visible');
|
|
747
|
-
assert(tool && typeof tool.invoke === 'function', 'session_truncate_visible invoke is missing');
|
|
748
|
-
|
|
749
|
-
// The injected seam only corrupts the bytes read back after the rename; the
|
|
750
|
-
// file on disk keeps the truncated bytes, so this exercises readbackVerify
|
|
751
|
-
// instead of failing earlier at the rename.
|
|
752
|
-
const out = tool.invoke({
|
|
753
|
-
sessionPath: file, dryRun: false, confirm: VISIBLE_CONFIRM_WORD,
|
|
754
|
-
keepTurns: 5, keepTokens: 1_000_000,
|
|
755
|
-
}, {
|
|
756
|
-
home: path.join(base, 'home'),
|
|
757
|
-
recentWriteWindowMs: 0,
|
|
758
|
-
currentSessionId: 'session-suite-runner',
|
|
759
|
-
faultAt: 'after-rename-corrupt-readback',
|
|
760
|
-
});
|
|
761
|
-
|
|
762
|
-
assert(out.ok === false, `tool reported ok=${out.ok}`);
|
|
763
|
-
assert(out.status === 'error', `tool status ${out.status}`);
|
|
764
|
-
assert(out.code === ERROR_CODES.POST_VERIFY, `tool code ${out.code}`);
|
|
765
|
-
assert(out.errorCode === ERROR_CODES.POST_VERIFY, `errorCode ${out.errorCode}`);
|
|
766
|
-
assert(out.restored === true, 'tool result did not report a restore');
|
|
767
|
-
assert(out.backupPath && fs.existsSync(out.backupPath), 'backup file is missing after rollback');
|
|
768
|
-
assert(sha256(fs.readFileSync(out.backupPath)) === beforeSha, 'backup bytes differ from the original');
|
|
769
|
-
assert(out.archivePath && fs.existsSync(out.archivePath), 'archive file is missing');
|
|
770
|
-
const afterBuf = fs.readFileSync(file);
|
|
771
|
-
assert(afterBuf.length === beforeBuf.length, `main file size ${afterBuf.length} != ${beforeBuf.length}`);
|
|
772
|
-
assert(sha256(afterBuf) === beforeSha, 'main file was not rolled back byte-for-byte');
|
|
773
|
-
assert(!fs.existsSync(inflightPathFor(file)), 'inflight record survived the failed write');
|
|
774
|
-
const leftovers = fs.readdirSync(path.dirname(file)).filter((name) => name.includes('.truncate-visible.tmp-'));
|
|
775
|
-
assert(leftovers.length === 0, `tmp leftovers: ${leftovers.join(', ')}`);
|
|
776
|
-
return `POST_VERIFY, restored ${beforeSha.slice(0, 12)}`;
|
|
777
|
-
});
|
|
778
|
-
|
|
779
|
-
runCase('V14', '截断产物里每个 turn/end 都有非空字符串 data.reason.kind', () => {
|
|
780
|
-
const { file } = writeFixture(base, 'reason');
|
|
781
|
-
const result = truncateVisibleSession(file, {
|
|
782
|
-
dryRun: false, confirm: VISIBLE_CONFIRM_WORD,
|
|
783
|
-
keepTurns: 5, keepTokens: 1_000_000, recentWriteWindowMs: 0,
|
|
784
|
-
});
|
|
785
|
-
assert(result.applied === true, 'the truncation did not land');
|
|
786
|
-
const parsed = readParsed(file);
|
|
787
|
-
const ends = parsed.events.filter((event) => event.type === 'turn/end');
|
|
788
|
-
assert(ends.length > 0, 'the truncated log contains no turn/end at all');
|
|
789
|
-
for (const event of ends) {
|
|
790
|
-
const reason = event.data?.reason;
|
|
791
|
-
assert(reason !== null && typeof reason === 'object' && !Array.isArray(reason),
|
|
792
|
-
`turn/end seq ${event.seq} (turn ${event.data?.turn}) has no data.reason object: ${JSON.stringify(reason)}`);
|
|
793
|
-
assert(typeof reason.kind === 'string' && reason.kind.trim() !== '',
|
|
794
|
-
`turn/end seq ${event.seq} (turn ${event.data?.turn}) has no non-empty string data.reason.kind: ${JSON.stringify(reason.kind)}`);
|
|
795
|
-
}
|
|
796
|
-
// The synthetic head is the one turn/end the plugin writes itself; pin its
|
|
797
|
-
// kind so a future refactor cannot "fix" the crash with a host kind that
|
|
798
|
-
// would misreport why that turn ended.
|
|
799
|
-
const headEnd = parsed.events[4];
|
|
800
|
-
assert(headEnd.type === 'turn/end', `event 4 is ${headEnd?.type}, not the synthetic turn/end`);
|
|
801
|
-
assert(headEnd.data.reason.kind === 'truncated',
|
|
802
|
-
`synthetic head reason: ${JSON.stringify(headEnd.data.reason)}`);
|
|
803
|
-
return `${ends.length} turn/end events, synthetic head kind "${headEnd.data.reason.kind}"`;
|
|
804
|
-
});
|
|
805
|
-
|
|
806
|
-
runCase('V15', '严格消费者:逐个 turn/end 直接读 event.data.reason.kind 不抛异常', () => {
|
|
807
|
-
const { file } = writeFixture(base, 'strict-consumer');
|
|
808
|
-
const result = truncateVisibleSession(file, {
|
|
809
|
-
dryRun: false, confirm: VISIBLE_CONFIRM_WORD,
|
|
810
|
-
keepTurns: 5, keepTokens: 1_000_000, recentWriteWindowMs: 0,
|
|
811
|
-
});
|
|
812
|
-
assert(result.applied === true, 'the truncation did not land');
|
|
813
|
-
const parsed = readParsed(file);
|
|
814
|
-
const kinds = [];
|
|
815
|
-
for (const event of parsed.events) {
|
|
816
|
-
if (event.type !== 'turn/end') continue;
|
|
817
|
-
// No optional chaining on purpose: this is the exact third-party access
|
|
818
|
-
// that threw before the synthetic event carried data.reason.
|
|
819
|
-
const kind = event.data.reason.kind;
|
|
820
|
-
assert(typeof kind === 'string' && kind !== '',
|
|
821
|
-
`turn/end seq ${event.seq} exposed kind ${JSON.stringify(kind)}`);
|
|
822
|
-
kinds.push(kind);
|
|
823
|
-
}
|
|
824
|
-
const total = parsed.events.filter((event) => event.type === 'turn/end').length;
|
|
825
|
-
assert(kinds.length > 0, 'the consumer never saw a turn/end');
|
|
826
|
-
assert(kinds.length === total, `consumer read ${kinds.length} of ${total} turn/end events`);
|
|
827
|
-
return `consumer read ${kinds.length} reasons without throwing: ${[...new Set(kinds)].join(', ')}`;
|
|
828
|
-
});
|
|
829
|
-
|
|
830
|
-
// -------------------------------------------------------------------------
|
|
831
|
-
// V16–V18: 0.8.0-rc.11 — a bounded first-user carry, a post-cut token
|
|
832
|
-
// budget that includes the synthetic cards, and a boundary retry that drops
|
|
833
|
-
// one more turn instead of throwing VISIBLE_NO_BOUNDARY at the caller.
|
|
834
|
-
// -------------------------------------------------------------------------
|
|
835
|
-
|
|
836
|
-
runCase('V16', '15,524 字符首条消息 + keepTokens 8000:复刻卡截断后预算达标', () => {
|
|
837
|
-
const firstUserChars = 15_524;
|
|
838
|
-
const { file } = writePatchedFixture('long-first-user', { turns: 20 }, (events) => {
|
|
839
|
-
const prompt = events.find((event) => event.type === 'system/message');
|
|
840
|
-
prompt.data.message.content[0].text = 'S'.repeat(5_952); // keeps the head's weight realistic
|
|
841
|
-
const firstUser = events.find((event) =>
|
|
842
|
-
event.type === 'user/message' && event.data?.source?.kind === 'user');
|
|
843
|
-
firstUser.data.content[0].text = 'A'.repeat(firstUserChars);
|
|
844
|
-
for (const event of events) {
|
|
845
|
-
if (event.type !== 'assistant/message') continue;
|
|
846
|
-
const part = event.data.message.content[0];
|
|
847
|
-
if (part.type === 'text') part.text = part.text.padEnd(2_000, 'x');
|
|
848
|
-
}
|
|
849
|
-
});
|
|
850
|
-
const result = truncateVisibleSession(file, { dryRun: true, keepTurns: 6, keepTokens: 8_000 });
|
|
851
|
-
assert(result.needed === true, `no cut was planned: ${result.reason ?? result.message}`);
|
|
852
|
-
assert(result.feasible !== false, 'V16 must be feasible');
|
|
853
|
-
assert(result.budget.carryTokens > 0, 'the carried card is not counted in the budget');
|
|
854
|
-
assert(result.after.tokens <= 8_000,
|
|
855
|
-
`after ${result.after.tokens} tokens is still over keepTokens 8000 -> an immediate retrigger`);
|
|
856
|
-
assert(result.firstUserCarry.capped === true, 'the first-user carry was not capped');
|
|
857
|
-
assert(result.firstUserCarry.originalChars === firstUserChars,
|
|
858
|
-
`originalChars ${result.firstUserCarry.originalChars}, expected ${firstUserChars}`);
|
|
859
|
-
assert(result.firstUserCarry.keptChars <= 4_000, `kept ${result.firstUserCarry.keptChars} chars`);
|
|
860
|
-
assert(result.firstUserCarry.text.endsWith(`原文见 ${result.archivePath}]`),
|
|
861
|
-
`carry text lost the archive pointer: …${result.firstUserCarry.text.slice(-80)}`);
|
|
862
|
-
assert(result.message.includes('已截断') && result.message.includes('预算'),
|
|
863
|
-
'report does not show the cap / budget lines');
|
|
864
|
-
// Same log, same cut request, but no cap: the planner can only fit the
|
|
865
|
-
// budget by dropping extra turns it was asked to keep. That difference is
|
|
866
|
-
// exactly why the cap is not cosmetic.
|
|
867
|
-
const uncapped = planVisibleTruncation(readParsed(file), {
|
|
868
|
-
keepTurns: 6, keepTokens: 8_000, firstUserCapChars: 10_000_000,
|
|
869
|
-
});
|
|
870
|
-
assert(uncapped.budget.carryTokens > 3_000,
|
|
871
|
-
`uncapped carry ${uncapped.budget.carryTokens} tokens; fixture does not reproduce the VM card`);
|
|
872
|
-
assert(uncapped.budget.trimmedTurns >= 1,
|
|
873
|
-
'uncapped plan fits without trimming — the fixture is too small to prove the fix');
|
|
874
|
-
assert(uncapped.budget.afterTokens > result.budget.afterTokens,
|
|
875
|
-
'capping did not reduce the projected tokens');
|
|
876
|
-
return `${firstUserChars} chars -> ${result.firstUserCarry.keptChars}, after ${result.budget.afterTokens} <= 8000`;
|
|
877
|
-
});
|
|
878
|
-
|
|
879
|
-
// A kept event that points into the dropped prefix is unsalvageable; an
|
|
880
|
-
// event that points at *it* only becomes unsalvageable in the next pass.
|
|
881
|
-
// rc.10 rebuilt the candidate set from base each pass, so those two events
|
|
882
|
-
// kept taking each other's place and the loop never converged (the VM's
|
|
883
|
-
// "22 candidates, 21 survived").
|
|
884
|
-
function writeBoundaryRefsFixture(name, cutTurn = 15) {
|
|
885
|
-
return writePatchedFixture(name, { turns: 20 }, (events) => {
|
|
886
|
-
// keepTurns 6 over 20 turns cuts at turn 15 by default.
|
|
887
|
-
const droppedCall = events.find((event) => event.type === 'tool/call' && event.data.turn === 2);
|
|
888
|
-
const poisoned = events.find((event) =>
|
|
889
|
-
event.type === 'assistant/message'
|
|
890
|
-
&& event.data.turn === cutTurn
|
|
891
|
-
&& event.data.message.content[0].type === 'text');
|
|
892
|
-
poisoned.data.messageSeqs = [droppedCall.seq]; // invalid on its own
|
|
893
|
-
const dependent = events.find((event) =>
|
|
894
|
-
event.type === 'tool/result' && event.data.turn === cutTurn);
|
|
895
|
-
dependent.data.sourceEventSeq = poisoned.seq; // only invalid once poisoned is gone
|
|
896
|
-
});
|
|
897
|
-
}
|
|
898
|
-
|
|
899
|
-
runCase('V17', '边界不稳样本(引用被删前缀的链): dryrun 收敛、不抛 NO_BOUNDARY', () => {
|
|
900
|
-
const { file } = writeBoundaryRefsFixture('boundary-chain');
|
|
901
|
-
const before = fileSha(file);
|
|
902
|
-
const parsed = readParsed(file);
|
|
903
|
-
const result = truncateVisibleSession(file, { dryRun: true, keepTurns: 6, keepTokens: 1_000_000 });
|
|
904
|
-
assert(result.needed === true, `no cut: ${result.reason ?? ''}`);
|
|
905
|
-
assert(result.feasible !== false, 'the boundary chain reported infeasible');
|
|
906
|
-
assert(result.attempts.length === 1,
|
|
907
|
-
`one pass should suffice, got ${result.attempts.length} attempts`);
|
|
908
|
-
assert(result.attempts[0].code === null, `attempt carried code ${result.attempts[0].code}`);
|
|
909
|
-
// Both the directly-poisoned event and its dependent are gone: the built
|
|
910
|
-
// log must not reference a seq that survived the cut. The build itself
|
|
911
|
-
// validates this (remapReferences returns false for a dangling seq), so
|
|
912
|
-
// reaching `planned` at all is the contract; assert the sizes too.
|
|
913
|
-
assert(result.after.events < result.before.events,
|
|
914
|
-
`retained ${result.after.events} of ${result.before.events} events`);
|
|
915
|
-
assert(fileSha(file) === before, 'dry-run rewrote the log');
|
|
916
|
-
assert(result.message.includes('预演'), 'report is not a dry-run report');
|
|
917
|
-
return `converged on attempt 1 (${result.before.events} -> ${result.after.events} events)`;
|
|
918
|
-
});
|
|
919
|
-
|
|
920
|
-
runCase('V18', '边界重试:第 1 次 NO_BOUNDARY,再删 1 轮后成功;预算死路则 feasible:false', () => {
|
|
921
|
-
const { file } = writeBoundaryRefsFixture('boundary-retry');
|
|
922
|
-
// stabilizePasses:1 makes the first cut fail on purpose, which is the
|
|
923
|
-
// same decision the planner takes when its real pass budget runs out.
|
|
924
|
-
const retried = truncateVisibleSession(file, {
|
|
925
|
-
dryRun: true, keepTurns: 6, keepTokens: 1_000_000, stabilizePasses: 1, boundaryRetries: 2,
|
|
926
|
-
});
|
|
927
|
-
assert(retried.needed === true, 'the retry path did not produce a cut');
|
|
928
|
-
assert(retried.feasible === true, 'the retry path reported infeasible');
|
|
929
|
-
assert(retried.attempts.length === 2,
|
|
930
|
-
`expected 2 attempts, got ${retried.attempts.length}`);
|
|
931
|
-
assert(retried.attempts[0].code === 'VISIBLE_NO_BOUNDARY',
|
|
932
|
-
`first attempt code ${retried.attempts[0].code}, expected VISIBLE_NO_BOUNDARY`);
|
|
933
|
-
assert(retried.attempts[1].code === null, `second attempt code ${retried.attempts[1].code}`);
|
|
934
|
-
assert(retried.cut.turn === retried.attempts[1].cutTurn,
|
|
935
|
-
'successful attempt does not describe the applied cut');
|
|
936
|
-
assert(retried.cut.turn > retried.attempts[0].cutTurn,
|
|
937
|
-
'the retry did not drop an extra turn');
|
|
938
|
-
|
|
939
|
-
// Dead end: the protected head + capped cards alone exceed the budget, so
|
|
940
|
-
// every attempt is infeasible. That must be a structured result, never a
|
|
941
|
-
// throw, and never a silent "noop".
|
|
942
|
-
const headHeavy = writePatchedFixture('boundary-infeasible', { turns: 20 }, (events) => {
|
|
943
|
-
const prompt = events.find((event) => event.type === 'system/message');
|
|
944
|
-
prompt.data.message.content[0].text = 'H'.repeat(8_000);
|
|
945
|
-
});
|
|
946
|
-
const before = fileSha(headHeavy.file);
|
|
947
|
-
const dead = truncateVisibleSession(headHeavy.file, {
|
|
948
|
-
dryRun: true, keepTurns: 6, keepTokens: 100, boundaryRetries: 2,
|
|
949
|
-
});
|
|
950
|
-
assert(dead.ok === false, 'infeasible result claims ok');
|
|
951
|
-
assert(dead.feasible === false, 'infeasible result claims feasible');
|
|
952
|
-
assert(dead.status === 'infeasible', `status ${dead.status}`);
|
|
953
|
-
assert(dead.code === ERROR_CODES.TOKEN_BUDGET, `code ${dead.code}`);
|
|
954
|
-
assert(Array.isArray(dead.attempts) && dead.attempts.length >= 1,
|
|
955
|
-
'the dead end recorded no attempt at all');
|
|
956
|
-
assert(dead.attempts.every((attempt) => attempt.code === ERROR_CODES.TOKEN_BUDGET),
|
|
957
|
-
'a dead-end attempt does not say why it was infeasible');
|
|
958
|
-
assert(dead.attempts.every((attempt) => typeof attempt.cutTurn === 'number'),
|
|
959
|
-
'an attempt does not carry the keepTurns/cutTurn it tried');
|
|
960
|
-
assert(dead.message.includes('无法截断'), 'report does not say 无法截断');
|
|
961
|
-
assert(fileSha(headHeavy.file) === before, 'infeasible dry-run changed the log');
|
|
962
|
-
return `retry ${retried.attempts[0].cutTurn}->${retried.attempts[1].cutTurn}, dead end ${dead.attempts.length} attempt(s)`;
|
|
963
|
-
});
|
|
964
|
-
|
|
965
|
-
runCase('V19', '边界重试跑满 3 次:坏事件在下一轮里,逐轮多删才收敛', () => {
|
|
966
|
-
// The poisoned pair sits in turn 16, so the first retry (cut turn 16) still
|
|
967
|
-
// keeps it and only the second retry (cut turn 17) drops the whole turn.
|
|
968
|
-
// This pins "drop one more turn per attempt", not "retry once and give up".
|
|
969
|
-
const { file } = writeBoundaryRefsFixture('boundary-retry-2', 16);
|
|
970
|
-
const result = truncateVisibleSession(file, {
|
|
971
|
-
dryRun: true, keepTurns: 6, keepTokens: 1_000_000, stabilizePasses: 1, boundaryRetries: 3,
|
|
972
|
-
});
|
|
973
|
-
assert(result.feasible === true, `feasible ${result.feasible} (${result.code}: ${result.reason})`);
|
|
974
|
-
assert(result.attempts.length === 3, `expected 3 attempts, got ${result.attempts.length}`);
|
|
975
|
-
assert(result.attempts[0].code === 'VISIBLE_NO_BOUNDARY', `attempt 0 ${result.attempts[0].code}`);
|
|
976
|
-
assert(result.attempts[1].code === 'VISIBLE_NO_BOUNDARY', `attempt 1 ${result.attempts[1].code}`);
|
|
977
|
-
assert(result.attempts[2].code === null, `attempt 2 ${result.attempts[2].code}`);
|
|
978
|
-
assert(result.cut.turn === 17, `cut turn ${result.cut.turn}, expected 17`);
|
|
979
|
-
return `3 attempts, cut turn ${result.cut.turn}`;
|
|
980
|
-
});
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
// N4 keeps the real log it used so N5 can diff against real text too.
|
|
984
|
-
let realLogFile = null;
|
|
985
|
-
|
|
986
|
-
runCase('N1', 'base64 PNG 长串(≥6000 字符、多斜杠)单次路径抽取 <100ms', () => {
|
|
987
|
-
const payload = 'iVBORw0KGgo' + '/'.repeat(400) + 'A'.repeat(6_000) + '/'.repeat(400) + '===';
|
|
988
|
-
const text = ``;
|
|
989
|
-
assert(text.length >= 6_000, `payload is only ${text.length} chars`);
|
|
990
|
-
const started = process.hrtime.bigint();
|
|
991
|
-
const paths = extractPaths([{ data: { text, note: 'n1' } }], 8);
|
|
992
|
-
const elapsedMs = Number(process.hrtime.bigint() - started) / 1e6;
|
|
993
|
-
assert(paths.length === 0, `base64 payload yielded paths ${JSON.stringify(paths)}`);
|
|
994
|
-
assert(elapsedMs < 100, `single extraction took ${elapsedMs.toFixed(1)}ms (limit 100ms)`);
|
|
995
|
-
return `${text.length} chars, 0 paths, ${elapsedMs.toFixed(2)}ms`;
|
|
996
|
-
});
|
|
997
|
-
|
|
998
|
-
runCase('N2', '转义 Windows 路径串:归一化、去重与计数正确', () => {
|
|
999
|
-
const escaped = String.raw`D:\\Users\\codeuser\\repos\\proj\\engine2.py`;
|
|
1000
|
-
const text = `cd ${escaped} && node ${escaped}`;
|
|
1001
|
-
const started = process.hrtime.bigint();
|
|
1002
|
-
const paths = extractPaths([{ data: { text } }], 8);
|
|
1003
|
-
const elapsedMs = Number(process.hrtime.bigint() - started) / 1e6;
|
|
1004
|
-
assert(isDeepStrictEqual(paths, ['D:/Users/codeuser/repos/proj/engine2.py']),
|
|
1005
|
-
`escaped path extracted as ${JSON.stringify(paths)}`);
|
|
1006
|
-
assert(elapsedMs < 100, `single extraction took ${elapsedMs.toFixed(1)}ms (limit 100ms)`);
|
|
1007
|
-
// Same path, different case and separator spelling: one entry, three hits,
|
|
1008
|
-
// and the surviving spelling is the last one seen (0.7.6 behaviour).
|
|
1009
|
-
const mixed = extractPaths([
|
|
1010
|
-
{ data: { text: 'C:\\Work\\A.js and C:/WORK/A.js and c:\\work\\a.js' } },
|
|
1011
|
-
{ data: { text: escaped } },
|
|
1012
|
-
], 8);
|
|
1013
|
-
assert(mixed.length === 2, `expected 2 distinct paths, got ${JSON.stringify(mixed)}`);
|
|
1014
|
-
assert(mixed[0].toLowerCase() === 'c:/work/a.js', `most frequent path is ${mixed[0]}`);
|
|
1015
|
-
assert(mixed[1].toLowerCase() === 'd:/users/codeuser/repos/proj/engine2.py',
|
|
1016
|
-
`second path is ${mixed[1]}`);
|
|
1017
|
-
return `escaped path → ${paths[0]}, ${mixed.length} distinct across spellings`;
|
|
1018
|
-
});
|
|
1019
|
-
|
|
1020
|
-
runCase('N3', '/a 重复 30 次 + /zzz:<100ms 且结果正确', () => {
|
|
1021
|
-
const run = '/a'.repeat(30);
|
|
1022
|
-
const misses = run + '/zzz';
|
|
1023
|
-
const hits = run + '/zzz.js';
|
|
1024
|
-
let started = process.hrtime.bigint();
|
|
1025
|
-
const none = matchPathStrings(misses);
|
|
1026
|
-
const missMs = Number(process.hrtime.bigint() - started) / 1e6;
|
|
1027
|
-
started = process.hrtime.bigint();
|
|
1028
|
-
const found = matchPathStrings(hits);
|
|
1029
|
-
const hitMs = Number(process.hrtime.bigint() - started) / 1e6;
|
|
1030
|
-
assert(none.length === 0, `slash run yielded ${JSON.stringify(none)}`);
|
|
1031
|
-
assert(isDeepStrictEqual(found, [hits]), `slash run with extension yielded ${JSON.stringify(found)}`);
|
|
1032
|
-
assert(missMs < 100, `no-match scan took ${missMs.toFixed(2)}ms (limit 100ms)`);
|
|
1033
|
-
assert(hitMs < 100, `match scan took ${hitMs.toFixed(2)}ms (limit 100ms)`);
|
|
1034
|
-
const extractionMs = (() => {
|
|
1035
|
-
const t0 = process.hrtime.bigint();
|
|
1036
|
-
extractPaths([{ data: { text: misses } }], 8);
|
|
1037
|
-
return Number(process.hrtime.bigint() - t0) / 1e6;
|
|
1038
|
-
})();
|
|
1039
|
-
assert(extractionMs < 100, `extractPaths took ${extractionMs.toFixed(2)}ms (limit 100ms)`);
|
|
1040
|
-
return `no-match ${missMs.toFixed(2)}ms, match ${hitMs.toFixed(2)}ms, extract ${extractionMs.toFixed(2)}ms`;
|
|
1041
|
-
});
|
|
1042
|
-
|
|
1043
|
-
runCase('N4', '真实日志(46,834 事件,只读副本)带归档卡端到端截断 <10s', () => {
|
|
1044
|
-
const root = path.join(base, 'real', 'sessions', 'scope-real', 'session-real-copy');
|
|
1045
|
-
fs.mkdirSync(root, { recursive: true });
|
|
1046
|
-
const target = path.join(root, 'session.v4.jsonl.zstd');
|
|
1047
|
-
const real = findRealSessionLog();
|
|
1048
|
-
let source;
|
|
1049
|
-
if (real) {
|
|
1050
|
-
fs.copyFileSync(real.file, target);
|
|
1051
|
-
realLogFile = real.file;
|
|
1052
|
-
source = `real log ${real.size} bytes`;
|
|
1053
|
-
} else {
|
|
1054
|
-
// Fallback for machines without a big real log: the same shape (46,8xx
|
|
1055
|
-
// events over 5,200 turns) with the pathological payloads injected.
|
|
1056
|
-
const { header, events } = buildFixture({ id: 'session-visible-real-fallback', turns: 5_200 });
|
|
1057
|
-
const base64 = 'iVBORw0KGgo' + '/'.repeat(400) + 'A'.repeat(6_000) + '/'.repeat(400) + '===';
|
|
1058
|
-
const slashRun = '/a'.repeat(30) + '/zzz';
|
|
1059
|
-
let injected = 0;
|
|
1060
|
-
for (let i = 120; i < events.length - 120; i += 37) {
|
|
1061
|
-
const content = events[i]?.data?.message?.content;
|
|
1062
|
-
if (!Array.isArray(content) || !content[0] || events[i].type !== 'tool/result') continue;
|
|
1063
|
-
content[0].text = [
|
|
1064
|
-
`data:image/png;base64,${base64}`,
|
|
1065
|
-
String.raw`cwd C:\\work\\proj\\engine2.py`,
|
|
1066
|
-
slashRun,
|
|
1067
|
-
].join('\n');
|
|
1068
|
-
injected += 1;
|
|
1069
|
-
}
|
|
1070
|
-
assert(injected > 0, 'the fallback log injected no pathological payload');
|
|
1071
|
-
fs.writeFileSync(target, encodeSession(header, events));
|
|
1072
|
-
source = `synthetic fallback (${injected} pathological payloads, no real log found)`;
|
|
1073
|
-
}
|
|
1074
|
-
|
|
1075
|
-
const started = process.hrtime.bigint();
|
|
1076
|
-
const result = truncateVisibleSession(target, {
|
|
1077
|
-
dryRun: false, confirm: VISIBLE_CONFIRM_WORD,
|
|
1078
|
-
keepTurns: 12, keepTokens: 80_000, recentWriteWindowMs: 0,
|
|
1079
|
-
});
|
|
1080
|
-
const elapsedMs = Number(process.hrtime.bigint() - started) / 1e6;
|
|
1081
|
-
assert(result.applied === true, 'the end-to-end truncation did not land');
|
|
1082
|
-
assert(result.archiveCard?.inserted === true, 'the archive card was not inserted');
|
|
1083
|
-
const card = result.archiveCard.text;
|
|
1084
|
-
assert(card.includes('涉及文件'), `the card has no path section:\n${card}`);
|
|
1085
|
-
assert(!/\/{20,}/.test(card), 'the card carries a raw slash run');
|
|
1086
|
-
assert(result.before.events >= 40_000, `only ${result.before.events} events — expected a 46.8k-event log`);
|
|
1087
|
-
assert(elapsedMs < 10_000, `end-to-end truncation took ${elapsedMs.toFixed(0)}ms (limit 10,000ms)`);
|
|
1088
|
-
const after = parseSession(fs.readFileSync(target));
|
|
1089
|
-
assertContiguous(after.events);
|
|
1090
|
-
assert(fs.existsSync(result.archivePath), 'the archive file is missing');
|
|
1091
|
-
assert(fs.existsSync(result.backupPath), 'the backup file is missing');
|
|
1092
|
-
return `${source}, ${result.before.events} events, card in ${elapsedMs.toFixed(0)}ms`;
|
|
1093
|
-
});
|
|
1094
|
-
|
|
1095
|
-
runCase('N5', '旧新实现等价性:小样本语料逐串一致', () => {
|
|
1096
|
-
const corpus = [...CURATED_PATH_SAMPLES, ...generatePathCorpus(3_000)];
|
|
1097
|
-
let compared = 0;
|
|
1098
|
-
let withPaths = 0;
|
|
1099
|
-
for (const text of corpus) {
|
|
1100
|
-
const before = legacyMatchStrings(text);
|
|
1101
|
-
const after = matchPathStrings(text);
|
|
1102
|
-
assert(before.length === after.length,
|
|
1103
|
-
`match count differs for ${JSON.stringify(text.slice(0, 120))}: old ${before.length} new ${after.length}`);
|
|
1104
|
-
for (let i = 0; i < before.length; i += 1) {
|
|
1105
|
-
assert(before[i] === after[i],
|
|
1106
|
-
`match ${i} differs for ${JSON.stringify(text.slice(0, 120))}: ${JSON.stringify(before[i])} != ${JSON.stringify(after[i])}`);
|
|
1107
|
-
}
|
|
1108
|
-
compared += 1;
|
|
1109
|
-
if (before.length) withPaths += 1;
|
|
1110
|
-
}
|
|
1111
|
-
const events = corpus.filter((_, index) => index % 3 === 0).map((text, index) => ({ data: { text, index } }));
|
|
1112
|
-
assert(isDeepStrictEqual(legacyExtractPaths(events, 8), extractPaths(events, 8)),
|
|
1113
|
-
'the extracted path set/order differs from the 0.7.6 pipeline');
|
|
1114
|
-
|
|
1115
|
-
// A bounded slice of the real log N4 used, if there is one: pathological
|
|
1116
|
-
// strings are excluded because the old pattern cannot finish them at all.
|
|
1117
|
-
let realDetail = '';
|
|
1118
|
-
if (realLogFile) {
|
|
1119
|
-
const parsed = parseSession(fs.readFileSync(realLogFile));
|
|
1120
|
-
const limit = 200_000;
|
|
1121
|
-
let seen = 0;
|
|
1122
|
-
let skipped = 0;
|
|
1123
|
-
for (const event of parsed.events) {
|
|
1124
|
-
for (const text of walkStrings(event.data)) {
|
|
1125
|
-
if (separatorCount(text, 11) > 10 || text.length > 4_000) { skipped += 1; continue; }
|
|
1126
|
-
if (seen >= limit) break;
|
|
1127
|
-
const before = legacyMatchStrings(text);
|
|
1128
|
-
const after = matchPathStrings(text);
|
|
1129
|
-
assert(before.length === after.length,
|
|
1130
|
-
`real-log match count differs for ${JSON.stringify(text.slice(0, 120))}`);
|
|
1131
|
-
for (let i = 0; i < before.length; i += 1) {
|
|
1132
|
-
assert(before[i] === after[i],
|
|
1133
|
-
`real-log match ${i} differs for ${JSON.stringify(text.slice(0, 120))}`);
|
|
1134
|
-
}
|
|
1135
|
-
seen += 1;
|
|
1136
|
-
}
|
|
1137
|
-
if (seen >= limit) break;
|
|
1138
|
-
}
|
|
1139
|
-
compared += seen;
|
|
1140
|
-
realDetail = `, +${seen} real-log strings (${skipped} pathological skipped)`;
|
|
1141
|
-
}
|
|
1142
|
-
return `${compared} strings identical (${withPaths} with paths)${realDetail}`;
|
|
1143
|
-
});
|
|
1144
|
-
}
|
|
1145
|
-
|
|
1146
|
-
export const VISIBLE_SUITE_CASES = [
|
|
1147
|
-
'V1', 'V2', 'V3', 'V4', 'V5', 'V6', 'V7', 'V8', 'V9', 'V10', 'V11', 'V12', 'V13', 'V14', 'V15',
|
|
1148
|
-
'V16', 'V17', 'V18', 'V19',
|
|
1149
|
-
'N1', 'N2', 'N3', 'N4', 'N5',
|
|
1150
|
-
];
|