@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.
Files changed (289) hide show
  1. package/CHANGELOG.md +70 -1508
  2. package/LICENSE +1 -1
  3. package/QUICKSTART.md +34 -13
  4. package/README.en.md +18 -7
  5. package/README.md +34 -9
  6. package/SPEC.md +5 -5
  7. package/cordis.patch.yml +23 -9
  8. package/docs/ANSWER-GUARD.md +92 -0
  9. package/docs/ARCHITECTURE.md +4 -3
  10. package/docs/AUTO-RECALL-WIRING.md +1 -1
  11. package/docs/AUTO-RECALL.md +15 -9
  12. package/docs/CONFIG.md +168 -35
  13. package/docs/ERRORS.md +17 -5
  14. package/docs/FAQ.md +7 -7
  15. package/docs/FEATURES.md +96 -28
  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 +4 -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 +47 -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 +760 -0
  41. package/src/activity/model.js +351 -0
  42. package/src/activity/store.js +644 -0
  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 +171 -47
  58. package/src/deps.js +6 -4
  59. package/src/features.js +182 -6
  60. package/src/heartbeat.js +156 -23
  61. package/src/identity/handover.js +52 -1
  62. package/src/identity/index.js +13 -5
  63. package/src/identity/inject-position.js +2 -2
  64. package/src/index.js +97 -7
  65. package/src/lifecycle/gap-clocks.js +328 -0
  66. package/src/lifecycle/index.js +269 -0
  67. package/src/live.js +22 -2
  68. package/src/memory/activity-capture.js +229 -0
  69. package/src/memory/anchors.js +194 -0
  70. package/src/memory/audit-records.js +222 -0
  71. package/src/memory/auto-cards.js +401 -0
  72. package/src/memory/capture.js +442 -0
  73. package/src/memory/card-anchors.js +203 -0
  74. package/src/memory/conflicts.js +106 -0
  75. package/src/memory/decay.js +311 -0
  76. package/src/memory/distill.js +471 -0
  77. package/src/memory/event-index.js +917 -0
  78. package/src/memory/evidence-chain.js +295 -0
  79. package/src/memory/evidence.js +145 -0
  80. package/src/memory/filter-runner.js +1 -1
  81. package/src/memory/filter.js +5 -1
  82. package/src/memory/forget-v2.js +410 -0
  83. package/src/memory/forget.js +71 -0
  84. package/src/memory/frames-activation.js +247 -0
  85. package/src/memory/fts-query.js +174 -0
  86. package/src/memory/governance.js +604 -0
  87. package/src/memory/index.js +1 -0
  88. package/src/memory/l2-gate.js +169 -0
  89. package/src/memory/lock.js +121 -0
  90. package/src/memory/migrate.js +139 -0
  91. package/src/memory/recall-v2.js +223 -0
  92. package/src/memory/recall.js +65 -2
  93. package/src/memory/records.js +425 -0
  94. package/src/memory/retention.js +128 -0
  95. package/src/memory/review.js +124 -0
  96. package/src/memory/trust.js +88 -0
  97. package/src/memory/version-chain.js +264 -0
  98. package/src/memory/wal.js +137 -0
  99. package/src/memory/working-frame.js +516 -0
  100. package/src/metrics/classify.mjs +5 -3
  101. package/src/metrics/index.mjs +21 -1
  102. package/src/metrics/prestep-latency.mjs +300 -0
  103. package/src/metrics/store.mjs +25 -0
  104. package/src/policy-profile.js +18 -3
  105. package/src/recall/anaphora.mjs +87 -0
  106. package/src/recall/cards.mjs +7 -0
  107. package/src/recall/embedding.mjs +8 -8
  108. package/src/recall/entities.mjs +112 -0
  109. package/src/recall/index.js +235 -19
  110. package/src/recall/inject-order.mjs +10 -8
  111. package/src/recall/privacy.mjs +105 -16
  112. package/src/recall/recall-core.mjs +116 -10
  113. package/src/recall/shared-visibility.js +302 -0
  114. package/src/recall/time-normalizer.mjs +196 -0
  115. package/src/role/activation.js +191 -0
  116. package/src/role/attention.js +318 -0
  117. package/src/role/base.js +36 -0
  118. package/src/role/channels.js +423 -0
  119. package/src/role/index.js +425 -0
  120. package/src/role/interfaces.js +115 -0
  121. package/src/role/personality.js +370 -0
  122. package/src/role/readers.js +151 -0
  123. package/src/role/relationships.js +477 -0
  124. package/src/role/store.js +202 -0
  125. package/src/role/writeprotect.js +373 -0
  126. package/src/router/aliases.json +176 -25
  127. package/src/router/background/agent-runner.mjs +1 -1
  128. package/src/router/background/anchor.mjs +1 -1
  129. package/src/router/background/audit.mjs +2 -2
  130. package/src/router/background/budget-ledger.mjs +2 -2
  131. package/src/router/background/host-sim.mjs +1 -1
  132. package/src/router/background/memory.mjs +4 -4
  133. package/src/router/background/queue.mjs +1 -1
  134. package/src/router/background/retry.mjs +1 -1
  135. package/src/router/background/router.mjs +1 -1
  136. package/src/router/background/stream.mjs +1 -1
  137. package/src/router/background/tool-policy.mjs +1 -1
  138. package/src/router/design-headings.json +5 -5
  139. package/src/router/face/config.mjs +1 -1
  140. package/src/router/face/identity.mjs +3 -3
  141. package/src/router/judge.mjs +8 -7
  142. package/src/router/policies/generic.json +21 -4
  143. package/src/router/route.js +109 -22
  144. package/src/router/router.mjs +10 -6
  145. package/src/router/routing-rules.json +260 -445
  146. package/src/router/run-sim.mjs +8 -8
  147. package/src/router/runtime.js +23 -12
  148. package/src/router/service/board.mjs +95 -15
  149. package/src/router/service/config.mjs +5 -5
  150. package/src/router/service/context.mjs +1 -1
  151. package/src/router/service/hint.mjs +14 -0
  152. package/src/router/service/queue.mjs +1 -1
  153. package/src/router/service/service.mjs +27 -11
  154. package/src/router/shadow.mjs +4 -3
  155. package/src/surgery-recovery.js +2 -2
  156. package/src/tool-output.js +2 -2
  157. package/src/tools.js +39 -7
  158. package/src/truncate-visible.js +2 -2
  159. package/src/ui/actions.js +1312 -0
  160. package/src/ui/panel-api.js +367 -0
  161. package/src/ui/panel-auth.js +251 -0
  162. package/src/ui/panel-integrity.js +243 -0
  163. package/src/ui/routes-readonly.js +695 -0
  164. package/src/ui/routes.js +3 -0
  165. package/docs/DEV.md +0 -279
  166. package/docs/PRESENCE-BUS-WIRING.md +0 -491
  167. package/docs/PRESENCE-BUS.md +0 -694
  168. package/docs/SURGERY.md +0 -186
  169. package/scripts/mark-core-cards.mjs +0 -289
  170. package/scripts/pack.mjs +0 -392
  171. package/scripts/router-proposals.mjs +0 -386
  172. package/src/router/fixtures/M1.json +0 -16
  173. package/src/router/fixtures/M2.json +0 -16
  174. package/src/router/fixtures/M3.json +0 -20
  175. package/src/router/fixtures/M4.json +0 -20
  176. package/src/router/fixtures/M5.json +0 -45
  177. package/src/router/fixtures/M6.json +0 -53
  178. package/src/router/fixtures/M7.json +0 -46
  179. package/src/router/fixtures/S1.json +0 -20
  180. package/src/router/fixtures/S2.json +0 -23
  181. package/src/router/fixtures/S3.json +0 -20
  182. package/src/router/fixtures/S4.json +0 -34
  183. package/src/router/fixtures/S5.json +0 -43
  184. package/src/router/fixtures/S6.json +0 -47
  185. package/src/router/fixtures/T1.json +0 -23
  186. package/src/router/fixtures/T2.json +0 -16
  187. package/src/router/fixtures/T3.json +0 -19
  188. package/src/router/fixtures/T4.json +0 -16
  189. package/src/router/fixtures/X1.json +0 -17
  190. package/src/router/fixtures/X2.json +0 -20
  191. package/src/router/gen-design-headings.mjs +0 -107
  192. package/src/router/policies/owner-rulings-2026-11-03.json +0 -62
  193. package/test/auto-recall.test.mjs +0 -474
  194. package/test/auto-truncate.test.mjs +0 -931
  195. package/test/autobind.test.mjs +0 -385
  196. package/test/bus.test.mjs +0 -1572
  197. package/test/cli-guard.test.mjs +0 -198
  198. package/test/conclusion.test.mjs +0 -408
  199. package/test/config-schema.test.mjs +0 -204
  200. package/test/d6-output.test.mjs +0 -194
  201. package/test/d6.test.mjs +0 -395
  202. package/test/deps.test.mjs +0 -342
  203. package/test/doctor-setup.test.mjs +0 -297
  204. package/test/embedding-recall.test.mjs +0 -347
  205. package/test/feature-flags.test.mjs +0 -568
  206. package/test/filter-shadow.test.mjs +0 -170
  207. package/test/fixtures/baseline-0.8.0-registration.json +0 -556
  208. package/test/fixtures/d6-header-tools.json +0 -1
  209. package/test/fixtures/lock-child.mjs +0 -67
  210. package/test/fixtures/pre-step-container.mjs +0 -100
  211. package/test/fixtures/privacy-memory/topics/pii-unmarked.md +0 -9
  212. package/test/fixtures/privacy-memory/topics/secret-local-only.md +0 -11
  213. package/test/fixtures/profile-session-longlive-config.json +0 -20
  214. package/test/fixtures/proposal-cas-child.mjs +0 -66
  215. package/test/host-engine-status.test.mjs +0 -307
  216. package/test/hot-truncate.test.mjs +0 -1349
  217. package/test/identity-card-marker.test.mjs +0 -307
  218. package/test/identity-router/run.mjs +0 -721
  219. package/test/integration-pre-step.test.mjs +0 -553
  220. package/test/live.test.mjs +0 -1020
  221. package/test/maintenance-schedule.test.mjs +0 -538
  222. package/test/memory.test.mjs +0 -2828
  223. package/test/metrics.test.mjs +0 -478
  224. package/test/orchestrator.test.mjs +0 -266
  225. package/test/p1_probe.mjs +0 -97
  226. package/test/packaging.test.mjs +0 -182
  227. package/test/portability.test.mjs +0 -343
  228. package/test/rc4-regressions.test.mjs +0 -562
  229. package/test/rc5-regressions.test.mjs +0 -197
  230. package/test/rc6-chinese.test.mjs +0 -394
  231. package/test/router-1100/apply-off.test.mjs +0 -175
  232. package/test/router-1100/budget-reconcile.test.mjs +0 -215
  233. package/test/router-1100/config-context.test.mjs +0 -211
  234. package/test/router-1100/helpers.mjs +0 -129
  235. package/test/router-1100/hint-envelope.test.mjs +0 -150
  236. package/test/router-1100/lock-crossproc.test.mjs +0 -206
  237. package/test/router-1100/proposal-cas-crossproc.test.mjs +0 -184
  238. package/test/router-1100/router-apply.test.mjs +0 -372
  239. package/test/router-1100/router-fixb.test.mjs +0 -602
  240. package/test/router-1100/router-proposals.test.mjs +0 -405
  241. package/test/router-1100/router-queue-lease-wal.test.mjs +0 -355
  242. package/test/router-1100/router-security-cr.test.mjs +0 -333
  243. package/test/router-1100/service-lifecycle.test.mjs +0 -220
  244. package/test/router-1100/tools-contract.test.mjs +0 -164
  245. package/test/router-1100/turn-reflect-tick.test.mjs +0 -89
  246. package/test/router-1100/v6-contract.test.mjs +0 -158
  247. package/test/router-1100/v6b-contract.test.mjs +0 -293
  248. package/test/router-1100/v6c-contract.test.mjs +0 -249
  249. package/test/router-1100/wal-rotation.test.mjs +0 -375
  250. package/test/router-1100/wp1-config.test.mjs +0 -170
  251. package/test/router-1100/wp1-default-off.test.mjs +0 -77
  252. package/test/router-1100/wp1-model-status.test.mjs +0 -90
  253. package/test/router-1100/wp1-status.test.mjs +0 -220
  254. package/test/router-1100/wp1-tools.test.mjs +0 -146
  255. package/test/router-1100/wp5-cli.test.mjs +0 -240
  256. package/test/router-1100/wp5-model-auto.test.mjs +0 -418
  257. package/test/router-1100/wp6-merge.test.mjs +0 -386
  258. package/test/router-1100/wp6-wake.test.mjs +0 -502
  259. package/test/router-background/audit.test.mjs +0 -37
  260. package/test/router-background/budget-ledger.test.mjs +0 -330
  261. package/test/router-background/cross-process.test.mjs +0 -222
  262. package/test/router-background/fixtures/cross-child.mjs +0 -85
  263. package/test/router-background/fixtures/real-shapes.mjs +0 -239
  264. package/test/router-background/router.test.mjs +0 -1044
  265. package/test/router-background/stream-retry.test.mjs +0 -358
  266. package/test/router-background/tool-agent.test.mjs +0 -384
  267. package/test/router-face/bridge.test.mjs +0 -169
  268. package/test/router-face/face.test.mjs +0 -316
  269. package/test/router-failclosed.test.mjs +0 -466
  270. package/test/router-identity.test.mjs +0 -384
  271. package/test/router-l1-l2.contract.test.mjs +0 -1075
  272. package/test/router-memory-tools.test.mjs +0 -262
  273. package/test/router-policy.test.mjs +0 -225
  274. package/test/router-runtime.test.mjs +0 -438
  275. package/test/router-shadow.test.mjs +0 -287
  276. package/test/router.test.mjs +0 -903
  277. package/test/run-rc.mjs +0 -299
  278. package/test/run.mjs +0 -2469
  279. package/test/safety-defaults.test.mjs +0 -179
  280. package/test/seeded-load.test.mjs +0 -436
  281. package/test/session-original.test.mjs +0 -338
  282. package/test/surgery-recovery.test.mjs +0 -936
  283. package/test/t7_drive.mjs +0 -151
  284. package/test/tool-output.test.mjs +0 -393
  285. package/test/tool-schema.test.mjs +0 -177
  286. package/test/tools_contract.test.mjs +0 -716
  287. package/test/truncate-visible.test.mjs +0 -1150
  288. package/test/ui-flags.test.mjs +0 -477
  289. package/test/v4-hardening.test.mjs +0 -427
@@ -1,1020 +0,0 @@
1
- // Live session registry tests (L0-L9).
2
- //
3
- // The registry is a cross-process, crash-tolerant table, so these cases write
4
- // real files under the harness tmp directory and L3 runs real child processes.
5
- // Nothing here writes inside the package tree (P6 checks that afterwards),
6
- // reads credentials, or touches the network.
7
-
8
- import fs from 'node:fs';
9
- import os from 'node:os';
10
- import path from 'node:path';
11
- import crypto from 'node:crypto';
12
- import { spawn } from 'node:child_process';
13
-
14
- import {
15
- LIVE_SCHEMA_VERSION,
16
- LIVE_CONFIRM,
17
- LIVE_RECORD_FIELDS,
18
- GOAL_MAX_CHARS,
19
- pidAlive,
20
- liveFile,
21
- liveUpdate,
22
- liveList,
23
- liveGet,
24
- livePrune,
25
- } from '../src/live.js';
26
- import { TOOLS } from '../src/tools.js';
27
-
28
- const LIVE_MODULE_URL = new URL('../src/live.js', import.meta.url).href;
29
- const SUITE = 'live-suite';
30
- const NOW = Date.parse('2026-05-06T07:08:09.000Z');
31
- const HOST = os.hostname();
32
- const REMOTE_HOST = 'live-test-remote-host';
33
- const FAKE_PID = 0x7ffffff0;
34
-
35
- function iso(ms) {
36
- return new Date(ms).toISOString();
37
- }
38
-
39
- function sha256(bytes) {
40
- return crypto.createHash('sha256').update(bytes).digest('hex');
41
- }
42
-
43
- function liveDirOf(root) {
44
- return path.join(root, '.longlive', 'live');
45
- }
46
-
47
- function newRoot(TMP, name) {
48
- const root = path.join(TMP, SUITE, name);
49
- fs.mkdirSync(root, { recursive: true });
50
- return root;
51
- }
52
-
53
- /** One complete row with every field, ready to be tweaked per case. */
54
- function makeRecord(overrides = {}) {
55
- return {
56
- schemaVersion: LIVE_SCHEMA_VERSION,
57
- sessionId: 'row',
58
- pid: process.pid,
59
- host: HOST,
60
- startedAt: iso(NOW),
61
- updatedAt: iso(NOW),
62
- heartbeatAt: iso(NOW),
63
- ttlMs: 60000,
64
- state: 'running',
65
- turn: 0,
66
- goal: '',
67
- blocked_on: '',
68
- queued: [],
69
- last_action: { at: iso(NOW), kind: 'test', detail: '' },
70
- ...overrides,
71
- };
72
- }
73
-
74
- function putRow(root, record) {
75
- const dir = liveDirOf(root);
76
- fs.mkdirSync(dir, { recursive: true });
77
- const file = path.join(dir, `${record.sessionId}.json`);
78
- fs.writeFileSync(file, `${JSON.stringify(record, null, 2)}\n`);
79
- return file;
80
- }
81
-
82
- /** name -> sha256 of every regular file, sorted, for byte-identical checks. */
83
- function snapshotFiles(dir) {
84
- const out = {};
85
- if (!fs.existsSync(dir)) return out;
86
- for (const name of fs.readdirSync(dir).sort()) {
87
- const full = path.join(dir, name);
88
- if (fs.statSync(full).isFile()) out[name] = sha256(fs.readFileSync(full));
89
- }
90
- return out;
91
- }
92
-
93
- /** Swap fs methods for one call; restores them even when the call throws. */
94
- function withFsPatch(patches, fn) {
95
- const originals = new Map();
96
- for (const [key, value] of Object.entries(patches)) {
97
- originals.set(key, fs[key]);
98
- fs[key] = value;
99
- }
100
- try {
101
- return fn();
102
- } finally {
103
- for (const [key, value] of originals) fs[key] = value;
104
- }
105
- }
106
-
107
- /** Run one child to completion without stdio pipes; results travel by file. */
108
- function runChild(script, args, timeoutMs = 60000) {
109
- return new Promise((resolve) => {
110
- const child = spawn(process.execPath, [script, ...args], { stdio: 'ignore', windowsHide: true });
111
- const timer = setTimeout(() => {
112
- try {
113
- child.kill();
114
- } catch {
115
- /* already gone */
116
- }
117
- resolve({ code: 'timeout', signal: null });
118
- }, timeoutMs);
119
- child.on('error', (error) => {
120
- clearTimeout(timer);
121
- resolve({ code: 'spawn-error', error: error.message });
122
- });
123
- child.on('exit', (code, signal) => {
124
- clearTimeout(timer);
125
- resolve({ code, signal });
126
- });
127
- });
128
- }
129
-
130
- // Each child patches the same row 12 times with a ~52 KB payload, so the
131
- // renames genuinely overlap. Results go to per-child files: a piped stdout can
132
- // be unavailable under Windows confinement, a file cannot.
133
- const WORKER_SOURCE = [
134
- "import fs from 'node:fs';",
135
- `import { liveUpdate } from ${JSON.stringify(LIVE_MODULE_URL)};`,
136
- '',
137
- "const [root, sessionId, index, outFile] = process.argv.slice(2);",
138
- "const queue = Array.from({ length: 300 }, (_, i) => 'q-' + index + '-' + i + '-' + 'x'.repeat(160));",
139
- 'let last = null;',
140
- 'try {',
141
- ' for (let round = 0; round < 12; round += 1) {',
142
- ' last = liveUpdate({',
143
- ' sessionId,',
144
- " state: round % 2 === 0 ? 'running' : 'waiting',",
145
- ' turn: round,',
146
- " goal: 'race ' + index + ':' + round,",
147
- ' queued: queue,',
148
- ' ttlMs: 60000,',
149
- ' }, { memoryRoot: root });',
150
- ' }',
151
- ' fs.writeFileSync(outFile, JSON.stringify({',
152
- ' ok: true, sha256: last.sha256, bytes: last.bytes,',
153
- " superseded: last.superseded, pid: process.pid, sessionId: last.sessionId,",
154
- ' }));',
155
- '} catch (error) {',
156
- ' fs.writeFileSync(outFile, JSON.stringify({',
157
- " ok: false, code: error.code ?? null, message: error.message,",
158
- ' }));',
159
- ' process.exitCode = 1;',
160
- '}',
161
- '',
162
- ].join('\n');
163
-
164
- export async function runLiveSuite({ runCase, runAsyncCase, runSymlinkCase, assert, expectCode, TMP }) {
165
- fs.mkdirSync(path.join(TMP, SUITE), { recursive: true });
166
-
167
- // L0 — wiring: the four tools exist and carry the documented schema.
168
- runCase('L0', '四个 session_live_* 已注册,state 必填且枚举只有五种声明态', () => {
169
- const names = [
170
- 'session_live_update',
171
- 'session_live_list',
172
- 'session_live_get',
173
- 'session_live_prune',
174
- ];
175
- for (const name of names) {
176
- assert(TOOLS.some((tool) => tool.name === name), `missing tool ${name}`);
177
- }
178
- const update = TOOLS.find((tool) => tool.name === 'session_live_update');
179
- assert(update.parameters.state.type === 'string', 'state must be a string');
180
- assert(
181
- JSON.stringify(update.parameters.state.enum)
182
- === JSON.stringify(['idle', 'running', 'waiting', 'blocked', 'stale']),
183
- `state enum must be the five declared states, got ${JSON.stringify(update.parameters.state.enum)}`,
184
- );
185
- assert(update.parameters.sessionId, 'sessionId schema must exist');
186
- const list = TOOLS.find((tool) => tool.name === 'session_live_list');
187
- assert(list.parameters.includeDead.type === 'boolean', 'includeDead schema');
188
- const get = TOOLS.find((tool) => tool.name === 'session_live_get');
189
- assert(get.parameters.sessionId.type === 'string', 'get sessionId schema');
190
- const prune = TOOLS.find((tool) => tool.name === 'session_live_prune');
191
- assert(prune.parameters.confirm.type === 'string', 'prune confirm schema');
192
- assert(prune.parameters.dryRun.type === 'boolean', 'prune dryRun schema');
193
-
194
- const root = newRoot(TMP, 'l0');
195
- const written = update.invoke({ sessionId: 's-l0', state: 'idle' }, { memoryRoot: root });
196
- assert(written.ok && written.created === true, 'registered invoke must write through live.js');
197
- return '4 tools registered; state enum = 5 declared states';
198
- });
199
-
200
- // L1 — round-trip, exact field set, patch semantics, goal truncation.
201
- runCase('L1', '写读往返:14 字段齐全,patch 保留旧值,goal 截断并标注', () => {
202
- const root = newRoot(TMP, 'l1');
203
- const sessionId = 's-l1';
204
- const longGoal = '一二三四五六七八九十'.repeat(9); // 90 code points
205
- const first = liveUpdate({
206
- sessionId,
207
- state: 'blocked',
208
- turn: 7,
209
- goal: longGoal,
210
- blocked_on: 'waiting for review',
211
- queued: ['a', 'b', 'c'],
212
- ttlMs: 120000,
213
- last_action: { at: iso(NOW), kind: 'edit', detail: 'first write' },
214
- }, { memoryRoot: root, now: NOW });
215
-
216
- assert(first.ok === true && first.created === true, 'first write must create');
217
- assert(first.goalTruncated === true, 'long goal must be flagged as truncated');
218
- assert(first.goalChars === 90, `goalChars must be 90, got ${first.goalChars}`);
219
- assert(first.goalLimit === GOAL_MAX_CHARS, 'goalLimit');
220
- // Independent oracle: the literal first eight repetitions, NOT the same
221
- // Array.from().slice() expression the implementation uses.
222
- assert(
223
- first.record.goal === '一二三四五六七八九十'.repeat(8),
224
- 'stored goal must be the first 80 code points (literal expectation)',
225
- );
226
-
227
- const file = path.join(root, '.longlive', 'live', `${sessionId}.json`);
228
- assert(fs.existsSync(file), `row file must exist at ${file}`);
229
- const stored = JSON.parse(fs.readFileSync(file, 'utf8'));
230
- // Hard-coded field list: importing LIVE_RECORD_FIELDS would let a mutation
231
- // that drops a field pass, because the expectation would move with it.
232
- const DOCUMENTED_FIELDS = [
233
- 'schemaVersion', 'sessionId', 'pid', 'host', 'startedAt', 'updatedAt', 'heartbeatAt',
234
- 'ttlMs', 'state', 'turn', 'goal', 'blocked_on', 'queued', 'last_action',
235
- ];
236
- assert(
237
- JSON.stringify(Object.keys(stored)) === JSON.stringify(DOCUMENTED_FIELDS),
238
- `stored row must be exactly the 14 documented fields in order, got ${JSON.stringify(Object.keys(stored))}`,
239
- );
240
- assert(stored.schemaVersion === LIVE_SCHEMA_VERSION, 'schemaVersion');
241
- assert(stored.pid === process.pid, 'pid must be the writing process');
242
- assert(stored.host === HOST, 'host must be this machine');
243
- assert(stored.startedAt === iso(NOW), 'startedAt = now');
244
- assert(stored.updatedAt === iso(NOW) && stored.heartbeatAt === iso(NOW), 'updatedAt/heartbeatAt = now');
245
- assert(stored.state === 'blocked', 'state');
246
- assert(stored.turn === 7, 'turn');
247
- assert(stored.blocked_on === 'waiting for review', 'blocked_on while blocked');
248
- assert(JSON.stringify(stored.queued) === JSON.stringify(['a', 'b', 'c']), 'queued');
249
- assert(stored.ttlMs === 120000, 'ttlMs');
250
- assert(
251
- stored.last_action.at === iso(NOW)
252
- && stored.last_action.kind === 'edit'
253
- && stored.last_action.detail === 'first write',
254
- 'last_action',
255
- );
256
-
257
- // Patch: only state. Everything else is preserved; blocked_on is cleared
258
- // because the session is no longer blocked.
259
- const second = liveUpdate({ sessionId, state: 'running' }, { memoryRoot: root, now: NOW + 5000 });
260
- assert(second.created === false, 'second write is an update');
261
- assert(second.blockedOnCleared === true, 'blocked_on must be cleared when state != blocked');
262
- const patched = second.record;
263
- assert(patched.turn === 7, 'turn preserved by patch');
264
- assert(patched.goal === stored.goal, 'goal preserved by patch');
265
- assert(JSON.stringify(patched.queued) === JSON.stringify(['a', 'b', 'c']), 'queued preserved');
266
- assert(patched.blocked_on === '', 'blocked_on emptied');
267
- assert(patched.startedAt === iso(NOW), 'startedAt preserved across updates');
268
- assert(patched.updatedAt === iso(NOW + 5000), 'updatedAt moves');
269
- assert(patched.last_action.kind === 'edit', 'last_action preserved when omitted');
270
-
271
- const got = liveGet({ sessionId }, { memoryRoot: root, now: NOW + 5000 });
272
- assert(got.ok === true && got.found === true && got.status === 'ok', 'get ok');
273
- assert(got.live.effectiveState === 'running', `get effectiveState running, got ${got.live.effectiveState}`);
274
- assert(got.live.fileRel === '.longlive/live/s-l1.json', `fileRel, got ${got.live.fileRel}`);
275
- assert(got.live.pidAlive === true && got.live.sameHost === true, 'get reports liveness');
276
-
277
- const listed = liveList({}, { memoryRoot: root, now: NOW + 5000 });
278
- assert(listed.ok === true && listed.count === 1 && listed.scanned === 1, 'list count');
279
- assert(listed.entries[0].sessionId === sessionId, 'list sessionId');
280
- assert(listed.entries[0].goal === stored.goal, 'list goal matches stored');
281
- assert(listed.entries[0].ttlMs === 120000, 'list ttlMs');
282
- assert(listed.counts.running === 1, 'list counts.running');
283
-
284
- const names = fs.readdirSync(path.dirname(file)).sort();
285
- assert(
286
- JSON.stringify(names) === JSON.stringify([`${sessionId}.json`]),
287
- `registry dir must hold exactly one row, got ${names.join(',')}`,
288
- );
289
- return 'round-trip ok; goal 90 -> 80; blocked_on cleared on unblock';
290
- });
291
-
292
- // L2 — atomic write: a crash half-way leaves the previous complete row.
293
- runCase('L2', '原子写:写一半 / rename 失败 / 读回损坏都不留半个 JSON,旧文件仍可解析', () => {
294
- const root = newRoot(TMP, 'l2');
295
- const sessionId = 's-atomic';
296
- liveUpdate(
297
- { sessionId, state: 'running', turn: 1, goal: 'before' },
298
- { memoryRoot: root, now: NOW },
299
- );
300
- const file = liveFile(root, sessionId);
301
- const beforeText = fs.readFileSync(file, 'utf8');
302
- const realWrite = fs.writeFileSync;
303
- const realRead = fs.readFileSync;
304
-
305
- // (a) the tmp write explodes before it completes
306
- expectCode(() => withFsPatch({
307
- writeFileSync: (...args) => {
308
- if (String(args[0]).includes('.tmp-')) {
309
- throw Object.assign(new Error('injected half write'), { code: 'EIO' });
310
- }
311
- return realWrite(...args);
312
- },
313
- }, () => liveUpdate(
314
- { sessionId, state: 'running', turn: 2 },
315
- { memoryRoot: root, now: NOW + 1000 },
316
- )), 'E_LIVE_WRITE');
317
- assert(fs.readFileSync(file, 'utf8') === beforeText, 'failed tmp write must leave the old row byte-identical');
318
- assert(JSON.parse(fs.readFileSync(file, 'utf8')).turn === 1, 'old row still parses');
319
-
320
- // (b) rename fails: the tmp is cleaned up and the old row survives
321
- expectCode(() => withFsPatch({
322
- renameSync: () => {
323
- throw Object.assign(new Error('injected rename failure'), { code: 'EIO' });
324
- },
325
- }, () => liveUpdate(
326
- { sessionId, state: 'waiting', turn: 3 },
327
- { memoryRoot: root, now: NOW + 2000 },
328
- )), 'E_LIVE_WRITE');
329
- assert(fs.readFileSync(file, 'utf8') === beforeText, 'failed rename must leave the old row byte-identical');
330
- assert(
331
- fs.readdirSync(path.dirname(file)).filter((name) => name.includes('.tmp-')).length === 0,
332
- 'failed rename must not leave a tmp file behind',
333
- );
334
-
335
- // (c) post-rename read-back is damaged: the old bytes are restored and the
336
- // call fails instead of reporting a write it cannot verify. Reads of the
337
- // target are: readPrior (1), writeLiveText prior (2), read-back (3).
338
- let targetReads = 0;
339
- const readBackError = expectCode(() => withFsPatch({
340
- readFileSync: (...args) => {
341
- if (args[0] === file) {
342
- targetReads += 1;
343
- if (targetReads === 3) return '{"half": ';
344
- }
345
- return realRead(...args);
346
- },
347
- }, () => liveUpdate(
348
- { sessionId, state: 'blocked', turn: 4 },
349
- { memoryRoot: root, now: NOW + 3000 },
350
- )), 'E_LIVE_WRITE');
351
- assert(readBackError.code === 'E_LIVE_WRITE', 'read-back failure is E_LIVE_WRITE');
352
- assert(fs.readFileSync(file, 'utf8') === beforeText, 'damaged read-back must restore the old row');
353
- assert(JSON.parse(fs.readFileSync(file, 'utf8')).turn === 1, 'restored row still parses');
354
-
355
- // and the registry is still writable afterwards
356
- const recovered = liveUpdate(
357
- { sessionId, state: 'running', turn: 5 },
358
- { memoryRoot: root, now: NOW + 4000 },
359
- );
360
- assert(recovered.ok === true && JSON.parse(fs.readFileSync(file, 'utf8')).turn === 5, 'write recovers');
361
- return 'tmp failure, rename failure and damaged read-back all keep the old complete row';
362
- });
363
-
364
- // L3 — real concurrent writers; the final file is one complete JSON row.
365
- await runAsyncCase('L3', '并发写同一会话:4 个真进程 x 12 次,最后是一份完整 JSON', async () => {
366
- const root = newRoot(TMP, 'l3');
367
- const sessionId = 's-race';
368
- const script = path.join(TMP, SUITE, 'l3-worker.mjs');
369
- fs.writeFileSync(script, WORKER_SOURCE);
370
-
371
- const children = [];
372
- for (let index = 0; index < 4; index += 1) {
373
- const out = path.join(TMP, SUITE, `l3-out-${index}.json`);
374
- children.push(runChild(script, [root, sessionId, String(index), out]).then((result) => ({ ...result, out })));
375
- }
376
- const finished = await Promise.all(children);
377
- for (const child of finished) {
378
- assert(fs.existsSync(child.out), `child wrote no result (code ${child.code})`);
379
- const result = JSON.parse(fs.readFileSync(child.out, 'utf8'));
380
- assert(result.ok === true, `child failed (exit ${child.code}): ${JSON.stringify(result)}`);
381
- assert(result.sessionId === sessionId, 'child wrote another row');
382
- }
383
-
384
- const file = liveFile(root, sessionId);
385
- const text = fs.readFileSync(file, 'utf8');
386
- // JSON.parse over the WHOLE text is the interleaving test: two payloads
387
- // mixed together would not parse.
388
- const record = JSON.parse(text);
389
- assert(record.sessionId === sessionId, 'final row sessionId');
390
- // MAX_QUEUED_ITEMS caps the row: 300 offered items become 200 stored ones.
391
- assert(Array.isArray(record.queued) && record.queued.length === 200, `final queued 200, got ${record.queued?.length}`);
392
- assert(record.queued.every((item) => typeof item === 'string' && item.startsWith('q-')), 'queue items intact');
393
- assert(record.queued.every((item) => [...item].length <= 300), 'each queued item is capped at 300 code points');
394
- assert(
395
- [...LIVE_RECORD_FIELDS].every((key) => key in record),
396
- 'final row has every field',
397
- );
398
- assert(text.trim().startsWith('{') && text.trim().endsWith('}'), 'file is exactly one JSON object');
399
- const leftovers = fs.readdirSync(path.dirname(file)).filter((name) => name.includes('.tmp-'));
400
- assert(leftovers.length === 0, `no orphan tmp files, got ${leftovers.join(',')}`);
401
- return `4 children x 12 writes; final ${Buffer.byteLength(text)} bytes parse as one row`;
402
- });
403
-
404
- // L4 — heartbeat bands: fresh wins over everything, stale starts after 2x.
405
- runCase('L4', '心跳带:ttl 内一律 running(pid 已死也是);> 2x ttl 才 stale', () => {
406
- const root = newRoot(TMP, 'l4');
407
- const ttl = 60000;
408
- putRow(root, makeRecord({
409
- sessionId: 's-boundary',
410
- ttlMs: ttl,
411
- heartbeatAt: iso(NOW - 2 * ttl),
412
- updatedAt: iso(NOW - 2 * ttl),
413
- }));
414
- putRow(root, makeRecord({
415
- sessionId: 's-stale',
416
- ttlMs: ttl,
417
- heartbeatAt: iso(NOW - 2 * ttl - 1),
418
- updatedAt: iso(NOW - 2 * ttl - 1),
419
- }));
420
- putRow(root, makeRecord({
421
- sessionId: 's-declared-stale',
422
- state: 'stale',
423
- heartbeatAt: iso(NOW - 10),
424
- updatedAt: iso(NOW - 10),
425
- }));
426
- // B4: the writer's pid is not the session's; a fresh heartbeat wins even
427
- // when that pid no longer exists.
428
- putRow(root, makeRecord({
429
- sessionId: 's-fresh-dead-pid',
430
- pid: FAKE_PID,
431
- heartbeatAt: iso(NOW - 10),
432
- updatedAt: iso(NOW - 10),
433
- }));
434
-
435
- const listed = liveList({}, { memoryRoot: root, now: NOW });
436
- const byId = Object.fromEntries(listed.entries.map((entry) => [entry.sessionId, entry]));
437
- assert(byId['s-boundary'].effectiveState === 'running', `age == 2x ttl stays running, got ${byId['s-boundary'].effectiveState}`);
438
- assert(byId['s-stale'].effectiveState === 'stale', 'age > 2x ttl must be stale');
439
- assert(byId['s-stale'].heartbeatAgeMs === 2 * ttl + 1, 'heartbeatAgeMs reported');
440
- assert(byId['s-declared-stale'].effectiveState === 'running', 'a fresh heartbeat overrides a declared stale');
441
- assert(byId['s-fresh-dead-pid'].effectiveState === 'running', 'fresh heartbeat must beat a dead pid');
442
- assert(byId['s-fresh-dead-pid'].pidAlive === false, 'the dead pid is still reported, just not decisive');
443
- assert(listed.counts.stale === 1, `counts.stale 1, got ${listed.counts.stale}`);
444
- assert(listed.counts.running === 3, `counts.running 3, got ${listed.counts.running}`);
445
-
446
- const got = liveGet({ sessionId: 's-stale' }, { memoryRoot: root, now: NOW });
447
- assert(got.live.effectiveState === 'stale', 'get must compute the same stale state');
448
- return 'age = 2x ttl -> running; age = 2x ttl + 1 -> stale; fresh heartbeat beats dead pid';
449
- });
450
-
451
- // L5 — dead needs old heartbeat or a definitively missing same-host pid.
452
- runCase('L5', 'dead 判定:>4x ttl 或同 host 死 pid;新心跳压过死 pid;跨 host 不探 pid', () => {
453
- const root = newRoot(TMP, 'l5');
454
- assert(pidAlive(FAKE_PID) === false, `fixture pid ${FAKE_PID} unexpectedly exists`);
455
- // Eight ttl of silence: dead without any pid evidence.
456
- putRow(root, makeRecord({
457
- sessionId: 's-dead',
458
- pid: FAKE_PID,
459
- host: HOST,
460
- heartbeatAt: iso(NOW - 500000),
461
- updatedAt: iso(NOW - 500000),
462
- }));
463
- // 1.17 ttl of silence, same host, pid definitively gone: pid accelerates it.
464
- putRow(root, makeRecord({
465
- sessionId: 's-pid-dead',
466
- pid: FAKE_PID,
467
- host: HOST,
468
- heartbeatAt: iso(NOW - 70000),
469
- updatedAt: iso(NOW - 70000),
470
- }));
471
- putRow(root, makeRecord({ sessionId: 's-fresh-dead-pid', pid: FAKE_PID, host: HOST }));
472
- putRow(root, makeRecord({ sessionId: 's-alive', pid: process.pid, host: HOST }));
473
- putRow(root, makeRecord({
474
- sessionId: 's-remote-dead',
475
- pid: FAKE_PID,
476
- host: REMOTE_HOST,
477
- heartbeatAt: iso(NOW - 500000),
478
- updatedAt: iso(NOW - 500000),
479
- }));
480
-
481
- const hidden = liveList({}, { memoryRoot: root, now: NOW });
482
- assert(!hidden.entries.some((entry) => entry.sessionId === 's-dead'), 'dead row hidden by default');
483
- assert(hidden.hiddenDead === 3, `hiddenDead 3, got ${hidden.hiddenDead}`);
484
- assert(hidden.counts.dead === 3, `counts.dead 3, got ${hidden.counts.dead}`);
485
- assert(hidden.entries.some((entry) => entry.sessionId === 's-fresh-dead-pid'), 'fresh heartbeat row stays visible');
486
-
487
- const all = liveList({ includeDead: true }, { memoryRoot: root, now: NOW });
488
- const byId = Object.fromEntries(all.entries.map((entry) => [entry.sessionId, entry]));
489
- assert(byId['s-dead'].effectiveState === 'dead', '>4x ttl -> dead');
490
- assert(byId['s-dead'].sameHost === true && byId['s-dead'].pidAlive === false, 'dead row liveness flags');
491
- assert(byId['s-pid-dead'].effectiveState === 'dead', 'same host + missing pid -> dead before 4x ttl');
492
- assert(byId['s-fresh-dead-pid'].effectiveState === 'running', 'fresh heartbeat must not be overruled by pid');
493
- assert(byId['s-remote-dead'].effectiveState === 'dead', 'remote row ages by heartbeat alone');
494
- assert(byId['s-remote-dead'].sameHost === false && byId['s-remote-dead'].pidAlive === null, 'remote pid must not be probed');
495
-
496
- const got = liveGet({ sessionId: 's-dead' }, { memoryRoot: root, now: NOW });
497
- assert(got.live.effectiveState === 'dead', 'get dead');
498
- return 'dead by 4x ttl or same-host dead pid; fresh heartbeat wins; remote pid never probed';
499
- });
500
-
501
- // L6 — corrupt rows are listed, named, and never break the list.
502
- runCase('L6', 'corrupt 文件不炸列表:坏 JSON 与 sessionId 不符都列为 corrupt', () => {
503
- const root = newRoot(TMP, 'l6');
504
- liveUpdate({ sessionId: 's-good', state: 'idle' }, { memoryRoot: root, now: NOW });
505
- const dir = liveDirOf(root);
506
- fs.writeFileSync(path.join(dir, 's-bad-json.json'), '{"schemaVersion": 1, "sessionId": "s-bad-json"');
507
- fs.writeFileSync(
508
- path.join(dir, 's-wrong-id.json'),
509
- `${JSON.stringify(makeRecord({ sessionId: 'someone-else' }))}\n`,
510
- );
511
- fs.writeFileSync(path.join(dir, 's-orphan.tmp-123'), 'not a record');
512
-
513
- const listed = liveList({}, { memoryRoot: root, now: NOW });
514
- assert(listed.ok === true, 'list must not throw on corrupt rows');
515
- assert(listed.count === 3, `3 rows (1 good + 2 corrupt), got ${listed.count}`);
516
- assert(listed.counts.corrupt === 2, `counts.corrupt 2, got ${listed.counts.corrupt}`);
517
- for (const id of ['s-bad-json', 's-wrong-id']) {
518
- const entry = listed.entries.find((item) => item.sessionId === id);
519
- assert(entry, `${id} must be listed`);
520
- assert(entry.effectiveState === 'corrupt', `${id} effectiveState corrupt`);
521
- assert(typeof entry.corruptReason === 'string' && entry.corruptReason.length > 0, `${id} corruptReason`);
522
- assert(
523
- entry.pid === null && entry.state === null && entry.last_action === null
524
- && Array.isArray(entry.queued) && entry.queued.length === 0,
525
- `${id} corrupt row shape`,
526
- );
527
- }
528
- assert(!listed.entries.some((entry) => entry.sessionId.includes('orphan')), 'tmp file is not a row');
529
-
530
- const error = expectCode(
531
- () => liveGet({ sessionId: 's-bad-json' }, { memoryRoot: root, now: NOW }),
532
- 'E_LIVE_CORRUPT',
533
- );
534
- assert(error.message.includes('s-bad-json'), `get error names the row: ${error.message}`);
535
- return '2 corrupt rows listed (bad JSON + wrong sessionId); tmp ignored';
536
- });
537
-
538
- // L7 — prune: dry-run by default, only dead/corrupt, never cross-host.
539
- runCase('L7', 'prune:默认 dry-run 零删除;confirm 只删 dead/corrupt,跨 host 与活 pid 的 stale 不动', () => {
540
- const root = newRoot(TMP, 'l7');
541
- const records = [
542
- // Eight ttl of silence: dead by heartbeat (pid evidence unnecessary).
543
- makeRecord({
544
- sessionId: 's-dead',
545
- pid: FAKE_PID,
546
- host: HOST,
547
- heartbeatAt: iso(NOW - 500000),
548
- updatedAt: iso(NOW - 500000),
549
- }),
550
- makeRecord({ sessionId: 's-live', pid: process.pid, host: HOST }),
551
- // 2.5 ttl: stale, but the same-host pid is alive, so it must be kept.
552
- makeRecord({
553
- sessionId: 's-stale-alive',
554
- pid: process.pid,
555
- host: HOST,
556
- heartbeatAt: iso(NOW - 150000),
557
- updatedAt: iso(NOW - 150000),
558
- }),
559
- makeRecord({ sessionId: 's-remote', pid: FAKE_PID, host: REMOTE_HOST }),
560
- // Cross-host stale: heartbeat says stale, never dead, and never pruned.
561
- makeRecord({
562
- sessionId: 's-remote-stale',
563
- pid: FAKE_PID,
564
- host: REMOTE_HOST,
565
- heartbeatAt: iso(NOW - 150000),
566
- updatedAt: iso(NOW - 150000),
567
- }),
568
- ];
569
- for (const record of records) putRow(root, record);
570
- const dir = liveDirOf(root);
571
- const corruptFile = path.join(dir, 's-corrupt.json');
572
- fs.writeFileSync(corruptFile, 'half a json {');
573
-
574
- const before = snapshotFiles(dir);
575
- assert(Object.keys(before).length === 6, '6 fixture files');
576
-
577
- const preview = livePrune({}, { memoryRoot: root, now: NOW });
578
- assert(preview.ok === true && preview.status === 'dry-run' && preview.dryRun === true, 'default is dry-run');
579
- assert(preview.deleted.length === 0, 'dry-run deletes nothing');
580
- assert(preview.wouldDelete.length === 2, `wouldDelete 2, got ${preview.wouldDelete.length}`);
581
- const candidateIds = preview.candidates.map((item) => item.sessionId).sort();
582
- assert(
583
- JSON.stringify(candidateIds) === JSON.stringify(['s-corrupt', 's-dead']),
584
- `candidates must be dead + corrupt, got ${JSON.stringify(candidateIds)}`,
585
- );
586
- assert(preview.kept.length === 4, 'dry-run kept 4');
587
- assert(
588
- JSON.stringify(snapshotFiles(dir)) === JSON.stringify(before),
589
- 'dry-run must not change a single byte',
590
- );
591
-
592
- expectCode(
593
- () => livePrune({ dryRun: false }, { memoryRoot: root, now: NOW }),
594
- 'E_CONFIRM_REQUIRED',
595
- );
596
- assert(
597
- JSON.stringify(snapshotFiles(dir)) === JSON.stringify(before),
598
- 'refused prune must not delete anything',
599
- );
600
-
601
- const real = livePrune({ confirm: LIVE_CONFIRM }, { memoryRoot: root, now: NOW });
602
- assert(real.ok === true && real.status === 'pruned' && real.dryRun === false, 'confirmed prune runs');
603
- assert(
604
- JSON.stringify(real.deleted.map((item) => item.sessionId).sort())
605
- === JSON.stringify(['s-corrupt', 's-dead']),
606
- 'confirmed prune deletes exactly dead + corrupt',
607
- );
608
- assert(real.failed.length === 0, 'no failed deletes');
609
- assert(!fs.existsSync(path.join(dir, 's-dead.json')), 'dead row removed');
610
- assert(!fs.existsSync(corruptFile), 'corrupt row removed');
611
-
612
- const after = snapshotFiles(dir);
613
- for (const name of [
614
- 's-live.json',
615
- 's-stale-alive.json', // same host but pid alive: never deleted
616
- 's-remote.json', // cross-host fresh: never touched
617
- 's-remote-stale.json', // cross-host stale: never touched
618
- ]) {
619
- assert(after[name] === before[name], `${name} must be byte-identical`);
620
- }
621
- assert(!('s-dead.json' in after) && !('s-corrupt.json' in after), 'only the two candidates are gone');
622
-
623
- const again = livePrune({ confirm: LIVE_CONFIRM }, { memoryRoot: root, now: NOW });
624
- assert(again.candidates.length === 0 && again.deleted.length === 0, 'second prune is a no-op');
625
-
626
- const confirmedPreview = livePrune({ confirm: LIVE_CONFIRM, dryRun: true }, { memoryRoot: root, now: NOW });
627
- assert(confirmedPreview.status === 'dry-run' && confirmedPreview.deleted.length === 0, 'dryRun:true wins over confirm');
628
- return 'dry-run kept 6 files; prune removed exactly dead + corrupt; 4 kept byte-identical';
629
- });
630
-
631
- // L8 — strict mode keeps the "no root, no registry" contract; the derived
632
- // default itself is covered by the portability suite.
633
- runCase('L8', 'strictMemoryRoot:四工具全拒 E_MEMORY_ROOT_UNSET;null/字符串/数组 E_BAD_ARGUMENT', () => {
634
- const strict = { strictMemoryRoot: true };
635
- const calls = [
636
- ['update', () => liveUpdate({ sessionId: 's', state: 'running' }, strict)],
637
- ['list', () => liveList({}, strict)],
638
- ['get', () => liveGet({ sessionId: 's' }, strict)],
639
- ['prune', () => livePrune({}, strict)],
640
- ];
641
- for (const [name, call] of calls) {
642
- const error = expectCode(call, 'E_MEMORY_ROOT_UNSET');
643
- assert(error.message.includes('memoryRoot'), `${name}: message must name memoryRoot: ${error.message}`);
644
- }
645
- expectCode(() => liveList({}, { memoryRoot: ' ', strictMemoryRoot: true }), 'E_MEMORY_ROOT_UNSET');
646
- expectCode(
647
- () => liveList({}, { memoryRoot: path.join(TMP, 'does-not-exist-live') }),
648
- 'E_MEMORY_ROOT_MISSING',
649
- );
650
-
651
- for (const badArgs of [null, '{"state":"running"}', ['running'], 42]) {
652
- expectCode(() => liveUpdate(badArgs, strict), 'E_BAD_ARGUMENT');
653
- expectCode(() => liveList(badArgs, strict), 'E_BAD_ARGUMENT');
654
- expectCode(() => liveGet(badArgs, strict), 'E_BAD_ARGUMENT');
655
- expectCode(() => livePrune(badArgs, strict), 'E_BAD_ARGUMENT');
656
- }
657
- expectCode(() => liveUpdate({ state: 'running' }, null), 'E_BAD_ARGUMENT');
658
- expectCode(() => liveUpdate({ state: 'running' }, []), 'E_BAD_ARGUMENT');
659
- // state is required and must be one of the five writer-declared states.
660
- expectCode(() => liveUpdate({ sessionId: 's' }, { memoryRoot: TMP }), 'E_BAD_ARGUMENT');
661
- expectCode(() => liveUpdate({ sessionId: 's', state: 'dead' }, { memoryRoot: TMP }), 'E_BAD_ARGUMENT');
662
- expectCode(() => liveUpdate({ sessionId: 's', state: 'corrupt' }, { memoryRoot: TMP }), 'E_BAD_ARGUMENT');
663
- return '4 tools refuse unset memoryRoot; null/string/array args rejected';
664
- });
665
-
666
- // L9 — an id that could be a path is refused, and nothing is created.
667
- runCase('L9', '路径越界:../、绝对路径、反斜杠一律 E_PATH_OUTSIDE_ROOT,不建目录', () => {
668
- const root = newRoot(TMP, 'l9');
669
- const escapeIds = ['../evil', '..\\evil', '../../etc/passwd', 'C:\\evil', '/evil', 'a/b', 'a\\b', '..'];
670
- for (const sessionId of escapeIds) {
671
- expectCode(
672
- () => liveUpdate({ sessionId, state: 'running' }, { memoryRoot: root }),
673
- 'E_PATH_OUTSIDE_ROOT',
674
- );
675
- expectCode(
676
- () => liveGet({ sessionId }, { memoryRoot: root }),
677
- 'E_PATH_OUTSIDE_ROOT',
678
- );
679
- }
680
- assert(!fs.existsSync(path.join(root, '.longlive')), 'refused ids must not create the registry dir');
681
- assert(!fs.existsSync(path.join(root, '..', 'evil.json')), 'no file may appear above the root');
682
-
683
- for (const sessionId of ['', ' ', 'bad id', 'x'.repeat(129), 'evil%2f..', '.hidden']) {
684
- expectCode(
685
- () => liveUpdate({ sessionId, state: 'running' }, { memoryRoot: root }),
686
- 'E_BAD_ARGUMENT',
687
- );
688
- }
689
- assert(!fs.existsSync(path.join(root, '.longlive')), 'malformed ids must not create the registry dir either');
690
-
691
- const accepted = liveUpdate({ sessionId: 's.9_ok-1', state: 'idle' }, { memoryRoot: root });
692
- assert(accepted.ok === true && fs.existsSync(liveFile(root, 's.9_ok-1')), 'a legal dotted id is accepted');
693
- return '8 path-like ids refused, 6 malformed ids refused, legal dotted id accepted';
694
- });
695
-
696
- // L10 — B2: prune re-reads and re-judges every candidate before unlinking.
697
- runCase('L10', 'B2 prune 删除前重读:blocked_on 不静默丢弃,字节变化则 skipped', () => {
698
- const root = newRoot(TMP, 'l10');
699
- putRow(root, makeRecord({
700
- sessionId: 's-dead',
701
- pid: FAKE_PID,
702
- host: HOST,
703
- startedAt: iso(NOW - 900000),
704
- queued: ['deleted-queue-1', 'deleted-queue-2'],
705
- heartbeatAt: iso(NOW - 500000),
706
- updatedAt: iso(NOW - 500000),
707
- }));
708
- putRow(root, makeRecord({
709
- sessionId: 's-blocked-dead',
710
- pid: FAKE_PID,
711
- host: HOST,
712
- state: 'blocked',
713
- blocked_on: 'waiting for approval',
714
- startedAt: iso(NOW - 800000),
715
- queued: ['blocked-queue'],
716
- heartbeatAt: iso(NOW - 500000),
717
- updatedAt: iso(NOW - 500000),
718
- }));
719
-
720
- const real = livePrune({ confirm: LIVE_CONFIRM }, { memoryRoot: root, now: NOW });
721
- assert(
722
- JSON.stringify(real.deleted.map((item) => item.sessionId)) === JSON.stringify(['s-dead']),
723
- `only the unprotected dead row may go, got ${JSON.stringify(real.deleted.map((item) => item.sessionId))}`,
724
- );
725
- assert(
726
- real.skipped.length === 1
727
- && real.skipped[0].sessionId === 's-blocked-dead'
728
- && real.skipped[0].reason.includes('blocked_on'),
729
- `blocked_on row must be skipped and visible, got ${JSON.stringify(real.skipped)}`,
730
- );
731
- assert(
732
- JSON.stringify(real.skipped[0].queued) === JSON.stringify(['blocked-queue'])
733
- && real.skipped[0].startedAt === iso(NOW - 800000),
734
- 'skipped row must keep queued/startedAt in the result',
735
- );
736
- assert(
737
- JSON.stringify(real.deleted[0].queued) === JSON.stringify(['deleted-queue-1', 'deleted-queue-2'])
738
- && real.deleted[0].startedAt === iso(NOW - 900000),
739
- 'deleted row must report the queued/startedAt it removed',
740
- );
741
- assert(fs.existsSync(liveFile(root, 's-blocked-dead')), 'blocked_on row must still exist after prune');
742
-
743
- // Race: the row is dead at scan time, then becomes running before unlink.
744
- const racedRoot = newRoot(TMP, 'l10-race');
745
- putRow(racedRoot, makeRecord({
746
- sessionId: 's-race',
747
- pid: FAKE_PID,
748
- host: HOST,
749
- heartbeatAt: iso(NOW - 500000),
750
- updatedAt: iso(NOW - 500000),
751
- }));
752
- const target = liveFile(racedRoot, 's-race');
753
- const realRead = fs.readFileSync;
754
- let reads = 0;
755
- withFsPatch({
756
- readFileSync: (file, ...rest) => {
757
- if (path.resolve(String(file)) === path.resolve(target)) {
758
- reads += 1;
759
- if (reads === 2) {
760
- const row = JSON.parse(realRead(target, 'utf8'));
761
- row.heartbeatAt = iso(NOW);
762
- row.updatedAt = iso(NOW);
763
- row.pid = process.pid;
764
- row.goal = 'changed after scan';
765
- return `${JSON.stringify(row, null, 2)}\n`;
766
- }
767
- }
768
- return realRead(file, ...rest);
769
- },
770
- }, () => {
771
- const raced = livePrune({ confirm: LIVE_CONFIRM }, { memoryRoot: racedRoot, now: NOW });
772
- assert(raced.deleted.length === 0, 'a row that changed after scanning must not be deleted');
773
- assert(
774
- raced.skipped.some((item) => item.sessionId === 's-race' && item.reason.includes('变化')),
775
- `changed row must be reported as skipped, got ${JSON.stringify(raced.skipped)}`,
776
- );
777
- });
778
- assert(fs.existsSync(target), 'race row must survive');
779
- return 'blocked_on skipped visibly; changed-after-scan row skipped';
780
- });
781
-
782
- // L11 — M-a: one session, one row; readers must name the canonical spelling.
783
- runCase('L11', 'M-a 大小写别名:写统一小写;get 用别名报 E_SESSION_ID_NOT_CANONICAL 并给出 canonical', () => {
784
- const root = newRoot(TMP, 'l11');
785
- const first = liveUpdate({ sessionId: 'S-Ali', state: 'idle' }, { memoryRoot: root, now: NOW });
786
- assert(first.sessionId === 's-ali', `sessionId must be canonical lowercase, got ${first.sessionId}`);
787
- const dir = liveDirOf(root);
788
- assert(
789
- JSON.stringify(fs.readdirSync(dir)) === JSON.stringify(['s-ali.json']),
790
- `one lowercase file, got ${JSON.stringify(fs.readdirSync(dir))}`,
791
- );
792
- for (const alias of ['S-ALI', 's-Ali']) {
793
- const error = expectCode(
794
- () => liveGet({ sessionId: alias }, { memoryRoot: root, now: NOW }),
795
- 'E_SESSION_ID_NOT_CANONICAL',
796
- );
797
- assert(error.canonical === 's-ali', `alias ${alias}: canonical must be s-ali, got ${error.canonical}`);
798
- assert(error.message.includes('规范'), `alias ${alias}: message must explain canonical form`);
799
- }
800
- const got = liveGet({ sessionId: 's-ali' }, { memoryRoot: root, now: NOW });
801
- assert(got.ok === true && got.sessionId === 's-ali', 'canonical id reads the row');
802
- assert(liveList({}, { memoryRoot: root, now: NOW }).scanned === 1, 'aliases are one row, not several');
803
-
804
- // A row written before canonicalisation may still carry mixed case on disk.
805
- putRow(root, makeRecord({ sessionId: 'S-Legacy' }));
806
- const legacy = liveGet({ sessionId: 's-legacy' }, { memoryRoot: root, now: NOW });
807
- assert(legacy.ok === true && legacy.live.corrupt === false, 'mixed-case legacy row is the same session, not corrupt');
808
- const legacyAlias = expectCode(
809
- () => liveGet({ sessionId: 'S-Legacy' }, { memoryRoot: root, now: NOW }),
810
- 'E_SESSION_ID_NOT_CANONICAL',
811
- );
812
- assert(legacyAlias.canonical === 's-legacy', 'legacy alias reports its canonical id');
813
- return 'S-Ali -> s-ali.json; aliases refused with canonical; legacy mixed-case row readable by canonical id';
814
- });
815
-
816
- // L12 — B3: lexical escape is not enough; realpath is the guard. A junction
817
- // needs no privilege and always runs; the symlinked-row half needs a real
818
- // file symlink, so it is a separate case that can honestly SKIP.
819
- runCase('L12', 'B3 realpath:live 目录 junction 指根外 -> E_PATH_OUTSIDE_ROOT', () => {
820
- const root = newRoot(TMP, 'l12');
821
- const outside = path.join(TMP, SUITE, 'l12-outside');
822
- fs.mkdirSync(outside, { recursive: true });
823
- const live = path.join(root, '.longlive', 'live');
824
- fs.mkdirSync(path.dirname(live), { recursive: true });
825
- fs.symlinkSync(outside, live, 'junction');
826
- const calls = [
827
- ['list', () => liveList({}, { memoryRoot: root })],
828
- ['update', () => liveUpdate({ sessionId: 's', state: 'idle' }, { memoryRoot: root })],
829
- ['get', () => liveGet({ sessionId: 's' }, { memoryRoot: root })],
830
- ['prune', () => livePrune({}, { memoryRoot: root })],
831
- ];
832
- for (const [name, call] of calls) {
833
- const error = expectCode(call, 'E_PATH_OUTSIDE_ROOT');
834
- assert(error.message.includes('真实路径'), `${name}: message must say the real path escaped`);
835
- }
836
- assert(fs.readdirSync(outside).length === 0, 'junction target must stay untouched');
837
- return 'junction -> 4 tools E_PATH_OUTSIDE_ROOT';
838
- });
839
-
840
- runSymlinkCase('L12-link', 'B3 realpath:符号链接行被拒且只报告,不删除(需符号链接权限)', () => {
841
- const clean = newRoot(TMP, 'l12-file');
842
- putRow(clean, makeRecord({ sessionId: 's-real' }));
843
- const dir = liveDirOf(clean);
844
- const link = path.join(dir, 's-link.json');
845
- fs.symlinkSync(path.join(dir, 's-real.json'), link, 'file');
846
- expectCode(() => liveGet({ sessionId: 's-link' }, { memoryRoot: clean, now: NOW }), 'E_LIVE_CORRUPT');
847
-
848
- const preview = livePrune({}, { memoryRoot: clean, now: NOW });
849
- assert(
850
- preview.placeholders.some((item) => item.kind === 'symlink' && item.fileRel.endsWith('s-link.json')),
851
- 'prune must report the symlinked row',
852
- );
853
- const real = livePrune({ confirm: LIVE_CONFIRM }, { memoryRoot: clean, now: NOW });
854
- assert(real.deleted.length === 0, 'a symlink is never a row candidate');
855
- assert(fs.existsSync(link) && fs.existsSync(path.join(dir, 's-real.json')), 'symlink and its target survive');
856
- return 'symlinked row refused and only reported; never deleted';
857
- });
858
-
859
- // L13 — M-b/M-c: orphan tmp files and empty directory placeholders.
860
- runCase('L13', 'M-b/M-c prune:陈旧 tmp 与空目录 confirm 后清理;新 tmp/非空目录只报告', () => {
861
- const root = newRoot(TMP, 'l13');
862
- const dir = liveDirOf(root);
863
- fs.mkdirSync(dir, { recursive: true });
864
- putRow(root, makeRecord({ sessionId: 's-alive', pid: process.pid }));
865
-
866
- const oldTmp = path.join(dir, 's-old.json.tmp-999-1-aaaa');
867
- fs.writeFileSync(oldTmp, 'half a row');
868
- fs.utimesSync(oldTmp, new Date(NOW - 7200000), new Date(NOW - 7200000));
869
- const freshTmp = path.join(dir, 's-fresh.json.tmp-999-2-bbbb');
870
- fs.writeFileSync(freshTmp, 'still writing');
871
- fs.utimesSync(freshTmp, new Date(NOW - 60000), new Date(NOW - 60000));
872
- const emptyDir = path.join(dir, 's-empty.json');
873
- fs.mkdirSync(emptyDir);
874
- const nonEmptyDir = path.join(dir, 's-nonempty.json');
875
- fs.mkdirSync(nonEmptyDir);
876
- fs.writeFileSync(path.join(nonEmptyDir, 'child'), 'x');
877
-
878
- const preview = livePrune({}, { memoryRoot: root, now: NOW });
879
- assert(preview.tmpFiles.length === 2, `two tmp files reported, got ${preview.tmpFiles.length}`);
880
- assert(preview.placeholders.length === 2, `two directory placeholders reported, got ${preview.placeholders.length}`);
881
- assert(preview.wouldDelete.length === 2, `old tmp + empty dir are deletable, got ${preview.wouldDelete.length}`);
882
- assert(fs.existsSync(oldTmp) && fs.existsSync(emptyDir), 'dry-run touches nothing');
883
-
884
- const real = livePrune({ confirm: LIVE_CONFIRM }, { memoryRoot: root, now: NOW });
885
- assert(!fs.existsSync(oldTmp), 'old orphan tmp removed');
886
- assert(fs.existsSync(freshTmp), 'fresh tmp kept (may belong to a live writer)');
887
- assert(!fs.existsSync(emptyDir), 'empty directory placeholder removed');
888
- assert(fs.existsSync(path.join(nonEmptyDir, 'child')), 'non-empty directory is reported, never recursively deleted');
889
- assert(
890
- real.tmpFiles.some((item) => item.fileRel.endsWith('s-old.json.tmp-999-1-aaaa') && item.action === 'deleted'),
891
- 'deletion is visible in the result',
892
- );
893
- assert(
894
- real.placeholders.some((item) => item.fileRel.endsWith('s-nonempty.json') && item.action === 'report'),
895
- 'non-empty directory is visible as a report',
896
- );
897
- return 'old tmp + empty dir removed on confirm; fresh tmp and non-empty dir kept and reported';
898
- });
899
-
900
- // L14 — M-d: bounded queue and action detail, with visible truncation flags.
901
- runCase('L14', 'M-d 上限:queued 200 项、每项 300 字,last_action.detail 500 字,结果明示截断', () => {
902
- const root = newRoot(TMP, 'l14');
903
- const queued = Array.from({ length: 250 }, (_, index) => `q-${index}-${'y'.repeat(400)}`);
904
- const written = liveUpdate({
905
- sessionId: 's-caps',
906
- state: 'running',
907
- queued,
908
- last_action: { at: iso(NOW), kind: 'edit', detail: 'z'.repeat(700) },
909
- }, { memoryRoot: root, now: NOW });
910
- assert(written.queuedTruncated === true, 'queued truncation must be flagged');
911
- assert(written.queuedInput === 250 && written.queuedCount === 200, 'queue input/kept counts');
912
- assert(written.record.queued.length === 200, `stored queue 200, got ${written.record.queued.length}`);
913
- assert([...written.record.queued[0]].length === 300, 'each stored queue item is 300 code points');
914
- assert(written.lastActionDetailTruncated === true, 'detail truncation must be flagged');
915
- assert(written.lastActionDetailChars === 700, 'original detail length reported');
916
- assert(written.record.last_action.detail.length === 500, 'stored detail is 500 chars');
917
-
918
- const stored = JSON.parse(fs.readFileSync(liveFile(root, 's-caps'), 'utf8'));
919
- assert(stored.queued.length === 200 && stored.last_action.detail.length === 500, 'on-disk row obeys the caps');
920
- return 'queue 250 -> 200 x 300 chars; detail 700 -> 500; both flagged';
921
- });
922
-
923
- // L16 — cross-host corrupt rows: a host stamp is evidence of another owner.
924
- runCase('L16', '跨 host corrupt:带远端 host 的损坏行不删;host 未知/本机才可清理', () => {
925
- const root = newRoot(TMP, 'l16');
926
- const dir = liveDirOf(root);
927
- fs.mkdirSync(dir, { recursive: true });
928
- putRow(root, makeRecord({ sessionId: 's-alive', pid: process.pid }));
929
-
930
- const remoteFile = path.join(dir, 's-corrupt-remote.json');
931
- fs.writeFileSync(remoteFile, JSON.stringify({
932
- schemaVersion: LIVE_SCHEMA_VERSION,
933
- sessionId: 's-corrupt-remote',
934
- host: REMOTE_HOST,
935
- heartbeatAt: iso(NOW),
936
- // state/pid/ttl are missing: this row cannot be decoded.
937
- }));
938
- const remoteHalf = path.join(dir, 's-corrupt-remote-half.json');
939
- fs.writeFileSync(remoteHalf, `{"sessionId":"s-corrupt-remote-half","host":"${REMOTE_HOST}"`);
940
- const localFile = path.join(dir, 's-corrupt-local.json');
941
- fs.writeFileSync(localFile, JSON.stringify({
942
- schemaVersion: LIVE_SCHEMA_VERSION,
943
- sessionId: 's-corrupt-local',
944
- host: HOST,
945
- heartbeatAt: iso(NOW),
946
- }));
947
- const hostless = path.join(dir, 's-corrupt-hostless.json');
948
- fs.writeFileSync(hostless, 'not json at all');
949
-
950
- const before = snapshotFiles(dir);
951
- const preview = livePrune({}, { memoryRoot: root, now: NOW });
952
- const candidateIds = preview.candidates.map((item) => item.sessionId).sort();
953
- assert(
954
- JSON.stringify(candidateIds) === JSON.stringify(['s-corrupt-hostless', 's-corrupt-local']),
955
- `only local/unknown-host corrupt rows are candidates, got ${JSON.stringify(candidateIds)}`,
956
- );
957
- assert(
958
- preview.skipped.filter((item) => item.sessionId.startsWith('s-corrupt-remote')).length === 2,
959
- 'both remote corrupt rows must be reported as skipped',
960
- );
961
- assert(
962
- preview.skipped.every((item) => !item.sessionId.startsWith('s-corrupt-remote') || item.reason.includes('跨 host')),
963
- 'remote corrupt skip must say why',
964
- );
965
- assert(JSON.stringify(snapshotFiles(dir)) === JSON.stringify(before), 'dry-run touches nothing');
966
-
967
- const real = livePrune({ confirm: LIVE_CONFIRM }, { memoryRoot: root, now: NOW });
968
- assert(
969
- JSON.stringify(real.deleted.map((item) => item.sessionId).sort())
970
- === JSON.stringify(['s-corrupt-hostless', 's-corrupt-local']),
971
- `deleted exactly local/unknown corrupt rows, got ${JSON.stringify(real.deleted.map((item) => item.sessionId))}`,
972
- );
973
- assert(fs.existsSync(remoteFile) && fs.existsSync(remoteHalf), 'remote corrupt rows survive');
974
- const after = snapshotFiles(dir);
975
- assert(after['s-corrupt-remote.json'] === before['s-corrupt-remote.json'], 'remote row is byte-identical');
976
- assert(after['s-corrupt-remote-half.json'] === before['s-corrupt-remote-half.json'], 'remote half row is byte-identical');
977
- return 'remote corrupt rows protected and reported; local/unknown corrupt rows removed';
978
- });
979
-
980
- // L17 — a directory on the row path must fail early and clearly. The
981
- // directory half needs no privilege; the symlink half is skippable.
982
- runCase('L17', '目录占位:update 抛 E_LIVE_ROW_BLOCKED;空目录 prune 后写入恢复', () => {
983
- const root = newRoot(TMP, 'l17');
984
- const dir = liveDirOf(root);
985
- fs.mkdirSync(dir, { recursive: true });
986
- const placeholder = path.join(dir, 's-dir.json');
987
- fs.mkdirSync(placeholder);
988
- const error = expectCode(
989
- () => liveUpdate({ sessionId: 's-dir', state: 'idle' }, { memoryRoot: root, now: NOW }),
990
- 'E_LIVE_ROW_BLOCKED',
991
- );
992
- assert(error.message.includes('目录') && error.message.includes(placeholder), 'error must name the directory');
993
-
994
- const preview = livePrune({}, { memoryRoot: root, now: NOW });
995
- assert(
996
- preview.placeholders.some((item) => item.kind === 'directory' && item.fileRel.endsWith('s-dir.json')),
997
- 'empty directory is reported as a placeholder',
998
- );
999
- livePrune({ confirm: LIVE_CONFIRM }, { memoryRoot: root, now: NOW });
1000
- assert(!fs.existsSync(placeholder), 'empty directory placeholder removed');
1001
- const written = liveUpdate({ sessionId: 's-dir', state: 'idle' }, { memoryRoot: root, now: NOW });
1002
- assert(written.ok === true && fs.existsSync(liveFile(root, 's-dir')), 'write succeeds after the placeholder is gone');
1003
- return 'update refused a directory with a named error; prune cleared the empty dir; write recovered';
1004
- });
1005
-
1006
- runSymlinkCase('L17-link', '符号链接占位:update 抛 E_LIVE_ROW_BLOCKED 并按名字指出链接(需符号链接权限)', () => {
1007
- const root = newRoot(TMP, 'l17-link');
1008
- const dir = liveDirOf(root);
1009
- fs.mkdirSync(dir, { recursive: true });
1010
- putRow(root, makeRecord({ sessionId: 's-real', pid: process.pid }));
1011
- const link = path.join(dir, 's-link.json');
1012
- fs.symlinkSync(path.join(dir, 's-real.json'), link, 'file');
1013
- const linkError = expectCode(
1014
- () => liveUpdate({ sessionId: 's-link', state: 'idle' }, { memoryRoot: root, now: NOW }),
1015
- 'E_LIVE_ROW_BLOCKED',
1016
- );
1017
- assert(linkError.message.includes('符号链接'), 'symlink row must be refused by name');
1018
- return 'update refused the symlink row with a named error';
1019
- });
1020
- }