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
@@ -0,0 +1,73 @@
1
+ // Generated from packages/operation-coordinator/src/assignment-changes.ts. Do not edit directly.
2
+ import type { StoreContext } from "./sqlite.ts";
3
+
4
+ /** Additive observation journal. Triggers also cover already-running old writers. */
5
+ export function ensureAssignmentChanges(ctx: StoreContext): void {
6
+ ctx.transaction(() => {
7
+ ctx.db.exec(`CREATE TABLE IF NOT EXISTS assignment_change_source (
8
+ singleton INTEGER PRIMARY KEY CHECK(singleton=1), generation TEXT NOT NULL);
9
+ INSERT OR IGNORE INTO assignment_change_source VALUES(1, lower(hex(randomblob(16))));
10
+ CREATE TABLE IF NOT EXISTS assignment_changes (
11
+ seq INTEGER PRIMARY KEY AUTOINCREMENT, entity TEXT NOT NULL, entity_id TEXT NOT NULL DEFAULT '',
12
+ assignment_id TEXT, session_id TEXT NOT NULL, workspace TEXT NOT NULL,
13
+ changed_at INTEGER NOT NULL DEFAULT (unixepoch()*1000));
14
+ CREATE INDEX IF NOT EXISTS waits_assignment_observation ON waits
15
+ (owner_kind,owner_session_id,owner_workspace,json_extract(origin_json,'$.assignmentRef'),created_at DESC,generation DESC);
16
+ CREATE INDEX IF NOT EXISTS resume_claims_wait_observation ON resume_claims(wait_id,generation,attempt_id);
17
+ CREATE TABLE IF NOT EXISTS background_input_versions (
18
+ operation_id TEXT PRIMARY KEY, revision INTEGER NOT NULL);
19
+ CREATE TRIGGER IF NOT EXISTS assignment_changes_retention AFTER INSERT ON assignment_changes
20
+ BEGIN DELETE FROM assignment_changes WHERE seq <= NEW.seq - 4096; END;`);
21
+ // Repair is an operation-ID keyset, not an observer equality lookup.
22
+ // A leading observer column competes with the ordered recent-terminal index.
23
+ if (ctx.db.prepare("PRAGMA index_info(background_operation_repair)").all().length > 1)
24
+ ctx.db.exec("DROP INDEX background_operation_repair");
25
+ ctx.db.exec("CREATE INDEX IF NOT EXISTS background_operation_repair ON operations(operation_id) WHERE observer_kind='local-supervisor'");
26
+ const sources = [
27
+ { table: "waits", select: (r: string) => `SELECT 'wait', ${r}.wait_id || ':' || ${r}.generation, json_extract(${r}.origin_json,'$.assignmentRef'), ${r}.owner_session_id, ${r}.owner_workspace WHERE ${r}.owner_kind='worker-conversation'` },
28
+ { table: "resume_claims", select: (r: string) => `SELECT 'claim', ${r}.claim_id, json_extract(w.origin_json,'$.assignmentRef'), w.owner_session_id, w.owner_workspace FROM waits w WHERE w.wait_id=${r}.wait_id AND w.generation=${r}.generation AND w.owner_kind='worker-conversation'` },
29
+ { table: "assignment_bindings", select: (r: string) => `SELECT 'binding', ${r}.assignment_id, ${r}.assignment_id, json_extract(${r}.owner_json,'$.sessionId'), json_extract(${r}.owner_json,'$.workspace')` },
30
+ { table: "assignment_attempts", select: (r: string) => `SELECT 'attempt', ${r}.attempt_id, b.assignment_id, json_extract(b.owner_json,'$.sessionId'), json_extract(b.owner_json,'$.workspace') FROM assignment_bindings b WHERE b.assignment_id=${r}.assignment_id` },
31
+ { table: "assignment_outcomes", select: (r: string) => `SELECT 'outcome', ${r}.assignment_id, ${r}.assignment_id, json_extract(${r}.record_json,'$.owner.sessionId'), json_extract(${r}.record_json,'$.owner.workspace')` },
32
+ { table: "outbox_events", select: (r: string) => `SELECT 'receipt', ${r}.event_id, b.assignment_id, json_extract(b.owner_json,'$.sessionId'), json_extract(b.owner_json,'$.workspace') FROM assignment_bindings b WHERE b.assignment_id=${r}.operation_id UNION ALL SELECT 'receipt', ${r}.event_id, json_extract(w.origin_json,'$.assignmentRef'), w.owner_session_id, w.owner_workspace FROM waits w WHERE w.wait_id=${r}.wait_id AND w.generation=${r}.generation AND w.owner_kind='worker-conversation'` },
33
+ ];
34
+ for (const { table, select } of sources) for (const action of ["INSERT", "UPDATE", "DELETE"]) {
35
+ const records = action === "UPDATE" ? ["OLD", "NEW"] : [action === "DELETE" ? "OLD" : "NEW"];
36
+ ctx.db.exec(`CREATE TRIGGER IF NOT EXISTS assignment_change_${table}_${action.toLowerCase()} AFTER ${action} ON ${table} BEGIN ${records.map(r => `INSERT INTO assignment_changes(entity,entity_id,assignment_id,session_id,workspace) ${select(r)};`).join(" ")} END;`);
37
+ }
38
+ // These are observation inputs, not execution or delivery authority. Old
39
+ // cooperative SQL writers inherit the same atomic invalidation triggers.
40
+ const backgroundSources = [
41
+ { table: "operations", select: (r: string) => `SELECT ${r}.operation_id, 1 WHERE ${r}.observer_kind='local-supervisor'` },
42
+ { table: "waits", select: (r: string) => `SELECT d.operation_id, 1 FROM wait_dependencies d JOIN operations o ON o.operation_id=d.operation_id WHERE d.wait_id=${r}.wait_id AND d.generation=${r}.generation AND o.observer_kind='local-supervisor'` },
43
+ { table: "wait_dependencies", select: (r: string) => `SELECT ${r}.operation_id, 1 WHERE EXISTS(SELECT 1 FROM operations o WHERE o.operation_id=${r}.operation_id AND o.observer_kind='local-supervisor')` },
44
+ { table: "background_parent_callbacks", select: (r: string) => `SELECT ${r}.operation_id, 1 WHERE 1` },
45
+ { table: "coordinator_state", select: (r: string) => `SELECT o.operation_id, 1 FROM operations o WHERE ${r}.key LIKE 'result-supervision-v1:%' AND o.operation_id=substr(${r}.key,length('result-supervision-v1:')+1) AND o.observer_kind='local-supervisor'` },
46
+ ];
47
+ // Version 1 installed one-column SELECTs into a two-column INSERT. Replace
48
+ // only these owned triggers, atomically, without resetting source positions.
49
+ const replaceBackgroundTriggers = ctx.db.prepare("SELECT value FROM schema_meta WHERE key='background_input_triggers_version'").get()?.value !== "2";
50
+ for (const { table, select } of backgroundSources) for (const action of ["INSERT", "UPDATE", "DELETE"]) {
51
+ if (replaceBackgroundTriggers) ctx.db.exec(`DROP TRIGGER IF EXISTS background_input_${table}_${action.toLowerCase()}`);
52
+ const records = action === "UPDATE" ? ["OLD", "NEW"] : [action === "DELETE" ? "OLD" : "NEW"];
53
+ ctx.db.exec(`CREATE TRIGGER IF NOT EXISTS background_input_${table}_${action.toLowerCase()}
54
+ ${action === "DELETE" ? "BEFORE" : "AFTER"} ${action} ON ${table} BEGIN
55
+ ${records.map(r => `INSERT INTO background_input_versions(operation_id,revision) ${select(r)}
56
+ ON CONFLICT(operation_id) DO UPDATE SET revision=revision+1;`).join(" ")}
57
+ END;`);
58
+ }
59
+ if (replaceBackgroundTriggers) ctx.db.prepare("INSERT OR REPLACE INTO schema_meta(key,value) VALUES('background_input_triggers_version','2')").run();
60
+ ctx.db.exec(`CREATE TRIGGER IF NOT EXISTS background_journal_insert AFTER INSERT ON background_input_versions BEGIN
61
+ INSERT INTO assignment_changes(entity,entity_id,assignment_id,session_id,workspace)
62
+ SELECT 'background:operation', NEW.operation_id, NEW.operation_id, owner_session_id, owner_workspace FROM operations WHERE operation_id=NEW.operation_id;
63
+ END;
64
+ CREATE TRIGGER IF NOT EXISTS background_journal_update AFTER UPDATE ON background_input_versions BEGIN
65
+ INSERT INTO assignment_changes(entity,entity_id,assignment_id,session_id,workspace)
66
+ SELECT 'background:operation', NEW.operation_id, NEW.operation_id, owner_session_id, owner_workspace FROM operations WHERE operation_id=NEW.operation_id;
67
+ END;
68
+ CREATE TRIGGER IF NOT EXISTS background_journal_previous_scope AFTER UPDATE ON operations
69
+ WHEN OLD.observer_kind='local-supervisor' AND (OLD.owner_session_id<>NEW.owner_session_id OR OLD.owner_workspace<>NEW.owner_workspace OR OLD.owner_kind<>NEW.owner_kind)
70
+ BEGIN INSERT INTO assignment_changes(entity,entity_id,assignment_id,session_id,workspace)
71
+ VALUES('background:operation',OLD.operation_id,OLD.operation_id,OLD.owner_session_id,OLD.owner_workspace); END;`);
72
+ });
73
+ }
@@ -1,5 +1,6 @@
1
1
  // Generated from packages/operation-coordinator/src/assignment-outcomes.ts. Do not edit directly.
2
2
  import { createHash, randomUUID } from "node:crypto";
3
+ import { bumpChangeRevision } from "./discovery.ts";
3
4
  import { StoreError } from "./errors.ts";
4
5
  import { columnText, getRow, getRows, run, type StoreContext } from "./sqlite.ts";
5
6
  import { requireWait, readPins } from "./rows.ts";
@@ -120,6 +121,7 @@ export function recordAssignmentOutcome(ctx: StoreContext, input: AssignmentOutc
120
121
  }
121
122
  for (const e of retained) run(ctx, `INSERT OR IGNORE INTO evidence_pins (pin_id, wait_id, generation, operation_id, terminal_revision, kind, ref, summary, detail_lost, bytes, pinned_at) VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?)`, `pin_${randomUUID()}`, eventId, e.operationId, e.terminalRevision, e.kind, e.ref, e.summary ?? null, e.detailLost ? 1 : 0, e.bytes ?? null, at);
122
123
  run(ctx, `INSERT INTO outbox_events (event_id, event_type, operation_id, terminal_revision, wait_id, generation, recipient_kind, recipient_session_id, recipient_workspace, recipient_branch_id, recipient_goal_id, state, created_at) VALUES (?, 'assignment-outcome', ?, ?, ?, 1, ?, ?, ?, ?, ?, 'pending', ?)`, eventId, assignmentId, revision, eventId, recipient.kind, recipient.sessionId, recipient.workspace, recipient.branchId ?? null, recipient.goalId ?? null, at);
124
+ bumpChangeRevision(ctx);
123
125
  return record;
124
126
  });
125
127
  }
@@ -0,0 +1,68 @@
1
+ // Generated from packages/operation-coordinator/src/background-parent-callbacks.ts. Do not edit directly.
2
+ /** Pending parent notifications are obligations, independent of UI retention. */
3
+ import { bumpChangeRevision } from './discovery.ts';
4
+ import { mapOperation } from './rows.ts';
5
+ import { getRow, getRows, run, type StoreContext } from './sqlite.ts';
6
+ import { requireBoolean, requireCounter, requireId, requirePath } from './validate.ts';
7
+ import type { OperationRecord } from './types.ts';
8
+
9
+ export interface ParentCallbackScope { sessionId: string; workspace: string }
10
+ export interface ParentCallbackPage { after?: string; limit?: number }
11
+ export interface RecentBackgroundTerminalPage {
12
+ since: number;
13
+ after?: { terminalAt: number; operationId: string };
14
+ limit?: number;
15
+ owner?: ParentCallbackScope;
16
+ }
17
+ const pageSize = (limit = 256) => Math.max(1, Math.min(256, requireCounter('limit', limit)));
18
+ const scopeValues = (scope: ParentCallbackScope) => [requirePath('workspace', scope.workspace), requireId('sessionId', scope.sessionId)] as const;
19
+
20
+ export function setParentCallbackPending(ctx: StoreContext, taskId: string, pending: boolean): boolean {
21
+ taskId = requireId('taskId', taskId);
22
+ pending = requireBoolean('pending', pending);
23
+ return ctx.transaction(() => {
24
+ const operation = getRow(ctx, "SELECT operation_id, owner_workspace, owner_session_id FROM operations WHERE task_id=? AND owner_kind='parent-session' AND observer_kind='local-supervisor'", taskId);
25
+ if (!operation) return false;
26
+ const changed = pending
27
+ ? run(ctx, `INSERT OR IGNORE INTO background_parent_callbacks(operation_id,owner_kind,owner_workspace,owner_session_id)
28
+ VALUES (?,'parent-session',?,?)`, String(operation.operation_id), String(operation.owner_workspace), String(operation.owner_session_id))
29
+ : run(ctx, 'DELETE FROM background_parent_callbacks WHERE operation_id=?', String(operation.operation_id));
30
+ if (changed > 0) bumpChangeRevision(ctx);
31
+ return changed > 0;
32
+ });
33
+ }
34
+
35
+ export function listPendingParentCallbacks(ctx: StoreContext, scope: ParentCallbackScope, options: ParentCallbackPage = {}): OperationRecord[] {
36
+ return getRows(ctx, `SELECT o.* FROM background_parent_callbacks p JOIN operations o ON o.operation_id=p.operation_id
37
+ WHERE p.owner_kind='parent-session' AND p.owner_workspace=? AND p.owner_session_id=? AND p.operation_id>? AND o.terminal_revision>0
38
+ ORDER BY p.operation_id LIMIT ?`, ...scopeValues(scope), options.after === undefined ? '' : requireId('after', options.after), pageSize(options.limit)).map(mapOperation);
39
+ }
40
+
41
+ export function listRecentBackgroundTerminals(ctx: StoreContext, options: RecentBackgroundTerminalPage): OperationRecord[] {
42
+ const params: Array<string|number> = [requireCounter('since', options.since)];
43
+ let where = "observer_kind='local-supervisor' AND terminal_revision>0 AND terminal_at>=?";
44
+ if (options.owner) { where += " AND owner_kind='parent-session' AND owner_workspace=? AND owner_session_id=?"; params.push(...scopeValues(options.owner)); }
45
+ if (options.after) { where += ' AND (terminal_at,operation_id)>(?,?)'; params.push(requireCounter('after.terminalAt', options.after.terminalAt), requireId('after.operationId', options.after.operationId)); }
46
+ params.push(pageSize(options.limit));
47
+ return getRows(ctx, `SELECT * FROM operations WHERE ${where} ORDER BY terminal_at,operation_id LIMIT ?`, ...params).map(mapOperation);
48
+ }
49
+
50
+ /** Call from the canonical manager in bounded batches, yielding between pages. */
51
+ export function seedPendingParentCallbacks(ctx: StoreContext, options: { limit?: number } = {}): { done: boolean; seeded: number } {
52
+ return ctx.transaction(() => {
53
+ const migration = getRow(ctx, 'SELECT * FROM background_parent_callback_migration WHERE singleton=1')!;
54
+ if (Number(migration.done)) return { done: true, seeded: 0 };
55
+ const limit = pageSize(options.limit);
56
+ const rows = getRows(ctx, `SELECT operation_id,owner_workspace,owner_session_id FROM operations
57
+ WHERE owner_kind='parent-session' AND observer_kind='local-supervisor' AND operation_id>? AND operation_id<=?
58
+ ORDER BY operation_id LIMIT ?`, String(migration.after_operation_id), String(migration.through_operation_id), limit);
59
+ let seeded = 0;
60
+ for (const row of rows) seeded += Number(run(ctx, `INSERT OR IGNORE INTO background_parent_callbacks(operation_id,owner_kind,owner_workspace,owner_session_id)
61
+ VALUES (?,'parent-session',?,?)`, String(row.operation_id), String(row.owner_workspace), String(row.owner_session_id)));
62
+ const after = rows.length ? String(rows.at(-1)!.operation_id) : String(migration.after_operation_id);
63
+ const done = rows.length < limit || after === migration.through_operation_id;
64
+ run(ctx, 'UPDATE background_parent_callback_migration SET after_operation_id=?,done=? WHERE singleton=1', after, done ? 1 : 0);
65
+ if (seeded) bumpChangeRevision(ctx);
66
+ return { done, seeded };
67
+ });
68
+ }
@@ -0,0 +1,90 @@
1
+ // Generated from packages/operation-coordinator/src/background-requests.ts. Do not edit directly.
2
+ import { createHash } from 'node:crypto';
3
+ import type { StoreContext } from './sqlite.ts';
4
+ export interface BackgroundRequest {
5
+ owner: string;
6
+ key: string;
7
+ digest: string;
8
+ state: 'accepted' | 'dispatching' | 'returned';
9
+ operations: Array<{
10
+ operationId: string;
11
+ taskId: string;
12
+ token: string;
13
+ }>;
14
+ result?: unknown;
15
+ acceptedAt?: number;
16
+ lastProgressAt?: number;
17
+ writerFence?: { instance: string; pid: number; start: string };
18
+ }
19
+ const prefix = 'background-request-v1:';
20
+ // A partial index excludes returned history. CASE protects other coordinator
21
+ // records and makes corrupt request rows visible to recovery rather than hiding them.
22
+ const pendingPredicate = "key GLOB 'background-request-v1:*' AND CASE WHEN json_valid(value) THEN COALESCE(json_extract(value, '$.state'), '') != 'returned' ELSE 1 END";
23
+ export const BACKGROUND_PENDING_QUERY = `SELECT value FROM coordinator_state INDEXED BY background_requests_pending WHERE ${pendingPredicate} ORDER BY key LIMIT ?`;
24
+ function storageKey(owner: string, key: string) { return prefix + createHash('sha256').update(JSON.stringify([owner, key])).digest('hex'); }
25
+ export class BackgroundRequests {
26
+ private context: StoreContext;
27
+ private alive: () => void;
28
+ constructor(context: StoreContext, alive: () => void) {
29
+ this.context = context;
30
+ this.alive = alive;
31
+ alive();
32
+ context.db.exec(`CREATE INDEX IF NOT EXISTS background_requests_pending ON coordinator_state(key) WHERE ${pendingPredicate}`);
33
+ }
34
+ read(owner: string, key: string): BackgroundRequest | undefined {
35
+ this.alive();
36
+ const row = this.context.db.prepare('SELECT value FROM coordinator_state WHERE key=?').get(storageKey(owner, key));
37
+ return row ? JSON.parse(String(row.value)) : undefined;
38
+ }
39
+ private write(value: BackgroundRequest) {
40
+ this.context.db.prepare('INSERT OR REPLACE INTO coordinator_state (key,value) VALUES (?,?)').run(storageKey(value.owner, value.key), JSON.stringify(value));
41
+ }
42
+ accept(owner: string, key: string, digest: string, writerFence?: BackgroundRequest['writerFence']) {
43
+ this.alive();
44
+ return this.context.transaction(() => {
45
+ const prior = this.read(owner, key);
46
+ if (prior) {
47
+ if (prior.digest !== digest)
48
+ throw new Error('request-conflict: Background request key changed content');
49
+ return { prior: true, record: prior };
50
+ }
51
+ const record: BackgroundRequest = { owner, key, digest, state: 'accepted', operations: [], acceptedAt: Date.now(), lastProgressAt: Date.now(), writerFence };
52
+ this.write(record);
53
+ return { prior: false, record };
54
+ });
55
+ }
56
+ dispatch(owner: string, key: string) { this.update(owner, key, value => { if (value.state !== 'accepted')
57
+ throw new Error('Background request already dispatched'); value.state = 'dispatching'; }); }
58
+ operation(owner: string, key: string, operation: BackgroundRequest['operations'][number]) {
59
+ this.update(owner, key, value => {
60
+ if (value.state !== 'dispatching')
61
+ throw new Error('Background request is not dispatching');
62
+ if (value.operations.some(prior => prior.operationId === operation.operationId))
63
+ throw new Error('Background operation already prepared');
64
+ value.operations.push(operation);
65
+ });
66
+ }
67
+ finish(owner: string, key: string, result: unknown) { this.update(owner, key, value => { value.result = result; value.state = 'returned'; }); }
68
+ private update(owner: string, key: string, change: (value: BackgroundRequest) => void) {
69
+ this.alive();
70
+ this.context.transaction(() => { const value = this.read(owner, key); if (!value)
71
+ throw new Error('Background request not admitted'); change(value); value.lastProgressAt = Date.now(); this.write(value); });
72
+ }
73
+ lifecycleReasons() {
74
+ return this.pending().map(record => ({ kind: 'task', id: storageKey(record.owner, record.key),
75
+ owner: record.owner, state: record.state, acceptedAt: record.acceptedAt ?? null,
76
+ writerFence: record.writerFence ?? null,
77
+ lastProgressAt: record.lastProgressAt ?? null, executionDeadline: null, nextDeadline: null,
78
+ operations: record.operations.map(({ operationId, taskId }) => ({ operationId, taskId })),
79
+ recovery: 'drain-accepted-background-request-until-journal-return-or-authoritative-handoff' }));
80
+ }
81
+ hasPending(): boolean {
82
+ this.alive();
83
+ return Boolean(this.context.db.prepare(`SELECT 1 FROM coordinator_state INDEXED BY background_requests_pending WHERE ${pendingPredicate} LIMIT 1`).get());
84
+ }
85
+ pending(limit = 128): BackgroundRequest[] {
86
+ this.alive();
87
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 128) throw new Error('Background recovery batch limit must be 1..128');
88
+ return this.context.db.prepare(BACKGROUND_PENDING_QUERY).all(limit).map(row => JSON.parse(String(row.value)));
89
+ }
90
+ }
@@ -49,11 +49,13 @@ export function readDiscoveryClaim(ctx: StoreContext, scope: unknown): Discovery
49
49
  }
50
50
 
51
51
  /** Read scope transfer and its discovery claim from one SQLite snapshot. */
52
- export function readDiscoveryState(ctx: StoreContext, scope: string): { managed: boolean; claim: DiscoveryClaimRecord | null } {
52
+ export function readDiscoveryState(ctx: StoreContext, scope: string): { managed: boolean; claim: DiscoveryClaimRecord | null; hasAssignmentTasks: boolean } {
53
53
  scope = requireId("scope", scope);
54
- const row = getRow(ctx, `SELECT d.*, EXISTS(SELECT 1 FROM coordinator_state WHERE key = ?) AS managed
54
+ const row = getRow(ctx, `SELECT d.*, EXISTS(SELECT 1 FROM coordinator_state WHERE key = ?) AS managed,
55
+ EXISTS(SELECT 1 FROM operations INDEXED BY operations_assignment_cleanup
56
+ WHERE assignment_attempt_id IS NOT NULL) AS has_assignment_tasks
55
57
  FROM (SELECT 1) LEFT JOIN discovery_claims d ON d.scope = ?`, "result-scope-v1:" + scope, scope)!;
56
- return { managed: Number(row.managed) === 1, claim: row.scope == null ? null : mapClaim(row) };
58
+ return { managed: Number(row.managed) === 1, claim: row.scope == null ? null : mapClaim(row), hasAssignmentTasks: Number(row.has_assignment_tasks) === 1 };
57
59
  }
58
60
 
59
61
  export function tryClaimDiscovery(
@@ -14,7 +14,9 @@
14
14
  import { StoreError } from "./errors.ts";
15
15
  import { mapOperation, ownerFromRow, readOperation, requireOperation } from "./rows.ts";
16
16
  import {
17
+ columnJson,
17
18
  columnText,
19
+ getRow,
18
20
  getRows,
19
21
  isUniqueViolation,
20
22
  run,
@@ -25,6 +27,7 @@ import type {
25
27
  ObserverHealth,
26
28
  OperationFilter,
27
29
  OperationRecord,
30
+ OwnerIdentity,
28
31
  ReleaseSupervisionInput,
29
32
  RecordSupervisionInput,
30
33
  RecordTerminalOutcomeInput,
@@ -40,6 +43,7 @@ import {
40
43
  normalizeOwner,
41
44
  optionalText,
42
45
  requireBoolean,
46
+ requireCounter,
43
47
  requireEnum,
44
48
  requireEvidenceKind,
45
49
  requireId,
@@ -54,6 +58,7 @@ import { bumpChangeRevision } from "./discovery.ts";
54
58
 
55
59
  const HEALTH_VALUES: readonly ObserverHealth[] = ["active", "unmonitored", "lost"];
56
60
  const OUTCOME_VALUES: readonly TerminalOutcome[] = ["succeeded", "failed", "cancelled", "lost"];
61
+ const ASSIGNMENT_CLEANUP_PAGE_MAX = 256;
57
62
 
58
63
  function normalizeSupervision(value: unknown): SupervisionIdentity | null {
59
64
  if (value === undefined || value === null) return null;
@@ -108,6 +113,9 @@ export function registerOperation(
108
113
  const taskId = requireId("taskId", input.taskId);
109
114
  const launchToken = requireId("launchToken", input.launchToken);
110
115
  const owner = normalizeOwner("owner", input.owner);
116
+ const assignmentAttemptId = input.assignmentAttemptId === undefined
117
+ ? undefined
118
+ : requireId("assignmentAttemptId", input.assignmentAttemptId);
111
119
  const observer = requireObserver("observer", input.observer);
112
120
  const supervision = normalizeSupervision(input.supervision);
113
121
  const authorityRef = optionalText("authorityRef", input.authorityRef, 512);
@@ -133,6 +141,7 @@ export function registerOperation(
133
141
  const differences: string[] = [];
134
142
  if (existing.taskId !== taskId) differences.push("taskId");
135
143
  if (existing.launchToken !== launchToken) differences.push("launchToken");
144
+ if (existing.assignmentAttemptId !== assignmentAttemptId) differences.push("assignmentAttemptId");
136
145
  if (!sameOwner(existing.owner, owner)) {
137
146
  differences.push(`owner (${describeOwnerDiff(existing.owner, owner)})`);
138
147
  }
@@ -154,6 +163,20 @@ export function registerOperation(
154
163
  return { operation: existing, created: false };
155
164
  }
156
165
  assertTaskAvailable();
166
+ if (assignmentAttemptId !== undefined) {
167
+ const binding = getRow(ctx, `SELECT b.owner_json, o.assignment_id AS terminal_assignment_id
168
+ FROM assignment_attempts a
169
+ JOIN assignment_bindings b ON b.assignment_id = a.assignment_id
170
+ LEFT JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
171
+ WHERE a.attempt_id = ?`, assignmentAttemptId);
172
+ const capturedOwner = binding && columnJson<OwnerIdentity>(binding, "owner_json");
173
+ if (!binding || !capturedOwner || !sameOwner(capturedOwner, owner)) {
174
+ throw new StoreError("foreign-owner", "Operation owner must match the captured owner of a registered assignment attempt.");
175
+ }
176
+ if (binding.terminal_assignment_id !== null) {
177
+ throw new StoreError("validation", "A terminal assignment cannot register a new operation.");
178
+ }
179
+ }
157
180
 
158
181
  const at = ctx.now();
159
182
  try {
@@ -161,10 +184,10 @@ export function registerOperation(
161
184
  ctx,
162
185
  `INSERT INTO operations (
163
186
  operation_id, task_id, launch_token,
164
- owner_kind, owner_session_id, owner_workspace, owner_branch_id, owner_goal_id,
187
+ owner_kind, owner_session_id, owner_workspace, owner_branch_id, owner_goal_id, assignment_attempt_id,
165
188
  observer_kind, observer_version, supervision_json, supervision_host_id, authority_ref, intent_ref,
166
189
  phase, health, health_reason, terminal_revision, created_at, updated_at
167
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'running', 'active', NULL, 0, ?, ?)`,
190
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'running', 'active', NULL, 0, ?, ?)`,
168
191
  operationId,
169
192
  taskId,
170
193
  launchToken,
@@ -173,6 +196,7 @@ export function registerOperation(
173
196
  owner.workspace,
174
197
  owner.branchId ?? null,
175
198
  owner.goalId ?? null,
199
+ assignmentAttemptId ?? null,
176
200
  observer.kind,
177
201
  observer.version,
178
202
  supervision ? JSON.stringify(supervision) : null,
@@ -439,6 +463,30 @@ export function listOperations(
439
463
  .map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
440
464
  }
441
465
 
466
+ export function listAssignmentCleanupOperations(
467
+ ctx: StoreContext,
468
+ limit: number,
469
+ afterOperationId?: string,
470
+ ): OperationRecord[] {
471
+ const requested = requireCounter("limit", limit);
472
+ if (requested === 0) throw new StoreError("validation", "Invalid limit: must be at least 1");
473
+ const cursor = afterOperationId === undefined ? "" : requireId("afterOperationId", afterOperationId);
474
+ // Seek the partial index in cursor order rather than sorting all running operations.
475
+ return getRows(ctx, `SELECT op.*, EXISTS(SELECT 1 FROM coordinator_state s
476
+ WHERE s.key = 'result-supervision-v1:' || op.operation_id) AS result_managed
477
+ FROM operations op INDEXED BY operations_assignment_cleanup
478
+ JOIN assignment_attempts a ON a.attempt_id = op.assignment_attempt_id
479
+ JOIN assignment_outcomes o ON o.assignment_id = a.assignment_id
480
+ WHERE op.assignment_attempt_id IS NOT NULL AND op.operation_id > ?
481
+ AND (op.terminal_revision = 0 OR op.terminal_outcome = 'lost'
482
+ OR EXISTS (SELECT 1 FROM operation_evidence e WHERE e.operation_id = op.operation_id
483
+ AND e.terminal_revision = op.terminal_revision AND e.kind = 'terminal-record'
484
+ AND e.summary LIKE '%groupCleanup=unproven%'))
485
+ AND NOT EXISTS (SELECT 1 FROM coordinator_state s WHERE s.key = 'assignment-cleanup-verified:' || op.operation_id)
486
+ ORDER BY op.operation_id LIMIT ?`, cursor, Math.min(requested, ASSIGNMENT_CLEANUP_PAGE_MAX))
487
+ .map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
488
+ }
489
+
442
490
  /** Running operations assigned to one supervising host, using the phase/host index. */
443
491
  export function listRunningSupervisedBy(
444
492
  ctx: StoreContext,
@@ -7,6 +7,18 @@ import type { RecordTerminalOutcomeInput } from "./types.ts";
7
7
  import type { OwnerIdentity } from "./types.ts";
8
8
 
9
9
  const PREFIX = "result-supervision-v1:";
10
+ /** A bounded observation page. A gap requires restoring active authority, not history. */
11
+ export function resultSupervisionChanges(ctx: StoreContext, after?: { generation: string; seq: number }) {
12
+ const generation = String(ctx.db.prepare("SELECT generation FROM assignment_change_source WHERE singleton=1").get()!.generation);
13
+ const bounds = ctx.db.prepare("SELECT min(seq) AS first, max(seq) AS last FROM assignment_changes").get()!;
14
+ const last = Number(bounds.last ?? 0);
15
+ const reset = !after || after.generation !== generation || after.seq > last
16
+ || (bounds.first !== null && after.seq < Number(bounds.first) - 1);
17
+ const rows = reset ? [] : ctx.db.prepare("SELECT seq, entity, entity_id FROM assignment_changes WHERE seq>? ORDER BY seq LIMIT 128").all(after!.seq);
18
+ const seq = reset ? last : Number(rows.at(-1)?.seq ?? after!.seq);
19
+ return { generation, seq, reset, more: seq < last,
20
+ operationIds: [...new Set(rows.filter(row => row.entity === "background:operation").map(row => String(row.entity_id)))] };
21
+ }
10
22
  export interface ResultSupervision {
11
23
  operationId: string;
12
24
  directory: string;
@@ -74,11 +74,13 @@ export function getOperationRowByTask(
74
74
  }
75
75
 
76
76
  export function mapOperation(row: Record<string, unknown>): OperationRecord {
77
+ const assignmentAttemptId = columnNullableText(row, "assignment_attempt_id");
77
78
  return {
78
79
  operationId: columnText(row, "operation_id"),
79
80
  taskId: columnText(row, "task_id"),
80
81
  launchToken: columnText(row, "launch_token"),
81
82
  owner: ownerFromRow(row),
83
+ ...(assignmentAttemptId === null ? {} : { assignmentAttemptId }),
82
84
  observer: {
83
85
  kind: columnText(row, "observer_kind"),
84
86
  version: columnText(row, "observer_version"),
@@ -1,6 +1,6 @@
1
1
  // Generated from packages/operation-coordinator/src/schema.ts. Do not edit directly.
2
2
  /**
3
- * Schema v4 for the durable operation coordinator.
3
+ * Schema v5 for the durable operation coordinator.
4
4
  *
5
5
  * The store refuses to open a database whose recorded version it does not
6
6
  * understand, and leaves the file untouched. An unreadable or newer database
@@ -30,6 +30,42 @@ const RESULT_ADMISSION_FENCE = `CREATE TRIGGER IF NOT EXISTS result_scope_admiss
30
30
  OR key = 'result-scope-v1:' || json_extract(NEW.supervision_json, '$.resultScope')))
31
31
  BEGIN SELECT RAISE(ABORT, 'permission-unavailable: legacy launch into managed result scope'); END`;
32
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
+
60
+ const ASSIGNMENT_ATTEMPTS_DDL = `CREATE TABLE IF NOT EXISTS assignment_attempts (
61
+ attempt_id TEXT PRIMARY KEY,
62
+ assignment_id TEXT NOT NULL REFERENCES assignment_bindings (assignment_id)
63
+ )`;
64
+ const ASSIGNMENT_ATTEMPT_COLUMN = `assignment_attempt_id TEXT REFERENCES assignment_attempts (attempt_id)`;
65
+ const ASSIGNMENT_CLEANUP_INDEX = `CREATE INDEX IF NOT EXISTS operations_assignment_cleanup
66
+ ON operations (operation_id, assignment_attempt_id)
67
+ WHERE assignment_attempt_id IS NOT NULL`;
68
+
33
69
  const DDL: readonly string[] = [
34
70
  `CREATE TABLE task_cancellation_authorities (
35
71
  credential_hash TEXT PRIMARY KEY,
@@ -66,6 +102,7 @@ const DDL: readonly string[] = [
66
102
  owner_workspace TEXT NOT NULL,
67
103
  owner_branch_id TEXT,
68
104
  owner_goal_id TEXT,
105
+ ${ASSIGNMENT_ATTEMPT_COLUMN},
69
106
  observer_kind TEXT NOT NULL,
70
107
  observer_version TEXT NOT NULL,
71
108
  supervision_json TEXT,
@@ -84,9 +121,11 @@ const DDL: readonly string[] = [
84
121
  updated_at INTEGER NOT NULL,
85
122
  terminal_at INTEGER
86
123
  )`,
124
+ ...BACKGROUND_CALLBACK_DDL,
87
125
  `CREATE INDEX operations_owner ON operations (owner_kind, owner_session_id)`,
88
126
  `CREATE INDEX operations_phase ON operations (phase)`,
89
127
  `CREATE INDEX operations_running_supervisor ON operations (phase, supervision_host_id)`,
128
+ ASSIGNMENT_CLEANUP_INDEX,
90
129
  // Discovery leadership is separate from per-operation supervision. The token
91
130
  // fences stale acquisition and release; the host id is checked with process
92
131
  // identity before a replacement.
@@ -240,10 +279,7 @@ const DDL: readonly string[] = [
240
279
  owner_json TEXT NOT NULL,
241
280
  recipient_json TEXT NOT NULL
242
281
  )`,
243
- `CREATE TABLE assignment_attempts (
244
- attempt_id TEXT PRIMARY KEY,
245
- assignment_id TEXT NOT NULL REFERENCES assignment_bindings (assignment_id)
246
- )`,
282
+ ASSIGNMENT_ATTEMPTS_DDL,
247
283
  `CREATE TABLE assignment_outcome_waits (
248
284
  assignment_id TEXT NOT NULL REFERENCES assignment_outcomes (assignment_id),
249
285
  wait_id TEXT NOT NULL,
@@ -305,34 +341,42 @@ export function ensureSchema(ctx: StoreContext): void {
305
341
  );
306
342
  }
307
343
  if (recorded < SCHEMA_VERSION) {
308
- if (recorded === 3) {
309
- ctx.transaction(() => {
310
- ensureAdditiveSchema(ctx);
311
- ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE TABLE assignment_repairs"))!);
312
- run(ctx, "UPDATE schema_meta SET value = ? WHERE key = ?", String(SCHEMA_VERSION), SCHEMA_VERSION_KEY);
313
- });
314
- return;
315
- }
316
- if (recorded === 1 || recorded === 2) {
344
+ ctx.transaction(() => {
345
+ // Another opener may have finished the upgrade before we acquired the write lock.
346
+ const current = readSchemaVersion(ctx);
347
+ if (current === SCHEMA_VERSION) return;
348
+ if (current !== recorded) {
349
+ throw new StoreError("schema-version", "The coordinator schema changed during opening. Reopen the store to verify it.");
350
+ }
317
351
  ensureAdditiveSchema(ctx);
318
- ctx.transaction(() => {
352
+ if (recorded <= 2) {
319
353
  if (recorded === 1) ctx.db.exec("ALTER TABLE outbox_events ADD COLUMN event_type TEXT NOT NULL DEFAULT 'dependency-ready'");
320
354
  for (const statement of DDL.filter((sql) => sql.startsWith("CREATE TABLE assignment_"))) ctx.db.exec(statement.replace("CREATE TABLE", "CREATE TABLE IF NOT EXISTS"));
321
355
  ctx.db.exec("ALTER TABLE waits ADD COLUMN dispatch_disarmed INTEGER NOT NULL DEFAULT 0");
322
356
  ctx.db.exec("UPDATE waits SET dispatch_disarmed = 1 WHERE EXISTS (SELECT 1 FROM assignment_outcome_waits aw WHERE aw.wait_id = waits.wait_id AND aw.generation = waits.generation)");
323
357
  ctx.db.exec("DROP INDEX waits_one_pending_per_owner");
324
358
  ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE UNIQUE INDEX waits_one_pending_per_owner"))!);
325
- run(ctx, "UPDATE schema_meta SET value = ? WHERE key = ?", String(SCHEMA_VERSION), SCHEMA_VERSION_KEY);
326
- });
327
- return;
328
- }
329
- throw new StoreError(
330
- "schema-version",
331
- `The database is at schema version ${recorded}; this build needs version ${SCHEMA_VERSION}. No migration is provided for this pair; records are left in place.`,
332
- );
359
+ } else if (recorded === 3) {
360
+ ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE TABLE assignment_repairs"))!);
361
+ }
362
+ ensureAssignmentCleanupSchema(ctx);
363
+ run(ctx, "UPDATE schema_meta SET value = ? WHERE key = ?", String(SCHEMA_VERSION), SCHEMA_VERSION_KEY);
364
+ });
365
+ return;
333
366
  }
334
367
  ensureAdditiveSchema(ctx);
335
- ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE TABLE assignment_attempts"))!.replace("CREATE TABLE", "CREATE TABLE IF NOT EXISTS"));
368
+ ensureAssignmentCleanupSchema(ctx);
369
+ }
370
+
371
+ function ensureAssignmentCleanupSchema(ctx: StoreContext): void {
372
+ const hasColumn = () => getRows(ctx, "PRAGMA table_info(operations)").some(row => row.name === "assignment_attempt_id");
373
+ if (hasColumn() && getRow(ctx, "SELECT 1 FROM sqlite_master WHERE name = 'operations_assignment_cleanup'")) return;
374
+ ctx.transaction(() => {
375
+ ctx.db.exec(ASSIGNMENT_ATTEMPTS_DDL);
376
+ // Legacy writers leave the nullable provenance unset.
377
+ if (!hasColumn()) ctx.db.exec(`ALTER TABLE operations ADD COLUMN ${ASSIGNMENT_ATTEMPT_COLUMN}`);
378
+ ctx.db.exec(ASSIGNMENT_CLEANUP_INDEX);
379
+ });
336
380
  }
337
381
 
338
382
  /**
@@ -341,6 +385,9 @@ export function ensureSchema(ctx: StoreContext): void {
341
385
  * records during a rolling upgrade. Missing additions are created once on open.
342
386
  */
343
387
  function ensureAdditiveSchema(ctx: StoreContext): void {
388
+ // Schema/index creation is atomic; legacy obligation seeding is performed
389
+ // separately in bounded batches by the canonical manager.
390
+ ctx.transaction(() => { for (const statement of BACKGROUND_CALLBACK_DDL) ctx.db.exec(statement); });
344
391
  const hasColumn = (): boolean =>
345
392
  getRows(ctx, "PRAGMA table_info(operations)").some((row) => columnText(row, "name") === "supervision_host_id");
346
393
  const hasIndex = (): boolean =>