t3code-session-manager 0.0.0-stage → 0.4.1

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 +149 -0
  4. package/LICENSE +21 -0
  5. package/README.md +661 -2
  6. package/README.pt.md +617 -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,61 @@
1
+ // t3sm changelog [--since <version>]: the release notes of the installed t3sm, read from its own CHANGELOG.md (shipped
2
+ // in the package). Default: the installed version's section; --since: every release newer than that version, up to the
3
+ // installed one, newest first. Read-only.
4
+
5
+ import { readFileSync } from "node:fs";
6
+ import { changelogSections, sectionsBetween } from "../../core/changelog.js";
7
+ import { packageVersion } from "../../core/version.js";
8
+ import { parseSemver } from "../../core/semver.js";
9
+ import { parseFlags } from "./quarantine.js";
10
+ import { renderNotes } from "./update.js";
11
+ import { cliUi } from "../ui.js";
12
+ import { flagsOf } from "../flags.js";
13
+ import { noteLines } from "../screen.js";
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+ /** This install's CHANGELOG.md (src/ and dist/ both sit two folders below the package root), or null. */
24
+ export function installedChangelog() {
25
+ try { return readFileSync(new URL("../../../CHANGELOG.md", import.meta.url), "utf8"); } catch { return null; }
26
+ }
27
+
28
+ export async function changelogCommand(args , io , deps = {}) {
29
+ const spec = flagsOf("changelog");
30
+ const p = parseFlags(args, io, "changelog", spec.bool, spec.valued);
31
+ if (!p) return 2;
32
+ const ui = cliUi(io);
33
+ const since = p.values.get("--since");
34
+ if (since !== undefined && parseSemver(since) === null) {
35
+ io.stderr(`${ui.t("changelog.badSince", { since: JSON.stringify(since) })}\n`);
36
+ return 2;
37
+ }
38
+ const version = (deps.readVersion ?? packageVersion)();
39
+ const text = (deps.readChangelog ?? installedChangelog)();
40
+ if (text === null) {
41
+ io.stderr(`${ui.t("changelog.missing")}\n`);
42
+ return 1;
43
+ }
44
+ if (parseSemver(version) === null) {
45
+ io.stderr(`${ui.t("changelog.notRelease", { version: JSON.stringify(version) })}\n`);
46
+ return 1;
47
+ }
48
+ const v = parseSemver(version) .join(".");
49
+ // Without --since: just this version's own section.
50
+ const sections = since === undefined ? changelogSections(text).filter((s) => s.version === v).slice(0, 1) : sectionsBetween(text, since, v);
51
+ if (sections.length === 0) {
52
+ const msg = since === undefined ? ui.t("changelog.none", { version: v }) : ui.t("changelog.noneNewer", { since: parseSemver(since) .join("."), version: v });
53
+ io.stdout(noteLines(ui.s, "ok", msg, ui.width).join("\n") + "\n");
54
+ return 0;
55
+ }
56
+ // The notes are written in English; drawn like a help topic (headings, bullets, wrapped to the window).
57
+ // In another language, one muted line says so (they are not translated).
58
+ const hint = ui.lang === "en" ? [] : [ui.s("muted", ui.t("changelog.inEnglish")), ""];
59
+ io.stdout([...hint, ...renderNotes(ui, sections)].join("\n") + "\n");
60
+ return 0;
61
+ }
@@ -0,0 +1,105 @@
1
+ import { defaultDoctorDeps, runDoctor, sayText, } from "../../ops/doctor.js";
2
+ import { shownText } from "../../plan/names.js";
3
+ import { callout, panel, table, } from "../../ui/components.js";
4
+ import { snugWidth, textLines } from "../screen.js";
5
+ import { FLAG_SPECS } from "../flags.js";
6
+
7
+ import { cliUi, unknownOption } from "../ui.js";
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+ /** Io plus the terminal width when known (the launcher may set it; tests do). */
18
+
19
+
20
+ const KNOWN = new Set (FLAG_SPECS.doctor.bool);
21
+
22
+ /** Each check's name on screen (the id stays in --json). */
23
+ const CHECK_NAME = {
24
+ "node-version": "doctor.check.nodeVersion", "state-dir": "doctor.check.stateDir", config: "doctor.check.config",
25
+ lock: "doctor.check.lock", "pending-mtimes": "doctor.check.pendingMtimes", "future-mtimes": "doctor.check.futureMtimes",
26
+ "claude-env": "doctor.check.claudeEnv", "t3-runtime": "doctor.check.t3Runtime", "t3-reachable": "doctor.check.t3Reachable",
27
+ "t3-version": "doctor.check.t3Version", "t3-cli": "doctor.check.t3Cli", "t3-token": "doctor.check.t3Token",
28
+ instances: "doctor.check.instances", "instance-home-drift": "doctor.check.instanceHomeDrift",
29
+ "instance-unpinned": "doctor.check.instanceUnpinned", "instance-accounts": "doctor.check.instanceAccounts",
30
+ "accounts-undiscovered": "doctor.check.accountsUndiscovered", "backups-present": "doctor.check.backupsPresent",
31
+ "quarantine-orphans": "doctor.check.quarantineOrphans", harnesses: "doctor.check.harnesses",
32
+ "t3sm-plugin": "doctor.check.t3smPlugin", schedule: "doctor.check.schedule", "sync-watcher": "doctor.check.syncWatcher",
33
+ "merge-pending": "doctor.check.mergePending",
34
+ };
35
+ const HARNESS_NAME = { claude: "Claude Code", codex: "Codex", pi: "Pi", opencode: "OpenCode" };
36
+
37
+ /** A check's name in the user's language: `harness:codex` -> "Codex sessions"; an unknown id stays as it is. */
38
+ export function checkName(ui , id ) {
39
+ const h = /^harness:(.+)$/.exec(id);
40
+ if (h) return ui.t("doctor.check.harness", { name: HARNESS_NAME[h[1] ] ?? shownText(h[1], 40) });
41
+ const k = CHECK_NAME[id];
42
+ return k ? ui.t(k) : shownText(id, 40);
43
+ }
44
+
45
+
46
+
47
+ /** A check's result and fix in the user's language: worded from the catalogue (English: the --json message and fix). */
48
+ export function checkWords(c , lang ) {
49
+ return { message: c.say ? sayText(c.say, lang) : c.message, fix: c.sayFix ? sayText(c.sayFix, lang) : c.fix };
50
+ }
51
+
52
+ /**
53
+ * The checks as one table (symbol, check, result cut to the width), then every warning and failure in full with what
54
+ * to do, then the verdict as a panel as wide as it needs. Results and fixes in the user's language (checkWords).
55
+ */
56
+ export function renderDoctor(checks , ui ) {
57
+ const { s, t } = ui;
58
+ const width = Math.max(1, ui.width);
59
+ const symOf = (c ) => c.status === "ok" ? s("ok", s.sym.ok) : c.status === "warn" ? s("warn", s.sym.warn) : c.status === "fail" ? s("err", s.sym.err) : s("muted", s.sym.ring);
60
+ // A warning or failure is told once, in full, below the table: its row only points there.
61
+ const rows = checks.map((c) => ({
62
+ sym: symOf(c), name: checkName(ui, c.id),
63
+ message: c.status === "warn" || c.status === "fail" ? s("muted", t("doctor.seeBelow")) : shownText(checkWords(c, ui.lang).message, 400),
64
+ }));
65
+ const cols = [
66
+ { header: "", get: (r) => (r ).sym, priority: 9, min: 1 },
67
+ { header: t("doctor.col.check"), get: (r) => (r ).name, priority: 8, min: 10 },
68
+ { header: t("doctor.col.result"), get: (r) => (r ).message, priority: 5, min: 10 },
69
+ ];
70
+ const out = table(s, cols, rows, width);
71
+ // What is wrong, in full: the message and the fix, never cut.
72
+ for (const c of checks.filter((x) => x.status === "fail" || x.status === "warn")) {
73
+ const w = checkWords(c, ui.lang);
74
+ // `backticked` commands are shown whole, in the key style, without their backticks.
75
+ const body = [...textLines(s, shownText(w.message, 1000), Math.max(1, width - 2)), ...(w.fix ? textLines(s, t("doctor.whatToDo", { fix: shownText(w.fix, 1000) }), Math.max(1, width - 2)) : [])];
76
+ out.push("", ...callout(s, { kind: c.status === "fail" ? "needs-you" : "warn", title: checkName(ui, c.id), body }, width));
77
+ }
78
+ const fails = checks.filter((c) => c.status === "fail").length;
79
+ const warns = checks.filter((c) => c.status === "warn").length;
80
+ const v = fails > 0
81
+ ? { tone: "err" , title: t("doctor.problems", { n: fails }), body: [t("doctor.problemsBody", { sym: s.sym.err })] }
82
+ : { tone: "ok" , title: warns > 0 ? t("doctor.readyWarnings", { n: warns }) : t("doctor.ready"), body: [t("doctor.next")] };
83
+ // As wide as its content (like the other panels), never wider than the window.
84
+ const verdict = panel(s, v, snugWidth(`${s.sym.ok} ${v.title}`, v.body, width));
85
+ out.push("", ...verdict);
86
+ return out.join("\n") + "\n";
87
+ }
88
+
89
+ export async function doctorCommand(args , io , d = {}) {
90
+ for (const a of args) {
91
+ if (!KNOWN.has(a)) { unknownOption(io, a, "doctor"); return 2; }
92
+ }
93
+ const repair = args.includes("--repair");
94
+ const deps = d.deps
95
+ ? { ...d.deps, repair: d.deps.repair || repair }
96
+ : { ...defaultDoctorDeps({ home: d.home, env: io.env, repair }), ...(d.overrides ?? {}) };
97
+ const { checks } = await runDoctor(deps);
98
+ // --json is unchanged: the English message and fix, never the screen's wording parts.
99
+ if (args.includes("--json")) io.stdout(JSON.stringify(checks.map(({ say: _s, sayFix: _f, ...c }) => c), null, 2) + "\n");
100
+ else {
101
+ const ui = cliUi(io);
102
+ io.stdout(renderDoctor(checks, io.columns !== undefined ? { ...ui, width: io.columns } : ui));
103
+ }
104
+ return checks.some((c) => c.status === "fail") ? 1 : 0;
105
+ }
@@ -0,0 +1,158 @@
1
+ // t3sm help [<topic> | <command>]: what a message on a t3sm screen means, why it happens and what to do. The topics
2
+ // are short Markdown files shipped with t3sm: docs/help/<topic>.md (English) and <topic>.pt.md (European Portuguese),
3
+ // copied into dist/help by the build. A topic is drawn as wrapped text in the user's language (English when it has no
4
+ // translation): headings in bold, lists as bullets, `code` as a command, links as their text. Without a topic: the list
5
+ // of topics with their titles. An unknown topic: exit 2 with the list. A command's name: that command's --help.
6
+
7
+ import { existsSync, readFileSync } from "node:fs";
8
+ import { fileURLToPath } from "node:url";
9
+
10
+ import { HELP_TOPICS } from "../helpTopics.js";
11
+ import { commandHelp, renderHelpText } from "../helpText.js";
12
+ import { fitLine, richAtoms, wrapAtoms } from "../screen.js";
13
+ import { cliUi, } from "../ui.js";
14
+ import { displayWidth } from "../../ui/text.js";
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+ /**
23
+ * This install's help folder: dist/help next to the compiled commands (an installed package), else the checkout's
24
+ * docs/help (src/ runs straight from the sources). Null when neither exists.
25
+ */
26
+ export function helpDir() {
27
+ for (const rel of ["../../help/", "../../../docs/help/"]) {
28
+ const p = fileURLToPath(new URL(rel, import.meta.url));
29
+ if (existsSync(p)) return p;
30
+ }
31
+ return null;
32
+ }
33
+
34
+ /** A topic's Markdown in `lang`, else in English; null when the topic has no file. */
35
+ export function readTopic(dir , topic , lang ) {
36
+ const names = lang === "pt" ? [`${topic}.pt.md`, `${topic}.md`] : [`${topic}.md`];
37
+ for (const n of names) {
38
+ try { return readFileSync(`${dir.replace(/[\\/]+$/, "")}/${n}`, "utf8"); } catch { /* the next one */ }
39
+ }
40
+ return null;
41
+ }
42
+
43
+ /** A topic's one-line summary: its title (the first `# ` heading). */
44
+ export function topicSummary(md ) {
45
+ return /^# +(.+?)\s*$/m.exec(md)?.[1] ?? "";
46
+ }
47
+
48
+ /** Inline Markdown as plain text with `code` kept in backticks for richAtoms: links become their text, emphasis goes. */
49
+ function inline(text ) {
50
+ return text
51
+ .replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1")
52
+ .replace(/\*\*([^*]+)\*\*/g, "$1")
53
+ .replace(/(^|[^\w*])\*([^*\s][^*]*)\*(?!\w)/g, "$1$2")
54
+ .replace(/(^|\W)_([^_\s][^_]*)_(?!\w)/g, "$1$2");
55
+ }
56
+
57
+ /**
58
+ * Markdown as styled lines that fit `width`: `#` headings bold (a blank line before each but the first), paragraphs
59
+ * wrapped, `- ` / `1. ` lists as hanging bullets, fenced code as indented commands (fitted, never re-wrapped), inline
60
+ * `code` as a command. Tables and HTML are not used in the topics.
61
+ */
62
+ export function renderMarkdown(ui , md , width = ui.width) {
63
+ const { s } = ui;
64
+ const w = Math.max(20, width);
65
+ const out = [];
66
+ const blank = () => { if (out.length > 0 && out.at(-1) !== "") out.push(""); };
67
+ const lines = md.replace(/\r\n/g, "\n").split("\n");
68
+ let para = [];
69
+ let item = null;
70
+ const flushPara = () => {
71
+ if (para.length > 0) { blank(); out.push(...wrapAtoms(richAtoms(s, inline(para.join(" "))), w, w)); para = []; }
72
+ };
73
+ const flushItem = () => {
74
+ if (!item) return;
75
+ const lead = ` ${item.lead} `;
76
+ const hang = displayWidth(lead);
77
+ wrapAtoms(richAtoms(s, inline(item.text)), w - hang, w - hang).forEach((l, i) => out.push((i === 0 ? s("muted", lead) : " ".repeat(hang)) + l));
78
+ item = null;
79
+ };
80
+ let inList = false;
81
+ for (let i = 0; i < lines.length; i++) {
82
+ const l = lines[i] ;
83
+ if (/^```/.test(l)) {
84
+ flushPara(); flushItem(); inList = false;
85
+ blank();
86
+ for (i++; i < lines.length && !/^```/.test(lines[i] ); i++) {
87
+ const code = lines[i] .replace(/\s+$/, "");
88
+ if (code === "") { out.push(""); continue; }
89
+ for (const c of fitLine(" " + code, w, 2)) out.push(s("key", c));
90
+ }
91
+ continue;
92
+ }
93
+ const h = /^(#{1,6})\s+(.*)$/.exec(l);
94
+ if (h) {
95
+ flushPara(); flushItem(); inList = false;
96
+ blank();
97
+ out.push(...fitLine(s("title", inline(h[2] ).replace(/`/g, "")), w));
98
+ continue;
99
+ }
100
+ const li = /^\s*(?:[-*+]|(\d+)\.)\s+(.*)$/.exec(l);
101
+ if (li) {
102
+ flushPara(); flushItem();
103
+ if (!inList) blank();
104
+ inList = true;
105
+ item = { lead: li[1] !== undefined ? `${li[1]}.` : s.sym.bullet, text: li[2] };
106
+ continue;
107
+ }
108
+ if (l.trim() === "") { flushPara(); flushItem(); inList = false; continue; }
109
+ if (item && /^\s+\S/.test(l)) { item.text += " " + l.trim(); continue; }
110
+ flushItem(); inList = false;
111
+ para.push(l.trim());
112
+ }
113
+ flushPara(); flushItem();
114
+ return out.map((x) => x.replace(/ +$/, ""));
115
+ }
116
+
117
+ /** The topics with their summaries in `lang` (English summary when a translation is missing). */
118
+ export function renderTopicList(ui , dir , width = ui.width) {
119
+ const { s } = ui;
120
+ const rows = HELP_TOPICS.map((t) => ({ t, sum: dir === null ? "" : topicSummary(readTopic(dir, t, ui.lang) ?? "") }));
121
+ const nameW = Math.max(...rows.map((r) => displayWidth(r.t)));
122
+ const col = 2 + nameW + 2;
123
+ const out = [...fitLine(s("title", ui.t("help.topicsTitle")), width), ""];
124
+ for (const r of rows) {
125
+ if (width >= 50) {
126
+ wrapAtoms(r.sum.split(" "), width - col, width - col).forEach((l, i) => out.push((i === 0 ? " " + s("key", r.t) + " ".repeat(col - 2 - displayWidth(r.t)) : " ".repeat(col)) + l));
127
+ if (r.sum === "") out.push(" " + s("key", r.t));
128
+ } else {
129
+ out.push(" " + s("key", r.t));
130
+ for (const l of wrapAtoms(r.sum.split(" "), width - 4, width - 4)) out.push(" " + l);
131
+ }
132
+ }
133
+ out.push("", ...wrapAtoms(richAtoms(s, ui.t("help.topicsHint")), width, width));
134
+ return out.map((x) => x.replace(/ +$/, ""));
135
+ }
136
+
137
+ export async function helpCommand(args , io , deps = {}) {
138
+ const ui = cliUi(io);
139
+ const width = ui.width;
140
+ const dir = deps.dir ?? helpDir();
141
+ const extra = args.filter((a) => a !== "--help" && a !== "-h");
142
+ if (extra.length > 1 || extra.some((a) => a.startsWith("-"))) {
143
+ io.stderr(`${ui.t("help.usage")}\n`);
144
+ return 2;
145
+ }
146
+ if (extra.length === 0) { io.stdout(renderTopicList(ui, dir, width).join("\n") + "\n"); return 0; }
147
+ const name = extra[0] ;
148
+ if ((HELP_TOPICS ).includes(name)) {
149
+ const md = dir === null ? null : readTopic(dir, name, ui.lang);
150
+ if (md === null) { io.stderr(`${ui.t("help.missing", { topic: name })}\n`); return 1; }
151
+ io.stdout(renderMarkdown(ui, md, width).join("\n") + "\n");
152
+ return 0;
153
+ }
154
+ const cmd = commandHelp(name, ui.lang);
155
+ if (cmd !== null) { io.stdout(renderHelpText(ui, cmd, width).join("\n") + "\n"); return 0; }
156
+ io.stderr([ui.t("help.unknown", { topic: name }), "", ...renderTopicList(ui, dir, width)].join("\n") + "\n");
157
+ return 2;
158
+ }
@@ -0,0 +1,224 @@
1
+ // t3sm merge: bring work continued in a terminal into T3 Code as a revision thread (spec §4.6, src/ops/merge.ts).
2
+ // Flow: neither --session nor --all, or --dry-run: list the candidates (read-only, no lock) and exit 0. Writing without
3
+ // --yes on a non-terminal: exit 2 before anything else. Otherwise: lock -> recoverPendingMtimes -> connect -> fresh plan
4
+ // -> candidates -> confirm -> run-start (only once something is written) -> merges -> run-end.
5
+
6
+ import { homedir } from "node:os";
7
+ import { join } from "node:path";
8
+ import { expandHome, stateDir } from "../../core/paths.js";
9
+ import { Journal, newRunId, recoverPendingMtimes } from "../../core/journal.js";
10
+ import { acquireLock } from "../../core/lock.js";
11
+ import { connectT3, } from "../../t3/api.js";
12
+ import { STOP_SIGNALS, } from "../../apply/apply.js";
13
+
14
+ import {
15
+ FAILED_REASONS, executeMerges, findMergeCandidates, setMergePending,
16
+ } from "../../ops/merge.js";
17
+ import { freshPlan } from "./plan.js";
18
+ import { parseFlags } from "./quarantine.js";
19
+ import { cliUi, confirm, } from "../ui.js";
20
+ import { flagsOf } from "../flags.js";
21
+ import { table } from "../../ui/components.js";
22
+ import { bulletLines, fitLine, noteLines, textLines } from "../screen.js";
23
+ import { folderName } from "../words.js";
24
+ import { shownText } from "../../plan/names.js";
25
+ import { reportLockBusy } from "../locked.js";
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+
36
+
37
+ const processSignals = {
38
+ on: (sig, fn) => void process.on(sig , fn),
39
+ off: (sig, fn) => void process.off(sig , fn),
40
+ };
41
+
42
+ /** Why a session is not merged, in words (a catalogue key per reason). */
43
+ const REASON_KEY = {
44
+ "active": "merge.why.active", "not-continued": "merge.why.notContinued", "rehomed-copy": "merge.why.rehomedCopy",
45
+ "no-t3-marker": "merge.why.noT3Marker", "broken-chain": "merge.why.brokenChain", "corrupt-lines": "merge.why.corruptLines",
46
+ "compacted": "merge.why.compacted", "unsettled": "merge.why.unsettled", "thread-archived": "merge.why.threadArchived",
47
+ "revision-in-use": "merge.why.revisionInUse", "already-merged": "merge.why.alreadyMerged", "target-exists": "merge.why.targetExists",
48
+ "copy-failed": "merge.why.copyFailed", "import-failed": "merge.why.importFailed", "import-unverified": "merge.why.importUnverified",
49
+ "project-in-use": "merge.why.projectInUse", "archive-failed": "merge.why.archiveFailed", "over-cap": "merge.why.overCap",
50
+ "clock-jump": "merge.why.clockJump", "file-busy": "merge.why.fileBusy", "aborted": "merge.why.aborted",
51
+ };
52
+
53
+ const short = (id ) => id.slice(0, 8);
54
+
55
+
56
+
57
+ /** The candidates as a table: project, session, last terminal activity, messages added, the T3 title. */
58
+ export function candidateTable(ui , cs , width = ui.width) {
59
+ const { s, t, f } = ui;
60
+ const rows = cs.map((c) => ({
61
+ project: shownText(folderName(c.projectRoot), 60), session: short(c.nativeId),
62
+ when: c.lastActivity && Number.isFinite(Date.parse(c.lastActivity)) ? f.date(c.lastActivity) : "-",
63
+ added: `+${f.n(c.addedMessages)}`, title: shownText(c.oldTitle, 80),
64
+ }));
65
+ return table(s, [
66
+ { header: t("merge.col.project"), get: (r) => (r ).project, priority: 8 },
67
+ { header: t("merge.col.session"), get: (r) => (r ).session, priority: 9, min: 8 },
68
+ { header: t("merge.col.when"), get: (r) => (r ).when, priority: 5 },
69
+ { header: t("merge.col.added"), get: (r) => (r ).added, align: "right", priority: 7 },
70
+ { header: t("merge.col.title"), get: (r) => (r ).title, priority: 4 },
71
+ ], rows, width);
72
+ }
73
+
74
+ /** Terminal work on a side branch: never merged automatically; the user recovers it in a terminal. */
75
+ function orphanLines(ui , o , width ) {
76
+ if (o.length === 0) return [];
77
+ const { s, t } = ui;
78
+ return ["", ...noteLines(s, "warn", t("merge.orphaned", { n: o.length }), width),
79
+ ...o.flatMap((x) => bulletLines(s, `${shownText(folderName(x.projectRoot), 60)} ${short(x.nativeId)}: \`claude --resume ${x.nativeId}\``, width))];
80
+ }
81
+
82
+ /** Why the other sessions are not merged, counted per reason (the ones that were simply not continued are left out). */
83
+ function skipLines(ui , sk , width ) {
84
+ const by = new Map ();
85
+ for (const x of sk) if (x.reason !== "not-continued") by.set(x.reason, (by.get(x.reason) ?? 0) + 1);
86
+ return [...by].flatMap(([r, n]) => bulletLines(ui.s, ui.t("merge.notMergedCount", { n, why: ui.t(REASON_KEY[r]) }), width));
87
+ }
88
+
89
+ /**
90
+ * The listing of `t3sm merge`: how many sessions were continued outside T3 Code, the table, why others are not merged,
91
+ * terminal work on side branches, and (listing only) what a merge would do.
92
+ */
93
+ export function renderMergeList(ui , chosen , found , o , width = ui.width) {
94
+ const { s, t } = ui;
95
+ if (chosen.length === 0) {
96
+ return [...noteLines(s, "ok", t("merge.none"), width), ...skipLines(ui, found.skipped, width), ...orphanLines(ui, found.orphaned, width)];
97
+ }
98
+ const out = [...noteLines(s, "info", t("merge.found", { n: chosen.length }), width), "", ...candidateTable(ui, chosen, width)];
99
+ const branches = chosen.filter((c) => c.divergedLeaves > 0);
100
+ for (const c of branches) out.push(...bulletLines(s, t("merge.otherBranches", { session: short(c.nativeId), n: c.divergedLeaves }), width));
101
+ if (o.all) { const k = skipLines(ui, found.skipped, width); if (k.length > 0) out.push("", ...k); out.push(...orphanLines(ui, found.orphaned, width)); }
102
+ if (o.listOnly) out.push("", ...textLines(s, t("merge.howTo"), width));
103
+ return out;
104
+ }
105
+
106
+ /** What a merge did: each new thread, how to continue it, and what could not be merged. */
107
+ export function renderMergeResult(ui , r , runId , width = ui.width) {
108
+ const { s, t, f } = ui;
109
+ const out = [];
110
+ if (r.merged.length > 0) {
111
+ out.push(...noteLines(s, "ok", runId ? t("merge.doneRun", { n: r.merged.length, runId }) : t("merge.done", { n: r.merged.length }), width));
112
+ for (const m of r.merged) {
113
+ out.push("", ...fitLine(`${s("title", shownText(folderName(m.projectRoot), 60))} ${s("muted", s.sym.sep)} ${short(m.nativeId)}`, width, 2));
114
+ out.push(...bulletLines(s, t("merge.newThread", { thread: shownText(m.newThreadId, 80), n: f.n(m.addedMessages) }), width));
115
+ out.push(...bulletLines(s, t("merge.terminal", { id: m.revisionUuid }), width));
116
+ out.push(...bulletLines(s, t("merge.oldTitle", { title: shownText(m.oldTitle, 80) }), width));
117
+ if (m.divergedLeaves > 0) out.push(...bulletLines(s, t("merge.branchesLeft", { n: m.divergedLeaves }), width));
118
+ }
119
+ out.push("", ...textLines(s, t("merge.note"), width));
120
+ }
121
+ for (const x of r.skipped) out.push(...noteLines(s, "warn", t("merge.notMerged", { session: short(x.nativeId), why: t(REASON_KEY[x.reason]) }), width));
122
+ return out;
123
+ }
124
+
125
+ export async function mergeCommand(args , io , deps = {}) {
126
+ const spec = flagsOf("merge");
127
+ const p = parseFlags(args, io, "merge", spec.bool, spec.valued);
128
+ if (!p) return 2;
129
+ const session = p.values.get("--session") ?? null;
130
+ const all = p.flags.has("--all");
131
+ const ui = cliUi(io, { now: deps.now });
132
+ const say = (l ) => io.stdout(l.join("\n") + "\n");
133
+ if (session !== null && all) { io.stderr(`${ui.t("merge.eitherOr")}\n`); return 2; }
134
+ const listOnly = p.flags.has("--dry-run") || (session === null && !all);
135
+ const yes = p.flags.has("--yes");
136
+ if (!listOnly && !yes && !io.isTTY) {
137
+ io.stderr(`${ui.t("merge.needsYes")}\n`);
138
+ return 2;
139
+ }
140
+
141
+ const home = deps.home ?? homedir();
142
+ const now = deps.now ?? Date.now;
143
+ const dir = stateDir(io.env, home);
144
+ const journal = new Journal(join(dir, "journal.jsonl"));
145
+ const connect = deps.connect ?? connectT3;
146
+ const notice = (l ) => io.stderr(`${l}\n`);
147
+
148
+ const lock = listOnly ? null : await acquireLock(dir);
149
+ if (!listOnly && !lock) { reportLockBusy(io); return 0; }
150
+ const signals = deps.signals ?? processSignals;
151
+ let abort = false;
152
+ const onSignal = () => { abort = true; };
153
+ for (const sig of STOP_SIGNALS) signals.on(sig, onSignal);
154
+ try {
155
+ if (!listOnly) {
156
+ const rec = await recoverPendingMtimes(journal);
157
+ if (rec.restored.length > 0) io.stderr(`${ui.t("apply.recovered", { n: rec.restored.length })}\n`);
158
+ }
159
+ const api = await connect(home, { allowUntested: p.flags.has("--allow-untested"), manageProviders: false, onNotice: notice });
160
+ try {
161
+ const fp = await freshPlan(api, {
162
+ home, env: io.env, now, adapters: deps.adapters, existsDir: deps.existsDir, missingConfig: "memory", onNotice: notice, readOnly: listOnly,
163
+ });
164
+ let runId = null;
165
+ const mdeps = {
166
+ api, journal, now, stateDir: dir, readOnly: listOnly, retryFailed: true, exposureItems: fp.plan.items, batch: fp.config.batch,
167
+ accountHomes: Object.fromEntries(fp.config.accounts.map((a) => [a.id, expandHome(a.home, home)])),
168
+ aborted: () => abort,
169
+ runId: async () => {
170
+ runId = newRunId(new Date(now()));
171
+ await journal.append({ t: "run-start", runId, at: new Date(now()).toISOString(), command: `merge${session ? ` --session ${session}` : " --all"}` });
172
+ return runId;
173
+ },
174
+ };
175
+ const found = await findMergeCandidates(fp.plan.items, mdeps);
176
+ let chosen = found.candidates;
177
+ if (session !== null) {
178
+ const want = session.toLowerCase();
179
+ const ids = [...new Set(fp.plan.items.filter((i) => i.session.harness === "claude").map((i) => i.session.nativeId))];
180
+ const exact = ids.filter((id) => id.toLowerCase() === want);
181
+ const matches = exact.length > 0 ? exact : want.length >= 8 ? ids.filter((id) => id.toLowerCase().startsWith(want)) : [];
182
+ if (matches.length !== 1) {
183
+ io.stderr(`${matches.length === 0 ? ui.t("merge.noSession", { id: shownText(session, 80) }) : ui.t("merge.ambiguous", { id: shownText(session, 80), n: matches.length })}\n`);
184
+ return 2;
185
+ }
186
+ const id = matches[0] ;
187
+ chosen = found.candidates.filter((c) => c.nativeId === id);
188
+ if (chosen.length === 0) {
189
+ const why = found.skipped.find((s) => s.nativeId === id)?.reason;
190
+ say([...noteLines(ui.s, "ok", ui.t("merge.nothingFor", { session: short(id), why: why ? ui.t(REASON_KEY[why]) : ui.t("merge.why.notInT3") }), ui.width),
191
+ ...orphanLines(ui, found.orphaned.filter((o) => o.nativeId === id), ui.width)]);
192
+ return 0;
193
+ }
194
+ }
195
+
196
+ say(renderMergeList(ui, chosen, found, { listOnly, all: session === null }));
197
+ if (chosen.length === 0 || listOnly) return 0;
198
+ if (!yes) {
199
+ io.stdout("\n");
200
+ if (!(await confirm(io, ui.t("merge.confirm", { n: chosen.length })))) { io.stdout(`${ui.t("common.nothingChanged")}\n`); return 0; }
201
+ }
202
+
203
+ let status = "aborted";
204
+ let r ;
205
+ try {
206
+ r = await executeMerges(chosen, mdeps);
207
+ const failed = r.skipped.filter((s) => FAILED_REASONS.has(s.reason)).length;
208
+ status = abort ? "aborted" : failed > 0 ? "partial" : "ok";
209
+ } finally {
210
+ if (runId !== null) await journal.append({ t: "run-end", runId, at: new Date(now()).toISOString(), status });
211
+ }
212
+ if (r.merged.length > 0) await setMergePending(dir, Math.max(0, found.candidates.length - r.merged.length), new Date(now()));
213
+
214
+ if (r.merged.length > 0 || r.skipped.length > 0) say(["", ...renderMergeResult(ui, r, runId)]);
215
+ if (abort) { io.stderr(`${ui.t("merge.interrupted")}\n`); return 130; }
216
+ return r.skipped.some((s) => FAILED_REASONS.has(s.reason)) ? 5 : 0;
217
+ } finally {
218
+ await api.close();
219
+ }
220
+ } finally {
221
+ for (const sig of STOP_SIGNALS) signals.off(sig, onSignal);
222
+ await lock?.release();
223
+ }
224
+ }