@codemem/core 0.43.1 → 0.44.0-alpha.1

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 (113) hide show
  1. package/dist/attribution-diagnostics.d.ts.map +1 -1
  2. package/dist/better-sqlite-coordinator-store.d.ts +5 -0
  3. package/dist/better-sqlite-coordinator-store.d.ts.map +1 -1
  4. package/dist/coordinator-actions.d.ts +24 -0
  5. package/dist/coordinator-actions.d.ts.map +1 -1
  6. package/dist/{coordinator-api-DGTIU3Ri.js → coordinator-api-Dlr65yhR.js} +1234 -904
  7. package/dist/coordinator-api-Dlr65yhR.js.map +1 -0
  8. package/dist/coordinator-api.d.ts.map +1 -1
  9. package/dist/coordinator-enrollment-reconciler.d.ts +1 -1
  10. package/dist/coordinator-enrollment-reconciler.d.ts.map +1 -1
  11. package/dist/coordinator-legacy-team-completion.d.ts +75 -0
  12. package/dist/coordinator-legacy-team-completion.d.ts.map +1 -0
  13. package/dist/coordinator-membership-effects.d.ts.map +1 -1
  14. package/dist/coordinator-runtime.d.ts +11 -1
  15. package/dist/coordinator-runtime.d.ts.map +1 -1
  16. package/dist/coordinator-store-contract.d.ts +11 -0
  17. package/dist/coordinator-store-contract.d.ts.map +1 -1
  18. package/dist/coordinator-store-test-harness.d.ts.map +1 -1
  19. package/dist/coordinator-store.d.ts +2 -0
  20. package/dist/coordinator-store.d.ts.map +1 -1
  21. package/dist/d1-coordinator-store.d.ts +5 -0
  22. package/dist/d1-coordinator-store.d.ts.map +1 -1
  23. package/dist/db.d.ts.map +1 -1
  24. package/dist/dedup-key-backfill.d.ts.map +1 -1
  25. package/dist/distill.d.ts.map +1 -1
  26. package/dist/embeddings.d.ts +69 -6
  27. package/dist/embeddings.d.ts.map +1 -1
  28. package/dist/filters.d.ts.map +1 -1
  29. package/dist/hook-transcript.d.ts.map +1 -1
  30. package/dist/identity-device-assignment.d.ts.map +1 -1
  31. package/dist/identity-target.d.ts +3 -1
  32. package/dist/identity-target.d.ts.map +1 -1
  33. package/dist/index.d.ts +10 -4
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +10598 -8850
  36. package/dist/index.js.map +1 -1
  37. package/dist/ingest-pipeline.d.ts +9 -0
  38. package/dist/ingest-pipeline.d.ts.map +1 -1
  39. package/dist/ingest-xml-parser.d.ts.map +1 -1
  40. package/dist/internal/cloudflare-coordinator.d.ts +2 -0
  41. package/dist/internal/cloudflare-coordinator.d.ts.map +1 -1
  42. package/dist/internal/cloudflare-coordinator.js +391 -305
  43. package/dist/internal/cloudflare-coordinator.js.map +1 -1
  44. package/dist/legacy-recipient-policy-projection.d.ts +5 -0
  45. package/dist/legacy-recipient-policy-projection.d.ts.map +1 -1
  46. package/dist/legacy-team-attempt-lifecycle.d.ts +16 -0
  47. package/dist/legacy-team-attempt-lifecycle.d.ts.map +1 -0
  48. package/dist/legacy-team-candidate.d.ts +3 -13
  49. package/dist/legacy-team-candidate.d.ts.map +1 -1
  50. package/dist/legacy-team-project-canonical-preflight.d.ts +3 -1
  51. package/dist/legacy-team-project-canonical-preflight.d.ts.map +1 -1
  52. package/dist/legacy-team-project-policy.d.ts +4 -0
  53. package/dist/legacy-team-project-policy.d.ts.map +1 -0
  54. package/dist/legacy-team-setup-activation.d.ts +41 -1
  55. package/dist/legacy-team-setup-activation.d.ts.map +1 -1
  56. package/dist/legacy-team-setup-completion-manifest.d.ts +53 -0
  57. package/dist/legacy-team-setup-completion-manifest.d.ts.map +1 -0
  58. package/dist/legacy-team-setup-draft.d.ts +5 -2
  59. package/dist/legacy-team-setup-draft.d.ts.map +1 -1
  60. package/dist/legacy-team-setup-errors.d.ts +9 -2
  61. package/dist/legacy-team-setup-errors.d.ts.map +1 -1
  62. package/dist/legacy-team-setup-label-policy.d.ts +30 -0
  63. package/dist/legacy-team-setup-label-policy.d.ts.map +1 -0
  64. package/dist/legacy-team-setup-limits.d.ts +19 -1
  65. package/dist/legacy-team-setup-limits.d.ts.map +1 -1
  66. package/dist/local-project-inventory.d.ts +3 -0
  67. package/dist/local-project-inventory.d.ts.map +1 -0
  68. package/dist/memory-kinds.d.ts +24 -0
  69. package/dist/memory-kinds.d.ts.map +1 -0
  70. package/dist/observer-auth.d.ts.map +1 -1
  71. package/dist/observer-client.d.ts.map +1 -1
  72. package/dist/policy-team-device-eligibility.d.ts.map +1 -1
  73. package/dist/project-invite-acceptance.d.ts.map +1 -1
  74. package/dist/project-scope-settings.d.ts.map +1 -1
  75. package/dist/prompt-transport.d.ts.map +1 -1
  76. package/dist/raw-event-flush.d.ts.map +1 -1
  77. package/dist/raw-event-ingest.d.ts.map +1 -1
  78. package/dist/raw-event-sweeper.d.ts.map +1 -1
  79. package/dist/recipient-policy-contract.d.ts +5 -0
  80. package/dist/recipient-policy-contract.d.ts.map +1 -1
  81. package/dist/recipient-policy-edges.d.ts.map +1 -1
  82. package/dist/recipient-policy-identifiers.d.ts.map +1 -1
  83. package/dist/recipient-policy-migration.d.ts.map +1 -1
  84. package/dist/recipient-policy-onboarding.d.ts.map +1 -1
  85. package/dist/recipient-policy-review.d.ts +1 -13
  86. package/dist/recipient-policy-review.d.ts.map +1 -1
  87. package/dist/recipient-policy-team-metadata.d.ts +38 -0
  88. package/dist/recipient-policy-team-metadata.d.ts.map +1 -0
  89. package/dist/recipient-reviewed-intent.d.ts.map +1 -1
  90. package/dist/ref-backfill.d.ts.map +1 -1
  91. package/dist/release-discovery.d.ts.map +1 -1
  92. package/dist/schema-bootstrap.d.ts.map +1 -1
  93. package/dist/schema.d.ts +147 -109
  94. package/dist/schema.d.ts.map +1 -1
  95. package/dist/scope-backfill.d.ts.map +1 -1
  96. package/dist/secret-scanner.d.ts.map +1 -1
  97. package/dist/session-context-backfill.d.ts.map +1 -1
  98. package/dist/store.d.ts +3 -0
  99. package/dist/store.d.ts.map +1 -1
  100. package/dist/summary-dedup-backfill.d.ts.map +1 -1
  101. package/dist/sync-capability.d.ts.map +1 -1
  102. package/dist/sync-daemon.d.ts +15 -0
  103. package/dist/sync-daemon.d.ts.map +1 -1
  104. package/dist/sync-identity.d.ts.map +1 -1
  105. package/dist/sync-retention-runner.d.ts.map +1 -1
  106. package/dist/test-schema.generated.d.ts +1 -1
  107. package/dist/test-schema.generated.d.ts.map +1 -1
  108. package/dist/vector-migration.d.ts +1 -0
  109. package/dist/vector-migration.d.ts.map +1 -1
  110. package/dist/vectors.d.ts +36 -3
  111. package/dist/vectors.d.ts.map +1 -1
  112. package/package.json +18 -10
  113. package/dist/coordinator-api-DGTIU3Ri.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"cloudflare-coordinator.js","names":[],"sources":["../../src/d1-coordinator-store.ts","../../src/d1-coordinator-runtime.ts"],"sourcesContent":["import {\n\tassertMatchingMembershipEffectReceipt,\n\ttype CoordinatorMembershipEffectReceipt,\n\tCoordinatorMembershipError,\n\tgrantMembershipEffectRequestJson,\n\tmembershipFromEffectReceipt,\n\tnormalizeMembershipEffectId,\n\trevokeMembershipEffectRequestJson,\n} from \"./coordinator-membership-effects.js\";\nimport type {\n\tCoordinatorBootstrapGrant,\n\tCoordinatorConsumeProjectInviteInput,\n\tCoordinatorConsumeRecipientInviteInput,\n\tCoordinatorCreateBootstrapGrantInput,\n\tCoordinatorCreateInviteInput,\n\tCoordinatorCreateJoinRequestInput,\n\tCoordinatorCreateReciprocalApprovalInput,\n\tCoordinatorCreateScopeInput,\n\tCoordinatorEnrollDeviceInput,\n\tCoordinatorEnrollment,\n\tCoordinatorGrantScopeMembershipInput,\n\tCoordinatorGroup,\n\tCoordinatorInspectRecipientInviteInput,\n\tCoordinatorInvite,\n\tCoordinatorInviteKind,\n\tCoordinatorJoinRequest,\n\tCoordinatorJoinRequestReviewResult,\n\tCoordinatorListReciprocalApprovalsInput,\n\tCoordinatorListScopeMembershipAuditInput,\n\tCoordinatorListScopesInput,\n\tCoordinatorPeerRecord,\n\tCoordinatorPresenceRecord,\n\tCoordinatorProjectInviteAcceptance,\n\tCoordinatorRecipientInviteAcceptance,\n\tCoordinatorRecipientInviteInspection,\n\tCoordinatorReciprocalApproval,\n\tCoordinatorReviewJoinRequestBootstrapGrantInput,\n\tCoordinatorReviewJoinRequestInput,\n\tCoordinatorRevokeScopeMembershipInput,\n\tCoordinatorScope,\n\tCoordinatorScopeMembership,\n\tCoordinatorScopeMembershipAuditEvent,\n\tCoordinatorStore,\n\tCoordinatorUpdateScopeInput,\n\tCoordinatorUpsertPresenceInput,\n} from \"./coordinator-store-contract.js\";\nimport {\n\tCoordinatorReciprocalApprovalRequestChangedError,\n\tisCoordinatorAssignedIdentityId,\n\tnormalizeInviteExpiresAt,\n\trecipientInviteAuthoritativeIdentityId,\n} from \"./coordinator-store-contract.js\";\nimport {\n\tcanonicalRecipientReviewedIntentJson,\n\tparseStoredRecipientReviewedIntent,\n\ttype RecipientReviewedIntentTargetV1,\n\tverifyRecipientReviewedIntent,\n} from \"./recipient-reviewed-intent.js\";\nimport { fingerprintPublicKey } from \"./sync-fingerprint.js\";\n\ninterface D1RunResultLike {\n\tmeta?: {\n\t\tchanges?: number;\n\t};\n}\n\n/**\n * Experimental D1 adapter scaffold.\n *\n * This is intentionally internal for now while the sync-only store contract\n * is still being validated against an async backend shape.\n */\n\nexport interface D1PreparedStatementLike {\n\tbind(...values: unknown[]): D1PreparedStatementLike;\n\tfirst<T = unknown>(): Promise<T | null>;\n\trun(): Promise<unknown>;\n\tall<T = unknown>(): Promise<{ results?: T[] }>;\n\traw<T = unknown>(): Promise<T[]>;\n}\n\nexport interface D1DatabaseLike {\n\tprepare(query: string): D1PreparedStatementLike;\n\tbatch?(statements: D1PreparedStatementLike[]): Promise<unknown[]>;\n\texec?(query: string): Promise<unknown>;\n}\n\nfunction rowToRecord<T>(row: unknown): T {\n\tif (row == null) throw new Error(\"expected row\");\n\treturn row as T;\n}\n\nfunction rowToEnrollmentWithPresence(row: unknown): CoordinatorEnrollment {\n\tconst record = rowToRecord<Record<string, unknown>>(row);\n\tconst {\n\t\tpresence_capabilities_json: capabilitiesJson,\n\t\tpresence_expires_at: expiresAt,\n\t\t...base\n\t} = record;\n\tif (typeof expiresAt !== \"string\" || typeof capabilitiesJson !== \"string\") {\n\t\treturn base as unknown as CoordinatorEnrollment;\n\t}\n\ttry {\n\t\tconst capabilities = JSON.parse(capabilitiesJson) as unknown;\n\t\tif (!capabilities || typeof capabilities !== \"object\" || Array.isArray(capabilities)) {\n\t\t\treturn base as unknown as CoordinatorEnrollment;\n\t\t}\n\t\tconst capabilityRecord = capabilities as Record<string, unknown>;\n\t\treturn {\n\t\t\t...(base as unknown as CoordinatorEnrollment),\n\t\t\tpresence_expires_at: expiresAt,\n\t\t\tpresence_capabilities: {\n\t\t\t\tsync_capability: capabilityRecord.sync_capability,\n\t\t\t\tsync_features: capabilityRecord.sync_features,\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn base as unknown as CoordinatorEnrollment;\n\t}\n}\n\nfunction normalizeAddress(address: string): string {\n\tconst value = address.trim();\n\tif (!value) return \"\";\n\tconst withScheme = value.includes(\"://\") ? value : `http://${value}`;\n\ttry {\n\t\tconst url = new URL(withScheme);\n\t\tif (!url.hostname) return \"\";\n\t\tif (url.port && (Number(url.port) <= 0 || Number(url.port) > 65535)) return \"\";\n\t\treturn url.origin + url.pathname.replace(/\\/+$/, \"\");\n\t} catch {\n\t\treturn \"\";\n\t}\n}\n\nfunction addressDedupeKey(address: string): string {\n\tif (!address) return \"\";\n\ttry {\n\t\tconst parsed = new URL(address);\n\t\tconst host = parsed.hostname.toLowerCase();\n\t\tif (\n\t\t\t(parsed.protocol === \"http:\" || parsed.protocol === \"\") &&\n\t\t\thost &&\n\t\t\tparsed.port &&\n\t\t\tparsed.pathname === \"/\"\n\t\t) {\n\t\t\treturn `${host}:${parsed.port}`;\n\t\t}\n\t} catch {}\n\treturn address;\n}\n\nfunction mergeAddresses(existing: string[], candidates: string[]): string[] {\n\tconst normalized: string[] = [];\n\tconst seen = new Set<string>();\n\tfor (const address of [...existing, ...candidates]) {\n\t\tconst cleaned = normalizeAddress(address);\n\t\tconst key = addressDedupeKey(cleaned);\n\t\tif (!cleaned || seen.has(key)) continue;\n\t\tseen.add(key);\n\t\tnormalized.push(cleaned);\n\t}\n\treturn normalized;\n}\n\nfunction nowISO(): string {\n\treturn new Date().toISOString();\n}\n\nfunction reciprocalPendingPair(\n\trequestingDeviceId: string,\n\trequestedDeviceId: string,\n): {\n\tlow: string;\n\thigh: string;\n} {\n\treturn requestingDeviceId <= requestedDeviceId\n\t\t? { low: requestingDeviceId, high: requestedDeviceId }\n\t\t: { low: requestedDeviceId, high: requestingDeviceId };\n}\n\nfunction isUniqueConstraintError(error: unknown): boolean {\n\treturn error instanceof Error && /unique|constraint/i.test(error.message);\n}\n\nfunction tokenUrlSafe(bytes: number): string {\n\tconst alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\n\tconst random = new Uint8Array(bytes);\n\tglobalThis.crypto.getRandomValues(random);\n\tconst output: string[] = [];\n\tfor (const byte of random) {\n\t\toutput.push(alphabet[byte % alphabet.length] ?? \"A\");\n\t}\n\treturn output.join(\"\");\n}\n\nasync function tokenDigest(token: string): Promise<string> {\n\tconst digest = await globalThis.crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(token));\n\treturn Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nconst INVITE_COLUMNS = `invite_id, group_id, token, policy, expires_at, created_at, created_by,\n\tteam_name_snapshot, revoked_at, operation_id, reviewed_project_set_digest, token_digest,\n\tinviter_actor_id, inviter_display_name, inviter_device_id, pending_person_id,\n\tproject_summaries_json, project_intent_json, consumed_at, bound_device_id, bound_public_key, bound_fingerprint,\n\trecipient_actor_id, recipient_display_name, recipient_device_display_name, trust_state,\n\tbootstrap_grant_id, invite_kind, policy_team_id, target_identity_id, assigned_identity_id,\n\treviewed_preview_digest, reviewed_intent_json`;\n\nconst ENROLLMENT_COLUMNS =\n\t\"group_id, device_id, public_key, fingerprint, identity_id, display_name, enabled, created_at\";\n\nconst ENROLLMENT_PRESENCE_COLUMNS = `enrolled_devices.group_id, enrolled_devices.device_id,\n\tenrolled_devices.public_key, enrolled_devices.fingerprint, enrolled_devices.identity_id,\n\tenrolled_devices.display_name, enrolled_devices.enabled, enrolled_devices.created_at,\n\tpresence_records.expires_at AS presence_expires_at,\n\tpresence_records.capabilities_json AS presence_capabilities_json`;\n\nfunction requireTrimmedBootstrapGrantInput(opts: CoordinatorCreateBootstrapGrantInput): {\n\tgroupId: string;\n\tseedDeviceId: string;\n\tworkerDeviceId: string;\n\texpiresAt: string;\n\tcreatedBy: string | null;\n} {\n\tconst groupId = String(opts.groupId ?? \"\").trim();\n\tconst seedDeviceId = String(opts.seedDeviceId ?? \"\").trim();\n\tconst workerDeviceId = String(opts.workerDeviceId ?? \"\").trim();\n\tconst expiresAt = String(opts.expiresAt ?? \"\").trim();\n\tconst createdBy = String(opts.createdBy ?? \"\").trim() || null;\n\tif (!groupId || !seedDeviceId || !workerDeviceId || !expiresAt) {\n\t\tthrow new Error(\"groupId, seedDeviceId, workerDeviceId, and expiresAt are required.\");\n\t}\n\treturn { groupId, seedDeviceId, workerDeviceId, expiresAt, createdBy };\n}\n\nfunction clean(value: string | null | undefined): string | null {\n\tconst trimmed = value?.trim();\n\treturn trimmed ? trimmed : null;\n}\n\nasync function normalizeInviteMetadata(opts: CoordinatorCreateInviteInput): Promise<{\n\tinviteKind: CoordinatorInviteKind;\n\tpolicyTeamId: string | null;\n\ttargetIdentityId: string | null;\n\treviewedPreviewDigest: string | null;\n\treviewedIntentJson: string | null;\n}> {\n\tconst inviteKind =\n\t\topts.inviteKind ?? (clean(opts.operationId) ? \"project_share\" : \"legacy_enrollment\");\n\tconst policyTeamId = clean(opts.policyTeamId);\n\tconst targetIdentityId = clean(opts.targetIdentityId);\n\tconst reviewedPreviewDigest = clean(opts.reviewedPreviewDigest);\n\tif (\n\t\t!([\"legacy_enrollment\", \"project_share\", \"team_member\", \"add_device\"] as const).includes(\n\t\t\tinviteKind,\n\t\t)\n\t) {\n\t\tthrow new Error(\"inviteKind is invalid.\");\n\t}\n\tif (\n\t\t[policyTeamId, targetIdentityId]\n\t\t\t.filter((value): value is string => Boolean(value))\n\t\t\t.some((value) => value.length > 256 || /[\\p{Cc}\\p{Cf}]/u.test(value))\n\t) {\n\t\tthrow new Error(\"recipient invite identifier is invalid.\");\n\t}\n\tif (reviewedPreviewDigest && !/^[a-f0-9]{64}$/u.test(reviewedPreviewDigest)) {\n\t\tthrow new Error(\"reviewedPreviewDigest must be a SHA-256 digest.\");\n\t}\n\tif (inviteKind === \"project_share\") {\n\t\tif (!clean(opts.operationId)) throw new Error(\"project_share invite requires operationId.\");\n\t\tif (policyTeamId || targetIdentityId || reviewedPreviewDigest) {\n\t\t\tthrow new Error(\"recipient invite metadata requires a recipient invite kind.\");\n\t\t}\n\t} else if (inviteKind === \"legacy_enrollment\") {\n\t\tif (clean(opts.operationId))\n\t\t\tthrow new Error(\"legacy_enrollment invite cannot reference an operation.\");\n\t\tif (policyTeamId || targetIdentityId || reviewedPreviewDigest) {\n\t\t\tthrow new Error(\"recipient invite metadata requires a recipient invite kind.\");\n\t\t}\n\t} else if (inviteKind === \"team_member\") {\n\t\tif (!policyTeamId || !reviewedPreviewDigest || targetIdentityId || clean(opts.operationId)) {\n\t\t\tthrow new Error(\"team_member invite metadata is invalid.\");\n\t\t}\n\t} else if (inviteKind === \"add_device\") {\n\t\tif (!targetIdentityId || !reviewedPreviewDigest || policyTeamId || clean(opts.operationId)) {\n\t\t\tthrow new Error(\"add_device invite metadata is invalid.\");\n\t\t}\n\t}\n\tconst reviewedIntentProvided = opts.reviewedIntent !== undefined && opts.reviewedIntent !== null;\n\tif (!reviewedIntentProvided) {\n\t\tif (inviteKind === \"team_member\" || inviteKind === \"add_device\") {\n\t\t\tthrow new Error(\"recipient_invite_review_unavailable\");\n\t\t}\n\t\treturn {\n\t\t\tinviteKind,\n\t\t\tpolicyTeamId,\n\t\t\ttargetIdentityId,\n\t\t\treviewedPreviewDigest,\n\t\t\treviewedIntentJson: null,\n\t\t};\n\t}\n\tlet target: RecipientReviewedIntentTargetV1;\n\tif (inviteKind === \"team_member\" && policyTeamId && reviewedPreviewDigest) {\n\t\ttarget = { kind: \"team_member\", policyTeamId };\n\t} else if (inviteKind === \"add_device\" && targetIdentityId && reviewedPreviewDigest) {\n\t\ttarget = { kind: \"add_device\", targetIdentityId };\n\t} else {\n\t\tthrow new Error(\"recipient invite metadata requires a recipient invite kind.\");\n\t}\n\tawait verifyRecipientReviewedIntent(opts.reviewedIntent, {\n\t\ttarget,\n\t\tdigest: reviewedPreviewDigest,\n\t});\n\treturn {\n\t\tinviteKind,\n\t\tpolicyTeamId,\n\t\ttargetIdentityId,\n\t\treviewedPreviewDigest,\n\t\treviewedIntentJson: canonicalRecipientReviewedIntentJson(opts.reviewedIntent, target),\n\t};\n}\n\nasync function recipientInspection(\n\tinvite: CoordinatorInvite,\n): Promise<CoordinatorRecipientInviteInspection | null> {\n\tif (invite.invite_kind === \"team_member\") {\n\t\tif (\n\t\t\t!invite.policy_team_id ||\n\t\t\t!isCoordinatorAssignedIdentityId(invite.assigned_identity_id) ||\n\t\t\t!invite.reviewed_preview_digest\n\t\t)\n\t\t\tthrow new Error(\"invite_invalid\");\n\t\tconst reviewedIntent = await parseStoredRecipientReviewedIntent(invite.reviewed_intent_json, {\n\t\t\ttarget: { kind: \"team_member\", policyTeamId: invite.policy_team_id },\n\t\t\tdigest: invite.reviewed_preview_digest,\n\t\t});\n\t\treturn {\n\t\t\tkind: \"team_member\",\n\t\t\tinvite,\n\t\t\tpolicy_team_id: invite.policy_team_id,\n\t\t\tassigned_identity_id: invite.assigned_identity_id,\n\t\t\treviewed_preview_digest: invite.reviewed_preview_digest,\n\t\t\treviewed_intent: reviewedIntent,\n\t\t\tbound: Boolean(invite.consumed_at),\n\t\t};\n\t}\n\tif (invite.invite_kind === \"add_device\") {\n\t\tif (!invite.target_identity_id || !invite.reviewed_preview_digest)\n\t\t\tthrow new Error(\"invite_invalid\");\n\t\tconst reviewedIntent = await parseStoredRecipientReviewedIntent(invite.reviewed_intent_json, {\n\t\t\ttarget: { kind: \"add_device\", targetIdentityId: invite.target_identity_id },\n\t\t\tdigest: invite.reviewed_preview_digest,\n\t\t});\n\t\treturn {\n\t\t\tkind: \"add_device\",\n\t\t\tinvite,\n\t\t\ttarget_identity_id: invite.target_identity_id,\n\t\t\treviewed_preview_digest: invite.reviewed_preview_digest,\n\t\t\treviewed_intent: reviewedIntent,\n\t\t\tbound: Boolean(invite.consumed_at),\n\t\t};\n\t}\n\treturn null;\n}\n\nfunction normalizeEpoch(value: number | null | undefined, fallback = 0): number {\n\tif (value == null) return fallback;\n\tif (!Number.isFinite(value) || value < 0)\n\t\tthrow new Error(\"membershipEpoch must be non-negative.\");\n\treturn Math.trunc(value);\n}\n\nfunction normalizeCreateScopeInput(opts: CoordinatorCreateScopeInput) {\n\tconst scopeId = clean(opts.scopeId);\n\tconst label = clean(opts.label);\n\tif (!scopeId || !label) throw new Error(\"scopeId and label are required.\");\n\treturn {\n\t\tscopeId,\n\t\tlabel,\n\t\tkind: clean(opts.kind) ?? \"user\",\n\t\tauthorityType: clean(opts.authorityType) ?? \"coordinator\",\n\t\tcoordinatorId: clean(opts.coordinatorId),\n\t\tgroupId: clean(opts.groupId),\n\t\tmanifestIssuerDeviceId: clean(opts.manifestIssuerDeviceId),\n\t\tmembershipEpoch: normalizeEpoch(opts.membershipEpoch),\n\t\tmanifestHash: clean(opts.manifestHash),\n\t\tstatus: clean(opts.status) ?? \"active\",\n\t};\n}\n\nfunction cleanRequiredUpdate(\n\tvalue: string | null | undefined,\n\tcurrent: string,\n\tfieldName: string,\n): string {\n\tif (value === undefined) return current;\n\tconst cleaned = clean(value);\n\tif (!cleaned) throw new Error(`${fieldName} must not be empty.`);\n\treturn cleaned;\n}\n\nfunction cleanNullableUpdate(\n\tvalue: string | null | undefined,\n\tcurrent: string | null,\n): string | null {\n\treturn value === undefined ? current : clean(value);\n}\n\nfunction normalizeUpdateScopeInput(opts: CoordinatorUpdateScopeInput, existing: CoordinatorScope) {\n\tconst scopeId = clean(opts.scopeId);\n\tif (!scopeId) throw new Error(\"scopeId is required.\");\n\tconst requestedEpoch = opts.membershipEpoch == null ? null : normalizeEpoch(opts.membershipEpoch);\n\tif (requestedEpoch != null && requestedEpoch < existing.membership_epoch) {\n\t\tthrow new Error(\"membershipEpoch must not move backwards.\");\n\t}\n\treturn {\n\t\tscopeId,\n\t\tlabel: cleanRequiredUpdate(opts.label, existing.label, \"label\"),\n\t\tkind: cleanRequiredUpdate(opts.kind, existing.kind, \"kind\"),\n\t\tauthorityType: cleanRequiredUpdate(\n\t\t\topts.authorityType,\n\t\t\texisting.authority_type,\n\t\t\t\"authorityType\",\n\t\t),\n\t\tcoordinatorId: cleanNullableUpdate(opts.coordinatorId, existing.coordinator_id),\n\t\tgroupId: cleanNullableUpdate(opts.groupId, existing.group_id),\n\t\tmanifestIssuerDeviceId: cleanNullableUpdate(\n\t\t\topts.manifestIssuerDeviceId,\n\t\t\texisting.manifest_issuer_device_id,\n\t\t),\n\t\tmembershipEpoch: requestedEpoch ?? existing.membership_epoch,\n\t\tmanifestHash: cleanNullableUpdate(opts.manifestHash, existing.manifest_hash),\n\t\tstatus: cleanRequiredUpdate(opts.status, existing.status, \"status\"),\n\t};\n}\n\nfunction normalizeGrantInput(\n\topts: CoordinatorGrantScopeMembershipInput,\n\tscope: CoordinatorScope | null,\n\texisting: CoordinatorScopeMembership | null,\n) {\n\tconst scopeId = clean(opts.scopeId);\n\tconst deviceId = clean(opts.deviceId);\n\tif (!scopeId || !deviceId) throw new Error(\"scopeId and deviceId are required.\");\n\tconst coordinatorId = clean(opts.coordinatorId);\n\tconst groupId = clean(opts.groupId);\n\tif (coordinatorId && coordinatorId !== scope?.coordinator_id) {\n\t\tthrow new Error(\"membership coordinatorId must match the scope coordinatorId.\");\n\t}\n\tif (groupId && groupId !== scope?.group_id) {\n\t\tthrow new CoordinatorMembershipError(\"scope_group_mismatch\");\n\t}\n\tconst requestedEpoch = opts.membershipEpoch == null ? null : normalizeEpoch(opts.membershipEpoch);\n\tconst inheritedEpoch = scope?.membership_epoch ?? 0;\n\tif (requestedEpoch != null && requestedEpoch < inheritedEpoch) {\n\t\tthrow new Error(\"membershipEpoch must not be lower than the scope membershipEpoch.\");\n\t}\n\tif (requestedEpoch != null && existing) {\n\t\tconst minimumEpoch =\n\t\t\texisting.status === \"revoked\" ? existing.membership_epoch + 1 : existing.membership_epoch;\n\t\tif (requestedEpoch < minimumEpoch) {\n\t\t\tthrow new Error(\"membershipEpoch must not move backwards.\");\n\t\t}\n\t}\n\tconst membershipEpoch =\n\t\trequestedEpoch ??\n\t\t(existing\n\t\t\t? Math.max(\n\t\t\t\t\tinheritedEpoch,\n\t\t\t\t\texisting.membership_epoch + (existing.status === \"revoked\" ? 1 : 0),\n\t\t\t\t)\n\t\t\t: inheritedEpoch);\n\treturn {\n\t\tscopeId,\n\t\tdeviceId,\n\t\trole: clean(opts.role) ?? \"member\",\n\t\tmembershipEpoch,\n\t\tcoordinatorId: scope?.coordinator_id ?? null,\n\t\tgroupId: scope?.group_id ?? null,\n\t\tmanifestIssuerDeviceId:\n\t\t\tclean(opts.manifestIssuerDeviceId) ?? scope?.manifest_issuer_device_id ?? null,\n\t\tmanifestHash: clean(opts.manifestHash) ?? scope?.manifest_hash ?? null,\n\t\tsignedManifestJson: clean(opts.signedManifestJson),\n\t\tactorType: clean(opts.actorType),\n\t\tactorId: clean(opts.actorId),\n\t};\n}\n\nfunction normalizeAuditLimit(limit: number | null | undefined): number {\n\tif (limit == null) return 100;\n\tif (!Number.isFinite(limit)) return 100;\n\treturn Math.max(1, Math.min(1000, Math.trunc(limit)));\n}\n\nfunction prepareMembershipAuditFromCurrentRow(\n\tdb: D1DatabaseLike,\n\tinput: {\n\t\teffectId: string;\n\t\trequestJson: string;\n\t\taction: \"grant\" | \"revoke\";\n\t\tprevious: CoordinatorScopeMembership | null;\n\t\tscopeId: string;\n\t\tdeviceId: string;\n\t\tstatus: string;\n\t\tmembershipEpoch: number;\n\t\tupdatedAt: string;\n\t\tactorType: string | null;\n\t\tactorId: string | null;\n\t\tcreatedAt: string;\n\t},\n): D1PreparedStatementLike {\n\t// The immediately preceding statement inserts the immutable effect receipt.\n\t// changes() therefore emits an audit row only for the request that won the\n\t// receipt insert, while outcome_applied excludes persisted no-op revokes.\n\treturn db\n\t\t.prepare(`INSERT INTO coordinator_scope_membership_audit_log(\n\t\t\teffect_id, action, scope_id, device_id, role, status, membership_epoch,\n\t\t\tprevious_role, previous_status, previous_membership_epoch,\n\t\t\tcoordinator_id, group_id, actor_type, actor_id, manifest_hash, created_at\n\t\t)\n\t\tSELECT receipt.effect_id, ?, membership.scope_id, membership.device_id, membership.role, membership.status,\n\t\t\tmembership.membership_epoch, ?, ?, ?, membership.coordinator_id, membership.group_id,\n\t\t\t?, ?, membership.manifest_hash, ?\n\t\tFROM (SELECT 1 WHERE changes() > 0) AS required\n\t\tJOIN coordinator_scope_membership_effect_receipts AS receipt\n\t\t\tON receipt.effect_id = ? AND receipt.action = ? AND receipt.request_json = ?\n\t\t\tAND receipt.outcome_applied = 1\n\t\tLEFT JOIN coordinator_scope_memberships AS membership\n\t\t\tON membership.scope_id = ?\n\t\t\tAND membership.device_id = ?\n\t\t\tAND membership.status = ?\n\t\t\tAND membership.membership_epoch = ?\n\t\t\tAND membership.updated_at = ?`)\n\t\t.bind(\n\t\t\tinput.action,\n\t\t\tinput.previous?.role ?? null,\n\t\t\tinput.previous?.status ?? null,\n\t\t\tinput.previous?.membership_epoch ?? null,\n\t\t\tinput.actorType,\n\t\t\tinput.actorId,\n\t\t\tinput.createdAt,\n\t\t\tinput.effectId,\n\t\t\tinput.action,\n\t\t\tinput.requestJson,\n\t\t\tinput.scopeId,\n\t\t\tinput.deviceId,\n\t\t\tinput.status,\n\t\t\tinput.membershipEpoch,\n\t\t\tinput.updatedAt,\n\t\t);\n}\n\nasync function getMembershipEffectReceipt(\n\tdb: D1DatabaseLike,\n\teffectId: string,\n): Promise<CoordinatorMembershipEffectReceipt | null> {\n\treturn await firstRow<CoordinatorMembershipEffectReceipt>(\n\t\tdb\n\t\t\t.prepare(`SELECT effect_id, action, request_json, outcome_applied, scope_id, device_id,\n\t\t\t\trole, status, membership_epoch, coordinator_id, group_id, manifest_issuer_device_id,\n\t\t\t\tmanifest_hash, signed_manifest_json, updated_at, created_at\n\t\t\t FROM coordinator_scope_membership_effect_receipts WHERE effect_id = ?`)\n\t\t\t.bind(effectId),\n\t);\n}\n\nfunction prepareGrantEffectReceipt(\n\tdb: D1DatabaseLike,\n\tinput: {\n\t\teffectId: string;\n\t\trequestJson: string;\n\t\tscopeId: string;\n\t\tdeviceId: string;\n\t\tcreatedAt: string;\n\t},\n): D1PreparedStatementLike {\n\treturn db\n\t\t.prepare(`INSERT INTO coordinator_scope_membership_effect_receipts(\n\t\t\teffect_id, action, request_json, outcome_applied, scope_id, device_id,\n\t\t\trole, status, membership_epoch, coordinator_id, group_id, manifest_issuer_device_id,\n\t\t\tmanifest_hash, signed_manifest_json, updated_at, created_at\n\t\t)\n\t\tSELECT ?, 'grant', ?, 1, membership.scope_id, membership.device_id,\n\t\t\tmembership.role, membership.status, membership.membership_epoch,\n\t\t\tmembership.coordinator_id, membership.group_id, membership.manifest_issuer_device_id,\n\t\t\tmembership.manifest_hash, membership.signed_manifest_json, membership.updated_at, ?\n\t\tFROM coordinator_scope_memberships AS membership\n\t\tWHERE changes() > 0 AND membership.scope_id = ? AND membership.device_id = ?`)\n\t\t.bind(input.effectId, input.requestJson, input.createdAt, input.scopeId, input.deviceId);\n}\n\nfunction prepareRevokeEffectReceipt(\n\tdb: D1DatabaseLike,\n\tinput: {\n\t\teffectId: string;\n\t\trequestJson: string;\n\t\tscopeId: string;\n\t\tdeviceId: string;\n\t\tcreatedAt: string;\n\t},\n): D1PreparedStatementLike {\n\treturn db\n\t\t.prepare(`INSERT INTO coordinator_scope_membership_effect_receipts(\n\t\t\teffect_id, action, request_json, outcome_applied, scope_id, device_id,\n\t\t\trole, status, membership_epoch, coordinator_id, group_id, manifest_issuer_device_id,\n\t\t\tmanifest_hash, signed_manifest_json, updated_at, created_at\n\t\t)\n\t\tSELECT ?, 'revoke', ?, changed.applied, ?, ?, membership.role, membership.status,\n\t\t\tmembership.membership_epoch, membership.coordinator_id, membership.group_id,\n\t\t\tmembership.manifest_issuer_device_id, membership.manifest_hash,\n\t\t\tmembership.signed_manifest_json, membership.updated_at, ?\n\t\tFROM (SELECT CASE WHEN changes() > 0 THEN 1 ELSE 0 END AS applied) AS changed\n\t\tLEFT JOIN coordinator_scope_memberships AS membership\n\t\t\tON changed.applied = 1 AND membership.scope_id = ? AND membership.device_id = ?\n\t\tWHERE NOT EXISTS (\n\t\t\tSELECT 1 FROM coordinator_scope_membership_effect_receipts WHERE effect_id = ?\n\t\t)`)\n\t\t.bind(\n\t\t\tinput.effectId,\n\t\t\tinput.requestJson,\n\t\t\tinput.scopeId,\n\t\t\tinput.deviceId,\n\t\t\tinput.createdAt,\n\t\t\tinput.scopeId,\n\t\t\tinput.deviceId,\n\t\t\tinput.effectId,\n\t\t);\n}\n\nasync function runAuditedBatch(\n\tdb: D1DatabaseLike,\n\tstatements: D1PreparedStatementLike[],\n): Promise<unknown[]> {\n\tif (!db.batch) {\n\t\tthrow new Error(\"D1 batch support is required for audited scope membership changes.\");\n\t}\n\treturn await db.batch(statements);\n}\n\nfunction batchResultChanges(result: unknown): number {\n\treturn Number((result as D1RunResultLike | undefined)?.meta?.changes ?? 0);\n}\n\nfunction normalizeBootstrapGrantRequest(\n\tinput: CoordinatorReviewJoinRequestBootstrapGrantInput | null | undefined,\n): CoordinatorCreateBootstrapGrantInput | null {\n\tif (!input) return null;\n\tconst seedDeviceId = String(input.seedDeviceId ?? \"\").trim();\n\tconst expiresAt = String(input.expiresAt ?? \"\").trim();\n\tconst createdBy = String(input.createdBy ?? \"\").trim() || null;\n\tif (!seedDeviceId || !expiresAt) {\n\t\tthrow new Error(\"bootstrapGrant.seedDeviceId and expiresAt are required.\");\n\t}\n\treturn {\n\t\tgroupId: \"\",\n\t\tseedDeviceId,\n\t\tworkerDeviceId: \"\",\n\t\texpiresAt,\n\t\tcreatedBy,\n\t};\n}\n\nasync function allRows<T>(statement: D1PreparedStatementLike): Promise<T[]> {\n\tconst result = await statement.all<T>();\n\treturn Array.isArray(result?.results) ? result.results : [];\n}\n\nasync function firstRow<T>(statement: D1PreparedStatementLike): Promise<T | null> {\n\treturn await statement.first<T>();\n}\n\nasync function runChanges(statement: D1PreparedStatementLike): Promise<number> {\n\tconst result = (await statement.run()) as D1RunResultLike | undefined;\n\treturn Number(result?.meta?.changes ?? 0);\n}\n\nexport class D1CoordinatorStore implements CoordinatorStore {\n\treadonly db: D1DatabaseLike;\n\n\tconstructor(db: D1DatabaseLike) {\n\t\tthis.db = db;\n\t}\n\n\tasync close(): Promise<void> {\n\t\t// No-op for D1 bindings.\n\t}\n\n\tasync createGroup(_groupId: string, _displayName?: string | null): Promise<void> {\n\t\tawait this.db\n\t\t\t.prepare(\n\t\t\t\t\"INSERT OR IGNORE INTO groups(group_id, display_name, archived_at, created_at) VALUES (?, ?, NULL, ?)\",\n\t\t\t)\n\t\t\t.bind(_groupId, _displayName ?? null, nowISO())\n\t\t\t.run();\n\t}\n\n\tasync getGroup(_groupId: string): Promise<CoordinatorGroup | null> {\n\t\tconst row = await firstRow<CoordinatorGroup>(\n\t\t\tthis.db\n\t\t\t\t.prepare(\n\t\t\t\t\t\"SELECT group_id, display_name, archived_at, created_at FROM groups WHERE group_id = ?\",\n\t\t\t\t)\n\t\t\t\t.bind(_groupId),\n\t\t);\n\t\treturn row ? rowToRecord<CoordinatorGroup>(row) : null;\n\t}\n\n\tasync listGroups(_includeArchived = false): Promise<CoordinatorGroup[]> {\n\t\tconst where = _includeArchived ? \"\" : \"WHERE archived_at IS NULL\";\n\t\treturn (\n\t\t\tawait allRows<CoordinatorGroup>(\n\t\t\t\tthis.db.prepare(\n\t\t\t\t\t`SELECT group_id, display_name, archived_at, created_at FROM groups ${where} ORDER BY created_at ASC`,\n\t\t\t\t),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorGroup>(row));\n\t}\n\n\tasync renameGroup(_groupId: string, _displayName: string): Promise<boolean> {\n\t\treturn (\n\t\t\t(await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(\"UPDATE groups SET display_name = ? WHERE group_id = ?\")\n\t\t\t\t\t.bind(_displayName, _groupId),\n\t\t\t)) > 0\n\t\t);\n\t}\n\n\tasync archiveGroup(_groupId: string, _archivedAt = nowISO()): Promise<boolean> {\n\t\treturn (\n\t\t\t(await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(\"UPDATE groups SET archived_at = ? WHERE group_id = ? AND archived_at IS NULL\")\n\t\t\t\t\t.bind(_archivedAt, _groupId),\n\t\t\t)) > 0\n\t\t);\n\t}\n\n\tasync unarchiveGroup(_groupId: string): Promise<boolean> {\n\t\treturn (\n\t\t\t(await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\"UPDATE groups SET archived_at = NULL WHERE group_id = ? AND archived_at IS NOT NULL\",\n\t\t\t\t\t)\n\t\t\t\t\t.bind(_groupId),\n\t\t\t)) > 0\n\t\t);\n\t}\n\n\tasync enrollDevice(_groupId: string, _opts: CoordinatorEnrollDeviceInput): Promise<void> {\n\t\tconst changes = await runChanges(\n\t\t\tthis.db\n\t\t\t\t.prepare(`INSERT INTO enrolled_devices(\n\t\t\t\t\tgroup_id, device_id, public_key, fingerprint, identity_id, display_name, enabled, created_at\n\t\t\t\t) VALUES (?, ?, ?, ?, ?, ?, 1, ?)\n\t\t\t\tON CONFLICT(group_id, device_id) DO UPDATE SET\n\t\t\t\t\tpublic_key = excluded.public_key,\n\t\t\t\t\tfingerprint = excluded.fingerprint,\n\t\t\t\t\tidentity_id = COALESCE(enrolled_devices.identity_id, excluded.identity_id),\n\t\t\t\t\tdisplay_name = excluded.display_name,\n\t\t\t\t\tenabled = 1\n\t\t\t\tWHERE excluded.identity_id IS NULL\n\t\t\t\t\tOR enrolled_devices.identity_id IS NULL\n\t\t\t\t\tOR enrolled_devices.identity_id = excluded.identity_id`)\n\t\t\t\t.bind(\n\t\t\t\t\t_groupId,\n\t\t\t\t\t_opts.deviceId,\n\t\t\t\t\t_opts.publicKey,\n\t\t\t\t\t_opts.fingerprint,\n\t\t\t\t\t_opts.identityId ?? null,\n\t\t\t\t\t_opts.displayName ?? null,\n\t\t\t\t\tnowISO(),\n\t\t\t\t),\n\t\t);\n\t\tif (changes === 0) throw new Error(\"invite_identity_conflict\");\n\t}\n\n\tasync listEnrolledDevices(\n\t\t_groupId: string,\n\t\t_includeDisabled?: boolean,\n\t): Promise<CoordinatorEnrollment[]> {\n\t\tconst where = _includeDisabled ? \"\" : \"AND enrolled_devices.enabled = 1\";\n\t\treturn (\n\t\t\tawait allRows<CoordinatorEnrollment>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT ${ENROLLMENT_PRESENCE_COLUMNS}\n\t\t\t\t\t\t FROM enrolled_devices\n\t\t\t\t\t\t LEFT JOIN presence_records\n\t\t\t\t\t\t ON presence_records.group_id = enrolled_devices.group_id\n\t\t\t\t\t\t AND presence_records.device_id = enrolled_devices.device_id\n\t\t\t\t\t\t WHERE enrolled_devices.group_id = ? ${where}\n\t\t\t\t\t\t ORDER BY enrolled_devices.created_at ASC, enrolled_devices.device_id ASC`)\n\t\t\t\t\t.bind(_groupId),\n\t\t\t)\n\t\t).map(rowToEnrollmentWithPresence);\n\t}\n\n\tasync getEnrollment(\n\t\t_groupId: string,\n\t\t_deviceId: string,\n\t\t_includeDisabled = false,\n\t): Promise<CoordinatorEnrollment | null> {\n\t\tconst enabledClause = _includeDisabled ? \"\" : \"AND enabled = 1\";\n\t\tconst row = await firstRow<CoordinatorEnrollment>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n\t\t\t\t\t FROM enrolled_devices\n\t\t\t\t\t WHERE group_id = ? AND device_id = ? ${enabledClause}`)\n\t\t\t\t.bind(_groupId, _deviceId),\n\t\t);\n\t\treturn row ? rowToRecord<CoordinatorEnrollment>(row) : null;\n\t}\n\n\tasync renameDevice(_groupId: string, _deviceId: string, _displayName: string): Promise<boolean> {\n\t\treturn (\n\t\t\t(await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE enrolled_devices SET display_name = ?\n\t\t\t\t\t WHERE group_id = ? AND device_id = ?`)\n\t\t\t\t\t.bind(_displayName, _groupId, _deviceId),\n\t\t\t)) > 0\n\t\t);\n\t}\n\n\tasync setDeviceEnabled(_groupId: string, _deviceId: string, _enabled: boolean): Promise<boolean> {\n\t\treturn (\n\t\t\t(await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE enrolled_devices SET enabled = ?\n\t\t\t\t\t WHERE group_id = ? AND device_id = ?`)\n\t\t\t\t\t.bind(_enabled ? 1 : 0, _groupId, _deviceId),\n\t\t\t)) > 0\n\t\t);\n\t}\n\n\tasync removeDevice(_groupId: string, _deviceId: string): Promise<boolean> {\n\t\t// Presence, reciprocal approvals, and the enrollment row must be removed\n\t\t// all-or-nothing. Running them as independent statements can orphan rows\n\t\t// (an enrolled device with no presence/approvals, or vice versa) if any\n\t\t// one statement fails. D1 batch() is the transaction boundary here, the\n\t\t// same convention used for audited membership changes via runAuditedBatch.\n\t\tif (!this.db.batch) {\n\t\t\tthrow new Error(\"D1 batch support is required for atomic device removal.\");\n\t\t}\n\t\tconst results = await this.db.batch([\n\t\t\tthis.db\n\t\t\t\t.prepare(\"DELETE FROM presence_records WHERE group_id = ? AND device_id = ?\")\n\t\t\t\t.bind(_groupId, _deviceId),\n\t\t\tthis.db\n\t\t\t\t.prepare(\n\t\t\t\t\t\"DELETE FROM coordinator_reciprocal_approvals WHERE group_id = ? AND (requesting_device_id = ? OR requested_device_id = ?)\",\n\t\t\t\t)\n\t\t\t\t.bind(_groupId, _deviceId, _deviceId),\n\t\t\tthis.db\n\t\t\t\t.prepare(\"DELETE FROM enrolled_devices WHERE group_id = ? AND device_id = ?\")\n\t\t\t\t.bind(_groupId, _deviceId),\n\t\t]);\n\t\t// The enrolled_devices delete is the last statement; its changes() tells us\n\t\t// whether the device existed, preserving the boolean return contract.\n\t\treturn batchResultChanges(results[2]) > 0;\n\t}\n\n\tasync recordNonce(_deviceId: string, _nonce: string, _createdAt: string): Promise<boolean> {\n\t\treturn (\n\t\t\t(await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\"INSERT OR IGNORE INTO request_nonces(device_id, nonce, created_at) VALUES (?, ?, ?)\",\n\t\t\t\t\t)\n\t\t\t\t\t.bind(_deviceId, _nonce, _createdAt),\n\t\t\t)) > 0\n\t\t);\n\t}\n\n\tasync cleanupNonces(_cutoff: string): Promise<void> {\n\t\tawait this.db.prepare(\"DELETE FROM request_nonces WHERE created_at < ?\").bind(_cutoff).run();\n\t}\n\n\tasync createInvite(_opts: CoordinatorCreateInviteInput): Promise<CoordinatorInvite> {\n\t\tconst now = nowISO();\n\t\tconst inviteId = tokenUrlSafe(12);\n\t\tconst token = tokenUrlSafe(24);\n\t\tconst digest = await tokenDigest(token);\n\t\tconst expiresAt = normalizeInviteExpiresAt(_opts.expiresAt);\n\t\tconst group = await this.getGroup(_opts.groupId);\n\t\tconst operationId = String(_opts.operationId ?? \"\").trim() || null;\n\t\tconst reviewedProjectSetDigest = String(_opts.reviewedProjectSetDigest ?? \"\").trim() || null;\n\t\tconst metadata = await normalizeInviteMetadata(_opts);\n\t\tconst assignedIdentityId =\n\t\t\tmetadata.inviteKind === \"team_member\" ? `identity:${tokenUrlSafe(18)}` : null;\n\t\tif (Boolean(operationId) !== Boolean(reviewedProjectSetDigest)) {\n\t\t\tthrow new Error(\"operationId and reviewedProjectSetDigest must be provided together.\");\n\t\t}\n\t\tconst readOperationInvite = async (): Promise<CoordinatorInvite | null> => {\n\t\t\tif (!operationId) return null;\n\t\t\tconst existing = await firstRow<CoordinatorInvite>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE operation_id = ?`)\n\t\t\t\t\t.bind(operationId),\n\t\t\t);\n\t\t\tif (!existing) return null;\n\t\t\t// Pre-consume create retries can recover the bearer token. Successful\n\t\t\t// consume clears it, so post-consume create retries fail closed.\n\t\t\tif (existing.consumed_at) throw new Error(\"invite_already_bound\");\n\t\t\tif (\n\t\t\t\texisting.group_id !== _opts.groupId ||\n\t\t\t\texisting.policy !== _opts.policy ||\n\t\t\t\texisting.invite_kind !== metadata.inviteKind ||\n\t\t\t\texisting.reviewed_project_set_digest !== reviewedProjectSetDigest ||\n\t\t\t\texisting.inviter_actor_id !== (String(_opts.inviterActorId ?? \"\").trim() || null) ||\n\t\t\t\texisting.inviter_display_name !== (String(_opts.inviterDisplayName ?? \"\").trim() || null) ||\n\t\t\t\texisting.inviter_device_id !== (String(_opts.inviterDeviceId ?? \"\").trim() || null) ||\n\t\t\t\texisting.pending_person_id !== (String(_opts.pendingPersonId ?? \"\").trim() || null) ||\n\t\t\t\texisting.project_summaries_json !==\n\t\t\t\t\t(_opts.projectSummaries ? JSON.stringify(_opts.projectSummaries) : null) ||\n\t\t\t\texisting.project_intent_json !==\n\t\t\t\t\t(_opts.projectIntent ? JSON.stringify(_opts.projectIntent) : null) ||\n\t\t\t\texisting.policy_team_id !== metadata.policyTeamId ||\n\t\t\t\texisting.target_identity_id !== metadata.targetIdentityId ||\n\t\t\t\texisting.reviewed_preview_digest !== metadata.reviewedPreviewDigest ||\n\t\t\t\texisting.reviewed_intent_json !== metadata.reviewedIntentJson\n\t\t\t) {\n\t\t\t\tthrow new Error(\"invite_operation_intent_conflict\");\n\t\t\t}\n\t\t\treturn rowToRecord<CoordinatorInvite>(existing);\n\t\t};\n\t\tconst renewOperationInvite = async (\n\t\t\texisting: CoordinatorInvite,\n\t\t): Promise<CoordinatorInvite> => {\n\t\t\tif (!existing.revoked_at && existing.expires_at > now) return existing;\n\t\t\tawait runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_invites\n\t\t\t\t\t\tSET token = ?, token_digest = ?, expires_at = ?, created_at = ?, created_by = ?,\n\t\t\t\t\t\t\tteam_name_snapshot = ?, revoked_at = NULL\n\t\t\t\t\t\tWHERE operation_id = ? AND token = ?\n\t\t\t\t\t\t AND (revoked_at IS NOT NULL OR expires_at <= ?)`)\n\t\t\t\t\t.bind(\n\t\t\t\t\t\ttoken,\n\t\t\t\t\t\tdigest,\n\t\t\t\t\t\texpiresAt,\n\t\t\t\t\t\tnow,\n\t\t\t\t\t\t_opts.createdBy ?? null,\n\t\t\t\t\t\tgroup?.display_name ?? null,\n\t\t\t\t\t\toperationId,\n\t\t\t\t\t\texisting.token,\n\t\t\t\t\t\tnow,\n\t\t\t\t\t),\n\t\t\t);\n\t\t\tconst renewed = await readOperationInvite();\n\t\t\tif (!renewed) throw new Error(\"invite_operation_reissue_failed\");\n\t\t\treturn renewed;\n\t\t};\n\t\tif (operationId) {\n\t\t\tconst existing = await readOperationInvite();\n\t\t\tif (existing) return await renewOperationInvite(existing);\n\t\t}\n\t\ttry {\n\t\t\tawait this.db\n\t\t\t\t.prepare(`INSERT INTO coordinator_invites(\n\t\t\t\tinvite_id, group_id, token, policy, expires_at, created_at, created_by,\n\t\t\t\tteam_name_snapshot, revoked_at, operation_id, reviewed_project_set_digest,\n\t\t\t\ttoken_digest, inviter_actor_id, inviter_display_name, inviter_device_id,\n\t\t\t\tpending_person_id, project_summaries_json, project_intent_json, trust_state,\n\t\t\t\tinvite_kind, policy_team_id, target_identity_id, assigned_identity_id,\n\t\t\t\treviewed_preview_digest, reviewed_intent_json\n\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)\n\t\t\t\t.bind(\n\t\t\t\t\tinviteId,\n\t\t\t\t\t_opts.groupId,\n\t\t\t\t\ttoken,\n\t\t\t\t\t_opts.policy,\n\t\t\t\t\texpiresAt,\n\t\t\t\t\tnow,\n\t\t\t\t\t_opts.createdBy ?? null,\n\t\t\t\t\tgroup?.display_name ?? null,\n\t\t\t\t\toperationId,\n\t\t\t\t\treviewedProjectSetDigest,\n\t\t\t\t\tdigest,\n\t\t\t\t\tString(_opts.inviterActorId ?? \"\").trim() || null,\n\t\t\t\t\tString(_opts.inviterDisplayName ?? \"\").trim() || null,\n\t\t\t\t\tString(_opts.inviterDeviceId ?? \"\").trim() || null,\n\t\t\t\t\tString(_opts.pendingPersonId ?? \"\").trim() || null,\n\t\t\t\t\t_opts.projectSummaries ? JSON.stringify(_opts.projectSummaries) : null,\n\t\t\t\t\t_opts.projectIntent ? JSON.stringify(_opts.projectIntent) : null,\n\t\t\t\t\toperationId ? \"pending\" : null,\n\t\t\t\t\tmetadata.inviteKind,\n\t\t\t\t\tmetadata.policyTeamId,\n\t\t\t\t\tmetadata.targetIdentityId,\n\t\t\t\t\tassignedIdentityId,\n\t\t\t\t\tmetadata.reviewedPreviewDigest,\n\t\t\t\t\tmetadata.reviewedIntentJson,\n\t\t\t\t)\n\t\t\t\t.run();\n\t\t} catch (error) {\n\t\t\tif (operationId) {\n\t\t\t\tconst existing = await readOperationInvite();\n\t\t\t\tif (existing) return await renewOperationInvite(existing);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tconst row = await firstRow<CoordinatorInvite>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE invite_id = ?`)\n\t\t\t\t.bind(inviteId),\n\t\t);\n\t\treturn rowToRecord<CoordinatorInvite>(row);\n\t}\n\n\tasync getInviteByToken(_token: string): Promise<CoordinatorInvite | null> {\n\t\tconst digest = await tokenDigest(_token);\n\t\tconst row = await firstRow<CoordinatorInvite>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT ${INVITE_COLUMNS}\n\t\t\t\t\t FROM coordinator_invites\n\t\t\t\t\t WHERE (token_digest = ? OR token = ?)\n\t\t\t\t\t AND revoked_at IS NULL\n\t\t\t\t\t AND expires_at > ?`)\n\t\t\t\t.bind(digest, _token, nowISO()),\n\t\t);\n\t\treturn row ? rowToRecord<CoordinatorInvite>(row) : null;\n\t}\n\n\tasync getInviteByTokenForInspection(_token: string): Promise<CoordinatorInvite | null> {\n\t\tconst digest = await tokenDigest(_token);\n\t\tconst row = await firstRow<CoordinatorInvite>(\n\t\t\tthis.db\n\t\t\t\t.prepare(\n\t\t\t\t\t`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE token_digest = ? OR token = ?`,\n\t\t\t\t)\n\t\t\t\t.bind(digest, _token),\n\t\t);\n\t\treturn row ? rowToRecord<CoordinatorInvite>(row) : null;\n\t}\n\n\tasync inspectRecipientInvite(\n\t\t_opts: CoordinatorInspectRecipientInviteInput,\n\t): Promise<CoordinatorRecipientInviteInspection | null> {\n\t\tconst invite = await this.getInviteByTokenForInspection(_opts.token);\n\t\tif (!invite) return null;\n\t\tconst inspection = await recipientInspection(invite);\n\t\tif (!inspection) return null;\n\t\tif (invite.revoked_at) throw new Error(\"invite_invalid\");\n\t\tif (\n\t\t\t!invite.consumed_at &&\n\t\t\tnew Date(invite.expires_at) <= new Date(normalizeInviteExpiresAt(_opts.now))\n\t\t) {\n\t\t\tthrow new Error(\"invite_expired\");\n\t\t}\n\t\tconst group = await this.getGroup(invite.group_id);\n\t\tif (!group) throw new Error(\"group_not_found\");\n\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\treturn inspection;\n\t}\n\n\tasync consumeRecipientInvite(\n\t\t_opts: CoordinatorConsumeRecipientInviteInput,\n\t): Promise<CoordinatorRecipientInviteAcceptance> {\n\t\tconst consumedAt = normalizeInviteExpiresAt(_opts.now);\n\t\tconst recipientDisplayName = _opts.recipientDisplayName ?? null;\n\t\tconst deviceDisplayName = _opts.deviceDisplayName ?? null;\n\t\tif (\n\t\t\t!_opts.identityId ||\n\t\t\t!_opts.deviceId ||\n\t\t\t!_opts.publicKey ||\n\t\t\t!_opts.fingerprint ||\n\t\t\t_opts.identityId !== _opts.identityId.trim() ||\n\t\t\t_opts.deviceId !== _opts.deviceId.trim() ||\n\t\t\t_opts.identityId.length > 256 ||\n\t\t\t_opts.deviceId.length > 256 ||\n\t\t\t/[\\p{Cc}\\p{Cf}]/u.test(_opts.identityId) ||\n\t\t\t/[\\p{Cc}\\p{Cf}]/u.test(_opts.deviceId)\n\t\t) {\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t}\n\t\tconst digest = await tokenDigest(_opts.token);\n\t\tconst initial = await this.getInviteByTokenForInspection(_opts.token);\n\t\tconst inspection = initial ? await recipientInspection(initial) : null;\n\t\tif (!initial || !inspection || inspection.kind !== _opts.inviteKind || initial.revoked_at) {\n\t\t\tthrow new Error(\"invite_invalid\");\n\t\t}\n\t\tconst group = await this.getGroup(initial.group_id);\n\t\tif (!group) throw new Error(\"group_not_found\");\n\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\tif (!initial.consumed_at && new Date(initial.expires_at) <= new Date(consumedAt)) {\n\t\t\tthrow new Error(\"invite_expired\");\n\t\t}\n\t\tif (fingerprintPublicKey(_opts.publicKey) !== _opts.fingerprint) {\n\t\t\tthrow new Error(\"fingerprint_mismatch\");\n\t\t}\n\t\tconst authoritativeIdentityId = recipientInviteAuthoritativeIdentityId(inspection);\n\t\tif (authoritativeIdentityId !== _opts.identityId) {\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t}\n\t\tconst sameBinding =\n\t\t\tinitial.bound_device_id === _opts.deviceId &&\n\t\t\tinitial.bound_public_key === _opts.publicKey &&\n\t\t\tinitial.bound_fingerprint === _opts.fingerprint;\n\t\tif (initial.consumed_at && !sameBinding) throw new Error(\"invite_already_bound\");\n\t\tif (initial.consumed_at && initial.recipient_actor_id !== authoritativeIdentityId) {\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t}\n\t\tconst existingEnrollment = await firstRow<CoordinatorEnrollment>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n\t\t\t\t\tFROM enrolled_devices WHERE group_id = ? AND device_id = ?`)\n\t\t\t\t.bind(initial.group_id, _opts.deviceId),\n\t\t);\n\t\tif (\n\t\t\texistingEnrollment &&\n\t\t\t(existingEnrollment.public_key !== _opts.publicKey ||\n\t\t\t\texistingEnrollment.fingerprint !== _opts.fingerprint ||\n\t\t\t\t(existingEnrollment.identity_id !== null &&\n\t\t\t\t\texistingEnrollment.identity_id !== authoritativeIdentityId))\n\t\t) {\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t}\n\t\tlet changed = 0;\n\t\tconst bootstrapGrantId = tokenUrlSafe(12);\n\t\tif (!initial.consumed_at) {\n\t\t\tif (!this.db.batch)\n\t\t\t\tthrow new Error(\"D1 batch support is required for atomic invite consume.\");\n\t\t\tconst results = await this.db.batch([\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_invites SET token = ?, consumed_at = ?, bound_device_id = ?,\n\t\t\t\t\t\tbound_public_key = ?, bound_fingerprint = ?, recipient_actor_id = ?,\n\t\t\t\t\t\trecipient_display_name = ?, recipient_device_display_name = ?\n\t\t\t\t\t\tWHERE (token_digest = ? OR token = ?) AND consumed_at IS NULL\n\t\t\t\t\t\tAND revoked_at IS NULL AND expires_at > ? AND invite_kind = ?\n\t\t\t\t\t\tAND reviewed_intent_json = ? AND reviewed_preview_digest = ?\n\t\t\t\t\t\tAND ((invite_kind = 'team_member' AND assigned_identity_id = ?)\n\t\t\t\t\t\t\tOR (invite_kind = 'add_device' AND target_identity_id = ?))\n\t\t\t\t\t\tAND NOT EXISTS (\n\t\t\t\t\t\t\tSELECT 1 FROM enrolled_devices e\n\t\t\t\t\t\t\tWHERE e.group_id = coordinator_invites.group_id AND e.device_id = ?\n\t\t\t\t\t\t\t\tAND (e.public_key <> ? OR e.fingerprint <> ?\n\t\t\t\t\t\t\t\t\tOR (e.identity_id IS NOT NULL AND e.identity_id <> ?))\n\t\t\t\t\t\t)\n\t\t\t\t\t\tAND EXISTS (SELECT 1 FROM groups g WHERE g.group_id = coordinator_invites.group_id\n\t\t\t\t\t\t\tAND g.archived_at IS NULL)`)\n\t\t\t\t\t.bind(\n\t\t\t\t\t\t`consumed:${initial.invite_id}`,\n\t\t\t\t\t\tconsumedAt,\n\t\t\t\t\t\t_opts.deviceId,\n\t\t\t\t\t\t_opts.publicKey,\n\t\t\t\t\t\t_opts.fingerprint,\n\t\t\t\t\t\tauthoritativeIdentityId,\n\t\t\t\t\t\trecipientDisplayName,\n\t\t\t\t\t\tdeviceDisplayName,\n\t\t\t\t\t\tdigest,\n\t\t\t\t\t\t_opts.token,\n\t\t\t\t\t\tconsumedAt,\n\t\t\t\t\t\t_opts.inviteKind,\n\t\t\t\t\t\tinitial.reviewed_intent_json,\n\t\t\t\t\t\tinitial.reviewed_preview_digest,\n\t\t\t\t\t\tauthoritativeIdentityId,\n\t\t\t\t\t\tauthoritativeIdentityId,\n\t\t\t\t\t\t_opts.deviceId,\n\t\t\t\t\t\t_opts.publicKey,\n\t\t\t\t\t\t_opts.fingerprint,\n\t\t\t\t\t\tauthoritativeIdentityId,\n\t\t\t\t\t),\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`INSERT INTO enrolled_devices(\n\t\t\t\t\t\tgroup_id, device_id, public_key, fingerprint, identity_id, display_name, enabled, created_at\n\t\t\t\t\t) SELECT i.group_id, i.bound_device_id, i.bound_public_key, i.bound_fingerprint,\n\t\t\t\t\t\ti.recipient_actor_id, i.recipient_device_display_name, 1, ? FROM coordinator_invites i\n\t\t\t\t\tJOIN groups g ON g.group_id = i.group_id AND g.archived_at IS NULL\n\t\t\t\t\tWHERE (i.token_digest = ? OR i.token = ?) AND i.bound_device_id = ?\n\t\t\t\t\t\tAND i.bound_public_key = ? AND i.bound_fingerprint = ?\n\t\t\t\t\t\tAND i.recipient_actor_id = ?\n\t\t\t\t\tON CONFLICT(group_id, device_id) DO UPDATE SET\n\t\t\t\t\t\tidentity_id = COALESCE(enrolled_devices.identity_id, excluded.identity_id),\n\t\t\t\t\t\tdisplay_name = COALESCE(enrolled_devices.display_name, excluded.display_name),\n\t\t\t\t\t\tenabled = 1\n\t\t\t\t\tWHERE enrolled_devices.identity_id IS NULL\n\t\t\t\t\t\tOR enrolled_devices.identity_id = excluded.identity_id`)\n\t\t\t\t\t.bind(\n\t\t\t\t\t\tconsumedAt,\n\t\t\t\t\t\tdigest,\n\t\t\t\t\t\t_opts.token,\n\t\t\t\t\t\t_opts.deviceId,\n\t\t\t\t\t\t_opts.publicKey,\n\t\t\t\t\t\t_opts.fingerprint,\n\t\t\t\t\t\tauthoritativeIdentityId,\n\t\t\t\t\t),\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_invites SET bootstrap_grant_id = ?,\n\t\t\t\t\t\ttrust_state = 'bootstrap_grant_created'\n\t\t\t\t\t\tWHERE (token_digest = ? OR token = ?) AND invite_kind = 'add_device'\n\t\t\t\t\t\tAND bootstrap_grant_id IS NULL AND inviter_device_id IS NOT NULL\n\t\t\t\t\t\tAND expires_at > ?\n\t\t\t\t\t\tAND EXISTS (SELECT 1 FROM enrolled_devices e\n\t\t\t\t\t\t\tWHERE e.group_id = coordinator_invites.group_id\n\t\t\t\t\t\t\tAND e.device_id = coordinator_invites.inviter_device_id AND e.enabled = 1)`)\n\t\t\t\t\t.bind(bootstrapGrantId, digest, _opts.token, consumedAt),\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`INSERT OR IGNORE INTO coordinator_bootstrap_grants(\n\t\t\t\t\t\tgrant_id, group_id, seed_device_id, worker_device_id, expires_at,\n\t\t\t\t\t\tcreated_at, created_by, revoked_at\n\t\t\t\t\t) SELECT i.bootstrap_grant_id, i.group_id, i.inviter_device_id, i.bound_device_id,\n\t\t\t\t\t\ti.expires_at, ?, i.recipient_actor_id, NULL FROM coordinator_invites i\n\t\t\t\t\tJOIN enrolled_devices e ON e.group_id = i.group_id\n\t\t\t\t\t\tAND e.device_id = i.inviter_device_id AND e.enabled = 1\n\t\t\t\t\tWHERE (i.token_digest = ? OR i.token = ?) AND i.invite_kind = 'add_device'\n\t\t\t\t\t\tAND i.bootstrap_grant_id IS NOT NULL AND i.bound_device_id = ?`)\n\t\t\t\t\t.bind(consumedAt, digest, _opts.token, _opts.deviceId),\n\t\t\t]);\n\t\t\tchanged = batchResultChanges(results[0]);\n\t\t}\n\t\tconst currentGroup = await this.getGroup(initial.group_id);\n\t\tif (!currentGroup) throw new Error(\"group_not_found\");\n\t\tif (currentGroup.archived_at) throw new Error(\"group_archived\");\n\t\tconst currentEnrollment = await firstRow<CoordinatorEnrollment>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n\t\t\t\t\tFROM enrolled_devices WHERE group_id = ? AND device_id = ?`)\n\t\t\t\t.bind(initial.group_id, _opts.deviceId),\n\t\t);\n\t\tif (\n\t\t\tcurrentEnrollment &&\n\t\t\t(currentEnrollment.public_key !== _opts.publicKey ||\n\t\t\t\tcurrentEnrollment.fingerprint !== _opts.fingerprint ||\n\t\t\t\t(currentEnrollment.identity_id !== null &&\n\t\t\t\t\tcurrentEnrollment.identity_id !== authoritativeIdentityId))\n\t\t) {\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t}\n\t\tconst saved = await this.getInviteByTokenForInspection(_opts.token);\n\t\tif (\n\t\t\t!saved ||\n\t\t\tsaved.revoked_at ||\n\t\t\t(!saved.consumed_at && new Date(saved.expires_at) <= new Date(consumedAt))\n\t\t) {\n\t\t\tthrow new Error(\"invite_invalid\");\n\t\t}\n\t\tconst savedInspection = await recipientInspection(saved);\n\t\tif (!savedInspection || savedInspection.kind !== _opts.inviteKind) {\n\t\t\tthrow new Error(\"invite_invalid\");\n\t\t}\n\t\tconst savedIdentityId = recipientInviteAuthoritativeIdentityId(savedInspection);\n\t\tif (savedIdentityId !== authoritativeIdentityId) {\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t}\n\t\tif (\n\t\t\tsaved.bound_device_id !== _opts.deviceId ||\n\t\t\tsaved.bound_public_key !== _opts.publicKey ||\n\t\t\tsaved.bound_fingerprint !== _opts.fingerprint\n\t\t) {\n\t\t\tthrow new Error(\"invite_already_bound\");\n\t\t}\n\t\tif (saved.recipient_actor_id !== authoritativeIdentityId)\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\tawait this.db\n\t\t\t.prepare(`UPDATE enrolled_devices SET identity_id = ?\n\t\t\t\tWHERE group_id = ? AND device_id = ? AND identity_id IS NULL\n\t\t\t\t\tAND public_key = ? AND fingerprint = ?`)\n\t\t\t.bind(\n\t\t\t\tauthoritativeIdentityId,\n\t\t\t\tsaved.group_id,\n\t\t\t\t_opts.deviceId,\n\t\t\t\t_opts.publicKey,\n\t\t\t\t_opts.fingerprint,\n\t\t\t)\n\t\t\t.run();\n\t\tconst enrollment = await this.getEnrollment(saved.group_id, _opts.deviceId);\n\t\tif (!enrollment) throw new Error(\"invite_acceptance_incomplete\");\n\t\tif (\n\t\t\tenrollment.public_key !== _opts.publicKey ||\n\t\t\tenrollment.fingerprint !== _opts.fingerprint ||\n\t\t\tenrollment.identity_id !== authoritativeIdentityId\n\t\t) {\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t}\n\t\tlet savedWithGrant = saved;\n\t\tif (\n\t\t\tsavedInspection.kind === \"add_device\" &&\n\t\t\tsaved.inviter_device_id &&\n\t\t\t!saved.bootstrap_grant_id &&\n\t\t\tnew Date(saved.expires_at) > new Date(consumedAt)\n\t\t) {\n\t\t\tif (!this.db.batch)\n\t\t\t\tthrow new Error(\"D1 batch support is required for atomic bootstrap grant recovery.\");\n\t\t\tconst recoveryGrantId = tokenUrlSafe(12);\n\t\t\tawait this.db.batch([\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_invites SET bootstrap_grant_id = ?,\n\t\t\t\t\t\ttrust_state = 'bootstrap_grant_created'\n\t\t\t\t\t\tWHERE invite_id = ? AND invite_kind = 'add_device'\n\t\t\t\t\t\tAND bootstrap_grant_id IS NULL AND inviter_device_id IS NOT NULL\n\t\t\t\t\t\tAND bound_device_id = ? AND recipient_actor_id = ? AND expires_at > ?\n\t\t\t\t\t\tAND EXISTS (SELECT 1 FROM enrolled_devices e\n\t\t\t\t\t\t\tWHERE e.group_id = coordinator_invites.group_id\n\t\t\t\t\t\t\tAND e.device_id = coordinator_invites.inviter_device_id AND e.enabled = 1)`)\n\t\t\t\t\t.bind(\n\t\t\t\t\t\trecoveryGrantId,\n\t\t\t\t\t\tsaved.invite_id,\n\t\t\t\t\t\t_opts.deviceId,\n\t\t\t\t\t\tauthoritativeIdentityId,\n\t\t\t\t\t\tconsumedAt,\n\t\t\t\t\t),\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`INSERT OR IGNORE INTO coordinator_bootstrap_grants(\n\t\t\t\t\t\tgrant_id, group_id, seed_device_id, worker_device_id, expires_at,\n\t\t\t\t\t\tcreated_at, created_by, revoked_at\n\t\t\t\t\t) SELECT i.bootstrap_grant_id, i.group_id, i.inviter_device_id, i.bound_device_id,\n\t\t\t\t\t\ti.expires_at, ?, i.recipient_actor_id, NULL FROM coordinator_invites i\n\t\t\t\t\tJOIN enrolled_devices e ON e.group_id = i.group_id\n\t\t\t\t\t\tAND e.device_id = i.inviter_device_id AND e.enabled = 1\n\t\t\t\t\tWHERE i.invite_id = ? AND i.invite_kind = 'add_device'\n\t\t\t\t\t\tAND i.bootstrap_grant_id IS NOT NULL AND i.bound_device_id = ?`)\n\t\t\t\t\t.bind(consumedAt, saved.invite_id, _opts.deviceId),\n\t\t\t]);\n\t\t\tconst refreshed = await this.getInviteByTokenForInspection(_opts.token);\n\t\t\tif (!refreshed) throw new Error(\"invite_invalid\");\n\t\t\tsavedWithGrant = refreshed;\n\t\t}\n\t\tconst bootstrapGrant = savedWithGrant.bootstrap_grant_id\n\t\t\t? await this.getBootstrapGrant(savedWithGrant.bootstrap_grant_id)\n\t\t\t: null;\n\t\treturn {\n\t\t\tstatus: changed === 1 ? \"accepted\" : \"existing\",\n\t\t\tinvite: savedWithGrant,\n\t\t\treviewed_intent: savedInspection.reviewed_intent,\n\t\t\tbootstrap_grant: bootstrapGrant,\n\t\t};\n\t}\n\n\tasync consumeProjectInvite(\n\t\t_opts: CoordinatorConsumeProjectInviteInput,\n\t): Promise<CoordinatorProjectInviteAcceptance> {\n\t\tif (!this.db.batch) throw new Error(\"D1 batch support is required for atomic invite consume.\");\n\t\tconst consumedAt = normalizeInviteExpiresAt(_opts.now);\n\t\tconst digest = await tokenDigest(_opts.token);\n\t\tconst initial = await this.getInviteByTokenForInspection(_opts.token);\n\t\tif (!initial?.operation_id || !initial.project_intent_json || initial.revoked_at) {\n\t\t\tthrow new Error(\"invite_invalid\");\n\t\t}\n\t\tconst group = await this.getGroup(initial.group_id);\n\t\tif (!group) throw new Error(\"group_not_found\");\n\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\tif (initial.operation_id !== _opts.operationId) throw new Error(\"invite_invalid\");\n\t\tif (fingerprintPublicKey(_opts.publicKey) !== _opts.fingerprint) {\n\t\t\tthrow new Error(\"fingerprint_mismatch\");\n\t\t}\n\t\tif (!initial.consumed_at && new Date(initial.expires_at) <= new Date(consumedAt)) {\n\t\t\tthrow new Error(\"invite_expired\");\n\t\t}\n\t\tconst sameBinding =\n\t\t\tinitial.bound_device_id === _opts.deviceId &&\n\t\t\tinitial.bound_public_key === _opts.publicKey &&\n\t\t\tinitial.bound_fingerprint === _opts.fingerprint;\n\t\tif (initial.consumed_at && !sameBinding) throw new Error(\"invite_already_bound\");\n\t\tif (\n\t\t\tinitial.consumed_at &&\n\t\t\t(initial.recipient_actor_id !== _opts.recipientActorId ||\n\t\t\t\tinitial.recipient_display_name !== _opts.recipientDisplayName ||\n\t\t\t\tinitial.recipient_device_display_name !== _opts.deviceDisplayName)\n\t\t) {\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t}\n\t\tconst existingEnrollment = await firstRow<CoordinatorEnrollment>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n\t\t\t\t\tFROM enrolled_devices WHERE group_id = ? AND device_id = ?`)\n\t\t\t\t.bind(initial.group_id, _opts.deviceId),\n\t\t);\n\t\tif (\n\t\t\texistingEnrollment &&\n\t\t\t(existingEnrollment.public_key !== _opts.publicKey ||\n\t\t\t\texistingEnrollment.fingerprint !== _opts.fingerprint ||\n\t\t\t\t(existingEnrollment.identity_id != null &&\n\t\t\t\t\texistingEnrollment.identity_id !== _opts.recipientActorId))\n\t\t) {\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t}\n\n\t\tconst grantId = tokenUrlSafe(12);\n\t\tconst results = await this.db.batch([\n\t\t\tthis.db\n\t\t\t\t.prepare(`UPDATE coordinator_invites SET token = ?, consumed_at = ?, bound_device_id = ?,\n\t\t\t\t\tbound_public_key = ?, bound_fingerprint = ?, recipient_actor_id = ?,\n\t\t\t\t\trecipient_display_name = ?, recipient_device_display_name = ?,\n\t\t\t\t\ttrust_state = 'pending_inviter_device'\n\t\t\t\t\tWHERE (token_digest = ? OR token = ?) AND consumed_at IS NULL\n\t\t\t\t\tAND EXISTS (SELECT 1 FROM groups g WHERE g.group_id = coordinator_invites.group_id\n\t\t\t\t\t\tAND g.archived_at IS NULL)`)\n\t\t\t\t.bind(\n\t\t\t\t\t`consumed:${initial.invite_id}`,\n\t\t\t\t\tconsumedAt,\n\t\t\t\t\t_opts.deviceId,\n\t\t\t\t\t_opts.publicKey,\n\t\t\t\t\t_opts.fingerprint,\n\t\t\t\t\t_opts.recipientActorId,\n\t\t\t\t\t_opts.recipientDisplayName,\n\t\t\t\t\t_opts.deviceDisplayName,\n\t\t\t\t\tdigest,\n\t\t\t\t\t_opts.token,\n\t\t\t\t),\n\t\t\tthis.db\n\t\t\t\t.prepare(`INSERT INTO enrolled_devices(\n\t\t\t\t\tgroup_id, device_id, public_key, fingerprint, identity_id, display_name, enabled, created_at\n\t\t\t\t) SELECT i.group_id, i.bound_device_id, i.bound_public_key, i.bound_fingerprint,\n\t\t\t\t\ti.recipient_actor_id, i.recipient_device_display_name, 1, ? FROM coordinator_invites i\n\t\t\t\t\tJOIN groups g ON g.group_id = i.group_id AND g.archived_at IS NULL\n\t\t\t\t\tWHERE (i.token_digest = ? OR i.token = ?) AND i.bound_device_id = ? AND ? = 1\n\t\t\t\tON CONFLICT(group_id, device_id) DO UPDATE SET\n\t\t\t\t\tidentity_id = COALESCE(enrolled_devices.identity_id, excluded.identity_id),\n\t\t\t\t\tdisplay_name = excluded.display_name, enabled = 1\n\t\t\t\tWHERE enrolled_devices.identity_id IS NULL\n\t\t\t\t\tOR enrolled_devices.identity_id = excluded.identity_id`)\n\t\t\t\t.bind(consumedAt, digest, _opts.token, _opts.deviceId, initial.consumed_at ? 0 : 1),\n\t\t\tthis.db\n\t\t\t\t.prepare(`UPDATE coordinator_invites SET bootstrap_grant_id = ?,\n\t\t\t\t\ttrust_state = 'bootstrap_grant_created'\n\t\t\t\t\tWHERE (token_digest = ? OR token = ?) AND bootstrap_grant_id IS NULL\n\t\t\t\t\tAND bound_device_id = ?\n\t\t\t\t\tAND EXISTS (SELECT 1 FROM groups g WHERE g.group_id = coordinator_invites.group_id\n\t\t\t\t\t\tAND g.archived_at IS NULL)\n\t\t\t\t\tAND expires_at > ?\n\t\t\t\t\tAND EXISTS (SELECT 1 FROM enrolled_devices e WHERE e.group_id = coordinator_invites.group_id\n\t\t\t\t\t\tAND e.device_id = coordinator_invites.inviter_device_id AND e.enabled = 1)`)\n\t\t\t\t.bind(grantId, digest, _opts.token, _opts.deviceId, consumedAt),\n\t\t\tthis.db\n\t\t\t\t.prepare(`INSERT OR IGNORE INTO coordinator_bootstrap_grants(\n\t\t\t\t\tgrant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at,\n\t\t\t\t\tcreated_by, revoked_at\n\t\t\t\t) SELECT i.bootstrap_grant_id, i.group_id, i.inviter_device_id, i.bound_device_id,\n\t\t\t\t\ti.expires_at, ?, i.inviter_actor_id, NULL FROM coordinator_invites i\n\t\t\t\t\tJOIN groups g ON g.group_id = i.group_id AND g.archived_at IS NULL\n\t\t\t\t\tJOIN enrolled_devices e ON e.group_id = i.group_id AND e.device_id = i.inviter_device_id\n\t\t\t\t\tWHERE (i.token_digest = ? OR i.token = ?) AND i.bootstrap_grant_id IS NOT NULL\n\t\t\t\t\tAND i.bound_device_id = ? AND e.enabled = 1`)\n\t\t\t\t.bind(consumedAt, digest, _opts.token, _opts.deviceId),\n\t\t]);\n\t\tconst accepted = batchResultChanges(results[0]) === 1;\n\t\tconst currentGroup = await this.getGroup(initial.group_id);\n\t\tif (!currentGroup) throw new Error(\"group_not_found\");\n\t\tif (currentGroup.archived_at) throw new Error(\"group_archived\");\n\t\tconst saved = await this.getInviteByTokenForInspection(_opts.token);\n\t\tif (!saved) throw new Error(\"invite_invalid\");\n\t\tif (\n\t\t\tsaved.bound_device_id !== _opts.deviceId ||\n\t\t\tsaved.bound_public_key !== _opts.publicKey ||\n\t\t\tsaved.bound_fingerprint !== _opts.fingerprint\n\t\t) {\n\t\t\tthrow new Error(\"invite_already_bound\");\n\t\t}\n\t\tif (\n\t\t\tsaved.recipient_actor_id !== _opts.recipientActorId ||\n\t\t\tsaved.recipient_display_name !== _opts.recipientDisplayName ||\n\t\t\tsaved.recipient_device_display_name !== _opts.deviceDisplayName\n\t\t) {\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t}\n\t\tif (!accepted) {\n\t\t\tawait this.db\n\t\t\t\t.prepare(`UPDATE enrolled_devices SET identity_id = ?\n\t\t\t\t\tWHERE group_id = ? AND device_id = ? AND identity_id IS NULL AND enabled = 1\n\t\t\t\t\t\tAND public_key = ? AND fingerprint = ?`)\n\t\t\t\t.bind(\n\t\t\t\t\t_opts.recipientActorId,\n\t\t\t\t\tsaved.group_id,\n\t\t\t\t\t_opts.deviceId,\n\t\t\t\t\t_opts.publicKey,\n\t\t\t\t\t_opts.fingerprint,\n\t\t\t\t)\n\t\t\t\t.run();\n\t\t}\n\t\tconst enrollment = await this.getEnrollment(saved.group_id, _opts.deviceId);\n\t\tif (!enrollment) throw new Error(\"invite_acceptance_incomplete\");\n\t\tif (enrollment.identity_id !== _opts.recipientActorId) {\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t}\n\t\tconst seed = saved.inviter_device_id\n\t\t\t? await this.getEnrollment(saved.group_id, saved.inviter_device_id)\n\t\t\t: null;\n\t\tconst grant = saved.bootstrap_grant_id\n\t\t\t? await this.getBootstrapGrant(saved.bootstrap_grant_id)\n\t\t\t: null;\n\t\treturn {\n\t\t\tstatus: accepted ? \"accepted\" : \"existing\",\n\t\t\tinvite: saved,\n\t\t\tenrollment,\n\t\t\tseed_enrollment: seed,\n\t\t\tbootstrap_grant: grant,\n\t\t};\n\t}\n\n\tasync listInvites(_groupId: string): Promise<CoordinatorInvite[]> {\n\t\treturn (\n\t\t\tawait allRows<CoordinatorInvite>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT ${INVITE_COLUMNS}\n\t\t\t\t\t FROM coordinator_invites WHERE group_id = ?\n\t\t\t\t\t ORDER BY created_at DESC`)\n\t\t\t\t\t.bind(_groupId),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorInvite>(row));\n\t}\n\n\tasync createJoinRequest(\n\t\t_opts: CoordinatorCreateJoinRequestInput,\n\t): Promise<CoordinatorJoinRequest> {\n\t\tconst now = nowISO();\n\t\tconst requestId = tokenUrlSafe(12);\n\t\tawait this.db\n\t\t\t.prepare(`INSERT INTO coordinator_join_requests(\n\t\t\t\trequest_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, NULL, NULL)`)\n\t\t\t.bind(\n\t\t\t\trequestId,\n\t\t\t\t_opts.groupId,\n\t\t\t\t_opts.deviceId,\n\t\t\t\t_opts.publicKey,\n\t\t\t\t_opts.fingerprint,\n\t\t\t\t_opts.displayName ?? null,\n\t\t\t\t_opts.token,\n\t\t\t\tnow,\n\t\t\t)\n\t\t\t.run();\n\t\tconst row = await firstRow<CoordinatorJoinRequest>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n\t\t\t\t\t FROM coordinator_join_requests WHERE request_id = ?`)\n\t\t\t\t.bind(requestId),\n\t\t);\n\t\treturn rowToRecord<CoordinatorJoinRequest>(row);\n\t}\n\n\tasync listJoinRequests(_groupId: string, _status?: string): Promise<CoordinatorJoinRequest[]> {\n\t\tconst status = _status ?? \"pending\";\n\t\treturn (\n\t\t\tawait allRows<CoordinatorJoinRequest>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n\t\t\t\t\t\t FROM coordinator_join_requests\n\t\t\t\t\t\t WHERE group_id = ? AND status = ?\n\t\t\t\t\t\t ORDER BY created_at ASC, device_id ASC`)\n\t\t\t\t\t.bind(_groupId, status),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorJoinRequest>(row));\n\t}\n\n\tasync reviewJoinRequest(\n\t\t_opts: CoordinatorReviewJoinRequestInput,\n\t): Promise<CoordinatorJoinRequestReviewResult | null> {\n\t\tconst row = await firstRow<CoordinatorJoinRequest & { public_key: string }>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status,\n\t\t\t\t\t created_at, reviewed_at, reviewed_by\n\t\t\t\t\t FROM coordinator_join_requests WHERE request_id = ?`)\n\t\t\t\t.bind(_opts.requestId),\n\t\t);\n\t\tif (!row) return null;\n\t\tif (row.status !== \"pending\") {\n\t\t\treturn { ...rowToRecord<CoordinatorJoinRequest>(row), _no_transition: true };\n\t\t}\n\t\tconst bootstrapGrantRequest = normalizeBootstrapGrantRequest(_opts.bootstrapGrant);\n\t\tconst reviewedAt = nowISO();\n\t\tconst nextStatus = _opts.approved ? \"approved\" : \"denied\";\n\t\tlet bootstrapGrantInput: CoordinatorCreateBootstrapGrantInput | null = null;\n\t\tlet bootstrapGrantId: string | null = null;\n\t\tif (_opts.approved && bootstrapGrantRequest) {\n\t\t\tconst seedEnrollment = await firstRow<{ device_id: string }>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`SELECT device_id FROM enrolled_devices WHERE group_id = ? AND device_id = ? AND enabled = 1`,\n\t\t\t\t\t)\n\t\t\t\t\t.bind(row.group_id, bootstrapGrantRequest.seedDeviceId),\n\t\t\t);\n\t\t\tif (!seedEnrollment) {\n\t\t\t\tthrow new Error(\"bootstrap grant seed device is not enrolled in the group.\");\n\t\t\t}\n\t\t\tif (bootstrapGrantRequest.seedDeviceId === row.device_id) {\n\t\t\t\tthrow new Error(\"bootstrap grant seed and worker device ids must differ.\");\n\t\t\t}\n\t\t\tbootstrapGrantInput = {\n\t\t\t\t...bootstrapGrantRequest,\n\t\t\t\tgroupId: row.group_id,\n\t\t\t\tworkerDeviceId: row.device_id,\n\t\t\t};\n\t\t}\n\t\tif (this.db.batch) {\n\t\t\tconst statements: D1PreparedStatementLike[] = [];\n\t\t\tstatements.push(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_join_requests\n\t\t\t\t\t\t SET status = ?, reviewed_at = ?, reviewed_by = ?\n\t\t\t\t\t\t WHERE request_id = ? AND status = 'pending'`)\n\t\t\t\t\t.bind(nextStatus, reviewedAt, _opts.reviewedBy ?? null, _opts.requestId),\n\t\t\t);\n\t\t\tif (_opts.approved) {\n\t\t\t\tstatements.push(\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.prepare(`INSERT INTO enrolled_devices(\n\t\t\t\t\t\t\tgroup_id, device_id, public_key, fingerprint, display_name, enabled, created_at\n\t\t\t\t\t\t)\n\t\t\t\t\t\tSELECT group_id, device_id, public_key, fingerprint, display_name, 1, ?\n\t\t\t\t\t\tFROM coordinator_join_requests\n\t\t\t\t\t\tWHERE request_id = ?\n\t\t\t\t\t\t AND status = 'approved'\n\t\t\t\t\t\t AND reviewed_at = ?\n\t\t\t\t\t\tON CONFLICT(group_id, device_id) DO UPDATE SET\n\t\t\t\t\t\t\tpublic_key = excluded.public_key,\n\t\t\t\t\t\t\tfingerprint = excluded.fingerprint,\n\t\t\t\t\t\t\tdisplay_name = excluded.display_name,\n\t\t\t\t\t\t\tenabled = 1`)\n\t\t\t\t\t\t.bind(nowISO(), _opts.requestId, reviewedAt),\n\t\t\t\t);\n\t\t\t\tif (bootstrapGrantInput) {\n\t\t\t\t\tbootstrapGrantId = tokenUrlSafe(12);\n\t\t\t\t\tconst createdAt = nowISO();\n\t\t\t\t\t// Conditional INSERT: only mint a grant if the join request was\n\t\t\t\t\t// actually transitioned to 'approved' by the UPDATE in this batch.\n\t\t\t\t\t// This prevents issuing extra grants under concurrent review races.\n\t\t\t\t\tstatements.push(\n\t\t\t\t\t\tthis.db\n\t\t\t\t\t\t\t.prepare(`INSERT INTO coordinator_bootstrap_grants(\n\t\t\t\t\t\t\tgrant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n\t\t\t\t\t\t) SELECT ?, ?, ?, ?, ?, ?, ?, NULL\n\t\t\t\t\t\tWHERE EXISTS (\n\t\t\t\t\t\t\tSELECT 1 FROM coordinator_join_requests\n\t\t\t\t\t\t\tWHERE request_id = ? AND status = 'approved' AND reviewed_at = ?\n\t\t\t\t\t\t)`)\n\t\t\t\t\t\t\t.bind(\n\t\t\t\t\t\t\t\tbootstrapGrantId,\n\t\t\t\t\t\t\t\tbootstrapGrantInput.groupId,\n\t\t\t\t\t\t\t\tbootstrapGrantInput.seedDeviceId,\n\t\t\t\t\t\t\t\tbootstrapGrantInput.workerDeviceId,\n\t\t\t\t\t\t\t\tbootstrapGrantInput.expiresAt,\n\t\t\t\t\t\t\t\tcreatedAt,\n\t\t\t\t\t\t\t\tbootstrapGrantInput.createdBy ?? null,\n\t\t\t\t\t\t\t\t_opts.requestId,\n\t\t\t\t\t\t\t\treviewedAt,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tawait this.db.batch(statements);\n\t\t} else {\n\t\t\tlet createdGrantId: string | null = null;\n\t\t\tif (_opts.approved) {\n\t\t\t\tawait this.enrollDevice(row.group_id, {\n\t\t\t\t\tdeviceId: row.device_id,\n\t\t\t\t\tfingerprint: row.fingerprint,\n\t\t\t\t\tpublicKey: row.public_key,\n\t\t\t\t\tdisplayName: (row.display_name ?? \"\").trim() || null,\n\t\t\t\t});\n\t\t\t\tif (bootstrapGrantInput) {\n\t\t\t\t\tconst grant = await this.createBootstrapGrant(bootstrapGrantInput);\n\t\t\t\t\tcreatedGrantId = grant.grant_id;\n\t\t\t\t\tbootstrapGrantId = grant.grant_id;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst changes = await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_join_requests\n\t\t\t\t\t\t SET status = ?, reviewed_at = ?, reviewed_by = ?\n\t\t\t\t\t\t WHERE request_id = ? AND status = 'pending'`)\n\t\t\t\t\t.bind(nextStatus, reviewedAt, _opts.reviewedBy ?? null, _opts.requestId),\n\t\t\t);\n\t\t\tif (changes === 0) {\n\t\t\t\tif (createdGrantId) {\n\t\t\t\t\tawait this.revokeBootstrapGrant(createdGrantId);\n\t\t\t\t}\n\t\t\t\tconst latest = await firstRow<CoordinatorJoinRequestReviewResult>(\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.prepare(`SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n\t\t\t\t\t\t\t FROM coordinator_join_requests WHERE request_id = ?`)\n\t\t\t\t\t\t.bind(_opts.requestId),\n\t\t\t\t);\n\t\t\t\treturn latest\n\t\t\t\t\t? { ...rowToRecord<CoordinatorJoinRequestReviewResult>(latest), _no_transition: true }\n\t\t\t\t\t: null;\n\t\t\t}\n\t\t}\n\t\tconst updated = await firstRow<CoordinatorJoinRequestReviewResult>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n\t\t\t\t\t FROM coordinator_join_requests WHERE request_id = ?`)\n\t\t\t\t.bind(_opts.requestId),\n\t\t);\n\t\tif (!updated) return null;\n\t\tconst bootstrapGrant = bootstrapGrantInput\n\t\t\t? bootstrapGrantId\n\t\t\t\t? await this.getBootstrapGrant(bootstrapGrantId)\n\t\t\t\t: await this.createBootstrapGrant(bootstrapGrantInput)\n\t\t\t: null;\n\t\treturn {\n\t\t\t...rowToRecord<CoordinatorJoinRequestReviewResult>(updated),\n\t\t\tbootstrap_grant: bootstrapGrant,\n\t\t};\n\t}\n\n\tasync createReciprocalApproval(\n\t\topts: CoordinatorCreateReciprocalApprovalInput,\n\t): Promise<CoordinatorReciprocalApproval> {\n\t\tconst groupId = opts.groupId.trim();\n\t\tconst requestingDeviceId = opts.requestingDeviceId.trim();\n\t\tconst requestedDeviceId = opts.requestedDeviceId.trim();\n\t\tconst hasExpectedIncomingRequestId = opts.expectedIncomingRequestId !== undefined;\n\t\tconst expectedIncomingRequestId = opts.expectedIncomingRequestId?.trim() ?? \"\";\n\t\tif (!groupId || !requestingDeviceId || !requestedDeviceId) {\n\t\t\tthrow new Error(\"groupId, requestingDeviceId, and requestedDeviceId are required.\");\n\t\t}\n\t\tif (requestingDeviceId === requestedDeviceId) {\n\t\t\tthrow new Error(\"requesting and requested device ids must differ.\");\n\t\t}\n\t\tif (hasExpectedIncomingRequestId) {\n\t\t\tconst resolvedAt = nowISO();\n\t\t\tconst changes = await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_reciprocal_approvals\n\t\t\t\t\t\t SET status = 'completed', resolved_at = ?\n\t\t\t\t\t\t WHERE request_id = ?\n\t\t\t\t\t\t AND group_id = ?\n\t\t\t\t\t\t AND requesting_device_id = ?\n\t\t\t\t\t\t AND requested_device_id = ?\n\t\t\t\t\t\t AND status = 'pending'`)\n\t\t\t\t\t.bind(\n\t\t\t\t\t\tresolvedAt,\n\t\t\t\t\t\texpectedIncomingRequestId,\n\t\t\t\t\t\tgroupId,\n\t\t\t\t\t\trequestedDeviceId,\n\t\t\t\t\t\trequestingDeviceId,\n\t\t\t\t\t),\n\t\t\t);\n\t\t\tif (changes !== 1) {\n\t\t\t\tthrow new CoordinatorReciprocalApprovalRequestChangedError();\n\t\t\t}\n\t\t\tconst completed = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t\t FROM coordinator_reciprocal_approvals WHERE request_id = ?`)\n\t\t\t\t\t.bind(expectedIncomingRequestId),\n\t\t\t);\n\t\t\treturn rowToRecord<CoordinatorReciprocalApproval>(completed);\n\t\t}\n\t\tconst pendingPair = reciprocalPendingPair(requestingDeviceId, requestedDeviceId);\n\t\tconst existing = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t FROM coordinator_reciprocal_approvals\n\t\t\t\t\t WHERE group_id = ? AND requesting_device_id = ? AND requested_device_id = ? AND status = 'pending'\n\t\t\t\t\t ORDER BY created_at DESC LIMIT 1`)\n\t\t\t\t.bind(groupId, requestingDeviceId, requestedDeviceId),\n\t\t);\n\t\tif (existing) return rowToRecord<CoordinatorReciprocalApproval>(existing);\n\t\tconst reverse = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t FROM coordinator_reciprocal_approvals\n\t\t\t\t\t WHERE group_id = ? AND requesting_device_id = ? AND requested_device_id = ? AND status = 'pending'\n\t\t\t\t\t ORDER BY created_at DESC LIMIT 1`)\n\t\t\t\t.bind(groupId, requestedDeviceId, requestingDeviceId),\n\t\t);\n\t\tif (reverse) {\n\t\t\tconst resolvedAt = nowISO();\n\t\t\tawait this.db\n\t\t\t\t.prepare(\n\t\t\t\t\t`UPDATE coordinator_reciprocal_approvals SET status = 'completed', resolved_at = ? WHERE request_id = ?`,\n\t\t\t\t)\n\t\t\t\t.bind(resolvedAt, reverse.request_id)\n\t\t\t\t.run();\n\t\t\tconst completed = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t\t FROM coordinator_reciprocal_approvals WHERE request_id = ?`)\n\t\t\t\t\t.bind(reverse.request_id),\n\t\t\t);\n\t\t\treturn rowToRecord<CoordinatorReciprocalApproval>(completed);\n\t\t}\n\t\tconst requestId = tokenUrlSafe(12);\n\t\tconst createdAt = nowISO();\n\t\ttry {\n\t\t\tawait this.db\n\t\t\t\t.prepare(`INSERT INTO coordinator_reciprocal_approvals(\n\t\t\t\t\t\trequest_id,\n\t\t\t\t\t\tgroup_id,\n\t\t\t\t\t\trequesting_device_id,\n\t\t\t\t\t\trequested_device_id,\n\t\t\t\t\t\tpending_pair_low_device_id,\n\t\t\t\t\t\tpending_pair_high_device_id,\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\tcreated_at,\n\t\t\t\t\t\tresolved_at\n\t\t\t\t\t) VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, NULL)`)\n\t\t\t\t.bind(\n\t\t\t\t\trequestId,\n\t\t\t\t\tgroupId,\n\t\t\t\t\trequestingDeviceId,\n\t\t\t\t\trequestedDeviceId,\n\t\t\t\t\tpendingPair.low,\n\t\t\t\t\tpendingPair.high,\n\t\t\t\t\tcreatedAt,\n\t\t\t\t)\n\t\t\t\t.run();\n\t\t} catch (error) {\n\t\t\tif (!isUniqueConstraintError(error)) throw error;\n\t\t\tconst sameDirection = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t\t FROM coordinator_reciprocal_approvals\n\t\t\t\t\t\t WHERE group_id = ? AND requesting_device_id = ? AND requested_device_id = ? AND status = 'pending'\n\t\t\t\t\t\t ORDER BY created_at DESC LIMIT 1`)\n\t\t\t\t\t.bind(groupId, requestingDeviceId, requestedDeviceId),\n\t\t\t);\n\t\t\tif (sameDirection) return rowToRecord<CoordinatorReciprocalApproval>(sameDirection);\n\t\t\tconst reverseAfterConflict = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t\t FROM coordinator_reciprocal_approvals\n\t\t\t\t\t\t WHERE group_id = ? AND requesting_device_id = ? AND requested_device_id = ? AND status = 'pending'\n\t\t\t\t\t\t ORDER BY created_at DESC LIMIT 1`)\n\t\t\t\t\t.bind(groupId, requestedDeviceId, requestingDeviceId),\n\t\t\t);\n\t\t\tif (reverseAfterConflict) {\n\t\t\t\tconst resolvedAt = nowISO();\n\t\t\t\tawait this.db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`UPDATE coordinator_reciprocal_approvals SET status = 'completed', resolved_at = ? WHERE request_id = ?`,\n\t\t\t\t\t)\n\t\t\t\t\t.bind(resolvedAt, reverseAfterConflict.request_id)\n\t\t\t\t\t.run();\n\t\t\t\tconst completed = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t\t\t FROM coordinator_reciprocal_approvals WHERE request_id = ?`)\n\t\t\t\t\t\t.bind(reverseAfterConflict.request_id),\n\t\t\t\t);\n\t\t\t\treturn rowToRecord<CoordinatorReciprocalApproval>(completed);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tconst created = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t FROM coordinator_reciprocal_approvals WHERE request_id = ?`)\n\t\t\t\t.bind(requestId),\n\t\t);\n\t\treturn rowToRecord<CoordinatorReciprocalApproval>(created);\n\t}\n\n\tasync createBootstrapGrant(\n\t\topts: CoordinatorCreateBootstrapGrantInput,\n\t): Promise<CoordinatorBootstrapGrant> {\n\t\tconst normalized = requireTrimmedBootstrapGrantInput(opts);\n\t\tconst grantId = tokenUrlSafe(12);\n\t\tconst createdAt = nowISO();\n\t\tawait this.db\n\t\t\t.prepare(`INSERT INTO coordinator_bootstrap_grants(\n\t\t\t\tgrant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, NULL)`)\n\t\t\t.bind(\n\t\t\t\tgrantId,\n\t\t\t\tnormalized.groupId,\n\t\t\t\tnormalized.seedDeviceId,\n\t\t\t\tnormalized.workerDeviceId,\n\t\t\t\tnormalized.expiresAt,\n\t\t\t\tcreatedAt,\n\t\t\t\tnormalized.createdBy,\n\t\t\t)\n\t\t\t.run();\n\t\tconst row = await firstRow<CoordinatorBootstrapGrant>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n\t\t\t\t\t FROM coordinator_bootstrap_grants WHERE grant_id = ?`)\n\t\t\t\t.bind(grantId),\n\t\t);\n\t\treturn rowToRecord<CoordinatorBootstrapGrant>(row);\n\t}\n\n\tprivate async getScope(scopeId: string): Promise<CoordinatorScope | null> {\n\t\tconst row = await firstRow<CoordinatorScope>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT scope_id, label, kind, authority_type, coordinator_id, group_id,\n\t\t\t\t\t\tmanifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at\n\t\t\t\t\t FROM coordinator_scopes WHERE scope_id = ?`)\n\t\t\t\t.bind(scopeId),\n\t\t);\n\t\treturn row ? rowToRecord<CoordinatorScope>(row) : null;\n\t}\n\n\tprivate async getScopeMembership(\n\t\tscopeId: string,\n\t\tdeviceId: string,\n\t): Promise<CoordinatorScopeMembership | null> {\n\t\tconst row = await firstRow<CoordinatorScopeMembership>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\t\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t\t\t\t FROM coordinator_scope_memberships\n\t\t\t\t\t WHERE scope_id = ? AND device_id = ?`)\n\t\t\t\t.bind(scopeId, deviceId),\n\t\t);\n\t\treturn row ? rowToRecord<CoordinatorScopeMembership>(row) : null;\n\t}\n\n\tasync createScope(opts: CoordinatorCreateScopeInput): Promise<CoordinatorScope> {\n\t\tconst normalized = normalizeCreateScopeInput(opts);\n\t\tif (await this.getScope(normalized.scopeId)) throw new Error(\"scopeId already exists.\");\n\t\tconst now = nowISO();\n\t\tawait this.db\n\t\t\t.prepare(`INSERT INTO coordinator_scopes(\n\t\t\t\t\tscope_id, label, kind, authority_type, coordinator_id, group_id,\n\t\t\t\t\tmanifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at\n\t\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)\n\t\t\t.bind(\n\t\t\t\tnormalized.scopeId,\n\t\t\t\tnormalized.label,\n\t\t\t\tnormalized.kind,\n\t\t\t\tnormalized.authorityType,\n\t\t\t\tnormalized.coordinatorId,\n\t\t\t\tnormalized.groupId,\n\t\t\t\tnormalized.manifestIssuerDeviceId,\n\t\t\t\tnormalized.membershipEpoch,\n\t\t\t\tnormalized.manifestHash,\n\t\t\t\tnormalized.status,\n\t\t\t\tnow,\n\t\t\t\tnow,\n\t\t\t)\n\t\t\t.run();\n\t\tconst scope = await this.getScope(normalized.scopeId);\n\t\tif (!scope) throw new Error(\"scope insert returned no row\");\n\t\treturn scope;\n\t}\n\n\tasync updateScope(opts: CoordinatorUpdateScopeInput): Promise<CoordinatorScope | null> {\n\t\tconst scopeId = clean(opts.scopeId);\n\t\tconst existing = scopeId ? await this.getScope(scopeId) : null;\n\t\tif (!existing) return null;\n\t\tconst normalized = normalizeUpdateScopeInput(opts, existing);\n\t\tawait this.db\n\t\t\t.prepare(`UPDATE coordinator_scopes\n\t\t\t\t SET label = ?,\n\t\t\t\t\t kind = ?,\n\t\t\t\t\t authority_type = ?,\n\t\t\t\t\t coordinator_id = ?,\n\t\t\t\t\t group_id = ?,\n\t\t\t\t\t manifest_issuer_device_id = ?,\n\t\t\t\t\t membership_epoch = ?,\n\t\t\t\t\t manifest_hash = ?,\n\t\t\t\t\t status = ?,\n\t\t\t\t\t updated_at = ?\n\t\t\t\t WHERE scope_id = ?`)\n\t\t\t.bind(\n\t\t\t\tnormalized.label,\n\t\t\t\tnormalized.kind,\n\t\t\t\tnormalized.authorityType,\n\t\t\t\tnormalized.coordinatorId,\n\t\t\t\tnormalized.groupId,\n\t\t\t\tnormalized.manifestIssuerDeviceId,\n\t\t\t\tnormalized.membershipEpoch,\n\t\t\t\tnormalized.manifestHash,\n\t\t\t\tnormalized.status,\n\t\t\t\tnowISO(),\n\t\t\t\tnormalized.scopeId,\n\t\t\t)\n\t\t\t.run();\n\t\treturn await this.getScope(normalized.scopeId);\n\t}\n\n\tasync listScopes(opts: CoordinatorListScopesInput = {}): Promise<CoordinatorScope[]> {\n\t\tconst where: string[] = [];\n\t\tconst params: unknown[] = [];\n\t\tconst coordinatorId = clean(opts.coordinatorId);\n\t\tconst groupId = clean(opts.groupId);\n\t\tconst status = clean(opts.status);\n\t\tif (coordinatorId) {\n\t\t\twhere.push(\"coordinator_id = ?\");\n\t\t\tparams.push(coordinatorId);\n\t\t}\n\t\tif (groupId) {\n\t\t\twhere.push(\"group_id = ?\");\n\t\t\tparams.push(groupId);\n\t\t}\n\t\tif (status) {\n\t\t\twhere.push(\"status = ?\");\n\t\t\tparams.push(status);\n\t\t} else if (!opts.includeInactive) {\n\t\t\twhere.push(\"status = 'active'\");\n\t\t}\n\t\tconst whereSql = where.length ? `WHERE ${where.join(\" AND \")}` : \"\";\n\t\tconst statement =\n\t\t\tthis.db.prepare(`SELECT scope_id, label, kind, authority_type, coordinator_id, group_id,\n\t\t\t\tmanifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at\n\t\t\t FROM coordinator_scopes ${whereSql}\n\t\t\t ORDER BY coordinator_id ASC, group_id ASC, scope_id ASC`);\n\t\treturn (\n\t\t\tawait allRows<CoordinatorScope>(params.length ? statement.bind(...params) : statement)\n\t\t).map((row) => rowToRecord<CoordinatorScope>(row));\n\t}\n\n\tasync grantScopeMembership(\n\t\topts: CoordinatorGrantScopeMembershipInput,\n\t): Promise<CoordinatorScopeMembership> {\n\t\tconst effectId = normalizeMembershipEffectId(opts.effectId);\n\t\tconst requestJson = grantMembershipEffectRequestJson(opts);\n\t\tconst priorReceipt = await getMembershipEffectReceipt(this.db, effectId);\n\t\tif (priorReceipt) {\n\t\t\tassertMatchingMembershipEffectReceipt(priorReceipt, \"grant\", requestJson);\n\t\t\treturn membershipFromEffectReceipt(priorReceipt);\n\t\t}\n\t\tconst scopeId = clean(opts.scopeId);\n\t\tconst deviceId = clean(opts.deviceId);\n\t\tconst scope = scopeId ? await this.getScope(scopeId) : null;\n\t\tif (!scope) throw new CoordinatorMembershipError(\"scope_not_found\");\n\t\tif (scope.status !== \"active\") throw new CoordinatorMembershipError(\"scope_inactive\");\n\t\tconst existing = scopeId && deviceId ? await this.getScopeMembership(scopeId, deviceId) : null;\n\t\tconst normalized = normalizeGrantInput(opts, scope, existing);\n\t\tif (normalized.groupId) {\n\t\t\tconst enrollment = await this.getEnrollment(normalized.groupId, normalized.deviceId);\n\t\t\tif (!enrollment) {\n\t\t\t\tthrow new CoordinatorMembershipError(\"device_not_enrolled\");\n\t\t\t}\n\t\t}\n\t\tconst now = nowISO();\n\t\tawait runAuditedBatch(this.db, [\n\t\t\tthis.db\n\t\t\t\t.prepare(`INSERT INTO coordinator_scope_memberships(\n\t\t\t\t\tscope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t\t\t) SELECT ?, ?, ?, 'active', ?, ?, ?, ?, ?, ?, ?\n\t\t\t\tWHERE NOT EXISTS (\n\t\t\t\t\tSELECT 1 FROM coordinator_scope_membership_effect_receipts WHERE effect_id = ?\n\t\t\t\t)\n\t\t\t\tON CONFLICT(scope_id, device_id) DO UPDATE SET\n\t\t\t\t\trole = excluded.role,\n\t\t\t\t\tstatus = 'active',\n\t\t\t\t\tmembership_epoch = excluded.membership_epoch,\n\t\t\t\t\tcoordinator_id = excluded.coordinator_id,\n\t\t\t\t\tgroup_id = excluded.group_id,\n\t\t\t\t\tmanifest_issuer_device_id = excluded.manifest_issuer_device_id,\n\t\t\t\t\tmanifest_hash = excluded.manifest_hash,\n\t\t\t\t\tsigned_manifest_json = excluded.signed_manifest_json,\n\t\t\t\t\tupdated_at = excluded.updated_at\n\t\t\t\tWHERE excluded.membership_epoch > coordinator_scope_memberships.membership_epoch\n\t\t\t\t OR (\n\t\t\t\t\texcluded.membership_epoch = coordinator_scope_memberships.membership_epoch\n\t\t\t\t\tAND coordinator_scope_memberships.status != 'revoked'\n\t\t\t\t )`)\n\t\t\t\t.bind(\n\t\t\t\t\tnormalized.scopeId,\n\t\t\t\t\tnormalized.deviceId,\n\t\t\t\t\tnormalized.role,\n\t\t\t\t\tnormalized.membershipEpoch,\n\t\t\t\t\tnormalized.coordinatorId,\n\t\t\t\t\tnormalized.groupId,\n\t\t\t\t\tnormalized.manifestIssuerDeviceId,\n\t\t\t\t\tnormalized.manifestHash,\n\t\t\t\t\tnormalized.signedManifestJson,\n\t\t\t\t\tnow,\n\t\t\t\t\teffectId,\n\t\t\t\t),\n\t\t\tprepareGrantEffectReceipt(this.db, {\n\t\t\t\teffectId,\n\t\t\t\trequestJson,\n\t\t\t\tscopeId: normalized.scopeId,\n\t\t\t\tdeviceId: normalized.deviceId,\n\t\t\t\tcreatedAt: now,\n\t\t\t}),\n\t\t\tprepareMembershipAuditFromCurrentRow(this.db, {\n\t\t\t\teffectId,\n\t\t\t\trequestJson,\n\t\t\t\taction: \"grant\",\n\t\t\t\tprevious: existing,\n\t\t\t\tscopeId: normalized.scopeId,\n\t\t\t\tdeviceId: normalized.deviceId,\n\t\t\t\tstatus: \"active\",\n\t\t\t\tmembershipEpoch: normalized.membershipEpoch,\n\t\t\t\tupdatedAt: now,\n\t\t\t\tactorType: normalized.actorType,\n\t\t\t\tactorId: normalized.actorId,\n\t\t\t\tcreatedAt: now,\n\t\t\t}),\n\t\t]);\n\t\tconst receipt = await getMembershipEffectReceipt(this.db, effectId);\n\t\tif (!receipt) throw new Error(\"scope membership grant was not applied.\");\n\t\tassertMatchingMembershipEffectReceipt(receipt, \"grant\", requestJson);\n\t\treturn membershipFromEffectReceipt(receipt);\n\t}\n\n\tasync revokeScopeMembership(opts: CoordinatorRevokeScopeMembershipInput): Promise<boolean> {\n\t\tconst scopeId = clean(opts.scopeId);\n\t\tconst deviceId = clean(opts.deviceId);\n\t\tif (!scopeId || !deviceId) throw new Error(\"scopeId and deviceId are required.\");\n\t\tconst effectId = normalizeMembershipEffectId(opts.effectId);\n\t\tconst requestJson = revokeMembershipEffectRequestJson(opts);\n\t\tconst priorReceipt = await getMembershipEffectReceipt(this.db, effectId);\n\t\tif (priorReceipt) {\n\t\t\tassertMatchingMembershipEffectReceipt(priorReceipt, \"revoke\", requestJson);\n\t\t\treturn priorReceipt.outcome_applied === 1;\n\t\t}\n\t\tconst membershipEpoch =\n\t\t\topts.membershipEpoch == null ? null : normalizeEpoch(opts.membershipEpoch);\n\t\tconst requestedGroupId = clean(opts.groupId);\n\t\tconst scope = requestedGroupId ? await this.getScope(scopeId) : null;\n\t\tif (requestedGroupId && requestedGroupId !== scope?.group_id) {\n\t\t\tthrow new CoordinatorMembershipError(\"scope_group_mismatch\");\n\t\t}\n\t\tconst existing = await this.getScopeMembership(scopeId, deviceId);\n\t\tif (membershipEpoch != null && existing && membershipEpoch <= existing.membership_epoch) {\n\t\t\tthrow new Error(\"membershipEpoch must increase on revoke.\");\n\t\t}\n\t\tconst now = nowISO();\n\t\tconst revokedEpoch = membershipEpoch ?? (existing?.membership_epoch ?? -1) + 1;\n\t\tconst updateStatement = this.db\n\t\t\t.prepare(`UPDATE coordinator_scope_memberships\n\t\t\t\t\t\t SET status = 'revoked',\n\t\t\t\t\t\t\t membership_epoch = CASE WHEN ? IS NULL THEN membership_epoch + 1 ELSE ? END,\n\t\t\t\t\t\t\t manifest_hash = COALESCE(?, manifest_hash),\n\t\t\t\t\t\t\t signed_manifest_json = COALESCE(?, signed_manifest_json),\n\t\t\t\t\t\t\t updated_at = ?\n\t\t\t\t\t\t WHERE scope_id = ? AND device_id = ? AND membership_epoch = ? AND status = ?\n\t\t\t\t\t\t AND NOT EXISTS (\n\t\t\t\t\t\t\tSELECT 1 FROM coordinator_scope_membership_effect_receipts WHERE effect_id = ?\n\t\t\t\t\t\t )`)\n\t\t\t.bind(\n\t\t\t\tmembershipEpoch,\n\t\t\t\tmembershipEpoch,\n\t\t\t\tclean(opts.manifestHash),\n\t\t\t\tclean(opts.signedManifestJson),\n\t\t\t\tnow,\n\t\t\t\tscopeId,\n\t\t\t\tdeviceId,\n\t\t\t\texisting?.membership_epoch ?? -1,\n\t\t\t\texisting?.status ?? \"\",\n\t\t\t\teffectId,\n\t\t\t);\n\t\tconst receiptStatement = prepareRevokeEffectReceipt(this.db, {\n\t\t\teffectId,\n\t\t\trequestJson,\n\t\t\tscopeId,\n\t\t\tdeviceId,\n\t\t\tcreatedAt: now,\n\t\t});\n\t\tconst auditStatement = prepareMembershipAuditFromCurrentRow(this.db, {\n\t\t\teffectId,\n\t\t\trequestJson,\n\t\t\taction: \"revoke\",\n\t\t\tprevious: existing,\n\t\t\tscopeId,\n\t\t\tdeviceId,\n\t\t\tstatus: \"revoked\",\n\t\t\tmembershipEpoch: revokedEpoch,\n\t\t\tupdatedAt: now,\n\t\t\tactorType: clean(opts.actorType),\n\t\t\tactorId: clean(opts.actorId),\n\t\t\tcreatedAt: now,\n\t\t});\n\t\ttry {\n\t\t\tawait runAuditedBatch(this.db, [updateStatement, receiptStatement, auditStatement]);\n\t\t} catch (err) {\n\t\t\tconst current = await this.getScopeMembership(scopeId, deviceId);\n\t\t\tif (\n\t\t\t\texisting &&\n\t\t\t\t(!current ||\n\t\t\t\t\tcurrent.membership_epoch !== existing.membership_epoch ||\n\t\t\t\t\tcurrent.status !== existing.status)\n\t\t\t) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tthrow err;\n\t\t}\n\t\tconst receipt = await getMembershipEffectReceipt(this.db, effectId);\n\t\tif (!receipt) throw new Error(\"scope membership revoke receipt was not persisted.\");\n\t\tassertMatchingMembershipEffectReceipt(receipt, \"revoke\", requestJson);\n\t\treturn receipt.outcome_applied === 1;\n\t}\n\n\tasync listScopeMemberships(\n\t\tscopeId: string,\n\t\tincludeRevoked = false,\n\t): Promise<CoordinatorScopeMembership[]> {\n\t\tconst normalizedScopeId = clean(scopeId);\n\t\tif (!normalizedScopeId) throw new Error(\"scopeId is required.\");\n\t\tconst statusWhere = includeRevoked ? \"\" : \"AND status = 'active'\";\n\t\treturn (\n\t\t\tawait allRows<CoordinatorScopeMembership>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\t\t\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t\t\t\t\t FROM coordinator_scope_memberships\n\t\t\t\t\t\t WHERE scope_id = ? ${statusWhere}\n\t\t\t\t\t\t ORDER BY device_id ASC`)\n\t\t\t\t\t.bind(normalizedScopeId),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorScopeMembership>(row));\n\t}\n\n\tasync listScopeMembershipAuditEvents(\n\t\topts: CoordinatorListScopeMembershipAuditInput,\n\t): Promise<CoordinatorScopeMembershipAuditEvent[]> {\n\t\tconst scopeId = clean(opts.scopeId);\n\t\tif (!scopeId) throw new Error(\"scopeId is required.\");\n\t\tconst deviceId = clean(opts.deviceId);\n\t\tconst limit = normalizeAuditLimit(opts.limit);\n\t\tconst where = deviceId ? \"scope_id = ? AND device_id = ?\" : \"scope_id = ?\";\n\t\tconst params = deviceId ? [scopeId, deviceId, limit] : [scopeId, limit];\n\t\treturn (\n\t\t\tawait allRows<CoordinatorScopeMembershipAuditEvent>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT event_id, effect_id, action, scope_id, device_id, role, status, membership_epoch,\n\t\t\t\t\t\t\tprevious_role, previous_status, previous_membership_epoch,\n\t\t\t\t\t\t\tcoordinator_id, group_id, actor_type, actor_id, manifest_hash, created_at\n\t\t\t\t\t\t FROM coordinator_scope_membership_audit_log\n\t\t\t\t\t\t WHERE ${where}\n\t\t\t\t\t\t ORDER BY event_id ASC\n\t\t\t\t\t\t LIMIT ?`)\n\t\t\t\t\t.bind(...params),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorScopeMembershipAuditEvent>(row));\n\t}\n\n\tasync getBootstrapGrant(grantId: string): Promise<CoordinatorBootstrapGrant | null> {\n\t\tconst row = await firstRow<CoordinatorBootstrapGrant>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n\t\t\t\t\t FROM coordinator_bootstrap_grants WHERE grant_id = ?`)\n\t\t\t\t.bind(grantId),\n\t\t);\n\t\treturn row ? rowToRecord<CoordinatorBootstrapGrant>(row) : null;\n\t}\n\n\tasync listBootstrapGrants(groupId: string): Promise<CoordinatorBootstrapGrant[]> {\n\t\treturn (\n\t\t\tawait allRows<CoordinatorBootstrapGrant>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n\t\t\t\t\t\t FROM coordinator_bootstrap_grants WHERE group_id = ?\n\t\t\t\t\t\t ORDER BY created_at DESC, grant_id DESC`)\n\t\t\t\t\t.bind(groupId),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorBootstrapGrant>(row));\n\t}\n\n\tasync revokeBootstrapGrant(grantId: string, revokedAt = nowISO()): Promise<boolean> {\n\t\treturn (\n\t\t\t(await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_bootstrap_grants\n\t\t\t\t\t\t SET revoked_at = COALESCE(revoked_at, ?)\n\t\t\t\t\t\t WHERE grant_id = ?`)\n\t\t\t\t\t.bind(revokedAt, grantId),\n\t\t\t)) > 0\n\t\t);\n\t}\n\n\tasync listReciprocalApprovals(\n\t\topts: CoordinatorListReciprocalApprovalsInput,\n\t): Promise<CoordinatorReciprocalApproval[]> {\n\t\tconst directionColumn =\n\t\t\topts.direction === \"incoming\" ? \"requested_device_id\" : \"requesting_device_id\";\n\t\tconst status = opts.status?.trim() || \"pending\";\n\t\treturn (\n\t\t\tawait allRows<CoordinatorReciprocalApproval>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t\t FROM coordinator_reciprocal_approvals\n\t\t\t\t\t\t WHERE group_id = ? AND ${directionColumn} = ? AND status = ?\n\t\t\t\t\t\t ORDER BY created_at ASC, request_id ASC`)\n\t\t\t\t\t.bind(opts.groupId, opts.deviceId, status),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorReciprocalApproval>(row));\n\t}\n\n\tasync upsertPresence(_opts: CoordinatorUpsertPresenceInput): Promise<CoordinatorPresenceRecord> {\n\t\tconst now = new Date();\n\t\tconst expiresAt = new Date(now.getTime() + _opts.ttlS * 1000).toISOString();\n\t\tconst normalized = mergeAddresses([], _opts.addresses);\n\t\tawait this.db\n\t\t\t.prepare(`INSERT INTO presence_records(group_id, device_id, addresses_json, last_seen_at, expires_at, capabilities_json)\n\t\t\t\t VALUES (?, ?, ?, ?, ?, ?)\n\t\t\t\t ON CONFLICT(group_id, device_id) DO UPDATE SET\n\t\t\t\t\taddresses_json = excluded.addresses_json,\n\t\t\t\t\tlast_seen_at = excluded.last_seen_at,\n\t\t\t\t\texpires_at = excluded.expires_at,\n\t\t\t\t\tcapabilities_json = excluded.capabilities_json`)\n\t\t\t.bind(\n\t\t\t\t_opts.groupId,\n\t\t\t\t_opts.deviceId,\n\t\t\t\tJSON.stringify(normalized),\n\t\t\t\tnow.toISOString(),\n\t\t\t\texpiresAt,\n\t\t\t\tJSON.stringify(_opts.capabilities ?? {}),\n\t\t\t)\n\t\t\t.run();\n\t\treturn {\n\t\t\tgroup_id: _opts.groupId,\n\t\t\tdevice_id: _opts.deviceId,\n\t\t\taddresses: normalized,\n\t\t\texpires_at: expiresAt,\n\t\t};\n\t}\n\n\tasync listGroupPeers(\n\t\t_groupId: string,\n\t\t_requestingDeviceId: string,\n\t): Promise<CoordinatorPeerRecord[]> {\n\t\tconst now = nowISO();\n\t\tconst rows = await allRows<Record<string, unknown>>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT enrolled_devices.device_id, enrolled_devices.public_key, enrolled_devices.fingerprint, enrolled_devices.display_name,\n\t\t\t\t\t\tpresence_records.addresses_json, presence_records.last_seen_at, presence_records.expires_at,\n\t\t\t\t\t\tpresence_records.capabilities_json\n\t\t\t\t\t FROM enrolled_devices\n\t\t\t\t\t LEFT JOIN presence_records\n\t\t\t\t\t ON presence_records.group_id = enrolled_devices.group_id\n\t\t\t\t\t AND presence_records.device_id = enrolled_devices.device_id\n\t\t\t\t\t WHERE enrolled_devices.group_id = ?\n\t\t\t\t\t AND enrolled_devices.enabled = 1\n\t\t\t\t\t AND enrolled_devices.device_id != ?\n\t\t\t\t\t ORDER BY enrolled_devices.device_id ASC`)\n\t\t\t\t.bind(_groupId, _requestingDeviceId),\n\t\t);\n\t\treturn rows.map((row) => {\n\t\t\tconst expiresRaw = String(row.expires_at ?? \"\").trim();\n\t\t\tlet stale = true;\n\t\t\tif (expiresRaw) {\n\t\t\t\tconst expiresAt = new Date(expiresRaw);\n\t\t\t\tstale = Number.isNaN(expiresAt.getTime()) || expiresAt.toISOString() <= now;\n\t\t\t}\n\t\t\tconst addresses = stale\n\t\t\t\t? []\n\t\t\t\t: mergeAddresses([], JSON.parse(String(row.addresses_json ?? \"[]\")) as string[]);\n\t\t\treturn {\n\t\t\t\tdevice_id: String(row.device_id ?? \"\"),\n\t\t\t\tpublic_key: String(row.public_key ?? \"\"),\n\t\t\t\tfingerprint: String(row.fingerprint ?? \"\"),\n\t\t\t\tdisplay_name: (row.display_name as string | null) ?? null,\n\t\t\t\taddresses,\n\t\t\t\tlast_seen_at: (row.last_seen_at as string | null) ?? null,\n\t\t\t\texpires_at: (row.expires_at as string | null) ?? null,\n\t\t\t\tstale,\n\t\t\t\tcapabilities: JSON.parse(String(row.capabilities_json ?? \"{}\")) as Record<string, unknown>,\n\t\t\t} satisfies CoordinatorPeerRecord;\n\t\t});\n\t}\n}\n","import {\n\ttype CoordinatorRequestVerifier,\n\ttype CoordinatorRuntimeDeps,\n\tcreateCoordinatorApp,\n} from \"./coordinator-api.js\";\nimport { D1CoordinatorStore, type D1DatabaseLike } from \"./d1-coordinator-store.js\";\n\nexport interface CreateD1CoordinatorAppOptions {\n\tdb: D1DatabaseLike;\n\tadminSecret?: string | null;\n\tnow?: () => string;\n\trequestVerifier: CoordinatorRequestVerifier;\n}\n\nexport function createD1CoordinatorApp(\n\topts: CreateD1CoordinatorAppOptions,\n): ReturnType<typeof createCoordinatorApp> {\n\tconst runtime: CoordinatorRuntimeDeps = {\n\t\tadminSecret: () => String(opts.adminSecret ?? \"\").trim() || null,\n\t\tnow: opts.now ?? (() => new Date().toISOString()),\n\t};\n\treturn createCoordinatorApp({\n\t\tstoreFactory: () => new D1CoordinatorStore(opts.db),\n\t\truntime,\n\t\trequestVerifier: opts.requestVerifier,\n\t});\n}\n"],"mappings":";;AAuFA,SAAS,EAAe,GAAiB;CACxC,IAAI,KAAO,MAAM,MAAU,MAAM,cAAc;CAC/C,OAAO;AACR;AAEA,SAAS,EAA4B,GAAqC;CAEzE,IAAM,EACL,4BAA4B,GAC5B,qBAAqB,GACrB,GAAG,MAJW,EAAqC,CAKhD;CACJ,IAAI,OAAO,KAAc,YAAY,OAAO,KAAqB,UAChE,OAAO;CAER,IAAI;EACH,IAAM,IAAe,KAAK,MAAM,CAAgB;EAChD,IAAI,CAAC,KAAgB,OAAO,KAAiB,YAAY,MAAM,QAAQ,CAAY,GAClF,OAAO;EAER,IAAM,IAAmB;EACzB,OAAO;GACN,GAAI;GACJ,qBAAqB;GACrB,uBAAuB;IACtB,iBAAiB,EAAiB;IAClC,eAAe,EAAiB;GACjC;EACD;CACD,QAAQ;EACP,OAAO;CACR;AACD;AAEA,SAAS,EAAiB,GAAyB;CAClD,IAAM,IAAQ,EAAQ,KAAK;CAC3B,IAAI,CAAC,GAAO,OAAO;CACnB,IAAM,IAAa,EAAM,SAAS,KAAK,IAAI,IAAQ,UAAU;CAC7D,IAAI;EACH,IAAM,IAAM,IAAI,IA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GAAG,KAAK,MAAM,OAAO,EAAI,kBAAkB,IAAI,CAAC,CAAa;GAChF,OAAO;IACN,WAAW,OAAO,EAAI,aAAa,EAAE;IACrC,YAAY,OAAO,EAAI,cAAc,EAAE;IACvC,aAAa,OAAO,EAAI,eAAe,EAAE;IACzC,cAAe,EAAI,gBAAkC;IACrD;IACA,cAAe,EAAI,gBAAkC;IACrD,YAAa,EAAI,cAAgC;IACjD;IACA,cAAc,KAAK,MAAM,OAAO,EAAI,qBAAqB,IAAI,CAAC;GAC/D;EACD,CAAC;CACF;AACD;;;ACxxEA,SAAgB,EACf,GAC0C;CAK1C,OAAO,EAAqB;EAC3B,oBAAoB,IAAI,EAAmB,EAAK,EAAE;EAClD,SAAA;GALA,mBAAmB,OAAO,EAAK,eAAe,EAAE,EAAE,KAAK,KAAK;GAC5D,KAAK,EAAK,+BAAc,IAAI,KAAK,GAAE,YAAY;EAI/C;EACA,iBAAiB,EAAK;CACvB,CAAC;AACF"}
1
+ {"version":3,"file":"cloudflare-coordinator.js","names":[],"sources":["../../src/d1-coordinator-store.ts","../../src/d1-coordinator-runtime.ts"],"sourcesContent":["import type {\n\tCoordinatorLegacyTeamCompletionManifestV1,\n\tCoordinatorLegacyTeamCompletionRecord,\n\tCoordinatorLegacyTeamCompletionScopeBinding,\n\tCoordinatorLegacyTeamCompletionWriteResult,\n} from \"./coordinator-legacy-team-completion.js\";\nimport {\n\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES,\n\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES,\n\tCOORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS,\n\tCoordinatorLegacyTeamCompletionConflictError,\n\tcanonicalCoordinatorLegacyTeamCompletionManifestJson,\n\tnormalizeCoordinatorLegacyTeamCompletionCandidateRef,\n\tnormalizeCoordinatorLegacyTeamCompletionGroupIds,\n\tnormalizeCoordinatorLegacyTeamCompletionManifest,\n\trequireCoordinatorLegacyTeamCompletionScopeBindings,\n\trequireCoordinatorLegacyTeamCompletionTeamBinding,\n} from \"./coordinator-legacy-team-completion.js\";\nimport {\n\tassertMatchingMembershipEffectReceipt,\n\ttype CoordinatorMembershipEffectReceipt,\n\tCoordinatorMembershipError,\n\tgrantMembershipEffectRequestJson,\n\tmembershipFromEffectReceipt,\n\tnormalizeMembershipEffectId,\n\trevokeMembershipEffectRequestJson,\n} from \"./coordinator-membership-effects.js\";\nimport type {\n\tCoordinatorBootstrapGrant,\n\tCoordinatorConsumeProjectInviteInput,\n\tCoordinatorConsumeRecipientInviteInput,\n\tCoordinatorCreateBootstrapGrantInput,\n\tCoordinatorCreateInviteInput,\n\tCoordinatorCreateJoinRequestInput,\n\tCoordinatorCreateReciprocalApprovalInput,\n\tCoordinatorCreateScopeInput,\n\tCoordinatorEnrollDeviceInput,\n\tCoordinatorEnrollment,\n\tCoordinatorGrantScopeMembershipInput,\n\tCoordinatorGroup,\n\tCoordinatorInspectRecipientInviteInput,\n\tCoordinatorInvite,\n\tCoordinatorInviteKind,\n\tCoordinatorJoinRequest,\n\tCoordinatorJoinRequestReviewResult,\n\tCoordinatorListReciprocalApprovalsInput,\n\tCoordinatorListScopeMembershipAuditInput,\n\tCoordinatorListScopesInput,\n\tCoordinatorPeerRecord,\n\tCoordinatorPresenceRecord,\n\tCoordinatorProjectInviteAcceptance,\n\tCoordinatorRecipientInviteAcceptance,\n\tCoordinatorRecipientInviteInspection,\n\tCoordinatorReciprocalApproval,\n\tCoordinatorReviewJoinRequestBootstrapGrantInput,\n\tCoordinatorReviewJoinRequestInput,\n\tCoordinatorRevokeScopeMembershipInput,\n\tCoordinatorScope,\n\tCoordinatorScopeMembership,\n\tCoordinatorScopeMembershipAuditEvent,\n\tCoordinatorStore,\n\tCoordinatorUpdateScopeInput,\n\tCoordinatorUpsertPresenceInput,\n} from \"./coordinator-store-contract.js\";\nimport {\n\tCoordinatorReciprocalApprovalRequestChangedError,\n\tisCoordinatorAssignedIdentityId,\n\tnormalizeInviteExpiresAt,\n\trecipientInviteAuthoritativeIdentityId,\n} from \"./coordinator-store-contract.js\";\nimport {\n\tcanonicalRecipientReviewedIntentJson,\n\tparseStoredRecipientReviewedIntent,\n\ttype RecipientReviewedIntentTargetV1,\n\tverifyRecipientReviewedIntent,\n} from \"./recipient-reviewed-intent.js\";\nimport { fingerprintPublicKey } from \"./sync-fingerprint.js\";\n\ninterface D1RunResultLike {\n\tmeta?: {\n\t\tchanges?: number;\n\t};\n}\n\n/**\n * Experimental D1 adapter scaffold.\n *\n * This is intentionally internal for now while the sync-only store contract\n * is still being validated against an async backend shape.\n */\n\nexport interface D1PreparedStatementLike {\n\tbind(...values: unknown[]): D1PreparedStatementLike;\n\tfirst<T = unknown>(): Promise<T | null>;\n\trun(): Promise<unknown>;\n\tall<T = unknown>(): Promise<{ results?: T[] }>;\n\traw<T = unknown>(): Promise<T[]>;\n}\n\nexport interface D1DatabaseLike {\n\tprepare(query: string): D1PreparedStatementLike;\n\tbatch?(statements: D1PreparedStatementLike[]): Promise<unknown[]>;\n\texec?(query: string): Promise<unknown>;\n}\n\nfunction rowToRecord<T>(row: unknown): T {\n\tif (row == null) throw new Error(\"expected row\");\n\treturn row as T;\n}\n\nfunction rowToEnrollmentWithPresence(row: unknown): CoordinatorEnrollment {\n\tconst record = rowToRecord<Record<string, unknown>>(row);\n\tconst {\n\t\tpresence_capabilities_json: capabilitiesJson,\n\t\tpresence_expires_at: expiresAt,\n\t\t...base\n\t} = record;\n\tif (typeof expiresAt !== \"string\" || typeof capabilitiesJson !== \"string\") {\n\t\treturn base as unknown as CoordinatorEnrollment;\n\t}\n\ttry {\n\t\tconst capabilities = JSON.parse(capabilitiesJson) as unknown;\n\t\tif (!capabilities || typeof capabilities !== \"object\" || Array.isArray(capabilities)) {\n\t\t\treturn base as unknown as CoordinatorEnrollment;\n\t\t}\n\t\tconst capabilityRecord = capabilities as Record<string, unknown>;\n\t\treturn {\n\t\t\t...(base as unknown as CoordinatorEnrollment),\n\t\t\tpresence_expires_at: expiresAt,\n\t\t\tpresence_capabilities: {\n\t\t\t\tsync_capability: capabilityRecord.sync_capability,\n\t\t\t\tsync_features: capabilityRecord.sync_features,\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn base as unknown as CoordinatorEnrollment;\n\t}\n}\n\nfunction normalizeAddress(address: string): string {\n\tconst value = address.trim();\n\tif (!value) return \"\";\n\tconst withScheme = value.includes(\"://\") ? value : `http://${value}`;\n\ttry {\n\t\tconst url = new URL(withScheme);\n\t\tif (!url.hostname) return \"\";\n\t\tif (url.port && (Number(url.port) <= 0 || Number(url.port) > 65535)) return \"\";\n\t\treturn url.origin + url.pathname.replace(/\\/+$/, \"\");\n\t} catch {\n\t\treturn \"\";\n\t}\n}\n\nfunction addressDedupeKey(address: string): string {\n\tif (!address) return \"\";\n\ttry {\n\t\tconst parsed = new URL(address);\n\t\tconst host = parsed.hostname.toLowerCase();\n\t\tif (\n\t\t\t(parsed.protocol === \"http:\" || parsed.protocol === \"\") &&\n\t\t\thost &&\n\t\t\tparsed.port &&\n\t\t\tparsed.pathname === \"/\"\n\t\t) {\n\t\t\treturn `${host}:${parsed.port}`;\n\t\t}\n\t} catch {}\n\treturn address;\n}\n\nfunction mergeAddresses(existing: string[], candidates: string[]): string[] {\n\tconst normalized: string[] = [];\n\tconst seen = new Set<string>();\n\tfor (const address of [...existing, ...candidates]) {\n\t\tconst cleaned = normalizeAddress(address);\n\t\tconst key = addressDedupeKey(cleaned);\n\t\tif (!cleaned || seen.has(key)) continue;\n\t\tseen.add(key);\n\t\tnormalized.push(cleaned);\n\t}\n\treturn normalized;\n}\n\nfunction nowISO(): string {\n\treturn new Date().toISOString();\n}\n\nfunction reciprocalPendingPair(\n\trequestingDeviceId: string,\n\trequestedDeviceId: string,\n): {\n\tlow: string;\n\thigh: string;\n} {\n\treturn requestingDeviceId <= requestedDeviceId\n\t\t? { low: requestingDeviceId, high: requestedDeviceId }\n\t\t: { low: requestedDeviceId, high: requestingDeviceId };\n}\n\nfunction isUniqueConstraintError(error: unknown): boolean {\n\treturn error instanceof Error && /unique|constraint/i.test(error.message);\n}\n\nfunction tokenUrlSafe(bytes: number): string {\n\tconst alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\n\tconst random = new Uint8Array(bytes);\n\tglobalThis.crypto.getRandomValues(random);\n\tconst output: string[] = [];\n\tfor (const byte of random) {\n\t\toutput.push(alphabet[byte % alphabet.length] ?? \"A\");\n\t}\n\treturn output.join(\"\");\n}\n\nasync function tokenDigest(token: string): Promise<string> {\n\tconst digest = await globalThis.crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(token));\n\treturn Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\nconst INVITE_COLUMNS = `invite_id, group_id, token, policy, expires_at, created_at, created_by,\n\tteam_name_snapshot, revoked_at, operation_id, reviewed_project_set_digest, token_digest,\n\tinviter_actor_id, inviter_display_name, inviter_device_id, pending_person_id,\n\tproject_summaries_json, project_intent_json, consumed_at, bound_device_id, bound_public_key, bound_fingerprint,\n\trecipient_actor_id, recipient_display_name, recipient_device_display_name, trust_state,\n\tbootstrap_grant_id, invite_kind, policy_team_id, target_identity_id, assigned_identity_id,\n\treviewed_preview_digest, reviewed_intent_json`;\n\nconst ENROLLMENT_COLUMNS =\n\t\"group_id, device_id, public_key, fingerprint, identity_id, display_name, enabled, created_at\";\n\nconst ENROLLMENT_PRESENCE_COLUMNS = `enrolled_devices.group_id, enrolled_devices.device_id,\n\tenrolled_devices.public_key, enrolled_devices.fingerprint, enrolled_devices.identity_id,\n\tenrolled_devices.display_name, enrolled_devices.enabled, enrolled_devices.created_at,\n\tpresence_records.expires_at AS presence_expires_at,\n\tpresence_records.capabilities_json AS presence_capabilities_json`;\n\nfunction requireTrimmedBootstrapGrantInput(opts: CoordinatorCreateBootstrapGrantInput): {\n\tgroupId: string;\n\tseedDeviceId: string;\n\tworkerDeviceId: string;\n\texpiresAt: string;\n\tcreatedBy: string | null;\n} {\n\tconst groupId = String(opts.groupId ?? \"\").trim();\n\tconst seedDeviceId = String(opts.seedDeviceId ?? \"\").trim();\n\tconst workerDeviceId = String(opts.workerDeviceId ?? \"\").trim();\n\tconst expiresAt = String(opts.expiresAt ?? \"\").trim();\n\tconst createdBy = String(opts.createdBy ?? \"\").trim() || null;\n\tif (!groupId || !seedDeviceId || !workerDeviceId || !expiresAt) {\n\t\tthrow new Error(\"groupId, seedDeviceId, workerDeviceId, and expiresAt are required.\");\n\t}\n\treturn { groupId, seedDeviceId, workerDeviceId, expiresAt, createdBy };\n}\n\nfunction clean(value: string | null | undefined): string | null {\n\tconst trimmed = value?.trim();\n\treturn trimmed ? trimmed : null;\n}\n\nasync function normalizeInviteMetadata(opts: CoordinatorCreateInviteInput): Promise<{\n\tinviteKind: CoordinatorInviteKind;\n\tpolicyTeamId: string | null;\n\ttargetIdentityId: string | null;\n\treviewedPreviewDigest: string | null;\n\treviewedIntentJson: string | null;\n}> {\n\tconst inviteKind =\n\t\topts.inviteKind ?? (clean(opts.operationId) ? \"project_share\" : \"legacy_enrollment\");\n\tconst policyTeamId = clean(opts.policyTeamId);\n\tconst targetIdentityId = clean(opts.targetIdentityId);\n\tconst reviewedPreviewDigest = clean(opts.reviewedPreviewDigest);\n\tif (\n\t\t!([\"legacy_enrollment\", \"project_share\", \"team_member\", \"add_device\"] as const).includes(\n\t\t\tinviteKind,\n\t\t)\n\t) {\n\t\tthrow new Error(\"inviteKind is invalid.\");\n\t}\n\tif (\n\t\t[policyTeamId, targetIdentityId]\n\t\t\t.filter((value): value is string => Boolean(value))\n\t\t\t.some((value) => value.length > 256 || /[\\p{Cc}\\p{Cf}]/u.test(value))\n\t) {\n\t\tthrow new Error(\"recipient invite identifier is invalid.\");\n\t}\n\tif (reviewedPreviewDigest && !/^[a-f0-9]{64}$/u.test(reviewedPreviewDigest)) {\n\t\tthrow new Error(\"reviewedPreviewDigest must be a SHA-256 digest.\");\n\t}\n\tif (inviteKind === \"project_share\") {\n\t\tif (!clean(opts.operationId)) throw new Error(\"project_share invite requires operationId.\");\n\t\tif (policyTeamId || targetIdentityId || reviewedPreviewDigest) {\n\t\t\tthrow new Error(\"recipient invite metadata requires a recipient invite kind.\");\n\t\t}\n\t} else if (inviteKind === \"legacy_enrollment\") {\n\t\tif (clean(opts.operationId))\n\t\t\tthrow new Error(\"legacy_enrollment invite cannot reference an operation.\");\n\t\tif (policyTeamId || targetIdentityId || reviewedPreviewDigest) {\n\t\t\tthrow new Error(\"recipient invite metadata requires a recipient invite kind.\");\n\t\t}\n\t} else if (inviteKind === \"team_member\") {\n\t\tif (!policyTeamId || !reviewedPreviewDigest || targetIdentityId || clean(opts.operationId)) {\n\t\t\tthrow new Error(\"team_member invite metadata is invalid.\");\n\t\t}\n\t} else if (inviteKind === \"add_device\") {\n\t\tif (!targetIdentityId || !reviewedPreviewDigest || policyTeamId || clean(opts.operationId)) {\n\t\t\tthrow new Error(\"add_device invite metadata is invalid.\");\n\t\t}\n\t}\n\tconst reviewedIntentProvided = opts.reviewedIntent !== undefined && opts.reviewedIntent !== null;\n\tif (!reviewedIntentProvided) {\n\t\tif (inviteKind === \"team_member\" || inviteKind === \"add_device\") {\n\t\t\tthrow new Error(\"recipient_invite_review_unavailable\");\n\t\t}\n\t\treturn {\n\t\t\tinviteKind,\n\t\t\tpolicyTeamId,\n\t\t\ttargetIdentityId,\n\t\t\treviewedPreviewDigest,\n\t\t\treviewedIntentJson: null,\n\t\t};\n\t}\n\tlet target: RecipientReviewedIntentTargetV1;\n\tif (inviteKind === \"team_member\" && policyTeamId && reviewedPreviewDigest) {\n\t\ttarget = { kind: \"team_member\", policyTeamId };\n\t} else if (inviteKind === \"add_device\" && targetIdentityId && reviewedPreviewDigest) {\n\t\ttarget = { kind: \"add_device\", targetIdentityId };\n\t} else {\n\t\tthrow new Error(\"recipient invite metadata requires a recipient invite kind.\");\n\t}\n\tawait verifyRecipientReviewedIntent(opts.reviewedIntent, {\n\t\ttarget,\n\t\tdigest: reviewedPreviewDigest,\n\t});\n\treturn {\n\t\tinviteKind,\n\t\tpolicyTeamId,\n\t\ttargetIdentityId,\n\t\treviewedPreviewDigest,\n\t\treviewedIntentJson: canonicalRecipientReviewedIntentJson(opts.reviewedIntent, target),\n\t};\n}\n\nasync function recipientInspection(\n\tinvite: CoordinatorInvite,\n): Promise<CoordinatorRecipientInviteInspection | null> {\n\tif (invite.invite_kind === \"team_member\") {\n\t\tif (\n\t\t\t!invite.policy_team_id ||\n\t\t\t!isCoordinatorAssignedIdentityId(invite.assigned_identity_id) ||\n\t\t\t!invite.reviewed_preview_digest\n\t\t)\n\t\t\tthrow new Error(\"invite_invalid\");\n\t\tconst reviewedIntent = await parseStoredRecipientReviewedIntent(invite.reviewed_intent_json, {\n\t\t\ttarget: { kind: \"team_member\", policyTeamId: invite.policy_team_id },\n\t\t\tdigest: invite.reviewed_preview_digest,\n\t\t});\n\t\treturn {\n\t\t\tkind: \"team_member\",\n\t\t\tinvite,\n\t\t\tpolicy_team_id: invite.policy_team_id,\n\t\t\tassigned_identity_id: invite.assigned_identity_id,\n\t\t\treviewed_preview_digest: invite.reviewed_preview_digest,\n\t\t\treviewed_intent: reviewedIntent,\n\t\t\tbound: Boolean(invite.consumed_at),\n\t\t};\n\t}\n\tif (invite.invite_kind === \"add_device\") {\n\t\tif (!invite.target_identity_id || !invite.reviewed_preview_digest)\n\t\t\tthrow new Error(\"invite_invalid\");\n\t\tconst reviewedIntent = await parseStoredRecipientReviewedIntent(invite.reviewed_intent_json, {\n\t\t\ttarget: { kind: \"add_device\", targetIdentityId: invite.target_identity_id },\n\t\t\tdigest: invite.reviewed_preview_digest,\n\t\t});\n\t\treturn {\n\t\t\tkind: \"add_device\",\n\t\t\tinvite,\n\t\t\ttarget_identity_id: invite.target_identity_id,\n\t\t\treviewed_preview_digest: invite.reviewed_preview_digest,\n\t\t\treviewed_intent: reviewedIntent,\n\t\t\tbound: Boolean(invite.consumed_at),\n\t\t};\n\t}\n\treturn null;\n}\n\nfunction normalizeEpoch(value: number | null | undefined, fallback = 0): number {\n\tif (value == null) return fallback;\n\tif (!Number.isFinite(value) || value < 0)\n\t\tthrow new Error(\"membershipEpoch must be non-negative.\");\n\treturn Math.trunc(value);\n}\n\nfunction normalizeCreateScopeInput(opts: CoordinatorCreateScopeInput) {\n\tconst scopeId = clean(opts.scopeId);\n\tconst label = clean(opts.label);\n\tif (!scopeId || !label) throw new Error(\"scopeId and label are required.\");\n\treturn {\n\t\tscopeId,\n\t\tlabel,\n\t\tkind: clean(opts.kind) ?? \"user\",\n\t\tauthorityType: clean(opts.authorityType) ?? \"coordinator\",\n\t\tcoordinatorId: clean(opts.coordinatorId),\n\t\tgroupId: clean(opts.groupId),\n\t\tmanifestIssuerDeviceId: clean(opts.manifestIssuerDeviceId),\n\t\tmembershipEpoch: normalizeEpoch(opts.membershipEpoch),\n\t\tmanifestHash: clean(opts.manifestHash),\n\t\tstatus: clean(opts.status) ?? \"active\",\n\t};\n}\n\nfunction cleanRequiredUpdate(\n\tvalue: string | null | undefined,\n\tcurrent: string,\n\tfieldName: string,\n): string {\n\tif (value === undefined) return current;\n\tconst cleaned = clean(value);\n\tif (!cleaned) throw new Error(`${fieldName} must not be empty.`);\n\treturn cleaned;\n}\n\nfunction cleanNullableUpdate(\n\tvalue: string | null | undefined,\n\tcurrent: string | null,\n): string | null {\n\treturn value === undefined ? current : clean(value);\n}\n\nfunction normalizeUpdateScopeInput(opts: CoordinatorUpdateScopeInput, existing: CoordinatorScope) {\n\tconst scopeId = clean(opts.scopeId);\n\tif (!scopeId) throw new Error(\"scopeId is required.\");\n\tconst requestedEpoch = opts.membershipEpoch == null ? null : normalizeEpoch(opts.membershipEpoch);\n\tif (requestedEpoch != null && requestedEpoch < existing.membership_epoch) {\n\t\tthrow new Error(\"membershipEpoch must not move backwards.\");\n\t}\n\treturn {\n\t\tscopeId,\n\t\tlabel: cleanRequiredUpdate(opts.label, existing.label, \"label\"),\n\t\tkind: cleanRequiredUpdate(opts.kind, existing.kind, \"kind\"),\n\t\tauthorityType: cleanRequiredUpdate(\n\t\t\topts.authorityType,\n\t\t\texisting.authority_type,\n\t\t\t\"authorityType\",\n\t\t),\n\t\tcoordinatorId: cleanNullableUpdate(opts.coordinatorId, existing.coordinator_id),\n\t\tgroupId: cleanNullableUpdate(opts.groupId, existing.group_id),\n\t\tmanifestIssuerDeviceId: cleanNullableUpdate(\n\t\t\topts.manifestIssuerDeviceId,\n\t\t\texisting.manifest_issuer_device_id,\n\t\t),\n\t\tmembershipEpoch: requestedEpoch ?? existing.membership_epoch,\n\t\tmanifestHash: cleanNullableUpdate(opts.manifestHash, existing.manifest_hash),\n\t\tstatus: cleanRequiredUpdate(opts.status, existing.status, \"status\"),\n\t};\n}\n\nfunction normalizeGrantInput(\n\topts: CoordinatorGrantScopeMembershipInput,\n\tscope: CoordinatorScope | null,\n\texisting: CoordinatorScopeMembership | null,\n) {\n\tconst scopeId = clean(opts.scopeId);\n\tconst deviceId = clean(opts.deviceId);\n\tif (!scopeId || !deviceId) throw new Error(\"scopeId and deviceId are required.\");\n\tconst coordinatorId = clean(opts.coordinatorId);\n\tconst groupId = clean(opts.groupId);\n\tif (coordinatorId && coordinatorId !== scope?.coordinator_id) {\n\t\tthrow new Error(\"membership coordinatorId must match the scope coordinatorId.\");\n\t}\n\tif (groupId && groupId !== scope?.group_id) {\n\t\tthrow new CoordinatorMembershipError(\"scope_group_mismatch\");\n\t}\n\tconst requestedEpoch = opts.membershipEpoch == null ? null : normalizeEpoch(opts.membershipEpoch);\n\tconst inheritedEpoch = scope?.membership_epoch ?? 0;\n\tif (requestedEpoch != null && requestedEpoch < inheritedEpoch) {\n\t\tthrow new Error(\"membershipEpoch must not be lower than the scope membershipEpoch.\");\n\t}\n\tif (requestedEpoch != null && existing) {\n\t\tconst minimumEpoch =\n\t\t\texisting.status === \"revoked\" ? existing.membership_epoch + 1 : existing.membership_epoch;\n\t\tif (requestedEpoch < minimumEpoch) {\n\t\t\tthrow new Error(\"membershipEpoch must not move backwards.\");\n\t\t}\n\t}\n\tconst membershipEpoch =\n\t\trequestedEpoch ??\n\t\t(existing\n\t\t\t? Math.max(\n\t\t\t\t\tinheritedEpoch,\n\t\t\t\t\texisting.membership_epoch + (existing.status === \"revoked\" ? 1 : 0),\n\t\t\t\t)\n\t\t\t: inheritedEpoch);\n\treturn {\n\t\tscopeId,\n\t\tdeviceId,\n\t\trole: clean(opts.role) ?? \"member\",\n\t\tmembershipEpoch,\n\t\tcoordinatorId: scope?.coordinator_id ?? null,\n\t\tgroupId: scope?.group_id ?? null,\n\t\tmanifestIssuerDeviceId:\n\t\t\tclean(opts.manifestIssuerDeviceId) ?? scope?.manifest_issuer_device_id ?? null,\n\t\tmanifestHash: clean(opts.manifestHash) ?? scope?.manifest_hash ?? null,\n\t\tsignedManifestJson: clean(opts.signedManifestJson),\n\t\tactorType: clean(opts.actorType),\n\t\tactorId: clean(opts.actorId),\n\t};\n}\n\nfunction normalizeAuditLimit(limit: number | null | undefined): number {\n\tif (limit == null) return 100;\n\tif (!Number.isFinite(limit)) return 100;\n\treturn Math.max(1, Math.min(1000, Math.trunc(limit)));\n}\n\nfunction prepareMembershipAuditFromCurrentRow(\n\tdb: D1DatabaseLike,\n\tinput: {\n\t\teffectId: string;\n\t\trequestJson: string;\n\t\taction: \"grant\" | \"revoke\";\n\t\tprevious: CoordinatorScopeMembership | null;\n\t\tscopeId: string;\n\t\tdeviceId: string;\n\t\tstatus: string;\n\t\tmembershipEpoch: number;\n\t\tupdatedAt: string;\n\t\tactorType: string | null;\n\t\tactorId: string | null;\n\t\tcreatedAt: string;\n\t},\n): D1PreparedStatementLike {\n\t// The immediately preceding statement inserts the immutable effect receipt.\n\t// changes() therefore emits an audit row only for the request that won the\n\t// receipt insert, while outcome_applied excludes persisted no-op revokes.\n\treturn db\n\t\t.prepare(`INSERT INTO coordinator_scope_membership_audit_log(\n\t\t\teffect_id, action, scope_id, device_id, role, status, membership_epoch,\n\t\t\tprevious_role, previous_status, previous_membership_epoch,\n\t\t\tcoordinator_id, group_id, actor_type, actor_id, manifest_hash, created_at\n\t\t)\n\t\tSELECT receipt.effect_id, ?, membership.scope_id, membership.device_id, membership.role, membership.status,\n\t\t\tmembership.membership_epoch, ?, ?, ?, membership.coordinator_id, membership.group_id,\n\t\t\t?, ?, membership.manifest_hash, ?\n\t\tFROM (SELECT 1 WHERE changes() > 0) AS required\n\t\tJOIN coordinator_scope_membership_effect_receipts AS receipt\n\t\t\tON receipt.effect_id = ? AND receipt.action = ? AND receipt.request_json = ?\n\t\t\tAND receipt.outcome_applied = 1\n\t\tLEFT JOIN coordinator_scope_memberships AS membership\n\t\t\tON membership.scope_id = ?\n\t\t\tAND membership.device_id = ?\n\t\t\tAND membership.status = ?\n\t\t\tAND membership.membership_epoch = ?\n\t\t\tAND membership.updated_at = ?`)\n\t\t.bind(\n\t\t\tinput.action,\n\t\t\tinput.previous?.role ?? null,\n\t\t\tinput.previous?.status ?? null,\n\t\t\tinput.previous?.membership_epoch ?? null,\n\t\t\tinput.actorType,\n\t\t\tinput.actorId,\n\t\t\tinput.createdAt,\n\t\t\tinput.effectId,\n\t\t\tinput.action,\n\t\t\tinput.requestJson,\n\t\t\tinput.scopeId,\n\t\t\tinput.deviceId,\n\t\t\tinput.status,\n\t\t\tinput.membershipEpoch,\n\t\t\tinput.updatedAt,\n\t\t);\n}\n\nasync function getMembershipEffectReceipt(\n\tdb: D1DatabaseLike,\n\teffectId: string,\n): Promise<CoordinatorMembershipEffectReceipt | null> {\n\treturn await firstRow<CoordinatorMembershipEffectReceipt>(\n\t\tdb\n\t\t\t.prepare(`SELECT effect_id, action, request_json, outcome_applied, scope_id, device_id,\n\t\t\t\trole, status, membership_epoch, coordinator_id, group_id, manifest_issuer_device_id,\n\t\t\t\tmanifest_hash, signed_manifest_json, updated_at, created_at\n\t\t\t FROM coordinator_scope_membership_effect_receipts WHERE effect_id = ?`)\n\t\t\t.bind(effectId),\n\t);\n}\n\nfunction prepareGrantEffectReceipt(\n\tdb: D1DatabaseLike,\n\tinput: {\n\t\teffectId: string;\n\t\trequestJson: string;\n\t\tscopeId: string;\n\t\tdeviceId: string;\n\t\tcreatedAt: string;\n\t},\n): D1PreparedStatementLike {\n\treturn db\n\t\t.prepare(`INSERT INTO coordinator_scope_membership_effect_receipts(\n\t\t\teffect_id, action, request_json, outcome_applied, scope_id, device_id,\n\t\t\trole, status, membership_epoch, coordinator_id, group_id, manifest_issuer_device_id,\n\t\t\tmanifest_hash, signed_manifest_json, updated_at, created_at\n\t\t)\n\t\tSELECT ?, 'grant', ?, 1, membership.scope_id, membership.device_id,\n\t\t\tmembership.role, membership.status, membership.membership_epoch,\n\t\t\tmembership.coordinator_id, membership.group_id, membership.manifest_issuer_device_id,\n\t\t\tmembership.manifest_hash, membership.signed_manifest_json, membership.updated_at, ?\n\t\tFROM coordinator_scope_memberships AS membership\n\t\tWHERE changes() > 0 AND membership.scope_id = ? AND membership.device_id = ?`)\n\t\t.bind(input.effectId, input.requestJson, input.createdAt, input.scopeId, input.deviceId);\n}\n\nfunction prepareRevokeEffectReceipt(\n\tdb: D1DatabaseLike,\n\tinput: {\n\t\teffectId: string;\n\t\trequestJson: string;\n\t\tscopeId: string;\n\t\tdeviceId: string;\n\t\tcreatedAt: string;\n\t},\n): D1PreparedStatementLike {\n\treturn db\n\t\t.prepare(`INSERT INTO coordinator_scope_membership_effect_receipts(\n\t\t\teffect_id, action, request_json, outcome_applied, scope_id, device_id,\n\t\t\trole, status, membership_epoch, coordinator_id, group_id, manifest_issuer_device_id,\n\t\t\tmanifest_hash, signed_manifest_json, updated_at, created_at\n\t\t)\n\t\tSELECT ?, 'revoke', ?, changed.applied, ?, ?, membership.role, membership.status,\n\t\t\tmembership.membership_epoch, membership.coordinator_id, membership.group_id,\n\t\t\tmembership.manifest_issuer_device_id, membership.manifest_hash,\n\t\t\tmembership.signed_manifest_json, membership.updated_at, ?\n\t\tFROM (SELECT CASE WHEN changes() > 0 THEN 1 ELSE 0 END AS applied) AS changed\n\t\tLEFT JOIN coordinator_scope_memberships AS membership\n\t\t\tON changed.applied = 1 AND membership.scope_id = ? AND membership.device_id = ?\n\t\tWHERE NOT EXISTS (\n\t\t\tSELECT 1 FROM coordinator_scope_membership_effect_receipts WHERE effect_id = ?\n\t\t)`)\n\t\t.bind(\n\t\t\tinput.effectId,\n\t\t\tinput.requestJson,\n\t\t\tinput.scopeId,\n\t\t\tinput.deviceId,\n\t\t\tinput.createdAt,\n\t\t\tinput.scopeId,\n\t\t\tinput.deviceId,\n\t\t\tinput.effectId,\n\t\t);\n}\n\nasync function runAuditedBatch(\n\tdb: D1DatabaseLike,\n\tstatements: D1PreparedStatementLike[],\n): Promise<unknown[]> {\n\tif (!db.batch) {\n\t\tthrow new Error(\"D1 batch support is required for audited scope membership changes.\");\n\t}\n\treturn await db.batch(statements);\n}\n\nfunction batchResultChanges(result: unknown): number {\n\treturn Number((result as D1RunResultLike | undefined)?.meta?.changes ?? 0);\n}\n\nfunction normalizeBootstrapGrantRequest(\n\tinput: CoordinatorReviewJoinRequestBootstrapGrantInput | null | undefined,\n): CoordinatorCreateBootstrapGrantInput | null {\n\tif (!input) return null;\n\tconst seedDeviceId = String(input.seedDeviceId ?? \"\").trim();\n\tconst expiresAt = String(input.expiresAt ?? \"\").trim();\n\tconst createdBy = String(input.createdBy ?? \"\").trim() || null;\n\tif (!seedDeviceId || !expiresAt) {\n\t\tthrow new Error(\"bootstrapGrant.seedDeviceId and expiresAt are required.\");\n\t}\n\treturn {\n\t\tgroupId: \"\",\n\t\tseedDeviceId,\n\t\tworkerDeviceId: \"\",\n\t\texpiresAt,\n\t\tcreatedBy,\n\t};\n}\n\nasync function allRows<T>(statement: D1PreparedStatementLike): Promise<T[]> {\n\tconst result = await statement.all<T>();\n\treturn Array.isArray(result?.results) ? result.results : [];\n}\n\nasync function firstRow<T>(statement: D1PreparedStatementLike): Promise<T | null> {\n\treturn await statement.first<T>();\n}\n\nasync function runChanges(statement: D1PreparedStatementLike): Promise<number> {\n\tconst result = (await statement.run()) as D1RunResultLike | undefined;\n\treturn Number(result?.meta?.changes ?? 0);\n}\n\nexport class D1CoordinatorStore implements CoordinatorStore {\n\treadonly db: D1DatabaseLike;\n\n\tconstructor(db: D1DatabaseLike) {\n\t\tthis.db = db;\n\t}\n\n\tasync close(): Promise<void> {\n\t\t// No-op for D1 bindings.\n\t}\n\n\tasync createGroup(_groupId: string, _displayName?: string | null): Promise<void> {\n\t\tawait this.db\n\t\t\t.prepare(\n\t\t\t\t\"INSERT OR IGNORE INTO groups(group_id, display_name, archived_at, created_at) VALUES (?, ?, NULL, ?)\",\n\t\t\t)\n\t\t\t.bind(_groupId, _displayName ?? null, nowISO())\n\t\t\t.run();\n\t}\n\n\tasync getGroup(_groupId: string): Promise<CoordinatorGroup | null> {\n\t\tconst row = await firstRow<CoordinatorGroup>(\n\t\t\tthis.db\n\t\t\t\t.prepare(\n\t\t\t\t\t\"SELECT group_id, display_name, archived_at, created_at FROM groups WHERE group_id = ?\",\n\t\t\t\t)\n\t\t\t\t.bind(_groupId),\n\t\t);\n\t\treturn row ? rowToRecord<CoordinatorGroup>(row) : null;\n\t}\n\n\tasync listGroups(_includeArchived = false): Promise<CoordinatorGroup[]> {\n\t\tconst where = _includeArchived ? \"\" : \"WHERE archived_at IS NULL\";\n\t\treturn (\n\t\t\tawait allRows<CoordinatorGroup>(\n\t\t\t\tthis.db.prepare(\n\t\t\t\t\t`SELECT group_id, display_name, archived_at, created_at FROM groups ${where} ORDER BY created_at ASC`,\n\t\t\t\t),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorGroup>(row));\n\t}\n\n\tasync renameGroup(_groupId: string, _displayName: string): Promise<boolean> {\n\t\treturn (\n\t\t\t(await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(\"UPDATE groups SET display_name = ? WHERE group_id = ?\")\n\t\t\t\t\t.bind(_displayName, _groupId),\n\t\t\t)) > 0\n\t\t);\n\t}\n\n\tasync archiveGroup(_groupId: string, _archivedAt = nowISO()): Promise<boolean> {\n\t\treturn (\n\t\t\t(await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(\"UPDATE groups SET archived_at = ? WHERE group_id = ? AND archived_at IS NULL\")\n\t\t\t\t\t.bind(_archivedAt, _groupId),\n\t\t\t)) > 0\n\t\t);\n\t}\n\n\tasync unarchiveGroup(_groupId: string): Promise<boolean> {\n\t\treturn (\n\t\t\t(await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\"UPDATE groups SET archived_at = NULL WHERE group_id = ? AND archived_at IS NOT NULL\",\n\t\t\t\t\t)\n\t\t\t\t\t.bind(_groupId),\n\t\t\t)) > 0\n\t\t);\n\t}\n\n\tasync enrollDevice(_groupId: string, _opts: CoordinatorEnrollDeviceInput): Promise<void> {\n\t\tconst changes = await runChanges(\n\t\t\tthis.db\n\t\t\t\t.prepare(`INSERT INTO enrolled_devices(\n\t\t\t\t\tgroup_id, device_id, public_key, fingerprint, identity_id, display_name, enabled, created_at\n\t\t\t\t) VALUES (?, ?, ?, ?, ?, ?, 1, ?)\n\t\t\t\tON CONFLICT(group_id, device_id) DO UPDATE SET\n\t\t\t\t\tpublic_key = excluded.public_key,\n\t\t\t\t\tfingerprint = excluded.fingerprint,\n\t\t\t\t\tidentity_id = COALESCE(enrolled_devices.identity_id, excluded.identity_id),\n\t\t\t\t\tdisplay_name = excluded.display_name,\n\t\t\t\t\tenabled = 1\n\t\t\t\tWHERE excluded.identity_id IS NULL\n\t\t\t\t\tOR enrolled_devices.identity_id IS NULL\n\t\t\t\t\tOR enrolled_devices.identity_id = excluded.identity_id`)\n\t\t\t\t.bind(\n\t\t\t\t\t_groupId,\n\t\t\t\t\t_opts.deviceId,\n\t\t\t\t\t_opts.publicKey,\n\t\t\t\t\t_opts.fingerprint,\n\t\t\t\t\t_opts.identityId ?? null,\n\t\t\t\t\t_opts.displayName ?? null,\n\t\t\t\t\tnowISO(),\n\t\t\t\t),\n\t\t);\n\t\tif (changes === 0) throw new Error(\"invite_identity_conflict\");\n\t}\n\n\tasync listEnrolledDevices(\n\t\t_groupId: string,\n\t\t_includeDisabled?: boolean,\n\t): Promise<CoordinatorEnrollment[]> {\n\t\tconst where = _includeDisabled ? \"\" : \"AND enrolled_devices.enabled = 1\";\n\t\treturn (\n\t\t\tawait allRows<CoordinatorEnrollment>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT ${ENROLLMENT_PRESENCE_COLUMNS}\n\t\t\t\t\t\t FROM enrolled_devices\n\t\t\t\t\t\t LEFT JOIN presence_records\n\t\t\t\t\t\t ON presence_records.group_id = enrolled_devices.group_id\n\t\t\t\t\t\t AND presence_records.device_id = enrolled_devices.device_id\n\t\t\t\t\t\t WHERE enrolled_devices.group_id = ? ${where}\n\t\t\t\t\t\t ORDER BY enrolled_devices.created_at ASC, enrolled_devices.device_id ASC`)\n\t\t\t\t\t.bind(_groupId),\n\t\t\t)\n\t\t).map(rowToEnrollmentWithPresence);\n\t}\n\n\tasync getEnrollment(\n\t\t_groupId: string,\n\t\t_deviceId: string,\n\t\t_includeDisabled = false,\n\t): Promise<CoordinatorEnrollment | null> {\n\t\tconst enabledClause = _includeDisabled ? \"\" : \"AND enabled = 1\";\n\t\tconst row = await firstRow<CoordinatorEnrollment>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n\t\t\t\t\t FROM enrolled_devices\n\t\t\t\t\t WHERE group_id = ? AND device_id = ? ${enabledClause}`)\n\t\t\t\t.bind(_groupId, _deviceId),\n\t\t);\n\t\treturn row ? rowToRecord<CoordinatorEnrollment>(row) : null;\n\t}\n\n\tasync renameDevice(_groupId: string, _deviceId: string, _displayName: string): Promise<boolean> {\n\t\treturn (\n\t\t\t(await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE enrolled_devices SET display_name = ?\n\t\t\t\t\t WHERE group_id = ? AND device_id = ?`)\n\t\t\t\t\t.bind(_displayName, _groupId, _deviceId),\n\t\t\t)) > 0\n\t\t);\n\t}\n\n\tasync setDeviceEnabled(_groupId: string, _deviceId: string, _enabled: boolean): Promise<boolean> {\n\t\treturn (\n\t\t\t(await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE enrolled_devices SET enabled = ?\n\t\t\t\t\t WHERE group_id = ? AND device_id = ?`)\n\t\t\t\t\t.bind(_enabled ? 1 : 0, _groupId, _deviceId),\n\t\t\t)) > 0\n\t\t);\n\t}\n\n\tasync removeDevice(_groupId: string, _deviceId: string): Promise<boolean> {\n\t\t// Presence, reciprocal approvals, and the enrollment row must be removed\n\t\t// all-or-nothing. Running them as independent statements can orphan rows\n\t\t// (an enrolled device with no presence/approvals, or vice versa) if any\n\t\t// one statement fails. D1 batch() is the transaction boundary here, the\n\t\t// same convention used for audited membership changes via runAuditedBatch.\n\t\tif (!this.db.batch) {\n\t\t\tthrow new Error(\"D1 batch support is required for atomic device removal.\");\n\t\t}\n\t\tconst results = await this.db.batch([\n\t\t\tthis.db\n\t\t\t\t.prepare(\"DELETE FROM presence_records WHERE group_id = ? AND device_id = ?\")\n\t\t\t\t.bind(_groupId, _deviceId),\n\t\t\tthis.db\n\t\t\t\t.prepare(\n\t\t\t\t\t\"DELETE FROM coordinator_reciprocal_approvals WHERE group_id = ? AND (requesting_device_id = ? OR requested_device_id = ?)\",\n\t\t\t\t)\n\t\t\t\t.bind(_groupId, _deviceId, _deviceId),\n\t\t\tthis.db\n\t\t\t\t.prepare(\"DELETE FROM enrolled_devices WHERE group_id = ? AND device_id = ?\")\n\t\t\t\t.bind(_groupId, _deviceId),\n\t\t]);\n\t\t// The enrolled_devices delete is the last statement; its changes() tells us\n\t\t// whether the device existed, preserving the boolean return contract.\n\t\treturn batchResultChanges(results[2]) > 0;\n\t}\n\n\tasync recordNonce(_deviceId: string, _nonce: string, _createdAt: string): Promise<boolean> {\n\t\treturn (\n\t\t\t(await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\"INSERT OR IGNORE INTO request_nonces(device_id, nonce, created_at) VALUES (?, ?, ?)\",\n\t\t\t\t\t)\n\t\t\t\t\t.bind(_deviceId, _nonce, _createdAt),\n\t\t\t)) > 0\n\t\t);\n\t}\n\n\tasync cleanupNonces(_cutoff: string): Promise<void> {\n\t\tawait this.db.prepare(\"DELETE FROM request_nonces WHERE created_at < ?\").bind(_cutoff).run();\n\t}\n\n\tasync createInvite(_opts: CoordinatorCreateInviteInput): Promise<CoordinatorInvite> {\n\t\tconst now = nowISO();\n\t\tconst inviteId = tokenUrlSafe(12);\n\t\tconst token = tokenUrlSafe(24);\n\t\tconst digest = await tokenDigest(token);\n\t\tconst expiresAt = normalizeInviteExpiresAt(_opts.expiresAt);\n\t\tconst group = await this.getGroup(_opts.groupId);\n\t\tconst operationId = String(_opts.operationId ?? \"\").trim() || null;\n\t\tconst reviewedProjectSetDigest = String(_opts.reviewedProjectSetDigest ?? \"\").trim() || null;\n\t\tconst metadata = await normalizeInviteMetadata(_opts);\n\t\tconst assignedIdentityId =\n\t\t\tmetadata.inviteKind === \"team_member\" ? `identity:${tokenUrlSafe(18)}` : null;\n\t\tif (Boolean(operationId) !== Boolean(reviewedProjectSetDigest)) {\n\t\t\tthrow new Error(\"operationId and reviewedProjectSetDigest must be provided together.\");\n\t\t}\n\t\tconst readOperationInvite = async (): Promise<CoordinatorInvite | null> => {\n\t\t\tif (!operationId) return null;\n\t\t\tconst existing = await firstRow<CoordinatorInvite>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE operation_id = ?`)\n\t\t\t\t\t.bind(operationId),\n\t\t\t);\n\t\t\tif (!existing) return null;\n\t\t\t// Pre-consume create retries can recover the bearer token. Successful\n\t\t\t// consume clears it, so post-consume create retries fail closed.\n\t\t\tif (existing.consumed_at) throw new Error(\"invite_already_bound\");\n\t\t\tif (\n\t\t\t\texisting.group_id !== _opts.groupId ||\n\t\t\t\texisting.policy !== _opts.policy ||\n\t\t\t\texisting.invite_kind !== metadata.inviteKind ||\n\t\t\t\texisting.reviewed_project_set_digest !== reviewedProjectSetDigest ||\n\t\t\t\texisting.inviter_actor_id !== (String(_opts.inviterActorId ?? \"\").trim() || null) ||\n\t\t\t\texisting.inviter_display_name !== (String(_opts.inviterDisplayName ?? \"\").trim() || null) ||\n\t\t\t\texisting.inviter_device_id !== (String(_opts.inviterDeviceId ?? \"\").trim() || null) ||\n\t\t\t\texisting.pending_person_id !== (String(_opts.pendingPersonId ?? \"\").trim() || null) ||\n\t\t\t\texisting.project_summaries_json !==\n\t\t\t\t\t(_opts.projectSummaries ? JSON.stringify(_opts.projectSummaries) : null) ||\n\t\t\t\texisting.project_intent_json !==\n\t\t\t\t\t(_opts.projectIntent ? JSON.stringify(_opts.projectIntent) : null) ||\n\t\t\t\texisting.policy_team_id !== metadata.policyTeamId ||\n\t\t\t\texisting.target_identity_id !== metadata.targetIdentityId ||\n\t\t\t\texisting.reviewed_preview_digest !== metadata.reviewedPreviewDigest ||\n\t\t\t\texisting.reviewed_intent_json !== metadata.reviewedIntentJson\n\t\t\t) {\n\t\t\t\tthrow new Error(\"invite_operation_intent_conflict\");\n\t\t\t}\n\t\t\treturn rowToRecord<CoordinatorInvite>(existing);\n\t\t};\n\t\tconst renewOperationInvite = async (\n\t\t\texisting: CoordinatorInvite,\n\t\t): Promise<CoordinatorInvite> => {\n\t\t\tif (!existing.revoked_at && existing.expires_at > now) return existing;\n\t\t\tawait runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_invites\n\t\t\t\t\t\tSET token = ?, token_digest = ?, expires_at = ?, created_at = ?, created_by = ?,\n\t\t\t\t\t\t\tteam_name_snapshot = ?, revoked_at = NULL\n\t\t\t\t\t\tWHERE operation_id = ? AND token = ?\n\t\t\t\t\t\t AND (revoked_at IS NOT NULL OR expires_at <= ?)`)\n\t\t\t\t\t.bind(\n\t\t\t\t\t\ttoken,\n\t\t\t\t\t\tdigest,\n\t\t\t\t\t\texpiresAt,\n\t\t\t\t\t\tnow,\n\t\t\t\t\t\t_opts.createdBy ?? null,\n\t\t\t\t\t\tgroup?.display_name ?? null,\n\t\t\t\t\t\toperationId,\n\t\t\t\t\t\texisting.token,\n\t\t\t\t\t\tnow,\n\t\t\t\t\t),\n\t\t\t);\n\t\t\tconst renewed = await readOperationInvite();\n\t\t\tif (!renewed) throw new Error(\"invite_operation_reissue_failed\");\n\t\t\treturn renewed;\n\t\t};\n\t\tif (operationId) {\n\t\t\tconst existing = await readOperationInvite();\n\t\t\tif (existing) return await renewOperationInvite(existing);\n\t\t}\n\t\ttry {\n\t\t\tawait this.db\n\t\t\t\t.prepare(`INSERT INTO coordinator_invites(\n\t\t\t\tinvite_id, group_id, token, policy, expires_at, created_at, created_by,\n\t\t\t\tteam_name_snapshot, revoked_at, operation_id, reviewed_project_set_digest,\n\t\t\t\ttoken_digest, inviter_actor_id, inviter_display_name, inviter_device_id,\n\t\t\t\tpending_person_id, project_summaries_json, project_intent_json, trust_state,\n\t\t\t\tinvite_kind, policy_team_id, target_identity_id, assigned_identity_id,\n\t\t\t\treviewed_preview_digest, reviewed_intent_json\n\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)\n\t\t\t\t.bind(\n\t\t\t\t\tinviteId,\n\t\t\t\t\t_opts.groupId,\n\t\t\t\t\ttoken,\n\t\t\t\t\t_opts.policy,\n\t\t\t\t\texpiresAt,\n\t\t\t\t\tnow,\n\t\t\t\t\t_opts.createdBy ?? null,\n\t\t\t\t\tgroup?.display_name ?? null,\n\t\t\t\t\toperationId,\n\t\t\t\t\treviewedProjectSetDigest,\n\t\t\t\t\tdigest,\n\t\t\t\t\tString(_opts.inviterActorId ?? \"\").trim() || null,\n\t\t\t\t\tString(_opts.inviterDisplayName ?? \"\").trim() || null,\n\t\t\t\t\tString(_opts.inviterDeviceId ?? \"\").trim() || null,\n\t\t\t\t\tString(_opts.pendingPersonId ?? \"\").trim() || null,\n\t\t\t\t\t_opts.projectSummaries ? JSON.stringify(_opts.projectSummaries) : null,\n\t\t\t\t\t_opts.projectIntent ? JSON.stringify(_opts.projectIntent) : null,\n\t\t\t\t\toperationId ? \"pending\" : null,\n\t\t\t\t\tmetadata.inviteKind,\n\t\t\t\t\tmetadata.policyTeamId,\n\t\t\t\t\tmetadata.targetIdentityId,\n\t\t\t\t\tassignedIdentityId,\n\t\t\t\t\tmetadata.reviewedPreviewDigest,\n\t\t\t\t\tmetadata.reviewedIntentJson,\n\t\t\t\t)\n\t\t\t\t.run();\n\t\t} catch (error) {\n\t\t\tif (operationId) {\n\t\t\t\tconst existing = await readOperationInvite();\n\t\t\t\tif (existing) return await renewOperationInvite(existing);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tconst row = await firstRow<CoordinatorInvite>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE invite_id = ?`)\n\t\t\t\t.bind(inviteId),\n\t\t);\n\t\treturn rowToRecord<CoordinatorInvite>(row);\n\t}\n\n\tasync getInviteByToken(_token: string): Promise<CoordinatorInvite | null> {\n\t\tconst digest = await tokenDigest(_token);\n\t\tconst row = await firstRow<CoordinatorInvite>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT ${INVITE_COLUMNS}\n\t\t\t\t\t FROM coordinator_invites\n\t\t\t\t\t WHERE (token_digest = ? OR token = ?)\n\t\t\t\t\t AND revoked_at IS NULL\n\t\t\t\t\t AND expires_at > ?`)\n\t\t\t\t.bind(digest, _token, nowISO()),\n\t\t);\n\t\treturn row ? rowToRecord<CoordinatorInvite>(row) : null;\n\t}\n\n\tasync getInviteByTokenForInspection(_token: string): Promise<CoordinatorInvite | null> {\n\t\tconst digest = await tokenDigest(_token);\n\t\tconst row = await firstRow<CoordinatorInvite>(\n\t\t\tthis.db\n\t\t\t\t.prepare(\n\t\t\t\t\t`SELECT ${INVITE_COLUMNS} FROM coordinator_invites WHERE token_digest = ? OR token = ?`,\n\t\t\t\t)\n\t\t\t\t.bind(digest, _token),\n\t\t);\n\t\treturn row ? rowToRecord<CoordinatorInvite>(row) : null;\n\t}\n\n\tasync inspectRecipientInvite(\n\t\t_opts: CoordinatorInspectRecipientInviteInput,\n\t): Promise<CoordinatorRecipientInviteInspection | null> {\n\t\tconst invite = await this.getInviteByTokenForInspection(_opts.token);\n\t\tif (!invite) return null;\n\t\tconst inspection = await recipientInspection(invite);\n\t\tif (!inspection) return null;\n\t\tif (invite.revoked_at) throw new Error(\"invite_invalid\");\n\t\tif (\n\t\t\t!invite.consumed_at &&\n\t\t\tnew Date(invite.expires_at) <= new Date(normalizeInviteExpiresAt(_opts.now))\n\t\t) {\n\t\t\tthrow new Error(\"invite_expired\");\n\t\t}\n\t\tconst group = await this.getGroup(invite.group_id);\n\t\tif (!group) throw new Error(\"group_not_found\");\n\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\treturn inspection;\n\t}\n\n\tasync consumeRecipientInvite(\n\t\t_opts: CoordinatorConsumeRecipientInviteInput,\n\t): Promise<CoordinatorRecipientInviteAcceptance> {\n\t\tconst consumedAt = normalizeInviteExpiresAt(_opts.now);\n\t\tconst recipientDisplayName = _opts.recipientDisplayName ?? null;\n\t\tconst deviceDisplayName = _opts.deviceDisplayName ?? null;\n\t\tif (\n\t\t\t!_opts.identityId ||\n\t\t\t!_opts.deviceId ||\n\t\t\t!_opts.publicKey ||\n\t\t\t!_opts.fingerprint ||\n\t\t\t_opts.identityId !== _opts.identityId.trim() ||\n\t\t\t_opts.deviceId !== _opts.deviceId.trim() ||\n\t\t\t_opts.identityId.length > 256 ||\n\t\t\t_opts.deviceId.length > 256 ||\n\t\t\t/[\\p{Cc}\\p{Cf}]/u.test(_opts.identityId) ||\n\t\t\t/[\\p{Cc}\\p{Cf}]/u.test(_opts.deviceId)\n\t\t) {\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t}\n\t\tconst digest = await tokenDigest(_opts.token);\n\t\tconst initial = await this.getInviteByTokenForInspection(_opts.token);\n\t\tconst inspection = initial ? await recipientInspection(initial) : null;\n\t\tif (!initial || !inspection || inspection.kind !== _opts.inviteKind || initial.revoked_at) {\n\t\t\tthrow new Error(\"invite_invalid\");\n\t\t}\n\t\tconst group = await this.getGroup(initial.group_id);\n\t\tif (!group) throw new Error(\"group_not_found\");\n\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\tif (!initial.consumed_at && new Date(initial.expires_at) <= new Date(consumedAt)) {\n\t\t\tthrow new Error(\"invite_expired\");\n\t\t}\n\t\tif (fingerprintPublicKey(_opts.publicKey) !== _opts.fingerprint) {\n\t\t\tthrow new Error(\"fingerprint_mismatch\");\n\t\t}\n\t\tconst authoritativeIdentityId = recipientInviteAuthoritativeIdentityId(inspection);\n\t\tif (authoritativeIdentityId !== _opts.identityId) {\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t}\n\t\tconst sameBinding =\n\t\t\tinitial.bound_device_id === _opts.deviceId &&\n\t\t\tinitial.bound_public_key === _opts.publicKey &&\n\t\t\tinitial.bound_fingerprint === _opts.fingerprint;\n\t\tif (initial.consumed_at && !sameBinding) throw new Error(\"invite_already_bound\");\n\t\tif (initial.consumed_at && initial.recipient_actor_id !== authoritativeIdentityId) {\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t}\n\t\tconst existingEnrollment = await firstRow<CoordinatorEnrollment>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n\t\t\t\t\tFROM enrolled_devices WHERE group_id = ? AND device_id = ?`)\n\t\t\t\t.bind(initial.group_id, _opts.deviceId),\n\t\t);\n\t\tif (\n\t\t\texistingEnrollment &&\n\t\t\t(existingEnrollment.public_key !== _opts.publicKey ||\n\t\t\t\texistingEnrollment.fingerprint !== _opts.fingerprint ||\n\t\t\t\t(existingEnrollment.identity_id !== null &&\n\t\t\t\t\texistingEnrollment.identity_id !== authoritativeIdentityId))\n\t\t) {\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t}\n\t\tlet changed = 0;\n\t\tconst bootstrapGrantId = tokenUrlSafe(12);\n\t\tif (!initial.consumed_at) {\n\t\t\tif (!this.db.batch)\n\t\t\t\tthrow new Error(\"D1 batch support is required for atomic invite consume.\");\n\t\t\tconst results = await this.db.batch([\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_invites SET token = ?, consumed_at = ?, bound_device_id = ?,\n\t\t\t\t\t\tbound_public_key = ?, bound_fingerprint = ?, recipient_actor_id = ?,\n\t\t\t\t\t\trecipient_display_name = ?, recipient_device_display_name = ?\n\t\t\t\t\t\tWHERE (token_digest = ? OR token = ?) AND consumed_at IS NULL\n\t\t\t\t\t\tAND revoked_at IS NULL AND expires_at > ? AND invite_kind = ?\n\t\t\t\t\t\tAND reviewed_intent_json = ? AND reviewed_preview_digest = ?\n\t\t\t\t\t\tAND ((invite_kind = 'team_member' AND assigned_identity_id = ?)\n\t\t\t\t\t\t\tOR (invite_kind = 'add_device' AND target_identity_id = ?))\n\t\t\t\t\t\tAND NOT EXISTS (\n\t\t\t\t\t\t\tSELECT 1 FROM enrolled_devices e\n\t\t\t\t\t\t\tWHERE e.group_id = coordinator_invites.group_id AND e.device_id = ?\n\t\t\t\t\t\t\t\tAND (e.public_key <> ? OR e.fingerprint <> ?\n\t\t\t\t\t\t\t\t\tOR (e.identity_id IS NOT NULL AND e.identity_id <> ?))\n\t\t\t\t\t\t)\n\t\t\t\t\t\tAND EXISTS (SELECT 1 FROM groups g WHERE g.group_id = coordinator_invites.group_id\n\t\t\t\t\t\t\tAND g.archived_at IS NULL)`)\n\t\t\t\t\t.bind(\n\t\t\t\t\t\t`consumed:${initial.invite_id}`,\n\t\t\t\t\t\tconsumedAt,\n\t\t\t\t\t\t_opts.deviceId,\n\t\t\t\t\t\t_opts.publicKey,\n\t\t\t\t\t\t_opts.fingerprint,\n\t\t\t\t\t\tauthoritativeIdentityId,\n\t\t\t\t\t\trecipientDisplayName,\n\t\t\t\t\t\tdeviceDisplayName,\n\t\t\t\t\t\tdigest,\n\t\t\t\t\t\t_opts.token,\n\t\t\t\t\t\tconsumedAt,\n\t\t\t\t\t\t_opts.inviteKind,\n\t\t\t\t\t\tinitial.reviewed_intent_json,\n\t\t\t\t\t\tinitial.reviewed_preview_digest,\n\t\t\t\t\t\tauthoritativeIdentityId,\n\t\t\t\t\t\tauthoritativeIdentityId,\n\t\t\t\t\t\t_opts.deviceId,\n\t\t\t\t\t\t_opts.publicKey,\n\t\t\t\t\t\t_opts.fingerprint,\n\t\t\t\t\t\tauthoritativeIdentityId,\n\t\t\t\t\t),\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`INSERT INTO enrolled_devices(\n\t\t\t\t\t\tgroup_id, device_id, public_key, fingerprint, identity_id, display_name, enabled, created_at\n\t\t\t\t\t) SELECT i.group_id, i.bound_device_id, i.bound_public_key, i.bound_fingerprint,\n\t\t\t\t\t\ti.recipient_actor_id, i.recipient_device_display_name, 1, ? FROM coordinator_invites i\n\t\t\t\t\tJOIN groups g ON g.group_id = i.group_id AND g.archived_at IS NULL\n\t\t\t\t\tWHERE (i.token_digest = ? OR i.token = ?) AND i.bound_device_id = ?\n\t\t\t\t\t\tAND i.bound_public_key = ? AND i.bound_fingerprint = ?\n\t\t\t\t\t\tAND i.recipient_actor_id = ?\n\t\t\t\t\tON CONFLICT(group_id, device_id) DO UPDATE SET\n\t\t\t\t\t\tidentity_id = COALESCE(enrolled_devices.identity_id, excluded.identity_id),\n\t\t\t\t\t\tdisplay_name = COALESCE(enrolled_devices.display_name, excluded.display_name),\n\t\t\t\t\t\tenabled = 1\n\t\t\t\t\tWHERE enrolled_devices.identity_id IS NULL\n\t\t\t\t\t\tOR enrolled_devices.identity_id = excluded.identity_id`)\n\t\t\t\t\t.bind(\n\t\t\t\t\t\tconsumedAt,\n\t\t\t\t\t\tdigest,\n\t\t\t\t\t\t_opts.token,\n\t\t\t\t\t\t_opts.deviceId,\n\t\t\t\t\t\t_opts.publicKey,\n\t\t\t\t\t\t_opts.fingerprint,\n\t\t\t\t\t\tauthoritativeIdentityId,\n\t\t\t\t\t),\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_invites SET bootstrap_grant_id = ?,\n\t\t\t\t\t\ttrust_state = 'bootstrap_grant_created'\n\t\t\t\t\t\tWHERE (token_digest = ? OR token = ?) AND invite_kind = 'add_device'\n\t\t\t\t\t\tAND bootstrap_grant_id IS NULL AND inviter_device_id IS NOT NULL\n\t\t\t\t\t\tAND expires_at > ?\n\t\t\t\t\t\tAND EXISTS (SELECT 1 FROM enrolled_devices e\n\t\t\t\t\t\t\tWHERE e.group_id = coordinator_invites.group_id\n\t\t\t\t\t\t\tAND e.device_id = coordinator_invites.inviter_device_id AND e.enabled = 1)`)\n\t\t\t\t\t.bind(bootstrapGrantId, digest, _opts.token, consumedAt),\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`INSERT OR IGNORE INTO coordinator_bootstrap_grants(\n\t\t\t\t\t\tgrant_id, group_id, seed_device_id, worker_device_id, expires_at,\n\t\t\t\t\t\tcreated_at, created_by, revoked_at\n\t\t\t\t\t) SELECT i.bootstrap_grant_id, i.group_id, i.inviter_device_id, i.bound_device_id,\n\t\t\t\t\t\ti.expires_at, ?, i.recipient_actor_id, NULL FROM coordinator_invites i\n\t\t\t\t\tJOIN enrolled_devices e ON e.group_id = i.group_id\n\t\t\t\t\t\tAND e.device_id = i.inviter_device_id AND e.enabled = 1\n\t\t\t\t\tWHERE (i.token_digest = ? OR i.token = ?) AND i.invite_kind = 'add_device'\n\t\t\t\t\t\tAND i.bootstrap_grant_id IS NOT NULL AND i.bound_device_id = ?`)\n\t\t\t\t\t.bind(consumedAt, digest, _opts.token, _opts.deviceId),\n\t\t\t]);\n\t\t\tchanged = batchResultChanges(results[0]);\n\t\t}\n\t\tconst currentGroup = await this.getGroup(initial.group_id);\n\t\tif (!currentGroup) throw new Error(\"group_not_found\");\n\t\tif (currentGroup.archived_at) throw new Error(\"group_archived\");\n\t\tconst currentEnrollment = await firstRow<CoordinatorEnrollment>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n\t\t\t\t\tFROM enrolled_devices WHERE group_id = ? AND device_id = ?`)\n\t\t\t\t.bind(initial.group_id, _opts.deviceId),\n\t\t);\n\t\tif (\n\t\t\tcurrentEnrollment &&\n\t\t\t(currentEnrollment.public_key !== _opts.publicKey ||\n\t\t\t\tcurrentEnrollment.fingerprint !== _opts.fingerprint ||\n\t\t\t\t(currentEnrollment.identity_id !== null &&\n\t\t\t\t\tcurrentEnrollment.identity_id !== authoritativeIdentityId))\n\t\t) {\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t}\n\t\tconst saved = await this.getInviteByTokenForInspection(_opts.token);\n\t\tif (\n\t\t\t!saved ||\n\t\t\tsaved.revoked_at ||\n\t\t\t(!saved.consumed_at && new Date(saved.expires_at) <= new Date(consumedAt))\n\t\t) {\n\t\t\tthrow new Error(\"invite_invalid\");\n\t\t}\n\t\tconst savedInspection = await recipientInspection(saved);\n\t\tif (!savedInspection || savedInspection.kind !== _opts.inviteKind) {\n\t\t\tthrow new Error(\"invite_invalid\");\n\t\t}\n\t\tconst savedIdentityId = recipientInviteAuthoritativeIdentityId(savedInspection);\n\t\tif (savedIdentityId !== authoritativeIdentityId) {\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t}\n\t\tif (\n\t\t\tsaved.bound_device_id !== _opts.deviceId ||\n\t\t\tsaved.bound_public_key !== _opts.publicKey ||\n\t\t\tsaved.bound_fingerprint !== _opts.fingerprint\n\t\t) {\n\t\t\tthrow new Error(\"invite_already_bound\");\n\t\t}\n\t\tif (saved.recipient_actor_id !== authoritativeIdentityId)\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\tawait this.db\n\t\t\t.prepare(`UPDATE enrolled_devices SET identity_id = ?\n\t\t\t\tWHERE group_id = ? AND device_id = ? AND identity_id IS NULL\n\t\t\t\t\tAND public_key = ? AND fingerprint = ?`)\n\t\t\t.bind(\n\t\t\t\tauthoritativeIdentityId,\n\t\t\t\tsaved.group_id,\n\t\t\t\t_opts.deviceId,\n\t\t\t\t_opts.publicKey,\n\t\t\t\t_opts.fingerprint,\n\t\t\t)\n\t\t\t.run();\n\t\tconst enrollment = await this.getEnrollment(saved.group_id, _opts.deviceId);\n\t\tif (!enrollment) throw new Error(\"invite_acceptance_incomplete\");\n\t\tif (\n\t\t\tenrollment.public_key !== _opts.publicKey ||\n\t\t\tenrollment.fingerprint !== _opts.fingerprint ||\n\t\t\tenrollment.identity_id !== authoritativeIdentityId\n\t\t) {\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t}\n\t\tlet savedWithGrant = saved;\n\t\tif (\n\t\t\tsavedInspection.kind === \"add_device\" &&\n\t\t\tsaved.inviter_device_id &&\n\t\t\t!saved.bootstrap_grant_id &&\n\t\t\tnew Date(saved.expires_at) > new Date(consumedAt)\n\t\t) {\n\t\t\tif (!this.db.batch)\n\t\t\t\tthrow new Error(\"D1 batch support is required for atomic bootstrap grant recovery.\");\n\t\t\tconst recoveryGrantId = tokenUrlSafe(12);\n\t\t\tawait this.db.batch([\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_invites SET bootstrap_grant_id = ?,\n\t\t\t\t\t\ttrust_state = 'bootstrap_grant_created'\n\t\t\t\t\t\tWHERE invite_id = ? AND invite_kind = 'add_device'\n\t\t\t\t\t\tAND bootstrap_grant_id IS NULL AND inviter_device_id IS NOT NULL\n\t\t\t\t\t\tAND bound_device_id = ? AND recipient_actor_id = ? AND expires_at > ?\n\t\t\t\t\t\tAND EXISTS (SELECT 1 FROM enrolled_devices e\n\t\t\t\t\t\t\tWHERE e.group_id = coordinator_invites.group_id\n\t\t\t\t\t\t\tAND e.device_id = coordinator_invites.inviter_device_id AND e.enabled = 1)`)\n\t\t\t\t\t.bind(\n\t\t\t\t\t\trecoveryGrantId,\n\t\t\t\t\t\tsaved.invite_id,\n\t\t\t\t\t\t_opts.deviceId,\n\t\t\t\t\t\tauthoritativeIdentityId,\n\t\t\t\t\t\tconsumedAt,\n\t\t\t\t\t),\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`INSERT OR IGNORE INTO coordinator_bootstrap_grants(\n\t\t\t\t\t\tgrant_id, group_id, seed_device_id, worker_device_id, expires_at,\n\t\t\t\t\t\tcreated_at, created_by, revoked_at\n\t\t\t\t\t) SELECT i.bootstrap_grant_id, i.group_id, i.inviter_device_id, i.bound_device_id,\n\t\t\t\t\t\ti.expires_at, ?, i.recipient_actor_id, NULL FROM coordinator_invites i\n\t\t\t\t\tJOIN enrolled_devices e ON e.group_id = i.group_id\n\t\t\t\t\t\tAND e.device_id = i.inviter_device_id AND e.enabled = 1\n\t\t\t\t\tWHERE i.invite_id = ? AND i.invite_kind = 'add_device'\n\t\t\t\t\t\tAND i.bootstrap_grant_id IS NOT NULL AND i.bound_device_id = ?`)\n\t\t\t\t\t.bind(consumedAt, saved.invite_id, _opts.deviceId),\n\t\t\t]);\n\t\t\tconst refreshed = await this.getInviteByTokenForInspection(_opts.token);\n\t\t\tif (!refreshed) throw new Error(\"invite_invalid\");\n\t\t\tsavedWithGrant = refreshed;\n\t\t}\n\t\tconst bootstrapGrant = savedWithGrant.bootstrap_grant_id\n\t\t\t? await this.getBootstrapGrant(savedWithGrant.bootstrap_grant_id)\n\t\t\t: null;\n\t\treturn {\n\t\t\tstatus: changed === 1 ? \"accepted\" : \"existing\",\n\t\t\tinvite: savedWithGrant,\n\t\t\treviewed_intent: savedInspection.reviewed_intent,\n\t\t\tbootstrap_grant: bootstrapGrant,\n\t\t};\n\t}\n\n\tasync consumeProjectInvite(\n\t\t_opts: CoordinatorConsumeProjectInviteInput,\n\t): Promise<CoordinatorProjectInviteAcceptance> {\n\t\tif (!this.db.batch) throw new Error(\"D1 batch support is required for atomic invite consume.\");\n\t\tconst consumedAt = normalizeInviteExpiresAt(_opts.now);\n\t\tconst digest = await tokenDigest(_opts.token);\n\t\tconst initial = await this.getInviteByTokenForInspection(_opts.token);\n\t\tif (!initial?.operation_id || !initial.project_intent_json || initial.revoked_at) {\n\t\t\tthrow new Error(\"invite_invalid\");\n\t\t}\n\t\tconst group = await this.getGroup(initial.group_id);\n\t\tif (!group) throw new Error(\"group_not_found\");\n\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\tif (initial.operation_id !== _opts.operationId) throw new Error(\"invite_invalid\");\n\t\tif (fingerprintPublicKey(_opts.publicKey) !== _opts.fingerprint) {\n\t\t\tthrow new Error(\"fingerprint_mismatch\");\n\t\t}\n\t\tif (!initial.consumed_at && new Date(initial.expires_at) <= new Date(consumedAt)) {\n\t\t\tthrow new Error(\"invite_expired\");\n\t\t}\n\t\tconst sameBinding =\n\t\t\tinitial.bound_device_id === _opts.deviceId &&\n\t\t\tinitial.bound_public_key === _opts.publicKey &&\n\t\t\tinitial.bound_fingerprint === _opts.fingerprint;\n\t\tif (initial.consumed_at && !sameBinding) throw new Error(\"invite_already_bound\");\n\t\tif (\n\t\t\tinitial.consumed_at &&\n\t\t\t(initial.recipient_actor_id !== _opts.recipientActorId ||\n\t\t\t\tinitial.recipient_display_name !== _opts.recipientDisplayName ||\n\t\t\t\tinitial.recipient_device_display_name !== _opts.deviceDisplayName)\n\t\t) {\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t}\n\t\tconst existingEnrollment = await firstRow<CoordinatorEnrollment>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT ${ENROLLMENT_COLUMNS}\n\t\t\t\t\tFROM enrolled_devices WHERE group_id = ? AND device_id = ?`)\n\t\t\t\t.bind(initial.group_id, _opts.deviceId),\n\t\t);\n\t\tif (\n\t\t\texistingEnrollment &&\n\t\t\t(existingEnrollment.public_key !== _opts.publicKey ||\n\t\t\t\texistingEnrollment.fingerprint !== _opts.fingerprint ||\n\t\t\t\t(existingEnrollment.identity_id != null &&\n\t\t\t\t\texistingEnrollment.identity_id !== _opts.recipientActorId))\n\t\t) {\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t}\n\n\t\tconst grantId = tokenUrlSafe(12);\n\t\tconst results = await this.db.batch([\n\t\t\tthis.db\n\t\t\t\t.prepare(`UPDATE coordinator_invites SET token = ?, consumed_at = ?, bound_device_id = ?,\n\t\t\t\t\tbound_public_key = ?, bound_fingerprint = ?, recipient_actor_id = ?,\n\t\t\t\t\trecipient_display_name = ?, recipient_device_display_name = ?,\n\t\t\t\t\ttrust_state = 'pending_inviter_device'\n\t\t\t\t\tWHERE (token_digest = ? OR token = ?) AND consumed_at IS NULL\n\t\t\t\t\tAND EXISTS (SELECT 1 FROM groups g WHERE g.group_id = coordinator_invites.group_id\n\t\t\t\t\t\tAND g.archived_at IS NULL)`)\n\t\t\t\t.bind(\n\t\t\t\t\t`consumed:${initial.invite_id}`,\n\t\t\t\t\tconsumedAt,\n\t\t\t\t\t_opts.deviceId,\n\t\t\t\t\t_opts.publicKey,\n\t\t\t\t\t_opts.fingerprint,\n\t\t\t\t\t_opts.recipientActorId,\n\t\t\t\t\t_opts.recipientDisplayName,\n\t\t\t\t\t_opts.deviceDisplayName,\n\t\t\t\t\tdigest,\n\t\t\t\t\t_opts.token,\n\t\t\t\t),\n\t\t\tthis.db\n\t\t\t\t.prepare(`INSERT INTO enrolled_devices(\n\t\t\t\t\tgroup_id, device_id, public_key, fingerprint, identity_id, display_name, enabled, created_at\n\t\t\t\t) SELECT i.group_id, i.bound_device_id, i.bound_public_key, i.bound_fingerprint,\n\t\t\t\t\ti.recipient_actor_id, i.recipient_device_display_name, 1, ? FROM coordinator_invites i\n\t\t\t\t\tJOIN groups g ON g.group_id = i.group_id AND g.archived_at IS NULL\n\t\t\t\t\tWHERE (i.token_digest = ? OR i.token = ?) AND i.bound_device_id = ? AND ? = 1\n\t\t\t\tON CONFLICT(group_id, device_id) DO UPDATE SET\n\t\t\t\t\tidentity_id = COALESCE(enrolled_devices.identity_id, excluded.identity_id),\n\t\t\t\t\tdisplay_name = excluded.display_name, enabled = 1\n\t\t\t\tWHERE enrolled_devices.identity_id IS NULL\n\t\t\t\t\tOR enrolled_devices.identity_id = excluded.identity_id`)\n\t\t\t\t.bind(consumedAt, digest, _opts.token, _opts.deviceId, initial.consumed_at ? 0 : 1),\n\t\t\tthis.db\n\t\t\t\t.prepare(`UPDATE coordinator_invites SET bootstrap_grant_id = ?,\n\t\t\t\t\ttrust_state = 'bootstrap_grant_created'\n\t\t\t\t\tWHERE (token_digest = ? OR token = ?) AND bootstrap_grant_id IS NULL\n\t\t\t\t\tAND bound_device_id = ?\n\t\t\t\t\tAND EXISTS (SELECT 1 FROM groups g WHERE g.group_id = coordinator_invites.group_id\n\t\t\t\t\t\tAND g.archived_at IS NULL)\n\t\t\t\t\tAND expires_at > ?\n\t\t\t\t\tAND EXISTS (SELECT 1 FROM enrolled_devices e WHERE e.group_id = coordinator_invites.group_id\n\t\t\t\t\t\tAND e.device_id = coordinator_invites.inviter_device_id AND e.enabled = 1)`)\n\t\t\t\t.bind(grantId, digest, _opts.token, _opts.deviceId, consumedAt),\n\t\t\tthis.db\n\t\t\t\t.prepare(`INSERT OR IGNORE INTO coordinator_bootstrap_grants(\n\t\t\t\t\tgrant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at,\n\t\t\t\t\tcreated_by, revoked_at\n\t\t\t\t) SELECT i.bootstrap_grant_id, i.group_id, i.inviter_device_id, i.bound_device_id,\n\t\t\t\t\ti.expires_at, ?, i.inviter_actor_id, NULL FROM coordinator_invites i\n\t\t\t\t\tJOIN groups g ON g.group_id = i.group_id AND g.archived_at IS NULL\n\t\t\t\t\tJOIN enrolled_devices e ON e.group_id = i.group_id AND e.device_id = i.inviter_device_id\n\t\t\t\t\tWHERE (i.token_digest = ? OR i.token = ?) AND i.bootstrap_grant_id IS NOT NULL\n\t\t\t\t\tAND i.bound_device_id = ? AND e.enabled = 1`)\n\t\t\t\t.bind(consumedAt, digest, _opts.token, _opts.deviceId),\n\t\t]);\n\t\tconst accepted = batchResultChanges(results[0]) === 1;\n\t\tconst currentGroup = await this.getGroup(initial.group_id);\n\t\tif (!currentGroup) throw new Error(\"group_not_found\");\n\t\tif (currentGroup.archived_at) throw new Error(\"group_archived\");\n\t\tconst saved = await this.getInviteByTokenForInspection(_opts.token);\n\t\tif (!saved) throw new Error(\"invite_invalid\");\n\t\tif (\n\t\t\tsaved.bound_device_id !== _opts.deviceId ||\n\t\t\tsaved.bound_public_key !== _opts.publicKey ||\n\t\t\tsaved.bound_fingerprint !== _opts.fingerprint\n\t\t) {\n\t\t\tthrow new Error(\"invite_already_bound\");\n\t\t}\n\t\tif (\n\t\t\tsaved.recipient_actor_id !== _opts.recipientActorId ||\n\t\t\tsaved.recipient_display_name !== _opts.recipientDisplayName ||\n\t\t\tsaved.recipient_device_display_name !== _opts.deviceDisplayName\n\t\t) {\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t}\n\t\tif (!accepted) {\n\t\t\tawait this.db\n\t\t\t\t.prepare(`UPDATE enrolled_devices SET identity_id = ?\n\t\t\t\t\tWHERE group_id = ? AND device_id = ? AND identity_id IS NULL AND enabled = 1\n\t\t\t\t\t\tAND public_key = ? AND fingerprint = ?`)\n\t\t\t\t.bind(\n\t\t\t\t\t_opts.recipientActorId,\n\t\t\t\t\tsaved.group_id,\n\t\t\t\t\t_opts.deviceId,\n\t\t\t\t\t_opts.publicKey,\n\t\t\t\t\t_opts.fingerprint,\n\t\t\t\t)\n\t\t\t\t.run();\n\t\t}\n\t\tconst enrollment = await this.getEnrollment(saved.group_id, _opts.deviceId);\n\t\tif (!enrollment) throw new Error(\"invite_acceptance_incomplete\");\n\t\tif (enrollment.identity_id !== _opts.recipientActorId) {\n\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t}\n\t\tconst seed = saved.inviter_device_id\n\t\t\t? await this.getEnrollment(saved.group_id, saved.inviter_device_id)\n\t\t\t: null;\n\t\tconst grant = saved.bootstrap_grant_id\n\t\t\t? await this.getBootstrapGrant(saved.bootstrap_grant_id)\n\t\t\t: null;\n\t\treturn {\n\t\t\tstatus: accepted ? \"accepted\" : \"existing\",\n\t\t\tinvite: saved,\n\t\t\tenrollment,\n\t\t\tseed_enrollment: seed,\n\t\t\tbootstrap_grant: grant,\n\t\t};\n\t}\n\n\tasync listInvites(_groupId: string): Promise<CoordinatorInvite[]> {\n\t\treturn (\n\t\t\tawait allRows<CoordinatorInvite>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT ${INVITE_COLUMNS}\n\t\t\t\t\t FROM coordinator_invites WHERE group_id = ?\n\t\t\t\t\t ORDER BY created_at DESC`)\n\t\t\t\t\t.bind(_groupId),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorInvite>(row));\n\t}\n\n\tasync createJoinRequest(\n\t\t_opts: CoordinatorCreateJoinRequestInput,\n\t): Promise<CoordinatorJoinRequest> {\n\t\tconst now = nowISO();\n\t\tconst requestId = tokenUrlSafe(12);\n\t\tawait this.db\n\t\t\t.prepare(`INSERT INTO coordinator_join_requests(\n\t\t\t\trequest_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, NULL, NULL)`)\n\t\t\t.bind(\n\t\t\t\trequestId,\n\t\t\t\t_opts.groupId,\n\t\t\t\t_opts.deviceId,\n\t\t\t\t_opts.publicKey,\n\t\t\t\t_opts.fingerprint,\n\t\t\t\t_opts.displayName ?? null,\n\t\t\t\t_opts.token,\n\t\t\t\tnow,\n\t\t\t)\n\t\t\t.run();\n\t\tconst row = await firstRow<CoordinatorJoinRequest>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n\t\t\t\t\t FROM coordinator_join_requests WHERE request_id = ?`)\n\t\t\t\t.bind(requestId),\n\t\t);\n\t\treturn rowToRecord<CoordinatorJoinRequest>(row);\n\t}\n\n\tasync listJoinRequests(_groupId: string, _status?: string): Promise<CoordinatorJoinRequest[]> {\n\t\tconst status = _status ?? \"pending\";\n\t\treturn (\n\t\t\tawait allRows<CoordinatorJoinRequest>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n\t\t\t\t\t\t FROM coordinator_join_requests\n\t\t\t\t\t\t WHERE group_id = ? AND status = ?\n\t\t\t\t\t\t ORDER BY created_at ASC, device_id ASC`)\n\t\t\t\t\t.bind(_groupId, status),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorJoinRequest>(row));\n\t}\n\n\tasync reviewJoinRequest(\n\t\t_opts: CoordinatorReviewJoinRequestInput,\n\t): Promise<CoordinatorJoinRequestReviewResult | null> {\n\t\tconst row = await firstRow<CoordinatorJoinRequest & { public_key: string }>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status,\n\t\t\t\t\t created_at, reviewed_at, reviewed_by\n\t\t\t\t\t FROM coordinator_join_requests WHERE request_id = ?`)\n\t\t\t\t.bind(_opts.requestId),\n\t\t);\n\t\tif (!row) return null;\n\t\tif (row.status !== \"pending\") {\n\t\t\treturn { ...rowToRecord<CoordinatorJoinRequest>(row), _no_transition: true };\n\t\t}\n\t\tconst bootstrapGrantRequest = normalizeBootstrapGrantRequest(_opts.bootstrapGrant);\n\t\tconst reviewedAt = nowISO();\n\t\tconst nextStatus = _opts.approved ? \"approved\" : \"denied\";\n\t\tlet bootstrapGrantInput: CoordinatorCreateBootstrapGrantInput | null = null;\n\t\tlet bootstrapGrantId: string | null = null;\n\t\tif (_opts.approved && bootstrapGrantRequest) {\n\t\t\tconst seedEnrollment = await firstRow<{ device_id: string }>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`SELECT device_id FROM enrolled_devices WHERE group_id = ? AND device_id = ? AND enabled = 1`,\n\t\t\t\t\t)\n\t\t\t\t\t.bind(row.group_id, bootstrapGrantRequest.seedDeviceId),\n\t\t\t);\n\t\t\tif (!seedEnrollment) {\n\t\t\t\tthrow new Error(\"bootstrap grant seed device is not enrolled in the group.\");\n\t\t\t}\n\t\t\tif (bootstrapGrantRequest.seedDeviceId === row.device_id) {\n\t\t\t\tthrow new Error(\"bootstrap grant seed and worker device ids must differ.\");\n\t\t\t}\n\t\t\tbootstrapGrantInput = {\n\t\t\t\t...bootstrapGrantRequest,\n\t\t\t\tgroupId: row.group_id,\n\t\t\t\tworkerDeviceId: row.device_id,\n\t\t\t};\n\t\t}\n\t\tif (this.db.batch) {\n\t\t\tconst statements: D1PreparedStatementLike[] = [];\n\t\t\tstatements.push(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_join_requests\n\t\t\t\t\t\t SET status = ?, reviewed_at = ?, reviewed_by = ?\n\t\t\t\t\t\t WHERE request_id = ? AND status = 'pending'`)\n\t\t\t\t\t.bind(nextStatus, reviewedAt, _opts.reviewedBy ?? null, _opts.requestId),\n\t\t\t);\n\t\t\tif (_opts.approved) {\n\t\t\t\tstatements.push(\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.prepare(`INSERT INTO enrolled_devices(\n\t\t\t\t\t\t\tgroup_id, device_id, public_key, fingerprint, display_name, enabled, created_at\n\t\t\t\t\t\t)\n\t\t\t\t\t\tSELECT group_id, device_id, public_key, fingerprint, display_name, 1, ?\n\t\t\t\t\t\tFROM coordinator_join_requests\n\t\t\t\t\t\tWHERE request_id = ?\n\t\t\t\t\t\t AND status = 'approved'\n\t\t\t\t\t\t AND reviewed_at = ?\n\t\t\t\t\t\tON CONFLICT(group_id, device_id) DO UPDATE SET\n\t\t\t\t\t\t\tpublic_key = excluded.public_key,\n\t\t\t\t\t\t\tfingerprint = excluded.fingerprint,\n\t\t\t\t\t\t\tdisplay_name = excluded.display_name,\n\t\t\t\t\t\t\tenabled = 1`)\n\t\t\t\t\t\t.bind(nowISO(), _opts.requestId, reviewedAt),\n\t\t\t\t);\n\t\t\t\tif (bootstrapGrantInput) {\n\t\t\t\t\tbootstrapGrantId = tokenUrlSafe(12);\n\t\t\t\t\tconst createdAt = nowISO();\n\t\t\t\t\t// Conditional INSERT: only mint a grant if the join request was\n\t\t\t\t\t// actually transitioned to 'approved' by the UPDATE in this batch.\n\t\t\t\t\t// This prevents issuing extra grants under concurrent review races.\n\t\t\t\t\tstatements.push(\n\t\t\t\t\t\tthis.db\n\t\t\t\t\t\t\t.prepare(`INSERT INTO coordinator_bootstrap_grants(\n\t\t\t\t\t\t\tgrant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n\t\t\t\t\t\t) SELECT ?, ?, ?, ?, ?, ?, ?, NULL\n\t\t\t\t\t\tWHERE EXISTS (\n\t\t\t\t\t\t\tSELECT 1 FROM coordinator_join_requests\n\t\t\t\t\t\t\tWHERE request_id = ? AND status = 'approved' AND reviewed_at = ?\n\t\t\t\t\t\t)`)\n\t\t\t\t\t\t\t.bind(\n\t\t\t\t\t\t\t\tbootstrapGrantId,\n\t\t\t\t\t\t\t\tbootstrapGrantInput.groupId,\n\t\t\t\t\t\t\t\tbootstrapGrantInput.seedDeviceId,\n\t\t\t\t\t\t\t\tbootstrapGrantInput.workerDeviceId,\n\t\t\t\t\t\t\t\tbootstrapGrantInput.expiresAt,\n\t\t\t\t\t\t\t\tcreatedAt,\n\t\t\t\t\t\t\t\tbootstrapGrantInput.createdBy ?? null,\n\t\t\t\t\t\t\t\t_opts.requestId,\n\t\t\t\t\t\t\t\treviewedAt,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tawait this.db.batch(statements);\n\t\t} else {\n\t\t\tlet createdGrantId: string | null = null;\n\t\t\tif (_opts.approved) {\n\t\t\t\tawait this.enrollDevice(row.group_id, {\n\t\t\t\t\tdeviceId: row.device_id,\n\t\t\t\t\tfingerprint: row.fingerprint,\n\t\t\t\t\tpublicKey: row.public_key,\n\t\t\t\t\tdisplayName: (row.display_name ?? \"\").trim() || null,\n\t\t\t\t});\n\t\t\t\tif (bootstrapGrantInput) {\n\t\t\t\t\tconst grant = await this.createBootstrapGrant(bootstrapGrantInput);\n\t\t\t\t\tcreatedGrantId = grant.grant_id;\n\t\t\t\t\tbootstrapGrantId = grant.grant_id;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst changes = await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_join_requests\n\t\t\t\t\t\t SET status = ?, reviewed_at = ?, reviewed_by = ?\n\t\t\t\t\t\t WHERE request_id = ? AND status = 'pending'`)\n\t\t\t\t\t.bind(nextStatus, reviewedAt, _opts.reviewedBy ?? null, _opts.requestId),\n\t\t\t);\n\t\t\tif (changes === 0) {\n\t\t\t\tif (createdGrantId) {\n\t\t\t\t\tawait this.revokeBootstrapGrant(createdGrantId);\n\t\t\t\t}\n\t\t\t\tconst latest = await firstRow<CoordinatorJoinRequestReviewResult>(\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.prepare(`SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n\t\t\t\t\t\t\t FROM coordinator_join_requests WHERE request_id = ?`)\n\t\t\t\t\t\t.bind(_opts.requestId),\n\t\t\t\t);\n\t\t\t\treturn latest\n\t\t\t\t\t? { ...rowToRecord<CoordinatorJoinRequestReviewResult>(latest), _no_transition: true }\n\t\t\t\t\t: null;\n\t\t\t}\n\t\t}\n\t\tconst updated = await firstRow<CoordinatorJoinRequestReviewResult>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, device_id, public_key, fingerprint, display_name, token, status, created_at, reviewed_at, reviewed_by\n\t\t\t\t\t FROM coordinator_join_requests WHERE request_id = ?`)\n\t\t\t\t.bind(_opts.requestId),\n\t\t);\n\t\tif (!updated) return null;\n\t\tconst bootstrapGrant = bootstrapGrantInput\n\t\t\t? bootstrapGrantId\n\t\t\t\t? await this.getBootstrapGrant(bootstrapGrantId)\n\t\t\t\t: await this.createBootstrapGrant(bootstrapGrantInput)\n\t\t\t: null;\n\t\treturn {\n\t\t\t...rowToRecord<CoordinatorJoinRequestReviewResult>(updated),\n\t\t\tbootstrap_grant: bootstrapGrant,\n\t\t};\n\t}\n\n\tasync createReciprocalApproval(\n\t\topts: CoordinatorCreateReciprocalApprovalInput,\n\t): Promise<CoordinatorReciprocalApproval> {\n\t\tconst groupId = opts.groupId.trim();\n\t\tconst requestingDeviceId = opts.requestingDeviceId.trim();\n\t\tconst requestedDeviceId = opts.requestedDeviceId.trim();\n\t\tconst hasExpectedIncomingRequestId = opts.expectedIncomingRequestId !== undefined;\n\t\tconst expectedIncomingRequestId = opts.expectedIncomingRequestId?.trim() ?? \"\";\n\t\tif (!groupId || !requestingDeviceId || !requestedDeviceId) {\n\t\t\tthrow new Error(\"groupId, requestingDeviceId, and requestedDeviceId are required.\");\n\t\t}\n\t\tif (requestingDeviceId === requestedDeviceId) {\n\t\t\tthrow new Error(\"requesting and requested device ids must differ.\");\n\t\t}\n\t\tif (hasExpectedIncomingRequestId) {\n\t\t\tconst resolvedAt = nowISO();\n\t\t\tconst changes = await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_reciprocal_approvals\n\t\t\t\t\t\t SET status = 'completed', resolved_at = ?\n\t\t\t\t\t\t WHERE request_id = ?\n\t\t\t\t\t\t AND group_id = ?\n\t\t\t\t\t\t AND requesting_device_id = ?\n\t\t\t\t\t\t AND requested_device_id = ?\n\t\t\t\t\t\t AND status = 'pending'`)\n\t\t\t\t\t.bind(\n\t\t\t\t\t\tresolvedAt,\n\t\t\t\t\t\texpectedIncomingRequestId,\n\t\t\t\t\t\tgroupId,\n\t\t\t\t\t\trequestedDeviceId,\n\t\t\t\t\t\trequestingDeviceId,\n\t\t\t\t\t),\n\t\t\t);\n\t\t\tif (changes !== 1) {\n\t\t\t\tthrow new CoordinatorReciprocalApprovalRequestChangedError();\n\t\t\t}\n\t\t\tconst completed = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t\t FROM coordinator_reciprocal_approvals WHERE request_id = ?`)\n\t\t\t\t\t.bind(expectedIncomingRequestId),\n\t\t\t);\n\t\t\treturn rowToRecord<CoordinatorReciprocalApproval>(completed);\n\t\t}\n\t\tconst pendingPair = reciprocalPendingPair(requestingDeviceId, requestedDeviceId);\n\t\tconst existing = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t FROM coordinator_reciprocal_approvals\n\t\t\t\t\t WHERE group_id = ? AND requesting_device_id = ? AND requested_device_id = ? AND status = 'pending'\n\t\t\t\t\t ORDER BY created_at DESC LIMIT 1`)\n\t\t\t\t.bind(groupId, requestingDeviceId, requestedDeviceId),\n\t\t);\n\t\tif (existing) return rowToRecord<CoordinatorReciprocalApproval>(existing);\n\t\tconst reverse = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t FROM coordinator_reciprocal_approvals\n\t\t\t\t\t WHERE group_id = ? AND requesting_device_id = ? AND requested_device_id = ? AND status = 'pending'\n\t\t\t\t\t ORDER BY created_at DESC LIMIT 1`)\n\t\t\t\t.bind(groupId, requestedDeviceId, requestingDeviceId),\n\t\t);\n\t\tif (reverse) {\n\t\t\tconst resolvedAt = nowISO();\n\t\t\tawait this.db\n\t\t\t\t.prepare(\n\t\t\t\t\t`UPDATE coordinator_reciprocal_approvals SET status = 'completed', resolved_at = ? WHERE request_id = ?`,\n\t\t\t\t)\n\t\t\t\t.bind(resolvedAt, reverse.request_id)\n\t\t\t\t.run();\n\t\t\tconst completed = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t\t FROM coordinator_reciprocal_approvals WHERE request_id = ?`)\n\t\t\t\t\t.bind(reverse.request_id),\n\t\t\t);\n\t\t\treturn rowToRecord<CoordinatorReciprocalApproval>(completed);\n\t\t}\n\t\tconst requestId = tokenUrlSafe(12);\n\t\tconst createdAt = nowISO();\n\t\ttry {\n\t\t\tawait this.db\n\t\t\t\t.prepare(`INSERT INTO coordinator_reciprocal_approvals(\n\t\t\t\t\t\trequest_id,\n\t\t\t\t\t\tgroup_id,\n\t\t\t\t\t\trequesting_device_id,\n\t\t\t\t\t\trequested_device_id,\n\t\t\t\t\t\tpending_pair_low_device_id,\n\t\t\t\t\t\tpending_pair_high_device_id,\n\t\t\t\t\t\tstatus,\n\t\t\t\t\t\tcreated_at,\n\t\t\t\t\t\tresolved_at\n\t\t\t\t\t) VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, NULL)`)\n\t\t\t\t.bind(\n\t\t\t\t\trequestId,\n\t\t\t\t\tgroupId,\n\t\t\t\t\trequestingDeviceId,\n\t\t\t\t\trequestedDeviceId,\n\t\t\t\t\tpendingPair.low,\n\t\t\t\t\tpendingPair.high,\n\t\t\t\t\tcreatedAt,\n\t\t\t\t)\n\t\t\t\t.run();\n\t\t} catch (error) {\n\t\t\tif (!isUniqueConstraintError(error)) throw error;\n\t\t\tconst sameDirection = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t\t FROM coordinator_reciprocal_approvals\n\t\t\t\t\t\t WHERE group_id = ? AND requesting_device_id = ? AND requested_device_id = ? AND status = 'pending'\n\t\t\t\t\t\t ORDER BY created_at DESC LIMIT 1`)\n\t\t\t\t\t.bind(groupId, requestingDeviceId, requestedDeviceId),\n\t\t\t);\n\t\t\tif (sameDirection) return rowToRecord<CoordinatorReciprocalApproval>(sameDirection);\n\t\t\tconst reverseAfterConflict = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t\t FROM coordinator_reciprocal_approvals\n\t\t\t\t\t\t WHERE group_id = ? AND requesting_device_id = ? AND requested_device_id = ? AND status = 'pending'\n\t\t\t\t\t\t ORDER BY created_at DESC LIMIT 1`)\n\t\t\t\t\t.bind(groupId, requestedDeviceId, requestingDeviceId),\n\t\t\t);\n\t\t\tif (reverseAfterConflict) {\n\t\t\t\tconst resolvedAt = nowISO();\n\t\t\t\tawait this.db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t`UPDATE coordinator_reciprocal_approvals SET status = 'completed', resolved_at = ? WHERE request_id = ?`,\n\t\t\t\t\t)\n\t\t\t\t\t.bind(resolvedAt, reverseAfterConflict.request_id)\n\t\t\t\t\t.run();\n\t\t\t\tconst completed = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\t\t\tthis.db\n\t\t\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t\t\t FROM coordinator_reciprocal_approvals WHERE request_id = ?`)\n\t\t\t\t\t\t.bind(reverseAfterConflict.request_id),\n\t\t\t\t);\n\t\t\t\treturn rowToRecord<CoordinatorReciprocalApproval>(completed);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tconst created = await firstRow<CoordinatorReciprocalApproval>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t FROM coordinator_reciprocal_approvals WHERE request_id = ?`)\n\t\t\t\t.bind(requestId),\n\t\t);\n\t\treturn rowToRecord<CoordinatorReciprocalApproval>(created);\n\t}\n\n\tasync createBootstrapGrant(\n\t\topts: CoordinatorCreateBootstrapGrantInput,\n\t): Promise<CoordinatorBootstrapGrant> {\n\t\tconst normalized = requireTrimmedBootstrapGrantInput(opts);\n\t\tconst grantId = tokenUrlSafe(12);\n\t\tconst createdAt = nowISO();\n\t\tawait this.db\n\t\t\t.prepare(`INSERT INTO coordinator_bootstrap_grants(\n\t\t\t\tgrant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, NULL)`)\n\t\t\t.bind(\n\t\t\t\tgrantId,\n\t\t\t\tnormalized.groupId,\n\t\t\t\tnormalized.seedDeviceId,\n\t\t\t\tnormalized.workerDeviceId,\n\t\t\t\tnormalized.expiresAt,\n\t\t\t\tcreatedAt,\n\t\t\t\tnormalized.createdBy,\n\t\t\t)\n\t\t\t.run();\n\t\tconst row = await firstRow<CoordinatorBootstrapGrant>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n\t\t\t\t\t FROM coordinator_bootstrap_grants WHERE grant_id = ?`)\n\t\t\t\t.bind(grantId),\n\t\t);\n\t\treturn rowToRecord<CoordinatorBootstrapGrant>(row);\n\t}\n\n\tprivate async getScope(scopeId: string): Promise<CoordinatorScope | null> {\n\t\tconst row = await firstRow<CoordinatorScope>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT scope_id, label, kind, authority_type, coordinator_id, group_id,\n\t\t\t\t\t\tmanifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at\n\t\t\t\t\t FROM coordinator_scopes WHERE scope_id = ?`)\n\t\t\t\t.bind(scopeId),\n\t\t);\n\t\treturn row ? rowToRecord<CoordinatorScope>(row) : null;\n\t}\n\n\tprivate async getScopeMembership(\n\t\tscopeId: string,\n\t\tdeviceId: string,\n\t): Promise<CoordinatorScopeMembership | null> {\n\t\tconst row = await firstRow<CoordinatorScopeMembership>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\t\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t\t\t\t FROM coordinator_scope_memberships\n\t\t\t\t\t WHERE scope_id = ? AND device_id = ?`)\n\t\t\t\t.bind(scopeId, deviceId),\n\t\t);\n\t\treturn row ? rowToRecord<CoordinatorScopeMembership>(row) : null;\n\t}\n\n\tasync createScope(opts: CoordinatorCreateScopeInput): Promise<CoordinatorScope> {\n\t\tconst normalized = normalizeCreateScopeInput(opts);\n\t\tif (await this.getScope(normalized.scopeId)) throw new Error(\"scopeId already exists.\");\n\t\tconst now = nowISO();\n\t\tawait this.db\n\t\t\t.prepare(`INSERT INTO coordinator_scopes(\n\t\t\t\t\tscope_id, label, kind, authority_type, coordinator_id, group_id,\n\t\t\t\t\tmanifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at\n\t\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)\n\t\t\t.bind(\n\t\t\t\tnormalized.scopeId,\n\t\t\t\tnormalized.label,\n\t\t\t\tnormalized.kind,\n\t\t\t\tnormalized.authorityType,\n\t\t\t\tnormalized.coordinatorId,\n\t\t\t\tnormalized.groupId,\n\t\t\t\tnormalized.manifestIssuerDeviceId,\n\t\t\t\tnormalized.membershipEpoch,\n\t\t\t\tnormalized.manifestHash,\n\t\t\t\tnormalized.status,\n\t\t\t\tnow,\n\t\t\t\tnow,\n\t\t\t)\n\t\t\t.run();\n\t\tconst scope = await this.getScope(normalized.scopeId);\n\t\tif (!scope) throw new Error(\"scope insert returned no row\");\n\t\treturn scope;\n\t}\n\n\tasync updateScope(opts: CoordinatorUpdateScopeInput): Promise<CoordinatorScope | null> {\n\t\tconst scopeId = clean(opts.scopeId);\n\t\tconst existing = scopeId ? await this.getScope(scopeId) : null;\n\t\tif (!existing) return null;\n\t\tconst normalized = normalizeUpdateScopeInput(opts, existing);\n\t\tawait this.db\n\t\t\t.prepare(`UPDATE coordinator_scopes\n\t\t\t\t SET label = ?,\n\t\t\t\t\t kind = ?,\n\t\t\t\t\t authority_type = ?,\n\t\t\t\t\t coordinator_id = ?,\n\t\t\t\t\t group_id = ?,\n\t\t\t\t\t manifest_issuer_device_id = ?,\n\t\t\t\t\t membership_epoch = ?,\n\t\t\t\t\t manifest_hash = ?,\n\t\t\t\t\t status = ?,\n\t\t\t\t\t updated_at = ?\n\t\t\t\t WHERE scope_id = ?`)\n\t\t\t.bind(\n\t\t\t\tnormalized.label,\n\t\t\t\tnormalized.kind,\n\t\t\t\tnormalized.authorityType,\n\t\t\t\tnormalized.coordinatorId,\n\t\t\t\tnormalized.groupId,\n\t\t\t\tnormalized.manifestIssuerDeviceId,\n\t\t\t\tnormalized.membershipEpoch,\n\t\t\t\tnormalized.manifestHash,\n\t\t\t\tnormalized.status,\n\t\t\t\tnowISO(),\n\t\t\t\tnormalized.scopeId,\n\t\t\t)\n\t\t\t.run();\n\t\treturn await this.getScope(normalized.scopeId);\n\t}\n\n\tasync listScopes(opts: CoordinatorListScopesInput = {}): Promise<CoordinatorScope[]> {\n\t\tconst where: string[] = [];\n\t\tconst params: unknown[] = [];\n\t\tconst coordinatorId = clean(opts.coordinatorId);\n\t\tconst groupId = clean(opts.groupId);\n\t\tconst status = clean(opts.status);\n\t\tif (coordinatorId) {\n\t\t\twhere.push(\"coordinator_id = ?\");\n\t\t\tparams.push(coordinatorId);\n\t\t}\n\t\tif (groupId) {\n\t\t\twhere.push(\"group_id = ?\");\n\t\t\tparams.push(groupId);\n\t\t}\n\t\tif (status) {\n\t\t\twhere.push(\"status = ?\");\n\t\t\tparams.push(status);\n\t\t} else if (!opts.includeInactive) {\n\t\t\twhere.push(\"status = 'active'\");\n\t\t}\n\t\tconst whereSql = where.length ? `WHERE ${where.join(\" AND \")}` : \"\";\n\t\tconst statement =\n\t\t\tthis.db.prepare(`SELECT scope_id, label, kind, authority_type, coordinator_id, group_id,\n\t\t\t\tmanifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at\n\t\t\t FROM coordinator_scopes ${whereSql}\n\t\t\t ORDER BY coordinator_id ASC, group_id ASC, scope_id ASC`);\n\t\treturn (\n\t\t\tawait allRows<CoordinatorScope>(params.length ? statement.bind(...params) : statement)\n\t\t).map((row) => rowToRecord<CoordinatorScope>(row));\n\t}\n\n\tasync grantScopeMembership(\n\t\topts: CoordinatorGrantScopeMembershipInput,\n\t): Promise<CoordinatorScopeMembership> {\n\t\tconst effectId = normalizeMembershipEffectId(opts.effectId);\n\t\tconst requestJson = grantMembershipEffectRequestJson(opts);\n\t\tconst priorReceipt = await getMembershipEffectReceipt(this.db, effectId);\n\t\tif (priorReceipt) {\n\t\t\tassertMatchingMembershipEffectReceipt(priorReceipt, \"grant\", requestJson);\n\t\t\treturn membershipFromEffectReceipt(priorReceipt);\n\t\t}\n\t\tconst scopeId = clean(opts.scopeId);\n\t\tconst deviceId = clean(opts.deviceId);\n\t\tconst scope = scopeId ? await this.getScope(scopeId) : null;\n\t\tif (!scope) throw new CoordinatorMembershipError(\"scope_not_found\");\n\t\tif (scope.status !== \"active\") throw new CoordinatorMembershipError(\"scope_inactive\");\n\t\tconst existing = scopeId && deviceId ? await this.getScopeMembership(scopeId, deviceId) : null;\n\t\tconst normalized = normalizeGrantInput(opts, scope, existing);\n\t\tif (normalized.groupId) {\n\t\t\tconst enrollment = await this.getEnrollment(normalized.groupId, normalized.deviceId);\n\t\t\tif (!enrollment) {\n\t\t\t\tthrow new CoordinatorMembershipError(\"device_not_enrolled\");\n\t\t\t}\n\t\t}\n\t\tconst now = nowISO();\n\t\tawait runAuditedBatch(this.db, [\n\t\t\tthis.db\n\t\t\t\t.prepare(`INSERT INTO coordinator_scope_memberships(\n\t\t\t\t\tscope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t\t\t) SELECT ?, ?, ?, 'active', ?, ?, ?, ?, ?, ?, ?\n\t\t\t\tWHERE NOT EXISTS (\n\t\t\t\t\tSELECT 1 FROM coordinator_scope_membership_effect_receipts WHERE effect_id = ?\n\t\t\t\t)\n\t\t\t\tON CONFLICT(scope_id, device_id) DO UPDATE SET\n\t\t\t\t\trole = excluded.role,\n\t\t\t\t\tstatus = 'active',\n\t\t\t\t\tmembership_epoch = excluded.membership_epoch,\n\t\t\t\t\tcoordinator_id = excluded.coordinator_id,\n\t\t\t\t\tgroup_id = excluded.group_id,\n\t\t\t\t\tmanifest_issuer_device_id = excluded.manifest_issuer_device_id,\n\t\t\t\t\tmanifest_hash = excluded.manifest_hash,\n\t\t\t\t\tsigned_manifest_json = excluded.signed_manifest_json,\n\t\t\t\t\tupdated_at = excluded.updated_at\n\t\t\t\tWHERE excluded.membership_epoch > coordinator_scope_memberships.membership_epoch\n\t\t\t\t OR (\n\t\t\t\t\texcluded.membership_epoch = coordinator_scope_memberships.membership_epoch\n\t\t\t\t\tAND coordinator_scope_memberships.status != 'revoked'\n\t\t\t\t )`)\n\t\t\t\t.bind(\n\t\t\t\t\tnormalized.scopeId,\n\t\t\t\t\tnormalized.deviceId,\n\t\t\t\t\tnormalized.role,\n\t\t\t\t\tnormalized.membershipEpoch,\n\t\t\t\t\tnormalized.coordinatorId,\n\t\t\t\t\tnormalized.groupId,\n\t\t\t\t\tnormalized.manifestIssuerDeviceId,\n\t\t\t\t\tnormalized.manifestHash,\n\t\t\t\t\tnormalized.signedManifestJson,\n\t\t\t\t\tnow,\n\t\t\t\t\teffectId,\n\t\t\t\t),\n\t\t\tprepareGrantEffectReceipt(this.db, {\n\t\t\t\teffectId,\n\t\t\t\trequestJson,\n\t\t\t\tscopeId: normalized.scopeId,\n\t\t\t\tdeviceId: normalized.deviceId,\n\t\t\t\tcreatedAt: now,\n\t\t\t}),\n\t\t\tprepareMembershipAuditFromCurrentRow(this.db, {\n\t\t\t\teffectId,\n\t\t\t\trequestJson,\n\t\t\t\taction: \"grant\",\n\t\t\t\tprevious: existing,\n\t\t\t\tscopeId: normalized.scopeId,\n\t\t\t\tdeviceId: normalized.deviceId,\n\t\t\t\tstatus: \"active\",\n\t\t\t\tmembershipEpoch: normalized.membershipEpoch,\n\t\t\t\tupdatedAt: now,\n\t\t\t\tactorType: normalized.actorType,\n\t\t\t\tactorId: normalized.actorId,\n\t\t\t\tcreatedAt: now,\n\t\t\t}),\n\t\t]);\n\t\tconst receipt = await getMembershipEffectReceipt(this.db, effectId);\n\t\tif (!receipt) throw new Error(\"scope membership grant was not applied.\");\n\t\tassertMatchingMembershipEffectReceipt(receipt, \"grant\", requestJson);\n\t\treturn membershipFromEffectReceipt(receipt);\n\t}\n\n\tasync revokeScopeMembership(opts: CoordinatorRevokeScopeMembershipInput): Promise<boolean> {\n\t\tconst scopeId = clean(opts.scopeId);\n\t\tconst deviceId = clean(opts.deviceId);\n\t\tif (!scopeId || !deviceId) throw new Error(\"scopeId and deviceId are required.\");\n\t\tconst effectId = normalizeMembershipEffectId(opts.effectId);\n\t\tconst requestJson = revokeMembershipEffectRequestJson(opts);\n\t\tconst priorReceipt = await getMembershipEffectReceipt(this.db, effectId);\n\t\tif (priorReceipt) {\n\t\t\tassertMatchingMembershipEffectReceipt(priorReceipt, \"revoke\", requestJson);\n\t\t\treturn priorReceipt.outcome_applied === 1;\n\t\t}\n\t\tconst membershipEpoch =\n\t\t\topts.membershipEpoch == null ? null : normalizeEpoch(opts.membershipEpoch);\n\t\tconst requestedGroupId = clean(opts.groupId);\n\t\tconst scope = requestedGroupId ? await this.getScope(scopeId) : null;\n\t\tif (requestedGroupId && requestedGroupId !== scope?.group_id) {\n\t\t\tthrow new CoordinatorMembershipError(\"scope_group_mismatch\");\n\t\t}\n\t\tconst existing = await this.getScopeMembership(scopeId, deviceId);\n\t\tif (membershipEpoch != null && existing && membershipEpoch <= existing.membership_epoch) {\n\t\t\tthrow new Error(\"membershipEpoch must increase on revoke.\");\n\t\t}\n\t\tconst now = nowISO();\n\t\tconst revokedEpoch = membershipEpoch ?? (existing?.membership_epoch ?? -1) + 1;\n\t\tconst updateStatement = this.db\n\t\t\t.prepare(`UPDATE coordinator_scope_memberships\n\t\t\t\t\t\t SET status = 'revoked',\n\t\t\t\t\t\t\t membership_epoch = CASE WHEN ? IS NULL THEN membership_epoch + 1 ELSE ? END,\n\t\t\t\t\t\t\t manifest_hash = COALESCE(?, manifest_hash),\n\t\t\t\t\t\t\t signed_manifest_json = COALESCE(?, signed_manifest_json),\n\t\t\t\t\t\t\t updated_at = ?\n\t\t\t\t\t\t WHERE scope_id = ? AND device_id = ? AND membership_epoch = ? AND status = ?\n\t\t\t\t\t\t AND NOT EXISTS (\n\t\t\t\t\t\t\tSELECT 1 FROM coordinator_scope_membership_effect_receipts WHERE effect_id = ?\n\t\t\t\t\t\t )`)\n\t\t\t.bind(\n\t\t\t\tmembershipEpoch,\n\t\t\t\tmembershipEpoch,\n\t\t\t\tclean(opts.manifestHash),\n\t\t\t\tclean(opts.signedManifestJson),\n\t\t\t\tnow,\n\t\t\t\tscopeId,\n\t\t\t\tdeviceId,\n\t\t\t\texisting?.membership_epoch ?? -1,\n\t\t\t\texisting?.status ?? \"\",\n\t\t\t\teffectId,\n\t\t\t);\n\t\tconst receiptStatement = prepareRevokeEffectReceipt(this.db, {\n\t\t\teffectId,\n\t\t\trequestJson,\n\t\t\tscopeId,\n\t\t\tdeviceId,\n\t\t\tcreatedAt: now,\n\t\t});\n\t\tconst auditStatement = prepareMembershipAuditFromCurrentRow(this.db, {\n\t\t\teffectId,\n\t\t\trequestJson,\n\t\t\taction: \"revoke\",\n\t\t\tprevious: existing,\n\t\t\tscopeId,\n\t\t\tdeviceId,\n\t\t\tstatus: \"revoked\",\n\t\t\tmembershipEpoch: revokedEpoch,\n\t\t\tupdatedAt: now,\n\t\t\tactorType: clean(opts.actorType),\n\t\t\tactorId: clean(opts.actorId),\n\t\t\tcreatedAt: now,\n\t\t});\n\t\ttry {\n\t\t\tawait runAuditedBatch(this.db, [updateStatement, receiptStatement, auditStatement]);\n\t\t} catch (err) {\n\t\t\tconst current = await this.getScopeMembership(scopeId, deviceId);\n\t\t\tif (\n\t\t\t\texisting &&\n\t\t\t\t(!current ||\n\t\t\t\t\tcurrent.membership_epoch !== existing.membership_epoch ||\n\t\t\t\t\tcurrent.status !== existing.status)\n\t\t\t) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tthrow err;\n\t\t}\n\t\tconst receipt = await getMembershipEffectReceipt(this.db, effectId);\n\t\tif (!receipt) throw new Error(\"scope membership revoke receipt was not persisted.\");\n\t\tassertMatchingMembershipEffectReceipt(receipt, \"revoke\", requestJson);\n\t\treturn receipt.outcome_applied === 1;\n\t}\n\n\tasync listScopeMemberships(\n\t\tscopeId: string,\n\t\tincludeRevoked = false,\n\t): Promise<CoordinatorScopeMembership[]> {\n\t\tconst normalizedScopeId = clean(scopeId);\n\t\tif (!normalizedScopeId) throw new Error(\"scopeId is required.\");\n\t\tconst statusWhere = includeRevoked ? \"\" : \"AND status = 'active'\";\n\t\treturn (\n\t\t\tawait allRows<CoordinatorScopeMembership>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\t\t\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t\t\t\t\t FROM coordinator_scope_memberships\n\t\t\t\t\t\t WHERE scope_id = ? ${statusWhere}\n\t\t\t\t\t\t ORDER BY device_id ASC`)\n\t\t\t\t\t.bind(normalizedScopeId),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorScopeMembership>(row));\n\t}\n\n\tasync listDeviceScopeMemberships(\n\t\tdeviceId: string,\n\t\tincludeRevoked = false,\n\t): Promise<CoordinatorScopeMembership[]> {\n\t\tconst normalizedDeviceId = clean(deviceId);\n\t\tif (!normalizedDeviceId) throw new Error(\"deviceId is required.\");\n\t\t// Served by idx_coordinator_scope_memberships_device_status.\n\t\tconst statusWhere = includeRevoked ? \"\" : \"AND status = 'active'\";\n\t\treturn (\n\t\t\tawait allRows<CoordinatorScopeMembership>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT scope_id, device_id, role, status, membership_epoch, coordinator_id, group_id,\n\t\t\t\t\t\t\tmanifest_issuer_device_id, manifest_hash, signed_manifest_json, updated_at\n\t\t\t\t\t\t FROM coordinator_scope_memberships\n\t\t\t\t\t\t WHERE device_id = ? ${statusWhere}\n\t\t\t\t\t\t ORDER BY scope_id ASC`)\n\t\t\t\t\t.bind(normalizedDeviceId),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorScopeMembership>(row));\n\t}\n\n\tasync listScopeMembershipAuditEvents(\n\t\topts: CoordinatorListScopeMembershipAuditInput,\n\t): Promise<CoordinatorScopeMembershipAuditEvent[]> {\n\t\tconst scopeId = clean(opts.scopeId);\n\t\tif (!scopeId) throw new Error(\"scopeId is required.\");\n\t\tconst deviceId = clean(opts.deviceId);\n\t\tconst limit = normalizeAuditLimit(opts.limit);\n\t\tconst where = deviceId ? \"scope_id = ? AND device_id = ?\" : \"scope_id = ?\";\n\t\tconst params = deviceId ? [scopeId, deviceId, limit] : [scopeId, limit];\n\t\treturn (\n\t\t\tawait allRows<CoordinatorScopeMembershipAuditEvent>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT event_id, effect_id, action, scope_id, device_id, role, status, membership_epoch,\n\t\t\t\t\t\t\tprevious_role, previous_status, previous_membership_epoch,\n\t\t\t\t\t\t\tcoordinator_id, group_id, actor_type, actor_id, manifest_hash, created_at\n\t\t\t\t\t\t FROM coordinator_scope_membership_audit_log\n\t\t\t\t\t\t WHERE ${where}\n\t\t\t\t\t\t ORDER BY event_id ASC\n\t\t\t\t\t\t LIMIT ?`)\n\t\t\t\t\t.bind(...params),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorScopeMembershipAuditEvent>(row));\n\t}\n\n\tasync getBootstrapGrant(grantId: string): Promise<CoordinatorBootstrapGrant | null> {\n\t\tconst row = await firstRow<CoordinatorBootstrapGrant>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n\t\t\t\t\t FROM coordinator_bootstrap_grants WHERE grant_id = ?`)\n\t\t\t\t.bind(grantId),\n\t\t);\n\t\treturn row ? rowToRecord<CoordinatorBootstrapGrant>(row) : null;\n\t}\n\n\tasync listBootstrapGrants(groupId: string): Promise<CoordinatorBootstrapGrant[]> {\n\t\treturn (\n\t\t\tawait allRows<CoordinatorBootstrapGrant>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT grant_id, group_id, seed_device_id, worker_device_id, expires_at, created_at, created_by, revoked_at\n\t\t\t\t\t\t FROM coordinator_bootstrap_grants WHERE group_id = ?\n\t\t\t\t\t\t ORDER BY created_at DESC, grant_id DESC`)\n\t\t\t\t\t.bind(groupId),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorBootstrapGrant>(row));\n\t}\n\n\tasync revokeBootstrapGrant(grantId: string, revokedAt = nowISO()): Promise<boolean> {\n\t\treturn (\n\t\t\t(await runChanges(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`UPDATE coordinator_bootstrap_grants\n\t\t\t\t\t\t SET revoked_at = COALESCE(revoked_at, ?)\n\t\t\t\t\t\t WHERE grant_id = ?`)\n\t\t\t\t\t.bind(revokedAt, grantId),\n\t\t\t)) > 0\n\t\t);\n\t}\n\n\tasync listReciprocalApprovals(\n\t\topts: CoordinatorListReciprocalApprovalsInput,\n\t): Promise<CoordinatorReciprocalApproval[]> {\n\t\tconst directionColumn =\n\t\t\topts.direction === \"incoming\" ? \"requested_device_id\" : \"requesting_device_id\";\n\t\tconst status = opts.status?.trim() || \"pending\";\n\t\treturn (\n\t\t\tawait allRows<CoordinatorReciprocalApproval>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT request_id, group_id, requesting_device_id, requested_device_id, status, created_at, resolved_at\n\t\t\t\t\t\t FROM coordinator_reciprocal_approvals\n\t\t\t\t\t\t WHERE group_id = ? AND ${directionColumn} = ? AND status = ?\n\t\t\t\t\t\t ORDER BY created_at ASC, request_id ASC`)\n\t\t\t\t\t.bind(opts.groupId, opts.deviceId, status),\n\t\t\t)\n\t\t).map((row) => rowToRecord<CoordinatorReciprocalApproval>(row));\n\t}\n\n\tasync createLegacyTeamCompletion(\n\t\tgroupId: string,\n\t\tmanifest: CoordinatorLegacyTeamCompletionManifestV1,\n\t): Promise<CoordinatorLegacyTeamCompletionWriteResult> {\n\t\tconst [normalizedGroupId] = normalizeCoordinatorLegacyTeamCompletionGroupIds([groupId]);\n\t\tif (!normalizedGroupId) throw new Error(\"completion_manifest_invalid\");\n\t\tconst group = await this.getGroup(normalizedGroupId);\n\t\tif (!group) throw new Error(\"group_not_found\");\n\t\tif (group.archived_at) throw new Error(\"group_archived\");\n\t\tconst manifestJson = canonicalCoordinatorLegacyTeamCompletionManifestJson(manifest);\n\t\tconst normalized = JSON.parse(manifestJson) as CoordinatorLegacyTeamCompletionManifestV1;\n\t\trequireCoordinatorLegacyTeamCompletionTeamBinding(normalized);\n\t\tconst existing = await firstRow<{ manifest_json: string }>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT manifest_json FROM coordinator_legacy_team_completions\n\t\t\t\t\tWHERE group_id = ? AND candidate_ref = ?`)\n\t\t\t\t.bind(normalizedGroupId, normalized.candidate_ref),\n\t\t);\n\t\tif (existing) {\n\t\t\tif (existing.manifest_json !== manifestJson) {\n\t\t\t\tthrow new CoordinatorLegacyTeamCompletionConflictError();\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tstatus: \"existing\",\n\t\t\t\tmanifest: normalizeCoordinatorLegacyTeamCompletionManifest(\n\t\t\t\t\tJSON.parse(existing.manifest_json),\n\t\t\t\t),\n\t\t\t};\n\t\t}\n\t\tconst scopeBindings = await allRows<CoordinatorLegacyTeamCompletionScopeBinding>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT DISTINCT\n\t\t\t\t\trequested.scope_id,\n\t\t\t\t\tscope.authority_type,\n\t\t\t\t\tscope.coordinator_id,\n\t\t\t\t\tscope.group_id,\n\t\t\t\t\tscope.status\n\t\t\t\t FROM (\n\t\t\t\t\tSELECT json_extract(value, '$.scope_id') AS scope_id\n\t\t\t\t\tFROM json_each(?, '$.project_mappings')\n\t\t\t\t ) AS requested\n\t\t\t\t LEFT JOIN coordinator_scopes AS scope ON scope.scope_id = requested.scope_id`)\n\t\t\t\t.bind(manifestJson),\n\t\t);\n\t\tconst coordinatorId = requireCoordinatorLegacyTeamCompletionScopeBindings(\n\t\t\tnormalized,\n\t\t\tnormalizedGroupId,\n\t\t\tscopeBindings,\n\t\t);\n\t\tconst changes = await runChanges(\n\t\t\tthis.db\n\t\t\t\t.prepare(`INSERT OR IGNORE INTO coordinator_legacy_team_completions(\n\t\t\t\t\tgroup_id, candidate_ref, manifest_version, manifest_json, completed_at, created_at\n\t\t\t\t\t) SELECT ?, ?, ?, ?, ?, ?\n\t\t\t\t\t FROM groups\n\t\t\t\t\t WHERE group_id = ? AND archived_at IS NULL\n\t\t\t\t\t AND NOT EXISTS (\n\t\t\t\t\t SELECT 1\n\t\t\t\t\t FROM json_each(?, '$.project_mappings') AS requested\n\t\t\t\t\t LEFT JOIN coordinator_scopes AS scope\n\t\t\t\t\t ON scope.scope_id = json_extract(requested.value, '$.scope_id')\n\t\t\t\t\t AND scope.authority_type = 'coordinator'\n\t\t\t\t\t AND scope.coordinator_id = ?\n\t\t\t\t\t AND scope.group_id = ?\n\t\t\t\t\t AND scope.status = 'active'\n\t\t\t\t\t WHERE scope.scope_id IS NULL\n\t\t\t\t\t )\n\t\t\t\t\t AND NOT EXISTS (\n\t\t\t\t\t SELECT 1 FROM enrolled_devices AS enrolled\n\t\t\t\t\t WHERE enrolled.group_id = ?\n\t\t\t\t\t AND NOT EXISTS (\n\t\t\t\t\t SELECT 1 FROM json_each(?, '$.device_decisions') AS requested\n\t\t\t\t\t WHERE json_extract(requested.value, '$.device_id') = enrolled.device_id\n\t\t\t\t\t AND json_extract(requested.value, '$.key_fingerprint') = enrolled.fingerprint\n\t\t\t\t\t AND json_extract(requested.value, '$.enabled') = enrolled.enabled\n\t\t\t\t\t )\n\t\t\t\t\t )\n\t\t\t\t\t AND NOT EXISTS (\n\t\t\t\t\t SELECT 1 FROM json_each(?, '$.device_decisions') AS requested\n\t\t\t\t\t WHERE json_extract(requested.value, '$.decision') = 'included'\n\t\t\t\t\t AND NOT EXISTS (\n\t\t\t\t\t SELECT 1 FROM enrolled_devices AS enrolled\n\t\t\t\t\t WHERE enrolled.group_id = ?\n\t\t\t\t\t AND enrolled.device_id = json_extract(requested.value, '$.device_id')\n\t\t\t\t\t AND enrolled.fingerprint = json_extract(requested.value, '$.key_fingerprint')\n\t\t\t\t\t AND enrolled.enabled = 1\n\t\t\t\t\t )\n\t\t\t\t\t )`)\n\t\t\t\t.bind(\n\t\t\t\t\tnormalizedGroupId,\n\t\t\t\t\tnormalized.candidate_ref,\n\t\t\t\t\tnormalized.version,\n\t\t\t\t\tmanifestJson,\n\t\t\t\t\tnormalized.completed_at,\n\t\t\t\t\tnowISO(),\n\t\t\t\t\tnormalizedGroupId,\n\t\t\t\t\tmanifestJson,\n\t\t\t\t\tcoordinatorId,\n\t\t\t\t\tnormalizedGroupId,\n\t\t\t\t\tnormalizedGroupId,\n\t\t\t\t\tmanifestJson,\n\t\t\t\t\tmanifestJson,\n\t\t\t\t\tnormalizedGroupId,\n\t\t\t\t),\n\t\t);\n\t\tconst stored = await firstRow<{ manifest_json: string }>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT manifest_json FROM coordinator_legacy_team_completions\n\t\t\t\t\tWHERE group_id = ? AND candidate_ref = ?`)\n\t\t\t\t.bind(normalizedGroupId, normalized.candidate_ref),\n\t\t);\n\t\tif (!stored) {\n\t\t\tconst currentGroup = await this.getGroup(normalizedGroupId);\n\t\t\tif (!currentGroup) throw new Error(\"group_not_found\");\n\t\t\tif (currentGroup.archived_at) throw new Error(\"group_archived\");\n\t\t\tconst currentScopeBindings = await allRows<CoordinatorLegacyTeamCompletionScopeBinding>(\n\t\t\t\tthis.db\n\t\t\t\t\t.prepare(`SELECT DISTINCT\n\t\t\t\t\t\trequested.scope_id,\n\t\t\t\t\t\tscope.authority_type,\n\t\t\t\t\t\tscope.coordinator_id,\n\t\t\t\t\t\tscope.group_id,\n\t\t\t\t\t\tscope.status\n\t\t\t\t\t FROM (\n\t\t\t\t\t\tSELECT json_extract(value, '$.scope_id') AS scope_id\n\t\t\t\t\t\tFROM json_each(?, '$.project_mappings')\n\t\t\t\t\t ) AS requested\n\t\t\t\t\t LEFT JOIN coordinator_scopes AS scope ON scope.scope_id = requested.scope_id`)\n\t\t\t\t\t.bind(manifestJson),\n\t\t\t);\n\t\t\trequireCoordinatorLegacyTeamCompletionScopeBindings(\n\t\t\t\tnormalized,\n\t\t\t\tnormalizedGroupId,\n\t\t\t\tcurrentScopeBindings,\n\t\t\t);\n\t\t\tthrow new Error(\"completion_manifest_unavailable\");\n\t\t}\n\t\tif (stored.manifest_json !== manifestJson) {\n\t\t\tthrow new CoordinatorLegacyTeamCompletionConflictError();\n\t\t}\n\t\treturn {\n\t\t\tstatus: changes === 1 ? \"created\" : \"existing\",\n\t\t\tmanifest: normalizeCoordinatorLegacyTeamCompletionManifest(JSON.parse(stored.manifest_json)),\n\t\t};\n\t}\n\n\tasync getLegacyTeamCompletion(\n\t\tgroupId: string,\n\t\tcandidateRef: string,\n\t): Promise<CoordinatorLegacyTeamCompletionManifestV1 | null> {\n\t\tconst [normalizedGroupId] = normalizeCoordinatorLegacyTeamCompletionGroupIds([groupId]);\n\t\tconst normalizedCandidateRef =\n\t\t\tnormalizeCoordinatorLegacyTeamCompletionCandidateRef(candidateRef);\n\t\tif (!normalizedGroupId) throw new Error(\"completion_manifest_invalid\");\n\t\tconst row = await firstRow<{ manifest_json: string }>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT manifest_json FROM coordinator_legacy_team_completions\n\t\t\t\t\tWHERE group_id = ? AND candidate_ref = ?`)\n\t\t\t\t.bind(normalizedGroupId, normalizedCandidateRef),\n\t\t);\n\t\treturn row\n\t\t\t? normalizeCoordinatorLegacyTeamCompletionManifest(JSON.parse(row.manifest_json))\n\t\t\t: null;\n\t}\n\n\tasync listLegacyTeamCompletions(\n\t\tgroupIds: string[],\n\t): Promise<CoordinatorLegacyTeamCompletionRecord[]> {\n\t\tconst normalizedGroupIds = normalizeCoordinatorLegacyTeamCompletionGroupIds(groupIds);\n\t\tif (normalizedGroupIds.length === 0) return [];\n\t\tconst placeholders = normalizedGroupIds.map(() => \"?\").join(\", \");\n\t\tconst stats = await firstRow<{\n\t\t\trecord_count: number;\n\t\t\tbatch_bytes: number;\n\t\t\tmax_manifest_bytes: number;\n\t\t}>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT\n\t\t\t\t\tCOUNT(*) AS record_count,\n\t\t\t\t\tCOALESCE(SUM(\n\t\t\t\t\t\tLENGTH(CAST(group_id AS BLOB)) + LENGTH(CAST(manifest_json AS BLOB))\n\t\t\t\t\t), 0) AS batch_bytes,\n\t\t\t\t\tCOALESCE(MAX(LENGTH(CAST(manifest_json AS BLOB))), 0) AS max_manifest_bytes\n\t\t\t\tFROM coordinator_legacy_team_completions\n\t\t\t\tWHERE group_id IN (${placeholders})`)\n\t\t\t\t.bind(...normalizedGroupIds),\n\t\t);\n\t\tif (\n\t\t\t!stats ||\n\t\t\tstats.record_count > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS ||\n\t\t\tstats.batch_bytes > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES ||\n\t\t\tstats.max_manifest_bytes > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES\n\t\t) {\n\t\t\tthrow new Error(\"completion_results_too_large\");\n\t\t}\n\t\tconst rows = await allRows<{ group_id: string; manifest_json: string }>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`WITH completion_stats AS (\n\t\t\t\t\tSELECT\n\t\t\t\t\t\tCOUNT(*) AS record_count,\n\t\t\t\t\t\tCOALESCE(SUM(\n\t\t\t\t\t\t\tLENGTH(CAST(group_id AS BLOB)) + LENGTH(CAST(manifest_json AS BLOB))\n\t\t\t\t\t\t), 0) AS batch_bytes,\n\t\t\t\t\t\tCOALESCE(MAX(LENGTH(CAST(manifest_json AS BLOB))), 0) AS max_manifest_bytes\n\t\t\t\t\tFROM coordinator_legacy_team_completions\n\t\t\t\t\tWHERE group_id IN (${placeholders})\n\t\t\t\t)\n\t\t\t\tSELECT completions.group_id, completions.manifest_json\n\t\t\t\tFROM coordinator_legacy_team_completions AS completions\n\t\t\t\tCROSS JOIN completion_stats\n\t\t\t\tWHERE completions.group_id IN (${placeholders})\n\t\t\t\t\t AND completion_stats.record_count <= ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS}\n\t\t\t\t\t AND completion_stats.batch_bytes <= ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES}\n\t\t\t\t\t AND completion_stats.max_manifest_bytes <= ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES}\n\t\t\t\t\t AND LENGTH(completions.manifest_json) <= ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES}\n\t\t\t\t\t AND LENGTH(CAST(completions.manifest_json AS BLOB)) <= ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BYTES}\n\t\t\t\t\tORDER BY completions.group_id, completions.completed_at, completions.candidate_ref\n\t\t\t\t\tLIMIT ${COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS + 1}`)\n\t\t\t\t.bind(...normalizedGroupIds, ...normalizedGroupIds),\n\t\t);\n\t\tif (rows.length === 0 && stats.record_count > 0) {\n\t\t\tthrow new Error(\"completion_results_too_large\");\n\t\t}\n\t\tif (rows.length > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_RECORDS) {\n\t\t\tthrow new Error(\"completion_results_too_large\");\n\t\t}\n\t\tconst batchBytes = rows.reduce(\n\t\t\t(total, row) =>\n\t\t\t\ttotal +\n\t\t\t\tnew TextEncoder().encode(row.group_id).byteLength +\n\t\t\t\tnew TextEncoder().encode(row.manifest_json).byteLength,\n\t\t\t0,\n\t\t);\n\t\tif (batchBytes > COORDINATOR_LEGACY_TEAM_COMPLETION_MAX_BATCH_BYTES) {\n\t\t\tthrow new Error(\"completion_results_too_large\");\n\t\t}\n\t\treturn rows.map((row) => ({\n\t\t\tgroup_id: row.group_id,\n\t\t\tmanifest: normalizeCoordinatorLegacyTeamCompletionManifest(JSON.parse(row.manifest_json)),\n\t\t}));\n\t}\n\n\tasync upsertPresence(_opts: CoordinatorUpsertPresenceInput): Promise<CoordinatorPresenceRecord> {\n\t\tconst now = new Date();\n\t\tconst expiresAt = new Date(now.getTime() + _opts.ttlS * 1000).toISOString();\n\t\tconst normalized = mergeAddresses([], _opts.addresses);\n\t\tawait this.db\n\t\t\t.prepare(`INSERT INTO presence_records(group_id, device_id, addresses_json, last_seen_at, expires_at, capabilities_json)\n\t\t\t\t VALUES (?, ?, ?, ?, ?, ?)\n\t\t\t\t ON CONFLICT(group_id, device_id) DO UPDATE SET\n\t\t\t\t\taddresses_json = excluded.addresses_json,\n\t\t\t\t\tlast_seen_at = excluded.last_seen_at,\n\t\t\t\t\texpires_at = excluded.expires_at,\n\t\t\t\t\tcapabilities_json = excluded.capabilities_json`)\n\t\t\t.bind(\n\t\t\t\t_opts.groupId,\n\t\t\t\t_opts.deviceId,\n\t\t\t\tJSON.stringify(normalized),\n\t\t\t\tnow.toISOString(),\n\t\t\t\texpiresAt,\n\t\t\t\tJSON.stringify(_opts.capabilities ?? {}),\n\t\t\t)\n\t\t\t.run();\n\t\treturn {\n\t\t\tgroup_id: _opts.groupId,\n\t\t\tdevice_id: _opts.deviceId,\n\t\t\taddresses: normalized,\n\t\t\texpires_at: expiresAt,\n\t\t};\n\t}\n\n\tasync listGroupPeers(\n\t\t_groupId: string,\n\t\t_requestingDeviceId: string,\n\t): Promise<CoordinatorPeerRecord[]> {\n\t\tconst now = nowISO();\n\t\tconst rows = await allRows<Record<string, unknown>>(\n\t\t\tthis.db\n\t\t\t\t.prepare(`SELECT enrolled_devices.device_id, enrolled_devices.public_key, enrolled_devices.fingerprint, enrolled_devices.display_name,\n\t\t\t\t\t\tpresence_records.addresses_json, presence_records.last_seen_at, presence_records.expires_at,\n\t\t\t\t\t\tpresence_records.capabilities_json\n\t\t\t\t\t FROM enrolled_devices\n\t\t\t\t\t LEFT JOIN presence_records\n\t\t\t\t\t ON presence_records.group_id = enrolled_devices.group_id\n\t\t\t\t\t AND presence_records.device_id = enrolled_devices.device_id\n\t\t\t\t\t WHERE enrolled_devices.group_id = ?\n\t\t\t\t\t AND enrolled_devices.enabled = 1\n\t\t\t\t\t AND enrolled_devices.device_id != ?\n\t\t\t\t\t ORDER BY enrolled_devices.device_id ASC`)\n\t\t\t\t.bind(_groupId, _requestingDeviceId),\n\t\t);\n\t\treturn rows.map((row) => {\n\t\t\tconst expiresRaw = String(row.expires_at ?? \"\").trim();\n\t\t\tlet stale = true;\n\t\t\tif (expiresRaw) {\n\t\t\t\tconst expiresAt = new Date(expiresRaw);\n\t\t\t\tstale = Number.isNaN(expiresAt.getTime()) || expiresAt.toISOString() <= now;\n\t\t\t}\n\t\t\tconst addresses = stale\n\t\t\t\t? []\n\t\t\t\t: mergeAddresses([], JSON.parse(String(row.addresses_json ?? \"[]\")) as string[]);\n\t\t\treturn {\n\t\t\t\tdevice_id: String(row.device_id ?? \"\"),\n\t\t\t\tpublic_key: String(row.public_key ?? \"\"),\n\t\t\t\tfingerprint: String(row.fingerprint ?? \"\"),\n\t\t\t\tdisplay_name: (row.display_name as string | null) ?? null,\n\t\t\t\taddresses,\n\t\t\t\tlast_seen_at: (row.last_seen_at as string | null) ?? null,\n\t\t\t\texpires_at: (row.expires_at as string | null) ?? null,\n\t\t\t\tstale,\n\t\t\t\tcapabilities: JSON.parse(String(row.capabilities_json ?? \"{}\")) as Record<string, unknown>,\n\t\t\t} satisfies CoordinatorPeerRecord;\n\t\t});\n\t}\n}\n","import {\n\ttype CoordinatorRequestVerifier,\n\ttype CoordinatorRuntimeDeps,\n\tcreateCoordinatorApp,\n} from \"./coordinator-api.js\";\nimport { D1CoordinatorStore, type D1DatabaseLike } from \"./d1-coordinator-store.js\";\n\nexport interface CreateD1CoordinatorAppOptions {\n\tdb: D1DatabaseLike;\n\tadminSecret?: string | null;\n\tnow?: () => string;\n\trequestVerifier: CoordinatorRequestVerifier;\n}\n\nexport function createD1CoordinatorApp(\n\topts: CreateD1CoordinatorAppOptions,\n): ReturnType<typeof createCoordinatorApp> {\n\tconst runtime: CoordinatorRuntimeDeps = {\n\t\tadminSecret: () => String(opts.adminSecret ?? \"\").trim() || null,\n\t\tnow: opts.now ?? (() => new Date().toISOString()),\n\t};\n\treturn createCoordinatorApp({\n\t\tstoreFactory: () => new D1CoordinatorStore(opts.db),\n\t\truntime,\n\t\trequestVerifier: opts.requestVerifier,\n\t});\n}\n"],"mappings":";;AAyGA,SAAS,EAAe,GAAiB;CACxC,IAAI,KAAO,MAAM,MAAU,MAAM,cAAc;CAC/C,OAAO;AACR;AAEA,SAAS,GAA4B,GAAqC;CAEzE,IAAM,EACL,4BAA4B,GAC5B,qBAAqB,GACrB,GAAG,MAJW,EAAqC,CAKhD;CACJ,IAAI,OAAO,KAAc,YAAY,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