@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/persons.js CHANGED
@@ -83,6 +83,22 @@ export function rawActor() {
83
83
  return s && typeof s === 'object' ? s : null;
84
84
  }
85
85
 
86
+ /**
87
+ * The HTTP credential's tag. Stdio returns null: the caller’s declared tag
88
+ * stands there. A claimed basis is not a credential.
89
+ */
90
+ export function httpCredentialTag() {
91
+ const actor = currentActor();
92
+ if (!actor || actor.transport !== 'http') return null;
93
+ const attr = declaredAttribution();
94
+ const basis = attr && attr.basis;
95
+ if (basis === 'subkey' && attr.effective) return { tag: String(attr.effective).trim(), claimedOnly: false };
96
+ if (basis === 'declared' || basis === 'auto' || basis === 'legacy') return { tag: null, claimedOnly: true };
97
+ if (attr && attr.login) return { tag: attr.login, claimedOnly: false };
98
+ if (typeof actor.sourceTag === 'string' && actor.sourceTag.trim()) return { tag: actor.sourceTag.trim(), claimedOnly: false };
99
+ return { tag: null, claimedOnly: false };
100
+ }
101
+
86
102
  /** Per-request attribution set by attribution.preflight (HTTP only). */
87
103
  export function declaredAttribution() {
88
104
  const s = actorStore.getStore();
@@ -51,6 +51,7 @@
51
51
 
52
52
  import { setting } from './env.js';
53
53
  import { CodedError } from './error-codes.js';
54
+ import { httpCredentialTag } from './persons.js';
54
55
 
55
56
  export const GRAPH_MODES = Object.freeze(['enforce']);
56
57
 
@@ -112,6 +113,72 @@ export function writeSourceOf(args = {}) {
112
113
  return typeof v === 'string' && v.trim() ? v.trim() : null;
113
114
  }
114
115
 
116
+ function declaredSessionTag(tool, args = {}) {
117
+ if (tool === 'emet_session_open') {
118
+ const v = typeof args.source === 'string' ? args.source.trim() : '';
119
+ return v || null;
120
+ }
121
+ if (tool === 'save_to_layer') {
122
+ const md = args.metadata;
123
+ const v = md && typeof md === 'object' && !Array.isArray(md) && typeof md.source === 'string' ? md.source.trim() : '';
124
+ return v || null;
125
+ }
126
+ return writeSourceOf(args);
127
+ }
128
+
129
+ const SESSION_TAG_TOOLS = new Set(['emet_session_open', 'save_to_layer', 'write_doc', 'patch_doc', 'write_doc_commit']);
130
+
131
+ /**
132
+ * The tag a session row may store. The row stores a tag only while the
133
+ * per-tag flag is warn or enforce. With the flag on, HTTP uses the
134
+ * credential. A claimed HTTP caller stores no tag. Stdio uses the declared
135
+ * tag. A top-level source on save_to_layer is not a field of that tool.
136
+ */
137
+ export function sessionTagFrom(tool, args = {}) {
138
+ if (!tagHandoffsOn()) return null;
139
+ const declared = declaredSessionTag(tool, args);
140
+ const cred = httpCredentialTag();
141
+ if (!cred) return declared;
142
+ if (cred.claimedOnly) return null;
143
+ if (cred.tag) return cred.tag;
144
+ return declared;
145
+ }
146
+
147
+ /**
148
+ * With the per-tag flag on, an HTTP session tag comes from the credential.
149
+ * A declared tag that differs, and a claimed tag on a session, are refused.
150
+ * A call that declares no tag is kept. The flag off skips this check. Stdio
151
+ * is unchanged. write_doc, patch_doc and write_doc_commit are checked when
152
+ * they name a session.
153
+ */
154
+ export async function refuseForeignSessionTag(tool, args = {}) {
155
+ if (!tagHandoffsOn() || !SESSION_TAG_TOOLS.has(tool)) return;
156
+ if (tool !== 'emet_session_open' && tool !== 'save_to_layer') {
157
+ const sid = args && args.session_id;
158
+ if (typeof sid !== 'string' || !sid.trim()) return;
159
+ }
160
+ const cred = httpCredentialTag();
161
+ if (!cred) return;
162
+ const declared = declaredSessionTag(tool, args);
163
+ if (!declared) return;
164
+ const { ValidationError } = await import('./validation.js');
165
+ if (cred.claimedOnly) {
166
+ throw new ValidationError(
167
+ 'This HTTP call is a claimed tag, not a credential, so it cannot name a session tag. Nothing was written.',
168
+ { code: 'EMET-DOC-088' }
169
+ );
170
+ }
171
+ // This branch is now reachable only by sub-key callers. A bound login
172
+ // declaring a different tag is classified claimed and refused by the
173
+ // cred.claimedOnly branch above.
174
+ if (cred.tag && declared !== cred.tag) {
175
+ throw new ValidationError(
176
+ `The declared tag ${declared} is not this credential's tag ${cred.tag}. The session tag comes from the credential. Nothing was written.`,
177
+ { code: 'EMET-DOC-088' }
178
+ );
179
+ }
180
+ }
181
+
115
182
  /** write_doc, and the staged begin/commit that land a handoff through that door. Append and abort do not. */
116
183
  const HANDOFF_STAGE_TOOLS = new Set(['write_doc', 'write_doc_begin', 'write_doc_commit']);
117
184
 
@@ -122,8 +189,20 @@ export function isBotHandoffWrite(tool, args = {}) {
122
189
  return !!tag && isBotTag(tag) && args.doc_id === botHandoffDoc(tag);
123
190
  }
124
191
 
192
+ function tagHandoffsOn() {
193
+ const value = String(setting('TAG_HANDOFFS', 'off') ?? 'off').trim().toLowerCase();
194
+ return value === 'warn' || value === 'enforce';
195
+ }
196
+
197
+ /** write_doc (or staged begin/commit) of HANDOFF/<source>.md while per-tag handoffs are on. */
198
+ export function isTagHandoffWrite(tool, args = {}) {
199
+ if (!tagHandoffsOn() || !HANDOFF_STAGE_TOOLS.has(tool)) return false;
200
+ const tag = writeSourceOf(args);
201
+ return !!tag && args.doc_id === `HANDOFF/${tag}.md`;
202
+ }
203
+
125
204
  function handoffRecordWrite(tool, args = {}) {
126
- return HANDOFF_STAGE_TOOLS.has(tool) && (args.doc_id === HANDOFF_DOC || isBotHandoffWrite(tool, args));
205
+ return HANDOFF_STAGE_TOOLS.has(tool) && (args.doc_id === HANDOFF_DOC || isBotHandoffWrite(tool, args) || isTagHandoffWrite(tool, args));
127
206
  }
128
207
 
129
208
  /** The base session id of a part id (2026-09-30_x_verbatim_part2 -> 2026-09-30_x). */
@@ -284,9 +363,10 @@ export function evaluate(tool, args = {}, state = {}, highest = 0, now = new Dat
284
363
  // Begin and commit of a handoff take the gate. Append and abort do not, and
285
364
  // begin does not count as the handoff being written.
286
365
  const botHandoff = isBotHandoffWrite(tool, args);
366
+ const tagHandoff = isTagHandoffWrite(tool, args);
287
367
  if (handoffRecordWrite(tool, args)) {
288
368
  const missing = [];
289
- if (!botHandoff && !state.board) missing.push(`the board (${BOARD_DOC}) with patch_doc`);
369
+ if (!botHandoff && !tagHandoff && !state.board) missing.push(`the board (${BOARD_DOC}) with patch_doc`);
290
370
  if (!state.episodic) missing.push('the episodic session record with save_to_layer (layer "episodic")');
291
371
  if (!(highest > 0)) missing.push('the transcript with emet_transcript_append');
292
372
  if (missing.length) {
@@ -300,8 +380,8 @@ export function evaluate(tool, args = {}, state = {}, highest = 0, now = new Dat
300
380
  // pre-call step, because that step is still the one owed.
301
381
  let after = { state, highest };
302
382
  if (tool === 'emet_transcript_append' && n !== null && n === highest + 1) after = { state: { ...state, opened: true }, highest: n };
303
- if ((tool === 'write_doc' || tool === 'write_doc_commit') && (args.doc_id === HANDOFF_DOC || botHandoff)) after = { state: { ...state, handoff: true }, highest };
304
- if (tool === 'write_doc_begin' && (args.doc_id === HANDOFF_DOC || botHandoff)) {
383
+ if ((tool === 'write_doc' || tool === 'write_doc_commit') && (args.doc_id === HANDOFF_DOC || botHandoff || tagHandoff)) after = { state: { ...state, handoff: true }, highest };
384
+ if (tool === 'write_doc_begin' && (args.doc_id === HANDOFF_DOC || botHandoff || tagHandoff)) {
305
385
  return {
306
386
  verdict: 'ok', gate: null, reason: null,
307
387
  next: 'write_doc_append each part in order, then write_doc_commit with the sha256 of the whole document'
@@ -327,7 +407,7 @@ export function recordStep(tool, args = {}, data = {}, now = new Date()) {
327
407
  if (tool === 'emet_transcript_append' || tool === 'save_transcript') return null;
328
408
  if (tool === 'save_to_layer' && args.layer === 'episodic') return { episodic: true, episodic_id: data && data.id };
329
409
  if ((tool === 'write_doc' || tool === 'patch_doc' || tool === 'restore_doc') && args.doc_id === BOARD_DOC) return { board: true, board_version: data && data.version };
330
- if ((tool === 'write_doc' || tool === 'write_doc_commit') && (args.doc_id === HANDOFF_DOC || isBotHandoffWrite(tool, args))) return { handoff: true, handoff_version: data && data.version };
410
+ if ((tool === 'write_doc' || tool === 'write_doc_commit') && (args.doc_id === HANDOFF_DOC || isBotHandoffWrite(tool, args) || isTagHandoffWrite(tool, args))) return { handoff: true, handoff_version: data && data.version };
331
411
  if (tool === 'emet_session_close' && data && data.state === 'complete') return { closed: true, closed_at: now };
332
412
  return null;
333
413
  }
@@ -386,6 +466,34 @@ export async function isSessionClosed(base, dbManager) {
386
466
  export const DEFAULT_CLOSE_GRACE_MINUTES = 5;
387
467
  export const MAX_CLOSE_GRACE_MINUTES = 60;
388
468
 
469
+ /**
470
+ * Close one transcript session and keep the row. Nothing is deleted.
471
+ * An already-closed row is left as it is. A missing row is not created.
472
+ * `closed_by` is `server-sweep` or `reclaim by key <key_id>`.
473
+ */
474
+ export async function retainSessionClose(dbManager, base, { at = new Date(), closed_by, note } = {}) {
475
+ if (!base || !dbManager || typeof dbManager.ensureClient !== 'function') return { recorded: false, base: base || null };
476
+ const when = at instanceof Date && !Number.isNaN(at.getTime()) ? at : new Date();
477
+ const who = typeof closed_by === 'string' && closed_by.trim() ? closed_by.trim() : 'server-sweep';
478
+ const col = await sessionsCollection(dbManager);
479
+ const row = await col.findOne({ _id: base });
480
+ if (!row) return { recorded: false, missing: true, base };
481
+ if (row.closed === true) return { recorded: false, already: true, base };
482
+ const entry = {
483
+ at: when.toISOString(),
484
+ closed_by: who,
485
+ note: typeof note === 'string' && note.trim() ? note.trim() : `Closed ${when.toISOString()} by ${who}. The transcript stays.`
486
+ };
487
+ const res = await col.updateOne(
488
+ { _id: base, closed: { $ne: true } },
489
+ {
490
+ $set: { closed: true, closed_at: when, closed_by: who, retained: true, deleted: false, updated_at: when },
491
+ $push: { close_history: entry }
492
+ }
493
+ );
494
+ return { recorded: !!(res && res.matchedCount === 1), base };
495
+ }
496
+
389
497
  /**
390
498
  * The window setting, checked (2026-10-01, Tester's nit 4). Unset or blank: the
391
499
  * default, 5. A number from 0 to 60: that many minutes (0 turns the window
@@ -741,6 +849,7 @@ export async function startupPagesGate(args = {}, now = new Date()) {
741
849
  * Throws a ValidationError when the decision is a refusal.
742
850
  */
743
851
  export async function graphBefore(tool, args, dbManager, now = new Date()) {
852
+ await refuseForeignSessionTag(tool, args);
744
853
  const mode = graphMode();
745
854
  if (tool === STARTUP_PAGES_TOOL) return startupPagesGate(args, now);
746
855
  if (!GRAPH_WRITE_TOOLS.has(tool)) return null;
@@ -953,7 +1062,9 @@ export async function graphAfter(tool, args, data, dbManager, logger = null, now
953
1062
  const unverified = tool === 'emet_session_open' && data && data.drops_unverified === true ? { drops_unverified: true } : {};
954
1063
  const verifiedOpen = tool === 'emet_session_open' && data && data.drops_unverified !== true && Array.isArray(data.drops_seen);
955
1064
  const clearUnverified = verifiedOpen ? { $unset: { drops_unverified: '' } } : {};
956
- await col.updateOne({ _id: base }, { $set: { ...set, ...unverified, updated_at: now }, $setOnInsert: { created_at: now, ...opened }, ...addDrops, ...clearUnverified }, { upsert: true });
1065
+ const tag = sessionTagFrom(tool, args);
1066
+ const tagged = tag ? { tag } : {};
1067
+ await col.updateOne({ _id: base }, { $set: { ...set, ...tagged, ...unverified, updated_at: now }, $setOnInsert: { created_at: now, ...opened }, ...addDrops, ...clearUnverified }, { upsert: true });
957
1068
  if (verifiedOpen && listed.length === 0) {
958
1069
  await col.updateOne({ _id: base, drops_seen: { $exists: false } }, { $set: { drops_seen: [] } });
959
1070
  }
@@ -964,4 +1075,4 @@ export async function graphAfter(tool, args, data, dbManager, logger = null, now
964
1075
  }
965
1076
  }
966
1077
 
967
- export default { GRAPH_MODES, graphMode, ID_ECHO_MAX, echoId, pageRanges, PAGE_LIST_MAX, unknownLoadIdDecision, GRAPH_WRITE_TOOLS, STARTUP_PAGES_TOOL, noLoadIdDecision, startupPagesDecision, startupPagesGate, recordLatePages, botRecordDir, botHandoffDoc, isBotTag, mainRecordIds, writeSourceOf, isBotHandoffWrite, baseOf, candidateBases, groupedUnder, isMintedPartOf, sessionOf, normalizeExchangeNumber, declaredExchange, CLOSED_NEXT, nextStep, evaluate, recordStep, graphBefore, graphBlock, graphAfter, sessionStatus, isSessionClosed, DEFAULT_CLOSE_GRACE_MINUTES, MAX_CLOSE_GRACE_MINUTES, closeGraceSetting, closeGraceMinutes, graceDecision, markCloseGrace, TRANSCRIPT_WRITE_TOOLS, closedSessionGuard, LAB_SUFFIX, labRow, labRecord, labSummary };
1078
+ export default { GRAPH_MODES, graphMode, ID_ECHO_MAX, echoId, pageRanges, PAGE_LIST_MAX, unknownLoadIdDecision, GRAPH_WRITE_TOOLS, STARTUP_PAGES_TOOL, noLoadIdDecision, startupPagesDecision, startupPagesGate, recordLatePages, botRecordDir, botHandoffDoc, isBotTag, mainRecordIds, writeSourceOf, isBotHandoffWrite, isTagHandoffWrite, sessionTagFrom, refuseForeignSessionTag, baseOf, candidateBases, groupedUnder, isMintedPartOf, sessionOf, normalizeExchangeNumber, declaredExchange, CLOSED_NEXT, nextStep, evaluate, recordStep, graphBefore, graphBlock, graphAfter, sessionStatus, isSessionClosed, retainSessionClose, DEFAULT_CLOSE_GRACE_MINUTES, MAX_CLOSE_GRACE_MINUTES, closeGraceSetting, closeGraceMinutes, graceDecision, markCloseGrace, TRANSCRIPT_WRITE_TOOLS, closedSessionGuard, LAB_SUFFIX, labRow, labRecord, labSummary };
package/src/session.js CHANGED
@@ -33,6 +33,7 @@
33
33
 
34
34
  import { connectMongo } from './mongo-connect.js';
35
35
  import { setting } from './env.js';
36
+ import { tagHandoffMode, stampWithoutAsOf, attachHandoffView, handoffIdsFor } from './per-tag-handoff.js';
36
37
  import { MONGODB_URI, MONGODB_DB, COLLECTION_PREFIX, DatabaseError } from './database.js';
37
38
  import { LAYERS } from './layers.js';
38
39
  import { parseMetadata } from './metadata.js';
@@ -467,7 +468,16 @@ export function checkReceipts(receipts, observed) {
467
468
  const problems = [];
468
469
  // A bot session (C1): observed.bot = {tag, handoff_doc, dir, main_records}.
469
470
  const bot = observed && observed.bot ? observed.bot : null;
470
- const FIELDS = bot ? BOT_RECEIPT_FIELDS : RECEIPT_FIELDS;
471
+ const tagOn = observed && observed.tag_handoffs === true;
472
+ const FIELDS = { ...(bot ? BOT_RECEIPT_FIELDS : RECEIPT_FIELDS) };
473
+ if (tagOn) {
474
+ FIELDS.handoff_doc = 'the handoff this credential wrote last';
475
+ FIELDS.handoff_view = 'the handoff_view stamp from initialize, including as_of';
476
+ if (!observed.board_updated) {
477
+ delete FIELDS.board_doc;
478
+ delete FIELDS.board_version;
479
+ }
480
+ }
471
481
  if (!receipts || typeof receipts !== 'object' || Array.isArray(receipts)) {
472
482
  return {
473
483
  supplied: false,
@@ -490,18 +500,22 @@ export function checkReceipts(receipts, observed) {
490
500
  // receipt that does is refused here, and those ids get no other check.
491
501
  const mainIds = bot ? (bot.main_records || []) : [];
492
502
  const isMain = (id) => mainIds.includes(id);
503
+ const ownBoardOk = tagOn && bot ? stateDoc() : null;
504
+ const forbiddenMain = (id) => isMain(id) && id !== ownBoardOk;
493
505
  if (bot) {
494
506
  const named = [
495
507
  ...(Array.isArray(receipts.working_docs) ? receipts.working_docs.map(receiptDocId) : []),
496
508
  typeof receipts.board_doc === 'string' ? receipts.board_doc : null,
497
509
  typeof receipts.handoff_doc === 'string' ? receipts.handoff_doc : null
498
- ].filter((id) => id && isMain(id));
510
+ ].filter((id) => id && forbiddenMain(id));
499
511
  if (named.length) {
500
512
  problems.push(`receipts name ${[...new Set(named)].join(', ')} - ${hubRecordsMessage(bot.tag)}`);
501
513
  }
502
- if (typeof receipts.handoff_doc === 'string' && receipts.handoff_doc && !isMain(receipts.handoff_doc) &&
503
- receipts.handoff_doc !== bot.handoff_doc) {
504
- problems.push(`handoff_doc names ${receipts.handoff_doc}; this session's handoff is ${bot.handoff_doc}`);
514
+ if (typeof receipts.handoff_doc === 'string' && receipts.handoff_doc && !isMain(receipts.handoff_doc)) {
515
+ const allowed = new Set([bot.handoff_doc, ...(handoffIdsFor(bot.tag) || [])]);
516
+ if (!allowed.has(receipts.handoff_doc)) {
517
+ problems.push(`handoff_doc names ${receipts.handoff_doc}; this session's handoff is ${[...allowed].join(' or ')}`);
518
+ }
505
519
  }
506
520
  }
507
521
 
@@ -568,6 +582,11 @@ export function checkReceipts(receipts, observed) {
568
582
  }
569
583
  }
570
584
 
585
+ if (tagOn && receipts && typeof receipts === 'object') {
586
+ const stamp = stampWithoutAsOf(receipts.handoff_view);
587
+ if (!stamp.ok) problems.push(`handoff_view ${stamp.reason}`);
588
+ }
589
+
571
590
  // 5. handoff, written last
572
591
  const h = docs.get(observed.handoff_doc);
573
592
  if (typeof receipts.handoff_version === 'number' && h && h.exists) {
@@ -770,7 +789,11 @@ export async function sessionClose(options = {}) {
770
789
  const bot = sessionTag && isBotTag(sessionTag)
771
790
  ? { tag: sessionTag, handoff_doc: botHandoffDoc(sessionTag), dir: botRecordDir(sessionTag), main_records: mainRecordIds() }
772
791
  : null;
773
- const sessionHandoff = bot ? bot.handoff_doc : handoffDoc();
792
+ const choices = handoffIdsFor(sessionTag);
793
+ const namedHandoff = receipts && typeof receipts.handoff_doc === 'string' ? receipts.handoff_doc : null;
794
+ const sessionHandoff = choices
795
+ ? ((namedHandoff && choices.includes(namedHandoff)) ? namedHandoff : choices[0])
796
+ : (bot ? bot.handoff_doc : handoffDoc());
774
797
 
775
798
  // --- continuity documents --------------------------------------------
776
799
  const receiptDocs = receipts
@@ -779,9 +802,10 @@ export async function sessionClose(options = {}) {
779
802
  : [];
780
803
  // A bot session checks its own handoff and no board; the main records are
781
804
  // read separately below, only to see whether the bot revised them.
805
+ const tagOn = tagHandoffMode() !== 'off';
782
806
  const wanted = bot
783
- ? [...new Set([bot.handoff_doc, ...(options.thread_docs || []), ...receiptDocs])].filter((id) => !bot.main_records.includes(id))
784
- : [...new Set([handoffDoc(), stateDoc(), ...(options.thread_docs || []), ...receiptDocs])];
807
+ ? [...new Set([sessionHandoff, ...(options.thread_docs || []), ...receiptDocs])].filter((id) => !bot.main_records.includes(id))
808
+ : [...new Set([sessionHandoff, stateDoc(), ...(options.thread_docs || []), ...receiptDocs])];
785
809
  const readDoc = async (docId) => {
786
810
  const found = await docs.findOne(
787
811
  { doc_id: docId },
@@ -943,10 +967,17 @@ export async function sessionClose(options = {}) {
943
967
  if (!d.exists) missing.push(`${d.doc_id} does not exist`);
944
968
  else if (bot && !d.updated_this_session && d.updated_in_window) {
945
969
  missing.push(`${d.doc_id} was not updated this session by ${bot.tag} - its revision in the window is by ${d.updated_by || '(no tag)'}`);
946
- } else if (!d.updated_this_session) missing.push(`${d.doc_id} was not updated this session`);
970
+ } else if (!d.updated_this_session) {
971
+ if (tagOn && !bot && d.doc_id === stateDoc()) continue;
972
+ missing.push(`${d.doc_id} was not updated this session`);
973
+ }
974
+ }
975
+ if (choices && namedHandoff && !choices.includes(namedHandoff)) {
976
+ missing.push(`handoff_doc names ${namedHandoff}; this session's handoff is ${choices.join(' or ')}`);
947
977
  }
948
978
  if (bot) {
949
979
  for (const m of mainRecords) {
980
+ if (tagOn && m.doc_id === stateDoc()) continue;
950
981
  if (m.revised_by_session_tag) missing.push(`${m.doc_id} was revised by ${bot.tag} this session - ${hubRecordsMessage(bot.tag)}`);
951
982
  }
952
983
  if (ownEpisodicCount === 0) missing.push(`no episodic entry was written this session under ${bot.tag}`);
@@ -979,13 +1010,16 @@ export async function sessionClose(options = {}) {
979
1010
  // procedural ref 391: receipts required from the first deploy; the former
980
1011
  // `unconfirmed` state is blocked, not passed).
981
1012
  const storeMissing = [...missing];
1013
+ const boardId = setting('STATE_DOC', 'STATE.md');
1014
+ const boardUpdated = documents.some((d) => d && d.doc_id === boardId && d.updated_this_session);
982
1015
  const receiptCheck = checkReceipts(receipts, {
983
1016
  documents,
984
1017
  episodic: receiptEpisodic,
985
1018
  episodic_rejected: episodicRejected,
986
1019
  transcript,
987
1020
  handoff_doc: sessionHandoff,
988
- ...(bot ? { bot } : {})
1021
+ ...(bot ? { bot } : {}),
1022
+ ...(tagHandoffMode() !== 'off' ? { tag_handoffs: true, board_updated: boardUpdated } : {})
989
1023
  });
990
1024
  for (const p of receiptCheck.problems) missing.push(p);
991
1025
  const foreign = foreignContinuityProblems({
@@ -1061,9 +1095,19 @@ export async function sessionClose(options = {}) {
1061
1095
  speak.push(note);
1062
1096
  }
1063
1097
 
1098
+ let handoffView = null;
1099
+ if (tagHandoffMode() !== 'off') {
1100
+ try {
1101
+ const echo = {};
1102
+ await attachHandoffView(conn.db, echo, null);
1103
+ handoffView = echo.handoff_view || null;
1104
+ } catch { handoffView = null; }
1105
+ }
1106
+
1064
1107
  return {
1065
1108
  state,
1066
1109
  speak,
1110
+ ...(handoffView ? { handoff_view: handoffView } : {}),
1067
1111
  close_attempts: {
1068
1112
  blocked_count: capped.blocked_count,
1069
1113
  cap: CLOSE_CAP,
package/src/setup.js CHANGED
@@ -47,6 +47,8 @@ import { registerSecretsFromEnv } from './redact.js';
47
47
  import { payloadForLayerCharter } from './startup-payload.js';
48
48
  import { namedItemsFrom } from './named-items.js';
49
49
  import { paginate, cacheLoad, cachedLoad, loadIdOf, restartPage, notePageServed, wholeStartup } from './startup-pages.js';
50
+ import { continuityCurrencyEnabled, loadContinuityCurrency, continuityCurrencyUnreadable } from './continuity-currency.js';
51
+ import { tagHandoffMode, attachHandoffView, credentialForWrite } from './per-tag-handoff.js';
50
52
 
51
53
  const DOCS_COLLECTION = 'documents';
52
54
  const CHARTER_DOC = 'CHARTER.md';
@@ -417,7 +419,10 @@ export function shortInstructions(available) {
417
419
  '`install_notes`; mint a session id from the user\'s local date; tag every write with this ' +
418
420
  'host\'s source tag. (4) After every startup page, call emet_session_open with its load_id, then say every name in ' +
419
421
  '`named_items` (half-state, dated within seven days, open, undecided, then parked under its own heading, never pressed). ' +
420
- 'Read HANDOFF.md and STATE.md when a section is marked unread. Then `lessons_pending`. A count is the check, never the list. ' +
422
+ (tagHandoffMode() === 'off'
423
+ ? 'Read HANDOFF.md and STATE.md when a section is marked unread. '
424
+ : 'Read the handoff view, your own handoff and STATE.md when a section is marked unread. The hub handoff stays HANDOFF.md. ') +
425
+ 'Then `lessons_pending`. A count is the check, never the list. ' +
421
426
  gemStartupLine(available) + ' Never open with a question alone. (5) Append every exchange with ' +
422
427
  'emet_transcript_append; pass session_id and exchange on every write; follow ' +
423
428
  '`session_graph.next`. (6) Close per ' +
@@ -1152,6 +1157,20 @@ async function buildStartup(options = {}) {
1152
1157
  const { approvalsDeps } = await import('./tools.js');
1153
1158
  subkeys = subkeysView(await loadSubkeyRecords(approvalsDeps), rawActor() || { transport: 'stdio' }, personId, new Date());
1154
1159
  }
1160
+ let continuity_currency = null;
1161
+ if (continuityCurrencyEnabled()) {
1162
+ try {
1163
+ continuity_currency = await loadContinuityCurrency(conn.db);
1164
+ } catch {
1165
+ continuity_currency = continuityCurrencyUnreadable();
1166
+ }
1167
+ }
1168
+ const handoffExtra = {};
1169
+ if (tagHandoffMode() !== 'off') {
1170
+ try {
1171
+ await attachHandoffView(conn.db, handoffExtra, credentialForWrite(null).tag);
1172
+ } catch { /* a failed view read does not block startup */ }
1173
+ }
1155
1174
 
1156
1175
  return {
1157
1176
  state: 'ready',
@@ -1160,6 +1179,8 @@ async function buildStartup(options = {}) {
1160
1179
  person_id: personId,
1161
1180
  ...((() => { const v = approvalsView(cachedApprovals(), rawActor() || { transport: 'stdio' }, null); return v ? { client_approvals: v } : {}; })()),
1162
1181
  ...(subkeys ? { subkeys } : {}),
1182
+ ...(continuity_currency ? { continuity_currency } : {}),
1183
+ ...handoffExtra,
1163
1184
  unhandled_drops: shown.map((d) => d.doc_id),
1164
1185
  unhandled_drops_more: Math.max(0, openDrops.length - shown.length),
1165
1186
  retired_drops: retiredDrops.map((d) => ({ doc_id: d.doc_id, ...retirementFields(d) })),
@@ -42,7 +42,8 @@ export function pageBudget(raw = process.env.EMET_INIT_PAGE_BYTES) {
42
42
 
43
43
  /** Binding first: the order keys are paged in. Keys not listed follow, in payload order. */
44
44
  export const PAGE_ORDER = Object.freeze([
45
- 'state', 'database', 'source_tag', 'grant_id', 'door', 'source_basis', 'source_login', 'source_remembered', 'approval_state', 'person_id', 'client_approvals', 'unhandled_drops', 'unhandled_drops_more', 'retired_drops', 'emet_line', 'emet_line_if_unanswered',
45
+ 'state', 'database', 'source_tag', 'grant_id', 'door', 'source_basis', 'source_login', 'source_remembered', 'approval_state', 'person_id', 'client_approvals', 'unhandled_drops', 'unhandled_drops_more', 'retired_drops', 'emet_line', 'emet_line_if_unanswered', 'continuity_currency',
46
+ 'handoff_view', 'handoff_view_text', 'handoff_view_conflicts', 'own_handoff', 'stale_open',
46
47
  'tools_in_force', 'instructions_short', 'session_close_protocol', 'operating_discipline', 'charter',
47
48
  'floor', 'floor_precedence', 'floor_reassertion', 'gems_available', 'gems_active',
48
49
  'seeds_due', 'seeds_evaluated_on', 'install_notes_doc_id',
@@ -62,7 +63,17 @@ export const BINDING_KEYS = Object.freeze([
62
63
  /** Page fields that are never payload keys. */
63
64
  export const PAGE_FIELDS = Object.freeze(['startup_page', 'page_notice', 'page_plan']);
64
65
 
65
- export const loadIdOf = (full) => crypto.createHash('sha256').update(JSON.stringify(full), 'utf8').digest('hex').slice(0, 16);
66
+ /** Recomputed on every read. They ride on the payload and stay out of load_id. */
67
+ const LOAD_ID_SKIP = new Set(['handoff_view', 'handoff_view_text', 'handoff_view_conflicts', 'own_handoff', 'stale_open']);
68
+
69
+ export const loadIdOf = (full) => {
70
+ const stable = {};
71
+ for (const key of Object.keys(full || {})) {
72
+ if (LOAD_ID_SKIP.has(key)) continue;
73
+ stable[key] = full[key];
74
+ }
75
+ return crypto.createHash('sha256').update(JSON.stringify(stable), 'utf8').digest('hex').slice(0, 16);
76
+ };
66
77
 
67
78
  function orderedKeys(full) {
68
79
  const keys = PAGE_ORDER.filter((k) => k in full);
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Sub-key session lifetime (handle renewal, grace, and the backstop).
3
+ *
4
+ * A handle lasts 12 hours. The last hour is the renewal window. After
5
+ * expiry, the same length is a grace window. Past that, the session is
6
+ * stranded and the sweep can close it. This module is the clock and the
7
+ * words. The store writes live in src/subkeys.js.
8
+ *
9
+ * A client_kind on the call is not a kind. The kind is the value the owner
10
+ * stored on the key.
11
+ */
12
+
13
+ import { setting } from './env.js';
14
+
15
+ export const HANDLE_TTL_MS = 12 * 60 * 60 * 1000;
16
+
17
+ export const UNWRAPPED_NOTICE =
18
+ 'The previous chat was not wrapped up. Go back to that chat and wrap it up to save it.';
19
+
20
+ export const RENEW_MESSAGE =
21
+ 'Wrap up and call emet_session_open with your sub-key and this session_handle. The server cannot push a new handle to an idle client.';
22
+
23
+ const TERMINAL = new Set(['closed', 'auto_closed', 'revoked']);
24
+
25
+ export function isTerminalState(state) {
26
+ return TERMINAL.has(state);
27
+ }
28
+
29
+ /** 'chat', 'bot', or null when the value is absent or not one of those two. */
30
+ export function clientKindValue(value) {
31
+ if (value === undefined || value === null) return null;
32
+ const text = String(value).trim();
33
+ if (!text) return null;
34
+ if (text === 'chat' || text === 'bot') return text;
35
+ return null;
36
+ }
37
+
38
+ /** The kind stored on the key. A missing value is a bot: the collision rule stays. */
39
+ export function clientKindOf(row) {
40
+ return row && row.client_kind === 'chat' ? 'chat' : 'bot';
41
+ }
42
+
43
+ export function renewalWindowMs() {
44
+ const raw = setting('SUBKEY_RENEWAL_MINUTES');
45
+ const cap = Math.floor(HANDLE_TTL_MS / 60000) - 1;
46
+ if (raw === undefined || raw === null || String(raw).trim() === '') return 60 * 60 * 1000;
47
+ const n = Number(raw);
48
+ if (!Number.isFinite(n) || n < 1) return 60 * 60 * 1000;
49
+ return Math.min(Math.floor(n), cap) * 60 * 1000;
50
+ }
51
+
52
+ export function handleGraceMs() {
53
+ const raw = setting('SUBKEY_HANDLE_GRACE_MINUTES');
54
+ if (raw === undefined || raw === null || String(raw).trim() === '') return 60 * 60 * 1000;
55
+ const n = Number(raw);
56
+ if (!Number.isFinite(n) || n < 0) return 60 * 60 * 1000;
57
+ return Math.floor(n) * 60 * 1000;
58
+ }
59
+
60
+ export function sweepIntervalMs() {
61
+ const raw = setting('SUBKEY_SWEEP_MINUTES');
62
+ if (raw === undefined || raw === null || String(raw).trim() === '') return 15 * 60 * 1000;
63
+ const n = Number(raw);
64
+ if (!Number.isFinite(n) || n < 1) return 15 * 60 * 1000;
65
+ return Math.floor(n) * 60 * 1000;
66
+ }
67
+
68
+ /**
69
+ * Where a handle sits against its expiry.
70
+ * fresh: more than the renewal window remains.
71
+ * window: inside the last stretch, the handle still verifies.
72
+ * grace: expired, and a renewal that presents the key is still open.
73
+ * beyond: the grace window is over.
74
+ */
75
+ export function phaseOf(expiresAt, now, windowMs = renewalWindowMs(), graceMs = handleGraceMs()) {
76
+ const exp = expiresAt ? new Date(expiresAt).getTime() : NaN;
77
+ if (!Number.isFinite(exp)) return 'fresh';
78
+ const t = now instanceof Date ? now.getTime() : new Date(now).getTime();
79
+ if (!Number.isFinite(t)) return 'fresh';
80
+ if (t >= exp + graceMs) return 'beyond';
81
+ if (t >= exp) return 'grace';
82
+ if (t >= exp - windowMs) return 'window';
83
+ return 'fresh';
84
+ }
85
+
86
+ export function renewalRequest(session) {
87
+ return {
88
+ action: 'reinitialize',
89
+ session_id: session && session.session_id || null,
90
+ open_id: session && session.open_id || null,
91
+ expires_at: session && session.expires_at || null,
92
+ message: RENEW_MESSAGE
93
+ };
94
+ }
95
+
96
+ /**
97
+ * The code http-remote puts on a preflight failure.
98
+ * A stranded session is EMET-SESS-014. It is not EMET-AUTH-039.
99
+ */
100
+ export function preflightHttpCode(err) {
101
+ if (!err) return null;
102
+ if (err.subkeyHold) return 'EMET-SESS-014';
103
+ if (err.attributionRefusal) return err.emetCode === 'EMET-AUTH-044' ? 'EMET-AUTH-044' : 'EMET-AUTH-039';
104
+ return null;
105
+ }