pi-better-background-tasks 0.17.0 → 0.19.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 (55) hide show
  1. package/README.md +4 -3
  2. package/package.json +4 -2
  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/work-client.mjs +150 -7
  13. package/src/adapter-contract.ts +1 -1
  14. package/src/failures.ts +4 -2
  15. package/src/goal-provider.ts +31 -16
  16. package/src/index.ts +9 -37
  17. package/src/managed-authority.ts +30 -0
  18. package/src/managed-client.ts +73 -0
  19. package/src/managed-frontend.ts +176 -0
  20. package/src/navigator-provider.ts +28 -10
  21. package/src/observed-wait-client.ts +10 -0
  22. package/src/observed-waits.ts +268 -62
  23. package/src/output.ts +12 -0
  24. package/src/process-identity.ts +18 -2
  25. package/src/process.ts +3 -3
  26. package/src/registry.ts +71 -6
  27. package/src/runtime.ts +26 -10
  28. package/src/sandbox.ts +21 -11
  29. package/src/shared-callback-batcher.ts +15 -3
  30. package/src/shared-failure-observations.ts +3 -0
  31. package/src/shared-navigator-panels.ts +26 -4
  32. package/src/shared-navigator.ts +220 -19
  33. package/src/shared-operation-coordinator/assignment-observation.mjs +71 -33
  34. package/src/shared-operation-coordinator/index.ts +2 -0
  35. package/src/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  36. package/src/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  37. package/src/shared-operation-coordinator/src/background-parent-callbacks.ts +68 -0
  38. package/src/shared-operation-coordinator/src/background-requests.ts +90 -0
  39. package/src/shared-operation-coordinator/src/discovery.ts +5 -3
  40. package/src/shared-operation-coordinator/src/operations.ts +50 -2
  41. package/src/shared-operation-coordinator/src/result-supervision.ts +12 -0
  42. package/src/shared-operation-coordinator/src/rows.ts +2 -0
  43. package/src/shared-operation-coordinator/src/schema.ts +71 -24
  44. package/src/shared-operation-coordinator/src/store.ts +50 -6
  45. package/src/shared-operation-coordinator/src/subagent-launch.ts +142 -0
  46. package/src/shared-operation-coordinator/src/types.ts +5 -1
  47. package/src/shared-operation-coordinator/src/upgrade.ts +22 -0
  48. package/src/shared-sandbox-core.ts +1 -1
  49. package/src/shared-work-client.mjs +150 -7
  50. package/src/supervisor/generated/process-identity.mjs +20 -2
  51. package/src/supervisor/generated/process.mjs +3 -3
  52. package/src/task-diagnostics.ts +1 -1
  53. package/src/tools.ts +60 -41
  54. package/src/types.ts +3 -1
  55. package/src/work-observation.ts +46 -19
@@ -7,8 +7,12 @@
7
7
  * synchronous and transactional; a refusal throws `StoreError` with a typed code
8
8
  * and leaves no partial record.
9
9
  */
10
+ import { setUpgradeFence } from "./upgrade.ts";
11
+ import { setParentCallbackPending, listPendingParentCallbacks, listRecentBackgroundTerminals, seedPendingParentCallbacks, type ParentCallbackScope, type ParentCallbackPage, type RecentBackgroundTerminalPage } from './background-parent-callbacks.ts';
12
+ import { BackgroundRequests } from "./background-requests.ts";
10
13
  import { StoreError } from "./errors.ts";
11
- import { resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.ts";
14
+ import { SubagentLaunchJournal } from "./subagent-launch.ts";
15
+ import { resultSupervisionChanges, resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.ts";
12
16
  import { acceptTaskCancellation, getTaskCancellation, recordTaskStopRequested, admitTaskCancellation, authorizedTaskCancellation, finishTaskCancellation, cancellationRuntimeEpoch, acceptAuthorizedTaskCancellation, taskCancellationManaged, pendingTaskCancellations, finishTaskCancellationIntent, unknownTaskCancellation } from "./task-cancellation.ts";
13
17
  import type { TaskCancellationIntent, TaskCancellationRequest } from "./task-cancellation.ts";
14
18
  import { repairFailedResume, type RepairResumeInput } from "./recovery.ts";
@@ -22,9 +26,11 @@ import {
22
26
  requirePath,
23
27
  } from "./validate.ts";
24
28
  import { ensureSchema } from "./schema.ts";
25
- 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";
26
31
  import {
27
32
  getOperation as readOperationRecord,
33
+ listAssignmentCleanupOperations as readAssignmentCleanupOperations,
28
34
  listOperations as readOperationRecords,
29
35
  listRunningSupervisedBy as readRunningSupervisedBy,
30
36
  releaseSupervision as writeSupervisionRelease,
@@ -120,6 +126,9 @@ import {
120
126
  } from "./types.ts";
121
127
 
122
128
  export interface Store {
129
+ hasSubagentManagement(): boolean;
130
+ resultSupervisionChanges(after?: Parameters<typeof resultSupervisionChanges>[1]): ReturnType<typeof resultSupervisionChanges>;
131
+ subagentLaunchJournal(): SubagentLaunchJournal;
123
132
  resultScopeManaged(scope: string): boolean;
124
133
  handoffResultScope(input: Parameters<typeof handoffResultScope>[1]): ReturnType<typeof handoffResultScope>;
125
134
  resultSupervision(operationId: string): ReturnType<typeof resultSupervision>;
@@ -155,11 +164,16 @@ export interface Store {
155
164
 
156
165
  // ---- operations ----
157
166
 
167
+ backgroundRequests(): BackgroundRequests;
168
+ setParentCallbackPending(taskId: string, pending: boolean): boolean;
169
+ listPendingParentCallbacks(scope: ParentCallbackScope, options?: ParentCallbackPage): OperationRecord[];
170
+ listRecentBackgroundTerminals(options: RecentBackgroundTerminalPage): OperationRecord[];
171
+ seedPendingParentCallbacks(options?: { limit?: number }): { done: boolean; seeded: number };
172
+ setUpgradeFence(epoch: string | null): void;
158
173
  /**
159
- * Register a durable operation for one task launch. The owner, task id,
160
- * launch token and observer are immutable: a replay of the same launch
161
- * returns `created: false`, and any difference is refused with
162
- * `operation-conflict` or `task-ownership`.
174
+ * Register a durable launch. Owner, task id, launch token, observer, and
175
+ * assignment attempt provenance are immutable. An exact replay returns
176
+ * `created: false`, even after assignment end, and admits no new work.
163
177
  */
164
178
  registerOperation(input: RegisterOperationInput): RegisterOperationResult;
165
179
  /**
@@ -185,6 +199,12 @@ export interface Store {
185
199
  recordTerminalOutcome(input: RecordTerminalOutcomeInput): RecordTerminalOutcomeResult;
186
200
  getOperation(operationId: string): OperationRecord | null;
187
201
  listOperations(filter?: OperationFilter): OperationRecord[];
202
+ /**
203
+ * Read up to 256 unfinished cleanup obligations in operation id order.
204
+ * The cursor is exclusive. Start each new sweep without a cursor.
205
+ */
206
+ listAssignmentCleanupOperations(limit: number, afterOperationId?: string): OperationRecord[];
207
+ verifyAssignmentCleanup(operationId: string, launchToken: string, terminalRevision: number): boolean;
188
208
  /** Running operations currently assigned to this supervising host. */
189
209
  listRunningSupervisedBy(hostId: string): OperationRecord[];
190
210
  listOperationEvidence(operationId: string, terminalRevision?: number): OperationEvidenceRecord[];
@@ -316,6 +336,7 @@ export function openStore(options: StoreOptions): Store {
316
336
  const ctx: StoreContext = createContext(db, options.now ? { now: options.now } : {});
317
337
  try {
318
338
  ensureSchema(ctx);
339
+ ensureAssignmentChanges(ctx);
319
340
  } catch (error) {
320
341
  try {
321
342
  db.close();
@@ -336,9 +357,12 @@ export function openStore(options: StoreOptions): Store {
336
357
  };
337
358
 
338
359
  const store: Store = {
360
+ subagentLaunchJournal() { alive(); return new SubagentLaunchJournal(ctx, alive); },
339
361
  resultScopeManaged(scope) { alive(); return resultScopeManaged(ctx, scope); },
340
362
  handoffResultScope(input) { alive(); return handoffResultScope(ctx, input); },
341
363
  resultSupervision(id) { alive(); return resultSupervision(ctx, id); },
364
+ hasSubagentManagement() { alive(); return Boolean(ctx.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='subagent_management'").get()); },
365
+ resultSupervisionChanges(after) { alive(); return resultSupervisionChanges(ctx, after); },
342
366
  resultSupervisions(activeOnly) { alive(); return resultSupervisions(ctx, activeOnly); },
343
367
  handoffResultSupervision(input) { alive(); return handoffResultSupervision(ctx, input); },
344
368
  handoffResultSupervisions(input) { alive(); return handoffResultSupervisions(ctx, input); },
@@ -366,6 +390,12 @@ export function openStore(options: StoreOptions): Store {
366
390
  closed = true;
367
391
  db.close();
368
392
  },
393
+ setParentCallbackPending(taskId, pending) { alive(); return setParentCallbackPending(ctx, taskId, pending); },
394
+ listPendingParentCallbacks(scope, options) { alive(); return listPendingParentCallbacks(ctx, scope, options); },
395
+ listRecentBackgroundTerminals(options) { alive(); return listRecentBackgroundTerminals(ctx, options); },
396
+ seedPendingParentCallbacks(options) { alive(); return seedPendingParentCallbacks(ctx, options); },
397
+ backgroundRequests() { alive(); return new BackgroundRequests(ctx, alive); },
398
+ setUpgradeFence(epoch) { alive(); setUpgradeFence(ctx, epoch); },
369
399
  registerOperation(input) {
370
400
  alive();
371
401
  return writeOperation(ctx, input);
@@ -390,6 +420,20 @@ export function openStore(options: StoreOptions): Store {
390
420
  alive();
391
421
  return readOperationRecords(ctx, filter);
392
422
  },
423
+ listAssignmentCleanupOperations(limit, afterOperationId) {
424
+ alive();
425
+ return readAssignmentCleanupOperations(ctx, limit, afterOperationId);
426
+ },
427
+ verifyAssignmentCleanup(operationId, launchToken, terminalRevision) {
428
+ alive();
429
+ if (!Number.isSafeInteger(terminalRevision) || terminalRevision < 1) return false;
430
+ return run(ctx, `INSERT OR IGNORE INTO coordinator_state (key, value)
431
+ SELECT 'assignment-cleanup-verified:' || op.operation_id, op.launch_token
432
+ FROM operations op JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
433
+ JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
434
+ WHERE op.operation_id = ? AND op.launch_token = ? AND op.terminal_revision = ?`,
435
+ operationId, launchToken, terminalRevision) > 0;
436
+ },
393
437
  listRunningSupervisedBy(hostId) {
394
438
  alive();
395
439
  return readRunningSupervisedBy(ctx, hostId);
@@ -0,0 +1,142 @@
1
+ // Generated from packages/operation-coordinator/src/subagent-launch.ts. Do not edit directly.
2
+ import { createHash, randomBytes } from "node:crypto";
3
+ import type { StoreContext } from "./sqlite.ts";
4
+
5
+ export interface LaunchAttempt {
6
+ id: string;
7
+ sessionId: string;
8
+ lease: string;
9
+ leasePath: string;
10
+ preflightPath: string;
11
+ preflightDigest: string;
12
+ policyPath?: string;
13
+ policyDigest?: string;
14
+ capacityOwner: { pid: number; start: string };
15
+ launchAuthority?: unknown;
16
+ recipe: unknown;
17
+ permissions: unknown;
18
+ token: string;
19
+ state: "prepared" | "spawned";
20
+ pid?: number;
21
+ writerPid?: number;
22
+ writerStartTime?: string;
23
+ pidStartTime?: string;
24
+ recoveryMeta?: unknown;
25
+ bootstrapped?: boolean;
26
+ }
27
+ export interface LaunchIntent {
28
+ owner: string; request_key: string; digest: string; epoch: number;
29
+ state: "accepted" | "returned"; attempts: string; result: string | null;
30
+ }
31
+
32
+ /** Fixed launch journal on the coordinator's existing connection and transaction. */
33
+ export class SubagentLaunchJournal {
34
+ private context: StoreContext;
35
+ private alive: () => void;
36
+ constructor(context: StoreContext, alive: () => void) {
37
+ this.context = context;
38
+ this.alive = alive;
39
+ this.transaction(() => this.db.exec(`CREATE TABLE IF NOT EXISTS subagent_launch_intents (
40
+ owner TEXT NOT NULL, request_key TEXT NOT NULL, digest TEXT NOT NULL,
41
+ epoch INTEGER NOT NULL, state TEXT NOT NULL, attempts TEXT NOT NULL, result TEXT,
42
+ PRIMARY KEY(owner, request_key));
43
+ CREATE TABLE IF NOT EXISTS subagent_management (singleton INTEGER PRIMARY KEY CHECK(singleton=1), instance TEXT NOT NULL, epoch INTEGER NOT NULL);`));
44
+ }
45
+ private get db() { this.alive(); return this.context.db; }
46
+ private transaction<T>(run: () => T): T { this.alive(); return this.context.transaction(run); }
47
+ epoch(instance: string) {
48
+ return this.transaction(() => {
49
+ const previous = this.db.prepare("SELECT * FROM subagent_management WHERE singleton=1").get();
50
+ if (previous?.instance === instance) return Number(previous.epoch);
51
+ const epoch = (Number(previous?.epoch ?? 0)) + 1;
52
+ this.db.prepare("INSERT OR REPLACE INTO subagent_management VALUES (1, ?, ?)").run(instance, epoch);
53
+ return epoch;
54
+ });
55
+ }
56
+ current(epoch: number) {
57
+ if (this.db.prepare("SELECT epoch FROM subagent_management WHERE singleton=1").get()?.epoch !== epoch) throw new Error("stale-runtime-epoch");
58
+ }
59
+ read(owner: string, key: string): LaunchIntent | undefined { return this.db.prepare("SELECT * FROM subagent_launch_intents WHERE owner=? AND request_key=?").get(owner, key) as unknown as LaunchIntent | undefined; }
60
+ attempt(id: string): LaunchAttempt | undefined {
61
+ const row = this.db.prepare("SELECT j.value AS attempt FROM subagent_launch_intents, json_each(subagent_launch_intents.attempts) j WHERE json_extract(j.value, '$.id')=? LIMIT 1").get(id);
62
+ return row ? JSON.parse(String(row.attempt)) : undefined;
63
+ }
64
+ unresolvedAttempts() {
65
+ return this.db.prepare("SELECT j.value AS attempt FROM subagent_launch_intents, json_each(subagent_launch_intents.attempts) j WHERE subagent_launch_intents.state='accepted'").all().map(row => JSON.parse(String(row.attempt)));
66
+ }
67
+ pendingIntents(): LaunchIntent[] {
68
+ return this.db.prepare("SELECT * FROM subagent_launch_intents WHERE state='accepted'").all() as unknown as LaunchIntent[];
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
+ }
90
+ finishRecovery(owner: string, key: string, epoch: number, result: unknown) {
91
+ this.transaction(() => {
92
+ this.current(epoch);
93
+ this.db.prepare("UPDATE subagent_launch_intents SET state='returned', result=? WHERE owner=? AND request_key=? AND state='accepted' AND epoch<?")
94
+ .run(JSON.stringify(result), owner, key, epoch);
95
+ });
96
+ }
97
+ accept(owner: string, key: string, digest: string, epoch: number) {
98
+ return this.transaction(() => {
99
+ this.current(epoch);
100
+ const prior = this.read(owner, key);
101
+ if (prior) {
102
+ if (prior.digest !== digest) throw new Error("request-conflict: launch key has different content");
103
+ return { prior: true, ...prior };
104
+ }
105
+ this.db.prepare("INSERT INTO subagent_launch_intents VALUES (?, ?, ?, ?, 'accepted', '[]', NULL)").run(owner, key, digest, epoch);
106
+ this.noteProgress(owner, key);
107
+ return this.read(owner, key);
108
+ });
109
+ }
110
+ prepare(owner: string, key: string, epoch: number, input: Omit<LaunchAttempt, "token" | "state">) {
111
+ return this.transaction(() => {
112
+ this.current(epoch);
113
+ const row = this.read(owner, key);
114
+ if (!row || row.epoch !== epoch || row.state !== "accepted") throw new Error("Launch intent is not admitted");
115
+ const attempts: LaunchAttempt[] = JSON.parse(row.attempts);
116
+ if (attempts.some(attempt => attempt.id === input.id)) throw new Error("Attempt already dispatched; reconcile exact identity");
117
+ const attempt: LaunchAttempt = { ...input, token: randomBytes(32).toString("hex"), state: "prepared" };
118
+ attempts.push(attempt);
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);
121
+ return attempt;
122
+ });
123
+ }
124
+ spawned(owner: string, key: string, epoch: number, id: string, pid: number, pidStartTime?: string) {
125
+ this.transaction(() => {
126
+ this.current(epoch);
127
+ const attempts = JSON.parse(this.read(owner, key)!.attempts) as LaunchAttempt[];
128
+ const attempt = attempts.find(value => value.id === id);
129
+ if (!attempt || attempt.state !== "prepared") throw new Error("Launch publication is ambiguous");
130
+ if (attempt.writerPid && attempt.writerPid !== pid) throw new Error("Launch writer does not match spawned process");
131
+ Object.assign(attempt, { state: "spawned", pid, pidStartTime });
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);
134
+ });
135
+ }
136
+ finish(owner: string, key: string, epoch: number, result: unknown) {
137
+ this.transaction(() => {
138
+ this.current(epoch);
139
+ this.db.prepare("UPDATE subagent_launch_intents SET state='returned', result=? WHERE owner=? AND request_key=? AND epoch=?").run(JSON.stringify(result), owner, key, epoch);
140
+ });
141
+ }
142
+ }
@@ -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;
@@ -0,0 +1,22 @@
1
+ // Generated from packages/operation-coordinator/src/upgrade.ts. Do not edit directly.
2
+ import type { StoreContext } from "./sqlite.ts";
3
+
4
+ /** Persistent admission fence also enforced against older bundled writers. */
5
+ export function setUpgradeFence(ctx: StoreContext, epoch: string | null) {
6
+ ctx.transaction(() => {
7
+ ctx.db.exec(`CREATE TRIGGER IF NOT EXISTS runtime_upgrade_admission_v1 BEFORE INSERT ON operations
8
+ WHEN EXISTS (SELECT 1 FROM coordinator_state WHERE key='runtime-upgrade-fence-v1')
9
+ AND NOT EXISTS (SELECT 1 FROM operations WHERE operation_id=NEW.operation_id)
10
+ AND NOT (NEW.owner_kind='worker-conversation' AND EXISTS (
11
+ SELECT 1 FROM assignment_bindings b JOIN assignment_attempts a USING(assignment_id)
12
+ WHERE json_extract(b.owner_json, '$.kind')=NEW.owner_kind
13
+ AND json_extract(b.owner_json, '$.sessionId')=NEW.owner_session_id
14
+ AND json_extract(b.owner_json, '$.workspace')=NEW.owner_workspace
15
+ AND json_extract(b.owner_json, '$.branchId') IS NEW.owner_branch_id
16
+ AND json_extract(b.owner_json, '$.goalId') IS NEW.owner_goal_id
17
+ AND NOT EXISTS (SELECT 1 FROM assignment_outcomes o WHERE o.assignment_id=b.assignment_id)))
18
+ BEGIN SELECT RAISE(ABORT, 'runtime-draining: new execution deferred for upgrade'); END`);
19
+ if (epoch === null) ctx.db.prepare("DELETE FROM coordinator_state WHERE key='runtime-upgrade-fence-v1'").run();
20
+ else ctx.db.prepare("INSERT OR REPLACE INTO coordinator_state VALUES ('runtime-upgrade-fence-v1', ?)").run(epoch);
21
+ });
22
+ }
@@ -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
+ }
@@ -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.
@@ -62,8 +62,8 @@ export function validateCommandSpec(spec) {
62
62
  /** Convert a Windows path to the `/c/...` form MSYS bash resolves in redirections. Exposed for tests and reuse. */
63
63
  export function toMsysPath(path) {
64
64
  const forward = path.replace(/\\/g, "/");
65
- const drive = /^([A-Za-z]):(\/.+)$/.exec(forward);
66
- return drive ? `/${drive[1].toLowerCase()}${drive[2]}` : forward;
65
+ const [, drive, rest] = /^([A-Za-z]):(\/.+)$/.exec(forward) ?? [];
66
+ return drive && rest ? `/${drive.toLowerCase()}${rest}` : forward;
67
67
  }
68
68
  /** Single-quote a value for safe literal use in a bash script line. Exposed for tests and reuse. */
69
69
  export function bashSingleQuote(value) {
@@ -147,7 +147,7 @@ export function parseStepGateFailure(logText, id) {
147
147
  if (!line.startsWith(marker) || !line.endsWith(" ---"))
148
148
  continue;
149
149
  const match = /^--- step gate \[[^\]]+\]: first failing step exit=(-?\d+); shell exit=(-?\d+): (.*) ---$/.exec(line);
150
- if (!match)
150
+ if (!match || match[3] === undefined)
151
151
  continue;
152
152
  const stepExitCode = Number(match[1]);
153
153
  const shellExitCode = Number(match[2]);
@@ -52,7 +52,7 @@ export function inspectTaskProcess(
52
52
  ({ availability: "unavailable", reason, ...(identity ? { identity } : {}), limit: LIMIT });
53
53
  if (access === "confined") return unavailable("Process activity adapter is unavailable under Main confinement; no unconfined process probe was run. Process access Read does not bypass kernel rules.");
54
54
  if (access !== "read") return { availability: "blocked", reason: access === "off"
55
- ? "Process access is Off in Main or Background tasks. Enable Read in /sandbox; this does not describe task confinement."
55
+ ? "An active Main or Background tasks profile denies process reads. Check Process access in /sandbox; this does not describe task confinement."
56
56
  : "Current process-access policy is unavailable; no process probe was run.", limit: LIMIT };
57
57
  if (meta.ssh) return unavailable("Remote activity is unavailable; no remote diagnostic command was run.");
58
58
  if (meta.kind !== "process") return unavailable("Watch poll PID is not retained; last completed check is progress evidence only.");