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,872 @@
1
+ // t3sm organize: tidy the history t3sm imported into T3 Code (spec §5) and undo it.
2
+ // organize [--dry-run | --yes] [--only <folder>] [--history <days|all|off>] [--min <n>] [--auto-settle <days|off>]
3
+ // [--no-delete] [--no-pin <ids>] [--no-archive-folders] [--allow-untested] [--plain]
4
+ // organize --undo [<run>] [--dry-run | --yes] [--allow-untested]
5
+ // On a terminal (and without --plain) the confirmation also offers "d = details": the planned changes as an interactive
6
+ // review list (src/ui/list.ts), grouped by kind; an unchecked change is dropped from the plan before it is applied
7
+ // (ruling R3). Without a terminal, or with --plain, the output and the question stay as they were.
8
+ // --dry-run reads T3 Code and the transcripts and writes nothing (no lock, no journal, no discovery cache). Without
9
+ // --yes or --dry-run on a non-terminal: refuse (exit 2) before contacting T3 Code. Otherwise: lock ->
10
+ // recoverPendingMtimes -> connect -> plan -> summary -> confirm -> applyOrganize (journaled; undone by --undo or
11
+ // `t3sm rollback`). Organize runs on any T3 Code version with one warning (ruling R18): T3 is connected with
12
+ // allowUntested and organizeGate gives the warning.
13
+ // --history / --min override config.json's organize.history for this run only (same ranges: days 1..3650, all or off;
14
+ // minimum 0..1000). --auto-settle <1..90|off> sets T3 Code's own sidebarAutoSettleAfterDays (journaled, undone by --undo).
15
+
16
+ import { homedir, tmpdir } from "node:os";
17
+ import { join } from "node:path";
18
+
19
+ import { expandHome, normalizeCwd, pathKey, sameCwd, stateDir, tildePath } from "../../core/paths.js";
20
+ import { readSyncStatus } from "../../ops/syncStatus.js";
21
+ import { latestPlan, readPlan } from "./apply.js";
22
+
23
+ import { ConfigError, DEFAULT_HISTORY, defaultConfig, loadConfig, normalizeHistory, organizeSettings } from "../../core/config.js";
24
+ import { Journal, newRunId, recoverPendingMtimes } from "../../core/journal.js";
25
+ import { acquireLock } from "../../core/lock.js";
26
+ import { resolveAccounts } from "../../ops/discoverAccounts.js";
27
+ import { normalizeFolder } from "../../ops/projects.js";
28
+ import { applyOrganize, assertOrganizeOnly, undoOrganize, } from "../../organize/apply.js";
29
+ import { STOP_SIGNALS, } from "../../apply/apply.js";
30
+ import { AUTO_SETTLE_TARGET, buildOrganizePlan } from "../../organize/plan.js";
31
+ import { SHOWN_NO_OVERRIDE, isShownMark } from "../../organize/history.js";
32
+ import { matchSessions } from "../../organize/sessions.js";
33
+ import { proposeTitle } from "../../organize/titles.js";
34
+
35
+ import { classifyFolder, } from "../../plan/folders.js";
36
+ import { shownText } from "../../plan/names.js";
37
+ import { allAdapters } from "../../sources/registry.js";
38
+
39
+ import { reviewList, } from "../../ui/list.js";
40
+ import { nodeTerm, } from "../../ui/terminal.js";
41
+ import { connectT3, } from "../../t3/api.js";
42
+ import { organizeGate } from "../../t3/compat.js";
43
+ import { reportLockBusy } from "../locked.js";
44
+ import { FLAG_SPECS } from "../flags.js";
45
+
46
+ import { cliT, cliUi, confirm, confirmOrDetails, ioTerm, langOf, unknownOption, usageLine } from "../ui.js";
47
+ import { fitLine, flowAtoms, noteLines, sectionLines, textLines } from "../screen.js";
48
+ import { table as uiTable } from "../../ui/components.js";
49
+ import { organizePreviewTable, } from "../../ui/organizePreview.js";
50
+ import { progressBar } from "../../ui/progress.js";
51
+ import { discoverAll, makeEnv } from "./scan.js";
52
+
53
+ /** writeSettings: the session may change T3 Code's own settings (settings:write), only for a run that changes one. */
54
+
55
+
56
+
57
+
58
+
59
+
60
+
61
+
62
+
63
+
64
+
65
+
66
+
67
+
68
+
69
+
70
+
71
+
72
+ const processSignals = {
73
+ on: (sig, fn) => void process.on(sig , fn),
74
+ off: (sig, fn) => void process.off(sig , fn),
75
+ };
76
+
77
+ /** Same sentence as `apply`. */
78
+ const TITLE_MAX = 80;
79
+ /** Commands whose runs `organize --undo` picks by itself (an unattended sync is only undone when named). */
80
+ const OWN_COMMANDS = new Set(["organize", "projects rename"]);
81
+
82
+ const fmt = (n ) => n.toLocaleString("en-US");
83
+
84
+ /** Each line once per command, on stderr. */
85
+ export function noticeOnce(io ) {
86
+ const seen = new Set ();
87
+ return (l) => {
88
+ if (seen.has(l)) return;
89
+ seen.add(l);
90
+ io.stderr(`${l}\n`);
91
+ };
92
+ }
93
+
94
+ /**
95
+ * Connects for organize work (ruling R18): the connection's own version gate is passed (allowUntested) and its notice
96
+ * dropped; organizeGate then gives the one warning (none with --allow-untested). Notices after connecting (a failed
97
+ * revoke at close) still show.
98
+ */
99
+ export async function connectForOrganize(connect , home , allowUntested , onNotice , writeSettings = false) {
100
+ let connecting = true;
101
+ let api ;
102
+ try {
103
+ api = await connect(home, { allowUntested: true, manageProviders: false, ...(writeSettings ? { writeSettings } : {}), onNotice: (l) => { if (!connecting) onNotice(l); } });
104
+ } finally {
105
+ connecting = false;
106
+ }
107
+ organizeGate(api.version, { allowUntested, onNotice });
108
+ return api;
109
+ }
110
+
111
+ /** What a plan is built for (the guided assistant passes the same, read-only). */
112
+
113
+
114
+
115
+
116
+
117
+
118
+
119
+
120
+
121
+
122
+
123
+
124
+
125
+
126
+
127
+
128
+
129
+
130
+
131
+
132
+
133
+
134
+
135
+
136
+
137
+
138
+
139
+
140
+
141
+ const ORGANIZE_FLAGS = new Set ([...FLAG_SPECS.organize.bool, ...FLAG_SPECS.organize.valued]);
142
+ const HISTORY_BAD = "--history takes a number of days from 1 to 3650, all or off. Run `t3sm organize --help`.\n";
143
+ const MIN_BAD = "--min takes a number from 0 to 1000 (conversations shown per project at least). Run `t3sm organize --help`.\n";
144
+ const AUTO_SETTLE_BAD = "--auto-settle takes a number of days from 1 to 90, or off (T3 Code accepts nothing else). Run `t3sm organize --help`.\n";
145
+
146
+ /** A whole number in lo..hi written with digits only; null otherwise. */
147
+ function intArg(v , lo , hi ) {
148
+ if (v === undefined || !/^\d+$/.test(v)) return null;
149
+ const n = Number(v);
150
+ return n >= lo && n <= hi ? n : null;
151
+ }
152
+
153
+ /** `t3sm organize` arguments (exported for the test that every printed undo command parses). */
154
+ export function parseOrganizeArgs(args , io ) {
155
+ const p = { dryRun: false, yes: false, allowUntested: false, plain: false, undo: undefined, only: null, noDelete: false, noPin: new Set() };
156
+ let days ;
157
+ let min ;
158
+ for (let i = 0; i < args.length; i++) {
159
+ const a = args[i] ;
160
+ // Only the options src/cli/flags.ts lists (what --help documents and a test checks); each is handled below.
161
+ if (!ORGANIZE_FLAGS.has(a)) { unknownOption(io, a, "organize"); return null; }
162
+ if (a === "--dry-run") p.dryRun = true;
163
+ else if (a === "--yes") p.yes = true;
164
+ else if (a === "--allow-untested") p.allowUntested = true;
165
+ else if (a === "--plain") p.plain = true;
166
+ else if (a === "--undo") {
167
+ const v = args[i + 1];
168
+ if (v !== undefined && !v.startsWith("--")) { p.undo = v; i++; } else p.undo = null;
169
+ } else if (a === "--only") {
170
+ const v = args[i + 1];
171
+ if (v === undefined || v.startsWith("--")) { usageLine(io, "common.needsValue", { option: "--only", help: "t3sm organize --help" }); return null; }
172
+ p.only = v;
173
+ i++;
174
+ } else if (a === "--auto-settle") {
175
+ const v = args[i + 1];
176
+ const n = intArg(v, 1, 90);
177
+ if (v !== "off" && n === null) { io.stderr(AUTO_SETTLE_BAD); return null; }
178
+ p.autoSettle = v === "off" ? null : n;
179
+ i++;
180
+ } else if (a === "--history") {
181
+ const v = args[i + 1]?.toLowerCase();
182
+ const n = intArg(v, 1, 3650);
183
+ if (v !== "all" && v !== "off" && n === null) { io.stderr(HISTORY_BAD); return null; }
184
+ days = v === "all" || v === "off" ? v : n ;
185
+ i++;
186
+ } else if (a === "--min") {
187
+ const n = intArg(args[i + 1], 0, 1000);
188
+ if (n === null) { io.stderr(MIN_BAD); return null; }
189
+ min = n;
190
+ i++;
191
+ } else if (a === "--no-delete") p.noDelete = true;
192
+ else if (a === "--no-archive-folders") p.noArchiveFolders = true;
193
+ else if (a === "--no-pin") {
194
+ const v = args[i + 1];
195
+ if (v === undefined || v.startsWith("--")) { usageLine(io, "usage.noPinValue"); return null; }
196
+ for (const id of v.split(",")) if (id.trim() !== "") (p.noPin ).add(id.trim());
197
+ i++;
198
+ } else { unknownOption(io, a, "organize"); return null; }
199
+ }
200
+ if (p.dryRun && p.yes) { usageLine(io, "common.eitherDryRunOrYes"); return null; }
201
+ if (p.undo !== undefined && p.only !== null) { usageLine(io, "usage.onlyNotUndo"); return null; }
202
+ if (p.undo !== undefined && (p.autoSettle !== undefined || days !== undefined || min !== undefined || p.noDelete === true || p.noPin .size > 0 || p.noArchiveFolders === true)) {
203
+ usageLine(io, "usage.notWithUndo");
204
+ return null;
205
+ }
206
+ if (days === "off" && min !== undefined) { usageLine(io, "usage.minHistoryOff"); return null; }
207
+ if (days === "off") p.history = "off";
208
+ else if (days !== undefined || min !== undefined) p.history = { ...(days !== undefined ? { days } : {}), ...(min !== undefined ? { min } : {}) };
209
+ return p;
210
+ }
211
+
212
+ export async function organizeCommand(args , io , deps = {}) {
213
+ const p = parseOrganizeArgs(args, io);
214
+ if (!p) return 2;
215
+ if (!p.yes && !p.dryRun && !io.isTTY) { usageLine(io, "common.needsYesT3"); return 2; }
216
+ try {
217
+ return p.undo !== undefined ? await undo(p, p.undo, io, deps) : await organize(p, io, deps);
218
+ } catch (e) {
219
+ if (e instanceof ConfigError) { io.stderr(`${e.message}\n`); return 2; }
220
+ throw e;
221
+ }
222
+ }
223
+
224
+ // ---------------- organize ----------------
225
+
226
+
227
+
228
+
229
+
230
+
231
+
232
+
233
+
234
+
235
+
236
+
237
+
238
+ /** Reads T3 Code and the transcripts (writes nothing with `dryRun`) and plans the changes of `config.organize`. */
239
+ export async function buildOrganize(api , j , config , p , io , deps , home , now ) {
240
+ const platform = deps.platform ?? process.platform;
241
+ const [threads, projects, instances, journal] = [await api.listThreads(), await api.listProjects(), await api.providerInstances(), await j.readAll()];
242
+ const saved = organizeSettings(config, langOf(io, config.language));
243
+ const off = { history: normalizeHistory(saved.history) === null, titles: !saved.titles, archiveAutomated: !saved.archiveAutomated, pinRecent: !saved.pinRecent.enabled };
244
+ const offered = p.offerAll !== true ? saved : {
245
+ ...saved, history: off.history ? { ...DEFAULT_HISTORY } : saved.history, titles: true, archiveAutomated: true, pinRecent: { ...saved.pinRecent, enabled: true },
246
+ };
247
+ const settings = { ...offered, history: overrideHistory(offered.history, p.history) };
248
+
249
+ let onlyThreads ;
250
+ if (p.only !== null) {
251
+ const folder = normalizeFolder(p.only, platform, home);
252
+ const project = projects.find((x) => sameCwd(x.workspaceRoot, folder, platform));
253
+ if (!project) throw new ConfigError(`${folder} is not a T3 Code project. Run \`t3sm projects\` to list them.`);
254
+ onlyThreads = new Set(threads.filter((t) => t.projectId === project.id).map((t) => t.id));
255
+ } else if (p.onlyThreads !== undefined) {
256
+ onlyThreads = new Set(p.onlyThreads);
257
+ }
258
+
259
+ // The threads the history rule may move, when that is not the same set as archive and title (sync).
260
+ let historyThreads ;
261
+ if (onlyThreads !== undefined && p.historyScope === "all") historyThreads = new Set(threads.filter((t) => t.id.startsWith("import:")).map((t) => t.id));
262
+ else if (onlyThreads !== undefined && p.historyScope === "projects") {
263
+ const touched = new Set(threads.filter((t) => onlyThreads .has(t.id)).map((t) => t.projectId));
264
+ historyThreads = new Set(threads.filter((t) => t.id.startsWith("import:") && touched.has(t.projectId)).map((t) => t.id));
265
+ }
266
+
267
+ const claude = (deps.adapters ?? allAdapters()).filter((a) => a.id === "claude");
268
+ // A dry run writes nothing, not even the discovery cache.
269
+ const found = await discoverAll(claude, { ...makeEnv(io, home, config, now), readOnly: p.dryRun });
270
+ const match = (only , titles ) => matchSessions({
271
+ threads: threads.filter(only), instances, accounts: config.accounts, userHome: home, discovered: found.sessions, journal,
272
+ title: titles ? (file) => proposeTitle(file, { maxLength: TITLE_MAX }) : null, platform,
273
+ });
274
+ const { sessions, missing } = await match((t) => onlyThreads === undefined || onlyThreads.has(t.id), settings.titles);
275
+ // History-only threads: their origin (an automated one never moves), never a title.
276
+ if (historyThreads !== undefined) {
277
+ for (const [id, s] of (await match((t) => historyThreads .has(t.id) && !sessions.has(t.id), false)).sessions) sessions.set(id, s);
278
+ }
279
+
280
+ const t3Base = normalizeCwd(expandHome("~/.t3", home), platform);
281
+ const folderEnv = deps.folderEnv ?? { platform, home, tmpdir: tmpdir(), env: io.env, t3BaseDir: t3Base, t3WorktreesDir: `${t3Base}/worktrees` };
282
+ const projectCategory = new Map(projects.map((x) => [x.id, classifyFolder(x.workspaceRoot, folderEnv)] ));
283
+
284
+ let autoSettleDays ;
285
+ try { autoSettleDays = await api.getServerSetting(AUTO_SETTLE_TARGET); } catch (e) {
286
+ autoSettleDays = undefined; // not reported, or a value this t3sm does not know: the setting is left alone
287
+ if (p.autoSettle !== undefined) io.stderr(`${shownError(e)}: --auto-settle ${p.autoSettle === null ? "off" : p.autoSettle} is skipped.\n`);
288
+ }
289
+
290
+ const keepProjects = await waitingProjects(stateDir(io.env, home), projects, threads, platform);
291
+ const built = buildOrganizePlan({
292
+ runId: newRunId(new Date(now())), threads, projects, journal, config: settings, sessions, now: now(), projectCategory, keepProjects,
293
+ archiveFolders: p.noArchiveFolders !== true,
294
+ // --only: that project's conversations; pins and deletes span every project, so they wait for a full organize.
295
+ scope: onlyThreads
296
+ ? { onlyThreads, ...(historyThreads ? { historyThreads } : {}), allowPins: false, allowDeletes: false }
297
+ : { allowPins: true, allowDeletes: p.noDelete !== true },
298
+ ...(p.autoSettle !== undefined && autoSettleDays !== undefined ? { autoSettle: { want: p.autoSettle, current: autoSettleDays } } : {}),
299
+ ...(autoSettleDays !== undefined ? { t3AutoSettleDays: autoSettleDays } : {}),
300
+ });
301
+ const skipPin = p.noPin ?? new Set ();
302
+ const plan = skipPin.size === 0 ? built : keepChecked(built, built.actions.map((a, i) => ({ id: String(i), label: "", detail: "", checked: !(a.kind === "pin" && skipPin.has(a.target)) })));
303
+ return { plan, missing, names: namesOf(threads, projects, home), threads, projects, autoSettleDays, history: normalizeHistory(settings.history), off };
304
+ }
305
+
306
+ /** organize.history with a run's override (`--history`, `--min`) applied; `--min` alone keeps the configured days (90 when off). */
307
+ export function overrideHistory(saved , o ) {
308
+ if (o === undefined) return saved;
309
+ if (o === "off") return "off";
310
+ const base = normalizeHistory(saved) ?? DEFAULT_HISTORY;
311
+ return { days: o.days ?? base.days, minPerProject: o.min ?? base.minPerProject };
312
+ }
313
+
314
+ /**
315
+ * Projects with sessions still waiting to import, which this organize never deletes: the roots of the latest plan's
316
+ * imports T3 Code does not hold yet (a root held because a conversation was in use gets its project created empty and
317
+ * is imported later), and the projects `sync-status.json` lists as held (by the name T3 Code shows). A missing or
318
+ * unreadable file counts as none.
319
+ */
320
+ async function waitingProjects(dir , projects , threads , platform ) {
321
+ const inT3 = new Set(threads.map((t) => t.id));
322
+ const roots = new Set ();
323
+ try {
324
+ const file = await latestPlan(dir);
325
+ if (file !== null) {
326
+ for (const i of (await readPlan(file)).items) {
327
+ if (i.action.kind !== "skip" && !inT3.has(i.action.expectedThreadId)) roots.add(pathKey(i.action.projectRoot, platform));
328
+ }
329
+ }
330
+ } catch { /* no usable plan: nothing known to be waiting */ }
331
+ const held = new Set((await readSyncStatus(dir).catch(() => null))?.held.map((h) => h.project) ?? []);
332
+ return new Set(projects.filter((p) => held.has(p.title) || roots.has(pathKey(p.workspaceRoot, platform))).map((p) => p.id));
333
+ }
334
+
335
+ // ---------------- names ----------------
336
+
337
+ /**
338
+ * How conversations, projects and folders are named in the output: their T3 Code titles, never ids. Every name is
339
+ * untrusted text (from a transcript or T3 Code): shownText strips control characters, so no escape reaches the
340
+ * terminal.
341
+ */
342
+ /** How a change names what it is about, in `lang`: a conversation ("'Fix the login form' (demo)"), a project, a folder. */
343
+
344
+
345
+ const TITLE_SHOWN = 60;
346
+ const quoted = (t ) => `'${shownText(t, TITLE_SHOWN)}'`;
347
+ /** Error texts and notes (they quote T3 Code's replies): one safe line. */
348
+ const ERROR_SHOWN = 200;
349
+ const shownError = (e ) => shownText(e, ERROR_SHOWN);
350
+
351
+ /**
352
+ * Why a change failed, for the screen: T3 Code's refusal for a missing permission (an EnvironmentAuthorizationError, a
353
+ * session without the scope the change needs) in plain words; any other error as T3 Code or t3sm worded it.
354
+ */
355
+ export function failureWords(error , lang ) {
356
+ if (/EnvironmentAuthorizationError|missing required scope/i.test(error)) return cliT(lang, "organize.why.noPermission");
357
+ return shownError(error);
358
+ }
359
+
360
+ export function namesOf(threads , projects , home , lang = "en") {
361
+ const p = new Map(projects.map((x) => [x.id, x.title] ));
362
+ const t = new Map(threads.map((x) => [x.id, x] ));
363
+ return {
364
+ lang,
365
+ project: (id) => (p.has(id) ? cliT(lang, "organize.name.project", { title: quoted(p.get(id) ) }) : cliT(lang, "organize.name.projectGone")),
366
+ thread: (id) => {
367
+ const x = t.get(id);
368
+ if (!x) return cliT(lang, "organize.name.threadGone");
369
+ const pt = p.get(x.projectId);
370
+ return `${quoted(x.title)}${pt !== undefined ? ` (${shownText(pt, TITLE_SHOWN)})` : ""}`;
371
+ },
372
+ folder: (path) => shownText(tildePath(path, home), 120),
373
+ };
374
+ }
375
+
376
+ const days = (x , lang ) => (x === null ? cliT(lang, "organize.off") : cliT(lang, "organize.days", { n: Number(x) }));
377
+ const str = (x ) => (typeof x === "string" ? x : JSON.stringify(x));
378
+
379
+ /** One planned change, in words ("Archive 'Fix the login form' (demo)"), in the language of `n`. */
380
+ export function actionLine(a , n ) {
381
+ const t = (k , v = {}) => cliT(n.lang, k, v);
382
+ switch (a.kind) {
383
+ case "archive": return t("organize.act.archive", { thread: n.thread(a.target) });
384
+ case "title": return t("organize.act.title", { thread: n.thread(a.target), title: quoted(str(a.next)) });
385
+ case "unsettle": return t(a.previous === SHOWN_NO_OVERRIDE ? "organize.act.keep" : "organize.act.show", { thread: n.thread(a.target) });
386
+ case "settle": return t("organize.act.settle", { thread: n.thread(a.target) });
387
+ case "pin": return t("organize.act.pin", { project: n.project(a.target) });
388
+ case "unpin": return t("organize.act.unpin", { project: n.project(a.target) });
389
+ case "project-delete": return t("organize.act.delete", { project: n.project(a.target) });
390
+ case "project-title": return t("organize.act.rename", { project: n.project(a.target), title: quoted(str(a.next)) });
391
+ case "auto-settle": return t("organize.act.autoSettle", { days: days(a.next, n.lang) });
392
+ }
393
+ }
394
+
395
+ /** What undoing one journaled change does, in words ("Unarchive 'Fix the login form' (demo)"), in the language of `n`. */
396
+ export function revertLine(e , n ) {
397
+ const t = (k , v = {}) => cliT(n.lang, k, v);
398
+ switch (e.kind) {
399
+ case "archive": return t(e.next === true ? "organize.rev.unarchive" : "organize.rev.archive", { thread: n.thread(e.target) });
400
+ case "title": return t("organize.rev.title", { thread: n.thread(e.target), title: quoted(str(e.previous)) });
401
+ case "unsettle": return t(e.next === "active" ? "organize.rev.putAway" : "organize.rev.show", { thread: n.thread(e.target) });
402
+ case "settle": return t("organize.rev.showInside", { thread: n.thread(e.target) });
403
+ case "pin": case "unpin": return t(e.next === true ? "organize.rev.unpin" : "organize.rev.pin", { project: n.project(e.target) });
404
+ case "project-delete": {
405
+ const prev = e.previous ;
406
+ const folder = typeof prev?.workspaceRoot === "string" ? ` (${n.folder(prev.workspaceRoot)})` : "";
407
+ return typeof prev?.title === "string" ? t("organize.rev.recreate", { title: quoted(prev.title), folder }) : t("organize.rev.recreateUntitled", { folder });
408
+ }
409
+ case "project-title": return t("organize.rev.rename", { project: n.project(e.target), title: quoted(str(e.previous)) });
410
+ case "auto-settle": return t("organize.rev.autoSettle", { days: days(e.previous, n.lang) });
411
+ }
412
+ }
413
+
414
+ /** What an undo item is about, without the change ("'Fix the login form' (demo)", "project 'demo'"). */
415
+ function subjectOf(e , n ) {
416
+ if (e.kind === "archive" || e.kind === "title" || e.kind === "unsettle" || e.kind === "settle") return n.thread(e.target);
417
+ if (e.kind === "auto-settle") return cliT(n.lang, "organize.name.autoSettle");
418
+ if (e.kind === "project-delete") {
419
+ const prev = e.previous ;
420
+ return typeof prev?.title === "string" ? cliT(n.lang, "organize.name.project", { title: quoted(prev.title) }) : cliT(n.lang, "organize.name.projectDeleted");
421
+ }
422
+ return n.project(e.target);
423
+ }
424
+
425
+ /** Groups `xs` by `key`, counted, most frequent first (ties: first seen). */
426
+ function tally(xs , key ) {
427
+ const m = new Map ();
428
+ for (const a of xs) m.set(key(a), (m.get(key(a)) ?? 0) + 1);
429
+ return [...m.entries()].sort((a, b) => b[1] - a[1]);
430
+ }
431
+
432
+ /** The archive reasons as the review list names them ("automated conversation"). */
433
+ const ARCHIVE_NOUN = {
434
+ "automated session (Agent SDK)": "organize.why.automatedNoun", "temp folder": "organize.why.tempNoun", "system folder": "organize.why.systemNoun",
435
+ };
436
+
437
+ /**
438
+ * How the summary is told: its language (English by default), the dash before the undo hint ("-" without Unicode), and
439
+ * whether each line ends with the undo hint (default true; the screen says it once, under the lines).
440
+ */
441
+
442
+
443
+ const ARCHIVE_WORDS = {
444
+ "automated session (Agent SDK)": "organize.why.automated", "temp folder": "organize.why.temp", "system folder": "organize.why.system",
445
+ };
446
+ const TITLE_WORDS = { "technical title": "organize.why.technical", "title set by t3sm earlier": "organize.why.earlier" };
447
+
448
+ /** The planner's history reason in `lang` ("history: last 90 days" -> "from the last 90 days"). */
449
+ function historyWhy(lang , r ) {
450
+ if (r === "history: all") return cliT(lang, "organize.why.all");
451
+ const last = /^history: last (\d+) days$/.exec(r);
452
+ if (last) return cliT(lang, "organize.why.last", { days: last[1] });
453
+ const min = /^history: at least (\d+) per project$/.exec(r);
454
+ if (min) return cliT(lang, "organize.why.min", { min: min[1] });
455
+ const kept = /^history: kept visible, at least (\d+) per project$/.exec(r);
456
+ if (kept) return cliT(lang, "organize.why.kept", { min: kept[1] });
457
+ const older = /^history: older than (\d+) days$/.exec(r);
458
+ return older ? cliT(lang, "organize.why.older", { days: older[1] }) : r;
459
+ }
460
+
461
+ /** One line per kind (spec §5.6): what, why, and how to undo; in `o.lang` (English by default). */
462
+ export function summaryLines(plan , o = {}) {
463
+ const lang = o.lang ?? "en";
464
+ const t = (k , v = {}) => cliT(lang, k, v);
465
+ const undo = o.undo !== false ? ` ${o.dash ?? "—"} ${cliT(lang, "organize.undo")}` : "";
466
+ const num = (n ) => (lang === "pt" ? String(n).replace(/\B(?=(\d{3})+(?!\d))/g, " ") : fmt(n));
467
+ const of = (k ) => plan.actions.filter((a) => a.kind === k);
468
+ const L = [];
469
+ const archive = of("archive");
470
+ if (archive.length > 0) {
471
+ const reasons = tally(archive, (a) => a.reason);
472
+ if (reasons.length === 1 && reasons[0] [0] === "automated session (Agent SDK)") L.push(t("organize.sum.archiveAutomated", { n: num(archive.length) }) + undo);
473
+ else {
474
+ const why = reasons.map(([r, n]) => `${num(n)} ${ARCHIVE_WORDS[r] ? cliT(lang, ARCHIVE_WORDS[r] ) : r}`).join(", ");
475
+ L.push(t("organize.sum.archive", { n: num(archive.length), why }) + undo);
476
+ }
477
+ }
478
+ const title = of("title");
479
+ if (title.length > 0) {
480
+ const reasons = tally(title, (a) => a.reason);
481
+ const word = (r ) => (TITLE_WORDS[r] ? cliT(lang, TITLE_WORDS[r] ) : r);
482
+ const why = reasons.length === 1 ? word(reasons[0] [0]) : reasons.map(([r, n]) => `${num(n)} ${word(r)}`).join(", ");
483
+ L.push(t("organize.sum.title", { n: num(title.length), why }) + undo);
484
+ }
485
+ const show = of("unsettle").filter((a) => !isShownMark(a));
486
+ if (show.length > 0) {
487
+ const projects = new Set(show.map((a) => a.projectId)).size;
488
+ const why = tally(show, (a) => a.reason).map(([r]) => historyWhy(lang, r)).join(", ");
489
+ L.push(t("organize.sum.show", { n: num(show.length), p: num(projects), why }) + undo);
490
+ }
491
+ // Already shown: marked so T3 Code's own auto-settle leaves them shown (src/organize/history.ts, step 6).
492
+ const kept = of("unsettle").filter((a) => isShownMark(a));
493
+ if (kept.length > 0) {
494
+ const projects = new Set(kept.map((a) => a.projectId)).size;
495
+ L.push(t("organize.sum.keep", { n: num(kept.length), p: num(projects) }) + undo);
496
+ }
497
+ const settle = of("settle");
498
+ if (settle.length > 0) {
499
+ const projects = new Set(settle.map((a) => a.projectId)).size;
500
+ const why = tally(settle, (a) => a.reason).map(([r]) => historyWhy(lang, r)).join(", ");
501
+ L.push(t("organize.sum.settle", { n: num(settle.length), p: num(projects), why }) + undo);
502
+ }
503
+ const pin = of("pin");
504
+ if (pin.length > 0) {
505
+ const top = /top (\d+) recent/.exec(pin[0] .reason)?.[1];
506
+ L.push(t("organize.sum.pin", { n: num(pin.length), why: top ? cliT(lang, "organize.why.pin", { top }) : pin[0] .reason }) + undo);
507
+ }
508
+ const unpin = of("unpin");
509
+ if (unpin.length > 0) {
510
+ const top = /top (\d+) recent/.exec(unpin[0] .reason)?.[1];
511
+ L.push(t("organize.sum.unpin", { n: num(unpin.length), why: top ? cliT(lang, "organize.why.unpin", { top }) : unpin[0] .reason }) + undo);
512
+ }
513
+ const del = of("project-delete");
514
+ if (del.length > 0) L.push(t("organize.sum.delete", { n: num(del.length) }) + (undo ? `${undo} ${t("organize.recreates", { n: del.length })}` : ""));
515
+ const rename = of("project-title");
516
+ if (rename.length > 0) L.push(t("organize.sum.rename", { n: num(rename.length) }) + undo);
517
+ for (const a of of("auto-settle")) {
518
+ const v = (x ) => (x === null ? cliT(lang, "organize.off") : cliT(lang, "organize.days", { n: String(x) }));
519
+ L.push(t("organize.sum.autoSettle", { from: v(a.previous), to: v(a.next) }) + undo);
520
+ }
521
+ return L;
522
+ }
523
+
524
+ const TOP_PROJECTS = 10;
525
+
526
+ /** The history rule in words: "History: the last 90 days, at least 10 per project". */
527
+ export function historyLine(ui , rule ) {
528
+ if (rule === null) return ui.t("organize.history.off");
529
+ if (rule.days === "all") return ui.t("organize.history.all");
530
+ return ui.t("organize.history.rule", { days: ui.f.n(rule.days), min: ui.f.n(rule.minPerProject) });
531
+ }
532
+
533
+ /** The preview table's words in the CLI's language. */
534
+ export function previewWords(ui ) {
535
+ return {
536
+ project: ui.t("organize.col.project"), visible: ui.t("organize.col.visible", { to: "{to}" }), settled: ui.t("organize.col.settled"),
537
+ retitled: ui.t("organize.col.retitled"), archived: ui.t("organize.col.archived"), more: (n) => ui.t("organize.moreProjects", { n }),
538
+ };
539
+ }
540
+
541
+ /**
542
+ * The organize screen: one line per kind of change (what, why, how to undo), the history rule in words, and the
543
+ * per-project before/after table.
544
+ */
545
+ export function renderOrganize(ui , plan , history , width = ui.width) {
546
+ const { s } = ui;
547
+ const w = Math.max(1, width);
548
+ const L = summaryLines(plan, { lang: ui.lang, undo: false });
549
+ if (L.length === 0) return fitLine(`${s("ok", s.sym.ok)} ${ui.t("organize.nothing")}`, w, 2);
550
+ const out = L.flatMap((l) => fitLine(`${s("accent", s.sym.sep)} ${l}`, w, 2));
551
+ // How to undo, once for every line above; the command is never split.
552
+ out.push(...flowAtoms([...ui.t("organize.undoAll").split(/\s+/), s("key", "t3sm organize --undo")], w, 2));
553
+ out.push("", ...fitLine(s("muted", historyLine(ui, history)), w, 2));
554
+ const table = organizePreviewTable(s, ui.f, plan, previewWords(ui), w, { max: TOP_PROJECTS });
555
+ if (table.length > 0) out.push("", ...table);
556
+ return out;
557
+ }
558
+
559
+ function render(b , ui ) {
560
+ return renderOrganize(ui, b.plan, b.history).join("\n") + "\n";
561
+ }
562
+
563
+ function missingNotice(n , lang ) {
564
+ return cliT(lang, "organize.missing", { n });
565
+ }
566
+
567
+ // ---------------- review list ("d = details") ----------------
568
+
569
+ const KIND_ORDER = ["archive", "title", "unsettle", "settle", "pin", "unpin", "project-delete", "project-title", "auto-settle"];
570
+ const KIND_LABEL = {
571
+ archive: "organize.kind.archive", title: "organize.kind.title", unsettle: "organize.kind.show", settle: "organize.kind.settle", pin: "organize.kind.pin",
572
+ unpin: "organize.kind.unpin", "project-delete": "organize.kind.delete", "project-title": "organize.kind.rename", "auto-settle": "organize.kind.setting",
573
+ };
574
+
575
+ /** The planner's reason in words, for the line's detail. */
576
+ function reasonText(a , lang ) {
577
+ if (a.kind === "archive") return ARCHIVE_NOUN[a.reason] ? cliT(lang, ARCHIVE_NOUN[a.reason] ) : a.reason;
578
+ if (a.kind === "title") return TITLE_WORDS[a.reason] ? cliT(lang, TITLE_WORDS[a.reason] ) : a.reason;
579
+ if (a.kind === "unsettle" || a.kind === "settle") return historyWhy(lang, a.reason);
580
+ return a.reason;
581
+ }
582
+
583
+ /**
584
+ * The plan's actions as review items, grouped by kind (the planner's order inside a kind), each with its sentence, the
585
+ * reason and the kind. The id is the action's index in plan.actions; every item starts checked.
586
+ */
587
+ export function reviewItems(plan , names ) {
588
+ const order = (k ) => KIND_ORDER.indexOf(k);
589
+ return plan.actions
590
+ .map((a, i) => ({ a, i }))
591
+ .sort((x, y) => order(x.a.kind) - order(y.a.kind) || x.i - y.i)
592
+ .map(({ a, i }) => ({ id: String(i), label: actionLine(a, names), detail: reasonText(a, names.lang), meta: cliT(names.lang, KIND_LABEL[a.kind]), checked: true }));
593
+ }
594
+
595
+ /** The plan without the changes that were unchecked in the review (ids are indexes into plan.actions). */
596
+ export function keepChecked(plan , items ) {
597
+ const keep = new Set(items.filter((i) => i.checked).map((i) => Number(i.id)));
598
+ const actions = plan.actions.filter((_, i) => keep.has(i));
599
+ const counts = { ...plan.counts };
600
+ for (const k of Object.keys(counts) ) counts[k] = actions.filter((a) => a.kind === k).length;
601
+ return { ...plan, actions, counts };
602
+ }
603
+
604
+ /**
605
+ * Asks whether to apply the plan. With a terminal, "d" opens the review list; confirming it narrows the plan to the
606
+ * checked changes and asks again. Returns the plan to apply, or null for "no" (or nothing left to apply).
607
+ */
608
+ async function decide(b , io , term , lang ) {
609
+ const question = cliUi(io).t("organize.confirm");
610
+ if (term === null) return (await confirm(io, question)) ? b.plan : null;
611
+ let plan = b.plan;
612
+ for (;;) {
613
+ const ans = await confirmOrDetails(io, question);
614
+ if (ans === "yes") return plan;
615
+ if (ans === "no") return null;
616
+ const r = await reviewList(term, {
617
+ title: "t3sm organize", help: cliT(lang, "organize.reviewHelp"),
618
+ items: reviewItems(plan, b.names), lang,
619
+ });
620
+ if (!r.confirmed) continue;
621
+ const before = plan.actions.length;
622
+ plan = keepChecked(plan, r.items);
623
+ io.stdout(`${cliT(lang, "organize.keeping", { n: plan.actions.length, total: before })}\n`);
624
+ if (plan.actions.length === 0) { io.stdout(`${cliT(lang, "organize.nothingLeft")}\n`); return null; }
625
+ for (const l of summaryLines(plan, { lang })) io.stdout(`${l}\n`);
626
+ }
627
+ }
628
+
629
+ async function organize(p , io , deps ) {
630
+ const home = deps.home ?? homedir();
631
+ const now = deps.now ?? Date.now;
632
+ const dir = stateDir(io.env, home);
633
+ const j = new Journal(join(dir, "journal.jsonl"));
634
+ const config = (await loadConfig(dir, home)) ?? defaultConfig(await resolveAccounts(home, [], io.env));
635
+ const onNotice = noticeOnce(io);
636
+ // settings:write only for a run that may change T3 Code's own auto-settle option (--auto-settle); a dry run never writes.
637
+ const connect = () => connectForOrganize(deps.connect ?? connectT3, home, p.allowUntested, onNotice, !p.dryRun && p.autoSettle !== undefined);
638
+
639
+ const ui = cliUi(io, { now });
640
+ const plan = async (api ) => {
641
+ const b = await buildOrganize(api, j, config, p, io, deps, home, now);
642
+ if (b.missing > 0) onNotice(missingNotice(b.missing, ui.lang));
643
+ io.stdout(render(b, ui));
644
+ return b;
645
+ };
646
+
647
+ if (p.dryRun) {
648
+ const api = await connect();
649
+ try {
650
+ const b = await plan(api);
651
+ if (b.plan.actions.length > 0) io.stdout(`\n${ui.t("organize.dryRun")}\n`);
652
+ } finally {
653
+ await api.close();
654
+ }
655
+ return 0;
656
+ }
657
+
658
+ const lock = await acquireLock(dir);
659
+ if (!lock) { reportLockBusy(io); return 0; }
660
+ try {
661
+ const rec = await recoverPendingMtimes(j);
662
+ if (rec.restored.length > 0) io.stderr(`${cliT(io.lang ?? "en", "apply.recovered", { n: rec.restored.length })}\n`);
663
+ const api = await connect();
664
+ try {
665
+ const b = await plan(api);
666
+ if (b.plan.actions.length === 0) return 0;
667
+ let chosen = b.plan;
668
+ if (!p.yes) {
669
+ const term = io.isTTY && !p.plain ? (deps.term ?? nodeTerm({ env: io.env })) : null;
670
+ const c = await decide(b, io, term !== null && term.isTTY ? term : null, langOf(io, config.language));
671
+ if (c === null) { io.stdout(`${ui.t("common.nothingChanged")}\n`); return 0; }
672
+ chosen = c;
673
+ }
674
+ const n = chosen.actions.length;
675
+ let i = 0;
676
+ // One progress bar for the whole run (redrawn in place on a terminal, a few milestone lines otherwise).
677
+ const bar = progressBar(ioTerm(io, ui), ui.s, ui.f, now, { words: { left: ui.t("progress.left") } });
678
+ const started = now();
679
+ const signals = deps.signals ?? processSignals;
680
+ let stop = false;
681
+ const onSignal = () => { stop = true; };
682
+ for (const sig of STOP_SIGNALS) signals.on(sig, onSignal);
683
+ let r ;
684
+ try {
685
+ io.stdout("\n");
686
+ bar.start(n, ui.t("organize.progress", { n }));
687
+ r = await applyOrganize(chosen, {
688
+ api, journal: j, runId: chosen.runId, now, allowUntested: true, onNotice, // organizeGate already spoke
689
+ aborted: () => stop,
690
+ onProgress: () => { i++; bar.tick(i); },
691
+ });
692
+ bar.end(ui.t("organize.progressDone", { n: i, total: n, dur: ui.f.dur(now() - started) }));
693
+ } finally {
694
+ bar.dispose();
695
+ for (const sig of STOP_SIGNALS) signals.off(sig, onSignal);
696
+ }
697
+ if (r.failed.length > 0) io.stdout(failedTable(ui, r.failed, b.names).join("\n") + "\n");
698
+ const parts = [r.done > 0 ? ui.t("organize.made", { n: r.done }) : ui.t("organize.madeNone")];
699
+ if (r.skippedChanged > 0) parts.push(ui.t("organize.leftAlone", { n: r.skippedChanged }));
700
+ if (r.failed.length > 0) parts.push(ui.t("organize.failedCount", { n: r.failed.length }));
701
+ if (r.done > 0) parts.push(ui.t("organize.runUndo", { runId: shownText(chosen.runId) }));
702
+ io.stdout(parts.join(" ") + "\n");
703
+ if (r.status === "aborted") {
704
+ io.stderr(`${ui.t("organize.interrupted")}\n`);
705
+ return 130;
706
+ }
707
+ return r.failed.length > 0 ? 5 : 0;
708
+ } finally {
709
+ await api.close();
710
+ }
711
+ } finally {
712
+ await lock.release();
713
+ }
714
+ }
715
+
716
+ /** The changes that could not be made: the change in words and the error, as a table (at most 20 rows). */
717
+ function failedTable(ui , failed , names , width = ui.width) {
718
+ const { s } = ui;
719
+ const rows = failed.slice(0, 20).map((f) => [actionLine(f.action, names), failureWords(f.error, ui.lang)] );
720
+ const out = [...fitLine(`${s("err", s.sym.err)} ${s("title", ui.t("organize.failedTitle", { n: failed.length }))}`, width, 2),
721
+ ...uiTable(s, [
722
+ { header: ui.t("organize.col.change"), get: (r) => (r )[0], priority: 5, min: 24 },
723
+ { header: ui.t("organize.col.why"), get: (r) => (r )[1], priority: 9, min: 16 },
724
+ ], rows, width)];
725
+ if (failed.length > rows.length) out.push(...fitLine(s("muted", `${s.sym.ellipsis} ${ui.t("common.andMore", { n: failed.length - rows.length })} (t3sm runs)`), width));
726
+ return out;
727
+ }
728
+
729
+ // ---------------- undo ----------------
730
+
731
+ /**
732
+ * The newest run of `organize` / `projects rename` with organize changes that no rollback has undone yet (`latest`),
733
+ * and whether there is any such run at all, undone or not (`any`).
734
+ */
735
+ export function latestOrganizeRun(entries ) {
736
+ const command = new Map ();
737
+ const undone = new Set ();
738
+ for (const e of entries) {
739
+ if (e.t === "run-start") command.set(e.runId, e.command);
740
+ else if (e.t === "rolled-back") undone.add(e.targetRunId);
741
+ }
742
+ let latest = null;
743
+ let any = false;
744
+ for (const e of entries) {
745
+ if (e.t !== "organize-change" || !OWN_COMMANDS.has(command.get(e.runId) ?? "")) continue;
746
+ any = true;
747
+ if (!undone.has(e.runId)) latest = e.runId;
748
+ }
749
+ return { latest, any };
750
+ }
751
+
752
+
753
+
754
+
755
+ /** The organize-change entries of `target`, by kind and target (what each undo item reverts). */
756
+ export function changesOf(entries , target ) {
757
+ const m = new Map ();
758
+ for (const e of entries) if (e.t === "organize-change" && e.runId === target) m.set(`${e.kind}\u0000${e.target}`, e);
759
+ return m;
760
+ }
761
+
762
+ /**
763
+ * An undo's items in organize's words (shared with `t3sm rollback`): what is reverted, what is left alone and why, what
764
+ * could not be reverted. Titles come from `names` (T3 Code as it was before the undo); never ids or raw JSON.
765
+ */
766
+ export function undoLines(items , changes , names ) {
767
+ const entry = (x ) => changes.get(`${x.kind}\u0000${x.target}`) ?? { kind: x.kind, target: x.target, previous: null, next: null };
768
+ const of = (status , line ) => items.filter((x) => x.status === status).map(line);
769
+ const why = (x ) => cliT(names.lang,
770
+ /no longer exists/.test(x.note ?? "") ? "organize.undo.gone" : x.kind === "project-delete" ? "organize.undo.folderTaken" : "organize.undo.changed");
771
+ return {
772
+ reverted: of("reverted", (x) => revertLine(entry(x), names)),
773
+ userChanged: of("user-changed", (x) => `${subjectOf(entry(x), names)}: ${why(x)}`),
774
+ kept: of("kept", (x) => `${subjectOf(entry(x), names)}: ${cliT(names.lang, "organize.undo.kept")}`),
775
+ failed: of("failed", (x) => `${revertLine(entry(x), names)}: ${failureWords(x.note ?? "failed", names.lang)}`),
776
+ };
777
+ }
778
+
779
+ /**
780
+ * An organize undo (or its preview, `dry`) in the user's language: a panel saying what is reverted, then what is
781
+ * reverted, what is left alone and why, and what could not be reverted (at most 20 items each).
782
+ */
783
+ export function renderUndo(ui , r , target , dry , changes , names , width = ui.width) {
784
+ const { s, t } = ui;
785
+ const u = undoLines(r.items, changes, names);
786
+ const head = dry ? t("organize.undo.would", { n: r.reverted, runId: shownText(target) })
787
+ : t(r.runId ? "organize.undo.didJournal" : "organize.undo.did", { n: r.reverted, runId: shownText(target), journal: shownText(r.runId ?? "") });
788
+ const out = noteLines(s, dry ? "info" : "ok", head, width);
789
+ const list = (key , xs ) => {
790
+ const l = sectionLines(s, t(key), xs, width, { max: 20, more: (n) => t("common.andMore", { n }) });
791
+ if (l.length > 0) out.push("", ...l);
792
+ };
793
+ list(dry ? "organize.undo.willRevert" : "organize.undo.reverted", u.reverted);
794
+ list("organize.undo.leftAlone", u.userChanged);
795
+ list("organize.undo.keptTitle", u.kept);
796
+ if (r.alreadyRestored > 0) out.push("", ...textLines(s, t("organize.undo.alreadyBack", { n: r.alreadyRestored }), width));
797
+ list("organize.undo.couldNot", u.failed);
798
+ return out;
799
+ }
800
+
801
+ async function undo(p , run , io , deps ) {
802
+ const home = deps.home ?? homedir();
803
+ const now = deps.now ?? Date.now;
804
+ const dir = stateDir(io.env, home);
805
+ const j = new Journal(join(dir, "journal.jsonl"));
806
+ const entries = await j.readAll();
807
+ const ui = cliUi(io, { now });
808
+ const found = latestOrganizeRun(entries);
809
+ const target = run ?? found.latest;
810
+ if (target === null) {
811
+ io.stdout(`${ui.t(found.any ? "organize.undo.allUndone" : "organize.undo.noRuns")}\n`);
812
+ return 0;
813
+ }
814
+ // Without a run id the target is picked here: never silently with --yes (as `t3sm rollback`).
815
+ if (p.yes && run === null) {
816
+ io.stderr(`${ui.t("organize.undo.needsRun", { runId: shownText(target) })}\n`);
817
+ return 2;
818
+ }
819
+ if (!entries.some((e) => e.runId === target)) throw new ConfigError(`No run ${shownText(target)} in the journal. Run \`t3sm runs\` to list them.`);
820
+ if (!entries.some((e) => e.t === "organize-change" && e.runId === target)) {
821
+ throw new ConfigError(`Run ${shownText(target)} made no organize changes. Use \`t3sm rollback --run ${shownText(target)}\` to undo it.`);
822
+ }
823
+ assertOrganizeOnly(entries, target); // a sync run that imported too: rollback undoes it whole (exit 2)
824
+ const onNotice = noticeOnce(io);
825
+ const changes = changesOf(entries, target);
826
+ // settings:write only when the undo may put T3 Code's own auto-settle option back (never for a preview).
827
+ const settingBack = [...changes.values()].some((c) => c.kind === "auto-settle");
828
+ const connect = () => connectForOrganize(deps.connect ?? connectT3, home, p.allowUntested, onNotice, !p.dryRun && settingBack);
829
+ const base = { journal: j, now, allowUntested: true, onNotice }; // organizeGate already spoke
830
+ // Titles as T3 Code shows them before anything is reverted.
831
+ const names = async (api ) => namesOf(await api.listThreads(), await api.listProjects(), home, ui.lang);
832
+ const say = (l ) => io.stdout(l.join("\n") + "\n");
833
+
834
+ if (p.dryRun) {
835
+ const api = await connect();
836
+ try {
837
+ const n = await names(api);
838
+ const r = await undoOrganize(target, { ...base, api, dryRun: true });
839
+ say(renderUndo(ui, r, target, true, changes, n));
840
+ say(["", ...noteLines(ui.s, "info", ui.t("organize.undo.dryDone", { runId: shownText(target) }), ui.width)]);
841
+ } finally {
842
+ await api.close();
843
+ }
844
+ return 0;
845
+ }
846
+
847
+ const lock = await acquireLock(dir);
848
+ if (!lock) { reportLockBusy(io); return 0; }
849
+ try {
850
+ const rec = await recoverPendingMtimes(j);
851
+ if (rec.restored.length > 0) io.stderr(`${cliT(io.lang ?? "en", "apply.recovered", { n: rec.restored.length })}\n`);
852
+ const api = await connect();
853
+ try {
854
+ const n = await names(api);
855
+ if (!p.yes) {
856
+ const preview = await undoOrganize(target, { ...base, api, dryRun: true });
857
+ say(renderUndo(ui, preview, target, true, changes, n));
858
+ if (preview.reverted === 0) { io.stdout(`${ui.t("organize.undo.nothing", { runId: shownText(target) })}\n`); return 0; }
859
+ io.stdout("\n");
860
+ if (!(await confirm(io, ui.t("organize.confirmUndo", { runId: shownText(target) })))) { io.stdout(`${ui.t("common.nothingChanged")}\n`); return 0; }
861
+ }
862
+ const r = await undoOrganize(target, { ...base, api });
863
+ if (r.runId === null && r.failed.length === 0) { io.stdout(`${ui.t("organize.undo.nothing", { runId: shownText(target) })}\n`); return 0; }
864
+ say(renderUndo(ui, r, target, false, changes, n));
865
+ return r.failed.length > 0 ? 5 : 0;
866
+ } finally {
867
+ await api.close();
868
+ }
869
+ } finally {
870
+ await lock.release();
871
+ }
872
+ }