t3code-session-manager 0.0.0-stage → 0.4.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 (172) hide show
  1. package/.claude-plugin/marketplace.json +21 -0
  2. package/.claude-plugin/plugin.json +19 -0
  3. package/CHANGELOG.md +138 -0
  4. package/LICENSE +21 -0
  5. package/README.md +660 -2
  6. package/README.pt.md +616 -0
  7. package/bin/entry.d.mts +2 -0
  8. package/bin/entry.mjs +19 -0
  9. package/bin/t3sm.mjs +44 -0
  10. package/commands/import.md +30 -0
  11. package/commands/organize.md +36 -0
  12. package/commands/status.md +24 -0
  13. package/commands/sync.md +26 -0
  14. package/dist/apply/apply.js +993 -0
  15. package/dist/apply/claudeWriter.js +168 -0
  16. package/dist/apply/copyTranscript.js +116 -0
  17. package/dist/apply/importer.js +697 -0
  18. package/dist/apply/materialize.js +335 -0
  19. package/dist/apply/waves.js +108 -0
  20. package/dist/assistant/core.js +295 -0
  21. package/dist/assistant/deps.js +256 -0
  22. package/dist/assistant/i18n.js +38 -0
  23. package/dist/assistant/messages.en.js +494 -0
  24. package/dist/assistant/messages.pt.js +495 -0
  25. package/dist/assistant/runner.js +64 -0
  26. package/dist/assistant/steps.js +1362 -0
  27. package/dist/build.json +1 -0
  28. package/dist/cli/applyScreen.js +158 -0
  29. package/dist/cli/commands/accounts.js +254 -0
  30. package/dist/cli/commands/apply.js +199 -0
  31. package/dist/cli/commands/changelog.js +61 -0
  32. package/dist/cli/commands/doctor.js +105 -0
  33. package/dist/cli/commands/help.js +158 -0
  34. package/dist/cli/commands/merge.js +224 -0
  35. package/dist/cli/commands/organize.js +872 -0
  36. package/dist/cli/commands/plan.js +161 -0
  37. package/dist/cli/commands/projects.js +430 -0
  38. package/dist/cli/commands/quarantine.js +203 -0
  39. package/dist/cli/commands/recover.js +230 -0
  40. package/dist/cli/commands/rollback.js +281 -0
  41. package/dist/cli/commands/scan.js +117 -0
  42. package/dist/cli/commands/schedule.js +288 -0
  43. package/dist/cli/commands/start.js +45 -0
  44. package/dist/cli/commands/status.js +615 -0
  45. package/dist/cli/commands/sync.js +336 -0
  46. package/dist/cli/commands/update.js +398 -0
  47. package/dist/cli/errors.js +53 -0
  48. package/dist/cli/failures.js +91 -0
  49. package/dist/cli/flags.js +53 -0
  50. package/dist/cli/help.en.js +549 -0
  51. package/dist/cli/help.pt.js +566 -0
  52. package/dist/cli/helpText.js +211 -0
  53. package/dist/cli/helpTopics.js +58 -0
  54. package/dist/cli/locked.js +12 -0
  55. package/dist/cli/main.js +155 -0
  56. package/dist/cli/screen.js +3 -0
  57. package/dist/cli/ui.js +111 -0
  58. package/dist/cli/words.js +2 -0
  59. package/dist/core/activity.js +16 -0
  60. package/dist/core/changelog.js +47 -0
  61. package/dist/core/config.js +530 -0
  62. package/dist/core/fsutil.js +171 -0
  63. package/dist/core/glob.js +34 -0
  64. package/dist/core/history.js +32 -0
  65. package/dist/core/journal.js +274 -0
  66. package/dist/core/lock.js +337 -0
  67. package/dist/core/mask.js +31 -0
  68. package/dist/core/paths.js +68 -0
  69. package/dist/core/pid.js +101 -0
  70. package/dist/core/run.js +4 -0
  71. package/dist/core/semver.js +18 -0
  72. package/dist/core/sysroot.js +29 -0
  73. package/dist/core/types.js +229 -0
  74. package/dist/core/uuid.js +29 -0
  75. package/dist/core/version.js +72 -0
  76. package/dist/help/convert.md +20 -0
  77. package/dist/help/convert.pt.md +21 -0
  78. package/dist/help/cwd-unreadable.md +22 -0
  79. package/dist/help/cwd-unreadable.pt.md +22 -0
  80. package/dist/help/decisions.md +20 -0
  81. package/dist/help/decisions.pt.md +20 -0
  82. package/dist/help/errors.md +20 -0
  83. package/dist/help/errors.pt.md +22 -0
  84. package/dist/help/held.md +20 -0
  85. package/dist/help/held.pt.md +20 -0
  86. package/dist/help/history.md +27 -0
  87. package/dist/help/history.pt.md +29 -0
  88. package/dist/help/instance-unavailable.md +18 -0
  89. package/dist/help/instance-unavailable.pt.md +19 -0
  90. package/dist/help/not-imported.md +19 -0
  91. package/dist/help/not-imported.pt.md +19 -0
  92. package/dist/help/orphaned.md +19 -0
  93. package/dist/help/orphaned.pt.md +19 -0
  94. package/dist/help/project-mismatch.md +15 -0
  95. package/dist/help/project-mismatch.pt.md +15 -0
  96. package/dist/help/t3-native.md +22 -0
  97. package/dist/help/t3-native.pt.md +22 -0
  98. package/dist/help/updates.md +26 -0
  99. package/dist/help/updates.pt.md +28 -0
  100. package/dist/help/watcher.md +24 -0
  101. package/dist/help/watcher.pt.md +25 -0
  102. package/dist/i18n/cli.js +41 -0
  103. package/dist/i18n/lang.js +55 -0
  104. package/dist/i18n/messages.en.js +1140 -0
  105. package/dist/i18n/messages.pt.js +1149 -0
  106. package/dist/i18n/words.js +12 -0
  107. package/dist/ops/accounts.js +170 -0
  108. package/dist/ops/autoUpdate.js +223 -0
  109. package/dist/ops/discoverAccounts.js +343 -0
  110. package/dist/ops/doctor.js +811 -0
  111. package/dist/ops/elevated.js +47 -0
  112. package/dist/ops/errorCodes.js +39 -0
  113. package/dist/ops/follow.js +558 -0
  114. package/dist/ops/merge.js +830 -0
  115. package/dist/ops/notify.js +249 -0
  116. package/dist/ops/plugin.js +92 -0
  117. package/dist/ops/projects.js +113 -0
  118. package/dist/ops/quarantine.js +415 -0
  119. package/dist/ops/rollback.js +868 -0
  120. package/dist/ops/schedule.js +464 -0
  121. package/dist/ops/successor.js +51 -0
  122. package/dist/ops/sync.js +859 -0
  123. package/dist/ops/syncStatus.js +290 -0
  124. package/dist/ops/update.js +273 -0
  125. package/dist/ops/updater.js +641 -0
  126. package/dist/ops/watch.js +676 -0
  127. package/dist/ops/watcherControl.js +212 -0
  128. package/dist/ops/watcherHealth.js +75 -0
  129. package/dist/organize/apply.js +495 -0
  130. package/dist/organize/history.js +192 -0
  131. package/dist/organize/plan.js +283 -0
  132. package/dist/organize/rename.js +58 -0
  133. package/dist/organize/sessions.js +100 -0
  134. package/dist/organize/titles.js +70 -0
  135. package/dist/organize/types.js +73 -0
  136. package/dist/plan/categories.js +104 -0
  137. package/dist/plan/dedupe.js +137 -0
  138. package/dist/plan/folders.js +82 -0
  139. package/dist/plan/names.js +93 -0
  140. package/dist/plan/ownership.js +316 -0
  141. package/dist/plan/planner.js +669 -0
  142. package/dist/plan/rehome.js +101 -0
  143. package/dist/plan/report.js +407 -0
  144. package/dist/sources/cache.js +89 -0
  145. package/dist/sources/claude.js +297 -0
  146. package/dist/sources/codex.js +496 -0
  147. package/dist/sources/flatten.js +23 -0
  148. package/dist/sources/jsonl.js +169 -0
  149. package/dist/sources/native.js +233 -0
  150. package/dist/sources/opencode.js +483 -0
  151. package/dist/sources/pi.js +133 -0
  152. package/dist/sources/registry.js +67 -0
  153. package/dist/sources/types.js +80 -0
  154. package/dist/t3/api.js +492 -0
  155. package/dist/t3/auth.js +248 -0
  156. package/dist/t3/compat.js +62 -0
  157. package/dist/t3/decode.js +408 -0
  158. package/dist/t3/errors.js +185 -0
  159. package/dist/t3/rpc.js +185 -0
  160. package/dist/t3/runtime.js +80 -0
  161. package/dist/ui/caps.js +56 -0
  162. package/dist/ui/components.js +202 -0
  163. package/dist/ui/layout.js +205 -0
  164. package/dist/ui/list.js +423 -0
  165. package/dist/ui/locale.js +73 -0
  166. package/dist/ui/organizePreview.js +72 -0
  167. package/dist/ui/progress.js +237 -0
  168. package/dist/ui/style.js +32 -0
  169. package/dist/ui/terminal.js +126 -0
  170. package/dist/ui/text.js +186 -0
  171. package/package.json +58 -4
  172. package/skills/t3code-sessions/SKILL.md +183 -0
@@ -0,0 +1,697 @@
1
+ // The importer loop: bump -> scan -> import -> restore -> verify, one wave at a time (docs/spikes/S2-import.md §5).
2
+ //
3
+ // Crash safety: every mtime change (bump or park) is journaled with the file's original atime/mtime BEFORE the first
4
+ // utimes, and restored in `finally`. A restore that fails leaves the bump pending in the journal; the next writing
5
+ // command's recoverPendingMtimes puts it back. A file written while its wave ran is never moved backwards.
6
+ //
7
+ // A file that is in use (mtime within ACTIVE_WINDOW_MS), gone, or different from the plan (size or mtime) is never
8
+ // bumped this run. T3 imports EVERY in-window transcript of a project, from every instance (S2 §3), so per wave root:
9
+ // an exposed transcript in use holds the whole root for the rest of the run; every other exposed one is PARKED.
10
+ //
11
+ // Parking is always in the FUTURE (now + 7 days + i ms): T3 skips transcripts with a future mtime (S2 §3), and a
12
+ // transcript is never given a past mtime, because Claude Code deletes transcripts older than cleanupPeriodDays
13
+ // (default 30) by mtime: a file parked in the past and left there by a crash could be deleted. Bumped files sit at
14
+ // (now - 2 s) + i ms, i.e. at most a few seconds before now.
15
+ //
16
+ // Clock jumps: T3 judges eligibility with ITS clock at import time. A machine that sleeps between the bump and an
17
+ // import call wakes with parked files closer to "now" (a week covers any single call). The guard starts at the wave's
18
+ // FIRST clock reading (before the exposure scan): a bump time outside [start - 2 s, start + CLOCK_JUMP_MS] defers the
19
+ // whole wave `clock-jump` before any utimes (what the scan judged "in the future" may be inside the window by then).
20
+ // After the bump the clock is checked before the scan and before every import call: more than CLOCK_JUMP_MS past the
21
+ // start, or more than 2 s earlier than the last reading, stops the wave there (restore as usual); its projects not yet
22
+ // imported are deferred `clock-jump`, and the next wave (or run) starts afresh with a new start.
23
+ //
24
+ // The caller MUST hold the state-dir lock and have run recoverPendingMtimes.
25
+
26
+ import { statSync, utimesSync } from "node:fs";
27
+ import { stat, utimes } from "node:fs/promises";
28
+
29
+
30
+ import { near } from "../core/journal.js";
31
+ import { statSafe } from "../core/fsutil.js";
32
+ import { pathKey as pathKeyOf } from "../core/paths.js";
33
+ import { ACTIVE_WINDOW_MS, CWD_SCAN_MAX_BYTES } from "../sources/types.js";
34
+ import { inImportWindow, isActive } from "../core/activity.js";
35
+ import { DEFAULT_BATCH } from "../core/config.js";
36
+
37
+ import { RpcError } from "../t3/errors.js";
38
+ import { WAVE_COST_CAP, buildWaves, bumpTargets, byOriginalMtime, itemRoot, rootKey, waveItems, } from "./waves.js";
39
+
40
+ export { IMPORT_WINDOW_MS } from "../core/activity.js";
41
+ /** Parked files sit this far in the future during their project's wave (T3 skips future mtimes). */
42
+ export const PARK_AHEAD_MS = 7 * 86_400_000;
43
+ /** A clock reading this far past a wave's bump time (a suspend, or the clock was set) stops that wave. */
44
+ export const CLOCK_JUMP_MS = 30 * 60_000;
45
+ /** A clock reading may be this much earlier than the previous one (time sync nudges) without stopping the wave. */
46
+ export const CLOCK_BACK_TOLERANCE_MS = 2_000;
47
+
48
+ /** A reading `t` is sane when it is not more than the tolerance before `last`, nor CLOCK_JUMP_MS past the wave's start. */
49
+ function clockWithin(t , last , start ) {
50
+ return t >= last - CLOCK_BACK_TOLERANCE_MS && t <= start + CLOCK_JUMP_MS;
51
+ }
52
+ /** An item missing after its wave is tried once more in a later wave, then reported. */
53
+ const MAX_ATTEMPTS = 2;
54
+ const PROJECT_MISMATCH_TAGS = new Set(["AgentSessionImportProjectChangedError", "AgentSessionImportProjectNotFoundError"]);
55
+
56
+
57
+ /**
58
+ * project-in-use: another transcript of the project is being written, so T3 would import it now; the root waits.
59
+ * clock-jump: the system clock jumped (suspend, time change) during the wave before its project was imported.
60
+ * file-busy: a transcript of the project stayed locked (EBUSY / EPERM / EACCES) through the retries; the root waits.
61
+ */
62
+
63
+
64
+ /** Error codes of a file another program holds open (antivirus, sync client, an editor) on Windows. */
65
+ const BUSY_CODES = new Set(["EBUSY", "EPERM", "EACCES"]);
66
+ export const isBusy = (e ) => BUSY_CODES.has((e )?.code ?? "");
67
+ /** Waits between tries of a busy file: tried once, then again after 100, 300 and 1000 ms. */
68
+ export const BUSY_RETRY_MS = [100, 300, 1000];
69
+
70
+ /** `fn`, retried while it fails with a busy-file error; the last error is thrown. */
71
+ export async function retryBusy (fn , delays = BUSY_RETRY_MS) {
72
+ for (let i = 0; ; i++) {
73
+ try {
74
+ return await fn();
75
+ } catch (e) {
76
+ if (!isBusy(e) || i >= delays.length) throw e;
77
+ await new Promise((r) => setTimeout(r, delays[i]));
78
+ }
79
+ }
80
+ }
81
+
82
+ /**
83
+ * A discovered transcript T3 could import into the project of its cwd (agentSessions.import takes EVERY in-window
84
+ * transcript of a root, from every instance; S2 §3): plan items of any action, mirror and backup copies, excluded ones.
85
+ * `threadIds` / `refs` (`<instanceId>:<nativeId>`) say how T3 would represent it; one present = already in T3.
86
+ */
87
+
88
+
89
+
90
+
91
+
92
+
93
+
94
+
95
+
96
+
97
+ /** A transcript parked for a wave: fresh stat, identity, and what it costs T3's metadata pass of its source. */
98
+
99
+ /** T3 budgets metadata per source (S2 §4): converted OpenCode sessions are Claude transcripts. */
100
+
101
+ export function sourceOf(h ) {
102
+ return h === "codex" || h === "pi" ? h : "claude";
103
+ }
104
+ /** The metadata source of an item's file: a convert-import's file is a Claude transcript, whatever its harness. */
105
+ function itemSource(it ) {
106
+ return it.action.kind === "convert-import" ? "claude" : it.session.harness;
107
+ }
108
+ /** What T3 reads of a file to find its cwd: never more than the file, never more than 1 MiB (S2 §4). */
109
+ function metadataCost(cost , size ) {
110
+ return Math.max(0, Math.min(cost ?? size, size, CWD_SCAN_MAX_BYTES));
111
+ }
112
+
113
+ /** The transcript that holds its project: being written (mtime within ACTIVE_WINDOW_MS of now). */
114
+
115
+
116
+
117
+
118
+
119
+
120
+
121
+
122
+
123
+
124
+
125
+
126
+
127
+
128
+
129
+ /** Static exposure (plan items of any action + `entries`) plus the optional wave-time listing `live` (new files). */
130
+ export function exposureIndex(o
131
+
132
+
133
+
134
+
135
+
136
+ ) {
137
+ const key = (r ) => rootKey(r, o.platform);
138
+ const pathKey = (p ) => pathKeyOf(p, o.platform);
139
+ const byPath = new Map ();
140
+ const add = (path , k , threadIds , refs , id , cost , harness ) => {
141
+ const pk = pathKey(path);
142
+ const c = byPath.get(pk) ?? { path, keys: new Set (), threadIds: [], refs: [], id: null, cost: null, harness: null };
143
+ c.keys.add(k);
144
+ c.threadIds.push(...threadIds);
145
+ c.refs.push(...refs);
146
+ c.id ??= id;
147
+ c.cost ??= cost;
148
+ c.harness ??= harness;
149
+ byPath.set(pk, c);
150
+ };
151
+ const idOf = (x ) =>
152
+ x.harness && x.nativeId && x.threadIds[0] ? { harness: x.harness, nativeId: x.nativeId, threadId: x.threadIds[0] } : null;
153
+ for (const x of o.entries) add(x.path, key(x.cwd), x.threadIds, x.refs, idOf(x), x.cost ?? null, x.harness ?? null);
154
+ for (const it of o.items) {
155
+ if (it.action.kind === "skip") continue;
156
+ const s = it.session;
157
+ const id = { harness: s.harness, nativeId: s.nativeId, threadId: it.action.expectedThreadId };
158
+ add(s.file.path, key(it.action.projectRoot), [it.action.expectedThreadId], [], id, s.cwdOffsetBytes, itemSource(it));
159
+ if (s.cwd) add(s.file.path, key(s.cwd), [], [], id, s.cwdOffsetBytes, itemSource(it));
160
+ }
161
+ return {
162
+ pathKey,
163
+ async scan(k, root, clock, exclude, wave) {
164
+ const cands = [...byPath.values()].filter((c) => c.keys.has(k));
165
+ for (const x of (await o.live?.(root, wave).catch(() => [])) ?? []) {
166
+ if (!byPath.has(pathKey(x.path))) cands.push({ path: x.path, keys: new Set([k]), threadIds: x.threadIds, refs: x.refs, id: idOf(x), cost: x.cost ?? null, harness: x.harness ?? null });
167
+ }
168
+ const park = [];
169
+ const seen = new Set ();
170
+ for (const c of cands) {
171
+ const pk = pathKey(c.path);
172
+ if (seen.has(pk) || exclude.has(pk) || o.inT3(c.threadIds, c.refs)) continue;
173
+ seen.add(pk);
174
+ let st ;
175
+ try {
176
+ st = await retryBusy(() => statSafe(c.path), o.busyRetryMs);
177
+ } catch (e) {
178
+ if (isBusy(e)) return { inUse: false, busy: true, park: [] }; // cannot tell where it is: hold the root
179
+ continue;
180
+ }
181
+ if (st === null) continue;
182
+ const t = clock(); // at stat time, never before the awaits
183
+ if (st.mtimeMs > t + ACTIVE_WINDOW_MS) continue; // parked (a leftover at +7 days): T3 skips it
184
+ if (!inImportWindow(st.mtimeMs, t)) continue; // outside the window: T3 cannot take it
185
+ if (isActive(st.mtimeMs, t)) return { inUse: true, active: { path: c.path, mtimeMs: st.mtimeMs, harness: c.harness }, park: [] }; // recent, or up to 10 min ahead
186
+ park.push({ st, id: c.id, cost: metadataCost(c.cost, st.size), source: sourceOf(c.harness) });
187
+ }
188
+ return { inUse: false, park };
189
+ },
190
+ };
191
+ }
192
+
193
+
194
+
195
+
196
+
197
+
198
+
199
+
200
+
201
+
202
+
203
+
204
+
205
+
206
+
207
+
208
+
209
+
210
+
211
+
212
+
213
+
214
+
215
+
216
+
217
+
218
+
219
+
220
+
221
+
222
+
223
+
224
+
225
+
226
+
227
+
228
+
229
+
230
+
231
+
232
+
233
+
234
+
235
+
236
+
237
+
238
+
239
+
240
+
241
+
242
+
243
+
244
+
245
+
246
+
247
+
248
+
249
+
250
+
251
+
252
+
253
+
254
+
255
+
256
+
257
+
258
+
259
+
260
+
261
+
262
+
263
+
264
+
265
+
266
+
267
+
268
+
269
+ /**
270
+ * Synchronous restore for a forced exit: puts back every file still at its bump target (same guard as the async
271
+ * restore: a file anywhere else was never bumped or was written meanwhile, and is left alone). Never throws. The
272
+ * journal stays the safety net: no mtime-restore is written here; the next run's recoverPendingMtimes finds these
273
+ * files at their originals and marks them restored.
274
+ */
275
+ export function restoreSync(files ) {
276
+ let n = 0;
277
+ for (const f of files) {
278
+ try {
279
+ if (!near(statSync(f.path).mtimeMs, f.targetMtimeMs)) continue;
280
+ utimesSync(f.path, f.atimeMs / 1000, f.mtimeMs / 1000);
281
+ n++;
282
+ } catch { /* left pending for recoverPendingMtimes */ }
283
+ }
284
+ return n;
285
+ }
286
+
287
+ function threadIdOf(i ) {
288
+ return i.action.kind === "skip" ? null : i.action.expectedThreadId;
289
+ }
290
+
291
+ function instanceOf(i ) {
292
+ return i.action.kind === "skip" ? null : i.action.instanceId;
293
+ }
294
+
295
+ /** The file is still exactly what the plan saw (size and mtime). */
296
+ function matchesPlan(st , it ) {
297
+ return st.size === it.session.file.size && near(st.mtimeMs, it.session.file.mtimeMs);
298
+ }
299
+
300
+ function inferBatch(waves ) {
301
+ let projectsPerWave = 0, filesPerProject = 0;
302
+ for (const w of waves) {
303
+ projectsPerWave = Math.max(projectsPerWave, w.projects.length);
304
+ for (const p of w.projects) filesPerProject = Math.max(filesPerProject, p.items.length);
305
+ }
306
+ return { filesPerProject: filesPerProject || DEFAULT_BATCH.filesPerProject, projectsPerWave: projectsPerWave || DEFAULT_BATCH.projectsPerWave };
307
+ }
308
+
309
+ const errText = (e ) => (e instanceof Error ? e.message : String(e));
310
+
311
+ /**
312
+ * Put every file back where the journal says it was. Never throws for a single file; returns the paths that are
313
+ * resolved (restored, gone, never moved, or modified by someone else meanwhile) and the errors (left pending for
314
+ * recoverPendingMtimes).
315
+ */
316
+ async function restoreAll(
317
+ files , setTimes , statFn , skipped ,
318
+ busyRetryMs ,
319
+ ) {
320
+ const resolved = [];
321
+ const errors = [];
322
+ for (const f of files) {
323
+ // Never bumped (written to or gone before its utimes) and already journaled restored: never touched, even if a
324
+ // coarse-timestamp filesystem makes its fresh mtime look like the target.
325
+ if (skipped.has(f.path)) continue;
326
+ try {
327
+ let cur ;
328
+ try {
329
+ cur = await retryBusy(() => statFn(f.path), busyRetryMs);
330
+ } catch (e) {
331
+ if ((e ).code !== "ENOENT") throw e;
332
+ cur = null;
333
+ }
334
+ // Still at our target: put it back. Anywhere else: either our utimes never ran (it is at its original) or
335
+ // someone wrote to it during the wave (it is newer); never move it backwards.
336
+ if (cur !== null && near(cur.mtimeMs, f.targetMtimeMs)) await retryBusy(() => setTimes(f.path, f.atimeMs / 1000, f.mtimeMs / 1000), busyRetryMs);
337
+ resolved.push(f.path);
338
+ } catch (e) {
339
+ if ((e ).code === "ENOENT") resolved.push(f.path);
340
+ else errors.push({ path: f.path, error: errText(e) });
341
+ }
342
+ }
343
+ return { resolved, errors };
344
+ }
345
+
346
+ /**
347
+ * Runs the waves. Every item is bumped only in its own wave; the next wave is always rebuilt from what is still
348
+ * pending (retries included), in ascending ORIGINAL mtime, so T3's thread order (updatedAt = bump time) follows the
349
+ * original order. Termination: each item is attempted at most MAX_ATTEMPTS times, so the loop ends when every
350
+ * expected thread id is present or a pass brings no progress for the rest.
351
+ */
352
+ export async function runWaves(ctx , waves ) {
353
+ const platform = ctx.platform ?? process.platform;
354
+ const key = (r ) => rootKey(r, platform);
355
+ const cost = ctx.cost ?? ((i ) => i.session.cwdOffsetBytes);
356
+ const batch = ctx.batch ?? inferBatch(waves);
357
+ const aborted = () => ctx.aborted?.() ?? false;
358
+ const setTimes = ctx.utimes ?? utimes;
359
+ const projectId = new Map ();
360
+ for (const [r, id] of ctx.projectIds) projectId.set(key(r), id);
361
+
362
+ const all = waves.flatMap(waveItems).filter((i) => threadIdOf(i) !== null).sort(byOriginalMtime);
363
+ const res = { imported: [], failed: [], deferred: [], restoreErrors: [], unverified: [], stoppedUnverified: false, aborted: false, waves: 0, heldRoots: [], heldActive: [], clockJumps: 0, parked: 0 };
364
+ const statFn = ctx.stat ?? stat;
365
+ /** Imported or failed: T3 will not take these in a later wave. */
366
+ const settled = new Set ();
367
+ /** Settled this run: imported, failed or deferred. Never bumped or parked again. */
368
+ const done = new Set ();
369
+ const attempts = new Map ();
370
+ const mismatch = new Set ();
371
+
372
+ const markImported = async (it , src ) => {
373
+ done.add(it);
374
+ settled.add(it);
375
+ res.imported.push(it);
376
+ await ctx.journal.append({
377
+ t: "imported", runId: ctx.runId, harness: it.session.harness, nativeId: it.session.nativeId, threadId: threadIdOf(it) ,
378
+ source: { path: src.path, size: src.size, mtimeMs: src.mtimeMs },
379
+ });
380
+ };
381
+ const reasonFor = (it ) => {
382
+ if (it.session.cwdOffsetBytes > CWD_SCAN_MAX_BYTES) return "cwd-unreadable-in-t3";
383
+ const inst = instanceOf(it);
384
+ if (inst !== null && ctx.instanceAvailability?.get(inst) === "unavailable") return "instance-unavailable";
385
+ if (mismatch.has(key(itemRoot(it)))) return "project-mismatch";
386
+ return "not-imported";
387
+ };
388
+ const markFailed = async (it , reason ) => {
389
+ done.add(it);
390
+ settled.add(it);
391
+ res.failed.push({ item: it, reason });
392
+ await ctx.journal.append({ t: "import-failed", runId: ctx.runId, harness: it.session.harness, nativeId: it.session.nativeId, reason });
393
+ };
394
+
395
+ let refs = new Set ();
396
+ const readThreads = (list ) => {
397
+ refs = new Set(list.flatMap((t) => (t.nativeSessionId ? [`${t.instanceId}:${t.nativeSessionId}`] : [])));
398
+ return new Set(list.map((t) => t.id));
399
+ };
400
+ let threads = readThreads(await ctx.api.listThreads());
401
+ const exposure = exposureIndex({
402
+ entries: ctx.exposure ?? [], items: all, platform, live: ctx.liveExposure?.bind(ctx), busyRetryMs: ctx.busyRetryMs,
403
+ inT3: (ids, rs) => ids.some((id) => threads.has(id)) || rs.some((r) => refs.has(r)),
404
+ });
405
+ /** Held once = held for the rest of the run (a project in use now is still in use a wave later). */
406
+ const heldForRun = new Set (ctx.heldRoots ?? []);
407
+ /** Why a root is held when it is not "project-in-use" (a busy file). */
408
+ const heldWhy = new Map ();
409
+ const holdBusy = (k ) => { heldForRun.add(k); heldWhy.set(k, "file-busy"); };
410
+ const holdRoot = (it ) => {
411
+ const r = itemRoot(it);
412
+ if (!res.heldRoots.some((x) => key(x) === key(r))) res.heldRoots.push(r);
413
+ };
414
+ const deferHeld = (it ) => {
415
+ const why = heldWhy.get(key(itemRoot(it))) ?? "project-in-use";
416
+ done.add(it);
417
+ res.deferred.push({ item: it, reason: why });
418
+ if (why === "project-in-use") holdRoot(it);
419
+ };
420
+ // T3 reads a cwd only within the first 1 MiB of a transcript (S2 §4): such a session can never be imported, so it
421
+ // fails up front instead of spending two waves. (The planner already skips them; this is the defensive path.)
422
+ for (const it of all) {
423
+ if (threads.has(threadIdOf(it) ) || it.session.cwdOffsetBytes <= CWD_SCAN_MAX_BYTES) continue;
424
+ await markFailed(it, "cwd-unreadable-in-t3");
425
+ }
426
+ let pool = all.filter((i) => !done.has(i));
427
+
428
+ while (pool.length > 0) {
429
+ if (aborted()) { res.aborted = true; break; }
430
+ // Imported meanwhile (e.g. a natural in-window side effect of an earlier wave): never bump again (S2 §5).
431
+ for (const it of pool) {
432
+ if (!threads.has(threadIdOf(it) )) continue;
433
+ const st = await retryBusy(() => statSafe(it.session.file.path), ctx.busyRetryMs).catch(() => null);
434
+ await markImported(it, st ?? it.session.file);
435
+ }
436
+ for (const it of pool) if (!done.has(it) && !projectId.has(key(itemRoot(it)))) await markFailed(it, "project-mismatch");
437
+ pool = pool.filter((i) => !done.has(i));
438
+ if (pool.length === 0) break;
439
+
440
+ const candidates = waveItems(buildWaves(pool, batch, cost, { platform })[0] );
441
+ const inWave = new Set(candidates);
442
+ pool = pool.filter((i) => !inWave.has(i));
443
+
444
+ // Re-stat at bump time: anything in use, changed or gone since planning is left alone this run.
445
+ // This first reading starts the wave's clock guard: the exposure scan and the bump are judged against it.
446
+ const now = ctx.now();
447
+ const waveStart = now;
448
+ const ready = [];
449
+ let deferredNow = 0;
450
+ for (const it of candidates) {
451
+ if (heldForRun.has(key(itemRoot(it)))) { deferHeld(it); deferredNow++; continue; }
452
+ let st ;
453
+ try {
454
+ st = await retryBusy(() => statSafe(it.session.file.path), ctx.busyRetryMs);
455
+ } catch (e) {
456
+ if (!isBusy(e)) throw e;
457
+ holdBusy(key(itemRoot(it))); deferHeld(it); deferredNow++; continue;
458
+ }
459
+ const reason = st === null ? "missing"
460
+ : isActive(st.mtimeMs, now) ? "active"
461
+ : !matchesPlan(st, it) ? "changed" : null;
462
+ if (reason !== null) { done.add(it); res.deferred.push({ item: it, reason }); deferredNow++; continue; }
463
+ ready.push({ item: it, st: st });
464
+ }
465
+ if (ready.length === 0) continue;
466
+
467
+ // T3 imports every in-window transcript of a project, from every instance (S2 §3). Per wave root, the EXPOSED set
468
+ // is every transcript of that root (discovered, or listed now: created after planning) inside the window, not in
469
+ // the future and not already in T3. One of them in use: T3 would import it now (live mtime, maybe half-written),
470
+ // so the root is held for the rest of the run. Otherwise every exposed one that is not imported in this wave
471
+ // (mirror and backup copies, excluded ones, duplicates, later waves, new files) is parked in the future.
472
+ const readyKeys = new Set(ready.map((r) => exposure.pathKey(r.st.path)));
473
+ const waveRoots = new Map ();
474
+ for (const r of ready) waveRoots.set(key(itemRoot(r.item)), itemRoot(r.item));
475
+ const parkedOf = new Map ();
476
+ for (const [k, root] of waveRoots) {
477
+ const s = await exposure.scan(k, root, () => ctx.now(), readyKeys, res.waves + 1);
478
+ if (s.busy) holdBusy(k);
479
+ else if (s.inUse) {
480
+ heldForRun.add(k);
481
+ if (s.active) res.heldActive.push({ root, file: s.active });
482
+ }
483
+ else parkedOf.set(k, s.park);
484
+ }
485
+ if (ready.some((r) => heldForRun.has(key(itemRoot(r.item))))) {
486
+ for (const r of ready) {
487
+ if (!heldForRun.has(key(itemRoot(r.item)))) continue;
488
+ deferHeld(r.item);
489
+ deferredNow++;
490
+ }
491
+ ready.splice(0, ready.length, ...ready.filter((r) => !heldForRun.has(key(itemRoot(r.item)))));
492
+ // a parked file of a held root (two roots can share a file only through remap) stays parked: harmless
493
+ }
494
+ if (ready.length === 0) continue;
495
+
496
+ // Metadata budget (S2 §4): T3 reads metadata newest first, so parked files (future mtime) are read BEFORE the
497
+ // bumped ones and spend the same per-source 64 MiB. Roots join the wave in order (oldest item first) while every
498
+ // source's bumped + parked cost stays within WAVE_COST_CAP; the next root waits for a later wave (its items go
499
+ // back to the pool, untouched). The first root always goes, alone and with a warning when it alone is over.
500
+ const spent = new Map ();
501
+ const parkedSeen = new Set ();
502
+ const keep = new Set ();
503
+ for (const k of [...new Set(ready.map((r) => key(itemRoot(r.item))))]) {
504
+ const add = new Map ();
505
+ const plus = (src , n ) => void add.set(src, (add.get(src) ?? 0) + n);
506
+ for (const r of ready) if (key(itemRoot(r.item)) === k) plus(sourceOf(itemSource(r.item)), metadataCost(cost(r.item), r.st.size));
507
+ for (const p of parkedOf.get(k) ?? []) if (!parkedSeen.has(exposure.pathKey(p.st.path))) plus(p.source, p.cost);
508
+ const over = [...add].some(([src, n]) => (spent.get(src) ?? 0) + n > WAVE_COST_CAP);
509
+ if (over && keep.size > 0) break;
510
+ keep.add(k);
511
+ for (const [src, n] of add) spent.set(src, (spent.get(src) ?? 0) + n);
512
+ for (const p of parkedOf.get(k) ?? []) parkedSeen.add(exposure.pathKey(p.st.path));
513
+ if (over) {
514
+ const mib = (n ) => (n / 1024 / 1024).toFixed(1);
515
+ const worst = Math.max(...spent.values());
516
+ ctx.onNotice?.(`Warning: ${itemRoot(ready.find((r) => key(itemRoot(r.item)) === k) .item)}: its sessions and the copies parked while it imports cost ${mib(worst)} MiB of T3 Code's 64 MiB read budget; some may not be imported this run (they are retried once, then reported).`);
517
+ break;
518
+ }
519
+ }
520
+ if (keep.size < new Set(ready.map((r) => key(itemRoot(r.item)))).size) {
521
+ for (const r of ready) if (!keep.has(key(itemRoot(r.item)))) pool.push(r.item); // a later wave, re-stat'ed then
522
+ pool.sort(byOriginalMtime);
523
+ ready.splice(0, ready.length, ...ready.filter((r) => keep.has(key(itemRoot(r.item)))));
524
+ }
525
+ const parkedByPath = new Map ();
526
+ for (const k of keep) for (const p of parkedOf.get(k) ?? []) parkedByPath.set(exposure.pathKey(p.st.path), p);
527
+ const parked = [...parkedByPath.values()];
528
+
529
+ // `now` is re-read immediately before bumping. Bumped: (now - 2 s) + i ms, asserted in the past (bumpTargets).
530
+ // Parked: now + 7 days + i ms, asserted in the future (never a past mtime: Claude Code's cleanup deletes by mtime).
531
+ const bumpNow = ctx.now();
532
+ if (!clockWithin(bumpNow, waveStart, waveStart)) {
533
+ // The clock jumped since the wave's first reading: what the exposure scan saw in the future (or outside the
534
+ // window) may be inside it now. Nothing is touched; the wave's items wait for the next run.
535
+ res.clockJumps++;
536
+ for (const r of ready) { done.add(r.item); res.deferred.push({ item: r.item, reason: "clock-jump" }); }
537
+ continue;
538
+ }
539
+ const targets = bumpTargets(ready.length, bumpNow);
540
+ const parkTargets = parked.map((_, i) => Math.floor(bumpNow) + PARK_AHEAD_MS + i);
541
+ if (parkTargets.some((t) => !(t > bumpNow))) throw new Error("internal: a park target must lie in the future");
542
+ const files = [
543
+ ...ready.map((r, i) => ({ path: r.st.path, atimeMs: r.st.atimeMs, mtimeMs: r.st.mtimeMs, targetMtimeMs: targets[i] })),
544
+ ...parked.map((o, i) => ({ path: o.st.path, atimeMs: o.st.atimeMs, mtimeMs: o.st.mtimeMs, targetMtimeMs: parkTargets[i] })),
545
+ ];
546
+ const identityOf = new Map ();
547
+ for (const r of ready) identityOf.set(r.st.path, { harness: r.item.session.harness, nativeId: r.item.session.nativeId, threadId: threadIdOf(r.item) });
548
+ for (const p of parked) if (p.id) identityOf.set(p.st.path, p.id);
549
+ const projects = [];
550
+ for (const r of ready) {
551
+ const k = key(itemRoot(r.item));
552
+ if (!projects.some((p) => p.k === k)) projects.push({ k, root: ctx.importRoots?.get(k) ?? itemRoot(r.item), id: projectId.get(k) });
553
+ }
554
+ res.waves++;
555
+ res.parked += parked.length;
556
+
557
+ const sizeOf = new Map ([...ready, ...parked].map((x) => [x.st.path, x.st.size]));
558
+ /** The wave roots each file belongs to (a busy file holds all of them). */
559
+ const rootsOfPath = new Map ();
560
+ const addRoot = (path , k ) => {
561
+ const set = rootsOfPath.get(path) ?? new Set ();
562
+ set.add(k);
563
+ rootsOfPath.set(path, set);
564
+ };
565
+ for (const r of ready) addRoot(r.st.path, key(itemRoot(r.item)));
566
+ for (const k of keep) for (const p of parkedOf.get(k) ?? []) addRoot(p.st.path, k);
567
+ /** Roots of this wave not imported because one of their files stayed busy. */
568
+ const busyNow = new Set ();
569
+ /** Written to (or gone) between the re-stat and its own utimes: never bumped, left as the writer left it. */
570
+ const skipped = new Map ();
571
+ let skippedJournaled = false;
572
+ // The skipped paths were never changed by us: journal them restored at once, so neither this wave's restore nor a
573
+ // crash recovery can ever "restore" them (a coarse-timestamp fs could show their fresh mtime as the target).
574
+ const journalSkipped = async () => {
575
+ if (skippedJournaled) return;
576
+ skippedJournaled = true;
577
+ if (skipped.size > 0) {
578
+ await ctx.journal.append({ t: "mtime-restore", runId: ctx.runId, paths: [...skipped.keys()] });
579
+ // A file written under us could not be parked: it sits in the window with its live mtime, so T3 may import it
580
+ // in this wave. Name it in a follow-up import-attempt (rollback finds its thread). Bumped ready items that
581
+ // were skipped are already in the first entry.
582
+ const extra = [...skipped].filter(([p, why]) => why !== "file-busy" && !ready.some((r) => r.st.path === p)).map(([p]) => identityOf.get(p)).filter((x) => !!x);
583
+ if (extra.length > 0) await ctx.journal.append({ t: "import-attempt", runId: ctx.runId, items: extra });
584
+ }
585
+ ctx.onPendingFiles?.(files.filter((f) => !skipped.has(f.path)));
586
+ };
587
+
588
+ await ctx.journal.append({ t: "mtime-bump", runId: ctx.runId, files }); // before any utimes
589
+ // Before the import calls: every thread this wave may create (nothing else of its projects is importable now: the
590
+ // rest is parked or the root is held), so a rollback finds them even if verification never happens.
591
+ // `parked`: the copies parked for this wave (never meant to be imported; a rollback lists them for review only).
592
+ await ctx.journal.append({
593
+ t: "import-attempt", runId: ctx.runId,
594
+ items: ready.map(({ item: it, st }) => ({
595
+ harness: it.session.harness, nativeId: it.session.nativeId, threadId: threadIdOf(it) , source: { path: st.path, size: st.size, mtimeMs: st.mtimeMs },
596
+ })),
597
+ parked: parked.flatMap((p) => (p.id ? [p.id] : [])),
598
+ });
599
+ ctx.onPendingFiles?.(files);
600
+ // Every clock reading of this wave must stay within [the last reading - CLOCK_BACK_TOLERANCE_MS, waveStart + CLOCK_JUMP_MS].
601
+ let lastClock = bumpNow;
602
+ let clockJump = false;
603
+ const clockOk = () => {
604
+ const t = ctx.now();
605
+ if (!clockWithin(t, lastClock, waveStart)) { clockJump = true; return false; }
606
+ lastClock = Math.max(lastClock, t);
607
+ return true;
608
+ };
609
+ /** Roots whose import call was made in this wave. */
610
+ const called = new Set ();
611
+ try {
612
+ // A file that stays busy is left as it is and holds every root it belongs to (none is imported this run: a copy
613
+ // that could not be parked would be imported under its own account).
614
+ const busy = (path ) => {
615
+ skipped.set(path, "file-busy");
616
+ for (const k of rootsOfPath.get(path) ?? []) { busyNow.add(k); holdBusy(k); }
617
+ };
618
+ for (const f of files) {
619
+ // Close the stat->utimes race: a file written since the re-stat keeps its fresh mtime.
620
+ let cur ;
621
+ try { cur = await retryBusy(() => statFn(f.path), ctx.busyRetryMs); } catch (e) {
622
+ if (isBusy(e)) busy(f.path);
623
+ else skipped.set(f.path, (e ).code === "ENOENT" ? "missing" : "changed");
624
+ continue;
625
+ }
626
+ if (cur.size !== sizeOf.get(f.path) || cur.mtimeMs !== f.mtimeMs) { skipped.set(f.path, "changed"); continue; }
627
+ try {
628
+ await retryBusy(() => setTimes(f.path, f.atimeMs / 1000, f.targetMtimeMs / 1000), ctx.busyRetryMs);
629
+ } catch (e) {
630
+ if (!isBusy(e)) throw e;
631
+ busy(f.path);
632
+ }
633
+ }
634
+ await journalSkipped();
635
+ if (!aborted() && clockOk()) {
636
+ await ctx.api.scanSessions(); // mandatory: import only sees mtimes from the last scan (S2 §2.1)
637
+ for (const p of projects) {
638
+ if (busyNow.has(p.k)) continue; // a file of it stayed busy: nothing of it is imported this run
639
+ if (aborted() || !clockOk()) break;
640
+ called.add(p.k);
641
+ try {
642
+ await ctx.api.importSessions(p.id, p.root);
643
+ } catch (e) {
644
+ if (e instanceof RpcError && e.errorTag !== null && PROJECT_MISMATCH_TAGS.has(e.errorTag)) mismatch.add(p.k);
645
+ else throw e;
646
+ }
647
+ }
648
+ }
649
+ } finally {
650
+ await journalSkipped(); // the bump loop threw: still record the skipped ones before restoring the rest
651
+ const r = await restoreAll(files, setTimes, statFn, new Set(skipped.keys()), ctx.busyRetryMs);
652
+ res.restoreErrors.push(...r.errors);
653
+ if (r.resolved.length > 0) await ctx.journal.append({ t: "mtime-restore", runId: ctx.runId, paths: r.resolved });
654
+ ctx.onPendingFiles?.(null);
655
+ }
656
+
657
+ // Verify against the shell: the only success signal (importedCount is not "new threads", S2 §2.2). One retry;
658
+ // if the shell stays unreachable the wave's items end unverified (reported; the import-attempt entry names them).
659
+ let shell = null;
660
+ for (let k = 0; k < 2 && shell === null; k++) {
661
+ try { shell = readThreads(await ctx.api.listThreads()); } catch { /* retried once */ }
662
+ }
663
+ let importedNow = 0, retry = 0, failedNow = 0;
664
+ const stopped = aborted();
665
+ if (clockJump) res.clockJumps++;
666
+ if (shell === null) {
667
+ // T3's thread list is unreachable: stop here. Starting more waves could not be verified either.
668
+ for (const { item } of ready) { done.add(item); res.unverified.push(item); }
669
+ res.stoppedUnverified = true;
670
+ } else threads = shell;
671
+ for (const { item, st } of shell === null ? [] : ready) {
672
+ if (threads.has(threadIdOf(item) )) {
673
+ await markImported(item, skipped.has(st.path) ? (await statSafe(st.path)) ?? st : st);
674
+ importedNow++;
675
+ continue;
676
+ }
677
+ const why = skipped.get(st.path);
678
+ if (why !== undefined) { done.add(item); res.deferred.push({ item, reason: why }); deferredNow++; continue; } // never bumped
679
+ if (busyNow.has(key(itemRoot(item)))) { done.add(item); res.deferred.push({ item, reason: "file-busy" }); deferredNow++; continue; }
680
+ if (clockJump && !called.has(key(itemRoot(item)))) { done.add(item); res.deferred.push({ item, reason: "clock-jump" }); deferredNow++; continue; }
681
+ if (stopped) continue; // not attempted to the end: neither a failure nor a retry
682
+ const n = (attempts.get(item) ?? 0) + 1;
683
+ attempts.set(item, n);
684
+ if (n < MAX_ATTEMPTS) { pool.push(item); retry++; }
685
+ else { await markFailed(item, reasonFor(item)); failedNow++; }
686
+ }
687
+ pool.sort(byOriginalMtime);
688
+ const remaining = pool.length > 0 ? buildWaves(pool, batch, cost, { platform }).length : 0;
689
+ ctx.onProgress({
690
+ wave: res.waves, totalWaves: res.waves + remaining, projects: projects.length, sessions: ready.length,
691
+ imported: importedNow, retry, failed: failedNow, deferred: deferredNow,
692
+ });
693
+ if (stopped) { res.aborted = true; break; }
694
+ if (res.stoppedUnverified) break;
695
+ }
696
+ return res;
697
+ }