dsh-context-compression-improved 0.2.3 → 0.2.5

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 (149) hide show
  1. package/.gitattributes +2 -1
  2. package/.githooks/pre-push +37 -0
  3. package/.github/workflows/ci.yml +39 -39
  4. package/CHANGELOG.ja.md +169 -39
  5. package/CHANGELOG.ko.md +167 -39
  6. package/CHANGELOG.md +333 -135
  7. package/CHANGELOG.zh.md +152 -39
  8. package/CONTRIBUTING.md +22 -22
  9. package/README.ja.md +85 -104
  10. package/README.ko.md +85 -103
  11. package/README.md +94 -112
  12. package/README.zh.md +85 -101
  13. package/THIRD_PARTY_NOTICES.md +14 -14
  14. package/docs/compat-0.1.5-report.md +77 -0
  15. package/docs/installation.ja.md +78 -76
  16. package/docs/installation.ko.md +78 -76
  17. package/docs/installation.md +103 -76
  18. package/docs/installation.zh.md +100 -76
  19. package/docs/repair-log.md +657 -582
  20. package/eslint.config.js +30 -30
  21. package/package.json +163 -142
  22. package/packages/selector/README.md +26 -31
  23. package/packages/selector/README.zh.md +24 -31
  24. package/packages/selector/THIRD_PARTY_NOTICES.md +32 -38
  25. package/packages/selector/cordis.patch.yml +27 -19
  26. package/packages/selector/dsh.plugin.json +2 -2
  27. package/packages/selector/lib/client.d.ts +320 -228
  28. package/packages/selector/lib/client.js +3254 -1462
  29. package/packages/selector/lib/config.js +1713 -842
  30. package/packages/selector/lib/index.d.ts +46 -38
  31. package/packages/selector/lib/index.js +1099 -645
  32. package/packages/selector/lib/invariant.js +70 -70
  33. package/packages/selector/lib/pruner.d.ts +904 -684
  34. package/packages/selector/lib/pruner.js +5800 -3807
  35. package/packages/selector/lib/style.css +88 -46
  36. package/packages/selector/lib/tail-trim.js +145 -136
  37. package/packages/selector/package.json +18 -19
  38. package/packages/selector/screenshots.json +3 -6
  39. package/packages/selector/src/client/CompressionProfileControls.tsx +293 -229
  40. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
  41. package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -79
  42. package/packages/selector/src/client/EstimatorControls.tsx +277 -281
  43. package/packages/selector/src/client/decode.ts +57 -49
  44. package/packages/selector/src/client/index.ts +249 -111
  45. package/packages/selector/src/client/locales/de.ts +141 -0
  46. package/packages/selector/src/client/locales/es.ts +141 -0
  47. package/packages/selector/src/client/locales/fr.ts +141 -0
  48. package/packages/selector/src/client/locales/it.ts +141 -0
  49. package/packages/selector/src/client/locales/ja.ts +141 -0
  50. package/packages/selector/src/client/locales/ko.ts +141 -0
  51. package/packages/selector/src/client/locales/ru.ts +141 -0
  52. package/packages/selector/src/client/locales.ts +282 -198
  53. package/packages/selector/src/client/monitor-fab.ts +336 -0
  54. package/packages/selector/src/client/preset-options.ts +88 -70
  55. package/packages/selector/src/client/savings-card.tsx +150 -0
  56. package/packages/selector/src/client/settings-section.tsx +140 -126
  57. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -210
  58. package/packages/selector/src/index.ts +671 -327
  59. package/packages/selector/src/invariant.ts +113 -113
  60. package/packages/selector/src/preset-overlay.ts +60 -1
  61. package/packages/selector/src/profiles.ts +431 -342
  62. package/packages/selector/src/pruner/content.ts +18 -5
  63. package/packages/selector/src/pruner/state.ts +57 -43
  64. package/packages/selector/src/pruner/types.ts +23 -5
  65. package/packages/selector/src/pruner.ts +2736 -2144
  66. package/packages/selector/src/runtime/adaptive-cost.ts +23 -12
  67. package/packages/selector/src/runtime/audit.ts +303 -215
  68. package/packages/selector/src/runtime/config.ts +756 -613
  69. package/packages/selector/src/runtime/measurement.ts +436 -403
  70. package/packages/selector/src/runtime/monitor.ts +235 -0
  71. package/packages/selector/src/runtime/reducers.ts +1115 -97
  72. package/packages/selector/src/runtime/retrieve.ts +479 -457
  73. package/packages/selector/src/runtime/savings.ts +337 -0
  74. package/packages/selector/src/runtime/session-events.ts +30 -17
  75. package/packages/selector/src/runtime/summary-command.ts +127 -0
  76. package/packages/selector/src/runtime/tail-trim.ts +166 -166
  77. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -0
  78. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -0
  79. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -0
  80. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -0
  81. package/packages/selector/src/runtime/tokenpilot/dedup.ts +1 -1
  82. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -183
  83. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  84. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  85. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  86. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  87. package/packages/selector/src/runtime/tokenpilot/locator.ts +1 -1
  88. package/packages/selector/src/runtime/tokenpilot/read-state.ts +23 -2
  89. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -0
  90. package/packages/selector/src/runtime/toolclass.ts +103 -0
  91. package/packages/selector/src/runtime/types.ts +365 -309
  92. package/packages/selector/tests/advisor-report.host.spec.ts +223 -0
  93. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -226
  94. package/packages/selector/tests/built/client-artifact.spec.ts +59 -51
  95. package/packages/selector/tests/code-skeleton.client.spec.ts +91 -88
  96. package/packages/selector/tests/custom-contract.client.spec.ts +205 -202
  97. package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -247
  98. package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -176
  99. package/packages/selector/tests/host-preset-overlay.host.spec.ts +206 -204
  100. package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
  101. package/packages/selector/tests/preset-options-write.client.spec.ts +207 -181
  102. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +201 -196
  103. package/packages/selector/tests/preset-overlay.host.spec.ts +246 -243
  104. package/packages/selector/tests/profiles.client.spec.tsx +436 -434
  105. package/packages/selector/tests/public/package-contract.client.spec.ts +78 -33
  106. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +7 -7
  107. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +232 -0
  108. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -0
  109. package/packages/selector/tests/runtime/advisor.spec.ts +226 -0
  110. package/packages/selector/tests/runtime/audit.spec.ts +275 -129
  111. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -0
  112. package/packages/selector/tests/runtime/code-skeleton.spec.ts +14 -3
  113. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -0
  114. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -0
  115. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -0
  116. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  117. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  118. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -0
  119. package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
  120. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -0
  121. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2724 -2531
  122. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -0
  123. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  124. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -0
  125. package/packages/selector/tests/runtime/session-events.spec.ts +27 -27
  126. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -0
  127. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  128. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -0
  129. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -0
  130. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -56
  131. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +116 -100
  132. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +24 -0
  133. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -0
  134. package/packages/selector/tests/settings-seat.client.spec.ts +130 -0
  135. package/packages/selector/tests/standing-generation.host.spec.ts +697 -631
  136. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +253 -250
  137. package/pnpm-workspace.yaml +66 -19
  138. package/scripts/capture-profile-baseline.mjs +42 -0
  139. package/scripts/generate-tokenizer-fixtures.py +81 -81
  140. package/scripts/generate-vision-fixtures.py +208 -208
  141. package/scripts/{packed-components-smoke.ts → packed-components-smoke.mjs} +732 -713
  142. package/scripts/{packed-install-e2e.ts → packed-install-e2e.mjs} +1273 -1072
  143. package/scripts/toolclass-corpus-replay.mjs +281 -0
  144. package/scripts/{verify-release.ts → verify-release.mjs} +318 -300
  145. package/tests/TEST_INVENTORY.md +41 -42
  146. package/scripts/capture-profile-baseline.ts +0 -80
  147. package/tsconfig.scripts.json +0 -13
  148. /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-profiles.jpg +0 -0
  149. /package/{packages/selector/assets/screenshots → docs/assets}/context-compression-selector-settings.png +0 -0
@@ -1,113 +1,113 @@
1
- /** Package-owned invariants for standard-prune compression publications. */
2
-
3
- import type { Context } from '@deepseek-ai/cordis'
4
- import type { InvariantFailure, InvariantInstaller } from '@deepseek-ai/dsh-invariants'
5
- import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
6
- import type {} from '@deepseek-ai/dsh-compaction'
7
- import { validatePublishedTailTrim } from './runtime/tail-trim.ts'
8
- import { sessionEvents } from './runtime/session-events.ts'
9
-
10
- const PACKAGE_NAME = 'dsh-context-compression-improved-runtime'
11
-
12
- /** Cordis companion plugin name. */
13
- export const name = 'context-compression-selector-runtime-invariant'
14
- /** Services required before the companion can register. */
15
- export const inject = ['invariants']
16
-
17
- type PruneEvent = SessionEvent<'compaction/prune'>
18
-
19
- /** Whether the next event claims the unresolved prune's replacement range. */
20
- function resemblesCompanion(prune: PruneEvent, event: SessionEvent): boolean {
21
- if ((event.type !== 'tool/result' && event.type !== 'user/message')
22
- || typeof event.surfaceOp !== 'object') return false
23
- const sources = new Set(event.sourceEventSeqs ?? [])
24
- return (event.surfaceOp.start === prune.data.shadowedRange.start
25
- && event.surfaceOp.end === prune.data.shadowedRange.end)
26
- || prune.data.shadowedSeqs.some(seq => sources.has(seq))
27
- }
28
-
29
- /** Validate one standard prune's immediately adjacent surface replacement. */
30
- function validateCompanion(
31
- session: Session,
32
- prune: PruneEvent,
33
- event: SessionEvent,
34
- fail: InvariantFailure,
35
- ): void {
36
- if ((event.type !== 'tool/result' && event.type !== 'user/message')
37
- || typeof event.surfaceOp !== 'object') {
38
- fail(`compaction/prune at seq ${prune.seq} must be immediately followed by a replacement surface event`)
39
- }
40
- const { shadowedRange, shadowedSeqs } = prune.data
41
- if (shadowedSeqs.length === 0
42
- || shadowedSeqs[0] !== shadowedRange.start
43
- || shadowedSeqs.at(-1) !== shadowedRange.end) {
44
- fail(`compaction/prune at seq ${prune.seq} has a shadowed range inconsistent with shadowedSeqs`)
45
- }
46
- if (event.surfaceOp.start !== shadowedRange.start || event.surfaceOp.end !== shadowedRange.end) {
47
- fail(`replacement at seq ${event.seq} does not replace compaction/prune range ${shadowedRange.start}-${shadowedRange.end}`)
48
- }
49
- const sources = new Set(event.sourceEventSeqs ?? [])
50
- const missing = shadowedSeqs.filter(seq => !sources.has(seq))
51
- if (missing.length > 0) {
52
- fail(`replacement at seq ${event.seq} omits shadowed source seqs ${missing.join(', ')}`)
53
- }
54
- if (event.type === 'user/message' && validatePublishedTailTrim(session, prune.seq) === null) {
55
- fail(`TailTrim publication at seq ${prune.seq} is invalid`)
56
- }
57
- }
58
-
59
- /** Validate a replayed log and return its only legal unresolved tail. */
60
- function seedPending(session: Session, fail: InvariantFailure): PruneEvent | undefined {
61
- let pending: PruneEvent | undefined
62
- for (const event of sessionEvents(session)) {
63
- if (pending !== undefined) {
64
- // A prune whose synchronous companion never committed is an inert,
65
- // aborted publication. It must not brick a restored Session. A surface
66
- // replacement that claims the prune is still validated strictly.
67
- if (resemblesCompanion(pending, event)) validateCompanion(session, pending, event, fail)
68
- pending = undefined
69
- }
70
- if (event.type === 'compaction/prune') pending = event
71
- }
72
- return pending
73
- }
74
-
75
- /** Install adjacency checks with pre-commit staging. */
76
- const install: InvariantInstaller = Object.assign((ctx: Context, fail: InvariantFailure) => {
77
- const pending = new WeakMap<Session, PruneEvent | undefined>()
78
- const staged = new WeakMap<SessionEvent, { session: Session; next: PruneEvent | undefined }>()
79
- const seed = (session: Session): void => { pending.set(session, seedPending(session, fail)) }
80
- const current = (session: Session): PruneEvent | undefined => {
81
- if (!pending.has(session)) seed(session)
82
- return pending.get(session)
83
- }
84
-
85
- for (const session of ctx.sessions.list()) seed(session)
86
- ctx.on('session/created', seed, { global: true })
87
-
88
- ctx.on('internal/dispatch', (_mode, eventName, args) => {
89
- if (eventName !== 'session/event') return
90
- const [session, event] = args as [Session, SessionEvent]
91
- const open = current(session)
92
- if (open !== undefined && resemblesCompanion(open, event)) {
93
- validateCompanion(session, open, event, fail)
94
- }
95
- staged.set(event, {
96
- session,
97
- next: event.type === 'compaction/prune' ? event : undefined,
98
- })
99
- }, { global: true })
100
-
101
- ctx.on('session/event', (session, event) => {
102
- const candidate = staged.get(event)
103
- if (candidate === undefined || candidate.session !== session) {
104
- return fail('session/event reached publication without matching pre-commit validation')
105
- }
106
- staged.delete(event)
107
- pending.set(session, candidate.next)
108
- }, { global: true })
109
- }, { inject: ['sessions'] })
110
-
111
- /** Register this package's invariant companion. */
112
- export const apply = (ctx: Context): Promise<() => void> =>
113
- Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))
1
+ /** Package-owned invariants for standard-prune compression publications. */
2
+
3
+ import type { Context } from '@deepseek-ai/cordis'
4
+ import type { InvariantFailure, InvariantInstaller } from '@deepseek-ai/dsh-invariants'
5
+ import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
6
+ import type {} from '@deepseek-ai/dsh-compaction'
7
+ import { validatePublishedTailTrim } from './runtime/tail-trim.ts'
8
+ import { sessionEvents } from './runtime/session-events.ts'
9
+
10
+ const PACKAGE_NAME = 'dsh-context-compression-improved-runtime'
11
+
12
+ /** Cordis companion plugin name. */
13
+ export const name = 'context-compression-selector-runtime-invariant'
14
+ /** Services required before the companion can register. */
15
+ export const inject = ['invariants']
16
+
17
+ type PruneEvent = SessionEvent<'compaction/prune'>
18
+
19
+ /** Whether the next event claims the unresolved prune's replacement range. */
20
+ function resemblesCompanion(prune: PruneEvent, event: SessionEvent): boolean {
21
+ if ((event.type !== 'tool/result' && event.type !== 'user/message')
22
+ || typeof event.surfaceOp !== 'object') return false
23
+ const sources = new Set(event.sourceEventSeqs ?? [])
24
+ return (event.surfaceOp.startSeq === prune.data.shadowedRange.start
25
+ && event.surfaceOp.endSeq === prune.data.shadowedRange.end)
26
+ || prune.data.shadowedSeqs.some(seq => sources.has(seq))
27
+ }
28
+
29
+ /** Validate one standard prune's immediately adjacent surface replacement. */
30
+ function validateCompanion(
31
+ session: Session,
32
+ prune: PruneEvent,
33
+ event: SessionEvent,
34
+ fail: InvariantFailure,
35
+ ): void {
36
+ if ((event.type !== 'tool/result' && event.type !== 'user/message')
37
+ || typeof event.surfaceOp !== 'object') {
38
+ fail(`compaction/prune at seq ${prune.seq} must be immediately followed by a replacement surface event`)
39
+ }
40
+ const { shadowedRange, shadowedSeqs } = prune.data
41
+ if (shadowedSeqs.length === 0
42
+ || shadowedSeqs[0] !== Number(shadowedRange.start)
43
+ || shadowedSeqs.at(-1) !== Number(shadowedRange.end)) {
44
+ fail(`compaction/prune at seq ${prune.seq} has a shadowed range inconsistent with shadowedSeqs`)
45
+ }
46
+ if (event.surfaceOp.startSeq !== shadowedRange.start || event.surfaceOp.endSeq !== shadowedRange.end) {
47
+ fail(`replacement at seq ${event.seq} does not replace compaction/prune range ${shadowedRange.start}-${shadowedRange.end}`)
48
+ }
49
+ const sources = new Set(event.sourceEventSeqs ?? [])
50
+ const missing = shadowedSeqs.filter(seq => !sources.has(seq))
51
+ if (missing.length > 0) {
52
+ fail(`replacement at seq ${event.seq} omits shadowed source seqs ${missing.join(', ')}`)
53
+ }
54
+ if (event.type === 'user/message' && validatePublishedTailTrim(session, prune.seq) === null) {
55
+ fail(`TailTrim publication at seq ${prune.seq} is invalid`)
56
+ }
57
+ }
58
+
59
+ /** Validate a replayed log and return its only legal unresolved tail. */
60
+ function seedPending(session: Session, fail: InvariantFailure): PruneEvent | undefined {
61
+ let pending: PruneEvent | undefined
62
+ for (const event of sessionEvents(session)) {
63
+ if (pending !== undefined) {
64
+ // A prune whose synchronous companion never committed is an inert,
65
+ // aborted publication. It must not brick a restored Session. A surface
66
+ // replacement that claims the prune is still validated strictly.
67
+ if (resemblesCompanion(pending, event)) validateCompanion(session, pending, event, fail)
68
+ pending = undefined
69
+ }
70
+ if (event.type === 'compaction/prune') pending = event
71
+ }
72
+ return pending
73
+ }
74
+
75
+ /** Install adjacency checks with pre-commit staging. */
76
+ const install: InvariantInstaller = Object.assign((ctx: Context, fail: InvariantFailure) => {
77
+ const pending = new WeakMap<Session, PruneEvent | undefined>()
78
+ const staged = new WeakMap<SessionEvent, { session: Session; next: PruneEvent | undefined }>()
79
+ const seed = (session: Session): void => { pending.set(session, seedPending(session, fail)) }
80
+ const current = (session: Session): PruneEvent | undefined => {
81
+ if (!pending.has(session)) seed(session)
82
+ return pending.get(session)
83
+ }
84
+
85
+ for (const session of ctx.sessions.list()) seed(session)
86
+ ctx.on('session/created', seed, { global: true })
87
+
88
+ ctx.on('internal/dispatch', (_mode, eventName, args) => {
89
+ if (eventName !== 'session/event') return
90
+ const [session, event] = args as [Session, SessionEvent]
91
+ const open = current(session)
92
+ if (open !== undefined && resemblesCompanion(open, event)) {
93
+ validateCompanion(session, open, event, fail)
94
+ }
95
+ staged.set(event, {
96
+ session,
97
+ next: event.type === 'compaction/prune' ? event : undefined,
98
+ })
99
+ }, { global: true })
100
+
101
+ ctx.on('session/event', (session, event) => {
102
+ const candidate = staged.get(event)
103
+ if (candidate === undefined || candidate.session !== session) {
104
+ return fail('session/event reached publication without matching pre-commit validation')
105
+ }
106
+ staged.delete(event)
107
+ pending.set(session, candidate.next)
108
+ }, { global: true })
109
+ }, { inject: ['sessions'] })
110
+
111
+ /** Register this package's invariant companion. */
112
+ export const apply = (ctx: Context): Promise<() => void> =>
113
+ Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))
@@ -116,6 +116,16 @@ export function standingStampMs(identity: string): number {
116
116
  return standingStampMsAtWindow(identity, 0)
117
117
  }
118
118
 
119
+ /**
120
+ * True for the filesystem errors a concurrent publish can raise on Windows:
121
+ * `MoveFileEx` reports a lost race — or a reader holding the destination open —
122
+ * as EPERM/EBUSY/EACCES, where POSIX `rename` simply replaces the destination.
123
+ */
124
+ function isPublishRace(error: unknown): boolean {
125
+ const code = (error as { code?: unknown } | null)?.code
126
+ return code === 'EPERM' || code === 'EBUSY' || code === 'EACCES' || code === 'EEXIST'
127
+ }
128
+
119
129
  const COMPRESSION_IDS = new Set([
120
130
  'compaction',
121
131
  'compaction-basic',
@@ -224,7 +234,7 @@ class PresetOverlayStore {
224
234
  // still private. No reader can observe a colliding {mtimeMs,size}
225
235
  // between rename and a later corrective utimes call.
226
236
  await this.disambiguateStamp(staging, identity)
227
- await rename(staging, path)
237
+ await this.publish(staging, path)
228
238
  } catch (error) {
229
239
  // A failed publish must not leak its staging file into the store; the
230
240
  // cleanup must never mask the original failure either.
@@ -238,6 +248,55 @@ class PresetOverlayStore {
238
248
  return { ...preset, path }
239
249
  }
240
250
 
251
+ /** In-flight publish chains, one per destination path. */
252
+ private readonly publishChains = new Map<string, Promise<void>>()
253
+
254
+ /**
255
+ * Publish one stamped staging file to its final path, serialized per path.
256
+ *
257
+ * POSIX `rename` replaces an existing destination atomically, so concurrent
258
+ * composers of one identity are naturally idempotent there. Windows
259
+ * `MoveFileEx` instead fails the loser of that race with EPERM/EBUSY, which
260
+ * surfaced as `standingKeyFor()` throwing during concurrent composition.
261
+ * Every composer of one identity writes identical bytes and re-derives the
262
+ * same deterministic identity stamp, so a destination that already observes
263
+ * this staging file's {mtimeMs, size} key IS the intended end state: confirm
264
+ * it and treat the lost race as success. Every other outcome still throws, so
265
+ * a silently reused generation stays forbidden, and the caller still removes
266
+ * the staging file when this rejects.
267
+ */
268
+ private publish(staging: string, path: string): Promise<void> {
269
+ const previous = this.publishChains.get(path) ?? Promise.resolve()
270
+ const queued = previous.catch(() => undefined).then(async () => {
271
+ try {
272
+ await rename(staging, path)
273
+ return
274
+ } catch (error) {
275
+ if (!isPublishRace(error)) throw error
276
+ try {
277
+ const intended = await this.metadataIo.read(staging)
278
+ const published = await this.metadataIo.read(path)
279
+ // Sub-second precision survives a wrapped seconds field, but NTFS
280
+ // rounds it to 100ns, so compare the standing key within that
281
+ // rounding rather than by exact float equality.
282
+ if (published.size === intended.size
283
+ && Math.abs(published.mtimeMs - intended.mtimeMs) < 2) {
284
+ await rm(staging, { force: true })
285
+ return
286
+ }
287
+ } catch {
288
+ // The destination is unreadable: report the original publish failure.
289
+ }
290
+ throw error
291
+ }
292
+ })
293
+ const tracked = queued.finally(() => {
294
+ if (this.publishChains.get(path) === tracked) this.publishChains.delete(path)
295
+ })
296
+ this.publishChains.set(path, tracked)
297
+ return tracked
298
+ }
299
+
241
300
  /** Observed {mtimeMs,size} keys published by this store, per identity. */
242
301
  private readonly standingKeys = new Map<string, string>()
243
302