@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/persons.js CHANGED
@@ -24,7 +24,8 @@ export function currentActor() {
24
24
  clientId: s.clientId || null,
25
25
  scopes: Array.isArray(s.scopes) ? s.scopes : [],
26
26
  transport: s.transport || null,
27
- authenticated: s.authenticated === true
27
+ authenticated: s.authenticated === true,
28
+ sourceTag: typeof s.sourceTag === 'string' ? s.sourceTag : null
28
29
  };
29
30
  }
30
31
  return { personId: null, clientId: null, scopes: [], transport: null, authenticated: false };
package/src/provenance.js CHANGED
@@ -82,7 +82,7 @@ function isPositiveInt(v) {
82
82
  export function validateProvenance(input) {
83
83
  if (input === null || input === undefined) return null;
84
84
  if (typeof input !== 'object' || Array.isArray(input)) {
85
- throw new ValidationError('derived_from', 'must be an object');
85
+ throw new ValidationError('derived_from', 'must be an object', { code: 'EMET-PROV-001' });
86
86
  }
87
87
 
88
88
  const hasSpan = input.session_id !== undefined;
@@ -92,38 +92,38 @@ export function validateProvenance(input) {
92
92
  throw new ValidationError(
93
93
  'derived_from',
94
94
  'give a transcript span or a list of source entries, not both - an entry has one origin'
95
- );
95
+ , { code: 'EMET-PROV-002' });
96
96
  }
97
97
  if (!hasSpan && !hasEntries) {
98
98
  throw new ValidationError(
99
99
  'derived_from',
100
100
  'needs either session_id (with optional exchange_start/exchange_end) or entries'
101
- );
101
+ , { code: 'EMET-PROV-003' });
102
102
  }
103
103
 
104
104
  if (hasEntries) {
105
105
  if (!Array.isArray(input.entries) || input.entries.length === 0) {
106
- throw new ValidationError('derived_from.entries', 'must be a non-empty array of entry ids');
106
+ throw new ValidationError('derived_from.entries', 'must be a non-empty array of entry ids', { code: 'EMET-PROV-004' });
107
107
  }
108
108
  if (!input.entries.every(isPositiveInt)) {
109
- throw new ValidationError('derived_from.entries', 'entry ids must be positive integers');
109
+ throw new ValidationError('derived_from.entries', 'entry ids must be positive integers', { code: 'EMET-PROV-005' });
110
110
  }
111
111
  return { entries: [...input.entries] };
112
112
  }
113
113
 
114
114
  if (typeof input.session_id !== 'string' || input.session_id.length === 0) {
115
- throw new ValidationError('derived_from.session_id', 'must be a non-empty string');
115
+ throw new ValidationError('derived_from.session_id', 'must be a non-empty string', { code: 'EMET-PROV-006' });
116
116
  }
117
117
  const start = input.exchange_start;
118
118
  const end = input.exchange_end;
119
119
  if (start !== undefined && !isPositiveInt(start)) {
120
- throw new ValidationError('derived_from.exchange_start', 'must be a positive integer');
120
+ throw new ValidationError('derived_from.exchange_start', 'must be a positive integer', { code: 'EMET-PROV-007' });
121
121
  }
122
122
  if (end !== undefined && !isPositiveInt(end)) {
123
- throw new ValidationError('derived_from.exchange_end', 'must be a positive integer');
123
+ throw new ValidationError('derived_from.exchange_end', 'must be a positive integer', { code: 'EMET-PROV-009' });
124
124
  }
125
125
  if (isPositiveInt(start) && isPositiveInt(end) && end < start) {
126
- throw new ValidationError('derived_from.exchange_end', 'must not be before exchange_start');
126
+ throw new ValidationError('derived_from.exchange_end', 'must not be before exchange_start', { code: 'EMET-PROV-008' });
127
127
  }
128
128
 
129
129
  return {
@@ -160,7 +160,7 @@ export function provenanceColumns(provenance) {
160
160
  * This is the precedence rule, in one place, so no caller has to decide it.
161
161
  */
162
162
  export function resolveProvenance(entry, windowSeconds = FALLBACK_WINDOW_SECONDS) {
163
- if (!entry) throw new ValidationError('entry', 'is required');
163
+ if (!entry) throw new ValidationError('entry', 'is required', { code: 'EMET-PROV-010' });
164
164
 
165
165
  if (entry.source_session_id) {
166
166
  return {
@@ -252,7 +252,7 @@ export function frozenAttestation(parent, incoming) {
252
252
  const sent = incoming && typeof incoming === 'object' ? incoming : {};
253
253
  for (const key of FREEZE_KEYS) {
254
254
  if (!Object.prototype.hasOwnProperty.call(sent, key)) continue;
255
- if (sent[key] !== prior[key]) throw new ValidationError(key, 'attestation is immutable');
255
+ if (sent[key] !== prior[key]) throw new ValidationError(key, 'attestation is immutable', { code: 'EMET-GEM-033' });
256
256
  }
257
257
  return prior;
258
258
  }
@@ -268,11 +268,11 @@ export async function sealAttestation(metadata, opts = {}) {
268
268
  const full = SEAL_KEYS.every((key) => typeof metadata[key] === 'string' && metadata[key]);
269
269
  if (!full) { stripUnsealed(metadata); return; }
270
270
  const rune = activeByGem(metadata.gem, metadata.rune);
271
- if (!rune) throw new ValidationError('gem', "metadata.gem must be '<gem>@<version>' and match an active directive");
271
+ if (!rune) throw new ValidationError('gem', "metadata.gem must be '<gem>@<version>' and match an active directive", { code: 'EMET-GEM-034' });
272
272
  const pinned = pinRune(rune);
273
- if (!pinned) throw new ValidationError('served_sha256', 'hash pin');
273
+ if (!pinned) throw new ValidationError('served_sha256', 'hash pin', { code: 'EMET-GEM-035' });
274
274
  const principal = servePrincipal();
275
- if (!principal) throw new ValidationError('principal', 'no authenticated principal');
275
+ if (!principal) throw new ValidationError('principal', 'no authenticated principal', { code: 'EMET-GEM-036' });
276
276
  const session_id = sessionOf(opts.session_id);
277
277
  const query = { principal, session_id, gem: rune.gemId, rune: rune.name, sha256: pinned.sha256 };
278
278
  let db = opts.db && typeof opts.db.collection === 'function' ? opts.db : null;
@@ -286,16 +286,16 @@ export async function sealAttestation(metadata, opts = {}) {
286
286
  try { served = await storeHasServe(db, query); }
287
287
  catch (e) {
288
288
  if (e instanceof ValidationError) throw e;
289
- throw new ValidationError('gem', 'serve log');
289
+ throw new ValidationError('gem', 'serve log', { code: 'EMET-GEM-037' });
290
290
  }
291
291
  }
292
- if (!served) throw new ValidationError('gem', 'no serve event');
292
+ if (!served) throw new ValidationError('gem', 'no serve event', { code: 'EMET-GEM-038' });
293
293
  if (!SHA256_RE.test(metadata.client_sha256 || '')) {
294
- throw new ValidationError('client_sha256', 'client-reported sha256');
294
+ throw new ValidationError('client_sha256', 'client-reported sha256', { code: 'EMET-GEM-039' });
295
295
  }
296
296
  const inputHash = SHA256_RE.test(metadata.input_sha256 || '');
297
297
  const inputRef = typeof metadata.input_ref === 'string' && metadata.input_ref.trim().length > 0;
298
- if (!inputHash && !inputRef) throw new ValidationError('input_sha256', 'input hash or reference');
298
+ if (!inputHash && !inputRef) throw new ValidationError('input_sha256', 'input hash or reference', { code: 'EMET-GEM-040' });
299
299
  metadata.gem = metadataGemValue(rune);
300
300
  metadata.version = rune.version;
301
301
  metadata.rune = rune.name;
@@ -327,7 +327,7 @@ export async function serveRune(name, args, ctx) {
327
327
  if (!rune) return null;
328
328
  const { handleError, createSuccessResponse } = await import('./tools.js');
329
329
  const pinned = pinRune(rune);
330
- if (!pinned) return handleError(new ValidationError('rune', 'hash pin'), name, ctx && ctx.logger);
330
+ if (!pinned) return handleError(new ValidationError('rune', 'hash pin', { code: 'EMET-GEM-041' }), name, ctx && ctx.logger);
331
331
  const principal = servePrincipal();
332
332
  const session_id = sessionOf(args && args.session_id);
333
333
  const event = {
@@ -342,7 +342,7 @@ export async function serveRune(name, args, ctx) {
342
342
  const db = await openServeStore(ctx);
343
343
  try { await recordServe(event, db); }
344
344
  catch (e) {
345
- const err = e instanceof ValidationError ? e : new ValidationError('gem', 'serve log');
345
+ const err = e instanceof ValidationError ? e : new ValidationError('gem', 'serve log', { code: 'EMET-GEM-037' });
346
346
  return handleError(err, name, ctx && ctx.logger);
347
347
  }
348
348
  const op = ctx && ctx.AuditOperation && ctx.AuditOperation.GEM_SERVE ? ctx.AuditOperation.GEM_SERVE : 'GEM_SERVE';
@@ -50,6 +50,7 @@
50
50
  */
51
51
 
52
52
  import { setting } from './env.js';
53
+ import { CodedError } from './error-codes.js';
53
54
 
54
55
  export const GRAPH_MODES = Object.freeze(['enforce']);
55
56
 
@@ -138,7 +139,7 @@ export function echoId(id) {
138
139
  * Every session base an id could belong to, the way the close check groups a
139
140
  * session's documents (session.js inspectSession: ^base(_.*)?$). An id like
140
141
  * `<base>_extra` is counted by the close as part of `<base>`, so the closed-
141
- * session guard must treat it as `<base>` too (2026-10-01, the tester's gate
142
+ * session guard must treat it as `<base>` too (2026-10-01, the reviewer's gate
142
143
  * (a)). Longest first: the id itself, then each prefix ending before a `_`.
143
144
  */
144
145
  export function candidateBases(sessionId) {
@@ -171,7 +172,7 @@ export function groupedUnder(sessionId, base) {
171
172
  * that shape ("receipts.transcript_session_id is used when this is omitted")
172
173
  * and sessionClose checks that session; until 2026-10-01 the graph read only
173
174
  * `session_id`, so a close naming its session only in the receipts was never
174
- * recorded and the session stayed open (the reviewer's nit 3 on commit-df21117, the tester's
175
+ * recorded and the session stayed open (the second reader's nit 3 on an earlier draft, the reviewer's
175
176
  * condition 1). Receipts sent as JSON text are read as sessionClose reads
176
177
  * them (session.js parseReceipts).
177
178
  */
@@ -195,8 +196,8 @@ function receiptsOf(value) {
195
196
  }
196
197
 
197
198
  /**
198
- * An exchange number as sent, normalized ONCE (2026-10-01, the reviewer's re-check of
199
- * commit-2a361fd). Hosts send numbers as numbers or as text ("4"). The guard read "4"
199
+ * An exchange number as sent, normalized ONCE (2026-10-01, the second reader's re-check of
200
+ * an earlier draft). Hosts send numbers as numbers or as text ("4"). The guard read "4"
200
201
  * as 4 while emet_transcript_append only took real numbers, so a text "4" was a
201
202
  * "retry" to the guard and "the next exchange" to the tool. dispatch now runs
202
203
  * every exchange_index through this before the graph, the guard and the tool,
@@ -210,7 +211,7 @@ export function normalizeExchangeNumber(v) {
210
211
  let n = v;
211
212
  if (typeof n === 'string' && /^\s*\d+\s*$/.test(n)) n = Number(n);
212
213
  if (typeof n === 'number' && Number.isInteger(n) && n >= 1) return { value: n };
213
- return { error: `exchange_index must be a whole number, 1 or more (got ${JSON.stringify(v)})` };
214
+ return { error: `exchange_index must be a whole number, 1 or more (got ${JSON.stringify(v)})`, emet_code: 'EMET-TRN-010' };
214
215
  }
215
216
 
216
217
  /** The exchange a call declares, if any: `exchange` on writes, `exchange_index` on an append. */
@@ -353,8 +354,8 @@ export async function isSessionClosed(base, dbManager) {
353
354
  * once the window passes, the session is locked. A retry of that same
354
355
  * exchange number is answered as already saved, never as a second write:
355
356
  * the guard answers it itself and the tool is not called, at any time after
356
- * the close, so a retry can write nothing anywhere (2026-10-01, the reviewer's blocker
357
- * and the tester's gate on commit-2a361fd). The closing exchange itself is written
357
+ * the close, so a retry can write nothing anywhere (2026-10-01, the second reader's blocker
358
+ * and the reviewer's gate on an earlier draft). The closing exchange itself is written
358
359
  * into the session's last live part, whatever part or base id the caller sent.
359
360
  *
360
361
  * graceDecision is pure: state is the session row, declared the exchange the
@@ -370,7 +371,7 @@ export const DEFAULT_CLOSE_GRACE_MINUTES = 5;
370
371
  export const MAX_CLOSE_GRACE_MINUTES = 60;
371
372
 
372
373
  /**
373
- * The window setting, checked (2026-10-01, the reviewer's nit 4). Unset or blank: the
374
+ * The window setting, checked (2026-10-01, the second reader's nit 4). Unset or blank: the
374
375
  * default, 5. A number from 0 to 60: that many minutes (0 turns the window
375
376
  * off). Anything else is NOT silently accepted: a negative or non-numeric value
376
377
  * falls back to the default 5, and a value over 60 is capped at 60; both come
@@ -392,7 +393,7 @@ function closeGraceName() {
392
393
  export function closeGraceSetting(raw = setting('CLOSE_GRACE_MINUTES'), name = closeGraceName()) {
393
394
  if (raw === undefined || raw === null || String(raw).trim() === '') return { minutes: DEFAULT_CLOSE_GRACE_MINUTES, note: null };
394
395
  // Decimal only: Number() also reads hex, octal and binary ("0x10" is 16),
395
- // which no one means for minutes (the reviewer's nit 5 on commit-df21117).
396
+ // which no one means for minutes (the second reader's nit 5 on an earlier draft).
396
397
  const text = String(raw).trim();
397
398
  const n = /^[+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i.test(text) ? Number(text) : NaN;
398
399
  if (!Number.isFinite(n) || n < 0) {
@@ -519,7 +520,7 @@ export async function closedSessionGuard(tool, args = {}, dbManager, now = new D
519
520
  } catch (e) { throw await unreadable(tool, base, 'the transcript part to be revised', e); }
520
521
  if (!part) return null; // the tool itself refuses a revision of a part that does not exist
521
522
  // A correction of a closed session keeps EXACTLY the exchange numbers the
522
- // part holds (2026-10-01, the reviewer's nit 2): none added, none dropped, none
523
+ // part holds (2026-10-01, the second reader's nit 2): none added, none dropped, none
523
524
  // duplicated. Numbers sent as text are stored as numbers; the corrected
524
525
  // part is stored in exchange order.
525
526
  const held = [...new Set((part.exchanges || []).map((e) => Number(e && e.exchange_index)))].sort((a, b) => a - b);
@@ -555,7 +556,7 @@ export async function closedSessionGuard(tool, args = {}, dbManager, now = new D
555
556
  let pos;
556
557
  try {
557
558
  pos = typeof dbManager.transcriptPosition === 'function' ? await dbManager.transcriptPosition(base) : null;
558
- if (!pos || typeof pos.highest !== 'number') throw new Error('the transcript position is not available');
559
+ if (!pos || typeof pos.highest !== 'number') throw new CodedError('the transcript position is not available', { code: 'EMET-SESS-001' });
559
560
  } catch (e) { throw await unreadable(tool, base, 'the transcript position', e); }
560
561
  const highest = pos.highest;
561
562
  const declared = declaredExchange(tool, args);
@@ -565,8 +566,8 @@ export async function closedSessionGuard(tool, args = {}, dbManager, now = new D
565
566
  const d = graceDecision(row, declared, highest, now, minutes);
566
567
 
567
568
  if (d === 'retry') {
568
- // Answered HERE, and the tool is never called (2026-10-01, the reviewer's blocker on
569
- // commit-2a361fd): a retry handed to the tool with the caller's arguments could
569
+ // Answered HERE, and the tool is never called (2026-10-01, the second reader's blocker on
570
+ // an earlier draft): a retry handed to the tool with the caller's arguments could
570
571
  // land in another part id, the base id, or - with the number sent as text -
571
572
  // as a new exchange, while the reply said nothing was written.
572
573
  return { retry: true, base, index: row.grace_index,
@@ -574,7 +575,7 @@ export async function closedSessionGuard(tool, args = {}, dbManager, now = new D
574
575
  }
575
576
  if (d === 'grace') {
576
577
  const index = highest + 1;
577
- // Pinned to the session's last live part (2026-10-01, the reviewer's nit 3), never
578
+ // Pinned to the session's last live part (2026-10-01, the second reader's nit 3), never
578
579
  // the part or base id the caller named. If that part is full, the append
579
580
  // rolls to the next part number exactly as a live append does.
580
581
  let part = typeof pos.last_part === 'string' && pos.last_part ? pos.last_part : null;
@@ -903,7 +904,7 @@ export function graphBlock(g) {
903
904
  /**
904
905
  * After a successful call: record the step. Never throws - a failed record is
905
906
  * logged, not fatal. Returns what happened, so the close can say so
906
- * (2026-10-01, the reviewer's nit 2 on commit-df21117, the tester's condition 2):
907
+ * (2026-10-01, the second reader's nit 2 on an earlier draft, the reviewer's condition 2):
907
908
  * null nothing to record (no session, or no step)
908
909
  * {recorded: true, base} the step was written
909
910
  * {recorded: false, base, error} the write failed (logged as a warning)
package/src/session.js CHANGED
@@ -95,7 +95,7 @@ export const CLOSE_PROTOCOL = Object.freeze([
95
95
  async function connect() {
96
96
  const { testClientActive } = await import('./mongo-connect.js');
97
97
  if (!MONGODB_URI && !testClientActive()) {
98
- throw new DatabaseError('MONGODB_URI is not set; cannot verify session artifacts.');
98
+ throw new DatabaseError('MONGODB_URI is not set; cannot verify session artifacts.', { code: 'EMET-DB-001' });
99
99
  }
100
100
  const client = await connectMongo(MONGODB_URI || 'mongodb://test', { serverSelectionTimeoutMS: 15000 });
101
101
  return { client, db: client.db(MONGODB_DB) };
package/src/setup.js CHANGED
@@ -42,6 +42,7 @@ function callerHoldsWriteScope() {
42
42
  return scopes.includes('emet.write') || scopes.includes('emet') || scopes.includes('*');
43
43
  }
44
44
  import { gapCounts } from './gaps.js';
45
+ import { pageLintDigest } from './pages.js';
45
46
  import { registerSecretsFromEnv } from './redact.js';
46
47
  import { payloadForLayerCharter } from './startup-payload.js';
47
48
  import { namedItemsFrom } from './named-items.js';
@@ -496,7 +497,7 @@ export function readyInstructions(hasCharacter, available) {
496
497
 
497
498
  async function connect() {
498
499
  if (!MONGODB_URI) {
499
- throw new ValidationError('MONGODB_URI is not set. Copy .env.example to .env and fill it in.');
500
+ throw new ValidationError('MONGODB_URI is not set. Copy .env.example to .env and fill it in.', { code: 'EMET-DB-001' });
500
501
  }
501
502
  const client = await connectMongo(MONGODB_URI, { serverSelectionTimeoutMS: 8000, maxPoolSize: 5 });
502
503
  return { client, db: client.db(MONGODB_DB) };
@@ -623,14 +624,14 @@ export function upsertEnvAssignments(text, assignments) {
623
624
  */
624
625
  export function enableSubkeysAtFirstUse({ envFile = ENV_FILE, env = process.env, startup } = {}) {
625
626
  if (!dotenvWritable(envFile, env, startup)) {
626
- throw new ValidationError('more_than_one_bot', HOSTED_SUBKEY_STEPS);
627
+ throw new ValidationError('more_than_one_bot', HOSTED_SUBKEY_STEPS, { code: 'EMET-CFG-004' });
627
628
  }
628
629
  let raw = '';
629
630
  try {
630
631
  raw = fs.readFileSync(envFile, 'utf8');
631
632
  } catch (e) {
632
633
  if (!e || e.code !== 'ENOENT') {
633
- throw new ValidationError('more_than_one_bot', 'Could not read .env. Sub-keys were not turned on.');
634
+ throw new ValidationError('more_than_one_bot', 'Could not read .env. Sub-keys were not turned on.', { code: 'EMET-CFG-005' });
634
635
  }
635
636
  }
636
637
  const fromFile = parseEnvAssignments(raw);
@@ -650,7 +651,7 @@ export function enableSubkeysAtFirstUse({ envFile = ENV_FILE, env = process.env,
650
651
  fs.renameSync(tmp, envFile);
651
652
  } catch (e) {
652
653
  try { fs.unlinkSync(tmp); } catch { /* the temp file may not exist */ }
653
- throw new ValidationError('more_than_one_bot', 'Could not write .env. Sub-keys were not turned on.');
654
+ throw new ValidationError('more_than_one_bot', 'Could not write .env. Sub-keys were not turned on.', { code: 'EMET-CFG-006' });
654
655
  }
655
656
  // The flag stays off in this process. Tools and /owner/approvals appear together on restart.
656
657
  // Register the pepper so a later write that contains it is masked.
@@ -875,7 +876,7 @@ export async function initialize(options = {}, hooks = {}) {
875
876
  // A number, or the text of one; anything else (true, "two", 2.5) is refused, never read as page 1.
876
877
  k = typeof raw === 'number' ? raw : (typeof raw === 'string' && /^\s*\d+\s*$/.test(raw) ? Number(raw) : NaN);
877
878
  if (!Number.isInteger(k) || k < 1) {
878
- throw new ValidationError('page', 'page is a whole number from 1 (the startup is served in pages; start with no page, or page 1), or "all" for the whole startup in one result on a host with no size limit.');
879
+ throw new ValidationError('page', 'page is a whole number from 1 (the startup is served in pages; start with no page, or page 1), or "all" for the whole startup in one result on a host with no size limit.', { code: 'EMET-CFG-007' });
879
880
  }
880
881
  }
881
882
  // Every startup carries a load_id (2026-10-03), so every host can open a
@@ -892,7 +893,7 @@ export async function initialize(options = {}, hooks = {}) {
892
893
  // its load_id. A ready startup today never does (~27K minimum).
893
894
  if (pages.length === 1) return whole(full, 1);
894
895
  if (k > pages.length) {
895
- throw new ValidationError('page', `this startup has ${pages.length} pages; page ${k} does not exist.`);
896
+ throw new ValidationError('page', `this startup has ${pages.length} pages; page ${k} does not exist.`, { code: 'EMET-CFG-008' });
896
897
  }
897
898
  notePage(pages[k - 1].startup_page.load_id, k, pages.length);
898
899
  return pages[k - 1];
@@ -1220,6 +1221,9 @@ async function buildStartup(options = {}) {
1220
1221
  // the same move layers.js made for the silent meta layer. The ids are
1221
1222
  // one emet_gaps call away. A failed assessment is reported, not hidden.
1222
1223
  record_gaps: await gapCounts(),
1224
+ // Topic-page lint, counts only, on the weekly cadence. The page is a view.
1225
+ // This field is the digest. It writes nothing and it is not a record.
1226
+ page_lint: await pageLintDigest(),
1223
1227
  // The rows the board and the handoff already name. The session says them.
1224
1228
  // A section marked unread was not a table, so the document is still read.
1225
1229
  named_items: namedItemsFrom(
@@ -1338,7 +1342,7 @@ function renderUserDoc(a) {
1338
1342
 
1339
1343
  export async function setupComplete(answers = {}, logger = null, options = {}) {
1340
1344
  // First-time setup is the owner's (decision 2, procedural ref 407). Stage 1
1341
- // guards (2026-10-02, the tester's stage 1 admission, conditions S1-S2):
1345
+ // guards (2026-10-02, the reviewer's stage 1 admission, conditions S1-S2):
1342
1346
  // - refused under a configured bot tag. The tag is self-declared and
1343
1347
  // emet_initialize takes no source until stage 2, so this is inert until a
1344
1348
  // caller declares a bot tag that Alex has configured (stage 3);
@@ -1346,7 +1350,7 @@ export async function setupComplete(answers = {}, logger = null, options = {}) {
1346
1350
  // answer 5): a re-run replaces the user's identity documents with new
1347
1351
  // versions, so it needs the owner's explicit word. Nothing is written
1348
1352
  // when either refusal fires.
1349
- // S1-1 (the tester's re-check of commit-1a215d7): EACH declared value is checked, not
1353
+ // S1-1 (the reviewer's re-check of commit-1a215d7): EACH declared value is checked, not
1350
1354
  // the first non-empty one. The write below takes answers.source_tag first, so
1351
1355
  // checking only `source` let `source: <host>` + `answers.source_tag: <bot>`
1352
1356
  // write the identity documents as the bot. The tag that would be written
@@ -1361,7 +1365,7 @@ export async function setupComplete(answers = {}, logger = null, options = {}) {
1361
1365
  throw new ValidationError(
1362
1366
  field,
1363
1367
  `First-time setup is the owner's: ${declared} is a bot tag. Stop and tell the user. Nothing was written.`
1364
- );
1368
+ , { code: 'EMET-CFG-009' });
1365
1369
  }
1366
1370
  }
1367
1371
  const missing = SETUP_INTERVIEW.filter(q => q.required && !String(answers[q.key] || '').trim())
@@ -1370,25 +1374,25 @@ export async function setupComplete(answers = {}, logger = null, options = {}) {
1370
1374
  throw new ValidationError(
1371
1375
  `Setup is missing required answers: ${missing.join(', ')}. ` +
1372
1376
  'Ask the user for them - do not supply them yourself.'
1373
- );
1377
+ , { code: 'EMET-CFG-010' });
1374
1378
  }
1375
1379
  const multi = parseMoreThanOneBot(answers.more_than_one_bot);
1376
1380
  if (multi === null) {
1377
1381
  throw new ValidationError(
1378
1382
  'more_than_one_bot',
1379
1383
  'Answer yes or no. Yes turns on delegated client sub-keys. No leaves them off. Leaving it out leaves them off. Do not invent the answer. Nothing was written.'
1380
- );
1384
+ , { code: 'EMET-CFG-011' });
1381
1385
  }
1382
1386
  const backup = parseBotTeamBackup(answers.bot_team_backup);
1383
1387
  if (backup === null) {
1384
1388
  throw new ValidationError(
1385
1389
  'bot_team_backup',
1386
1390
  'Answer yes or no, in your own words. Yes and Yes. record bot-team backup as on. Yes is the recommended choice. No leaves it off. Leaving it out leaves it off. A non-string is refused. Do not invent the answer. Nothing was written.'
1387
- );
1391
+ , { code: 'EMET-CFG-012' });
1388
1392
  }
1389
1393
  answers = { ...answers, bot_team_backup: backup };
1390
1394
  if (multi && !dotenvWritable(options.envFile || ENV_FILE, process.env, options.startup)) {
1391
- throw new ValidationError('more_than_one_bot', HOSTED_SUBKEY_STEPS);
1395
+ throw new ValidationError('more_than_one_bot', HOSTED_SUBKEY_STEPS, { code: 'EMET-CFG-004' });
1392
1396
  }
1393
1397
 
1394
1398
  const written = [];
@@ -1404,16 +1408,16 @@ export async function setupComplete(answers = {}, logger = null, options = {}) {
1404
1408
  if (pid) {
1405
1409
  const person = await getPerson(conn.db, pid);
1406
1410
  if (!person || person.role !== 'owner') {
1407
- throw new ValidationError('role', 'emet_setup_complete requires the owner. Nothing was written.');
1411
+ throw new ValidationError('role', 'emet_setup_complete requires the owner. Nothing was written.', { code: 'EMET-CFG-013' });
1408
1412
  }
1409
1413
  } else if (who.transport === 'http') {
1410
- throw new ValidationError('role', 'emet_setup_complete requires the owner. Nothing was written.');
1414
+ throw new ValidationError('role', 'emet_setup_complete requires the owner. Nothing was written.', { code: 'EMET-CFG-013' });
1411
1415
  }
1412
1416
  const docsCol = conn.db.collection(DOCS_COLLECTION);
1413
1417
  const [hasIdentity, hasUser] = await Promise.all([
1414
1418
  docsCol.findOne({ doc_id: IDENTITY_DOC }), docsCol.findOne({ doc_id: USER_DOC })
1415
1419
  ]);
1416
- // Set up = BOTH identity documents exist (the reviewer's S-c; the tester: test it,
1420
+ // Set up = BOTH identity documents exist (the second reader's S-c; the reviewer: test it,
1417
1421
  // don't loosen it). A half-set-up store (one of the two) is an interrupted
1418
1422
  // first setup, and completing it needs no reissue.
1419
1423
  if (hasIdentity && hasUser && options.reissue !== true) {
@@ -1422,7 +1426,7 @@ export async function setupComplete(answers = {}, logger = null, options = {}) {
1422
1426
  'This store is already set up. Re-running setup writes new versions of the user\'s identity ' +
1423
1427
  'documents (prior versions are archived). Pass reissue: true only on the owner\'s explicit word. ' +
1424
1428
  'Nothing was written.'
1425
- );
1429
+ , { code: 'EMET-CFG-014' });
1426
1430
  }
1427
1431
  // Both writes below go through the same doors as every other write.
1428
1432
  // Until 2026-09-07 the three setup documents were written by a private
@@ -27,6 +27,7 @@
27
27
 
28
28
  import crypto from 'crypto';
29
29
  import { resultSize } from './startup-payload.js';
30
+ import { CodedError } from './error-codes.js';
30
31
 
31
32
  export const DEFAULT_PAGE_BYTES = 18000;
32
33
  export const MIN_PAGE_BYTES = 12000;
@@ -46,7 +47,7 @@ export const PAGE_ORDER = Object.freeze([
46
47
  'floor', 'floor_precedence', 'floor_reassertion', 'gems_available', 'gems_active',
47
48
  'seeds_due', 'seeds_evaluated_on', 'install_notes_doc_id',
48
49
  'identity', 'character', 'character_doc_id', 'character_sha256', 'user',
49
- 'record_gaps', 'named_items', 'lessons_pending', 'layer_health',
50
+ 'record_gaps', 'page_lint', 'named_items', 'lessons_pending', 'layer_health',
50
51
  'install_notes', 'instructions', 'layer_charter',
51
52
  'seeds', 'threads', 'recent_context', 'layer_counts', 'layer_counts_last_30d'
52
53
  ]);
@@ -243,7 +244,7 @@ export function paginate(full, { budget = pageBudget(), recentLimit } = {}) {
243
244
  other = Math.max(...measured.slice(1), 600);
244
245
  if (!fits) sizes.forEach((sz, i) => { if (sz > budget) overhead[i] += sz - budget + 64; });
245
246
  }
246
- if (!best) throw new Error('startup paging: could not fit the pages to the budget');
247
+ if (!best) throw new CodedError('startup paging: could not fit the pages to the budget', { code: 'EMET-PAGE-007' });
247
248
  return best;
248
249
  }
249
250
 
@@ -30,6 +30,7 @@
30
30
 
31
31
  import crypto from 'crypto';
32
32
  import { LAYER_CHARTER } from './layers.js';
33
+ import { CodedError } from './error-codes.js';
33
34
 
34
35
  const sha256 = (s) => crypto.createHash('sha256').update(String(s), 'utf8').digest('hex');
35
36
 
@@ -64,7 +65,7 @@ export const ABRIDGED_KEEP = Object.freeze([
64
65
  'identity', 'character', 'character_doc_id', 'character_sha256', 'user',
65
66
  'install_notes_doc_id',
66
67
  'seeds_due', 'seeds_evaluated_on',
67
- 'record_gaps', 'named_items', 'lessons_pending',
68
+ 'record_gaps', 'page_lint', 'named_items', 'lessons_pending',
68
69
  'floor', 'floor_precedence', 'floor_reassertion',
69
70
  'gems_available', 'gems_active'
70
71
  ]);
@@ -89,7 +90,7 @@ function layerHealthy(h) {
89
90
  * @param {string} [opts.reason] startup_reason to report
90
91
  */
91
92
  export function abridgeReadyPayload(full, opts = {}) {
92
- if (!full || full.state !== 'ready') throw new Error('abridgeReadyPayload: only a ready payload can be abridged');
93
+ if (!full || full.state !== 'ready') throw new CodedError('abridgeReadyPayload: only a ready payload can be abridged', { code: 'EMET-MEM-034' });
93
94
  const out = { startup_mode: 'abridged', startup_reason: opts.reason || 'returning configured bot (proven by receipt)' };
94
95
  for (const k of ABRIDGED_KEEP) if (k in full) out[k] = full[k];
95
96
 
@@ -25,6 +25,7 @@ import crypto from 'node:crypto';
25
25
  import { setting } from './env.js';
26
26
  import { acquireSharedClient, testClientActive } from './mongo-connect.js';
27
27
  import { MONGODB_URI, MONGODB_DB, COLLECTION_PREFIX } from './database.js';
28
+ import { CodedError } from './error-codes.js';
28
29
 
29
30
  const SUBKEYS_COLLECTION = `${COLLECTION_PREFIX}subkeys`;
30
31
  const SUBKEYS_HISTORY_COLLECTION = `${COLLECTION_PREFIX}subkeys_history`;
@@ -301,7 +302,7 @@ function mongoStore() {
301
302
  const cur = await keys.findOne({ _id: done.id });
302
303
  if (!cur || cur.rev !== revOf(done.prev) + 1) owned = false;
303
304
  }
304
- if (!owned) throw new Error('superseded by a concurrent open; this open was not made live.');
305
+ if (!owned) throw new CodedError('superseded by a concurrent open; this open was not made live.', { code: 'EMET-AUTH-026' });
305
306
  for (const done of applied.reverse()) await revertUpdate(keys, done.id, done.prev);
306
307
  continue;
307
308
  }
@@ -310,7 +311,7 @@ function mongoStore() {
310
311
  }
311
312
  return { written: true };
312
313
  }
313
- throw new Error('sub-key store conflict. Nothing was written.');
314
+ throw new CodedError('sub-key store conflict. Nothing was written.', { code: 'EMET-AUTH-027' });
314
315
  },
315
316
  async sweepFlagOff(note) {
316
317
  const client = await acquireSharedClient(MONGODB_URI, { serverSelectionTimeoutMS: 8000, maxPoolSize: 10 });