@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/tools.js CHANGED
@@ -19,6 +19,10 @@ import { resolveModulePath } from './module-path.js';
19
19
  import { replacedByOf } from './setup.js';
20
20
  import { currentActor, rawActor, writerStamp, boundSourceTag, declaredAttribution, LOCAL_SUBJECT } from './persons.js';
21
21
  import { guardClaimedTag } from './claimed-tag.js';
22
+ import {
23
+ tagHandoffMode, guardTagHandoff, isTagHandoffDoc, boardWritePlan, hubTag, credentialForWrite, authorizeHandoffWrite, attachHandoffView, requireHubTag
24
+ } from './per-tag-handoff.js';
25
+ import { continuityCurrencyEnabled, loadContinuityCurrency, continuityCurrencyUnreadable } from './continuity-currency.js';
22
26
  import { approvedTags, APPROVALS_DOC } from './attribution.js';
23
27
  import { refuseBoundHostDoor, boundHostActor, boundHostCredentialOverrides, boundHostClaimOnSharedLogin, isBoundHostTag, isLegacyBoundHostSpelling, CLAIM_TAG } from './bound-door.js';
24
28
  import { sealAttestation, frozenAttestation } from './rune-dispatch.js';
@@ -2151,7 +2155,13 @@ export async function sessionOpen({ slug, load_id } = {}, logger = null, dbManag
2151
2155
  : 'Nothing was merged into another session.')
2152
2156
  : null;
2153
2157
  logger?.info?.('transcript session open', { session_id, ...(suffixed ? { requested } : {}) });
2154
- const session_handle = await subkeyHandleForOpen(rawActor(), base, now);
2158
+ const opener = rawActor();
2159
+ const session_handle = await subkeyHandleForOpen(opener, base, now);
2160
+ let subkeyNotice = null;
2161
+ if (session_handle && setting('SUBKEYS') === '1') {
2162
+ const { takeOpenNotice } = await import('./subkeys.js');
2163
+ subkeyNotice = takeOpenNotice(opener);
2164
+ }
2155
2165
  // Startup page completion (2026-10-03). Through dispatch, an open with no
2156
2166
  // load_id or with pages missing is refused before this runs (the
2157
2167
  // startup_pages gate); a direct call is told what was checked.
@@ -2173,10 +2183,12 @@ export async function sessionOpen({ slug, load_id } = {}, logger = null, dbManag
2173
2183
  drops_seen = null;
2174
2184
  drops_unverified = true;
2175
2185
  }
2176
- return {
2186
+ const opened = {
2177
2187
  session_id,
2178
2188
  base,
2179
2189
  ...(session_handle ? { session_handle } : {}),
2190
+ ...(subkeyNotice ? { session_renewal: subkeyNotice } : {}),
2191
+ ...(subkeyNotice && subkeyNotice.wrap_up_notice ? { wrap_up_notice: subkeyNotice.wrap_up_notice } : {}),
2180
2192
  drops_seen,
2181
2193
  ...(drops_unverified ? { drops_unverified: true } : {}),
2182
2194
  next_exchange_index: 1,
@@ -2188,10 +2200,25 @@ export async function sessionOpen({ slug, load_id } = {}, logger = null, dbManag
2188
2200
  } : {}),
2189
2201
  ...(pages ? { startup_pages: pages } : {}),
2190
2202
  instructions:
2203
+ (subkeyNotice && subkeyNotice.wrap_up_notice ? `Tell the user: ${subkeyNotice.wrap_up_notice} ` : '') +
2191
2204
  (suffixed ? `Tell the user, in one line: ${notice} ` : '') +
2192
2205
  (pages && pages.notice ? `${pages.notice} ` : '') +
2193
2206
  'After EVERY reply, call emet_transcript_append with this session_id, the user message, and your reply. One exchange per call. Do not wait until the session ends. Do not reconstruct earlier turns.'
2194
2207
  };
2208
+ if (continuityCurrencyEnabled() || tagHandoffMode() !== 'off') {
2209
+ let client;
2210
+ try {
2211
+ client = await connectMongo(MONGODB_URI, { serverSelectionTimeoutMS: 8000, maxPoolSize: 5 });
2212
+ const db = client.db(MONGODB_DB);
2213
+ if (continuityCurrencyEnabled()) opened.continuity_currency = await loadContinuityCurrency(db);
2214
+ if (tagHandoffMode() !== 'off') await attachHandoffView(db, opened, credentialForWrite(null).tag);
2215
+ } catch {
2216
+ if (continuityCurrencyEnabled()) opened.continuity_currency = continuityCurrencyUnreadable();
2217
+ } finally {
2218
+ if (client) await client.close();
2219
+ }
2220
+ }
2221
+ return opened;
2195
2222
  }
2196
2223
 
2197
2224
  /** Which pages of a startup load were never served (the session graph's startup_pages gate reads it here). */
@@ -2785,7 +2812,7 @@ function stateDoc() {
2785
2812
  return setting('STATE_DOC', 'STATE.md');
2786
2813
  }
2787
2814
  function _refuseRecordAmendment(doc_id, tool) {
2788
- if (isRecordDoc(doc_id)) {
2815
+ if (isRecordDoc(doc_id) || (tagHandoffMode() !== 'off' && isTagHandoffDoc(doc_id))) {
2789
2816
  throw new ValidationError(
2790
2817
  `${tool}: ${doc_id} is a record. Records are superseded, not amended (ISO 9001 7.5.3 / 13485 4.2.5). ` +
2791
2818
  `Issue a new revision with write_doc - the whole record, with \`supersedes\` set to the version now in force. ` +
@@ -2944,7 +2971,12 @@ function mayCleanUpLookalike(tag) {
2944
2971
  }
2945
2972
 
2946
2973
  export function refuseBotMainRecord(doc_id, updated_by, tool, options = {}) {
2947
- for (const t of rightsTags(updated_by)) refuseBotMainRecordOne(doc_id, t, tool, options);
2974
+ let warning = null;
2975
+ for (const t of rightsTags(updated_by)) {
2976
+ const result = refuseBotMainRecordOne(doc_id, t, tool, options);
2977
+ if (result && result.warning) warning = result.warning;
2978
+ }
2979
+ return warning ? { warning } : undefined;
2948
2980
  }
2949
2981
  function refuseBotMainRecordOne(doc_id, updated_by, tool, options = {}) {
2950
2982
  const tag = updated_by || setting('SOURCE_TAG') || null;
@@ -2978,7 +3010,9 @@ function refuseBotMainRecordOne(doc_id, updated_by, tool, options = {}) {
2978
3010
  // set, a non-bot write under bots/ is refused unless its tag is registered; a missing source counts as
2979
3011
  // unregistered. Without this, a misspelled or unregistered tag is not a bot tag, so the cross-bot guard
2980
3012
  // above never fires and it can write any bot's records or the roster. A listed bot is already fenced to
2981
- // its own bots/<tag>/ above; registered hosts (the hub) still write anywhere under bots/.
3013
+ // its own bots/<tag>/ above. With EMET_TAG_HANDOFFS off, a registered host may still write under bots/.
3014
+ // With the flag at warn, a write inside another tag's folder is kept and the warning is on the receipt.
3015
+ // With the flag at enforce, that write is refused (EMET-DOC-084), and the hub is refused too.
2982
3016
  const registry = sourceRegistry();
2983
3017
  if (!bot && registry.length && typeof doc_id === 'string' && doc_id.startsWith('bots/') && !(tag && registry.includes(tag))) {
2984
3018
  throw new ValidationError(
@@ -2986,8 +3020,17 @@ function refuseBotMainRecordOne(doc_id, updated_by, tool, options = {}) {
2986
3020
  `only a registered host or the bot itself writes under bots/. Nothing was written.`
2987
3021
  , { code: 'EMET-DOC-012' });
2988
3022
  }
2989
- if (!mainRecordIds().includes(doc_id)) return;
2990
- if (bot) {
3023
+ let handoffWarning = null;
3024
+ const noteHandoff = (result) => {
3025
+ if (result && result.warning) handoffWarning = result.warning;
3026
+ };
3027
+ if (!mainRecordIds().includes(doc_id)) {
3028
+ if (tagHandoffMode() !== 'off') noteHandoff(guardTagHandoff(doc_id, updated_by, tool));
3029
+ return handoffWarning ? { warning: handoffWarning } : undefined;
3030
+ }
3031
+ if (bot && doc_id === stateDoc() && tagHandoffMode() !== 'off') {
3032
+ // A write tag patches the board rows it opened. The hub handoff stays refused below.
3033
+ } else if (bot) {
2991
3034
  throw new ValidationError(
2992
3035
  `${tool}: ${doc_id} is a main record and ${tag} is a bot tag - a bot session closes against ` +
2993
3036
  `${botRecordDir(tag)} records; the main handoff and board are the hub's. Write the bot's own ` +
@@ -2995,13 +3038,16 @@ function refuseBotMainRecordOne(doc_id, updated_by, tool, options = {}) {
2995
3038
  , { code: 'EMET-DOC-013' });
2996
3039
  }
2997
3040
  if (options && options.serverProvision === true) return;
2998
- if (registry.length && !(tag && registry.includes(tag))) {
3041
+ const botOwnRows = bot && doc_id === stateDoc() && tagHandoffMode() !== 'off';
3042
+ if (registry.length && !(tag && registry.includes(tag)) && !botOwnRows) {
2999
3043
  throw new ValidationError(
3000
3044
  `${tool}: ${doc_id} is a main record and ` +
3001
3045
  `${tag ? `"${tag}" is not a registered source tag` : 'this write names no source tag'} - only a registered ` +
3002
3046
  `host writes the main handoff and board. Pass the host's registered \`source\` (EMET_SOURCE_TAGS). Nothing was written.`
3003
3047
  , { code: 'EMET-DOC-014' });
3004
3048
  }
3049
+ if (tagHandoffMode() !== 'off') noteHandoff(guardTagHandoff(doc_id, updated_by, tool));
3050
+ return handoffWarning ? { warning: handoffWarning } : undefined;
3005
3051
  }
3006
3052
 
3007
3053
  /**
@@ -3064,10 +3110,12 @@ export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint
3064
3110
  if (casOn && ((prev ? prev.version : null) ?? null) !== (options.expectedVersion ?? null)) throw casConflict();
3065
3111
  // A record in force is superseded only by a revision that names it.
3066
3112
  // Checked before anything is archived, so a refused write leaves no trace.
3067
- if (prev && isRecordDoc(doc_id) && options && options.restore_of && (options.supersedes === undefined || options.supersedes === null)) {
3113
+ const tagHandoffRecord = tagHandoffMode() !== 'off' && isTagHandoffDoc(doc_id);
3114
+ const recordLike = isRecordDoc(doc_id) || tagHandoffRecord;
3115
+ if (prev && recordLike && options && options.restore_of && (options.supersedes === undefined || options.supersedes === null)) {
3068
3116
  options = { ...options, supersedes: prev.version };
3069
3117
  }
3070
- if (prev && isRecordDoc(doc_id)) {
3118
+ if (prev && recordLike) {
3071
3119
  const named = options && options.supersedes;
3072
3120
  if (named === undefined || named === null) {
3073
3121
  throw new ValidationError(
@@ -3114,7 +3162,7 @@ export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint
3114
3162
  }
3115
3163
  throw new ValidationError('The board is provisioned by the server at setup (emet_setup_complete). Nothing was written.', { code: 'EMET-MEM-023' });
3116
3164
  }
3117
- if (prev && isWorkingDoc(doc_id) && !internal) {
3165
+ if (prev && isWorkingDoc(doc_id) && !tagHandoffRecord && !internal) {
3118
3166
  throw new ValidationError(
3119
3167
  `write_doc: ${doc_id} exists, so it is edited, not rewritten. Use patch_doc with \`reason\`. Nothing was written.`
3120
3168
  , { code: 'EMET-DOC-022' });
@@ -3169,6 +3217,52 @@ export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint
3169
3217
  }
3170
3218
  const sizeSamples = recentSamples.slice();
3171
3219
  if (prev) sizeSamples.push({ size: String(prev.content || '').length, at: prev.updated_at || new Date() });
3220
+ let tagHandoffWarnings = [];
3221
+ let rowOpeners = null;
3222
+ let conflictSettled = null;
3223
+ if (tagHandoffMode() !== 'off') {
3224
+ requireHubTag();
3225
+ let personIds = [];
3226
+ let ownerPerson = (currentActor() && currentActor().personId) || 'owner';
3227
+ try {
3228
+ const people = await client.db(MONGODB_DB).collection('persons').find({}, { projection: { person_id: 1, role: 1 } }).toArray();
3229
+ personIds = (people || []).map((row) => row && row.person_id).filter(Boolean);
3230
+ const owner = (people || []).find((row) => row && row.role === 'owner');
3231
+ if (owner && owner.person_id) ownerPerson = owner.person_id;
3232
+ } catch { /* a store without the persons collection keeps the actor's person */ }
3233
+ const credential = credentialForWrite(updated_by);
3234
+ const registry = sourceRegistry();
3235
+ const auth = authorizeHandoffWrite({
3236
+ docId: doc_id,
3237
+ tool: options && options.restore_of ? 'restore_doc' : (options && options.edited ? 'patch_doc' : 'write_doc'),
3238
+ mode: tagHandoffMode(),
3239
+ credentialTag: credential.tag,
3240
+ claimedOnly: credential.claimedOnly,
3241
+ isBot: !!(credential.tag && isBotTag(credential.tag)),
3242
+ isHub: !!(hubTag() && credential.tag === hubTag()),
3243
+ registered: registry.length === 0 || (!!credential.tag && registry.includes(credential.tag)),
3244
+ ownerPerson,
3245
+ personIds
3246
+ });
3247
+ if (auth && auth.warning) tagHandoffWarnings.push(auth.warning);
3248
+ if (doc_id === stateDoc() && (options && (options.edited || options.provision || options.restore_of))) {
3249
+ const plan = await boardWritePlan(col, {
3250
+ previous: prev,
3251
+ next: content,
3252
+ writer: credential.tag,
3253
+ hub: hubTag(),
3254
+ mode: tagHandoffMode(),
3255
+ resolve: options && options.resolve_conflict,
3256
+ at: new Date().toISOString(),
3257
+ person: ownerPerson,
3258
+ docId: doc_id,
3259
+ db: client.db(MONGODB_DB)
3260
+ });
3261
+ rowOpeners = plan.openers;
3262
+ conflictSettled = plan.conflict_settled;
3263
+ tagHandoffWarnings = [...tagHandoffWarnings, ...(plan.warnings || [])];
3264
+ }
3265
+ }
3172
3266
  const docDecision = resolvedSourceTag(updated_by);
3173
3267
  const stampedUpdatedBy = stampedSource(docDecision, updated_by || (isDropDoc(doc_id) ? 'visitor' : (setting('SOURCE_TAG') || null)));
3174
3268
  const docClaim = guardClaimedTag({
@@ -3222,6 +3316,8 @@ export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint
3222
3316
  size_session_id: base,
3223
3317
  size_baselines: baselines,
3224
3318
  size_samples: typeof sizeSamples !== 'undefined' ? sizeSamples : (prev && prev.size_samples) || [],
3319
+ ...(rowOpeners ? { row_openers: rowOpeners } : {}),
3320
+ ...(conflictSettled ? { conflict_settled: conflictSettled } : {}),
3225
3321
  drop_bucket: (options && options.drop_bucket) || (prev && prev.drop_bucket) || null,
3226
3322
  path_hint: path_hint || (prev && prev.path_hint) || null,
3227
3323
  // Writing a retired document brings it back into the working view.
@@ -3263,12 +3359,16 @@ export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint
3263
3359
  // aleph: the write is not done because the call returned.
3264
3360
  const check = await col.findOne({ doc_id });
3265
3361
  verifyDocument(check, { doc_id, sha256, version });
3362
+ if (tagHandoffWarnings.length) {
3363
+ try { logger?.warn?.(tagHandoffWarnings.join(' ')); } catch { /* a failing logger never fails the write */ }
3364
+ }
3266
3365
  return { doc_id, sha256, version, size: content.length, updated_at: now, verified: true,
3267
3366
  signed: signatureIntegrityOf(check, signingKey),
3268
3367
  signature_stored: typeof check?.signature === 'string' && check.signature.length > 0,
3269
3368
  redacted: redaction.hits, conformance,
3270
3369
  grant_id: docStamp.grant_id,
3271
- ...(docClaim.warning ? { claimed_tag_warning: docClaim.warning } : {}) };
3370
+ ...(docClaim.warning ? { claimed_tag_warning: docClaim.warning } : {}),
3371
+ ...(tagHandoffWarnings.length ? { warnings: tagHandoffWarnings } : {}) };
3272
3372
  } finally { await client.close(); }
3273
3373
  } catch (error) {
3274
3374
  if (error && error.versionConflict) throw error;
@@ -3357,10 +3457,13 @@ export async function retireDoc(doc_id, reason = null, retired_by = null, logger
3357
3457
  try { await assertAreaOwner(opened.client.db(MONGODB_DB), 'retire_doc'); }
3358
3458
  finally { await opened.client.close(); }
3359
3459
  }
3360
- refuseBotMainRecord(doc_id, retired_by, 'retire_doc', { cleanup: true });
3460
+ const gap = refuseBotMainRecord(doc_id, retired_by, 'retire_doc', { cleanup: true });
3461
+ const gapWarnings = gap && gap.warning ? [gap.warning] : [];
3462
+ if (gapWarnings.length) logger?.warn?.(gapWarnings.join(' '));
3361
3463
  refuseBotRetireRename(retired_by, 'retire_doc');
3362
3464
  if (doc_id === stateDoc()) throw new ValidationError('retire_doc: the board is never retired. Edit it with patch_doc and a reason. Nothing was changed.', { code: 'EMET-DOC-027' });
3363
- if (!isDropDoc(doc_id) && !(options && options.fromRename)) throw new ValidationError(`retire_doc: ${doc_id} is not a drop. Working documents are edited, not retired. Nothing was changed.`, { code: 'EMET-DOC-028' });
3465
+ const hubCleanup = tagHandoffMode() !== 'off' && !!hubTag() && retired_by === hubTag() && doc_id === `HANDOFF/${hubTag()}.md`;
3466
+ if (!isDropDoc(doc_id) && !(options && options.fromRename) && !hubCleanup) throw new ValidationError(`retire_doc: ${doc_id} is not a drop. Working documents are edited, not retired. Nothing was changed.`, { code: 'EMET-DOC-028' });
3364
3467
  if (typeof reason !== 'string' || reason.trim().length < 10) throw new ValidationError('retire_doc needs reason (at least 10 characters), naming where the drop went. Nothing was changed.', { code: 'EMET-DOC-029' });
3365
3468
 
3366
3469
  const { client, col } = await _docsClient();
@@ -3370,7 +3473,8 @@ export async function retireDoc(doc_id, reason = null, retired_by = null, logger
3370
3473
  if (doc.retired) {
3371
3474
  return { doc_id, retired: true, already_retired: true, verified: true,
3372
3475
  retired_at: doc.retired_at, retired_reason: doc.retired_reason || null,
3373
- version: doc.version, sha256: doc.sha256 };
3476
+ version: doc.version, sha256: doc.sha256,
3477
+ ...(gapWarnings.length ? { warnings: gapWarnings } : {}) };
3374
3478
  }
3375
3479
 
3376
3480
  const now = new Date();
@@ -3426,6 +3530,7 @@ export async function retireDoc(doc_id, reason = null, retired_by = null, logger
3426
3530
  return { doc_id, retired: true, verified: true, retired_at: now, conformance,
3427
3531
  retired_reason: reason || null, version: check.version,
3428
3532
  sha256: check.sha256, content_unchanged: true,
3533
+ ...(gapWarnings.length ? { warnings: gapWarnings } : {}),
3429
3534
  grant_id: retireStamp.grant_id,
3430
3535
  ...(retireClaim.warning ? { claimed_tag_warning: retireClaim.warning } : {}),
3431
3536
  note: 'Content retained at this id. list_docs keeps it after the current documents, marked with retired_at and, when a rename replaced it, what replaced it. read_doc still returns it. Nothing was deleted.' };
@@ -3447,8 +3552,8 @@ export async function renameDoc(old_id, new_id, updated_by = null, logger = null
3447
3552
  try { await assertAreaOwner(opened.client.db(MONGODB_DB), 'rename_doc'); }
3448
3553
  finally { await opened.client.close(); }
3449
3554
  }
3450
- refuseBotMainRecord(old_id, updated_by, 'rename_doc', { cleanup: true });
3451
- refuseBotMainRecord(new_id, updated_by, 'rename_doc');
3555
+ const sourceGap = refuseBotMainRecord(old_id, updated_by, 'rename_doc', { cleanup: true });
3556
+ const destGap = refuseBotMainRecord(new_id, updated_by, 'rename_doc');
3452
3557
  refuseBotRetireRename(updated_by, 'rename_doc');
3453
3558
  if (typeof reason !== 'string' || reason.trim().length < 10) throw new ValidationError('rename_doc needs reason (at least 10 characters). Nothing was changed.', { code: 'EMET-DOC-033' });
3454
3559
  if (old_id === stateDoc() || new_id === stateDoc()) throw new ValidationError('rename_doc: the board is never renamed. Nothing was changed.', { code: 'EMET-DOC-034' });
@@ -3482,10 +3587,13 @@ export async function renameDoc(old_id, new_id, updated_by = null, logger = null
3482
3587
  // asks for. The old id keeps its content and stays readable at its own id.
3483
3588
  const retired = await retireDoc(old_id, `Reissued as ${new_id}`, updated_by, logger, { fromRename: true });
3484
3589
 
3590
+ const warnings = [sourceGap && sourceGap.warning, destGap && destGap.warning, ...(written.warnings || []), ...(retired.warnings || [])].filter(Boolean);
3591
+ if (warnings.length) logger?.warn?.(warnings.join(' '));
3485
3592
  return {
3486
3593
  from: old_id, to: new_id, verified: written.verified === true && retired.verified === true,
3487
3594
  conformance: written.conformance || null,
3488
3595
  sha256: written.sha256, version: written.version, size: written.size,
3596
+ ...(warnings.length ? { warnings } : {}),
3489
3597
  redacted: written.redacted,
3490
3598
  old_id_retired: true, old_id_retired_at: retired.retired_at,
3491
3599
  old_content_retained: true,
@@ -3526,7 +3634,7 @@ export async function restoreDoc(doc_id, version, updated_by = null, logger = nu
3526
3634
  if (typeof reason !== 'string' || reason.trim().length < 10) throw new ValidationError('restore_doc needs reason (at least 10 characters). Nothing was written.', { code: 'EMET-DOC-037' });
3527
3635
  if (!updated_by) throw new ValidationError('restore_doc needs a source. Nothing was written.', { code: 'EMET-DOC-038' });
3528
3636
  if (isDropDoc(doc_id)) throw new ValidationError('restore_doc: a drop is never restored. Nothing was written.', { code: 'EMET-DOC-039' });
3529
- if (isRecordDoc(doc_id)) throw new ValidationError('restore_doc: a record is not restored. Records are superseded via revise_memory, not restored. Nothing was written.', { code: 'EMET-DOC-040' });
3637
+ if (isRecordDoc(doc_id) || (tagHandoffMode() !== 'off' && isTagHandoffDoc(doc_id))) throw new ValidationError('restore_doc: a record is not restored. Records are superseded via revise_memory, not restored. Nothing was written.', { code: 'EMET-DOC-040' });
3530
3638
  if (isGovernedByShippedCopy(doc_id)) throw new ValidationError('restore_doc: a shipped copy is not restored. Nothing was written.', { code: 'EMET-DOC-041' });
3531
3639
  const allowed = (setting('RESTORE_TAGS') || setting('SOURCE_TAG') || '').split(',').map((s) => s.trim()).filter(Boolean);
3532
3640
  if (!allowed.includes(updated_by)) throw new ValidationError(`restore_doc: ${updated_by} is not in EMET_RESTORE_TAGS. Nothing was written.`, { code: 'EMET-DOC-042' });
@@ -3619,7 +3727,9 @@ export async function acceptNonconformance(doc_id, reason, accepted_by = null, l
3619
3727
  try { await assertAreaOwner(opened.client.db(MONGODB_DB), 'accept_nonconformance'); }
3620
3728
  finally { await opened.client.close(); }
3621
3729
  }
3622
- refuseBotMainRecord(doc_id, accepted_by, 'accept_nonconformance');
3730
+ const gap = refuseBotMainRecord(doc_id, accepted_by, 'accept_nonconformance');
3731
+ const gapWarnings = gap && gap.warning ? [gap.warning] : [];
3732
+ if (gapWarnings.length) logger?.warn?.(gapWarnings.join(' '));
3623
3733
  if (!doc_id || typeof doc_id !== 'string') throw new ValidationError('doc_id must be a non-empty string', { code: 'EMET-DOC-001' });
3624
3734
  if (typeof reason !== 'string' || reason.trim().length < 10) {
3625
3735
  throw new ValidationError(
@@ -3665,6 +3775,7 @@ export async function acceptNonconformance(doc_id, reason, accepted_by = null, l
3665
3775
  return {
3666
3776
  doc_id, verified: true, version: doc.version, covers_version: doc.version,
3667
3777
  accepted, failures_accepted: current.failures || [],
3778
+ ...(gapWarnings.length ? { warnings: gapWarnings } : {}),
3668
3779
  grant_id: stamp.grant_id,
3669
3780
  ...(acceptClaim.warning ? { claimed_tag_warning: acceptClaim.warning } : {}),
3670
3781
  note: 'The marker is retained with this acceptance beside it. It covers this revision only - the next write is validated fresh, and accepted markers stay counted at session start, separately from open ones.'
@@ -3754,7 +3865,10 @@ export async function patchDoc(doc_id, old_str, new_str, updated_by = null, expe
3754
3865
  throw new ValidationError(`patch_doc: the board edit is nonconforming. ${(checked.failures || []).join('; ')} Nothing was written.`, { code: 'EMET-MEM-029' });
3755
3866
  }
3756
3867
  }
3757
- const res = await writeDoc(doc_id, next, updated_by, null, logger, { edited: true, reason, origin: options.origin || null, session_id: options.session_id || null });
3868
+ const res = await writeDoc(doc_id, next, updated_by, null, logger, {
3869
+ edited: true, reason, origin: options.origin || null, session_id: options.session_id || null,
3870
+ resolve_conflict: options && options.resolve_conflict
3871
+ });
3758
3872
  return { ...res, previous_version: cur.version, replaced: edits.length,
3759
3873
  size_delta: next.length - cur.content.length };
3760
3874
  } catch (error) {
@@ -4035,7 +4149,7 @@ export async function memberAccessCreate(dbManager, { display_name, days, source
4035
4149
  const TOOL_DEFINITIONS = [
4036
4150
  {
4037
4151
  name: "emet_initialize",
4038
- description: "START HERE. Call this FIRST in every session, before answering anything that might have prior context, and always when the user opens with 'initialize', 'start', 'begin', 'hello' or similar. It is the only setup step a user should ever have to know about. A large startup comes in pages: read `page_notice` first and call again with the page it names until the last page, before replying. If this memory store is new it returns a short interview to run conversationally; if it is established it returns who you are, how you speak (`character`, when the store keeps one - authoritative on voice for the whole session), who you are serving, and where things were left. The user never needs to know which case applied.",
4152
+ description: "START HERE. Call this FIRST in every session, before answering anything that might have prior context, and always when the user opens with 'initialize', 'start', 'begin', 'hello' or similar. It is the only setup step a user should ever have to know about. A large startup comes in pages: read `page_notice` first and call again with the page it names until the last page, before replying. If this memory store is new it returns a short interview to run conversationally; if it is established it returns who you are, how you speak (`character`, when the store keeps one - authoritative on voice for the whole session), who you are serving, and where things were left. The user never needs to know which case applied. When EMET_TAG_HANDOFFS is warn or enforce, the startup also carries handoff_view, a stamp computed on read and not stored. A write tag also receives its own handoff section and any stale-open mark. A read-only tag receives the view only. Off, the default, adds none of that.",
4039
4153
  inputSchema: {
4040
4154
  type: "object",
4041
4155
  properties: {
@@ -4209,7 +4323,7 @@ const TOOL_DEFINITIONS = [
4209
4323
  importance_degree: { type: "string", description: "low|mid|high — only when degree inside the bucket matters" },
4210
4324
  emotional_intensity: { type: "number" },
4211
4325
  context: { type: "string" },
4212
- source: { type: "string", description: "Which host produced this write. A shared default tag is ambiguity, not attribution." },
4326
+ source: { type: "string", description: "Which host produced this write. A shared default tag is ambiguity, not attribution. With EMET_TAG_HANDOFFS off, an HTTP caller may still name a tag here. With the flag at warn or enforce, HTTP uses the credential's tag, and a declared tag that differs is refused (EMET-DOC-088). Stdio keeps the declared tag." },
4213
4327
  tags: { type: "array", items: { type: "string" } },
4214
4328
  valid_until: { type: "number", description: "Unix seconds. After this the entry is marked ended and stays in recall and queries, with this date as its end date. It is not hidden and it is not deleted." },
4215
4329
  derived_from: {
@@ -4350,11 +4464,12 @@ const TOOL_DEFINITIONS = [
4350
4464
  },
4351
4465
  {
4352
4466
  name: "emet_session_open",
4353
- description: "Open a transcript session. Returns session_id, dated in the configured local time zone (EMET_TIMEZONE, default America/New_York). A slug that already begins with YYYY-MM-DD_ (month 01-12, day 01-31) is not dated again, even when that date is not the local day. A slug whose id is already CLOSED is never reopened: the session opens as <id>-2, -3, ... and the result's `notice` says so. Pass load_id from your startup pages (startup_page.load_id on every emet_initialize page) so the startup page check runs on your own startup; an open without load_id, or with a page of that startup never fetched, is refused (the refusal says how to pass). After every reply, call emet_transcript_append with that id and the one exchange that just happened. Do not dump the whole chat at close.",
4467
+ description: "Open a transcript session. Returns session_id, dated in the configured local time zone (EMET_TIMEZONE, default America/New_York). A slug that already begins with YYYY-MM-DD_ (month 01-12, day 01-31) is not dated again, even when that date is not the local day. A slug whose id is already CLOSED is never reopened: the session opens as <id>-2, -3, ... and the result's `notice` says so. Pass load_id from your startup pages (startup_page.load_id on every emet_initialize page) so the startup page check runs on your own startup; an open without load_id, or with a page of that startup never fetched, is refused (the refusal says how to pass). After every reply, call emet_transcript_append with that id and the one exchange that just happened. Do not dump the whole chat at close. When EMET_TAG_HANDOFFS is warn or enforce, the result also carries handoff_view (the stamp, including as_of), own_handoff, and stale_open. An open session with material work is an in-progress line. After EMET_STALE_OPEN_HOURS it is stale-open. Those fields are not part of load_id. With EMET_TAG_HANDOFFS at warn or enforce, HTTP uses the credential's tag, and a declared tag that differs is refused (EMET-DOC-088). With the flag off that check does not run.",
4354
4468
  inputSchema: {
4355
4469
  type: "object",
4356
4470
  properties: {
4357
4471
  slug: { type: "string", description: "Short name for the session, e.g. grok-init. A slug that already begins with YYYY-MM-DD_ (month 01-12, day 01-31) is the base and is not dated again, even when that date is not the local day. Any other slug receives the local day. A closed id still opens as -2, -3, .... Parts are still _verbatim_partN." },
4472
+ source: { type: "string", description: "The write tag opening this session. On stdio this declared tag is the session tag. With EMET_TAG_HANDOFFS at warn or enforce, HTTP uses the credential's tag, and a declared tag that differs is refused (EMET-DOC-088). With the flag off that check does not run. save_to_layer puts the same tag in metadata.source." },
4358
4473
  load_id: { type: "string", description: "Required for the startup page check (by policy; the schema leaves it optional so older hosts can still open): the load_id from `startup_page` on your emet_initialize pages - page 1 returns it, every page carries it, and the last page names it. An open without load_id, or with a page of that load known not fetched, is refused before anything is written (gate startup_pages); the refusal names the exact calls that pass." }
4359
4474
  }
4360
4475
  }
@@ -4397,20 +4512,20 @@ const TOOL_DEFINITIONS = [
4397
4512
  },
4398
4513
  {
4399
4514
  name: "write_doc",
4400
- description: "Write or update a continuity document in the document store (versioned, prior copy archived to documents_history and marked obsolete, sha256 read-back verified). RECORDS - the handoff (HANDOFF.md) and any id in EMET_RECORD_DOCS - are superseded, never amended: patch_doc is refused on them, and a new revision is written here WHOLE with `supersedes` set to the version currently in force (ISO 9001 7.5.3 / 13485 4.2.5).",
4515
+ description: "Write or update a continuity document in the document store (versioned, prior copy archived to documents_history and marked obsolete, sha256 read-back verified). RECORDS - the handoff (HANDOFF.md) and any id in EMET_RECORD_DOCS - are superseded, never amended: patch_doc is refused on them, and a new revision is written here WHOLE with `supersedes` set to the version currently in force (ISO 9001 7.5.3 / 13485 4.2.5). When EMET_TAG_HANDOFFS is warn or enforce, a write tag's handoff is HANDOFF/<tag>.md and only that credential writes it. Only the hub tag writes HANDOFF.md. A claimed tag is refused on HANDOFF/ (EMET-DOC-087). A two-segment id and a tag equal to a person id are refused (EMET-DOC-086). Another tag's handoff is refused (EMET-DOC-084). In warn, those new-prefix refusals apply at once. A registered non-hub write of HANDOFF.md or another tag's bots/ folder warns and is kept; enforce refuses it.",
4401
4516
  inputSchema: { type: "object", properties: {
4402
4517
  doc_id: { type: "string" },
4403
4518
  content: { type: "string" },
4404
4519
  supersedes: { type: "number", description: "Required when writing a new revision of a RECORD (the handoff): the version currently in force, which this revision supersedes. Ignored for ordinary documents." },
4405
4520
  reason: { type: "string", description: "Required on a record revision (at least 10 characters). Stored as edit_reason." },
4406
4521
  session_id: { type: "string", description: "Transcript session id. The floor is measured from the size when this session first touched the document." },
4407
- source: { type: "string", description: "Source tag - which host produced this write. One name on every write since 2026-09-27." },
4522
+ source: { type: "string", description: "Source tag - which host produced this write. One name on every write since 2026-09-27. With EMET_TAG_HANDOFFS at warn or enforce, HTTP refuses a declared tag that is not the credential when session_id is set (EMET-DOC-088). A call that declares no tag is kept. With the flag off that check does not run." },
4408
4523
  updated_by: { type: "string", description: "Alias of `source` (the older name, kept one release). Prefer `source`." }
4409
4524
  }, required: ["doc_id", "content"] }
4410
4525
  },
4411
4526
  {
4412
4527
  name: "write_doc_begin",
4413
- description: "Open a staged write when a document will not fit in one write_doc argument. The stage is not a document and does not change the current revision. Send each part with write_doc_append, then write_doc_commit. A record (HANDOFF.md and any id in EMET_RECORD_DOCS) still needs supersedes and reason; commit writes one whole revision through write_doc. Limits: 16000 characters per part, 128 parts, 2000000 characters total, 30 minutes from begin, 4 open stages per writer. Same source, session, and writer stamp as write_doc.",
4528
+ description: "Open a staged write when a document will not fit in one write_doc argument. The stage is not a document and does not change the current revision. Send each part with write_doc_append, then write_doc_commit. A record (HANDOFF.md and any id in EMET_RECORD_DOCS) still needs supersedes and reason; commit writes one whole revision through write_doc. Limits: 16000 characters per part, 128 parts, 2000000 characters total, 30 minutes from begin, 4 open stages per writer. When EMET_TAG_HANDOFFS is warn or enforce, HANDOFF/<tag>.md is that kind of record too, and the same credential check as write_doc runs at commit (EMET-DOC-088). Same source, session, and writer stamp as write_doc.",
4414
4529
  inputSchema: { type: "object", properties: {
4415
4530
  doc_id: { type: "string" },
4416
4531
  supersedes: { type: "number", description: "Required when staging a new revision of a RECORD: the version currently in force. Stored on the stage and passed to write_doc at commit." },
@@ -4432,7 +4547,7 @@ const TOOL_DEFINITIONS = [
4432
4547
  },
4433
4548
  {
4434
4549
  name: "write_doc_commit",
4435
- description: "Assemble an open stage, check part_count and the sha256 of the exact assembled text (the concatenation of the parts in order, before this server redacts it), then write one revision through write_doc. A mismatch or a write_doc refusal leaves the current document unchanged and the stage open. A second commit of the same sha256 returns the first receipt and does not write another revision. A record is still one whole revision: it is superseded, never patched or appended.",
4550
+ description: "Assemble an open stage, check part_count and the sha256 of the exact assembled text (the concatenation of the parts in order, before this server redacts it), then write one revision through write_doc. A mismatch or a write_doc refusal leaves the current document unchanged and the stage open. A second commit of the same sha256 returns the first receipt and does not write another revision. A record is still one whole revision: it is superseded, never patched or appended. Commit uses the same handoff credential check as write_doc when EMET_TAG_HANDOFFS is warn or enforce (EMET-DOC-088). A call that declares no tag is kept.",
4436
4551
  inputSchema: { type: "object", properties: {
4437
4552
  stage_id: { type: "string" },
4438
4553
  doc_id: { type: "string", description: "The same document id the stage was begun for." },
@@ -4517,7 +4632,7 @@ const TOOL_DEFINITIONS = [
4517
4632
  },
4518
4633
  {
4519
4634
  name: "patch_doc",
4520
- description: "Replace one exact substring in a document (str_replace semantics) without resending the whole file. THE PREFERRED WAY TO MAKE SMALL EDITS to large docs like STATE.md. old_str must match EXACTLY ONCE - zero or multiple matches are rejected rather than guessed. Pass new_str as an empty string to delete. Same versioning, archiving, and sha256 read-back as write_doc.",
4635
+ description: "Replace one exact substring in a document (str_replace semantics) without resending the whole file. THE PREFERRED WAY TO MAKE SMALL EDITS to large docs like STATE.md. old_str must match EXACTLY ONCE - zero or multiple matches are rejected rather than guessed. Pass new_str as an empty string to delete. Same versioning, archiving, and sha256 read-back as write_doc. When EMET_TAG_HANDOFFS is warn or enforce, a tag patches only the STATE.md rows it opened. Rows already on the board when the flag turns on belong to the hub tag. The hub changes another tag's row only to resolve a marked conflict, and resolve_conflict names that row and the handoff_view stamp, including as_of. A foreign row is warned and kept in warn, and refused in enforce (EMET-DOC-085). A bot tag may patch its own rows and still cannot write HANDOFF.md. patch_doc stays refused on a handoff record. HTTP refuses a declared tag that is not the credential when session_id is set (EMET-DOC-088). A call that declares no tag is kept.",
4521
4636
  inputSchema: { type: "object", properties: {
4522
4637
  doc_id: { type: "string" },
4523
4638
  old_str: { type: "string", description: "Exact text to replace. Must occur exactly once in the current text. Omit when `edits` is set." },
@@ -4567,7 +4682,7 @@ const TOOL_DEFINITIONS = [
4567
4682
  },
4568
4683
  {
4569
4684
  name: "emet_page_lint",
4570
- description: "Flag problems in topic pages and the records they read. Read-only: it never edits a record. Findings cover contradictions (two current records that share a subject and disagree), superseded or retired records still claimed as current, lines with no source, duplicates, broken links, and statuses unconfirmed longer than the area's staleness window. It builds on the emet_gaps classifiers. A fix is a person's revise_memory, retire_doc, or accept_nonconformance. Owner only. Omit area to lint every area.",
4685
+ description: "Flag problems in topic pages and the records they read. Read-only: it never edits a record. Findings cover contradictions (two current records that share a subject and disagree), superseded or retired records still claimed as current, lines with no source, duplicates, broken links, and statuses unconfirmed longer than the area's staleness window. When EMET_TAG_HANDOFFS is warn or enforce, a handoff_conflict finding names a board row whose current handoff lines disagree. The view does not pick a winner. It builds on the emet_gaps classifiers. A fix is a person's revise_memory, retire_doc, or accept_nonconformance. Owner only. Omit area to lint every area.",
4571
4686
  inputSchema: { type: "object", properties: {
4572
4687
  area: { type: "string", description: "Optional area slug. Omit to lint every current area." }
4573
4688
  } }
@@ -4644,7 +4759,7 @@ const TOOL_DEFINITIONS = [
4644
4759
  },
4645
4760
  {
4646
4761
  name: "emet_session_close",
4647
- description: "Call this when the session is ending - the user says goodbye, asks you to wrap up, mentions restarting or opening a new session, or you are about to run out of room. An acknowledgement of the turn just completed - thanks, great, perfect - is not a session end; if it is ambiguous, ask rather than close. Checks whether this session's work has actually been written to the store and reports exactly what is missing. It does not write anything itself. RECEIPTS ARE REQUIRED: pass `receipts` naming what you wrote and read back for each close step - working documents, the episodic session record id, the board and its version, the transcript part ids and highest exchange index as query_transcripts returned them, and the handoff version (written last). Each receipt is compared with the store; omitted or mismatched receipts, a handoff that was not the last write, or a transcript no layer entry cites (derived_from) return state 'blocked'. Each missing line carries a `scope`: touch only what it names. THREE blocked closes on one session return state 'escalate': stop retrying, say the `speak` lines, and hand the user the list - the counter does not reset on a changed receipt, only with a new session. Say every line of the returned `speak` to the user, in order - a wrap that leaves it out is a failed close. A records/ session disposition is not a receipt and does not make this call complete. Pass carry_forward only for an old open session whose HANDOFF and STATE a later session already advanced. The owner door, or the credential that wrote the session, cites the current conforming records/ disposition (CARRIED_FORWARD, SUPERSEDED_BY_LATER_SESSION, or ABANDONED_NO_TRANSCRIPT) and those later versions. RETAINED_OPEN_CRITICAL stays open. A declared source is not authority. Transcripts are not deleted. A refused carry_forward is not counted. A receipt close blocked only because a later session holds HANDOFF or STATE stays blocked and is not counted. A same-session close is unchanged. Never tell the user their session is saved unless this returns state 'complete'.",
4762
+ description: "Call this when the session is ending - the user says goodbye, asks you to wrap up, mentions restarting or opening a new session, or you are about to run out of room. An acknowledgement of the turn just completed - thanks, great, perfect - is not a session end; if it is ambiguous, ask rather than close. Checks whether this session's work has actually been written to the store and reports exactly what is missing. It does not write anything itself. RECEIPTS ARE REQUIRED: pass `receipts` naming what you wrote and read back for each close step - working documents, the episodic session record id, the board and its version, the transcript part ids and highest exchange index as query_transcripts returned them, and the handoff version (written last). Each receipt is compared with the store; omitted or mismatched receipts, a handoff that was not the last write, or a transcript no layer entry cites (derived_from) return state 'blocked'. Each missing line carries a `scope`: touch only what it names. THREE blocked closes on one session return state 'escalate': stop retrying, say the `speak` lines, and hand the user the list - the counter does not reset on a changed receipt, only with a new session. Say every line of the returned `speak` to the user, in order - a wrap that leaves it out is a failed close. A records/ session disposition is not a receipt and does not make this call complete. Pass carry_forward only for an old open session whose HANDOFF and STATE a later session already advanced. The owner door, or the credential that wrote the session, cites the current conforming records/ disposition (CARRIED_FORWARD, SUPERSEDED_BY_LATER_SESSION, or ABANDONED_NO_TRANSCRIPT) and those later versions. RETAINED_OPEN_CRITICAL stays open. A declared source is not authority. Transcripts are not deleted. A refused carry_forward is not counted. A receipt close blocked only because a later session holds HANDOFF or STATE stays blocked and is not counted. A same-session close is unchanged. When EMET_TAG_HANDOFFS is warn or enforce, every tag uses one receipt set: handoff_doc, handoff_version, and handoff_view (the stamp from initialize, including as_of). A stamp without as_of blocks the close. A board receipt is required only when this credential patched the board. The result echoes handoff_view. The continuity-currency gate stays warn-only and does not refuse the close. Never tell the user their session is saved unless this returns state 'complete'.",
4648
4763
  inputSchema: {
4649
4764
  type: "object",
4650
4765
  properties: {
@@ -4660,7 +4775,8 @@ const TOOL_DEFINITIONS = [
4660
4775
  transcript_parts: { type: "array", items: { type: "string" }, description: "Part ids query_transcripts returned for this session." },
4661
4776
  transcript_exchanges: { type: "number", description: "Highest exchange index query_transcripts returned." },
4662
4777
  handoff_version: { type: "number", description: "Version of the handoff, written last." },
4663
- handoff_doc: { type: "string", description: "Bot sessions only: the bot's own handoff record, bots/<source tag>/HANDOFF.md. A bot session needs no board receipt and never names the main HANDOFF.md or STATE.md." }
4778
+ handoff_doc: { type: "string", description: "The handoff this credential wrote last. The hub names HANDOFF.md. Another write tag names HANDOFF/<tag>.md. A bot may still name bots/<tag>/HANDOFF.md until that id is renamed." },
4779
+ handoff_view: { type: "object", description: "When EMET_TAG_HANDOFFS is warn or enforce: the stamp from initialize, with as_of, person, inputs, board, and view_sha256. A stamp without as_of is refused." }
4664
4780
  }
4665
4781
  },
4666
4782
  session_id: { type: "string", description: "The session_id used (or to be used) for this session's transcript, e.g. '2026-09-03_short-description'. Without it the transcript cannot be checked; receipts.transcript_session_id is used when this is omitted." },
@@ -4725,6 +4841,15 @@ const SUBKEY_TOOL_DEFINITIONS = [
4725
4841
  key_id: { type: "string", description: "The key whose live session to end. Pass tag or key_id." },
4726
4842
  reason: { type: "string", description: "Why the session was ended. Kept on the record." }
4727
4843
  } }
4844
+ },
4845
+ {
4846
+ name: "emet_subkey_set_kind",
4847
+ description: "Set the client kind stored on an approved sub-key. Owner only. bot keeps the one-live-session collision. chat is a client that wakes on a message. A key with no kind stored is a bot. The change is a history event. The key is not revoked.",
4848
+ inputSchema: { type: "object", properties: {
4849
+ tag: { type: "string", description: "The tag whose approved key to update. Pass tag or key_id." },
4850
+ key_id: { type: "string", description: "The key to update. Pass tag or key_id." },
4851
+ client_kind: { type: "string", description: "bot or chat. This is the kind the owner stores. A later call cannot set it." }
4852
+ }, required: ["client_kind"] }
4728
4853
  }
4729
4854
  ];
4730
4855
 
@@ -4776,7 +4901,7 @@ function cloneTool(t) {
4776
4901
 
4777
4902
  let toolCache = { flag: null, tools: null };
4778
4903
 
4779
- /** The tool list a host receives. The four sub-key tools and their schema fields exist only when EMET_SUBKEYS=1. */
4904
+ /** The tool list a host receives. The sub-key tools and their schema fields exist only when EMET_SUBKEYS=1. */
4780
4905
  export function hostTools() {
4781
4906
  const on = setting('SUBKEYS') === '1';
4782
4907
  if (toolCache.tools && toolCache.flag === on) return toolCache.tools;
package/src/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  /** The server's version, in one place. tests/version.test.js keeps it equal to package.json. */
2
- export const EMET_VERSION = '0.3.6';
2
+ export const EMET_VERSION = '0.3.7';
@@ -44,6 +44,7 @@ Every document listed under **Fills** is validated against its template by its i
44
44
  | `templates/USER.md` | `bootstrap/USER.md` | A store that relearns the person's name and preferences every session | IN FORCE 2026-09-26 · procedural ref 361 |
45
45
  | `templates/INSTALL.md` | `bootstrap/INSTALL.md` | A paste-block start that cannot check a machine or tag a write | IN FORCE 2026-09-26 · procedural ref 361 |
46
46
  | `templates/BOTHANDOFF.md` | `bots/<tag>/HANDOFF.md` (unmapped while DRAFT) | A bot that could close only by writing the user's own handoff and board; scheduled bot runs citing sessions never opened (episodic ref 558, ref 592); bot handoffs marked nonconforming against a template that demands a board | DRAFT — requested by the user 2026-10-01; approval and decision record pending. Supersede-only after revision 1 (`EMET_RECORD_DOCS`) |
47
+ | `templates/TAGHANDOFF.md` | `HANDOFF/<tag>.md` when `EMET_TAG_HANDOFFS` is warn or enforce | Several write tags sharing one handoff, and a board row changed by a tag that did not open it | IN FORCE with the flag. Off, the template is not applied. The view is not a record. |
47
48
  | `templates/ROSTER.md` | `bots/ROSTER.md` (unmapped while DRAFT) | A bot tag the server did not treat as a bot because its handoff id was never listed (a live check of per-bot close records, 2026-10-01); the hub's tag at risk of being listed with the bots | DRAFT — requested by the user 2026-10-01; approval and decision record pending. The hub is listed apart and never in `EMET_RECORD_DOCS` |
48
49
  | `templates/AREA.md` | `areas/<slug>.md` | A topic page stored as a record, so a view computed from the memory database became a second source of truth (the owner, 2026-10-20). The area document holds the selector only | IN FORCE 2026-10-20 · user. Only the owner creates or edits an area. The page is computed on each read and is never written back |
49
50
  | `templates/SESSIONDISPOSITION.md` | `records/*` | A close days later blocked because receipts are compared with the store that day, and a duplicate save_transcript left unmarked (inserted_id 6ae1df09c4da08b2cadc1fb4, 2026-10-28). The disposition notes the session or the transcript. It does not write a receipt and it does not delete the transcript | IN FORCE 2026-10-28 · user, session-disposition brief. A session-level row covers checkpoint overdue. An inserted_id row does not close the session |
@@ -0,0 +1,45 @@
1
+ # TEMPLATE — TAG HANDOFF
2
+
3
+ **Template control:** id `templates/TAGHANDOFF.md` · revision: the store's version governs · status: IN FORCE with the flag · owner: EMET (base) · built to `templates/STANDARD.md` · supersedes: none
4
+ **Fills:** `HANDOFF/<tag>.md` — one write tag's own session narrative, written last at that tag's close. It is a record when `EMET_TAG_HANDOFFS` is `warn` or `enforce`: revision 1 is written plain, every later revision is written whole with `supersedes` and a reason, and `patch_doc` is refused. The hub's `HANDOFF.md` is not filled from this template.
5
+ **Failure it prevents:** several write tags sharing one handoff, so the next session opens on whichever tag closed last, and a board row changed by a tag that did not open it.
6
+ **Completion rules:** `templates/STANDARD.md` §5, unmodified.
7
+
8
+ The flag is off by default. While it is off this template is not applied. The view that reads §1 is computed on read and is not a record.
9
+
10
+ ---
11
+
12
+ ## HOW TO FILL — rules specific to this template
13
+
14
+ 1. **This is this tag's record.** It holds what this tag did. Another tag's handoff is not this file.
15
+ 2. **Write this last,** after the working documents, the episodic record, any board patch of rows this tag opened, and the transcript.
16
+ 3. **§1 is the only section the shared view reads, plus the close-verification line.** At most 10 lines. Each line names a board row id, the state as this tag sees it, and the next step.
17
+ 4. **The view does not pick a winner.** If two tags disagree, both lines stay, under a conflict mark. Only the hub resolves a marked conflict, and the board write names the stamp.
18
+
19
+ ---
20
+
21
+ ## §0 RECORD CONTROL
22
+
23
+ - Template: `templates/TAGHANDOFF.md` rev __ · Handoff revision: v__ · Supersedes: v__ (or "none — first revision")
24
+ - Session id: __ · Source tag: __ · Person: the owner · Machine: __ · Written (local): __
25
+
26
+ ## §1 OVERALL PICTURE
27
+
28
+ At most 10 rows. The view reads this table and the close-verification line.
29
+
30
+ | Row | State | Next step |
31
+ | --- | --- | --- |
32
+ | B-___ | __ | __ |
33
+
34
+ ## §2 DONE THIS SESSION
35
+
36
+ | What | Evidence |
37
+ | --- | --- |
38
+
39
+ Or: *"Nothing completed this session."*
40
+
41
+ ## §3 CLOSE VERIFICATION
42
+
43
+ Close verification: episodic __
44
+
45
+ The episodic id counts as a pointer only when that session is closed. An open session is an in-progress line on the view, not a pointer.
@@ -0,0 +1,12 @@
1
+ SPECIFICATION Spec
2
+ INVARIANT TypeOK
3
+ INVARIANT NeverRewrites
4
+ INVARIANT NeverBlocks
5
+ INVARIANT WarnOnlyOnMaterialLag
6
+ INVARIANT FlagOffShowsNothing
7
+ INVARIANT NoOpIsNotAWarning
8
+ INVARIANT NoHandoffIsQuiet
9
+ INVARIANT UnreadableIsQuiet
10
+ INVARIANT FallbackOnlyIsNotBlockEligible
11
+ INVARIANT ScratchIsNotAWarning
12
+ INVARIANT VersionAloneDoesNotWarn