pi-better-background-tasks 0.18.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 (49) hide show
  1. package/README.md +4 -3
  2. package/package.json +1 -1
  3. package/runtime-client/artifacts/darwin-arm64.gz +0 -0
  4. package/runtime-client/artifacts/darwin-arm64.json +1 -1
  5. package/runtime-client/artifacts/darwin-x64.gz +0 -0
  6. package/runtime-client/artifacts/darwin-x64.json +1 -1
  7. package/runtime-client/artifacts/linux-arm64.gz +0 -0
  8. package/runtime-client/artifacts/linux-arm64.json +1 -1
  9. package/runtime-client/artifacts/linux-x64.gz +0 -0
  10. package/runtime-client/artifacts/linux-x64.json +1 -1
  11. package/runtime-client/src/runtime/client.mjs +30 -3
  12. package/runtime-client/src/runtime/work-client.mjs +150 -7
  13. package/src/adapter-contract.ts +1 -1
  14. package/src/goal-provider.ts +31 -16
  15. package/src/index.ts +6 -9
  16. package/src/managed-authority.ts +5 -3
  17. package/src/managed-client.ts +20 -7
  18. package/src/managed-frontend.ts +62 -17
  19. package/src/navigator-provider.ts +15 -5
  20. package/src/observed-wait-client.ts +10 -0
  21. package/src/observed-waits.ts +154 -30
  22. package/src/process-identity.ts +18 -2
  23. package/src/process.ts +3 -3
  24. package/src/registry.ts +53 -5
  25. package/src/runtime.ts +19 -9
  26. package/src/sandbox.ts +14 -11
  27. package/src/shared-callback-batcher.ts +11 -2
  28. package/src/shared-navigator-panels.ts +26 -4
  29. package/src/shared-navigator.ts +197 -14
  30. package/src/shared-operation-coordinator/assignment-observation.mjs +43 -35
  31. package/src/shared-operation-coordinator/src/assignment-changes.ts +73 -0
  32. package/src/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
  33. package/src/shared-operation-coordinator/src/background-requests.ts +14 -3
  34. package/src/shared-operation-coordinator/src/discovery.ts +5 -3
  35. package/src/shared-operation-coordinator/src/operations.ts +50 -2
  36. package/src/shared-operation-coordinator/src/result-supervision.ts +12 -0
  37. package/src/shared-operation-coordinator/src/rows.ts +2 -0
  38. package/src/shared-operation-coordinator/src/schema.ts +40 -24
  39. package/src/shared-operation-coordinator/src/store.ts +34 -8
  40. package/src/shared-operation-coordinator/src/subagent-launch.ts +24 -1
  41. package/src/shared-operation-coordinator/src/types.ts +5 -1
  42. package/src/shared-sandbox-core.ts +1 -1
  43. package/src/shared-work-client.mjs +150 -7
  44. package/src/supervisor/generated/process-identity.mjs +20 -2
  45. package/src/supervisor/generated/process.mjs +3 -3
  46. package/src/task-diagnostics.ts +1 -1
  47. package/src/tools.ts +41 -38
  48. package/src/types.ts +3 -1
  49. package/src/work-observation.ts +46 -19
@@ -1,6 +1,16 @@
1
1
  // Generated from packages/operation-coordinator/assignment-observation.mjs. Do not edit directly.
2
2
  import { createRequire } from "node:module";
3
- import { createHash } from "node:crypto";
3
+ import { AssignmentInbox } from "./assignment-inbox.mjs";
4
+ import { pathToFileURL } from "node:url";
5
+
6
+ // Only first-party source SQL passes this facade; quoted values stay untouched.
7
+ const sourceTables = new Set(["schema_meta", "sqlite_master", "sqlite_schema", "assignment_change_source", "assignment_changes",
8
+ "waits", "wait_dependencies", "resume_claims", "operations", "coordinator_state", "assignment_outcomes",
9
+ "subagent_launch_intents", "background_input_versions", "background_parent_callbacks", "assignments", "assignment_bindings", "assignment_attempts"]);
10
+ function sourceSQL(sql) {
11
+ if (/^PRAGMA\s+data_version\s*$/i.test(sql)) return "PRAGMA coordinator_source.data_version";
12
+ return sql.replace(/'(?:''|[^'])*'|\b[A-Za-z_][A-Za-z_0-9]*\b/g, token => sourceTables.has(token) ? `coordinator_source.${token}` : token);
13
+ }
4
14
 
5
15
  /** Read-only, bounded projection input. Never creates/migrates a database. */
6
16
  export function readAssignmentWaits(path, owner, connection) {
@@ -44,42 +54,63 @@ export function readAssignmentWaits(path, owner, connection) {
44
54
  }
45
55
 
46
56
  /** A root read model owns this connection; ordinary observers remain one-shot. */
47
- export function createAssignmentReader(path) {
57
+ export function createAssignmentReader(path, inboxPath = ":memory:", derivedConnection, options = {}) {
58
+ const inbox = new AssignmentInbox(inboxPath, derivedConnection);
48
59
  let db;
49
60
  let identity;
50
61
  let snapshot = false;
62
+ const composed = options.composed === true;
63
+ const owner = derivedConnection;
64
+ const dropSource = () => {
65
+ if (composed) { if (db) owner.exec("DETACH DATABASE coordinator_source"); }
66
+ else db?.close();
67
+ db = undefined; statements.clear();
68
+ };
51
69
  const statements = new Map();
52
- return {
70
+ const reader = {
53
71
  revision() {
54
72
  const { statSync } = createRequire(import.meta.url)("node:fs");
55
73
  const stat = statSync(path, { bigint: true });
56
74
  const next = `${stat.dev}:${stat.ino}`;
57
75
  if (identity !== next) {
58
76
  if (snapshot) throw new Error("Coordinator identity changed during observation");
59
- db?.close();
60
- db = undefined;
61
- statements.clear();
77
+ dropSource();
62
78
  identity = next;
63
79
  }
64
80
  const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
65
- db ??= new DatabaseSync(path, { readOnly: true });
81
+ if (!db) {
82
+ if (composed) {
83
+ const uri = pathToFileURL(path); uri.searchParams.set("mode", "ro");
84
+ owner.prepare("ATTACH DATABASE ? AS coordinator_source").run(uri.href);
85
+ db = { prepare: sql => owner.prepare(sourceSQL(sql)), get observationActive() { return snapshot; }, beginSnapshot: () => reader.beginSnapshot() };
86
+ } else db = new DatabaseSync(path, { readOnly: true });
87
+ }
66
88
  return `${identity}:${db.prepare("PRAGMA data_version").get().data_version}`;
67
89
  },
68
90
  connection(refresh = true) { if (refresh) this.revision(); return db; },
91
+ changes() { this.revision(); return inbox.receive(db, identity); },
92
+ acknowledgeChanges(batch, complete) { inbox.acknowledge(batch, complete); },
93
+ get changeMetrics() { return inbox.metrics; },
94
+ get snapshotActive() { return snapshot; },
69
95
 
70
96
  beginSnapshot() {
71
97
  this.revision();
72
98
  if (snapshot) throw new Error("Coordinator snapshot already open");
73
- db.exec("BEGIN");
99
+ const transaction = composed ? owner : db;
100
+ transaction.exec("BEGIN");
74
101
  snapshot = true;
75
102
  const release = () => {
76
103
  if (!snapshot) return;
77
- try { db.exec("ROLLBACK"); } finally { snapshot = false; }
104
+ try { transaction.exec("ROLLBACK"); } finally { snapshot = false; }
78
105
  };
79
106
  try {
80
107
  // Pin the WAL read view before recording its revision; other writers keep advancing.
81
108
  db.prepare("SELECT count(*) FROM sqlite_schema").get();
82
- return { revision: this.revision(), release };
109
+ return { revision: this.revision(), release, commit: () => {
110
+ if (!snapshot) return;
111
+ transaction.exec("COMMIT");
112
+ snapshot = false;
113
+ } };
83
114
  } catch (error) { release(); throw error; }
84
115
  },
85
116
 
@@ -94,30 +125,6 @@ export function createAssignmentReader(path) {
94
125
  return { verified: false, waits: [], reason: "Coordinator state is unverified; compatible supervision is unavailable." };
95
126
  }
96
127
  },
97
- conversationRevisions() {
98
- try {
99
- this.revision();
100
- if (!["1", "2", "3", "4"].includes(db.prepare("SELECT value FROM schema_meta WHERE key = 'schema_version'").get()?.value)) return undefined;
101
- const hashes = new Map();
102
- const add = (sessionId, workspace, value) => {
103
- const key = JSON.stringify([sessionId, workspace]);
104
- if (!hashes.has(key)) hashes.set(key, createHash("sha256"));
105
- hashes.get(key).update(JSON.stringify(value));
106
- };
107
- // One source pass per changed database revision, instead of one
108
- // projection/query/log parse for every historical attempt.
109
- for (const row of db.prepare(`SELECT w.*, (SELECT json_group_array(attempt_id)
110
- FROM resume_claims c WHERE c.wait_id = w.wait_id AND c.generation = w.generation) AS claimed_attempts
111
- FROM waits w WHERE owner_kind = 'worker-conversation' ORDER BY wait_id, generation`).all()) {
112
- add(row.owner_session_id, row.owner_workspace, row);
113
- }
114
- for (const row of db.prepare("SELECT record_json FROM assignment_outcomes ORDER BY assignment_id").all()) {
115
- const record = JSON.parse(row.record_json);
116
- add(record.owner.sessionId, record.owner.workspace, record);
117
- }
118
- return new Map([...hashes].map(([key, hash]) => [key, hash.digest("hex")]));
119
- } catch { return undefined; }
120
- },
121
128
  upgradeObligations() {
122
129
  try { this.revision(); } catch (error) {
123
130
  if (error.code === "ENOENT") return [];
@@ -144,7 +151,8 @@ export function createAssignmentReader(path) {
144
151
  return [...obligations, ...reasons];
145
152
  },
146
153
 
147
- close() { if (snapshot) { db.exec("ROLLBACK"); snapshot = false; } db?.close(); db = undefined; statements.clear(); identity = undefined; },
154
+ close() { if (snapshot) { (composed ? owner : db).exec("ROLLBACK"); snapshot = false; } dropSource(); identity = undefined; inbox.close(); },
148
155
 
149
156
  };
157
+ return reader;
150
158
  }
@@ -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
  }
@@ -12,6 +12,9 @@ export interface BackgroundRequest {
12
12
  token: string;
13
13
  }>;
14
14
  result?: unknown;
15
+ acceptedAt?: number;
16
+ lastProgressAt?: number;
17
+ writerFence?: { instance: string; pid: number; start: string };
15
18
  }
16
19
  const prefix = 'background-request-v1:';
17
20
  // A partial index excludes returned history. CASE protects other coordinator
@@ -36,7 +39,7 @@ export class BackgroundRequests {
36
39
  private write(value: BackgroundRequest) {
37
40
  this.context.db.prepare('INSERT OR REPLACE INTO coordinator_state (key,value) VALUES (?,?)').run(storageKey(value.owner, value.key), JSON.stringify(value));
38
41
  }
39
- accept(owner: string, key: string, digest: string) {
42
+ accept(owner: string, key: string, digest: string, writerFence?: BackgroundRequest['writerFence']) {
40
43
  this.alive();
41
44
  return this.context.transaction(() => {
42
45
  const prior = this.read(owner, key);
@@ -45,7 +48,7 @@ export class BackgroundRequests {
45
48
  throw new Error('request-conflict: Background request key changed content');
46
49
  return { prior: true, record: prior };
47
50
  }
48
- const record: BackgroundRequest = { owner, key, digest, state: 'accepted', operations: [] };
51
+ const record: BackgroundRequest = { owner, key, digest, state: 'accepted', operations: [], acceptedAt: Date.now(), lastProgressAt: Date.now(), writerFence };
49
52
  this.write(record);
50
53
  return { prior: false, record };
51
54
  });
@@ -65,7 +68,15 @@ export class BackgroundRequests {
65
68
  private update(owner: string, key: string, change: (value: BackgroundRequest) => void) {
66
69
  this.alive();
67
70
  this.context.transaction(() => { const value = this.read(owner, key); if (!value)
68
- throw new Error('Background request not admitted'); change(value); this.write(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' }));
69
80
  }
70
81
  hasPending(): boolean {
71
82
  this.alive();
@@ -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
@@ -57,6 +57,15 @@ const BACKGROUND_CALLBACK_DDL = [
57
57
  FROM operations WHERE owner_kind='parent-session' AND observer_kind='local-supervisor'`,
58
58
  ];
59
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
+
60
69
  const DDL: readonly string[] = [
61
70
  `CREATE TABLE task_cancellation_authorities (
62
71
  credential_hash TEXT PRIMARY KEY,
@@ -93,6 +102,7 @@ const DDL: readonly string[] = [
93
102
  owner_workspace TEXT NOT NULL,
94
103
  owner_branch_id TEXT,
95
104
  owner_goal_id TEXT,
105
+ ${ASSIGNMENT_ATTEMPT_COLUMN},
96
106
  observer_kind TEXT NOT NULL,
97
107
  observer_version TEXT NOT NULL,
98
108
  supervision_json TEXT,
@@ -115,6 +125,7 @@ const DDL: readonly string[] = [
115
125
  `CREATE INDEX operations_owner ON operations (owner_kind, owner_session_id)`,
116
126
  `CREATE INDEX operations_phase ON operations (phase)`,
117
127
  `CREATE INDEX operations_running_supervisor ON operations (phase, supervision_host_id)`,
128
+ ASSIGNMENT_CLEANUP_INDEX,
118
129
  // Discovery leadership is separate from per-operation supervision. The token
119
130
  // fences stale acquisition and release; the host id is checked with process
120
131
  // identity before a replacement.
@@ -268,10 +279,7 @@ const DDL: readonly string[] = [
268
279
  owner_json TEXT NOT NULL,
269
280
  recipient_json TEXT NOT NULL
270
281
  )`,
271
- `CREATE TABLE assignment_attempts (
272
- attempt_id TEXT PRIMARY KEY,
273
- assignment_id TEXT NOT NULL REFERENCES assignment_bindings (assignment_id)
274
- )`,
282
+ ASSIGNMENT_ATTEMPTS_DDL,
275
283
  `CREATE TABLE assignment_outcome_waits (
276
284
  assignment_id TEXT NOT NULL REFERENCES assignment_outcomes (assignment_id),
277
285
  wait_id TEXT NOT NULL,
@@ -333,34 +341,42 @@ export function ensureSchema(ctx: StoreContext): void {
333
341
  );
334
342
  }
335
343
  if (recorded < SCHEMA_VERSION) {
336
- if (recorded === 3) {
337
- ctx.transaction(() => {
338
- ensureAdditiveSchema(ctx);
339
- ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE TABLE assignment_repairs"))!);
340
- run(ctx, "UPDATE schema_meta SET value = ? WHERE key = ?", String(SCHEMA_VERSION), SCHEMA_VERSION_KEY);
341
- });
342
- return;
343
- }
344
- 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
+ }
345
351
  ensureAdditiveSchema(ctx);
346
- ctx.transaction(() => {
352
+ if (recorded <= 2) {
347
353
  if (recorded === 1) ctx.db.exec("ALTER TABLE outbox_events ADD COLUMN event_type TEXT NOT NULL DEFAULT 'dependency-ready'");
348
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"));
349
355
  ctx.db.exec("ALTER TABLE waits ADD COLUMN dispatch_disarmed INTEGER NOT NULL DEFAULT 0");
350
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)");
351
357
  ctx.db.exec("DROP INDEX waits_one_pending_per_owner");
352
358
  ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE UNIQUE INDEX waits_one_pending_per_owner"))!);
353
- run(ctx, "UPDATE schema_meta SET value = ? WHERE key = ?", String(SCHEMA_VERSION), SCHEMA_VERSION_KEY);
354
- });
355
- return;
356
- }
357
- throw new StoreError(
358
- "schema-version",
359
- `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.`,
360
- );
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;
361
366
  }
362
367
  ensureAdditiveSchema(ctx);
363
- 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
+ });
364
380
  }
365
381
 
366
382
  /**