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,47 @@
1
+ // An elevated shell on Windows (Run as Administrator): `t3sm start`, `schedule` and `update` still work, but what they
2
+ // install (the scheduled task, the /t3sm plugin, the global t3sm) belongs to the user that runs them, which may not be
3
+ // the account the person signs in with. t3sm warns once and never blocks. Detected with `net session`, which only an
4
+ // elevated shell may run (exit 0): by its absolute path under System32 (never through PATH or a shell), with a time
5
+ // limit and without CLAUDE_CONFIG_DIR. Anything else (another platform, a failure, a timeout) counts as not elevated.
6
+
7
+
8
+ import { cliT, } from "../i18n/cli.js";
9
+ import { defaultRunner, } from "../t3/auth.js";
10
+ import { system32 } from "../core/sysroot.js";
11
+
12
+ export const NET_SESSION_TIMEOUT_MS = 5_000;
13
+
14
+ export async function isElevated(platform , run , env ) {
15
+ if (platform !== "win32") return false;
16
+ const childEnv = {};
17
+ for (const [k, v] of Object.entries(env)) if (v !== undefined && k.toUpperCase() !== "CLAUDE_CONFIG_DIR") childEnv[k] = v;
18
+ try {
19
+ const r = await run(system32(env, "net.exe"), ["session"], { shell: false, timeoutMs: NET_SESSION_TIMEOUT_MS, env: childEnv });
20
+ return r.code === 0 && !r.timedOut;
21
+ } catch { return false; }
22
+ }
23
+
24
+ /** The real check: this process's platform and environment. */
25
+ export const realIsElevated = () => isElevated(process.platform, defaultRunner, process.env);
26
+
27
+ let warned = false;
28
+
29
+ /** Forget that the warning was given (tests). */
30
+ export function resetElevatedWarning() { warned = false; }
31
+
32
+ /** What a command installs, which the warning names: start (the schedule and the /t3sm commands), schedule, update. */
33
+
34
+ const WARNING = { start: "elevated.start", schedule: "elevated.schedule", update: "elevated.update" };
35
+
36
+ /**
37
+ * One line on stderr naming what `command` installs for this user only, at most once per process (`t3sm start` runs
38
+ * schedule and update itself), when `check` says the shell is elevated. Never throws and never blocks the command.
39
+ */
40
+ export async function warnIfElevated(io , check , command ) {
41
+ if (warned) return;
42
+ let elevated = false;
43
+ try { elevated = await check(); } catch { elevated = false; }
44
+ if (!elevated || warned) return;
45
+ warned = true;
46
+ io.stderr(`! ${cliT(io.lang ?? "en", WARNING[command])}\n`);
47
+ }
@@ -0,0 +1,39 @@
1
+ // The error to exit-code mapping and the plain-text message of every typed error (English: logs, --quiet, --json).
2
+ // Lives under ops/ so the operations (doctor, sync) use it without importing the CLI; src/cli/errors.ts draws the panel.
3
+ import { homedir } from "node:os";
4
+ import { ConfigError } from "../core/config.js";
5
+ import { RpcClosed, RpcError, RpcTimeout, ShapeError, T3AuthError, T3HttpError, T3Incompatible, T3NotRunning, redact } from "../t3/errors.js";
6
+ import { InstanceHomeDrift } from "./accounts.js";
7
+ import { ApplyRefusal } from "../apply/apply.js";
8
+ import { JournalWriteError } from "./quarantine.js";
9
+
10
+ /** An unexpected error's text, safe to print and log: tokens redacted, the user's home folder shown as ~. */
11
+ export function redactUnexpected(message ) {
12
+ const home = homedir();
13
+ const variants = [home, home.replaceAll("\\", "/"), home.replaceAll("/", "\\")].filter((h) => h.length > 1);
14
+ let out = message;
15
+ for (const h of [...new Set(variants)]) out = out.split(h).join("~");
16
+ return redact(out);
17
+ }
18
+
19
+ /** T3 Code unreachable mid-run, whichever transport noticed: the WebSocket closed or stopped answering, or no HTTP response. */
20
+ export const lostContact = (e ) => e instanceof RpcClosed || e instanceof RpcTimeout || (e instanceof T3HttpError && e.status === null);
21
+
22
+ /** Central error to exit-code mapping: 2 usage/config, 3 T3 not running, 4 incompatible/shape, 1 unexpected. */
23
+ export function describeError(e ) {
24
+ if (e instanceof T3NotRunning) return { code: 3, message: "T3 Code is not running. Open it from the Start menu and try again." };
25
+ if (e instanceof T3Incompatible || e instanceof ShapeError) return { code: 4, message: e.message };
26
+ if (e instanceof JournalWriteError) return { code: 1, message: e.message };
27
+ if (e instanceof ConfigError || e instanceof InstanceHomeDrift || e instanceof ApplyRefusal) return { code: 2, message: e.message };
28
+ if (e instanceof T3AuthError) return { code: 1, message: `${e.message}${e.hint ? `\n${e.hint}` : ""}` };
29
+ // Exit 3, like "not running".
30
+ if (lostContact(e)) return { code: 3, message: `Lost contact with T3 Code (${e.message}). Is it still running? Try again.` };
31
+ if (e instanceof T3HttpError || e instanceof RpcError) return { code: 1, message: `T3 Code rejected the request: ${e.message}` };
32
+ return { code: 1, message: `Unexpected error: ${redactUnexpected(e instanceof Error ? e.message : String(e))}` };
33
+ }
34
+
35
+ /** The message on one line (for --quiet and scheduler logs). */
36
+ export function oneLine(message ) {
37
+ return message.split(/\r?\n/).map((l) => l.trim()).filter(Boolean).join(" ");
38
+ }
39
+
@@ -0,0 +1,558 @@
1
+ // Rehome copies follow their original (spec §5.1.4). A conversation run from a folder T3 Code refuses (the home folder)
2
+ // is in T3 as a faithful copy inside a project folder (copyTranscript.faithfulCopy: only cwd / sessionId swapped,
3
+ // journaled `file-written` with `rehomeOf`). When the user keeps working on the ORIGINAL (VS Code, from the home
4
+ // folder), sync brings the new messages into T3: `followRehomed` runs after every apply, inside the cycle's run and
5
+ // lock, whatever `sync.autoMerge` says, and only for rehome copies (orphan copies of T3-native sessions included).
6
+ //
7
+ // The copy that follows an original is its newest write that still stands: the first copy, or a revision a standing
8
+ // `merged` entry uses (a rolled-back run counts for nothing; a revision never swapped in is "unfinished"). Rules:
9
+ // - a candidate is a copy whose original grew past the journaled `rehomeOf.size`. The original deleted, not grown,
10
+ // the copy gone, or the copy's thread archived by the user (or never imported): nothing, no error;
11
+ // - the copy itself changed since t3sm wrote it (its sha256 is not the journaled one: continued in T3 Code, or in a
12
+ // terminal): a CONFLICT. Nothing is written or sent; it is listed with both titles;
13
+ // - either file written in the last 10 minutes (ACTIVE_WINDOW_MS): deferred, so a conversation in use is never
14
+ // copied half-way, and one growth gives one revision (its id is the original's size: revisionUuid);
15
+ // - an original whose branch crosses a compaction is refused (`compacted`, as merge refuses it);
16
+ // - the state a rollback undid (same original, same size) is not followed again; a later growth is;
17
+ // - T3 Code unreachable: deferred, retried next cycle. At most FOLLOWS_PER_CYCLE per cycle (the rest: deferred).
18
+ //
19
+ // Modes (FOLLOW_MODE in src/t3/compat.ts, decided by the live spike S7):
20
+ // - "revision" (spike S5: T3 only continues a thread from records it wrote): the faithful copy of the grown original
21
+ // is written as a NEW file `<copy folder>/<revisionUuid(first copy id, original size)>.jsonl` with merge's revision
22
+ // write (journaled before it is published, never over a file t3sm did not write), imported through merge's import
23
+ // step (runWaves), then merge's archive step: the new thread gets the old thread's title and settled state
24
+ // (journaled as `organize-change`, so later organize runs and the history rule treat them as t3sm's), and only then
25
+ // is the old thread archived. Journaled like a merge (`thread-archived`, `merged`) plus `followed`, so one
26
+ // `t3sm rollback <run>` removes the revision, brings the old thread back and archives the new one. T3 has no thread
27
+ // pin call: only the title and the settled state are carried.
28
+ // - "refresh" (if S7 shows T3 growing the same thread): the copy is rewritten in place (same id) by materialize's
29
+ // refresh path (rename-over only after re-checking it is still t3sm's untouched write) and imported again into the
30
+ // same thread. Journaled `file-written`, `imported`, `followed` (newThread null). A rollback keeps the refreshed
31
+ // copy: T3's thread already holds its records.
32
+ // The original is only ever read.
33
+
34
+ import { mkdir, readFile, rm, utimes, writeFile } from "node:fs/promises";
35
+ import { createHash } from "node:crypto";
36
+ import path from "node:path";
37
+
38
+
39
+ import { effectiveWrites } from "../core/journal.js";
40
+ import { revisionUuid } from "../core/uuid.js";
41
+ import { atomicWrite, sha256File, statSafe, sweepWriteTemps, writeTempPath, } from "../core/fsutil.js";
42
+ import { pathKey } from "../core/paths.js";
43
+ import { isActive } from "../core/activity.js";
44
+ import { FOLLOW_MODE } from "../t3/compat.js";
45
+
46
+ import { RpcClosed, RpcTimeout, T3HttpError, T3NotRunning } from "../t3/errors.js";
47
+ import { readFaithfulCopy } from "../apply/copyTranscript.js";
48
+ import { WRITTEN_MAX_AGE_MS, materializeConversions, writtenMtime } from "../apply/materialize.js";
49
+
50
+ import { scanJsonl } from "../sources/jsonl.js";
51
+ import { proposeTitle } from "../organize/titles.js";
52
+ import { failureText } from "../organize/apply.js";
53
+ import { JournalWriteError } from "./quarantine.js";
54
+ import { IMPORT_THREAD, appendOrStop, importRevision, publishRevision, readBranch, removeIfOurs, standingMerges, swapThreads, } from "./merge.js";
55
+
56
+ /** sync follows at most this many rehome copies per cycle (each one is a wave of its own). */
57
+ export const FOLLOWS_PER_CYCLE = 10;
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
+ /** Refusals per original state (`<path key>|<size>|<mtimeMs>` -> reason): reported once, never re-read. */
87
+
88
+ const cachePath = (stateDir ) => path.join(stateDir, "cache", "follow.json");
89
+
90
+ async function readFollowCache(stateDir ) {
91
+ if (!stateDir) return { version: 1, refused: {} };
92
+ try {
93
+ const u = JSON.parse(await readFile(cachePath(stateDir), "utf8")) ;
94
+ if (u && u.version === 1 && typeof u.refused === "object" && u.refused !== null) return u;
95
+ } catch { /* missing or unreadable: start over */ }
96
+ return { version: 1, refused: {} };
97
+ }
98
+
99
+ async function writeFollowCache(stateDir , c ) {
100
+ if (!stateDir) return;
101
+ try {
102
+ await mkdir(path.dirname(cachePath(stateDir)), { recursive: true });
103
+ await atomicWrite(cachePath(stateDir), JSON.stringify(c) + "\n");
104
+ } catch { /* a cache is never worth failing a follow */ }
105
+ }
106
+
107
+
108
+
109
+
110
+
111
+
112
+
113
+
114
+
115
+
116
+
117
+
118
+
119
+
120
+
121
+ /** The copies of one original, from the journal. */
122
+
123
+
124
+
125
+
126
+
127
+
128
+
129
+
130
+
131
+
132
+
133
+ const isStr = (u ) => typeof u === "string" && u !== "";
134
+ const msg = (e ) => (e instanceof Error ? e.message : String(e));
135
+ const validCopied = (r ) => {
136
+ const o = r ;
137
+ return !!o && isStr(o.path) && isStr(o.nativeId) && typeof o.cwd === "string" && typeof o.size === "number" && typeof o.mtimeMs === "number";
138
+ };
139
+
140
+ /** T3 Code could not be reached (closed, connection lost, no answer): the follow waits for the next cycle. */
141
+ function unreachable(e ) {
142
+ return e instanceof T3NotRunning || e instanceof RpcClosed || e instanceof RpcTimeout || (e instanceof T3HttpError && e.status === null);
143
+ }
144
+
145
+ /** The first record of a transcript that carries cwd: its cwd and the bytes read up to and including it; null: none. */
146
+ async function firstCwd(file ) {
147
+ let found = null;
148
+ await scanJsonl(file, {}, (o, info) => {
149
+ if (typeof o.cwd === "string" && o.cwd !== "") { found = { cwd: o.cwd, offset: info.offset }; return "stop"; }
150
+ });
151
+ return found;
152
+ }
153
+
154
+ const DEFERRED = new Set(["import-unverified", "project-in-use", "clock-jump", "file-busy", "active", "aborted"]);
155
+
156
+ export async function followRehomed(ctx ) {
157
+ const now = ctx.now ?? Date.now;
158
+ const platform = ctx.platform ?? process.platform;
159
+ const mode = ctx.mode ?? FOLLOW_MODE;
160
+ const limit = ctx.limit ?? FOLLOWS_PER_CYCLE;
161
+ const key = (p ) => pathKey(p, platform);
162
+ const out = { followed: 0, conflicts: [], deferred: 0, failed: [] };
163
+ const api = ctx.api;
164
+ const j = ctx.journal;
165
+ let started = null;
166
+ const runId = () => (started ??= typeof ctx.runId === "string" ? Promise.resolve(ctx.runId) : ctx.runId());
167
+
168
+ // ---------- the copies of every original, from the journal ----------
169
+ const entries = await j.readAll();
170
+ const rolledBack = new Set(entries.flatMap((e) => (e.t === "rolled-back" ? [e.targetRunId] : [])));
171
+ const mergedFiles = new Set(standingMerges(entries).map((m) => key(m.revisionFile)));
172
+ const anyMergedFiles = new Set(entries.flatMap((e) => (e.t === "merged" && isStr(e.revisionFile) ? [key(e.revisionFile)] : [])));
173
+ const failedRevs = new Set(entries.flatMap((e) => (e.t === "import-failed" ? [e.nativeId] : [])));
174
+ const ours = new Map ();
175
+ const lineages = new Map ();
176
+ for (const w of effectiveWrites(entries, key)) {
177
+ ours.set(key(w.path), w.sha256);
178
+ if (!validCopied(w.rehomeOf)) continue;
179
+ const k = `${key(w.rehomeOf.path)}|${w.rehomeOf.nativeId}`;
180
+ const l = lineages.get(k) ?? lineages.set(k, { root: null, current: null, unfinished: [], rolledBackSizes: new Set() }).get(k) ;
181
+ // A rolled-back write counts for nothing, unless the rollback kept it (in use, T3 Code unreachable, a refreshed
182
+ // copy): still on disk exactly as written, it is still the copy whose thread T3 shows.
183
+ const kept = rolledBack.has(w.runId) && (await sha256File(w.path).catch(() => null)) === w.sha256;
184
+ if (rolledBack.has(w.runId) && !kept) { l.rolledBackSizes.add(w.rehomeOf.size); continue; }
185
+ if (w.revisionOf && !(kept ? anyMergedFiles : mergedFiles).has(key(w.path))) { l.unfinished.push(w); continue; }
186
+ if (!w.revisionOf && l.root === null) l.root = w;
187
+ l.current = w;
188
+ }
189
+
190
+ // T3, read once and only when needed.
191
+ let threads = null;
192
+ let projects = null;
193
+ let providers = null;
194
+ const getThreads = async () => (threads ??= await api.listThreads());
195
+ const getProjects = async () => (projects ??= await api.listProjects());
196
+ const threadOf = (list , nativeId ) => {
197
+ const own = list.filter((t) => IMPORT_THREAD.exec(t.id)?.[2] === nativeId);
198
+ return own.find((t) => !t.archived) ?? own[0];
199
+ };
200
+
201
+ // ---------- candidates (files only: no T3 needed) ----------
202
+
203
+ const candidates = [];
204
+ for (const l of lineages.values()) {
205
+ const c = l.current;
206
+ if (c === null) continue;
207
+ const r = c.rehomeOf ;
208
+ const orig = await statSafe(r.path).catch(() => null);
209
+ if (orig === null || orig.size <= r.size) continue; // deleted, or not grown
210
+ if (l.rolledBackSizes.has(orig.size)) continue; // the user rolled this very state back
211
+ const copySt = await statSafe(c.path).catch(() => null);
212
+ if (copySt === null) continue; // the copy is gone: nothing to follow
213
+ const have = await sha256File(c.path).catch(() => null);
214
+ if (have !== c.sha256) {
215
+ // The copy's thread archived by the user, or gone from T3 Code: they decided (archiving it is what the conflict
216
+ // advice offers), exactly as for a copy that did not change. T3 Code unreadable: still listed.
217
+ let copyTitle = null;
218
+ try {
219
+ const t = threadOf(await getThreads(), path.basename(c.path, ".jsonl"));
220
+ if (t === undefined || t.archived) continue;
221
+ copyTitle = t.title;
222
+ } catch { /* T3 closed: the file's title */ }
223
+ out.conflicts.push({
224
+ original: r.path, copy: c.path,
225
+ originalTitle: (await proposeTitle(r.path, { maxLength: 120 })) ?? "",
226
+ copyTitle: copyTitle ?? (await proposeTitle(c.path, { maxLength: 120 })) ?? "",
227
+ });
228
+ continue;
229
+ }
230
+ if (isActive(orig.mtimeMs, now()) || isActive(copySt.mtimeMs, now())) { out.deferred++; continue; }
231
+ candidates.push({ l, c, r, orig });
232
+ }
233
+ candidates.sort((a, b) => a.orig.mtimeMs - b.orig.mtimeMs || (a.r.path < b.r.path ? -1 : a.r.path > b.r.path ? 1 : 0));
234
+
235
+ /** Journals a change T3 already holds; a failure stops everything (the journal must hear of every T3 change). */
236
+ const record = (e , what ) => appendOrStop(j, e, what);
237
+ /** The copy is still exactly t3sm's write and idle (checked again right before the import). */
238
+ const copyStill = async (c ) => {
239
+ const st = await statSafe(c.path).catch(() => null);
240
+ if (st === null || (await sha256File(c.path).catch(() => null)) !== c.sha256) return "changed";
241
+ return isActive(st.mtimeMs, now()) ? "active" : "ok";
242
+ };
243
+ const swept = new Set ();
244
+
245
+ // ---------- revision mode ----------
246
+ const followRevision = async (k , old ) => {
247
+ const { l, c, r, orig } = k;
248
+ const fail = (reason , copy = c.path) => void out.failed.push({ copy, reason });
249
+ const project = (await getProjects()).find((p) => p.id === old.projectId);
250
+ if (!project) { fail("project-missing"); return; }
251
+ const instanceId = IMPORT_THREAD.exec(old.id) [1] ;
252
+ const oldNativeId = path.basename(c.path, ".jsonl");
253
+ let rev = revisionUuid(path.basename((l.root ?? c).path, ".jsonl"), orig.size);
254
+ const dir = path.dirname(c.path);
255
+ let revFile = path.join(dir, `${rev}.jsonl`);
256
+ let newThreadId = `import:${instanceId}:${rev}`;
257
+ /** The state of the original the revision holds (the one this follow swaps in). */
258
+ let target = { size: orig.size, mtimeMs: orig.mtimeMs };
259
+ const first = await firstCwd(c.path).catch(() => null);
260
+ if (first === null) { fail("copy-unreadable"); return; }
261
+
262
+ // Earlier revisions of this original never swapped in (newest write of each path). T3 holds no thread for one: it is
263
+ // removed while still exactly what t3sm wrote and idle. Its thread archived (the swap was cancelled and the thread
264
+ // archived back): left as it is, an archived thread keeps its transcript, and the follow goes on to the new size.
265
+ // Its thread active (the archive failed, or the import was not verified then): that swap is finished first, here,
266
+ // and the next cycle follows the revision in turn; an older one, or two of them, block the follow (a person decides).
267
+ const inT3 = new Map ();
268
+ for (const t of await getThreads()) {
269
+ for (const id of [IMPORT_THREAD.exec(t.id)?.[2], t.nativeSessionId]) {
270
+ if (!id) continue;
271
+ const had = inT3.get(id);
272
+ if (had === undefined || (had.archived && !t.archived)) inT3.set(id, t);
273
+ }
274
+ }
275
+ const unfinished = new Map ();
276
+ for (const u of l.unfinished) unfinished.set(key(u.path), u);
277
+ let pending = null;
278
+ for (const u of unfinished.values()) {
279
+ if (key(u.path) === key(revFile)) continue;
280
+ const ust = await statSafe(u.path).catch(() => null);
281
+ if (ust === null) continue;
282
+ const t = inT3.get(path.basename(u.path, ".jsonl"));
283
+ if (t === undefined) {
284
+ if (!isActive(ust.mtimeMs, now())) await removeIfOurs(u.path, u.sha256);
285
+ continue;
286
+ }
287
+ if (t.archived) continue;
288
+ const newer = validCopied(u.rehomeOf) && u.rehomeOf.size > r.size && IMPORT_THREAD.test(t.id);
289
+ if (!newer || pending !== null) { fail("revision-pending", (pending?.u ?? u).path); return; }
290
+ pending = { u, thread: t };
291
+ }
292
+ if (pending !== null) {
293
+ revFile = pending.u.path;
294
+ rev = path.basename(revFile, ".jsonl");
295
+ newThreadId = pending.thread.id;
296
+ target = { size: pending.u.rehomeOf .size, mtimeMs: pending.u.rehomeOf .mtimeMs };
297
+ }
298
+ if (failedRevs.has(rev)) { fail("import-failed"); return; } // never retried every cycle; the next growth is
299
+
300
+ let sha ;
301
+ let cwdOffsetBytes ;
302
+ let activity ;
303
+ /** Reused: the revision an earlier cycle wrote, journaled again in this run right before its import. */
304
+ let reused = null;
305
+ const existing = await statSafe(revFile).catch(() => null);
306
+ if (existing !== null) {
307
+ // Written by an earlier cycle that stopped before the swap: reused while it is still exactly t3sm's write.
308
+ const mine = ours.get(key(revFile));
309
+ if (mine === undefined) { fail("target-exists", revFile); return; }
310
+ if ((await sha256File(revFile).catch(() => null)) !== mine) { fail("revision-in-use", revFile); return; }
311
+ sha = mine;
312
+ const w = unfinished.get(key(revFile));
313
+ activity = w?.source ? { updatedAt: w.source.updatedAt, messageCount: w.source.messageCount } : { updatedAt: new Date(existing.mtimeMs).toISOString(), messageCount: 0 };
314
+ const fc = await firstCwd(revFile).catch(() => null);
315
+ if (fc === null) { fail("copy-unreadable", revFile); return; }
316
+ cwdOffsetBytes = fc.offset;
317
+ reused = {
318
+ t: "file-written", runId: "", path: revFile, sha256: sha, mtimeMs: existing.mtimeMs,
319
+ revisionOf: w?.revisionOf ?? { harness: "claude", nativeId: oldNativeId },
320
+ source: w?.source ?? { harness: "claude", nativeId: r.nativeId, updatedAt: activity.updatedAt, messageCount: activity.messageCount },
321
+ rehomeOf: w?.rehomeOf ?? { path: r.path, nativeId: r.nativeId, cwd: r.cwd, size: target.size, mtimeMs: target.mtimeMs },
322
+ };
323
+ } else {
324
+ const copy = await readFaithfulCopy({ path: r.path, nativeId: r.nativeId }, { cwd: first.cwd, sessionId: rev, fromCwd: r.cwd }, now());
325
+ // In use, or grown again since the stat (the revision id is the size): next cycle, never two revisions.
326
+ if ("defer" in copy || copy.rehomeOf.size !== orig.size) { out.deferred++; return; }
327
+ if (!swept.has(key(dir))) { swept.add(key(dir)); await sweepWriteTemps(dir); }
328
+ const tmp = writeTempPath(dir, rev); // not *.jsonl: no scanner takes it
329
+ sha = createHash("sha256").update(copy.text, "utf8").digest("hex");
330
+ try {
331
+ await writeFile(tmp, copy.text, { encoding: "utf8", flag: "wx", mode: 0o600 });
332
+ } catch (e) {
333
+ await rm(tmp, { force: true }).catch(() => {});
334
+ fail(`write-failed: ${failureText(msg(e))}`);
335
+ return;
336
+ }
337
+ const pub = await publishRevision({
338
+ tmp, target: revFile, sha256: sha, mtimeMs: writtenMtime(Date.parse(copy.activity.updatedAt), now()), journal: j, runId: await runId(),
339
+ entry: {
340
+ revisionOf: { harness: "claude", nativeId: oldNativeId },
341
+ source: { harness: "claude", nativeId: r.nativeId, updatedAt: copy.activity.updatedAt, messageCount: copy.activity.messageCount },
342
+ rehomeOf: copy.rehomeOf,
343
+ },
344
+ linkFs: ctx.linkFs,
345
+ });
346
+ if (pub !== "published") { fail(pub, revFile); return; }
347
+ ours.set(key(revFile), sha);
348
+ activity = copy.activity;
349
+ cwdOffsetBytes = copy.cwdOffsetBytes;
350
+ }
351
+
352
+ // The copy, again, right before anything reaches T3: continued meanwhile -> conflict; in use -> next cycle.
353
+ const still = await copyStill(c);
354
+ if (still !== "ok") {
355
+ if (!inT3.has(rev)) await removeIfOurs(revFile, sha); // a revision T3 holds a thread of keeps its transcript
356
+ if (still === "active") out.deferred++;
357
+ else out.conflicts.push({ original: r.path, copy: c.path, originalTitle: (await proposeTitle(r.path, { maxLength: 120 })) ?? "", copyTitle: old.title });
358
+ return;
359
+ }
360
+
361
+ const rid = await runId();
362
+ if (reused !== null) {
363
+ // Journaled again in this run, before the import, as publishRevision does: the run that swaps the revision in owns
364
+ // it, so a rollback of the earlier run keeps it ("rewritten") and a rollback of this one undoes the swap. Ours and
365
+ // aged past now - 20 days while it waited: re-clamped (utimes only), never into Claude Code's cleanup zone.
366
+ let mtimeMs = reused.mtimeMs ?? now();
367
+ if (mtimeMs < now() - WRITTEN_MAX_AGE_MS) {
368
+ mtimeMs = writtenMtime(Date.parse(activity.updatedAt), now());
369
+ await utimes(revFile, mtimeMs / 1000, mtimeMs / 1000);
370
+ }
371
+ await j.append({ ...reused, runId: rid, mtimeMs });
372
+ }
373
+ const st = await statSafe(revFile);
374
+ if (st === null) { fail("copy-failed", revFile); return; }
375
+ const session = {
376
+ harness: "claude", accountId: null, nativeId: rev, cwd: first.cwd, startedAt: null, updatedAt: activity.updatedAt,
377
+ messageCount: activity.messageCount, corruptLines: 0, file: st, flags: [], cwdOffsetBytes,
378
+ };
379
+ const item = { session, action: { kind: "import", projectRoot: project.workspaceRoot, instanceId, expectedThreadId: newThreadId }, notes: [] };
380
+ providers ??= await api.providerInstances();
381
+ const outcome = await importRevision(item, {
382
+ api, journal: j, runId: rid, now, platform, projectId: project.id, projectRoot: project.workspaceRoot, providers,
383
+ exposureItems: ctx.exposureItems ?? [], accountHomes: ctx.accountHomes, batch: ctx.batch, aborted: ctx.aborted, onPendingFiles: ctx.onPendingFiles,
384
+ });
385
+ threads = null; // the list moved on
386
+ if (outcome !== "imported") {
387
+ // Unverified: T3 may have it, kept for the next cycle; so is a revision T3 already holds a thread of.
388
+ if (outcome !== "import-unverified" && !inT3.has(rev)) await removeIfOurs(revFile, sha);
389
+ if (DEFERRED.has(outcome)) out.deferred++;
390
+ else fail(outcome, revFile);
391
+ return;
392
+ }
393
+
394
+ // Carry the old thread's title and settled state to the new one, then archive the old one (merge's archive step).
395
+ // The copy is checked once more first: typed into in T3 Code during the waves, archiving its thread would fork the
396
+ // conversation, so the old thread stays and the new one is archived back.
397
+ let meanwhile = null;
398
+ const beforeArchive = async (fresh ) => {
399
+ const now2 = await copyStill(c);
400
+ if (now2 !== "ok") { meanwhile = now2; return false; }
401
+ await carry(fresh);
402
+ return true;
403
+ };
404
+ const carry = async (fresh ) => {
405
+ const changes = [];
406
+ if (old.title.trim() !== "" && fresh.title !== old.title) {
407
+ changes.push({ kind: "title", previous: fresh.title, next: old.title, write: () => api.setThreadTitle(fresh.id, old.title) });
408
+ }
409
+ const want = old.settledOverride ?? null;
410
+ const have = fresh.settledOverride ?? null;
411
+ if ((want === "settled" || want === "active") && have !== "unknown" && have !== want) {
412
+ // Journaled as the change it is (settle: -> "settled", unsettle: -> "active"), so undo and the planner read it.
413
+ changes.push(want === "settled"
414
+ ? { kind: "settle", previous: have, next: want, write: () => api.settleThread(fresh.id) }
415
+ : { kind: "unsettle", previous: have, next: want, write: () => api.unsettleThread(fresh.id) });
416
+ }
417
+ for (const ch of changes) {
418
+ try {
419
+ await ch.write();
420
+ } catch (e) {
421
+ const error = failureText(msg(e));
422
+ await record({ t: "organize-failed", runId: rid, kind: ch.kind, target: fresh.id, projectId: project.id, error }, `nothing (${ch.kind} failed)`);
423
+ fail(`carry-failed: ${ch.kind}`, revFile);
424
+ continue;
425
+ }
426
+ await record({ t: "organize-change", runId: rid, kind: ch.kind, target: fresh.id, previous: ch.previous, next: ch.next }, `${ch.kind} ${fresh.id}`);
427
+ }
428
+ };
429
+ const swapped = await swapThreads({ api, journal: j, runId: rid, oldThreadId: old.id, newThreadId, beforeArchive });
430
+ if (swapped === "cancelled") {
431
+ // The old thread is left alone; the revision's thread goes back to the archive (its file is kept: an archived
432
+ // thread keeps its transcript). Changed: a conflict. Only in use: the next cycle unarchives and retries.
433
+ try {
434
+ await api.archiveThread(newThreadId);
435
+ } catch {
436
+ fail("archive-failed: the copy changed during the import and the new thread could not be archived; two threads are active", revFile);
437
+ return;
438
+ }
439
+ await record({ t: "thread-archived", runId: rid, threadId: newThreadId }, `the archive of ${newThreadId}`);
440
+ if (meanwhile === "active") out.deferred++;
441
+ else out.conflicts.push({ original: r.path, copy: c.path, originalTitle: (await proposeTitle(r.path, { maxLength: 120 })) ?? "", copyTitle: old.title });
442
+ return;
443
+ }
444
+ if (swapped === "import-unverified") { out.deferred++; return; } // the new thread is not listed (yet): kept for reuse
445
+ if (swapped === "archive-failed") { fail("archive-failed", revFile); return; } // next cycle reuses the revision and retries
446
+ await record({
447
+ t: "merged", runId: rid, harness: "claude", nativeId: oldNativeId, revisionUuid: rev, revisionFile: revFile,
448
+ oldThreadId: old.id, newThreadId, sourceSize: target.size, sourceMtimeMs: target.mtimeMs,
449
+ }, `the archive of ${old.id}`);
450
+ await record({ t: "followed", runId: rid, original: r.path, copy: revFile, oldThread: old.id, newThread: newThreadId, mode: "revision" }, `the archive of ${old.id}`);
451
+ out.followed++;
452
+ };
453
+
454
+ // ---------- refresh mode ----------
455
+ const followRefresh = async (k , old ) => {
456
+ const { c, r, orig } = k;
457
+ const fail = (reason ) => void out.failed.push({ copy: c.path, reason });
458
+ const project = (await getProjects()).find((p) => p.id === old.projectId);
459
+ if (!project) { fail("project-missing"); return; }
460
+ const first = await firstCwd(c.path).catch(() => null);
461
+ if (first === null) { fail("copy-unreadable"); return; }
462
+ const instanceId = IMPORT_THREAD.exec(old.id) [1] ;
463
+ const accounts = Object.entries(ctx.accountHomes ?? {}).map(([id, home]) => ({ id, home, displayName: id, accentColor: null }));
464
+ const session = {
465
+ harness: "claude", accountId: null, nativeId: r.nativeId, cwd: r.cwd, startedAt: null, updatedAt: new Date(orig.mtimeMs).toISOString(),
466
+ messageCount: 0, corruptLines: 0, file: orig, flags: [], cwdOffsetBytes: 0,
467
+ };
468
+ const item = {
469
+ session,
470
+ action: { kind: "convert-import", projectRoot: first.cwd, instanceId, expectedThreadId: old.id, uuid: path.basename(c.path, ".jsonl"), targetFile: c.path, copy: "faithful", rehomeFrom: r.cwd },
471
+ notes: [],
472
+ };
473
+ // Nothing to write (in use, or the copy already holds this text): the run is not started for nothing.
474
+ const pre = await readFaithfulCopy({ path: r.path, nativeId: r.nativeId }, { cwd: first.cwd, sessionId: path.basename(c.path, ".jsonl"), fromCwd: r.cwd }, now());
475
+ if ("defer" in pre) { out.deferred++; return; }
476
+ if (createHash("sha256").update(pre.text, "utf8").digest("hex") === c.sha256) return;
477
+ const rid = await runId();
478
+ // materialize's refresh path: rewritten in place only while the copy is still t3sm's untouched write and idle.
479
+ const m = await materializeConversions([item], new Map(), accounts, j, rid, { platform, now });
480
+ if (m.deferred.length > 0) { out.deferred++; return; }
481
+ if (m.failed.length > 0) { fail(m.failed[0] .reason); return; }
482
+ if (m.resumed.length > 0) {
483
+ out.conflicts.push({ original: r.path, copy: c.path, originalTitle: (await proposeTitle(r.path, { maxLength: 120 })) ?? "", copyTitle: old.title });
484
+ return;
485
+ }
486
+ const ready = m.ready[0];
487
+ if (m.written.length === 0 || ready === undefined) return; // identical already: nothing to bring
488
+ // Imported again into the same thread. runWaves would take a thread that already exists as imported without
489
+ // calling T3, so it is shown T3 without that thread until the import call has been made.
490
+ let called = false;
491
+ const wavesApi = {
492
+ ...api,
493
+ listThreads: async () => (await api.listThreads()).filter((t) => called || t.id !== old.id),
494
+ importSessions: async (projectId , root ) => { called = true; return api.importSessions(projectId, root); },
495
+ };
496
+ providers ??= await api.providerInstances();
497
+ let outcome ;
498
+ try {
499
+ outcome = await importRevision(ready, {
500
+ api, wavesApi, journal: j, runId: rid, now, platform, projectId: project.id, projectRoot: project.workspaceRoot, providers,
501
+ exposureItems: ctx.exposureItems ?? [], accountHomes: ctx.accountHomes, batch: ctx.batch, aborted: ctx.aborted, onPendingFiles: ctx.onPendingFiles,
502
+ });
503
+ } catch (e) {
504
+ if (e instanceof JournalWriteError) throw e;
505
+ // The copy is already rewritten: not a candidate any more, so this is a failure, not a retry.
506
+ fail(`import-failed: ${failureText(msg(e))}`);
507
+ return;
508
+ }
509
+ threads = null;
510
+ if (outcome !== "imported") { fail(outcome); return; }
511
+ await record({ t: "followed", runId: rid, original: r.path, copy: c.path, oldThread: old.id, newThread: null, mode: "refresh" }, `the import of ${old.id}`);
512
+ out.followed++;
513
+ };
514
+
515
+ // ---------- follow, one at a time ----------
516
+ // The limit counts real attempts only: a refused or skipped candidate never takes a slot (a compacted original stays
517
+ // a candidate forever and must not starve the others). A refusal that lasts until the original changes is reported
518
+ // once per state of the original (cache), and that state is not read again.
519
+ const cache = await readFollowCache(ctx.stateDir);
520
+ const refused = {};
521
+ let attempts = 0;
522
+ for (const k of candidates) {
523
+ if (ctx.aborted?.()) { out.deferred++; continue; }
524
+ const state = `${key(k.r.path)}|${k.orig.size}|${k.orig.mtimeMs}`;
525
+ const known = cache.refused[state];
526
+ if (known !== undefined) { refused[state] = known; continue; }
527
+ try {
528
+ const old = threadOf(await getThreads(), path.basename(k.c.path, ".jsonl"));
529
+ if (!old || old.archived) continue; // never imported, or archived by the user: left alone
530
+ let branch;
531
+ try { branch = await readBranch(k.r.path); } catch { out.deferred++; continue; } // gone or busy while read
532
+ if (branch.problem === "compacted" || branch.chain.some((n) => n.compact)) {
533
+ refused[state] = "compacted";
534
+ out.failed.push({ copy: k.c.path, reason: "compacted" });
535
+ continue;
536
+ }
537
+ if (branch.problem === "unsettled") { out.deferred++; continue; } // a torn last line: being written
538
+ // A revision of this very state whose import failed: never retried (the next growth is), and it never takes a
539
+ // slot; reported once per state of the original, like a compacted one.
540
+ if (mode === "revision" && failedRevs.has(revisionUuid(path.basename((k.l.root ?? k.c).path, ".jsonl"), k.orig.size))) {
541
+ refused[state] = "import-failed";
542
+ out.failed.push({ copy: k.c.path, reason: "import-failed" });
543
+ continue;
544
+ }
545
+ if (attempts >= limit) { out.deferred++; continue; }
546
+ attempts++;
547
+ await (mode === "refresh" ? followRefresh(k, old) : followRevision(k, old));
548
+ } catch (e) {
549
+ if (e instanceof JournalWriteError) throw e;
550
+ threads = null;
551
+ if (unreachable(e)) out.deferred++;
552
+ else out.failed.push({ copy: k.c.path, reason: `failed: ${failureText(msg(e))}` });
553
+ }
554
+ }
555
+ // Only the states still current are kept (an original that changed is judged again).
556
+ if (JSON.stringify(refused) !== JSON.stringify(cache.refused)) await writeFollowCache(ctx.stateDir, { version: 1, refused });
557
+ return out;
558
+ }