@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.
Files changed (288) hide show
  1. package/CHANGELOG.md +69 -1539
  2. package/LICENSE +1 -1
  3. package/QUICKSTART.md +33 -12
  4. package/README.en.md +17 -7
  5. package/README.md +29 -10
  6. package/SPEC.md +5 -5
  7. package/cordis.patch.yml +17 -12
  8. package/docs/ANSWER-GUARD.md +92 -0
  9. package/docs/ARCHITECTURE.md +3 -3
  10. package/docs/AUTO-RECALL-WIRING.md +1 -1
  11. package/docs/AUTO-RECALL.md +15 -9
  12. package/docs/CONFIG.md +143 -37
  13. package/docs/ERRORS.md +17 -5
  14. package/docs/FAQ.md +7 -7
  15. package/docs/FEATURES.md +66 -29
  16. package/docs/MIGRATION-1.6.0.md +2 -2
  17. package/docs/OPERATIONS.md +6 -6
  18. package/docs/PANEL-INTEGRATION.md +6 -0
  19. package/docs/PRIVACY.md +88 -0
  20. package/docs/QUICKSTART.md +5 -5
  21. package/docs/README.en.md +3 -2
  22. package/docs/RESIDENT-WATCHER.md +1 -1
  23. package/docs/SESSION-WATCH.md +6 -6
  24. package/docs/TROUBLESHOOTING.md +4 -4
  25. package/package.json +42 -117
  26. package/runbook.md +2 -2
  27. package/scripts/backfill-auto-cards.mjs +98 -0
  28. package/scripts/install-surgery-task.ps1 +5 -2
  29. package/scripts/lib/session-watch-fixture.mjs +1 -1
  30. package/scripts/longlive-doctor.mjs +6 -0
  31. package/scripts/migrate-180.mjs +163 -0
  32. package/scripts/recall-index-build.mjs +128 -0
  33. package/scripts/session-watch-drill.mjs +1 -1
  34. package/scripts/surgery-run.cmd +1 -1
  35. package/scripts/unattended-surgery.ps1 +5 -2
  36. package/scripts/verify-card-anchors.mjs +138 -0
  37. package/src/actions/audit.js +125 -0
  38. package/src/actions/evidence.js +122 -0
  39. package/src/actions/fs.js +162 -0
  40. package/src/activity/index.js +129 -18
  41. package/src/activity/model.js +11 -1
  42. package/src/activity/store.js +22 -3
  43. package/src/activity/thinking.js +176 -0
  44. package/src/adapters/constants.js +11 -0
  45. package/src/adapters/engram/data/aliases.json +51 -0
  46. package/src/adapters/engram/data/policy.json +8 -0
  47. package/src/adapters/engram/data/routing-rules.json +546 -0
  48. package/src/adapters/engram/index.js +235 -0
  49. package/src/adapters/registry.js +315 -0
  50. package/src/answer/audit.js +193 -0
  51. package/src/answer/evidence.js +30 -0
  52. package/src/answer/guard.js +1370 -0
  53. package/src/answer/index.js +1067 -0
  54. package/src/answer/query.js +111 -0
  55. package/src/answer/second-hop.mjs +101 -0
  56. package/src/auto-truncate.js +1 -1
  57. package/src/config.js +145 -48
  58. package/src/deps.js +6 -4
  59. package/src/features.js +158 -8
  60. package/src/identity/index.js +13 -5
  61. package/src/identity/inject-position.js +2 -2
  62. package/src/index.js +97 -7
  63. package/src/lifecycle/gap-clocks.js +328 -0
  64. package/src/lifecycle/index.js +269 -0
  65. package/src/memory/activity-capture.js +229 -0
  66. package/src/memory/anchors.js +194 -0
  67. package/src/memory/audit-records.js +222 -0
  68. package/src/memory/auto-cards.js +401 -0
  69. package/src/memory/capture.js +442 -0
  70. package/src/memory/card-anchors.js +203 -0
  71. package/src/memory/conflicts.js +106 -0
  72. package/src/memory/decay.js +311 -0
  73. package/src/memory/distill.js +471 -0
  74. package/src/memory/event-index.js +917 -0
  75. package/src/memory/evidence-chain.js +295 -0
  76. package/src/memory/evidence.js +145 -0
  77. package/src/memory/filter-runner.js +1 -1
  78. package/src/memory/filter.js +5 -1
  79. package/src/memory/forget-v2.js +410 -0
  80. package/src/memory/forget.js +71 -0
  81. package/src/memory/frames-activation.js +247 -0
  82. package/src/memory/fts-query.js +174 -0
  83. package/src/memory/governance.js +604 -0
  84. package/src/memory/index.js +1 -0
  85. package/src/memory/l2-gate.js +169 -0
  86. package/src/memory/lock.js +121 -0
  87. package/src/memory/migrate.js +139 -0
  88. package/src/memory/recall-v2.js +223 -0
  89. package/src/memory/recall.js +65 -2
  90. package/src/memory/records.js +425 -0
  91. package/src/memory/retention.js +128 -0
  92. package/src/memory/review.js +124 -0
  93. package/src/memory/trust.js +88 -0
  94. package/src/memory/version-chain.js +264 -0
  95. package/src/memory/wal.js +137 -0
  96. package/src/memory/working-frame.js +516 -0
  97. package/src/metrics/classify.mjs +5 -3
  98. package/src/metrics/index.mjs +21 -1
  99. package/src/metrics/prestep-latency.mjs +300 -0
  100. package/src/metrics/store.mjs +25 -0
  101. package/src/policy-profile.js +18 -3
  102. package/src/recall/anaphora.mjs +87 -0
  103. package/src/recall/cards.mjs +7 -0
  104. package/src/recall/embedding.mjs +8 -8
  105. package/src/recall/entities.mjs +112 -0
  106. package/src/recall/index.js +235 -19
  107. package/src/recall/inject-order.mjs +10 -8
  108. package/src/recall/privacy.mjs +1 -1
  109. package/src/recall/recall-core.mjs +116 -10
  110. package/src/recall/shared-visibility.js +302 -0
  111. package/src/recall/time-normalizer.mjs +196 -0
  112. package/src/role/activation.js +191 -0
  113. package/src/role/attention.js +318 -0
  114. package/src/role/base.js +36 -0
  115. package/src/role/channels.js +423 -0
  116. package/src/role/index.js +425 -0
  117. package/src/role/interfaces.js +115 -0
  118. package/src/role/personality.js +370 -0
  119. package/src/role/readers.js +151 -0
  120. package/src/role/relationships.js +477 -0
  121. package/src/role/store.js +202 -0
  122. package/src/role/writeprotect.js +373 -0
  123. package/src/router/aliases.json +176 -25
  124. package/src/router/background/agent-runner.mjs +1 -1
  125. package/src/router/background/anchor.mjs +1 -1
  126. package/src/router/background/audit.mjs +2 -2
  127. package/src/router/background/budget-ledger.mjs +2 -2
  128. package/src/router/background/host-sim.mjs +1 -1
  129. package/src/router/background/memory.mjs +4 -4
  130. package/src/router/background/queue.mjs +1 -1
  131. package/src/router/background/retry.mjs +1 -1
  132. package/src/router/background/router.mjs +1 -1
  133. package/src/router/background/stream.mjs +1 -1
  134. package/src/router/background/tool-policy.mjs +1 -1
  135. package/src/router/design-headings.json +5 -5
  136. package/src/router/face/config.mjs +1 -1
  137. package/src/router/face/identity.mjs +3 -3
  138. package/src/router/judge.mjs +8 -7
  139. package/src/router/policies/generic.json +21 -4
  140. package/src/router/route.js +109 -22
  141. package/src/router/router.mjs +10 -6
  142. package/src/router/routing-rules.json +260 -445
  143. package/src/router/run-sim.mjs +8 -8
  144. package/src/router/runtime.js +23 -12
  145. package/src/router/service/config.mjs +5 -5
  146. package/src/router/service/context.mjs +1 -1
  147. package/src/router/service/queue.mjs +1 -1
  148. package/src/router/shadow.mjs +4 -3
  149. package/src/surgery-recovery.js +2 -2
  150. package/src/tool-output.js +2 -2
  151. package/src/tools.js +39 -7
  152. package/src/truncate-visible.js +2 -2
  153. package/src/ui/actions.js +1312 -0
  154. package/src/ui/panel-api.js +367 -0
  155. package/src/ui/panel-auth.js +251 -0
  156. package/src/ui/panel-integrity.js +243 -0
  157. package/src/ui/routes-readonly.js +695 -0
  158. package/src/ui/routes.js +3 -0
  159. package/docs/DEV.md +0 -279
  160. package/docs/PRESENCE-BUS-WIRING.md +0 -491
  161. package/docs/PRESENCE-BUS.md +0 -694
  162. package/docs/SURGERY.md +0 -186
  163. package/scripts/mark-core-cards.mjs +0 -289
  164. package/scripts/pack.mjs +0 -392
  165. package/scripts/router-proposals.mjs +0 -386
  166. package/src/router/fixtures/M1.json +0 -16
  167. package/src/router/fixtures/M2.json +0 -16
  168. package/src/router/fixtures/M3.json +0 -20
  169. package/src/router/fixtures/M4.json +0 -20
  170. package/src/router/fixtures/M5.json +0 -45
  171. package/src/router/fixtures/M6.json +0 -53
  172. package/src/router/fixtures/M7.json +0 -46
  173. package/src/router/fixtures/S1.json +0 -20
  174. package/src/router/fixtures/S2.json +0 -23
  175. package/src/router/fixtures/S3.json +0 -20
  176. package/src/router/fixtures/S4.json +0 -34
  177. package/src/router/fixtures/S5.json +0 -43
  178. package/src/router/fixtures/S6.json +0 -47
  179. package/src/router/fixtures/T1.json +0 -23
  180. package/src/router/fixtures/T2.json +0 -16
  181. package/src/router/fixtures/T3.json +0 -19
  182. package/src/router/fixtures/T4.json +0 -16
  183. package/src/router/fixtures/X1.json +0 -17
  184. package/src/router/fixtures/X2.json +0 -20
  185. package/src/router/gen-design-headings.mjs +0 -107
  186. package/src/router/policies/owner-rulings-2026-11-03.json +0 -62
  187. package/test/activity-realtime.test.mjs +0 -959
  188. package/test/activity-stream.test.mjs +0 -512
  189. package/test/auto-recall.test.mjs +0 -474
  190. package/test/auto-truncate.test.mjs +0 -931
  191. package/test/autobind.test.mjs +0 -399
  192. package/test/bus.test.mjs +0 -1572
  193. package/test/cli-guard.test.mjs +0 -198
  194. package/test/conclusion.test.mjs +0 -408
  195. package/test/config-schema.test.mjs +0 -210
  196. package/test/d6-output.test.mjs +0 -194
  197. package/test/d6.test.mjs +0 -395
  198. package/test/deps.test.mjs +0 -342
  199. package/test/doctor-setup.test.mjs +0 -297
  200. package/test/embedding-recall.test.mjs +0 -347
  201. package/test/feature-flags.test.mjs +0 -585
  202. package/test/filter-shadow.test.mjs +0 -170
  203. package/test/fixtures/activity-append-child.mjs +0 -29
  204. package/test/fixtures/baseline-0.8.0-registration.json +0 -556
  205. package/test/fixtures/d6-header-tools.json +0 -1
  206. package/test/fixtures/lock-child.mjs +0 -67
  207. package/test/fixtures/pre-step-container.mjs +0 -100
  208. package/test/fixtures/privacy-memory/topics/pii-unmarked.md +0 -9
  209. package/test/fixtures/privacy-memory/topics/secret-local-only.md +0 -11
  210. package/test/fixtures/profile-session-longlive-config.json +0 -20
  211. package/test/fixtures/proposal-cas-child.mjs +0 -66
  212. package/test/host-engine-status.test.mjs +0 -307
  213. package/test/hot-truncate.test.mjs +0 -1349
  214. package/test/identity-card-marker.test.mjs +0 -307
  215. package/test/identity-router/run.mjs +0 -721
  216. package/test/integration-pre-step.test.mjs +0 -553
  217. package/test/live.test.mjs +0 -1023
  218. package/test/maintenance-schedule.test.mjs +0 -538
  219. package/test/memory.test.mjs +0 -2828
  220. package/test/metrics.test.mjs +0 -478
  221. package/test/orchestrator.test.mjs +0 -266
  222. package/test/p1_probe.mjs +0 -97
  223. package/test/packaging.test.mjs +0 -184
  224. package/test/portability.test.mjs +0 -343
  225. package/test/rc4-regressions.test.mjs +0 -562
  226. package/test/rc5-regressions.test.mjs +0 -197
  227. package/test/rc6-chinese.test.mjs +0 -394
  228. package/test/router-1100/apply-off.test.mjs +0 -175
  229. package/test/router-1100/budget-reconcile.test.mjs +0 -215
  230. package/test/router-1100/config-context.test.mjs +0 -211
  231. package/test/router-1100/helpers.mjs +0 -129
  232. package/test/router-1100/hint-envelope.test.mjs +0 -150
  233. package/test/router-1100/lock-crossproc.test.mjs +0 -206
  234. package/test/router-1100/proposal-cas-crossproc.test.mjs +0 -184
  235. package/test/router-1100/router-apply.test.mjs +0 -372
  236. package/test/router-1100/router-fixb.test.mjs +0 -602
  237. package/test/router-1100/router-proposals.test.mjs +0 -405
  238. package/test/router-1100/router-queue-lease-wal.test.mjs +0 -355
  239. package/test/router-1100/router-security-cr.test.mjs +0 -333
  240. package/test/router-1100/service-lifecycle.test.mjs +0 -220
  241. package/test/router-1100/tools-contract.test.mjs +0 -164
  242. package/test/router-1100/turn-reflect-tick.test.mjs +0 -89
  243. package/test/router-1100/v6-contract.test.mjs +0 -158
  244. package/test/router-1100/v6b-contract.test.mjs +0 -293
  245. package/test/router-1100/v6c-contract.test.mjs +0 -249
  246. package/test/router-1100/wal-rotation.test.mjs +0 -375
  247. package/test/router-1100/wp1-config.test.mjs +0 -170
  248. package/test/router-1100/wp1-default-off.test.mjs +0 -77
  249. package/test/router-1100/wp1-model-status.test.mjs +0 -90
  250. package/test/router-1100/wp1-status.test.mjs +0 -220
  251. package/test/router-1100/wp1-tools.test.mjs +0 -146
  252. package/test/router-1100/wp5-cli.test.mjs +0 -240
  253. package/test/router-1100/wp5-model-auto.test.mjs +0 -418
  254. package/test/router-1100/wp6-merge.test.mjs +0 -386
  255. package/test/router-1100/wp6-wake.test.mjs +0 -502
  256. package/test/router-background/audit.test.mjs +0 -37
  257. package/test/router-background/budget-ledger.test.mjs +0 -330
  258. package/test/router-background/cross-process.test.mjs +0 -222
  259. package/test/router-background/fixtures/cross-child.mjs +0 -85
  260. package/test/router-background/fixtures/real-shapes.mjs +0 -239
  261. package/test/router-background/router.test.mjs +0 -1076
  262. package/test/router-background/stream-retry.test.mjs +0 -358
  263. package/test/router-background/tool-agent.test.mjs +0 -384
  264. package/test/router-face/bridge.test.mjs +0 -169
  265. package/test/router-face/face.test.mjs +0 -316
  266. package/test/router-failclosed.test.mjs +0 -466
  267. package/test/router-identity.test.mjs +0 -384
  268. package/test/router-l1-l2.contract.test.mjs +0 -1075
  269. package/test/router-memory-tools.test.mjs +0 -262
  270. package/test/router-policy.test.mjs +0 -225
  271. package/test/router-runtime.test.mjs +0 -438
  272. package/test/router-shadow.test.mjs +0 -287
  273. package/test/router.test.mjs +0 -903
  274. package/test/run-rc.mjs +0 -315
  275. package/test/run.mjs +0 -2469
  276. package/test/safety-defaults.test.mjs +0 -181
  277. package/test/seeded-load.test.mjs +0 -436
  278. package/test/session-original.test.mjs +0 -338
  279. package/test/state-truth.test.mjs +0 -937
  280. package/test/surgery-recovery.test.mjs +0 -936
  281. package/test/t7_drive.mjs +0 -151
  282. package/test/tool-output.test.mjs +0 -393
  283. package/test/tool-schema.test.mjs +0 -177
  284. package/test/tools_contract.test.mjs +0 -716
  285. package/test/truncate-visible.test.mjs +0 -1150
  286. package/test/ui-flags.test.mjs +0 -477
  287. package/test/v4-hardening.test.mjs +0 -427
  288. package/test/version-consistency.test.mjs +0 -286
@@ -1,931 +0,0 @@
1
- // 0.7.1 — user-authored-message detection + auto-truncation tests.
2
- //
3
- // Everything here writes under TMP. No test reads ~/.dsh/sessions.
4
- //
5
- // The cases are built to fail against plausible fake-greens:
6
- // * if isUserAuthoredMessage is loosened back to "any kind:user row", A2
7
- // carries the surgical checkpoint instead of the human line and goes red;
8
- // * if auto-truncate writes the session log again (mode apply, or a request
9
- // mode that "helpfully" cuts in-process), A6/A12's sha256 assertions go red;
10
- // * if the request file loses its single-flight guard, A12's byte compare of
11
- // the pending request goes red;
12
- // * if log/dryrun accidentally touch the session log, the sha256 assertions
13
- // go red.
14
-
15
- import fs from 'node:fs';
16
- import path from 'node:path';
17
- import crypto from 'node:crypto';
18
- import { spawnSync } from 'node:child_process';
19
- import { fileURLToPath } from 'node:url';
20
-
21
- import { parseSession, encodeSession } from '../src/codec.js';
22
- import {
23
- isUserAuthoredMessage,
24
- looksLikeInjectedText,
25
- USER_TEXT_MARKERS,
26
- planVisibleTruncation,
27
- truncateVisibleSession,
28
- archiveDirFor,
29
- inflightPathFor,
30
- VISIBLE_CONFIRM_WORD,
31
- } from '../src/truncate-visible.js';
32
- import {
33
- AUTO_TRUNCATE_DEFAULTS,
34
- AUTO_TRUNCATE_ERRORS,
35
- AUTO_TRUNCATE_LEGACY_MODES,
36
- AUTO_TRUNCATE_MODES,
37
- appendAutoTruncateLog,
38
- autoTruncatePaths,
39
- createAutoTruncator,
40
- findSessionFile,
41
- normalizeAutoTruncateConfig,
42
- } from '../src/auto-truncate.js';
43
- import { createAutoHeartbeat } from '../src/heartbeat.js';
44
-
45
- function sha256(buf) {
46
- return crypto.createHash('sha256').update(buf).digest('hex');
47
- }
48
-
49
- function fileSha(file) {
50
- return sha256(fs.readFileSync(file));
51
- }
52
-
53
- function readParsed(file) {
54
- return parseSession(fs.readFileSync(file));
55
- }
56
-
57
- function readLogLines(memoryRoot) {
58
- const { logPath } = autoTruncatePaths(memoryRoot);
59
- if (!fs.existsSync(logPath)) return [];
60
- return fs.readFileSync(logPath, 'utf8').split('\n').filter((line) => line.trim() !== '');
61
- }
62
-
63
- /**
64
- * A synthetic log with 20 turns. `checkpointAt` inserts one surgical-checkpoint
65
- * user/message (source.kind "user", rpcId, no clientTimeZone) before turn 1;
66
- * `humanSource` lets a case turn every turn message into an injected block.
67
- */
68
- function buildFixture({ id, turns = 20, checkpointAt = null, humanSource = null, padding = 900 }) {
69
- const events = [];
70
- const base = Date.now() - 120_000;
71
- const push = (event) => {
72
- event.seq = events.length;
73
- event.time = base + events.length;
74
- events.push(event);
75
- };
76
- push({
77
- type: 'system/message',
78
- surfaceOp: 'append',
79
- data: {
80
- message: {
81
- role: 'system', id: 'system-1', source: { kind: 'system-prompt' },
82
- content: [{ type: 'text', text: '测试用系统提示' }],
83
- },
84
- },
85
- });
86
- if (checkpointAt != null) {
87
- push({
88
- type: 'user/message',
89
- surfaceOp: 'append',
90
- data: {
91
- role: 'user', id: 'checkpoint-1',
92
- content: [{
93
- type: 'text',
94
- text: 'This is an automatically generated checkpoint condensing an earlier span of the conversation. 这是压缩检查点(非用户发言)。',
95
- }],
96
- source: { kind: 'user', rpcId: 'rpc-checkpoint' },
97
- },
98
- });
99
- }
100
- for (let t = 1; t <= turns; t += 1) {
101
- push({ type: 'turn/start', data: { turn: t } });
102
- push({
103
- type: 'user/message',
104
- surfaceOp: 'append',
105
- data: {
106
- turn: t, step: 1, role: 'user', id: `user-${t}`,
107
- content: [{ type: 'text', text: humanSource ? humanSource(t) : `第 ${t} 个问题` }],
108
- source: humanSource
109
- ? { kind: 'runtime-context', snapshot: { t } }
110
- : { kind: 'user', rpcId: `rpc-${t}`, clientTimeZone: 'Asia/Shanghai' },
111
- },
112
- });
113
- push({
114
- type: 'assistant/message',
115
- surfaceOp: 'append',
116
- data: {
117
- turn: t, step: 1, stream: [],
118
- message: {
119
- role: 'assistant', id: `assistant-${t}`,
120
- source: { kind: 'model', provider: 'deepseek-official', model: 'deepseek-chat' },
121
- content: [{ type: 'text', text: `第 ${t} 个回答 ${'x'.repeat(padding)}` }],
122
- },
123
- },
124
- });
125
- push({ type: 'turn/end', data: { turn: t } });
126
- }
127
- return {
128
- header: {
129
- type: 'session', version: 4, id, createdAt: base,
130
- cwd: 'C:\\fixtures', isSeeded: false, delegationDepth: 0,
131
- },
132
- events,
133
- };
134
- }
135
-
136
- function writeFixture(TMP, name, options = {}) {
137
- const id = `session-auto-${name}`;
138
- const { header, events } = buildFixture({ id, ...options });
139
- const home = path.join(TMP, 'auto-truncate', name, 'home');
140
- const file = path.join(home, 'sessions', 'scope-fixtures', id, 'session.v4.jsonl.zstd');
141
- fs.mkdirSync(path.dirname(file), { recursive: true });
142
- fs.writeFileSync(file, encodeSession(header, events));
143
- return { id, home, file, header, events, memoryRoot: path.join(TMP, 'auto-truncate', name, 'memory') };
144
- }
145
-
146
- const NOW = 1_700_000_000_000;
147
-
148
- function clock(stepMs = 0) {
149
- let t = NOW;
150
- return () => {
151
- t += stepMs;
152
- return t;
153
- };
154
- }
155
-
156
- export async function runAutoTruncateSuite({ runCase, assert, TMP }) {
157
- const base = path.join(TMP, 'auto-truncate');
158
-
159
- runCase('A1', 'isUserAuthoredMessage:宿主字段优先,拿不准一律 false', () => {
160
- const human = {
161
- type: 'user/message',
162
- data: { source: { kind: 'user', rpcId: 'rpc-1', clientTimeZone: 'Asia/Shanghai' }, content: [{ type: 'text', text: '这不对,上下文会暴涨' }] },
163
- };
164
- const checkpoint = {
165
- type: 'user/message',
166
- data: {
167
- source: { kind: 'user', rpcId: 'rpc-2' },
168
- content: [{ type: 'text', text: 'This is an automatically generated checkpoint condensing an earlier span of the conversation.' }],
169
- },
170
- };
171
- const spliced = {
172
- type: 'user/message',
173
- data: { source: { kind: 'user' }, content: [{ type: 'text', text: '你是打包执行者,任务如下' }] },
174
- };
175
- const runtime = {
176
- type: 'user/message',
177
- data: { source: { kind: 'runtime-context', snapshot: {} }, content: [{ type: 'text', text: 'Current runtime context.' }] },
178
- };
179
- assert(isUserAuthoredMessage(human) === true, 'real human message (clientTimeZone) rejected');
180
- assert(isUserAuthoredMessage(checkpoint) === false, 'checkpoint accepted as human');
181
- assert(isUserAuthoredMessage(spliced) === false, 'spliced task brief accepted as human');
182
- assert(isUserAuthoredMessage(runtime) === false, 'runtime-context block accepted as human');
183
- assert(isUserAuthoredMessage({ type: 'assistant/message', data: human.data }) === false, 'assistant message accepted');
184
- assert(isUserAuthoredMessage(null) === false, 'null accepted');
185
-
186
- for (const marker of [
187
- 'This is an automatically generated checkpoint',
188
- 'Current runtime context',
189
- '<current_user_request>',
190
- '<engram_profile>',
191
- '<engram_memory_context>',
192
- '<system-reminder>',
193
- '[Compressed conversation section]',
194
- 'background job b-123 finished',
195
- '<available_skills>',
196
- ]) {
197
- assert(looksLikeInjectedText(`${marker} …`) === true, `blacklist missed marker: ${marker}`);
198
- }
199
- assert(USER_TEXT_MARKERS.length >= 9, 'blacklist is shorter than the spec');
200
- return `${USER_TEXT_MARKERS.length} markers; host positive field = clientTimeZone`;
201
- });
202
-
203
- runCase('A2', '首条真人消息复刻:跳过检查点,只认 clientTimeZone 那条', () => {
204
- const { file } = writeFixture(TMP, 'carry', { checkpointAt: 0 });
205
- const parsed = readParsed(file);
206
- const checkpointSeq = parsed.events.findIndex((event) => event.data?.id === 'checkpoint-1');
207
- const humanSeq = parsed.events.findIndex((event) => event.data?.id === 'user-1');
208
- assert(checkpointSeq > 0 && humanSeq > checkpointSeq, 'fixture does not have checkpoint before human');
209
-
210
- const result = truncateVisibleSession(file, {
211
- dryRun: true, keepTurns: 5, keepTokens: 1_000_000,
212
- });
213
- assert(result.needed === true, 'fixture was not truncatable');
214
- assert(result.firstUserMessage !== null, 'no first user message found');
215
- assert(result.firstUserMessage.seq === humanSeq, `carried seq ${result.firstUserMessage.seq}, expected ${humanSeq}`);
216
- assert(result.firstUserMessage.text.includes('第 1 个问题'), 'human text missing');
217
- assert(!result.firstUserMessage.text.includes('automatically generated checkpoint'), 'checkpoint text leaked into carry');
218
-
219
- const plan = planVisibleTruncation(parsed, { keepTurns: 5, keepTokens: 1_000_000 });
220
- assert(plan.firstUserMessage.seq === humanSeq, 'plan picked the checkpoint');
221
- assert(plan.carryFirstUserMessage === true, 'plan did not mark the human message as carried');
222
-
223
- // And the assembled buffer carries the human line, not the checkpoint.
224
- const applied = truncateVisibleSession(file, {
225
- dryRun: false, confirm: VISIBLE_CONFIRM_WORD, keepTurns: 5, keepTokens: 1_000_000, recentWriteWindowMs: 0,
226
- });
227
- const after = readParsed(file);
228
- const carry = after.events.slice(0, 8).find((event) => (event.data?.content?.[0]?.text ?? '').startsWith('[会话起点 · 已归档]'));
229
- assert(carry, 'no carried first-user message in the rewritten log');
230
- assert(carry.data.content[0].text.includes('第 1 个问题'), 'carry is not the human message');
231
- assert(!carry.data.content[0].text.includes('automatically generated checkpoint'), 'carry is the checkpoint');
232
- assert(applied.firstUserMessage.seq === humanSeq, 'report seq is not the human message');
233
- return `carried seq ${humanSeq}, not checkpoint seq ${checkpointSeq}`;
234
- });
235
-
236
- runCase('A3', '只有注入块:不回退,工具明说「未找到真人消息」', () => {
237
- const { file } = writeFixture(TMP, 'no-human', { humanSource: (t) => `Current runtime context snapshot ${t}` });
238
- const parsed = readParsed(file);
239
- assert(parsed.events.some((event) => event.type === 'user/message'), 'fixture has no user/message rows');
240
-
241
- // The load-bearing assertion: with only injected rows the plan must report
242
- // "no human", not quietly promote the first runtime-context block.
243
- const plan = planVisibleTruncation(parsed, { keepTurns: 5, keepTokens: 1_000_000 });
244
- assert(plan.firstUserMessage === null, 'plan fell back to an injected block');
245
- assert(plan.firstUserMessageNote.includes('未找到真人消息'), 'plan note does not say no human message');
246
- assert(parsed.events.filter((event) => event.type === 'user/message').every((event) => isUserAuthoredMessage(event) === false),
247
- 'fixture accidentally contains a human message');
248
-
249
- const result = truncateVisibleSession(file, { dryRun: true, keepTurns: 5, keepTokens: 1_000_000 });
250
- assert(result.needed === false, 'no-human fixture should not be cut (no safe boundary)');
251
- assert(result.firstUserMessage === null, 'result fell back to an injected block');
252
- assert(result.message.includes('未找到真人消息'), `tool message does not say it: ${result.message.slice(0, 120)}`);
253
- assert(fs.existsSync(file), 'dry-run removed the file');
254
- return 'no human -> noop + explicit note';
255
- });
256
-
257
- runCase('A4', 'auto log:会话字节不变、日志恰一行、含切割范围与预计降幅', () => {
258
- const { id, file, memoryRoot } = writeFixture(TMP, 'mode-log');
259
- const beforeSha = fileSha(file);
260
- const truncator = createAutoTruncator({
261
- memoryRoot, autoTruncate: { enabled: true, mode: 'log', tokensThreshold: 500, minTurns: 3 }, now: clock(),
262
- });
263
- assert(truncator.config.mode === 'log', 'default override failed');
264
-
265
- const status = truncator.onTurnEnd({ sessionId: id, turn: 20, sessionPath: file });
266
- assert(status.status === 'logged', `unexpected status ${status.status}`);
267
- assert(status.action === 'planned', `unexpected action ${status.action}`);
268
- assert(fileSha(file) === beforeSha, 'log mode wrote the session file');
269
- assert(!fs.existsSync(archiveDirFor(file)), 'log mode created an archive dir');
270
- assert(!fs.existsSync(inflightPathFor(file)), 'log mode left an inflight record');
271
-
272
- const lines = readLogLines(memoryRoot);
273
- assert(lines.length === 1, `expected exactly one log line, got ${lines.length}`);
274
- const entry = JSON.parse(lines[0]);
275
- assert(entry.mode === 'log', 'log entry mode');
276
- assert(entry.sessionId === id, 'log entry session id');
277
- assert(entry.estimate.basis.includes('MESSAGE_TYPES'), 'log entry has no estimate basis');
278
- assert(entry.estimate.tokens >= 500, 'estimate did not exceed threshold');
279
- assert(entry.plan.cut.droppedTurns > 0, 'plan has no cut range');
280
- assert(entry.plan.projected.dropTokens > 0, 'plan has no projected drop');
281
- assert(entry.plan.projected.dropPercent > 0, 'plan has no drop percent');
282
- assert(entry.threshold.tokens === 500, 'threshold not recorded');
283
- return `one line, drop ${entry.plan.projected.dropPercent}%`;
284
- });
285
-
286
- runCase('A5', 'auto dryrun:仍不写会话,日志含完整计划(cut/before/after)', () => {
287
- const { id, file, memoryRoot } = writeFixture(TMP, 'mode-dryrun');
288
- const beforeSha = fileSha(file);
289
- const truncator = createAutoTruncator({
290
- memoryRoot, autoTruncate: { enabled: true, mode: 'dryrun', tokensThreshold: 500, minTurns: 3 }, now: clock(),
291
- });
292
- const status = truncator.onTurnEnd({ sessionId: id, turn: 20, sessionPath: file });
293
- assert(status.status === 'dryrun', `unexpected status ${status.status}`);
294
- assert(status.action === 'dryrun-planned', `unexpected action ${status.action}`);
295
- assert(fileSha(file) === beforeSha, 'dryrun mode wrote the session file');
296
- assert(!fs.existsSync(archiveDirFor(file)), 'dryrun created an archive dir');
297
-
298
- const lines = readLogLines(memoryRoot);
299
- assert(lines.length === 1, `expected one log line, got ${lines.length}`);
300
- const entry = JSON.parse(lines[0]);
301
- assert(entry.dryRun === true, 'entry not marked dryRun');
302
- assert(entry.wroteSessionFile === false, 'entry claims a write');
303
- assert(entry.plan.cut.droppedTurns > 0, 'dryrun plan has no cut');
304
- assert(entry.plan.after.tokens < entry.plan.dropped.tokens + entry.plan.kept.tokens,
305
- 'dryrun plan has no after estimate');
306
- assert(entry.plan.after.sha256 && entry.plan.after.sha256 !== beforeSha, 'dryrun after sha missing/unchanged');
307
- return `planned cut turn ${entry.plan.cut.turn}, no write`;
308
- });
309
-
310
- runCase('A6', 'auto apply(旧配置):按 request 处理,会话字节不变,日志记 modeAlias', () => {
311
- const { id, file, memoryRoot } = writeFixture(TMP, 'mode-apply');
312
- const beforeSha = fileSha(file);
313
- const truncator = createAutoTruncator({
314
- memoryRoot,
315
- autoTruncate: { enabled: true,
316
- mode: 'apply',
317
- tokensThreshold: 500,
318
- minTurns: 3,
319
- keepTurns: 5,
320
- keepTokens: 1_000_000,
321
- appExe: 'C:\\fake\\DeepSeek Harness.exe',
322
- profile: 'desktop',
323
- },
324
- now: () => Date.now(),
325
- });
326
- assert(truncator.config.mode === 'request', 'legacy apply was not rewritten to request');
327
- assert(truncator.config.modeAlias === 'apply->request', 'modeAlias missing from normalized config');
328
-
329
- const status = truncator.onTurnEnd({ sessionId: id, turn: 20, sessionPath: file });
330
- assert(status.status === 'request-written', `unexpected status ${status.status} (${status.code ?? ''})`);
331
- assert(status.action === 'request-written', `unexpected action ${status.action}`);
332
- assert(fileSha(file) === beforeSha, 'legacy apply wrote the session file');
333
- assert(!fs.existsSync(archiveDirFor(file)), 'legacy apply created an archive dir');
334
- assert(!fs.existsSync(inflightPathFor(file)), 'legacy apply left an inflight record');
335
-
336
- const lines = readLogLines(memoryRoot);
337
- assert(lines.length === 1, `expected one log line, got ${lines.length}`);
338
- const entry = JSON.parse(lines[0]);
339
- assert(entry.mode === 'request', `log mode is ${entry.mode}, expected request`);
340
- assert(entry.modeAlias === 'apply->request', 'log has no modeAlias');
341
- assert(entry.action === 'request-written', `log action is ${entry.action}`);
342
- assert(entry.wroteSessionFile === false, 'log claims a session write');
343
- for (const oldField of ['applied', 'before', 'after', 'delta', 'hostReloadRequired', 'backupPath', 'archivePath']) {
344
- assert(!(oldField in entry), `old apply field ${oldField} came back`);
345
- }
346
-
347
- const request = JSON.parse(fs.readFileSync(truncator.requestPath, 'utf8'));
348
- assert(request.sessionPath === path.resolve(file), 'request points at another session');
349
- assert(request.app.exe === 'C:\\fake\\DeepSeek Harness.exe', 'request app.exe not from config');
350
- return `alias logged, request ${request.requestId.slice(0, 8)}, session untouched`;
351
- });
352
-
353
- runCase('A7', '防抖:同一 turn 只评估一次;cooldown 内不重复;below-threshold 不写日志', () => {
354
- const { id, file, memoryRoot } = writeFixture(TMP, 'debounce');
355
- const now = clock(0);
356
- const truncator = createAutoTruncator({
357
- memoryRoot, autoTruncate: { enabled: true, mode: 'log', tokensThreshold: 500, minTurns: 3, cooldownMinutes: 60 }, now,
358
- });
359
- const first = truncator.onTurnEnd({ sessionId: id, turn: 20, sessionPath: file });
360
- assert(first.status === 'logged', 'first evaluation did not log');
361
- const duplicate = truncator.onTurnEnd({ sessionId: id, turn: 20, sessionPath: file });
362
- assert(duplicate.status === 'skipped' && duplicate.reason === 'duplicate-turn', 'duplicate turn re-evaluated');
363
- const cooldown = truncator.onTurnEnd({ sessionId: id, turn: 21, sessionPath: file });
364
- assert(cooldown.status === 'skipped' && cooldown.reason === 'cooldown', 'cooldown not applied');
365
- assert(readLogLines(memoryRoot).length === 1, 'debounce still produced log lines');
366
-
367
- const small = writeFixture(TMP, 'below-threshold');
368
- const tr2 = createAutoTruncator({
369
- memoryRoot: small.memoryRoot,
370
- autoTruncate: { enabled: true, mode: 'log', tokensThreshold: 10_000_000, minTurns: 3 },
371
- now: clock(),
372
- });
373
- const under = tr2.onTurnEnd({ sessionId: small.id, turn: 20, sessionPath: small.file });
374
- assert(under.status === 'skipped' && under.reason === 'below-threshold', `unexpected ${under.reason}`);
375
- assert(readLogLines(small.memoryRoot).length === 0, 'below-threshold wrote a log line');
376
- return 'duplicate + cooldown + below-threshold all quiet';
377
- });
378
-
379
- runCase('A8', '防抖:inflight 记录存在时跳过且不写日志;坏配置明确报错', () => {
380
- const { id, file, memoryRoot } = writeFixture(TMP, 'inflight');
381
- fs.mkdirSync(path.dirname(inflightPathFor(file)), { recursive: true });
382
- fs.writeFileSync(inflightPathFor(file), JSON.stringify({ version: 1, phase: 'prepared' }));
383
- const truncator = createAutoTruncator({
384
- memoryRoot, autoTruncate: { enabled: true, mode: 'log', tokensThreshold: 500, minTurns: 3 }, now: clock(),
385
- });
386
- const status = truncator.onTurnEnd({ sessionId: id, turn: 20, sessionPath: file });
387
- assert(status.status === 'skipped' && status.reason === 'inflight', `unexpected ${status.reason}`);
388
- assert(readLogLines(memoryRoot).length === 0, 'inflight skip wrote a log line');
389
-
390
- const alias = normalizeAutoTruncateConfig({ mode: 'apply' });
391
- assert(alias.mode === 'request' && alias.modeAlias === 'apply->request', 'apply was not aliased to request');
392
- assert(AUTO_TRUNCATE_MODES.join(',') === 'log,dryrun,request', 'mode list');
393
- assert(AUTO_TRUNCATE_LEGACY_MODES.join(',') === 'apply', 'legacy mode list');
394
-
395
- let badMode = null;
396
- try {
397
- normalizeAutoTruncateConfig({ mode: 'APPLY' });
398
- } catch (error) {
399
- badMode = error;
400
- }
401
- assert(badMode?.code === AUTO_TRUNCATE_ERRORS.BAD_MODE, 'bad mode was silently accepted');
402
- let badThreshold = null;
403
- try {
404
- normalizeAutoTruncateConfig({ tokensThreshold: 0 });
405
- } catch (error) {
406
- badThreshold = error;
407
- }
408
- assert(badThreshold?.code === AUTO_TRUNCATE_ERRORS.BAD_CONFIG, 'bad threshold was silently accepted');
409
- let badProfile = null;
410
- try {
411
- normalizeAutoTruncateConfig({ profile: ' ' });
412
- } catch (error) {
413
- badProfile = error;
414
- }
415
- assert(badProfile?.code === AUTO_TRUNCATE_ERRORS.BAD_CONFIG, 'empty profile was silently accepted');
416
- let badAppExe = null;
417
- try {
418
- normalizeAutoTruncateConfig({ appExe: 42 });
419
- } catch (error) {
420
- badAppExe = error;
421
- }
422
- assert(badAppExe?.code === AUTO_TRUNCATE_ERRORS.BAD_CONFIG, 'non-string appExe was silently accepted');
423
-
424
- const defaults = normalizeAutoTruncateConfig(undefined);
425
- assert(defaults.mode === 'dryrun' && defaults.enabled === false && defaults.tokensThreshold === 300000,
426
- '1.6.0 safety defaults changed');
427
- assert(defaults.keepTurns === AUTO_TRUNCATE_DEFAULTS.keepTurns, 'keepTurns default changed');
428
- assert(defaults.profile === 'desktop' && defaults.appExe === '', 'request defaults changed');
429
- return 'inflight quiet; apply aliased; bad config throws';
430
- });
431
-
432
- runCase('A9', '触发点:heartbeat 的 session/event turn/end 调用 onTurnEnd(未绑定也调用)', () => {
433
- const calls = [];
434
- let listener = null;
435
- const ctx = {
436
- on(name, fn) {
437
- if (name === 'session/event') listener = fn;
438
- return () => { listener = null; };
439
- },
440
- };
441
- const hb = createAutoHeartbeat({
442
- ctx,
443
- memoryRoot: path.join(base, 'hb-memory'),
444
- heartbeatMs: 0,
445
- now: () => NOW,
446
- onTurnEnd: (info) => calls.push(info),
447
- });
448
- hb.start();
449
- assert(typeof listener === 'function', 'heartbeat did not subscribe to session/event');
450
- listener({ id: 'session-never-bound' }, { type: 'turn/end', data: { turn: 7 } });
451
- assert(calls.length === 1, `turn/end did not call onTurnEnd (${calls.length})`);
452
- assert(calls[0].sessionId === 'session-never-bound' && calls[0].turn === 7, 'wrong info');
453
- listener({ id: 'session-never-bound' }, { type: 'turn/start', data: { turn: 8 } });
454
- assert(calls.length === 1, 'turn/start incorrectly triggered auto-truncate');
455
- hb.stop();
456
- return 'turn/end only, before the bound-set gate';
457
- });
458
-
459
- runCase('A10', '日志/状态隔离:不同 memoryRoot 互不影响,状态文件可解析', () => {
460
- const one = writeFixture(TMP, 'iso-one');
461
- const two = writeFixture(TMP, 'iso-two');
462
- const tr1 = createAutoTruncator({
463
- memoryRoot: one.memoryRoot, autoTruncate: { enabled: true, mode: 'log', tokensThreshold: 500, minTurns: 3 }, now: clock(),
464
- });
465
- const tr2 = createAutoTruncator({
466
- memoryRoot: two.memoryRoot, autoTruncate: { enabled: true, mode: 'log', tokensThreshold: 500, minTurns: 3 }, now: clock(),
467
- });
468
- tr1.onTurnEnd({ sessionId: one.id, turn: 20, sessionPath: one.file });
469
- tr2.onTurnEnd({ sessionId: two.id, turn: 20, sessionPath: two.file });
470
- assert(readLogLines(one.memoryRoot).length === 1, 'session one log');
471
- assert(readLogLines(two.memoryRoot).length === 1, 'session two log');
472
- const statePath = autoTruncatePaths(one.memoryRoot).statePath;
473
- const state = JSON.parse(fs.readFileSync(statePath, 'utf8'));
474
- assert(state.sessions[one.id]?.status === 'over', 'state did not record the evaluation');
475
- assert(findSessionFile(one.home, one.id) === one.file, 'findSessionFile did not resolve the id');
476
- return 'isolated logs + resolvable id -> path';
477
- });
478
-
479
- runCase('A11', 'appendAutoTruncateLog 是追加(不是覆盖),并返回同一路径', () => {
480
- const memoryRoot = path.join(base, 'append-log', 'memory');
481
- const a = appendAutoTruncateLog(memoryRoot, { time: 't1', action: 'a' });
482
- const b = appendAutoTruncateLog(memoryRoot, { time: 't2', action: 'b' });
483
- assert(a.logPath === b.logPath, 'log path changed between appends');
484
- const lines = readLogLines(memoryRoot);
485
- assert(lines.length === 2, `expected 2 lines, got ${lines.length}`);
486
- assert(JSON.parse(lines[0]).action === 'a' && JSON.parse(lines[1]).action === 'b', 'order lost');
487
- return 'append-only, same path';
488
- });
489
-
490
- runCase('A12', 'auto request:请求文件 schema 完整、会话不变;已有请求时单飞不覆盖', () => {
491
- const { id, file, memoryRoot } = writeFixture(TMP, 'mode-request');
492
- const beforeSha = fileSha(file);
493
- const truncator = createAutoTruncator({
494
- memoryRoot,
495
- autoTruncate: { enabled: true,
496
- mode: 'request',
497
- tokensThreshold: 500,
498
- minTurns: 3,
499
- keepTurns: 5,
500
- keepTokens: 1_000_000,
501
- appExe: 'C:\\fake\\App.exe',
502
- profile: 'desktop',
503
- },
504
- now: () => Date.now(),
505
- });
506
- const status = truncator.onTurnEnd({ sessionId: id, turn: 20, sessionPath: file });
507
- assert(status.status === 'request-written', `unexpected status ${status.status} (${status.code ?? ''})`);
508
- assert(fileSha(file) === beforeSha, 'request mode wrote the session file');
509
- assert(!fs.existsSync(archiveDirFor(file)), 'request mode created an archive dir');
510
- assert(!fs.existsSync(inflightPathFor(file)), 'request mode left an inflight record');
511
-
512
- const requestPath = autoTruncatePaths(memoryRoot).requestPath;
513
- assert(requestPath === truncator.requestPath, 'requestPath is not under .longlive/logs');
514
- assert(fs.existsSync(requestPath), 'request file missing');
515
- const request = JSON.parse(fs.readFileSync(requestPath, 'utf8'));
516
- const keys = Object.keys(request).sort();
517
- const expected = ['app', 'at', 'estimate', 'plan', 'pluginDir', 'reason', 'requestId', 'sessionId', 'sessionPath', 'version'];
518
- assert(keys.join(',') === expected.join(','), `schema keys: ${keys.join(',')}`);
519
- assert(request.version === 1, 'version is not 1');
520
- assert(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(request.requestId),
521
- `requestId is not a uuid: ${request.requestId}`);
522
- assert(Math.abs(Date.now() - Date.parse(request.at)) < 10_000, 'at is not real time');
523
- assert(request.sessionPath === path.resolve(file), 'sessionPath is not absolute');
524
- assert(request.sessionId === id, 'sessionId mismatch');
525
- assert(request.reason === 'tokens-over-threshold', 'reason mismatch');
526
- assert(request.estimate.threshold === 500 && request.estimate.tokens >= 500, 'estimate mismatch');
527
- assert(Number.isInteger(request.plan.cut) && request.plan.cut > 0, 'plan.cut');
528
- assert(Number.isInteger(request.plan.dropped) && request.plan.dropped > 0, 'plan.dropped');
529
- assert(Number.isInteger(request.plan.kept) && request.plan.kept > 0, 'plan.kept');
530
- assert(request.plan.keepTurns === 5 && request.plan.keepTokens === 1_000_000, 'plan keeps changed');
531
- assert(request.plan.projectedTokens < request.estimate.tokens, 'projectedTokens does not drop');
532
- assert(request.app.exe === 'C:\\fake\\App.exe' && request.app.profile === 'desktop', 'app metadata');
533
- assert(fs.statSync(request.pluginDir).isDirectory(), 'pluginDir is not a directory');
534
- assert(fs.readdirSync(path.dirname(requestPath)).every((name) => !name.includes('.tmp-')),
535
- 'request tmp file left behind');
536
-
537
- const entry = JSON.parse(readLogLines(memoryRoot)[0]);
538
- assert(entry.action === 'request-written' && entry.requestId === request.requestId, 'log does not carry the request');
539
- assert(entry.request?.requestId === request.requestId, 'log does not embed the full request');
540
- assert(entry.plan?.projected?.dropEvents > 0, 'log plan projection missing');
541
- assert(entry.wroteSessionFile === false, 'log claims a session write');
542
-
543
- const bytesBefore = fs.readFileSync(requestPath);
544
- const second = createAutoTruncator({
545
- memoryRoot,
546
- autoTruncate: { enabled: true,
547
- mode: 'request',
548
- tokensThreshold: 500,
549
- minTurns: 3,
550
- cooldownMinutes: 0,
551
- keepTurns: 5,
552
- keepTokens: 1_000_000,
553
- appExe: 'C:\\fake\\App.exe',
554
- profile: 'desktop',
555
- },
556
- now: () => Date.now(),
557
- });
558
- const pending = second.onTurnEnd({ sessionId: id, turn: 19, sessionPath: file });
559
- assert(pending.status === 'request-pending' && pending.action === 'request-pending',
560
- `single-flight status ${pending.status}`);
561
- assert(pending.requestId === request.requestId, 'pending lost the existing requestId');
562
- assert(fs.readFileSync(requestPath).equals(bytesBefore), 'pending evaluation overwrote the request');
563
- assert(fileSha(file) === beforeSha, 'pending evaluation wrote the session');
564
- const lines = readLogLines(memoryRoot);
565
- assert(lines.length === 2, `expected two log lines, got ${lines.length}`);
566
- const pendingEntry = JSON.parse(lines[1]);
567
- assert(pendingEntry.action === 'request-pending' && pendingEntry.requestPending === true,
568
- 'pending log entry missing the flag');
569
- assert(pendingEntry.wroteSessionFile === false, 'pending log claims a write');
570
- assert(pendingEntry.plan?.needed === true, 'pending entry lost the plan');
571
- return `schema ok, ${request.requestId.slice(0, 8)}, single-flight preserved`;
572
- });
573
-
574
- runCase('A16', 'request 前文件又长了几条:estimate/plan 按最新计数,plan 记录 snapshotEvents/snapshotAt', () => {
575
- // The VM run: the plugin read 295 events / 91 messages at turn/end, the app
576
- // appended seq 295-297 eight milliseconds later, and the request described a
577
- // file that no longer existed. The fake fs appends those three events on the
578
- // SECOND session read, i.e. exactly between the turn/end snapshot and the
579
- // moment the request is built.
580
- const { id, file, memoryRoot } = writeFixture(TMP, 'growing-file');
581
- const parsed = readParsed(file);
582
- const grown = parsed.events.map((event) => ({ ...event }));
583
- for (let i = 0; i < 3; i += 1) {
584
- grown.push({
585
- type: 'session/title',
586
- seq: grown.length,
587
- time: Date.now() + i,
588
- data: { title: `late-${i}`, messageSeqs: [], source: { kind: 'user' } },
589
- });
590
- }
591
- const grownBuf = encodeSession(parsed.header, grown.map((event, index) => ({ ...event, seq: index })));
592
- const staleEvents = parsed.events.length;
593
- const freshPlan = planVisibleTruncation(parseSession(grownBuf), { keepTurns: 5, keepTokens: 1_000_000 });
594
-
595
- let reads = 0;
596
- const fakeFs = Object.create(fs);
597
- fakeFs.readFileSync = (target, opts) => {
598
- if (path.resolve(String(target)) === path.resolve(file)) {
599
- reads += 1;
600
- if (reads >= 2) return grownBuf;
601
- }
602
- return fs.readFileSync(target, opts);
603
- };
604
-
605
- const truncator = createAutoTruncator({
606
- memoryRoot,
607
- autoTruncate: { enabled: true,
608
- mode: 'request',
609
- tokensThreshold: 500,
610
- minTurns: 3,
611
- cooldownMinutes: 0,
612
- keepTurns: 5,
613
- keepTokens: 1_000_000,
614
- appExe: 'C:\\fake\\App.exe',
615
- profile: 'desktop',
616
- },
617
- fs: fakeFs,
618
- now: () => Date.now(),
619
- });
620
- const status = truncator.onTurnEnd({ sessionId: id, turn: 20, sessionPath: file });
621
- assert(status.status === 'request-written', `unexpected status ${status.status} (${status.code ?? ''})`);
622
- assert(reads >= 2, `the request never re-read the session file (${reads} read(s))`);
623
-
624
- const request = JSON.parse(fs.readFileSync(autoTruncatePaths(memoryRoot).requestPath, 'utf8'));
625
- assert(request.estimate.events === grown.length,
626
- `estimate described ${request.estimate.events} events, the file had ${grown.length} (stale snapshot: ${staleEvents})`);
627
- assert(request.estimate.events !== staleEvents, 'estimate reused the stale turn/end count');
628
- assert(request.estimate.source === 'pre-request', `estimate.source ${request.estimate.source}`);
629
- assert(request.plan.snapshotEvents === grown.length,
630
- `plan.snapshotEvents ${request.plan.snapshotEvents}, expected ${grown.length}`);
631
- assert(request.plan.snapshotMessages === freshPlan.original.messages,
632
- `plan.snapshotMessages ${request.plan.snapshotMessages}, expected ${freshPlan.original.messages}`);
633
- assert(typeof request.plan.snapshotAt === 'string' && Number.isFinite(Date.parse(request.plan.snapshotAt)),
634
- `plan.snapshotAt is not a timestamp: ${request.plan.snapshotAt}`);
635
- assert(request.plan.kept === freshPlan.kept.events,
636
- `plan.kept ${request.plan.kept} does not match a plan over the grown file (${freshPlan.kept.events})`);
637
- assert(request.plan.dropped === freshPlan.dropped.events,
638
- `plan.dropped ${request.plan.dropped} does not match a plan over the grown file (${freshPlan.dropped.events})`);
639
-
640
- const entry = JSON.parse(readLogLines(memoryRoot)[0]);
641
- assert(entry.action === 'request-written', 'log entry missing');
642
- assert(entry.plan?.snapshot?.source === 'pre-request', 'log does not record which snapshot the plan used');
643
- assert(entry.plan?.snapshot?.events === grown.length, 'log snapshotEvents mismatch');
644
- return `${staleEvents} -> ${grown.length} events, plan rebuilt from the pre-request snapshot`;
645
- });
646
-
647
- runCase('A14', 'request 原子写:tmp 写到 12 字节 ENOSPC -> 无请求文件/无残留 tmp,下一次评估正常写', () => {
648
- const { id, file, memoryRoot } = writeFixture(TMP, 'request-enospc');
649
- const beforeSha = fileSha(file);
650
- const paths = autoTruncatePaths(memoryRoot);
651
- const config = {
652
- enabled: true,
653
- mode: 'request',
654
- tokensThreshold: 500,
655
- minTurns: 3,
656
- cooldownMinutes: 0,
657
- keepTurns: 5,
658
- keepTokens: 1_000_000,
659
- appExe: 'C:\\fake\\App.exe',
660
- profile: 'desktop',
661
- };
662
-
663
- // A disk-full writer leaves 12 bytes behind and throws. The tmp write is
664
- // inside writeRequestAtomic's try, so the partial file must be removed and
665
- // the final name must never appear.
666
- let injected = false;
667
- const fakeFs = Object.create(fs);
668
- fakeFs.writeFileSync = (target, data, opts) => {
669
- if (!injected && String(target).includes('.tmp-')) {
670
- fs.writeFileSync(target, String(data).slice(0, 12), opts);
671
- injected = true;
672
- const error = new Error('ENOSPC: no space left on device, write');
673
- error.code = 'ENOSPC';
674
- throw error;
675
- }
676
- return fs.writeFileSync(target, data, opts);
677
- };
678
- const failing = createAutoTruncator({ memoryRoot, autoTruncate: config, fs: fakeFs, now: () => Date.now() });
679
- const failed = failing.onTurnEnd({ sessionId: id, turn: 20, sessionPath: file });
680
- assert(injected, 'fake fs never reached the tmp write');
681
- assert(failed.status === 'request-failed' && failed.code === 'ENOSPC',
682
- `unexpected failure ${failed.status}/${failed.code}`);
683
- assert(!fs.existsSync(paths.requestPath), 'half-written request file is visible');
684
- const leftovers = fs.readdirSync(paths.logDir).filter((name) => name.includes('.tmp-'));
685
- assert(leftovers.length === 0, `tmp leftovers after ENOSPC: ${leftovers.join(', ')}`);
686
- assert(fileSha(file) === beforeSha, 'ENOSPC path wrote the session');
687
-
688
- // The next evaluation (real fs, same memory root) self-heals by publishing
689
- // a complete request instead of sticking at "corrupt" forever.
690
- const healthy = createAutoTruncator({ memoryRoot, autoTruncate: config, now: () => Date.now() });
691
- const healed = healthy.onTurnEnd({ sessionId: id, turn: 21, sessionPath: file });
692
- assert(healed.status === 'request-written', `second evaluation ${healed.status}/${healed.code ?? ''}`);
693
- const request = JSON.parse(fs.readFileSync(paths.requestPath, 'utf8'));
694
- assert(request.requestId && request.sessionId === id, 'healed request is incomplete');
695
- assert(fs.readdirSync(paths.logDir).every((name) => !name.includes('.tmp-')), 'second write left a tmp');
696
- return `ENOSPC -> no request, next turn wrote ${request.requestId.slice(0, 8)}`;
697
- });
698
-
699
- runCase('A15', '坏 request JSON:quarantine 保留证据并自愈重写;合法请求仍单飞', () => {
700
- const { id, file, memoryRoot } = writeFixture(TMP, 'request-corrupt');
701
- const paths = autoTruncatePaths(memoryRoot);
702
- fs.mkdirSync(paths.logDir, { recursive: true });
703
- const junk = '{"version":1,"requestId":"half';
704
- fs.writeFileSync(paths.requestPath, junk);
705
-
706
- const config = {
707
- enabled: true,
708
- mode: 'request',
709
- tokensThreshold: 500,
710
- minTurns: 3,
711
- cooldownMinutes: 0,
712
- keepTurns: 5,
713
- keepTokens: 1_000_000,
714
- appExe: 'C:\\fake\\App.exe',
715
- profile: 'desktop',
716
- };
717
- const truncator = createAutoTruncator({ memoryRoot, autoTruncate: config, now: () => Date.now() });
718
- const healed = truncator.onTurnEnd({ sessionId: id, turn: 20, sessionPath: file });
719
- assert(healed.status === 'request-written', `heal status ${healed.status}/${healed.code ?? ''}`);
720
-
721
- const quarantined = fs.readdirSync(paths.logDir)
722
- .filter((name) => /^auto-truncate\.request\.corrupt-.*\.json$/.test(name));
723
- assert(quarantined.length === 1, `quarantine files: ${quarantined.join(', ') || '(none)'}`);
724
- assert(fs.readFileSync(path.join(paths.logDir, quarantined[0]), 'utf8') === junk,
725
- 'quarantine did not preserve the corrupt bytes verbatim');
726
- assert(fs.existsSync(paths.requestPath), 'self-healing did not write a fresh request');
727
- const healedRequest = JSON.parse(fs.readFileSync(paths.requestPath, 'utf8'));
728
- assert(healedRequest.requestId && healedRequest.sessionId === id, 'healed request is incomplete');
729
-
730
- const entry = JSON.parse(readLogLines(memoryRoot)[0]);
731
- assert(entry.action === 'request-written', `log action ${entry.action}`);
732
- assert(entry.pendingState === 'quarantined', `pendingState ${entry.pendingState}`);
733
- assert(entry.quarantinedFile === path.join(paths.logDir, quarantined[0]), 'log lost the quarantine path');
734
-
735
- // A valid request still wins single-flight: no second heal, no overwrite.
736
- const bytes = fs.readFileSync(paths.requestPath);
737
- const second = createAutoTruncator({ memoryRoot, autoTruncate: config, now: () => Date.now() });
738
- const pending = second.onTurnEnd({ sessionId: id, turn: 21, sessionPath: file });
739
- assert(pending.status === 'request-pending' && pending.entry.pendingState === 'valid',
740
- `pending after heal ${pending.status}/${pending.entry?.pendingState}`);
741
- assert(fs.readFileSync(paths.requestPath).equals(bytes), 'pending evaluation overwrote the healed request');
742
- return `quarantined ${quarantined[0]}, then ${entry.requestId.slice(0, 8)}`;
743
- });
744
-
745
- runCase('A13', 'truncate-cli:成功单行 JSON;坏文件/缺 confirm 退出 2 且不留半写', () => {
746
- const fixture = writeFixture(TMP, 'cli-cut');
747
- const beforeSha = fileSha(fixture.file);
748
- const cli = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'scripts', 'truncate-cli.mjs');
749
- // rc.2: truncate-cli.mjs refuses a --session outside <DSH_HOME>/sessions.
750
- const run = (args) => spawnSync(process.execPath, [cli, ...args], {
751
- encoding: 'utf8',
752
- timeout: 120_000,
753
- env: { ...process.env, DSH_HOME: fixture.home },
754
- });
755
-
756
- const ok = run(['--session', fixture.file, '--keep-turns', '5', '--keep-tokens', '1000000',
757
- '--confirm', VISIBLE_CONFIRM_WORD]);
758
- assert(ok.status === 0, `cli exit ${ok.status}: ${ok.stdout.slice(0, 300)} ${ok.stderr}`);
759
- assert(ok.stdout.trim().split('\n').length === 1, `stdout is not one line: ${ok.stdout}`);
760
- const out = JSON.parse(ok.stdout.trim());
761
- assert(out.ok === true && out.needed === true && out.applied === true && out.status === 'truncated',
762
- `unexpected cli result ${out.status}`);
763
- assert(out.before.sha256 === beforeSha, 'cli before sha mismatch');
764
- assert(out.after.bytes === fs.statSync(fixture.file).size, 'cli after bytes mismatch');
765
- assert(out.bytes.before === out.before.bytes && out.bytes.after === out.after.bytes, 'bytes block mismatch');
766
- assert(out.archivePath && fs.existsSync(out.archivePath), 'cli archive missing');
767
- assert(out.backupPath && fs.existsSync(out.backupPath), 'cli backup missing');
768
- assert(out.verify.ok === true && out.verify.messages === out.after.messages, 'cli read-back verify missing');
769
- assert(fileSha(fixture.file) === out.after.sha256, 'cli result does not match the file');
770
- assert(!fs.existsSync(inflightPathFor(fixture.file)), 'cli left an inflight record');
771
-
772
- const again = run(['--session', fixture.file, '--keep-turns', '5', '--keep-tokens', '1000000',
773
- '--confirm', VISIBLE_CONFIRM_WORD]);
774
- assert(again.status === 0, `noop exit ${again.status}: ${again.stderr}`);
775
- const noop = JSON.parse(again.stdout.trim());
776
- assert(noop.ok === true && noop.needed === false && noop.applied === false, 'second run is not a noop');
777
- assert(noop.bytes.before === noop.bytes.after, 'noop changed the file');
778
-
779
- const badDir = path.join(fixture.home, 'sessions', 'scope-fixtures', 'cli-bad');
780
- fs.mkdirSync(badDir, { recursive: true });
781
- const bad = path.join(badDir, 'session.v4.jsonl.zstd');
782
- fs.writeFileSync(bad, 'not a zstd session\n');
783
- const badSha = fileSha(bad);
784
- const failed = run(['--session', bad, '--keep-turns', '5', '--keep-tokens', '1000',
785
- '--confirm', VISIBLE_CONFIRM_WORD]);
786
- assert(failed.status === 2, `bad file exit ${failed.status}: ${failed.stdout}`);
787
- assert(failed.stdout.trim().split('\n').length === 1, 'bad file stdout is not one line');
788
- const failJson = JSON.parse(failed.stdout.trim());
789
- assert(failJson.ok === false && typeof failJson.code === 'string' && failJson.message, 'bad file JSON');
790
- assert(fileSha(bad) === badSha, 'bad file changed');
791
- assert(!fs.existsSync(inflightPathFor(bad)), 'bad file left an inflight record');
792
- assert(fs.readdirSync(badDir).every((name) => !name.includes('.truncate-visible.tmp-')),
793
- 'bad file left a tmp record');
794
-
795
- const fresh = writeFixture(TMP, 'cli-noconfirm');
796
- const freshSha = fileSha(fresh.file);
797
- const noConfirm = run(['--session', fresh.file, '--keep-turns', '5', '--keep-tokens', '1000000']);
798
- assert(noConfirm.status === 2, `missing confirm exit ${noConfirm.status}`);
799
- const nc = JSON.parse(noConfirm.stdout.trim());
800
- assert(nc.code === 'CONFIRM_REQUIRED', 'missing confirm code');
801
- assert(fileSha(fresh.file) === freshSha, 'missing confirm wrote the session');
802
- assert(!fs.existsSync(archiveDirFor(fresh.file)), 'missing confirm created an archive');
803
- return 'ok one-line JSON; bad input exit 2 with no tmp/inflight; confirm required';
804
- });
805
-
806
- // -------------------------------------------------------------------------
807
- // A17–A20: 0.8.0-rc.11 — infeasible plans are recorded, requests are only
808
- // written after the cut has been built, and an unexpected exception leaves a
809
- // log line instead of vanishing into {status:'error'}.
810
- // -------------------------------------------------------------------------
811
-
812
- function writeHeadHeavyFixture(name) {
813
- const fixture = writeFixture(TMP, name);
814
- const prompt = fixture.events.find((event) => event.type === 'system/message');
815
- prompt.data.message.content[0].text = 'H'.repeat(8_000); // ~2,000 tokens of head
816
- fs.writeFileSync(fixture.file, encodeSession(fixture.header, fixture.events));
817
- return fixture;
818
- }
819
-
820
- runCase('A17', 'auto dryrun 不可行:写 dryrun-infeasible 日志行,带 code/attempts,会话不变', () => {
821
- const { id, file, memoryRoot } = writeHeadHeavyFixture('dryrun-infeasible');
822
- const beforeSha = fileSha(file);
823
- const truncator = createAutoTruncator({
824
- memoryRoot,
825
- autoTruncate: { enabled: true, mode: 'dryrun', tokensThreshold: 500, minTurns: 3, keepTurns: 6, keepTokens: 100 },
826
- now: clock(),
827
- });
828
- const status = truncator.onTurnEnd({ sessionId: id, turn: 20, sessionPath: file });
829
- assert(status.status === 'dryrun-infeasible', `status ${status.status}`);
830
- assert(status.action === 'dryrun-infeasible', `action ${status.action}`);
831
- assert(status.code === 'VISIBLE_TOKEN_BUDGET', `code ${status.code}`);
832
- assert(fileSha(file) === beforeSha, 'infeasible dryrun wrote the session');
833
-
834
- const lines = readLogLines(memoryRoot);
835
- assert(lines.length === 1, `expected one log line, got ${lines.length}`);
836
- const entry = JSON.parse(lines[0]);
837
- assert(entry.action === 'dryrun-infeasible', `entry action ${entry.action}`);
838
- assert(entry.feasible === false, 'entry claims feasible');
839
- assert(entry.code === 'VISIBLE_TOKEN_BUDGET', `entry code ${entry.code}`);
840
- assert(typeof entry.reason === 'string' && entry.reason.length > 0, 'entry has no reason');
841
- assert(Array.isArray(entry.attempts) && entry.attempts.length >= 1, 'entry has no attempts');
842
- assert(entry.plan.needed === true && entry.plan.feasible === false, 'entry plan does not say infeasible');
843
- assert(entry.wroteSessionFile === false, 'entry claims a write');
844
- return `infeasible ${entry.code} after ${entry.attempts.length} attempt(s), logged`;
845
- });
846
-
847
- runCase('A18', 'auto request 不可行:不写请求文件,写 request-infeasible 日志行', () => {
848
- const { id, file, memoryRoot } = writeHeadHeavyFixture('request-infeasible');
849
- const beforeSha = fileSha(file);
850
- const truncator = createAutoTruncator({
851
- memoryRoot,
852
- autoTruncate: { enabled: true,
853
- mode: 'request', tokensThreshold: 500, minTurns: 3, keepTurns: 6, keepTokens: 100,
854
- appExe: 'C:\\fake\\DeepSeek Harness.exe', profile: 'desktop',
855
- },
856
- now: clock(),
857
- });
858
- const status = truncator.onTurnEnd({ sessionId: id, turn: 20, sessionPath: file });
859
- assert(status.status === 'request-infeasible', `status ${status.status} (${status.code ?? ''})`);
860
- assert(status.action === 'request-infeasible', `action ${status.action}`);
861
- assert(status.code === 'VISIBLE_TOKEN_BUDGET', `code ${status.code}`);
862
- assert(!fs.existsSync(truncator.requestPath), 'an impossible request was written');
863
- assert(fileSha(file) === beforeSha, 'request-infeasible wrote the session');
864
-
865
- const lines = readLogLines(memoryRoot);
866
- assert(lines.length === 1, `expected one log line, got ${lines.length}`);
867
- const entry = JSON.parse(lines[0]);
868
- assert(entry.action === 'request-infeasible' && entry.feasible === false, 'log line does not record infeasible');
869
- assert(entry.code === 'VISIBLE_TOKEN_BUDGET', `log code ${entry.code}`);
870
- assert(Array.isArray(entry.attempts) && entry.attempts.length >= 1, 'log has no attempts');
871
- return `no request file, logged ${entry.code}`;
872
- });
873
-
874
- runCase('A19', 'auto request 只在裁剪构建成功后写:projectedTokens 等于实际裁剪估算', () => {
875
- const { id, file, memoryRoot } = writeFixture(TMP, 'request-verified');
876
- const truncator = createAutoTruncator({
877
- memoryRoot,
878
- autoTruncate: { enabled: true,
879
- mode: 'request', tokensThreshold: 500, minTurns: 3, keepTurns: 5, keepTokens: 1_000_000,
880
- appExe: 'C:\\fake\\DeepSeek Harness.exe', profile: 'desktop',
881
- },
882
- now: clock(),
883
- });
884
- const status = truncator.onTurnEnd({ sessionId: id, turn: 20, sessionPath: file });
885
- assert(status.status === 'request-written', `status ${status.status} (${status.code ?? ''})`);
886
- const request = JSON.parse(fs.readFileSync(truncator.requestPath, 'utf8'));
887
- assert(request.plan.feasible === true, 'request plan is not feasible');
888
- assert(request.plan.firstUserCapChars === AUTO_TRUNCATE_DEFAULTS.firstUserCapChars,
889
- `request cap ${request.plan.firstUserCapChars}`);
890
- assert(request.plan.attempts >= 1, `request attempts ${request.plan.attempts}`);
891
- const preview = truncateVisibleSession(file, {
892
- dryRun: true, keepTurns: 5, keepTokens: 1_000_000,
893
- });
894
- assert(request.plan.projectedTokens === preview.after.tokens,
895
- `request projectedTokens ${request.plan.projectedTokens} != built ${preview.after.tokens}`);
896
- assert(request.plan.projectedTokens <= Math.ceil(1_000_000 * 1.05), 'request projects over budget');
897
- const entry = JSON.parse(readLogLines(memoryRoot).at(-1));
898
- assert(entry.plan.projected.afterTokensEstimate === request.plan.projectedTokens,
899
- 'log entry and request disagree on the projection');
900
- return `request ${request.requestId.slice(0, 8)}, projected ${request.plan.projectedTokens}`;
901
- });
902
-
903
- runCase('A20', 'auto 意外异常:写 action:error 日志行,返回结构化错误而不抛', () => {
904
- const { id, file, memoryRoot } = writeFixture(TMP, 'evaluate-error');
905
- fs.writeFileSync(file, 'not a zstd session at all\n');
906
- const beforeSha = fileSha(file);
907
- const truncator = createAutoTruncator({
908
- memoryRoot, autoTruncate: { enabled: true, mode: 'dryrun', tokensThreshold: 500, minTurns: 3 }, now: clock(),
909
- });
910
- const status = truncator.onTurnEnd({ sessionId: id, turn: 20, sessionPath: file });
911
- assert(status.status === 'error', `status ${status.status}`);
912
- assert(status.reason === 'exception', `reason ${status.reason}`);
913
- assert(typeof status.code === 'string' && status.code.length > 0, 'error has no code');
914
- assert(typeof status.message === 'string' && status.message.length > 0, 'error has no message');
915
- assert(status.logPath && fs.existsSync(status.logPath), 'error was not logged');
916
- const lines = readLogLines(memoryRoot);
917
- assert(lines.length === 1, `expected one error line, got ${lines.length}`);
918
- const entry = JSON.parse(lines[0]);
919
- assert(entry.action === 'error', `entry action ${entry.action}`);
920
- assert(entry.code === status.code, 'entry code differs from return value');
921
- assert(typeof entry.message === 'string' && entry.message.length > 0, 'entry has no message');
922
- assert(entry.wroteSessionFile === false, 'error entry claims a write');
923
- assert(fileSha(file) === beforeSha, 'error path rewrote the corrupt file');
924
- return `logged ${status.code}`;
925
- });
926
- }
927
-
928
- export const AUTO_SUITE_CASES = [
929
- 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'A9', 'A10', 'A11', 'A12', 'A13', 'A16',
930
- 'A17', 'A18', 'A19', 'A20',
931
- ];