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,245 @@
1
+ // Generated canonical coordinator. Do not edit directly.
2
+ /**
3
+ * The coordinator store handle.
4
+ *
5
+ * One `Store` is one SQLite database. Open it once per process path, hand the
6
+ * handle to the hosting extension, and close it on extension unload. Every call is
7
+ * synchronous and transactional; a refusal throws `StoreError` with a typed code
8
+ * and leaves no partial record.
9
+ */
10
+ import { StoreError } from "./errors.mjs";
11
+ import { resultSupervision, resultSupervisions, resultScopeManaged, handoffResultScope, handoffResultSupervision, handoffResultSupervisions, recoverResultSupervision, publishSupervisedResult } from "./result-supervision.mjs";
12
+ import { acceptTaskCancellation, getTaskCancellation, recordTaskStopRequested, admitTaskCancellation, authorizedTaskCancellation, finishTaskCancellation, cancellationRuntimeEpoch, acceptAuthorizedTaskCancellation, taskCancellationManaged, pendingTaskCancellations, finishTaskCancellationIntent, unknownTaskCancellation } from "./task-cancellation.mjs";
13
+ import { repairFailedResume } from "./recovery.mjs";
14
+ import { recordAssignmentOutcome, getAssignmentOutcome, inspectAssignmentOutcome, consumeAssignmentOutcome, registerAssignment, receiptAssignmentOutcome } from "./assignment-outcomes.mjs";
15
+ import { describeOwnerDiff, normalizeOwner, requireCounter, requireId, requirePath, } from "./validate.mjs";
16
+ import { ensureSchema } from "./schema.mjs";
17
+ import { createContext, openDatabase } from "./sqlite.mjs";
18
+ import { getOperation as readOperationRecord, listOperations as readOperationRecords, listRunningSupervisedBy as readRunningSupervisedBy, releaseSupervision as writeSupervisionRelease, recordSupervision as writeSupervision, recordTerminalOutcome as writeTerminalOutcome, registerOperation as writeOperation, } from "./operations.mjs";
19
+ import { getChangeRevision as readChangeRevision, readDiscoveryClaim as readClaim, readDiscoveryState, releaseDiscoveryClaim as deleteDiscoveryClaim, tryClaimDiscovery as writeDiscoveryClaim, } from "./discovery.mjs";
20
+ import { acknowledgeResult as writeAcknowledgement, cancelWait as writeCancellation, claimResume as writeClaim, findPendingWaitForOwner, getWait as readWait, listDependencies as readDependencies, listEvidencePins as readPins, listEvidenceReads as readReads, listResumeClaims as readClaims, listUnreconciledClaims, listWaits as readWaits, publishResumeAttempt as writeAttemptPublication, recordEvidencePin as writePin, recordEvidenceRead as writeRead, registerWait as writeWait, releaseEvidencePins as writePinRelease, holdFailedResume as writeHoldFailedResume, releaseResumeClaim as writeClaimRelease, transitionWaitPhase as writePhase, } from "./waits.mjs";
21
+ import { claimOutbox as writeOutboxClaim, listDispatchableOutboxRecipients as readDispatchableOutboxRecipients, listOutbox as readOutbox, markOutboxDelivered as writeOutboxDelivery, releaseOutbox as writeOutboxRelease, } from "./outbox.mjs";
22
+ import { readOperationEvidence } from "./rows.mjs";
23
+ import { SCHEMA_VERSION, } from "./types.mjs";
24
+ export function openStore(options) {
25
+ const path = requirePath("path", options.path);
26
+ const db = openDatabase(path, { busyTimeoutMs: options.busyTimeoutMs ?? 5_000 });
27
+ const ctx = createContext(db, options.now ? { now: options.now } : {});
28
+ try {
29
+ ensureSchema(ctx);
30
+ }
31
+ catch (error) {
32
+ try {
33
+ db.close();
34
+ }
35
+ catch {
36
+ // The schema refusal is the failure worth reporting.
37
+ }
38
+ throw error;
39
+ }
40
+ let closed = false;
41
+ const alive = () => {
42
+ if (closed) {
43
+ throw new StoreError("closed", "This operation coordinator store was closed. Open a new handle instead of reusing it.");
44
+ }
45
+ };
46
+ const store = {
47
+ resultScopeManaged(scope) { alive(); return resultScopeManaged(ctx, scope); },
48
+ handoffResultScope(input) { alive(); return handoffResultScope(ctx, input); },
49
+ resultSupervision(id) { alive(); return resultSupervision(ctx, id); },
50
+ resultSupervisions(activeOnly) { alive(); return resultSupervisions(ctx, activeOnly); },
51
+ handoffResultSupervision(input) { alive(); return handoffResultSupervision(ctx, input); },
52
+ handoffResultSupervisions(input) { alive(); return handoffResultSupervisions(ctx, input); },
53
+ recoverResultSupervision(input) { alive(); recoverResultSupervision(ctx, input); },
54
+ publishSupervisedResult(input) { alive(); return publishSupervisedResult(ctx, input); },
55
+ unknownTaskCancellation(input) { alive(); return unknownTaskCancellation(ctx, input); },
56
+ taskCancellationManaged(operationId) { alive(); return taskCancellationManaged(ctx, operationId); },
57
+ pendingTaskCancellations() { alive(); return pendingTaskCancellations(ctx); },
58
+ finishTaskCancellationIntent(input) { alive(); return finishTaskCancellationIntent(ctx, input); },
59
+ cancellationRuntimeEpoch(instanceId) { alive(); return cancellationRuntimeEpoch(ctx, instanceId); },
60
+ acceptAuthorizedTaskCancellation(input) { alive(); return acceptAuthorizedTaskCancellation(ctx, input); },
61
+ admitTaskCancellation(input) { alive(); admitTaskCancellation(ctx, input); },
62
+ authorizedTaskCancellation(credential) { alive(); return authorizedTaskCancellation(ctx, credential); },
63
+ finishTaskCancellation(input) { alive(); return finishTaskCancellation(ctx, input); },
64
+ registerAssignment(input) { alive(); registerAssignment(ctx, input); },
65
+ receiptAssignmentOutcome(input) { alive(); return receiptAssignmentOutcome(ctx, input); },
66
+ recordAssignmentOutcome(input) { alive(); return recordAssignmentOutcome(ctx, input); },
67
+ getAssignmentOutcome(assignmentId) { alive(); return getAssignmentOutcome(ctx, assignmentId); },
68
+ inspectAssignmentOutcome(input) { alive(); return inspectAssignmentOutcome(ctx, input); },
69
+ consumeAssignmentOutcome(input) { alive(); return consumeAssignmentOutcome(ctx, input); },
70
+ schemaVersion: SCHEMA_VERSION,
71
+ path,
72
+ close() {
73
+ if (closed)
74
+ return;
75
+ closed = true;
76
+ db.close();
77
+ },
78
+ registerOperation(input) {
79
+ alive();
80
+ return writeOperation(ctx, input);
81
+ },
82
+ recordSupervision(input) {
83
+ alive();
84
+ return writeSupervision(ctx, input);
85
+ },
86
+ releaseSupervision(input) {
87
+ alive();
88
+ return writeSupervisionRelease(ctx, input);
89
+ },
90
+ recordTerminalOutcome(input) {
91
+ alive();
92
+ return writeTerminalOutcome(ctx, input);
93
+ },
94
+ getOperation(operationId) {
95
+ alive();
96
+ return readOperationRecord(ctx, requireId("operationId", operationId));
97
+ },
98
+ listOperations(filter = {}) {
99
+ alive();
100
+ return readOperationRecords(ctx, filter);
101
+ },
102
+ listRunningSupervisedBy(hostId) {
103
+ alive();
104
+ return readRunningSupervisedBy(ctx, hostId);
105
+ },
106
+ listOperationEvidence(operationId, terminalRevision) {
107
+ alive();
108
+ return readOperationEvidence(ctx, requireId("operationId", operationId), terminalRevision === undefined ? undefined : requireCounter("terminalRevision", terminalRevision));
109
+ },
110
+ readDiscoveryState(scope) { alive(); return readDiscoveryState(ctx, scope); },
111
+ readDiscoveryClaim(scope) {
112
+ alive();
113
+ return readClaim(ctx, scope);
114
+ },
115
+ tryClaimDiscovery(input) {
116
+ alive();
117
+ return writeDiscoveryClaim(ctx, input);
118
+ },
119
+ releaseDiscoveryClaim(input) {
120
+ alive();
121
+ return deleteDiscoveryClaim(ctx, input);
122
+ },
123
+ getChangeRevision() {
124
+ alive();
125
+ return readChangeRevision(ctx);
126
+ },
127
+ registerWait(input) {
128
+ alive();
129
+ return writeWait(ctx, input);
130
+ },
131
+ acceptTaskCancellation(input) {
132
+ alive();
133
+ return acceptTaskCancellation(ctx, input);
134
+ },
135
+ getTaskCancellation(input) {
136
+ alive();
137
+ return getTaskCancellation(ctx, input);
138
+ },
139
+ recordTaskStopRequested(input) {
140
+ alive();
141
+ return recordTaskStopRequested(ctx, input);
142
+ },
143
+ transitionWaitPhase(input) {
144
+ alive();
145
+ return writePhase(ctx, input);
146
+ },
147
+ cancelWait(input) {
148
+ alive();
149
+ return writeCancellation(ctx, input);
150
+ },
151
+ getWait(ref) {
152
+ alive();
153
+ return readWait(ctx, ref);
154
+ },
155
+ listWaits(filter = {}) {
156
+ alive();
157
+ return readWaits(ctx, filter);
158
+ },
159
+ listDependencies(ref) {
160
+ alive();
161
+ return readDependencies(ctx, ref);
162
+ },
163
+ findPendingWait(owner) {
164
+ alive();
165
+ return findPendingWaitForOwner(ctx, normalizeOwner("owner", owner));
166
+ },
167
+ claimResume(input) {
168
+ alive();
169
+ return writeClaim(ctx, input);
170
+ },
171
+ publishResumeAttempt(input) {
172
+ alive();
173
+ return writeAttemptPublication(ctx, input);
174
+ },
175
+ releaseResumeClaim(input) {
176
+ alive();
177
+ return writeClaimRelease(ctx, input);
178
+ },
179
+ holdFailedResume(input) {
180
+ alive();
181
+ return writeHoldFailedResume(ctx, input);
182
+ },
183
+ repairFailedResume(input) {
184
+ alive();
185
+ return repairFailedResume(ctx, input);
186
+ },
187
+ listResumeClaims(filter = {}) {
188
+ alive();
189
+ return readClaims(ctx, filter);
190
+ },
191
+ listUnreconciledClaims() {
192
+ alive();
193
+ return listUnreconciledClaims(ctx);
194
+ },
195
+ recordEvidenceRead(input) {
196
+ alive();
197
+ return writeRead(ctx, input);
198
+ },
199
+ listEvidenceReads(ref) {
200
+ alive();
201
+ return readReads(ctx, ref);
202
+ },
203
+ recordEvidencePin(input) {
204
+ alive();
205
+ return writePin(ctx, input);
206
+ },
207
+ listEvidencePins(ref, options) {
208
+ alive();
209
+ return readPins(ctx, ref, options);
210
+ },
211
+ releaseEvidencePins(ref, reason) {
212
+ alive();
213
+ return writePinRelease(ctx, ref, reason);
214
+ },
215
+ acknowledgeResult(input) {
216
+ alive();
217
+ return writeAcknowledgement(ctx, input);
218
+ },
219
+ listOutbox(filter = {}) {
220
+ alive();
221
+ return readOutbox(ctx, filter);
222
+ },
223
+ listDispatchableOutboxRecipients() {
224
+ alive();
225
+ return readDispatchableOutboxRecipients(ctx);
226
+ },
227
+ claimOutbox(input) {
228
+ alive();
229
+ return writeOutboxClaim(ctx, input);
230
+ },
231
+ markOutboxDelivered(input) {
232
+ alive();
233
+ return writeOutboxDelivery(ctx, input);
234
+ },
235
+ releaseOutbox(input) {
236
+ alive();
237
+ return writeOutboxRelease(ctx, input);
238
+ },
239
+ };
240
+ return store;
241
+ }
242
+ /** Identity helper re-exported for callers that compare recorded owners. */
243
+ export function ownerDiff(a, b) {
244
+ return describeOwnerDiff(a, b);
245
+ }
@@ -0,0 +1,187 @@
1
+ // Generated canonical coordinator. Do not edit directly.
2
+ /**
3
+ * Durable intent for the fixed cancel_task operation. Admission and process
4
+ * identity checks remain the host's responsibility. An accepted intent is not
5
+ * evidence that a process stopped; recovery must use its original launch token.
6
+ */
7
+ import { StoreError } from "./errors.mjs";
8
+ import { createHash, randomBytes } from "node:crypto";
9
+ import { getOperation, recordTerminalOutcome } from "./operations.mjs";
10
+ import { columnText, getRow, run } from "./sqlite.mjs";
11
+ import { normalizeOwner, requireCounter, requireId, requireText, sameOwner } from "./validate.mjs";
12
+ export function cancellationRuntimeEpoch(ctx, instanceId) {
13
+ return ctx.transaction(() => {
14
+ const row = getRow(ctx, "SELECT value FROM coordinator_state WHERE key = 'cancellation-runtime'");
15
+ const current = row ? JSON.parse(columnText(row, "value")) : { epoch: 0 };
16
+ if (!instanceId || current.instanceId === instanceId)
17
+ return current.epoch;
18
+ const epoch = current.epoch + 1;
19
+ run(ctx, "INSERT INTO coordinator_state (key, value) VALUES ('cancellation-runtime', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value", JSON.stringify({ instanceId, epoch }));
20
+ return epoch;
21
+ });
22
+ }
23
+ function cancelEpoch(ctx, operationId) {
24
+ const row = getRow(ctx, "SELECT value FROM coordinator_state WHERE key = ?", `cancel:${operationId}`);
25
+ return row ? Number(columnText(row, "value")) : 0;
26
+ }
27
+ function revision(operation, epoch) {
28
+ const op = operation;
29
+ return createHash("sha256").update(JSON.stringify([op && {
30
+ operationId: op.operationId, owner: op.owner, launchToken: op.launchToken,
31
+ terminalRevision: op.terminalRevision, phase: op.phase, authorityRef: op.authorityRef,
32
+ hostId: op.supervision?.hostId,
33
+ }, epoch])).digest("hex");
34
+ }
35
+ export function taskCancellationManaged(ctx, operationId) {
36
+ return !!getRow(ctx, "SELECT credential_hash FROM task_cancellation_authorities WHERE json_extract(request_json, '$.request.operationId') = ? LIMIT 1", requireId("operationId", operationId));
37
+ }
38
+ export function pendingTaskCancellations(ctx) {
39
+ return ctx.db.prepare("SELECT a.* FROM task_cancellation_authorities a JOIN task_cancellation_requests r ON json_extract(a.request_json, '$.request.operationId') = r.operation_id AND json_extract(a.request_json, '$.request.idempotencyKey') = r.request_key WHERE r.result_json IS NULL").all()
40
+ .map(row => ({ credentialHash: columnText(row, "credential_hash"), ...JSON.parse(columnText(row, "request_json")), directory: columnText(row, "directory") }));
41
+ }
42
+ export function acceptAuthorizedTaskCancellation(ctx, input) {
43
+ return ctx.transaction(() => {
44
+ const admission = authorizedTaskCancellation(ctx, input.credential);
45
+ const previous = getTaskCancellation(ctx, admission.request);
46
+ if (previous)
47
+ return acceptTaskCancellation(ctx, admission.request);
48
+ if (input.runtimeEpoch !== cancellationRuntimeEpoch(ctx) || input.runtimeEpoch !== admission.runtimeEpoch)
49
+ throw new StoreError("supervision-conflict", "not_accepted: stale-runtime-epoch; query journal before new admission");
50
+ const operation = getOperation(ctx, admission.request.operationId);
51
+ const epoch = cancelEpoch(ctx, admission.request.operationId);
52
+ if (epoch !== admission.cancelEpoch || revision(operation, epoch) !== admission.revision)
53
+ throw new StoreError("operation-conflict", "not_accepted: stale-revision or cancellation epoch");
54
+ const intent = acceptTaskCancellation(ctx, admission.request);
55
+ run(ctx, "INSERT INTO coordinator_state (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value", `cancel:${intent.operationId}`, String(epoch + 1));
56
+ return intent;
57
+ });
58
+ }
59
+ export function cancellationCredential() {
60
+ const credential = randomBytes(32).toString("hex");
61
+ return { credential, hash: credentialHash(credential) };
62
+ }
63
+ function credentialHash(credential) {
64
+ return createHash("sha256").update(requireText("credential", credential, 128)).digest("hex");
65
+ }
66
+ /** Called only by the existing admitted domain host, never by a socket command. */
67
+ export function admitTaskCancellation(ctx, input) {
68
+ const normalized = request(input.request);
69
+ const hash = requireId("credentialHash", input.credentialHash);
70
+ const directory = requireText("directory", input.directory, 4096);
71
+ ctx.transaction(() => {
72
+ const operation = getOperation(ctx, normalized.operationId);
73
+ if (!operation || !sameOwner(operation.owner, normalized.owner))
74
+ throw new StoreError("foreign-owner", "Cancellation admission requires the recorded owner.");
75
+ const previous = getTaskCancellation(ctx, normalized);
76
+ if (operation.launchToken !== normalized.expectedLaunchToken || (!previous && operation.supervision?.hostId !== normalized.expectedHostId)) {
77
+ throw new StoreError("supervision-conflict", "Cancellation admission requires the current exact launch and host.");
78
+ }
79
+ if (previous && JSON.stringify(request(previous)) !== JSON.stringify(normalized))
80
+ throw new StoreError("request-conflict", "Cancellation key is bound to different request content.");
81
+ const original = previous ? request(previous) : normalized;
82
+ const epoch = cancelEpoch(ctx, normalized.operationId);
83
+ run(ctx, "INSERT INTO task_cancellation_authorities (credential_hash, request_json, directory) VALUES (?, ?, ?)", hash, JSON.stringify({ request: original, runtimeEpoch: cancellationRuntimeEpoch(ctx), cancelEpoch: epoch, revision: revision(operation, epoch) }), directory);
84
+ });
85
+ }
86
+ /** A credential binds an already-admitted exact request, not a claimed session ID. */
87
+ export function authorizedTaskCancellation(ctx, credential) {
88
+ const row = getRow(ctx, "SELECT * FROM task_cancellation_authorities WHERE credential_hash = ?", credentialHash(credential));
89
+ if (!row)
90
+ throw new StoreError("foreign-owner", "permission-unavailable: cancellation authority is not registered.");
91
+ return { credentialHash: credentialHash(credential), ...JSON.parse(columnText(row, "request_json")), directory: columnText(row, "directory") };
92
+ }
93
+ export function finishTaskCancellation(ctx, input) {
94
+ const admission = authorizedTaskCancellation(ctx, input.credential);
95
+ return finishTaskCancellationIntent(ctx, { request: admission.request, status: input.status, terminal: input.terminal });
96
+ }
97
+ export function finishTaskCancellationIntent(ctx, input) {
98
+ return ctx.transaction(() => {
99
+ const intent = recordTaskStopRequested(ctx, input.request);
100
+ if (intent.result)
101
+ return intent;
102
+ if (input.publication) {
103
+ if (input.publication.operationId !== intent.operationId || !sameOwner(input.publication.owner, intent.owner))
104
+ throw new StoreError("foreign-owner", "Terminal publication does not match the cancellation intent.");
105
+ recordTerminalOutcome(ctx, input.publication);
106
+ }
107
+ const result = { status: requireText("status", input.status, 64), terminal: input.terminal === true };
108
+ run(ctx, "UPDATE task_cancellation_requests SET result_json = ? WHERE owner_key = ? AND request_key = ?", JSON.stringify(result), ownerKey(intent.owner), intent.idempotencyKey);
109
+ return { ...intent, result };
110
+ });
111
+ }
112
+ export function unknownTaskCancellation(ctx, input) {
113
+ return ctx.transaction(() => {
114
+ const intent = getTaskCancellation(ctx, input);
115
+ if (!intent)
116
+ throw new StoreError("request-conflict", "Cannot record an unknown outcome without an accepted intent.");
117
+ if (intent.result)
118
+ return intent;
119
+ const result = { status: "outcome_unknown", terminal: false };
120
+ run(ctx, "UPDATE task_cancellation_requests SET result_json = ? WHERE owner_key = ? AND request_key = ?", JSON.stringify(result), ownerKey(intent.owner), intent.idempotencyKey);
121
+ return { ...intent, result };
122
+ });
123
+ }
124
+ function ownerKey(owner) {
125
+ return JSON.stringify([owner.kind, owner.sessionId, owner.workspace, owner.branchId, owner.goalId]);
126
+ }
127
+ function request(input) {
128
+ return {
129
+ owner: normalizeOwner("owner", input.owner),
130
+ idempotencyKey: requireText("idempotencyKey", input.idempotencyKey, 512),
131
+ operationId: requireId("operationId", input.operationId),
132
+ expectedLaunchToken: requireId("launchToken", input.expectedLaunchToken),
133
+ expectedTerminalRevision: requireCounter("terminalRevision", input.expectedTerminalRevision),
134
+ expectedHostId: requireId("hostId", input.expectedHostId),
135
+ reason: requireText("reason", input.reason, 1024),
136
+ };
137
+ }
138
+ export function getTaskCancellation(ctx, input) {
139
+ const owner = normalizeOwner("owner", input.owner);
140
+ const key = requireText("idempotencyKey", input.idempotencyKey, 512);
141
+ const row = getRow(ctx, "SELECT intent_json, state, result_json FROM task_cancellation_requests WHERE owner_key = ? AND request_key = ?", ownerKey(owner), key);
142
+ if (!row)
143
+ return null;
144
+ return { ...JSON.parse(columnText(row, "intent_json")), state: columnText(row, "state"), ...(row.result_json ? { result: JSON.parse(columnText(row, "result_json")) } : {}) };
145
+ }
146
+ export function acceptTaskCancellation(ctx, input) {
147
+ const normalized = request(input);
148
+ return ctx.transaction(() => {
149
+ // Journal lookup precedes current object checks: a retry after terminal
150
+ // publication must recover the original receipt, not become a new stop.
151
+ const previous = getTaskCancellation(ctx, normalized);
152
+ if (previous) {
153
+ const { operation: _operation, taskId: _taskId, state: _state, acceptedAt: _at, result: _result, ...original } = previous;
154
+ if (JSON.stringify(original) !== JSON.stringify(normalized)) {
155
+ throw new StoreError("request-conflict", "Cancellation key is already bound to different request content.");
156
+ }
157
+ return previous;
158
+ }
159
+ const operation = getOperation(ctx, normalized.operationId);
160
+ if (!operation)
161
+ throw new StoreError("unknown-operation", "Cancellation operation does not exist.");
162
+ if (!sameOwner(operation.owner, normalized.owner))
163
+ throw new StoreError("foreign-owner", "Cancellation requires the recorded execution owner.");
164
+ if (operation.launchToken !== normalized.expectedLaunchToken || operation.terminalRevision !== normalized.expectedTerminalRevision) {
165
+ throw new StoreError("operation-conflict", "Cancellation launch token or terminal revision changed.");
166
+ }
167
+ if (operation.supervision?.hostId !== normalized.expectedHostId) {
168
+ throw new StoreError("supervision-conflict", "Cancellation supervision host changed.");
169
+ }
170
+ const intent = {
171
+ ...normalized, operation: "cancel_task", taskId: operation.taskId, state: "accepted", acceptedAt: ctx.now(),
172
+ };
173
+ run(ctx, "INSERT INTO task_cancellation_requests (owner_key, request_key, operation_id, intent_json, state) VALUES (?, ?, ?, ?, 'accepted')", ownerKey(normalized.owner), normalized.idempotencyKey, operation.operationId, JSON.stringify(intent));
174
+ return intent;
175
+ });
176
+ }
177
+ /** Record durable stop-file publication, never process exit or a terminal verdict. */
178
+ export function recordTaskStopRequested(ctx, input) {
179
+ return ctx.transaction(() => {
180
+ const normalized = request(input);
181
+ if (!getTaskCancellation(ctx, normalized))
182
+ throw new StoreError("request-conflict", "Cancellation intent must commit before the stop action.");
183
+ const intent = acceptTaskCancellation(ctx, normalized);
184
+ run(ctx, "UPDATE task_cancellation_requests SET state = 'stop-requested' WHERE owner_key = ? AND request_key = ?", ownerKey(normalized.owner), normalized.idempotencyKey);
185
+ return { ...intent, state: "stop-requested" };
186
+ });
187
+ }
@@ -0,0 +1,24 @@
1
+ // Generated canonical coordinator. Do not edit directly.
2
+ /**
3
+ * Public record and call shapes for the durable operation coordinator.
4
+ *
5
+ * The store owns dependency records, phase transitions, resume claims, evidence
6
+ * pins and the result outbox. It owns no provider transport, no tool execution,
7
+ * no model call and no permission decision. Callers keep launch authority,
8
+ * continuation admission and interpretation of the evidence.
9
+ *
10
+ * Identity rules that the API itself enforces:
11
+ *
12
+ * - an operation's owner, task id and launch token are immutable after
13
+ * registration; a different caller writing a terminal outcome is refused;
14
+ * - a wait belongs to exactly one owner identity, and only that owner may cancel
15
+ * it or acknowledge its evidence;
16
+ * - one owner identity holds at most one pending wait generation, and every
17
+ * mutation names the generation it acts on;
18
+ * - a resume attempt id and launch token are persisted before the attempt is
19
+ * spawned, so a crash is reconciled instead of relaunched.
20
+ */
21
+ /** Schema version this build writes and accepts. Any other version is refused. */
22
+ export const SCHEMA_VERSION = 4;
23
+ /** Phases that no longer accept automatic continuation. */
24
+ export const TERMINAL_WAIT_PHASES = ["consumed", "cancelled"];