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,415 @@
1
+ // Reversible quarantine of backup folders and mirror copies (spec §4.3 rule 4).
2
+ // Writing functions here REQUIRE the caller to hold the state-dir lock (acquireLock) and to have run
3
+ // recoverPendingMtimes first; they never take the lock themselves.
4
+ //
5
+ // Every move stays inside one account home (same volume) and never replaces anything (moveEntry): a FILE moves by
6
+ // hard link + unlink (EEXIST at the destination = nothing changed), a DIRECTORY by rename after checking the target is
7
+ // free (a non-empty target makes rename fail). File times, contents and ACLs travel with the entry. Cross-device
8
+ // (EXDEV) or a filesystem without hard links aborts that item; t3sm never copies and deletes. Each move is journaled
9
+ // (`quarantined`) right AFTER it succeeds; if the journal cannot be written the entry is moved back and the error
10
+ // aborts the command, so nothing ever sits in quarantine without a journal line that can undo it.
11
+
12
+ import { link, lstat, mkdir, readdir, rename, rmdir, unlink } from "node:fs/promises";
13
+ import { homedir } from "node:os";
14
+ import { basename, dirname, extname, join } from "node:path";
15
+
16
+
17
+ import { expandHome, normalizeCwd, pathKey, sameCwd } from "../core/paths.js";
18
+ import { ACTIVE_WINDOW_MS, isActive } from "../core/activity.js";
19
+ import { MoveRefused, publishNoClobber } from "../core/fsutil.js";
20
+ import { compareCopies } from "../plan/ownership.js";
21
+
22
+
23
+ export const QUARANTINE_DIR = "session-manager-quarantine";
24
+
25
+ /** The filesystem calls a move uses; injected by tests (EXDEV, a file appearing at the destination). */
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+
36
+
37
+
38
+
39
+
40
+
41
+
42
+
43
+
44
+
45
+
46
+
47
+
48
+
49
+ /** A skip reason in the catalogue's words (moves.why.*). */
50
+
51
+ const why = (key , vars ) => ({ key, ...(vars ? { vars } : {}) });
52
+
53
+ /** The journal could not be written around a move. Aborts the command (exit 1). */
54
+ export class JournalWriteError extends Error {
55
+ name = "JournalWriteError";
56
+ }
57
+
58
+ /** A move refused before anything changed: destination exists, other drive, no hard links (shared with fsutil). */
59
+ export { MoveRefused };
60
+
61
+ const RETRYABLE = new Set(["EPERM", "EBUSY", "EACCES"]);
62
+ const sleep = (ms ) => new Promise((r) => setTimeout(r, ms));
63
+
64
+ async function retrying (fn , retryable ) {
65
+ for (let attempt = 0; ; attempt++) {
66
+ try {
67
+ return await fn();
68
+ } catch (e) {
69
+ const code = (e ).code ?? "";
70
+ if (!retryable.has(code) || attempt >= 4) throw e;
71
+ await sleep(25 * (attempt + 1));
72
+ }
73
+ }
74
+ }
75
+
76
+ /** node:fs with a few retries for the transient sharing errors Windows raises (antivirus, indexer). */
77
+ export const nodeMoveFs = {
78
+ rename: (a, b) => retrying(() => rename(a, b), RETRYABLE),
79
+ link: (a, b) => retrying(() => link(a, b), new Set(["EBUSY"])),
80
+ unlink: (p) => retrying(() => unlink(p), RETRYABLE),
81
+ };
82
+
83
+ const errCode = (e ) => (e ).code ?? (e instanceof Error ? e.message : String(e));
84
+ const msg = (e ) => (e instanceof Error ? e.message : String(e));
85
+
86
+ async function lstatOrNull(p ) {
87
+ try {
88
+ return await lstat(p);
89
+ } catch (e) {
90
+ if ((e ).code === "ENOENT") return null;
91
+ throw e;
92
+ }
93
+ }
94
+
95
+ /**
96
+ * Moves `from` to `to` without ever replacing an existing entry (node's rename replaces a target FILE).
97
+ * File: link(from, to) then unlink(from); EEXIST -> MoveRefused, nothing changed; no hard-link support -> MoveRefused.
98
+ * Directory: refused when `to` exists, else rename (a non-empty target makes rename fail anyway).
99
+ * The parent of `to` must exist.
100
+ */
101
+ export async function moveEntry(from , to , fs = nodeMoveFs) {
102
+ const st = await lstat(from);
103
+ if (st.isDirectory()) {
104
+ if ((await lstatOrNull(to)) !== null) throw new MoveRefused(`${to} already exists; nothing was changed`, "EEXIST");
105
+ try {
106
+ await fs.rename(from, to);
107
+ } catch (e) {
108
+ const code = errCode(e);
109
+ if (code === "EEXIST" || code === "ENOTEMPTY") throw new MoveRefused(`${to} already exists; nothing was changed`, "EEXIST");
110
+ throw e;
111
+ }
112
+ return;
113
+ }
114
+ await publishNoClobber(from, to, fs);
115
+ }
116
+
117
+ /** Human reason for a failed move. */
118
+ export function moveFailure(e ) {
119
+ if (e instanceof MoveRefused) return e.message;
120
+ const code = errCode(e);
121
+ if (code === "EXDEV") return "on another drive than its account home (EXDEV); not moved (t3sm never copies and deletes)";
122
+ return `could not move (${code})`;
123
+ }
124
+
125
+ const BACKUP_RE = /\.bak(-\d{8}-\d{6})?$/;
126
+
127
+ export function isBackupDirName(name ) {
128
+ return name.startsWith(".bak-") || BACKUP_RE.test(name);
129
+ }
130
+
131
+ /** Direct children of `<accountHome>/projects` that are backup folders (`.bak-*` or `*.bak[-YYYYMMDD-HHMMSS]`). */
132
+ export async function findBackupDirs(accountHome ) {
133
+ const projects = join(accountHome, "projects");
134
+ let ents;
135
+ try {
136
+ ents = await readdir(projects, { withFileTypes: true });
137
+ } catch (e) {
138
+ const code = (e ).code;
139
+ if (code === "ENOENT" || code === "ENOTDIR") return [];
140
+ throw e;
141
+ }
142
+ return ents.filter((e) => e.isDirectory() && isBackupDirName(e.name)).map((e) => join(projects, e.name)).sort();
143
+ }
144
+
145
+ /** First file under `dir` (symlinks not followed) modified after `cutoff`, relative to `dir`; null if none. */
146
+ async function findActive(dir , cutoff ) {
147
+ const stack = [dir];
148
+ while (stack.length > 0) {
149
+ const d = stack.pop() ;
150
+ for (const e of await readdir(d, { withFileTypes: true })) {
151
+ const p = join(d, e.name);
152
+ if (e.isDirectory()) { stack.push(p); continue; }
153
+ const st = await lstatOrNull(p);
154
+ if (st && st.mtimeMs > cutoff) return p.slice(dir.length + 1);
155
+ }
156
+ }
157
+ return null;
158
+ }
159
+
160
+ const foldsCase = (platform ) => platform === "win32" || platform === "darwin";
161
+
162
+ function key(p , platform ) {
163
+ return pathKey(p, platform);
164
+ }
165
+
166
+ /** `child` lies strictly inside directory `parent` (path identity per platform). */
167
+ export function isInside(child , parent , platform = process.platform) {
168
+ const c = key(child, platform), p = key(parent, platform);
169
+ return c.startsWith(p.endsWith("/") ? p : `${p}/`);
170
+ }
171
+
172
+ /** A raw path string with a `..` segment (journal entries carrying one are never acted on). */
173
+ export function hasDotDot(p ) {
174
+ return p.split(/[\\/]+/).includes("..");
175
+ }
176
+
177
+ /**
178
+ * `dir` relative to `parent` ("/"-separated, original case of `dir`), compared case-insensitively on win32/darwin.
179
+ * "" when they are the same folder; null when `dir` is not inside `parent` or the result would be absolute or climb
180
+ * (`..`). Never path.relative: posix relative is case-sensitive, so a darwin case variant would climb out.
181
+ */
182
+ export function subdirOf(parent , dir , platform = process.platform) {
183
+ const fold = foldsCase(platform);
184
+ const p = normalizeCwd(parent, platform), d = normalizeCwd(dir, platform);
185
+ const pk = fold ? p.toLowerCase() : p;
186
+ if ((fold ? d.toLowerCase() : d) === pk) return "";
187
+ const prefix = pk.endsWith("/") ? pk : `${pk}/`;
188
+ const head = d.slice(0, prefix.length);
189
+ if ((fold ? head.toLowerCase() : head) !== prefix) return null; // also catches case folding that changes length
190
+ const rel = d.slice(prefix.length);
191
+ if (rel === "" || rel.startsWith("/") || /^[A-Za-z]:/.test(rel) || rel.split("/").some((s) => s === ".." || s === "." || s === "")) return null;
192
+ return rel;
193
+ }
194
+
195
+
196
+
197
+ /**
198
+ * The first suffix ("", "-2", "-3", ...) for which every name built by `names(sfx)` is free in `dir` (on disk and
199
+ * not reserved earlier in this run, which matters for dry runs).
200
+ */
201
+ async function pickFree(dir , names , ctx ) {
202
+ for (let n = 1; n < 100_000; n++) {
203
+ const sfx = n === 1 ? "" : `-${n}`;
204
+ const paths = names(sfx).map((x) => join(dir, x));
205
+ let free = true;
206
+ for (const p of paths) {
207
+ if (ctx.reserved.has(key(p, ctx.platform)) || (await lstatOrNull(p)) !== null) { free = false; break; }
208
+ }
209
+ if (free) {
210
+ for (const p of paths) ctx.reserved.add(key(p, ctx.platform));
211
+ return paths;
212
+ }
213
+ }
214
+ throw new Error(`no free name in ${dir}`);
215
+ }
216
+
217
+ /** Move, then journal; a failed journal write moves the entry back (no-clobber) and throws JournalWriteError. */
218
+ async function moveAndJournal(from , to , reason , ctx ) {
219
+ await mkdir(dirname(to), { recursive: true });
220
+ await moveEntry(from, to, ctx.fs);
221
+ try {
222
+ await ctx.j.append({ t: "quarantined", runId: ctx.runId, from, to, reason } );
223
+ } catch (e) {
224
+ try {
225
+ await moveEntry(to, from, ctx.fs);
226
+ } catch (back) {
227
+ throw new JournalWriteError(`Could not write the journal (${msg(e)}) and could not move ${to} back to ${from} (${moveFailure(back)}). Move it back by hand.`);
228
+ }
229
+ throw new JournalWriteError(`Could not write the journal (${msg(e)}); ${from} was left in place.`);
230
+ }
231
+ }
232
+
233
+ function ctxOf(j , runId , opts ) {
234
+ return { fs: opts.fs ?? nodeMoveFs, j, runId, reserved: new Set(), platform: opts.platform ?? process.platform };
235
+ }
236
+
237
+ /**
238
+ * Moves backup folders of one account to `<accountHome>/session-manager-quarantine/backups/<name>` (collisions get
239
+ * `-2`, `-3`). Skips (and reports) a folder that is not a backup child of `<accountHome>/projects`, is missing, or
240
+ * holds a file changed within ACTIVE_WINDOW_MS. Throws only JournalWriteError (after moving the folder back).
241
+ */
242
+ export async function quarantine(dirs , accountHome , j , runId , opts = {}) {
243
+ const ctx = ctxOf(j, runId, opts);
244
+ const now = opts.now ?? Date.now;
245
+ const report = { moved: [], skipped: [] };
246
+ const projects = join(accountHome, "projects");
247
+ const dest = join(accountHome, QUARANTINE_DIR, "backups");
248
+ for (const dir of dirs) {
249
+ const skip = (reason , say ) => void report.skipped.push({ path: dir, reason, ...(say ? { say } : {}) });
250
+ try {
251
+ if (!sameCwd(dirname(dir), projects, ctx.platform) || !isBackupDirName(basename(dir))) { skip(`not a backup folder of ${accountHome}`, why("moves.why.notBackup")); continue; }
252
+ const st = await lstatOrNull(dir);
253
+ if (st === null) { skip("missing", why("moves.why.missing")); continue; }
254
+ if (!st.isDirectory()) { skip("not a folder", why("moves.why.notFolder")); continue; }
255
+ const live = await findActive(dir, now() - ACTIVE_WINDOW_MS);
256
+ if (live !== null) { skip(`active (${live} changed in the last 10 minutes)`, why("moves.why.activeFile", { file: live })); continue; }
257
+ const [to] = await pickFree(dest, (sfx) => [basename(dir) + sfx], ctx);
258
+ if (!opts.dryRun) await moveAndJournal(dir, to , "backup-dir", ctx);
259
+ report.moved.push({ from: dir, to: to });
260
+ } catch (e) {
261
+ if (e instanceof JournalWriteError) throw e;
262
+ skip(moveFailure(e));
263
+ }
264
+ }
265
+ return report;
266
+ }
267
+
268
+ /**
269
+ * Moves each plan mirror copy to `<its account home>/session-manager-quarantine/mirror/<encoded project dir>/<file>`,
270
+ * together with its sidecar folder (`<stem>/`, subagents and tool results) when one exists. Right before moving it
271
+ * re-checks: the copy still exists and is not active, the kept copy still exists, and the copy is still identical to
272
+ * or a prefix of the kept one (compareCopies). Forks are never moved. Throws only JournalWriteError.
273
+ */
274
+ export async function dedupe(copies , accounts , j , runId , opts = {}) {
275
+ const ctx = ctxOf(j, runId, opts);
276
+ const now = opts.now ?? Date.now;
277
+ const home = opts.home ?? homedir();
278
+ const report = { moved: [], skipped: [] };
279
+ for (const c of copies) {
280
+ const skip = (reason , say ) => void report.skipped.push({ path: c.path, reason, ...(say ? { say } : {}) });
281
+ if (typeof c.path !== "string" || typeof c.keptPath !== "string" || hasDotDot(c.path) || hasDotDot(c.keptPath)) { skip("invalid plan entry", why("moves.why.invalidEntry")); continue; }
282
+ const acct = accounts.map((a) => expandHome(a.home, home)).find((h) => isInside(c.path, join(h, "projects"), ctx.platform));
283
+ if (acct === undefined) { skip("not inside a configured account's projects folder", why("moves.why.outsideAccount")); continue; }
284
+ const rel = subdirOf(join(acct, "projects"), dirname(c.path), ctx.platform);
285
+ if (rel === null) { skip("not inside a configured account's projects folder", why("moves.why.outsideAccount")); continue; }
286
+ try {
287
+ const st = await lstatOrNull(c.path);
288
+ if (st === null) { skip("missing", why("moves.why.missing")); continue; }
289
+ if (!st.isFile()) { skip("not a file", why("moves.why.notFile")); continue; }
290
+ if (isActive(st.mtimeMs, now())) { skip("active", why("moves.why.active")); continue; }
291
+ if (sameCwd(c.path, c.keptPath, ctx.platform)) { skip("kept copy is the same file", why("moves.why.keptSame")); continue; }
292
+ if ((await lstatOrNull(c.keptPath)) === null) { skip("kept copy missing", why("moves.why.keptMissing")); continue; }
293
+ let relation;
294
+ try {
295
+ relation = await compareCopies(c.path, c.keptPath, ctx.platform);
296
+ } catch (e) {
297
+ skip(`compare failed (${errCode(e)})`, why("moves.why.compareFailed", { code: errCode(e) }));
298
+ continue;
299
+ }
300
+ if (relation !== "identical" && relation !== "b-extends-a") { skip("no longer a mirror", why("moves.why.notMirror")); continue; }
301
+
302
+ const ext = extname(c.path);
303
+ const stem = basename(c.path, ext);
304
+ const sidecarPath = join(dirname(c.path), stem);
305
+ const side = await lstatOrNull(sidecarPath);
306
+ const sidecar = side !== null && side.isDirectory() ? sidecarPath : null;
307
+ if (sidecar !== null) {
308
+ const live = await findActive(sidecar, now() - ACTIVE_WINDOW_MS);
309
+ if (live !== null) { skip(`active (${live} changed in the last 10 minutes)`, why("moves.why.activeFile", { file: live })); continue; }
310
+ }
311
+ const destDir = join(acct, QUARANTINE_DIR, "mirror", ...(rel === "" ? [] : rel.split("/")));
312
+ const [to, sideTo] = await pickFree(destDir, (sfx) => (sidecar ? [stem + sfx + ext, stem + sfx] : [stem + sfx + ext]), ctx);
313
+ // Changed while it was being compared (the session resumed): leave it for the next run.
314
+ const again = await lstatOrNull(c.path);
315
+ if (again === null || again.mtimeMs !== st.mtimeMs || again.size !== st.size) { skip("changed while checking", why("moves.why.changed")); continue; }
316
+ if (opts.dryRun) {
317
+ report.moved.push({ from: c.path, to: to });
318
+ if (sidecar) report.moved.push({ from: sidecar, to: sideTo });
319
+ continue;
320
+ }
321
+ await moveAndJournal(c.path, to , "mirror-copy", ctx);
322
+ if (sidecar) {
323
+ try {
324
+ await moveAndJournal(sidecar, sideTo , "mirror-copy", ctx);
325
+ } catch (e) {
326
+ if (e instanceof JournalWriteError) throw e;
327
+ const why = moveFailure(e);
328
+ // Keep the pair together: put the transcript back too.
329
+ try {
330
+ await moveEntry(to , c.path, ctx.fs);
331
+ } catch (back) {
332
+ report.moved.push({ from: c.path, to: to });
333
+ skip(`sidecar folder ${sidecar} could not be moved (${why}), and the transcript could not be moved back (${moveFailure(back)}); it stays in quarantine at ${to} (journaled, \`t3sm rollback\` restores it)`);
334
+ continue;
335
+ }
336
+ try {
337
+ await ctx.j.append({ t: "unquarantined", runId, from: to , to: c.path } );
338
+ } catch (je) {
339
+ throw new JournalWriteError(`Moved ${to} back to ${c.path} because its sidecar folder could not be moved, but could not journal that (${msg(je)}). Nothing is lost; \`t3sm rollback\` reports it as already restored.`);
340
+ }
341
+ skip(`sidecar folder ${sidecar} could not be moved (${why}); the transcript was left in place`);
342
+ continue;
343
+ }
344
+ }
345
+ report.moved.push({ from: c.path, to: to });
346
+ if (sidecar) report.moved.push({ from: sidecar, to: sideTo });
347
+ } catch (e) {
348
+ if (e instanceof JournalWriteError) throw e;
349
+ skip(moveFailure(e));
350
+ }
351
+ }
352
+ return report;
353
+ }
354
+
355
+ /**
356
+ * Removes now-empty folders from `dir` up to and including `<accountHome>/session-manager-quarantine` (rmdir only:
357
+ * a folder with anything in it stays). Best effort; never throws.
358
+ */
359
+ export async function pruneEmptyQuarantineDirs(dir , accountHome , platform = process.platform) {
360
+ const root = join(accountHome, QUARANTINE_DIR);
361
+ let d = dir;
362
+ while (isInside(d, root, platform) || sameCwd(d, root, platform)) {
363
+ try {
364
+ await rmdir(d);
365
+ } catch {
366
+ return; // ENOTEMPTY, ENOENT, EBUSY...: stop
367
+ }
368
+ if (sameCwd(d, root, platform)) return;
369
+ d = dirname(d);
370
+ }
371
+ }
372
+
373
+
374
+
375
+ /**
376
+ * Entries in each account's quarantine that no `quarantined` journal entry refers to (moved there by hand, or a
377
+ * journal lost). backups/: every child. mirror/: every file, and every folder named like a sibling transcript's stem
378
+ * (a sidecar), found under the encoded project folders. Read-only. Accounts' homes must be expanded.
379
+ */
380
+ export async function findOrphanedQuarantine(accounts , journalEntries , platform = process.platform) {
381
+ const known = new Set ();
382
+ for (const e of journalEntries) {
383
+ if (e.t === "quarantined" && typeof e.to === "string") known.add(key(e.to, platform));
384
+ }
385
+ const out = [];
386
+ const list = async (d ) => {
387
+ try {
388
+ return await readdir(d, { withFileTypes: true });
389
+ } catch (e) {
390
+ const code = errCode(e);
391
+ if (code === "ENOENT" || code === "ENOTDIR") return [];
392
+ throw e;
393
+ }
394
+ };
395
+ for (const a of accounts) {
396
+ const root = join(a.home, QUARANTINE_DIR);
397
+ for (const e of await list(join(root, "backups"))) {
398
+ const p = join(root, "backups", e.name);
399
+ if (!known.has(key(p, platform))) out.push({ accountHome: a.home, path: p, kind: "backup" });
400
+ }
401
+ const walk = async (d ) => {
402
+ const ents = await list(d);
403
+ const stems = new Set(ents.filter((e) => !e.isDirectory() && e.name.endsWith(".jsonl")).map((e) => e.name.slice(0, -".jsonl".length)));
404
+ for (const e of ents) {
405
+ const p = join(d, e.name);
406
+ if (known.has(key(p, platform))) continue;
407
+ if (!e.isDirectory()) { out.push({ accountHome: a.home, path: p, kind: "mirror" }); continue; }
408
+ if (stems.has(e.name)) { out.push({ accountHome: a.home, path: p, kind: "mirror" }); continue; }
409
+ await walk(p);
410
+ }
411
+ };
412
+ await walk(join(root, "mirror"));
413
+ }
414
+ return out;
415
+ }