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,171 @@
1
+ import { createReadStream } from "node:fs";
2
+ import { mkdir, open, readdir, rename, rm, stat } from "node:fs/promises";
3
+ import { createHash, randomBytes } from "node:crypto";
4
+ import { dirname, join } from "node:path";
5
+
6
+ import { pidAlive } from "./pid.js";
7
+
8
+ /** Rename retries after the first attempt; the delays (10, 20, 40, ... ms, at most 250 each) add up to about 5 s. */
9
+ export const RENAME_RETRIES = 24;
10
+ const RETRYABLE = new Set(["EPERM", "EBUSY", "EACCES"]);
11
+
12
+ /** A rename Windows refused because another process has a file open (antivirus, indexer, a reader): worth retrying. */
13
+ export function renameRefused(e ) {
14
+ return RETRYABLE.has((e )?.code ?? "");
15
+ }
16
+
17
+ /** Delay before rename retry `attempt` (0-based): doubles from 10 ms, capped at 250 ms. */
18
+ export function renameRetryDelay(attempt ) {
19
+ return Math.min(10 * 2 ** attempt, 250);
20
+ }
21
+
22
+ function sleep(ms ) {
23
+ return new Promise((r) => setTimeout(r, ms));
24
+ }
25
+
26
+ /** What atomicWrite does to the world that tests replace: the final rename and the wait between its retries. */
27
+
28
+
29
+
30
+
31
+
32
+ /**
33
+ * Write `data` to `path` atomically: temp file in the same directory, fsync, rename.
34
+ * Creates parent directories. Windows refuses to rename over a file another process has open (a second t3sm
35
+ * reading config.json or a plan, an antivirus scan, a sync client): EPERM / EBUSY / EACCES. The rename alone is
36
+ * retried with a growing delay for about 5 s (RENAME_RETRIES, renameRetryDelay), then the error is thrown. The temp
37
+ * file never outlives a failure.
38
+ */
39
+ export async function atomicWrite(path , data , deps = {}) {
40
+ const doRename = deps.rename ?? rename;
41
+ const wait = deps.sleep ?? sleep;
42
+ await mkdir(dirname(path), { recursive: true });
43
+ const tmp = `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
44
+ try {
45
+ const fh = await open(tmp, "w");
46
+ try {
47
+ await fh.writeFile(data, "utf8");
48
+ await fh.sync();
49
+ } finally {
50
+ await fh.close();
51
+ }
52
+ await renameRetrying(tmp, path, { rename: doRename, sleep: wait });
53
+ } catch (e) {
54
+ await rm(tmp, { force: true }).catch(() => {});
55
+ throw e;
56
+ }
57
+ }
58
+
59
+ /**
60
+ * `rename(from, to)` over an existing `to`, retried like atomicWrite's (RENAME_RETRIES, renameRetryDelay) while Windows
61
+ * refuses it because another process has `to` open (EPERM / EBUSY / EACCES: an antivirus scan, the indexer). Any other
62
+ * error, or the last refusal, is thrown; the caller removes `from`.
63
+ */
64
+ export async function renameRetrying(from , to , deps = {}) {
65
+ const doRename = deps.rename ?? rename;
66
+ const wait = deps.sleep ?? sleep;
67
+ for (let attempt = 0; ; attempt++) {
68
+ try {
69
+ await doRename(from, to);
70
+ return;
71
+ } catch (e) {
72
+ if (!renameRefused(e) || attempt >= RENAME_RETRIES) throw e;
73
+ await wait(renameRetryDelay(attempt));
74
+ }
75
+ }
76
+ }
77
+
78
+ /**
79
+ * sha256 of a file's bytes. Resolves once the file is closed, not at the end of the data: Windows refuses to rename over
80
+ * or delete a file that is still open, and callers replace the file they just hashed (materialize's refresh).
81
+ */
82
+ export function sha256File(path ) {
83
+ return new Promise((resolve, reject) => {
84
+ const h = createHash("sha256");
85
+ const s = createReadStream(path);
86
+ let digest = null;
87
+ s.on("error", reject);
88
+ s.on("data", (c) => h.update(c));
89
+ s.on("end", () => { digest = h.digest("hex"); });
90
+ s.on("close", () => { if (digest !== null) resolve(digest); });
91
+ });
92
+ }
93
+
94
+ export async function statSafe(path ) {
95
+ try {
96
+ const s = await stat(path);
97
+ return { path, size: s.size, mtimeMs: s.mtimeMs, atimeMs: s.atimeMs };
98
+ } catch (e) {
99
+ if ((e ).code === "ENOENT") return null;
100
+ throw e;
101
+ }
102
+ }
103
+
104
+ /** A no-clobber move/publish refused before anything changed: destination exists, other drive, no hard links. */
105
+ export class MoveRefused extends Error {
106
+ name = "MoveRefused";
107
+ code ;
108
+ constructor(message , code ) {
109
+ super(message);
110
+ this.code = code;
111
+ }
112
+ }
113
+
114
+ /** The calls publishNoClobber makes; injected by tests (a file appearing at the destination, EXDEV). */
115
+
116
+
117
+
118
+
119
+
120
+ const LINK_UNSUPPORTED = new Set(["EPERM", "ENOTSUP", "ENOSYS", "EOPNOTSUPP", "EMLINK"]);
121
+ const codeOf = (e ) => (e ).code ?? (e instanceof Error ? e.message : String(e));
122
+
123
+ /**
124
+ * Gives FILE `from` the name `to` without ever replacing an existing entry (node's rename replaces a target file):
125
+ * link(from, to) then unlink(from). EEXIST at `to` -> MoveRefused("EEXIST"), nothing changed; EXDEV or a filesystem
126
+ * without hard links -> MoveRefused, nothing changed (never copy-and-delete). If `from` cannot be removed afterwards,
127
+ * the new name is dropped again (the exact previous state) and the error is thrown. The parent of `to` must exist.
128
+ */
129
+ export async function publishNoClobber(from , to , fs ) {
130
+ try {
131
+ await fs.link(from, to);
132
+ } catch (e) {
133
+ const code = codeOf(e);
134
+ if (code === "EEXIST") throw new MoveRefused(`${to} already exists; nothing was changed`, "EEXIST");
135
+ if (code === "EXDEV") throw new MoveRefused(`${to} is on another drive (EXDEV); not moved (t3sm never copies and deletes)`, "EXDEV");
136
+ if (LINK_UNSUPPORTED.has(code)) throw new MoveRefused(`this filesystem cannot hard-link (${code}); not moved (t3sm never copies and deletes)`, code);
137
+ throw e;
138
+ }
139
+ try {
140
+ await fs.unlink(from);
141
+ } catch (e) {
142
+ // Both names point at the same file: dropping the new name restores the exact previous state.
143
+ try {
144
+ await fs.unlink(to);
145
+ } catch (e2) {
146
+ throw new Error(`could not remove ${from} after linking it to ${to} (${codeOf(e)}), nor undo the link (${codeOf(e2)}); the file now has both names, nothing is lost`);
147
+ }
148
+ throw e;
149
+ }
150
+ }
151
+
152
+ /** Temp files of files t3sm writes into account folders: `.<uuid>.<pid>.<12 hex>.tmp` (not *.jsonl: no scanner reads it). */
153
+ export const WRITE_TEMP_RE = /^\.[0-9a-f-]{36}\.(\d+)\.[0-9a-f]{12}\.tmp$/;
154
+
155
+ /** A temp name next to a converted transcript or merge revision `<uuid>.jsonl` in `dir` (sweepWriteTemps finds it). */
156
+ export function writeTempPath(dir , uuid ) {
157
+ return join(dir, `.${uuid}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
158
+ }
159
+
160
+
161
+ /** Removes the write temps (WRITE_TEMP_RE) left in `dir` by t3sm processes that are gone; returns their paths. */
162
+ export async function sweepWriteTemps(dir , alive = pidAlive) {
163
+ const out = [];
164
+ for (const n of await readdir(dir).catch(() => [] )) {
165
+ const m = WRITE_TEMP_RE.exec(n);
166
+ if (!m || alive(Number(m[1]))) continue;
167
+ await rm(join(dir, n), { force: true }).catch(() => {});
168
+ out.push(join(dir, n));
169
+ }
170
+ return out;
171
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Compile a path glob to a RegExp. Match it against `normalizeCwd` output.
3
+ * `**` crosses `/`, `*` and `?` stay within one segment. Case-insensitive on win32.
4
+ */
5
+ export function globToRegExp(glob , platform = process.platform) {
6
+ const g = platform === "win32" ? glob.replace(/\\/g, "/") : glob;
7
+ let re = "";
8
+ for (let i = 0; i < g.length; i++) {
9
+ const c = g[i] ;
10
+ if (c === "*") {
11
+ if (g[i + 1] === "*") {
12
+ const before = i === 0 || g[i - 1] === "/";
13
+ const after = g[i + 2];
14
+ if (before && after === "/") {
15
+ re += "(?:.*/)?"; // "**/": zero or more directories
16
+ i += 2;
17
+ } else if (before && after === undefined && i > 0) {
18
+ re = re.replace(/\/$/, "") + "(?:/.*)?"; // trailing "/**"
19
+ i += 1;
20
+ } else {
21
+ re += ".*";
22
+ i += 1;
23
+ }
24
+ } else {
25
+ re += "[^/]*";
26
+ }
27
+ } else if (c === "?") {
28
+ re += "[^/]";
29
+ } else {
30
+ re += c.replace(/[.+^${}()|[\]\\]/g, "\\$&");
31
+ }
32
+ }
33
+ return new RegExp("^" + re + "$", platform === "win32" ? "i" : "");
34
+ }
@@ -0,0 +1,32 @@
1
+ // The history rule's stored values (spec §5.2), read without any I/O: src/organize/plan.ts uses it, and plan.ts is pure.
2
+ // src/core/config.ts re-exports these, so `import { historyRule } from "../core/config.js"` keeps working.
3
+
4
+
5
+ export const DEFAULT_HISTORY = Object.freeze({ days: 90, minPerProject: 10 });
6
+
7
+ /** A stored history value as a rule: 0.2 strings map ("all" -> all days, "days:N" -> N days, minimum 10), "off" is null. */
8
+ export function normalizeHistory(h ) {
9
+ if (h === undefined) return { ...DEFAULT_HISTORY };
10
+ if (h === "off") return null;
11
+ if (h === "all") return { days: "all", minPerProject: DEFAULT_HISTORY.minPerProject };
12
+ if (typeof h === "string") return { days: Number(h.slice("days:".length)), minPerProject: DEFAULT_HISTORY.minPerProject };
13
+ return { days: h.days ?? DEFAULT_HISTORY.days, minPerProject: h.minPerProject ?? DEFAULT_HISTORY.minPerProject };
14
+ }
15
+
16
+ /** The decided key of the 0.3 history question (days and a minimum per project); "history" alone was 0.2's. */
17
+ export const HISTORY_V2 = "history-v2";
18
+
19
+ /**
20
+ * organize.history as 0.2 stored it ("all", "off", "days:N") while the 0.3 question (HISTORY_V2) was never answered:
21
+ * the assistant asks that question once after the upgrade. Null otherwise (a 0.3 rule, nothing stored, or answered).
22
+ */
23
+ export function legacyHistory(c ) {
24
+ const h = c.organize?.history;
25
+ if (typeof h !== "string") return null;
26
+ return c.organize?.decided?.includes(HISTORY_V2) ? null : h;
27
+ }
28
+
29
+ /** The history rule of `c` (defaults filled); null = history off. */
30
+ export function historyRule(c ) {
31
+ return normalizeHistory(c.organize?.history);
32
+ }
@@ -0,0 +1,274 @@
1
+ import { mkdir, open, readFile, stat, utimes } from "node:fs/promises";
2
+ import { randomBytes } from "node:crypto";
3
+ import { dirname } from "node:path";
4
+
5
+ import { pathKey } from "./paths.js";
6
+
7
+ /** Mtime bumps in the journal without a matching restore (path identity per platform). Read-only. */
8
+ export function pendingMtimePaths(entries , platform = process.platform) {
9
+ const key = (p ) => pathKey(p, platform);
10
+ const pending = new Map ();
11
+ for (const e of entries) {
12
+ if (e.t === "mtime-bump" && Array.isArray(e.files)) {
13
+ for (const f of e.files) {
14
+ if (!f || typeof f.path !== "string" || f.path === "") continue;
15
+ const k = key(f.path);
16
+ let s = pending.get(k);
17
+ if (!s) pending.set(k, (s = { path: f.path, runs: new Set() }));
18
+ s.runs.add(e.runId);
19
+ }
20
+ } else if (e.t === "mtime-restore" && Array.isArray(e.paths)) {
21
+ for (const p of e.paths) if (typeof p === "string") pending.get(key(p))?.runs.delete(e.runId);
22
+ }
23
+ }
24
+ return [...pending.values()].filter((s) => s.runs.size > 0).map((s) => s.path);
25
+ }
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+ /**
36
+ * Append-only JSONL journal. One JSON object per line, UTF-8, "\n".
37
+ * `readAll()` sets `lastReadCorruptLines` to the number of unparseable/invalid
38
+ * lines skipped by that call (a truncated final line without newline is skipped silently).
39
+ */
40
+ // The file is created owner-only (0o600); win32 ignores the mode, so there it relies on the user profile ACLs.
41
+ export class Journal {
42
+ file ;
43
+ lastReadCorruptLines = 0;
44
+ #chain = Promise.resolve();
45
+
46
+ constructor(file ) {
47
+ this.file = file;
48
+ }
49
+
50
+ append(e ) {
51
+ const line = JSON.stringify(e) + "\n";
52
+ const run = this.#chain.then(() => this.#write(line));
53
+ this.#chain = run.catch(() => {});
54
+ return run;
55
+ }
56
+
57
+ async #write(line ) {
58
+ await mkdir(dirname(this.file), { recursive: true });
59
+ const fh = await open(this.file, "a+", 0o600);
60
+ try {
61
+ // Never glue a new entry onto a truncated tail left by a crash.
62
+ const { size } = await fh.stat();
63
+ let prefix = "";
64
+ if (size > 0) {
65
+ const b = Buffer.alloc(1);
66
+ await fh.read(b, 0, 1, size - 1);
67
+ if (b[0] !== 0x0a) prefix = "\n";
68
+ }
69
+ await fh.appendFile(prefix + line, "utf8");
70
+ await fh.sync();
71
+ } finally {
72
+ await fh.close();
73
+ }
74
+ }
75
+
76
+ async readAll() {
77
+ let text ;
78
+ try {
79
+ text = await readFile(this.file, "utf8");
80
+ } catch (e) {
81
+ if ((e ).code === "ENOENT") {
82
+ this.lastReadCorruptLines = 0;
83
+ return [];
84
+ }
85
+ throw e;
86
+ }
87
+ if (text.charCodeAt(0) === 0xfeff) text = text.slice(1);
88
+ const endsWithNewline = text.endsWith("\n");
89
+ const lines = text.split("\n");
90
+ if (endsWithNewline) lines.pop();
91
+ const out = [];
92
+ let corrupt = 0;
93
+ for (let i = 0; i < lines.length; i++) {
94
+ const raw = lines[i] .replace(/\r$/, "");
95
+ if (raw.trim() === "") continue;
96
+ const isTruncatedTail = i === lines.length - 1 && !endsWithNewline;
97
+ let v ;
98
+ try {
99
+ v = JSON.parse(raw);
100
+ } catch {
101
+ if (!isTruncatedTail) corrupt++;
102
+ continue;
103
+ }
104
+ if (isEntry(v)) out.push(v);
105
+ else corrupt++;
106
+ }
107
+ this.lastReadCorruptLines = corrupt;
108
+ return out;
109
+ }
110
+ }
111
+
112
+ function isEntry(v ) {
113
+ if (typeof v !== "object" || v === null) return false;
114
+ const o = v ;
115
+ return typeof o["t"] === "string" && typeof o["runId"] === "string";
116
+ }
117
+
118
+ export function newRunId(now ) {
119
+ const p = (n , w = 2) => String(n).padStart(w, "0");
120
+ const d = `${p(now.getUTCFullYear(), 4)}${p(now.getUTCMonth() + 1)}${p(now.getUTCDate())}`;
121
+ const t = `${p(now.getUTCHours())}${p(now.getUTCMinutes())}${p(now.getUTCSeconds())}`;
122
+ return `${d}-${t}-${randomBytes(2).toString("hex")}`;
123
+ }
124
+
125
+ /**
126
+ * The `file-written` entries that really happened, in journal order: each `file-write-aborted` cancels the latest
127
+ * earlier `file-written` of the same run and path (`key` = path identity, e.g. case-folded on win32). "Last written
128
+ * sha" logic must use this, or a write that lost its race would look like ours forever.
129
+ */
130
+ export function effectiveWrites(entries , key = (p) => p) {
131
+ const out = [];
132
+ for (const e of entries) {
133
+ if (e.t === "file-written" && typeof e.path === "string") out.push(e);
134
+ else if (e.t === "file-write-aborted" && typeof e.path === "string") {
135
+ const k = key(e.path);
136
+ for (let i = out.length - 1; i >= 0; i--) {
137
+ const w = out[i];
138
+ if (w && w.runId === e.runId && key(w.path) === k) { out[i] = null; break; }
139
+ }
140
+ }
141
+ }
142
+ return out.filter((w) => w !== null);
143
+ }
144
+
145
+ export function importedIndex(entries ) {
146
+ const m = new Map ();
147
+ for (const e of entries) {
148
+ if (e.t === "imported") m.set(`${e.harness}:${e.nativeId}`, e);
149
+ }
150
+ return m;
151
+ }
152
+
153
+ /** The `organize-failed` entries of one run (journal order): why each change the run could not make failed. */
154
+ export function organizeFailures(entries , runId ) {
155
+ return entries.filter((e) => e.t === "organize-failed" && e.runId === runId);
156
+ }
157
+
158
+ /**
159
+ * True when `observed` (a stat'd mtime) matches `expected` (a value we set or journaled):
160
+ * within 2 ms, or equal after the truncation a coarse-timestamp filesystem applies
161
+ * (1 s, e.g. HFS+; 2 s, FAT/exFAT).
162
+ */
163
+ export function near(observed , expected ) {
164
+ if (Math.abs(observed - expected) <= 2) return true;
165
+ if (expected % 1000 !== 0 && observed % 1000 === 0 && Math.floor(observed / 1000) === Math.floor(expected / 1000)) return true;
166
+ if (observed % 2000 === 0 && Math.abs(observed - expected) < 2000) return true;
167
+ return false;
168
+ }
169
+
170
+ /**
171
+ * Restore every bumped mtime that has no later restore in the same run.
172
+ *
173
+ * MUST be called only while holding the state-dir lock (`acquireLock`): it rewrites
174
+ * file times and appends to the journal, and a concurrent run's bumps would be undone.
175
+ *
176
+ * Matching is per (runId, path) but restoration is per path (identity normalized with
177
+ * `normalizeCwd`, case-insensitive on win32/darwin): one `utimes` per path, using the
178
+ * original of the EARLIEST still-pending bump (a later run may have journaled an
179
+ * already-bumped value as its "original"), except that a later bump whose original differs
180
+ * from the previous bump's `targetMtimeMs` by more than 2 ms (a user edit in between)
181
+ * replaces it. If the file already sits at that original (+-2 ms; crash between utimes and
182
+ * the restore entry) it counts as `restored` without touching it. Afterwards one `mtime-restore` per affected
183
+ * run lists its paths.
184
+ * - ENOENT: reported in `missing`, marked restored (no endless retry).
185
+ * - Current mtime differs from the latest pending bump's `targetMtimeMs` (+-2 ms): the
186
+ * file was modified by someone else; never moved backwards. Reported in
187
+ * `skippedModified`, marked restored. Entries without `targetMtimeMs` restore as before.
188
+ * - Other errors: `failed`, left pending.
189
+ * - Structurally invalid bump/restore entries are skipped and counted in `malformed`.
190
+ */
191
+ export async function recoverPendingMtimes(
192
+ j ,
193
+ opts = {},
194
+ ) {
195
+ const statFn = opts.stat ?? stat;
196
+ const entries = await j.readAll();
197
+
198
+ const byKey = new Map ();
199
+ const keyOf = (p ) => pathKey(p, process.platform);
200
+ let malformed = 0;
201
+ const num = (v ) => typeof v === "number" && Number.isFinite(v);
202
+ for (const e of entries) {
203
+ if (e.t === "mtime-bump") {
204
+ const files = (e ).files;
205
+ if (!Array.isArray(files)) { malformed++; continue; }
206
+ let bad = false;
207
+ for (const f of files ) {
208
+ if (typeof f !== "object" || f === null || typeof f["path"] !== "string" || f["path"] === "" || !num(f["atimeMs"]) || !num(f["mtimeMs"])) { bad = true; continue; }
209
+ const key = keyOf(f["path"]);
210
+ let slot = byKey.get(key);
211
+ if (!slot) byKey.set(key, (slot = { path: f["path"], bumps: [] }));
212
+ slot.bumps.push({
213
+ runId: e.runId,
214
+ original: { atimeMs: f["atimeMs"], mtimeMs: f["mtimeMs"] },
215
+ target: num(f["targetMtimeMs"]) ? f["targetMtimeMs"] : null,
216
+ });
217
+ }
218
+ if (bad) malformed++;
219
+ } else if (e.t === "mtime-restore") {
220
+ const paths = (e ).paths;
221
+ if (!Array.isArray(paths) || paths.some((p) => typeof p !== "string")) { malformed++; continue; }
222
+ for (const p of paths ) {
223
+ const slot = byKey.get(keyOf(p));
224
+ if (slot) slot.bumps = slot.bumps.filter((b) => b.runId !== e.runId);
225
+ }
226
+ }
227
+ }
228
+ const result = { restored: [], missing: [], failed: [], skippedModified: [], malformed };
229
+ const doneByRun = new Map ();
230
+ for (const slot of byKey.values()) {
231
+ if (slot.bumps.length === 0) continue;
232
+ // Effective original: the earliest pending bump's, unless a later bump started from a
233
+ // value that is not where the previous bump left the file (a real edit happened between).
234
+ let original = slot.bumps[0] .original;
235
+ for (let k = 1; k < slot.bumps.length; k++) {
236
+ const prev = slot.bumps[k - 1] ;
237
+ const cur = slot.bumps[k] ;
238
+ // Continuation if it starts where the previous bump left the file OR where the previous
239
+ // bump itself started (that earlier run restored the file but crashed before journaling it).
240
+ if (prev.target !== null && !near(cur.original.mtimeMs, prev.target) && !near(cur.original.mtimeMs, prev.original.mtimeMs)) original = cur.original;
241
+ }
242
+ const target = slot.bumps[slot.bumps.length - 1] .target;
243
+ let outcome ;
244
+ try {
245
+ const cur = await statFn(slot.path).catch((e ) => {
246
+ if (e.code === "ENOENT") return null;
247
+ throw e;
248
+ });
249
+ if (cur === null) outcome = "missing";
250
+ else if (near(cur.mtimeMs, original.mtimeMs)) outcome = "restored"; // crashed after utimes, before the restore entry
251
+ else if (target !== null && !near(cur.mtimeMs, target)) outcome = "skipped";
252
+ else {
253
+ await utimes(slot.path, original.atimeMs / 1000, original.mtimeMs / 1000);
254
+ outcome = "restored";
255
+ }
256
+ } catch (e) {
257
+ if ((e ).code === "ENOENT") outcome = "missing";
258
+ else {
259
+ result.failed.push({ path: slot.path, error: e instanceof Error ? e.message : String(e) });
260
+ continue;
261
+ }
262
+ }
263
+ if (outcome === "restored") result.restored.push(slot.path);
264
+ else if (outcome === "missing") result.missing.push(slot.path);
265
+ else result.skippedModified.push(slot.path);
266
+ for (const b of slot.bumps) {
267
+ let l = doneByRun.get(b.runId);
268
+ if (!l) doneByRun.set(b.runId, (l = []));
269
+ if (!l.includes(slot.path)) l.push(slot.path);
270
+ }
271
+ }
272
+ for (const [runId, paths] of doneByRun) await j.append({ t: "mtime-restore", runId, paths });
273
+ return result;
274
+ }