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
package/lib/index.js CHANGED
@@ -417,7 +417,9 @@ const REMOTE_API = {
417
417
  /** Remote listening TCP sockets for the port panel (one bounded probe). */
418
418
  listenPorts: "/api/dsh-remote/listen-ports",
419
419
  /** Live system metrics for the monitor panel (one bounded probe per host). */
420
- metrics: "/api/dsh-remote/metrics"
420
+ metrics: "/api/dsh-remote/metrics",
421
+ /** One bounded process table for the monitor page, plus TERM/KILL actions. */
422
+ processes: "/api/dsh-remote/processes"
421
423
  };
422
424
  /** Suggested/attachment file name for one multi-selection archive. */
423
425
  function selectionDownloadName(count) {
@@ -3809,6 +3811,153 @@ var HostMonitor = class {
3809
3811
  }
3810
3812
  };
3811
3813
  //#endregion
3814
+ //#region src/processes.ts
3815
+ /** Marker proving which probe branch actually ran. */
3816
+ const PROCESSES_MARK = "@@RVS-PROCS";
3817
+ /** Budget for the whole probe; a stuck process table must not pin a channel. */
3818
+ const PROCESSES_TIMEOUT_MS = 15e3;
3819
+ /**
3820
+ * One bounded probe.
3821
+ *
3822
+ * GNU first (`--sort` + `etimes`), then the portable `ps aux` table for BSD /
3823
+ * old systems (`ppid` and elapsed time are unknown there). The marker
3824
+ * line is printed BEFORE the table so an interrupted probe is distinguishable
3825
+ * from a genuinely empty one; the final marker lets the parser reject a
3826
+ * truncated run.
3827
+ */
3828
+ function processesCommand(max = 500) {
3829
+ const cap = Math.max(1, Math.min(500, Math.floor(max)));
3830
+ const gnu = `ps -eo pid=,ppid=,user:20=,pcpu=,pmem=,etimes=,args= --sort=-pcpu 2>/dev/null`;
3831
+ return [
3832
+ "export LC_ALL=C",
3833
+ `if ${gnu} >/dev/null 2>&1; then`,
3834
+ ` echo "${PROCESSES_MARK} gnu"`,
3835
+ ` ${gnu} | head -n ${cap + 1}`,
3836
+ "elif ps aux >/dev/null 2>&1; then",
3837
+ ` echo "${PROCESSES_MARK} bsd"`,
3838
+ ` ps aux | tail -n +2 | sort -k3 -rn | head -n ${cap + 1}`,
3839
+ "else",
3840
+ ` echo "${PROCESSES_MARK} none"`,
3841
+ "fi",
3842
+ `echo "${PROCESSES_MARK} end"`
3843
+ ].join("\n");
3844
+ }
3845
+ function isKillSignal(value) {
3846
+ return value === "TERM" || value === "KILL";
3847
+ }
3848
+ /** Assert a PID a process snapshot may contain (1 is the remote init). */
3849
+ function assertProcessPid(value) {
3850
+ const pid = typeof value === "number" ? value : Number(value);
3851
+ if (!Number.isInteger(pid) || pid <= 1 || pid > 2147483647) throw new Error("invalid process id");
3852
+ return pid;
3853
+ }
3854
+ /**
3855
+ * Build the one kill command. The PID has already passed the snapshot check;
3856
+ * single-quoting it keeps the command shape uniform with every other builder.
3857
+ */
3858
+ function killCommand(pid, signal) {
3859
+ return `kill -s ${signal} ${shQuote(String(assertProcessPid(pid)))}`;
3860
+ }
3861
+ function numberOr(value) {
3862
+ if (!/^[0-9]+(?:\.[0-9]+)?$/.test(value)) return null;
3863
+ const number = Number(value);
3864
+ return Number.isFinite(number) ? number : null;
3865
+ }
3866
+ /** Bound one argv line before it is serialized into the JSON response. */
3867
+ function trimCommand(command) {
3868
+ return command.length <= 300 ? command : `${command.slice(0, 299)}…`;
3869
+ }
3870
+ /** GNU row: pid ppid user pcpu pmem etimes args. */
3871
+ function parseGnuRow(line) {
3872
+ const match = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+([0-9.]+)\s+([0-9.]+)\s+(\d+)\s+(.*)$/.exec(line);
3873
+ if (match === null) return void 0;
3874
+ const pid = match[1];
3875
+ const ppid = match[2];
3876
+ const user = match[3];
3877
+ const cpu = match[4];
3878
+ const mem = match[5];
3879
+ const elapsed = match[6];
3880
+ const command = match[7];
3881
+ return {
3882
+ pid: Number(pid),
3883
+ ppid: Number(ppid),
3884
+ user,
3885
+ cpuPercent: numberOr(cpu) ?? 0,
3886
+ memPercent: numberOr(mem) ?? 0,
3887
+ elapsedSeconds: numberOr(elapsed) ?? null,
3888
+ command: trimCommand(command.trim())
3889
+ };
3890
+ }
3891
+ /** BSD `ps aux` row: user pid %cpu %mem vsz rss tt stat started time command. */
3892
+ function parseBsdRow(line) {
3893
+ const match = /^\s*(\S+)\s+(\d+)\s+([0-9.]+)\s+([0-9.]+)\s+\S+\s+\S+\s+\S+\s+\S+\s+(\S+)\s+\S+\s+(.*)$/.exec(line);
3894
+ if (match === null) return void 0;
3895
+ const user = match[1];
3896
+ const pid = match[2];
3897
+ const cpu = match[3];
3898
+ const mem = match[4];
3899
+ const command = match[6];
3900
+ return {
3901
+ pid: Number(pid),
3902
+ ppid: 0,
3903
+ user,
3904
+ cpuPercent: numberOr(cpu) ?? 0,
3905
+ memPercent: numberOr(mem) ?? 0,
3906
+ elapsedSeconds: null,
3907
+ command: trimCommand(command.trim())
3908
+ };
3909
+ }
3910
+ /**
3911
+ * Parse one probe. `exitCode === null` (channel died) or a missing end marker
3912
+ * means `unknown`, never an empty process table.
3913
+ */
3914
+ function parseProcesses(stdout, exitCode) {
3915
+ const lines = stdout.split("\n").map((line) => line.endsWith("\r") ? line.slice(0, -1) : line);
3916
+ const markerAt = lines.findIndex((line) => line.trim() === `@@RVS-PROCS gnu` || line.trim() === `@@RVS-PROCS bsd` || line.trim() === `@@RVS-PROCS none`);
3917
+ if (exitCode === null || markerAt < 0) return {
3918
+ tool: "unknown",
3919
+ processes: [],
3920
+ truncated: false,
3921
+ error: "the remote process probe ended without a complete answer"
3922
+ };
3923
+ const marker = lines[markerAt]?.trim() ?? "";
3924
+ let endAt = -1;
3925
+ for (let index = lines.length - 1; index > markerAt; index -= 1) if (lines[index].trim() === `@@RVS-PROCS end`) {
3926
+ endAt = index;
3927
+ break;
3928
+ }
3929
+ if (endAt < 0) return {
3930
+ tool: "unknown",
3931
+ processes: [],
3932
+ truncated: false,
3933
+ error: "the remote process probe was interrupted"
3934
+ };
3935
+ if (marker.endsWith("none")) return {
3936
+ tool: "none",
3937
+ processes: [],
3938
+ truncated: false
3939
+ };
3940
+ const gnu = marker.endsWith("gnu");
3941
+ const parsedProcesses = [];
3942
+ for (const line of lines.slice(markerAt + 1, endAt)) {
3943
+ if (line.trim() === "") continue;
3944
+ const row = gnu ? parseGnuRow(line) : parseBsdRow(line);
3945
+ if (row !== void 0 && !row.command.includes("@@RVS-PROCS")) parsedProcesses.push(row);
3946
+ }
3947
+ if (parsedProcesses.length === 0) return {
3948
+ tool: "unknown",
3949
+ processes: [],
3950
+ truncated: false,
3951
+ error: "the remote ps output could not be parsed"
3952
+ };
3953
+ const truncated = parsedProcesses.length > 500;
3954
+ return {
3955
+ tool: gnu ? "gnu" : "bsd",
3956
+ processes: parsedProcesses.slice(0, 500),
3957
+ truncated
3958
+ };
3959
+ }
3960
+ //#endregion
3812
3961
  //#region src/routes.ts
3813
3962
  function queryParam(url, name) {
3814
3963
  const value = url.searchParams.get(name);
@@ -4001,6 +4150,60 @@ function makeRoutes(deps) {
4001
4150
  const files = new RemoteFiles(pool);
4002
4151
  const terminalSessions = new TerminalSessionRegistry(pool);
4003
4152
  const monitor = new HostMonitor(pool);
4153
+ /**
4154
+ * Last process snapshot per alias. The kill route validates against this
4155
+ * table, so a browser cannot construct a `kill` for an arbitrary PID; a stale
4156
+ * entry is refreshed before validation rather than trusted indefinitely.
4157
+ */
4158
+ const processSnapshots = /* @__PURE__ */ new Map();
4159
+ /** One probe per alias at a time; a second reader joins the in-flight one. */
4160
+ const processInflight = /* @__PURE__ */ new Map();
4161
+ const forgetProcesses = (alias) => {
4162
+ processSnapshots.delete(alias);
4163
+ processInflight.delete(alias);
4164
+ };
4165
+ const readProcesses = async (alias, maxAgeMs) => {
4166
+ const cached = processSnapshots.get(alias);
4167
+ if (maxAgeMs > 0 && cached !== void 0 && Date.now() - cached.at < maxAgeMs) return cached.result;
4168
+ const joined = processInflight.get(alias);
4169
+ if (joined !== void 0) return joined;
4170
+ const task = (async () => {
4171
+ const result = await pool.exec(alias, processesCommand(), { timeoutMs: PROCESSES_TIMEOUT_MS });
4172
+ let parsed;
4173
+ if (result.error !== void 0) parsed = {
4174
+ tool: "unknown",
4175
+ processes: [],
4176
+ truncated: false,
4177
+ error: result.error
4178
+ };
4179
+ else if (result.timedOut) parsed = {
4180
+ tool: "unknown",
4181
+ processes: [],
4182
+ truncated: false,
4183
+ error: `the process probe did not finish within ${PROCESSES_TIMEOUT_MS / 1e3}s`
4184
+ };
4185
+ else if (result.exitCode === null) parsed = {
4186
+ tool: "unknown",
4187
+ processes: [],
4188
+ truncated: false,
4189
+ error: "the process probe ended without an exit status"
4190
+ };
4191
+ else parsed = parseProcesses(result.stdout, result.exitCode);
4192
+ if (parsed.tool === "gnu" || parsed.tool === "bsd") processSnapshots.set(alias, {
4193
+ at: Date.now(),
4194
+ result: parsed
4195
+ });
4196
+ else processSnapshots.delete(alias);
4197
+ return parsed;
4198
+ })();
4199
+ processInflight.set(alias, task);
4200
+ task.then(() => {
4201
+ if (processInflight.get(alias) === task) processInflight.delete(alias);
4202
+ }, () => {
4203
+ if (processInflight.get(alias) === task) processInflight.delete(alias);
4204
+ });
4205
+ return task;
4206
+ };
4004
4207
  const forwards = deps.forwards;
4005
4208
  const viewSettings = deps.viewSettings ?? new RemoteViewSettingsStore();
4006
4209
  /**
@@ -4193,6 +4396,7 @@ function makeRoutes(deps) {
4193
4396
  forwards?.stopAlias(alias);
4194
4397
  pool.forget(alias);
4195
4398
  monitor.forget(alias);
4399
+ forgetProcesses(alias);
4196
4400
  worlds.dropHost(alias).catch(() => void 0);
4197
4401
  if (!store.remove(alias)) {
4198
4402
  writeJson(res, 404, { error: `unknown host alias: ${alias}` });
@@ -4212,6 +4416,7 @@ function makeRoutes(deps) {
4212
4416
  try {
4213
4417
  pool.forget(alias);
4214
4418
  monitor.forget(alias);
4419
+ forgetProcesses(alias);
4215
4420
  worlds.dropHost(alias).catch(() => void 0);
4216
4421
  const entry = store.update(alias, body);
4217
4422
  writeJson(res, 200, { host: store.summarize(entry) });
@@ -4844,8 +5049,8 @@ function makeRoutes(deps) {
4844
5049
  const body = read.body;
4845
5050
  const sessionId = typeof body?.sessionId === "string" ? body.sessionId : "";
4846
5051
  const op = typeof body?.op === "string" ? body.op : "";
4847
- if (sessionId === "" || op !== "list" && op !== "diff") {
4848
- writeJson(res, 400, { error: "op (list|diff) and a non-empty sessionId are required" });
5052
+ if (sessionId === "" || op !== "list" && op !== "diff" && op !== "turnDiff") {
5053
+ writeJson(res, 400, { error: "op (list|diff|turnDiff) and a non-empty sessionId are required" });
4849
5054
  return;
4850
5055
  }
4851
5056
  const ledger = deps.changes;
@@ -4866,17 +5071,18 @@ function makeRoutes(deps) {
4866
5071
  });
4867
5072
  }
4868
5073
  if (body?.force === true) ledger.rescan(sessionId);
5074
+ else if (body?.trackedOnly === true) ledger.touch(sessionId, 0);
4869
5075
  else ledger.touch(sessionId);
4870
5076
  writeJson(res, 200, { summary: ledger.summary(sessionId) });
4871
5077
  return;
4872
5078
  }
4873
5079
  const path = typeof body?.path === "string" ? body.path : "";
4874
5080
  if (path === "") {
4875
- writeJson(res, 400, { error: "path is required for op=diff" });
5081
+ writeJson(res, 400, { error: `path is required for op=${op}` });
4876
5082
  return;
4877
5083
  }
4878
5084
  try {
4879
- writeJson(res, 200, { diff: await ledger.diff(sessionId, path) });
5085
+ writeJson(res, 200, { diff: op === "turnDiff" ? await ledger.turnDiff(sessionId, path) : await ledger.diff(sessionId, path) });
4880
5086
  } catch (error) {
4881
5087
  writeRouteError(res, error);
4882
5088
  }
@@ -5163,6 +5369,75 @@ function makeRoutes(deps) {
5163
5369
  }
5164
5370
  }
5165
5371
  },
5372
+ {
5373
+ kind: "exact",
5374
+ path: REMOTE_API.processes,
5375
+ handler: async (req, res) => {
5376
+ if (!isLoopbackRequest(req)) {
5377
+ writeJson(res, 403, { error: "forbidden: loopback-only" });
5378
+ return;
5379
+ }
5380
+ const method = req.method ?? "GET";
5381
+ if (method !== "GET" && method !== "POST") {
5382
+ writeJson(res, 405, { error: `method not allowed: ${method}` });
5383
+ return;
5384
+ }
5385
+ try {
5386
+ if (method === "GET") {
5387
+ const url = new URL(req.url ?? "/", "http://localhost");
5388
+ const alias = queryParam(url, "alias");
5389
+ if (alias === void 0 || alias === "") {
5390
+ writeJson(res, 400, { error: "alias query parameter is required" });
5391
+ return;
5392
+ }
5393
+ if (store.get(alias) === void 0) {
5394
+ writeJson(res, 404, { error: `unknown host alias: ${alias}` });
5395
+ return;
5396
+ }
5397
+ writeJson(res, 200, await readProcesses(alias, queryParam(url, "refresh") === "1" ? 0 : 3e3));
5398
+ return;
5399
+ }
5400
+ const read = await readBodyOrError(req, res, { objectOnly: true });
5401
+ if (!read.ok) return;
5402
+ const body = read.body ?? {};
5403
+ const alias = typeof body.alias === "string" ? body.alias : "";
5404
+ if (alias === "") {
5405
+ writeJson(res, 400, { error: "alias is required" });
5406
+ return;
5407
+ }
5408
+ let pid;
5409
+ try {
5410
+ pid = assertProcessPid(body.pid);
5411
+ } catch (error) {
5412
+ writeJson(res, 400, { error: error instanceof Error ? error.message : String(error) });
5413
+ return;
5414
+ }
5415
+ if (!isKillSignal(body.signal)) {
5416
+ writeJson(res, 400, { error: "signal must be TERM or KILL" });
5417
+ return;
5418
+ }
5419
+ if ((await readProcesses(alias, 0)).processes.find((process) => process.pid === pid) === void 0) {
5420
+ writeJson(res, 400, { error: `process ${pid} is not in the current remote snapshot` });
5421
+ return;
5422
+ }
5423
+ const result = await pool.exec(alias, killCommand(pid, body.signal), { timeoutMs: 1e4 });
5424
+ if (result.error !== void 0 || result.exitCode !== 0) {
5425
+ const message = result.error ?? result.stderr.trim() ?? "";
5426
+ writeJson(res, 502, { error: message === "" ? `kill failed [exit code: ${result.exitCode ?? "?"}]` : message });
5427
+ return;
5428
+ }
5429
+ processSnapshots.delete(alias);
5430
+ writeJson(res, 200, {
5431
+ ok: true,
5432
+ pid,
5433
+ signal: body.signal
5434
+ });
5435
+ } catch (error) {
5436
+ if (isStoreError(error)) writeStoreError(res, error);
5437
+ else writeJson(res, 502, { error: error instanceof Error ? error.message : String(error) });
5438
+ }
5439
+ }
5440
+ },
5166
5441
  {
5167
5442
  kind: "exact",
5168
5443
  path: REMOTE_API.metrics,
@@ -6235,6 +6510,17 @@ function filePatch(displayPath, hunks) {
6235
6510
  function panelStatus(status) {
6236
6511
  return status === "?" ? "A" : status;
6237
6512
  }
6513
+ /** Text of one read result, with "nothing usable transferred" folded into null. */
6514
+ function turnSideOf(read) {
6515
+ const binary = read.binary === true;
6516
+ const truncated = read.truncated === true;
6517
+ return {
6518
+ text: read.absent || binary || truncated ? null : read.text,
6519
+ binary,
6520
+ truncated,
6521
+ known: !binary && !truncated
6522
+ };
6523
+ }
6238
6524
  /** Grace added to an exec budget before the watchdog gives up on it. */
6239
6525
  const WATCHDOG_GRACE_MS = 5e3;
6240
6526
  /** Sentinel for "the host call never came back". */
@@ -6253,6 +6539,66 @@ const DIFF_LIMITS = {
6253
6539
  perFile: DIFF_MAX_FILE_BYTES,
6254
6540
  total: DIFF_MAX_FILE_BYTES
6255
6541
  };
6542
+ /**
6543
+ * Budget for ONE completed turn's **per-file hunks and reverse patches**.
6544
+ *
6545
+ * What it counts (and what it deliberately does NOT): the sum of every served
6546
+ * file patch plus the hunk line bodies. The two FULL texts per record (`before`
6547
+ * and `after`) and the `turnAfter` snapshot are not counted — they are what the
6548
+ * staleness proof compares against, and they are already bounded by the scan
6549
+ * caps (≲256 KiB/file, 8 MiB/turn for `after` plus the same order for `before`
6550
+ * and the snapshot). So the real resident cost is this budget PLUS those texts
6551
+ * (worst case ≈ 16 MiB + 4 MiB per active session), which is why the copy says
6552
+ * "patches and hunk text" rather than "the turn's contents".
6553
+ *
6554
+ * The turn view must keep a comparison per changed file until the next turn
6555
+ * closes (that is what `turnDiff` serves without re-reading the remote). 4 MiB
6556
+ * fits a large refactor's patches; crossing it disables per-turn hunks for the
6557
+ * session (see {@link Ledger.turnDisabled}) rather than thrashing the budget.
6558
+ */
6559
+ const MAX_TURN_PATCH_BYTES = 4 * 1024 * 1024;
6560
+ /**
6561
+ * Bounds of the self-heal window (see {@link selfHealMaxAge}).
6562
+ *
6563
+ * The floor is a measured small repository: `git status -uno` answers in ~0.1s
6564
+ * there, so 5s of staleness is already a large win over the old flat 30s — and
6565
+ * the probe has been observed to take 30–60s to surface a manual edit when only
6566
+ * the turn boundary and the 3/15/30s client polls apply.
6567
+ *
6568
+ * The ceiling is the OLD fixed value on purpose: it is what keeps the panel from
6569
+ * turning into a status loop on a huge checkout (the reference monorepo answers
6570
+ * in ~1.7s, i.e. a 6.8s window — still 4x its own cost, never lower for bigger
6571
+ * trees).
6572
+ */
6573
+ const SELF_HEAL_MIN_MS = 5e3;
6574
+ const SELF_HEAL_MAX_MS = 3e4;
6575
+ /**
6576
+ * How many scan durations the panel may wait before re-scanning.
6577
+ *
6578
+ * Self-heal is a POLL backstop, not a live watch: waiting the cost of about four
6579
+ * `git status -uno` runs keeps the added load proportional to what the probe can
6580
+ * afford, instead of one scan per client poll.
6581
+ */
6582
+ const SELF_HEAL_FACTOR = 4;
6583
+ /**
6584
+ * How stale the ledger may get before a *poll* re-scans it.
6585
+ *
6586
+ * Self-tuning: the host has no idea whether this session sits in a 50-file
6587
+ * repository or a monorepo, and the same 30s window is either 300x the scan cost
6588
+ * (small tree: the user waits half a minute to see a manual edit) or about right
6589
+ * (AOSP: still 17x). Four times the LAST tracked scan, clamped to
6590
+ * [{@link SELF_HEAL_MIN_MS}, {@link SELF_HEAL_MAX_MS}].
6591
+ *
6592
+ * An unknown / failed measurement falls back to the old ceiling, so a Host that
6593
+ * has not scanned anything yet behaves exactly as before.
6594
+ *
6595
+ * @param scanMs - Duration of the last successful tracked scan, in ms.
6596
+ */
6597
+ function selfHealMaxAge(scanMs) {
6598
+ if (scanMs === void 0 || !Number.isFinite(scanMs) || scanMs < 0) return SELF_HEAL_MAX_MS;
6599
+ const scaled = Math.round(scanMs * SELF_HEAL_FACTOR);
6600
+ return Math.min(SELF_HEAL_MAX_MS, Math.max(SELF_HEAL_MIN_MS, scaled));
6601
+ }
6256
6602
  /** POSIX join — `node:path` would apply Windows semantics on the host. */
6257
6603
  function posixJoin(base, rel) {
6258
6604
  if (rel.startsWith("/")) return rel;
@@ -6260,6 +6606,11 @@ function posixJoin(base, rel) {
6260
6606
  const right = rel.startsWith("./") ? rel.slice(2) : rel;
6261
6607
  return right === "" ? left : `${left}/${right}`;
6262
6608
  }
6609
+ /** The inverse of {@link posixJoin} for a path under `root`; '' when it is not. */
6610
+ function displayUnder(root, path) {
6611
+ const base = root.endsWith("/") ? root : `${root}/`;
6612
+ return path.startsWith(base) ? path.slice(base.length) : "";
6613
+ }
6263
6614
  /**
6264
6615
  * Whether two reads prove the file did not move between them.
6265
6616
  *
@@ -6294,7 +6645,9 @@ var SessionChanges = class {
6294
6645
  if (this.disposed) return;
6295
6646
  const ledger = this.ensure(target);
6296
6647
  if (ledger === void 0) return;
6648
+ const advanced = turn > ledger.turn;
6297
6649
  ledger.turn = Math.max(ledger.turn, turn);
6650
+ if (advanced) ledger.pendingClose = turn;
6298
6651
  this.schedule(ledger);
6299
6652
  }
6300
6653
  /** The current summary for one session, or null when it has no ledger. */
@@ -6314,7 +6667,18 @@ var SessionChanges = class {
6314
6667
  ...excludedDirs.length === 0 ? {} : { excludedDirs },
6315
6668
  pending: ledger.untrackedJob !== void 0 || ledger.pending && ledger.files.length > 0,
6316
6669
  ...ledger.truncated === true ? { truncated: true } : {},
6317
- ...unavailable === void 0 ? {} : { unavailable }
6670
+ ...unavailable === void 0 ? {} : { unavailable },
6671
+ ...ledger.turnDelta === void 0 ? {} : { turnView: {
6672
+ turn: ledger.turnDelta.turn,
6673
+ files: ledger.turnDelta.files,
6674
+ added: ledger.turnDelta.added,
6675
+ deleted: ledger.turnDelta.deleted,
6676
+ at: ledger.turnDelta.at,
6677
+ cached: ledger.turnDelta.cached,
6678
+ ...ledger.turnDelta.reason === void 0 ? {} : { reason: ledger.turnDelta.reason },
6679
+ ...ledger.turnDelta.truncated === true ? { truncated: true } : {},
6680
+ ...ledger.turnDelta.provisional ? { pending: true } : {}
6681
+ } }
6318
6682
  };
6319
6683
  }
6320
6684
  /**
@@ -6388,21 +6752,158 @@ var SessionChanges = class {
6388
6752
  lines: hunk.lines,
6389
6753
  patch: reverse === "" ? "" : hunkPatch(record.display, hunk)
6390
6754
  }));
6391
- if (hunks.length === 0) return {
6392
- kind: "missing",
6755
+ if (hunks.length === 0) {
6756
+ /**
6757
+ * Both sides were READ and compared, so "no hunks" means the file is back
6758
+ * at its session baseline (the change was reverted, or an identical byte
6759
+ * round-trip). That is NOT "missing": the panel shows `missing` as "the
6760
+ * remote cannot read this file", and saying that about a file the host
6761
+ * just read is a lie that also hides "your change is gone". A withheld
6762
+ * side (null) keeps `missing` — there is genuinely nothing to compare.
6763
+ */
6764
+ /**
6765
+ * 判定只看**改后那一侧读到了**:新建的空文件 before 是 null(不存在),after
6766
+ * 读到 `''`,零 hunk 是"读到了、只是没有内容",不是"读不到"。老条件要求两侧
6767
+ * 都非 null,于是会话新建的空文件被报成 `missing`,面板显示「远端读不到」
6768
+ * (审核 NIT-1)。
6769
+ */
6770
+ if (afterText !== null) return {
6771
+ kind: "text",
6772
+ path,
6773
+ display: record.display,
6774
+ hunks: [],
6775
+ ...status === void 0 ? {} : { status }
6776
+ };
6777
+ return {
6778
+ kind: "missing",
6779
+ path,
6780
+ display: record.display,
6781
+ hunks: [],
6782
+ ...status === void 0 ? {} : { status }
6783
+ };
6784
+ }
6785
+ return {
6786
+ kind: "text",
6787
+ path,
6788
+ display: record.display,
6789
+ hunks,
6790
+ ...reverse === "" ? {} : { patch: reverse },
6791
+ ...status === void 0 ? {} : { status },
6792
+ ...truncated ? { truncated: true } : {}
6793
+ };
6794
+ }
6795
+ /**
6796
+ * One file's comparison for the most recent COMPLETED turn.
6797
+ *
6798
+ * Same shape as {@link diff} (the editor paints both the same way), but the
6799
+ * "before" side is the previous turn's close instead of the session baseline.
6800
+ * The hunks are served from the turn delta's cache, so this call costs NO
6801
+ * remote work in the common case — but a cached comparison is only worth
6802
+ * showing while it still describes the disk. That is why the `after` side is
6803
+ * read back here and compared with the cached text FIRST: if the file moved on
6804
+ * after the turn closed (a later save, a terminal command, an agent), the
6805
+ * answer is `stale` and the client falls back to the session view instead of
6806
+ * painting line numbers that no longer exist.
6807
+ *
6808
+ * @param sessionId - live session owning the ledger.
6809
+ * @param path - the file's remote absolute path (as listed in `turnView.files`).
6810
+ * @returns hunks for decorations, `unavailable`/`stale` with a reason, or null
6811
+ * when the session itself is unknown.
6812
+ */
6813
+ async turnDiff(sessionId, path) {
6814
+ const ledger = this.ledgers.get(sessionId);
6815
+ if (ledger === void 0) return null;
6816
+ const delta = ledger.turnDelta;
6817
+ const display = delta?.records.get(path)?.display ?? displayUnder(ledger.root, path);
6818
+ if (delta === void 0) return {
6819
+ kind: "unavailable",
6820
+ path,
6821
+ display,
6822
+ hunks: [],
6823
+ reason: "no turn has closed since this session started"
6824
+ };
6825
+ if (!delta.cached) return {
6826
+ kind: "unavailable",
6827
+ path,
6828
+ display,
6829
+ hunks: [],
6830
+ reason: delta.reason ?? "per-turn change contents are not cached for this session"
6831
+ };
6832
+ const record = delta.records.get(path);
6833
+ if (record === void 0) return {
6834
+ kind: "unavailable",
6835
+ path,
6836
+ display,
6837
+ hunks: [],
6838
+ reason: `this file is not part of turn ${delta.turn}'s change set`
6839
+ };
6840
+ const status = record.status;
6841
+ if (record.binary) return {
6842
+ kind: "binary",
6843
+ path,
6844
+ display: record.display,
6845
+ hunks: [],
6846
+ ...status === void 0 ? {} : { status }
6847
+ };
6848
+ if (record.oversized) return {
6849
+ kind: "unavailable",
6850
+ path,
6851
+ display: record.display,
6852
+ hunks: [],
6853
+ reason: "the bytes of this file were withheld by the size cap, so there is no line-level comparison",
6854
+ ...status === void 0 ? {} : { status }
6855
+ };
6856
+ /**
6857
+ * Verify the cache against the disk before serving it.
6858
+ *
6859
+ * A failed read is NOT "unchanged": without evidence the honest answer is
6860
+ * `unavailable` (no palatable guess). A binary or cap-truncated read proves
6861
+ * the bytes moved on after the turn closed, which is exactly `stale`.
6862
+ */
6863
+ const fresh = await this.readPaths(ledger, [record.display], "worktree", DIFF_LIMITS);
6864
+ if (ledger.disposed) return null;
6865
+ const side = fresh.get(record.display);
6866
+ if (side === void 0) return {
6867
+ kind: "unavailable",
6868
+ path,
6869
+ display: record.display,
6870
+ hunks: [],
6871
+ reason: "the file could not be read back from the host, so the turn comparison cannot be verified",
6872
+ ...status === void 0 ? {} : { status }
6873
+ };
6874
+ const current = turnSideOf(side);
6875
+ if (current.binary || current.truncated) return {
6876
+ kind: "stale",
6877
+ path,
6878
+ display: record.display,
6879
+ hunks: [],
6880
+ reason: current.binary ? "the file has become binary since the turn closed" : "the file has grown past the read budget since the turn closed",
6881
+ ...status === void 0 ? {} : { status }
6882
+ };
6883
+ if (current.text !== record.after) return {
6884
+ kind: "stale",
6393
6885
  path,
6394
6886
  display: record.display,
6395
6887
  hunks: [],
6888
+ reason: "the file was modified after the turn closed",
6396
6889
  ...status === void 0 ? {} : { status }
6397
6890
  };
6891
+ const hunks = record.hunks.map((hunk) => ({
6892
+ oldStart: hunk.oldStart,
6893
+ oldCount: hunk.oldLines,
6894
+ newStart: hunk.newStart,
6895
+ newCount: hunk.newLines,
6896
+ heading: "",
6897
+ lines: hunk.lines,
6898
+ patch: record.filePatch === "" ? "" : hunkPatch(record.display, hunk)
6899
+ }));
6398
6900
  return {
6399
6901
  kind: "text",
6400
6902
  path,
6401
6903
  display: record.display,
6402
6904
  hunks,
6403
- ...reverse === "" ? {} : { patch: reverse },
6404
- ...status === void 0 ? {} : { status },
6405
- ...truncated ? { truncated: true } : {}
6905
+ ...record.filePatch === "" ? {} : { patch: record.filePatch },
6906
+ ...status === void 0 ? {} : { status }
6406
6907
  };
6407
6908
  }
6408
6909
  /** Resolve once every queued refresh has settled, including coalesced work. */
@@ -6448,16 +6949,25 @@ var SessionChanges = class {
6448
6949
  * Self-heal a ledger whose data has gone stale.
6449
6950
  *
6450
6951
  * The panel polls `list`, and a poll is the one moment we know a human is
6451
- * looking at the answer. If the data is older than `maxAgeMs`, re-scan — so a
6952
+ * looking at the answer. If the data is older than the window, re-scan — so a
6452
6953
  * turn boundary this Host never delivered costs a few seconds of staleness
6453
6954
  * instead of a manual refresh.
6454
6955
  *
6956
+ * The window is ADAPTIVE ({@link selfHealMaxAge}): four times the last tracked
6957
+ * scan, clamped to 5–30s. A small repository therefore surfaces a manual edit
6958
+ * (one with no turn event behind it) within seconds instead of the old fixed
6959
+ * half minute, while a monorepo keeps the old ceiling. The two `false` paths —
6960
+ * a scan already running, and data that is still fresh — are unchanged.
6961
+ *
6962
+ * @param maxAgeMs - explicit window; callers that know better (and the checks)
6963
+ * override the adaptive default and keep the old semantics exactly.
6455
6964
  * @returns whether a refresh was queued.
6456
6965
  */
6457
- touch(sessionId, maxAgeMs = 3e4) {
6966
+ touch(sessionId, maxAgeMs) {
6458
6967
  const ledger = this.ledgers.get(sessionId);
6459
6968
  if (ledger === void 0 || ledger.disposed || ledger.pending) return false;
6460
- if (ledger.at > 0 && Date.now() - ledger.at < maxAgeMs) return false;
6969
+ const windowMs = maxAgeMs ?? selfHealMaxAge(ledger.scanMs);
6970
+ if (ledger.at > 0 && Date.now() - ledger.at < windowMs) return false;
6461
6971
  this.schedule(ledger);
6462
6972
  return true;
6463
6973
  }
@@ -6508,6 +7018,7 @@ var SessionChanges = class {
6508
7018
  ledger.untracked = void 0;
6509
7019
  ledger.untrackedAt = 0;
6510
7020
  ledger.untrackedMs = void 0;
7021
+ ledger.scanMs = void 0;
6511
7022
  ledger.untrackedGivenUp = false;
6512
7023
  ledger.untrackedFailure = void 0;
6513
7024
  ledger.files = [];
@@ -6518,6 +7029,13 @@ var SessionChanges = class {
6518
7029
  ledger.at = 0;
6519
7030
  ledger.unavailable = void 0;
6520
7031
  ledger.startedAt = Date.now();
7032
+ ledger.pendingClose = void 0;
7033
+ ledger.turnAfter = void 0;
7034
+ ledger.turnAfterTruncated = false;
7035
+ ledger.turnDelta = void 0;
7036
+ ledger.turnBefore = void 0;
7037
+ ledger.turnBeforeTruncated = false;
7038
+ ledger.turnProvisional = false;
6521
7039
  }
6522
7040
  /**
6523
7041
  * Resolve (or rebind) the ledger for one session from its CURRENT cwd.
@@ -6581,6 +7099,7 @@ var SessionChanges = class {
6581
7099
  untracked: void 0,
6582
7100
  untrackedAt: 0,
6583
7101
  untrackedMs: void 0,
7102
+ scanMs: void 0,
6584
7103
  untrackedJob: void 0,
6585
7104
  turn: 0,
6586
7105
  files: [],
@@ -6593,6 +7112,14 @@ var SessionChanges = class {
6593
7112
  pending: false,
6594
7113
  queue: Promise.resolve(),
6595
7114
  dirty: false,
7115
+ pendingClose: void 0,
7116
+ turnAfter: void 0,
7117
+ turnAfterTruncated: false,
7118
+ turnDelta: void 0,
7119
+ turnBefore: void 0,
7120
+ turnBeforeTruncated: false,
7121
+ turnProvisional: false,
7122
+ turnDisabled: void 0,
6596
7123
  publishSeq: 0,
6597
7124
  disposed: false
6598
7125
  };
@@ -6626,15 +7153,24 @@ var SessionChanges = class {
6626
7153
  */
6627
7154
  async refresh(ledger) {
6628
7155
  if (ledger.disposed || ledger.root === "") return;
7156
+ const scanStartedAt = Date.now();
6629
7157
  const scanned = await this.scanTracked(ledger);
6630
7158
  if (ledger.disposed || scanned === void 0) return;
6631
7159
  if (ledger.root !== scanned.root) return;
7160
+ ledger.scanMs = Math.max(0, Date.now() - scanStartedAt);
6632
7161
  ledger.tracked = scanned.entries;
6633
7162
  await this.publish(ledger);
6634
7163
  this.kickUntracked(ledger);
6635
7164
  }
6636
- /** Recompute the panel's list from the scans currently known. */
6637
- async publish(ledger) {
7165
+ /**
7166
+ * Recompute the panel's list from the scans currently known.
7167
+ *
7168
+ * @param fromSlowScan - this publish was triggered by the `git ls-files
7169
+ * --others` walk. A turn delta closed before that walk landed is still
7170
+ * provisional: this flag is what lets it be re-derived once the turn's new
7171
+ * files are known (see `correctTurn`).
7172
+ */
7173
+ async publish(ledger, fromSlowScan = false) {
6638
7174
  if (ledger.disposed) return;
6639
7175
  const seq = ++ledger.publishSeq;
6640
7176
  const root = ledger.root;
@@ -6721,6 +7257,274 @@ var SessionChanges = class {
6721
7257
  ledger.truncated = truncated ? true : void 0;
6722
7258
  ledger.unavailable = listed.length > 0 && after.size === 0 ? "file contents could not be read from the host" : void 0;
6723
7259
  ledger.at = Date.now();
7260
+ if (ledger.pendingClose !== void 0) await this.closeTurn(ledger, root, seq, entries, listed, after, records, truncated);
7261
+ else if (fromSlowScan) await this.correctTurn(ledger, root, seq, entries, listed, after, records, truncated);
7262
+ }
7263
+ /**
7264
+ * Close one turn: compute "what did it change" and remember this close as the
7265
+ * next turn's starting point.
7266
+ *
7267
+ * The delta is defined against the PREVIOUS close, not the session baseline, so
7268
+ * a file the session changed in turn 1 and left alone in turn 2 must not appear
7269
+ * in turn 2's list — otherwise the view says the same work happened twice.
7270
+ * That is what `turnAfter` is for: it holds every listed path's text at the
7271
+ * moment the previous turn closed, and it is replaced (never merged) here.
7272
+ *
7273
+ * A failed `after` read leaves the boundary unconsumed, so the next publish
7274
+ * retries instead of recording a turn against "nothing".
7275
+ */
7276
+ async closeTurn(ledger, root, seq, entries, listed, after, records, truncated) {
7277
+ const turn = ledger.pendingClose;
7278
+ if (turn === void 0 || ledger.disposed) return;
7279
+ ledger.pendingClose = void 0;
7280
+ if (ledger.turnDisabled !== void 0) return;
7281
+ const known = ledger.turnAfter;
7282
+ const collected = await this.collectTurnSides(ledger, root, seq, listed, after, known);
7283
+ if (collected.kind === "retry") {
7284
+ ledger.pendingClose = turn;
7285
+ return;
7286
+ }
7287
+ if (collected.kind === "superseded") return;
7288
+ /**
7289
+ * A previous snapshot cut by the file cap cannot prove that a path MISSING
7290
+ * from it was clean — it may simply have been past the cap. Entries that were
7291
+ * listed then are still exact, so only the "newcomer = changed this turn"
7292
+ * inference is dropped, and the view says it is partial (`truncated`).
7293
+ */
7294
+ const partial = ledger.turnAfterTruncated;
7295
+ const previousUncorrected = ledger.turnProvisional;
7296
+ const built = this.buildTurnDelta(root, turn, collected.now, entries, records, known, partial, truncated);
7297
+ this.storeTurnDelta(ledger, built, previousUncorrected);
7298
+ if (built.overflow) return;
7299
+ ledger.turnBefore = known;
7300
+ ledger.turnBeforeTruncated = partial;
7301
+ ledger.turnProvisional = true;
7302
+ /**
7303
+ * This close becomes the next turn's starting point. Built from `listed`
7304
+ * ONLY: a path that left the dirty list is at its baseline, and the session
7305
+ * baseline is exactly what a re-appearance will be compared against — keeping
7306
+ * it here would cost a full re-read of every reverted file on every later
7307
+ * turn.
7308
+ */
7309
+ ledger.turnAfter = this.turnSnapshotOf(listed, collected.now);
7310
+ ledger.turnAfterTruncated = truncated;
7311
+ }
7312
+ /**
7313
+ * Re-derive the CURRENT turn's delta once the slow scan behind it has landed.
7314
+ *
7315
+ * A turn's new files are discovered by `git ls-files --others`, which runs
7316
+ * after the tracked scan by design and can land seconds later. Rebuilding the
7317
+ * same turn from the SAME "before" snapshot (kept in `turnBefore`) is what
7318
+ * makes those files appear in the turn they belong to instead of in the next
7319
+ * one. Guarded against the two ways this could lie: a newer turn boundary
7320
+ * (which supersedes this delta) and a root move.
7321
+ */
7322
+ async correctTurn(ledger, root, seq, entries, listed, after, records, truncated) {
7323
+ const delta = ledger.turnDelta;
7324
+ const before = ledger.turnBefore;
7325
+ if (!ledger.turnProvisional || delta === void 0) return;
7326
+ ledger.turnProvisional = false;
7327
+ if (ledger.turnDisabled !== void 0 || ledger.turn !== delta.turn) return;
7328
+ const collected = await this.collectTurnSides(ledger, root, seq, listed, after, before);
7329
+ if (collected.kind !== "ok") return;
7330
+ const partial = ledger.turnBeforeTruncated;
7331
+ const built = this.buildTurnDelta(root, delta.turn, collected.now, entries, records, before, partial, truncated);
7332
+ this.storeTurnDelta(ledger, built, false);
7333
+ if (built.overflow) return;
7334
+ const stored = ledger.turnDelta;
7335
+ if (stored !== void 0) stored.provisional = false;
7336
+ ledger.turnAfter = this.turnSnapshotOf(listed, collected.now);
7337
+ }
7338
+ /** Remember one close's sides for the next boundary (see `TurnSideText`). */
7339
+ turnSnapshotOf(listed, now) {
7340
+ const snapshot = /* @__PURE__ */ new Map();
7341
+ for (const entry of listed) {
7342
+ const side = now.get(entry.path);
7343
+ snapshot.set(entry.path, {
7344
+ text: side?.text ?? null,
7345
+ known: side?.known ?? false
7346
+ });
7347
+ }
7348
+ return snapshot;
7349
+ }
7350
+ /**
7351
+ * The "after" side of one turn close, in `display` space.
7352
+ *
7353
+ * Starts from the publish's own reads (every listed path), then reads the paths
7354
+ * the PREVIOUS close listed but this publish does not: those left the dirty
7355
+ * list (reverted to their baseline, deleted, restored), and without reading
7356
+ * them now the revert would be attributed to nobody — "the turn put the file
7357
+ * back" would look like "the turn changed nothing".
7358
+ *
7359
+ * @returns `ok` with the sides; `retry` when a read failed (the caller keeps
7360
+ * the turn boundary for the next publish); `superseded` when a root move or
7361
+ * a newer publish already owns the observation.
7362
+ */
7363
+ async collectTurnSides(ledger, root, seq, listed, after, known) {
7364
+ if (listed.length > 0 && after.size === 0) return { kind: "retry" };
7365
+ const now = /* @__PURE__ */ new Map();
7366
+ for (const entry of listed) {
7367
+ const side = after.get(entry.path);
7368
+ if (side === void 0) return { kind: "retry" };
7369
+ now.set(entry.path, turnSideOf(side));
7370
+ }
7371
+ const vanished = known === void 0 ? [] : [...known.keys()].filter((display) => !now.has(display));
7372
+ if (vanished.length === 0) return {
7373
+ kind: "ok",
7374
+ now
7375
+ };
7376
+ const reads = await this.readPaths(ledger, vanished, "worktree");
7377
+ if (ledger.disposed) return { kind: "superseded" };
7378
+ if (ledger.root !== root || ledger.publishSeq !== seq) return { kind: "superseded" };
7379
+ if (reads.size === 0) return { kind: "retry" };
7380
+ for (const display of vanished) {
7381
+ const side = reads.get(display);
7382
+ if (side === void 0) return { kind: "retry" };
7383
+ now.set(display, turnSideOf(side));
7384
+ }
7385
+ return {
7386
+ kind: "ok",
7387
+ now
7388
+ };
7389
+ }
7390
+ /**
7391
+ * Compare one turn's before/after sides into panel rows plus cached hunks.
7392
+ *
7393
+ * The comparison rules are the ones the whole-session `publish` uses (binary
7394
+ * and cap-withheld bytes carry 0/0 counts, a creation has no reverse patch,
7395
+ * hunks come from the same Myers implementation), so a row means the same
7396
+ * thing in both views.
7397
+ */
7398
+ buildTurnDelta(root, turn, now, entries, records, known, partial, capTruncated) {
7399
+ const statusOf = /* @__PURE__ */ new Map();
7400
+ for (const entry of entries) statusOf.set(entry.path, panelStatus(entry.status));
7401
+ const budget = this.deps.turnPatchBytes ?? MAX_TURN_PATCH_BYTES;
7402
+ const files = [];
7403
+ const turnRecords = /* @__PURE__ */ new Map();
7404
+ let added = 0;
7405
+ let deleted = 0;
7406
+ let bytes = 0;
7407
+ let incomplete = partial || capTruncated;
7408
+ for (const [display, side] of now) {
7409
+ const absolute = posixJoin(root, display);
7410
+ const record = records.get(absolute);
7411
+ const had = known !== void 0 && known.has(display);
7412
+ if (!had && (record === void 0 || partial)) continue;
7413
+ const previous = had ? known.get(display) : void 0;
7414
+ if (had && previous !== void 0 && previous.known === false) {
7415
+ incomplete = true;
7416
+ continue;
7417
+ }
7418
+ const before = had ? previous?.text ?? null : record?.before ?? null;
7419
+ if (had && before === side.text) continue;
7420
+ const binary = side.binary || record?.binary === true;
7421
+ const oversized = !binary && (side.truncated || record?.truncated === true);
7422
+ let fileAdded = 0;
7423
+ let fileDeleted = 0;
7424
+ let hunks = [];
7425
+ let patch = "";
7426
+ if (!binary && !oversized) {
7427
+ const result = diffText(before ?? "", side.text ?? "");
7428
+ fileAdded = result.added;
7429
+ fileDeleted = result.deleted;
7430
+ hunks = result.hunks;
7431
+ patch = before !== null && hunks.length > 0 ? filePatch(display, hunks) : "";
7432
+ if (patch !== "") bytes += Buffer.byteLength(patch, "utf8");
7433
+ for (const hunk of hunks) for (const line of hunk.lines) bytes += Buffer.byteLength(line, "utf8") + 1;
7434
+ }
7435
+ added += fileAdded;
7436
+ deleted += fileDeleted;
7437
+ const status = statusOf.get(display);
7438
+ const revert = patch === "" ? void 0 : "patch";
7439
+ files.push({
7440
+ path: absolute,
7441
+ display,
7442
+ added: fileAdded,
7443
+ deleted: fileDeleted,
7444
+ ...binary ? { binary: true } : {},
7445
+ ...oversized ? { oversized: true } : {},
7446
+ ...status === void 0 ? {} : { status },
7447
+ ...revert === void 0 ? {} : { revert }
7448
+ });
7449
+ turnRecords.set(absolute, {
7450
+ display,
7451
+ path: absolute,
7452
+ status,
7453
+ binary,
7454
+ oversized,
7455
+ hunks,
7456
+ before,
7457
+ after: side.text,
7458
+ filePatch: patch
7459
+ });
7460
+ }
7461
+ files.sort((left, right) => left.display.localeCompare(right.display));
7462
+ return {
7463
+ turn,
7464
+ files,
7465
+ added,
7466
+ deleted,
7467
+ records: turnRecords,
7468
+ bytes,
7469
+ overflow: bytes > budget,
7470
+ incomplete
7471
+ };
7472
+ }
7473
+ /**
7474
+ * Commit one built delta, degrading honestly when it blew the memory budget.
7475
+ *
7476
+ * Over budget the statistics are already computed and stay usable, but the
7477
+ * per-file hunks and patches are dropped and this session stops computing turn
7478
+ * views: keeping a half-filled snapshot would make the NEXT turn compare
7479
+ * against texts that belong to an older boundary.
7480
+ */
7481
+ storeTurnDelta(ledger, built, uncorrectedPrevious) {
7482
+ const truncated = built.incomplete || uncorrectedPrevious;
7483
+ if (!built.overflow) {
7484
+ ledger.turnDelta = {
7485
+ turn: built.turn,
7486
+ files: built.files,
7487
+ added: built.added,
7488
+ deleted: built.deleted,
7489
+ at: Date.now(),
7490
+ cached: true,
7491
+ reason: void 0,
7492
+ truncated: truncated ? true : void 0,
7493
+ provisional: true,
7494
+ records: built.records,
7495
+ bytes: built.bytes
7496
+ };
7497
+ return;
7498
+ }
7499
+ const reason = `the per-turn patches and hunk text exceed the ${this.deps.turnPatchBytes ?? MAX_TURN_PATCH_BYTES} byte memory budget; turn totals stay available without per-file hunks`;
7500
+ ledger.turnDelta = {
7501
+ turn: built.turn,
7502
+ files: built.files.map((file) => {
7503
+ const { revert: _revert, ...rest } = file;
7504
+ return rest;
7505
+ }),
7506
+ added: built.added,
7507
+ deleted: built.deleted,
7508
+ at: Date.now(),
7509
+ cached: false,
7510
+ reason,
7511
+ truncated: truncated ? true : void 0,
7512
+ provisional: false,
7513
+ records: /* @__PURE__ */ new Map(),
7514
+ bytes: built.bytes
7515
+ };
7516
+ this.disableTurn(ledger, reason);
7517
+ }
7518
+ /** Stop computing turn views for this session, saying why (sticky). */
7519
+ disableTurn(ledger, reason) {
7520
+ if (ledger.turnDisabled !== void 0) return;
7521
+ ledger.turnDisabled = reason;
7522
+ ledger.turnAfter = void 0;
7523
+ ledger.turnAfterTruncated = false;
7524
+ ledger.turnBefore = void 0;
7525
+ ledger.turnBeforeTruncated = false;
7526
+ ledger.turnProvisional = false;
7527
+ this.warn(`per-turn view disabled: ${reason}`);
6724
7528
  }
6725
7529
  /**
6726
7530
  * The cheap scan: tracked files whose working-tree bytes differ from the
@@ -6840,7 +7644,7 @@ var SessionChanges = class {
6840
7644
  ledger.untrackedFailure = void 0;
6841
7645
  ledger.untracked = parseUntrackedZ(scan.stdout);
6842
7646
  await this.absorbPreExisting(ledger);
6843
- await this.publish(ledger);
7647
+ await this.publish(ledger, true);
6844
7648
  })().catch((error) => this.warn(`untracked scan failed: ${messageOf(error)}`)).finally(() => {
6845
7649
  ledger.untrackedJob = void 0;
6846
7650
  });