@dreamforgestudiollc/emet 0.3.5 → 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 (103) hide show
  1. package/.env.example +29 -0
  2. package/CHANGELOG.md +49 -11
  3. package/CHARTER.md +1 -1
  4. package/CONTRIBUTING.md +21 -0
  5. package/README.md +25 -10
  6. package/RELEASE_NOTES-0.2.6.md +43 -0
  7. package/RELEASE_NOTES-0.3.6.md +29 -0
  8. package/RELEASE_NOTES-0.3.7.md +19 -0
  9. package/SECURITY.md +13 -0
  10. package/docs/BOTS.md +4 -4
  11. package/docs/DEPLOY.md +23 -4
  12. package/docs/ERROR-CODES-SPEC.md +4 -0
  13. package/docs/ERROR-CODES.md +7 -0
  14. package/docs/GUIDED-SETUP.md +1 -1
  15. package/docs/ROADMAP.md +62 -49
  16. package/docs/SETUP.md +11 -1
  17. package/docs/SUBKEYS.md +3 -1
  18. package/docs/continuity-currency-statechart.md +34 -0
  19. package/docs/features/README.md +21 -0
  20. package/docs/features/access.md +28 -0
  21. package/docs/features/documents.md +35 -0
  22. package/docs/features/errors.md +32 -0
  23. package/docs/features/gems.md +31 -0
  24. package/docs/features/memory.md +29 -0
  25. package/docs/features/pages.md +28 -0
  26. package/docs/features/record.md +27 -0
  27. package/docs/features/search.md +27 -0
  28. package/docs/features/startup.md +29 -0
  29. package/docs/features/subkeys.md +30 -0
  30. package/docs/features/transcripts.md +33 -0
  31. package/docs/per-tag-handoff-statechart.md +147 -0
  32. package/docs/subkey-session-statechart.md +57 -0
  33. package/package.json +6 -2
  34. package/server.json +27 -2
  35. package/src/annotations.js +5 -3
  36. package/src/attribution.js +2 -2
  37. package/src/carry-forward-close.js +1 -1
  38. package/src/chooser.js +74 -3
  39. package/src/conformance.js +2 -0
  40. package/src/continuity-currency-statechart.js +139 -0
  41. package/src/continuity-currency.js +869 -0
  42. package/src/database.js +1 -1
  43. package/src/dispatch.js +1 -1
  44. package/src/error-codes.js +7 -0
  45. package/src/gem-check.js +4 -1
  46. package/src/grants.js +28 -5
  47. package/src/host-reach.js +1 -1
  48. package/src/http-remote.js +29 -5
  49. package/src/index.js +3 -2
  50. package/src/invites.js +2 -2
  51. package/src/owl.js +12 -11
  52. package/src/pages.js +15 -0
  53. package/src/per-tag-handoff-statechart.js +264 -0
  54. package/src/per-tag-handoff.js +988 -0
  55. package/src/persons.js +16 -0
  56. package/src/session-graph.js +123 -12
  57. package/src/session.js +56 -12
  58. package/src/setup.js +32 -11
  59. package/src/startup-pages.js +13 -2
  60. package/src/subkey-lifecycle.js +105 -0
  61. package/src/subkey-session-statechart.js +253 -0
  62. package/src/subkeys.js +648 -89
  63. package/src/tools.js +171 -51
  64. package/src/transcript-session.js +2 -2
  65. package/src/version.js +1 -1
  66. package/templates/INDEX.md +1 -0
  67. package/templates/SESSIONDISPOSITION.md +2 -2
  68. package/templates/TAGHANDOFF.md +45 -0
  69. package/verification/continuity-currency/ContinuityCurrency.cfg +12 -0
  70. package/verification/continuity-currency/ContinuityCurrency.tla +239 -0
  71. package/verification/continuity-currency/tlc-output.txt +32 -0
  72. package/verification/continuity-currency/view.mjs +54 -0
  73. package/verification/load-gate/load-gate.mjs +1 -1
  74. package/verification/per-tag-handoff/PerTagHandoff.cfg +10 -0
  75. package/verification/per-tag-handoff/PerTagHandoff.tla +191 -0
  76. package/verification/per-tag-handoff/StampCounter.cfg +10 -0
  77. package/verification/per-tag-handoff/out/report.md +6 -0
  78. package/verification/per-tag-handoff/out-counter/chart.mmd +30 -0
  79. package/verification/per-tag-handoff/out-counter/report.md +15 -0
  80. package/verification/per-tag-handoff/out-counter/tlc.out +130 -0
  81. package/verification/per-tag-handoff/split/PerTagConflict.cfg +6 -0
  82. package/verification/per-tag-handoff/split/PerTagConflict.tla +104 -0
  83. package/verification/per-tag-handoff/split/PerTagTime.cfg +8 -0
  84. package/verification/per-tag-handoff/split/PerTagTime.tla +100 -0
  85. package/verification/per-tag-handoff/split/conflict-chart.mmd +47 -0
  86. package/verification/per-tag-handoff/split/conflict-report.md +8 -0
  87. package/verification/per-tag-handoff/split/conflict-tlc.txt +19 -0
  88. package/verification/per-tag-handoff/split/conflict-view.mjs +34 -0
  89. package/verification/per-tag-handoff/split/time-chart.mmd +44 -0
  90. package/verification/per-tag-handoff/split/time-report.md +8 -0
  91. package/verification/per-tag-handoff/split/time-tlc.txt +19 -0
  92. package/verification/per-tag-handoff/split/time-view.mjs +33 -0
  93. package/verification/per-tag-handoff/tlc-output.txt +19 -0
  94. package/verification/per-tag-handoff/v1-draft/PerTagHandoff.cfg +5 -0
  95. package/verification/per-tag-handoff/v1-draft/PerTagHandoff.tla +94 -0
  96. package/verification/per-tag-handoff/v1-draft/out/chart.mmd +37 -0
  97. package/verification/per-tag-handoff/v1-draft/out/report.md +7 -0
  98. package/verification/per-tag-handoff/v1-draft/out/tlc.out +19 -0
  99. package/verification/per-tag-handoff/v1-draft/view.mjs +20 -0
  100. package/verification/per-tag-handoff/view.mjs +31 -0
  101. package/verification/subkey-session/SubkeySession.cfg +11 -0
  102. package/verification/subkey-session/SubkeySession.tla +254 -0
  103. 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();
@@ -3,7 +3,7 @@
3
3
  * board board 120, design the staging note; the practice is
4
4
  * docs/GUARDRAILS-AND-MONORAILS.md).
5
5
  *
6
- * Alex: "guardrails give a field of movement and execution to allow an AI to do
6
+ * the owner: "guardrails give a field of movement and execution to allow an AI to do
7
7
  * processes where rails guide the AI through a process flow without it
8
8
  * processing" (semantic ref 297). The floor, the character and the served
9
9
  * instructions are the guardrails. This file is the monorail - the car cannot
@@ -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
 
@@ -72,14 +73,14 @@ export const BOARD_DOC = 'STATE.md';
72
73
 
73
74
  /**
74
75
  * Per-bot close records (C1, 2026-10-01; review note "C1: per-bot close
75
- * records", Alex's decisions 1-7). The rule, stated once: a session written
76
+ * records", the owner's decisions 1-7). The rule, stated once: a session written
76
77
  * under a bot's source tag closes against that bot's own records
77
78
  * (bots/<tag>/HANDOFF.md); only that tag's own revisions in the session window
78
79
  * count; a bot tag never writes or cites the main HANDOFF.md or STATE.md.
79
80
  *
80
81
  * A tag T is a BOT TAG when bots/T/HANDOFF.md is listed in EMET_RECORD_DOCS,
81
82
  * the list that already marks ids as supersede-only records (tools.js
82
- * recordDocIds). No new setting: Alex adds one id per bot, and removing it
83
+ * recordDocIds). No new setting: the owner adds one id per bot, and removing it
83
84
  * puts that tag back on the host rules. Bot records are named by the source
84
85
  * tag itself (decision 1), so no tag-to-name mapping exists. These are pure
85
86
  * reads of settings - no database - so the graph can key its bot-handoff gate
@@ -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
  }
@@ -361,7 +441,7 @@ export async function isSessionClosed(base, dbManager) {
361
441
  }
362
442
 
363
443
  /**
364
- * The closing exchange (2026-10-01, Alex's decision). In the closing turn the
444
+ * The closing exchange (2026-10-01, the owner's decision). In the closing turn the
365
445
  * assistant writes the handoff, gets `complete` from emet_session_close, and
366
446
  * only then replies - so the append of that last exchange always arrives
367
447
  * after the close. A closed session therefore takes exactly ONE more append:
@@ -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;
@@ -786,7 +895,7 @@ export async function graphBefore(tool, args, dbManager, now = new Date()) {
786
895
  }
787
896
 
788
897
  // ---------------------------------------------------------------------------
789
- // Lab results (2026-09-29, Alex: "a 'lab results' location for storing the
898
+ // Lab results (2026-09-29, the owner: "a 'lab results' location for storing the
790
899
  // results in real time with time stamps so we can have a resource to look at
791
900
  // after the probationary period"). Every check the monorail makes - ok,
792
901
  // refuse, unknown (would_refuse in rows from before enforce-only) - is one timestamped row in
@@ -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';
@@ -355,7 +356,7 @@ export async function corroborateCoverage(db, baseId) {
355
356
  * The store check above answers "do the artifacts exist". It could not answer
356
357
  * "did the host actually do each step", and a host that skipped a step, or
357
358
  * never read the transcript back, could still walk away with `complete`
358
- * because the store happened to look fine. Alex's requirement (procedural ref 388,
359
+ * because the store happened to look fine. the owner's requirement (procedural ref 388,
359
360
  * 389, 391): the wrap steps HAVE TO BE FOLLOWED, whichever model is hosting,
360
361
  * and a skipped step blocks the close the same way a skipped opening is caught
361
362
  * at initialize.
@@ -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}`);
@@ -975,17 +1006,20 @@ export async function sessionClose(options = {}) {
975
1006
  }
976
1007
 
977
1008
  // Store-level gaps make the session incomplete. Receipt problems, and a
978
- // transcript nothing independently corroborates, BLOCK it (Alex 2026-09-26,
1009
+ // transcript nothing independently corroborates, BLOCK it (the owner 2026-09-26,
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';
@@ -250,7 +252,7 @@ export function registeredSourceTags() {
250
252
  return env.length ? [...new Set([...env, ...approvedTags()])] : env;
251
253
  }
252
254
 
253
- /** Attribution v2: the caller's real tag, not the server-wide default (Alex 2026-10-12 (c)).
255
+ /** Attribution v2: the caller's real tag, not the server-wide default (the owner 2026-10-12 (c)).
254
256
  * R2 adds the credential: grant_id (the token family) and door. Stdio has no grant. */
255
257
  export function callerAttribution() {
256
258
  const d = declaredAttribution();
@@ -335,7 +337,7 @@ export function summarizeSeed(doc_id, text, today = new Date().toISOString().sli
335
337
  }
336
338
 
337
339
  /**
338
- * One line per seed for the initialize payload (Alex, 2026-09-27, code audit
340
+ * One line per seed for the initialize payload (the owner, 2026-09-27, code audit
339
341
  * 2.3: "seeds can be one line since follow-up inquiry by the user will expand
340
342
  * it"). Before this every trigger's full test text was served - 13K characters
341
343
  * for 21 seeds with none due. The line keeps what a startup scan needs: the
@@ -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 ' +
@@ -876,7 +881,7 @@ export async function initialize(options = {}, hooks = {}) {
876
881
  if (late && late.length && typeof hooks.onLate === 'function') { try { hooks.onLate(late); } catch { /* recording never fails a page */ } }
877
882
  return late;
878
883
  };
879
- // Paged startup (2026-10-03, Alex approved paging; src/startup-pages.js).
884
+ // Paged startup (2026-10-03, the owner approved paging; src/startup-pages.js).
880
885
  // The full payload is built exactly as before; only its delivery changes.
881
886
  const raw = options.page;
882
887
  const wantAll = typeof raw === 'string' && raw.trim().toLowerCase() === 'all';
@@ -1130,9 +1135,9 @@ async function buildStartup(options = {}) {
1130
1135
  lessonsPending = { assessed: false, error: e && e.message ? e.message : String(e), pending: [] };
1131
1136
  }
1132
1137
 
1133
- // Stage 1 of the ref 358 startup amendment (2026-10-02; Alex's decision 2,
1138
+ // Stage 1 of the ref 358 startup amendment (2026-10-02; the owner's decision 2,
1134
1139
  // procedural ref 407: "emet_initialize is the startup doorway every bot
1135
- // calls; only first-time setup stays Alex's"). Initialize no longer creates
1140
+ // calls; only first-time setup stays the owner's"). Initialize no longer creates
1136
1141
  // the owner person: that write moved to setupComplete, the owner's
1137
1142
  // first-time setup, so initialize is read-only in every branch and matches
1138
1143
  // its annotation (annotations.js, READ) for every caller. A store with no
@@ -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) })),
@@ -1168,7 +1189,7 @@ async function buildStartup(options = {}) {
1168
1189
  // and connection; the user's name does the animating.
1169
1190
  emet_line: EMET_LINE,
1170
1191
  emet_line_if_unanswered: EMET_LINE_UNANSWERED,
1171
- // 2026-09-26 Alex: prune may not drop the close-order tool. These two
1192
+ // 2026-09-26 the owner: prune may not drop the close-order tool. These two
1172
1193
  // fields MUST precede identity/character/user so a 20k host truncate
1173
1194
  // still receives them. The charter text may stay pointed; the steps may not.
1174
1195
  tools_in_force: {
@@ -1181,7 +1202,7 @@ async function buildStartup(options = {}) {
1181
1202
  'source tag on every write'
1182
1203
  ],
1183
1204
  on_wrap: ['working documents', 'episodic session record', 'board', 'verbatim transcript', 'HANDOFF last one write'],
1184
- // 2026-09-26 Alex (procedural ref 391): close is blocked without receipts.
1205
+ // 2026-09-26 the owner (procedural ref 391): close is blocked without receipts.
1185
1206
  confirm: 'emet_session_close with receipts for all four items and the handoff; say its speak lines in order; saved only when state is complete'
1186
1207
  },
1187
1208
  // Code audit 2026-09-27 (2.1): the short instructions ride up front with
@@ -1208,7 +1229,7 @@ async function buildStartup(options = {}) {
1208
1229
  ...retirementFields(installNotes)
1209
1230
  } : null,
1210
1231
  install_notes_doc_id: installDoc(),
1211
- // One line each since 2026-09-27 (Alex); the full seed is one read_doc away.
1232
+ // One line each since 2026-09-27 (the owner); the full seed is one read_doc away.
1212
1233
  seeds: seeds.map((s) => seedLine(s)),
1213
1234
  seeds_due: seeds.filter((s) => s.due && s.retired !== true).map((s) => s.doc_id),
1214
1235
  seeds_evaluated_on: today,
@@ -1354,8 +1375,8 @@ export async function setupComplete(answers = {}, logger = null, options = {}) {
1354
1375
  // guards (2026-10-02, Reviewer's stage 1 admission, conditions S1-S2):
1355
1376
  // - refused under a configured bot tag. The tag is self-declared and
1356
1377
  // emet_initialize takes no source until stage 2, so this is inert until a
1357
- // caller declares a bot tag that Alex has configured (stage 3);
1358
- // - refused on a store that is already set up unless `reissue: true` (Alex's
1378
+ // caller declares a bot tag that the owner has configured (stage 3);
1379
+ // - refused on a store that is already set up unless `reissue: true` (the owner's
1359
1380
  // answer 5): a re-run replaces the user's identity documents with new
1360
1381
  // versions, so it needs the owner's explicit word. Nothing is written
1361
1382
  // when either refusal fires.
@@ -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);