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,495 @@
1
+ // Applies an organize plan (spec §5) to T3 Code, journals every change, and undoes a run (`t3sm organize --undo`,
2
+ // `t3sm rollback <organize run>`). Callers: `t3sm organize` and `t3sm projects rename --suggest` (src/cli/commands),
3
+ // the assistant, sync.
4
+ // applyOrganize and undoOrganize REQUIRE the caller to hold the state-dir lock (acquireLock) and to have run
5
+ // recoverPendingMtimes first (a dry undo needs neither: it writes nothing).
6
+ //
7
+ // Contract (rulings R13, R14):
8
+ // - `organize-change` is journaled only AFTER T3 accepted the command. A crash in between leaves T3 changed but
9
+ // unjournaled; the next plan sees that state and plans nothing for it.
10
+ // - Before each action the target must still be in the plan's `previous` state. Freshness: projects (and, for
11
+ // project-delete, threads) are read again right before every project action and the auto-settle setting right before
12
+ // its write; threads are read at the start and again every THREAD_BATCH thread actions (one thread read costs the
13
+ // whole HTTP shell plus the archived snapshot). A target changed since the plan is skipped (`skippedChanged`).
14
+ // - A write that throws is confirmed by reading T3 again ONLY when T3 may have applied it: a reply that did not decode
15
+ // (ShapeError after a 2xx), or a lost reply (RPC timeout / closed socket, HTTP without a response). Then, when T3
16
+ // shows the planned value, the change is journaled, so a confirmed change is never left unjournaled. A refusal (HTTP
17
+ // 4xx/5xx, an RPC domain error such as ProjectNotFoundError, a bad value) is a plain failure, never journaled.
18
+ // - A journal append that fails stops the run with JournalWriteError naming what T3 Code already holds.
19
+ // - Settle-family values (settle, unsettle) are compared as the override T3 shows (`settleShown`): a backdated settle's
20
+ // `{ settledAt }` is "settled"; a null `previous` is the side the change left (T3 cannot clear an override).
21
+ // - Undo goes newest first and acts only on targets still at the value t3sm set; anything else was changed by the user
22
+ // since and stays (`skippedUserChanged`). Undo never writes `organize-change` (it journals `organize-undone`, and
23
+ // `project-created` for a project it re-creates), never deletes or rewrites a journal line, so an undone target
24
+ // differs from t3sm's last `next` and the planner leaves it alone from then on.
25
+ // - Any T3 Code version (owner's decision): organizeGate warns on an unverified one; strict decoding is the guard.
26
+
27
+
28
+ import { newRunId, } from "../core/journal.js";
29
+ import { ConfigError } from "../core/config.js";
30
+ import { sameCwd } from "../core/paths.js";
31
+
32
+ import { organizeGate } from "../t3/compat.js";
33
+ import { RpcClosed, RpcTimeout, ShapeError, T3HttpError, redact } from "../t3/errors.js";
34
+ import { JournalWriteError } from "../ops/quarantine.js";
35
+ import { changeKind, isObj, isShownMark, isVisibleInProject, settleShown } from "./history.js";
36
+ import { AUTO_SETTLE_TARGET } from "./plan.js";
37
+
38
+
39
+
40
+
41
+
42
+
43
+
44
+
45
+
46
+
47
+
48
+
49
+
50
+
51
+
52
+
53
+
54
+
55
+
56
+
57
+
58
+
59
+
60
+
61
+
62
+
63
+
64
+
65
+
66
+
67
+
68
+
69
+
70
+
71
+
72
+
73
+
74
+
75
+
76
+
77
+
78
+
79
+
80
+
81
+
82
+
83
+
84
+
85
+
86
+
87
+
88
+
89
+
90
+
91
+
92
+
93
+
94
+
95
+
96
+
97
+
98
+
99
+
100
+
101
+ const KINDS = new Set (["archive", "title", "unsettle", "settle", "pin", "unpin", "project-delete", "project-title", "auto-settle"]);
102
+ const THREAD_KINDS = new Set (["archive", "title", "unsettle", "settle"]);
103
+ const PROJECT_KINDS = new Set (["pin", "unpin", "project-delete", "project-title"]);
104
+ /** The journal entries of a run that only organized (what `organize --undo` reverts whole). */
105
+ const ORGANIZE_RUN_KINDS = new Set(["run-start", "run-end", "organize-change", "organize-failed"]);
106
+ /** Thread actions between two reads of T3's thread list. */
107
+ export const THREAD_BATCH = 50;
108
+
109
+ /** T3 Code could not be read before the first revert (nothing was changed). */
110
+ export class OrganizeReadError extends Error {
111
+ constructor(message ) {
112
+ super(message);
113
+ this.name = "OrganizeReadError";
114
+ }
115
+ }
116
+
117
+ /** A failure reason as journaled and shown: secrets redacted, one line, at most 200 characters (code points: never half a pair). */
118
+ export const failureText = (error ) => {
119
+ const one = [...redact(error).replace(/\s+/g, " ").trim()];
120
+ return one.length > 200 ? `${one.slice(0, 199).join("")}…` : one.join("");
121
+ };
122
+
123
+ const msg = (e ) => (e instanceof Error ? e.message : String(e));
124
+
125
+ /** Equality of journal values (primitives and plain objects such as project-delete's `{ title, workspaceRoot }`). */
126
+ function same(a , b ) {
127
+ if (a === b) return true;
128
+ if (!isObj(a) || !isObj(b)) return false;
129
+ const ka = Object.keys(a);
130
+ return ka.length === Object.keys(b).length && ka.every((k) => Object.hasOwn(b, k) && same(a[k], b[k]));
131
+ }
132
+
133
+ /** T3 as read once at the start; updated with every change made since. */
134
+
135
+
136
+ async function loadWorld(api , kinds ) {
137
+ const ks = [...kinds];
138
+ // project-delete also needs the threads: T3 refuses to delete a project that holds one.
139
+ const needThreads = ks.some((k) => THREAD_KINDS.has(k) || k === "project-delete");
140
+ const needProjects = ks.some((k) => PROJECT_KINDS.has(k));
141
+ return {
142
+ threads: needThreads ? await threadMap(api) : new Map(),
143
+ projects: needProjects ? await api.listProjects() : [],
144
+ };
145
+ }
146
+
147
+ const threadMap = async (api ) => new Map((await api.listThreads()).map((t) => [t.id, t] ));
148
+
149
+ /** Reads again what the next action is judged on (the freshness rule in the header). */
150
+ function refresher(api , w ) {
151
+ let threadActions = 0;
152
+ return async (kind) => {
153
+ if (THREAD_KINDS.has(kind)) {
154
+ if (threadActions > 0 && threadActions % THREAD_BATCH === 0) w.threads = await threadMap(api);
155
+ threadActions++;
156
+ } else if (PROJECT_KINDS.has(kind)) {
157
+ w.projects = await api.listProjects();
158
+ if (kind === "project-delete") w.threads = await threadMap(api);
159
+ }
160
+ };
161
+ }
162
+
163
+ /** T3 may have applied a write that threw this: its reply did not decode, or never arrived. */
164
+ function mayHaveApplied(e ) {
165
+ return e instanceof ShapeError || e instanceof RpcTimeout || e instanceof RpcClosed || (e instanceof T3HttpError && e.status === null);
166
+ }
167
+
168
+ /** Appends, turning a failure into a JournalWriteError that says what T3 Code already holds. */
169
+ async function appendOrStop(j , e , what ) {
170
+ try {
171
+ await j.append(e);
172
+ } catch (err) {
173
+ throw new JournalWriteError(`Could not write the journal (${msg(err)}) ${what}.`);
174
+ }
175
+ }
176
+
177
+
178
+
179
+ /** The value of `kind` on `target` as organize journals it (see OrganizeAction's previous/next per kind). */
180
+ async function current(api , w , kind , target ) {
181
+ if (kind === "auto-settle") return { exists: true, value: await api.getServerSetting(AUTO_SETTLE_TARGET) };
182
+ if (THREAD_KINDS.has(kind)) {
183
+ const t = w.threads.get(target);
184
+ if (!t) return { exists: false };
185
+ return { exists: true, value: kind === "archive" ? t.archived : kind === "title" ? t.title : (t.settledOverride ?? null) };
186
+ }
187
+ const p = w.projects.find((x) => x.id === target);
188
+ // A deleted project is the state `null` (listProjects drops deleted ones).
189
+ if (kind === "project-delete") return { exists: true, value: p ? { title: p.title, workspaceRoot: p.workspaceRoot } : null };
190
+ if (!p) return { exists: false };
191
+ return { exists: true, value: kind === "project-title" ? p.title : p.pinned };
192
+ }
193
+
194
+ /** Reads T3 again for one target (after a write that threw). */
195
+ async function reread(api , kind , target ) {
196
+ return current(api, await loadWorld(api, [kind]), kind, target);
197
+ }
198
+
199
+ /** Sets `kind` on `target` to `value` through T3's API. project-delete only deletes (re-creating is undo's own step). */
200
+ async function write(api , kind , target , value ) {
201
+ const bad = () => { throw new Error(`invalid ${kind} value ${JSON.stringify(value)}`); };
202
+ switch (kind) {
203
+ case "archive":
204
+ if (typeof value !== "boolean") bad();
205
+ return value ? api.archiveThread(target) : api.unarchiveThread(target);
206
+ case "title":
207
+ if (typeof value !== "string" || value.trim() === "") bad();
208
+ return api.setThreadTitle(target, value );
209
+ case "unsettle": case "settle": {
210
+ // A backdated settle carries the date T3 Code records (sent only when backdating is on: src/t3/api.ts).
211
+ if (isObj(value) && typeof value.settledAt === "string") return api.settleThread(target, value.settledAt);
212
+ const shown = settleShown(kind, value);
213
+ if (shown === "active") return api.unsettleThread(target);
214
+ if (shown === "settled") return api.settleThread(target);
215
+ return bad();
216
+ }
217
+ case "pin": case "unpin":
218
+ if (typeof value !== "boolean") bad();
219
+ return api.setProjectPinned(target, value );
220
+ case "project-delete":
221
+ if (value !== null) bad();
222
+ return api.deleteProject(target);
223
+ case "auto-settle":
224
+ if (value !== null && typeof value !== "number") bad();
225
+ await api.setAutoSettleAfterDays(value );
226
+ return;
227
+ case "project-title":
228
+ if (typeof value !== "string" || value.trim() === "") bad();
229
+ return api.setProjectTitle(target, value );
230
+ }
231
+ }
232
+
233
+ /** Mirrors a change T3 accepted into the snapshot. */
234
+ function remember(w , kind , target , value ) {
235
+ const t = w.threads.get(target);
236
+ if (kind === "archive" && t) t.archived = value ;
237
+ else if (kind === "title" && t) t.title = value ;
238
+ else if ((kind === "unsettle" || kind === "settle") && t) t.settledOverride = settleShown(kind, value) ;
239
+ else if (kind === "pin" || kind === "unpin" || kind === "project-title") {
240
+ const p = w.projects.find((x) => x.id === target);
241
+ if (p && kind === "project-title") p.title = value ;
242
+ else if (p) p.pinned = value ;
243
+ } else if (kind === "project-delete" && value === null) w.projects = w.projects.filter((x) => x.id !== target);
244
+ }
245
+
246
+ /**
247
+ * Runs `fn` (a write). When it throws an error after which T3 may have applied it (mayHaveApplied), reads T3 again and
248
+ * returns true if T3 shows `want`. Returns the error message otherwise: a refusal is never confirmed.
249
+ */
250
+ async function writeConfirmed(api , kind , target , want , fn ) {
251
+ try {
252
+ await fn();
253
+ return true;
254
+ } catch (e) {
255
+ if (!mayHaveApplied(e)) return msg(e);
256
+ try {
257
+ const c = await reread(api, kind, target);
258
+ if (c.exists && same(c.value, want)) return true;
259
+ } catch { /* report the write's own error */ }
260
+ return msg(e);
261
+ }
262
+ }
263
+
264
+ export async function applyOrganize(plan , d ) {
265
+ organizeGate(d.api.version, { allowUntested: d.allowUntested ?? false, onNotice: d.onNotice });
266
+ const r = { done: 0, skippedChanged: 0, failed: [], status: "ok" };
267
+ if (plan.actions.length === 0) return r;
268
+ const now = d.now ?? Date.now;
269
+ const command = d.command === undefined ? "organize" : d.command;
270
+ const j = d.journal;
271
+ const w = await loadWorld(d.api, plan.actions.map((a) => a.kind));
272
+ const refresh = refresher(d.api, w);
273
+
274
+ let started = false;
275
+ const begin = async () => {
276
+ if (started) return;
277
+ if (command !== null) await appendOrStop(j, { t: "run-start", runId: d.runId, at: new Date(now()).toISOString(), command }, "before the first change; nothing was changed");
278
+ started = true;
279
+ };
280
+ // Journaled before it is counted (the reason survives the run); a journal failure stops the run like any other write.
281
+ const fail = async (a , error ) => {
282
+ const shown = failureText(error);
283
+ await begin();
284
+ await appendOrStop(j, { t: "organize-failed", runId: d.runId, kind: a.kind, target: a.target, projectId: a.projectId, error: shown },
285
+ `after ${a.kind} ${a.target} failed (${shown}): the reason is not journaled`);
286
+ r.failed.push({ action: a, error: shown });
287
+ return `failed (${shown})`;
288
+ };
289
+
290
+ const one = async (a ) => {
291
+ let cur ;
292
+ try {
293
+ await refresh(a.kind);
294
+ cur = await current(d.api, w, a.kind, a.target);
295
+ } catch (e) { return await fail(a, `could not read T3 Code: ${msg(e)}`); }
296
+ // A mark of a thread already shown (isShownMark) expects it still shown (not archived, settledAt null) and with no
297
+ // override at all, right before the write: a thread put on the shelf since (by hand, or by T3 Code's own option,
298
+ // which leaves no override) or archived is left as it is.
299
+ const markGone = isShownMark(a) && !(w.threads.has(a.target) && isVisibleInProject(w.threads.get(a.target) ));
300
+ const stale = !cur.exists || markGone || !same(cur.value, isShownMark(a) ? null : a.previous)
301
+ || (a.kind === "project-delete" && [...w.threads.values()].some((t) => t.projectId === a.target));
302
+ if (stale) {
303
+ r.skippedChanged++;
304
+ return "skipped (changed in T3 Code since the plan)";
305
+ }
306
+ await begin();
307
+ const ok = await writeConfirmed(d.api, a.kind, a.target, settleShown(a.kind, a.next), () => write(d.api, a.kind, a.target, a.next));
308
+ if (ok !== true) return await fail(a, ok);
309
+ remember(w, a.kind, a.target, a.next);
310
+ await appendOrStop(j, { t: "organize-change", runId: d.runId, kind: a.kind, target: a.target, previous: a.previous, next: a.next },
311
+ `after T3 Code accepted ${a.kind} ${a.target}: that change is in T3 Code but not journaled (the ${r.done} before it are)`);
312
+ r.done++;
313
+ return "done";
314
+ };
315
+
316
+ try {
317
+ const n = plan.actions.length;
318
+ for (const [i, a] of plan.actions.entries()) {
319
+ if (d.aborted?.()) { r.status = "aborted"; break; }
320
+ const outcome = await one(a);
321
+ d.onProgress?.(`[${i + 1}/${n}] ${a.kind} ${a.target}: ${outcome}`);
322
+ }
323
+ } catch (e) {
324
+ // The journal could not be written (JournalWriteError): stop; T3 may hold one change more than the journal.
325
+ if (started && command !== null) await j.append({ t: "run-end", runId: d.runId, at: new Date(now()).toISOString(), status: "aborted" }).catch(() => {});
326
+ throw e;
327
+ }
328
+ if (r.status !== "aborted") r.status = r.failed.length > 0 ? "partial" : "ok";
329
+ if (started && command !== null) await j.append({ t: "run-end", runId: d.runId, at: new Date(now()).toISOString(), status: r.status });
330
+ return r;
331
+ }
332
+
333
+
334
+
335
+
336
+
337
+
338
+
339
+
340
+
341
+
342
+
343
+
344
+
345
+ /** Projects re-created by earlier undos of `targetRunId` (runs whose run-start is `rollback <targetRunId>`). */
346
+ function recreatedBy(history , targetRunId ) {
347
+ const undoRuns = new Set(history.filter((e) => e.t === "run-start" && e.command === `rollback ${targetRunId}`).map((e) => e.runId));
348
+ return new Set(history.filter((e) => e.t === "project-created" && undoRuns.has(e.runId)).map((e) => e.projectId));
349
+ }
350
+
351
+ /**
352
+ * Reverts the `organize-change` entries of `targetRunId` among `entries` (journal order), newest first. Shared by
353
+ * undoOrganize and rollbackRun, which own the run (run-start through `begin`, rolled-back, run-end).
354
+ */
355
+ export async function undoOrganizeEntries(entries , targetRunId , c , items = []) {
356
+ const mine = entries.filter((e) => e.t === "organize-change" && e.runId === targetRunId);
357
+ if (mine.length === 0) return items;
358
+ const valid = mine.filter((e) => typeof e.kind === "string" && KINDS.has(e.kind) && typeof e.target === "string" && e.target !== "");
359
+ let w ;
360
+ try { w = await loadWorld(c.api, valid.map((e) => e.kind)); } catch (e) { throw new OrganizeReadError(`could not read T3 Code (${msg(e)})`); }
361
+ const refresh = refresher(c.api, w);
362
+ const recreated = recreatedBy(c.history ?? entries, targetRunId);
363
+ const reverted = () => items.filter((x) => x.status === "reverted").map((x) => `${x.kind} ${x.target}`).join(", ") || "nothing";
364
+ const begin = async () => {
365
+ try { return await c.begin(); } catch (err) {
366
+ throw err instanceof JournalWriteError ? err : new JournalWriteError(`Could not write the journal (${msg(err)}) before the first revert; nothing was changed.`);
367
+ }
368
+ };
369
+ /** Journals a revert T3 already holds; a failure stops the undo and says what is reverted (a rerun skips those). */
370
+ const record = (e , what ) =>
371
+ appendOrStop(c.journal, e, `after T3 Code accepted the undo of ${what}; reverted before it: ${reverted()}. Run the undo again: what is back already is skipped`);
372
+
373
+ const one = async (e ) => {
374
+ // Labelled by what the change really is (a legacy follow carry, kind unsettle -> "settled", is a settle).
375
+ const label = typeof e.kind === "string" ? changeKind(e.kind, e.next) : e.kind;
376
+ const it = (status , note ) =>
377
+ (note === undefined ? { kind: label, target: e.target, status } : { kind: label, target: e.target, status, note });
378
+ if (!valid.includes(e)) return it("failed", "malformed organize-change journal entry");
379
+ let cur ;
380
+ try {
381
+ await refresh(e.kind);
382
+ cur = await current(c.api, w, e.kind, e.target);
383
+ } catch (err) { return it("failed", `could not read T3 Code: ${msg(err)}`); }
384
+ if (!cur.exists) return it("user-changed", "no longer exists in T3 Code");
385
+ // A mark of a thread already shown cannot be undone: it was shown and stays shown, and T3 Code cannot remove the
386
+ // override ("kept"); unless the user settled it since.
387
+ if (isShownMark(e)) return cur.value === "active" || cur.value === null ? it("kept") : it("user-changed", `changed since: now ${JSON.stringify(cur.value)}`);
388
+ // A legacy follow carry (kind unsettle, next "settled") is a settle: its null previous means "shown".
389
+ const kind = changeKind(e.kind, e.next);
390
+ if (same(cur.value, settleShown(kind, e.previous))) return it("already");
391
+ if (!same(cur.value, settleShown(kind, e.next))) return it("user-changed", `changed since: now ${JSON.stringify(cur.value)}`);
392
+
393
+ if (e.kind === "project-delete") {
394
+ const prev = e.previous;
395
+ if (!isObj(prev) || typeof prev.title !== "string" || prev.title === "" || typeof prev.workspaceRoot !== "string" || prev.workspaceRoot === "") {
396
+ return it("failed", "malformed organize-change journal entry (previous)");
397
+ }
398
+ const root = prev.workspaceRoot;
399
+ const taken = (ps ) => ps.find((p) => sameCwd(p.workspaceRoot, root, c.platform));
400
+ const there = taken(w.projects);
401
+ if (there) return recreated.has(there.id) ? it("already") : it("user-changed", `a project for ${root} exists again`);
402
+ if (c.dryRun) return it("reverted");
403
+ const runId = await begin();
404
+ let created ;
405
+ try {
406
+ created = await c.api.createProject(root, prev.title);
407
+ } catch (err) {
408
+ // T3 may have created it and the reply been lost: a project at that root now is the one just made.
409
+ if (mayHaveApplied(err)) { try { created = taken(await c.api.listProjects()); } catch { /* report the create's own error */ } }
410
+ if (!created) return it("failed", msg(err));
411
+ }
412
+ w.projects.push(created);
413
+ const what = `${e.kind} ${e.target} (re-created as ${created.id})`;
414
+ await record({ t: "project-created", runId, projectId: created.id, root, title: created.title }, what);
415
+ await record({ t: "organize-undone", runId, targetRunId, kind: e.kind, target: e.target, previous: null, next: e.previous }, what);
416
+ return it("reverted", `re-created as ${created.id}`);
417
+ }
418
+
419
+ if (c.dryRun) {
420
+ remember(w, kind, e.target, e.previous);
421
+ return it("reverted");
422
+ }
423
+ const runId = await begin();
424
+ const ok = await writeConfirmed(c.api, kind, e.target, settleShown(kind, e.previous), () => write(c.api, kind, e.target, e.previous));
425
+ if (ok !== true) return it("failed", ok);
426
+ remember(w, kind, e.target, e.previous);
427
+ await record({ t: "organize-undone", runId, targetRunId, kind: e.kind, target: e.target, previous: cur.value, next: e.previous }, `${e.kind} ${e.target}`);
428
+ return it("reverted");
429
+ };
430
+
431
+ const n = mine.length;
432
+ for (const [i, e] of [...mine].reverse().entries()) {
433
+ const x = await one(e);
434
+ items.push(x);
435
+ c.onProgress?.(`[${i + 1}/${n}] undo ${x.kind} ${x.target}: ${x.status}${x.note ? ` (${x.note})` : ""}`);
436
+ }
437
+ return items;
438
+ }
439
+
440
+ /**
441
+ * Refuses (ConfigError, exit 2) a run that did more than organize (a sync that imported, then organized what it
442
+ * imported): undoing only its organize changes would journal `rolled-back` for the whole run while its imports and
443
+ * files stay. `t3sm rollback --run <run>` undoes all of it.
444
+ */
445
+ export function assertOrganizeOnly(entries , runId ) {
446
+ if (entries.some((e) => e.runId === runId && !ORGANIZE_RUN_KINDS.has(e.t))) {
447
+ throw new ConfigError(`This run also imported conversations; use \`t3sm rollback --run ${runId}\` to undo all of it.`);
448
+ }
449
+ }
450
+
451
+ /** Reverts one organize run (`t3sm organize --undo <run>`); journals itself as `rollback <run>`, like `t3sm rollback`. */
452
+ export async function undoOrganize(runId , d ) {
453
+ const j = d.journal;
454
+ const all = await j.readAll();
455
+ if (!all.some((e) => e.runId === runId)) throw new ConfigError(`No run ${runId} in the journal. Run \`t3sm runs\` to list them.`);
456
+ if (all.some((e) => e.t === "run-start" && e.runId === runId && typeof e.command === "string" && e.command.startsWith("rollback"))) {
457
+ throw new ConfigError("Cannot roll back a rollback run.");
458
+ }
459
+ assertOrganizeOnly(all, runId);
460
+ organizeGate(d.api.version, { allowUntested: d.allowUntested ?? false, onNotice: d.onNotice });
461
+
462
+ let rb = null;
463
+ const begin = async () => {
464
+ if (rb === null) {
465
+ const id = newRunId(new Date(d.now()));
466
+ await j.append({ t: "run-start", runId: id, at: new Date(d.now()).toISOString(), command: `rollback ${runId}` });
467
+ rb = id;
468
+ }
469
+ return rb;
470
+ };
471
+ let items ;
472
+ try {
473
+ items = await undoOrganizeEntries(all, runId, {
474
+ api: d.api, journal: j, begin, dryRun: d.dryRun ?? false, platform: d.platform ?? process.platform, onProgress: d.onProgress,
475
+ });
476
+ } catch (e) {
477
+ if (rb !== null) await j.append({ t: "run-end", runId: rb, at: new Date(d.now()).toISOString(), status: "aborted" }).catch(() => {});
478
+ throw e;
479
+ }
480
+ const failed = items.filter((x) => x.status === "failed").map((x) => ({ kind: x.kind, target: x.target, error: x.note ?? "failed" }));
481
+ if (rb !== null) {
482
+ const at = new Date(d.now()).toISOString();
483
+ await j.append({ t: "rolled-back", runId: rb, targetRunId: runId, at });
484
+ await j.append({ t: "run-end", runId: rb, at, status: failed.length > 0 ? "partial" : "ok" });
485
+ }
486
+ return {
487
+ runId: rb,
488
+ reverted: items.filter((x) => x.status === "reverted").length,
489
+ skippedUserChanged: items.filter((x) => x.status === "user-changed").length,
490
+ alreadyRestored: items.filter((x) => x.status === "already").length,
491
+ kept: items.filter((x) => x.status === "kept").length,
492
+ failed,
493
+ items,
494
+ };
495
+ }