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,70 @@
1
+ // Readable titles for imported threads (spec §5.2). T3 Code titles an imported Claude thread from its `custom-title` /
2
+ // `ai-title` record when present, else from the first user message, which in real histories is often technical
3
+ // (`<command-name>/model</command-name>`, `<ide_opened_file>…`, `[external unsupported block: image]`).
4
+ // `proposeTitle` computes a clean one; `isTechnicalTitle` tells the planner which current titles deserve replacing.
5
+ import { cleanText, truncateTitle } from "../plan/names.js";
6
+ import { extractText, obj, scanJsonl } from "../sources/jsonl.js";
7
+
8
+ const TAG_ONLY_RE = /<\/?[A-Za-z][\w-]*(?:\s[^<>]*)?\/?>/g;
9
+
10
+ /** Starts with a tag, an external-block marker or a caveat, or nothing but tags and whitespace is left. */
11
+ export function isTechnicalTitle(t ) {
12
+ const s = t.trim();
13
+ if (s === "" || s.startsWith("<") || s.startsWith("[external") || s.startsWith("Caveat:")) return true;
14
+ return cleanText(s.replace(TAG_ONLY_RE, " ")) === "";
15
+ }
16
+
17
+ // Blocks removed whole when closed: command plumbing, IDE context, reminders, environment, browser notes.
18
+ const BLOCK_RE = /<(command-[\w-]+|local-command-[\w-]+|ide_[\w-]+|system-reminder|environment_context|browser_instruction)(?:\s[^>]*)?>[\s\S]*?<\/\1>/g;
19
+ // An opening tag of the same family that never closes: its line goes.
20
+ const OPEN_LINE_RE = /^[^\S\n]*<(?:command-[\w-]+|local-command-[\w-]+|ide_[\w-]+|system-reminder|environment_context|browser_instruction)(?:\s[^>]*)?>.*$/gm;
21
+ const EXTERNAL_RE = /\[external [^\]\n]*\]/g;
22
+ const CAVEAT_LINE_RE = /^[^\S\n]*Caveat:.*$/gm;
23
+ const INTERRUPT_RE = /\[Request interrupted by user(?: for tool use)?\]/g;
24
+ const COMMAND_NAME_RE = /<command-name>\s*([^<]*?)\s*<\/command-name>/;
25
+
26
+
27
+
28
+ function strip(raw ) {
29
+ const command = COMMAND_NAME_RE.exec(raw)?.[1] || null;
30
+ const text = cleanText(
31
+ raw.replace(BLOCK_RE, " ").replace(OPEN_LINE_RE, " ").replace(EXTERNAL_RE, " ").replace(INTERRUPT_RE, " ").replace(CAVEAT_LINE_RE, " "),
32
+ );
33
+ return { text, command };
34
+ }
35
+
36
+ const str = (v ) => (typeof v === "string" ? cleanText(v) : "");
37
+
38
+ /**
39
+ * Latest `custom-title`, else latest `ai-title`, else latest `summary`, else the first user message that is not
40
+ * tool plumbing once technical blocks are removed (a lone slash command counts only when nothing real follows).
41
+ * Cleaned with `cleanText` and cut to `maxLength` graphemes in the middle; null when nothing remains or the file
42
+ * cannot be read.
43
+ */
44
+ export async function proposeTitle(file , o ) {
45
+ let custom = "";
46
+ let ai = "";
47
+ let summary = "";
48
+ let firstText = "";
49
+ let firstCommand = "";
50
+ try {
51
+ await scanJsonl(file, {}, (rec) => {
52
+ const type = rec["type"];
53
+ if (type === "custom-title") custom = str(rec["customTitle"]) || custom;
54
+ else if (type === "ai-title") ai = str(rec["aiTitle"]) || ai;
55
+ else if (type === "summary") summary = str(rec["summary"]) || summary;
56
+ else if (type === "user" && firstText === "") {
57
+ if (rec["isMeta"] === true || rec["isSidechain"] === true || rec["isCompactSummary"] === true || rec["isVisibleInTranscriptOnly"] === true) return;
58
+ const content = obj(rec["message"])?.["content"];
59
+ const s = strip(extractText(content));
60
+ if (s.text !== "") firstText = s.text;
61
+ else if (s.command !== null && firstCommand === "") firstCommand = s.command;
62
+ }
63
+ });
64
+ } catch {
65
+ return null;
66
+ }
67
+ const best = custom || ai || summary || firstText || firstCommand;
68
+ const clean = cleanText(best);
69
+ return clean === "" ? null : truncateTitle(clean, o.maxLength);
70
+ }
@@ -0,0 +1,73 @@
1
+ // Types of `t3sm organize` (spec §5): the plan of what to archive, retitle, show (unsettle), settle and pin in T3 Code.
2
+
3
+
4
+
5
+
6
+
7
+ /**
8
+ * One change to make in T3 Code. `previous` / `next` are what the journal's `organize-change` records, per kind:
9
+ * - archive: thread `archived` flag, false -> true (target: thread id)
10
+ * - title: thread title, current -> proposal (target: thread id)
11
+ * - unsettle: thread `settledOverride`, "settled" (or null: no override) -> "active" (target: thread id)
12
+ * - settle: thread `settledOverride`, "active" (or null) -> "settled", or `{ settledAt }` (ISO, the activity date) when
13
+ * the settle is backdated (target: thread id). `settleShown` (src/organize/history.ts) is how both kinds compare with
14
+ * T3's state: `{ settledAt }` is "settled", and a null `previous` (T3 cannot clear an override) is the side the
15
+ * change left ("active" for settle, "settled" for unsettle).
16
+ * - pin / unpin: project `pinned` flag, false -> true / true -> false (target: project id)
17
+ * - project-delete: `{ title, workspaceRoot }` -> null (target: project id)
18
+ * - auto-settle: `sidebarAutoSettleAfterDays`, current -> wanted (target: "sidebarAutoSettleAfterDays")
19
+ * - project-title: project title, current -> clean title (target: project id); planned by `t3sm projects rename
20
+ * --suggest` (src/organize/rename.ts), never by buildOrganizePlan.
21
+ */
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+
36
+
37
+
38
+
39
+
40
+
41
+
42
+
43
+
44
+
45
+
46
+
47
+
48
+
49
+
50
+
51
+
52
+
53
+
54
+
55
+
56
+
57
+
58
+
59
+
60
+
61
+
62
+
63
+
64
+
65
+
66
+
67
+
68
+
69
+
70
+
71
+
72
+
73
+
@@ -0,0 +1,104 @@
1
+ // Where a session goes by its folder and session categories (spec §4.1–§4.4): imported as is, skipped (and why), or
2
+ // rehomed (a copy imported into another project, because T3 Code refuses its folder). Pure: the planner applies it.
3
+
4
+
5
+ import { isDecided, organizeSettings } from "../core/config.js";
6
+ import { globToRegExp } from "../core/glob.js";
7
+ import { expandHome, normalizeCwd, sameCwd } from "../core/paths.js";
8
+ import { classifyFolder, isT3Refused, } from "./folders.js";
9
+
10
+ /** The questions (`organize.decided` keys) a plan can find unanswered, in report order. */
11
+
12
+ export const PENDING_KEYS = ["home", "t3-refused", "temp", "system", "automated", "orphaned"];
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+ /** The default General folders (`organize.generalFolder` unset), one per language. */
35
+ export const DEFAULT_GENERAL_FOLDERS = { pt: "~/T3 Geral", en: "~/T3 General" } ;
36
+
37
+ /**
38
+ * The one General folder (ruling R10): `organize.generalFolder` when set; else a live T3 project already at a default
39
+ * General folder (either language: `lang`'s first), reused as it is; else `lang`'s default. Expanded and normalized.
40
+ */
41
+ export function resolveGeneralFolder(config , lang , liveRoots , o ) {
42
+ const norm = (p ) => normalizeCwd(expandHome(p, o.home), o.platform);
43
+ if (config.organize?.generalFolder !== undefined) return norm(config.organize.generalFolder);
44
+ const other = lang === "pt" ? "en" : "pt";
45
+ for (const d of [DEFAULT_GENERAL_FOLDERS[lang], DEFAULT_GENERAL_FOLDERS[other]]) {
46
+ const hit = liveRoots.find((r) => sameCwd(r, norm(d), o.platform));
47
+ if (hit !== undefined) return normalizeCwd(hit, o.platform);
48
+ }
49
+ return norm(DEFAULT_GENERAL_FOLDERS[lang]);
50
+ }
51
+
52
+ /** `generalFolder`: the resolved General folder (resolveGeneralFolder); default: `organize.generalFolder` for `lang`. */
53
+ export function categoryRules(config , lang , folderEnv , generalFolder ) {
54
+ const organize = organizeSettings(config, lang);
55
+ const { platform, home } = folderEnv;
56
+ return {
57
+ organize, folderEnv,
58
+ generalFolder: generalFolder ?? normalizeCwd(expandHome(organize.generalFolder, home), platform),
59
+ decided: (k) => isDecided(config, k),
60
+ overrides: organize.overrides.map((o) => ({ re: globToRegExp(expandHome(o.match, home), platform), action: o.action })),
61
+ };
62
+ }
63
+
64
+ const SKIP_REASON = {
65
+ home: "t3-refused", "t3-refused": "t3-refused", temp: "temp-folder", system: "system-folder",
66
+ };
67
+
68
+ /**
69
+ * The route of a session whose (effective, normalized) folder is `cwd`. Rules, in order:
70
+ * 1. `automated` sessions: skipped while `sessions.automated` is "skip" (or undecided).
71
+ * 2. The first `overrides` rule matching the folder wins over its category ("skip" = excluded).
72
+ * 3. `project` folders are imported as is; any other category waits for its question, then follows `folders`.
73
+ * A folder T3 Code refuses (home, t3-refused) is never imported as is: "import" there means a rehomed copy, and a
74
+ * session t3sm cannot copy (`canCopy` false: Pi) is skipped `t3-refused`.
75
+ */
76
+ export function routeOf(s , cwd , r , canCopy ) {
77
+ if (s.origin === "automated") {
78
+ if (!r.decided("automated")) return { kind: "skip", reason: "undecided", pending: "automated" };
79
+ if (r.organize.sessions.automated === "skip") return { kind: "skip", reason: "automated" };
80
+ }
81
+ const refused = isT3Refused(cwd, r.folderEnv);
82
+ const rehome = (target ) => {
83
+ if (canCopy) return { kind: "rehome", target };
84
+ return refused ? { kind: "skip", reason: "t3-refused" } : { kind: "native" };
85
+ };
86
+ const o = r.overrides.find((x) => x.re.test(cwd));
87
+ if (o) {
88
+ if (o.action === "skip") return { kind: "skip", reason: "excluded" };
89
+ if (o.action === "import") return refused ? rehome(null) : { kind: "native" };
90
+ const { platform, home } = r.folderEnv;
91
+ const target = normalizeCwd(expandHome(o.action.slice("rehome:".length).trim(), home), platform);
92
+ // Never a destination T3 Code would refuse, nor a temp or system folder (spec 4.3, 3.4).
93
+ if (canCopy && classifyFolder(target, r.folderEnv) !== "project") return { kind: "skip", reason: "t3-refused", badTarget: o.action.slice("rehome:".length).trim() };
94
+ return rehome(target);
95
+ }
96
+ const cat = classifyFolder(cwd, r.folderEnv);
97
+ if (cat === "project") return { kind: "native" };
98
+ if (refused && !canCopy) return { kind: "skip", reason: "t3-refused" }; // whatever the answer
99
+ if (!r.decided(cat)) return { kind: "skip", reason: "undecided", pending: cat };
100
+ const action = r.organize.folders[cat];
101
+ if (action === "skip") return { kind: "skip", reason: SKIP_REASON[cat] };
102
+ if (action === "import" && !refused) return { kind: "native" };
103
+ return rehome(null);
104
+ }
@@ -0,0 +1,137 @@
1
+ // Picks one copy per session (spec §4.3 rule 2): copies of one `harness:nativeId` are resolved by backup status,
2
+ // then by size/mtime inside one account (drive-case variant dirs), then by content across accounts.
3
+
4
+
5
+ import { resolveRemap } from "../core/config.js";
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+  
17
+
18
+
19
+
20
+
21
+ const isBackup = (s ) => s.flags.includes("backup-copy");
22
+
23
+ /** Larger file, then newer mtime, then path (deterministic). */
24
+ function biggerNewer(a , b ) {
25
+ if (a.file.size !== b.file.size) return b.file.size - a.file.size;
26
+ if (a.file.mtimeMs !== b.file.mtimeMs) return b.file.mtimeMs - a.file.mtimeMs;
27
+ return a.file.path < b.file.path ? -1 : a.file.path > b.file.path ? 1 : 0;
28
+ }
29
+
30
+ export async function pickWinners(sessions , config , deps ) {
31
+ const platform = deps.platform ?? process.platform;
32
+ const groups = new Map ();
33
+ for (const s of sessions) {
34
+ const k = `${s.harness}:${s.nativeId}`;
35
+ const g = groups.get(k);
36
+ if (g) g.push(s);
37
+ else groups.set(k, [s]);
38
+ }
39
+ const acctOrder = (id ) => {
40
+ const i = config.accounts.findIndex((a) => a.id === id);
41
+ return i === -1 ? config.accounts.length : i;
42
+ };
43
+
44
+ const winners = [];
45
+ const losers = [];
46
+ const forks = [];
47
+
48
+ for (const group of groups.values()) {
49
+ if (group.length === 1) {
50
+ winners.push(group[0] );
51
+ continue;
52
+ }
53
+ const live = group.filter((s) => !isBackup(s));
54
+ const pool = live.length > 0 ? live : group;
55
+ const backupLosers = live.length > 0 ? group.filter(isBackup) : [];
56
+
57
+ // Inside one account (drive-case variant dirs like `d--X` / `D--X`). On win32/darwin the copies are picked by size,
58
+ // then mtime, without a content compare: a case-insensitive filesystem (NTFS, APFS default) cannot hold two such
59
+ // dirs at once, so both copies only coexist through a rename and the bigger/newer one is where work last happened.
60
+ // On case-sensitive platforms (linux) the two dirs really are distinct, so same-account copies go through the
61
+ // content compare below like cross-account copies (identical/prefix -> `case-variant` loser; diverged -> fork).
62
+ const foldsCase = platform === "win32" || platform === "darwin";
63
+ const byAccount = new Map ();
64
+ for (const s of pool) {
65
+ const k = s.accountId ?? "";
66
+ const g = byAccount.get(k);
67
+ if (g) g.push(s);
68
+ else byAccount.set(k, [s]);
69
+ }
70
+ const pending = [];
71
+ const candidates = [];
72
+ for (const g of byAccount.values()) {
73
+ if (!foldsCase) {
74
+ candidates.push(...g);
75
+ continue;
76
+ }
77
+ const sorted = [...g].sort(biggerNewer);
78
+ candidates.push(sorted[0] );
79
+ for (const s of sorted.slice(1)) pending.push({ session: s, winner: sorted[0] , relation: "case-variant" });
80
+ }
81
+ candidates.sort((a, b) => acctOrder(a.accountId) - acctOrder(b.accountId) || (a.file.path < b.file.path ? -1 : 1));
82
+
83
+ // Across accounts: by content.
84
+ const replacedBy = new Map ();
85
+ let heads = [];
86
+ for (const c of candidates) {
87
+ let placed = false;
88
+ for (let i = 0; i < heads.length; i++) {
89
+ const h = heads[i] ;
90
+ const rel = await deps.compareCopies(c.file.path, h.file.path);
91
+ if (rel === "diverged") continue;
92
+ placed = true;
93
+ let keep ;
94
+ let drop ;
95
+ let relation ;
96
+ const sameAccount = c.accountId === h.accountId;
97
+ if (rel === "identical" && sameAccount) {
98
+ relation = "case-variant";
99
+ [keep, drop] = biggerNewer(c, h) < 0 ? [c, h] : [h, c];
100
+ } else if (rel === "identical") {
101
+ relation = "identical";
102
+ const cwd = c.cwd ?? h.cwd;
103
+ const owner = cwd === null ? config.defaultAccount : (await deps.projectAccount(resolveRemap(cwd, config, platform).cwd)).accountId;
104
+ if (c.accountId === owner && h.accountId !== owner) [keep, drop] = [c, h];
105
+ else [keep, drop] = [h, c];
106
+ } else {
107
+ relation = sameAccount ? "case-variant" : "prefix";
108
+ [keep, drop] = rel === "a-extends-b" ? [c, h] : [h, c];
109
+ }
110
+ pending.push({ session: drop, winner: keep, relation });
111
+ if (keep === c) {
112
+ replacedBy.set(h, c);
113
+ heads[i] = c;
114
+ }
115
+ break;
116
+ }
117
+ if (!placed) heads.push(c);
118
+ }
119
+ heads = heads.filter((h) => !replacedBy.has(h));
120
+ const final = (s ) => {
121
+ let cur = s;
122
+ for (let r = replacedBy.get(cur); r !== undefined; r = replacedBy.get(cur)) cur = r;
123
+ if (heads.includes(cur)) return cur;
124
+ // A winner that later lost (e.g. a case-variant's account winner lost across accounts): follow its own loss.
125
+ const lost = pending.find((p) => p.session === cur);
126
+ return lost ? final(lost.winner) : cur;
127
+ };
128
+ for (const p of pending) losers.push({ session: p.session, winner: final(p.winner), relation: p.relation });
129
+ for (const b of backupLosers) {
130
+ const sameAcct = heads.find((h) => h.accountId === b.accountId) ?? heads[0] ;
131
+ losers.push({ session: b, winner: sameAcct, relation: "backup" });
132
+ }
133
+ winners.push(...heads);
134
+ if (heads.length > 1) forks.push([...heads]);
135
+ }
136
+ return { winners, losers, forks };
137
+ }
@@ -0,0 +1,82 @@
1
+
2
+ import { pathKey } from "../core/paths.js";
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+ function key(p , e ) {
16
+ return pathKey(p, e.platform);
17
+ }
18
+
19
+ function isInside(k , rootKey ) {
20
+ if (rootKey === "") return false;
21
+ return k.startsWith(rootKey.endsWith("/") ? rootKey : rootKey + "/");
22
+ }
23
+
24
+ function isUnderOrEqual(k , rootKey ) {
25
+ return k === rootKey || isInside(k, rootKey);
26
+ }
27
+
28
+ function envVar(e , name ) {
29
+ const direct = e.env[name];
30
+ if (direct) return direct;
31
+ if (e.platform !== "win32") return undefined;
32
+ const hit = Object.keys(e.env).find((k) => k.toLowerCase() === name.toLowerCase());
33
+ return hit ? e.env[hit] : undefined;
34
+ }
35
+
36
+ function homeSub(e , sub ) {
37
+ return key(e.home.replace(/[\\/]+$/, "") + "/" + sub, e);
38
+ }
39
+
40
+ function isHome(k , e ) {
41
+ return k === key(e.home, e);
42
+ }
43
+
44
+ /** The T3 rules except `home`: exact tmpdir, `/tmp`, `/private/tmp`; prefix Downloads, Documents/Codex, T3 base, T3 worktrees. */
45
+ function isRefusedNotHome(k , e ) {
46
+ if ([key(e.tmpdir, e), key("/tmp", e), key("/private/tmp", e)].includes(k)) return true;
47
+ const ancestors = [homeSub(e, "Downloads"), homeSub(e, "Documents/Codex"), key(e.t3BaseDir, e), key(e.t3WorktreesDir, e)];
48
+ return ancestors.some((a) => isUnderOrEqual(k, a));
49
+ }
50
+
51
+ /** Mirror of T3 Code 0.1.10 `AgentSessionScanner.isExcludedProjectPath`: folders T3 never imports (home included). */
52
+ export function isT3Refused(cwd , e ) {
53
+ const k = key(cwd, e);
54
+ return isHome(k, e) || isRefusedNotHome(k, e);
55
+ }
56
+
57
+ function isTemp(k , e ) {
58
+ if (isInside(k, key(e.tmpdir, e)) || isInside(k, key("/tmp", e)) || isInside(k, key("/private/tmp", e))) return true;
59
+ if (/^[a-z]:\/(tmp|temp)(\/|$)/i.test(k)) return true;
60
+ return k.split("/").some((s) => s.toLowerCase() === "scratchpad");
61
+ }
62
+
63
+ function isSystem(k , e ) {
64
+ if (e.platform === "win32") {
65
+ const roots = [envVar(e, "WINDIR"), envVar(e, "ProgramFiles"), envVar(e, "ProgramFiles(x86)"), envVar(e, "ProgramData")]
66
+ .filter((r) => !!r)
67
+ .map((r) => key(r, e));
68
+ roots.push(homeSub(e, "AppData"));
69
+ return roots.some((r) => isUnderOrEqual(k, r));
70
+ }
71
+ return ["/usr", "/etc", "/System", "/Library", "/opt"].some((r) => isUnderOrEqual(k, key(r, e)));
72
+ }
73
+
74
+ /** First match wins: home, t3-refused, temp, system, project. */
75
+ export function classifyFolder(cwd , e ) {
76
+ const k = key(cwd, e);
77
+ if (isHome(k, e)) return "home";
78
+ if (isRefusedNotHome(k, e)) return "t3-refused";
79
+ if (isTemp(k, e)) return "temp";
80
+ if (isSystem(k, e)) return "system";
81
+ return "project";
82
+ }
@@ -0,0 +1,93 @@
1
+ import { maskAddressesIn } from "../core/mask.js";
2
+
3
+ // Clean, unique, bounded titles for T3 projects (spec §4.5). `cleanText` and `truncateTitle` are shared with thread titles.
4
+
5
+ /** Folder names that say nothing about the project; the title then uses `parent/last`. Compared case-insensitively. */
6
+ export const GENERIC_SEGMENTS = [
7
+ "src", "source", "app", "apps", "frontend", "backend", "front", "back", "api", "web", "client", "server",
8
+ "main", "master", "project", "projects", "code", "repo", "lib", "packages", "www", "public", "dist", "build",
9
+ "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12",
10
+ ];
11
+
12
+ const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
13
+ const graphemes = (s ) => [...segmenter.segment(s)].map((g) => g.segment);
14
+
15
+ /** NFC, no control or invisible characters (a joiner survives only inside an emoji sequence), single spaces, trimmed. */
16
+ export function cleanText(s ) {
17
+ return s
18
+ .normalize("NFC")
19
+ .replace(/[\t\n\r\v\f]/g, " ")
20
+ .replace(/[\p{Cc}\p{Cf}]/gu, (c, i , all ) => (c === "\u200D" && /\p{Extended_Pictographic}\uFE0F?$/u.test(all.slice(0, i)) ? c : ""))
21
+ .replace(/\s+/g, " ")
22
+ .trim();
23
+ }
24
+
25
+ /**
26
+ * Untrusted text (a title, path, error or note from a transcript or T3 Code) made safe for one terminal line: no
27
+ * control or format characters, so no escape sequence reaches the terminal (cleanText), cut in the middle to `max`
28
+ * graphemes when given.
29
+ */
30
+ export function shownText(s , max ) {
31
+ const t = cleanText(typeof s === "string" ? s : String(s));
32
+ return max === undefined ? t : truncateTitle(t, max);
33
+ }
34
+
35
+ /**
36
+ * An account's display name (config.json's or T3 Code's) as t3sm shows it anywhere, --json included: safe for one line
37
+ * (shownText) and with any email address in it masked, since people often name an account after its email.
38
+ */
39
+ export function shownAccountName(name , max = 60) {
40
+ // Clean first (an invisible character inside an address must not hide it from the mask), then mask, then cut.
41
+ return truncateTitle(maskAddressesIn(cleanText(name)), max);
42
+ }
43
+
44
+ /** At most `max` graphemes, cut in the middle with "…" so the start and the end stay visible. */
45
+ export function truncateTitle(s , max ) {
46
+ const g = graphemes(s);
47
+ if (g.length <= max) return s;
48
+ if (max <= 1) return "…";
49
+ const keep = max - 1;
50
+ const head = Math.ceil(keep / 2);
51
+ return g.slice(0, head).join("") + "…" + g.slice(g.length - (keep - head)).join("");
52
+ }
53
+
54
+ function segmentsOf(root , platform ) {
55
+ const parts = root.split(platform === "win32" ? /[\\/]/ : "/").filter((x) => x !== "");
56
+ return parts.filter((x, i) => !(i === 0 && /^[A-Za-z]:$/.test(x)));
57
+ }
58
+
59
+ export function projectTitle(
60
+ root ,
61
+ taken ,
62
+ o ,
63
+ ) {
64
+ const segs = segmentsOf(root, o.platform).map(cleanText).filter((x) => x !== "");
65
+ const last = segs[segs.length - 1] ?? cleanText(root);
66
+ const parent = segs[segs.length - 2];
67
+ const grand = segs[segs.length - 3];
68
+ const great = segs[segs.length - 4];
69
+ const generic = GENERIC_SEGMENTS.includes(last.toLowerCase());
70
+ const base = truncateTitle(generic && parent ? `${parent}/${last}` : last, o.maxLength);
71
+ const used = new Set([...taken].map((t) => t.toLowerCase()));
72
+ const free = (t ) => !used.has(t.toLowerCase());
73
+ // The label is never cut; the base gives up room for it so the whole title stays within the limit.
74
+ const withLabel = (label ) => {
75
+ const suffix = ` · ${label}`;
76
+ const room = Math.max(8, o.maxLength - graphemes(suffix).length);
77
+ return truncateTitle(generic && parent ? `${parent}/${last}` : last, room) + suffix;
78
+ };
79
+ if (free(base)) return base;
80
+ // A `parent/last` base already shows the parent, so its labels start one level higher.
81
+ const labels = generic && parent
82
+ ? [grand, grand && great ? `${great}/${grand}` : undefined]
83
+ : [parent, parent && grand ? `${grand}/${parent}` : undefined];
84
+ for (const label of labels) {
85
+ if (label === undefined) continue;
86
+ const t = withLabel(label);
87
+ if (free(t)) return t;
88
+ }
89
+ for (let n = 2; ; n++) {
90
+ const t = `${truncateTitle(base, Math.max(8, o.maxLength - String(n).length - 3))} (${n})`;
91
+ if (free(t)) return t;
92
+ }
93
+ }