@dreamforgestudiollc/emet 0.3.1 → 0.3.3

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 (72) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +29 -6
  3. package/docs/BOOTSTRAP.md +2 -0
  4. package/docs/BOTS.md +8 -7
  5. package/docs/DEPLOY.md +6 -0
  6. package/docs/ERROR-CODES-SPEC.md +2 -2
  7. package/docs/ERROR-CODES.md +29 -0
  8. package/docs/GUIDED-SETUP.md +1 -1
  9. package/docs/PERMISSIONS.md +5 -5
  10. package/docs/SETUP.md +10 -4
  11. package/docs/SUBKEYS.md +4 -4
  12. package/package.json +2 -2
  13. package/server.json +8 -4
  14. package/src/aleph.js +34 -13
  15. package/src/annotations.js +6 -2
  16. package/src/approve-throttle.js +3 -0
  17. package/src/atlas-role.js +1 -1
  18. package/src/attribution.js +76 -28
  19. package/src/bound-door.js +170 -0
  20. package/src/break-glass.js +531 -0
  21. package/src/carry-forward-close.js +386 -0
  22. package/src/checkpoint.js +241 -0
  23. package/src/chooser.js +543 -0
  24. package/src/claimed-tag.js +140 -0
  25. package/src/conformance.js +269 -5
  26. package/src/deep-links.js +267 -0
  27. package/src/dispatch.js +112 -18
  28. package/src/error-codes.js +29 -0
  29. package/src/error-log.js +138 -26
  30. package/src/error-report.js +17 -5
  31. package/src/gaps.js +1 -1
  32. package/src/grants.js +230 -0
  33. package/src/http-remote.js +80 -26
  34. package/src/index.js +18 -2
  35. package/src/invites.js +47 -1
  36. package/src/layers.js +1 -1
  37. package/src/lessons-to-checks.js +1 -1
  38. package/src/logger.js +3 -1
  39. package/src/oauth-provider.js +89 -5
  40. package/src/owl.js +232 -0
  41. package/src/owner-approvals.js +24 -267
  42. package/src/owner-session.js +235 -0
  43. package/src/pages.js +1 -1
  44. package/src/persons.js +39 -6
  45. package/src/proof-run.js +70 -0
  46. package/src/redact.js +4 -0
  47. package/src/request-log.js +2 -2
  48. package/src/rotate.js +554 -0
  49. package/src/rune-dispatch.js +1 -1
  50. package/src/session-graph.js +44 -25
  51. package/src/session.js +52 -9
  52. package/src/setup.js +21 -12
  53. package/src/staged-write.js +522 -0
  54. package/src/startup-pages.js +2 -2
  55. package/src/startup-payload.js +3 -3
  56. package/src/subkeys.js +61 -0
  57. package/src/tools.js +290 -79
  58. package/src/transcript-session.js +23 -4
  59. package/src/validation.js +1 -1
  60. package/src/version.js +1 -1
  61. package/src/writer-approval.js +394 -0
  62. package/templates/AREA.md +1 -1
  63. package/templates/BOTHANDOFF.md +2 -2
  64. package/templates/GRANT.md +48 -0
  65. package/templates/INDEX.md +9 -7
  66. package/templates/PROCEDURE.md +1 -1
  67. package/templates/ROSTER.md +2 -2
  68. package/templates/SEED.md +2 -2
  69. package/templates/SESSIONDISPOSITION.md +59 -0
  70. package/templates/STAGING.md +1 -1
  71. package/templates/STANDARD.md +1 -1
  72. package/templates/THREAD.md +1 -1
@@ -10,10 +10,11 @@ import { currentActor, getPerson } from './persons.js';
10
10
  import { EMET_VERSION } from './version.js';
11
11
  import { ERROR_CODES, EMET_CODE_RE } from './error-codes.js';
12
12
  import { redactText } from './redact.js';
13
- import { queryErrorLog } from './error-log.js';
13
+ import { logClientId, logDoor, logGrantId } from './grants.js';
14
+ import { queryErrorLog, logSessionId } from './error-log.js';
14
15
 
15
16
  export const SEND_INSTRUCTION = 'The calling assistant may send this report only after showing the report to its user and getting their OK.';
16
- export const DEFAULT_REPORT_EMAIL = 'dreamforgestudio@mail.grokbot.com';
17
+ export const DEFAULT_REPORT_EMAIL = 'dreamforgestudio@mail.hubbot.com';
17
18
  export const MAILTO_MAX = 1800;
18
19
 
19
20
  /**
@@ -101,10 +102,21 @@ function shown(entry) {
101
102
  transport: entry.transport === 'http' ? 'http' : 'stdio',
102
103
  caller: redactText(String(entry.caller || 'unregistered')),
103
104
  role: entry.role === 'owner' ? 'owner' : 'guest',
105
+ client_id: logClientId(entry.client_id),
106
+ grant_id: logGrantId(entry.grant_id),
107
+ door: logDoor(entry.door),
108
+ session_id: shownSessionId(entry.session_id),
104
109
  correlation_id: redactText(String(entry.correlation_id || ''))
105
110
  };
106
111
  }
107
112
 
113
+ /** A stored session id, or none when the row is not a session close. */
114
+ function shownSessionId(id) {
115
+ if (id == null || id === '' || id === 'none') return 'none';
116
+ if (id === 'unknown') return 'unknown';
117
+ return logSessionId(id);
118
+ }
119
+
108
120
  function totalsOf(rows) {
109
121
  const map = new Map();
110
122
  for (const row of rows) {
@@ -141,11 +153,11 @@ function assemble({ version, shortId, generated, windowStart, windowEnd, nodeVer
141
153
  lines.push('Most recent');
142
154
  if (!recent.length) lines.push(' (none)');
143
155
  for (const entry of recent) {
144
- lines.push(` ${entry.t} ${entry.emet_code} ${entry.tool} ${entry.transport} ${entry.caller} ${entry.role} ${entry.correlation_id}`);
156
+ lines.push(` ${entry.t} ${entry.emet_code} ${entry.tool} ${entry.transport} ${entry.caller} ${entry.role} ${entry.client_id} ${entry.grant_id} ${entry.door} ${entry.session_id} ${entry.correlation_id}`);
145
157
  }
146
158
  lines.push('');
147
- lines.push('Contains: codes, times, tool names, versions, caller tags, ids.');
148
- lines.push('Does not contain: memory, documents, arguments, names, tokens.');
159
+ lines.push('Contains: codes, times, tool names, versions, caller tags, client ids, grant ids, doors, session ids.');
160
+ lines.push('Does not contain: memory, documents, arguments, message text, or tokens.');
149
161
  lines.push('You are sending this yourself. EMET has not sent it anywhere.');
150
162
  return lines.join('\n');
151
163
  }
package/src/gaps.js CHANGED
@@ -265,7 +265,7 @@ export async function findGaps({ layer = null, since = null, limit = 50 } = {})
265
265
  const push = (name, ref) => { const c = classes[name]; c.count++; if (c.ids.length < cap) c.ids.push(ref); };
266
266
 
267
267
  // Declared outside the try: the return below reads it (live-caught 2026-09-29,
268
- // "chain is not defined", deploy commit-9968716c).
268
+ // "chain is not defined", deploy thatcommit).
269
269
  const chain = {};
270
270
  let graphLab = null;
271
271
  const { client, db } = await connect();
package/src/grants.js ADDED
@@ -0,0 +1,230 @@
1
+ /**
2
+ * Door grants (R2 design scaffolding, 2026-10-26).
3
+ *
4
+ * A grant is one OAuth consent: the token `family` already minted in
5
+ * oauth-provider.js. This module names that id and the three doors. It does
6
+ * not issue or revoke tokens, and it does not decide who may write.
7
+ *
8
+ * Rotate-all (R5) is implemented beside break-glass. The owl MCP clone
9
+ * account (R6) is retired and retained. Its wiring stays so a later rung
10
+ * cannot delete that record in silence. Claude/ChatGPT write-versus-guest
11
+ * is open; this file does not pick it.
12
+ */
13
+
14
+ export const DOORS = Object.freeze(['owner', 'member', 'guest']);
15
+
16
+ /** Stored `issued_via` values. Guest keeps the historical marker `invite`. */
17
+ export const ISSUED_VIA = Object.freeze({
18
+ owner: 'owner',
19
+ member: 'member',
20
+ guest: 'invite'
21
+ });
22
+
23
+ /**
24
+ * Door of a stored token. Null means the row has no door marker (legacy).
25
+ * Do not guess owner from a missing field: older passphrase tokens omitted it.
26
+ */
27
+ export function doorFromIssuedVia(issuedVia) {
28
+ if (issuedVia === ISSUED_VIA.member) return 'member';
29
+ if (issuedVia === ISSUED_VIA.guest) return 'guest';
30
+ if (issuedVia === ISSUED_VIA.owner) return 'owner';
31
+ return null;
32
+ }
33
+
34
+ /** The grant id is the token family. Blank is not a grant. Never minted here. */
35
+ export function grantIdFromFamily(family) {
36
+ if (typeof family !== 'string') return null;
37
+ const id = family.trim();
38
+ return id || null;
39
+ }
40
+
41
+ /** Door copied onto an HTTP actor. Stdio is not an HTTP door. */
42
+ export function httpDoor(door) {
43
+ if (door === 'owner' || door === 'member' || door === 'guest') return door;
44
+ return null;
45
+ }
46
+
47
+ /** A family is randTok(16): 22 base64url characters. A bearer is longer, so it cannot be stored as a grant id. */
48
+ const GRANT_RE = /^[A-Za-z0-9_-]{1,22}$/;
49
+ const CLIENT_RE = /^[A-Za-z0-9._~:/?#@!$&'()*+,;=%-]{1,200}$/;
50
+
51
+ /** Log-safe grant id. Anything else, including a bearer, becomes `none`. */
52
+ export function logGrantId(id) {
53
+ return typeof id === 'string' && GRANT_RE.test(id) ? id : 'none';
54
+ }
55
+
56
+ /** Log-safe client id. Stdio is kept. Anything else unrecognised is `unknown`. */
57
+ export function logClientId(id) {
58
+ if (id === 'stdio') return 'stdio';
59
+ if (typeof id === 'string' && CLIENT_RE.test(id) && !/\s/.test(id)) return id;
60
+ return 'unknown';
61
+ }
62
+
63
+ /** Log-safe door. Null and anything off the list are `unknown`. */
64
+ export function logDoor(door) {
65
+ if (door === 'owner' || door === 'member' || door === 'guest' || door === 'stdio') return door;
66
+ return 'unknown';
67
+ }
68
+
69
+ /**
70
+ * Read-only view of one token row for a diagnostic. No token, digest, or
71
+ * secret. R2 does not list a household; a caller sees their own grant on
72
+ * emet_initialize. A household listing is a later owner-only tool.
73
+ */
74
+ export function grantView(tokenRow) {
75
+ if (!tokenRow || typeof tokenRow !== 'object') return null;
76
+ return {
77
+ grant_id: grantIdFromFamily(tokenRow.family),
78
+ client_id: typeof tokenRow.client_id === 'string' ? tokenRow.client_id : null,
79
+ door: doorFromIssuedVia(tokenRow.issued_via),
80
+ source_tag: typeof tokenRow.source_tag === 'string' ? tokenRow.source_tag : null
81
+ };
82
+ }
83
+
84
+ /**
85
+ * Identity fields for an audit line. Sanitized. Not a token.
86
+ * @param {{ clientId?: string, grantId?: string, door?: string }} actor
87
+ */
88
+ export function auditIdentity(actor) {
89
+ const a = actor && typeof actor === 'object' ? actor : {};
90
+ return {
91
+ client_id: logClientId(a.clientId),
92
+ grant_id: logGrantId(a.grantId),
93
+ door: logDoor(a.transport === 'http' ? a.door : (a.transport === 'stdio' ? 'stdio' : a.door))
94
+ };
95
+ }
96
+
97
+ /**
98
+ * TOOL_CALL audit details. Identity is sanitized here so both transports
99
+ * record the same fields. Parameter names only; never argument values.
100
+ */
101
+ export function toolCallAuditDetails(actor, fields) {
102
+ const f = fields && typeof fields === 'object' ? fields : {};
103
+ return {
104
+ tool: f.tool,
105
+ success: f.success,
106
+ durationMs: f.durationMs,
107
+ params: f.params,
108
+ ...auditIdentity(actor)
109
+ };
110
+ }
111
+
112
+ /**
113
+ * R5 rotate-all. Owner session only, with an explicit confirm.
114
+ * grace_window_seconds is null on purpose: the owner locked revoke-all plus fresh
115
+ * invites, with no grace window (2026-10-25). The 60-second refresh-rotation
116
+ * grace in oauth-provider.js is a different control (one client lost one
117
+ * refresh response). It is not a household grace and must not be reused as one.
118
+ */
119
+ export const ROTATE_ALL = Object.freeze({
120
+ rung: 'R5',
121
+ implemented: true,
122
+ grace_window_seconds: null,
123
+ effect: 'revoke every grant and sub-key, then issue fresh invites',
124
+ trigger: 'owner session',
125
+ confirm: 'rotate-all',
126
+ path: '/owner/break-glass/rotate-all'
127
+ });
128
+
129
+ /**
130
+ * R5b. Revoke one member or one bot. Does not bump the household generation,
131
+ * so every other credential keeps working. Same confirm rule, no grace.
132
+ */
133
+ export const MEMBER_REVOKE = Object.freeze({
134
+ rung: 'R5b',
135
+ implemented: true,
136
+ grace_window_seconds: null,
137
+ effect: 'revoke one member or bot; leave every other credential working',
138
+ trigger: 'owner session',
139
+ confirm: 'revoke-member',
140
+ path: '/owner/break-glass/revoke-member'
141
+ });
142
+
143
+ /** The owl MCP clone account. Exact string. A substring is not this account. */
144
+ export const OWL_ACCOUNT = 'user-EMET--owl';
145
+
146
+ /**
147
+ * R6. The owl MCP clone account was a second OAuth client used only to get a
148
+ * different client_id. R6 retires it. the owner decides a new writer on the
149
+ * chooser. Master Hub prepares. The server validates. Rows stay.
150
+ * delete_wiring stays false: the name and the historical grants are retained.
151
+ */
152
+ export const OWL_KILL = Object.freeze({
153
+ rung: 'R6',
154
+ implemented: true,
155
+ delete_wiring: false,
156
+ account: OWL_ACCOUNT,
157
+ status: 'retired',
158
+ superseded_by: 'R6',
159
+ retained: true,
160
+ deleted: false,
161
+ validator: 'server',
162
+ decision_path: '/owner/chooser',
163
+ path: 'refuse the owl MCP clone account; retain its grants and logs; the owner decides a new writer on /owner/chooser'
164
+ });
165
+
166
+ /**
167
+ * R6a validator. The server-side check is what runs. the owner can later name
168
+ * another existing reviewer credential. The owl account is not a choice.
169
+ */
170
+ export const WRITER_VALIDATOR = Object.freeze({
171
+ rung: 'R6a',
172
+ implemented: 'server',
173
+ alex_choice_open: true,
174
+ options: Object.freeze(['server', 'existing-reviewer-credential']),
175
+ not_an_option: OWL_ACCOUNT,
176
+ 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
+ });
178
+
179
+ /** Claude and ChatGPT: write-capable member or read-only guest. Not decided. */
180
+ export const CLAUDE_CHATGPT_DOOR = Object.freeze({
181
+ decided: false,
182
+ door: null
183
+ });
184
+
185
+ /**
186
+ * The passphrase session is an owner factor, not a writer grant. It has no
187
+ * grant id. R4 folds the decision page onto /owner/chooser. /owner/approvals
188
+ * is retired and retained: it answers with a pointer and does not delete records.
189
+ */
190
+ export const OWNER_PAGE = Object.freeze({
191
+ is_grant: false,
192
+ door: 'owner',
193
+ grant_id: null,
194
+ decision_path: '/owner/chooser',
195
+ retired_path: '/owner/approvals'
196
+ });
197
+
198
+ /**
199
+ * R4 deep link. Proposed lifetime is 15 minutes, for the owner to set.
200
+ * EMET_DEEP_LINK_TTL_MINUTES may narrow that to 1–60. It does not grant a door.
201
+ */
202
+ export const DEEP_LINK = Object.freeze({
203
+ rung: 'R4',
204
+ ttl_ms: 15 * 60 * 1000,
205
+ ttl_proposal: '15 minutes, for the owner to set',
206
+ single_use: true,
207
+ instance_scoped: true,
208
+ grants_access: false
209
+ });
210
+
211
+ /** R4 break-glass. Owner passphrase only. Not a member or guest grant. */
212
+ export const BREAK_GLASS = Object.freeze({
213
+ rung: 'R4',
214
+ path: '/owner/break-glass',
215
+ owner_session_only: true,
216
+ reachable_by_member_or_guest_grant: false
217
+ });
218
+
219
+ /**
220
+ * The old owner-approvals path. Superseded, retired, retained.
221
+ * Pending rows are listed on the chooser. They are not copied and not deleted.
222
+ */
223
+ export const OWNER_APPROVALS_RETIRED = Object.freeze({
224
+ rung: 'R4',
225
+ status: 'retired',
226
+ path: '/owner/approvals',
227
+ superseded_by: '/owner/chooser',
228
+ retained: true,
229
+ deleted: false
230
+ });
@@ -88,18 +88,8 @@ function buildServer() {
88
88
  });
89
89
  server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
90
90
  const { name, arguments: args = {} } = request.params;
91
- const { actorStore, personFromAuth } = await import('./persons.js');
92
- const auth = extra && extra.authInfo;
93
- const clientId = (auth && auth.clientId) || 'http:visitor';
94
- const actor = {
95
- personId: personFromAuth(extra),
96
- clientId,
97
- scopes: (auth && auth.scopes) || [],
98
- transport: 'http',
99
- sourceTag: (auth && auth.extra && auth.extra.sourceTag) || null,
100
- grantId: (auth && auth.extra && auth.extra.grantId) || null,
101
- authenticated: Boolean(auth)
102
- };
91
+ const { actorStore, httpToolActor } = await import('./persons.js');
92
+ const actor = httpToolActor(extra);
103
93
  const bucket = t.rateBucket(actor);
104
94
  const rl = rateLimiter.checkLimit(name, bucket);
105
95
  if (!rl.allowed) return actorStore.run(actor, () => t.handleError(new t.RateLimitError(rl.reason, rl.retryAfterMs), name, logger));
@@ -107,7 +97,7 @@ function buildServer() {
107
97
  // Every tool call leaves one audit entry (H6). callTool never throws: it
108
98
  // returns either a success response or handleError's isError response.
109
99
  const t0 = Date.now();
110
- // Parameter NAMES, never values (Alex, 2026-09-27, code audit 1.6).
100
+ // Parameter NAMES, never values (the owner, 2026-09-27, code audit 1.6).
111
101
  const paramNames = Object.keys(args || {}).sort();
112
102
  try {
113
103
  const att = await import('./attribution.js');
@@ -121,12 +111,16 @@ function buildServer() {
121
111
  } catch (e) {
122
112
  if (e && e.attributionRefusal) {
123
113
  const { ValidationError } = await import('./validation.js');
124
- return actorStore.run(actor, () => t.handleError(new ValidationError('source', e.message, { code: 'EMET-AUTH-039' }), name, logger));
114
+ const code = e.emetCode === 'EMET-AUTH-044' ? 'EMET-AUTH-044' : 'EMET-AUTH-039';
115
+ const err = new ValidationError('source', e.message, { code });
116
+ if (e.chooser) err.chooser = e.chooser;
117
+ return actorStore.run(actor, () => t.handleError(err, name, logger));
125
118
  }
126
119
  throw e;
127
120
  }
128
121
  const result = await actorStore.run(actor, () => callTool(name, args));
129
- logger.audit(AuditOperation.TOOL_CALL, { tool: name, success: result.isError !== true, durationMs: Date.now() - t0, params: paramNames });
122
+ 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 }));
130
124
  return result;
131
125
  });
132
126
  return server;
@@ -155,18 +149,36 @@ app.use(requestLogger({ enabled: process.env.EMET_REQUEST_LOG !== '0' }));
155
149
 
156
150
  app.get('/health', (_req, res) => res.json({ ok: true, service: 'emet', tools: t.TOOLS.length, cimd: provider.cimdEnabled }));
157
151
 
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') {
152
+ // Chooser, break-glass, and the retired owner-approvals pointer. The passphrase
153
+ // and the per-address lockout are the same ones /oauth/approve uses. A member
154
+ // or guest grant is not a session. Sub-key tools still follow EMET_SUBKEYS;
155
+ // the human pages stay mounted either way so a refusal link has somewhere to open.
156
+ {
157
+ const { setChooserPublicUrl, breakGlassStartupLine } = await import('./deep-links.js');
158
+ const { rotateStartupLine } = await import('./rotate.js');
159
+ const { createOwnerGate } = await import('./owner-session.js');
160
+ const { mountChooser } = await import('./chooser.js');
161
+ const { mountBreakGlass } = await import('./break-glass.js');
162
162
  const { mountOwnerApprovals } = await import('./owner-approvals.js');
163
163
  const { resolveTokenSubject } = await import('./persons.js');
164
- mountOwnerApprovals(app, {
164
+ setChooserPublicUrl(PUBLIC_URL);
165
+ const human = {
165
166
  checkPassphrase: (input) => provider.checkPassphrase(input),
166
167
  throttle: approveThrottle,
167
168
  deps: t.approvalsDeps,
168
- ownerId: () => resolveTokenSubject(dbManager.db)
169
- });
169
+ ownerId: () => resolveTokenSubject(dbManager.db),
170
+ db: () => dbManager.db,
171
+ prefix: provider.prefix,
172
+ provider,
173
+ rateLimiter,
174
+ logger
175
+ };
176
+ human.gate = createOwnerGate(human);
177
+ mountChooser(app, human);
178
+ mountBreakGlass(app, human);
179
+ mountOwnerApprovals(app, human);
180
+ app.locals.breakGlassStartupLine = breakGlassStartupLine;
181
+ app.locals.rotateStartupLine = rotateStartupLine;
170
182
  }
171
183
 
172
184
  // OAuth 2.1 authorization server + protected-resource metadata:
@@ -244,8 +256,19 @@ app.post('/oauth/approve', express.urlencoded({ extended: false }), async (req,
244
256
  }
245
257
  sourceTag = requested || null;
246
258
  }
259
+ const { isOwlIdentity } = await import('./owl.js');
260
+ if (isOwlIdentity(client_id) || isOwlIdentity(sourceTag)) {
261
+ res.locals.reason = 'owl_retired';
262
+ res.status(401).setHeader('Content-Type', 'text/html; charset=utf-8');
263
+ return res.end('<p style="font-family:system-ui;background:#12141a;color:#e8e6e0;padding:24px">This owl MCP clone account was retired by R6. the owner decides a new writer on /owner/chooser. Nothing was granted.</p>');
264
+ }
247
265
  const client = await provider.clientsStore.getClient(client_id);
248
266
  if (!client) { res.locals.reason = 'unknown_client'; return res.status(400).end('unknown client'); }
267
+ if (isOwlIdentity(client)) {
268
+ res.locals.reason = 'owl_retired';
269
+ res.status(401).setHeader('Content-Type', 'text/html; charset=utf-8');
270
+ return res.end('<p style="font-family:system-ui;background:#12141a;color:#e8e6e0;padding:24px">This owl MCP clone account was retired by R6. the owner decides a new writer on /owner/chooser. Nothing was granted.</p>');
271
+ }
249
272
  // Same rule the SDK's /authorize applies: exact match, except that loopback
250
273
  // redirects (localhost / 127.0.0.1 / [::1]) match with the port ignored, per
251
274
  // RFC 8252 §7.3 — Claude Code binds an ephemeral port on every run.
@@ -264,10 +287,19 @@ app.post('/oauth/approve', express.urlencoded({ extended: false }), async (req,
264
287
  scopes: grantedScopes,
265
288
  resource: resource || null,
266
289
  subject: inviteSubject || null,
267
- // The door rides on the token: 'member' for EMET Member Access, 'invite' for EMET Guest Access.
268
- issued_via: inviteSubject ? (inviteDoor === 'member' ? 'member' : 'invite') : null,
290
+ // The door rides on the token: 'member', 'invite' (guest), or 'owner' (passphrase).
291
+ issued_via: inviteSubject ? (inviteDoor === 'member' ? 'member' : 'invite') : 'owner',
269
292
  source_tag: sourceTag,
270
293
  });
294
+ if (sourceTag === 'grok-project') {
295
+ try {
296
+ const { recordSophiaCredential } = await import('./bound-door.js');
297
+ const door = inviteSubject ? (inviteDoor === 'member' ? 'member' : 'guest') : 'owner';
298
+ await recordSophiaCredential(t.approvalsDeps, { client_id, door, grant_id: null, by: 'consent' });
299
+ } catch {
300
+ console.error('[emet] bound door listing was not written');
301
+ }
302
+ }
271
303
  const u = new URL(redirect_uri);
272
304
  u.searchParams.set('code', code);
273
305
  if (state) u.searchParams.set('state', state);
@@ -294,10 +326,28 @@ app.post('/mcp', requireBearerAuth({ verifier: provider, resourceMetadataUrl: PR
294
326
  }
295
327
  });
296
328
 
297
- (async () => {
329
+ export { app, dbManager };
330
+
331
+ // EMET_HTTP_LISTEN=0 lets a test import this module and POST /oauth/approve
332
+ // without binding the production port. Production does not set it.
333
+ if (process.env.EMET_HTTP_LISTEN !== '0') (async () => {
298
334
  if (!PASSPHRASE) console.error('[emet] WARNING: EMET_OAUTH_PASSPHRASE unset — all authorization attempts will be rejected.');
299
335
  try { await dbManager.ensureClient(); console.error('[emet] Mongo connected'); }
300
336
  catch (e) { console.error('[emet] Mongo connect FAILED:', e.message); }
337
+ try {
338
+ if (dbManager.db) {
339
+ const { runStartupChecks } = await import('./owl.js');
340
+ await runStartupChecks(dbManager.db, { prefix: provider.prefix, log: (line) => console.error(line) });
341
+ }
342
+ } catch {
343
+ console.error('[emet] OWL RETIREMENT CHECK FAILED account=user-EMET--owl active=unknown rung=R6 pointer=/owner/chooser');
344
+ }
345
+ try {
346
+ const { proofStartupLine } = await import('./proof-run.js');
347
+ console.error(proofStartupLine());
348
+ } catch {
349
+ console.error('[emet] proof-run status=not_run rung=R7');
350
+ }
301
351
  try {
302
352
  const { seatGems } = await import('./socket.js');
303
353
  const seated = await seatGems({ log: logger });
@@ -308,7 +358,11 @@ app.post('/mcp', requireBearerAuth({ verifier: provider, resourceMetadataUrl: PR
308
358
  }
309
359
  }
310
360
  catch (e) { console.error('[emet] GEM socket failed closed'); }
311
- app.listen(PORT, HOST, () => console.error(`[emet] listening ${PUBLIC_URL} (bind ${HOST}:${PORT}); /mcp OAuth-protected; PRM ${PRM_URL}`));
361
+ app.listen(PORT, HOST, () => {
362
+ console.error(`[emet] listening ${PUBLIC_URL} (bind ${HOST}:${PORT}); /mcp OAuth-protected; PRM ${PRM_URL}`);
363
+ console.error(app.locals.breakGlassStartupLine());
364
+ console.error(app.locals.rotateStartupLine());
365
+ });
312
366
  import('./subkeys.js').then((m) => m.startFlagOffSweep((msg) => console.error(`[emet] ${msg}`))).catch(() => console.error('[emet] sub-key flag-off sweep failed'));
313
367
  import('./error-log.js').then((m) => m.startErrorLogRotation()).catch(() => {});
314
368
  })();
package/src/index.js CHANGED
@@ -25,6 +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
29
  import { redactText } from './redact.js';
29
30
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
30
31
  import {
@@ -171,11 +172,11 @@ server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
171
172
  // Every tool call leaves one audit entry (H6, 2026-09-19). callTool never
172
173
  // throws: it returns either a success response or handleError's response.
173
174
  const t0 = Date.now();
174
- // Parameter NAMES, never values (Alex, 2026-09-27, code audit 1.6): the next
175
+ // Parameter NAMES, never values (the owner, 2026-09-27, code audit 1.6): the next
175
176
  // audit can measure which parameters hosts use; nothing a host sent is stored.
176
177
  const paramNames = Object.keys(args || {}).sort();
177
178
  const result = await actorStore.run(actor, () => callTool(name, args));
178
- logger.audit(AuditOperation.TOOL_CALL, { tool: name, success: result.isError !== true, durationMs: Date.now() - t0, params: paramNames });
179
+ logger.audit(AuditOperation.TOOL_CALL, toolCallAuditDetails(actor, { tool: name, success: result.isError !== true, durationMs: Date.now() - t0, params: paramNames }));
179
180
  return result;
180
181
  });
181
182
 
@@ -261,6 +262,21 @@ async function main() {
261
262
  try { await seatGems({ log: logger }); }
262
263
  catch (e) { logger.error('GEM socket failed closed', { error: e && e.message }); }
263
264
 
265
+ if (initializedLayers.length && dbManager.db) {
266
+ try {
267
+ const { runStartupChecks } = await import('./owl.js');
268
+ await runStartupChecks(dbManager.db, { log: (line) => logger.error(line) });
269
+ } catch {
270
+ logger.error('[emet] OWL RETIREMENT CHECK FAILED account=user-EMET--owl active=unknown rung=R6 pointer=/owner/chooser');
271
+ }
272
+ }
273
+ try {
274
+ const { proofStartupLine } = await import('./proof-run.js');
275
+ logger.error(proofStartupLine());
276
+ } catch {
277
+ logger.error('[emet] proof-run status=not_run rung=R7');
278
+ }
279
+
264
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 }));
265
281
  import('./error-log.js').then((m) => m.startErrorLogRotation()).catch(() => {});
266
282
 
package/src/invites.js CHANGED
@@ -2,6 +2,7 @@ import crypto from 'crypto';
2
2
  import { slugPersonId } from './persons.js';
3
3
  import { setting } from './env.js';
4
4
  import { CodedError } from './error-codes.js';
5
+ import { currentInstanceId } from './deep-links.js';
5
6
 
6
7
  const COLLECTION = 'invites';
7
8
 
@@ -86,7 +87,7 @@ export async function createMemberAccess(db, { created_by, display_name, days =
86
87
  * A redeemed invite always gets a NEW person (multi-user report v2, defect 2,
87
88
  * 2026-10-01). Until then the guest's id was the slug of the display name the
88
89
  * invite carried, and an existing person with that slug was silently reused:
89
- * an invite named "Alex" (or "ALEX", "Alex!") redeemed as the owner, wrote as
90
+ * an invite named "Alex" (or "ALEX", "Aléx") redeemed as the owner, wrote as
90
91
  * the owner and passed the owner-only invite check. A display name is a label,
91
92
  * not a credential, so it never selects an existing identity:
92
93
  * - the slug is a starting point; if any person already holds it, or it is a
@@ -127,6 +128,10 @@ export async function redeemInvite(db, code) {
127
128
  const digest = inviteDigest(String(code).trim());
128
129
  const row = await col.findOne({ digest });
129
130
  if (!row) return { ok: false, reason: 'unknown' };
131
+ if (row.retired_at || row.superseded_by || row.retired === true) return { ok: false, reason: 'retired' };
132
+ if (typeof row.instance_id === 'string' && row.instance_id && row.instance_id !== currentInstanceId()) {
133
+ return { ok: false, reason: 'wrong_instance' };
134
+ }
130
135
  const door = row.door === 'member' ? 'member' : 'guest';
131
136
  if (door === 'member' ? MEMBER_ACCESS_FROZEN : INVITES_FROZEN) {
132
137
  return { ok: false, reason: 'frozen', message: door === 'member' ? MEMBER_ACCESS_FROZEN_REASON : INVITES_FROZEN_REASON };
@@ -166,3 +171,44 @@ export async function redeemInvite(db, code) {
166
171
  await col.updateOne({ digest }, { $set: { person_id } });
167
172
  return { ok: true, person_id, scopes, display_name: claimed.display_name || row.display_name, door, source_tag: claimed.source_tag || row.source_tag || null };
168
173
  }
174
+
175
+ /** Retire unused invite codes. Rows stay. A code already redeemed is history. */
176
+ export async function retireUnusedInvites(db, { eventId, at, household = false, tag = null, personId = null } = {}) {
177
+ const col = db.collection(COLLECTION);
178
+ const rows = typeof col.find === 'function' ? await col.find({}).toArray() : [];
179
+ let n = 0;
180
+ for (const row of rows) {
181
+ if (!row || row.used_at || row.retired_at || row.superseded_by) continue;
182
+ if (row.rotation_event_id === eventId) continue;
183
+ if (!household) {
184
+ const tagOk = tag && row.source_tag === tag;
185
+ const personOk = personId && row.person_id === personId;
186
+ if (!tagOk && !personOk) continue;
187
+ }
188
+ const filter = row._id != null ? { _id: row._id } : { digest: row.digest };
189
+ await col.updateOne(filter, { $set: { retired_at: at, superseded_by: eventId, retired: true, deleted: false } });
190
+ n += 1;
191
+ }
192
+ return n;
193
+ }
194
+
195
+ /**
196
+ * One fresh invite from a rotation. Single-use like every invite, and bound
197
+ * to this process instance. The plaintext code is returned once and is not
198
+ * written to a log by this function.
199
+ */
200
+ export async function createRotationInvite(db, { created_by, display_name, door, source_tag, instance_id, rotation_event_id } = {}) {
201
+ const made = door === 'member'
202
+ ? await createMemberAccess(db, { created_by, display_name, source_tag })
203
+ : await createInvite(db, { created_by, display_name, source_tag });
204
+ await db.collection(COLLECTION).updateOne(
205
+ { digest: inviteDigest(made.code) },
206
+ { $set: { instance_id: instance_id || null, rotation_event_id: rotation_event_id || null, single_use: true } }
207
+ );
208
+ return {
209
+ ...made,
210
+ source_tag: source_tag || null,
211
+ instance_id: instance_id || null,
212
+ rotation_event_id: rotation_event_id || null
213
+ };
214
+ }
package/src/layers.js CHANGED
@@ -248,7 +248,7 @@ export function bandFor(layer) {
248
248
 
249
249
  /** Named importance buckets. The word is the differentiator; the range is
250
250
  * compatibility for the stored float. Degree (low/mid/high) is the only
251
- * reason to pick a number other than the midpoint. Alex 2026-09-26. */
251
+ * reason to pick a number other than the midpoint. the owner 2026-09-26. */
252
252
  export const IMPORTANCE_BUCKETS = Object.freeze({
253
253
  constitutive: { range: [0.9, 1.0], layers: ['identity'] },
254
254
  durable: { range: [0.6, 0.9], layers: ['semantic', 'meta'] },
@@ -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
- * staging/emet-lessons-to-checks.md.
35
+ * the staging note.
36
36
  */
37
37
 
38
38
  // ---------------------------------------------------------------------------
package/src/logger.js CHANGED
@@ -52,7 +52,9 @@ const AuditOperation = Object.freeze({
52
52
  SERVER_START: 'SERVER_START',
53
53
  SERVER_STOP: 'SERVER_STOP',
54
54
  CONFIG_CHANGE: 'CONFIG_CHANGE',
55
- GEM_SERVE: 'GEM_SERVE'
55
+ GEM_SERVE: 'GEM_SERVE',
56
+ BREAK_GLASS: 'BREAK_GLASS',
57
+ ROTATE_ALL: 'ROTATE_ALL'
56
58
  });
57
59
 
58
60
  /**