@unson/brainbase-mcp 0.50.31 → 0.51.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 (51) hide show
  1. package/contracts/canonical-task/store-schema.sql +3 -0
  2. package/dist/automation-run.js +3 -2
  3. package/dist/canonical-task-postgres.js +3 -0
  4. package/dist/canonical-task-service.d.ts +6 -0
  5. package/dist/canonical-task-service.js +40 -1
  6. package/dist/company-os-learning-adoption.d.ts +9 -0
  7. package/dist/company-os-learning-adoption.js +50 -1
  8. package/dist/durable-waits.d.ts +30 -0
  9. package/dist/durable-waits.js +100 -94
  10. package/dist/foundation-public-provider.d.ts +3 -1
  11. package/dist/foundation-public-provider.js +2 -2
  12. package/dist/graph-corrections.d.ts +46 -1
  13. package/dist/graph-corrections.js +172 -1
  14. package/dist/judgment-event-outbox.d.ts +24 -2
  15. package/dist/judgment-event-outbox.js +92 -10
  16. package/dist/judgment-frame.js +2 -2
  17. package/dist/judgment-host.d.ts +4 -1
  18. package/dist/judgment-host.js +126 -14
  19. package/dist/judgment-task-progress.d.ts +41 -0
  20. package/dist/judgment-task-progress.js +18 -0
  21. package/dist/knowledge-continuation.js +7 -1
  22. package/dist/knowledge-lookup.js +43 -58
  23. package/dist/mcp-runtime.d.ts +9 -0
  24. package/dist/mcp-runtime.js +12 -4
  25. package/dist/meeting-automation-runtime.d.ts +52 -0
  26. package/dist/meeting-automation-runtime.js +46 -0
  27. package/dist/queue-task-tools.js +2 -2
  28. package/dist/routine-liveness.js +0 -1
  29. package/dist/routine-runtime.js +1 -1
  30. package/dist/server.d.ts +59 -85
  31. package/dist/server.js +44 -36
  32. package/dist/ssot.js +1 -1
  33. package/dist/testing/queue-task-tools-contract.js +1 -1
  34. package/dist/world-model-impact-index.d.ts +132 -0
  35. package/dist/world-model-impact-index.js +901 -0
  36. package/package.json +6 -18
  37. package/ui/judgment-history.css +13 -0
  38. package/ui/objective-editor.css +19 -2
  39. package/ui/objective-editor.js +6 -3
  40. package/ui/project-workspace.css +33 -26
  41. package/ui/workspace-kit.js +9 -7
  42. package/ui/world/world-view.css +65 -46
  43. package/ui/world/world-view.js +27 -18
  44. package/dist/execution-authority-http.d.ts +0 -30
  45. package/dist/execution-authority-http.js +0 -454
  46. package/dist/execution-authority.d.ts +0 -282
  47. package/dist/execution-authority.js +0 -867
  48. package/dist/resource-reservation-http.d.ts +0 -31
  49. package/dist/resource-reservation-http.js +0 -371
  50. package/dist/resource-reservations.d.ts +0 -221
  51. package/dist/resource-reservations.js +0 -577
@@ -1,867 +0,0 @@
1
- import { createHash } from 'node:crypto';
2
- import { initializePersonalOs, mutatePersonalOsWithSidecar, readPersonalOsSidecar } from './ssot.js';
3
- const ledgerVersion = 1;
4
- const defaultSidecarPath = 'execution-authority/intents.json';
5
- const snapshotIdPattern = /^sha256:[0-9a-f]{64}$/u;
6
- export class ExecutionAuthorityError extends Error {
7
- code;
8
- constructor(code, message) {
9
- super(message);
10
- this.name = 'ExecutionAuthorityError';
11
- this.code = code;
12
- }
13
- }
14
- /**
15
- * Persists the execution intent before crossing either the reservation or
16
- * external-effect boundary. The reservation and intent stores are separate
17
- * transactions; callers must reconcile recovery_required/unknown states.
18
- */
19
- export class ExecutionAuthorityService {
20
- store;
21
- authority;
22
- approval;
23
- constraint;
24
- reservation;
25
- readAccess;
26
- effect;
27
- clock;
28
- constructor(options) {
29
- if (!options.authority || typeof options.authority.verify !== 'function')
30
- throw new TypeError('authority port is required');
31
- if (!options.approval || typeof options.approval.verify !== 'function')
32
- throw new TypeError('approval port is required');
33
- if (!options.constraint || typeof options.constraint.verify !== 'function')
34
- throw new TypeError('constraint port is required');
35
- if (!options.reservation || typeof options.reservation.verify !== 'function' || typeof options.reservation.markStarted !== 'function') {
36
- throw new TypeError('reservation port is required');
37
- }
38
- if (!options.readAccess || typeof options.readAccess.verify !== 'function')
39
- throw new TypeError('read access port is required');
40
- if (options.effect !== undefined && (!options.effect || typeof options.effect.start !== 'function')) {
41
- throw new TypeError('effect port must implement start');
42
- }
43
- if (options.store) {
44
- if (typeof options.store.read !== 'function' || typeof options.store.insert !== 'function' || typeof options.store.update !== 'function') {
45
- throw new TypeError('store must implement read, insert, and update');
46
- }
47
- this.store = options.store;
48
- }
49
- else {
50
- if (!isText(options.dataDir))
51
- throw new TypeError('store or dataDir is required');
52
- this.store = createSidecarExecutionIntentStore({ dataDir: options.dataDir, sidecarPath: options.sidecarPath });
53
- }
54
- this.authority = options.authority;
55
- this.approval = options.approval;
56
- this.constraint = options.constraint;
57
- this.reservation = options.reservation;
58
- this.readAccess = options.readAccess;
59
- this.effect = options.effect;
60
- this.clock = options.clock ?? (() => new Date());
61
- }
62
- async initialize() {
63
- await this.storeCall(async () => { await this.store.initialize?.(); });
64
- }
65
- /** Runs the checks, marks the reservation, and calls the in-process effect port. */
66
- async start(input, options = {}) {
67
- if (!this.effect)
68
- throw new ExecutionAuthorityError('effect_unconfigured', 'This host has no effect port; use register instead');
69
- const normalized = normalizeInput(input);
70
- const attribution = normalizeAttribution(options.attribution, normalized.principal);
71
- const payloadDigest = digest(normalized);
72
- await this.initialize();
73
- await this.verifyReadAccess(normalized);
74
- const existing = await this.findIntent(normalized);
75
- if (existing)
76
- return this.handleExisting(existing, payloadDigest, attribution);
77
- const prepared = await this.prepare(normalized, payloadDigest, attribution, 'start');
78
- if ('replay' in prepared)
79
- return this.handleExisting(prepared.replay, payloadDigest, attribution);
80
- let effectResult;
81
- try {
82
- effectResult = normalizeEffectResult(await this.effect.start({ ...normalized, capability: prepared.capability }));
83
- }
84
- catch {
85
- await this.persistRecovery(normalized, payloadDigest, {
86
- code: 'effect_unknown',
87
- reason: 'effect provider failed after the reservation start boundary',
88
- reservationMark: 'started',
89
- effect: 'unknown',
90
- phase: 'unknown',
91
- });
92
- throw new ExecutionAuthorityError('effect_unknown', 'External effect start is unknown; reconciliation is required');
93
- }
94
- if (effectResult.status !== 'started') {
95
- await this.persistRecovery(normalized, payloadDigest, {
96
- code: 'effect_unknown',
97
- reason: 'effect provider returned an unknown start state',
98
- reservationMark: 'started',
99
- effect: 'unknown',
100
- phase: 'unknown',
101
- });
102
- throw new ExecutionAuthorityError('effect_unknown', 'External effect start is unknown; reconciliation is required');
103
- }
104
- try {
105
- const intent = await this.updateIntent(normalized, payloadDigest, (next) => {
106
- next.phase = 'started';
107
- next.reservationMark = 'started';
108
- next.effect.status = 'started';
109
- });
110
- return {
111
- intent: publicIntent(intent),
112
- effect: { operationId: normalized.operationId, status: 'started' },
113
- replayed: false,
114
- };
115
- }
116
- catch {
117
- throw new ExecutionAuthorityError('recovery_required', 'Effect started but the execution intent could not be finalized');
118
- }
119
- }
120
- /**
121
- * Registers the execution: runs the checks, marks the reservation, and
122
- * issues the permit. The effect owner reports the outcome with reportEffect.
123
- */
124
- async register(input, options = {}) {
125
- const normalized = normalizeInput(input);
126
- const attribution = normalizeAttribution(options.attribution, normalized.principal);
127
- const payloadDigest = digest(normalized);
128
- await this.initialize();
129
- await this.verifyReadAccess(normalized);
130
- const existing = await this.findIntent(normalized);
131
- if (existing)
132
- return this.replayRegistration(existing, payloadDigest, attribution);
133
- const prepared = await this.prepare(normalized, payloadDigest, attribution, 'register');
134
- if ('replay' in prepared)
135
- return this.replayRegistration(prepared.replay, payloadDigest, attribution);
136
- return {
137
- intent: publicIntent(prepared.intent),
138
- capability: clone(prepared.capability),
139
- capabilityDigest: prepared.capabilityDigest,
140
- replayed: false,
141
- };
142
- }
143
- /** Records the effect owner's outcome for a registered execution. */
144
- async reportEffect(report) {
145
- const lookup = normalizeLookup(report);
146
- if (report.status !== 'started' && report.status !== 'unknown') {
147
- throw new ExecutionAuthorityError('validation_error', 'status must be started or unknown');
148
- }
149
- assertText(report.capabilityDigest, 'capabilityDigest');
150
- await this.initialize();
151
- await this.verifyReadAccess(lookup);
152
- const updated = await this.storeCall(() => this.store.update(intentKey(lookup), (current) => {
153
- validateStoredIntent(current);
154
- assertIntentScope(lookup, current);
155
- if (current.capability?.digest !== report.capabilityDigest) {
156
- throw new ExecutionAuthorityError('capability_mismatch', 'The report does not match the issued permit');
157
- }
158
- const next = clone(current);
159
- if (report.status === 'started') {
160
- if (current.phase === 'started')
161
- return current;
162
- if (current.phase !== 'registered' && current.phase !== 'unknown') {
163
- throw new ExecutionAuthorityError('recovery_required', `Operation ${current.operationId} requires reconciliation before a report`);
164
- }
165
- next.phase = 'started';
166
- next.effect.status = 'started';
167
- delete next.failure;
168
- }
169
- else {
170
- if (current.phase === 'unknown')
171
- return current;
172
- if (current.phase === 'started') {
173
- throw new ExecutionAuthorityError('operation_conflict', `Operation ${current.operationId} already reported a started effect`);
174
- }
175
- if (current.phase !== 'registered') {
176
- throw new ExecutionAuthorityError('recovery_required', `Operation ${current.operationId} requires reconciliation before a report`);
177
- }
178
- next.phase = 'unknown';
179
- next.effect.status = 'unknown';
180
- next.failure = { code: 'effect_unknown', reason: 'effect owner reported an unknown outcome' };
181
- }
182
- next.updatedAt = this.now().toISOString();
183
- return next;
184
- }));
185
- if (!updated)
186
- throw new ExecutionAuthorityError('intent_not_found', `Execution intent ${lookup.operationId} was not found`);
187
- validateStoredIntent(updated);
188
- return publicIntent(updated);
189
- }
190
- async readIntent(input) {
191
- const lookup = normalizeLookup(input);
192
- await this.initialize();
193
- await this.verifyReadAccess(lookup);
194
- const intent = await this.findIntent(lookup);
195
- return intent ? publicIntent(intent) : undefined;
196
- }
197
- /**
198
- * Shared path for start and register: initial checks, durable intent,
199
- * fenced final checks, permit, and the reservation mark.
200
- */
201
- async prepare(normalized, payloadDigest, attribution, mode) {
202
- const initial = await this.verifyAll(normalized, 'initial', undefined, attribution);
203
- if (initial.failure)
204
- throw errorFromFailure(initial.failure);
205
- const recorded = await this.recordIntent(normalized, payloadDigest, initial.checks, attribution);
206
- if (!recorded.created)
207
- return { replay: recorded.intent };
208
- const expectedRevisions = Object.fromEntries(initial.checks.map((check) => [check.check, check.revision ?? '']));
209
- const final = await this.verifyAll(normalized, 'final', expectedRevisions, attribution);
210
- if (final.failure) {
211
- await this.tryUpdateIntent(normalized, payloadDigest, (intent) => {
212
- intent.verification.final = final.checks;
213
- intent.phase = 'rejected';
214
- intent.failure = final.failure;
215
- });
216
- throw errorFromFailure(final.failure);
217
- }
218
- if (!final.capability) {
219
- const failure = {
220
- code: 'fencing_unsupported',
221
- reason: 'Final execution checks did not provide a fencing capability',
222
- };
223
- await this.tryUpdateIntent(normalized, payloadDigest, (intent) => {
224
- intent.verification.final = final.checks;
225
- intent.phase = 'rejected';
226
- intent.failure = failure;
227
- });
228
- throw errorFromFailure(failure);
229
- }
230
- const capability = final.capability;
231
- const capabilityDigest = digest(capability);
232
- await this.updateIntent(normalized, payloadDigest, (intent) => {
233
- intent.verification.final = final.checks;
234
- intent.capability = {
235
- expiresAt: capability.expiresAt,
236
- digest: capabilityDigest,
237
- ...(mode === 'register' ? { grant: clone(capability) } : {}),
238
- };
239
- });
240
- let mark;
241
- try {
242
- const reservationCheck = final.checks.find((check) => check.check === 'reservation');
243
- if (!reservationCheck || reservationCheck.status !== 'approved' || reservationCheck.revision === null) {
244
- throw new ExecutionAuthorityError('ledger_invalid', 'Reservation verification did not provide a start fence');
245
- }
246
- mark = normalizeMarkResult(await this.reservation.markStarted({
247
- ...normalized,
248
- expectedRevision: reservationCheck.revision,
249
- }));
250
- }
251
- catch {
252
- await this.persistRecovery(normalized, payloadDigest, {
253
- code: 'reservation_mark_unknown',
254
- reason: 'reservation start mark may have committed before the provider failed',
255
- reservationMark: 'unknown',
256
- effect: 'unknown',
257
- });
258
- throw new ExecutionAuthorityError('reservation_mark_unknown', 'Reservation start could not be determined; reconciliation is required');
259
- }
260
- if (mark.status !== 'started') {
261
- await this.persistRecovery(normalized, payloadDigest, {
262
- code: 'reservation_mark_unknown',
263
- reason: 'reservation provider returned an unknown start state',
264
- reservationMark: 'unknown',
265
- effect: 'unknown',
266
- });
267
- throw new ExecutionAuthorityError('reservation_mark_unknown', 'Reservation start is unknown; reconciliation is required');
268
- }
269
- try {
270
- const intent = await this.updateIntent(normalized, payloadDigest, (next) => {
271
- next.reservationMark = 'started';
272
- if (mode === 'register') {
273
- // The permit is issued; the effect owner has not started yet.
274
- next.phase = 'registered';
275
- next.effect.status = 'not_started';
276
- }
277
- else {
278
- next.phase = 'reservation_marked';
279
- // A crash after this write and during effect.start is ambiguous.
280
- next.effect.status = 'unknown';
281
- }
282
- });
283
- return { intent, capability, capabilityDigest };
284
- }
285
- catch {
286
- throw new ExecutionAuthorityError('recovery_required', 'Reservation started but the execution intent could not be advanced');
287
- }
288
- }
289
- async findIntent(input) {
290
- const intent = await this.storeCall(() => this.store.read(intentKey(input)));
291
- if (!intent)
292
- return undefined;
293
- validateStoredIntent(intent);
294
- assertIntentScope(input, intent);
295
- return clone(intent);
296
- }
297
- async verifyReadAccess(input) {
298
- let result;
299
- try {
300
- result = await this.readAccess.verify({ ...input, phase: 'read' });
301
- }
302
- catch {
303
- result = { status: 'unknown', revision: null };
304
- }
305
- const status = result && typeof result === 'object' && ['approved', 'revoked', 'expired', 'unknown'].includes(result.status)
306
- ? result.status
307
- : 'unknown';
308
- if (status === 'approved')
309
- return;
310
- const code = status === 'revoked' ? 'read_revoked' : status === 'expired' ? 'read_expired' : 'read_unknown';
311
- throw new ExecutionAuthorityError(code, `Current execution intent read access is ${status}`);
312
- }
313
- async recordIntent(input, payloadDigest, checks, attribution) {
314
- const now = this.now().toISOString();
315
- const intent = {
316
- version: ledgerVersion,
317
- operationId: input.operationId,
318
- tenantId: input.tenantId,
319
- principal: input.principal,
320
- scopeId: input.scopeId,
321
- runId: input.runId,
322
- reservationId: input.reservationId,
323
- approvalId: input.approvalId,
324
- authorityRef: input.authorityRef,
325
- constraintRefs: [...input.constraintRefs],
326
- problem: { ...input.problem },
327
- payloadDigest,
328
- ...(attribution ? { attribution: clone(attribution) } : {}),
329
- // This is deliberately a non-replayable durable state. The current
330
- // call may continue in memory; a later caller must reconcile it.
331
- phase: 'recovery_required',
332
- reservationMark: 'not_started',
333
- effect: { operationId: input.operationId, status: 'not_started' },
334
- verification: { initial: clone(checks) },
335
- createdAt: now,
336
- updatedAt: now,
337
- };
338
- const result = await this.storeCall(() => this.store.insert(intent));
339
- validateStoredIntent(result.intent);
340
- if (!result.created) {
341
- assertIntentScope(input, result.intent);
342
- if (result.intent.payloadDigest !== payloadDigest) {
343
- throw new ExecutionAuthorityError('operation_conflict', `Operation ${input.operationId} was already used with a different payload`);
344
- }
345
- }
346
- return { intent: clone(result.intent), created: result.created };
347
- }
348
- async updateIntent(input, payloadDigest, mutation) {
349
- const updated = await this.storeCall(() => this.store.update(intentKey(input), (existing) => {
350
- validateStoredIntent(existing);
351
- assertIntentScope(input, existing);
352
- if (existing.payloadDigest !== payloadDigest) {
353
- throw new ExecutionAuthorityError('operation_conflict', `Operation ${input.operationId} was already used with a different payload`);
354
- }
355
- const nextIntent = clone(existing);
356
- mutation(nextIntent);
357
- nextIntent.updatedAt = this.now().toISOString();
358
- return nextIntent;
359
- }));
360
- if (!updated)
361
- throw new ExecutionAuthorityError('ledger_invalid', `Execution intent ${input.operationId} was not found`);
362
- validateStoredIntent(updated);
363
- return clone(updated);
364
- }
365
- async tryUpdateIntent(input, payloadDigest, mutation) {
366
- try {
367
- await this.updateIntent(input, payloadDigest, mutation);
368
- }
369
- catch {
370
- // The durable recovery_required state is safer than retrying a failed
371
- // cross-store transition. Preserve the original denial to the caller.
372
- }
373
- }
374
- async persistRecovery(input, payloadDigest, options) {
375
- await this.tryUpdateIntent(input, payloadDigest, (intent) => {
376
- intent.phase = options.phase ?? 'recovery_required';
377
- intent.reservationMark = options.reservationMark;
378
- intent.effect.status = options.effect;
379
- intent.failure = { code: options.code, reason: options.reason };
380
- });
381
- }
382
- async verifyAll(input, phase, expectedRevisions, attribution) {
383
- const providers = [
384
- ['authority', this.authority],
385
- ['approval', this.approval],
386
- ['constraint', this.constraint],
387
- ['reservation', this.reservation],
388
- ];
389
- const normalizedChecks = await Promise.all(providers.map(async ([check, provider]) => {
390
- let result;
391
- try {
392
- result = await provider.verify({
393
- ...input,
394
- ...(attribution ? { attribution: clone(attribution) } : {}),
395
- check,
396
- phase,
397
- expectedRevision: expectedRevisions?.[check],
398
- });
399
- }
400
- catch {
401
- result = { status: 'unknown', revision: null };
402
- }
403
- return normalizeCheckResult(check, result);
404
- }));
405
- const checks = normalizedChecks.map(({ record }) => record);
406
- const denied = checks.find((check) => check.status !== 'approved');
407
- if (denied) {
408
- return {
409
- checks,
410
- failure: {
411
- code: checkFailureCode(denied.check, denied.status),
412
- reason: `${denied.check} provider returned ${denied.status}`,
413
- },
414
- };
415
- }
416
- if (expectedRevisions) {
417
- const changed = checks.find((check) => check.revision !== expectedRevisions[check.check]);
418
- if (changed) {
419
- return { checks, failure: { code: 'revision_conflict', reason: `${changed.check} revision changed before execution start` } };
420
- }
421
- }
422
- if (phase !== 'final')
423
- return { checks };
424
- const missingFence = normalizedChecks.find(({ fencingToken, expiresAt }) => fencingToken === null || expiresAt === null);
425
- if (missingFence) {
426
- return { checks, failure: { code: 'fencing_unsupported', reason: `${missingFence.record.check} provider did not return an execution fencing capability` } };
427
- }
428
- const now = this.now();
429
- const expirationTimes = normalizedChecks.map(({ expiresAt }) => Date.parse(expiresAt));
430
- const earliestExpiration = Math.min(...expirationTimes);
431
- if (!Number.isFinite(earliestExpiration) || earliestExpiration <= now.getTime()) {
432
- return { checks, failure: { code: 'capability_expired', reason: 'Execution fencing capability is already expired' } };
433
- }
434
- const capability = {
435
- kind: 'execution-start',
436
- operationId: input.operationId,
437
- tenantId: input.tenantId,
438
- principal: input.principal,
439
- scopeId: input.scopeId,
440
- issuedAt: now.toISOString(),
441
- expiresAt: new Date(earliestExpiration).toISOString(),
442
- ...(attribution ? { attribution: clone(attribution) } : {}),
443
- checks: Object.fromEntries(normalizedChecks.map(({ record, fencingToken, expiresAt }) => [record.check, {
444
- revision: record.revision,
445
- fencingToken: fencingToken,
446
- expiresAt: expiresAt,
447
- }])),
448
- };
449
- return { checks, capability };
450
- }
451
- handleExisting(intent, payloadDigest, attribution) {
452
- assertSameRequest(intent, payloadDigest, attribution);
453
- if (intent.phase === 'started' && intent.effect.status === 'started') {
454
- return {
455
- intent: publicIntent(intent),
456
- effect: { operationId: intent.operationId, status: 'started' },
457
- replayed: true,
458
- };
459
- }
460
- if (intent.phase === 'rejected' && intent.failure)
461
- throw errorFromFailure(intent.failure);
462
- if (intent.phase === 'unknown' && intent.failure?.code === 'effect_unknown') {
463
- throw errorFromFailure(intent.failure);
464
- }
465
- throw new ExecutionAuthorityError('recovery_required', `Operation ${intent.operationId} requires reconciliation before another attempt`);
466
- }
467
- replayRegistration(intent, payloadDigest, attribution) {
468
- assertSameRequest(intent, payloadDigest, attribution);
469
- const grant = intent.capability?.grant;
470
- const replayable = intent.phase === 'registered' || intent.phase === 'started' || intent.phase === 'unknown';
471
- if (replayable && grant && intent.capability) {
472
- if (intent.phase === 'registered' && Date.parse(grant.expiresAt) <= this.now().getTime()) {
473
- throw new ExecutionAuthorityError('capability_expired', `The permit for operation ${intent.operationId} has expired`);
474
- }
475
- return {
476
- intent: publicIntent(intent),
477
- capability: clone(grant),
478
- capabilityDigest: intent.capability.digest,
479
- replayed: true,
480
- };
481
- }
482
- if (intent.phase === 'rejected' && intent.failure)
483
- throw errorFromFailure(intent.failure);
484
- throw new ExecutionAuthorityError('recovery_required', `Operation ${intent.operationId} requires reconciliation before another attempt`);
485
- }
486
- /** Store failures are never success and never switch to another ledger. */
487
- async storeCall(call) {
488
- try {
489
- return await call();
490
- }
491
- catch (error) {
492
- if (error instanceof ExecutionAuthorityError)
493
- throw error;
494
- throw new ExecutionAuthorityError('store_unavailable', 'Execution intent store is unavailable');
495
- }
496
- }
497
- now() {
498
- const now = this.clock();
499
- if (!(now instanceof Date) || !Number.isFinite(now.getTime()))
500
- throw new ExecutionAuthorityError('validation_error', 'Clock returned an invalid date');
501
- return new Date(now);
502
- }
503
- }
504
- /** The default store: a JSON sidecar under the local SSOT lock. */
505
- export function createSidecarExecutionIntentStore(options) {
506
- assertText(options?.dataDir, 'dataDir');
507
- const dataDir = options.dataDir;
508
- const sidecarPath = options.sidecarPath ?? defaultSidecarPath;
509
- assertSidecarPath(sidecarPath);
510
- const findIndex = (ledger, key) => ledger.intents
511
- .findIndex((candidate) => candidate.tenantId === key.tenantId && candidate.operationId === key.operationId);
512
- return {
513
- async initialize() {
514
- await initializePersonalOs(dataDir);
515
- },
516
- async read(key) {
517
- const ledger = parseLedger(await readPersonalOsSidecar(dataDir, sidecarPath));
518
- const index = findIndex(ledger, key);
519
- return index < 0 ? undefined : clone(ledger.intents[index]);
520
- },
521
- async insert(intent) {
522
- return mutatePersonalOsWithSidecar(dataDir, sidecarPath, async (current, sidecarContent) => {
523
- const ledger = parseLedger(sidecarContent);
524
- const index = findIndex(ledger, intent);
525
- if (index >= 0) {
526
- return { next: current, sidecarContent: serializeLedger(ledger), result: { intent: clone(ledger.intents[index]), created: false } };
527
- }
528
- ledger.intents.push(clone(intent));
529
- return { next: current, sidecarContent: serializeLedger(ledger), result: { intent: clone(intent), created: true } };
530
- });
531
- },
532
- async update(key, mutate) {
533
- return mutatePersonalOsWithSidecar(dataDir, sidecarPath, async (current, sidecarContent) => {
534
- const ledger = parseLedger(sidecarContent);
535
- const index = findIndex(ledger, key);
536
- if (index < 0)
537
- return { next: current, sidecarContent: serializeLedger(ledger), result: undefined };
538
- const next = mutate(clone(ledger.intents[index]));
539
- ledger.intents[index] = clone(next);
540
- return { next: current, sidecarContent: serializeLedger(ledger), result: clone(next) };
541
- });
542
- },
543
- };
544
- }
545
- /**
546
- * Binds the existing reservation store to the execution port without calling
547
- * it from inside the execution sidecar transaction. The store remains the
548
- * owner of its current authorization and reservation-state checks.
549
- */
550
- export function createResourceReservationExecutionPort(options) {
551
- if (!options || !options.service || typeof options.service.readLedger !== 'function' || typeof options.service.startExternalAction !== 'function') {
552
- throw new TypeError('resource reservation service is required');
553
- }
554
- return {
555
- async verify(input) {
556
- try {
557
- const snapshot = await options.service.readLedger({
558
- tenantId: input.tenantId,
559
- principal: input.principal,
560
- scopeId: input.scopeId,
561
- });
562
- const reservation = snapshot.reservations.find((candidate) => candidate.reservationId === input.reservationId);
563
- if (!reservation || reservation.state !== 'reserved')
564
- return { status: 'revoked', revision: 'missing' };
565
- const revision = `${reservation.reservationId}:${reservation.updatedAt}`;
566
- if (reservation.externalAction.status !== 'not_started')
567
- return { status: 'unknown', revision };
568
- const expiresAt = reservation.approval.expiresAt;
569
- if (!expiresAt)
570
- return { status: 'unknown', revision };
571
- return {
572
- status: 'approved',
573
- revision,
574
- fencingToken: `reservation:${revision}`,
575
- expiresAt,
576
- };
577
- }
578
- catch {
579
- return { status: 'unknown', revision: null };
580
- }
581
- },
582
- async markStarted(input) {
583
- try {
584
- const snapshot = await options.service.readLedger({
585
- tenantId: input.tenantId,
586
- principal: input.principal,
587
- scopeId: input.scopeId,
588
- });
589
- const reservation = snapshot.reservations.find((candidate) => candidate.reservationId === input.reservationId);
590
- if (!reservation || reservation.state !== 'reserved' || reservation.externalAction.status !== 'not_started') {
591
- return { status: 'unknown' };
592
- }
593
- const currentRevision = `${reservation.reservationId}:${reservation.updatedAt}`;
594
- if (currentRevision !== input.expectedRevision)
595
- return { status: 'unknown' };
596
- const result = await options.service.startExternalAction(toReservationMutationInput(input));
597
- return { status: result.reservation.externalAction.status === 'started' ? 'started' : 'unknown' };
598
- }
599
- catch {
600
- return { status: 'unknown' };
601
- }
602
- },
603
- };
604
- }
605
- function toReservationMutationInput(input) {
606
- return {
607
- operationId: input.operationId,
608
- tenantId: input.tenantId,
609
- principal: input.principal,
610
- scopeId: input.scopeId,
611
- reservationId: input.reservationId,
612
- };
613
- }
614
- function normalizeInput(input) {
615
- if (!input || typeof input !== 'object')
616
- throw new ExecutionAuthorityError('validation_error', 'execution input is required');
617
- assertText(input.operationId, 'operationId');
618
- assertText(input.tenantId, 'tenantId');
619
- assertText(input.principal, 'principal');
620
- assertText(input.scopeId, 'scopeId');
621
- assertText(input.runId, 'runId');
622
- assertText(input.reservationId, 'reservationId');
623
- assertText(input.approvalId, 'approvalId');
624
- assertText(input.authorityRef, 'authorityRef');
625
- if (!Array.isArray(input.constraintRefs))
626
- throw new ExecutionAuthorityError('validation_error', 'constraintRefs must be an array');
627
- const constraintRefs = input.constraintRefs.map((ref, index) => {
628
- assertText(ref, `constraintRefs[${index}]`);
629
- return ref;
630
- });
631
- const problem = normalizeProblem(input.problem);
632
- return {
633
- operationId: input.operationId,
634
- tenantId: input.tenantId,
635
- principal: input.principal,
636
- scopeId: input.scopeId,
637
- runId: input.runId,
638
- reservationId: input.reservationId,
639
- approvalId: input.approvalId,
640
- authorityRef: input.authorityRef,
641
- constraintRefs,
642
- problem,
643
- };
644
- }
645
- const attributionModes = ['person', 'delegated_service', 'service'];
646
- /** Enforces who may appear in which role; a service never passes as the person. */
647
- function normalizeAttribution(value, principal) {
648
- if (value === undefined)
649
- return undefined;
650
- if (!isRecord(value))
651
- throw new ExecutionAuthorityError('validation_error', 'attribution must be an object');
652
- const known = new Set(['mode', 'servicePrincipal', 'delegationRef', 'correlationId']);
653
- if (Object.keys(value).some((key) => !known.has(key))) {
654
- throw new ExecutionAuthorityError('validation_error', 'attribution contains an unknown field');
655
- }
656
- if (!attributionModes.includes(value.mode))
657
- throw new ExecutionAuthorityError('validation_error', 'attribution.mode is invalid');
658
- for (const field of ['servicePrincipal', 'delegationRef', 'correlationId']) {
659
- if (value[field] !== undefined)
660
- assertText(value[field], `attribution.${field}`);
661
- }
662
- if (value.mode === 'person') {
663
- if (value.servicePrincipal !== undefined || value.delegationRef !== undefined) {
664
- throw new ExecutionAuthorityError('validation_error', 'A person attribution cannot carry a service principal or delegation');
665
- }
666
- }
667
- else {
668
- if (value.servicePrincipal === undefined || value.delegationRef === undefined) {
669
- throw new ExecutionAuthorityError('validation_error', `A ${value.mode} attribution requires servicePrincipal and delegationRef`);
670
- }
671
- if (value.mode === 'delegated_service' && value.servicePrincipal === principal) {
672
- throw new ExecutionAuthorityError('validation_error', 'A delegated service must differ from the principal it acts for');
673
- }
674
- if (value.mode === 'service' && value.servicePrincipal !== principal) {
675
- throw new ExecutionAuthorityError('validation_error', 'A service attribution must name the service as the principal');
676
- }
677
- }
678
- return {
679
- mode: value.mode,
680
- ...(value.servicePrincipal !== undefined ? { servicePrincipal: value.servicePrincipal } : {}),
681
- ...(value.delegationRef !== undefined ? { delegationRef: value.delegationRef } : {}),
682
- ...(value.correlationId !== undefined ? { correlationId: value.correlationId } : {}),
683
- };
684
- }
685
- function assertSameRequest(intent, payloadDigest, attribution) {
686
- if (intent.payloadDigest !== payloadDigest || digest(intent.attribution ?? null) !== digest(attribution ?? null)) {
687
- throw new ExecutionAuthorityError('operation_conflict', `Operation ${intent.operationId} was already used with a different payload or attribution`);
688
- }
689
- }
690
- /** Readers see the permit's expiry and digest, never its fencing tokens. */
691
- function publicIntent(intent) {
692
- const next = clone(intent);
693
- if (next.capability)
694
- next.capability = { expiresAt: next.capability.expiresAt, digest: next.capability.digest };
695
- return next;
696
- }
697
- function intentKey(input) {
698
- return { tenantId: input.tenantId, operationId: input.operationId };
699
- }
700
- function normalizeLookup(input) {
701
- if (!input || typeof input !== 'object')
702
- throw new ExecutionAuthorityError('validation_error', 'execution lookup is required');
703
- assertText(input.operationId, 'operationId');
704
- assertText(input.tenantId, 'tenantId');
705
- assertText(input.principal, 'principal');
706
- assertText(input.scopeId, 'scopeId');
707
- return { operationId: input.operationId, tenantId: input.tenantId, principal: input.principal, scopeId: input.scopeId };
708
- }
709
- function normalizeProblem(problem) {
710
- assertText(problem?.problem_snapshot_id, 'problem.problem_snapshot_id');
711
- assertText(problem?.problem_id, 'problem.problem_id');
712
- assertText(problem?.revision, 'problem.revision');
713
- if (!snapshotIdPattern.test(problem.problem_snapshot_id)) {
714
- throw new ExecutionAuthorityError('validation_error', 'problem.problem_snapshot_id must be a sha256 snapshot ID');
715
- }
716
- return {
717
- problem_snapshot_id: problem.problem_snapshot_id,
718
- problem_id: problem.problem_id,
719
- revision: problem.revision,
720
- };
721
- }
722
- function normalizeCheckResult(check, result) {
723
- const status = result && typeof result === 'object' && ['approved', 'revoked', 'expired', 'unknown'].includes(result.status)
724
- ? result.status
725
- : 'unknown';
726
- const revision = typeof result?.revision === 'string' && result.revision.length > 0 ? result.revision : null;
727
- const fencingToken = isText(result?.fencingToken) ? result.fencingToken : null;
728
- const expiresAt = normalizeExpiration(result?.expiresAt);
729
- const evidence = normalizeEvidence(result?.evidence);
730
- if (status === 'approved' && revision === null) {
731
- return {
732
- record: { check, status: 'unknown', revision: null, fencingTokenDigest: fencingToken ? digest(fencingToken) : undefined, expiresAt: expiresAt ?? undefined, evidence },
733
- fencingToken,
734
- expiresAt,
735
- };
736
- }
737
- return {
738
- record: { check, status, revision, fencingTokenDigest: fencingToken ? digest(fencingToken) : undefined, expiresAt: expiresAt ?? undefined, evidence },
739
- fencingToken,
740
- expiresAt,
741
- };
742
- }
743
- function normalizeExpiration(value) {
744
- if (!isText(value))
745
- return null;
746
- const time = Date.parse(value);
747
- return Number.isFinite(time) ? new Date(time).toISOString() : null;
748
- }
749
- function normalizeMarkResult(result) {
750
- if (!result || (result.status !== 'started' && result.status !== 'unknown'))
751
- return { status: 'unknown' };
752
- return { status: result.status };
753
- }
754
- function normalizeEffectResult(result) {
755
- if (!result || (result.status !== 'started' && result.status !== 'unknown'))
756
- return { status: 'unknown' };
757
- return { status: result.status };
758
- }
759
- function normalizeEvidence(evidence) {
760
- if (!evidence || typeof evidence !== 'object' || Array.isArray(evidence))
761
- return {};
762
- const normalized = {};
763
- for (const [key, value] of Object.entries(evidence)) {
764
- if (isText(key) && isText(value))
765
- normalized[key] = value;
766
- }
767
- return normalized;
768
- }
769
- function checkFailureCode(check, status) {
770
- if (status === 'revoked')
771
- return `${check}_revoked`;
772
- if (status === 'expired')
773
- return `${check}_expired`;
774
- return `${check}_unknown`;
775
- }
776
- function errorFromFailure(failure) {
777
- return new ExecutionAuthorityError(failure.code, failure.reason);
778
- }
779
- function assertIntentScope(input, intent) {
780
- if (input.tenantId !== intent.tenantId || input.principal !== intent.principal || input.scopeId !== intent.scopeId) {
781
- throw new ExecutionAuthorityError('scope_mismatch', `Execution intent ${intent.operationId} is outside the requested scope`);
782
- }
783
- }
784
- function parseLedger(content) {
785
- if (!content || content.trim() === '')
786
- return { version: ledgerVersion, intents: [] };
787
- let value;
788
- try {
789
- value = JSON.parse(content);
790
- }
791
- catch {
792
- throw new ExecutionAuthorityError('ledger_invalid', 'Execution intent ledger is not valid JSON');
793
- }
794
- if (!isRecord(value) || value.version !== ledgerVersion || !Array.isArray(value.intents)) {
795
- throw new ExecutionAuthorityError('ledger_invalid', 'Execution intent ledger has an unsupported shape');
796
- }
797
- for (const intent of value.intents)
798
- validateStoredIntent(intent);
799
- return value;
800
- }
801
- function validateStoredIntent(value) {
802
- if (!isRecord(value)
803
- || value.version !== ledgerVersion
804
- || !isText(value.operationId)
805
- || !isText(value.tenantId)
806
- || !isText(value.principal)
807
- || !isText(value.scopeId)
808
- || !isText(value.payloadDigest)
809
- || !['recovery_required', 'reservation_marked', 'registered', 'started', 'unknown', 'rejected'].includes(value.phase)
810
- || !['not_started', 'started', 'unknown'].includes(value.reservationMark)
811
- || !isRecord(value.effect)
812
- || value.effect.operationId !== value.operationId
813
- || !['not_started', 'started', 'unknown'].includes(value.effect.status)
814
- || !isRecord(value.verification)
815
- || !Array.isArray(value.verification.initial)
816
- || !Array.isArray(value.constraintRefs)
817
- || !isRecord(value.problem)
818
- || !isText(value.createdAt)
819
- || !isText(value.updatedAt)) {
820
- throw new ExecutionAuthorityError('ledger_invalid', 'Execution intent ledger contains an invalid record');
821
- }
822
- if (value.attribution !== undefined) {
823
- try {
824
- normalizeAttribution(value.attribution, value.principal);
825
- }
826
- catch {
827
- throw new ExecutionAuthorityError('ledger_invalid', 'Execution intent ledger contains an invalid attribution');
828
- }
829
- }
830
- if (value.capability !== undefined && (!isRecord(value.capability)
831
- || !isText(value.capability.expiresAt)
832
- || !isText(value.capability.digest)
833
- || (value.capability.grant !== undefined && (!isRecord(value.capability.grant) || value.capability.grant.kind !== 'execution-start')))) {
834
- throw new ExecutionAuthorityError('ledger_invalid', 'Execution intent ledger contains an invalid capability');
835
- }
836
- }
837
- function serializeLedger(ledger) {
838
- return `${JSON.stringify(ledger, null, 2)}\n`;
839
- }
840
- function digest(value) {
841
- return createHash('sha256').update(JSON.stringify(sortJson(value))).digest('hex');
842
- }
843
- function sortJson(value) {
844
- if (Array.isArray(value))
845
- return value.map((item) => sortJson(item));
846
- if (!isRecord(value))
847
- return value;
848
- return Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => [key, sortJson(item)]));
849
- }
850
- function assertText(value, label) {
851
- if (!isText(value))
852
- throw new ExecutionAuthorityError('validation_error', `${label} must be a bounded text value`);
853
- }
854
- function isText(value) {
855
- return typeof value === 'string' && value.length > 0 && value.length <= 512 && !/[\u0000-\u001f\u007f]/u.test(value);
856
- }
857
- function assertSidecarPath(path) {
858
- if (!path || path.startsWith('/') || path.includes('\\') || path.split('/').some((part) => !part || part === '.' || part === '..')) {
859
- throw new ExecutionAuthorityError('validation_error', 'sidecarPath must remain relative to the SSOT root');
860
- }
861
- }
862
- function isRecord(value) {
863
- return typeof value === 'object' && value !== null && !Array.isArray(value);
864
- }
865
- function clone(value) {
866
- return structuredClone(value);
867
- }