my-durable 0.0.56 → 0.0.57

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.
@@ -42,6 +42,8 @@ export const defaultAwakeIo = (): AwakeIo => ({
42
42
  const child: ChildProcess = nodeSpawn(cmd, args as string[], {
43
43
  stdio: "ignore",
44
44
  detached: false,
45
+ // A keep-awake holder is background machinery: no console window.
46
+ windowsHide: true,
45
47
  });
46
48
  child.unref();
47
49
  return { kill: () => void child.kill("SIGTERM") };
@@ -162,7 +162,9 @@ interface Io {
162
162
 
163
163
  const execDefault = (cmd: string, args: string[]) =>
164
164
  new Promise<{ ok: boolean; output: string; code: number }>((resolve) => {
165
- execFile(cmd, args, { timeout: 30_000 }, (error, stdout, stderr) => {
165
+ // windowsHide: this daemon runs under a supervisor with no terminal — a
166
+ // console window flashing per call is pure noise on Windows.
167
+ execFile(cmd, args, { timeout: 30_000, windowsHide: true }, (error, stdout, stderr) => {
166
168
  const code = (error as { code?: number } | null)?.code ?? 0;
167
169
  resolve({ ok: !error, output: String(stdout ?? "") + String(stderr ?? ""), code });
168
170
  });
@@ -272,6 +274,8 @@ export function startBackendDetached(
272
274
  stdio: ["ignore", fd, fd],
273
275
  env: cleanChildEnv(env),
274
276
  cwd: dirname(dpi),
277
+ // The whole point of this spawn is "no terminal" — never flash a console.
278
+ windowsHide: true,
275
279
  });
276
280
  child.unref();
277
281
  closeSync(fd);
@@ -20,7 +20,42 @@ const GIT_SLOW_TIMEOUT = 45_000;
20
20
  /** Same-path status within this window returns the cached answer — the UIs
21
21
  * poll, and a 20s status must not restart on every poll tick. */
22
22
  const STATUS_TTL = 5_000;
23
+ /** A FAILED status is cached too, but briefly: without this, a repo git cannot
24
+ * reach re-spawned git on every UI poll tick (935 failures in one user log).
25
+ * Short enough that a fixed path (git installed, drive mounted) recovers on
26
+ * its own; long enough that a poll storm costs one spawn. */
27
+ const STATUS_FAIL_TTL = 15_000;
23
28
  const statusCache = new Map<string, { at: number; s: GitStatus }>();
29
+ const statusFailCache = new Map<string, { at: number; msg: string }>();
30
+ /** One in-flight status per path: N UI clients polling the same repos through
31
+ * /git/status-batch must share ONE git spawn, not N. */
32
+ const statusInFlight = new Map<string, Promise<GitStatus>>();
33
+
34
+ /** Paths as git ARGV: Git-for-Windows' msys layer mangles backslashes inside
35
+ * argv (`D:\source\x` arrives as `D:source?x` → "cannot change to"), while
36
+ * the very same path with forward slashes works. Pure — no fs, no resolution. */
37
+ export function gitPathFor(p: string, platform: NodeJS.Platform): string {
38
+ return platform === "win32" ? p.replace(/\\/g, "/") : p;
39
+ }
40
+
41
+ /** `gitPathFor` against THIS platform — the form every argv path must take. */
42
+ export const gitPath = (p: string): string => gitPathFor(p, process.platform);
43
+
44
+ /** Same, for the `-- <paths...>` lists (stage/discard/commit/unstage/resolve). */
45
+ const gitPaths = (paths: string[]): string[] => paths.map(gitPath);
46
+
47
+ /** Child-process options, exported so a test can assert the Windows console
48
+ * window stays hidden: a daemon that polls git must never flash a terminal. */
49
+ export const GIT_EXEC_OPTS = (timeout: number) => ({ timeout, maxBuffer: 8 * 1024 * 1024, windowsHide: true });
50
+ export const GH_EXEC_OPTS = (cwd: string, timeout: number) => ({ cwd, timeout, maxBuffer: 4 * 1024 * 1024, windowsHide: true });
51
+
52
+ /** Test seam for counting/driving spawns: `node:child_process`'s ESM namespace
53
+ * is not redefinable, so `mock.method` cannot reach `execFile`. Pass nothing
54
+ * to restore the real one. */
55
+ let execFileImpl: typeof execFile = execFile;
56
+ export function setGitExecForTests(fn?: typeof execFile) {
57
+ execFileImpl = fn ?? execFile;
58
+ }
24
59
 
25
60
  /** The ONE stderr that legitimately means "no repo here" — anything else
26
61
  * (git missing, permission, timeout) is a failure we must not flatten into
@@ -34,7 +69,8 @@ export function isNotARepoError(e: unknown): boolean {
34
69
  /** One git call; rejects on non-zero exit with stderr in the message. */
35
70
  export function git(cwd: string, args: string[], timeout = GIT_TIMEOUT): Promise<string> {
36
71
  return new Promise((ok, fail) => {
37
- execFile("git", ["-C", cwd, ...args], { timeout, maxBuffer: 8 * 1024 * 1024 }, (error, stdout, stderr) => {
72
+ // `-C` is ARGV, so the path goes out forward-slashed (see gitPath).
73
+ execFileImpl("git", ["-C", gitPath(cwd), ...args], GIT_EXEC_OPTS(timeout), (error, stdout, stderr) => {
38
74
  if (error) fail(Error(String(stderr || stdout || error.message).trim().slice(0, 400)));
39
75
  // git chats on stderr for worktree add/switch/fetch — keep both.
40
76
  else ok(`${String(stdout)}${String(stdout) && String(stderr) ? "\n" : ""}${String(stderr)}`);
@@ -48,7 +84,8 @@ export function git(cwd: string, args: string[], timeout = GIT_TIMEOUT): Promise
48
84
  export function gh(cwd: string, args: string[], timeout = GIT_TIMEOUT): Promise<string> {
49
85
  return new Promise((ok, fail) => {
50
86
  // gh resolves the repo from cwd (a --repo flag wants a slug, not a path).
51
- execFile("gh", args, { cwd, timeout, maxBuffer: 4 * 1024 * 1024 }, (error, stdout, stderr) => {
87
+ // cwd is a Node spawn option, not argv — Node handles Windows paths here.
88
+ execFileImpl("gh", args, GH_EXEC_OPTS(cwd, timeout), (error, stdout, stderr) => {
52
89
  if (error) fail(Error(String(stderr || stdout || error.message).trim().slice(0, 400)));
53
90
  else ok(String(stdout));
54
91
  });
@@ -118,7 +155,9 @@ export function gitDirtyMarks(): { root: string; at: number }[] {
118
155
 
119
156
  function markDirty(root: string) {
120
157
  const now = Date.now();
121
- for (const [p, c] of statusCache) if (p === root || p.startsWith(root + "/") || p.startsWith(root + "\\")) statusCache.delete(p);
158
+ for (const [p] of statusCache) if (p === root || p.startsWith(root + "/") || p.startsWith(root + "\\")) statusCache.delete(p);
159
+ // A repo whose files change must get a fresh ATTEMPT, failures included.
160
+ for (const [p] of statusFailCache) if (p === root || p.startsWith(root + "/") || p.startsWith(root + "\\")) statusFailCache.delete(p);
122
161
  dirty.push({ root, at: now });
123
162
  dirtyListener?.();
124
163
  }
@@ -169,12 +208,30 @@ function ensureWatcher(root: string) {
169
208
  /** Test hook: the TTL cache would serve a pre-mutation answer. */
170
209
  export function clearGitStatusCache() {
171
210
  statusCache.clear();
211
+ statusFailCache.clear();
172
212
  }
173
213
 
174
- /** Structured status for a folder: everything the UIs show, one call. */
175
- export async function gitStatus(path: string): Promise<GitStatus> {
176
- const cached = statusCache.get(path);
177
- if (cached && Date.now() - cached.at < STATUS_TTL) return cached.s;
214
+ /** Structured status for a folder: everything the UIs show, one call.
215
+ * `now` is injectable so a test can age the caches without sleeping. */
216
+ export async function gitStatus(path: string, now = Date.now()): Promise<GitStatus> {
217
+ // One key per repo, not per spelling: `D:\\x` and `D:/x` are the same repo,
218
+ // and single-flight only dedupes if both land on the same entry.
219
+ const key = gitPath(path);
220
+ const cached = statusCache.get(key);
221
+ if (cached && now - cached.at < STATUS_TTL) return cached.s;
222
+ const failed = statusFailCache.get(key);
223
+ // Same error text as the original failure — the UI still shows WHY.
224
+ if (failed && now - failed.at < STATUS_FAIL_TTL) throw new Error(failed.msg);
225
+ const running = statusInFlight.get(key);
226
+ if (running) return running;
227
+ const p = statusOnce(path, key).finally(() => {
228
+ if (statusInFlight.get(key) === p) statusInFlight.delete(key);
229
+ });
230
+ statusInFlight.set(key, p);
231
+ return p;
232
+ }
233
+
234
+ async function statusOnce(path: string, key: string): Promise<GitStatus> {
178
235
  const out: GitStatus = { repo: false };
179
236
  try {
180
237
  // Reach git at all before trusting any "empty" answer: git missing from
@@ -275,7 +332,8 @@ export async function gitStatus(path: string): Promise<GitStatus> {
275
332
  // silently (checklist fs-auto-refresh, device side).
276
333
  ensureWatcher(root);
277
334
  const wl = wlP.value;
278
- statusCache.set(path, { at: Date.now(), s: out });
335
+ statusCache.set(key, { at: Date.now(), s: out });
336
+ statusFailCache.delete(key);
279
337
  out.worktrees = wl
280
338
  .split("\n\n")
281
339
  .map((b) => b.trim())
@@ -288,7 +346,29 @@ export async function gitStatus(path: string): Promise<GitStatus> {
288
346
  } catch (e) {
289
347
  // Only a GENUINE "not a git repository" is repo:false. Anything else —
290
348
  // git not found, EACCES, timeout — is a real failure the UIs must show.
291
- if (!isNotARepoError(e)) throw new Error(`git failed on the device: ${(e as Error).message.slice(0, 160)}`);
349
+ if (!isNotARepoError(e)) {
350
+ const msg = `git failed on the device: ${(e as Error).message.slice(0, 160)}`;
351
+ // Cache the FAILURE (briefly): the UIs poll, and a path git cannot reach
352
+ // must cost one spawn per TTL, not one per tick.
353
+ const at = Date.now();
354
+ for (const [k, v] of statusFailCache) if (at - v.at >= STATUS_FAIL_TTL) statusFailCache.delete(k);
355
+ statusFailCache.set(key, { at, msg });
356
+ throw new Error(msg);
357
+ }
358
+ // "Not a repository" is an ANSWER, not a failure: cache it exactly like a
359
+ // success (STATUS_TTL). Without this, every UI poll tick re-spawned git for
360
+ // a plain folder — and on Windows each spawn flashes a console window, the
361
+ // "spam terminal" symptom. Sessions routinely live in non-git folders, so
362
+ // this is the common path. Deliberately NOT in statusFailCache: nothing
363
+ // throws here, so the 15s fail TTL must not apply.
364
+ //
365
+ // Recovery when the folder BECOMES a repo: a plain dir has no fs watcher
366
+ // (ensureWatcher runs on the success path only), so markDirty is
367
+ // unreachable for it — the 5s TTL IS the recovery path: `git init` shows
368
+ // up within STATUS_TTL. Do not add a watcher for it.
369
+ // Keyed by the normalized gitPath key, so markDirty/clearGitStatusCache
370
+ // (which clear statusCache by that key) invalidate it too.
371
+ statusCache.set(key, { at: Date.now(), s: out });
292
372
  }
293
373
  return out;
294
374
  }
@@ -419,16 +499,16 @@ export async function gitOp(
419
499
  }
420
500
  case "stage": {
421
501
  if (!files?.length) throw Error("stage needs files");
422
- return { text: (await git(path, ["add", "--", ...files])).trim() || `staged ${files.length} file(s)` };
502
+ return { text: (await git(path, ["add", "--", ...gitPaths(files)])).trim() || `staged ${files.length} file(s)` };
423
503
  }
424
504
  case "discard": {
425
505
  // IntelliJ's Rollback: index AND worktree back to HEAD for these paths.
426
506
  if (!files?.length) throw Error("discard needs files");
427
- return { text: (await git(path, ["checkout", "HEAD", "--", ...files])).trim() || `discarded ${files.length} file(s)` };
507
+ return { text: (await git(path, ["checkout", "HEAD", "--", ...gitPaths(files)])).trim() || `discarded ${files.length} file(s)` };
428
508
  }
429
509
  case "diff-file": {
430
510
  if (!target) throw Error("diff-file needs a file path");
431
- return { text: (await git(path, ["--no-pager", "diff", ...(staged ? ["--cached"] : []), "HEAD", "--", target])).trim() || "no diff" };
511
+ return { text: (await git(path, ["--no-pager", "diff", ...(staged ? ["--cached"] : []), "HEAD", "--", gitPath(target)])).trim() || "no diff" };
432
512
  }
433
513
  case "stash-push":
434
514
  return { text: (await git(path, ["stash", "push", ...(message ? ["-m", message] : [])])).trim() || "stashed" };
@@ -438,10 +518,10 @@ export async function gitOp(
438
518
  // IntelliJ's Unstage: index only, worktree keeps its changes.
439
519
  if (!files?.length) throw Error("unstage needs files");
440
520
  try {
441
- return { text: (await git(path, ["reset", "-q", "HEAD", "--", ...files])).trim() || `unstaged ${files.length} file(s)` };
521
+ return { text: (await git(path, ["reset", "-q", "HEAD", "--", ...gitPaths(files)])).trim() || `unstaged ${files.length} file(s)` };
442
522
  } catch {
443
523
  // unborn branch: HEAD does not resolve yet — reset against the empty tree.
444
- return { text: (await git(path, ["reset", "-q", "--", ...files])).trim() || `unstaged ${files.length} file(s)` };
524
+ return { text: (await git(path, ["reset", "-q", "--", ...gitPaths(files)])).trim() || `unstaged ${files.length} file(s)` };
445
525
  }
446
526
  }
447
527
  case "compare": {
@@ -518,8 +598,8 @@ export async function gitOp(
518
598
  // orca's conflicts section, one click: pick a side, stage the result.
519
599
  if (side !== "ours" && side !== "theirs") throw Error("resolve needs side=ours|theirs");
520
600
  if (!files?.length) throw Error("resolve needs files");
521
- await git(path, ["checkout", `--${side}`, "--", ...files]);
522
- return { text: (await git(path, ["add", "--", ...files])).trim() || `resolved ${files.length} file(s) with --${side}` };
601
+ await git(path, ["checkout", `--${side}`, "--", ...gitPaths(files)]);
602
+ return { text: (await git(path, ["add", "--", ...gitPaths(files)])).trim() || `resolved ${files.length} file(s) with --${side}` };
523
603
  }
524
604
  case "submodule-update":
525
605
  return { text: (await git(path, ["submodule", "update", "--init", "--recursive"], GIT_SLOW_TIMEOUT)).trim() || "submodules up to date" };
@@ -559,7 +639,7 @@ export async function gitOp(
559
639
  // IntelliJ-style: chosen files only, when the caller picked some.
560
640
  if (files?.length) {
561
641
  for (const f of files) if (f.includes("\0") || f === "") throw Error("bad file path");
562
- return { text: (await git(path, ["commit", "-m", msg, "--", ...files])).split("\n")[0]?.trim() ?? "committed" };
642
+ return { text: (await git(path, ["commit", "-m", msg, "--", ...gitPaths(files)])).split("\n")[0]?.trim() ?? "committed" };
563
643
  }
564
644
  return { text: (await git(path, ["commit", "-am", msg])).split("\n")[0]?.trim() ?? "committed" };
565
645
  }
@@ -571,14 +651,14 @@ export async function gitOp(
571
651
  if (!target || !isAbsolute(target)) throw Error("worktree-add needs an absolute target path");
572
652
  if (branch) {
573
653
  if (!safeRef(branch)) throw Error("worktree-add branch name is invalid (letters, digits, ./-_)");
574
- return { text: (await git(path, ["worktree", "add", "-b", branch, target])).trim() };
654
+ return { text: (await git(path, ["worktree", "add", "-b", branch, gitPath(target)])).trim() };
575
655
  }
576
656
  if (!ref || !safeRef(ref)) throw Error("worktree-add needs a branch (new) or ref (existing)");
577
- return { text: (await git(path, ["worktree", "add", target, ref])).trim() };
657
+ return { text: (await git(path, ["worktree", "add", gitPath(target), ref])).trim() };
578
658
  }
579
659
  case "worktree-remove": {
580
660
  if (!target || !isAbsolute(target)) throw Error("worktree-remove needs an absolute path");
581
- return { text: (await git(path, ["worktree", "remove", target])).trim() || `removed ${target}` };
661
+ return { text: (await git(path, ["worktree", "remove", gitPath(target)])).trim() || `removed ${target}` };
582
662
  }
583
663
  }
584
664
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "my-durable",
3
- "version": "0.0.56",
3
+ "version": "0.0.57",
4
4
  "description": "Durable Pi — the durable agent network: hub web UI, device backend daemon, TUI admin and the shared SDK, packaged as one runnable monorepo install",
5
5
  "license": "MIT",
6
6
  "repository": {