pi-better-background-tasks 0.16.0 → 0.18.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 (40) hide show
  1. package/README.md +9 -0
  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/daemon-owner.mjs +2 -1
  12. package/runtime-client/src/runtime/work-client.mjs +16 -2
  13. package/src/failures.ts +4 -2
  14. package/src/index.ts +6 -30
  15. package/src/managed-authority.ts +28 -0
  16. package/src/managed-client.ts +60 -0
  17. package/src/managed-frontend.ts +131 -0
  18. package/src/navigator-provider.ts +14 -6
  19. package/src/observed-waits.ts +286 -48
  20. package/src/output.ts +12 -0
  21. package/src/registry.ts +18 -1
  22. package/src/runtime.ts +8 -2
  23. package/src/sandbox.ts +7 -0
  24. package/src/shared-callback-batcher.ts +4 -1
  25. package/src/shared-failure-observations.ts +3 -0
  26. package/src/shared-navigator.ts +23 -5
  27. package/src/shared-operation-coordinator/assignment-observation.mjs +48 -1
  28. package/src/shared-operation-coordinator/index.ts +2 -0
  29. package/src/shared-operation-coordinator/src/background-parent-callbacks.ts +68 -0
  30. package/src/shared-operation-coordinator/src/background-requests.ts +79 -0
  31. package/src/shared-operation-coordinator/src/discovery.ts +9 -0
  32. package/src/shared-operation-coordinator/src/operations.ts +6 -4
  33. package/src/shared-operation-coordinator/src/result-supervision.ts +128 -0
  34. package/src/shared-operation-coordinator/src/schema.ts +50 -1
  35. package/src/shared-operation-coordinator/src/store.ts +38 -0
  36. package/src/shared-operation-coordinator/src/subagent-launch.ts +119 -0
  37. package/src/shared-operation-coordinator/src/types.ts +6 -0
  38. package/src/shared-operation-coordinator/src/upgrade.ts +22 -0
  39. package/src/shared-work-client.mjs +16 -2
  40. package/src/tools.ts +76 -37
@@ -0,0 +1,128 @@
1
+ // Generated from packages/operation-coordinator/src/result-supervision.ts. Do not edit directly.
2
+ import { isDeepStrictEqual } from "node:util";
3
+ import { getRow, run, type StoreContext } from "./sqlite.ts";
4
+ import { getOperation, recordSupervision, recordTerminalOutcome } from "./operations.ts";
5
+ import { requireId, requirePath } from "./validate.ts";
6
+ import type { RecordTerminalOutcomeInput } from "./types.ts";
7
+ import type { OwnerIdentity } from "./types.ts";
8
+
9
+ const PREFIX = "result-supervision-v1:";
10
+ export interface ResultSupervision {
11
+ operationId: string;
12
+ directory: string;
13
+ launchToken: string;
14
+ authorityRef: string | null;
15
+ hostId: string;
16
+ epoch: string;
17
+ owner: OwnerIdentity;
18
+ capability?: { adapter: string; captured: unknown; current: unknown };
19
+ }
20
+
21
+ export function resultSupervisions(ctx: StoreContext, activeOnly = false): ResultSupervision[] {
22
+ const rows = activeOnly
23
+ ? ctx.db.prepare("SELECT s.value FROM operations o JOIN coordinator_state s ON s.key = ? || o.operation_id WHERE o.phase = 'running'").all(PREFIX)
24
+ : ctx.db.prepare("SELECT value FROM coordinator_state WHERE key LIKE ?").all(`${PREFIX}%`);
25
+ return rows
26
+ .map(row => JSON.parse(String(row.value)));
27
+ }
28
+
29
+ export function resultSupervision(ctx: StoreContext, operationId: string): ResultSupervision | null {
30
+ const row = getRow(ctx, "SELECT value FROM coordinator_state WHERE key = ?", PREFIX + requireId("operationId", operationId));
31
+ return row ? JSON.parse(String(row.value)) : null;
32
+ }
33
+
34
+ /** The admitting host has stopped its local route before this exact-owner CAS. */
35
+ export function handoffResultSupervision(ctx: StoreContext, input: {
36
+ operationId: string; expectedHostId: string; directory: string; hostId: string; epoch: string;
37
+ capability?: ResultSupervision["capability"];
38
+ }): ResultSupervision {
39
+ const operationId = requireId("operationId", input.operationId);
40
+ const hostId = requireId("hostId", input.hostId);
41
+ const epoch = requireId("epoch", input.epoch);
42
+ const directory = requirePath("directory", input.directory);
43
+ return ctx.transaction(() => {
44
+ const previous = resultSupervision(ctx, operationId);
45
+ if (previous) {
46
+ if (previous.directory !== directory || previous.hostId !== hostId || previous.epoch !== epoch
47
+ || !isDeepStrictEqual(previous.capability, input.capability)) {
48
+ throw new Error("supervision-conflict: repeated handoff changed destination or captured authority");
49
+ }
50
+ return previous;
51
+ }
52
+ const operation = getOperation(ctx, operationId);
53
+ if (!operation || operation.supervision?.hostId !== input.expectedHostId) throw new Error("permission-unavailable: exact supervision owner changed");
54
+ const grant = { operationId, directory, hostId, epoch, launchToken: operation.launchToken,
55
+ authorityRef: operation.authorityRef, owner: operation.owner, ...(input.capability ? { capability: input.capability } : {}) };
56
+ recordSupervision(ctx, { operationId, owner: operation.owner, expectedHostId: input.expectedHostId,
57
+ supervision: { hostId }, health: "active" });
58
+ run(ctx, "INSERT INTO coordinator_state (key, value) VALUES (?, ?)", PREFIX + operationId, JSON.stringify(grant));
59
+ return grant;
60
+ });
61
+ }
62
+
63
+ /** A wait's dependency set transfers together, or none of it does. */
64
+ export function handoffResultSupervisions(ctx: StoreContext, inputs: Parameters<typeof handoffResultSupervision>[1][]): ResultSupervision[] {
65
+ return ctx.transaction(() => inputs.map(input => handoffResultSupervision(ctx, input)));
66
+ }
67
+
68
+ export function resultScopeManaged(ctx: StoreContext, scope: string): boolean {
69
+ return !!getRow(ctx, "SELECT value FROM coordinator_state WHERE key = ?", "result-scope-v1:" + requireId("scope", scope));
70
+ }
71
+
72
+ export function handoffResultScope(ctx: StoreContext, input: {
73
+ scope: string;
74
+ expectedDiscovery: { hostId: string; token: string } | null;
75
+ grants: Parameters<typeof handoffResultSupervision>[1][];
76
+ }): ResultSupervision[] {
77
+ return ctx.transaction(() => {
78
+ const claim = getRow(ctx, "SELECT host_id, token FROM discovery_claims WHERE scope = ?", requireId("scope", input.scope));
79
+ if (claim ? !input.expectedDiscovery || claim.host_id !== input.expectedDiscovery.hostId || claim.token !== input.expectedDiscovery.token : input.expectedDiscovery !== null) {
80
+ throw new Error("supervision-conflict: discovery owner changed during handoff");
81
+ }
82
+ const grants = handoffResultSupervisions(ctx, input.grants);
83
+ // Registration precedes sidecar creation. Check durable records inside
84
+ // this transaction, including old records whose scope is unknown.
85
+ const stranded = getRow(ctx, `SELECT operation_id FROM operations o
86
+ WHERE phase = 'running' AND observer_kind = 'local-supervisor'
87
+ AND COALESCE(json_extract(supervision_json, '$.resultAdapter'), 0) != 1
88
+ AND (json_extract(supervision_json, '$.resultScope') IS NULL
89
+ OR json_extract(supervision_json, '$.resultScope') = ?)
90
+ AND NOT EXISTS (SELECT 1 FROM coordinator_state s WHERE s.key = ? || o.operation_id)
91
+ LIMIT 1`, input.scope, PREFIX);
92
+ if (stranded) throw new Error("permission-unavailable: untransferred legacy operation prevents scope handoff");
93
+ run(ctx, "DELETE FROM discovery_claims WHERE scope = ?", input.scope);
94
+ run(ctx, "INSERT OR IGNORE INTO coordinator_state (key, value) VALUES (?, 'managed')", "result-scope-v1:" + input.scope);
95
+ return grants;
96
+ });
97
+ }
98
+
99
+ /** Called by the singleton server after proving the preceding server has exited. */
100
+ export function recoverResultSupervision(ctx: StoreContext, input: ResultSupervision): void {
101
+ ctx.transaction(() => {
102
+ const previous = resultSupervision(ctx, input.operationId);
103
+ if (!previous || previous.launchToken !== input.launchToken || previous.directory !== input.directory
104
+ || previous.authorityRef !== input.authorityRef || JSON.stringify(previous.owner) !== JSON.stringify(input.owner)
105
+ || JSON.stringify(previous.capability) !== JSON.stringify(input.capability)) {
106
+ throw new Error("supervision-conflict: execution or captured authority changed");
107
+ }
108
+ const operation = getOperation(ctx, input.operationId)!;
109
+ if (operation.terminalRevision > 0) return;
110
+ recordSupervision(ctx, { operationId: input.operationId, owner: operation.owner,
111
+ expectedHostId: previous.hostId, supervision: { hostId: input.hostId }, health: "active" });
112
+ run(ctx, "UPDATE coordinator_state SET value = ? WHERE key = ?", JSON.stringify(input), PREFIX + input.operationId);
113
+ });
114
+ }
115
+
116
+ export function publishSupervisedResult(ctx: StoreContext, input: {
117
+ operationId: string; epoch: string; publication: RecordTerminalOutcomeInput;
118
+ }) {
119
+ return ctx.transaction(() => {
120
+ const grant = resultSupervision(ctx, input.operationId);
121
+ const operation = getOperation(ctx, input.operationId);
122
+ if (!grant || grant.epoch !== input.epoch || operation?.supervision?.hostId !== grant.hostId
123
+ || operation.launchToken !== grant.launchToken || input.publication.operationId !== input.operationId) {
124
+ throw new Error("stale-runtime-epoch: result supervision changed");
125
+ }
126
+ return recordTerminalOutcome(ctx, input.publication);
127
+ });
128
+ }
@@ -18,6 +18,45 @@ import { SCHEMA_VERSION } from "./types.ts";
18
18
  import { StoreError } from "./errors.ts";
19
19
  import { columnText, getRow, getRows, run, type StoreContext } from "./sqlite.ts";
20
20
 
21
+ // Enforce the handoff even for an older process still using its bundled store.
22
+ // Unknown legacy scopes conservatively conflict with any managed root scope.
23
+ const RESULT_ADMISSION_FENCE = `CREATE TRIGGER IF NOT EXISTS result_scope_admission_v1
24
+ BEFORE INSERT ON operations
25
+ WHEN NEW.observer_kind = 'local-supervisor'
26
+ AND COALESCE(json_extract(NEW.supervision_json, '$.resultAdapter'), 0) != 1
27
+ AND EXISTS (SELECT 1 FROM coordinator_state
28
+ WHERE key LIKE 'result-scope-v1:%'
29
+ AND (json_extract(NEW.supervision_json, '$.resultScope') IS NULL
30
+ OR key = 'result-scope-v1:' || json_extract(NEW.supervision_json, '$.resultScope')))
31
+ BEGIN SELECT RAISE(ABORT, 'permission-unavailable: legacy launch into managed result scope'); END`;
32
+
33
+ const BACKGROUND_CALLBACK_DDL = [
34
+ `CREATE TABLE IF NOT EXISTS background_parent_callbacks (
35
+ operation_id TEXT PRIMARY KEY REFERENCES operations(operation_id),
36
+ owner_kind TEXT NOT NULL CHECK(owner_kind='parent-session'),
37
+ owner_workspace TEXT NOT NULL,
38
+ owner_session_id TEXT NOT NULL
39
+ )`,
40
+ `CREATE TRIGGER IF NOT EXISTS background_parent_callback_registration
41
+ AFTER INSERT ON operations
42
+ WHEN NEW.owner_kind='parent-session' AND NEW.observer_kind='local-supervisor'
43
+ BEGIN INSERT OR IGNORE INTO background_parent_callbacks(operation_id,owner_kind,owner_workspace,owner_session_id)
44
+ VALUES(NEW.operation_id,NEW.owner_kind,NEW.owner_workspace,NEW.owner_session_id); END`,
45
+ `CREATE INDEX IF NOT EXISTS background_parent_callbacks_owner ON background_parent_callbacks(owner_kind,owner_workspace,owner_session_id,operation_id)`,
46
+ `CREATE INDEX IF NOT EXISTS operations_background_recent ON operations(terminal_at,operation_id) WHERE observer_kind='local-supervisor' AND terminal_revision>0`,
47
+ `CREATE INDEX IF NOT EXISTS operations_background_owner_recent ON operations(owner_kind,owner_workspace,owner_session_id,terminal_at,operation_id) WHERE observer_kind='local-supervisor' AND terminal_revision>0`,
48
+ `CREATE INDEX IF NOT EXISTS operations_background_parent_seed ON operations(operation_id) WHERE owner_kind='parent-session' AND observer_kind='local-supervisor'`,
49
+ `CREATE TABLE IF NOT EXISTS background_parent_callback_migration (
50
+ singleton INTEGER PRIMARY KEY CHECK(singleton=1),
51
+ after_operation_id TEXT NOT NULL,
52
+ through_operation_id TEXT NOT NULL,
53
+ done INTEGER NOT NULL CHECK(done IN (0,1))
54
+ )`,
55
+ `INSERT OR IGNORE INTO background_parent_callback_migration(singleton,after_operation_id,through_operation_id,done)
56
+ SELECT 1,'',COALESCE(MAX(operation_id),''),CASE WHEN MAX(operation_id) IS NULL THEN 1 ELSE 0 END
57
+ FROM operations WHERE owner_kind='parent-session' AND observer_kind='local-supervisor'`,
58
+ ];
59
+
21
60
  const DDL: readonly string[] = [
22
61
  `CREATE TABLE task_cancellation_authorities (
23
62
  credential_hash TEXT PRIMARY KEY,
@@ -72,6 +111,7 @@ const DDL: readonly string[] = [
72
111
  updated_at INTEGER NOT NULL,
73
112
  terminal_at INTEGER
74
113
  )`,
114
+ ...BACKGROUND_CALLBACK_DDL,
75
115
  `CREATE INDEX operations_owner ON operations (owner_kind, owner_session_id)`,
76
116
  `CREATE INDEX operations_phase ON operations (phase)`,
77
117
  `CREATE INDEX operations_running_supervisor ON operations (phase, supervision_host_id)`,
@@ -238,6 +278,7 @@ const DDL: readonly string[] = [
238
278
  generation INTEGER NOT NULL,
239
279
  PRIMARY KEY (wait_id, generation)
240
280
  )`,
281
+ RESULT_ADMISSION_FENCE,
241
282
  ];
242
283
 
243
284
  const SCHEMA_VERSION_KEY = "schema_version";
@@ -294,6 +335,7 @@ export function ensureSchema(ctx: StoreContext): void {
294
335
  if (recorded < SCHEMA_VERSION) {
295
336
  if (recorded === 3) {
296
337
  ctx.transaction(() => {
338
+ ensureAdditiveSchema(ctx);
297
339
  ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE TABLE assignment_repairs"))!);
298
340
  run(ctx, "UPDATE schema_meta SET value = ? WHERE key = ?", String(SCHEMA_VERSION), SCHEMA_VERSION_KEY);
299
341
  });
@@ -327,6 +369,9 @@ export function ensureSchema(ctx: StoreContext): void {
327
369
  * records during a rolling upgrade. Missing additions are created once on open.
328
370
  */
329
371
  function ensureAdditiveSchema(ctx: StoreContext): void {
372
+ // Schema/index creation is atomic; legacy obligation seeding is performed
373
+ // separately in bounded batches by the canonical manager.
374
+ ctx.transaction(() => { for (const statement of BACKGROUND_CALLBACK_DDL) ctx.db.exec(statement); });
330
375
  const hasColumn = (): boolean =>
331
376
  getRows(ctx, "PRAGMA table_info(operations)").some((row) => columnText(row, "name") === "supervision_host_id");
332
377
  const hasIndex = (): boolean =>
@@ -340,7 +385,10 @@ function ensureAdditiveSchema(ctx: StoreContext): void {
340
385
  && hasTable("task_cancellation_requests")
341
386
  && hasTable("task_cancellation_authorities")
342
387
  && getRows(ctx, "PRAGMA table_info(task_cancellation_requests)").some(row => row.name === "result_json")
343
- ) return;
388
+ ) {
389
+ ctx.db.exec(RESULT_ADMISSION_FENCE);
390
+ return;
391
+ }
344
392
 
345
393
  ctx.transaction(() => {
346
394
  ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE TABLE task_cancellation_requests"))!.replace("CREATE TABLE", "CREATE TABLE IF NOT EXISTS"));
@@ -366,6 +414,7 @@ function ensureAdditiveSchema(ctx: StoreContext): void {
366
414
  key TEXT PRIMARY KEY,
367
415
  value TEXT NOT NULL
368
416
  )`);
417
+ ctx.db.exec(RESULT_ADMISSION_FENCE);
369
418
  });
370
419
  }
371
420
 
@@ -7,7 +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";
14
+ import { SubagentLaunchJournal } from "./subagent-launch.ts";
15
+ import { resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.ts";
11
16
  import { acceptTaskCancellation, getTaskCancellation, recordTaskStopRequested, admitTaskCancellation, authorizedTaskCancellation, finishTaskCancellation, cancellationRuntimeEpoch, acceptAuthorizedTaskCancellation, taskCancellationManaged, pendingTaskCancellations, finishTaskCancellationIntent, unknownTaskCancellation } from "./task-cancellation.ts";
12
17
  import type { TaskCancellationIntent, TaskCancellationRequest } from "./task-cancellation.ts";
13
18
  import { repairFailedResume, type RepairResumeInput } from "./recovery.ts";
@@ -34,6 +39,7 @@ import {
34
39
  import {
35
40
  getChangeRevision as readChangeRevision,
36
41
  readDiscoveryClaim as readClaim,
42
+ readDiscoveryState,
37
43
  releaseDiscoveryClaim as deleteDiscoveryClaim,
38
44
  tryClaimDiscovery as writeDiscoveryClaim,
39
45
  } from "./discovery.ts";
@@ -118,6 +124,15 @@ import {
118
124
  } from "./types.ts";
119
125
 
120
126
  export interface Store {
127
+ subagentLaunchJournal(): SubagentLaunchJournal;
128
+ resultScopeManaged(scope: string): boolean;
129
+ handoffResultScope(input: Parameters<typeof handoffResultScope>[1]): ReturnType<typeof handoffResultScope>;
130
+ resultSupervision(operationId: string): ReturnType<typeof resultSupervision>;
131
+ resultSupervisions(activeOnly?: boolean): ReturnType<typeof resultSupervisions>;
132
+ handoffResultSupervision(input: Parameters<typeof handoffResultSupervision>[1]): ReturnType<typeof handoffResultSupervision>;
133
+ handoffResultSupervisions(input: Parameters<typeof handoffResultSupervisions>[1]): ReturnType<typeof handoffResultSupervisions>;
134
+ recoverResultSupervision(input: Parameters<typeof recoverResultSupervision>[1]): void;
135
+ publishSupervisedResult(input: Parameters<typeof publishSupervisedResult>[1]): ReturnType<typeof publishSupervisedResult>;
121
136
  unknownTaskCancellation(input: TaskCancellationRequest): TaskCancellationIntent;
122
137
  taskCancellationManaged(operationId: string): boolean;
123
138
  pendingTaskCancellations(): ReturnType<typeof pendingTaskCancellations>;
@@ -151,6 +166,12 @@ export interface Store {
151
166
  * returns `created: false`, and any difference is refused with
152
167
  * `operation-conflict` or `task-ownership`.
153
168
  */
169
+ backgroundRequests(): BackgroundRequests;
170
+ setParentCallbackPending(taskId: string, pending: boolean): boolean;
171
+ listPendingParentCallbacks(scope: ParentCallbackScope, options?: ParentCallbackPage): OperationRecord[];
172
+ listRecentBackgroundTerminals(options: RecentBackgroundTerminalPage): OperationRecord[];
173
+ seedPendingParentCallbacks(options?: { limit?: number }): { done: boolean; seeded: number };
174
+ setUpgradeFence(epoch: string | null): void;
154
175
  registerOperation(input: RegisterOperationInput): RegisterOperationResult;
155
176
  /**
156
177
  * Replace supervision identity and/or report observer health
@@ -183,6 +204,7 @@ export interface Store {
183
204
 
184
205
  /** The shared discovery leader for this store/supervisor scope, if recorded. */
185
206
  readDiscoveryClaim(scope: string): DiscoveryClaimRecord | null;
207
+ readDiscoveryState(scope: string): ReturnType<typeof readDiscoveryState>;
186
208
  /**
187
209
  * Compare-and-swap a discovery claim. The caller must name the exact claim it
188
210
  * observed, or null for none; a stale contender receives null and must not
@@ -325,6 +347,15 @@ export function openStore(options: StoreOptions): Store {
325
347
  };
326
348
 
327
349
  const store: Store = {
350
+ subagentLaunchJournal() { alive(); return new SubagentLaunchJournal(ctx, alive); },
351
+ resultScopeManaged(scope) { alive(); return resultScopeManaged(ctx, scope); },
352
+ handoffResultScope(input) { alive(); return handoffResultScope(ctx, input); },
353
+ resultSupervision(id) { alive(); return resultSupervision(ctx, id); },
354
+ resultSupervisions(activeOnly) { alive(); return resultSupervisions(ctx, activeOnly); },
355
+ handoffResultSupervision(input) { alive(); return handoffResultSupervision(ctx, input); },
356
+ handoffResultSupervisions(input) { alive(); return handoffResultSupervisions(ctx, input); },
357
+ recoverResultSupervision(input) { alive(); recoverResultSupervision(ctx, input); },
358
+ publishSupervisedResult(input) { alive(); return publishSupervisedResult(ctx, input); },
328
359
  unknownTaskCancellation(input) { alive(); return unknownTaskCancellation(ctx, input); },
329
360
  taskCancellationManaged(operationId) { alive(); return taskCancellationManaged(ctx, operationId); },
330
361
  pendingTaskCancellations() { alive(); return pendingTaskCancellations(ctx); },
@@ -347,6 +378,12 @@ export function openStore(options: StoreOptions): Store {
347
378
  closed = true;
348
379
  db.close();
349
380
  },
381
+ setParentCallbackPending(taskId, pending) { alive(); return setParentCallbackPending(ctx, taskId, pending); },
382
+ listPendingParentCallbacks(scope, options) { alive(); return listPendingParentCallbacks(ctx, scope, options); },
383
+ listRecentBackgroundTerminals(options) { alive(); return listRecentBackgroundTerminals(ctx, options); },
384
+ seedPendingParentCallbacks(options) { alive(); return seedPendingParentCallbacks(ctx, options); },
385
+ backgroundRequests() { alive(); return new BackgroundRequests(ctx, alive); },
386
+ setUpgradeFence(epoch) { alive(); setUpgradeFence(ctx, epoch); },
350
387
  registerOperation(input) {
351
388
  alive();
352
389
  return writeOperation(ctx, input);
@@ -383,6 +420,7 @@ export function openStore(options: StoreOptions): Store {
383
420
  terminalRevision === undefined ? undefined : requireCounter("terminalRevision", terminalRevision),
384
421
  );
385
422
  },
423
+ readDiscoveryState(scope) { alive(); return readDiscoveryState(ctx, scope); },
386
424
  readDiscoveryClaim(scope) {
387
425
  alive();
388
426
  return readClaim(ctx, scope);
@@ -0,0 +1,119 @@
1
+ // Generated from packages/operation-coordinator/src/subagent-launch.ts. Do not edit directly.
2
+ import { 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
+ finishRecovery(owner: string, key: string, epoch: number, result: unknown) {
71
+ this.transaction(() => {
72
+ this.current(epoch);
73
+ this.db.prepare("UPDATE subagent_launch_intents SET state='returned', result=? WHERE owner=? AND request_key=? AND state='accepted' AND epoch<?")
74
+ .run(JSON.stringify(result), owner, key, epoch);
75
+ });
76
+ }
77
+ accept(owner: string, key: string, digest: string, epoch: number) {
78
+ return this.transaction(() => {
79
+ this.current(epoch);
80
+ const prior = this.read(owner, key);
81
+ if (prior) {
82
+ if (prior.digest !== digest) throw new Error("request-conflict: launch key has different content");
83
+ return { prior: true, ...prior };
84
+ }
85
+ this.db.prepare("INSERT INTO subagent_launch_intents VALUES (?, ?, ?, ?, 'accepted', '[]', NULL)").run(owner, key, digest, epoch);
86
+ return this.read(owner, key);
87
+ });
88
+ }
89
+ prepare(owner: string, key: string, epoch: number, input: Omit<LaunchAttempt, "token" | "state">) {
90
+ return this.transaction(() => {
91
+ this.current(epoch);
92
+ const row = this.read(owner, key);
93
+ if (!row || row.epoch !== epoch || row.state !== "accepted") throw new Error("Launch intent is not admitted");
94
+ const attempts: LaunchAttempt[] = JSON.parse(row.attempts);
95
+ if (attempts.some(attempt => attempt.id === input.id)) throw new Error("Attempt already dispatched; reconcile exact identity");
96
+ const attempt: LaunchAttempt = { ...input, token: randomBytes(32).toString("hex"), state: "prepared" };
97
+ attempts.push(attempt);
98
+ this.db.prepare("UPDATE subagent_launch_intents SET attempts=? WHERE owner=? AND request_key=?").run(JSON.stringify(attempts), owner, key);
99
+ return attempt;
100
+ });
101
+ }
102
+ spawned(owner: string, key: string, epoch: number, id: string, pid: number, pidStartTime?: string) {
103
+ this.transaction(() => {
104
+ this.current(epoch);
105
+ const attempts = JSON.parse(this.read(owner, key)!.attempts) as LaunchAttempt[];
106
+ const attempt = attempts.find(value => value.id === id);
107
+ if (!attempt || attempt.state !== "prepared") throw new Error("Launch publication is ambiguous");
108
+ if (attempt.writerPid && attempt.writerPid !== pid) throw new Error("Launch writer does not match spawned process");
109
+ Object.assign(attempt, { state: "spawned", pid, pidStartTime });
110
+ this.db.prepare("UPDATE subagent_launch_intents SET attempts=? WHERE owner=? AND request_key=?").run(JSON.stringify(attempts), owner, key);
111
+ });
112
+ }
113
+ finish(owner: string, key: string, epoch: number, result: unknown) {
114
+ this.transaction(() => {
115
+ this.current(epoch);
116
+ 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);
117
+ });
118
+ }
119
+ }
@@ -83,6 +83,10 @@ export interface ObserverIdentity {
83
83
  * (a replacement host takes over on reload) while launch identity is not.
84
84
  */
85
85
  export interface SupervisionIdentity {
86
+ /** Durable discovery scope, recorded before sidecar creation or runner start. */
87
+ resultScope?: string;
88
+ /** The host uses grant-before-runner result admission and performs no global discovery. */
89
+ resultAdapter?: 1;
86
90
  /** Host that owns supervision, e.g. the Pi process id plus a start token. */
87
91
  hostId: string;
88
92
  /** Runner process identity, when a separate runner owns the operation. */
@@ -112,6 +116,8 @@ export interface RegisterOperationInput {
112
116
  }
113
117
 
114
118
  export interface OperationRecord {
119
+ /** Grant presence in the same snapshot as a bulk operation read. */
120
+ resultManaged?: boolean;
115
121
  operationId: string;
116
122
  taskId: string;
117
123
  launchToken: string;
@@ -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
+ }
@@ -1,4 +1,5 @@
1
1
  import { connect } from "node:net";
2
+ import { performance } from "node:perf_hooks";
2
3
 
3
4
  /** SDK-free observation stream. Cached snapshots are the only synchronous read API. */
4
5
  export class WorkClient {
@@ -6,6 +7,7 @@ export class WorkClient {
6
7
  snapshot;
7
8
  pending = new Map();
8
9
  listeners = new Set();
10
+ catalogListeners = new Set();
9
11
  sequence = 0;
10
12
  scope;
11
13
  buffer = "";
@@ -23,6 +25,7 @@ export class WorkClient {
23
25
  try {
24
26
  const message = JSON.parse(line);
25
27
  if (message.type === "event") {
28
+ if (message.event.type === "runtime_catalog_snapshot") { for (const listener of this.catalogListeners) listener(message.event.snapshot); continue; }
26
29
  if (message.event.type === "resync_required") { this.degrade(message.event.reason); void this.resync().catch(error => this.degrade(String(error))); }
27
30
  else if (message.event.type === "runtime_snapshot") this.accept(message.event.snapshot);
28
31
  } else {
@@ -50,6 +53,7 @@ export class WorkClient {
50
53
  });
51
54
  }
52
55
  onChange(listener) { this.listeners.add(listener); return () => this.listeners.delete(listener); }
56
+ onCatalog(listener) { this.catalogListeners.add(listener); return () => this.catalogListeners.delete(listener); }
53
57
  notify() { for (const listener of this.listeners) listener(this.snapshot); }
54
58
  degrade(reason) {
55
59
  this.snapshot = { ...this.snapshot, status: "degraded", reason, rows: this.snapshot?.rows ?? [] };
@@ -77,12 +81,22 @@ export class WorkClient {
77
81
  const snapshot = await this.request("runtime_subscribe", { scope: this.scope, sinceSeq: this.snapshot?.seq, instanceId: this.snapshot?.instanceId });
78
82
  this.accept(snapshot); return snapshot;
79
83
  }
80
- async get(scope) { await this.ready; return this.request("runtime_get_snapshot", { scope }); }
84
+ async get(scope) {
85
+ await this.ready;
86
+ const until = performance.now() + 3500;
87
+ for (let attempt = 0; ; attempt++) {
88
+ const value = await this.request("runtime_get_snapshot", { scope });
89
+ if (!scope?.id || value.status !== "rebuilding" || value.rows.length || performance.now() >= until) return value;
90
+ // A newly written ID may join an inventory without holding the shared RPC queue.
91
+ await new Promise(resolve => setTimeout(resolve, Math.min(250, 50 * 2 ** attempt, until - performance.now())));
92
+ }
93
+ }
81
94
  fail(error) {
82
95
  if (this.closed) return;
83
96
  this.closed = true;
84
97
  for (const request of this.pending.values()) { clearTimeout(request.timer); request.reject(error); }
85
98
  this.pending.clear(); this.socket.destroy(); this.degrade(String(error));
99
+ for (const listener of this.catalogListeners) listener({ status: "revoked" });
86
100
  }
87
- close() { this.fail(new Error("runtime-unavailable: client closed")); this.listeners.clear(); }
101
+ close() { this.fail(new Error("runtime-unavailable: client closed")); this.listeners.clear(); this.catalogListeners.clear(); }
88
102
  }