@kabmo-labs/kabmo 0.38.0 → 0.38.1

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 (112) hide show
  1. package/dist/client/index.html +1 -1
  2. package/dist/client/index.js +420 -419
  3. package/dist/client/static/js/{CsvGrid-90zfbn7f.js → CsvGrid-t1n057vw.js} +1 -1
  4. package/dist/client/static/js/{DocxView-vwq2rf16.js → DocxView-c9g6teks.js} +1 -1
  5. package/dist/client/static/js/{DrawioView-bvx7eqcz.js → DrawioView-gd14j54m.js} +1 -1
  6. package/dist/client/static/js/{ImageView-q6xfmbrq.js → ImageView-57f1ecdp.js} +1 -1
  7. package/dist/client/static/js/{LayoutWrapper-qatdaw3n.js → LayoutWrapper-x7srbpz1.js} +1 -1
  8. package/dist/client/static/js/{Modal-6jx1fvfb.js → Modal-0bn3f77b.js} +1 -1
  9. package/dist/client/static/js/{PdfView-tkv2d2zs.js → PdfView-cybz0xbj.js} +1 -1
  10. package/dist/client/static/js/{SessionsView-rbnecykz.js → SessionsView-gx5q68tp.js} +1 -1
  11. package/dist/client/static/js/{SheetView-t08g8kdr.js → SheetView-1kk5y326.js} +1 -1
  12. package/dist/client/static/js/{SvgPreview-9vh6mdcp.js → SvgPreview-mp4tk37p.js} +1 -1
  13. package/dist/client/static/js/{abnfDiagram-O67JEVCF-bxcn33e1.js → abnfDiagram-O67JEVCF-78qb3can.js} +1 -1
  14. package/dist/client/static/js/{architectureDiagram-NJMV4G6O-40ggw6e8.js → architectureDiagram-NJMV4G6O-n0fr4hb6.js} +1 -1
  15. package/dist/client/static/js/{blockDiagram-BEXU5L5S-k41cvjrd.js → blockDiagram-BEXU5L5S-2xemfrzh.js} +1 -1
  16. package/dist/client/static/js/{c4Diagram-YGBWAQC7-rdcmn6ac.js → c4Diagram-YGBWAQC7-zxfdx3eb.js} +1 -1
  17. package/dist/client/static/js/{classDiagram-v2-NBCMYWYE-txbmbkxv.js → classDiagram-v2-NBCMYWYE-z9sasy3k.js} +1 -1
  18. package/dist/client/static/js/{cose-bilkent-JH36ORCC-bxzh3qj1.js → cose-bilkent-JH36ORCC-9byp0czh.js} +1 -1
  19. package/dist/client/static/js/{cynefinDiagram-VND7K2PF-abx5343b.js → cynefinDiagram-VND7K2PF-gnm129fx.js} +1 -1
  20. package/dist/client/static/js/{dagre-6A5THRUB-baj278kt.js → dagre-6A5THRUB-sc5tfv1w.js} +1 -1
  21. package/dist/client/static/js/{diagram-22UHCM2B-vqvhdc5m.js → diagram-22UHCM2B-hq11eek7.js} +1 -1
  22. package/dist/client/static/js/{diagram-3UASUU5V-w328rfx0.js → diagram-3UASUU5V-7bk532gd.js} +1 -1
  23. package/dist/client/static/js/{diagram-ATOU4E4O-zzcmwnm8.js → diagram-ATOU4E4O-yt8wxttm.js} +1 -1
  24. package/dist/client/static/js/{diagram-CDSNMT55-8yw39mmj.js → diagram-CDSNMT55-n3978w6p.js} +1 -1
  25. package/dist/client/static/js/{diagram-MLGK6HIB-zgc386pv.js → diagram-MLGK6HIB-004x4gyw.js} +1 -1
  26. package/dist/client/static/js/{diagram-MPIPVDR6-efmvvscm.js → diagram-MPIPVDR6-498nt489.js} +1 -1
  27. package/dist/client/static/js/{dockerfile-bp5dre33.js → dockerfile-6hbcmkc8.js} +1 -1
  28. package/dist/client/static/js/{ebnfDiagram-ZINNZB2B-p66h0dzq.js → ebnfDiagram-ZINNZB2B-5fkmymqn.js} +1 -1
  29. package/dist/client/static/js/{elk-276RUBZZ-g0jjxcqd.js → elk-276RUBZZ-6xrfa2kd.js} +1 -1
  30. package/dist/client/static/js/{erDiagram-OPXOYQCR-39gat96z.js → erDiagram-OPXOYQCR-byz4zbkn.js} +1 -1
  31. package/dist/client/static/js/flowDiagram-KWPJA3E3-s3fbfwrz.js +1 -0
  32. package/dist/client/static/js/{ganttDiagram-FUAMR5RP-nsjv1zt4.js → ganttDiagram-FUAMR5RP-4fkw1k01.js} +1 -1
  33. package/dist/client/static/js/{gitGraphDiagram-X574FWY7-r4vnkcy3.js → gitGraphDiagram-X574FWY7-19g84yw8.js} +1 -1
  34. package/dist/client/static/js/{index-hzx81cjq.js → index-0v8b5pzb.js} +1 -1
  35. package/dist/client/static/js/{index-h8h5c2r8.js → index-1j1s91c4.js} +1 -1
  36. package/dist/client/static/js/{index-6ax2z70w.js → index-20vhkcb9.js} +1 -1
  37. package/dist/client/static/js/{index-st202rjv.js → index-3wpsr2bc.js} +7 -7
  38. package/dist/client/static/js/{index-73jwm4d5.js → index-3y6krykq.js} +1 -1
  39. package/dist/client/static/js/{index-1qszrvzk.js → index-4jbbdq6n.js} +1 -1
  40. package/dist/client/static/js/{index-tfsaj5d1.js → index-4qt2e84b.js} +1 -1
  41. package/dist/client/static/js/{index-da10qpns.js → index-57z8mtmx.js} +1 -1
  42. package/dist/client/static/js/{index-ha75kff0.js → index-5gn56236.js} +1 -1
  43. package/dist/client/static/js/{index-k9xsvab3.js → index-74scnfpk.js} +1 -1
  44. package/dist/client/static/js/{index-dkseg29t.js → index-7kafzae0.js} +2 -2
  45. package/dist/client/static/js/{index-ra38ggke.js → index-89a2702q.js} +1 -1
  46. package/dist/client/static/js/{index-tv61v3t3.js → index-8j90mdgz.js} +1 -1
  47. package/dist/client/static/js/{index-50z4ek83.js → index-baet2nv8.js} +1 -1
  48. package/dist/client/static/js/{index-a74k07z2.js → index-bhng2dax.js} +1 -1
  49. package/dist/client/static/js/{index-24yyj78e.js → index-cj9193d5.js} +1 -1
  50. package/dist/client/static/js/{index-5ebhb94w.js → index-dd4q54y0.js} +1 -1
  51. package/dist/client/static/js/{index-dfgdn3fj.js → index-e3w46vsc.js} +1 -1
  52. package/dist/client/static/js/{index-rgp69pa8.js → index-e99ec2f0.js} +1 -1
  53. package/dist/client/static/js/{index-2ndq1ngv.js → index-ehnztdd2.js} +1 -1
  54. package/dist/client/static/js/{index-rqrcw8nj.js → index-epbqzayj.js} +1 -1
  55. package/dist/client/static/js/{index-vnn7m9yp.js → index-fpf1jkwd.js} +1 -1
  56. package/dist/client/static/js/{index-vxd4gykh.js → index-g252205p.js} +1 -1
  57. package/dist/client/static/js/{index-11bdd235.js → index-gxtgyya0.js} +1 -1
  58. package/dist/client/static/js/{index-tzm90bsz.js → index-j314me09.js} +1 -1
  59. package/dist/client/static/js/{index-gwhx66f4.js → index-jbwns6sc.js} +1 -1
  60. package/dist/client/static/js/{index-c15r8jd3.js → index-kdgcbt17.js} +1 -1
  61. package/dist/client/static/js/{index-rf0p3v7q.js → index-m4bjsyj2.js} +1 -1
  62. package/dist/client/static/js/{index-2drjp9ks.js → index-pfwd0160.js} +1 -1
  63. package/dist/client/static/js/{index-e1pr3k50.js → index-qntytvt0.js} +1 -1
  64. package/dist/client/static/js/{index-z0cpp5bc.js → index-rgdhyry3.js} +1 -1
  65. package/dist/client/static/js/{index-9wtg6ywn.js → index-sjnnv1gd.js} +1 -1
  66. package/dist/client/static/js/{index-5y0bvq4q.js → index-zj45wj1x.js} +2 -2
  67. package/dist/client/static/js/{index-0kxqzafy.js → index-zw7qjx65.js} +1 -1
  68. package/dist/client/static/js/{infoDiagram-VRGFBTTK-e39pvm4j.js → infoDiagram-VRGFBTTK-aw6ter0a.js} +1 -1
  69. package/dist/client/static/js/{ishikawaDiagram-OU5B5YK6-rqhszgvp.js → ishikawaDiagram-OU5B5YK6-62gst5wh.js} +1 -1
  70. package/dist/client/static/js/{journeyDiagram-ZHPQQLJL-wgy5qrsv.js → journeyDiagram-ZHPQQLJL-6kgv5a4j.js} +1 -1
  71. package/dist/client/static/js/{kanban-definition-PNTS6WVX-b8bxn0h1.js → kanban-definition-PNTS6WVX-8p3515b7.js} +1 -1
  72. package/dist/client/static/js/{mermaid.core-vb5ehtre.js → mermaid.core-b6ga2y8y.js} +2 -2
  73. package/dist/client/static/js/{mindmap-definition-NLK3R4M7-t4p38s38.js → mindmap-definition-NLK3R4M7-na9e9b4a.js} +1 -1
  74. package/dist/client/static/js/one-dark-pro-xp6ssk4z.js +1 -0
  75. package/dist/client/static/js/one-light-xgab7b02.js +1 -0
  76. package/dist/client/static/js/{pegDiagram-GJSIUBJH-3gp4madx.js → pegDiagram-GJSIUBJH-d1hk7fnq.js} +1 -1
  77. package/dist/client/static/js/{pieDiagram-5QR66LMP-0cbm773h.js → pieDiagram-5QR66LMP-7b9f4x0y.js} +1 -1
  78. package/dist/client/static/js/{quadrantDiagram-O4NWA36T-jwg7fc9f.js → quadrantDiagram-O4NWA36T-q4wxgmhg.js} +1 -1
  79. package/dist/client/static/js/{railroadDiagram-XR7U4H2S-38xh691s.js → railroadDiagram-XR7U4H2S-jngq1qx4.js} +1 -1
  80. package/dist/client/static/js/{requirementDiagram-PLB6GJNP-gpddawxh.js → requirementDiagram-PLB6GJNP-6xph3b72.js} +1 -1
  81. package/dist/client/static/js/{rust-bx3ecv4n.js → rust-w6hen2h4.js} +1 -1
  82. package/dist/client/static/js/{sankeyDiagram-IPEJSGJF-s6t6bbhk.js → sankeyDiagram-IPEJSGJF-ncfzgdj8.js} +1 -1
  83. package/dist/client/static/js/{sequenceDiagram-PO4LG4MO-wkq51pmb.js → sequenceDiagram-PO4LG4MO-sqz0yfg0.js} +1 -1
  84. package/dist/client/static/js/{sizeCapture-INFHLROL-xtwexf8k.js → sizeCapture-INFHLROL-vt8qp04d.js} +1 -1
  85. package/dist/client/static/js/{stateDiagram-v2-GCMORJYK-jnwsqa7y.js → stateDiagram-v2-GCMORJYK-myjtrmfe.js} +1 -1
  86. package/dist/client/static/js/{swimlanes-2SLR337P-mnkkqcbx.js → swimlanes-2SLR337P-z9vx7z4j.js} +1 -1
  87. package/dist/client/static/js/{swimlanesDiagram-TC7HE7FX-6xmrz03n.js → swimlanesDiagram-TC7HE7FX-5vha7thx.js} +1 -1
  88. package/dist/client/static/js/{timeline-definition-EJHVYXUP-rxq6heqh.js → timeline-definition-EJHVYXUP-z815np57.js} +1 -1
  89. package/dist/client/static/js/{usecaseDiagram-POWQR4AR-dz94f57t.js → usecaseDiagram-POWQR4AR-06ntggng.js} +1 -1
  90. package/dist/client/static/js/{vennDiagram-UO4OBE2U-5mmvkhsq.js → vennDiagram-UO4OBE2U-nmtaf5rp.js} +1 -1
  91. package/dist/client/static/js/{wardleyDiagram-VNRHLVJA-dctdntpa.js → wardleyDiagram-VNRHLVJA-zgsxmak8.js} +1 -1
  92. package/dist/client/static/js/{xychartDiagram-PMCCYNJV-njyfrqkv.js → xychartDiagram-PMCCYNJV-8bg9qdra.js} +1 -1
  93. package/package.json +1 -1
  94. package/src/server/lib/changes/capture-bash.server.ts +69 -4
  95. package/src/server/lib/changes/capture-fs.server.ts +2 -2
  96. package/src/server/lib/changes/capture-races.test.ts +107 -0
  97. package/src/server/lib/changes/capture-scan.test.ts +157 -0
  98. package/src/server/lib/changes/capture-test-util.ts +1 -1
  99. package/src/server/lib/changes/capture-types.ts +3 -1
  100. package/src/server/lib/changes/capture-write.server.ts +50 -0
  101. package/src/server/lib/changes/capture.server.ts +32 -16
  102. package/src/server/lib/changes/capture.test.ts +48 -0
  103. package/src/server/lib/changes/journal.server.ts +3 -1
  104. package/src/server/lib/changes/omp-fallback.server.ts +48 -0
  105. package/src/server/lib/changes/omp-fallback.test.ts +75 -0
  106. package/src/server/lib/changes/reader.server.ts +28 -0
  107. package/src/server/lib/changes/scan.server.ts +51 -1
  108. package/src/server/lib/changes/sessions.server.ts +65 -0
  109. package/src/server/lib/changes/sessions.test.ts +52 -0
  110. package/dist/client/static/js/flowDiagram-KWPJA3E3-f6jpcqyq.js +0 -1
  111. package/dist/client/static/js/one-dark-pro-dhybn1ff.js +0 -1
  112. package/dist/client/static/js/one-light-bqg77ay0.js +0 -1
@@ -25,11 +25,16 @@ import type {
25
25
  ShellTrace,
26
26
  } from '@/server/lib/changes/capture-types';
27
27
  import type { GitScan } from '@/server/lib/changes/scan.server';
28
+ import { readSessionChangeLast, readSessionChangePaths } from '@/server/lib/changes/reader.server';
29
+ import { blobKey } from '@/server/lib/changes/blobs.server';
30
+ import { sessionsInCwd } from '@/server/lib/changes/sessions.server';
28
31
 
29
32
  export interface BashCaptureHost {
33
+ sessionId: string;
30
34
  cwd: string;
31
35
  home: string;
32
36
  readFile(absolute: string): Promise<string | null | undefined>;
37
+ statFile(absolute: string): Promise<{ mtimeMs: number; size: number; birthtimeMs: number } | null>;
33
38
  takeScan(cwd: string): Promise<GitScan | null>;
34
39
  readHead(root: string, absolute: string): Promise<string | null>;
35
40
  writeChange(
@@ -65,12 +70,24 @@ export async function captureBashChanges(
65
70
  }
66
71
 
67
72
  const exit = typeof trace?.status === 'number' ? trace.status : undefined;
73
+ // Paths the trace already handled; the scan must not record them again.
74
+ const written = new Set<string>();
68
75
  for (const mutation of mutations.values()) {
76
+ written.add(mutation.path);
77
+ if (mutation.from) written.add(mutation.from);
69
78
  if (mutation.op === 'rename' && mutation.from) {
70
79
  const fromEntry = pending.before.get(mutation.from);
71
80
  const before = fromEntry ? fromEntry.text : null;
72
81
  const after = await host.readFile(mutation.path);
73
- if (before === after) continue;
82
+ if (before === after) {
83
+ const info = await host.statFile(mutation.path);
84
+ if (info && info.mtimeMs >= pending.startedAt) {
85
+ const created = info.birthtimeMs >= pending.startedAt;
86
+ await host.writeChange(pending, mutation.from, created ? null : undefined, null, 'trace', { command: pending.command, exit, ...(created ? {} : { unavailableReason: 'snapshot-race' }) });
87
+ await host.writeChange(pending, mutation.path, null, after, 'trace', { command: pending.command, exit, from: mutation.from });
88
+ }
89
+ continue;
90
+ }
74
91
  // Two records, so the existing A/M/D list can render a rename.
75
92
  await host.writeChange(pending, mutation.from, before, null, 'trace', { command: pending.command, exit });
76
93
  await host.writeChange(pending, mutation.path, null, after, 'trace', { command: pending.command, exit, from: mutation.from });
@@ -79,28 +96,76 @@ export async function captureBashChanges(
79
96
  const pathEntry = pending.before.get(mutation.path);
80
97
  const before = pathEntry ? pathEntry.text : null;
81
98
  const after = await host.readFile(mutation.path);
99
+ if (before === after) {
100
+ // A fast command can finish before the start-frame snapshot reads the
101
+ // file. The mtime proves the command touched it; the birth time says
102
+ // whether it created the file (A) or rewrote an existing one (M).
103
+ const info = await host.statFile(mutation.path);
104
+ if (info && info.mtimeMs >= pending.startedAt) {
105
+ const created = info.birthtimeMs >= pending.startedAt;
106
+ await host.writeChange(
107
+ pending,
108
+ mutation.path,
109
+ created ? null : undefined,
110
+ after,
111
+ 'trace',
112
+ created ? { command: pending.command, exit } : { command: pending.command, exit, unavailableReason: 'snapshot-race' },
113
+ );
114
+ }
115
+ continue;
116
+ }
82
117
  await host.writeChange(pending, mutation.path, before, after, 'trace', { command: pending.command, exit });
83
118
  }
84
119
 
85
- if (pending.scan) await reconcileScan(pending, pending.scan, host);
120
+ if (pending.scan) await reconcileScan(pending, pending.scan, host, written);
86
121
  if (plan.opaque) await host.note(pending, 'opaque-command', pending.command);
87
122
  }
88
123
 
89
124
  /** Journal the delta an opaque command made, from the two git snapshots. */
90
- async function reconcileScan(pending: PendingCall, start: GitScan, host: BashCaptureHost): Promise<void> {
125
+ async function reconcileScan(
126
+ pending: PendingCall,
127
+ start: GitScan,
128
+ host: BashCaptureHost,
129
+ skip: Set<string>,
130
+ ): Promise<void> {
91
131
  const after = await host.takeScan(host.cwd);
92
132
  if (!after) return;
93
133
  if (start.truncated || after.truncated) await host.note(pending, 'scan-budget', pending.command);
94
134
 
135
+ // A concurrent session in the same cwd may have written a path the scan
136
+ // sees. Its own journal is the exact record; skip what it already claimed.
137
+ const from = pending.startedAt - 1000;
138
+ const to = Date.now() + 1000;
139
+ const claimed = new Set<string>();
140
+ for (const sessionId of await sessionsInCwd(host.cwd, host.sessionId)) {
141
+ for (const path of await readSessionChangePaths(sessionId, from, to)) claimed.add(path);
142
+ }
143
+
95
144
  const paths = new Set([...start.dirty.keys(), ...after.dirty.keys()]);
96
145
  for (const absolute of paths) {
146
+ if (skip.has(absolute)) continue;
147
+ if (claimed.has(absolute)) continue;
97
148
  const before = start.dirty.has(absolute)
98
149
  ? start.dirty.get(absolute) ?? null
99
150
  : await host.readHead(start.root, absolute);
100
151
  const afterText = after.dirty.has(absolute)
101
152
  ? after.dirty.get(absolute) ?? null
102
153
  : await host.readFile(absolute);
103
- if (before === afterText) continue;
154
+ if (before === afterText) {
155
+ // A fast command can create the file before the start scan reads the
156
+ // directory, so both snapshots hold the after content. The birth time
157
+ // still proves the command created it.
158
+ const info = await host.statFile(absolute);
159
+ if (info && info.birthtimeMs >= pending.startedAt) {
160
+ await host.writeChange(pending, absolute, null, afterText, 'scan');
161
+ }
162
+ continue;
163
+ }
164
+ // A later opaque command's scan sees files an earlier call already
165
+ // recorded. Same content means no new change; skip the duplicate.
166
+ const last = await readSessionChangeLast(host.sessionId, absolute);
167
+ const afterKey = afterText === null || afterText === undefined ? afterText : blobKey(afterText);
168
+ if (last && last.after === afterKey) continue;
104
169
  await host.writeChange(pending, absolute, before, afterText, 'scan');
105
170
  }
106
171
  }
@@ -38,10 +38,10 @@ export async function defaultReadFile(absolute: string): Promise<string | null>
38
38
  }
39
39
  }
40
40
 
41
- export async function defaultStatFile(absolute: string): Promise<{ mtimeMs: number; size: number } | null> {
41
+ export async function defaultStatFile(absolute: string): Promise<{ mtimeMs: number; size: number; birthtimeMs: number } | null> {
42
42
  try {
43
43
  const info = await stat(absolute);
44
- return { mtimeMs: info.mtimeMs, size: info.size };
44
+ return { mtimeMs: info.mtimeMs, size: info.size, birthtimeMs: info.birthtimeMs };
45
45
  } catch {
46
46
  return null;
47
47
  }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Snapshot races: the start-frame read lost to the tool's own write.
8
+ *
9
+ * A `write` whose before snapshot already holds the after content, and a fast
10
+ * `bash` command that finishes before the snapshot reads the file, must not be
11
+ * dropped. The birth time decides create (A) from rewrite (M), and a rewrite
12
+ * with no omp record is an unknown before plus a `snapshot-race` note.
13
+ */
14
+
15
+ import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
16
+ import * as fsp from 'node:fs/promises';
17
+ import * as os from 'node:os';
18
+ import * as path from 'node:path';
19
+ import { makeCapture, records, REPO } from '@/server/lib/changes/capture-test-util';
20
+
21
+ // The capture journals the host's spelling of the path: a literal `/repo` never
22
+ // matches on Windows.
23
+ const RACE = path.join(REPO, 'race.txt');
24
+
25
+ let dataDir = '';
26
+ let agentDir = '';
27
+ let original: string | undefined;
28
+ let originalAgent: string | undefined;
29
+
30
+ beforeAll(async () => {
31
+ original = Bun.env.KABMO_DATA_DIR;
32
+ originalAgent = Bun.env.PI_CODING_AGENT_DIR;
33
+ dataDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'kabmo-changes-races-'));
34
+ agentDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'kabmo-changes-races-agent-'));
35
+ Bun.env.KABMO_DATA_DIR = dataDir;
36
+ Bun.env.PI_CODING_AGENT_DIR = agentDir;
37
+ });
38
+
39
+ afterAll(async () => {
40
+ if (original === undefined) delete Bun.env.KABMO_DATA_DIR;
41
+ else Bun.env.KABMO_DATA_DIR = original;
42
+ if (originalAgent === undefined) delete Bun.env.PI_CODING_AGENT_DIR;
43
+ else Bun.env.PI_CODING_AGENT_DIR = originalAgent;
44
+ await fsp.rm(dataDir, { recursive: true, force: true });
45
+ await fsp.rm(agentDir, { recursive: true, force: true });
46
+ });
47
+
48
+ describe('snapshot races', () => {
49
+ test('a write whose snapshot raced is recorded with an unknown before', async () => {
50
+ const files = new Map([[RACE, 'content']]);
51
+ const capture = makeCapture('cap-write-race', files);
52
+ capture.onFrame({
53
+ type: 'tool_execution_start',
54
+ toolCallId: 'c1',
55
+ toolName: 'write',
56
+ args: { path: 'race.txt', content: 'content' },
57
+ });
58
+ await capture.flush();
59
+ // The file already holds the content: the snapshot read the after state.
60
+ capture.onFrame({ type: 'tool_execution_end', toolCallId: 'c1', toolName: 'write' });
61
+ await capture.flush();
62
+
63
+ const lines = await records('cap-write-race');
64
+ const change = lines.find((line) => line.type === 'change');
65
+ expect(change?.type).toBe('change');
66
+ if (change?.type !== 'change') throw new Error('expected a change');
67
+ expect(change.before).toBeUndefined();
68
+ expect(typeof change.after).toBe('string');
69
+ const note = lines.find((line) => line.type === 'note');
70
+ expect(note?.type).toBe('note');
71
+ if (note?.type !== 'note') throw new Error('expected a note');
72
+ expect(note.reason).toBe('snapshot-race');
73
+ });
74
+
75
+ test('a fast bash create whose snapshot raced is recorded as a create', async () => {
76
+ const files = new Map([[RACE, 'hi\n']]);
77
+ const capture = makeCapture('cap-bash-race', files, {
78
+ statFile: async (absolute) =>
79
+ files.has(absolute)
80
+ ? { mtimeMs: Date.now() + 1000, size: files.get(absolute)?.length ?? 0, birthtimeMs: Date.now() + 1000 }
81
+ : null,
82
+ });
83
+ capture.onFrame({
84
+ type: 'tool_execution_start',
85
+ toolCallId: 'c1',
86
+ toolName: 'bash',
87
+ args: { command: 'echo hi > race.txt' },
88
+ });
89
+ await capture.flush();
90
+ capture.onFrame({
91
+ type: 'tool_execution_end',
92
+ toolCallId: 'c1',
93
+ toolName: 'bash',
94
+ result: { details: { trace: { status: 0, units: [{ nodes: [{ k: 'simple', argv: ['echo', 'hi'], st: 0 }] }] } } },
95
+ });
96
+ await capture.flush();
97
+
98
+ const lines = await records('cap-bash-race');
99
+ const change = lines.find((line) => line.type === 'change');
100
+ expect(change?.type).toBe('change');
101
+ if (change?.type !== 'change') throw new Error('expected a change');
102
+ expect(change.before).toBeNull();
103
+ expect(typeof change.after).toBe('string');
104
+ expect(lines.some((line) => line.type === 'note')).toBe(false);
105
+ });
106
+ });
107
+
@@ -0,0 +1,157 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The scan's same-content dedupe.
8
+ *
9
+ * A later opaque command's scan sees every file in the cwd, including ones an
10
+ * earlier call already recorded. If the current session's last record for the
11
+ * path holds the same content, the scan must not journal it again.
12
+ */
13
+
14
+ import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
15
+ import * as fsp from 'node:fs/promises';
16
+ import * as os from 'node:os';
17
+ import * as path from 'node:path';
18
+ import { ChangeCapture } from '@/server/lib/changes/capture.server';
19
+ import { ChangeJournal } from '@/server/lib/changes/journal.server';
20
+ import { HOME, REPO, makeCapture, records } from '@/server/lib/changes/capture-test-util';
21
+
22
+ function at(relative: string): string {
23
+ return path.join(REPO, relative);
24
+ }
25
+
26
+ let dataDir = '';
27
+ let original: string | undefined;
28
+
29
+ beforeAll(async () => {
30
+ original = Bun.env.KABMO_DATA_DIR;
31
+ dataDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'kabmo-changes-scan-'));
32
+ Bun.env.KABMO_DATA_DIR = dataDir;
33
+ });
34
+
35
+ afterAll(async () => {
36
+ if (original === undefined) delete Bun.env.KABMO_DATA_DIR;
37
+ else Bun.env.KABMO_DATA_DIR = original;
38
+ await fsp.rm(dataDir, { recursive: true, force: true });
39
+ });
40
+
41
+ describe('scan dedupe', () => {
42
+ test('a scan skips a path the current session already recorded with the same content', async () => {
43
+ const file = path.join(REPO, 'same.txt');
44
+ const journal = new ChangeJournal('cap-same', REPO);
45
+ await journal.recordChange({
46
+ at: Date.now(), agent: 'Main', tool: 'bash', op: 'create', path: file,
47
+ displayPath: 'same.txt', before: null, after: 'python', source: 'trace',
48
+ });
49
+ await journal.flush();
50
+
51
+ const scans = [
52
+ { root: REPO, dirty: new Map([[file, 'old']]), truncated: false },
53
+ { root: REPO, dirty: new Map([[file, 'python']]), truncated: false },
54
+ ];
55
+ const capture = new ChangeCapture({
56
+ journal,
57
+ cwd: REPO,
58
+ home: HOME,
59
+ takeScan: async () => scans.shift() ?? null,
60
+ readHead: async () => null,
61
+ });
62
+ capture.onFrame({
63
+ type: 'tool_execution_start',
64
+ toolCallId: 'c1',
65
+ toolName: 'bash',
66
+ args: { command: "python3 - <<'PY'\nopen('same.txt','w').write('python')\nPY" },
67
+ });
68
+ await capture.flush();
69
+ capture.onFrame({
70
+ type: 'tool_execution_end',
71
+ toolCallId: 'c1',
72
+ toolName: 'bash',
73
+ result: { details: { trace: { status: 0, units: [{ nodes: [{ k: 'simple', argv: ['python3', '-'], st: 0 }] }] } } },
74
+ });
75
+ await capture.flush();
76
+
77
+ const changes = (await records('cap-same')).filter((line) => line.type === 'change' && line.path === file);
78
+ expect(changes.length).toBe(1);
79
+ });
80
+ });
81
+
82
+ describe('directory scan', () => {
83
+ test('a python3 script in a non-git cwd is reconciled from the directory scan', async () => {
84
+ const files = new Map<string, string>();
85
+ const scans = [
86
+ { root: REPO, dirty: new Map<string, string | null>(), truncated: false },
87
+ { root: REPO, dirty: new Map([[at('file4.txt'), 'python']]), truncated: false },
88
+ ];
89
+ const capture = makeCapture('cap-dir-scan', files, {
90
+ takeScan: async () => scans.shift() ?? null,
91
+ readHead: async () => null,
92
+ });
93
+ capture.onFrame({
94
+ type: 'tool_execution_start',
95
+ toolCallId: 'c1',
96
+ toolName: 'bash',
97
+ args: { command: "python3 - <<'PY'\nopen('file4.txt','w').write('python')\nPY" },
98
+ });
99
+ await capture.flush();
100
+ files.set(at('file4.txt'), 'python');
101
+ capture.onFrame({
102
+ type: 'tool_execution_end',
103
+ toolCallId: 'c1',
104
+ toolName: 'bash',
105
+ result: { details: { trace: { status: 0, units: [{ nodes: [{ k: 'simple', argv: ['python3', '-'], st: 0 }] }] } } },
106
+ });
107
+ await capture.flush();
108
+
109
+ const lines = await records('cap-dir-scan');
110
+ const change = lines.find((line) => line.type === 'change');
111
+ expect(change?.type).toBe('change');
112
+ if (change?.type !== 'change') throw new Error('expected a change');
113
+ expect(change.before).toBeNull();
114
+ expect(typeof change.after).toBe('string');
115
+ expect(change.source).toBe('scan');
116
+ expect(lines.some((line) => line.type === 'note' && line.reason === 'opaque-command')).toBe(true);
117
+ });
118
+ });
119
+
120
+ describe('directory scan race', () => {
121
+ test('a file created before the start scan is still a create', async () => {
122
+ const files = new Map([[at('race4.txt'), 'python']]);
123
+ const scans = [
124
+ { root: REPO, dirty: new Map([[at('race4.txt'), 'python']]), truncated: false },
125
+ { root: REPO, dirty: new Map([[at('race4.txt'), 'python']]), truncated: false },
126
+ ];
127
+ const capture = makeCapture('cap-dir-race', files, {
128
+ takeScan: async () => scans.shift() ?? null,
129
+ readHead: async () => null,
130
+ statFile: async (absolute) =>
131
+ files.has(absolute)
132
+ ? { mtimeMs: Date.now() + 1000, size: files.get(absolute)?.length ?? 0, birthtimeMs: Date.now() + 1000 }
133
+ : null,
134
+ });
135
+ capture.onFrame({
136
+ type: 'tool_execution_start',
137
+ toolCallId: 'c1',
138
+ toolName: 'bash',
139
+ args: { command: "python3 - <<'PY'\nopen('race4.txt','w').write('python')\nPY" },
140
+ });
141
+ await capture.flush();
142
+ capture.onFrame({
143
+ type: 'tool_execution_end',
144
+ toolCallId: 'c1',
145
+ toolName: 'bash',
146
+ result: { details: { trace: { status: 0, units: [{ nodes: [{ k: 'simple', argv: ['python3', '-'], st: 0 }] }] } } },
147
+ });
148
+ await capture.flush();
149
+
150
+ const change = (await records('cap-dir-race')).find((line) => line.type === 'change');
151
+ expect(change?.type).toBe('change');
152
+ if (change?.type !== 'change') throw new Error('expected a change');
153
+ expect(change.before).toBeNull();
154
+ expect(change.source).toBe('scan');
155
+ });
156
+ });
157
+
@@ -35,7 +35,7 @@ export function makeCapture(
35
35
  cwd: REPO,
36
36
  home: HOME,
37
37
  readFile: async (absolute) => files.get(absolute) ?? null,
38
- statFile: async (absolute) => (files.has(absolute) ? { mtimeMs: 1, size: files.get(absolute)?.length ?? 0 } : null),
38
+ statFile: async (absolute) => (files.has(absolute) ? { mtimeMs: 1, size: files.get(absolute)?.length ?? 0, birthtimeMs: 0 } : null),
39
39
  ...extra,
40
40
  });
41
41
  }
@@ -48,6 +48,8 @@ export interface ChangeExtra {
48
48
  command?: string;
49
49
  exit?: number;
50
50
  from?: string;
51
+ /** Why a side is `undefined`; the journal writes the matching note. */
52
+ unavailableReason?: 'too-large' | 'snapshot-race';
51
53
  }
52
54
 
53
55
  export interface CaptureDeps {
@@ -55,7 +57,7 @@ export interface CaptureDeps {
55
57
  cwd: string;
56
58
  home: string;
57
59
  readFile?: (absolute: string) => Promise<string | null>;
58
- statFile?: (absolute: string) => Promise<{ mtimeMs: number; size: number } | null>;
60
+ statFile?: (absolute: string) => Promise<{ mtimeMs: number; size: number; birthtimeMs: number } | null>;
59
61
  /** The git snapshot seam; tests inject a fake, production uses `scan.server`. */
60
62
  takeScan?: (cwd: string) => Promise<GitScan | null>;
61
63
  readHead?: (root: string, absolute: string) => Promise<string | null>;
@@ -0,0 +1,50 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The `write` race: the start-frame snapshot read the file AFTER the tool wrote
8
+ * it, so `before === after` and the change would be dropped.
9
+ *
10
+ * omp reads the file inside the tool, before the write, so its journal's
11
+ * `before` blob is exact. When it has no record (an ACP agent, or a build that
12
+ * does not journal), the file's birth time decides: a file born after the call
13
+ * started was created by this write (`before: null`, an A), and an older file
14
+ * is a rewrite whose before is unknown (`before: undefined`, an M with a
15
+ * `snapshot-race` note).
16
+ */
17
+
18
+ import type { PendingCall } from '@/server/lib/changes/capture-types';
19
+ import { readOmpBefore } from '@/server/lib/changes/omp-fallback.server';
20
+
21
+ /** The before side of an `edit` whose write landed before the snapshot. */
22
+ export function reconstructEdit(pending: PendingCall, after: string | null | undefined): string | null {
23
+ if (after === null || after === undefined) return null;
24
+ const oldString = pending.args.old_string;
25
+ const newString = pending.args.new_string;
26
+ if (typeof oldString !== 'string' || typeof newString !== 'string' || !newString) return null;
27
+ if (!after.includes(newString)) return null;
28
+ return after.replace(newString, oldString);
29
+ }
30
+
31
+ export interface RacedWrite {
32
+ before: string | null | undefined;
33
+ reason?: 'snapshot-race';
34
+ }
35
+
36
+ export async function resolveRacedWrite(
37
+ pending: PendingCall,
38
+ absolute: string,
39
+ deps: {
40
+ sessionId: string;
41
+ statFile: (path: string) => Promise<{ birthtimeMs: number } | null>;
42
+ },
43
+ ): Promise<RacedWrite> {
44
+ const ompBefore = await readOmpBefore(deps.sessionId, absolute, pending.startedAt);
45
+ if (ompBefore !== undefined) return { before: ompBefore };
46
+
47
+ const info = await deps.statFile(absolute);
48
+ const created = info !== null && info.birthtimeMs >= pending.startedAt;
49
+ return created ? { before: null } : { before: undefined, reason: 'snapshot-race' };
50
+ }
@@ -48,14 +48,15 @@ import type {
48
48
  PendingCall,
49
49
  ShellTrace,
50
50
  } from '@/server/lib/changes/capture-types';
51
- import { readHeadContent, takeGitScan, type GitScan } from '@/server/lib/changes/scan.server';
51
+ import { readHeadContent, takeScan, type GitScan } from '@/server/lib/changes/scan.server';
52
+ import { reconstructEdit, resolveRacedWrite } from '@/server/lib/changes/capture-write.server';
52
53
  import { MAX_BLOB_BYTES } from '@/server/lib/changes/blobs.server';
53
54
 
54
55
  export class ChangeCapture {
55
56
  readonly #pending = new Map<string, PendingCall>();
56
57
  readonly #tasks = new Set<Promise<void>>();
57
58
  readonly #readFile: (absolute: string) => Promise<string | null>;
58
- readonly #statFile: (absolute: string) => Promise<{ mtimeMs: number; size: number } | null>;
59
+ readonly #statFile: (absolute: string) => Promise<{ mtimeMs: number; size: number; birthtimeMs: number } | null>;
59
60
  readonly #takeScan: (cwd: string) => Promise<GitScan | null>;
60
61
  readonly #readHead: (root: string, absolute: string) => Promise<string | null>;
61
62
  /** The open run; kept after a terminal end so a late subagent keeps its id. */
@@ -66,7 +67,7 @@ export class ChangeCapture {
66
67
  constructor(private readonly deps: CaptureDeps) {
67
68
  this.#readFile = deps.readFile ?? defaultReadFile;
68
69
  this.#statFile = deps.statFile ?? defaultStatFile;
69
- this.#takeScan = deps.takeScan ?? takeGitScan;
70
+ this.#takeScan = deps.takeScan ?? takeScan;
70
71
  this.#readHead = deps.readHead ?? readHeadContent;
71
72
  }
72
73
 
@@ -159,6 +160,9 @@ export class ChangeCapture {
159
160
  args,
160
161
  });
161
162
  pending.ready = this.#snapshotBefore(pending);
163
+ // The start task is not done until the snapshot is: `flush()` after a start
164
+ // frame must mean the before state was read, not merely scheduled.
165
+ await pending.ready;
162
166
  }
163
167
 
164
168
  async #snapshotBefore(pending: PendingCall): Promise<void> {
@@ -235,9 +239,28 @@ export class ChangeCapture {
235
239
  const before = entry ? entry.text : null;
236
240
  const after = await this.#readCapped(absolute);
237
241
  if (before === after) {
238
- const reconstructed = this.#reconstructEdit(pending, after);
239
- if (reconstructed === null) continue;
240
- await this.#writeChange(pending, absolute, reconstructed, after, 'tool');
242
+ const reconstructed = reconstructEdit(pending, after);
243
+ if (reconstructed !== null) {
244
+ await this.#writeChange(pending, absolute, reconstructed, after, 'tool');
245
+ continue;
246
+ }
247
+ // A `write` whose snapshot raced the tool: omp's own journal read the
248
+ // file before the write, so its `before` is exact. Without it, record
249
+ // the change with an unknown before rather than dropping the file.
250
+ if (pending.tool === 'write' && typeof pending.args.content === 'string' && after === pending.args.content) {
251
+ const raced = await resolveRacedWrite(pending, absolute, {
252
+ sessionId: this.deps.journal.sessionId,
253
+ statFile: this.#statFile,
254
+ });
255
+ await this.#writeChange(
256
+ pending,
257
+ absolute,
258
+ raced.before,
259
+ after,
260
+ 'tool',
261
+ raced.reason ? { unavailableReason: raced.reason } : {},
262
+ );
263
+ }
241
264
  continue;
242
265
  }
243
266
  await this.#writeChange(pending, absolute, before, after, 'tool');
@@ -251,21 +274,13 @@ export class ChangeCapture {
251
274
  return this.#readFile(absolute);
252
275
  }
253
276
 
254
- /** The before side of an `edit` whose write landed before the snapshot. */
255
- #reconstructEdit(pending: PendingCall, after: string | null | undefined): string | null {
256
- if (after === null || after === undefined) return null;
257
- const oldString = pending.args.old_string;
258
- const newString = pending.args.new_string;
259
- if (typeof oldString !== 'string' || typeof newString !== 'string' || !newString) return null;
260
- if (!after.includes(newString)) return null;
261
- return after.replace(newString, oldString);
262
- }
263
-
264
277
  async #endBash(pending: PendingCall, trace: ShellTrace | null): Promise<void> {
265
278
  const host: BashCaptureHost = {
279
+ sessionId: this.deps.journal.sessionId,
266
280
  cwd: this.deps.cwd,
267
281
  home: this.deps.home,
268
282
  readFile: (absolute) => this.#readCapped(absolute),
283
+ statFile: this.#statFile,
269
284
  takeScan: this.#takeScan,
270
285
  readHead: this.#readHead,
271
286
  writeChange: (call, absolute, before, after, source, extra) =>
@@ -313,6 +328,7 @@ export class ChangeCapture {
313
328
  source,
314
329
  ...(extra.command ? { command: extra.command } : {}),
315
330
  ...(extra.exit !== undefined ? { exit: extra.exit } : {}),
331
+ ...(extra.unavailableReason ? { unavailableReason: extra.unavailableReason } : {}),
316
332
  });
317
333
  }
318
334
 
@@ -21,21 +21,30 @@ import * as fsp from 'node:fs/promises';
21
21
  import * as os from 'node:os';
22
22
  import * as path from 'node:path';
23
23
  import { makeCapture, records, REPO } from '@/server/lib/changes/capture-test-util';
24
+ import { ChangeJournal } from '@/server/lib/changes/journal.server';
24
25
  import { readSessionChangeDiff } from '@/server/lib/changes/reader.server';
25
26
 
26
27
  let dataDir = '';
28
+ let agentDir = '';
27
29
  let original: string | undefined;
30
+ let originalAgent: string | undefined;
28
31
 
29
32
  beforeAll(async () => {
30
33
  original = Bun.env.KABMO_DATA_DIR;
34
+ originalAgent = Bun.env.PI_CODING_AGENT_DIR;
31
35
  dataDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'kabmo-changes-capture-'));
36
+ agentDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'kabmo-changes-capture-agent-'));
32
37
  Bun.env.KABMO_DATA_DIR = dataDir;
38
+ Bun.env.PI_CODING_AGENT_DIR = agentDir;
33
39
  });
34
40
 
35
41
  afterAll(async () => {
36
42
  if (original === undefined) delete Bun.env.KABMO_DATA_DIR;
37
43
  else Bun.env.KABMO_DATA_DIR = original;
44
+ if (originalAgent === undefined) delete Bun.env.PI_CODING_AGENT_DIR;
45
+ else Bun.env.PI_CODING_AGENT_DIR = originalAgent;
38
46
  await fsp.rm(dataDir, { recursive: true, force: true });
47
+ await fsp.rm(agentDir, { recursive: true, force: true });
39
48
  });
40
49
 
41
50
  const WINDOW_END = Date.now() + 60_000;
@@ -221,6 +230,45 @@ describe('scan pass', () => {
221
230
  });
222
231
  });
223
232
 
233
+ describe('cross-session scan', () => {
234
+ test('a scan skips a path another session in the same cwd recorded', async () => {
235
+ const other = new ChangeJournal('cap-other', REPO);
236
+ await other.recordChange({
237
+ at: Date.now(), agent: 'Main', tool: 'edit', op: 'update', path: at('file4.txt'),
238
+ displayPath: 'file4.txt', before: 'a', after: 'b', source: 'tool',
239
+ });
240
+ await other.flush();
241
+
242
+ const files = new Map<string, string>();
243
+ const scans = [
244
+ { root: REPO, dirty: new Map<string, string | null>(), truncated: false },
245
+ { root: REPO, dirty: new Map([[at('file4.txt'), 'python']]), truncated: false },
246
+ ];
247
+ const capture = makeCapture('cap-cross', files, {
248
+ takeScan: async () => scans.shift() ?? null,
249
+ readHead: async () => null,
250
+ });
251
+ capture.onFrame({
252
+ type: 'tool_execution_start',
253
+ toolCallId: 'c1',
254
+ toolName: 'bash',
255
+ args: { command: "python3 - <<'PY'\nopen('file4.txt','w').write('python')\nPY" },
256
+ });
257
+ await capture.flush();
258
+ files.set(at('file4.txt'), 'python');
259
+ capture.onFrame({
260
+ type: 'tool_execution_end',
261
+ toolCallId: 'c1',
262
+ toolName: 'bash',
263
+ result: { details: { trace: { status: 0, units: [{ nodes: [{ k: 'simple', argv: ['python3', '-'], st: 0 }] }] } } },
264
+ });
265
+ await capture.flush();
266
+
267
+ const lines = await records('cap-cross');
268
+ expect(lines.some((line) => line.type === 'change' && line.path === at('file4.txt'))).toBe(false);
269
+ });
270
+ });
271
+
224
272
  describe('subagents', () => {
225
273
  test('a child edit is attributed to the child', async () => {
226
274
  const files = new Map([[at('f.ts'), 'old']]);
@@ -60,6 +60,8 @@ export interface ChangeInput {
60
60
  source: JournalChangeRecord['source'];
61
61
  command?: string;
62
62
  exit?: number;
63
+ /** Why a side is `undefined`; defaults to the blob cap. */
64
+ unavailableReason?: 'too-large' | 'snapshot-race';
63
65
  }
64
66
 
65
67
  export class ChangeJournal {
@@ -96,7 +98,7 @@ export class ChangeJournal {
96
98
  type: 'note',
97
99
  at: input.at,
98
100
  ...(input.toolCallId ? { toolCallId: input.toolCallId } : {}),
99
- reason: 'too-large',
101
+ reason: input.unavailableReason ?? 'too-large',
100
102
  detail: input.path,
101
103
  });
102
104
  }