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,203 @@
1
+ // t3sm quarantine / t3sm dedupe: move backup folders and mirror copies to the account's reversible quarantine.
2
+ // Flow: --dry-run, or no --yes on a non-terminal: list (read-only, no lock) and exit 0 / 2.
3
+ // Otherwise: lock -> recoverPendingMtimes -> list -> confirm -> run-start -> moves -> run-end.
4
+
5
+ import { homedir } from "node:os";
6
+ import { join } from "node:path";
7
+
8
+ import { expandHome, stateDir } from "../../core/paths.js";
9
+ import { ConfigError, NoPlanError, defaultConfig, loadConfig } from "../../core/config.js";
10
+ import { resolveAccounts } from "../../ops/discoverAccounts.js";
11
+ import { Journal, newRunId, recoverPendingMtimes } from "../../core/journal.js";
12
+ import { acquireLock } from "../../core/lock.js";
13
+ import { PLAN_MAX_AGE_MS } from "../../apply/apply.js";
14
+ import { dedupe, findBackupDirs, quarantine, } from "../../ops/quarantine.js";
15
+
16
+ import { latestPlan, readPlan } from "./apply.js";
17
+ import { reportLockBusy } from "../locked.js";
18
+
19
+ import { cliUi, confirm, unknownOption, usageLine } from "../ui.js";
20
+ import { FLAG_SPECS, flagsOf } from "../flags.js";
21
+ import { bulletLines, fitLine, hardLines, noteLines } from "../screen.js";
22
+ import { shownText } from "../../plan/names.js";
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+ /** Flags in `bool`, `--x <value>` options in `valued`; null after printing the error (exit 2). */
33
+ export function parseFlags(args , io , cmd , bool , valued = []) {
34
+ const out = { flags: new Set(), values: new Map() };
35
+ for (let i = 0; i < args.length; i++) {
36
+ const a = args[i] ;
37
+ if (valued.includes(a)) {
38
+ const v = args[i + 1];
39
+ if (v === undefined || v.startsWith("--")) { usageLine(io, "common.needsValue", { option: a, help: `t3sm ${cmd} --help` }); return null; }
40
+ out.values.set(a, v);
41
+ i++;
42
+ } else if (bool.includes(a)) out.flags.add(a);
43
+ else { unknownOption(io, a, cmd); return null; }
44
+ }
45
+ if (out.flags.has("--dry-run") && out.flags.has("--yes")) { usageLine(io, "common.eitherDryRunOrYes"); return null; }
46
+ return out;
47
+ }
48
+
49
+ /** Config accounts (or the discovered accounts when there is no config.json), homes expanded. */
50
+ export async function accountsOf(dir , home , env = {}) {
51
+ const cfg = (await loadConfig(dir, home)) ?? defaultConfig(await resolveAccounts(home, [], env));
52
+ return cfg.accounts.map((a) => ({ ...a, home: expandHome(a.home, home) }));
53
+ }
54
+
55
+ /** The shared localized confirmation (cli/ui.ts), re-exported for the commands that import it from here. */
56
+ export { confirm };
57
+
58
+
59
+
60
+
61
+ /** What one account (or the plan, for dedupe) would move: a heading with the count, each move, then what stays and why. */
62
+ export function renderBatch(ui , b , n , noun , width = ui.width) {
63
+ const { s, t } = ui;
64
+ const who = b.label ?? `${shownText(b.account.id, 60)} (${shownText(b.account.home, 200)})`;
65
+ const head = t("moves.batch", { who, what: t(noun, { n }) }) + (b.preview.skipped.length ? t("moves.skippedCount", { n: b.preview.skipped.length }) : "");
66
+ const out = fitLine(s("title", head), width, 2);
67
+ for (const m of b.preview.moved) {
68
+ out.push(...bulletLines(s, shownText(m.from, 400), width));
69
+ out.push(...hardLines(` ${s("muted", s.caps.unicode ? "→" : "->")} `, shownText(m.to, 400), width, 6));
70
+ }
71
+ for (const k of b.preview.skipped) out.push(...noteLines(s, "warn", t("moves.skip", { path: shownText(k.path, 400), reason: shownText(k.say ? t(k.say.key, k.say.vars) : k.reason, 200) }), width - 2).map((l) => " " + l));
72
+ return out;
73
+ }
74
+
75
+ /**
76
+ * Shared skeleton of quarantine and dedupe. `preview` runs the move with dryRun (read-only); `execute` moves the
77
+ * previewed sources. Exit 5 when an item that passed the preview could not be moved.
78
+ */
79
+ async function runMoves(
80
+ io , p , dir , now , what ,
81
+ preview ,
82
+ execute ,
83
+ ) {
84
+ const yes = p.flags.has("--yes");
85
+ const dry = p.flags.has("--dry-run");
86
+ const j = new Journal(join(dir, "journal.jsonl"));
87
+ const ui = cliUi(io, { now });
88
+ const say = (l ) => io.stdout(l.join("\n") + "\n");
89
+ const show = (bs ) => {
90
+ let total = 0;
91
+ for (const b of bs) {
92
+ if (b.preview.moved.length === 0 && b.preview.skipped.length === 0) continue;
93
+ const n = what.countOf ? what.countOf(b.preview) : b.preview.moved.length;
94
+ total += n;
95
+ say(renderBatch(ui, b, n, what.noun));
96
+ }
97
+ return total;
98
+ };
99
+ const nothing = () => say(noteLines(ui.s, "ok", ui.t(what.nothing), ui.width));
100
+
101
+ if (dry || (!yes && !io.isTTY)) {
102
+ const total = show(await preview(j));
103
+ if (total === 0) { nothing(); return 0; }
104
+ if (dry) { say(["", ...noteLines(ui.s, "info", ui.t("moves.dry", { what: ui.t(what.noun, { n: total }), command: what.command.split(" ")[0] }), ui.width)]); return 0; }
105
+ io.stderr(`${ui.t("moves.needsYes")}\n`);
106
+ return 2;
107
+ }
108
+
109
+ const lock = await acquireLock(dir);
110
+ if (!lock) { reportLockBusy(io); return 0; }
111
+ try {
112
+ const rec = await recoverPendingMtimes(j);
113
+ if (rec.restored.length > 0) io.stderr(`${ui.t("apply.recovered", { n: rec.restored.length })}\n`);
114
+ const batches = await preview(j);
115
+ const total = show(batches);
116
+ if (total === 0) { nothing(); return 0; }
117
+ if (!yes) {
118
+ io.stdout("\n");
119
+ if (!(await confirm(io, ui.t(what.question)))) { io.stdout(`${ui.t("common.nothingChanged")}\n`); return 0; }
120
+ }
121
+
122
+ const runId = newRunId(new Date(now()));
123
+ await j.append({ t: "run-start", runId, at: new Date(now()).toISOString(), command: what.command });
124
+ let moved = 0;
125
+ const failed = [];
126
+ try {
127
+ for (const b of batches) {
128
+ if (b.preview.moved.length === 0) continue;
129
+ const r = await execute(b, j, runId);
130
+ moved += r.moved.length;
131
+ const planned = new Set(b.preview.moved.map((m) => m.from));
132
+ for (const s of r.skipped) {
133
+ if (planned.has(s.path)) failed.push(s);
134
+ }
135
+ }
136
+ } catch (e) {
137
+ await j.append({ t: "run-end", runId, at: new Date(now()).toISOString(), status: "aborted" }).catch(() => {});
138
+ throw e;
139
+ }
140
+ await j.append({ t: "run-end", runId, at: new Date(now()).toISOString(), status: failed.length ? "partial" : "ok" });
141
+ say(["", ...noteLines(ui.s, "ok", ui.t("moves.done", { n: moved, runId }), ui.width)]);
142
+ for (const f of failed) io.stderr(`${ui.t("moves.notMoved", { path: shownText(f.path, 400), reason: shownText(f.reason, 200) })}\n`);
143
+ return failed.length > 0 ? 5 : 0;
144
+ } finally {
145
+ await lock.release();
146
+ }
147
+ }
148
+
149
+ export async function quarantineCommand(args , io , deps = {}) {
150
+ const p = parseFlags(args, io, "quarantine", [...FLAG_SPECS.quarantine.bool]);
151
+ if (!p) return 2;
152
+ const home = deps.home ?? homedir();
153
+ const now = deps.now ?? Date.now;
154
+ const dir = stateDir(io.env, home);
155
+ const accounts = await accountsOf(dir, home, io.env);
156
+ const preview = async (j ) => {
157
+ const out = [];
158
+ for (const a of accounts) {
159
+ const dirs = await findBackupDirs(a.home);
160
+ out.push({ account: a, preview: await quarantine(dirs, a.home, j, "preview", { dryRun: true, now }) });
161
+ }
162
+ return out;
163
+ };
164
+ return runMoves(io, p, dir, now, {
165
+ command: "quarantine", noun: "quarantine.noun", question: "quarantine.confirm", nothing: "quarantine.nothing",
166
+ }, preview, (b, j, runId) => quarantine(b.preview.moved.map((m) => m.from), b.account.home, j, runId, { now }));
167
+ }
168
+
169
+ export async function dedupeCommand(args , io , deps = {}) {
170
+ const spec = flagsOf("dedupe");
171
+ const p = parseFlags(args, io, "dedupe", spec.bool, spec.valued);
172
+ if (!p) return 2;
173
+ const home = deps.home ?? homedir();
174
+ const now = deps.now ?? Date.now;
175
+ const dir = stateDir(io.env, home);
176
+ let plan ;
177
+ try {
178
+ const path = p.values.get("--plan") ?? (await latestPlan(dir));
179
+ if (path === null) throw new NoPlanError();
180
+ plan = await readPlan(path);
181
+ const created = Date.parse(plan.createdAt);
182
+ if (!Number.isFinite(created) || now() - created > PLAN_MAX_AGE_MS || created - now() > 3_600_000) {
183
+ throw new ConfigError(`The plan ${path} is older than 24 h (stale). Run \`t3sm plan\` again.`);
184
+ }
185
+ } catch (e) {
186
+ if (e instanceof ConfigError) { io.stderr(`${e.message}\n`); return 2; }
187
+ throw e;
188
+ }
189
+ const accounts = await accountsOf(dir, home, io.env);
190
+ const copyPaths = new Set(plan.mirrorCopies.map((c) => c.path));
191
+ // One listing for the whole plan; dedupe derives each copy's account (and quarantine folder) itself.
192
+ const preview = async (j ) => {
193
+ const r = await dedupe(plan.mirrorCopies, accounts, j, "preview", { dryRun: true, now, home });
194
+ return [{ account: { id: "mirror copies", home: "plan " + plan.runId, displayName: "", accentColor: null }, preview: r, label: cliUi(io).t("dedupe.who", { runId: shownText(plan.runId) }) }];
195
+ };
196
+ return runMoves(io, p, dir, now, {
197
+ command: `dedupe ${plan.runId}`, noun: "dedupe.noun", question: "dedupe.confirm",
198
+ nothing: "dedupe.nothing", countOf: (r) => r.moved.filter((m) => copyPaths.has(m.from)).length,
199
+ }, preview, (b, j, runId) => {
200
+ const planned = new Set(b.preview.moved.map((m) => m.from));
201
+ return dedupe(plan.mirrorCopies.filter((c) => planned.has(c.path)), accounts, j, runId, { now, home });
202
+ });
203
+ }
@@ -0,0 +1,230 @@
1
+ // t3sm recover <session-id> [--dry-run | --yes] [--allow-untested]
2
+ //
3
+ // Brings back one conversation started in T3 Code whose T3 thread is gone, when t3sm cannot tell that by itself: its
4
+ // transcript names no T3 thread (the plan skips it as `t3-native-unknown`), so only the user knows the thread was
5
+ // deleted. It refuses unless the session was started in T3 Code and no T3 thread t3sm can see holds it. The conversation
6
+ // comes back the way an orphaned one does (organize.sessions.orphaned "copy"): a faithful copy with a new session id,
7
+ // written and imported by apply (journaled; `t3sm rollback --run <id> --archive-threads` undoes it). If the thread
8
+ // still exists in T3 Code where t3sm cannot see it, this makes a duplicate: the screen says so before asking.
9
+ //
10
+ // Writes ask (invariant 12): without a terminal it needs --yes, and --dry-run writes nothing. The real run plans under
11
+ // the lock, after the recovery of pending file times, before it contacts T3 Code (applyPlan's loader: invariant 3).
12
+
13
+ import { homedir } from "node:os";
14
+
15
+ import { expandHome, sameCwd, stateDir, tildePath } from "../../core/paths.js";
16
+ import { defaultConfig, loadConfig } from "../../core/config.js";
17
+ import { applyPlan, } from "../../apply/apply.js";
18
+ import { connectT3, } from "../../t3/api.js";
19
+ import { allAdapters } from "../../sources/registry.js";
20
+
21
+
22
+ import { orphanUuid } from "../../plan/planner.js";
23
+ import { SKIP_WORDS } from "../../plan/report.js";
24
+ import { shownText } from "../../plan/names.js";
25
+ import { freshPlan } from "./plan.js";
26
+ import { defaultFolderEnv } from "./apply.js";
27
+ import { discoverAll, makeEnv } from "./scan.js";
28
+ import { importProgress, renderApplyResult } from "../applyScreen.js";
29
+ import { FAILURES_SHOWN } from "../failures.js";
30
+ import { reportLockBusy } from "../locked.js";
31
+ import { FLAG_SPECS } from "../flags.js";
32
+
33
+ import { cliUi, confirm, unknownOption, usageLine, } from "../ui.js";
34
+ import { noteLines, snugWidth } from "../screen.js";
35
+ import { kv, panel } from "../../ui/components.js";
36
+ import { folderName } from "../words.js";
37
+
38
+
39
+
40
+
41
+
42
+
43
+
44
+
45
+
46
+
47
+
48
+
49
+
50
+ const FLAGS = new Set (FLAG_SPECS.recover.bool);
51
+ /** A session id, or the start of one (at least 8 characters, as `t3sm status` shows them). */
52
+ const ID_RE = /^[0-9A-Fa-f-]{8,36}$/;
53
+
54
+
55
+
56
+
57
+
58
+
59
+ /** "demo (claude 1a2b3c4d)": the project folder's name and the short id, as `t3sm status` names a session. */
60
+ function sessionName(i ) {
61
+ const s = i.session;
62
+ const id = `claude ${shownText(s.nativeId.slice(0, 8), 8)}`;
63
+ return s.cwd ? `${shownText(folderName(s.cwd), 60)} (${id})` : id;
64
+ }
65
+
66
+ /**
67
+ * The plan item that brings session `id` back (a plan built with `recover` matching it), or why it cannot come back:
68
+ * not found, ambiguous (a short id matching two sessions), not started in T3 Code, still in T3 Code (its thread, or a
69
+ * copy already brought back), an account without a T3 Code instance, or skipped for another reason (in use, ...).
70
+ */
71
+ export function pickRecover(plan , id ) {
72
+ const want = id.toLowerCase();
73
+ const items = plan.items.filter((i) => i.session.harness === "claude" && i.session.nativeId.toLowerCase().startsWith(want));
74
+ const ids = new Set(items.map((i) => i.session.nativeId));
75
+ if (ids.size === 0) return { ok: false, key: "recover.notFound", vars: { id: shownText(id, 40) } };
76
+ if (ids.size > 1) return { ok: false, key: "recover.ambiguous", vars: { id: shownText(id, 40), n: ids.size } };
77
+ const nativeId = [...ids][0] ;
78
+ const name = sessionName(items[0] );
79
+ const copy = items.find((i) => i.action.kind === "convert-import" && i.action.uuid === orphanUuid(nativeId));
80
+ if (copy) {
81
+ if (plan.instancesToCreate.some((x) => x.id === copy.action.instanceId)) return { ok: false, key: "recover.needsInstance", vars: { name } };
82
+ return { ok: true, item: copy, name };
83
+ }
84
+ if (!items.some((i) => i.session.startedIn === "t3")) return { ok: false, key: "recover.notNative", vars: { name } };
85
+ if (items.some((i) => i.notes.includes("recovered"))) return { ok: false, key: "recover.already", vars: { name } };
86
+ const reasons = items.flatMap((i) => (i.action.kind === "skip" ? [i.action.reason] : []));
87
+ if (reasons.includes("already-in-t3")) return { ok: false, key: "recover.inT3", vars: { name } };
88
+ // The reason of the session's own item (T3-native, not a mirror or a duplicate of it in another account) says why.
89
+ const own = items.find((i) => i.session.startedIn === "t3" && i.action.kind === "skip" && i.action.reason !== "mirror-copy" && i.action.reason !== "duplicate");
90
+ const reason = own?.action.kind === "skip" ? own.action.reason : reasons[0] ?? "already-in-t3";
91
+ return { ok: false, key: "recover.skipped", vars: { name }, reason };
92
+ }
93
+
94
+ /** The plan as the run goes: only the copy, and the project its folder needs (no instance, pin or mirror work). */
95
+ export function recoverPlan(plan , item , platform ) {
96
+ const same = (r ) => sameCwd(r, item.action.projectRoot, platform);
97
+ const projectsToCreate = plan.projectsToCreate.filter((p) => same(p.root));
98
+ return {
99
+ ...plan, items: [item], instancesToCreate: [], projectsToCreate, mirrorCopies: [], pinDefault: null,
100
+ projectDefaults: plan.projectDefaults.filter((d) => same(d.root) && projectsToCreate.length > 0),
101
+ };
102
+ }
103
+
104
+ class RecoverRefused extends Error {
105
+ pick ;
106
+ constructor(pick ) { super(pick.key); this.pick = pick; }
107
+ }
108
+
109
+ /** What will happen, as a panel, and the duplicate warning under it. */
110
+ function willLines(ui , p , home , platform ) {
111
+ const { s, t } = ui;
112
+ const width = Math.max(1, ui.width);
113
+ const body = kv(s, [
114
+ [t("recover.row.conversation"), p.name],
115
+ [t("recover.row.newId"), shownText(p.item.action.uuid, 40)],
116
+ [t("recover.row.project"), s("path", shownText(tildePath(p.item.action.projectRoot, home, platform), 200))],
117
+ [t("recover.row.undo"), s("key", "t3sm rollback --run <id> --archive-threads")],
118
+ ], Math.max(1, width - 4));
119
+ const title = t("recover.title");
120
+ return [...panel(s, { title, body }, snugWidth(title, body, width)), "", ...noteLines(s, "warn", t("recover.duplicate"), width)];
121
+ }
122
+
123
+ function refuse(io , ui , p ) {
124
+ const vars = p.reason !== undefined ? { ...p.vars, why: ui.t(SKIP_WORDS[p.reason]) } : p.vars;
125
+ io.stderr(noteLines(ui.s, "err", ui.t(p.key, vars), Math.max(1, ui.width)).join("\n") + "\n");
126
+ return 2;
127
+ }
128
+
129
+ export async function recoverCommand(args , io , deps = {}) {
130
+ const flags = new Set ();
131
+ let id = null;
132
+ for (const a of args) {
133
+ if (FLAGS.has(a)) flags.add(a);
134
+ else if (a.startsWith("-")) { unknownOption(io, a, "recover"); return 2; }
135
+ else if (id === null) id = a;
136
+ else { usageLine(io, "recover.oneId"); return 2; }
137
+ }
138
+ if (id === null) { usageLine(io, "recover.needsId"); return 2; }
139
+ if (!ID_RE.test(id)) { usageLine(io, "recover.badId", { id: shownText(id, 60) }); return 2; }
140
+ const yes = flags.has("--yes");
141
+ const dryRun = flags.has("--dry-run");
142
+ if (yes && dryRun) { usageLine(io, "common.eitherDryRunOrYes"); return 2; }
143
+ if (!yes && !dryRun && !io.isTTY) { usageLine(io, "common.needsYesT3"); return 2; }
144
+
145
+ const home = deps.home ?? homedir();
146
+ const now = deps.now ?? Date.now;
147
+ const platform = deps.platform ?? process.platform;
148
+ const dir = stateDir(io.env, home);
149
+ const ui = cliUi(io, { now });
150
+ const allowUntested = flags.has("--allow-untested");
151
+ const connect = deps.connect ?? connectT3;
152
+ const onNotice = (l ) => io.stderr(`${l}\n`);
153
+ const say = (l ) => io.stdout(l.join("\n") + "\n");
154
+ const want = id.toLowerCase();
155
+ // The planner treats every session whose id starts with `id` as named; pickRecover refuses when that is not one.
156
+ const recover = { has: (nativeId ) => nativeId.toLowerCase().startsWith(want) };
157
+ const planOpts = { home, env: io.env, now, adapters: deps.adapters, existsDir: deps.existsDir, lang: ui.lang, missingConfig: "memory" , recover };
158
+
159
+ if (dryRun) {
160
+ const api = await connect(home, { allowUntested, manageProviders: false, onNotice });
161
+ try {
162
+ const fp = await freshPlan(api, { ...planOpts, readOnly: true });
163
+ const p = pickRecover(fp.plan, id);
164
+ if (!p.ok) return refuse(io, ui, p);
165
+ say([...willLines(ui, p, home, platform), "", ...noteLines(ui.s, "info", ui.t("recover.dryDone", { id: shownText(p.item.session.nativeId, 40) }), Math.max(1, ui.width))]);
166
+ return 0;
167
+ } finally {
168
+ await api.close();
169
+ }
170
+ }
171
+
172
+ const config = await loadConfig(dir, home);
173
+ let api = null;
174
+ let picked = null;
175
+ let full = [];
176
+ // Under the lock, after the recovery (applyPlan's loader): read-only against T3, its connection lent to applyPlan.
177
+ const build = async () => {
178
+ api = await connect(home, { allowUntested, manageProviders: false, onNotice });
179
+ const fp = await freshPlan(api, planOpts);
180
+ const p = pickRecover(fp.plan, id);
181
+ if (!p.ok) throw new RecoverRefused(p);
182
+ picked = p;
183
+ full = fp.plan.items;
184
+ return recoverPlan(fp.plan, p.item, platform);
185
+ };
186
+ const bar = importProgress(io, ui, now, { silent: false, verbose: false });
187
+ let r ;
188
+ try {
189
+ r = await applyPlan(build, {
190
+ stateDir: dir, home, now, platform, signals: deps.signals, allowUntested, batch: config?.batch,
191
+ connect: async () => new Proxy(api , { get: (t, k) => (k === "close" ? async () => {} : Reflect.get(t, k)) }),
192
+ // The journal names the whole id the plan found (read when the run starts, after the loader).
193
+ get command() { return `recover ${picked?.item.session.nativeId ?? id}`; },
194
+ pinDefaultInstance: false,
195
+ exposure: () => full, // every discovered session is still on disk and visible to T3 Code's importer
196
+ rehomeFolders: { env: deps.folderEnv ?? defaultFolderEnv(home, io.env, platform) },
197
+ accountHomes: () => Object.fromEntries((config?.accounts ?? []).map((a) => [a.id, expandHome(a.home, home)])),
198
+ rediscover: async () => (await discoverAll((deps.adapters ?? allAdapters()).filter((a) => a.id !== "claude"), makeEnv(io, home, config ?? defaultConfig([]), now))).sessions,
199
+ failureTitles: FAILURES_SHOWN,
200
+ onImportStart: (n) => bar.onImportStart(n), onWave: (p) => bar.onWave(p), onProgress: (l) => bar.onProgress(l),
201
+ onNotice: (l) => { if (!bar.note(l)) onNotice(l); }, lang: ui.lang,
202
+ confirm: async () => {
203
+ say(willLines(ui, picked , home, platform));
204
+ if (yes) return true;
205
+ io.stdout("\n");
206
+ return confirm(io, ui.t("recover.confirm"));
207
+ },
208
+ });
209
+ bar.end();
210
+ } catch (e) {
211
+ if (e instanceof RecoverRefused) return refuse(io, ui, e.pick);
212
+ throw e;
213
+ } finally {
214
+ bar.dispose();
215
+ await (api )?.close();
216
+ }
217
+ if (r.status === "locked") { reportLockBusy(io); return 0; }
218
+ if (r.status === "declined") { io.stdout(`${ui.t("common.nothingChanged")}\n`); return 0; }
219
+ const rec = r.recovered;
220
+ if (rec && rec.restored.length > 0) io.stderr(`${ui.t("apply.recovered", { n: rec.restored.length })}\n`);
221
+ if (rec && rec.failed.length > 0) io.stderr(`${ui.t("apply.recoverFailed", { n: rec.failed.length })}\n`);
222
+ if (r.status === "aborted" && r.runId === null) { io.stderr(`${ui.t("apply.interruptedBefore")}\n`); return 130; }
223
+ say(renderApplyResult(ui, r));
224
+ const done = picked ;
225
+ if (r.imported > 0 && done !== null && r.runId !== null) {
226
+ say(["", ...noteLines(ui.s, "ok", ui.t("recover.done", { name: done.name, runId: shownText(r.runId, 40) }), Math.max(1, ui.width))]);
227
+ }
228
+ if (r.status === "aborted") { io.stderr(`${ui.t("apply.interrupted")}\n`); return 130; }
229
+ return r.failed > 0 || r.unverified > 0 || r.restoreErrors.length > 0 ? 5 : 0;
230
+ }