@dreamforgestudiollc/emet 0.3.5 → 0.3.7

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 (103) hide show
  1. package/.env.example +29 -0
  2. package/CHANGELOG.md +49 -11
  3. package/CHARTER.md +1 -1
  4. package/CONTRIBUTING.md +21 -0
  5. package/README.md +25 -10
  6. package/RELEASE_NOTES-0.2.6.md +43 -0
  7. package/RELEASE_NOTES-0.3.6.md +29 -0
  8. package/RELEASE_NOTES-0.3.7.md +19 -0
  9. package/SECURITY.md +13 -0
  10. package/docs/BOTS.md +4 -4
  11. package/docs/DEPLOY.md +23 -4
  12. package/docs/ERROR-CODES-SPEC.md +4 -0
  13. package/docs/ERROR-CODES.md +7 -0
  14. package/docs/GUIDED-SETUP.md +1 -1
  15. package/docs/ROADMAP.md +62 -49
  16. package/docs/SETUP.md +11 -1
  17. package/docs/SUBKEYS.md +3 -1
  18. package/docs/continuity-currency-statechart.md +34 -0
  19. package/docs/features/README.md +21 -0
  20. package/docs/features/access.md +28 -0
  21. package/docs/features/documents.md +35 -0
  22. package/docs/features/errors.md +32 -0
  23. package/docs/features/gems.md +31 -0
  24. package/docs/features/memory.md +29 -0
  25. package/docs/features/pages.md +28 -0
  26. package/docs/features/record.md +27 -0
  27. package/docs/features/search.md +27 -0
  28. package/docs/features/startup.md +29 -0
  29. package/docs/features/subkeys.md +30 -0
  30. package/docs/features/transcripts.md +33 -0
  31. package/docs/per-tag-handoff-statechart.md +147 -0
  32. package/docs/subkey-session-statechart.md +57 -0
  33. package/package.json +6 -2
  34. package/server.json +27 -2
  35. package/src/annotations.js +5 -3
  36. package/src/attribution.js +2 -2
  37. package/src/carry-forward-close.js +1 -1
  38. package/src/chooser.js +74 -3
  39. package/src/conformance.js +2 -0
  40. package/src/continuity-currency-statechart.js +139 -0
  41. package/src/continuity-currency.js +869 -0
  42. package/src/database.js +1 -1
  43. package/src/dispatch.js +1 -1
  44. package/src/error-codes.js +7 -0
  45. package/src/gem-check.js +4 -1
  46. package/src/grants.js +28 -5
  47. package/src/host-reach.js +1 -1
  48. package/src/http-remote.js +29 -5
  49. package/src/index.js +3 -2
  50. package/src/invites.js +2 -2
  51. package/src/owl.js +12 -11
  52. package/src/pages.js +15 -0
  53. package/src/per-tag-handoff-statechart.js +264 -0
  54. package/src/per-tag-handoff.js +988 -0
  55. package/src/persons.js +16 -0
  56. package/src/session-graph.js +123 -12
  57. package/src/session.js +56 -12
  58. package/src/setup.js +32 -11
  59. package/src/startup-pages.js +13 -2
  60. package/src/subkey-lifecycle.js +105 -0
  61. package/src/subkey-session-statechart.js +253 -0
  62. package/src/subkeys.js +648 -89
  63. package/src/tools.js +171 -51
  64. package/src/transcript-session.js +2 -2
  65. package/src/version.js +1 -1
  66. package/templates/INDEX.md +1 -0
  67. package/templates/SESSIONDISPOSITION.md +2 -2
  68. package/templates/TAGHANDOFF.md +45 -0
  69. package/verification/continuity-currency/ContinuityCurrency.cfg +12 -0
  70. package/verification/continuity-currency/ContinuityCurrency.tla +239 -0
  71. package/verification/continuity-currency/tlc-output.txt +32 -0
  72. package/verification/continuity-currency/view.mjs +54 -0
  73. package/verification/load-gate/load-gate.mjs +1 -1
  74. package/verification/per-tag-handoff/PerTagHandoff.cfg +10 -0
  75. package/verification/per-tag-handoff/PerTagHandoff.tla +191 -0
  76. package/verification/per-tag-handoff/StampCounter.cfg +10 -0
  77. package/verification/per-tag-handoff/out/report.md +6 -0
  78. package/verification/per-tag-handoff/out-counter/chart.mmd +30 -0
  79. package/verification/per-tag-handoff/out-counter/report.md +15 -0
  80. package/verification/per-tag-handoff/out-counter/tlc.out +130 -0
  81. package/verification/per-tag-handoff/split/PerTagConflict.cfg +6 -0
  82. package/verification/per-tag-handoff/split/PerTagConflict.tla +104 -0
  83. package/verification/per-tag-handoff/split/PerTagTime.cfg +8 -0
  84. package/verification/per-tag-handoff/split/PerTagTime.tla +100 -0
  85. package/verification/per-tag-handoff/split/conflict-chart.mmd +47 -0
  86. package/verification/per-tag-handoff/split/conflict-report.md +8 -0
  87. package/verification/per-tag-handoff/split/conflict-tlc.txt +19 -0
  88. package/verification/per-tag-handoff/split/conflict-view.mjs +34 -0
  89. package/verification/per-tag-handoff/split/time-chart.mmd +44 -0
  90. package/verification/per-tag-handoff/split/time-report.md +8 -0
  91. package/verification/per-tag-handoff/split/time-tlc.txt +19 -0
  92. package/verification/per-tag-handoff/split/time-view.mjs +33 -0
  93. package/verification/per-tag-handoff/tlc-output.txt +19 -0
  94. package/verification/per-tag-handoff/v1-draft/PerTagHandoff.cfg +5 -0
  95. package/verification/per-tag-handoff/v1-draft/PerTagHandoff.tla +94 -0
  96. package/verification/per-tag-handoff/v1-draft/out/chart.mmd +37 -0
  97. package/verification/per-tag-handoff/v1-draft/out/report.md +7 -0
  98. package/verification/per-tag-handoff/v1-draft/out/tlc.out +19 -0
  99. package/verification/per-tag-handoff/v1-draft/view.mjs +20 -0
  100. package/verification/per-tag-handoff/view.mjs +31 -0
  101. package/verification/subkey-session/SubkeySession.cfg +11 -0
  102. package/verification/subkey-session/SubkeySession.tla +254 -0
  103. package/verification/subkey-session/tlc-output.txt +13 -0
package/src/database.js CHANGED
@@ -454,7 +454,7 @@ export class EmetDatabase {
454
454
  }
455
455
 
456
456
  /**
457
- * THE layer insert, native (2026-09-27, code audit 1.7 stage 1 - Alex: "if SQL
457
+ * THE layer insert, native (2026-09-27, code audit 1.7 stage 1 - the owner: "if SQL
458
458
  * is the old and needs to be updated then update it"). Takes the document as
459
459
  * a document. Every key must be a known layer field; the id is allocated
460
460
  * here. The INSERT-string shim it replaced went with the SQL translator in
package/src/dispatch.js CHANGED
@@ -38,7 +38,7 @@ import { beginStagedDoc, appendStagedChunk, commitStagedDoc, abortStagedDoc } fr
38
38
  import { reserveToolNames } from './rune-registry.js';
39
39
  import { applyCheckpoint, checkpointOnError, checkpointStatus } from './checkpoint.js';
40
40
 
41
- reserveToolNames([...TOOLS.map((tool) => tool.name), 'emet_subkey_request', 'emet_subkey_claim', 'emet_subkey_revoke', 'emet_subkey_end_session']);
41
+ reserveToolNames([...TOOLS.map((tool) => tool.name), 'emet_subkey_request', 'emet_subkey_claim', 'emet_subkey_revoke', 'emet_subkey_end_session', 'emet_subkey_set_kind']);
42
42
 
43
43
  /**
44
44
  * Route one tool call. `ctx` carries what the transport owns: dbManager, logger,
@@ -93,6 +93,7 @@ export const ERROR_CODES = Object.freeze({
93
93
  'EMET-CFG-012': Object.freeze({ area: 'CFG', summary: "Backup answer must be yes or no", status: 'active', internal: false }),
94
94
  'EMET-CFG-013': Object.freeze({ area: 'CFG', summary: "Setup requires the owner", status: 'active', internal: false }),
95
95
  'EMET-CFG-014': Object.freeze({ area: 'CFG', summary: "Store is already set up", status: 'active', internal: false }),
96
+ 'EMET-CFG-015': Object.freeze({ area: 'CFG', summary: "Per-tag handoffs are on and the hub tag is unset", status: 'active', internal: false }),
96
97
  'EMET-DB-001': Object.freeze({ area: 'DB', summary: "MONGODB_URI is not set", status: 'active', internal: false }),
97
98
  'EMET-DB-002': Object.freeze({ area: 'DB', summary: "Failed to connect to MongoDB", status: 'active', internal: false }),
98
99
  'EMET-DB-003': Object.freeze({ area: 'DB', summary: "Query failed on a memory layer", status: 'active', internal: false }),
@@ -207,6 +208,11 @@ export const ERROR_CODES = Object.freeze({
207
208
  'EMET-DOC-078': Object.freeze({ area: 'DOC', summary: "Commit reason does not match the stage", status: 'active', internal: false }),
208
209
  'EMET-DOC-079': Object.freeze({ area: 'DOC', summary: "This call's source does not match the stage", status: 'active', internal: false }),
209
210
  'EMET-DOC-080': Object.freeze({ area: 'DOC', summary: "This call's session does not match the stage", status: 'active', internal: false }),
211
+ 'EMET-DOC-084': Object.freeze({ area: 'DOC', summary: "Another tag's handoff, folder, or an unregistered credential", status: 'active', internal: false }),
212
+ 'EMET-DOC-085': Object.freeze({ area: 'DOC', summary: "A credential changed a board row it did not open", status: 'active', internal: false }),
213
+ 'EMET-DOC-086': Object.freeze({ area: 'DOC', summary: "A reserved, malformed, or person-equal handoff id", status: 'active', internal: false }),
214
+ 'EMET-DOC-087': Object.freeze({ area: 'DOC', summary: "A claimed tag cannot write a handoff", status: 'active', internal: false }),
215
+ 'EMET-DOC-088': Object.freeze({ area: 'DOC', summary: "A declared session tag is not the credential", status: 'active', internal: false }),
210
216
  'EMET-GEM-001': Object.freeze({ area: 'GEM', summary: "Read-back found no document", status: 'active', internal: false }),
211
217
  'EMET-GEM-002': Object.freeze({ area: 'GEM', summary: "Read-back content digest differs", status: 'active', internal: false }),
212
218
  'EMET-GEM-003': Object.freeze({ area: 'GEM', summary: "Read-back version differs", status: 'active', internal: false }),
@@ -307,6 +313,7 @@ export const ERROR_CODES = Object.freeze({
307
313
  'EMET-SESS-005': Object.freeze({ area: 'SESS', summary: "Session graph is unavailable", status: 'active', internal: false }),
308
314
  'EMET-SESS-006': Object.freeze({ area: 'SESS', summary: "Session close was blocked", status: 'active', internal: false }),
309
315
  'EMET-SESS-007': Object.freeze({ area: 'SESS', summary: "Session close escalated", status: 'active', internal: false }),
316
+ 'EMET-SESS-014': Object.freeze({ area: 'SESS', summary: "A stranded sub-key session needs a new open", status: 'active', internal: false }),
310
317
  'EMET-TOOL-001': Object.freeze({ area: 'TOOL', summary: "A tool has no annotation entry", status: 'active', internal: true }),
311
318
  'EMET-TOOL-002': Object.freeze({ area: 'TOOL', summary: "A source tag is required", status: 'active', internal: false }),
312
319
  'EMET-TOOL-003': Object.freeze({ area: 'TOOL', summary: "A source tag is required and none are registered", status: 'active', internal: false }),
package/src/gem-check.js CHANGED
@@ -96,6 +96,9 @@ const SECRET_PATTERNS = Object.freeze([
96
96
  /(api[_-]?key|secret|token|password)\s*[:=]\s*['"][^\s'"]{12,}/i
97
97
  ]);
98
98
 
99
+ /** In-repo schema id. Not a URL. The bundled schema and this check use the same string. */
100
+ export const GEM_SCHEMA_ID = 'emet:gem-library/gem.schema.json';
101
+
99
102
  const SECTION_KEY = /^[a-z][a-z0-9_]{0,40}$/;
100
103
  const FORBIDDEN_SECTIONS = new Set(['voice', 'engagement', 'persistence', 'corpus_discipline', 'operating_discipline']);
101
104
 
@@ -114,7 +117,7 @@ function loadSchema(explicit) {
114
117
  if (schemaCache) return schemaCache;
115
118
  const text = fs.readFileSync(schemaPath(), 'utf8');
116
119
  const parsed = JSON.parse(text);
117
- if (!parsed || parsed.$id !== 'https://github.com/dreamforgestudiollc/EMET-GEMs/raw/main/gem.schema.json') {
120
+ if (!parsed || parsed.$id !== GEM_SCHEMA_ID) {
118
121
  throw new CodedError('schema id', { code: 'EMET-GEM-013' });
119
122
  }
120
123
  schemaCache = parsed;
package/src/grants.js CHANGED
@@ -1,3 +1,5 @@
1
+ import crypto from 'node:crypto';
2
+
1
3
  /**
2
4
  * Door grants (R2 design scaffolding, 2026-10-26).
3
5
  *
@@ -140,8 +142,29 @@ export const MEMBER_REVOKE = Object.freeze({
140
142
  path: '/owner/break-glass/revoke-member'
141
143
  });
142
144
 
143
- /** The owl MCP clone account. Exact string. A substring is not this account. */
144
- export const OWL_ACCOUNT = 'user-EMET--owl';
145
+ /**
146
+ * Public label for logs and the retirement marker. Not compared to stored
147
+ * client ids. The retired account id is matched by digest so this package
148
+ * does not spell it. A substring is not that account.
149
+ */
150
+ export const OWL_ACCOUNT_LABEL = 'retired-owl-account';
151
+ /** sha256 of the retired account id, utf8. Exact match only. */
152
+ export const OWL_ACCOUNT_DIGEST = 'd2f8d11e0e331afd1315642e613b3f2d4c864904767c0a420761a40f81e01b0f';
153
+
154
+ export function isRetiredOwlAccount(value) {
155
+ if (typeof value !== 'string' || value.length === 0) return false;
156
+ const digest = crypto.createHash('sha256').update(value, 'utf8').digest('hex');
157
+ if (digest.length !== OWL_ACCOUNT_DIGEST.length) return false;
158
+ return crypto.timingSafeEqual(Buffer.from(digest), Buffer.from(OWL_ACCOUNT_DIGEST));
159
+ }
160
+
161
+ export function owlRetirementFailureLine(active = 'unknown') {
162
+ return `[emet] OWL RETIREMENT CHECK FAILED account=${OWL_ACCOUNT_LABEL} active=${active} rung=R6 pointer=/owner/chooser`;
163
+ }
164
+
165
+ export function owlRetirementPassLine() {
166
+ return `[emet] owl-retirement check=pass account=${OWL_ACCOUNT_LABEL} active=0 rung=R6`;
167
+ }
145
168
 
146
169
  /**
147
170
  * R6. The owl MCP clone account was a second OAuth client used only to get a
@@ -153,7 +176,7 @@ export const OWL_KILL = Object.freeze({
153
176
  rung: 'R6',
154
177
  implemented: true,
155
178
  delete_wiring: false,
156
- account: OWL_ACCOUNT,
179
+ account: OWL_ACCOUNT_LABEL,
157
180
  status: 'retired',
158
181
  superseded_by: 'R6',
159
182
  retained: true,
@@ -170,9 +193,9 @@ export const OWL_KILL = Object.freeze({
170
193
  export const WRITER_VALIDATOR = Object.freeze({
171
194
  rung: 'R6a',
172
195
  implemented: 'server',
173
- alex_choice_open: true,
196
+ owner_choice_open: true,
174
197
  options: Object.freeze(['server', 'existing-reviewer-credential']),
175
- not_an_option: OWL_ACCOUNT,
198
+ not_an_option: OWL_ACCOUNT_LABEL,
176
199
  note: 'The server-side check is what runs. the owner can later name another existing reviewer credential. The owl account is not a choice.'
177
200
  });
178
201
 
package/src/host-reach.js CHANGED
@@ -5,7 +5,7 @@
5
5
  * Licensed under the MIT License - see LICENSE
6
6
  *
7
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
8
+ * A library checkout can vendor that file and its corpus byte-for-byte. This module
9
9
  * is the import path gem-check already uses. There is no second scan.
10
10
  */
11
11
 
@@ -33,6 +33,7 @@ import { requireBearerAuth } from '@modelcontextprotocol/sdk/server/auth/middlew
33
33
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
34
34
  import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
35
35
  import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
36
+ import { owlRetirementFailureLine } from './grants.js';
36
37
  import { EMET_VERSION } from './version.js';
37
38
 
38
39
 
@@ -109,23 +110,45 @@ function buildServer() {
109
110
  registry: t.sourceRegistry()
110
111
  }, actor, args, name));
111
112
  } catch (e) {
113
+ const { preflightHttpCode } = await import('./subkey-lifecycle.js');
114
+ const code = preflightHttpCode(e);
115
+ if (code === 'EMET-SESS-014') {
116
+ const { ValidationError } = await import('./validation.js');
117
+ const err = new ValidationError('session_handle', e.message, { code: 'EMET-SESS-014' });
118
+ const response = await actorStore.run(actor, () => t.handleError(err, name, logger));
119
+ return attachSubkeyNotice(response, e.subkeyHold);
120
+ }
112
121
  if (e && e.attributionRefusal) {
113
122
  const { ValidationError } = await import('./validation.js');
114
- const code = e.emetCode === 'EMET-AUTH-044' ? 'EMET-AUTH-044' : 'EMET-AUTH-039';
115
- const err = new ValidationError('source', e.message, { code });
123
+ const mapped = code === 'EMET-AUTH-044' ? 'EMET-AUTH-044' : 'EMET-AUTH-039';
124
+ const err = new ValidationError('source', e.message, { code: mapped });
116
125
  if (e.chooser) err.chooser = e.chooser;
117
126
  return actorStore.run(actor, () => t.handleError(err, name, logger));
118
127
  }
119
128
  throw e;
120
129
  }
121
130
  const result = await actorStore.run(actor, () => callTool(name, args));
131
+ const noted = actor && actor.subkeyRenewal ? attachSubkeyNotice(result, actor.subkeyRenewal) : result;
122
132
  const { toolCallAuditDetails } = await import('./grants.js');
123
- logger.audit(AuditOperation.TOOL_CALL, toolCallAuditDetails(actor, { tool: name, success: result.isError !== true, durationMs: Date.now() - t0, params: paramNames }));
124
- return result;
133
+ logger.audit(AuditOperation.TOOL_CALL, toolCallAuditDetails(actor, { tool: name, success: noted.isError !== true, durationMs: Date.now() - t0, params: paramNames }));
134
+ return noted;
125
135
  });
126
136
  return server;
127
137
  }
128
138
 
139
+ /** Put a renewal or wrap-up notice on a tool result. The tool body is unchanged when it is not JSON. */
140
+ function attachSubkeyNotice(result, notice) {
141
+ if (!notice || !result || !Array.isArray(result.content) || !result.content[0] || typeof result.content[0].text !== 'string') return result;
142
+ try {
143
+ const data = JSON.parse(result.content[0].text);
144
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return result;
145
+ data.session_renewal = notice;
146
+ if (notice.wrap_up_notice && !data.wrap_up_notice) data.wrap_up_notice = notice.wrap_up_notice;
147
+ result.content[0].text = JSON.stringify(data);
148
+ } catch { /* a non-JSON tool body stays as the tool wrote it */ }
149
+ return result;
150
+ }
151
+
129
152
  async function callTool(name, args) {
130
153
  // One dispatch table for both transports - src/dispatch.js (audit 2026-09-27).
131
154
  return dispatchTool(name, args, { dbManager, logger, AuditOperation });
@@ -349,7 +372,7 @@ if (process.env.EMET_HTTP_LISTEN !== '0') (async () => {
349
372
  await runStartupChecks(dbManager.db, { prefix: provider.prefix, log: (line) => console.error(line) });
350
373
  }
351
374
  } catch {
352
- console.error('[emet] OWL RETIREMENT CHECK FAILED account=user-EMET--owl active=unknown rung=R6 pointer=/owner/chooser');
375
+ console.error(owlRetirementFailureLine());
353
376
  }
354
377
  try {
355
378
  const { proofStartupLine } = await import('./proof-run.js');
@@ -373,5 +396,6 @@ if (process.env.EMET_HTTP_LISTEN !== '0') (async () => {
373
396
  console.error(app.locals.rotateStartupLine());
374
397
  });
375
398
  import('./subkeys.js').then((m) => m.startFlagOffSweep((msg) => console.error(`[emet] ${msg}`))).catch(() => console.error('[emet] sub-key flag-off sweep failed'));
399
+ import('./subkeys.js').then((m) => m.startStrandedSweep((msg) => console.error(`[emet] ${msg}`), dbManager)).catch(() => console.error('[emet] sub-key sweep failed'));
376
400
  import('./error-log.js').then((m) => m.startErrorLogRotation()).catch(() => {});
377
401
  })();
package/src/index.js CHANGED
@@ -25,7 +25,7 @@
25
25
 
26
26
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
27
27
  import { setting } from './env.js';
28
- import { toolCallAuditDetails } from './grants.js';
28
+ import { owlRetirementFailureLine, toolCallAuditDetails } from './grants.js';
29
29
  import { redactText } from './redact.js';
30
30
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
31
31
  import {
@@ -267,7 +267,7 @@ async function main() {
267
267
  const { runStartupChecks } = await import('./owl.js');
268
268
  await runStartupChecks(dbManager.db, { log: (line) => logger.error(line) });
269
269
  } catch {
270
- logger.error('[emet] OWL RETIREMENT CHECK FAILED account=user-EMET--owl active=unknown rung=R6 pointer=/owner/chooser');
270
+ logger.error(owlRetirementFailureLine());
271
271
  }
272
272
  }
273
273
  try {
@@ -278,6 +278,7 @@ async function main() {
278
278
  }
279
279
 
280
280
  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 }));
281
+ import('./subkeys.js').then((m) => m.startStrandedSweep((msg) => logger.error(msg), dbManager)).catch((e) => logger.error('sub-key sweep failed', { error: e && e.message }));
281
282
  import('./error-log.js').then((m) => m.startErrorLogRotation()).catch(() => {});
282
283
 
283
284
  const startupDurationMs = Date.now() - startTime;
package/src/invites.js CHANGED
@@ -87,8 +87,8 @@ export async function createMemberAccess(db, { created_by, display_name, days =
87
87
  * A redeemed invite always gets a NEW person (multi-user report v2, defect 2,
88
88
  * 2026-10-01). Until then the guest's id was the slug of the display name the
89
89
  * invite carried, and an existing person with that slug was silently reused:
90
- * an invite named "Alex" (or "ALEX", "Aléx") redeemed as the owner, wrote as
91
- * the owner and passed the owner-only invite check. A display name is a label,
90
+ * an invite named "Member" (or "MEMBER", "Mémber") redeemed as the owner, wrote as
91
+ * the owner, and passed checks that only the owner should pass. A display name is a label,
92
92
  * not a credential, so it never selects an existing identity:
93
93
  * - the slug is a starting point; if any person already holds it, or it is a
94
94
  * reserved subject ('owner', the legacy owner subject and slugPersonId's
package/src/owl.js CHANGED
@@ -16,7 +16,7 @@
16
16
 
17
17
  import { COLLECTION_PREFIX } from './database.js';
18
18
  import { assignCode, newCorrelationId } from './error-codes.js';
19
- import { OWL_ACCOUNT, doorFromIssuedVia, grantIdFromFamily, logClientId, logDoor, logGrantId } from './grants.js';
19
+ import { OWL_ACCOUNT_LABEL, doorFromIssuedVia, grantIdFromFamily, isRetiredOwlAccount, logClientId, logDoor, logGrantId, owlRetirementFailureLine, owlRetirementPassLine } from './grants.js';
20
20
  import { InvalidGrantError, InvalidTokenError } from '@modelcontextprotocol/sdk/server/auth/errors.js';
21
21
 
22
22
  const POINTER = 'this owl MCP clone account was retired by R6. A new writer is prepared by the hub login, validated on the server, and decided by the owner at /owner/chooser. This account cannot approve. Records are retained.';
@@ -39,7 +39,7 @@ export function _resetOwlForTests() {
39
39
  export function owlRetirementMetric() {
40
40
  return {
41
41
  rung: 'R6',
42
- account: OWL_ACCOUNT,
42
+ account: OWL_ACCOUNT_LABEL,
43
43
  status: 'retired',
44
44
  retained: true,
45
45
  deleted: false,
@@ -56,13 +56,13 @@ export function owlRetirementMetric() {
56
56
  /** Exact account identity. A substring is not a match. */
57
57
  export function isOwlIdentity(value) {
58
58
  if (value == null) return false;
59
- if (typeof value === 'string') return value === OWL_ACCOUNT;
59
+ if (typeof value === 'string') return isRetiredOwlAccount(value);
60
60
  if (typeof value !== 'object') return false;
61
61
  const fields = [
62
62
  value.clientId, value.client_id, value.sourceTag, value.source_tag,
63
63
  value.effectiveTag, value.client_name, value.clientName, value.tag
64
64
  ];
65
- return fields.some((field) => field === OWL_ACCOUNT);
65
+ return fields.some((field) => isRetiredOwlAccount(field));
66
66
  }
67
67
 
68
68
  function notRetired(doc) {
@@ -91,11 +91,12 @@ async function readAll(db, name) {
91
91
  }
92
92
 
93
93
  /**
94
- * The account id, plus any registered client whose name or id is that
95
- * account. A token may carry an opaque registration id.
94
+ * Client ids of registered OAuth clients that are the retired account.
95
+ * A token may carry only an opaque registration id. The account string
96
+ * itself is matched by isOwlIdentity and is not stored in this set.
96
97
  */
97
98
  export async function owlClientIds(db, prefix = COLLECTION_PREFIX) {
98
- const ids = new Set([OWL_ACCOUNT]);
99
+ const ids = new Set();
99
100
  const clients = await readAll(db, `${prefix}oauth_clients`);
100
101
  for (const client of clients) {
101
102
  if (client && isOwlIdentity(client) && typeof client.client_id === 'string' && client.client_id) {
@@ -140,7 +141,7 @@ export async function ensureOwlRetirementMarker(db, prefix = COLLECTION_PREFIX,
140
141
  if (existing) return existing;
141
142
  const row = {
142
143
  _id: MARKER_ID,
143
- account: OWL_ACCOUNT,
144
+ account: OWL_ACCOUNT_LABEL,
144
145
  status: 'retired',
145
146
  superseded_by: 'R6',
146
147
  rung: 'R6',
@@ -167,8 +168,8 @@ export async function owlStartupCheck(db, prefix = COLLECTION_PREFIX, now = new
167
168
  }
168
169
  const ok = !failed && active.length === 0;
169
170
  const line = ok
170
- ? `[emet] owl-retirement check=pass account=${OWL_ACCOUNT} active=0 rung=R6`
171
- : `[emet] OWL RETIREMENT CHECK FAILED account=${OWL_ACCOUNT} active=${failed ? 'unknown' : active.length} rung=R6 pointer=/owner/chooser`;
171
+ ? owlRetirementPassLine()
172
+ : owlRetirementFailureLine(failed ? 'unknown' : active.length);
172
173
  metric.ok = ok;
173
174
  metric.active = failed ? null : active.length;
174
175
  metric.last_line = line;
@@ -194,7 +195,7 @@ export async function runStartupChecks(db, { prefix = COLLECTION_PREFIX, log } =
194
195
  const owl = await owlStartupCheck(db, prefix);
195
196
  line = owl.line;
196
197
  } catch {
197
- line = `[emet] OWL RETIREMENT CHECK FAILED account=${OWL_ACCOUNT} active=unknown rung=R6 pointer=/owner/chooser`;
198
+ line = owlRetirementFailureLine();
198
199
  }
199
200
  write(line);
200
201
  return { line, exited: false };
package/src/pages.js CHANGED
@@ -14,6 +14,7 @@
14
14
  */
15
15
 
16
16
  import { connectMongo } from './mongo-connect.js';
17
+ import { tagHandoffMode, loadHandoffView } from './per-tag-handoff.js';
17
18
  import { MONGODB_URI, MONGODB_DB, COLLECTION_PREFIX, DatabaseError } from './database.js';
18
19
  import { LAYERS } from './layers.js';
19
20
  import { classifyRow } from './gaps.js';
@@ -759,6 +760,20 @@ export async function lintPages({ area = null } = {}, now = new Date()) {
759
760
  }
760
761
  }
761
762
 
763
+ if (tagHandoffMode() !== 'off') {
764
+ try {
765
+ const view = await loadHandoffView(db, { asOf: now.toISOString(), readOnly: true });
766
+ if (view.handoff_view_conflicts && view.handoff_view_conflicts.length) {
767
+ pushFinding(findings, seen, {
768
+ class: 'handoff_conflict',
769
+ ids: view.handoff_view_conflicts.map((id) => `row:${id}`),
770
+ area: area || 'board',
771
+ detail: 'Two handoffs disagree on a board row. The view does not pick a winner.'
772
+ });
773
+ }
774
+ } catch { /* a view that cannot be read does not hide the other findings */ }
775
+ }
776
+
762
777
  return { findings, areas: slugs, read_only: true };
763
778
  });
764
779
  }
@@ -0,0 +1,264 @@
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
+ * Per-tag handoff statechart. Served on /statechart.
8
+ * The picture is docs/per-tag-handoff-statechart.md.
9
+ * The reference model is verification/per-tag-handoff/PerTagHandoff.tla
10
+ * (958,557 states). The pictures are the split models under
11
+ * verification/per-tag-handoff/split/.
12
+ */
13
+
14
+ export const PER_TAG_HANDOFF_MERMAID = `stateDiagram-v2
15
+ state "Legend" as legend {
16
+ lg0: refused
17
+ lg1: session
18
+ lg2: rest
19
+ }
20
+ class lg0 pink
21
+ class lg1 blue
22
+ class lg2 teal
23
+ s0: No handoffs yet
24
+ s1: In session, merged view read
25
+ s2: Write refused, nothing written
26
+ s3: Handoffs at rest
27
+ s4: In session, board moved since read
28
+ s5: In session, row conflict waiting for the hub
29
+ s6: At rest, row conflict waiting for the hub
30
+ [*] --> s0
31
+ s0 --> s1: an AI starts and reads the view
32
+ s1 --> s2: an AI tries to write another AI's handoff or an AI tries to patch a row it did not open
33
+ s1 --> s3: a write AI writes its own handoff last
34
+ s1 --> s4: a write AI opens a board row
35
+ s2 --> s1: an AI starts and reads the view or a write AI opens a board row or a write AI writes its own handoff last
36
+ s2 --> s3: a write AI writes its own handoff last
37
+ s3 --> s1: an AI starts and reads the view
38
+ s2 --> s4: a write AI opens a board row or a write AI writes its own handoff last or an AI starts and reads the view
39
+ s4 --> s2: an AI tries to patch a row it did not open or an AI tries to write another AI's handoff or a write on a moved board is refused
40
+ s4 --> s1: a write AI writes its own handoff last
41
+ s4 --> s5: a write AI writes its own handoff last
42
+ s1 --> s5: a write AI writes its own handoff last
43
+ s2 --> s5: a write AI writes its own handoff last or an AI starts and reads the view
44
+ s4 --> s3: a write AI writes its own handoff last
45
+ s4 --> s6: a write AI writes its own handoff last
46
+ s1 --> s6: a write AI writes its own handoff last
47
+ s5 --> s2: an AI tries to write another AI's handoff or an AI tries to patch a row it did not open
48
+ s5 --> s6: a write AI writes its own handoff last
49
+ s2 --> s6: a write AI writes its own handoff last
50
+ s6 --> s5: an AI starts and reads the view
51
+ class s0 teal
52
+ class s1 blue
53
+ class s2 pink
54
+ class s3 teal
55
+ class s4 blue
56
+ class s5 blue
57
+ class s6 teal
58
+ `;
59
+
60
+ export const PER_TAG_TIME_MERMAID = `stateDiagram-v2
61
+ state "Legend" as legend {
62
+ lg0: session
63
+ lg1: rest
64
+ }
65
+ class lg0 blue
66
+ class lg1 teal
67
+ s0: No handoff yet
68
+ s1: In session, merged view read
69
+ s2: In session, work shown in progress
70
+ s3: Handoff at rest
71
+ s4: In session, open work marked stale
72
+ s5: Handoff at rest, line aging
73
+ s6: In session, reading an aging line
74
+ [*] --> s0
75
+ s0 --> s1: an AI starts, reads the view, and stamps it
76
+ s1 --> s2: a write AI saves work in an open session
77
+ s1 --> s3: a write AI writes its own handoff last or a read-only AI leaves, writing nothing
78
+ s1 --> s0: a read-only AI leaves, writing nothing
79
+ s1 --> s4: a write AI saves work in an open session
80
+ s2 --> s4: time passes (24 hours open, 7 days aging)
81
+ s2 --> s3: a write AI writes its own handoff last
82
+ s3 --> s1: an AI starts, reads the view, and stamps it
83
+ s3 --> s5: time passes (24 hours open, 7 days aging)
84
+ s2 --> s1: a write AI writes its own handoff last
85
+ s4 --> s3: a write AI writes its own handoff last
86
+ s5 --> s6: an AI starts, reads the view, and stamps it
87
+ s4 --> s1: a write AI writes its own handoff last
88
+ s6 --> s2: a write AI saves work in an open session
89
+ s1 --> s6: an AI starts, reads the view, and stamps it
90
+ s6 --> s5: a read-only AI leaves, writing nothing
91
+ s1 --> s5: a read-only AI leaves, writing nothing
92
+ s6 --> s4: a write AI saves work in an open session
93
+ s6 --> s1: a read-only AI leaves, writing nothing
94
+ class s0 teal
95
+ class s1 blue
96
+ class s2 blue
97
+ class s3 teal
98
+ class s4 blue
99
+ class s5 teal
100
+ class s6 blue
101
+ `;
102
+
103
+ export const PER_TAG_HANDOFF_STEPS = Object.freeze([
104
+ 'A session reads the shared handoff view. The stamp includes the time it was read, the person, each handoff version, and the board version.',
105
+ 'Rows already on the board belong to the hub tag. Another tag patching one of those rows is refused.',
106
+ 'A new row belongs to the credential that adds it. That tag can patch it. A bot tag can patch its own rows and still cannot write the hub handoff.',
107
+ 'The hub changes another tag\'s row only when the view has marked that row in conflict, and the write names the stamp, including the time it was read. With no mark the hub is refused.',
108
+ 'Each write tag writes its own handoff last. A write of another tag\'s handoff, or of the hub handoff by anyone else, is refused.',
109
+ 'A read-only tag receives the view and writes nothing.',
110
+ 'An open session with material work is an in-progress line. It is not a pointer and it is not a lag. After 24 hours the line is marked stale-open. The gate stays warn-only.',
111
+ 'A handoff line older than 7 days, by the revision\'s updated_at, is aging. The same stamp rebuilds that class because it carries the time it was read. A stamp of versions alone does not.'
112
+ ]);
113
+
114
+ const PLACES = new Set([
115
+ 'reading', 'opened', 'ownRow', 'foreignRefused', 'conflict', 'resolved',
116
+ 'hubRefused', 'ownHandoff', 'foreignHandoff', 'readOnly',
117
+ 'inProgress', 'staleOpen', 'agingLine', 'done'
118
+ ]);
119
+
120
+ export function perTagInitial() {
121
+ return {
122
+ place: 'reading',
123
+ conflict: false,
124
+ stale: false,
125
+ aging: false,
126
+ stampAsOf: true,
127
+ handoffBy: 'none',
128
+ rowOwner: 'hub',
129
+ refused: false,
130
+ blocked: false,
131
+ person: 'owner'
132
+ };
133
+ }
134
+
135
+ function same(state, extra) {
136
+ return { ...state, ...extra, person: 'owner', blocked: false };
137
+ }
138
+
139
+ /**
140
+ * One step of the chart. An event that cannot happen returns null.
141
+ * blocked stays false. The person stays the owner.
142
+ */
143
+ export function perTagHandoffStep(state, event) {
144
+ if (!state || !PLACES.has(state.place)) return null;
145
+ if (!event || typeof event.type !== 'string') return null;
146
+ const type = event.type;
147
+ if (type === 'start') {
148
+ if (state.place !== 'reading') return null;
149
+ return same(state, { stampAsOf: true });
150
+ }
151
+ if (type === 'open_row') {
152
+ if (state.place !== 'reading' || state.rowOwner !== 'hub') return null;
153
+ return same(state, { place: 'opened', rowOwner: 'writer', refused: false });
154
+ }
155
+ if (type === 'patch_own') {
156
+ if (state.place !== 'opened' || state.rowOwner !== 'writer') return null;
157
+ return same(state, { place: 'ownRow', refused: false });
158
+ }
159
+ if (type === 'foreign_row') {
160
+ if (state.place !== 'reading' || state.rowOwner !== 'hub') return null;
161
+ return same(state, { place: 'foreignRefused', refused: true });
162
+ }
163
+ if (type === 'mark_conflict') {
164
+ if (state.place !== 'opened') return null;
165
+ return same(state, { place: 'conflict', conflict: true });
166
+ }
167
+ if (type === 'resolve') {
168
+ if (state.place !== 'conflict' || state.conflict !== true || state.stampAsOf !== true) return null;
169
+ return same(state, { place: 'resolved', refused: false });
170
+ }
171
+ if (type === 'resolve_unmarked') {
172
+ if (state.place !== 'opened' || state.conflict !== false || state.rowOwner !== 'writer') return null;
173
+ return same(state, { place: 'hubRefused', refused: true });
174
+ }
175
+ if (type === 'wrap_own') {
176
+ if (!['reading', 'ownRow', 'resolved', 'inProgress'].includes(state.place)) return null;
177
+ return same(state, { place: 'ownHandoff', handoffBy: 'writer', refused: false });
178
+ }
179
+ if (type === 'foreign_handoff') {
180
+ if (state.place !== 'reading') return null;
181
+ return same(state, { place: 'foreignHandoff', refused: true, handoffBy: 'none' });
182
+ }
183
+ if (type === 'leave_readonly') {
184
+ if (state.place !== 'reading') return null;
185
+ return same(state, { place: 'readOnly', refused: false });
186
+ }
187
+ if (type === 'show_progress') {
188
+ if (state.place !== 'reading') return null;
189
+ return same(state, { place: 'inProgress', stale: false });
190
+ }
191
+ if (type === 'tick_open') {
192
+ if (state.place !== 'inProgress') return null;
193
+ return same(state, { place: 'staleOpen', stale: true });
194
+ }
195
+ if (type === 'tick_age') {
196
+ if (!['reading', 'ownHandoff'].includes(state.place) || state.stampAsOf !== true) return null;
197
+ return same(state, { place: 'agingLine', aging: true });
198
+ }
199
+ if (type === 'done') {
200
+ if (!['ownRow', 'foreignRefused', 'resolved', 'hubRefused', 'ownHandoff', 'foreignHandoff', 'readOnly', 'staleOpen', 'agingLine', 'done'].includes(state.place)) return null;
201
+ return same(state, { place: 'done' });
202
+ }
203
+ return null;
204
+ }
205
+
206
+ /** The chart rules. A block, a lost opener, or a stamp with no as_of breaks one. */
207
+ export function perTagInvariant(state) {
208
+ if (!state) return false;
209
+ if (state.blocked !== false) return false;
210
+ if (state.person !== 'owner') return false;
211
+ if (state.handoffBy !== 'none' && state.handoffBy !== 'writer') return false;
212
+ if (state.place === 'resolved' && state.conflict !== true) return false;
213
+ if (state.place === 'hubRefused' && (state.conflict !== false || state.rowOwner !== 'writer')) return false;
214
+ if (state.place === 'foreignRefused' && state.rowOwner !== 'hub') return false;
215
+ if (state.place === 'readOnly' && (state.handoffBy !== 'none' || state.rowOwner !== 'hub')) return false;
216
+ if ((state.place === 'inProgress' || state.place === 'staleOpen') && state.handoffBy !== 'none') return false;
217
+ if (state.stale === true && state.place !== 'staleOpen' && state.place !== 'done') return false;
218
+ if (state.stampAsOf !== true) return false;
219
+ return true;
220
+ }
221
+
222
+ /**
223
+ * The four-step counter-check. Versions without as_of do not rebuild the view
224
+ * once the line has aged. The real stamp carries as_of, so the same inputs rebuild.
225
+ */
226
+ export function stampCounterSteps(build) {
227
+ const asOf = '2026-11-03T00:00:00.000Z';
228
+ const later = '2026-11-11T00:00:00.000Z';
229
+ const board = { doc_id: 'STATE.md', version: 1, content: boardText() };
230
+ const input = {
231
+ doc_id: 'HANDOFF/writer.md',
232
+ tag: 'writer',
233
+ version: 1,
234
+ updated_at: '2026-11-03T00:00:00.000Z',
235
+ content: handoffText('B-001', 'open', 'wait')
236
+ };
237
+ const first = build({ inputs: [input], board, as_of: asOf, person: 'owner' });
238
+ const again = build({ inputs: [input], board, as_of: asOf, person: 'owner' });
239
+ const aged = build({ inputs: [input], board, as_of: later, person: 'owner' });
240
+ const versionsOnly = { inputs: ['HANDOFF/writer.md@v1'], board: 'STATE.md@v1' };
241
+ return { first, again, aged, versionsOnly };
242
+ }
243
+
244
+ export function boardText() {
245
+ return [
246
+ '## §1 HALF-STATE',
247
+ '| Id | State | Next action |',
248
+ '| --- | --- | --- |',
249
+ '| B-001 | open | wait |',
250
+ '## §3 OPEN BOARD',
251
+ '| Id | Status | Next action |',
252
+ '| --- | --- | --- |'
253
+ ].join('\n');
254
+ }
255
+
256
+ export function handoffText(row, state, next) {
257
+ return [
258
+ '## §1 OVERALL PICTURE',
259
+ '| Row | State | Next step |',
260
+ '| --- | --- | --- |',
261
+ `| ${row} | ${state} | ${next} |`,
262
+ 'Close verification: episodic 1'
263
+ ].join('\n');
264
+ }