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.
- package/.claude-plugin/marketplace.json +21 -0
- package/.claude-plugin/plugin.json +19 -0
- package/CHANGELOG.md +138 -0
- package/LICENSE +21 -0
- package/README.md +660 -2
- package/README.pt.md +616 -0
- package/bin/entry.d.mts +2 -0
- package/bin/entry.mjs +19 -0
- package/bin/t3sm.mjs +44 -0
- package/commands/import.md +30 -0
- package/commands/organize.md +36 -0
- package/commands/status.md +24 -0
- package/commands/sync.md +26 -0
- package/dist/apply/apply.js +993 -0
- package/dist/apply/claudeWriter.js +168 -0
- package/dist/apply/copyTranscript.js +116 -0
- package/dist/apply/importer.js +697 -0
- package/dist/apply/materialize.js +335 -0
- package/dist/apply/waves.js +108 -0
- package/dist/assistant/core.js +295 -0
- package/dist/assistant/deps.js +256 -0
- package/dist/assistant/i18n.js +38 -0
- package/dist/assistant/messages.en.js +494 -0
- package/dist/assistant/messages.pt.js +495 -0
- package/dist/assistant/runner.js +64 -0
- package/dist/assistant/steps.js +1362 -0
- package/dist/build.json +1 -0
- package/dist/cli/applyScreen.js +158 -0
- package/dist/cli/commands/accounts.js +254 -0
- package/dist/cli/commands/apply.js +199 -0
- package/dist/cli/commands/changelog.js +61 -0
- package/dist/cli/commands/doctor.js +105 -0
- package/dist/cli/commands/help.js +158 -0
- package/dist/cli/commands/merge.js +224 -0
- package/dist/cli/commands/organize.js +872 -0
- package/dist/cli/commands/plan.js +161 -0
- package/dist/cli/commands/projects.js +430 -0
- package/dist/cli/commands/quarantine.js +203 -0
- package/dist/cli/commands/recover.js +230 -0
- package/dist/cli/commands/rollback.js +281 -0
- package/dist/cli/commands/scan.js +117 -0
- package/dist/cli/commands/schedule.js +288 -0
- package/dist/cli/commands/start.js +45 -0
- package/dist/cli/commands/status.js +615 -0
- package/dist/cli/commands/sync.js +336 -0
- package/dist/cli/commands/update.js +398 -0
- package/dist/cli/errors.js +53 -0
- package/dist/cli/failures.js +91 -0
- package/dist/cli/flags.js +53 -0
- package/dist/cli/help.en.js +549 -0
- package/dist/cli/help.pt.js +566 -0
- package/dist/cli/helpText.js +211 -0
- package/dist/cli/helpTopics.js +58 -0
- package/dist/cli/locked.js +12 -0
- package/dist/cli/main.js +155 -0
- package/dist/cli/screen.js +3 -0
- package/dist/cli/ui.js +111 -0
- package/dist/cli/words.js +2 -0
- package/dist/core/activity.js +16 -0
- package/dist/core/changelog.js +47 -0
- package/dist/core/config.js +530 -0
- package/dist/core/fsutil.js +171 -0
- package/dist/core/glob.js +34 -0
- package/dist/core/history.js +32 -0
- package/dist/core/journal.js +274 -0
- package/dist/core/lock.js +337 -0
- package/dist/core/mask.js +31 -0
- package/dist/core/paths.js +68 -0
- package/dist/core/pid.js +101 -0
- package/dist/core/run.js +4 -0
- package/dist/core/semver.js +18 -0
- package/dist/core/sysroot.js +29 -0
- package/dist/core/types.js +229 -0
- package/dist/core/uuid.js +29 -0
- package/dist/core/version.js +72 -0
- package/dist/help/convert.md +20 -0
- package/dist/help/convert.pt.md +21 -0
- package/dist/help/cwd-unreadable.md +22 -0
- package/dist/help/cwd-unreadable.pt.md +22 -0
- package/dist/help/decisions.md +20 -0
- package/dist/help/decisions.pt.md +20 -0
- package/dist/help/errors.md +20 -0
- package/dist/help/errors.pt.md +22 -0
- package/dist/help/held.md +20 -0
- package/dist/help/held.pt.md +20 -0
- package/dist/help/history.md +27 -0
- package/dist/help/history.pt.md +29 -0
- package/dist/help/instance-unavailable.md +18 -0
- package/dist/help/instance-unavailable.pt.md +19 -0
- package/dist/help/not-imported.md +19 -0
- package/dist/help/not-imported.pt.md +19 -0
- package/dist/help/orphaned.md +19 -0
- package/dist/help/orphaned.pt.md +19 -0
- package/dist/help/project-mismatch.md +15 -0
- package/dist/help/project-mismatch.pt.md +15 -0
- package/dist/help/t3-native.md +22 -0
- package/dist/help/t3-native.pt.md +22 -0
- package/dist/help/updates.md +26 -0
- package/dist/help/updates.pt.md +28 -0
- package/dist/help/watcher.md +24 -0
- package/dist/help/watcher.pt.md +25 -0
- package/dist/i18n/cli.js +41 -0
- package/dist/i18n/lang.js +55 -0
- package/dist/i18n/messages.en.js +1140 -0
- package/dist/i18n/messages.pt.js +1149 -0
- package/dist/i18n/words.js +12 -0
- package/dist/ops/accounts.js +170 -0
- package/dist/ops/autoUpdate.js +223 -0
- package/dist/ops/discoverAccounts.js +343 -0
- package/dist/ops/doctor.js +811 -0
- package/dist/ops/elevated.js +47 -0
- package/dist/ops/errorCodes.js +39 -0
- package/dist/ops/follow.js +558 -0
- package/dist/ops/merge.js +830 -0
- package/dist/ops/notify.js +249 -0
- package/dist/ops/plugin.js +92 -0
- package/dist/ops/projects.js +113 -0
- package/dist/ops/quarantine.js +415 -0
- package/dist/ops/rollback.js +868 -0
- package/dist/ops/schedule.js +464 -0
- package/dist/ops/successor.js +51 -0
- package/dist/ops/sync.js +859 -0
- package/dist/ops/syncStatus.js +290 -0
- package/dist/ops/update.js +273 -0
- package/dist/ops/updater.js +641 -0
- package/dist/ops/watch.js +676 -0
- package/dist/ops/watcherControl.js +212 -0
- package/dist/ops/watcherHealth.js +75 -0
- package/dist/organize/apply.js +495 -0
- package/dist/organize/history.js +192 -0
- package/dist/organize/plan.js +283 -0
- package/dist/organize/rename.js +58 -0
- package/dist/organize/sessions.js +100 -0
- package/dist/organize/titles.js +70 -0
- package/dist/organize/types.js +73 -0
- package/dist/plan/categories.js +104 -0
- package/dist/plan/dedupe.js +137 -0
- package/dist/plan/folders.js +82 -0
- package/dist/plan/names.js +93 -0
- package/dist/plan/ownership.js +316 -0
- package/dist/plan/planner.js +669 -0
- package/dist/plan/rehome.js +101 -0
- package/dist/plan/report.js +407 -0
- package/dist/sources/cache.js +89 -0
- package/dist/sources/claude.js +297 -0
- package/dist/sources/codex.js +496 -0
- package/dist/sources/flatten.js +23 -0
- package/dist/sources/jsonl.js +169 -0
- package/dist/sources/native.js +233 -0
- package/dist/sources/opencode.js +483 -0
- package/dist/sources/pi.js +133 -0
- package/dist/sources/registry.js +67 -0
- package/dist/sources/types.js +80 -0
- package/dist/t3/api.js +492 -0
- package/dist/t3/auth.js +248 -0
- package/dist/t3/compat.js +62 -0
- package/dist/t3/decode.js +408 -0
- package/dist/t3/errors.js +185 -0
- package/dist/t3/rpc.js +185 -0
- package/dist/t3/runtime.js +80 -0
- package/dist/ui/caps.js +56 -0
- package/dist/ui/components.js +202 -0
- package/dist/ui/layout.js +205 -0
- package/dist/ui/list.js +423 -0
- package/dist/ui/locale.js +73 -0
- package/dist/ui/organizePreview.js +72 -0
- package/dist/ui/progress.js +237 -0
- package/dist/ui/style.js +32 -0
- package/dist/ui/terminal.js +126 -0
- package/dist/ui/text.js +186 -0
- package/package.json +58 -4
- package/skills/t3code-sessions/SKILL.md +183 -0
|
@@ -0,0 +1,669 @@
|
|
|
1
|
+
// buildPlan: for every discovered session, which T3 project and which subscription (instance) it goes to, or why it is
|
|
2
|
+
// skipped. Pure apart from the injected readers (existsDir, readVscodePin, compareCopies, labelRecords); never calls T3.
|
|
3
|
+
|
|
4
|
+
import { homedir, tmpdir } from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
import { encodeClaudeProjectDir, expandHome, normalizeCwd, pathKey as pathKeyOf, sameCwd } from "../core/paths.js";
|
|
11
|
+
import { inImportWindow } from "../core/activity.js";
|
|
12
|
+
import { globToRegExp } from "../core/glob.js";
|
|
13
|
+
import { resolveRemap } from "../core/config.js";
|
|
14
|
+
import { projectTitle } from "./names.js";
|
|
15
|
+
import { classifyFolder, isT3Refused, } from "./folders.js";
|
|
16
|
+
import { categoryRules, PENDING_KEYS, resolveGeneralFolder, routeOf, } from "./categories.js";
|
|
17
|
+
import { inferProjectRoot as realInferRoot, } from "./rehome.js";
|
|
18
|
+
import { effectiveWrites, importedIndex, near } from "../core/journal.js";
|
|
19
|
+
import { revisionUuid, uuidV5 } from "../core/uuid.js";
|
|
20
|
+
|
|
21
|
+
import { compareCopies as realCompare, labelRecords as realLabels, projectAccount, readVscodePin as realReadPin, } from "./ownership.js";
|
|
22
|
+
import { pickWinners, } from "./dedupe.js";
|
|
23
|
+
import { hasConverter as registryHasConverter, isConvertHarness as registryIsConvert, isConvertSession, otherForms } from "../sources/registry.js";
|
|
24
|
+
export { sessionForms } from "../sources/registry.js";
|
|
25
|
+
import { isConvertedTranscript as realIsConverted } from "../apply/claudeWriter.js";
|
|
26
|
+
|
|
27
|
+
/** T3 driver for each natively imported non-Claude harness. */
|
|
28
|
+
const NATIVE_DRIVER = { codex: "codex", pi: "pi" };
|
|
29
|
+
/** T3's native importer only looks at transcripts modified in the last 30 days. */
|
|
30
|
+
/** T3 scans at most this many transcripts per source. */
|
|
31
|
+
const T3_SOURCE_CAP = 5000;
|
|
32
|
+
/** Errors worth retrying when comparing copies (file held open by a running agent, AV scan, fd pressure). */
|
|
33
|
+
const TRANSIENT_CODES = new Set(["EBUSY", "EPERM", "EAGAIN", "EMFILE", "EACCES"]);
|
|
34
|
+
const RETRY_BACKOFF_MS = [100, 300, 1000] ;
|
|
35
|
+
|
|
36
|
+
|
|
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
|
+
function memo (fn , key ) {
|
|
79
|
+
const m = new Map ();
|
|
80
|
+
return (k) => {
|
|
81
|
+
const kk = key(k);
|
|
82
|
+
let p = m.get(kk);
|
|
83
|
+
if (!p) {
|
|
84
|
+
p = fn(k);
|
|
85
|
+
m.set(kk, p);
|
|
86
|
+
}
|
|
87
|
+
return p;
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export async function buildPlan(input ) {
|
|
92
|
+
const { config, t3, now } = input;
|
|
93
|
+
/** A Claude session `t3sm recover` names: brought back as an orphan's faithful copy when T3 Code holds no thread of it. */
|
|
94
|
+
const recovering = (s ) => s.harness === "claude" && input.recover?.has(s.nativeId) === true;
|
|
95
|
+
const platform = input.platform ?? process.platform;
|
|
96
|
+
const home = input.home ?? homedir();
|
|
97
|
+
const rootKey = (p ) => pathKeyOf(p, platform);
|
|
98
|
+
const lang = input.lang ?? "en";
|
|
99
|
+
const pp = platform === "win32" ? path.win32 : path.posix;
|
|
100
|
+
// T3 Code's own folders (default ~/.t3): only compared with session folders, never opened.
|
|
101
|
+
const t3Base = normalizeCwd(expandHome("~/.t3", home), platform);
|
|
102
|
+
const folderEnv = input.folderEnv ?? {
|
|
103
|
+
platform, home, tmpdir: tmpdir(), env: process.env, t3BaseDir: t3Base, t3WorktreesDir: `${t3Base}/worktrees`,
|
|
104
|
+
};
|
|
105
|
+
// One General folder only (R10): the configured one, else an existing T3 project at either default, else lang's.
|
|
106
|
+
const generalFolder = resolveGeneralFolder(config, lang, t3.projects.filter((p) => !p.deleted).map((p) => p.workspaceRoot), { platform, home });
|
|
107
|
+
const rules = categoryRules(config, lang, folderEnv, generalFolder);
|
|
108
|
+
const generalKey = rootKey(rules.generalFolder);
|
|
109
|
+
const readPin = memo(input.readVscodePin ?? realReadPin, rootKey);
|
|
110
|
+
const existsDir = memo(input.existsDir, rootKey);
|
|
111
|
+
const warnings = [];
|
|
112
|
+
const rawCompare = input.compareCopies ?? ((a , b ) => realCompare(a, b, platform));
|
|
113
|
+
const sessionByPath = new Map(input.sessions.map((s) => [s.file.path, s]));
|
|
114
|
+
const errCode = (e ) => (e )?.code ?? (e )?.message ?? String(e);
|
|
115
|
+
const sleep = input.sleep ?? ((ms ) => new Promise ((r) => setTimeout(r, ms)));
|
|
116
|
+
// A copy that cannot be read never aborts the plan and never imports on a guess (importing both after a transient
|
|
117
|
+
// EBUSY could leave a permanent duplicate thread in the wrong account). Transient errors are retried with backoff;
|
|
118
|
+
// if the compare still fails, both copies of that session are skipped as `compare-failed` and retried next run.
|
|
119
|
+
// pickWinners sees `diverged` for a failed pair; its sessions are removed from winners/forks afterwards.
|
|
120
|
+
const failedIds = new Map (); // "harness:nativeId" -> error code
|
|
121
|
+
const compare = async (a , b ) => {
|
|
122
|
+
for (let attempt = 0; ; attempt++) {
|
|
123
|
+
try {
|
|
124
|
+
return await rawCompare(a, b);
|
|
125
|
+
} catch (e) {
|
|
126
|
+
const code = errCode(e);
|
|
127
|
+
if (TRANSIENT_CODES.has(code) && attempt < RETRY_BACKOFF_MS.length) {
|
|
128
|
+
await sleep(RETRY_BACKOFF_MS[attempt] );
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
const s = sessionByPath.get(a) ?? sessionByPath.get(b);
|
|
132
|
+
if (s) {
|
|
133
|
+
const k = `${s.harness}:${s.nativeId}`;
|
|
134
|
+
if (!failedIds.has(k)) failedIds.set(k, code);
|
|
135
|
+
}
|
|
136
|
+
return "diverged";
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
const readLabels = input.labelRecords ?? realLabels;
|
|
141
|
+
const labelsOf = async (file ) => {
|
|
142
|
+
try {
|
|
143
|
+
return await readLabels(file);
|
|
144
|
+
} catch (e) {
|
|
145
|
+
warnings.push(`could not read labels of a ${sessionByPath.get(file)?.harness ?? ""} transcript ${sessionByPath.get(file)?.nativeId ?? ""} (${errCode(e)})`);
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
// ---------- instances ----------
|
|
151
|
+
const accountById = new Map (config.accounts.map((a) => [a.id, a]));
|
|
152
|
+
const accountHome = (a ) => normalizeCwd(expandHome(a.home, home), platform);
|
|
153
|
+
const instancesToCreate = [];
|
|
154
|
+
const instanceOfAccount = new Map ();
|
|
155
|
+
for (const a of config.accounts) {
|
|
156
|
+
const existing = t3.instances.find((i) => sameCwd(i.homePath, accountHome(a), platform));
|
|
157
|
+
if (existing) {
|
|
158
|
+
instanceOfAccount.set(a.id, existing.id);
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
if (t3.instances.some((i) => i.id === a.id)) {
|
|
162
|
+
warnings.push(`account ${a.id}: a T3 instance with this id points at another home; fix config.json or the instance before applying`);
|
|
163
|
+
}
|
|
164
|
+
instancesToCreate.push({ id: a.id, driver: "claudeAgent", displayName: a.displayName, accentColor: a.accentColor, homePath: accountHome(a), environment: [] });
|
|
165
|
+
instanceOfAccount.set(a.id, a.id);
|
|
166
|
+
}
|
|
167
|
+
const driverInstance = (driver ) => {
|
|
168
|
+
const ps = t3.providers.filter((p) => p.driver === driver && p.enabled !== false);
|
|
169
|
+
return (ps.find((p) => p.instanceId === driver) ?? ps[0])?.instanceId ?? null;
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
// ---------- per-source cap warning ----------
|
|
173
|
+
const perSource = new Map ();
|
|
174
|
+
for (const s of input.sessions) {
|
|
175
|
+
if (s.flags.includes("compressed")) continue; // T3 lists only plain rollouts: compressed ones never count
|
|
176
|
+
const k = s.harness === "claude" ? `claude account ${s.accountId ?? "?"}` : s.harness;
|
|
177
|
+
perSource.set(k, (perSource.get(k) ?? 0) + 1);
|
|
178
|
+
}
|
|
179
|
+
for (const [k, n] of [...perSource].sort()) {
|
|
180
|
+
if (n > T3_SOURCE_CAP) warnings.push(`${k}: ${n} transcripts; T3 scans at most ${T3_SOURCE_CAP} per source, the rest are not seen by its importer`);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// ---------- effective cwd (remap) ----------
|
|
184
|
+
const eff = new Map ();
|
|
185
|
+
for (const s of input.sessions) {
|
|
186
|
+
if (s.cwd === null || s.cwd === "") eff.set(s, { cwd: null, remapped: false });
|
|
187
|
+
else eff.set(s, resolveRemap(s.cwd, config, platform));
|
|
188
|
+
}
|
|
189
|
+
const withEff = (s ) => {
|
|
190
|
+
const e = eff.get(s) ;
|
|
191
|
+
return e.cwd === s.cwd ? s : { ...s, cwd: e.cwd };
|
|
192
|
+
};
|
|
193
|
+
const indexByRoot = (xs ) => {
|
|
194
|
+
const m = new Map ();
|
|
195
|
+
for (const s of xs) {
|
|
196
|
+
const c = eff.get(s)?.cwd ?? null;
|
|
197
|
+
if (c === null || s.harness !== "claude") continue;
|
|
198
|
+
const k = rootKey(c);
|
|
199
|
+
const g = m.get(k);
|
|
200
|
+
if (g) g.push(withEff(s));
|
|
201
|
+
else m.set(k, [withEff(s)]);
|
|
202
|
+
}
|
|
203
|
+
return m;
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
// ---------- dedupe ----------
|
|
207
|
+
// Evidence for "newest activity" while choosing between identical copies: sessions that live in one account only.
|
|
208
|
+
const accountsOfId = new Map ();
|
|
209
|
+
for (const s of input.sessions) {
|
|
210
|
+
if (s.accountId === null || s.flags.includes("backup-copy")) continue;
|
|
211
|
+
const k = `${s.harness}:${s.nativeId}`;
|
|
212
|
+
(accountsOfId.get(k) ?? accountsOfId.set(k, new Set()).get(k) ).add(s.accountId);
|
|
213
|
+
}
|
|
214
|
+
const unambiguous = indexByRoot(input.sessions.filter((s) =>
|
|
215
|
+
!s.flags.includes("backup-copy") && (accountsOfId.get(`${s.harness}:${s.nativeId}`)?.size ?? 0) <= 1));
|
|
216
|
+
const preAccount = memo((root ) => projectAccount(root, { sessions: unambiguous.get(rootKey(root)) ?? [], config, readVscodePin: readPin, platform, home }), rootKey);
|
|
217
|
+
// Compressed rollouts are never compared byte for byte: discovery already keeps one session per id (a plain twin
|
|
218
|
+
// wins), and the rest are converted or skipped `compressed`.
|
|
219
|
+
const picked = await pickWinners(input.sessions.filter((s) => !s.flags.includes("compressed")), config, { compareCopies: compare, projectAccount: preAccount, platform });
|
|
220
|
+
const failedKey = (s ) => failedIds.has(`${s.harness}:${s.nativeId}`) ? `${s.harness}:${s.nativeId}` : undefined;
|
|
221
|
+
const winners = picked.winners.filter((s) => failedKey(s) === undefined);
|
|
222
|
+
const losers = picked.losers.filter((l) => failedKey(l.session) === undefined);
|
|
223
|
+
const forks = picked.forks.filter((f) => f.every((s) => failedKey(s) === undefined));
|
|
224
|
+
for (const [k, code] of failedIds) warnings.push(`could not compare copies of ${k.slice(k.indexOf(":") + 1)} (${code}); skipped both, will retry next run`);
|
|
225
|
+
|
|
226
|
+
const winnersByRoot = indexByRoot(winners);
|
|
227
|
+
const finalAccount = memo((root ) => projectAccount(root, { sessions: winnersByRoot.get(rootKey(root)) ?? [], config, readVscodePin: readPin, platform, home }), rootKey);
|
|
228
|
+
|
|
229
|
+
const loserOf = new Map (losers.map((l) => [l.session, l]));
|
|
230
|
+
const notes = new Map ();
|
|
231
|
+
const note = (s , n ) => {
|
|
232
|
+
(notes.get(s) ?? notes.set(s, new Set()).get(s) ).add(n);
|
|
233
|
+
};
|
|
234
|
+
const inWindow = (s ) => inImportWindow(s.file.mtimeMs, now);
|
|
235
|
+
for (const f of forks) {
|
|
236
|
+
for (const s of f) {
|
|
237
|
+
note(s, "diverged-fork");
|
|
238
|
+
if (f.some((o) => o !== s && inWindow(o))) note(s, "duplicate-in-window");
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// ---------- projects (existing) ----------
|
|
243
|
+
const liveProjects = t3.projects.filter((p) => !p.deleted);
|
|
244
|
+
const projectByKey = new Map ();
|
|
245
|
+
for (const p of liveProjects) {
|
|
246
|
+
const k = rootKey(p.workspaceRoot);
|
|
247
|
+
if (!projectByKey.has(k)) projectByKey.set(k, p);
|
|
248
|
+
}
|
|
249
|
+
const threadIds = new Set(t3.threads.map((t) => t.id));
|
|
250
|
+
// Sessions started inside T3 carry T3's own thread id; their native ref (instance + native session) identifies them.
|
|
251
|
+
const nativeRefs = new Set(t3.threads.flatMap((t) => (t.nativeSessionId ? [`${t.instanceId}:${t.nativeSessionId}`] : [])));
|
|
252
|
+
/** native session id -> the instances T3 holds a thread of it under (`import:<instance>:<id>` or its native ref). */
|
|
253
|
+
const instancesOfSession = new Map ();
|
|
254
|
+
/** native session id -> the project T3 holds a thread of it in (the first one listed). */
|
|
255
|
+
const projectOfSession = new Map ();
|
|
256
|
+
/** Every thread by id (listThreads: active and archived, every instance). */
|
|
257
|
+
const threadById = new Map(t3.threads.map((t) => [t.id, t]));
|
|
258
|
+
/** native session id -> the first thread T3 holds of it (`import:<instance>:<id>` or its native ref). */
|
|
259
|
+
const threadOfSession = new Map ();
|
|
260
|
+
for (const t of t3.threads) {
|
|
261
|
+
const m = /^import:([^:]+):(.+)$/.exec(t.id);
|
|
262
|
+
for (const [inst, id] of [...(m ? [[m[1] , m[2] ]] : []), ...(t.nativeSessionId ? [[t.instanceId, t.nativeSessionId]] : [])]) {
|
|
263
|
+
const set = instancesOfSession.get(id ) ?? new Set ();
|
|
264
|
+
set.add(inst );
|
|
265
|
+
instancesOfSession.set(id , set);
|
|
266
|
+
if (!projectOfSession.has(id )) projectOfSession.set(id , t.projectId);
|
|
267
|
+
if (!threadOfSession.has(id )) threadOfSession.set(id , t);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
/**
|
|
271
|
+
* The thread of a session T3 Code started: the one its handoff names (T3-native thread ids are plain uuids, matched
|
|
272
|
+
* exactly), else one T3 holds of the session itself. Active or archived, any instance; undefined when none is left.
|
|
273
|
+
*/
|
|
274
|
+
const t3ThreadOf = (s ) =>
|
|
275
|
+
(s.t3ThreadId !== undefined ? threadById.get(s.t3ThreadId) : undefined) ?? threadOfSession.get(s.nativeId);
|
|
276
|
+
/** The root of the live project T3 holds a thread of session `id` in, or null. */
|
|
277
|
+
const t3RootOf = (id ) => {
|
|
278
|
+
const pid = projectOfSession.get(id);
|
|
279
|
+
const p = pid === undefined ? undefined : liveProjects.find((x) => x.id === pid);
|
|
280
|
+
return p ? canonicalRoot(p.workspaceRoot) : null;
|
|
281
|
+
};
|
|
282
|
+
const imported = importedIndex(input.journal);
|
|
283
|
+
const converted = new Map ();
|
|
284
|
+
// Faithful copies (spec §4.3): the original as copied. A record without a timestamp (a rename) changes neither
|
|
285
|
+
// updatedAt nor messageCount, so its size and time are compared too.
|
|
286
|
+
const copiedFile = new Map ();
|
|
287
|
+
for (const e of effectiveWrites(input.journal)) {
|
|
288
|
+
if (!e.source) continue;
|
|
289
|
+
const k = `${e.source.harness}:${e.source.nativeId}`;
|
|
290
|
+
converted.set(k, e.source);
|
|
291
|
+
const r = e.rehomeOf;
|
|
292
|
+
if (r && typeof r.size === "number" && typeof r.mtimeMs === "number") copiedFile.set(k, { size: r.size, mtimeMs: r.mtimeMs });
|
|
293
|
+
else copiedFile.delete(k);
|
|
294
|
+
}
|
|
295
|
+
// Revisions merged into T3 (t3sm merge): a session merged at its current size is not "continued outside" any more.
|
|
296
|
+
const rolledBack = new Set(input.journal.flatMap((e) => (e.t === "rolled-back" ? [e.targetRunId] : [])));
|
|
297
|
+
const standing = input.journal.filter((e) => e.t === "merged" && !rolledBack.has(e.runId));
|
|
298
|
+
const mergedRevs = new Set(standing.map((e) => e.revisionUuid));
|
|
299
|
+
const excludeRes = config.exclude.map((g) => globToRegExp(g, platform));
|
|
300
|
+
const isConvert = input.isConvertHarness ?? registryIsConvert;
|
|
301
|
+
// Per session: Codex compressed rollouts are converted while plain Codex rollouts stay native.
|
|
302
|
+
const convertSession = (s ) => isConvertSession(s, isConvert);
|
|
303
|
+
// Provenance: conversions of any harness t3sm converts sessions of (OpenCode; Codex compressed rollouts).
|
|
304
|
+
const converts = input.isConvertHarness ?? registryHasConverter;
|
|
305
|
+
// Converted transcripts t3sm wrote (journaled targets of a convert-mode session): the Claude adapter rediscovers them
|
|
306
|
+
// as native sessions; they are imported through their convert-import item, never twice.
|
|
307
|
+
const pathKey = (p ) => pathKeyOf(p, platform);
|
|
308
|
+
// Merge revisions t3sm wrote that no standing merge uses (import failed / unverified / interrupted): never imported
|
|
309
|
+
// on their own; `t3sm merge` reuses or removes them. One T3 already holds a thread for (a merge kept by a partial
|
|
310
|
+
// rollback, an archive that failed) is an ordinary already-in-t3 session and stays mergeable.
|
|
311
|
+
const usedRevisions = new Set(standing.map((e) => pathKey(e.revisionFile)));
|
|
312
|
+
const unmergedRevisions = new Set(effectiveWrites(input.journal, pathKey).flatMap((e) => (e.revisionOf && !usedRevisions.has(pathKey(e.path)) ? [pathKey(e.path)] : [])));
|
|
313
|
+
// A file-written with a Claude source is a rehomed copy (spec §4.3): t3sm's own, like a conversion.
|
|
314
|
+
const convertedPaths = new Set(effectiveWrites(input.journal, pathKey).flatMap((e) => (e.source && (converts(e.source.harness) || e.source.harness === "claude") ? [pathKey(e.path)] : [])));
|
|
315
|
+
// Rehomed copies are named uuidV5("claude:<source id>"), copies of orphaned T3 sessions uuidV5("claude-orphan:<source
|
|
316
|
+
// id>"): one whose source is also discovered is that copy.
|
|
317
|
+
const copyIds = new Set(input.sessions.flatMap((s) => (s.harness === "claude" ? [uuidV5(`claude:${s.nativeId}`), orphanUuid(s.nativeId)] : [])));
|
|
318
|
+
const rehomeCopyPaths = new Set(effectiveWrites(input.journal, pathKey).flatMap((e) => (e.source?.harness === "claude" ? [pathKey(e.path)] : [])));
|
|
319
|
+
/** A faithful copy t3sm wrote of a conversation from a refused folder (`t3sm merge` cannot handle it: R11). */
|
|
320
|
+
const isRehomeCopy = (s ) => s.harness === "claude" && (rehomeCopyPaths.has(pathKey(s.file.path)) || copyIds.has(s.nativeId));
|
|
321
|
+
// Imports journaled by the file T3 read (a converted transcript was imported under its convert-mode session's id).
|
|
322
|
+
const importedByPath = new Map ();
|
|
323
|
+
for (const e of input.journal) if (e.t === "imported" && typeof e.source?.path === "string") importedByPath.set(pathKey(e.source.path), e);
|
|
324
|
+
const looksConverted = input.isConvertedTranscript ?? ((f , id ) => realIsConverted(f, id, converts));
|
|
325
|
+
|
|
326
|
+
// Canonical spelling of each new root: most frequent normalized variant, then lexicographic.
|
|
327
|
+
const variantCount = new Map ();
|
|
328
|
+
for (const s of input.sessions) {
|
|
329
|
+
const c = eff.get(s) .cwd;
|
|
330
|
+
if (c === null) continue;
|
|
331
|
+
const k = rootKey(c);
|
|
332
|
+
const vm = variantCount.get(k) ?? variantCount.set(k, new Map()).get(k) ;
|
|
333
|
+
vm.set(c, (vm.get(c) ?? 0) + 1);
|
|
334
|
+
}
|
|
335
|
+
const canonicalRoot = (c ) => {
|
|
336
|
+
const k = rootKey(c);
|
|
337
|
+
const p = projectByKey.get(k);
|
|
338
|
+
if (p) return normalizeCwd(p.workspaceRoot, platform);
|
|
339
|
+
const vm = variantCount.get(k);
|
|
340
|
+
if (!vm) return normalizeCwd(c, platform);
|
|
341
|
+
return [...vm].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))[0] [0];
|
|
342
|
+
};
|
|
343
|
+
|
|
344
|
+
// ---------- categories (spec §4.1-§4.4) ----------
|
|
345
|
+
// Known roots for rehome inference: live T3 projects and this plan's `project` folders, never the home folder, and
|
|
346
|
+
// only folders that still exist (a missing folder is `missing`, not a project: never a rehome target).
|
|
347
|
+
// Built once, on the first inference (a plan with nothing to rehome checks no extra folders).
|
|
348
|
+
let knownRoots = null;
|
|
349
|
+
const knownRootsOnce = () => (knownRoots ??= (async () => {
|
|
350
|
+
const out = new Map ();
|
|
351
|
+
for (const r of [...liveProjects.map((p) => p.workspaceRoot), ...[...eff.values()].flatMap((e) => (e.cwd === null ? [] : [e.cwd]))]) {
|
|
352
|
+
const k = rootKey(r);
|
|
353
|
+
if (out.has(k) || classifyFolder(r, folderEnv) !== "project") continue;
|
|
354
|
+
if (await existsDir(normalizeCwd(r, platform))) out.set(k, canonicalRoot(r));
|
|
355
|
+
}
|
|
356
|
+
return [...out.values()];
|
|
357
|
+
})());
|
|
358
|
+
const inferRoot = input.inferProjectRoot ?? realInferRoot;
|
|
359
|
+
let lastShare = null;
|
|
360
|
+
async function rehomeTarget(s , route ) {
|
|
361
|
+
lastShare = null;
|
|
362
|
+
if (route.target !== null) return route.target;
|
|
363
|
+
if (s.harness !== "claude") return rules.generalFolder; // inference reads Claude transcripts only
|
|
364
|
+
try {
|
|
365
|
+
const g = await inferRoot(s.file.path, await knownRootsOnce(), { platform, home });
|
|
366
|
+
// Defensive: an inferred folder that does not exist is never a target.
|
|
367
|
+
if (g !== null && await existsDir(normalizeCwd(g.root, platform))) { lastShare = { hits: g.hits, total: g.total }; return g.root; }
|
|
368
|
+
return rules.generalFolder;
|
|
369
|
+
} catch (e) {
|
|
370
|
+
warnings.push(`could not read Claude transcript ${s.nativeId} to find its project (${errCode(e)}); it goes to the General folder`);
|
|
371
|
+
return rules.generalFolder;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
const pending = new Map ();
|
|
375
|
+
|
|
376
|
+
// ---------- items ----------
|
|
377
|
+
const items = [];
|
|
378
|
+
const mirrorCopies = [];
|
|
379
|
+
const rootsUsed = new Map (); // key -> canonical root (import / convert / already-in-t3)
|
|
380
|
+
const importRoots = new Set ();
|
|
381
|
+
const skip = (reason ) => ({ kind: "skip", reason });
|
|
382
|
+
|
|
383
|
+
for (const s of input.sessions) {
|
|
384
|
+
const e = eff.get(s) ;
|
|
385
|
+
if (e.remapped) note(s, "remapped-cwd");
|
|
386
|
+
if (s.flags.includes("over-32mib")) note(s, "truncated-over-32mib");
|
|
387
|
+
const action = await decide(s, e.cwd);
|
|
388
|
+
items.push({ session: s, action, notes: [], sortRoot: e.cwd === null ? "" : canonicalRoot(e.cwd) });
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* Work after T3 got the session in its other form. Converted now, native thread before: the session's activity is
|
|
393
|
+
* newer than the run that imported it natively (journal; a session started inside T3 has no record: no note).
|
|
394
|
+
* Native now, converted thread before: its activity differs from what the conversion recorded.
|
|
395
|
+
*/
|
|
396
|
+
function continuedSinceOtherForm(s , convert ) {
|
|
397
|
+
if (convert) {
|
|
398
|
+
const j = imported.get(`${s.harness}:${s.nativeId}`);
|
|
399
|
+
if (!j || !j.threadId.endsWith(`:${s.nativeId}`)) return false;
|
|
400
|
+
const at = runTime(j.runId);
|
|
401
|
+
return at !== null && Date.parse(s.updatedAt) > at;
|
|
402
|
+
}
|
|
403
|
+
const w = converted.get(`${s.harness}:${s.nativeId}`);
|
|
404
|
+
return w !== undefined && (w.updatedAt !== s.updatedAt || w.messageCount !== s.messageCount);
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
async function checkLabels(loser , winner ) {
|
|
408
|
+
const mine = await labelsOf(loser.file.path);
|
|
409
|
+
if (mine === null || mine.size === 0) return;
|
|
410
|
+
const kept = await labelsOf(winner.file.path);
|
|
411
|
+
if (kept !== null && [...mine].some((x) => !kept.has(x))) note(winner, "label-only-in-mirror");
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
async function decide(s , cwd ) {
|
|
415
|
+
const has = (f ) => s.flags.includes(f);
|
|
416
|
+
const filePath = normalizeCwd(s.file.path, platform);
|
|
417
|
+
const ncwd = cwd === null ? null : normalizeCwd(cwd, platform);
|
|
418
|
+
const ownCopy = s.harness === "claude" && (convertedPaths.has(pathKey(s.file.path)) || copyIds.has(s.nativeId) || await looksConverted(s.file.path, s.nativeId));
|
|
419
|
+
if (ownCopy) {
|
|
420
|
+
// Not in T3 yet: its convert-import item imports it (never two candidates for one path). Already in T3: from now
|
|
421
|
+
// on it is the Claude session it became (resumable in a terminal), so it takes the normal already-in-t3 path
|
|
422
|
+
// below, where continued-outside-t3 lets `t3sm merge` see terminal work on it.
|
|
423
|
+
const inst = s.accountId !== null ? instanceOfAccount.get(s.accountId) : undefined;
|
|
424
|
+
const inT3 = inst !== undefined && (threadIds.has(`import:${inst}:${s.nativeId}`) || nativeRefs.has(`${inst}:${s.nativeId}`));
|
|
425
|
+
if (!inT3) return skip("converted");
|
|
426
|
+
}
|
|
427
|
+
if (excludeRes.some((re) => (ncwd !== null && re.test(ncwd)) || re.test(filePath))) return skip("excluded");
|
|
428
|
+
if (has("backup-copy") && !config.includeBackups) return skip("backup-copy");
|
|
429
|
+
if (has("duplicate-file")) return skip("duplicate"); // discovery planned another file of this session
|
|
430
|
+
if (has("subagent")) return skip("subagent");
|
|
431
|
+
const convert = convertSession(s);
|
|
432
|
+
// A compressed rollout T3 cannot read and t3sm does not convert (codex.convertCompressed false): never opened.
|
|
433
|
+
if (has("compressed") && !convert) return skip("compressed");
|
|
434
|
+
if (has("active")) return skip("active");
|
|
435
|
+
if (s.harness === "claude" && has("non-uuid-id")) return skip("non-uuid-id");
|
|
436
|
+
if (has("no-session-id")) return skip("no-session-id");
|
|
437
|
+
if (has("only-hidden")) return skip("only-hidden");
|
|
438
|
+
if (has("over-4gib")) return skip("over-4gib");
|
|
439
|
+
if (has("too-large")) return skip("too-large");
|
|
440
|
+
if (ncwd === null || has("no-cwd")) return skip("no-cwd");
|
|
441
|
+
if (has("cwd-unreadable")) return skip("cwd-unreadable");
|
|
442
|
+
// A session T3 Code started (before the folder category). Its thread still there (active or archived, any
|
|
443
|
+
// instance): already in T3. No thread id: t3sm cannot tell, and never copies it. Its thread deleted: T3 Code will
|
|
444
|
+
// not import it again, so after a yes (`organize.sessions.orphaned`) it comes back as a faithful copy with a new
|
|
445
|
+
// id, in its own folder (a folder T3 Code refuses: the rehome target). A copy t3sm wrote is never one of these:
|
|
446
|
+
// it keeps the original's records (entrypoint t3-code, the handoff) and is recognised as t3sm's own above. A
|
|
447
|
+
// mirror of a copy kept in another account stays a mirror copy (below), for `t3sm dedupe`.
|
|
448
|
+
const fromT3 = s.harness === "claude" && s.startedIn === "t3" && !ownCopy && !loserOf.has(s);
|
|
449
|
+
if (fromT3) {
|
|
450
|
+
const held = t3ThreadOf(s);
|
|
451
|
+
if (held !== undefined) {
|
|
452
|
+
const p = liveProjects.find((x) => x.id === held.projectId);
|
|
453
|
+
if (p) rootsUsed.set(rootKey(p.workspaceRoot), canonicalRoot(p.workspaceRoot));
|
|
454
|
+
note(s, "started-in-t3");
|
|
455
|
+
return skip("already-in-t3");
|
|
456
|
+
}
|
|
457
|
+
// Brought back already (`t3sm recover`): its copy's thread is in T3 Code (any instance, archived or not).
|
|
458
|
+
if (s.t3ThreadId === undefined && instancesOfSession.has(orphanUuid(s.nativeId))) {
|
|
459
|
+
const r = t3RootOf(orphanUuid(s.nativeId));
|
|
460
|
+
if (r !== null) rootsUsed.set(rootKey(r), r);
|
|
461
|
+
note(s, "recovered");
|
|
462
|
+
return skip("already-in-t3");
|
|
463
|
+
}
|
|
464
|
+
// `t3sm recover <id>` names one: the user says its thread is gone, so it is treated as orphaned (below).
|
|
465
|
+
if (s.t3ThreadId === undefined && !recovering(s)) return skip("t3-native-unknown");
|
|
466
|
+
}
|
|
467
|
+
/** Started in T3 Code and its thread is gone (every other case returned above). */
|
|
468
|
+
const orphan = fromT3;
|
|
469
|
+
// A category skip applies last (below): only to sessions that would otherwise be imported.
|
|
470
|
+
const category = routeOf(s, ncwd, rules, s.harness === "claude" || convert || converts(s.harness));
|
|
471
|
+
// An orphan ignores the folder category, never an `organize.overrides` rule: a `rehome:<folder>` one (a route
|
|
472
|
+
// with a target) sends its copy there; a `skip` one (`excluded`, or a bad rehome target) keeps it out.
|
|
473
|
+
const overrideSkip = category.kind === "skip" && (category.reason === "excluded" || category.badTarget !== undefined);
|
|
474
|
+
const route = !orphan ? category
|
|
475
|
+
: category.kind === "rehome" && category.target !== null ? category
|
|
476
|
+
: !isT3Refused(ncwd, folderEnv) ? { kind: "native" }
|
|
477
|
+
: category.kind === "rehome" ? category : { kind: "rehome", target: null };
|
|
478
|
+
/** Why an orphaned session waits or stays out (applied where a category skip would be). */
|
|
479
|
+
const orphanHold = !orphan ? null
|
|
480
|
+
: overrideSkip ? category
|
|
481
|
+
: recovering(s) ? null // asked for by name (`t3sm recover`): no question, whatever organize.sessions.orphaned says
|
|
482
|
+
: !rules.decided("orphaned") ? { kind: "skip", reason: "undecided", pending: "orphaned" }
|
|
483
|
+
: rules.organize.sessions.orphaned === "skip" ? { kind: "skip", reason: "orphaned-in-t3" } : null;
|
|
484
|
+
// A rehomed session's own folder does not matter (and its target may not exist yet: created on apply). R9: a
|
|
485
|
+
// session from a deleted refused folder is still rehomed.
|
|
486
|
+
if (route.kind !== "rehome" && !(await existsDir(ncwd))) return skip("cwd-missing");
|
|
487
|
+
|
|
488
|
+
const rehome = route.kind === "rehome";
|
|
489
|
+
const asCopy = convert || rehome || orphan;
|
|
490
|
+
/** The id of the copy (convert-mode, rehomed or orphaned session). */
|
|
491
|
+
const copyUuid = orphan ? orphanUuid(s.nativeId) : uuidV5(`${s.harness}:${s.nativeId}`);
|
|
492
|
+
// Where the session goes. A rehomed Claude transcript's project is inferred by reading the whole transcript
|
|
493
|
+
// (rehomeTarget), so it is resolved only for a session that will be imported; one already in T3 (or skipped below)
|
|
494
|
+
// is never read for it.
|
|
495
|
+
let target = null;
|
|
496
|
+
const resolveTarget = async () => {
|
|
497
|
+
if (target === null) {
|
|
498
|
+
if (route.kind !== "rehome") target = { root: canonicalRoot(ncwd), share: null };
|
|
499
|
+
else {
|
|
500
|
+
const r = canonicalRoot(await rehomeTarget(s, route));
|
|
501
|
+
target = { root: r, share: lastShare };
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
return target;
|
|
505
|
+
};
|
|
506
|
+
const lazyTarget = rehome && s.harness === "claude";
|
|
507
|
+
/** The project this item counts for (rootsUsed) when T3 already holds it: for a lazy target, where T3 holds its thread. */
|
|
508
|
+
const useRootInT3 = async (id ) => {
|
|
509
|
+
const r = lazyTarget ? t3RootOf(id) : (await resolveTarget()).root;
|
|
510
|
+
if (r !== null) rootsUsed.set(rootKey(r), r);
|
|
511
|
+
};
|
|
512
|
+
let instanceId ;
|
|
513
|
+
let convertAccount = null;
|
|
514
|
+
if (lazyTarget || orphan) {
|
|
515
|
+
// A faithful copy stays in its own account.
|
|
516
|
+
convertAccount = s.accountId !== null ? accountById.get(s.accountId) ?? null : null;
|
|
517
|
+
instanceId = convertAccount ? instanceOfAccount.get(convertAccount.id) ?? null : null;
|
|
518
|
+
} else if (asCopy) {
|
|
519
|
+
const acct = accountById.get((await finalAccount((await resolveTarget()).root)).accountId);
|
|
520
|
+
convertAccount = acct ?? null;
|
|
521
|
+
instanceId = acct ? instanceOfAccount.get(acct.id) ?? null : null;
|
|
522
|
+
} else if (s.harness === "claude") {
|
|
523
|
+
instanceId = s.accountId !== null && accountById.has(s.accountId) ? instanceOfAccount.get(s.accountId) ?? null : null;
|
|
524
|
+
} else {
|
|
525
|
+
const driver = NATIVE_DRIVER[s.harness];
|
|
526
|
+
instanceId = driver ? driverInstance(driver) : null;
|
|
527
|
+
}
|
|
528
|
+
// One session, two forms (Codex: its native id and its converted uuid). Already in T3 under the other form (any
|
|
529
|
+
// instance) and not under this one: it is in T3; importing this form would make a second thread of one session.
|
|
530
|
+
const own = asCopy ? copyUuid : s.nativeId;
|
|
531
|
+
if (!instancesOfSession.has(own) && otherForms(s, own).some((f) => instancesOfSession.has(f))) {
|
|
532
|
+
await useRootInT3(own);
|
|
533
|
+
note(s, "in-t3-as-other-form");
|
|
534
|
+
if (continuedSinceOtherForm(s, asCopy)) note(s, "continued-outside-t3");
|
|
535
|
+
return skip("already-in-t3");
|
|
536
|
+
}
|
|
537
|
+
if (instanceId === null) return skip("harness-unavailable");
|
|
538
|
+
|
|
539
|
+
if (failedKey(s) !== undefined) return skip("compare-failed");
|
|
540
|
+
const l = loserOf.get(s);
|
|
541
|
+
if (l) {
|
|
542
|
+
if (l.relation === "identical" || l.relation === "prefix") {
|
|
543
|
+
mirrorCopies.push({ path: s.file.path, nativeId: s.nativeId, keptPath: l.winner.file.path, relation: l.relation });
|
|
544
|
+
if (inWindow(s)) note(l.winner, "duplicate-in-window");
|
|
545
|
+
// Metadata-only differences stay mirror copies (dedupe quarantines reversibly); flag a user label that only
|
|
546
|
+
// the mirror holds so the report can say where it is.
|
|
547
|
+
await checkLabels(s, l.winner);
|
|
548
|
+
return skip("mirror-copy");
|
|
549
|
+
}
|
|
550
|
+
if (l.relation === "case-variant") {
|
|
551
|
+
if (inWindow(s)) note(l.winner, "duplicate-in-window");
|
|
552
|
+
await checkLabels(s, l.winner);
|
|
553
|
+
}
|
|
554
|
+
return skip("duplicate");
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
const uuid = asCopy ? copyUuid : null;
|
|
558
|
+
const expectedThreadId = `import:${instanceId}:${uuid ?? s.nativeId}`;
|
|
559
|
+
if (threadIds.has(expectedThreadId) || nativeRefs.has(`${instanceId}:${uuid ?? s.nativeId}`)) {
|
|
560
|
+
await useRootInT3(uuid ?? s.nativeId);
|
|
561
|
+
if (asCopy) {
|
|
562
|
+
// Convert-mode sessions share one source file (the harness db): compare the session's own activity with what
|
|
563
|
+
// the last conversion recorded. A faithful copy's original is a file of its own: its size and time too. The
|
|
564
|
+
// copy in T3 is never rewritten (T3 never adds messages to an existing thread): the note is the signal, and
|
|
565
|
+
// for a rehomed Claude original it is its own note (R11: `t3sm merge` cannot bring that work into T3).
|
|
566
|
+
const w = converted.get(`${s.harness}:${s.nativeId}`);
|
|
567
|
+
const f = copiedFile.get(`${s.harness}:${s.nativeId}`);
|
|
568
|
+
if ((w && (w.updatedAt !== s.updatedAt || w.messageCount !== s.messageCount))
|
|
569
|
+
|| (f && (f.size !== s.file.size || !near(s.file.mtimeMs, f.mtimeMs)))) {
|
|
570
|
+
note(s, (rehome || orphan) && s.harness === "claude" ? "continued-after-rehome" : "continued-outside-t3");
|
|
571
|
+
}
|
|
572
|
+
return skip("already-in-t3");
|
|
573
|
+
}
|
|
574
|
+
const j = imported.get(`${s.harness}:${s.nativeId}`) ?? importedByPath.get(pathKey(s.file.path));
|
|
575
|
+
if (j && (j.source.size !== s.file.size || !near(s.file.mtimeMs, j.source.mtimeMs)) && !mergedRevs.has(revisionUuid(s.nativeId, s.file.size))) {
|
|
576
|
+
// A rehomed copy resumed outside T3 Code: merge cannot handle it either (R11).
|
|
577
|
+
note(s, isRehomeCopy(s) ? "continued-after-rehome" : "continued-outside-t3");
|
|
578
|
+
}
|
|
579
|
+
return skip("already-in-t3");
|
|
580
|
+
}
|
|
581
|
+
// The same session already in T3 under another instance (imported earlier under another account): importing it
|
|
582
|
+
// here would make a second thread of one session. Listed in the report for review instead.
|
|
583
|
+
if ([...(instancesOfSession.get(uuid ?? s.nativeId) ?? [])].some((i) => i !== instanceId)) {
|
|
584
|
+
await useRootInT3(uuid ?? s.nativeId);
|
|
585
|
+
note(s, "in-t3-under-other-account");
|
|
586
|
+
return skip("already-in-t3");
|
|
587
|
+
}
|
|
588
|
+
const hold = orphanHold ?? (route.kind === "skip" ? route : null);
|
|
589
|
+
if (hold !== null) {
|
|
590
|
+
if (hold.badTarget !== undefined) warnings.push(`organize.overrides: rehome:${hold.badTarget} is not a folder T3 Code can hold a project in (refused, temporary or system); its sessions are skipped`);
|
|
591
|
+
if (hold.pending) {
|
|
592
|
+
const p = pending.get(hold.pending) ?? pending.set(hold.pending, { sessions: 0, folders: new Set() }).get(hold.pending) ;
|
|
593
|
+
p.sessions++;
|
|
594
|
+
p.folders.add(rootKey(ncwd));
|
|
595
|
+
}
|
|
596
|
+
return skip(hold.reason);
|
|
597
|
+
}
|
|
598
|
+
const { root, share } = await resolveTarget();
|
|
599
|
+
rootsUsed.set(rootKey(root), root);
|
|
600
|
+
if (s.harness === "claude" && unmergedRevisions.has(pathKey(s.file.path))) return skip("revision");
|
|
601
|
+
importRoots.add(rootKey(root));
|
|
602
|
+
if (asCopy) {
|
|
603
|
+
const targetFile = pp.join(accountHome(convertAccount ), "projects", encodeClaudeProjectDir(root), `${uuid}.jsonl`);
|
|
604
|
+
const action = { kind: "convert-import", projectRoot: root, instanceId, expectedThreadId, uuid: uuid , targetFile };
|
|
605
|
+
if (rehome) Object.assign(action, s.harness === "claude" ? { copy: "faithful", rehomeFrom: ncwd } : { rehomeFrom: ncwd }, share ? { rehomeShare: share } : {});
|
|
606
|
+
else if (orphan) Object.assign(action, { copy: "faithful" });
|
|
607
|
+
return action;
|
|
608
|
+
}
|
|
609
|
+
return { kind: "import", projectRoot: root, instanceId, expectedThreadId };
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
for (const it of items) it.notes = [...(notes.get(it.session) ?? [])].sort();
|
|
613
|
+
items.sort((a, b) =>
|
|
614
|
+
cmp(a.sortRoot, b.sortRoot) || cmp(a.session.updatedAt, b.session.updatedAt) || cmp(a.session.harness, b.session.harness)
|
|
615
|
+
|| cmp(a.session.nativeId, b.session.nativeId) || cmp(a.session.file.path, b.session.file.path));
|
|
616
|
+
|
|
617
|
+
// ---------- projects ----------
|
|
618
|
+
const projectsToCreate = [];
|
|
619
|
+
const projectAccounts = [];
|
|
620
|
+
const projectDefaults = [];
|
|
621
|
+
const nameLimit = rules.organize.names.maxLength;
|
|
622
|
+
const takenTitles = new Set(liveProjects.map((p) => p.title.toLowerCase()));
|
|
623
|
+
for (const [k, root] of [...rootsUsed].sort((a, b) => cmp(a[1], b[1]))) {
|
|
624
|
+
const pa = await finalAccount(root);
|
|
625
|
+
projectAccounts.push({ root, accountId: pa.accountId, source: pa.source });
|
|
626
|
+
const inst = instanceOfAccount.get(pa.accountId) ?? null;
|
|
627
|
+
const existing = projectByKey.get(k);
|
|
628
|
+
if (existing) {
|
|
629
|
+
if (existing.archived && importRoots.has(k)) warnings.push(`project "${existing.title}" is archived in T3; sessions are imported into it anyway (unarchive it to see them)`);
|
|
630
|
+
const cur = existing.defaultModelSelection?.["instanceId"];
|
|
631
|
+
if (inst !== null && cur !== inst) projectDefaults.push({ root, instanceId: inst });
|
|
632
|
+
} else if (importRoots.has(k)) {
|
|
633
|
+
// The General folder (rehomed sessions with no project of their own) has a fixed title.
|
|
634
|
+
const title = k === generalKey ? (lang === "pt" ? "Geral" : "General") : projectTitle(root, takenTitles, { maxLength: nameLimit, platform });
|
|
635
|
+
takenTitles.add(title.toLowerCase());
|
|
636
|
+
projectsToCreate.push({ root, title, defaultInstanceId: inst });
|
|
637
|
+
if (inst !== null) projectDefaults.push({ root, instanceId: inst });
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
return {
|
|
642
|
+
version: 1, runId: input.runId, createdAt: new Date(now).toISOString(), t3Version: t3.version,
|
|
643
|
+
instancesToCreate, projectsToCreate, projectAccounts, projectDefaults,
|
|
644
|
+
mirrorCopies: mirrorCopies.sort((a, b) => cmp(a.path, b.path)),
|
|
645
|
+
items: items.map(({ sortRoot: _r, ...it }) => it),
|
|
646
|
+
warnings: [...new Set(warnings)],
|
|
647
|
+
...(pending.size > 0 ? {
|
|
648
|
+
decisionsPending: PENDING_KEYS.flatMap((key) => {
|
|
649
|
+
const p = pending.get(key);
|
|
650
|
+
return p ? [{ key, sessions: p.sessions, folders: p.folders.size }] : [];
|
|
651
|
+
}),
|
|
652
|
+
} : {}),
|
|
653
|
+
};
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
/** The id of the copy of an orphaned T3 session (its thread deleted): distinct from a rehome copy's `claude:<id>`. */
|
|
657
|
+
export function orphanUuid(nativeId ) {
|
|
658
|
+
return uuidV5(`claude-orphan:${nativeId}`);
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/** A run's start time from its id (`YYYYMMDD-HHMMSS-…`, UTC), or null. */
|
|
662
|
+
function runTime(runId ) {
|
|
663
|
+
const m = /^(\d{4})(\d{2})(\d{2})-(\d{2})(\d{2})(\d{2})-/.exec(runId);
|
|
664
|
+
return m ? Date.UTC(+m[1] , +m[2] - 1, +m[3] , +m[4] , +m[5] , +m[6] ) : null;
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
function cmp(a , b ) {
|
|
668
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
669
|
+
}
|