dsh-remote-vs 0.26.0 → 0.28.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 (75) hide show
  1. package/README.en.md +112 -28
  2. package/README.md +84 -25
  3. package/THIRD-PARTY-NOTICES.md +7 -2
  4. package/lib/client.js +1237 -254
  5. package/lib/index.js +821 -17
  6. package/lib/types/changes/recorder.d.ts +119 -2
  7. package/lib/types/client/CodeEditor.d.ts +29 -0
  8. package/lib/types/client/OutlinePanel.d.ts +22 -0
  9. package/lib/types/client/ProcessesSection.d.ts +19 -0
  10. package/lib/types/client/api.d.ts +22 -2
  11. package/lib/types/client/blame-model.d.ts +77 -0
  12. package/lib/types/client/changes/apply-failure.d.ts +41 -0
  13. package/lib/types/client/changes/block-confirm.d.ts +97 -0
  14. package/lib/types/client/changes/diff-outcome.d.ts +56 -0
  15. package/lib/types/client/changes/freshness.d.ts +51 -0
  16. package/lib/types/client/changes/model.d.ts +19 -1
  17. package/lib/types/client/changes/session-diff.d.ts +100 -0
  18. package/lib/types/client/changes/staleness.d.ts +98 -0
  19. package/lib/types/client/changes/turn-reverted.d.ts +82 -0
  20. package/lib/types/client/changes/turn-view.d.ts +131 -0
  21. package/lib/types/client/changes/undo-affordance.d.ts +44 -10
  22. package/lib/types/client/changes/undo-target.d.ts +12 -0
  23. package/lib/types/client/i18n.d.ts +1 -1
  24. package/lib/types/client/outline-model.d.ts +59 -0
  25. package/lib/types/client/scm/actions.d.ts +12 -1
  26. package/lib/types/client/store.d.ts +109 -1
  27. package/lib/types/client/vsc/blame.d.ts +19 -0
  28. package/lib/types/client/vsc/change-marks.d.ts +21 -0
  29. package/lib/types/client/vsc/kit.d.ts +0 -2
  30. package/lib/types/client/vsc/preview-document.d.ts +46 -0
  31. package/lib/types/client/vsc/preview-model.d.ts +31 -0
  32. package/lib/types/client/vsc/preview-services.d.ts +24 -0
  33. package/lib/types/git-ops.d.ts +18 -0
  34. package/lib/types/processes.d.ts +43 -0
  35. package/lib/types/protocol.d.ts +133 -1
  36. package/package.json +2 -1
  37. package/src/changes/recorder.ts +851 -8
  38. package/src/client/CodeEditor.tsx +86 -4
  39. package/src/client/EditorPane.tsx +581 -41
  40. package/src/client/MonitorView.tsx +16 -5
  41. package/src/client/OutlinePanel.tsx +287 -0
  42. package/src/client/ProcessesSection.tsx +292 -0
  43. package/src/client/api.ts +38 -3
  44. package/src/client/blame-model.ts +242 -0
  45. package/src/client/changes/ChangesDock.tsx +539 -54
  46. package/src/client/changes/apply-failure.ts +73 -0
  47. package/src/client/changes/block-confirm.ts +180 -0
  48. package/src/client/changes/changes.css +45 -0
  49. package/src/client/changes/diff-outcome.ts +97 -0
  50. package/src/client/changes/freshness.ts +68 -0
  51. package/src/client/changes/model.ts +56 -1
  52. package/src/client/changes/session-diff.ts +187 -0
  53. package/src/client/changes/staleness.ts +148 -0
  54. package/src/client/changes/turn-reverted.ts +254 -0
  55. package/src/client/changes/turn-view.ts +195 -0
  56. package/src/client/changes/undo-affordance.ts +295 -63
  57. package/src/client/changes/undo-target.ts +12 -0
  58. package/src/client/i18n.ts +294 -2
  59. package/src/client/index.tsx +4 -0
  60. package/src/client/outline-model.ts +775 -0
  61. package/src/client/scm/DiffView.tsx +32 -13
  62. package/src/client/scm/HistoryPanel.tsx +38 -1
  63. package/src/client/scm/actions.ts +55 -2
  64. package/src/client/store.tsx +446 -21
  65. package/src/client/vsc/blame.ts +147 -0
  66. package/src/client/vsc/change-marks.ts +21 -0
  67. package/src/client/vsc/kit.tsx +3 -11
  68. package/src/client/vsc/preview-document.tsx +326 -0
  69. package/src/client/vsc/preview-model.ts +216 -0
  70. package/src/client/vsc/preview-services.ts +118 -0
  71. package/src/client/vsc/vsc.css +965 -39
  72. package/src/git-ops.ts +34 -0
  73. package/src/processes.ts +177 -0
  74. package/src/protocol.ts +138 -1
  75. package/src/routes.ts +138 -9
@@ -54,7 +54,7 @@ import {
54
54
  type ReadResult,
55
55
  type StatusEntry,
56
56
  } from './status.ts'
57
- import { diffText, filePatch, hunkPatch } from './text-diff.ts'
57
+ import { diffText, filePatch, hunkPatch, type TextHunk } from './text-diff.ts'
58
58
 
59
59
  /** The two facts a turn boundary needs from a Session, kept cordis-free. */
60
60
  export interface LedgerTarget {
@@ -94,6 +94,13 @@ export interface SessionChangesDeps {
94
94
  * fire.
95
95
  */
96
96
  execBudgetMs?: number
97
+ /**
98
+ * Memory budget for the cached per-turn hunks and reverse patches, in bytes.
99
+ *
100
+ * Overridable so a check can exercise the over-budget degradation without
101
+ * generating four megabytes of text; the real default is {@link MAX_TURN_PATCH_BYTES}.
102
+ */
103
+ turnPatchBytes?: number
97
104
  }
98
105
 
99
106
  /** A status letter the panel can paint (untracked has no git letter of its own). */
@@ -132,6 +139,105 @@ interface FileRecord {
132
139
  beforeFrom: 'baseline' | 'head' | 'none'
133
140
  }
134
141
 
142
+ /**
143
+ * One file's comparison for the most recent COMPLETED turn.
144
+ *
145
+ * `before` is the text the file had at the previous turn's close (or, for a path
146
+ * that only became a session change in this turn, the session baseline — see
147
+ * `closeTurn`), `after` is the text at THIS turn's close. Both sides are kept so
148
+ * `turnDiff` can prove the file has not moved since (a fresh read against
149
+ * `after`) — that proof is what keeps stale hunks off the screen.
150
+ */
151
+ interface TurnFileRecord {
152
+ display: string
153
+ /** Remote absolute POSIX path (the `turnDiff` lookup key). */
154
+ path: string
155
+ status: PanelStatus | undefined
156
+ binary: boolean
157
+ /** Bytes were withheld by a read cap: no comparison, no patch. */
158
+ oversized: boolean
159
+ hunks: TextHunk[]
160
+ before: string | null
161
+ after: string | null
162
+ /** The WHOLE turn comparison as one reverse-appliable patch (`''` = none). */
163
+ filePatch: string
164
+ }
165
+
166
+ /** The last completed turn's delta, cached between turn closes. */
167
+ interface TurnDelta {
168
+ turn: number
169
+ files: RemoteChangedFile[]
170
+ added: number
171
+ deleted: number
172
+ at: number
173
+ /**
174
+ * Whether {@link TurnDelta.records} is usable.
175
+ *
176
+ * `false` = the contents blew the memory budget: the counts/files above are
177
+ * still real, but there are no hunks and no revert. Set once per session and
178
+ * never cleared (see {@link Ledger.turnDisabled}).
179
+ */
180
+ cached: boolean
181
+ reason: string | undefined
182
+ /**
183
+ * This view is incomplete — see `RemoteChangesTurnView.truncated` for the exact
184
+ * meaning (it is NOT "files is a prefix": rows that cannot be attributed are
185
+ * dropped outright).
186
+ */
187
+ truncated: true | undefined
188
+ /**
189
+ * The turn's slow scan has not landed yet: the same turn will be rebuilt once
190
+ * it does (`correctTurn`), so the row list may still grow.
191
+ */
192
+ provisional: boolean
193
+ /** Per absolute remote path. */
194
+ records: Map<string, TurnFileRecord>
195
+ /** Bytes the cached hunks/patches occupy (see {@link MAX_TURN_PATCH_BYTES}). */
196
+ bytes: number
197
+ }
198
+
199
+ /** Both sides of one path as the turn delta builder needs them. */
200
+ interface TurnSide {
201
+ /** Text on this side, or null when the side is absent / not text. */
202
+ text: string | null
203
+ binary: boolean
204
+ truncated: boolean
205
+ /**
206
+ * Whether `text: null` means "the file is absent" (known) or "the bytes were
207
+ * withheld" (unknown).
208
+ *
209
+ * Load-bearing at a turn boundary: an unknown side must never be read as an
210
+ * empty one, or the next turn reports the file as a whole-file CREATION even
211
+ * though its bytes never moved (review M2).
212
+ */
213
+ known: boolean
214
+ }
215
+
216
+ /** Text of one read result, with "nothing usable transferred" folded into null. */
217
+ function turnSideOf(read: ReadResult): TurnSide {
218
+ const binary = read.binary === true
219
+ const truncated = read.truncated === true
220
+ return {
221
+ text: read.absent || binary || truncated ? null : read.text,
222
+ binary,
223
+ truncated,
224
+ known: !binary && !truncated,
225
+ }
226
+ }
227
+
228
+ /**
229
+ * One path's remembered side at a turn close.
230
+ *
231
+ * A plain `string | null` could not tell "the file was absent" from "its bytes
232
+ * were withheld", and the two call for opposite answers at the next boundary
233
+ * (absent = a creation; withheld = no evidence at all).
234
+ */
235
+ interface TurnSideText {
236
+ text: string | null
237
+ /** False = `text` is unknown (binary or over a read cap), not "empty". */
238
+ known: boolean
239
+ }
240
+
135
241
  /** Grace added to an exec budget before the watchdog gives up on it. */
136
242
  const WATCHDOG_GRACE_MS = 5_000
137
243
  /** Sentinel for "the host call never came back". */
@@ -150,6 +256,69 @@ const DIFF_MAX_FILE_BYTES = 2 * 1024 * 1024
150
256
  /** The single-file read budget, as `readPaths` wants it. */
151
257
  const DIFF_LIMITS = { perFile: DIFF_MAX_FILE_BYTES, total: DIFF_MAX_FILE_BYTES } as const
152
258
 
259
+ /**
260
+ * Budget for ONE completed turn's **per-file hunks and reverse patches**.
261
+ *
262
+ * What it counts (and what it deliberately does NOT): the sum of every served
263
+ * file patch plus the hunk line bodies. The two FULL texts per record (`before`
264
+ * and `after`) and the `turnAfter` snapshot are not counted — they are what the
265
+ * staleness proof compares against, and they are already bounded by the scan
266
+ * caps (≲256 KiB/file, 8 MiB/turn for `after` plus the same order for `before`
267
+ * and the snapshot). So the real resident cost is this budget PLUS those texts
268
+ * (worst case ≈ 16 MiB + 4 MiB per active session), which is why the copy says
269
+ * "patches and hunk text" rather than "the turn's contents".
270
+ *
271
+ * The turn view must keep a comparison per changed file until the next turn
272
+ * closes (that is what `turnDiff` serves without re-reading the remote). 4 MiB
273
+ * fits a large refactor's patches; crossing it disables per-turn hunks for the
274
+ * session (see {@link Ledger.turnDisabled}) rather than thrashing the budget.
275
+ */
276
+ const MAX_TURN_PATCH_BYTES = 4 * 1024 * 1024
277
+
278
+ /**
279
+ * Bounds of the self-heal window (see {@link selfHealMaxAge}).
280
+ *
281
+ * The floor is a measured small repository: `git status -uno` answers in ~0.1s
282
+ * there, so 5s of staleness is already a large win over the old flat 30s — and
283
+ * the probe has been observed to take 30–60s to surface a manual edit when only
284
+ * the turn boundary and the 3/15/30s client polls apply.
285
+ *
286
+ * The ceiling is the OLD fixed value on purpose: it is what keeps the panel from
287
+ * turning into a status loop on a huge checkout (the reference monorepo answers
288
+ * in ~1.7s, i.e. a 6.8s window — still 4x its own cost, never lower for bigger
289
+ * trees).
290
+ */
291
+ const SELF_HEAL_MIN_MS = 5_000
292
+ const SELF_HEAL_MAX_MS = 30_000
293
+ /**
294
+ * How many scan durations the panel may wait before re-scanning.
295
+ *
296
+ * Self-heal is a POLL backstop, not a live watch: waiting the cost of about four
297
+ * `git status -uno` runs keeps the added load proportional to what the probe can
298
+ * afford, instead of one scan per client poll.
299
+ */
300
+ const SELF_HEAL_FACTOR = 4
301
+
302
+ /**
303
+ * How stale the ledger may get before a *poll* re-scans it.
304
+ *
305
+ * Self-tuning: the host has no idea whether this session sits in a 50-file
306
+ * repository or a monorepo, and the same 30s window is either 300x the scan cost
307
+ * (small tree: the user waits half a minute to see a manual edit) or about right
308
+ * (AOSP: still 17x). Four times the LAST tracked scan, clamped to
309
+ * [{@link SELF_HEAL_MIN_MS}, {@link SELF_HEAL_MAX_MS}].
310
+ *
311
+ * An unknown / failed measurement falls back to the old ceiling, so a Host that
312
+ * has not scanned anything yet behaves exactly as before.
313
+ *
314
+ * @param scanMs - Duration of the last successful tracked scan, in ms.
315
+ */
316
+ export function selfHealMaxAge(scanMs?: number): number {
317
+ if (scanMs === undefined || !Number.isFinite(scanMs) || scanMs < 0) return SELF_HEAL_MAX_MS
318
+ const scaled = Math.round(scanMs * SELF_HEAL_FACTOR)
319
+ return Math.min(SELF_HEAL_MAX_MS, Math.max(SELF_HEAL_MIN_MS, scaled))
320
+ }
321
+
153
322
  /** One session's bookkeeping. */
154
323
  interface Ledger {
155
324
  sessionId: string
@@ -197,6 +366,15 @@ interface Ledger {
197
366
  untrackedAt: number
198
367
  /** How long the last completed untracked scan took, for the cadence. */
199
368
  untrackedMs: number | undefined
369
+ /**
370
+ * How long the last successful TRACKED scan took (ms).
371
+ *
372
+ * Feeds {@link selfHealMaxAge}: a repository whose `git status -uno` answers in
373
+ * ~100ms can be re-polled every few seconds, while a monorepo (1.7s measured)
374
+ * keeps a much longer self-heal window so the panel cannot turn into a status
375
+ * loop. Internal only — not exposed on the summary.
376
+ */
377
+ scanMs: number | undefined
200
378
  /** In-flight untracked scan, so a turn boundary cannot start a second one. */
201
379
  untrackedJob: Promise<void> | undefined
202
380
  turn: number
@@ -212,6 +390,63 @@ interface Ledger {
212
390
  /** Serialized background work; a second schedule coalesces into one run. */
213
391
  queue: Promise<void>
214
392
  dirty: boolean
393
+ /**
394
+ * The latest turn that closed since the last publish consumed it.
395
+ *
396
+ * `endTurn` only records the boundary; the delta itself is computed inside
397
+ * `publish`, AFTER its root/publishSeq gates. Computing it in `endTurn` would
398
+ * race the very refresh it is about to schedule (the file reads are the
399
+ * expensive part), and also miss the untracked scan that a turn's new files
400
+ * arrive through.
401
+ */
402
+ pendingClose: number | undefined
403
+ /**
404
+ * Every LISTED path's side at the previous turn close (see `TurnSideText`:
405
+ * `known: false` = the bytes were withheld, so the value says nothing about
406
+ * whether the file was there). This is the "before" side of the next turn's
407
+ * delta; it moves only when a turn closes, so a mid-turn poll cannot fold the
408
+ * session's own work into the next turn.
409
+ */
410
+ turnAfter: Map<string, TurnSideText> | undefined
411
+ /**
412
+ * The previous close's snapshot was cut by the file cap.
413
+ *
414
+ * A path missing from a truncated snapshot is not evidence that it was not
415
+ * dirty then, so "new to the list = changed this turn" becomes a guess. The
416
+ * ledger stops attributing rather than guessing (see {@link turnDisabled}).
417
+ */
418
+ turnAfterTruncated: boolean
419
+ /** The most recent completed turn's delta (what `summary().turnView` reports). */
420
+ turnDelta: TurnDelta | undefined
421
+ /**
422
+ * The snapshot the CURRENT delta was computed against.
423
+ *
424
+ * Kept so a late `git ls-files --others` result can RECOMPUTE the same turn:
425
+ * the slow walk is what discovers files a turn created, and it lands after the
426
+ * turn's tracked scan by design. Without this the delta would either miss them
427
+ * or attribute them to the next turn.
428
+ */
429
+ turnBefore: Map<string, TurnSideText> | undefined
430
+ /**
431
+ * Whether THAT snapshot was cut by the file cap.
432
+ *
433
+ * Kept apart from {@link turnAfterTruncated}: a correction compares against the
434
+ * snapshot the delta was built from, while the close records the one the NEXT
435
+ * turn will use. Sharing one flag made the correction of a turn that had just
436
+ * crossed the cap silently drop every row it had.
437
+ */
438
+ turnBeforeTruncated: boolean
439
+ /** The current delta is still waiting for its turn's slow scan to land. */
440
+ turnProvisional: boolean
441
+ /**
442
+ * Why per-turn views stopped for this session; sticky.
443
+ *
444
+ * Currently one source: the memory budget. Once the hunks of a turn were
445
+ * dropped, its "before" side was never advanced, so continuing would attribute
446
+ * an older change to the newest turn — worse than not having the view at all.
447
+ * The session-cumulative view is unaffected.
448
+ */
449
+ turnDisabled: string | undefined
215
450
  /**
216
451
  * Monotonic publish ledger: only the LATEST started publish may write.
217
452
  *
@@ -234,6 +469,12 @@ function posixJoin(base: string, rel: string): string {
234
469
  return right === '' ? left : `${left}/${right}`
235
470
  }
236
471
 
472
+ /** The inverse of {@link posixJoin} for a path under `root`; '' when it is not. */
473
+ function displayUnder(root: string, path: string): string {
474
+ const base = root.endsWith('/') ? root : `${root}/`
475
+ return path.startsWith(base) ? path.slice(base.length) : ''
476
+ }
477
+
237
478
  /**
238
479
  * Whether two reads prove the file did not move between them.
239
480
  *
@@ -274,7 +515,16 @@ export class SessionChanges {
274
515
  if (this.disposed) return
275
516
  const ledger = this.ensure(target)
276
517
  if (ledger === undefined) return
518
+ /*
519
+ * Two events deliver the SAME boundary: `turn/end` and
520
+ * `agent/turn-stopping`. Re-opening it after it was consumed would make the
521
+ * next publish close the same turn again — with `turnAfter` already advanced,
522
+ * that second delta is empty and would overwrite the real one (review S3).
523
+ * A boundary is therefore recorded only when it moves the ledger forward.
524
+ */
525
+ const advanced = turn > ledger.turn
277
526
  ledger.turn = Math.max(ledger.turn, turn)
527
+ if (advanced) ledger.pendingClose = turn
278
528
  this.schedule(ledger)
279
529
  }
280
530
 
@@ -327,6 +577,28 @@ export class SessionChanges {
327
577
  pending: ledger.untrackedJob !== undefined || (ledger.pending && ledger.files.length > 0),
328
578
  ...(ledger.truncated === true ? { truncated: true as const } : {}),
329
579
  ...(unavailable === undefined ? {} : { unavailable }),
580
+ /*
581
+ * The turn view rides along with every summary: the panel polls ONE route,
582
+ * and a second request just to learn "is there a turn delta" would double
583
+ * the poll cost. Omitted entirely when no turn has closed yet, which is
584
+ * what keeps an older client (and a session that never finished a turn)
585
+ * on the cumulative list.
586
+ */
587
+ ...(ledger.turnDelta === undefined ? {} : {
588
+ turnView: {
589
+ turn: ledger.turnDelta.turn,
590
+ files: ledger.turnDelta.files,
591
+ added: ledger.turnDelta.added,
592
+ deleted: ledger.turnDelta.deleted,
593
+ at: ledger.turnDelta.at,
594
+ cached: ledger.turnDelta.cached,
595
+ ...(ledger.turnDelta.reason === undefined ? {} : { reason: ledger.turnDelta.reason }),
596
+ ...(ledger.turnDelta.truncated === true ? { truncated: true as const } : {}),
597
+ // The turn's own slow scan has not landed yet: the rows may still grow
598
+ // (the same turn is rebuilt, never relabelled as the next one).
599
+ ...(ledger.turnDelta.provisional ? { pending: true as const } : {}),
600
+ },
601
+ }),
330
602
  }
331
603
  }
332
604
 
@@ -407,6 +679,23 @@ export class SessionChanges {
407
679
  patch: reverse === '' ? '' : hunkPatch(record.display, hunk),
408
680
  }))
409
681
  if (hunks.length === 0) {
682
+ /**
683
+ * Both sides were READ and compared, so "no hunks" means the file is back
684
+ * at its session baseline (the change was reverted, or an identical byte
685
+ * round-trip). That is NOT "missing": the panel shows `missing` as "the
686
+ * remote cannot read this file", and saying that about a file the host
687
+ * just read is a lie that also hides "your change is gone". A withheld
688
+ * side (null) keeps `missing` — there is genuinely nothing to compare.
689
+ */
690
+ /**
691
+ * 判定只看**改后那一侧读到了**:新建的空文件 before 是 null(不存在),after
692
+ * 读到 `''`,零 hunk 是"读到了、只是没有内容",不是"读不到"。老条件要求两侧
693
+ * 都非 null,于是会话新建的空文件被报成 `missing`,面板显示「远端读不到」
694
+ * (审核 NIT-1)。
695
+ */
696
+ if (afterText !== null) {
697
+ return { kind: 'text', path, display: record.display, hunks: [], ...(status === undefined ? {} : { status }) }
698
+ }
410
699
  return { kind: 'missing', path, display: record.display, hunks: [], ...(status === undefined ? {} : { status }) }
411
700
  }
412
701
  return {
@@ -420,6 +709,135 @@ export class SessionChanges {
420
709
  }
421
710
  }
422
711
 
712
+ /**
713
+ * One file's comparison for the most recent COMPLETED turn.
714
+ *
715
+ * Same shape as {@link diff} (the editor paints both the same way), but the
716
+ * "before" side is the previous turn's close instead of the session baseline.
717
+ * The hunks are served from the turn delta's cache, so this call costs NO
718
+ * remote work in the common case — but a cached comparison is only worth
719
+ * showing while it still describes the disk. That is why the `after` side is
720
+ * read back here and compared with the cached text FIRST: if the file moved on
721
+ * after the turn closed (a later save, a terminal command, an agent), the
722
+ * answer is `stale` and the client falls back to the session view instead of
723
+ * painting line numbers that no longer exist.
724
+ *
725
+ * @param sessionId - live session owning the ledger.
726
+ * @param path - the file's remote absolute path (as listed in `turnView.files`).
727
+ * @returns hunks for decorations, `unavailable`/`stale` with a reason, or null
728
+ * when the session itself is unknown.
729
+ */
730
+ async turnDiff(sessionId: string, path: string): Promise<RemoteChangesDiff | null> {
731
+ const ledger = this.ledgers.get(sessionId)
732
+ if (ledger === undefined) return null
733
+ const delta = ledger.turnDelta
734
+ const display = delta?.records.get(path)?.display ?? displayUnder(ledger.root, path)
735
+ if (delta === undefined) {
736
+ return {
737
+ kind: 'unavailable',
738
+ path,
739
+ display,
740
+ hunks: [],
741
+ reason: 'no turn has closed since this session started',
742
+ }
743
+ }
744
+ if (!delta.cached) {
745
+ return {
746
+ kind: 'unavailable',
747
+ path,
748
+ display,
749
+ hunks: [],
750
+ reason: delta.reason ?? 'per-turn change contents are not cached for this session',
751
+ }
752
+ }
753
+ const record = delta.records.get(path)
754
+ if (record === undefined) {
755
+ return {
756
+ kind: 'unavailable',
757
+ path,
758
+ display,
759
+ hunks: [],
760
+ reason: `this file is not part of turn ${delta.turn}'s change set`,
761
+ }
762
+ }
763
+ const status = record.status
764
+ if (record.binary) {
765
+ return { kind: 'binary', path, display: record.display, hunks: [], ...(status === undefined ? {} : { status }) }
766
+ }
767
+ if (record.oversized) {
768
+ return {
769
+ kind: 'unavailable',
770
+ path,
771
+ display: record.display,
772
+ hunks: [],
773
+ reason: 'the bytes of this file were withheld by the size cap, so there is no line-level comparison',
774
+ ...(status === undefined ? {} : { status }),
775
+ }
776
+ }
777
+ /**
778
+ * Verify the cache against the disk before serving it.
779
+ *
780
+ * A failed read is NOT "unchanged": without evidence the honest answer is
781
+ * `unavailable` (no palatable guess). A binary or cap-truncated read proves
782
+ * the bytes moved on after the turn closed, which is exactly `stale`.
783
+ */
784
+ const fresh = await this.readPaths(ledger, [record.display], 'worktree', DIFF_LIMITS)
785
+ if (ledger.disposed) return null
786
+ const side = fresh.get(record.display)
787
+ if (side === undefined) {
788
+ return {
789
+ kind: 'unavailable',
790
+ path,
791
+ display: record.display,
792
+ hunks: [],
793
+ reason: 'the file could not be read back from the host, so the turn comparison cannot be verified',
794
+ ...(status === undefined ? {} : { status }),
795
+ }
796
+ }
797
+ const current = turnSideOf(side)
798
+ if (current.binary || current.truncated) {
799
+ return {
800
+ kind: 'stale',
801
+ path,
802
+ display: record.display,
803
+ hunks: [],
804
+ reason: current.binary
805
+ ? 'the file has become binary since the turn closed'
806
+ : 'the file has grown past the read budget since the turn closed',
807
+ ...(status === undefined ? {} : { status }),
808
+ }
809
+ }
810
+ if (current.text !== record.after) {
811
+ return {
812
+ kind: 'stale',
813
+ path,
814
+ display: record.display,
815
+ hunks: [],
816
+ reason: 'the file was modified after the turn closed',
817
+ ...(status === undefined ? {} : { status }),
818
+ }
819
+ }
820
+ const hunks: UnifiedHunk[] = record.hunks.map(hunk => ({
821
+ oldStart: hunk.oldStart,
822
+ oldCount: hunk.oldLines,
823
+ newStart: hunk.newStart,
824
+ newCount: hunk.newLines,
825
+ heading: '',
826
+ lines: hunk.lines,
827
+ // Same rule as `diff`: a real `git apply -R` patch per hunk, empty when the
828
+ // turn's reverse cannot be expressed (a whole-file creation).
829
+ patch: record.filePatch === '' ? '' : hunkPatch(record.display, hunk),
830
+ }))
831
+ return {
832
+ kind: 'text',
833
+ path,
834
+ display: record.display,
835
+ hunks,
836
+ ...(record.filePatch === '' ? {} : { patch: record.filePatch }),
837
+ ...(status === undefined ? {} : { status }),
838
+ }
839
+ }
840
+
423
841
  /** Resolve once every queued refresh has settled, including coalesced work. */
424
842
  async settled(): Promise<void> {
425
843
  for (let guard = 0; guard < 100; guard += 1) {
@@ -477,16 +895,25 @@ export class SessionChanges {
477
895
  * Self-heal a ledger whose data has gone stale.
478
896
  *
479
897
  * The panel polls `list`, and a poll is the one moment we know a human is
480
- * looking at the answer. If the data is older than `maxAgeMs`, re-scan — so a
898
+ * looking at the answer. If the data is older than the window, re-scan — so a
481
899
  * turn boundary this Host never delivered costs a few seconds of staleness
482
900
  * instead of a manual refresh.
483
901
  *
902
+ * The window is ADAPTIVE ({@link selfHealMaxAge}): four times the last tracked
903
+ * scan, clamped to 5–30s. A small repository therefore surfaces a manual edit
904
+ * (one with no turn event behind it) within seconds instead of the old fixed
905
+ * half minute, while a monorepo keeps the old ceiling. The two `false` paths —
906
+ * a scan already running, and data that is still fresh — are unchanged.
907
+ *
908
+ * @param maxAgeMs - explicit window; callers that know better (and the checks)
909
+ * override the adaptive default and keep the old semantics exactly.
484
910
  * @returns whether a refresh was queued.
485
911
  */
486
- touch(sessionId: string, maxAgeMs = 30_000): boolean {
912
+ touch(sessionId: string, maxAgeMs?: number): boolean {
487
913
  const ledger = this.ledgers.get(sessionId)
488
914
  if (ledger === undefined || ledger.disposed || ledger.pending) return false
489
- if (ledger.at > 0 && Date.now() - ledger.at < maxAgeMs) return false
915
+ const windowMs = maxAgeMs ?? selfHealMaxAge(ledger.scanMs)
916
+ if (ledger.at > 0 && Date.now() - ledger.at < windowMs) return false
490
917
  this.schedule(ledger)
491
918
  return true
492
919
  }
@@ -539,6 +966,10 @@ export class SessionChanges {
539
966
  ledger.untracked = undefined
540
967
  ledger.untrackedAt = 0
541
968
  ledger.untrackedMs = undefined
969
+ // The self-heal window describes THIS tree's scan cost; another root may be
970
+ // far bigger or smaller (`selfHealMaxAge` then falls back to the 30s ceiling
971
+ // until the first scan of the new root is measured).
972
+ ledger.scanMs = undefined
542
973
  ledger.untrackedGivenUp = false
543
974
  ledger.untrackedFailure = undefined
544
975
  ledger.files = []
@@ -553,6 +984,18 @@ export class SessionChanges {
553
984
  // appeared in the new one before the move "session work" (and list them with
554
985
  // whole-file counts). Restart it with the rest of the observation.
555
986
  ledger.startedAt = Date.now()
987
+ // The turn delta describes the previous tree: its paths are relative to the
988
+ // old root and its patch headers would apply in the wrong checkout. Drop it
989
+ // with the rest of the observation. `turnDisabled` deliberately stays — it is
990
+ // a verdict about this session's size (like `publishSeq`, which is not an
991
+ // observation either), and re-enabling it would only re-blow the budget.
992
+ ledger.pendingClose = undefined
993
+ ledger.turnAfter = undefined
994
+ ledger.turnAfterTruncated = false
995
+ ledger.turnDelta = undefined
996
+ ledger.turnBefore = undefined
997
+ ledger.turnBeforeTruncated = false
998
+ ledger.turnProvisional = false
556
999
  }
557
1000
 
558
1001
  // ------------------------------------------------------------- internals
@@ -628,6 +1071,7 @@ export class SessionChanges {
628
1071
  untracked: undefined,
629
1072
  untrackedAt: 0,
630
1073
  untrackedMs: undefined,
1074
+ scanMs: undefined,
631
1075
  untrackedJob: undefined,
632
1076
  turn: 0,
633
1077
  files: [],
@@ -640,6 +1084,14 @@ export class SessionChanges {
640
1084
  pending: false,
641
1085
  queue: Promise.resolve(),
642
1086
  dirty: false,
1087
+ pendingClose: undefined,
1088
+ turnAfter: undefined,
1089
+ turnAfterTruncated: false,
1090
+ turnDelta: undefined,
1091
+ turnBefore: undefined,
1092
+ turnBeforeTruncated: false,
1093
+ turnProvisional: false,
1094
+ turnDisabled: undefined,
643
1095
  publishSeq: 0,
644
1096
  disposed: false,
645
1097
  }
@@ -678,6 +1130,7 @@ export class SessionChanges {
678
1130
  */
679
1131
  private async refresh(ledger: Ledger): Promise<void> {
680
1132
  if (ledger.disposed || ledger.root === '') return
1133
+ const scanStartedAt = Date.now()
681
1134
  const scanned = await this.scanTracked(ledger)
682
1135
  if (ledger.disposed || scanned === undefined) return
683
1136
  // The root may have moved while the scan was in flight (the user picked
@@ -685,13 +1138,24 @@ export class SessionChanges {
685
1138
  // belong to, so a mismatch means someone else owns the observation now —
686
1139
  // publish nothing and let that caller's own refresh land.
687
1140
  if (ledger.root !== scanned.root) return
1141
+ // What this tree's tracked scan costs is what its self-heal window is derived
1142
+ // from (`selfHealMaxAge`). Only successful scans are measured: a timeout or a
1143
+ // missing repository says nothing about the cost of a real answer.
1144
+ ledger.scanMs = Math.max(0, Date.now() - scanStartedAt)
688
1145
  ledger.tracked = scanned.entries
689
1146
  await this.publish(ledger)
690
1147
  void this.kickUntracked(ledger)
691
1148
  }
692
1149
 
693
- /** Recompute the panel's list from the scans currently known. */
694
- private async publish(ledger: Ledger): Promise<void> {
1150
+ /**
1151
+ * Recompute the panel's list from the scans currently known.
1152
+ *
1153
+ * @param fromSlowScan - this publish was triggered by the `git ls-files
1154
+ * --others` walk. A turn delta closed before that walk landed is still
1155
+ * provisional: this flag is what lets it be re-derived once the turn's new
1156
+ * files are known (see `correctTurn`).
1157
+ */
1158
+ private async publish(ledger: Ledger, fromSlowScan = false): Promise<void> {
695
1159
  if (ledger.disposed) return
696
1160
  // Ordering ticket: see Ledger.publishSeq. Taken before the first await.
697
1161
  const seq = ++ledger.publishSeq
@@ -816,6 +1280,384 @@ export class SessionChanges {
816
1280
  ? 'file contents could not be read from the host'
817
1281
  : undefined
818
1282
  ledger.at = Date.now()
1283
+ /*
1284
+ * The turn delta is derived from the SAME snapshot the panel just received
1285
+ * and only after the two write gates above: it compares against "what the
1286
+ * file looked like when the previous turn closed", so it must not be fed an
1287
+ * older (or mixed-root) list. A publish that only carries the slow scan's
1288
+ * result instead CORRECTS the turn it already closed.
1289
+ */
1290
+ if (ledger.pendingClose !== undefined) {
1291
+ await this.closeTurn(ledger, root, seq, entries, listed, after, records, truncated)
1292
+ } else if (fromSlowScan) {
1293
+ await this.correctTurn(ledger, root, seq, entries, listed, after, records, truncated)
1294
+ }
1295
+ }
1296
+
1297
+ /**
1298
+ * Close one turn: compute "what did it change" and remember this close as the
1299
+ * next turn's starting point.
1300
+ *
1301
+ * The delta is defined against the PREVIOUS close, not the session baseline, so
1302
+ * a file the session changed in turn 1 and left alone in turn 2 must not appear
1303
+ * in turn 2's list — otherwise the view says the same work happened twice.
1304
+ * That is what `turnAfter` is for: it holds every listed path's text at the
1305
+ * moment the previous turn closed, and it is replaced (never merged) here.
1306
+ *
1307
+ * A failed `after` read leaves the boundary unconsumed, so the next publish
1308
+ * retries instead of recording a turn against "nothing".
1309
+ */
1310
+ private async closeTurn(
1311
+ ledger: Ledger,
1312
+ root: string,
1313
+ seq: number,
1314
+ entries: readonly StatusEntry[],
1315
+ listed: readonly StatusEntry[],
1316
+ after: Map<string, ReadResult>,
1317
+ records: Map<string, FileRecord>,
1318
+ truncated: boolean,
1319
+ ): Promise<void> {
1320
+ const turn = ledger.pendingClose
1321
+ if (turn === undefined || ledger.disposed) return
1322
+ // A written-off session must not keep a boundary around: nothing will ever
1323
+ // consume it, and `endTurn` would only re-set it on the next turn.
1324
+ ledger.pendingClose = undefined
1325
+ if (ledger.turnDisabled !== undefined) return
1326
+ const known = ledger.turnAfter
1327
+ const collected = await this.collectTurnSides(ledger, root, seq, listed, after, known)
1328
+ if (collected.kind === 'retry') {
1329
+ ledger.pendingClose = turn
1330
+ return
1331
+ }
1332
+ if (collected.kind === 'superseded') return
1333
+ /**
1334
+ * A previous snapshot cut by the file cap cannot prove that a path MISSING
1335
+ * from it was clean — it may simply have been past the cap. Entries that were
1336
+ * listed then are still exact, so only the "newcomer = changed this turn"
1337
+ * inference is dropped, and the view says it is partial (`truncated`).
1338
+ */
1339
+ const partial = ledger.turnAfterTruncated
1340
+ /*
1341
+ * If the PREVIOUS turn's slow scan never landed before this close, its
1342
+ * snapshot may be missing files — so this turn's "newcomer = changed now"
1343
+ * inference is unreliable too. The new view therefore keeps saying it is
1344
+ * partial (review S2).
1345
+ */
1346
+ const previousUncorrected = ledger.turnProvisional
1347
+ const built = this.buildTurnDelta(root, turn, collected.now, entries, records, known, partial, truncated)
1348
+ this.storeTurnDelta(ledger, built, previousUncorrected)
1349
+ if (built.overflow) return
1350
+ ledger.turnBefore = known
1351
+ ledger.turnBeforeTruncated = partial
1352
+ ledger.turnProvisional = true
1353
+ /**
1354
+ * This close becomes the next turn's starting point. Built from `listed`
1355
+ * ONLY: a path that left the dirty list is at its baseline, and the session
1356
+ * baseline is exactly what a re-appearance will be compared against — keeping
1357
+ * it here would cost a full re-read of every reverted file on every later
1358
+ * turn.
1359
+ */
1360
+ ledger.turnAfter = this.turnSnapshotOf(listed, collected.now)
1361
+ ledger.turnAfterTruncated = truncated
1362
+ }
1363
+
1364
+ /**
1365
+ * Re-derive the CURRENT turn's delta once the slow scan behind it has landed.
1366
+ *
1367
+ * A turn's new files are discovered by `git ls-files --others`, which runs
1368
+ * after the tracked scan by design and can land seconds later. Rebuilding the
1369
+ * same turn from the SAME "before" snapshot (kept in `turnBefore`) is what
1370
+ * makes those files appear in the turn they belong to instead of in the next
1371
+ * one. Guarded against the two ways this could lie: a newer turn boundary
1372
+ * (which supersedes this delta) and a root move.
1373
+ */
1374
+ private async correctTurn(
1375
+ ledger: Ledger,
1376
+ root: string,
1377
+ seq: number,
1378
+ entries: readonly StatusEntry[],
1379
+ listed: readonly StatusEntry[],
1380
+ after: Map<string, ReadResult>,
1381
+ records: Map<string, FileRecord>,
1382
+ truncated: boolean,
1383
+ ): Promise<void> {
1384
+ const delta = ledger.turnDelta
1385
+ const before = ledger.turnBefore
1386
+ // `before === undefined` is legitimate on the FIRST turn (there is no previous
1387
+ // close): the delta then compares against the session baseline, so the
1388
+ // correction must run there too or a turn's new files never arrive.
1389
+ if (!ledger.turnProvisional || delta === undefined) return
1390
+ // Only the first slow-scan publish after the close may correct it, and only
1391
+ // while its turn is still the current one.
1392
+ ledger.turnProvisional = false
1393
+ if (ledger.turnDisabled !== undefined || ledger.turn !== delta.turn) return
1394
+ const collected = await this.collectTurnSides(ledger, root, seq, listed, after, before)
1395
+ if (collected.kind !== 'ok') return
1396
+ // The correction compares against `turnBefore`, so it must use THAT snapshot's
1397
+ // cap verdict — not the one the close just stored for the next turn.
1398
+ const partial = ledger.turnBeforeTruncated
1399
+ const built = this.buildTurnDelta(root, delta.turn, collected.now, entries, records, before, partial, truncated)
1400
+ // `previousUncorrected` is false here: this IS the correction, so it must not
1401
+ // carry the "previous view was uncorrected" verdict forward.
1402
+ this.storeTurnDelta(ledger, built, false)
1403
+ if (built.overflow) return
1404
+ // The correction has landed: the view is final for this turn.
1405
+ const stored = ledger.turnDelta
1406
+ if (stored !== undefined) stored.provisional = false
1407
+ ledger.turnAfter = this.turnSnapshotOf(listed, collected.now)
1408
+ }
1409
+
1410
+ /** Remember one close's sides for the next boundary (see `TurnSideText`). */
1411
+ private turnSnapshotOf(
1412
+ listed: readonly StatusEntry[],
1413
+ now: Map<string, TurnSide>,
1414
+ ): Map<string, TurnSideText> {
1415
+ const snapshot = new Map<string, TurnSideText>()
1416
+ for (const entry of listed) {
1417
+ const side = now.get(entry.path)
1418
+ snapshot.set(entry.path, { text: side?.text ?? null, known: side?.known ?? false })
1419
+ }
1420
+ return snapshot
1421
+ }
1422
+
1423
+ /**
1424
+ * The "after" side of one turn close, in `display` space.
1425
+ *
1426
+ * Starts from the publish's own reads (every listed path), then reads the paths
1427
+ * the PREVIOUS close listed but this publish does not: those left the dirty
1428
+ * list (reverted to their baseline, deleted, restored), and without reading
1429
+ * them now the revert would be attributed to nobody — "the turn put the file
1430
+ * back" would look like "the turn changed nothing".
1431
+ *
1432
+ * @returns `ok` with the sides; `retry` when a read failed (the caller keeps
1433
+ * the turn boundary for the next publish); `superseded` when a root move or
1434
+ * a newer publish already owns the observation.
1435
+ */
1436
+ private async collectTurnSides(
1437
+ ledger: Ledger,
1438
+ root: string,
1439
+ seq: number,
1440
+ listed: readonly StatusEntry[],
1441
+ after: Map<string, ReadResult>,
1442
+ known: Map<string, TurnSideText> | undefined,
1443
+ ): Promise<{ kind: 'ok'; now: Map<string, TurnSide> } | { kind: 'retry' } | { kind: 'superseded' }> {
1444
+ // No "after" side at all (the reads failed): there is nothing to compare.
1445
+ if (listed.length > 0 && after.size === 0) return { kind: 'retry' }
1446
+ const now = new Map<string, TurnSide>()
1447
+ for (const entry of listed) {
1448
+ const side = after.get(entry.path)
1449
+ if (side === undefined) return { kind: 'retry' }
1450
+ now.set(entry.path, turnSideOf(side))
1451
+ }
1452
+ const vanished = known === undefined ? [] : [...known.keys()].filter(display => !now.has(display))
1453
+ if (vanished.length === 0) return { kind: 'ok', now }
1454
+ const reads = await this.readPaths(ledger, vanished, 'worktree')
1455
+ if (ledger.disposed) return { kind: 'superseded' }
1456
+ if (ledger.root !== root || ledger.publishSeq !== seq) return { kind: 'superseded' }
1457
+ if (reads.size === 0) return { kind: 'retry' }
1458
+ for (const display of vanished) {
1459
+ const side = reads.get(display)
1460
+ if (side === undefined) return { kind: 'retry' }
1461
+ now.set(display, turnSideOf(side))
1462
+ }
1463
+ return { kind: 'ok', now }
1464
+ }
1465
+
1466
+ /**
1467
+ * Compare one turn's before/after sides into panel rows plus cached hunks.
1468
+ *
1469
+ * The comparison rules are the ones the whole-session `publish` uses (binary
1470
+ * and cap-withheld bytes carry 0/0 counts, a creation has no reverse patch,
1471
+ * hunks come from the same Myers implementation), so a row means the same
1472
+ * thing in both views.
1473
+ */
1474
+ private buildTurnDelta(
1475
+ root: string,
1476
+ turn: number,
1477
+ now: Map<string, TurnSide>,
1478
+ entries: readonly StatusEntry[],
1479
+ records: Map<string, FileRecord>,
1480
+ known: Map<string, TurnSideText> | undefined,
1481
+ partial: boolean,
1482
+ capTruncated: boolean,
1483
+ ): {
1484
+ turn: number
1485
+ files: RemoteChangedFile[]
1486
+ added: number
1487
+ deleted: number
1488
+ records: Map<string, TurnFileRecord>
1489
+ bytes: number
1490
+ overflow: boolean
1491
+ /** This view drops rows it cannot attribute (see `TurnDelta.truncated`). */
1492
+ incomplete: boolean
1493
+ } {
1494
+ const statusOf = new Map<string, PanelStatus | undefined>()
1495
+ for (const entry of entries) statusOf.set(entry.path, panelStatus(entry.status))
1496
+ const budget = this.deps.turnPatchBytes ?? MAX_TURN_PATCH_BYTES
1497
+ const files: RemoteChangedFile[] = []
1498
+ const turnRecords = new Map<string, TurnFileRecord>()
1499
+ let added = 0
1500
+ let deleted = 0
1501
+ let bytes = 0
1502
+ let incomplete = partial || capTruncated
1503
+ for (const [display, side] of now) {
1504
+ const absolute = posixJoin(root, display)
1505
+ const record = records.get(absolute)
1506
+ const had = known !== undefined && known.has(display)
1507
+ // Not listed at the previous close AND not a session change now either: a
1508
+ // file the session never touched (pre-existing dirt), which is not work.
1509
+ // With a truncated previous snapshot, a newcomer is not evidence either.
1510
+ if (!had && (record === undefined || partial)) continue
1511
+ /*
1512
+ * The PREVIOUS side is unknown (its bytes were binary / over a read cap).
1513
+ * "null" here must never be read as "the file was absent": doing so turns an
1514
+ * unchanged binary/oversized file into a whole-file CREATION (review M2).
1515
+ * There is no evidence to compare, so the row is dropped and the view is
1516
+ * marked incomplete — an honest gap, not a fabricated diff. The next close
1517
+ * can attribute normally because this close records the side as readable.
1518
+ */
1519
+ const previous = had ? known.get(display) : undefined
1520
+ if (had && previous !== undefined && previous.known === false) {
1521
+ incomplete = true
1522
+ continue
1523
+ }
1524
+ /*
1525
+ * Where the "before" side comes from, in order of authority:
1526
+ * - the previous turn close, when this path was listed then (exact);
1527
+ * - the session baseline, for a path that became a session change in THIS
1528
+ * turn (the best remaining evidence, and the only side that exists);
1529
+ * - nothing, otherwise.
1530
+ */
1531
+ const before = had ? (previous?.text ?? null) : (record?.before ?? null)
1532
+ // Listed on both sides and byte-identical: the turn did not touch it.
1533
+ if (had && before === side.text) continue
1534
+ const binary = side.binary || record?.binary === true
1535
+ const oversized = !binary && (side.truncated || record?.truncated === true)
1536
+ let fileAdded = 0
1537
+ let fileDeleted = 0
1538
+ let hunks: TextHunk[] = []
1539
+ let patch = ''
1540
+ if (!binary && !oversized) {
1541
+ const result = diffText(before ?? '', side.text ?? '')
1542
+ fileAdded = result.added
1543
+ fileDeleted = result.deleted
1544
+ hunks = result.hunks
1545
+ /*
1546
+ * A whole-file creation has no reverse patch (its reverse is "delete the
1547
+ * file", which the client expresses through `revert` and only the HOST
1548
+ * may decide). Same rule as `publish`/`diff`.
1549
+ */
1550
+ patch = before !== null && hunks.length > 0 ? filePatch(display, hunks) : ''
1551
+ // Memory accounting: the patch plus the hunk bodies are what the cache
1552
+ // holds beyond the two texts (which the record needs for the staleness
1553
+ // proof) — see MAX_TURN_PATCH_BYTES.
1554
+ if (patch !== '') bytes += Buffer.byteLength(patch, 'utf8')
1555
+ for (const hunk of hunks) {
1556
+ for (const line of hunk.lines) bytes += Buffer.byteLength(line, 'utf8') + 1
1557
+ }
1558
+ }
1559
+ added += fileAdded
1560
+ deleted += fileDeleted
1561
+ const status = statusOf.get(display)
1562
+ const revert: 'patch' | undefined = patch === '' ? undefined : 'patch'
1563
+ files.push({
1564
+ path: absolute,
1565
+ display,
1566
+ added: fileAdded,
1567
+ deleted: fileDeleted,
1568
+ ...(binary ? { binary: true as const } : {}),
1569
+ ...(oversized ? { oversized: true as const } : {}),
1570
+ ...(status === undefined ? {} : { status }),
1571
+ ...(revert === undefined ? {} : { revert }),
1572
+ })
1573
+ turnRecords.set(absolute, {
1574
+ display,
1575
+ path: absolute,
1576
+ status,
1577
+ binary,
1578
+ oversized,
1579
+ hunks,
1580
+ before,
1581
+ after: side.text,
1582
+ filePatch: patch,
1583
+ })
1584
+ }
1585
+ files.sort((left, right) => left.display.localeCompare(right.display))
1586
+ return { turn, files, added, deleted, records: turnRecords, bytes, overflow: bytes > budget, incomplete }
1587
+ }
1588
+
1589
+ /**
1590
+ * Commit one built delta, degrading honestly when it blew the memory budget.
1591
+ *
1592
+ * Over budget the statistics are already computed and stay usable, but the
1593
+ * per-file hunks and patches are dropped and this session stops computing turn
1594
+ * views: keeping a half-filled snapshot would make the NEXT turn compare
1595
+ * against texts that belong to an older boundary.
1596
+ */
1597
+ private storeTurnDelta(
1598
+ ledger: Ledger,
1599
+ built: {
1600
+ turn: number
1601
+ files: RemoteChangedFile[]
1602
+ added: number
1603
+ deleted: number
1604
+ records: Map<string, TurnFileRecord>
1605
+ bytes: number
1606
+ overflow: boolean
1607
+ incomplete: boolean
1608
+ },
1609
+ /** The turn BEFORE this one closed without ever being corrected (review S2). */
1610
+ uncorrectedPrevious: boolean,
1611
+ ): void {
1612
+ const truncated = built.incomplete || uncorrectedPrevious
1613
+ if (!built.overflow) {
1614
+ ledger.turnDelta = {
1615
+ turn: built.turn,
1616
+ files: built.files,
1617
+ added: built.added,
1618
+ deleted: built.deleted,
1619
+ at: Date.now(),
1620
+ cached: true,
1621
+ reason: undefined,
1622
+ truncated: truncated ? true : undefined,
1623
+ provisional: true,
1624
+ records: built.records,
1625
+ bytes: built.bytes,
1626
+ }
1627
+ return
1628
+ }
1629
+ const budget = this.deps.turnPatchBytes ?? MAX_TURN_PATCH_BYTES
1630
+ const reason = `the per-turn patches and hunk text exceed the ${budget} byte memory budget`
1631
+ + '; turn totals stay available without per-file hunks'
1632
+ ledger.turnDelta = {
1633
+ turn: built.turn,
1634
+ files: built.files.map(file => {
1635
+ const { revert: _revert, ...rest } = file
1636
+ return rest
1637
+ }),
1638
+ added: built.added,
1639
+ deleted: built.deleted,
1640
+ at: Date.now(),
1641
+ cached: false,
1642
+ reason,
1643
+ truncated: truncated ? true : undefined,
1644
+ provisional: false,
1645
+ records: new Map(),
1646
+ bytes: built.bytes,
1647
+ }
1648
+ this.disableTurn(ledger, reason)
1649
+ }
1650
+
1651
+ /** Stop computing turn views for this session, saying why (sticky). */
1652
+ private disableTurn(ledger: Ledger, reason: string): void {
1653
+ if (ledger.turnDisabled !== undefined) return
1654
+ ledger.turnDisabled = reason
1655
+ ledger.turnAfter = undefined
1656
+ ledger.turnAfterTruncated = false
1657
+ ledger.turnBefore = undefined
1658
+ ledger.turnBeforeTruncated = false
1659
+ ledger.turnProvisional = false
1660
+ this.warn(`per-turn view disabled: ${reason}`)
819
1661
  }
820
1662
 
821
1663
  /**
@@ -954,8 +1796,9 @@ export class SessionChanges {
954
1796
  ledger.untracked = parseUntrackedZ(scan.stdout)
955
1797
  await this.absorbPreExisting(ledger)
956
1798
  // A completed scan is worth one more publish: it is the only source of
957
- // "a file appeared" rows.
958
- await this.publish(ledger)
1799
+ // "a file appeared" rows — and of the per-turn delta that must include
1800
+ // them (see `correctTurn`).
1801
+ await this.publish(ledger, true)
959
1802
  })()
960
1803
  .catch(error => this.warn(`untracked scan failed: ${messageOf(error)}`))
961
1804
  .finally(() => { ledger.untrackedJob = undefined })