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,641 @@
1
+ // The update engine (spec §5.3 points 3-4): find the newest release of the remembered source, never downgrade, install
2
+ // it with npm, restart the watcher into it, check that it is healthy within HEALTH_MS, roll back if it is not, and
3
+ // journal every update. `t3sm update` and the watcher's daily check (Task 14) drive it.
4
+ //
5
+ // Sources: the npm registry (`npm view <name> versions --json`), GitHub (`git ls-remote --tags --refs
6
+ // https://github.com/<repo>.git`, npm as the fallback when git itself fails; with the registry, the only network calls
7
+ // t3sm makes) or a local checkout (its `vX.Y.Z` tags merged into `main`, or `master` when
8
+ // there is no `main`). Every external command goes through the injected CommandRunner as an argument array with a time
9
+ // limit (QUERY_TIMEOUT_MS, INSTALL_TIMEOUT_MS); versions are checked with parseSemver, repository slugs with REPO_RE and
10
+ // folders must be absolute before anything runs. npm and git never get CLAUDE_CONFIG_DIR and git never prompts
11
+ // (updateRunner in src/ops/update.ts). State: `<state>/update.json`, written atomically.
12
+
13
+ import { mkdtemp, readFile, rm } from "node:fs/promises";
14
+ import { tmpdir } from "node:os";
15
+ import { join } from "node:path";
16
+ import { spawn as nodeSpawn } from "node:child_process";
17
+ import { atomicWrite } from "../core/fsutil.js";
18
+ import { Journal, newRunId } from "../core/journal.js";
19
+ import { acquireLock, } from "../core/lock.js";
20
+
21
+ import { compareSemver, parseSemver } from "../core/semver.js";
22
+
23
+ import { detectConhost, installSchedule, scheduleSpec, scheduleStatus, } from "./schedule.js";
24
+ import { spawnSuccessor, } from "./successor.js";
25
+ import { readHeartbeat as realReadHeartbeat, } from "./watch.js";
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+
36
+
37
+
38
+
39
+
40
+
41
+
42
+
43
+
44
+
45
+ /** How long a new version has to write a healthy heartbeat (counted from when the restart returned) before rollback. */
46
+ export const HEALTH_MS = 120_000;
47
+ /** Time limit of a lookup (ls-remote, npm view, git tag). */
48
+ export const QUERY_TIMEOUT_MS = 60_000;
49
+ /** Time limit of a clone or an npm install. */
50
+ export const INSTALL_TIMEOUT_MS = 600_000;
51
+ const POLL_MS = 2000;
52
+ /** A heartbeat's startedAt comes from another process's clock: this much before the restart still counts. */
53
+ const START_SLACK_MS = 2000;
54
+ const UPDATE_FILE = "update.json";
55
+ /** GitHub `owner/name`: owners are letters, digits and hyphens; names add `_` and `.` (never `.` or `..` alone). */
56
+ const REPO_RE = /^[A-Za-z0-9-]+\/(?!\.\.?$)[A-Za-z0-9_.-]+$/;
57
+ /** An npm package name: lower case, optionally `@scope/`, never starting with `.`, `_` or `-` (so never an option). */
58
+ const NPM_NAME_RE = /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/;
59
+ /** npm without the extra network calls and banners nobody sees in a background install. */
60
+ const NPM_INSTALL = ["install", "-g", "--install-links", "--no-audit", "--no-fund", "--no-update-notifier"];
61
+
62
+ export class UpdateError extends Error {
63
+ name = "UpdateError";
64
+ }
65
+
66
+ // ---------- update.json ----------
67
+
68
+ const isObj = (u ) => typeof u === "object" && u !== null && !Array.isArray(u);
69
+ const strOrNull = (u ) => u === null || typeof u === "string";
70
+
71
+ function decodeSource(u ) {
72
+ if (!isObj(u)) return null;
73
+ if (u["kind"] === "npm" && typeof u["name"] === "string" && NPM_NAME_RE.test(u["name"])) return { kind: "npm", name: u["name"] };
74
+ if (u["kind"] === "github" && typeof u["repo"] === "string" && REPO_RE.test(u["repo"])) return { kind: "github", repo: u["repo"] };
75
+ if (u["kind"] === "folder" && typeof u["path"] === "string" && u["path"] !== "") return { kind: "folder", path: u["path"] };
76
+ return null;
77
+ }
78
+
79
+ function decodeState(u ) {
80
+ if (!isObj(u)) return null;
81
+ const source = decodeSource(u["source"]);
82
+ const prev = u["previous"];
83
+ if (source === null || !strOrNull(u["lastCheckAt"]) || !strOrNull(u["available"])) return null;
84
+ if (u["available"] !== null && parseSemver(u["available"] ) === null) return null;
85
+ let previous = null;
86
+ if (prev !== null) {
87
+ if (!isObj(prev) || typeof prev["version"] !== "string" || parseSemver(prev["version"]) === null || typeof prev["spec"] !== "string") return null;
88
+ previous = { version: prev["version"], spec: prev["spec"] };
89
+ }
90
+ const skip = u["skip"] ?? [];
91
+ if (!Array.isArray(skip) || !skip.every((v) => typeof v === "string" && parseSemver(v) !== null)) return null;
92
+ return { source, lastCheckAt: u["lastCheckAt"] , previous, available: u["available"] , skip: skip.map(release) };
93
+ }
94
+
95
+ /** `<state>/update.json`, or null when it is absent or not valid (strictly decoded). */
96
+ export async function readUpdateState(stateDir ) {
97
+ try { return decodeState(JSON.parse(await readFile(join(stateDir, UPDATE_FILE), "utf8"))); } catch { return null; }
98
+ }
99
+
100
+ export async function writeUpdateState(stateDir , s ) {
101
+ await atomicWrite(join(stateDir, UPDATE_FILE), JSON.stringify(s, null, 2) + "\n");
102
+ }
103
+
104
+ // ---------- versions ----------
105
+
106
+ /** Never "downgrade": an older or equal (or unreadable) latest is "none". Majors are only announced (the caller's rule). */
107
+ export function classify(installed , latest ) {
108
+ const a = parseSemver(installed);
109
+ const b = parseSemver(latest);
110
+ if (a === null || b === null || compareSemver(latest, installed) <= 0) return "none";
111
+ return b[0] !== a[0] ? "major" : b[1] !== a[1] ? "minor" : "patch";
112
+ }
113
+
114
+ /** The release version of `v`, without the `v` ("0.3.1"); throws when it is not one. */
115
+ function release(v ) {
116
+ const p = parseSemver(v);
117
+ if (p === null) throw new UpdateError(`not a release version: ${JSON.stringify(v)}`);
118
+ return p.join(".");
119
+ }
120
+
121
+ /** The newest of `versions` (release versions only, without the `v`) that is not in `skip`, or null. */
122
+ export function newestRelease(versions , skip = []) {
123
+ const skipped = new Set(skip.filter((v) => parseSemver(v) !== null).map(release));
124
+ const ok = versions.filter((v) => parseSemver(v) !== null).map(release).filter((v) => !skipped.has(v));
125
+ return ok.length === 0 ? null : ok.sort(compareSemver).at(-1) ;
126
+ }
127
+
128
+ /**
129
+ * A local absolute folder on `platform`, never one that could be read as an option. Windows: a drive path
130
+ * (`D:\code\t3sm`) only, never a network or device path (`\\server\share`, `\\?\UNC\...`, `//host/...`, `\\?\C:\...`)
131
+ * or a drive-relative one (`\code`). POSIX: a path starting with a single `/` (`//host/...` is refused too). An update
132
+ * installs and runs code from this folder, so it must be the user's own checkout on this machine. This only refuses
133
+ * network paths written out as such: a mapped network drive letter (Windows) or an NFS/SMB mount point (POSIX) looks
134
+ * local and still passes.
135
+ */
136
+ function absoluteFolder(p , platform ) {
137
+ if (/[\0\r\n]/.test(p)) return false;
138
+ return platform === "win32" ? /^[A-Za-z]:[\\/]/.test(p) : p.startsWith("/") && !p.startsWith("//");
139
+ }
140
+
141
+ /** Why `src` cannot be used on `platform` (a slug that is not owner/name, a folder that is not local and absolute), or null. */
142
+ export function sourceProblem(src , platform ) {
143
+ try { checkSource(src, platform); return null; } catch (e) { return (e ).message; }
144
+ }
145
+
146
+ function checkSource(src , platform ) {
147
+ if (src.kind === "npm" && !NPM_NAME_RE.test(src.name)) throw new UpdateError(`not an npm package name: ${JSON.stringify(src.name)}`);
148
+ if (src.kind === "github" && !REPO_RE.test(src.repo)) throw new UpdateError(`the GitHub repository must be owner/name: ${JSON.stringify(src.repo)}`);
149
+ if (src.kind === "folder" && !absoluteFolder(src.path, platform)) {
150
+ const example = platform === "win32" ? "D:\\code\\t3sm" : "/home/you/code/t3sm";
151
+ throw new UpdateError(`the update folder must be a local absolute path (such as ${example}); network folders are not accepted: ${JSON.stringify(src.path)}`);
152
+ }
153
+ }
154
+
155
+ /** `file://` URL of a local checkout (absoluteFolder) for git clone (`--depth` needs a URL, not a path); git takes it unencoded. */
156
+ function fileUrl(p , platform ) {
157
+ return platform === "win32" ? `file:///${p.replace(/\\/g, "/")}` : `file://${p}`;
158
+ }
159
+
160
+ /**
161
+ * The `vX.Y.Z` releases of `src` (without the `v`; prereleases and junk left out), or null when they cannot be looked
162
+ * up. Never throws: offline, a timeout, git or npm missing, or an unusable source all give null. GitHub asks npm (which
163
+ * only knows the newest) only when git itself failed: an answer without release tags is an empty list.
164
+ */
165
+ export async function releaseVersions(src , run , platform = process.platform) {
166
+ const attempt = async (cmd , args ) => {
167
+ try { const r = await run(cmd, args, { timeoutMs: QUERY_TIMEOUT_MS }); return r.code === 0 ? r : null; } catch { return null; }
168
+ };
169
+ const releases = (tags ) => tags.filter((t) => t.startsWith("v") && parseSemver(t) !== null).map(release);
170
+ try { checkSource(src, platform); } catch { return null; }
171
+ if (src.kind === "npm") {
172
+ // Every published version (a JSON array, or a JSON string when there is only one); E404 before the first publish.
173
+ const r = await attempt("npm", ["view", src.name, "versions", "--json"]);
174
+ if (r === null) return null;
175
+ let v ;
176
+ try { v = JSON.parse(r.stdout); } catch { return null; }
177
+ const list = typeof v === "string" ? [v] : Array.isArray(v) ? v.filter((x) => typeof x === "string") : null;
178
+ return list === null ? null : list.filter((x) => /^\d+\.\d+\.\d+$/.test(x));
179
+ }
180
+ if (src.kind === "github") {
181
+ const r = await attempt("git", ["ls-remote", "--tags", "--refs", `https://github.com/${src.repo}.git`]);
182
+ if (r !== null) return releases(r.stdout.split(/\r?\n/).map((l) => /\trefs\/tags\/(.+)$/.exec(l.trim())?.[1] ?? ""));
183
+ const v = await attempt("npm", ["view", `github:${src.repo}`, "version"]);
184
+ if (v === null) return null;
185
+ const one = v.stdout.trim().replace(/^['"]|['"]$/g, "");
186
+ return parseSemver(one) === null ? [] : [release(one)];
187
+ }
188
+ for (const branch of ["main", "master"]) {
189
+ const r = await attempt("git", ["-C", src.path, "tag", "--merged", branch, "--list", "v*"]);
190
+ if (r) return releases(r.stdout.split(/\r?\n/).map((l) => l.trim()));
191
+ }
192
+ return null;
193
+ }
194
+
195
+ /**
196
+ * The newest `vX.Y.Z` release of `src` (without the `v`), leaving out the versions in `skip` (rolled back before), or
197
+ * null when none can be found (see releaseVersions). Never throws.
198
+ */
199
+ export async function latestRelease(src , run , platform = process.platform, skip = []) {
200
+ const v = await releaseVersions(src, run, platform);
201
+ return v === null ? null : newestRelease(v, skip);
202
+ }
203
+
204
+ // ---------- installing ----------
205
+
206
+ /** The spec rollback reinstalls: `npm:<name>#v<version>`, `github:<repo>#v<version>` or `folder:<path>#v<version>`. */
207
+ export function releaseSpecOf(src , version ) {
208
+ const head = src.kind === "npm" ? `npm:${src.name}` : src.kind === "github" ? `github:${src.repo}` : `folder:${src.path}`;
209
+ return `${head}#v${release(version)}`;
210
+ }
211
+
212
+ /** The source and version of a releaseSpecOf spec, or null when it is not one. */
213
+ export function parseReleaseSpec(spec ) {
214
+ const at = spec.lastIndexOf("#v");
215
+ if (at < 0 || parseSemver(spec.slice(at + 1)) === null) return null;
216
+ const head = spec.slice(0, at);
217
+ const version = release(spec.slice(at + 1));
218
+ if (head.startsWith("npm:")) return NPM_NAME_RE.test(head.slice(4)) ? { source: { kind: "npm", name: head.slice(4) }, version } : null;
219
+ if (head.startsWith("github:")) return { source: { kind: "github", repo: head.slice(7) }, version };
220
+ if (head.startsWith("folder:") && head.length > 7) return { source: { kind: "folder", path: head.slice(7) }, version };
221
+ return null;
222
+ }
223
+
224
+ /** Temporary folders for a folder install's clone (tests inject their own). */
225
+
226
+ const realTemp = {
227
+ make: () => mkdtemp(join(tmpdir(), "t3sm-update-")),
228
+ remove: (p) => rm(p, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }),
229
+ };
230
+
231
+
232
+
233
+
234
+
235
+
236
+
237
+
238
+ function failure(tool , what , r ) {
239
+ if (r.code === 127) {
240
+ return new UpdateError(tool === "npm"
241
+ ? "npm was not found on PATH. Install Node.js (it includes npm), then try again."
242
+ : "git was not found on PATH. Install Git (https://git-scm.com), then try again.");
243
+ }
244
+ if (r.code === 124) return new UpdateError(`${what} timed out after ${Math.round(INSTALL_TIMEOUT_MS / 1000)} s (no network, a proxy that does not answer, or a credential prompt)`);
245
+ const why = (r.stderr || r.stdout).trim().split(/\r?\n/)[0] ?? "";
246
+ return new UpdateError(`${what} failed (exit ${r.code})${why ? `: ${why}` : ""}`);
247
+ }
248
+
249
+ /**
250
+ * Installs release `version` of `src` globally. GitHub: `npm install -g --install-links ... github:<repo>#v<version>`.
251
+ * Folder: `git clone --depth 1 --branch v<version> file://<path> <tmp>`, then `npm install -g --install-links ... .` run
252
+ * in the clone (npm resolves `.` against its working folder, so no path reaches npm's command line, which on Windows
253
+ * goes through a shell), and the clone is removed in finally. `--install-links` makes npm copy the package instead of
254
+ * linking to a folder that is about to be deleted. Each command has INSTALL_TIMEOUT_MS. Throws UpdateError (with the
255
+ * install hint when npm or git is missing).
256
+ */
257
+ export async function installRelease(src , version , d ) {
258
+ const v = release(version);
259
+ checkSource(src, d.platform);
260
+ const limit = { timeoutMs: INSTALL_TIMEOUT_MS };
261
+ if (src.kind === "npm") {
262
+ const r = await d.run("npm", [...NPM_INSTALL, `${src.name}@${v}`], limit);
263
+ if (r.code !== 0) throw failure("npm", "npm install", r);
264
+ return;
265
+ }
266
+ if (src.kind === "github") {
267
+ const r = await d.run("npm", [...NPM_INSTALL, `github:${src.repo}#v${v}`], limit);
268
+ if (r.code !== 0) throw failure("npm", "npm install", r);
269
+ return;
270
+ }
271
+ const tmp = d.tmp ?? realTemp;
272
+ const dir = await tmp.make();
273
+ try {
274
+ const c = await d.run("git", ["-c", "advice.detachedHead=false", "clone", "--depth", "1", "--branch", `v${v}`, "--", fileUrl(src.path, d.platform), dir], limit);
275
+ if (c.code !== 0) throw failure("git", `git clone of v${v}`, c);
276
+ const r = await d.run("npm", [...NPM_INSTALL, "."], { cwd: dir, ...limit });
277
+ if (r.code !== 0) throw failure("npm", "npm install", r);
278
+ } finally {
279
+ await tmp.remove(dir).catch(() => { /* a leftover temp folder is harmless */ });
280
+ }
281
+ }
282
+
283
+ // ---------- restarting the watcher ----------
284
+
285
+ /** Stopping and starting the background watcher around an install (tests inject a fake; watcherOps is the real one). */
286
+
287
+
288
+
289
+
290
+
291
+
292
+
293
+
294
+
295
+
296
+
297
+
298
+
299
+
300
+
301
+
302
+
303
+
304
+
305
+
306
+
307
+
308
+
309
+
310
+
311
+
312
+
313
+
314
+
315
+
316
+ /**
317
+ * The real WatcherOps. Every scheduler call has QUERY_TIMEOUT_MS (a hung schtasks.exe or launchctl must not hold the
318
+ * state lock forever). With a scheduled watcher (`sync --watch` registered with the scheduler):
319
+ * - win32: the task is re-created (`schtasks /Create`, only when reinstalling), then `schtasks /Run`, and the successor
320
+ * is spawned as well, whatever /Run said: Task Scheduler drops a /Run (exit 0, IgnoreNew) while it still counts a
321
+ * task instance as running (the stopped watcher's conhost exiting, or the automatic update's own task tree), and a
322
+ * duplicate finds the single-instance pipe taken and exits 0 (the keep-alive trigger is the safety net either way);
323
+ * - darwin: reinstalling = bootout + bootstrap of the LaunchAgent (RunAtLoad starts the new code); otherwise
324
+ * `launchctl kickstart -k gui/<uid>/dev.t3sm.sync`, and bootstrap when it is not loaded. A release that crashes at
325
+ * start is relaunched by KeepAlive about every 60 s until the rollback reinstalls the previous one, which launchd
326
+ * then runs;
327
+ * - cron: the crontab is rewritten (only when reinstalling), then the successor is spawned (@reboot waits for a reboot).
328
+ * Without one: the successor is spawned only when a watcher was running.
329
+ */
330
+ export function watcherOps(o ) {
331
+ const run = (cmd, args, op) => o.run(cmd, args, { timeoutMs: QUERY_TIMEOUT_MS, ...op });
332
+ const spec = () => scheduleSpec(o.platform, o.nodePath, o.binPath, o.everyMinutes, {
333
+ watch: true, home: o.home, uid: o.uid, conhost: o.conhost, stateDir: o.stateDir, systemRoot: o.systemRoot, userId: o.userId,
334
+ });
335
+ const successor = () => spawnSuccessor({
336
+ platform: o.platform, nodePath: o.nodePath, binPath: o.binPath, systemRoot: o.systemRoot,
337
+ conhost: o.conhost !== undefined ? o.conhost : o.platform === "win32" ? detectConhost() : null,
338
+ spawn: o.spawn ?? (nodeSpawn ),
339
+ });
340
+ return {
341
+ stop: o.stop,
342
+ async restart({ wasRunning, reinstallSchedule }) {
343
+ const s = spec();
344
+ const st = await scheduleStatus(s, run).catch(() => null);
345
+ const scheduled = st !== null && st.installed && (st.command === null || st.command.includes("--watch"));
346
+ if (!scheduled) {
347
+ if (!wasRunning) return false;
348
+ successor();
349
+ return true;
350
+ }
351
+ if (s.kind === "schtasks") {
352
+ if (reinstallSchedule) await installSchedule({ ...s, install: [s.install[0] ] }, run, o.fs);
353
+ await run(s.install[1] [0] , s.install[1] .slice(1));
354
+ successor();
355
+ return true;
356
+ }
357
+ if (s.kind === "launchd") {
358
+ if (reinstallSchedule) { await installSchedule(s, run, o.fs); return true; }
359
+ const r = await run("launchctl", ["kickstart", "-k", s.remove[0] [2] ]);
360
+ if (r.code !== 0) await installSchedule(s, run, o.fs);
361
+ return true;
362
+ }
363
+ if (reinstallSchedule) await installSchedule(s, run, o.fs);
364
+ successor();
365
+ return true;
366
+ },
367
+ };
368
+ }
369
+
370
+ // ---------- the update ----------
371
+
372
+
373
+
374
+
375
+
376
+
377
+
378
+
379
+
380
+
381
+
382
+
383
+
384
+
385
+
386
+
387
+
388
+
389
+
390
+
391
+
392
+
393
+
394
+
395
+
396
+
397
+
398
+
399
+
400
+
401
+
402
+ /** installing: npm (and git for a folder); restarting: stop and start the watcher; checking: the health wait; rolling-back. */
403
+
404
+
405
+
406
+
407
+ const message = (e ) => (e instanceof Error ? e.message : String(e)).split(/\r?\n/)[0] .slice(0, 300);
408
+
409
+ // ---------- the attempt on disk (update.pending.json) ----------
410
+
411
+ const PENDING_FILE = "update.pending.json";
412
+
413
+ /**
414
+ * An update that started installing: written (atomically) before the install, removed after its outcome is journaled.
415
+ * Still there at the next start: t3sm was killed mid-update (power loss, a killed watcher). `interrupted` is set once
416
+ * that was journaled; `previous` says what to reinstall to roll it back.
417
+ */
418
+
419
+
420
+
421
+
422
+
423
+
424
+
425
+
426
+
427
+ function decodePending(u ) {
428
+ if (!isObj(u) || typeof u["runId"] !== "string" || typeof u["startedAt"] !== "string" || typeof u["target"] !== "string" || parseSemver(u["target"]) === null) return null;
429
+ const prev = u["previous"];
430
+ const source = decodeSource(u["source"]);
431
+ if (source === null || !isObj(prev) || typeof prev["version"] !== "string" || parseSemver(prev["version"]) === null || typeof prev["spec"] !== "string") return null;
432
+ return {
433
+ runId: u["runId"], previous: { version: prev["version"], spec: prev["spec"] }, source, target: u["target"], startedAt: u["startedAt"],
434
+ ...(u["interrupted"] === true ? { interrupted: true } : {}),
435
+ };
436
+ }
437
+
438
+ /** `<state>/update.pending.json`: an update in progress, or one that was interrupted (read-only; for status). */
439
+ export async function readPendingUpdate(stateDir ) {
440
+ try { return decodePending(JSON.parse(await readFile(join(stateDir, PENDING_FILE), "utf8"))); } catch { return null; }
441
+ }
442
+
443
+ const writePending = (stateDir , p ) => atomicWrite(join(stateDir, PENDING_FILE), JSON.stringify(p, null, 2) + "\n");
444
+ const removePending = (stateDir ) => rm(join(stateDir, PENDING_FILE), { force: true }).catch(() => { /* best effort */ });
445
+
446
+ /**
447
+ * A leftover update.pending.json from an update that never journaled its outcome: journals it once as `failed` with
448
+ * error "interrupted" and keeps the record (marked `interrupted`, with `previous` for a rollback) until the next update
449
+ * replaces it. One whose outcome was journaled (t3sm died just before removing the file) is simply removed. Call it
450
+ * under the state lock (runUpdate does, before its own attempt). Returns the interrupted record, or null.
451
+ */
452
+ export async function recoverInterruptedUpdate(stateDir , journal ) {
453
+ const p = await readPendingUpdate(stateDir);
454
+ if (p === null) return null;
455
+ if (p.interrupted) return p;
456
+ const entries = await journal.readAll();
457
+ const ended = entries.some((e) => e.t === "update" && e.runId === p.runId && e.outcome !== "pending");
458
+ if (ended) { await removePending(stateDir); return null; }
459
+ await journal.append({ t: "update", runId: p.runId, from: p.previous.version, to: p.target, source: p.source, outcome: "failed", error: "interrupted" });
460
+ const marked = { ...p, interrupted: true };
461
+ await writePending(stateDir, marked).catch(() => { /* journaled; the record is only a hint */ });
462
+ return marked;
463
+ }
464
+
465
+ /**
466
+ * Installs release `target` over the installed version, in this order: lock (busy: "failed" with error "busy", the next
467
+ * check retries), report an interrupted earlier update (recoverInterruptedUpdate), journal `update` pending, record the
468
+ * attempt in update.pending.json and `previous` in update.json, install, stop the watcher, start it again
469
+ * (re-registering the scheduled watcher), then wait HEALTH_MS (from when the restart returned) for a heartbeat of
470
+ * `target` that started after the restart and has not stopped; none: reinstall `previous`, stop and start again
471
+ * ("rolled-back", and `target` goes into `skip`). Only evidence against the new version rolls it back: when the restart
472
+ * itself did not happen (the old watcher would not stop, or the scheduler call failed), a missing heartbeat says nothing
473
+ * about the release, so it stays: "installed" with that reason as `error`, no skip (status then shows the watcher's own
474
+ * state: an old one restarts itself into the install after its cycle; a stopped one is restart-lost). Then the outcome is
475
+ * journaled. A target that is not strictly newer is
476
+ * refused ("not-newer") before anything runs: never a downgrade. Once the pending entry is written, every error ends in
477
+ * a journaled outcome; update.json writes after the install are best effort (they never change what happened).
478
+ */
479
+ export async function runUpdate(target , d ) {
480
+ const asked = { from: d.installed, to: target };
481
+ if (parseSemver(target) === null || parseSemver(d.installed) === null) return { outcome: "failed", ...asked, error: "invalid-version" };
482
+ if (compareSemver(target, d.installed) <= 0) return { outcome: "failed", ...asked, error: "not-newer" };
483
+ const lock = await (d.lock ?? acquireLock)(d.stateDir);
484
+ if (!lock) return { outcome: "failed", ...asked, error: "busy" };
485
+ try {
486
+ // Read again under the lock: another update may have installed it (or something newer) while this one waited.
487
+ let from ;
488
+ try { from = d.readInstalled?.() ?? d.installed; } catch { return { outcome: "failed", ...asked, error: "invalid-version" }; }
489
+ const base = { from, to: target };
490
+ if (parseSemver(from) === null) return { outcome: "failed", ...base, error: "invalid-version" };
491
+ if (compareSemver(target, from) <= 0) return { outcome: "failed", ...base, error: "not-newer" };
492
+ const journal = d.journal ?? new Journal(join(d.stateDir, "journal.jsonl"));
493
+ await recoverInterruptedUpdate(d.stateDir, journal);
494
+ const state = await readUpdateState(d.stateDir);
495
+ const source = d.source ?? state?.source;
496
+ if (!source) return { outcome: "failed", ...base, error: "no-source" };
497
+ const runId = newRunId(new Date(d.clock.now()));
498
+ const { previous, confirmed } = previousOf(from, state, source);
499
+ let attemptOnDisk = false;
500
+ const done = async (outcome , error ) => {
501
+ await journal.append({ t: "update", runId, from, to: target, source, outcome, ...(error !== undefined ? { error } : {}) });
502
+ if (attemptOnDisk) await removePending(d.stateDir); // after the outcome: a crash in between is not "interrupted"
503
+ return { outcome, ...base, ...(error !== undefined ? { error } : {}) };
504
+ };
505
+ // The attempt on disk first, then the pending entry: a crash after the entry always leaves the record that
506
+ // recoverInterruptedUpdate reports. Nothing is installed yet, so a record that cannot be written ends here.
507
+ try {
508
+ await writePending(d.stateDir, { runId, previous, source, target: release(target), startedAt: new Date(d.clock.now()).toISOString() });
509
+ attemptOnDisk = true;
510
+ } catch (e) {
511
+ return done("failed", message(e));
512
+ }
513
+ await journal.append({ t: "update", runId, from, to: target, source, outcome: "pending" });
514
+ try {
515
+ return await update(target, d, source, state, previous, confirmed, done);
516
+ } catch (e) {
517
+ // Not expected (every step below catches its own errors), but the pending entry must never stay alone.
518
+ return done("failed", message(e));
519
+ }
520
+ } finally {
521
+ await lock.release();
522
+ }
523
+ }
524
+
525
+ const sourceKey = (s ) => (s.kind === "npm" ? s.name : s.kind === "github" ? s.repo : s.path);
526
+ const sameSource = (a , b ) => a.kind === b.kind && sourceKey(a) === sourceKey(b);
527
+
528
+ /**
529
+ * How to reinstall the installed version `from` (the rollback target), and whether that is known (`confirmed`) or a
530
+ * guess. update.json's `previous` is written only once an install went through (see update), so an update.json that
531
+ * has one remembers the source that installed `from`: confirmed. Its `previous` already naming `from` (an attempt that
532
+ * did not install) keeps its spec, but only when that spec's source is the remembered one or this update's. Without a
533
+ * `previous` (the daily check's update.json under the default source) or without update.json, nothing says how `from`
534
+ * came: the guess is this update's own source, kept only in update.pending.json, never in update.json.
535
+ */
536
+ function previousOf(from , state , source ) {
537
+ const v = release(from);
538
+ const confirmed = state !== null && state.previous !== null;
539
+ const kept = state?.previous ? parseReleaseSpec(state.previous.spec) : null;
540
+ if (state?.previous && kept !== null && release(state.previous.version) === v && (sameSource(kept.source, state.source) || sameSource(kept.source, source))) {
541
+ return { previous: { version: v, spec: state.previous.spec }, confirmed: confirmed && sameSource(kept.source, state.source) };
542
+ }
543
+ return { previous: { version: v, spec: releaseSpecOf(confirmed ? state.source : source, from) }, confirmed };
544
+ }
545
+
546
+ async function update(
547
+ target , d , source , state , previous ,
548
+ confirmed , done ,
549
+ ) {
550
+ const write = d.writeState ?? writeUpdateState;
551
+ const bestEffort = (s ) => write(d.stateDir, s).catch(() => { /* never changes the outcome */ });
552
+ const step = (s ) => { try { d.onStep?.(s); } catch { /* progress output never stops an update */ } };
553
+ // The remembered source stays until the new version is in (a new --from only applies to the new version), and so
554
+ // does a guessed `previous`: it goes into update.json only once the install went through.
555
+ const old = {
556
+ source: state?.source ?? source, lastCheckAt: state?.lastCheckAt ?? null, previous: confirmed ? previous : state?.previous ?? null,
557
+ available: state?.available ?? null, skip: state?.skip ?? [],
558
+ };
559
+
560
+ // Nothing is touched yet: a failure here (or in the install) leaves the installed version and the watcher alone.
561
+ try {
562
+ // Without an update.json no source was ever confirmed: update.json is not created until the new version is in.
563
+ if (state !== null) await write(d.stateDir, old);
564
+ step("installing");
565
+ await installRelease(source, target, d);
566
+ } catch (e) {
567
+ return done("failed", message(e)); // npm leaves the previous install in place; the watcher was not touched
568
+ }
569
+
570
+ const since = d.clock.now();
571
+ step("restarting");
572
+ const { expected, problem } = await restart(d, true);
573
+ if (expected) step("checking");
574
+ const ok = !expected || (await healthy(d, target, since, d.clock.now()));
575
+ if (ok || problem !== null) {
576
+ // A newer release clears every rolled-back version up to it.
577
+ await bestEffort({ ...old, source, previous, available: null, skip: old.skip.filter((v) => compareSemver(v, target) > 0) });
578
+ // Not healthy because the restart did not happen: nothing says the release is bad, so it is neither rolled back nor
579
+ // skipped; the reason is kept with the outcome.
580
+ return ok ? done("installed") : done("installed", `${problem}; ${release(target)} is installed and starts with the next watcher`);
581
+ }
582
+
583
+ const why = `no healthy heartbeat from ${release(target)} within ${Math.round((d.healthMs ?? HEALTH_MS) / 1000)} s`;
584
+ step("rolling-back");
585
+ try {
586
+ const p = parseReleaseSpec(previous.spec);
587
+ if (p === null) throw new UpdateError(`cannot read ${JSON.stringify(previous.spec)}`);
588
+ await installRelease(p.source, p.version, d);
589
+ } catch (e) {
590
+ // The reinstall failed: the watcher is left as it is (the new version, unhealthy, or none). Its own restart on a
591
+ // newer install, the keep-alive trigger or launchd brings one back; status reports the failed update.
592
+ return done("failed", `${why}; reinstalling ${previous.version} failed: ${message(e)}`);
593
+ }
594
+ // The previous version is not health-checked again: it is the one that ran before this update.
595
+ await restart(d, false);
596
+ // Keep the bad version out of later checks. Without an update.json, only under the caller's default source: an
597
+ // unconfirmed --from is never remembered, not even as the way to reinstall the previous version (previous: null);
598
+ // without a default the skip cannot be kept.
599
+ const skip = [...new Set([...old.skip, release(target)])];
600
+ if (state !== null) await bestEffort({ ...old, skip });
601
+ else if (d.defaultSource !== undefined) await bestEffort({ ...old, source: d.defaultSource, previous: null, skip });
602
+ return done("rolled-back", `${why}; reinstalled ${previous.version}`);
603
+ }
604
+
605
+ /**
606
+ * Stop, then start. A stop or start that throws, or a watcher that is still running after the stop, is not fatal: the
607
+ * start still runs and the health check still waits; `problem` names what kept the restart from happening (then a
608
+ * missing heartbeat is no evidence against the new version).
609
+ */
610
+ async function restart(d , reinstallSchedule ) {
611
+ let problem = null;
612
+ const s = await d.watcher.stop().catch((e ) => {
613
+ problem = `the running watcher could not be stopped (${message(e)})`;
614
+ return { how: "none", pid: null, running: true };
615
+ });
616
+ if (s.running && problem === null) problem = `the running watcher${s.pid !== null ? ` (pid ${s.pid})` : ""} did not stop`;
617
+ const wasRunning = s.how !== "none" || s.running || !reinstallSchedule;
618
+ const expected = await d.watcher.restart({ wasRunning, reinstallSchedule }).catch((e ) => {
619
+ problem ??= `the watcher could not be started again (${message(e)})`;
620
+ return true;
621
+ });
622
+ return { expected, problem };
623
+ }
624
+
625
+ /**
626
+ * Polls the heartbeat until one of `target` that started after `since` (minus clock slack) and has not stopped shows
627
+ * up, or HEALTH_MS passes after `start` (when the restart returned: a slow scheduler call does not eat the wait).
628
+ */
629
+ async function healthy(d , target , since , start ) {
630
+ const read = d.readHeartbeat ?? realReadHeartbeat;
631
+ const want = release(target);
632
+ const end = start + (d.healthMs ?? HEALTH_MS);
633
+ for (;;) {
634
+ const hb = await read(d.stateDir).catch(() => null);
635
+ const started = hb ? Date.parse(hb.startedAt) : Number.NaN;
636
+ if (hb && typeof hb.version === "string" && parseSemver(hb.version) !== null && release(hb.version) === want && !hb.stoppedAt
637
+ && Number.isFinite(started) && started >= since - START_SLACK_MS) return true;
638
+ if (d.clock.now() >= end) return false;
639
+ await new Promise ((ok) => { d.clock.setTimer(ok, d.pollMs ?? POLL_MS); });
640
+ }
641
+ }