@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/guides.js CHANGED
@@ -22,14 +22,36 @@ import crypto from 'crypto';
22
22
  import { resolveModulePath } from './module-path.js';
23
23
 
24
24
  export const GUIDES_DIR = resolveModulePath(import.meta.url, ['..', 'guides']);
25
+ const GEMS_DIR = resolveModulePath(import.meta.url, ['..', 'gems']);
25
26
  const GUIDE_ID = /^guides\/([A-Za-z0-9_-]+\.md)$/;
26
27
 
28
+ /**
29
+ * One release: the old neurodivergent guide id resolves to the Neurendipity
30
+ * copy. There is one file. This map is not a second copy of the text.
31
+ */
32
+ const GUIDE_ALIAS = Object.freeze({
33
+ 'guides/NEURODIVERGENT_SUPPORT.md': resolveModulePath(import.meta.url, ['..', 'gems', 'neurendipity', 'guides', 'NEURODIVERGENT_SUPPORT.md'])
34
+ });
35
+
27
36
  /** The shipped guide for this doc_id, or null when it is not a shipped guide. */
28
37
  export function readShippedGuide(doc_id, { dir = GUIDES_DIR } = {}) {
29
38
  const m = typeof doc_id === 'string' ? GUIDE_ID.exec(doc_id) : null;
30
39
  if (!m) return null;
40
+ const file = Object.prototype.hasOwnProperty.call(GUIDE_ALIAS, doc_id) ? GUIDE_ALIAS[doc_id] : path.join(dir, m[1]);
31
41
  let content;
32
- try { content = fs.readFileSync(path.join(dir, m[1]), 'utf8'); } catch { return null; }
42
+ try { content = fs.readFileSync(file, 'utf8'); } catch {
43
+ // A bundled GEM's own guide (2026-10-12: Neurendipity's floor points to
44
+ // read_doc('guides/AUTISTIC_BURNOUT.md'), which no folder served). Only the
45
+ // default shipped dir falls through, and only to bundled gems/<id>/guides/.
46
+ if (dir !== GUIDES_DIR) return null;
47
+ content = null;
48
+ let gems = [];
49
+ try { gems = fs.readdirSync(GEMS_DIR).filter((g) => /^[a-z0-9-]+$/.test(g)).sort(); } catch { gems = []; }
50
+ for (const g of gems) {
51
+ try { content = fs.readFileSync(path.join(GEMS_DIR, g, 'guides', m[1]), 'utf8'); break; } catch { /* next */ }
52
+ }
53
+ if (content === null) return null;
54
+ }
33
55
  return {
34
56
  doc_id,
35
57
  content,
@@ -41,8 +63,13 @@ export function readShippedGuide(doc_id, { dir = GUIDES_DIR } = {}) {
41
63
  };
42
64
  }
43
65
 
44
- /** Names of the guides this release ships. */
66
+ /** Names of the guides this release ships. The one-release alias is included. */
45
67
  export function shippedGuides({ dir = GUIDES_DIR } = {}) {
46
- try { return fs.readdirSync(dir).filter(f => /\.md$/.test(f)).map(f => `guides/${f}`).sort(); }
47
- catch { return []; }
68
+ let names = [];
69
+ try { names = fs.readdirSync(dir).filter(f => /\.md$/.test(f)).map(f => `guides/${f}`); }
70
+ catch { names = []; }
71
+ for (const id of Object.keys(GUIDE_ALIAS)) {
72
+ if (!names.includes(id) && fs.existsSync(GUIDE_ALIAS[id])) names.push(id);
73
+ }
74
+ return names.sort();
48
75
  }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * EMET - Enduring Memory & Epistemic Tiers
3
+ * Copyright (c) 2026 Dreamforge Studio LLC
4
+ *
5
+ * Licensed under the MIT License - see LICENSE
6
+ *
7
+ * The RUNE load gate lives in verification/load-gate/load-gate.mjs so
8
+ * EMET-GEMs can vendor that file and its corpus byte-for-byte. This module
9
+ * is the import path gem-check already uses. There is no second scan.
10
+ */
11
+
12
+ export {
13
+ refuseHostAccess,
14
+ scanSource,
15
+ hostRules,
16
+ runeSpecifierReason,
17
+ runeExtensionReason,
18
+ MAX_SOURCE_BYTES,
19
+ HOST_GLOBALS,
20
+ OBJECT_METHODS,
21
+ MEMBER_NAMES,
22
+ MATH_MEMBERS
23
+ } from '../verification/load-gate/load-gate.mjs';
@@ -82,7 +82,9 @@ function buildServer() {
82
82
  const { scopesAllow } = await import('./scopes.js');
83
83
  const auth = extra && extra.authInfo;
84
84
  const scopes = (auth && auth.scopes) || [];
85
- return { tools: t.TOOLS.filter((tool) => scopesAllow(scopes, tool.name, { http: true, authenticated: Boolean(auth), args: null })) };
85
+ const { runeToolList } = await import('./rune-registry.js');
86
+ const tools = [...t.TOOLS, ...runeToolList()];
87
+ return { tools: tools.filter((tool) => scopesAllow(scopes, tool.name, { http: true, authenticated: Boolean(auth), args: null })) };
86
88
  });
87
89
  server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
88
90
  const { name, arguments: args = {} } = request.params;
@@ -95,6 +97,7 @@ function buildServer() {
95
97
  scopes: (auth && auth.scopes) || [],
96
98
  transport: 'http',
97
99
  sourceTag: (auth && auth.extra && auth.extra.sourceTag) || null,
100
+ grantId: (auth && auth.extra && auth.extra.grantId) || null,
98
101
  authenticated: Boolean(auth)
99
102
  };
100
103
  const bucket = t.rateBucket(actor);
@@ -104,8 +107,24 @@ function buildServer() {
104
107
  // Every tool call leaves one audit entry (H6). callTool never throws: it
105
108
  // returns either a success response or handleError's isError response.
106
109
  const t0 = Date.now();
107
- // Parameter NAMES, never values (the owner, 2026-09-27, code audit 1.6).
110
+ // Parameter NAMES, never values (Alex, 2026-09-27, code audit 1.6).
108
111
  const paramNames = Object.keys(args || {}).sort();
112
+ try {
113
+ const att = await import('./attribution.js');
114
+ const { resolveTokenSubject } = await import('./persons.js');
115
+ actor.ownerId = await resolveTokenSubject(dbManager.db).catch(() => null);
116
+ await actorStore.run(actor, () => att.preflight({
117
+ db: dbManager.db, prefix: provider.prefix, ownerId: actor.ownerId, deps: t.approvalsDeps,
118
+ layerCollections: ['episodic', 'semantic', 'procedural', 'meta', 'identity', 'working'].map((l) => { try { return dbManager.collectionFor(l); } catch { return null; } }).filter(Boolean),
119
+ registry: t.sourceRegistry()
120
+ }, actor, args, name));
121
+ } catch (e) {
122
+ if (e && e.attributionRefusal) {
123
+ const { ValidationError } = await import('./validation.js');
124
+ return actorStore.run(actor, () => t.handleError(new ValidationError('source', e.message, { code: 'EMET-AUTH-039' }), name, logger));
125
+ }
126
+ throw e;
127
+ }
109
128
  const result = await actorStore.run(actor, () => callTool(name, args));
110
129
  logger.audit(AuditOperation.TOOL_CALL, { tool: name, success: result.isError !== true, durationMs: Date.now() - t0, params: paramNames });
111
130
  return result;
@@ -136,6 +155,20 @@ app.use(requestLogger({ enabled: process.env.EMET_REQUEST_LOG !== '0' }));
136
155
 
137
156
  app.get('/health', (_req, res) => res.json({ ok: true, service: 'emet', tools: t.TOOLS.length, cimd: provider.cimdEnabled }));
138
157
 
158
+ // Pending sub-keys. Same passphrase and the same per-address failure throttle
159
+ // as /oauth/approve. The routes are not mounted unless EMET_SUBKEYS=1, so a
160
+ // flag-off process answers these paths the way it answers any other unknown path.
161
+ if (setting('SUBKEYS') === '1') {
162
+ const { mountOwnerApprovals } = await import('./owner-approvals.js');
163
+ const { resolveTokenSubject } = await import('./persons.js');
164
+ mountOwnerApprovals(app, {
165
+ checkPassphrase: (input) => provider.checkPassphrase(input),
166
+ throttle: approveThrottle,
167
+ deps: t.approvalsDeps,
168
+ ownerId: () => resolveTokenSubject(dbManager.db)
169
+ });
170
+ }
171
+
139
172
  // OAuth 2.1 authorization server + protected-resource metadata:
140
173
  // /.well-known/oauth-authorization-server, /.well-known/oauth-protected-resource/mcp,
141
174
  // /register, /authorize, /token, /revoke
@@ -265,5 +298,17 @@ app.post('/mcp', requireBearerAuth({ verifier: provider, resourceMetadataUrl: PR
265
298
  if (!PASSPHRASE) console.error('[emet] WARNING: EMET_OAUTH_PASSPHRASE unset — all authorization attempts will be rejected.');
266
299
  try { await dbManager.ensureClient(); console.error('[emet] Mongo connected'); }
267
300
  catch (e) { console.error('[emet] Mongo connect FAILED:', e.message); }
301
+ try {
302
+ const { seatGems } = await import('./socket.js');
303
+ const seated = await seatGems({ log: logger });
304
+ // The structured line keeps the id in the middle of a JSON object. This
305
+ // line ends with the id so the image boot can anchor it.
306
+ for (const row of seated.gems_available || []) {
307
+ if (row.loadable) console.error(`GEM seated: ${row.id}`);
308
+ }
309
+ }
310
+ catch (e) { console.error('[emet] GEM socket failed closed'); }
268
311
  app.listen(PORT, HOST, () => console.error(`[emet] listening ${PUBLIC_URL} (bind ${HOST}:${PORT}); /mcp OAuth-protected; PRM ${PRM_URL}`));
312
+ import('./subkeys.js').then((m) => m.startFlagOffSweep((msg) => console.error(`[emet] ${msg}`))).catch(() => console.error('[emet] sub-key flag-off sweep failed'));
313
+ import('./error-log.js').then((m) => m.startErrorLogRotation()).catch(() => {});
269
314
  })();
package/src/index.js CHANGED
@@ -57,6 +57,8 @@ import {
57
57
  } from './database.js';
58
58
 
59
59
  import { dispatchTool } from './dispatch.js';
60
+ import { seatGems } from './socket.js';
61
+ import { runeToolList } from './rune-registry.js';
60
62
  // Import tools module (the per-tool handlers are reached through dispatch.js)
61
63
  import {
62
64
  TOOLS,
@@ -124,7 +126,7 @@ const server = new Server(
124
126
  * List available tools
125
127
  */
126
128
  server.setRequestHandler(ListToolsRequestSchema, async () => {
127
- return { tools: TOOLS };
129
+ return { tools: [...TOOLS, ...runeToolList()] };
128
130
  });
129
131
 
130
132
  /**
@@ -169,7 +171,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
169
171
  // Every tool call leaves one audit entry (H6, 2026-09-19). callTool never
170
172
  // throws: it returns either a success response or handleError's response.
171
173
  const t0 = Date.now();
172
- // Parameter NAMES, never values (the owner, 2026-09-27, code audit 1.6): the next
174
+ // Parameter NAMES, never values (Alex, 2026-09-27, code audit 1.6): the next
173
175
  // audit can measure which parameters hosts use; nothing a host sent is stored.
174
176
  const paramNames = Object.keys(args || {}).sort();
175
177
  const result = await actorStore.run(actor, () => callTool(name, args));
@@ -256,6 +258,12 @@ async function main() {
256
258
  }
257
259
  }
258
260
 
261
+ try { await seatGems({ log: logger }); }
262
+ catch (e) { logger.error('GEM socket failed closed', { error: e && e.message }); }
263
+
264
+ import('./subkeys.js').then((m) => m.startFlagOffSweep((msg) => logger.error(msg))).catch((e) => logger.error('sub-key flag-off sweep failed', { error: e && e.message }));
265
+ import('./error-log.js').then((m) => m.startErrorLogRotation()).catch(() => {});
266
+
259
267
  const startupDurationMs = Date.now() - startTime;
260
268
 
261
269
  logger.audit(AuditOperation.SERVER_START, {
package/src/invites.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import crypto from 'crypto';
2
2
  import { slugPersonId } from './persons.js';
3
3
  import { setting } from './env.js';
4
+ import { CodedError } from './error-codes.js';
4
5
 
5
6
  const COLLECTION = 'invites';
6
7
 
@@ -29,13 +30,13 @@ export const DOORS_FROZEN_REASON =
29
30
 
30
31
  export async function createInvite(db, { created_by, display_name, scopes = ['emet.read'], days = 14, source_tag = null } = {}) {
31
32
  if (INVITES_FROZEN) {
32
- const err = new Error(INVITES_FROZEN_REASON);
33
+ const err = new CodedError(INVITES_FROZEN_REASON, { code: 'EMET-AUTH-030' });
33
34
  err.code = 'INVITES_FROZEN';
34
35
  throw err;
35
36
  }
36
37
  const requested = Array.isArray(scopes) && scopes.length ? scopes : ['emet.read'];
37
38
  if (requested.length !== 1 || requested[0] !== 'emet.read') {
38
- const err = new Error('A guest invite accepts only emet.read');
39
+ const err = new CodedError('A guest invite accepts only emet.read', { code: 'EMET-AUTH-031' });
39
40
  err.code = 'GUEST_SCOPE';
40
41
  throw err;
41
42
  }
@@ -59,7 +60,7 @@ export async function createInvite(db, { created_by, display_name, scopes = ['em
59
60
 
60
61
  export async function createMemberAccess(db, { created_by, display_name, days = 14, source_tag = null } = {}) {
61
62
  if (MEMBER_ACCESS_FROZEN) {
62
- const err = new Error(MEMBER_ACCESS_FROZEN_REASON);
63
+ const err = new CodedError(MEMBER_ACCESS_FROZEN_REASON, { code: 'EMET-AUTH-034' });
63
64
  err.code = 'MEMBER_ACCESS_FROZEN';
64
65
  throw err;
65
66
  }
@@ -109,7 +110,7 @@ export async function allocateGuestPersonId(persons, display_name) {
109
110
  const id = `${base}-${n}`;
110
111
  if (!(await taken(id))) return id;
111
112
  }
112
- throw new Error('could not allocate a person id for this invite');
113
+ throw new CodedError('could not allocate a person id for this invite', { code: 'EMET-AUTH-001' });
113
114
  }
114
115
 
115
116
  function claimedRow(result) {
@@ -161,7 +162,7 @@ export async function redeemInvite(db, code) {
161
162
  if (!(e && (e.code === 11000 || /duplicate/i.test(String(e.message || ''))))) throw e;
162
163
  }
163
164
  }
164
- if (!saved) throw new Error('could not allocate a person id for this invite');
165
+ if (!saved) throw new CodedError('could not allocate a person id for this invite', { code: 'EMET-AUTH-001' });
165
166
  await col.updateOne({ digest }, { $set: { person_id } });
166
167
  return { ok: true, person_id, scopes, display_name: claimed.display_name || row.display_name, door, source_tag: claimed.source_tag || row.source_tag || null };
167
168
  }
package/src/layers.js CHANGED
@@ -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
@@ -238,7 +239,7 @@ export function resolveLayer(name) {
238
239
  export function bandFor(layer) {
239
240
  const entry = LAYER_CHARTER[layer];
240
241
  if (!entry || !Array.isArray(entry.importance_range)) {
241
- throw new Error(`Unknown layer '${layer}'. Must be one of: ${LAYERS.join(', ')}`);
242
+ throw new CodedError(`Unknown layer '${layer}'. Must be one of: ${LAYERS.join(', ')}`, { code: 'EMET-MEM-001' });
242
243
  }
243
244
  const [min, max] = entry.importance_range;
244
245
  // Rounded so 0.3 + 0.6 reads as 0.45, not 0.44999999999999996.
@@ -247,7 +248,7 @@ export function bandFor(layer) {
247
248
 
248
249
  /** Named importance buckets. The word is the differentiator; the range is
249
250
  * compatibility for the stored float. Degree (low/mid/high) is the only
250
- * reason to pick a number other than the midpoint. The owner 2026-09-26. */
251
+ * reason to pick a number other than the midpoint. Alex 2026-09-26. */
251
252
  export const IMPORTANCE_BUCKETS = Object.freeze({
252
253
  constitutive: { range: [0.9, 1.0], layers: ['identity'] },
253
254
  durable: { range: [0.6, 0.9], layers: ['semantic', 'meta'] },
@@ -304,20 +305,20 @@ export function resolveImportance(layer, raw, extras = {}) {
304
305
  } else if (IMPORTANCE_DEGREES.includes(parts[0])) {
305
306
  degree = parts[0];
306
307
  } else {
307
- throw new Error(
308
+ throw new CodedError(
308
309
  `Unknown importance bucket '${raw}'. Use one of: ${Object.keys(IMPORTANCE_BUCKETS).join(', ')}` +
309
310
  ` (optional :low|:mid|:high).`
310
- );
311
+ , { code: 'EMET-MEM-002' });
311
312
  }
312
313
  }
313
314
 
314
315
  if (bucket && !IMPORTANCE_BUCKETS[bucket]) {
315
- throw new Error(
316
+ throw new CodedError(
316
317
  `Unknown importance bucket '${bucket}'. Use one of: ${Object.keys(IMPORTANCE_BUCKETS).join(', ')}`
317
- );
318
+ , { code: 'EMET-MEM-003' });
318
319
  }
319
320
  if (degree && !IMPORTANCE_DEGREES.includes(degree)) {
320
- throw new Error(`Unknown importance degree '${degree}'. Use low, mid, or high.`);
321
+ throw new CodedError(`Unknown importance degree '${degree}'. Use low, mid, or high.`, { code: 'EMET-MEM-004' });
321
322
  }
322
323
 
323
324
  if (typeof raw === 'number' && Number.isFinite(raw)) {
@@ -362,7 +363,7 @@ export function resolveImportance(layer, raw, extras = {}) {
362
363
  export function policyFor(layer) {
363
364
  const entry = LAYER_CHARTER[layer];
364
365
  if (!entry) {
365
- throw new Error(`Unknown layer '${layer}'. Must be one of: ${LAYERS.join(', ')}`);
366
+ throw new CodedError(`Unknown layer '${layer}'. Must be one of: ${LAYERS.join(', ')}`, { code: 'EMET-MEM-001' });
366
367
  }
367
368
  return {
368
369
  revisable: entry.revisable,
@@ -32,7 +32,7 @@
32
32
  *
33
33
  * Source of the three-attempt rule and the scope line: Hanako, "Loops and
34
34
  * Graphs" (2026-08-23), read in full 2026-09-27; the user's decisions are in
35
- * the owner's store.
35
+ * staging/emet-lessons-to-checks.md.
36
36
  */
37
37
 
38
38
  // ---------------------------------------------------------------------------
@@ -244,7 +244,7 @@ function familyEntry(members, key) {
244
244
  * One detector, the explicit key (2026-09-29). Rows carrying metadata.lesson
245
245
  * are grouped by that key - the writer says "same lesson" at save time and
246
246
  * nothing is inferred. The tag-family heuristic that ran beside it in shadow
247
- * from 2026-09-27 was DROPPED on the owner's ruling: "that's
247
+ * from 2026-09-27 was DROPPED on the owner's ruling (procedural ref 397): "that's
248
248
  * just another instance of forking... I would rather the original be more
249
249
  * heavily, better enforced, than having a backup that can rot or fork." The
250
250
  * enforcement moved to the write: checkLessonFields below refuses a malformed
@@ -292,7 +292,7 @@ export function pendingLessons(rows, { threshold = LESSON_REPEAT_THRESHOLD } = {
292
292
  }
293
293
 
294
294
  // ---------------------------------------------------------------------------
295
- // 4. The lesson fields are checked at the door (2026-09-29, a decision record)
295
+ // 4. The lesson fields are checked at the door (2026-09-29, procedural ref 397)
296
296
  // ---------------------------------------------------------------------------
297
297
 
298
298
  /** A lesson key is a lowercase slug: letters and digits in hyphen-joined
package/src/logger.js CHANGED
@@ -51,7 +51,8 @@ const AuditOperation = Object.freeze({
51
51
  VALIDATION_FAIL: 'VALIDATION_FAIL',
52
52
  SERVER_START: 'SERVER_START',
53
53
  SERVER_STOP: 'SERVER_STOP',
54
- CONFIG_CHANGE: 'CONFIG_CHANGE'
54
+ CONFIG_CHANGE: 'CONFIG_CHANGE',
55
+ GEM_SERVE: 'GEM_SERVE'
55
56
  });
56
57
 
57
58
  /**
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * EMET - the one way to open a MongoDB connection (2026-09-29).
3
3
  *
4
- * Some local resolvers (home routers, VPN DNS) refuse
4
+ * Some local resolvers (home routers, VPN DNS - STUDIO's among them) refuse
5
5
  * the SRV queries a mongodb+srv:// URI needs, and the driver fails with
6
6
  * "querySrv ECONNREFUSED". Until today the public-DNS fallback lived only in
7
7
  * EmetDatabase.ensureClient; nine other connections in src/ and
@@ -31,9 +31,57 @@ export function isSrvRefusal(error) {
31
31
  * with no database. Never set outside tests; null means the real driver.
32
32
  */
33
33
  let testClient = null;
34
- export function useTestClient(Client) { testClient = Client || null; }
34
+ let sharedClient = null;
35
+ let sharedToken = null;
36
+ let sharedConnect = null;
37
+
38
+ /** The server's Mongo client, reused by stores that would otherwise connect per call. */
39
+ /** The client already opened for this process, or null. Does not connect. */
40
+ export function readySharedClient() {
41
+ return sharedClient;
42
+ }
43
+
44
+ export function bindSharedClient(client) {
45
+ if (!client) return;
46
+ sharedClient = client;
47
+ sharedToken = testClient || 'live';
48
+ }
49
+
50
+ function resetSharedClient() {
51
+ sharedClient = null;
52
+ sharedToken = null;
53
+ sharedConnect = null;
54
+ }
55
+
56
+ export function useTestClient(Client) {
57
+ testClient = Client || null;
58
+ resetSharedClient();
59
+ }
35
60
  export function testClientActive() { return testClient != null; }
36
61
 
62
+ /**
63
+ * One client for this process (or for the installed test client). A second
64
+ * call does not open another connection.
65
+ */
66
+ export async function acquireSharedClient(uri, options = {}) {
67
+ const token = testClient || 'live';
68
+ if (sharedClient && sharedToken === token) return sharedClient;
69
+ if (!sharedConnect) {
70
+ let resolve;
71
+ let reject;
72
+ // Assign before connectMongo yields, so a second caller waits on this promise.
73
+ sharedConnect = new Promise((res, rej) => { resolve = res; reject = rej; });
74
+ connectMongo(uri, options).then((client) => {
75
+ if ((testClient || 'live') === token && sharedConnect) {
76
+ sharedClient = client;
77
+ sharedToken = token;
78
+ }
79
+ resolve(client);
80
+ }, reject).finally(() => { sharedConnect = null; });
81
+ }
82
+ return sharedConnect;
83
+ }
84
+
37
85
  /** Connect and return the client. `onFallback(message)` is told when the retry happens. */
38
86
  export async function connectMongo(uri, options = {}, { onFallback = null, _Client = testClient || MongoClient, _dns = dns } = {}) {
39
87
  const attempt = async () => { const c = new _Client(uri, options); await c.connect(); return c; };
@@ -43,6 +43,7 @@ import { COLLECTION_PREFIX } from './database.js';
43
43
  import { setting } from './env.js';
44
44
  import { InvalidGrantError, InvalidScopeError, InvalidTokenError } from '@modelcontextprotocol/sdk/server/auth/errors.js';
45
45
  import { scopesNotGranted } from './scopes.js';
46
+ import { CodedError, assignCode } from './error-codes.js';
46
47
 
47
48
  const CODE_TTL_MS = 5 * 60 * 1000; // authorization codes: 5 minutes
48
49
  const ACCESS_TTL_S = 60 * 60; // access tokens: 1 hour
@@ -83,7 +84,7 @@ function escapeHtml(s) {
83
84
  return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
84
85
  }
85
86
 
86
- function timingSafeEqualStr(a, b) {
87
+ export function timingSafeEqualStr(a, b) {
87
88
  const ab = Buffer.from(String(a));
88
89
  const bb = Buffer.from(String(b));
89
90
  if (ab.length !== bb.length) {
@@ -122,17 +123,17 @@ export function isCimdClientId(clientId) {
122
123
  */
123
124
  export function validateCimdDocument(doc, url) {
124
125
  if (!doc || typeof doc !== 'object' || Array.isArray(doc)) {
125
- throw new Error('CIMD document must be a JSON object');
126
+ throw new CodedError('CIMD document must be a JSON object', { code: 'EMET-AUTH-002' });
126
127
  }
127
128
  if (doc.client_id !== url) {
128
- throw new Error(`CIMD document client_id does not match its URL (expected ${url})`);
129
+ throw new CodedError(`CIMD document client_id does not match its URL (expected ${url})`, { code: 'EMET-AUTH-003' });
129
130
  }
130
131
  if (!Array.isArray(doc.redirect_uris) || doc.redirect_uris.length === 0 || !doc.redirect_uris.every(r => typeof r === 'string' && r.length > 0)) {
131
- throw new Error('CIMD document must carry a non-empty redirect_uris array of strings');
132
+ throw new CodedError('CIMD document must carry a non-empty redirect_uris array of strings', { code: 'EMET-AUTH-004' });
132
133
  }
133
134
  const method = doc.token_endpoint_auth_method === undefined ? 'none' : doc.token_endpoint_auth_method;
134
135
  if (method !== 'none') {
135
- throw new Error(`CIMD clients are public; token_endpoint_auth_method must be "none" (got ${method})`);
136
+ throw new CodedError(`CIMD clients are public; token_endpoint_auth_method must be "none" (got ${method})`, { code: 'EMET-AUTH-005' });
136
137
  }
137
138
  const { client_secret, client_secret_expires_at, ...rest } = doc;
138
139
  return {
@@ -216,17 +217,17 @@ export async function assertCimdTargetPublic(url, lookup) {
216
217
  const u = new URL(url);
217
218
  const host = u.hostname.replace(/^\[|\]$/g, '');
218
219
  if (!host || host === 'localhost' || host.endsWith('.localhost') || host === 'metadata.google.internal') {
219
- throw new Error('CIMD host is not a public address');
220
+ throw new CodedError('CIMD host is not a public address', { code: 'EMET-AUTH-006' });
220
221
  }
221
- if (isBlockedCimdAddress(host)) throw new Error('CIMD host is not a public address');
222
+ if (isBlockedCimdAddress(host)) throw new CodedError('CIMD host is not a public address', { code: 'EMET-AUTH-006' });
222
223
  const fn = lookup || dnsPromises.lookup;
223
224
  const found = await fn(host, { all: true, verbatim: true });
224
225
  const list = Array.isArray(found) ? found : (found ? [found] : []);
225
- if (!list.length) throw new Error('CIMD host did not resolve');
226
+ if (!list.length) throw new CodedError('CIMD host did not resolve', { code: 'EMET-AUTH-007' });
226
227
  const checked = [];
227
228
  for (const item of list) {
228
229
  const address = typeof item === 'string' ? item : item && item.address;
229
- if (isBlockedCimdAddress(address)) throw new Error('CIMD host resolves to a blocked address');
230
+ if (isBlockedCimdAddress(address)) throw new CodedError('CIMD host resolves to a blocked address', { code: 'EMET-AUTH-008' });
230
231
  const family = (item && item.family === 6) || String(address).includes(':') ? 6 : 4;
231
232
  checked.push({ address, family });
232
233
  }
@@ -535,7 +536,7 @@ export class MongoOAuthProvider {
535
536
 
536
537
  async _fetchCimdDocument(url) {
537
538
  const host = new URL(url).hostname;
538
- if (!takeCimdFetchSlot(host)) throw new Error('CIMD fetch rate limit');
539
+ if (!takeCimdFetchSlot(host)) throw new CodedError('CIMD fetch rate limit', { code: 'EMET-AUTH-009' });
539
540
  const checked = await assertCimdTargetPublic(url, this._lookup);
540
541
  const chosen = checked[0];
541
542
  const controller = new AbortController();
@@ -550,13 +551,13 @@ export class MongoOAuthProvider {
550
551
  const res = this._fetch
551
552
  ? await this._fetch(url, init)
552
553
  : await pinnedHttpsGet(url, init, this._https);
553
- if (!res || !res.ok) throw new Error(`HTTP ${res ? res.status : 'no response'}`);
554
+ if (!res || !res.ok) throw new CodedError(`HTTP ${res ? res.status : 'no response'}`, { code: 'EMET-AUTH-010' });
554
555
  const text = await res.text();
555
556
  if (typeof text !== 'string' || Buffer.byteLength(text, 'utf8') > CIMD_MAX_BYTES) {
556
- throw new Error(`document exceeds ${CIMD_MAX_BYTES} bytes`);
557
+ throw new CodedError(`document exceeds ${CIMD_MAX_BYTES} bytes`, { code: 'EMET-AUTH-011' });
557
558
  }
558
559
  try { return JSON.parse(text); }
559
- catch { throw new Error('document is not valid JSON'); }
560
+ catch { throw new CodedError('document is not valid JSON', { code: 'EMET-AUTH-012' }); }
560
561
  } finally {
561
562
  clearTimeout(timer);
562
563
  }
@@ -635,7 +636,7 @@ export class MongoOAuthProvider {
635
636
 
636
637
  async challengeForAuthorizationCode(client, authorizationCode) {
637
638
  const doc = await this.col('codes').findOne({ code: tokenDigest(authorizationCode), client_id: client.client_id });
638
- if (!doc) throw new InvalidGrantError('this authorization code is not recognised - start the connection again');
639
+ if (!doc) throw assignCode(new InvalidGrantError('this authorization code is not recognised - start the connection again'), 'EMET-AUTH-013');
639
640
  return doc.code_challenge;
640
641
  }
641
642
 
@@ -643,15 +644,15 @@ export class MongoOAuthProvider {
643
644
  const codes = this.col('codes');
644
645
  const digest = tokenDigest(authorizationCode);
645
646
  const existing = await codes.findOne({ code: digest, client_id: client.client_id });
646
- if (!existing) throw new InvalidGrantError('this authorization code is not recognised - start the connection again');
647
- if (existing.expiresAtMs < Date.now()) throw new InvalidGrantError('this authorization code has expired - start the connection again');
648
- if (redirectUri && existing.redirect_uri && redirectUri !== existing.redirect_uri) throw new InvalidGrantError('redirect_uri does not match the one this code was issued for');
647
+ if (!existing) throw assignCode(new InvalidGrantError('this authorization code is not recognised - start the connection again'), 'EMET-AUTH-013');
648
+ if (existing.expiresAtMs < Date.now()) throw assignCode(new InvalidGrantError('this authorization code has expired - start the connection again'), 'EMET-AUTH-014');
649
+ if (redirectUri && existing.redirect_uri && redirectUri !== existing.redirect_uri) throw assignCode(new InvalidGrantError('redirect_uri does not match the one this code was issued for'), 'EMET-AUTH-015');
649
650
  const claimed = await codes.findOneAndUpdate(
650
651
  { code: digest, client_id: client.client_id, used: false },
651
652
  { $set: { used: true } }
652
653
  );
653
654
  const doc = claimed && Object.prototype.hasOwnProperty.call(claimed, 'value') ? claimed.value : claimed;
654
- if (!doc) throw new InvalidGrantError('this authorization code has already been used - start the connection again');
655
+ if (!doc) throw assignCode(new InvalidGrantError('this authorization code has already been used - start the connection again'), 'EMET-AUTH-016');
655
656
  return this._issueTokens(client.client_id, doc.scopes || [], doc.resource || (resource ? resource.href : null), doc.subject || null, doc.issued_via || null, null, doc.source_tag || null);
656
657
  }
657
658
 
@@ -668,21 +669,21 @@ export class MongoOAuthProvider {
668
669
  // Every refusal here is an OAuth error the SDK maps to 400 invalid_grant
669
670
  // (RFC 6749 section 5.2). A plain Error became a 500 server_error, which
670
671
  // told the client the server was broken instead of "sign in again".
671
- if (!rt) throw new InvalidGrantError('this refresh token is not recognised (it may have been revoked, or issued to another client) - reconnect to sign in again');
672
+ if (!rt) throw assignCode(new InvalidGrantError('this refresh token is not recognised (it may have been revoked, or issued to another client) - reconnect to sign in again'), 'EMET-AUTH-017');
672
673
  const nowS = Math.floor(Date.now() / 1000);
673
- if (rt.expiresAt && rt.expiresAt < nowS) throw new InvalidGrantError('this refresh token has expired - reconnect to sign in again');
674
+ if (rt.expiresAt && rt.expiresAt < nowS) throw assignCode(new InvalidGrantError('this refresh token has expired - reconnect to sign in again'), 'EMET-AUTH-018');
674
675
  // A token issued before source tags were stored must not mint another
675
676
  // token with an empty tag. The client signs in again; the new consent
676
677
  // binds a registered tag. Expiry is reported first, so an expired
677
678
  // legacy token still says it has expired.
678
679
  if (!rt.source_tag) {
679
- throw new InvalidGrantError('this login has no source tag bound. Sign in again so the new consent binds a registered tag.');
680
+ throw assignCode(new InvalidGrantError('this login has no source tag bound. Sign in again so the new consent binds a registered tag.'), 'EMET-AUTH-019');
680
681
  }
681
682
  if (typeof rt.rotated_at === 'number') {
682
683
  const withinGrace = (nowS - rt.rotated_at) <= REFRESH_ROTATION_GRACE_S && rt.grace_replacement;
683
684
  if (withinGrace) return { ...rt.grace_replacement };
684
685
  await this._revokeFamily(rt);
685
- throw new InvalidGrantError('this refresh token has already been replaced by a newer one - reconnect to sign in again');
686
+ throw assignCode(new InvalidGrantError('this refresh token has already been replaced by a newer one - reconnect to sign in again'), 'EMET-AUTH-020');
686
687
  }
687
688
  // R6: a token minted from an invite stops refreshing while invites are
688
689
  // frozen, so a re-freeze ends it within one access-token lifetime instead
@@ -692,10 +693,10 @@ export class MongoOAuthProvider {
692
693
  // likewise against EMET_INVITES.
693
694
  const door = await this._tokenDoor(rt);
694
695
  if (door === 'member' && await this._memberAccessIsFrozen()) {
695
- throw new InvalidGrantError('this login came from EMET Member Access, and member access is off on this install - it can no longer be refreshed');
696
+ throw assignCode(new InvalidGrantError('this login came from EMET Member Access, and member access is off on this install - it can no longer be refreshed'), 'EMET-AUTH-021');
696
697
  }
697
698
  if (door === 'guest' && await this._invitesAreFrozen()) {
698
- throw new InvalidGrantError('this login came from an invite, and invites are off on this install - it can no longer be refreshed');
699
+ throw assignCode(new InvalidGrantError('this login came from an invite, and invites are off on this install - it can no longer be refreshed'), 'EMET-AUTH-022');
699
700
  }
700
701
  // Defect 1: a refresh keeps or narrows the scopes granted, never widens
701
702
  // them (RFC 6749 section 6: a requested scope not originally granted is
@@ -704,7 +705,7 @@ export class MongoOAuthProvider {
704
705
  const granted = rt.scopes || [];
705
706
  const wider = scopesNotGranted(granted, requested);
706
707
  if (wider.length) {
707
- throw new InvalidScopeError(`a refresh cannot widen scope: ${wider.join(', ')} was not granted (granted: ${granted.join(', ')})`);
708
+ throw assignCode(new InvalidScopeError(`a refresh cannot widen scope: ${wider.join(', ')} was not granted (granted: ${granted.join(', ')})`), 'EMET-AUTH-023');
708
709
  }
709
710
  const useScopes = requested.length ? requested : granted;
710
711
  const family = rt.family || randTok(16);
@@ -722,7 +723,7 @@ export class MongoOAuthProvider {
722
723
  return { ...fresh.grace_replacement };
723
724
  }
724
725
  await this._revokeFamily(fresh || rt);
725
- throw new InvalidGrantError('this refresh token has already been replaced by a newer one - reconnect to sign in again');
726
+ throw assignCode(new InvalidGrantError('this refresh token has already been replaced by a newer one - reconnect to sign in again'), 'EMET-AUTH-020');
726
727
  }
727
728
  return out;
728
729
  }
@@ -817,14 +818,14 @@ export class MongoOAuthProvider {
817
818
  // Error here became a 500 server_error for every expired or revoked login.
818
819
  // No double quotes in these messages: they are copied into that header.
819
820
  const doc = await this._findToken(token, 'access');
820
- if (!doc) throw new InvalidTokenError('this access token is not recognised (it may have been revoked or replaced) - sign in again');
821
- if (doc.expiresAt && doc.expiresAt * 1000 < Date.now()) throw new InvalidTokenError('this access token has expired - refresh it or sign in again');
821
+ if (!doc) throw assignCode(new InvalidTokenError('this access token is not recognised (it may have been revoked or replaced) - sign in again'), 'EMET-AUTH-024');
822
+ if (doc.expiresAt && doc.expiresAt * 1000 < Date.now()) throw assignCode(new InvalidTokenError('this access token has expired - refresh it or sign in again'), 'EMET-AUTH-025');
822
823
  return {
823
824
  token,
824
825
  clientId: doc.client_id,
825
826
  scopes: doc.scopes || [],
826
827
  expiresAt: doc.expiresAt,
827
- extra: { subject: doc.subject || 'owner', sourceTag: doc.source_tag || null },
828
+ extra: { subject: doc.subject || 'owner', sourceTag: doc.source_tag || null, grantId: doc.family || null },
828
829
  };
829
830
  }
830
831