@dsh-ray/assistant-delivery 0.2.4 → 0.3.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 (79) hide show
  1. package/README.md +15 -2
  2. package/cordis.patch.yml +0 -2
  3. package/lib/agent-runtime.d.ts +15 -0
  4. package/lib/agent-runtime.d.ts.map +1 -1
  5. package/lib/agent-runtime.js +446 -51
  6. package/lib/agent-runtime.js.map +1 -1
  7. package/lib/attention-audit-store.d.ts +2 -1
  8. package/lib/attention-audit-store.d.ts.map +1 -1
  9. package/lib/attention-audit-store.js +3 -0
  10. package/lib/attention-audit-store.js.map +1 -1
  11. package/lib/coordinator.d.ts +21 -1
  12. package/lib/coordinator.d.ts.map +1 -1
  13. package/lib/coordinator.js +255 -68
  14. package/lib/coordinator.js.map +1 -1
  15. package/lib/feedback-command.d.ts +1 -0
  16. package/lib/feedback-command.d.ts.map +1 -1
  17. package/lib/feedback-command.js +1 -1
  18. package/lib/feedback-command.js.map +1 -1
  19. package/lib/index.d.ts +2 -1
  20. package/lib/index.d.ts.map +1 -1
  21. package/lib/index.js +1 -0
  22. package/lib/index.js.map +1 -1
  23. package/lib/interrupted-notices.d.ts +20 -5
  24. package/lib/interrupted-notices.d.ts.map +1 -1
  25. package/lib/interrupted-notices.js +238 -24
  26. package/lib/interrupted-notices.js.map +1 -1
  27. package/lib/learning-command.d.ts +2 -0
  28. package/lib/learning-command.d.ts.map +1 -1
  29. package/lib/learning-command.js +2 -0
  30. package/lib/learning-command.js.map +1 -1
  31. package/lib/native-web-owner.d.ts +12 -0
  32. package/lib/native-web-owner.d.ts.map +1 -1
  33. package/lib/native-web-owner.js +653 -80
  34. package/lib/native-web-owner.js.map +1 -1
  35. package/lib/operator-snapshot.d.ts +1 -1
  36. package/lib/operator-snapshot.d.ts.map +1 -1
  37. package/lib/operator-snapshot.js +6 -5
  38. package/lib/operator-snapshot.js.map +1 -1
  39. package/lib/ray-worker-runtime.d.ts +192 -0
  40. package/lib/ray-worker-runtime.d.ts.map +1 -0
  41. package/lib/ray-worker-runtime.js +1300 -0
  42. package/lib/ray-worker-runtime.js.map +1 -0
  43. package/lib/service.d.ts +286 -3
  44. package/lib/service.d.ts.map +1 -1
  45. package/lib/service.js +1608 -72
  46. package/lib/service.js.map +1 -1
  47. package/lib/session-commands.d.ts +6 -0
  48. package/lib/session-commands.d.ts.map +1 -1
  49. package/lib/session-commands.js +14 -0
  50. package/lib/session-commands.js.map +1 -1
  51. package/lib/session-lease-runtime.d.ts +31 -6
  52. package/lib/session-lease-runtime.d.ts.map +1 -1
  53. package/lib/session-lease-runtime.js +553 -43
  54. package/lib/session-lease-runtime.js.map +1 -1
  55. package/lib/sqlite.d.ts +1 -1
  56. package/lib/sqlite.d.ts.map +1 -1
  57. package/lib/sqlite.js +83 -3
  58. package/lib/sqlite.js.map +1 -1
  59. package/lib/store.d.ts +93 -2
  60. package/lib/store.d.ts.map +1 -1
  61. package/lib/store.js +695 -24
  62. package/lib/store.js.map +1 -1
  63. package/lib/tools.d.ts.map +1 -1
  64. package/lib/tools.js +319 -0
  65. package/lib/tools.js.map +1 -1
  66. package/lib/version-query.d.ts.map +1 -1
  67. package/lib/version-query.js +109 -20
  68. package/lib/version-query.js.map +1 -1
  69. package/lib/version.d.ts +1 -1
  70. package/lib/version.js +1 -1
  71. package/lib/work-item-feedback-store.d.ts +2 -1
  72. package/lib/work-item-feedback-store.d.ts.map +1 -1
  73. package/lib/work-item-feedback-store.js +1 -0
  74. package/lib/work-item-feedback-store.js.map +1 -1
  75. package/lib/work-item-replies-store.d.ts +2 -1
  76. package/lib/work-item-replies-store.d.ts.map +1 -1
  77. package/lib/work-item-replies-store.js +3 -0
  78. package/lib/work-item-replies-store.js.map +1 -1
  79. package/package.json +11 -11
package/lib/store.js CHANGED
@@ -2,7 +2,7 @@ import { WorkItemFeedbackStore } from './work-item-feedback-store.js';
2
2
  import { AttentionAuditStore } from './attention-audit-store.js';
3
3
  import { WorkItemRepliesStore } from './work-item-replies-store.js';
4
4
  import { normalizeForegroundTerminationObservation } from './foreground-termination.js';
5
- import { INTERRUPTED_INBOX_NOTICE_FAILURE_CODES, isNotifiableInterruptedFailureCode, } from './interrupted-notices.js';
5
+ import { INTERRUPTED_INBOX_NOTICE_FAILURE_CODES, isNotifiableInterruptedFailureCode, normalizeInterruptedTurnMutationSummary, } from './interrupted-notices.js';
6
6
  import { createHash, randomBytes, randomUUID, scryptSync, timingSafeEqual } from 'node:crypto';
7
7
  import { isAbsolute } from 'node:path';
8
8
  import { acceptanceCanonicalJson } from '@dsh-ray/task-acceptance-contract';
@@ -40,6 +40,28 @@ function foregroundSourceText(text, limit) {
40
40
  return Object.freeze({ text: bytes.subarray(0, end).toString('utf8'), fullTextDigest: createHash('sha256').update(bytes).digest('hex'),
41
41
  returnedBytes: end, fullBytes: bytes.length, truncated: end < bytes.length });
42
42
  }
43
+ function ownerCanonicalSessionFromRow(row) {
44
+ let converged = [];
45
+ try {
46
+ const parsed = JSON.parse(row.converged_from_sessions_json);
47
+ if (Array.isArray(parsed))
48
+ converged = parsed.filter((x) => typeof x === 'string');
49
+ }
50
+ catch { /* ignore */ }
51
+ return Object.freeze({
52
+ id: row.id,
53
+ rootOwnerId: row.root_owner_id,
54
+ workspace: row.workspace,
55
+ agentPreset: row.agent_preset,
56
+ canonicalSessionId: row.canonical_session_id,
57
+ generation: row.generation,
58
+ primaryBindingId: row.primary_binding_id,
59
+ convergedFromSessions: Object.freeze(converged),
60
+ createdAt: row.created_at,
61
+ updatedAt: row.updated_at,
62
+ version: row.version,
63
+ });
64
+ }
43
65
  export class DeliveryStoreError extends Error {
44
66
  code;
45
67
  constructor(code, message) {
@@ -1401,6 +1423,7 @@ export class DeliveryStore {
1401
1423
  workItemFeedback;
1402
1424
  attentionAudit;
1403
1425
  database;
1426
+ databasePath;
1404
1427
  /** Scan position only; every candidate is authorized again before a provider retry. */
1405
1428
  progressRecoveryCursors = new Map();
1406
1429
  databaseInstanceId;
@@ -1408,15 +1431,20 @@ export class DeliveryStore {
1408
1431
  codeGenerator;
1409
1432
  maxTextBytes;
1410
1433
  closed = false;
1434
+ reloading = false;
1411
1435
  writerTransactionActive = false;
1412
1436
  constructor(options) {
1413
- this.database = openDeliveryDatabase(options.path);
1437
+ this.databasePath = options.path;
1438
+ this.database = openDeliveryDatabase(this.databasePath);
1414
1439
  this.now = options.now ?? Date.now;
1415
1440
  this.codeGenerator = options.codeGenerator ?? (() => randomBytes(5).toString('hex').toUpperCase());
1416
1441
  this.maxTextBytes = options.maxTextBytes ?? 65_536;
1417
1442
  this.workItemReplies = new WorkItemRepliesStore(this.database, operation => this.transaction(operation), id => this.getInbox(id), id => this.getBinding(id), id => this.getOutbox(id), binding => this.getPrincipal(binding.principal));
1418
1443
  this.workItemFeedback = new WorkItemFeedbackStore(this.database, operation => this.transaction(operation), id => this.getInbox(id));
1419
1444
  this.attentionAudit = new AttentionAuditStore(this.database, operation => this.writerTransactionActive ? operation() : this.transaction(operation), () => this.now());
1445
+ this.databaseInstanceId = this.initializeInstanceMetadata();
1446
+ }
1447
+ initializeInstanceMetadata() {
1420
1448
  const instance = this.database.prepare(`
1421
1449
  SELECT instance_id FROM delivery_instance WHERE singleton = 1
1422
1450
  `).get();
@@ -1425,11 +1453,10 @@ export class DeliveryStore {
1425
1453
  this.closed = true;
1426
1454
  throw new DeliveryStoreError('conflict', 'delivery database instance namespace is missing or invalid');
1427
1455
  }
1428
- this.databaseInstanceId = instance.instance_id;
1429
1456
  const now = this.now();
1430
1457
  const authorityDigest = growthObjectDigest({
1431
1458
  contract: 'assistant-delivery-workflow-trace-source/v1',
1432
- databaseInstanceId: this.databaseInstanceId,
1459
+ databaseInstanceId: instance.instance_id,
1433
1460
  sourceId: WORKFLOW_TRACE_SOURCE_ID,
1434
1461
  });
1435
1462
  this.database.prepare(`
@@ -1450,6 +1477,41 @@ export class DeliveryStore {
1450
1477
  throw new DeliveryStoreError('conflict', 'workflow trace source authority is missing or stale');
1451
1478
  }
1452
1479
  this.detachLinksOfInactiveOwners(now);
1480
+ return instance.instance_id;
1481
+ }
1482
+ checkpoint() {
1483
+ if (this.closed || this.reloading)
1484
+ return;
1485
+ try {
1486
+ this.database.exec('PRAGMA wal_checkpoint(TRUNCATE);');
1487
+ }
1488
+ catch { }
1489
+ }
1490
+ closeForReload() {
1491
+ if (this.closed || this.reloading)
1492
+ return;
1493
+ this.reloading = true;
1494
+ try {
1495
+ this.database.close();
1496
+ }
1497
+ catch { }
1498
+ }
1499
+ reopen() {
1500
+ if (this.closed)
1501
+ return;
1502
+ if (!this.reloading) {
1503
+ try {
1504
+ this.database.close();
1505
+ }
1506
+ catch { }
1507
+ }
1508
+ this.database = openDeliveryDatabase(this.databasePath);
1509
+ this.workItemReplies.setDatabase(this.database);
1510
+ this.workItemFeedback.setDatabase(this.database);
1511
+ this.attentionAudit.setDatabase(this.database);
1512
+ this.progressRecoveryCursors.clear();
1513
+ this.databaseInstanceId = this.initializeInstanceMetadata();
1514
+ this.reloading = false;
1453
1515
  }
1454
1516
  /**
1455
1517
  * Idempotent startup repair for links written before revoking an owner
@@ -1662,6 +1724,9 @@ export class DeliveryStore {
1662
1724
  SET role = 'owner', status = 'active', linked_to_id = NULL, updated_at = ?, version = version + 1
1663
1725
  WHERE id = ?
1664
1726
  `).run(now, replacement.id);
1727
+ this.database.prepare(`
1728
+ DELETE FROM owner_canonical_sessions WHERE root_owner_id = ?
1729
+ `).run(replacement.id);
1665
1730
  }
1666
1731
  // Revoke every linked identity not explicitly rooted in the replacement.
1667
1732
  // This covers both legacy NULL orphans and identities whose former owner
@@ -1695,6 +1760,9 @@ export class DeliveryStore {
1695
1760
  SET status = 'revoked', updated_at = ?, version = version + 1
1696
1761
  WHERE principal_id = ? AND status = 'active'
1697
1762
  `).run(now, owner.id);
1763
+ this.database.prepare(`
1764
+ DELETE FROM owner_canonical_sessions WHERE root_owner_id = ?
1765
+ `).run(owner.id);
1698
1766
  }
1699
1767
  // A challenge issued before the handoff must not be able to reactivate a
1700
1768
  // retired owner after setup has returned successfully.
@@ -1858,6 +1926,19 @@ export class DeliveryStore {
1858
1926
  `).get(principalHash(input));
1859
1927
  return row === undefined ? undefined : principalFromRow(row);
1860
1928
  }
1929
+ getPrincipalByRecordId(id) {
1930
+ this.assertOpen();
1931
+ const row = this.database.prepare(`
1932
+ SELECT id, principal_json, role, status, linked_to_id, created_at, updated_at, version
1933
+ FROM delivery_principals WHERE id = ?
1934
+ `).get(id);
1935
+ return row === undefined ? undefined : principalFromRow(row);
1936
+ }
1937
+ hasAnyBindings() {
1938
+ this.assertOpen();
1939
+ return this.database.prepare('SELECT 1 FROM conversation_bindings LIMIT 1').get() !== undefined
1940
+ || this.database.prepare('SELECT 1 FROM delivery_principals LIMIT 1').get() !== undefined;
1941
+ }
1861
1942
  getBindingPrincipal(bindingId) {
1862
1943
  const row = this.database.prepare(`
1863
1944
  SELECT principal.id, principal.principal_json, principal.role, principal.status,
@@ -2151,9 +2232,282 @@ export class DeliveryStore {
2151
2232
  });
2152
2233
  }
2153
2234
  getBindingBySession(sessionId) {
2235
+ return this.listBindingsBySession(sessionId)[0];
2236
+ }
2237
+ listBindingsBySession(sessionId) {
2154
2238
  this.assertOpen();
2155
- const row = this.database.prepare(`${bindingSelect} WHERE session_id = ?`).get(sessionId);
2156
- return row === undefined ? undefined : bindingFromRow(row);
2239
+ const rows = this.database.prepare(`
2240
+ SELECT binding.id, binding.conversation_json, binding.principal_json, binding.workspace,
2241
+ binding.agent_preset, binding.session_id, binding.generation, binding.policy_ref,
2242
+ binding.status, binding.created_at, binding.updated_at, binding.version
2243
+ FROM conversation_bindings AS binding
2244
+ LEFT JOIN delivery_principals AS principal ON principal.id = binding.principal_id
2245
+ WHERE binding.session_id = ?
2246
+ ORDER BY
2247
+ CASE WHEN binding.status = 'active' THEN 0 ELSE 1 END,
2248
+ CASE WHEN principal.status = 'active' AND principal.role = 'owner' THEN 0 ELSE 1 END,
2249
+ binding.updated_at DESC,
2250
+ binding.id ASC
2251
+ `).all(sessionId);
2252
+ return rows.map(bindingFromRow);
2253
+ }
2254
+ listActiveOwnerPrincipals() {
2255
+ this.assertOpen();
2256
+ const rows = this.database.prepare(`
2257
+ SELECT id, principal_json, role, status, linked_to_id, created_at, updated_at, version
2258
+ FROM delivery_principals WHERE role = 'owner' AND status = 'active' ORDER BY created_at ASC, id ASC
2259
+ `).all();
2260
+ return rows.map(principalFromRow);
2261
+ }
2262
+ listActiveCanonicalWebPrincipals(rootOwnerId) {
2263
+ this.assertOpen();
2264
+ const rows = this.database.prepare(`
2265
+ SELECT id, principal_json, role, status, linked_to_id, created_at, updated_at, version
2266
+ FROM delivery_principals
2267
+ WHERE status = 'active'
2268
+ AND ((role = 'owner' AND id = ?) OR (role = 'linked' AND linked_to_id = ?))
2269
+ ORDER BY created_at ASC, id ASC
2270
+ `).all(rootOwnerId, rootOwnerId);
2271
+ return rows.map(principalFromRow).filter(p => p.principal.channel === 'web');
2272
+ }
2273
+ resolveCanonicalOwnerRoot(principalInput) {
2274
+ this.assertOpen();
2275
+ if (principalInput === undefined)
2276
+ return undefined;
2277
+ const principal = 'id' in principalInput ? principalInput : this.getPrincipal(principalInput);
2278
+ if (principal?.status !== 'active')
2279
+ return undefined;
2280
+ if (principal.role === 'owner')
2281
+ return principal.id;
2282
+ if (principal.role === 'linked' && principal.principal.channel === 'web' && principal.linkedToId !== undefined) {
2283
+ const root = this.getPrincipalByRecordId(principal.linkedToId);
2284
+ if (root?.status === 'active' && root.role === 'owner')
2285
+ return root.id;
2286
+ }
2287
+ return undefined;
2288
+ }
2289
+ getCanonicalOwnerSession(input) {
2290
+ this.assertOpen();
2291
+ const row = this.database.prepare(`
2292
+ SELECT id, root_owner_id, workspace, agent_preset, canonical_session_id, generation,
2293
+ primary_binding_id, converged_from_sessions_json, created_at, updated_at, version
2294
+ FROM owner_canonical_sessions
2295
+ WHERE root_owner_id = ? AND workspace = ? AND agent_preset = ?
2296
+ `).get(input.rootOwnerId, input.workspace, input.agentPreset);
2297
+ return row === undefined ? undefined : ownerCanonicalSessionFromRow(row);
2298
+ }
2299
+ getCanonicalOwnerSessionBySessionId(sessionId) {
2300
+ this.assertOpen();
2301
+ const row = this.database.prepare(`
2302
+ SELECT id, root_owner_id, workspace, agent_preset, canonical_session_id, generation,
2303
+ primary_binding_id, converged_from_sessions_json, created_at, updated_at, version
2304
+ FROM owner_canonical_sessions
2305
+ WHERE canonical_session_id = ?
2306
+ `).get(sessionId);
2307
+ return row === undefined ? undefined : ownerCanonicalSessionFromRow(row);
2308
+ }
2309
+ listCanonicalOwnerSessions() {
2310
+ this.assertOpen();
2311
+ const rows = this.database.prepare(`
2312
+ SELECT id, root_owner_id, workspace, agent_preset, canonical_session_id, generation,
2313
+ primary_binding_id, converged_from_sessions_json, created_at, updated_at, version
2314
+ FROM owner_canonical_sessions
2315
+ ORDER BY created_at ASC, id ASC
2316
+ `).all();
2317
+ return rows.map(ownerCanonicalSessionFromRow);
2318
+ }
2319
+ ensureCanonicalOwnerSession(input) {
2320
+ this.assertOpen();
2321
+ const workspace = validateBindingText(input.workspace, 'workspace', 4_096);
2322
+ const agentPreset = validateBindingText(input.agentPreset, 'agentPreset', 128);
2323
+ const canonicalSessionId = validateBindingText(input.canonicalSessionId, 'sessionId', 512);
2324
+ const primaryBindingId = validateBindingText(input.primaryBindingId, 'bindingId', 256);
2325
+ const generation = input.generation ?? 1;
2326
+ if (!Number.isSafeInteger(generation) || generation < 1) {
2327
+ throw new DeliveryStoreError('invalid-binding', 'canonical owner session generation is invalid');
2328
+ }
2329
+ return this.transaction(() => {
2330
+ const root = this.getPrincipalByRecordId(input.rootOwnerId);
2331
+ if (root?.status !== 'active' || root.role !== 'owner') {
2332
+ throw new DeliveryStoreError('unauthorized-principal', 'canonical owner root principal is not active owner');
2333
+ }
2334
+ const existing = this.getCanonicalOwnerSession({
2335
+ rootOwnerId: input.rootOwnerId,
2336
+ workspace,
2337
+ agentPreset,
2338
+ });
2339
+ const now = this.now();
2340
+ if (existing !== undefined) {
2341
+ if (input.convergedFromSessions !== undefined && input.convergedFromSessions.length > 0) {
2342
+ const merged = [...new Set([...existing.convergedFromSessions, ...input.convergedFromSessions])];
2343
+ if (merged.length !== existing.convergedFromSessions.length) {
2344
+ this.database.prepare(`
2345
+ UPDATE owner_canonical_sessions
2346
+ SET converged_from_sessions_json = ?, updated_at = ?, version = version + 1
2347
+ WHERE id = ?
2348
+ `).run(JSON.stringify(merged), now, existing.id);
2349
+ return this.getCanonicalOwnerSession({ rootOwnerId: input.rootOwnerId, workspace, agentPreset });
2350
+ }
2351
+ }
2352
+ return existing;
2353
+ }
2354
+ const id = `canon_${randomUUID()}`;
2355
+ const converged = [...new Set(input.convergedFromSessions ?? [])];
2356
+ this.database.prepare(`
2357
+ INSERT INTO owner_canonical_sessions (
2358
+ id, root_owner_id, workspace, agent_preset, canonical_session_id, generation,
2359
+ primary_binding_id, converged_from_sessions_json, created_at, updated_at, version
2360
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
2361
+ `).run(id, input.rootOwnerId, workspace, agentPreset, canonicalSessionId, generation, primaryBindingId, JSON.stringify(converged), now, now);
2362
+ return this.getCanonicalOwnerSession({ rootOwnerId: input.rootOwnerId, workspace, agentPreset });
2363
+ });
2364
+ }
2365
+ addConvergedCanonicalSessions(input) {
2366
+ this.assertOpen();
2367
+ if (input.sessionIds.length === 0) {
2368
+ return this.getCanonicalOwnerSession({
2369
+ rootOwnerId: input.rootOwnerId,
2370
+ workspace: input.workspace,
2371
+ agentPreset: input.agentPreset,
2372
+ });
2373
+ }
2374
+ return this.transaction(() => {
2375
+ const existing = this.getCanonicalOwnerSession({
2376
+ rootOwnerId: input.rootOwnerId,
2377
+ workspace: input.workspace,
2378
+ agentPreset: input.agentPreset,
2379
+ });
2380
+ if (existing === undefined)
2381
+ return undefined;
2382
+ const merged = [...new Set([...existing.convergedFromSessions, ...input.sessionIds.filter(s => s.trim() !== '')])];
2383
+ if (merged.length === existing.convergedFromSessions.length)
2384
+ return existing;
2385
+ this.database.prepare(`
2386
+ UPDATE owner_canonical_sessions
2387
+ SET converged_from_sessions_json = ?, updated_at = ?, version = version + 1
2388
+ WHERE id = ?
2389
+ `).run(JSON.stringify(merged), this.now(), existing.id);
2390
+ return this.getCanonicalOwnerSession({
2391
+ rootOwnerId: input.rootOwnerId,
2392
+ workspace: input.workspace,
2393
+ agentPreset: input.agentPreset,
2394
+ });
2395
+ });
2396
+ }
2397
+ convergeBindingSessionId(bindingId, canonicalSessionId) {
2398
+ this.assertOpen();
2399
+ const cleanId = validateBindingText(bindingId, 'bindingId', 256);
2400
+ const cleanSid = validateBindingText(canonicalSessionId, 'sessionId', 512);
2401
+ return this.transaction(() => {
2402
+ const current = this.getBinding(cleanId);
2403
+ if (current === undefined || current.status !== 'active') {
2404
+ throw new DeliveryStoreError('invalid-binding', 'cannot converge missing or revoked binding');
2405
+ }
2406
+ if (current.sessionId === cleanSid)
2407
+ return current;
2408
+ this.database.prepare(`
2409
+ UPDATE conversation_bindings
2410
+ SET session_id = ?, updated_at = ?, version = version + 1
2411
+ WHERE id = ? AND status = 'active'
2412
+ `).run(cleanSid, this.now(), cleanId);
2413
+ return this.getBinding(cleanId);
2414
+ });
2415
+ }
2416
+ listCanonicalOwnerBindings(input) {
2417
+ this.assertOpen();
2418
+ const active = this.listActiveBindings();
2419
+ return active.filter(binding => binding.workspace === input.workspace
2420
+ && binding.agentPreset === input.agentPreset
2421
+ && this.resolveCanonicalOwnerRoot(binding.principal) === input.rootOwnerId);
2422
+ }
2423
+ isActiveOwnerSession(sessionId) {
2424
+ this.assertOpen();
2425
+ const clean = sessionId.trim();
2426
+ const lower = clean.toLowerCase();
2427
+ if (clean === '' || lower.startsWith('memory-extract-') || lower.startsWith('memory-review-') || clean.startsWith('ray_worker_')) {
2428
+ return false;
2429
+ }
2430
+ const bindings = this.listBindingsBySession(clean);
2431
+ for (const binding of bindings) {
2432
+ if (binding.status !== 'active')
2433
+ continue;
2434
+ const active = this.getActiveBinding(binding.conversation);
2435
+ const principal = this.getPrincipal(binding.principal);
2436
+ if (active?.id === binding.id
2437
+ && principal?.status === 'active'
2438
+ && principal.role === 'owner'
2439
+ && JSON.stringify(principal.principal) === JSON.stringify(binding.principal)) {
2440
+ return true;
2441
+ }
2442
+ }
2443
+ const canonical = this.getCanonicalOwnerSessionBySessionId(clean);
2444
+ if (canonical === undefined)
2445
+ return false;
2446
+ const root = this.getPrincipalByRecordId(canonical.rootOwnerId);
2447
+ if (root?.status !== 'active' || root.role !== 'owner')
2448
+ return false;
2449
+ return bindings.some(binding => {
2450
+ if (binding.status !== 'active' || binding.workspace !== canonical.workspace || binding.agentPreset !== canonical.agentPreset) {
2451
+ return false;
2452
+ }
2453
+ const active = this.getActiveBinding(binding.conversation);
2454
+ return active?.id === binding.id && this.resolveCanonicalOwnerRoot(binding.principal) === root.id;
2455
+ });
2456
+ }
2457
+ rotateCanonicalOwnerSession(input) {
2458
+ this.assertOpen();
2459
+ const nextSessionId = validateBindingText(input.nextSessionId, 'sessionId', 512);
2460
+ return this.transaction(() => this.rotateCanonicalOwnerSessionInTx({ ...input, nextSessionId }));
2461
+ }
2462
+ rotateCanonicalOwnerSessionInTx(input) {
2463
+ const nextSessionId = input.nextSessionId;
2464
+ const existing = this.getCanonicalOwnerSession({
2465
+ rootOwnerId: input.rootOwnerId,
2466
+ workspace: input.workspace,
2467
+ agentPreset: input.agentPreset,
2468
+ });
2469
+ if (existing === undefined)
2470
+ return undefined;
2471
+ const now = this.now();
2472
+ const previousSessionId = existing.canonicalSessionId;
2473
+ const nextPrimaryId = input.nextPrimaryBindingId ?? existing.primaryBindingId;
2474
+ const converged = previousSessionId !== nextSessionId
2475
+ ? [...new Set([...existing.convergedFromSessions, previousSessionId])]
2476
+ : [...existing.convergedFromSessions];
2477
+ this.database.prepare(`
2478
+ UPDATE owner_canonical_sessions
2479
+ SET canonical_session_id = ?, generation = generation + 1, primary_binding_id = ?,
2480
+ converged_from_sessions_json = ?, updated_at = ?, version = version + 1
2481
+ WHERE id = ?
2482
+ `).run(nextSessionId, nextPrimaryId, JSON.stringify(converged), now, existing.id);
2483
+ // Rotate any sibling active canonical bindings still pointing at the old canonical session.
2484
+ const siblings = this.listCanonicalOwnerBindings({
2485
+ rootOwnerId: input.rootOwnerId,
2486
+ workspace: input.workspace,
2487
+ agentPreset: input.agentPreset,
2488
+ }).filter(b => b.sessionId === previousSessionId);
2489
+ for (const sibling of siblings) {
2490
+ const siblingPrincipal = this.getPrincipal(sibling.principal);
2491
+ if (siblingPrincipal?.status !== 'active')
2492
+ continue;
2493
+ const nextGen = this.nextBindingGenerationByHash(conversationHash(sibling.conversation));
2494
+ const nextSiblingId = `binding_${randomUUID()}`;
2495
+ this.database.prepare(`
2496
+ UPDATE conversation_bindings SET status = 'revoked', updated_at = ?, version = version + 1
2497
+ WHERE id = ? AND status = 'active' AND version = ?
2498
+ `).run(now, sibling.id, sibling.version);
2499
+ this.database.prepare(`
2500
+ INSERT INTO conversation_bindings (
2501
+ id, conversation_hash, conversation_json, principal_id, principal_json, workspace, agent_preset,
2502
+ session_id, generation, policy_ref, status, created_at, updated_at, version
2503
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, ?, 1)
2504
+ `).run(nextSiblingId, conversationHash(sibling.conversation), conversationJson(sibling.conversation), siblingPrincipal.id, principalJson(sibling.principal), sibling.workspace, sibling.agentPreset, nextSessionId, nextGen, sibling.policyRef, now, now);
2505
+ }
2506
+ return this.getCanonicalOwnerSession({
2507
+ rootOwnerId: input.rootOwnerId,
2508
+ workspace: input.workspace,
2509
+ agentPreset: input.agentPreset,
2510
+ });
2157
2511
  }
2158
2512
  /** Read one exact Agent owner attestation under a single SQLite snapshot. */
2159
2513
  getPreferencePrincipalForSession(input) {
@@ -2377,6 +2731,23 @@ export class DeliveryStore {
2377
2731
  if (queued.changes !== 1) {
2378
2732
  throw new DeliveryStoreError('conflict', 'new-session command queue transition lost a race');
2379
2733
  }
2734
+ const rootOwnerId = this.resolveCanonicalOwnerRoot(principal);
2735
+ if (rootOwnerId !== undefined) {
2736
+ const canonical = this.getCanonicalOwnerSession({
2737
+ rootOwnerId,
2738
+ workspace: current.workspace,
2739
+ agentPreset: current.agentPreset,
2740
+ });
2741
+ if (canonical !== undefined && canonical.canonicalSessionId === current.sessionId) {
2742
+ this.rotateCanonicalOwnerSessionInTx({
2743
+ rootOwnerId,
2744
+ workspace: current.workspace,
2745
+ agentPreset: current.agentPreset,
2746
+ nextSessionId: sessionId,
2747
+ nextPrimaryBindingId: nextBindingId,
2748
+ });
2749
+ }
2750
+ }
2380
2751
  return {
2381
2752
  binding: this.getBinding(nextBindingId),
2382
2753
  inbox: this.getInbox(inboxId),
@@ -2482,13 +2853,25 @@ export class DeliveryStore {
2482
2853
  SELECT id, principal_json, role, status, linked_to_id, created_at, updated_at, version
2483
2854
  FROM delivery_principals WHERE key_hash = ? AND principal_json = ?
2484
2855
  `).get(principalHash(input.binding.principal), bindingPrincipalJson);
2856
+ const principalAllowed = principal !== undefined
2857
+ && principal.status === 'active'
2858
+ && (principal.role === 'owner'
2859
+ || (principal.role === 'linked'
2860
+ && envelope.channel === 'web'
2861
+ && input.binding.conversation.channel === 'web'
2862
+ && input.binding.principal.channel === 'web'
2863
+ && principal.linked_to_id !== null
2864
+ && (() => {
2865
+ const root = this.getPrincipalByRecordId(principal.linked_to_id);
2866
+ return root?.status === 'active' && root.role === 'owner';
2867
+ })()));
2485
2868
  if (binding === undefined || binding.status !== 'active'
2486
2869
  || binding.version !== input.binding.version || binding.generation !== input.binding.generation
2487
2870
  || binding.session_id !== sessionId || binding.conversation_json !== bindingConversationJson
2488
2871
  || binding.principal_json !== bindingPrincipalJson
2489
2872
  || principal === undefined || principal.id !== bindingPrincipal?.principal_id
2490
2873
  || principal.id !== input.ownerLineage.principalRecordId || principal.version !== input.ownerLineage.principalVersion
2491
- || principal.status !== 'active' || principal.role !== 'owner') {
2874
+ || !principalAllowed) {
2492
2875
  throw new DeliveryStoreError('invalid-binding', 'native Inbox binding is no longer an active owner binding');
2493
2876
  }
2494
2877
  this.database.prepare(`
@@ -2506,6 +2889,15 @@ export class DeliveryStore {
2506
2889
  ) VALUES (?, 'inbox', ?, ?, ?, ?, ?, NULL, ?, ?, ?, 'metadata', NULL, ?)
2507
2890
  `).run(`attachment_${digest(`${id}:${ordinal}:${attachment.providerRef}`).slice(0, 40)}`, id, ordinal, attachment.mediaType ?? '', attachment.sizeBytes ?? 0, descriptorHash, attachment.resourceType, attachment.providerRef, attachment.fileName ?? null, now);
2508
2891
  }
2892
+ const isDirectNativeOwnerTurn = envelope.kind === 'text'
2893
+ || parseDeliveryCommand(envelope)?.name === 'veto';
2894
+ const vetoCommandFilter = `
2895
+ json_extract(earlier.envelope_json, '$.kind') = 'command'
2896
+ AND NOT (
2897
+ lower(ltrim(json_extract(earlier.envelope_json, '$.text'))) = '/veto'
2898
+ OR lower(ltrim(json_extract(earlier.envelope_json, '$.text'))) GLOB '/veto[ '||char(9)||char(10)||char(13)||']*'
2899
+ )
2900
+ `;
2509
2901
  const blocked = this.database.prepare(`
2510
2902
  SELECT 1 FROM inbox_messages AS earlier
2511
2903
  LEFT JOIN conversation_bindings AS earlier_binding ON earlier_binding.id = earlier.binding_id
@@ -2513,7 +2905,8 @@ export class DeliveryStore {
2513
2905
  JOIN delivery_inbox_admissions AS admitted ON admitted.inbox_id = ?
2514
2906
  WHERE earlier.id <> ? AND earlier.status NOT IN ('processed', 'dead_letter')
2515
2907
  AND (
2516
- (earlier_binding.workspace = ? AND earlier_binding.agent_preset = ?
2908
+ earlier_binding.session_id = ?
2909
+ OR (earlier_binding.workspace = ? AND earlier_binding.agent_preset = ?
2517
2910
  AND earlier_binding.principal_id = ?)
2518
2911
  OR (earlier.binding_id IS NULL
2519
2912
  AND json_extract(earlier.envelope_json, '$.conversation') = json(?)
@@ -2521,8 +2914,9 @@ export class DeliveryStore {
2521
2914
  )
2522
2915
  AND (earlier_admission.admission_sequence < admitted.admission_sequence
2523
2916
  OR earlier.status = 'claimed')
2917
+ ${isDirectNativeOwnerTurn ? `AND (${vetoCommandFilter})` : ''}
2524
2918
  LIMIT 1
2525
- `).get(id, id, binding.workspace, binding.agent_preset, principal.id, bindingConversationJson, bindingPrincipalJson);
2919
+ `).get(id, id, sessionId, binding.workspace, binding.agent_preset, principal.id, bindingConversationJson, bindingPrincipalJson);
2526
2920
  if (blocked !== undefined) {
2527
2921
  throw new DeliveryStoreError('conflict', 'native Inbox lane has unfinished earlier or active work');
2528
2922
  }
@@ -3037,10 +3431,15 @@ export class DeliveryStore {
3037
3431
  .run(this.now(), inbox.id);
3038
3432
  }
3039
3433
  const succeeded = inbox.status === 'processed' && execution?.status === 'succeeded' && execution.quiescent === 1;
3434
+ const fallbackFailureCode = inbox.status === 'dead_letter'
3435
+ && isNotifiableInterruptedFailureCode(inbox.failureCode)
3436
+ && inbox.failureCode !== 'dispatch-ambiguous'
3437
+ ? inbox.failureCode
3438
+ : 'INTERRUPTED_RESULT_UNKNOWN';
3040
3439
  const terminal = current.terminal?.kind === 'failed' || current.terminal?.kind === 'paused'
3041
3440
  ? current.terminal
3042
3441
  : succeeded ? { kind: 'completed' }
3043
- : { kind: 'failed', code: 'INTERRUPTED_RESULT_UNKNOWN' };
3442
+ : { kind: 'failed', code: fallbackFailureCode };
3044
3443
  this.database.prepare(`UPDATE delivery_progress SET state = 'pending', terminal_kind = ?, terminal_code = ?,
3045
3444
  step = step + ?, retry_attempts = retry_attempts + 1, next_retry_at = ?, updated_at = ?
3046
3445
  WHERE inbox_id = ? AND state IN ('active', 'pending') AND retry_attempts < 8`).run(terminal.kind, terminal.kind === 'failed' ? terminal.code ?? null : null, row.state === 'active' || row.terminal_kind !== terminal.kind ? 1 : 0, this.now() + Math.min(300_000, 10_000 * (2 ** row.retry_attempts)), this.now(), inbox.id);
@@ -3390,6 +3789,9 @@ export class DeliveryStore {
3390
3789
  throw new DeliveryStoreError('conflict', 'invalid inbox max attempts');
3391
3790
  }
3392
3791
  const maintenanceLimit = boundedMaintenanceLimit(input.maintenanceLimit, input.limit, 'inbox');
3792
+ const excludedSessionsJson = input.excludeSessionIds !== undefined && input.excludeSessionIds.size > 0
3793
+ ? JSON.stringify([...input.excludeSessionIds])
3794
+ : '[]';
3393
3795
  const now = this.now();
3394
3796
  const claims = [];
3395
3797
  this.transaction(() => {
@@ -3415,10 +3817,39 @@ export class DeliveryStore {
3415
3817
  ORDER BY candidate_admission.admission_sequence LIMIT ?
3416
3818
  )
3417
3819
  `).run(now, now, input.maxAttempts, maintenanceLimit);
3820
+ const vetoCandidateExpr = `
3821
+ lower(ltrim(json_extract(candidate.envelope_json, '$.text'))) = '/veto'
3822
+ OR lower(ltrim(json_extract(candidate.envelope_json, '$.text'))) GLOB '/veto[ '||char(9)||char(10)||char(13)||']*'
3823
+ `;
3824
+ const interruptCommandCandidateExpr = `
3825
+ json_extract(candidate.envelope_json, '$.kind') = 'command'
3826
+ AND lower(trim(json_extract(candidate.envelope_json, '$.text'), ' '||char(9)||char(10)||char(13))) IN ('/stop', '/new', '/clear')
3827
+ `;
3828
+ const isDirectOwnerTurnCandidateExpr = `
3829
+ candidate_binding.status = 'active'
3830
+ AND candidate_principal.status = 'active'
3831
+ AND candidate_principal.role = 'owner'
3832
+ AND (
3833
+ json_extract(candidate.envelope_json, '$.kind') = 'text'
3834
+ OR (
3835
+ json_extract(candidate.envelope_json, '$.kind') = 'command'
3836
+ AND (${vetoCandidateExpr})
3837
+ )
3838
+ )
3839
+ `;
3840
+ const nonVetoCommandExpr = (alias) => `
3841
+ json_extract(${alias}.envelope_json, '$.kind') = 'command'
3842
+ AND NOT (
3843
+ lower(ltrim(json_extract(${alias}.envelope_json, '$.text'))) = '/veto'
3844
+ OR lower(ltrim(json_extract(${alias}.envelope_json, '$.text'))) GLOB '/veto[ '||char(9)||char(10)||char(13)||']*'
3845
+ )
3846
+ `;
3418
3847
  const candidates = this.database.prepare(`
3419
3848
  SELECT candidate.id FROM inbox_messages AS candidate
3420
3849
  JOIN conversation_bindings AS candidate_binding
3421
3850
  ON candidate_binding.id = candidate.binding_id
3851
+ JOIN delivery_principals AS candidate_principal
3852
+ ON candidate_principal.id = candidate_binding.principal_id
3422
3853
  JOIN delivery_inbox_admissions AS candidate_admission
3423
3854
  ON candidate_admission.inbox_id = candidate.id
3424
3855
  WHERE candidate.status IN ('queued', 'retry_wait')
@@ -3438,23 +3869,58 @@ export class DeliveryStore {
3438
3869
  ON earlier_binding.id = earlier.binding_id
3439
3870
  JOIN delivery_inbox_admissions AS earlier_admission
3440
3871
  ON earlier_admission.inbox_id = earlier.id
3441
- WHERE earlier_binding.workspace = candidate_binding.workspace
3442
- AND earlier_binding.agent_preset = candidate_binding.agent_preset
3443
- AND earlier_binding.principal_id = candidate_binding.principal_id
3872
+ WHERE (
3873
+ earlier_binding.session_id = candidate_binding.session_id
3874
+ OR (
3875
+ earlier_binding.workspace = candidate_binding.workspace
3876
+ AND earlier_binding.agent_preset = candidate_binding.agent_preset
3877
+ AND earlier_binding.principal_id = candidate_binding.principal_id
3878
+ )
3879
+ )
3444
3880
  AND earlier_admission.admission_sequence < candidate_admission.admission_sequence
3445
3881
  AND earlier.status NOT IN ('processed', 'dead_letter')
3882
+ AND (
3883
+ CASE
3884
+ WHEN earlier_binding.principal_id <> candidate_binding.principal_id THEN (
3885
+ NOT (${isDirectOwnerTurnCandidateExpr} OR (${interruptCommandCandidateExpr}))
3886
+ OR (${nonVetoCommandExpr('earlier')})
3887
+ )
3888
+ ELSE (
3889
+ NOT (${isDirectOwnerTurnCandidateExpr})
3890
+ OR (${nonVetoCommandExpr('earlier')})
3891
+ )
3892
+ END
3893
+ )
3446
3894
  )
3447
3895
  AND NOT EXISTS (
3448
3896
  SELECT 1 FROM inbox_messages AS active
3449
3897
  JOIN conversation_bindings AS active_binding
3450
3898
  ON active_binding.id = active.binding_id
3451
- WHERE active_binding.workspace = candidate_binding.workspace
3452
- AND active_binding.agent_preset = candidate_binding.agent_preset
3453
- AND active_binding.principal_id = candidate_binding.principal_id
3899
+ WHERE (
3900
+ active_binding.session_id = candidate_binding.session_id
3901
+ OR (
3902
+ active_binding.workspace = candidate_binding.workspace
3903
+ AND active_binding.agent_preset = candidate_binding.agent_preset
3904
+ AND active_binding.principal_id = candidate_binding.principal_id
3905
+ )
3906
+ )
3454
3907
  AND active.status = 'claimed'
3908
+ AND (
3909
+ CASE
3910
+ WHEN active_binding.principal_id <> candidate_binding.principal_id THEN (
3911
+ NOT (${isDirectOwnerTurnCandidateExpr} OR (${interruptCommandCandidateExpr}))
3912
+ OR (${nonVetoCommandExpr('active')})
3913
+ )
3914
+ ELSE (
3915
+ NOT (${isDirectOwnerTurnCandidateExpr})
3916
+ OR (${nonVetoCommandExpr('active')})
3917
+ )
3918
+ END
3919
+ )
3455
3920
  )
3921
+ AND (? = '[]' OR candidate_binding.session_id NOT IN (SELECT value FROM json_each(?)))
3456
3922
  ORDER BY candidate_admission.admission_sequence LIMIT ?
3457
- `).all(now, input.maxAttempts, input.limit);
3923
+ `).all(now, input.maxAttempts, excludedSessionsJson, excludedSessionsJson, input.limit);
3458
3924
  for (const candidate of candidates) {
3459
3925
  const current = this.getInbox(candidate.id);
3460
3926
  const previousFence = this.database.prepare('SELECT COALESCE(MAX(fencing_token), 0) AS maximum FROM inbox_attempts WHERE inbox_id = ?')
@@ -3642,7 +4108,19 @@ export class DeliveryStore {
3642
4108
  JOIN delivery_principals AS principal ON principal.id = binding.principal_id
3643
4109
  WHERE inbox.id = ? AND inbox.status = 'claimed' AND inbox.binding_id = ?
3644
4110
  AND binding.status = 'active' AND binding.version = ? AND binding.generation = ?
3645
- AND principal.status = 'active' AND principal.role = 'owner'
4111
+ AND principal.status = 'active'
4112
+ AND (
4113
+ principal.role = 'owner'
4114
+ OR (
4115
+ principal.role = 'linked'
4116
+ AND json_extract(principal.principal_json, '$.channel') = 'web'
4117
+ AND json_extract(binding.conversation_json, '$.channel') = 'web'
4118
+ AND EXISTS (
4119
+ SELECT 1 FROM delivery_principals AS root
4120
+ WHERE root.id = principal.linked_to_id AND root.status = 'active' AND root.role = 'owner'
4121
+ )
4122
+ )
4123
+ )
3646
4124
  AND principal.id = ? AND principal.version = ?
3647
4125
  AND binding.workspace = ? AND binding.agent_preset = ?
3648
4126
  `).get(input.inboxId, input.binding.id, input.binding.version, input.binding.generation, input.owner.principalRecordId, input.owner.principalVersion, input.scope.workspace, input.scope.preset);
@@ -3756,7 +4234,19 @@ export class DeliveryStore {
3756
4234
  AND binding.status = 'active' AND binding.session_id = ?
3757
4235
  AND binding.id = ? AND binding.version = ? AND binding.generation = ?
3758
4236
  AND binding.workspace = ? AND binding.agent_preset = ?
3759
- AND principal.status = 'active' AND principal.role = 'owner'
4237
+ AND principal.status = 'active'
4238
+ AND (
4239
+ principal.role = 'owner'
4240
+ OR (
4241
+ principal.role = 'linked'
4242
+ AND json_extract(principal.principal_json, '$.channel') = 'web'
4243
+ AND json_extract(binding.conversation_json, '$.channel') = 'web'
4244
+ AND EXISTS (
4245
+ SELECT 1 FROM delivery_principals AS root
4246
+ WHERE root.id = principal.linked_to_id AND root.status = 'active' AND root.role = 'owner'
4247
+ )
4248
+ )
4249
+ )
3760
4250
  AND principal.id = ? AND principal.version = ?
3761
4251
  AND execution.workspace = binding.workspace AND execution.preset = binding.agent_preset
3762
4252
  AND execution.principal_record_id = principal.id AND execution.principal_version = principal.version
@@ -3833,7 +4323,19 @@ export class DeliveryStore {
3833
4323
  JOIN delivery_principals AS principal ON principal.id = binding.principal_id
3834
4324
  WHERE inbox.id = ? AND inbox.status = 'claimed' AND inbox.binding_id = ?
3835
4325
  AND binding.status = 'active' AND binding.version = ? AND binding.generation = ?
3836
- AND principal.status = 'active' AND principal.role = 'owner'
4326
+ AND principal.status = 'active'
4327
+ AND (
4328
+ principal.role = 'owner'
4329
+ OR (
4330
+ principal.role = 'linked'
4331
+ AND json_extract(principal.principal_json, '$.channel') = 'web'
4332
+ AND json_extract(binding.conversation_json, '$.channel') = 'web'
4333
+ AND EXISTS (
4334
+ SELECT 1 FROM delivery_principals AS root
4335
+ WHERE root.id = principal.linked_to_id AND root.status = 'active' AND root.role = 'owner'
4336
+ )
4337
+ )
4338
+ )
3837
4339
  AND principal.id = ? AND principal.version = ?
3838
4340
  AND binding.workspace = ? AND binding.agent_preset = ?
3839
4341
  `).get(input.inboxId, input.binding.id, input.binding.version, input.binding.generation, input.owner.principalRecordId, input.owner.principalVersion, input.scope.workspace, input.scope.preset);
@@ -5466,6 +5968,9 @@ export class DeliveryStore {
5466
5968
  UPDATE delivery_principals SET linked_to_id = NULL, updated_at = ?, version = version + 1
5467
5969
  WHERE role = 'linked' AND status = 'active' AND linked_to_id = ?
5468
5970
  `).run(now, id);
5971
+ this.database.prepare(`
5972
+ DELETE FROM owner_canonical_sessions WHERE root_owner_id = ?
5973
+ `).run(id);
5469
5974
  }
5470
5975
  return principalFromRow(row);
5471
5976
  });
@@ -7847,9 +8352,25 @@ export class DeliveryStore {
7847
8352
  // A released construction can outlive a crash before createBinding. Its Session
7848
8353
  // remains owned by the original identity, even though no binding exists yet.
7849
8354
  try {
7850
- if (row.principal_record_id !== authority.id
7851
- || leaseSessionIdentity(JSON.parse(row.target_json)) !== leaseSessionIdentity(target))
7852
- return { kind: 'denied' };
8355
+ const prevTarget = JSON.parse(row.target_json);
8356
+ const exactSameIdentity = row.principal_record_id === authority.id
8357
+ && leaseSessionIdentity(prevTarget) === leaseSessionIdentity(target);
8358
+ if (!exactSameIdentity) {
8359
+ let sharedCanonicalOwner = false;
8360
+ if (target.kind === 'bound') {
8361
+ const canonical = this.getCanonicalOwnerSessionBySessionId(sessionId);
8362
+ const prevPrincipalRecord = this.getPrincipalByRecordId(row.principal_record_id);
8363
+ if (canonical !== undefined
8364
+ && target.binding.workspace === canonical.workspace
8365
+ && target.binding.agentPreset === canonical.agentPreset
8366
+ && this.resolveCanonicalOwnerRoot(authority) === canonical.rootOwnerId
8367
+ && this.resolveCanonicalOwnerRoot(prevPrincipalRecord) === canonical.rootOwnerId) {
8368
+ sharedCanonicalOwner = true;
8369
+ }
8370
+ }
8371
+ if (!sharedCanonicalOwner)
8372
+ return { kind: 'denied' };
8373
+ }
7853
8374
  }
7854
8375
  catch {
7855
8376
  return { kind: 'denied' };
@@ -7983,11 +8504,161 @@ export class DeliveryStore {
7983
8504
  const principal = this.sessionLeaseAuthority(target);
7984
8505
  return principal !== undefined && principal.id === row.principal_record_id && principal.version === row.principal_version ? row : undefined;
7985
8506
  }
8507
+ markGrowthEventEmitted(inboxId, category) {
8508
+ this.assertOpen();
8509
+ this.database.exec(`
8510
+ CREATE TABLE IF NOT EXISTS delivery_growth_emitted (
8511
+ inbox_id TEXT NOT NULL,
8512
+ category TEXT NOT NULL,
8513
+ emitted_at INTEGER NOT NULL,
8514
+ PRIMARY KEY (inbox_id, category)
8515
+ ) STRICT;
8516
+ `);
8517
+ const res = this.database.prepare(`
8518
+ INSERT OR IGNORE INTO delivery_growth_emitted (inbox_id, category, emitted_at)
8519
+ VALUES (?, ?, ?)
8520
+ `).run(inboxId, category, this.now());
8521
+ return Number(res.changes) === 1;
8522
+ }
8523
+ recordInterruptedTurnSummary(input) {
8524
+ this.assertOpen();
8525
+ const summary = normalizeInterruptedTurnMutationSummary(input.summary);
8526
+ if (summary === undefined) {
8527
+ throw new DeliveryStoreError('invalid-intent', 'interrupted turn mutation summary is invalid');
8528
+ }
8529
+ this.database.exec(`
8530
+ CREATE TABLE IF NOT EXISTS delivery_interrupted_turn_summaries (
8531
+ inbox_id TEXT PRIMARY KEY,
8532
+ failure_code TEXT NOT NULL,
8533
+ summary_json TEXT NOT NULL,
8534
+ recorded_at INTEGER NOT NULL
8535
+ ) STRICT;
8536
+ `);
8537
+ this.database.prepare(`
8538
+ INSERT INTO delivery_interrupted_turn_summaries (inbox_id, failure_code, summary_json, recorded_at)
8539
+ VALUES (?, ?, ?, ?)
8540
+ ON CONFLICT(inbox_id) DO UPDATE SET
8541
+ failure_code = excluded.failure_code,
8542
+ summary_json = excluded.summary_json,
8543
+ recorded_at = excluded.recorded_at
8544
+ `).run(input.inboxId, input.failureCode, JSON.stringify(summary), this.now());
8545
+ }
8546
+ getInterruptedTurnSummary(inboxId) {
8547
+ this.assertOpen();
8548
+ const table = this.database.prepare(`SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'delivery_interrupted_turn_summaries'`).get();
8549
+ if (table === undefined)
8550
+ return undefined;
8551
+ const row = this.database.prepare(`
8552
+ SELECT summary_json FROM delivery_interrupted_turn_summaries WHERE inbox_id = ?
8553
+ `).get(inboxId);
8554
+ if (row === undefined)
8555
+ return undefined;
8556
+ try {
8557
+ return normalizeInterruptedTurnMutationSummary(JSON.parse(row.summary_json));
8558
+ }
8559
+ catch {
8560
+ return undefined;
8561
+ }
8562
+ }
8563
+ getForegroundExecutionTiming(inboxId) {
8564
+ this.assertOpen();
8565
+ const row = this.database.prepare(`
8566
+ SELECT dispatched_at, completed_at, status
8567
+ FROM delivery_foreground_executions
8568
+ WHERE inbox_id = ? AND status != 'pending' AND completed_at IS NOT NULL
8569
+ `).get(inboxId);
8570
+ if (row === undefined)
8571
+ return undefined;
8572
+ return {
8573
+ dispatchedAt: row.dispatched_at,
8574
+ completedAt: row.completed_at,
8575
+ status: row.status,
8576
+ };
8577
+ }
8578
+ listRecentOwnerInboxTexts(input) {
8579
+ this.assertOpen();
8580
+ const boundary = this.database.prepare(`
8581
+ SELECT admission_sequence FROM delivery_inbox_admissions WHERE inbox_id = ?
8582
+ `).get(input.beforeInboxId);
8583
+ if (boundary === undefined)
8584
+ return [];
8585
+ const limit = Math.max(1, Math.min(50, Math.trunc(input.limit ?? 20)));
8586
+ const rows = this.database.prepare(`
8587
+ SELECT message.id, message.envelope_json
8588
+ FROM inbox_messages AS message
8589
+ JOIN delivery_inbox_admissions AS admission ON admission.inbox_id = message.id
8590
+ WHERE admission.admission_sequence < ?
8591
+ AND message.status != 'dead_letter'
8592
+ AND (
8593
+ message.binding_id = ?
8594
+ OR message.binding_id IN (SELECT id FROM conversation_bindings WHERE session_id = ?)
8595
+ OR (
8596
+ json_extract(message.envelope_json, '$.conversation') = json(?)
8597
+ AND json_extract(message.envelope_json, '$.principal') = json(?)
8598
+ )
8599
+ )
8600
+ ORDER BY admission.admission_sequence DESC
8601
+ LIMIT ?
8602
+ `).all(boundary.admission_sequence, input.binding.id, input.binding.sessionId, conversationJson(input.binding.conversation), principalJson(input.binding.principal), limit);
8603
+ const out = [];
8604
+ for (const row of rows) {
8605
+ try {
8606
+ const env = JSON.parse(row.envelope_json);
8607
+ if (env.kind !== 'text' || typeof env.text !== 'string')
8608
+ continue;
8609
+ const trimmed = env.text.trim();
8610
+ if (trimmed === '' || trimmed.startsWith('/'))
8611
+ continue;
8612
+ out.push({ inboxId: row.id, text: trimmed });
8613
+ }
8614
+ catch {
8615
+ // Ignore malformed historical envelope.
8616
+ }
8617
+ }
8618
+ return out;
8619
+ }
8620
+ listActiveOwnerBindingScopes() {
8621
+ this.assertOpen();
8622
+ const rows = this.database.prepare(`
8623
+ SELECT
8624
+ binding.principal_json,
8625
+ binding.workspace,
8626
+ binding.agent_preset,
8627
+ principal.id AS principal_record_id,
8628
+ principal.version AS principal_version
8629
+ FROM conversation_bindings AS binding
8630
+ JOIN delivery_principals AS principal ON principal.id = binding.principal_id
8631
+ WHERE binding.status = 'active'
8632
+ AND principal.status = 'active'
8633
+ AND principal.role = 'owner'
8634
+ ORDER BY binding.updated_at DESC
8635
+ LIMIT 16
8636
+ `).all();
8637
+ const out = [];
8638
+ for (const row of rows) {
8639
+ try {
8640
+ const p = JSON.parse(row.principal_json);
8641
+ out.push({
8642
+ principalId: externalPrincipalId(p),
8643
+ principalRecordId: row.principal_record_id,
8644
+ principalVersion: row.principal_version,
8645
+ workspace: row.workspace,
8646
+ agentPreset: row.agent_preset,
8647
+ });
8648
+ }
8649
+ catch {
8650
+ // Ignore malformed row.
8651
+ }
8652
+ }
8653
+ return out;
8654
+ }
7986
8655
  close() {
7987
8656
  if (this.closed)
7988
8657
  return;
7989
8658
  this.closed = true;
7990
- this.database.close();
8659
+ if (!this.reloading) {
8660
+ this.database.close();
8661
+ }
7991
8662
  }
7992
8663
  transaction(operation) {
7993
8664
  this.database.exec('BEGIN IMMEDIATE');