@dreamforgestudiollc/emet 0.3.6 → 0.3.7

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 (88) hide show
  1. package/.env.example +29 -0
  2. package/CHANGELOG.md +25 -1
  3. package/README.md +9 -3
  4. package/RELEASE_NOTES-0.2.6.md +1 -1
  5. package/RELEASE_NOTES-0.3.7.md +19 -0
  6. package/docs/BOTS.md +1 -1
  7. package/docs/DEPLOY.md +14 -1
  8. package/docs/ERROR-CODES-SPEC.md +4 -0
  9. package/docs/ERROR-CODES.md +7 -0
  10. package/docs/ROADMAP.md +3 -3
  11. package/docs/SETUP.md +4 -0
  12. package/docs/SUBKEYS.md +3 -1
  13. package/docs/continuity-currency-statechart.md +34 -0
  14. package/docs/features/README.md +21 -0
  15. package/docs/features/access.md +28 -0
  16. package/docs/features/documents.md +35 -0
  17. package/docs/features/errors.md +32 -0
  18. package/docs/features/gems.md +31 -0
  19. package/docs/features/memory.md +29 -0
  20. package/docs/features/pages.md +28 -0
  21. package/docs/features/record.md +27 -0
  22. package/docs/features/search.md +27 -0
  23. package/docs/features/startup.md +29 -0
  24. package/docs/features/subkeys.md +30 -0
  25. package/docs/features/transcripts.md +33 -0
  26. package/docs/per-tag-handoff-statechart.md +147 -0
  27. package/docs/subkey-session-statechart.md +57 -0
  28. package/package.json +3 -2
  29. package/server.json +27 -2
  30. package/src/annotations.js +4 -3
  31. package/src/attribution.js +1 -1
  32. package/src/chooser.js +74 -3
  33. package/src/conformance.js +2 -0
  34. package/src/continuity-currency-statechart.js +139 -0
  35. package/src/continuity-currency.js +869 -0
  36. package/src/dispatch.js +1 -1
  37. package/src/error-codes.js +7 -0
  38. package/src/http-remote.js +27 -4
  39. package/src/index.js +1 -0
  40. package/src/pages.js +15 -0
  41. package/src/per-tag-handoff-statechart.js +264 -0
  42. package/src/per-tag-handoff.js +988 -0
  43. package/src/persons.js +16 -0
  44. package/src/session-graph.js +118 -7
  45. package/src/session.js +54 -10
  46. package/src/setup.js +22 -1
  47. package/src/startup-pages.js +13 -2
  48. package/src/subkey-lifecycle.js +105 -0
  49. package/src/subkey-session-statechart.js +253 -0
  50. package/src/subkeys.js +648 -89
  51. package/src/tools.js +157 -32
  52. package/src/version.js +1 -1
  53. package/templates/INDEX.md +1 -0
  54. package/templates/TAGHANDOFF.md +45 -0
  55. package/verification/continuity-currency/ContinuityCurrency.cfg +12 -0
  56. package/verification/continuity-currency/ContinuityCurrency.tla +239 -0
  57. package/verification/continuity-currency/tlc-output.txt +32 -0
  58. package/verification/continuity-currency/view.mjs +54 -0
  59. package/verification/per-tag-handoff/PerTagHandoff.cfg +10 -0
  60. package/verification/per-tag-handoff/PerTagHandoff.tla +191 -0
  61. package/verification/per-tag-handoff/StampCounter.cfg +10 -0
  62. package/verification/per-tag-handoff/out/report.md +6 -0
  63. package/verification/per-tag-handoff/out-counter/chart.mmd +30 -0
  64. package/verification/per-tag-handoff/out-counter/report.md +15 -0
  65. package/verification/per-tag-handoff/out-counter/tlc.out +130 -0
  66. package/verification/per-tag-handoff/split/PerTagConflict.cfg +6 -0
  67. package/verification/per-tag-handoff/split/PerTagConflict.tla +104 -0
  68. package/verification/per-tag-handoff/split/PerTagTime.cfg +8 -0
  69. package/verification/per-tag-handoff/split/PerTagTime.tla +100 -0
  70. package/verification/per-tag-handoff/split/conflict-chart.mmd +47 -0
  71. package/verification/per-tag-handoff/split/conflict-report.md +8 -0
  72. package/verification/per-tag-handoff/split/conflict-tlc.txt +19 -0
  73. package/verification/per-tag-handoff/split/conflict-view.mjs +34 -0
  74. package/verification/per-tag-handoff/split/time-chart.mmd +44 -0
  75. package/verification/per-tag-handoff/split/time-report.md +8 -0
  76. package/verification/per-tag-handoff/split/time-tlc.txt +19 -0
  77. package/verification/per-tag-handoff/split/time-view.mjs +33 -0
  78. package/verification/per-tag-handoff/tlc-output.txt +19 -0
  79. package/verification/per-tag-handoff/v1-draft/PerTagHandoff.cfg +5 -0
  80. package/verification/per-tag-handoff/v1-draft/PerTagHandoff.tla +94 -0
  81. package/verification/per-tag-handoff/v1-draft/out/chart.mmd +37 -0
  82. package/verification/per-tag-handoff/v1-draft/out/report.md +7 -0
  83. package/verification/per-tag-handoff/v1-draft/out/tlc.out +19 -0
  84. package/verification/per-tag-handoff/v1-draft/view.mjs +20 -0
  85. package/verification/per-tag-handoff/view.mjs +31 -0
  86. package/verification/subkey-session/SubkeySession.cfg +11 -0
  87. package/verification/subkey-session/SubkeySession.tla +254 -0
  88. package/verification/subkey-session/tlc-output.txt +13 -0
package/src/subkeys.js CHANGED
@@ -11,13 +11,18 @@
11
11
  * (src/subkey-store.js), not in emet/CLIENT_APPROVALS.md. Nothing in this
12
12
  * module deletes a record. A later state is written beside the earlier one.
13
13
  * Each session open is its own record.
14
+ *
15
+ * A handle lasts 12 hours. In the last hour, and for a grace window after
16
+ * expiry, the same key can close that session into the next one. A sweep
17
+ * records auto_closed when the link is already ended or the grace window
18
+ * is over. The row stays.
14
19
  */
15
20
 
16
21
  import crypto from 'node:crypto';
17
22
  import { setting } from './env.js';
18
23
  import {
19
24
  personIsOwner, actorIsOwner, actorIsCos, cosTag, sessionBaseOf,
20
- rememberSubkeySession
25
+ rememberSubkeySession, WRITE_TOOLS
21
26
  } from './attribution.js';
22
27
  import { isOwlIdentity } from './owl.js';
23
28
  import { isMasterBlasterActor } from './writer-approval.js';
@@ -25,6 +30,12 @@ import { isLegacyBoundHostSpelling } from './bound-door.js';
25
30
  import { assignCode } from './error-codes.js';
26
31
  import { parseReceipts } from './session.js';
27
32
  import { storeFor, sweepFlagOffLiveSessions } from './subkey-store.js';
33
+ import { retainSessionClose } from './session-graph.js';
34
+ import {
35
+ UNWRAPPED_NOTICE, RENEW_MESSAGE,
36
+ clientKindValue, clientKindOf, phaseOf, renewalRequest,
37
+ isTerminalState, sweepIntervalMs
38
+ } from './subkey-lifecycle.js';
28
39
 
29
40
  const KEY_PREFIX = 'emk_';
30
41
  const HANDLE_PREFIX = 'emh_';
@@ -37,12 +48,12 @@ const DEFAULT_FAIL_MAX = 5;
37
48
  const DEFAULT_FAIL_WINDOW_MS = 15 * 60 * 1000;
38
49
 
39
50
  export const SUBKEY_TOOLS = Object.freeze([
40
- 'emet_subkey_request', 'emet_subkey_claim', 'emet_subkey_revoke', 'emet_subkey_end_session'
51
+ 'emet_subkey_request', 'emet_subkey_claim', 'emet_subkey_revoke', 'emet_subkey_end_session', 'emet_subkey_set_kind'
41
52
  ]);
42
53
  /** Tools a verified sub-key session must not call. Settings and access stay on the owner login. */
43
54
  const OWNER_ONLY_TOOLS = Object.freeze(new Set([
44
55
  'emet_client_approve',
45
- 'emet_subkey_request', 'emet_subkey_claim', 'emet_subkey_revoke', 'emet_subkey_end_session',
56
+ 'emet_subkey_request', 'emet_subkey_claim', 'emet_subkey_revoke', 'emet_subkey_end_session', 'emet_subkey_set_kind',
46
57
  'emet_invite_create', 'emet_member_access_create', 'emet_setup_complete'
47
58
  ]));
48
59
 
@@ -51,12 +62,16 @@ const HANDLE_RE = /^emh_[A-Za-z0-9_-]{43}$/;
51
62
  const NONCE_RE = /^emn_[A-Za-z0-9_-]{43}$/;
52
63
 
53
64
  let openTokens = new WeakMap();
65
+ let openPlans = new WeakMap();
66
+ let openNotices = new WeakMap();
54
67
  const throttle = createThrottle();
55
68
 
56
69
  function subkeysEnabled() { return setting('SUBKEYS') === '1'; }
57
70
 
58
71
  export function _resetForTests() {
59
72
  openTokens = new WeakMap();
73
+ openPlans = new WeakMap();
74
+ openNotices = new WeakMap();
60
75
  throttle.reset();
61
76
  }
62
77
 
@@ -279,7 +294,7 @@ function sessionsForBase(data, base) {
279
294
  /** The unexpired live open for a base, or the latest open when none is. */
280
295
  function currentSession(data, base, now) {
281
296
  const rows = sessionsForBase(data, base);
282
- const live = rows.filter((s) => s.state === 'live' && !past(s.expires_at, now));
297
+ const live = rows.filter((s) => (s.state === 'live' || s.state === 'renewal_offered') && !past(s.expires_at, now));
283
298
  if (live.length) return live[live.length - 1];
284
299
  return rows.length ? rows[rows.length - 1] : null;
285
300
  }
@@ -298,11 +313,362 @@ function livePointer(row, data, now) {
298
313
  }
299
314
  if (s.key_id !== row.key_id) return null;
300
315
  if (s.state === 'opening') return openIsStale(s.opened_at || row.live_set_at, now) ? null : s;
301
- if (s.state !== 'live') return null;
316
+ if (s.state !== 'live' && s.state !== 'renewal_offered') return null;
302
317
  if (past(s.expires_at, now)) return null;
303
318
  return s;
304
319
  }
305
320
 
321
+ function timeIn(iso, fromIso, now) {
322
+ const t = new Date(iso).getTime();
323
+ const from = new Date(fromIso).getTime();
324
+ const to = now instanceof Date ? now.getTime() : new Date(now).getTime();
325
+ return Number.isFinite(t) && Number.isFinite(from) && Number.isFinite(to) && t >= from && t <= to;
326
+ }
327
+
328
+ /**
329
+ * A wrap-up is a record of this tag written from the handle's issue time
330
+ * through now. The owner's stored kind decides whether the check runs.
331
+ * deps.wrapUps is the test seam. A handoff write and an episodic row with
332
+ * metadata.wrap_up are the store records.
333
+ */
334
+ export async function wrapUpFound(ctx, tag, fromIso, now) {
335
+ if (!tag || !fromIso) return false;
336
+ const deps = ctx && ctx.deps;
337
+ const listed = deps && Array.isArray(deps.wrapUps) ? deps.wrapUps : [];
338
+ if (listed.some((row) => row && row.tag === tag && timeIn(row.at, fromIso, now))) return true;
339
+ const db = ctx && ctx.db;
340
+ if (!db || typeof db.collection !== 'function') return false;
341
+ try {
342
+ const ids = ['HANDOFF.md', `HANDOFF/${tag}.md`, `bots/${tag}/HANDOFF.md`];
343
+ const found = await db.collection('documents').find({ doc_id: { $in: ids } }).limit(20).toArray();
344
+ for (const doc of found || []) {
345
+ const by = doc && (doc.updated_by || (doc.metadata && doc.metadata.source));
346
+ const at = doc && (doc.updated_at || doc.updatedAt);
347
+ if (by === tag && timeIn(at, fromIso, now)) return true;
348
+ }
349
+ } catch { /* a missed read is not a wrap-up */ }
350
+ const cols = ctx && Array.isArray(ctx.layerCollections) ? ctx.layerCollections : [];
351
+ for (const col of cols) {
352
+ if (!col || typeof col.find !== 'function') continue;
353
+ try {
354
+ const rows = await col.find({ 'metadata.source': tag, 'metadata.wrap_up': true }).limit(20).toArray();
355
+ for (const row of rows || []) {
356
+ const raw = row && (row.timestamp || row.updated_at);
357
+ const iso = typeof raw === 'number' ? new Date(raw > 1e12 ? raw : raw * 1000).toISOString() : raw;
358
+ if (timeIn(iso, fromIso, now)) return true;
359
+ }
360
+ } catch { /* a missed read is not a wrap-up */ }
361
+ }
362
+ return false;
363
+ }
364
+
365
+ function hold(message, extra = {}) {
366
+ const e = new Error(message);
367
+ e.subkeyHold = { message, action: 'reinitialize', ...extra };
368
+ e.emetCode = 'EMET-SESS-014';
369
+ return e;
370
+ }
371
+
372
+ function sessionsForKey(data, keyId) {
373
+ return (data.sessions || []).filter((s) => s && s.key_id === keyId);
374
+ }
375
+
376
+ function handleMatches(session, handle, peppers) {
377
+ if (!session || !session.handle_hmac || !HANDLE_RE.test(handle || '')) return false;
378
+ return verifyMac(session.handle_hmac, handle, peppers);
379
+ }
380
+
381
+ function priorByHandle(data, keyId, handle, peppers) {
382
+ if (!HANDLE_RE.test(handle || '')) return null;
383
+ return sessionsForKey(data, keyId).find((s) => !isTerminalState(s.state) && handleMatches(s, handle, peppers)) || null;
384
+ }
385
+
386
+ function isSessionStranded(session, now) {
387
+ if (!session || session.state === 'revoked') return false;
388
+ if (isTerminalState(session.state)) return true;
389
+ if (session.state === 'ended' || session.state === 'expired' || session.state === 'unwrapped') return true;
390
+ if (session.state === 'opening') return openIsStale(session.opened_at, now);
391
+ const phase = phaseOf(session.expires_at, now);
392
+ return (session.state === 'live' || session.state === 'renewal_offered') && (phase === 'grace' || phase === 'beyond');
393
+ }
394
+
395
+ /** What this open does to the key's current slot. A bot's healthy slot collides. */
396
+ function openDecision(data, row, now, handle, peppers) {
397
+ const prior = priorByHandle(data, row.key_id, handle, peppers);
398
+ if (prior) {
399
+ const phase = phaseOf(prior.expires_at, now);
400
+ if (phase === 'window' || phase === 'grace') return { action: 'renew', prior };
401
+ }
402
+ const healthy = livePointer(row, data, now);
403
+ if (healthy && clientKindOf(row) !== 'chat') return { action: 'collision', prior: healthy };
404
+ if (healthy) return { action: 'reclaim', prior: healthy };
405
+ const rest = sessionsForKey(data, row.key_id).find((s) => !isTerminalState(s.state));
406
+ if (rest) return { action: 'reclaim', prior: rest };
407
+ return { action: 'open', prior: null };
408
+ }
409
+
410
+ function clearPointer(row, openId) {
411
+ if (row && row.live_session_id === openId) {
412
+ row.live_session_id = null;
413
+ row.live_set_at = null;
414
+ }
415
+ }
416
+
417
+ function carryForwardClose(data, session, now, reason, event, next) {
418
+ if (!session || isTerminalState(session.state)) return false;
419
+ session.state = 'closed';
420
+ session.ended_at = now.toISOString();
421
+ session.end_reason = reason;
422
+ session.retained = true;
423
+ session.deleted = false;
424
+ if (next) {
425
+ session.next_open_id = next.open_id;
426
+ session.next_session_id = next.session_id;
427
+ next.prev_open_id = session.open_id;
428
+ next.prev_session_id = session.session_id;
429
+ }
430
+ const row = keyById(data, session.key_id);
431
+ clearPointer(row, session.open_id);
432
+ if (row) {
433
+ pushHistory(row, event, {
434
+ at: session.ended_at,
435
+ session_id: session.session_id,
436
+ open_id: session.open_id,
437
+ reason,
438
+ next_open_id: next ? next.open_id : null,
439
+ next_session_id: next ? next.session_id : null
440
+ });
441
+ }
442
+ return true;
443
+ }
444
+
445
+ function markUnwrapped(data, session, now, next) {
446
+ if (!session || isTerminalState(session.state)) return false;
447
+ const row = keyById(data, session.key_id);
448
+ if (session.state !== 'unwrapped') {
449
+ session.state = 'unwrapped';
450
+ session.unwrapped_at = now.toISOString();
451
+ session.retained = true;
452
+ session.deleted = false;
453
+ if (row) pushHistory(row, 'unwrapped', { at: session.unwrapped_at, session_id: session.session_id, open_id: session.open_id });
454
+ }
455
+ if (next) {
456
+ session.next_open_id = next.open_id;
457
+ session.next_session_id = next.session_id;
458
+ if (!next.prev_open_id) {
459
+ next.prev_open_id = session.open_id;
460
+ next.prev_session_id = session.session_id;
461
+ }
462
+ }
463
+ clearPointer(row, session.open_id);
464
+ return true;
465
+ }
466
+
467
+ function autoCloseSession(data, session, now, reason, next) {
468
+ if (!session || isTerminalState(session.state)) return false;
469
+ session.state = 'auto_closed';
470
+ session.ended_at = now.toISOString();
471
+ session.end_reason = reason || 'abandoned';
472
+ session.retained = true;
473
+ session.deleted = false;
474
+ if (next) {
475
+ session.next_open_id = next.open_id;
476
+ session.next_session_id = next.session_id;
477
+ if (!next.prev_open_id) {
478
+ next.prev_open_id = session.open_id;
479
+ next.prev_session_id = session.session_id;
480
+ }
481
+ }
482
+ const row = keyById(data, session.key_id);
483
+ clearPointer(row, session.open_id);
484
+ if (row) {
485
+ pushHistory(row, 'session_auto_closed', {
486
+ at: session.ended_at,
487
+ session_id: session.session_id,
488
+ open_id: session.open_id,
489
+ reason: session.end_reason,
490
+ next_open_id: next ? next.open_id : null
491
+ });
492
+ }
493
+ return true;
494
+ }
495
+
496
+ /** Ended links, and sessions past the grace window. Rows stay. */
497
+ function closeStranded(data, now) {
498
+ let n = 0;
499
+ for (const session of data.sessions || []) {
500
+ if (!session || isTerminalState(session.state)) continue;
501
+ const phase = phaseOf(session.expires_at, now);
502
+ const ended = session.state === 'ended';
503
+ const beyond = phase === 'beyond' && ['live', 'renewal_offered', 'expired', 'unwrapped', 'opening'].includes(session.state);
504
+ if ((ended || beyond) && autoCloseSession(data, session, now, ended ? 'link ended' : 'abandoned')) n += 1;
505
+ }
506
+ return n;
507
+ }
508
+
509
+ function healthyPointer(row, session, now) {
510
+ if (!row || !session || row.live_session_id !== session.open_id) return false;
511
+ if (session.state !== 'live' && session.state !== 'renewal_offered') return false;
512
+ const phase = phaseOf(session.expires_at, now);
513
+ return phase === 'fresh' || phase === 'window';
514
+ }
515
+
516
+ /** A sub-key link that is ended, expired, or no longer the live pointer. */
517
+ function linkGone(row, session, now) {
518
+ if (!session || !session.session_id) return false;
519
+ if (healthyPointer(row, session, now)) return false;
520
+ if (['ended', 'expired', 'unwrapped', 'auto_closed', 'closed', 'revoked'].includes(session.state)) return true;
521
+ const phase = phaseOf(session.expires_at, now);
522
+ if (phase === 'grace' || phase === 'beyond') return true;
523
+ return !row || row.live_session_id !== session.open_id;
524
+ }
525
+
526
+ function strandedTranscripts(data, now) {
527
+ const out = [];
528
+ const seen = new Set();
529
+ for (const session of data.sessions || []) {
530
+ if (!session || !session.session_id || seen.has(session.session_id)) continue;
531
+ const siblings = (data.sessions || []).filter((item) => item && item.session_id === session.session_id);
532
+ if (siblings.some((item) => healthyPointer(keyById(data, item.key_id), item, now))) continue;
533
+ if (!siblings.some((item) => linkGone(keyById(data, item.key_id), item, now))) continue;
534
+ seen.add(session.session_id);
535
+ out.push({
536
+ session_id: session.session_id,
537
+ key_id: session.key_id,
538
+ closed_by: 'server-sweep',
539
+ note: `Closed ${now.toISOString()} by server-sweep. The transcript stays.`
540
+ });
541
+ }
542
+ return out;
543
+ }
544
+
545
+ function reclaimCloser(keyId) {
546
+ return `reclaim by key ${keyId}`;
547
+ }
548
+
549
+ async function closeTranscriptList(deps, items, now) {
550
+ if (!items || !items.length || !deps || !deps.dbManager) return 0;
551
+ const seen = new Set();
552
+ let n = 0;
553
+ for (const item of items) {
554
+ if (!item || !item.session_id || seen.has(item.session_id)) continue;
555
+ seen.add(item.session_id);
556
+ try {
557
+ const res = await retainSessionClose(deps.dbManager, item.session_id, {
558
+ at: now,
559
+ closed_by: item.closed_by,
560
+ note: item.note
561
+ });
562
+ if (res && res.recorded) n += 1;
563
+ } catch { /* a transcript close that cannot be written does not undo the sub-key record */ }
564
+ }
565
+ return n;
566
+ }
567
+
568
+ function loseOpening(data, session, now) {
569
+ if (!session || session.state !== 'opening') return false;
570
+ const row = keyById(data, session.key_id);
571
+ session.state = 'ended';
572
+ session.ended_at = now.toISOString();
573
+ session.end_reason = 'session lost';
574
+ session.retained = true;
575
+ session.deleted = false;
576
+ clearPointer(row, session.open_id);
577
+ if (row) {
578
+ pushHistory(row, 'session_lost', {
579
+ at: session.ended_at,
580
+ open_id: session.open_id,
581
+ session_id: session.session_id,
582
+ reason: 'session lost'
583
+ });
584
+ }
585
+ return true;
586
+ }
587
+
588
+ /**
589
+ * Close or flag every non-terminal session of this key, then the caller
590
+ * stores `created` as the one live session.
591
+ */
592
+ function settlePriors(data, row, created, now, { action, prior, wrapFound }, transcripts) {
593
+ let notice = null;
594
+ const kind = clientKindOf(row);
595
+ const noteTranscript = (session) => {
596
+ if (!transcripts || !session || !session.session_id) return;
597
+ transcripts.push({
598
+ session_id: session.session_id,
599
+ key_id: row.key_id,
600
+ closed_by: reclaimCloser(row.key_id),
601
+ note: `Closed ${now.toISOString()} by ${reclaimCloser(row.key_id)}. The transcript stays.`
602
+ });
603
+ };
604
+ for (const session of sessionsForKey(data, row.key_id)) {
605
+ if (!session || isTerminalState(session.state)) continue;
606
+ const phase = phaseOf(session.expires_at, now);
607
+ const isPrior = !!(prior && session.open_id === prior.open_id);
608
+ if (session.state === 'opening') {
609
+ loseOpening(data, session, now);
610
+ noteTranscript(session);
611
+ continue;
612
+ }
613
+ if (isPrior && action === 'renew') {
614
+ carryForwardClose(data, session, now, 'renewed', 'session_renewed', created);
615
+ noteTranscript(session);
616
+ notice = {
617
+ action: 'continued',
618
+ session_id: created.session_id,
619
+ previous_session_id: session.session_id,
620
+ message: 'This session continues the previous one. The previous session is closed. Keep this session_handle.'
621
+ };
622
+ continue;
623
+ }
624
+ if (phase === 'beyond') {
625
+ autoCloseSession(data, session, now, 'abandoned', created);
626
+ noteTranscript(session);
627
+ continue;
628
+ }
629
+ if (kind === 'chat' && wrapFound !== true && isPrior && session.state !== 'ended') {
630
+ markUnwrapped(data, session, now, created);
631
+ noteTranscript(session);
632
+ notice = {
633
+ ...renewalRequest(created),
634
+ previous_session_id: session.session_id,
635
+ wrap_up_notice: UNWRAPPED_NOTICE,
636
+ message: `${UNWRAPPED_NOTICE} ${RENEW_MESSAGE}`
637
+ };
638
+ continue;
639
+ }
640
+ carryForwardClose(data, session, now, 'reclaimed', 'session_reclaimed', created);
641
+ noteTranscript(session);
642
+ }
643
+ return notice;
644
+ }
645
+
646
+ function healthySlot(session, now) {
647
+ if (!session) return false;
648
+ if (session.state !== 'live' && session.state !== 'renewal_offered') return false;
649
+ const phase = phaseOf(session.expires_at, now);
650
+ return phase === 'fresh' || phase === 'window';
651
+ }
652
+
653
+ function recordCollision(row, now, actor) {
654
+ row.collisions = Array.isArray(row.collisions) ? row.collisions : [];
655
+ row.collisions.push({ at: now.toISOString(), client_id: actor.clientId || null, grant_id: actor.grantId || null });
656
+ pushHistory(row, 'collision', { at: now.toISOString(), client_id: actor.clientId || null, grant_id: actor.grantId || null });
657
+ }
658
+
659
+ function strandedWriteMessage(session, kind, wrap, now) {
660
+ if (!session) return `${RENEW_MESSAGE} Nothing was written.`;
661
+ if (session.state === 'closed' || session.state === 'auto_closed') {
662
+ return 'This sub-key session is closed. Call emet_session_open with your sub-key. Nothing was written.';
663
+ }
664
+ const phase = phaseOf(session.expires_at, now);
665
+ if (kind === 'chat' && wrap !== true && (session.state === 'unwrapped' || session.state === 'expired' || phase === 'grace' || phase === 'beyond')) {
666
+ return `${UNWRAPPED_NOTICE} ${RENEW_MESSAGE} Nothing was written.`;
667
+ }
668
+ if (phase === 'beyond') return 'This session handle is past its grace window. Call emet_session_open with your sub-key. Nothing was written.';
669
+ return `${RENEW_MESSAGE} Nothing was written.`;
670
+ }
671
+
306
672
  function registryOf(envList) {
307
673
  if (Array.isArray(envList)) return envList;
308
674
  return String(setting('SOURCE_TAGS') ?? '').split(',').map((s) => s.trim()).filter(Boolean);
@@ -379,7 +745,7 @@ export function sessionIdForClose(args) {
379
745
  * Request a sub-key for one registered tag. The response carries the claim
380
746
  * nonce once. The record stores only its HMAC.
381
747
  */
382
- export async function requestSubkey(deps, actor, { tag } = {}, registry = [], now = new Date()) {
748
+ export async function requestSubkey(deps, actor, { tag, client_kind } = {}, registry = [], now = new Date()) {
383
749
  if (!subkeysEnabled()) throw refusal('sub-keys are off (EMET_SUBKEYS is not 1). Nothing was changed.');
384
750
  const peppers = requirePepper();
385
751
  assertHttpOwner(actor, actor && actor.ownerId);
@@ -401,7 +767,8 @@ export async function requestSubkey(deps, actor, { tag } = {}, registry = [], no
401
767
  person_id: actor.personId || null, login_tag: actor.sourceTag || null,
402
768
  requested_at: now.toISOString(),
403
769
  nonce_hmac: seal(nonce, peppers), nonce_spent: false,
404
- replaces, collisions: [], history: []
770
+ replaces, collisions: [], history: [],
771
+ requested_client_kind: clientKindValue(client_kind)
405
772
  };
406
773
  pushHistory(row, 'request', { at: row.requested_at, by: actor.clientId || null, client_id: actor.clientId || null });
407
774
  data.keys[key_id] = row;
@@ -418,7 +785,7 @@ export async function requestSubkey(deps, actor, { tag } = {}, registry = [], no
418
785
  * is decided. Returns null when nothing is pending, so the ordinary client
419
786
  * approval can proceed.
420
787
  */
421
- export async function decideSubkeyIfPending(deps, actor, ownerId, { tag, decision, reason, key_id, via } = {}, now = new Date()) {
788
+ export async function decideSubkeyIfPending(deps, actor, ownerId, { tag, decision, reason, key_id, via, client_kind } = {}, now = new Date()) {
422
789
  if (!subkeysEnabled()) return null;
423
790
  const id = typeof key_id === 'string' ? key_id.trim() : '';
424
791
  const t = typeof tag === 'string' ? tag.trim() : '';
@@ -456,10 +823,15 @@ export async function decideSubkeyIfPending(deps, actor, ownerId, { tag, decisio
456
823
  if (why) hist.reason = why;
457
824
  if (channel) hist.via = channel;
458
825
  if (decision === 'approve') {
826
+ const named = clientKindValue(client_kind);
827
+ const rawKind = client_kind === undefined || client_kind === null ? '' : String(client_kind).trim();
828
+ if (rawKind && !named) throw refusal('emet_client_approve: "client_kind" must be "bot" or "chat". Nothing was changed.');
829
+ row.client_kind = named || 'bot';
459
830
  row.status = 'approved';
460
831
  row.approved_by = by;
461
832
  row.approved_at = hist.at;
462
833
  row.approve_reason = why || null;
834
+ hist.client_kind = row.client_kind;
463
835
  pushHistory(row, 'approve', hist);
464
836
  } else if (decision === 'deny') {
465
837
  row.status = 'denied';
@@ -473,6 +845,7 @@ export async function decideSubkeyIfPending(deps, actor, ownerId, { tag, decisio
473
845
  const replaces = row.replaces || null;
474
846
  result = {
475
847
  kind: 'subkey', tag: label, key_id: row.key_id, decision, by, at: row.approved_at,
848
+ client_kind: row.client_kind || null,
476
849
  replaces,
477
850
  replaces_existing_key: !!replaces,
478
851
  ...(replaces ? { approval_note: `This approval replaces the existing key ${replaces} for "${label}". The old key stays in its grace window, then stops.` } : {})
@@ -553,16 +926,20 @@ function endLive(data, row, state, now, reason) {
553
926
  if (!row || !row.live_session_id) return;
554
927
  const openId = row.live_session_id;
555
928
  const s = sessionByOpen(data, openId);
556
- if (s && s.key_id === row.key_id && s.state === 'live') {
929
+ if (s && s.key_id === row.key_id && (s.state === 'live' || s.state === 'renewal_offered')) {
557
930
  s.state = state;
558
931
  s.ended_at = now.toISOString();
559
932
  s.end_reason = reason || null;
560
- } else {
561
- if (s && s.key_id === row.key_id && s.state === 'opening') {
562
- s.state = 'ended';
563
- s.ended_at = now.toISOString();
564
- s.end_reason = reason || 'session lost';
565
- }
933
+ s.retained = true;
934
+ s.deleted = false;
935
+ } else if (s && s.key_id === row.key_id && s.state === 'opening') {
936
+ s.state = 'ended';
937
+ s.ended_at = now.toISOString();
938
+ s.end_reason = reason || 'session lost';
939
+ s.retained = true;
940
+ s.deleted = false;
941
+ pushHistory(row, 'session_lost', { at: now.toISOString(), open_id: openId, session_id: s.session_id, reason: reason || null });
942
+ } else if (!s || s.key_id !== row.key_id) {
566
943
  pushHistory(row, 'session_lost', { at: now.toISOString(), open_id: openId, session_id: s ? s.session_id : null, reason: reason || null });
567
944
  }
568
945
  row.live_session_id = null;
@@ -662,7 +1039,10 @@ export async function retireSubkeysForRotation(deps, { eventId, tags = null, now
662
1039
  return { revoked, sessions, unavailable: false };
663
1040
  }
664
1041
 
665
- /** End the key's live session without revoking the key. Owner login only. */
1042
+ /**
1043
+ * Carry-forward close every non-terminal session of the key.
1044
+ * The key stays. The rows stay. The state is closed, not a lock.
1045
+ */
666
1046
  export async function endSubkeySession(deps, actor, ownerId, { tag, key_id, reason } = {}, now = new Date()) {
667
1047
  if (!subkeysEnabled()) throw refusal('sub-keys are off (EMET_SUBKEYS is not 1). Nothing was changed.');
668
1048
  requirePepper();
@@ -671,20 +1051,41 @@ export async function endSubkeySession(deps, actor, ownerId, { tag, key_id, reas
671
1051
  const t = typeof tag === 'string' ? tag.trim() : '';
672
1052
  if (!id && !t) throw refusal('emet_subkey_end_session: pass "tag" or "key_id". Nothing was changed.');
673
1053
  let result = null;
1054
+ const transcripts = [];
674
1055
  await edit(deps, (data) => {
675
1056
  ensureMaps(data);
676
1057
  const row = id
677
1058
  ? keyById(data, id)
678
- : Object.values(data.keys).find((k) => k && k.tag === t && k.live_session_id);
1059
+ : Object.values(data.keys).find((k) => k && k.tag === t && sessionsForKey(data, k.key_id).some((s) => !isTerminalState(s.state)));
679
1060
  if (!row) throw refusal('emet_subkey_end_session: no sub-key matched. Nothing was changed.');
680
- if (!row.live_session_id) throw refusal(`emet_subkey_end_session: "${row.tag}" has no live session. The key was not changed.`);
681
- const live = sessionByOpen(data, row.live_session_id);
682
- const base = live ? live.session_id : null;
683
- endLive(data, row, 'ended', now, reason || 'owner ended the live session');
684
- pushHistory(row, 'session_ended', { at: now.toISOString(), by: `owner (${actor.personId || 'local'})`, session_id: base, reason: reason || null });
685
- result = { key_id: row.key_id, tag: row.tag, status: row.status, session_id: base, ended: true };
1061
+ const pointed = sessionByOpen(data, row.live_session_id);
1062
+ const targets = sessionsForKey(data, row.key_id).filter((s) => {
1063
+ if (isTerminalState(s.state)) return false;
1064
+ if (pointed && s.open_id === pointed.open_id) return true;
1065
+ return isSessionStranded(s, now);
1066
+ });
1067
+ if (!targets.length) throw refusal(`emet_subkey_end_session: "${row.tag}" has no session to close. The key was not changed.`);
1068
+ const why = reason || 'owner carry-forward';
1069
+ for (const session of targets) {
1070
+ carryForwardClose(data, session, now, why, 'session_closed', null);
1071
+ transcripts.push({
1072
+ session_id: session.session_id,
1073
+ key_id: row.key_id,
1074
+ closed_by: reclaimCloser(row.key_id),
1075
+ note: `Closed ${now.toISOString()} by ${reclaimCloser(row.key_id)}. The transcript stays.`
1076
+ });
1077
+ }
1078
+ row.live_session_id = null;
1079
+ row.live_set_at = null;
1080
+ const base = targets[0] ? targets[0].session_id : null;
1081
+ pushHistory(row, 'session_ended', { at: now.toISOString(), by: `owner (${actor.personId || 'local'})`, session_id: base, reason: why });
1082
+ result = {
1083
+ key_id: row.key_id, tag: row.tag, status: row.status, session_id: base,
1084
+ ended: true, carried_forward: true, state: 'closed', sessions: targets.length
1085
+ };
686
1086
  return true;
687
1087
  });
1088
+ await closeTranscriptList(deps, transcripts, now);
688
1089
  return result;
689
1090
  }
690
1091
 
@@ -725,6 +1126,7 @@ function presentFailure(found) {
725
1126
  */
726
1127
  export async function prepareSubkeyCall(ctx, actor, args, toolName) {
727
1128
  if (!subkeysEnabled()) return;
1129
+ if (actor) delete actor.subkeyRenewal;
728
1130
  const now = (ctx && ctx.now) || new Date();
729
1131
  const a = args || {};
730
1132
  const handle = typeof a.session_handle === 'string' ? a.session_handle.trim() : '';
@@ -738,8 +1140,8 @@ export async function prepareSubkeyCall(ctx, actor, args, toolName) {
738
1140
  return;
739
1141
  }
740
1142
 
741
- if (presentingKey && toolName !== 'emet_session_open') {
742
- throw refusal('a sub-key is presented only at emet_session_open. Pass session_handle on later writes. Nothing was written.');
1143
+ if (presentingKey && toolName !== 'emet_session_open' && toolName !== 'emet_session_close') {
1144
+ throw refusal('a sub-key is presented only at emet_session_open. Pass session_handle on later writes. emet_session_close may also present the key that opened the session. Nothing was written.');
743
1145
  }
744
1146
 
745
1147
  const base = toolName === 'emet_session_open' ? null : sessionBaseOf(a);
@@ -749,20 +1151,27 @@ export async function prepareSubkeyCall(ctx, actor, args, toolName) {
749
1151
  assertHttpOwner(actor, ctx && ctx.ownerId);
750
1152
  const parts = splitKeyToken(token);
751
1153
  const bucket = { keyId: parts.key_id, clientId: actor.clientId || null, sessionId: null };
1154
+ const priorHandle = handle;
752
1155
  let outcome = null;
1156
+ let priorOpened = null;
1157
+ let priorId = null;
753
1158
  await edit(ctx.deps, (data) => {
754
1159
  ensureMaps(data);
755
1160
  const found = lookupUsable(data, parts.key_id, parts.secret, peppers, now);
756
1161
  if (!found.ok) { outcome = { fail: found }; return found.changed === true; }
757
- const live = livePointer(found.row, data, now);
758
- if (live) {
1162
+ const decision = openDecision(data, found.row, now, priorHandle, peppers);
1163
+ if (decision.action === 'collision') {
759
1164
  found.row.collisions = Array.isArray(found.row.collisions) ? found.row.collisions : [];
760
1165
  found.row.collisions.push({ at: now.toISOString(), client_id: actor.clientId || null, grant_id: actor.grantId || null });
761
1166
  pushHistory(found.row, 'collision', { at: now.toISOString(), client_id: actor.clientId || null, grant_id: actor.grantId || null });
762
1167
  outcome = { collision: true, key_id: found.row.key_id, tag: found.row.tag };
763
1168
  return true;
764
1169
  }
765
- outcome = { key_id: found.row.key_id, tag: found.row.tag };
1170
+ if (decision.prior) {
1171
+ priorOpened = decision.prior.opened_at || null;
1172
+ priorId = decision.prior.open_id || null;
1173
+ }
1174
+ outcome = { key_id: found.row.key_id, tag: found.row.tag, kind: clientKindOf(found.row), action: decision.action };
766
1175
  return false;
767
1176
  });
768
1177
  if (!outcome || (outcome.fail && outcome.fail.reason === 'mismatch')) {
@@ -772,6 +1181,9 @@ export async function prepareSubkeyCall(ctx, actor, args, toolName) {
772
1181
  if (outcome.fail) throw refusal(presentFailure(outcome.fail));
773
1182
  clearPresent(bucket);
774
1183
  if (outcome.collision) throw refusal('this sub-key already has a live session. Close it, or ask the owner to end it, before opening another. Nothing was opened.');
1184
+ let wrapFound = false;
1185
+ if (outcome.kind === 'chat' && priorOpened) wrapFound = await wrapUpFound(ctx, outcome.tag, priorOpened, now);
1186
+ openPlans.set(actor, { handle: priorHandle, wrapFound, prior_open_id: priorId });
775
1187
  actor.subkeySession = true;
776
1188
  actor.subkeyTag = outcome.tag;
777
1189
  actor.subkeyId = outcome.key_id;
@@ -794,9 +1206,14 @@ export async function prepareSubkeyCall(ctx, actor, args, toolName) {
794
1206
  }
795
1207
 
796
1208
  let session = null;
1209
+ let keyStatus = null;
797
1210
  await edit(ctx.deps, (data) => {
798
1211
  ensureMaps(data);
799
1212
  if (base) session = currentSession(data, base, now);
1213
+ if (session) {
1214
+ const row = keyById(data, session.key_id);
1215
+ keyStatus = row ? row.status : null;
1216
+ }
800
1217
  return false;
801
1218
  });
802
1219
 
@@ -804,53 +1221,103 @@ export async function prepareSubkeyCall(ctx, actor, args, toolName) {
804
1221
  const peppers = requirePepper();
805
1222
  assertHttpOwner(actor, ctx && ctx.ownerId);
806
1223
  const bucket = { keyId: session.key_id, clientId: actor.clientId || null, sessionId: base };
807
- if (session.state !== 'live') {
808
- const why = session.state === 'revoked'
809
- ? 'sub-key revoked; open a new session with a current key'
810
- : session.state === 'ended'
1224
+ if (session.state === 'revoked' || keyStatus === 'revoked') {
1225
+ throw refusal('sub-key revoked; open a new session with a current key. Nothing was written.');
1226
+ }
1227
+ const stranded = isSessionStranded(session, now);
1228
+ const read = !WRITE_TOOLS.has(toolName);
1229
+ if (!stranded) {
1230
+ if (session.state !== 'live' && session.state !== 'renewal_offered') {
1231
+ const why = session.state === 'ended'
811
1232
  ? 'this sub-key session was ended; open a new session'
812
1233
  : session.state === 'closed'
813
1234
  ? 'this sub-key session is closed; open a new session'
814
1235
  : 'this sub-key session is no longer live; open a new session';
815
- throw refusal(`${why}. Nothing was written.`);
816
- }
817
- if (past(session.expires_at, now)) {
818
- await edit(ctx.deps, (data) => {
819
- const s = currentSession(data, base, now);
820
- const row = s && keyById(data, s.key_id);
821
- if (s && s.state === 'live') { s.state = 'expired'; s.ended_at = now.toISOString(); s.end_reason = 'handle expired'; }
822
- if (row && row.live_session_id === s.open_id) row.live_session_id = null;
823
- if (row) pushHistory(row, 'handle_expired', { at: now.toISOString(), session_id: base });
824
- return true;
825
- });
826
- throw refusal('this session handle has expired. Open a new session. Nothing was written.');
1236
+ throw refusal(`${why}. Nothing was written.`);
1237
+ }
1238
+ if (!HANDLE_RE.test(handle)) {
1239
+ const throttled = noteFailure(bucket, now);
1240
+ throw refusal(throttled || `session ${base} is a sub-key session; pass its session_handle. Nothing was written.`);
1241
+ }
1242
+ if (!verifyMac(session.handle_hmac, handle, peppers)) {
1243
+ const throttled = noteFailure(bucket, now);
1244
+ throw refusal(throttled || 'session handle does not match this sub-key session. Nothing was written.');
1245
+ }
1246
+ clearPresent(bucket);
1247
+ if (OWNER_ONLY_TOOLS.has(toolName)) {
1248
+ throw refusal('a sub-key session cannot call this tool. Nothing was changed.');
1249
+ }
1250
+ const cur = await loadSubkeyRecords(ctx.deps);
1251
+ const row = keyById(cur, session.key_id);
1252
+ if (!row || row.status === 'revoked') throw refusal('sub-key revoked; open a new session with a current key. Nothing was written.');
1253
+ if (row.live_session_id !== session.open_id) throw refusal('this sub-key session is no longer the live session for its key. Nothing was written.');
1254
+ if (!usableKey(row, now)) throw refusal('this sub-key is no longer active. Nothing was written.');
1255
+ const declared = typeof a.source === 'string' && a.source.trim() ? a.source.trim() : (a.metadata && typeof a.metadata.source === 'string' ? a.metadata.source.trim() : '');
1256
+ if (declared && declared !== row.tag) {
1257
+ throw refusal(`this session is bound to "${row.tag}"; "${declared}" does not match. Nothing was written.`);
1258
+ }
1259
+ if (toolName === 'emet_status') {
1260
+ if (phaseOf(session.expires_at, now) === 'window') actor.subkeyRenewal = renewalRequest(session);
1261
+ actor.subkeySession = true;
1262
+ actor.subkeyTag = row.tag;
1263
+ actor.subkeyId = row.key_id;
1264
+ return;
1265
+ }
1266
+ if (phaseOf(session.expires_at, now) === 'window') {
1267
+ await edit(ctx.deps, (data) => {
1268
+ const s = currentSession(data, base, now);
1269
+ if (s && s.state === 'live' && s.open_id === session.open_id) {
1270
+ s.state = 'renewal_offered';
1271
+ return true;
1272
+ }
1273
+ return false;
1274
+ });
1275
+ actor.subkeyRenewal = renewalRequest(session);
1276
+ }
1277
+ await (await storeFor(ctx.deps)).touchLastUsed(session.key_id, now.toISOString());
1278
+ actor.subkeySession = true;
1279
+ actor.subkeyTag = row.tag;
1280
+ actor.subkeyId = row.key_id;
1281
+ return;
827
1282
  }
828
- if (!HANDLE_RE.test(handle)) {
829
- const throttled = noteFailure(bucket, now);
830
- throw refusal(throttled || `session ${base} is a sub-key session; pass its session_handle. Nothing was written.`);
1283
+
1284
+ const cur = await loadSubkeyRecords(ctx.deps);
1285
+ const row = keyById(cur, session.key_id);
1286
+ const kind = clientKindOf(row);
1287
+ const handleOk = handleMatches(session, handle, peppers);
1288
+ let keyOk = false;
1289
+ if (presentingKey) {
1290
+ const parts = splitKeyToken(token);
1291
+ keyOk = !!(parts && row && parts.key_id === row.key_id && verifyMac(row.secret_hmac, parts.secret, peppers));
831
1292
  }
832
- if (!verifyMac(session.handle_hmac, handle, peppers)) {
833
- const throttled = noteFailure(bucket, now);
834
- throw refusal(throttled || 'session handle does not match this sub-key session. Nothing was written.');
1293
+ const owner = actorIsOwner(actor, (ctx && ctx.ownerId) || (actor && actor.ownerId));
1294
+ if (handleOk) clearPresent(bucket);
1295
+ if (toolName === 'emet_session_close' && (owner || handleOk || keyOk)) {
1296
+ if (row && (handleOk || keyOk)) {
1297
+ actor.subkeySession = true;
1298
+ actor.subkeyTag = row.tag;
1299
+ actor.subkeyId = row.key_id;
1300
+ }
1301
+ return;
835
1302
  }
836
- clearPresent(bucket);
837
- if (OWNER_ONLY_TOOLS.has(toolName)) {
838
- throw refusal('a sub-key session cannot call this tool. Nothing was changed.');
1303
+ let wrap = true;
1304
+ if (kind === 'chat' && row && (handleOk || session.state === 'expired' || session.state === 'unwrapped' || phaseOf(session.expires_at, now) === 'grace')) {
1305
+ wrap = await wrapUpFound(ctx, row.tag, session.opened_at, now);
839
1306
  }
840
- const cur = await loadSubkeyRecords(ctx.deps);
841
- const row = keyById(cur, session.key_id);
842
- if (!row || row.status === 'revoked') throw refusal('sub-key revoked; open a new session with a current key. Nothing was written.');
843
- if (row.live_session_id !== session.open_id) throw refusal('this sub-key session is no longer the live session for its key. Nothing was written.');
844
- if (!usableKey(row, now)) throw refusal('this sub-key is no longer active. Nothing was written.');
845
- const declared = typeof a.source === 'string' && a.source.trim() ? a.source.trim() : (a.metadata && typeof a.metadata.source === 'string' ? a.metadata.source.trim() : '');
846
- if (declared && declared !== row.tag) {
847
- throw refusal(`this session is bound to "${row.tag}"; "${declared}" does not match. Nothing was written.`);
1307
+ const notice = kind === 'chat' && !wrap
1308
+ ? { ...renewalRequest(session), wrap_up_notice: UNWRAPPED_NOTICE, message: UNWRAPPED_NOTICE }
1309
+ : renewalRequest(session);
1310
+ if (read) {
1311
+ actor.subkeyRenewal = notice;
1312
+ if (handleOk && row) {
1313
+ actor.subkeySession = true;
1314
+ actor.subkeyTag = row.tag;
1315
+ actor.subkeyId = row.key_id;
1316
+ }
1317
+ return;
848
1318
  }
849
- await (await storeFor(ctx.deps)).touchLastUsed(session.key_id, now.toISOString());
850
- actor.subkeySession = true;
851
- actor.subkeyTag = row.tag;
852
- actor.subkeyId = row.key_id;
853
- return;
1319
+ const message = strandedWriteMessage(session, kind, wrap, now);
1320
+ throw hold(message, { ...notice, message, session_id: base });
854
1321
  }
855
1322
 
856
1323
  if (presentingHandle) {
@@ -863,52 +1330,76 @@ export async function prepareSubkeyCall(ctx, actor, args, toolName) {
863
1330
  export async function commitLiveSession(deps, actor, base, now = new Date()) {
864
1331
  const token = openTokens.get(actor);
865
1332
  if (!token || !base) return null;
1333
+ const plan = openPlans.get(actor) || { handle: '', wrapFound: false, prior_open_id: null };
866
1334
  const peppers = requirePepper();
867
1335
  const parts = splitKeyToken(token);
868
1336
  if (!parts) throw refusal('emet_session_open: this sub-key does not match an active key. Nothing was opened.');
869
1337
  const handle = `${HANDLE_PREFIX}${b64(32)}`;
870
1338
  let collision = false;
871
1339
  let failed = null;
1340
+ let notice = null;
1341
+ const transcripts = [];
872
1342
  await edit(deps, (data) => {
873
1343
  ensureMaps(data);
874
1344
  const found = lookupUsable(data, parts.key_id, parts.secret, peppers, now);
875
1345
  if (!found.ok) { failed = found; return found.changed === true; }
876
- const live = livePointer(found.row, data, now);
877
- if (live) {
878
- found.row.collisions = Array.isArray(found.row.collisions) ? found.row.collisions : [];
879
- found.row.collisions.push({ at: now.toISOString(), client_id: actor.clientId || null, grant_id: actor.grantId || null });
880
- pushHistory(found.row, 'collision', { at: now.toISOString(), client_id: actor.clientId || null });
1346
+ const decision = openDecision(data, found.row, now, plan.handle, peppers);
1347
+ if (decision.action === 'collision') {
1348
+ recordCollision(found.row, now, actor);
881
1349
  collision = true;
882
1350
  return true;
883
1351
  }
884
- if (found.row.live_session_id) endLive(data, found.row, 'ended', now, 'session lost');
1352
+ if (decision.action === 'reclaim' && healthySlot(decision.prior, now)) recordCollision(found.row, now, actor);
1353
+ const wrapFound = !!(decision.prior && decision.prior.open_id === plan.prior_open_id && plan.wrapFound === true);
885
1354
  const open_id = hexId();
886
1355
  const expires_at = new Date(now.getTime() + HANDLE_TTL_MS).toISOString();
887
- data.sessions.push({
1356
+ const created = {
888
1357
  open_id, session_id: base,
889
1358
  key_id: found.row.key_id, tag: found.row.tag, state: 'live',
890
1359
  handle_hmac: seal(handle, peppers),
891
1360
  opened_at: now.toISOString(), expires_at,
892
- client_id: actor.clientId || null, grant_id: actor.grantId || null
893
- });
894
- found.row.live_session_id = open_id;
1361
+ client_id: actor.clientId || null, grant_id: actor.grantId || null,
1362
+ retained: true, deleted: false
1363
+ };
1364
+ notice = settlePriors(data, found.row, created, now, { action: decision.action, prior: decision.prior, wrapFound }, transcripts);
1365
+ if (found.row.live_session_id && found.row.live_session_id !== created.open_id) {
1366
+ endLive(data, found.row, 'ended', now, 'session lost');
1367
+ }
1368
+ data.sessions.push(created);
1369
+ found.row.live_session_id = created.open_id;
895
1370
  found.row.live_set_at = now.toISOString();
896
1371
  found.row.last_used = now.toISOString();
897
- pushHistory(found.row, 'session_open', { at: now.toISOString(), session_id: base, open_id, client_id: actor.clientId || null, expires_at });
1372
+ pushHistory(found.row, 'session_open', {
1373
+ at: now.toISOString(), session_id: base, open_id, client_id: actor.clientId || null, expires_at,
1374
+ prev_open_id: created.prev_open_id || null, prev_session_id: created.prev_session_id || null
1375
+ });
898
1376
  return true;
899
1377
  });
900
1378
  if (failed) throw refusal(presentFailure(failed));
901
1379
  if (collision) throw refusal('this sub-key already has a live session. Nothing was opened.');
1380
+ await closeTranscriptList(deps, transcripts, now);
902
1381
  openTokens.delete(actor);
1382
+ openPlans.delete(actor);
1383
+ if (notice) {
1384
+ actor.subkeyRenewal = notice;
1385
+ openNotices.set(actor, notice);
1386
+ }
903
1387
  return handle;
904
1388
  }
905
1389
 
906
1390
  export function takeOpenToken(actor) { return openTokens.get(actor) || null; }
907
1391
 
1392
+ /** The notice commit stored for this open. One read. */
1393
+ export function takeOpenNotice(actor) {
1394
+ const notice = actor ? openNotices.get(actor) || null : null;
1395
+ if (actor) openNotices.delete(actor);
1396
+ return notice;
1397
+ }
1398
+
908
1399
  /**
909
- * Release a live sub-key session when its own close completes. The caller
910
- * must present that session's sub-key and its session handle. A close that
911
- * names another session, or that lacks either secret, leaves the record live.
1400
+ * Release a sub-key session when its own close completes. The caller
1401
+ * presents that session's key and its handle. An expired handle still
1402
+ * releases when the key matches. A different key releases nothing.
912
1403
  */
913
1404
  export async function releaseClosedSession(deps, base, now = new Date(), proof = null) {
914
1405
  if (!subkeysEnabled() || !base) return null;
@@ -921,21 +1412,47 @@ export async function releaseClosedSession(deps, base, now = new Date(), proof =
921
1412
  let released = null;
922
1413
  await edit(deps, (data) => {
923
1414
  ensureMaps(data);
924
- const s = (data.sessions || []).find((row) => row && row.session_id === base && row.state === 'live' && row.key_id === parts.key_id && !past(row.expires_at, now));
1415
+ const row = keyById(data, parts.key_id);
1416
+ if (!row || !verifyMac(row.secret_hmac, parts.secret, peppers)) return false;
1417
+ const s = (data.sessions || []).find((item) => item && item.session_id === base && item.key_id === parts.key_id && !isTerminalState(item.state) && verifyMac(item.handle_hmac, handle, peppers));
925
1418
  if (!s) return false;
926
- const row = keyById(data, s.key_id);
927
- if (!row || !verifyMac(s.handle_hmac, handle, peppers) || !verifyMac(row.secret_hmac, parts.secret, peppers)) return false;
928
- s.state = 'closed';
929
- s.ended_at = now.toISOString();
930
- s.end_reason = 'session closed';
931
- if (row.live_session_id === s.open_id) row.live_session_id = null;
932
- pushHistory(row, 'session_closed', { at: s.ended_at, session_id: base, open_id: s.open_id });
933
- released = { key_id: s.key_id, session_id: base, open_id: s.open_id };
1419
+ carryForwardClose(data, s, now, 'session closed', 'session_closed', null);
1420
+ released = { key_id: s.key_id, session_id: base, open_id: s.open_id, state: 'closed' };
934
1421
  return true;
935
1422
  });
936
1423
  return released;
937
1424
  }
938
1425
 
1426
+ /** Close ended links and sessions past the grace window. Nothing is deleted. */
1427
+ export async function sweepStrandedSessions(deps, now = new Date()) {
1428
+ if (!subkeysEnabled()) return 0;
1429
+ let n = 0;
1430
+ let transcripts = [];
1431
+ await edit(deps || {}, (data) => {
1432
+ ensureMaps(data);
1433
+ n = closeStranded(data, now);
1434
+ transcripts = strandedTranscripts(data, now);
1435
+ return n > 0;
1436
+ });
1437
+ const closed = await closeTranscriptList(deps, transcripts, now);
1438
+ return n + closed;
1439
+ }
1440
+
1441
+ /** One pass at startup, then a periodic pass. It does not block listen. */
1442
+ export function startStrandedSweep(log, dbManager) {
1443
+ if (!subkeysEnabled()) return;
1444
+ const go = () => {
1445
+ sweepStrandedSessions({ dbManager }).then((n) => {
1446
+ if (n > 0 && typeof log === 'function') log(`sub-key sweep closed ${n} stranded session${n === 1 ? '' : 's'}`);
1447
+ }).catch((e) => {
1448
+ if (typeof log === 'function') log(`sub-key sweep failed: ${e && e.message ? e.message : 'unknown error'}`);
1449
+ });
1450
+ };
1451
+ go();
1452
+ const timer = setInterval(go, sweepIntervalMs());
1453
+ if (timer.unref) timer.unref();
1454
+ }
1455
+
939
1456
  function keyMapOf(data) {
940
1457
  if (!data) return {};
941
1458
  if (data.keys && typeof data.keys === 'object' && !Array.isArray(data.keys)) return data.keys;
@@ -957,6 +1474,8 @@ export function subkeysView(data, actor, ownerId, now = new Date()) {
957
1474
  const pendingReplacement = !!replaces && (k.status === 'pending' || k.status === 'approved');
958
1475
  return {
959
1476
  tag: k.tag, key_id: k.key_id, status: k.status,
1477
+ client_kind: k.client_kind === 'chat' ? 'chat' : (k.client_kind === 'bot' ? 'bot' : null),
1478
+ requested_client_kind: k.requested_client_kind || null,
960
1479
  requested_at: k.requested_at || null,
961
1480
  approved_at: k.approved_at || null,
962
1481
  created_at: k.created_at || null,
@@ -995,17 +1514,57 @@ export async function readSubkeyHistory(deps, actor, ownerId) {
995
1514
  }));
996
1515
  }
997
1516
 
1517
+ /** Set the kind stored on an approved key. Owner only. A missing kind stays bot until this writes one. */
1518
+ export async function setSubkeyClientKind(deps, actor, ownerId, { tag, key_id, client_kind } = {}, now = new Date()) {
1519
+ if (!subkeysEnabled()) throw refusal('sub-keys are off (EMET_SUBKEYS is not 1). Nothing was changed.');
1520
+ requirePepper();
1521
+ assertOwnerActor(actor, ownerId, 'emet_subkey_set_kind');
1522
+ const kind = clientKindValue(client_kind);
1523
+ if (!kind) throw refusal('emet_subkey_set_kind: "client_kind" must be "bot" or "chat". Nothing was changed.');
1524
+ const id = typeof key_id === 'string' ? key_id.trim() : '';
1525
+ const t = typeof tag === 'string' ? tag.trim() : '';
1526
+ if (!id && !t) throw refusal('emet_subkey_set_kind: pass "tag" or "key_id". Nothing was changed.');
1527
+ let result = null;
1528
+ await edit(deps, (data) => {
1529
+ ensureMaps(data);
1530
+ const row = id
1531
+ ? keyById(data, id)
1532
+ : Object.values(data.keys).find((k) => k && k.tag === t && ['approved', 'active', 'grace'].includes(k.status));
1533
+ if (!row) throw refusal('emet_subkey_set_kind: no sub-key matched. Nothing was changed.');
1534
+ if (!['approved', 'active', 'grace'].includes(row.status)) {
1535
+ throw refusal(`emet_subkey_set_kind: "${row.tag}" is not an approved key. Nothing was changed.`);
1536
+ }
1537
+ const previous = row.client_kind === 'chat' ? 'chat' : (row.client_kind === 'bot' ? 'bot' : null);
1538
+ if ((previous || 'bot') === kind && row.client_kind === kind) {
1539
+ result = { key_id: row.key_id, tag: row.tag, client_kind: kind, previous: previous || 'bot', unchanged: true };
1540
+ return false;
1541
+ }
1542
+ row.client_kind = kind;
1543
+ pushHistory(row, 'client_kind', {
1544
+ at: now.toISOString(),
1545
+ by: `owner (${actor.personId || 'local'})`,
1546
+ client_kind: kind,
1547
+ previous: previous || 'bot'
1548
+ });
1549
+ result = { key_id: row.key_id, tag: row.tag, client_kind: kind, previous: previous || 'bot', unchanged: false };
1550
+ return true;
1551
+ });
1552
+ return result;
1553
+ }
1554
+
998
1555
  export async function dispatchSubkey(name, deps, actor, ownerId, args, registry, now) {
999
1556
  const a = args || {};
1000
1557
  if (name === 'emet_subkey_request') return requestSubkey(deps, actor, a, registry, now);
1001
1558
  if (name === 'emet_subkey_claim') return claimSubkey(deps, actor, a, now);
1002
1559
  if (name === 'emet_subkey_revoke') return revokeSubkey(deps, actor, ownerId, a, now);
1003
1560
  if (name === 'emet_subkey_end_session') return endSubkeySession(deps, actor, ownerId, a, now);
1561
+ if (name === 'emet_subkey_set_kind') return setSubkeyClientKind(deps, actor, ownerId, a, now);
1004
1562
  throw refusal(`unknown sub-key tool ${name}. Nothing was changed.`);
1005
1563
  }
1006
1564
 
1007
1565
  export default {
1008
1566
  requestSubkey, claimSubkey, revokeSubkey, endSubkeySession,
1009
1567
  decideSubkeyIfPending, prepareSubkeyCall, commitLiveSession, releaseClosedSession,
1568
+ sweepStrandedSessions, startStrandedSweep, takeOpenNotice, wrapUpFound, setSubkeyClientKind,
1010
1569
  subkeysView, readSubkeyHistory, dispatchSubkey, verifyMac, macEqual, splitKeyToken, pepperState
1011
1570
  };