t3code-session-manager 0.0.0-stage → 0.4.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 (172) hide show
  1. package/.claude-plugin/marketplace.json +21 -0
  2. package/.claude-plugin/plugin.json +19 -0
  3. package/CHANGELOG.md +149 -0
  4. package/LICENSE +21 -0
  5. package/README.md +661 -2
  6. package/README.pt.md +617 -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,830 @@
1
+ // Merge revisions (spec §4.6, docs/spikes/S3-conversion.md §6, docs/spikes/S5-merge.md): bring work continued in a
2
+ // terminal (`claude --resume`) into T3 Code. T3 continues an imported thread from the last record IT wrote, so terminal
3
+ // turns end up on a side branch T3 never shows. A merge writes a linear "revision" transcript of the branch
4
+ // `claude --resume` would continue, imports it as a NEW thread, and only then archives the old thread.
5
+ //
6
+ // Rules:
7
+ // - the original transcript is NEVER modified; the revision is a new file `<same dir>/<revisionUuid>.jsonl`
8
+ // (revisionUuid = uuidV5("rev:<nativeId>:<size>")), never written over a file t3sm did not write, journaled
9
+ // (`file-written` with `revisionOf`) before it is published, published without clobbering (link), given the
10
+ // source's mtime. Its bytes depend only on the source (the provenance date is the source's mtime);
11
+ // - the import goes through runWaves (bump / park / restore, exposure, held projects): a project with another
12
+ // transcript in use defers the merge ("project-in-use");
13
+ // - only after the new thread is confirmed in T3's thread list (unarchived first if a rolled-back merge left it
14
+ // archived): archiveThread(old), journal `thread-archived`, then `merged`. A failed or deferred import deletes the
15
+ // revision (while it is still exactly what t3sm wrote) and leaves the old thread alone; only the failure is
16
+ // journaled (runWaves' import-failed);
17
+ // - transcripts are streamed (two passes: an index of byte offsets, then the chain records read back by offset), so
18
+ // a transcript over 32 MiB never sits in memory; verdicts are cached by (path, size, mtime, baseline).
19
+ //
20
+ // Branch and leaf (S3 §6, measured): nodes = records with a uuid, any type, not isSidechain. Leaf = the record named by
21
+ // the newest `last-prompt.leafUuid` that resolves, else the last node in file order. Chain = walk parentUuid from the
22
+ // leaf to the root. A revision is written only from a whole chain: a root whose parent is set but unknown, a cycle, or a
23
+ // corrupt line inside the chain's byte range -> skipped (`broken-chain` / `corrupt-lines`), never a truncated revision.
24
+ // A chain that crosses a compaction (`compact_boundary`, or a record with `logicalParentUuid`) -> `compacted`: merging
25
+ // compacted sessions is not supported yet. The revision holds a provenance record (isMeta user, parentUuid null) and
26
+ // then the chain root->leaf with `sessionId` rewritten and the chain root's `parentUuid` pointed at the provenance
27
+ // record; uuids and everything else are kept. Records without a uuid (last-prompt, summary, custom-title, ...) are not
28
+ // carried: none is needed to resume, and a copied last-prompt would redirect the revision's own resume.
29
+ //
30
+ // "Continued outside T3" needs POSITIVE evidence (controller ruling R1): after the baseline (the size t3sm imported, or
31
+ // the size of the last merge), a visible message record (user/assistant; not isMeta, isSidechain, isCompactSummary,
32
+ // isVisibleInTranscriptOnly) on the branch `claude --resume` continues, whose `entrypoint` is a string other than
33
+ // "t3-code". A record without an entrypoint is not evidence. If T3 evidently wrote since the baseline (the thread's
34
+ // latestUserMessageAt is newer than the baseline file's mtime) but no record after the baseline carries "t3-code",
35
+ // T3's marker may have changed: `no-t3-marker`, never merged. Sessions t3sm did not import have no baseline: never
36
+ // candidates.
37
+
38
+ import { createReadStream } from "node:fs";
39
+ import { link, mkdir, open, readFile, rm, unlink, utimes } from "node:fs/promises";
40
+ import { createHash } from "node:crypto";
41
+ import path from "node:path";
42
+
43
+
44
+ import { effectiveWrites, importedIndex, near } from "../core/journal.js";
45
+ import { revisionUuid, uuidV5 } from "../core/uuid.js";
46
+ import { MoveRefused, atomicWrite, publishNoClobber, sha256File, statSafe, sweepWriteTemps, writeTempPath, } from "../core/fsutil.js";
47
+ import { pathKey } from "../core/paths.js";
48
+ import { DEFAULT_BATCH } from "../core/config.js";
49
+ import { isActive } from "../core/activity.js";
50
+
51
+ import { exposureOf, liveExposure } from "../apply/apply.js";
52
+ import { runWaves, } from "../apply/importer.js";
53
+ import { buildWaves, rootKey } from "../apply/waves.js";
54
+ import { WRITTEN_MAX_AGE_MS, writtenMtime } from "../apply/materialize.js";
55
+ import { JournalWriteError } from "./quarantine.js";
56
+
57
+ export { revisionUuid };
58
+
59
+ /** sync merges at most this many sessions per cycle. */
60
+ export const MERGES_PER_CYCLE = 20;
61
+ const T3_ENTRYPOINT = "t3-code";
62
+
63
+ // unsettled: an unreadable line after the chain (a record being written, or a torn tail): skipped this run, like active.
64
+
65
+
66
+
67
+
68
+
69
+
70
+
71
+
72
+
73
+
74
+
75
+
76
+
77
+
78
+
79
+
80
+
81
+
82
+
83
+
84
+ // interrupted (Ctrl+C) before this session was merged
85
+
86
+ /** Waiting on something else (counted as merge-deferred by sync); "active" is the user's own session, not counted. */
87
+ export const DEFERRED_REASONS = new Set(["project-in-use", "over-cap", "clock-jump", "file-busy", "aborted"]);
88
+ /** Failures worth an exit code 5. */
89
+ export const FAILED_REASONS = new Set(["copy-failed", "import-failed", "import-unverified", "archive-failed"]);
90
+
91
+ // ---------------- reading the branch ----------------
92
+
93
+
94
+
95
+
96
+
97
+
98
+
99
+
100
+
101
+
102
+
103
+
104
+
105
+
106
+
107
+
108
+
109
+
110
+
111
+
112
+
113
+
114
+
115
+
116
+
117
+
118
+
119
+
120
+
121
+
122
+
123
+
124
+
125
+
126
+
127
+
128
+ /** Every line of a file with its byte offset, streamed (a line is held only while it is yielded). */
129
+ async function* fileLines(file ) {
130
+ const s = createReadStream(file, { highWaterMark: 1 << 20 });
131
+ let pending = [];
132
+ let pendingLen = 0;
133
+ let start = 0;
134
+ for await (const chunk of s ) {
135
+ let from = 0;
136
+ for (;;) {
137
+ const nl = chunk.indexOf(0x0a, from);
138
+ if (nl === -1) {
139
+ if (from < chunk.length) { pending.push(chunk.subarray(from)); pendingLen += chunk.length - from; }
140
+ break;
141
+ }
142
+ const part = chunk.subarray(from, nl + 1);
143
+ const buf = pendingLen > 0 ? Buffer.concat([...pending, part]) : part;
144
+ yield { offset: start, buf };
145
+ start += buf.length;
146
+ pending = [];
147
+ pendingLen = 0;
148
+ from = nl + 1;
149
+ }
150
+ }
151
+ if (pendingLen > 0) yield { offset: start, buf: Buffer.concat(pending) };
152
+ }
153
+
154
+ function parseLine(buf , offset ) {
155
+ let text = buf.toString("utf8");
156
+ if (offset === 0 && text.charCodeAt(0) === 0xfeff) text = text.slice(1);
157
+ text = text.replace(/\r?\n$/, "");
158
+ if (text.trim() === "") return null;
159
+ try {
160
+ const v = JSON.parse(text);
161
+ return typeof v === "object" && v !== null && !Array.isArray(v) ? (v ) : null;
162
+ } catch {
163
+ return null;
164
+ }
165
+ }
166
+
167
+ /**
168
+ * The branch `claude --resume` would continue (S3 §6), whether it can be copied whole, and the positive evidence of
169
+ * terminal work on it after `importedSize` (the baseline: the transcript's size when t3sm imported or last merged it).
170
+ */
171
+ export async function readBranch(file , opts = {}) {
172
+ const nodes = new Map ();
173
+ const lastPrompts = [];
174
+ const corruptAt = [];
175
+ let lastNode = null;
176
+ let t3MarkerAfter = false;
177
+ const baseline = opts.importedSize ?? 0;
178
+ for await (const { offset, buf } of fileLines(file)) {
179
+ const o = parseLine(buf, offset);
180
+ if (o === null) {
181
+ if (buf.toString("utf8").trim() !== "") corruptAt.push(offset);
182
+ continue;
183
+ }
184
+ if (offset >= baseline && o.entrypoint === T3_ENTRYPOINT) t3MarkerAfter = true;
185
+ if (o.type === "last-prompt") {
186
+ if (typeof o.leafUuid === "string" && o.leafUuid !== "") lastPrompts.push(o.leafUuid);
187
+ continue; // never a node
188
+ }
189
+ if (typeof o.uuid !== "string" || o.uuid === "" || o.isSidechain === true) continue;
190
+ if (!nodes.has(o.uuid)) {
191
+ const type = typeof o.type === "string" ? o.type : "";
192
+ nodes.set(o.uuid, {
193
+ uuid: o.uuid, parent: typeof o.parentUuid === "string" && o.parentUuid !== "" ? o.parentUuid : null, type,
194
+ visible: (type === "user" || type === "assistant") && o.isMeta !== true && o.isCompactSummary !== true && o.isVisibleInTranscriptOnly !== true,
195
+ compact: o.subtype === "compact_boundary" || (typeof o.logicalParentUuid === "string" && o.logicalParentUuid !== ""),
196
+ entrypoint: typeof o.entrypoint === "string" ? o.entrypoint : null,
197
+ offset, length: buf.length,
198
+ timestamp: typeof o.timestamp === "string" ? o.timestamp : null, cwd: typeof o.cwd === "string" ? o.cwd : null,
199
+ });
200
+ }
201
+ lastNode = o.uuid;
202
+ }
203
+
204
+ const res = {
205
+ leaf: null, leafSource: null, chain: [], problem: null, addedMessages: 0, t3MarkerAfter, divergedLeaves: 0, orphanedTerminal: 0, lastActivity: null,
206
+ corruptLines: corruptAt.length,
207
+ };
208
+ // The newest last-prompt whose leafUuid resolves wins; an unresolvable newer one does not hide an older valid one.
209
+ let fromPrompt = null;
210
+ for (let i = lastPrompts.length - 1; i >= 0 && fromPrompt === null; i--) if (nodes.has(lastPrompts[i] )) fromPrompt = lastPrompts[i] ;
211
+ const leaf = fromPrompt ?? lastNode;
212
+ if (leaf === null) return res;
213
+ res.leaf = leaf;
214
+ res.leafSource = fromPrompt !== null ? "last-prompt" : "file-order";
215
+
216
+ const chain = [];
217
+ const seen = new Set ();
218
+ let id = leaf;
219
+ while (id !== null) {
220
+ if (seen.has(id)) { res.problem = "broken-chain"; break; } // cycle
221
+ const n = nodes.get(id);
222
+ if (!n) { res.problem = "broken-chain"; break; } // a parent that is not in the file
223
+ seen.add(id);
224
+ chain.push(n);
225
+ id = n.parent;
226
+ }
227
+ res.chain = chain.reverse();
228
+ if (res.problem === null && res.chain.some((n) => n.compact)) res.problem = "compacted";
229
+ if (res.problem === null && corruptAt.length > 0) {
230
+ const lo = Math.min(...res.chain.map((n) => n.offset));
231
+ const hi = Math.max(...res.chain.map((n) => n.offset + n.length));
232
+ if (corruptAt.some((o) => o >= lo && o < hi)) res.problem = "corrupt-lines";
233
+ else if (corruptAt.some((o) => o >= hi)) res.problem = "unsettled";
234
+ }
235
+ const onChain = new Set(res.chain.map((n) => n.uuid));
236
+ res.addedMessages = res.chain.filter((n) => n.visible && n.offset >= baseline && n.entrypoint !== null && n.entrypoint !== T3_ENTRYPOINT).length;
237
+ for (let i = res.chain.length - 1; i >= 0 && res.lastActivity === null; i--) res.lastActivity = res.chain[i] .timestamp;
238
+
239
+ // Other leaves: report the ones whose own segment (up to the chain or an already walked node) holds messages.
240
+ const parents = new Set ();
241
+ for (const n of nodes.values()) if (n.parent !== null) parents.add(n.parent);
242
+ const walked = new Set (onChain);
243
+ for (const n of nodes.values()) {
244
+ if (parents.has(n.uuid) || n.uuid === leaf) continue;
245
+ let msg = false;
246
+ let terminal = false;
247
+ for (let x = n; x && !walked.has(x.uuid); x = x.parent !== null ? nodes.get(x.parent) : undefined) {
248
+ walked.add(x.uuid);
249
+ if (x.visible) msg = true;
250
+ if (x.visible && x.offset >= baseline && x.entrypoint !== null && x.entrypoint !== T3_ENTRYPOINT) terminal = true;
251
+ }
252
+ if (msg) res.divergedLeaves++;
253
+ if (terminal) res.orphanedTerminal++;
254
+ }
255
+ return res;
256
+ }
257
+
258
+ // ---------------- verdict cache ----------------
259
+
260
+
261
+ /** count: mergeable now; orphaned: sessions whose only terminal work sits on a side branch (never merged). */
262
+
263
+
264
+
265
+ const cachePath = (stateDir ) => path.join(stateDir, "cache", "merge.json");
266
+
267
+ async function readCache(stateDir ) {
268
+ if (!stateDir) return { version: 2, verdicts: {} };
269
+ try {
270
+ const u = JSON.parse(await readFile(cachePath(stateDir), "utf8")) ;
271
+ if (u && u.version === 2 && typeof u.verdicts === "object" && u.verdicts !== null) return u;
272
+ } catch { /* missing or unreadable: start over */ }
273
+ return { version: 2, verdicts: {} };
274
+ }
275
+
276
+ async function writeCache(stateDir , c ) {
277
+ if (!stateDir) return;
278
+ try {
279
+ await mkdir(path.dirname(cachePath(stateDir)), { recursive: true });
280
+ await atomicWrite(cachePath(stateDir), JSON.stringify(c) + "\n");
281
+ } catch { /* a cache is never worth failing a merge */ }
282
+ }
283
+
284
+ /** Sessions continued in a terminal and mergeable, as last counted by sync or `t3sm merge` (null: never counted). */
285
+ export async function readMergePending(stateDir ) {
286
+ const c = await readCache(stateDir);
287
+ return c.pending && typeof c.pending.count === "number" ? { ...c.pending, orphaned: c.pending.orphaned ?? 0 } : null;
288
+ }
289
+
290
+ /** Records the pending counts (orphaned kept when omitted). */
291
+ export async function setMergePending(stateDir , count , at , orphaned ) {
292
+ if (!stateDir) return;
293
+ const c = await readCache(stateDir);
294
+ const next = { count, orphaned: orphaned ?? c.pending?.orphaned ?? 0 };
295
+ if (c.pending?.count !== next.count || c.pending?.orphaned !== next.orphaned) { c.pending = { ...next, at: at.toISOString() }; await writeCache(stateDir, c); }
296
+ }
297
+
298
+ // ---------------- writing the revision ----------------
299
+
300
+
301
+
302
+ export function provenanceText(nativeId , at ) {
303
+ return `Merged revision of session ${nativeId} on ${at.toISOString()} by t3code-session-manager.`;
304
+ }
305
+
306
+ /**
307
+ * Writes the revision to a temp file next to the source (`.<revisionUuid>.<pid>.<rand>.tmp`, not a `.jsonl`, so no
308
+ * scanner takes it): the provenance record, then the chain root->leaf read back by offset. Same input, same bytes.
309
+ * `at` is the date in the provenance text (executeMerges passes the source's mtime).
310
+ */
311
+ export async function prepareRevision(
312
+ source , branch , o ,
313
+ ) {
314
+ if (branch.chain.length === 0) throw new Error("the transcript has no record with a uuid");
315
+ if (branch.problem !== null) throw new Error(`refusing to write a revision from a ${branch.problem} transcript`);
316
+ const rev = o.revisionUuid;
317
+ const provUuid = uuidV5(`rev-provenance:${rev}`);
318
+ const cwd = o.cwd ?? branch.chain.find((n) => n.cwd !== null)?.cwd ?? null;
319
+ const ts = branch.chain.find((n) => n.timestamp !== null)?.timestamp ?? o.at.toISOString();
320
+ const prov = {
321
+ parentUuid: null, type: "user", isMeta: true, message: { role: "user", content: provenanceText(o.nativeId, o.at) },
322
+ uuid: provUuid, timestamp: ts,
323
+ };
324
+ if (cwd !== null) prov.cwd = cwd;
325
+ prov.sessionId = rev;
326
+ const first = JSON.stringify(prov) + "\n";
327
+
328
+ const tmp = writeTempPath(path.dirname(source), rev);
329
+ const hash = createHash("sha256");
330
+ let size = 0;
331
+ const src = await open(source, "r");
332
+ try {
333
+ const out = await open(tmp, "wx");
334
+ try {
335
+ const put = async (s ) => {
336
+ const b = Buffer.from(s, "utf8");
337
+ hash.update(b);
338
+ size += b.length;
339
+ await out.write(b);
340
+ };
341
+ await put(first);
342
+ for (const [i, n] of branch.chain.entries()) {
343
+ const buf = Buffer.alloc(n.length);
344
+ const { bytesRead } = await src.read(buf, 0, n.length, n.offset);
345
+ const rec = parseLine(buf.subarray(0, bytesRead), n.offset);
346
+ if (rec === null || rec.uuid !== n.uuid) throw new Error(`${source} changed while the revision was written`);
347
+ rec.sessionId = rev;
348
+ if (i === 0) rec.parentUuid = provUuid;
349
+ await put(JSON.stringify(rec) + "\n");
350
+ }
351
+ await out.sync();
352
+ } finally {
353
+ await out.close();
354
+ }
355
+ } catch (e) {
356
+ await rm(tmp, { force: true }).catch(() => {});
357
+ throw e;
358
+ } finally {
359
+ await src.close();
360
+ }
361
+ return { tmp, sha256: hash.digest("hex"), size, firstLineBytes: Buffer.byteLength(first) };
362
+ }
363
+
364
+ /** Removes revision temp files (`.<rev>.<pid>.<rand>.tmp`) left in `dir` by a t3sm process that is gone. */
365
+ export const sweepStaleTemps = sweepWriteTemps;
366
+
367
+ // ---------------- candidates ----------------
368
+
369
+
370
+
371
+
372
+
373
+
374
+
375
+
376
+
377
+
378
+
379
+
380
+
381
+
382
+
383
+
384
+
385
+
386
+
387
+
388
+
389
+
390
+
391
+
392
+
393
+
394
+
395
+
396
+
397
+
398
+
399
+
400
+ /** A session that is not merged, but holds terminal work on a side branch neither T3 nor `claude --resume` shows. */
401
+
402
+
403
+
404
+
405
+
406
+
407
+
408
+
409
+
410
+
411
+
412
+
413
+
414
+
415
+
416
+
417
+
418
+
419
+
420
+
421
+
422
+
423
+
424
+
425
+
426
+
427
+
428
+
429
+
430
+ /** A thread T3 imported from a transcript: `import:<instance>:<native id>`. */
431
+ export const IMPORT_THREAD = /^import:([^:]+):(.+)$/s;
432
+
433
+
434
+
435
+
436
+ /** Merges still standing: not rolled back. */
437
+ export function standingMerges(entries ) {
438
+ const rolledBack = new Set(entries.flatMap((e) => (e.t === "rolled-back" ? [e.targetRunId] : [])));
439
+ return entries.filter((e) => e.t === "merged" && !rolledBack.has(e.runId));
440
+ }
441
+
442
+ /** Revision files t3sm wrote that no standing merge uses (path identity per platform: case-folded on win32/darwin). */
443
+ export function unmergedRevisionFiles(entries , platform = process.platform) {
444
+ const key = (p ) => pathKey(p, platform);
445
+ const used = new Set(standingMerges(entries).map((e) => key(e.revisionFile)));
446
+ const last = new Map ();
447
+ for (const e of effectiveWrites(entries, key)) if (e.revisionOf) last.set(key(e.path), e);
448
+ return [...last].filter(([k]) => !used.has(k)).map(([, e]) => e);
449
+ }
450
+
451
+ /** Read-only (apart from the verdict cache): which of `items` would be merged, and why the others are not. */
452
+ export async function findMergeCandidates(items , deps ) {
453
+ const now = deps.now ?? Date.now;
454
+ const platform = deps.platform ?? process.platform;
455
+ const key = (p ) => pathKey(p, platform);
456
+ const entries = await deps.journal.readAll();
457
+ const imported = importedIndex(entries);
458
+ const ours = new Map ();
459
+ for (const e of effectiveWrites(entries, key)) ours.set(key(e.path), e.sha256);
460
+ const merges = standingMerges(entries);
461
+ const mergedRevs = new Set(merges.map((e) => e.revisionUuid));
462
+ const failedRevs = new Set(entries.filter((e) => e.t === "import-failed").map((e) => (e ).nativeId));
463
+ const [threads, projects] = await Promise.all([deps.api.listThreads(), deps.api.listProjects()]);
464
+ const byNative = new Map ();
465
+ for (const t of threads) {
466
+ const m = IMPORT_THREAD.exec(t.id);
467
+ if (m) (byNative.get(m[2] ) ?? byNative.set(m[2] , []).get(m[2] ) ).push(t);
468
+ }
469
+ const projectById = new Map (projects.map((p) => [p.id, p]));
470
+ const cache = await readCache(deps.stateDir);
471
+ const fresh = {};
472
+ let cacheChanged = false;
473
+
474
+ const candidates = [];
475
+ const skipped = [];
476
+ const orphaned = [];
477
+ const seen = new Set ();
478
+ for (const item of items) {
479
+ const s = item.session;
480
+ if (s.harness !== "claude" || item.action.kind !== "skip" || item.action.reason !== "already-in-t3") continue;
481
+ if (seen.has(s.nativeId)) continue;
482
+ seen.add(s.nativeId);
483
+ const skip = (reason ) => void skipped.push({ nativeId: s.nativeId, reason });
484
+ // Its T3 thread is a faithful copy under another id (spec §4.3): a revision of this file could not reach it (R11).
485
+ if (item.notes.includes("continued-after-rehome")) { skip("rehomed-copy"); continue; }
486
+ const st = await statSafe(s.file.path).catch(() => null);
487
+ if (st === null) continue;
488
+ const rev = revisionUuid(s.nativeId, st.size);
489
+ const revisionFile = path.join(path.dirname(s.file.path), `${rev}.jsonl`);
490
+ const revSt = await statSafe(revisionFile).catch(() => null);
491
+ if (mergedRevs.has(rev) && revSt !== null) { skip("already-merged"); continue; }
492
+ const own = byNative.get(s.nativeId) ?? [];
493
+ const thread = own.find((t) => !t.archived);
494
+ if (!thread) { if (own.length > 0) skip("thread-archived"); continue; }
495
+ const project = projectById.get(thread.projectId);
496
+ if (!project) continue;
497
+
498
+ // Baseline: what t3sm imported, or what it merged last (R1).
499
+ const j = imported.get(`claude:${s.nativeId}`);
500
+ if (!j) { skip("not-continued"); continue; } // not imported by t3sm: no baseline, never a candidate
501
+ let base = { size: j.source.size, mtimeMs: j.source.mtimeMs };
502
+ for (const m of merges) {
503
+ if (m.nativeId === s.nativeId && typeof m.sourceSize === "number" && m.sourceSize > base.size && m.sourceSize <= st.size) {
504
+ base = { size: m.sourceSize, mtimeMs: typeof m.sourceMtimeMs === "number" ? m.sourceMtimeMs : base.mtimeMs };
505
+ }
506
+ }
507
+ if (base.size === st.size && near(st.mtimeMs, base.mtimeMs)) { skip("not-continued"); continue; }
508
+ if (isActive(st.mtimeMs, now())) { skip("active"); continue; }
509
+ if (deps.retryFailed === false && failedRevs.has(rev)) { skip("import-failed"); continue; }
510
+
511
+ const ck = `${key(s.file.path)}|${st.size}|${st.mtimeMs}|${base.size}`;
512
+ let branch = null;
513
+ let v = cache.verdicts[ck];
514
+ if (!v) {
515
+ try {
516
+ branch = await readBranch(s.file.path, { importedSize: base.size });
517
+ } catch {
518
+ skip("copy-failed");
519
+ continue;
520
+ }
521
+ v = {
522
+ problem: branch.problem, addedMessages: branch.addedMessages, t3MarkerAfter: branch.t3MarkerAfter, divergedLeaves: branch.divergedLeaves,
523
+ orphanedTerminal: branch.orphanedTerminal, lastActivity: branch.lastActivity, empty: branch.chain.length === 0,
524
+ };
525
+ cacheChanged = true;
526
+ }
527
+ fresh[ck] = v;
528
+ if (v.problem !== null) { skip(v.problem); continue; }
529
+ const orphan = () => { if (v.orphanedTerminal > 0) orphaned.push({ nativeId: s.nativeId, projectRoot: project.workspaceRoot, branches: v.orphanedTerminal }); };
530
+ if (v.empty || v.addedMessages === 0) { skip("not-continued"); orphan(); continue; }
531
+ const t3Wrote = typeof thread.latestUserMessageAt === "string" && Date.parse(thread.latestUserMessageAt) > base.mtimeMs;
532
+ if (t3Wrote && !v.t3MarkerAfter) { skip("no-t3-marker"); orphan(); continue; }
533
+
534
+ let reuse = null;
535
+ if (revSt !== null) {
536
+ const mine = ours.get(key(revisionFile));
537
+ if (mine === undefined) { skip("target-exists"); continue; }
538
+ const have = await sha256File(revisionFile).catch(() => null);
539
+ if (have !== mine) { skip("revision-in-use"); continue; }
540
+ reuse = { sha256: mine };
541
+ }
542
+ if (branch === null) {
543
+ try {
544
+ branch = await readBranch(s.file.path, { importedSize: base.size });
545
+ } catch {
546
+ skip("copy-failed");
547
+ continue;
548
+ }
549
+ if (branch.problem !== null || branch.addedMessages === 0) { skip(branch.problem ?? "not-continued"); continue; }
550
+ }
551
+ const instanceId = IMPORT_THREAD.exec(thread.id) [1] ;
552
+ candidates.push({
553
+ item, nativeId: s.nativeId, sourcePath: s.file.path, source: { size: st.size, mtimeMs: st.mtimeMs, atimeMs: st.atimeMs },
554
+ projectId: project.id, projectRoot: project.workspaceRoot, instanceId, oldThreadId: thread.id, oldTitle: thread.title,
555
+ revisionUuid: rev, revisionFile, newThreadId: `import:${instanceId}:${rev}`,
556
+ addedMessages: branch.addedMessages, divergedLeaves: branch.divergedLeaves, lastActivity: branch.lastActivity, reuse, branch,
557
+ });
558
+ }
559
+ candidates.sort((a, b) => a.source.mtimeMs - b.source.mtimeMs || (a.nativeId < b.nativeId ? -1 : a.nativeId > b.nativeId ? 1 : 0));
560
+ // The pending counts (doctor's merge-pending check) and the verdicts of the sessions seen this run.
561
+ const pendingChanged = cache.pending?.count !== candidates.length || (cache.pending?.orphaned ?? 0) !== orphaned.length || cache.pending === undefined;
562
+ if (cacheChanged || pendingChanged || Object.keys(fresh).length !== Object.keys(cache.verdicts).length) {
563
+ const pending = pendingChanged ? { count: candidates.length, orphaned: orphaned.length, at: new Date(now()).toISOString() } : cache.pending;
564
+ if (!deps.readOnly) await writeCache(deps.stateDir, { ...cache, version: 2, verdicts: fresh, pending });
565
+ }
566
+ return { candidates, skipped, orphaned };
567
+ }
568
+
569
+ // ---------------- merging ----------------
570
+
571
+ /** Removes a file while it is still exactly what t3sm wrote. */
572
+ export async function removeIfOurs(file , sha ) {
573
+ try {
574
+ if ((await sha256File(file)) !== sha) return false;
575
+ await rm(file, { force: true });
576
+ return true;
577
+ } catch {
578
+ return false; // gone, or unreadable: left as it is
579
+ }
580
+ }
581
+
582
+
583
+
584
+ /**
585
+ * The revision write (merge, and follow: src/ops/follow.ts). `tmp` (next to `target`, not a .jsonl) is journaled as
586
+ * `file-written` BEFORE it is published, then published without clobbering (link + unlink only: never replaces a file at
587
+ * the target, never falls back to rename) and given `mtimeMs`. Not published: the temp is removed and the write is
588
+ * cancelled with `file-write-aborted`, so the journal never claims a file t3sm did not write.
589
+ */
590
+ export async function publishRevision(o
591
+
592
+ ) {
593
+ await o.journal.append({ t: "file-written", runId: o.runId, path: o.target, sha256: o.sha256, mtimeMs: o.mtimeMs, ...o.entry });
594
+ try {
595
+ await publishNoClobber(o.tmp, o.target, o.linkFs ?? { link, unlink });
596
+ } catch (e) {
597
+ await rm(o.tmp, { force: true }).catch(() => {});
598
+ await o.journal.append({ t: "file-write-aborted", runId: o.runId, path: o.target });
599
+ return e instanceof MoveRefused && e.code === "EEXIST" ? "target-exists" : "copy-failed";
600
+ }
601
+ await utimes(o.target, o.mtimeMs / 1000, o.mtimeMs / 1000);
602
+ return "published";
603
+ }
604
+
605
+
606
+
607
+
608
+
609
+
610
+
611
+
612
+
613
+
614
+
615
+
616
+
617
+
618
+
619
+
620
+ /** What importRevision did: imported (in T3's thread list), unverified (T3 may have it), or why it was not imported. */
621
+
622
+
623
+ /**
624
+ * The import step (merge and follow): one item through runWaves (bump / park / restore, exposure, held projects), alone
625
+ * in its project's wave. The file is never removed here: the caller removes it (removeIfOurs) when it was not imported.
626
+ */
627
+ export async function importRevision(item , o ) {
628
+ const batch = o.batch ?? DEFAULT_BATCH;
629
+ const cost = (x ) => x.session.cwdOffsetBytes;
630
+ const homes = o.accountHomes ?? {};
631
+ const provs = o.providers;
632
+ const waves = await runWaves({
633
+ api: o.wavesApi ?? o.api, journal: o.journal, runId: o.runId, now: o.now, platform: o.platform, batch, cost,
634
+ projectIds: new Map([[o.projectRoot, o.projectId]]),
635
+ importRoots: new Map([[rootKey(o.projectRoot, o.platform), o.projectRoot]]),
636
+ instanceAvailability: new Map(provs.map((p) => [p.instanceId, p.availability] )),
637
+ exposure: exposureOf(o.exposureItems, provs, o.platform),
638
+ liveExposure: liveExposure(() => provs, o.platform, undefined, { accountHome: (id) => (Object.hasOwn(homes, id) ? homes[id] : undefined) }),
639
+ aborted: o.aborted,
640
+ onPendingFiles: o.onPendingFiles,
641
+ onProgress: () => {},
642
+ }, buildWaves([item], batch, cost, { platform: o.platform }));
643
+ if (waves.imported.includes(item)) return "imported";
644
+ if (waves.unverified.includes(item)) return "import-unverified"; // T3 may have it: the caller keeps the file
645
+ const deferred = waves.deferred.find((d) => d.item === item);
646
+ if (deferred) {
647
+ return deferred.reason === "project-in-use" || deferred.reason === "clock-jump" || deferred.reason === "file-busy" ? deferred.reason : deferred.reason === "missing" ? "copy-failed" : "active";
648
+ }
649
+ if (waves.failed.some((f) => f.item === item)) return "import-failed";
650
+ return "aborted";
651
+ }
652
+
653
+ /**
654
+ * The archive step (merge and follow): only once the new thread is confirmed in T3's thread list (read once more right
655
+ * before the old thread is touched). A rolled-back earlier swap left the new thread archived: unarchived first
656
+ * (journaled), so the session always keeps one active thread. `beforeArchive` (follow: carry the old thread's title and
657
+ * settled state) runs on the fresh new thread; its errors propagate. Then the old thread is archived and journaled
658
+ * `thread-archived`. The caller journals what the swap was for (`merged`).
659
+ */
660
+ export async function swapThreads(o
661
+
662
+
663
+
664
+ ) {
665
+ const listed = await o.api.listThreads().catch(() => null);
666
+ const fresh = listed?.find((t) => t.id === o.newThreadId);
667
+ if (!fresh) return "import-unverified";
668
+ if (fresh.archived) {
669
+ try {
670
+ await o.api.unarchiveThread(o.newThreadId);
671
+ } catch {
672
+ return "archive-failed";
673
+ }
674
+ await appendOrStop(o.journal, { t: "thread-unarchived", runId: o.runId, threadId: o.newThreadId }, `the unarchive of ${o.newThreadId}`);
675
+ }
676
+ if (o.beforeArchive && (await o.beforeArchive({ ...fresh, archived: false })) === false) return "cancelled";
677
+ try {
678
+ await o.api.archiveThread(o.oldThreadId);
679
+ } catch {
680
+ return "archive-failed";
681
+ }
682
+ await appendOrStop(o.journal, { t: "thread-archived", runId: o.runId, threadId: o.oldThreadId }, `the archive of ${o.oldThreadId}`);
683
+ return "swapped";
684
+ }
685
+
686
+ /**
687
+ * Journals a change T3 Code already holds. A failure is a JournalWriteError: the run stops (merge, follow and sync
688
+ * never go on with T3 holding a change the journal did not hear of, which no rollback could undo).
689
+ */
690
+ export async function appendOrStop(j , e , what ) {
691
+ try {
692
+ await j.append(e);
693
+ } catch (err) {
694
+ throw new JournalWriteError(`Could not write the journal (${err instanceof Error ? err.message : String(err)}) after T3 Code accepted ${what}; stopped.`);
695
+ }
696
+ }
697
+
698
+ /** Writes, imports and swaps the threads of each candidate, one at a time (see the header for the order). */
699
+ export async function executeMerges(candidates , deps ) {
700
+ const now = deps.now ?? Date.now;
701
+ const platform = deps.platform ?? process.platform;
702
+ const res = { merged: [], skipped: [] };
703
+ const limit = deps.limit ?? Infinity;
704
+ let started = null;
705
+ const runId = () => (started ??= typeof deps.runId === "string" ? Promise.resolve(deps.runId) : deps.runId());
706
+ let providers = null;
707
+ const swept = new Set ();
708
+ let journalNow = null;
709
+ let threadIdsNow = null;
710
+
711
+ for (const [i, c] of candidates.entries()) {
712
+ const skip = (reason ) => void res.skipped.push({ nativeId: c.nativeId, reason });
713
+ if (i >= limit) { skip("over-cap"); continue; }
714
+ if (deps.aborted?.()) { skip("aborted"); continue; }
715
+ const dir = path.dirname(c.revisionFile);
716
+ if (!swept.has(dir)) { swept.add(dir); await sweepStaleTemps(dir); }
717
+
718
+ // Earlier revisions of this session that were never merged (import failed, unverified, crash) and are still ours:
719
+ // removed, unless T3 holds a thread for them.
720
+ journalNow ??= await deps.journal.readAll();
721
+ threadIdsNow = null;
722
+ for (const e of unmergedRevisionFiles(journalNow, platform)) {
723
+ if (e.revisionOf?.nativeId !== c.nativeId || e.path === c.revisionFile) continue;
724
+ // Any instance's thread for that revision (an import under another account) keeps it.
725
+ threadIdsNow ??= new Set((await deps.api.listThreads()).flatMap((t) => [IMPORT_THREAD.exec(t.id)?.[2] ?? "", t.nativeSessionId ?? ""]).filter((x) => x !== ""));
726
+ if (threadIdsNow.has(path.basename(e.path, ".jsonl"))) continue;
727
+ if (await removeIfOurs(e.path, e.sha256)) deps.onProgress?.(`Removed an unmerged earlier revision ${e.path}`);
728
+ }
729
+
730
+ // ---------- the revision file ----------
731
+ let sha ;
732
+ let firstLineBytes ;
733
+ if (c.reuse) {
734
+ sha = c.reuse.sha256;
735
+ firstLineBytes = await firstLineLength(c.revisionFile);
736
+ // The source must still be idle and unchanged right before the import (it was checked at planning time only).
737
+ const again = await statSafe(c.sourcePath).catch(() => null);
738
+ if (again === null || again.size !== c.source.size || !near(again.mtimeMs, c.source.mtimeMs) || isActive(again.mtimeMs, now())) {
739
+ skip("active");
740
+ continue;
741
+ }
742
+ // Ours (sha checked when it became a candidate) and aged past now - 20 days while unmerged: re-clamped (utimes
743
+ // only), so it never drifts into Claude Code's cleanup zone while it waits.
744
+ const revSt = await statSafe(c.revisionFile).catch(() => null);
745
+ let revMtime = revSt?.mtimeMs ?? now();
746
+ if (revSt !== null && revSt.mtimeMs < now() - WRITTEN_MAX_AGE_MS) {
747
+ revMtime = writtenMtime(c.source.mtimeMs, now());
748
+ await utimes(c.revisionFile, revMtime / 1000, revMtime / 1000);
749
+ }
750
+ // Journaled again in this run, before the import (as publishRevision does): the run that swaps the revision in
751
+ // owns it, so a rollback of the earlier run keeps it ("rewritten") and a rollback of this one undoes the merge.
752
+ await deps.journal.append({ t: "file-written", runId: await runId(), path: c.revisionFile, sha256: sha, mtimeMs: revMtime, revisionOf: { harness: "claude", nativeId: c.nativeId } });
753
+ journalNow = null;
754
+ } else {
755
+ let prep ;
756
+ try {
757
+ prep = await prepareRevision(c.sourcePath, c.branch, {
758
+ nativeId: c.nativeId, revisionUuid: c.revisionUuid, at: new Date(c.source.mtimeMs),
759
+ cwd: c.branch.chain.find((n) => n.cwd !== null)?.cwd ?? c.item.session.cwd,
760
+ });
761
+ } catch {
762
+ skip("copy-failed");
763
+ continue;
764
+ }
765
+ // Written to while we read it: the session is in use again; nothing was journaled yet.
766
+ const again = await statSafe(c.sourcePath).catch(() => null);
767
+ if (again === null || again.size !== c.source.size || !near(again.mtimeMs, c.source.mtimeMs)) {
768
+ await rm(prep.tmp, { force: true });
769
+ skip("active");
770
+ continue;
771
+ }
772
+ const rid = await runId();
773
+ const harness = "claude";
774
+ const revMtime = writtenMtime(c.source.mtimeMs, now()); // never inside Claude Code's cleanup zone (materialize.ts)
775
+ const pub = await publishRevision({
776
+ tmp: prep.tmp, target: c.revisionFile, sha256: prep.sha256, mtimeMs: revMtime, journal: deps.journal, runId: rid,
777
+ entry: { revisionOf: { harness, nativeId: c.nativeId } }, linkFs: deps.linkFs,
778
+ });
779
+ if (pub !== "published") { skip(pub); continue; }
780
+ sha = prep.sha256;
781
+ firstLineBytes = prep.firstLineBytes;
782
+ }
783
+
784
+ // ---------- import through the waves ----------
785
+ const rid = await runId();
786
+ const st = await statSafe(c.revisionFile);
787
+ if (st === null) { skip("copy-failed"); continue; }
788
+ const item = {
789
+ session: {
790
+ ...c.item.session, nativeId: c.revisionUuid, file: st, flags: [], cwdOffsetBytes: firstLineBytes,
791
+ updatedAt: c.lastActivity ?? new Date(c.source.mtimeMs).toISOString(),
792
+ },
793
+ action: { kind: "import", projectRoot: c.projectRoot, instanceId: c.instanceId, expectedThreadId: c.newThreadId },
794
+ notes: [],
795
+ };
796
+ providers ??= await deps.api.providerInstances();
797
+ const outcome = await importRevision(item, {
798
+ api: deps.api, journal: deps.journal, runId: rid, now, platform, projectId: c.projectId, projectRoot: c.projectRoot, providers,
799
+ exposureItems: deps.exposureItems ?? candidates.map((x) => x.item), accountHomes: deps.accountHomes, batch: deps.batch,
800
+ aborted: deps.aborted, onPendingFiles: deps.onPendingFiles,
801
+ });
802
+ threadIdsNow = null;
803
+
804
+ if (outcome === "imported") {
805
+ // Confirmed in the thread list by the importer; swapThreads reads it once more before touching the old thread.
806
+ const swapped = await swapThreads({ api: deps.api, journal: deps.journal, runId: rid, oldThreadId: c.oldThreadId, newThreadId: c.newThreadId });
807
+ if (swapped !== "swapped") { skip(swapped === "cancelled" ? "archive-failed" : swapped); continue; }
808
+ await appendOrStop(deps.journal, {
809
+ t: "merged", runId: rid, harness: "claude", nativeId: c.nativeId, revisionUuid: c.revisionUuid, revisionFile: c.revisionFile,
810
+ oldThreadId: c.oldThreadId, newThreadId: c.newThreadId, sourceSize: c.source.size, sourceMtimeMs: c.source.mtimeMs,
811
+ }, `the archive of ${c.oldThreadId}`);
812
+ journalNow = null;
813
+ res.merged.push({
814
+ nativeId: c.nativeId, revisionUuid: c.revisionUuid, revisionFile: c.revisionFile, newThreadId: c.newThreadId, oldThreadId: c.oldThreadId,
815
+ oldTitle: c.oldTitle, addedMessages: c.addedMessages, divergedLeaves: c.divergedLeaves, projectRoot: c.projectRoot,
816
+ });
817
+ deps.onProgress?.(`Merged ${c.nativeId} -> ${c.newThreadId}`);
818
+ continue;
819
+ }
820
+ if (outcome === "import-unverified") { skip("import-unverified"); continue; } // T3 may have it: keep the file
821
+ await removeIfOurs(c.revisionFile, sha);
822
+ skip(outcome);
823
+ }
824
+ return res;
825
+ }
826
+
827
+ async function firstLineLength(file ) {
828
+ for await (const { buf } of fileLines(file)) return buf.length;
829
+ return 0;
830
+ }