@moxuli/moremote 0.0.0-stage → 0.1.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 (65) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +31 -0
  3. package/README.md +73 -2
  4. package/bin/moremote-cli.js +34 -0
  5. package/bin/moremote-service.js +7 -0
  6. package/dist/bindings.d.ts +6 -0
  7. package/dist/bindings.js +4 -0
  8. package/dist/cli.d.ts +1 -0
  9. package/dist/cli.js +308 -0
  10. package/dist/cloud-client.d.ts +43 -0
  11. package/dist/cloud-client.js +128 -0
  12. package/dist/config.d.ts +36 -0
  13. package/dist/config.js +68 -0
  14. package/dist/control.d.ts +3 -0
  15. package/dist/control.js +226 -0
  16. package/dist/controls.d.ts +15 -0
  17. package/dist/controls.js +36 -0
  18. package/dist/crypto.d.ts +23 -0
  19. package/dist/crypto.js +68 -0
  20. package/dist/evidence.d.ts +19 -0
  21. package/dist/evidence.js +4 -0
  22. package/dist/journal.d.ts +104 -0
  23. package/dist/journal.js +132 -0
  24. package/dist/limits.d.ts +21 -0
  25. package/dist/limits.js +8 -0
  26. package/dist/official-client.d.ts +120 -0
  27. package/dist/official-client.js +162 -0
  28. package/dist/operations.d.ts +71 -0
  29. package/dist/operations.js +210 -0
  30. package/dist/pairing.d.ts +19 -0
  31. package/dist/pairing.js +68 -0
  32. package/dist/permission.d.ts +9 -0
  33. package/dist/permission.js +66 -0
  34. package/dist/projection.d.ts +24 -0
  35. package/dist/projection.js +35 -0
  36. package/dist/resources.d.ts +76 -0
  37. package/dist/resources.js +299 -0
  38. package/dist/runtime.d.ts +8 -0
  39. package/dist/runtime.js +375 -0
  40. package/dist/service.d.ts +21 -0
  41. package/dist/service.js +310 -0
  42. package/dist/supervisor.d.ts +15 -0
  43. package/dist/supervisor.js +175 -0
  44. package/dist/update-state.d.ts +30 -0
  45. package/dist/update-state.js +158 -0
  46. package/dist/updater.d.ts +9 -0
  47. package/dist/updater.js +152 -0
  48. package/docs/README.md +23 -0
  49. package/docs/STATE.md +132 -0
  50. package/docs/configuration.md +37 -0
  51. package/docs/conventions.md +9 -0
  52. package/docs/decisions/0001-managed-updates.md +19 -0
  53. package/docs/plans/2026-11-10-managed-updates.md +26 -0
  54. package/docs/plans/2026-11-10-notification-delivery.md +118 -0
  55. package/docs/releasing.md +38 -0
  56. package/docs/specs/01-architecture.md +102 -0
  57. package/docs/specs/02-encrypted-delivery.md +194 -0
  58. package/docs/specs/03-api-contract.md +397 -0
  59. package/docs/specs/04-control-and-receipt-lifecycle.md +175 -0
  60. package/docs/specs/05-endpoint-and-lifecycle.md +57 -0
  61. package/docs/specs/06-managed-updates.md +49 -0
  62. package/licenses/Paseo-0.15.3.txt +211 -0
  63. package/package.json +37 -4
  64. package/vectors/bearer-v1.json +6 -0
  65. package/vectors/envelope-v1.json +24 -0
@@ -0,0 +1,226 @@
1
+ import { createServer, createConnection } from 'node:net';
2
+ import { randomBytes, randomUUID, timingSafeEqual, createHash } from 'node:crypto';
3
+ import { join } from 'node:path';
4
+ import { chmodSync, renameSync, readdirSync } from 'node:fs';
5
+ import { assertStateRoot, createPrivateFile, hasCode, inspectResource, inspectRuntime, readRuntimeOwner, readRuntimeRecord, removeOwnedResource, runtimeMatches, RUNTIME_OWNER, sameResource, writePrivateAtomic } from './resources.js';
6
+ export function controlEndpoint(dir) { return process.platform === 'win32' ? '\\\\.\\pipe\\moremote-cli-' + createHash('sha256').update(dir).digest('hex').slice(0, 24) : join(dir, 'runtime.sock'); }
7
+ function object(value) { return typeof value === 'object' && value !== null && !Array.isArray(value); }
8
+ function removeRuntimeFile(path, identity, owner, record = false) {
9
+ try {
10
+ const current = record ? readRuntimeRecord(path) : readRuntimeOwner(path);
11
+ if (!sameResource(current.identity, identity) || !runtimeMatches(current.value, owner))
12
+ return false;
13
+ return removeOwnedResource(path, identity);
14
+ }
15
+ catch {
16
+ return false;
17
+ }
18
+ }
19
+ function running(pid) {
20
+ try {
21
+ process.kill(pid, 0);
22
+ return true;
23
+ }
24
+ catch (error) {
25
+ if (hasCode(error, 'ESRCH'))
26
+ return false;
27
+ throw error;
28
+ }
29
+ }
30
+ export async function requestControl(dir, action) {
31
+ if (!inspectResource(dir, 'directory', true))
32
+ return null;
33
+ if (readdirSync(dir).length === 0)
34
+ return null;
35
+ assertStateRoot(dir);
36
+ const resources = inspectRuntime(dir);
37
+ if (!resources.record)
38
+ return null;
39
+ if (process.platform !== 'win32' && !resources.socket)
40
+ return null;
41
+ const expectedRecord = resources.record.identity;
42
+ const record = resources.record.value;
43
+ const ownerEnded = () => { const path = join(dir, 'runtime.json'); if (!inspectResource(path, 'file', true))
44
+ return true; const current = readRuntimeRecord(path); return !sameResource(current.identity, expectedRecord) || !runtimeMatches(current.value, record); };
45
+ const disconnected = () => { try {
46
+ if (ownerEnded())
47
+ resolve(null);
48
+ else
49
+ reject(Error('CONTROL_CONNECTION_CLOSED'));
50
+ }
51
+ catch (error) {
52
+ reject(error);
53
+ } };
54
+ const { promise, resolve, reject } = Promise.withResolvers();
55
+ const socket = createConnection(controlEndpoint(dir));
56
+ let raw = '';
57
+ socket.setTimeout(2000);
58
+ socket.on('connect', () => {
59
+ try {
60
+ const current = inspectRuntime(dir);
61
+ if (!current.record || !sameResource(current.record.identity, expectedRecord) || !runtimeMatches(current.record.value, record))
62
+ throw Error('RUNTIME_RESOURCE_COLLISION');
63
+ socket.end(JSON.stringify({ token: record.token, action }) + '\n');
64
+ }
65
+ catch (error) {
66
+ socket.destroy(error instanceof Error ? error : Error('CONTROL_INVALID'));
67
+ }
68
+ });
69
+ socket.on('data', chunk => { raw += chunk; if (Buffer.byteLength(raw) > 4096)
70
+ socket.destroy(Error('CONTROL_LIMIT')); });
71
+ socket.on('end', () => { if (!raw) {
72
+ disconnected();
73
+ return;
74
+ } try {
75
+ const value = JSON.parse(raw);
76
+ if (!object(value))
77
+ throw Error('CONTROL_INVALID_RESPONSE');
78
+ resolve(value);
79
+ }
80
+ catch {
81
+ reject(Error('CONTROL_INVALID_RESPONSE'));
82
+ } });
83
+ socket.on('timeout', () => socket.destroy(Error('CONTROL_TIMEOUT')));
84
+ socket.on('error', error => { if (hasCode(error, 'ECONNREFUSED') || hasCode(error, 'ENOENT'))
85
+ resolve(null);
86
+ else if (hasCode(error, 'ECONNRESET') || hasCode(error, 'EPIPE'))
87
+ disconnected();
88
+ else
89
+ reject(error); });
90
+ return promise;
91
+ }
92
+ function closeServer(server) {
93
+ const { promise, resolve } = Promise.withResolvers();
94
+ server.close(() => resolve());
95
+ return promise;
96
+ }
97
+ async function assertPipeAbsent(endpoint) {
98
+ const { promise, resolve, reject } = Promise.withResolvers();
99
+ const socket = createConnection(endpoint);
100
+ socket.setTimeout(2000);
101
+ socket.once('connect', () => { socket.destroy(); reject(Error('RUNTIME_RESOURCE_COLLISION')); });
102
+ socket.once('timeout', () => { socket.destroy(); reject(Error('CONTROL_TIMEOUT')); });
103
+ socket.once('error', error => { if (hasCode(error, 'ENOENT') || hasCode(error, 'ECONNREFUSED'))
104
+ resolve();
105
+ else
106
+ reject(error); });
107
+ return promise;
108
+ }
109
+ export async function ownRuntime(dir, status, stop) {
110
+ assertStateRoot(dir);
111
+ let previous = inspectRuntime(dir);
112
+ const endpoint = controlEndpoint(dir);
113
+ if (process.platform === 'win32' && !previous.lock) {
114
+ await assertPipeAbsent(endpoint);
115
+ previous = inspectRuntime(dir);
116
+ }
117
+ // Validate every collision before replacing any lock, record or socket.
118
+ if (previous.lock && running(previous.lock.value.pid))
119
+ throw Error('CLI_ALREADY_RUNNING');
120
+ if (previous.socket && !previous.record && !(previous.lock?.value.staging && sameResource(previous.socket, previous.lock.value.staging)))
121
+ throw Error('RUNTIME_RESOURCE_COLLISION');
122
+ if (previous.staged) {
123
+ if (!previous.lock)
124
+ throw Error('RUNTIME_UNPROVEN_STAGE');
125
+ const current = readRuntimeOwner(join(dir, 'runtime.lock'));
126
+ if (!sameResource(current.identity, previous.lock.identity) || !runtimeMatches(current.value, previous.lock.value) || !current.value.staging || !sameResource(current.value.staging, previous.staged.identity))
127
+ throw Error('RUNTIME_UNPROVEN_STAGE');
128
+ if (!removeOwnedResource(previous.staged.path, previous.staged.identity, 'socket', false))
129
+ throw Error('RUNTIME_RESOURCE_COLLISION');
130
+ }
131
+ if (previous.socket && !removeOwnedResource(endpoint, previous.socket, 'socket'))
132
+ throw Error('RUNTIME_RESOURCE_COLLISION');
133
+ if (previous.record && !removeRuntimeFile(join(dir, 'runtime.json'), previous.record.identity, previous.record.value, true))
134
+ throw Error('RUNTIME_RESOURCE_COLLISION');
135
+ if (previous.lock && !removeRuntimeFile(join(dir, 'runtime.lock'), previous.lock.identity, previous.lock.value))
136
+ throw Error('RUNTIME_RESOURCE_COLLISION');
137
+ const owner = { owner: RUNTIME_OWNER, version: 1, instanceId: randomUUID(), pid: process.pid, startedAt: Date.now(), token: randomBytes(32).toString('base64url') };
138
+ const lockPath = join(dir, 'runtime.lock'), recordPath = join(dir, 'runtime.json');
139
+ let lock = createPrivateFile(lockPath, JSON.stringify(owner) + '\n');
140
+ const staging = process.platform === 'win32' ? endpoint : join(dir, 's.' + owner.instanceId.slice(0, 8));
141
+ let socketIdentity = null, recordIdentity = null;
142
+ const server = createServer({ allowHalfOpen: true }, socket => {
143
+ let raw = '';
144
+ socket.setTimeout(2000, () => socket.destroy());
145
+ socket.on('error', () => { });
146
+ socket.on('data', chunk => { raw += chunk; if (Buffer.byteLength(raw) > 4096)
147
+ socket.destroy(); });
148
+ socket.on('end', () => {
149
+ try {
150
+ const request = JSON.parse(raw);
151
+ if (!object(request) || typeof request.token !== 'string' || request.token.length !== 43)
152
+ throw Error('CONTROL_AUTH');
153
+ const left = Buffer.from(request.token), right = Buffer.from(owner.token);
154
+ if (left.length !== right.length || !timingSafeEqual(left, right))
155
+ throw Error('CONTROL_AUTH');
156
+ if (request.action === 'stop') {
157
+ socket.end(JSON.stringify({ ok: true, stopping: true }));
158
+ stop();
159
+ }
160
+ else if (request.action === 'status') {
161
+ const value = status();
162
+ if (!object(value))
163
+ throw Error('CONTROL_STATUS');
164
+ socket.end(JSON.stringify({ ok: true, ...value }));
165
+ }
166
+ else
167
+ throw Error('CONTROL_ACTION');
168
+ }
169
+ catch {
170
+ socket.end(JSON.stringify({ ok: false }));
171
+ }
172
+ });
173
+ });
174
+ try {
175
+ if (process.platform !== 'win32' && inspectResource(staging, 'socket', true))
176
+ throw Error('RUNTIME_RESOURCE_COLLISION');
177
+ const { promise, resolve, reject } = Promise.withResolvers();
178
+ server.once('error', reject);
179
+ server.listen(staging, resolve);
180
+ await promise;
181
+ server.removeListener('error', reject);
182
+ if (process.platform !== 'win32') {
183
+ const created = inspectResource(staging, 'socket', false, false);
184
+ if (!created)
185
+ throw Error('RUNTIME_RESOURCE_COLLISION');
186
+ const current = readRuntimeOwner(lockPath);
187
+ if (!sameResource(current.identity, lock) || !runtimeMatches(current.value, owner))
188
+ throw Error('RUNTIME_RESOURCE_COLLISION');
189
+ lock = writePrivateAtomic(lockPath, { ...owner, staging: { dev: created.dev, ino: created.ino } });
190
+ chmodSync(staging, 0o600);
191
+ const secured = inspectResource(staging, 'socket');
192
+ if (!secured || !sameResource(created, secured) || inspectResource(endpoint, 'socket', true))
193
+ throw Error('RUNTIME_RESOURCE_COLLISION');
194
+ // libuv closes/unlinks the bind path, not the public path. A replacement
195
+ // runtime.sock therefore cannot be removed implicitly by server.close().
196
+ renameSync(staging, endpoint);
197
+ socketIdentity = { dev: secured.dev, ino: secured.ino };
198
+ }
199
+ recordIdentity = writePrivateAtomic(recordPath, { ...owner, socket: socketIdentity });
200
+ }
201
+ catch (error) {
202
+ await closeServer(server);
203
+ if (socketIdentity)
204
+ removeOwnedResource(endpoint, socketIdentity, 'socket');
205
+ if (recordIdentity)
206
+ removeRuntimeFile(recordPath, recordIdentity, owner, true);
207
+ removeRuntimeFile(lockPath, lock, owner);
208
+ throw error;
209
+ }
210
+ let closing;
211
+ return () => {
212
+ if (closing)
213
+ return closing;
214
+ if (process.platform !== 'win32' && inspectResource(staging, 'socket', true))
215
+ throw Error('RUNTIME_RESOURCE_COLLISION');
216
+ closing = (async () => {
217
+ await closeServer(server);
218
+ if (socketIdentity)
219
+ removeOwnedResource(endpoint, socketIdentity, 'socket');
220
+ if (recordIdentity)
221
+ removeRuntimeFile(recordPath, recordIdentity, owner, true);
222
+ removeRuntimeFile(lockPath, lock, owner);
223
+ })();
224
+ return closing;
225
+ };
226
+ }
@@ -0,0 +1,15 @@
1
+ import { type Envelope } from './crypto.js';
2
+ import type { Pair } from './config.js';
3
+ import type { OperationJournal } from './journal.js';
4
+ interface Context {
5
+ pair: Pick<Pair, 'pairId' | 'rootKey'>;
6
+ journal: OperationJournal;
7
+ cloud: {
8
+ controlReceipt(id: string, body: {
9
+ envelope: Envelope;
10
+ }): Promise<unknown>;
11
+ };
12
+ }
13
+ export declare function processControl(ctx: Context, input: unknown, now?: number): Promise<string>;
14
+ export declare function retransmitControls(ctx: Context, now?: number): Promise<void>;
15
+ export {};
@@ -0,0 +1,36 @@
1
+ import { openEnvelope, sealEnvelope, decode, validateEnvelope } from './crypto.js';
2
+ import { object, exact, UUID, LIMITS } from './limits.js';
3
+ export async function processControl(ctx, input, now) {
4
+ const clock = now === undefined ? Date.now : () => now;
5
+ now = now ?? clock();
6
+ const e = validateEnvelope(input, now);
7
+ if (e.pairId !== ctx.pair.pairId || e.channel !== 'control')
8
+ throw Error('CONTROL_CONTEXT');
9
+ const payload = object(await openEnvelope(decode(ctx.pair.rootKey, 32), e, now));
10
+ if (payload.type === 'revoke')
11
+ exact(payload, ['type']);
12
+ else if (payload.type === 'cancel') {
13
+ exact(payload, ['type', 'operationId']);
14
+ if (typeof payload.operationId !== 'string' || !UUID.test(payload.operationId))
15
+ throw Error('INVALID_OPERATION_ID');
16
+ }
17
+ else
18
+ throw Error('INVALID_CONTROL');
19
+ if (e.expiresAt <= clock())
20
+ throw Error('EXPIRED_CONTROL');
21
+ ctx.journal.applyControl(e, payload.type, payload.operationId, clock());
22
+ return finishControl(ctx, e.id, clock());
23
+ }
24
+ async function finishControl(ctx, id, now) {
25
+ const record = ctx.journal.control(ctx.pair.pairId, id);
26
+ let receipt = record.receipt;
27
+ if (!receipt) {
28
+ receipt = await sealEnvelope(decode(ctx.pair.rootKey, 32), { version: 1, pairId: ctx.pair.pairId, id, channel: 'controlReceipt', issuedAt: now, expiresAt: now + LIMITS.snapshotMs }, { controlId: id, type: record.type, ...(record.type === 'cancel' ? { operationId: record.operationId } : {}), state: record.state, revision: 1 });
29
+ ctx.journal.controlReceipt(ctx.pair.pairId, id, receipt);
30
+ }
31
+ await ctx.cloud.controlReceipt(id, { envelope: receipt });
32
+ ctx.journal.controlReceiptSent(ctx.pair.pairId, id);
33
+ return record.state;
34
+ }
35
+ export async function retransmitControls(ctx, now = Date.now()) { for (const record of ctx.journal.controlReceipts(ctx.pair.pairId, now))
36
+ await finishControl(ctx, record.id, now); }
@@ -0,0 +1,23 @@
1
+ export type Channel = 'enrollment' | 'activation' | 'command' | 'receipt' | 'state' | 'attention' | 'control' | 'controlReceipt';
2
+ export interface Metadata {
3
+ version: 1;
4
+ pairId: string;
5
+ id: string;
6
+ channel: Channel;
7
+ issuedAt: number;
8
+ expiresAt: number;
9
+ }
10
+ export interface Envelope extends Metadata {
11
+ nonce: string;
12
+ ciphertext: string;
13
+ }
14
+ export declare function decode(value: unknown, length?: number): Buffer<ArrayBuffer>;
15
+ export declare function validateEnvelope(input: unknown, now: number, allowExpired?: boolean): Envelope;
16
+ export declare function deriveKey(root: Uint8Array, pairId: string, channel: Channel | 'presence' | 'requestBinding'): Promise<Uint8Array<ArrayBuffer>>;
17
+ export declare function sealEnvelope(root: Uint8Array, metadata: Metadata, payload: unknown, nonce?: Uint8Array): Promise<Envelope>;
18
+ export declare function openEnvelope(root: Uint8Array, input: unknown, now?: number): Promise<unknown>;
19
+ /** Display only: historical state/attention never authorizes any operation. */
20
+ export declare function openHistoricalSnapshot(root: Uint8Array, input: unknown, now?: number): Promise<unknown>;
21
+ /** Read-only outcome audit. This API can never decode a command or enrollment. */
22
+ export declare function openHistoricalReceipt(root: Uint8Array, input: unknown, now?: number): Promise<unknown>;
23
+ export declare function presenceTopic(root: Uint8Array, pairId: string, agentId: string): Promise<string>;
package/dist/crypto.js ADDED
@@ -0,0 +1,68 @@
1
+ import { webcrypto, randomBytes } from 'node:crypto';
2
+ import { LIMITS, UUID, object, exact } from './limits.js';
3
+ const subtle = webcrypto.subtle;
4
+ const channels = ['enrollment', 'activation', 'command', 'receipt', 'state', 'attention', 'control', 'controlReceipt'];
5
+ function bytes(v) { return Uint8Array.from(v); }
6
+ export function decode(value, length) { if (typeof value !== 'string' || !/^[A-Za-z0-9_-]+$/.test(value))
7
+ throw Error('INVALID_BASE64URL'); const b = Buffer.from(value, 'base64url'); if (b.toString('base64url') !== value || (length !== undefined && b.length !== length))
8
+ throw Error('INVALID_BASE64URL'); return b; }
9
+ export function validateEnvelope(input, now, allowExpired = false) {
10
+ const e = object(input);
11
+ exact(e, ['version', 'pairId', 'id', 'channel', 'issuedAt', 'expiresAt', 'nonce', 'ciphertext']);
12
+ if (Buffer.byteLength(JSON.stringify(e)) > LIMITS.envelopeBytes || e.version !== 1 || typeof e.pairId !== 'string' || !UUID.test(e.pairId) || typeof e.id !== 'string' || !UUID.test(e.id) || !channels.includes(String(e.channel)))
13
+ throw Error('INVALID_ENVELOPE');
14
+ if ((e.channel === 'receipt' || e.channel === 'controlReceipt') && Buffer.byteLength(JSON.stringify(e)) > LIMITS.receiptBytes)
15
+ throw Error('RECEIPT_LIMIT');
16
+ if (!Number.isSafeInteger(e.issuedAt) || !Number.isSafeInteger(e.expiresAt) || Number(e.issuedAt) < 0 || Number(e.expiresAt) <= Number(e.issuedAt))
17
+ throw Error('INVALID_TIME');
18
+ const ttl = e.channel === 'command' || e.channel === 'control' ? LIMITS.commandMs : LIMITS.enrollmentMs;
19
+ if (Number(e.expiresAt) - Number(e.issuedAt) > ttl || Number(e.issuedAt) > now + LIMITS.futureMs || (!allowExpired && Number(e.expiresAt) <= now))
20
+ throw Error('EXPIRED_OR_FUTURE');
21
+ decode(e.nonce, 12);
22
+ const c = decode(e.ciphertext);
23
+ if (c.length < 16 || c.length > LIMITS.plainBytes + 16)
24
+ throw Error('INVALID_CIPHERTEXT');
25
+ return e;
26
+ }
27
+ export async function deriveKey(root, pairId, channel) {
28
+ if (root.length !== 32 || !UUID.test(pairId))
29
+ throw Error('INVALID_KEY_CONTEXT');
30
+ const key = await subtle.importKey('raw', bytes(root), 'HKDF', false, ['deriveBits']);
31
+ return new Uint8Array(await subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: Buffer.from('MoRemote pairing v1'), info: Buffer.from(JSON.stringify([1, pairId, channel])) }, key, 256));
32
+ }
33
+ function aad(m) { return Buffer.from(JSON.stringify([1, m.pairId, m.id, m.channel, m.issuedAt, m.expiresAt])); }
34
+ export async function sealEnvelope(root, metadata, payload, nonce = randomBytes(12)) {
35
+ const plain = Buffer.from(JSON.stringify(payload));
36
+ if (plain.length > LIMITS.plainBytes || nonce.length !== 12)
37
+ throw Error('PAYLOAD_LIMIT');
38
+ const key = await subtle.importKey('raw', bytes(await deriveKey(root, metadata.pairId, metadata.channel)), 'AES-GCM', false, ['encrypt']);
39
+ const encrypted = await subtle.encrypt({ name: 'AES-GCM', iv: bytes(nonce), additionalData: aad(metadata), tagLength: 128 }, key, plain);
40
+ const envelope = { ...metadata, nonce: Buffer.from(nonce).toString('base64url'), ciphertext: Buffer.from(encrypted).toString('base64url') };
41
+ validateEnvelope(envelope, metadata.issuedAt);
42
+ return envelope;
43
+ }
44
+ async function decryptEnvelope(root, e) {
45
+ const key = await subtle.importKey('raw', bytes(await deriveKey(root, e.pairId, e.channel)), 'AES-GCM', false, ['decrypt']);
46
+ const plain = await subtle.decrypt({ name: 'AES-GCM', iv: decode(e.nonce, 12), additionalData: aad(e), tagLength: 128 }, key, decode(e.ciphertext));
47
+ if (plain.byteLength > LIMITS.plainBytes)
48
+ throw Error('PAYLOAD_LIMIT');
49
+ return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(plain));
50
+ }
51
+ export async function openEnvelope(root, input, now = Date.now()) {
52
+ return decryptEnvelope(root, validateEnvelope(input, now));
53
+ }
54
+ /** Display only: historical state/attention never authorizes any operation. */
55
+ export async function openHistoricalSnapshot(root, input, now = Date.now()) {
56
+ const e = validateEnvelope(input, now, true);
57
+ if (e.channel !== 'state' && e.channel !== 'attention')
58
+ throw Error('HISTORICAL_AUTHORITY_REFUSED');
59
+ return decryptEnvelope(root, e);
60
+ }
61
+ /** Read-only outcome audit. This API can never decode a command or enrollment. */
62
+ export async function openHistoricalReceipt(root, input, now = Date.now()) {
63
+ const e = validateEnvelope(input, now, true);
64
+ if (e.channel !== 'receipt' && e.channel !== 'controlReceipt')
65
+ throw Error('HISTORICAL_AUTHORITY_REFUSED');
66
+ return decryptEnvelope(root, e);
67
+ }
68
+ export async function presenceTopic(root, pairId, agentId) { const key = await subtle.importKey('raw', bytes(await deriveKey(root, pairId, 'presence')), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']); return Buffer.from(await subtle.sign('HMAC', key, Buffer.from(agentId))).toString('base64url'); }
@@ -0,0 +1,19 @@
1
+ import type { Command } from './operations.js';
2
+ export type Evidence = ({
3
+ type: 'send';
4
+ serverId: string;
5
+ agentId: string;
6
+ messageId: string;
7
+ textDigest: string;
8
+ } | {
9
+ type: 'permission';
10
+ serverId: string;
11
+ agentId: string;
12
+ requestId: string;
13
+ requestBinding: string;
14
+ responseDigest: string;
15
+ }) & {
16
+ occurrenceId?: string;
17
+ };
18
+ export declare function contentDigest(value: string): string;
19
+ export declare function evidenceForCommand(command: Command, serverId: string): Evidence;
@@ -0,0 +1,4 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { canonical } from './journal.js';
3
+ export function contentDigest(value) { return createHash('sha256').update(value).digest('hex'); }
4
+ export function evidenceForCommand(command, serverId) { return command.type === 'send' ? { type: 'send', serverId, agentId: command.agentId, messageId: command.messageId, textDigest: contentDigest(command.text) } : { type: 'permission', serverId, agentId: command.agentId, requestId: command.requestId, requestBinding: command.requestBinding, responseDigest: contentDigest(canonical(command.response)) }; }
@@ -0,0 +1,104 @@
1
+ import type { Envelope } from './crypto.js';
2
+ import type { Evidence } from './evidence.js';
3
+ export type ReceiptState = 'accepted' | 'resolved' | 'rejected' | 'unknown';
4
+ export interface JournalRecord {
5
+ pairId: string;
6
+ id: string;
7
+ digest: string;
8
+ expiresAt: number;
9
+ state: 'prepared' | 'dispatched' | ReceiptState;
10
+ envelope: Envelope | null;
11
+ receipt: Envelope | null;
12
+ code: string | null;
13
+ revision: number;
14
+ sentRevision: number;
15
+ evidence: Evidence | null;
16
+ }
17
+ export interface Occurrence {
18
+ occurrenceId: string;
19
+ serverId: string;
20
+ agentId: string;
21
+ requestId: string;
22
+ generation: string;
23
+ fingerprint: string;
24
+ active: number;
25
+ createdAt: number;
26
+ }
27
+ export declare function digest(value: unknown): string;
28
+ export declare function canonical(value: unknown): string;
29
+ export declare class OperationJournal {
30
+ private db;
31
+ constructor(path: string);
32
+ get(pairId: string, id: string): JournalRecord | undefined;
33
+ prepare(e: Envelope): {
34
+ record: JournalRecord;
35
+ fresh: boolean;
36
+ };
37
+ dispatched(pairId: string, id: string): void;
38
+ outcome(pairId: string, id: string, state: ReceiptState, receipt: Envelope, code?: string, revision?: number): void;
39
+ pending(pairId: string): JournalRecord[];
40
+ receipts(pairId: string, now: number): JournalRecord[];
41
+ receiptSent(pairId: string, id: string, revision: number): void;
42
+ evidence(pairId: string, id: string, evidence: Evidence): void;
43
+ evidenceOccurrence(pairId: string, id: string, occurrenceId: string): void;
44
+ reconciled(pairId: string, id: string, now: number): void;
45
+ revokePair(pairId: string, now?: number): void;
46
+ pairRevoked(pairId: string): boolean;
47
+ revocationTime(pairId: string): number | undefined;
48
+ retirementDeadline(pairId: string, revokedAt: number): number;
49
+ cleanupRevocations(retainedPairIds: string[], now: number): void;
50
+ blocked(pairId: string, id: string): boolean;
51
+ applyControl(e: Envelope, type: 'cancel' | 'revoke', operationId: string | undefined, now: number): Envelope | null;
52
+ control(pairId: string, id: string): {
53
+ receipt: Envelope | null;
54
+ state: string;
55
+ expiresAt: number;
56
+ type: "cancel" | "revoke";
57
+ operationId: string | null;
58
+ } | undefined;
59
+ controlReceipt(pairId: string, id: string, receipt: Envelope): void;
60
+ controlReceipts(pairId: string, now: number): {
61
+ id: string;
62
+ }[];
63
+ controlReceiptSent(pairId: string, id: string): void;
64
+ observe(serverId: string, agentId: string, generation: string, request: Record<string, unknown>, now?: number): Occurrence;
65
+ currentOccurrence(serverId: string, agentId: string, requestId: string): Occurrence | undefined;
66
+ isCurrent(occurrence: Occurrence): boolean;
67
+ syncRequests(serverId: string, agentId: string, generation: string, requests: {
68
+ id: string;
69
+ }[]): void;
70
+ retire(serverId: string, agentId: string, requestId: string): void;
71
+ retireGeneration(serverId: string, generation: string): void;
72
+ syncAttention(agentId: string, requiresAttention: boolean, timestamp: number | null): void;
73
+ resolution(serverId: string, agentId: string, requestId: string, generation: string, response: unknown, now?: number): void;
74
+ resolutionFacts(serverId: string, agentId: string, requestId: string): (Occurrence & {
75
+ response: string;
76
+ })[];
77
+ queueAttention(pairId: string, id: string, expiresAt: number, body: {
78
+ envelope: Envelope;
79
+ [key: string]: unknown;
80
+ }, event: {
81
+ agentId: string;
82
+ requestId?: string;
83
+ requestBinding?: string;
84
+ }): void;
85
+ attention(pairId: string, now: number): {
86
+ id: string;
87
+ body: any;
88
+ }[];
89
+ attentionSent(pairId: string, id: string): void;
90
+ attentionRecords(pairId: string): {
91
+ id: string;
92
+ agentId: string;
93
+ requestId: string | null;
94
+ requestBinding: string | null;
95
+ }[];
96
+ resolveAttention(pairId: string, id: string, now: number): void;
97
+ attentionResolutions(pairId: string): {
98
+ id: string;
99
+ resolvedAt: number;
100
+ }[];
101
+ attentionResolutionSent(pairId: string, id: string): void;
102
+ cleanup(now: number): void;
103
+ close(): void;
104
+ }
@@ -0,0 +1,132 @@
1
+ import { openOwnedJournal } from './resources.js';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { LIMITS } from './limits.js';
4
+ export function digest(value) { return createHash('sha256').update(JSON.stringify(value)).digest('hex'); }
5
+ export function canonical(value) { if (value === null || typeof value !== 'object')
6
+ return JSON.stringify(value) ?? 'null'; if (Array.isArray(value))
7
+ return '[' + value.map(canonical).join(',') + ']'; return '{' + Object.keys(value).filter(k => value[k] !== undefined).sort().map(k => JSON.stringify(k) + ':' + canonical(value[k])).join(',') + '}'; }
8
+ export class OperationJournal {
9
+ db;
10
+ constructor(path) {
11
+ this.db = openOwnedJournal(path);
12
+ try {
13
+ this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000;
14
+ CREATE TABLE IF NOT EXISTS operations(pairId TEXT NOT NULL,id TEXT NOT NULL,digest TEXT NOT NULL,expiresAt INTEGER NOT NULL,state TEXT NOT NULL,envelope TEXT,receipt TEXT,code TEXT,revision INTEGER NOT NULL DEFAULT 0,evidence TEXT,sentRevision INTEGER NOT NULL DEFAULT 0,reconciledAt INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(pairId,id));
15
+ CREATE TABLE IF NOT EXISTS attention(pairId TEXT NOT NULL,id TEXT NOT NULL,expiresAt INTEGER NOT NULL,body TEXT NOT NULL,sent INTEGER NOT NULL DEFAULT 0,agentId TEXT,requestId TEXT,requestBinding TEXT,resolvedAt INTEGER,resolveSent INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(pairId,id));
16
+ CREATE TABLE IF NOT EXISTS controls(pairId TEXT NOT NULL,id TEXT NOT NULL,digest TEXT NOT NULL,expiresAt INTEGER NOT NULL,receipt TEXT,state TEXT,type TEXT NOT NULL,operationId TEXT,receiptSent INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(pairId,id));
17
+ CREATE TABLE IF NOT EXISTS pair_revocations(pairId TEXT PRIMARY KEY,at INTEGER NOT NULL);
18
+ CREATE TABLE IF NOT EXISTS cancellations(pairId TEXT NOT NULL,id TEXT NOT NULL,at INTEGER NOT NULL,expiresAt INTEGER NOT NULL,PRIMARY KEY(pairId,id));
19
+ CREATE TABLE IF NOT EXISTS occurrences(occurrenceId TEXT PRIMARY KEY,serverId TEXT NOT NULL,agentId TEXT NOT NULL,requestId TEXT NOT NULL,generation TEXT NOT NULL,fingerprint TEXT NOT NULL,active INTEGER NOT NULL,createdAt INTEGER NOT NULL);
20
+ CREATE INDEX IF NOT EXISTS occurrence_current ON occurrences(serverId,agentId,requestId,active);
21
+ CREATE TABLE IF NOT EXISTS resolutions(occurrenceId TEXT PRIMARY KEY,response TEXT NOT NULL,at INTEGER NOT NULL);`);
22
+ }
23
+ catch (error) {
24
+ this.db.close();
25
+ throw error;
26
+ }
27
+ }
28
+ get(pairId, id) { const r = this.db.prepare('SELECT * FROM operations WHERE pairId=? AND id=?').get(pairId, id); return r ? { ...r, envelope: r.envelope ? JSON.parse(r.envelope) : null, receipt: r.receipt ? JSON.parse(r.receipt) : null, evidence: r.evidence ? JSON.parse(r.evidence) : null } : undefined; }
29
+ prepare(e) { const old = this.get(e.pairId, e.id); if (old) {
30
+ if (old.digest !== digest(e))
31
+ throw Error('OPERATION_CONFLICT');
32
+ return { record: old, fresh: false };
33
+ } const count = this.db.prepare('SELECT count(*) AS n FROM operations WHERE pairId=?').get(e.pairId); if (count.n >= LIMITS.operations)
34
+ throw Error('JOURNAL_LIMIT'); this.db.prepare('INSERT INTO operations(pairId,id,digest,expiresAt,state,envelope) VALUES(?,?,?,?,?,?)').run(e.pairId, e.id, digest(e), e.expiresAt, 'prepared', JSON.stringify(e)); return { record: this.get(e.pairId, e.id), fresh: true }; }
35
+ dispatched(pairId, id) { this.db.prepare("UPDATE operations SET state='dispatched' WHERE pairId=? AND id=? AND state='prepared'").run(pairId, id); }
36
+ outcome(pairId, id, state, receipt, code, revision) { const old = this.get(pairId, id); if (!old)
37
+ throw Error('MISSING_OPERATION'); if ((old.state === 'resolved' || old.state === 'rejected') && old.state !== state || old.state === 'accepted' && state === 'unknown')
38
+ throw Error('RECEIPT_REGRESSION'); const next = revision ?? old.revision + 1; if (next <= old.revision)
39
+ throw Error('RECEIPT_REVISION_REGRESSION'); this.db.prepare('UPDATE operations SET state=?,receipt=?,code=?,revision=? WHERE pairId=? AND id=?').run(state, JSON.stringify(receipt), code || null, next, pairId, id); }
40
+ pending(pairId) { return this.db.prepare("SELECT id FROM operations WHERE pairId=? AND state IN ('dispatched','unknown') ORDER BY reconciledAt,expiresAt LIMIT 100").all(pairId).map(r => this.get(pairId, r.id)); }
41
+ receipts(pairId, now) { return this.db.prepare('SELECT id FROM operations WHERE pairId=? AND receipt IS NOT NULL AND revision>sentRevision AND expiresAt>? ORDER BY expiresAt LIMIT 100').all(pairId, now - LIMITS.retentionMs).map(r => this.get(pairId, r.id)); }
42
+ receiptSent(pairId, id, revision) { this.db.prepare('UPDATE operations SET sentRevision=MAX(sentRevision,?) WHERE pairId=? AND id=?').run(revision, pairId, id); }
43
+ evidence(pairId, id, evidence) { this.db.prepare('UPDATE operations SET evidence=? WHERE pairId=? AND id=? AND evidence IS NULL').run(JSON.stringify(evidence), pairId, id); }
44
+ evidenceOccurrence(pairId, id, occurrenceId) { this.db.prepare("UPDATE operations SET evidence=json_set(evidence,'$.occurrenceId',?) WHERE pairId=? AND id=? AND evidence IS NOT NULL").run(occurrenceId, pairId, id); }
45
+ reconciled(pairId, id, now) { this.db.prepare('UPDATE operations SET reconciledAt=? WHERE pairId=? AND id=?').run(now, pairId, id); }
46
+ revokePair(pairId, now = Date.now()) { if (!this.pairRevoked(pairId)) {
47
+ const count = this.db.prepare('SELECT count(*) AS n FROM pair_revocations').get();
48
+ if (count.n >= LIMITS.revocations)
49
+ throw Error('REVOCATION_LIMIT');
50
+ } this.db.prepare('INSERT OR IGNORE INTO pair_revocations(pairId,at) VALUES(?,?)').run(pairId, now); }
51
+ pairRevoked(pairId) { return !!this.db.prepare('SELECT pairId FROM pair_revocations WHERE pairId=?').get(pairId); }
52
+ revocationTime(pairId) { return this.db.prepare('SELECT at FROM pair_revocations WHERE pairId=?').get(pairId)?.at; }
53
+ retirementDeadline(pairId, revokedAt) { const child = this.db.prepare('SELECT MAX(expiresAt) AS latest FROM (SELECT expiresAt FROM operations WHERE pairId=? UNION ALL SELECT expiresAt FROM controls WHERE pairId=? UNION ALL SELECT expiresAt FROM attention WHERE pairId=? UNION ALL SELECT expiresAt FROM cancellations WHERE pairId=?)').get(pairId, pairId, pairId, pairId); return Math.max(revokedAt, child.latest ?? 0) + LIMITS.retentionMs; }
54
+ cleanupRevocations(retainedPairIds, now) { for (const row of this.db.prepare('SELECT pairId,at FROM pair_revocations').all())
55
+ if (!retainedPairIds.includes(row.pairId) && this.retirementDeadline(row.pairId, row.at) <= now)
56
+ this.db.prepare('DELETE FROM pair_revocations WHERE pairId=?').run(row.pairId); }
57
+ blocked(pairId, id) { return this.pairRevoked(pairId) || !!this.db.prepare('SELECT id FROM cancellations WHERE pairId=? AND id=?').get(pairId, id); }
58
+ applyControl(e, type, operationId, now) {
59
+ const old = this.db.prepare('SELECT digest,receipt FROM controls WHERE pairId=? AND id=?').get(e.pairId, e.id);
60
+ if (old) {
61
+ if (old.digest !== digest(e))
62
+ throw Error('CONTROL_CONFLICT');
63
+ return old.receipt ? JSON.parse(old.receipt) : null;
64
+ }
65
+ const count = this.db.prepare('SELECT count(*) AS n FROM controls WHERE pairId=?').get(e.pairId);
66
+ if (count.n >= LIMITS.operations)
67
+ throw Error('CONTROL_LIMIT');
68
+ this.db.exec('BEGIN IMMEDIATE');
69
+ try {
70
+ let state;
71
+ if (type === 'revoke') {
72
+ this.revokePair(e.pairId, now);
73
+ state = 'revoked';
74
+ }
75
+ else {
76
+ const operation = this.get(e.pairId, operationId);
77
+ state = operation && operation.state !== 'prepared' ? 'tooLate' : 'cancelled';
78
+ if (state === 'cancelled')
79
+ this.db.prepare('INSERT OR IGNORE INTO cancellations(pairId,id,at,expiresAt) VALUES(?,?,?,?)').run(e.pairId, operationId, now, e.expiresAt);
80
+ }
81
+ this.db.prepare('INSERT INTO controls(pairId,id,digest,expiresAt,state,type,operationId) VALUES(?,?,?,?,?,?,?)').run(e.pairId, e.id, digest(e), e.expiresAt, state, type, operationId || null);
82
+ this.db.exec('COMMIT');
83
+ }
84
+ catch (error) {
85
+ this.db.exec('ROLLBACK');
86
+ throw error;
87
+ }
88
+ return null;
89
+ }
90
+ control(pairId, id) { const r = this.db.prepare('SELECT state,receipt,expiresAt,type,operationId FROM controls WHERE pairId=? AND id=?').get(pairId, id); return r ? { ...r, receipt: r.receipt ? JSON.parse(r.receipt) : null } : undefined; }
91
+ controlReceipt(pairId, id, receipt) { this.db.prepare('UPDATE controls SET receipt=? WHERE pairId=? AND id=? AND receipt IS NULL').run(JSON.stringify(receipt), pairId, id); }
92
+ controlReceipts(pairId, now) { return this.db.prepare('SELECT id FROM controls WHERE pairId=? AND receiptSent=0 AND expiresAt>? LIMIT 100').all(pairId, now - LIMITS.retentionMs); }
93
+ controlReceiptSent(pairId, id) { this.db.prepare('UPDATE controls SET receiptSent=1 WHERE pairId=? AND id=?').run(pairId, id); }
94
+ observe(serverId, agentId, generation, request, now = Date.now()) { const requestId = String(request.id); const fingerprint = digest(canonical(request)); const old = this.currentOccurrence(serverId, agentId, requestId); if (old && old.generation === generation && old.fingerprint === fingerprint)
95
+ return old; this.retire(serverId, agentId, requestId); const occurrenceId = randomUUID(); this.db.prepare('INSERT INTO occurrences VALUES(?,?,?,?,?,?,1,?)').run(occurrenceId, serverId, agentId, requestId, generation, fingerprint, now); return this.currentOccurrence(serverId, agentId, requestId); }
96
+ currentOccurrence(serverId, agentId, requestId) { return this.db.prepare('SELECT * FROM occurrences WHERE serverId=? AND agentId=? AND requestId=? AND active=1').get(serverId, agentId, requestId); }
97
+ isCurrent(occurrence) { const current = this.currentOccurrence(occurrence.serverId, occurrence.agentId, occurrence.requestId); return !!current && current.occurrenceId === occurrence.occurrenceId && current.generation === occurrence.generation && current.fingerprint === occurrence.fingerprint; }
98
+ syncRequests(serverId, agentId, generation, requests) { for (const r of this.db.prepare('SELECT requestId,generation FROM occurrences WHERE serverId=? AND agentId=? AND active=1').all(serverId, agentId))
99
+ if (r.generation !== generation || !requests.some(request => request.id === r.requestId))
100
+ this.retire(serverId, agentId, r.requestId); for (const r of requests)
101
+ this.observe(serverId, agentId, generation, r); }
102
+ retire(serverId, agentId, requestId) { this.db.prepare('UPDATE occurrences SET active=0 WHERE serverId=? AND agentId=? AND requestId=?').run(serverId, agentId, requestId); this.db.prepare('UPDATE attention SET resolvedAt=? WHERE agentId=? AND requestId=? AND resolvedAt IS NULL').run(Date.now(), agentId, requestId); }
103
+ retireGeneration(serverId, generation) { for (const r of this.db.prepare('SELECT agentId,requestId FROM occurrences WHERE serverId=? AND generation!=? AND active=1').all(serverId, generation))
104
+ this.retire(serverId, r.agentId, r.requestId); }
105
+ syncAttention(agentId, requiresAttention, timestamp) { if (!requiresAttention)
106
+ this.db.prepare('UPDATE attention SET resolvedAt=? WHERE agentId=? AND resolvedAt IS NULL').run(Date.now(), agentId);
107
+ else if (timestamp !== null)
108
+ this.db.prepare("UPDATE attention SET resolvedAt=? WHERE agentId=? AND requestId IS NULL AND resolvedAt IS NULL AND body!='' AND json_extract(body,'$.envelope.issuedAt')!=?").run(Date.now(), agentId, timestamp); }
109
+ resolution(serverId, agentId, requestId, generation, response, now = Date.now()) { const occurrence = this.currentOccurrence(serverId, agentId, requestId); if (occurrence?.generation === generation)
110
+ this.db.prepare('INSERT OR IGNORE INTO resolutions VALUES(?,?,?)').run(occurrence.occurrenceId, createHash('sha256').update(canonical(response)).digest('hex'), now); this.retire(serverId, agentId, requestId); }
111
+ resolutionFacts(serverId, agentId, requestId) { return this.db.prepare('SELECT o.*,r.response FROM occurrences o JOIN resolutions r USING(occurrenceId) WHERE serverId=? AND agentId=? AND requestId=?').all(serverId, agentId, requestId); }
112
+ queueAttention(pairId, id, expiresAt, body, event) { const old = this.db.prepare('SELECT id FROM attention WHERE pairId=? AND id=?').get(pairId, id); if (old)
113
+ return; const count = this.db.prepare('SELECT count(*) AS n FROM attention WHERE pairId=?').get(pairId); if (count.n >= LIMITS.attention)
114
+ throw Error('ATTENTION_LIMIT'); this.db.prepare('INSERT INTO attention(pairId,id,expiresAt,body,agentId,requestId,requestBinding) VALUES(?,?,?,?,?,?,?)').run(pairId, id, expiresAt, JSON.stringify(body), event.agentId, event.requestId || null, event.requestBinding || null); }
115
+ attention(pairId, now) { return this.db.prepare('SELECT id,body FROM attention WHERE pairId=? AND expiresAt>? AND sent=0 AND resolvedAt IS NULL LIMIT 50').all(pairId, now).map(r => ({ id: r.id, body: JSON.parse(r.body) })); }
116
+ attentionSent(pairId, id) { this.db.prepare('UPDATE attention SET sent=1 WHERE pairId=? AND id=?').run(pairId, id); }
117
+ attentionRecords(pairId) { return this.db.prepare('SELECT id,agentId,requestId,requestBinding FROM attention WHERE pairId=? AND resolvedAt IS NULL').all(pairId); }
118
+ resolveAttention(pairId, id, now) { this.db.prepare('UPDATE attention SET resolvedAt=? WHERE pairId=? AND id=? AND resolvedAt IS NULL').run(now, pairId, id); }
119
+ attentionResolutions(pairId) { return this.db.prepare('SELECT id,resolvedAt FROM attention WHERE pairId=? AND resolvedAt IS NOT NULL AND resolveSent=0 LIMIT 100').all(pairId); }
120
+ attentionResolutionSent(pairId, id) { this.db.prepare('UPDATE attention SET resolveSent=1 WHERE pairId=? AND id=?').run(pairId, id); }
121
+ cleanup(now) {
122
+ this.db.prepare('UPDATE operations SET envelope=NULL WHERE expiresAt<=?').run(now);
123
+ this.db.prepare('DELETE FROM operations WHERE expiresAt<?').run(now - LIMITS.retentionMs);
124
+ this.db.prepare("UPDATE attention SET body='' WHERE expiresAt<=?").run(now);
125
+ this.db.prepare('DELETE FROM attention WHERE expiresAt<?').run(now - LIMITS.retentionMs);
126
+ this.db.prepare('DELETE FROM controls WHERE expiresAt<?').run(now - LIMITS.retentionMs);
127
+ this.db.prepare('DELETE FROM cancellations WHERE expiresAt<?').run(now - LIMITS.retentionMs);
128
+ this.db.prepare("DELETE FROM resolutions WHERE at<? AND NOT EXISTS(SELECT 1 FROM operations WHERE json_extract(evidence,'$.occurrenceId')=resolutions.occurrenceId)").run(now - LIMITS.retentionMs);
129
+ this.db.prepare("DELETE FROM occurrences WHERE active=0 AND createdAt<? AND NOT EXISTS(SELECT 1 FROM resolutions WHERE resolutions.occurrenceId=occurrences.occurrenceId) AND NOT EXISTS(SELECT 1 FROM operations WHERE json_extract(evidence,'$.occurrenceId')=occurrences.occurrenceId)").run(now - LIMITS.retentionMs);
130
+ }
131
+ close() { this.db.close(); }
132
+ }