pi-better-server 0.2.4 → 0.4.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 (109) hide show
  1. package/package.json +6 -3
  2. package/scripts/measure-shared-reads/daemon.mjs +7 -0
  3. package/scripts/measure-shared-reads/probe.mjs +10 -0
  4. package/scripts/measure-shared-reads.mjs +165 -0
  5. package/scripts/test-on-pi.sh +21 -3
  6. package/src/cli.ts +39 -2
  7. package/src/client.ts +9 -4
  8. package/src/daemon-owner.ts +48 -6
  9. package/src/handshake.ts +8 -7
  10. package/src/lifecycle-config.ts +4 -0
  11. package/src/paths.ts +1 -11
  12. package/src/protocol.ts +7 -0
  13. package/src/registry.ts +2 -1
  14. package/src/runtime/background-history.ts +241 -0
  15. package/src/runtime/background.ts +182 -0
  16. package/src/runtime/cancellation.ts +99 -0
  17. package/src/runtime/catalog-admission.ts +50 -0
  18. package/src/runtime/catalog.ts +133 -0
  19. package/src/runtime/client.ts +111 -0
  20. package/src/runtime/domain/assignment-observation.d.mts +1 -0
  21. package/src/runtime/domain/assignment-observation.mjs +120 -0
  22. package/src/runtime/domain/assignment-projection.d.mts +1 -0
  23. package/src/runtime/domain/assignment-projection.mjs +245 -0
  24. package/src/runtime/domain/background/conditions.mjs +93 -0
  25. package/src/runtime/domain/background/process-identity.mjs +110 -0
  26. package/src/runtime/domain/background/process.mjs +511 -0
  27. package/src/runtime/domain/background/registry.mjs +374 -0
  28. package/src/runtime/domain/background/snapshot.mjs +73 -0
  29. package/src/runtime/domain/background/supervisor/identity.mjs +92 -0
  30. package/src/runtime/domain/background/supervisor/invocation.mjs +29 -0
  31. package/src/runtime/domain/background/supervisor/store.mjs +604 -0
  32. package/src/runtime/domain/background/supervisor/supervisor.mjs +720 -0
  33. package/src/runtime/domain/background/supervisor/types.mjs +47 -0
  34. package/src/runtime/domain/background/terminal-publication.mjs +58 -0
  35. package/src/runtime/domain/background/types.mjs +3 -0
  36. package/src/runtime/domain/catalog/agent-session-settings.d.mts +30 -0
  37. package/src/runtime/domain/catalog/agent-session-settings.mjs +112 -0
  38. package/src/runtime/domain/catalog/catalog-overlay.d.mts +3 -0
  39. package/src/runtime/domain/catalog/catalog-overlay.mjs +9 -0
  40. package/src/runtime/domain/catalog/catalog-preferences.d.mts +17 -0
  41. package/src/runtime/domain/catalog/catalog-preferences.mjs +164 -0
  42. package/src/runtime/domain/catalog/catalog-schema.d.mts +265 -0
  43. package/src/runtime/domain/catalog/catalog-schema.mjs +1331 -0
  44. package/src/runtime/domain/catalog/catalog-skill-edits.d.mts +42 -0
  45. package/src/runtime/domain/catalog/catalog-skill-edits.mjs +95 -0
  46. package/src/runtime/domain/catalog/catalog-store.d.mts +126 -0
  47. package/src/runtime/domain/catalog/catalog-store.mjs +810 -0
  48. package/src/runtime/domain/catalog/roles/role.architect.md +13 -0
  49. package/src/runtime/domain/catalog/roles/role.developer.md +16 -0
  50. package/src/runtime/domain/catalog/roles/role.explorer.md +13 -0
  51. package/src/runtime/domain/catalog/roles/role.product-manager.md +13 -0
  52. package/src/runtime/domain/catalog/roles/role.researcher.md +13 -0
  53. package/src/runtime/domain/catalog/roles/role.reviewer.md +13 -0
  54. package/src/runtime/domain/catalog/roles/role.writer.md +12 -0
  55. package/src/runtime/domain/catalog/thinking.d.mts +8 -0
  56. package/src/runtime/domain/catalog/thinking.mjs +22 -0
  57. package/src/runtime/domain/coordinator/index.mjs +50 -0
  58. package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +160 -0
  59. package/src/runtime/domain/coordinator/src/discovery.mjs +94 -0
  60. package/src/runtime/domain/coordinator/src/errors.mjs +12 -0
  61. package/src/runtime/domain/coordinator/src/operations.mjs +301 -0
  62. package/src/runtime/domain/coordinator/src/outbox.mjs +282 -0
  63. package/src/runtime/domain/coordinator/src/recovery.mjs +51 -0
  64. package/src/runtime/domain/coordinator/src/result-supervision.mjs +101 -0
  65. package/src/runtime/domain/coordinator/src/rows.mjs +277 -0
  66. package/src/runtime/domain/coordinator/src/schema.mjs +367 -0
  67. package/src/runtime/domain/coordinator/src/sqlite.mjs +193 -0
  68. package/src/runtime/domain/coordinator/src/store.mjs +245 -0
  69. package/src/runtime/domain/coordinator/src/task-cancellation.mjs +187 -0
  70. package/src/runtime/domain/coordinator/src/types.mjs +24 -0
  71. package/src/runtime/domain/coordinator/src/validate.mjs +233 -0
  72. package/src/runtime/domain/coordinator/src/waits.mjs +850 -0
  73. package/src/runtime/domain/health-observation.d.mts +3 -0
  74. package/src/runtime/domain/health-observation.mjs +613 -0
  75. package/src/runtime/domain/health-surface.mjs +279 -0
  76. package/src/runtime/domain/log-cursor.mjs +148 -0
  77. package/src/runtime/domain/log-paths.mjs +13 -0
  78. package/src/runtime/domain/parse.d.mts +2 -0
  79. package/src/runtime/domain/parse.mjs +1173 -0
  80. package/src/runtime/domain/process-status.d.mts +1 -0
  81. package/src/runtime/domain/process-status.mjs +25 -0
  82. package/src/runtime/domain/session-store.d.mts +2 -0
  83. package/src/runtime/domain/session-store.mjs +489 -0
  84. package/src/runtime/domain/shared-harness-settings.d.mts +1 -0
  85. package/src/runtime/domain/shared-harness-settings.mjs +126 -0
  86. package/src/runtime/domain/shared-log-utils.mjs +1223 -0
  87. package/src/runtime/domain/shared-stall-detector.mjs +37 -0
  88. package/src/runtime/domain/widget.d.mts +1 -0
  89. package/src/runtime/domain/widget.mjs +250 -0
  90. package/src/runtime/guardian.ts +189 -0
  91. package/src/runtime/health-config.ts +27 -0
  92. package/src/runtime/local-client.ts +34 -0
  93. package/src/runtime/mutation-store.ts +34 -0
  94. package/src/runtime/queries.ts +76 -0
  95. package/src/runtime/query-executor.ts +277 -0
  96. package/src/runtime/query-worker.mjs +119 -0
  97. package/src/runtime/read-model.ts +409 -0
  98. package/src/runtime/result-supervision.ts +63 -0
  99. package/src/runtime/root.ts +29 -0
  100. package/src/runtime/socket.ts +10 -0
  101. package/src/runtime/status-cli.ts +11 -0
  102. package/src/runtime/work-client.d.mts +14 -0
  103. package/src/runtime/work-client.mjs +102 -0
  104. package/src/server.ts +199 -14
  105. package/src/session-activity.ts +22 -2
  106. package/src/startup/activation.ts +32 -5
  107. package/src/startup/ensure.ts +13 -1
  108. package/src/startup/install.ts +2 -0
  109. package/src/version.ts +4 -0
@@ -0,0 +1,301 @@
1
+ // Generated canonical coordinator. Do not edit directly.
2
+ /**
3
+ * Operation registration, supervision updates and terminal outcomes.
4
+ *
5
+ * Launch identity is immutable. Registering the same launch twice is an
6
+ * idempotent replay; changing any of it is refused, because a store that
7
+ * rewrites an owner or a task binding cannot be used to prove who owns a wait.
8
+ *
9
+ * A terminal outcome is recorded once per operation (`terminalRevision` 1) with
10
+ * the supervisor's event id. A replay with the same event id returns the
11
+ * recorded revision without side effects; a different terminal event for the
12
+ * same operation is refused instead of overwriting the first evidence.
13
+ */
14
+ import { StoreError } from "./errors.mjs";
15
+ import { mapOperation, ownerFromRow, readOperation, requireOperation } from "./rows.mjs";
16
+ import { columnText, getRows, isUniqueViolation, run, } from "./sqlite.mjs";
17
+ import { describeOwnerDiff, normalizeOwner, optionalText, requireBoolean, requireEnum, requireEvidenceKind, requireId, requireObserver, requireOptionalCounter, requireText, sameOwner, } from "./validate.mjs";
18
+ import { mapOutbox } from "./rows.mjs";
19
+ import { settleWaitsForOperation } from "./waits.mjs";
20
+ import { bumpChangeRevision } from "./discovery.mjs";
21
+ const HEALTH_VALUES = ["active", "unmonitored", "lost"];
22
+ const OUTCOME_VALUES = ["succeeded", "failed", "cancelled", "lost"];
23
+ function normalizeSupervision(value) {
24
+ if (value === undefined || value === null)
25
+ return null;
26
+ if (typeof value !== "object" || Array.isArray(value)) {
27
+ throw new StoreError("validation", "Invalid supervision: must be an object");
28
+ }
29
+ const supervision = value;
30
+ return {
31
+ hostId: requireId("supervision.hostId", supervision.hostId),
32
+ ...(supervision.resultScope === undefined ? {} : { resultScope: requireId("supervision.resultScope", supervision.resultScope) }),
33
+ ...(supervision.resultAdapter === 1 ? { resultAdapter: 1 } : {}),
34
+ runnerId: supervision.runnerId === undefined || supervision.runnerId === null
35
+ ? null
36
+ : requireId("supervision.runnerId", supervision.runnerId),
37
+ processStartToken: supervision.processStartToken === undefined || supervision.processStartToken === null
38
+ ? null
39
+ : requireId("supervision.processStartToken", supervision.processStartToken),
40
+ };
41
+ }
42
+ function normalizeEvidence(value) {
43
+ if (value === undefined || value === null)
44
+ return [];
45
+ if (!Array.isArray(value)) {
46
+ throw new StoreError("validation", "Invalid evidence: must be an array");
47
+ }
48
+ return value.map((entry, index) => {
49
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
50
+ throw new StoreError("validation", `Invalid evidence[${index}]: must be an object`);
51
+ }
52
+ const item = entry;
53
+ const normalized = {
54
+ kind: requireEvidenceKind(`evidence[${index}].kind`, item.kind),
55
+ ref: requireText(`evidence[${index}].ref`, item.ref, 1024),
56
+ detailLost: item.detailLost === undefined ? false : requireBoolean(`evidence[${index}].detailLost`, item.detailLost),
57
+ };
58
+ const summary = optionalText(`evidence[${index}].summary`, item.summary, 2048);
59
+ if (summary !== null)
60
+ normalized.summary = summary;
61
+ const bytes = requireOptionalCounter(`evidence[${index}].bytes`, item.bytes);
62
+ if (bytes !== null)
63
+ normalized.bytes = bytes;
64
+ return normalized;
65
+ });
66
+ }
67
+ export function registerOperation(ctx, input) {
68
+ const operationId = requireId("operationId", input.operationId);
69
+ const taskId = requireId("taskId", input.taskId);
70
+ const launchToken = requireId("launchToken", input.launchToken);
71
+ const owner = normalizeOwner("owner", input.owner);
72
+ const observer = requireObserver("observer", input.observer);
73
+ const supervision = normalizeSupervision(input.supervision);
74
+ const authorityRef = optionalText("authorityRef", input.authorityRef, 512);
75
+ const intentRef = optionalText("intentRef", input.intentRef, 200);
76
+ const assertTaskAvailable = () => {
77
+ const byTask = getRows(ctx, "SELECT * FROM operations WHERE task_id = ?", taskId)[0];
78
+ if (!byTask)
79
+ return;
80
+ const existingOwner = ownerFromRow(byTask);
81
+ if (!sameOwner(existingOwner, owner)) {
82
+ throw new StoreError("task-ownership", `Background task ${taskId} is owned by another execution owner. A task id belongs to the launch that registered it; a different owner must not attach to it.`);
83
+ }
84
+ throw new StoreError("operation-conflict", `Background task ${taskId} is already bound to operation ${columnText(byTask, "operation_id")}. One durable operation exists per task launch; reconcile the recorded one instead of registering a second.`);
85
+ };
86
+ const assertLaunchIdentity = (existing) => {
87
+ const differences = [];
88
+ if (existing.taskId !== taskId)
89
+ differences.push("taskId");
90
+ if (existing.launchToken !== launchToken)
91
+ differences.push("launchToken");
92
+ if (!sameOwner(existing.owner, owner)) {
93
+ differences.push(`owner (${describeOwnerDiff(existing.owner, owner)})`);
94
+ }
95
+ if (existing.observer.kind !== observer.kind || existing.observer.version !== observer.version) {
96
+ differences.push("observer");
97
+ }
98
+ if (differences.length > 0) {
99
+ throw new StoreError("operation-conflict", `Operation ${operationId} is already registered with a different launch identity: ${differences.join(", ")}. Launch identity and ownership are immutable; register a new operation id for a new launch.`);
100
+ }
101
+ };
102
+ return ctx.transaction(() => {
103
+ const existing = readOperation(ctx, operationId);
104
+ if (existing) {
105
+ assertLaunchIdentity(existing);
106
+ return { operation: existing, created: false };
107
+ }
108
+ assertTaskAvailable();
109
+ const at = ctx.now();
110
+ try {
111
+ run(ctx, `INSERT INTO operations (
112
+ operation_id, task_id, launch_token,
113
+ owner_kind, owner_session_id, owner_workspace, owner_branch_id, owner_goal_id,
114
+ observer_kind, observer_version, supervision_json, supervision_host_id, authority_ref, intent_ref,
115
+ phase, health, health_reason, terminal_revision, created_at, updated_at
116
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'running', 'active', NULL, 0, ?, ?)`, operationId, taskId, launchToken, owner.kind, owner.sessionId, owner.workspace, owner.branchId ?? null, owner.goalId ?? null, observer.kind, observer.version, supervision ? JSON.stringify(supervision) : null, supervision?.hostId ?? null, authorityRef, intentRef, at, at);
117
+ }
118
+ catch (error) {
119
+ // Another process may have registered the same launch (or the same task)
120
+ // between the check above and this insert. Re-read and report the same
121
+ // typed outcome instead of leaking a raw constraint error.
122
+ if (!isUniqueViolation(error, "operations.task_id", "operations.operation_id"))
123
+ throw error;
124
+ const raced = readOperation(ctx, operationId);
125
+ if (raced) {
126
+ assertLaunchIdentity(raced);
127
+ return { operation: raced, created: false };
128
+ }
129
+ assertTaskAvailable();
130
+ throw error;
131
+ }
132
+ bumpChangeRevision(ctx);
133
+ return { operation: requireOperation(ctx, operationId), created: true };
134
+ });
135
+ }
136
+ /**
137
+ * Replace the supervision identity and/or observer health. A replacement host
138
+ * may take over observation; ownership and launch identity stay untouched.
139
+ */
140
+ export function recordSupervision(ctx, input) {
141
+ const operationId = requireId("operationId", input.operationId);
142
+ const owner = normalizeOwner("owner", input.owner);
143
+ const supervision = normalizeSupervision(input.supervision);
144
+ const expectedHostId = input.expectedHostId === undefined
145
+ ? undefined
146
+ : input.expectedHostId === null
147
+ ? null
148
+ : requireId("expectedHostId", input.expectedHostId);
149
+ const health = input.health === undefined
150
+ ? null
151
+ : requireEnum("health", input.health, HEALTH_VALUES);
152
+ const reason = optionalText("reason", input.reason, 1024);
153
+ if (health === null && supervision === null) {
154
+ throw new StoreError("validation", "Invalid supervision update: nothing to record");
155
+ }
156
+ if (supervision !== null && expectedHostId === undefined) {
157
+ throw new StoreError("validation", "Invalid expectedHostId: replacing supervision requires the observed current host id, or null when no supervisor was recorded.");
158
+ }
159
+ return ctx.transaction(() => {
160
+ const operation = requireOperation(ctx, operationId);
161
+ if (!sameOwner(operation.owner, owner)) {
162
+ throw new StoreError("foreign-owner", `Operation ${operationId} belongs to another execution owner (differs in ${describeOwnerDiff(operation.owner, owner)}).`);
163
+ }
164
+ if (expectedHostId !== undefined) {
165
+ const currentHostId = operation.supervision?.hostId ?? null;
166
+ if (currentHostId !== expectedHostId) {
167
+ throw new StoreError("supervision-conflict", `Operation ${operationId} is now supervised by ${currentHostId ?? "no host"}, not the observed ${expectedHostId ?? "no host"}; the stale replacement was refused.`);
168
+ }
169
+ }
170
+ const nextHealth = health ?? operation.health;
171
+ const nextReason = nextHealth === "active" ? null : (reason ?? operation.healthReason);
172
+ if (nextHealth !== "active" && nextReason === null) {
173
+ throw new StoreError("validation", "Invalid reason: observer health other than active requires a recorded reason");
174
+ }
175
+ const nextSupervision = supervision ?? operation.supervision;
176
+ const nextHostId = nextSupervision?.hostId ?? null;
177
+ const authorityChanged = (operation.supervision?.hostId ?? null) !== nextHostId;
178
+ run(ctx, "UPDATE operations SET supervision_json = ?, supervision_host_id = ?, health = ?, health_reason = ?, updated_at = ? WHERE operation_id = ?", nextSupervision ? JSON.stringify(nextSupervision) : null, nextHostId, nextHealth, nextReason, ctx.now(), operationId);
179
+ if (authorityChanged)
180
+ bumpChangeRevision(ctx);
181
+ return requireOperation(ctx, operationId);
182
+ });
183
+ }
184
+ /**
185
+ * Release a closed host's supervision authority without clearing a newer
186
+ * holder. The update is conditional on the exact recorded host, so a host that
187
+ * shut down while another process already took over cannot erase the takeover.
188
+ * A terminal operation keeps its final supervision record; only running work
189
+ * becomes explicitly unmonitored for the next host.
190
+ */
191
+ export function releaseSupervision(ctx, input) {
192
+ const operationId = requireId("operationId", input.operationId);
193
+ const owner = normalizeOwner("owner", input.owner);
194
+ const hostId = requireId("hostId", input.hostId);
195
+ const reason = optionalText("reason", input.reason, 1024)
196
+ ?? "the supervising host closed; another host may take over";
197
+ return ctx.transaction(() => {
198
+ const operation = requireOperation(ctx, operationId);
199
+ if (!sameOwner(operation.owner, owner)) {
200
+ throw new StoreError("foreign-owner", `Operation ${operationId} belongs to another execution owner (differs in ${describeOwnerDiff(operation.owner, owner)}).`);
201
+ }
202
+ if (operation.supervision?.hostId !== hostId)
203
+ return null;
204
+ if (operation.phase === "terminal")
205
+ return operation;
206
+ run(ctx, `UPDATE operations
207
+ SET supervision_json = NULL, supervision_host_id = NULL,
208
+ health = 'unmonitored', health_reason = ?, updated_at = ?
209
+ WHERE operation_id = ?`, reason, ctx.now(), operationId);
210
+ bumpChangeRevision(ctx);
211
+ return requireOperation(ctx, operationId);
212
+ });
213
+ }
214
+ export function recordTerminalOutcome(ctx, input) {
215
+ const operationId = requireId("operationId", input.operationId);
216
+ const eventId = requireId("eventId", input.eventId);
217
+ const outcome = requireEnum("outcome", input.outcome, OUTCOME_VALUES);
218
+ const owner = normalizeOwner("owner", input.owner);
219
+ const evidence = normalizeEvidence(input.evidence);
220
+ const reason = optionalText("reason", input.reason, 1024);
221
+ const detailLost = input.detailLost === undefined
222
+ ? outcome === "lost"
223
+ : requireBoolean("detailLost", input.detailLost);
224
+ return ctx.transaction(() => {
225
+ const operation = requireOperation(ctx, operationId);
226
+ if (!sameOwner(operation.owner, owner)) {
227
+ throw new StoreError("foreign-owner", `Operation ${operationId} belongs to another execution owner (differs in ${describeOwnerDiff(operation.owner, owner)}); a terminal outcome must be reported by or for its registered owner.`);
228
+ }
229
+ if (operation.phase === "terminal") {
230
+ if (operation.terminalEventId === eventId) {
231
+ return {
232
+ operation,
233
+ recorded: false,
234
+ outbox: listOutboxForRevision(ctx, operationId, operation.terminalRevision),
235
+ ready: [],
236
+ };
237
+ }
238
+ throw new StoreError("terminal-conflict", `Operation ${operationId} already recorded terminal event ${operation.terminalEventId} (${operation.terminalOutcome}). Event ${eventId} is a different terminal event and cannot replace it; a replayed event must reuse its original event id.`);
239
+ }
240
+ // A replay may omit evidence: the recorded revision already holds it. Only a
241
+ // new terminal revision must be interpretable on its own.
242
+ if (evidence.length === 0 && reason === null) {
243
+ throw new StoreError("validation", "Invalid reason: a terminal outcome without evidence must record why (for example lost supervision), so the result is interpretable.");
244
+ }
245
+ const at = ctx.now();
246
+ evidence.forEach((item, ordinal) => {
247
+ run(ctx, `INSERT INTO operation_evidence (
248
+ operation_id, terminal_revision, ordinal, kind, ref, summary, detail_lost, bytes, captured_at
249
+ ) VALUES (?, 1, ?, ?, ?, ?, ?, ?, ?)`, operationId, ordinal, item.kind, item.ref, item.summary ?? null, item.detailLost ? 1 : 0, item.bytes ?? null, at);
250
+ });
251
+ run(ctx, `UPDATE operations
252
+ SET phase = 'terminal', terminal_revision = 1, terminal_outcome = ?, terminal_event_id = ?,
253
+ terminal_detail_lost = ?, terminal_reason = ?, terminal_at = ?, updated_at = ?
254
+ WHERE operation_id = ?`, outcome, eventId, detailLost ? 1 : 0, reason, at, at, operationId);
255
+ bumpChangeRevision(ctx);
256
+ const settledOperation = requireOperation(ctx, operationId);
257
+ const settled = settleWaitsForOperation(ctx, settledOperation, at);
258
+ const outbox = listOutboxForRevision(ctx, operationId, 1);
259
+ return {
260
+ operation: settledOperation,
261
+ recorded: true,
262
+ outbox,
263
+ ready: settled.ready,
264
+ };
265
+ });
266
+ }
267
+ export function getOperation(ctx, operationId) {
268
+ return readOperation(ctx, operationId);
269
+ }
270
+ export function listOperations(ctx, filter = {}) {
271
+ const clauses = [];
272
+ const params = [];
273
+ if (filter.ownerScope) {
274
+ const owner = normalizeOwner("ownerScope", filter.ownerScope);
275
+ clauses.push("owner_kind = ? AND owner_session_id = ? AND owner_workspace = ?");
276
+ params.push(owner.kind, owner.sessionId, owner.workspace);
277
+ }
278
+ if (filter.owner) {
279
+ const owner = normalizeOwner("owner", filter.owner);
280
+ clauses.push("owner_kind = ? AND owner_session_id = ? AND owner_workspace = ? AND coalesce(owner_branch_id, '') = ? AND coalesce(owner_goal_id, '') = ?");
281
+ params.push(owner.kind, owner.sessionId, owner.workspace, owner.branchId ?? "", owner.goalId ?? "");
282
+ }
283
+ if (filter.phase !== undefined) {
284
+ clauses.push("phase = ?");
285
+ params.push(requireEnum("phase", filter.phase, ["running", "terminal"]));
286
+ }
287
+ if (filter.taskId !== undefined) {
288
+ clauses.push("task_id = ?");
289
+ params.push(requireId("taskId", filter.taskId));
290
+ }
291
+ const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
292
+ 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)
293
+ .map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
294
+ }
295
+ /** Running operations assigned to one supervising host, using the phase/host index. */
296
+ export function listRunningSupervisedBy(ctx, hostId) {
297
+ 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 phase = 'running' AND supervision_host_id = ? ORDER BY created_at, operation_id", requireId("hostId", hostId)).map(row => ({ ...mapOperation(row), resultManaged: Number(row.result_managed) === 1 }));
298
+ }
299
+ function listOutboxForRevision(ctx, operationId, terminalRevision) {
300
+ return getRows(ctx, "SELECT * FROM outbox_events WHERE operation_id = ? AND terminal_revision = ? ORDER BY created_at, event_id", operationId, terminalRevision).map((row) => mapOutbox(ctx, row));
301
+ }
@@ -0,0 +1,282 @@
1
+ // Generated canonical coordinator. Do not edit directly.
2
+ /**
3
+ * Durable result delivery.
4
+ *
5
+ * The outbox is addressed to the wait's owner identity, not to a process. One
6
+ * event exists per terminal revision per wait generation, so duplicate terminal
7
+ * events, reload replay and repeated reconciliation cannot enqueue a second
8
+ * event for the same result.
9
+ *
10
+ * Delivery itself is at-least-once, not exactly-once. The unique event and its
11
+ * unique index make enqueue idempotent, but `markOutboxDelivered` commits after
12
+ * the caller emitted the result: a crash between emission and that write leaves
13
+ * the event claimed, and a reconciled host may emit it again. Recipients must
14
+ * key on the event id (or operation, revision, wait and generation) instead of
15
+ * assuming a result is emitted once.
16
+ *
17
+ * Delivery and interpretation are separate: a dispatched or delivered event is
18
+ * not a consumed result. Only `acknowledgeResult` marks the generation consumed,
19
+ * and only an acknowledgement releases the evidence pins that kept the terminal
20
+ * evidence alive.
21
+ */
22
+ import { randomUUID } from "node:crypto";
23
+ import { StoreError } from "./errors.mjs";
24
+ import { dependencyState, mapOutbox, ownerFromRow, readOperationEvidence, readOutboxRow, requireWaitRow, } from "./rows.mjs";
25
+ import { columnJson, columnNullableText, columnNumber, columnText, getRows, run } from "./sqlite.mjs";
26
+ import { requireCounter, requireId, requireText } from "./validate.mjs";
27
+ const OUTBOX_STATES = [
28
+ "pending",
29
+ "claimed",
30
+ "delivered",
31
+ "acknowledged",
32
+ "voided",
33
+ ];
34
+ /** Delivery is only meaningful once the generation can act on the evidence. */
35
+ const DELIVERABLE_WAIT_PHASES = ["ready", "resuming"];
36
+ const UNCONSUMED_OUTBOX_STATES = ["pending", "claimed", "delivered"];
37
+ function placeholders(count) {
38
+ return new Array(count).fill("?").join(", ");
39
+ }
40
+ /**
41
+ * Enqueue one event per settled dependency at its terminal revision, and pin the
42
+ * evidence that event refers to. Idempotent: the unique
43
+ * (operation, revision, wait, generation) index decides whether anything is new.
44
+ */
45
+ export function enqueueGenerationOutbox(ctx, waitId, generation, recipient, dependencies, at) {
46
+ const inserted = [];
47
+ for (const dependency of dependencies) {
48
+ if (dependency.terminalRevision <= 0)
49
+ continue;
50
+ const eventId = `evt_${randomUUID()}`;
51
+ const changes = run(ctx, `INSERT OR IGNORE INTO outbox_events (
52
+ event_id, operation_id, terminal_revision, wait_id, generation,
53
+ recipient_kind, recipient_session_id, recipient_workspace, recipient_branch_id, recipient_goal_id,
54
+ state, attempts, created_at
55
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 0, ?)`, eventId, dependency.operationId, dependency.terminalRevision, waitId, generation, recipient.kind, recipient.sessionId, recipient.workspace, recipient.branchId ?? null, recipient.goalId ?? null, at);
56
+ if (changes === 0)
57
+ continue;
58
+ for (const evidence of readOperationEvidence(ctx, dependency.operationId, dependency.terminalRevision)) {
59
+ run(ctx, `INSERT OR IGNORE INTO evidence_pins (
60
+ pin_id, wait_id, generation, operation_id, terminal_revision,
61
+ kind, ref, summary, detail_lost, bytes, pinned_at
62
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, `pin_${randomUUID()}`, waitId, generation, evidence.operationId, evidence.terminalRevision, evidence.kind, evidence.ref, evidence.summary ?? null, evidence.detailLost ? 1 : 0, evidence.bytes ?? null, at);
63
+ }
64
+ const row = readOutboxRow(ctx, eventId);
65
+ if (row)
66
+ inserted.push(mapOutbox(ctx, row));
67
+ }
68
+ return inserted;
69
+ }
70
+ /** Enqueue for a generation that just became ready, reading its dependencies. */
71
+ export function enqueueReadyGeneration(ctx, waitId, generation, at) {
72
+ const row = requireWaitRow(ctx, waitId, generation);
73
+ const recipient = {
74
+ kind: columnText(row, "owner_kind"),
75
+ sessionId: columnText(row, "owner_session_id"),
76
+ workspace: columnText(row, "owner_workspace"),
77
+ branchId: columnNullableText(row, "owner_branch_id"),
78
+ goalId: columnNullableText(row, "owner_goal_id"),
79
+ };
80
+ const state = dependencyState(ctx, waitId, generation);
81
+ if (!state.settled) {
82
+ throw new StoreError("dependencies-unsettled", `Wait ${waitId} generation ${generation} still has unfinished dependencies; result delivery is enqueued only when every dependency has a terminal outcome.`);
83
+ }
84
+ return enqueueGenerationOutbox(ctx, waitId, generation, recipient, state.dependencies, at);
85
+ }
86
+ /** Release the pins of a generation; used by acknowledgement and cancellation. */
87
+ export function releaseGenerationPins(ctx, waitId, generation, reason, at) {
88
+ const rows = getRows(ctx, "SELECT pin_id FROM evidence_pins WHERE wait_id = ? AND generation = ? AND released_at IS NULL", waitId, generation);
89
+ const ids = rows.map((row) => columnText(row, "pin_id"));
90
+ if (ids.length === 0)
91
+ return [];
92
+ run(ctx, `UPDATE evidence_pins SET released_at = ?, release_reason = ?
93
+ WHERE wait_id = ? AND generation = ? AND released_at IS NULL`, at, reason, waitId, generation);
94
+ return ids;
95
+ }
96
+ /** Void unconsumed deliveries of a generation; cancellation resolves the wait, not the result. */
97
+ export function voidGenerationOutbox(ctx, waitId, generation, reason, at) {
98
+ const rows = getRows(ctx, `SELECT event_id FROM outbox_events
99
+ WHERE wait_id = ? AND generation = ? AND state IN (${placeholders(UNCONSUMED_OUTBOX_STATES.length)})`, waitId, generation, ...UNCONSUMED_OUTBOX_STATES);
100
+ const ids = rows.map((row) => columnText(row, "event_id"));
101
+ if (ids.length === 0)
102
+ return [];
103
+ run(ctx, `UPDATE outbox_events SET state = 'voided', voided_at = ?, reason = ?, dispatch_claim_json = NULL
104
+ WHERE wait_id = ? AND generation = ? AND state IN (${placeholders(UNCONSUMED_OUTBOX_STATES.length)})`, at, reason, waitId, generation, ...UNCONSUMED_OUTBOX_STATES);
105
+ return ids;
106
+ }
107
+ /** Mark the generation's deliveries consumed by interpretation. */
108
+ export function acknowledgeGenerationOutbox(ctx, waitId, generation, at) {
109
+ const rows = getRows(ctx, `SELECT event_id FROM outbox_events
110
+ WHERE wait_id = ? AND generation = ? AND state IN (${placeholders(UNCONSUMED_OUTBOX_STATES.length)})`, waitId, generation, ...UNCONSUMED_OUTBOX_STATES);
111
+ const ids = rows.map((row) => columnText(row, "event_id"));
112
+ if (ids.length === 0)
113
+ return [];
114
+ run(ctx, `UPDATE outbox_events SET state = 'acknowledged', acknowledged_at = ?, dispatch_claim_json = NULL
115
+ WHERE wait_id = ? AND generation = ? AND state IN (${placeholders(UNCONSUMED_OUTBOX_STATES.length)})`, at, waitId, generation, ...UNCONSUMED_OUTBOX_STATES);
116
+ return ids;
117
+ }
118
+ function ownerClause(prefix, owner) {
119
+ return {
120
+ sql: `${prefix}_kind = ? AND ${prefix}_session_id = ? AND ${prefix}_workspace = ?
121
+ AND coalesce(${prefix}_branch_id, '') = ? AND coalesce(${prefix}_goal_id, '') = ?`,
122
+ params: [owner.kind, owner.sessionId, owner.workspace, owner.branchId ?? "", owner.goalId ?? ""],
123
+ };
124
+ }
125
+ export function listOutbox(ctx, filter = {}) {
126
+ const clauses = [];
127
+ const params = [];
128
+ if (filter.recipient) {
129
+ const clause = ownerClause("recipient", filter.recipient);
130
+ clauses.push(clause.sql);
131
+ params.push(...clause.params);
132
+ }
133
+ if (filter.state !== undefined) {
134
+ const states = Array.isArray(filter.state) ? filter.state : [filter.state];
135
+ for (const state of states) {
136
+ if (!OUTBOX_STATES.includes(state)) {
137
+ throw new StoreError("validation", `Invalid state: must be one of ${OUTBOX_STATES.join(", ")}`);
138
+ }
139
+ }
140
+ clauses.push(`state IN (${placeholders(states.length)})`);
141
+ params.push(...states);
142
+ }
143
+ if (filter.waitId !== undefined) {
144
+ clauses.push("wait_id = ?");
145
+ params.push(requireId("waitId", filter.waitId));
146
+ }
147
+ if (filter.generation !== undefined) {
148
+ clauses.push("generation = ?");
149
+ params.push(requireCounter("generation", filter.generation));
150
+ }
151
+ if (filter.operationId !== undefined) {
152
+ clauses.push("operation_id = ?");
153
+ params.push(requireId("operationId", filter.operationId));
154
+ }
155
+ const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
156
+ return getRows(ctx, `SELECT * FROM outbox_events ${where} ORDER BY created_at, event_id`, ...params).map((row) => mapOutbox(ctx, row));
157
+ }
158
+ /** Find recipients with deliverable dependencies without loading each event's evidence. */
159
+ export function listDispatchableOutboxRecipients(ctx) {
160
+ return getRows(ctx, `SELECT recipient_kind, recipient_session_id, recipient_workspace, recipient_branch_id, recipient_goal_id,
161
+ count(*) AS pending_count
162
+ FROM outbox_events
163
+ WHERE state = 'pending' AND event_type = 'dependency-ready'
164
+ AND EXISTS (SELECT 1 FROM waits w WHERE w.wait_id = outbox_events.wait_id
165
+ AND w.generation = outbox_events.generation
166
+ AND w.phase IN (${placeholders(DELIVERABLE_WAIT_PHASES.length)}))
167
+ GROUP BY recipient_kind, recipient_session_id, recipient_workspace, recipient_branch_id, recipient_goal_id
168
+ ORDER BY min(created_at), min(event_id)`, ...DELIVERABLE_WAIT_PHASES).map((row) => ({ recipient: ownerFromRow(row, "recipient"), count: columnNumber(row, "pending_count") }));
169
+ }
170
+ function readDispatchClaim(row) {
171
+ return columnJson(row, "dispatch_claim_json");
172
+ }
173
+ function assertDispatchTokenUnused(ctx, claimToken) {
174
+ const rows = getRows(ctx, "SELECT event_id, dispatch_claim_json FROM outbox_events WHERE state = 'claimed'");
175
+ for (const row of rows) {
176
+ const claim = readDispatchClaim(row);
177
+ if (claim === null)
178
+ continue;
179
+ if (claim.token === claimToken) {
180
+ throw new StoreError("outbox-state", `Dispatch token ${claimToken} is already held by event ${columnText(row, "event_id")}. Use a fresh token for a new dispatch attempt.`);
181
+ }
182
+ }
183
+ }
184
+ /**
185
+ * Claim pending deliveries for dispatch. Claiming records an attempt but does not
186
+ * consume the result: an event that is never acknowledged stays visible.
187
+ */
188
+ export function claimOutbox(ctx, input) {
189
+ const claimToken = requireId("claimToken", input.claimToken);
190
+ const claimedBy = requireText("claimedBy", input.claimedBy, 200);
191
+ const limit = input.limit === undefined ? 10 : requireCounter("limit", input.limit);
192
+ if (limit < 1) {
193
+ throw new StoreError("validation", "Invalid limit: must be at least 1");
194
+ }
195
+ const recipient = input.recipient;
196
+ return ctx.transaction(() => {
197
+ assertDispatchTokenUnused(ctx, claimToken);
198
+ const clauses = [
199
+ "state = 'pending'",
200
+ `(event_type = 'assignment-outcome' OR EXISTS (SELECT 1 FROM waits w WHERE w.wait_id = outbox_events.wait_id
201
+ AND w.generation = outbox_events.generation
202
+ AND w.phase IN (${placeholders(DELIVERABLE_WAIT_PHASES.length)})))`,
203
+ ];
204
+ const params = [...DELIVERABLE_WAIT_PHASES];
205
+ if (input.eventId !== undefined) {
206
+ clauses.push("event_id = ?");
207
+ params.push(requireId("eventId", input.eventId));
208
+ }
209
+ if (input.type !== undefined) {
210
+ if (!["dependency-ready", "assignment-outcome"].includes(input.type))
211
+ throw new StoreError("validation", "Unknown outbox event type.");
212
+ clauses.push("event_type = ?");
213
+ params.push(input.type);
214
+ }
215
+ if (input.waitId !== undefined) {
216
+ clauses.push("wait_id = ?");
217
+ params.push(requireId("waitId", input.waitId));
218
+ }
219
+ if (input.generation !== undefined) {
220
+ clauses.push("generation = ?");
221
+ params.push(requireCounter("generation", input.generation));
222
+ }
223
+ if (recipient) {
224
+ const clause = ownerClause("recipient", recipient);
225
+ clauses.push(clause.sql);
226
+ params.push(...clause.params);
227
+ }
228
+ const rows = getRows(ctx, `SELECT * FROM outbox_events WHERE ${clauses.join(" AND ")} ORDER BY created_at, event_id LIMIT ?`, ...params, limit);
229
+ const at = ctx.now();
230
+ const claimed = [];
231
+ for (const row of rows) {
232
+ const eventId = columnText(row, "event_id");
233
+ run(ctx, `UPDATE outbox_events
234
+ SET state = 'claimed', attempts = attempts + 1, claimed_at = ?, dispatch_claim_json = ?
235
+ WHERE event_id = ? AND state = 'pending'`, at, JSON.stringify({ token: claimToken, claimedBy, claimedAt: at }), eventId);
236
+ const updated = readOutboxRow(ctx, eventId);
237
+ if (updated)
238
+ claimed.push(mapOutbox(ctx, updated));
239
+ }
240
+ return claimed;
241
+ });
242
+ }
243
+ function requireClaimedEvent(ctx, input) {
244
+ const eventId = requireId("eventId", input.eventId);
245
+ const claimToken = requireId("claimToken", input.claimToken);
246
+ const row = readOutboxRow(ctx, eventId);
247
+ if (!row) {
248
+ throw new StoreError("outbox-state", `No outbox event ${eventId} is recorded.`);
249
+ }
250
+ const state = columnText(row, "state");
251
+ if (state !== "claimed") {
252
+ throw new StoreError("outbox-state", `Outbox event ${eventId} is ${state}; only a claimed delivery can be completed or released.`);
253
+ }
254
+ const claim = readDispatchClaim(row);
255
+ if (claim === null || claim.token !== claimToken) {
256
+ throw new StoreError("outbox-state", `Outbox event ${eventId} is claimed by a different dispatch token; the caller does not hold this delivery.`);
257
+ }
258
+ return row;
259
+ }
260
+ export function markOutboxDelivered(ctx, input) {
261
+ return ctx.transaction(() => {
262
+ const row = requireClaimedEvent(ctx, input);
263
+ const eventId = columnText(row, "event_id");
264
+ run(ctx, "UPDATE outbox_events SET state = 'delivered', delivered_at = ?, dispatch_claim_json = NULL WHERE event_id = ?", ctx.now(), eventId);
265
+ const updated = readOutboxRow(ctx, eventId);
266
+ return mapOutbox(ctx, updated);
267
+ });
268
+ }
269
+ /**
270
+ * Return a claimed delivery to the queue with a recorded reason. Attempts and the
271
+ * recovery reason are retained, and the result stays unconsumed.
272
+ */
273
+ export function releaseOutbox(ctx, input) {
274
+ const reason = requireText("reason", input.reason, 1024);
275
+ return ctx.transaction(() => {
276
+ const row = requireClaimedEvent(ctx, input);
277
+ const eventId = columnText(row, "event_id");
278
+ run(ctx, "UPDATE outbox_events SET state = 'pending', reason = ?, dispatch_claim_json = NULL WHERE event_id = ?", reason, eventId);
279
+ const updated = readOutboxRow(ctx, eventId);
280
+ return mapOutbox(ctx, updated);
281
+ });
282
+ }
@@ -0,0 +1,51 @@
1
+ // Generated canonical coordinator. Do not edit directly.
2
+ import { createHash } from "node:crypto";
3
+ import { StoreError } from "./errors.mjs";
4
+ import { getRow, getRows, columnText, run } from "./sqlite.mjs";
5
+ import { requireWait } from "./rows.mjs";
6
+ import { holdFailedResume } from "./waits.mjs";
7
+ import { getAssignmentOutcome, recordAssignmentOutcome } from "./assignment-outcomes.mjs";
8
+ /** The exact exit is fenced and the allowance committed in the same transaction. */
9
+ export function repairFailedResume(ctx, input) {
10
+ return ctx.transaction(() => {
11
+ const wait = requireWait(ctx, input.waitId, input.generation);
12
+ const assignmentId = wait.origin?.assignmentRef;
13
+ if (!assignmentId || !wait.park || input.checkpointId !== wait.park.checkpointId) {
14
+ throw new StoreError("resume-proof", "Repair requires the assignment's original checkpoint identity.");
15
+ }
16
+ if (wait.cancelEpoch !== input.expectedCancelEpoch)
17
+ throw new StoreError("stale-cancel-epoch", "Repair cancellation epoch changed.");
18
+ const publication = getRow(ctx, "SELECT claim_id FROM resume_claims WHERE claim_id = ? AND claim_token = ? AND attempt_id = ? AND launch_token = ? AND wait_id = ? AND generation = ? AND cancel_epoch = ?", input.claimId, input.claimToken, input.attemptId, input.launchToken, wait.waitId, wait.generation, wait.cancelEpoch);
19
+ if (!publication)
20
+ throw new StoreError("claim-state", "Repair does not match the exact published writer.");
21
+ const fault = JSON.stringify({ category: "unacknowledged-exit", checkpointId: input.checkpointId,
22
+ dependencies: wait.dependencies.map((d) => [d.operationId, d.terminalRevision]).sort((a, b) => String(a[0]).localeCompare(String(b[0]))) });
23
+ const key = createHash("sha256").update(JSON.stringify([assignmentId, wait.waitId, wait.generation, fault])).digest("hex");
24
+ const prior = getRow(ctx, "SELECT claim_id FROM assignment_repairs WHERE fault_key = ?", key);
25
+ const terminal = getAssignmentOutcome(ctx, assignmentId);
26
+ if (terminal) {
27
+ holdFailedResume(ctx, input);
28
+ return { phase: "held", repaired: false };
29
+ }
30
+ // Duplicate exit notifications cannot exhaust a repair that has not run.
31
+ if (prior && columnText(prior, "claim_id") === input.claimId)
32
+ return { phase: wait.phase, repaired: false };
33
+ holdFailedResume(ctx, input);
34
+ if (prior) {
35
+ const binding = getRow(ctx, "SELECT recipient_json FROM assignment_bindings WHERE assignment_id = ?", assignmentId);
36
+ if (!binding)
37
+ throw new StoreError("foreign-owner", "Repair has no captured parent recipient.");
38
+ recordAssignmentOutcome(ctx, { assignmentId, owner: wait.owner, recipient: JSON.parse(columnText(binding, "recipient_json")),
39
+ revision: 1, outcome: "failed", reason: "Automatic repair repeated the same unacknowledged-exit fault; the one-repair allowance is exhausted.",
40
+ processUncertain: false, evidence: [{ kind: "summary", ref: `repair:${key}`, summary: input.reason }],
41
+ waits: getRows(ctx, "SELECT wait_id, generation FROM waits WHERE json_extract(origin_json, '$.assignmentRef') = ?", assignmentId).map((row) => {
42
+ const linked = requireWait(ctx, columnText(row, "wait_id"), Number(row.generation));
43
+ return { waitId: linked.waitId, generation: linked.generation, cancelEpoch: linked.cancelEpoch };
44
+ }) });
45
+ return { phase: "held", repaired: false };
46
+ }
47
+ run(ctx, "INSERT INTO assignment_repairs VALUES (?, ?, ?, ?, ?, ?)", key, assignmentId, wait.waitId, wait.generation, fault, input.claimId);
48
+ run(ctx, "UPDATE waits SET phase = 'ready', phase_reason = 'bounded-repair', updated_at = ? WHERE wait_id = ? AND generation = ?", ctx.now(), wait.waitId, wait.generation);
49
+ return { phase: "ready", repaired: true };
50
+ });
51
+ }