pi-better-background-tasks 0.18.0 → 0.20.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 (63) hide show
  1. package/README.md +25 -13
  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/client.mjs +30 -3
  12. package/runtime-client/src/runtime/root.mjs +5 -2
  13. package/runtime-client/src/runtime/work-client.mjs +150 -7
  14. package/src/adapter-contract.ts +1 -1
  15. package/src/goal-provider.ts +31 -16
  16. package/src/index.ts +25 -9
  17. package/src/managed-authority.ts +5 -3
  18. package/src/managed-client.ts +20 -7
  19. package/src/managed-frontend.ts +135 -19
  20. package/src/navigator-provider.ts +19 -5
  21. package/src/observed-wait-client.ts +10 -0
  22. package/src/observed-waits.ts +321 -53
  23. package/src/process-identity.ts +18 -2
  24. package/src/process.ts +48 -14
  25. package/src/registry.ts +53 -5
  26. package/src/review-settings.ts +18 -0
  27. package/src/runtime.ts +27 -82
  28. package/src/sandbox.ts +14 -11
  29. package/src/shared-callback-batcher.ts +11 -2
  30. package/src/shared-navigator-panels.ts +26 -4
  31. package/src/shared-navigator.ts +244 -40
  32. package/src/shared-operation-coordinator/assignment-observation.mjs +43 -35
  33. package/src/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  34. package/src/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  35. package/src/shared-operation-coordinator/src/background-requests.ts +14 -3
  36. package/src/shared-operation-coordinator/src/discovery.ts +5 -3
  37. package/src/shared-operation-coordinator/src/operations.ts +50 -2
  38. package/src/shared-operation-coordinator/src/outbox.ts +9 -0
  39. package/src/shared-operation-coordinator/src/result-supervision.ts +12 -0
  40. package/src/shared-operation-coordinator/src/rows.ts +2 -0
  41. package/src/shared-operation-coordinator/src/schema.ts +40 -24
  42. package/src/shared-operation-coordinator/src/store.ts +40 -8
  43. package/src/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  44. package/src/shared-operation-coordinator/src/types.ts +5 -1
  45. package/src/shared-sandbox-core.ts +1 -1
  46. package/src/shared-work-client.mjs +150 -7
  47. package/src/stall.ts +7 -4
  48. package/src/supervised-progress.ts +43 -0
  49. package/src/supervisor/README.md +1 -4
  50. package/src/supervisor/emit-runner.mjs +1 -0
  51. package/src/supervisor/generated/process-identity.mjs +20 -2
  52. package/src/supervisor/generated/process.mjs +52 -14
  53. package/src/supervisor/generated/runner.mjs +47 -4
  54. package/src/supervisor/generated/store.mjs +3 -3
  55. package/src/supervisor/generated/watch-fingerprint.mjs +69 -0
  56. package/src/supervisor/runner.ts +38 -3
  57. package/src/supervisor/store.ts +3 -3
  58. package/src/supervisor/supervisor.ts +6 -3
  59. package/src/task-diagnostics.ts +1 -1
  60. package/src/tools.ts +67 -54
  61. package/src/types.ts +7 -3
  62. package/src/watch-fingerprint.ts +70 -0
  63. package/src/work-observation.ts +46 -19
@@ -12,7 +12,7 @@ import { setParentCallbackPending, listPendingParentCallbacks, listRecentBackgro
12
12
  import { BackgroundRequests } from "./background-requests.ts";
13
13
  import { StoreError } from "./errors.ts";
14
14
  import { SubagentLaunchJournal } from "./subagent-launch.ts";
15
- import { resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.ts";
15
+ import { resultSupervisionChanges, resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.ts";
16
16
  import { acceptTaskCancellation, getTaskCancellation, recordTaskStopRequested, admitTaskCancellation, authorizedTaskCancellation, finishTaskCancellation, cancellationRuntimeEpoch, acceptAuthorizedTaskCancellation, taskCancellationManaged, pendingTaskCancellations, finishTaskCancellationIntent, unknownTaskCancellation } from "./task-cancellation.ts";
17
17
  import type { TaskCancellationIntent, TaskCancellationRequest } from "./task-cancellation.ts";
18
18
  import { repairFailedResume, type RepairResumeInput } from "./recovery.ts";
@@ -26,9 +26,11 @@ import {
26
26
  requirePath,
27
27
  } from "./validate.ts";
28
28
  import { ensureSchema } from "./schema.ts";
29
- import { createContext, openDatabase, type StoreContext } from "./sqlite.ts";
29
+ import { ensureAssignmentChanges } from "./assignment-changes.ts";
30
+ import { createContext, openDatabase, run, type StoreContext } from "./sqlite.ts";
30
31
  import {
31
32
  getOperation as readOperationRecord,
33
+ listAssignmentCleanupOperations as readAssignmentCleanupOperations,
32
34
  listOperations as readOperationRecords,
33
35
  listRunningSupervisedBy as readRunningSupervisedBy,
34
36
  releaseSupervision as writeSupervisionRelease,
@@ -66,6 +68,7 @@ import {
66
68
  } from "./waits.ts";
67
69
  import {
68
70
  claimOutbox as writeOutboxClaim,
71
+ hasDeliveredWaitDependency as readDeliveredWaitDependency,
69
72
  listDispatchableOutboxRecipients as readDispatchableOutboxRecipients,
70
73
  listOutbox as readOutbox,
71
74
  markOutboxDelivered as writeOutboxDelivery,
@@ -124,6 +127,8 @@ import {
124
127
  } from "./types.ts";
125
128
 
126
129
  export interface Store {
130
+ hasSubagentManagement(): boolean;
131
+ resultSupervisionChanges(after?: Parameters<typeof resultSupervisionChanges>[1]): ReturnType<typeof resultSupervisionChanges>;
127
132
  subagentLaunchJournal(): SubagentLaunchJournal;
128
133
  resultScopeManaged(scope: string): boolean;
129
134
  handoffResultScope(input: Parameters<typeof handoffResultScope>[1]): ReturnType<typeof handoffResultScope>;
@@ -160,18 +165,17 @@ export interface Store {
160
165
 
161
166
  // ---- operations ----
162
167
 
163
- /**
164
- * Register a durable operation for one task launch. The owner, task id,
165
- * launch token and observer are immutable: a replay of the same launch
166
- * returns `created: false`, and any difference is refused with
167
- * `operation-conflict` or `task-ownership`.
168
- */
169
168
  backgroundRequests(): BackgroundRequests;
170
169
  setParentCallbackPending(taskId: string, pending: boolean): boolean;
171
170
  listPendingParentCallbacks(scope: ParentCallbackScope, options?: ParentCallbackPage): OperationRecord[];
172
171
  listRecentBackgroundTerminals(options: RecentBackgroundTerminalPage): OperationRecord[];
173
172
  seedPendingParentCallbacks(options?: { limit?: number }): { done: boolean; seeded: number };
174
173
  setUpgradeFence(epoch: string | null): void;
174
+ /**
175
+ * Register a durable launch. Owner, task id, launch token, observer, and
176
+ * assignment attempt provenance are immutable. An exact replay returns
177
+ * `created: false`, even after assignment end, and admits no new work.
178
+ */
175
179
  registerOperation(input: RegisterOperationInput): RegisterOperationResult;
176
180
  /**
177
181
  * Replace supervision identity and/or report observer health
@@ -196,6 +200,12 @@ export interface Store {
196
200
  recordTerminalOutcome(input: RecordTerminalOutcomeInput): RecordTerminalOutcomeResult;
197
201
  getOperation(operationId: string): OperationRecord | null;
198
202
  listOperations(filter?: OperationFilter): OperationRecord[];
203
+ /**
204
+ * Read up to 256 unfinished cleanup obligations in operation id order.
205
+ * The cursor is exclusive. Start each new sweep without a cursor.
206
+ */
207
+ listAssignmentCleanupOperations(limit: number, afterOperationId?: string): OperationRecord[];
208
+ verifyAssignmentCleanup(operationId: string, launchToken: string, terminalRevision: number): boolean;
199
209
  /** Running operations currently assigned to this supervising host. */
200
210
  listRunningSupervisedBy(hostId: string): OperationRecord[];
201
211
  listOperationEvidence(operationId: string, terminalRevision?: number): OperationEvidenceRecord[];
@@ -309,6 +319,7 @@ export interface Store {
309
319
  // ---- outbox ----
310
320
 
311
321
  listOutbox(filter?: OutboxFilter): OutboxEventRecord[];
322
+ hasDeliveredWaitDependency(operationId: string, terminalRevision: number, recipient: OwnerIdentity): boolean;
312
323
  /** Lightweight dispatch candidates; evidence is read only after a claim succeeds. */
313
324
  listDispatchableOutboxRecipients(): Array<{ recipient: OwnerIdentity; count: number }>;
314
325
  /** Claim pending deliveries for a `ready`/`resuming` generation. */
@@ -327,6 +338,7 @@ export function openStore(options: StoreOptions): Store {
327
338
  const ctx: StoreContext = createContext(db, options.now ? { now: options.now } : {});
328
339
  try {
329
340
  ensureSchema(ctx);
341
+ ensureAssignmentChanges(ctx);
330
342
  } catch (error) {
331
343
  try {
332
344
  db.close();
@@ -351,6 +363,8 @@ export function openStore(options: StoreOptions): Store {
351
363
  resultScopeManaged(scope) { alive(); return resultScopeManaged(ctx, scope); },
352
364
  handoffResultScope(input) { alive(); return handoffResultScope(ctx, input); },
353
365
  resultSupervision(id) { alive(); return resultSupervision(ctx, id); },
366
+ hasSubagentManagement() { alive(); return Boolean(ctx.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='subagent_management'").get()); },
367
+ resultSupervisionChanges(after) { alive(); return resultSupervisionChanges(ctx, after); },
354
368
  resultSupervisions(activeOnly) { alive(); return resultSupervisions(ctx, activeOnly); },
355
369
  handoffResultSupervision(input) { alive(); return handoffResultSupervision(ctx, input); },
356
370
  handoffResultSupervisions(input) { alive(); return handoffResultSupervisions(ctx, input); },
@@ -408,6 +422,20 @@ export function openStore(options: StoreOptions): Store {
408
422
  alive();
409
423
  return readOperationRecords(ctx, filter);
410
424
  },
425
+ listAssignmentCleanupOperations(limit, afterOperationId) {
426
+ alive();
427
+ return readAssignmentCleanupOperations(ctx, limit, afterOperationId);
428
+ },
429
+ verifyAssignmentCleanup(operationId, launchToken, terminalRevision) {
430
+ alive();
431
+ if (!Number.isSafeInteger(terminalRevision) || terminalRevision < 1) return false;
432
+ return run(ctx, `INSERT OR IGNORE INTO coordinator_state (key, value)
433
+ SELECT 'assignment-cleanup-verified:' || op.operation_id, op.launch_token
434
+ FROM operations op JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
435
+ JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
436
+ WHERE op.operation_id = ? AND op.launch_token = ? AND op.terminal_revision = ?`,
437
+ operationId, launchToken, terminalRevision) > 0;
438
+ },
411
439
  listRunningSupervisedBy(hostId) {
412
440
  alive();
413
441
  return readRunningSupervisedBy(ctx, hostId);
@@ -533,6 +561,10 @@ export function openStore(options: StoreOptions): Store {
533
561
  alive();
534
562
  return readOutbox(ctx, filter);
535
563
  },
564
+ hasDeliveredWaitDependency(operationId, terminalRevision, recipient) {
565
+ alive();
566
+ return readDeliveredWaitDependency(ctx, operationId, terminalRevision, recipient);
567
+ },
536
568
  listDispatchableOutboxRecipients() {
537
569
  alive();
538
570
  return readDispatchableOutboxRecipients(ctx);
@@ -1,5 +1,5 @@
1
1
  // Generated from packages/operation-coordinator/src/subagent-launch.ts. Do not edit directly.
2
- import { randomBytes } from "node:crypto";
2
+ import { createHash, randomBytes } from "node:crypto";
3
3
  import type { StoreContext } from "./sqlite.ts";
4
4
 
5
5
  export interface LaunchAttempt {
@@ -67,6 +67,26 @@ export class SubagentLaunchJournal {
67
67
  pendingIntents(): LaunchIntent[] {
68
68
  return this.db.prepare("SELECT * FROM subagent_launch_intents WHERE state='accepted'").all() as unknown as LaunchIntent[];
69
69
  }
70
+ private progressKey(owner: string, key: string) { return `launch-progress:${createHash('sha256').update(JSON.stringify([owner, key])).digest('hex')}`; }
71
+ private progress(owner: string, key: string) {
72
+ const row = this.db.prepare('SELECT value FROM coordinator_state WHERE key=?').get(this.progressKey(owner, key));
73
+ return row ? JSON.parse(String(row.value)) as { acceptedAt: number; lastProgressAt: number } : undefined;
74
+ }
75
+ private noteProgress(owner: string, key: string) {
76
+ const previous = this.progress(owner, key), now = Date.now();
77
+ this.db.prepare('INSERT OR REPLACE INTO coordinator_state (key,value) VALUES (?,?)').run(this.progressKey(owner, key),
78
+ JSON.stringify({ acceptedAt: previous?.acceptedAt ?? now, lastProgressAt: now }));
79
+ }
80
+ lifecycleReasons(owner?: string, key?: string) {
81
+ const exact = owner !== undefined && key !== undefined ? this.read(owner, key) : undefined;
82
+ const intents = owner !== undefined ? exact?.state === 'accepted' ? [exact] : [] : this.pendingIntents();
83
+ return intents.map(intent => ({ kind: 'task', id: this.progressKey(intent.owner, intent.request_key),
84
+ owner: intent.owner, management: { epoch: intent.epoch }, acceptedAt: this.progress(intent.owner, intent.request_key)?.acceptedAt ?? null,
85
+ lastProgressAt: this.progress(intent.owner, intent.request_key)?.lastProgressAt ?? null, executionDeadline: null, nextDeadline: null,
86
+ attempts: (JSON.parse(intent.attempts) as LaunchAttempt[]).map(attempt => ({ id: attempt.id, sessionId: attempt.sessionId,
87
+ state: attempt.state, writer: { pid: attempt.writerPid ?? attempt.pid, start: attempt.writerStartTime ?? attempt.pidStartTime } })),
88
+ recovery: 'drain-accepted-launch-until-journal-return-or-authoritative-handoff' }));
89
+ }
70
90
  finishRecovery(owner: string, key: string, epoch: number, result: unknown) {
71
91
  this.transaction(() => {
72
92
  this.current(epoch);
@@ -83,6 +103,7 @@ export class SubagentLaunchJournal {
83
103
  return { prior: true, ...prior };
84
104
  }
85
105
  this.db.prepare("INSERT INTO subagent_launch_intents VALUES (?, ?, ?, ?, 'accepted', '[]', NULL)").run(owner, key, digest, epoch);
106
+ this.noteProgress(owner, key);
86
107
  return this.read(owner, key);
87
108
  });
88
109
  }
@@ -96,6 +117,7 @@ export class SubagentLaunchJournal {
96
117
  const attempt: LaunchAttempt = { ...input, token: randomBytes(32).toString("hex"), state: "prepared" };
97
118
  attempts.push(attempt);
98
119
  this.db.prepare("UPDATE subagent_launch_intents SET attempts=? WHERE owner=? AND request_key=?").run(JSON.stringify(attempts), owner, key);
120
+ this.noteProgress(owner, key);
99
121
  return attempt;
100
122
  });
101
123
  }
@@ -108,6 +130,7 @@ export class SubagentLaunchJournal {
108
130
  if (attempt.writerPid && attempt.writerPid !== pid) throw new Error("Launch writer does not match spawned process");
109
131
  Object.assign(attempt, { state: "spawned", pid, pidStartTime });
110
132
  this.db.prepare("UPDATE subagent_launch_intents SET attempts=? WHERE owner=? AND request_key=?").run(JSON.stringify(attempts), owner, key);
133
+ this.noteProgress(owner, key);
111
134
  });
112
135
  }
113
136
  finish(owner: string, key: string, epoch: number, result: unknown) {
@@ -19,7 +19,7 @@
19
19
  * spawned, so a crash is reconciled instead of relaunched.
20
20
  */
21
21
 
22
- /** Schema version this build writes and accepts. Any other version is refused. */
22
+ /** Schema version this build writes after creating or migrating a store. */
23
23
  export const SCHEMA_VERSION = 4;
24
24
 
25
25
  /** Who receives an operation's result and decides what happens next. */
@@ -107,6 +107,8 @@ export interface RegisterOperationInput {
107
107
  */
108
108
  launchToken: string;
109
109
  owner: OwnerIdentity;
110
+ /** Exact registered worker attempt for this launch. Omit when no binding is known. */
111
+ assignmentAttemptId?: string;
110
112
  observer: ObserverIdentity;
111
113
  supervision?: SupervisionIdentity | null;
112
114
  /** Reference to the permission/authority snapshot. Never credential material. */
@@ -122,6 +124,8 @@ export interface OperationRecord {
122
124
  taskId: string;
123
125
  launchToken: string;
124
126
  owner: OwnerIdentity;
127
+ /** Immutable launch provenance. Absent on unbound and legacy operations. */
128
+ assignmentAttemptId?: string;
125
129
  observer: ObserverIdentity;
126
130
  supervision: SupervisionIdentity | null;
127
131
  authorityRef: string | null;
@@ -69,7 +69,7 @@ export type SandboxPermissions = {
69
69
  */
70
70
  commandTimeoutSeconds?: number | null;
71
71
  network: boolean;
72
- /** Fixed process_list adapter only; omitted legacy profiles keep it Off. */
72
+ /** Fixed process adapters (inventory and Darwin identity compatibility); omitted legacy profiles keep it Off. */
73
73
  processAccess?: "off" | "read";
74
74
  };
75
75
 
@@ -1,5 +1,17 @@
1
+ import { existsSync } from "node:fs";
1
2
  import { connect } from "node:net";
2
3
  import { performance } from "node:perf_hooks";
4
+ import { setTimeout as delay } from "node:timers/promises";
5
+
6
+ /** A persisted session can own work even when its selected branch is empty. */
7
+ export function shouldRestoreWorkObservation(event, session) {
8
+ if (event?.piBetterObserveWork) return true;
9
+ const reason = event?.reason;
10
+ if (reason === "new") return false;
11
+ if (reason !== "startup" || typeof session?.getSessionFile !== "function") return true;
12
+ const file = session.getSessionFile();
13
+ return file ? existsSync(file) : Boolean(session.getLeafId?.());
14
+ }
3
15
 
4
16
  /** SDK-free observation stream. Cached snapshots are the only synchronous read API. */
5
17
  export class WorkClient {
@@ -12,6 +24,11 @@ export class WorkClient {
12
24
  scope;
13
25
  buffer = "";
14
26
  closed = false;
27
+ recoveryTimer;
28
+ recoveryActive = false;
29
+ recoveryAgain = false;
30
+ recoveryDelay = 100;
31
+ scopeGeneration = 0;
15
32
 
16
33
  constructor(socketPath, agentDir, requiredCapabilities = []) {
17
34
  this.socket = typeof socketPath === "string" ? connect(socketPath) : socketPath;
@@ -26,8 +43,8 @@ export class WorkClient {
26
43
  const message = JSON.parse(line);
27
44
  if (message.type === "event") {
28
45
  if (message.event.type === "runtime_catalog_snapshot") { for (const listener of this.catalogListeners) listener(message.event.snapshot); continue; }
29
- if (message.event.type === "resync_required") { this.degrade(message.event.reason); void this.resync().catch(error => this.degrade(String(error))); }
30
- else if (message.event.type === "runtime_snapshot") this.accept(message.event.snapshot);
46
+ if (message.event.type === "resync_required") { this.degrade(message.event.reason); this.scheduleRecovery(); }
47
+ else if (message.event.type === "runtime_snapshot") this.accept(message.event.snapshot, message.event.previousSeq);
31
48
  } else {
32
49
  const request = this.pending.get(message.id);
33
50
  if (!request) continue;
@@ -37,7 +54,9 @@ export class WorkClient {
37
54
  } catch (error) { this.fail(error); }
38
55
  }
39
56
  });
40
- this.socket.on("error", error => this.fail(error));
57
+ this.socket.on("error", error => this.fail(["ECONNRESET", "EPIPE"].includes(error.code)
58
+ ? Object.assign(new Error(`runtime-unavailable: disconnected (${error.code}); resync required`, { cause: error }), { code: error.code })
59
+ : error));
41
60
  this.socket.on("close", () => this.fail(new Error("runtime-unavailable: disconnected; resync required")));
42
61
  this.ready = this.request("hello", { protocolVersion: 1, runtimeRoot: agentDir, requiredCapabilities: ["runtime-state-v1", "runtime-subscriptions-v1", ...requiredCapabilities] })
43
62
  .then(async hello => { if (typeof socketPath === "string" && hello.capabilities?.includes("runtime-client-retention-v1")) await this.request("runtime_register_client", { clientId: `work-${process.pid}` }); return hello; });
@@ -59,27 +78,63 @@ export class WorkClient {
59
78
  this.snapshot = { ...this.snapshot, status: "degraded", reason, rows: this.snapshot?.rows ?? [] };
60
79
  this.notify();
61
80
  }
62
- accept(snapshot) {
81
+ accept(snapshot, previousSeq) {
63
82
  if (this.snapshot?.instanceId === snapshot.instanceId && snapshot.seq < this.snapshot.seq) return;
64
83
  if (this.snapshot?.instanceId && this.snapshot.instanceId !== snapshot.instanceId) {
65
84
  this.degrade("instance-changed: resync required");
66
85
  snapshot = { ...snapshot, resyncRequired: true, resyncReason: "instance-changed" };
67
- } else if (this.snapshot?.seq !== undefined && snapshot.seq > this.snapshot.seq + 1) {
86
+ } else if (this.snapshot?.seq !== undefined && Number.isSafeInteger(previousSeq) && previousSeq > this.snapshot.seq) {
68
87
  this.degrade("sequence-gap: replacing with a full authoritative snapshot");
69
88
  snapshot = { ...snapshot, resyncRequired: true, resyncReason: "sequence-gap" };
70
89
  }
71
- // Every event contains a complete bounded snapshot; gaps do not require inferred deltas.
90
+ // Global seq may skip unrelated changes; only a missing subscription
91
+ // predecessor indicates loss. The received snapshot is still complete.
72
92
  this.snapshot = Object.freeze(snapshot); this.notify();
73
93
  }
94
+ scheduleRecovery(delay = 0) {
95
+ if (this.closed) return;
96
+ if (this.recoveryActive) { this.recoveryAgain = true; return; }
97
+ if (this.recoveryTimer) return;
98
+ this.recoveryTimer = setTimeout(() => {
99
+ this.recoveryTimer = undefined;
100
+ void this.recover();
101
+ }, delay);
102
+ this.recoveryTimer.unref?.();
103
+ }
104
+ async recover() {
105
+ const generation = this.scopeGeneration;
106
+ this.recoveryActive = true;
107
+ let retry = false;
108
+ try { await this.resync(); this.recoveryDelay = 100; }
109
+ catch (error) {
110
+ if (!this.closed && generation === this.scopeGeneration) {
111
+ this.degrade(String(error));
112
+ retry = /runtime-(?:timeout|overloaded|unhealthy)/.test(String(error));
113
+ }
114
+ } finally {
115
+ this.recoveryActive = false;
116
+ const again = this.recoveryAgain;
117
+ this.recoveryAgain = false;
118
+ if (!this.closed && (again || retry && generation === this.scopeGeneration)) {
119
+ this.scheduleRecovery(again ? 0 : this.recoveryDelay);
120
+ this.recoveryDelay = Math.min(1000, this.recoveryDelay * 2);
121
+ }
122
+ }
123
+ }
74
124
  async subscribe(scope) {
75
125
  await this.ready;
126
+ this.scopeGeneration++;
127
+ clearTimeout(this.recoveryTimer); this.recoveryTimer = undefined;
128
+ this.recoveryAgain = false; this.recoveryDelay = 100;
76
129
  this.scope = scope;
77
130
  const snapshot = await this.request("runtime_subscribe", { scope });
78
131
  this.accept(snapshot); return snapshot;
79
132
  }
80
133
  async resync() {
134
+ const generation = this.scopeGeneration;
81
135
  const snapshot = await this.request("runtime_subscribe", { scope: this.scope, sinceSeq: this.snapshot?.seq, instanceId: this.snapshot?.instanceId });
82
- this.accept(snapshot); return snapshot;
136
+ if (!this.closed && generation === this.scopeGeneration) this.accept(snapshot);
137
+ return snapshot;
83
138
  }
84
139
  async get(scope) {
85
140
  await this.ready;
@@ -94,9 +149,97 @@ export class WorkClient {
94
149
  fail(error) {
95
150
  if (this.closed) return;
96
151
  this.closed = true;
152
+ this.scopeGeneration++;
153
+ clearTimeout(this.recoveryTimer); this.recoveryTimer = undefined;
97
154
  for (const request of this.pending.values()) { clearTimeout(request.timer); request.reject(error); }
98
155
  this.pending.clear(); this.socket.destroy(); this.degrade(String(error));
99
156
  for (const listener of this.catalogListeners) listener({ status: "revoked" });
100
157
  }
101
158
  close() { this.fail(new Error("runtime-unavailable: client closed")); this.listeners.clear(); this.catalogListeners.clear(); }
102
159
  }
160
+
161
+ // Shared across the standalone extension copies, but never across agent roots.
162
+ const recoveryKey = Symbol.for("pi-better-runtime.connection-recovery.v2");
163
+ const recoveries = globalThis[recoveryKey] ??= new Map();
164
+ const connectionDemands = globalThis[Symbol.for("pi-better-runtime.connection-demand.v2")] ??= new Map();
165
+
166
+ /** Establish a transport only. Never replay an application request after dispatch. */
167
+ export async function connectWorkClient(socketPath, agentDir, capabilities = [], options = {}) {
168
+ const timeoutMs = options.timeoutMs ?? 60000;
169
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new Error("Invalid connection timeout");
170
+ const deadline = performance.now() + timeoutMs;
171
+ const started = performance.now();
172
+ let backoff = 100, recovered = false, lastError, recoveryError, ownedRecovery;
173
+ const remaining = () => Math.max(1, deadline - performance.now());
174
+ const key = JSON.stringify([agentDir, socketPath]);
175
+ connectionDemands.set(key, (connectionDemands.get(key) ?? 0) + 1);
176
+ try {
177
+ while (performance.now() < deadline) {
178
+ options.signal?.throwIfAborted();
179
+ const client = new WorkClient(socketPath, agentDir, capabilities);
180
+ const abort = () => client.close();
181
+ options.signal?.addEventListener("abort", abort, { once: true });
182
+ const timer = setTimeout(() => client.close(), remaining());
183
+ try {
184
+ await client.ready;
185
+ options.signal?.throwIfAborted();
186
+ return client;
187
+ } catch (error) {
188
+ client.close();
189
+ options.signal?.throwIfAborted();
190
+ lastError = error;
191
+ if (recoveryError) throw recoveryError;
192
+ if (!["ENOENT", "ECONNREFUSED", "ECONNRESET", "EPIPE"].includes(error?.code)
193
+ && !/runtime-unavailable: (?:disconnected|server closed)/.test(String(error))) throw error;
194
+ } finally {
195
+ clearTimeout(timer);
196
+ options.signal?.removeEventListener("abort", abort);
197
+ }
198
+ // Most replacement gaps need only a reconnect. Startup remains owner-safe.
199
+ if (!recovered && options.recover && performance.now() - started >= 250 && performance.now() < deadline) {
200
+ recovered = true;
201
+ let recovery = recoveries.get(key);
202
+ if (!recovery) {
203
+ const controller = new AbortController();
204
+ const budget = Math.ceil(remaining());
205
+ const timer = setTimeout(() => {
206
+ controller.abort(new Error("runtime-unavailable: reconnect deadline exceeded during recovery"));
207
+ }, budget);
208
+ const promise = waitForRecovery(Promise.resolve().then(() => options.recover({ timeoutMs: budget, signal: controller.signal })), controller.signal)
209
+ .finally(() => clearTimeout(timer));
210
+ recovery = { promise, controller, key };
211
+ recoveries.set(key, recovery);
212
+ void recovery.promise.finally(() => { if (recoveries.get(key) === recovery) recoveries.delete(key); }).catch(() => {});
213
+ }
214
+ // A caller can cancel its wait without cancelling another caller's recovery.
215
+ // Keep trying the transport while the owner-safe installer waits.
216
+ // A replacement can accept compatible clients before the pinned
217
+ // installer finishes; waiting for it would stall all subscribers.
218
+ ownedRecovery = recovery;
219
+ void recovery.promise.catch(error => { recoveryError = error; });
220
+ }
221
+ if (performance.now() >= deadline) break;
222
+ await delay(Math.min(backoff, remaining()), undefined, { signal: options.signal });
223
+ backoff = Math.min(1000, backoff * 2);
224
+ }
225
+ throw new Error("runtime-unavailable: reconnect deadline exceeded; task state is unknown, retry after recovery", { cause: lastError });
226
+ } finally {
227
+ const remainingDemand = connectionDemands.get(key) - 1;
228
+ if (remainingDemand) connectionDemands.set(key, remainingDemand);
229
+ else {
230
+ connectionDemands.delete(key);
231
+ const recovery = recoveries.get(key) ?? ownedRecovery;
232
+ if (recovery) { recoveries.delete(key); recovery.controller.abort(); }
233
+ }
234
+ }
235
+ }
236
+
237
+ function waitForRecovery(recovery, signal) {
238
+ return new Promise((resolve, reject) => {
239
+ const finish = (callback, value) => { signal.removeEventListener("abort", abort); callback(value); };
240
+ const abort = () => finish(reject, signal.reason);
241
+ signal.addEventListener("abort", abort, { once: true });
242
+ recovery.then(value => finish(resolve, value), error => finish(reject, error));
243
+ if (signal.aborted) abort();
244
+ });
245
+ }
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" },
@@ -1,6 +1,7 @@
1
1
  // Generated by src/supervisor/emit-runner.mjs from the TypeScript source.
2
2
  // Do not edit: change the source and re-run the emitter (a drift test enforces this).
3
3
 
4
+ import { readFileSync } from "node:fs";
4
5
  import { execFileSync } from "node:child_process";
5
6
  /**
6
7
  * Process start-token reads.
@@ -23,11 +24,12 @@ const TOKEN_MEMO_TTL_MS = 1_000;
23
24
  /** Bound on memo entries; the panel is small, but a long session is not. */
24
25
  const TOKEN_MEMO_MAX_ENTRIES = 512;
25
26
  const tokenMemo = new Map();
26
- function readTokenUncached(pid) {
27
+ function readTokenUncached(pid, admission = false) {
27
28
  if (!Number.isInteger(pid) || pid <= 0 || process.platform === "win32")
28
29
  return undefined;
29
30
  try {
30
- const output = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
31
+ const output = execFileSync(admission ? "/bin/ps" : "ps", ["-o", "lstart=", "-p", String(pid)], {
32
+ env: admission ? { LC_ALL: "C", TZ: "UTC0", PATH: "/usr/bin:/bin" } : process.env,
31
33
  encoding: "utf8",
32
34
  stdio: ["ignore", "pipe", "ignore"],
33
35
  timeout: 2_000,
@@ -38,6 +40,22 @@ function readTokenUncached(pid) {
38
40
  return undefined;
39
41
  }
40
42
  }
43
+ // Admission crosses process environments; stored task tokens retain their original format.
44
+ export function readAdmissionStartToken(pid) {
45
+ if (process.platform !== "linux")
46
+ return readTokenUncached(pid, true);
47
+ if (!Number.isInteger(pid) || pid <= 0)
48
+ return undefined;
49
+ try {
50
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
51
+ // Fields after the parenthesized command start at field 3. Start time is field 22.
52
+ const start = stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
53
+ return start && /^\d+$/.test(start) ? start : undefined;
54
+ }
55
+ catch {
56
+ return undefined;
57
+ }
58
+ }
41
59
  function remember(pid, token, now) {
42
60
  if (tokenMemo.size >= TOKEN_MEMO_MAX_ENTRIES) {
43
61
  // Drop expired entries first; only evict live ones if that was not enough.