@dreamforgestudiollc/emet 0.2.4 → 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 (116) hide show
  1. package/.env.example +63 -0
  2. package/CHANGELOG.md +84 -3
  3. package/CHARTER.md +19 -7
  4. package/README.md +130 -21
  5. package/areas/emet.md +18 -0
  6. package/areas/garden.md +18 -0
  7. package/areas/health.md +18 -0
  8. package/areas/home.md +18 -0
  9. package/areas/learning.md +18 -0
  10. package/areas/state.md +18 -0
  11. package/docs/AUTHORSHIP.md +3 -3
  12. package/docs/BOTS.md +4 -0
  13. package/docs/COVERAGE.md +2 -2
  14. package/docs/DEPLOY.md +41 -5
  15. package/docs/ERROR-CODES-SPEC.md +43 -0
  16. package/docs/ERROR-CODES.md +332 -0
  17. package/docs/GUARDRAILS-AND-MONORAILS.md +2 -1
  18. package/docs/GUIDED-SETUP.md +24 -3
  19. package/docs/PERMISSIONS.md +13 -7
  20. package/docs/ROADMAP.md +18 -15
  21. package/docs/SETUP.md +123 -14
  22. package/docs/SUBKEYS.md +59 -0
  23. package/gems/artifact-index.json +12 -0
  24. package/gems/bot-team-backup/floor.json +15 -0
  25. package/gems/bot-team-backup/gem.json +43 -0
  26. package/gems/bot-team-backup/guides/BOT_TEAM_BACKUP.md +27 -0
  27. package/gems/bot-team-backup/guides/BOT_TEAM_RECOVERY.md +23 -0
  28. package/gems/fieldnote/floor.json +14 -0
  29. package/gems/fieldnote/gem.json +70 -0
  30. package/gems/fieldnote/runes/fieldnote.js +4 -0
  31. package/gems/lean-six-sigma/CHANGELOG.md +10 -0
  32. package/gems/lean-six-sigma/README.md +92 -0
  33. package/gems/lean-six-sigma/floor.json +31 -0
  34. package/gems/lean-six-sigma/gem.json +1296 -0
  35. package/gems/lean-six-sigma/guides/ASSUMPTIONS.md +45 -0
  36. package/gems/lean-six-sigma/guides/BELTS.md +52 -0
  37. package/gems/lean-six-sigma/guides/DMADV.md +56 -0
  38. package/gems/lean-six-sigma/guides/DMAIC.md +127 -0
  39. package/gems/lean-six-sigma/guides/FORMULAS.md +330 -0
  40. package/gems/lean-six-sigma/guides/LEAN.md +97 -0
  41. package/gems/lean-six-sigma/guides/TEMPLATES.md +279 -0
  42. package/gems/lean-six-sigma/runes/lss_capability.js +132 -0
  43. package/gems/lean-six-sigma/runes/lss_control_limits.js +240 -0
  44. package/gems/lean-six-sigma/runes/lss_dpmo_sigma.js +81 -0
  45. package/gems/lean-six-sigma/runes/lss_hypothesis.js +298 -0
  46. package/gems/lean-six-sigma/runes/lss_sample_size.js +81 -0
  47. package/gems/neurendipity/floor.json +65 -0
  48. package/gems/neurendipity/gem.json +42 -0
  49. package/gems/neurendipity/guides/AUTISTIC_BURNOUT.md +81 -0
  50. package/{guides → gems/neurendipity/guides}/NEURODIVERGENT_SUPPORT.md +17 -8
  51. package/guides/README.md +3 -0
  52. package/package.json +12 -5
  53. package/server.json +48 -4
  54. package/src/aleph.js +18 -12
  55. package/src/annotations.js +45 -5
  56. package/src/atlas-role.js +9 -4
  57. package/src/attribution.js +555 -0
  58. package/src/conformance.js +7 -5
  59. package/src/database.js +34 -17
  60. package/src/dispatch.js +136 -16
  61. package/src/env.js +54 -9
  62. package/src/error-codes.js +394 -0
  63. package/src/error-log.js +273 -0
  64. package/src/error-report.js +245 -0
  65. package/src/floor.js +84 -41
  66. package/src/gaps.js +41 -8
  67. package/src/gem-check.js +1360 -0
  68. package/src/guides.js +31 -4
  69. package/src/host-reach.js +23 -0
  70. package/src/http-remote.js +47 -2
  71. package/src/index.js +10 -2
  72. package/src/invites.js +6 -5
  73. package/src/layers.js +9 -8
  74. package/src/lessons-to-checks.js +3 -3
  75. package/src/logger.js +2 -1
  76. package/src/mongo-connect.js +50 -2
  77. package/src/oauth-provider.js +30 -29
  78. package/src/owner-approvals.js +281 -0
  79. package/src/pages.js +806 -0
  80. package/src/persons.js +22 -1
  81. package/src/provenance.js +10 -10
  82. package/src/redact.js +10 -4
  83. package/src/request-log.js +1 -1
  84. package/src/rune-dispatch.js +360 -0
  85. package/src/rune-registry.js +71 -0
  86. package/src/rune-scope.js +42 -0
  87. package/src/scopes.js +3 -0
  88. package/src/session-graph.js +15 -12
  89. package/src/session.js +10 -10
  90. package/src/setup.js +307 -36
  91. package/src/socket.js +545 -0
  92. package/src/startup-pages.js +26 -8
  93. package/src/startup-payload.js +12 -8
  94. package/src/subkey-store.js +358 -0
  95. package/src/subkeys.js +947 -0
  96. package/src/tools.js +518 -204
  97. package/src/transcript-session.js +1 -1
  98. package/src/validation.js +85 -52
  99. package/src/version.js +1 -1
  100. package/templates/AREA.md +35 -0
  101. package/templates/BOARD.md +2 -2
  102. package/templates/BOTHANDOFF.md +2 -2
  103. package/templates/CHARACTER.md +1 -1
  104. package/templates/HANDOFF.md +1 -1
  105. package/templates/IDENTITY.md +1 -1
  106. package/templates/INDEX.md +21 -20
  107. package/templates/INSTALL.md +1 -1
  108. package/templates/PROCEDURE.md +1 -1
  109. package/templates/ROSTER.md +2 -2
  110. package/templates/SEED.md +2 -2
  111. package/templates/STAGING.md +2 -2
  112. package/templates/STANDARD.md +5 -5
  113. package/templates/THREAD.md +1 -1
  114. package/templates/USER.md +4 -1
  115. package/verification/load-gate/corpus.json +1765 -0
  116. package/verification/load-gate/load-gate.mjs +1246 -0
package/src/database.js CHANGED
@@ -23,7 +23,7 @@
23
23
  */
24
24
 
25
25
  import './env.js';
26
- import { connectMongo } from './mongo-connect.js';
26
+ import { connectMongo, bindSharedClient } from './mongo-connect.js';
27
27
  import path from 'path';
28
28
 
29
29
  import {
@@ -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
 
@@ -230,7 +246,7 @@ const FIELD_SET = new Set([
230
246
  'id', 'timestamp', 'content', 'context', 'emotional_intensity', 'importance', 'metadata',
231
247
  'superseded_by', 'valid_until', 'is_live',
232
248
  'source_session_id', 'source_exchange_start', 'source_exchange_end', 'derived_from_ids',
233
- // sha256 of content, written at save time (2026-09-05). Before this the
249
+ // sha256 of content, written at save time (EMET ref 12, 2026-09-05). Before this the
234
250
  // digest was computed for the read-back receipt and then discarded, so no layer
235
251
  // entry could ever be re-verified after the moment it was written.
236
252
  'sha256',
@@ -258,7 +274,7 @@ const FIELD_SET = new Set([
258
274
  // `metadata.superseded_by` matched ZERO documents. Confirmed by probe 2026-08-24.
259
275
  // The fix therefore PROMOTED the two fields to real top-level columns, which are
260
276
  // queryable and indexable, and filters on those. Since 2026-09-05 metadata is a
261
- // real subdocument and its copy IS visible to Mongo - but the promoted
277
+ // real subdocument (EMET ref 6) and its copy IS visible to Mongo - but the promoted
262
278
  // columns remain the fields the liveness predicate reads: they are indexed, and
263
279
  // the vector-search filter can only see top-level booleans. The JS-level checks
264
280
  // in tools.js remain as a second line of defence.
@@ -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,10 +391,11 @@ 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);
398
+ bindSharedClient(client);
382
399
  this.log('info', `Connected to MongoDB database '${MONGODB_DB}'`);
383
400
  })();
384
401
 
@@ -407,7 +424,7 @@ export class EmetDatabase {
407
424
  return (await cursor.toArray()).map(stripMongoId);
408
425
  } catch (error) {
409
426
  if (error instanceof EmetError) throw error;
410
- 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' });
411
428
  }
412
429
  }
413
430
 
@@ -422,7 +439,7 @@ export class EmetDatabase {
422
439
  return (await col.aggregate(pipeline, { allowDiskUse: true }).toArray()).map(stripMongoId);
423
440
  } catch (error) {
424
441
  if (error instanceof EmetError) throw error;
425
- 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' });
426
443
  }
427
444
  }
428
445
 
@@ -432,12 +449,12 @@ export class EmetDatabase {
432
449
  try {
433
450
  return await this.collectionFor(layer).countDocuments({});
434
451
  } catch (error) {
435
- 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' });
436
453
  }
437
454
  }
438
455
 
439
456
  /**
440
- * THE layer insert, native (2026-09-27, code audit 1.7 stage 1 - the owner: "if SQL
457
+ * THE layer insert, native (2026-09-27, code audit 1.7 stage 1 - Alex: "if SQL
441
458
  * is the old and needs to be updated then update it"). Takes the document as
442
459
  * a document. Every key must be a known layer field; the id is allocated
443
460
  * here. The INSERT-string shim it replaced went with the SQL translator in
@@ -445,7 +462,7 @@ export class EmetDatabase {
445
462
  */
446
463
  async insertMemory(layer, doc) {
447
464
  for (const k of Object.keys(doc)) {
448
- 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' });
449
466
  }
450
467
  const col = this.collectionFor(layer);
451
468
  try {
@@ -456,7 +473,7 @@ export class EmetDatabase {
456
473
  return id;
457
474
  } catch (error) {
458
475
  if (error instanceof EmetError) throw error;
459
- 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' });
460
477
  }
461
478
  }
462
479
 
@@ -468,7 +485,7 @@ export class EmetDatabase {
468
485
 
469
486
  /**
470
487
  * Where a transcript session stands, for the provenance auto-stamp
471
- * (2026-09-29, a decision record). Read-only. Resolves a base id or any part id
488
+ * (2026-09-29, procedural ref 398). Read-only. Resolves a base id or any part id
472
489
  * to its base and the highest exchange index stored across every live part;
473
490
  * 0 when nothing is stored yet (a session opened but not yet appended).
474
491
  */
@@ -515,7 +532,7 @@ export class EmetDatabase {
515
532
  async getConnection(layer) {
516
533
  const validatedLayer = validateLayer(layer, true);
517
534
  if (!MEMORY_LAYERS[validatedLayer]) {
518
- throw new ValidationError('layer', `Invalid memory layer: ${layer}`);
535
+ throw new ValidationError('layer', `Invalid memory layer: ${layer}`, { code: 'EMET-DB-007' });
519
536
  }
520
537
 
521
538
  if (this.readConnections.has(validatedLayer)) {
@@ -559,7 +576,7 @@ export class EmetDatabase {
559
576
  `Failed to initialize schema for layer: ${layer}`,
560
577
  'schema_creation',
561
578
  { layer }
562
- );
579
+ , { code: 'EMET-DB-008' });
563
580
  }
564
581
  }
565
582
 
package/src/dispatch.js CHANGED
@@ -29,8 +29,12 @@ import {
29
29
  queryTranscripts, reviseTranscript, saveTranscript, sessionOpen, transcriptAppend,
30
30
  readDoc, READ_DOC_PAGE_DEFAULT, readDocHistory, writeDoc, validateDoc, acceptNonconformance,
31
31
  listDocs, retireDoc, renameDoc, restoreDoc, patchDoc, inviteCreate, memberAccessCreate,
32
- resolvedSourceTag
32
+ resolvedSourceTag,
33
+ TOOLS
33
34
  } from './tools.js';
35
+ import { reserveToolNames } from './rune-registry.js';
36
+
37
+ reserveToolNames([...TOOLS.map((tool) => tool.name), 'emet_subkey_request', 'emet_subkey_claim', 'emet_subkey_revoke', 'emet_subkey_end_session']);
34
38
 
35
39
  /**
36
40
  * Route one tool call. `ctx` carries what the transport owns: dbManager, logger,
@@ -38,7 +42,7 @@ import {
38
42
  * isError envelope, so the transport's audit line always has an outcome.
39
43
  */
40
44
  /**
41
- * The source tag under one name. `source` is the name on every write (the owner,
45
+ * The source tag under one name. `source` is the name on every write (Alex,
42
46
  * 2026-09-27, code audit 1.5c); the older per-tool names - updated_by,
43
47
  * retired_by, accepted_by on documents, channel on transcripts - are read as
44
48
  * aliases for one release and then dropped. metadata.source on the layers is
@@ -54,7 +58,7 @@ export function sourceOf(args) {
54
58
  }
55
59
 
56
60
  /**
57
- * A transcript write names a registered host or is refused (the owner, 2026-09-27,
61
+ * A transcript write names a registered host or is refused (Alex, 2026-09-27,
58
62
  * code audit 1.5d: nine spellings for five hosts in the store). Registered =
59
63
  * EMET_SOURCE_TAGS, exact membership only. With no registry configured, any
60
64
  * non-empty tag passes. A refusal does not publish the registry.
@@ -85,17 +89,26 @@ export function requireRegisteredSource(tag, tool, allowNull = false) {
85
89
  if (tag === null || tag === undefined || tag === '') {
86
90
  if (allowNull) return null;
87
91
  const reg = registeredSourceTags();
88
- throw new ValidationError('source', reg.length
89
- ? `${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.`
90
- : `${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' });
91
96
  }
92
97
  const registry = registeredSourceTags();
93
98
  if (registry.length && !registry.includes(tag)) {
94
- 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' });
95
100
  }
96
101
  return tag;
97
102
  }
98
103
 
104
+ const SILENT_GEM_LOG = Object.freeze({ warn() {}, info() {}, error() {} });
105
+ /**
106
+ * Test seam: the suites swap in a seatGems stand-in to drive emet_status's
107
+ * fail-closed branch. Never set outside tests; pass null to restore.
108
+ */
109
+ let statusSeatForTests = null;
110
+ export function setStatusSeatForTests(fn) { statusSeatForTests = typeof fn === 'function' ? fn : null; }
111
+
99
112
  export async function dispatchTool(name, args, ctx) {
100
113
  const { dbManager, logger, AuditOperation } = ctx;
101
114
  args = args || {};
@@ -108,9 +121,9 @@ export async function dispatchTool(name, args, ctx) {
108
121
  const { scopesAllow, deniedMessage } = await import('./scopes.js');
109
122
  const { scopes } = actor;
110
123
  if (!scopesAllow(scopes, name, { http: actor.transport === 'http', authenticated: actor.authenticated === true, args })) {
111
- 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' });
112
125
  }
113
- // The session graph (2026-09-29): the monorail (docs/GUARDRAILS-AND-MONORAILS.md). State is read BEFORE a
126
+ // The session graph (2026-09-29, board 120): the monorail (docs/GUARDRAILS-AND-MONORAILS.md). State is read BEFORE a
114
127
  // governed write; the write's result carries `session_graph` with the next
115
128
  // step; the step is recorded after it succeeds. Enforce only (2026-10-03):
116
129
  // a skipped step is refused before anything is written. A governed write
@@ -122,7 +135,7 @@ export async function dispatchTool(name, args, ctx) {
122
135
  // a new exchange to the other). A whole number, or its text, or absent.
123
136
  if (name === 'emet_transcript_append') {
124
137
  const { value, error } = sg.normalizeExchangeNumber(args.exchange_index);
125
- 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' });
126
139
  args = { ...args };
127
140
  if (value === null) delete args.exchange_index; else args.exchange_index = value;
128
141
  }
@@ -139,7 +152,7 @@ export async function dispatchTool(name, args, ctx) {
139
152
  // A governed write that names a session fails closed on any graph
140
153
  // error. An unreadable session is not a reason to edit the board.
141
154
  if (sg.GRAPH_WRITE_TOOLS.has(name) && sg.sessionOf(args)) {
142
- 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' });
143
156
  closed.graph = { mode: sg.graphMode(), decision: { verdict: 'refuse', gate: 'unavailable', reason: closed.message, next: null } };
144
157
  sg.labRecord(name, args, closed.graph, dbManager, logger);
145
158
  throw closed;
@@ -181,6 +194,13 @@ export async function dispatchTool(name, args, ctx) {
181
194
  }, name);
182
195
  }
183
196
  const ok = (data) => {
197
+ // A sub-key, claim nonce, or session handle is delivered once by the tool
198
+ // that minted it. Later receipts do not repeat it.
199
+ if (data && typeof data === 'object' && !Array.isArray(data)) {
200
+ if (name !== 'emet_subkey_claim') delete data.subkey;
201
+ if (name !== 'emet_subkey_request') delete data.nonce;
202
+ if (name !== 'emet_session_open') delete data.session_handle;
203
+ }
184
204
  const block = sg.graphBlock(graph);
185
205
  if (block && data && typeof data === 'object' && !Array.isArray(data)) data.session_graph = block;
186
206
  if (name === sg.STARTUP_PAGES_TOOL && graph) sg.labRecord(name, args, graph, dbManager, logger); // the open succeeded
@@ -226,13 +246,61 @@ export async function dispatchTool(name, args, ctx) {
226
246
  switch (name) {
227
247
  case 'emet_initialize': return ok(await initialize(args, { onLate: (late) => sg.recordLatePages(late, dbManager, logger) }));
228
248
  case 'emet_setup_complete': return ok(await setupComplete(args.answers || {}, logger, { reissue: args.reissue === true, source: sourceOf(args) }));
229
- case 'emet_session_close': return await ok(await sessionClose(args));
249
+ case 'emet_session_close': {
250
+ const data = await sessionClose(args);
251
+ try {
252
+ const { setting } = await import('./env.js');
253
+ if (data && data.state === 'complete' && setting('SUBKEYS') === '1') {
254
+ const sk = await import('./subkeys.js');
255
+ const { approvalsDeps } = await import('./tools.js');
256
+ const named = sk.sessionIdForClose(args);
257
+ if (named.mismatch) {
258
+ logger?.warn?.('sub-key session not released: session_id and receipts.transcript_session_id name different sessions');
259
+ } else {
260
+ await sk.releaseClosedSession(approvalsDeps, named.base, now, {
261
+ handle: args.session_handle, subkey: args.subkey
262
+ });
263
+ }
264
+ }
265
+ } catch (e) {
266
+ logger?.warn?.('sub-key session not released on close', { error: e && e.message });
267
+ }
268
+ return await ok(data);
269
+ }
230
270
  case 'emet_gaps': return ok(await findGaps(args));
231
- case 'emet_floor': return ok(readFloor(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
+ }
287
+ case 'emet_client_approve': {
288
+ const att = await import('./attribution.js');
289
+ const { rawActor, resolveTokenSubject } = await import('./persons.js');
290
+ const { approvalsDeps, sourceRegistry } = await import('./tools.js');
291
+ const ownerId = await resolveTokenSubject(dbManager.db).catch(() => null);
292
+ try {
293
+ return ok(await att.clientApprove(approvalsDeps, rawActor(), ownerId, args, sourceRegistry()));
294
+ } catch (e) {
295
+ if (e && e.attributionRefusal) throw new ValidationError('tag', e.message, { code: 'EMET-TOOL-007' });
296
+ throw e;
297
+ }
298
+ }
299
+ case 'emet_floor': return ok(await readFloor(args));
232
300
  case 'recall': return ok(await recallMemories(dbManager, args.query, args.layer || null, args.limit || 10, logger, AuditOperation, { history: args.history === true, order: args.order }));
233
301
  case 'query_layer': return ok(await queryLayer(dbManager, args.layer, args.options || {}, logger, AuditOperation));
234
302
  case 'emet_status': {
235
- // One diagnostic (2026-09-27, the owner: one tool with several functions over
303
+ // One diagnostic (2026-09-27, Alex: one tool with several functions over
236
304
  // several overlapping ones). setupStatus + the per-layer counts, and the
237
305
  // write-path probe on request.
238
306
  const status = await setupStatus();
@@ -241,6 +309,35 @@ export async function dispatchTool(name, args, ctx) {
241
309
  status.layers = layers.layers; status.total_memories = layers.total_memories; status.health = layers.health;
242
310
  }
243
311
  if (args.probe === true) status.probe = await verifyConnection();
312
+ {
313
+ // Socket PR 4: each GEM's byte cost against the caps the socket enforces.
314
+ // Read-only; a socket failure is reported here and never fails the status.
315
+ try {
316
+ const { seatGems, gemCost } = await import('./socket.js');
317
+ const seat = statusSeatForTests || seatGems;
318
+ // Silent logger, as floor.js does: a status read must not write
319
+ // seating or refusal lines to stderr on every call.
320
+ status.gems = gemCost(await seat({ log: SILENT_GEM_LOG }));
321
+ } catch {
322
+ status.gems = { error: 'GEM socket failed closed', emet_code: 'EMET-GEM-042' };
323
+ }
324
+ }
325
+ {
326
+ const att = await import('./attribution.js');
327
+ const { rawActor } = await import('./persons.js');
328
+ const { callerAttribution } = await import('./setup.js');
329
+ const { setting } = await import('./env.js');
330
+ Object.assign(status, callerAttribution());
331
+ const v = att.approvalsView(att.cachedApprovals(), rawActor() || { transport: 'stdio' }, null);
332
+ if (v) status.client_approvals = v;
333
+ if (setting('SUBKEYS') === '1') {
334
+ const sk = await import('./subkeys.js');
335
+ const { approvalsDeps } = await import('./tools.js');
336
+ const records = await sk.loadSubkeyRecords(approvalsDeps);
337
+ const keys = sk.subkeysView(records, rawActor() || { transport: 'stdio' }, null);
338
+ if (keys) status.subkeys = keys;
339
+ }
340
+ }
244
341
  return ok(status);
245
342
  }
246
343
  case 'save_to_layer': return ok(await saveMemory(dbManager, args.content, args.layer, args.metadata || {}, logger, AuditOperation, { session_id: args.session_id }));
@@ -264,8 +361,31 @@ export async function dispatchTool(name, args, ctx) {
264
361
  case 'semantic_recall': return ok(await semanticRecall(args.query, args.layer || null, args.limit || 10, logger, { history: args.history === true }, dbManager));
265
362
  case 'emet_invite_create': return ok(await inviteCreate(dbManager, args, logger));
266
363
  case 'emet_member_access_create': return ok(await memberAccessCreate(dbManager, args, logger));
267
- default:
268
- throw new EmetError(`Unknown tool: ${name}`, ErrorCodes.UNKNOWN_TOOL, StatusCodes.BAD_REQUEST);
364
+ default: {
365
+ // The four sub-key tools are not case labels. A case label would put
366
+ // them in the dispatch table while EMET_SUBKEYS is off, and the host
367
+ // list would no longer match that table. They dispatch from here only
368
+ // while the flag is on; off, the name is an unknown tool.
369
+ const { setting } = await import('./env.js');
370
+ if (setting('SUBKEYS') === '1') {
371
+ const sk = await import('./subkeys.js');
372
+ if (sk.SUBKEY_TOOLS.includes(name)) {
373
+ const { rawActor, resolveTokenSubject } = await import('./persons.js');
374
+ const { approvalsDeps, sourceRegistry } = await import('./tools.js');
375
+ const ownerId = dbManager && dbManager.db ? await resolveTokenSubject(dbManager.db).catch(() => null) : null;
376
+ try {
377
+ return ok(await sk.dispatchSubkey(name, approvalsDeps, rawActor(), ownerId, args, sourceRegistry(), now));
378
+ } catch (e) {
379
+ if (e && e.attributionRefusal) throw new ValidationError('subkey', e.message, { code: 'EMET-AUTH-028' });
380
+ throw e;
381
+ }
382
+ }
383
+ }
384
+ const { serveRune } = await import('./rune-dispatch.js');
385
+ const ran = await serveRune(name, args, { logger, AuditOperation, dbManager });
386
+ if (ran) return ran;
387
+ throw new EmetError(`Unknown tool: ${name}`, ErrorCodes.UNKNOWN_TOOL, StatusCodes.BAD_REQUEST, { code: 'EMET-TOOL-008' });
388
+ }
269
389
  }
270
390
  } catch (error) {
271
391
  if (grace && grace.grace) { // the claimed closing exchange was not written: give the window back
package/src/env.js CHANGED
@@ -17,27 +17,72 @@ import path from 'path';
17
17
  import { resolveModulePath } from './module-path.js';
18
18
 
19
19
  const ROOT = resolveModulePath(import.meta.url, ['..']);
20
+ const DEFAULT_ENV_FILE = path.join(ROOT, '.env');
20
21
 
21
- export function loadEnv(file = path.join(ROOT, '.env')) {
22
- let raw;
23
- try { raw = fs.readFileSync(file, 'utf8'); } catch { return { loaded: false, keys: [] }; }
24
-
25
- const keys = [];
26
- for (const line of raw.split(/\r?\n/)) {
22
+ /** Active KEY=value lines. Commented lines are skipped. Later lines win. */
23
+ export function parseEnvAssignments(text) {
24
+ const out = {};
25
+ for (const line of String(text ?? '').split(/\r?\n/)) {
27
26
  const trimmed = line.trim();
28
27
  if (!trimmed || trimmed.startsWith('#')) continue;
29
28
  const eq = trimmed.indexOf('=');
30
29
  if (eq < 1) continue;
31
30
  const key = trimmed.slice(0, eq).trim();
32
- if (process.env[key] !== undefined) continue; // a real env var always wins
33
31
  let value = trimmed.slice(eq + 1).trim();
34
32
  if ((value.startsWith('"') && value.endsWith('"')) ||
35
33
  (value.startsWith("'") && value.endsWith("'"))) value = value.slice(1, -1);
36
34
  if (value === '') continue;
37
- process.env[key] = value;
35
+ out[key] = value;
36
+ }
37
+ return out;
38
+ }
39
+
40
+ const HOSTED_PLATFORM_MARKERS = [
41
+ 'RAILWAY_ENVIRONMENT', 'RAILWAY_PROJECT_ID', 'RAILWAY_SERVICE_ID',
42
+ 'FLY_APP_NAME', 'RENDER', 'RENDER_SERVICE_ID', 'DYNO', 'K_SERVICE'
43
+ ];
44
+
45
+ /** What the startup load of the default .env file actually applied. */
46
+ const startupEnv = { loaded: false, keys: [], file: DEFAULT_ENV_FILE };
47
+
48
+ /** The .env path loadEnv reads at startup. Setup refuses a pepper write against this file when it was not the config source. */
49
+ export function defaultEnvFile() {
50
+ return DEFAULT_ENV_FILE;
51
+ }
52
+
53
+ export function loadEnv(file = DEFAULT_ENV_FILE, env = process.env) {
54
+ let raw;
55
+ try { raw = fs.readFileSync(file, 'utf8'); } catch {
56
+ const missed = { loaded: false, keys: [], file };
57
+ if (env === process.env && path.resolve(file) === path.resolve(startupEnv.file)) Object.assign(startupEnv, missed);
58
+ return missed;
59
+ }
60
+ const keys = [];
61
+ for (const [key, value] of Object.entries(parseEnvAssignments(raw))) {
62
+ if (env[key] !== undefined) continue; // a real env var always wins
63
+ env[key] = value;
38
64
  keys.push(key);
39
65
  }
40
- return { loaded: true, keys };
66
+ const result = { loaded: true, keys, file };
67
+ if (env === process.env && path.resolve(file) === path.resolve(startupEnv.file)) Object.assign(startupEnv, result);
68
+ return result;
69
+ }
70
+
71
+ /** A platform injects the process environment (Railway and the same shape). */
72
+ export function platformEnv(env = process.env) {
73
+ return HOSTED_PLATFORM_MARKERS.some((key) => env[key] !== undefined && String(env[key]).length > 0);
74
+ }
75
+
76
+ /**
77
+ * True when this process did not take its settings from .env. A real env var
78
+ * wins over the file, and a hosted deploy rebuilds the container, so a pepper
79
+ * written there would not be the one the next process verifies.
80
+ */
81
+ export function realEnvIsConfigSource(env = process.env, startup = startupEnv) {
82
+ if (platformEnv(env)) return true;
83
+ if (!startup.loaded) return true;
84
+ if (startup.keys.length === 0) return true;
85
+ return false;
41
86
  }
42
87
 
43
88
  /**