pi-better-background-tasks 0.15.4 → 0.17.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 (42) hide show
  1. package/README.md +22 -0
  2. package/package.json +5 -2
  3. package/runtime-client/artifacts/darwin-arm64.gz +0 -0
  4. package/runtime-client/artifacts/darwin-arm64.json +1 -0
  5. package/runtime-client/artifacts/darwin-x64.gz +0 -0
  6. package/runtime-client/artifacts/darwin-x64.json +1 -0
  7. package/runtime-client/artifacts/linux-arm64.gz +0 -0
  8. package/runtime-client/artifacts/linux-arm64.json +1 -0
  9. package/runtime-client/artifacts/linux-x64.gz +0 -0
  10. package/runtime-client/artifacts/linux-x64.json +1 -0
  11. package/runtime-client/scripts/private-runtime/format.mjs +90 -0
  12. package/runtime-client/src/daemon-owner.mjs +218 -0
  13. package/runtime-client/src/runtime/client.mjs +130 -0
  14. package/runtime-client/src/runtime/root.mjs +41 -0
  15. package/runtime-client/src/runtime/socket.mjs +9 -0
  16. package/runtime-client/src/runtime/status-cli.mjs +14 -0
  17. package/runtime-client/src/runtime/work-client.mjs +102 -0
  18. package/runtime-client/src/startup/artifact.mjs +76 -0
  19. package/runtime-client/src/startup/install.mjs +184 -0
  20. package/runtime-client/src/startup/managed-types.mjs +1 -0
  21. package/runtime-client/src/startup/runtime.mjs +120 -0
  22. package/src/goal-provider.ts +11 -7
  23. package/src/index.ts +4 -0
  24. package/src/observed-waits.ts +255 -37
  25. package/src/output.ts +16 -13
  26. package/src/registry.ts +15 -0
  27. package/src/shared-harness-settings.ts +4 -2
  28. package/src/shared-log-utils.ts +18 -7
  29. package/src/shared-navigator.ts +16 -4
  30. package/src/shared-operation-coordinator/assignment-observation.mjs +80 -3
  31. package/src/shared-operation-coordinator/index.ts +2 -0
  32. package/src/shared-operation-coordinator/src/discovery.ts +9 -0
  33. package/src/shared-operation-coordinator/src/errors.ts +2 -0
  34. package/src/shared-operation-coordinator/src/operations.ts +6 -4
  35. package/src/shared-operation-coordinator/src/result-supervision.ts +128 -0
  36. package/src/shared-operation-coordinator/src/schema.ts +39 -1
  37. package/src/shared-operation-coordinator/src/store.ts +55 -0
  38. package/src/shared-operation-coordinator/src/task-cancellation.ts +224 -0
  39. package/src/shared-operation-coordinator/src/types.ts +6 -0
  40. package/src/shared-work-client.mjs +102 -0
  41. package/src/tools.ts +87 -59
  42. package/src/work-observation.ts +117 -0
@@ -1124,10 +1124,12 @@ export function sessionScopeKey(input: {
1124
1124
  origin?: ScopeOrigin;
1125
1125
  /** Key when there is no origin at all (for example, a per-process scope). */
1126
1126
  fallback?: string;
1127
+ /** Sessionless ownership may be limited to the process that launched work. */
1128
+ processId?: number;
1127
1129
  }): string {
1128
1130
  if (input.all) return "all";
1129
1131
  if (input.unavailable) return "session:unavailable";
1130
- if (input.origin) return `session:${originScopeDigest(input.origin)}`;
1132
+ if (input.origin) return `session:${originScopeDigest(input.origin)}${!input.origin.sessionId && input.processId !== undefined ? `:process:${input.processId}` : ""}`;
1131
1133
  return input.fallback ?? "none";
1132
1134
  }
1133
1135
 
@@ -1176,6 +1178,8 @@ export interface RowPageRequest<T> {
1176
1178
  maxBytes: number;
1177
1179
  keyOf: (item: T) => RowKey;
1178
1180
  render: (item: T) => string;
1181
+ /** Global counts when the items were selected by an indexed keyset query. */
1182
+ indexed?: { total: number; before: number };
1179
1183
  }
1180
1184
 
1181
1185
  export interface RowPage extends VerbatimPage {
@@ -1208,6 +1212,12 @@ export function isRowCursor(cursor: string | undefined): boolean {
1208
1212
  return decodeRowCursor(cursor) !== undefined;
1209
1213
  }
1210
1214
 
1215
+ /** Resolve a list anchor only in the scope/filter that issued it. */
1216
+ export function rowCursorKey(cursor: string | undefined, resource: string): RowKey | undefined {
1217
+ const parsed = decodeRowCursor(cursor);
1218
+ return parsed?.r === resourceTag(resource) && Number.isFinite(parsed.t) ? { time: parsed.t, id: parsed.i } : undefined;
1219
+ }
1220
+
1211
1221
  /** Sorts before every real row: a cursor anchored here starts at the first row. */
1212
1222
  const HEAD_ROW_KEY: RowKey = { time: Number.MAX_SAFE_INTEGER, id: "" };
1213
1223
 
@@ -1235,7 +1245,7 @@ function clipRow(row: string, maxBytes: number): string {
1235
1245
  export function pageRows<T>(items: readonly T[], request: RowPageRequest<T>): RowPage {
1236
1246
  const keyed = items.map((item) => ({ item, key: request.keyOf(item) }))
1237
1247
  .sort((a, b) => rowOrder(a.key, b.key));
1238
- const total = keyed.length;
1248
+ const total = request.indexed?.total ?? keyed.length;
1239
1249
  const limit = Math.max(1, Math.floor(request.limit));
1240
1250
  const maxBytes = Math.max(0, Math.floor(request.maxBytes));
1241
1251
  let start = 0;
@@ -1248,14 +1258,14 @@ export function pageRows<T>(items: readonly T[], request: RowPageRequest<T>): Ro
1248
1258
  } else {
1249
1259
  const anchor: RowKey = { time: parsed.t, id: parsed.i };
1250
1260
  start = keyed.findIndex((row) => rowOrder(row.key, anchor) > 0);
1251
- if (start < 0) start = total;
1261
+ if (start < 0) start = keyed.length;
1252
1262
  }
1253
1263
  }
1254
1264
  const lines: string[] = [];
1255
1265
  let used = 0;
1256
1266
  let clippedRows = 0;
1257
1267
  let index = start;
1258
- for (; index < total && lines.length < limit; index += 1) {
1268
+ for (; index < keyed.length && lines.length < limit; index += 1) {
1259
1269
  const row = request.render(keyed[index]!.item);
1260
1270
  const sep = lines.length ? 1 : 0;
1261
1271
  const size = utf8ByteLength(row);
@@ -1276,11 +1286,12 @@ export function pageRows<T>(items: readonly T[], request: RowPageRequest<T>): Ro
1276
1286
  break;
1277
1287
  }
1278
1288
  const shown = lines.length;
1279
- const remaining = Math.max(0, total - index);
1289
+ const before = request.indexed?.before ?? start;
1290
+ const remaining = Math.max(0, total - before - lines.length);
1280
1291
  const current = request.cursor && !reset ? request.cursor : undefined;
1281
1292
  // The next page starts after the last row shown, or — when no row fit —
1282
1293
  // at this page's own start, so a caller can always retry with a larger page.
1283
- const anchor = shown > 0 ? keyed[index - 1]!.key : start > 0 ? keyed[start - 1]!.key : HEAD_ROW_KEY;
1294
+ const anchor = shown > 0 ? keyed[index - 1]!.key : rowCursorKey(current, request.resource) ?? (start > 0 ? keyed[start - 1]!.key : HEAD_ROW_KEY);
1284
1295
  const nextCursor = remaining > 0
1285
1296
  ? encodeRowCursor({ k: "l", r: resource, t: anchor.time, i: anchor.id })
1286
1297
  : undefined;
@@ -1295,7 +1306,7 @@ export function pageRows<T>(items: readonly T[], request: RowPageRequest<T>): Ro
1295
1306
  gaps: [],
1296
1307
  shown,
1297
1308
  total,
1298
- before: start,
1309
+ before,
1299
1310
  remaining,
1300
1311
  clippedRows,
1301
1312
  };
@@ -111,7 +111,7 @@ type NavigatorState = {
111
111
  detailOverlayRows?: number;
112
112
  dispose?: () => void;
113
113
  /** The mounted detail overlay, reused instead of stacking a second one. */
114
- overlay?: { showDetail(navigatorId: string): void; focus(): void };
114
+ overlay?: { showDetail(navigatorId: string): void; refreshDetail(): void; focus(): void };
115
115
  };
116
116
 
117
117
  const GLOBAL_KEY = Symbol.for("pi-better-harness.navigator.state");
@@ -262,6 +262,7 @@ export function refreshBackgroundWorkNavigator(ctx?: ExtensionContext): void {
262
262
  if (!isNavigatorUiAvailable(activeCtx)) return;
263
263
  try {
264
264
  refreshMainListWidget();
265
+ s.overlay?.refreshDetail();
265
266
  } catch { /* ignore */ }
266
267
  }
267
268
 
@@ -954,6 +955,7 @@ function openNavigator(): void {
954
955
  }, selectedId);
955
956
  overlayRef = {
956
957
  showDetail: (navigatorId) => component.showDetail(navigatorId),
958
+ refreshDetail: () => component.refreshDetail(),
957
959
  focus: () => {
958
960
  if (s.overlay !== overlayRef) return;
959
961
  try { handle?.focus?.(); } catch { /* ignore */ }
@@ -1030,9 +1032,9 @@ function createOverlayComponent(
1030
1032
  startDetailTimer();
1031
1033
  });
1032
1034
 
1033
- function refreshRows(): void {
1035
+ function refreshRows(rows = listRows()): void {
1034
1036
  const selectedId = state().mainListSelectedId ?? overlayState.rows[overlayState.selected]?.navigatorId;
1035
- overlayState.rows = listRows();
1037
+ overlayState.rows = rows;
1036
1038
  const nextIdx = selectedId ? overlayState.rows.findIndex((row) => row.navigatorId === selectedId) : -1;
1037
1039
  overlayState.selected = nextIdx >= 0 ? nextIdx : Math.min(overlayState.selected, Math.max(0, overlayState.rows.length - 1));
1038
1040
  }
@@ -1160,7 +1162,8 @@ function createOverlayComponent(
1160
1162
  return {
1161
1163
  render(width: number) {
1162
1164
  closeIfEditorReplaced();
1163
- refreshRows();
1165
+ // The main-list refresh owns provider I/O; streaming paints reuse its snapshot.
1166
+ refreshRows(state().mainListRows ?? []);
1164
1167
  const rail = buildMainListLayout(overlayState.rows, width, deps.truncate, fg, {
1165
1168
  selectedId: selectedRow()?.navigatorId,
1166
1169
  focused: true,
@@ -1260,6 +1263,15 @@ function createOverlayComponent(
1260
1263
  backToMain();
1261
1264
  }
1262
1265
  },
1266
+ /** Observation arrival updates this row without resetting selection or folded sections. */
1267
+ refreshDetail() {
1268
+ if (closed) return;
1269
+ const wasLoading = detail?.status === "rebuilding";
1270
+ detail = detailFor(detailId, Date.now(), { logTailLines: logTailRows }) ?? detail;
1271
+ if (wasLoading) applyDefaultExpandedSections(detail, expandedSections);
1272
+ startDetailTimer();
1273
+ requestRender();
1274
+ },
1263
1275
  /** Show another row's detail in this overlay (the main list moved while it was unfocused). */
1264
1276
  showDetail(navigatorId: string) {
1265
1277
  if (closed) return;
@@ -1,12 +1,13 @@
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
4
 
4
5
  /** Read-only, bounded projection input. Never creates/migrates a database. */
5
- export function readAssignmentWaits(path, owner) {
6
+ export function readAssignmentWaits(path, owner, connection) {
6
7
  let db;
7
8
  try {
8
9
  const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
9
- db = new DatabaseSync(path, { readOnly: true });
10
+ db = connection ?? new DatabaseSync(path, { readOnly: true });
10
11
  // v4 adds repair accounting; the observed wait/outcome fields are unchanged.
11
12
  if (!["1", "2", "3", "4"].includes(db.prepare("SELECT value FROM schema_meta WHERE key = 'schema_version'").get()?.value)) {
12
13
  return { verified: false, waits: [], reason: "Unsupported coordinator schema; assignment state is unverified." };
@@ -38,6 +39,82 @@ export function readAssignmentWaits(path, owner) {
38
39
  } catch {
39
40
  return { verified: false, waits: [], reason: "Coordinator state is unverified; compatible supervision is unavailable." };
40
41
  } finally {
41
- db?.close();
42
+ if (!connection) db?.close();
42
43
  }
43
44
  }
45
+
46
+ /** A root read model owns this connection; ordinary observers remain one-shot. */
47
+ export function createAssignmentReader(path) {
48
+ let db;
49
+ let identity;
50
+ let snapshot = false;
51
+ const statements = new Map();
52
+ return {
53
+ revision() {
54
+ const { statSync } = createRequire(import.meta.url)("node:fs");
55
+ const stat = statSync(path, { bigint: true });
56
+ const next = `${stat.dev}:${stat.ino}`;
57
+ if (identity !== next) {
58
+ if (snapshot) throw new Error("Coordinator identity changed during observation");
59
+ db?.close();
60
+ db = undefined;
61
+ statements.clear();
62
+ identity = next;
63
+ }
64
+ const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
65
+ db ??= new DatabaseSync(path, { readOnly: true });
66
+ return `${identity}:${db.prepare("PRAGMA data_version").get().data_version}`;
67
+ },
68
+ beginSnapshot() {
69
+ this.revision();
70
+ if (snapshot) throw new Error("Coordinator snapshot already open");
71
+ db.exec("BEGIN");
72
+ snapshot = true;
73
+ const release = () => {
74
+ if (!snapshot) return;
75
+ try { db.exec("ROLLBACK"); } finally { snapshot = false; }
76
+ };
77
+ try {
78
+ // Pin the WAL read view before recording its revision; other writers keep advancing.
79
+ db.prepare("SELECT count(*) FROM sqlite_schema").get();
80
+ return { revision: this.revision(), release };
81
+ } catch (error) { release(); throw error; }
82
+ },
83
+ read(owner) {
84
+ try {
85
+ this.revision();
86
+ return readAssignmentWaits(path, owner, { prepare(sql) {
87
+ if (!statements.has(sql)) statements.set(sql, db.prepare(sql));
88
+ return statements.get(sql);
89
+ } });
90
+ } catch {
91
+ return { verified: false, waits: [], reason: "Coordinator state is unverified; compatible supervision is unavailable." };
92
+ }
93
+ },
94
+ conversationRevisions() {
95
+ try {
96
+ this.revision();
97
+ if (!["1", "2", "3", "4"].includes(db.prepare("SELECT value FROM schema_meta WHERE key = 'schema_version'").get()?.value)) return undefined;
98
+ const hashes = new Map();
99
+ const add = (sessionId, workspace, value) => {
100
+ const key = JSON.stringify([sessionId, workspace]);
101
+ if (!hashes.has(key)) hashes.set(key, createHash("sha256"));
102
+ hashes.get(key).update(JSON.stringify(value));
103
+ };
104
+ // One source pass per changed database revision, instead of one
105
+ // projection/query/log parse for every historical attempt.
106
+ for (const row of db.prepare(`SELECT w.*, (SELECT json_group_array(attempt_id)
107
+ FROM resume_claims c WHERE c.wait_id = w.wait_id AND c.generation = w.generation) AS claimed_attempts
108
+ FROM waits w WHERE owner_kind = 'worker-conversation' ORDER BY wait_id, generation`).all()) {
109
+ add(row.owner_session_id, row.owner_workspace, row);
110
+ }
111
+ for (const row of db.prepare("SELECT record_json FROM assignment_outcomes ORDER BY assignment_id").all()) {
112
+ const record = JSON.parse(row.record_json);
113
+ add(record.owner.sessionId, record.owner.workspace, record);
114
+ }
115
+ return new Map([...hashes].map(([key, hash]) => [key, hash.digest("hex")]));
116
+ } catch { return undefined; }
117
+ },
118
+ close() { if (snapshot) { db.exec("ROLLBACK"); snapshot = false; } db?.close(); db = undefined; statements.clear(); identity = undefined; },
119
+ };
120
+ }
@@ -45,6 +45,8 @@
45
45
  * to be durable.
46
46
  */
47
47
  export { SCHEMA_VERSION, TERMINAL_WAIT_PHASES } from "./src/types.ts";
48
+ export type { TaskCancellationIntent, TaskCancellationRequest } from "./src/task-cancellation.ts";
49
+ export { cancellationCredential } from "./src/task-cancellation.ts";
48
50
  export type { AssignmentOutcomeInput, AssignmentOutcomeRecord } from "./src/assignment-outcomes.ts";
49
51
  export type {
50
52
  AcknowledgeDisposition,
@@ -48,6 +48,14 @@ export function readDiscoveryClaim(ctx: StoreContext, scope: unknown): Discovery
48
48
  return readClaim(ctx, requireId("scope", scope));
49
49
  }
50
50
 
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 } {
53
+ scope = requireId("scope", scope);
54
+ const row = getRow(ctx, `SELECT d.*, EXISTS(SELECT 1 FROM coordinator_state WHERE key = ?) AS managed
55
+ 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) };
57
+ }
58
+
51
59
  export function tryClaimDiscovery(
52
60
  ctx: StoreContext,
53
61
  input: TryClaimDiscoveryInput,
@@ -62,6 +70,7 @@ export function tryClaimDiscovery(
62
70
  const expectedToken = input.expected === null ? null : requireId("expected.token", input.expected.token);
63
71
 
64
72
  return ctx.transaction(() => {
73
+ if (getRow(ctx, "SELECT value FROM coordinator_state WHERE key = ?", "result-scope-v1:" + scope)) return null;
65
74
  const current = readClaim(ctx, scope);
66
75
  if (input.expected === null) {
67
76
  if (current) return null;
@@ -21,6 +21,8 @@ export type StoreErrorCode =
21
21
  | "unknown-operation"
22
22
  /** An operation already exists with different immutable launch identity. */
23
23
  | "operation-conflict"
24
+ /** An idempotency key was reused with different request content. */
25
+ | "request-conflict"
24
26
  /** The background task id belongs to a different owner. */
25
27
  | "task-ownership"
26
28
  /** The caller is not the recorded owner of the record it wants to change. */
@@ -63,6 +63,8 @@ function normalizeSupervision(value: unknown): SupervisionIdentity | null {
63
63
  const supervision = value as Partial<SupervisionIdentity>;
64
64
  return {
65
65
  hostId: requireId("supervision.hostId", supervision.hostId),
66
+ ...(supervision.resultScope === undefined ? {} : { resultScope: requireId("supervision.resultScope", supervision.resultScope) }),
67
+ ...(supervision.resultAdapter === 1 ? { resultAdapter: 1 as const } : {}),
66
68
  runnerId: supervision.runnerId === undefined || supervision.runnerId === null
67
69
  ? null
68
70
  : requireId("supervision.runnerId", supervision.runnerId),
@@ -433,8 +435,8 @@ export function listOperations(
433
435
  params.push(requireId("taskId", filter.taskId));
434
436
  }
435
437
  const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
436
- return getRows(ctx, `SELECT * FROM operations ${where} ORDER BY created_at, operation_id`, ...params)
437
- .map(mapOperation);
438
+ return getRows(ctx, `SELECT *, EXISTS(SELECT 1 FROM coordinator_state s WHERE s.key = 'result-supervision-v1:' || operations.operation_id) AS result_managed FROM operations ${where} ORDER BY created_at, operation_id`, ...params)
439
+ .map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
438
440
  }
439
441
 
440
442
  /** Running operations assigned to one supervising host, using the phase/host index. */
@@ -444,9 +446,9 @@ export function listRunningSupervisedBy(
444
446
  ): OperationRecord[] {
445
447
  return getRows(
446
448
  ctx,
447
- "SELECT * FROM operations WHERE phase = 'running' AND supervision_host_id = ? ORDER BY created_at, operation_id",
449
+ "SELECT *, EXISTS(SELECT 1 FROM coordinator_state s WHERE s.key = 'result-supervision-v1:' || operations.operation_id) AS result_managed FROM operations WHERE phase = 'running' AND supervision_host_id = ? ORDER BY created_at, operation_id",
448
450
  requireId("hostId", hostId),
449
- ).map(mapOperation);
451
+ ).map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
450
452
  }
451
453
 
452
454
  function listOutboxForRevision(
@@ -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,7 +18,33 @@ 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
+
21
33
  const DDL: readonly string[] = [
34
+ `CREATE TABLE task_cancellation_authorities (
35
+ credential_hash TEXT PRIMARY KEY,
36
+ request_json TEXT NOT NULL,
37
+ directory TEXT NOT NULL
38
+ )`,
39
+ `CREATE TABLE task_cancellation_requests (
40
+ owner_key TEXT NOT NULL,
41
+ request_key TEXT NOT NULL,
42
+ operation_id TEXT NOT NULL REFERENCES operations (operation_id),
43
+ intent_json TEXT NOT NULL,
44
+ result_json TEXT,
45
+ state TEXT NOT NULL CHECK (state IN ('accepted', 'stop-requested')),
46
+ PRIMARY KEY (owner_key, request_key)
47
+ )`,
22
48
  `CREATE TABLE assignment_repairs (
23
49
  fault_key TEXT PRIMARY KEY,
24
50
  assignment_id TEXT NOT NULL,
@@ -224,6 +250,7 @@ const DDL: readonly string[] = [
224
250
  generation INTEGER NOT NULL,
225
251
  PRIMARY KEY (wait_id, generation)
226
252
  )`,
253
+ RESULT_ADMISSION_FENCE,
227
254
  ];
228
255
 
229
256
  const SCHEMA_VERSION_KEY = "schema_version";
@@ -280,6 +307,7 @@ export function ensureSchema(ctx: StoreContext): void {
280
307
  if (recorded < SCHEMA_VERSION) {
281
308
  if (recorded === 3) {
282
309
  ctx.transaction(() => {
310
+ ensureAdditiveSchema(ctx);
283
311
  ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE TABLE assignment_repairs"))!);
284
312
  run(ctx, "UPDATE schema_meta SET value = ? WHERE key = ?", String(SCHEMA_VERSION), SCHEMA_VERSION_KEY);
285
313
  });
@@ -323,9 +351,18 @@ function ensureAdditiveSchema(ctx: StoreContext): void {
323
351
  && hasIndex()
324
352
  && hasTable("discovery_claims")
325
353
  && hasTable("coordinator_state")
326
- ) return;
354
+ && hasTable("task_cancellation_requests")
355
+ && hasTable("task_cancellation_authorities")
356
+ && getRows(ctx, "PRAGMA table_info(task_cancellation_requests)").some(row => row.name === "result_json")
357
+ ) {
358
+ ctx.db.exec(RESULT_ADMISSION_FENCE);
359
+ return;
360
+ }
327
361
 
328
362
  ctx.transaction(() => {
363
+ ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE TABLE task_cancellation_requests"))!.replace("CREATE TABLE", "CREATE TABLE IF NOT EXISTS"));
364
+ if (!getRows(ctx, "PRAGMA table_info(task_cancellation_requests)").some(row => row.name === "result_json")) ctx.db.exec("ALTER TABLE task_cancellation_requests ADD COLUMN result_json TEXT");
365
+ ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE TABLE task_cancellation_authorities"))!.replace("CREATE TABLE", "CREATE TABLE IF NOT EXISTS"));
329
366
  if (!hasColumn()) {
330
367
  ctx.db.exec("ALTER TABLE operations ADD COLUMN supervision_host_id TEXT");
331
368
  ctx.db.exec(`UPDATE operations
@@ -346,6 +383,7 @@ function ensureAdditiveSchema(ctx: StoreContext): void {
346
383
  key TEXT PRIMARY KEY,
347
384
  value TEXT NOT NULL
348
385
  )`);
386
+ ctx.db.exec(RESULT_ADMISSION_FENCE);
349
387
  });
350
388
  }
351
389
 
@@ -8,6 +8,9 @@
8
8
  * and leaves no partial record.
9
9
  */
10
10
  import { StoreError } from "./errors.ts";
11
+ import { resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.ts";
12
+ import { acceptTaskCancellation, getTaskCancellation, recordTaskStopRequested, admitTaskCancellation, authorizedTaskCancellation, finishTaskCancellation, cancellationRuntimeEpoch, acceptAuthorizedTaskCancellation, taskCancellationManaged, pendingTaskCancellations, finishTaskCancellationIntent, unknownTaskCancellation } from "./task-cancellation.ts";
13
+ import type { TaskCancellationIntent, TaskCancellationRequest } from "./task-cancellation.ts";
11
14
  import { repairFailedResume, type RepairResumeInput } from "./recovery.ts";
12
15
  import { recordAssignmentOutcome, getAssignmentOutcome, inspectAssignmentOutcome, consumeAssignmentOutcome, registerAssignment, receiptAssignmentOutcome } from "./assignment-outcomes.ts";
13
16
  import type { AssignmentOutcomeInput, AssignmentOutcomeRecord } from "./assignment-outcomes.ts";
@@ -32,6 +35,7 @@ import {
32
35
  import {
33
36
  getChangeRevision as readChangeRevision,
34
37
  readDiscoveryClaim as readClaim,
38
+ readDiscoveryState,
35
39
  releaseDiscoveryClaim as deleteDiscoveryClaim,
36
40
  tryClaimDiscovery as writeDiscoveryClaim,
37
41
  } from "./discovery.ts";
@@ -116,6 +120,26 @@ import {
116
120
  } from "./types.ts";
117
121
 
118
122
  export interface Store {
123
+ resultScopeManaged(scope: string): boolean;
124
+ handoffResultScope(input: Parameters<typeof handoffResultScope>[1]): ReturnType<typeof handoffResultScope>;
125
+ resultSupervision(operationId: string): ReturnType<typeof resultSupervision>;
126
+ resultSupervisions(activeOnly?: boolean): ReturnType<typeof resultSupervisions>;
127
+ handoffResultSupervision(input: Parameters<typeof handoffResultSupervision>[1]): ReturnType<typeof handoffResultSupervision>;
128
+ handoffResultSupervisions(input: Parameters<typeof handoffResultSupervisions>[1]): ReturnType<typeof handoffResultSupervisions>;
129
+ recoverResultSupervision(input: Parameters<typeof recoverResultSupervision>[1]): void;
130
+ publishSupervisedResult(input: Parameters<typeof publishSupervisedResult>[1]): ReturnType<typeof publishSupervisedResult>;
131
+ unknownTaskCancellation(input: TaskCancellationRequest): TaskCancellationIntent;
132
+ taskCancellationManaged(operationId: string): boolean;
133
+ pendingTaskCancellations(): ReturnType<typeof pendingTaskCancellations>;
134
+ finishTaskCancellationIntent(input: Parameters<typeof finishTaskCancellationIntent>[1]): TaskCancellationIntent;
135
+ cancellationRuntimeEpoch(instanceId?: string): number;
136
+ acceptAuthorizedTaskCancellation(input: { credential: string; runtimeEpoch: number }): TaskCancellationIntent;
137
+ admitTaskCancellation(input: Parameters<typeof admitTaskCancellation>[1]): void;
138
+ authorizedTaskCancellation(credential: string): ReturnType<typeof authorizedTaskCancellation>;
139
+ finishTaskCancellation(input: Parameters<typeof finishTaskCancellation>[1]): TaskCancellationIntent;
140
+ acceptTaskCancellation(input: TaskCancellationRequest): TaskCancellationIntent;
141
+ getTaskCancellation(input: { owner: OwnerIdentity; idempotencyKey: string }): TaskCancellationIntent | null;
142
+ recordTaskStopRequested(input: TaskCancellationRequest): TaskCancellationIntent;
119
143
  registerAssignment(input: Parameters<typeof registerAssignment>[1]): void;
120
144
  receiptAssignmentOutcome(input: Parameters<typeof receiptAssignmentOutcome>[1]): AssignmentOutcomeRecord;
121
145
  recordAssignmentOutcome(input: AssignmentOutcomeInput): AssignmentOutcomeRecord;
@@ -169,6 +193,7 @@ export interface Store {
169
193
 
170
194
  /** The shared discovery leader for this store/supervisor scope, if recorded. */
171
195
  readDiscoveryClaim(scope: string): DiscoveryClaimRecord | null;
196
+ readDiscoveryState(scope: string): ReturnType<typeof readDiscoveryState>;
172
197
  /**
173
198
  * Compare-and-swap a discovery claim. The caller must name the exact claim it
174
199
  * observed, or null for none; a stale contender receives null and must not
@@ -311,6 +336,23 @@ export function openStore(options: StoreOptions): Store {
311
336
  };
312
337
 
313
338
  const store: Store = {
339
+ resultScopeManaged(scope) { alive(); return resultScopeManaged(ctx, scope); },
340
+ handoffResultScope(input) { alive(); return handoffResultScope(ctx, input); },
341
+ resultSupervision(id) { alive(); return resultSupervision(ctx, id); },
342
+ resultSupervisions(activeOnly) { alive(); return resultSupervisions(ctx, activeOnly); },
343
+ handoffResultSupervision(input) { alive(); return handoffResultSupervision(ctx, input); },
344
+ handoffResultSupervisions(input) { alive(); return handoffResultSupervisions(ctx, input); },
345
+ recoverResultSupervision(input) { alive(); recoverResultSupervision(ctx, input); },
346
+ publishSupervisedResult(input) { alive(); return publishSupervisedResult(ctx, input); },
347
+ unknownTaskCancellation(input) { alive(); return unknownTaskCancellation(ctx, input); },
348
+ taskCancellationManaged(operationId) { alive(); return taskCancellationManaged(ctx, operationId); },
349
+ pendingTaskCancellations() { alive(); return pendingTaskCancellations(ctx); },
350
+ finishTaskCancellationIntent(input) { alive(); return finishTaskCancellationIntent(ctx, input); },
351
+ cancellationRuntimeEpoch(instanceId) { alive(); return cancellationRuntimeEpoch(ctx, instanceId); },
352
+ acceptAuthorizedTaskCancellation(input) { alive(); return acceptAuthorizedTaskCancellation(ctx, input); },
353
+ admitTaskCancellation(input) { alive(); admitTaskCancellation(ctx, input); },
354
+ authorizedTaskCancellation(credential) { alive(); return authorizedTaskCancellation(ctx, credential); },
355
+ finishTaskCancellation(input) { alive(); return finishTaskCancellation(ctx, input); },
314
356
  registerAssignment(input) { alive(); registerAssignment(ctx, input); },
315
357
  receiptAssignmentOutcome(input) { alive(); return receiptAssignmentOutcome(ctx, input); },
316
358
  recordAssignmentOutcome(input) { alive(); return recordAssignmentOutcome(ctx, input); },
@@ -360,6 +402,7 @@ export function openStore(options: StoreOptions): Store {
360
402
  terminalRevision === undefined ? undefined : requireCounter("terminalRevision", terminalRevision),
361
403
  );
362
404
  },
405
+ readDiscoveryState(scope) { alive(); return readDiscoveryState(ctx, scope); },
363
406
  readDiscoveryClaim(scope) {
364
407
  alive();
365
408
  return readClaim(ctx, scope);
@@ -380,6 +423,18 @@ export function openStore(options: StoreOptions): Store {
380
423
  alive();
381
424
  return writeWait(ctx, input);
382
425
  },
426
+ acceptTaskCancellation(input) {
427
+ alive();
428
+ return acceptTaskCancellation(ctx, input);
429
+ },
430
+ getTaskCancellation(input) {
431
+ alive();
432
+ return getTaskCancellation(ctx, input);
433
+ },
434
+ recordTaskStopRequested(input) {
435
+ alive();
436
+ return recordTaskStopRequested(ctx, input);
437
+ },
383
438
  transitionWaitPhase(input) {
384
439
  alive();
385
440
  return writePhase(ctx, input);