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,290 @@
1
+ // <state>/sync-status.json: what an unattended `sync` leaves for a person to see (spec 4.7) next to the watcher's
2
+ // heartbeat (pid, startedAt, lastCycleAt, lastResult, nextCycleAt; src/ops/watch.ts).
3
+ // needsAttention one reason at a time, with the command that fixes it; `since` is the first time the SAME reason was
4
+ // seen (it is not reset by every cycle) and goes back to null as soon as the reason is gone.
5
+ // undecided sessions waiting for an organize question, per question key.
6
+ // heldRehome copies from refused folders waiting for a destination folder that does not exist in T3 yet.
7
+ // failures consecutive failing cycles (three raise `repeated-failures`).
8
+ // lastNotified reason -> ISO time of the last system notification (src/ops/notify.ts: one per reason per 24 h).
9
+ // followConflicts rehome copies continued both in T3 Code and outside it (src/ops/follow.ts): both titles and the
10
+ // session ids of the original and the copy, never a path. Replaced by every cycle that ran the
11
+ // follow step; absent when there is none.
12
+ // lastHistoryAt ISO time of sync's last complete daily pass of the history rule (src/ops/sync.ts): the next one runs
13
+ // 24 h later; absent when none ran yet, or when a pass left changes for the next cycle.
14
+ // updateFailure the last t3sm update that failed, was rolled back or was interrupted ({ from, to, outcome, at }:
15
+ // versions only, never the error, which may name a folder; that is in the journal). A failed or
16
+ // interrupted one raises `update-failed` (the lowest reason) until an update installs
17
+ // (recordUpdateOutcome); a rolled-back one never does (t3sm recovered: `status` shows it as info).
18
+ // Written by both a one-shot `sync` and the watcher: every write merges into what the file holds, and nothing is written
19
+ // when nothing changed (a quiet cycle leaves the file alone). Never holds paths, the heartbeat's `lastResult` included
20
+ // (sync.resultSummary keeps a held project's name, title and time only); held conversation titles are kept for
21
+ // `t3sm status`.
22
+
23
+ import { readFile } from "node:fs/promises";
24
+ import { join } from "node:path";
25
+ import { atomicWrite } from "../core/fsutil.js";
26
+ import { parseSemver } from "../core/semver.js";
27
+ import { cliT } from "../i18n/cli.js";
28
+
29
+
30
+ /**
31
+ * The values an attention reason is about, recorded next to its English `detail` so a screen or a notification words
32
+ * it in any language (src/ops/notify.ts attentionText) without reading the English back. Absent in files written by
33
+ * t3sm 0.3.0 and older.
34
+ */
35
+
36
+
37
+
38
+ /** Only the known facts, of the right type (the file may come from another version). */
39
+ function factsOf(v ) {
40
+ if (v === null || typeof v !== "object" || Array.isArray(v)) return undefined;
41
+ const o = v ;
42
+ const out = {};
43
+ for (const k of ["n", "q", "limit"] ) if (typeof o[k] === "number" && Number.isFinite(o[k])) out[k] = o[k] ;
44
+ for (const k of ["version", "from", "to", "outcome"] ) if (typeof o[k] === "string") out[k] = o[k] ;
45
+ return Object.keys(out).length > 0 ? out : undefined;
46
+ }
47
+
48
+ /** A failing streak of `n` cycles: needs a person (repeated-failures). */
49
+ export function streakAttention(n ) {
50
+ return { reason: "repeated-failures", detail: cliT("en", "notify.failures", { n }), command: "t3sm doctor", facts: { n } };
51
+ }
52
+
53
+ /** A rehome copy and its original, both continued (nothing done): titles and session ids only, never a path. */
54
+
55
+
56
+ /**
57
+ * A project held because one of its conversations is in use: names and time only, never a path. `since`: when a cycle
58
+ * first saw the project held (kept while later cycles still see it; recordSyncStatus sets it), absent in older files.
59
+ */
60
+
61
+
62
+
63
+
64
+
65
+
66
+
67
+
68
+
69
+
70
+
71
+
72
+
73
+ /** Highest first: the one reason a person sees when several apply (a specific cause beats a generic streak). */
74
+ export const ATTENTION_PRIORITY = ["t3-incompatible", "signed-out", "repeated-failures", "over-limit", "undecided", "update-failed"];
75
+ const rank = (r ) => ATTENTION_PRIORITY.indexOf(r);
76
+
77
+ /** Consecutive failing cycles that raise `repeated-failures`. */
78
+ export const REPEATED_FAILURES = 3;
79
+
80
+ const FILE = "sync-status.json";
81
+ const REASONS = new Set(ATTENTION_PRIORITY);
82
+
83
+ async function readRaw(stateDir ) {
84
+ try {
85
+ const v = JSON.parse(await readFile(join(stateDir, FILE), "utf8"));
86
+ return v !== null && typeof v === "object" && !Array.isArray(v) ? (v ) : {};
87
+ } catch { return {}; }
88
+ }
89
+
90
+ function fieldsOf(raw ) {
91
+ const na = raw["needsAttention"] ;
92
+ const ok = na && typeof na === "object" && typeof na.reason === "string" && REASONS.has(na.reason) && typeof na.since === "string"
93
+ && typeof na.detail === "string" && typeof na.command === "string";
94
+ const u = raw["undecided"];
95
+ const undecided = {};
96
+ if (u && typeof u === "object") for (const [k, n] of Object.entries(u)) if (typeof n === "number") undecided[k] = n;
97
+ const h = raw["held"];
98
+ const held = [];
99
+ if (Array.isArray(h)) for (const e of h ) {
100
+ const o = e ;
101
+ if (o && typeof o === "object" && typeof o["project"] === "string" && typeof o["modifiedAt"] === "string") {
102
+ held.push({ project: o["project"], title: typeof o["title"] === "string" ? o["title"] : null, modifiedAt: o["modifiedAt"], ...(typeof o["since"] === "string" ? { since: o["since"] } : {}) });
103
+ }
104
+ }
105
+ const fc = raw["followConflicts"];
106
+ const followConflicts = [];
107
+ if (Array.isArray(fc)) for (const e of fc ) {
108
+ const o = e ;
109
+ if (o && typeof o === "object" && typeof o["originalId"] === "string" && typeof o["copyId"] === "string" && typeof o["originalTitle"] === "string" && typeof o["copyTitle"] === "string") {
110
+ followConflicts.push({ originalId: o["originalId"], copyId: o["copyId"], originalTitle: o["originalTitle"], copyTitle: o["copyTitle"] });
111
+ }
112
+ }
113
+ return {
114
+ held,
115
+ needsAttention: ok ? (() => {
116
+ const a = na ;
117
+ const facts = factsOf(a.facts);
118
+ return { reason: a.reason, detail: a.detail, command: a.command, since: a.since, ...(facts ? { facts } : {}) };
119
+ })() : null,
120
+ undecided,
121
+ heldRehome: typeof raw["heldRehome"] === "number" ? raw["heldRehome"] : 0,
122
+ failures: typeof raw["failures"] === "number" ? raw["failures"] : 0,
123
+ ...(followConflicts.length > 0 ? { followConflicts } : {}),
124
+ };
125
+ }
126
+
127
+ export async function readSyncStatus(stateDir ) {
128
+ return fieldsOf(await readRaw(stateDir));
129
+ }
130
+
131
+ /** Whether a sync cycle ever recorded `undecided` in the file (a 0.2.1 watcher never does). */
132
+ export async function recordsUndecided(stateDir ) {
133
+ return "undecided" in (await readRaw(stateDir));
134
+ }
135
+
136
+ /** What one cycle saw. `attention` undefined: the cycle could not tell (an error): keep what the file says. */
137
+
138
+
139
+
140
+
141
+
142
+
143
+
144
+
145
+
146
+
147
+
148
+ /** Deep equality of JSON values, whatever the key order (objects compared by sorted keys). */
149
+ const canon = (v ) => (Array.isArray(v) ? v.map(canon)
150
+ : v !== null && typeof v === "object" ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, canon((v )[k])])) : v);
151
+ const same = (a , b ) => JSON.stringify(canon(a)) === JSON.stringify(canon(b));
152
+
153
+ /** Merges one cycle into the file. Returns what the file holds now. */
154
+ export async function recordSyncStatus(stateDir , o , now ) {
155
+ const raw = await readRaw(stateDir);
156
+ const prev = fieldsOf(raw);
157
+ const failures = o.cycle === "failed" ? prev.failures + 1 : o.cycle === "ok" ? 0 : prev.failures;
158
+ let attention = o.attention;
159
+ // A failing streak competes with the cycle's own reason by rank (ATTENTION_PRIORITY): the more specific, actionable cause wins.
160
+ if (failures >= REPEATED_FAILURES) {
161
+ const streak = streakAttention(failures);
162
+ if (!attention || rank(streak.reason) < rank(attention.reason)) attention = streak;
163
+ }
164
+ // A failed update (the lowest reason) shows whenever nothing else needs a person; a cycle that could not tell keeps the
165
+ // file's. A rolled-back one is not a need (the previous version runs): it never raises the reason.
166
+ const failure = updateFailureOf(raw);
167
+ if (attention === null && failure !== null && failure.outcome !== "rolled-back") attention = updateFailedAttention(failure);
168
+ let needsAttention ;
169
+ if (attention === undefined) needsAttention = prev.needsAttention;
170
+ else if (attention === null) needsAttention = null;
171
+ else if (attention.reason === "update-failed" && failure !== null) needsAttention = { ...attention, since: failure.at };
172
+ else needsAttention = { ...attention, since: prev.needsAttention?.reason === attention.reason ? prev.needsAttention.since : now.toISOString() };
173
+ const next = {
174
+ needsAttention,
175
+ undecided: o.undecided ?? prev.undecided,
176
+ heldRehome: o.heldRehome ?? prev.heldRehome,
177
+ // A project still held keeps the time a cycle first saw it held; a new one is held since now.
178
+ held: o.held ? o.held.map((h) => ({ ...h, since: prev.held.find((p) => p.project === h.project)?.since ?? h.since ?? now.toISOString() })) : prev.held,
179
+ failures,
180
+ };
181
+ const conflicts = o.followConflicts ?? prev.followConflicts ?? [];
182
+ if (conflicts.length > 0) next.followConflicts = conflicts;
183
+ // A cycle that looked always leaves the `undecided` key (even {}): `status` reads its presence as "a 0.3 cycle
184
+ // recorded the questions" (a 0.2.1 watcher never writes it), so a file without it must get it now.
185
+ if (!same(prev, next) || (o.undecided !== undefined && !("undecided" in raw))) {
186
+ const out = { ...raw, ...next };
187
+ if (next.followConflicts === undefined) delete out["followConflicts"];
188
+ await atomicWrite(join(stateDir, FILE), JSON.stringify(out, null, 2) + "\n");
189
+ }
190
+ return next;
191
+ }
192
+
193
+ /** The watcher's heartbeat, written over its own fields only: what a cycle recorded stays. */
194
+ export async function writeHeartbeatMerged(stateDir , heartbeat ) {
195
+ const raw = await readRaw(stateDir);
196
+ const keep = {};
197
+ for (const k of ["needsAttention", "undecided", "heldRehome", "held", "failures", "lastNotified", "followConflicts", "lastHistoryAt", "updateFailure"]) if (k in raw) keep[k] = raw[k];
198
+ await atomicWrite(join(stateDir, FILE), JSON.stringify({ ...keep, ...heartbeat }, null, 2) + "\n");
199
+ }
200
+
201
+ /** When sync's daily history pass last completed (epoch ms); null when never, or unreadable. */
202
+ export async function readLastHistoryAt(stateDir ) {
203
+ const v = (await readRaw(stateDir))["lastHistoryAt"];
204
+ const at = typeof v === "string" ? Date.parse(v) : NaN;
205
+ return Number.isFinite(at) ? at : null;
206
+ }
207
+
208
+ /** Records (or, with null, clears) sync's daily history pass, merged into what the file holds. */
209
+ export async function markHistoryPass(stateDir , at ) {
210
+ const raw = await readRaw(stateDir);
211
+ const out = { ...raw };
212
+ if (at === null) {
213
+ if (!("lastHistoryAt" in raw)) return;
214
+ delete out["lastHistoryAt"];
215
+ } else out["lastHistoryAt"] = at.toISOString();
216
+ await atomicWrite(join(stateDir, FILE), JSON.stringify(out, null, 2) + "\n");
217
+ }
218
+
219
+ /** reason -> ISO time of the last system notification (invalid entries dropped). */
220
+ export async function readLastNotified(stateDir ) {
221
+ const v = (await readRaw(stateDir))["lastNotified"];
222
+ const out = {};
223
+ if (v && typeof v === "object" && !Array.isArray(v)) for (const [k, t] of Object.entries(v)) if (typeof t === "string") out[k] = t;
224
+ return out;
225
+ }
226
+
227
+ /** Records a notification for `reason`, merged into what the file holds (the cycle's fields and the heartbeat stay). */
228
+ export async function markNotified(stateDir , reason , at ) {
229
+ const raw = await readRaw(stateDir);
230
+ const lastNotified = { ...(await readLastNotified(stateDir)), [reason]: at.toISOString() };
231
+ await atomicWrite(join(stateDir, FILE), JSON.stringify({ ...raw, lastNotified }, null, 2) + "\n");
232
+ }
233
+
234
+ // ---------- update-failed ----------
235
+
236
+ /** The last update that did not install (versions and time only: never the error, which may name a folder). */
237
+
238
+
239
+ /** The last update that did not install, as recorded by recordUpdateOutcome; null when none (or unreadable). */
240
+ export async function readUpdateFailure(stateDir ) {
241
+ return updateFailureOf(await readRaw(stateDir));
242
+ }
243
+
244
+ /** The words `status` and the attention reason use for a failed, rolled-back or interrupted update. */
245
+ export function updateFailureText(f ) {
246
+ return updateFailedAttention(f).detail;
247
+ }
248
+
249
+ function updateFailureOf(raw ) {
250
+ const f = raw["updateFailure"] ;
251
+ if (!f || typeof f !== "object" || typeof f.from !== "string" || typeof f.to !== "string" || typeof f.at !== "string") return null;
252
+ if (f.outcome !== "failed" && f.outcome !== "rolled-back" && f.outcome !== "interrupted") return null;
253
+ // A version that is not a release version is unknown: the failure is still reported, the text never carries it.
254
+ const v = (x ) => (parseSemver(x) !== null ? x : "unknown");
255
+ return { from: v(f.from), to: v(f.to), outcome: f.outcome, at: f.at };
256
+ }
257
+
258
+ function updateFailedAttention(f ) {
259
+ const detail = f.outcome === "rolled-back" ? `t3sm ${f.to} did not start properly, so ${f.from} was put back`
260
+ : f.outcome === "interrupted" ? `The update of t3sm from ${f.from} to ${f.to} was interrupted`
261
+ : `Updating t3sm from ${f.from} to ${f.to} failed; ${f.from} is still installed`;
262
+ return { reason: "update-failed", detail, command: "t3sm update --check", facts: { from: f.from, to: f.to, outcome: f.outcome } };
263
+ }
264
+
265
+ /**
266
+ * After an update (`t3sm update`, the watcher's `update --auto-run` child, or an interrupted one found at the watcher's
267
+ * start): a failed, rolled-back or interrupted one is kept in `updateFailure`. A failed or interrupted one raises
268
+ * `update-failed` now when nothing else needs a person (later cycles keep it, see recordSyncStatus); a rolled-back one
269
+ * never does, and clears an older failure's `update-failed` (status ranks it info, and `--json` must agree). An installed
270
+ * one clears both. `since` is the failure's time. Merged into what the file holds; nothing is written when nothing
271
+ * changes. Throws on a write error.
272
+ */
273
+ export async function recordUpdateOutcome(
274
+ stateDir , u , now ,
275
+ ) {
276
+ const raw = await readRaw(stateDir);
277
+ const prev = fieldsOf(raw).needsAttention;
278
+ const out = { ...raw };
279
+ if (u.outcome === "installed") {
280
+ if (!("updateFailure" in raw) && prev?.reason !== "update-failed") return;
281
+ delete out["updateFailure"];
282
+ if (prev?.reason === "update-failed") out["needsAttention"] = null;
283
+ } else {
284
+ const failure = { from: u.from, to: u.to, outcome: u.outcome, at: now.toISOString() };
285
+ out["updateFailure"] = failure;
286
+ if (u.outcome === "rolled-back") { if (prev?.reason === "update-failed") out["needsAttention"] = null; }
287
+ else if (prev === null || prev.reason === "update-failed") out["needsAttention"] = { ...updateFailedAttention(failure), since: failure.at };
288
+ }
289
+ if (!same(raw, out)) await atomicWrite(join(stateDir, FILE), JSON.stringify(out, null, 2) + "\n");
290
+ }
@@ -0,0 +1,273 @@
1
+ // t3sm update's building blocks: how this t3sm was installed (a checkout, a global npm install, npx's cache), its own
2
+ // GitHub repository (the default update source), and updateRunner, the runner the update engine (src/ops/updater.ts)
3
+ // uses for git and npm: no prompts, a time limit per call, no CLAUDE_CONFIG_DIR.
4
+
5
+ import { spawn, } from "node:child_process";
6
+ import { readFileSync } from "node:fs";
7
+ import { tmpdir } from "node:os";
8
+ import { join, win32 } from "node:path";
9
+
10
+ import { driveSystemRoot } from "../core/sysroot.js";
11
+
12
+
13
+
14
+
15
+ /** `root` is the package root (the folder holding bin/ and package.json). */
16
+ export function installKind(root ) {
17
+ const parts = root.split(/[\\/]+/);
18
+ if (!parts.includes("node_modules")) return "checkout";
19
+ return parts.includes("_npx") ? "npx" : "global";
20
+ }
21
+
22
+ /** `owner/name` of a GitHub repository URL. Throws when it is not one. */
23
+ export function repoSlug(repositoryUrl ) {
24
+ const m = /github\.com[/:]([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/.exec(repositoryUrl);
25
+ if (!m) throw new Error(`package.json's repository is not a GitHub URL: ${repositoryUrl}`);
26
+ return `${m[1]}/${m[2]}`;
27
+ }
28
+
29
+ /** The npm spec of the newest release, from package.json's repository URL. */
30
+ export function releaseSpec(repositoryUrl ) {
31
+ return `github:${repoSlug(repositoryUrl)}#semver:*`;
32
+ }
33
+
34
+ /** This t3sm's own repository URL, from its package.json (src/ops and dist/ops both sit two folders below the root). */
35
+ export function ownRepositoryUrl() {
36
+ try {
37
+ const r = (JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")) ).repository;
38
+ return typeof r === "string" ? r : r?.url ?? "";
39
+ } catch { return ""; }
40
+ }
41
+
42
+ /** This t3sm's own npm package name, from its package.json ("" when it cannot be read). */
43
+ export function ownPackageName() {
44
+ try {
45
+ const n = (JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")) ).name;
46
+ return typeof n === "string" ? n : "";
47
+ } catch { return ""; }
48
+ }
49
+
50
+ /**
51
+ * Whether the package at `root` is the one published to the npm registry: the Release workflow builds it with
52
+ * `channel: "npm"` in dist/build.json (scripts/build.js). npm itself keeps no record of where a global package came
53
+ * from, and a build from a GitHub tag or a checkout has no channel. Read-only, no network; false when unknown.
54
+ */
55
+ export function isRegistryInstall(root ) {
56
+ try {
57
+ const stamp = JSON.parse(readFileSync(join(root, "dist", "build.json"), "utf8"));
58
+ return typeof stamp === "object" && stamp !== null && (stamp ).channel === "npm";
59
+ } catch { return false; }
60
+ }
61
+
62
+ /**
63
+ * The source t3sm updates from when nothing is remembered: the npm registry for an install that came from it (its
64
+ * package name), otherwise the GitHub repository in package.json (null: neither is known).
65
+ */
66
+ export function defaultUpdateSource(repositoryUrl = ownRepositoryUrl(), registry ) {
67
+ if (registry?.installed && registry.name !== "") return { kind: "npm", name: registry.name };
68
+ try { return { kind: "github", repo: repoSlug(repositoryUrl) }; } catch { return null; }
69
+ }
70
+
71
+ /** The environment npm runs with: everything but CLAUDE_CONFIG_DIR (a child process never inherits it). */
72
+ export function npmEnv(env ) {
73
+ const out = {};
74
+ for (const [k, v] of Object.entries(env)) if (v !== undefined && k.toUpperCase() !== "CLAUDE_CONFIG_DIR") out[k] = v;
75
+ return out;
76
+ }
77
+
78
+ /** Arguments safe to hand to cmd.exe unquoted (npm is npm.cmd on Windows, which needs a shell). */
79
+ const SAFE_ARG = /^[A-Za-z0-9:/._#*@-]+$/;
80
+
81
+ /** How updateRunner starts a process (tests inject a fake child). `args` empty: `cmd` is a whole shell command line. */
82
+
83
+
84
+ /** The slice of `process` updateRunner uses to stop a POSIX child's group when t3sm exits or is interrupted. */
85
+
86
+
87
+
88
+
89
+
90
+
91
+
92
+ const GUARD_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
93
+
94
+ /** The timer updateRunner arms per call (tests inject one that fires on demand). */
95
+
96
+ const realTimer = {
97
+ // unref: a pending time limit never keeps the process alive by itself.
98
+ setTimer: (fn, ms) => { const t = setTimeout(fn, ms); t.unref(); return t; },
99
+ clearTimer: (h) => clearTimeout(h ),
100
+ };
101
+
102
+ /** How long a killed command gets to report its exit before the call returns the timeout result anyway. */
103
+ export const KILL_GRACE_MS = 5000;
104
+ /** How long an exited command may keep its pipes open (a helper that inherited them) before the call ends anyway. */
105
+ export const EXIT_GRACE_MS = 5000;
106
+
107
+ /** The slice of a ChildProcess the kill needs. */
108
+
109
+
110
+
111
+
112
+
113
+
114
+
115
+ /** What defaultKill starts or signals (tests inject a fake, so no real pid or group is ever signalled by a test). */
116
+
117
+
118
+
119
+
120
+
121
+
122
+ const realKillSys = {
123
+ spawn: (cmd, args, env) => { spawn(cmd, args, { stdio: "ignore", windowsHide: true, env }).on("error", () => {}); },
124
+ killGroup: (pgid) => { process.kill(-pgid, "SIGKILL"); },
125
+ };
126
+
127
+ /**
128
+ * Kills a command updateRunner started, by its own pid, never by name, and only while that child is known to be alive
129
+ * (no exit code, no signal yet: a pid that already exited may belong to another process by now). win32:
130
+ * `taskkill /PID <pid> /T /F` (the tree: the shell npm runs in, npm, git, a `prepare` script), started without
131
+ * CLAUDE_CONFIG_DIR, and only under a SystemRoot that is a drive path such as `C:\Windows` (a relative, drive-less,
132
+ * network or device SystemRoot never runs a taskkill.exe found somewhere else). POSIX: the child leads its own process group (updateRunner starts it detached), so the whole
133
+ * group gets SIGKILL (npm's git clone and `prepare` too, so nothing keeps writing the install after a timeout), then
134
+ * the child itself through its handle.
135
+ */
136
+ export function defaultKill(platform , env , sys = realKillSys) {
137
+ return (c) => {
138
+ const pid = c.pid;
139
+ if (pid === undefined || !Number.isInteger(pid) || pid <= 1 || pid === process.pid) return;
140
+ if (c.exitCode !== null || c.signalCode !== null) return; // already gone: never signal a pid that may be reused
141
+ if (platform === "win32") {
142
+ // A drive path only (`C:\Windows`): a drive-less rooted folder (`\Windows`, the current drive), a relative one, a
143
+ // network share or a device path never resolves the taskkill.exe that is started.
144
+ const root = driveSystemRoot(env);
145
+ if (root === null) return;
146
+ const taskkill = win32.join(root, "System32", "taskkill.exe");
147
+ if (!win32.isAbsolute(taskkill)) return;
148
+ try { sys.spawn(taskkill, ["/PID", String(pid), "/T", "/F"], npmEnv(env)); } catch { /* gone */ }
149
+ return;
150
+ }
151
+ try { sys.killGroup(pid); } catch { /* the group is gone */ }
152
+ try { c.kill("SIGKILL"); } catch { /* gone */ }
153
+ };
154
+ }
155
+
156
+ /**
157
+ * The environment of every command the update engine runs: npmEnv (no CLAUDE_CONFIG_DIR), and git never asks for
158
+ * anything: GIT_TERMINAL_PROMPT=0 (no username/password prompt) and GCM_INTERACTIVE=never (Git Credential Manager on
159
+ * Windows would otherwise open a sign-in window from a hidden background process and wait for it forever).
160
+ */
161
+ export function updateEnv(env ) {
162
+ return { ...npmEnv(env), GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" };
163
+ }
164
+
165
+ /**
166
+ * The runner the update engine (src/ops/updater.ts) uses for git and npm: output captured, env from updateEnv, and a
167
+ * time limit per call (`timeoutMs`): past it the command is killed by its own pid (defaultKill) and the result is exit
168
+ * 124 with "timed out after N s" (at the latest KILL_GRACE_MS after the kill, whether or not the child reports its
169
+ * exit), so a stalled proxy or a hidden prompt never holds the sync lock. On POSIX each child leads its own process
170
+ * group (detached), so the kill reaches what npm started itself (git clone, a `prepare` script) as well; and because a
171
+ * detached group misses the terminal's Ctrl+C, the call registers exit, SIGINT, SIGTERM and SIGHUP handlers for its
172
+ * duration that kill the live child's group (a signal is raised again afterwards when nobody else handles it, so
173
+ * Ctrl+C still ends t3sm). A child that exited but whose pipes stay open (a background helper inherited them) ends the
174
+ * call EXIT_GRACE_MS later with its own exit code. No shell, except npm
175
+ * on Windows (npm.cmd only starts through cmd.exe): its arguments must pass SAFE_ARG (no spaces, quotes or cmd.exe
176
+ * metacharacters), the command line is joined here, never by Node, and anything else is refused with exit 126 before a
177
+ * process starts. NoDefaultCurrentDirectoryInExePath=1 stops cmd.exe from resolving `npm` from the working folder (a
178
+ * folder install runs npm inside the clone; that checkout's own `prepare` script runs anyway, so this is tidiness, not
179
+ * a trust boundary). A call without `cwd` runs in the temp folder (`o.cwd`, default os.tmpdir()), never in the folder
180
+ * t3sm was started from: Windows resolves a bare `git` in the working folder before PATH, so `t3sm update --check` run
181
+ * in a folder holding a planted git.exe would start it. Spawn errors are exit 127, and so is cmd.exe's 9009 (command not found).
182
+ */
183
+ export function updateRunner(
184
+ platform , env ,
185
+ o = {},
186
+ ) {
187
+ const proc = o.proc ?? (process );
188
+ const sp = o.spawn ?? ((c, a, opts) => (a.length > 0 ? spawn(c, a, opts) : spawn(c, opts)));
189
+ const timer = o.timer ?? realTimer;
190
+ const kill = o.kill ?? defaultKill(platform, env);
191
+ return (cmd, args, opts) => new Promise((resolve) => {
192
+ const viaShell = platform === "win32" && cmd === "npm";
193
+ if (viaShell) {
194
+ const bad = args.find((a) => !SAFE_ARG.test(a));
195
+ if (bad !== undefined) { resolve({ code: 126, stdout: "", stderr: `refusing to pass ${JSON.stringify(bad)} to npm` }); return; }
196
+ }
197
+ const out = [];
198
+ const err = [];
199
+ let done = false;
200
+ let timedOut = false;
201
+ let handle = null;
202
+ let grace = null;
203
+ let exitGrace = null;
204
+ let exited = false; // the 'exit' event: 'close' also waits for every process holding the pipes (grandchildren)
205
+ let unguard = () => {};
206
+ const finish = (code , fallbackErr = "") => {
207
+ if (done) return; // late child events after a timeout result are ignored
208
+ done = true;
209
+ unguard();
210
+ if (handle !== null) timer.clearTimer(handle);
211
+ if (grace !== null) timer.clearTimer(grace);
212
+ if (exitGrace !== null) timer.clearTimer(exitGrace);
213
+ const stderr = Buffer.concat(err).toString("utf8") || fallbackErr;
214
+ if (timedOut) resolve({ code: 124, stdout: Buffer.concat(out).toString("utf8"), stderr: `timed out after ${Math.round((opts?.timeoutMs ?? 0) / 1000)} s${stderr ? `\n${stderr}` : ""}` });
215
+ else resolve({ code: code === 9009 ? 127 : code, stdout: Buffer.concat(out).toString("utf8"), stderr });
216
+ };
217
+ let child;
218
+ try {
219
+ const childEnv = viaShell ? { ...updateEnv(env), NoDefaultCurrentDirectoryInExePath: "1" } : updateEnv(env);
220
+ // POSIX: its own process group, so a kill reaches everything it started (see defaultKill).
221
+ // Never the launch folder: without a shell, Windows looks for a bare `git` there before PATH (a planted git.exe).
222
+ const o2 = { shell: viaShell, windowsHide: true, detached: platform !== "win32", cwd: opts?.cwd ?? o.cwd ?? tmpdir(), env: childEnv, stdio: ["pipe", "pipe", "pipe"] };
223
+ child = viaShell ? sp(["npm", ...args].join(" "), [], o2) : sp(cmd, args, o2);
224
+ } catch (e) {
225
+ finish(127, (e ).message);
226
+ return;
227
+ }
228
+ const c = child;
229
+ const letGo = () => { for (const st of [c.stdin, c.stdout, c.stderr]) { try { st.destroy(); } catch { /* already closed */ } } };
230
+ o.onSpawn?.(c);
231
+ const alive = () => !exited && c.exitCode === null && c.signalCode === null;
232
+ if (platform !== "win32") {
233
+ // The detached group does not get the terminal's Ctrl+C: t3sm passes it on while this call runs.
234
+ const onExit = () => { if (alive()) kill(c); };
235
+ const onSignal = (sig ) => {
236
+ if (alive()) kill(c);
237
+ unguard();
238
+ if (proc.listenerCount(sig) === 0) proc.kill(proc.pid, sig); // nobody else handles it: the default action
239
+ };
240
+ proc.on("exit", onExit);
241
+ for (const sig of GUARD_SIGNALS) proc.on(sig, onSignal);
242
+ unguard = () => {
243
+ unguard = () => {};
244
+ proc.off("exit", onExit);
245
+ for (const sig of GUARD_SIGNALS) proc.off(sig, onSignal);
246
+ };
247
+ }
248
+ c.on("exit", (code) => {
249
+ exited = true;
250
+ // 'close' also waits for every process holding the pipes (a background helper that inherited stdout): the child
251
+ // is done, so after a short grace the call ends with its own exit code (a signal exit counts as 1).
252
+ if (!done) exitGrace = timer.setTimer(() => { letGo(); finish(code ?? 1); }, EXIT_GRACE_MS);
253
+ });
254
+ c.stdout.on("data", (d ) => void out.push(d));
255
+ c.stderr.on("data", (d ) => void err.push(d));
256
+ c.on("error", (e) => finish(127, e.message));
257
+ c.on("close", (code) => finish(code ?? 1));
258
+ c.stdin.on("error", () => {});
259
+ c.stdin.end(opts?.input ?? "");
260
+ if (opts?.timeoutMs !== undefined && opts.timeoutMs > 0) {
261
+ handle = timer.setTimer(() => {
262
+ if (done) return;
263
+ timedOut = true;
264
+ if (alive()) kill(c);
265
+ // A grandchild holding the pipes must not keep the call alive: let go of them.
266
+ letGo();
267
+ // The child is gone: the timeout result now. Otherwise never wait on its events forever: the grace period.
268
+ if (exited) finish(124);
269
+ else grace = timer.setTimer(() => finish(124), KILL_GRACE_MS);
270
+ }, opts.timeoutMs);
271
+ }
272
+ });
273
+ }