t3code-session-manager 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/.claude-plugin/marketplace.json +21 -0
  2. package/.claude-plugin/plugin.json +19 -0
  3. package/CHANGELOG.md +138 -0
  4. package/LICENSE +21 -0
  5. package/README.md +660 -2
  6. package/README.pt.md +616 -0
  7. package/bin/entry.d.mts +2 -0
  8. package/bin/entry.mjs +19 -0
  9. package/bin/t3sm.mjs +44 -0
  10. package/commands/import.md +30 -0
  11. package/commands/organize.md +36 -0
  12. package/commands/status.md +24 -0
  13. package/commands/sync.md +26 -0
  14. package/dist/apply/apply.js +993 -0
  15. package/dist/apply/claudeWriter.js +168 -0
  16. package/dist/apply/copyTranscript.js +116 -0
  17. package/dist/apply/importer.js +697 -0
  18. package/dist/apply/materialize.js +335 -0
  19. package/dist/apply/waves.js +108 -0
  20. package/dist/assistant/core.js +295 -0
  21. package/dist/assistant/deps.js +256 -0
  22. package/dist/assistant/i18n.js +38 -0
  23. package/dist/assistant/messages.en.js +494 -0
  24. package/dist/assistant/messages.pt.js +495 -0
  25. package/dist/assistant/runner.js +64 -0
  26. package/dist/assistant/steps.js +1362 -0
  27. package/dist/build.json +1 -0
  28. package/dist/cli/applyScreen.js +158 -0
  29. package/dist/cli/commands/accounts.js +254 -0
  30. package/dist/cli/commands/apply.js +199 -0
  31. package/dist/cli/commands/changelog.js +61 -0
  32. package/dist/cli/commands/doctor.js +105 -0
  33. package/dist/cli/commands/help.js +158 -0
  34. package/dist/cli/commands/merge.js +224 -0
  35. package/dist/cli/commands/organize.js +872 -0
  36. package/dist/cli/commands/plan.js +161 -0
  37. package/dist/cli/commands/projects.js +430 -0
  38. package/dist/cli/commands/quarantine.js +203 -0
  39. package/dist/cli/commands/recover.js +230 -0
  40. package/dist/cli/commands/rollback.js +281 -0
  41. package/dist/cli/commands/scan.js +117 -0
  42. package/dist/cli/commands/schedule.js +288 -0
  43. package/dist/cli/commands/start.js +45 -0
  44. package/dist/cli/commands/status.js +615 -0
  45. package/dist/cli/commands/sync.js +336 -0
  46. package/dist/cli/commands/update.js +398 -0
  47. package/dist/cli/errors.js +53 -0
  48. package/dist/cli/failures.js +91 -0
  49. package/dist/cli/flags.js +53 -0
  50. package/dist/cli/help.en.js +549 -0
  51. package/dist/cli/help.pt.js +566 -0
  52. package/dist/cli/helpText.js +211 -0
  53. package/dist/cli/helpTopics.js +58 -0
  54. package/dist/cli/locked.js +12 -0
  55. package/dist/cli/main.js +155 -0
  56. package/dist/cli/screen.js +3 -0
  57. package/dist/cli/ui.js +111 -0
  58. package/dist/cli/words.js +2 -0
  59. package/dist/core/activity.js +16 -0
  60. package/dist/core/changelog.js +47 -0
  61. package/dist/core/config.js +530 -0
  62. package/dist/core/fsutil.js +171 -0
  63. package/dist/core/glob.js +34 -0
  64. package/dist/core/history.js +32 -0
  65. package/dist/core/journal.js +274 -0
  66. package/dist/core/lock.js +337 -0
  67. package/dist/core/mask.js +31 -0
  68. package/dist/core/paths.js +68 -0
  69. package/dist/core/pid.js +101 -0
  70. package/dist/core/run.js +4 -0
  71. package/dist/core/semver.js +18 -0
  72. package/dist/core/sysroot.js +29 -0
  73. package/dist/core/types.js +229 -0
  74. package/dist/core/uuid.js +29 -0
  75. package/dist/core/version.js +72 -0
  76. package/dist/help/convert.md +20 -0
  77. package/dist/help/convert.pt.md +21 -0
  78. package/dist/help/cwd-unreadable.md +22 -0
  79. package/dist/help/cwd-unreadable.pt.md +22 -0
  80. package/dist/help/decisions.md +20 -0
  81. package/dist/help/decisions.pt.md +20 -0
  82. package/dist/help/errors.md +20 -0
  83. package/dist/help/errors.pt.md +22 -0
  84. package/dist/help/held.md +20 -0
  85. package/dist/help/held.pt.md +20 -0
  86. package/dist/help/history.md +27 -0
  87. package/dist/help/history.pt.md +29 -0
  88. package/dist/help/instance-unavailable.md +18 -0
  89. package/dist/help/instance-unavailable.pt.md +19 -0
  90. package/dist/help/not-imported.md +19 -0
  91. package/dist/help/not-imported.pt.md +19 -0
  92. package/dist/help/orphaned.md +19 -0
  93. package/dist/help/orphaned.pt.md +19 -0
  94. package/dist/help/project-mismatch.md +15 -0
  95. package/dist/help/project-mismatch.pt.md +15 -0
  96. package/dist/help/t3-native.md +22 -0
  97. package/dist/help/t3-native.pt.md +22 -0
  98. package/dist/help/updates.md +26 -0
  99. package/dist/help/updates.pt.md +28 -0
  100. package/dist/help/watcher.md +24 -0
  101. package/dist/help/watcher.pt.md +25 -0
  102. package/dist/i18n/cli.js +41 -0
  103. package/dist/i18n/lang.js +55 -0
  104. package/dist/i18n/messages.en.js +1140 -0
  105. package/dist/i18n/messages.pt.js +1149 -0
  106. package/dist/i18n/words.js +12 -0
  107. package/dist/ops/accounts.js +170 -0
  108. package/dist/ops/autoUpdate.js +223 -0
  109. package/dist/ops/discoverAccounts.js +343 -0
  110. package/dist/ops/doctor.js +811 -0
  111. package/dist/ops/elevated.js +47 -0
  112. package/dist/ops/errorCodes.js +39 -0
  113. package/dist/ops/follow.js +558 -0
  114. package/dist/ops/merge.js +830 -0
  115. package/dist/ops/notify.js +249 -0
  116. package/dist/ops/plugin.js +92 -0
  117. package/dist/ops/projects.js +113 -0
  118. package/dist/ops/quarantine.js +415 -0
  119. package/dist/ops/rollback.js +868 -0
  120. package/dist/ops/schedule.js +464 -0
  121. package/dist/ops/successor.js +51 -0
  122. package/dist/ops/sync.js +859 -0
  123. package/dist/ops/syncStatus.js +290 -0
  124. package/dist/ops/update.js +273 -0
  125. package/dist/ops/updater.js +641 -0
  126. package/dist/ops/watch.js +676 -0
  127. package/dist/ops/watcherControl.js +212 -0
  128. package/dist/ops/watcherHealth.js +75 -0
  129. package/dist/organize/apply.js +495 -0
  130. package/dist/organize/history.js +192 -0
  131. package/dist/organize/plan.js +283 -0
  132. package/dist/organize/rename.js +58 -0
  133. package/dist/organize/sessions.js +100 -0
  134. package/dist/organize/titles.js +70 -0
  135. package/dist/organize/types.js +73 -0
  136. package/dist/plan/categories.js +104 -0
  137. package/dist/plan/dedupe.js +137 -0
  138. package/dist/plan/folders.js +82 -0
  139. package/dist/plan/names.js +93 -0
  140. package/dist/plan/ownership.js +316 -0
  141. package/dist/plan/planner.js +669 -0
  142. package/dist/plan/rehome.js +101 -0
  143. package/dist/plan/report.js +407 -0
  144. package/dist/sources/cache.js +89 -0
  145. package/dist/sources/claude.js +297 -0
  146. package/dist/sources/codex.js +496 -0
  147. package/dist/sources/flatten.js +23 -0
  148. package/dist/sources/jsonl.js +169 -0
  149. package/dist/sources/native.js +233 -0
  150. package/dist/sources/opencode.js +483 -0
  151. package/dist/sources/pi.js +133 -0
  152. package/dist/sources/registry.js +67 -0
  153. package/dist/sources/types.js +80 -0
  154. package/dist/t3/api.js +492 -0
  155. package/dist/t3/auth.js +248 -0
  156. package/dist/t3/compat.js +62 -0
  157. package/dist/t3/decode.js +408 -0
  158. package/dist/t3/errors.js +185 -0
  159. package/dist/t3/rpc.js +185 -0
  160. package/dist/t3/runtime.js +80 -0
  161. package/dist/ui/caps.js +56 -0
  162. package/dist/ui/components.js +202 -0
  163. package/dist/ui/layout.js +205 -0
  164. package/dist/ui/list.js +423 -0
  165. package/dist/ui/locale.js +73 -0
  166. package/dist/ui/organizePreview.js +72 -0
  167. package/dist/ui/progress.js +237 -0
  168. package/dist/ui/style.js +32 -0
  169. package/dist/ui/terminal.js +126 -0
  170. package/dist/ui/text.js +186 -0
  171. package/package.json +58 -4
  172. package/skills/t3code-sessions/SKILL.md +183 -0
@@ -0,0 +1,811 @@
1
+ // `t3sm doctor`: the first command a new user runs. Read-only: it writes nothing except, with --repair, the restore of
2
+ // pending transcript file times (under the state-dir lock). It opens at most one T3 session (read-only scopes) and
3
+ // revokes it before returning. Every check is isolated and bounded by a timeout (its own, or the default 10 s): a throw
4
+ // or a timeout is `fail` only for the checks that block t3sm (CRITICAL_CHECKS); for every other check it is a `warn`, so
5
+ // a slow, large home never reads as a problem to fix.
6
+
7
+ import { statSync } from "node:fs";
8
+ import { access, constants, stat } from "node:fs/promises";
9
+ import { dirname, join } from "node:path";
10
+ import { homedir, hostname, uptime } from "node:os";
11
+
12
+ import { ConfigError, DEFAULT_SCHEDULE_MINUTES, defaultConfig, loadConfig } from "../core/config.js";
13
+ import { expandHome, normalizeCwd, pathKey, sameCwd, stateDir as stateDirOf, tildePath } from "../core/paths.js";
14
+ import { ACTIVE_WINDOW_MS } from "../core/activity.js";
15
+ import { Journal, pendingMtimePaths, recoverPendingMtimes, } from "../core/journal.js";
16
+ import { acquireLock, lockInfo, rebootedSince, } from "../core/lock.js";
17
+ import { probeServer, readServerRuntime, resolveT3Cli, } from "../t3/runtime.js";
18
+ import { connectT3, } from "../t3/api.js";
19
+ import { checkCompat, TESTED_VERSIONS } from "../t3/compat.js";
20
+ import { defaultRunner } from "../t3/auth.js";
21
+ import { redact } from "../t3/errors.js";
22
+ import { describeError, oneLine } from "./errorCodes.js";
23
+
24
+ import { cliT, } from "../i18n/cli.js";
25
+ import { STOP_SIGNALS, futureLeftovers } from "../apply/apply.js";
26
+ import { discoverAccountHomes, formatSources, nodeDiscoveryEnv, resolveAccounts, } from "./discoverAccounts.js";
27
+ import { findBackupDirs, findOrphanedQuarantine, QUARANTINE_DIR, } from "./quarantine.js";
28
+ import { defaultBinPath, realRunner, scheduleSpec, scheduleStatus } from "./schedule.js";
29
+ import { pidAlive, readHeartbeat, } from "./watch.js";
30
+ import { readMergePending } from "./merge.js";
31
+ import { PLUGIN_ID, packageVersion, readPluginState, } from "./plugin.js";
32
+ import { installChangedAt, installRoot, installStamp, } from "../core/version.js";
33
+ import { watcherHealth } from "./watcherHealth.js";
34
+ import { allAdapters, sessionForms, sessionIdsInT3 } from "../sources/registry.js";
35
+ import { countCodexSessions } from "../sources/codex.js";
36
+
37
+ import { shownAccountName, shownText } from "../plan/names.js";
38
+ import { maskEmail, maskEmailsIn } from "../core/mask.js";
39
+
40
+
41
+
42
+
43
+
44
+
45
+
46
+
47
+
48
+
49
+
50
+
51
+
52
+
53
+
54
+
55
+
56
+
57
+ /**
58
+ * What a check found, for a screen that words it itself (the guided assistant) instead of reading the English message:
59
+ * merge-pending: sessions continued in a terminal, sessions with work on a side branch, when they were counted (ISO);
60
+ * harness:<agent>: the agent, its sessions (null: not counted for this agent), unreadable files, and whether T3 Code
61
+ * lacks the agent's own instance for sessions that need it. Additive: `--json` shows it too.
62
+ */
63
+
64
+
65
+
66
+
67
+ /**
68
+ * One piece of a check's text for the screen, in the user's language: a catalogue key (src/i18n/messages.*.ts), its
69
+ * values (a value may itself be parts, worded in the same language), literal punctuation before it (`sep`), and `cap`
70
+ * to start it with a capital. A value named `<x>Ms` (a duration) also gives `<x>` ("3 h", "2 days").
71
+ */
72
+
73
+
74
+ /**
75
+ * A check. `message` and `fix` are English (what --json prints, unchanged); `say` and `sayFix` word the same text from
76
+ * the catalogues for the screen (English gives exactly `message` and `fix`). --json leaves `say` and `sayFix` out.
77
+ */
78
+
79
+
80
+ /** A duration the way doctor words it: minutes under an hour, hours under two days, then days. */
81
+ function ageText(ms , lang ) {
82
+ const m = Math.round(ms / 60_000);
83
+ if (m < 60) return cliT(lang, "doctor.age.min", { n: m });
84
+ const h = Math.round(m / 60);
85
+ return h < 48 ? cliT(lang, "doctor.age.h", { n: h }) : cliT(lang, "doctor.age.days", { n: Math.round(h / 24) });
86
+ }
87
+
88
+ /** Parts as one text in `lang`. */
89
+ export function sayText(parts , lang ) {
90
+ return parts.map((p) => {
91
+ const vars = {};
92
+ for (const [k, v] of Object.entries(p.vars ?? {})) {
93
+ vars[k] = Array.isArray(v) ? sayText(v, lang) : v;
94
+ if (/Ms$/.test(k) && typeof v === "number") vars[k.slice(0, -2)] = ageText(v, lang);
95
+ }
96
+ const text = cliT(lang, p.key, vars);
97
+ return (p.sep ?? "") + (p.cap ? text.replace(/^./, (c) => c.toUpperCase()) : text);
98
+ }).join("");
99
+ }
100
+
101
+ const part = (key , vars , sep ) => ({ key, ...(vars ? { vars } : {}), ...(sep !== undefined ? { sep } : {}) });
102
+
103
+ /** A check worded from the catalogue: its English message and fix, and the parts the screen words in any language. */
104
+ function said(id , status , msg , fix , data ) {
105
+ return {
106
+ id, status, message: sayText(msg, "en"), say: msg,
107
+ ...(fix && fix.length > 0 ? { fix: sayText(fix, "en"), sayFix: fix } : {}),
108
+ ...(data !== undefined ? { data } : {}),
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
+
163
+
164
+
165
+
166
+
167
+
168
+
169
+
170
+
171
+
172
+
173
+
174
+
175
+
176
+
177
+
178
+
179
+
180
+ const MIN_NODE = [22, 18];
181
+ const LOCK_OLD_MS = 6 * 3600_000;
182
+ const DEFAULT_TIMEOUT_MS = 10_000;
183
+ /**
184
+ * Checks with their own budget: future-mtimes stats every native transcript (thousands on a large home, cold), and
185
+ * harnesses may snapshot the OpenCode db. Both degrade to a warn when they run out of time.
186
+ */
187
+ export const CHECK_TIMEOUTS_MS = { "future-mtimes": 45_000, harnesses: 30_000 };
188
+ /** The only checks whose throw or timeout is a FAIL: without them t3sm cannot run (or would import wrongly). */
189
+ const CRITICAL_CHECKS = new Set(["node-version", "state-dir", "config", "t3-runtime", "t3-reachable", "t3-version", "t3-cli", "t3-token", "instances", "instance-home-drift"]);
190
+ const HARNESS_BIN = { claude: "claude", codex: "codex", pi: "pi", opencode: "opencode" };
191
+ const HARNESS_DRIVER = { codex: "codex", pi: "pi" };
192
+
193
+ export { maskEmail };
194
+
195
+ export { pendingMtimePaths };
196
+
197
+ class CheckTimeout extends Error {}
198
+
199
+ const CLOSE_TIMEOUT_MS = 3_000;
200
+
201
+ /** Settles when `p` settles (either way) or after `ms`, whichever comes first; the timer is always cleared. */
202
+ function bounded(p , ms ) {
203
+ let timer ;
204
+ return Promise.race([p.then(() => {}, () => {}), new Promise ((r) => { timer = setTimeout(r, ms); })]).finally(() => clearTimeout(timer));
205
+ }
206
+
207
+ export async function runDoctor(deps ) {
208
+ const { home, platform } = deps;
209
+ const budgetOf = (id ) => deps.checkTimeoutsMs?.[id] ?? CHECK_TIMEOUTS_MS[id] ?? deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
210
+ const t = (p ) => tildePath(p, home, platform);
211
+ const win = platform === "win32";
212
+ const openT3 = [part(win ? "doctor.fix.openT3.win" : "doctor.fix.openT3.other")];
213
+ const slowFix = [part("doctor.fix.slow")];
214
+ const checks = [];
215
+
216
+ /** `onTimeout` (optional) builds the check's own result when its budget runs out (e.g. how far a walk got). */
217
+ async function run(id , fn , onTimeout ) {
218
+ const budget = budgetOf(id);
219
+ let timer ;
220
+ try {
221
+ const r = await Promise.race([
222
+ fn(),
223
+ new Promise ((_, rej) => { timer = setTimeout(() => rej(new CheckTimeout()), budget); }),
224
+ ]);
225
+ checks.push(...(Array.isArray(r) ? r : [r]));
226
+ } catch (e) {
227
+ if (e instanceof CheckTimeout && onTimeout) { checks.push(onTimeout(budget)); return; }
228
+ const s = budget / 1000;
229
+ const msg = e instanceof CheckTimeout ? [part("doctor.say.timeout", { s })] : [part("doctor.say.error", { error: oneLine(describeError(e).message.replace(/^Unexpected error: /, "")) })];
230
+ if (CRITICAL_CHECKS.has(id)) checks.push(said(id, "fail", msg));
231
+ else if (e instanceof CheckTimeout) checks.push(said(id, "warn", [part("doctor.say.timeoutWarn", { s })], slowFix));
232
+ else checks.push(said(id, "warn", msg));
233
+ } finally {
234
+ clearTimeout(timer);
235
+ }
236
+ }
237
+ const ok = (id , ...msg ) => said(id, "ok", msg);
238
+ const skip = (id , ...msg ) => said(id, "skip", msg);
239
+ const needsT3 = (id ) => skip(id, part("doctor.say.needsT3"));
240
+ const needs = (id , check ) => skip(id, part("doctor.say.needs", { check }));
241
+
242
+ // ---------- this machine ----------
243
+ await run("node-version", async () => {
244
+ const [maj = 0, min = 0] = deps.nodeVersion.split(".").map(Number);
245
+ const good = maj > MIN_NODE[0] || (maj === MIN_NODE[0] && min >= MIN_NODE[1]);
246
+ return good ? ok("node-version", part("doctor.say.nodeVersion.ok", { version: deps.nodeVersion }))
247
+ : said("node-version", "fail", [part("doctor.say.nodeVersion.old", { version: deps.nodeVersion, min: MIN_NODE.join(".") })], [part("doctor.fix.nodeVersion")]);
248
+ });
249
+
250
+ await run("state-dir", async () => {
251
+ const why = await deps.stateWritable();
252
+ return why === null ? ok("state-dir", part("doctor.say.stateDir.ok", { dir: t(deps.stateDir) }))
253
+ : said("state-dir", "fail", [part("doctor.say.stateDir.fail", { dir: t(deps.stateDir), why })], [part("doctor.fix.stateDir")]);
254
+ });
255
+
256
+ let config = null;
257
+ let configValid = true;
258
+ await run("config", async () => {
259
+ try {
260
+ config = await deps.loadConfig();
261
+ } catch (e) {
262
+ configValid = false;
263
+ if (e instanceof ConfigError) {
264
+ return said("config", "fail", [part("doctor.say.config.invalid", { error: oneLine(e.message.split("\n").slice(0, 2).join(" ")) })], [part("doctor.fix.config")]);
265
+ }
266
+ throw e;
267
+ }
268
+ if (config === null) return ok("config", part("doctor.say.config.none"));
269
+ const c = config ;
270
+ return ok("config", part("doctor.say.config.ok", { n: c.accounts.length, ids: c.accounts.map((a) => a.id).join(", "), default: c.defaultAccount }));
271
+ });
272
+ let accounts = [];
273
+ try { accounts = config !== null ? (config ).accounts : configValid ? await deps.detectAccounts() : []; } catch { accounts = []; }
274
+ const expanded = accounts.map((a) => ({ ...a, home: expandHome(a.home, home) }));
275
+ const effective = config ?? defaultConfig(expanded);
276
+
277
+ await run("lock", async () => {
278
+ const info = await deps.lockInfo();
279
+ if (info === null) return ok("lock", part("doctor.say.lock.free"));
280
+ const file = t(join(deps.stateDir, "lock"));
281
+ if (info.hostname !== (deps.hostname ?? hostname())) {
282
+ // A shared state folder: the pid means nothing here, and t3sm never takes over another machine's lock.
283
+ const what = part("doctor.say.lock.otherMachine", { pid: info.pid, ageMs: info.ageMs });
284
+ return info.ageMs > LOCK_OLD_MS ? said("lock", "warn", [what], [part("doctor.fix.lock.otherMachine", { file })]) : ok("lock", what);
285
+ }
286
+ if (rebootedSince(info.uptimeSec, (deps.uptime ?? uptime)())) return ok("lock", part("doctor.say.lock.rebooted"));
287
+ const alive = deps.pidAlive(info.pid);
288
+ if (!alive) return ok("lock", part("doctor.say.lock.gone", { pid: info.pid }));
289
+ if (info.ageMs > LOCK_OLD_MS) return said("lock", "warn", [part("doctor.say.lock.old", { ageMs: info.ageMs, pid: info.pid })], [part("doctor.fix.lock.old", { file })]);
290
+ return ok("lock", part("doctor.say.lock.held", { pid: info.pid, ageMs: info.ageMs }));
291
+ });
292
+
293
+ let journal = [];
294
+ await run("pending-mtimes", async () => {
295
+ journal = await deps.readJournal();
296
+ const pending = pendingMtimePaths(journal, platform);
297
+ if (pending.length === 0) return ok("pending-mtimes", part("doctor.say.pendingMtimes.none"));
298
+ const what = part("doctor.say.pendingMtimes.left", { n: pending.length });
299
+ if (!deps.repair) return said("pending-mtimes", "warn", [what], [part("doctor.fix.pendingMtimes")]);
300
+ const r = await deps.repairMtimes();
301
+ if (r === null) return said("pending-mtimes", "warn", [what, part("doctor.say.pendingMtimes.busy")], [part("doctor.fix.pendingMtimes.busy")]);
302
+ const parts = [part("doctor.say.pendingMtimes.restored", { n: r.restored.length })];
303
+ if (r.missing.length) parts.push(part("doctor.say.pendingMtimes.gone", { n: r.missing.length }, ", "));
304
+ if (r.skippedModified.length) parts.push(part("doctor.say.pendingMtimes.edited", { n: r.skippedModified.length }, ", "));
305
+ if (r.failed.length) {
306
+ parts.push(part("doctor.say.pendingMtimes.failed", { n: r.failed.length, error: r.failed[0] .error }, ", "));
307
+ return said("pending-mtimes", "warn", parts, [part("doctor.fix.pendingMtimes.failed")]);
308
+ }
309
+ return said("pending-mtimes", "ok", parts);
310
+ });
311
+
312
+ {
313
+ // Streamed: only files already ahead are kept. At its budget the walk is stopped and the check reports how far it got.
314
+ let checked = 0;
315
+ let stop = false;
316
+ const ahead = [];
317
+ const leftovers = () => futureLeftovers(ahead, journal, deps.now(), platform);
318
+ const list = (paths ) => `${paths.slice(0, 3).map((p) => t(p)).join(", ")}${paths.length > 3 ? ", ..." : ""}`;
319
+ const fix = [part("doctor.fix.futureMtimes")];
320
+ await run("future-mtimes", async () => {
321
+ if (!deps.futureMtimes) return ok("future-mtimes", part("doctor.say.futureMtimes.unchecked"));
322
+ const src = deps.futureMtimes(effective);
323
+ const horizon = deps.now() + ACTIVE_WINDOW_MS;
324
+ for await (const f of src instanceof Promise ? await src : src) {
325
+ if (stop) break;
326
+ checked++;
327
+ if (f.mtimeMs > horizon) ahead.push(f);
328
+ }
329
+ const found = leftovers();
330
+ if (found.length === 0) return ok("future-mtimes", part("doctor.say.futureMtimes.none", { n: checked }));
331
+ return said("future-mtimes", "warn", [part("doctor.say.futureMtimes.found", { n: found.length, list: list(found) })], fix);
332
+ }, (ms) => {
333
+ stop = true;
334
+ const found = leftovers();
335
+ const sofar = found.length === 0 ? part("doctor.say.futureMtimes.timeoutNone") : part("doctor.say.futureMtimes.timeoutSome", { n: found.length, list: list(found) });
336
+ return said("future-mtimes", "warn", [part("doctor.say.futureMtimes.timeout", { s: ms / 1000, n: checked }), sofar], found.length === 0 ? slowFix : fix);
337
+ });
338
+ }
339
+
340
+ await run("claude-env", async () => {
341
+ const v = deps.env["CLAUDE_CONFIG_DIR"];
342
+ if (!v) return ok("claude-env", part("doctor.say.claudeEnv.unset"));
343
+ return said("claude-env", "warn", [part("doctor.say.claudeEnv.set", { dir: t(v) })], [part(win ? "doctor.fix.claudeEnv.win" : "doctor.fix.claudeEnv.other")]);
344
+ });
345
+
346
+ // ---------- T3 Code ----------
347
+ let rt = null;
348
+ let reachable = false;
349
+ await run("t3-runtime", async () => {
350
+ rt = await deps.readRuntime();
351
+ if (rt === null) return said("t3-runtime", "fail", [part("doctor.say.t3Runtime.none")], openT3);
352
+ return ok("t3-runtime", part("doctor.say.t3Runtime.ok", { version: rt.serverVersion, origin: rt.origin }));
353
+ });
354
+ await run("t3-reachable", async () => {
355
+ if (rt === null) return needs("t3-reachable", "t3-runtime");
356
+ reachable = await deps.probe(rt);
357
+ const origin = (rt ).origin;
358
+ return reachable ? ok("t3-reachable", part("doctor.say.t3Reachable.ok", { origin }))
359
+ : said("t3-reachable", "fail", [part("doctor.say.t3Reachable.fail", { origin })], openT3);
360
+ });
361
+ await run("t3-version", async () => {
362
+ if (!reachable || rt === null) return needsT3("t3-version");
363
+ const v = (rt ).serverVersion;
364
+ // Same minor or not, an untested version warns with one wording (as compatGate does when a command connects).
365
+ if (checkCompat(v) === "tested") return ok("t3-version", part("doctor.say.t3Version.tested", { version: v }));
366
+ return said("t3-version", "warn", [part("doctor.say.t3Version.untested", { version: v, tested: TESTED_VERSIONS.join(", ") })], [part("doctor.fix.t3Version")]);
367
+ });
368
+ let cli = null;
369
+ await run("t3-cli", async () => {
370
+ cli = deps.resolveCli();
371
+ return cli !== null ? ok("t3-cli", part("doctor.say.t3Cli.ok", { path: t(cli) }))
372
+ : said("t3-cli", "fail", [part("doctor.say.t3Cli.missing")], [part("doctor.fix.t3Cli")]);
373
+ });
374
+
375
+ // ---- the one T3 session: revoked when the T3 checks end, or on Ctrl+C / SIGTERM (bounded), never awaited unboundedly.
376
+ let connecting = null;
377
+ let api = null;
378
+ let closing = null;
379
+ const closeBudget = deps.closeTimeoutMs ?? CLOSE_TIMEOUT_MS;
380
+ /** wait=true (signal): give a pending connect the close budget too. wait=false (normal end): a pending connect is closed whenever it arrives. */
381
+ const closeSession = (wait ) => {
382
+ if (closing) return closing;
383
+ const open = api ;
384
+ const pending = connecting ;
385
+ if (open !== null) closing = bounded(open.close(), closeBudget);
386
+ else if (pending !== null && wait) closing = bounded(pending.then((a) => a.close()), closeBudget);
387
+ else if (pending !== null) { void pending.then((a) => a.close(), () => {}); closing = Promise.resolve(); }
388
+ else closing = Promise.resolve();
389
+ return closing;
390
+ };
391
+ const signals = deps.signals ?? (process );
392
+ const exit = deps.exit ?? ((code ) => process.exit(code));
393
+ let listening = false;
394
+ const onSignal = () => { void closeSession(true).then(() => exit(130)); };
395
+
396
+ /** The session the API checks may use: only when t3-token reported ok (a connect landing after its timeout is not used). */
397
+ let live = null;
398
+ let instancesP = null;
399
+ let threadIdsP = null;
400
+ const instances = () => (instancesP ??= (live ).providerInstances());
401
+ const claudeInstances = async () => (await instances()).filter((i) => i.driver === "claudeAgent");
402
+ const needApi = (id ) => (reachable ? needs(id, "t3-token") : needsT3(id));
403
+
404
+ try {
405
+ await run("t3-token", async () => {
406
+ if (!reachable) return needsT3("t3-token");
407
+ if (cli === null) return needs("t3-token", "t3-cli");
408
+ for (const s of STOP_SIGNALS) signals.once(s, onSignal);
409
+ listening = true;
410
+ connecting = deps.connect();
411
+ const a = await connecting;
412
+ api = a;
413
+ return ok("t3-token", part("doctor.say.t3Token.ok"));
414
+ });
415
+ if (checks.at(-1)?.id === "t3-token" && checks.at(-1)?.status === "ok") live = api;
416
+ // The session ids T3 holds (read-only; for harness:codex's "already in T3"), fetched while the session is open.
417
+ if (live !== null && typeof (live ).listThreads === "function") {
418
+ threadIdsP = (live ).listThreads().then((ts) => sessionIdsInT3(ts), () => null);
419
+ }
420
+
421
+ await run("instances", async () => {
422
+ if (live === null) return needApi("instances");
423
+ const list = await claudeInstances();
424
+ const problems = [];
425
+ const seen = new Map ();
426
+ for (const i of list) {
427
+ if (i.homePath === null) continue;
428
+ const k = normalizeCwd(i.homePath, platform).toLowerCase();
429
+ seen.set(k, [...(seen.get(k) ?? []), i.instanceId]);
430
+ }
431
+ for (const [, ids] of seen) {
432
+ if (ids.length < 2) continue;
433
+ const h = list.find((i) => i.instanceId === ids[0]) .homePath ;
434
+ problems.push(part("doctor.say.instances.shared", { ids: ids.slice(0, -1).join(", "), last: ids.at(-1) , home: t(h) }, problems.length > 0 ? "; " : undefined));
435
+ }
436
+ if (problems.length) return said("instances", "fail", problems, [part("doctor.fix.instances.shared")]);
437
+ const missing = expanded.filter((a) => !list.some((i) => i.homePath !== null && sameCwd(i.homePath, a.home, platform)));
438
+ if (missing.length) {
439
+ return said("instances", "warn", [part("doctor.say.instances.missing", { list: missing.map((a) => `${a.id} (${t(a.home)})`).join(", ") })], [part("doctor.fix.instances.missing")]);
440
+ }
441
+ return ok("instances", part("doctor.say.instances.ok", { n: expanded.length }));
442
+ });
443
+
444
+ await run("instance-home-drift", async () => {
445
+ if (live === null) return needApi("instance-home-drift");
446
+ const def = (await claudeInstances()).find((i) => i.instanceId === "claudeAgent");
447
+ if (!def) return ok("instance-home-drift", part("doctor.say.defaultInstance.none"));
448
+ if (def.homePath === null) return ok("instance-home-drift", part("doctor.say.homeDrift.unreported"));
449
+ if (sameCwd(def.homePath, `${home}/.claude`, platform)) return ok("instance-home-drift", part("doctor.say.homeDrift.ok"));
450
+ if (Object.hasOwn((await (live ).getConfig()).settings.providerInstances, "claudeAgent")) {
451
+ return said("instance-home-drift", "fail", [part("doctor.say.homeDrift.configured", { home: t(def.homePath) })], [part("doctor.fix.homeDrift.configured")]);
452
+ }
453
+ return said("instance-home-drift", "fail", [part("doctor.say.homeDrift.shell", { home: t(def.homePath) })], [part(win ? "doctor.fix.homeDrift.win" : "doctor.fix.homeDrift.other")]);
454
+ });
455
+
456
+ await run("instance-unpinned", async () => {
457
+ if (live === null) return needApi("instance-unpinned");
458
+ const def = (await claudeInstances()).find((i) => i.instanceId === "claudeAgent");
459
+ if (!def) return ok("instance-unpinned", part("doctor.say.defaultInstance.none"));
460
+ const explicit = Object.hasOwn((await (live ).getConfig()).settings.providerInstances, "claudeAgent");
461
+ if (explicit) return ok("instance-unpinned", part("doctor.say.unpinned.ok"));
462
+ return said("instance-unpinned", "warn", [part("doctor.say.unpinned.warn")], [part("doctor.fix.unpinned")]);
463
+ });
464
+
465
+ await run("instance-accounts", async () => {
466
+ if (live === null) return needApi("instance-accounts");
467
+ const list = await claudeInstances();
468
+ if (list.length === 0) return said("instance-accounts", "warn", [part("doctor.say.instanceAccounts.none")], [part("doctor.fix.instanceAccounts.none")]);
469
+ const issues = [];
470
+ const fixes = [];
471
+ // Each account by its name (config.json's display name, else T3 Code's), never a bare id when it has one.
472
+ const baseName = (i ) =>
473
+ shownAccountName(effective.accounts.find((a) => a.id === i.instanceId)?.displayName || i.displayName || i.instanceId);
474
+ // Two accounts with the same name are told apart by their id.
475
+ const nameCount = new Map ();
476
+ for (const i of list) nameCount.set(baseName(i), (nameCount.get(baseName(i)) ?? 0) + 1);
477
+ const nameOf = (i ) => {
478
+ const n = baseName(i);
479
+ return (nameCount.get(n) ?? 0) > 1 && n !== i.instanceId ? `${n} (${shownText(i.instanceId, 40)})` : n;
480
+ };
481
+ const byEmail = new Map ();
482
+ for (const i of list) if (i.email) byEmail.set(i.email.toLowerCase(), [...(byEmail.get(i.email.toLowerCase()) ?? []), nameOf(i)]);
483
+ const sep = () => (issues.length > 0 ? "; " : undefined);
484
+ for (const [email, ids] of byEmail) {
485
+ if (ids.length < 2) continue;
486
+ issues.push(part("doctor.say.instanceAccounts.shared", { ids: ids.join(" and "), email: maskEmail(email) }, sep()));
487
+ fixes.push("doctor.fix.instanceAccounts.shared");
488
+ }
489
+ for (const i of list) {
490
+ if (i.authStatus === "unauthenticated") { issues.push(part("doctor.say.instanceAccounts.signedOut", { id: nameOf(i) }, sep())); fixes.push("doctor.fix.instanceAccounts.signedOut"); }
491
+ else if (i.availability === "unavailable") { issues.push(part("doctor.say.instanceAccounts.unavailable", { id: nameOf(i) }, sep())); fixes.push("doctor.fix.instanceAccounts.unavailable"); }
492
+ }
493
+ const summary = list.map((i, n) => part(
494
+ i.email ? "doctor.say.instanceAccounts.email" : i.authStatus === "unauthenticated" ? "doctor.say.instanceAccounts.signedOutShort" : "doctor.say.instanceAccounts.noEmail",
495
+ { id: nameOf(i), ...(i.email ? { email: maskEmail(i.email) } : {}) }, n > 0 ? ", " : undefined,
496
+ ));
497
+ if (issues.length) {
498
+ const fix = [...new Set(fixes)].map((k, n) => ({ ...part(k, undefined, n > 0 ? "; " : undefined), ...(n === 0 ? { cap: true } : {}) }));
499
+ return said("instance-accounts", "warn", [...issues, part("doctor.say.instanceAccounts.summary", { summary })], fix);
500
+ }
501
+ return said("instance-accounts", "ok", summary);
502
+ });
503
+ } finally {
504
+ // Revoke the session as soon as T3 is no longer needed: an open one within closeTimeoutMs; a connect that outlived
505
+ // its timeout is closed whenever it arrives (never awaited here, so a connect that never settles cannot hang doctor).
506
+ await closeSession(false);
507
+ if (listening) for (const s of STOP_SIGNALS) signals.off(s, onSignal);
508
+ }
509
+
510
+ // ---------- accounts on disk ----------
511
+ await run("accounts-undiscovered", async () => {
512
+ const instHomes = instancesP ? (await (instancesP ).catch(() => [] )).filter((i) => i.driver === "claudeAgent" && i.homePath !== null).map((i) => i.homePath ) : [];
513
+ const found = await deps.discover(instHomes);
514
+ const missing = found.filter((f) => !expanded.some((a) => sameCwd(a.home, f.home, platform)));
515
+ if (missing.length === 0) return ok("accounts-undiscovered", part(config ? "doctor.say.undiscovered.ok" : "doctor.say.undiscovered.okDetected", { n: found.length }));
516
+ const list = missing.map((f) => `${t(f.home)} (${formatSources(f)})`).join(", ");
517
+ return said("accounts-undiscovered", "warn", [part(config ? "doctor.say.undiscovered.missing" : "doctor.say.undiscovered.missingDetected", { list, n: missing.length })],
518
+ [part(config ? "doctor.fix.undiscovered" : "doctor.fix.undiscovered.init")]);
519
+ });
520
+
521
+ await run("backups-present", async () => {
522
+ const per = [];
523
+ let n = 0;
524
+ for (const a of expanded) {
525
+ const dirs = await deps.findBackupDirs(a.home);
526
+ if (dirs.length) { n += dirs.length; per.push(`${t(a.home)}: ${dirs.length}`); }
527
+ }
528
+ if (n === 0) return ok("backups-present", part("doctor.say.backups.none"));
529
+ return said("backups-present", "warn", [part("doctor.say.backups.found", { n, per: per.join(", ") })], [part("doctor.fix.backups")]);
530
+ });
531
+
532
+ await run("quarantine-orphans", async () => {
533
+ const items = await deps.findOrphanedQuarantine(expanded, journal);
534
+ if (items.length === 0) return ok("quarantine-orphans", part("doctor.say.quarantine.ok"));
535
+ const homes = [...new Set(items.map((i) => t(i.accountHome)))];
536
+ return said("quarantine-orphans", "warn", [part("doctor.say.quarantine.orphans", { n: items.length, dirs: homes.map((h) => `${h}/${QUARANTINE_DIR}`).join(", ") })], [part("doctor.fix.quarantine")]);
537
+ });
538
+
539
+ // ---------- harnesses ----------
540
+ let harnessList = [];
541
+ await run("harnesses", async () => { harnessList = await deps.harnesses(effective); return []; });
542
+ const providerDrivers = instancesP ? (await (instancesP ).catch(() => null)) : null;
543
+ for (const h of harnessList) {
544
+ const id = `harness:${h.id}`;
545
+ await run(id, async () => {
546
+ const bin = deps.findBin(HARNESS_BIN[h.id]);
547
+ const version = bin !== null ? await deps.binVersion(bin) : null;
548
+ const name = HARNESS_BIN[h.id];
549
+ const versionText = version ? (version.toLowerCase().startsWith(name) ? version : `${name} ${version}`) : null;
550
+ const ver = versionText !== null ? [part("doctor.say.harness.version", { version: versionText })] : bin !== null ? [part("doctor.say.harness.onPath", { name })] : [];
551
+ const counted0 = h.importable !== undefined && h.convertible !== undefined;
552
+ const sessions = counted0 ? h.importable + h.convertible : h.available ? null : 0;
553
+ const data = (noInstance ) => ({ harness: h.id, sessions, readErrors: h.readErrors ?? 0, noInstance });
554
+ if (h.problem) {
555
+ return said(id, "warn", [part("doctor.say.harness.problem", { problem: h.problem }), ...ver, part("doctor.say.harness.notConverted")], [part("doctor.fix.harness.problem", { name })], data(false));
556
+ }
557
+ if (!h.available) return said(id, "ok", [part("doctor.say.harness.none"), ...ver], undefined, data(false));
558
+ // Codex: sessions by how they reach T3 (native import, conversion of compressed rollouts, skipped).
559
+ const counted = h.importable !== undefined && h.convertible !== undefined && h.skipped !== undefined;
560
+ const readErrors = h.readErrors ?? 0;
561
+ const inT3 = counted && h.sessionIds && threadIdsP ? await (threadIdsP ) : null;
562
+ const already = inT3 ? (h.sessionIds ?? []).filter((x) => sessionForms(h.id, x).some((f) => inT3.has(f))).length : null;
563
+ const counts = counted
564
+ ? [
565
+ versionText !== null ? part("doctor.say.harness.countsVersion", { version: versionText }) : bin !== null ? part("doctor.say.harness.countsOnPath", { name }) : part("doctor.say.harness.countsFound"),
566
+ part("doctor.say.harness.counts", { importable: h.importable , convertible: h.convertible , skipped: h.skipped }),
567
+ ...(readErrors > 0 ? [part("doctor.say.harness.readErrors", { n: readErrors })] : []),
568
+ ...(already !== null ? [part("doctor.say.harness.already", { n: already })] : []),
569
+ ]
570
+ : null;
571
+ const driver = HARNESS_DRIVER[h.id];
572
+ // Converted sessions become Claude threads: only native imports need the harness's own T3 instance.
573
+ const needsDriver = !counted || (h.importable ?? 0) > 0;
574
+ const noDriver = driver !== undefined && needsDriver && providerDrivers !== null && !providerDrivers.some((p) => p.driver === driver && p.enabled);
575
+ const enableFix = part("doctor.fix.harness.enable", { agent: driver === "codex" ? "Codex" : "Pi" });
576
+ if (noDriver && counts === null) return said(id, "warn", [part("doctor.say.harness.noDriver", { driver: driver })], [enableFix], data(true));
577
+ if (counts !== null && (noDriver || readErrors > 0)) {
578
+ // Every problem is reported: one warn, messages and fixes combined.
579
+ const fixes = [
580
+ ...(noDriver ? [enableFix] : []),
581
+ ...(readErrors > 0 ? [part("doctor.fix.harness.readErrors", undefined, noDriver ? ". " : undefined)] : []),
582
+ ];
583
+ const message = noDriver ? [...counts, part("doctor.say.harness.noDriverCounts", { driver: driver , n: h.importable })] : counts;
584
+ return said(id, "warn", message, fixes, data(noDriver));
585
+ }
586
+ const unchecked = driver && providerDrivers === null ? [part("doctor.say.harness.unchecked")] : [];
587
+ return said(id, "ok", counts !== null ? [...counts, ...unchecked] : [part("doctor.say.harness.found"), ...ver, ...unchecked], undefined, data(false));
588
+ });
589
+ }
590
+
591
+ // ---------- the /t3sm commands inside T3 Code ----------
592
+ await run("t3sm-plugin", async () => {
593
+ const read = deps.pluginState, version = deps.packageVersion;
594
+ if (!read || !version) return skip("t3sm-plugin", part("doctor.say.plugin.unchecked"));
595
+ const states = await Promise.all(effective.accounts.map(async (a) => ({ id: shownAccountName(a.displayName || a.id), state: await read(expandHome(a.home, home)) })));
596
+ if (states.length === 0) return skip("t3sm-plugin", part("doctor.say.plugin.noAccounts"));
597
+ const stateWords = (s ) => s.state === "installed" ? part("status.plugin.installed", { version: s.version })
598
+ : s.state === "outdated" ? part("status.plugin.outdated", { version: s.version, expected: version, id: PLUGIN_ID }) : part("status.plugin.missing");
599
+ const line = states.map((x, n) => part("doctor.say.plugin.account", { id: x.id, state: [stateWords(x.state)] }, n > 0 ? "; " : undefined));
600
+ if (states.some((x) => x.state.state === "outdated")) return said("t3sm-plugin", "warn", line, [part("doctor.fix.plugin", { id: PLUGIN_ID })]);
601
+ const missing = states.some((x) => x.state.state === "missing");
602
+ return said("t3sm-plugin", "ok", missing ? [...line, part("doctor.say.plugin.optional")] : line);
603
+ });
604
+
605
+ // ---------- background sync ----------
606
+ await run("schedule", async () => {
607
+ const s = await deps.scheduleStatus();
608
+ if (!s.installed) return ok("schedule", part("doctor.say.schedule.none"));
609
+ if (s.missing && s.missing.length > 0) {
610
+ return said("schedule", "warn", [part("doctor.say.schedule.missing", { kind: s.kind, paths: s.missing.map(t).join(", "), n: s.missing.length })], [part("doctor.fix.schedule")]);
611
+ }
612
+ return said("schedule", "ok", [
613
+ part("doctor.say.schedule.ok", { kind: s.kind }),
614
+ ...(s.nextRun ? [part("doctor.say.schedule.next", { next: s.nextRun })] : []),
615
+ ...(s.detail && s.kind !== "cron" ? [part("doctor.say.schedule.detail", { detail: s.detail })] : []),
616
+ ]);
617
+ });
618
+
619
+ await run("sync-watcher", async () => {
620
+ const hb = await deps.readHeartbeat();
621
+ const now = deps.now();
622
+ // The same classification as `t3sm status` (src/ops/watcherHealth.ts): the two never disagree.
623
+ const h = watcherHealth(hb, { now, pidAlive: deps.pidAlive, install: (r) => deps.installStamp?.(r) ?? null, everyMinutes: effective.schedule.everyMinutes });
624
+ const watcherFix = [part("doctor.fix.watcher.start")];
625
+ if (h.state === "none") return ok("sync-watcher", part("doctor.say.watcher.none"));
626
+ if (h.state === "stopped") return ok("sync-watcher", part("doctor.say.watcher.stopped", { at: h.stoppedAt }));
627
+ const restartFix = [part("doctor.fix.watcher.restart", { pid: h.pid })];
628
+ if (h.state === "restart-lost") return said("sync-watcher", "warn", [part("doctor.say.watcher.restartLost", { at: h.stoppedAt })], [part("doctor.fix.watcher.restartLost")]);
629
+ if (h.state === "gone") return said("sync-watcher", "warn", [part("doctor.say.watcher.gone", { pid: h.pid, last: h.lastCycleAt ?? [part("doctor.say.watcher.never")] })], watcherFix);
630
+ if (h.state === "no-version") return said("sync-watcher", "warn", [part("doctor.say.watcher.noVersion", { pid: h.pid })], restartFix);
631
+ if (h.state === "no-stamp") return said("sync-watcher", "warn", [part("doctor.say.watcher.noStamp", { pid: h.pid, version: h.version })], restartFix);
632
+ if (h.state === "stale-version") {
633
+ return said("sync-watcher", "warn", [part(h.rebuilt ? "doctor.say.watcher.staleRebuilt" : "doctor.say.watcher.stale", { pid: h.pid, version: h.version, installed: h.installed })], restartFix);
634
+ }
635
+ const pending = h.pendingVersion !== null ? [part("doctor.say.watcher.pending", { version: h.pendingVersion })] : [];
636
+ const last = [h.lastCycleAt ? part("doctor.say.watcher.lastCycle", { ageMs: now - Date.parse(h.lastCycleAt) }) : part("doctor.say.watcher.noCycle")];
637
+ if (h.fresh) return said("sync-watcher", "ok", [part("doctor.say.watcher.running", { pid: h.pid, last }), ...pending]);
638
+ if (!reachable) return said("sync-watcher", "ok", [part("doctor.say.watcher.running", { pid: h.pid, last }), part("doctor.say.watcher.waitingT3"), ...pending]);
639
+ return said("sync-watcher", "warn", [part("doctor.say.watcher.late", { pid: h.pid, last, due: h.nextCycleAt ?? "-" })], [part("doctor.fix.watcher.late", { pid: h.pid })]);
640
+ });
641
+
642
+ await run("merge-pending", async () => {
643
+ const p = deps.mergePending ? await deps.mergePending() : null;
644
+ if (p === null) return ok("merge-pending", part("doctor.say.merge.uncounted"));
645
+ const data = { continued: p.count, sideBranch: p.orphaned, at: p.at };
646
+ if (p.count === 0 && p.orphaned === 0) return said("merge-pending", "ok", [part("doctor.say.merge.none", { at: p.at })], undefined, data);
647
+ const parts = [
648
+ ...(p.count > 0 ? [part("doctor.say.merge.continued", { n: p.count })] : []),
649
+ ...(p.orphaned > 0 ? [part("doctor.say.merge.sideBranch", { n: p.orphaned }, p.count > 0 ? "; " : undefined)] : []),
650
+ part("doctor.say.merge.asOf", { at: p.at }),
651
+ ];
652
+ return said("merge-pending", "warn", parts, [part(p.count > 0 ? "doctor.fix.merge.continued" : "doctor.fix.merge.sideBranch")], data);
653
+ });
654
+
655
+ return { checks: checks.map((c) => scrub(c, home)) };
656
+ }
657
+
658
+ /** Last line of defence: emails masked, the home folder shown as ~, tokens redacted. */
659
+ function scrub(c , home ) {
660
+ const h = home.replace(/[\\/]+$/, "");
661
+ const variants = [...new Set([h, h.replace(/\\/g, "/"), h.replace(/\//g, "\\")])].map((v) => v.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
662
+ const re = new RegExp(`(?:${variants.join("|")})(?=[\\\\/]|\\b|$)`, "gi");
663
+ // Control and format characters go first, so an invisible character inside an address cannot hide it from the mask.
664
+ const clean = (s ) => redact(maskEmailsIn(s.replace(/[\p{Cc}\p{Cf}]/gu, (c) => (c === "\n" ? c : "")))).replace(re, "~");
665
+ // The screen's wording carries the same values: cleaned the same way.
666
+ const cleanParts = (ps ) => ps.map((x) => ({
667
+ ...x, ...(x.vars ? { vars: Object.fromEntries(Object.entries(x.vars).map(([k, v]) => [k, typeof v === "string" ? clean(v) : Array.isArray(v) ? cleanParts(v) : v])) } : {}),
668
+ }));
669
+ const out = { id: c.id, status: c.status, message: clean(c.message) };
670
+ if (c.fix !== undefined) out.fix = clean(c.fix);
671
+ if (c.data !== undefined) out.data = c.data;
672
+ if (c.say !== undefined) out.say = cleanParts(c.say);
673
+ if (c.sayFix !== undefined) out.sayFix = cleanParts(c.sayFix);
674
+ return out;
675
+ }
676
+
677
+ // ---------- real dependencies ----------
678
+
679
+ function findOnPath(name , platform , pathEnv , pathExt ) {
680
+ const win = platform === "win32";
681
+ const exts = win ? (pathExt ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean) : [""];
682
+ for (const dir of pathEnv.split(win ? ";" : ":").filter(Boolean)) {
683
+ for (const ext of exts) {
684
+ const p = join(dir, name + ext.toLowerCase());
685
+ if (isFile(p)) return p;
686
+ }
687
+ }
688
+ return null;
689
+ }
690
+
691
+ function isFile(p ) {
692
+ try { return statSync(p).isFile(); } catch { return false; }
693
+ }
694
+
695
+ async function nearestWritable(dir ) {
696
+ let d = dir;
697
+ for (;;) {
698
+ try {
699
+ await access(d, constants.F_OK);
700
+ } catch {
701
+ const up = dirname(d);
702
+ if (up === d) return "no existing parent folder";
703
+ d = up;
704
+ continue;
705
+ }
706
+ try { await access(d, constants.W_OK); return null; } catch (e) { return (e ).code ?? "not writable"; }
707
+ }
708
+ }
709
+
710
+
711
+
712
+ export function defaultDoctorDeps(o ) {
713
+ const home = o.home ?? homedir();
714
+ const platform = o.platform ?? process.platform;
715
+ const dir = stateDirOf(o.env, home);
716
+ const journal = new Journal(join(dir, "journal.jsonl"));
717
+ const childEnv = {};
718
+ for (const [k, v] of Object.entries(process.env)) if (v !== undefined && k.toUpperCase() !== "CLAUDE_CONFIG_DIR") childEnv[k] = v;
719
+ return {
720
+ home, platform, env: o.env, stateDir: dir, nodeVersion: process.versions.node, now: Date.now, repair: o.repair,
721
+ loadConfig: () => loadConfig(dir, home, platform),
722
+ detectAccounts: () => resolveAccounts(home, [], o.env, platform),
723
+ stateWritable: () => nearestWritable(dir),
724
+ lockInfo: () => lockInfo(dir),
725
+ pidAlive,
726
+ readJournal: () => journal.readAll(),
727
+ async repairMtimes() {
728
+ const lock = await acquireLock(dir);
729
+ if (!lock) return null;
730
+ try { return await recoverPendingMtimes(journal); } finally { await lock.release(); }
731
+ },
732
+ readRuntime: () => readServerRuntime(home),
733
+ probe: (rt) => probeServer(rt),
734
+ resolveCli: () => resolveT3Cli(home, platform, process.env.PATH ?? ""),
735
+ connect: () => connectT3(home, { allowUntested: true, manageProviders: false, onNotice: () => {} }),
736
+ discover: (instanceHomes) => discoverAccountHomes(nodeDiscoveryEnv({ home, platform, env: o.env, instanceHomes })),
737
+ findBackupDirs: (h) => findBackupDirs(h),
738
+ findOrphanedQuarantine: (accs, entries) => findOrphanedQuarantine(accs, entries, platform),
739
+ async harnesses(config) {
740
+ // readOnly: doctor leaves no persistent state (an OpenCode snapshot lives in a temp dir removed at exit).
741
+ const env = { home, platform, now: Date.now, config, stateDir: dir, env: o.env, readOnly: true };
742
+ const out = [];
743
+ for (const a of allAdapters()) {
744
+ if (a.availability) {
745
+ const v = await a.availability(env).catch((e ) => ({ unreadable: e instanceof Error ? e.message : String(e) }));
746
+ if (v === "ok" || v === "absent") out.push({ id: a.id, available: v === "ok" });
747
+ else out.push({ id: a.id, available: false, problem: "drift" in v ? `storage format changed: ${v.drift}` : `present but unreadable: ${v.unreadable}` });
748
+ } else {
749
+ const available = await a.isAvailable(env).catch(() => false);
750
+ // Codex: sessions by kind (read-only discovery: the cache is read, never saved).
751
+ const counts = a.id === "codex" && available ? await countCodexSessions(env).catch(() => null) : null;
752
+ out.push({ id: a.id, available, ...(counts ?? {}) });
753
+ }
754
+ }
755
+ return out;
756
+ },
757
+ findBin: (name) => findOnPath(name, platform, process.env.PATH ?? "", process.env.PATHEXT),
758
+ async binVersion(path) {
759
+ const shell = platform === "win32" && /\.(cmd|bat)$/i.test(path);
760
+ if (shell && /["\r\n\0!%]/.test(path)) return null;
761
+ const r = await defaultRunner(path, ["--version"], { shell, timeoutMs: 8000, env: childEnv });
762
+ if (r.timedOut || r.code !== 0) return null;
763
+ const line = (r.stdout || r.stderr).replace(/\x1b\[[0-9;]*m/g, "").split(/\r?\n/).map((l) => l.trim()).find(Boolean);
764
+ return line ? line.slice(0, 80) : null;
765
+ },
766
+ async scheduleStatus() {
767
+ // Not a fresh literal: `stateDir` is newer than some SpecOptions versions (win32 needs it to name the task XML).
768
+ const opts = { home, conhost: null, stateDir: dir };
769
+ // The interval `t3sm schedule install` used: config.json's schedule.everyMinutes (default 15).
770
+ const every = (await loadConfig(dir, home, platform).catch(() => null))?.schedule.everyMinutes ?? DEFAULT_SCHEDULE_MINUTES;
771
+ const spec = scheduleSpec(platform, process.execPath, defaultBinPath(), every, opts);
772
+ return { kind: spec.kind, ...(await scheduleStatus(spec, realRunner)) };
773
+ },
774
+ readHeartbeat: () => readHeartbeat(dir),
775
+ installStamp: (root) => {
776
+ const r = root ?? installRoot();
777
+ try { return { ...installStamp(r), changedAtMs: installChangedAt(r) }; } catch { return null; }
778
+ },
779
+ packageVersion: packageVersion(),
780
+ pluginState: (h) => readPluginState(h, packageVersion()),
781
+ mergePending: () => readMergePending(dir),
782
+ async *futureMtimes(config) {
783
+ // The harnesses t3sm parks files of (native transcripts). Stat only: no transcript is opened, nothing written.
784
+ // Warm discovery caches first: a file they last saw in the future is re-checked before the walk, so a known
785
+ // leftover is reported even when the walk runs out of time on a large home.
786
+ const env = { home, platform, now: Date.now, config, stateDir: dir, env: o.env, readOnly: true };
787
+ const native = allAdapters().filter((x) => x.mode === "native");
788
+ const seen = new Set ();
789
+ const horizon = Date.now() + ACTIVE_WINDOW_MS;
790
+ for (const a of native) {
791
+ for (const c of (await a.cachedFileTimes?.(env).catch(() => [])) ?? []) {
792
+ const k = pathKey(c.path, platform);
793
+ if (c.mtimeMs <= horizon || seen.has(k)) continue;
794
+ const st = await stat(c.path).catch(() => null);
795
+ if (!st) continue;
796
+ seen.add(k);
797
+ yield { path: c.path, mtimeMs: st.mtimeMs };
798
+ }
799
+ }
800
+ for (const a of native) {
801
+ if (!a.fileTimes || !(await a.isAvailable(env).catch(() => false))) continue;
802
+ for await (const f of a.fileTimes(env)) {
803
+ const k = pathKey(f.path, platform);
804
+ if (seen.has(k)) continue;
805
+ seen.add(k);
806
+ yield f;
807
+ }
808
+ }
809
+ },
810
+ };
811
+ }