@dreamforgestudiollc/emet 0.3.0 → 0.3.2

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 (73) hide show
  1. package/.env.example +2 -2
  2. package/CHANGELOG.md +37 -0
  3. package/README.md +33 -8
  4. package/docs/BOOTSTRAP.md +2 -0
  5. package/docs/BOTS.md +8 -7
  6. package/docs/DEPLOY.md +6 -0
  7. package/docs/DEVELOPMENT-PRACTICES.md +26 -0
  8. package/docs/ERROR-CODES-SPEC.md +1 -1
  9. package/docs/ERROR-CODES.md +29 -0
  10. package/docs/GUIDED-SETUP.md +1 -1
  11. package/docs/PERMISSIONS.md +5 -5
  12. package/docs/SETUP.md +10 -4
  13. package/docs/SUBKEYS.md +4 -4
  14. package/package.json +3 -2
  15. package/server.json +8 -4
  16. package/src/aleph.js +34 -13
  17. package/src/annotations.js +6 -2
  18. package/src/approve-throttle.js +3 -0
  19. package/src/atlas-role.js +1 -1
  20. package/src/attribution.js +76 -28
  21. package/src/bound-door.js +170 -0
  22. package/src/break-glass.js +531 -0
  23. package/src/checkpoint.js +241 -0
  24. package/src/chooser.js +543 -0
  25. package/src/claimed-tag.js +140 -0
  26. package/src/conformance.js +269 -5
  27. package/src/deep-links.js +267 -0
  28. package/src/dispatch.js +112 -18
  29. package/src/error-codes.js +29 -0
  30. package/src/error-log.js +138 -26
  31. package/src/error-report.js +17 -5
  32. package/src/gaps.js +1 -1
  33. package/src/grants.js +230 -0
  34. package/src/http-remote.js +80 -26
  35. package/src/index.js +18 -2
  36. package/src/invites.js +47 -1
  37. package/src/layers.js +1 -1
  38. package/src/lessons-to-checks.js +1 -1
  39. package/src/logger.js +3 -1
  40. package/src/oauth-provider.js +89 -5
  41. package/src/owl.js +232 -0
  42. package/src/owner-approvals.js +24 -267
  43. package/src/owner-session.js +174 -0
  44. package/src/pages.js +1 -1
  45. package/src/persons.js +39 -6
  46. package/src/proof-run.js +70 -0
  47. package/src/redact.js +4 -0
  48. package/src/request-log.js +2 -2
  49. package/src/rotate.js +554 -0
  50. package/src/rune-dispatch.js +1 -1
  51. package/src/session-graph.js +44 -25
  52. package/src/session.js +3 -3
  53. package/src/setup.js +21 -12
  54. package/src/staged-write.js +522 -0
  55. package/src/startup-pages.js +2 -2
  56. package/src/startup-payload.js +3 -3
  57. package/src/subkeys.js +61 -0
  58. package/src/tools.js +270 -78
  59. package/src/transcript-session.js +23 -4
  60. package/src/validation.js +1 -1
  61. package/src/version.js +1 -1
  62. package/src/writer-approval.js +394 -0
  63. package/templates/AREA.md +1 -1
  64. package/templates/BOTHANDOFF.md +2 -2
  65. package/templates/GRANT.md +48 -0
  66. package/templates/INDEX.md +9 -7
  67. package/templates/PROCEDURE.md +1 -1
  68. package/templates/ROSTER.md +2 -2
  69. package/templates/SEED.md +2 -2
  70. package/templates/SESSIONDISPOSITION.md +59 -0
  71. package/templates/STAGING.md +1 -1
  72. package/templates/STANDARD.md +1 -1
  73. package/templates/THREAD.md +1 -1
package/src/tools.js CHANGED
@@ -13,17 +13,20 @@
13
13
 
14
14
  import { connectMongo } from './mongo-connect.js';
15
15
  import { newCorrelationId, EMET_INT_001, EMET_CODE_RE, lookupEmetCode } from './error-codes.js';
16
+ import { attachChooserLink } from './deep-links.js';
16
17
  import { recordError } from './error-log.js';
17
18
  import { resolveModulePath } from './module-path.js';
18
19
  import { replacedByOf } from './setup.js';
19
20
  import { currentActor, rawActor, writerStamp, boundSourceTag, declaredAttribution, LOCAL_SUBJECT } from './persons.js';
21
+ import { guardClaimedTag } from './claimed-tag.js';
20
22
  import { approvedTags, APPROVALS_DOC } from './attribution.js';
23
+ import { refuseSophiaDoor, sophiaActor, sophiaCredentialOverrides, sophiaClaimOnSharedLogin, CLAIM_TAG } from './bound-door.js';
21
24
  import { sealAttestation, frozenAttestation } from './rune-dispatch.js';
22
25
 
23
26
  /** Approvals record io for attribution.js (server-kept doc, written as emet-server). */
24
27
  export const approvalsDeps = {
25
28
  readDoc: (id) => readDoc(id),
26
- // Compare-and-set on the stored version (the second reader 3). mutateApprovals serializes
29
+ // Compare-and-set on the stored version (Tester 3). mutateApprovals serializes
27
30
  // writers in this process; this check catches a writer elsewhere.
28
31
  writeDoc: async (id, content, expectedVersion) => {
29
32
  // Atomic across processes: writeDoc filters the update on { doc_id, version: expected }.
@@ -209,6 +212,13 @@ export class RateLimiter {
209
212
  return { allowed: true };
210
213
  }
211
214
 
215
+ /** Forget tool-call counters in this process. Does not revoke a grant. */
216
+ clearToolLockout() {
217
+ const n = this.buckets.size;
218
+ this.buckets.clear();
219
+ return n;
220
+ }
221
+
212
222
  recordRequest(toolName, bucketKey = 'stdio') {
213
223
  const now = Date.now();
214
224
  const bucket = this._bucket(bucketKey);
@@ -319,7 +329,7 @@ function wrapValidationError(error) {
319
329
  /**
320
330
  * Central error handler for all tool operations
321
331
  */
322
- export function handleError(error, toolName, logger = null) {
332
+ export function handleError(error, toolName, logger = null, logFields = null) {
323
333
  let errorResponse;
324
334
 
325
335
  if (error instanceof EmetError) {
@@ -370,11 +380,14 @@ export function handleError(error, toolName, logger = null) {
370
380
  const correlationId = newCorrelationId();
371
381
  errorResponse.error.emet_code = stamped;
372
382
  errorResponse.error.correlation_id = correlationId;
383
+ attachChooserLink(errorResponse, error, correlationId);
384
+ if (error && error.chooser) delete error.chooser;
373
385
  void recordError({
374
386
  emet_code: stamped,
375
387
  class_code: errorResponse.error.code,
376
388
  tool: toolName,
377
- correlation_id: correlationId
389
+ correlation_id: correlationId,
390
+ ...(toolName === 'emet_session_close' ? { session_id: logFields && logFields.session_id } : {})
378
391
  });
379
392
 
380
393
  // Read at call time. Never attach a stack on the HTTP server.
@@ -545,6 +558,7 @@ export async function saveMemory(dbManager, content, layer = null, metadata = {}
545
558
  // stored (no bound tag) may use the caller's tag only when that tag is an
546
559
  // exact member of EMET_SOURCE_TAGS. The shared default is not applied there.
547
560
  const sourceDecision = resolvedSourceTag(validatedMetadata.source);
561
+ if (sourceDecision.from === 'bound-door') refuseSophiaDoor(sophiaActor());
548
562
  if (sourceDecision.from === 'caller') {
549
563
  const defaultTag = setting('SOURCE_TAG');
550
564
  if (sourceDecision.tag) {
@@ -558,7 +572,7 @@ export async function saveMemory(dbManager, content, layer = null, metadata = {}
558
572
  }
559
573
  } else {
560
574
  validatedMetadata.source = sourceDecision.tag;
561
- if (sourceDecision.from === 'declared' || sourceDecision.from === 'auto' || sourceDecision.from === 'subkey') {
575
+ if (sourceDecision.from === 'declared' || sourceDecision.from === 'auto' || sourceDecision.from === 'subkey' || sourceDecision.from === 'credential') {
562
576
  validatedMetadata.source_basis = sourceDecision.from;
563
577
  if (sourceDecision.login) validatedMetadata.source_login = sourceDecision.login;
564
578
  if (sourceDecision.from === 'subkey' && sourceDecision.key_id) validatedMetadata.key_id = sourceDecision.key_id;
@@ -579,14 +593,29 @@ export async function saveMemory(dbManager, content, layer = null, metadata = {}
579
593
  // one fixed local subject. A caller client_id never survives in custom.
580
594
  {
581
595
  const stamp = writerStamp();
596
+ const claimed = guardClaimedTag({
597
+ transport: currentActor().transport,
598
+ grant_id: stamp.grant_id,
599
+ sourceFrom: sourceDecision.from,
600
+ caller: sourceDecision.tag,
601
+ tool: 'save_to_layer'
602
+ });
603
+ if (claimed.warning) warnings.push(claimed.warning);
582
604
  validatedMetadata.person_id = stamp.person_id;
583
605
  delete validatedMetadata.client_id;
606
+ delete validatedMetadata.grant_id;
607
+ delete validatedMetadata.door;
584
608
  if (validatedMetadata.custom && typeof validatedMetadata.custom === 'object') {
585
609
  delete validatedMetadata.custom.client_id;
586
610
  delete validatedMetadata.custom.person_id;
611
+ delete validatedMetadata.custom.grant_id;
612
+ delete validatedMetadata.custom.door;
587
613
  if (Object.keys(validatedMetadata.custom).length === 0) delete validatedMetadata.custom;
588
614
  }
589
615
  validatedMetadata.client_id = stamp.client_id;
616
+ validatedMetadata.grant_id = stamp.grant_id;
617
+ validatedMetadata.door = stamp.door;
618
+ if (claimed.claimed) validatedMetadata.claimed_tag = true;
590
619
  }
591
620
  await sealAttestation(validatedMetadata, {
592
621
  session_id: options && options.session_id,
@@ -792,7 +821,7 @@ export async function saveMemory(dbManager, content, layer = null, metadata = {}
792
821
  const correction = (validatedMetadata.corrects !== undefined && validatedMetadata.corrects !== null)
793
822
  ? await markCorrectedBy(dbManager, targetLayer, validatedMetadata.corrects, memoryId)
794
823
  : null;
795
- // the second reader N4: a correction whose parent could not be marked is still saved,
824
+ // Tester N4: a correction whose parent could not be marked is still saved,
796
825
  // but the caller is told in words, not only by a boolean.
797
826
  if (correction && correction.marked !== true) {
798
827
  warnings.push(`corrects: ${correction.parent_id} - the parent entry was not marked corrected_by (missing in ${targetLayer}, or the mark did not hold); the correction is saved, the link is one-sided until the parent is marked`);
@@ -847,6 +876,7 @@ export async function saveMemory(dbManager, content, layer = null, metadata = {}
847
876
  ...(provenanceStamped ? { provenance_stamped: 'from the named transcript session; the exchange is the one in progress, stored by the append after this reply' } : {}),
848
877
  ...(md.provenance_missing ? { provenance_missing: true } : {}),
849
878
  source: md.source,
879
+ grant_id: md.grant_id,
850
880
  ...(md.source_defaulted ? { source_defaulted: true } : {}),
851
881
  ...(md.source_unregistered ? { source_unregistered: true } : {}),
852
882
  ...(md.source_missing ? { source_missing: true } : {}),
@@ -985,7 +1015,7 @@ export async function resolveSupersessionChain(read, entry, maxHops = 50) {
985
1015
  }
986
1016
 
987
1017
  /**
988
- * Option A correction back-pointer (Alex, 2026-10-02, procedural ref 405 item 4; the reviewer's sketch in his
1018
+ * Option A correction back-pointer (Alex, 2026-10-02, procedural ref 405 item 4; Reviewer's sketch in his
989
1019
  * second read of episodic ref 604). Episodic entries are immutable events, so a PARTIAL correction cannot
990
1020
  * supersede its parent: supersession would put an end date on the whole parent and present every item
991
1021
  * in it as replaced. Instead the new entry carries metadata.corrects = <parent id>, and the parent is MARKED:
@@ -999,7 +1029,7 @@ export async function resolveSupersessionChain(read, entry, maxHops = 50) {
999
1029
  * corrected_by mark): the new metadata digest and, when a signing key is set
1000
1030
  * and the row's existing signature verifies against its metadata before the
1001
1031
  * marks (aleph.js signatureCoversPriorMetadata), a fresh signature over the
1002
- * same content digest and the new metadata digest (2026-10-02, the reviewer's
1032
+ * same content digest and the new metadata digest (2026-10-02, Reviewer's
1003
1033
  * finding: the marks left signed:false behind). With no key, or a signature
1004
1034
  * that does not verify, the signature is left exactly as it is: never re-signed
1005
1035
  * blindly, so a row changed outside the sanctioned path keeps reading
@@ -1019,23 +1049,32 @@ export async function markCorrectedBy(dbManager, layer, parentId, childId) {
1019
1049
  const parent = await col.findOne({ id: parentId });
1020
1050
  if (!parent) return { parent_id: parentId, marked: false };
1021
1051
  const cid = Number(childId);
1022
- // Race-safe (the second reader N3 / the reviewer, 2026-10-02): the id is ADDED atomically
1052
+ // Race-safe (Tester N3 / Reviewer, 2026-10-02): the id is ADDED atomically
1023
1053
  // ($addToSet on the column and on the metadata copy), never written back
1024
1054
  // from a stale read, so two simultaneous corrections of one parent both
1025
1055
  // land. A legacy string-metadata row falls back to read-modify-write.
1056
+ // corrected_grant_id is the latest door that marked this parent. corrected_by
1057
+ // keeps every child. A later correction by a different grant replaces the
1058
+ // grant value; it is not appended. The prior signature covered the previous
1059
+ // grant, so that row is not re-signed (aleph.js).
1060
+ const grant = writerStamp().grant_id;
1026
1061
  if (parent.metadata && typeof parent.metadata === 'object') {
1027
- await col.updateOne({ id: parentId }, { $addToSet: { corrected_by: cid, 'metadata.corrected_by': cid } });
1062
+ await col.updateOne({ id: parentId }, {
1063
+ $addToSet: { corrected_by: cid, 'metadata.corrected_by': cid },
1064
+ $set: { corrected_grant_id: grant, 'metadata.corrected_grant_id': grant }
1065
+ });
1028
1066
  } else {
1029
1067
  const md = parseMetadata(parent.metadata);
1030
1068
  const list = Array.isArray(md.corrected_by) ? md.corrected_by.map(Number) : [];
1031
1069
  if (!list.includes(cid)) list.push(cid);
1032
1070
  md.corrected_by = list;
1033
- await col.updateOne({ id: parentId }, { $set: { metadata: md, corrected_by: list } });
1071
+ md.corrected_grant_id = grant;
1072
+ await col.updateOne({ id: parentId }, { $set: { metadata: md, corrected_by: list, corrected_grant_id: grant } });
1034
1073
  }
1035
1074
  // Re-attest from what is actually stored. The digest is set only if the
1036
1075
  // stored metadata is still exactly the metadata it was computed from: the
1037
1076
  // compare-and-set filter is the WHOLE metadata value, not only corrected_by
1038
- // (the reviewer, 2026-10-02), so a concurrent change to any metadata field in
1077
+ // (Reviewer, 2026-10-02), so a concurrent change to any metadata field in
1039
1078
  // between (another mark, a superseded_by, anything) makes the filter miss,
1040
1079
  // and the loop re-reads and re-digests. The last re-attest therefore always
1041
1080
  // covers what is stored. The value compared is the one just read back, so
@@ -1112,6 +1151,7 @@ export async function reviseMemory(dbManager, layer, target_id, content, metadat
1112
1151
 
1113
1152
  targetMd.superseded_by = saved.id;
1114
1153
  targetMd.superseded_at = saved.timestamp;
1154
+ targetMd.superseded_grant_id = writerStamp().grant_id;
1115
1155
  // Write BOTH the metadata copy and the promoted top-level column. The
1116
1156
  // top-level one is what a reader follows (indexed); the metadata copy
1117
1157
  // stays for audit. Always written as a subdocument - a parent still
@@ -1122,6 +1162,7 @@ export async function reviseMemory(dbManager, layer, target_id, content, metadat
1122
1162
  metadata: targetMd,
1123
1163
  superseded_by: saved.id,
1124
1164
  superseded_at: saved.timestamp,
1165
+ superseded_grant_id: targetMd.superseded_grant_id,
1125
1166
  // C1: marking a parent is the ONE sanctioned mutation of stored metadata,
1126
1167
  // so the parent is re-attested in the same write. Without this every
1127
1168
  // superseded row would read as a metadata mismatch from then on. With a
@@ -1922,6 +1963,16 @@ export async function saveTranscript(session_id, session_start, session_end, exc
1922
1963
  }
1923
1964
  assertExchangeBudget(exchanges.flatMap((ex) => [ex && ex.user_message, ex && ex.assistant_message]));
1924
1965
  const resolvedExchanges = exchanges;
1966
+ const transcriptStamp = writerStamp();
1967
+ const transcriptDecision = resolvedSourceTag(resolvedChannel);
1968
+ const stampedChannel = stampedSource(transcriptDecision, resolvedChannel);
1969
+ const transcriptClaim = guardClaimedTag({
1970
+ transport: currentActor().transport,
1971
+ grant_id: transcriptStamp.grant_id,
1972
+ sourceFrom: transcriptDecision.from,
1973
+ caller: transcriptDecision.tag,
1974
+ tool: 'save_transcript'
1975
+ });
1925
1976
 
1926
1977
  const client = await connectMongo(MONGODB_URI, { serverSelectionTimeoutMS: 5000, maxPoolSize: 10 });
1927
1978
  const db = client.db(MONGODB_DB);
@@ -1945,11 +1996,11 @@ export async function saveTranscript(session_id, session_start, session_end, exc
1945
1996
 
1946
1997
  const sessionDoc = {
1947
1998
  session_id,
1948
- channel: resolvedChannel,
1999
+ channel: stampedChannel,
1949
2000
  session_start: new Date(session_start * 1000),
1950
2001
  session_end: session_end ? new Date(session_end * 1000) : new Date(),
1951
2002
  exchange_count: resolvedExchanges.length,
1952
- exchanges: resolvedExchanges.map((ex, i) => stampExchange(storedExchange(ex, i, scrub), resolvedChannel)),
2003
+ exchanges: resolvedExchanges.map((ex, i) => stampExchange(storedExchange(ex, i, scrub), stampedChannel, transcriptStamp)),
1953
2004
  created_at: new Date()
1954
2005
  };
1955
2006
  if (redactedSpans > 0) sessionDoc.redacted_spans = redactedSpans;
@@ -1962,10 +2013,12 @@ export async function saveTranscript(session_id, session_start, session_end, exc
1962
2013
  return {
1963
2014
  success: true,
1964
2015
  session_id,
1965
- channel: resolvedChannel,
2016
+ channel: stampedChannel,
1966
2017
  inserted_id: result.insertedId.toString(),
1967
2018
  exchange_count: resolvedExchanges.length,
1968
2019
  redacted: redactedSpans,
2020
+ grant_id: transcriptStamp.grant_id,
2021
+ ...(transcriptClaim.warning ? { claimed_tag_warning: transcriptClaim.warning } : {}),
1969
2022
  ...(timestampsDefaulted > 0 ? { timestamps_defaulted: timestampsDefaulted } : {}),
1970
2023
  performance: { duration_ms: duration }
1971
2024
  };
@@ -1999,13 +2052,14 @@ export function storedExchange(ex, i, scrub, now = new Date()) {
1999
2052
  };
2000
2053
  }
2001
2054
 
2002
- function stampExchange(row, source) {
2003
- const stamp = writerStamp();
2055
+ export function stampExchange(row, source, stamp = writerStamp()) {
2004
2056
  return {
2005
2057
  ...row,
2006
2058
  source: source || setting('SOURCE_TAG') || null,
2007
2059
  person_id: stamp.person_id,
2008
- client_id: stamp.client_id
2060
+ client_id: stamp.client_id,
2061
+ grant_id: stamp.grant_id,
2062
+ door: stamp.door
2009
2063
  };
2010
2064
  }
2011
2065
 
@@ -2204,6 +2258,16 @@ export async function transcriptAppend(args = {}, logger = null) {
2204
2258
  throw new ValidationError('user_message and assistant_message must be strings', { code: 'EMET-TRN-006' });
2205
2259
  }
2206
2260
  assertExchangeBudget([user_message, assistant_message]);
2261
+ const appendStamp = writerStamp();
2262
+ const appendDecision = resolvedSourceTag(channel);
2263
+ const stampedChannel = stampedSource(appendDecision, channel || setting('SOURCE_TAG') || null);
2264
+ const appendClaim = guardClaimedTag({
2265
+ transport: currentActor().transport,
2266
+ grant_id: appendStamp.grant_id,
2267
+ sourceFrom: appendDecision.from,
2268
+ caller: appendDecision.tag || channel,
2269
+ tool: 'emet_transcript_append'
2270
+ });
2207
2271
  const {
2208
2272
  partId, partNumber, baseFromPart, nextExchangeIndex, shouldStartNewPart, EXCHANGES_PER_PART
2209
2273
  } = await import('./transcript-session.js');
@@ -2228,18 +2292,12 @@ export async function transcriptAppend(args = {}, logger = null) {
2228
2292
  }
2229
2293
 
2230
2294
  const scrub = (s) => redactWithReport(s || '').text;
2231
- const stamp = writerStamp();
2232
- const row = {
2233
- ...storedExchange({
2234
- exchange_index: idx,
2235
- user_message,
2236
- assistant_message,
2237
- timestamp: Date.now() / 1000
2238
- }, idx - 1, scrub),
2239
- source: channel || setting('SOURCE_TAG') || null,
2240
- person_id: stamp.person_id,
2241
- client_id: stamp.client_id
2242
- };
2295
+ const row = stampExchange(storedExchange({
2296
+ exchange_index: idx,
2297
+ user_message,
2298
+ assistant_message,
2299
+ timestamp: Date.now() / 1000
2300
+ }, idx - 1, scrub), stampedChannel, appendStamp);
2243
2301
  const attr = declaredAttribution();
2244
2302
  if (attr && attr.basis === 'subkey' && attr.keyId) {
2245
2303
  row.key_id = attr.keyId;
@@ -2265,7 +2323,7 @@ export async function transcriptAppend(args = {}, logger = null) {
2265
2323
  const start = typeof session_start === 'number' ? session_start : Date.now() / 1000;
2266
2324
  await col.insertOne({
2267
2325
  session_id: part,
2268
- channel: channel || setting('SOURCE_TAG') || 'mcp',
2326
+ channel: stampedChannel || 'mcp',
2269
2327
  session_start: new Date(start * 1000),
2270
2328
  session_end: new Date(),
2271
2329
  exchange_count: 1,
@@ -2274,6 +2332,8 @@ export async function transcriptAppend(args = {}, logger = null) {
2274
2332
  });
2275
2333
  return {
2276
2334
  session_id: part, exchange_index: idx, exchange_count: 1, rolled: part !== session_id,
2335
+ grant_id: appendStamp.grant_id,
2336
+ ...(appendClaim.warning ? { claimed_tag_warning: appendClaim.warning } : {}),
2277
2337
  ...(machineCheck ? { machine_line: machineCheck.enforced ? `checked: ${machineCheck.matched}` : machineCheck.reason } : {})
2278
2338
  };
2279
2339
  }
@@ -2288,7 +2348,9 @@ export async function transcriptAppend(args = {}, logger = null) {
2288
2348
  exchange_index: idx,
2289
2349
  exchange_count: (live.exchange_count || exchanges.length) + 1,
2290
2350
  rolled: part !== session_id,
2291
- next_part_after: EXCHANGES_PER_PART
2351
+ next_part_after: EXCHANGES_PER_PART,
2352
+ grant_id: appendStamp.grant_id,
2353
+ ...(appendClaim.warning ? { claimed_tag_warning: appendClaim.warning } : {})
2292
2354
  };
2293
2355
  } finally {
2294
2356
  await client.close();
@@ -2320,6 +2382,15 @@ export async function reviseTranscript(session_id, exchanges, reason, session_st
2320
2382
  throw new ValidationError('exchanges must be a non-empty array - a revision replaces the whole part, not a field within it', { code: 'EMET-TRN-007' });
2321
2383
  if (!reason || typeof reason !== 'string' || reason.trim().length < 10)
2322
2384
  throw new ValidationError('reason is required and must describe what was wrong - at least 10 characters. An unexplained correction is a silent rewrite.', { code: 'EMET-TRN-008' });
2385
+ const reviseStamp = writerStamp();
2386
+ const reviseDecision = resolvedSourceTag(channel);
2387
+ const reviseClaim = guardClaimedTag({
2388
+ transport: currentActor().transport,
2389
+ grant_id: reviseStamp.grant_id,
2390
+ sourceFrom: reviseDecision.from,
2391
+ caller: reviseDecision.tag || channel,
2392
+ tool: 'revise_transcript'
2393
+ });
2323
2394
 
2324
2395
  const client = await connectMongo(MONGODB_URI, { serverSelectionTimeoutMS: 5000, maxPoolSize: 10 });
2325
2396
  const db = client.db(MONGODB_DB);
@@ -2342,7 +2413,7 @@ export async function reviseTranscript(session_id, exchanges, reason, session_st
2342
2413
  session_start: session_start ? new Date(session_start * 1000) : parent.session_start,
2343
2414
  session_end: session_end ? new Date(session_end * 1000) : parent.session_end,
2344
2415
  exchange_count: exchanges.length,
2345
- exchanges: exchanges.map((ex, i) => stampExchange(storedExchange(ex, i, scrub), channel || parent.channel)),
2416
+ exchanges: exchanges.map((ex, i) => stampExchange(storedExchange(ex, i, scrub), channel || parent.channel, reviseStamp)),
2346
2417
  ...(redactedSpans > 0 ? { redacted_spans: redactedSpans } : {}),
2347
2418
  revision,
2348
2419
  supersedes: parent._id,
@@ -2353,7 +2424,8 @@ export async function reviseTranscript(session_id, exchanges, reason, session_st
2353
2424
  };
2354
2425
 
2355
2426
  const result = await col.insertOne(revised);
2356
- await col.updateOne({ _id: parent._id }, { $set: { superseded_by: result.insertedId } });
2427
+ const reviseGrant = reviseStamp.grant_id;
2428
+ await col.updateOne({ _id: parent._id }, { $set: { superseded_by: result.insertedId, superseded_grant_id: reviseGrant } });
2357
2429
 
2358
2430
  // Read back rather than trust the write, and confirm the parent survived -
2359
2431
  // a supersession that lost the original would be a deletion with extra steps.
@@ -2382,6 +2454,8 @@ export async function reviseTranscript(session_id, exchanges, reason, session_st
2382
2454
  ? { timestamps_defaulted: revised.exchanges.filter(e => e.timestamp_defaulted).length } : {}),
2383
2455
  previous_exchange_count: parent.exchange_count ?? null,
2384
2456
  redacted: redactedSpans,
2457
+ grant_id: reviseStamp.grant_id,
2458
+ ...(reviseClaim.warning ? { claimed_tag_warning: reviseClaim.warning } : {}),
2385
2459
  revision_reason: reason.trim(),
2386
2460
  note: verified
2387
2461
  ? 'The prior version is retained and marked superseded. Readers take the revision; the original stays auditable.'
@@ -2560,7 +2634,7 @@ export async function readDoc(doc_id, logger = null, opts = {}) {
2560
2634
  // current, which is the whole of "prevent unintended use".
2561
2635
  return { doc_id: doc.doc_id, content, sha256: doc.sha256, version: doc.version,
2562
2636
  updated_at: doc.updated_at, updated_by: doc.updated_by || null,
2563
- client_id: doc.client_id || null, session_id: doc.session_id || null,
2637
+ client_id: doc.client_id || null, grant_id: doc.grant_id || null, door: doc.door || null, session_id: doc.session_id || null,
2564
2638
  ...(doc.key_id ? { key_id: doc.key_id } : {}),
2565
2639
  ...(doc.source_basis ? { source_basis: doc.source_basis } : {}),
2566
2640
  path_hint: doc.path_hint || null, size: doc.content.length,
@@ -2604,7 +2678,7 @@ export async function readDocHistory(doc_id, version = null, logger = null) {
2604
2678
  if (version === null || version === undefined) {
2605
2679
  const retained = await hist.find({ doc_id }, { projection: { content: 0 } }).sort({ version: 1 }).toArray();
2606
2680
  const rows = retained.map(r => ({ version: r.version, sha256: r.sha256 || null, size: r.size ?? null,
2607
- updated_at: r.updated_at || null, updated_by: r.updated_by || null, client_id: r.client_id || null, session_id: r.session_id || null, archived_at: r.archived_at || null,
2681
+ updated_at: r.updated_at || null, updated_by: r.updated_by || null, client_id: r.client_id || null, grant_id: r.grant_id || null, door: r.door || null, session_id: r.session_id || null, archived_at: r.archived_at || null,
2608
2682
  ...(r.key_id ? { key_id: r.key_id } : {}),
2609
2683
  ...(r.source_basis ? { source_basis: r.source_basis } : {}),
2610
2684
  conformance: r.conformance ? r.conformance.verdict : null }));
@@ -2614,7 +2688,7 @@ export async function readDocHistory(doc_id, version = null, logger = null) {
2614
2688
  if (current && current.version === version) {
2615
2689
  return { doc_id, version, is_current: true, content: current.content, sha256: current.sha256, size: current.content.length,
2616
2690
  updated_at: current.updated_at, updated_by: current.updated_by || null,
2617
- client_id: current.client_id || null, session_id: current.session_id || null,
2691
+ client_id: current.client_id || null, grant_id: current.grant_id || null, door: current.door || null, session_id: current.session_id || null,
2618
2692
  ...(current.key_id ? { key_id: current.key_id } : {}),
2619
2693
  ...(current.source_basis ? { source_basis: current.source_basis } : {}),
2620
2694
  conformance: current.conformance || null };
@@ -2626,7 +2700,7 @@ export async function readDocHistory(doc_id, version = null, logger = null) {
2626
2700
  const integrity = row.sha256 ? (digest(row.content) === row.sha256) : 'unattested';
2627
2701
  return { doc_id, version, is_current: false, content: row.content, sha256: row.sha256 || null, size: row.content.length,
2628
2702
  updated_at: row.updated_at || null, updated_by: row.updated_by || null, archived_at: row.archived_at || null,
2629
- client_id: row.client_id || null, session_id: row.session_id || null,
2703
+ client_id: row.client_id || null, grant_id: row.grant_id || null, door: row.door || null, session_id: row.session_id || null,
2630
2704
  ...(row.key_id ? { key_id: row.key_id } : {}),
2631
2705
  ...(row.source_basis ? { source_basis: row.source_basis } : {}),
2632
2706
  conformance: row.conformance || null,
@@ -2682,14 +2756,14 @@ function _refuseRecordAmendment(doc_id, tool) {
2682
2756
  * 3.5). write_doc and patch_doc refuse the main HANDOFF.md or STATE.md when the
2683
2757
  * write's source is a bot tag (bots/<tag>/HANDOFF.md listed in
2684
2758
  * EMET_RECORD_DOCS), and nothing is written. So do the other doors that can
2685
- * change a main record (the reviewer's F1 on PR 2): retire_doc, rename_doc (from
2759
+ * change a main record (Reviewer's F1 on PR 2): retire_doc, rename_doc (from
2686
2760
  * or onto one) and accept_nonconformance - retire and rename set retired_by,
2687
2761
  * not updated_by, so the close alone could not see them. The source is the one the door
2688
2762
  * stamps as updated_by: the caller's, else EMET_SOURCE_TAG. A records rule like
2689
2763
  * the record-amendment refusal above, so it applies in every graph mode.
2690
2764
  *
2691
- * Two further guards on the same doors (2026-10-01, the owner's 4:17 PM approval to
2692
- * make the bot tags fully functional; the reviewer's review of PR 3):
2765
+ * Two further guards on the same doors (2026-10-01, Alex's 4:17 PM approval to
2766
+ * make the bot tags fully functional; Reviewer's review of PR 3):
2693
2767
  * - REGISTERED HOSTS ONLY on the main records. With a source registry
2694
2768
  * configured (EMET_SOURCE_TAGS, parsed as save_to_layer parses it), the
2695
2769
  * main handoff and board take writes only from a registered tag. An
@@ -2710,7 +2784,7 @@ export function sourceRegistry() {
2710
2784
  }
2711
2785
 
2712
2786
  /**
2713
- * Attribution v2 (the second reader A3): a declared tag never gains rights beyond the login's
2787
+ * Attribution v2 (Tester A3): a declared tag never gains rights beyond the login's
2714
2788
  * tag. A guard is run for every tag returned here and the write must pass all.
2715
2789
  */
2716
2790
  export function rightsTags(tag) {
@@ -2733,6 +2807,17 @@ export function resolvedSourceTag(caller) {
2733
2807
  const bound = boundSourceTag();
2734
2808
  const tag = typeof caller === 'string' ? caller.trim() : '';
2735
2809
  if (bound === undefined) return { tag: tag || null, from: 'caller' };
2810
+ const actor = sophiaActor();
2811
+ if (sophiaCredentialOverrides(actor, tag)) {
2812
+ const sub = actor.subkeySession === true && actor.subkeyTag === CLAIM_TAG;
2813
+ return {
2814
+ tag: CLAIM_TAG,
2815
+ from: sub ? 'subkey' : 'credential',
2816
+ login: bound || null,
2817
+ ...(sub && actor.subkeyId ? { key_id: actor.subkeyId } : {})
2818
+ };
2819
+ }
2820
+ if (sophiaClaimOnSharedLogin(actor, tag)) return { tag: null, from: 'bound-door', login: bound || null };
2736
2821
  // Attribution v2: the per-request tag decided by attribution.preflight is the
2737
2822
  // stamp (declared, or generated for a login with none). Rights stay the
2738
2823
  // login's: see rightsTags().
@@ -2745,14 +2830,21 @@ export function resolvedSourceTag(caller) {
2745
2830
  return { tag: null, from: 'legacy' };
2746
2831
  }
2747
2832
 
2748
- // Look-alike doc ids (the second reader's recheck d1-d5, 2026-10-02): a `.` or `..` segment,
2833
+ /** A BOUND credential stamp replaces a forged Master Hub string. A door claim throws. */
2834
+ function stampedSource(decision, fallback) {
2835
+ if (decision && decision.from === 'bound-door') refuseSophiaDoor(sophiaActor());
2836
+ if (decision && (decision.from === 'credential' || (decision.from === 'subkey' && decision.tag === CLAIM_TAG))) return decision.tag;
2837
+ return fallback;
2838
+ }
2839
+
2840
+ // Look-alike doc ids (Tester's recheck d1-d5, 2026-10-02): a `.` or `..` segment,
2749
2841
  // a leading `/`, or a `bots/` prefix in the wrong case would let a write pass
2750
2842
  // the prefix checks below while naming a record they are meant to fence (d1:
2751
2843
  // bots/tester-bot/../intake-bot/HANDOFF.md passed the own-dir check). Doc
2752
2844
  // ids are flat strings, never resolved as paths, so these shapes are refused
2753
2845
  // outright, before any guard, on every door that calls this.
2754
2846
  //
2755
- // Hardening (the reviewer's scope on the doc-id fix, 2026-10-02): also refused are
2847
+ // Hardening (Reviewer's scope on the doc-id fix, 2026-10-02): also refused are
2756
2848
  // control and invisible-format characters (\p{Cc}, \p{Cf}) anywhere; leading or
2757
2849
  // trailing whitespace on the id or on any segment; a backslash; the `/`, `.`/`..`
2758
2850
  // and `bots/` checks run on the NFKC form too (so full-width dots and slashes,
@@ -2799,7 +2891,7 @@ export function refuseLookalikeDocId(doc_id, tool) {
2799
2891
  }
2800
2892
  }
2801
2893
 
2802
- // Cleanup path (the reviewer's scope): a look-alike id may already exist in a store
2894
+ // Cleanup path (Reviewer's scope): a look-alike id may already exist in a store
2803
2895
  // written before these checks. retire_doc, and rename_doc FROM such an id, are let
2804
2896
  // through for a registered host tag only: EMET_SOURCE_TAGS set, the tag listed,
2805
2897
  // and not a bot tag. Never for a write, a patch, a rename onto it, or a bot.
@@ -2813,12 +2905,12 @@ export function refuseBotMainRecord(doc_id, updated_by, tool, options = {}) {
2813
2905
  }
2814
2906
  function refuseBotMainRecordOne(doc_id, updated_by, tool, options = {}) {
2815
2907
  const tag = updated_by || setting('SOURCE_TAG') || null;
2816
- // The client-approvals record is server-only (the second reader 4): no host writes,
2908
+ // The client-approvals record is server-only (Tester 4): no host writes,
2817
2909
  // patches, retires, renames, restores or accepts it.
2818
2910
  if (typeof doc_id === 'string' && FOLD(doc_id.normalize('NFKC')) === FOLD(APPROVALS_DOC) && !(options && options.approvalsRecord === true)) {
2819
2911
  throw new ValidationError(`${tool}: ${doc_id} is kept by the server (client approvals). Decide clients with emet_client_approve. Nothing was written.`, { code: 'EMET-DOC-009' });
2820
2912
  }
2821
- // A3 without a registry (the second reader re-review): a declared or generated tag writes
2913
+ // A3 without a registry (Tester re-review): a declared or generated tag writes
2822
2914
  // under bots/ only inside bots/<its own tag>/ and only once approved.
2823
2915
  {
2824
2916
  const d = declaredAttribution();
@@ -2839,7 +2931,7 @@ function refuseBotMainRecordOne(doc_id, updated_by, tool, options = {}) {
2839
2931
  `Hand it to the hub instead. Nothing was written.`
2840
2932
  , { code: 'EMET-DOC-011' });
2841
2933
  }
2842
- // Registry guard on bots/ too (the reviewer's PR 5 review; the second reader's fix (a), 2026-10-02): with EMET_SOURCE_TAGS
2934
+ // Registry guard on bots/ too (Reviewer's PR 5 review; Tester's fix (a), 2026-10-02): with EMET_SOURCE_TAGS
2843
2935
  // set, a non-bot write under bots/ is refused unless its tag is registered; a missing source counts as
2844
2936
  // unregistered. Without this, a misspelled or unregistered tag is not a bot tag, so the cross-bot guard
2845
2937
  // above never fires and it can write any bot's records or the roster. A listed bot is already fenced to
@@ -2873,11 +2965,11 @@ function refuseBotMainRecordOne(doc_id, updated_by, tool, options = {}) {
2873
2965
  * retire_doc and rename_doc are not bot tools at all (Alex, 2026-10-01 4:27 PM
2874
2966
  * ET, decision 1, as relayed: "retire_doc isn't needed for bots: keep it
2875
2967
  * Alex/hub only and out of every bot profile"; procedural ref 407; stage 1 of the
2876
- * ref 358 startup amendment, admitted by the reviewer 2026-10-02). A profile is not a
2968
+ * ref 358 startup amendment, admitted by Reviewer 2026-10-02). A profile is not a
2877
2969
  * security boundary, so the door refuses them under ANY bot tag, for every
2878
2970
  * doc_id - not only the main records refuseBotMainRecord covers. ref 407(1)
2879
- * covers retire_doc only; rename_doc stays owner-only under procedural ref 409
2880
- * (owner-confirmed 2026-10-02 the recorded time: every other owner-only tool is
2971
+ * covers retire_doc only; rename_doc stays Alex-only under procedural ref 409
2972
+ * (Alex-confirmed 2026-10-02 7:50: every other Alex-only tool is
2881
2973
  * unchanged), and it retires its old id internally, so it is refused too. The tag is the
2882
2974
  * one the door would stamp: the caller's, else EMET_SOURCE_TAG. Hosts and the
2883
2975
  * hub have no bots/<tag>/HANDOFF.md record and are unaffected. Nothing is
@@ -2900,7 +2992,7 @@ function refuseBotRetireRenameOne(tag, tool) {
2900
2992
  throw new ValidationError(
2901
2993
  'source',
2902
2994
  `${tool} is not a bot tool: ${t} is a bot tag, and ` +
2903
- `renaming documents stays owner-only (procedural ref 409)` +
2995
+ `renaming documents stays the owner-only (procedural ref 409)` +
2904
2996
  `. Ask the hub. Nothing was changed.`
2905
2997
  , { code: 'EMET-MEM-020' });
2906
2998
  }
@@ -2927,7 +3019,7 @@ export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint
2927
3019
  }
2928
3020
  const prev = await col.findOne({ doc_id });
2929
3021
  const version = (prev && prev.version ? prev.version : 0) + 1;
2930
- // Compare-and-set for the client-approvals record (the second reader round 3): checked
3022
+ // Compare-and-set for the client-approvals record (Tester round 3): checked
2931
3023
  // here before anything is archived, and again atomically in the update filter.
2932
3024
  const casOn = options && options.approvalsRecord === true && Object.prototype.hasOwnProperty.call(options, 'expectedVersion');
2933
3025
  const casConflict = () => { const e = new ValidationError(`${doc_id} changed under this write (compare-and-set). Nothing was written.`); e.versionConflict = true; return e; };
@@ -2965,9 +3057,9 @@ export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint
2965
3057
  if (!rightsTags(updated_by).every(passes) && !serverProvision && !(isDropDoc(doc_id) && !prev)) {
2966
3058
  throw new ValidationError(`write_doc: ${updated_by || 'no source'} is not a registered source. This session may read, and may write a new drop only. Nothing was written.`, { code: 'EMET-DOC-020' });
2967
3059
  }
3060
+ const docStamp = writerStamp();
2968
3061
  if (isDropDoc(doc_id) && !prev) {
2969
- const { writerStamp } = await import('./persons.js');
2970
- const bucket = dropBucket(writerStamp().client_id, updated_by);
3062
+ const bucket = dropBucket(docStamp.client_id, updated_by);
2971
3063
  const day = nyDay(new Date());
2972
3064
  const same = (await col.find({ doc_id: { $regex: '^drops/' } }).toArray()).filter((d) => (d.drop_bucket || dropBucket(d.client_id, d.updated_by)) === bucket && nyDay(d.updated_at instanceof Date ? d.updated_at : new Date(d.updated_at || 0)) === day);
2973
3065
  if (same.length >= 20) throw new ValidationError(`write_doc: this connected app already wrote 20 drops today. Nothing was written.`, { code: 'EMET-DOC-021' });
@@ -3015,7 +3107,7 @@ export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint
3015
3107
  if (prev && !floorExempt && baseline > 0 && content.length * 2 < baseline) {
3016
3108
  const pct = Math.floor((content.length / baseline) * 100);
3017
3109
  throw new ValidationError(
3018
- `This change would leave ${doc_id} at ${pct}% of its size when this session first touched it. Condensing below half is not done on the EMET server. Nothing was written.`
3110
+ `This change would leave ${doc_id} at ${pct}% of its size when this session first touched it. Condensing below half is not done on the EMET server. Nothing was written. Write the full revision: the whole content in one write_doc, or write_doc_begin, write_doc_append, and write_doc_commit. A condensed or header-only substitute is refused.`
3019
3111
  , { code: 'EMET-DOC-025' });
3020
3112
  }
3021
3113
  // Cross-session floor. The per-session floor is measured from this
@@ -3039,6 +3131,15 @@ export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint
3039
3131
  }
3040
3132
  const sizeSamples = recentSamples.slice();
3041
3133
  if (prev) sizeSamples.push({ size: String(prev.content || '').length, at: prev.updated_at || new Date() });
3134
+ const docDecision = resolvedSourceTag(updated_by);
3135
+ const stampedUpdatedBy = stampedSource(docDecision, updated_by || (isDropDoc(doc_id) ? 'visitor' : (setting('SOURCE_TAG') || null)));
3136
+ const docClaim = guardClaimedTag({
3137
+ transport: currentActor().transport,
3138
+ grant_id: docStamp.grant_id,
3139
+ sourceFrom: docDecision.from,
3140
+ caller: docDecision.tag || updated_by,
3141
+ tool: options && options.edited ? 'patch_doc' : 'write_doc'
3142
+ });
3042
3143
  if (prev) {
3043
3144
  const { _id, size_baselines: _liveBaselines, ...rest } = prev;
3044
3145
  // Retained and marked obsolete (ISO 7.5.3 / 4.2.5): the archived copy
@@ -3069,11 +3170,14 @@ export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint
3069
3170
  doc_id, content, sha256, signature, version, size: content.length, updated_at: now,
3070
3171
  conformance,
3071
3172
  supersedes_version: prev ? prev.version : null,
3072
- updated_by: updated_by || (isDropDoc(doc_id) ? 'visitor' : (setting('SOURCE_TAG') || null)),
3173
+ updated_by: stampedUpdatedBy,
3073
3174
  edit_reason: (options && options.reason) || null,
3074
3175
  edit_origin: (options && options.origin) || null,
3075
- person_id: (await import('./persons.js').then((m) => m.writerStamp())).person_id,
3076
- client_id: (await import('./persons.js').then((m) => m.writerStamp())).client_id,
3176
+ person_id: docStamp.person_id,
3177
+ client_id: docStamp.client_id,
3178
+ grant_id: docStamp.grant_id,
3179
+ door: docStamp.door,
3180
+ ...(docClaim.claimed ? { claimed_tag: true } : {}),
3077
3181
  session_id: sid,
3078
3182
  restored_from_version: (options && options.restore_of) || null,
3079
3183
  size_at_session_start: baseline,
@@ -3094,6 +3198,7 @@ export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint
3094
3198
  writtenRow.key_id = attr.keyId;
3095
3199
  writtenRow.source_basis = 'subkey';
3096
3200
  }
3201
+ if (docDecision.from === 'credential') writtenRow.source_basis = 'credential';
3097
3202
  if (options && options.provision && doc_id === stateDoc()) {
3098
3203
  const ins = await col.updateOne({ doc_id }, { $setOnInsert: writtenRow }, { upsert: true });
3099
3204
  if (ins && ins.upsertedCount === 0) {
@@ -3103,7 +3208,7 @@ export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint
3103
3208
  let res;
3104
3209
  try {
3105
3210
  res = options.expectedVersion == null
3106
- // the second reader delta M1: documents.doc_id has no unique index, so the first
3211
+ // Tester delta M1: documents.doc_id has no unique index, so the first
3107
3212
  // create keys on a deterministic _id; _id is always unique, so a
3108
3213
  // second racing insert matches it (or hits a duplicate key) and loses.
3109
3214
  ? await col.updateOne({ _id: `${APPROVALS_DOC}#current` }, { $setOnInsert: writtenRow }, { upsert: true })
@@ -3123,7 +3228,9 @@ export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint
3123
3228
  return { doc_id, sha256, version, size: content.length, updated_at: now, verified: true,
3124
3229
  signed: signatureIntegrityOf(check, signingKey),
3125
3230
  signature_stored: typeof check?.signature === 'string' && check.signature.length > 0,
3126
- redacted: redaction.hits, conformance };
3231
+ redacted: redaction.hits, conformance,
3232
+ grant_id: docStamp.grant_id,
3233
+ ...(docClaim.warning ? { claimed_tag_warning: docClaim.warning } : {}) };
3127
3234
  } finally { await client.close(); }
3128
3235
  } catch (error) {
3129
3236
  if (error && error.versionConflict) throw error;
@@ -3229,14 +3336,26 @@ export async function retireDoc(doc_id, reason = null, retired_by = null, logger
3229
3336
  }
3230
3337
 
3231
3338
  const now = new Date();
3339
+ const retireStamp = writerStamp();
3340
+ const retireDecision = resolvedSourceTag(retired_by);
3341
+ const retireClaim = guardClaimedTag({
3342
+ transport: currentActor().transport,
3343
+ grant_id: retireStamp.grant_id,
3344
+ sourceFrom: retireDecision.from,
3345
+ caller: retireDecision.tag || retired_by,
3346
+ tool: 'retire_doc'
3347
+ });
3232
3348
  await col.updateOne({ doc_id }, { $set: {
3233
3349
  retired: true,
3234
3350
  retired_at: now,
3235
3351
  retired_by: retired_by || setting('SOURCE_TAG') || null,
3236
3352
  retired_reason: reason || null,
3237
- retired_person_id: (await import('./persons.js').then((m) => m.currentPersonId())) || null,
3238
- retired_client_id: (await import('./persons.js').then((m) => m.currentClientId())) || 'stdio',
3239
- retired_session_id: (options && options.session_id) || null
3353
+ retired_person_id: retireStamp.person_id,
3354
+ retired_client_id: retireStamp.client_id || 'stdio',
3355
+ retired_grant_id: retireStamp.grant_id,
3356
+ retired_door: retireStamp.door,
3357
+ retired_session_id: (options && options.session_id) || null,
3358
+ ...(retireClaim.claimed ? { claimed_tag: true } : {})
3240
3359
  } });
3241
3360
 
3242
3361
  // aleph: the mark is not set because the call returned. Content and
@@ -3269,6 +3388,8 @@ export async function retireDoc(doc_id, reason = null, retired_by = null, logger
3269
3388
  return { doc_id, retired: true, verified: true, retired_at: now, conformance,
3270
3389
  retired_reason: reason || null, version: check.version,
3271
3390
  sha256: check.sha256, content_unchanged: true,
3391
+ grant_id: retireStamp.grant_id,
3392
+ ...(retireClaim.warning ? { claimed_tag_warning: retireClaim.warning } : {}),
3272
3393
  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.' };
3273
3394
  } finally { await client.close(); }
3274
3395
  } catch (error) {
@@ -3479,11 +3600,21 @@ export async function acceptNonconformance(doc_id, reason, accepted_by = null, l
3479
3600
  `Its verdict is "${current ? current.verdict : 'not yet checked'}".`
3480
3601
  , { code: 'EMET-DOC-050' });
3481
3602
  }
3482
- const { currentPersonId, currentClientId } = await import('./persons.js');
3603
+ const acceptDecision = resolvedSourceTag(accepted_by);
3604
+ const acceptClaim = guardClaimedTag({
3605
+ transport: currentActor().transport,
3606
+ grant_id: writerStamp().grant_id,
3607
+ sourceFrom: acceptDecision.from,
3608
+ caller: acceptDecision.tag || accepted_by,
3609
+ tool: 'accept_nonconformance'
3610
+ });
3611
+ const stamp = writerStamp();
3483
3612
  const accepted = buildAcceptance({
3484
3613
  reason, by: accepted_by || setting('SOURCE_TAG') || null, version: doc.version,
3485
- person_id: currentPersonId() || null,
3486
- client_id: currentClientId() || 'stdio',
3614
+ person_id: stamp.person_id,
3615
+ client_id: stamp.client_id || 'stdio',
3616
+ grant_id: stamp.grant_id,
3617
+ door: stamp.door,
3487
3618
  session_id: (options && options.session_id) || null
3488
3619
  });
3489
3620
  await col.updateOne({ doc_id }, { $set: { 'conformance.accepted': accepted } });
@@ -3496,6 +3627,8 @@ export async function acceptNonconformance(doc_id, reason, accepted_by = null, l
3496
3627
  return {
3497
3628
  doc_id, verified: true, version: doc.version, covers_version: doc.version,
3498
3629
  accepted, failures_accepted: current.failures || [],
3630
+ grant_id: stamp.grant_id,
3631
+ ...(acceptClaim.warning ? { claimed_tag_warning: acceptClaim.warning } : {}),
3499
3632
  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.'
3500
3633
  };
3501
3634
  } finally { await client.close(); }
@@ -3592,7 +3725,7 @@ export async function patchDoc(doc_id, old_str, new_str, updated_by = null, expe
3592
3725
  }
3593
3726
  }
3594
3727
 
3595
- // Restored 2026-09-19: both constants were dropped in an earlier commit while the function
3728
+ // Restored 2026-09-19: both constants were dropped in thatcommit while the function
3596
3729
  // kept referencing them, which made every semantic_recall call throw
3597
3730
  // "SEMANTIC_RECALL_LAYERS is not defined".
3598
3731
  const SEMANTIC_RECALL_LAYERS = ['episodic', 'semantic', 'procedural', 'meta', 'identity', 'working'];
@@ -3828,6 +3961,15 @@ export async function memberAccessCreate(dbManager, { display_name, days, source
3828
3961
  await dbManager.getConnection('working');
3829
3962
  const { createMemberAccess, MEMBER_ACCESS_FROZEN, MEMBER_ACCESS_FROZEN_REASON } = await import('./invites.js');
3830
3963
  if (MEMBER_ACCESS_FROZEN) throw new ValidationError(MEMBER_ACCESS_FROZEN_REASON, { code: 'EMET-AUTH-034' });
3964
+ const { currentActor } = await import('./persons.js');
3965
+ const { actorIsCos } = await import('./attribution.js');
3966
+ const { isOwlIdentity } = await import('./owl.js');
3967
+ const { isMasterBlasterActor } = await import('./writer-approval.js');
3968
+ const who = currentActor();
3969
+ const aiWriter = isOwlIdentity(who) || (who.transport === 'http' && (isMasterBlasterActor(who) || actorIsCos(who) || (who.sourceTag && isBotTag(who.sourceTag))));
3970
+ if (aiWriter) {
3971
+ throw new ValidationError('An AI cannot grant a writer. Alex decides on /owner/chooser with an owner session. Nothing was created.', { code: 'EMET-AUTH-043' });
3972
+ }
3831
3973
  const { registeredSourceTags } = await import('./setup.js');
3832
3974
  const actor = await codeCreator(dbManager);
3833
3975
  if (!actor) throw new ValidationError('Only the owner can create EMET Member Access', { code: 'EMET-AUTH-037' });
@@ -3862,12 +4004,13 @@ const TOOL_DEFINITIONS = [
3862
4004
  },
3863
4005
  {
3864
4006
  name: "emet_status",
3865
- description: "Diagnostic in one call (replaces emet_setup_status, get_status and emet_verify_connection, 2026-09-27). Reports environment, database, collections, vector index, whether identity and user documents exist, and per-layer counts and health. Pass probe: true to also prove the write path - connect, write a probe document, read the same value back, remove it; a read alone cannot reveal a broken write path. Prefer emet_initialize for a normal session start.",
4007
+ description: "Diagnostic in one call (replaces emet_setup_status, get_status and emet_verify_connection, 2026-09-27). Reports environment, database, collections, vector index, whether identity and user documents exist, and per-layer counts and health. Pass probe: true to also prove the write path - connect, write a probe document, read the same value back, remove it; a read alone cannot reveal a broken write path. Pass session_id to read that session: `session.state` is open, closed, or absent, or unreadable when the session row cannot be read (the rest of the status still returns, and the asked id is not echoed). A part id is read as its base session. Prefer emet_initialize for a normal session start. Also reports checkpoint on every call: due when an open session's last verbatim save, or the open itself when no transcript is saved, is at least 24 hours old. A session covered by a current conforming records/ disposition (templates/SESSIONDISPOSITION.md) is not listed as checkpoint-due. A row that names an inserted_id dispositions that transcript only and does not close the session. The disposition is not a receipt. Save that verbatim text with emet_transcript_append or save_transcript, under the open session or the daily YYYY-MM-DD_chat-daily session. emet_session_close cites the saved parts. A store that cannot be read sets checkpoint.unread and does not claim the save is current.",
3866
4008
  inputSchema: {
3867
4009
  type: "object",
3868
4010
  properties: {
3869
4011
  probe: { type: "boolean", description: "Also write and read back a probe document (default false). Use after a deploy or a configuration change." },
3870
- source: { type: "string", description: "Your own source tag. The status then reports the tag your writes will carry and its approval state." }
4012
+ source: { type: "string", description: "Your own source tag. The status then reports the tag your writes will carry and its approval state." },
4013
+ session_id: { type: "string", description: "A transcript session id from emet_session_open, or one of its part ids. The result's session.state is open, closed, or absent, or unreadable when that session cannot be read." }
3871
4014
  }
3872
4015
  }
3873
4016
  },
@@ -4163,11 +4306,11 @@ const TOOL_DEFINITIONS = [
4163
4306
  },
4164
4307
  {
4165
4308
  name: "emet_session_open",
4166
- description: "Open a transcript session. Returns session_id, dated in the configured local time zone (EMET_TIMEZONE, default America/New_York). 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.",
4309
+ 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.",
4167
4310
  inputSchema: {
4168
4311
  type: "object",
4169
4312
  properties: {
4170
- slug: { type: "string", description: "Short name for the session, e.g. grok-init" },
4313
+ 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." },
4171
4314
  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." }
4172
4315
  }
4173
4316
  }
@@ -4221,6 +4364,51 @@ const TOOL_DEFINITIONS = [
4221
4364
  updated_by: { type: "string", description: "Alias of `source` (the older name, kept one release). Prefer `source`." }
4222
4365
  }, required: ["doc_id", "content"] }
4223
4366
  },
4367
+ {
4368
+ name: "write_doc_begin",
4369
+ 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.",
4370
+ inputSchema: { type: "object", properties: {
4371
+ doc_id: { type: "string" },
4372
+ 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." },
4373
+ reason: { type: "string", description: "Required on a record revision (at least 10 characters). Stored on the stage and passed to write_doc at commit." },
4374
+ source: { type: "string", description: "Source tag - which host produced this write. One name on every write since 2026-09-27." },
4375
+ updated_by: { type: "string", description: "Alias of `source` (the older name, kept one release). Prefer `source`." }
4376
+ }, required: ["doc_id"] }
4377
+ },
4378
+ {
4379
+ name: "write_doc_append",
4380
+ description: "Append the next ordered chunk of an open stage. part starts at 1 and increases by one. The same part with the same bytes is a no-op. A different byte string, a skipped part, or a chunk over 16000 characters is refused and the current document is unchanged.",
4381
+ inputSchema: { type: "object", properties: {
4382
+ stage_id: { type: "string", description: "The stage_id write_doc_begin returned." },
4383
+ part: { type: "number", description: "The 1-based part index. The next part is next_part from the previous call. A whole number sent as text is accepted." },
4384
+ chunk: { type: "string", description: "The next slice of the document, at most 16000 characters. Chunks are concatenated in order at commit." },
4385
+ source: { type: "string", description: "Source tag. Must be the same source the stage was begun with." },
4386
+ updated_by: { type: "string", description: "Alias of `source`. Prefer `source`." }
4387
+ }, required: ["stage_id", "part", "chunk"] }
4388
+ },
4389
+ {
4390
+ name: "write_doc_commit",
4391
+ 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.",
4392
+ inputSchema: { type: "object", properties: {
4393
+ stage_id: { type: "string" },
4394
+ doc_id: { type: "string", description: "The same document id the stage was begun for." },
4395
+ sha256: { type: "string", description: "Lowercase hex sha256 of the exact assembled text." },
4396
+ part_count: { type: "number", description: "How many parts were appended. Commit is refused if the stage holds a different number." },
4397
+ supersedes: { type: "number", description: "Optional. When omitted, the value stored at begin is used. A different number is refused." },
4398
+ reason: { type: "string", description: "Optional. When omitted, the reason stored at begin is used. A different reason is refused." },
4399
+ source: { type: "string", description: "Source tag. Must match the stage." },
4400
+ updated_by: { type: "string", description: "Alias of `source`. Prefer `source`." }
4401
+ }, required: ["stage_id", "doc_id", "sha256", "part_count"] }
4402
+ },
4403
+ {
4404
+ name: "write_doc_abort",
4405
+ description: "Drop an open stage. The current document is unchanged. Aborting a stage that is already aborted reports that abort and writes nothing.",
4406
+ inputSchema: { type: "object", properties: {
4407
+ stage_id: { type: "string" },
4408
+ source: { type: "string", description: "Source tag. Must match the stage." },
4409
+ updated_by: { type: "string", description: "Alias of `source`. Prefer `source`." }
4410
+ }, required: ["stage_id"] }
4411
+ },
4224
4412
  {
4225
4413
  name: "list_docs",
4226
4414
  description: "List continuity documents (metadata only; optional doc_id prefix filter, e.g. 'threads/'). Current documents come first. Retired documents stay in the list, marked with retired_at and, when a rename replaced them, what replaced them.",
@@ -4313,7 +4501,7 @@ const TOOL_DEFINITIONS = [
4313
4501
  name: "emet_page",
4314
4502
  description: "Read one compiled topic page for an area slug (areas/<slug>.md). A page is a view of current records. It is not a record: this tool writes nothing, stores nothing, and the result is never written back and is not returned by recall. Every displayed line cites its source as [mem:<id> · <layer> · <client> · <YYYY-MM-DD>] or [doc:<doc_id>@v<version>]. A line with no source is dropped. Superseded and retired records stay out of the current sections; pass include_history true to show them under History only. A line is marked stale when its source has not been confirmed or revised within the area's staleness window (default 30 days; the area document may set its own). Owner only. Computed on every call, so cache_hit is false.",
4315
4503
  inputSchema: { type: "object", properties: {
4316
- area: { type: "string", description: "Area slug, for example health. The selector is the current areas/<slug>.md document." },
4504
+ area: { type: "string", description: "Area slug, for example finances. The selector is the current areas/<slug>.md document." },
4317
4505
  as_of: { type: "string", description: "Optional ISO date or unix seconds. The page shows records that were current at that moment. A document line cites the revision in force then, from documents_history. A revision that was never archived is absent. A superseded or retired record with no end date is still shown in this past view, labelled \"end date unknown\", and is not a current line. The area selector is the current area document." },
4318
4506
  include_history: { type: "boolean", description: "When true, superseded and retired records appear under History, labelled as not current. Default false." }
4319
4507
  }, required: ["area"] }
@@ -4366,15 +4554,19 @@ const TOOL_DEFINITIONS = [
4366
4554
  },
4367
4555
  {
4368
4556
  name: "emet_client_approve",
4369
- description: "Approve or deny a new client (a bot, or a single-instance AI such as Claude or ChatGPT) that EMET flagged on its first write. A new client is read-limited until approved. Only the owner, or the chief-of-staff bot named by EMET_COS_TAG, may decide. Pending clients are listed in emet_initialize and emet_status as client_approvals.",
4557
+ description: "Approve or deny a pending client tag, or prepare a new writer. decision prepare drafts a writer request: client, claimed tag, door (member or guest), reason, and correlation_id. Master Hub prepares that draft. The server validates it. Validation is a check and is not approval. Alex decides a new writer on /owner/chooser with the owner session. No AI grants a writer, including Master Hub and the retired owl account. The owner login may still approve or deny a pending client tag. Pending client tags are listed in emet_initialize and emet_status as client_approvals.",
4370
4558
  inputSchema: {
4371
4559
  type: "object",
4372
4560
  properties: {
4373
- tag: { type: "string", description: "The pending client's tag, as listed in client_approvals.pending" },
4374
- decision: { type: "string", enum: ["approve", "deny"] },
4375
- reason: { type: "string", description: "Optional note kept with the decision" },
4561
+ tag: { type: "string", description: "The pending client's tag, as listed in client_approvals.pending. For decision prepare, this is the claimed tag when claimed_tag is omitted." },
4562
+ decision: { type: "string", enum: ["approve", "deny", "prepare"] },
4563
+ reason: { type: "string", description: "Note kept with the decision, or the reason on a prepared writer request." },
4376
4564
  as: { type: "string", enum: ["rename", "add"], description: "Required when the client_id already has approved tags: add keeps them all (several bots on one shared client); rename retires one" },
4377
- from: { type: "string", description: "With as=rename on a client that has several approved tags: the tag being replaced" }
4565
+ from: { type: "string", description: "With as=rename on a client that has several approved tags: the tag being replaced" },
4566
+ client: { type: "string", description: "For decision prepare: the client id the writer request names." },
4567
+ claimed_tag: { type: "string", description: "For decision prepare: the tag the writer would be known by." },
4568
+ door: { type: "string", enum: ["member", "guest"], description: "For decision prepare: member is a writer. Guest is not a writer." },
4569
+ correlation_id: { type: "string", description: "For decision prepare: 16 lowercase hex characters. The same id again returns the retained request." }
4378
4570
  },
4379
4571
  required: ["tag", "decision"]
4380
4572
  }
@@ -4408,7 +4600,7 @@ const TOOL_DEFINITIONS = [
4408
4600
  },
4409
4601
  {
4410
4602
  name: "emet_session_close",
4411
- 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. Never tell the user their session is saved unless this returns state 'complete'.",
4603
+ 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. Never tell the user their session is saved unless this returns state 'complete'.",
4412
4604
  inputSchema: {
4413
4605
  type: "object",
4414
4606
  properties: {