@dreamforgestudiollc/emet 0.3.0 → 0.3.2

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 (73) hide show
  1. package/.env.example +2 -2
  2. package/CHANGELOG.md +37 -0
  3. package/README.md +33 -8
  4. package/docs/BOOTSTRAP.md +2 -0
  5. package/docs/BOTS.md +8 -7
  6. package/docs/DEPLOY.md +6 -0
  7. package/docs/DEVELOPMENT-PRACTICES.md +26 -0
  8. package/docs/ERROR-CODES-SPEC.md +1 -1
  9. package/docs/ERROR-CODES.md +29 -0
  10. package/docs/GUIDED-SETUP.md +1 -1
  11. package/docs/PERMISSIONS.md +5 -5
  12. package/docs/SETUP.md +10 -4
  13. package/docs/SUBKEYS.md +4 -4
  14. package/package.json +3 -2
  15. package/server.json +8 -4
  16. package/src/aleph.js +34 -13
  17. package/src/annotations.js +6 -2
  18. package/src/approve-throttle.js +3 -0
  19. package/src/atlas-role.js +1 -1
  20. package/src/attribution.js +76 -28
  21. package/src/bound-door.js +170 -0
  22. package/src/break-glass.js +531 -0
  23. package/src/checkpoint.js +241 -0
  24. package/src/chooser.js +543 -0
  25. package/src/claimed-tag.js +140 -0
  26. package/src/conformance.js +269 -5
  27. package/src/deep-links.js +267 -0
  28. package/src/dispatch.js +112 -18
  29. package/src/error-codes.js +29 -0
  30. package/src/error-log.js +138 -26
  31. package/src/error-report.js +17 -5
  32. package/src/gaps.js +1 -1
  33. package/src/grants.js +230 -0
  34. package/src/http-remote.js +80 -26
  35. package/src/index.js +18 -2
  36. package/src/invites.js +47 -1
  37. package/src/layers.js +1 -1
  38. package/src/lessons-to-checks.js +1 -1
  39. package/src/logger.js +3 -1
  40. package/src/oauth-provider.js +89 -5
  41. package/src/owl.js +232 -0
  42. package/src/owner-approvals.js +24 -267
  43. package/src/owner-session.js +174 -0
  44. package/src/pages.js +1 -1
  45. package/src/persons.js +39 -6
  46. package/src/proof-run.js +70 -0
  47. package/src/redact.js +4 -0
  48. package/src/request-log.js +2 -2
  49. package/src/rotate.js +554 -0
  50. package/src/rune-dispatch.js +1 -1
  51. package/src/session-graph.js +44 -25
  52. package/src/session.js +3 -3
  53. package/src/setup.js +21 -12
  54. package/src/staged-write.js +522 -0
  55. package/src/startup-pages.js +2 -2
  56. package/src/startup-payload.js +3 -3
  57. package/src/subkeys.js +61 -0
  58. package/src/tools.js +270 -78
  59. package/src/transcript-session.js +23 -4
  60. package/src/validation.js +1 -1
  61. package/src/version.js +1 -1
  62. package/src/writer-approval.js +394 -0
  63. package/templates/AREA.md +1 -1
  64. package/templates/BOTHANDOFF.md +2 -2
  65. package/templates/GRANT.md +48 -0
  66. package/templates/INDEX.md +9 -7
  67. package/templates/PROCEDURE.md +1 -1
  68. package/templates/ROSTER.md +2 -2
  69. package/templates/SEED.md +2 -2
  70. package/templates/SESSIONDISPOSITION.md +59 -0
  71. package/templates/STAGING.md +1 -1
  72. package/templates/STANDARD.md +1 -1
  73. package/templates/THREAD.md +1 -1
@@ -81,7 +81,7 @@ const ANNOTATION_TABLE = {
81
81
 
82
82
  // --- Additive writes. These add; they do not remove or replace. -----------
83
83
  // Was READ until 2026-09-27: "it does not write anything itself". Since the
84
- // blocked-close cap it records each blocked attempt in
84
+ // blocked-close cap (thatcommit) it records each blocked attempt in
85
85
  // close_attempts, so a read-only hint would be untrue (code audit, 1.3).
86
86
  emet_session_close: { title: 'Check session is saved', ...ADD },
87
87
  emet_client_approve: { title: 'Approve a new client', ...REPLACE },
@@ -101,6 +101,10 @@ const ANNOTATION_TABLE = {
101
101
  // --- Replacing writes. Prior versions are archived, but the visible
102
102
  // content of an existing document is replaced. -------------------------
103
103
  write_doc: { title: 'Write a document', ...REPLACE },
104
+ write_doc_begin: { title: 'Begin a staged document write', ...ADD },
105
+ write_doc_append: { title: 'Append a staged document chunk', readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
106
+ write_doc_commit: { title: 'Commit a staged document write', readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
107
+ write_doc_abort: { title: 'Abort a staged document write', readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
104
108
  patch_doc: { title: 'Edit a document', ...REPLACE },
105
109
  emet_setup_complete: { title: 'Complete setup', ...REPLACE },
106
110
 
@@ -123,7 +127,7 @@ const ANNOTATION_TABLE = {
123
127
  // probe document and removes it again, so it is not declared read-only -
124
128
  // a health check that only reads cannot detect a broken write path.
125
129
  // Replaced emet_setup_status, get_status and emet_verify_connection on
126
- // 2026-09-27 (Alex: consolidate overlapping tools). -----------------------
130
+ // 2026-09-27 (the owner: consolidate overlapping tools). -----------------------
127
131
  emet_status: { title: 'Store status and write-path probe', readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }
128
132
  };
129
133
 
@@ -51,4 +51,7 @@ export class ApproveThrottle {
51
51
  }
52
52
 
53
53
  recordSuccess(ip) { this.failures.delete(String(ip)); }
54
+
55
+ /** Owner break-glass clears one address. It does not clear every address. */
56
+ clearAddress(ip) { this.failures.delete(String(ip)); }
54
57
  }
package/src/atlas-role.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { CodedError } from './error-codes.js';
2
2
  /**
3
3
  * EMET - the least-privilege MongoDB Atlas role for the server's own login
4
- * (2026-09-29; security audit question 9, staging/emet-security-audit.md).
4
+ * (2026-09-29; security audit question 9, the staging note).
5
5
  *
6
6
  * The record is retained, never deleted (the owner's rule, 2026-09-08). Until
7
7
  * this role existed that rule lived only in the code: the server's login held
@@ -1,16 +1,19 @@
1
1
  /**
2
2
  * EMET - attribution per session, v2 (2026-10-12).
3
3
  *
4
- * Alex approved PROPOSAL.md (the attribution proposal) with its 7 defaults;
5
- * v1 (PR 32) was reverted after the second reader's review (A1-A4). This version:
4
+ * the owner approved PROPOSAL.md (the attribution proposal) with its 7 defaults;
5
+ * v1 (PR 32) was reverted after Tester's review (A1-A4). This version:
6
6
  *
7
7
  * STAMP vs RIGHTS. Several agents share one OAuth login (the Grok client
8
- * 8xm-7ILLKEDFc3-QRxqlgw). A bot's declared tag is what its writes are
8
+ * bound-login-client). A bot's declared tag is what its writes are
9
9
  * stamped with (source_basis "declared", source_login = the login's tag),
10
10
  * but a declared tag never gains rights beyond the login's tag (A3): every
11
11
  * guard is run for BOTH tags and the write must pass both (rightsTags()).
12
+ * grok-project on the token bound to hub-bot is not that
13
+ * claim: it is refused (BOUND's own door). A credential row (basis
14
+ * "credential") is not a remembered tag for the shared client.
12
15
  *
13
- * NEW CLIENTS (Alex, 2026-10-12). A tag is known when it is in
16
+ * NEW CLIENTS (the owner, 2026-10-12). A tag is known when it is in
14
17
  * EMET_SOURCE_TAGS, approved in the approvals record, or bound to a login at
15
18
  * consent (the owner approved that at the consent page). The first write by
16
19
  * any other tag is refused (read-limited) and queued in the approvals
@@ -34,14 +37,19 @@
34
37
  */
35
38
 
36
39
  import { setting } from './env.js';
40
+ import { chooserBinding } from './deep-links.js';
41
+ import { isOwlIdentity } from './owl.js';
42
+ import { isMasterBlasterActor } from './writer-approval.js';
43
+ import { isSophiaCredential, sophiaClaimOnSharedLogin, BOUND_LOGIN_MESSAGE, CLAIM_TAG, MB_TAG } from './bound-door.js';
37
44
 
38
45
  export const APPROVALS_DOC = 'emet/CLIENT_APPROVALS.md';
39
46
  export const WRITE_TOOLS = new Set([
40
- 'save_to_layer', 'revise_memory', 'write_doc', 'patch_doc', 'retire_doc', 'rename_doc', 'restore_doc',
47
+ 'save_to_layer', 'revise_memory', 'write_doc', 'write_doc_begin', 'write_doc_append', 'write_doc_commit', 'write_doc_abort',
48
+ 'patch_doc', 'retire_doc', 'rename_doc', 'restore_doc',
41
49
  'accept_nonconformance', 'emet_transcript_append', 'save_transcript', 'revise_transcript', 'emet_session_close',
42
- // the second reader's re-review (2026-10-12): opening a session claims it; deciding a client is a write.
50
+ // Tester's re-review (2026-10-12): opening a session claims it; deciding a client is a write.
43
51
  'emet_session_open', 'emet_client_approve',
44
- // the second reader's PR 47 review: setup writes durable identity and board docs.
52
+ // Tester's PR 47 review: setup writes durable identity and board docs.
45
53
  'emet_setup_complete'
46
54
  ]);
47
55
  /** Tools the strict login tag also covers. emet_initialize can provision, so a
@@ -92,7 +100,7 @@ export function cachedApprovals() { return approvalsCache.data; }
92
100
  export function emptyApprovals() { return { approved: {}, pending: {}, denied: {}, clients: {} }; }
93
101
 
94
102
  /**
95
- * Remembered tags for one client_id (Alex 2026-10-12): approved clients keep
103
+ * Remembered tags for one client_id (the owner 2026-10-12): approved clients keep
96
104
  * their tag across logins. A shared client_id can carry several approved tags
97
105
  * (one per bot), so this is a set. Retired entries (renamed away) are skipped.
98
106
  * Approvals recorded before the map existed count through their request.
@@ -104,6 +112,7 @@ export function rememberedFor(d, clientId) {
104
112
  const retired = new Set();
105
113
  if (row && row.tags) for (const [t, v] of Object.entries(row.tags)) (v && v.retired ? retired : out).add(t);
106
114
  for (const [t, v] of Object.entries(d.approved || {})) {
115
+ if (v && v.basis === 'credential') continue;
107
116
  const cid = v && (v.client_id || (v.request && v.request.client_id));
108
117
  if (cid === clientId && !retired.has(t)) out.add(t);
109
118
  }
@@ -119,7 +128,7 @@ function remember(d, clientId, tag, { declared_name = null, basis = null, at, re
119
128
  if (renamed_from && row.tags[renamed_from]) row.tags[renamed_from] = { ...row.tags[renamed_from], retired: true, renamed_to: tag, retired_at: at };
120
129
  }
121
130
 
122
- /** Strict: returns null when the record does not parse (fail closed, the second reader 4). */
131
+ /** Strict: returns null when the record does not parse (fail closed, Tester 4). */
123
132
  export function parseApprovals(content) {
124
133
  const m = /```json\n([\s\S]*?)\n```/.exec(String(content || ''));
125
134
  if (!m) return null;
@@ -160,7 +169,7 @@ export async function loadApprovals(deps, { fresh = false } = {}) {
160
169
  }
161
170
 
162
171
  /**
163
- * Compare-and-set (the second reader 3): mutations run one at a time in this process, each
172
+ * Compare-and-set (Tester 3): mutations run one at a time in this process, each
164
173
  * re-reads the record and writes with the version it read; a version moved by
165
174
  * another writer is retried on the fresh copy. `fn(data)` returns false to write nothing.
166
175
  */
@@ -197,7 +206,7 @@ export function personIsOwner(actor, ownerId) {
197
206
  }
198
207
 
199
208
  /**
200
- * The owner acting as the owner (the second reader A2 re-review). Over HTTP the person must be
209
+ * The owner acting as the owner (Tester A2 re-review). Over HTTP the person must be
201
210
  * the owner AND the call must carry the login's own tag (no declared or
202
211
  * generated tag) AND that tag must not be a bot tag. Every bot on the owner's
203
212
  * shared login is therefore not the owner. Stdio is the local owner.
@@ -239,7 +248,12 @@ export function autoTag(clientId) {
239
248
  return `auto-${slug}`;
240
249
  }
241
250
 
242
- function refusal(msg) { const e = new Error(msg); e.attributionRefusal = true; return e; }
251
+ function refusal(msg, chooser) {
252
+ const e = new Error(msg);
253
+ e.attributionRefusal = true;
254
+ if (chooser) e.chooser = chooser;
255
+ return e;
256
+ }
243
257
 
244
258
  export function bindSession(base, tag, extra = {}) {
245
259
  if (SESSION_BINDINGS.has(base)) return;
@@ -247,7 +261,7 @@ export function bindSession(base, tag, extra = {}) {
247
261
  SESSION_BINDINGS.set(base, { agent_tag: tag, ...extra, bound_at: new Date() });
248
262
  }
249
263
 
250
- /** Tags already on the session's stored rows (A4: survives a restart). Read only; fails closed (the second reader A4). */
264
+ /** Tags already on the session's stored rows (A4: survives a restart). Read only; fails closed (Tester A4). */
251
265
  export async function storedSessionTags(db, base, layerCollections = []) {
252
266
  if (!base) return [];
253
267
  if (!db) throw refusal(`the store cannot be read to check who owns session ${base}; nothing was written.`);
@@ -336,6 +350,15 @@ export async function preflight(ctx, actor, args, toolName) {
336
350
  if (foreign) throw refusal(`source "${actor.subkeyTag}" is bound to another person's login, so this session may not write under it. Pass your own tag. Nothing was written.`);
337
351
  }
338
352
 
353
+ if (STRICT_TAG_TOOLS.has(toolName) && sophiaClaimOnSharedLogin(actor, declared)) {
354
+ const denied = refusal(
355
+ BOUND_LOGIN_MESSAGE,
356
+ chooserBinding({ kind: 'onboarding_required', grantId: actor.grantId, tag: CLAIM_TAG, door: 'member' })
357
+ );
358
+ denied.emetCode = 'EMET-AUTH-044';
359
+ throw denied;
360
+ }
361
+
339
362
  if (actor.subkeySession && actor.subkeyTag) {
340
363
  actor.declaredTag = null;
341
364
  actor.sourceBasis = 'subkey';
@@ -357,7 +380,7 @@ export async function preflight(ctx, actor, args, toolName) {
357
380
  return actor;
358
381
  }
359
382
 
360
- // Remembered tags for this client_id (Alex 2026-10-12).
383
+ // Remembered tags for this client_id (the owner 2026-10-12).
361
384
  let remembered = [];
362
385
  if (deps && actor.clientId && actor.clientId !== 'http:visitor') {
363
386
  const cur0 = await loadApprovals(deps);
@@ -380,21 +403,29 @@ export async function preflight(ctx, actor, args, toolName) {
380
403
  };
381
404
  return true;
382
405
  });
383
- throw refusal(`this client is remembered as ${remembered.map((t) => `"${t}"`).join(', ')}; "${declared}" is a rename and waits for ${cosTag() ? `the chief of staff (${cosTag()})` : 'the owner'} to approve it. Use your remembered tag. Nothing was written.`);
406
+ throw refusal(
407
+ `this client is remembered as ${remembered.map((t) => `"${t}"`).join(', ')}; "${declared}" is a rename and waits for ${cosTag() ? `the chief of staff (${cosTag()})` : 'the owner'} to approve it. Use your remembered tag. Nothing was written.`,
408
+ chooserBinding({ kind: 'rename_pending', grantId: actor.grantId, tag: declared, door: actor.door })
409
+ );
384
410
  }
385
411
  return actor;
386
412
  }
387
413
  const keptAuto = !declared && !bound && remembered.length === 1 ? remembered[0] : null;
388
- const effective = declared || bound || keptAuto || (actor.clientId && actor.clientId !== 'http:visitor' ? autoTag(actor.clientId) : null);
389
- const basis = declared && declared !== bound ? 'declared' : (bound ? 'login' : (keptAuto ? 'remembered' : (effective ? 'auto' : null)));
414
+ let effective = declared || bound || keptAuto || (actor.clientId && actor.clientId !== 'http:visitor' ? autoTag(actor.clientId) : null);
415
+ let basis = declared && declared !== bound ? 'declared' : (bound ? 'login' : (keptAuto ? 'remembered' : (effective ? 'auto' : null)));
416
+ const sophiaDoor = isSophiaCredential(actor) && (!declared || declared === CLAIM_TAG || declared === MB_TAG);
417
+ if (sophiaDoor) {
418
+ effective = CLAIM_TAG;
419
+ basis = 'credential';
420
+ }
390
421
  actor.declaredTag = basis === 'declared' || basis === 'auto' || basis === 'remembered' ? effective : null;
391
422
  actor.sourceBasis = basis;
392
423
  actor.effectiveTag = effective;
393
- actor.approvalState = basis === 'login' ? 'login' : (registry.includes(effective) ? 'registered' : null);
424
+ actor.approvalState = basis === 'credential' ? 'credential' : (basis === 'login' ? 'login' : (registry.includes(effective) ? 'registered' : null));
394
425
 
395
- // New-client gate (Alex 2026-10-12). Bound tags were approved at consent;
426
+ // New-client gate (the owner 2026-10-12). Bound tags were approved at consent;
396
427
  // registered tags by the owner's env. Everything else needs the record.
397
- if (deps && effective && basis !== 'login' && !registry.includes(effective)) {
428
+ if (!sophiaDoor && deps && effective && basis !== 'login' && basis !== 'credential' && !registry.includes(effective)) {
398
429
  const cur = await loadApprovals(deps);
399
430
  if (cur.broken) {
400
431
  actor.approvalState = 'unreadable';
@@ -405,7 +436,10 @@ export async function preflight(ctx, actor, args, toolName) {
405
436
  if (Object.prototype.hasOwnProperty.call(appr.approved, effective)) actor.approvalState = 'approved';
406
437
  else if (Object.prototype.hasOwnProperty.call(appr.denied, effective)) {
407
438
  actor.approvalState = 'denied';
408
- if (isWrite) throw refusal(`"${effective}" was denied as a client on this store; it may read only. Nothing was written.`);
439
+ if (isWrite) throw refusal(
440
+ `"${effective}" was denied as a client on this store; it may read only. Nothing was written.`,
441
+ chooserBinding({ kind: 'deny', grantId: actor.grantId, tag: effective, door: actor.door })
442
+ );
409
443
  } else {
410
444
  const fresh = cur.missing && registry.length === 0 && personIsOwner(actor, ownerId) && !(await storeHasOtherClients(db, prefix, actor));
411
445
  if (fresh && isWrite) {
@@ -415,7 +449,10 @@ export async function preflight(ctx, actor, args, toolName) {
415
449
  remember(d, actor.clientId, effective, { declared_name: declared || effective, basis, at: now.toISOString() });
416
450
  return true;
417
451
  });
418
- if (!approvalsCache.data.approved[effective]) throw refusal(`"${effective}" is a new client and the store already has a primary; it waits for approval. Nothing was written.`);
452
+ if (!approvalsCache.data.approved[effective]) throw refusal(
453
+ `"${effective}" is a new client and the store already has a primary; it waits for approval. Nothing was written.`,
454
+ chooserBinding({ kind: 'onboarding_required', grantId: actor.grantId, tag: effective, door: actor.door })
455
+ );
419
456
  actor.approvalState = 'approved';
420
457
  } else {
421
458
  actor.approvalState = appr.pending[effective] ? 'pending' : 'new';
@@ -432,7 +469,10 @@ export async function preflight(ctx, actor, args, toolName) {
432
469
  return true;
433
470
  });
434
471
  actor.approvalState = 'pending';
435
- throw refusal(`"${effective}" is a new client on this store and is read-limited until ${cosTag() ? `the chief of staff (${cosTag()})` : 'the owner'} approves it with emet_client_approve. The request is queued; nothing was written.`);
472
+ throw refusal(
473
+ `"${effective}" is a new client on this store and is read-limited until ${cosTag() ? `the chief of staff (${cosTag()})` : 'the owner'} approves it with emet_client_approve. The request is queued; nothing was written.`,
474
+ chooserBinding({ kind: 'onboarding_required', grantId: actor.grantId, tag: effective, door: actor.door })
475
+ );
436
476
  }
437
477
  }
438
478
  }
@@ -460,6 +500,7 @@ export function summarizeWrite(toolName, args) {
460
500
  const a = args || {};
461
501
  const parts = [toolName];
462
502
  if (a.doc_id) parts.push(`doc ${a.doc_id}`);
503
+ if (a.stage_id) parts.push(`stage ${a.stage_id}`);
463
504
  if (a.layer) parts.push(`layer ${a.layer}`);
464
505
  if (a.session_id) parts.push(`session ${a.session_id}`);
465
506
  const text = a.content || a.new_str || a.assistant_message || '';
@@ -482,8 +523,8 @@ export function approvalsView(data, actor, ownerId) {
482
523
 
483
524
  /**
484
525
  * emet_client_approve. Only the owner acting as the owner, or the configured
485
- * COS on its own login tag; never the client deciding itself (the second reader 1).
486
- * Idempotent: the same decision again writes nothing (the second reader 2).
526
+ * COS on its own login tag; never the client deciding itself (Tester 1).
527
+ * Idempotent: the same decision again writes nothing (Tester 2).
487
528
  */
488
529
  export async function clientApprove(deps, actor, ownerId, { tag, decision, reason, as, from } = {}, _registry = [], now = new Date()) {
489
530
  const t = typeof tag === 'string' ? tag.trim() : '';
@@ -494,6 +535,13 @@ export async function clientApprove(deps, actor, ownerId, { tag, decision, reaso
494
535
  const ownerOk = actorIsOwner(actor, ownerId);
495
536
  const cosOk = actorIsCos(actor);
496
537
  if (!(ownerOk || cosOk)) throw refusal(`emet_client_approve: only the owner${cosTag() ? ` or the chief of staff (${cosTag()})` : ''} may decide new clients. Nothing was changed.`);
538
+ if (isOwlIdentity(actor)) throw refusal('emet_client_approve: the owl MCP clone account was retired by R6 and cannot approve. the owner decides a new writer on /owner/chooser. Nothing was changed.');
539
+ if (decision === 'approve' && isMasterBlasterActor(actor) && !(actor && actor.ownerSession === true)) {
540
+ throw refusal('emet_client_approve: an AI cannot grant a writer. Master Hub prepares a request. the owner decides it on /owner/chooser. Nothing was changed.');
541
+ }
542
+ if (decision === 'approve' && cosOk && !(actor && actor.ownerSession === true)) {
543
+ throw refusal('emet_client_approve: an AI cannot grant a writer. Master Hub prepares a request. the owner decides it on /owner/chooser. Nothing was changed.');
544
+ }
497
545
  if (setting('SUBKEYS') === '1') {
498
546
  const { decideSubkeyIfPending } = await import('./subkeys.js');
499
547
  const decided = await decideSubkeyIfPending(deps, actor, ownerId, { tag: t, decision, reason }, now);
@@ -502,7 +550,7 @@ export async function clientApprove(deps, actor, ownerId, { tag, decision, reaso
502
550
  const by = ownerOk ? `owner (${actor && actor.personId || 'local'})` : `cos ${cosTag()}`;
503
551
  let result = null;
504
552
  await mutateApprovals(deps, (d) => {
505
- // the second reader round 3: whatever path made the caller "owner" or "COS", it may never
553
+ // Tester round 3: whatever path made the caller "owner" or "COS", it may never
506
554
  // decide a request that its own connection queued (same client_id or same
507
555
  // grant), nor a tag equal to its own. A bot on a shared login that omits
508
556
  // `source` looks like the login; this catches it.
@@ -512,7 +560,7 @@ export async function clientApprove(deps, actor, ownerId, { tag, decision, reaso
512
560
  const sameGrant = !!req.grant_id && req.grant_id === (actor.grantId || null);
513
561
  if (sameClient || sameGrant) throw refusal('emet_client_approve: this connection queued the request for "' + t + '", so it may not decide it. Decide from another client. Nothing was changed.');
514
562
  }
515
- // the second reader delta M2: a client_id that already has approved tags needs an explicit
563
+ // Tester delta M2: a client_id that already has approved tags needs an explicit
516
564
  // `as` ('add' keeps every sibling, 'rename' retires one named tag).
517
565
  const cidReq = (d.pending[t] && d.pending[t].client_id) || null;
518
566
  const siblings = decision === 'approve' && cidReq ? rememberedFor(d, cidReq).filter((x) => x !== t) : [];
@@ -540,7 +588,7 @@ export async function clientApprove(deps, actor, ownerId, { tag, decision, reaso
540
588
  return result;
541
589
  }
542
590
 
543
- /** What emet_initialize tells a client about its remembered tag (Alex 2026-10-12). */
591
+ /** What emet_initialize tells a client about its remembered tag (the owner 2026-10-12). */
544
592
  export function rememberedView(actor) {
545
593
  const tags = actor && Array.isArray(actor.rememberedTags) ? actor.rememberedTags : [];
546
594
  if (!tags.length) return null;
@@ -0,0 +1,170 @@
1
+ /**
2
+ * BOUND's door (init audit items 3 and 5, 2026-10-27).
3
+ *
4
+ * grok-project is a host tag. It is not a declared claim on the Master
5
+ * Hub token that shares OAuth client bound-login-client. That token
6
+ * is bound to hub-bot. A grok-project claim on it is refused
7
+ * and is not stamped hub-bot.
8
+ *
9
+ * A credential is the token's own source_tag grok-project (member, owner, or
10
+ * a legacy token with no door) or a sub-key whose tag is grok-project. Guest
11
+ * is not a writer credential. One EMET server. No second instance.
12
+ *
13
+ * The approvals row lists that credential. It does not remember grok-project
14
+ * onto the shared client, so the claim path stays closed. CI does not mint a
15
+ * live key and does not approve a production client.
16
+ */
17
+
18
+ import { rawActor } from './persons.js';
19
+ import { chooserBinding } from './deep-links.js';
20
+ import { ValidationError } from './validation.js';
21
+
22
+ export const CLAIM_TAG = 'grok-project';
23
+ /** Same string as writer-approval.js MB_TAG. */
24
+ export const MB_TAG = 'hub-bot';
25
+ export const SHARED_GROK_CLIENT = 'bound-login-client';
26
+ export const EPISODIC_697_ID = 697;
27
+ export const CORRECTION_NOTE_DATE = '2026-10-27';
28
+
29
+ export const BOUND_LOGIN_MESSAGE =
30
+ 'A bound login cannot stamp another tag (EMET-AUTH-044). Nothing was written.';
31
+
32
+ /**
33
+ * HTTP, authenticated, and the tag is on the credential rather than a claim.
34
+ * Guest is not a writer credential. A declared tag does not remove a login
35
+ * credential and is not itself a credential.
36
+ */
37
+ export function isSophiaCredential(actor) {
38
+ if (!actor || actor.transport !== 'http' || actor.authenticated !== true) return false;
39
+ if (actor.door === 'guest') return false;
40
+ if (actor.subkeySession === true && actor.subkeyTag === CLAIM_TAG) return true;
41
+ const login = typeof actor.sourceTag === 'string' ? actor.sourceTag.trim() : '';
42
+ if (login !== CLAIM_TAG) return false;
43
+ return actor.door === 'member' || actor.door === 'owner' || actor.door == null;
44
+ }
45
+
46
+ /**
47
+ * The shared Grok client, bound to Master Hub, claiming grok-project.
48
+ * A BOUND credential is not this claim. Only the caller string counts, so a
49
+ * tag left on a reused actor object cannot refuse a later write that names
50
+ * no source.
51
+ */
52
+ export function sophiaClaimOnSharedLogin(actor, callerTag) {
53
+ if (!actor || actor.transport !== 'http' || actor.authenticated !== true) return false;
54
+ if (actor.clientId !== SHARED_GROK_CLIENT) return false;
55
+ const bound = typeof actor.sourceTag === 'string' ? actor.sourceTag.trim() : '';
56
+ if (bound !== MB_TAG) return false;
57
+ if (isSophiaCredential(actor)) return false;
58
+ const declared = typeof callerTag === 'string' ? callerTag.trim() : '';
59
+ return declared === CLAIM_TAG;
60
+ }
61
+
62
+ /** Stamp grok-project when the credential's caller is empty, itself, or Master Hub. */
63
+ export function sophiaCredentialOverrides(actor, callerTag) {
64
+ if (!isSophiaCredential(actor)) return false;
65
+ const caller = typeof callerTag === 'string' ? callerTag.trim() : '';
66
+ return caller === '' || caller === CLAIM_TAG || caller === MB_TAG;
67
+ }
68
+
69
+ export function refuseSophiaDoor(actor) {
70
+ const grantId = actor && typeof actor.grantId === 'string' && actor.grantId.trim() ? actor.grantId.trim() : 'unknown';
71
+ const err = new ValidationError('source', BOUND_LOGIN_MESSAGE, { code: 'EMET-AUTH-044' });
72
+ err.chooser = chooserBinding({ kind: 'onboarding_required', grantId, tag: CLAIM_TAG, door: 'member' });
73
+ throw err;
74
+ }
75
+
76
+ /**
77
+ * Dated episodic correction for 697. The parent stays. This is not
78
+ * revise_memory and it does not supersede the row. Master Hub writes it
79
+ * on the live store after merge, from the Master Hub login, and does not
80
+ * pass source grok-project on that login.
81
+ */
82
+ export function episodic697CorrectionNote() {
83
+ return {
84
+ layer: 'episodic',
85
+ content: [
86
+ `Correction note dated ${CORRECTION_NOTE_DATE}.`,
87
+ `Episodic ${EPISODIC_697_ID} was written from client ${SHARED_GROK_CLIENT} and stamped ${MB_TAG}.`,
88
+ `That stamp is a misattribution when the writer was BOUND (${CLAIM_TAG}).`,
89
+ 'The original row is retained. This note does not edit it in place and does not supersede it.',
90
+ `A BOUND write carries ${CLAIM_TAG} from its own door.`,
91
+ `Master Hub writes this note on the live store after merge, from the Master Hub login, and does not pass source ${CLAIM_TAG} on that login.`
92
+ ].join(' '),
93
+ metadata: {
94
+ corrects: EPISODIC_697_ID,
95
+ assertion_origin: 'assistant',
96
+ custom: {
97
+ correction: 'misattribution',
98
+ cited_source: MB_TAG,
99
+ correct_source: CLAIM_TAG,
100
+ cited_client: SHARED_GROK_CLIENT,
101
+ dated: CORRECTION_NOTE_DATE
102
+ }
103
+ }
104
+ };
105
+ }
106
+
107
+ /**
108
+ * List grok-project as a credential door. Does not remember() it onto the
109
+ * shared client. Idempotent for the same client, door, and grant.
110
+ */
111
+ export async function recordSophiaCredential(deps, { client_id, door, grant_id, by } = {}, now = new Date()) {
112
+ if (!deps || typeof deps.readDoc !== 'function' || typeof deps.writeDoc !== 'function') {
113
+ return { written: false, reason: 'no-approvals-io' };
114
+ }
115
+ const doorName = door === 'owner' || door === 'member' ? door : null;
116
+ if (!doorName) return { written: false, reason: door === 'guest' ? 'guest' : 'door' };
117
+ if (typeof client_id !== 'string' || !client_id.trim()) return { written: false, reason: 'client' };
118
+ const clientId = client_id.trim();
119
+ const grant = typeof grant_id === 'string' && grant_id.trim() ? grant_id.trim() : null;
120
+ const { mutateApprovals } = await import('./attribution.js');
121
+ const at = (now instanceof Date ? now : new Date(now)).toISOString();
122
+ const out = await mutateApprovals(deps, (d) => {
123
+ const prev = d.approved[CLAIM_TAG];
124
+ const pending = d.pending && d.pending[CLAIM_TAG];
125
+ const same = prev
126
+ && prev.basis === 'credential'
127
+ && prev.door === doorName
128
+ && prev.client_id === clientId
129
+ && (prev.grant_id || null) === grant
130
+ && !pending;
131
+ if (same) return false;
132
+ d.approved[CLAIM_TAG] = {
133
+ basis: 'credential',
134
+ door: doorName,
135
+ client_id: clientId,
136
+ grant_id: grant,
137
+ source_tag: CLAIM_TAG,
138
+ separate_from_client: SHARED_GROK_CLIENT,
139
+ separate_from_tag: MB_TAG,
140
+ by: by || 'owner',
141
+ at,
142
+ rule: 'separate login, then assign grok-project, then initialize'
143
+ };
144
+ if (d.pending && d.pending[CLAIM_TAG]) delete d.pending[CLAIM_TAG];
145
+ return true;
146
+ });
147
+ return { written: out.written, approved: out.data.approved[CLAIM_TAG] };
148
+ }
149
+
150
+ /** After the owner's chooser issues a grok-project door. The preparer's grant is not stored. */
151
+ export async function sophiaListingAfterWriterIssue({ recorded, issued, deps, by, now } = {}) {
152
+ if (!recorded || recorded.claimed_tag !== CLAIM_TAG) return { written: false, reason: 'tag' };
153
+ if (!issued || issued.issued !== true) return { written: false, reason: 'not-issued' };
154
+ if (recorded.door === 'guest') return { written: false, reason: 'guest' };
155
+ try {
156
+ return await recordSophiaCredential(deps, {
157
+ client_id: recorded.client_id,
158
+ door: recorded.door,
159
+ grant_id: null,
160
+ by: by || 'owner'
161
+ }, now instanceof Date ? now : new Date());
162
+ } catch {
163
+ return { written: false, reason: 'failed' };
164
+ }
165
+ }
166
+
167
+ /** The actor in force, for stamp sites that do not take one. */
168
+ export function sophiaActor() {
169
+ return rawActor();
170
+ }