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,993 @@
|
|
|
1
|
+
// applyPlan: the only command path that changes T3 Code and file times for imports.
|
|
2
|
+
// Order: lock -> recoverPendingMtimes -> load plan + age -> connect -> version + response shapes + instance-home
|
|
3
|
+
// checks (+ mirror warning) -> confirm (all BEFORE the first write) -> instances -> conversions -> projects -> defaults
|
|
4
|
+
// -> waves -> run-end. A dry run (`dryRun`) stops before confirm, reports, and skips the recovery (read-only).
|
|
5
|
+
//
|
|
6
|
+
// Rehome destination folders (interactive runs only, `rehomeFolders`; sync never passes it, safety invariant 13): a
|
|
7
|
+
// copy's destination folder that T3 Code does not have yet and that is missing on disk (the General folder, a
|
|
8
|
+
// `rehome:<folder>` override) is created and journaled (`folder-created`) before the copies are written. One T3 Code
|
|
9
|
+
// refuses, a temp or system folder, or one that cannot be created fails its own items ("cannot create <folder>:
|
|
10
|
+
// <reason>"); the rest of the run goes on.
|
|
11
|
+
//
|
|
12
|
+
// Conversions (convert-import items: OpenCode, Codex compressed rollouts) are written by materializeConversions into their account's projects
|
|
13
|
+
// folder before the projects are created (a root whose only sessions fail to convert gets no empty project), then go
|
|
14
|
+
// through the same waves as native imports with the written transcript as their file.
|
|
15
|
+
|
|
16
|
+
import path from "node:path";
|
|
17
|
+
import { join } from "node:path";
|
|
18
|
+
import { mkdir, readdir, stat } from "node:fs/promises";
|
|
19
|
+
|
|
20
|
+
import { allAdapters, isConvertSession, otherForms, sessionIdsInT3 } from "../sources/registry.js";
|
|
21
|
+
import { CWD_SCAN_MAX_BYTES, } from "../sources/types.js";
|
|
22
|
+
import { ACTIVE_WINDOW_MS, inImportWindow } from "../core/activity.js";
|
|
23
|
+
import { DEFAULT_BATCH } from "../core/config.js";
|
|
24
|
+
import { materializeConversions, } from "./materialize.js";
|
|
25
|
+
import { Journal, near, newRunId, pendingMtimePaths, recoverPendingMtimes, } from "../core/journal.js";
|
|
26
|
+
import { acquireLock } from "../core/lock.js";
|
|
27
|
+
import { statSafe } from "../core/fsutil.js";
|
|
28
|
+
import { encodeClaudeProjectDir, normalizeCwd, pathKey, sameCwd, tildePath } from "../core/paths.js";
|
|
29
|
+
import { classifyFolder, } from "../plan/folders.js";
|
|
30
|
+
import { readClaudeNativeId } from "../sources/claude.js";
|
|
31
|
+
import { shownText } from "../plan/names.js";
|
|
32
|
+
import { cliT, } from "../i18n/cli.js";
|
|
33
|
+
|
|
34
|
+
import { conversationTitle } from "../plan/ownership.js";
|
|
35
|
+
import { connectT3, } from "../t3/api.js";
|
|
36
|
+
import { T3HttpError, T3Incompatible } from "../t3/errors.js";
|
|
37
|
+
import { DEFAULT_ID, applyProjectDefaults, assertDefaultInstanceHome, defaultClaudeHome, driftError, ensureInstances, entryHome } from "../ops/accounts.js";
|
|
38
|
+
import { buildWaves, itemRoot, rootKey, waveItems } from "./waves.js";
|
|
39
|
+
import {
|
|
40
|
+
exposureIndex, restoreSync, runWaves,
|
|
41
|
+
} from "./importer.js";
|
|
42
|
+
|
|
43
|
+
export const PLAN_MAX_AGE_MS = 24 * 3_600_000;
|
|
44
|
+
const STALE = "Plan is stale; run `t3sm plan` again.";
|
|
45
|
+
|
|
46
|
+
/** apply refuses to run (stale plan, instance home moved). Exit 2, nothing written. */
|
|
47
|
+
export class ApplyRefusal extends Error {
|
|
48
|
+
name = "ApplyRefusal";
|
|
49
|
+
exitCode = 2;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The signals that stop a writing run: Ctrl+C, a kill, and the terminal or console window closing. */
|
|
53
|
+
export const STOP_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"] ;
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
const processSignals = {
|
|
61
|
+
on: (sig, fn) => void process.on(sig , fn),
|
|
62
|
+
off: (sig, fn) => void process.off(sig , fn),
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
/** What `apply --dry-run` found: the run as it would go, computed from the same checks, before any write. */
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* One conversation that could not be imported, as a screen names it: its project root (where it was going) and its
|
|
187
|
+
* title (Claude transcripts: `custom-title`, else `ai-title`; null for none or another harness), with the reason code.
|
|
188
|
+
*/
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
/** Each failure's transcript, beside it (never in the result itself): its title is read only for the rows shown. */
|
|
196
|
+
const FILE_OF = new WeakMap ();
|
|
197
|
+
|
|
198
|
+
/** The failure entry for a plan item. Its title is filled by nameFailures, for the failures a screen shows. */
|
|
199
|
+
export function failureOf(i , reason ) {
|
|
200
|
+
const f = { harness: i.session.harness, nativeId: i.session.nativeId, reason, projectRoot: itemRoot(i), title: null };
|
|
201
|
+
FILE_OF.set(f, i.session.file.path);
|
|
202
|
+
return f;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Reads the title (`custom-title`, else `ai-title`; never message content) of the first `limit` failures that are
|
|
207
|
+
* Claude transcripts: the rows a screen shows. 0 (an unattended or quiet run) reads no transcript at all.
|
|
208
|
+
*/
|
|
209
|
+
export async function nameFailures(failures , limit ) {
|
|
210
|
+
for (const f of failures.slice(0, Math.max(0, limit))) {
|
|
211
|
+
const file = FILE_OF.get(f);
|
|
212
|
+
if (f.title === null && f.harness === "claude" && file !== undefined) f.title = await conversationTitle(file);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
const isObj = (u ) => typeof u === "object" && u !== null && !Array.isArray(u);
|
|
248
|
+
|
|
249
|
+
/** The T3 responses this run acts on, re-checked field by field before the first write (exit 4 on drift). */
|
|
250
|
+
export function validateSnapshot(version , projects , threads , providers ) {
|
|
251
|
+
const bad = (what ) => {
|
|
252
|
+
throw new T3Incompatible(version, `T3 Code ${version} returned an unexpected ${what} shape; nothing was changed. Update t3sm or report it.`);
|
|
253
|
+
};
|
|
254
|
+
if (!Array.isArray(projects)) bad("project list");
|
|
255
|
+
for (const p of projects ) {
|
|
256
|
+
if (!isObj(p) || typeof p.id !== "string" || typeof p.workspaceRoot !== "string" || typeof p.title !== "string" || typeof p.archived !== "boolean") bad("project");
|
|
257
|
+
}
|
|
258
|
+
if (!Array.isArray(threads)) bad("thread list");
|
|
259
|
+
for (const t of threads ) if (!isObj(t) || typeof t.id !== "string" || typeof t.projectId !== "string") bad("thread");
|
|
260
|
+
if (!Array.isArray(providers)) bad("provider list");
|
|
261
|
+
for (const i of providers ) {
|
|
262
|
+
if (!isObj(i) || typeof i.instanceId !== "string" || typeof i.driver !== "string" || !(i.homePath === null || typeof i.homePath === "string")
|
|
263
|
+
|| (i.availability !== "available" && i.availability !== "unavailable")) bad("provider instance");
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function lastSegment(root ) {
|
|
268
|
+
const parts = root.split("/").filter((x) => x !== "");
|
|
269
|
+
return parts.length === 0 ? root : parts[parts.length - 1] ;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function nativeRoot(root , platform ) {
|
|
273
|
+
return platform === "win32" ? path.win32.normalize(root) : root;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** `file` lies inside directory `dir` (path identity per platform). */
|
|
277
|
+
function inside(file , dir , platform ) {
|
|
278
|
+
const f = rootKey(file, platform), d = rootKey(dir, platform);
|
|
279
|
+
return f.startsWith(d.endsWith("/") ? d : `${d}/`);
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function filterOnly(plan , only , platform ) {
|
|
283
|
+
const keep = (r ) => r !== null && sameCwd(r, only, platform);
|
|
284
|
+
const items = plan.items.filter((i) => keep(i.action.kind === "skip" ? i.session.cwd : i.action.projectRoot));
|
|
285
|
+
const keptPaths = new Set(items.map((i) => i.session.file.path));
|
|
286
|
+
const instancesUsed = new Set ([
|
|
287
|
+
...items.flatMap((i) => (i.action.kind === "skip" ? [] : [i.action.instanceId])),
|
|
288
|
+
...plan.projectDefaults.filter((d) => keep(d.root)).map((d) => d.instanceId),
|
|
289
|
+
]);
|
|
290
|
+
return {
|
|
291
|
+
...plan,
|
|
292
|
+
items,
|
|
293
|
+
projectsToCreate: plan.projectsToCreate.filter((p) => keep(p.root)),
|
|
294
|
+
projectDefaults: plan.projectDefaults.filter((d) => keep(d.root)),
|
|
295
|
+
projectAccounts: plan.projectAccounts.filter((p) => keep(p.root)),
|
|
296
|
+
instancesToCreate: plan.instancesToCreate.filter((s) => instancesUsed.has(s.id)),
|
|
297
|
+
// A mirror whose kept copy is not in this root cannot be imported by this run's import calls.
|
|
298
|
+
mirrorCopies: plan.mirrorCopies.filter((m) => keptPaths.has(m.keptPath) || !plan.items.some((i) => i.session.file.path === m.keptPath)),
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
export function progressLine(p ) {
|
|
303
|
+
return `Wave ${p.wave}/${p.totalWaves} · ${p.projects} ${p.projects === 1 ? "project" : "projects"} · ${p.sessions} sessions · imported ${p.imported} · retry ${p.retry}`
|
|
304
|
+
+ (p.failed ? ` · failed ${p.failed}` : "") + (p.deferred ? ` · deferred ${p.deferred}` : "");
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* `planSource` is the plan, or a loader called only once the lock is held (the CLI reads plan.json there, so a held
|
|
309
|
+
* lock always wins over a missing or stale plan).
|
|
310
|
+
*/
|
|
311
|
+
export async function applyPlan(planSource , deps ) {
|
|
312
|
+
const platform = deps.platform ?? process.platform;
|
|
313
|
+
const now = deps.now ?? Date.now;
|
|
314
|
+
const notice = deps.onNotice ?? (() => {});
|
|
315
|
+
const tr = (k , v = {}) => cliT(deps.lang ?? "en", k, v);
|
|
316
|
+
const result = {
|
|
317
|
+
status: "ok", runId: null, imported: 0, failed: 0, failures: [], converted: 0, deferred: 0, deferredInUse: 0, heldRoots: [], held: [], alreadyInT3: 0, restoreErrors: [], unverified: 0, parked: 0, recovered: null,
|
|
318
|
+
};
|
|
319
|
+
|
|
320
|
+
// A dry run takes the lock too (it reads a consistent state), but never creates the state folder for it.
|
|
321
|
+
const noStateDir = deps.dryRun === true && (await stat(deps.stateDir).then(() => false, () => true));
|
|
322
|
+
const lock = noStateDir ? { release: async () => {} } : await acquireLock(deps.stateDir);
|
|
323
|
+
if (!lock) return { ...result, status: "locked" };
|
|
324
|
+
const signals = deps.signals ?? processSignals;
|
|
325
|
+
const exit = deps.exit ?? ((code ) => process.exit(code));
|
|
326
|
+
let abort = false;
|
|
327
|
+
let signalCount = 0;
|
|
328
|
+
let pendingFiles = null;
|
|
329
|
+
// 1st: stop after the current wave's restore. 2nd: if a wave is in progress, say so (once); otherwise nothing.
|
|
330
|
+
// 3rd: restore the wave's files synchronously and exit 130 now; whatever could not be restored stays pending in the
|
|
331
|
+
// journal for the next run's recovery. The lock file is left behind with this (dead) pid; the next run treats it as
|
|
332
|
+
// stale.
|
|
333
|
+
const onSignal = () => {
|
|
334
|
+
abort = true;
|
|
335
|
+
signalCount++;
|
|
336
|
+
if (signalCount === 2) {
|
|
337
|
+
if (pendingFiles) notice(tr("apply.notice.stillRestoring"));
|
|
338
|
+
} else if (signalCount >= 3) {
|
|
339
|
+
if (pendingFiles) restoreSync(pendingFiles);
|
|
340
|
+
notice(tr("apply.notice.forcedExit"));
|
|
341
|
+
exit(130);
|
|
342
|
+
}
|
|
343
|
+
};
|
|
344
|
+
// SIGHUP (the terminal or console window closed) stops the run like SIGTERM.
|
|
345
|
+
for (const sig of STOP_SIGNALS) signals.on(sig, onSignal);
|
|
346
|
+
try {
|
|
347
|
+
const journal = new Journal(join(deps.stateDir, "journal.jsonl"));
|
|
348
|
+
const entriesBefore = await journal.readAll(); // before the recovery: which future file times are t3sm's own
|
|
349
|
+
const pendingRecovery = deps.dryRun ? pendingMtimePaths(entriesBefore, platform) : [];
|
|
350
|
+
if (!deps.dryRun) result.recovered = await recoverPendingMtimes(journal);
|
|
351
|
+
|
|
352
|
+
const inputPlan = typeof planSource === "function" ? await planSource() : planSource;
|
|
353
|
+
const created = Date.parse(inputPlan.createdAt);
|
|
354
|
+
if (inputPlan.version !== 1 || !Number.isFinite(created) || now() - created > PLAN_MAX_AGE_MS || created - now() > 3_600_000) throw new ApplyRefusal(STALE);
|
|
355
|
+
const plan = deps.only ? filterOnly(inputPlan, deps.only, platform) : inputPlan;
|
|
356
|
+
if (deps.only && plan.items.length === 0 && plan.projectsToCreate.length === 0 && plan.projectDefaults.length === 0) {
|
|
357
|
+
throw new ApplyRefusal(`No sessions or projects under ${deps.only} in this plan.`);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
const connect = deps.connect ?? connectT3;
|
|
361
|
+
const pinWanted = deps.pinDefaultInstance !== false && plan.pinDefault != null ? plan.pinDefault : null;
|
|
362
|
+
const manageProviders = !deps.dryRun && (plan.instancesToCreate.length > 0 || pinWanted !== null);
|
|
363
|
+
const api = await connect(deps.home, { allowUntested: deps.allowUntested ?? false, manageProviders, onNotice: notice });
|
|
364
|
+
try {
|
|
365
|
+
if (plan.t3Version !== api.version) throw new ApplyRefusal(`T3 Code changed from ${plan.t3Version} to ${api.version} since the plan. ${STALE}`);
|
|
366
|
+
|
|
367
|
+
// ---------- checks: nothing has been written yet ----------
|
|
368
|
+
const [projects, threads, providers] = await Promise.all([api.listProjects(), api.listThreads(), api.providerInstances()]);
|
|
369
|
+
validateSnapshot(api.version, projects, threads, providers);
|
|
370
|
+
// T3's default Claude instance must read the config account whose home is ~/.claude (matched by home, any id).
|
|
371
|
+
let settingsP = null;
|
|
372
|
+
const settings = () => (settingsP ??= api.getConfig().then((c) => c.settings.providerInstances));
|
|
373
|
+
if (deps.accountHomes) {
|
|
374
|
+
const homes = Object.values(deps.accountHomes());
|
|
375
|
+
const def = providers.find((p) => p.instanceId === DEFAULT_ID && p.driver === "claudeAgent");
|
|
376
|
+
// T3's settings are read only when the default instance's home is in question (they say which advice applies).
|
|
377
|
+
assertDefaultInstanceHome(providers, homes, deps.home, platform, def?.homePath != null && !sameCwd(def.homePath, defaultClaudeHome(deps.home), platform) ? await settings() : undefined);
|
|
378
|
+
}
|
|
379
|
+
await warnMirrors(plan, now(), notice, tr);
|
|
380
|
+
checkInstanceHomes(plan, providers, platform);
|
|
381
|
+
// The pin is made only while the instance is still implicit (no settings entry) and reads that home (or none).
|
|
382
|
+
let pin = null;
|
|
383
|
+
if (pinWanted !== null) {
|
|
384
|
+
const def = providers.find((p) => p.instanceId === pinWanted.instanceId);
|
|
385
|
+
if (def && def.homePath !== null && !sameCwd(def.homePath, pinWanted.homePath, platform)) throw driftError(await settings(), def.homePath);
|
|
386
|
+
if (def && sameCwd(pinWanted.homePath, defaultClaudeHome(deps.home), platform)
|
|
387
|
+
&& !Object.hasOwn(await settings(), pinWanted.instanceId)) pin = pinWanted;
|
|
388
|
+
}
|
|
389
|
+
if (abort) return { ...result, status: "aborted" };
|
|
390
|
+
|
|
391
|
+
// Exposure (what T3 could import besides the plan's items): every discovered session, plus the homes of the
|
|
392
|
+
// instances this run will create (a mirror there is exposed as soon as the instance exists), plus a wave-time
|
|
393
|
+
// listing of new files. Projects with a transcript in use right now are held for the whole run: computed here,
|
|
394
|
+
// before the nothing-to-write check, so a cycle where everything pending is held writes nothing at all.
|
|
395
|
+
const exposedItems = deps.exposure?.() ?? inputPlan.items;
|
|
396
|
+
const ahead = futureLeftovers(exposedItems.map((i) => i.session.file), entriesBefore, now(), platform);
|
|
397
|
+
if (ahead.length > 0) {
|
|
398
|
+
notice(tr("apply.notice.futureTimes", { n: ahead.length }));
|
|
399
|
+
}
|
|
400
|
+
let liveProviders = [...providers, ...plan.instancesToCreate
|
|
401
|
+
.filter((s) => !providers.some((p) => p.instanceId === s.id))
|
|
402
|
+
.map((s) => ({ instanceId: s.id, driver: "claudeAgent", homePath: s.homePath, displayName: s.displayName, accentColor: s.accentColor, email: null, authStatus: null, enabled: true, availability: "available" }))];
|
|
403
|
+
const homes = deps.accountHomes?.() ?? {};
|
|
404
|
+
// Claude transcripts discovery already read keep its id (no re-read at wave time); only new files are streamed.
|
|
405
|
+
const knownIds = new Map(exposedItems.filter((i) => i.session.harness === "claude").map((i) => [pathKey(i.session.file.path, platform), i.session.nativeId]));
|
|
406
|
+
const live = liveExposure(() => liveProviders, platform, deps.rediscover, {
|
|
407
|
+
accountHome: (id) => (Object.hasOwn(homes, id) ? homes[id] : undefined), warn: notice,
|
|
408
|
+
knownId: (p) => knownIds.get(pathKey(p, platform)),
|
|
409
|
+
});
|
|
410
|
+
// An item whose session T3 already holds in its other form (Codex: native vs converted thread) counts as in T3.
|
|
411
|
+
const threadIds0 = inT3ThreadIds(plan.items, threads);
|
|
412
|
+
const refs0 = new Set(threads.flatMap((t) => (t.nativeSessionId ? [`${t.instanceId}:${t.nativeSessionId}`] : [])));
|
|
413
|
+
// A convert-import item is exposed through its converted transcript (written by an earlier run, or not yet).
|
|
414
|
+
const pendingImports = plan.items.filter((i) => i.action.kind !== "skip" && !threadIds0.has(i.action.expectedThreadId)).map(asTargetItem);
|
|
415
|
+
const pre = exposureIndex({
|
|
416
|
+
entries: exposureOf(exposedItems, liveProviders, platform), items: pendingImports, platform, live,
|
|
417
|
+
inT3: (ids, rs) => ids.some((id) => threadIds0.has(id)) || rs.some((r) => refs0.has(r)),
|
|
418
|
+
});
|
|
419
|
+
const heldAtStart = new Set ();
|
|
420
|
+
const rootsOf = new Map ();
|
|
421
|
+
for (const i of pendingImports) rootsOf.set(rootKey(itemRoot(i), platform), itemRoot(i));
|
|
422
|
+
// A held project's name as T3 shows it: its existing title (renamed, General, de-duplicated), else the plan's, else the folder.
|
|
423
|
+
const projectName = (root ) => {
|
|
424
|
+
const k = rootKey(root, platform);
|
|
425
|
+
return projects.find((p) => !p.deleted && rootKey(p.workspaceRoot, platform) === k)?.title
|
|
426
|
+
?? plan.projectsToCreate.find((p) => rootKey(p.root, platform) === k)?.title ?? lastSegment(normalizeCwd(root, platform));
|
|
427
|
+
};
|
|
428
|
+
for (const [k, root] of rootsOf) {
|
|
429
|
+
const s = await pre.scan(k, root, now, new Set(), 0);
|
|
430
|
+
if (!s.inUse) continue;
|
|
431
|
+
heldAtStart.add(k);
|
|
432
|
+
if (s.active) result.held.push(await heldEntry(projectName(root), root, s.active));
|
|
433
|
+
}
|
|
434
|
+
const isHeld = (r ) => heldAtStart.has(rootKey(r, platform));
|
|
435
|
+
const heldItems = pendingImports.filter((i) => isHeld(itemRoot(i)));
|
|
436
|
+
// A held project keeps its project and default (S6: creating one imports nothing); only its imports wait.
|
|
437
|
+
const runnable = heldAtStart.size === 0 ? { ...plan, pinDefault: pin } : {
|
|
438
|
+
...plan,
|
|
439
|
+
pinDefault: pin,
|
|
440
|
+
items: plan.items.filter((i) => !(i.action.kind !== "skip" && isHeld(i.action.projectRoot))),
|
|
441
|
+
};
|
|
442
|
+
const noteHeld = () => {
|
|
443
|
+
result.deferred += heldItems.length;
|
|
444
|
+
result.deferredInUse += heldItems.length;
|
|
445
|
+
for (const r of rootsOf.values()) if (isHeld(r) && !result.heldRoots.includes(r)) result.heldRoots.push(r);
|
|
446
|
+
};
|
|
447
|
+
|
|
448
|
+
const heldToCreate = heldItems.some((i) => !projects.some((p) => !p.deleted && rootKey(p.workspaceRoot, platform) === rootKey(itemRoot(i), platform)));
|
|
449
|
+
if (deps.noopWithoutWrites && pin === null && !heldToCreate && nothingToWrite(runnable, projects, threadIds0, platform)) {
|
|
450
|
+
const ids = threadIds0;
|
|
451
|
+
const liveIds = runnable.items.flatMap((i) => (i.action.kind === "skip" ? [] : [i.action.expectedThreadId]));
|
|
452
|
+
result.alreadyInT3 = liveIds.filter((id) => ids.has(id)).length;
|
|
453
|
+
noteHeld();
|
|
454
|
+
result.status = "noop";
|
|
455
|
+
if (deps.afterApply) await deps.afterApply({ api, journal, plan, result, runId: null, aborted: () => abort, onPendingFiles: (f) => { pendingFiles = f; } });
|
|
456
|
+
return result;
|
|
457
|
+
}
|
|
458
|
+
const heldRootNames = [...rootsOf.values()].filter((r) => isHeld(r));
|
|
459
|
+
// The folders a run would create for rehome copies: shown by the dry run and the confirmation.
|
|
460
|
+
const foldersToCreate = deps.rehomeFolders
|
|
461
|
+
? (await checkRehomeFolders(pendingImports, projects, deps.rehomeFolders, platform)).flatMap((c) => (c.state === "create" ? [c.root] : []))
|
|
462
|
+
: [];
|
|
463
|
+
if (deps.dryRun) {
|
|
464
|
+
const report = dryRunReport(runnable, heldItems, projects, providers, threadIds0, deps.batch ?? DEFAULT_BATCH, platform);
|
|
465
|
+
const failUpFront = report.failUpFront.map(({ item, reason }) => failureOf(item, reason) );
|
|
466
|
+
await nameFailures(failUpFront, deps.failureTitles ?? 0);
|
|
467
|
+
return { ...result, status: "dry-run", dryRun: { ...report, failUpFront, pendingRecovery, held: { roots: heldRootNames, sessions: heldItems.length }, pinDefault: pin?.homePath ?? null, foldersToCreate } };
|
|
468
|
+
}
|
|
469
|
+
if (deps.confirm && !(await deps.confirm(runnable, { roots: heldRootNames, sessions: heldItems.length }, { foldersToCreate }))) return { ...result, status: "declined" };
|
|
470
|
+
if (abort) return { ...result, status: "aborted" };
|
|
471
|
+
if (deps.beforeWrites) await deps.beforeWrites(runnable); // what this run does (held projects' sessions removed)
|
|
472
|
+
|
|
473
|
+
// ---------- writes ----------
|
|
474
|
+
const runId = deps.runId ?? newRunId(new Date(now()));
|
|
475
|
+
result.runId = runId;
|
|
476
|
+
await journal.append({ t: "run-start", runId, at: new Date(now()).toISOString(), command: deps.command ?? `apply ${inputPlan.runId}${deps.only ? " --only" : ""}` });
|
|
477
|
+
await backfillImported(journal, new Set(threads.map((t) => t.id)));
|
|
478
|
+
let waves = null;
|
|
479
|
+
try {
|
|
480
|
+
if (pin !== null) {
|
|
481
|
+
const r = await api.pinInstanceHome(pin.instanceId, pin.homePath);
|
|
482
|
+
if (r.changed) await journal.append({ t: "instance-pinned", runId, instanceId: pin.instanceId, previous: { homePath: entryHome(r.previous) }, next: { homePath: pin.homePath } });
|
|
483
|
+
}
|
|
484
|
+
if (plan.instancesToCreate.length > 0) {
|
|
485
|
+
await ensureInstances(api, plan.instancesToCreate, journal, runId, defaultClaudeHome(deps.home));
|
|
486
|
+
liveProviders = await api.providerInstances(); // the instances as T3 now has them (created ones included)
|
|
487
|
+
}
|
|
488
|
+
noteHeld();
|
|
489
|
+
|
|
490
|
+
const threadIds = threadIds0;
|
|
491
|
+
const liveItems = runnable.items.filter((i) => i.action.kind !== "skip");
|
|
492
|
+
const pending = liveItems.filter((i) => !threadIds.has((i.action ).expectedThreadId));
|
|
493
|
+
result.alreadyInT3 = liveItems.length - pending.length;
|
|
494
|
+
const toImport = pending.filter((i) => i.action.kind === "import");
|
|
495
|
+
let toConvert = pending.filter((i) => i.action.kind === "convert-import");
|
|
496
|
+
// Orphan copies (a session T3 Code started whose thread it no longer lists) rely on T3's thread lists being
|
|
497
|
+
// complete: listed once more before anything is written for them (their folder, project or copy), and one whose
|
|
498
|
+
// thread (its handoff id, or a thread of the session itself) is listed now is not copied. It waits for the next
|
|
499
|
+
// plan, which sees it in T3. A listing that fails defers every orphan copy (nothing journaled for them); the
|
|
500
|
+
// rest of the run goes on.
|
|
501
|
+
let orphanHeld = new Set ();
|
|
502
|
+
if ([...toConvert, ...heldItems].some(isOrphanCopy) && !abort) {
|
|
503
|
+
let fresh = null;
|
|
504
|
+
try { fresh = await api.listThreads(); } catch (e) {
|
|
505
|
+
const waiting = toConvert.filter(isOrphanCopy);
|
|
506
|
+
result.deferred += waiting.length;
|
|
507
|
+
orphanHeld = new Set(heldItems.filter(isOrphanCopy));
|
|
508
|
+
const why = shownText(((e )?.message ?? String(e)).split(/\r?\n/)[0] ?? "");
|
|
509
|
+
notice(tr("apply.notice.orphanCheckFailed", { n: waiting.length + orphanHeld.size, error: why }));
|
|
510
|
+
toConvert = toConvert.filter((i) => !isOrphanCopy(i));
|
|
511
|
+
}
|
|
512
|
+
if (fresh !== null) {
|
|
513
|
+
const ids = new Set(fresh.flatMap((t) => [t.id, /^import:[^:]+:(.+)$/s.exec(t.id)?.[1] ?? "", t.nativeSessionId ?? ""]).filter((x) => x !== ""));
|
|
514
|
+
const listed = (i ) => isOrphanCopy(i) && (ids.has(i.session.nativeId) || (i.session.t3ThreadId !== undefined && ids.has(i.session.t3ThreadId)));
|
|
515
|
+
const live = toConvert.filter(listed);
|
|
516
|
+
orphanHeld = new Set(heldItems.filter(listed));
|
|
517
|
+
if (live.length > 0) {
|
|
518
|
+
result.deferred += live.length;
|
|
519
|
+
notice(tr("apply.notice.orphanListed", { n: live.length }));
|
|
520
|
+
toConvert = toConvert.filter((i) => !live.includes(i));
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
// Rehome destination folders, before any copy is written; a folder that cannot be used fails its items only.
|
|
525
|
+
let heldProjects = heldItems.filter((i) => !orphanHeld.has(i)); // held items whose project is still created (empty)
|
|
526
|
+
if (deps.rehomeFolders && !abort) {
|
|
527
|
+
const blocked = await prepareRehomeFolders([...toConvert, ...heldProjects], projects, deps.rehomeFolders, journal, runId, platform, notice, tr);
|
|
528
|
+
if (blocked.size > 0) {
|
|
529
|
+
const why = (i ) => blocked.get(rootKey(itemRoot(i), platform));
|
|
530
|
+
for (const i of toConvert) {
|
|
531
|
+
const w = why(i);
|
|
532
|
+
if (w === undefined) continue;
|
|
533
|
+
const reason = `target-folder: ${w}`;
|
|
534
|
+
result.failed++;
|
|
535
|
+
result.failures.push(failureOf(i, reason));
|
|
536
|
+
await journal.append({ t: "import-failed", runId, harness: i.session.harness, nativeId: i.session.nativeId, reason });
|
|
537
|
+
}
|
|
538
|
+
toConvert = toConvert.filter((i) => why(i) === undefined);
|
|
539
|
+
heldProjects = heldProjects.filter((i) => why(i) === undefined);
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
if (toConvert.length > 0 && !abort) { // interrupted first: not attempted (like a wave never started)
|
|
543
|
+
const m = await materializeConversions(toConvert, adapterMap(deps.adapters ?? allAdapters()), conversionAccounts(liveProviders, deps.accountHomes?.() ?? {}), journal, runId, { platform });
|
|
544
|
+
result.converted = m.written.length;
|
|
545
|
+
result.deferred += m.deferred.length; // source busy / session in use: next run, not a failure
|
|
546
|
+
for (const { item, reason } of m.failed) {
|
|
547
|
+
result.failed++;
|
|
548
|
+
result.failures.push(failureOf(item, reason));
|
|
549
|
+
await journal.append({ t: "import-failed", runId, harness: item.session.harness, nativeId: item.session.nativeId, reason: `convert: ${reason}` });
|
|
550
|
+
}
|
|
551
|
+
toImport.push(...m.ready); // the converted transcript is now the item's file
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
const projectOf = await ensureProjects(api, runnable, projects, [...toImport, ...heldProjects], journal, runId, platform);
|
|
555
|
+
const defaults = [];
|
|
556
|
+
for (const d of runnable.projectDefaults) {
|
|
557
|
+
const p = projectOf.get(rootKey(d.root, platform));
|
|
558
|
+
if (p) defaults.push({ projectId: p.id, instanceId: d.instanceId });
|
|
559
|
+
}
|
|
560
|
+
if (defaults.length > 0) await applyProjectDefaults(api, defaults, journal, runId);
|
|
561
|
+
|
|
562
|
+
if (toImport.length > 0 && !abort) {
|
|
563
|
+
const batch = deps.batch ?? DEFAULT_BATCH;
|
|
564
|
+
const cost = (i ) => i.session.cwdOffsetBytes;
|
|
565
|
+
const projectIds = new Map ();
|
|
566
|
+
const importRoots = new Map ();
|
|
567
|
+
for (const [k, p] of projectOf) { projectIds.set(k, p.id); importRoots.set(k, p.workspaceRoot); }
|
|
568
|
+
// From the list read after ensureInstances: a just-created instance has its real availability here.
|
|
569
|
+
const providerAvail = new Map(liveProviders.map((p) => [p.instanceId, p.availability] ));
|
|
570
|
+
const planned = buildWaves(toImport, batch, cost, { platform });
|
|
571
|
+
deps.onImportStart?.({ sessions: toImport.length, projects: new Set(toImport.map((i) => rootKey(itemRoot(i), platform))).size });
|
|
572
|
+
waves = await runWaves({
|
|
573
|
+
api, journal, runId, projectIds, importRoots, now, batch, cost, platform,
|
|
574
|
+
instanceAvailability: providerAvail,
|
|
575
|
+
exposure: exposureOf(exposedItems, liveProviders, platform), liveExposure: live,
|
|
576
|
+
aborted: () => abort,
|
|
577
|
+
onPendingFiles: (f) => { pendingFiles = f; },
|
|
578
|
+
onProgress: (p) => { deps.onWave?.(p); deps.onProgress?.(progressLine(p)); },
|
|
579
|
+
onNotice: notice,
|
|
580
|
+
}, planned);
|
|
581
|
+
result.imported = waves.imported.length;
|
|
582
|
+
result.unverified = waves.unverified.length;
|
|
583
|
+
result.failed += waves.failed.length;
|
|
584
|
+
for (const f of waves.failed) result.failures.push(failureOf(f.item, f.reason));
|
|
585
|
+
result.deferred += waves.deferred.length;
|
|
586
|
+
result.deferredInUse += waves.deferred.filter((d) => d.reason === "project-in-use").length;
|
|
587
|
+
for (const r of waves.heldRoots) if (!result.heldRoots.some((x) => rootKey(x, platform) === rootKey(r, platform))) result.heldRoots.push(r);
|
|
588
|
+
for (const h of waves.heldActive) if (!result.held.some((x) => rootKey(x.root, platform) === rootKey(h.root, platform))) result.held.push(await heldEntry(projectName(h.root), h.root, h.file));
|
|
589
|
+
result.restoreErrors = waves.restoreErrors;
|
|
590
|
+
result.parked = waves.parked;
|
|
591
|
+
const jumped = waves.deferred.filter((d) => d.reason === "clock-jump").length;
|
|
592
|
+
if (jumped > 0) notice(tr("apply.notice.clockJump", { n: jumped }));
|
|
593
|
+
}
|
|
594
|
+
result.status = abort || waves?.aborted ? "aborted" : result.failed > 0 || result.unverified > 0 || result.restoreErrors.length > 0 ? "partial" : "ok";
|
|
595
|
+
if (deps.afterApply && !abort) await deps.afterApply({ api, journal, plan, result, runId, aborted: () => abort, onPendingFiles: (f) => { pendingFiles = f; } });
|
|
596
|
+
} catch (e) {
|
|
597
|
+
await journal.append({ t: "run-end", runId, at: new Date(now()).toISOString(), status: "aborted" }).catch(() => {});
|
|
598
|
+
throw e;
|
|
599
|
+
}
|
|
600
|
+
// How many projects waited (in use): read back after the fact, e.g. by the guided assistant (never from the plan).
|
|
601
|
+
await journal.append({
|
|
602
|
+
t: "run-end", runId, at: new Date(now()).toISOString(), status: result.status ,
|
|
603
|
+
...(result.heldRoots.length > 0 ? { held: result.heldRoots.length } : {}),
|
|
604
|
+
});
|
|
605
|
+
await nameFailures(result.failures, deps.failureTitles ?? 0);
|
|
606
|
+
return result;
|
|
607
|
+
} finally {
|
|
608
|
+
await api.close();
|
|
609
|
+
}
|
|
610
|
+
} finally {
|
|
611
|
+
for (const sig of STOP_SIGNALS) signals.off(sig, onSignal);
|
|
612
|
+
await lock.release();
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
/** A notice in the run's language. */
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
/** A rehome destination folder as checked before a run: kept as it is, to create, or unusable (and why). */
|
|
620
|
+
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
/** An absolute folder as normalizeCwd spells it (a drive or UNC root on Windows). */
|
|
624
|
+
function isAbsoluteRoot(root , platform ) {
|
|
625
|
+
return platform === "win32" ? /^[A-Za-z]:\//.test(root) || root.startsWith("//") : root.startsWith("/");
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
/**
|
|
629
|
+
* Read-only: the destination folder of each rehome copy among `items` (distinct roots). A folder that exists is used
|
|
630
|
+
* as it is when T3 Code has its project, else it must be a folder T3 Code accepts (not temp / system) and a directory.
|
|
631
|
+
* A missing one, whether or not T3 Code still has its project (rolled back, deleted by hand), is to be created once it
|
|
632
|
+
* passes the same checks. A relative root is never used (it would land in the current folder).
|
|
633
|
+
*/
|
|
634
|
+
async function checkRehomeFolders(items , projects , o , platform ) {
|
|
635
|
+
const out = [];
|
|
636
|
+
const seen = new Set ();
|
|
637
|
+
const code = (e ) => (e )?.code ?? (e )?.message ?? String(e);
|
|
638
|
+
for (const i of items) {
|
|
639
|
+
if (i.action.kind !== "convert-import" || i.action.rehomeFrom === undefined) continue;
|
|
640
|
+
const root = i.action.projectRoot;
|
|
641
|
+
const key = rootKey(root, platform);
|
|
642
|
+
if (seen.has(key)) continue;
|
|
643
|
+
seen.add(key);
|
|
644
|
+
const base = { root, key, native: nativeRoot(root, platform), shown: shownText(tildePath(root, o.env.home, platform)) };
|
|
645
|
+
const blocked = (verb , reason ) => ({ ...base, state: "blocked", verb, reason });
|
|
646
|
+
if (!isAbsoluteRoot(root, platform)) { out.push(blocked("cannot create", "it is not an absolute folder")); continue; }
|
|
647
|
+
if (/[\p{Cc}\p{Cf}]/u.test(root)) { out.push(blocked("cannot create", "its name contains control or invisible characters")); continue; }
|
|
648
|
+
let st = null;
|
|
649
|
+
try { st = await stat(base.native); } catch (e) {
|
|
650
|
+
if (code(e) !== "ENOENT") { out.push(blocked("cannot use", code(e))); continue; }
|
|
651
|
+
}
|
|
652
|
+
const inT3 = projects.some((p) => !p.deleted && rootKey(p.workspaceRoot, platform) === key);
|
|
653
|
+
if (st !== null && inT3) { out.push({ ...base, state: "ok" }); continue; } // T3 Code has it, and its folder is there
|
|
654
|
+
const verb = st === null ? "cannot create" : "cannot use";
|
|
655
|
+
const cat = classifyFolder(root, o.env);
|
|
656
|
+
if (cat === "temp" || cat === "system") { out.push(blocked(verb, "it is a temporary or system folder")); continue; }
|
|
657
|
+
if (cat !== "project") { out.push(blocked(verb, "T3 Code does not accept it as a project")); continue; }
|
|
658
|
+
if (st === null) out.push({ ...base, state: "create" });
|
|
659
|
+
else out.push(st.isDirectory() ? { ...base, state: "ok" } : blocked("cannot create", "a file with that name is in the way"));
|
|
660
|
+
}
|
|
661
|
+
return out;
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
/**
|
|
665
|
+
* The writes of checkRehomeFolders: a missing folder is created (and journaled) right before the copies; an unusable
|
|
666
|
+
* one is reported once ("cannot create <folder>: <reason>", home shown as ~). Returns root key -> why it cannot be used.
|
|
667
|
+
*/
|
|
668
|
+
async function prepareRehomeFolders(
|
|
669
|
+
items , projects , o , journal , runId , platform , notice , tr ,
|
|
670
|
+
) {
|
|
671
|
+
const blocked = new Map ();
|
|
672
|
+
const make = o.mkdir ?? ((p ) => mkdir(p, { recursive: true }));
|
|
673
|
+
const code = (e ) => (e )?.code ?? (e )?.message ?? String(e);
|
|
674
|
+
for (const c of await checkRehomeFolders(items, projects, o, platform)) {
|
|
675
|
+
const block = (verb , reason ) => {
|
|
676
|
+
blocked.set(c.key, reason);
|
|
677
|
+
notice(tr(verb === "cannot create" ? "apply.notice.cannotCreate" : "apply.notice.cannotUse", { path: c.shown, reason: shownText(reason) }));
|
|
678
|
+
};
|
|
679
|
+
if (c.state === "blocked") { block(c.verb, c.reason); continue; }
|
|
680
|
+
if (c.state === "ok") continue;
|
|
681
|
+
let created ;
|
|
682
|
+
try { created = await make(c.native); } catch (e) {
|
|
683
|
+
block("cannot create", code(e) === "EEXIST" || code(e) === "ENOTDIR" ? "a file with that name is in the way" : code(e));
|
|
684
|
+
continue;
|
|
685
|
+
}
|
|
686
|
+
if (created === undefined) continue; // made meanwhile by someone else: not t3sm's
|
|
687
|
+
await journal.append({ t: "folder-created", runId, path: c.native, created });
|
|
688
|
+
notice(tr("apply.notice.folderCreated", { path: c.shown }));
|
|
689
|
+
}
|
|
690
|
+
return blocked;
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
/** A held root's entry: its project's name, the active transcript, its title (Claude transcripts only; never message content), its time. */
|
|
694
|
+
async function heldEntry(project , root , f ) {
|
|
695
|
+
const title = f.harness === null || f.harness === "claude" ? await conversationTitle(f.path) : null;
|
|
696
|
+
return { project, root, file: f.path, title, modifiedAt: new Date(f.mtimeMs).toISOString() };
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
/**
|
|
700
|
+
* Transcripts more than ACTIVE_WINDOW_MS ahead of `now` that no pending journal bump explains (a parked file whose
|
|
701
|
+
* journal entry was lost, or a clock that was wrong when the file was written). T3 Code skips them; t3sm cannot know
|
|
702
|
+
* their real time, so they are only reported (apply / sync warn, doctor lists them).
|
|
703
|
+
*/
|
|
704
|
+
export function futureLeftovers(files , entries , now , platform = process.platform) {
|
|
705
|
+
const key = (p ) => pathKey(p, platform);
|
|
706
|
+
const pending = new Set(pendingMtimePaths(entries, platform).map(key));
|
|
707
|
+
const seen = new Set ();
|
|
708
|
+
const out = [];
|
|
709
|
+
for (const f of files) {
|
|
710
|
+
const k = key(f.path);
|
|
711
|
+
if (f.mtimeMs <= now + ACTIVE_WINDOW_MS || pending.has(k) || seen.has(k)) continue;
|
|
712
|
+
seen.add(k);
|
|
713
|
+
out.push(f.path);
|
|
714
|
+
}
|
|
715
|
+
return out;
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/**
|
|
719
|
+
* A wave that died before it could verify (crash, T3's thread list unreachable) left `import-attempt` items without an
|
|
720
|
+
* `imported` entry. For each whose thread exists now and whose file is still exactly as attempted (size + mtime), the
|
|
721
|
+
* missing `imported` is journaled under the attempt's run (merge reads it as the session's import baseline; `runs`
|
|
722
|
+
* counts it). A file changed since is left without one: what T3 holds of it is unknown. Idempotent.
|
|
723
|
+
*/
|
|
724
|
+
async function backfillImported(journal , threadIds ) {
|
|
725
|
+
const es = await journal.readAll();
|
|
726
|
+
const have = new Set(es.flatMap((e) => (e.t === "imported" ? [`${e.harness}:${e.nativeId}`] : [])));
|
|
727
|
+
let n = 0;
|
|
728
|
+
for (const e of es) {
|
|
729
|
+
if (e.t !== "import-attempt" || !Array.isArray(e.items)) continue;
|
|
730
|
+
for (const x of e.items ) {
|
|
731
|
+
if (!isObj(x) || typeof x.threadId !== "string" || typeof x.nativeId !== "string" || typeof x.harness !== "string" || !isObj(x.source)) continue;
|
|
732
|
+
const src = x.source;
|
|
733
|
+
if (typeof src.path !== "string" || typeof src.size !== "number" || typeof src.mtimeMs !== "number") continue;
|
|
734
|
+
const k = `${x.harness}:${x.nativeId}`;
|
|
735
|
+
if (have.has(k) || !threadIds.has(x.threadId)) continue;
|
|
736
|
+
const st = await statSafe(src.path).catch(() => null);
|
|
737
|
+
if (!st || st.size !== src.size || !near(st.mtimeMs, src.mtimeMs)) continue;
|
|
738
|
+
const item = x ;
|
|
739
|
+
await journal.append({ t: "imported", runId: e.runId, harness: item.harness, nativeId: item.nativeId, threadId: item.threadId, source: { path: src.path, size: src.size, mtimeMs: src.mtimeMs } });
|
|
740
|
+
have.add(k);
|
|
741
|
+
n++;
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
return n;
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
/**
|
|
748
|
+
* The writes a run of `plan` (already --only-filtered, held projects' sessions removed; `held` adds their roots) would make, mirroring the write phase:
|
|
749
|
+
* instances (ensureInstances), conversions (materializeConversions), projects (ensureProjects), defaults
|
|
750
|
+
* (applyProjectDefaults: unchanged ones are skipped), up-front failures and waves (runWaves / buildWaves).
|
|
751
|
+
*/
|
|
752
|
+
function dryRunReport(
|
|
753
|
+
plan , held , projects , providers , threadIds , batch , platform ,
|
|
754
|
+
) {
|
|
755
|
+
const live = plan.items.filter((i) => i.action.kind !== "skip");
|
|
756
|
+
const pending = live.filter((i) => !threadIds.has((i.action ).expectedThreadId));
|
|
757
|
+
const existing = (root ) => projects.find((p) => !p.deleted && rootKey(p.workspaceRoot, platform) === rootKey(root, platform));
|
|
758
|
+
const projectsToCreate = [];
|
|
759
|
+
for (const i of [...pending, ...held]) { // a held project is created too (empty)
|
|
760
|
+
const r = itemRoot(i);
|
|
761
|
+
if (!existing(r) && !projectsToCreate.some((x) => rootKey(x, platform) === rootKey(r, platform))) projectsToCreate.push(r);
|
|
762
|
+
}
|
|
763
|
+
const defaultsToSet = plan.projectDefaults.filter((d) => {
|
|
764
|
+
const p = existing(d.root);
|
|
765
|
+
if (p) return p.defaultModelSelection?.instanceId !== d.instanceId;
|
|
766
|
+
return projectsToCreate.some((x) => rootKey(x, platform) === rootKey(d.root, platform));
|
|
767
|
+
}).map((d) => ({ root: d.root, instanceId: d.instanceId }));
|
|
768
|
+
const availability = new Map(providers.map((p) => [p.instanceId, p.availability] ));
|
|
769
|
+
const failUpFront = [];
|
|
770
|
+
const waveable = [];
|
|
771
|
+
for (const i of pending) {
|
|
772
|
+
const id = (i.action ).instanceId;
|
|
773
|
+
const reason = i.action.kind === "import" && i.session.cwdOffsetBytes > CWD_SCAN_MAX_BYTES ? "cwd-unreadable-in-t3"
|
|
774
|
+
: availability.get(id) === "unavailable" ? "instance-unavailable" : null;
|
|
775
|
+
if (reason) failUpFront.push({ item: i, reason });
|
|
776
|
+
else waveable.push(asTargetItem(i));
|
|
777
|
+
}
|
|
778
|
+
const waves = buildWaves(waveable, batch, (i) => i.session.cwdOffsetBytes, { platform });
|
|
779
|
+
return {
|
|
780
|
+
plan,
|
|
781
|
+
instancesToCreate: plan.instancesToCreate.filter((s) => !providers.some((p) => p.instanceId === s.id)).map((s) => s.id),
|
|
782
|
+
projectsToCreate, defaultsToSet,
|
|
783
|
+
conversions: pending.filter((i) => i.action.kind === "convert-import").length,
|
|
784
|
+
waves: waves.length,
|
|
785
|
+
waveSessions: waves.reduce((n, w) => n + waveItems(w).length, 0),
|
|
786
|
+
alreadyInT3: live.length - pending.length,
|
|
787
|
+
failUpFront,
|
|
788
|
+
};
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
/**
|
|
792
|
+
* T3's thread ids, plus the expected thread id of every item whose session T3 already holds in its OTHER form (any
|
|
793
|
+
* instance): a Codex session imported natively and since compressed, or converted and since seen as a plain rollout.
|
|
794
|
+
* One session never gets a second thread, whatever the plan (an older plan.json) says.
|
|
795
|
+
*/
|
|
796
|
+
export function inT3ThreadIds(items , threads ) {
|
|
797
|
+
const out = new Set(threads.map((t) => t.id));
|
|
798
|
+
const sessionIds = sessionIdsInT3(threads);
|
|
799
|
+
for (const i of items) {
|
|
800
|
+
if (i.action.kind === "skip") continue;
|
|
801
|
+
const own = i.action.kind === "convert-import" ? i.action.uuid : i.session.nativeId;
|
|
802
|
+
if (!sessionIds.has(own) && otherForms(i.session, own).some((f) => sessionIds.has(f))) out.add(i.action.expectedThreadId);
|
|
803
|
+
}
|
|
804
|
+
return out;
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
/** No instance to create, no import pending in T3, no project default that would change: a run would write nothing. */
|
|
808
|
+
function nothingToWrite(plan , projects , threadIds , platform ) {
|
|
809
|
+
if (plan.instancesToCreate.length > 0) return false;
|
|
810
|
+
if (plan.items.some((i) => i.action.kind !== "skip" && !threadIds.has(i.action.expectedThreadId))) return false;
|
|
811
|
+
for (const d of plan.projectDefaults) {
|
|
812
|
+
const k = rootKey(d.root, platform);
|
|
813
|
+
const p = projects.find((x) => !x.deleted && rootKey(x.workspaceRoot, platform) === k);
|
|
814
|
+
// A project that does not exist is only created for imports (none pending here), so its default is not set either.
|
|
815
|
+
if (p && p.defaultModelSelection?.instanceId !== d.instanceId) return false;
|
|
816
|
+
}
|
|
817
|
+
return true;
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
/**
|
|
821
|
+
* A mirror copy inside the 30-day window is parked during every wave of its project (runWaves' exposure), so this run
|
|
822
|
+
* never imports it under the wrong account. T3's own Welcome import could still take it: warn, recommend dedupe.
|
|
823
|
+
*/
|
|
824
|
+
async function warnMirrors(plan , now , notice , tr ) {
|
|
825
|
+
let live = 0;
|
|
826
|
+
for (const m of plan.mirrorCopies) {
|
|
827
|
+
const st = await statSafe(m.path).catch(() => null);
|
|
828
|
+
if (st && inImportWindow(st.mtimeMs, now)) live++;
|
|
829
|
+
}
|
|
830
|
+
if (live > 0) {
|
|
831
|
+
notice(tr("apply.notice.mirrors", { n: live }));
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
/**
|
|
836
|
+
* What T3 could import, as ExposedTranscript: every discovered native transcript with a cwd, with the thread ids T3
|
|
837
|
+
* would give it. A Claude transcript belongs to the instances whose home holds it (unknown homes: every instance
|
|
838
|
+
* without one); none = no instance reads it, so T3 cannot import it. Other harnesses: any non-Claude instance.
|
|
839
|
+
*/
|
|
840
|
+
export function exposureOf(items , providers , platform ) {
|
|
841
|
+
const out = [];
|
|
842
|
+
const claude = providers.filter((p) => p.driver === "claudeAgent");
|
|
843
|
+
// A disabled or unavailable Codex/Pi instance does not import anything.
|
|
844
|
+
const others = providers.filter((p) => p.driver !== "claudeAgent" && p.enabled && p.availability === "available");
|
|
845
|
+
for (const it of items) {
|
|
846
|
+
const s = it.session;
|
|
847
|
+
// Convert-mode sessions and compressed rollouts are never read by T3 itself.
|
|
848
|
+
if (s.cwd === null || isConvertSession(s) || s.flags?.includes("compressed")) continue;
|
|
849
|
+
if (s.flags.includes("cwd-unreadable")) continue; // T3 cannot read its cwd, so it cannot match a project
|
|
850
|
+
let insts ;
|
|
851
|
+
if (s.harness === "claude") {
|
|
852
|
+
const owners = claude.filter((p) => p.homePath !== null && inside(s.file.path, p.homePath, platform));
|
|
853
|
+
insts = (owners.length > 0 ? owners : claude.filter((p) => p.homePath === null)).map((p) => p.instanceId);
|
|
854
|
+
} else insts = others.map((p) => p.instanceId);
|
|
855
|
+
if (insts.length === 0) continue;
|
|
856
|
+
const threadIds = insts.map((i) => `import:${i}:${s.nativeId}`);
|
|
857
|
+
if (it.action.kind !== "skip") threadIds.push(it.action.expectedThreadId);
|
|
858
|
+
out.push({ path: s.file.path, cwd: s.cwd, threadIds, refs: insts.map((i) => `${i}:${s.nativeId}`), harness: s.harness, nativeId: s.nativeId, cost: s.cwdOffsetBytes });
|
|
859
|
+
}
|
|
860
|
+
return out;
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
/**
|
|
864
|
+
* Wave-time listing of a root's transcripts, for files created after planning. Claude: `<home>/projects/<encoded
|
|
865
|
+
* root>/*.jsonl` in every Claude instance home (the encoded folder matched case-insensitively on Windows and macOS, so
|
|
866
|
+
* drive-letter case variants are included), each under the id T3 imports it as (claudeNativeId: `knownId` for files
|
|
867
|
+
* discovery already read, else the file is streamed once). Codex / Pi: `rediscover` (the adapters' cached
|
|
868
|
+
* discovery), at most once per wave, filtered to that cwd.
|
|
869
|
+
*/
|
|
870
|
+
export function liveExposure(
|
|
871
|
+
getProviders , platform , rediscover ,
|
|
872
|
+
o = {},
|
|
873
|
+
) {
|
|
874
|
+
const fold = platform === "win32" || platform === "darwin";
|
|
875
|
+
let natWave = -1;
|
|
876
|
+
let nat = Promise.resolve([]);
|
|
877
|
+
const warned = new Set ();
|
|
878
|
+
return async (root, wave) => {
|
|
879
|
+
const out = [];
|
|
880
|
+
const enc = encodeClaudeProjectDir(normalizeCwd(root, platform));
|
|
881
|
+
const want = fold ? enc.toLowerCase() : enc;
|
|
882
|
+
for (const p of getProviders()) {
|
|
883
|
+
if (p.driver !== "claudeAgent") continue;
|
|
884
|
+
// T3 reports no home for an implicit instance it has not resolved: the config account of that id names it.
|
|
885
|
+
const home = p.homePath ?? o.accountHome?.(p.instanceId);
|
|
886
|
+
if (!home) {
|
|
887
|
+
if (!warned.has(p.instanceId)) { warned.add(p.instanceId); o.warn?.(`Warning: could not list ${p.instanceId}: home unknown (new transcripts there are not parked this run).`); }
|
|
888
|
+
continue;
|
|
889
|
+
}
|
|
890
|
+
const projects = join(home, "projects");
|
|
891
|
+
const dirs = await readdir(projects).catch(() => [] );
|
|
892
|
+
for (const d of dirs) {
|
|
893
|
+
if ((fold ? d.toLowerCase() : d) !== want) continue;
|
|
894
|
+
for (const f of await readdir(join(projects, d)).catch(() => [] )) {
|
|
895
|
+
if (!f.endsWith(".jsonl")) continue;
|
|
896
|
+
// T3's id rule, as discovery applies it (claudeNativeId): a file named after one session can carry another.
|
|
897
|
+
const path = join(projects, d, f);
|
|
898
|
+
const id = o.knownId?.(path) ?? await readClaudeNativeId(path);
|
|
899
|
+
out.push({ path, cwd: root, threadIds: [`import:${p.instanceId}:${id}`], refs: [`${p.instanceId}:${id}`], harness: "claude", nativeId: id });
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
if (rediscover && getProviders().some((p) => p.driver !== "claudeAgent" && p.enabled && p.availability === "available")) {
|
|
904
|
+
if (natWave !== wave) { natWave = wave; nat = rediscover().catch(() => []); }
|
|
905
|
+
const k = rootKey(root, platform);
|
|
906
|
+
const mine = (await nat).filter((s) => s.harness !== "claude" && s.cwd !== null && rootKey(s.cwd, platform) === k);
|
|
907
|
+
out.push(...exposureOf(mine.map((session) => ({ session, action: { kind: "skip", reason: "excluded" }, notes: [] })), getProviders(), platform));
|
|
908
|
+
}
|
|
909
|
+
return out;
|
|
910
|
+
};
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
/** A convert-import item as the exposure checks see it: its file is the converted transcript (the source is shared). */
|
|
914
|
+
function asTargetItem(i ) {
|
|
915
|
+
if (i.action.kind !== "convert-import") return i;
|
|
916
|
+
return { ...i, session: { ...i.session, file: { ...i.session.file, path: i.action.targetFile } } };
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
/** The adapters that convert sessions (`read`), by harness: convert-mode ones, and Codex for compressed rollouts. */
|
|
920
|
+
function adapterMap(adapters ) {
|
|
921
|
+
return new Map(adapters.filter((a) => typeof a.read === "function").map((a) => [a.id, a]));
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
/** The homes conversions may write into: every Claude instance home T3 reports, plus the config accounts' homes. */
|
|
925
|
+
function conversionAccounts(providers , homes ) {
|
|
926
|
+
const out = [];
|
|
927
|
+
for (const p of providers) if (p.driver === "claudeAgent" && p.homePath !== null) out.push({ id: p.instanceId, home: p.homePath, displayName: p.displayName, accentColor: null });
|
|
928
|
+
for (const [id, home] of Object.entries(homes)) out.push({ id, home, displayName: id, accentColor: null });
|
|
929
|
+
return out;
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
/** Every Claude item must still live in the home its instance reads (S4: an inherited CLAUDE_CONFIG_DIR moves homes). */
|
|
933
|
+
function checkInstanceHomes(plan , providers , platform ) {
|
|
934
|
+
const toCreate = new Set(plan.instancesToCreate.map((s) => s.id));
|
|
935
|
+
for (const it of plan.items) {
|
|
936
|
+
if (it.action.kind === "skip") continue;
|
|
937
|
+
const id = it.action.instanceId;
|
|
938
|
+
const live = providers.find((p) => p.instanceId === id);
|
|
939
|
+
if (!live) {
|
|
940
|
+
if (toCreate.has(id)) continue;
|
|
941
|
+
throw new ApplyRefusal(`T3 instance ${id} no longer exists. ${STALE}`);
|
|
942
|
+
}
|
|
943
|
+
if (it.action.kind === "convert-import") {
|
|
944
|
+
if (live.homePath !== null && !inside(it.action.targetFile, live.homePath, platform)) {
|
|
945
|
+
throw new ApplyRefusal(`T3 instance ${id} now reads ${live.homePath}, not the home session ${it.session.nativeId} would be converted into; converting would file it under the wrong account. Check \`t3sm accounts\`, then run \`t3sm plan\` again.`);
|
|
946
|
+
}
|
|
947
|
+
continue;
|
|
948
|
+
}
|
|
949
|
+
if (it.session.harness !== "claude" || it.action.kind !== "import" || live.homePath === null) continue;
|
|
950
|
+
if (!inside(it.session.file.path, live.homePath, platform)) {
|
|
951
|
+
throw new ApplyRefusal(`T3 instance ${id} now reads ${live.homePath}, which does not hold session ${it.session.nativeId}; importing would file it under the wrong account. Check \`t3sm accounts\`, then run \`t3sm plan\` again.`);
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
/** root key -> T3 project for every root with an import item: existing projects first (sameCwd), else created and journaled. */
|
|
957
|
+
async function ensureProjects(
|
|
958
|
+
api , plan , liveProjects , toImport , journal , runId , platform ,
|
|
959
|
+
) {
|
|
960
|
+
const out = new Map ();
|
|
961
|
+
const find = (ps , k ) => ps.find((p) => !p.deleted && rootKey(p.workspaceRoot, platform) === k);
|
|
962
|
+
const needed = new Map ();
|
|
963
|
+
for (const i of toImport) needed.set(rootKey(itemRoot(i), platform), itemRoot(i));
|
|
964
|
+
for (const d of plan.projectDefaults) {
|
|
965
|
+
const k = rootKey(d.root, platform);
|
|
966
|
+
const p = find(liveProjects, k);
|
|
967
|
+
if (p) out.set(k, p);
|
|
968
|
+
}
|
|
969
|
+
for (const [k, root] of needed) {
|
|
970
|
+
const existing = find(liveProjects, k);
|
|
971
|
+
if (existing) { out.set(k, existing); continue; }
|
|
972
|
+
const spec = plan.projectsToCreate.find((p) => rootKey(p.root, platform) === k);
|
|
973
|
+
const title = spec?.title ?? lastSegment(normalizeCwd(root, platform));
|
|
974
|
+
let p ;
|
|
975
|
+
try {
|
|
976
|
+
p = await api.createProject(nativeRoot(root, platform), title);
|
|
977
|
+
} catch (e) {
|
|
978
|
+
// 400 invalid_command = a project already owns this root (S2 §7): re-read and use it.
|
|
979
|
+
const again = e instanceof T3HttpError && e.status === 400 ? find(await api.listProjects(), k) : undefined;
|
|
980
|
+
if (!again) throw e;
|
|
981
|
+
out.set(k, again);
|
|
982
|
+
continue;
|
|
983
|
+
}
|
|
984
|
+
await journal.append({ t: "project-created", runId, projectId: p.id, root: p.workspaceRoot, title: p.title });
|
|
985
|
+
out.set(k, p);
|
|
986
|
+
}
|
|
987
|
+
return out;
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
/** A faithful copy of a session T3 Code started (its thread gone from T3's lists: an "orphan", src/plan/planner.ts). */
|
|
991
|
+
function isOrphanCopy(i ) {
|
|
992
|
+
return i.action.kind === "convert-import" && i.action.copy === "faithful" && i.session.harness === "claude" && i.session.startedIn === "t3";
|
|
993
|
+
}
|