pi-better-background-tasks 0.19.0 → 0.20.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 (37) hide show
  1. package/README.md +21 -10
  2. package/package.json +1 -1
  3. package/runtime-client/artifacts/darwin-arm64.gz +0 -0
  4. package/runtime-client/artifacts/darwin-arm64.json +1 -1
  5. package/runtime-client/artifacts/darwin-x64.gz +0 -0
  6. package/runtime-client/artifacts/darwin-x64.json +1 -1
  7. package/runtime-client/artifacts/linux-arm64.gz +0 -0
  8. package/runtime-client/artifacts/linux-arm64.json +1 -1
  9. package/runtime-client/artifacts/linux-x64.gz +0 -0
  10. package/runtime-client/artifacts/linux-x64.json +1 -1
  11. package/runtime-client/src/runtime/root.mjs +5 -2
  12. package/src/index.ts +19 -0
  13. package/src/managed-frontend.ts +76 -5
  14. package/src/navigator-provider.ts +4 -0
  15. package/src/observed-waits.ts +168 -24
  16. package/src/process.ts +45 -11
  17. package/src/review-settings.ts +18 -0
  18. package/src/runtime.ts +8 -73
  19. package/src/shared-harness-settings.ts +2 -5
  20. package/src/shared-navigator.ts +47 -26
  21. package/src/shared-operation-coordinator/src/outbox.ts +9 -0
  22. package/src/shared-operation-coordinator/src/store.ts +6 -0
  23. package/src/shared-ssh-core/index.ts +1 -1
  24. package/src/stall.ts +7 -4
  25. package/src/supervised-progress.ts +43 -0
  26. package/src/supervisor/README.md +1 -4
  27. package/src/supervisor/emit-runner.mjs +1 -0
  28. package/src/supervisor/generated/process.mjs +49 -11
  29. package/src/supervisor/generated/runner.mjs +47 -4
  30. package/src/supervisor/generated/store.mjs +3 -3
  31. package/src/supervisor/generated/watch-fingerprint.mjs +69 -0
  32. package/src/supervisor/runner.ts +38 -3
  33. package/src/supervisor/store.ts +3 -3
  34. package/src/supervisor/supervisor.ts +6 -3
  35. package/src/tools.ts +26 -16
  36. package/src/types.ts +4 -2
  37. package/src/watch-fingerprint.ts +70 -0
@@ -460,7 +460,7 @@ const BACK_TARGET = "back-to-main";
460
460
 
461
461
  function highlightPointerTarget(theme: unknown, line: string, width: number): string {
462
462
  const colors = theme as { bg?(color: string, value: string): string } | undefined;
463
- return colors?.bg?.("selectedBg", line + " ".repeat(Math.max(0, width - visibleWidth(line))))
463
+ return colors?.bg?.("selectedBg", line + " ".repeat(Math.max(0, width - piVisibleWidth(line))))
464
464
  ?? themeFgFromTheme(theme)("accent", line);
465
465
  }
466
466
 
@@ -783,16 +783,16 @@ function formatMainListRow(row: InternalRow, selected: boolean, fg: (color: stri
783
783
  const status = fg(indicator.color, indicator.glyph);
784
784
  const elapsed = singleLine(row.elapsed || "-");
785
785
  const available = Math.max(24, width || MAIN_LIST_FALLBACK_WIDTH);
786
- const elapsedWidth = Math.min(Math.max(visibleWidth(elapsed), 4), 12);
786
+ const elapsedWidth = Math.min(Math.max(piVisibleWidth(elapsed), 4), 12);
787
787
  const statusWidth = 2;
788
- const leftPrefixWidth = visibleWidth(prefix) + statusWidth + 1;
788
+ const leftPrefixWidth = piVisibleWidth(prefix) + statusWidth + 1;
789
789
  const maxNameWidth = Math.max(8, Math.floor(available * 0.36));
790
790
  const nameWidth = Math.max(8, Math.min(44, maxNameWidth, available - leftPrefixWidth - elapsedWidth - 10));
791
791
  const rightWidth = Math.max(8, available - leftPrefixWidth - nameWidth - 1);
792
792
  const summaryWidth = Math.max(1, rightWidth - elapsedWidth - 1);
793
793
  const left = `${prefix}${fit(status, statusWidth)} ${fit(name, nameWidth)}`;
794
794
  const right = `${dim(fitRight(rowSummary(row), summaryWidth), fg)} ${fitRight(elapsed, elapsedWidth)}`;
795
- const gap = Math.max(1, available - visibleWidth(left) - visibleWidth(right));
795
+ const gap = Math.max(1, available - piVisibleWidth(left) - piVisibleWidth(right));
796
796
  return `${left}${" ".repeat(gap)}${right}`;
797
797
  }
798
798
 
@@ -879,15 +879,15 @@ function rowSummary(row: InternalRow): string {
879
879
 
880
880
  function fit(value: string, width: number): string {
881
881
  const str = singleLine(value);
882
- const visible = visibleWidth(str);
883
- if (visible >= width) return truncateVisible(str, width);
882
+ const visible = piVisibleWidth(str);
883
+ if (visible > width) return piTruncateToWidth(str, width);
884
884
  return str + " ".repeat(width - visible);
885
885
  }
886
886
 
887
887
  function fitRight(value: string, width: number): string {
888
888
  const str = singleLine(value);
889
- const visible = visibleWidth(str);
890
- if (visible >= width) return truncateVisible(str, width);
889
+ const visible = piVisibleWidth(str);
890
+ if (visible > width) return piTruncateToWidth(str, width);
891
891
  return " ".repeat(width - visible) + str;
892
892
  }
893
893
 
@@ -954,28 +954,43 @@ function installNavigatorEditor(ui: any, deps: HostDeps): unknown {
954
954
 
955
955
  function wrapEditor(inner: any, deps: HostDeps): unknown {
956
956
  if (inner && typeof inner.render === "function") state().editorComponent = inner as Component;
957
+ const methods = new Map<PropertyKey, { original: Function; exposed: Function }>();
958
+ const replacements = new Map<PropertyKey, Function>();
957
959
  const proxy: any = new Proxy(inner, {
958
960
  get(target, prop) {
961
+ const value = Reflect.get(target, prop);
962
+ if (typeof value !== "function" || replacements.get(prop) === value) return value;
963
+ const cached = methods.get(prop);
964
+ if (cached && cached.original === value) return cached.exposed;
965
+ // Capture the method before another editor decorator replaces it.
966
+ // A decorator can retain this wrapper and call it as its delegate.
967
+ let exposed = value.bind(target);
959
968
  if (prop === "handleInput") {
960
- return (data: string) => {
969
+ exposed = (data: string) => {
961
970
  if (target.getText?.() === "" && handleMainListInput(data, deps)) {
962
971
  return;
963
972
  }
964
- target.handleInput(data);
973
+ value.call(target, data);
965
974
  };
966
975
  }
967
- if (prop === "render" && typeof target.render === "function") {
968
- return (...args: unknown[]) => {
976
+ if (prop === "render") {
977
+ exposed = (...args: unknown[]) => {
969
978
  const s = state();
970
979
  if (s.editorFocusTarget === proxy) s.editorRenders = (s.editorRenders ?? 0) + 1;
971
- return target.render(...args);
980
+ return value.apply(target, args);
972
981
  };
973
982
  }
974
- const value = Reflect.get(target, prop);
975
- return typeof value === "function" ? value.bind(target) : value;
983
+ methods.set(prop, { original: value, exposed });
984
+ return exposed;
976
985
  },
977
986
  set(target, prop, value) {
978
- return Reflect.set(target, prop, value);
987
+ const cached = methods.get(prop);
988
+ const restoring = cached !== undefined && value === cached.exposed;
989
+ if (!Reflect.set(target, prop, restoring ? cached.original : value)) return false;
990
+ // Preserve replacement identity so the installing decorator can undo it.
991
+ if (!restoring && typeof value === "function") replacements.set(prop, value);
992
+ else replacements.delete(prop);
993
+ return true;
979
994
  },
980
995
  });
981
996
  // Pi mounts and focuses whatever the factory returns; an extension that
@@ -1174,6 +1189,8 @@ function createOverlayComponent(
1174
1189
  onClosed: () => void,
1175
1190
  initialDetailId: string,
1176
1191
  ) {
1192
+ let editorRendersSeen = state().editorRenders ?? 0;
1193
+ let sawLiveEditor = liveEditorMounted(tui) === true;
1177
1194
  // The overlay only ever shows one row's detail; the rail below it is the list.
1178
1195
  const overlayState: OverlayState = { rows: initialRows, selected: 0 };
1179
1196
  let logTailRows: number = DEFAULT_LOG_TAIL_ROWS;
@@ -1331,19 +1348,23 @@ function createOverlayComponent(
1331
1348
  requestRender();
1332
1349
  }
1333
1350
 
1334
- let editorRendersSeen: number | undefined;
1335
1351
  /**
1336
- * Our editor wrapper was uninstalled: close, since no key of ours can reach this overlay again and
1337
- * it would cover the editor that replaced ours (#332). An extension that composes the editor inside
1338
- * its own non-container component still renders ours, so the wrapper also counts as live while it
1339
- * rendered since the previous overlay frame (Pi renders the editor before it composites overlays).
1352
+ * Close when a replacement editor takes over while the sheet is open (#332).
1353
+ * A wrapper inside another extension's editor still counts as live if it rendered since
1354
+ * the last overlay frame. Pi renders the editor before it composites overlays.
1340
1355
  */
1341
1356
  function closeIfEditorReplaced(): void {
1342
- const rendersBefore = editorRendersSeen;
1343
1357
  const renders = state().editorRenders ?? 0;
1358
+ const rendered = renders !== editorRendersSeen;
1344
1359
  editorRendersSeen = renders;
1345
- state().editorRenderedLastFrame = rendersBefore === undefined ? undefined : renders !== rendersBefore;
1346
- if (closed || liveEditorMounted(tui) !== false || rendersBefore === undefined || renders !== rendersBefore) return;
1360
+ state().editorRenderedLastFrame = rendered;
1361
+ if (closed) return;
1362
+ const mounted = liveEditorMounted(tui);
1363
+ if (rendered || mounted === true) {
1364
+ sawLiveEditor = true;
1365
+ return;
1366
+ }
1367
+ if (mounted !== false || !sawLiveEditor) return;
1347
1368
  // Not from inside pi-tui's render pass: hiding an overlay there would change the stack it is drawing.
1348
1369
  queueMicrotask(() => {
1349
1370
  if (closed) return;
@@ -1870,9 +1891,9 @@ function fill(glyph: string, label: string, width: number): string {
1870
1891
  }
1871
1892
 
1872
1893
  function safeTruncate(line: string, width: number, truncate: (s: string, width: number) => string): string {
1873
- if (visibleWidth(line) <= width) return line;
1894
+ if (piVisibleWidth(line) <= width) return line;
1874
1895
  const cut = truncate(line, width);
1875
- return visibleWidth(cut) > width ? truncateVisible(cut, width) : cut;
1896
+ return piVisibleWidth(cut) > width ? piTruncateToWidth(cut, width) : cut;
1876
1897
  }
1877
1898
 
1878
1899
  const ANSI_RE = new RegExp("[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\\u0007)|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))", "g");
@@ -281,6 +281,15 @@ export function listOutbox(ctx: StoreContext, filter: OutboxFilter = {}): Outbox
281
281
  ).map((row) => mapOutbox(ctx, row));
282
282
  }
283
283
 
284
+ /** Check a wait handoff without loading the retained evidence for its generations. */
285
+ export function hasDeliveredWaitDependency(ctx: StoreContext, operationId: string, terminalRevision: number, recipient: OwnerIdentity): boolean {
286
+ const owner = ownerClause("recipient", recipient);
287
+ return getRows(ctx, `SELECT 1 FROM outbox_events
288
+ WHERE operation_id = ? AND terminal_revision = ? AND event_type = 'dependency-ready'
289
+ AND delivered_at IS NOT NULL AND ${owner.sql} LIMIT 1`,
290
+ requireId("operationId", operationId), requireCounter("terminalRevision", terminalRevision), ...owner.params).length > 0;
291
+ }
292
+
284
293
  /** Find recipients with deliverable dependencies without loading each event's evidence. */
285
294
  export function listDispatchableOutboxRecipients(ctx: StoreContext): Array<{ recipient: OwnerIdentity; count: number }> {
286
295
  return getRows(
@@ -68,6 +68,7 @@ import {
68
68
  } from "./waits.ts";
69
69
  import {
70
70
  claimOutbox as writeOutboxClaim,
71
+ hasDeliveredWaitDependency as readDeliveredWaitDependency,
71
72
  listDispatchableOutboxRecipients as readDispatchableOutboxRecipients,
72
73
  listOutbox as readOutbox,
73
74
  markOutboxDelivered as writeOutboxDelivery,
@@ -318,6 +319,7 @@ export interface Store {
318
319
  // ---- outbox ----
319
320
 
320
321
  listOutbox(filter?: OutboxFilter): OutboxEventRecord[];
322
+ hasDeliveredWaitDependency(operationId: string, terminalRevision: number, recipient: OwnerIdentity): boolean;
321
323
  /** Lightweight dispatch candidates; evidence is read only after a claim succeeds. */
322
324
  listDispatchableOutboxRecipients(): Array<{ recipient: OwnerIdentity; count: number }>;
323
325
  /** Claim pending deliveries for a `ready`/`resuming` generation. */
@@ -559,6 +561,10 @@ export function openStore(options: StoreOptions): Store {
559
561
  alive();
560
562
  return readOutbox(ctx, filter);
561
563
  },
564
+ hasDeliveredWaitDependency(operationId, terminalRevision, recipient) {
565
+ alive();
566
+ return readDeliveredWaitDependency(ctx, operationId, terminalRevision, recipient);
567
+ },
562
568
  listDispatchableOutboxRecipients() {
563
569
  alive();
564
570
  return readDispatchableOutboxRecipients(ctx);
@@ -328,7 +328,7 @@ export function wrapRemoteBashCommand(input: RemoteBashCommandInput): string {
328
328
 
329
329
  export function defaultSshControlPathRoot(): string {
330
330
  const agentDirectory = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
331
- const root = join(agentDirectory, "ssh-control");
331
+ const root = resolve(agentDirectory, "ssh-control");
332
332
  // A long agent directory would push the socket past the unix path limit; fall back to a short per-user root.
333
333
  if (Buffer.byteLength(join(root, MUX_CONTROL_PATH_NAME_TEMPLATE)) <= MAX_SSH_CONTROL_PATH_BYTES) return root;
334
334
  return join("/tmp", `pi-ssh-${process.getuid?.() ?? "user"}`);
package/src/stall.ts CHANGED
@@ -47,11 +47,14 @@ export function observeBackgroundTaskStall(meta: BackgroundTaskMeta, now = Date.
47
47
  });
48
48
  }
49
49
 
50
+ export function formatProgressDuration(ms: number): string {
51
+ const seconds = Math.max(0, Math.round(ms / 1000));
52
+ return seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m${(seconds % 60).toString().padStart(2, "0")}s`;
53
+ }
54
+
50
55
  /** Silence is an observation, not proof that the process is hung. */
51
- export function formatBackgroundTaskStall(observation: StallObservation): string | undefined {
56
+ export function formatBackgroundTaskStall(observation: Pick<StallObservation, "state" | "ageMs">): string | undefined {
52
57
  if (observation.state !== "quiet" && observation.state !== "stalled") return undefined;
53
- const seconds = Math.max(0, Math.round((observation.ageMs ?? 0) / 1000));
54
- const duration = seconds < 60 ? `${seconds}s` : `${Math.floor(seconds / 60)}m${(seconds % 60).toString().padStart(2, "0")}s`;
55
58
  const label = observation.state === "stalled" ? "suspected stall" : "quiet";
56
- return `${label}; no observed progress for ${duration}`;
59
+ return `${label}; no observed progress for ${formatProgressDuration(observation.ageMs ?? 0)}`;
57
60
  }
@@ -0,0 +1,43 @@
1
+ import { readFileSync, statSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { backgroundTaskStallThresholds, formatBackgroundTaskStall } from "./stall.js";
4
+ import { observeStall } from "./shared-stall-detector.js";
5
+
6
+ interface ProgressSource {
7
+ status: string;
8
+ kind: string;
9
+ claim?: { claimedAt: number };
10
+ logs: { stdout: string; stderr?: string };
11
+ }
12
+
13
+ export function supervisedProgress(source: ProgressSource | undefined, now = Date.now()) {
14
+ if (source?.status !== "running" || !source.claim) return;
15
+ let observedAt: number;
16
+ try {
17
+ observedAt = JSON.parse(readFileSync(join(dirname(source.logs.stdout), "progress.json"), "utf8")).observedAt;
18
+ if (!Number.isFinite(observedAt) || observedAt < source.claim.claimedAt) return;
19
+ } catch (error) {
20
+ // Older process runners still have separate append-only streams. Older watches
21
+ // appended every poll, so their logs cannot establish a meaningful progress time.
22
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT" || source.kind !== "process") return;
23
+ observedAt = source.claim.claimedAt;
24
+ for (const path of [source.logs.stdout, source.logs.stderr]) {
25
+ if (!path) continue;
26
+ try {
27
+ const stat = statSync(path, { throwIfNoEntry: false });
28
+ if (stat?.size) observedAt = Math.max(observedAt, Math.trunc(stat.mtimeMs));
29
+ } catch { return; }
30
+ }
31
+ }
32
+ const { state, thresholds } = observeStall({ now, lastProgressAt: observedAt, thresholds: backgroundTaskStallThresholds() });
33
+ const quietAt = observedAt + thresholds.quietMs;
34
+ const stalledAt = observedAt + thresholds.stallMs;
35
+ const alertAt = stalledAt + 60_000;
36
+ return { observedAt, state, alertDue: now >= alertAt, nextDeadline: [quietAt, stalledAt, alertAt].find(time => time > now) };
37
+ }
38
+
39
+ export type SupervisedProgress = NonNullable<ReturnType<typeof supervisedProgress>>;
40
+
41
+ export function describeSupervisedProgress(progress: SupervisedProgress, now = Date.now()) {
42
+ return formatBackgroundTaskStall({ ...progress, ageMs: now - progress.observedAt });
43
+ }
@@ -1,9 +1,6 @@
1
1
  # Detached local supervisor
2
2
 
3
- Slice 2 of [ADR 0020](../../../../docs/adr/0020-observed-waits-retain-an-owner.md) and the
4
- [observed-waits design](../../../../docs/plans/observed-waits-design.md): local process and command-watch
5
- supervision that survives the process that launched it. Nothing in this directory is wired into the
6
- Background Tasks tools yet; the parent owns that integration.
3
+ The detached supervisor runs local processes and command watches after the launching frontend exits. The coordinator retains the wait and its owner. [Observed waits](https://github.com/1aboveio/pi-better-harness/blob/main/docs/adr/0020-observed-waits-retain-an-owner.md) · [Supervisor design](https://github.com/1aboveio/pi-better-harness/blob/main/docs/plans/observed-waits-design.md)
7
4
 
8
5
  ## Contract
9
6
 
@@ -39,6 +39,7 @@ const CLOSURE = [
39
39
  { source: join(here, "store.ts"), out: "store.mjs" },
40
40
  { source: join(here, "types.ts"), out: "types.mjs" },
41
41
  { source: join(here, "identity.ts"), out: "identity.mjs" },
42
+ { source: join(here, "..", "watch-fingerprint.ts"), out: "watch-fingerprint.mjs" },
42
43
  { source: join(here, "..", "conditions.ts"), out: "conditions.mjs" },
43
44
  { source: join(here, "..", "process.ts"), out: "process.mjs" },
44
45
  { source: join(here, "..", "process-identity.ts"), out: "process-identity.mjs" },
@@ -2,8 +2,9 @@
2
2
  // Do not edit: change the source and re-run the emitter (a drift test enforces this).
3
3
 
4
4
  import { spawn, spawnSync } from "node:child_process";
5
- import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, writeSync } from "node:fs";
6
- import { dirname, join } from "node:path";
5
+ import { accessSync, appendFileSync, closeSync, constants, existsSync, mkdirSync, openSync, readFileSync, writeSync } from "node:fs";
6
+ import { homedir } from "node:os";
7
+ import { dirname, join, win32 } from "node:path";
7
8
  /** Known Git for Windows locations; `bash -lc` needs a real bash, not the WSL shim. */
8
9
  const WINDOWS_BASH_CANDIDATES = [
9
10
  "C:\\Program Files\\Git\\bin\\bash.exe",
@@ -16,7 +17,8 @@ const WINDOWS_BASH_CANDIDATES = [
16
17
  * POSIX keeps `/bin/bash`. Windows has no `/bin/bash`, and the `bash.exe` found
17
18
  * on PATH is usually the WSL launcher in System32 or the WindowsApps alias,
18
19
  * either of which would run the command inside WSL instead of Windows. Prefer
19
- * an explicit override, then Git for Windows, then a non-WSL `bash.exe` on PATH.
20
+ * an explicit override, then Pi's shellPath, Git for Windows, and a non-WSL
21
+ * `bash.exe` on PATH.
20
22
  *
21
23
  * Resolved lazily at spawn time, not module load: env-injection extensions
22
24
  * (e.g. pi-env) may apply settings.json `env` values after this module is
@@ -24,27 +26,62 @@ const WINDOWS_BASH_CANDIDATES = [
24
26
  *
25
27
  * Exposed for tests and reuse.
26
28
  */
27
- export function resolveDefaultShell() {
29
+ export function resolveDefaultShell(shellPath) {
28
30
  const fromEnv = process.env.PI_BETTER_BACKGROUND_TASKS_SHELL;
29
31
  if (fromEnv)
30
32
  return fromEnv;
31
33
  if (process.platform !== "win32")
32
34
  return "/bin/bash";
33
- for (const candidate of WINDOWS_BASH_CANDIDATES) {
35
+ const configured = shellPath ?? readWindowsShellSetting();
36
+ const tried = [];
37
+ if (configured?.trim()) {
38
+ const candidate = /^~[\\/]/.test(configured) ? win32.join(homedir(), configured.slice(2)) : configured;
39
+ tried.push(candidate);
40
+ try {
41
+ accessSync(candidate, constants.F_OK);
42
+ return candidate;
43
+ }
44
+ catch { /* An unavailable setting leaves standard Windows discovery enabled. */ }
45
+ }
46
+ const gitCandidates = [process.env.ProgramFiles, process.env["ProgramFiles(x86)"]]
47
+ .filter((directory) => Boolean(directory))
48
+ .map(directory => win32.join(directory, "Git", "bin", "bash.exe"));
49
+ for (const candidate of new Set([...gitCandidates, ...WINDOWS_BASH_CANDIDATES])) {
50
+ tried.push(candidate);
34
51
  if (existsSync(candidate))
35
52
  return candidate;
36
53
  }
37
- for (const dir of (process.env.PATH ?? "").split(";")) {
54
+ for (const dir of (process.env.PATH ?? process.env.Path ?? "").split(";")) {
38
55
  const trimmed = dir.trim();
39
56
  if (!trimmed || /(^|[\\/])(system32|windowsapps)([\\/]|$)/i.test(trimmed))
40
57
  continue;
41
- const candidate = join(trimmed, "bash.exe");
58
+ const candidate = win32.join(trimmed, "bash.exe");
59
+ tried.push(candidate);
42
60
  if (existsSync(candidate))
43
61
  return candidate;
44
62
  }
45
- // Nothing usable found: keep the POSIX default so the failure surfaces as a
46
- // logged spawn error for the task instead of crashing the whole host process.
47
- return "/bin/bash";
63
+ throw new Error("No Bash executable found for Windows Background tasks. Set Pi's shellPath in settings.json or "
64
+ + "PI_BETTER_BACKGROUND_TASKS_SHELL to a working bash.exe. Searched:\n " + [...new Set(tried)].join("\n "));
65
+ }
66
+ function readWindowsShellSetting() {
67
+ const agentDir = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
68
+ try {
69
+ const settings = JSON.parse(readFileSync(join(agentDir, "settings.json"), "utf8"));
70
+ return typeof settings?.shellPath === "string" ? settings.shellPath : undefined;
71
+ }
72
+ catch {
73
+ return undefined;
74
+ }
75
+ }
76
+ /** Capture effective session settings before dispatching a Windows launch. */
77
+ export function resolveWindowsLaunchShell(pi) {
78
+ if (process.platform !== "win32")
79
+ return undefined;
80
+ const override = process.env.PI_BETTER_BACKGROUND_TASKS_SHELL;
81
+ if (override)
82
+ return override;
83
+ const settings = pi.getSettings?.();
84
+ return resolveDefaultShell(typeof settings?.shellPath === "string" ? settings.shellPath : undefined);
48
85
  }
49
86
  /** How long a timed-out process group has to exit on SIGTERM before SIGKILL. */
50
87
  const TERMINATION_GRACE_MS = 2_000;
@@ -497,7 +534,8 @@ export function commandExecution(spec) {
497
534
  const [command, ...args] = spec.argv;
498
535
  return { execPath: command, execArgs: args };
499
536
  }
500
- return { execPath: resolveDefaultShell(), execArgs: [spec.loginShell === false ? "-c" : "-lc", spec.command] };
537
+ const resolved = process.platform === "win32" ? spec.resolvedWindowsShell : undefined;
538
+ return { execPath: resolved ?? resolveDefaultShell(), execArgs: [spec.loginShell === false ? "-c" : "-lc", spec.command] };
501
539
  }
502
540
  function spawnArgs(spec, detached, stdio) {
503
541
  const env = { ...process.env, ...spec.env };
@@ -32,14 +32,15 @@
32
32
  */
33
33
  import { spawn } from "node:child_process";
34
34
  import { closeSync, openSync, realpathSync } from "node:fs";
35
- import { resolve } from "node:path";
35
+ import { join, resolve } from "node:path";
36
36
  import { setTimeout as delay } from "node:timers/promises";
37
37
  import { fileURLToPath } from "node:url";
38
+ import { watchOutcomeFingerprint } from "./watch-fingerprint.mjs";
38
39
  import { evaluateCondition, validateCondition } from "./conditions.mjs";
39
40
  import { completeUtf8Length, stopProcessGroup, utf8PrefixLength } from "./process.mjs";
40
41
  import { readProcessStartToken } from "./process-identity.mjs";
41
42
  import { processGroupAlive } from "./identity.mjs";
42
- import { appendEvent, appendStreamBytes, claimLaunch, ensureSupervisorTaskDir, readLaunchRecord, readStopRequest, writeCommandRecord, writeTerminalRecord, } from "./store.mjs";
43
+ import { appendEvent, appendStreamBytes, claimLaunch, ensureSupervisorTaskDir, readLaunchRecord, readStopRequest, writeCommandRecord, writeTerminalRecord, writeTextAtomic, } from "./store.mjs";
43
44
  import { DEFAULT_TERMINAL_TAIL_BYTES, DEFAULT_WATCH_INTERVAL_MS, SUPERVISOR_GROUP_CLEANUP_DEADLINE_MS, SUPERVISOR_POLL_MS, SUPERVISOR_RECORD_VERSION, SUPERVISOR_RUNNER_VERSION, SUPERVISOR_TERMINATION_GRACE_MS, } from "./types.mjs";
44
45
  /** How long the runner waits for `close` after the child reported `exit`. */
45
46
  const PIPE_CLOSE_GRACE_MS = 1_000;
@@ -117,6 +118,39 @@ function streamChunk(sink, chunk, maxBytes) {
117
118
  sink.tailBytes = keep.length;
118
119
  }
119
120
  }
121
+ /** Coalesce stream bursts while retaining the timestamp of the last byte, including discarded output. */
122
+ function progressRecorder(directory) {
123
+ const path = join(directory, "progress.json");
124
+ let pending;
125
+ let timer;
126
+ let lastWrite = 0;
127
+ const flush = () => {
128
+ timer = undefined;
129
+ if (!pending)
130
+ return;
131
+ try {
132
+ writeTextAtomic(path, JSON.stringify(pending));
133
+ }
134
+ catch (error) {
135
+ process.stderr.write(`Could not record Background progress: ${String(error)}\n`);
136
+ }
137
+ lastWrite = Date.now();
138
+ };
139
+ return (observedAt, fingerprint) => {
140
+ if (fingerprint !== undefined && pending?.fingerprint === fingerprint)
141
+ return;
142
+ pending = { observedAt, fingerprint };
143
+ if (timer)
144
+ return;
145
+ const remaining = lastWrite + 1000 - Date.now();
146
+ if (remaining <= 0)
147
+ flush();
148
+ else {
149
+ timer = setTimeout(flush, remaining);
150
+ timer.unref();
151
+ }
152
+ };
153
+ }
120
154
  function startToken(pid) {
121
155
  return pid === undefined ? undefined : readProcessStartToken(pid);
122
156
  }
@@ -389,15 +423,21 @@ function runChild(ctx, plan) {
389
423
  };
390
424
  child.stdout?.on("data", (chunk) => {
391
425
  const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
392
- if (plan.mode === "stream")
426
+ if (plan.mode === "stream") {
393
427
  streamChunk(ctx.stdout, buffer, plan.maxBytes);
428
+ if (buffer.length)
429
+ ctx.progress(Date.now());
430
+ }
394
431
  else
395
432
  captureChunk(stdoutCapture, buffer, plan.maxBytes);
396
433
  });
397
434
  child.stderr?.on("data", (chunk) => {
398
435
  const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
399
- if (plan.mode === "stream")
436
+ if (plan.mode === "stream") {
400
437
  streamChunk(ctx.stderr, buffer, plan.maxBytes);
438
+ if (buffer.length)
439
+ ctx.progress(Date.now());
440
+ }
401
441
  else
402
442
  captureChunk(stderrCapture, buffer, plan.maxBytes);
403
443
  });
@@ -596,6 +636,7 @@ async function runWatch(ctx) {
596
636
  if (ctx.finalized)
597
637
  return;
598
638
  ctx.checks += 1;
639
+ ctx.progress(outcome.endedAt, watchOutcomeFingerprint({ ...asCommandResult(outcome), ...(outcome.spawnError ? { error: outcome.spawnError } : {}) }));
599
640
  // Per-check output keeps the streams apart: stdout bytes in stdout.log, stderr in stderr.log.
600
641
  streamChunk(ctx.stdout, Buffer.from(outcome.stdout), ctx.launch.maxLogBytes);
601
642
  streamChunk(ctx.stderr, Buffer.from(outcome.stderr), ctx.launch.maxLogBytes);
@@ -823,9 +864,11 @@ function main() {
823
864
  checks: 0,
824
865
  stdout,
825
866
  stderr,
867
+ progress: progressRecorder(paths.dir),
826
868
  stopRequested: false,
827
869
  finalized: false,
828
870
  };
871
+ ctx.progress(ctx.startedAt);
829
872
  appendEvent(paths.events, `claimed runner_pid=${process.pid} runner_version=${SUPERVISOR_RUNNER_VERSION} kind=${launch.kind} cwd=${launch.command.cwd}`);
830
873
  const onSignal = (signal) => {
831
874
  appendEvent(paths.events, `runner received ${signal}`);
@@ -328,13 +328,13 @@ function readText(path) {
328
328
  catch (error) {
329
329
  if (error.code === "ENOENT")
330
330
  return { missing: true };
331
- return { missing: true, error: error instanceof Error ? error.message : String(error) };
331
+ return { missing: false, error: error instanceof Error ? error.message : String(error) };
332
332
  }
333
333
  }
334
334
  function readJsonRecord(path, problem) {
335
335
  const read = readText(path);
336
- if (read.missing)
337
- return { missing: true, error: read.error };
336
+ if (read.value === undefined)
337
+ return { missing: read.missing, error: read.error };
338
338
  let parsed;
339
339
  try {
340
340
  parsed = JSON.parse(read.value);
@@ -0,0 +1,69 @@
1
+ // Generated by src/supervisor/emit-runner.mjs from the TypeScript source.
2
+ // Do not edit: change the source and re-run the emitter (a drift test enforces this).
3
+
4
+ import { createHash } from "node:crypto";
5
+ /** Version tag of the watch outcome fingerprint. A value from another version is adopted, never compared. */
6
+ export const WATCH_FINGERPRINT_VERSION = "v1";
7
+ /** OSC and CSI control sequences are display markup, not content. */
8
+ const TERMINAL_ESCAPE = /\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)|\u001b\[[0-?]*[ -/]*[@-~]/g;
9
+ /**
10
+ * Text as the terminal would settle it. Redraw frames and control sequences are
11
+ * display churn: repainting the same visible line is not a new observation.
12
+ */
13
+ function settledTerminalText(text) {
14
+ return text
15
+ .replace(TERMINAL_ESCAPE, "")
16
+ .split("\n")
17
+ .map((line) => {
18
+ // A CR immediately before LF ends the line; any other CR overwrites it in place.
19
+ const body = line.endsWith("\r") ? line.slice(0, -1) : line;
20
+ return (body.split("\r").at(-1) ?? "").replace(/[ \t]+$/, "");
21
+ })
22
+ .join("\n")
23
+ .replace(/\n+$/, "");
24
+ }
25
+ /** Objects compare by content regardless of key order, so reordered keys are not progress. */
26
+ function canonicalJsonText(value) {
27
+ if (Array.isArray(value))
28
+ return `[${value.map(canonicalJsonText).join(",")}]`;
29
+ if (value && typeof value === "object") {
30
+ const record = value;
31
+ const entries = Object.keys(record).sort()
32
+ .map((key) => `${JSON.stringify(key)}:${canonicalJsonText(record[key])}`);
33
+ return `{${entries.join(",")}}`;
34
+ }
35
+ return JSON.stringify(value) ?? "null";
36
+ }
37
+ /** stdout compares as JSON content when it parses, and as settled text otherwise. */
38
+ function canonicalWatchStdout(stdout) {
39
+ const settled = settledTerminalText(stdout);
40
+ try {
41
+ return `json:${canonicalJsonText(JSON.parse(settled))}`;
42
+ }
43
+ catch {
44
+ return `text:${settled}`;
45
+ }
46
+ }
47
+ /**
48
+ * What a poll observed, independent of when it ran. Exit status, signal, error,
49
+ * stdout content, and stderr content are included; poll metadata (start time,
50
+ * end time, duration, check count) is deliberately not, so it can never hide a
51
+ * watch that reports the same outcome forever. Watch stdout may carry its own
52
+ * timestamps: projecting meaningful fields is the caller's job, not this
53
+ * fingerprint's guess.
54
+ */
55
+ export function watchOutcomeFingerprint(result) {
56
+ // A runner may report why the check itself could not run; that is part of the
57
+ // observed outcome, not poll metadata.
58
+ const reported = result.error;
59
+ const error = typeof reported === "string" ? settledTerminalText(reported) : null;
60
+ const payload = JSON.stringify([
61
+ result.exitCode,
62
+ result.signal ?? null,
63
+ result.timedOut === true,
64
+ error,
65
+ canonicalWatchStdout(result.stdout),
66
+ settledTerminalText(result.stderr),
67
+ ]);
68
+ return `${WATCH_FINGERPRINT_VERSION}:${createHash("sha256").update(payload).digest("hex")}`;
69
+ }