@dreamforgestudiollc/emet 0.2.6 → 0.3.0

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 (56) hide show
  1. package/.env.example +10 -0
  2. package/CHANGELOG.md +18 -1
  3. package/README.md +31 -7
  4. package/areas/emet.md +18 -0
  5. package/areas/garden.md +18 -0
  6. package/areas/health.md +18 -0
  7. package/areas/home.md +18 -0
  8. package/areas/learning.md +18 -0
  9. package/areas/state.md +18 -0
  10. package/docs/DEPLOY.md +32 -1
  11. package/docs/ERROR-CODES-SPEC.md +43 -0
  12. package/docs/ERROR-CODES.md +332 -0
  13. package/docs/GUIDED-SETUP.md +16 -0
  14. package/docs/PERMISSIONS.md +8 -5
  15. package/docs/ROADMAP.md +10 -10
  16. package/docs/SETUP.md +115 -12
  17. package/package.json +3 -2
  18. package/server.json +7 -3
  19. package/src/aleph.js +16 -10
  20. package/src/annotations.js +8 -3
  21. package/src/atlas-role.js +8 -3
  22. package/src/attribution.js +12 -12
  23. package/src/conformance.js +6 -4
  24. package/src/database.js +28 -12
  25. package/src/dispatch.js +33 -16
  26. package/src/error-codes.js +394 -0
  27. package/src/error-log.js +273 -0
  28. package/src/error-report.js +245 -0
  29. package/src/floor.js +6 -4
  30. package/src/gaps.js +2 -2
  31. package/src/gem-check.js +27 -26
  32. package/src/http-remote.js +2 -1
  33. package/src/index.js +1 -0
  34. package/src/invites.js +6 -5
  35. package/src/layers.js +8 -7
  36. package/src/mongo-connect.js +5 -0
  37. package/src/oauth-provider.js +28 -27
  38. package/src/pages.js +806 -0
  39. package/src/persons.js +2 -1
  40. package/src/provenance.js +10 -10
  41. package/src/rune-dispatch.js +10 -10
  42. package/src/session-graph.js +16 -15
  43. package/src/session.js +1 -1
  44. package/src/setup.js +21 -17
  45. package/src/startup-pages.js +3 -2
  46. package/src/startup-payload.js +3 -2
  47. package/src/subkey-store.js +3 -2
  48. package/src/tools.js +254 -177
  49. package/src/validation.js +61 -52
  50. package/src/version.js +1 -1
  51. package/templates/AREA.md +35 -0
  52. package/templates/INDEX.md +7 -6
  53. package/templates/PROCEDURE.md +1 -1
  54. package/templates/SEED.md +2 -2
  55. package/templates/STAGING.md +1 -1
  56. package/templates/THREAD.md +1 -1
package/src/tools.js CHANGED
@@ -12,6 +12,8 @@
12
12
  */
13
13
 
14
14
  import { connectMongo } from './mongo-connect.js';
15
+ import { newCorrelationId, EMET_INT_001, EMET_CODE_RE, lookupEmetCode } from './error-codes.js';
16
+ import { recordError } from './error-log.js';
15
17
  import { resolveModulePath } from './module-path.js';
16
18
  import { replacedByOf } from './setup.js';
17
19
  import { currentActor, rawActor, writerStamp, boundSourceTag, declaredAttribution, LOCAL_SUBJECT } from './persons.js';
@@ -21,7 +23,7 @@ import { sealAttestation, frozenAttestation } from './rune-dispatch.js';
21
23
  /** Approvals record io for attribution.js (server-kept doc, written as emet-server). */
22
24
  export const approvalsDeps = {
23
25
  readDoc: (id) => readDoc(id),
24
- // Compare-and-set on the stored version (the reviewer 3). mutateApprovals serializes
26
+ // Compare-and-set on the stored version (the second reader 3). mutateApprovals serializes
25
27
  // writers in this process; this check catches a writer elsewhere.
26
28
  writeDoc: async (id, content, expectedVersion) => {
27
29
  // Atomic across processes: writeDoc filters the update on { doc_id, version: expected }.
@@ -129,6 +131,7 @@ export class RateLimitError extends Error {
129
131
  this.name = 'RateLimitError';
130
132
  this.retryAfterMs = retryAfterMs;
131
133
  this.statusCode = 429;
134
+ this.emetCode = 'EMET-RATE-001';
132
135
  }
133
136
  }
134
137
 
@@ -361,6 +364,18 @@ export function handleError(error, toolName, logger = null) {
361
364
  }
362
365
 
363
366
  errorResponse.error.tool = toolName;
367
+ const stamped = error && typeof error.emetCode === 'string' && EMET_CODE_RE.test(error.emetCode) && lookupEmetCode(error.emetCode)
368
+ ? error.emetCode
369
+ : EMET_INT_001;
370
+ const correlationId = newCorrelationId();
371
+ errorResponse.error.emet_code = stamped;
372
+ errorResponse.error.correlation_id = correlationId;
373
+ void recordError({
374
+ emet_code: stamped,
375
+ class_code: errorResponse.error.code,
376
+ tool: toolName,
377
+ correlation_id: correlationId
378
+ });
364
379
 
365
380
  // Read at call time. Never attach a stack on the HTTP server.
366
381
  if (process.env.DEBUG === 'true' && error?.stack && currentActor().transport !== 'http') {
@@ -514,7 +529,7 @@ export async function saveMemory(dbManager, content, layer = null, metadata = {}
514
529
  {
515
530
  const { checkLessonFields } = await import('./lessons-to-checks.js');
516
531
  const lessonProblem = checkLessonFields(targetLayer, incoming);
517
- if (lessonProblem) throw new ValidationError('metadata.lesson', `${lessonProblem} Nothing was written.`);
532
+ if (lessonProblem) throw new ValidationError('metadata.lesson', `${lessonProblem} Nothing was written.`, { code: 'EMET-MEM-005' });
518
533
  }
519
534
  if (!validatedLayer) {
520
535
  warnings.push(
@@ -608,8 +623,8 @@ export async function saveMemory(dbManager, content, layer = null, metadata = {}
608
623
  let provenanceStamped = false;
609
624
  if (!provenance && options && options.session_id !== undefined && options.session_id !== null) {
610
625
  const sid = typeof options.session_id === 'string' ? options.session_id.trim() : '';
611
- if (!sid || sid.length > 200) throw new ValidationError('session_id', 'must be the non-empty transcript session id from emet_session_open. Nothing was written.');
612
- if (typeof dbManager.transcriptPosition !== 'function') throw new ValidationError('session_id', 'this store cannot read transcript positions, so the pointer cannot be stamped - pass derived_from instead. Nothing was written.');
626
+ if (!sid || sid.length > 200) throw new ValidationError('session_id', 'must be the non-empty transcript session id from emet_session_open. Nothing was written.', { code: 'EMET-MEM-006' });
627
+ if (typeof dbManager.transcriptPosition !== 'function') throw new ValidationError('session_id', 'this store cannot read transcript positions, so the pointer cannot be stamped - pass derived_from instead. Nothing was written.', { code: 'EMET-MEM-007' });
613
628
  const pos = await dbManager.transcriptPosition(sid);
614
629
  const ex = pos.highest + 1;
615
630
  provenance = validateProvenance({ session_id: pos.base, exchange_start: ex, exchange_end: ex });
@@ -620,7 +635,7 @@ export async function saveMemory(dbManager, content, layer = null, metadata = {}
620
635
  throw new ValidationError('derived_from',
621
636
  `${targetLayer} entries must carry their source. Pass session_id (your transcript session from ` +
622
637
  `emet_session_open - the server stamps the exchange), or derived_from {session_id, exchange_start, ` +
623
- `exchange_end}, or derived_from {entries: [ids]} for an entry consolidated from other entries. Nothing was written.`);
638
+ `exchange_end}, or derived_from {entries: [ids]} for an entry consolidated from other entries. Nothing was written.`, { code: 'EMET-MEM-008' });
624
639
  }
625
640
  if (!provenance && provenancePolicy === 'encouraged') {
626
641
  validatedMetadata.provenance_missing = true;
@@ -760,7 +775,7 @@ export async function saveMemory(dbManager, content, layer = null, metadata = {}
760
775
  if (validatedMetadata.corrects !== undefined && validatedMetadata.corrects !== null) {
761
776
  const parent = await dbManager.readMemory(targetLayer, validatedMetadata.corrects);
762
777
  if (!parent) {
763
- throw new ValidationError('corrects', `No entry with id ${validatedMetadata.corrects} in layer '${targetLayer}' - a correction names an entry in its own layer. Nothing was written.`);
778
+ throw new ValidationError('corrects', `No entry with id ${validatedMetadata.corrects} in layer '${targetLayer}' - a correction names an entry in its own layer. Nothing was written.`, { code: 'EMET-MEM-009' });
764
779
  }
765
780
  }
766
781
 
@@ -777,7 +792,7 @@ export async function saveMemory(dbManager, content, layer = null, metadata = {}
777
792
  const correction = (validatedMetadata.corrects !== undefined && validatedMetadata.corrects !== null)
778
793
  ? await markCorrectedBy(dbManager, targetLayer, validatedMetadata.corrects, memoryId)
779
794
  : null;
780
- // the reviewer N4: a correction whose parent could not be marked is still saved,
795
+ // the second reader N4: a correction whose parent could not be marked is still saved,
781
796
  // but the caller is told in words, not only by a boolean.
782
797
  if (correction && correction.marked !== true) {
783
798
  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`);
@@ -879,7 +894,7 @@ export async function saveMemory(dbManager, content, layer = null, metadata = {}
879
894
  'Failed to save memory',
880
895
  'save_memory',
881
896
  { layer: layer || 'auto' }
882
- );
897
+ , { code: 'EMET-DB-013' });
883
898
  }
884
899
  }
885
900
 
@@ -970,7 +985,7 @@ export async function resolveSupersessionChain(read, entry, maxHops = 50) {
970
985
  }
971
986
 
972
987
  /**
973
- * Option A correction back-pointer (Alex, 2026-10-02, procedural ref 405 item 4; the tester's sketch in his
988
+ * Option A correction back-pointer (Alex, 2026-10-02, procedural ref 405 item 4; the reviewer's sketch in his
974
989
  * second read of episodic ref 604). Episodic entries are immutable events, so a PARTIAL correction cannot
975
990
  * supersede its parent: supersession would put an end date on the whole parent and present every item
976
991
  * in it as replaced. Instead the new entry carries metadata.corrects = <parent id>, and the parent is MARKED:
@@ -984,7 +999,7 @@ export async function resolveSupersessionChain(read, entry, maxHops = 50) {
984
999
  * corrected_by mark): the new metadata digest and, when a signing key is set
985
1000
  * and the row's existing signature verifies against its metadata before the
986
1001
  * marks (aleph.js signatureCoversPriorMetadata), a fresh signature over the
987
- * same content digest and the new metadata digest (2026-10-02, the tester's
1002
+ * same content digest and the new metadata digest (2026-10-02, the reviewer's
988
1003
  * finding: the marks left signed:false behind). With no key, or a signature
989
1004
  * that does not verify, the signature is left exactly as it is: never re-signed
990
1005
  * blindly, so a row changed outside the sanctioned path keeps reading
@@ -1004,7 +1019,7 @@ export async function markCorrectedBy(dbManager, layer, parentId, childId) {
1004
1019
  const parent = await col.findOne({ id: parentId });
1005
1020
  if (!parent) return { parent_id: parentId, marked: false };
1006
1021
  const cid = Number(childId);
1007
- // Race-safe (the reviewer N3 / the tester, 2026-10-02): the id is ADDED atomically
1022
+ // Race-safe (the second reader N3 / the reviewer, 2026-10-02): the id is ADDED atomically
1008
1023
  // ($addToSet on the column and on the metadata copy), never written back
1009
1024
  // from a stale read, so two simultaneous corrections of one parent both
1010
1025
  // land. A legacy string-metadata row falls back to read-modify-write.
@@ -1020,7 +1035,7 @@ export async function markCorrectedBy(dbManager, layer, parentId, childId) {
1020
1035
  // Re-attest from what is actually stored. The digest is set only if the
1021
1036
  // stored metadata is still exactly the metadata it was computed from: the
1022
1037
  // compare-and-set filter is the WHOLE metadata value, not only corrected_by
1023
- // (the tester, 2026-10-02), so a concurrent change to any metadata field in
1038
+ // (the reviewer, 2026-10-02), so a concurrent change to any metadata field in
1024
1039
  // between (another mark, a superseded_by, anything) makes the filter miss,
1025
1040
  // and the loop re-reads and re-digests. The last re-attest therefore always
1026
1041
  // covers what is stored. The value compared is the one just read back, so
@@ -1054,29 +1069,29 @@ export async function reviseMemory(dbManager, layer, target_id, content, metadat
1054
1069
  // Which layers may be revised is the charter's call (layers.js), not a
1055
1070
  // string comparison here. Today only episodic says false.
1056
1071
  if (policyFor(validatedLayer).revisable === false) {
1057
- throw new ValidationError('layer', 'Episodic revision is prohibited - events are immutable history. Save a new episodic entry instead.');
1072
+ throw new ValidationError('layer', 'Episodic revision is prohibited - events are immutable history. Save a new episodic entry instead.', { code: 'EMET-MEM-010' });
1058
1073
  }
1059
1074
  const targetId = Number(target_id);
1060
1075
  if (!Number.isFinite(targetId) || !Number.isInteger(targetId) || targetId <= 0) {
1061
- throw new ValidationError('target_id', 'target_id must be a positive integer');
1076
+ throw new ValidationError('target_id', 'target_id must be a positive integer', { code: 'EMET-MEM-011' });
1062
1077
  }
1063
1078
  const validatedContent = validateContent(content);
1064
1079
  // A7: metadata is validated exactly ONCE, inside saveMemory, with
1065
1080
  // `supersedes` already present as a first-class field. Validating here and
1066
1081
  // again there is what used to relocate it under custom on the second pass.
1067
1082
  if (metadata !== null && metadata !== undefined && !isPlainObject(metadata)) {
1068
- throw new ValidationError('metadata', 'Metadata must be an object', typeof metadata);
1083
+ throw new ValidationError('metadata', 'Metadata must be an object', typeof metadata, { code: 'EMET-VAL-018' });
1069
1084
  }
1070
1085
  await dbManager.getConnection(validatedLayer);
1071
1086
  const col = dbManager.collectionFor(validatedLayer);
1072
1087
 
1073
1088
  const target = await col.findOne({ id: targetId });
1074
1089
  if (!target) {
1075
- throw new ValidationError('target_id', `No entry with id ${targetId} in layer '${validatedLayer}'`);
1090
+ throw new ValidationError('target_id', `No entry with id ${targetId} in layer '${validatedLayer}'`, { code: 'EMET-MEM-012' });
1076
1091
  }
1077
1092
  const targetMd = parseMetadata(target.metadata);
1078
1093
  if (isMemorySuperseded(targetMd)) {
1079
- throw new ValidationError('target_id', `Entry ${targetId} is already superseded by ${targetMd.superseded_by} - revise the CURRENT entry, not the archived one`);
1094
+ throw new ValidationError('target_id', `Entry ${targetId} is already superseded by ${targetMd.superseded_by} - revise the CURRENT entry, not the archived one`, { code: 'EMET-MEM-013' });
1080
1095
  }
1081
1096
  // 2026-09-29 (procedural ref 398): a revision with no source of its own cites
1082
1097
  // the entry it revises, so revising a semantic or procedural entry is never
@@ -1141,7 +1156,7 @@ export async function reviseMemory(dbManager, layer, target_id, content, metadat
1141
1156
  };
1142
1157
  } catch (error) {
1143
1158
  if (error instanceof ValidationError || error instanceof EmetError) throw error;
1144
- throw new DatabaseError(`Failed to revise memory: ${error.message}`, 'revise_memory');
1159
+ throw new DatabaseError(`Failed to revise memory: ${error.message}`, 'revise_memory', { code: 'EMET-DB-014' });
1145
1160
  }
1146
1161
  }
1147
1162
 
@@ -1389,19 +1404,19 @@ export async function recallMemories(dbManager, query, layer = null, limit = 10,
1389
1404
 
1390
1405
  try {
1391
1406
  if (query === null || query === undefined || (typeof query === 'string' && query.trim() === '')) {
1392
- throw new ValidationError('query', 'Query is required');
1407
+ throw new ValidationError('query', 'Query is required', { code: 'EMET-VAL-005' });
1393
1408
  }
1394
1409
  if (typeof query !== 'string') {
1395
- throw new ValidationError('query', 'Query must be a string');
1410
+ throw new ValidationError('query', 'Query must be a string', { code: 'EMET-VAL-006' });
1396
1411
  }
1397
1412
  if (query.length > CONTENT_LIMITS.MAX_QUERY_LENGTH) {
1398
- throw new ValidationError('query', `Query exceeds maximum length of ${CONTENT_LIMITS.MAX_QUERY_LENGTH} characters`);
1413
+ throw new ValidationError('query', `Query exceeds maximum length of ${CONTENT_LIMITS.MAX_QUERY_LENGTH} characters`, { code: 'EMET-VAL-008' });
1399
1414
  }
1400
1415
  const validatedQuery = query.trim();
1401
1416
  const validatedLayer = layer ? validateLayer(layer) : null;
1402
1417
  const validatedLimit = validateLimit(limit);
1403
1418
  if (options && options.order != null && options.order !== 'latest') {
1404
- throw new ValidationError('order', "order must be 'latest' when it is set");
1419
+ throw new ValidationError('order', "order must be 'latest' when it is set", { code: 'EMET-MEM-014' });
1405
1420
  }
1406
1421
 
1407
1422
  logger?.debug('Recalling memories', {
@@ -1517,7 +1532,7 @@ export async function recallMemories(dbManager, query, layer = null, limit = 10,
1517
1532
  'Failed to recall memories',
1518
1533
  'recall_memories',
1519
1534
  { layer: layer || 'all' }
1520
- );
1535
+ , { code: 'EMET-DB-015' });
1521
1536
  }
1522
1537
  }
1523
1538
 
@@ -1572,7 +1587,7 @@ export async function queryLayer(dbManager, layer, options = {}, logger = null,
1572
1587
  const searchTerm = validatedOptions.params[0];
1573
1588
  if (typeof searchTerm === 'string') {
1574
1589
  if (searchTerm.length > CONTENT_LIMITS.MAX_QUERY_LENGTH) {
1575
- throw new ValidationError('params[0]', `Search term exceeds maximum length of ${CONTENT_LIMITS.MAX_QUERY_LENGTH}`);
1590
+ throw new ValidationError('params[0]', `Search term exceeds maximum length of ${CONTENT_LIMITS.MAX_QUERY_LENGTH}`, { code: 'EMET-MEM-015' });
1576
1591
  }
1577
1592
  filter = { $or: [{ content: containsRegex(searchTerm) }, { context: containsRegex(searchTerm) }] };
1578
1593
  }
@@ -1694,7 +1709,7 @@ export async function queryLayer(dbManager, layer, options = {}, logger = null,
1694
1709
  'Failed to query layer',
1695
1710
  'query_layer',
1696
1711
  { layer: layer || 'unknown' }
1697
- );
1712
+ , { code: 'EMET-DB-016' });
1698
1713
  }
1699
1714
  }
1700
1715
 
@@ -1743,7 +1758,7 @@ export async function getStatus(dbManager, logger = null) {
1743
1758
  throw new DatabaseError(
1744
1759
  'Failed to get system status',
1745
1760
  'emet_status'
1746
- );
1761
+ , { code: 'EMET-DB-017' });
1747
1762
  }
1748
1763
  }
1749
1764
 
@@ -1766,14 +1781,14 @@ export async function queryTranscripts(timestamp_start, timestamp_end, session_i
1766
1781
  const startTime = Date.now();
1767
1782
  try {
1768
1783
  if (typeof timestamp_start !== 'number' || typeof timestamp_end !== 'number')
1769
- throw new ValidationError('timestamp_start and timestamp_end must be numbers (Unix timestamps)');
1784
+ throw new ValidationError('timestamp_start and timestamp_end must be numbers (Unix timestamps)', { code: 'EMET-SESS-002' });
1770
1785
  if (timestamp_start >= timestamp_end)
1771
- throw new ValidationError('timestamp_start must be less than timestamp_end');
1786
+ throw new ValidationError('timestamp_start must be less than timestamp_end', { code: 'EMET-SESS-003' });
1772
1787
  // Security audit 2026-09-29: session_id reached the query unchecked, so an
1773
1788
  // object such as {"$ne": null} was an operator, not an id. Every other
1774
1789
  // doc_id / session_id door already refused a non-string.
1775
1790
  if (session_id !== null && session_id !== undefined && typeof session_id !== 'string')
1776
- throw new ValidationError('session_id', 'must be a string');
1791
+ throw new ValidationError('session_id', 'must be a string', { code: 'EMET-SESS-004' });
1777
1792
  const effectiveLimit = Math.min(Math.max(1, limit || 50), 500);
1778
1793
  const client = await connectMongo(MONGODB_URI, { serverSelectionTimeoutMS: 5000, maxPoolSize: 10 });
1779
1794
  const db = client.db(MONGODB_DB);
@@ -1807,7 +1822,7 @@ export async function queryTranscripts(timestamp_start, timestamp_end, session_i
1807
1822
  };
1808
1823
  } catch (error) {
1809
1824
  if (error instanceof ValidationError || error instanceof EmetError) throw error;
1810
- throw new DatabaseError(`Failed to query transcripts: ${error.message}`, 'query_transcripts');
1825
+ throw new DatabaseError(`Failed to query transcripts: ${error.message}`, 'query_transcripts', { code: 'EMET-DB-018' });
1811
1826
  }
1812
1827
  }
1813
1828
 
@@ -1874,12 +1889,12 @@ export function assertExchangeBudget(parts) {
1874
1889
  for (const part of parts) {
1875
1890
  const text = String(part ?? '');
1876
1891
  if (text.length > EXCHANGE_FIELD_MAX) {
1877
- throw new ValidationError(`an exchange field exceeds ${EXCHANGE_FIELD_MAX} characters. Nothing was written.`);
1892
+ throw new ValidationError(`an exchange field exceeds ${EXCHANGE_FIELD_MAX} characters. Nothing was written.`, { code: 'EMET-TRN-001' });
1878
1893
  }
1879
1894
  total += text.length;
1880
1895
  }
1881
1896
  if (total > EXCHANGE_REQUEST_MAX) {
1882
- throw new ValidationError(`this transcript request exceeds ${EXCHANGE_REQUEST_MAX} characters. Nothing was written.`);
1897
+ throw new ValidationError(`this transcript request exceeds ${EXCHANGE_REQUEST_MAX} characters. Nothing was written.`, { code: 'EMET-TRN-002' });
1883
1898
  }
1884
1899
  }
1885
1900
 
@@ -1895,15 +1910,15 @@ export async function saveTranscript(session_id, session_start, session_end, exc
1895
1910
 
1896
1911
  try {
1897
1912
  if (!session_id || typeof session_id !== 'string') {
1898
- throw new ValidationError('session_id must be a non-empty string');
1913
+ throw new ValidationError('session_id must be a non-empty string', { code: 'EMET-TRN-003' });
1899
1914
  }
1900
1915
  if (typeof session_start !== 'number') {
1901
- throw new ValidationError('session_start must be a Unix timestamp (number)');
1916
+ throw new ValidationError('session_start must be a Unix timestamp (number)', { code: 'EMET-TRN-004' });
1902
1917
  }
1903
1918
 
1904
1919
  const resolvedChannel = channel || 'claude_project';
1905
1920
  if (!Array.isArray(exchanges) || exchanges.length === 0) {
1906
- throw new ValidationError('exchanges must be a non-empty array');
1921
+ throw new ValidationError('exchanges must be a non-empty array', { code: 'EMET-TRN-005' });
1907
1922
  }
1908
1923
  assertExchangeBudget(exchanges.flatMap((ex) => [ex && ex.user_message, ex && ex.assistant_message]));
1909
1924
  const resolvedExchanges = exchanges;
@@ -1957,7 +1972,7 @@ export async function saveTranscript(session_id, session_start, session_end, exc
1957
1972
 
1958
1973
  } catch (error) {
1959
1974
  if (error instanceof ValidationError || error instanceof EmetError) throw error;
1960
- throw new DatabaseError(`Failed to save session transcript: ${error.message}`, 'save_transcript');
1975
+ throw new DatabaseError(`Failed to save session transcript: ${error.message}`, 'save_transcript', { code: 'EMET-DB-019' });
1961
1976
  }
1962
1977
  }
1963
1978
 
@@ -2050,7 +2065,7 @@ export async function dropsSeenForOpen(load_id) {
2050
2065
  throw new DatabaseError(
2051
2066
  `emet_session_open could not load unhandled drops from the store, so no session was opened: ${e && e.message}. Nothing was stamped.`,
2052
2067
  'emet_session_open'
2053
- );
2068
+ , { code: 'EMET-DB-020' });
2054
2069
  }
2055
2070
  }
2056
2071
 
@@ -2067,9 +2082,9 @@ export async function sessionOpen({ slug, load_id } = {}, logger = null, dbManag
2067
2082
  try {
2068
2083
  resolved = await firstUnclosedBase(requested, (b) => sessionStatus(b, dbManager));
2069
2084
  } catch (e) {
2070
- if (e && e.allClosed) throw new ValidationError('slug', `${e.message} Nothing was opened.`);
2085
+ if (e && e.allClosed) throw new ValidationError('slug', `${e.message} Nothing was opened.`, { code: 'EMET-MEM-016' });
2071
2086
  throw new DatabaseError(`emet_session_open could not check whether ${requested} is already closed, so no session was opened: ${e && e.message}. ` +
2072
- 'Call emet_session_open again with the same slug and load_id.', 'emet_session_open');
2087
+ 'Call emet_session_open again with the same slug and load_id.', 'emet_session_open', { code: 'EMET-DB-021' });
2073
2088
  }
2074
2089
  const base = resolved.base;
2075
2090
  const session_id = partId(base, 1);
@@ -2169,7 +2184,7 @@ async function subkeyHandleForOpen(actor, base, now) {
2169
2184
  try {
2170
2185
  return await commitLiveSession(approvalsDeps, actor, base, now);
2171
2186
  } catch (e) {
2172
- if (e && e.attributionRefusal) throw new ValidationError('subkey', e.message);
2187
+ if (e && e.attributionRefusal) throw new ValidationError('subkey', e.message, { code: 'EMET-AUTH-028' });
2173
2188
  throw e;
2174
2189
  }
2175
2190
  }
@@ -2183,10 +2198,10 @@ export async function transcriptAppend(args = {}, logger = null) {
2183
2198
  const channel = args.channel;
2184
2199
  redactWithReport(String(user_message || '') + String(assistant_message || ''));
2185
2200
  if (!session_id || typeof session_id !== 'string') {
2186
- throw new ValidationError('session_id is required');
2201
+ throw new ValidationError('session_id is required', { code: 'EMET-MEM-017' });
2187
2202
  }
2188
2203
  if (typeof user_message !== 'string' || typeof assistant_message !== 'string') {
2189
- throw new ValidationError('user_message and assistant_message must be strings');
2204
+ throw new ValidationError('user_message and assistant_message must be strings', { code: 'EMET-TRN-006' });
2190
2205
  }
2191
2206
  assertExchangeBudget([user_message, assistant_message]);
2192
2207
  const {
@@ -2243,7 +2258,7 @@ export async function transcriptAppend(args = {}, logger = null) {
2243
2258
  const notes = await client.db(MONGODB_DB).collection('documents')
2244
2259
  .findOne({ doc_id: installDoc(), retired: { $ne: true } }, { projection: { content: 1 } });
2245
2260
  machineCheck = machineLineCheck(assistant_message, knownMachinesFromInstallNotes(notes && notes.content));
2246
- if (!machineCheck.ok) throw new ValidationError(machineCheck.reason);
2261
+ if (!machineCheck.ok) throw new ValidationError(machineCheck.reason, { code: 'EMET-MEM-018' });
2247
2262
  }
2248
2263
 
2249
2264
  if (!live) {
@@ -2300,11 +2315,11 @@ export async function reviseTranscript(session_id, exchanges, reason, session_st
2300
2315
  const startTime = Date.now();
2301
2316
  try {
2302
2317
  if (!session_id || typeof session_id !== 'string')
2303
- throw new ValidationError('session_id must be a non-empty string');
2318
+ throw new ValidationError('session_id must be a non-empty string', { code: 'EMET-TRN-003' });
2304
2319
  if (!Array.isArray(exchanges) || exchanges.length === 0)
2305
- throw new ValidationError('exchanges must be a non-empty array - a revision replaces the whole part, not a field within it');
2320
+ 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' });
2306
2321
  if (!reason || typeof reason !== 'string' || reason.trim().length < 10)
2307
- throw new ValidationError('reason is required and must describe what was wrong - at least 10 characters. An unexplained correction is a silent rewrite.');
2322
+ 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' });
2308
2323
 
2309
2324
  const client = await connectMongo(MONGODB_URI, { serverSelectionTimeoutMS: 5000, maxPoolSize: 10 });
2310
2325
  const db = client.db(MONGODB_DB);
@@ -2315,7 +2330,7 @@ export async function reviseTranscript(session_id, exchanges, reason, session_st
2315
2330
  || await col.findOne({ session_id });
2316
2331
  if (!parent) {
2317
2332
  await client.close();
2318
- throw new ValidationError(`No transcript found under session_id "${session_id}". Use save_transcript to write a new part; revise_transcript only corrects one that exists.`);
2333
+ throw new ValidationError(`No transcript found under session_id "${session_id}". Use save_transcript to write a new part; revise_transcript only corrects one that exists.`, { code: 'EMET-TRN-009' });
2319
2334
  }
2320
2335
 
2321
2336
  const revision = (typeof parent.revision === 'number' ? parent.revision : 1) + 1;
@@ -2375,7 +2390,7 @@ export async function reviseTranscript(session_id, exchanges, reason, session_st
2375
2390
  };
2376
2391
  } catch (error) {
2377
2392
  if (error instanceof ValidationError || error instanceof EmetError) throw error;
2378
- throw new DatabaseError(`Failed to revise transcript: ${error.message}`, 'revise_transcript');
2393
+ throw new DatabaseError(`Failed to revise transcript: ${error.message}`, 'revise_transcript', { code: 'EMET-DB-022' });
2379
2394
  }
2380
2395
  }
2381
2396
 
@@ -2511,7 +2526,7 @@ export function checkReadPin(doc_id, current, opts = {}) {
2511
2526
  const hasS = typeof wantS === 'string' && wantS.trim() !== '';
2512
2527
  if (!hasV && !hasS) return;
2513
2528
  if (hasV && !(Number.isInteger(Number(wantV)) && Number(wantV) >= 1)) {
2514
- throw new ValidationError('expected_version', 'expected_version is the whole-number `version` an earlier page of this document returned.');
2529
+ throw new ValidationError('expected_version', 'expected_version is the whole-number `version` an earlier page of this document returned.', { code: 'EMET-DOC-004' });
2515
2530
  }
2516
2531
  const vChanged = hasV && current.version !== undefined && current.version !== null && Number(wantV) !== Number(current.version);
2517
2532
  const sChanged = hasS && String(current.sha256 || '').toLowerCase() !== wantS.trim().toLowerCase();
@@ -2522,12 +2537,12 @@ export function checkReadPin(doc_id, current, opts = {}) {
2522
2537
  throw new ValidationError('expected_version',
2523
2538
  `${doc_id}: document changed - restart from offset 0. You read earlier pages of ${was}; it is now ${now}. ` +
2524
2539
  'Pages of two versions are never joined, so nothing was returned. Call read_doc again with offset 0 and no expected_version, ' +
2525
- 'discard the pages you already have, and read every page of the new version.');
2540
+ 'discard the pages you already have, and read every page of the new version.', { code: 'EMET-DOC-005' });
2526
2541
  }
2527
2542
 
2528
2543
  export async function readDoc(doc_id, logger = null, opts = {}) {
2529
2544
  try {
2530
- if (!doc_id || typeof doc_id !== 'string') throw new ValidationError('doc_id must be a non-empty string');
2545
+ if (!doc_id || typeof doc_id !== 'string') throw new ValidationError('doc_id must be a non-empty string', { code: 'EMET-DOC-001' });
2531
2546
  const guide = readShippedGuide(doc_id);
2532
2547
  if (guide) {
2533
2548
  checkReadPin(doc_id, guide, opts);
@@ -2537,7 +2552,7 @@ export async function readDoc(doc_id, logger = null, opts = {}) {
2537
2552
  const { client, col } = await _docsClient();
2538
2553
  try {
2539
2554
  const doc = await col.findOne({ doc_id });
2540
- if (!doc) throw new ValidationError(`Document not found: ${doc_id}`);
2555
+ if (!doc) throw new ValidationError(`Document not found: ${doc_id}`, { code: 'EMET-DOC-002' });
2541
2556
  checkReadPin(doc_id, doc, opts);
2542
2557
  const { content, page } = pageContent(doc.content, opts.offset ?? 0, opts.limit ?? null);
2543
2558
  // A retired document is still returned in full - retain and mark, never
@@ -2567,7 +2582,7 @@ export async function readDoc(doc_id, logger = null, opts = {}) {
2567
2582
  } finally { await client.close(); }
2568
2583
  } catch (error) {
2569
2584
  if (error instanceof ValidationError || error instanceof EmetError) throw error;
2570
- throw new DatabaseError(`Failed to read document: ${error.message}`, 'read_doc');
2585
+ throw new DatabaseError(`Failed to read document: ${error.message}`, 'read_doc', { code: 'EMET-DB-023' });
2571
2586
  }
2572
2587
  }
2573
2588
 
@@ -2581,8 +2596,8 @@ export async function readDoc(doc_id, logger = null, opts = {}) {
2581
2596
  */
2582
2597
  export async function readDocHistory(doc_id, version = null, logger = null) {
2583
2598
  try {
2584
- if (!doc_id || typeof doc_id !== 'string') throw new ValidationError('doc_id must be a non-empty string');
2585
- if (version !== null && version !== undefined && (!Number.isInteger(version) || version < 1)) throw new ValidationError('version must be a positive integer');
2599
+ if (!doc_id || typeof doc_id !== 'string') throw new ValidationError('doc_id must be a non-empty string', { code: 'EMET-DOC-001' });
2600
+ if (version !== null && version !== undefined && (!Number.isInteger(version) || version < 1)) throw new ValidationError('version must be a positive integer', { code: 'EMET-DOC-006' });
2586
2601
  const { client, col, hist } = await _docsClient();
2587
2602
  try {
2588
2603
  const current = await col.findOne({ doc_id });
@@ -2607,7 +2622,7 @@ export async function readDocHistory(doc_id, version = null, logger = null) {
2607
2622
  // More than one archived row can carry a version when a write was retried;
2608
2623
  // the most recently archived is the one the store last held at that number.
2609
2624
  const row = await hist.find({ doc_id, version }).sort({ archived_at: -1 }).limit(1).next();
2610
- if (!row) throw new ValidationError(`No retained revision ${version} of ${doc_id}`);
2625
+ if (!row) throw new ValidationError(`No retained revision ${version} of ${doc_id}`, { code: 'EMET-DOC-003' });
2611
2626
  const integrity = row.sha256 ? (digest(row.content) === row.sha256) : 'unattested';
2612
2627
  return { doc_id, version, is_current: false, content: row.content, sha256: row.sha256 || null, size: row.content.length,
2613
2628
  updated_at: row.updated_at || null, updated_by: row.updated_by || null, archived_at: row.archived_at || null,
@@ -2621,7 +2636,7 @@ export async function readDocHistory(doc_id, version = null, logger = null) {
2621
2636
  } finally { await client.close(); }
2622
2637
  } catch (error) {
2623
2638
  if (error instanceof ValidationError || error instanceof EmetError) throw error;
2624
- throw new DatabaseError(`Failed to read document history: ${error.message}`, 'read_doc_history');
2639
+ throw new DatabaseError(`Failed to read document history: ${error.message}`, 'read_doc_history', { code: 'EMET-DB-024' });
2625
2640
  }
2626
2641
  }
2627
2642
 
@@ -2658,7 +2673,7 @@ function _refuseRecordAmendment(doc_id, tool) {
2658
2673
  `${tool}: ${doc_id} is a record. Records are superseded, not amended (ISO 9001 7.5.3 / 13485 4.2.5). ` +
2659
2674
  `Issue a new revision with write_doc - the whole record, with \`supersedes\` set to the version now in force. ` +
2660
2675
  `The prior revision is retained and marked obsolete. Nothing was changed.`
2661
- );
2676
+ , { code: 'EMET-DOC-007' });
2662
2677
  }
2663
2678
  }
2664
2679
 
@@ -2667,14 +2682,14 @@ function _refuseRecordAmendment(doc_id, tool) {
2667
2682
  * 3.5). write_doc and patch_doc refuse the main HANDOFF.md or STATE.md when the
2668
2683
  * write's source is a bot tag (bots/<tag>/HANDOFF.md listed in
2669
2684
  * EMET_RECORD_DOCS), and nothing is written. So do the other doors that can
2670
- * change a main record (the tester's F1 on PR 2): retire_doc, rename_doc (from
2685
+ * change a main record (the reviewer's F1 on PR 2): retire_doc, rename_doc (from
2671
2686
  * or onto one) and accept_nonconformance - retire and rename set retired_by,
2672
2687
  * not updated_by, so the close alone could not see them. The source is the one the door
2673
2688
  * stamps as updated_by: the caller's, else EMET_SOURCE_TAG. A records rule like
2674
2689
  * the record-amendment refusal above, so it applies in every graph mode.
2675
2690
  *
2676
2691
  * Two further guards on the same doors (2026-10-01, the owner's 4:17 PM approval to
2677
- * make the bot tags fully functional; the tester's review of PR 3):
2692
+ * make the bot tags fully functional; the reviewer's review of PR 3):
2678
2693
  * - REGISTERED HOSTS ONLY on the main records. With a source registry
2679
2694
  * configured (EMET_SOURCE_TAGS, parsed as save_to_layer parses it), the
2680
2695
  * main handoff and board take writes only from a registered tag. An
@@ -2695,7 +2710,7 @@ export function sourceRegistry() {
2695
2710
  }
2696
2711
 
2697
2712
  /**
2698
- * Attribution v2 (the reviewer A3): a declared tag never gains rights beyond the login's
2713
+ * Attribution v2 (the second reader A3): a declared tag never gains rights beyond the login's
2699
2714
  * tag. A guard is run for every tag returned here and the write must pass all.
2700
2715
  */
2701
2716
  export function rightsTags(tag) {
@@ -2730,14 +2745,14 @@ export function resolvedSourceTag(caller) {
2730
2745
  return { tag: null, from: 'legacy' };
2731
2746
  }
2732
2747
 
2733
- // Look-alike doc ids (the reviewer's recheck d1-d5, 2026-10-02): a `.` or `..` segment,
2748
+ // Look-alike doc ids (the second reader's recheck d1-d5, 2026-10-02): a `.` or `..` segment,
2734
2749
  // a leading `/`, or a `bots/` prefix in the wrong case would let a write pass
2735
2750
  // the prefix checks below while naming a record they are meant to fence (d1:
2736
- // bots/reviewer-bot/../intake-bot/HANDOFF.md passed the own-dir check). Doc
2751
+ // bots/tester-bot/../intake-bot/HANDOFF.md passed the own-dir check). Doc
2737
2752
  // ids are flat strings, never resolved as paths, so these shapes are refused
2738
2753
  // outright, before any guard, on every door that calls this.
2739
2754
  //
2740
- // Hardening (the tester's scope on the doc-id fix, 2026-10-02): also refused are
2755
+ // Hardening (the reviewer's scope on the doc-id fix, 2026-10-02): also refused are
2741
2756
  // control and invisible-format characters (\p{Cc}, \p{Cf}) anywhere; leading or
2742
2757
  // trailing whitespace on the id or on any segment; a backslash; the `/`, `.`/`..`
2743
2758
  // and `bots/` checks run on the NFKC form too (so full-width dots and slashes,
@@ -2780,11 +2795,11 @@ export function refuseLookalikeDocId(doc_id, tool) {
2780
2795
  throw new ValidationError(
2781
2796
  `${tool}: doc_id ${JSON.stringify(doc_id)} ${why}. Doc ids are not paths and are not resolved; write the id ` +
2782
2797
  `exactly as it is meant to be stored. Nothing was written.`
2783
- );
2798
+ , { code: 'EMET-DOC-008' });
2784
2799
  }
2785
2800
  }
2786
2801
 
2787
- // Cleanup path (the tester's scope): a look-alike id may already exist in a store
2802
+ // Cleanup path (the reviewer's scope): a look-alike id may already exist in a store
2788
2803
  // written before these checks. retire_doc, and rename_doc FROM such an id, are let
2789
2804
  // through for a registered host tag only: EMET_SOURCE_TAGS set, the tag listed,
2790
2805
  // and not a bot tag. Never for a write, a patch, a rename onto it, or a bot.
@@ -2798,12 +2813,12 @@ export function refuseBotMainRecord(doc_id, updated_by, tool, options = {}) {
2798
2813
  }
2799
2814
  function refuseBotMainRecordOne(doc_id, updated_by, tool, options = {}) {
2800
2815
  const tag = updated_by || setting('SOURCE_TAG') || null;
2801
- // The client-approvals record is server-only (the reviewer 4): no host writes,
2816
+ // The client-approvals record is server-only (the second reader 4): no host writes,
2802
2817
  // patches, retires, renames, restores or accepts it.
2803
2818
  if (typeof doc_id === 'string' && FOLD(doc_id.normalize('NFKC')) === FOLD(APPROVALS_DOC) && !(options && options.approvalsRecord === true)) {
2804
- throw new ValidationError(`${tool}: ${doc_id} is kept by the server (client approvals). Decide clients with emet_client_approve. Nothing was written.`);
2819
+ 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' });
2805
2820
  }
2806
- // A3 without a registry (the reviewer re-review): a declared or generated tag writes
2821
+ // A3 without a registry (the second reader re-review): a declared or generated tag writes
2807
2822
  // under bots/ only inside bots/<its own tag>/ and only once approved.
2808
2823
  {
2809
2824
  const d = declaredAttribution();
@@ -2811,7 +2826,7 @@ function refuseBotMainRecordOne(doc_id, updated_by, tool, options = {}) {
2811
2826
  typeof doc_id === 'string' && doc_id.startsWith('bots/')) {
2812
2827
  const approved = approvedTags().includes(tag) || sourceRegistry().includes(tag);
2813
2828
  if (!doc_id.startsWith(botRecordDir(tag)) || !approved) {
2814
- throw new ValidationError(`${tool}: ${doc_id} is a bot record and "${tag}" is a ${approved ? 'declared tag outside its own folder' : 'declared tag not yet approved'} - a declared tag writes only bots/${tag}/ once approved. Nothing was written.`);
2829
+ throw new ValidationError(`${tool}: ${doc_id} is a bot record and "${tag}" is a ${approved ? 'declared tag outside its own folder' : 'declared tag not yet approved'} - a declared tag writes only bots/${tag}/ once approved. Nothing was written.`, { code: 'EMET-DOC-010' });
2815
2830
  }
2816
2831
  }
2817
2832
  }
@@ -2822,9 +2837,9 @@ function refuseBotMainRecordOne(doc_id, updated_by, tool, options = {}) {
2822
2837
  `${tool}: ${doc_id} is outside ${botRecordDir(tag)} and ${tag} is a bot tag - a bot writes only its own ` +
2823
2838
  `${botRecordDir(tag)} records; other bots' records and the roster are not its to change. ` +
2824
2839
  `Hand it to the hub instead. Nothing was written.`
2825
- );
2840
+ , { code: 'EMET-DOC-011' });
2826
2841
  }
2827
- // Registry guard on bots/ too (the tester's PR 5 review; the reviewer's fix (a), 2026-10-02): with EMET_SOURCE_TAGS
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
2828
2843
  // set, a non-bot write under bots/ is refused unless its tag is registered; a missing source counts as
2829
2844
  // unregistered. Without this, a misspelled or unregistered tag is not a bot tag, so the cross-bot guard
2830
2845
  // above never fires and it can write any bot's records or the roster. A listed bot is already fenced to
@@ -2834,7 +2849,7 @@ function refuseBotMainRecordOne(doc_id, updated_by, tool, options = {}) {
2834
2849
  throw new ValidationError(
2835
2850
  `${tool}: ${doc_id} is a bot record and ${tag ? `"${tag}" is not a registered source tag` : 'this write names no source tag'} - ` +
2836
2851
  `only a registered host or the bot itself writes under bots/. Nothing was written.`
2837
- );
2852
+ , { code: 'EMET-DOC-012' });
2838
2853
  }
2839
2854
  if (!mainRecordIds().includes(doc_id)) return;
2840
2855
  if (bot) {
@@ -2842,7 +2857,7 @@ function refuseBotMainRecordOne(doc_id, updated_by, tool, options = {}) {
2842
2857
  `${tool}: ${doc_id} is a main record and ${tag} is a bot tag - a bot session closes against ` +
2843
2858
  `${botRecordDir(tag)} records; the main handoff and board are the hub's. Write the bot's own ` +
2844
2859
  `${botRecordDir(tag)}HANDOFF.md instead. Nothing was written.`
2845
- );
2860
+ , { code: 'EMET-DOC-013' });
2846
2861
  }
2847
2862
  if (options && options.serverProvision === true) return;
2848
2863
  if (registry.length && !(tag && registry.includes(tag))) {
@@ -2850,15 +2865,15 @@ function refuseBotMainRecordOne(doc_id, updated_by, tool, options = {}) {
2850
2865
  `${tool}: ${doc_id} is a main record and ` +
2851
2866
  `${tag ? `"${tag}" is not a registered source tag` : 'this write names no source tag'} - only a registered ` +
2852
2867
  `host writes the main handoff and board. Pass the host's registered \`source\` (EMET_SOURCE_TAGS). Nothing was written.`
2853
- );
2868
+ , { code: 'EMET-DOC-014' });
2854
2869
  }
2855
2870
  }
2856
2871
 
2857
2872
  /**
2858
2873
  * retire_doc and rename_doc are not bot tools at all (Alex, 2026-10-01 4:27 PM
2859
2874
  * ET, decision 1, as relayed: "retire_doc isn't needed for bots: keep it
2860
- * owner/hub only and out of every bot profile"; procedural ref 407; stage 1 of the
2861
- * ref 358 startup amendment, admitted by the tester 2026-10-02). A profile is not a
2875
+ * 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
2862
2877
  * security boundary, so the door refuses them under ANY bot tag, for every
2863
2878
  * doc_id - not only the main records refuseBotMainRecord covers. ref 407(1)
2864
2879
  * covers retire_doc only; rename_doc stays owner-only under procedural ref 409
@@ -2874,23 +2889,29 @@ export function refuseBotRetireRename(tag, tool) {
2874
2889
  function refuseBotRetireRenameOne(tag, tool) {
2875
2890
  const t = tag || setting('SOURCE_TAG') || null;
2876
2891
  if (!t || !isBotTag(t)) return;
2892
+ if (tool === 'retire_doc') {
2893
+ throw new ValidationError(
2894
+ 'source',
2895
+ `${tool} is not a bot tool: ${t} is a bot tag, and ` +
2896
+ `retiring documents is the owner's and the hub's (decision 1, procedural ref 407 item 1)` +
2897
+ `. Ask the hub. Nothing was changed.`
2898
+ , { code: 'EMET-MEM-019' });
2899
+ }
2877
2900
  throw new ValidationError(
2878
2901
  'source',
2879
2902
  `${tool} is not a bot tool: ${t} is a bot tag, and ` +
2880
- (tool === 'retire_doc'
2881
- ? `retiring documents is the owner's and the hub's (decision 1, procedural ref 407 item 1)`
2882
- : `renaming documents stays owner-only (procedural ref 409)`) +
2903
+ `renaming documents stays owner-only (procedural ref 409)` +
2883
2904
  `. Ask the hub. Nothing was changed.`
2884
- );
2905
+ , { code: 'EMET-MEM-020' });
2885
2906
  }
2886
2907
 
2887
2908
  export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint = null, logger = null, options = {}) {
2888
2909
  try {
2889
- if (!doc_id || typeof doc_id !== 'string') throw new ValidationError('doc_id must be a non-empty string');
2910
+ if (!doc_id || typeof doc_id !== 'string') throw new ValidationError('doc_id must be a non-empty string', { code: 'EMET-DOC-001' });
2890
2911
  // write_doc, patch_doc (which lands here) and rename_doc's copy (reissued_from).
2891
2912
  refuseBotMainRecord(doc_id, updated_by, options && options.reissued_from ? 'rename_doc' : 'write_doc', options && options.serverProvision === true ? { serverProvision: true, ...(options.approvalsRecord === true ? { approvalsRecord: true } : {}) } : {});
2892
- if (typeof rawContent !== 'string' || rawContent.length === 0) throw new ValidationError('content must be a non-empty string');
2893
- if (rawContent.length > 2000000) throw new ValidationError('content exceeds 2MB limit');
2913
+ if (typeof rawContent !== 'string' || rawContent.length === 0) throw new ValidationError('content must be a non-empty string', { code: 'EMET-DOC-015' });
2914
+ if (rawContent.length > 2000000) throw new ValidationError('content exceeds 2MB limit', { code: 'EMET-DOC-016' });
2894
2915
  // patch_doc lands here too, so one
2895
2916
  // scrub covers every document write. The digest is of the stored text.
2896
2917
  const redaction = redactWithReport(rawContent);
@@ -2900,9 +2921,13 @@ export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint
2900
2921
  const signature = signDigests(sha256, '', signingKey);
2901
2922
  const { client, col, hist } = await _docsClient();
2902
2923
  try {
2924
+ if (typeof doc_id === 'string' && doc_id.startsWith('areas/')) {
2925
+ const { assertAreaOwner } = await import('./pages.js');
2926
+ await assertAreaOwner(client.db(MONGODB_DB), 'write_doc');
2927
+ }
2903
2928
  const prev = await col.findOne({ doc_id });
2904
2929
  const version = (prev && prev.version ? prev.version : 0) + 1;
2905
- // Compare-and-set for the client-approvals record (the reviewer round 3): checked
2930
+ // Compare-and-set for the client-approvals record (the second reader round 3): checked
2906
2931
  // here before anything is archived, and again atomically in the update filter.
2907
2932
  const casOn = options && options.approvalsRecord === true && Object.prototype.hasOwnProperty.call(options, 'expectedVersion');
2908
2933
  const casConflict = () => { const e = new ValidationError(`${doc_id} changed under this write (compare-and-set). Nothing was written.`); e.versionConflict = true; return e; };
@@ -2918,19 +2943,19 @@ export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint
2918
2943
  throw new ValidationError(
2919
2944
  `write_doc: ${doc_id} is a record and v${prev.version} is in force. A new revision must name what it ` +
2920
2945
  `supersedes - pass supersedes: ${prev.version}. Nothing was changed.`
2921
- );
2946
+ , { code: 'EMET-DOC-017' });
2922
2947
  }
2923
2948
  if (Number(named) !== prev.version) {
2924
2949
  throw new ValidationError(
2925
2950
  `write_doc: ${doc_id} - supersedes names v${named}, but v${prev.version} is in force. Re-read the record ` +
2926
2951
  `and supersede the current revision. Nothing was changed.`
2927
- );
2952
+ , { code: 'EMET-DOC-018' });
2928
2953
  }
2929
2954
  const reason = options && options.reason;
2930
2955
  if (typeof reason !== 'string' || reason.trim().length < 10) {
2931
2956
  throw new ValidationError(
2932
2957
  `write_doc: ${doc_id} is a record. A new revision needs reason (at least 10 characters) as well as supersedes. Nothing was changed.`
2933
- );
2958
+ , { code: 'EMET-DOC-019' });
2934
2959
  }
2935
2960
  }
2936
2961
  const registry = sourceRegistry();
@@ -2938,35 +2963,36 @@ export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint
2938
2963
  // Attribution v2 (A3): the declared tag and the login's tag must both pass.
2939
2964
  const passes = (t) => registry.length === 0 || registry.includes(t || '') || (isBotTag(t) && doc_id.startsWith(`bots/${t}/`));
2940
2965
  if (!rightsTags(updated_by).every(passes) && !serverProvision && !(isDropDoc(doc_id) && !prev)) {
2941
- 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.`);
2966
+ 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' });
2942
2967
  }
2943
2968
  if (isDropDoc(doc_id) && !prev) {
2944
2969
  const { writerStamp } = await import('./persons.js');
2945
2970
  const bucket = dropBucket(writerStamp().client_id, updated_by);
2946
2971
  const day = nyDay(new Date());
2947
2972
  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);
2948
- if (same.length >= 20) throw new ValidationError(`write_doc: this connected app already wrote 20 drops today. Nothing was written.`);
2973
+ if (same.length >= 20) throw new ValidationError(`write_doc: this connected app already wrote 20 drops today. Nothing was written.`, { code: 'EMET-DOC-021' });
2949
2974
  options = { ...options, drop_bucket: bucket };
2950
2975
  }
2951
2976
  const floorExempt = options && options.provision;
2952
2977
  const internal = options && (options.provision || options.edited || options.setupReissue || options.restore_of || (options.approvalsRecord === true && options.serverProvision === true && doc_id === APPROVALS_DOC));
2953
2978
  if (options && options.provision && prev && doc_id === stateDoc()) {
2954
- throw new ValidationError('The board already exists. Provision does not replace it. Nothing was written.');
2979
+ throw new ValidationError('The board already exists. Provision does not replace it. Nothing was written.', { code: 'EMET-MEM-021' });
2955
2980
  }
2956
2981
  if (doc_id === stateDoc() && !(options && (options.provision || options.edited || options.restore_of))) {
2957
- throw new ValidationError(prev
2958
- ? 'The board is never written. Edit it with patch_doc, with `reason` (and `origin` for an added row). Nothing was written.'
2959
- : 'The board is provisioned by the server at setup (emet_setup_complete). Nothing was written.');
2982
+ if (prev) {
2983
+ throw new ValidationError('The board is never written. Edit it with patch_doc, with `reason` (and `origin` for an added row). Nothing was written.', { code: 'EMET-MEM-022' });
2984
+ }
2985
+ throw new ValidationError('The board is provisioned by the server at setup (emet_setup_complete). Nothing was written.', { code: 'EMET-MEM-023' });
2960
2986
  }
2961
2987
  if (prev && isWorkingDoc(doc_id) && !internal) {
2962
2988
  throw new ValidationError(
2963
2989
  `write_doc: ${doc_id} exists, so it is edited, not rewritten. Use patch_doc with \`reason\`. Nothing was written.`
2964
- );
2990
+ , { code: 'EMET-DOC-022' });
2965
2991
  }
2966
2992
  if (isDropDoc(doc_id) && (prev || (options && options.restore_of))) {
2967
2993
  throw new ValidationError(
2968
2994
  `write_doc: ${doc_id} is a drop and already exists, retired drops included. A drop is never patched or restored. Use a new id. Nothing was written.`
2969
- );
2995
+ , { code: 'EMET-DOC-023' });
2970
2996
  }
2971
2997
  if (isGovernedByShippedCopy(doc_id) && !(options && options.provision)) {
2972
2998
  const { readFileSync } = await import('node:fs');
@@ -2974,7 +3000,7 @@ export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint
2974
3000
  let shipped = '';
2975
3001
  try { shipped = readFileSync(shippedPath, 'utf8'); } catch { shipped = ''; }
2976
3002
  if (content !== shipped) {
2977
- throw new ValidationError(`write_doc: ${doc_id} is governed by the copy shipped with this release. Only that text may be stored. Nothing was written.`);
3003
+ throw new ValidationError(`write_doc: ${doc_id} is governed by the copy shipped with this release. Only that text may be stored. Nothing was written.`, { code: 'EMET-DOC-024' });
2978
3004
  }
2979
3005
  }
2980
3006
  const sid = (options && options.session_id) || null;
@@ -2990,7 +3016,7 @@ export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint
2990
3016
  const pct = Math.floor((content.length / baseline) * 100);
2991
3017
  throw new ValidationError(
2992
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.`
2993
- );
3019
+ , { code: 'EMET-DOC-025' });
2994
3020
  }
2995
3021
  // Cross-session floor. The per-session floor is measured from this
2996
3022
  // session's first touch, so a new session can shrink a document once.
@@ -3009,7 +3035,7 @@ export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint
3009
3035
  const pct = Math.floor((content.length / peak) * 100);
3010
3036
  throw new ValidationError(
3011
3037
  `This change would leave ${doc_id} at ${pct}% of its largest size in the last 24 hours. A write may not fall below half of that peak. Nothing was written.`
3012
- );
3038
+ , { code: 'EMET-DOC-026' });
3013
3039
  }
3014
3040
  const sizeSamples = recentSamples.slice();
3015
3041
  if (prev) sizeSamples.push({ size: String(prev.content || '').length, at: prev.updated_at || new Date() });
@@ -3071,13 +3097,13 @@ export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint
3071
3097
  if (options && options.provision && doc_id === stateDoc()) {
3072
3098
  const ins = await col.updateOne({ doc_id }, { $setOnInsert: writtenRow }, { upsert: true });
3073
3099
  if (ins && ins.upsertedCount === 0) {
3074
- throw new ValidationError('The board already exists. Provision does not replace it. Nothing was written.');
3100
+ throw new ValidationError('The board already exists. Provision does not replace it. Nothing was written.', { code: 'EMET-MEM-021' });
3075
3101
  }
3076
3102
  } else if (casOn) {
3077
3103
  let res;
3078
3104
  try {
3079
3105
  res = options.expectedVersion == null
3080
- // the reviewer delta M1: documents.doc_id has no unique index, so the first
3106
+ // the second reader delta M1: documents.doc_id has no unique index, so the first
3081
3107
  // create keys on a deterministic _id; _id is always unique, so a
3082
3108
  // second racing insert matches it (or hits a duplicate key) and loses.
3083
3109
  ? await col.updateOne({ _id: `${APPROVALS_DOC}#current` }, { $setOnInsert: writtenRow }, { upsert: true })
@@ -3102,7 +3128,7 @@ export async function writeDoc(doc_id, rawContent, updated_by = null, path_hint
3102
3128
  } catch (error) {
3103
3129
  if (error && error.versionConflict) throw error;
3104
3130
  if (error instanceof ValidationError || error instanceof EmetError) throw error;
3105
- throw new DatabaseError(`Failed to write document: ${error.message}`, 'write_doc');
3131
+ throw new DatabaseError(`Failed to write document: ${error.message}`, 'write_doc', { code: 'EMET-DB-025' });
3106
3132
  }
3107
3133
  }
3108
3134
 
@@ -3136,7 +3162,7 @@ export async function listDocs(prefix = null, logger = null, include_retired = f
3136
3162
  } finally { await client.close(); }
3137
3163
  } catch (error) {
3138
3164
  if (error instanceof ValidationError || error instanceof EmetError) throw error;
3139
- throw new DatabaseError(`Failed to list documents: ${error.message}`, 'list_docs');
3165
+ throw new DatabaseError(`Failed to list documents: ${error.message}`, 'list_docs', { code: 'EMET-DB-026' });
3140
3166
  }
3141
3167
  }
3142
3168
 
@@ -3179,17 +3205,23 @@ export async function listDocs(prefix = null, logger = null, include_retired = f
3179
3205
  */
3180
3206
  export async function retireDoc(doc_id, reason = null, retired_by = null, logger = null, options = {}) {
3181
3207
  try {
3182
- if (!doc_id || typeof doc_id !== 'string') throw new ValidationError('doc_id must be a non-empty string');
3208
+ if (!doc_id || typeof doc_id !== 'string') throw new ValidationError('doc_id must be a non-empty string', { code: 'EMET-DOC-001' });
3209
+ if (doc_id.startsWith('areas/')) {
3210
+ const { assertAreaOwner } = await import('./pages.js');
3211
+ const opened = await _docsClient();
3212
+ try { await assertAreaOwner(opened.client.db(MONGODB_DB), 'retire_doc'); }
3213
+ finally { await opened.client.close(); }
3214
+ }
3183
3215
  refuseBotMainRecord(doc_id, retired_by, 'retire_doc', { cleanup: true });
3184
3216
  refuseBotRetireRename(retired_by, 'retire_doc');
3185
- 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.');
3186
- 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.`);
3187
- 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.');
3217
+ 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' });
3218
+ 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' });
3219
+ 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' });
3188
3220
 
3189
3221
  const { client, col } = await _docsClient();
3190
3222
  try {
3191
3223
  const doc = await col.findOne({ doc_id });
3192
- if (!doc) throw new ValidationError(`Document not found: ${doc_id}`);
3224
+ if (!doc) throw new ValidationError(`Document not found: ${doc_id}`, { code: 'EMET-DOC-002' });
3193
3225
  if (doc.retired) {
3194
3226
  return { doc_id, retired: true, already_retired: true, verified: true,
3195
3227
  retired_at: doc.retired_at, retired_reason: doc.retired_reason || null,
@@ -3211,10 +3243,10 @@ export async function retireDoc(doc_id, reason = null, retired_by = null, logger
3211
3243
  // digest are re-checked too - retiring must not touch either.
3212
3244
  const check = await col.findOne({ doc_id });
3213
3245
  if (!check || check.retired !== true) {
3214
- throw new DatabaseError(`Retirement mark did not persist: ${doc_id}`, 'retire_doc');
3246
+ throw new DatabaseError(`Retirement mark did not persist: ${doc_id}`, 'retire_doc', { code: 'EMET-DB-027' });
3215
3247
  }
3216
3248
  if (check.sha256 !== doc.sha256 || check.version !== doc.version) {
3217
- throw new DatabaseError(`Retiring altered the document: ${doc_id}`, 'retire_doc');
3249
+ throw new DatabaseError(`Retiring altered the document: ${doc_id}`, 'retire_doc', { code: 'EMET-DB-028' });
3218
3250
  }
3219
3251
 
3220
3252
  // L5 - retirement is not an escape hatch. retireDoc is the one document
@@ -3241,32 +3273,38 @@ export async function retireDoc(doc_id, reason = null, retired_by = null, logger
3241
3273
  } finally { await client.close(); }
3242
3274
  } catch (error) {
3243
3275
  if (error instanceof ValidationError || error instanceof EmetError) throw error;
3244
- throw new DatabaseError(`Failed to retire document: ${error.message}`, 'retire_doc');
3276
+ throw new DatabaseError(`Failed to retire document: ${error.message}`, 'retire_doc', { code: 'EMET-DB-029' });
3245
3277
  }
3246
3278
  }
3247
3279
 
3248
3280
  export async function renameDoc(old_id, new_id, updated_by = null, logger = null, reason = null, options = {}) {
3249
3281
  try {
3250
- if (!old_id || typeof old_id !== 'string') throw new ValidationError('old_id must be a non-empty string');
3251
- if (!new_id || typeof new_id !== 'string') throw new ValidationError('new_id must be a non-empty string');
3252
- if (old_id === new_id) throw new ValidationError('old_id and new_id name the same document');
3282
+ if (!old_id || typeof old_id !== 'string') throw new ValidationError('old_id must be a non-empty string', { code: 'EMET-DOC-030' });
3283
+ if (!new_id || typeof new_id !== 'string') throw new ValidationError('new_id must be a non-empty string', { code: 'EMET-DOC-031' });
3284
+ if (old_id === new_id) throw new ValidationError('old_id and new_id name the same document', { code: 'EMET-DOC-032' });
3285
+ if ((typeof old_id === 'string' && old_id.startsWith('areas/')) || (typeof new_id === 'string' && new_id.startsWith('areas/'))) {
3286
+ const { assertAreaOwner } = await import('./pages.js');
3287
+ const opened = await _docsClient();
3288
+ try { await assertAreaOwner(opened.client.db(MONGODB_DB), 'rename_doc'); }
3289
+ finally { await opened.client.close(); }
3290
+ }
3253
3291
  refuseBotMainRecord(old_id, updated_by, 'rename_doc', { cleanup: true });
3254
3292
  refuseBotMainRecord(new_id, updated_by, 'rename_doc');
3255
3293
  refuseBotRetireRename(updated_by, 'rename_doc');
3256
- if (typeof reason !== 'string' || reason.trim().length < 10) throw new ValidationError('rename_doc needs reason (at least 10 characters). Nothing was changed.');
3257
- if (old_id === stateDoc() || new_id === stateDoc()) throw new ValidationError('rename_doc: the board is never renamed. Nothing was changed.');
3258
- if (isDropDoc(old_id) || isDropDoc(new_id)) throw new ValidationError('rename_doc: a drop is write-once. Use a new id. Nothing was changed.');
3294
+ 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' });
3295
+ if (old_id === stateDoc() || new_id === stateDoc()) throw new ValidationError('rename_doc: the board is never renamed. Nothing was changed.', { code: 'EMET-DOC-034' });
3296
+ if (isDropDoc(old_id) || isDropDoc(new_id)) throw new ValidationError('rename_doc: a drop is write-once. Use a new id. Nothing was changed.', { code: 'EMET-DOC-035' });
3259
3297
 
3260
3298
  let content, path_hint;
3261
3299
  const { client, col } = await _docsClient();
3262
3300
  try {
3263
3301
  const source = await col.findOne({ doc_id: old_id });
3264
- if (!source) throw new ValidationError(`Document not found: ${old_id}`);
3302
+ if (!source) throw new ValidationError(`Document not found: ${old_id}`, { code: 'EMET-DOC-002' });
3265
3303
  // Never clobber. A rename onto an occupied id is a MERGE decision, and a
3266
3304
  // merge is not something to guess at on the caller's behalf.
3267
3305
  const occupied = await col.findOne({ doc_id: new_id });
3268
3306
  if (occupied) {
3269
- throw new ValidationError(`Destination already exists: ${new_id} (version ${occupied.version}). Rename refused; nothing was changed.`);
3307
+ throw new ValidationError(`Destination already exists: ${new_id} (version ${occupied.version}). Rename refused; nothing was changed.`, { code: 'EMET-DOC-036' });
3270
3308
  }
3271
3309
  content = source.content;
3272
3310
  path_hint = source.path_hint || null;
@@ -3296,17 +3334,17 @@ export async function renameDoc(old_id, new_id, updated_by = null, logger = null
3296
3334
  };
3297
3335
  } catch (error) {
3298
3336
  if (error instanceof ValidationError || error instanceof EmetError) throw error;
3299
- throw new DatabaseError(`Failed to rename document: ${error.message}`, 'rename_doc');
3337
+ throw new DatabaseError(`Failed to rename document: ${error.message}`, 'rename_doc', { code: 'EMET-DB-030' });
3300
3338
  }
3301
3339
  }
3302
3340
 
3303
3341
  async function unretiredBootDrops(session_id) {
3304
3342
  if (!session_id || typeof session_id !== 'string' || !String(session_id).trim()) {
3305
- throw new ValidationError('a board edit or restore needs session_id from emet_session_open, with a verified drop list. Nothing was written.');
3343
+ throw new ValidationError('a board edit or restore needs session_id from emet_session_open, with a verified drop list. Nothing was written.', { code: 'EMET-MEM-024' });
3306
3344
  }
3307
3345
  const base = String(session_id).replace(/_verbatim_part\d+$/, '').trim();
3308
3346
  if (!base) {
3309
- throw new ValidationError('a board edit or restore needs session_id from emet_session_open, with a verified drop list. Nothing was written.');
3347
+ throw new ValidationError('a board edit or restore needs session_id from emet_session_open, with a verified drop list. Nothing was written.', { code: 'EMET-MEM-024' });
3310
3348
  }
3311
3349
  const { COLLECTION_PREFIX } = await import('./database.js');
3312
3350
  const client = await connectMongo(MONGODB_URI, { serverSelectionTimeoutMS: dropListTimeoutMs(), maxPoolSize: 10 });
@@ -3314,7 +3352,7 @@ async function unretiredBootDrops(session_id) {
3314
3352
  const db = client.db(MONGODB_DB);
3315
3353
  const row = await db.collection(`${COLLECTION_PREFIX}sessions`).findOne({ _id: base });
3316
3354
  if (!row || row.drops_unverified === true || !Array.isArray(row.drops_seen)) {
3317
- throw new ValidationError('unhandled drops could not be loaded at this session boot, so the board cannot be edited or restored until the list is known. Nothing was written.');
3355
+ throw new ValidationError('unhandled drops could not be loaded at this session boot, so the board cannot be edited or restored until the list is known. Nothing was written.', { code: 'EMET-MEM-025' });
3318
3356
  }
3319
3357
  const listed = row.drops_seen;
3320
3358
  if (!listed.length) return [];
@@ -3326,28 +3364,28 @@ async function unretiredBootDrops(session_id) {
3326
3364
  export async function restoreDoc(doc_id, version, updated_by = null, logger = null, reason = null, options = {}) {
3327
3365
  refuseBotMainRecord(doc_id, updated_by, 'restore_doc');
3328
3366
  refuseBotRetireRename(updated_by, 'restore_doc');
3329
- if (typeof reason !== 'string' || reason.trim().length < 10) throw new ValidationError('restore_doc needs reason (at least 10 characters). Nothing was written.');
3330
- if (!updated_by) throw new ValidationError('restore_doc needs a source. Nothing was written.');
3331
- if (isDropDoc(doc_id)) throw new ValidationError('restore_doc: a drop is never restored. Nothing was written.');
3332
- 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.');
3333
- if (isGovernedByShippedCopy(doc_id)) throw new ValidationError('restore_doc: a shipped copy is not restored. Nothing was written.');
3367
+ 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' });
3368
+ if (!updated_by) throw new ValidationError('restore_doc needs a source. Nothing was written.', { code: 'EMET-DOC-038' });
3369
+ if (isDropDoc(doc_id)) throw new ValidationError('restore_doc: a drop is never restored. Nothing was written.', { code: 'EMET-DOC-039' });
3370
+ 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' });
3371
+ if (isGovernedByShippedCopy(doc_id)) throw new ValidationError('restore_doc: a shipped copy is not restored. Nothing was written.', { code: 'EMET-DOC-041' });
3334
3372
  const allowed = (setting('RESTORE_TAGS') || setting('SOURCE_TAG') || '').split(',').map((s) => s.trim()).filter(Boolean);
3335
- if (!allowed.includes(updated_by)) throw new ValidationError(`restore_doc: ${updated_by} is not in EMET_RESTORE_TAGS. Nothing was written.`);
3373
+ 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' });
3336
3374
  const prior = await readDocHistory(doc_id, version, logger);
3337
- if (!prior || typeof prior.content !== 'string') throw new ValidationError(`No retained revision ${version} of ${doc_id}`);
3338
- if (prior.integrity !== true) throw new ValidationError(`restore_doc: retained revision ${version} of ${doc_id} does not match its digest. Nothing was written.`);
3375
+ if (!prior || typeof prior.content !== 'string') throw new ValidationError(`No retained revision ${version} of ${doc_id}`, { code: 'EMET-DOC-003' });
3376
+ if (prior.integrity !== true) throw new ValidationError(`restore_doc: retained revision ${version} of ${doc_id} does not match its digest. Nothing was written.`, { code: 'EMET-DOC-043' });
3339
3377
  const verdict = prior.conformance && prior.conformance.verdict;
3340
3378
  const accepted = prior.conformance && prior.conformance.accepted;
3341
3379
  if (!verdict) {
3342
- if (templateFor(doc_id)) throw new ValidationError(`restore_doc: ${doc_id} is templated and the retained revision has no conformance verdict. Only an untemplated document can be restored without a verdict. Nothing was written.`);
3380
+ if (templateFor(doc_id)) throw new ValidationError(`restore_doc: ${doc_id} is templated and the retained revision has no conformance verdict. Only an untemplated document can be restored without a verdict. Nothing was written.`, { code: 'EMET-DOC-044' });
3343
3381
  } else if (verdict !== 'conforms' && verdict !== 'untemplated' && !accepted) {
3344
- throw new ValidationError(`restore_doc: retained revision ${version} of ${doc_id} was not conforming. Nothing was written.`);
3382
+ throw new ValidationError(`restore_doc: retained revision ${version} of ${doc_id} was not conforming. Nothing was written.`, { code: 'EMET-DOC-045' });
3345
3383
  }
3346
3384
  const current = await readDoc(doc_id, logger).catch(() => null);
3347
3385
  const checked = validateDocument(doc_id, prior.content, current && current.content);
3348
3386
  const lost = (checked.failures || []).filter((f) => /no disposition/.test(f));
3349
3387
  if (doc_id === stateDoc() && (await unretiredBootDrops(options && options.session_id)).length) {
3350
- throw new ValidationError('restore_doc: unhandled drops were listed at this session boot and must be retired with retire_doc before the board is restored. Nothing was written.');
3388
+ throw new ValidationError('restore_doc: unhandled drops were listed at this session boot and must be retired with retire_doc before the board is restored. Nothing was written.', { code: 'EMET-MEM-026' });
3351
3389
  }
3352
3390
  const written = await writeDoc(doc_id, prior.content, updated_by, null, logger, { restore_of: version, reason, session_id: options && options.session_id, supersedes: current && current.version });
3353
3391
  return { ...written, rows_lost: lost, restored_from_version: version };
@@ -3368,7 +3406,7 @@ export async function validateDoc(options = {}, logger = null) {
3368
3406
  if (!doc_id && !content) {
3369
3407
  throw new ValidationError(
3370
3408
  'Give a doc_id to check a stored document, or content (with template_id) to check text that is not stored yet.'
3371
- );
3409
+ , { code: 'EMET-DOC-046' });
3372
3410
  }
3373
3411
 
3374
3412
  if (content) {
@@ -3378,7 +3416,7 @@ export async function validateDoc(options = {}, logger = null) {
3378
3416
  failures: [], warnings: ['No template_id was given and no map entry matches, so nothing governs this content.'] };
3379
3417
  }
3380
3418
  const template = loadShipped(tpl_id);
3381
- if (!template) throw new ValidationError(`No template ${tpl_id} ships with this release.`);
3419
+ if (!template) throw new ValidationError(`No template ${tpl_id} ships with this release.`, { code: 'EMET-DOC-047' });
3382
3420
  const r = checkRecord(content, template, { doc_id });
3383
3421
  return { checked: doc_id || '(content)', template: tpl_id, template_status: template.status,
3384
3422
  verdict: r.failures.length ? CONFORMANCE_VERDICT.NONCONFORMING : CONFORMANCE_VERDICT.CONFORMS,
@@ -3389,7 +3427,7 @@ export async function validateDoc(options = {}, logger = null) {
3389
3427
  const { client, col, hist } = await _docsClient();
3390
3428
  try {
3391
3429
  const doc = await col.findOne({ doc_id });
3392
- if (!doc) throw new ValidationError(`Document not found: ${doc_id}`);
3430
+ if (!doc) throw new ValidationError(`Document not found: ${doc_id}`, { code: 'EMET-DOC-002' });
3393
3431
  // The carry-forward check needs the revision before this one, which is
3394
3432
  // exactly what the history collection archived when this one was written.
3395
3433
  const prior = await hist.find({ doc_id }).sort({ version: -1 }).limit(1).toArray();
@@ -3404,7 +3442,7 @@ export async function validateDoc(options = {}, logger = null) {
3404
3442
  } finally { await client.close(); }
3405
3443
  } catch (error) {
3406
3444
  if (error instanceof ValidationError || error instanceof EmetError) throw error;
3407
- throw new DatabaseError(`Failed to validate document: ${error.message}`, 'validate_doc');
3445
+ throw new DatabaseError(`Failed to validate document: ${error.message}`, 'validate_doc', { code: 'EMET-DB-031' });
3408
3446
  }
3409
3447
  }
3410
3448
 
@@ -3416,24 +3454,30 @@ export async function validateDoc(options = {}, logger = null) {
3416
3454
  */
3417
3455
  export async function acceptNonconformance(doc_id, reason, accepted_by = null, logger = null, options = {}) {
3418
3456
  try {
3457
+ if (typeof doc_id === 'string' && doc_id.startsWith('areas/')) {
3458
+ const { assertAreaOwner } = await import('./pages.js');
3459
+ const opened = await _docsClient();
3460
+ try { await assertAreaOwner(opened.client.db(MONGODB_DB), 'accept_nonconformance'); }
3461
+ finally { await opened.client.close(); }
3462
+ }
3419
3463
  refuseBotMainRecord(doc_id, accepted_by, 'accept_nonconformance');
3420
- if (!doc_id || typeof doc_id !== 'string') throw new ValidationError('doc_id must be a non-empty string');
3464
+ if (!doc_id || typeof doc_id !== 'string') throw new ValidationError('doc_id must be a non-empty string', { code: 'EMET-DOC-001' });
3421
3465
  if (typeof reason !== 'string' || reason.trim().length < 10) {
3422
3466
  throw new ValidationError(
3423
3467
  'An acceptance needs a written reason of at least 10 characters. It is the disposition of ' +
3424
3468
  'record for a nonconformance and is what an audit reads later - the same rule revise_transcript uses.'
3425
- );
3469
+ , { code: 'EMET-DOC-048' });
3426
3470
  }
3427
3471
  const { client, col } = await _docsClient();
3428
3472
  try {
3429
3473
  const doc = await col.findOne({ doc_id });
3430
- if (!doc) throw new ValidationError(`Document not found: ${doc_id}`);
3474
+ if (!doc) throw new ValidationError(`Document not found: ${doc_id}`, { code: 'EMET-DOC-002' });
3431
3475
  const current = doc.conformance;
3432
3476
  if (!current || current.verdict !== CONFORMANCE_VERDICT.NONCONFORMING) {
3433
3477
  throw new ValidationError(
3434
3478
  `${doc_id} version ${doc.version} carries no nonconformance marker, so there is nothing to accept. ` +
3435
3479
  `Its verdict is "${current ? current.verdict : 'not yet checked'}".`
3436
- );
3480
+ , { code: 'EMET-DOC-050' });
3437
3481
  }
3438
3482
  const { currentPersonId, currentClientId } = await import('./persons.js');
3439
3483
  const accepted = buildAcceptance({
@@ -3447,7 +3491,7 @@ export async function acceptNonconformance(doc_id, reason, accepted_by = null, l
3447
3491
  const check = await col.findOne({ doc_id });
3448
3492
  const stored = check && check.conformance && check.conformance.accepted;
3449
3493
  if (!stored || stored.reason !== accepted.reason || Number(stored.covers_version) !== Number(doc.version)) {
3450
- throw new DatabaseError(`The acceptance did not persist on ${doc_id}.`, 'accept_nonconformance');
3494
+ throw new DatabaseError(`The acceptance did not persist on ${doc_id}.`, 'accept_nonconformance', { code: 'EMET-DB-032' });
3451
3495
  }
3452
3496
  return {
3453
3497
  doc_id, verified: true, version: doc.version, covers_version: doc.version,
@@ -3457,7 +3501,7 @@ export async function acceptNonconformance(doc_id, reason, accepted_by = null, l
3457
3501
  } finally { await client.close(); }
3458
3502
  } catch (error) {
3459
3503
  if (error instanceof ValidationError || error instanceof EmetError) throw error;
3460
- throw new DatabaseError(`Failed to accept nonconformance: ${error.message}`, 'accept_nonconformance');
3504
+ throw new DatabaseError(`Failed to accept nonconformance: ${error.message}`, 'accept_nonconformance', { code: 'EMET-DB-033' });
3461
3505
  }
3462
3506
  }
3463
3507
 
@@ -3472,7 +3516,7 @@ export async function acceptNonconformance(doc_id, reason, accepted_by = null, l
3472
3516
 
3473
3517
  function _assertStr(v, name) {
3474
3518
  if (typeof v !== 'string' || v.length === 0) {
3475
- throw new ValidationError(`${name} must be a non-empty string`);
3519
+ throw new ValidationError(`${name} must be a non-empty string`, { code: 'EMET-DOC-051' });
3476
3520
  }
3477
3521
  }
3478
3522
 
@@ -3481,7 +3525,7 @@ function _assertVersion(cur, expected_version, tool) {
3481
3525
  if (cur.version !== expected_version) {
3482
3526
  throw new ValidationError(
3483
3527
  `${tool}: version conflict - document is at v${cur.version}, caller expected v${expected_version}. Re-read and retry.`
3484
- );
3528
+ , { code: 'EMET-DOC-052' });
3485
3529
  }
3486
3530
  }
3487
3531
 
@@ -3489,11 +3533,11 @@ function _assertVersion(cur, expected_version, tool) {
3489
3533
  function _splitUnique(hay, needle, tool, what, doc_id) {
3490
3534
  const parts = hay.split(needle);
3491
3535
  const n = parts.length - 1;
3492
- if (n === 0) throw new ValidationError(`${tool}: ${what} not found in ${doc_id}`);
3536
+ if (n === 0) throw new ValidationError(`${tool}: ${what} not found in ${doc_id}`, { code: 'EMET-DOC-053' });
3493
3537
  if (n > 1) {
3494
3538
  throw new ValidationError(
3495
3539
  `${tool}: ${what} matches ${n} times in ${doc_id} - must match exactly once. Add surrounding context to disambiguate.`
3496
- );
3540
+ , { code: 'EMET-DOC-054' });
3497
3541
  }
3498
3542
  return [parts[0], parts[1]];
3499
3543
  }
@@ -3506,17 +3550,17 @@ export async function patchDoc(doc_id, old_str, new_str, updated_by = null, expe
3506
3550
  if (!(Array.isArray(options.edits) && options.edits.length)) _assertStr(old_str, 'old_str');
3507
3551
  const reason = options && options.reason;
3508
3552
  if (typeof reason !== 'string' || reason.trim().length < 10) {
3509
- throw new ValidationError('patch_doc needs reason (at least 10 characters). Nothing was written.');
3553
+ throw new ValidationError('patch_doc needs reason (at least 10 characters). Nothing was written.', { code: 'EMET-DOC-055' });
3510
3554
  }
3511
3555
  const cur = await readDoc(doc_id, logger);
3512
3556
  _assertVersion(cur, expected_version, 'patch_doc');
3513
- if (isDropDoc(doc_id)) throw new ValidationError('patch_doc: a drop is write-once. Use a new id. Nothing was written.');
3557
+ if (isDropDoc(doc_id)) throw new ValidationError('patch_doc: a drop is write-once. Use a new id. Nothing was written.', { code: 'EMET-DOC-056' });
3514
3558
  const edits = Array.isArray(options.edits) && options.edits.length
3515
3559
  ? options.edits
3516
3560
  : [{ old_str, new_str }];
3517
3561
  for (const edit of edits) {
3518
- if (typeof edit.old_str !== 'string' || edit.old_str.length === 0) throw new ValidationError('old_str must be a non-empty string');
3519
- if (typeof edit.new_str !== 'string') throw new ValidationError('new_str must be a string (empty string allowed = delete)');
3562
+ if (typeof edit.old_str !== 'string' || edit.old_str.length === 0) throw new ValidationError('old_str must be a non-empty string', { code: 'EMET-DOC-057' });
3563
+ if (typeof edit.new_str !== 'string') throw new ValidationError('new_str must be a string (empty string allowed = delete)', { code: 'EMET-DOC-058' });
3520
3564
  _splitUnique(cur.content, edit.old_str, 'patch_doc', 'old_str', doc_id);
3521
3565
  }
3522
3566
  const spans = edits.map((edit) => {
@@ -3525,18 +3569,18 @@ export async function patchDoc(doc_id, old_str, new_str, updated_by = null, expe
3525
3569
  });
3526
3570
  const ordered = [...spans].sort((a, b) => a.at - b.at);
3527
3571
  for (let i = 1; i < ordered.length; i++) {
3528
- if (ordered[i].at < ordered[i - 1].at + ordered[i - 1].len) throw new ValidationError('patch_doc: edits overlap. Nothing was written.');
3572
+ if (ordered[i].at < ordered[i - 1].at + ordered[i - 1].len) throw new ValidationError('patch_doc: edits overlap. Nothing was written.', { code: 'EMET-DOC-059' });
3529
3573
  }
3530
3574
  let next = cur.content;
3531
3575
  for (const span of [...spans].sort((a, b) => b.at - a.at)) next = next.slice(0, span.at) + span.new_str + next.slice(span.at + span.len);
3532
3576
  if (doc_id === stateDoc()) {
3533
- if ((await unretiredBootDrops(options && options.session_id)).length) throw new ValidationError('patch_doc: unhandled drops were listed at this session boot and must be retired with retire_doc before the board is edited. Nothing was written.');
3577
+ if ((await unretiredBootDrops(options && options.session_id)).length) throw new ValidationError('patch_doc: unhandled drops were listed at this session boot and must be retired with retire_doc before the board is edited. Nothing was written.', { code: 'EMET-MEM-027' });
3534
3578
  const ids = (text) => new Set([...String(text || '').matchAll(/\bB-\d+\b/g)].map((m) => m[0]));
3535
3579
  const added = [...ids(next)].filter((id) => !ids(cur.content).has(id));
3536
- if (added.length && !(options && options.origin)) throw new ValidationError('patch_doc: an added board row needs origin. Nothing was written.');
3580
+ if (added.length && !(options && options.origin)) throw new ValidationError('patch_doc: an added board row needs origin. Nothing was written.', { code: 'EMET-MEM-028' });
3537
3581
  const checked = validateDocument(doc_id, next, cur.content);
3538
3582
  if (checked && checked.verdict === 'nonconforming') {
3539
- throw new ValidationError(`patch_doc: the board edit is nonconforming. ${(checked.failures || []).join('; ')} Nothing was written.`);
3583
+ throw new ValidationError(`patch_doc: the board edit is nonconforming. ${(checked.failures || []).join('; ')} Nothing was written.`, { code: 'EMET-MEM-029' });
3540
3584
  }
3541
3585
  }
3542
3586
  const res = await writeDoc(doc_id, next, updated_by, null, logger, { edited: true, reason, origin: options.origin || null, session_id: options.session_id || null });
@@ -3544,11 +3588,11 @@ export async function patchDoc(doc_id, old_str, new_str, updated_by = null, expe
3544
3588
  size_delta: next.length - cur.content.length };
3545
3589
  } catch (error) {
3546
3590
  if (error instanceof ValidationError || error instanceof EmetError) throw error;
3547
- throw new DatabaseError(`Failed to patch document: ${error.message}`, 'patch_doc');
3591
+ throw new DatabaseError(`Failed to patch document: ${error.message}`, 'patch_doc', { code: 'EMET-DB-034' });
3548
3592
  }
3549
3593
  }
3550
3594
 
3551
- // Restored 2026-09-19: both constants were dropped in commit-685d822 while the function
3595
+ // Restored 2026-09-19: both constants were dropped in an earlier commit while the function
3552
3596
  // kept referencing them, which made every semantic_recall call throw
3553
3597
  // "SEMANTIC_RECALL_LAYERS is not defined".
3554
3598
  const SEMANTIC_RECALL_LAYERS = ['episodic', 'semantic', 'procedural', 'meta', 'identity', 'working'];
@@ -3557,10 +3601,10 @@ const SEMANTIC_RECALL_INDEX = process.env.EMET_VECTOR_INDEX || 'emet_content_aut
3557
3601
  export async function semanticRecall(query, layer = null, limit = 10, logger = null, options = null, dbManager = null) {
3558
3602
  try {
3559
3603
  if (!query || typeof query !== 'string' || query.trim() === '') {
3560
- throw new ValidationError('query', 'query must be a non-empty string');
3604
+ throw new ValidationError('query', 'query must be a non-empty string', { code: 'EMET-MEM-030' });
3561
3605
  }
3562
3606
  if (query.length > CONTENT_LIMITS.MAX_QUERY_LENGTH) {
3563
- throw new ValidationError('query', `query exceeds maximum length of ${CONTENT_LIMITS.MAX_QUERY_LENGTH}`);
3607
+ throw new ValidationError('query', `query exceeds maximum length of ${CONTENT_LIMITS.MAX_QUERY_LENGTH}`, { code: 'EMET-VAL-008' });
3564
3608
  }
3565
3609
  const validatedLimit = validateLimit(limit);
3566
3610
  const layers = layer ? [validateLayer(layer)] : SEMANTIC_RECALL_LAYERS;
@@ -3621,7 +3665,7 @@ export async function semanticRecall(query, layer = null, limit = 10, logger = n
3621
3665
  } finally { if (client) await client.close(); }
3622
3666
  } catch (error) {
3623
3667
  if (error instanceof ValidationError || error instanceof EmetError) throw error;
3624
- throw new DatabaseError(`Failed semantic recall: ${error.message}`, 'semantic_recall');
3668
+ throw new DatabaseError(`Failed semantic recall: ${error.message}`, 'semantic_recall', { code: 'EMET-DB-035' });
3625
3669
  }
3626
3670
  }
3627
3671
 
@@ -3648,15 +3692,15 @@ const CORPUS_VALUES = (process.env.EMET_CORPORA || '').split(',').map(s => s.tri
3648
3692
  export async function corpusRecall(query, corpus = null, limit = 5, logger = null) {
3649
3693
  try {
3650
3694
  if (!query || typeof query !== 'string' || query.trim() === '') {
3651
- throw new ValidationError('query', 'query must be a non-empty string');
3695
+ throw new ValidationError('query', 'query must be a non-empty string', { code: 'EMET-MEM-030' });
3652
3696
  }
3653
3697
  if (query.length > CONTENT_LIMITS.MAX_QUERY_LENGTH) {
3654
- throw new ValidationError('query', `query exceeds maximum length of ${CONTENT_LIMITS.MAX_QUERY_LENGTH}`);
3698
+ throw new ValidationError('query', `query exceeds maximum length of ${CONTENT_LIMITS.MAX_QUERY_LENGTH}`, { code: 'EMET-VAL-008' });
3655
3699
  }
3656
3700
  const validatedLimit = Math.min(Math.max(parseInt(limit) || 5, 1), 25);
3657
3701
  // An empty EMET_CORPORA means "unrestricted", not "nothing allowed".
3658
3702
  if (corpus && CORPUS_VALUES.length && !CORPUS_VALUES.includes(corpus)) {
3659
- throw new ValidationError('corpus', `corpus must be one of: ${CORPUS_VALUES.join(', ')}`);
3703
+ throw new ValidationError('corpus', `corpus must be one of: ${CORPUS_VALUES.join(', ')}`, { code: 'EMET-MEM-032' });
3660
3704
  }
3661
3705
  const client = await connectMongo(MONGODB_URI, { serverSelectionTimeoutMS: 5000, maxPoolSize: 10 });
3662
3706
  try {
@@ -3701,7 +3745,7 @@ export async function corpusRecall(query, corpus = null, limit = 5, logger = nul
3701
3745
  } finally { await client.close(); }
3702
3746
  } catch (error) {
3703
3747
  if (error instanceof ValidationError || error instanceof EmetError) throw error;
3704
- throw new DatabaseError(`Failed corpus recall: ${error.message}`, 'corpus_recall');
3748
+ throw new DatabaseError(`Failed corpus recall: ${error.message}`, 'corpus_recall', { code: 'EMET-DB-036' });
3705
3749
  }
3706
3750
  }
3707
3751
 
@@ -3732,35 +3776,36 @@ export {
3732
3776
  * and is the owner. HTTP still requires a loaded person whose role is owner.
3733
3777
  * An in-process actor that names a person is checked the same way.
3734
3778
  */
3735
- async function codeCreator(dbManager, refusal) {
3779
+ async function codeCreator(dbManager) {
3736
3780
  const { currentActor, getPerson } = await import('./persons.js');
3737
3781
  const actor = currentActor();
3738
3782
  if (actor.transport === 'stdio' || (actor.transport !== 'http' && !actor.personId)) {
3739
3783
  return actor.personId || LOCAL_SUBJECT;
3740
3784
  }
3741
- if (!actor.personId) throw new ValidationError(refusal);
3785
+ if (!actor.personId) return null;
3742
3786
  const person = await getPerson(dbManager.db, actor.personId);
3743
- if (!person || person.role !== 'owner') throw new ValidationError(refusal);
3787
+ if (!person || person.role !== 'owner') return null;
3744
3788
  return actor.personId;
3745
3789
  }
3746
3790
 
3747
3791
  export async function inviteCreate(dbManager, { display_name, scopes, days, source } = {}, logger = null) {
3748
3792
  if (!display_name || !String(display_name).trim()) {
3749
- throw new ValidationError('display_name is required — the name the guest will be known by');
3793
+ throw new ValidationError('display_name is required — the name the guest will be known by', { code: 'EMET-AUTH-029' });
3750
3794
  }
3751
3795
  await dbManager.getConnection('working');
3752
3796
  const { createInvite, INVITES_FROZEN, INVITES_FROZEN_REASON } = await import('./invites.js');
3753
- if (INVITES_FROZEN) throw new ValidationError(INVITES_FROZEN_REASON);
3797
+ if (INVITES_FROZEN) throw new ValidationError(INVITES_FROZEN_REASON, { code: 'EMET-AUTH-030' });
3754
3798
  const { registeredSourceTags } = await import('./setup.js');
3755
- const actor = await codeCreator(dbManager, 'Only the owner can create invites');
3799
+ const actor = await codeCreator(dbManager);
3800
+ if (!actor) throw new ValidationError('Only the owner can create invites', { code: 'EMET-AUTH-036' });
3756
3801
  const requested = Array.isArray(scopes) ? scopes : ['emet.read'];
3757
3802
  if (requested.length !== 1 || requested[0] !== 'emet.read') {
3758
- throw new ValidationError('A guest invite accepts only emet.read');
3803
+ throw new ValidationError('A guest invite accepts only emet.read', { code: 'EMET-AUTH-031' });
3759
3804
  }
3760
3805
  const registry = registeredSourceTags();
3761
3806
  const tag = typeof source === 'string' ? source.trim() : '';
3762
3807
  if (registry.length && tag && !registry.includes(tag)) {
3763
- throw new ValidationError('source', 'A guest invite source must be a registered tag. Nothing was created.');
3808
+ throw new ValidationError('source', 'A guest invite source must be a registered tag. Nothing was created.', { code: 'EMET-AUTH-032' });
3764
3809
  }
3765
3810
  const out = await createInvite(dbManager.db, {
3766
3811
  created_by: actor,
@@ -3778,17 +3823,18 @@ export async function inviteCreate(dbManager, { display_name, scopes, days, sour
3778
3823
 
3779
3824
  export async function memberAccessCreate(dbManager, { display_name, days, source } = {}, logger = null) {
3780
3825
  if (!display_name || !String(display_name).trim()) {
3781
- throw new ValidationError('display_name is required \u2014 the name the member will be known by');
3826
+ throw new ValidationError('display_name is required \u2014 the name the member will be known by', { code: 'EMET-AUTH-033' });
3782
3827
  }
3783
3828
  await dbManager.getConnection('working');
3784
3829
  const { createMemberAccess, MEMBER_ACCESS_FROZEN, MEMBER_ACCESS_FROZEN_REASON } = await import('./invites.js');
3785
- if (MEMBER_ACCESS_FROZEN) throw new ValidationError(MEMBER_ACCESS_FROZEN_REASON);
3830
+ if (MEMBER_ACCESS_FROZEN) throw new ValidationError(MEMBER_ACCESS_FROZEN_REASON, { code: 'EMET-AUTH-034' });
3786
3831
  const { registeredSourceTags } = await import('./setup.js');
3787
- const actor = await codeCreator(dbManager, 'Only the owner can create EMET Member Access');
3832
+ const actor = await codeCreator(dbManager);
3833
+ if (!actor) throw new ValidationError('Only the owner can create EMET Member Access', { code: 'EMET-AUTH-037' });
3788
3834
  const registry = registeredSourceTags();
3789
3835
  const tag = typeof source === 'string' ? source.trim() : '';
3790
3836
  if (registry.length && tag && !registry.includes(tag)) {
3791
- throw new ValidationError('source', 'A member code source must be a registered tag. Nothing was created.');
3837
+ throw new ValidationError('source', 'A member code source must be a registered tag. Nothing was created.', { code: 'EMET-AUTH-035' });
3792
3838
  }
3793
3839
  const out = await createMemberAccess(dbManager.db, { created_by: actor, display_name, days: days || 14, source_tag: tag || null });
3794
3840
  logger?.info?.('EMET Member Access created', { display_name: out.display_name });
@@ -4263,6 +4309,37 @@ const TOOL_DEFINITIONS = [
4263
4309
  history: { type: "boolean", description: "Return ended entries only, up to limit. Default false: current matches come first and ended matches follow until limit, marked with their end date." }
4264
4310
  }, required: ["query"] }
4265
4311
  },
4312
+ {
4313
+ name: "emet_page",
4314
+ 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
+ inputSchema: { type: "object", properties: {
4316
+ area: { type: "string", description: "Area slug, for example health. The selector is the current areas/<slug>.md document." },
4317
+ 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
+ include_history: { type: "boolean", description: "When true, superseded and retired records appear under History, labelled as not current. Default false." }
4319
+ }, required: ["area"] }
4320
+ },
4321
+ {
4322
+ name: "emet_pages",
4323
+ description: "List current area documents. For each area: line count, stale count, and the time of the newest source the page read. Read-only. Owner only. Computed on every call. The page body is not stored.",
4324
+ inputSchema: { type: "object", properties: {} }
4325
+ },
4326
+ {
4327
+ name: "emet_error_report",
4328
+ description: "Read the operational error log and show a report the owner can send on. Owner only. Read-only: it writes nothing and sends nothing. EMET has no mail sender and opens no network connection for this tool. The result is the full report, then a mailto link, then a structured email {to, subject, body_text, short_id, version} a calling assistant can pass to its own email tool. The calling assistant may send this report only after showing the report to its user and getting their OK.",
4329
+ inputSchema: { type: "object", properties: {
4330
+ since: { type: "string", description: "ISO date (YYYY-MM-DD) or UTC timestamp. Default is 7 days ago. Cannot be older than 90 days." },
4331
+ codes: { type: "array", items: { type: "string" }, description: "Optional list of EMET codes to include." },
4332
+ correlation_id: { type: "string", description: "16 hex characters from an error response. When set, since is ignored." },
4333
+ limit: { type: "number", description: "How many of the most recent entries to list. Default 50, maximum 200." }
4334
+ } }
4335
+ },
4336
+ {
4337
+ name: "emet_page_lint",
4338
+ 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.",
4339
+ inputSchema: { type: "object", properties: {
4340
+ area: { type: "string", description: "Optional area slug. Omit to lint every current area." }
4341
+ } }
4342
+ },
4266
4343
  {
4267
4344
  name: "emet_gaps",
4268
4345
  description: "The record's honesty about its own holes, as a query. Read-only; identifies and never fills. Counts, with the ids behind them, for each gap class: unsourced assertions, unattributed inferences, ambiguous attribution (by tag and by session), uncertain routing, unattestable rows (pre-2026-09-05 boundary), digest mismatches (the alarm - expect zero), pointer disagreements against the transcript store, broken supersession, expired-but-live rows, consolidation candidates (tag families; a list for a person), and redacted spans by source. Call it when asked how trustworthy the record is, before a consolidation pass, or after any migration. Closing a gap is a person's decision: revise_memory with a real derived_from where the source is knowable; otherwise the gap stands as a fact.",