@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/server.json CHANGED
@@ -2,8 +2,8 @@
2
2
  "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
3
3
  "name": "io.github.dreamforgestudiollc/emet",
4
4
  "title": "EMET",
5
- "description": "0.2.6. Free MIT; no account, key, or payment. Verifies the record, not the computation.",
6
- "version": "0.2.6",
5
+ "description": "0.3.0. Free MIT; no account, key, or payment. Verifies the record, not the computation.",
6
+ "version": "0.3.0",
7
7
  "websiteUrl": "https://dreamforgestudiollc.github.io/EMET/",
8
8
  "repository": {
9
9
  "url": "https://github.com/dreamforgestudiollc/EMET",
@@ -22,7 +22,7 @@
22
22
  "registryType": "npm",
23
23
  "registryBaseUrl": "https://registry.npmjs.org",
24
24
  "identifier": "@dreamforgestudiollc/emet",
25
- "version": "0.2.6",
25
+ "version": "0.3.0",
26
26
  "transport": {
27
27
  "type": "stdio"
28
28
  },
@@ -42,11 +42,15 @@
42
42
  "accept_nonconformance",
43
43
  "corpus_recall",
44
44
  "emet_client_approve",
45
+ "emet_error_report",
45
46
  "emet_floor",
46
47
  "emet_gaps",
47
48
  "emet_initialize",
48
49
  "emet_invite_create",
49
50
  "emet_member_access_create",
51
+ "emet_page",
52
+ "emet_page_lint",
53
+ "emet_pages",
50
54
  "emet_session_close",
51
55
  "emet_session_open",
52
56
  "emet_setup_complete",
package/src/aleph.js CHANGED
@@ -33,6 +33,7 @@
33
33
 
34
34
  import crypto from 'crypto';
35
35
  import { EmetError, ErrorCodes, StatusCodes } from './database.js';
36
+ import { isEmetCodeOptions } from './error-codes.js';
36
37
 
37
38
  /** sha256 of a string, hex. The canonical digest for everything EMET stores. */
38
39
  export function digest(text) {
@@ -41,10 +42,15 @@ export function digest(text) {
41
42
 
42
43
  export class AlephError extends EmetError {
43
44
  constructor(message, operation = 'unknown', details = {}) {
44
- super(message, ErrorCodes.WRITE_ERROR, StatusCodes.INTERNAL_ERROR, details);
45
+ let emetCode;
46
+ let det = details;
47
+ if (isEmetCodeOptions(arguments[3])) emetCode = arguments[3].code;
48
+ if (isEmetCodeOptions(det)) { emetCode = det.code; det = {}; }
49
+ super(message, ErrorCodes.WRITE_ERROR, StatusCodes.INTERNAL_ERROR, det);
45
50
  this.name = 'AlephError';
46
51
  this.operation = operation;
47
52
  this.verified = false;
53
+ if (emetCode) this.emetCode = emetCode;
48
54
  }
49
55
 
50
56
  toSafeJSON() {
@@ -75,7 +81,7 @@ export function verifyDocument(readBack, expected) {
75
81
  `success and the store does not contain it.`,
76
82
  'aleph.verifyDocument',
77
83
  { doc_id }
78
- );
84
+ , { code: 'EMET-GEM-001' });
79
85
  }
80
86
  if (readBack.sha256 !== sha256) {
81
87
  throw new AlephError(
@@ -84,7 +90,7 @@ export function verifyDocument(readBack, expected) {
84
90
  `actually there.`,
85
91
  'aleph.verifyDocument',
86
92
  { doc_id, expected_sha256: sha256, stored_sha256: readBack.sha256 }
87
- );
93
+ , { code: 'EMET-GEM-002' });
88
94
  }
89
95
  if (version !== undefined && readBack.version !== version) {
90
96
  throw new AlephError(
@@ -92,7 +98,7 @@ export function verifyDocument(readBack, expected) {
92
98
  `created. Another writer reached the document between the write and the read.`,
93
99
  'aleph.verifyDocument',
94
100
  { doc_id, expected_version: version, stored_version: readBack.version }
95
- );
101
+ , { code: 'EMET-GEM-003' });
96
102
  }
97
103
  return { verified: true, doc_id, sha256, version };
98
104
  }
@@ -119,7 +125,7 @@ export function verifyLayerEntry(readBack, expected) {
119
125
  `reported success and the store does not contain it.`,
120
126
  'aleph.verifyLayerEntry',
121
127
  { layer, id }
122
- );
128
+ , { code: 'EMET-GEM-004' });
123
129
  }
124
130
  const wrote = digest(content);
125
131
  const stored = digest(readBack.content !== undefined && readBack.content !== null
@@ -137,7 +143,7 @@ export function verifyLayerEntry(readBack, expected) {
137
143
  `The row is internally inconsistent - either the content or the digest was altered after the write.`,
138
144
  'aleph.verifyLayerEntry',
139
145
  { layer, id, column_sha256: storedColumn, content_sha256: stored }
140
- );
146
+ , { code: 'EMET-GEM-005' });
141
147
  }
142
148
 
143
149
  if (stored !== wrote) {
@@ -148,7 +154,7 @@ export function verifyLayerEntry(readBack, expected) {
148
154
  `collection prefix before writing anything else to this store.`,
149
155
  'aleph.verifyLayerEntry',
150
156
  { layer, id, expected_sha256: wrote, stored_sha256: stored }
151
- );
157
+ , { code: 'EMET-GEM-006' });
152
158
  }
153
159
  // C1 (2026-09-07): the metadata column, when present, must agree with the
154
160
  // metadata it sits beside, and with what the caller says it wrote. Same
@@ -169,7 +175,7 @@ export function verifyLayerEntry(readBack, expected) {
169
175
  `The row is internally inconsistent - either the metadata or its digest was altered after the write.`,
170
176
  'aleph.verifyLayerEntry',
171
177
  { layer, id, column_metadata_sha256: metaColumn, metadata_sha256: storedMeta }
172
- );
178
+ , { code: 'EMET-GEM-007' });
173
179
  }
174
180
  metadataDigestStored = true;
175
181
  metadataSha256 = metaColumn;
@@ -182,7 +188,7 @@ export function verifyLayerEntry(readBack, expected) {
182
188
  `Read-back of ${layer} entry ${id} returned different metadata than was written.`,
183
189
  'aleph.verifyLayerEntry',
184
190
  { layer, id, expected_metadata_sha256: wroteMeta, stored_metadata_sha256: storedMeta }
185
- );
191
+ , { code: 'EMET-GEM-008' });
186
192
  }
187
193
  metadataSha256 = wroteMeta;
188
194
  }
@@ -344,7 +350,7 @@ export function signatureIntegrityOf(row, key) {
344
350
 
345
351
  /**
346
352
  * May a row be RE-SIGNED after one of the sanctioned metadata marks? (2026-10-02,
347
- * the tester's finding: the marks re-attested metadata_sha256 but left the
353
+ * the reviewer's finding: the marks re-attested metadata_sha256 but left the
348
354
  * signature over the old metadata digest, so every superseded or corrected
349
355
  * row read signed:false.)
350
356
  *
@@ -1,3 +1,4 @@
1
+ import { CodedError } from './error-codes.js';
1
2
  /**
2
3
  * EMET - Enduring Memory & Epistemic Tiers
3
4
  * Copyright (c) 2026 Dreamforge Studio LLC
@@ -69,6 +70,10 @@ const ANNOTATION_TABLE = {
69
70
  read_doc_history: { title: 'Read a retained document revision', ...READ },
70
71
  list_docs: { title: 'List documents', ...READ },
71
72
  emet_gaps: { title: 'Count the record\'s gaps', ...READ },
73
+ emet_page: { title: 'Read a topic page', ...READ },
74
+ emet_pages: { title: 'List topic pages', ...READ },
75
+ emet_page_lint: { title: 'Lint topic pages', ...READ },
76
+ emet_error_report: { title: 'Error report', ...READ },
72
77
  emet_floor: { title: 'Read the floor', ...READ },
73
78
  // Checks a document against its template and writes nothing - not even the
74
79
  // verdict. The write path stores that; this is the same check, borrowed.
@@ -76,7 +81,7 @@ const ANNOTATION_TABLE = {
76
81
 
77
82
  // --- Additive writes. These add; they do not remove or replace. -----------
78
83
  // Was READ until 2026-09-27: "it does not write anything itself". Since the
79
- // blocked-close cap (commit-82bb76c) it records each blocked attempt in
84
+ // blocked-close cap it records each blocked attempt in
80
85
  // close_attempts, so a read-only hint would be untrue (code audit, 1.3).
81
86
  emet_session_close: { title: 'Check session is saved', ...ADD },
82
87
  emet_client_approve: { title: 'Approve a new client', ...REPLACE },
@@ -159,10 +164,10 @@ export const TOOL_ANNOTATIONS = new Proxy(ANNOTATION_TABLE, {
159
164
  export function annotate(tools) {
160
165
  const missing = tools.filter((tool) => !TOOL_ANNOTATIONS[tool.name]).map((tool) => tool.name);
161
166
  if (missing.length > 0) {
162
- throw new Error(
167
+ throw new CodedError(
163
168
  `Tools declared with no annotation entry: ${missing.join(', ')}. ` +
164
169
  `Add them to TOOL_ANNOTATIONS in src/annotations.js.`
165
- );
170
+ , { code: 'EMET-TOOL-001' });
166
171
  }
167
172
  return tools.map((tool) => ({ ...tool, annotations: TOOL_ANNOTATIONS[tool.name] }));
168
173
  }
package/src/atlas-role.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { CodedError } from './error-codes.js';
1
2
  /**
2
3
  * EMET - the least-privilege MongoDB Atlas role for the server's own login
3
4
  * (2026-09-29; security audit question 9, staging/emet-security-audit.md).
@@ -18,6 +19,8 @@
18
19
  * are credentials, not the record.
19
20
  * - _emet_verify: the status probe writes one document, reads it back, and
20
21
  * deletes that document (setup.js verifyConnection). The collection stays.
22
+ * - error_log: rotation removes old operational rows after a daily summary
23
+ * is kept (error-log.js rotateErrorLog). This is bookkeeping, not the record.
21
24
  * Everything else - memory layers, documents, their history, transcripts - is
22
25
  * find / insert / update only.
23
26
  */
@@ -41,13 +44,15 @@ export const DATABASE_ACTIONS = Object.freeze([
41
44
  */
42
45
  export const DELETE_ALLOWED = Object.freeze({
43
46
  '{prefix}oauth_tokens': Object.freeze(['REMOVE']),
44
- _emet_verify: Object.freeze(['REMOVE'])
47
+ _emet_verify: Object.freeze(['REMOVE']),
48
+ // Unprefixed, like the probe. Operational error log, not the record.
49
+ error_log: Object.freeze(['REMOVE'])
45
50
  });
46
51
 
47
52
  /** Privileges in the Atlas CLI form ACTION@db or ACTION@db.collection. */
48
53
  export function atlasPrivileges(dbName, prefix = 'emet_') {
49
- if (!dbName || typeof dbName !== 'string' || /[\s@.]/.test(dbName)) throw new Error('database name must be a plain name');
50
- if (typeof prefix !== 'string' || /[\s@.]/.test(prefix)) throw new Error('prefix must be a plain name');
54
+ if (!dbName || typeof dbName !== 'string' || /[\s@.]/.test(dbName)) throw new CodedError('database name must be a plain name', { code: 'EMET-CFG-001' });
55
+ if (typeof prefix !== 'string' || /[\s@.]/.test(prefix)) throw new CodedError('prefix must be a plain name', { code: 'EMET-CFG-002' });
51
56
  const out = DATABASE_ACTIONS.map((a) => `${a}@${dbName}`);
52
57
  for (const [col, actions] of Object.entries(DELETE_ALLOWED)) {
53
58
  for (const a of actions) out.push(`${a}@${dbName}.${col.replace('{prefix}', prefix)}`);
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * EMET - attribution per session, v2 (2026-10-12).
3
3
  *
4
- * Alex approved PROPOSAL.md with its 7 defaults;
5
- * v1 (PR 32) was reverted after the reviewer's review (A1-A4). This version:
4
+ * Alex approved PROPOSAL.md (the attribution proposal) with its 7 defaults;
5
+ * v1 (PR 32) was reverted after the second reader's review (A1-A4). This version:
6
6
  *
7
7
  * STAMP vs RIGHTS. Several agents share one OAuth login (the Grok client
8
8
  * 8xm-7ILLKEDFc3-QRxqlgw). A bot's declared tag is what its writes are
@@ -39,9 +39,9 @@ export const APPROVALS_DOC = 'emet/CLIENT_APPROVALS.md';
39
39
  export const WRITE_TOOLS = new Set([
40
40
  'save_to_layer', 'revise_memory', 'write_doc', 'patch_doc', 'retire_doc', 'rename_doc', 'restore_doc',
41
41
  'accept_nonconformance', 'emet_transcript_append', 'save_transcript', 'revise_transcript', 'emet_session_close',
42
- // the reviewer's re-review (2026-10-12): opening a session claims it; deciding a client is a write.
42
+ // the second reader's re-review (2026-10-12): opening a session claims it; deciding a client is a write.
43
43
  'emet_session_open', 'emet_client_approve',
44
- // the reviewer's PR 47 review: setup writes durable identity and board docs.
44
+ // the second reader's PR 47 review: setup writes durable identity and board docs.
45
45
  'emet_setup_complete'
46
46
  ]);
47
47
  /** Tools the strict login tag also covers. emet_initialize can provision, so a
@@ -119,7 +119,7 @@ function remember(d, clientId, tag, { declared_name = null, basis = null, at, re
119
119
  if (renamed_from && row.tags[renamed_from]) row.tags[renamed_from] = { ...row.tags[renamed_from], retired: true, renamed_to: tag, retired_at: at };
120
120
  }
121
121
 
122
- /** Strict: returns null when the record does not parse (fail closed, the reviewer 4). */
122
+ /** Strict: returns null when the record does not parse (fail closed, the second reader 4). */
123
123
  export function parseApprovals(content) {
124
124
  const m = /```json\n([\s\S]*?)\n```/.exec(String(content || ''));
125
125
  if (!m) return null;
@@ -160,7 +160,7 @@ export async function loadApprovals(deps, { fresh = false } = {}) {
160
160
  }
161
161
 
162
162
  /**
163
- * Compare-and-set (the reviewer 3): mutations run one at a time in this process, each
163
+ * Compare-and-set (the second reader 3): mutations run one at a time in this process, each
164
164
  * re-reads the record and writes with the version it read; a version moved by
165
165
  * another writer is retried on the fresh copy. `fn(data)` returns false to write nothing.
166
166
  */
@@ -197,7 +197,7 @@ export function personIsOwner(actor, ownerId) {
197
197
  }
198
198
 
199
199
  /**
200
- * The owner acting as the owner (the reviewer A2 re-review). Over HTTP the person must be
200
+ * The owner acting as the owner (the second reader A2 re-review). Over HTTP the person must be
201
201
  * the owner AND the call must carry the login's own tag (no declared or
202
202
  * generated tag) AND that tag must not be a bot tag. Every bot on the owner's
203
203
  * shared login is therefore not the owner. Stdio is the local owner.
@@ -247,7 +247,7 @@ export function bindSession(base, tag, extra = {}) {
247
247
  SESSION_BINDINGS.set(base, { agent_tag: tag, ...extra, bound_at: new Date() });
248
248
  }
249
249
 
250
- /** Tags already on the session's stored rows (A4: survives a restart). Read only; fails closed (the reviewer A4). */
250
+ /** Tags already on the session's stored rows (A4: survives a restart). Read only; fails closed (the second reader A4). */
251
251
  export async function storedSessionTags(db, base, layerCollections = []) {
252
252
  if (!base) return [];
253
253
  if (!db) throw refusal(`the store cannot be read to check who owns session ${base}; nothing was written.`);
@@ -482,8 +482,8 @@ export function approvalsView(data, actor, ownerId) {
482
482
 
483
483
  /**
484
484
  * emet_client_approve. Only the owner acting as the owner, or the configured
485
- * COS on its own login tag; never the client deciding itself (the reviewer 1).
486
- * Idempotent: the same decision again writes nothing (the reviewer 2).
485
+ * COS on its own login tag; never the client deciding itself (the second reader 1).
486
+ * Idempotent: the same decision again writes nothing (the second reader 2).
487
487
  */
488
488
  export async function clientApprove(deps, actor, ownerId, { tag, decision, reason, as, from } = {}, _registry = [], now = new Date()) {
489
489
  const t = typeof tag === 'string' ? tag.trim() : '';
@@ -502,7 +502,7 @@ export async function clientApprove(deps, actor, ownerId, { tag, decision, reaso
502
502
  const by = ownerOk ? `owner (${actor && actor.personId || 'local'})` : `cos ${cosTag()}`;
503
503
  let result = null;
504
504
  await mutateApprovals(deps, (d) => {
505
- // the reviewer round 3: whatever path made the caller "owner" or "COS", it may never
505
+ // the second reader round 3: whatever path made the caller "owner" or "COS", it may never
506
506
  // decide a request that its own connection queued (same client_id or same
507
507
  // grant), nor a tag equal to its own. A bot on a shared login that omits
508
508
  // `source` looks like the login; this catches it.
@@ -512,7 +512,7 @@ export async function clientApprove(deps, actor, ownerId, { tag, decision, reaso
512
512
  const sameGrant = !!req.grant_id && req.grant_id === (actor.grantId || null);
513
513
  if (sameClient || sameGrant) throw refusal('emet_client_approve: this connection queued the request for "' + t + '", so it may not decide it. Decide from another client. Nothing was changed.');
514
514
  }
515
- // the reviewer delta M2: a client_id that already has approved tags needs an explicit
515
+ // the second reader delta M2: a client_id that already has approved tags needs an explicit
516
516
  // `as` ('add' keeps every sibling, 'rename' retires one named tag).
517
517
  const cidReq = (d.pending[t] && d.pending[t].client_id) || null;
518
518
  const siblings = decision === 'approve' && cidReq ? rememberedFor(d, cidReq).filter((x) => x !== t) : [];
@@ -33,6 +33,7 @@ import fs from 'fs';
33
33
  import path from 'path';
34
34
  import { resolveModulePath } from './module-path.js';
35
35
  import { setting } from './env.js';
36
+ import { CodedError } from './error-codes.js';
36
37
 
37
38
  const HERE = resolveModulePath(import.meta.url);
38
39
 
@@ -257,7 +258,8 @@ export function baseMap() {
257
258
  'seeds/': 'templates/SEED.md',
258
259
  'threads/': 'templates/THREAD.md',
259
260
  'staging/': 'templates/STAGING.md',
260
- 'procedures/': 'templates/PROCEDURE.md'
261
+ 'procedures/': 'templates/PROCEDURE.md',
262
+ 'areas/': 'templates/AREA.md'
261
263
  }
262
264
  };
263
265
  }
@@ -369,7 +371,7 @@ function idCell(row, idIndex) {
369
371
  * a closed row named in a note, an item cross-referenced in a next action -
370
372
  * read as a row of its own, so the carry-forward check reported it missing
371
373
  * from the next revision. Found by running the validator against the reference
372
- * install's own board, 2026-09-11: board 012 and board 050 were both closed on the
374
+ * install's own board, 2026-09-11: board 12 and board 50 were both closed on the
373
375
  * prior revision and appeared only inside another row's text.
374
376
  *
375
377
  * The failure direction matters and is recorded so no one "fixes" this by
@@ -652,10 +654,10 @@ export const MIN_ACCEPTANCE_REASON = 10;
652
654
  export function buildAcceptance({ reason, by = null, version = null, person_id = null, client_id = null, session_id = null }) {
653
655
  const text = String(reason || '').trim();
654
656
  if (text.length < MIN_ACCEPTANCE_REASON) {
655
- throw new Error(
657
+ throw new CodedError(
656
658
  `An acceptance needs a written reason of at least ${MIN_ACCEPTANCE_REASON} characters. ` +
657
659
  `It is the disposition of record for a nonconformance and is read by whoever audits it later.`
658
- );
660
+ , { code: 'EMET-DOC-049' });
659
661
  }
660
662
  return {
661
663
  reason: text, accepted_by: by, accepted_at: new Date().toISOString(), covers_version: version,
package/src/database.js CHANGED
@@ -36,6 +36,7 @@ import {
36
36
  validateLimit
37
37
  } from './validation.js';
38
38
  import { isMetadataPath } from './metadata.js';
39
+ import { isEmetCodeOptions } from './error-codes.js';
39
40
 
40
41
  // ============================================
41
42
  // CONFIGURATION
@@ -171,12 +172,17 @@ export function sanitizeDetails(details) {
171
172
 
172
173
  export class EmetError extends Error {
173
174
  constructor(message, code = ErrorCodes.INTERNAL_ERROR, statusCode = StatusCodes.INTERNAL_ERROR, details = {}) {
175
+ let emetCode;
176
+ let det = details;
177
+ if (isEmetCodeOptions(arguments[4])) emetCode = arguments[4].code;
178
+ if (isEmetCodeOptions(det)) { emetCode = det.code; det = {}; }
174
179
  super(message);
175
180
  this.name = 'EmetError';
176
181
  this.code = code;
177
182
  this.statusCode = statusCode;
178
- this.details = details;
183
+ this.details = det && typeof det === 'object' && !Array.isArray(det) ? det : {};
179
184
  this.timestamp = Date.now();
185
+ if (emetCode) this.emetCode = emetCode;
180
186
  }
181
187
 
182
188
  toSafeJSON() {
@@ -195,9 +201,14 @@ export class EmetError extends Error {
195
201
 
196
202
  export class DatabaseError extends EmetError {
197
203
  constructor(message, operation = 'unknown', details = {}) {
198
- super(message, ErrorCodes.DATABASE_ERROR, StatusCodes.INTERNAL_ERROR, details);
204
+ let emetCode;
205
+ let det = details;
206
+ if (isEmetCodeOptions(arguments[3])) emetCode = arguments[3].code;
207
+ if (isEmetCodeOptions(det)) { emetCode = det.code; det = {}; }
208
+ super(message, ErrorCodes.DATABASE_ERROR, StatusCodes.INTERNAL_ERROR, det);
199
209
  this.name = 'DatabaseError';
200
210
  this.operation = operation;
211
+ if (emetCode) this.emetCode = emetCode;
201
212
  }
202
213
 
203
214
  toSafeJSON() {
@@ -209,8 +220,13 @@ export class DatabaseError extends EmetError {
209
220
 
210
221
  export class ConfigurationError extends EmetError {
211
222
  constructor(message, details = {}) {
212
- super(message, ErrorCodes.CONFIGURATION_ERROR, StatusCodes.SERVICE_UNAVAILABLE, details);
223
+ let emetCode;
224
+ let det = details;
225
+ if (isEmetCodeOptions(arguments[2])) emetCode = arguments[2].code;
226
+ if (isEmetCodeOptions(det)) { emetCode = det.code; det = {}; }
227
+ super(message, ErrorCodes.CONFIGURATION_ERROR, StatusCodes.SERVICE_UNAVAILABLE, det);
213
228
  this.name = 'ConfigurationError';
229
+ if (emetCode) this.emetCode = emetCode;
214
230
  }
215
231
  }
216
232
 
@@ -356,7 +372,7 @@ export class EmetDatabase {
356
372
  }
357
373
 
358
374
  if (!MONGODB_URI) {
359
- throw new ConfigurationError('MONGODB_URI is not set - EMET requires a MongoDB connection');
375
+ throw new ConfigurationError('MONGODB_URI is not set - EMET requires a MongoDB connection', { code: 'EMET-DB-001' });
360
376
  }
361
377
 
362
378
  this.connectPromise = (async () => {
@@ -375,7 +391,7 @@ export class EmetDatabase {
375
391
  `Failed to connect to MongoDB Atlas${fellBack ? ' after DNS fallback' : ''} - check network and cluster state (cluster may be paused)`,
376
392
  'connection',
377
393
  { reason: error.message }
378
- );
394
+ , { code: 'EMET-DB-002' });
379
395
  }
380
396
  this.client = client;
381
397
  this.db = client.db(MONGODB_DB);
@@ -408,7 +424,7 @@ export class EmetDatabase {
408
424
  return (await cursor.toArray()).map(stripMongoId);
409
425
  } catch (error) {
410
426
  if (error instanceof EmetError) throw error;
411
- throw new DatabaseError(`Query failed on layer ${layer}`, 'query', { reason: error.message });
427
+ throw new DatabaseError(`Query failed on layer ${layer}`, 'query', { reason: error.message }, { code: 'EMET-DB-003' });
412
428
  }
413
429
  }
414
430
 
@@ -423,7 +439,7 @@ export class EmetDatabase {
423
439
  return (await col.aggregate(pipeline, { allowDiskUse: true }).toArray()).map(stripMongoId);
424
440
  } catch (error) {
425
441
  if (error instanceof EmetError) throw error;
426
- throw new DatabaseError(`Query failed on layer ${layer}`, 'query', { reason: error.message });
442
+ throw new DatabaseError(`Query failed on layer ${layer}`, 'query', { reason: error.message }, { code: 'EMET-DB-003' });
427
443
  }
428
444
  }
429
445
 
@@ -433,7 +449,7 @@ export class EmetDatabase {
433
449
  try {
434
450
  return await this.collectionFor(layer).countDocuments({});
435
451
  } catch (error) {
436
- throw new DatabaseError(`Count failed on layer ${layer}`, 'query', { reason: error.message });
452
+ throw new DatabaseError(`Count failed on layer ${layer}`, 'query', { reason: error.message }, { code: 'EMET-DB-004' });
437
453
  }
438
454
  }
439
455
 
@@ -446,7 +462,7 @@ export class EmetDatabase {
446
462
  */
447
463
  async insertMemory(layer, doc) {
448
464
  for (const k of Object.keys(doc)) {
449
- if (!FIELD_SET.has(k)) throw new DatabaseError(`Unknown layer field: ${k}`, 'insert_memory', { layer });
465
+ if (!FIELD_SET.has(k)) throw new DatabaseError(`Unknown layer field: ${k}`, 'insert_memory', { layer }, { code: 'EMET-DB-005' });
450
466
  }
451
467
  const col = this.collectionFor(layer);
452
468
  try {
@@ -457,7 +473,7 @@ export class EmetDatabase {
457
473
  return id;
458
474
  } catch (error) {
459
475
  if (error instanceof EmetError) throw error;
460
- throw new DatabaseError('Failed to write to primary storage', 'storage_write', { layer, isPrimary: true, reason: error.message });
476
+ throw new DatabaseError('Failed to write to primary storage', 'storage_write', { layer, isPrimary: true, reason: error.message }, { code: 'EMET-DB-006' });
461
477
  }
462
478
  }
463
479
 
@@ -516,7 +532,7 @@ export class EmetDatabase {
516
532
  async getConnection(layer) {
517
533
  const validatedLayer = validateLayer(layer, true);
518
534
  if (!MEMORY_LAYERS[validatedLayer]) {
519
- throw new ValidationError('layer', `Invalid memory layer: ${layer}`);
535
+ throw new ValidationError('layer', `Invalid memory layer: ${layer}`, { code: 'EMET-DB-007' });
520
536
  }
521
537
 
522
538
  if (this.readConnections.has(validatedLayer)) {
@@ -560,7 +576,7 @@ export class EmetDatabase {
560
576
  `Failed to initialize schema for layer: ${layer}`,
561
577
  'schema_creation',
562
578
  { layer }
563
- );
579
+ , { code: 'EMET-DB-008' });
564
580
  }
565
581
  }
566
582
 
package/src/dispatch.js CHANGED
@@ -9,7 +9,7 @@
9
9
  * Until 2026-09-27 index.js (stdio) and http-remote.js (HTTP) each carried a
10
10
  * full switch mapping tool name to handler. dispatch.test.js compared the two
11
11
  * by case NAME and caught one class of drift (the session_id alias divergence,
12
- * commit-9e580d5); it could not see argument drift, and the code audit of
12
+ * an earlier fix); it could not see argument drift, and the code audit of
13
13
  * 2026-09-27 found one - setupComplete received the logger on stdio and not on
14
14
  * HTTP. A rule stated twice drifts; this file is the one statement.
15
15
  *
@@ -89,13 +89,14 @@ export function requireRegisteredSource(tag, tool, allowNull = false) {
89
89
  if (tag === null || tag === undefined || tag === '') {
90
90
  if (allowNull) return null;
91
91
  const reg = registeredSourceTags();
92
- throw new ValidationError('source', reg.length
93
- ? `${tool}: pass "source" set to the registered tag of the host this write comes from. A new host adopts one in bootstrap/INSTALL.md first. No source tag was given and one is required, so nothing was written.`
94
- : `${tool}: pass "source" set to the tag of the host this write comes from. No tags are registered on this server, so any non-empty tag passes: use the one bootstrap/INSTALL.md gives this host. No source tag was given and one is required, so nothing was written.`);
92
+ if (reg.length) {
93
+ throw new ValidationError('source', `${tool}: pass "source" set to the registered tag of the host this write comes from. A new host adopts one in bootstrap/INSTALL.md first. No source tag was given and one is required, so nothing was written.`, { code: 'EMET-TOOL-002' });
94
+ }
95
+ throw new ValidationError('source', `${tool}: pass "source" set to the tag of the host this write comes from. No tags are registered on this server, so any non-empty tag passes: use the one bootstrap/INSTALL.md gives this host. No source tag was given and one is required, so nothing was written.`, { code: 'EMET-TOOL-003' });
95
96
  }
96
97
  const registry = registeredSourceTags();
97
98
  if (registry.length && !registry.includes(tag)) {
98
- throw new ValidationError('source', `${tool}: pass "source" set to a registered tag. A new host adopts one in bootstrap/INSTALL.md first. Source tag "${echoId(tag)}" is not registered, so nothing was written.`);
99
+ throw new ValidationError('source', `${tool}: pass "source" set to a registered tag. A new host adopts one in bootstrap/INSTALL.md first. Source tag "${echoId(tag)}" is not registered, so nothing was written.`, { code: 'EMET-TOOL-004' });
99
100
  }
100
101
  return tag;
101
102
  }
@@ -120,7 +121,7 @@ export async function dispatchTool(name, args, ctx) {
120
121
  const { scopesAllow, deniedMessage } = await import('./scopes.js');
121
122
  const { scopes } = actor;
122
123
  if (!scopesAllow(scopes, name, { http: actor.transport === 'http', authenticated: actor.authenticated === true, args })) {
123
- throw new EmetError(deniedMessage(name, scopes, args), ErrorCodes.VALIDATION_ERROR, StatusCodes.BAD_REQUEST);
124
+ throw new EmetError(deniedMessage(name, scopes, args), ErrorCodes.VALIDATION_ERROR, StatusCodes.BAD_REQUEST, { code: 'EMET-TOOL-005' });
124
125
  }
125
126
  // The session graph (2026-09-29, board 120): the monorail (docs/GUARDRAILS-AND-MONORAILS.md). State is read BEFORE a
126
127
  // governed write; the write's result carries `session_graph` with the next
@@ -129,12 +130,12 @@ export async function dispatchTool(name, args, ctx) {
129
130
  // that names a session fails closed when the graph cannot be read.
130
131
  const sg = await import('./session-graph.js');
131
132
  // The exchange number, normalized ONCE, before the graph, the closed-session
132
- // guard and the tool all read it (2026-10-01, the reviewer's blocker on commit-2a361fd: the
133
+ // guard and the tool all read it (2026-10-01, the second reader's blocker on an earlier draft: the
133
134
  // guard read "4" as 4, the tool did not, so a text "4" was a retry to one and
134
135
  // a new exchange to the other). A whole number, or its text, or absent.
135
136
  if (name === 'emet_transcript_append') {
136
137
  const { value, error } = sg.normalizeExchangeNumber(args.exchange_index);
137
- if (error) throw new ValidationError('exchange_index', `${error}. Nothing was written.`);
138
+ if (error) throw new ValidationError('exchange_index', `${error}. Nothing was written.`, { code: 'EMET-TOOL-006' });
138
139
  args = { ...args };
139
140
  if (value === null) delete args.exchange_index; else args.exchange_index = value;
140
141
  }
@@ -151,7 +152,7 @@ export async function dispatchTool(name, args, ctx) {
151
152
  // A governed write that names a session fails closed on any graph
152
153
  // error. An unreadable session is not a reason to edit the board.
153
154
  if (sg.GRAPH_WRITE_TOOLS.has(name) && sg.sessionOf(args)) {
154
- const closed = new ValidationError('session', `session graph unavailable: ${e && e.message}. Nothing was written.`);
155
+ const closed = new ValidationError('session', `session graph unavailable: ${e && e.message}. Nothing was written.`, { code: 'EMET-SESS-005' });
155
156
  closed.graph = { mode: sg.graphMode(), decision: { verdict: 'refuse', gate: 'unavailable', reason: closed.message, next: null } };
156
157
  sg.labRecord(name, args, closed.graph, dbManager, logger);
157
158
  throw closed;
@@ -183,7 +184,7 @@ export async function dispatchTool(name, args, ctx) {
183
184
  // A correction of a closed session: the exchanges with their numbers normalized.
184
185
  if (grace && grace.revise) { args = { ...args, exchanges: grace.exchanges }; grace = null; }
185
186
  // A retry of the saved closing exchange is answered here; the tool is NOT
186
- // called, so nothing can be written (the reviewer's blocker on commit-2a361fd).
187
+ // called, so nothing can be written (the second reader's blocker on an earlier draft).
187
188
  if (grace && grace.retry) {
188
189
  const block = sg.graphBlock(graph);
189
190
  return createSuccessResponse({
@@ -219,11 +220,11 @@ export async function dispatchTool(name, args, ctx) {
219
220
  }
220
221
  return createSuccessResponse(data, name);
221
222
  };
222
- // The close's state write is awaited (the reviewer's nit 6), so an append sent after
223
+ // The close's state write is awaited (the second reader's nit 6), so an append sent after
223
224
  // the close returns already finds the session closed - when the write
224
225
  // succeeds. A failed write is retried once; if it still fails the reply
225
226
  // says so (closed_recorded: false, with a warning) instead of reading as a
226
- // locked session (2026-10-01, the reviewer's nit 2 on commit-df21117, the tester's
227
+ // locked session (2026-10-01, the second reader's nit 2 on an earlier draft, the reviewer's
227
228
  // condition 2). Every other step is recorded without holding up the reply.
228
229
  const recordClose = async (data) => {
229
230
  let rec = await sg.graphAfter(name, args, data, dbManager, logger, now);
@@ -267,6 +268,22 @@ export async function dispatchTool(name, args, ctx) {
267
268
  return await ok(data);
268
269
  }
269
270
  case 'emet_gaps': return ok(await findGaps(args));
271
+ case 'emet_page': {
272
+ const { readPage } = await import('./pages.js');
273
+ return ok(await readPage({ area: args.area, as_of: args.as_of ?? null, include_history: args.include_history === true }));
274
+ }
275
+ case 'emet_pages': {
276
+ const { listPages } = await import('./pages.js');
277
+ return ok(await listPages());
278
+ }
279
+ case 'emet_page_lint': {
280
+ const { lintPages } = await import('./pages.js');
281
+ return ok(await lintPages({ area: args.area || null }));
282
+ }
283
+ case 'emet_error_report': {
284
+ const { runErrorReport } = await import('./error-report.js');
285
+ return ok(await runErrorReport(args, dbManager));
286
+ }
270
287
  case 'emet_client_approve': {
271
288
  const att = await import('./attribution.js');
272
289
  const { rawActor, resolveTokenSubject } = await import('./persons.js');
@@ -275,7 +292,7 @@ export async function dispatchTool(name, args, ctx) {
275
292
  try {
276
293
  return ok(await att.clientApprove(approvalsDeps, rawActor(), ownerId, args, sourceRegistry()));
277
294
  } catch (e) {
278
- if (e && e.attributionRefusal) throw new ValidationError('tag', e.message);
295
+ if (e && e.attributionRefusal) throw new ValidationError('tag', e.message, { code: 'EMET-TOOL-007' });
279
296
  throw e;
280
297
  }
281
298
  }
@@ -302,7 +319,7 @@ export async function dispatchTool(name, args, ctx) {
302
319
  // seating or refusal lines to stderr on every call.
303
320
  status.gems = gemCost(await seat({ log: SILENT_GEM_LOG }));
304
321
  } catch {
305
- status.gems = { error: 'GEM socket failed closed' };
322
+ status.gems = { error: 'GEM socket failed closed', emet_code: 'EMET-GEM-042' };
306
323
  }
307
324
  }
308
325
  {
@@ -359,7 +376,7 @@ export async function dispatchTool(name, args, ctx) {
359
376
  try {
360
377
  return ok(await sk.dispatchSubkey(name, approvalsDeps, rawActor(), ownerId, args, sourceRegistry(), now));
361
378
  } catch (e) {
362
- if (e && e.attributionRefusal) throw new ValidationError('subkey', e.message);
379
+ if (e && e.attributionRefusal) throw new ValidationError('subkey', e.message, { code: 'EMET-AUTH-028' });
363
380
  throw e;
364
381
  }
365
382
  }
@@ -367,7 +384,7 @@ export async function dispatchTool(name, args, ctx) {
367
384
  const { serveRune } = await import('./rune-dispatch.js');
368
385
  const ran = await serveRune(name, args, { logger, AuditOperation, dbManager });
369
386
  if (ran) return ran;
370
- throw new EmetError(`Unknown tool: ${name}`, ErrorCodes.UNKNOWN_TOOL, StatusCodes.BAD_REQUEST);
387
+ throw new EmetError(`Unknown tool: ${name}`, ErrorCodes.UNKNOWN_TOOL, StatusCodes.BAD_REQUEST, { code: 'EMET-TOOL-008' });
371
388
  }
372
389
  }
373
390
  } catch (error) {