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,868 @@
1
+ // Undo one run from the journal (spec §4.3: quarantine is reversible; every default change is revertible).
2
+ // rollbackRun REQUIRES the caller to hold the state-dir lock (acquireLock) and to have run recoverPendingMtimes first
3
+ // (a dry run needs neither: it writes nothing).
4
+ //
5
+ // The journal is not trusted blindly: an entry is acted on only when its fields have the right types and its paths
6
+ // stay inside a configured account home (quarantine entries: `to` under <H>/session-manager-quarantine/(backups|mirror),
7
+ // `from` under <H>/projects, same H; converted files: <H>/projects/<dir>/<name>.jsonl; no `..` anywhere). Anything else
8
+ // is reported in `errors` and skipped; the rest of the run is still rolled back.
9
+ //
10
+ // File level (no T3 Code needed): converted files written by the run are deleted only while their sha256 still matches
11
+ // and they were not changed in the last 10 minutes (else kept and reported); quarantined entries move back without
12
+ // ever replacing anything (moveEntry; an original path that exists again is a conflict and the entry stays in
13
+ // quarantine), journaled `unquarantined`, and emptied quarantine folders are removed. T3 level (skipped with a report
14
+ // when T3 Code is not reachable): per-project default instance restored to `previous`; instance label/colour/home
15
+ // restored only with `instances`; imported threads listed (archived only with `archiveThreads`, never deleted).
16
+ // Merges (`merged` / `thread-archived`): a revision still exactly as t3sm wrote it is deleted (file level, above), its
17
+ // old thread unarchived and its revision thread archived; a revision continued since keeps both threads (reported), and
18
+ // so does a merge a later run (not rolled back) built on: a follow of its revision thread, or a revision of its
19
+ // revision ("followed again by run X; roll back X first"). A revision a later run journaled again (reused it and
20
+ // swapped it in) is that run's: kept here ("rewritten"), with its thread.
21
+ // Destination folders an apply created for rehome copies (`folder-created`): removed deepest first, up to the topmost
22
+ // one it created, each only while it is empty; one holding anything is kept (reported).
23
+ // Organize changes (`organize-change`): reverted exactly as `t3sm organize --undo` does (undoOrganizeEntries), newest
24
+ // first, only where T3 still shows the value t3sm set; T3 Code is reached first, before any file is touched.
25
+ // Idempotent: every step checks the current state (or a later journal entry) first, and a rollback that changes
26
+ // nothing writes nothing to the journal.
27
+
28
+ import { lstat, mkdir, readdir, rm, rmdir } from "node:fs/promises";
29
+ import { basename, dirname, isAbsolute, join } from "node:path";
30
+
31
+ import { effectiveWrites, newRunId, } from "../core/journal.js";
32
+ import { sha256File, statSafe } from "../core/fsutil.js";
33
+ import { pathKey, sameCwd } from "../core/paths.js";
34
+ import { ConfigError } from "../core/config.js";
35
+ import { isActive } from "../core/activity.js";
36
+
37
+ import { T3NotRunning } from "../t3/errors.js";
38
+ import { organizeGate } from "../t3/compat.js";
39
+ import { OrganizeReadError, undoOrganizeEntries, } from "../organize/apply.js";
40
+ import {
41
+ JournalWriteError, MoveRefused, QUARANTINE_DIR, hasDotDot, isInside, moveEntry, moveFailure, nodeMoveFs, pruneEmptyQuarantineDirs, subdirOf,
42
+
43
+ } from "./quarantine.js";
44
+
45
+
46
+
47
+
48
+
49
+
50
+
51
+
52
+
53
+
54
+
55
+
56
+
57
+
58
+
59
+
60
+
61
+
62
+
63
+
64
+
65
+
66
+
67
+
68
+
69
+
70
+
71
+
72
+
73
+
74
+
75
+
76
+
77
+
78
+
79
+
80
+
81
+
82
+
83
+
84
+
85
+
86
+
87
+
88
+
89
+
90
+
91
+
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
+
129
+
130
+
131
+
132
+
133
+
134
+ const isObj = (u ) => typeof u === "object" && u !== null && !Array.isArray(u);
135
+ const isStr = (u ) => typeof u === "string" && u !== "";
136
+ const strOrNull = (u ) => u === null || typeof u === "string";
137
+ const msg = (e ) => (e instanceof Error ? e.message : String(e));
138
+
139
+ /** `path`, then each parent up to and including `created` (deepest first); null when `created` is not one of them. */
140
+ function foldersUpTo(path , created ) {
141
+ const out = [];
142
+ for (let d = path; ; d = dirname(d)) {
143
+ out.push(d);
144
+ if (pathKey(d) === pathKey(created)) return out;
145
+ if (dirname(d) === d) return null;
146
+ }
147
+ }
148
+
149
+ /** Newest run with a run-start that is not itself a rollback. */
150
+ export function latestRunId(entries ) {
151
+ for (let i = entries.length - 1; i >= 0; i--) {
152
+ const e = entries[i] ;
153
+ if (e.t === "run-start" && typeof e.command === "string" && !e.command.startsWith("rollback")) return e.runId;
154
+ }
155
+ return null;
156
+ }
157
+
158
+ /** Entry kinds whose rollback changes T3 Code through something other than organize's commands. */
159
+ const OTHER_T3_KINDS = new Set(["project-default-set", "instance-pinned", "instance-updated", "imported", "import-attempt", "merged", "followed", "thread-archived", "thread-unarchived"]);
160
+
161
+ /**
162
+ * The rollback of `runId` touches T3 Code only through organize's commands (it has organize changes and nothing else
163
+ * for T3). Such a rollback runs on any T3 Code version with organizeGate's one warning (ruling R18), so the caller
164
+ * connects with allowUntested and lets organizeGate speak.
165
+ */
166
+ export function organizeOnlyRun(entries , runId ) {
167
+ const mine = entries.filter((e) => e.runId === runId);
168
+ return mine.some((e) => e.t === "organize-change") && !mine.some((e) => OTHER_T3_KINDS.has(e.t));
169
+ }
170
+
171
+ /** The run-start command of `runId` marks it as a rollback run (those are never rolled back). */
172
+ export function isRollbackRun(entries , runId ) {
173
+ return entries.some((e) => e.t === "run-start" && e.runId === runId && typeof e.command === "string" && e.command.startsWith("rollback"));
174
+ }
175
+
176
+ function selection(u ) {
177
+ if (!isObj(u)) return { instanceId: null, model: undefined };
178
+ const id = typeof u.instanceId === "string" ? u.instanceId : typeof u.provider === "string" ? u.provider : null;
179
+ return { instanceId: id, model: typeof u.model === "string" ? u.model : undefined };
180
+ }
181
+
182
+ /** Two paths name the same regular file (same device and inode: hard links). */
183
+ async function sameFile(a , b ) {
184
+ const [x, y] = await Promise.all([lstat(a, { bigint: true }), lstat(b, { bigint: true })]);
185
+ return x.isFile() && y.isFile() && x.dev === y.dev && x.ino === y.ino && x.ino !== 0n;
186
+ }
187
+
188
+ async function exists(p ) {
189
+ try {
190
+ await lstat(p);
191
+ return true;
192
+ } catch (e) {
193
+ if ((e ).code === "ENOENT") return false;
194
+ throw e;
195
+ }
196
+ }
197
+
198
+ /** The account home a quarantined entry belongs to, or why it is not acted on. */
199
+ function quarantineHome(e , homes , platform ) {
200
+ if (!isStr(e.from) || !isStr(e.to)) return { error: "from/to missing or not strings" };
201
+ if (hasDotDot(e.from) || hasDotDot(e.to)) return { error: "path with `..`" };
202
+ for (const h of homes) {
203
+ const q = join(h, QUARANTINE_DIR);
204
+ const toOk = isInside(e.to, join(q, "backups"), platform) || isInside(e.to, join(q, "mirror"), platform);
205
+ if (toOk && isInside(e.from, join(h, "projects"), platform)) return { home: h };
206
+ }
207
+ return { error: `${e.from} -> ${e.to} is outside the configured account folders` };
208
+ }
209
+
210
+ /** A converted transcript path: <H>/projects/<dir>/<name>.jsonl for a configured home H. */
211
+ function convertedFileOk(path , homes , platform ) {
212
+ if (!isStr(path) || hasDotDot(path) || !basename(path).endsWith(".jsonl")) return false;
213
+ return homes.some((h) => {
214
+ const rel = subdirOf(join(h, "projects"), dirname(path), platform);
215
+ return rel !== null && rel !== "" && !rel.includes("/");
216
+ });
217
+ }
218
+
219
+ /** Why an entry of the target run is malformed (null: well-formed). Path bounds are checked where they are used. */
220
+ function malformed(e ) {
221
+ const o = e ;
222
+ switch (e.t) {
223
+ case "file-written":
224
+ if (o.revisionOf !== undefined && !(isObj(o.revisionOf) && isStr(o.revisionOf.nativeId))) return "revisionOf invalid";
225
+ return isStr(o.path) && typeof o.sha256 === "string" && /^[0-9a-f]{64}$/.test(o.sha256) ? null : "path/sha256 missing or invalid";
226
+ case "quarantined": return isStr(o.from) && isStr(o.to) ? null : "from/to missing or not strings";
227
+ case "project-default-set": return isStr(o.projectId) ? null : "projectId missing";
228
+ case "project-created": return isStr(o.projectId) && typeof o.root === "string" ? null : "projectId/root missing";
229
+ case "instance-created": return isStr(o.instanceId) ? null : "instanceId missing";
230
+ case "folder-created": {
231
+ if (!isStr(o.path) || !isStr(o.created) || hasDotDot(o.path) || hasDotDot(o.created) || !isAbsolute(o.path)) return "path/created missing or not absolute";
232
+ return foldersUpTo(o.path, o.created) === null ? "created is not the folder or one of its parents" : null;
233
+ }
234
+ case "organize-change": return isStr(o.kind) && isStr(o.target) ? null : "kind/target missing";
235
+ case "imported": return isStr(o.threadId) ? null : "threadId missing";
236
+ case "import-attempt": return Array.isArray(o.items) && (o.parked === undefined || Array.isArray(o.parked)) ? null : "items missing";
237
+ case "thread-archived": return isStr(o.threadId) ? null : "threadId missing";
238
+ case "thread-unarchived": return isStr(o.threadId) ? null : "threadId missing";
239
+ case "merged": return isStr(o.nativeId) && isStr(o.revisionFile) && isStr(o.oldThreadId) && isStr(o.newThreadId) ? null : "nativeId/revisionFile/oldThreadId/newThreadId missing";
240
+ case "followed": return isStr(o.original) && isStr(o.copy) && isStr(o.oldThread) && (o.mode === "refresh" || o.mode === "revision") ? null : "original/copy/oldThread/mode missing";
241
+ case "instance-pinned":
242
+ return isStr(o.instanceId) && isObj(o.previous) && strOrNull(o.previous.homePath) && isObj(o.next) && typeof o.next.homePath === "string" ? null : "instanceId/previous/next invalid";
243
+ case "instance-updated": {
244
+ const d = (u ) => isObj(u) && strOrNull(u.displayName) && strOrNull(u.accentColor) && strOrNull(u.homePath);
245
+ return isStr(o.instanceId) && d(o.previous) && d(o.next) ? null : "instanceId/previous/next invalid";
246
+ }
247
+ default: return null;
248
+ }
249
+ }
250
+
251
+ export async function rollbackRun(targetRunId , deps ) {
252
+ const j = deps.journal;
253
+ const now = deps.now ?? Date.now;
254
+ const fs = deps.fs ?? nodeMoveFs;
255
+ const platform = deps.platform ?? process.platform;
256
+ const dry = deps.dryRun ?? false;
257
+ const homes = deps.accountHomes;
258
+ const keyOf = (p ) => pathKey(p, platform);
259
+
260
+ const all = await j.readAll();
261
+ if (isRollbackRun(all, targetRunId)) throw new ConfigError("Cannot roll back a rollback run.");
262
+ const r = {
263
+ runId: null, targetRunId, command: null,
264
+ filesRemoved: [], filesKeptModified: [], filesKeptActive: [], filesKeptRewritten: [], filesKeptRefreshed: [], foldersRemoved: [], foldersKept: [], unquarantined: [], unquarantineConflicts: [], alreadyRestored: [],
265
+ unquarantineMissing: [], unquarantineFailed: [], defaultsRestored: [], defaultsSkipped: [], instanceChanges: [], instancesCreated: [], projectsCreated: [],
266
+ threadsToReview: [], threadsVerified: false, threadsArchived: [], parkedThreads: [], threadsUnarchived: [], mergesKept: [], needsReview: [], organize: [], t3Unavailable: null, errors: [],
267
+ };
268
+ const mine = [];
269
+ let any = false;
270
+ all.forEach((e, i) => {
271
+ if (e.runId !== targetRunId) return;
272
+ any = true;
273
+ const bad = malformed(e);
274
+ if (bad) r.errors.push(`skipped a malformed ${e.t} journal entry (${bad})`);
275
+ else mine.push({ e, i });
276
+ });
277
+ if (!any) throw new ConfigError(`No run ${targetRunId} in the journal. Run \`t3sm runs\` to list them.`);
278
+ const start = mine.find((x) => x.e.t === "run-start")?.e ;
279
+ r.command = typeof start?.command === "string" ? start.command : null;
280
+
281
+ let rb = null;
282
+ const begin = async () => {
283
+ if (rb === null) {
284
+ const id = newRunId(new Date(now()));
285
+ await j.append({ t: "run-start", runId: id, at: new Date(now()).toISOString(), command: `rollback ${targetRunId}` });
286
+ rb = id;
287
+ }
288
+ return rb;
289
+ };
290
+ const laterUnquarantine = (i , from , to ) =>
291
+ all.some((x, xi) => xi > i && x.t === "unquarantined" && isStr(x.from) && isStr(x.to) && keyOf(x.from) === keyOf(to) && keyOf(x.to) === keyOf(from));
292
+
293
+ // Merge revisions (Task 23): their threads are fixed in T3 Code together with the file, so T3 Code is reached FIRST;
294
+ // when it cannot be, the revision files are left untouched (reported) and a later rollback finishes the job.
295
+ const revisionPaths = new Set ();
296
+ for (const { e } of mine) {
297
+ if (e.t === "merged" && isStr(e.revisionFile)) revisionPaths.add(keyOf(e.revisionFile));
298
+ if (e.t === "file-written" && e.revisionOf && isStr(e.path)) revisionPaths.add(keyOf(e.path));
299
+ }
300
+ let api = null ; // assigned in connectT3Once (the cast keeps TS from narrowing it to null)
301
+ let connectTried = false;
302
+ const connectT3Once = async () => {
303
+ if (connectTried) return;
304
+ connectTried = true;
305
+ if (!deps.connect) { r.t3Unavailable = "T3 Code not connected"; return; }
306
+ try {
307
+ api = await deps.connect();
308
+ } catch (e) {
309
+ r.t3Unavailable = e instanceof T3NotRunning ? "T3 Code not running" : `T3 Code not reachable (${msg(e)})`;
310
+ }
311
+ };
312
+ // The thread list is read before any revision file is touched: unreadable = the threads cannot be fixed, so the
313
+ // revision files stay (reported), exactly as when T3 Code is not reachable at all.
314
+ let live = null;
315
+ let revisionsBlocked = null;
316
+ if (revisionPaths.size > 0) {
317
+ await connectT3Once();
318
+ if (api === null) revisionsBlocked = r.t3Unavailable ?? "T3 Code not connected";
319
+ else {
320
+ try { live = new Map((await api.listThreads()).map((t) => [t.id, t.archived] )); } catch (e) {
321
+ revisionsBlocked = `could not read T3 threads (${msg(e)})`;
322
+ r.errors.push(`could not read T3 threads: ${msg(e)}`);
323
+ }
324
+ }
325
+ }
326
+ const kept = new Map ();
327
+
328
+ // Merges a later run built on (follow makes such chains routine: cycle A follows the copy into R1, cycle B follows R1
329
+ // into R2): a later run swapped this merge's revision thread out again (`merged` / `followed` with it as the old
330
+ // thread), or wrote a revision of this revision that is still there. Undoing it would delete the transcript the later
331
+ // chain continues from and bring back a second active thread, so it is kept whole (its revision file too) until that
332
+ // run is rolled back first. A later swap counts until a rollback undid it (rolled back, and its revision gone): a
333
+ // rollback that kept it (the revision continued since) leaves it standing.
334
+ const rolledBackRuns = new Set(all.flatMap((e) => (e.t === "rolled-back" ? [e.targetRunId] : [])));
335
+ const liveWrites = new Set (effectiveWrites(all, keyOf));
336
+ const there = async (file ) => exists(file).catch(() => true);
337
+ for (const { e, i } of mine) {
338
+ if (e.t !== "merged") continue;
339
+ const rev = basename(e.revisionFile, ".jsonl");
340
+ let later = null;
341
+ for (let xi = i + 1; xi < all.length && later === null; xi++) {
342
+ const x = all[xi] ;
343
+ if (x.runId === targetRunId) continue;
344
+ const swap = x.t === "merged" && x.oldThreadId === e.newThreadId && isStr(x.revisionFile) ? x.revisionFile
345
+ : x.t === "followed" && x.oldThread === e.newThreadId && isStr(x.copy) ? x.copy : null;
346
+ if (swap !== null && (!rolledBackRuns.has(x.runId) || (await there(swap)))) later = x.runId;
347
+ else if (x.t === "file-written" && x.revisionOf?.nativeId === rev && liveWrites.has(x) && isStr(x.path) && (await there(x.path))) later = x.runId;
348
+ }
349
+ if (later !== null) kept.set(keyOf(e.revisionFile), `followed again by run ${later}; roll back ${later} first`);
350
+ }
351
+
352
+ // Organize changes: T3 is opened before anything else, and an unverified version warns once (never refuses).
353
+ const organizeEntries = mine.filter((x) => x.e.t === "organize-change").map((x) => x.e);
354
+ if (organizeEntries.length > 0) {
355
+ await connectT3Once();
356
+ if (api !== null) organizeGate((api ).version, { allowUntested: deps.allowUntested ?? false, onNotice: deps.onNotice });
357
+ }
358
+
359
+ // ---------- files (newest first) ----------
360
+ const seenFiles = new Set ();
361
+ // Rehome copies a follow rewrote in place (refresh mode): T3 grew their thread from the new records, and the copy
362
+ // before the refresh is gone; removing the file would leave that thread without its transcript. Kept, reported.
363
+ const refreshed = new Set(mine.flatMap(({ e }) => (e.t === "followed" && e.mode === "refresh" && isStr(e.copy) ? [keyOf(e.copy)] : [])));
364
+ try {
365
+ for (const { e, i } of [...mine].reverse()) {
366
+ if (e.t === "file-written") {
367
+ if (!convertedFileOk(e.path, homes, platform)) { r.errors.push(`skipped file-written ${e.path}: not a transcript inside a configured account's projects folder`); continue; }
368
+ // Never published (file-write-aborted later in the same run): whatever sits there is not ours.
369
+ if (all.some((x, xi) => xi > i && x.t === "file-write-aborted" && x.runId === e.runId && isStr(x.path) && keyOf(x.path) === keyOf(e.path))) continue;
370
+ const k = keyOf(e.path);
371
+ if (seenFiles.has(k)) continue; // only this run's last write of a path counts
372
+ seenFiles.add(k);
373
+ if (refreshed.has(k)) { r.filesKeptRefreshed.push(e.path); continue; }
374
+ if (kept.has(k)) continue; // a later run built on this revision (above): reported with its merge
375
+ if (revisionPaths.has(k) && revisionsBlocked !== null && (await exists(e.path).catch(() => true))) {
376
+ kept.set(k, "T3 Code unreachable");
377
+ r.errors.push(`kept the merge revision ${e.path}: ${revisionsBlocked}; run the rollback again with T3 Code running`);
378
+ continue;
379
+ }
380
+ if (all.some((x, xi) => xi > i && x.t === "file-written" && x.runId !== targetRunId && isStr(x.path) && keyOf(x.path) === k)) { r.filesKeptRewritten.push(e.path); continue; }
381
+ let sha ;
382
+ let st;
383
+ try {
384
+ sha = await sha256File(e.path);
385
+ st = await statSafe(e.path);
386
+ } catch (err) {
387
+ if ((err ).code !== "ENOENT") r.errors.push(`could not read ${e.path}: ${msg(err)}`);
388
+ continue; // already gone: nothing to undo
389
+ }
390
+ if (sha !== e.sha256) { r.filesKeptModified.push(e.path); continue; }
391
+ if (!st || isActive(st.mtimeMs, now())) { r.filesKeptActive.push(e.path); continue; }
392
+ if (!dry) {
393
+ await begin();
394
+ try {
395
+ await rm(e.path);
396
+ } catch (err) {
397
+ r.errors.push(`could not remove ${e.path}: ${msg(err)}`);
398
+ continue;
399
+ }
400
+ }
401
+ r.filesRemoved.push(e.path);
402
+ } else if (e.t === "quarantined") {
403
+ const where = quarantineHome(e, homes, platform);
404
+ if ("error" in where) { r.errors.push(`skipped quarantined entry: ${where.error}`); continue; }
405
+ if (laterUnquarantine(i, e.from, e.to)) continue;
406
+ try {
407
+ const inQuarantine = await exists(e.to);
408
+ const atOrigin = await exists(e.from);
409
+ if (!inQuarantine) { (atOrigin ? r.alreadyRestored : r.unquarantineMissing).push(atOrigin ? e.from : e.to); continue; }
410
+ if (atOrigin) {
411
+ // Both names are ONE file (an earlier rollback crashed between its link and its unlink): finish that move.
412
+ if (await sameFile(e.to, e.from)) {
413
+ if (!dry) {
414
+ const id = await begin();
415
+ await fs.unlink(e.to);
416
+ await j.append({ t: "unquarantined", runId: id, from: e.to, to: e.from });
417
+ await pruneEmptyQuarantineDirs(dirname(e.to), where.home, platform);
418
+ }
419
+ r.unquarantined.push(e.from);
420
+ continue;
421
+ }
422
+ r.unquarantineConflicts.push({ from: e.to, to: e.from });
423
+ continue;
424
+ }
425
+ } catch (err) {
426
+ r.unquarantineFailed.push({ path: e.to, reason: msg(err) });
427
+ continue;
428
+ }
429
+ if (!dry) {
430
+ const id = await begin();
431
+ try {
432
+ await mkdir(dirname(e.from), { recursive: true }); // the encoded project folder may be gone
433
+ await moveEntry(e.to, e.from, fs);
434
+ } catch (err) {
435
+ if (err instanceof MoveRefused && err.code === "EEXIST") r.unquarantineConflicts.push({ from: e.to, to: e.from });
436
+ else r.unquarantineFailed.push({ path: e.to, reason: `could not move back (${moveFailure(err)})` });
437
+ continue;
438
+ }
439
+ try {
440
+ await j.append({ t: "unquarantined", runId: id, from: e.to, to: e.from });
441
+ } catch (err) {
442
+ try { await moveEntry(e.from, e.to, fs); } catch (back) {
443
+ throw new JournalWriteError(`Could not write the journal (${msg(err)}) after moving ${e.to} back to ${e.from}, and could not undo that move (${moveFailure(back)}). Nothing is lost; a later rollback reports it as already restored.`);
444
+ }
445
+ throw new JournalWriteError(`Could not write the journal (${msg(err)}); ${e.to} stays in quarantine.`);
446
+ }
447
+ await pruneEmptyQuarantineDirs(dirname(e.to), where.home, platform);
448
+ }
449
+ r.unquarantined.push(e.from);
450
+ } else if (e.t === "instance-created") {
451
+ r.instancesCreated.unshift(e.instanceId);
452
+ } else if (e.t === "project-created") {
453
+ r.projectsCreated.unshift({ projectId: e.projectId, root: e.root });
454
+ }
455
+ }
456
+ // Destination folders the run created (newest first): each only while it is empty, deepest first.
457
+ for (const { e } of [...mine].reverse()) {
458
+ if (e.t !== "folder-created") continue;
459
+ let removedChild = null;
460
+ for (const dir of foldersUpTo(e.path, e.created) ?? []) {
461
+ let entries ;
462
+ try { entries = await readdir(dir); } catch (err) {
463
+ if ((err ).code === "ENOENT") { removedChild = dir; continue; } // gone already
464
+ r.errors.push(`could not read ${dir}: ${msg(err)}`);
465
+ break;
466
+ }
467
+ if (entries.some((x) => removedChild === null || x !== basename(removedChild))) { r.foldersKept.push(dir); break; }
468
+ if (!dry) {
469
+ await begin();
470
+ try { await rmdir(dir); } catch (err) {
471
+ if ((err ).code === "ENOTEMPTY") r.foldersKept.push(dir);
472
+ else r.errors.push(`could not remove ${dir}: ${msg(err)}`);
473
+ break;
474
+ }
475
+ }
476
+ r.foldersRemoved.push(dir);
477
+ removedChild = dir;
478
+ }
479
+ }
480
+ } catch (e) {
481
+ await (api )?.close();
482
+ throw e;
483
+ }
484
+
485
+ // ---------- T3 ----------
486
+ const defaults = new Map ();
487
+ for (const { e } of mine) {
488
+ if (e.t !== "project-default-set") continue;
489
+ const d = defaults.get(e.projectId);
490
+ if (d) d.next = e.next; // the run's first `previous` is the original; its last `next` is what it left
491
+ else defaults.set(e.projectId, { previous: e.previous, next: e.next });
492
+ }
493
+ const instEntries = mine.map((x) => x.e).filter((e) => e.t === "instance-pinned" || e.t === "instance-updated");
494
+ const threadIds = [];
495
+ for (const { e } of mine) {
496
+ const ids = e.t === "imported" ? [e.threadId] : e.t === "import-attempt" ? e.items.map((x) => (isObj(x) ? x.threadId : undefined)) : [];
497
+ for (const id of ids) {
498
+ if (!isStr(id)) { r.errors.push(`skipped a malformed ${e.t} item (threadId missing)`); continue; }
499
+ if (!threadIds.includes(id)) threadIds.push(id);
500
+ }
501
+ }
502
+ const parkedIds = [];
503
+ for (const { e } of mine) {
504
+ if (e.t !== "import-attempt" || !Array.isArray(e.parked)) continue;
505
+ for (const x of e.parked) {
506
+ const id = isObj(x) ? x.threadId : undefined;
507
+ if (isStr(id) && !threadIds.includes(id) && !parkedIds.includes(id)) parkedIds.push(id);
508
+ }
509
+ }
510
+ // Merges (Task 23). Each undo is a swap: bring the old thread back (if the run archived it), then archive the
511
+ // revision thread. An undone merge (revision removed, or already gone) swaps; a merge whose revision was continued
512
+ // since is kept whole and reported. Also undone: a thread the run archived without a `merged` entry (crash between
513
+ // thread-archived and merged), and a revision thread the run UNarchived (re-merge after a rollback) whose revision is
514
+ // removed. The revision thread is archived only once its old thread is active, so no session ends with no thread.
515
+ for (const f of r.filesKeptModified) kept.set(keyOf(f), "revision continued");
516
+ for (const f of r.filesKeptActive) kept.set(keyOf(f), "revision in use");
517
+ for (const f of r.filesKeptRewritten) kept.set(keyOf(f), "revision rewritten");
518
+ const removed = new Set(r.filesRemoved.map(keyOf));
519
+ const gone = async (file ) => removed.has(keyOf(file)) || !(await exists(file).catch(() => true));
520
+ const swaps = [];
521
+ const addSwap = (old , rev ) => {
522
+ if (swaps.some((x) => x.old === old && x.rev === rev)) return;
523
+ swaps.push({ old, rev });
524
+ };
525
+ const keptOld = new Set ();
526
+ for (const { e } of mine) {
527
+ if (e.t !== "merged") continue;
528
+ const why = kept.get(keyOf(e.revisionFile));
529
+ if (why) { r.mergesKept.push({ nativeId: e.nativeId, revisionFile: e.revisionFile, reason: why }); keptOld.add(e.oldThreadId); continue; }
530
+ if (!(await gone(e.revisionFile))) {
531
+ r.errors.push(`merge of ${e.nativeId} not undone: its revision ${e.revisionFile} is still there`);
532
+ keptOld.add(e.oldThreadId);
533
+ continue;
534
+ }
535
+ addSwap(e.oldThreadId, e.newThreadId);
536
+ }
537
+ const revisionsOfRun = mine.flatMap(({ e }) => (e.t === "file-written" && e.revisionOf && isStr(e.path) ? [{ path: e.path, nativeId: e.revisionOf.nativeId, rev: basename(e.path, ".jsonl") }] : []));
538
+ const mergedOld = new Set(mine.flatMap(({ e }) => (e.t === "merged" ? [e.oldThreadId] : [])));
539
+ for (const { e } of mine) {
540
+ if (e.t !== "thread-archived" || keptOld.has(e.threadId) || mergedOld.has(e.threadId)) continue;
541
+ // The run's own revision thread, archived back by a follow that stopped before its swap (the copy changed during
542
+ // the import): it stays archived; there is no old thread to bring back.
543
+ if (revisionsOfRun.some((w) => e.threadId.endsWith(`:${w.rev}`))) continue;
544
+ let keep = false;
545
+ let any = false;
546
+ for (const w of revisionsOfRun) {
547
+ if (!e.threadId.endsWith(`:${w.nativeId}`)) continue;
548
+ if (kept.has(keyOf(w.path))) { keep = true; continue; }
549
+ any = true;
550
+ addSwap(e.threadId, `${e.threadId.slice(0, -w.nativeId.length)}${w.rev}`);
551
+ }
552
+ if (!keep && !any) addSwap(e.threadId, null);
553
+ }
554
+ for (const { e } of mine) {
555
+ if (e.t !== "thread-unarchived") continue;
556
+ const w = revisionsOfRun.find((x) => e.threadId.endsWith(`:${x.rev}`));
557
+ if (!w || kept.has(keyOf(w.path)) || !(await gone(w.path))) continue;
558
+ if (!swaps.some((x) => x.rev === e.threadId)) addSwap(null, e.threadId);
559
+ }
560
+
561
+ // Session lineages (Task 23): an original thread and the revision threads merged from it. THE invariant of every
562
+ // archive below (one guard, `mayArchive`): never archive a thread if that leaves its lineage without an active thread,
563
+ // judged on the freshly read thread list plus what this rollback already changed.
564
+ const lineage = new Map ();
565
+ const link = (a , b ) => {
566
+ const la = lineage.get(a) ?? new Set([a]);
567
+ const lb = lineage.get(b) ?? new Set([b]);
568
+ const all = new Set([...la, ...lb]);
569
+ for (const id of all) lineage.set(id, all);
570
+ };
571
+ for (const { e } of mine) if (e.t === "merged") link(e.oldThreadId, e.newThreadId);
572
+ for (const sw of swaps) if (sw.old !== null && sw.rev !== null) link(sw.old, sw.rev);
573
+ for (const { e } of mine) {
574
+ if (e.t !== "imported") continue;
575
+ const w = revisionsOfRun.find((x) => x.rev === e.nativeId);
576
+ if (w && e.threadId.endsWith(`:${w.rev}`)) link(`${e.threadId.slice(0, -w.rev.length)}${w.nativeId}`, e.threadId);
577
+ }
578
+ /**
579
+ * Threads of revisions this rollback keeps (a merge kept whole, or a revision a later run journaled again and swapped
580
+ * in): the session continues there, so they are never archived here, nor have their carried title or state reverted.
581
+ */
582
+ const keptNew = new Set(mine.flatMap(({ e }) => {
583
+ if (e.t === "merged") return kept.has(keyOf(e.revisionFile)) ? [e.newThreadId] : [];
584
+ if (e.t !== "imported") return [];
585
+ const w = revisionsOfRun.find((x) => x.rev === e.nativeId);
586
+ return w && e.threadId.endsWith(`:${w.rev}`) && kept.has(keyOf(w.path)) ? [e.threadId] : [];
587
+ }));
588
+ const needsReview = (threadId , reason ) => {
589
+ if (!r.needsReview.some((x) => x.threadId === threadId)) r.needsReview.push({ threadId, reason });
590
+ };
591
+ const mayArchive = (id , lv ) => {
592
+ const group = lineage.get(id);
593
+ if (!group) return true;
594
+ if ([...group].some((t) => t !== id && lv.get(t) === false)) return true;
595
+ const missing = [...group].filter((t) => t !== id && !lv.has(t));
596
+ needsReview(id, missing.length > 0
597
+ ? `left active: the session's other thread (${missing.join(", ")}) no longer exists in T3 Code, so this is its only thread`
598
+ : "left active: it is the session's only active thread (its original thread is archived and could not be brought back)");
599
+ return false;
600
+ };
601
+
602
+ const needT3 = organizeEntries.length > 0 || defaults.size > 0 || threadIds.length > 0 || swaps.length > 0 || (deps.instances === true && instEntries.length > 0);
603
+
604
+ if (needT3) await connectT3Once();
605
+ try {
606
+ // organize (first: the newest changes of a run that imported and then organized)
607
+ if (organizeEntries.length > 0) {
608
+ if (!api) r.errors.push(`organize changes not undone: ${r.t3Unavailable ?? "T3 Code not connected"}`);
609
+ else {
610
+ // Only the first read of T3 is caught (nothing changed yet); a journal failure (JournalWriteError, naming what
611
+ // was already reverted) stops the rollback like every other journal failure here. r.organize fills as it goes.
612
+ // A follow's title and settled state carried to its revision thread (src/ops/follow.ts) stay with that thread:
613
+ // the swap below archives it and brings the old thread back with its own. (T3 cannot clear a settled override,
614
+ // so a carry onto a thread that had none could not be put back anyway.)
615
+ const swappedOut = new Set(swaps.flatMap((sw) => (sw.old !== null && sw.rev !== null ? [sw.rev] : [])));
616
+ // A kept follow's revision thread (keptNew) keeps them too: it is the thread the user continues.
617
+ const carried = new Set(mine.flatMap(({ e }) => (e.t === "followed" && isStr(e.newThread) && (swappedOut.has(e.newThread) || keptNew.has(e.newThread)) ? [e.newThread] : [])));
618
+ const toUndo = organizeEntries.filter((e) => !(e.t === "organize-change" && carried.has(e.target) && (e.kind === "title" || e.kind === "unsettle" || e.kind === "settle")));
619
+ try {
620
+ await undoOrganizeEntries(toUndo, targetRunId, { api, journal: j, begin, dryRun: dry, platform, history: all }, r.organize);
621
+ } catch (e) {
622
+ if (!(e instanceof OrganizeReadError)) throw e;
623
+ r.errors.push(`organize changes not undone: ${e.message}`);
624
+ }
625
+ // An archive put back changes which threads are archived: read them again below when needed.
626
+ if (r.organize.some((x) => x.kind === "archive" && x.status === "reverted")) live = null;
627
+ }
628
+ }
629
+
630
+ // defaults
631
+ if (defaults.size > 0) {
632
+ let projects = null;
633
+ if (api) {
634
+ try { projects = await api.listProjects(); } catch (e) { r.t3Unavailable ??= `could not read T3 projects (${msg(e)})`; }
635
+ }
636
+ for (const [projectId, d] of defaults) {
637
+ if (!api || !projects) { r.defaultsSkipped.push({ projectId, reason: r.t3Unavailable ?? "T3 Code not connected" }); continue; }
638
+ const p = projects.find((x) => x.id === projectId);
639
+ if (!p) { r.defaultsSkipped.push({ projectId, reason: "project no longer exists in T3 Code" }); continue; }
640
+ const cur = selection(p.defaultModelSelection).instanceId;
641
+ const prev = selection(d.previous);
642
+ const next = selection(d.next).instanceId;
643
+ if (cur === prev.instanceId) continue; // already restored
644
+ if (cur !== next) { r.defaultsSkipped.push({ projectId, reason: `changed since (now ${cur ?? "none"})` }); continue; }
645
+ if (!dry) {
646
+ const id = await begin();
647
+ let previous ;
648
+ try {
649
+ ({ previous } = await api.setProjectDefault(projectId, prev.instanceId, prev.model));
650
+ } catch (e) {
651
+ r.defaultsSkipped.push({ projectId, reason: `failed: ${msg(e)}` });
652
+ continue;
653
+ }
654
+ await j.append({ t: "project-default-set", runId: id, projectId, previous, next: d.previous });
655
+ }
656
+ r.defaultsRestored.push(projectId);
657
+ }
658
+ }
659
+
660
+ // instances (newest first, so a run that changed one twice ends at its first `previous`)
661
+ for (const e of [...instEntries].reverse()) {
662
+ const c = { instanceId: e.instanceId, kind: e.t === "instance-pinned" ? "pinned" : "updated", previous: e.previous, next: e.next, status: "listed" };
663
+ r.instanceChanges.unshift(c);
664
+ if (!deps.instances) continue;
665
+ if (!api) { c.status = "failed"; c.note = r.t3Unavailable ?? "T3 Code not connected"; continue; }
666
+ try {
667
+ await restoreInstance(api, e, c, { dry, platform, begin, j });
668
+ } catch (err) {
669
+ c.status = "failed";
670
+ c.note = msg(err);
671
+ }
672
+ }
673
+
674
+ // threads
675
+ if (live === null && (threadIds.length > 0 || swaps.length > 0) && api) {
676
+ try { live = new Map((await api.listThreads()).map((t) => [t.id, t.archived] )); } catch (e) { r.errors.push(`could not read T3 threads: ${msg(e)}`); }
677
+ }
678
+ if (swaps.length > 0) {
679
+ const lv = live;
680
+ if (!api || !lv) r.errors.push(`merge threads not restored: ${r.t3Unavailable ?? "T3 threads unreadable"}`);
681
+ else {
682
+ // `lv` is updated in a dry run too: it is the projected state the guard judges.
683
+ for (const sw of swaps) {
684
+ if (sw.old !== null && lv.get(sw.old) === true) {
685
+ if (!dry) {
686
+ const rid = await begin();
687
+ try { await api.unarchiveThread(sw.old); } catch (e) {
688
+ r.errors.push(`could not unarchive thread ${sw.old}: ${msg(e)}`);
689
+ if (sw.rev !== null && lv.get(sw.rev) === false) needsReview(sw.rev, `left active: its original thread ${sw.old} could not be unarchived`);
690
+ continue;
691
+ }
692
+ await j.append({ t: "thread-unarchived", runId: rid, threadId: sw.old });
693
+ }
694
+ lv.set(sw.old, false);
695
+ if (!r.threadsUnarchived.includes(sw.old)) r.threadsUnarchived.push(sw.old);
696
+ }
697
+ if (sw.rev === null || lv.get(sw.rev) !== false) continue; // archived already, or gone
698
+ if (!mayArchive(sw.rev, lv)) continue;
699
+ if (!dry) {
700
+ const rid = await begin();
701
+ try { await api.archiveThread(sw.rev); } catch (e) { r.errors.push(`could not archive thread ${sw.rev}: ${msg(e)}`); continue; }
702
+ await j.append({ t: "thread-archived", runId: rid, threadId: sw.rev });
703
+ }
704
+ lv.set(sw.rev, true);
705
+ if (!r.threadsArchived.includes(sw.rev)) r.threadsArchived.push(sw.rev);
706
+ }
707
+ }
708
+ }
709
+ if (threadIds.length > 0) {
710
+ const lv = live;
711
+ if (lv) {
712
+ r.threadsVerified = true;
713
+ r.threadsToReview = threadIds.filter((id) => lv.has(id));
714
+ if (deps.archiveThreads && api) {
715
+ for (const id of r.threadsToReview) {
716
+ if (lv.get(id) || r.threadsArchived.includes(id)) continue; // already archived
717
+ if (keptNew.has(id)) continue; // a kept merge's revision thread: the session continues there
718
+ if (!mayArchive(id, lv)) continue;
719
+ if (!dry) {
720
+ const rid = await begin();
721
+ try {
722
+ await api.archiveThread(id);
723
+ } catch (e) {
724
+ r.errors.push(`could not archive thread ${id}: ${msg(e)}`);
725
+ continue;
726
+ }
727
+ await j.append({ t: "thread-archived", runId: rid, threadId: id });
728
+ }
729
+ lv.set(id, true);
730
+ r.threadsArchived.push(id);
731
+ }
732
+ }
733
+ } else {
734
+ r.threadsToReview = [...threadIds];
735
+ }
736
+ }
737
+ // Parked copies: listed only when T3's thread list was read and their thread exists.
738
+ if (live !== null) r.parkedThreads = parkedIds.filter((id) => (live ).has(id));
739
+ } finally {
740
+ await api?.close();
741
+ }
742
+
743
+ if (rb !== null) {
744
+ r.runId = rb;
745
+ const at = new Date(now()).toISOString();
746
+ const partial = r.errors.length > 0 || r.unquarantineConflicts.length > 0 || r.unquarantineFailed.length > 0 || r.defaultsSkipped.length > 0
747
+ || r.instanceChanges.some((c) => c.status === "failed") || r.organize.some((x) => x.status === "failed");
748
+ await j.append({ t: "rolled-back", runId: rb, targetRunId, at });
749
+ await j.append({ t: "run-end", runId: rb, at, status: partial ? "partial" : "ok" });
750
+ }
751
+ return r;
752
+ }
753
+
754
+ const DEFAULT_INSTANCE = "claudeAgent";
755
+
756
+ async function restoreInstance(
757
+ api ,
758
+ e ,
759
+ c ,
760
+ x ,
761
+ ) {
762
+ const cur = (await api.providerInstances()).find((i) => i.instanceId === e.instanceId);
763
+ if (!cur) { c.status = "not-restorable"; c.note = "the instance no longer exists"; return; }
764
+ const same = (a , b ) => (a === null || b === null ? a === b : sameCwd(a, b, x.platform));
765
+
766
+ if (e.t === "instance-pinned") {
767
+ const prev = e.previous.homePath;
768
+ if (e.instanceId === DEFAULT_INSTANCE) { c.status = "not-restorable"; c.note = "claudeAgent stays pinned to ~/.claude"; return; }
769
+ if (prev === null) { c.status = "not-restorable"; c.note = "it had no explicit home before; T3 Code has no way to unpin"; return; }
770
+ if (same(cur.homePath, prev)) { c.status = "already"; return; }
771
+ if (!same(cur.homePath, e.next.homePath)) { c.status = "changed-since"; c.note = `home is now ${cur.homePath ?? "unset"}`; return; }
772
+ if (!x.dry) {
773
+ const id = await x.begin();
774
+ await api.pinInstanceHome(e.instanceId, prev);
775
+ await x.j.append({ t: "instance-pinned", runId: id, instanceId: e.instanceId, previous: { homePath: cur.homePath }, next: { homePath: prev } });
776
+ }
777
+ c.status = "restored";
778
+ return;
779
+ }
780
+
781
+ const prev = e.previous, next = e.next;
782
+ // A null previous (no explicit label/colour before) cannot be written back: T3 Code has no "clear" for it.
783
+ const cannotClear = prev.accentColor === null && cur.accentColor !== null;
784
+ const note = cannotClear ? "the accent colour cannot be cleared through T3 Code; change it in T3 Code's settings" : undefined;
785
+ const homeBack = prev.homePath !== null && next.homePath !== null && !same(prev.homePath, next.homePath) && e.instanceId !== DEFAULT_INSTANCE;
786
+ const ap = {};
787
+ if (prev.displayName !== null && prev.displayName !== cur.displayName) ap.displayName = prev.displayName;
788
+ if (prev.accentColor !== null && prev.accentColor !== cur.accentColor) ap.accentColor = prev.accentColor;
789
+ const homeNeeded = homeBack && !same(cur.homePath, prev.homePath);
790
+ if (ap.displayName === undefined && ap.accentColor === undefined && !homeNeeded) {
791
+ c.status = cannotClear && cur.accentColor === next.accentColor && cur.displayName === (next.displayName ?? cur.displayName) ? "not-restorable" : "already";
792
+ c.note = note;
793
+ return;
794
+ }
795
+ if ((next.displayName !== null && cur.displayName !== next.displayName) || cur.accentColor !== next.accentColor) {
796
+ c.status = "changed-since";
797
+ c.note = `now ${JSON.stringify(cur.displayName)} ${cur.accentColor ?? "no colour"}`;
798
+ return;
799
+ }
800
+ const notes = note ? [note] : [];
801
+ if (!x.dry) {
802
+ const id = await x.begin();
803
+ if (ap.displayName !== undefined || ap.accentColor !== undefined) await api.updateInstanceAppearance(e.instanceId, ap);
804
+ if (homeBack) await api.pinInstanceHome(e.instanceId, prev.homePath );
805
+ await x.j.append({
806
+ t: "instance-updated", runId: id, instanceId: e.instanceId,
807
+ previous: { displayName: cur.displayName, accentColor: cur.accentColor, homePath: cur.homePath },
808
+ next: { displayName: ap.displayName ?? cur.displayName, accentColor: ap.accentColor ?? cur.accentColor, homePath: homeBack ? prev.homePath : cur.homePath },
809
+ });
810
+ }
811
+ c.status = "restored";
812
+ if (notes.length) c.note = notes.join("; ");
813
+ }
814
+
815
+ // ---------------- runs ----------------
816
+
817
+
818
+
819
+
820
+
821
+
822
+
823
+
824
+
825
+
826
+
827
+
828
+
829
+
830
+
831
+
832
+
833
+ /** One summary per run id, in journal order (mtime-bump/restore bookkeeping alone does not make a run). */
834
+ export function listRuns(entries ) {
835
+ const byId = new Map ();
836
+ const get = (id ) => {
837
+ let s = byId.get(id);
838
+ if (!s) {
839
+ s = { runId: id, at: null, command: null, status: "-", rolledBackBy: null, counts: { imported: 0, importFailed: 0, filesWritten: 0, quarantined: 0, unquarantined: 0, defaults: 0, instances: 0, projects: 0, archived: 0, merged: 0, organized: 0, organizeReverted: 0 } };
840
+ byId.set(id, s);
841
+ }
842
+ return s;
843
+ };
844
+ for (const e of entries) {
845
+ if (e.t === "mtime-bump" || e.t === "mtime-restore" || e.t === "update") continue; // update: t3sm update, not a run to roll back
846
+ const s = get(e.runId);
847
+ switch (e.t) {
848
+ case "run-start": s.at = e.at; s.command = e.command; if (s.status === "-") s.status = "incomplete"; break;
849
+ case "run-end": s.status = e.status; if (typeof e.held === "number" && e.held > 0) s.held = e.held; break;
850
+ case "imported": s.counts.imported++; break;
851
+ case "import-failed": s.counts.importFailed++; break;
852
+ case "file-written": break; // counted below from the writes that really happened (effectiveWrites)
853
+ case "merged": s.counts.merged++; break;
854
+ case "quarantined": s.counts.quarantined++; break;
855
+ case "unquarantined": s.counts.unquarantined++; break;
856
+ case "project-default-set": s.counts.defaults++; break;
857
+ case "instance-created": case "instance-pinned": case "instance-updated": s.counts.instances++; break;
858
+ case "project-created": s.counts.projects++; break;
859
+ case "thread-archived": s.counts.archived++; break;
860
+ case "organize-change": s.counts.organized++; break;
861
+ case "organize-undone": s.counts.organizeReverted++; break;
862
+ case "rolled-back": get(e.targetRunId).rolledBackBy = e.runId; break;
863
+ default: break;
864
+ }
865
+ }
866
+ for (const w of effectiveWrites(entries)) get(w.runId).counts.filesWritten++;
867
+ return [...byId.values()];
868
+ }