@codemem/server 0.44.0-alpha.1 → 0.44.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/middleware.ts","../src/request-rate-limit.ts","../src/routes/config.ts","../src/routes/health.ts","../src/helpers.ts","../src/routes/memory.ts","../src/routes/observer-status.ts","../src/routes/target-validation.ts","../src/routes/pack.ts","../src/routes/raw-events.ts","../src/routes/stats.ts","../src/routes/team-setup-view.ts","../src/routes/team-setup.ts","../src/routes/sync.ts","../src/routes/update-status.ts","../src/index.ts"],"sourcesContent":["/**\n * CORS and cross-origin protection middleware.\n *\n * Ports Python's reject_cross_origin() logic from codemem/viewer_http.py.\n * GETs are allowed from any origin by default (viewer is local-only).\n * Callers can mark side-effecting GET path prefixes as unsafe.\n * Mutations (POST/DELETE/PATCH/PUT) require an Origin header matching a\n * loopback address, or are rejected with 403.\n */\n\nimport type { Context, Next } from \"hono\";\nimport { createMiddleware } from \"hono/factory\";\n\nconst LOOPBACK_HOSTS = new Set([\"127.0.0.1\", \"localhost\", \"::1\"]);\n\n/**\n * Check whether an Origin header value is a valid loopback URL.\n * Mirrors Python's _is_allowed_loopback_origin_url().\n */\nfunction isLoopbackOrigin(origin: string): boolean {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(origin);\n\t} catch {\n\t\treturn false;\n\t}\n\tif (url.protocol !== \"http:\" && url.protocol !== \"https:\") return false;\n\tif (url.username || url.password) return false;\n\tconst hostname = url.hostname.startsWith(\"[\") ? url.hostname.slice(1, -1) : url.hostname;\n\treturn LOOPBACK_HOSTS.has(hostname);\n}\n\n/** HTTP methods that mutate state and require origin validation. */\nconst UNSAFE_METHODS = new Set([\"POST\", \"DELETE\", \"PATCH\", \"PUT\"]);\n\n/**\n * Check whether a missing-Origin request looks like a cross-site browser\n * request. Matches Python's `_is_unsafe_missing_origin()`:\n *\n * - Sec-Fetch-Site present and NOT same-origin/same-site/none → unsafe\n * - Referer present and NOT loopback → unsafe\n * - Otherwise → safe (CLI / programmatic caller, no browser context)\n */\nfunction isUnsafeMissingOrigin(c: Context): boolean {\n\tconst secFetchSite = (c.req.header(\"Sec-Fetch-Site\") ?? \"\").trim().toLowerCase();\n\tif (secFetchSite && ![\"same-origin\", \"same-site\", \"none\"].includes(secFetchSite)) {\n\t\treturn true;\n\t}\n\tconst referer = c.req.header(\"Referer\");\n\tif (!referer) return false;\n\treturn !isLoopbackOrigin(referer);\n}\n\n/**\n * Cross-origin protection middleware.\n *\n * Ports Python's `reject_cross_origin(missing_origin_policy=\"reject_if_unsafe\")`:\n *\n * - GET/HEAD/OPTIONS: allowed from any origin unless the caller marks a\n * side-effecting GET path prefix as unsafe.\n * - POST/DELETE/PATCH/PUT:\n * - Origin present + loopback → allowed (browser on localhost)\n * - Origin present + non-loopback → rejected 403\n * - No Origin + no suspicious browser signals → allowed (CLI callers)\n * - No Origin + suspicious Sec-Fetch-Site/Referer → rejected 403\n *\n * For same-origin requests (no Origin header) on safe methods, no\n * Access-Control-Allow-Origin is set — the browser doesn't need it.\n * For valid loopback origins, ACAO is echoed back.\n */\nexport function originGuard(options?: { unsafeGetPathPrefixes?: readonly string[] }) {\n\treturn createMiddleware(async (c: Context, next: Next) => {\n\t\tconst origin = c.req.header(\"Origin\");\n\t\tconst method = c.req.method;\n\t\tconst unsafeGet =\n\t\t\t(method === \"GET\" || method === \"HEAD\") &&\n\t\t\toptions?.unsafeGetPathPrefixes?.some((prefix) => c.req.path.startsWith(prefix));\n\n\t\tif (UNSAFE_METHODS.has(method) || unsafeGet) {\n\t\t\tif (origin) {\n\t\t\t\t// Origin present — must be loopback\n\t\t\t\tif (!isLoopbackOrigin(origin)) {\n\t\t\t\t\treturn c.json({ error: \"forbidden\" }, 403);\n\t\t\t\t}\n\t\t\t\t// Valid loopback origin — echo it for CORS\n\t\t\t\tc.header(\"Access-Control-Allow-Origin\", origin);\n\t\t\t\tc.header(\"Access-Control-Allow-Methods\", \"GET, POST, PUT, DELETE, OPTIONS\");\n\t\t\t\tc.header(\"Access-Control-Allow-Headers\", \"Content-Type\");\n\t\t\t} else {\n\t\t\t\t// No Origin — reject only if browser signals indicate cross-site\n\t\t\t\t// (matches Python's reject_if_unsafe policy for API endpoints)\n\t\t\t\tif (isUnsafeMissingOrigin(c)) {\n\t\t\t\t\treturn c.json({ error: \"forbidden\" }, 403);\n\t\t\t\t}\n\t\t\t\t// CLI / programmatic caller — no CORS headers needed\n\t\t\t}\n\t\t} else if (origin && isLoopbackOrigin(origin)) {\n\t\t\t// Safe method with valid origin — echo for preflight\n\t\t\tc.header(\"Access-Control-Allow-Origin\", origin);\n\t\t\tc.header(\"Access-Control-Allow-Methods\", \"GET, POST, PUT, DELETE, OPTIONS\");\n\t\t\tc.header(\"Access-Control-Allow-Headers\", \"Content-Type\");\n\t\t}\n\t\t// No origin or non-loopback on safe method: no ACAO header set.\n\t\t// Browser enforces same-origin; we don't set permissive headers.\n\n\t\tawait next();\n\t});\n}\n\n/**\n * Handle OPTIONS preflight requests.\n * Returns 204 with appropriate CORS headers for loopback origins.\n */\nexport function preflightHandler() {\n\treturn createMiddleware(async (c: Context, next: Next) => {\n\t\tif (c.req.method !== \"OPTIONS\") {\n\t\t\tawait next();\n\t\t\treturn;\n\t\t}\n\t\tconst origin = c.req.header(\"Origin\");\n\t\tif (origin && isLoopbackOrigin(origin)) {\n\t\t\tc.header(\"Access-Control-Allow-Origin\", origin);\n\t\t\tc.header(\"Access-Control-Allow-Methods\", \"GET, POST, PUT, DELETE, OPTIONS\");\n\t\t\tc.header(\"Access-Control-Allow-Headers\", \"Content-Type\");\n\t\t\tc.header(\"Access-Control-Max-Age\", \"86400\");\n\t\t\treturn c.body(null, 204);\n\t\t}\n\t\treturn c.body(null, 204);\n\t});\n}\n","import { RateLimiter } from \"limiter\";\n\nexport interface InMemoryRequestRateLimiter {\n\tcheck(key: string, limit: number): { allowed: boolean; retryAfterS: number };\n}\n\nexport function createInMemoryRequestRateLimiter(windowMs = 60_000): InMemoryRequestRateLimiter {\n\tconst safeWindowMs = Math.max(1000, Math.trunc(windowMs));\n\tconst buckets = new Map<string, { limiter: RateLimiter; lastUsedAt: number }>();\n\tlet checks = 0;\n\n\tfunction estimatedRetryAfterS(limit: number): number {\n\t\treturn Math.max(1, Math.ceil(safeWindowMs / Math.max(1, limit) / 1000));\n\t}\n\n\tfunction cleanupExpiredBuckets(currentNow: number): void {\n\t\tif (buckets.size < 64 || checks % 64 !== 0) return;\n\t\tconst staleBefore = currentNow - safeWindowMs * 10;\n\t\tfor (const [key, bucket] of buckets) {\n\t\t\tif (bucket.lastUsedAt < staleBefore) buckets.delete(key);\n\t\t}\n\t}\n\n\treturn {\n\t\tcheck(key: string, limit: number) {\n\t\t\tchecks += 1;\n\t\t\tconst currentNow = Date.now();\n\t\t\tcleanupExpiredBuckets(currentNow);\n\t\t\tconst safeLimit = Math.max(1, Math.trunc(limit));\n\t\t\tconst bucketKey = `${safeLimit}:${key}`;\n\t\t\tlet bucket = buckets.get(bucketKey);\n\t\t\tif (!bucket) {\n\t\t\t\tbucket = {\n\t\t\t\t\tlimiter: new RateLimiter({\n\t\t\t\t\t\ttokensPerInterval: safeLimit,\n\t\t\t\t\t\tinterval: safeWindowMs,\n\t\t\t\t\t\tfireImmediately: true,\n\t\t\t\t\t}),\n\t\t\t\t\tlastUsedAt: currentNow,\n\t\t\t\t};\n\t\t\t\tbuckets.set(bucketKey, bucket);\n\t\t\t}\n\t\t\tbucket.lastUsedAt = currentNow;\n\t\t\tif (bucket.limiter.tryRemoveTokens(1)) {\n\t\t\t\treturn { allowed: true, retryAfterS: 0 };\n\t\t\t}\n\t\t\treturn { allowed: false, retryAfterS: estimatedRetryAfterS(safeLimit) };\n\t\t},\n\t};\n}\n","/**\n * Config routes — GET /api/config, POST /api/config.\n *\n * Ports the user-facing config read/write path from Python's\n * codemem/viewer_routes/config.py, scoped to the TS runtime's current needs.\n */\n\nimport {\n\tCODEMEM_CONFIG_ENV_OVERRIDES,\n\tcoerceObserverCommand,\n\tgetCodememConfigPath,\n\tgetCodememEnvOverrides,\n\tlistObserverProviderOptions,\n\ttype RawEventSweeper,\n\treadCodememConfigFile,\n\twriteCodememConfigFile,\n} from \"@codemem/core\";\nimport { Hono } from \"hono\";\n\ntype ConfigData = Record<string, unknown>;\n\nconst REDACTED_VALUE = \"[redacted]\";\n\nconst RUNTIMES = new Set([\"api_http\", \"claude_sidecar\", \"codex_sidecar\"]);\nconst AUTH_SOURCES = new Set([\"auto\", \"env\", \"file\", \"command\", \"none\"]);\nconst HOT_RELOAD_KEYS = new Set([\"raw_events_sweeper_interval_s\"]);\nconst PROTECTED_WRITE_KEYS = new Set<string>([\n\t\"claude_command\",\n\t\"codex_command\",\n\t\"observer_base_url\",\n\t\"observer_auth_file\",\n\t\"observer_auth_command\",\n\t\"observer_headers\",\n\t\"sync_coordinator_url\",\n] as const);\nconst SECRET_CONFIG_KEYS = new Set<string>([\n\t\"observer_auth_file\",\n\t\"observer_auth_command\",\n\t\"observer_headers\",\n\t\"sync_coordinator_admin_secret\",\n] as const);\nconst REMOVED_CONFIG_KEYS = new Set<string>([\"observer_rich_openai_use_responses\"]);\nconst ALLOWED_KEYS = [\n\t\"claude_command\",\n\t\"codex_command\",\n\t\"observer_base_url\",\n\t\"observer_provider\",\n\t\"observer_model\",\n\t\"observer_tier_routing_enabled\",\n\t\"observer_simple_model\",\n\t\"observer_simple_temperature\",\n\t\"observer_reasoning_effort\",\n\t\"observer_reasoning_summary\",\n\t\"observer_rich_model\",\n\t\"observer_rich_temperature\",\n\t\"observer_rich_reasoning_effort\",\n\t\"observer_rich_reasoning_summary\",\n\t\"observer_rich_max_output_tokens\",\n\t\"observer_runtime\",\n\t\"observer_auth_source\",\n\t\"observer_auth_file\",\n\t\"observer_auth_command\",\n\t\"observer_auth_timeout_ms\",\n\t\"observer_auth_cache_ttl_s\",\n\t\"observer_headers\",\n\t\"observer_max_chars\",\n\t\"pack_observation_limit\",\n\t\"pack_session_limit\",\n\t\"sync_enabled\",\n\t\"sync_retention_enabled\",\n\t\"sync_retention_max_age_days\",\n\t\"sync_retention_max_size_mb\",\n\t\"sync_host\",\n\t\"sync_port\",\n\t\"sync_interval_s\",\n\t\"sync_mdns\",\n\t\"sync_coordinator_url\",\n\t\"sync_coordinator_group\",\n\t\"sync_coordinator_timeout_s\",\n\t\"sync_coordinator_presence_ttl_s\",\n\t\"raw_events_sweeper_interval_s\",\n] as const;\n\nconst DEFAULTS: ConfigData = {\n\tclaude_command: [\"claude\"],\n\tcodex_command: [\"codex\"],\n\tobserver_runtime: \"api_http\",\n\tobserver_auth_source: \"auto\",\n\tobserver_tier_routing_enabled: false,\n\tobserver_auth_command: [],\n\tobserver_auth_timeout_ms: 1500,\n\tobserver_auth_cache_ttl_s: 300,\n\tobserver_headers: {},\n\tobserver_max_chars: 12000,\n\tpack_observation_limit: 50,\n\tpack_session_limit: 10,\n\tsync_enabled: false,\n\tsync_retention_enabled: false,\n\tsync_retention_max_age_days: 30,\n\tsync_retention_max_size_mb: 512,\n\tsync_host: \"0.0.0.0\",\n\tsync_port: 7337,\n\tsync_interval_s: 120,\n\tsync_mdns: true,\n\tsync_coordinator_timeout_s: 3,\n\tsync_coordinator_presence_ttl_s: 180,\n\traw_events_sweeper_interval_s: 30,\n};\n\nexport interface ConfigRouteOptions {\n\tgetSweeper?: () => RawEventSweeper | null;\n}\n\nfunction loadProviderOptions(): string[] {\n\treturn listObserverProviderOptions();\n}\n\nfunction withoutRemovedConfigKeys(configData: ConfigData): ConfigData {\n\tconst next = { ...configData };\n\tfor (const key of REMOVED_CONFIG_KEYS) {\n\t\tdelete next[key];\n\t}\n\treturn next;\n}\n\nfunction getEffectiveConfig(configData: ConfigData): ConfigData {\n\tconst effective: ConfigData = { ...DEFAULTS, ...configData };\n\tfor (const key of [\"claude_command\", \"codex_command\"] as const) {\n\t\teffective[key] = coerceObserverCommand(effective[key]) ?? DEFAULTS[key];\n\t}\n\tfor (const [key, envVar] of Object.entries(CODEMEM_CONFIG_ENV_OVERRIDES) as Array<\n\t\t[string, string]\n\t>) {\n\t\tconst val = process.env[envVar];\n\t\tif (val == null || val === \"\") continue;\n\t\tif (key === \"claude_command\" || key === \"codex_command\") {\n\t\t\teffective[key] = coerceObserverCommand(val) ?? effective[key];\n\t\t} else {\n\t\t\teffective[key] = val;\n\t\t}\n\t}\n\treturn effective;\n}\n\nfunction redactConfigValue(key: string, value: unknown): unknown {\n\tif (value == null || !SECRET_CONFIG_KEYS.has(key)) return value;\n\tif (Array.isArray(value)) return value.length > 0 ? REDACTED_VALUE : [];\n\tif (typeof value === \"object\") {\n\t\treturn Object.keys(value as Record<string, unknown>).length > 0 ? REDACTED_VALUE : {};\n\t}\n\tif (typeof value === \"string\") return value.trim() ? REDACTED_VALUE : \"\";\n\treturn REDACTED_VALUE;\n}\n\nfunction sanitizeConfigForResponse(configData: ConfigData): ConfigData {\n\tconst sanitized: ConfigData = {};\n\tfor (const [key, value] of Object.entries(configData)) {\n\t\tsanitized[key] = redactConfigValue(key, value);\n\t}\n\treturn sanitized;\n}\n\nfunction configValuesEqual(left: unknown, right: unknown): boolean {\n\tif (Object.is(left, right)) return true;\n\tif (left == null || right == null) return left == null && right == null;\n\tif (typeof left === \"object\" || typeof right === \"object\") {\n\t\treturn JSON.stringify(left) === JSON.stringify(right);\n\t}\n\treturn false;\n}\n\nfunction partitionViewerUpdates(\n\tupdates: ConfigData,\n\tbeforeConfig: ConfigData,\n): { allowedUpdates: ConfigData; error: string | null } {\n\tconst allowedUpdates: ConfigData = {};\n\tfor (const [key, value] of Object.entries(updates)) {\n\t\tif (!PROTECTED_WRITE_KEYS.has(key)) {\n\t\t\tallowedUpdates[key] = value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (SECRET_CONFIG_KEYS.has(key) && value === REDACTED_VALUE) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (configValuesEqual(value, beforeConfig[key])) {\n\t\t\tcontinue;\n\t\t}\n\t\treturn {\n\t\t\tallowedUpdates: {},\n\t\t\terror: `${key} cannot be changed from the viewer API; edit the config file or environment instead`,\n\t\t};\n\t}\n\treturn { allowedUpdates, error: null };\n}\n\nfunction parsePositiveInt(value: unknown, allowZero = false): number | null {\n\tif (typeof value === \"boolean\") return null;\n\tconst parsed =\n\t\ttypeof value === \"number\"\n\t\t\t? value\n\t\t\t: typeof value === \"string\" && /^-?\\d+$/.test(value.trim())\n\t\t\t\t? Number(value.trim())\n\t\t\t\t: Number.NaN;\n\tif (!Number.isFinite(parsed) || !Number.isInteger(parsed)) return null;\n\tif (allowZero) return parsed >= 0 ? parsed : null;\n\treturn parsed > 0 ? parsed : null;\n}\n\nfunction parseFiniteNumber(value: unknown, allowZero = true): number | null {\n\tif (typeof value === \"boolean\") return null;\n\tconst parsed =\n\t\ttypeof value === \"number\"\n\t\t\t? value\n\t\t\t: typeof value === \"string\" && value.trim().length > 0\n\t\t\t\t? Number(value.trim())\n\t\t\t\t: Number.NaN;\n\tif (!Number.isFinite(parsed)) return null;\n\tif (allowZero) return parsed >= 0 ? parsed : null;\n\treturn parsed > 0 ? parsed : null;\n}\n\nfunction asStringMap(value: unknown): Record<string, string> | null {\n\tif (value == null || typeof value !== \"object\" || Array.isArray(value)) return null;\n\tconst parsed: Record<string, string> = {};\n\tfor (const [key, item] of Object.entries(value)) {\n\t\tif (typeof item !== \"string\") return null;\n\t\tconst stripped = key.trim();\n\t\tif (!stripped) return null;\n\t\tparsed[stripped] = item;\n\t}\n\treturn parsed;\n}\n\nfunction asExecutableArgv(value: unknown): string[] | null {\n\tif (!Array.isArray(value)) return null;\n\tconst argv: string[] = [];\n\tfor (const item of value) {\n\t\tif (typeof item !== \"string\") return null;\n\t\tconst token = item.trim();\n\t\tif (!token) return null;\n\t\targv.push(token);\n\t}\n\treturn argv;\n}\n\nfunction validateAndApplyUpdate(\n\tconfigData: ConfigData,\n\tkey: (typeof ALLOWED_KEYS)[number],\n\tvalue: unknown,\n\tproviders: Set<string>,\n): string | null {\n\tif (value == null || value === \"\") {\n\t\tdelete configData[key];\n\t\treturn null;\n\t}\n\tif (key === \"observer_provider\") {\n\t\tif (typeof value !== \"string\") return \"observer_provider must be string\";\n\t\tconst provider = value.trim().toLowerCase();\n\t\tconst savedBaseUrl = configData.observer_base_url;\n\t\tconst hasSavedBaseUrl = typeof savedBaseUrl === \"string\" && savedBaseUrl.trim().length > 0;\n\t\tif (!providers.has(provider) && !hasSavedBaseUrl) {\n\t\t\treturn \"observer_provider must match a configured provider\";\n\t\t}\n\t\tconfigData[key] = provider;\n\t\treturn null;\n\t}\n\tif (key === \"observer_runtime\") {\n\t\tif (typeof value !== \"string\") return \"observer_runtime must be string\";\n\t\tconst runtime = value.trim().toLowerCase();\n\t\tif (!RUNTIMES.has(runtime)) {\n\t\t\treturn \"observer_runtime must be one of: api_http, claude_sidecar, codex_sidecar\";\n\t\t}\n\t\tconfigData[key] = runtime;\n\t\treturn null;\n\t}\n\tif (key === \"observer_auth_source\") {\n\t\tif (typeof value !== \"string\") return \"observer_auth_source must be string\";\n\t\tconst source = value.trim().toLowerCase();\n\t\tif (!AUTH_SOURCES.has(source)) {\n\t\t\treturn \"observer_auth_source must be one of: auto, env, file, command, none\";\n\t\t}\n\t\tconfigData[key] = source;\n\t\treturn null;\n\t}\n\tif (key === \"claude_command\" || key === \"codex_command\" || key === \"observer_auth_command\") {\n\t\tconst argv = asExecutableArgv(value);\n\t\tif (argv == null) return `${key} must be string array`;\n\t\tif (argv.length > 0) configData[key] = argv;\n\t\telse delete configData[key];\n\t\treturn null;\n\t}\n\tif (key === \"observer_headers\") {\n\t\tconst headers = asStringMap(value);\n\t\tif (headers == null) return \"observer_headers must be object of string values\";\n\t\tif (Object.keys(headers).length > 0) configData[key] = headers;\n\t\telse delete configData[key];\n\t\treturn null;\n\t}\n\tif (key === \"sync_enabled\" || key === \"sync_retention_enabled\" || key === \"sync_mdns\") {\n\t\tif (typeof value !== \"boolean\") return `${key} must be boolean`;\n\t\tconfigData[key] = value;\n\t\treturn null;\n\t}\n\tif (key === \"observer_tier_routing_enabled\") {\n\t\tif (typeof value !== \"boolean\") return `${key} must be boolean`;\n\t\tconfigData[key] = value;\n\t\treturn null;\n\t}\n\tif (\n\t\tkey === \"observer_base_url\" ||\n\t\tkey === \"observer_model\" ||\n\t\tkey === \"observer_simple_model\" ||\n\t\tkey === \"observer_reasoning_effort\" ||\n\t\tkey === \"observer_reasoning_summary\" ||\n\t\tkey === \"observer_rich_model\" ||\n\t\tkey === \"observer_rich_reasoning_effort\" ||\n\t\tkey === \"observer_rich_reasoning_summary\" ||\n\t\tkey === \"observer_auth_file\" ||\n\t\tkey === \"sync_host\" ||\n\t\tkey === \"sync_coordinator_url\" ||\n\t\tkey === \"sync_coordinator_group\"\n\t) {\n\t\tif (typeof value !== \"string\") return `${key} must be string`;\n\t\tconst trimmed = value.trim();\n\t\tif (!trimmed) delete configData[key];\n\t\telse configData[key] = trimmed;\n\t\treturn null;\n\t}\n\tif (key === \"observer_simple_temperature\" || key === \"observer_rich_temperature\") {\n\t\tconst parsed = parseFiniteNumber(value, true);\n\t\tif (parsed == null) return `${key} must be non-negative number`;\n\t\tconfigData[key] = parsed;\n\t\treturn null;\n\t}\n\tconst allowZero = key === \"observer_auth_cache_ttl_s\";\n\tconst parsed = parsePositiveInt(value, allowZero);\n\tif (parsed == null) return `${key} must be ${allowZero ? \"non-negative int\" : \"int\"}`;\n\tconfigData[key] = parsed;\n\treturn null;\n}\n\nfunction applyRuntimeEffects(changedKeys: string[], opts: ConfigRouteOptions): string[] {\n\tconst applied: string[] = [];\n\tif (changedKeys.includes(\"raw_events_sweeper_interval_s\")) {\n\t\tconst configValue = readCodememConfigFile().raw_events_sweeper_interval_s;\n\t\tconst seconds =\n\t\t\ttypeof configValue === \"number\"\n\t\t\t\t? configValue\n\t\t\t\t: Number.parseInt(String(configValue ?? \"\"), 10);\n\t\tif (Number.isFinite(seconds) && seconds > 0) {\n\t\t\tprocess.env.CODEMEM_RAW_EVENTS_SWEEPER_INTERVAL_MS = String(seconds * 1000);\n\t\t} else {\n\t\t\tdelete process.env.CODEMEM_RAW_EVENTS_SWEEPER_INTERVAL_MS;\n\t\t}\n\t\topts.getSweeper?.()?.notifyConfigChanged();\n\t\tapplied.push(\"raw_events_sweeper_interval_s\");\n\t}\n\treturn applied;\n}\n\nexport function configRoutes(opts: ConfigRouteOptions = {}) {\n\tconst app = new Hono();\n\n\tapp.get(\"/api/config\", (c) => {\n\t\t// Resolve via the core resolver so GET reflects the same file POST\n\t\t// writes — including workspace-scoped overrides honored through\n\t\t// CODEMEM_RUNTIME_ROOT / CODEMEM_WORKSPACE_ID, which the legacy local\n\t\t// getConfigPath() ignored.\n\t\tconst configPath = getCodememConfigPath();\n\t\tconst configData = withoutRemovedConfigKeys(readCodememConfigFile());\n\t\tconst effective = getEffectiveConfig(configData);\n\t\treturn c.json({\n\t\t\tpath: configPath,\n\t\t\tconfig: sanitizeConfigForResponse(configData),\n\t\t\tdefaults: DEFAULTS,\n\t\t\teffective: sanitizeConfigForResponse(effective),\n\t\t\tenv_overrides: getCodememEnvOverrides(),\n\t\t\tprotected_keys: [...PROTECTED_WRITE_KEYS].sort(),\n\t\t\tproviders: loadProviderOptions(),\n\t\t});\n\t});\n\n\tapp.post(\"/api/config\", async (c) => {\n\t\tlet payload: unknown;\n\t\ttry {\n\t\t\tpayload = (await c.req.json()) as unknown;\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\" }, 400);\n\t\t}\n\t\tif (payload == null || typeof payload !== \"object\" || Array.isArray(payload)) {\n\t\t\treturn c.json({ error: \"payload must be an object\" }, 400);\n\t\t}\n\t\tif (\n\t\t\t\"config\" in payload &&\n\t\t\t(payload as ConfigData).config != null &&\n\t\t\t(typeof (payload as ConfigData).config !== \"object\" ||\n\t\t\t\tArray.isArray((payload as ConfigData).config))\n\t\t) {\n\t\t\treturn c.json({ error: \"config must be an object\" }, 400);\n\t\t}\n\t\tconst updates =\n\t\t\t\"config\" in payload &&\n\t\t\t(payload as ConfigData).config != null &&\n\t\t\ttypeof (payload as ConfigData).config === \"object\" &&\n\t\t\t!Array.isArray((payload as ConfigData).config)\n\t\t\t\t? ((payload as ConfigData).config as ConfigData)\n\t\t\t\t: (payload as ConfigData);\n\n\t\tconst configPath = getCodememConfigPath();\n\t\tconst beforeConfig = withoutRemovedConfigKeys(readCodememConfigFile());\n\t\tconst { allowedUpdates, error: protectedKeyError } = partitionViewerUpdates(\n\t\t\tupdates,\n\t\t\tbeforeConfig,\n\t\t);\n\t\tif (protectedKeyError) {\n\t\t\treturn c.json({ error: protectedKeyError }, 403);\n\t\t}\n\n\t\tconst beforeEffective = getEffectiveConfig(beforeConfig);\n\t\tconst nextConfig: ConfigData = { ...beforeConfig };\n\t\tconst providers = new Set(loadProviderOptions());\n\n\t\tconst touchedKeys = ALLOWED_KEYS.filter((key) => key in allowedUpdates);\n\t\tfor (const key of ALLOWED_KEYS) {\n\t\t\tif (!(key in allowedUpdates)) continue;\n\t\t\tconst error = validateAndApplyUpdate(nextConfig, key, allowedUpdates[key], providers);\n\t\t\tif (error) return c.json({ error }, 400);\n\t\t}\n\n\t\tlet savedPath: string;\n\t\ttry {\n\t\t\tsavedPath = writeCodememConfigFile(nextConfig, configPath);\n\t\t} catch {\n\t\t\treturn c.json({ error: \"failed to write config\" }, 500);\n\t\t}\n\n\t\tconst afterEffective = getEffectiveConfig(nextConfig);\n\t\tconst savedChangedKeys = ALLOWED_KEYS.filter((key) => beforeConfig[key] !== nextConfig[key]);\n\t\tconst effectiveChangedKeys = ALLOWED_KEYS.filter(\n\t\t\t(key) => !configValuesEqual(beforeEffective[key], afterEffective[key]),\n\t\t);\n\t\tconst envOverrides = getCodememEnvOverrides();\n\t\tconst ignoredByEnvKeys = savedChangedKeys.filter(\n\t\t\t(key) => !effectiveChangedKeys.includes(key) && key in envOverrides,\n\t\t);\n\t\tconst runtimeChangedKeys = [\n\t\t\t...new Set([...touchedKeys, ...savedChangedKeys, ...effectiveChangedKeys]),\n\t\t];\n\t\tconst hotReloadedKeys = applyRuntimeEffects(runtimeChangedKeys, opts);\n\t\tconst restartRequiredKeys = effectiveChangedKeys.filter(\n\t\t\t(key) => !HOT_RELOAD_KEYS.has(key) && !(key in envOverrides),\n\t\t);\n\n\t\treturn c.json({\n\t\t\tpath: savedPath,\n\t\t\tconfig: sanitizeConfigForResponse(nextConfig),\n\t\t\teffective: sanitizeConfigForResponse(afterEffective),\n\t\t\tprotected_keys: [...PROTECTED_WRITE_KEYS].sort(),\n\t\t\teffects: {\n\t\t\t\tsaved_keys: savedChangedKeys,\n\t\t\t\teffective_keys: effectiveChangedKeys,\n\t\t\t\thot_reloaded_keys: hotReloadedKeys,\n\t\t\t\trestart_required_keys: restartRequiredKeys,\n\t\t\t\tignored_by_env_keys: ignoredByEnvKeys,\n\t\t\t\twarnings: ignoredByEnvKeys.map(\n\t\t\t\t\t(key) =>\n\t\t\t\t\t\t`${key} is currently controlled by ${envOverrides[key]}; saved config will not take effect until that override is removed.`,\n\t\t\t\t),\n\t\t\t},\n\t\t});\n\t});\n\n\treturn app;\n}\n","import { type MemoryStore, VERSION, VIEWER_SERVICE_DISCRIMINATOR } from \"@codemem/core\";\nimport { Hono } from \"hono\";\n\ntype StoreFactory = () => MemoryStore;\n\nfunction databaseReachable(getStore: StoreFactory): boolean {\n\ttry {\n\t\tgetStore().db.pragma(\"schema_version\", { simple: true });\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport function healthRoutes(getStore: StoreFactory) {\n\tconst app = new Hono();\n\n\tapp.get(\"/api/health\", (c) => {\n\t\tconst reachable = databaseReachable(getStore);\n\t\tc.header(\"Cache-Control\", \"no-store\");\n\t\treturn c.json({\n\t\t\t// Bound to the shared probe contract so producer and clients\n\t\t\t// cannot drift independently.\n\t\t\tservice: VIEWER_SERVICE_DISCRIMINATOR,\n\t\t\tversion: VERSION,\n\t\t\tpid: process.pid,\n\t\t\tuptime_ms: Math.max(0, Math.floor(process.uptime() * 1_000)),\n\t\t\t// Database reachability is the only readiness dependency in this endpoint.\n\t\t\tready: reachable,\n\t\t\tdatabase: { reachable },\n\t\t});\n\t});\n\n\treturn app;\n}\n","import { parseStrictInteger } from \"@codemem/core\";\n\n/**\n * Shared helpers for viewer-server routes.\n */\n\n/**\n * Parse a JSON string that should be an array of strings.\n * Returns an empty array on null, invalid JSON, or non-array values.\n * Mirrors Python's store._safe_json_list().\n */\nexport function safeJsonList(raw: string | null | undefined): string[] {\n\tif (raw == null) return [];\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(raw);\n\t\tif (!Array.isArray(parsed)) return [];\n\t\treturn parsed.filter((item): item is string => typeof item === \"string\");\n\t} catch {\n\t\treturn [];\n\t}\n}\n\n/**\n * Parse a query parameter as an integer, returning the default on failure.\n */\nexport function queryInt(value: string | undefined, defaultValue: number): number {\n\tif (value == null) return defaultValue;\n\tconst parsed = parseStrictInteger(value);\n\treturn parsed == null ? defaultValue : parsed;\n}\n\n/**\n * Parse a query parameter as a boolean flag.\n * Recognizes \"1\", \"true\", \"yes\" as truthy.\n */\nexport function queryBool(value: string | undefined): boolean {\n\tif (value == null) return false;\n\treturn value === \"1\" || value === \"true\" || value === \"yes\";\n}\n\n/**\n * Parse and validate a JSON object body, enforcing size limits.\n * Returns the parsed payload or a Hono Response on error.\n */\nexport async function parseJsonObjectBody(\n\tc: {\n\t\treq: { header: (name: string) => string | undefined; raw: Request };\n\t\tjson: (data: unknown, status?: number) => Response;\n\t},\n\tmaxBytes: number,\n): Promise<Record<string, unknown> | Response> {\n\tconst contentLength = Number.parseInt(c.req.header(\"content-length\") ?? \"0\", 10);\n\tif (Number.isNaN(contentLength) || contentLength < 0) {\n\t\treturn c.json({ error: \"invalid content-length\" }, 400);\n\t}\n\tif (contentLength > maxBytes) {\n\t\treturn c.json({ error: \"payload too large\", max_bytes: maxBytes }, 413);\n\t}\n\tlet raw = \"\";\n\ttry {\n\t\tconst body = c.req.raw.body;\n\t\tif (body !== null) {\n\t\t\tconst reader = body.getReader();\n\t\t\tconst chunks: Uint8Array[] = [];\n\t\t\tlet totalBytes = 0;\n\t\t\ttry {\n\t\t\t\twhile (true) {\n\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\tif (done) break;\n\t\t\t\t\ttotalBytes += value.byteLength;\n\t\t\t\t\tif (totalBytes > maxBytes) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait reader.cancel();\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t// The size rejection is authoritative even if cancellation fails.\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn c.json({ error: \"payload too large\", max_bytes: maxBytes }, 413);\n\t\t\t\t\t}\n\t\t\t\t\tchunks.push(value);\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\treader.releaseLock();\n\t\t\t}\n\n\t\t\tconst bytes = new Uint8Array(totalBytes);\n\t\t\tlet offset = 0;\n\t\t\tfor (const chunk of chunks) {\n\t\t\t\tbytes.set(chunk, offset);\n\t\t\t\toffset += chunk.byteLength;\n\t\t\t}\n\t\t\traw = new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n\t\t}\n\t} catch {\n\t\treturn c.json({ error: \"invalid json\" }, 400);\n\t}\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = raw ? JSON.parse(raw) : {};\n\t} catch {\n\t\treturn c.json({ error: \"invalid json\" }, 400);\n\t}\n\tif (parsed == null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n\t\treturn c.json({ error: \"payload must be an object\" }, 400);\n\t}\n\treturn parsed as Record<string, unknown>;\n}\n","/**\n * Memory routes — observations, summaries, sessions, projects, pack, artifacts.\n */\n\nimport type { MemoryFilters, MemoryStore } from \"@codemem/core\";\nimport {\n\tbuildFilterClausesWithContext,\n\tcanonicalMemoryKind,\n\tfromJson,\n\tnormalizeHumanPresentationName,\n\tparsePositiveMemoryId,\n\tparseStrictInteger,\n\tschema,\n} from \"@codemem/core\";\nimport { eq, inArray } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport { Hono } from \"hono\";\nimport { queryInt } from \"../helpers.js\";\n\ntype StoreFactory = () => MemoryStore;\n\ntype OwnershipPredicate = (item: Record<string, unknown>) => boolean;\n\nconst MAX_FEED_QUERY_CODE_UNITS = 256;\nconst searchFunctionsRegisteredStores = new WeakSet<MemoryStore>();\n\nfunction casefold(value: unknown): string {\n\treturn String(value ?? \"\").toLowerCase();\n}\n\nfunction normalizeMemorySearchQuery(value: string | undefined): string | undefined {\n\tconst normalized = casefold(value?.trim()).slice(0, MAX_FEED_QUERY_CODE_UNITS);\n\treturn normalized || undefined;\n}\n\nfunction ensureMemorySearchFunctions(store: MemoryStore): void {\n\tif (searchFunctionsRegisteredStores.has(store)) return;\n\tstore.db.function(\"codemem_casefold\", { deterministic: true }, casefold);\n\tstore.db.function(\"codemem_project_basename\", { deterministic: true }, (value: unknown) =>\n\t\tprojectBasename(String(value ?? \"\").trim()),\n\t);\n\tsearchFunctionsRegisteredStores.add(store);\n}\n\ninterface ActorPresentationRow {\n\tactor_id: string;\n\tdisplay_name: string;\n\tstatus: string;\n\tmerged_into_actor_id: string | null;\n}\n\ninterface DevicePresentationRow {\n\tdevice_id: string;\n\tdisplay_name: string;\n}\n\ninterface PeerPresentationRow {\n\tpeer_device_id: string;\n\tname: string | null;\n\tactor_id: string | null;\n}\n\nconst IDENTITY_LOOKUP_BATCH_SIZE = 500;\n\nfunction identityValue(item: Record<string, unknown>, key: string): string {\n\tconst direct = String(item[key] ?? \"\").trim();\n\tif (direct) return direct;\n\tconst rawMetadata = item.metadata ?? item.metadata_json;\n\tconst metadata = typeof rawMetadata === \"string\" ? fromJson(rawMetadata) : rawMetadata;\n\tif (!metadata || typeof metadata !== \"object\" || Array.isArray(metadata)) return \"\";\n\treturn String((metadata as Record<string, unknown>)[key] ?? \"\").trim();\n}\n\nfunction uniqueStrings(items: Record<string, unknown>[], key: string): string[] {\n\treturn [...new Set(items.map((item) => identityValue(item, key)).filter(Boolean))];\n}\n\nfunction batchedLookup<T>(\n\tstore: MemoryStore,\n\tvalues: string[],\n\tquery: (placeholders: string) => string,\n): T[] {\n\tconst rows: T[] = [];\n\tfor (let offset = 0; offset < values.length; offset += IDENTITY_LOOKUP_BATCH_SIZE) {\n\t\tconst batch = values.slice(offset, offset + IDENTITY_LOOKUP_BATCH_SIZE);\n\t\tconst placeholders = batch.map(() => \"?\").join(\", \");\n\t\trows.push(...(store.db.prepare(query(placeholders)).all(...batch) as T[]));\n\t}\n\treturn rows;\n}\n\nfunction humanName(value: unknown): string | undefined {\n\tif (typeof value !== \"string\") return undefined;\n\ttry {\n\t\treturn normalizeHumanPresentationName(value, \"display_name\");\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Add presentation-only identity labels without changing persisted provenance.\n * Resolved names are display hints, not authority or ownership evidence; legacy\n * metadata receives the same top-level-first fallback as existing read paths.\n */\nfunction attachResolvedIdentityFieldsUnsafe(\n\tstore: MemoryStore,\n\titems: Record<string, unknown>[],\n): void {\n\tconst actorIds = uniqueStrings(items, \"actor_id\");\n\tconst deviceIds = uniqueStrings(items, \"origin_device_id\");\n\tconst peers = batchedLookup<PeerPresentationRow>(\n\t\tstore,\n\t\tdeviceIds,\n\t\t(placeholders) =>\n\t\t\t`SELECT peer_device_id, name, actor_id FROM sync_peers\n\t\t WHERE peer_device_id IN (${placeholders})\n\t\t AND TRIM(COALESCE(pinned_fingerprint, '')) <> ''`,\n\t);\n\tconst peerByDevice = new Map(peers.map((peer) => [peer.peer_device_id, peer]));\n\tconst peerActorIds = peers\n\t\t.map((peer) => String(peer.actor_id ?? \"\").trim())\n\t\t.filter((actorId) => actorId.length > 0);\n\tconst actorRows = batchedLookup<ActorPresentationRow>(\n\t\tstore,\n\t\t[...new Set([...actorIds, ...peerActorIds])],\n\t\t(placeholders) =>\n\t\t\t`SELECT actor_id, display_name, status, merged_into_actor_id FROM actors\n\t\t\t WHERE actor_id IN (${placeholders})`,\n\t);\n\tconst devices = batchedLookup<DevicePresentationRow>(\n\t\tstore,\n\t\tdeviceIds,\n\t\t(placeholders) =>\n\t\t\t`SELECT device_id, display_name FROM identity_devices\n\t\t WHERE device_id IN (${placeholders}) AND status = 'active'`,\n\t);\n\tconst actorById = new Map(actorRows.map((actor) => [actor.actor_id, actor] as const));\n\tlet pendingMergeTargets = [\n\t\t...new Set(\n\t\t\tactorRows\n\t\t\t\t.map((actor) => String(actor.merged_into_actor_id ?? \"\").trim())\n\t\t\t\t.filter((actorId) => actorId && !actorById.has(actorId)),\n\t\t),\n\t];\n\twhile (pendingMergeTargets.length > 0) {\n\t\tconst targetRows = batchedLookup<ActorPresentationRow>(\n\t\t\tstore,\n\t\t\tpendingMergeTargets,\n\t\t\t(placeholders) =>\n\t\t\t\t`SELECT actor_id, display_name, status, merged_into_actor_id FROM actors\n\t\t\t\t WHERE actor_id IN (${placeholders})`,\n\t\t);\n\t\tfor (const actor of targetRows) actorById.set(actor.actor_id, actor);\n\t\tpendingMergeTargets = [\n\t\t\t...new Set(\n\t\t\t\ttargetRows\n\t\t\t\t\t.map((actor) => String(actor.merged_into_actor_id ?? \"\").trim())\n\t\t\t\t\t.filter((actorId) => actorId && !actorById.has(actorId)),\n\t\t\t),\n\t\t];\n\t}\n\tconst resolvedActorName = (actorId: string): string | undefined => {\n\t\tconst seen = new Set<string>();\n\t\tlet currentActorId = actorId;\n\t\twhile (currentActorId && !seen.has(currentActorId)) {\n\t\t\tseen.add(currentActorId);\n\t\t\tconst actor = actorById.get(currentActorId);\n\t\t\tif (!actor) return undefined;\n\t\t\tif (actor.status === \"active\" && actor.merged_into_actor_id === null) {\n\t\t\t\treturn humanName(actor.display_name);\n\t\t\t}\n\t\t\tcurrentActorId = String(actor.merged_into_actor_id ?? \"\").trim();\n\t\t}\n\t\treturn undefined;\n\t};\n\tconst deviceNameById = new Map(\n\t\tdevices\n\t\t\t.map((device) => [device.device_id, humanName(device.display_name)] as const)\n\t\t\t.filter((entry): entry is readonly [string, string] => entry[1] !== undefined),\n\t);\n\n\tfor (const item of items) {\n\t\tconst actorId = identityValue(item, \"actor_id\");\n\t\tconst deviceId = identityValue(item, \"origin_device_id\");\n\t\tconst peer = peerByDevice.get(deviceId);\n\t\tconst peerActorId = String(peer?.actor_id ?? \"\").trim();\n\t\tconst knownMemoryActor = actorById.has(actorId);\n\t\tconst actorName = knownMemoryActor\n\t\t\t? (resolvedActorName(actorId) ?? humanName(item.actor_display_name))\n\t\t\t: (resolvedActorName(peerActorId) ?? humanName(item.actor_display_name));\n\t\tconst deviceName = deviceNameById.get(deviceId) ?? humanName(peer?.name);\n\t\tif (actorName) item.resolved_actor_display_name = actorName;\n\t\tif (deviceName) item.resolved_device_display_name = deviceName;\n\t}\n}\n\nfunction attachResolvedIdentityFields(store: MemoryStore, items: Record<string, unknown>[]): void {\n\ttry {\n\t\tattachResolvedIdentityFieldsUnsafe(store, items);\n\t} catch {\n\t\t// Presentation enrichment is optional; neutral Feed fallbacks must remain\n\t\t// available for legacy or partially initialized databases.\n\t}\n}\n\nfunction serializeMemoryRow(\n\townedBySelf: OwnershipPredicate,\n\trow: Record<string, unknown>,\n): Record<string, unknown> {\n\tconst metadata = fromJson((row.metadata_json as string) ?? null);\n\t// Evaluate ownership against the raw row (top-level columns + metadata_json\n\t// fallback) before we overwrite metadata_json with the parsed object.\n\tconst owned_by_self = ownedBySelf(row);\n\treturn {\n\t\t...row,\n\t\tkind: canonicalMemoryKind((row.kind as string | null | undefined) ?? null, row.metadata_json),\n\t\tmetadata_json: metadata,\n\t\towned_by_self,\n\t};\n}\n\n/**\n * Attach session project/cwd fields to memory items.\n */\nfunction attachSessionFields(store: MemoryStore, items: Record<string, unknown>[]): void {\n\tconst sessionIds: number[] = [];\n\tconst seen = new Set<number>();\n\tfor (const item of items) {\n\t\tconst value = item.session_id;\n\t\tif (value == null) continue;\n\t\tconst sid = Number(value);\n\t\tif (Number.isNaN(sid) || seen.has(sid)) continue;\n\t\tseen.add(sid);\n\t\tsessionIds.push(sid);\n\t}\n\tif (sessionIds.length === 0) return;\n\n\tconst d = drizzle(store.db, { schema });\n\tconst rows = d\n\t\t.select({\n\t\t\tid: schema.sessions.id,\n\t\t\tproject: schema.sessions.project,\n\t\t\tcwd: schema.sessions.cwd,\n\t\t})\n\t\t.from(schema.sessions)\n\t\t.where(inArray(schema.sessions.id, sessionIds))\n\t\t.all();\n\n\tconst bySession = new Map<number, { project: string; cwd: string }>();\n\tfor (const row of rows) {\n\t\tconst projectRaw = String(row.project ?? \"\").trim();\n\t\tconst project = projectRaw ? projectBasename(projectRaw) : \"\";\n\t\tconst cwd = String(row.cwd ?? \"\");\n\t\tbySession.set(row.id, { project, cwd });\n\t}\n\n\tfor (const item of items) {\n\t\tconst sid = Number(item.session_id);\n\t\tif (Number.isNaN(sid)) continue;\n\t\tconst fields = bySession.get(sid);\n\t\tif (!fields) continue;\n\t\titem.project ??= fields.project;\n\t\titem.cwd ??= fields.cwd;\n\t}\n}\n\n/**\n * Extract the basename of a project path.\n * Strips \"fatal:\" prefixed values.\n */\nfunction projectBasename(raw: string): string {\n\tif (raw.toLowerCase().startsWith(\"fatal:\")) return \"\";\n\tconst parts = raw.replace(/\\\\/g, \"/\").split(\"/\");\n\treturn parts[parts.length - 1] ?? raw;\n}\n\nfunction normalizeScope(raw: string | undefined): \"mine\" | \"theirs\" | undefined {\n\tconst value = String(raw ?? \"\")\n\t\t.trim()\n\t\t.toLowerCase();\n\tif (value === \"mine\" || value === \"theirs\") return value;\n\treturn undefined;\n}\n\nfunction buildViewerMemoryFilters(store: MemoryStore, filters?: MemoryFilters | null) {\n\treturn buildFilterClausesWithContext(filters, store.ownershipFilterContext());\n}\n\nfunction countVisibleMemoryRows(store: MemoryStore, filters?: MemoryFilters | null): number {\n\tconst filterResult = buildViewerMemoryFilters(store, filters);\n\tconst clauses = [\"memory_items.active = 1\", ...filterResult.clauses];\n\tconst from = filterResult.joinSessions\n\t\t? \"memory_items JOIN sessions ON sessions.id = memory_items.session_id\"\n\t\t: \"memory_items\";\n\tconst row = store.db\n\t\t.prepare(`SELECT COUNT(*) AS total FROM ${from} WHERE ${clauses.join(\" AND \")}`)\n\t\t.get(...filterResult.params) as Record<string, unknown> | undefined;\n\treturn Number(row?.total ?? 0);\n}\n\nfunction summaryLikeSqlPredicate(): string {\n\treturn `(\n\t\tLOWER(TRIM(COALESCE(memory_items.kind, ''))) = 'session_summary'\n\t\tOR (\n\t\t\tjson_valid(COALESCE(memory_items.metadata_json, ''))\n\t\t\tAND (\n\t\t\t\tCOALESCE(json_type(memory_items.metadata_json, '$.is_summary') = 'true', 0)\n\t\t\t\tOR LOWER(TRIM(COALESCE(json_extract(memory_items.metadata_json, '$.source'), ''))) = 'observer_summary'\n\t\t\t)\n\t\t)\n\t)`;\n}\n\nfunction memorySearchSql(query: string): { clause: string; params: unknown[] } {\n\tconst textClause = `INSTR(codemem_casefold(\n\t\tCOALESCE(memory_items.title, '') || CHAR(10) ||\n\t\tCOALESCE(memory_items.body_text, '') || CHAR(10) ||\n\t\tCASE WHEN ${summaryLikeSqlPredicate()} THEN 'session_summary' ELSE\n\t\t\tCOALESCE(NULLIF(LOWER(TRIM(COALESCE(memory_items.kind, ''))), ''), 'change')\n\t\tEND || CHAR(10) ||\n\t\tCOALESCE(\n\t\t\tmemory_items.project,\n\t\t\tcodemem_project_basename(\n\t\t\t\t(SELECT sessions.project FROM sessions WHERE sessions.id = memory_items.session_id)\n\t\t\t),\n\t\t\t''\n\t\t) || CHAR(10) ||\n\t\tCOALESCE(memory_items.tags_text, '') || CHAR(10) ||\n\t\tCOALESCE(memory_items.facts, '') || CHAR(10) ||\n\t\tCOALESCE(memory_items.subtitle, '') || CHAR(10) ||\n\t\tCOALESCE(memory_items.narrative, '') || CHAR(10) ||\n\t\tCASE WHEN json_valid(COALESCE(memory_items.metadata_json, '')) THEN\n\t\t\tCOALESCE(json_extract(memory_items.metadata_json, '$.request'), '') || CHAR(10) ||\n\t\t\tCOALESCE(json_extract(memory_items.metadata_json, '$.subtitle'), '') || CHAR(10) ||\n\t\t\tCOALESCE(json_extract(memory_items.metadata_json, '$.narrative'), '') || CHAR(10) ||\n\t\t\tCOALESCE(json_extract(memory_items.metadata_json, '$.facts'), '') || CHAR(10) ||\n\t\t\tCOALESCE(json_extract(memory_items.metadata_json, '$.summary'), '')\n\t\tELSE '' END\n\t), codemem_casefold(?)) > 0`;\n\tconst parsedMemoryId = parsePositiveMemoryId(query);\n\tconst memoryId =\n\t\tparsedMemoryId != null && String(parsedMemoryId) === query ? parsedMemoryId : null;\n\tif (memoryId != null) {\n\t\treturn { clause: `(memory_items.id = ? OR ${textClause})`, params: [memoryId, query] };\n\t}\n\treturn { clause: textClause, params: [query] };\n}\n\nfunction countVisibleObservationRows(store: MemoryStore, filters?: MemoryFilters | null): number {\n\tconst filterResult = buildViewerMemoryFilters(store, filters);\n\tconst clauses = [\n\t\t\"memory_items.active = 1\",\n\t\t`NOT ${summaryLikeSqlPredicate()}`,\n\t\t...filterResult.clauses,\n\t];\n\tconst from = filterResult.joinSessions\n\t\t? \"memory_items JOIN sessions ON sessions.id = memory_items.session_id\"\n\t\t: \"memory_items\";\n\tconst row = store.db\n\t\t.prepare(`SELECT COUNT(*) AS total FROM ${from} WHERE ${clauses.join(\" AND \")}`)\n\t\t.get(...filterResult.params) as Record<string, unknown> | undefined;\n\treturn Number(row?.total ?? 0);\n}\n\nfunction sessionAllowsArtifactAccess(store: MemoryStore, sessionId: number): boolean {\n\tconst visibleCount = countVisibleMemoryRows(store, { session_id: sessionId });\n\tif (visibleCount === 0) return false;\n\tconst row = store.db\n\t\t.prepare(\n\t\t\t`SELECT COUNT(*) AS total FROM memory_items\n\t\t\t WHERE session_id = ? AND active = 1`,\n\t\t)\n\t\t.get(sessionId) as Record<string, unknown> | undefined;\n\treturn visibleCount === Number(row?.total ?? 0);\n}\n\nfunction countVisiblePromptRows(store: MemoryStore, project?: string | null): number {\n\tconst filterResult = buildViewerMemoryFilters(store, null);\n\tconst clauses = [\n\t\t\"user_prompts.session_id IS NOT NULL\",\n\t\t`EXISTS (\n\t\t\tSELECT 1 FROM memory_items\n\t\t\tWHERE memory_items.session_id = user_prompts.session_id\n\t\t\t AND memory_items.active = 1\n\t\t\t AND ${filterResult.clauses.join(\" AND \")}\n\t\t)`,\n\t];\n\tconst params: unknown[] = [...filterResult.params];\n\tif (project) {\n\t\tclauses.unshift(\"user_prompts.project = ?\");\n\t\tparams.unshift(project);\n\t}\n\tconst row = store.db\n\t\t.prepare(`SELECT COUNT(*) AS total FROM user_prompts WHERE ${clauses.join(\" AND \")}`)\n\t\t.get(...params) as Record<string, unknown> | undefined;\n\treturn Number(row?.total ?? 0);\n}\n\nfunction countVisibleArtifactRows(store: MemoryStore, project?: string | null): number {\n\tconst filterResult = buildViewerMemoryFilters(store, null);\n\tconst clauses = [\n\t\t`EXISTS (\n\t\t\tSELECT 1 FROM memory_items\n\t\t\tWHERE memory_items.session_id = artifacts.session_id\n\t\t\t AND memory_items.active = 1\n\t\t\t AND ${filterResult.clauses.join(\" AND \")}\n\t\t)`,\n\t];\n\tconst params: unknown[] = [...filterResult.params];\n\tconst from = project\n\t\t? \"artifacts JOIN sessions ON sessions.id = artifacts.session_id\"\n\t\t: \"artifacts\";\n\tif (project) {\n\t\tclauses.unshift(\"sessions.project = ?\");\n\t\tparams.unshift(project);\n\t}\n\tconst row = store.db\n\t\t.prepare(`SELECT COUNT(*) AS total FROM ${from} WHERE ${clauses.join(\" AND \")}`)\n\t\t.get(...params) as Record<string, unknown> | undefined;\n\treturn Number(row?.total ?? 0);\n}\n\nfunction queryMemoryPage(\n\tstore: MemoryStore,\n\toptions: {\n\t\tlimit: number;\n\t\toffset: number;\n\t\tproject?: string;\n\t\tscope?: \"mine\" | \"theirs\";\n\t\tq?: string;\n\t\tclassification: \"observation\" | \"summary\";\n\t},\n): Record<string, unknown>[] {\n\tensureMemorySearchFunctions(store);\n\tconst filters: MemoryFilters = {};\n\tif (options.project) filters.project = options.project;\n\tif (options.scope) filters.ownership_scope = options.scope;\n\n\tconst filterResult = buildViewerMemoryFilters(store, filters);\n\tconst summaryPredicate = summaryLikeSqlPredicate();\n\tconst clauses = [\n\t\t\"memory_items.active = 1\",\n\t\toptions.classification === \"summary\" ? summaryPredicate : `NOT ${summaryPredicate}`,\n\t\t...filterResult.clauses,\n\t];\n\tconst params: unknown[] = [...filterResult.params];\n\tif (options.q) {\n\t\tconst search = memorySearchSql(options.q);\n\t\tclauses.push(search.clause);\n\t\tparams.push(...search.params);\n\t}\n\tconst where = clauses.join(\" AND \");\n\tconst from = filterResult.joinSessions\n\t\t? \"memory_items JOIN sessions ON sessions.id = memory_items.session_id\"\n\t\t: \"memory_items\";\n\n\tconst rows = store.db\n\t\t.prepare(\n\t\t\t`SELECT memory_items.* FROM ${from}\n\t\t\t WHERE ${where}\n\t\t\t ORDER BY memory_items.created_at DESC, memory_items.id DESC\n\t\t\t LIMIT ? OFFSET ?`,\n\t\t)\n\t\t.all(...params, options.limit + 1, options.offset) as Record<string, unknown>[];\n\n\tconst ownedBySelf = store.buildOwnershipPredicate();\n\treturn rows.map((row) => serializeMemoryRow(ownedBySelf, row));\n}\n\nexport function memoryRoutes(getStore: StoreFactory) {\n\tconst app = new Hono();\n\n\t// GET /api/sessions\n\tapp.get(\"/api/sessions\", (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tconst limit = queryInt(c.req.query(\"limit\"), 20);\n\t\t\tconst filterResult = buildViewerMemoryFilters(store, null);\n\t\t\tconst clauses = [\n\t\t\t\t\"memory_items.session_id = sessions.id\",\n\t\t\t\t\"memory_items.active = 1\",\n\t\t\t\t...filterResult.clauses,\n\t\t\t];\n\t\t\tconst rows = store.db\n\t\t\t\t.prepare(\n\t\t\t\t\t`SELECT sessions.* FROM sessions\n\t\t\t\t\t WHERE EXISTS (SELECT 1 FROM memory_items WHERE ${clauses.join(\" AND \")})\n\t\t\t\t\t ORDER BY sessions.started_at DESC\n\t\t\t\t\t LIMIT ?`,\n\t\t\t\t)\n\t\t\t\t.all(...filterResult.params, limit) as Record<string, unknown>[];\n\t\t\tconst items = rows.map((row) => ({\n\t\t\t\t...row,\n\t\t\t\tmetadata_json: fromJson((row.metadata_json as string | null | undefined) ?? null),\n\t\t\t}));\n\t\t\treturn c.json({ items });\n\t\t}\n\t});\n\n\t// GET /api/projects\n\tapp.get(\"/api/projects\", (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tconst filterResult = buildViewerMemoryFilters(store, null);\n\t\t\tconst clauses = [\n\t\t\t\t\"memory_items.session_id = sessions.id\",\n\t\t\t\t\"memory_items.active = 1\",\n\t\t\t\t\"sessions.project IS NOT NULL\",\n\t\t\t\t...filterResult.clauses,\n\t\t\t];\n\t\t\tconst rows = store.db\n\t\t\t\t.prepare(\n\t\t\t\t\t`SELECT DISTINCT sessions.project AS project FROM sessions\n\t\t\t\t\t JOIN memory_items ON memory_items.session_id = sessions.id\n\t\t\t\t\t WHERE ${clauses.join(\" AND \")}`,\n\t\t\t\t)\n\t\t\t\t.all(...filterResult.params) as Record<string, unknown>[];\n\t\t\tconst projects = [\n\t\t\t\t...new Set(\n\t\t\t\t\trows\n\t\t\t\t\t\t.map((r) => String(r.project ?? \"\").trim())\n\t\t\t\t\t\t.filter((p) => p && !p.toLowerCase().startsWith(\"fatal:\"))\n\t\t\t\t\t\t.map((p) => projectBasename(p))\n\t\t\t\t\t\t.filter(Boolean),\n\t\t\t\t),\n\t\t\t].sort();\n\t\t\treturn c.json({ projects });\n\t\t}\n\t});\n\n\t// GET /api/observations (aliased from /api/memories)\n\tapp.get(\"/api/memories\", (c) => {\n\t\tconst search = new URL(c.req.url).search;\n\t\treturn c.redirect(`/api/observations${search}`, 301);\n\t});\n\n\tapp.get(\"/api/observations\", (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tconst limit = Math.max(1, queryInt(c.req.query(\"limit\"), 20));\n\t\t\tconst offset = Math.max(0, queryInt(c.req.query(\"offset\"), 0));\n\t\t\tconst project = c.req.query(\"project\") || undefined;\n\t\t\tconst scope = normalizeScope(c.req.query(\"scope\"));\n\t\t\tconst q = normalizeMemorySearchQuery(c.req.query(\"q\"));\n\t\t\tconst items = queryMemoryPage(store, {\n\t\t\t\tlimit,\n\t\t\t\toffset,\n\t\t\t\tproject,\n\t\t\t\tscope,\n\t\t\t\tq,\n\t\t\t\tclassification: \"observation\",\n\t\t\t});\n\t\t\tconst hasMore = items.length > limit;\n\t\t\tconst result = hasMore ? items.slice(0, limit) : items;\n\t\t\tconst asRecords = result as unknown as Record<string, unknown>[];\n\t\t\tattachSessionFields(store, asRecords);\n\t\t\tattachResolvedIdentityFields(store, asRecords);\n\t\t\treturn c.json({\n\t\t\t\titems: asRecords,\n\t\t\t\tpagination: {\n\t\t\t\t\tlimit,\n\t\t\t\t\toffset,\n\t\t\t\t\tnext_offset: hasMore ? offset + result.length : null,\n\t\t\t\t\thas_more: hasMore,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t});\n\n\t// GET /api/summaries\n\tapp.get(\"/api/summaries\", (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tconst limit = Math.max(1, queryInt(c.req.query(\"limit\"), 50));\n\t\t\tconst offset = Math.max(0, queryInt(c.req.query(\"offset\"), 0));\n\t\t\tconst project = c.req.query(\"project\") || undefined;\n\t\t\tconst scope = normalizeScope(c.req.query(\"scope\"));\n\t\t\tconst q = normalizeMemorySearchQuery(c.req.query(\"q\"));\n\t\t\tconst items = queryMemoryPage(store, {\n\t\t\t\tlimit,\n\t\t\t\toffset,\n\t\t\t\tproject,\n\t\t\t\tscope,\n\t\t\t\tq,\n\t\t\t\tclassification: \"summary\",\n\t\t\t});\n\t\t\tconst hasMore = items.length > limit;\n\t\t\tconst result = hasMore ? items.slice(0, limit) : items;\n\t\t\tconst asRecords = result as unknown as Record<string, unknown>[];\n\t\t\tattachSessionFields(store, asRecords);\n\t\t\tattachResolvedIdentityFields(store, asRecords);\n\t\t\treturn c.json({\n\t\t\t\titems: asRecords,\n\t\t\t\tpagination: {\n\t\t\t\t\tlimit,\n\t\t\t\t\toffset,\n\t\t\t\t\tnext_offset: hasMore ? offset + result.length : null,\n\t\t\t\t\thas_more: hasMore,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t});\n\n\t// GET /api/session (aggregate counts)\n\tapp.get(\"/api/session\", (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tconst project = c.req.query(\"project\") || null;\n\t\t\tlet prompts: number;\n\t\t\tlet artifacts: number;\n\t\t\tlet memories: number;\n\t\t\tlet observations: number;\n\t\t\tif (project) {\n\t\t\t\tprompts = countVisiblePromptRows(store, project);\n\t\t\t\tartifacts = countVisibleArtifactRows(store, project);\n\t\t\t\tmemories = countVisibleMemoryRows(store, { project });\n\t\t\t\tobservations = countVisibleObservationRows(store, { project });\n\t\t\t} else {\n\t\t\t\tprompts = countVisiblePromptRows(store);\n\t\t\t\tartifacts = countVisibleArtifactRows(store);\n\t\t\t\tmemories = countVisibleMemoryRows(store);\n\t\t\t\tobservations = countVisibleObservationRows(store);\n\t\t\t}\n\t\t\tconst total = prompts + artifacts + memories;\n\t\t\treturn c.json({ total, memories, artifacts, prompts, observations });\n\t\t}\n\t});\n\n\t// GET /api/pack\n\tapp.get(\"/api/pack\", async (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tconst context = c.req.query(\"context\") || \"\";\n\t\t\tif (!context) {\n\t\t\t\treturn c.json({ error: \"context required\" }, 400);\n\t\t\t}\n\t\t\tconst limit = queryInt(c.req.query(\"limit\"), 10);\n\t\t\tconst tokenBudgetStr = c.req.query(\"token_budget\");\n\t\t\tlet tokenBudget: number | undefined;\n\t\t\tif (tokenBudgetStr) {\n\t\t\t\ttokenBudget = parseStrictInteger(tokenBudgetStr) ?? undefined;\n\t\t\t\tif (tokenBudget === undefined) {\n\t\t\t\t\treturn c.json({ error: \"token_budget must be int\" }, 400);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst project = c.req.query(\"project\") || undefined;\n\t\t\tconst filters: { project?: string } = {};\n\t\t\tif (project) filters.project = project;\n\t\t\tconst pack = await store.buildMemoryPackAsync(context, limit, tokenBudget ?? null, filters);\n\t\t\treturn c.json(pack);\n\t\t}\n\t});\n\n\tapp.post(\"/api/pack/trace\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst parsed = await c.req.json().catch(() => Symbol.for(\"invalid-json\"));\n\t\tif (parsed === Symbol.for(\"invalid-json\")) {\n\t\t\treturn c.json({ error: \"invalid json body\" }, 400);\n\t\t}\n\t\tconst body = parsed as {\n\t\t\tcontext?: unknown;\n\t\t\tlimit?: unknown;\n\t\t\ttoken_budget?: unknown;\n\t\t\tproject?: unknown;\n\t\t\tworking_set_files?: unknown;\n\t\t} | null;\n\t\tconst context = typeof body?.context === \"string\" ? body.context.trim() : \"\";\n\t\tif (!context) {\n\t\t\treturn c.json({ error: \"context required\" }, 400);\n\t\t}\n\t\tconst limit =\n\t\t\tbody?.limit == null\n\t\t\t\t? 10\n\t\t\t\t: typeof body.limit === \"number\" && Number.isInteger(body.limit) && body.limit >= 1\n\t\t\t\t\t? body.limit\n\t\t\t\t\t: null;\n\t\tif (limit == null) {\n\t\t\treturn c.json({ error: \"limit must be a positive int\" }, 400);\n\t\t}\n\t\tlet tokenBudget: number | null = null;\n\t\tif (body?.token_budget != null) {\n\t\t\tif (\n\t\t\t\ttypeof body.token_budget !== \"number\" ||\n\t\t\t\t!Number.isInteger(body.token_budget) ||\n\t\t\t\tbody.token_budget < 0\n\t\t\t) {\n\t\t\t\treturn c.json({ error: \"token_budget must be int\" }, 400);\n\t\t\t}\n\t\t\ttokenBudget = body.token_budget;\n\t\t}\n\t\tconst project = typeof body?.project === \"string\" && body.project.trim() ? body.project : null;\n\t\tif (body?.working_set_files != null && !Array.isArray(body.working_set_files)) {\n\t\t\treturn c.json({ error: \"working_set_files must be an array of strings\" }, 400);\n\t\t}\n\t\tif (\n\t\t\tArray.isArray(body?.working_set_files) &&\n\t\t\tbody.working_set_files.some((value) => typeof value !== \"string\")\n\t\t) {\n\t\t\treturn c.json({ error: \"working_set_files must be an array of strings\" }, 400);\n\t\t}\n\t\tconst workingSetFiles = Array.isArray(body?.working_set_files) ? body.working_set_files : [];\n\t\tconst filters: { project?: string; working_set_paths?: string[] } = {};\n\t\tif (project) filters.project = project;\n\t\tif (workingSetFiles.length > 0) filters.working_set_paths = workingSetFiles;\n\t\tconst trace = await store.buildMemoryPackTraceAsync(context, limit, tokenBudget, filters);\n\t\treturn c.json(trace);\n\t});\n\n\t// GET /api/memory\n\tapp.get(\"/api/memory\", (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tconst limit = queryInt(c.req.query(\"limit\"), 20);\n\t\t\tconst kind = c.req.query(\"kind\") || undefined;\n\t\t\tconst project = c.req.query(\"project\") || undefined;\n\t\t\tconst filters: MemoryFilters = {};\n\t\t\tif (kind) filters.kind = kind;\n\t\t\tif (project) filters.project = project;\n\t\t\tconst items = store.recent(limit, filters);\n\t\t\tconst asRecords = items as unknown as Record<string, unknown>[];\n\t\t\tattachSessionFields(store, asRecords);\n\t\t\tattachResolvedIdentityFields(store, asRecords);\n\t\t\treturn c.json({ items: asRecords });\n\t\t}\n\t});\n\n\t// GET /api/artifacts\n\tapp.get(\"/api/artifacts\", (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tconst sessionIdStr = c.req.query(\"session_id\");\n\t\t\tif (!sessionIdStr) {\n\t\t\t\treturn c.json({ error: \"session_id required\" }, 400);\n\t\t\t}\n\t\t\tconst sessionId = parseStrictInteger(sessionIdStr);\n\t\t\tif (sessionId == null) {\n\t\t\t\treturn c.json({ error: \"session_id must be int\" }, 400);\n\t\t\t}\n\t\t\tif (!sessionAllowsArtifactAccess(store, sessionId)) {\n\t\t\t\treturn c.json({ error: \"session not found\" }, 404);\n\t\t\t}\n\t\t\tconst d = drizzle(store.db, { schema });\n\t\t\tconst rows = d\n\t\t\t\t.select()\n\t\t\t\t.from(schema.artifacts)\n\t\t\t\t.where(eq(schema.artifacts.session_id, sessionId))\n\t\t\t\t.all();\n\t\t\treturn c.json({ items: rows });\n\t\t}\n\t});\n\n\t// POST /api/memories/visibility\n\tapp.post(\"/api/memories/visibility\", async (c) => {\n\t\tconst store = getStore();\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid JSON\" }, 400);\n\t\t}\n\t\tconst memoryId = parseStrictInteger(\n\t\t\ttypeof body.memory_id === \"string\" ? body.memory_id : String(body.memory_id ?? \"\"),\n\t\t);\n\t\tif (memoryId == null || memoryId <= 0) {\n\t\t\treturn c.json({ error: \"memory_id must be int\" }, 400);\n\t\t}\n\t\tif (!store.get(memoryId)) {\n\t\t\treturn c.json({ error: \"memory not found\" }, 404);\n\t\t}\n\t\tconst visibility = String(body.visibility ?? \"\").trim();\n\t\tif (visibility !== \"private\" && visibility !== \"shared\") {\n\t\t\treturn c.json({ error: \"visibility must be private or shared\" }, 400);\n\t\t}\n\t\ttry {\n\t\t\tconst item = store.updateMemoryVisibility(memoryId, visibility);\n\t\t\treturn c.json({ item });\n\t\t} catch (err) {\n\t\t\tconst msg = err instanceof Error ? err.message : String(err);\n\t\t\tif (msg.includes(\"not found\")) return c.json({ error: msg }, 404);\n\t\t\tif (msg.includes(\"not owned\")) return c.json({ error: msg }, 403);\n\t\t\treturn c.json({ error: msg }, 400);\n\t\t}\n\t});\n\n\t// POST /api/memories/project\n\tapp.post(\"/api/memories/project\", async (c) => {\n\t\tconst store = getStore();\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid JSON\" }, 400);\n\t\t}\n\t\tconst memoryId = parseStrictInteger(\n\t\t\ttypeof body.memory_id === \"string\" ? body.memory_id : String(body.memory_id ?? \"\"),\n\t\t);\n\t\tif (memoryId == null || memoryId <= 0) {\n\t\t\treturn c.json({ error: \"memory_id must be int\" }, 400);\n\t\t}\n\t\tconst project = String(body.project ?? \"\").trim();\n\t\tif (!project) {\n\t\t\treturn c.json({ error: \"project must be a non-empty string\" }, 400);\n\t\t}\n\t\tif (!store.get(memoryId)) {\n\t\t\treturn c.json({ error: \"memory not found\" }, 404);\n\t\t}\n\t\ttry {\n\t\t\tconst result = store.moveMemoryProject(memoryId, project);\n\t\t\treturn c.json(result);\n\t\t} catch (err) {\n\t\t\tconst msg = err instanceof Error ? err.message : String(err);\n\t\t\tif (msg.includes(\"not found\")) return c.json({ error: msg }, 404);\n\t\t\tif (msg.includes(\"not owned\")) return c.json({ error: msg }, 403);\n\t\t\treturn c.json({ error: msg }, 400);\n\t\t}\n\t});\n\n\t// POST /api/memories/forget\n\tapp.post(\"/api/memories/forget\", async (c) => {\n\t\tconst store = getStore();\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid JSON\" }, 400);\n\t\t}\n\t\tconst memoryId = parseStrictInteger(\n\t\t\ttypeof body.memory_id === \"string\" ? body.memory_id : String(body.memory_id ?? \"\"),\n\t\t);\n\t\tif (memoryId == null || memoryId <= 0) {\n\t\t\treturn c.json({ error: \"memory_id must be int\" }, 400);\n\t\t}\n\t\tif (!store.get(memoryId)) {\n\t\t\treturn c.json({ error: \"memory not found\" }, 404);\n\t\t}\n\n\t\tconst row = drizzle(store.db, { schema })\n\t\t\t.select()\n\t\t\t.from(schema.memoryItems)\n\t\t\t.where(eq(schema.memoryItems.id, memoryId))\n\t\t\t.get();\n\t\tif (!row) {\n\t\t\treturn c.json({ error: \"memory not found\" }, 404);\n\t\t}\n\t\tif (!store.memoryOwnedBySelf(row as Record<string, unknown>)) {\n\t\t\treturn c.json({ error: \"memory not owned by this device\" }, 403);\n\t\t}\n\t\tif (Number(row.active ?? 1) === 0 || row.deleted_at != null) {\n\t\t\treturn c.json({ status: \"ok\" });\n\t\t}\n\n\t\ttry {\n\t\t\tstore.forget(memoryId);\n\t\t\treturn c.json({ status: \"ok\" });\n\t\t} catch (err) {\n\t\t\tconst msg = err instanceof Error ? err.message : String(err);\n\t\t\tif (msg.includes(\"not found\")) return c.json({ error: msg }, 404);\n\t\t\tif (msg.includes(\"not owned\")) return c.json({ error: msg }, 403);\n\t\t\tif (msg.includes(\"sync_rebootstrap_in_progress\")) return c.json({ error: msg }, 409);\n\t\t\treturn c.json({ error: msg }, 400);\n\t\t}\n\t});\n\n\treturn app;\n}\n","/**\n * Observer status route — GET /api/observer-status.\n *\n * Ports Python's viewer_routes/observer_status.py.\n * Returns observer runtime info, credential availability, and queue status.\n */\n\nimport type { ObserverClient } from \"@codemem/core\";\nimport { type MemoryStore, probeAvailableCredentials, type RawEventSweeper } from \"@codemem/core\";\nimport { Hono } from \"hono\";\n\ntype StoreFactory = () => MemoryStore;\n\nexport interface ObserverStatusDeps {\n\tgetStore: StoreFactory;\n\tgetSweeper: () => RawEventSweeper | null;\n\tgetObserver?: () => ObserverClient | null;\n}\n\nfunction normalizeActiveObserver(active: ReturnType<ObserverClient[\"getStatus\"]> | null) {\n\tif (!active) return null;\n\treturn {\n\t\t...active,\n\t\tauth: {\n\t\t\t...active.auth,\n\t\t\tmethod: active.auth.type,\n\t\t\ttoken_present: active.auth.hasToken,\n\t\t},\n\t};\n}\n\nfunction buildFailureImpact(\n\tlatestFailure: Record<string, unknown> | null,\n\tqueueTotals: { pending: number; sessions: number },\n\tauthBackoff: { active: boolean; remainingS: number },\n): string | null {\n\tif (!latestFailure) return null;\n\tif (authBackoff.active) {\n\t\treturn `Queue retries paused for ~${authBackoff.remainingS}s after an observer auth failure.`;\n\t}\n\tif (queueTotals.pending > 0) {\n\t\treturn `${queueTotals.pending} queued raw events across ${queueTotals.sessions} session(s) are waiting on a successful flush.`;\n\t}\n\treturn \"Failed flush batches are pending retry.\";\n}\n\nexport function observerStatusRoutes(deps?: ObserverStatusDeps) {\n\tconst app = new Hono();\n\n\tapp.get(\"/api/observer-status\", (c) => {\n\t\tconst store = deps?.getStore();\n\t\tconst sweeper = deps?.getSweeper();\n\t\tconst observer = deps?.getObserver?.() ?? null;\n\n\t\t// Stub fallback when store doesn't have the required methods (e.g. tests with mock store)\n\t\tif (!store || typeof store.rawEventBacklogTotals !== \"function\") {\n\t\t\treturn c.json({\n\t\t\t\tactive: null,\n\t\t\t\tavailable_credentials: {},\n\t\t\t\tlatest_failure: null,\n\t\t\t\tqueue: {\n\t\t\t\t\tpending: 0,\n\t\t\t\t\tsessions: 0,\n\t\t\t\t\tauth_backoff_active: false,\n\t\t\t\t\tauth_backoff_remaining_s: 0,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\n\t\tconst queueTotals = store.rawEventBacklogTotals();\n\t\tconst authBackoff = sweeper?.authBackoffStatus() ?? { active: false, remainingS: 0 };\n\t\tconst latestFailure = store.latestRawEventFlushFailure();\n\t\tconst active = normalizeActiveObserver(observer?.getStatus() ?? null);\n\t\tconst availableCredentials = probeAvailableCredentials();\n\t\tconst shouldShowFailure =\n\t\t\tlatestFailure != null && (authBackoff.active || queueTotals.pending > 0);\n\n\t\tconst failureWithImpact =\n\t\t\tshouldShowFailure && latestFailure\n\t\t\t\t? { ...latestFailure, impact: buildFailureImpact(latestFailure, queueTotals, authBackoff) }\n\t\t\t\t: null;\n\n\t\treturn c.json({\n\t\t\tactive,\n\t\t\tavailable_credentials: availableCredentials,\n\t\t\tlatest_failure: failureWithImpact,\n\t\t\tqueue: {\n\t\t\t\t...queueTotals,\n\t\t\t\tauth_backoff_active: authBackoff.active,\n\t\t\t\tauth_backoff_remaining_s: authBackoff.remainingS,\n\t\t\t},\n\t\t});\n\t});\n\n\treturn app;\n}\n","import { resolve as resolvePath } from \"node:path\";\nimport type { MemoryStore, ViewerIdentityTarget } from \"@codemem/core\";\nimport {\n\tbuildViewerIdentityTarget,\n\tresolveDbPath,\n\tVIEWER_IDENTITY_TARGET_KEYS,\n} from \"@codemem/core\";\n\nconst IDENTITY_TARGET_KEYS = new Set<string>(VIEWER_IDENTITY_TARGET_KEYS);\nconst BOOLEAN_IDENTITY_TARGET_KEYS = new Set([\n\t\"actor_id_present\",\n\t\"embedding_disabled\",\n\t\"embedding_offline\",\n]);\n\nexport type ViewerTargetValidation =\n\t| { ok: true }\n\t| { ok: false; status: 400 | 409; body: { error: { code: string; message: string } } };\n\nfunction invalidRequest(message: string): ViewerTargetValidation {\n\treturn { ok: false, status: 400, body: { error: { code: \"invalid_request\", message } } };\n}\n\nfunction conflict(code: string, message: string): ViewerTargetValidation {\n\treturn { ok: false, status: 409, body: { error: { code, message } } };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn value != null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nexport function currentIdentityTarget(): ViewerIdentityTarget {\n\treturn buildViewerIdentityTarget();\n}\n\nfunction requestedDbMatches(store: MemoryStore, value: unknown): boolean | null {\n\tif (value == null) return true;\n\tif (typeof value !== \"string\" || !value.trim()) return null;\n\treturn resolvePath(resolveDbPath(value.trim())) === resolvePath(store.dbPath);\n}\n\nfunction requestedIdentityMatches(value: unknown): boolean | null | \"unsupported\" {\n\tif (value == null) return true;\n\tif (!isRecord(value)) return null;\n\tif (\n\t\tObject.keys(value).length !== IDENTITY_TARGET_KEYS.size ||\n\t\tObject.keys(value).some((key) => !IDENTITY_TARGET_KEYS.has(key))\n\t)\n\t\treturn \"unsupported\";\n\tconst expected = currentIdentityTarget();\n\tfor (const key of VIEWER_IDENTITY_TARGET_KEYS) {\n\t\tconst requested = value[key];\n\t\tif (BOOLEAN_IDENTITY_TARGET_KEYS.has(key)) {\n\t\t\tif (typeof requested !== \"boolean\") return null;\n\t\t} else if (requested !== null && typeof requested !== \"string\") {\n\t\t\treturn null;\n\t\t}\n\t\tif (requested !== expected[key]) return false;\n\t}\n\treturn true;\n}\n\nexport function validateViewerTarget(\n\tstore: MemoryStore,\n\tpayload: Record<string, unknown>,\n\toptions: { requireCurrentIdentity?: boolean; requirePairedTargets?: boolean } = {},\n): ViewerTargetValidation {\n\tif (options.requirePairedTargets) {\n\t\tconst hasDbPath = Object.hasOwn(payload, \"db_path\");\n\t\tconst hasIdentityTarget = Object.hasOwn(payload, \"identity_target\");\n\t\tif (hasDbPath !== hasIdentityTarget) {\n\t\t\treturn invalidRequest(\"db_path and identity_target must be provided together\");\n\t\t}\n\t\tif (hasDbPath && (payload.db_path == null || payload.identity_target == null)) {\n\t\t\treturn invalidRequest(\"db_path and identity_target must be valid when provided\");\n\t\t}\n\t}\n\tconst dbMatches = requestedDbMatches(store, payload.db_path);\n\tif (dbMatches == null) return invalidRequest(\"db_path must be a non-empty string\");\n\tif (!dbMatches) {\n\t\treturn conflict(\"viewer_db_mismatch\", \"viewer database does not match request\");\n\t}\n\n\tconst identityMatches = requestedIdentityMatches(payload.identity_target);\n\tif (identityMatches === \"unsupported\") {\n\t\treturn conflict(\"viewer_contract_unsupported\", \"viewer request contract is incompatible\");\n\t}\n\tif (identityMatches == null) return invalidRequest(\"identity_target is invalid\");\n\tif (!identityMatches) {\n\t\treturn conflict(\"viewer_identity_mismatch\", \"viewer identity does not match request\");\n\t}\n\tif (\n\t\t(options.requireCurrentIdentity || payload.identity_target != null) &&\n\t\t!store.hasCurrentIdentity()\n\t) {\n\t\treturn conflict(\"viewer_identity_mismatch\", \"viewer identity does not match request\");\n\t}\n\treturn { ok: true };\n}\n","import { isAbsolute, posix, resolve as resolvePath, win32 } from \"node:path\";\nimport type {\n\tMemoryFilters,\n\tMemoryStore,\n\tPackRenderOptions,\n\tPromptPackAttemptMetadata,\n\tRetrievalLedgerDeliveryOutcome,\n\tRetrievalLedgerFailureReason,\n\tRetrievalLedgerWriteOutcome,\n} from \"@codemem/core\";\nimport {\n\tclonePromptPackAttempt,\n\tPROMPT_TRANSPORT_PROTOCOL_RANGE,\n\tpromptPackArtifactFingerprint,\n\trecordPromptPackArtifacts,\n\trecordPromptPackTerminal,\n\tresolveProject,\n\ttryUpdateRetrievalDelivery,\n} from \"@codemem/core\";\nimport { Hono } from \"hono\";\nimport { currentIdentityTarget, validateViewerTarget } from \"./target-validation.js\";\n\ntype StoreFactory = () => MemoryStore;\ntype LedgerOutcome = RetrievalLedgerWriteOutcome | RetrievalLedgerDeliveryOutcome;\n\nconst MAX_LEDGER_PAYLOAD_BYTES = 16 * 1024;\nconst MAX_METADATA_FIELD_CHARS = 512;\nconst MAX_WORKING_SET_FILES = 50;\nconst MAX_WORKING_SET_PATH_CHARS = 512;\nconst INVALID_JSON = Symbol(\"invalid-json\");\n\nconst PACK_KEYS = new Set([\n\t\"context\",\n\t\"limit\",\n\t\"token_budget\",\n\t\"project\",\n\t\"cwd\",\n\t\"all_projects\",\n\t\"working_set_files\",\n\t\"compact\",\n\t\"compact_detail_count\",\n\t\"db_path\",\n\t\"identity_target\",\n\t\"attempt\",\n]);\nconst LEDGER_KEYS = new Set([\n\t\"action\",\n\t\"attempt_id\",\n\t\"started_at\",\n\t\"source\",\n\t\"stream_id\",\n\t\"source_session_id\",\n\t\"prompt_number\",\n\t\"request_id\",\n\t\"retrieval_status\",\n\t\"delivery_status\",\n\t\"failure_code\",\n\t\"failure_stage\",\n\t\"original_attempt_id\",\n\t\"db_path\",\n\t\"identity_target\",\n]);\nconst ATTEMPT_KEYS = new Set([\n\t\"attempt_id\",\n\t\"started_at\",\n\t\"source\",\n\t\"stream_id\",\n\t\"source_session_id\",\n\t\"prompt_number\",\n\t\"request_id\",\n]);\nconst FORBIDDEN_LEDGER_KEYS = new Set([\n\t\"body\",\n\t\"context\",\n\t\"pack\",\n\t\"pack_text\",\n\t\"path\",\n\t\"preview\",\n\t\"prompt\",\n\t\"query\",\n\t\"raw_prompt\",\n\t\"title\",\n]);\n\ntype ValidatedPackRequest = {\n\tcontext: string;\n\tlimit: number;\n\ttokenBudget: number | null;\n\tfilters: MemoryFilters;\n\trenderOptions?: PackRenderOptions;\n\tattempt?: Record<string, unknown>;\n};\n\nfunction invalidRequest(message: string) {\n\treturn { error: { code: \"invalid_request\", message } };\n}\n\nfunction viewerIdentityMismatch() {\n\treturn {\n\t\terror: {\n\t\t\tcode: \"viewer_identity_mismatch\",\n\t\t\tmessage: \"viewer identity does not match request\",\n\t\t},\n\t};\n}\n\nfunction viewerContractUnsupported() {\n\treturn {\n\t\terror: {\n\t\t\tcode: \"viewer_contract_unsupported\",\n\t\t\tmessage: \"viewer request contract is incompatible\",\n\t\t},\n\t};\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn value != null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction isAbsolutePath(value: string): boolean {\n\treturn posix.isAbsolute(value) || win32.isAbsolute(value);\n}\n\nfunction normalizeWorkingSetPath(value: string): string | null {\n\tconst trimmed = value.trim();\n\tif (!trimmed || trimmed.length > MAX_WORKING_SET_PATH_CHARS || isAbsolutePath(trimmed)) {\n\t\treturn null;\n\t}\n\tconst normalized = posix.normalize(trimmed.replaceAll(\"\\\\\", \"/\")).replace(/^\\.\\//, \"\");\n\tif (!normalized || normalized === \".\" || normalized === \"..\" || normalized.startsWith(\"../\")) {\n\t\treturn null;\n\t}\n\treturn normalized;\n}\n\nfunction validateMetadataFields(\n\tpayload: Record<string, unknown>,\n\tallowedKeys: ReadonlySet<string>,\n): string | null {\n\tif (Buffer.byteLength(JSON.stringify(payload), \"utf8\") > MAX_LEDGER_PAYLOAD_BYTES) {\n\t\treturn \"ledger metadata exceeds 16384 bytes\";\n\t}\n\tfor (const key of Object.keys(payload)) {\n\t\tif (FORBIDDEN_LEDGER_KEYS.has(key)) return `ledger metadata rejects sensitive field: ${key}`;\n\t\tif (!allowedKeys.has(key)) return `ledger metadata contains unsupported field: ${key}`;\n\t}\n\tif (typeof payload.attempt_id !== \"string\" || payload.attempt_id.length === 0) {\n\t\treturn \"ledger metadata requires attempt_id\";\n\t}\n\tif (\n\t\tpayload.prompt_number != null &&\n\t\t(typeof payload.prompt_number !== \"number\" ||\n\t\t\t!Number.isInteger(payload.prompt_number) ||\n\t\t\tpayload.prompt_number < 0)\n\t) {\n\t\treturn \"ledger metadata prompt_number must be a non-negative integer\";\n\t}\n\tfor (const key of [\n\t\t\"attempt_id\",\n\t\t\"started_at\",\n\t\t\"source\",\n\t\t\"stream_id\",\n\t\t\"source_session_id\",\n\t\t\"request_id\",\n\t\t\"failure_code\",\n\t\t\"failure_stage\",\n\t\t\"original_attempt_id\",\n\t] as const) {\n\t\tconst field = payload[key];\n\t\tif (field != null && (typeof field !== \"string\" || field.length > MAX_METADATA_FIELD_CHARS)) {\n\t\t\treturn `ledger metadata field ${key} is invalid`;\n\t\t}\n\t\tif (typeof field === \"string\" && isAbsolutePath(field)) {\n\t\t\treturn `ledger metadata rejects absolute paths in field: ${key}`;\n\t\t}\n\t}\n\treturn null;\n}\n\nfunction attemptMetadata(payload: Record<string, unknown>): PromptPackAttemptMetadata {\n\treturn {\n\t\tattemptId: payload.attempt_id as string,\n\t\tstartedAt: (payload.started_at as string | undefined) ?? new Date().toISOString(),\n\t\tcompletedAt: new Date().toISOString(),\n\t\tsource: (payload.source as string | undefined) ?? \"opencode\",\n\t\tstreamId: (payload.stream_id as string | undefined) ?? null,\n\t\tsourceSessionId: (payload.source_session_id as string | undefined) ?? null,\n\t\tpromptNumber: (payload.prompt_number as number | undefined) ?? null,\n\t\trequestId: (payload.request_id as string | undefined) ?? null,\n\t};\n}\n\nfunction validatePackRequest(value: unknown): ValidatedPackRequest | string {\n\tif (!isRecord(value)) return \"request body must be an object\";\n\tfor (const key of Object.keys(value)) {\n\t\tif (!PACK_KEYS.has(key)) return `request body contains unsupported field: ${key}`;\n\t}\n\tconst context = typeof value.context === \"string\" ? value.context.trim() : \"\";\n\tif (!context) return \"context required\";\n\tconst limit = value.limit ?? 10;\n\tif (typeof limit !== \"number\" || !Number.isInteger(limit) || limit < 1) {\n\t\treturn \"limit must be a positive int\";\n\t}\n\tconst tokenBudget = value.token_budget ?? null;\n\tif (\n\t\ttokenBudget !== null &&\n\t\t(typeof tokenBudget !== \"number\" || !Number.isInteger(tokenBudget) || tokenBudget < 0)\n\t) {\n\t\treturn \"token_budget must be a non-negative int\";\n\t}\n\tif (value.all_projects != null && typeof value.all_projects !== \"boolean\") {\n\t\treturn \"all_projects must be a boolean\";\n\t}\n\tif (value.project != null && (typeof value.project !== \"string\" || !value.project.trim())) {\n\t\treturn \"project must be a non-empty string\";\n\t}\n\tif (\n\t\tvalue.cwd != null &&\n\t\t(typeof value.cwd !== \"string\" || !value.cwd.trim() || !isAbsolute(value.cwd))\n\t) {\n\t\treturn \"cwd must be an absolute path\";\n\t}\n\tif (value.working_set_files != null && !Array.isArray(value.working_set_files)) {\n\t\treturn \"working_set_files must be an array of repository-relative strings\";\n\t}\n\tconst workingSetValues = (value.working_set_files ?? []) as unknown[];\n\tif (workingSetValues.length > MAX_WORKING_SET_FILES) {\n\t\treturn `working_set_files must contain at most ${MAX_WORKING_SET_FILES} entries`;\n\t}\n\tconst workingSetFiles: string[] = [];\n\tfor (const entry of workingSetValues) {\n\t\tif (typeof entry !== \"string\") {\n\t\t\treturn \"working_set_files must be an array of repository-relative strings\";\n\t\t}\n\t\tconst normalized = normalizeWorkingSetPath(entry);\n\t\tif (!normalized) return \"working_set_files contains an invalid repository-relative path\";\n\t\tif (!workingSetFiles.includes(normalized)) workingSetFiles.push(normalized);\n\t}\n\tif (value.compact != null && typeof value.compact !== \"boolean\") {\n\t\treturn \"compact must be a boolean\";\n\t}\n\tif (\n\t\tvalue.compact_detail_count != null &&\n\t\t(typeof value.compact_detail_count !== \"number\" ||\n\t\t\t!Number.isInteger(value.compact_detail_count) ||\n\t\t\tvalue.compact_detail_count < 0)\n\t) {\n\t\treturn \"compact_detail_count must be a non-negative int\";\n\t}\n\tlet attempt: Record<string, unknown> | undefined;\n\tif (value.attempt != null) {\n\t\tif (!isRecord(value.attempt)) return \"attempt must be an object\";\n\t\tconst attemptError = validateMetadataFields(value.attempt, ATTEMPT_KEYS);\n\t\tif (attemptError) return attemptError;\n\t\tattempt = value.attempt;\n\t}\n\n\tconst filters: MemoryFilters = {};\n\tif (value.all_projects !== true) {\n\t\tconst envProject = process.env.CODEMEM_PROJECT?.trim() || null;\n\t\tconst requestCwd = value.cwd as string | undefined;\n\t\tconst requestProject = value.project as string | undefined;\n\t\tconst project = resolveProject(\n\t\t\trequestCwd ?? process.cwd(),\n\t\t\trequestProject ?? (requestCwd == null ? envProject : undefined),\n\t\t);\n\t\tif (project) filters.project = project;\n\t}\n\tif (workingSetFiles.length > 0) filters.working_set_paths = workingSetFiles;\n\n\tlet renderOptions: PackRenderOptions | undefined;\n\tif (value.compact != null || value.compact_detail_count != null) {\n\t\trenderOptions = {\n\t\t\tcompact: value.compact === true || value.compact_detail_count != null,\n\t\t\t...(value.compact_detail_count != null\n\t\t\t\t? { compactDetailCount: value.compact_detail_count as number }\n\t\t\t\t: {}),\n\t\t};\n\t}\n\treturn {\n\t\tcontext,\n\t\tlimit,\n\t\ttokenBudget: tokenBudget as number | null,\n\t\tfilters,\n\t\trenderOptions,\n\t\tattempt,\n\t};\n}\n\nfunction ledgerFailureStatus(reason: RetrievalLedgerFailureReason): 400 | 409 | 422 | 503 {\n\tif (reason === \"idempotency_conflict\") return 409;\n\tif (reason === \"attempt_not_found\") return 422;\n\tif (reason === \"storage_unavailable\") return 503;\n\treturn 400;\n}\n\nfunction dispatchLedger(\n\tstore: MemoryStore,\n\tpayload: Record<string, unknown>,\n): LedgerOutcome | string {\n\tconst action = payload.action;\n\tif (action !== \"record\" && action !== \"delivery\" && action !== \"cache_reuse\") {\n\t\treturn \"ledger action is invalid\";\n\t}\n\tconst metadata = attemptMetadata(payload);\n\tif (action === \"delivery\") {\n\t\tconst status = payload.delivery_status;\n\t\tif (status !== \"handed_off\" && status !== \"failed\" && status !== \"unknown\") {\n\t\t\treturn \"delivery action requires a valid delivery_status\";\n\t\t}\n\t\treturn tryUpdateRetrievalDelivery(store.db, metadata.attemptId, status);\n\t}\n\tif (action === \"cache_reuse\") {\n\t\tif (typeof payload.original_attempt_id !== \"string\" || !payload.original_attempt_id) {\n\t\t\treturn \"cache_reuse action requires original_attempt_id\";\n\t\t}\n\t\treturn clonePromptPackAttempt(store.db, payload.original_attempt_id, metadata);\n\t}\n\tif (\n\t\t(payload.retrieval_status !== \"skipped\" && payload.retrieval_status !== \"failed\") ||\n\t\ttypeof payload.failure_code !== \"string\" ||\n\t\t!payload.failure_code ||\n\t\ttypeof payload.failure_stage !== \"string\" ||\n\t\t!payload.failure_stage\n\t) {\n\t\treturn \"record action requires retrieval_status, failure_code, and failure_stage\";\n\t}\n\treturn recordPromptPackTerminal(\n\t\tstore.db,\n\t\tmetadata,\n\t\tpayload.retrieval_status,\n\t\tpayload.failure_code,\n\t\tpayload.failure_stage,\n\t);\n}\n\nexport function packTransportRoutes(getStore: StoreFactory) {\n\tconst app = new Hono();\n\n\tapp.get(\"/api/prompt-pack-profile\", (c) => {\n\t\ttry {\n\t\t\tconst store = getStore();\n\t\t\tif (!store.hasCurrentIdentity()) return c.json(viewerIdentityMismatch(), 409);\n\t\t\treturn c.json({\n\t\t\t\tservice: \"codemem-viewer\",\n\t\t\t\tprotocol_version: PROMPT_TRANSPORT_PROTOCOL_RANGE.protocolVersion,\n\t\t\t\tmin_supported_protocol_version: PROMPT_TRANSPORT_PROTOCOL_RANGE.minSupportedProtocolVersion,\n\t\t\t\tdb_path: resolvePath(store.dbPath),\n\t\t\t\tidentity_target: currentIdentityTarget(),\n\t\t\t});\n\t\t} catch {\n\t\t\treturn c.json(\n\t\t\t\t{ error: { code: \"profile_failed\", message: \"viewer profile could not be read\" } },\n\t\t\t\t500,\n\t\t\t);\n\t\t}\n\t});\n\n\tapp.post(\"/api/pack\", async (c) => {\n\t\tconst parsed = await c.req.json().catch(() => INVALID_JSON);\n\t\tif (parsed === INVALID_JSON) return c.json(invalidRequest(\"invalid json body\"), 400);\n\t\tconst request = validatePackRequest(parsed);\n\t\tif (typeof request === \"string\") {\n\t\t\tif (request.startsWith(\"request body contains unsupported field:\"))\n\t\t\t\treturn c.json(viewerContractUnsupported(), 409);\n\t\t\treturn c.json(invalidRequest(request), 400);\n\t\t}\n\t\ttry {\n\t\t\tconst store = getStore();\n\t\t\tconst target = validateViewerTarget(store, parsed, { requireCurrentIdentity: true });\n\t\t\tif (!target.ok) return c.json(target.body, target.status);\n\t\t\tif (!request.attempt) {\n\t\t\t\tconst pack = await store.buildMemoryPackAsync(\n\t\t\t\t\trequest.context,\n\t\t\t\t\trequest.limit,\n\t\t\t\t\trequest.tokenBudget,\n\t\t\t\t\trequest.filters,\n\t\t\t\t\trequest.renderOptions,\n\t\t\t\t);\n\t\t\t\treturn c.json(pack);\n\t\t\t}\n\t\t\tconst artifacts = await store.buildMemoryPackWithTraceAsync(\n\t\t\t\trequest.context,\n\t\t\t\trequest.limit,\n\t\t\t\trequest.tokenBudget,\n\t\t\t\trequest.filters,\n\t\t\t\trequest.renderOptions,\n\t\t\t);\n\t\t\tlet ledgerArtifactFingerprint: string | undefined;\n\t\t\ttry {\n\t\t\t\tledgerArtifactFingerprint = promptPackArtifactFingerprint(\n\t\t\t\t\tstore.db,\n\t\t\t\t\trequest.context,\n\t\t\t\t\trequest.filters,\n\t\t\t\t\tartifacts,\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\t// Fingerprinting is instrumentation and must not block pack delivery.\n\t\t\t}\n\t\t\tlet ledgerOutcome: RetrievalLedgerWriteOutcome | undefined;\n\t\t\ttry {\n\t\t\t\tledgerOutcome = recordPromptPackArtifacts(\n\t\t\t\t\tstore.db,\n\t\t\t\t\tattemptMetadata(request.attempt),\n\t\t\t\t\trequest.context,\n\t\t\t\t\trequest.filters,\n\t\t\t\t\tartifacts,\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\t// Ledger instrumentation is best-effort and must not block pack delivery.\n\t\t\t}\n\t\t\treturn c.json({\n\t\t\t\t...artifacts.response,\n\t\t\t\t...(ledgerArtifactFingerprint\n\t\t\t\t\t? { ledger_artifact_fingerprint: ledgerArtifactFingerprint }\n\t\t\t\t\t: {}),\n\t\t\t\t...(ledgerOutcome?.ok === false && ledgerOutcome.reason === \"idempotency_conflict\"\n\t\t\t\t\t? { ledger_outcome: ledgerOutcome }\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t} catch {\n\t\t\treturn c.json(\n\t\t\t\t{ error: { code: \"pack_failed\", message: \"memory pack could not be built\" } },\n\t\t\t\t500,\n\t\t\t);\n\t\t}\n\t});\n\n\tapp.post(\"/api/prompt-pack-ledger\", async (c) => {\n\t\tconst parsed = await c.req.json().catch(() => INVALID_JSON);\n\t\tif (parsed === INVALID_JSON) return c.json(invalidRequest(\"invalid json body\"), 400);\n\t\tif (!isRecord(parsed)) return c.json(invalidRequest(\"request body must be an object\"), 400);\n\t\tconst validationError = validateMetadataFields(parsed, LEDGER_KEYS);\n\t\tif (validationError) {\n\t\t\tif (validationError.startsWith(\"ledger metadata contains unsupported field:\"))\n\t\t\t\treturn c.json(viewerContractUnsupported(), 409);\n\t\t\treturn c.json(invalidRequest(validationError), 400);\n\t\t}\n\t\ttry {\n\t\t\tconst store = getStore();\n\t\t\tconst target = validateViewerTarget(store, parsed, { requireCurrentIdentity: true });\n\t\t\tif (!target.ok) return c.json(target.body, target.status);\n\t\t\tconst outcome = dispatchLedger(store, parsed);\n\t\t\tif (typeof outcome === \"string\") return c.json(invalidRequest(outcome), 400);\n\t\t\tif (outcome.ok) return c.json(outcome);\n\t\t\treturn c.json(outcome, ledgerFailureStatus(outcome.reason));\n\t\t} catch {\n\t\t\treturn c.json(\n\t\t\t\t{ error: { code: \"ledger_failed\", message: \"prompt-pack ledger operation failed\" } },\n\t\t\t\t500,\n\t\t\t);\n\t\t}\n\t});\n\n\treturn app;\n}\n","/**\n * Raw events routes — GET & POST /api/raw-events, GET /api/raw-events/status,\n * POST /api/claude-hooks, POST /api/codex-hooks.\n */\n\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { HookTranscriptOutcome, MemoryStore, RawEventSweeper } from \"@codemem/core\";\nimport {\n\tbuildRawEventEnvelopeFromCodexHook,\n\tbuildRawEventEnvelopeFromHook,\n\tingestRawEvents,\n\tRawEventIngestValidationError,\n\tschema,\n} from \"@codemem/core\";\nimport { desc } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport { Hono } from \"hono\";\nimport { parseJsonObjectBody, queryInt } from \"../helpers.js\";\nimport { validateViewerTarget } from \"./target-validation.js\";\n\ntype StoreFactory = () => MemoryStore;\ntype JsonResponder = {\n\tjson: (data: unknown, status?: number) => Response;\n};\n\nconst DEFAULT_MAX_RAW_EVENTS_BODY_BYTES = 1_048_576;\n\nfunction configuredMaxRawEventsBodyBytes(): number {\n\tconst parsed = Number(process.env.CODEMEM_RAW_EVENTS_MAX_BODY_BYTES?.trim() ?? \"\");\n\treturn Number.isSafeInteger(parsed) && parsed > 0 ? parsed : DEFAULT_MAX_RAW_EVENTS_BODY_BYTES;\n}\n\nconst MAX_RAW_EVENTS_BODY_BYTES = configuredMaxRawEventsBodyBytes();\ntype LegacyTranscriptSource = \"claude\" | \"codex\";\ntype TranscriptOutcomeCounts = Record<HookTranscriptOutcome, number>;\n\nfunction emptyTranscriptOutcomeCounts(): TranscriptOutcomeCounts {\n\treturn {\n\t\tok: 0,\n\t\tnot_provided: 0,\n\t\tpath_rejected: 0,\n\t\tunreadable: 0,\n\t\tno_complete_record: 0,\n\t\tno_assistant_record: 0,\n\t} satisfies TranscriptOutcomeCounts;\n}\n\nfunction createTranscriptDiagnostics() {\n\tconst counts: Record<LegacyTranscriptSource, TranscriptOutcomeCounts> = {\n\t\tclaude: emptyTranscriptOutcomeCounts(),\n\t\tcodex: emptyTranscriptOutcomeCounts(),\n\t};\n\treturn {\n\t\trecord(source: LegacyTranscriptSource, outcome: HookTranscriptOutcome): void {\n\t\t\tcounts[source][outcome] += 1;\n\t\t},\n\t\tsnapshot() {\n\t\t\treturn {\n\t\t\t\tscope: \"legacy_compatibility_routes\" as const,\n\t\t\t\tcounts: {\n\t\t\t\t\tclaude: { ...counts.claude },\n\t\t\t\t\tcodex: { ...counts.codex },\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t};\n}\n\nfunction transcriptSkipResponse(outcome: HookTranscriptOutcome | null) {\n\tif (outcome !== null && outcome !== \"ok\") {\n\t\treturn {\n\t\t\tinserted: 0,\n\t\t\tskipped: 1,\n\t\t\tskip_reason: \"transcript_unavailable\" as const,\n\t\t\tskip_detail: outcome,\n\t\t};\n\t}\n\treturn { inserted: 0, skipped: 1, skip_reason: \"unsupported_hook\" as const };\n}\n\nfunction claudeTranscriptRoot(): string {\n\treturn join(process.env.CLAUDE_CONFIG_DIR?.trim() || join(homedir(), \".claude\"), \"projects\");\n}\n\nfunction codexTranscriptRoot(): string {\n\treturn join(process.env.CODEX_HOME?.trim() || join(homedir(), \".codex\"), \"sessions\");\n}\n\n/** Nudge the sweeper safely — never crashes the caller. */\nfunction nudgeSweeper(\n\tsweeper: RawEventSweeper | null | undefined,\n\tsessions: Iterable<{ source: string; streamId: string }>,\n): void {\n\tfor (const session of sessions) {\n\t\ttry {\n\t\t\tsweeper?.nudge(session.streamId, session.source);\n\t\t} catch {\n\t\t\t// A failed nudge must not block later validated sessions.\n\t\t}\n\t}\n}\n\nasync function flushBoundarySessions(\n\tsweeper: RawEventSweeper | null | undefined,\n\tsessions: Iterable<{ source: string; streamId: string }>,\n): Promise<void> {\n\tfor (const session of sessions) {\n\t\ttry {\n\t\t\tawait sweeper?.flushBoundary(session.streamId, session.source);\n\t\t} catch {\n\t\t\t// Boundary extraction remains best-effort, matching the legacy CLI path.\n\t\t}\n\t}\n}\n\nfunction isClaudeBoundaryEnvelope(envelope: object): boolean {\n\tconst record = envelope as Record<string, unknown>;\n\tif (\n\t\tString(record.source ?? \"\")\n\t\t\t.trim()\n\t\t\t.toLowerCase() !== \"claude\"\n\t)\n\t\treturn false;\n\tconst payload = record.payload;\n\tif (payload == null || typeof payload !== \"object\" || Array.isArray(payload)) return false;\n\tconst adapter = (payload as Record<string, unknown>)._adapter;\n\tif (adapter == null || typeof adapter !== \"object\" || Array.isArray(adapter)) return false;\n\tconst meta = (adapter as Record<string, unknown>).meta;\n\tif (meta == null || typeof meta !== \"object\" || Array.isArray(meta)) return false;\n\tconst hookEventName = (meta as Record<string, unknown>).hook_event_name;\n\treturn hookEventName === \"SessionEnd\" || hookEventName === \"Stop\";\n}\n\nconst SAFE_INGEST_VALIDATION_ERRORS = new Set([\n\t\"source must be string\",\n\t\"source is required\",\n\t\"source must use 1-64 letters, digits, dots, underscores, or hyphens\",\n\t\"session_stream_id must be string\",\n\t\"session_id must be string\",\n\t\"stream_id must be string\",\n\t\"opencode_session_id must be string\",\n\t\"conflicting session id fields\",\n\t\"invalid session id\",\n\t\"event source conflicts with request source\",\n\t\"session id required\",\n\t\"event_type must be string\",\n\t\"event_type required\",\n\t\"event_type has invalid syntax\",\n\t\"event_id must be string\",\n\t\"event_id required\",\n\t\"event_id has invalid syntax\",\n\t\"event_seq must be int\",\n\t\"ts_wall_ms must be number\",\n\t\"ts_mono_ms must be number\",\n\t\"payload must be an object\",\n\t\"cwd must be string\",\n\t\"project must be string\",\n\t\"started_at must be string\",\n\t\"events must be a list\",\n\t\"event must be an object\",\n]);\n\nfunction boundedIngestValidationMessage(error: RawEventIngestValidationError): string {\n\treturn SAFE_INGEST_VALIDATION_ERRORS.has(error.message)\n\t\t? error.message\n\t\t: \"invalid raw event request\";\n}\n\nfunction boundedIngestErrorResponse(c: JsonResponder, error: unknown): Response {\n\tif (error instanceof RawEventIngestValidationError) {\n\t\treturn c.json({ error: boundedIngestValidationMessage(error) }, 400);\n\t}\n\tconst response: Record<string, unknown> = { error: \"internal server error\" };\n\tif (process.env.CODEMEM_VIEWER_DEBUG === \"1\") {\n\t\tresponse.detail = error instanceof Error ? error.message : String(error);\n\t}\n\treturn c.json(response, 500);\n}\n\nfunction untargetedPayload(payload: Record<string, unknown>): Record<string, unknown> {\n\tconst { db_path: _dbPath, identity_target: _identityTarget, ...body } = payload;\n\treturn body;\n}\n\nasync function ingestNormalizedEnvelope(\n\tstore: MemoryStore,\n\tsweeper: RawEventSweeper | null | undefined,\n\tenvelope: object,\n\tflushBoundary = false,\n) {\n\tconst result = ingestRawEvents(store, envelope);\n\tnudgeSweeper(sweeper, result.sessions);\n\tif (flushBoundary && isClaudeBoundaryEnvelope(envelope)) {\n\t\tawait flushBoundarySessions(sweeper, result.sessions);\n\t}\n\treturn result;\n}\n\nexport function rawEventsRoutes(getStore: StoreFactory, sweeper?: RawEventSweeper | null) {\n\tconst app = new Hono();\n\tconst transcriptDiagnostics = createTranscriptDiagnostics();\n\n\t// GET /api/raw-events (compat endpoint for stats panel)\n\tapp.get(\"/api/raw-events\", (c) => {\n\t\tconst store = getStore();\n\t\tconst totals = store.rawEventBacklogTotals();\n\t\treturn c.json(totals);\n\t});\n\n\t// GET /api/raw-events/status\n\tapp.get(\"/api/raw-events/status\", (c) => {\n\t\tconst store = getStore();\n\t\tconst limit = queryInt(c.req.query(\"limit\"), 25);\n\t\tconst d = drizzle(store.db, { schema });\n\t\tconst rows = d\n\t\t\t.select({\n\t\t\t\tsource: schema.rawEventSessions.source,\n\t\t\t\tstream_id: schema.rawEventSessions.stream_id,\n\t\t\t\topencode_session_id: schema.rawEventSessions.opencode_session_id,\n\t\t\t\tcwd: schema.rawEventSessions.cwd,\n\t\t\t\tproject: schema.rawEventSessions.project,\n\t\t\t\tstarted_at: schema.rawEventSessions.started_at,\n\t\t\t\tlast_seen_ts_wall_ms: schema.rawEventSessions.last_seen_ts_wall_ms,\n\t\t\t\tlast_received_event_seq: schema.rawEventSessions.last_received_event_seq,\n\t\t\t\tlast_flushed_event_seq: schema.rawEventSessions.last_flushed_event_seq,\n\t\t\t\tupdated_at: schema.rawEventSessions.updated_at,\n\t\t\t})\n\t\t\t.from(schema.rawEventSessions)\n\t\t\t.orderBy(desc(schema.rawEventSessions.updated_at))\n\t\t\t.limit(limit)\n\t\t\t.all();\n\t\tconst items = rows.map((row) => {\n\t\t\tconst streamId = String(row.stream_id ?? row.opencode_session_id ?? \"\");\n\t\t\treturn {\n\t\t\t\t...row,\n\t\t\t\tsession_stream_id: streamId,\n\t\t\t\tsession_id: streamId,\n\t\t\t};\n\t\t});\n\t\tconst totals = store.rawEventBacklogTotals();\n\t\treturn c.json({\n\t\t\titems,\n\t\t\ttotals,\n\t\t\tingest: {\n\t\t\t\tavailable: true,\n\t\t\t\tmode: \"stream_queue\",\n\t\t\t\tmax_body_bytes: MAX_RAW_EVENTS_BODY_BYTES,\n\t\t\t},\n\t\t\ttranscript_diagnostics: transcriptDiagnostics.snapshot(),\n\t\t});\n\t});\n\n\t// POST /api/raw-events — ingest raw events from plugin\n\tapp.post(\"/api/raw-events\", async (c) => {\n\t\tconst result = await parseJsonObjectBody(c, MAX_RAW_EVENTS_BODY_BYTES);\n\t\tif (result instanceof Response) return result;\n\t\ttry {\n\t\t\tconst store = getStore();\n\t\t\tconst target = validateViewerTarget(store, result, { requirePairedTargets: true });\n\t\t\tif (!target.ok) return c.json(target.body, target.status);\n\t\t\tconst ingestResult = await ingestNormalizedEnvelope(\n\t\t\t\tstore,\n\t\t\t\tsweeper,\n\t\t\t\tuntargetedPayload(result),\n\t\t\t\tc.req.header(\"x-codemem-boundary-flush\") === \"1\",\n\t\t\t);\n\t\t\treturn c.json({\n\t\t\t\tinserted: ingestResult.inserted,\n\t\t\t\tskipped: ingestResult.skipped,\n\t\t\t\treceived: ingestResult.received,\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn boundedIngestErrorResponse(c, err);\n\t\t}\n\t});\n\n\t// POST /api/claude-hooks — ingest Claude Code hook events\n\tapp.post(\"/api/claude-hooks\", async (c) => {\n\t\tconst result = await parseJsonObjectBody(c, MAX_RAW_EVENTS_BODY_BYTES);\n\t\tif (result instanceof Response) return result;\n\t\tconst payload = result;\n\n\t\ttry {\n\t\t\tconst store = getStore();\n\t\t\tconst target = validateViewerTarget(store, payload, { requirePairedTargets: true });\n\t\t\tif (!target.ok) return c.json(target.body, target.status);\n\t\t\tlet transcriptOutcome: HookTranscriptOutcome | null = null;\n\t\t\tconst envelope = buildRawEventEnvelopeFromHook(untargetedPayload(payload), {\n\t\t\t\ttranscriptPolicy: { trust: \"restricted\", approvedRoots: [claudeTranscriptRoot()] },\n\t\t\t\tonTranscriptOutcome: (outcome) => {\n\t\t\t\t\ttranscriptOutcome = outcome;\n\t\t\t\t\ttranscriptDiagnostics.record(\"claude\", outcome);\n\t\t\t\t},\n\t\t\t});\n\t\t\tif (envelope === null) {\n\t\t\t\treturn c.json(transcriptSkipResponse(transcriptOutcome));\n\t\t\t}\n\t\t\tconst ingestResult = await ingestNormalizedEnvelope(\n\t\t\t\tstore,\n\t\t\t\tsweeper,\n\t\t\t\tenvelope,\n\t\t\t\tc.req.header(\"x-codemem-boundary-flush\") === \"1\",\n\t\t\t);\n\t\t\treturn c.json({ inserted: ingestResult.inserted, skipped: ingestResult.skipped });\n\t\t} catch (err) {\n\t\t\treturn boundedIngestErrorResponse(c, err);\n\t\t}\n\t});\n\n\t// POST /api/codex-hooks — ingest Codex hook events\n\tapp.post(\"/api/codex-hooks\", async (c) => {\n\t\tconst result = await parseJsonObjectBody(c, MAX_RAW_EVENTS_BODY_BYTES);\n\t\tif (result instanceof Response) return result;\n\t\tconst payload = result;\n\n\t\ttry {\n\t\t\tconst store = getStore();\n\t\t\tconst target = validateViewerTarget(store, payload, { requirePairedTargets: true });\n\t\t\tif (!target.ok) return c.json(target.body, target.status);\n\t\t\tlet transcriptOutcome: HookTranscriptOutcome | null = null;\n\t\t\tconst envelope = buildRawEventEnvelopeFromCodexHook(untargetedPayload(payload), {\n\t\t\t\ttranscriptPolicy: { trust: \"restricted\", approvedRoots: [codexTranscriptRoot()] },\n\t\t\t\tonTranscriptOutcome: (outcome) => {\n\t\t\t\t\ttranscriptOutcome = outcome;\n\t\t\t\t\ttranscriptDiagnostics.record(\"codex\", outcome);\n\t\t\t\t},\n\t\t\t});\n\t\t\tif (envelope === null) {\n\t\t\t\treturn c.json(transcriptSkipResponse(transcriptOutcome));\n\t\t\t}\n\t\t\tconst ingestResult = await ingestNormalizedEnvelope(store, sweeper, envelope);\n\t\t\treturn c.json({ inserted: ingestResult.inserted, skipped: ingestResult.skipped });\n\t\t} catch (err) {\n\t\t\treturn boundedIngestErrorResponse(c, err);\n\t\t}\n\t});\n\n\treturn app;\n}\n","/**\n * Stats routes — GET /api/stats, GET /api/usage.\n *\n * Ports Python's viewer_routes/stats.py.\n */\n\nimport {\n\tbuildFilterClausesWithContext,\n\tlistMaintenanceJobs,\n\ttype MemoryStore,\n\tVERSION,\n} from \"@codemem/core\";\nimport { Hono } from \"hono\";\n\nfunction maintenanceJobSortKey(job: {\n\tstarted_at: string | null;\n\tupdated_at: string;\n\tkind: string;\n}): [string, string] {\n\treturn [job.started_at ?? job.updated_at, job.kind];\n}\n\nfunction sortActiveMaintenanceJobs<\n\tT extends { started_at: string | null; updated_at: string; kind: string },\n>(jobs: T[]): T[] {\n\treturn [...jobs].sort((a, b) => {\n\t\tconst [aTime, aKind] = maintenanceJobSortKey(a);\n\t\tconst [bTime, bKind] = maintenanceJobSortKey(b);\n\t\tif (aTime !== bTime) return aTime.localeCompare(bTime);\n\t\treturn aKind.localeCompare(bKind);\n\t});\n}\n\nconst MEMORY_ID_METADATA_KEYS = [\"pack_item_ids\", \"added_ids\", \"removed_ids\", \"retained_ids\"];\n\ntype UsageRow = {\n\tid: number;\n\tsession_id: number | null;\n\tevent: string;\n\ttokens_read: number;\n\ttokens_written: number;\n\ttokens_saved: number;\n\tcreated_at: string;\n\tmetadata_json: Record<string, unknown> | null;\n};\n\ntype UsageVisibility = {\n\tvisibleMemoryIds: Set<number>;\n\tvisibleSessionIds: Set<number>;\n};\n\nfunction toUsageRow(\n\trow: Record<string, unknown>,\n\tmetadata: Record<string, unknown> | null,\n): UsageRow {\n\treturn {\n\t\tid: Number(row.id ?? 0),\n\t\tsession_id: row.session_id == null ? null : Number(row.session_id),\n\t\tevent: String(row.event ?? \"pack\"),\n\t\ttokens_read: Number(row.tokens_read ?? 0),\n\t\ttokens_written: Number(row.tokens_written ?? 0),\n\t\ttokens_saved: Number(row.tokens_saved ?? 0),\n\t\tcreated_at: String(row.created_at ?? \"\"),\n\t\tmetadata_json: metadata,\n\t};\n}\n\nfunction metadataMemoryIds(value: unknown): number[] {\n\tif (!Array.isArray(value)) return [];\n\treturn value\n\t\t.map((item) => (typeof item === \"number\" ? item : Number(item)))\n\t\t.filter((item) => Number.isInteger(item) && item > 0);\n}\n\nfunction chunkNumbers(values: number[], chunkSize = 500): number[][] {\n\tconst chunks: number[][] = [];\n\tfor (let start = 0; start < values.length; start += chunkSize) {\n\t\tchunks.push(values.slice(start, start + chunkSize));\n\t}\n\treturn chunks;\n}\n\nfunction visibleMemoryIdSet(store: MemoryStore, memoryIds: Set<number>): Set<number> {\n\tif (memoryIds.size === 0) return new Set();\n\tconst filterResult = buildFilterClausesWithContext(null, {\n\t\tactorId: store.actorId,\n\t\tdeviceId: store.deviceId,\n\t\tenforceScopeVisibility: true,\n\t});\n\tconst visibleIds = new Set<number>();\n\tfor (const chunk of chunkNumbers([...memoryIds])) {\n\t\tconst placeholders = chunk.map(() => \"?\").join(\", \");\n\t\tconst clauses = [\n\t\t\t\"memory_items.active = 1\",\n\t\t\t`memory_items.id IN (${placeholders})`,\n\t\t\t...filterResult.clauses,\n\t\t];\n\t\tconst rows = store.db\n\t\t\t.prepare(`SELECT memory_items.id FROM memory_items WHERE ${clauses.join(\" AND \")}`)\n\t\t\t.all(...chunk, ...filterResult.params) as Array<{ id: number }>;\n\t\tfor (const row of rows) visibleIds.add(Number(row.id));\n\t}\n\treturn visibleIds;\n}\n\nfunction visibleSessionIdSet(store: MemoryStore, sessionIds: Set<number>): Set<number> {\n\tif (sessionIds.size === 0) return new Set();\n\tconst filterResult = buildFilterClausesWithContext(null, {\n\t\tactorId: store.actorId,\n\t\tdeviceId: store.deviceId,\n\t\tenforceScopeVisibility: true,\n\t});\n\tconst visibleIds = new Set<number>();\n\tfor (const chunk of chunkNumbers([...sessionIds])) {\n\t\tconst placeholders = chunk.map(() => \"?\").join(\", \");\n\t\tconst clauses = [\n\t\t\t\"memory_items.active = 1\",\n\t\t\t`memory_items.session_id IN (${placeholders})`,\n\t\t\t...filterResult.clauses,\n\t\t];\n\t\tconst rows = store.db\n\t\t\t.prepare(\n\t\t\t\t`SELECT DISTINCT memory_items.session_id AS session_id\n\t\t\t\t FROM memory_items\n\t\t\t\t WHERE ${clauses.join(\" AND \")}`,\n\t\t\t)\n\t\t\t.all(...chunk, ...filterResult.params) as Array<{ session_id: number | null }>;\n\t\tfor (const row of rows) {\n\t\t\tif (typeof row.session_id === \"number\") visibleIds.add(row.session_id);\n\t\t}\n\t}\n\treturn visibleIds;\n}\n\nfunction buildUsageVisibility(store: MemoryStore, rows: UsageRow[]): UsageVisibility {\n\tconst memoryIds = new Set<number>();\n\tconst sessionIds = new Set<number>();\n\tfor (const row of rows) {\n\t\tif (typeof row.session_id === \"number\") sessionIds.add(row.session_id);\n\t\tfor (const key of MEMORY_ID_METADATA_KEYS) {\n\t\t\tfor (const memoryId of metadataMemoryIds(row.metadata_json?.[key])) {\n\t\t\t\tmemoryIds.add(memoryId);\n\t\t\t}\n\t\t}\n\t}\n\treturn {\n\t\tvisibleMemoryIds: visibleMemoryIdSet(store, memoryIds),\n\t\tvisibleSessionIds: visibleSessionIdSet(store, sessionIds),\n\t};\n}\n\nfunction usageRowVisible(row: UsageRow, visibility: UsageVisibility): boolean {\n\tconst rowSessionVisible =\n\t\trow.session_id == null || visibility.visibleSessionIds.has(row.session_id);\n\tconst packItemIds = row.metadata_json?.pack_item_ids;\n\tif (Array.isArray(packItemIds)) {\n\t\tif (packItemIds.length === 0) {\n\t\t\treturn row.session_id != null && visibility.visibleSessionIds.has(row.session_id);\n\t\t}\n\t\treturn (\n\t\t\trowSessionVisible &&\n\t\t\tmetadataMemoryIds(packItemIds).some((memoryId) => visibility.visibleMemoryIds.has(memoryId))\n\t\t);\n\t}\n\treturn row.session_id != null && visibility.visibleSessionIds.has(row.session_id);\n}\n\nfunction sanitizePackUsageMetadata(\n\tmetadata: Record<string, unknown> | null,\n\tvisibility: UsageVisibility,\n): Record<string, unknown> | null {\n\tif (!metadata) return null;\n\tconst sanitized = { ...metadata };\n\tfor (const key of MEMORY_ID_METADATA_KEYS) {\n\t\tif (Array.isArray(sanitized[key])) {\n\t\t\tsanitized[key] = metadataMemoryIds(sanitized[key]).filter((memoryId) =>\n\t\t\t\tvisibility.visibleMemoryIds.has(memoryId),\n\t\t\t);\n\t\t}\n\t}\n\treturn sanitized;\n}\n\ntype UsageAggregateRow = {\n\tevent: string;\n\tcount: number;\n\ttokens_read: number;\n\ttokens_written: number;\n\ttokens_saved: number;\n};\n\n/**\n * Convert the neutral core aggregate rows into the wire shape for /api/usage\n * (ApiUsageEventSummary: total_tokens_* names), sorted by event name ASC to\n * match the route's historical ordering.\n */\nfunction mapAggregateEvents(rows: UsageAggregateRow[]): Record<string, unknown>[] {\n\treturn rows\n\t\t.map((row) => ({\n\t\t\tevent: row.event,\n\t\t\ttotal_tokens_read: row.tokens_read,\n\t\t\ttotal_tokens_written: row.tokens_written,\n\t\t\ttotal_tokens_saved: row.tokens_saved,\n\t\t\tcount: row.count,\n\t\t}))\n\t\t.sort((a, b) => a.event.localeCompare(b.event));\n}\n\n/**\n * Sum the neutral core aggregate rows into the ApiUsageTotals wire shape.\n */\nfunction totalsFromAggregate(rows: UsageAggregateRow[]): {\n\ttokens_read: number;\n\ttokens_written: number;\n\ttokens_saved: number;\n\tcount: number;\n} {\n\treturn rows.reduce(\n\t\t(acc, row) => ({\n\t\t\ttokens_read: acc.tokens_read + row.tokens_read,\n\t\t\ttokens_written: acc.tokens_written + row.tokens_written,\n\t\t\ttokens_saved: acc.tokens_saved + row.tokens_saved,\n\t\t\tcount: acc.count + row.count,\n\t\t}),\n\t\t{ tokens_read: 0, tokens_written: 0, tokens_saved: 0, count: 0 },\n\t);\n}\n\ntype UsagePayload = Record<string, unknown>;\n\ninterface UsageCacheEntry {\n\tpayload: UsagePayload;\n\texpiresAtMs: number;\n}\n\n/**\n * Short-lived cache for the computed /api/usage payload.\n *\n * The health dot polls /api/usage on every 5s refresh regardless of the\n * active tab. The token/event totals come from indexed SQL aggregates and the\n * recent-pack window runs scope-visibility resolution over its bounded set, so\n * each miss is cheap — but the totals are cumulative dashboard figures where a\n * few seconds of staleness is acceptable, so caching still collapses the\n * repeated recompute on the polling loop. Keyed by db path + scope identity +\n * project filter so distinct stores/projects never share an entry.\n */\nconst usagePayloadCache = new Map<string, UsageCacheEntry>();\nconst USAGE_PAYLOAD_CACHE_MS = 10_000;\n\n/**\n * Hard cap on cached usage payloads. The cache key folds in the arbitrary\n * `?project=` filter and a scope-visibility fingerprint that becomes\n * per-request-unique on the error/bypass path, so without a bound the map\n * would grow without limit in a long-running viewer. The cap is far above the\n * realistic working set (a handful of projects times one or two scope\n * generations), so legitimate hits are never evicted under normal load.\n */\nconst USAGE_PAYLOAD_CACHE_MAX_ENTRIES = 256;\n\n/**\n * Sweep expired entries and enforce the size cap before inserting a new one.\n *\n * Mirrors the lazy-sweep approach in request-rate-limit.ts: eviction is\n * piggybacked on writes rather than run on a timer, so an idle viewer does no\n * background work. Expired entries (those past `expiresAtMs`) are always\n * dropped; if the map is still at capacity afterward — e.g. a burst of\n * distinct, still-live bypass keys — the oldest-expiring entries are evicted\n * to make room. This never changes hit/miss semantics for a live entry: the\n * caller still re-checks `expiresAtMs` on read, and only already-expired or\n * over-cap entries are removed here.\n */\nfunction sweepUsagePayloadCache(cache: Map<string, UsageCacheEntry>, nowMs: number): void {\n\tfor (const [key, entry] of cache) {\n\t\tif (entry.expiresAtMs <= nowMs) cache.delete(key);\n\t}\n\tif (cache.size < USAGE_PAYLOAD_CACHE_MAX_ENTRIES) return;\n\t// Leave room for the entry about to be inserted by evicting down to one\n\t// below the cap. Drop the soonest-to-expire entries first.\n\tconst byExpiry = [...cache.entries()].sort((a, b) => a[1].expiresAtMs - b[1].expiresAtMs);\n\tlet overflow = cache.size - USAGE_PAYLOAD_CACHE_MAX_ENTRIES + 1;\n\tfor (const [key] of byExpiry) {\n\t\tif (overflow <= 0) break;\n\t\tcache.delete(key);\n\t\toverflow -= 1;\n\t}\n}\n\n/**\n * Cheap fingerprint of the state that drives scope visibility\n * (`scope_memberships` / `replication_scopes`). Folding this into the usage\n * cache key ensures a membership/scope status change — e.g. a revocation —\n * invalidates any cached payload immediately instead of letting a device keep\n * reading a scope it can no longer see for up to the TTL. These tables are\n * small, so the aggregate is negligible next to the usage_events scan the\n * cache exists to avoid. Fails safe: any error forces a unique value so the\n * request bypasses the cache and recomputes visibility from scratch.\n */\nfunction scopeVisibilityGeneration(store: MemoryStore): string {\n\ttry {\n\t\tconst row = store.db\n\t\t\t.prepare(\n\t\t\t\t`SELECT\n\t\t\t\t\t(SELECT COUNT(*) FROM scope_memberships) AS m_count,\n\t\t\t\t\t(SELECT COUNT(*) FROM scope_memberships WHERE status = 'active') AS m_active,\n\t\t\t\t\t(SELECT COALESCE(MAX(updated_at), '') FROM scope_memberships) AS m_updated,\n\t\t\t\t\t(SELECT COALESCE(MAX(membership_epoch), 0) FROM scope_memberships) AS m_epoch,\n\t\t\t\t\t(SELECT COUNT(*) FROM replication_scopes) AS s_count,\n\t\t\t\t\t(SELECT COUNT(*) FROM replication_scopes WHERE status = 'active') AS s_active,\n\t\t\t\t\t(SELECT COALESCE(MAX(updated_at), '') FROM replication_scopes) AS s_updated`,\n\t\t\t)\n\t\t\t.get() as Record<string, unknown> | undefined;\n\t\tif (!row) return \"no-scope-state\";\n\t\treturn [\n\t\t\trow.m_count,\n\t\t\trow.m_active,\n\t\t\trow.m_updated,\n\t\t\trow.m_epoch,\n\t\t\trow.s_count,\n\t\t\trow.s_active,\n\t\t\trow.s_updated,\n\t\t].join(\":\");\n\t} catch {\n\t\t// Fail safe: bypass the cache rather than risk serving a payload\n\t\t// computed under stale visibility rules.\n\t\treturn `bypass-${Date.now()}-${Math.random()}`;\n\t}\n}\n\nfunction usageCacheKey(store: MemoryStore, projectFilter: string | null): string {\n\tconst visibilityGeneration = scopeVisibilityGeneration(store);\n\treturn `${store.dbPath}|${store.actorId}|${store.deviceId}|${projectFilter ?? \"\"}|${visibilityGeneration}`;\n}\n\n/**\n * Create stats routes. The store factory is called per-request to get a\n * fresh connection (matching the Python viewer pattern).\n */\nexport function statsRoutes(getStore: () => MemoryStore) {\n\tconst app = new Hono();\n\n\tconst parseMetadataJson = (value: unknown): Record<string, unknown> | null => {\n\t\tif (typeof value !== \"string\" || !value.trim()) return null;\n\t\ttry {\n\t\t\treturn JSON.parse(value) as Record<string, unknown>;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t};\n\n\t// Keep completed jobs visible in /api/stats for a short window after\n\t// finished_at so the health UI has a chance to render success confirmation\n\t// for fast-completing backfills (often <1s). Failed jobs stay indefinitely.\n\tconst RECENTLY_COMPLETED_WINDOW_MS = 120_000;\n\n\tapp.get(\"/api/stats\", (c) => {\n\t\tconst store = getStore();\n\t\tconst jobs = listMaintenanceJobs(store.db);\n\t\tconst now = Date.now();\n\t\tconst surfacedJobs = sortActiveMaintenanceJobs(\n\t\t\tjobs.filter((job) => {\n\t\t\t\tif (job.status === \"pending\" || job.status === \"running\" || job.status === \"failed\") {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (job.status === \"completed\" && job.finished_at) {\n\t\t\t\t\tconst finished = Date.parse(job.finished_at);\n\t\t\t\t\tif (Number.isFinite(finished) && now - finished <= RECENTLY_COMPLETED_WINDOW_MS) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}),\n\t\t).map((job) => ({\n\t\t\tkind: job.kind,\n\t\t\ttitle: job.title,\n\t\t\tstatus: job.status,\n\t\t\tmessage: job.message,\n\t\t\tprogress: job.progress,\n\t\t\tfinished_at: job.finished_at,\n\t\t\terror: job.error,\n\t\t}));\n\t\treturn c.json({\n\t\t\t...store.stats(),\n\t\t\tviewer_pid: process.pid,\n\t\t\tmaintenance_jobs: surfacedJobs,\n\t\t});\n\t});\n\n\tapp.get(\"/api/runtime\", (c) => {\n\t\treturn c.json({\n\t\t\tversion: VERSION,\n\t\t});\n\t});\n\n\tapp.get(\"/api/usage\", (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tconst projectFilter = c.req.query(\"project\") || null;\n\t\t\tconst cacheKey = usageCacheKey(store, projectFilter);\n\t\t\tconst nowMs = Date.now();\n\t\t\tconst cached = usagePayloadCache.get(cacheKey);\n\t\t\tif (cached && nowMs < cached.expiresAtMs) {\n\t\t\t\treturn c.json(cached.payload);\n\t\t\t}\n\n\t\t\t// Token/event aggregates are unfiltered SQL GROUP BYs (matching\n\t\t\t// store.stats()), so they never load the full usage_events table\n\t\t\t// into JS. Only the small surfaced recent_packs window below keeps\n\t\t\t// per-row scope visibility + metadata sanitization.\n\t\t\tconst globalAggregate = store.usageAggregate();\n\t\t\tconst eventsGlobal = mapAggregateEvents(globalAggregate);\n\t\t\tconst totalsGlobal = totalsFromAggregate(globalAggregate);\n\t\t\tconst filteredAggregate = projectFilter ? store.usageAggregate(projectFilter) : null;\n\t\t\tconst eventsFiltered = filteredAggregate ? mapAggregateEvents(filteredAggregate) : null;\n\t\t\tconst totalsFiltered = filteredAggregate ? totalsFromAggregate(filteredAggregate) : null;\n\n\t\t\t// recent_packs candidate window. Over-fetch the most-recent pack\n\t\t\t// events (20x the 10 we surface) so that, in the common case where a\n\t\t\t// device sees most of its own packs, 10 *visible* packs survive the\n\t\t\t// scope filter below without ever scanning the whole table.\n\t\t\t// Tradeoff vs. the old full-scan-then-slice: if MORE than\n\t\t\t// (LIMIT - 10) of the newest packs are non-visible, fewer than 10\n\t\t\t// surface, and a visible pack older than the newest 200 is not\n\t\t\t// shown at all. That only bites a heavily-shared DB whose recent\n\t\t\t// activity is dominated by other scopes; for an activity widget the\n\t\t\t// bounded recompute on a 5s poll is the right call.\n\t\t\tconst RECENT_PACK_SCAN_LIMIT = 200;\n\t\t\tconst loadRecentPackWindow = (project?: string | null): UsageRow[] => {\n\t\t\t\tconst rows = project\n\t\t\t\t\t? (store.db\n\t\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t\t`SELECT usage_events.id, usage_events.session_id, usage_events.event,\n\t\t\t\t\t\t\t\t\tusage_events.tokens_read, usage_events.tokens_written, usage_events.tokens_saved,\n\t\t\t\t\t\t\t\t\tusage_events.created_at, usage_events.metadata_json\n\t\t\t\t\t\t\t\t FROM usage_events\n\t\t\t\t\t\t\t\t JOIN sessions ON sessions.id = usage_events.session_id\n\t\t\t\t\t\t\t\t WHERE sessions.project = ? AND usage_events.event = 'pack'\n\t\t\t\t\t\t\t\t ORDER BY usage_events.created_at DESC\n\t\t\t\t\t\t\t\t LIMIT ?`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.all(project, RECENT_PACK_SCAN_LIMIT) as Record<string, unknown>[])\n\t\t\t\t\t: (store.db\n\t\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t\t`SELECT id, session_id, event, tokens_read, tokens_written, tokens_saved,\n\t\t\t\t\t\t\t\t\tcreated_at, metadata_json\n\t\t\t\t\t\t\t\t FROM usage_events\n\t\t\t\t\t\t\t\t WHERE event = 'pack'\n\t\t\t\t\t\t\t\t ORDER BY created_at DESC\n\t\t\t\t\t\t\t\t LIMIT ?`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.all(RECENT_PACK_SCAN_LIMIT) as Record<string, unknown>[]);\n\t\t\t\treturn rows.map((row) => toUsageRow(row, parseMetadataJson(row.metadata_json)));\n\t\t\t};\n\t\t\tconst recentWindow = loadRecentPackWindow(projectFilter);\n\t\t\tconst recentVisibility = buildUsageVisibility(store, recentWindow);\n\t\t\tconst recentPacks = recentWindow\n\t\t\t\t.filter((row) => usageRowVisible(row, recentVisibility))\n\t\t\t\t.slice(0, 10)\n\t\t\t\t.map((row) => ({\n\t\t\t\t\t...row,\n\t\t\t\t\tmetadata_json: sanitizePackUsageMetadata(row.metadata_json, recentVisibility),\n\t\t\t\t}));\n\n\t\t\tconst payload: UsagePayload = {\n\t\t\t\tproject: projectFilter,\n\t\t\t\tevents: projectFilter ? eventsFiltered : eventsGlobal,\n\t\t\t\ttotals: projectFilter ? totalsFiltered : totalsGlobal,\n\t\t\t\tevents_global: eventsGlobal,\n\t\t\t\ttotals_global: totalsGlobal,\n\t\t\t\tevents_filtered: eventsFiltered,\n\t\t\t\ttotals_filtered: totalsFiltered,\n\t\t\t\trecent_packs: recentPacks,\n\t\t\t};\n\t\t\tconst setAtMs = Date.now();\n\t\t\tsweepUsagePayloadCache(usagePayloadCache, setAtMs);\n\t\t\tusagePayloadCache.set(cacheKey, {\n\t\t\t\tpayload,\n\t\t\t\texpiresAtMs: setAtMs + USAGE_PAYLOAD_CACHE_MS,\n\t\t\t});\n\t\t\treturn c.json(payload);\n\t\t}\n\t});\n\n\treturn app;\n}\n\n/**\n * Internals exposed for unit tests of the usage-cache eviction. Not part of the\n * route's public surface; consumers should go through the HTTP handlers.\n */\nexport const __usageCacheTestHooks = {\n\tcache: usagePayloadCache,\n\tsweep: sweepUsagePayloadCache,\n\tmaxEntries: USAGE_PAYLOAD_CACHE_MAX_ENTRIES,\n\tttlMs: USAGE_PAYLOAD_CACHE_MS,\n};\n","import type { LegacyTeamSetupActivationErrorCode, LegacyTeamSetupDraftView } from \"@codemem/core\";\n\nexport interface LegacyTeamSetupCandidateSummaryV1 {\n\tcandidateRef: string;\n\tdisplayName: string;\n\tstatus: \"needs_setup\" | \"in_progress\" | \"stale\" | \"ready\";\n\tdeviceCount: number;\n\tprojectCount: number;\n\tunresolvedDeviceCount: number;\n\tunresolvedProjectCount: number;\n}\n\nexport type LegacyTeamSetupPendingCandidateSummaryV1 = Omit<\n\tLegacyTeamSetupCandidateSummaryV1,\n\t\"status\"\n> & {\n\tstatus: Exclude<LegacyTeamSetupCandidateSummaryV1[\"status\"], \"ready\">;\n};\n\nexport interface LegacyTeamSetupSummaryResponseV1 {\n\tversion: 1;\n\tcandidates: LegacyTeamSetupPendingCandidateSummaryV1[];\n}\n\nexport type LegacyTeamSetupActionBlockedReasonV1 =\n\t| \"setup_incomplete\"\n\t| \"setup_unavailable\"\n\t| \"setup_completed\"\n\t| \"device_inactive\"\n\t| \"device_active\"\n\t| \"assignment_evidence_inactive\"\n\t| \"assignment_required\"\n\t| \"assignment_unavailable\"\n\t| \"decision_unresolved\"\n\t| \"mapping_unavailable\"\n\t| \"automatic_mapping\";\n\nexport type LegacyTeamSetupActionGateV1 =\n\t| { enabled: true; blockedReason: null }\n\t| { enabled: false; blockedReason: LegacyTeamSetupActionBlockedReasonV1 };\n\nexport type LegacyTeamSetupUnavailableReasonV1 = Exclude<\n\tLegacyTeamSetupActivationErrorCode,\n\t\"team_setup_projection_changed\"\n>;\n\nexport interface LegacyTeamSetupDeviceV1 {\n\tdeviceRef: string;\n\tdisplayName: string;\n\tenabled: boolean;\n\texistingIdentityRef: string | null;\n\tsuggestedIdentityRef: string | null;\n\tverifiedEvidenceKind: \"active_assignment\" | null;\n\tdecision: \"unresolved\" | \"included\" | \"excluded\" | \"removed\";\n\ttargetIdentityRef: string | null;\n\texpectation:\n\t\t| { kind: \"absent\" }\n\t\t| { kind: \"existing\"; assignmentVersion: number; identityRef: string };\n\tactions: {\n\t\tassignIdentity: LegacyTeamSetupActionGateV1;\n\t\tinclude: LegacyTeamSetupActionGateV1;\n\t\texclude: LegacyTeamSetupActionGateV1;\n\t\tremove: LegacyTeamSetupActionGateV1;\n\t\tclearDecision: LegacyTeamSetupActionGateV1;\n\t};\n}\n\nexport interface LegacyTeamSetupProjectV1 {\n\tprojectRef: string;\n\tdisplayName: string;\n\tresolution: \"unresolved\" | \"deterministic\" | \"explicit\";\n\tcanonicalProjectRef: string | null;\n\tresolvedProjectRef: string | null;\n\tmappingChoices: Array<{ resolvedProjectRef: string; displayName: string }>;\n\tactions: { map: LegacyTeamSetupActionGateV1 };\n}\n\nexport interface LegacyTeamSetupIdentityChoiceV1 {\n\tidentityRef: string;\n\tdisplayName: string;\n}\n\nexport interface LegacyTeamSetupViewerAccessDeltaV1 {\n\tteamChanges: Array<{\n\t\tteamRef: string;\n\t\tteamDisplayName: string;\n\t\tchange: \"add\" | \"update\" | \"remove\";\n\t\tfromDeviceEligibilityMode: \"person_all_devices\" | \"reviewed_allowlist\" | null;\n\t\ttoDeviceEligibilityMode: \"reviewed_allowlist\";\n\t}>;\n\tmembershipChanges: Array<{\n\t\tteamRef: string;\n\t\tteamDisplayName: string;\n\t\tidentityRef: string;\n\t\tidentityDisplayName: string;\n\t\tchange: \"add\" | \"update\" | \"remove\";\n\t}>;\n\tprojectChanges: Array<{\n\t\tprojectRef: string;\n\t\tprojectDisplayName: string;\n\t\tfromCanonicalProjectRef: string | null;\n\t\tfromResolvedProjectRef: string | null;\n\t\tfromResolvedProjectDisplayName: string | null;\n\t\ttoCanonicalProjectRef: string | null;\n\t\ttoResolvedProjectRef: string | null;\n\t\ttoResolvedProjectDisplayName: string | null;\n\t\tchange: \"add\" | \"update\" | \"remove\";\n\t}>;\n\trecipientChanges: Array<{\n\t\tcanonicalProjectRef: string;\n\t\tcanonicalProjectDisplayName: string;\n\t\tcanonicalProjectKind: \"project\" | \"legacy_default_sharing\";\n\t\trecipientKind: \"team\";\n\t\trecipientRef: string;\n\t\trecipientDisplayName: string;\n\t\tchange: \"add\" | \"update\" | \"remove\";\n\t}>;\n\tdeviceAccessChanges: Array<{\n\t\tcanonicalProjectRef: string;\n\t\tcanonicalProjectDisplayName: string;\n\t\tcanonicalProjectKind: \"project\" | \"legacy_default_sharing\";\n\t\tdeviceRef: string;\n\t\tdeviceDisplayName: string;\n\t\tchange: \"add\" | \"remove\";\n\t}>;\n}\n\ninterface LegacyTeamSetupViewBaseV1 {\n\tversion: 1;\n\tcandidate: LegacyTeamSetupCandidateSummaryV1;\n\tattemptId: string;\n\tunresolvedDeviceCount: number;\n\tunresolvedProjectCount: number;\n\tdevices: LegacyTeamSetupDeviceV1[];\n\tprojects: LegacyTeamSetupProjectV1[];\n\tidentityChoices: LegacyTeamSetupIdentityChoiceV1[];\n}\n\nexport type LegacyTeamSetupViewV1 =\n\t| (LegacyTeamSetupViewBaseV1 & {\n\t\t\tstate: \"reviewing\";\n\t\t\tactions: {\n\t\t\t\trefresh: { enabled: true; blockedReason: null };\n\t\t\t\tfinish: { enabled: false; blockedReason: \"setup_incomplete\" };\n\t\t\t};\n\t })\n\t| (LegacyTeamSetupViewBaseV1 & {\n\t\t\tstate: \"ready_to_finish\";\n\t\t\tactions: {\n\t\t\t\trefresh: { enabled: true; blockedReason: null };\n\t\t\t\tfinish: { enabled: true; blockedReason: null };\n\t\t\t};\n\t\t\tfinishDigest: string;\n\t\t\taccessDeltaDigest: string;\n\t\t\tviewerAccessDeltaDigest: string;\n\t\t\taccessDelta: LegacyTeamSetupViewerAccessDeltaV1;\n\t })\n\t| (LegacyTeamSetupViewBaseV1 & {\n\t\t\tstate: \"unavailable\";\n\t\t\tunavailableReason: LegacyTeamSetupUnavailableReasonV1;\n\t\t\tactions: {\n\t\t\t\trefresh: { enabled: true; blockedReason: null };\n\t\t\t\tfinish: { enabled: false; blockedReason: \"setup_unavailable\" };\n\t\t\t};\n\t })\n\t| (LegacyTeamSetupViewBaseV1 & {\n\t\t\tstate: \"completed\";\n\t\t\tactions: {\n\t\t\t\trefresh: { enabled: false; blockedReason: \"setup_completed\" };\n\t\t\t\tfinish: { enabled: false; blockedReason: \"setup_completed\" };\n\t\t\t};\n\t });\n\nexport type LegacyTeamSetupDetailResponseV1 = LegacyTeamSetupViewV1;\nexport type LegacyTeamSetupMutationResponseV1 = LegacyTeamSetupViewV1;\n\nexport interface LegacyTeamSetupErrorResponseV1 {\n\terror: LegacyTeamSetupActivationErrorCode;\n}\n\nexport interface LegacyTeamSetupFinishResponseV1 {\n\tversion: 1;\n\tstatus: \"completed\";\n\tteamRef: string;\n\tattemptId: string;\n\taccessDeltaDigest: string;\n\tcompletedAt: string;\n}\n\ntype DeviceData = Omit<LegacyTeamSetupDeviceV1, \"actions\">;\ntype ProjectData = Omit<LegacyTeamSetupProjectV1, \"actions\">;\n\ninterface ProjectViewInput {\n\tversion: 1;\n\tcandidate: LegacyTeamSetupCandidateSummaryV1;\n\tdraftState: LegacyTeamSetupDraftView[\"state\"];\n\tattemptId: string;\n\tunresolvedDeviceCount: number;\n\tunresolvedProjectCount: number;\n\tdevices: DeviceData[];\n\tprojects: ProjectData[];\n\tidentityChoices: LegacyTeamSetupIdentityChoiceV1[];\n\tunavailableReason: LegacyTeamSetupUnavailableReasonV1 | null;\n\tpreview: null | {\n\t\tfinishDigest: string;\n\t\taccessDeltaDigest: string;\n\t\tviewerAccessDeltaDigest: string;\n\t\taccessDelta: LegacyTeamSetupViewerAccessDeltaV1;\n\t};\n}\n\nconst enabled = { enabled: true, blockedReason: null } as const;\n\nfunction blocked<const Reason extends LegacyTeamSetupActionBlockedReasonV1>(\n\treason: Reason,\n): { enabled: false; blockedReason: Reason } {\n\treturn { enabled: false, blockedReason: reason };\n}\n\nfunction deviceActions(\n\tdevice: DeviceData,\n\tidentityChoices: LegacyTeamSetupIdentityChoiceV1[],\n\tstate: LegacyTeamSetupViewV1[\"state\"],\n): LegacyTeamSetupDeviceV1[\"actions\"] {\n\tif (state === \"completed\") return disabledDeviceActions(\"setup_completed\");\n\tif (state === \"unavailable\") return disabledDeviceActions(\"setup_unavailable\");\n\tconst assignmentEvidenceInactive =\n\t\tdevice.expectation.kind === \"existing\" && device.verifiedEvidenceKind !== \"active_assignment\";\n\tconst targetAvailable = identityChoices.some(\n\t\t(identity) => identity.identityRef === device.targetIdentityRef,\n\t);\n\treturn {\n\t\tassignIdentity: !device.enabled\n\t\t\t? blocked(\"device_inactive\")\n\t\t\t: assignmentEvidenceInactive\n\t\t\t\t? blocked(\"assignment_evidence_inactive\")\n\t\t\t\t: identityChoices.length === 0\n\t\t\t\t\t? blocked(\"assignment_unavailable\")\n\t\t\t\t\t: enabled,\n\t\tinclude: !device.enabled\n\t\t\t? blocked(\"device_inactive\")\n\t\t\t: assignmentEvidenceInactive\n\t\t\t\t? blocked(\"assignment_evidence_inactive\")\n\t\t\t\t: !device.targetIdentityRef\n\t\t\t\t\t? blocked(\"assignment_required\")\n\t\t\t\t\t: !targetAvailable\n\t\t\t\t\t\t? blocked(\"assignment_unavailable\")\n\t\t\t\t\t\t: enabled,\n\t\texclude: device.enabled ? enabled : blocked(\"device_inactive\"),\n\t\tremove: device.enabled ? blocked(\"device_active\") : enabled,\n\t\tclearDecision: device.decision === \"unresolved\" ? blocked(\"decision_unresolved\") : enabled,\n\t};\n}\n\nfunction disabledDeviceActions(\n\treason: \"setup_completed\" | \"setup_unavailable\",\n): LegacyTeamSetupDeviceV1[\"actions\"] {\n\tconst gate = blocked(reason);\n\treturn {\n\t\tassignIdentity: gate,\n\t\tinclude: gate,\n\t\texclude: gate,\n\t\tremove: gate,\n\t\tclearDecision: gate,\n\t};\n}\n\nfunction projectActions(\n\tproject: ProjectData,\n\tstate: LegacyTeamSetupViewV1[\"state\"],\n): LegacyTeamSetupProjectV1[\"actions\"] {\n\tif (state === \"completed\") return { map: blocked(\"setup_completed\") };\n\tif (state === \"unavailable\") return { map: blocked(\"setup_unavailable\") };\n\treturn {\n\t\tmap:\n\t\t\tproject.resolution === \"deterministic\"\n\t\t\t\t? blocked(\"automatic_mapping\")\n\t\t\t\t: project.mappingChoices.length === 0\n\t\t\t\t\t? blocked(\"mapping_unavailable\")\n\t\t\t\t\t: enabled,\n\t};\n}\n\nfunction viewState(input: ProjectViewInput): LegacyTeamSetupViewV1[\"state\"] {\n\tif (input.draftState === \"completed\") return \"completed\";\n\tif (input.draftState === \"stale\" || input.unavailableReason) return \"unavailable\";\n\tif (input.preview) return \"ready_to_finish\";\n\treturn \"reviewing\";\n}\n\nexport function projectLegacyTeamSetupView(input: ProjectViewInput): LegacyTeamSetupViewV1 {\n\tconst state = viewState(input);\n\tconst base = {\n\t\tversion: input.version,\n\t\tcandidate: input.candidate,\n\t\tattemptId: input.attemptId,\n\t\tunresolvedDeviceCount: input.unresolvedDeviceCount,\n\t\tunresolvedProjectCount: input.unresolvedProjectCount,\n\t\tdevices: input.devices.map((device) => ({\n\t\t\t...device,\n\t\t\tactions: deviceActions(device, input.identityChoices, state),\n\t\t})),\n\t\tprojects: input.projects.map((project) => ({\n\t\t\t...project,\n\t\t\tactions: projectActions(project, state),\n\t\t})),\n\t\tidentityChoices: input.identityChoices,\n\t};\n\tif (state === \"completed\") {\n\t\treturn {\n\t\t\t...base,\n\t\t\tstate,\n\t\t\tactions: {\n\t\t\t\trefresh: blocked(\"setup_completed\"),\n\t\t\t\tfinish: blocked(\"setup_completed\"),\n\t\t\t},\n\t\t};\n\t}\n\tif (state === \"unavailable\") {\n\t\treturn {\n\t\t\t...base,\n\t\t\tstate,\n\t\t\tunavailableReason: input.unavailableReason ?? \"team_setup_confirmation_stale\",\n\t\t\tactions: { refresh: enabled, finish: blocked(\"setup_unavailable\") },\n\t\t};\n\t}\n\tif (state === \"ready_to_finish\" && input.preview) {\n\t\treturn {\n\t\t\t...base,\n\t\t\tstate,\n\t\t\tactions: { refresh: enabled, finish: enabled },\n\t\t\t...input.preview,\n\t\t};\n\t}\n\treturn {\n\t\t...base,\n\t\tstate: \"reviewing\",\n\t\tactions: { refresh: enabled, finish: blocked(\"setup_incomplete\") },\n\t};\n}\n","import type {\n\tCoordinatorLegacyTeamCompletionManifestV1,\n\tCoordinatorLegacyTeamCompletionRecord,\n\tLegacyTeamCandidateView,\n\tLegacyTeamConfiguredGroupSnapshot,\n\tLegacyTeamSetupAccessDeltaV1,\n\tLegacyTeamSetupActivationErrorCode,\n\tLegacyTeamSetupActivationResultV1,\n\tLegacyTeamSetupDraftView,\n\tMemoryStore,\n} from \"@codemem/core\";\nimport {\n\tapplyLegacyTeamSetupCompletionManifest,\n\tapplyLegacyTeamSetupCompletionManifestAndReturnActivation,\n\tareLegacyTeamSetupCompletionPolicyFactsAdditivelyCompatible,\n\tbuildBaseUrl,\n\tcanonicalCoordinatorLegacyTeamCompletionManifestJson,\n\tclaimRecipientPolicyActorMutations,\n\tclaimRecipientPolicyPublicationMutation,\n\tclearLegacyTeamSetupDeviceDecision,\n\tcontainLegacyTeamSetupCompletionConflict,\n\tcoordinatorCreateLegacyTeamCompletionAction,\n\tcoordinatorGetLegacyTeamCompletionAction,\n\tcoordinatorListDevicesAction,\n\tcoordinatorListGroupsAction,\n\tcoordinatorListLegacyTeamCompletionsAction,\n\tderiveLegacyTeamSetupCompletionManifest,\n\tdeterministicPolicyTeamId,\n\tdiscoverLegacyTeamCandidates,\n\tfingerprintPublicKey,\n\tgetLegacyTeamSetupDraft,\n\tinspectFreshLegacyTeamSetupActivation,\n\tinspectLegacyTeamSetupActivation,\n\tisLegacyTeamCandidateSelectable,\n\tisLegacyTeamSetupProjectMappingIdentity,\n\tLegacyTeamSetupAdditiveConvergenceError,\n\tlegacyTeamCandidateId,\n\tlegacyTeamCandidateProjectInventory,\n\tlegacyTeamCanonicalProjectRef,\n\tlegacyTeamDeviceRef,\n\tlegacyTeamResolvedProjectRef,\n\tlegacyTeamSetupApiErrorCode,\n\tlistProjectScopeCandidates,\n\tpreviewLegacyTeamSetupActivation,\n\treadCoordinatorSyncConfig,\n\trecipientPolicyDigest,\n\treconstructLegacyTeamSetupCompletionManifest,\n\trefreshLegacyTeamCandidate,\n\treplayLegacyTeamSetupActivation,\n\trequireLegacyTeamSetupAccessDeltaWithinLimit,\n\tserializeRecipientPolicyCoordinatorGroupMutation,\n\tserializeRecipientPolicyPublicationMutation,\n\tserializeRecipientPolicyTeamMutation,\n\tsetLegacyTeamSetupDeviceAssignment,\n\tsetLegacyTeamSetupDeviceDecision,\n\tsetLegacyTeamSetupProjectMapping,\n\tvalidateLegacyTeamSetupCompletionManifest,\n\tvalidateLegacyTeamSetupCompletionManifestBinding,\n} from \"@codemem/core\";\nimport { type Context, Hono } from \"hono\";\nimport {\n\ttype LegacyTeamSetupCandidateSummaryV1,\n\ttype LegacyTeamSetupDetailResponseV1,\n\ttype LegacyTeamSetupDeviceV1,\n\ttype LegacyTeamSetupFinishResponseV1,\n\ttype LegacyTeamSetupIdentityChoiceV1,\n\ttype LegacyTeamSetupPendingCandidateSummaryV1,\n\ttype LegacyTeamSetupProjectV1,\n\ttype LegacyTeamSetupSummaryResponseV1,\n\ttype LegacyTeamSetupUnavailableReasonV1,\n\ttype LegacyTeamSetupViewerAccessDeltaV1,\n\tprojectLegacyTeamSetupView,\n} from \"./team-setup-view.js\";\n\nexport type {\n\tLegacyTeamSetupActionBlockedReasonV1,\n\tLegacyTeamSetupActionGateV1,\n\tLegacyTeamSetupCandidateSummaryV1,\n\tLegacyTeamSetupDetailResponseV1,\n\tLegacyTeamSetupDeviceV1,\n\tLegacyTeamSetupErrorResponseV1,\n\tLegacyTeamSetupFinishResponseV1,\n\tLegacyTeamSetupIdentityChoiceV1,\n\tLegacyTeamSetupMutationResponseV1,\n\tLegacyTeamSetupPendingCandidateSummaryV1,\n\tLegacyTeamSetupProjectV1,\n\tLegacyTeamSetupSummaryResponseV1,\n\tLegacyTeamSetupUnavailableReasonV1,\n\tLegacyTeamSetupViewerAccessDeltaV1,\n\tLegacyTeamSetupViewV1,\n} from \"./team-setup-view.js\";\n\nconst TEAM_SETUP_VERSION = 1 as const;\nconst MAX_CONFIGURED_GROUPS = 25;\nconst MAX_SCOPE_EVIDENCE_COORDINATORS = 100;\nconst MAX_DEVICES = 500;\nconst MAX_PROJECTS = 500;\nconst MAX_IDENTITY_CHOICES = 500;\nconst MAX_COMPLETED_IDENTITY_CHOICES = MAX_DEVICES * 4;\nconst MAX_PROJECT_MAPPING_CHOICES = 500;\nconst MAX_TOTAL_PROJECT_MAPPING_CHOICES = 10_000;\nconst MAX_PROJECT_MAPPING_SCAN_ROWS = 10_000;\nconst MAX_PROJECT_MAPPING_METADATA_ROWS = 10_000;\nconst MAX_MUTATION_BODY_BYTES = 8_192;\nconst SUMMARY_SNAPSHOT_CACHE_TTL_MS = 30_000;\nconst COORDINATOR_ROSTER_READ_BUDGET_MS = 60_000;\nexport const TEAM_SETUP_ROUTE_PREFIX = \"/api/sync/team-setup/v1\";\nconst CANDIDATE_REF_PATTERN = /^legacy-team-candidate:[0-9a-f]{32}$/u;\nconst DEVICE_REF_PATTERN = /^legacy-team-device-ref-v1:[0-9a-f]{64}$/u;\nconst PROJECT_REF_PATTERN = /^legacy-team-project-ref-v1:[0-9a-f]{64}$/u;\nconst IDENTITY_REF_PATTERN = /^legacy-team-viewer-identity-ref-v1:[0-9a-f]{64}$/u;\nconst RESOLVED_PROJECT_REF_PATTERN = /^legacy-team-resolved-project-ref-v1:[0-9a-f]{64}$/u;\nconst ATTEMPT_ID_PATTERN = /^legacy-team-attempt:[0-9a-f-]{36}$/u;\nconst FINISH_DIGEST_PATTERN = /^legacy-team-activation-finish-v1:[0-9a-f]{64}$/u;\nconst ACCESS_DELTA_DIGEST_PATTERN = /^legacy-team-access-delta:[0-9a-f]{64}$/u;\nconst VIEWER_ACCESS_DELTA_DIGEST_PATTERN = /^legacy-team-viewer-access-delta-v1:[0-9a-f]{64}$/u;\nconst activeCandidateMutations = new WeakMap<MemoryStore[\"db\"], Map<string, Promise<void>>>();\n\nfunction claimCandidateMutation(db: MemoryStore[\"db\"], candidateRef: string): (() => void) | null {\n\tlet active = activeCandidateMutations.get(db);\n\tif (!active) {\n\t\tactive = new Map();\n\t\tactiveCandidateMutations.set(db, active);\n\t}\n\tif (active.has(candidateRef)) return null;\n\tlet settle: () => void = () => undefined;\n\tconst settled = new Promise<void>((resolve) => {\n\t\tsettle = resolve;\n\t});\n\tactive.set(candidateRef, settled);\n\tlet released = false;\n\treturn () => {\n\t\tif (released) return;\n\t\treleased = true;\n\t\tactive?.delete(candidateRef);\n\t\tsettle();\n\t};\n}\n\n/** Resolves once the current holder of the candidate claim (if any) releases it. */\nfunction candidateMutationSettled(db: MemoryStore[\"db\"], candidateRef: string): Promise<void> {\n\treturn activeCandidateMutations.get(db)?.get(candidateRef) ?? Promise.resolve();\n}\n\nasync function runCandidateMutation<T>(\n\tdb: MemoryStore[\"db\"],\n\tcandidateRef: string,\n\toperation: () => Promise<T>,\n): Promise<boolean> {\n\tconst release = claimCandidateMutation(db, candidateRef);\n\tif (!release) return false;\n\ttry {\n\t\tawait operation();\n\t\treturn true;\n\t} finally {\n\t\trelease();\n\t}\n}\n\ninterface LegacyTeamConfiguredGroupSnapshotLoadOptions {\n\tcandidateRef?: string;\n\tdeadlineMs?: number;\n}\n\nexport interface LegacyTeamCandidateGroupDescriptor {\n\tgroupId: string;\n\tcoordinatorId: string;\n}\n\nexport type LegacyTeamConfiguredGroupSnapshotLoader = (\n\toptions?: LegacyTeamConfiguredGroupSnapshotLoadOptions,\n) => Promise<LegacyTeamConfiguredGroupSnapshot[]>;\n\nexport interface TeamSetupRoutesOptions {\n\tgetStore: () => MemoryStore;\n\tloadLegacyTeamConfiguredGroupSnapshots?: LegacyTeamConfiguredGroupSnapshotLoader;\n\tsnapshotLoaderDependencies?: LegacyTeamSnapshotLoaderDependencies;\n\tcompletionDependencies?: LegacyTeamCompletionDependencies | null;\n\treadCoordinatorConfig?: typeof readCoordinatorSyncConfig;\n\tregisterSummaryInvalidator?: (invalidate: () => void) => void;\n}\n\nexport interface LegacyTeamCompletionDependencies {\n\tcreate: typeof coordinatorCreateLegacyTeamCompletionAction;\n\tget?: typeof coordinatorGetLegacyTeamCompletionAction;\n\tlist: typeof coordinatorListLegacyTeamCompletionsAction;\n}\n\nconst defaultCompletionDependencies: LegacyTeamCompletionDependencies = {\n\tcreate: coordinatorCreateLegacyTeamCompletionAction,\n\tget: coordinatorGetLegacyTeamCompletionAction,\n\tlist: coordinatorListLegacyTeamCompletionsAction,\n};\n\ninterface LegacyTeamSnapshotLoaderDependencies {\n\treadConfig: typeof readCoordinatorSyncConfig;\n\tlistGroups: typeof coordinatorListGroupsAction;\n\tlistDevices: typeof coordinatorListDevicesAction;\n}\n\nconst defaultSnapshotLoaderDependencies: LegacyTeamSnapshotLoaderDependencies = {\n\treadConfig: readCoordinatorSyncConfig,\n\tlistGroups: coordinatorListGroupsAction,\n\tlistDevices: coordinatorListDevicesAction,\n};\n\nfunction safeCoordinatorError(): Error {\n\treturn new Error(\"team_setup_roster_unavailable\");\n}\n\nfunction isCoordinatorRosterTooLargeError(error: unknown): boolean {\n\treturn error instanceof Error && error.message === \"coordinator_response_too_large\";\n}\n\nfunction remoteCoordinatorHttpStatus(error: unknown): number | null {\n\tif (!(error instanceof Error)) return null;\n\tconst status = /Remote coordinator request failed \\((\\d{3})\\):/u.exec(error.message)?.[1];\n\treturn status ? Number(status) : null;\n}\n\nfunction isTransientCoordinatorReadError(error: unknown): boolean {\n\tif (!(error instanceof Error)) return false;\n\tconst remoteStatus = remoteCoordinatorHttpStatus(error);\n\tif (remoteStatus) return [408, 429, 500, 502, 503, 504].includes(remoteStatus);\n\treturn (\n\t\terror.name === \"TimeoutError\" ||\n\t\terror.name === \"AbortError\" ||\n\t\t/request_timeout|fetch failed|timed out|timeout/iu.test(error.message)\n\t);\n}\n\nfunction isUnsupportedCompletionQuery(error: unknown): boolean {\n\tconst status = remoteCoordinatorHttpStatus(error);\n\treturn status === 404 || status === 405;\n}\n\n/**\n * Batch completion decoding rejects the whole payload when any one record is\n * malformed or misattributed, so the failure cannot be pinned to a group.\n */\nfunction isUnattributableCompletionBatchError(error: unknown): boolean {\n\treturn (\n\t\terror instanceof Error &&\n\t\t(error.message === \"coordinator_completion_response_malformed\" ||\n\t\t\terror.message === \"coordinator_completion_group_mismatch\")\n\t);\n}\n\nasync function listCompletionRecordsPerGroup(\n\tgroupIds: readonly string[],\n\tlist: (groupIds: string[]) => Promise<CoordinatorLegacyTeamCompletionRecord[]>,\n): Promise<CoordinatorLegacyTeamCompletionRecord[]> {\n\t// A single group re-query would repeat the same undecodable payload.\n\tif (groupIds.length < 2) return [];\n\tconst records: CoordinatorLegacyTeamCompletionRecord[] = [];\n\tfor (const groupId of groupIds) {\n\t\ttry {\n\t\t\trecords.push(...(await list([groupId])));\n\t\t} catch (error) {\n\t\t\tif (!isUnattributableCompletionBatchError(error)) throw error;\n\t\t}\n\t}\n\treturn records;\n}\n\nasync function retryTransientCoordinatorRead<T>(\n\tread: (timeoutS: number) => Promise<T>,\n\tconfiguredTimeoutS: number,\n\tdeadlineMs: number,\n): Promise<T> {\n\tlet lastError: unknown;\n\tfor (let attempt = 0; attempt < 8; attempt += 1) {\n\t\tconst remainingMs = deadlineMs - Date.now();\n\t\tif (remainingMs <= 0) throw lastError ?? safeCoordinatorError();\n\t\ttry {\n\t\t\treturn await read(Math.max(0.1, Math.min(configuredTimeoutS, remainingMs / 1_000)));\n\t\t} catch (error) {\n\t\t\tlastError = error;\n\t\t\tif (!isTransientCoordinatorReadError(error) || attempt === 7) throw error;\n\t\t\tconst delayMs = Math.min(100 * 2 ** attempt, 2_000, deadlineMs - Date.now());\n\t\t\tif (delayMs <= 0) throw error;\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, delayMs));\n\t\t}\n\t}\n\tthrow lastError;\n}\n\nexport function remainingCoordinatorTimeoutS(\n\tconfiguredTimeoutS: number,\n\tdeadlineMs: number,\n\tnowMs = Date.now(),\n): number | null {\n\tconst remainingMs = deadlineMs - nowMs;\n\treturn remainingMs <= 0 ? null : Math.max(0.1, Math.min(configuredTimeoutS, remainingMs / 1_000));\n}\n\nfunction configuredGroupIds(groups: string[]): string[] {\n\tconst unique = [...new Set(groups.map((group) => group.trim()).filter(Boolean))];\n\tif (unique.length > MAX_CONFIGURED_GROUPS) throw safeCoordinatorError();\n\treturn unique;\n}\n\nexport function normalizedCoordinatorId(value: string): string | null {\n\ttry {\n\t\tconst normalized = buildBaseUrl(value);\n\t\tif (!normalized) return null;\n\t\tconst parsed = new URL(normalized);\n\t\tif (\n\t\t\t(parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") ||\n\t\t\t!parsed.host ||\n\t\t\tparsed.username ||\n\t\t\tparsed.password\n\t\t) {\n\t\t\treturn null;\n\t\t}\n\t\tconst path = parsed.pathname === \"/\" ? \"\" : parsed.pathname;\n\t\treturn `${parsed.protocol}//${parsed.host}${path}${parsed.search}`;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function legacyTeamCandidateGroupDescriptors(\n\tstore: MemoryStore | undefined,\n\tcoordinatorUrl: string,\n\tgroups: string[],\n): LegacyTeamCandidateGroupDescriptor[] {\n\tconst configuredIds = configuredGroupIds(groups);\n\tconst configuredCoordinatorId = buildBaseUrl(coordinatorUrl);\n\tconst normalizedConfiguredCoordinatorId = normalizedCoordinatorId(configuredCoordinatorId);\n\tif (!configuredCoordinatorId || !normalizedConfiguredCoordinatorId) throw safeCoordinatorError();\n\tlet scopeBackedDescriptors: LegacyTeamCandidateGroupDescriptor[] = [];\n\tif (store) {\n\t\ttry {\n\t\t\tscopeBackedDescriptors = scopeBackedGroupDescriptors(\n\t\t\t\tstore,\n\t\t\t\tnormalizedConfiguredCoordinatorId,\n\t\t\t\tMAX_CONFIGURED_GROUPS - configuredIds.length,\n\t\t\t\tconfiguredIds,\n\t\t\t);\n\t\t} catch {\n\t\t\t// Scope discovery is additive. Preserve configured coordinator candidates\n\t\t\t// when local evidence cannot be read.\n\t\t\tscopeBackedDescriptors = [];\n\t\t}\n\t}\n\treturn [\n\t\t...configuredIds.map((groupId) => ({ groupId, coordinatorId: configuredCoordinatorId })),\n\t\t...scopeBackedDescriptors,\n\t];\n}\n\nfunction scopeBackedGroupDescriptors(\n\tstore: MemoryStore,\n\tnormalizedConfiguredCoordinatorId: string,\n\tlimit: number,\n\texcludedGroupIds: string[],\n): LegacyTeamCandidateGroupDescriptor[] {\n\tif (limit <= 0) return [];\n\tconst textualCoordinatorIds = store.db\n\t\t.prepare(\n\t\t\t`SELECT DISTINCT coordinator_id FROM replication_scopes\n\t\t\t WHERE status = 'active' AND authority_type = 'coordinator'\n\t\t\t AND kind IN ('team', 'team_default', 'org', 'client')\n\t\t\t AND coordinator_id IS NOT NULL\n\t\t\t AND group_id IS NOT NULL AND TRIM(group_id) <> ''\n\t\t\t ORDER BY coordinator_id LIMIT ?`,\n\t\t)\n\t\t.pluck()\n\t\t.all(MAX_SCOPE_EVIDENCE_COORDINATORS + 1) as string[];\n\tif (textualCoordinatorIds.length > MAX_SCOPE_EVIDENCE_COORDINATORS) {\n\t\treturn [];\n\t}\n\tconst matchingTextualIds = textualCoordinatorIds.filter(\n\t\t(value) => normalizedCoordinatorId(value) === normalizedConfiguredCoordinatorId,\n\t);\n\tif (matchingTextualIds.length === 0) return [];\n\tconst coordinatorPlaceholders = matchingTextualIds.map(() => \"?\").join(\", \");\n\tconst excludedGroupClause =\n\t\texcludedGroupIds.length === 0\n\t\t\t? \"\"\n\t\t\t: `AND TRIM(group_id) NOT IN (${excludedGroupIds.map(() => \"?\").join(\", \")})`;\n\tconst groupIds = store.db\n\t\t.prepare(\n\t\t\t`SELECT DISTINCT TRIM(group_id) AS group_id FROM replication_scopes\n\t\t\t WHERE status = 'active' AND authority_type = 'coordinator'\n\t\t\t AND kind IN ('team', 'team_default', 'org', 'client')\n\t\t\t AND coordinator_id IN (${coordinatorPlaceholders})\n\t\t\t AND group_id IS NOT NULL AND TRIM(group_id) <> ''\n\t\t\t ${excludedGroupClause}\n\t\t\t ORDER BY TRIM(group_id) LIMIT ?`,\n\t\t)\n\t\t.pluck()\n\t\t.all(...matchingTextualIds, ...excludedGroupIds, limit) as string[];\n\tif (groupIds.length === 0) return [];\n\tconst groupPlaceholders = groupIds.map(() => \"?\").join(\", \");\n\tconst records = store.db\n\t\t.prepare(\n\t\t\t`SELECT DISTINCT TRIM(group_id) AS group_id, coordinator_id FROM replication_scopes\n\t\t\t WHERE status = 'active' AND authority_type = 'coordinator'\n\t\t\t AND kind IN ('team', 'team_default', 'org', 'client')\n\t\t\t AND coordinator_id IN (${coordinatorPlaceholders})\n\t\t\t AND TRIM(group_id) IN (${groupPlaceholders})\n\t\t\t ORDER BY TRIM(group_id), coordinator_id`,\n\t\t)\n\t\t.all(...matchingTextualIds, ...groupIds) as Array<{\n\t\tgroup_id: string;\n\t\tcoordinator_id: string;\n\t}>;\n\tconst coordinatorIdsByGroup = new Map<string, string[]>();\n\tfor (const record of records) {\n\t\tconst coordinatorIds = coordinatorIdsByGroup.get(record.group_id) ?? [];\n\t\tcoordinatorIds.push(record.coordinator_id);\n\t\tcoordinatorIdsByGroup.set(record.group_id, coordinatorIds);\n\t}\n\treturn groupIds.flatMap((groupId) => {\n\t\tconst coordinatorIds = coordinatorIdsByGroup.get(groupId) ?? [];\n\t\t// Equivalent textual coordinator IDs still represent distinct persisted\n\t\t// candidate identities. Never merge their authorization evidence by label.\n\t\tconst coordinatorId = coordinatorIds[0];\n\t\treturn coordinatorIds.length === 1 && coordinatorId ? [{ groupId, coordinatorId }] : [];\n\t});\n}\n\nasync function loadConfiguredLegacyTeamGroupSnapshotsWith(\n\tdependencies: LegacyTeamSnapshotLoaderDependencies,\n\toptions: LegacyTeamConfiguredGroupSnapshotLoadOptions = {},\n\tgetStore?: () => MemoryStore,\n): Promise<LegacyTeamConfiguredGroupSnapshot[]> {\n\tlet config: ReturnType<typeof readCoordinatorSyncConfig>;\n\ttry {\n\t\tconfig = dependencies.readConfig();\n\t} catch {\n\t\tthrow safeCoordinatorError();\n\t}\n\tconst hasUrl = Boolean(config.syncCoordinatorUrl);\n\tconst hasSecret = Boolean(config.syncCoordinatorAdminSecret);\n\tif (!hasUrl && !hasSecret && config.syncCoordinatorGroups.length === 0) return [];\n\tif (!hasUrl || !hasSecret) throw safeCoordinatorError();\n\n\ttry {\n\t\tconst configuredCoordinatorId = buildBaseUrl(config.syncCoordinatorUrl);\n\t\tif (!configuredCoordinatorId) throw safeCoordinatorError();\n\t\tconst remoteUrl = configuredCoordinatorId;\n\t\tlet store: MemoryStore | undefined;\n\t\ttry {\n\t\t\tstore = getStore?.();\n\t\t} catch {\n\t\t\t// Scope discovery is additive. Preserve configured coordinator candidates\n\t\t\t// when local evidence cannot be read.\n\t\t\tstore = undefined;\n\t\t}\n\t\tconst groupDescriptors = legacyTeamCandidateGroupDescriptors(\n\t\t\tstore,\n\t\t\tconfig.syncCoordinatorUrl,\n\t\t\tconfig.syncCoordinatorGroups,\n\t\t);\n\t\tif (groupDescriptors.length === 0) throw safeCoordinatorError();\n\t\tconst timeoutS = Math.max(1, config.syncCoordinatorTimeoutS);\n\t\tconst deadlineMs = options.deadlineMs ?? Date.now() + COORDINATOR_ROSTER_READ_BUDGET_MS;\n\t\tconst requestedGroupDescriptors = options.candidateRef\n\t\t\t? groupDescriptors.filter(\n\t\t\t\t\t({ coordinatorId, groupId }) =>\n\t\t\t\t\t\tlegacyTeamCandidateId(coordinatorId, groupId) === options.candidateRef,\n\t\t\t\t)\n\t\t\t: groupDescriptors;\n\t\tconst groups = await retryTransientCoordinatorRead(\n\t\t\t(attemptTimeoutS) =>\n\t\t\t\tdependencies.listGroups({\n\t\t\t\t\tremoteUrl,\n\t\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret,\n\t\t\t\t\tincludeArchived: false,\n\t\t\t\t\ttimeoutS: attemptTimeoutS,\n\t\t\t\t}),\n\t\t\ttimeoutS,\n\t\t\tdeadlineMs,\n\t\t);\n\t\tconst groupById = new Map(groups.map((group) => [group.group_id, group]));\n\t\tconst outcomes = await Promise.all(\n\t\t\trequestedGroupDescriptors.map(async ({ coordinatorId, groupId }) => {\n\t\t\t\t// Authoritative absence is stale state, while malformed or unavailable\n\t\t\t\t// evidence stays fail-closed. Summary mode may isolate the latter only\n\t\t\t\t// when another requested group remains healthy.\n\t\t\t\tconst group = groupById.get(groupId);\n\t\t\t\tif (!group || group.archived_at != null) {\n\t\t\t\t\treturn { kind: \"absent\" as const };\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\tgroup.group_id !== groupId ||\n\t\t\t\t\t(group.display_name !== null && typeof group.display_name !== \"string\")\n\t\t\t\t) {\n\t\t\t\t\tif (options.candidateRef) throw safeCoordinatorError();\n\t\t\t\t\treturn { kind: \"unavailable\" as const };\n\t\t\t\t}\n\t\t\t\tlet devices: Awaited<ReturnType<typeof coordinatorListDevicesAction>>;\n\t\t\t\ttry {\n\t\t\t\t\tdevices = await retryTransientCoordinatorRead(\n\t\t\t\t\t\t(attemptTimeoutS) =>\n\t\t\t\t\t\t\tdependencies.listDevices({\n\t\t\t\t\t\t\t\tgroupId,\n\t\t\t\t\t\t\t\tincludeDisabled: true,\n\t\t\t\t\t\t\t\tremoteUrl,\n\t\t\t\t\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret,\n\t\t\t\t\t\t\t\ttimeoutS: attemptTimeoutS,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\ttimeoutS,\n\t\t\t\t\t\tdeadlineMs,\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!options.candidateRef) return { kind: \"unavailable\" as const };\n\t\t\t\t\tif (isCoordinatorRosterTooLargeError(error)) {\n\t\t\t\t\t\tthrow new Error(\"legacy_team_setup_roster_too_large\");\n\t\t\t\t\t}\n\t\t\t\t\tthrow safeCoordinatorError();\n\t\t\t\t}\n\t\t\t\tif (devices.length > MAX_DEVICES) {\n\t\t\t\t\tif (options.candidateRef) throw new Error(\"legacy_team_setup_roster_too_large\");\n\t\t\t\t\treturn { kind: \"unavailable\" as const };\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\tdevices.some(\n\t\t\t\t\t\t(device) =>\n\t\t\t\t\t\t\tfingerprintPublicKey(device.public_key) !== device.fingerprint ||\n\t\t\t\t\t\t\t(device.enabled !== 0 && device.enabled !== 1),\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\tif (options.candidateRef) throw safeCoordinatorError();\n\t\t\t\t\treturn { kind: \"unavailable\" as const };\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"snapshot\" as const,\n\t\t\t\t\tsnapshot: {\n\t\t\t\t\t\tcoordinatorId,\n\t\t\t\t\t\tgroupId,\n\t\t\t\t\t\tdisplayName: group.display_name ?? \"Legacy Team\",\n\t\t\t\t\t\tdevices: devices.map((device) => ({\n\t\t\t\t\t\t\tdeviceId: device.device_id,\n\t\t\t\t\t\t\tfingerprint: device.fingerprint,\n\t\t\t\t\t\t\tdisplayName: device.display_name ?? \"Device\",\n\t\t\t\t\t\t\tenabled: device.enabled === 1,\n\t\t\t\t\t\t\tlabelRedactionIds: [device.identity_id ?? \"\", device.public_key].filter(Boolean),\n\t\t\t\t\t\t})),\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}),\n\t\t);\n\t\tconst validSnapshots = outcomes.flatMap((outcome) =>\n\t\t\toutcome.kind === \"snapshot\" ? [outcome.snapshot] : [],\n\t\t);\n\t\tif (validSnapshots.length === 0 && outcomes.some((outcome) => outcome.kind === \"unavailable\")) {\n\t\t\tthrow safeCoordinatorError();\n\t\t}\n\t\treturn validSnapshots;\n\t} catch (error) {\n\t\tif (error instanceof Error && error.message === \"legacy_team_setup_roster_too_large\") {\n\t\t\tthrow error;\n\t\t}\n\t\tthrow safeCoordinatorError();\n\t}\n}\n\nfunction requireBoundedSnapshots(groups: LegacyTeamConfiguredGroupSnapshot[]): void {\n\tif (groups.length > MAX_CONFIGURED_GROUPS) {\n\t\tthrow new Error(\"legacy_team_setup_roster_too_large\");\n\t}\n}\n\nfunction projectionOptions(store: MemoryStore) {\n\treturn { localActorId: store.actorId, localDeviceId: store.deviceId };\n}\n\nfunction discoverCandidates(\n\tstore: MemoryStore,\n\tgroups: LegacyTeamConfiguredGroupSnapshot[],\n): LegacyTeamCandidateView[] {\n\trequireBoundedSnapshots(groups);\n\treturn discoverLegacyTeamCandidates(store.db, {\n\t\tprojection: projectionOptions(store),\n\t\tgroups,\n\t});\n}\n\nfunction candidateSummary(candidate: LegacyTeamCandidateView): LegacyTeamSetupCandidateSummaryV1 {\n\treturn {\n\t\tcandidateRef: candidate.candidateRef,\n\t\tdisplayName: candidate.displayName,\n\t\tstatus: candidate.status,\n\t\tdeviceCount: candidate.deviceCount,\n\t\tprojectCount: candidate.projectCount,\n\t\tunresolvedDeviceCount: candidate.unresolvedDeviceCount,\n\t\tunresolvedProjectCount: candidate.unresolvedProjectCount,\n\t};\n}\n\nfunction candidateSummaryForDraft(\n\tcandidate: LegacyTeamCandidateView,\n\tdraft: LegacyTeamSetupDraftView,\n): LegacyTeamSetupCandidateSummaryV1 {\n\treturn {\n\t\t...candidateSummary(candidate),\n\t\tstatus: draft.state === \"completed\" ? \"ready\" : draft.state,\n\t\tunresolvedDeviceCount: draft.unresolvedDeviceCount,\n\t\tunresolvedProjectCount: draft.unresolvedProjectCount,\n\t};\n}\n\nfunction candidateFromDraft(draft: LegacyTeamSetupDraftView): LegacyTeamCandidateView {\n\treturn {\n\t\tcandidateRef: draft.candidateRef,\n\t\tdisplayName: draft.displayName,\n\t\tstatus: draft.state === \"completed\" ? \"ready\" : draft.state,\n\t\tdeviceCount: draft.devices.length,\n\t\tprojectCount: draft.projects.length,\n\t\tunresolvedDeviceCount: draft.unresolvedDeviceCount,\n\t\tunresolvedProjectCount: draft.unresolvedProjectCount,\n\t};\n}\n\nfunction readPureCandidateViews(\n\tstore: MemoryStore,\n\tgroups: LegacyTeamConfiguredGroupSnapshot[],\n): LegacyTeamCandidateView[] {\n\tconst existing: LegacyTeamCandidateView[] = [];\n\tconst discoverable: LegacyTeamConfiguredGroupSnapshot[] = [];\n\tfor (const group of groups) {\n\t\tconst candidateRef = legacyTeamCandidateId(group.coordinatorId, group.groupId);\n\t\tconst draft = getLegacyTeamSetupDraft(store.db, candidateRef);\n\t\tif (hasCompletedLegacyTeamSetup(store, candidateRef)) {\n\t\t\t// Only canonical terminal completions pass through discovery: they can\n\t\t\t// reconcile missing setup recipient edges while preserving newer drafts.\n\t\t\tif (isLegacyTeamCandidateSelectable(store.db, candidateRef)) discoverable.push(group);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!draft || draft.state === \"completed\") {\n\t\t\tdiscoverable.push(group);\n\t\t\tcontinue;\n\t\t}\n\t\texisting.push(candidateFromDraft(draft));\n\t}\n\treturn [...existing, ...discoverCandidates(store, discoverable)]\n\t\t.filter((candidate) => !hasCompletedLegacyTeamSetup(store, candidate.candidateRef))\n\t\t.toSorted((left, right) =>\n\t\t\tleft.candidateRef < right.candidateRef ? -1 : left.candidateRef > right.candidateRef ? 1 : 0,\n\t\t);\n}\n\nfunction hasCompletedLegacyTeamSetup(store: MemoryStore, candidateRef: string): boolean {\n\treturn Boolean(\n\t\tstore.db\n\t\t\t.prepare(\n\t\t\t\t`SELECT 1 FROM policy_teams\n\t\t\t\t WHERE team_id = ? AND status = 'active'\n\t\t\t\t AND provenance = 'reviewed_team_candidate'\n\t\t\t\t AND migration_state = 'completed' LIMIT 1`,\n\t\t\t)\n\t\t\t.pluck()\n\t\t\t.get(deterministicPolicyTeamId(candidateRef)),\n\t);\n}\n\nfunction identityRef(candidateRef: string, identityId: string | null): string | null {\n\treturn identityId\n\t\t? recipientPolicyDigest(\"legacy-team-viewer-identity-ref-v1\", [candidateRef, identityId])\n\t\t: null;\n}\n\nfunction requiredIdentityRef(candidateRef: string, identityId: string): string {\n\treturn recipientPolicyDigest(\"legacy-team-viewer-identity-ref-v1\", [candidateRef, identityId]);\n}\n\nfunction teamRef(candidateRef: string, teamId: string): string {\n\treturn recipientPolicyDigest(\"legacy-team-viewer-team-ref-v1\", [candidateRef, teamId]);\n}\n\nfunction resolvedProjectRef(projectRef: string, projectIdentity: string | null): string | null {\n\treturn projectIdentity ? legacyTeamResolvedProjectRef(projectRef, projectIdentity) : null;\n}\n\nfunction viewerSafeAccessDelta(\n\tcandidateRef: string,\n\tdelta: LegacyTeamSetupAccessDeltaV1,\n\tlabels?: {\n\t\tteamDisplayName: string;\n\t\tdevices: Array<Omit<LegacyTeamSetupDeviceV1, \"actions\">>;\n\t\tprojects: Array<Omit<LegacyTeamSetupProjectV1, \"actions\">>;\n\t\tidentityChoices: LegacyTeamSetupIdentityChoiceV1[];\n\t},\n): LegacyTeamSetupViewerAccessDeltaV1 {\n\tconst fallbackLabels = new Map<string, string>();\n\tconst fallbackLabelCounts = new Map<string, number>();\n\tconst reservedLabels = new Set(\n\t\t[\n\t\t\tlabels?.teamDisplayName,\n\t\t\t...(labels?.devices.map((device) => device.displayName) ?? []),\n\t\t\t...(labels?.projects.flatMap((project) => [\n\t\t\t\tproject.displayName,\n\t\t\t\t...project.mappingChoices.map((choice) => choice.displayName),\n\t\t\t]) ?? []),\n\t\t\t...(labels?.identityChoices.map((identity) => identity.displayName) ?? []),\n\t\t]\n\t\t\t.filter((label): label is string => Boolean(label))\n\t\t\t.map((label) => normalizeChoiceLabelText(label).toLowerCase()),\n\t);\n\tconst fallbackLabel = (kind: string, ref: string) => {\n\t\tconst key = `${kind}:${ref}`;\n\t\tconst existing = fallbackLabels.get(key);\n\t\tif (existing) return existing;\n\t\tlet index = (fallbackLabelCounts.get(kind) ?? 0) + 1;\n\t\tlet label = `${kind} outside this setup (${index})`;\n\t\twhile (reservedLabels.has(normalizeChoiceLabelText(label).toLowerCase())) {\n\t\t\tindex += 1;\n\t\t\tlabel = `${kind} outside this setup (${index})`;\n\t\t}\n\t\tfallbackLabelCounts.set(kind, index);\n\t\treservedLabels.add(normalizeChoiceLabelText(label).toLowerCase());\n\t\tfallbackLabels.set(key, label);\n\t\treturn label;\n\t};\n\tconst projectsByRef = new Map(labels?.projects.map((project) => [project.projectRef, project]));\n\tconst projectsByCanonicalRef = new Map(\n\t\tlabels?.projects.flatMap((project) =>\n\t\t\tproject.canonicalProjectRef ? [[project.canonicalProjectRef, project] as const] : [],\n\t\t),\n\t);\n\tconst identitiesByRef = new Map(\n\t\tlabels?.identityChoices.map((identity) => [identity.identityRef, identity]),\n\t);\n\tconst devicesByRef = new Map(labels?.devices.map((device) => [device.deviceRef, device]));\n\tconst canonicalProjectPresentation = (identity: string, ref: string) => {\n\t\tif (identity === \"shared:default\") {\n\t\t\treturn { displayName: \"Legacy default sharing\", kind: \"legacy_default_sharing\" as const };\n\t\t}\n\t\treturn {\n\t\t\tdisplayName: projectsByCanonicalRef.get(ref)?.displayName ?? fallbackLabel(\"Project\", ref),\n\t\t\tkind: \"project\" as const,\n\t\t};\n\t};\n\tconst resolvedDisplayName = (projectRef: string, ref: string | null): string | null => {\n\t\tif (!ref) return null;\n\t\tconst project = projectsByRef.get(projectRef);\n\t\tconst choice = project?.mappingChoices.find((item) => item.resolvedProjectRef === ref);\n\t\tif (choice) return choice.displayName;\n\t\tif (project?.resolvedProjectRef === ref && project.resolution === \"deterministic\") {\n\t\t\treturn `${project.displayName} (automatic match)`;\n\t\t}\n\t\treturn fallbackLabel(\"Project\", ref);\n\t};\n\treturn {\n\t\tteamChanges: delta.teamChanges.map((change) => ({\n\t\t\tteamRef: teamRef(candidateRef, change.teamId),\n\t\t\tteamDisplayName:\n\t\t\t\tlabels?.teamDisplayName ?? fallbackLabel(\"Team\", teamRef(candidateRef, change.teamId)),\n\t\t\tchange: change.change,\n\t\t\tfromDeviceEligibilityMode: change.fromDeviceEligibilityMode,\n\t\t\ttoDeviceEligibilityMode: change.toDeviceEligibilityMode,\n\t\t})),\n\t\tmembershipChanges: delta.membershipChanges.map((change) => {\n\t\t\tconst identityRef = requiredIdentityRef(candidateRef, change.identityId);\n\t\t\tconst membershipTeamRef = teamRef(candidateRef, change.teamId);\n\t\t\treturn {\n\t\t\t\tteamRef: membershipTeamRef,\n\t\t\t\tteamDisplayName: labels?.teamDisplayName ?? fallbackLabel(\"Team\", membershipTeamRef),\n\t\t\t\tidentityRef,\n\t\t\t\tidentityDisplayName:\n\t\t\t\t\tidentitiesByRef.get(identityRef)?.displayName ?? fallbackLabel(\"Person\", identityRef),\n\t\t\t\tchange: change.change,\n\t\t\t};\n\t\t}),\n\t\tprojectChanges: delta.projectChanges.map((change) => {\n\t\t\tconst fromRef = resolvedProjectRef(change.projectRef, change.fromProjectIdentity);\n\t\t\tconst toRef = resolvedProjectRef(change.projectRef, change.toProjectIdentity);\n\t\t\treturn {\n\t\t\t\tprojectRef: change.projectRef,\n\t\t\t\tprojectDisplayName:\n\t\t\t\t\tprojectsByRef.get(change.projectRef)?.displayName ??\n\t\t\t\t\tfallbackLabel(\"Project\", change.projectRef),\n\t\t\t\tfromCanonicalProjectRef: change.fromProjectIdentity\n\t\t\t\t\t? legacyTeamCanonicalProjectRef(candidateRef, change.fromProjectIdentity)\n\t\t\t\t\t: null,\n\t\t\t\tfromResolvedProjectRef: fromRef,\n\t\t\t\tfromResolvedProjectDisplayName: resolvedDisplayName(change.projectRef, fromRef),\n\t\t\t\ttoCanonicalProjectRef: change.toProjectIdentity\n\t\t\t\t\t? legacyTeamCanonicalProjectRef(candidateRef, change.toProjectIdentity)\n\t\t\t\t\t: null,\n\t\t\t\ttoResolvedProjectRef: toRef,\n\t\t\t\ttoResolvedProjectDisplayName: resolvedDisplayName(change.projectRef, toRef),\n\t\t\t\tchange: change.change,\n\t\t\t};\n\t\t}),\n\t\trecipientChanges: delta.recipientChanges.map((change) => {\n\t\t\tconst canonicalProjectRef = legacyTeamCanonicalProjectRef(\n\t\t\t\tcandidateRef,\n\t\t\t\tchange.canonicalProjectIdentity,\n\t\t\t);\n\t\t\tconst recipientRef = teamRef(candidateRef, change.recipientId);\n\t\t\tconst projectPresentation = canonicalProjectPresentation(\n\t\t\t\tchange.canonicalProjectIdentity,\n\t\t\t\tcanonicalProjectRef,\n\t\t\t);\n\t\t\treturn {\n\t\t\t\tcanonicalProjectRef,\n\t\t\t\tcanonicalProjectDisplayName: projectPresentation.displayName,\n\t\t\t\tcanonicalProjectKind: projectPresentation.kind,\n\t\t\t\trecipientKind: change.recipientKind,\n\t\t\t\trecipientRef,\n\t\t\t\trecipientDisplayName: labels?.teamDisplayName ?? fallbackLabel(\"Team\", recipientRef),\n\t\t\t\tchange: change.change,\n\t\t\t};\n\t\t}),\n\t\tdeviceAccessChanges: delta.deviceAccessChanges.map((change) => {\n\t\t\tconst canonicalProjectRef = legacyTeamCanonicalProjectRef(\n\t\t\t\tcandidateRef,\n\t\t\t\tchange.canonicalProjectIdentity,\n\t\t\t);\n\t\t\tconst deviceRef = legacyTeamDeviceRef(candidateRef, change.deviceId);\n\t\t\tconst projectPresentation = canonicalProjectPresentation(\n\t\t\t\tchange.canonicalProjectIdentity,\n\t\t\t\tcanonicalProjectRef,\n\t\t\t);\n\t\t\treturn {\n\t\t\t\tcanonicalProjectRef,\n\t\t\t\tcanonicalProjectDisplayName: projectPresentation.displayName,\n\t\t\t\tcanonicalProjectKind: projectPresentation.kind,\n\t\t\t\tdeviceRef,\n\t\t\t\tdeviceDisplayName:\n\t\t\t\t\tdevicesByRef.get(deviceRef)?.displayName ?? fallbackLabel(\"Device\", deviceRef),\n\t\t\t\tchange: change.change,\n\t\t\t};\n\t\t}),\n\t};\n}\n\nfunction viewerAccessDeltaDigest(delta: LegacyTeamSetupViewerAccessDeltaV1): string {\n\treturn recipientPolicyDigest(\"legacy-team-viewer-access-delta-v1\", delta);\n}\n\nconst SAFE_CHOICE_LABEL_PATTERN = /^[\\p{L}\\p{N} '&,.()_-]*$/u;\n\n// Keep this byte-for-byte equivalent in behavior to the core setup-label\n// normalization without exporting a presentation-only core implementation.\nfunction normalizeChoiceLabelText(value: string): string {\n\treturn value\n\t\t.normalize(\"NFKC\")\n\t\t.replace(/\\p{Cf}/gu, \"\")\n\t\t.replace(/\\p{Cc}/gu, \" \")\n\t\t.replace(/\\s+/gu, \" \")\n\t\t.trim();\n}\n\nfunction safeChoiceLabel(\n\tvalue: string,\n\tfallback: string,\n\tforbiddenIds: readonly string[],\n\topaqueRef?: string,\n): string {\n\tconst normalized = normalizeChoiceLabelText(value.slice(0, 512));\n\tconst label = normalized.slice(0, 120).trim();\n\tconst forbiddenComparisons = forbiddenIds\n\t\t.map((forbiddenId) => normalizeChoiceLabelText(forbiddenId).toLowerCase())\n\t\t.filter(Boolean);\n\tconst comparable = normalized.toLowerCase();\n\tif (\n\t\t!label ||\n\t\t!SAFE_CHOICE_LABEL_PATTERN.test(label) ||\n\t\t/[\\p{L}\\p{N}]\\.[\\p{L}\\p{N}]/u.test(label) ||\n\t\t/-----|\\b(?:ssh|ecdsa|sk)-[\\p{L}\\p{N}-]+ /iu.test(label) ||\n\t\tforbiddenComparisons.some((forbiddenComparison) => comparable.includes(forbiddenComparison))\n\t) {\n\t\tconst suffix = opaqueRef?.slice(-6);\n\t\treturn suffix ? `${fallback} ${suffix}` : fallback;\n\t}\n\treturn label;\n}\n\nfunction disambiguateChoiceLabels<T extends { displayName: string }>(\n\tchoices: readonly T[],\n\tchoiceRef: (choice: T) => string,\n): T[] {\n\tconst counts = new Map<string, number>();\n\tconst originalLabels = new Set<string>();\n\tfor (const choice of choices) {\n\t\tconst comparable = normalizeChoiceLabelText(choice.displayName).toLowerCase();\n\t\tcounts.set(comparable, (counts.get(comparable) ?? 0) + 1);\n\t\toriginalLabels.add(comparable);\n\t}\n\tconst usedLabels = new Set<string>();\n\treturn choices.map((choice, index) => {\n\t\tconst comparable = normalizeChoiceLabelText(choice.displayName).toLowerCase();\n\t\tif ((counts.get(comparable) ?? 0) < 2 && !usedLabels.has(comparable)) {\n\t\t\tusedLabels.add(comparable);\n\t\t\treturn choice;\n\t\t}\n\t\tconst ref = choiceRef(choice);\n\t\tlet suffixLength = Math.min(6, ref.length);\n\t\tlet suffix = ref.slice(-suffixLength);\n\t\tconst maxAttempts = ref.length + originalLabels.size + usedLabels.size + 2;\n\t\tfor (let attempt = 0; attempt < maxAttempts; attempt += 1) {\n\t\t\tconst baseLength = Math.max(0, 119 - suffix.length);\n\t\t\tconst base = choice.displayName.slice(0, baseLength).trimEnd();\n\t\t\tconst displayName = base ? `${base} ${suffix}` : suffix.slice(-120);\n\t\t\tconst finalComparable = normalizeChoiceLabelText(displayName).toLowerCase();\n\t\t\tif (!usedLabels.has(finalComparable) && !originalLabels.has(finalComparable)) {\n\t\t\t\tusedLabels.add(finalComparable);\n\t\t\t\treturn { ...choice, displayName };\n\t\t\t}\n\t\t\tif (suffixLength < ref.length) {\n\t\t\t\tsuffixLength = Math.min(ref.length, suffixLength + 2);\n\t\t\t\tsuffix = ref.slice(-suffixLength);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tsuffix = `${ref.slice(-Math.min(96, ref.length))}-${index + 1}-${attempt + 1}`;\n\t\t}\n\t\tthrow new Error(\"legacy_team_setup_roster_too_large\");\n\t});\n}\n\nfunction requireCompleteMappingChoices(projectCount: number, choiceCount: number): void {\n\tif (projectCount * choiceCount > MAX_TOTAL_PROJECT_MAPPING_CHOICES) {\n\t\tthrow new Error(\"legacy_team_setup_roster_too_large\");\n\t}\n}\n\nfunction createCachedSnapshotLoader(\n\tload: () => Promise<LegacyTeamConfiguredGroupSnapshot[]>,\n\tttlMs: number,\n\tnow: () => number = Date.now,\n): (() => Promise<LegacyTeamConfiguredGroupSnapshot[]>) & {\n\tinvalidate: () => void;\n\tpeek: () => LegacyTeamConfiguredGroupSnapshot[] | null;\n} {\n\tlet cached: { expiresAt: number; snapshots: LegacyTeamConfiguredGroupSnapshot[] } | null = null;\n\tlet inFlight: Promise<LegacyTeamConfiguredGroupSnapshot[]> | null = null;\n\tlet generation = 0;\n\tconst cachedLoad = () => {\n\t\tif (cached && now() < cached.expiresAt) return Promise.resolve(cached.snapshots);\n\t\tif (inFlight) return inFlight;\n\t\tconst operationGeneration = generation;\n\t\tlet operation: Promise<LegacyTeamConfiguredGroupSnapshot[]>;\n\t\toperation = load()\n\t\t\t.then((snapshots) => {\n\t\t\t\tif (generation !== operationGeneration) return cachedLoad();\n\t\t\t\tcached = { expiresAt: now() + ttlMs, snapshots };\n\t\t\t\treturn snapshots;\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\tif (inFlight === operation) inFlight = null;\n\t\t\t});\n\t\tinFlight = operation;\n\t\treturn operation;\n\t};\n\tcachedLoad.invalidate = () => {\n\t\tgeneration += 1;\n\t\tcached = null;\n\t\tinFlight = null;\n\t};\n\tcachedLoad.peek = () => (cached && now() < cached.expiresAt ? cached.snapshots : null);\n\treturn cachedLoad;\n}\n\nasync function loadMutableCandidateSnapshots(\n\tstore: MemoryStore,\n\tcandidateRef: string,\n\tload: () => Promise<LegacyTeamConfiguredGroupSnapshot[]>,\n): Promise<LegacyTeamConfiguredGroupSnapshot[]> {\n\tif (getLegacyTeamSetupDraft(store.db, candidateRef)?.state === \"completed\") {\n\t\tthrow new Error(\"team_setup_confirmation_stale\");\n\t}\n\treturn load();\n}\n\nfunction projectMutationAtomically<Mutation, Projection>(\n\tstore: MemoryStore,\n\tmutate: () => Mutation,\n\tproject: (mutation: Mutation) => Projection,\n): Projection {\n\treturn store.db.transaction(() => project(mutate())).immediate();\n}\n\nexport const __teamSetupTestHooks = {\n\tcreateCachedSnapshotLoader,\n\tloadConfiguredLegacyTeamGroupSnapshotsWith,\n\tnormalizedCoordinatorId,\n\tprojectMutationAtomically,\n\trequireBoundedAccessDelta: requireLegacyTeamSetupAccessDeltaWithinLimit,\n\trequireCompleteMappingChoices,\n\tdisambiguateChoiceLabels,\n\tsafeChoiceLabel,\n\tviewerSafeAccessDelta,\n};\n\ninterface IdentityChoiceInternal extends LegacyTeamSetupIdentityChoiceV1 {\n\tidentityId: string;\n}\n\ntype IdentityChoiceRow = { actor_id: string; display_name: string };\n\nfunction identityChoicesFromRows(\n\trows: IdentityChoiceRow[],\n\tcandidateRef: string,\n\tmaxChoices = MAX_IDENTITY_CHOICES,\n): IdentityChoiceInternal[] {\n\tif (rows.length > maxChoices) {\n\t\tthrow new Error(\"legacy_team_setup_roster_too_large\");\n\t}\n\tconst actorIds = rows.map((row) => row.actor_id);\n\treturn disambiguateChoiceLabels(\n\t\trows.map((row) => {\n\t\t\tconst opaqueIdentityRef = requiredIdentityRef(candidateRef, row.actor_id);\n\t\t\treturn {\n\t\t\t\tidentityId: row.actor_id,\n\t\t\t\tidentityRef: opaqueIdentityRef,\n\t\t\t\tdisplayName: safeChoiceLabel(row.display_name, \"Person\", actorIds, opaqueIdentityRef),\n\t\t\t};\n\t\t}),\n\t\t(choice) => choice.identityRef,\n\t);\n}\n\nfunction identityChoices(store: MemoryStore, candidateRef: string): IdentityChoiceInternal[] {\n\tconst rows = store.db\n\t\t.prepare(\n\t\t\t`SELECT actor_id, display_name FROM actors\n\t\t\t WHERE status = 'active' AND merged_into_actor_id IS NULL\n\t\t\t ORDER BY display_name, actor_id LIMIT ?`,\n\t\t)\n\t\t.all(MAX_IDENTITY_CHOICES + 1) as IdentityChoiceRow[];\n\treturn identityChoicesFromRows(rows, candidateRef);\n}\n\nfunction completedDraftIdentityChoices(\n\tstore: MemoryStore,\n\tdraft: LegacyTeamSetupDraftView,\n): IdentityChoiceInternal[] {\n\tconst actorIds = [\n\t\t...new Set(\n\t\t\tdraft.devices.flatMap((device) => [\n\t\t\t\tdevice.existingIdentityId,\n\t\t\t\tdevice.suggestedIdentityId,\n\t\t\t\tdevice.targetIdentityId,\n\t\t\t\tdevice.expectation.kind === \"existing\" ? device.expectation.identityId : null,\n\t\t\t]),\n\t\t),\n\t].filter((actorId): actorId is string => actorId !== null);\n\tif (actorIds.length === 0) return [];\n\tconst placeholders = actorIds.map(() => \"?\").join(\", \");\n\tconst rows = store.db\n\t\t.prepare(\n\t\t\t`SELECT actor_id, display_name FROM actors\n\t\t\t WHERE status = 'active' AND merged_into_actor_id IS NULL\n\t\t\t AND actor_id IN (${placeholders})\n\t\t\t ORDER BY display_name, actor_id`,\n\t\t)\n\t\t.all(...actorIds) as IdentityChoiceRow[];\n\treturn identityChoicesFromRows(rows, draft.candidateRef, MAX_COMPLETED_IDENTITY_CHOICES);\n}\n\ninterface ProjectMappingChoiceInternal {\n\tprojectIdentity: string;\n\tsourceDisplayName: string;\n}\n\nfunction projectMappingChoices(store: MemoryStore): ProjectMappingChoiceInternal[] {\n\tlet candidates: ReturnType<typeof listProjectScopeCandidates>;\n\ttry {\n\t\tcandidates = listProjectScopeCandidates(store.db, {\n\t\t\tlimit: null,\n\t\t\tmaxScannedRows: MAX_PROJECT_MAPPING_SCAN_ROWS,\n\t\t\tmaxMetadataRows: MAX_PROJECT_MAPPING_METADATA_ROWS,\n\t\t\texcludePeerReceived: true,\n\t\t}).filter(\n\t\t\t(candidate) =>\n\t\t\t\t!candidate.read_only &&\n\t\t\t\tisLegacyTeamSetupProjectMappingIdentity(candidate.workspace_identity, store.db),\n\t\t);\n\t} catch (error) {\n\t\tif (\n\t\t\terror instanceof Error &&\n\t\t\t(error.message === \"project_scope_candidate_scan_too_large\" ||\n\t\t\t\terror.message === \"project_scope_candidate_metadata_too_large\")\n\t\t) {\n\t\t\tthrow new Error(\"legacy_team_setup_roster_too_large\");\n\t\t}\n\t\tthrow error;\n\t}\n\tif (candidates.length > MAX_PROJECT_MAPPING_CHOICES) {\n\t\tthrow new Error(\"legacy_team_setup_roster_too_large\");\n\t}\n\treturn candidates.map((candidate) => ({\n\t\tprojectIdentity: candidate.workspace_identity,\n\t\tsourceDisplayName: candidate.display_project,\n\t}));\n}\n\ninterface ViewerSafeDraft {\n\tdevices: Array<Omit<LegacyTeamSetupDeviceV1, \"actions\">>;\n\tprojects: Array<Omit<LegacyTeamSetupProjectV1, \"actions\">>;\n\tidentityChoices: LegacyTeamSetupIdentityChoiceV1[];\n}\n\nfunction viewerSafeDraft(store: MemoryStore, draft: LegacyTeamSetupDraftView): ViewerSafeDraft {\n\tif (draft.devices.length > MAX_DEVICES || draft.projects.length > MAX_PROJECTS) {\n\t\tthrow new Error(\"legacy_team_setup_roster_too_large\");\n\t}\n\tconst completed = draft.state === \"completed\";\n\tconst identities = completed\n\t\t? completedDraftIdentityChoices(store, draft)\n\t\t: identityChoices(store, draft.candidateRef);\n\tconst mappableProjectCount = completed\n\t\t? 0\n\t\t: draft.projects.filter((project) => project.resolution !== \"deterministic\").length;\n\tconst mappingChoices = mappableProjectCount === 0 ? [] : projectMappingChoices(store);\n\trequireCompleteMappingChoices(mappableProjectCount, mappingChoices.length);\n\tconst mappingChoiceIdentities = mappingChoices.map((choice) => choice.projectIdentity);\n\treturn {\n\t\tdevices: draft.devices.map((device) => ({\n\t\t\tdeviceRef: device.deviceRef,\n\t\t\tdisplayName: device.displayName,\n\t\t\tenabled: device.enabled,\n\t\t\texistingIdentityRef: identityRef(draft.candidateRef, device.existingIdentityId),\n\t\t\tsuggestedIdentityRef: identityRef(draft.candidateRef, device.suggestedIdentityId),\n\t\t\tverifiedEvidenceKind: device.verifiedEvidenceKind,\n\t\t\tdecision: device.decision,\n\t\t\ttargetIdentityRef: identityRef(draft.candidateRef, device.targetIdentityId),\n\t\t\texpectation:\n\t\t\t\tdevice.expectation.kind === \"existing\"\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tkind: \"existing\" as const,\n\t\t\t\t\t\t\tassignmentVersion: device.expectation.assignmentVersion,\n\t\t\t\t\t\t\tidentityRef: requiredIdentityRef(draft.candidateRef, device.expectation.identityId),\n\t\t\t\t\t\t}\n\t\t\t\t\t: { kind: \"absent\" as const },\n\t\t})),\n\t\tprojects: draft.projects.map((project) => ({\n\t\t\tprojectRef: project.projectRef,\n\t\t\tdisplayName: project.displayName,\n\t\t\tresolution: project.resolution,\n\t\t\tcanonicalProjectRef: project.canonicalProjectRef,\n\t\t\tresolvedProjectRef: project.resolvedProjectRef,\n\t\t\tmappingChoices:\n\t\t\t\tproject.resolution === \"deterministic\"\n\t\t\t\t\t? []\n\t\t\t\t\t: disambiguateChoiceLabels(\n\t\t\t\t\t\t\tmappingChoices.map((choice) => {\n\t\t\t\t\t\t\t\tconst opaqueResolvedProjectRef = legacyTeamResolvedProjectRef(\n\t\t\t\t\t\t\t\t\tproject.projectRef,\n\t\t\t\t\t\t\t\t\tchoice.projectIdentity,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\tresolvedProjectRef: opaqueResolvedProjectRef,\n\t\t\t\t\t\t\t\t\tdisplayName: safeChoiceLabel(\n\t\t\t\t\t\t\t\t\t\tchoice.sourceDisplayName,\n\t\t\t\t\t\t\t\t\t\t\"Project\",\n\t\t\t\t\t\t\t\t\t\tmappingChoiceIdentities,\n\t\t\t\t\t\t\t\t\t\topaqueResolvedProjectRef,\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t(choice) => choice.resolvedProjectRef,\n\t\t\t\t\t\t),\n\t\t})),\n\t\tidentityChoices: identities.map(({ identityRef, displayName }) => ({\n\t\t\tidentityRef,\n\t\t\tdisplayName,\n\t\t})),\n\t};\n}\n\nfunction viewerSafePreview(\n\tdraft: LegacyTeamSetupDraftView,\n\tsafeDraft: ViewerSafeDraft,\n\tpreview: ReturnType<typeof inspectLegacyTeamSetupActivation>,\n) {\n\tconst accessDelta = viewerSafeAccessDelta(draft.candidateRef, preview.accessDelta, {\n\t\tteamDisplayName: draft.displayName,\n\t\t...safeDraft,\n\t});\n\treturn {\n\t\tfinishDigest: preview.finishDigest,\n\t\taccessDeltaDigest: preview.accessDeltaDigest,\n\t\tviewerAccessDeltaDigest: viewerAccessDeltaDigest(accessDelta),\n\t\taccessDelta,\n\t};\n}\n\nfunction errorStatus(code: LegacyTeamSetupActivationErrorCode): 400 | 409 | 503 {\n\tif (code === \"team_setup_roster_unavailable\" || code === \"team_setup_completion_unavailable\")\n\t\treturn 503;\n\tif (code === \"team_setup_failed\") return 503;\n\tif (code === \"team_setup_incomplete\") return 400;\n\treturn 409;\n}\n\nfunction apiErrorCode(error: unknown): LegacyTeamSetupActivationErrorCode {\n\tconst code = legacyTeamSetupApiErrorCode(error);\n\treturn code === \"team_setup_projection_changed\" ? \"team_setup_conflict\" : code;\n}\n\nfunction completionApiError(error: unknown): LegacyTeamSetupActivationErrorCode {\n\tconst code = legacyTeamSetupApiErrorCode(error);\n\treturn code === \"team_setup_failed\" ? \"team_setup_completion_unavailable\" : code;\n}\n\ntype BoundedJsonResult = { ok: true; value: Record<string, unknown> } | { ok: false };\n\nasync function parseBoundedJsonObject(c: Context): Promise<BoundedJsonResult> {\n\tconst contentType = c.req.header(\"content-type\")?.split(\";\", 1)[0]?.trim().toLowerCase();\n\tif (contentType !== \"application/json\") return { ok: false };\n\tconst lengthHeader = c.req.header(\"content-length\");\n\tif (lengthHeader != null && !/^\\d+$/u.test(lengthHeader.trim())) return { ok: false };\n\tconst contentLength = lengthHeader == null ? null : Number(lengthHeader);\n\tif (contentLength != null && contentLength > MAX_MUTATION_BODY_BYTES) return { ok: false };\n\tconst body = c.req.raw.body;\n\tif (!body) return { ok: false };\n\tconst reader = body.getReader();\n\tconst chunks: Uint8Array[] = [];\n\tlet total = 0;\n\ttry {\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) break;\n\t\t\tif (!value) continue;\n\t\t\ttotal += value.byteLength;\n\t\t\tif (total > MAX_MUTATION_BODY_BYTES) {\n\t\t\t\tawait reader.cancel().catch(() => undefined);\n\t\t\t\treturn { ok: false };\n\t\t\t}\n\t\t\tchunks.push(value);\n\t\t}\n\t} catch {\n\t\treturn { ok: false };\n\t} finally {\n\t\treader.releaseLock();\n\t}\n\ttry {\n\t\tconst bytes = new Uint8Array(total);\n\t\tlet offset = 0;\n\t\tfor (const chunk of chunks) {\n\t\t\tbytes.set(chunk, offset);\n\t\t\toffset += chunk.byteLength;\n\t\t}\n\t\tconst parsed = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes)) as unknown;\n\t\treturn parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n\t\t\t? { ok: true, value: parsed as Record<string, unknown> }\n\t\t\t: { ok: false };\n\t} catch {\n\t\treturn { ok: false };\n\t}\n}\n\nfunction hasExactKeys(value: Record<string, unknown>, keys: readonly string[]): boolean {\n\tconst actual = Object.keys(value).toSorted();\n\tconst expected = keys.toSorted();\n\treturn actual.length === expected.length && actual.every((key, index) => key === expected[index]);\n}\n\nfunction detailResponse(\n\tstore: MemoryStore,\n\tdraft: LegacyTeamSetupDraftView,\n\tcandidate: LegacyTeamCandidateView = candidateFromDraft(draft),\n): LegacyTeamSetupDetailResponseV1 {\n\tlet unavailableReason: LegacyTeamSetupUnavailableReasonV1 | null = null;\n\tlet preview: ReturnType<typeof inspectLegacyTeamSetupActivation> | null = null;\n\tif (draft.state !== \"completed\") {\n\t\ttry {\n\t\t\tpreview = inspectLegacyTeamSetupActivation(store.db, {\n\t\t\t\tcandidateRef: draft.candidateRef,\n\t\t\t\tattemptId: draft.attemptId,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst code = apiErrorCode(error);\n\t\t\tif (code === \"team_setup_failed\") throw error;\n\t\t\tif (code === \"team_setup_projection_changed\") unavailableReason = \"team_setup_conflict\";\n\t\t\telse if (code !== \"team_setup_incomplete\") unavailableReason = code;\n\t\t}\n\t}\n\tif (preview) requireLegacyTeamSetupAccessDeltaWithinLimit(preview.accessDelta);\n\tconst safeDraft = viewerSafeDraft(store, draft);\n\tconst safePreview = preview ? viewerSafePreview(draft, safeDraft, preview) : null;\n\treturn projectLegacyTeamSetupView({\n\t\tversion: TEAM_SETUP_VERSION,\n\t\tcandidate: candidateSummaryForDraft(candidate, draft),\n\t\tdraftState: draft.state,\n\t\tattemptId: draft.attemptId,\n\t\tunresolvedDeviceCount: draft.unresolvedDeviceCount,\n\t\tunresolvedProjectCount: draft.unresolvedProjectCount,\n\t\t...safeDraft,\n\t\tunavailableReason,\n\t\tpreview: safePreview,\n\t});\n}\n\nfunction finishResponse(\n\tcandidateRef: string,\n\tresult: LegacyTeamSetupActivationResultV1,\n): LegacyTeamSetupFinishResponseV1 {\n\treturn {\n\t\tversion: TEAM_SETUP_VERSION,\n\t\tstatus: result.status,\n\t\tteamRef: teamRef(candidateRef, result.teamId),\n\t\tattemptId: result.attemptId,\n\t\taccessDeltaDigest: result.accessDeltaDigest,\n\t\tcompletedAt: result.completedAt,\n\t};\n}\n\nexport function teamSetupRoutes(options: TeamSetupRoutesOptions): Hono {\n\tconst app = new Hono();\n\tconst loadSnapshots =\n\t\toptions.loadLegacyTeamConfiguredGroupSnapshots ??\n\t\t((loadOptions?: LegacyTeamConfiguredGroupSnapshotLoadOptions) =>\n\t\t\tloadConfiguredLegacyTeamGroupSnapshotsWith(\n\t\t\t\toptions.snapshotLoaderDependencies ?? defaultSnapshotLoaderDependencies,\n\t\t\t\tloadOptions,\n\t\t\t\toptions.getStore,\n\t\t\t));\n\n\tasync function loadedSnapshots(\n\t\tcandidateRef?: string,\n\t\tdeadlineMs?: number,\n\t): Promise<LegacyTeamConfiguredGroupSnapshot[]> {\n\t\ttry {\n\t\t\treturn await loadSnapshots(\n\t\t\t\tcandidateRef || deadlineMs != null ? { candidateRef, deadlineMs } : undefined,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message === \"legacy_team_setup_roster_too_large\") {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tthrow safeCoordinatorError();\n\t\t}\n\t}\n\tconst loadedSummarySnapshots = createCachedSnapshotLoader(\n\t\t() => loadedSnapshots(),\n\t\tSUMMARY_SNAPSHOT_CACHE_TTL_MS,\n\t);\n\toptions.registerSummaryInvalidator?.(() => loadedSummarySnapshots.invalidate());\n\tconst completionDependencies =\n\t\toptions.completionDependencies === undefined\n\t\t\t? defaultCompletionDependencies\n\t\t\t: options.completionDependencies;\n\n\tinterface CompletionAuthorization {\n\t\tconfig: ReturnType<typeof readCoordinatorSyncConfig>;\n\t\tremoteUrl: string;\n\t\tconfiguredCoordinatorId: string;\n\t\tcurrentGroupIds: Set<string>;\n\t}\n\n\t/**\n\t * Reads the live coordinator configuration and the groups it currently\n\t * authorizes. Returns null when completion I/O is not configured or current\n\t * authorization cannot be proven.\n\t */\n\tfunction currentCompletionAuthorization(): CompletionAuthorization | null {\n\t\tconst config = (\n\t\t\toptions.readCoordinatorConfig ??\n\t\t\toptions.snapshotLoaderDependencies?.readConfig ??\n\t\t\treadCoordinatorSyncConfig\n\t\t)();\n\t\tconst remoteUrl = buildBaseUrl(config.syncCoordinatorUrl);\n\t\tif (!remoteUrl || !config.syncCoordinatorAdminSecret) return null;\n\t\tconst configuredCoordinatorId = normalizedCoordinatorId(remoteUrl);\n\t\tif (!configuredCoordinatorId) return null;\n\t\tlet currentGroupIds: Set<string>;\n\t\ttry {\n\t\t\tcurrentGroupIds = new Set(configuredGroupIds(config.syncCoordinatorGroups));\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t\treturn { config, remoteUrl, configuredCoordinatorId, currentGroupIds };\n\t}\n\n\t// Endpoint equivalence only: candidate identity stays bound to the persisted\n\t// coordinator string and is never rewritten from configuration.\n\tfunction authorizesGroup(\n\t\tauthorization: CompletionAuthorization,\n\t\tgroup: LegacyTeamCandidateGroupDescriptor,\n\t): boolean {\n\t\treturn (\n\t\t\tauthorization.currentGroupIds.has(group.groupId) &&\n\t\t\tnormalizedCoordinatorId(group.coordinatorId) === authorization.configuredCoordinatorId\n\t\t);\n\t}\n\n\t/**\n\t * Configuration may change while completion-list or roster requests are in\n\t * flight. Re-prove authorization for the exact coordinator and group right\n\t * before applying canonical policy, as the finish publication path does.\n\t */\n\tfunction stillAuthorizesGroup(\n\t\tinitial: CompletionAuthorization,\n\t\tgroup: LegacyTeamCandidateGroupDescriptor,\n\t): boolean {\n\t\tlet current: CompletionAuthorization | null;\n\t\ttry {\n\t\t\tcurrent = currentCompletionAuthorization();\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t\treturn (\n\t\t\tcurrent !== null &&\n\t\t\tcurrent.configuredCoordinatorId === initial.configuredCoordinatorId &&\n\t\t\tcurrent.remoteUrl === initial.remoteUrl &&\n\t\t\tcurrent.config.syncCoordinatorAdminSecret === initial.config.syncCoordinatorAdminSecret &&\n\t\t\tauthorizesGroup(current, group)\n\t\t);\n\t}\n\n\tfunction matchesGroupSnapshot(\n\t\tsnapshot: LegacyTeamConfiguredGroupSnapshot,\n\t\tgroup: LegacyTeamCandidateGroupDescriptor,\n\t): boolean {\n\t\treturn (\n\t\t\tsnapshot.groupId === group.groupId &&\n\t\t\tnormalizedCoordinatorId(snapshot.coordinatorId) ===\n\t\t\t\tnormalizedCoordinatorId(group.coordinatorId)\n\t\t);\n\t}\n\n\tfunction freshGroupKey(group: { coordinatorId: string; groupId: string }): string {\n\t\treturn `${normalizedCoordinatorId(group.coordinatorId) ?? group.coordinatorId}\\0${group.groupId}`;\n\t}\n\n\t/**\n\t * The snapshot loader keys candidates by the configured coordinator spelling,\n\t * while a persisted group may carry an equivalent but different spelling.\n\t * Ask for the roster under each spelling and match on normalized identity,\n\t * preserving the persisted candidate identity for everything else.\n\t */\n\tasync function loadFreshGroupSnapshot(\n\t\tgroup: LegacyTeamCandidateGroupDescriptor,\n\t\tremoteUrl: string,\n\t\tdeadlineMs: number,\n\t): Promise<LegacyTeamConfiguredGroupSnapshot | undefined> {\n\t\tconst candidateRefs = [\n\t\t\t...new Set([\n\t\t\t\tlegacyTeamCandidateId(remoteUrl, group.groupId),\n\t\t\t\tlegacyTeamCandidateId(group.coordinatorId, group.groupId),\n\t\t\t]),\n\t\t];\n\t\tfor (const candidateRef of candidateRefs) {\n\t\t\tconst snapshots = await loadedSnapshots(candidateRef, deadlineMs);\n\t\t\tconst matches = snapshots.filter((snapshot) => matchesGroupSnapshot(snapshot, group));\n\t\t\tif (matches.length > 1) throw new Error(\"team_setup_completion_invalid\");\n\t\t\tif (matches[0]) return matches[0];\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tfunction completionRecordCandidateRef(record: { manifest: unknown }): string | null {\n\t\tconst manifest = record.manifest;\n\t\tif (!manifest || typeof manifest !== \"object\" || Array.isArray(manifest)) return null;\n\t\tconst candidateRef = (manifest as { candidate_ref?: unknown }).candidate_ref;\n\t\treturn typeof candidateRef === \"string\" ? candidateRef : null;\n\t}\n\n\t// The coordinator lists every candidate a group has ever completed. A record\n\t// for a different candidate identity (an earlier coordinator address) is\n\t// historical context, not evidence about this candidate.\n\tfunction belongsToGroupCandidate(\n\t\trecord: { manifest: unknown },\n\t\tgroup: LegacyTeamCandidateGroupDescriptor,\n\t): boolean {\n\t\tconst candidateRef = completionRecordCandidateRef(record);\n\t\treturn (\n\t\t\tcandidateRef === null ||\n\t\t\tcandidateRef === legacyTeamCandidateId(group.coordinatorId, group.groupId)\n\t\t);\n\t}\n\n\t/**\n\t * Applies a canonical manifest with authorization re-proven inside the same\n\t * serialized section that guards the apply. Checking before the locks would\n\t * let a group removed while reconciliation waited on another policy\n\t * mutation still be applied once the queues open.\n\t */\n\tasync function applyCanonicalManifestIfStillAuthorized(\n\t\tstore: MemoryStore,\n\t\tauthorization: CompletionAuthorization,\n\t\tgroup: LegacyTeamCandidateGroupDescriptor,\n\t\tmanifest: CoordinatorLegacyTeamCompletionManifestV1,\n\t\tfreshRoster: LegacyTeamConfiguredGroupSnapshot[\"devices\"],\n\t): Promise<\"applied\" | \"unauthorized\" | \"claimed\"> {\n\t\tlet outcome: \"applied\" | \"unauthorized\" = \"unauthorized\";\n\t\tconst ran = await runCandidateMutation(\n\t\t\tstore.db,\n\t\t\tlegacyTeamCandidateId(group.coordinatorId, group.groupId),\n\t\t\t() =>\n\t\t\t\tserializeRecipientPolicyPublicationMutation(store.db, () =>\n\t\t\t\t\tserializeRecipientPolicyTeamMutation(store.db, manifest.team_id, () =>\n\t\t\t\t\t\tserializeRecipientPolicyCoordinatorGroupMutation(store.db, group.groupId, async () => {\n\t\t\t\t\t\t\tif (!stillAuthorizesGroup(authorization, group)) return;\n\t\t\t\t\t\t\tawait applyLegacyTeamSetupCompletionManifest(store.db, {\n\t\t\t\t\t\t\t\tcoordinatorId: group.coordinatorId,\n\t\t\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\t\t\tmanifest,\n\t\t\t\t\t\t\t\tfreshRoster,\n\t\t\t\t\t\t\t\trecipientPolicyLocksHeld: { publication: true, team: true, coordinatorGroup: true },\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\toutcome = \"applied\";\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t);\n\t\treturn ran ? outcome : \"claimed\";\n\t}\n\n\tasync function reconcileCompletions(\n\t\tstore: MemoryStore,\n\t\tgroups: LegacyTeamCandidateGroupDescriptor[],\n\t\treconciliationOptions: { isolateApplyFailures?: boolean } = {},\n\t): Promise<void> {\n\t\tif (!completionDependencies || groups.length === 0) return;\n\t\tlet authorization: CompletionAuthorization | null;\n\t\ttry {\n\t\t\tauthorization = currentCompletionAuthorization();\n\t\t} catch (error) {\n\t\t\tthrow new Error(completionApiError(error));\n\t\t}\n\t\t// If current authorization cannot be proven, skip completion I/O without\n\t\t// failing an otherwise serviceable persisted detail read.\n\t\tif (!authorization) return;\n\t\tconst { config, remoteUrl } = authorization;\n\t\tconst scopedGroups = groups.filter((group) => authorizesGroup(authorization, group));\n\t\tif (scopedGroups.length === 0) return;\n\t\tconst timeoutS = Math.max(1, config.syncCoordinatorTimeoutS);\n\t\ttry {\n\t\t\tconst reconciliationDeadlineMs = Date.now() + COORDINATOR_ROSTER_READ_BUDGET_MS;\n\t\t\tconst groupById = new Map(scopedGroups.map((group) => [group.groupId, group]));\n\t\t\tconst listCompletionRecords = (groupIds: string[]) =>\n\t\t\t\tretryTransientCoordinatorRead(\n\t\t\t\t\t(attemptTimeoutS) =>\n\t\t\t\t\t\tcompletionDependencies.list({\n\t\t\t\t\t\t\tgroupIds,\n\t\t\t\t\t\t\tremoteUrl,\n\t\t\t\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret,\n\t\t\t\t\t\t\ttimeoutS: attemptTimeoutS,\n\t\t\t\t\t\t}),\n\t\t\t\t\ttimeoutS,\n\t\t\t\t\treconciliationDeadlineMs,\n\t\t\t\t);\n\t\t\tconst scopedGroupIds = [...new Set(scopedGroups.map((group) => group.groupId))];\n\t\t\tlet records: Awaited<ReturnType<LegacyTeamCompletionDependencies[\"list\"]>>;\n\t\t\ttry {\n\t\t\t\trecords = await listCompletionRecords(scopedGroupIds);\n\t\t\t} catch (error) {\n\t\t\t\t// Older coordinators do not expose completion reconciliation. Read routes\n\t\t\t\t// remain usable, and best-effort publication below still lets upgraded\n\t\t\t\t// peers observe a locally completed migration.\n\t\t\t\tif (isUnsupportedCompletionQuery(error)) {\n\t\t\t\t\trecords = [];\n\t\t\t\t} else if (\n\t\t\t\t\treconciliationOptions.isolateApplyFailures &&\n\t\t\t\t\tisUnattributableCompletionBatchError(error)\n\t\t\t\t) {\n\t\t\t\t\t// One corrupt or mixed-version record must not hide every healthy\n\t\t\t\t\t// group's setup state. Re-query per group so the decode failure\n\t\t\t\t\t// stays attributable; a group whose own record cannot be decoded is\n\t\t\t\t\t// skipped, matching the unprovable-binding path below.\n\t\t\t\t\trecords = await listCompletionRecordsPerGroup(scopedGroupIds, listCompletionRecords);\n\t\t\t\t} else {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst freshGroupByKey = new Map<string, LegacyTeamConfiguredGroupSnapshot>();\n\t\t\tif (records.length > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tconst onlyGroup = scopedGroups.length === 1 ? scopedGroups[0] : undefined;\n\t\t\t\t\tconst freshGroups = onlyGroup\n\t\t\t\t\t\t? [await loadFreshGroupSnapshot(onlyGroup, remoteUrl, reconciliationDeadlineMs)]\n\t\t\t\t\t\t: await loadedSnapshots(undefined, reconciliationDeadlineMs);\n\t\t\t\t\tfor (const freshGroup of freshGroups) {\n\t\t\t\t\t\tif (!freshGroup) continue;\n\t\t\t\t\t\tconst key = freshGroupKey(freshGroup);\n\t\t\t\t\t\tif (freshGroupByKey.has(key)) throw new Error(\"team_setup_completion_invalid\");\n\t\t\t\t\t\tfreshGroupByKey.set(key, freshGroup);\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfor (const record of records) {\n\t\t\t\t\t\tconst group = groupById.get(record.group_id);\n\t\t\t\t\t\tif (!group || !belongsToGroupCandidate(record, group)) continue;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tvalidateLegacyTeamSetupCompletionManifestBinding(record.manifest, {\n\t\t\t\t\t\t\t\tcoordinatorId: group.coordinatorId,\n\t\t\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} catch (bindingError) {\n\t\t\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) throw bindingError;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlet canonicalManifest: ReturnType<typeof validateLegacyTeamSetupCompletionManifest>;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tcanonicalManifest = validateLegacyTeamSetupCompletionManifest(record.manifest, {\n\t\t\t\t\t\t\t\tcoordinatorId: group.coordinatorId,\n\t\t\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} catch (validationError) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tconst contained = await runCandidateMutation(\n\t\t\t\t\t\t\t\t\tstore.db,\n\t\t\t\t\t\t\t\t\tlegacyTeamCandidateId(group.coordinatorId, group.groupId),\n\t\t\t\t\t\t\t\t\t() =>\n\t\t\t\t\t\t\t\t\t\tcontainLegacyTeamSetupCompletionConflict(store.db, {\n\t\t\t\t\t\t\t\t\t\t\tcoordinatorId: group.coordinatorId,\n\t\t\t\t\t\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tif (!contained) {\n\t\t\t\t\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) throw validationError;\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} catch (containmentError) {\n\t\t\t\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) throw containmentError;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) throw validationError;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst localManifest = reconstructLegacyTeamSetupCompletionManifest(store.db, {\n\t\t\t\t\t\t\t\tcandidateRef: canonicalManifest.candidate_ref,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\tcanonicalCoordinatorLegacyTeamCompletionManifestJson(localManifest) ===\n\t\t\t\t\t\t\t\tcanonicalCoordinatorLegacyTeamCompletionManifestJson(canonicalManifest)\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\tareLegacyTeamSetupCompletionPolicyFactsAdditivelyCompatible(\n\t\t\t\t\t\t\t\t\tlocalManifest,\n\t\t\t\t\t\t\t\t\tcanonicalManifest,\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t// Missing or invalid local completion state must not remain active when\n\t\t\t\t\t\t\t// a valid coordinator winner cannot be applied safely.\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait runCandidateMutation(store.db, canonicalManifest.candidate_ref, () =>\n\t\t\t\t\t\t\t\tcontainLegacyTeamSetupCompletionConflict(store.db, {\n\t\t\t\t\t\t\t\t\tcoordinatorId: group.coordinatorId,\n\t\t\t\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} catch (containmentError) {\n\t\t\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) throw containmentError;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) throw error;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst coordinatorCompletionGroupIds = new Set<string>();\n\t\t\tfor (const record of records) {\n\t\t\t\tconst group = groupById.get(record.group_id);\n\t\t\t\tif (!group) throw new Error(\"team_setup_completion_invalid\");\n\t\t\t\tif (!belongsToGroupCandidate(record, group)) continue;\n\t\t\t\ttry {\n\t\t\t\t\tvalidateLegacyTeamSetupCompletionManifestBinding(record.manifest, {\n\t\t\t\t\t\tcoordinatorId: group.coordinatorId,\n\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t});\n\t\t\t\t} catch (bindingError) {\n\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) throw bindingError;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tlet canonicalManifest: ReturnType<typeof validateLegacyTeamSetupCompletionManifest>;\n\t\t\t\ttry {\n\t\t\t\t\tcanonicalManifest = validateLegacyTeamSetupCompletionManifest(record.manifest, {\n\t\t\t\t\t\tcoordinatorId: group.coordinatorId,\n\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t});\n\t\t\t\t} catch (validationError) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait runCandidateMutation(\n\t\t\t\t\t\t\tstore.db,\n\t\t\t\t\t\t\tlegacyTeamCandidateId(group.coordinatorId, group.groupId),\n\t\t\t\t\t\t\t() =>\n\t\t\t\t\t\t\t\tcontainLegacyTeamSetupCompletionConflict(store.db, {\n\t\t\t\t\t\t\t\t\tcoordinatorId: group.coordinatorId,\n\t\t\t\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t} catch (containmentError) {\n\t\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) throw containmentError;\n\t\t\t\t\t}\n\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) throw validationError;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tcoordinatorCompletionGroupIds.add(record.group_id);\n\t\t\t\ttry {\n\t\t\t\t\tlet freshGroup = freshGroupByKey.get(freshGroupKey(group));\n\t\t\t\t\tif (!freshGroup && scopedGroups.length > 1) {\n\t\t\t\t\t\tif (remainingCoordinatorTimeoutS(timeoutS, reconciliationDeadlineMs) == null) {\n\t\t\t\t\t\t\tthrow new Error(\"team_setup_roster_unavailable\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfreshGroup = await loadFreshGroupSnapshot(group, remoteUrl, reconciliationDeadlineMs);\n\t\t\t\t\t}\n\t\t\t\t\tif (!freshGroup) {\n\t\t\t\t\t\tconst contained = await runCandidateMutation(\n\t\t\t\t\t\t\tstore.db,\n\t\t\t\t\t\t\tlegacyTeamCandidateId(group.coordinatorId, group.groupId),\n\t\t\t\t\t\t\t() =>\n\t\t\t\t\t\t\t\tcontainLegacyTeamSetupCompletionConflict(store.db, {\n\t\t\t\t\t\t\t\t\tcoordinatorId: group.coordinatorId,\n\t\t\t\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (!contained) {\n\t\t\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) {\n\t\t\t\t\t\t\t\tthrow new Error(\"team_setup_completion_invalid\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthrow new Error(\"team_setup_completion_invalid\");\n\t\t\t\t\t}\n\t\t\t\t\tconst applied = await applyCanonicalManifestIfStillAuthorized(\n\t\t\t\t\t\tstore,\n\t\t\t\t\t\tauthorization,\n\t\t\t\t\t\tgroup,\n\t\t\t\t\t\tcanonicalManifest,\n\t\t\t\t\t\tfreshGroup.devices,\n\t\t\t\t\t);\n\t\t\t\t\tif (applied !== \"applied\") continue;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) throw error;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const group of scopedGroups) {\n\t\t\t\tif (coordinatorCompletionGroupIds.has(group.groupId)) continue;\n\t\t\t\tconst publicationTimeoutS = remainingCoordinatorTimeoutS(\n\t\t\t\t\ttimeoutS,\n\t\t\t\t\treconciliationDeadlineMs,\n\t\t\t\t);\n\t\t\t\tif (publicationTimeoutS == null) break;\n\t\t\t\tif (\n\t\t\t\t\t!hasCompletedLegacyTeamSetup(\n\t\t\t\t\t\tstore,\n\t\t\t\t\t\tlegacyTeamCandidateId(group.coordinatorId, group.groupId),\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst candidateRef = legacyTeamCandidateId(group.coordinatorId, group.groupId);\n\t\t\t\tlet reconstructionFailed = false;\n\t\t\t\ttry {\n\t\t\t\t\tconst published = await runCandidateMutation(store.db, candidateRef, () =>\n\t\t\t\t\t\tserializeRecipientPolicyPublicationMutation(store.db, () =>\n\t\t\t\t\t\t\tserializeRecipientPolicyTeamMutation(\n\t\t\t\t\t\t\t\tstore.db,\n\t\t\t\t\t\t\t\tdeterministicPolicyTeamId(candidateRef),\n\t\t\t\t\t\t\t\tasync () => {\n\t\t\t\t\t\t\t\t\tlet manifest: ReturnType<typeof reconstructLegacyTeamSetupCompletionManifest>;\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tmanifest = reconstructLegacyTeamSetupCompletionManifest(store.db, {\n\t\t\t\t\t\t\t\t\t\t\tcandidateRef,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t\t\treconstructionFailed = true;\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t// Publication sends identity and policy data to the coordinator;\n\t\t\t\t\t\t\t\t\t// re-prove the destination is still the configured one.\n\t\t\t\t\t\t\t\t\tif (!stillAuthorizesGroup(authorization, group)) {\n\t\t\t\t\t\t\t\t\t\treconstructionFailed = true;\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tawait completionDependencies.create({\n\t\t\t\t\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\t\t\t\t\tmanifest,\n\t\t\t\t\t\t\t\t\t\tremoteUrl,\n\t\t\t\t\t\t\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret,\n\t\t\t\t\t\t\t\t\t\ttimeoutS: publicationTimeoutS,\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tif (!published || reconstructionFailed) continue;\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Publishing an existing local completion is best-effort. The bounded\n\t\t\t\t\t// list/apply pass above remains authoritative and fail-closed.\n\t\t\t\t\tif (completionApiError(error) !== \"team_setup_completion_conflict\") continue;\n\t\t\t\t\tconst getCompletion = completionDependencies.get;\n\t\t\t\t\tlet canonicalManifest: Awaited<ReturnType<NonNullable<typeof getCompletion>>> = null;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (!getCompletion) throw new Error(\"team_setup_completion_conflict\");\n\t\t\t\t\t\tcanonicalManifest = await retryTransientCoordinatorRead(\n\t\t\t\t\t\t\t(attemptTimeoutS) =>\n\t\t\t\t\t\t\t\tgetCompletion({\n\t\t\t\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\t\t\t\tcandidateRef,\n\t\t\t\t\t\t\t\t\tremoteUrl,\n\t\t\t\t\t\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret,\n\t\t\t\t\t\t\t\t\ttimeoutS: attemptTimeoutS,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\ttimeoutS,\n\t\t\t\t\t\t\treconciliationDeadlineMs,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (!canonicalManifest) throw new Error(\"team_setup_completion_conflict\");\n\t\t\t\t\t} catch {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst contained = await runCandidateMutation(store.db, candidateRef, () =>\n\t\t\t\t\t\t\t\tcontainLegacyTeamSetupCompletionConflict(store.db, {\n\t\t\t\t\t\t\t\t\tcoordinatorId: group.coordinatorId,\n\t\t\t\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (!contained) {\n\t\t\t\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) {\n\t\t\t\t\t\t\t\t\tthrow new Error(\"team_setup_completion_conflict\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (containmentError) {\n\t\t\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) throw containmentError;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) {\n\t\t\t\t\t\t\tthrow new Error(\"team_setup_completion_conflict\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst freshGroup = await loadFreshGroupSnapshot(\n\t\t\t\t\t\t\tgroup,\n\t\t\t\t\t\t\tremoteUrl,\n\t\t\t\t\t\t\treconciliationDeadlineMs,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (!freshGroup) throw new Error(\"team_setup_roster_unavailable\");\n\t\t\t\t\t\tconst applied = await applyCanonicalManifestIfStillAuthorized(\n\t\t\t\t\t\t\tstore,\n\t\t\t\t\t\t\tauthorization,\n\t\t\t\t\t\t\tgroup,\n\t\t\t\t\t\t\tcanonicalManifest,\n\t\t\t\t\t\t\tfreshGroup.devices,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (applied !== \"applied\") continue;\n\t\t\t\t\t} catch (applyError) {\n\t\t\t\t\t\tif (applyError instanceof LegacyTeamSetupAdditiveConvergenceError) {\n\t\t\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) throw applyError;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst contained = await runCandidateMutation(store.db, candidateRef, () =>\n\t\t\t\t\t\t\t\tcontainLegacyTeamSetupCompletionConflict(store.db, {\n\t\t\t\t\t\t\t\t\tcoordinatorId: group.coordinatorId,\n\t\t\t\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (!contained) {\n\t\t\t\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) {\n\t\t\t\t\t\t\t\t\tthrow new Error(\"team_setup_completion_conflict\", { cause: applyError });\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (containmentError) {\n\t\t\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) throw containmentError;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) {\n\t\t\t\t\t\t\tthrow new Error(\"team_setup_completion_conflict\", { cause: applyError });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthrow new Error(completionApiError(error));\n\t\t}\n\t}\n\tasync function loadedCandidateSnapshots(\n\t\tcandidateRef: string,\n\t\tloadOptions: {\n\t\t\tallowCachedSummaryFallback?: boolean;\n\t\t\tdeadlineMs?: number;\n\t\t\tinvalidateSummaryCache?: boolean;\n\t\t} = {},\n\t): Promise<LegacyTeamConfiguredGroupSnapshot[]> {\n\t\tconst allowCachedSummaryFallback = loadOptions.allowCachedSummaryFallback ?? false;\n\t\tconst invalidateSummaryCache = loadOptions.invalidateSummaryCache ?? true;\n\t\tif (invalidateSummaryCache) loadedSummarySnapshots.invalidate();\n\t\ttry {\n\t\t\treturn await loadedSnapshots(candidateRef, loadOptions.deadlineMs);\n\t\t} catch (error) {\n\t\t\tif (!allowCachedSummaryFallback) throw error;\n\t\t\tconst cachedGroups = loadedSummarySnapshots.peek();\n\t\t\tif (!cachedGroups) throw error;\n\t\t\tconst matching = cachedGroups.filter(\n\t\t\t\t(group) => legacyTeamCandidateId(group.coordinatorId, group.groupId) === candidateRef,\n\t\t\t);\n\t\t\tif (matching.length !== 1) throw error;\n\t\t\treturn matching;\n\t\t} finally {\n\t\t\tif (invalidateSummaryCache) loadedSummarySnapshots.invalidate();\n\t\t}\n\t}\n\n\tfunction persistedCompletionGroup(\n\t\tstore: MemoryStore,\n\t\tcandidateRef: string,\n\t): LegacyTeamCandidateGroupDescriptor | null {\n\t\tconst row = store.db\n\t\t\t.prepare(\n\t\t\t\t`SELECT coordinator_id, group_id FROM legacy_team_setup_drafts\n\t\t\t\t WHERE candidate_id = ? ORDER BY rowid DESC LIMIT 1`,\n\t\t\t)\n\t\t\t.get(candidateRef) as { coordinator_id: string; group_id: string } | undefined;\n\t\tif (!row || legacyTeamCandidateId(row.coordinator_id, row.group_id) !== candidateRef)\n\t\t\treturn null;\n\t\treturn { coordinatorId: row.coordinator_id, groupId: row.group_id };\n\t}\n\n\tapp.get(\"/api/sync/team-setup/v1\", async (c) => {\n\t\tlet groups: LegacyTeamConfiguredGroupSnapshot[];\n\t\ttry {\n\t\t\tgroups = await loadedSummarySnapshots();\n\t\t} catch (error) {\n\t\t\tconst code = apiErrorCode(error);\n\t\t\treturn c.json({ error: code }, errorStatus(code));\n\t\t}\n\t\ttry {\n\t\t\tconst store = options.getStore();\n\t\t\treadPureCandidateViews(store, groups);\n\t\t\tawait reconcileCompletions(store, groups, { isolateApplyFailures: true });\n\t\t\tconst response = {\n\t\t\t\tversion: TEAM_SETUP_VERSION,\n\t\t\t\tcandidates: readPureCandidateViews(store, groups)\n\t\t\t\t\t.map(candidateSummary)\n\t\t\t\t\t.filter(\n\t\t\t\t\t\t(candidate): candidate is LegacyTeamSetupPendingCandidateSummaryV1 =>\n\t\t\t\t\t\t\tcandidate.status !== \"ready\",\n\t\t\t\t\t),\n\t\t\t} satisfies LegacyTeamSetupSummaryResponseV1;\n\t\t\treturn c.json(response);\n\t\t} catch (error) {\n\t\t\tconst code = apiErrorCode(error);\n\t\t\treturn c.json({ error: code }, errorStatus(code));\n\t\t}\n\t});\n\n\tapp.get(\"/api/sync/team-setup/v1/:candidateRef\", async (c) => {\n\t\tconst candidateRef = c.req.param(\"candidateRef\");\n\t\tif (!CANDIDATE_REF_PATTERN.test(candidateRef)) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\n\t\ttry {\n\t\t\tconst store = options.getStore();\n\t\t\tlet draft = getLegacyTeamSetupDraft(store.db, candidateRef);\n\t\t\tconst terminal = hasCompletedLegacyTeamSetup(store, candidateRef);\n\t\t\tlet candidateGroupsForCompletion: LegacyTeamConfiguredGroupSnapshot[] | null = null;\n\t\t\tif (terminal && draft?.state !== \"completed\") {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\t}\n\t\t\tlet candidate: LegacyTeamCandidateView;\n\t\t\tif (draft && (draft.state !== \"completed\" || terminal)) {\n\t\t\t\tcandidate = candidateFromDraft(draft);\n\t\t\t} else {\n\t\t\t\t// Revalidation may replace a completed draft, so it must never decide\n\t\t\t\t// against a stale summary-cache roster. Cache fallback remains safe for\n\t\t\t\t// candidates that have no persisted attempt yet.\n\t\t\t\tconst groups = await loadedCandidateSnapshots(candidateRef, {\n\t\t\t\t\tallowCachedSummaryFallback: draft == null,\n\t\t\t\t\tinvalidateSummaryCache: false,\n\t\t\t\t});\n\t\t\t\tconst candidateGroups = groups.filter(\n\t\t\t\t\t(group) => legacyTeamCandidateId(group.coordinatorId, group.groupId) === candidateRef,\n\t\t\t\t);\n\t\t\t\tcandidateGroupsForCompletion = candidateGroups;\n\t\t\t\tconst postLoadDraft = getLegacyTeamSetupDraft(store.db, candidateRef);\n\t\t\t\tif (hasCompletedLegacyTeamSetup(store, candidateRef)) {\n\t\t\t\t\tif (postLoadDraft?.state !== \"completed\") {\n\t\t\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\t\t\t}\n\t\t\t\t\tdraft = postLoadDraft;\n\t\t\t\t\tcandidate = candidateFromDraft(postLoadDraft);\n\t\t\t\t} else {\n\t\t\t\t\tconst discoveredCandidate = discoverCandidates(store, candidateGroups).find(\n\t\t\t\t\t\t(item) => item.candidateRef === candidateRef,\n\t\t\t\t\t);\n\t\t\t\t\tif (!discoveredCandidate) {\n\t\t\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\t\t\t}\n\t\t\t\t\tcandidate = discoveredCandidate;\n\t\t\t\t\tdraft = getLegacyTeamSetupDraft(store.db, candidateRef);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!draft) return c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\tconst cachedCandidateGroups = loadedSummarySnapshots\n\t\t\t\t.peek()\n\t\t\t\t?.filter(\n\t\t\t\t\t(group) => legacyTeamCandidateId(group.coordinatorId, group.groupId) === candidateRef,\n\t\t\t\t);\n\t\t\tlet completionGroups: LegacyTeamCandidateGroupDescriptor[] | null =\n\t\t\t\tcandidateGroupsForCompletion ??\n\t\t\t\t(cachedCandidateGroups?.length ? cachedCandidateGroups : null);\n\t\t\tif (!completionGroups) {\n\t\t\t\tconst persistedGroup = persistedCompletionGroup(store, candidateRef);\n\t\t\t\tcompletionGroups = persistedGroup ? [persistedGroup] : null;\n\t\t\t}\n\t\t\tconst terminalBeforeReconciliation = hasCompletedLegacyTeamSetup(store, candidateRef);\n\t\t\tif (completionGroups) await reconcileCompletions(store, completionGroups);\n\t\t\tdraft = getLegacyTeamSetupDraft(store.db, candidateRef);\n\t\t\tif (\n\t\t\t\t!draft ||\n\t\t\t\t(!terminalBeforeReconciliation && hasCompletedLegacyTeamSetup(store, candidateRef))\n\t\t\t) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\t}\n\t\t\tif (completionGroups) candidate = candidateFromDraft(draft);\n\n\t\t\treturn c.json(detailResponse(store, draft, candidate));\n\t\t} catch (error) {\n\t\t\tconst code = apiErrorCode(error);\n\t\t\treturn c.json({ error: code }, errorStatus(code));\n\t\t}\n\t});\n\n\tapp.put(\"/api/sync/team-setup/v1/:candidateRef/devices/:deviceRef/assignment\", async (c) => {\n\t\tconst candidateRef = c.req.param(\"candidateRef\");\n\t\tconst deviceRef = c.req.param(\"deviceRef\");\n\t\tif (!CANDIDATE_REF_PATTERN.test(candidateRef) || !DEVICE_REF_PATTERN.test(deviceRef)) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\tconst parsed = await parseBoundedJsonObject(c);\n\t\tif (\n\t\t\t!parsed.ok ||\n\t\t\t!hasExactKeys(parsed.value, [\"attemptId\", \"expectation\", \"targetIdentityRef\"])\n\t\t) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\tconst { attemptId, expectation, targetIdentityRef } = parsed.value;\n\t\tif (\n\t\t\ttypeof attemptId !== \"string\" ||\n\t\t\t!ATTEMPT_ID_PATTERN.test(attemptId) ||\n\t\t\ttypeof targetIdentityRef !== \"string\" ||\n\t\t\t!IDENTITY_REF_PATTERN.test(targetIdentityRef) ||\n\t\t\t!expectation ||\n\t\t\ttypeof expectation !== \"object\" ||\n\t\t\tArray.isArray(expectation)\n\t\t) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\ttry {\n\t\t\tconst store = options.getStore();\n\t\t\tconst draft = getLegacyTeamSetupDraft(store.db, candidateRef);\n\t\t\tif (!draft) return c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\tif (draft.state !== \"completed\" && hasCompletedLegacyTeamSetup(store, candidateRef)) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tif (draft.attemptId !== attemptId) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tif (draft.state === \"completed\") {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tconst device = draft.devices.find((item) => item.deviceRef === deviceRef);\n\t\t\tif (!device) return c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\tconst submittedExpectation = expectation as Record<string, unknown>;\n\t\t\tconst expectationMatches =\n\t\t\t\tdevice.expectation.kind === \"absent\"\n\t\t\t\t\t? hasExactKeys(submittedExpectation, [\"kind\"]) && submittedExpectation.kind === \"absent\"\n\t\t\t\t\t: hasExactKeys(submittedExpectation, [\"assignmentVersion\", \"identityRef\", \"kind\"]) &&\n\t\t\t\t\t\tsubmittedExpectation.kind === \"existing\" &&\n\t\t\t\t\t\tsubmittedExpectation.assignmentVersion === device.expectation.assignmentVersion &&\n\t\t\t\t\t\tsubmittedExpectation.identityRef ===\n\t\t\t\t\t\t\trequiredIdentityRef(candidateRef, device.expectation.identityId);\n\t\t\tif (!expectationMatches) {\n\t\t\t\treturn c.json({ error: \"team_setup_assignment_changed\" as const }, 409);\n\t\t\t}\n\t\t\tconst target = identityChoices(store, candidateRef).find(\n\t\t\t\t(choice) => choice.identityRef === targetIdentityRef,\n\t\t\t);\n\t\t\tif (!target) return c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\tconst releaseMutation = claimCandidateMutation(store.db, candidateRef);\n\t\t\tif (!releaseMutation) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn c.json(\n\t\t\t\t\tprojectMutationAtomically(\n\t\t\t\t\t\tstore,\n\t\t\t\t\t\t() =>\n\t\t\t\t\t\t\tsetLegacyTeamSetupDeviceAssignment(store.db, {\n\t\t\t\t\t\t\t\tattemptId,\n\t\t\t\t\t\t\t\tdeviceRef,\n\t\t\t\t\t\t\t\ttargetIdentityId: target.identityId,\n\t\t\t\t\t\t\t\texpectation: device.expectation,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t(draft) => detailResponse(store, draft),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} finally {\n\t\t\t\treleaseMutation();\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst code = apiErrorCode(error);\n\t\t\treturn c.json({ error: code }, errorStatus(code));\n\t\t}\n\t});\n\n\tapp.put(\"/api/sync/team-setup/v1/:candidateRef/devices/:deviceRef/decision\", async (c) => {\n\t\tconst candidateRef = c.req.param(\"candidateRef\");\n\t\tconst deviceRef = c.req.param(\"deviceRef\");\n\t\tif (!CANDIDATE_REF_PATTERN.test(candidateRef) || !DEVICE_REF_PATTERN.test(deviceRef)) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\tconst parsed = await parseBoundedJsonObject(c);\n\t\tif (!parsed.ok) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\tconst { attemptId, decision, expectedTargetIdentityRef } = parsed.value;\n\t\tif (\n\t\t\ttypeof attemptId !== \"string\" ||\n\t\t\t!ATTEMPT_ID_PATTERN.test(attemptId) ||\n\t\t\t!([\"included\", \"excluded\", \"removed\"] as unknown[]).includes(decision) ||\n\t\t\t(decision === \"included\"\n\t\t\t\t? !hasExactKeys(parsed.value, [\"attemptId\", \"decision\", \"expectedTargetIdentityRef\"]) ||\n\t\t\t\t\ttypeof expectedTargetIdentityRef !== \"string\" ||\n\t\t\t\t\t!IDENTITY_REF_PATTERN.test(expectedTargetIdentityRef)\n\t\t\t\t: !hasExactKeys(parsed.value, [\"attemptId\", \"decision\"]))\n\t\t) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\ttry {\n\t\t\tconst store = options.getStore();\n\t\t\tconst draft = getLegacyTeamSetupDraft(store.db, candidateRef);\n\t\t\tif (!draft) return c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\tif (draft.state !== \"completed\" && hasCompletedLegacyTeamSetup(store, candidateRef)) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tif (draft.attemptId !== attemptId) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tif (draft.state === \"completed\") {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tconst device = draft.devices.find((item) => item.deviceRef === deviceRef);\n\t\t\tif (!device) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\t}\n\t\t\tif (\n\t\t\t\tdecision === \"included\" &&\n\t\t\t\t(device.targetIdentityId === null ||\n\t\t\t\t\trequiredIdentityRef(candidateRef, device.targetIdentityId) !== expectedTargetIdentityRef)\n\t\t\t) {\n\t\t\t\treturn c.json({ error: \"team_setup_assignment_changed\" as const }, 409);\n\t\t\t}\n\t\t\tconst releaseMutation = claimCandidateMutation(store.db, candidateRef);\n\t\t\tif (!releaseMutation) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn c.json(\n\t\t\t\t\tprojectMutationAtomically(\n\t\t\t\t\t\tstore,\n\t\t\t\t\t\t() =>\n\t\t\t\t\t\t\tsetLegacyTeamSetupDeviceDecision(store.db, {\n\t\t\t\t\t\t\t\tattemptId,\n\t\t\t\t\t\t\t\tdeviceRef,\n\t\t\t\t\t\t\t\tdecision: decision as \"included\" | \"excluded\" | \"removed\",\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t(draft) => detailResponse(store, draft),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} finally {\n\t\t\t\treleaseMutation();\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst code = apiErrorCode(error);\n\t\t\treturn c.json({ error: code }, errorStatus(code));\n\t\t}\n\t});\n\n\tapp.delete(\"/api/sync/team-setup/v1/:candidateRef/devices/:deviceRef/decision\", async (c) => {\n\t\tconst candidateRef = c.req.param(\"candidateRef\");\n\t\tconst deviceRef = c.req.param(\"deviceRef\");\n\t\tif (!CANDIDATE_REF_PATTERN.test(candidateRef) || !DEVICE_REF_PATTERN.test(deviceRef)) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\tconst parsed = await parseBoundedJsonObject(c);\n\t\tif (!parsed.ok || !hasExactKeys(parsed.value, [\"attemptId\"])) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\tconst { attemptId } = parsed.value;\n\t\tif (typeof attemptId !== \"string\" || !ATTEMPT_ID_PATTERN.test(attemptId)) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\ttry {\n\t\t\tconst store = options.getStore();\n\t\t\tconst draft = getLegacyTeamSetupDraft(store.db, candidateRef);\n\t\t\tif (!draft) return c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\tif (draft.state !== \"completed\" && hasCompletedLegacyTeamSetup(store, candidateRef)) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tif (draft.attemptId !== attemptId) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tif (draft.state === \"completed\") {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tif (!draft.devices.some((item) => item.deviceRef === deviceRef)) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\t}\n\t\t\tconst releaseMutation = claimCandidateMutation(store.db, candidateRef);\n\t\t\tif (!releaseMutation) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn c.json(\n\t\t\t\t\tprojectMutationAtomically(\n\t\t\t\t\t\tstore,\n\t\t\t\t\t\t() => clearLegacyTeamSetupDeviceDecision(store.db, { attemptId, deviceRef }),\n\t\t\t\t\t\t(draft) => detailResponse(store, draft),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} finally {\n\t\t\t\treleaseMutation();\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst code = apiErrorCode(error);\n\t\t\treturn c.json({ error: code }, errorStatus(code));\n\t\t}\n\t});\n\n\tapp.put(\"/api/sync/team-setup/v1/:candidateRef/projects/:projectRef/mapping\", async (c) => {\n\t\tconst candidateRef = c.req.param(\"candidateRef\");\n\t\tconst projectRef = c.req.param(\"projectRef\");\n\t\tif (!CANDIDATE_REF_PATTERN.test(candidateRef) || !PROJECT_REF_PATTERN.test(projectRef)) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\tconst parsed = await parseBoundedJsonObject(c);\n\t\tif (!parsed.ok || !hasExactKeys(parsed.value, [\"attemptId\", \"resolvedProjectRef\"])) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\tconst { attemptId, resolvedProjectRef } = parsed.value;\n\t\tif (\n\t\t\ttypeof attemptId !== \"string\" ||\n\t\t\t!ATTEMPT_ID_PATTERN.test(attemptId) ||\n\t\t\ttypeof resolvedProjectRef !== \"string\" ||\n\t\t\t!RESOLVED_PROJECT_REF_PATTERN.test(resolvedProjectRef)\n\t\t) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\ttry {\n\t\t\tconst store = options.getStore();\n\t\t\tconst draft = getLegacyTeamSetupDraft(store.db, candidateRef);\n\t\t\tif (!draft) return c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\tif (draft.state !== \"completed\" && hasCompletedLegacyTeamSetup(store, candidateRef)) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tif (draft.attemptId !== attemptId) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tif (draft.state === \"completed\") {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tconst project = draft.projects.find((item) => item.projectRef === projectRef);\n\t\t\tif (!project) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\t}\n\t\t\tif (project.resolution === \"deterministic\") {\n\t\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t\t}\n\t\t\tconst target = projectMappingChoices(store).find(\n\t\t\t\t(choice) =>\n\t\t\t\t\tlegacyTeamResolvedProjectRef(projectRef, choice.projectIdentity) === resolvedProjectRef,\n\t\t\t);\n\t\t\tif (!target) return c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\tconst releaseMutation = claimCandidateMutation(store.db, candidateRef);\n\t\t\tif (!releaseMutation) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn c.json(\n\t\t\t\t\tprojectMutationAtomically(\n\t\t\t\t\t\tstore,\n\t\t\t\t\t\t() =>\n\t\t\t\t\t\t\tsetLegacyTeamSetupProjectMapping(store.db, {\n\t\t\t\t\t\t\t\tattemptId,\n\t\t\t\t\t\t\t\tprojectRef,\n\t\t\t\t\t\t\t\tresolvedProjectIdentity: target.projectIdentity,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t(draft) => detailResponse(store, draft),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} finally {\n\t\t\t\treleaseMutation();\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst code = apiErrorCode(error);\n\t\t\treturn c.json({ error: code }, errorStatus(code));\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/team-setup/v1/:candidateRef/refresh\", async (c) => {\n\t\tconst candidateRef = c.req.param(\"candidateRef\");\n\t\tif (!CANDIDATE_REF_PATTERN.test(candidateRef)) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\tconst parsed = await parseBoundedJsonObject(c);\n\t\tif (!parsed.ok || !hasExactKeys(parsed.value, [])) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\tlet store: MemoryStore;\n\t\ttry {\n\t\t\tstore = options.getStore();\n\t\t\tconst currentDraft = getLegacyTeamSetupDraft(store.db, candidateRef);\n\t\t\tif (currentDraft?.state === \"completed\" || hasCompletedLegacyTeamSetup(store, candidateRef)) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst code = apiErrorCode(error);\n\t\t\treturn c.json({ error: code }, errorStatus(code));\n\t\t}\n\t\tlet groups: LegacyTeamConfiguredGroupSnapshot[];\n\t\ttry {\n\t\t\tgroups = await loadMutableCandidateSnapshots(store, candidateRef, () =>\n\t\t\t\tloadedCandidateSnapshots(candidateRef),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconst code = apiErrorCode(error);\n\t\t\treturn c.json({ error: code }, errorStatus(code));\n\t\t}\n\t\tif (\n\t\t\tgroups.filter(\n\t\t\t\t(group) => legacyTeamCandidateId(group.coordinatorId, group.groupId) === candidateRef,\n\t\t\t).length === 0\n\t\t) {\n\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t}\n\t\ttry {\n\t\t\tconst releaseMutation = claimCandidateMutation(store.db, candidateRef);\n\t\t\tif (!releaseMutation) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn c.json(\n\t\t\t\t\tprojectMutationAtomically(\n\t\t\t\t\t\tstore,\n\t\t\t\t\t\t() => {\n\t\t\t\t\t\t\tconst currentDraft = getLegacyTeamSetupDraft(store.db, candidateRef);\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\tcurrentDraft?.state === \"completed\" ||\n\t\t\t\t\t\t\t\thasCompletedLegacyTeamSetup(store, candidateRef)\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tthrow new Error(\"team_setup_confirmation_stale\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn refreshLegacyTeamCandidate(\n\t\t\t\t\t\t\t\tstore.db,\n\t\t\t\t\t\t\t\t{ projection: projectionOptions(store), groups },\n\t\t\t\t\t\t\t\tcandidateRef,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t},\n\t\t\t\t\t\t(draft) => detailResponse(store, draft),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} finally {\n\t\t\t\treleaseMutation();\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst code = apiErrorCode(error);\n\t\t\treturn c.json({ error: code }, errorStatus(code));\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/team-setup/v1/:candidateRef/finish\", async (c) => {\n\t\tconst candidateRef = c.req.param(\"candidateRef\");\n\t\tif (!CANDIDATE_REF_PATTERN.test(candidateRef)) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\tconst parsed = await parseBoundedJsonObject(c);\n\t\tif (!parsed.ok) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\tconst finishKeys = [\n\t\t\t\"attemptId\",\n\t\t\t\"confirmedAccessDeltaDigest\",\n\t\t\t\"confirmedViewerAccessDeltaDigest\",\n\t\t\t\"finishDigest\",\n\t\t] as const;\n\t\tif (!hasExactKeys(parsed.value, finishKeys)) {\n\t\t\treturn Object.keys(parsed.value).every((key) =>\n\t\t\t\tfinishKeys.includes(key as (typeof finishKeys)[number]),\n\t\t\t)\n\t\t\t\t? c.json({ error: \"team_setup_confirmation_stale\" as const }, 409)\n\t\t\t\t: c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\tconst {\n\t\t\tattemptId,\n\t\t\tconfirmedAccessDeltaDigest,\n\t\t\tconfirmedViewerAccessDeltaDigest,\n\t\t\tfinishDigest,\n\t\t} = parsed.value;\n\t\tif (\n\t\t\ttypeof attemptId !== \"string\" ||\n\t\t\t!ATTEMPT_ID_PATTERN.test(attemptId) ||\n\t\t\ttypeof finishDigest !== \"string\" ||\n\t\t\t!FINISH_DIGEST_PATTERN.test(finishDigest) ||\n\t\t\ttypeof confirmedAccessDeltaDigest !== \"string\" ||\n\t\t\t!ACCESS_DELTA_DIGEST_PATTERN.test(confirmedAccessDeltaDigest) ||\n\t\t\ttypeof confirmedViewerAccessDeltaDigest !== \"string\" ||\n\t\t\t!VIEWER_ACCESS_DELTA_DIGEST_PATTERN.test(confirmedViewerAccessDeltaDigest)\n\t\t) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\tlet releaseMutation: (() => void) | undefined;\n\t\tlet releasePublicationMutation: (() => void) | undefined;\n\t\tlet releaseActorMutations: (() => void) | undefined;\n\t\ttry {\n\t\t\tconst store = options.getStore();\n\t\t\tconst draft = getLegacyTeamSetupDraft(store.db, candidateRef);\n\t\t\tif (!draft) return c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\tif (draft.state !== \"completed\" && hasCompletedLegacyTeamSetup(store, candidateRef)) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tif (draft.attemptId !== attemptId) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tconst replay = replayLegacyTeamSetupActivation(store.db, {\n\t\t\t\tcandidateRef,\n\t\t\t\tattemptId,\n\t\t\t\tfinishDigest,\n\t\t\t\tconfirmedAccessDeltaDigest,\n\t\t\t});\n\t\t\tif (replay) return c.json(finishResponse(candidateRef, replay));\n\t\t\tif (draft.state === \"completed\") {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tconst preview = previewLegacyTeamSetupActivation(store.db, {\n\t\t\t\tcandidateRef,\n\t\t\t\tattemptId: draft.attemptId,\n\t\t\t});\n\t\t\trequireLegacyTeamSetupAccessDeltaWithinLimit(preview.accessDelta);\n\t\t\tconst safeDraft = viewerSafeDraft(store, draft);\n\t\t\tconst currentViewerDigest = viewerAccessDeltaDigest(\n\t\t\t\tviewerSafeAccessDelta(candidateRef, preview.accessDelta, {\n\t\t\t\t\tteamDisplayName: draft.displayName,\n\t\t\t\t\t...safeDraft,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tif (currentViewerDigest !== confirmedViewerAccessDeltaDigest) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tconst freshGroups = await loadedCandidateSnapshots(candidateRef);\n\t\t\tconst matchingGroups = freshGroups.filter(\n\t\t\t\t(group) => legacyTeamCandidateId(group.coordinatorId, group.groupId) === candidateRef,\n\t\t\t);\n\t\t\tif (matchingGroups.length !== 1) throw safeCoordinatorError();\n\t\t\tconst group = matchingGroups[0];\n\t\t\tif (!group) throw safeCoordinatorError();\n\t\t\treleaseMutation = claimCandidateMutation(store.db, candidateRef) ?? undefined;\n\t\t\tif (!releaseMutation) {\n\t\t\t\t// An identical request may be committing right now. Wait for it and\n\t\t\t\t// return its immutable result instead of a stale-confirmation error.\n\t\t\t\tawait candidateMutationSettled(store.db, candidateRef);\n\t\t\t\tconst overlappingReplay = replayLegacyTeamSetupActivation(store.db, {\n\t\t\t\t\tcandidateRef,\n\t\t\t\t\tattemptId,\n\t\t\t\t\tfinishDigest,\n\t\t\t\t\tconfirmedAccessDeltaDigest,\n\t\t\t\t});\n\t\t\t\tif (overlappingReplay) return c.json(finishResponse(candidateRef, overlappingReplay));\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\t// The pre-claim replay lookup raced an in-flight commit; recheck under the claim.\n\t\t\tconst claimedReplay = replayLegacyTeamSetupActivation(store.db, {\n\t\t\t\tcandidateRef,\n\t\t\t\tattemptId,\n\t\t\t\tfinishDigest,\n\t\t\t\tconfirmedAccessDeltaDigest,\n\t\t\t});\n\t\t\tif (claimedReplay) return c.json(finishResponse(candidateRef, claimedReplay));\n\t\t\tconst claimedDraft = getLegacyTeamSetupDraft(store.db, candidateRef);\n\t\t\tif (!claimedDraft || claimedDraft.attemptId !== attemptId) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tconst publicationDeadlineMs = Date.now() + COORDINATOR_ROSTER_READ_BUDGET_MS;\n\t\t\treleasePublicationMutation = await claimRecipientPolicyPublicationMutation(store.db);\n\t\t\t// Every identity the activation reads or writes is part of the immutable\n\t\t\t// publication winner: the target of each included device and the existing\n\t\t\t// assignment of every reviewed device (including excluded or removed ones,\n\t\t\t// whose current assignment the access delta depends on). These locks cover\n\t\t\t// coordinator creation, conflict recovery, and local application.\n\t\t\treleaseActorMutations = await claimRecipientPolicyActorMutations(\n\t\t\t\tstore.db,\n\t\t\t\tclaimedDraft.devices.flatMap((device) => [\n\t\t\t\t\t...(device.decision === \"included\" && device.targetIdentityId\n\t\t\t\t\t\t? [device.targetIdentityId]\n\t\t\t\t\t\t: []),\n\t\t\t\t\t...(device.existingIdentityId ? [device.existingIdentityId] : []),\n\t\t\t\t]),\n\t\t\t);\n\t\t\tconst response = await serializeRecipientPolicyTeamMutation(\n\t\t\t\tstore.db,\n\t\t\t\tdeterministicPolicyTeamId(candidateRef),\n\t\t\t\t() =>\n\t\t\t\t\tserializeRecipientPolicyCoordinatorGroupMutation(store.db, group.groupId, async () => {\n\t\t\t\t\t\tlet authorization: CompletionAuthorization | null;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tauthorization = currentCompletionAuthorization();\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tthrow new Error(completionApiError(error));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!completionDependencies || !authorization) {\n\t\t\t\t\t\t\tthrow new Error(\"team_setup_completion_unavailable\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!authorizesGroup(authorization, group)) {\n\t\t\t\t\t\t\tthrow new Error(\"team_setup_completion_invalid\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst { config, remoteUrl } = authorization;\n\t\t\t\t\t\tconst freshGroup = await loadFreshGroupSnapshot(\n\t\t\t\t\t\t\tgroup,\n\t\t\t\t\t\t\tremoteUrl,\n\t\t\t\t\t\t\tpublicationDeadlineMs,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (!freshGroup) throw new Error(\"team_setup_roster_unavailable\");\n\t\t\t\t\t\tif (!stillAuthorizesGroup(authorization, group)) {\n\t\t\t\t\t\t\tthrow new Error(\"team_setup_completion_invalid\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst projectInventory = legacyTeamCandidateProjectInventory(\n\t\t\t\t\t\t\tstore.db,\n\t\t\t\t\t\t\tprojectionOptions(store),\n\t\t\t\t\t\t\tcandidateRef,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst freshPreview = inspectFreshLegacyTeamSetupActivation(store.db, {\n\t\t\t\t\t\t\tcandidateRef,\n\t\t\t\t\t\t\tattemptId,\n\t\t\t\t\t\t\tfreshRoster: freshGroup.devices,\n\t\t\t\t\t\t\tprojectInventory,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tfreshPreview.finishDigest !== finishDigest ||\n\t\t\t\t\t\t\tfreshPreview.accessDeltaDigest !== confirmedAccessDeltaDigest\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst freshDraft = getLegacyTeamSetupDraft(store.db, candidateRef);\n\t\t\t\t\t\tif (!freshDraft || freshDraft.attemptId !== attemptId) {\n\t\t\t\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst safeFreshDraft = viewerSafeDraft(store, freshDraft);\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tviewerAccessDeltaDigest(\n\t\t\t\t\t\t\t\tviewerSafeAccessDelta(candidateRef, freshPreview.accessDelta, {\n\t\t\t\t\t\t\t\t\tteamDisplayName: freshDraft.displayName,\n\t\t\t\t\t\t\t\t\t...safeFreshDraft,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t) !== confirmedViewerAccessDeltaDigest\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst completedAt = new Date().toISOString();\n\t\t\t\t\t\tconst proposedManifest = deriveLegacyTeamSetupCompletionManifest(store.db, {\n\t\t\t\t\t\t\tcandidateRef,\n\t\t\t\t\t\t\tattemptId,\n\t\t\t\t\t\t\tcompletedAt,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst timeoutS = Math.max(1, config.syncCoordinatorTimeoutS);\n\t\t\t\t\t\tconst publicationTimeoutS = remainingCoordinatorTimeoutS(\n\t\t\t\t\t\t\ttimeoutS,\n\t\t\t\t\t\t\tpublicationDeadlineMs,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (publicationTimeoutS == null) {\n\t\t\t\t\t\t\tthrow new Error(\"team_setup_completion_unavailable\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlet canonicalManifest: typeof proposedManifest;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tcanonicalManifest = validateLegacyTeamSetupCompletionManifest(\n\t\t\t\t\t\t\t\t(\n\t\t\t\t\t\t\t\t\tawait completionDependencies.create({\n\t\t\t\t\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\t\t\t\t\tmanifest: proposedManifest,\n\t\t\t\t\t\t\t\t\t\tremoteUrl,\n\t\t\t\t\t\t\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret,\n\t\t\t\t\t\t\t\t\t\ttimeoutS: publicationTimeoutS,\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t).manifest,\n\t\t\t\t\t\t\t\t{ coordinatorId: group.coordinatorId, groupId: group.groupId },\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\tcanonicalCoordinatorLegacyTeamCompletionManifestJson(canonicalManifest) !==\n\t\t\t\t\t\t\t\tcanonicalCoordinatorLegacyTeamCompletionManifestJson(proposedManifest)\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tthrow new Error(\"team_setup_completion_conflict\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tconst code = completionApiError(error);\n\t\t\t\t\t\t\tconst getCompletion = completionDependencies.get;\n\t\t\t\t\t\t\tif (code !== \"team_setup_completion_conflict\" || !getCompletion) {\n\t\t\t\t\t\t\t\tthrow new Error(code);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tconst existing = await retryTransientCoordinatorRead(\n\t\t\t\t\t\t\t\t\t(attemptTimeoutS) =>\n\t\t\t\t\t\t\t\t\t\tgetCompletion({\n\t\t\t\t\t\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\t\t\t\t\t\tcandidateRef,\n\t\t\t\t\t\t\t\t\t\t\tremoteUrl,\n\t\t\t\t\t\t\t\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret,\n\t\t\t\t\t\t\t\t\t\t\ttimeoutS: attemptTimeoutS,\n\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\ttimeoutS,\n\t\t\t\t\t\t\t\t\tpublicationDeadlineMs,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tif (!existing) throw new Error(\"team_setup_completion_conflict\");\n\t\t\t\t\t\t\t\tcanonicalManifest = validateLegacyTeamSetupCompletionManifest(existing, {\n\t\t\t\t\t\t\t\t\tcoordinatorId: group.coordinatorId,\n\t\t\t\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t// A conflict can mean an earlier request committed before its response was lost.\n\t\t\t\t\t\t\t\t// The matching policy digest identifies that winner; its publication timestamp\n\t\t\t\t\t\t\t\t// is coordinator-owned metadata and must be applied unchanged.\n\t\t\t\t\t\t\t\tif (canonicalManifest.finish_digest !== proposedManifest.finish_digest) {\n\t\t\t\t\t\t\t\t\tthrow new Error(\"team_setup_completion_conflict\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} catch (recoveryError) {\n\t\t\t\t\t\t\t\tthrow new Error(completionApiError(recoveryError));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Publication is the commit point. Apply its immutable winner after binding\n\t\t\t\t\t\t// each included device to the current coordinator roster evidence.\n\t\t\t\t\t\t// If this reload fails, reconciliation can apply the published winner later.\n\t\t\t\t\t\tlet postPublicationGroup: LegacyTeamConfiguredGroupSnapshot | undefined;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tpostPublicationGroup = await loadFreshGroupSnapshot(\n\t\t\t\t\t\t\t\tgroup,\n\t\t\t\t\t\t\t\tremoteUrl,\n\t\t\t\t\t\t\t\tpublicationDeadlineMs,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tif (legacyTeamSetupApiErrorCode(error) === \"team_setup_completion_invalid\") {\n\t\t\t\t\t\t\t\tthrow new Error(\"team_setup_roster_unavailable\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!postPublicationGroup) throw new Error(\"team_setup_roster_unavailable\");\n\t\t\t\t\t\tconst result = await applyLegacyTeamSetupCompletionManifestAndReturnActivation(\n\t\t\t\t\t\t\tstore.db,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcoordinatorId: group.coordinatorId,\n\t\t\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\t\t\tfreshRoster: postPublicationGroup.devices,\n\t\t\t\t\t\t\t\tmanifest: canonicalManifest,\n\t\t\t\t\t\t\t\texpectedDraftManifest: proposedManifest,\n\t\t\t\t\t\t\t\trecipientPolicyLocksHeld: {\n\t\t\t\t\t\t\t\t\tpublication: true,\n\t\t\t\t\t\t\t\t\tteam: true,\n\t\t\t\t\t\t\t\t\tcoordinatorGroup: true,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn c.json(finishResponse(candidateRef, result));\n\t\t\t\t\t}),\n\t\t\t);\n\t\t\treturn response;\n\t\t} catch (error) {\n\t\t\tconst code = apiErrorCode(error);\n\t\t\treturn c.json({ error: code }, errorStatus(code));\n\t\t} finally {\n\t\t\treleaseActorMutations?.();\n\t\t\treleasePublicationMutation?.();\n\t\t\treleaseMutation?.();\n\t\t}\n\t});\n\n\treturn app;\n}\n","/**\n * Sync routes — status, peers, actors, attempts, pairing, mutations.\n */\n\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { readFileSync } from \"node:fs\";\nimport { hostname, networkInterfaces } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport type {\n\tCoordinatorBootstrapGrantVerification,\n\tCoordinatorConsumedTeamInvite,\n\tCoordinatorEnrollment,\n\tCoordinatorEnrollmentReconcileResult,\n\tCoordinatorScope,\n\tCoordinatorScopeMembership,\n\tDeviceIdentityBindingCommitRequestV1,\n\tDeviceIdentityBindingPreviewRequestV1,\n\tDeviceIdentityCoordinatorEvidence,\n\tMaintenanceJobSnapshot,\n\tMemoryStore,\n\tProjectScopeGuardrailWarning,\n\tReassignScopeCapability,\n\tRecipientPolicyCoordinatorEffectReceipt,\n\tRecipientPolicyOnboardingPreviewV1,\n\tRecipientPolicyPeerCapability,\n\tRecipientPolicyReconcileResult,\n\tRecipientPolicyReconcilerEffects,\n\tRecipientPolicyReviewDecisionV1,\n\tRecipientPolicyReviewResolveRequestV1,\n\tRecipientReviewedIntentV1,\n\tReplicationOp,\n\tSemanticIndexDiagnostics,\n\tShareOperationLifecycleStepInput,\n\tShareOperationPlan,\n\tSharePersonIntent,\n\tShareProjectIntent,\n} from \"@codemem/core\";\nimport {\n\tACCESS_CLEANUP_OP_TYPE,\n\taddSyncScopeToBoundary,\n\tanalyzeProjectScopeMappingChangeGuardrails,\n\tapplyReplicationOps,\n\tbuildAuthHeaders,\n\tbuildBaseUrl,\n\tbuildDirectPeerAuthHeaders,\n\tCoordinatorReciprocalApprovalRequestChangedError,\n\tcanonicalWorkspaceIdentity,\n\tclaimRecipientPolicyActorMutations,\n\tclaimRecipientPolicyPublicationMutation,\n\tcleanupNonces,\n\tcommitDeviceIdentityBindings,\n\tcommitRecipientPolicyEdges,\n\tcoordinatorArchiveGroupAction,\n\tcoordinatorCreateAddDeviceInviteAction,\n\tcoordinatorCreateGroupAction,\n\tcoordinatorCreateInviteAction,\n\tcoordinatorCreateScopeAction,\n\tcoordinatorDisableDeviceAction,\n\tcoordinatorEnableDeviceAction,\n\tcoordinatorGrantScopeMembershipAction,\n\tcoordinatorImportInviteAction,\n\tcoordinatorListBootstrapGrantsAction,\n\tcoordinatorListConsumedTeamInvitesAction,\n\tcoordinatorListDevicesAction,\n\tcoordinatorListGroupsAction,\n\tcoordinatorListJoinRequestsAction,\n\tcoordinatorListReviewedRecipientInviteEvidenceAction,\n\tcoordinatorListScopeMembershipsAction,\n\tcoordinatorListScopesAction,\n\tcoordinatorRemoveDeviceAction,\n\tcoordinatorRenameDeviceAction,\n\tcoordinatorRenameGroupAction,\n\tcoordinatorReviewJoinRequestAction,\n\tcoordinatorRevokeBootstrapGrantAction,\n\tcoordinatorRevokeScopeMembershipAction,\n\tcoordinatorStatusSnapshot,\n\tcoordinatorUnarchiveGroupAction,\n\tcoordinatorUpdateScopeAction,\n\tcountShareableProjectMemories,\n\tcreateCoordinatorReciprocalApproval,\n\tDEFAULT_TIME_WINDOW_S,\n\tdecodeInvitePayload,\n\tdefaultSpaceScopeIdForGroup,\n\tdeleteProjectScopeSettingsMapping,\n\tdiagnoseStalePeerReceivedRows,\n\tensureDeviceIdentity,\n\texecuteShareProvisioning,\n\textractInvitePayload,\n\textractReplicationOps,\n\ttype FilterReplicationSkipped,\n\tfilterReplicationOpsForSyncWithStatus,\n\tfingerprintPublicKey,\n\tformatHostPort,\n\tfriendlyDeviceName,\n\tgetCoordinatorEnrollmentReconciliationIssueSummary,\n\tgetCoordinatorGroupPreference,\n\tgetRecipientPolicyAuthorityState,\n\tgetSemanticIndexDiagnostics,\n\tgetSyncResetState,\n\ttype InboundScopeRejectionPeerSummary,\n\tinviteTokenDigest,\n\tisPeerTrustBindingCompatible,\n\tisProjectSyncEnablementError,\n\tisScopedSyncCapability,\n\tLEGACY_SHARED_REVIEW_SCOPE_ID,\n\tLOCAL_DEFAULT_SCOPE_ID,\n\tLOCAL_SYNC_CAPABILITY,\n\tLOCAL_SYNC_FEATURES,\n\tlistAuthorizedScopesForPeer,\n\tlistCoordinatorJoinRequests,\n\tlistDeviceIdentityInventory,\n\tlistInboundScopeRejections,\n\tlistLegacyRecipientPolicyProjections,\n\tlistMaintenanceJobs,\n\tlistPerPeerScopeSyncState,\n\tlistProjectScopeCandidates,\n\tlistProjectScopeInventory,\n\tlistProjectScopeSettingsMappings,\n\tlistRecipientPolicyIntent,\n\tlistRecipientPolicyReview,\n\tlistSharingDomainSettingsScopes,\n\tloadMemorySnapshotPageForPeer,\n\tloadReplicationOpsForPeer,\n\tlookupCoordinatorPeers,\n\tmergeAddresses,\n\tmigrateRecipientPolicyIntent,\n\tnegotiateSyncCapability,\n\tnormalizeAddress,\n\tnormalizeHumanPresentationName,\n\tnormalizeSyncCapability,\n\tnormalizeSyncFeatures,\n\tnormalizeTeammateName,\n\tparseAcceptedProjectIntent,\n\tparseReassignScopePayload,\n\tparseRecipientPolicyEdgeCommitRequest,\n\tparseSyncScopeRequest,\n\tpersistShareOperation,\n\tpersonalScopeGrantStatusForPeer,\n\tplanShareOperation,\n\tpreviewDeviceIdentityBindings,\n\tpreviewRecipientPolicyEdges,\n\tpreviewRecipientPolicyOnboarding,\n\tpreviewRecipientPolicyOnboardingFromReviewedIntent,\n\tprojectShareLifecycle,\n\tRecipientPolicyEdgeRequestError,\n\tRecipientPolicyTeamRenameError,\n\treadCodememConfigFile,\n\treadCoordinatorSyncConfig,\n\treassignProjectScopeInventoryProject,\n\trecipientInviteAuthoritativeIdentityId,\n\trecipientReviewedIntentDigest,\n\treconcileCoordinatorEnrollmentSnapshot,\n\treconcileRecipientPolicyProject,\n\treconcileShareOperationAcceptance,\n\trecordHighestObservedDirectSignatureVersion,\n\trecordNonce,\n\trefreshAuthorizedCoordinatorPeerTrust,\n\trefreshConfiguredScopeMembershipCache,\n\trejectInboundScopeFailures,\n\trenameRecipientPolicyTeam,\n\trequestJson,\n\tresolveRecipientPolicyReview,\n\tresolveRecipientPolicyReviewBulk,\n\trunSyncPass,\n\tSCOPE_MEMBERSHIP_REVOCATION_LIMITATION,\n\tSYNC_AUTHORIZATION_REFRESH_HEADER,\n\tSYNC_CAPABILITY_HEADER,\n\tSYNC_FEATURES_HEADER,\n\tSYNC_SCOPE_QUERY_PARAM,\n\tschema,\n\tserializeRecipientPolicyTeamMutation,\n\tsummarizeInboundScopeRejections,\n\tsupportsSyncFeature,\n\tsyncScopeResetRequiredPayload,\n\tupdatePeerAddresses,\n\tupsertCoordinatorGroupPreference,\n\tupsertProjectScopeSettingsMapping,\n\tVERSION,\n\tverifyDirectPeerSignature,\n\tverifyRecipientReviewedIntent,\n\tverifySignature,\n\twriteCodememConfigFile,\n} from \"@codemem/core\";\nimport { and, count, desc, eq, max, ne } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport { type Context, Hono } from \"hono\";\nimport { queryBool, queryInt, safeJsonList } from \"../helpers.js\";\nimport type { InMemoryRequestRateLimiter } from \"../request-rate-limit.js\";\nimport { legacyTeamCandidateGroupDescriptors, normalizedCoordinatorId } from \"./team-setup.js\";\n\ntype StoreFactory = () => MemoryStore;\nexport type DeviceIdentityCoordinatorEvidenceLoader =\n\t() => Promise<DeviceIdentityCoordinatorEvidence>;\nexport interface SyncRoutesOptions {\n\tloadDeviceIdentityCoordinatorEvidence?: DeviceIdentityCoordinatorEvidenceLoader;\n\tonRecipientPolicyTeamRenamed?: () => void;\n\treadCoordinatorConfig?: typeof readCoordinatorSyncConfig;\n\trenameCoordinatorGroup?: typeof coordinatorRenameGroupAction;\n}\ntype SyncRuntimeStatus = {\n\tphase:\n\t\t| \"starting\"\n\t\t| \"running\"\n\t\t| \"stopping\"\n\t\t| \"error\"\n\t\t| \"disabled\"\n\t\t| \"rebootstrapping\"\n\t\t| \"needs_attention\"\n\t\t| null;\n\tdetail?: string | null;\n};\n\ntype SafeSkippedSyncDetail = Pick<\n\tFilterReplicationSkipped,\n\t\"reason\" | \"skipped_count\" | \"scope_id\" | \"project\" | \"visibility\"\n>;\n\nfunction safeSkippedSyncDetail(\n\tdetail: FilterReplicationSkipped | null | undefined,\n): SafeSkippedSyncDetail | null {\n\tif (!detail) return null;\n\treturn {\n\t\treason: detail.reason,\n\t\tskipped_count: detail.skipped_count,\n\t\tscope_id: detail.scope_id ?? null,\n\t\tproject: detail.project ?? null,\n\t\tvisibility: detail.visibility ?? null,\n\t};\n}\n\ninterface SyncProtocolRouteOptions {\n\trouteRateLimit?: {\n\t\tlimiter: InMemoryRequestRateLimiter;\n\t\treadLimit: number;\n\t\tmutationLimit: number;\n\t\tunauthenticatedReadLimit: number;\n\t\tunauthenticatedMutationLimit: number;\n\t};\n}\n\nconst SYNC_STALE_AFTER_SECONDS = 10 * 60;\nconst SYNC_PROTOCOL_VERSION = \"2\";\nconst LEGACY_SYNC_ACTOR_DISPLAY_NAME = \"Legacy synced peer\";\nconst LEGACY_SHARED_WORKSPACE_ID = \"shared:legacy\";\n\n/**\n * Attempt to decode a pasted string as a device-pairing payload.\n *\n * Returns:\n * - `{ kind: \"pair\", ... }` when the payload base64-decodes to JSON with\n * the expected pairing shape AND the fingerprint matches the public\n * key.\n * - `{ kind: \"invalid-pair\", error }` when the payload looked like a\n * pairing payload but failed validation — the caller should 400 this\n * rather than falling back to coordinator-invite handling.\n * - `null` when the string is not a pairing payload at all.\n */\nfunction tryParsePairingPayload(value: string):\n\t| {\n\t\t\tkind: \"pair\";\n\t\t\tdevice_id: string;\n\t\t\tfingerprint: string;\n\t\t\tpublic_key: string;\n\t\t\taddresses: string[];\n\t }\n\t| { kind: \"invalid-pair\"; error: string }\n\t| null {\n\t// Accept both shapes the CLI can emit:\n\t// - raw JSON (`codemem sync pair --payload-only`)\n\t// - base64-encoded JSON (the inner blob inside the shell pipe wrapper)\n\tlet parsed: Record<string, unknown>;\n\tif (value.trimStart().startsWith(\"{\")) {\n\t\ttry {\n\t\t\tparsed = JSON.parse(value) as Record<string, unknown>;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t} else {\n\t\tlet decoded: string;\n\t\ttry {\n\t\t\tdecoded = Buffer.from(value, \"base64\").toString(\"utf8\");\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t\tif (!decoded?.trimStart().startsWith(\"{\")) return null;\n\t\ttry {\n\t\t\tparsed = JSON.parse(decoded) as Record<string, unknown>;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\tconst deviceId = String(parsed.device_id ?? \"\").trim();\n\tconst fingerprint = String(parsed.fingerprint ?? \"\").trim();\n\tconst publicKey = String(parsed.public_key ?? \"\").trim();\n\t// If the JSON doesn't carry any of the pairing discriminators, treat\n\t// it as a different kind of payload (e.g. a coordinator invite happened\n\t// to be JSON-encoded directly). Let the caller keep trying.\n\tif (!deviceId && !fingerprint && !publicKey) return null;\n\tconst rawAddresses = Array.isArray(parsed.addresses) ? parsed.addresses : [];\n\tconst addresses = rawAddresses\n\t\t.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0)\n\t\t.map((item) => item.trim());\n\tif (!deviceId || !fingerprint || !publicKey || addresses.length === 0) {\n\t\treturn {\n\t\t\tkind: \"invalid-pair\",\n\t\t\terror: \"Pairing payload missing device_id, fingerprint, public_key, or addresses\",\n\t\t};\n\t}\n\tif (fingerprintPublicKey(publicKey) !== fingerprint) {\n\t\treturn { kind: \"invalid-pair\", error: \"Pairing payload fingerprint mismatch\" };\n\t}\n\treturn {\n\t\tkind: \"pair\",\n\t\tdevice_id: deviceId,\n\t\tfingerprint,\n\t\tpublic_key: publicKey,\n\t\taddresses,\n\t};\n}\n\ntype CoordinatorAdminReadiness = \"not_configured\" | \"partial\" | \"ready\";\n\nfunction coordinatorAdminStatusPayload(config = readCoordinatorSyncConfig()) {\n\tconst groups = config.syncCoordinatorGroups;\n\tconst activeGroup = groups[0] ?? null;\n\tconst hasUrl = Boolean(config.syncCoordinatorUrl);\n\tconst hasGroups = groups.length > 0;\n\tconst hasAdminSecret = Boolean(config.syncCoordinatorAdminSecret);\n\tlet readiness: CoordinatorAdminReadiness = \"ready\";\n\tif (!hasUrl) readiness = \"not_configured\";\n\telse if (!hasGroups || !hasAdminSecret) readiness = \"partial\";\n\treturn {\n\t\treadiness,\n\t\tcoordinator_url: config.syncCoordinatorUrl || null,\n\t\tgroups,\n\t\tactive_group: activeGroup,\n\t\thas_admin_secret: hasAdminSecret,\n\t\thas_groups: hasGroups,\n\t};\n}\n\nasync function ensureDefaultSpaceForTeam(opts: {\n\tstore: MemoryStore;\n\tconfig: ReturnType<typeof readCoordinatorSyncConfig>;\n\tgroupId: string;\n\tdisplayName: string | null;\n}): Promise<{\n\tscope: CoordinatorScope | null;\n\tmembership: CoordinatorScopeMembership | null;\n\tpreferences: ReturnType<typeof upsertCoordinatorGroupPreference>;\n}> {\n\tconst coordinatorId = opts.config.syncCoordinatorUrl || null;\n\tif (!coordinatorId) throw new Error(\"coordinator_not_configured\");\n\tconst scopeId = defaultSpaceScopeIdForGroup(opts.groupId);\n\tconst label = opts.displayName || opts.groupId;\n\tconst existingScopes = await coordinatorListScopesAction({\n\t\tgroupId: opts.groupId,\n\t\tincludeInactive: false,\n\t\tremoteUrl: opts.config.syncCoordinatorUrl || null,\n\t\tadminSecret: opts.config.syncCoordinatorAdminSecret || null,\n\t});\n\tconst existingScope = existingScopes.find((scope) => scope.scope_id === scopeId) ?? null;\n\tconst scope =\n\t\texistingScope ??\n\t\t(await coordinatorCreateScopeAction({\n\t\t\tgroupId: opts.groupId,\n\t\t\tscopeId,\n\t\t\tlabel,\n\t\t\tkind: \"team_default\",\n\t\t\tauthorityType: \"coordinator\",\n\t\t\tcoordinatorId,\n\t\t\tmembershipEpoch: 1,\n\t\t\tstatus: \"active\",\n\t\t\tremoteUrl: opts.config.syncCoordinatorUrl || null,\n\t\t\tadminSecret: opts.config.syncCoordinatorAdminSecret || null,\n\t\t}));\n\tconst [deviceId] = ensureDeviceIdentity(opts.store.db, { keysDir: syncKeysDir() });\n\tconst membership = await coordinatorGrantScopeMembershipAction({\n\t\teffectId: `team-default-grant:${opts.groupId}:${scopeId}:${deviceId}:1`,\n\t\tgroupId: opts.groupId,\n\t\tscopeId,\n\t\tdeviceId,\n\t\trole: \"admin\",\n\t\tmembershipEpoch: 1,\n\t\tcoordinatorId,\n\t\tremoteUrl: opts.config.syncCoordinatorUrl || null,\n\t\tadminSecret: opts.config.syncCoordinatorAdminSecret || null,\n\t});\n\tconst preferences = upsertCoordinatorGroupPreference(opts.store.db, {\n\t\tcoordinator_id: coordinatorId,\n\t\tgroup_id: opts.groupId,\n\t\tdefault_space_scope_id: scopeId,\n\t\tauto_grant_default_space_on_join: true,\n\t});\n\treturn { scope, membership, preferences };\n}\n\nasync function maybeGrantDefaultSpaceOnJoin(opts: {\n\tstore: MemoryStore;\n\tconfig: ReturnType<typeof readCoordinatorSyncConfig>;\n\tgroupId: string;\n\trequestId: string;\n\tdeviceId: string;\n}): Promise<CoordinatorScopeMembership | null> {\n\tconst coordinatorId = opts.config.syncCoordinatorUrl || null;\n\tif (!coordinatorId) return null;\n\tconst preferences = getCoordinatorGroupPreference(opts.store.db, coordinatorId, opts.groupId);\n\tif (!preferences?.auto_grant_default_space_on_join) return null;\n\tconst scopeId = preferences.default_space_scope_id?.trim();\n\tif (!scopeId) return null;\n\tif (scopeId !== defaultSpaceScopeIdForGroup(opts.groupId)) return null;\n\tconst scopes = await coordinatorListScopesAction({\n\t\tgroupId: opts.groupId,\n\t\tincludeInactive: false,\n\t\tremoteUrl: opts.config.syncCoordinatorUrl || null,\n\t\tadminSecret: opts.config.syncCoordinatorAdminSecret || null,\n\t});\n\tconst defaultScope = scopes.find((scope) => scope.scope_id === scopeId) ?? null;\n\tif (defaultScope?.kind !== \"team_default\") return null;\n\treturn await coordinatorGrantScopeMembershipAction({\n\t\teffectId: `team-default-join:${opts.requestId}:${scopeId}:${opts.deviceId}:1`,\n\t\tgroupId: opts.groupId,\n\t\tscopeId,\n\t\tdeviceId: opts.deviceId,\n\t\trole: \"member\",\n\t\tmembershipEpoch: 1,\n\t\tcoordinatorId,\n\t\tremoteUrl: opts.config.syncCoordinatorUrl || null,\n\t\tadminSecret: opts.config.syncCoordinatorAdminSecret || null,\n\t});\n}\n\nfunction removeConfiguredCoordinatorGroup(groupId: string): string[] {\n\tconst targetGroup = groupId.trim();\n\tif (!targetGroup) return [];\n\tconst config = readCodememConfigFile();\n\tconst rawGroups = config.sync_coordinator_groups;\n\tconst groups = Array.isArray(rawGroups)\n\t\t? rawGroups.map((group) => String(group).trim()).filter(Boolean)\n\t\t: typeof rawGroups === \"string\"\n\t\t\t? rawGroups\n\t\t\t\t\t.split(\",\")\n\t\t\t\t\t.map((group) => group.trim())\n\t\t\t\t\t.filter(Boolean)\n\t\t\t: typeof config.sync_coordinator_group === \"string\" && config.sync_coordinator_group.trim()\n\t\t\t\t? [config.sync_coordinator_group.trim()]\n\t\t\t\t: [];\n\tconst nextGroups = groups.filter((group) => group !== targetGroup);\n\tif (nextGroups.length === groups.length) return groups;\n\tconfig.sync_coordinator_groups = nextGroups;\n\tif (nextGroups.length) config.sync_coordinator_group = nextGroups[0];\n\telse delete config.sync_coordinator_group;\n\twriteCodememConfigFile(config);\n\treturn nextGroups;\n}\n\nfunction coordinatorAdminUnavailable(status: ReturnType<typeof coordinatorAdminStatusPayload>): {\n\tbody: Record<string, unknown>;\n\thttpStatus: 400;\n} | null {\n\tif (status.readiness === \"not_configured\") {\n\t\treturn { body: { error: \"coordinator_not_configured\", status }, httpStatus: 400 };\n\t}\n\tif (!status.has_admin_secret) {\n\t\treturn { body: { error: \"coordinator_admin_secret_missing\", status }, httpStatus: 400 };\n\t}\n\treturn null;\n}\n\nfunction recipientInviteCreationUnavailable(\n\tstatus: ReturnType<typeof coordinatorAdminStatusPayload>,\n\tkind: RecipientInviteKind,\n): { body: Record<string, unknown>; httpStatus: 400 } | null {\n\tif (status.readiness === \"not_configured\") {\n\t\treturn { body: { error: \"coordinator_not_configured\", status }, httpStatus: 400 };\n\t}\n\tif (!status.has_groups) {\n\t\treturn { body: { error: \"coordinator_group_missing\", status }, httpStatus: 400 };\n\t}\n\tif (kind === \"team_member\" && !status.has_admin_secret) {\n\t\treturn { body: { error: \"coordinator_admin_secret_missing\", status }, httpStatus: 400 };\n\t}\n\treturn null;\n}\n\nasync function parseViewerJsonBody(\n\tc: Context,\n\toptions: { allowEmpty?: boolean } = {},\n): Promise<Record<string, unknown> | null> {\n\tconst raw = await c.req.text();\n\tif (!raw.trim()) return options.allowEmpty ? {} : null;\n\ttry {\n\t\tconst parsed = JSON.parse(raw) as unknown;\n\t\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) return null;\n\t\treturn parsed as Record<string, unknown>;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction optionalViewerString(body: Record<string, unknown>, key: string): string | null {\n\tconst value = body[key];\n\tif (value == null) return null;\n\treturn String(value).trim() || null;\n}\n\nfunction optionalViewerStrictString(body: Record<string, unknown>, key: string): string | null {\n\tconst value = body[key];\n\tif (value == null) return null;\n\tif (typeof value !== \"string\") throw new Error(`${key} must be string`);\n\treturn value.trim() || null;\n}\n\nfunction optionalViewerStringList(body: Record<string, unknown>, key: string): string[] {\n\tconst value = body[key];\n\tif (value == null) return [];\n\tif (!Array.isArray(value)) throw new Error(`${key} must be an array of strings`);\n\treturn [\n\t\t...new Set(\n\t\t\tvalue\n\t\t\t\t.map((item) => {\n\t\t\t\t\tif (typeof item !== \"string\") throw new Error(`${key} must be an array of strings`);\n\t\t\t\t\treturn item.trim();\n\t\t\t\t})\n\t\t\t\t.filter(Boolean),\n\t\t),\n\t];\n}\n\nfunction optionalViewerNumber(body: Record<string, unknown>, key: string): number | null {\n\tconst value = body[key];\n\tif (value == null || value === \"\") return null;\n\tconst number = typeof value === \"number\" ? value : Number(value);\n\treturn Number.isFinite(number) ? Math.trunc(number) : Number.NaN;\n}\n\nfunction coordinatorAdminMembershipEffectId(\n\taction: \"grant\" | \"revoke\",\n\tattemptId: string,\n\tinput: {\n\t\tgroupId: string;\n\t\tscopeId: string;\n\t\tdeviceId: string;\n\t\trole?: string | null;\n\t\tmembershipEpoch: number | null;\n\t\tcoordinatorId?: string | null;\n\t\tmanifestIssuerDeviceId?: string | null;\n\t\tmanifestHash: string | null;\n\t\tsignedManifestJson: string | null;\n\t},\n): string {\n\tconst fingerprint = createHash(\"sha256\")\n\t\t.update(\n\t\t\tJSON.stringify({\n\t\t\t\taction,\n\t\t\t\tattemptId,\n\t\t\t\tgroupId: input.groupId,\n\t\t\t\tscopeId: input.scopeId,\n\t\t\t\tdeviceId: input.deviceId,\n\t\t\t\trole: input.role ?? null,\n\t\t\t\tmembershipEpoch: input.membershipEpoch,\n\t\t\t\tcoordinatorId: input.coordinatorId ?? null,\n\t\t\t\tmanifestIssuerDeviceId: input.manifestIssuerDeviceId ?? null,\n\t\t\t\tmanifestHash: input.manifestHash,\n\t\t\t\tsignedManifestJson: input.signedManifestJson,\n\t\t\t}),\n\t\t)\n\t\t.digest(\"hex\");\n\treturn `viewer-admin-membership:${action}:${fingerprint}`;\n}\n\nfunction optionalViewerInteger(body: Record<string, unknown>, key: string): number | null {\n\tconst value = body[key];\n\tif (value == null || value === \"\") return null;\n\tconst number = typeof value === \"number\" ? value : Number(value);\n\treturn Number.isInteger(number) ? number : Number.NaN;\n}\n\nfunction missingGuardrailConfirmations(\n\twarnings: ProjectScopeGuardrailWarning[],\n\tconfirmedTokens: string[],\n): ProjectScopeGuardrailWarning[] {\n\tconst confirmed = new Set(confirmedTokens);\n\treturn warnings.filter(\n\t\t(warning) =>\n\t\t\twarning.requires_confirmation &&\n\t\t\t(!warning.confirmation_token || !confirmed.has(warning.confirmation_token)),\n\t);\n}\n\nfunction parseViewerProjectMappingInput(body: Record<string, unknown>) {\n\tconst id = optionalViewerInteger(body, \"id\");\n\tconst priority = optionalViewerInteger(body, \"priority\");\n\tif (Number.isNaN(id)) throw new Error(\"id must be an integer\");\n\tif (Number.isNaN(priority)) throw new Error(\"priority must be an integer\");\n\treturn {\n\t\tid,\n\t\tworkspace_identity: optionalViewerStrictString(body, \"workspace_identity\"),\n\t\tproject_pattern: optionalViewerStrictString(body, \"project_pattern\"),\n\t\tscope_id: optionalViewerStrictString(body, \"scope_id\") ?? \"\",\n\t\tpriority,\n\t\tsource: optionalViewerStrictString(body, \"source\") ?? \"user\",\n\t};\n}\n\nfunction coordinatorAdminMutationStatus(message: string): 400 | 404 | 409 | 502 {\n\tif (\n\t\tmessage.includes(\"scope_not_found\") ||\n\t\tmessage.includes(\"membership_not_found\") ||\n\t\tmessage.includes(\"group_not_found\") ||\n\t\tmessage.includes(\"Group not found\") ||\n\t\tmessage.includes(\"Scope not found\") ||\n\t\tmessage.includes(\"device_not_enrolled_for_scope_group\") ||\n\t\tmessage.includes(\"device must be enrolled\")\n\t) {\n\t\treturn 404;\n\t}\n\tif (\n\t\tmessage.includes(\"not active\") ||\n\t\tmessage.includes(\"scope_not_active\") ||\n\t\tmessage.includes(\"scope_membership_effect_conflict\") ||\n\t\tmessage.includes(\"group_archived\") ||\n\t\tmessage.includes(\"Group is archived\")\n\t) {\n\t\treturn 409;\n\t}\n\tif (\n\t\tmessage.includes(\"Remote coordinator request failed (5\") ||\n\t\tmessage.includes(\"fetch failed\") ||\n\t\tmessage.includes(\"network\") ||\n\t\tmessage.includes(\"timed out\")\n\t) {\n\t\treturn 502;\n\t}\n\treturn 400;\n}\n\nfunction pairingAdvertiseAddresses(config = readCoordinatorSyncConfig()): string[] {\n\tconst advertise = String(config.syncAdvertise || \"auto\")\n\t\t.trim()\n\t\t.toLowerCase();\n\tif (advertise && advertise !== \"auto\" && advertise !== \"default\") {\n\t\treturn mergeAddresses(\n\t\t\t[],\n\t\t\tString(config.syncAdvertise || \"\")\n\t\t\t\t.split(\",\")\n\t\t\t\t.map((item) => item.trim())\n\t\t\t\t.filter(Boolean),\n\t\t\t{ defaultHttpPort: config.syncPort },\n\t\t);\n\t}\n\tif (config.syncHost && config.syncHost !== \"0.0.0.0\") {\n\t\treturn [normalizeAddress(formatHostPort(config.syncHost, config.syncPort))].filter(Boolean);\n\t}\n\tconst addresses = Object.values(networkInterfaces())\n\t\t.flatMap((entries) => entries ?? [])\n\t\t.filter((entry) => !entry.internal)\n\t\t.map((entry) => entry.address)\n\t\t.filter((address) => address && address !== \"127.0.0.1\" && address !== \"::1\")\n\t\t.map((address) => normalizeAddress(formatHostPort(address, config.syncPort)))\n\t\t.filter(Boolean);\n\treturn [...new Set(addresses)];\n}\n\nfunction resolveCoordinatorAdminGroup(\n\trequestedGroup: string | null | undefined,\n\tstatus: ReturnType<typeof coordinatorAdminStatusPayload>,\n): string | null {\n\tconst explicit = String(requestedGroup ?? \"\").trim();\n\tif (explicit) return explicit;\n\treturn status.active_group;\n}\n\nfunction parseInviteTtlHours(value: unknown): number | null {\n\tconst ttlHours = Number(String(value ?? 24));\n\tif (!Number.isInteger(ttlHours) || ttlHours < 1) return null;\n\treturn ttlHours;\n}\n\nfunction projectInviteAcceptanceFailure(error: unknown): {\n\terror: string;\n\tdetail: string;\n} {\n\tif (isProjectSyncEnablementError(error)) {\n\t\treturn { error: error.code, detail: error.detail };\n\t}\n\tconst code = error instanceof Error ? error.message : \"project_invite_acceptance_failed\";\n\tconst detailByCode: Record<string, string> = {\n\t\tinvite_already_bound:\n\t\t\t\"This invitation was accepted by another device. Ask the owner to create a new invitation.\",\n\t\tinvite_expired: \"This invitation expired. Ask the owner to create a new invitation.\",\n\t\tinvite_identity_conflict:\n\t\t\t\"This invitation does not match this Identity. Ask the owner to create a new invitation for this recipient.\",\n\t\tinvite_invalid: \"This invitation is no longer valid. Ask the owner to create a new invitation.\",\n\t\tinviter_identity_invalid:\n\t\t\t\"The owner's device identity could not be verified. Ask the owner to review the share and create a new invitation.\",\n\t\tproject_invite_self_acceptance_forbidden:\n\t\t\t\"The owner cannot accept this recipient invitation on the owner's device.\",\n\t\tproject_invite_bootstrap_incomplete:\n\t\t\t\"The owner's device is not ready to establish trust yet. Retry once, then ask the owner to review the share.\",\n\t\tproject_invite_trust_state_invalid:\n\t\t\t\"The owner's trust setup could not be verified. Ask the owner to review the share.\",\n\t\trecipient_display_name_invalid:\n\t\t\t\"Enter a human-readable Identity name instead of an internal identifier.\",\n\t\trecipient_display_name_required: \"Enter an Identity display name.\",\n\t\trecipient_display_name_too_long: \"Use an Identity display name with 120 characters or fewer.\",\n\t\tdevice_display_name_invalid:\n\t\t\t\"Enter a human-readable device name instead of an internal identifier.\",\n\t\tdevice_display_name_required: \"Enter a device display name.\",\n\t\tdevice_display_name_too_long: \"Use a device display name with 120 characters or fewer.\",\n\t};\n\tconst safeCode = Object.hasOwn(detailByCode, code) ? code : \"project_invite_acceptance_failed\";\n\treturn {\n\t\terror: safeCode,\n\t\tdetail:\n\t\t\tdetailByCode[code] ??\n\t\t\t\"The invitation could not be accepted safely. Retry once, then ask the owner to review the share.\",\n\t};\n}\n\nconst PROJECT_INVITE_TTL_HOURS = 7 * 24;\nconst PROJECT_INVITE_OWNER_FALLBACK = \"Project owner\";\nconst PROJECT_INVITE_BODY_KEYS = new Set([\n\t\"teammate_name\",\n\t\"project_ids\",\n\t\"reviewed_project_set_digest\",\n]);\n\nfunction projectInviteInviterDisplayName(value: string): string {\n\ttry {\n\t\treturn normalizeHumanPresentationName(value, \"inviter_display_name\");\n\t} catch {\n\t\treturn PROJECT_INVITE_OWNER_FALLBACK;\n\t}\n}\n\nfunction projectInviteStringList(body: Record<string, unknown>, key: string): string[] {\n\tconst value = body[key];\n\tif (!Array.isArray(value)) throw new Error(`${key}_must_be_string_array`);\n\tif (value.length > 100) throw new Error(`${key}_too_large`);\n\tconst items = value.map((item) => {\n\t\tif (typeof item !== \"string\") throw new Error(`${key}_must_be_string_array`);\n\t\treturn item.trim();\n\t});\n\tif (items.some((item) => !item)) throw new Error(`${key}_contains_empty_value`);\n\tif (new Set(items).size !== items.length) throw new Error(`${key}_contains_duplicates`);\n\treturn items;\n}\n\nfunction assertProjectInviteBody(body: Record<string, unknown>, creating: boolean): void {\n\tconst allowed = creating ? PROJECT_INVITE_BODY_KEYS : new Set([\"teammate_name\", \"project_ids\"]);\n\tif (Object.keys(body).some((key) => !allowed.has(key))) {\n\t\tthrow new Error(\"unexpected_project_invite_fields\");\n\t}\n\tif (typeof body.teammate_name !== \"string\") throw new Error(\"teammate_name_must_be_string\");\n\tif (creating && typeof body.reviewed_project_set_digest !== \"string\") {\n\t\tthrow new Error(\"reviewed_project_set_digest_required\");\n\t}\n\tif (creating && !/^[a-f0-9]{64}$/u.test(String(body.reviewed_project_set_digest).trim())) {\n\t\tthrow new Error(\"reviewed_project_set_digest_invalid\");\n\t}\n}\n\nfunction projectInviteStatus(config = readCoordinatorSyncConfig()): {\n\tgroupId: string;\n\tconfig: ReturnType<typeof readCoordinatorSyncConfig>;\n} {\n\tconst status = coordinatorAdminStatusPayload(config);\n\tif (status.readiness !== \"ready\") throw new Error(\"team_sharing_not_configured\");\n\tif (status.groups.length !== 1) throw new Error(\"team_selection_ambiguous\");\n\tif (!status.active_group) throw new Error(\"team_sharing_not_configured\");\n\treturn { groupId: status.active_group, config };\n}\n\ntype RecipientInviteKind = \"team_member\" | \"add_device\";\n\nfunction recipientInviteKind(value: unknown): RecipientInviteKind {\n\tif (value === \"team_member\" || value === \"add_device\") return value;\n\tthrow new Error(\"recipient_invite_kind_invalid\");\n}\n\nfunction localOnboardingBinding(\n\tstore: MemoryStore,\n\tdeviceName: string | null,\n\toptions: { materializeActor?: boolean } = {},\n): {\n\tdeviceId: string;\n\tdevicePublicKey: string;\n\tdeviceDisplayName: string;\n} {\n\tconst deviceId =\n\t\toptions.materializeActor === false\n\t\t\t? ensureStableStoreDeviceIdentity(store)\n\t\t\t: ensureStableStoreIdentity(store);\n\tconst devicePublicKey = String(\n\t\tstore.db\n\t\t\t.prepare(\"SELECT public_key FROM sync_device WHERE device_id = ?\")\n\t\t\t.pluck()\n\t\t\t.get(deviceId) ?? \"\",\n\t).trim();\n\tif (!devicePublicKey) throw new Error(\"device_public_key_missing\");\n\tconst config = readCodememConfigFile();\n\treturn {\n\t\tdeviceId,\n\t\tdevicePublicKey,\n\t\tdeviceDisplayName: friendlyDeviceName({\n\t\t\texplicitName: deviceName ?? String(config.sync_device_name ?? \"\"),\n\t\t\tosName: hostname(),\n\t\t\tfallbackSeed: deviceId,\n\t\t}),\n\t};\n}\n\nfunction recipientInviteOnboardingPreview(\n\tstore: MemoryStore,\n\tbody: Record<string, unknown>,\n\tinvitationId: string,\n) {\n\tconst kind = recipientInviteKind(body.kind ?? body.invite_kind);\n\tconst binding = localOnboardingBinding(store, optionalViewerString(body, \"device_name\"));\n\tconst teamId = optionalViewerStrictString(body, \"policy_team_id\");\n\tconst targetIdentityId = optionalViewerStrictString(body, \"target_identity_id\");\n\tif (kind === \"team_member\") {\n\t\tif (!teamId || targetIdentityId) throw new Error(\"recipient_invite_metadata_invalid\");\n\t\treturn previewRecipientPolicyOnboarding(store.db, {\n\t\t\tversion: 1,\n\t\t\tjourney: \"team\",\n\t\t\tinvitationId,\n\t\t\tidentityId: store.actorId,\n\t\t\t...binding,\n\t\t\tteamId,\n\t\t});\n\t}\n\tif (!targetIdentityId || teamId) throw new Error(\"recipient_invite_metadata_invalid\");\n\treturn previewRecipientPolicyOnboarding(\n\t\tstore.db,\n\t\t{\n\t\t\tversion: 1,\n\t\t\tjourney: \"add_device\",\n\t\t\tinvitationId,\n\t\t\tidentityId: targetIdentityId,\n\t\t\t...binding,\n\t\t},\n\t\t{\n\t\t\taddDeviceTeamEligibility: \"prospective_device\",\n\t\t},\n\t);\n}\n\nfunction recipientInviteReviewedIntent(\n\tstore: MemoryStore,\n\tkind: RecipientInviteKind,\n\ttargetId: string,\n\tpreview: RecipientPolicyOnboardingPreviewV1,\n): RecipientReviewedIntentV1 {\n\tif (kind === \"team_member\") {\n\t\tif (preview.journey !== \"team\" || !preview.team || preview.team.teamId !== targetId) {\n\t\t\tthrow new Error(\"recipient_invite_intent_mismatch\");\n\t\t}\n\t\treturn {\n\t\t\tversion: 1,\n\t\t\tjourney: \"team\",\n\t\t\tteam: preview.team,\n\t\t\tprojects: preview.projects,\n\t\t\texcludedProjects: [],\n\t\t};\n\t}\n\tif (preview.journey !== \"add_device\" || preview.binding.identityId !== targetId) {\n\t\tthrow new Error(\"recipient_invite_intent_mismatch\");\n\t}\n\tconst targetIdentity = store.db\n\t\t.prepare(\n\t\t\t`SELECT display_name FROM actors\n\t\t\t WHERE actor_id = ? AND status = 'active' AND merged_into_actor_id IS NULL`,\n\t\t)\n\t\t.get(targetId) as { display_name: string } | undefined;\n\tif (!targetIdentity?.display_name) throw new Error(\"identity_not_found\");\n\treturn {\n\t\tversion: 1,\n\t\tjourney: \"add_device\",\n\t\ttargetIdentity: { identityId: targetId, displayName: targetIdentity.display_name },\n\t\tprojects: preview.projects,\n\t\texcludedProjects: preview.excludedProjects,\n\t};\n}\n\nfunction recipientInviteOnboardingPreviewFromReviewedIntent(\n\tstore: MemoryStore,\n\tbody: Record<string, unknown>,\n\tinvitationId: string,\n\treviewedIntent: RecipientReviewedIntentV1,\n) {\n\tconst kind = recipientInviteKind(body.kind ?? body.invite_kind);\n\tconst binding = localOnboardingBinding(store, optionalViewerString(body, \"device_name\"), {\n\t\tmaterializeActor: false,\n\t});\n\tconst teamId = optionalViewerStrictString(body, \"policy_team_id\");\n\tconst targetIdentityId = optionalViewerStrictString(body, \"target_identity_id\");\n\tconst assignedIdentityId = optionalViewerStrictString(body, \"assigned_identity_id\");\n\tif (kind === \"team_member\") {\n\t\tif (!teamId || !assignedIdentityId || targetIdentityId) {\n\t\t\tthrow new Error(\"recipient_invite_metadata_invalid\");\n\t\t}\n\t\treturn previewRecipientPolicyOnboardingFromReviewedIntent(reviewedIntent, {\n\t\t\tversion: 1,\n\t\t\tjourney: \"team\",\n\t\t\tinvitationId,\n\t\t\tidentityId: assignedIdentityId,\n\t\t\t...binding,\n\t\t\tteamId,\n\t\t});\n\t}\n\tif (!targetIdentityId || teamId || assignedIdentityId) {\n\t\tthrow new Error(\"recipient_invite_metadata_invalid\");\n\t}\n\treturn previewRecipientPolicyOnboardingFromReviewedIntent(reviewedIntent, {\n\t\tversion: 1,\n\t\tjourney: \"add_device\",\n\t\tinvitationId,\n\t\tidentityId: targetIdentityId,\n\t\t...binding,\n\t});\n}\n\nconst SAFE_RECIPIENT_INVITE_ERRORS = new Set([\n\t\"device_display_name_invalid\",\n\t\"device_display_name_required\",\n\t\"device_display_name_too_long\",\n\t\"invite_already_bound\",\n\t\"invite_expired\",\n\t\"invite_identity_conflict\",\n\t\"invite_invalid\",\n\t\"recipient_display_name_invalid\",\n\t\"recipient_display_name_required\",\n\t\"recipient_display_name_too_long\",\n\t\"recipient_invite_intent_mismatch\",\n\t\"recipient_invite_review_unavailable\",\n\t\"reviewed_onboarding_stale\",\n]);\n\nfunction safeRecipientInviteError(value: unknown, fallback = \"invite_invalid\"): string {\n\tconst code = value instanceof Error ? value.message : String(value ?? \"\").trim();\n\treturn SAFE_RECIPIENT_INVITE_ERRORS.has(code) ? code : fallback;\n}\n\nfunction recipientInvitePreviewId(kind: RecipientInviteKind, targetId: string): string {\n\treturn `recipient-invite-preview:${kind}:${targetId}`;\n}\n\nexport function recipientPolicyCapabilityFromStatus(payload: {\n\tsync_capability?: unknown;\n\tsync_features?: unknown;\n}): RecipientPolicyPeerCapability {\n\tif (!isScopedSyncCapability(normalizeSyncCapability(payload.sync_capability))) {\n\t\treturn \"unsupported\";\n\t}\n\treturn supportsSyncFeature(payload.sync_features, \"reassign_scope\") ? \"supported\" : \"unsupported\";\n}\n\nexport async function peerSupportsSyncRequirements(\n\tstore: MemoryStore,\n\tdeviceId: string,\n\trequirements: { scoped: boolean; reassignScope: boolean },\n): Promise<RecipientPolicyPeerCapability> {\n\tconst [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });\n\tif (deviceId === localDeviceId) return \"supported\";\n\tconst row = store.db\n\t\t.prepare(\n\t\t\t\"SELECT addresses_json, pinned_fingerprint, public_key FROM sync_peers WHERE peer_device_id = ?\",\n\t\t)\n\t\t.get(deviceId) as\n\t\t| {\n\t\t\t\taddresses_json: string | null;\n\t\t\t\tpinned_fingerprint: string | null;\n\t\t\t\tpublic_key: string | null;\n\t\t }\n\t\t| undefined;\n\tconst expectedFingerprint =\n\t\tString(row?.pinned_fingerprint ?? \"\").trim() ||\n\t\t(row?.public_key ? fingerprintPublicKey(row.public_key) : \"\");\n\tconst addresses = safeJsonList(row?.addresses_json ?? null);\n\tfor (const address of addresses) {\n\t\ttry {\n\t\t\tconst url = `${buildBaseUrl(address)}/v1/status`;\n\t\t\tconst headers = {\n\t\t\t\t...buildDirectPeerAuthHeaders({\n\t\t\t\t\tdeviceId: localDeviceId,\n\t\t\t\t\trecipientId: deviceId,\n\t\t\t\t\tdbPath: store.dbPath,\n\t\t\t\t\tmethod: \"GET\",\n\t\t\t\t\turl,\n\t\t\t\t\tbodyBytes: Buffer.alloc(0),\n\t\t\t\t\tkeysDir: syncKeysDir(),\n\t\t\t\t}),\n\t\t\t\t[SYNC_CAPABILITY_HEADER]: LOCAL_SYNC_CAPABILITY,\n\t\t\t\t[SYNC_FEATURES_HEADER]: LOCAL_SYNC_FEATURES.join(\",\"),\n\t\t\t};\n\t\t\tconst [status, payload] = await requestJson(\"GET\", url, { headers, timeoutS: 5 });\n\t\t\tif (status < 200 || status >= 300) continue;\n\t\t\tif (String(payload?.device_id ?? \"\").trim() !== deviceId) continue;\n\t\t\tif (\n\t\t\t\texpectedFingerprint &&\n\t\t\t\tString(payload?.fingerprint ?? \"\").trim() !== expectedFingerprint\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (\n\t\t\t\trequirements.scoped &&\n\t\t\t\trequirements.reassignScope &&\n\t\t\t\trecipientPolicyCapabilityFromStatus(payload ?? {}) !== \"supported\"\n\t\t\t) {\n\t\t\t\treturn \"unsupported\";\n\t\t\t}\n\t\t\tif (\n\t\t\t\trequirements.scoped &&\n\t\t\t\t!isScopedSyncCapability(normalizeSyncCapability(payload?.sync_capability))\n\t\t\t) {\n\t\t\t\treturn \"unsupported\";\n\t\t\t}\n\t\t\tif (\n\t\t\t\trequirements.reassignScope &&\n\t\t\t\t!supportsSyncFeature(payload?.sync_features, \"reassign_scope\")\n\t\t\t) {\n\t\t\t\treturn \"unsupported\";\n\t\t\t}\n\t\t\treturn \"supported\";\n\t\t} catch {\n\t\t\t// Try the next reviewed address. Ambiguous/unreachable capability fails closed.\n\t\t}\n\t}\n\treturn \"undetermined\";\n}\n\nasync function peerSupportsReassignScope(\n\tstore: MemoryStore,\n\tdeviceId: string,\n): Promise<ReassignScopeCapability> {\n\treturn peerSupportsSyncRequirements(store, deviceId, {\n\t\tscoped: false,\n\t\treassignScope: true,\n\t});\n}\n\nfunction resolveProjectInviteSelection(\n\tstore: MemoryStore,\n\trequestedIds: string[],\n\tinitiatingDeviceId: string,\n): ShareProjectIntent[] {\n\tif (requestedIds.length === 0) throw new Error(\"project_selection_empty\");\n\tconst requested = new Set(requestedIds);\n\tconst byIdentity = new Map<\n\t\tstring,\n\t\tReturnType<typeof listProjectScopeInventory>[\"projects\"][number]\n\t>();\n\tlet offset = 0;\n\twhile (byIdentity.size < requested.size) {\n\t\tconst page = listProjectScopeInventory(store.db, { limit: 250, offset });\n\t\tfor (const project of page.projects) {\n\t\t\tif (requested.has(project.workspace_identity)) {\n\t\t\t\tbyIdentity.set(project.workspace_identity, project);\n\t\t\t}\n\t\t}\n\t\tif (!page.has_more) break;\n\t\toffset += page.limit;\n\t}\n\treturn requestedIds.map((projectId) => {\n\t\tconst project = byIdentity.get(projectId);\n\t\tif (!project) throw new Error(\"project_selection_unknown\");\n\t\tconst ambiguous = project.guardrail_warnings.some(\n\t\t\t(warning) => warning.code === \"basename_collision_review\" && warning.requires_confirmation,\n\t\t);\n\t\tif (ambiguous) throw new Error(\"project_selection_ambiguous\");\n\t\tif (\n\t\t\tproject.read_only ||\n\t\t\tproject.identity_source === \"unmapped\" ||\n\t\t\tproject.memory_count == null ||\n\t\t\tproject.guardrail_warnings.some((warning) => warning.requires_confirmation)\n\t\t) {\n\t\t\tthrow new Error(\"project_selection_unsupported\");\n\t\t}\n\t\treturn {\n\t\t\tcanonicalIdentity: project.workspace_identity,\n\t\t\tdisplayName: project.display_project,\n\t\t\tidentitySource: project.identity_source,\n\t\t\texistingMemoryCount: countShareableProjectMemories(store.db, {\n\t\t\t\tcanonicalIdentity: project.workspace_identity,\n\t\t\t\tinitiatingDeviceId,\n\t\t\t}),\n\t\t};\n\t});\n}\n\nfunction resolveSharePerson(store: MemoryStore, teammateName: string): SharePersonIntent {\n\tconst matches = store.db\n\t\t.prepare(\n\t\t\t`SELECT actor_id, display_name, status\n\t\t\t FROM actors\n\t\t\t WHERE status IN ('active', 'pending') AND lower(trim(display_name)) = lower(?)\n\t\t\t ORDER BY actor_id`,\n\t\t)\n\t\t.all(teammateName) as Array<{ actor_id: string; display_name: string; status: string }>;\n\tif (matches.length > 1) throw new Error(\"teammate_match_ambiguous\");\n\tconst match = matches[0];\n\tif (match) {\n\t\treturn match.status === \"pending\"\n\t\t\t? { kind: \"pending\", personId: match.actor_id, displayName: match.display_name }\n\t\t\t: { kind: \"existing\", personId: match.actor_id, displayName: match.display_name };\n\t}\n\treturn { kind: \"pending\", displayName: teammateName };\n}\n\nfunction projectInvitePlan(\n\tstore: MemoryStore,\n\tbody: Record<string, unknown>,\n\tcreatedAt: string,\n\tinviteExpiresAt: string,\n): { plan: ShareOperationPlan; config: ReturnType<typeof readCoordinatorSyncConfig> } {\n\tconst teammateName = normalizeTeammateName(String(body.teammate_name));\n\tconst [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });\n\tstore.adoptEnsuredDeviceIdentity(localDeviceId);\n\tconst projects = resolveProjectInviteSelection(\n\t\tstore,\n\t\tprojectInviteStringList(body, \"project_ids\"),\n\t\tlocalDeviceId,\n\t);\n\tconst { groupId, config } = projectInviteStatus();\n\treturn {\n\t\tplan: planShareOperation({\n\t\t\tinviterActorId: store.actorId,\n\t\t\tinviterDeviceIds: [localDeviceId],\n\t\t\tperson: resolveSharePerson(store, teammateName),\n\t\t\tprojects,\n\t\t\tcoordinatorGroupId: groupId,\n\t\t\tcreatedAt,\n\t\t\tinviteExpiresAt,\n\t\t}),\n\t\tconfig,\n\t};\n}\n\nfunction projectInvitePreview(plan: ShareOperationPlan) {\n\treturn {\n\t\toperation_id: plan.operationId,\n\t\tteammate: {\n\t\t\tdisplay_name: plan.teammateName,\n\t\t\tmatch: plan.personKind,\n\t\t\t...(plan.personKind === \"existing\" ? { person_id: plan.personId } : {}),\n\t\t},\n\t\tprojects: plan.projects.map((project) => ({\n\t\t\tproject_id: project.canonicalIdentity,\n\t\t\tdisplay_name: project.displayName,\n\t\t\texisting_memory_count: project.existingMemoryCount,\n\t\t})),\n\t\texisting_memory_count: plan.projects.reduce(\n\t\t\t(total, project) => total + project.existingMemoryCount,\n\t\t\t0,\n\t\t),\n\t\tfuture_memories_shared: true as const,\n\t\thistory_policy: plan.historyPolicy,\n\t\treviewed_project_set_digest: plan.reviewedProjectSetDigest,\n\t};\n}\n\ntype CoordinatorProjectInvitePayload = Record<string, unknown> & {\n\toperation_id?: string;\n\tgroup_id?: string;\n\tstate?: string;\n};\n\nasync function coordinatorProjectInvitePayload(operationId: string): Promise<{\n\tgroupId: string;\n\tconfig: ReturnType<typeof readCoordinatorSyncConfig>;\n\tpayload: CoordinatorProjectInvitePayload;\n}> {\n\tconst { groupId, config } = projectInviteStatus();\n\tconst [status, payload] = await requestJson(\n\t\t\"GET\",\n\t\t`${buildBaseUrl(config.syncCoordinatorUrl)}/v1/admin/project-invites/${encodeURIComponent(operationId)}?group_id=${encodeURIComponent(groupId)}`,\n\t\t{\n\t\t\theaders: { \"X-Codemem-Coordinator-Admin\": config.syncCoordinatorAdminSecret },\n\t\t\ttimeoutS: 10,\n\t\t},\n\t).catch((cause: unknown) => {\n\t\tconst error = new Error(\"coordinator_unavailable\", { cause });\n\t\tObject.assign(error, { status: 503 });\n\t\tthrow error;\n\t});\n\tif (status < 200 || status >= 300) {\n\t\tconst error = new Error(String(payload?.error ?? \"operation_read_failed\"));\n\t\tObject.assign(error, { status });\n\t\tthrow error;\n\t}\n\tif (!payload || payload.operation_id !== operationId || payload.group_id !== groupId) {\n\t\tconst error = new Error(\"operation_scope_mismatch\");\n\t\tObject.assign(error, { status: 409 });\n\t\tthrow error;\n\t}\n\treturn { groupId, config, payload: payload as CoordinatorProjectInvitePayload };\n}\n\nasync function reconcileProjectInviteAcceptance(\n\tstore: MemoryStore,\n\toperationId: string,\n): Promise<{ accepted: boolean; payload: CoordinatorProjectInvitePayload }> {\n\tconst owner = store.db\n\t\t.prepare(\"SELECT inviter_actor_id FROM share_operations WHERE operation_id = ?\")\n\t\t.pluck()\n\t\t.get(operationId) as string | undefined;\n\tif (!owner) throw new Error(\"operation_not_found\");\n\tif (owner !== store.actorId) throw new Error(\"operation_scope_mismatch\");\n\tensureLocalActorRecord(store);\n\tconst { groupId, payload } = await coordinatorProjectInvitePayload(operationId);\n\tif (payload.state === \"waiting_for_acceptance\") return { accepted: false, payload };\n\tif (payload.state !== \"accepted\") {\n\t\tconst error = new Error(\"operation_state_invalid\");\n\t\tObject.assign(error, { status: 409 });\n\t\tthrow error;\n\t}\n\tconst required = [\n\t\t\"reviewed_project_set_digest\",\n\t\t\"recipient_actor_id\",\n\t\t\"recipient_display_name\",\n\t\t\"recipient_device_id\",\n\t\t\"recipient_device_display_name\",\n\t\t\"recipient_public_key\",\n\t\t\"recipient_fingerprint\",\n\t\t\"consumed_at\",\n\t\t\"trust_state\",\n\t] as const;\n\tif (required.some((key) => typeof payload[key] !== \"string\" || !String(payload[key]).trim())) {\n\t\tconst error = new Error(\"operation_acceptance_invalid\");\n\t\tObject.assign(error, { status: 409 });\n\t\tthrow error;\n\t}\n\tconst trustState = String(payload.trust_state);\n\tconst bootstrapGrantId =\n\t\ttypeof payload.bootstrap_grant_id === \"string\" && payload.bootstrap_grant_id.trim()\n\t\t\t? payload.bootstrap_grant_id\n\t\t\t: null;\n\tif (\n\t\t(trustState !== \"pending_inviter_device\" && trustState !== \"bootstrap_grant_created\") ||\n\t\t(trustState === \"bootstrap_grant_created\") !== Boolean(bootstrapGrantId)\n\t) {\n\t\tconst error = new Error(\"operation_trust_state_invalid\");\n\t\tObject.assign(error, { status: 409 });\n\t\tthrow error;\n\t}\n\tconst projects = parseAcceptedProjectIntent(payload.projects);\n\treconcileShareOperationAcceptance(store.db, {\n\t\toperationId,\n\t\tlocalInviterActorId: store.actorId,\n\t\tcoordinatorGroupId: groupId,\n\t\treviewedProjectSetDigest: String(payload.reviewed_project_set_digest),\n\t\trecipientActorId: String(payload.recipient_actor_id),\n\t\trecipientDisplayName: String(payload.recipient_display_name),\n\t\trecipientDeviceId: String(payload.recipient_device_id),\n\t\trecipientDeviceDisplayName: String(payload.recipient_device_display_name),\n\t\trecipientPublicKey: String(payload.recipient_public_key),\n\t\trecipientFingerprint: String(payload.recipient_fingerprint),\n\t\tconsumedAt: String(payload.consumed_at),\n\t\ttrustState,\n\t\tbootstrapGrantId,\n\t\tprojects,\n\t});\n\treturn { accepted: true, payload };\n}\n\ninterface ShareOperationReadRow {\n\toperation_id: string;\n\tstate: string;\n\tperson_id: string;\n\tteammate_name: string;\n\trecipient_actor_id: string | null;\n\trecipient_display_name: string | null;\n\trecipient_device_id: string | null;\n\trecipient_device_display_name: string | null;\n\tinvite_expires_at: string;\n\tacceptance_consumed_at: string | null;\n\tcreated_at: string;\n\tupdated_at: string;\n\tactor_display_name: string | null;\n\tpeer_display_name: string | null;\n\tdevice_last_seen_at: string | null;\n\tdevice_last_reached_at: string | null;\n}\n\nasync function shareOperationReadModels(\n\tstore: MemoryStore,\n\toperationId?: string,\n\tincludeInviteLinks = true,\n) {\n\tconst rows = store.db\n\t\t.prepare(`SELECT o.operation_id, o.state, o.person_id, o.teammate_name,\n\t\t\to.recipient_actor_id, o.recipient_display_name, o.recipient_device_id,\n\t\t\to.recipient_device_display_name, o.invite_expires_at, o.acceptance_consumed_at,\n\t\t\to.created_at, o.updated_at, a.display_name AS actor_display_name,\n\t\t\tp.name AS peer_display_name, p.last_seen_at AS device_last_seen_at,\n\t\t\tp.last_sync_at AS device_last_reached_at\n\t\t FROM share_operations o\n\t\t LEFT JOIN actors a ON a.actor_id = o.person_id\n\t\t LEFT JOIN sync_peers p ON p.peer_device_id = o.recipient_device_id\n\t\t WHERE o.inviter_actor_id = ? AND (? IS NULL OR o.operation_id = ?)\n\t\t ORDER BY o.created_at DESC, o.operation_id`)\n\t\t.all(store.actorId, operationId ?? null, operationId ?? null) as ShareOperationReadRow[];\n\tconst now = new Date().toISOString();\n\treturn Promise.all(\n\t\trows.map(async (row) => {\n\t\t\tconst projects = store.db\n\t\t\t\t.prepare(`SELECT canonical_project_identity AS project_id, display_name, existing_memory_count\n\t\t\t\t FROM share_operation_projects WHERE operation_id = ? ORDER BY ordinal`)\n\t\t\t\t.all(row.operation_id) as Array<{\n\t\t\t\tproject_id: string;\n\t\t\t\tdisplay_name: string;\n\t\t\t\texisting_memory_count: number;\n\t\t\t}>;\n\t\t\tconst steps = (\n\t\t\t\tstore.db\n\t\t\t\t\t.prepare(`SELECT step_key, status, attempt_count, started_at, last_attempt_at,\n\t\t\t\t\t\tsafe_error_code, updated_at FROM share_operation_steps WHERE operation_id = ?`)\n\t\t\t\t\t.all(row.operation_id) as Array<{\n\t\t\t\t\tstep_key: string;\n\t\t\t\t\tstatus: ShareOperationLifecycleStepInput[\"status\"];\n\t\t\t\t\tattempt_count: number;\n\t\t\t\t\tstarted_at: string | null;\n\t\t\t\t\tlast_attempt_at: string | null;\n\t\t\t\t\tsafe_error_code: string | null;\n\t\t\t\t\tupdated_at: string;\n\t\t\t\t}>\n\t\t\t).map(\n\t\t\t\t(step): ShareOperationLifecycleStepInput => ({\n\t\t\t\t\tattemptCount: step.attempt_count,\n\t\t\t\t\tlastAttemptAt: step.last_attempt_at,\n\t\t\t\t\tsafeErrorCode: step.safe_error_code,\n\t\t\t\t\tstartedAt: step.started_at,\n\t\t\t\t\tstatus: step.status,\n\t\t\t\t\tstepKey: step.step_key,\n\t\t\t\t\tupdatedAt: step.updated_at,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tlet inviteLink: string | null = null;\n\t\t\tlet projectedState = row.state;\n\t\t\tif (includeInviteLinks && row.state === \"waiting_for_acceptance\") {\n\t\t\t\ttry {\n\t\t\t\t\tconst remote = await coordinatorProjectInvitePayload(row.operation_id);\n\t\t\t\t\tif (remote.payload.state === \"accepted\") projectedState = \"accepted\";\n\t\t\t\t\tinviteLink =\n\t\t\t\t\t\ttypeof remote.payload.invite_link === \"string\" && remote.payload.invite_link.trim()\n\t\t\t\t\t\t\t? remote.payload.invite_link\n\t\t\t\t\t\t\t: null;\n\t\t\t\t} catch {\n\t\t\t\t\t// A read-model refresh remains useful when the coordinator is temporarily unavailable.\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst personId = row.recipient_actor_id || row.person_id;\n\t\t\tconst personName = row.recipient_display_name || row.actor_display_name || row.teammate_name;\n\t\t\tconst deviceName = row.recipient_device_display_name || row.peer_display_name;\n\t\t\tconst lifecycle = projectShareLifecycle({\n\t\t\t\tdeviceLastSeenAt: row.device_last_seen_at,\n\t\t\t\tdeviceLastReachedAt: row.device_last_reached_at,\n\t\t\t\tdeviceName,\n\t\t\t\tinviteLink,\n\t\t\t\tnow,\n\t\t\t\tpersonName,\n\t\t\t\tstate: projectedState,\n\t\t\t\tsteps,\n\t\t\t});\n\t\t\treturn {\n\t\t\t\toperation_id: row.operation_id,\n\t\t\t\tperson: { actor_id: personId, display_name: personName },\n\t\t\t\tdevices:\n\t\t\t\t\trow.recipient_device_id && deviceName\n\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tdevice_id: row.recipient_device_id,\n\t\t\t\t\t\t\t\t\tdisplay_name: deviceName,\n\t\t\t\t\t\t\t\t\tlast_seen_at: row.device_last_seen_at,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t: [],\n\t\t\t\tprojects,\n\t\t\t\tproject_count: projects.length,\n\t\t\t\tlifecycle: {\n\t\t\t\t\tstate: lifecycle.lifecycle,\n\t\t\t\t\tlabel: lifecycle.label,\n\t\t\t\t\texplanation: lifecycle.explanation,\n\t\t\t\t\tprimary_action:\n\t\t\t\t\t\tlifecycle.primaryAction?.kind === \"copy_invite\"\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tkind: \"copy_invite\",\n\t\t\t\t\t\t\t\t\tlabel: lifecycle.primaryAction.label,\n\t\t\t\t\t\t\t\t\tinvite_link: lifecycle.primaryAction.inviteLink,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: !includeInviteLinks && lifecycle.lifecycle === \"waiting_for_acceptance\"\n\t\t\t\t\t\t\t\t? { kind: \"copy_invite\", label: \"Copy invite\" }\n\t\t\t\t\t\t\t\t: lifecycle.primaryAction,\n\t\t\t\t},\n\t\t\t\ttimestamps: {\n\t\t\t\t\tcreated_at: row.created_at,\n\t\t\t\t\tupdated_at: row.updated_at,\n\t\t\t\t\taccepted_at: row.acceptance_consumed_at,\n\t\t\t\t\tinvite_expires_at: row.invite_expires_at,\n\t\t\t\t},\n\t\t\t};\n\t\t}),\n\t);\n}\n\nasync function executeProjectShareProvisioning(store: MemoryStore, operationId: string) {\n\tconst { groupId, config } = projectInviteStatus();\n\tconst coordinatorId = config.syncCoordinatorUrl || null;\n\tif (!coordinatorId) throw new Error(\"coordinator_not_configured\");\n\tconst [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });\n\treturn executeShareProvisioning(\n\t\tstore.db,\n\t\t{ operationId, initiatingDeviceId: localDeviceId },\n\t\t{\n\t\t\tcreateOrGetBoundary: async (project, expectedGroupId) => {\n\t\t\t\tif (expectedGroupId !== groupId) throw new Error(\"operation_scope_mismatch\");\n\t\t\t\tconst readExisting = async () =>\n\t\t\t\t\t(\n\t\t\t\t\t\tawait coordinatorListScopesAction({\n\t\t\t\t\t\t\tgroupId,\n\t\t\t\t\t\t\tincludeInactive: true,\n\t\t\t\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t\t\t\t})\n\t\t\t\t\t).find((scope) => scope.scope_id === project.boundaryId) ?? null;\n\t\t\t\tconst existing = await readExisting();\n\t\t\t\tif (existing) return existing;\n\t\t\t\ttry {\n\t\t\t\t\treturn await coordinatorCreateScopeAction({\n\t\t\t\t\t\tgroupId,\n\t\t\t\t\t\tscopeId: project.boundaryId,\n\t\t\t\t\t\tlabel: project.displayName,\n\t\t\t\t\t\tkind: \"managed_project\",\n\t\t\t\t\t\tauthorityType: \"coordinator\",\n\t\t\t\t\t\tcoordinatorId,\n\t\t\t\t\t\tmembershipEpoch: 1,\n\t\t\t\t\t\tstatus: \"active\",\n\t\t\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst reread = await readExisting();\n\t\t\t\t\tif (reread) return reread;\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t},\n\t\t\tgrantMembership: ({ effectId, groupId: expectedGroupId, scopeId, deviceId, role }) => {\n\t\t\t\tif (expectedGroupId !== groupId) throw new Error(\"operation_scope_mismatch\");\n\t\t\t\treturn coordinatorGrantScopeMembershipAction({\n\t\t\t\t\teffectId,\n\t\t\t\t\tgroupId,\n\t\t\t\t\tscopeId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\trole,\n\t\t\t\t\tmembershipEpoch: 1,\n\t\t\t\t\tcoordinatorId,\n\t\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t\t});\n\t\t\t},\n\t\t\tsupportsReassignScope: (deviceId) => peerSupportsReassignScope(store, deviceId),\n\t\t\trefreshAuthorization: async (expectedGroupId) => {\n\t\t\t\tif (expectedGroupId !== groupId) throw new Error(\"operation_scope_mismatch\");\n\t\t\t\tconst refreshed = await refreshConfiguredScopeMembershipCache(store.db, config, {\n\t\t\t\t\tkeysDir: syncKeysDir(),\n\t\t\t\t\tdbPath: store.dbPath,\n\t\t\t\t});\n\t\t\t\tconst group = refreshed.groups.find((item) => item.groupId === groupId);\n\t\t\t\tif (group?.status !== \"refreshed\") throw new Error(\"authorization_refresh_failed\");\n\t\t\t},\n\t\t\trunInitialSync: (recipientDeviceId) =>\n\t\t\t\trunSyncPass(store.db, recipientDeviceId, {\n\t\t\t\t\tkeysDir: syncKeysDir(),\n\t\t\t\t\tdbPath: store.dbPath,\n\t\t\t\t\tscanner: store.scanner,\n\t\t\t\t\trefreshAuthorization: true,\n\t\t\t\t}),\n\t\t},\n\t);\n}\n\nexport interface AdvanceProjectShareOperationResult {\n\tadvanced: boolean;\n\tstate: \"active\" | \"waiting_for_acceptance\" | \"cancelled\";\n}\n\nexport async function advanceProjectShareOperation(\n\tstore: MemoryStore,\n\toperationId: string,\n): Promise<AdvanceProjectShareOperationResult> {\n\tconst operation = store.db\n\t\t.prepare(\n\t\t\t\"SELECT state, inviter_actor_id, recipient_device_id FROM share_operations WHERE operation_id = ?\",\n\t\t)\n\t\t.get(operationId) as\n\t\t| { state: string; inviter_actor_id: string; recipient_device_id: string | null }\n\t\t| undefined;\n\tif (!operation) throw new Error(\"operation_not_found\");\n\tif (operation.inviter_actor_id !== store.actorId) throw new Error(\"operation_scope_mismatch\");\n\tif (operation.state === \"cancelled\") {\n\t\t// Already superseded (possibly earlier in the same maintenance batch);\n\t\t// provisioning a cancelled operation would only produce a misleading\n\t\t// operation_not_accepted failure.\n\t\treturn { advanced: false, state: \"cancelled\" };\n\t}\n\tif (!operation.recipient_device_id) {\n\t\tconst reconciliation = await reconcileProjectInviteAcceptance(store, operationId);\n\t\tif (!reconciliation.accepted) {\n\t\t\treturn { advanced: false, state: \"waiting_for_acceptance\" };\n\t\t}\n\t}\n\tconst plan = await executeProjectShareProvisioning(store, operationId);\n\tif (plan.superseded) {\n\t\t// A duplicate operation won the race and cancelled this one mid-flight;\n\t\t// reporting it as active would contradict the stored state.\n\t\treturn { advanced: false, state: \"cancelled\" };\n\t}\n\treturn { advanced: true, state: \"active\" };\n}\n\nexport interface AdvancePendingProjectSharesResult {\n\tprocessed: number;\n\tadvanced: number;\n\twaiting: number;\n\tattention: number;\n\tfailed: number;\n\titems: Array<{\n\t\toperationId: string;\n\t\toutcome:\n\t\t\t| \"advanced\"\n\t\t\t| \"waiting_for_acceptance\"\n\t\t\t| \"waiting_for_device\"\n\t\t\t| \"retry_scheduled\"\n\t\t\t| \"needs_attention\"\n\t\t\t| \"superseded\"\n\t\t\t| \"failed\";\n\t\terror?: string;\n\t}>;\n}\n\nconst AUTOMATIC_SHARE_OPERATION_STATES = [\n\t\"waiting_for_acceptance\",\n\t\"accepted\",\n\t\"provisioning\",\n\t\"initial_sync\",\n\t\"waiting_for_device\",\n] as const;\n\nconst AUTOMATIC_WAITING_ACCEPTANCE_RETRY_COOLDOWN_MS = 30 * 1000;\nconst AUTOMATIC_WAITING_DEVICE_RETRY_COOLDOWN_MS = 5 * 60 * 1000;\nconst TERMINAL_SHARE_MAINTENANCE_ERRORS = new Set([\n\t\"coordinator_not_configured\",\n\t\"team_sharing_not_configured\",\n\t\"team_selection_ambiguous\",\n\t\"initiating_device_not_reviewed\",\n\t\"inviter_project_access_ambiguous\",\n\t\"managed_boundary_plan_missing\",\n\t\"operation_device_binding_missing\",\n\t\"operation_intent_invalid\",\n\t\"provisioning_membership_plan_invalid\",\n\t\"device_binding_conflict\",\n\t\"intent_conflict\",\n\t\"inviter_identity_conflict\",\n]);\nconst PROJECT_INVITE_OWNER_CONFLICT_ERRORS = new Set([\n\t\"operation_scope_mismatch\",\n\t\"operation_state_invalid\",\n\t\"operation_acceptance_invalid\",\n\t\"operation_trust_state_invalid\",\n\t\"operation_intent_invalid\",\n\t\"operation_intent_mismatch\",\n\t\"recipient_fingerprint_mismatch\",\n\t\"recipient_device_identity_conflict\",\n\t\"recipient_actor_conflict\",\n\t\"pending_person_identity_conflict\",\n\t\"device_binding_conflict\",\n\t\"intent_conflict\",\n\t\"inviter_identity_conflict\",\n]);\nconst TERMINAL_RECONCILIATION_ERRORS = new Set([\n\t\"coordinator_not_configured\",\n\t\"team_sharing_not_configured\",\n\t\"team_selection_ambiguous\",\n\t\"operation_not_found\",\n\t...PROJECT_INVITE_OWNER_CONFLICT_ERRORS,\n]);\n\nfunction errorStatus(error: unknown): number | null {\n\tconst value = error && typeof error === \"object\" ? (error as { status?: unknown }).status : null;\n\treturn typeof value === \"number\" && Number.isInteger(value) && value >= 400 && value <= 599\n\t\t? value\n\t\t: null;\n}\n\nfunction projectInviteOwnerErrorResponse(\n\terror: unknown,\n\tfallback: { code: \"operation_read_failed\" | \"operation_reconcile_failed\"; status: 400 | 409 },\n): {\n\tcode: string;\n\tstatus: 400 | 404 | 409 | 502 | 503;\n} {\n\tconst message = error instanceof Error ? error.message : \"\";\n\tconst status = errorStatus(error);\n\tif (message === \"operation_not_found\" && (status == null || status === 404)) {\n\t\treturn { code: message, status: 404 };\n\t}\n\tif (PROJECT_INVITE_OWNER_CONFLICT_ERRORS.has(message) && (status == null || status === 409)) {\n\t\treturn { code: message, status: 409 };\n\t}\n\tif (status != null && status >= 500 && message !== \"coordinator_unavailable\") {\n\t\treturn { code: \"coordinator_upstream_failed\", status: 502 };\n\t}\n\tif (message === \"coordinator_unavailable\" || status === 408 || status === 429 || status === 503) {\n\t\treturn { code: \"coordinator_unavailable\", status: 503 };\n\t}\n\treturn fallback;\n}\n\nfunction isRetryableReconciliationError(error: unknown): boolean {\n\tconst message = error instanceof Error ? error.message : String(error);\n\tif (TERMINAL_RECONCILIATION_ERRORS.has(message)) return false;\n\tconst status = errorStatus(error);\n\treturn status == null || status === 408 || status === 429 || status >= 500;\n}\n\nfunction safeReconciliationErrorCode(error: unknown): string {\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn TERMINAL_RECONCILIATION_ERRORS.has(message) ? message : \"operation_read_failed\";\n}\n\nfunction recordInviteReconciliationFailure(\n\tstore: MemoryStore,\n\toperationId: string,\n\terror: unknown,\n\tnow: string,\n): \"retry_scheduled\" | \"needs_attention\" {\n\tconst safeErrorCode = safeReconciliationErrorCode(error);\n\tconst retryable = isRetryableReconciliationError(error);\n\tstore.db\n\t\t.prepare(`UPDATE share_operation_steps SET\n\t\t\tstatus = CASE WHEN ? = 1 THEN 'pending' ELSE 'failed' END,\n\t\t\tattempt_count = attempt_count + 1, last_attempt_at = ?, safe_error_code = ?, updated_at = ?\n\t\t\tWHERE operation_id = ? AND step_key = 'invite_consumption'`)\n\t\t.run(retryable ? 1 : 0, now, safeErrorCode, now, operationId);\n\tconst outcome = retryable ? \"retry_scheduled\" : \"needs_attention\";\n\tstore.db\n\t\t.prepare(\"UPDATE share_operations SET state = ?, updated_at = ? WHERE operation_id = ?\")\n\t\t.run(\n\t\t\toutcome === \"needs_attention\" ? \"needs_attention\" : \"waiting_for_acceptance\",\n\t\t\tnow,\n\t\t\toperationId,\n\t\t);\n\treturn outcome;\n}\n\nexport async function advancePendingProjectShares(\n\tstore: MemoryStore,\n\toptions: {\n\t\tlimit?: number;\n\t\tnow?: Date;\n\t\tadvanceOperation?: (\n\t\t\tstore: MemoryStore,\n\t\t\toperationId: string,\n\t\t) => Promise<AdvanceProjectShareOperationResult>;\n\t} = {},\n): Promise<AdvancePendingProjectSharesResult> {\n\tconst limit = Math.max(1, Math.min(Math.trunc(options.limit ?? 3), 10));\n\tconst placeholders = AUTOMATIC_SHARE_OPERATION_STATES.map(() => \"?\").join(\", \");\n\tconst maintenanceNow = options.now ?? new Date();\n\tconst waitingAcceptanceRetryBefore = new Date(\n\t\tmaintenanceNow.getTime() - AUTOMATIC_WAITING_ACCEPTANCE_RETRY_COOLDOWN_MS,\n\t).toISOString();\n\tconst waitingRetryBefore = new Date(\n\t\tmaintenanceNow.getTime() - AUTOMATIC_WAITING_DEVICE_RETRY_COOLDOWN_MS,\n\t).toISOString();\n\t// A later failed attempt supersedes older reachability evidence and keeps the cooldown in force.\n\tconst rows = store.db\n\t\t.prepare(`SELECT operation.operation_id FROM share_operations AS operation\n\t\t WHERE operation.inviter_actor_id = ?\n\t\t AND operation.state IN (${placeholders})\n\t\t AND (operation.state <> 'waiting_for_acceptance' OR operation.updated_at <= ?)\n\t\t AND (\n\t\t\toperation.state <> 'waiting_for_device'\n\t\t\tOR operation.updated_at <= ?\n\t\t\tOR (\n\t\t\t\tNOT EXISTS (\n\t\t\t\t\tSELECT 1 FROM share_operation_steps AS step\n\t\t\t\t\tWHERE step.operation_id = operation.operation_id\n\t\t\t\t\tAND step.step_key = 'capability_preflight'\n\t\t\t\t\tAND step.status <> 'completed'\n\t\t\t\t\tAND (\n\t\t\t\t\t\tstep.status = 'running'\n\t\t\t\t\t\tOR step.safe_error_code IN (\n\t\t\t\t\t\t\t'waiting_for_device', 'device_offline', 'recipient_offline'\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t\tAND EXISTS (\n\t\t\t\t\tSELECT 1 FROM sync_attempts AS attempt\n\t\t\t\t\tWHERE attempt.id = (\n\t\t\t\t\t\tSELECT latest.id FROM sync_attempts AS latest\n\t\t\t\t\t\tWHERE latest.peer_device_id = operation.recipient_device_id\n\t\t\t\t\t\tORDER BY latest.started_at DESC, latest.id DESC\n\t\t\t\t\t\tLIMIT 1\n\t\t\t\t\t)\n\t\t\t\t\tAND attempt.ok = 1\n\t\t\t\t\tAND julianday(COALESCE(attempt.finished_at, attempt.started_at)) >\n\t\t\t\t\t\tjulianday(operation.updated_at)\n\t\t\t\t)\n\t\t\t)\n\t\t )\n\t\t ORDER BY CASE WHEN operation.state IN ('accepted', 'provisioning', 'initial_sync') THEN 0 ELSE 1 END,\n\t\t\tCASE WHEN operation.state IN ('waiting_for_acceptance', 'waiting_for_device')\n\t\t\t\tTHEN operation.updated_at ELSE operation.created_at END ASC,\n\t\t\toperation.created_at ASC, operation.operation_id ASC\n\t\t LIMIT ?`)\n\t\t.all(\n\t\t\tstore.actorId,\n\t\t\t...AUTOMATIC_SHARE_OPERATION_STATES,\n\t\t\twaitingAcceptanceRetryBefore,\n\t\t\twaitingRetryBefore,\n\t\t\tlimit,\n\t\t) as Array<{\n\t\toperation_id: string;\n\t}>;\n\tconst advanceOperation = options.advanceOperation ?? advanceProjectShareOperation;\n\tconst result: AdvancePendingProjectSharesResult = {\n\t\tprocessed: 0,\n\t\tadvanced: 0,\n\t\twaiting: 0,\n\t\tattention: 0,\n\t\tfailed: 0,\n\t\titems: [],\n\t};\n\tfor (const row of rows) {\n\t\tresult.processed += 1;\n\t\ttry {\n\t\t\tconst advanced = await advanceOperation(store, row.operation_id);\n\t\t\tif (!advanced.advanced) {\n\t\t\t\tif (advanced.state === \"cancelled\") {\n\t\t\t\t\t// Superseded by a duplicate that reached active first; terminal.\n\t\t\t\t\tresult.items.push({ operationId: row.operation_id, outcome: \"superseded\" });\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tstore.db\n\t\t\t\t\t.prepare(\"UPDATE share_operations SET updated_at = ? WHERE operation_id = ?\")\n\t\t\t\t\t.run(maintenanceNow.toISOString(), row.operation_id);\n\t\t\t\tresult.waiting += 1;\n\t\t\t\tresult.items.push({\n\t\t\t\t\toperationId: row.operation_id,\n\t\t\t\t\toutcome: \"waiting_for_acceptance\",\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tresult.advanced += 1;\n\t\t\tresult.items.push({ operationId: row.operation_id, outcome: \"advanced\" });\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tconst state = store.db\n\t\t\t\t.prepare(\"SELECT state FROM share_operations WHERE operation_id = ?\")\n\t\t\t\t.pluck()\n\t\t\t\t.get(row.operation_id);\n\t\t\tif (state === \"cancelled\") {\n\t\t\t\t// Superseded by a duplicate while a step was in flight; the stored\n\t\t\t\t// state is terminal and benign, so the step's rejection must not be\n\t\t\t\t// reported as a failure or push the daemon into an error phase.\n\t\t\t\tresult.items.push({ operationId: row.operation_id, outcome: \"superseded\" });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (message === \"waiting_for_device\" || state === \"waiting_for_device\") {\n\t\t\t\tresult.waiting += 1;\n\t\t\t\tresult.items.push({ operationId: row.operation_id, outcome: \"waiting_for_device\" });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (state === \"needs_attention\") {\n\t\t\t\tresult.attention += 1;\n\t\t\t\tresult.items.push({\n\t\t\t\t\toperationId: row.operation_id,\n\t\t\t\t\toutcome: \"needs_attention\",\n\t\t\t\t\terror: message,\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (state === \"waiting_for_acceptance\") {\n\t\t\t\tconst outcome = recordInviteReconciliationFailure(\n\t\t\t\t\tstore,\n\t\t\t\t\trow.operation_id,\n\t\t\t\t\terror,\n\t\t\t\t\tmaintenanceNow.toISOString(),\n\t\t\t\t);\n\t\t\t\tif (outcome === \"needs_attention\") result.attention += 1;\n\t\t\t\telse result.waiting += 1;\n\t\t\t\tresult.items.push({ operationId: row.operation_id, outcome, error: message });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (TERMINAL_SHARE_MAINTENANCE_ERRORS.has(message)) {\n\t\t\t\tstore.db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\"UPDATE share_operations SET state = 'needs_attention', updated_at = ? WHERE operation_id = ?\",\n\t\t\t\t\t)\n\t\t\t\t\t.run(maintenanceNow.toISOString(), row.operation_id);\n\t\t\t\tresult.attention += 1;\n\t\t\t\tresult.items.push({\n\t\t\t\t\toperationId: row.operation_id,\n\t\t\t\t\toutcome: \"needs_attention\",\n\t\t\t\t\terror: message,\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tresult.failed += 1;\n\t\t\tresult.items.push({\n\t\t\t\toperationId: row.operation_id,\n\t\t\t\toutcome: \"failed\",\n\t\t\t\terror: message,\n\t\t\t});\n\t\t}\n\t}\n\treturn result;\n}\n\nexport interface ReconcileConfiguredCoordinatorEnrollmentResult {\n\tskipped: boolean;\n\tgroupsProcessed: number;\n\tfailedGroups: number;\n\tfailures: CoordinatorEnrollmentMaintenanceFailure[];\n\tdevicesAdded: number;\n\tmembershipsAdded: number;\n\tidentitiesAdded: number;\n\tunchanged: number;\n\tissues: number;\n}\n\nexport type CoordinatorEnrollmentMaintenanceStage =\n\t| \"list_devices\"\n\t| \"list_consumed_team_invites\"\n\t| \"reconcile_snapshot\";\n\nexport interface CoordinatorEnrollmentMaintenanceFailure {\n\tgroupId: string;\n\tstage: CoordinatorEnrollmentMaintenanceStage;\n\tcode: string;\n}\n\nfunction coordinatorEnrollmentFailureCode(error: unknown): string {\n\tconst message = (error instanceof Error ? error.message : String(error)).trim();\n\tconst httpStatus = message.match(/\\((\\d{3})(?::|\\))/u)?.[1];\n\tif (httpStatus) return `http_${httpStatus}`;\n\tif (\n\t\tnew Set([\n\t\t\t\"coordinator_consumed_team_invite_invalid\",\n\t\t\t\"coordinator_device_list_malformed\",\n\t\t\t\"coordinator_group_id_invalid\",\n\t\t\t\"coordinator_id_invalid\",\n\t\t\t\"coordinator_invite_group_mismatch\",\n\t\t\t\"coordinator_invite_list_malformed\",\n\t\t\t\"reconciliation_time_invalid\",\n\t\t]).has(message)\n\t) {\n\t\treturn message;\n\t}\n\tif (/timeout|timed out|abort/iu.test(message)) return \"request_timeout\";\n\tif (/fetch failed|network|econn|enotfound/iu.test(message)) return \"network_error\";\n\treturn \"unexpected_error\";\n}\n\nfunction coordinatorEnrollmentFailure(\n\tgroupId: string,\n\tstage: CoordinatorEnrollmentMaintenanceStage,\n\terror: unknown,\n): CoordinatorEnrollmentMaintenanceFailure {\n\tconst safeGroupId = /^[A-Za-z0-9._-]{1,64}$/u.test(groupId)\n\t\t? groupId\n\t\t: `group_${createHash(\"sha256\").update(groupId).digest(\"hex\").slice(0, 12)}`;\n\treturn { groupId: safeGroupId, stage, code: coordinatorEnrollmentFailureCode(error) };\n}\n\nexport async function reconcileConfiguredCoordinatorEnrollment(\n\tstore: MemoryStore,\n\toptions: {\n\t\tconfig?: ReturnType<typeof readCoordinatorSyncConfig>;\n\t\tlistDevices?: (input: {\n\t\t\tgroupId: string;\n\t\t\tremoteUrl: string;\n\t\t\tadminSecret: string;\n\t\t}) => Promise<CoordinatorEnrollment[]>;\n\t\tlistConsumedTeamInvites?: (input: {\n\t\t\tgroupId: string;\n\t\t\tremoteUrl: string;\n\t\t\tadminSecret: string;\n\t\t}) => Promise<CoordinatorConsumedTeamInvite[]>;\n\t\treconcileSnapshot?: (\n\t\t\tinput: Parameters<typeof reconcileCoordinatorEnrollmentSnapshot>[1],\n\t\t) => CoordinatorEnrollmentReconcileResult | Promise<CoordinatorEnrollmentReconcileResult>;\n\t} = {},\n): Promise<ReconcileConfiguredCoordinatorEnrollmentResult> {\n\tconst config = options.config ?? readCoordinatorSyncConfig();\n\tconst remoteUrl = config.syncCoordinatorUrl.trim();\n\tconst adminSecret = config.syncCoordinatorAdminSecret.trim();\n\tif (!remoteUrl || !adminSecret || config.syncCoordinatorGroups.length === 0) {\n\t\treturn {\n\t\t\tskipped: true,\n\t\t\tgroupsProcessed: 0,\n\t\t\tfailedGroups: 0,\n\t\t\tfailures: [],\n\t\t\tdevicesAdded: 0,\n\t\t\tmembershipsAdded: 0,\n\t\t\tidentitiesAdded: 0,\n\t\t\tunchanged: 0,\n\t\t\tissues: 0,\n\t\t};\n\t}\n\tconst listDevices = options.listDevices ?? coordinatorListDevicesAction;\n\tconst listConsumedTeamInvites =\n\t\toptions.listConsumedTeamInvites ?? coordinatorListConsumedTeamInvitesAction;\n\tconst reconcileSnapshot =\n\t\toptions.reconcileSnapshot ??\n\t\t((input) => reconcileCoordinatorEnrollmentSnapshot(store.db, input));\n\tconst total: ReconcileConfiguredCoordinatorEnrollmentResult = {\n\t\tskipped: false,\n\t\tgroupsProcessed: 0,\n\t\tfailedGroups: 0,\n\t\tfailures: [],\n\t\tdevicesAdded: 0,\n\t\tmembershipsAdded: 0,\n\t\tidentitiesAdded: 0,\n\t\tunchanged: 0,\n\t\tissues: 0,\n\t};\n\tfor (const groupId of config.syncCoordinatorGroups) {\n\t\tconst [enrollmentsResult, consumedTeamInvitesResult] = await Promise.allSettled([\n\t\t\tlistDevices({ groupId, remoteUrl, adminSecret }),\n\t\t\tlistConsumedTeamInvites({ groupId, remoteUrl, adminSecret }),\n\t\t]);\n\t\tif (enrollmentsResult.status === \"rejected\") {\n\t\t\ttotal.failures.push(\n\t\t\t\tcoordinatorEnrollmentFailure(groupId, \"list_devices\", enrollmentsResult.reason),\n\t\t\t);\n\t\t}\n\t\tif (consumedTeamInvitesResult.status === \"rejected\") {\n\t\t\ttotal.failures.push(\n\t\t\t\tcoordinatorEnrollmentFailure(\n\t\t\t\t\tgroupId,\n\t\t\t\t\t\"list_consumed_team_invites\",\n\t\t\t\t\tconsumedTeamInvitesResult.reason,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\tenrollmentsResult.status === \"rejected\" ||\n\t\t\tconsumedTeamInvitesResult.status === \"rejected\"\n\t\t) {\n\t\t\ttotal.failedGroups += 1;\n\t\t\tcontinue;\n\t\t}\n\t\ttry {\n\t\t\tconst result = await reconcileSnapshot({\n\t\t\t\tcoordinatorId: buildBaseUrl(remoteUrl),\n\t\t\t\tgroupId,\n\t\t\t\tenrollments: enrollmentsResult.value,\n\t\t\t\tconsumedTeamInvites: consumedTeamInvitesResult.value,\n\t\t\t\tlocalDeviceId: store.deviceId,\n\t\t\t});\n\t\t\ttotal.groupsProcessed += 1;\n\t\t\ttotal.devicesAdded += result.devicesAdded;\n\t\t\ttotal.membershipsAdded += result.membershipsAdded;\n\t\t\ttotal.identitiesAdded += result.identitiesAdded;\n\t\t\ttotal.unchanged += result.unchanged;\n\t\t\ttotal.issues += result.issues.length;\n\t\t} catch (error) {\n\t\t\ttotal.failedGroups += 1;\n\t\t\ttotal.failures.push(coordinatorEnrollmentFailure(groupId, \"reconcile_snapshot\", error));\n\t\t}\n\t}\n\treturn total;\n}\n\nconst RECIPIENT_POLICY_MAINTENANCE_MAX_LIMIT = 10;\nconst RECIPIENT_POLICY_MAINTENANCE_DEFAULT_LIMIT = 3;\nconst RECIPIENT_POLICY_MAINTENANCE_BACKOFF_MS = 60_000;\nconst RECIPIENT_POLICY_WAITING_ERRORS = new Set([\n\t\"recipient_policy_capability_undetermined\",\n\t\"recipient_policy_parity_incomplete\",\n\t\"recipient_policy_snapshot_not_fresh\",\n]);\n\ninterface RecipientPolicyCoordinatorBoundary {\n\tcoordinatorId: string;\n\tgroupId: string;\n\tmembershipEpoch: number;\n}\n\nfunction recipientPolicyCoordinatorBoundary(\n\tstore: MemoryStore,\n\tscopeId: string,\n): RecipientPolicyCoordinatorBoundary {\n\tconst row = store.db\n\t\t.prepare(\n\t\t\t`SELECT coordinator_id, group_id, membership_epoch FROM replication_scopes\n\t\t\t WHERE scope_id = ? AND kind = 'managed_project' AND authority_type = 'coordinator'\n\t\t\t AND status = 'active'`,\n\t\t)\n\t\t.get(scopeId) as\n\t\t| {\n\t\t\t\tcoordinator_id: string | null;\n\t\t\t\tgroup_id: string | null;\n\t\t\t\tmembership_epoch: number;\n\t\t }\n\t\t| undefined;\n\tconst coordinatorId = String(row?.coordinator_id ?? \"\").trim();\n\tconst groupId = String(row?.group_id ?? \"\").trim();\n\tconst membershipEpoch = Number(row?.membership_epoch);\n\tif (!coordinatorId || !groupId || !Number.isSafeInteger(membershipEpoch) || membershipEpoch < 0) {\n\t\tthrow new Error(\"recipient_policy_active_managed_scope_required\");\n\t}\n\treturn { coordinatorId, groupId, membershipEpoch };\n}\n\nfunction recipientPolicySnapshotFingerprint(\n\tscopeId: string,\n\tscopeMembershipEpoch: number,\n\tmemberships: Array<{\n\t\tdeviceId: string;\n\t\tstatus: \"active\" | \"revoked\";\n\t\tmembershipEpoch: number;\n\t}>,\n): string {\n\tconst canonical = memberships\n\t\t.toSorted(\n\t\t\t(left, right) =>\n\t\t\t\tleft.deviceId.localeCompare(right.deviceId) ||\n\t\t\t\tleft.status.localeCompare(right.status) ||\n\t\t\t\tleft.membershipEpoch - right.membershipEpoch,\n\t\t)\n\t\t.map(\n\t\t\t(membership) =>\n\t\t\t\t`${membership.deviceId}\\u0000${membership.status}\\u0000${membership.membershipEpoch}`,\n\t\t)\n\t\t.join(\"\\u0001\");\n\treturn `recipient-policy-coordinator-snapshot-v2:${createHash(\"sha256\")\n\t\t.update(`${scopeId}\\u0000${scopeMembershipEpoch}\\u0000${canonical}`)\n\t\t.digest(\"hex\")}`;\n}\n\nfunction recipientPolicyPresenceCapabilityExpiresAt(\n\tenrollment: CoordinatorEnrollment,\n\tobservedAt: string,\n): number | null {\n\tconst expiresAt = enrollment.presence_expires_at;\n\tconst capabilities = enrollment.presence_capabilities;\n\tif (typeof expiresAt !== \"string\" || !capabilities) return null;\n\tconst expiresAtMs = Date.parse(expiresAt);\n\tconst observedAtMs = Date.parse(observedAt);\n\tif (\n\t\t!Number.isFinite(expiresAtMs) ||\n\t\t!Number.isFinite(observedAtMs) ||\n\t\tnew Date(expiresAtMs).toISOString() !== expiresAt ||\n\t\texpiresAtMs <= observedAtMs ||\n\t\tcapabilities.sync_capability !== \"scoped\" ||\n\t\t!Array.isArray(capabilities.sync_features) ||\n\t\t!capabilities.sync_features.every((feature) => typeof feature === \"string\") ||\n\t\t!capabilities.sync_features.includes(\"reassign_scope\")\n\t) {\n\t\treturn null;\n\t}\n\treturn expiresAtMs;\n}\n\nfunction recipientPolicyEnrollmentValueIsValid(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length > 0 && value === value.trim();\n}\n\nexport function createRecipientPolicyReconcilerEffects(\n\tstore: MemoryStore,\n\toptions: {\n\t\tconfig?: ReturnType<typeof readCoordinatorSyncConfig>;\n\t\tnow?: () => string;\n\t\tlistDevices?: typeof coordinatorListDevicesAction;\n\t\tlistReviewedRecipientInviteEvidence?: typeof coordinatorListReviewedRecipientInviteEvidenceAction;\n\t} = {},\n): RecipientPolicyReconcilerEffects {\n\tconst config = options.config ?? readCoordinatorSyncConfig();\n\tconst now = options.now ?? (() => new Date().toISOString());\n\tconst listDevices = options.listDevices ?? coordinatorListDevicesAction;\n\tconst listReviewedRecipientInviteEvidence =\n\t\toptions.listReviewedRecipientInviteEvidence ??\n\t\tcoordinatorListReviewedRecipientInviteEvidenceAction;\n\tconst reviewedRecipientInviteEvidence = new Map<\n\t\tstring,\n\t\tReturnType<typeof coordinatorListReviewedRecipientInviteEvidenceAction>\n\t>();\n\tconst loadReviewedRecipientInviteEvidence = (groupId: string) => {\n\t\tlet evidence = reviewedRecipientInviteEvidence.get(groupId);\n\t\tif (!evidence) {\n\t\t\tevidence = listReviewedRecipientInviteEvidence({\n\t\t\t\tgroupId,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\treviewedRecipientInviteEvidence.set(groupId, evidence);\n\t\t}\n\t\treturn evidence;\n\t};\n\tconst boundaryEnrollments = new Map<\n\t\tstring,\n\t\tMap<\n\t\t\tstring,\n\t\t\t{\n\t\t\t\tidentityId: string;\n\t\t\t\tpublicKey: string;\n\t\t\t\tfingerprint: string;\n\t\t\t\tpresenceCapabilityExpiresAtMs: number | null;\n\t\t\t}\n\t\t>\n\t>();\n\tconst target = (scopeId: string) => recipientPolicyCoordinatorBoundary(store, scopeId);\n\tconst coordinatorOptions = (scopeId: string) => {\n\t\tconst boundary = target(scopeId);\n\t\tconst remoteUrl = config.syncCoordinatorUrl?.trim();\n\t\tconst adminSecret = config.syncCoordinatorAdminSecret?.trim();\n\t\tif (!remoteUrl || !adminSecret) throw new Error(\"recipient_policy_effect_failed\");\n\t\tif (!config.syncCoordinatorGroups.includes(boundary.groupId)) {\n\t\t\tthrow new Error(\"recipient_policy_effect_failed\");\n\t\t}\n\t\ttry {\n\t\t\tif (buildBaseUrl(boundary.coordinatorId) !== buildBaseUrl(remoteUrl)) {\n\t\t\t\tthrow new Error(\"recipient_policy_effect_failed\");\n\t\t\t}\n\t\t} catch {\n\t\t\tthrow new Error(\"recipient_policy_effect_failed\");\n\t\t}\n\t\treturn {\n\t\t\t...boundary,\n\t\t\tremoteUrl,\n\t\t\tadminSecret,\n\t\t};\n\t};\n\treturn {\n\t\tnow,\n\t\tsnapshot: async ({ scopeId }) => {\n\t\t\tconst targetOptions = coordinatorOptions(scopeId);\n\t\t\tconst memberships = await coordinatorListScopeMembershipsAction({\n\t\t\t\tgroupId: targetOptions.groupId,\n\t\t\t\tscopeId,\n\t\t\t\tincludeRevoked: true,\n\t\t\t\tremoteUrl: targetOptions.remoteUrl,\n\t\t\t\tadminSecret: targetOptions.adminSecret,\n\t\t\t}).catch(() => {\n\t\t\t\tthrow new Error(\"recipient_policy_snapshot_not_fresh\");\n\t\t\t});\n\t\t\tconst snapshotMemberships = memberships.map((membership) => {\n\t\t\t\tif (\n\t\t\t\t\ttypeof membership.device_id !== \"string\" ||\n\t\t\t\t\t(membership.status !== \"active\" && membership.status !== \"revoked\")\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"recipient_policy_snapshot_invalid\");\n\t\t\t\t}\n\t\t\t\tconst status: \"active\" | \"revoked\" = membership.status;\n\t\t\t\treturn {\n\t\t\t\t\tdeviceId: membership.device_id,\n\t\t\t\t\tstatus,\n\t\t\t\t\tmembershipEpoch: membership.membership_epoch,\n\t\t\t\t};\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tauthoritative: true,\n\t\t\t\tscopeId,\n\t\t\t\tscopeMembershipEpoch: targetOptions.membershipEpoch,\n\t\t\t\tfingerprint: recipientPolicySnapshotFingerprint(\n\t\t\t\t\tscopeId,\n\t\t\t\t\ttargetOptions.membershipEpoch,\n\t\t\t\t\tsnapshotMemberships,\n\t\t\t\t),\n\t\t\t\tobservedAt: now(),\n\t\t\t\tmemberships: snapshotMemberships,\n\t\t\t};\n\t\t},\n\t\tlistBoundaryEnrollments: async ({ scopeId }) => {\n\t\t\tconst targetOptions = coordinatorOptions(scopeId);\n\t\t\tconst observedAt = now();\n\t\t\tconst enrollments = await listDevices({\n\t\t\t\tgroupId: targetOptions.groupId,\n\t\t\t\tincludeDisabled: true,\n\t\t\t\tremoteUrl: targetOptions.remoteUrl,\n\t\t\t\tadminSecret: targetOptions.adminSecret,\n\t\t\t}).catch(() => {\n\t\t\t\tthrow new Error(\"recipient_policy_snapshot_not_fresh\");\n\t\t\t});\n\t\t\tconst presenceCapabilityExpiries = new Map(\n\t\t\t\tenrollments.map((enrollment) => [\n\t\t\t\t\tenrollment.device_id,\n\t\t\t\t\trecipientPolicyPresenceCapabilityExpiresAt(enrollment, observedAt),\n\t\t\t\t]),\n\t\t\t);\n\t\t\tconst mapped = enrollments.map((enrollment) => {\n\t\t\t\tif (\n\t\t\t\t\tenrollment.group_id !== targetOptions.groupId ||\n\t\t\t\t\t!recipientPolicyEnrollmentValueIsValid(enrollment.device_id) ||\n\t\t\t\t\t!recipientPolicyEnrollmentValueIsValid(enrollment.public_key) ||\n\t\t\t\t\t!recipientPolicyEnrollmentValueIsValid(enrollment.fingerprint) ||\n\t\t\t\t\tfingerprintPublicKey(enrollment.public_key) !== enrollment.fingerprint ||\n\t\t\t\t\t(enrollment.enabled !== 0 && enrollment.enabled !== 1) ||\n\t\t\t\t\t(enrollment.identity_id !== null &&\n\t\t\t\t\t\t!recipientPolicyEnrollmentValueIsValid(enrollment.identity_id))\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"recipient_policy_snapshot_invalid\");\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tdeviceId: enrollment.device_id,\n\t\t\t\t\tidentityId: enrollment.identity_id,\n\t\t\t\t\tpublicKey: enrollment.public_key,\n\t\t\t\t\tfingerprint: enrollment.fingerprint,\n\t\t\t\t\tenabled: enrollment.enabled === 1,\n\t\t\t\t};\n\t\t\t});\n\t\t\tboundaryEnrollments.set(\n\t\t\t\tscopeId,\n\t\t\t\tnew Map(\n\t\t\t\t\tmapped.flatMap((enrollment) =>\n\t\t\t\t\t\tenrollment.enabled && enrollment.identityId !== null\n\t\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\tenrollment.deviceId,\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tidentityId: enrollment.identityId,\n\t\t\t\t\t\t\t\t\t\t\tpublicKey: enrollment.publicKey,\n\t\t\t\t\t\t\t\t\t\t\tfingerprint: enrollment.fingerprint,\n\t\t\t\t\t\t\t\t\t\t\tpresenceCapabilityExpiresAtMs:\n\t\t\t\t\t\t\t\t\t\t\t\tpresenceCapabilityExpiries.get(enrollment.deviceId) ?? null,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t] as const,\n\t\t\t\t\t\t\t\t]\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\treturn mapped;\n\t\t},\n\t\tprobeCapability: async ({ deviceId, scopeId }) => {\n\t\t\tif (deviceId === store.deviceId) return \"supported\";\n\t\t\t// Reconciliation always lists this scope's enrollments before capability\n\t\t\t// preflight. A missing binding still fails closed if that order changes.\n\t\t\tconst targetOptions = coordinatorOptions(scopeId);\n\t\t\tconst enrollment = boundaryEnrollments.get(scopeId)?.get(deviceId);\n\t\t\tif (!enrollment) return \"undetermined\";\n\t\t\tconst peer = store.db\n\t\t\t\t.prepare(\"SELECT pinned_fingerprint, public_key FROM sync_peers WHERE peer_device_id = ?\")\n\t\t\t\t.get(deviceId) as\n\t\t\t\t| { pinned_fingerprint: string | null; public_key: string | null }\n\t\t\t\t| undefined;\n\t\t\tif (peer) {\n\t\t\t\tconst peerPublicKey = String(peer.public_key ?? \"\").trim();\n\t\t\t\tconst peerFingerprint =\n\t\t\t\t\tString(peer.pinned_fingerprint ?? \"\").trim() ||\n\t\t\t\t\t(peerPublicKey ? fingerprintPublicKey(peerPublicKey) : \"\");\n\t\t\t\tif (\n\t\t\t\t\t(peerFingerprint || peerPublicKey) &&\n\t\t\t\t\t(peerFingerprint !== enrollment.fingerprint ||\n\t\t\t\t\t\t(peerPublicKey && peerPublicKey !== enrollment.publicKey))\n\t\t\t\t) {\n\t\t\t\t\treturn \"undetermined\";\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst observed = await peerSupportsSyncRequirements(store, deviceId, {\n\t\t\t\tscoped: true,\n\t\t\t\treassignScope: true,\n\t\t\t});\n\t\t\tif (observed !== \"undetermined\") return observed;\n\t\t\tconst observedAtMs = Date.parse(now());\n\t\t\tif (\n\t\t\t\tenrollment.presenceCapabilityExpiresAtMs == null ||\n\t\t\t\t!Number.isFinite(observedAtMs) ||\n\t\t\t\tenrollment.presenceCapabilityExpiresAtMs <= observedAtMs\n\t\t\t) {\n\t\t\t\treturn \"undetermined\";\n\t\t\t}\n\t\t\t// A consumed, still-reviewed Team/add-device invite is the only bootstrap\n\t\t\t// identity proof accepted before normal peer discovery can observe the new\n\t\t\t// device. Fresh authenticated presence separately proves capability.\n\t\t\tconst evidence = await loadReviewedRecipientInviteEvidence(targetOptions.groupId).catch(\n\t\t\t\t() => [],\n\t\t\t);\n\t\t\treturn evidence.some(\n\t\t\t\t(invite) =>\n\t\t\t\t\tinvite.group_id === targetOptions.groupId &&\n\t\t\t\t\tinvite.bound_device_id === deviceId &&\n\t\t\t\t\tinvite.recipient_actor_id === enrollment.identityId &&\n\t\t\t\t\tinvite.bound_public_key === enrollment.publicKey &&\n\t\t\t\t\tinvite.bound_fingerprint === enrollment.fingerprint,\n\t\t\t)\n\t\t\t\t? \"supported\"\n\t\t\t\t: \"undetermined\";\n\t\t},\n\t\trevoke: async (input): Promise<RecipientPolicyCoordinatorEffectReceipt> => {\n\t\t\tconst targetOptions = coordinatorOptions(input.scopeId);\n\t\t\tawait coordinatorRevokeScopeMembershipAction({\n\t\t\t\teffectId: input.effectId,\n\t\t\t\tgroupId: targetOptions.groupId,\n\t\t\t\tscopeId: input.scopeId,\n\t\t\t\tdeviceId: input.deviceId,\n\t\t\t\tremoteUrl: targetOptions.remoteUrl,\n\t\t\t\tadminSecret: targetOptions.adminSecret,\n\t\t\t});\n\t\t\treturn {\n\t\t\t\teffectId: input.effectId,\n\t\t\t\tscopeId: input.scopeId,\n\t\t\t\tdeviceId: input.deviceId,\n\t\t\t\tstatus: \"revoked\",\n\t\t\t};\n\t\t},\n\t\tgrant: async (input): Promise<RecipientPolicyCoordinatorEffectReceipt> => {\n\t\t\tconst targetOptions = coordinatorOptions(input.scopeId);\n\t\t\tconst membership = await coordinatorGrantScopeMembershipAction({\n\t\t\t\teffectId: input.effectId,\n\t\t\t\tgroupId: targetOptions.groupId,\n\t\t\t\tscopeId: input.scopeId,\n\t\t\t\tdeviceId: input.deviceId,\n\t\t\t\trole: input.role,\n\t\t\t\tcoordinatorId: targetOptions.coordinatorId,\n\t\t\t\tremoteUrl: targetOptions.remoteUrl,\n\t\t\t\tadminSecret: targetOptions.adminSecret,\n\t\t\t});\n\t\t\treturn {\n\t\t\t\teffectId: input.effectId,\n\t\t\t\tscopeId: membership.scope_id,\n\t\t\t\tdeviceId: membership.device_id,\n\t\t\t\tstatus: membership.status === \"active\" ? \"active\" : \"revoked\",\n\t\t\t};\n\t\t},\n\t\trefresh: async ({ scopeId }) => {\n\t\t\tconst boundary = target(scopeId);\n\t\t\tconst refreshed = await refreshConfiguredScopeMembershipCache(store.db, config, {\n\t\t\t\tkeysDir: syncKeysDir(),\n\t\t\t\tdbPath: store.dbPath,\n\t\t\t});\n\t\t\tconst group = refreshed.groups.find((item) => item.groupId === boundary.groupId);\n\t\t\tif (group?.status !== \"refreshed\") throw new Error(\"recipient_policy_effect_failed\");\n\t\t\tawait refreshAuthorizedCoordinatorPeerTrust(store, config);\n\t\t},\n\t};\n}\n\nexport interface ReconcileRecipientPolicyProjectsResult {\n\tprocessed: number;\n\tactive: number;\n\twaiting: number;\n\tattention: number;\n\tfailed: number;\n\titems: Array<{\n\t\tcanonicalProjectIdentity: string;\n\t\tstatus: RecipientPolicyReconcileResult[\"status\"] | \"failed\";\n\t\tsafeErrorCode: string | null;\n\t}>;\n}\n\nexport async function reconcileRecipientPolicyProjects(\n\tstore: MemoryStore,\n\toptions: {\n\t\tlimit?: number;\n\t\tnow?: Date;\n\t\tbackoffMs?: number;\n\t\tleaseOwner?: string;\n\t\teffects?: RecipientPolicyReconcilerEffects;\n\t\treconcileProject?: typeof reconcileRecipientPolicyProject;\n\t} = {},\n): Promise<ReconcileRecipientPolicyProjectsResult> {\n\tconst limit = Math.max(\n\t\t1,\n\t\tMath.min(\n\t\t\tMath.trunc(options.limit ?? RECIPIENT_POLICY_MAINTENANCE_DEFAULT_LIMIT),\n\t\t\tRECIPIENT_POLICY_MAINTENANCE_MAX_LIMIT,\n\t\t),\n\t);\n\tconst maintenanceNow = options.now ?? new Date();\n\tconst backoffMs = Math.max(\n\t\t0,\n\t\tMath.trunc(options.backoffMs ?? RECIPIENT_POLICY_MAINTENANCE_BACKOFF_MS),\n\t);\n\tconst retryBefore = new Date(maintenanceNow.getTime() - backoffMs).toISOString();\n\tconst rows = store.db\n\t\t.prepare(\n\t\t\t`WITH projects AS (\n\t\t\t\tSELECT DISTINCT canonical_project_identity FROM project_recipients\n\t\t\t\tUNION\n\t\t\t\tSELECT canonical_project_identity FROM recipient_policy_authority_states\n\t\t\t)\n\t\t\t SELECT projects.canonical_project_identity\n\t\t\t FROM projects\n\t\t\t LEFT JOIN recipient_policy_authority_states authority\n\t\t\t ON authority.canonical_project_identity = projects.canonical_project_identity\n\t\t\t WHERE authority.safe_error_code IS NULL OR authority.last_attempt_at IS NULL\n\t\t\t OR authority.last_attempt_at <= ?\n\t\t\t ORDER BY CASE WHEN authority.last_attempt_at IS NULL THEN 0 ELSE 1 END,\n\t\t\t authority.last_attempt_at, projects.canonical_project_identity\n\t\t\t LIMIT ?`,\n\t\t)\n\t\t.all(retryBefore, limit) as Array<{ canonical_project_identity: string }>;\n\tconst effects = options.effects ?? createRecipientPolicyReconcilerEffects(store);\n\tconst reconcileProject = options.reconcileProject ?? reconcileRecipientPolicyProject;\n\tconst result: ReconcileRecipientPolicyProjectsResult = {\n\t\tprocessed: 0,\n\t\tactive: 0,\n\t\twaiting: 0,\n\t\tattention: 0,\n\t\tfailed: 0,\n\t\titems: [],\n\t};\n\tfor (const row of rows) {\n\t\tresult.processed += 1;\n\t\ttry {\n\t\t\tconst outcome = await reconcileProject(\n\t\t\t\tstore.db,\n\t\t\t\t{\n\t\t\t\t\tcanonicalProjectIdentity: row.canonical_project_identity,\n\t\t\t\t\tleaseOwner:\n\t\t\t\t\t\toptions.leaseOwner ?? `recipient-policy-maintenance:${store.deviceId || process.pid}`,\n\t\t\t\t},\n\t\t\t\teffects,\n\t\t\t);\n\t\t\tif (outcome.status === \"active\") result.active += 1;\n\t\t\telse if (outcome.status === \"needs_attention\") result.attention += 1;\n\t\t\telse result.waiting += 1;\n\t\t\tresult.items.push({\n\t\t\t\tcanonicalProjectIdentity: row.canonical_project_identity,\n\t\t\t\tstatus: outcome.status,\n\t\t\t\tsafeErrorCode: outcome.safeErrorCode,\n\t\t\t});\n\t\t} catch {\n\t\t\tresult.failed += 1;\n\t\t\tresult.items.push({\n\t\t\t\tcanonicalProjectIdentity: row.canonical_project_identity,\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tsafeErrorCode: \"recipient_policy_reconciliation_failed\",\n\t\t\t});\n\t\t}\n\t}\n\treturn result;\n}\n\nexport type RecipientPolicyReconciliationReadState =\n\t| \"active\"\n\t| \"needs_attention\"\n\t| \"pending\"\n\t| \"verifying\"\n\t| \"waiting\";\n\nexport interface RecipientPolicyReconciliationReadModel {\n\tversion: 1;\n\titems: Array<{\n\t\tcanonicalProjectIdentity: string;\n\t\tstate: RecipientPolicyReconciliationReadState;\n\t\tlabel: string;\n\t\texplanation: string;\n\t\tdeliveredCopiesMayRemain: true;\n\t\trevocationWarning: string;\n\t}>;\n}\n\nfunction recipientPolicyReadState(\n\tauthority: ReturnType<typeof getRecipientPolicyAuthorityState>,\n): RecipientPolicyReconciliationReadState {\n\tif (!authority) return \"pending\";\n\tif (authority.safeErrorCode && RECIPIENT_POLICY_WAITING_ERRORS.has(authority.safeErrorCode)) {\n\t\treturn \"waiting\";\n\t}\n\tif (authority.safeErrorCode || authority.authorityState === \"rolled_back\") {\n\t\treturn \"needs_attention\";\n\t}\n\tif (authority.authorityState === \"active\") return \"active\";\n\tif (authority.authorityState === \"eligible\") return \"verifying\";\n\treturn \"pending\";\n}\n\nfunction recipientPolicyReadCopy(state: RecipientPolicyReconciliationReadState): {\n\tlabel: string;\n\texplanation: string;\n} {\n\tif (state === \"active\") {\n\t\treturn {\n\t\t\tlabel: \"Recipient policy active\",\n\t\t\texplanation: \"Recipient policy now controls future access for this Project.\",\n\t\t};\n\t}\n\tif (state === \"verifying\") {\n\t\treturn {\n\t\t\tlabel: \"Verifying recipient policy\",\n\t\t\texplanation: \"Current access matches recipient policy and needs one more stable check.\",\n\t\t};\n\t}\n\tif (state === \"waiting\") {\n\t\treturn {\n\t\t\tlabel: \"Waiting to reconcile\",\n\t\t\texplanation:\n\t\t\t\t\"Waiting for devices or a fresh coordinator snapshot. No partial grant is applied.\",\n\t\t};\n\t}\n\tif (state === \"needs_attention\") {\n\t\treturn {\n\t\t\tlabel: \"Reconciliation needs attention\",\n\t\t\texplanation:\n\t\t\t\t\"Legacy scope enforcement remains in control until this Project is safe to retry.\",\n\t\t};\n\t}\n\treturn {\n\t\tlabel: \"Recipient policy pending\",\n\t\texplanation: \"Legacy scope enforcement remains in control while reconciliation is pending.\",\n\t};\n}\n\nexport function listRecipientPolicyReconciliationStatus(\n\tstore: MemoryStore,\n): RecipientPolicyReconciliationReadModel {\n\tconst projectIds = (\n\t\tstore.db\n\t\t\t.prepare(\n\t\t\t\t`SELECT DISTINCT canonical_project_identity FROM project_recipients WHERE status = 'active'\n\t\t\t\t UNION SELECT canonical_project_identity FROM recipient_policy_authority_states\n\t\t\t\t ORDER BY canonical_project_identity`,\n\t\t\t)\n\t\t\t.all() as Array<{ canonical_project_identity: string }>\n\t).map((row) => row.canonical_project_identity);\n\treturn {\n\t\tversion: 1,\n\t\titems: projectIds.map((canonicalProjectIdentity) => {\n\t\t\tconst state = recipientPolicyReadState(\n\t\t\t\tgetRecipientPolicyAuthorityState(store.db, canonicalProjectIdentity),\n\t\t\t);\n\t\t\treturn {\n\t\t\t\tcanonicalProjectIdentity,\n\t\t\t\tstate,\n\t\t\t\t...recipientPolicyReadCopy(state),\n\t\t\t\tdeliveredCopiesMayRemain: true,\n\t\t\t\trevocationWarning: SCOPE_MEMBERSHIP_REVOCATION_LIMITATION,\n\t\t\t};\n\t\t}),\n\t};\n}\n\nfunction sortActiveMaintenanceJobs<\n\tT extends { started_at: string | null; updated_at: string; kind: string },\n>(jobs: T[]): T[] {\n\treturn [...jobs].sort((a, b) => {\n\t\tconst aTime = a.started_at ?? a.updated_at;\n\t\tconst bTime = b.started_at ?? b.updated_at;\n\t\tif (aTime !== bTime) return aTime.localeCompare(bTime);\n\t\treturn a.kind.localeCompare(b.kind);\n\t});\n}\n\nfunction summarizeMaintenanceJobs(\n\tjobs: MaintenanceJobSnapshot[],\n\tshowDiagnostics: boolean,\n): Array<Record<string, unknown>> {\n\treturn sortActiveMaintenanceJobs(\n\t\tjobs.filter((job) => [\"pending\", \"running\", \"failed\"].includes(String(job.status ?? \"\"))),\n\t).map((job) => ({\n\t\tkind: job.kind,\n\t\ttitle: job.title,\n\t\tstatus: job.status,\n\t\tprogress: job.progress,\n\t\t...(showDiagnostics\n\t\t\t? {\n\t\t\t\t\tmessage: job.message,\n\t\t\t\t\terror: job.error,\n\t\t\t\t\tmetadata: job.metadata,\n\t\t\t\t}\n\t\t\t: {}),\n\t}));\n}\n\nfunction redactSemanticIndexDiagnostics(\n\tdiagnostics: SemanticIndexDiagnostics,\n\tshowDiagnostics: boolean,\n): SemanticIndexDiagnostics {\n\tif (showDiagnostics || !diagnostics.maintenance_job) {\n\t\treturn diagnostics;\n\t}\n\tconst summary =\n\t\tdiagnostics.state === \"pending\"\n\t\t\t? \"Semantic-index catch-up is pending\"\n\t\t\t: diagnostics.state === \"failed\"\n\t\t\t\t? \"Semantic-index catch-up failed\"\n\t\t\t\t: diagnostics.state === \"degraded\"\n\t\t\t\t\t? \"Semantic index is running in degraded mode\"\n\t\t\t\t\t: diagnostics.summary;\n\treturn {\n\t\t...diagnostics,\n\t\tsummary,\n\t\tmaintenance_job: {\n\t\t\t...diagnostics.maintenance_job,\n\t\t\tmessage: null,\n\t\t\terror: null,\n\t\t},\n\t};\n}\n\nfunction syncKeysDir(): string | undefined {\n\treturn process.env.CODEMEM_KEYS_DIR?.trim() || undefined;\n}\n\n/** Strip control/format characters and cap length so attacker-controlled\n * headers cannot forge log lines when included in diagnostics. */\nfunction loggableHeaderValue(value: string | undefined): string {\n\tconst sanitized = (value ?? \"\")\n\t\t.replace(/[\\p{Cc}\\p{Cf}]/gu, \"\")\n\t\t.slice(0, 64)\n\t\t.trim();\n\treturn sanitized || \"unknown\";\n}\n\nfunction intEnvOr(name: string, fallback: number): number {\n\tconst value = Number.parseInt(process.env[name] ?? \"\", 10);\n\treturn Number.isFinite(value) ? value : fallback;\n}\n\nconst MAX_SYNC_BODY_BYTES = intEnvOr(\"CODEMEM_SYNC_MAX_BODY_BYTES\", 1_048_576);\nconst MAX_SYNC_OPS = intEnvOr(\"CODEMEM_SYNC_MAX_OPS\", 2000);\n\nasync function readBoundedRequestBytes(request: Request, maxBytes: number): Promise<Buffer | null> {\n\tconst contentLength = Number.parseInt(request.headers.get(\"content-length\") ?? \"\", 10);\n\tif (Number.isFinite(contentLength) && contentLength > maxBytes) {\n\t\treturn null;\n\t}\n\tconst stream = request.body;\n\tif (!stream) return Buffer.alloc(0);\n\tconst reader = stream.getReader();\n\tconst chunks: Uint8Array[] = [];\n\tlet total = 0;\n\ttry {\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) break;\n\t\t\tif (!value) continue;\n\t\t\ttotal += value.byteLength;\n\t\t\tif (total > maxBytes) {\n\t\t\t\tawait reader.cancel();\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tchunks.push(value);\n\t\t}\n\t} finally {\n\t\treader.releaseLock();\n\t}\n\treturn Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)));\n}\n\nconst PAIRING_FILTER_HINT =\n\t\"Run this on another device with codemem sync pair --accept '<payload>'. \" +\n\t\"On the accepting device, --include/--exclude control both what it sends and what it accepts from that peer.\";\n\nfunction pathWithQuery(url: string): string {\n\tconst parsed = new URL(url);\n\treturn parsed.search ? `${parsed.pathname}${parsed.search}` : parsed.pathname;\n}\n\nfunction unauthorizedPayload(): Record<string, string> {\n\treturn { error: \"unauthorized\" };\n}\n\nconst SYNC_AUTH_STORE_BUSY_REASON = \"sync_auth_store_busy\";\n\ntype SyncAuthResult = { ok: boolean; reason: string; deviceId: string };\ntype VerifiedDirectPeerSignature = { ok: true; version: 2 | 3 } | { ok: false; reason: string };\n\nconst DIRECT_PEER_SIGNATURE_VERSION_NUMBER = 3;\n\nfunction logDirectPeerAuthDiagnostic(...reasons: Array<string | null>): void {\n\tconst reason = reasons.find(\n\t\t(candidate) => candidate === \"recipient_mismatch\" || candidate === \"signature_downgrade\",\n\t);\n\tif (reason) console.warn(`[sync] peer auth failed: reason=${reason}`);\n}\n\nfunction isSqliteBusy(err: unknown): boolean {\n\tif (!err || typeof err !== \"object\") return false;\n\tconst code = \"code\" in err ? String((err as { code?: unknown }).code ?? \"\") : \"\";\n\tconst message = err instanceof Error ? err.message : \"\";\n\treturn code === \"SQLITE_BUSY\" || message.includes(\"database is locked\");\n}\n\nfunction recordSyncAuthNonce(\n\tstore: MemoryStore,\n\tdeviceId: string,\n\tnonce: string,\n\tcreatedAt: string,\n): SyncAuthResult | null {\n\ttry {\n\t\tif (!recordNonce(store.db, deviceId, nonce, createdAt)) {\n\t\t\treturn { ok: false, reason: \"nonce_replay\", deviceId };\n\t\t}\n\t} catch (err) {\n\t\tif (isSqliteBusy(err)) {\n\t\t\treturn { ok: false, reason: SYNC_AUTH_STORE_BUSY_REASON, deviceId };\n\t\t}\n\t\tthrow err;\n\t}\n\n\tconst cutoff = new Date(Date.now() - DEFAULT_TIME_WINDOW_S * 2 * 1000).toISOString();\n\ttry {\n\t\tcleanupNonces(store.db, cutoff);\n\t} catch (err) {\n\t\tif (!isSqliteBusy(err)) throw err;\n\t\t// Nonce cleanup is best-effort. A lock here should not fail a request\n\t\t// after its nonce was already recorded; the next request can prune.\n\t}\n\treturn null;\n}\n\nfunction isSyncAuthStoreBusy(auth: SyncAuthResult): boolean {\n\treturn !auth.ok && auth.reason === SYNC_AUTH_STORE_BUSY_REASON;\n}\n\nfunction syncAuthStoreBusyResponse(c: Context) {\n\tc.header(\"Retry-After\", \"1\");\n\treturn c.json({ error: SYNC_AUTH_STORE_BUSY_REASON }, 503);\n}\n\nfunction verifyDirectPeerRequestSignature(\n\trequest: { method: string; url: string; header(name: string): string | undefined },\n\tbody: Buffer,\n\toptions: {\n\t\tdeviceId: string;\n\t\tpublicKey: string;\n\t\texpectedRecipientId: string;\n\t\thighestObservedVersion: number | null;\n\t},\n): VerifiedDirectPeerSignature {\n\tconst timestamp = request.header(\"X-Opencode-Timestamp\") ?? \"\";\n\tconst nonce = request.header(\"X-Opencode-Nonce\") ?? \"\";\n\tconst legacySignature = request.header(\"X-Opencode-Signature\") ?? \"\";\n\tconst recipientHeader = request.header(\"X-Codemem-Recipient\");\n\tconst directSignatureHeader = request.header(\"X-Codemem-Signature\");\n\tconst hasDirectMaterial = recipientHeader !== undefined || directSignatureHeader !== undefined;\n\tconst direct = verifyDirectPeerSignature({\n\t\tmethod: request.method,\n\t\tpathWithQuery: pathWithQuery(request.url),\n\t\tbodyBytes: body,\n\t\ttimestamp,\n\t\tnonce,\n\t\trecipientId: recipientHeader,\n\t\texpectedRecipientId: options.expectedRecipientId,\n\t\tsignature: directSignatureHeader,\n\t\tpublicKey: options.publicKey,\n\t});\n\tif (hasDirectMaterial && direct.status === \"absent\") {\n\t\treturn { ok: false, reason: \"invalid_direct_signature\" };\n\t}\n\tif (direct.status === \"invalid\") {\n\t\treturn {\n\t\t\tok: false,\n\t\t\treason: direct.reason === \"recipient_mismatch\" ? direct.reason : \"invalid_direct_signature\",\n\t\t};\n\t}\n\n\tconst legacyValid = verifySignature({\n\t\tmethod: request.method,\n\t\tpathWithQuery: pathWithQuery(request.url),\n\t\tbodyBytes: body,\n\t\ttimestamp,\n\t\tnonce,\n\t\tsignature: legacySignature,\n\t\tpublicKey: options.publicKey,\n\t\tdeviceId: options.deviceId,\n\t});\n\tif (!legacyValid) return { ok: false, reason: \"invalid_signature\" };\n\tif (\n\t\tdirect.status === \"absent\" &&\n\t\t(options.highestObservedVersion ?? 0) >= DIRECT_PEER_SIGNATURE_VERSION_NUMBER\n\t) {\n\t\treturn { ok: false, reason: \"signature_downgrade\" };\n\t}\n\treturn { ok: true, version: direct.status === \"valid\" ? 3 : 2 };\n}\n\nfunction recordDirectPeerSignatureVersion(\n\tstore: MemoryStore,\n\tdeviceId: string,\n\tversion: 3,\n): SyncAuthResult | null {\n\ttry {\n\t\tconst advanced = recordHighestObservedDirectSignatureVersion(store.db, deviceId, version);\n\t\tif (!advanced) {\n\t\t\tconst observed = store.db\n\t\t\t\t.prepare(\n\t\t\t\t\t`SELECT sync_peer_signature_state.highest_observed_direct_signature_version\n\t\t\t\t\t FROM sync_peers\n\t\t\t\t\t LEFT JOIN sync_peer_signature_state USING (peer_device_id)\n\t\t\t\t\t WHERE sync_peers.peer_device_id = ? LIMIT 1`,\n\t\t\t\t)\n\t\t\t\t.pluck()\n\t\t\t\t.get(deviceId);\n\t\t\tif (observed === undefined) return { ok: false, reason: \"unknown_peer\", deviceId };\n\t\t}\n\t\treturn null;\n\t} catch (err) {\n\t\tif (isSqliteBusy(err)) {\n\t\t\treturn { ok: false, reason: SYNC_AUTH_STORE_BUSY_REASON, deviceId };\n\t\t}\n\t\tthrow err;\n\t}\n}\n\nfunction authorizeSyncRequest(\n\tstore: MemoryStore,\n\trequest: { method: string; url: string; header(name: string): string | undefined },\n\tbody: Buffer,\n): SyncAuthResult {\n\tconst deviceId = (request.header(\"X-Opencode-Device\") ?? \"\").trim();\n\tconst signature = request.header(\"X-Opencode-Signature\") ?? \"\";\n\tconst timestamp = request.header(\"X-Opencode-Timestamp\") ?? \"\";\n\tconst nonce = request.header(\"X-Opencode-Nonce\") ?? \"\";\n\tif (!deviceId || !signature || !timestamp || !nonce) {\n\t\treturn { ok: false, reason: \"missing_headers\", deviceId };\n\t}\n\n\tconst peerRow = store.db\n\t\t.prepare(\n\t\t\t`SELECT sync_peers.pinned_fingerprint, sync_peers.public_key,\n\t\t\t sync_peer_signature_state.highest_observed_direct_signature_version\n\t\t\t FROM sync_peers\n\t\t\t LEFT JOIN sync_peer_signature_state USING (peer_device_id)\n\t\t\t WHERE sync_peers.peer_device_id = ? LIMIT 1`,\n\t\t)\n\t\t.get(deviceId) as\n\t\t| {\n\t\t\t\tpinned_fingerprint: string | null;\n\t\t\t\tpublic_key: string | null;\n\t\t\t\thighest_observed_direct_signature_version: number | null;\n\t\t }\n\t\t| undefined;\n\tif (!peerRow) {\n\t\treturn { ok: false, reason: \"unknown_peer\", deviceId };\n\t}\n\n\tconst pinnedFingerprint = String(peerRow.pinned_fingerprint ?? \"\").trim();\n\tconst publicKey = String(peerRow.public_key ?? \"\").trim();\n\tif (!pinnedFingerprint || !publicKey) {\n\t\treturn { ok: false, reason: \"peer_record_incomplete\", deviceId };\n\t}\n\tif (fingerprintPublicKey(publicKey) !== pinnedFingerprint) {\n\t\treturn { ok: false, reason: \"fingerprint_mismatch\", deviceId };\n\t}\n\n\tlet verification: VerifiedDirectPeerSignature;\n\ttry {\n\t\tconst [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });\n\t\tverification = verifyDirectPeerRequestSignature(request, body, {\n\t\t\tdeviceId,\n\t\t\tpublicKey,\n\t\t\texpectedRecipientId: localDeviceId,\n\t\t\thighestObservedVersion: peerRow.highest_observed_direct_signature_version,\n\t\t});\n\t} catch {\n\t\treturn { ok: false, reason: \"signature_verification_error\", deviceId };\n\t}\n\tif (!verification.ok) {\n\t\treturn { ok: false, reason: verification.reason, deviceId };\n\t}\n\n\tconst createdAt = new Date().toISOString();\n\tconst nonceResult = recordSyncAuthNonce(store, deviceId, nonce, createdAt);\n\tif (nonceResult) return nonceResult;\n\tif (verification.version === DIRECT_PEER_SIGNATURE_VERSION_NUMBER) {\n\t\tconst versionResult = recordDirectPeerSignatureVersion(store, deviceId, verification.version);\n\t\tif (versionResult) return versionResult;\n\t}\n\treturn { ok: true, reason: \"ok\", deviceId };\n}\n\nasync function authorizeBootstrapGrantRequest(\n\tstore: MemoryStore,\n\trequest: { method: string; url: string; header(name: string): string | undefined },\n\tbody: Buffer,\n): Promise<SyncAuthResult> {\n\tconst grantId = (request.header(\"X-Codemem-Bootstrap-Grant\") ?? \"\").trim();\n\tconst deviceId = (request.header(\"X-Opencode-Device\") ?? \"\").trim();\n\tconst signature = request.header(\"X-Opencode-Signature\") ?? \"\";\n\tconst timestamp = request.header(\"X-Opencode-Timestamp\") ?? \"\";\n\tconst nonce = request.header(\"X-Opencode-Nonce\") ?? \"\";\n\tif (!grantId || !deviceId || !signature || !timestamp || !nonce) {\n\t\treturn { ok: false, reason: \"missing_bootstrap_grant_headers\", deviceId };\n\t}\n\n\tconst config = readCoordinatorSyncConfig();\n\tif (!config.syncCoordinatorUrl) {\n\t\treturn { ok: false, reason: \"bootstrap_grant_coordinator_not_configured\", deviceId };\n\t}\n\n\tconst [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });\n\tlet verification: CoordinatorBootstrapGrantVerification;\n\ttry {\n\t\tlet payload: Record<string, unknown> | null = null;\n\t\tif (config.syncCoordinatorAdminSecret) {\n\t\t\tconst [status, adminPayload] = await requestJson(\n\t\t\t\t\"GET\",\n\t\t\t\t`${buildBaseUrl(config.syncCoordinatorUrl)}/v1/admin/bootstrap-grants/${encodeURIComponent(grantId)}`,\n\t\t\t\t{\n\t\t\t\t\theaders: { \"X-Codemem-Coordinator-Admin\": config.syncCoordinatorAdminSecret },\n\t\t\t\t\ttimeoutS: Math.max(1, config.syncCoordinatorTimeoutS),\n\t\t\t\t},\n\t\t\t);\n\t\t\tif (status === 200) payload = adminPayload;\n\t\t} else {\n\t\t\tfor (const groupId of config.syncCoordinatorGroups) {\n\t\t\t\tconst lookupUrl = `${buildBaseUrl(config.syncCoordinatorUrl)}/v1/bootstrap-grants/${encodeURIComponent(grantId)}?group_id=${encodeURIComponent(groupId)}`;\n\t\t\t\tconst [status, signedPayload] = await requestJson(\"GET\", lookupUrl, {\n\t\t\t\t\theaders: buildAuthHeaders({\n\t\t\t\t\t\tdeviceId: localDeviceId,\n\t\t\t\t\t\tdbPath: store.dbPath,\n\t\t\t\t\t\tmethod: \"GET\",\n\t\t\t\t\t\turl: lookupUrl,\n\t\t\t\t\t\tbodyBytes: Buffer.alloc(0),\n\t\t\t\t\t\tkeysDir: syncKeysDir(),\n\t\t\t\t\t}),\n\t\t\t\t\ttimeoutS: Math.max(1, config.syncCoordinatorTimeoutS),\n\t\t\t\t});\n\t\t\t\tif (status === 200) {\n\t\t\t\t\tpayload = signedPayload;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!payload) return { ok: false, reason: \"bootstrap_grant_lookup_failed\", deviceId };\n\t\tverification = payload as unknown as CoordinatorBootstrapGrantVerification;\n\t} catch {\n\t\treturn { ok: false, reason: \"bootstrap_grant_lookup_failed\", deviceId };\n\t}\n\n\tconst grant = verification.grant;\n\tconst workerEnrollment = verification.worker_enrollment;\n\tif (!grant || !workerEnrollment) {\n\t\treturn { ok: false, reason: \"bootstrap_grant_invalid_payload\", deviceId };\n\t}\n\tif (\n\t\tconfig.syncCoordinatorGroups.length > 0 &&\n\t\t!config.syncCoordinatorGroups.includes(String(grant.group_id))\n\t) {\n\t\treturn { ok: false, reason: \"bootstrap_grant_group_mismatch\", deviceId };\n\t}\n\tif (grant.revoked_at) return { ok: false, reason: \"bootstrap_grant_revoked\", deviceId };\n\tif (String(workerEnrollment.device_id) !== String(grant.worker_device_id)) {\n\t\treturn { ok: false, reason: \"bootstrap_grant_worker_enrollment_mismatch\", deviceId };\n\t}\n\tif (String(workerEnrollment.group_id) !== String(grant.group_id)) {\n\t\treturn { ok: false, reason: \"bootstrap_grant_group_mismatch\", deviceId };\n\t}\n\tif (Number(workerEnrollment.enabled) !== 1) {\n\t\treturn { ok: false, reason: \"bootstrap_grant_worker_disabled\", deviceId };\n\t}\n\tconst workerPublicKey = String(workerEnrollment.public_key ?? \"\").trim();\n\tconst workerFingerprint = String(workerEnrollment.fingerprint ?? \"\").trim();\n\tif (!workerPublicKey || fingerprintPublicKey(workerPublicKey) !== workerFingerprint) {\n\t\treturn { ok: false, reason: \"bootstrap_grant_worker_identity_invalid\", deviceId };\n\t}\n\tif (grant.worker_device_id !== deviceId) {\n\t\treturn { ok: false, reason: \"bootstrap_grant_worker_mismatch\", deviceId };\n\t}\n\tif (grant.seed_device_id !== localDeviceId) {\n\t\treturn { ok: false, reason: \"bootstrap_grant_seed_mismatch\", deviceId };\n\t}\n\tif (new Date(grant.expires_at) <= new Date()) {\n\t\treturn { ok: false, reason: \"bootstrap_grant_expired\", deviceId };\n\t}\n\n\tconst existingPeer = store.db\n\t\t.prepare(\n\t\t\t`SELECT highest_observed_direct_signature_version\n\t\t\t FROM sync_peer_signature_state WHERE peer_device_id = ? LIMIT 1`,\n\t\t)\n\t\t.get(deviceId) as { highest_observed_direct_signature_version: number | null } | undefined;\n\tlet signatureVerification: VerifiedDirectPeerSignature;\n\ttry {\n\t\tsignatureVerification = verifyDirectPeerRequestSignature(request, body, {\n\t\t\tdeviceId,\n\t\t\tpublicKey: workerPublicKey,\n\t\t\texpectedRecipientId: localDeviceId,\n\t\t\thighestObservedVersion: existingPeer?.highest_observed_direct_signature_version ?? null,\n\t\t});\n\t} catch {\n\t\treturn { ok: false, reason: \"bootstrap_grant_signature_verification_error\", deviceId };\n\t}\n\tif (!signatureVerification.ok) {\n\t\treturn { ok: false, reason: signatureVerification.reason, deviceId };\n\t}\n\tif (!isPeerTrustBindingCompatible(store.db, deviceId, workerPublicKey, workerFingerprint)) {\n\t\treturn { ok: false, reason: \"bootstrap_grant_peer_trust_conflict\", deviceId };\n\t}\n\n\tconst createdAt = new Date().toISOString();\n\tconst nonceResult = recordSyncAuthNonce(store, deviceId, nonce, createdAt);\n\tif (nonceResult) return nonceResult;\n\tupdatePeerAddresses(store.db, deviceId, [], {\n\t\tname: String(workerEnrollment.display_name ?? \"\").trim() || undefined,\n\t\tpinnedFingerprint: workerFingerprint,\n\t\tpublicKey: workerPublicKey,\n\t\treplaceTrust: true,\n\t});\n\tif (signatureVerification.version === DIRECT_PEER_SIGNATURE_VERSION_NUMBER) {\n\t\tconst versionResult = recordDirectPeerSignatureVersion(\n\t\t\tstore,\n\t\t\tdeviceId,\n\t\t\tsignatureVerification.version,\n\t\t);\n\t\tif (versionResult) return versionResult;\n\t}\n\treturn { ok: true, reason: \"ok\", deviceId };\n}\n\nfunction parseJsonList(value: unknown): string[] {\n\tif (value == null) return [];\n\tif (typeof value === \"string\") {\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(value) as unknown;\n\t\t\tif (!Array.isArray(parsed)) return [];\n\t\t\treturn parsed.map((entry) => String(entry ?? \"\").trim()).filter(Boolean);\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n\tif (!Array.isArray(value)) return [];\n\treturn value.map((entry) => String(entry ?? \"\").trim()).filter(Boolean);\n}\n\nfunction readPeerProjectFilters(\n\tstore: MemoryStore,\n\tpeerDeviceId: string,\n): { include: string[]; exclude: string[] } {\n\tconst globalConfig = readCoordinatorSyncConfig();\n\tconst row = store.db\n\t\t.prepare(\n\t\t\t\"SELECT projects_include_json, projects_exclude_json FROM sync_peers WHERE peer_device_id = ? LIMIT 1\",\n\t\t)\n\t\t.get(peerDeviceId) as\n\t\t| { projects_include_json: string | null; projects_exclude_json: string | null }\n\t\t| undefined;\n\tif (!row) {\n\t\treturn {\n\t\t\tinclude: globalConfig.syncProjectsInclude,\n\t\t\texclude: globalConfig.syncProjectsExclude,\n\t\t};\n\t}\n\tconst hasOverride = row.projects_include_json != null || row.projects_exclude_json != null;\n\tif (!hasOverride) {\n\t\treturn {\n\t\t\tinclude: globalConfig.syncProjectsInclude,\n\t\t\texclude: globalConfig.syncProjectsExclude,\n\t\t};\n\t}\n\treturn {\n\t\tinclude: parseJsonList(row.projects_include_json),\n\t\texclude: parseJsonList(row.projects_exclude_json),\n\t};\n}\n\nfunction currentProjectScope(\n\trow: Record<string, unknown>,\n\teffective?: { include: string[]; exclude: string[] },\n): Record<string, unknown> {\n\treturn {\n\t\tinclude: safeJsonList(row.projects_include_json as string | null),\n\t\texclude: safeJsonList(row.projects_exclude_json as string | null),\n\t\teffective_include:\n\t\t\teffective?.include ?? safeJsonList(row.projects_include_json as string | null),\n\t\teffective_exclude:\n\t\t\teffective?.exclude ?? safeJsonList(row.projects_exclude_json as string | null),\n\t\tinherits_global: row.projects_include_json == null && row.projects_exclude_json == null,\n\t};\n}\n\nfunction cleanPeerScopeText(value: unknown): string | null {\n\tconst text = String(value ?? \"\").trim();\n\treturn text || null;\n}\n\nfunction peerAuthorizedScopes(store: MemoryStore, peerDeviceId: string): Record<string, unknown>[] {\n\tconst deviceId = peerDeviceId.trim();\n\tif (!deviceId) return [];\n\tconst rows = store.db\n\t\t.prepare(\n\t\t\t`SELECT\n\t\t\t\trs.scope_id,\n\t\t\t\trs.label,\n\t\t\t\trs.kind,\n\t\t\t\trs.authority_type,\n\t\t\t\trs.coordinator_id,\n\t\t\t\trs.group_id,\n\t\t\t\tsm.role,\n\t\t\t\tsm.membership_epoch,\n\t\t\t\tsm.updated_at\n\t\t\t FROM scope_memberships sm\n\t\t\t JOIN replication_scopes rs ON rs.scope_id = sm.scope_id\n\t\t\t WHERE sm.device_id = ?\n\t\t\t AND sm.status = 'active'\n\t\t\t AND rs.status = 'active'\n\t\t\t AND sm.membership_epoch >= rs.membership_epoch\n\t\t\t ORDER BY CASE WHEN rs.authority_type = 'local' THEN 1 ELSE 0 END,\n\t\t\t rs.label COLLATE NOCASE,\n\t\t\t rs.scope_id`,\n\t\t)\n\t\t.all(deviceId) as Array<Record<string, unknown>>;\n\treturn rows.map((row) => ({\n\t\tscope_id: String(row.scope_id ?? \"\"),\n\t\tlabel: String(row.label ?? row.scope_id ?? \"\"),\n\t\tkind: String(row.kind ?? \"user\"),\n\t\tauthority_type: String(row.authority_type ?? \"local\"),\n\t\tcoordinator_id: cleanPeerScopeText(row.coordinator_id),\n\t\tgroup_id: cleanPeerScopeText(row.group_id),\n\t\trole: String(row.role ?? \"member\"),\n\t\tmembership_epoch: Number(row.membership_epoch ?? 0),\n\t\tupdated_at: cleanPeerScopeText(row.updated_at),\n\t}));\n}\n\nfunction ensureLocalActorRecord(store: MemoryStore): void {\n\tconst d = drizzle(store.db, { schema });\n\tconst now = new Date().toISOString();\n\t// Invariant: exactly one row in `actors` has is_local=1, and it is the\n\t// row whose actor_id matches store.actorId. Stale is_local=1 rows can\n\t// appear when a device's actor_id changes (config edit, regenerated\n\t// device keys, DB copied from another machine). Demote any such rows\n\t// before ensuring the canonical local row exists.\n\td.update(schema.actors)\n\t\t.set({ is_local: 0, updated_at: now })\n\t\t.where(and(eq(schema.actors.is_local, 1), ne(schema.actors.actor_id, store.actorId)))\n\t\t.run();\n\tconst existing = d\n\t\t.select({ actor_id: schema.actors.actor_id, is_local: schema.actors.is_local })\n\t\t.from(schema.actors)\n\t\t.where(eq(schema.actors.actor_id, store.actorId))\n\t\t.get();\n\tif (existing) {\n\t\t// Row already exists for the canonical local actor id; the demotion\n\t\t// above guarantees it is the only is_local=1 row, but the row itself\n\t\t// may have been previously set to is_local=0 (e.g. via a stale demote\n\t\t// from an even earlier identity). Re-mark it as local idempotently.\n\t\tif (existing.is_local !== 1) {\n\t\t\td.update(schema.actors)\n\t\t\t\t.set({ is_local: 1, updated_at: now })\n\t\t\t\t.where(eq(schema.actors.actor_id, store.actorId))\n\t\t\t\t.run();\n\t\t}\n\t\treturn;\n\t}\n\td.insert(schema.actors)\n\t\t.values({\n\t\t\tactor_id: store.actorId,\n\t\t\tdisplay_name: store.actorDisplayName,\n\t\t\tis_local: 1,\n\t\t\tstatus: \"active\",\n\t\t\tmerged_into_actor_id: null,\n\t\t\tcreated_at: now,\n\t\t\tupdated_at: now,\n\t\t})\n\t\t.run();\n}\n\nfunction ensureStableStoreIdentity(store: MemoryStore): string {\n\tconst deviceId = ensureStableStoreDeviceIdentity(store);\n\tensureLocalActorRecord(store);\n\treturn deviceId;\n}\n\nfunction ensureStableStoreDeviceIdentity(store: MemoryStore): string {\n\tconst [deviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });\n\tstore.adoptEnsuredDeviceIdentity(deviceId);\n\treturn deviceId;\n}\n\nfunction findPeerDeviceIdForAddress(store: MemoryStore, address: string): string | null {\n\tconst rows = store.db\n\t\t.prepare(\"SELECT peer_device_id, addresses_json FROM sync_peers\")\n\t\t.all() as Array<{ peer_device_id: string; addresses_json: string | null }>;\n\tfor (const row of rows) {\n\t\tconst addresses = safeJsonList(row.addresses_json);\n\t\tif (addresses.includes(address)) return String(row.peer_device_id ?? \"\").trim() || null;\n\t}\n\treturn null;\n}\n\nfunction claimLegacyDeviceAsSelf(store: MemoryStore, originDeviceId: string): number {\n\tconst deviceId = String(originDeviceId || \"\").trim();\n\tif (!deviceId || deviceId === \"unknown\" || deviceId === store.deviceId) return 0;\n\tconst personalWorkspaceId = `personal:${store.actorId}`;\n\tconst result = store.db\n\t\t.prepare(\n\t\t\t`UPDATE memory_items\n\t\t\t SET actor_id = ?,\n\t\t\t actor_display_name = ?,\n\t\t\t visibility = 'private',\n\t\t\t workspace_id = ?,\n\t\t\t workspace_kind = 'personal',\n\t\t\t trust_state = 'trusted'\n\t\t\t WHERE origin_device_id = ?\n\t\t\t AND origin_device_id NOT IN (\n\t\t\t SELECT peer_device_id FROM sync_peers WHERE peer_device_id IS NOT NULL\n\t\t\t )\n\t\t\t AND (\n\t\t\t (\n\t\t\t actor_id IS NULL\n\t\t\t OR TRIM(actor_id) = ''\n\t\t\t OR actor_id LIKE 'legacy-sync:%'\n\t\t\t OR actor_id = ?\n\t\t\t )\n\t\t\t AND (\n\t\t\t actor_id IS NULL\n\t\t\t OR TRIM(actor_id) = ''\n\t\t\t OR actor_id LIKE 'legacy-sync:%'\n\t\t\t OR actor_display_name = ?\n\t\t\t OR workspace_id = ?\n\t\t\t OR trust_state = 'legacy_unknown'\n\t\t\t )\n\t\t\t )`,\n\t\t)\n\t\t.run(\n\t\t\tstore.actorId,\n\t\t\tstore.actorDisplayName,\n\t\t\tpersonalWorkspaceId,\n\t\t\tdeviceId,\n\t\t\tstore.actorId,\n\t\t\tLEGACY_SYNC_ACTOR_DISPLAY_NAME,\n\t\t\tLEGACY_SHARED_WORKSPACE_ID,\n\t\t);\n\treturn Number(result.changes ?? 0);\n}\n\nfunction redactCoordinatorStatus(\n\tcoordinator: Record<string, unknown>,\n\tshowDiag: boolean,\n): Record<string, unknown> {\n\tif (showDiag) return coordinator;\n\tconst discovered = Array.isArray(coordinator.discovered_devices)\n\t\t? coordinator.discovered_devices.map((item) => {\n\t\t\t\tif (!item || typeof item !== \"object\") return item;\n\t\t\t\tconst record = item as Record<string, unknown>;\n\t\t\t\tconst addressCount = Array.isArray(record.addresses) ? record.addresses.length : 0;\n\t\t\t\treturn {\n\t\t\t\t\tdevice_id: record.device_id,\n\t\t\t\t\tdisplay_name: record.display_name ?? null,\n\t\t\t\t\tgroups: Array.isArray(record.groups) ? record.groups : [],\n\t\t\t\t\tlast_seen_at: record.last_seen_at ?? null,\n\t\t\t\t\texpires_at: record.expires_at ?? null,\n\t\t\t\t\tstale: Boolean(record.stale),\n\t\t\t\t\tneeds_local_approval: Boolean(record.needs_local_approval),\n\t\t\t\t\twaiting_for_peer_approval: Boolean(record.waiting_for_peer_approval),\n\t\t\t\t\tincoming_reciprocal_request_id: record.incoming_reciprocal_request_id ?? null,\n\t\t\t\t\toutgoing_reciprocal_request_id: record.outgoing_reciprocal_request_id ?? null,\n\t\t\t\t\tfingerprint: null,\n\t\t\t\t\taddresses: [],\n\t\t\t\t\taddress_count: addressCount,\n\t\t\t\t};\n\t\t\t})\n\t\t: [];\n\treturn {\n\t\t...coordinator,\n\t\tdiscovered_devices: discovered,\n\t};\n}\n\ninterface AcceptDiscoveredPeerOptions {\n\tpeerDeviceId: string;\n\tfingerprint?: string;\n\t// Optional per-peer scope override. When undefined the group's scope\n\t// template is applied if auto_seed_scope is enabled; otherwise the peer\n\t// is enrolled with no scope filters.\n\t// Per-field: `undefined` = \"inherit from template\", `null` = \"explicit empty\",\n\t// `string[]` = \"use this list\". This avoids silently wiping the template's\n\t// exclude list when the caller only overrides include (or vice versa).\n\tscopeOverride?: {\n\t\tprojects_include?: string[] | null;\n\t\tprojects_exclude?: string[] | null;\n\t};\n\t// When provided and the caller is the admin-groups endpoint, this group\n\t// must be one of the match's coordinator groups. When undefined (legacy\n\t// /api/sync/peers/accept-discovered path) the match must belong to\n\t// exactly one group and that one is used.\n\texpectedGroupId?: string;\n\t// When provided, complete only the exact incoming reciprocal approval that\n\t// the caller reviewed instead of accepting a replacement request.\n\texpectedIncomingRequestId?: string;\n}\n\ntype AcceptDiscoveredPeerNotConfiguredReason =\n\t| \"coordinator_url_missing\"\n\t| \"coordinator_groups_empty\"\n\t| \"sync_disabled\";\n\nfunction detailForNotConfiguredReason(reason: AcceptDiscoveredPeerNotConfiguredReason): string {\n\tswitch (reason) {\n\t\tcase \"coordinator_url_missing\":\n\t\t\treturn \"Configure a coordinator URL before pairing with discovered peers.\";\n\t\tcase \"coordinator_groups_empty\":\n\t\t\treturn \"Join a coordinator team before pairing with discovered peers.\";\n\t\tcase \"sync_disabled\":\n\t\t\treturn \"Enable sync on this device before pairing with discovered peers.\";\n\t}\n}\n\nasync function acceptDiscoveredPeer(\n\tstore: MemoryStore,\n\tinput: AcceptDiscoveredPeerOptions,\n): Promise<\n\t| {\n\t\t\tok: true;\n\t\t\tpeer_device_id: string;\n\t\t\tcreated: boolean;\n\t\t\tupdated: boolean;\n\t\t\tname: string | null;\n\t\t\tgroup_id: string;\n\t }\n\t| {\n\t\t\tok: false;\n\t\t\tstatus: number;\n\t\t\terror: string;\n\t\t\tdetail: string;\n\t\t\treason?: AcceptDiscoveredPeerNotConfiguredReason;\n\t }\n> {\n\tconst config = readCoordinatorSyncConfig();\n\t// Order: address the most foundational gap first so the detail string\n\t// guides the user through setup in the correct sequence.\n\tlet notConfiguredReason: AcceptDiscoveredPeerNotConfiguredReason | null = null;\n\tif (!config.syncCoordinatorUrl) {\n\t\tnotConfiguredReason = \"coordinator_url_missing\";\n\t} else if (config.syncCoordinatorGroups.length === 0) {\n\t\tnotConfiguredReason = \"coordinator_groups_empty\";\n\t} else if (!config.syncEnabled) {\n\t\tnotConfiguredReason = \"sync_disabled\";\n\t}\n\tif (notConfiguredReason) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tstatus: 400,\n\t\t\terror: \"coordinator_not_configured\",\n\t\t\treason: notConfiguredReason,\n\t\t\tdetail: detailForNotConfiguredReason(notConfiguredReason),\n\t\t};\n\t}\n\tconst discovered = await lookupCoordinatorPeers(store, config);\n\tconst inputFingerprint = String(input.fingerprint ?? \"\").trim();\n\tconst candidates = discovered.filter(\n\t\t(peer) => String(peer.device_id ?? \"\").trim() === input.peerDeviceId,\n\t);\n\tconst matchingCandidates = inputFingerprint\n\t\t? candidates.filter((peer) => String(peer.fingerprint ?? \"\").trim() === inputFingerprint)\n\t\t: candidates;\n\tconst uniqueFingerprints = new Set(\n\t\tmatchingCandidates.map((peer) => String(peer.fingerprint ?? \"\").trim()).filter(Boolean),\n\t);\n\tif (!inputFingerprint && uniqueFingerprints.size > 1) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tstatus: 409,\n\t\t\terror: \"ambiguous_discovered_peer\",\n\t\t\tdetail:\n\t\t\t\t\"That discovered device has multiple coordinator fingerprints. Enable diagnostics, refresh sync status, and choose the intended device before trusting it.\",\n\t\t};\n\t}\n\tconst match = matchingCandidates[0];\n\tif (!match) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tstatus: 404,\n\t\t\terror: \"discovered_peer_not_found\",\n\t\t\tdetail: \"That discovered device is no longer available. Refresh sync status and try again.\",\n\t\t};\n\t}\n\tconst expiresAt = String(match.expires_at ?? \"\").trim();\n\tconst expired = expiresAt ? Date.parse(expiresAt) <= Date.now() : false;\n\tif (match.stale || expired) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tstatus: 409,\n\t\t\terror: \"discovered_peer_stale\",\n\t\t\tdetail:\n\t\t\t\t\"This discovered device's coordinator presence is stale. Wait for it to come online and refresh sync status before trusting it.\",\n\t\t};\n\t}\n\tconst nextFingerprint = String(match.fingerprint ?? \"\").trim();\n\tconst nextPublicKey = String(match.public_key ?? \"\").trim();\n\tconst nextName = String(match.display_name ?? \"\").trim() || null;\n\tconst nextAddresses = Array.isArray(match.addresses)\n\t\t? match.addresses.filter((value): value is string => typeof value === \"string\")\n\t\t: [];\n\tif (!nextPublicKey) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tstatus: 409,\n\t\t\terror: \"discovered_peer_missing_public_key\",\n\t\t\tdetail:\n\t\t\t\t\"This discovered device is missing its coordinator public key. Refresh sync status and try again.\",\n\t\t};\n\t}\n\tif (!nextFingerprint || fingerprintPublicKey(nextPublicKey) !== nextFingerprint) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tstatus: 409,\n\t\t\terror: \"discovered_peer_fingerprint_mismatch\",\n\t\t\tdetail:\n\t\t\t\t\"This discovered device's coordinator public key does not match its fingerprint. Refresh sync status or re-enroll the device before trusting it.\",\n\t\t};\n\t}\n\n\tconst groupIds = Array.isArray(match.groups)\n\t\t? match.groups.map((value) => String(value ?? \"\").trim()).filter(Boolean)\n\t\t: [];\n\tconst freshGroupIds = Array.isArray(match.fresh_groups)\n\t\t? match.fresh_groups.map((value) => String(value ?? \"\").trim()).filter(Boolean)\n\t\t: [];\n\tlet groupId: string;\n\tif (input.expectedGroupId) {\n\t\tif (!groupIds.includes(input.expectedGroupId)) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tstatus: 409,\n\t\t\t\terror: \"peer_not_in_group\",\n\t\t\t\tdetail:\n\t\t\t\t\t\"This discovered device is not visible through the specified coordinator group. Refresh sync status and try again.\",\n\t\t\t};\n\t\t}\n\t\tif (!freshGroupIds.includes(input.expectedGroupId)) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tstatus: 409,\n\t\t\t\terror: \"discovered_peer_stale\",\n\t\t\t\tdetail:\n\t\t\t\t\t\"This discovered device's coordinator presence is stale for the specified group. Wait for it to come online and refresh sync status before trusting it.\",\n\t\t\t};\n\t\t}\n\t\tgroupId = input.expectedGroupId;\n\t} else {\n\t\tif (groupIds.length !== 1) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tstatus: 409,\n\t\t\t\terror: \"ambiguous_coordinator_group\",\n\t\t\t\tdetail:\n\t\t\t\t\tgroupIds.length > 1\n\t\t\t\t\t\t? \"This device is visible through multiple coordinator groups. Review the team setup before approving it here.\"\n\t\t\t\t\t\t: \"This device is missing coordinator group context. Refresh sync status and try again.\",\n\t\t\t};\n\t\t}\n\t\tgroupId = groupIds[0] as string;\n\t}\n\tconst d = drizzle(store.db, { schema });\n\tconst existing = d\n\t\t.select({\n\t\t\tpeer_device_id: schema.syncPeers.peer_device_id,\n\t\t\tpinned_fingerprint: schema.syncPeers.pinned_fingerprint,\n\t\t\tpublic_key: schema.syncPeers.public_key,\n\t\t\taddresses_json: schema.syncPeers.addresses_json,\n\t\t\tdiscovered_via_group_id: schema.syncPeers.discovered_via_group_id,\n\t\t})\n\t\t.from(schema.syncPeers)\n\t\t.where(eq(schema.syncPeers.peer_device_id, input.peerDeviceId))\n\t\t.get();\n\tconst existingFingerprint = String(existing?.pinned_fingerprint ?? \"\").trim();\n\tif (existing && existingFingerprint && existingFingerprint !== nextFingerprint) {\n\t\treturn {\n\t\t\tok: false as const,\n\t\t\tstatus: 409,\n\t\t\terror: \"peer_conflict\",\n\t\t\tdetail:\n\t\t\t\t\"An existing peer with this device id is pinned to a different fingerprint. Remove or repair the old peer before accepting this discovered device.\",\n\t\t};\n\t}\n\tconst existingAddresses = (() => {\n\t\ttry {\n\t\t\tconst raw = JSON.parse(String(existing?.addresses_json ?? \"[]\"));\n\t\t\treturn Array.isArray(raw)\n\t\t\t\t? raw.filter((value): value is string => typeof value === \"string\")\n\t\t\t\t: [];\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t})();\n\tconst addressesJson = JSON.stringify(mergeAddresses(nextAddresses, existingAddresses));\n\tawait createCoordinatorReciprocalApproval(store, config, {\n\t\tgroupId,\n\t\trequestedDeviceId: input.peerDeviceId,\n\t\t...(input.expectedIncomingRequestId\n\t\t\t? { expectedIncomingRequestId: input.expectedIncomingRequestId }\n\t\t\t: {}),\n\t});\n\n\t// Resolve project-scope seed. On first enrollment (no existing row), apply\n\t// the group's scope template if auto_seed_scope is enabled. Per-field\n\t// overrides fall back to the template when undefined, so passing only\n\t// `projects_include` does not silently wipe the template's exclude list.\n\t// Existing peers are not re-scoped — the template is a seed, not a live link.\n\tconst coordinatorUrl = config.syncCoordinatorUrl || null;\n\tlet scopeInclude: string | null | undefined;\n\tlet scopeExclude: string | null | undefined;\n\tif (!existing) {\n\t\tlet templateInclude: string[] | null = null;\n\t\tlet templateExclude: string[] | null = null;\n\t\tif (coordinatorUrl) {\n\t\t\tconst prefs = getCoordinatorGroupPreference(store.db, coordinatorUrl, groupId);\n\t\t\tif (prefs?.auto_seed_scope) {\n\t\t\t\ttemplateInclude = prefs.projects_include ?? null;\n\t\t\t\ttemplateExclude = prefs.projects_exclude ?? null;\n\t\t\t}\n\t\t}\n\t\tconst overrideInclude = input.scopeOverride?.projects_include;\n\t\tconst overrideExclude = input.scopeOverride?.projects_exclude;\n\t\tconst resolvedInclude = overrideInclude === undefined ? templateInclude : overrideInclude;\n\t\tconst resolvedExclude = overrideExclude === undefined ? templateExclude : overrideExclude;\n\t\tscopeInclude = resolvedInclude ? JSON.stringify(resolvedInclude) : null;\n\t\tscopeExclude = resolvedExclude ? JSON.stringify(resolvedExclude) : null;\n\t}\n\n\tconst now = new Date().toISOString();\n\tconst result = store.db.transaction(() => {\n\t\tif (!existing) {\n\t\t\td.insert(schema.syncPeers)\n\t\t\t\t.values({\n\t\t\t\t\tpeer_device_id: input.peerDeviceId,\n\t\t\t\t\tname: nextName,\n\t\t\t\t\tpinned_fingerprint: nextFingerprint || null,\n\t\t\t\t\tpublic_key: nextPublicKey,\n\t\t\t\t\taddresses_json: addressesJson,\n\t\t\t\t\tprojects_include_json: scopeInclude ?? null,\n\t\t\t\t\tprojects_exclude_json: scopeExclude ?? null,\n\t\t\t\t\tcreated_at: now,\n\t\t\t\t\tlast_seen_at: now,\n\t\t\t\t\tdiscovered_via_coordinator_id: coordinatorUrl,\n\t\t\t\t\tdiscovered_via_group_id: groupId,\n\t\t\t\t})\n\t\t\t\t.run();\n\t\t\treturn {\n\t\t\t\tok: true as const,\n\t\t\t\tpeer_device_id: input.peerDeviceId,\n\t\t\t\tcreated: true,\n\t\t\t\tupdated: false,\n\t\t\t\tname: nextName,\n\t\t\t\tgroup_id: groupId,\n\t\t\t};\n\t\t}\n\t\td.update(schema.syncPeers)\n\t\t\t.set({\n\t\t\t\tname: nextName,\n\t\t\t\tpinned_fingerprint: nextFingerprint || existing.pinned_fingerprint || null,\n\t\t\t\tpublic_key: nextPublicKey || existing.public_key || null,\n\t\t\t\taddresses_json: addressesJson,\n\t\t\t\tlast_seen_at: now,\n\t\t\t\t// Backfill group-discovery attribution on existing rows if we know\n\t\t\t\t// it now and it wasn't stamped before. Don't overwrite a non-null\n\t\t\t\t// group reference — that would silently move the peer between\n\t\t\t\t// teams and invalidate any template-seeded scope.\n\t\t\t\t...((existing as { discovered_via_group_id?: string | null }).discovered_via_group_id\n\t\t\t\t\t? {}\n\t\t\t\t\t: { discovered_via_group_id: groupId, discovered_via_coordinator_id: coordinatorUrl }),\n\t\t\t})\n\t\t\t.where(eq(schema.syncPeers.peer_device_id, input.peerDeviceId))\n\t\t\t.run();\n\t\treturn {\n\t\t\tok: true as const,\n\t\t\tpeer_device_id: input.peerDeviceId,\n\t\t\tcreated: false,\n\t\t\tupdated: true,\n\t\t\tname: nextName,\n\t\t\tgroup_id: groupId,\n\t\t};\n\t})();\n\treturn result;\n}\n\nfunction filterOpsForPeer(\n\tstore: MemoryStore,\n\tpeerDeviceId: string,\n\tlocalDeviceId: string | null,\n\tops: ReplicationOp[],\n\toptions: { applyScopeFilter?: boolean; supportsReassignScope?: boolean } = {},\n): { allowed: ReplicationOp[]; skipped: number; skippedDetail: SafeSkippedSyncDetail | null } {\n\tconst [allowed, , skipped] = filterReplicationOpsForSyncWithStatus(store.db, ops, peerDeviceId, {\n\t\tlocalDeviceId,\n\t\tapplyScopeFilter: options.applyScopeFilter,\n\t\tsupportsReassignScope: options.supportsReassignScope,\n\t});\n\treturn {\n\t\tallowed,\n\t\tskipped: skipped?.skipped_count ?? 0,\n\t\tskippedDetail: skipped ? safeSkippedSyncDetail(skipped) : null,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Peer row mapping — deduplicated helper (fix #4)\n// ---------------------------------------------------------------------------\n\nfunction claimedLocalActorScopeStatus(\n\tstore: MemoryStore,\n\trow: Record<string, unknown>,\n): Record<string, unknown> | null {\n\tif (!row.claimed_local_actor) return null;\n\tconst peerDeviceId = String(row.peer_device_id ?? \"\").trim();\n\tconst actorId = String(row.actor_id ?? store.actorId).trim() || store.actorId;\n\tconst grant = personalScopeGrantStatusForPeer(store.db, { peerDeviceId, actorId });\n\treturn {\n\t\tscope_id: grant.scope_id,\n\t\tauthorized: grant.authorized,\n\t\tstate: grant.state,\n\t\taction_required: !grant.authorized,\n\t};\n}\n\n/**\n * Map a raw sync_peers DB row to the API response shape.\n * When showDiag is false, sensitive fields (fingerprint, last_error, addresses)\n * are redacted.\n */\nfunction mapPeerRow(\n\tstore: MemoryStore,\n\trow: Record<string, unknown>,\n\tshowDiag: boolean,\n\trecentOpsByPeer?: Map<string, { in: number; out: number }>,\n\tscopeRejectionsByPeer?: Map<string, InboundScopeRejectionPeerSummary>,\n\tlocalDeviceId?: string | null,\n): Record<string, unknown> {\n\tconst peerId = String(row.peer_device_id ?? \"\");\n\tconst recentOps = recentOpsByPeer?.get(peerId) ?? { in: 0, out: 0 };\n\tconst scopeRejections = scopeRejectionsByPeer?.get(peerId);\n\tconst addresses = safeJsonList(row.addresses_json as string | null);\n\tconst perScopeSync = listPerPeerScopeSyncState(store.db, {\n\t\tlocalDeviceId: localDeviceId ?? null,\n\t\tpeerDeviceId: peerId,\n\t});\n\treturn {\n\t\tpeer_device_id: row.peer_device_id,\n\t\tname: row.name,\n\t\tfingerprint: showDiag ? row.pinned_fingerprint : null,\n\t\tpinned: Boolean(row.pinned_fingerprint),\n\t\taddresses: showDiag ? addresses : [],\n\t\taddress_count: addresses.length,\n\t\tlast_seen_at: row.last_seen_at,\n\t\tlast_sync_at: row.last_sync_at,\n\t\tlast_error: showDiag ? row.last_error : null,\n\t\truntime_version: row.runtime_version ?? null,\n\t\truntime_version_observed_at: row.runtime_version_observed_at ?? null,\n\t\thas_error: Boolean(row.last_error),\n\t\tclaimed_local_actor: Boolean(row.claimed_local_actor),\n\t\tclaimed_local_actor_scope: claimedLocalActorScopeStatus(store, row),\n\t\tactor_id: row.actor_id ?? null,\n\t\tactor_display_name: row.actor_display_name ?? null,\n\t\tauthorized_scopes: peerAuthorizedScopes(store, peerId),\n\t\t// Per-Space sync state intersecting local + peer membership and joining\n\t\t// per-scope replication cursor data. Use this surface to render\n\t\t// per-Space progress in CLI/UI without exposing the legacy `status=ok`\n\t\t// shorthand that hid scoped sync gaps in 0.32.x.\n\t\tper_scope_sync: perScopeSync,\n\t\tproject_scope: {\n\t\t\t...currentProjectScope(row, readPeerProjectFilters(store, String(row.peer_device_id ?? \"\"))),\n\t\t},\n\t\trecent_ops: { in: recentOps.in, out: recentOps.out },\n\t\tscope_rejections: {\n\t\t\ttotal: scopeRejections?.total ?? 0,\n\t\t\tby_reason: scopeRejections?.by_reason ?? {},\n\t\t\tlast_at: scopeRejections?.last_at ?? null,\n\t\t},\n\t\tdiscovered_via_coordinator_id:\n\t\t\ttypeof row.discovered_via_coordinator_id === \"string\"\n\t\t\t\t? row.discovered_via_coordinator_id\n\t\t\t\t: null,\n\t\tdiscovered_via_group_id:\n\t\t\ttypeof row.discovered_via_group_id === \"string\" ? row.discovered_via_group_id : null,\n\t};\n}\n\nfunction redactSyncAttemptError(error: unknown): string | null {\n\tconst text = String(error ?? \"\").trim();\n\tif (!text) return null;\n\treturn \"sync attempt failed; enable diagnostics for details\";\n}\n\nfunction mapSyncAttemptRow(\n\trow: Record<string, unknown>,\n\tshowDiag: boolean,\n\taddresses?: string[],\n): Record<string, unknown> {\n\tconst redactedError = redactSyncAttemptError(row.error);\n\treturn {\n\t\t...row,\n\t\terror: showDiag ? row.error : redactedError,\n\t\terror_redacted: !showDiag && redactedError != null,\n\t\tstatus: attemptStatus(row),\n\t\taddress: showDiag && addresses?.length ? addresses[0] : null,\n\t};\n}\n\nconst SYNC_SCOPE_REJECTION_WINDOW_SECONDS = 24 * 60 * 60;\nconst CLEANUP_DIAGNOSTICS_MAX_ROWS = 250;\n\nfunction recentScopeRejectionsByPeer(\n\tstore: MemoryStore,\n): Map<string, InboundScopeRejectionPeerSummary> {\n\tconst cutoff = new Date(Date.now() - SYNC_SCOPE_REJECTION_WINDOW_SECONDS * 1000).toISOString();\n\tconst summaries = summarizeInboundScopeRejections(store.db, { sinceIso: cutoff });\n\tconst map = new Map<string, InboundScopeRejectionPeerSummary>();\n\tfor (const summary of summaries) {\n\t\tconst id = String(summary.peer_device_id ?? \"\").trim();\n\t\tif (!id) continue;\n\t\tmap.set(id, summary);\n\t}\n\treturn map;\n}\n\nfunction cleanupDiagnostics(\n\tstore: MemoryStore,\n\tlocalDeviceId: string | null,\n\tshowDiag: boolean,\n): Record<string, unknown> {\n\tconst opRows = store.db\n\t\t.prepare(\n\t\t\t`SELECT\n\t\t\t\tSUM(CASE WHEN device_id = ? THEN 1 ELSE 0 END) AS source_authored,\n\t\t\t\tSUM(CASE WHEN device_id != ? THEN 1 ELSE 0 END) AS applied,\n\t\t\t\tMAX(created_at) AS latest_at\n\t\t\t FROM replication_ops\n\t\t\t WHERE op_type = ?`,\n\t\t)\n\t\t.get(localDeviceId ?? \"\", localDeviceId ?? \"\", ACCESS_CLEANUP_OP_TYPE) as\n\t\t| { applied: number | null; latest_at: string | null; source_authored: number | null }\n\t\t| undefined;\n\tconst stale =\n\t\tlocalDeviceId && showDiag\n\t\t\t? diagnoseStalePeerReceivedRows(store.db, {\n\t\t\t\t\tlocalDeviceId,\n\t\t\t\t\tmaxRows: CLEANUP_DIAGNOSTICS_MAX_ROWS,\n\t\t\t\t})\n\t\t\t: { ambiguous: [], checked: 0, retained: 0, would_delete: 0, would_delete_memory_ids: [] };\n\tconst ambiguousByReason: Record<string, number> = {};\n\tfor (const item of stale.ambiguous) {\n\t\tambiguousByReason[item.reason] = (ambiguousByReason[item.reason] ?? 0) + 1;\n\t}\n\tconst sourceAuthored = Number(opRows?.source_authored ?? 0);\n\tconst applied = Number(opRows?.applied ?? 0);\n\tconst ambiguous = stale.ambiguous.length;\n\tconst state = stale.would_delete\n\t\t? \"cleanup_pending\"\n\t\t: ambiguous\n\t\t\t? \"needs_review\"\n\t\t\t: applied\n\t\t\t\t? \"cleanup_applied\"\n\t\t\t\t: sourceAuthored\n\t\t\t\t\t? \"cleanup_announced\"\n\t\t\t\t\t: \"clear\";\n\treturn {\n\t\tstate,\n\t\taccess_cleanup_ops: {\n\t\t\tsource_authored: sourceAuthored,\n\t\t\tapplied,\n\t\t\tlatest_at: opRows?.latest_at ?? null,\n\t\t},\n\t\tstale_peer_rows: {\n\t\t\tchecked: stale.checked,\n\t\t\tdiagnostic_limit: showDiag ? CLEANUP_DIAGNOSTICS_MAX_ROWS : 0,\n\t\t\tscan_skipped: !showDiag || !localDeviceId,\n\t\t\twould_remove: stale.would_delete,\n\t\t\tambiguous,\n\t\t\tambiguous_by_reason: ambiguousByReason,\n\t\t\tretained: stale.retained,\n\t\t\titems: showDiag ? stale.ambiguous.slice(0, 25) : undefined,\n\t\t},\n\t\tredacted: !showDiag,\n\t};\n}\n\nfunction legacySharedReviewSummary(store: MemoryStore): Record<string, unknown> {\n\tconst rows = legacySharedReviewRows(store);\n\tconst memoryCount = rows.length;\n\tconst lastUpdatedAt = rows.reduce<string | null>(\n\t\t(current, row) =>\n\t\t\trow.updated_at && (!current || row.updated_at > current) ? row.updated_at : current,\n\t\tnull,\n\t);\n\tconst ownedBySelf = store.buildOwnershipPredicate();\n\tconst candidatesByIdentity = new Map(\n\t\tlistProjectScopeCandidates(store.db, { limit: null }).map((candidate) => [\n\t\t\tcandidate.workspace_identity,\n\t\t\tcandidate,\n\t\t]),\n\t);\n\tconst groupsByIdentity = new Map<\n\t\tstring,\n\t\t{\n\t\t\tworkspace_identity: string;\n\t\t\tidentity_source: string;\n\t\t\tdisplay_project: string;\n\t\t\tmemory_count: number;\n\t\t\treassignable_memory_count: number;\n\t\t\tpeer_owned_memory_count: number;\n\t\t\tlast_updated_at: string | null;\n\t\t\tmemory_samples: LegacySharedReviewMemorySample[];\n\t\t\tsuggested_scope_id: string | null;\n\t\t\tsuggestion_reason: string | null;\n\t\t}\n\t>();\n\tfor (const row of rows) {\n\t\tconst identity = canonicalWorkspaceIdentity({\n\t\t\tcwd: row.cwd,\n\t\t\tgitBranch: row.git_branch,\n\t\t\tgitRemote: row.git_remote,\n\t\t\tproject: row.project,\n\t\t\tworkspaceId: row.workspace_id,\n\t\t});\n\t\tconst candidate = candidatesByIdentity.get(identity.value);\n\t\tconst resolvedScope = candidate?.resolved_scope_id ?? null;\n\t\tconst suggestedScope =\n\t\t\tresolvedScope &&\n\t\t\tresolvedScope !== LOCAL_DEFAULT_SCOPE_ID &&\n\t\t\tresolvedScope !== LEGACY_SHARED_REVIEW_SCOPE_ID\n\t\t\t\t? resolvedScope\n\t\t\t\t: candidate?.suggested_scope_id;\n\t\tconst existing = groupsByIdentity.get(identity.value);\n\t\tconst isOwnedBySelf = ownedBySelf(row as unknown as Record<string, unknown>);\n\t\tconst rowUpdatedAt = row.updated_at ?? null;\n\t\tif (existing) {\n\t\t\texisting.memory_count += 1;\n\t\t\tif (isOwnedBySelf) existing.reassignable_memory_count += 1;\n\t\t\telse existing.peer_owned_memory_count += 1;\n\t\t\tif (rowUpdatedAt && (!existing.last_updated_at || rowUpdatedAt > existing.last_updated_at)) {\n\t\t\t\texisting.last_updated_at = rowUpdatedAt;\n\t\t\t}\n\t\t\tif (existing.memory_samples.length < LEGACY_SHARED_REVIEW_SAMPLE_LIMIT) {\n\t\t\t\texisting.memory_samples.push(legacySharedReviewMemorySample(row, isOwnedBySelf));\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tgroupsByIdentity.set(identity.value, {\n\t\t\tworkspace_identity: identity.value,\n\t\t\tidentity_source: identity.source,\n\t\t\tdisplay_project: identity.displayProject ?? row.project ?? row.cwd ?? identity.value,\n\t\t\tmemory_count: 1,\n\t\t\treassignable_memory_count: isOwnedBySelf ? 1 : 0,\n\t\t\tpeer_owned_memory_count: isOwnedBySelf ? 0 : 1,\n\t\t\tlast_updated_at: rowUpdatedAt,\n\t\t\tmemory_samples: [legacySharedReviewMemorySample(row, isOwnedBySelf)],\n\t\t\tsuggested_scope_id: suggestedScope ?? null,\n\t\t\tsuggestion_reason: suggestedScope\n\t\t\t\t? (candidate?.suggestion_reason ??\n\t\t\t\t\t\"Existing project mapping can be reviewed as a destination, but legacy data is not promoted automatically.\")\n\t\t\t\t: null,\n\t\t});\n\t}\n\tconst totalGroupCount = groupsByIdentity.size;\n\tconst groups = [...groupsByIdentity.values()].sort(\n\t\t(left, right) =>\n\t\t\tright.memory_count - left.memory_count ||\n\t\t\t(right.last_updated_at ?? \"\").localeCompare(left.last_updated_at ?? \"\") ||\n\t\t\tleft.workspace_identity.localeCompare(right.workspace_identity),\n\t);\n\tconst targetScopes = listSharingDomainSettingsScopes(store.db)\n\t\t.filter(\n\t\t\t(scope) =>\n\t\t\t\tscope.scope_id !== LOCAL_DEFAULT_SCOPE_ID &&\n\t\t\t\tscope.scope_id !== LEGACY_SHARED_REVIEW_SCOPE_ID,\n\t\t)\n\t\t.map((scope) => ({\n\t\t\tauthority_type: scope.authority_type,\n\t\t\tlabel: scope.label || scope.scope_id,\n\t\t\tscope_id: scope.scope_id,\n\t\t}));\n\treturn {\n\t\tscope_id: LEGACY_SHARED_REVIEW_SCOPE_ID,\n\t\tmemory_count: memoryCount,\n\t\thas_data: memoryCount > 0,\n\t\tlast_updated_at: lastUpdatedAt,\n\t\tgroups,\n\t\ttotal_group_count: totalGroupCount,\n\t\ttarget_scopes: targetScopes,\n\t};\n}\n\ninterface LegacySharedReviewReassignmentMemoryRow {\n\tid: number;\n\trev: number | null;\n\tactive: number | null;\n\tdeleted_at: string | null;\n\tcreated_at: string | null;\n\tupdated_at: string | null;\n\tscope_id: string | null;\n\tkind: string | null;\n\ttitle: string | null;\n\tbody_text: string | null;\n\tproject: string | null;\n\tcwd: string | null;\n\tgit_remote: string | null;\n\tgit_branch: string | null;\n\tworkspace_id: string | null;\n\tactor_id: string | null;\n\torigin_device_id: string | null;\n\tmetadata_json: string | null;\n}\n\nconst LEGACY_SHARED_REVIEW_SAMPLE_LIMIT = 3;\nconst LEGACY_SHARED_REVIEW_BODY_PREVIEW_SQL_LIMIT = 360;\n\ninterface LegacySharedReviewMemorySample {\n\tid: number;\n\tkind: string | null;\n\ttitle: string;\n\tbody_preview: string | null;\n\tcreated_at: string | null;\n\tupdated_at: string | null;\n\townership: \"local\" | \"peer\";\n\tproject: string | null;\n\tcwd: string | null;\n\tgit_remote: string | null;\n}\n\nfunction previewText(value: string | null | undefined, limit = 180): string | null {\n\tconst normalized = value?.replace(/\\s+/g, \" \").trim();\n\tif (!normalized) return null;\n\treturn normalized.length > limit ? `${normalized.slice(0, limit - 1)}…` : normalized;\n}\n\nfunction legacySharedReviewMemorySample(\n\trow: LegacySharedReviewReassignmentMemoryRow,\n\tisOwnedBySelf: boolean,\n): LegacySharedReviewMemorySample {\n\treturn {\n\t\tid: row.id,\n\t\tkind: row.kind,\n\t\ttitle: previewText(row.title, 120) ?? `Memory ${row.id}`,\n\t\tbody_preview: previewText(row.body_text),\n\t\tcreated_at: row.created_at ?? null,\n\t\tupdated_at: row.updated_at ?? null,\n\t\townership: isOwnedBySelf ? \"local\" : \"peer\",\n\t\tproject: row.project ?? null,\n\t\tcwd: row.cwd ?? null,\n\t\tgit_remote: row.git_remote ?? null,\n\t};\n}\n\nfunction legacySharedReviewRows(store: MemoryStore): LegacySharedReviewReassignmentMemoryRow[] {\n\treturn store.db\n\t\t.prepare(\n\t\t\t`SELECT m.id,\n\t\t\t m.rev,\n\t\t\t m.active,\n\t\t\t m.deleted_at,\n\t\t\t m.created_at,\n\t\t\t m.updated_at,\n\t\t\t m.scope_id,\n\t\t\t m.kind,\n\t\t\t m.title,\n\t\t\t\t substr(m.body_text, 1, ?) AS body_text,\n\t\t\t s.project,\n\t\t\t s.cwd,\n\t\t\t s.git_remote,\n\t\t\t s.git_branch,\n\t\t\t m.workspace_id,\n\t\t\t m.actor_id,\n\t\t\t m.origin_device_id,\n\t\t\t m.metadata_json\n\t\t\t FROM memory_items m\n\t\t\t LEFT JOIN sessions s ON s.id = m.session_id\n\t\t\t WHERE m.scope_id = ?\n\t\t\t AND m.active = 1\n\t\t\t AND m.deleted_at IS NULL\n\t\t\t ORDER BY COALESCE(m.updated_at, m.created_at, '') DESC, m.id DESC`,\n\t\t)\n\t\t.all(\n\t\t\tLEGACY_SHARED_REVIEW_BODY_PREVIEW_SQL_LIMIT,\n\t\t\tLEGACY_SHARED_REVIEW_SCOPE_ID,\n\t\t) as LegacySharedReviewReassignmentMemoryRow[];\n}\n\nfunction legacySharedReviewConfirmationToken(input: {\n\trows: LegacySharedReviewReassignmentMemoryRow[];\n\tscopeId: string;\n\tstore: MemoryStore;\n\tworkspaceIdentity: string;\n}): string {\n\tconst ownedBySelf = input.store.buildOwnershipPredicate();\n\tconst payload = input.rows\n\t\t.map((row) => {\n\t\t\tconst ownership = ownedBySelf(row as unknown as Record<string, unknown>) ? \"local\" : \"peer\";\n\t\t\treturn `${row.id}:${row.rev ?? 0}:${row.scope_id ?? \"\"}:${ownership}`;\n\t\t})\n\t\t.sort()\n\t\t.join(\",\");\n\treturn Buffer.from(`${input.workspaceIdentity}|${input.scopeId}|${payload}`, \"utf8\").toString(\n\t\t\"base64url\",\n\t);\n}\n\ninterface LegacySharedReviewReassignmentPreview {\n\tconfirmation_token: string;\n\tworkspace_identity: string;\n\tscope_id: string;\n\ttarget_scope_label: string;\n\tmemory_count: number;\n\treassignable_memory_count: number;\n\tskipped_memory_count: number;\n\taffected_peer_device_count: number;\n\taffected_peer_device_ids: string[];\n\twarning: string;\n}\n\ninterface ProjectInventoryMemoryRow {\n\tid: number;\n\trev: number | null;\n\tproject: string | null;\n\tcwd: string | null;\n\tgit_remote: string | null;\n\tgit_branch: string | null;\n\tworkspace_id: string | null;\n\tactor_id: string | null;\n\torigin_device_id: string | null;\n\tmetadata_json: string | null;\n}\n\nfunction projectInventoryRowsForWorkspace(\n\tstore: MemoryStore,\n\tworkspaceIdentity: string,\n): ProjectInventoryMemoryRow[] {\n\tconst rows = store.db\n\t\t.prepare(\n\t\t\t`SELECT m.id,\n\t\t\t m.rev,\n\t\t\t s.project,\n\t\t\t s.cwd,\n\t\t\t s.git_remote,\n\t\t\t s.git_branch,\n\t\t\t m.workspace_id,\n\t\t\t m.actor_id,\n\t\t\t m.origin_device_id,\n\t\t\t m.metadata_json\n\t\t\t FROM memory_items m\n\t\t\t LEFT JOIN sessions s ON s.id = m.session_id\n\t\t\t WHERE m.active = 1\n\t\t\t AND m.deleted_at IS NULL`,\n\t\t)\n\t\t.all() as ProjectInventoryMemoryRow[];\n\treturn rows.filter((row) => {\n\t\tconst identity = canonicalWorkspaceIdentity({\n\t\t\tcwd: row.cwd,\n\t\t\tgitBranch: row.git_branch,\n\t\t\tgitRemote: row.git_remote,\n\t\t\tproject: row.project,\n\t\t\tworkspaceId: row.workspace_id,\n\t\t});\n\t\treturn identity.value === workspaceIdentity;\n\t});\n}\n\nfunction projectForgetConfirmationToken(\n\tstore: MemoryStore,\n\trows: ProjectInventoryMemoryRow[],\n): string {\n\tconst ownedBySelf = store.buildOwnershipPredicate();\n\tconst payload = rows\n\t\t.map((row) => {\n\t\t\tconst ownership = ownedBySelf(row as unknown as Record<string, unknown>) ? \"local\" : \"peer\";\n\t\t\treturn `${row.id}:${row.rev ?? 0}:${ownership}`;\n\t\t})\n\t\t.sort()\n\t\t.join(\",\");\n\treturn Buffer.from(payload, \"utf8\").toString(\"base64url\");\n}\n\nfunction forgetProjectInventoryLocalMemories(\n\tstore: MemoryStore,\n\tinput: { confirmationToken?: string | null; confirmed: boolean; workspaceIdentity: string },\n): Record<string, unknown> {\n\tif (!input.workspaceIdentity.trim()) {\n\t\tthrow new Error(\"workspace_identity must be a non-empty string\");\n\t}\n\tconst rows = projectInventoryRowsForWorkspace(store, input.workspaceIdentity);\n\tif (rows.length === 0) throw new Error(\"project identity not found\");\n\tconst ownedBySelf = store.buildOwnershipPredicate();\n\tconst localRows = rows.filter((row) => ownedBySelf(row as unknown as Record<string, unknown>));\n\tconst confirmationToken = projectForgetConfirmationToken(store, rows);\n\tconst preview = {\n\t\tconfirmation_token: confirmationToken,\n\t\tlocal_owned_memory_count: localRows.length,\n\t\tpeer_owned_memory_count: rows.length - localRows.length,\n\t\tworkspace_identity: input.workspaceIdentity,\n\t};\n\tif (!input.confirmed) {\n\t\treturn { confirmed: false, ...preview };\n\t}\n\tif (input.confirmationToken !== confirmationToken) {\n\t\tthrow new Error(\"project memories changed before cleanup; refresh and try again\");\n\t}\n\tstore.db.transaction(() => {\n\t\tfor (const row of localRows) store.forget(row.id);\n\t})();\n\treturn { confirmed: true, forgotten_memory_count: localRows.length, ...preview };\n}\n\nfunction assertLocalDeviceScopeMembership(store: MemoryStore, scopeId: string): void {\n\tif (scopeId === LOCAL_DEFAULT_SCOPE_ID) return;\n\tconst row = store.db\n\t\t.prepare(\n\t\t\t`SELECT 1\n\t\t\t FROM scope_memberships sm\n\t\t\t JOIN replication_scopes rs ON rs.scope_id = sm.scope_id\n\t\t\t WHERE sm.scope_id = ?\n\t\t\t AND sm.device_id = ?\n\t\t\t AND sm.status = 'active'\n\t\t\t AND rs.status = 'active'\n\t\t\t AND sm.membership_epoch >= rs.membership_epoch\n\t\t\t LIMIT 1`,\n\t\t)\n\t\t.get(scopeId, store.deviceId);\n\tif (!row) throw new Error(`local device is not a member of Sharing domain ${scopeId}`);\n}\n\nfunction legacySharedReviewRowsForWorkspace(\n\tstore: MemoryStore,\n\tworkspaceIdentity: string,\n): LegacySharedReviewReassignmentMemoryRow[] {\n\treturn legacySharedReviewRows(store).filter((row) => {\n\t\tconst identity = canonicalWorkspaceIdentity({\n\t\t\tcwd: row.cwd,\n\t\t\tgitBranch: row.git_branch,\n\t\t\tgitRemote: row.git_remote,\n\t\t\tproject: row.project,\n\t\t\tworkspaceId: row.workspace_id,\n\t\t});\n\t\treturn identity.value === workspaceIdentity;\n\t});\n}\n\nfunction reassignableLegacySharedReviewRows(\n\tstore: MemoryStore,\n\trows: LegacySharedReviewReassignmentMemoryRow[],\n): LegacySharedReviewReassignmentMemoryRow[] {\n\tconst reassignableRows = rows.filter((row) =>\n\t\tstore.memoryOwnedBySelf(row as unknown as Record<string, unknown>),\n\t);\n\tif (reassignableRows.length === 0) {\n\t\tthrow new Error(\n\t\t\t\"This legacy review group contains only peer-owned memories; this device cannot reassign them to a Sharing domain.\",\n\t\t);\n\t}\n\tconst currentRows = store.db\n\t\t.prepare(\n\t\t\t`SELECT id, scope_id, active, deleted_at\n\t\t\t FROM memory_items\n\t\t\t WHERE id IN (${reassignableRows.map(() => \"?\").join(\",\")})`,\n\t\t)\n\t\t.all(...reassignableRows.map((row) => row.id)) as Array<{\n\t\tactive: number | null;\n\t\tdeleted_at: string | null;\n\t\tid: number;\n\t\tscope_id: string | null;\n\t}>;\n\tconst currentById = new Map(currentRows.map((row) => [Number(row.id), row]));\n\tfor (const row of reassignableRows) {\n\t\tconst current = currentById.get(row.id);\n\t\tif (\n\t\t\tcurrent?.scope_id !== LEGACY_SHARED_REVIEW_SCOPE_ID ||\n\t\t\tcurrent.active !== 1 ||\n\t\t\tcurrent.deleted_at\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t\"legacy shared review group changed before reassignment; refresh and try again\",\n\t\t\t);\n\t\t}\n\t}\n\treturn reassignableRows;\n}\n\nfunction legacySharedReviewReassignmentPreview(\n\tstore: MemoryStore,\n\tinput: { scopeId: string; workspaceIdentity: string },\n): LegacySharedReviewReassignmentPreview {\n\tif (!input.workspaceIdentity.trim())\n\t\tthrow new Error(\"workspace_identity must be a non-empty string\");\n\tif (!input.scopeId.trim()) throw new Error(\"scope_id must be a non-empty string\");\n\tif (input.scopeId === LOCAL_DEFAULT_SCOPE_ID) {\n\t\tthrow new Error(\"local-default is not a valid target for legacy shared review reassignment\");\n\t}\n\tif (input.scopeId === LEGACY_SHARED_REVIEW_SCOPE_ID) {\n\t\tthrow new Error(\"legacy-shared-review is a review bucket, not an assignable Sharing domain\");\n\t}\n\tconst targetScope = listSharingDomainSettingsScopes(store.db).find(\n\t\t(scope) => scope.scope_id === input.scopeId,\n\t);\n\tif (!targetScope) throw new Error(`scope_id ${input.scopeId} is not an active Sharing domain`);\n\tassertLocalDeviceScopeMembership(store, input.scopeId);\n\tconst rows = legacySharedReviewRowsForWorkspace(store, input.workspaceIdentity);\n\tif (rows.length === 0) throw new Error(\"legacy shared review group not found\");\n\tconst reassignableRows = reassignableLegacySharedReviewRows(store, rows);\n\tconst peerDeviceIds = [\n\t\t...new Set(\n\t\t\trows\n\t\t\t\t.map((row) => String(row.origin_device_id ?? \"\").trim())\n\t\t\t\t.filter((deviceId) => deviceId && deviceId !== store.deviceId),\n\t\t),\n\t].sort();\n\treturn {\n\t\taffected_peer_device_count: peerDeviceIds.length,\n\t\taffected_peer_device_ids: peerDeviceIds.slice(0, 5),\n\t\tconfirmation_token: legacySharedReviewConfirmationToken({\n\t\t\trows,\n\t\t\tscopeId: input.scopeId,\n\t\t\tstore,\n\t\t\tworkspaceIdentity: input.workspaceIdentity,\n\t\t}),\n\t\tmemory_count: rows.length,\n\t\treassignable_memory_count: reassignableRows.length,\n\t\tscope_id: input.scopeId,\n\t\tskipped_memory_count: rows.length - reassignableRows.length,\n\t\ttarget_scope_label: targetScope.label || targetScope.scope_id,\n\t\twarning:\n\t\t\t\"This device can reassign only locally owned memories. Peer-owned copies must be fixed on their source device. Online compatible peers should converge after syncing, but offline devices, backups, copied databases, malicious peers, or old versions may retain old copies.\",\n\t\tworkspace_identity: input.workspaceIdentity,\n\t};\n}\n\nfunction reassignLegacySharedReviewGroup(\n\tstore: MemoryStore,\n\tinput: { confirmationToken?: string | null; scopeId: string; workspaceIdentity: string },\n): Record<string, unknown> {\n\tconst preview = legacySharedReviewReassignmentPreview(store, input);\n\tif (input.confirmationToken !== preview.confirmation_token) {\n\t\tthrow new Error(\n\t\t\t\"legacy shared review group changed before reassignment; refresh and try again\",\n\t\t);\n\t}\n\tconst rows = reassignableLegacySharedReviewRows(\n\t\tstore,\n\t\tlegacySharedReviewRowsForWorkspace(store, input.workspaceIdentity),\n\t);\n\tstore.db.transaction(() => {\n\t\tfor (const row of rows) store.reassignMemoryScope(row.id, input.scopeId);\n\t})();\n\treturn {\n\t\tok: true,\n\t\t...preview,\n\t\treassigned_memory_count: rows.length,\n\t\tlegacy_shared_review: legacySharedReviewSummary(store),\n\t};\n}\n\n// Aggregate ops_in / ops_out across recent successful sync_attempts per peer.\n// Window: last 24 hours. Feeds the per-peer direction glyph on the Sync tab\n// (↕ bidirectional, ↑ publishing, ↓ subscribed) off real traffic instead of\n// an invented peer-role field.\nconst SYNC_DIRECTION_WINDOW_SECONDS = 24 * 60 * 60;\n\nfunction recentPeerOps(store: MemoryStore): Map<string, { in: number; out: number }> {\n\tconst cutoff = new Date(Date.now() - SYNC_DIRECTION_WINDOW_SECONDS * 1000).toISOString();\n\tconst rows = store.db\n\t\t.prepare(\n\t\t\t`SELECT peer_device_id,\n\t\t\t COALESCE(SUM(ops_in), 0) AS ops_in,\n\t\t\t COALESCE(SUM(ops_out), 0) AS ops_out\n\t\t\t FROM sync_attempts\n\t\t\t WHERE ok = 1 AND finished_at IS NOT NULL AND finished_at >= ?\n\t\t\t GROUP BY peer_device_id`,\n\t\t)\n\t\t.all(cutoff) as Array<{\n\t\tpeer_device_id: string | null;\n\t\tops_in: number | null;\n\t\tops_out: number | null;\n\t}>;\n\tconst map = new Map<string, { in: number; out: number }>();\n\tfor (const row of rows) {\n\t\tconst id = String(row.peer_device_id ?? \"\").trim();\n\t\tif (!id) continue;\n\t\tmap.set(id, { in: Number(row.ops_in ?? 0), out: Number(row.ops_out ?? 0) });\n\t}\n\treturn map;\n}\n\n// ---------------------------------------------------------------------------\n// Peer status helpers\n// ---------------------------------------------------------------------------\n\nfunction isRecentIso(value: unknown, windowS = SYNC_STALE_AFTER_SECONDS): boolean {\n\tconst raw = String(value ?? \"\").trim();\n\tif (!raw) return false;\n\tconst normalized = raw.replace(\"Z\", \"+00:00\");\n\tconst hasOffset = /(?:Z|[+-]\\d{2}:?\\d{2})$/i.test(raw);\n\tconst ts = new Date(hasOffset ? normalized : `${normalized}+00:00`);\n\tif (Number.isNaN(ts.getTime())) return false;\n\tconst ageS = (Date.now() - ts.getTime()) / 1000;\n\treturn ageS >= 0 && ageS <= windowS;\n}\n\nfunction peerStatus(peer: Record<string, unknown>): Record<string, unknown> {\n\tconst lastSyncAt = peer.last_sync_at;\n\tconst lastPingAt = peer.last_seen_at;\n\tconst hasError = Boolean(peer.has_error);\n\n\tconst syncFresh = isRecentIso(lastSyncAt);\n\tconst pingFresh = isRecentIso(lastPingAt);\n\n\tlet peerState: string;\n\tif (hasError && !(syncFresh || pingFresh)) peerState = \"offline\";\n\telse if (hasError) peerState = \"degraded\";\n\telse if (syncFresh || pingFresh) peerState = \"online\";\n\telse if (lastSyncAt || lastPingAt) peerState = \"stale\";\n\telse peerState = \"unknown\";\n\n\tconst syncStatus = hasError ? \"error\" : syncFresh ? \"ok\" : lastSyncAt ? \"stale\" : \"unknown\";\n\tconst pingStatus = pingFresh ? \"ok\" : lastPingAt ? \"stale\" : \"unknown\";\n\n\treturn {\n\t\tsync_status: syncStatus,\n\t\tping_status: pingStatus,\n\t\tpeer_state: peerState,\n\t\tfresh: syncFresh || pingFresh,\n\t\tlast_sync_at: lastSyncAt,\n\t\tlast_ping_at: lastPingAt,\n\t};\n}\n\nfunction attemptStatus(attempt: Record<string, unknown>): string {\n\tif (attempt.ok) return \"ok\";\n\tif (attempt.error) return \"error\";\n\treturn \"unknown\";\n}\n\nfunction readViewerBinding(dbPath: string): { host: string; port: number } | null {\n\ttry {\n\t\tconst raw = readFileSync(join(dirname(dbPath), \"viewer.pid\"), \"utf8\");\n\t\tconst parsed = JSON.parse(raw) as Partial<{ host: string; port: number }>;\n\t\tif (typeof parsed.host === \"string\" && typeof parsed.port === \"number\") {\n\t\t\treturn { host: parsed.host, port: parsed.port };\n\t\t}\n\t} catch {\n\t\t// ignore missing/malformed pidfile\n\t}\n\treturn null;\n}\n\nconst PEERS_QUERY = `\n\tSELECT p.peer_device_id, p.name, p.pinned_fingerprint, p.addresses_json,\n\t p.last_seen_at, p.last_sync_at, p.last_error,\n\t p.runtime_version, p.runtime_version_observed_at,\n\t p.projects_include_json, p.projects_exclude_json, p.claimed_local_actor,\n\t p.actor_id, p.discovered_via_coordinator_id, p.discovered_via_group_id,\n\t a.display_name AS actor_display_name\n\tFROM sync_peers AS p\n\tLEFT JOIN actors AS a ON a.actor_id = p.actor_id\n\tORDER BY name, peer_device_id\n`;\n\n// ---------------------------------------------------------------------------\n// Route factory\n// ---------------------------------------------------------------------------\n\n/**\n * Compute the negotiated sync capability for a request by combining the\n * server's local capability with the value the caller advertised in the\n * `X-Codemem-Sync-Capability` header. Routes use this to decide whether to\n * honor scoped-sync wire features such as explicit `scope_id` parameters\n * and `/v1/status` `authorized_scopes` enumeration.\n *\n * Threat model: this header is intentionally only a best-effort capability\n * advertisement. It is not signed, so an authenticated paired peer — or a\n * bootstrap worker presenting a valid grant on `/v1/status` — can claim\n * `scoped` support and cause status to enumerate the scopes that caller is\n * already authorized to see. That is metadata disclosure inside the paired-peer\n * or bootstrap-grant trust boundary, not data authorization. Every scoped data\n * path still requires signed requests and checks membership before returning\n * scope contents.\n */\nfunction negotiatedSyncCapability(c: Context) {\n\tconst header = c.req.header(SYNC_CAPABILITY_HEADER) ?? null;\n\treturn negotiateSyncCapability(LOCAL_SYNC_CAPABILITY, normalizeSyncCapability(header));\n}\n\n/**\n * Peer-to-peer sync protocol routes (/v1/*).\n *\n * These are mounted on the sync listener (0.0.0.0:7337) and are\n * network-accessible. All requests are auth-gated via signature\n * verification so unauthenticated callers are rejected.\n */\nexport function syncProtocolRoutes(getStore: StoreFactory, opts: SyncProtocolRouteOptions = {}) {\n\tconst app = new Hono();\n\tconst routeRateLimit = opts.routeRateLimit ?? null;\n\n\tfunction rateLimitedResponse(c: Context, key: string, authenticated: boolean) {\n\t\tif (!routeRateLimit) return null;\n\t\tconst isRead = c.req.method === \"GET\" || c.req.method === \"HEAD\" || c.req.method === \"OPTIONS\";\n\t\tconst result = routeRateLimit.limiter.check(\n\t\t\t`${c.req.method}:${authenticated ? \"auth\" : \"anon\"}:${key}`,\n\t\t\tauthenticated\n\t\t\t\t? isRead\n\t\t\t\t\t? routeRateLimit.readLimit\n\t\t\t\t\t: routeRateLimit.mutationLimit\n\t\t\t\t: isRead\n\t\t\t\t\t? routeRateLimit.unauthenticatedReadLimit\n\t\t\t\t\t: routeRateLimit.unauthenticatedMutationLimit,\n\t\t);\n\t\tif (result.allowed) return null;\n\t\tc.header(\"Retry-After\", String(result.retryAfterS));\n\t\treturn c.json({ error: \"rate_limited\", retry_after_s: result.retryAfterS }, 429);\n\t}\n\n\t// GET /v1/status (peer sync protocol)\n\tapp.get(\"/v1/status\", (c) => {\n\t\tconst store = getStore();\n\t\treturn (async () => {\n\t\t\tlet auth = authorizeSyncRequest(store, c.req, Buffer.alloc(0));\n\t\t\tif (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);\n\t\t\tlet preauthChecked = false;\n\t\t\tlet bootstrapAttempted = false;\n\t\t\tlet deviceAuthReason: string | null = null;\n\t\t\tif (!auth.ok) {\n\t\t\t\tconst bootstrapGrantId = (c.req.header(\"X-Codemem-Bootstrap-Grant\") ?? \"\").trim();\n\t\t\t\tif (bootstrapGrantId) {\n\t\t\t\t\tpreauthChecked = true;\n\t\t\t\t\t// Use unauthenticated bucket with stable key — grant is not yet verified,\n\t\t\t\t\t// so caller-controlled headers must not influence rate-limit identity.\n\t\t\t\t\tconst bootstrapLimited = rateLimitedResponse(c, c.req.path, false);\n\t\t\t\t\tif (bootstrapLimited) return bootstrapLimited;\n\t\t\t\t} else {\n\t\t\t\t\tpreauthChecked = true;\n\t\t\t\t\tconst unauthLimited = rateLimitedResponse(c, c.req.path, false);\n\t\t\t\t\tif (unauthLimited) return unauthLimited;\n\t\t\t\t}\n\t\t\t\tdeviceAuthReason = auth.reason;\n\t\t\t\tauth = await authorizeBootstrapGrantRequest(store, c.req, Buffer.alloc(0));\n\t\t\t\tbootstrapAttempted = true;\n\t\t\t}\n\t\t\tif (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);\n\t\t\tif (!auth.ok) {\n\t\t\t\t// Specific reasons stay server-side; wire responses remain generic.\n\t\t\t\tconst grantPresent = Boolean((c.req.header(\"X-Codemem-Bootstrap-Grant\") ?? \"\").trim());\n\t\t\t\t// Warn only when the caller actually attempted authentication (a\n\t\t\t\t// grant or signed device headers); bare probes and health checks\n\t\t\t\t// must not fill logs with attacker-controllable noise.\n\t\t\t\tconst authAttempted =\n\t\t\t\t\tgrantPresent || (deviceAuthReason != null && deviceAuthReason !== \"missing_headers\");\n\t\t\t\tif (bootstrapAttempted && authAttempted) {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`[sync] peer auth failed: reason=${auth.reason} device_auth_reason=${deviceAuthReason ?? \"none\"} grant_present=${grantPresent} path=${c.req.path} device=${loggableHeaderValue(c.req.header(\"X-Opencode-Device\"))}`,\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tlogDirectPeerAuthDiagnostic(deviceAuthReason, auth.reason);\n\t\t\t\t}\n\t\t\t\treturn (\n\t\t\t\t\t(preauthChecked ? null : rateLimitedResponse(c, c.req.path, false)) ??\n\t\t\t\t\tc.json(unauthorizedPayload(), 401)\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst limited = rateLimitedResponse(c, auth.deviceId, true);\n\t\t\tif (limited) return limited;\n\n\t\t\ttry {\n\t\t\t\tif (\n\t\t\t\t\tc.req.header(SYNC_AUTHORIZATION_REFRESH_HEADER) === \"1\" &&\n\t\t\t\t\tsupportsSyncFeature(c.req.header(SYNC_FEATURES_HEADER), \"reassign_scope\")\n\t\t\t\t) {\n\t\t\t\t\t// Project-first provisioning grants at the coordinator immediately before\n\t\t\t\t\t// this status probe. Refresh now so the managed scope can participate in\n\t\t\t\t\t// the same initial sync pass instead of waiting for the daemon interval.\n\t\t\t\t\tawait refreshConfiguredScopeMembershipCache(store.db, undefined, {\n\t\t\t\t\t\tkeysDir: syncKeysDir(),\n\t\t\t\t\t\tdbPath: store.dbPath,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tconst [deviceId, fingerprint] = ensureDeviceIdentity(store.db, {\n\t\t\t\t\tkeysDir: syncKeysDir(),\n\t\t\t\t});\n\t\t\t\tconst syncReset = getSyncResetState(store.db);\n\t\t\t\tconst negotiated = negotiatedSyncCapability(c);\n\t\t\t\tconst authorizedScopes = isScopedSyncCapability(negotiated)\n\t\t\t\t\t? listAuthorizedScopesForPeer(store.db, {\n\t\t\t\t\t\t\tlocalDeviceId: deviceId,\n\t\t\t\t\t\t\tpeerDeviceId: auth.deviceId,\n\t\t\t\t\t\t})\n\t\t\t\t\t: null;\n\t\t\t\tconst response: Record<string, unknown> = {\n\t\t\t\t\tdevice_id: deviceId,\n\t\t\t\t\tprotocol_version: SYNC_PROTOCOL_VERSION,\n\t\t\t\t\tfingerprint,\n\t\t\t\t\truntime_version: VERSION,\n\t\t\t\t\tsync_reset: addSyncScopeToBoundary(syncReset, null),\n\t\t\t\t\tsync_capability: LOCAL_SYNC_CAPABILITY,\n\t\t\t\t\tsync_features: LOCAL_SYNC_FEATURES,\n\t\t\t\t};\n\t\t\t\tif (authorizedScopes !== null) {\n\t\t\t\t\tresponse.authorized_scopes = authorizedScopes;\n\t\t\t\t}\n\t\t\t\treturn c.json(response);\n\t\t\t} catch {\n\t\t\t\treturn c.json({ error: \"internal_error\" }, 500);\n\t\t\t}\n\t\t})();\n\t});\n\n\t// GET /v1/ops (peer sync protocol)\n\tapp.get(\"/v1/ops\", (c) => {\n\t\tconst store = getStore();\n\t\tconst auth = authorizeSyncRequest(store, c.req, Buffer.alloc(0));\n\t\tif (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);\n\t\tif (!auth.ok) {\n\t\t\tlogDirectPeerAuthDiagnostic(auth.reason);\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json(unauthorizedPayload(), 401);\n\t\t}\n\t\tconst limited = rateLimitedResponse(c, auth.deviceId, true);\n\t\tif (limited) return limited;\n\t\tconst peerDeviceId = auth.deviceId;\n\n\t\ttry {\n\t\t\tconst rawScopeId = c.req.query(SYNC_SCOPE_QUERY_PARAM);\n\t\t\tconst negotiated = negotiatedSyncCapability(c);\n\t\t\tconst [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });\n\t\t\tconst scopeRequest = parseSyncScopeRequest(rawScopeId, rawScopeId !== undefined, {\n\t\t\t\tdb: store.db,\n\t\t\t\tlocalDeviceId,\n\t\t\t\tnegotiatedCapability: negotiated,\n\t\t\t\tpeerDeviceId,\n\t\t\t});\n\t\t\tif (!scopeRequest.ok) {\n\t\t\t\treturn c.json(\n\t\t\t\t\tsyncScopeResetRequiredPayload(\n\t\t\t\t\t\tgetSyncResetState(store.db),\n\t\t\t\t\t\tscopeRequest.reason,\n\t\t\t\t\t\tLOCAL_SYNC_CAPABILITY,\n\t\t\t\t\t\tnull,\n\t\t\t\t\t),\n\t\t\t\t\t409,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst since = c.req.query(\"since\") ?? null;\n\t\t\tconst rawLimit = Number.parseInt(c.req.query(\"limit\") ?? \"200\", 10);\n\t\t\tconst rawGeneration = c.req.query(\"generation\");\n\t\t\tconst generation =\n\t\t\t\trawGeneration != null && rawGeneration.trim().length > 0\n\t\t\t\t\t? Number.parseInt(rawGeneration, 10)\n\t\t\t\t\t: null;\n\t\t\tconst snapshotId = c.req.query(\"snapshot_id\") ?? null;\n\t\t\tconst baselineCursor = c.req.query(\"baseline_cursor\") ?? null;\n\t\t\tconst limit = Number.isFinite(rawLimit) ? Math.max(1, Math.min(rawLimit, 1000)) : 200;\n\t\t\tconst result = loadReplicationOpsForPeer(store.db, {\n\t\t\t\tsince,\n\t\t\t\tlimit,\n\t\t\t\tdeviceId: localDeviceId,\n\t\t\t\tgeneration: Number.isFinite(generation) ? generation : null,\n\t\t\t\tsnapshotId,\n\t\t\t\tbaselineCursor,\n\t\t\t\tscopeId: scopeRequest.mode === \"scoped\" ? scopeRequest.scope_id : undefined,\n\t\t\t});\n\t\t\tif (result.reset_required) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"reset_required\",\n\t\t\t\t\t\tsync_capability: LOCAL_SYNC_CAPABILITY,\n\t\t\t\t\t\t...addSyncScopeToBoundary(result.reset, scopeRequest.scope_id),\n\t\t\t\t\t},\n\t\t\t\t\t409,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst { ops, nextCursor, boundary } = result;\n\t\t\tconst filtered = filterOpsForPeer(store, peerDeviceId, localDeviceId, ops, {\n\t\t\t\tsupportsReassignScope: supportsSyncFeature(\n\t\t\t\t\tc.req.header(SYNC_FEATURES_HEADER),\n\t\t\t\t\t\"reassign_scope\",\n\t\t\t\t),\n\t\t\t});\n\t\t\treturn c.json({\n\t\t\t\treset_required: false,\n\t\t\t\tsync_capability: LOCAL_SYNC_CAPABILITY,\n\t\t\t\tscope_id: scopeRequest.scope_id,\n\t\t\t\tgeneration: boundary.generation,\n\t\t\t\tsnapshot_id: boundary.snapshot_id,\n\t\t\t\tbaseline_cursor: boundary.baseline_cursor,\n\t\t\t\tretained_floor_cursor: boundary.retained_floor_cursor,\n\t\t\t\tops: filtered.allowed,\n\t\t\t\tnext_cursor: nextCursor,\n\t\t\t\tskipped: filtered.skipped,\n\t\t\t\tskipped_detail: filtered.skippedDetail,\n\t\t\t});\n\t\t} catch {\n\t\t\treturn c.json({ error: \"internal_error\" }, 500);\n\t\t}\n\t});\n\n\t// GET /v1/snapshot (peer sync protocol — bootstrap snapshot pages)\n\tapp.get(\"/v1/snapshot\", (c) => {\n\t\tconst store = getStore();\n\t\treturn (async () => {\n\t\t\tlet auth = authorizeSyncRequest(store, c.req, Buffer.alloc(0));\n\t\t\tif (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);\n\t\t\tlet preauthChecked = false;\n\t\t\tlet bootstrapAttempted = false;\n\t\t\tlet deviceAuthReason: string | null = null;\n\t\t\tif (!auth.ok) {\n\t\t\t\tconst bootstrapGrantId = (c.req.header(\"X-Codemem-Bootstrap-Grant\") ?? \"\").trim();\n\t\t\t\tif (bootstrapGrantId) {\n\t\t\t\t\tpreauthChecked = true;\n\t\t\t\t\t// Use unauthenticated bucket with stable key — grant is not yet verified,\n\t\t\t\t\t// so caller-controlled headers must not influence rate-limit identity.\n\t\t\t\t\tconst bootstrapLimited = rateLimitedResponse(c, c.req.path, false);\n\t\t\t\t\tif (bootstrapLimited) return bootstrapLimited;\n\t\t\t\t} else {\n\t\t\t\t\tpreauthChecked = true;\n\t\t\t\t\tconst unauthLimited = rateLimitedResponse(c, c.req.path, false);\n\t\t\t\t\tif (unauthLimited) return unauthLimited;\n\t\t\t\t}\n\t\t\t\tdeviceAuthReason = auth.reason;\n\t\t\t\tauth = await authorizeBootstrapGrantRequest(store, c.req, Buffer.alloc(0));\n\t\t\t\tbootstrapAttempted = true;\n\t\t\t}\n\t\t\tif (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);\n\t\t\tif (!auth.ok) {\n\t\t\t\t// Specific reasons stay server-side; wire responses remain generic.\n\t\t\t\tconst grantPresent = Boolean((c.req.header(\"X-Codemem-Bootstrap-Grant\") ?? \"\").trim());\n\t\t\t\t// Warn only when the caller actually attempted authentication (a\n\t\t\t\t// grant or signed device headers); bare probes and health checks\n\t\t\t\t// must not fill logs with attacker-controllable noise.\n\t\t\t\tconst authAttempted =\n\t\t\t\t\tgrantPresent || (deviceAuthReason != null && deviceAuthReason !== \"missing_headers\");\n\t\t\t\tif (bootstrapAttempted && authAttempted) {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`[sync] peer auth failed: reason=${auth.reason} device_auth_reason=${deviceAuthReason ?? \"none\"} grant_present=${grantPresent} path=${c.req.path} device=${loggableHeaderValue(c.req.header(\"X-Opencode-Device\"))}`,\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tlogDirectPeerAuthDiagnostic(deviceAuthReason, auth.reason);\n\t\t\t\t}\n\t\t\t\treturn (\n\t\t\t\t\t(preauthChecked ? null : rateLimitedResponse(c, c.req.path, false)) ??\n\t\t\t\t\tc.json(unauthorizedPayload(), 401)\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst limited = rateLimitedResponse(c, auth.deviceId, true);\n\t\t\tif (limited) return limited;\n\n\t\t\ttry {\n\t\t\t\tconst rawScopeId = c.req.query(SYNC_SCOPE_QUERY_PARAM);\n\t\t\t\tconst negotiated = negotiatedSyncCapability(c);\n\t\t\t\tconst [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });\n\t\t\t\tconst scopeRequest = parseSyncScopeRequest(rawScopeId, rawScopeId !== undefined, {\n\t\t\t\t\tdb: store.db,\n\t\t\t\t\tlocalDeviceId,\n\t\t\t\t\tnegotiatedCapability: negotiated,\n\t\t\t\t\tpeerDeviceId: auth.deviceId,\n\t\t\t\t});\n\t\t\t\tif (!scopeRequest.ok) {\n\t\t\t\t\treturn c.json(\n\t\t\t\t\t\tsyncScopeResetRequiredPayload(\n\t\t\t\t\t\t\tgetSyncResetState(store.db),\n\t\t\t\t\t\t\tscopeRequest.reason,\n\t\t\t\t\t\t\tLOCAL_SYNC_CAPABILITY,\n\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t),\n\t\t\t\t\t\t409,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst rawGeneration = c.req.query(\"generation\");\n\t\t\t\tconst generation =\n\t\t\t\t\trawGeneration != null && rawGeneration.trim().length > 0\n\t\t\t\t\t\t? Number.parseInt(rawGeneration, 10)\n\t\t\t\t\t\t: null;\n\t\t\t\tconst snapshotId = c.req.query(\"snapshot_id\") ?? null;\n\t\t\t\tconst baselineCursor = c.req.query(\"baseline_cursor\") ?? null;\n\t\t\t\tconst pageToken = c.req.query(\"page_token\") ?? null;\n\t\t\t\tconst rawLimit = Number.parseInt(c.req.query(\"limit\") ?? \"200\", 10);\n\t\t\t\t// Cap raised to 5000 to support elevated bootstrap page sizes (default 2000).\n\t\t\t\tconst limit = Number.isFinite(rawLimit) ? Math.max(1, Math.min(rawLimit, 5000)) : 200;\n\n\t\t\t\tif (generation == null || !Number.isFinite(generation)) {\n\t\t\t\t\treturn c.json({ error: \"missing_generation\" }, 400);\n\t\t\t\t}\n\t\t\t\tif (!snapshotId) {\n\t\t\t\t\treturn c.json({ error: \"missing_snapshot_id\" }, 400);\n\t\t\t\t}\n\n\t\t\t\tconst result = loadMemorySnapshotPageForPeer(store.db, {\n\t\t\t\t\tgeneration,\n\t\t\t\t\tsnapshotId,\n\t\t\t\t\tbaselineCursor,\n\t\t\t\t\tpageToken,\n\t\t\t\t\tlimit,\n\t\t\t\t\tpeerDeviceId: auth.deviceId,\n\t\t\t\t\tscopeId: scopeRequest.mode === \"scoped\" ? scopeRequest.scope_id : undefined,\n\t\t\t\t});\n\n\t\t\t\treturn c.json({\n\t\t\t\t\tscope_id: scopeRequest.scope_id,\n\t\t\t\t\tgeneration: result.boundary.generation,\n\t\t\t\t\tsnapshot_id: result.boundary.snapshot_id,\n\t\t\t\t\tbaseline_cursor: result.boundary.baseline_cursor,\n\t\t\t\t\tretained_floor_cursor: result.boundary.retained_floor_cursor,\n\t\t\t\t\tsync_capability: LOCAL_SYNC_CAPABILITY,\n\t\t\t\t\titems: result.items,\n\t\t\t\t\tnext_page_token: result.nextPageToken,\n\t\t\t\t\thas_more: result.hasMore,\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\tconst message = err instanceof Error ? err.message : \"\";\n\t\t\t\tif (message === \"generation_mismatch\" || message === \"boundary_mismatch\") {\n\t\t\t\t\treturn c.json({ error: message }, 409);\n\t\t\t\t}\n\t\t\t\treturn c.json({ error: \"internal_error\" }, 500);\n\t\t\t}\n\t\t})();\n\t});\n\n\t// POST /v1/ops (peer sync protocol)\n\tapp.post(\"/v1/ops\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst raw = await readBoundedRequestBytes(c.req.raw, MAX_SYNC_BODY_BYTES);\n\t\tif (raw == null) {\n\t\t\treturn c.json({ error: \"payload_too_large\" }, 413);\n\t\t}\n\n\t\tconst auth = authorizeSyncRequest(store, c.req, raw);\n\t\tif (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);\n\t\tif (!auth.ok) {\n\t\t\tlogDirectPeerAuthDiagnostic(auth.reason);\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json(unauthorizedPayload(), 401);\n\t\t}\n\t\tconst limited = rateLimitedResponse(c, auth.deviceId, true);\n\t\tif (limited) return limited;\n\t\tconst peerDeviceId = auth.deviceId;\n\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(raw.toString(\"utf-8\")) as unknown;\n\t\t\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n\t\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t\t}\n\t\t\tbody = parsed as Record<string, unknown>;\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst negotiated = negotiateSyncCapability(\n\t\t\tLOCAL_SYNC_CAPABILITY,\n\t\t\tnormalizeSyncCapability(body.sync_capability),\n\t\t);\n\t\tconst [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });\n\t\tconst scopeRequest = parseSyncScopeRequest(body.scope_id, Object.hasOwn(body, \"scope_id\"), {\n\t\t\tdb: store.db,\n\t\t\tlocalDeviceId,\n\t\t\tnegotiatedCapability: negotiated,\n\t\t\tpeerDeviceId,\n\t\t});\n\t\tif (!scopeRequest.ok) {\n\t\t\treturn c.json(\n\t\t\t\tsyncScopeResetRequiredPayload(\n\t\t\t\t\tgetSyncResetState(store.db),\n\t\t\t\t\tscopeRequest.reason,\n\t\t\t\t\tLOCAL_SYNC_CAPABILITY,\n\t\t\t\t\tnull,\n\t\t\t\t),\n\t\t\t\t409,\n\t\t\t);\n\t\t}\n\t\tif (!Array.isArray(body.ops)) {\n\t\t\treturn c.json({ error: \"invalid_ops\" }, 400);\n\t\t}\n\t\tif (body.ops.length > MAX_SYNC_OPS) {\n\t\t\treturn c.json({ error: \"too_many_ops\" }, 413);\n\t\t}\n\n\t\tconst normalizedOps = extractReplicationOps(body);\n\t\tconst peerFeatures = normalizeSyncFeatures(body.sync_features);\n\t\tconst reassignOps = normalizedOps.filter((op) => op.op_type === \"reassign_scope\");\n\t\tif (reassignOps.length > 0 && !peerFeatures.includes(\"reassign_scope\")) {\n\t\t\treturn c.json({ error: \"reassign_capability_required\" }, 409);\n\t\t}\n\t\ttry {\n\t\t\tfor (const op of reassignOps) parseReassignScopePayload(op);\n\t\t} catch {\n\t\t\treturn c.json({ error: \"reassign_payload_invalid\" }, 400);\n\t\t}\n\t\tfor (const op of normalizedOps) {\n\t\t\tif (op.device_id !== peerDeviceId || op.clock_device_id !== peerDeviceId) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"invalid_op_device\",\n\t\t\t\t\t\treason: \"device_id_mismatch\",\n\t\t\t\t\t\top_id: op.op_id,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\t// Inbound POSTs still use legacy visibility/project filters, but must not run\n\t\t// the outbound scope gate. Unsupported peers deliberately bypass strict inbound\n\t\t// scope rejection during rollout, so outbound filtering would silently drop data.\n\t\tconst filtered = filterOpsForPeer(store, peerDeviceId, localDeviceId, normalizedOps, {\n\t\t\tapplyScopeFilter: false,\n\t\t\tsupportsReassignScope: peerFeatures.includes(\"reassign_scope\"),\n\t\t});\n\t\t// Scope validation runs against the full signed batch so bad scoped ops cannot\n\t\t// evade fail-closed rejection by also tripping peer project filters.\n\t\tconst rejected = rejectInboundScopeFailures(store.db, normalizedOps, localDeviceId, {\n\t\t\tenabled: negotiated !== \"unsupported\",\n\t\t\tpeerDeviceId,\n\t\t});\n\t\tif (rejected) {\n\t\t\treturn c.json(\n\t\t\t\t{\n\t\t\t\t\terror: \"scope_rejected\",\n\t\t\t\t\treason: rejected.rejections[0]?.reason ?? \"scope_mismatch\",\n\t\t\t\t\trejections: rejected.rejections,\n\t\t\t\t\tsync_capability: LOCAL_SYNC_CAPABILITY,\n\t\t\t\t\tscope_id: scopeRequest.scope_id,\n\t\t\t\t},\n\t\t\t\t403,\n\t\t\t);\n\t\t}\n\n\t\tconst result = applyReplicationOps(store.db, filtered.allowed, localDeviceId, store.scanner);\n\t\tconst skipped = result.skipped + filtered.skipped;\n\t\treturn c.json({\n\t\t\t...result,\n\t\t\tskipped,\n\t\t\tskipped_detail: filtered.skippedDetail,\n\t\t\tsync_capability: LOCAL_SYNC_CAPABILITY,\n\t\t\tscope_id: scopeRequest.scope_id,\n\t\t});\n\t});\n\n\treturn app;\n}\n\nasync function loadConfiguredDeviceIdentityCoordinatorEvidence(): Promise<DeviceIdentityCoordinatorEvidence> {\n\tconst config = readCoordinatorSyncConfig();\n\tconst hasCoordinatorConfiguration =\n\t\tconfig.syncCoordinatorUrl.length > 0 || config.syncCoordinatorGroups.length > 0;\n\tconst remoteUrl = config.syncCoordinatorUrl.trim();\n\tconst adminSecret = config.syncCoordinatorAdminSecret.trim();\n\tconst groupIds = [\n\t\t...new Set(config.syncCoordinatorGroups.map((groupId) => groupId.trim())),\n\t].filter(Boolean);\n\tif (!hasCoordinatorConfiguration) {\n\t\treturn {\n\t\t\tavailability: \"unavailable\",\n\t\t\tsafeErrorCode: \"coordinator_not_configured\",\n\t\t\tenrollments: [],\n\t\t};\n\t}\n\tif (!remoteUrl || !adminSecret || groupIds.length === 0) {\n\t\treturn {\n\t\t\tavailability: \"unavailable\",\n\t\t\tsafeErrorCode: \"coordinator_unavailable\",\n\t\t\tenrollments: [],\n\t\t};\n\t}\n\tif (groupIds.length > 25) {\n\t\treturn {\n\t\t\tavailability: \"unavailable\",\n\t\t\tsafeErrorCode: \"coordinator_evidence_too_large\",\n\t\t\tenrollments: [],\n\t\t};\n\t}\n\ttry {\n\t\tconst enrollments = (\n\t\t\tawait Promise.all(\n\t\t\t\tgroupIds.map((groupId) =>\n\t\t\t\t\tcoordinatorListDevicesAction({\n\t\t\t\t\t\tgroupId,\n\t\t\t\t\t\tincludeDisabled: true,\n\t\t\t\t\t\tremoteUrl,\n\t\t\t\t\t\tadminSecret,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t)\n\t\t).flat();\n\t\tif (enrollments.length > 500) {\n\t\t\treturn {\n\t\t\t\tavailability: \"unavailable\",\n\t\t\t\tsafeErrorCode: \"coordinator_evidence_too_large\",\n\t\t\t\tenrollments: [],\n\t\t\t};\n\t\t}\n\t\treturn { availability: \"available\", safeErrorCode: null, enrollments };\n\t} catch {\n\t\treturn {\n\t\t\tavailability: \"unavailable\",\n\t\t\tsafeErrorCode: \"coordinator_unavailable\",\n\t\t\tenrollments: [],\n\t\t};\n\t}\n}\n\n/**\n * Viewer-facing sync management routes (/api/sync/*).\n *\n * These are mounted on the viewer listener (127.0.0.1:38888) and\n * provide sync status, peer management, and coordinator UI for the\n * local viewer.\n */\nexport function syncRoutes(\n\tgetStore: StoreFactory,\n\tgetSyncRuntimeStatus?: () => SyncRuntimeStatus | null,\n\toptions: SyncRoutesOptions = {},\n) {\n\tconst app = new Hono();\n\tconst readCoordinatorConfig = options.readCoordinatorConfig ?? readCoordinatorSyncConfig;\n\tconst renameCoordinatorGroup = options.renameCoordinatorGroup ?? coordinatorRenameGroupAction;\n\tconst loadCoordinatorEvidence =\n\t\toptions.loadDeviceIdentityCoordinatorEvidence ??\n\t\tloadConfiguredDeviceIdentityCoordinatorEvidence;\n\tconst currentCoordinatorEvidence = async (): Promise<DeviceIdentityCoordinatorEvidence> => {\n\t\ttry {\n\t\t\treturn await loadCoordinatorEvidence();\n\t\t} catch {\n\t\t\treturn {\n\t\t\t\tavailability: \"unavailable\",\n\t\t\t\tsafeErrorCode: \"coordinator_unavailable\",\n\t\t\t\tenrollments: [],\n\t\t\t};\n\t\t}\n\t};\n\tconst localInventoryInput = async (store: MemoryStore) => {\n\t\tlet explicitDeviceName = \"\";\n\t\ttry {\n\t\t\texplicitDeviceName = String(readCodememConfigFile().sync_device_name ?? \"\");\n\t\t} catch {\n\t\t\texplicitDeviceName = \"\";\n\t\t}\n\t\treturn {\n\t\t\tlocalDeviceId: store.deviceId,\n\t\t\tlocalDisplayName: friendlyDeviceName({\n\t\t\t\texplicitName: explicitDeviceName,\n\t\t\t\tosName: hostname(),\n\t\t\t\tfallbackSeed: store.deviceId,\n\t\t\t}),\n\t\t\tcoordinator: await currentCoordinatorEvidence(),\n\t\t};\n\t};\n\n\tapp.get(\"/api/sync/recipient-policy/v1/device-inventory\", async (c) => {\n\t\tconst store = getStore();\n\t\tensureStableStoreIdentity(store);\n\t\treturn c.json(listDeviceIdentityInventory(store.db, await localInventoryInput(store)));\n\t});\n\n\tapp.patch(\"/api/sync/recipient-policy/v1/teams/:teamId\", async (c) => {\n\t\tconst raw = await readBoundedRequestBytes(c.req.raw, 8_192);\n\t\tif (!raw) return c.json({ error: \"team_name_invalid\" as const }, 400);\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(raw.toString(\"utf8\")) as unknown;\n\t\t\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n\t\t\t\treturn c.json({ error: \"team_name_invalid\" as const }, 400);\n\t\t\t}\n\t\t\tbody = parsed as Record<string, unknown>;\n\t\t} catch {\n\t\t\treturn c.json({ error: \"team_name_invalid\" as const }, 400);\n\t\t}\n\t\tif (\n\t\t\tObject.keys(body).length !== 2 ||\n\t\t\t!Object.hasOwn(body, \"displayName\") ||\n\t\t\t!Object.hasOwn(body, \"expectedDisplayName\") ||\n\t\t\ttypeof body.displayName !== \"string\" ||\n\t\t\ttypeof body.expectedDisplayName !== \"string\"\n\t\t) {\n\t\t\treturn c.json({ error: \"team_name_invalid\" as const }, 400);\n\t\t}\n\t\ttry {\n\t\t\tconst store = getStore();\n\t\t\tconst config = readCoordinatorConfig();\n\t\t\tconst coordinatorId = config.syncCoordinatorUrl\n\t\t\t\t? buildBaseUrl(config.syncCoordinatorUrl)\n\t\t\t\t: null;\n\t\t\tconst normalizedConfiguredCoordinatorId = coordinatorId\n\t\t\t\t? normalizedCoordinatorId(coordinatorId)\n\t\t\t\t: null;\n\t\t\tlet configuredCoordinatorGroups: ReturnType<typeof legacyTeamCandidateGroupDescriptors> = [];\n\t\t\tif (coordinatorId) {\n\t\t\t\ttry {\n\t\t\t\t\t// Scope-backed descriptors widen rename eligibility only when\n\t\t\t\t\t// linkedGroup() also proves exact completed-setup history.\n\t\t\t\t\tconfiguredCoordinatorGroups = legacyTeamCandidateGroupDescriptors(\n\t\t\t\t\t\tstore,\n\t\t\t\t\t\tconfig.syncCoordinatorUrl,\n\t\t\t\t\t\tconfig.syncCoordinatorGroups,\n\t\t\t\t\t);\n\t\t\t\t} catch {\n\t\t\t\t\t// Bad coordinator evidence must not block a local-only rename.\n\t\t\t\t\t// Proven linked Teams still fail closed as team_link_stale.\n\t\t\t\t\tconfiguredCoordinatorGroups = [];\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst result = await renameRecipientPolicyTeam(store.db, {\n\t\t\t\tteamId: c.req.param(\"teamId\"),\n\t\t\t\tdisplayName: body.displayName,\n\t\t\t\texpectedDisplayName: body.expectedDisplayName,\n\t\t\t\tconfiguredCoordinatorGroups,\n\t\t\t\tcoordinatorIdsEquivalent: (left, right) => {\n\t\t\t\t\tconst normalizedLeft = normalizedCoordinatorId(left);\n\t\t\t\t\tconst normalizedRight = normalizedCoordinatorId(right);\n\t\t\t\t\treturn normalizedLeft !== null && normalizedLeft === normalizedRight;\n\t\t\t\t},\n\t\t\t\trenameCoordinatorGroup: async (group, normalizedDisplayName) => {\n\t\t\t\t\tconst normalizedLinkedCoordinatorId = normalizedCoordinatorId(group.coordinatorId);\n\t\t\t\t\tif (\n\t\t\t\t\t\t!config.syncCoordinatorUrl ||\n\t\t\t\t\t\t!config.syncCoordinatorAdminSecret ||\n\t\t\t\t\t\t!normalizedConfiguredCoordinatorId ||\n\t\t\t\t\t\t!normalizedLinkedCoordinatorId ||\n\t\t\t\t\t\tnormalizedLinkedCoordinatorId !== normalizedConfiguredCoordinatorId\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tconst renamed = await renameCoordinatorGroup({\n\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\tdisplayName: normalizedDisplayName,\n\t\t\t\t\t\tremoteUrl: config.syncCoordinatorUrl,\n\t\t\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret,\n\t\t\t\t\t});\n\t\t\t\t\treturn (\n\t\t\t\t\t\trenamed?.group_id === group.groupId && renamed.display_name === normalizedDisplayName\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t});\n\t\t\ttry {\n\t\t\t\toptions.onRecipientPolicyTeamRenamed?.();\n\t\t\t} catch {\n\t\t\t\t// Cache invalidation is best-effort after the authoritative rename commits.\n\t\t\t}\n\t\t\treturn c.json(result);\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof RecipientPolicyTeamRenameError)) {\n\t\t\t\treturn c.json({ error: \"team_rename_failed\" as const }, 503);\n\t\t\t}\n\t\t\tconst status =\n\t\t\t\terror.code === \"team_name_invalid\"\n\t\t\t\t\t? 400\n\t\t\t\t\t: error.code === \"team_not_found\"\n\t\t\t\t\t\t? 404\n\t\t\t\t\t\t: error.code === \"team_coordinator_rename_failed\" ||\n\t\t\t\t\t\t\t\terror.code === \"team_local_rename_pending\" ||\n\t\t\t\t\t\t\t\terror.code === \"team_rename_failed\"\n\t\t\t\t\t\t\t? 503\n\t\t\t\t\t\t\t: 409;\n\t\t\treturn c.json({ error: error.code }, status);\n\t\t}\n\t});\n\n\tconst parseDeviceBindingRequest = (\n\t\tvalue: unknown,\n\t\tcommit: boolean,\n\t): DeviceIdentityBindingPreviewRequestV1 | DeviceIdentityBindingCommitRequestV1 | null => {\n\t\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n\t\tconst body = value as Record<string, unknown>;\n\t\tconst allowed = new Set(commit ? [\"bindings\", \"reviewedInventoryDigest\"] : [\"bindings\"]);\n\t\tif (Object.keys(body).some((key) => !allowed.has(key)) || !Array.isArray(body.bindings)) {\n\t\t\treturn null;\n\t\t}\n\t\tconst bindings = body.bindings.map((value) => {\n\t\t\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n\t\t\tconst binding = value as Record<string, unknown>;\n\t\t\tconst bindingKeys = new Set([\"deviceId\", \"targetIdentityId\", \"confirmed\", \"allowRebind\"]);\n\t\t\tif (\n\t\t\t\tObject.keys(binding).some((key) => !bindingKeys.has(key)) ||\n\t\t\t\ttypeof binding.deviceId !== \"string\" ||\n\t\t\t\ttypeof binding.targetIdentityId !== \"string\" ||\n\t\t\t\ttypeof binding.confirmed !== \"boolean\" ||\n\t\t\t\t(Object.hasOwn(binding, \"allowRebind\") && typeof binding.allowRebind !== \"boolean\")\n\t\t\t) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tdeviceId: binding.deviceId,\n\t\t\t\ttargetIdentityId: binding.targetIdentityId,\n\t\t\t\tconfirmed: binding.confirmed,\n\t\t\t\t...(typeof binding.allowRebind === \"boolean\" ? { allowRebind: binding.allowRebind } : {}),\n\t\t\t};\n\t\t});\n\t\tif (bindings.some((binding) => binding == null)) return null;\n\t\tif (commit && typeof body.reviewedInventoryDigest !== \"string\") return null;\n\t\treturn {\n\t\t\tbindings: bindings as DeviceIdentityBindingPreviewRequestV1[\"bindings\"],\n\t\t\t...(commit ? { reviewedInventoryDigest: body.reviewedInventoryDigest as string } : {}),\n\t\t};\n\t};\n\n\tapp.post(\"/api/sync/recipient-policy/v1/device-bindings/preview\", async (c) => {\n\t\tconst body = parseDeviceBindingRequest(await parseViewerJsonBody(c), false);\n\t\tif (!body) return c.json({ error: \"binding_request_invalid\" }, 400);\n\t\tconst store = getStore();\n\t\ttry {\n\t\t\tensureStableStoreIdentity(store);\n\t\t\tconst result = previewDeviceIdentityBindings(\n\t\t\t\tstore.db,\n\t\t\t\tawait localInventoryInput(store),\n\t\t\t\tbody,\n\t\t\t);\n\t\t\tif (result.status === \"invalid\") return c.json(result, 400);\n\t\t\tif (result.status === \"not_found\") return c.json(result, 404);\n\t\t\tif (result.status === \"conflict\") return c.json(result, 409);\n\t\t\treturn c.json(result);\n\t\t} catch (error) {\n\t\t\tif (isSqliteBusy(error)) {\n\t\t\t\tc.header(\"Retry-After\", \"1\");\n\t\t\t\treturn c.json({ error: \"binding_preview_busy\" }, 503);\n\t\t\t}\n\t\t\treturn c.json({ error: \"binding_preview_failed\" }, 500);\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/recipient-policy/v1/device-bindings/commit\", async (c) => {\n\t\tconst body = parseDeviceBindingRequest(await parseViewerJsonBody(c), true);\n\t\tif (!body || !(\"reviewedInventoryDigest\" in body)) {\n\t\t\treturn c.json({ error: \"binding_request_invalid\" }, 400);\n\t\t}\n\t\tconst store = getStore();\n\t\tlet releasePublicationMutation: (() => void) | undefined;\n\t\ttry {\n\t\t\treleasePublicationMutation = await claimRecipientPolicyPublicationMutation(store.db);\n\t\t\tensureStableStoreIdentity(store);\n\t\t\tconst result = commitDeviceIdentityBindings(\n\t\t\t\tstore.db,\n\t\t\t\t{ localActorId: store.actorId, localDeviceId: store.deviceId },\n\t\t\t\tawait localInventoryInput(store),\n\t\t\t\tbody,\n\t\t\t);\n\t\t\tif (result.status === \"invalid\") return c.json(result, 400);\n\t\t\tif (result.status === \"not_found\") return c.json(result, 404);\n\t\t\tif (result.status === \"stale\" || result.status === \"conflict\") {\n\t\t\t\treturn c.json(result, 409);\n\t\t\t}\n\t\t\treturn c.json(result);\n\t\t} catch (error) {\n\t\t\tif (isSqliteBusy(error)) {\n\t\t\t\tc.header(\"Retry-After\", \"1\");\n\t\t\t\treturn c.json({ error: \"binding_commit_busy\" }, 503);\n\t\t\t}\n\t\t\treturn c.json({ error: \"binding_commit_failed\" }, 500);\n\t\t} finally {\n\t\t\treleasePublicationMutation?.();\n\t\t}\n\t});\n\n\t// GET /api/sync/status\n\tapp.get(\"/api/sync/status\", async (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tconst traceSync = <T>(label: string, fn: () => T): T => {\n\t\t\t\tif (process.env.CODEMEM_TRACE_SYNC_STATUS !== \"1\") return fn();\n\t\t\t\tconst startedAt = Date.now();\n\t\t\t\tconsole.warn(`[codemem sync-status] ${label} start`);\n\t\t\t\ttry {\n\t\t\t\t\treturn fn();\n\t\t\t\t} finally {\n\t\t\t\t\tconsole.warn(`[codemem sync-status] ${label} ${Date.now() - startedAt}ms`);\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst showDiag = queryBool(c.req.query(\"includeDiagnostics\"));\n\t\t\tconst includeJoinRequests = queryBool(c.req.query(\"includeJoinRequests\"));\n\t\t\tconst project = c.req.query(\"project\") || null;\n\t\t\tconst config = traceSync(\"readCoordinatorSyncConfig\", () => readCoordinatorSyncConfig());\n\t\t\tconst syncReset = traceSync(\"getSyncResetState\", () => getSyncResetState(store.db));\n\n\t\t\tconst d = drizzle(store.db, { schema });\n\n\t\t\tconst deviceRow = traceSync(\"deviceRow\", () =>\n\t\t\t\td\n\t\t\t\t\t.select({\n\t\t\t\t\t\tdevice_id: schema.syncDevice.device_id,\n\t\t\t\t\t\tfingerprint: schema.syncDevice.fingerprint,\n\t\t\t\t\t})\n\t\t\t\t\t.from(schema.syncDevice)\n\t\t\t\t\t.limit(1)\n\t\t\t\t\t.get(),\n\t\t\t);\n\n\t\t\tconst daemonState = traceSync(\"daemonState\", () =>\n\t\t\t\td.select().from(schema.syncDaemonState).where(eq(schema.syncDaemonState.id, 1)).get(),\n\t\t\t);\n\n\t\t\tconst peerCountRow = traceSync(\"peerCountRow\", () =>\n\t\t\t\td.select({ total: count() }).from(schema.syncPeers).get(),\n\t\t\t);\n\t\t\tlet retentionState:\n\t\t\t\t| {\n\t\t\t\t\t\tlast_run_at?: string | null;\n\t\t\t\t\t\tlast_duration_ms?: number | null;\n\t\t\t\t\t\tlast_deleted_ops?: number | null;\n\t\t\t\t\t\tlast_estimated_bytes_before?: number | null;\n\t\t\t\t\t\tlast_estimated_bytes_after?: number | null;\n\t\t\t\t\t\tretained_floor_cursor?: string | null;\n\t\t\t\t\t\tlast_error?: string | null;\n\t\t\t\t\t\tlast_error_at?: string | null;\n\t\t\t\t }\n\t\t\t\t| undefined;\n\t\t\ttry {\n\t\t\t\tretentionState = traceSync(\"retentionState\", () =>\n\t\t\t\t\td\n\t\t\t\t\t\t.select()\n\t\t\t\t\t\t.from(schema.syncRetentionState)\n\t\t\t\t\t\t.where(eq(schema.syncRetentionState.id, 1))\n\t\t\t\t\t\t.get(),\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\tretentionState = undefined;\n\t\t\t}\n\n\t\t\tconst lastSyncRow = traceSync(\"lastSyncRow\", () =>\n\t\t\t\td\n\t\t\t\t\t.select({ last_sync_at: max(schema.syncPeers.last_sync_at) })\n\t\t\t\t\t.from(schema.syncPeers)\n\t\t\t\t\t.get(),\n\t\t\t);\n\t\t\t// Always take the fast COUNT(DISTINCT) path. The slow\n\t\t\t// per-memory vec0 probe blocks the event loop for seconds on\n\t\t\t// larger DBs, which hangs every concurrent request — not\n\t\t\t// acceptable from a status endpoint. See codemem-00jn.\n\t\t\tconst semanticIndex = traceSync(\"semanticIndex\", () =>\n\t\t\t\tredactSemanticIndexDiagnostics(getSemanticIndexDiagnostics(store.db), showDiag),\n\t\t\t);\n\t\t\tconst enrollmentIssueSummary = traceSync(\"coordinatorEnrollmentIssues\", () =>\n\t\t\t\tgetCoordinatorEnrollmentReconciliationIssueSummary(store.db),\n\t\t\t);\n\t\t\tconst enrollmentIssueStatus = {\n\t\t\t\tcounts: enrollmentIssueSummary.counts,\n\t\t\t\t...(showDiag\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tissues: enrollmentIssueSummary.issues.map((issue) => ({\n\t\t\t\t\t\t\t\tcoordinator_id: issue.coordinatorId,\n\t\t\t\t\t\t\t\tgroup_id: issue.groupId,\n\t\t\t\t\t\t\t\tkind: issue.kind,\n\t\t\t\t\t\t\t\treference_id: issue.referenceId,\n\t\t\t\t\t\t\t\tcode: issue.code,\n\t\t\t\t\t\t\t\tstatus: issue.status,\n\t\t\t\t\t\t\t\tfirst_seen_at: issue.firstSeenAt,\n\t\t\t\t\t\t\t\tlast_seen_at: issue.lastSeenAt,\n\t\t\t\t\t\t\t\tresolved_at: issue.resolvedAt,\n\t\t\t\t\t\t\t\toccurrence_count: issue.occurrenceCount,\n\t\t\t\t\t\t\t\tupdated_at: issue.updatedAt,\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t};\n\n\t\t\tconst lastError = daemonState?.last_error as string | null;\n\t\t\tconst lastErrorAt = daemonState?.last_error_at as string | null;\n\t\t\tconst lastOkAt = daemonState?.last_ok_at as string | null;\n\t\t\tconst viewerBinding = traceSync(\"readViewerBinding\", () => readViewerBinding(store.dbPath));\n\t\t\t// The sync daemon runs inside the viewer-server process itself, so\n\t\t\t// if this request is being served, the daemon is by definition\n\t\t\t// running — the viewer is serving us right now. The prior\n\t\t\t// `portOpen` self-probe occasionally timed out under GC / socket\n\t\t\t// backlog pressure and mis-reported \"stopped · unreachable\" while\n\t\t\t// every other request kept succeeding. Trust the pidfile's\n\t\t\t// existence (a record was written at startup) and skip the loopback\n\t\t\t// probe.\n\t\t\tconst daemonRunning = Boolean(viewerBinding);\n\t\t\tconst daemonDetail = viewerBinding\n\t\t\t\t? `viewer pidfile at ${viewerBinding.host}:${viewerBinding.port}`\n\t\t\t\t: null;\n\n\t\t\tlet daemonStateValue = \"ok\";\n\t\t\tif (!config.syncEnabled) {\n\t\t\t\tdaemonStateValue = \"disabled\";\n\t\t\t} else if (lastError && (!lastOkAt || String(lastOkAt) < String(lastErrorAt ?? \"\"))) {\n\t\t\t\tdaemonStateValue = \"error\";\n\t\t\t} else if (!daemonRunning) {\n\t\t\t\tdaemonStateValue = \"stopped\";\n\t\t\t}\n\n\t\t\tconst statusPayload: Record<string, unknown> = {\n\t\t\t\tenabled: config.syncEnabled,\n\t\t\t\tinterval_s: config.syncIntervalS,\n\t\t\t\tretention: {\n\t\t\t\t\tenabled: config.syncRetentionEnabled,\n\t\t\t\t\tmax_age_days: config.syncRetentionMaxAgeDays,\n\t\t\t\t\tmax_size_mb: config.syncRetentionMaxSizeMb,\n\t\t\t\t\tretained_floor_cursor:\n\t\t\t\t\t\tsyncReset.retained_floor_cursor ??\n\t\t\t\t\t\t(retentionState?.retained_floor_cursor as string | null) ??\n\t\t\t\t\t\tnull,\n\t\t\t\t\tlast_run_at: (retentionState?.last_run_at as string | null) ?? null,\n\t\t\t\t\tlast_duration_ms:\n\t\t\t\t\t\ttypeof retentionState?.last_duration_ms === \"number\"\n\t\t\t\t\t\t\t? retentionState.last_duration_ms\n\t\t\t\t\t\t\t: null,\n\t\t\t\t\tlast_deleted_ops:\n\t\t\t\t\t\ttypeof retentionState?.last_deleted_ops === \"number\"\n\t\t\t\t\t\t\t? retentionState.last_deleted_ops\n\t\t\t\t\t\t\t: null,\n\t\t\t\t\tlast_estimated_bytes_before:\n\t\t\t\t\t\ttypeof retentionState?.last_estimated_bytes_before === \"number\"\n\t\t\t\t\t\t\t? retentionState.last_estimated_bytes_before\n\t\t\t\t\t\t\t: null,\n\t\t\t\t\tlast_estimated_bytes_after:\n\t\t\t\t\t\ttypeof retentionState?.last_estimated_bytes_after === \"number\"\n\t\t\t\t\t\t\t? retentionState.last_estimated_bytes_after\n\t\t\t\t\t\t\t: null,\n\t\t\t\t\tlast_error: (retentionState?.last_error as string | null) ?? null,\n\t\t\t\t\tlast_error_at: (retentionState?.last_error_at as string | null) ?? null,\n\t\t\t\t},\n\t\t\t\tsemantic_index: semanticIndex,\n\t\t\t\tcoordinator_enrollment_reconciliation_issues: enrollmentIssueStatus,\n\t\t\t\tpeer_count: Number(peerCountRow?.total ?? 0),\n\t\t\t\tlast_sync_at: lastSyncRow?.last_sync_at ?? null,\n\t\t\t\tdaemon_state: daemonStateValue,\n\t\t\t\tdaemon_running: daemonRunning,\n\t\t\t\tdaemon_detail: daemonDetail,\n\t\t\t\tproject_filter_active:\n\t\t\t\t\tconfig.syncProjectsInclude.length > 0 || config.syncProjectsExclude.length > 0,\n\t\t\t\tproject_filter: {\n\t\t\t\t\tinclude: config.syncProjectsInclude,\n\t\t\t\t\texclude: config.syncProjectsExclude,\n\t\t\t\t},\n\t\t\t\tcleanup_diagnostics: cleanupDiagnostics(\n\t\t\t\t\tstore,\n\t\t\t\t\t(deviceRow?.device_id as string | null | undefined) ?? null,\n\t\t\t\t\tshowDiag,\n\t\t\t\t),\n\t\t\t\tredacted: !showDiag,\n\t\t\t};\n\n\t\t\tif (showDiag) {\n\t\t\t\tstatusPayload.device_id = deviceRow?.device_id ?? null;\n\t\t\t\tstatusPayload.fingerprint = deviceRow?.fingerprint ?? null;\n\t\t\t\tstatusPayload.bind = `${config.syncHost}:${config.syncPort}`;\n\t\t\t\tstatusPayload.daemon_last_error = lastError;\n\t\t\t\tstatusPayload.daemon_last_error_at = lastErrorAt;\n\t\t\t\tstatusPayload.daemon_last_ok_at = lastOkAt;\n\t\t\t}\n\n\t\t\tconst runtimeStatus = getSyncRuntimeStatus?.() ?? null;\n\t\t\tif (runtimeStatus?.phase && runtimeStatus.phase !== \"running\") {\n\t\t\t\tdaemonStateValue = runtimeStatus.phase;\n\t\t\t\tstatusPayload.daemon_state = daemonStateValue;\n\t\t\t\tstatusPayload.daemon_running = runtimeStatus.phase === \"starting\" || daemonRunning;\n\t\t\t\tstatusPayload.daemon_detail = runtimeStatus.detail ?? daemonDetail;\n\t\t\t}\n\n\t\t\tconst coordinatorSnapshot = await coordinatorStatusSnapshot(store, config);\n\t\t\tconst coordinator = traceSync(\"coordinator\", () =>\n\t\t\t\tredactCoordinatorStatus(coordinatorSnapshot, showDiag),\n\t\t\t);\n\n\t\t\t// Build peers list using deduplicated mapPeerRow\n\t\t\tconst peerRows = traceSync(\n\t\t\t\t\"peerRows\",\n\t\t\t\t() => store.db.prepare(PEERS_QUERY).all() as Record<string, unknown>[],\n\t\t\t);\n\t\t\tconst recentOpsByPeer = traceSync(\"recentPeerOps\", () => recentPeerOps(store));\n\t\t\tconst scopeRejectionsByPeer = traceSync(\"recentScopeRejectionsByPeer\", () =>\n\t\t\t\trecentScopeRejectionsByPeer(store),\n\t\t\t);\n\t\t\tconst peersItems = peerRows.map((row) => {\n\t\t\t\tconst peer = mapPeerRow(\n\t\t\t\t\tstore,\n\t\t\t\t\trow,\n\t\t\t\t\tshowDiag,\n\t\t\t\t\trecentOpsByPeer,\n\t\t\t\t\tscopeRejectionsByPeer,\n\t\t\t\t\t(deviceRow?.device_id as string | null | undefined) ?? null,\n\t\t\t\t);\n\t\t\t\tpeer.status = peerStatus(peer);\n\t\t\t\treturn peer;\n\t\t\t});\n\n\t\t\tconst peersMap: Record<string, unknown> = {};\n\t\t\tfor (const peer of peersItems) {\n\t\t\t\tpeersMap[String(peer.peer_device_id)] = peer.status;\n\t\t\t}\n\n\t\t\t// Attempts\n\t\t\tconst attemptRows = traceSync(\"attemptRows\", () =>\n\t\t\t\td\n\t\t\t\t\t.select({\n\t\t\t\t\t\tpeer_device_id: schema.syncAttempts.peer_device_id,\n\t\t\t\t\t\tok: schema.syncAttempts.ok,\n\t\t\t\t\t\terror: schema.syncAttempts.error,\n\t\t\t\t\t\tstarted_at: schema.syncAttempts.started_at,\n\t\t\t\t\t\tfinished_at: schema.syncAttempts.finished_at,\n\t\t\t\t\t\tops_in: schema.syncAttempts.ops_in,\n\t\t\t\t\t\tops_out: schema.syncAttempts.ops_out,\n\t\t\t\t\t\tlocal_sync_capability: schema.syncAttempts.local_sync_capability,\n\t\t\t\t\t\tpeer_sync_capability: schema.syncAttempts.peer_sync_capability,\n\t\t\t\t\t\tnegotiated_sync_capability: schema.syncAttempts.negotiated_sync_capability,\n\t\t\t\t\t})\n\t\t\t\t\t.from(schema.syncAttempts)\n\t\t\t\t\t.orderBy(desc(schema.syncAttempts.finished_at))\n\t\t\t\t\t.limit(25)\n\t\t\t\t\t.all(),\n\t\t\t);\n\t\t\tconst peerAddressMap = new Map<string, string[]>();\n\t\t\tconst peerAddressRows = traceSync(\n\t\t\t\t\"peerAddressRows\",\n\t\t\t\t() =>\n\t\t\t\t\tstore.db.prepare(\"SELECT peer_device_id, addresses_json FROM sync_peers\").all() as Array<{\n\t\t\t\t\t\tpeer_device_id: string | null;\n\t\t\t\t\t\taddresses_json: string | null;\n\t\t\t\t\t}>,\n\t\t\t);\n\t\t\tpeerAddressRows.forEach((peerRow) => {\n\t\t\t\tconst addrs = safeJsonList(peerRow.addresses_json as string | null);\n\t\t\t\tif (addrs.length) peerAddressMap.set(String(peerRow.peer_device_id ?? \"\"), addrs);\n\t\t\t});\n\t\t\tconst attemptsItems = attemptRows.map((row) => {\n\t\t\t\tconst addrs = showDiag ? peerAddressMap.get(String(row.peer_device_id ?? \"\")) : undefined;\n\t\t\t\treturn mapSyncAttemptRow(row, showDiag, addrs);\n\t\t\t});\n\t\t\tconst latestAttemptError = String(attemptRows[0]?.error || \"\").trim();\n\n\t\t\tconst statusBlock: Record<string, unknown> = {\n\t\t\t\t...statusPayload,\n\t\t\t\tbackground_maintenance: summarizeMaintenanceJobs(listMaintenanceJobs(store.db), showDiag),\n\t\t\t\tpeers: peersMap,\n\t\t\t\tpending: 0,\n\t\t\t\tsync: {},\n\t\t\t\tping: {},\n\t\t\t};\n\t\t\tconst legacyDevices = traceSync(\"legacyDevices\", () => store.claimableLegacyDeviceIds());\n\t\t\tconst legacyReview = traceSync(\"legacySharedReview\", () => legacySharedReviewSummary(store));\n\t\t\tconst sharingReview = traceSync(\"sharingReview\", () => store.sharingReviewSummary(project));\n\t\t\tconst recipientPolicyReconciliation = traceSync(\"recipientPolicyReconciliation\", () =>\n\t\t\t\tlistRecipientPolicyReconciliationStatus(store),\n\t\t\t);\n\t\t\tlet joinRequests: Record<string, unknown>[] = [];\n\t\t\tif (includeJoinRequests && showDiag && config.syncCoordinatorAdminSecret) {\n\t\t\t\ttry {\n\t\t\t\t\tjoinRequests = await listCoordinatorJoinRequests(config);\n\t\t\t\t} catch {\n\t\t\t\t\tjoinRequests = [];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (daemonStateValue === \"ok\" && latestAttemptError.startsWith(\"needs_attention:\")) {\n\t\t\t\tdaemonStateValue = \"needs_attention\";\n\t\t\t\tstatusPayload.daemon_state = daemonStateValue;\n\t\t\t\tstatusPayload.daemon_detail = latestAttemptError.replace(/^needs_attention:/, \"\");\n\t\t\t\tstatusBlock.daemon_state = daemonStateValue;\n\t\t\t\tstatusBlock.daemon_detail = latestAttemptError.replace(/^needs_attention:/, \"\");\n\t\t\t}\n\n\t\t\tif (daemonStateValue === \"ok\") {\n\t\t\t\tconst peerStates = new Set(\n\t\t\t\t\tpeersItems.map((peer) =>\n\t\t\t\t\t\tString((peer.status as Record<string, unknown> | undefined)?.peer_state ?? \"\"),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tconst latestFailedRecently = Boolean(\n\t\t\t\t\tattemptsItems[0] &&\n\t\t\t\t\t\tattemptsItems[0].status === \"error\" &&\n\t\t\t\t\t\tisRecentIso(attemptsItems[0].finished_at),\n\t\t\t\t);\n\t\t\t\tconst allOffline =\n\t\t\t\t\tpeersItems.length > 0 &&\n\t\t\t\t\tpeersItems.every(\n\t\t\t\t\t\t(peer) =>\n\t\t\t\t\t\t\tString((peer.status as Record<string, unknown>)?.peer_state ?? \"\") === \"offline\",\n\t\t\t\t\t);\n\t\t\t\tif (latestFailedRecently) {\n\t\t\t\t\tconst hasLivePeer = peerStates.has(\"online\") || peerStates.has(\"degraded\");\n\t\t\t\t\tif (hasLivePeer) daemonStateValue = \"degraded\";\n\t\t\t\t\telse if (allOffline) daemonStateValue = \"offline-peers\";\n\t\t\t\t\telse if (peersItems.length > 0) daemonStateValue = \"stale\";\n\t\t\t\t} else if (peerStates.has(\"degraded\")) {\n\t\t\t\t\tdaemonStateValue = \"degraded\";\n\t\t\t\t} else if (allOffline) {\n\t\t\t\t\tdaemonStateValue = \"offline-peers\";\n\t\t\t\t} else if (peersItems.length > 0 && !peerStates.has(\"online\")) {\n\t\t\t\t\tdaemonStateValue = \"stale\";\n\t\t\t\t}\n\t\t\t\tstatusPayload.daemon_state = daemonStateValue;\n\t\t\t\tstatusBlock.daemon_state = daemonStateValue;\n\t\t\t}\n\n\t\t\tconst responsePayload: Record<string, unknown> = {\n\t\t\t\t...statusPayload,\n\t\t\t\tstatus: statusBlock,\n\t\t\t\tpeers: peersItems,\n\t\t\t\tattempts: attemptsItems.slice(0, 5),\n\t\t\t\tlegacy_devices: legacyDevices,\n\t\t\t\tlegacy_shared_review: legacyReview,\n\t\t\t\tsharing_review: sharingReview,\n\t\t\t\trecipient_policy_reconciliation: recipientPolicyReconciliation,\n\t\t\t\tcoordinator,\n\t\t\t};\n\t\t\tif (includeJoinRequests && showDiag) {\n\t\t\t\tresponsePayload.join_requests = joinRequests;\n\t\t\t}\n\t\t\treturn c.json(responsePayload);\n\t\t}\n\t});\n\n\t// GET /api/sync/peers\n\tapp.get(\"/api/sync/peers\", (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tconst showDiag = queryBool(c.req.query(\"includeDiagnostics\"));\n\t\t\tconst rows = store.db.prepare(PEERS_QUERY).all() as Record<string, unknown>[];\n\t\t\tconst recentOpsByPeer = recentPeerOps(store);\n\t\t\tconst scopeRejectionsByPeer = recentScopeRejectionsByPeer(store);\n\t\t\tconst d = drizzle(store.db, { schema });\n\t\t\tconst deviceRow = d\n\t\t\t\t.select({ device_id: schema.syncDevice.device_id })\n\t\t\t\t.from(schema.syncDevice)\n\t\t\t\t.limit(1)\n\t\t\t\t.get();\n\t\t\tconst localDeviceId = (deviceRow?.device_id as string | null | undefined) ?? null;\n\t\t\t// Use deduplicated mapPeerRow helper (fix #4)\n\t\t\tconst peers = rows.map((row) =>\n\t\t\t\tmapPeerRow(store, row, showDiag, recentOpsByPeer, scopeRejectionsByPeer, localDeviceId),\n\t\t\t);\n\t\t\treturn c.json({ items: peers, redacted: !showDiag });\n\t\t}\n\t});\n\n\t// GET /api/sync/peers/:peer_device_id/scope-rejections\n\t//\n\t// Recent scope-rejection records produced by the inbound fail-closed gate.\n\t// Each row is metadata only — op id, entity ref, scope id, reason code,\n\t// timestamp. The rejection log never stores op payloads, so this endpoint\n\t// can never leak inbound payload contents regardless of diagnostics state.\n\tapp.get(\"/api/sync/peers/:peer_device_id/scope-rejections\", (c) => {\n\t\tconst store = getStore();\n\t\tconst peerDeviceId = String(c.req.param(\"peer_device_id\") || \"\").trim();\n\t\tif (!peerDeviceId) return c.json({ error: \"missing_peer_device_id\" }, 400);\n\t\tconst limit = queryInt(c.req.query(\"limit\"), 100);\n\t\tif (limit <= 0) return c.json({ error: \"invalid_limit\" }, 400);\n\t\tconst sinceMinutesRaw = queryInt(c.req.query(\"sinceMinutes\"), 24 * 60);\n\t\t// Cap at ~10 years so a hostile or fat-fingered query cannot push the\n\t\t// computed timestamp past the Date range and turn toISOString() into\n\t\t// a 500. Anything older than 10 years is effectively \"all rejections\".\n\t\tconst SINCE_MINUTES_MAX = 10 * 365 * 24 * 60;\n\t\tconst sinceMinutes = Math.min(Math.max(sinceMinutesRaw, 0), SINCE_MINUTES_MAX);\n\t\tconst sinceIso =\n\t\t\tsinceMinutes > 0 ? new Date(Date.now() - sinceMinutes * 60_000).toISOString() : undefined;\n\t\tconst records = listInboundScopeRejections(store.db, {\n\t\t\tpeerDeviceId,\n\t\t\tsinceIso,\n\t\t\tlimit,\n\t\t});\n\t\tconst summaries = summarizeInboundScopeRejections(store.db, {\n\t\t\tpeerDeviceId,\n\t\t\tsinceIso,\n\t\t});\n\t\tconst summary = summaries[0] ?? {\n\t\t\tpeer_device_id: peerDeviceId,\n\t\t\ttotal: 0,\n\t\t\tby_reason: {},\n\t\t\tlast_at: null,\n\t\t};\n\t\treturn c.json({\n\t\t\tpeer_device_id: peerDeviceId,\n\t\t\tsummary,\n\t\t\titems: records,\n\t\t});\n\t});\n\n\t// GET /api/sync/actors\n\tapp.get(\"/api/sync/actors\", (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tensureLocalActorRecord(store);\n\t\t\tconst d = drizzle(store.db, { schema });\n\t\t\tconst includeMerged = queryBool(c.req.query(\"includeMerged\"));\n\t\t\tconst query = d.select().from(schema.actors);\n\t\t\tconst rows = includeMerged\n\t\t\t\t? query.orderBy(schema.actors.display_name).all()\n\t\t\t\t: query\n\t\t\t\t\t\t.where(and(ne(schema.actors.status, \"merged\"), ne(schema.actors.status, \"deactivated\")))\n\t\t\t\t\t\t.orderBy(schema.actors.display_name)\n\t\t\t\t\t\t.all();\n\t\t\treturn c.json({ items: rows });\n\t\t}\n\t});\n\n\t// GET /api/sync/attempts\n\tapp.get(\"/api/sync/attempts\", (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tconst d = drizzle(store.db, { schema });\n\t\t\tlet limit = queryInt(c.req.query(\"limit\"), 25);\n\t\t\tif (limit <= 0) return c.json({ error: \"invalid_limit\" }, 400);\n\t\t\tlimit = Math.min(limit, 500);\n\t\t\tconst rows = d\n\t\t\t\t.select({\n\t\t\t\t\tpeer_device_id: schema.syncAttempts.peer_device_id,\n\t\t\t\t\tok: schema.syncAttempts.ok,\n\t\t\t\t\terror: schema.syncAttempts.error,\n\t\t\t\t\tstarted_at: schema.syncAttempts.started_at,\n\t\t\t\t\tfinished_at: schema.syncAttempts.finished_at,\n\t\t\t\t\tops_in: schema.syncAttempts.ops_in,\n\t\t\t\t\tops_out: schema.syncAttempts.ops_out,\n\t\t\t\t\tlocal_sync_capability: schema.syncAttempts.local_sync_capability,\n\t\t\t\t\tpeer_sync_capability: schema.syncAttempts.peer_sync_capability,\n\t\t\t\t\tnegotiated_sync_capability: schema.syncAttempts.negotiated_sync_capability,\n\t\t\t\t})\n\t\t\t\t.from(schema.syncAttempts)\n\t\t\t\t.orderBy(desc(schema.syncAttempts.finished_at))\n\t\t\t\t.limit(limit)\n\t\t\t\t.all();\n\t\t\tconst showDiag = queryBool(c.req.query(\"includeDiagnostics\"));\n\t\t\tconst items = rows.map((row) => mapSyncAttemptRow(row, showDiag));\n\t\t\treturn c.json({ items, redacted: !showDiag });\n\t\t}\n\t});\n\n\t// GET /api/sync/pairing — uses ensureDeviceIdentity from core (fix #5 context)\n\t//\n\t// The pairing payload is not redacted by the generic diagnostics toggle:\n\t// it is the actual command the user shares with their own other devices,\n\t// and the UI already hides it inside a \"Show pairing command\" disclosure\n\t// that they explicitly open. Redacting the payload here broke the\n\t// happy-path pairing flow because the UI had nothing to render as the\n\t// command when diagnostics were off.\n\tapp.get(\"/api/sync/pairing\", (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tconst config = readCoordinatorSyncConfig();\n\t\t\tconst d = drizzle(store.db, { schema });\n\t\t\tlet deviceId: string | undefined;\n\t\t\tlet publicKey: string | undefined;\n\t\t\tlet fingerprint: string | undefined;\n\n\t\t\ttry {\n\t\t\t\tconst [id, fp] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });\n\t\t\t\tdeviceId = id;\n\t\t\t\tfingerprint = fp;\n\t\t\t\tconst row = d\n\t\t\t\t\t.select({ public_key: schema.syncDevice.public_key })\n\t\t\t\t\t.from(schema.syncDevice)\n\t\t\t\t\t.where(eq(schema.syncDevice.device_id, id))\n\t\t\t\t\t.get();\n\t\t\t\tpublicKey = row?.public_key ?? \"\";\n\t\t\t} catch {\n\t\t\t\treturn c.json({ error: \"device identity unavailable\" }, 500);\n\t\t\t}\n\n\t\t\tif (!deviceId || !fingerprint) {\n\t\t\t\treturn c.json({ error: \"public key missing\" }, 500);\n\t\t\t}\n\n\t\t\treturn c.json({\n\t\t\t\tdevice_id: deviceId,\n\t\t\t\tfingerprint,\n\t\t\t\tpublic_key: publicKey ?? null,\n\t\t\t\tpairing_filter_hint: PAIRING_FILTER_HINT,\n\t\t\t\taddresses: pairingAdvertiseAddresses(config),\n\t\t\t});\n\t\t}\n\t});\n\n\t// ------------------------------------------------------------------\n\t// POST mutations\n\t// ------------------------------------------------------------------\n\n\t// POST /api/sync/peers/rename\n\tapp.post(\"/api/sync/peers/rename\", async (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tconst d = drizzle(store.db, { schema });\n\t\t\tlet body: Record<string, unknown>;\n\t\t\ttry {\n\t\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t\t} catch {\n\t\t\t\treturn c.json({ error: \"invalid json\" }, 400);\n\t\t\t}\n\t\t\tconst peerDeviceId = String(body.peer_device_id ?? \"\").trim();\n\t\t\tconst rawName = String(body.name ?? \"\");\n\t\t\tif (!peerDeviceId) return c.json({ error: \"peer_device_id required\" }, 400);\n\t\t\tif (!rawName.trim()) return c.json({ error: \"name required\" }, 400);\n\t\t\tlet name: string;\n\t\t\ttry {\n\t\t\t\tname = normalizeHumanPresentationName(rawName, \"name\");\n\t\t\t} catch (error) {\n\t\t\t\treturn c.json({ error: error instanceof Error ? error.message : \"name_invalid\" }, 400);\n\t\t\t}\n\t\t\tconst exists = d\n\t\t\t\t.select({ peer_device_id: schema.syncPeers.peer_device_id })\n\t\t\t\t.from(schema.syncPeers)\n\t\t\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t\t\t.get();\n\t\t\tif (!exists) return c.json({ error: \"peer not found\" }, 404);\n\t\t\td.update(schema.syncPeers)\n\t\t\t\t.set({ name })\n\t\t\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t\t\t.run();\n\t\t\treturn c.json({ ok: true });\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/run\", async (c) => {\n\t\tconst store = getStore();\n\t\tlet body: Record<string, unknown> = {};\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\tbody = {};\n\t\t}\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tif (!config.syncEnabled) {\n\t\t\treturn c.json({ error: \"sync_disabled\" }, 403);\n\t\t}\n\t\tconst address =\n\t\t\ttypeof body.address === \"string\" && body.address.trim() ? body.address.trim() : null;\n\t\tconst requestedPeerId =\n\t\t\ttypeof body.peer_device_id === \"string\" && body.peer_device_id.trim()\n\t\t\t\t? body.peer_device_id.trim()\n\t\t\t\t: null;\n\t\tlet peerIds: string[];\n\t\tif (address) {\n\t\t\tconst peerId = findPeerDeviceIdForAddress(store, address);\n\t\t\tif (!peerId) return c.json({ error: \"unknown peer address\" }, 404);\n\t\t\tpeerIds = [peerId];\n\t\t} else if (requestedPeerId) {\n\t\t\tconst requestedPeerRows = store.db\n\t\t\t\t.prepare(\"SELECT peer_device_id FROM sync_peers WHERE peer_device_id = ?\")\n\t\t\t\t.all(requestedPeerId) as Array<{ peer_device_id: string | null }>;\n\t\t\tpeerIds = requestedPeerRows\n\t\t\t\t.map((row) => String(row.peer_device_id ?? \"\").trim())\n\t\t\t\t.filter(Boolean);\n\t\t} else {\n\t\t\tconst allPeerRows = store.db.prepare(\"SELECT peer_device_id FROM sync_peers\").all() as Array<{\n\t\t\t\tpeer_device_id: string | null;\n\t\t\t}>;\n\t\t\tpeerIds = allPeerRows.map((row) => String(row.peer_device_id ?? \"\").trim()).filter(Boolean);\n\t\t}\n\t\tconst items = [] as Array<Record<string, unknown>>;\n\t\tfor (const peerId of peerIds) {\n\t\t\t// keysDir must match the sync daemon's key material — omitting it made\n\t\t\t// this route sign with a different device key whenever CODEMEM_KEYS_DIR\n\t\t\t// was set, so manual sync runs failed peer auth while daemon syncs worked.\n\t\t\tconst result = await runSyncPass(store.db, peerId, {\n\t\t\t\tkeysDir: syncKeysDir(),\n\t\t\t\tdbPath: store.dbPath,\n\t\t\t\tscanner: store.scanner,\n\t\t\t});\n\t\t\titems.push({\n\t\t\t\tpeer_device_id: peerId,\n\t\t\t\t...result,\n\t\t\t\tskippedOut: undefined,\n\t\t\t\tskipped_out: safeSkippedSyncDetail(result.skippedOut),\n\t\t\t});\n\t\t}\n\t\treturn c.json({ items });\n\t});\n\n\tapp.post(\"/api/sync/peers/scope\", async (c) => {\n\t\tconst store = getStore();\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\" }, 400);\n\t\t}\n\t\tconst peerDeviceId = String(body.peer_device_id ?? \"\").trim();\n\t\tif (!peerDeviceId) return c.json({ error: \"peer_device_id required\" }, 400);\n\t\tconst include = Array.isArray(body.include)\n\t\t\t? body.include\n\t\t\t\t\t.filter((value): value is string => typeof value === \"string\")\n\t\t\t\t\t.map((value) => value.trim())\n\t\t\t\t\t.filter(Boolean)\n\t\t\t: null;\n\t\tconst exclude = Array.isArray(body.exclude)\n\t\t\t? body.exclude\n\t\t\t\t\t.filter((value): value is string => typeof value === \"string\")\n\t\t\t\t\t.map((value) => value.trim())\n\t\t\t\t\t.filter(Boolean)\n\t\t\t: null;\n\t\tconst inheritGlobal = Boolean(body.inherit_global);\n\t\tconst d = drizzle(store.db, { schema });\n\t\tconst exists = d\n\t\t\t.select({ peer_device_id: schema.syncPeers.peer_device_id })\n\t\t\t.from(schema.syncPeers)\n\t\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t\t.get();\n\t\tif (!exists) return c.json({ error: \"peer not found\" }, 404);\n\t\td.update(schema.syncPeers)\n\t\t\t.set({\n\t\t\t\tprojects_include_json: inheritGlobal ? null : JSON.stringify(include ?? []),\n\t\t\t\tprojects_exclude_json: inheritGlobal ? null : JSON.stringify(exclude ?? []),\n\t\t\t})\n\t\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t\t.run();\n\t\tconst row = d\n\t\t\t.select({\n\t\t\t\tprojects_include_json: schema.syncPeers.projects_include_json,\n\t\t\t\tprojects_exclude_json: schema.syncPeers.projects_exclude_json,\n\t\t\t})\n\t\t\t.from(schema.syncPeers)\n\t\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t\t.get() as Record<string, unknown> | undefined;\n\t\tif (!row) return c.json({ error: \"peer not found\" }, 404);\n\t\treturn c.json({\n\t\t\tok: true,\n\t\t\tproject_scope: currentProjectScope(row, readPeerProjectFilters(store, peerDeviceId)),\n\t\t});\n\t});\n\n\tapp.get(\"/api/sync/sharing-domains/settings\", (c) => {\n\t\tconst store = getStore();\n\t\tconst limit = Math.max(1, queryInt(c.req.query(\"limit\"), 250));\n\t\treturn c.json({\n\t\t\tscopes: listSharingDomainSettingsScopes(store.db),\n\t\t\tmappings: listProjectScopeSettingsMappings(store.db),\n\t\t\tprojects: listProjectScopeCandidates(store.db, { limit }),\n\t\t\tlocal_default_scope_id: LOCAL_DEFAULT_SCOPE_ID,\n\t\t});\n\t});\n\n\tapp.get(\"/api/sync/recipient-policy/v1/projection\", (c) => {\n\t\tconst store = getStore();\n\t\treturn c.json(\n\t\t\tlistLegacyRecipientPolicyProjections(store.db, {\n\t\t\t\tlocalActorId: store.actorId,\n\t\t\t\tlocalDeviceId: store.deviceId,\n\t\t\t}),\n\t\t);\n\t});\n\n\tapp.get(\"/api/sync/recipient-policy/v1/review\", (c) => {\n\t\tconst store = getStore();\n\t\tensureLocalActorRecord(store);\n\t\treturn c.json(\n\t\t\tlistRecipientPolicyReview(store.db, {\n\t\t\t\tlocalActorId: store.actorId,\n\t\t\t\tlocalDeviceId: store.deviceId,\n\t\t\t}),\n\t\t);\n\t});\n\n\tapp.get(\"/api/sync/recipient-policy/v1/intent\", (c) => {\n\t\tconst store = getStore();\n\t\treturn c.json(listRecipientPolicyIntent(store.db));\n\t});\n\n\tapp.get(\"/api/sync/recipient-policy/v1/reconciliation-status\", (c) => {\n\t\treturn c.json(listRecipientPolicyReconciliationStatus(getStore()));\n\t});\n\n\tapp.post(\"/api/sync/recipient-policy/v1/edges/preview\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst body = await parseViewerJsonBody(c);\n\t\ttry {\n\t\t\treturn c.json(previewRecipientPolicyEdges(store.db, body));\n\t\t} catch (error) {\n\t\t\tif (error instanceof RecipientPolicyEdgeRequestError) {\n\t\t\t\tif (error.status === \"not_found\") {\n\t\t\t\t\treturn c.json({ error: error.errorCode }, 404);\n\t\t\t\t}\n\t\t\t\treturn c.json({ error: error.errorCode }, 400);\n\t\t\t}\n\t\t\tif (isSqliteBusy(error)) {\n\t\t\t\tc.header(\"Retry-After\", \"1\");\n\t\t\t\treturn c.json({ error: \"edge_preview_busy\" }, 503);\n\t\t\t}\n\t\t\treturn c.json({ error: \"edge_preview_failed\" }, 500);\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/recipient-policy/v1/edges/commit\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst body = await parseViewerJsonBody(c);\n\t\ttry {\n\t\t\tconst request = parseRecipientPolicyEdgeCommitRequest(body);\n\t\t\t// Acquire every affected Team queue in one stable order. Finish publication\n\t\t\t// uses the same Team boundary, so its reviewed snapshot cannot race a\n\t\t\t// successful user recipient commit.\n\t\t\tconst teamIds = request\n\t\t\t\t? [\n\t\t\t\t\t\t...new Set(\n\t\t\t\t\t\t\trequest.changes.flatMap((change) =>\n\t\t\t\t\t\t\t\tchange.recipient.recipientKind === \"team\" ? [change.recipient.teamId] : [],\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t),\n\t\t\t\t\t].toSorted()\n\t\t\t\t: [];\n\t\t\tconst commit = async (\n\t\t\t\tindex: number,\n\t\t\t): Promise<ReturnType<typeof commitRecipientPolicyEdges>> => {\n\t\t\t\tconst teamId = teamIds[index];\n\t\t\t\tif (!teamId) return commitRecipientPolicyEdges(store.db, request ?? body);\n\t\t\t\treturn serializeRecipientPolicyTeamMutation(store.db, teamId, () => commit(index + 1));\n\t\t\t};\n\t\t\tconst result = await commit(0);\n\t\t\tif (result.status === \"invalid\") return c.json(result, 400);\n\t\t\tif (result.status === \"not_found\") return c.json(result, 404);\n\t\t\tif (result.status === \"stale\" || result.status === \"conflict\") {\n\t\t\t\treturn c.json(result, 409);\n\t\t\t}\n\t\t\treturn c.json(result);\n\t\t} catch (error) {\n\t\t\tif (isSqliteBusy(error)) {\n\t\t\t\tc.header(\"Retry-After\", \"1\");\n\t\t\t\treturn c.json({ error: \"edge_commit_busy\" }, 503);\n\t\t\t}\n\t\t\treturn c.json(\n\t\t\t\t{\n\t\t\t\t\tversion: 1,\n\t\t\t\t\tstatus: \"conflict\",\n\t\t\t\t\treviewedPolicyDigest: \"\",\n\t\t\t\t\terrorCode: \"edge_commit_conflict\",\n\t\t\t\t\toutcomes: [],\n\t\t\t\t\twriteCount: 0,\n\t\t\t\t\tidempotent: false,\n\t\t\t\t},\n\t\t\t\t409,\n\t\t\t);\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/recipient-policy/v1/invites/preview\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst body = await parseViewerJsonBody(c);\n\t\tif (!body) return c.json({ error: \"request_invalid\" }, 400);\n\t\ttry {\n\t\t\tconst kind = recipientInviteKind(body.kind ?? body.invite_kind);\n\t\t\tconst config = readCoordinatorSyncConfig();\n\t\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\t\tconst unavailable = recipientInviteCreationUnavailable(status, kind);\n\t\t\tif (unavailable) return c.json(unavailable.body, unavailable.httpStatus);\n\t\t\tconst targetId =\n\t\t\t\tkind === \"team_member\"\n\t\t\t\t\t? optionalViewerStrictString(body, \"policy_team_id\")\n\t\t\t\t\t: optionalViewerStrictString(body, \"target_identity_id\");\n\t\t\tif (!targetId) throw new Error(\"recipient_invite_metadata_invalid\");\n\t\t\tif (kind === \"add_device\" && targetId !== store.actorId) {\n\t\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t\t}\n\t\t\tconst preview = recipientInviteOnboardingPreview(\n\t\t\t\tstore,\n\t\t\t\tbody,\n\t\t\t\trecipientInvitePreviewId(kind, targetId),\n\t\t\t);\n\t\t\treturn c.json({ kind, preview });\n\t\t} catch (error) {\n\t\t\treturn c.json(\n\t\t\t\t{ error: error instanceof Error ? error.message : \"recipient_invite_invalid\" },\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/recipient-policy/v1/invites\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst body = await parseViewerJsonBody(c);\n\t\tif (!body) return c.json({ error: \"request_invalid\" }, 400);\n\t\ttry {\n\t\t\tconst kind = recipientInviteKind(body.kind ?? body.invite_kind);\n\t\t\tconst config = readCoordinatorSyncConfig();\n\t\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\t\tconst unavailable = recipientInviteCreationUnavailable(status, kind);\n\t\t\tif (unavailable) return c.json(unavailable.body, unavailable.httpStatus);\n\t\t\tconst targetId =\n\t\t\t\tkind === \"team_member\"\n\t\t\t\t\t? optionalViewerStrictString(body, \"policy_team_id\")\n\t\t\t\t\t: optionalViewerStrictString(body, \"target_identity_id\");\n\t\t\tif (!targetId) throw new Error(\"recipient_invite_metadata_invalid\");\n\t\t\tif (kind === \"add_device\" && targetId !== store.actorId) {\n\t\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t\t}\n\t\t\tconst preview = recipientInviteOnboardingPreview(\n\t\t\t\tstore,\n\t\t\t\tbody,\n\t\t\t\trecipientInvitePreviewId(kind, targetId),\n\t\t\t);\n\t\t\tconst reviewedDigest = optionalViewerStrictString(body, \"reviewed_onboarding_digest\");\n\t\t\tif (!reviewedDigest) throw new Error(\"reviewed_onboarding_digest_required\");\n\t\t\tif (reviewedDigest !== preview.reviewedOnboardingDigest) {\n\t\t\t\treturn c.json({ error: \"reviewed_onboarding_stale\", preview }, 409);\n\t\t\t}\n\t\t\tconst reviewedIntent = recipientInviteReviewedIntent(store, kind, targetId, preview);\n\t\t\tconst reviewedPreviewDigest = await recipientReviewedIntentDigest(reviewedIntent);\n\t\t\tconst groupId = resolveCoordinatorAdminGroup(optionalViewerString(body, \"group_id\"), status);\n\t\t\tconst ttlHours = parseInviteTtlHours(body.ttl_hours);\n\t\t\tif (!groupId) throw new Error(\"group_id_required\");\n\t\t\tif (ttlHours == null) throw new Error(\"ttl_hours_invalid\");\n\t\t\t// Initial owner enrollments intentionally remain Identity-unbound, so an explicitly\n\t\t\t// admin-configured owner selects admin issuance up front. Non-admin devices use the\n\t\t\t// signed Identity-bound endpoint; failures never fall back across this boundary.\n\t\t\tconst useAdminIssuance = kind === \"team_member\" || status.has_admin_secret;\n\t\t\tconst result = useAdminIssuance\n\t\t\t\t? await coordinatorCreateInviteAction({\n\t\t\t\t\t\tgroupId,\n\t\t\t\t\t\tcoordinatorUrl: config.syncCoordinatorUrl || null,\n\t\t\t\t\t\tpolicy: \"auto_admit\",\n\t\t\t\t\t\tttlHours,\n\t\t\t\t\t\tcreatedBy: store.actorId,\n\t\t\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t\t\t\tinviteKind: kind,\n\t\t\t\t\t\tpolicyTeamId: kind === \"team_member\" ? targetId : null,\n\t\t\t\t\t\ttargetIdentityId: kind === \"add_device\" ? targetId : null,\n\t\t\t\t\t\tinviterDeviceId: kind === \"add_device\" ? preview.binding.deviceId : null,\n\t\t\t\t\t\treviewedPreviewDigest,\n\t\t\t\t\t\treviewedIntent,\n\t\t\t\t\t})\n\t\t\t\t: await coordinatorCreateAddDeviceInviteAction({\n\t\t\t\t\t\tgroupId,\n\t\t\t\t\t\tcoordinatorUrl: config.syncCoordinatorUrl || null,\n\t\t\t\t\t\tttlHours,\n\t\t\t\t\t\tdeviceId: preview.binding.deviceId,\n\t\t\t\t\t\tkeysDir: syncKeysDir(),\n\t\t\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\t\t\treviewedPreviewDigest,\n\t\t\t\t\t\treviewedIntent,\n\t\t\t\t\t});\n\t\t\treturn c.json({ ok: true, kind, preview, invite: result });\n\t\t} catch (error) {\n\t\t\treturn c.json(\n\t\t\t\t{ error: error instanceof Error ? error.message : \"recipient_invite_failed\" },\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/recipient-policy/v1/migrate\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst value = await parseViewerJsonBody(c);\n\t\tif (!value || typeof value !== \"object\" || Array.isArray(value)) {\n\t\t\treturn c.json({ error: \"request_invalid\" }, 400);\n\t\t}\n\t\tconst body = value as Record<string, unknown>;\n\t\tif (\n\t\t\tObject.keys(body).some((key) => key !== \"dryRun\") ||\n\t\t\t(Object.hasOwn(body, \"dryRun\") && typeof body.dryRun !== \"boolean\")\n\t\t) {\n\t\t\treturn c.json({ error: \"request_invalid\" }, 400);\n\t\t}\n\t\ttry {\n\t\t\treturn c.json(\n\t\t\t\tmigrateRecipientPolicyIntent(\n\t\t\t\t\tstore.db,\n\t\t\t\t\t{ localActorId: store.actorId, localDeviceId: store.deviceId },\n\t\t\t\t\t{ dryRun: body.dryRun === true },\n\t\t\t\t),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (isSqliteBusy(error)) {\n\t\t\t\tc.header(\"Retry-After\", \"1\");\n\t\t\t\treturn c.json({ error: \"migration_busy\" }, 503);\n\t\t\t}\n\t\t\treturn c.json({ error: \"migration_failed\" }, 500);\n\t\t}\n\t});\n\n\tconst parseReviewRequest = (value: unknown): RecipientPolicyReviewResolveRequestV1 | null => {\n\t\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n\t\tconst body = value as Record<string, unknown>;\n\t\tconst allowedKeys = new Set([\"reviewItemId\", \"sourceFingerprint\", \"decision\", \"decisionInput\"]);\n\t\tif (\n\t\t\tObject.keys(body).some((key) => !allowedKeys.has(key)) ||\n\t\t\ttypeof body.reviewItemId !== \"string\" ||\n\t\t\ttypeof body.sourceFingerprint !== \"string\" ||\n\t\t\ttypeof body.decision !== \"string\"\n\t\t) {\n\t\t\treturn null;\n\t\t}\n\t\treturn {\n\t\t\treviewItemId: body.reviewItemId,\n\t\t\tsourceFingerprint: body.sourceFingerprint,\n\t\t\tdecision: body.decision as RecipientPolicyReviewDecisionV1,\n\t\t\t...(Object.hasOwn(body, \"decisionInput\") ? { decisionInput: body.decisionInput } : {}),\n\t\t};\n\t};\n\n\tapp.post(\"/api/sync/recipient-policy/v1/review/resolve\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst body = await parseViewerJsonBody(c);\n\t\tconst request = parseReviewRequest(body);\n\t\tif (!request) return c.json({ error: \"request_invalid\" }, 400);\n\t\tensureLocalActorRecord(store);\n\t\tconst result = resolveRecipientPolicyReview(\n\t\t\tstore.db,\n\t\t\t{ localActorId: store.actorId, localDeviceId: store.deviceId },\n\t\t\trequest,\n\t\t);\n\t\tif (result.status === \"stale\" || result.status === \"conflict\") return c.json(result, 409);\n\t\tif (result.status === \"not_found\") return c.json(result, 404);\n\t\tif (result.status === \"invalid\") return c.json(result, 400);\n\t\treturn c.json(result);\n\t});\n\n\tapp.post(\"/api/sync/recipient-policy/v1/review/resolve-bulk\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst body = await parseViewerJsonBody(c);\n\t\tif (\n\t\t\t!body ||\n\t\t\t!Array.isArray(body.requests) ||\n\t\t\tbody.requests.length === 0 ||\n\t\t\tbody.requests.length > 100\n\t\t)\n\t\t\treturn c.json({ error: \"request_invalid\" }, 400);\n\t\tconst requests = body.requests.map(parseReviewRequest);\n\t\tif (requests.some((request) => request == null))\n\t\t\treturn c.json({ error: \"request_invalid\" }, 400);\n\t\tensureLocalActorRecord(store);\n\t\tconst result = resolveRecipientPolicyReviewBulk(\n\t\t\tstore.db,\n\t\t\t{ localActorId: store.actorId, localDeviceId: store.deviceId },\n\t\t\trequests as RecipientPolicyReviewResolveRequestV1[],\n\t\t);\n\t\treturn c.json(result, result.results.some((item) => item.status !== \"applied\") ? 207 : 200);\n\t});\n\n\tapp.get(\"/api/sync/projects\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst limit = Math.max(1, queryInt(c.req.query(\"limit\"), 50));\n\t\tconst offset = Math.max(0, queryInt(c.req.query(\"offset\"), 0));\n\t\tconst inventory = listProjectScopeInventory(store.db, {\n\t\t\tidentitySource: c.req.query(\"identity_source\"),\n\t\t\tlimit,\n\t\t\toffset,\n\t\t\tquery: c.req.query(\"q\"),\n\t\t\tscopeId: c.req.query(\"scope_id\"),\n\t\t\tstatus: c.req.query(\"status\"),\n\t\t});\n\t\tconst operations = await shareOperationReadModels(store, undefined, false);\n\t\tconst operationById = new Map(\n\t\t\toperations.map((operation) => [operation.operation_id, operation]),\n\t\t);\n\t\tconst sharingByProject = new Map<string, Array<Record<string, unknown>>>();\n\t\tconst reviewed = store.db\n\t\t\t.prepare(`SELECT p.operation_id, p.canonical_project_identity\n\t\t\t FROM share_operation_projects p\n\t\t\t JOIN share_operations o ON o.operation_id = p.operation_id\n\t\t\t WHERE o.inviter_actor_id = ? ORDER BY o.created_at, p.ordinal`)\n\t\t\t.all(store.actorId) as Array<{ operation_id: string; canonical_project_identity: string }>;\n\t\tfor (const item of reviewed) {\n\t\t\tconst operation = operationById.get(item.operation_id);\n\t\t\tif (!operation) continue;\n\t\t\tconst current = sharingByProject.get(item.canonical_project_identity) ?? [];\n\t\t\tcurrent.push({\n\t\t\t\tperson: operation.person,\n\t\t\t\tlifecycle: {\n\t\t\t\t\tstate: operation.lifecycle.state,\n\t\t\t\t\tlabel: operation.lifecycle.label,\n\t\t\t\t\texplanation: operation.lifecycle.explanation,\n\t\t\t\t},\n\t\t\t});\n\t\t\tsharingByProject.set(item.canonical_project_identity, current);\n\t\t}\n\t\treturn c.json({\n\t\t\t...inventory,\n\t\t\tprojects: inventory.projects.map((project) => ({\n\t\t\t\t...project,\n\t\t\t\tsharing: sharingByProject.get(project.workspace_identity) ?? [],\n\t\t\t})),\n\t\t});\n\t});\n\n\tapp.post(\"/api/sync/projects/reassign-project\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst body = await parseViewerJsonBody(c);\n\t\tif (!body) return c.json({ error: \"invalid json\" }, 400);\n\t\ttry {\n\t\t\tconst workspaceIdentity = optionalViewerStrictString(body, \"workspace_identity\") ?? \"\";\n\t\t\tconst project = optionalViewerStrictString(body, \"project\") ?? \"\";\n\t\t\tconst [deviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });\n\t\t\tconst result = reassignProjectScopeInventoryProject(store.db, {\n\t\t\t\tdeviceId,\n\t\t\t\tproject,\n\t\t\t\tworkspaceIdentity,\n\t\t\t});\n\t\t\treturn c.json({ ok: true, ...result });\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\treturn c.json({ error: message }, message.includes(\"not found\") ? 404 : 400);\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/projects/forget\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst body = await parseViewerJsonBody(c);\n\t\tif (!body) return c.json({ error: \"invalid json\" }, 400);\n\t\ttry {\n\t\t\tconst workspaceIdentity = optionalViewerStrictString(body, \"workspace_identity\") ?? \"\";\n\t\t\tconst confirmationToken = optionalViewerStrictString(body, \"confirmation_token\");\n\t\t\tconst confirmed = body.confirmed === true;\n\t\t\tconst result = forgetProjectInventoryLocalMemories(store, {\n\t\t\t\tconfirmationToken,\n\t\t\t\tconfirmed,\n\t\t\t\tworkspaceIdentity,\n\t\t\t});\n\t\t\tif (!confirmed) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"project_forget_confirmation_required\",\n\t\t\t\t\t\tpreview: result,\n\t\t\t\t\t},\n\t\t\t\t\t409,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn c.json({ ok: true, ...result });\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\treturn c.json({ error: message }, message.includes(\"not found\") ? 404 : 400);\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/project-invites/preview\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst body = await parseViewerJsonBody(c);\n\t\tif (!body) return c.json({ error: \"invalid_json\" }, 400);\n\t\ttry {\n\t\t\tassertProjectInviteBody(body, false);\n\t\t\tconst createdAt = new Date().toISOString();\n\t\t\tconst inviteExpiresAt = new Date(\n\t\t\t\tnew Date(createdAt).getTime() + PROJECT_INVITE_TTL_HOURS * 3600 * 1000,\n\t\t\t).toISOString();\n\t\t\tconst { plan } = projectInvitePlan(store, body, createdAt, inviteExpiresAt);\n\t\t\treturn c.json(projectInvitePreview(plan));\n\t\t} catch (error) {\n\t\t\treturn c.json(\n\t\t\t\t{ error: error instanceof Error ? error.message : \"project_invite_invalid\" },\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/project-invites\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst body = await parseViewerJsonBody(c);\n\t\tif (!body) return c.json({ error: \"invalid_json\" }, 400);\n\t\ttry {\n\t\t\tassertProjectInviteBody(body, true);\n\t\t\tconst createdAt = new Date().toISOString();\n\t\t\tconst inviteExpiresAt = new Date(\n\t\t\t\tnew Date(createdAt).getTime() + PROJECT_INVITE_TTL_HOURS * 3600 * 1000,\n\t\t\t).toISOString();\n\t\t\tconst { plan, config } = projectInvitePlan(store, body, createdAt, inviteExpiresAt);\n\t\t\tif (String(body.reviewed_project_set_digest).trim() !== plan.reviewedProjectSetDigest) {\n\t\t\t\treturn c.json({ error: \"reviewed_project_set_changed\" }, 409);\n\t\t\t}\n\t\t\tconst existingState = (() => {\n\t\t\t\ttry {\n\t\t\t\t\treturn store.db\n\t\t\t\t\t\t.prepare(\"SELECT state FROM share_operations WHERE operation_id = ?\")\n\t\t\t\t\t\t.pluck()\n\t\t\t\t\t\t.get(plan.operationId) as string | undefined;\n\t\t\t\t} catch {\n\t\t\t\t\t// Local persistence below remains authoritative. Keeping this precheck\n\t\t\t\t\t// best-effort preserves coordinator idempotency if local storage is unavailable.\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t})();\n\t\t\tif (existingState && existingState !== \"waiting_for_acceptance\") {\n\t\t\t\treturn c.json({ error: \"operation_state_invalid\" }, 409);\n\t\t\t}\n\t\t\t// The coordinator invite is minted before local persistence. If the local\n\t\t\t// transaction fails, operationId makes coordinator creation return the\n\t\t\t// current invite. Expired or revoked waiting invites are renewed in place.\n\t\t\tconst result = await coordinatorCreateInviteAction({\n\t\t\t\tgroupId: plan.coordinatorGroupId,\n\t\t\t\tcoordinatorUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tpolicy: \"auto_admit\",\n\t\t\t\tttlHours: PROJECT_INVITE_TTL_HOURS,\n\t\t\t\tcreatedBy: store.actorId,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t\toperationId: plan.operationId,\n\t\t\t\treviewedProjectSetDigest: plan.reviewedProjectSetDigest,\n\t\t\t\tinviterActorId: plan.inviterActorId,\n\t\t\t\tinviterDisplayName: projectInviteInviterDisplayName(store.actorDisplayName),\n\t\t\t\tinviterDeviceId: plan.inviterDeviceIds[0],\n\t\t\t\tpendingPersonId: plan.personId,\n\t\t\t\tprojectSummaries: plan.projects.map((project) => ({\n\t\t\t\t\tdisplay_name: project.displayName,\n\t\t\t\t\texisting_memory_count: project.existingMemoryCount,\n\t\t\t\t})),\n\t\t\t\tprojectIntent: plan.projects.map((project) => ({\n\t\t\t\t\tcanonical_identity: project.canonicalIdentity,\n\t\t\t\t\tdisplay_name: project.displayName,\n\t\t\t\t\texisting_memory_count: project.existingMemoryCount,\n\t\t\t\t})),\n\t\t\t});\n\t\t\tif (\n\t\t\t\tString(result.operation_id ?? \"\").trim() !== plan.operationId ||\n\t\t\t\tString(result.reviewed_project_set_digest ?? \"\").trim() !== plan.reviewedProjectSetDigest\n\t\t\t) {\n\t\t\t\tthrow new Error(\"coordinator_invite_intent_mismatch\");\n\t\t\t}\n\t\t\tconst payload = result.payload;\n\t\t\tif (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n\t\t\t\tthrow new Error(\"coordinator_invite_payload_missing\");\n\t\t\t}\n\t\t\tconst token = String((payload as Record<string, unknown>).token ?? \"\").trim();\n\t\t\tconst expiresAt = String((payload as Record<string, unknown>).expires_at ?? \"\").trim();\n\t\t\tconst link = String(result.link ?? \"\").trim();\n\t\t\tconst encoded = String(result.encoded ?? \"\").trim();\n\t\t\tif (!token || !expiresAt || !link || !encoded) {\n\t\t\t\tthrow new Error(\"coordinator_invite_payload_invalid\");\n\t\t\t}\n\t\t\tconst persistedPlan = { ...plan, inviteExpiresAt: new Date(expiresAt).toISOString() };\n\t\t\tpersistShareOperation(store.db, persistedPlan, {\n\t\t\t\tinviteId: String(result.invite_id ?? \"\").trim() || null,\n\t\t\t\ttokenDigest: inviteTokenDigest(token),\n\t\t\t});\n\t\t\treturn c.json({\n\t\t\t\tok: true,\n\t\t\t\t...projectInvitePreview(persistedPlan),\n\t\t\t\tinvite: {\n\t\t\t\t\tlink,\n\t\t\t\t\tencoded,\n\t\t\t\t\texpires_at: persistedPlan.inviteExpiresAt,\n\t\t\t\t},\n\t\t\t});\n\t\t} catch (error) {\n\t\t\treturn c.json(\n\t\t\t\t{ error: error instanceof Error ? error.message : \"project_invite_failed\" },\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t});\n\n\tapp.get(\"/api/sync/project-invites/:operationId\", async (c) => {\n\t\tconst operationId = String(c.req.param(\"operationId\") ?? \"\").trim();\n\t\tif (!/^share_[a-f0-9]{40}$/u.test(operationId)) {\n\t\t\treturn c.json({ error: \"operation_id_invalid\" }, 400);\n\t\t}\n\t\ttry {\n\t\t\tconst { payload } = await coordinatorProjectInvitePayload(operationId);\n\t\t\treturn c.json(\n\t\t\t\tpayload.state === \"accepted\" ? { ...payload, state: \"pending_setup\" } : payload,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconst mapped = projectInviteOwnerErrorResponse(error, {\n\t\t\t\tcode: \"operation_read_failed\",\n\t\t\t\tstatus: 400,\n\t\t\t});\n\t\t\treturn c.json({ error: mapped.code }, mapped.status);\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/project-invites/:operationId/reconcile\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst operationId = String(c.req.param(\"operationId\") ?? \"\").trim();\n\t\tif (!/^share_[a-f0-9]{40}$/u.test(operationId)) {\n\t\t\treturn c.json({ error: \"operation_id_invalid\" }, 400);\n\t\t}\n\t\ttry {\n\t\t\tconst result = await reconcileProjectInviteAcceptance(store, operationId);\n\t\t\treturn c.json({\n\t\t\t\tok: true,\n\t\t\t\toperation_id: operationId,\n\t\t\t\treconciled: result.accepted,\n\t\t\t\tstate: result.accepted ? \"pending_setup\" : \"waiting_for_acceptance\",\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst mapped = projectInviteOwnerErrorResponse(error, {\n\t\t\t\tcode: \"operation_reconcile_failed\",\n\t\t\t\tstatus: 409,\n\t\t\t});\n\t\t\treturn c.json({ error: mapped.code }, mapped.status);\n\t\t}\n\t});\n\n\tapp.get(\"/api/sync/share-operations\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst items = await shareOperationReadModels(store, undefined, false);\n\t\treturn c.json({ items });\n\t});\n\n\tapp.get(\"/api/sync/share-operations/:operationId\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst operationId = String(c.req.param(\"operationId\") ?? \"\").trim();\n\t\tif (!/^share_[a-f0-9]{40}$/u.test(operationId)) {\n\t\t\treturn c.json({ error: \"operation_id_invalid\" }, 400);\n\t\t}\n\t\tconst [item] = await shareOperationReadModels(store, operationId);\n\t\treturn item ? c.json(item) : c.json({ error: \"operation_not_found\" }, 404);\n\t});\n\n\tconst advanceProjectShare = async (c: Context) => {\n\t\tconst store = getStore();\n\t\tconst operationId = String(c.req.param(\"operationId\") ?? \"\").trim();\n\t\tif (!/^share_[a-f0-9]{40}$/u.test(operationId)) {\n\t\t\treturn c.json({ error: \"operation_id_invalid\" }, 400);\n\t\t}\n\t\ttry {\n\t\t\tconst advanced = await advanceProjectShareOperation(store, operationId);\n\t\t\tif (!advanced.advanced) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror:\n\t\t\t\t\t\t\tadvanced.state === \"cancelled\" ? \"operation_superseded\" : \"invitation_not_accepted\",\n\t\t\t\t\t},\n\t\t\t\t\t409,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst [operation] = await shareOperationReadModels(store, operationId);\n\t\t\treturn c.json({ ok: true, operation });\n\t\t} catch (error) {\n\t\t\tconst code = error instanceof Error ? error.message : \"provisioning_failed\";\n\t\t\tconst state = store.db\n\t\t\t\t.prepare(\"SELECT state FROM share_operations WHERE operation_id = ?\")\n\t\t\t\t.pluck()\n\t\t\t\t.get(operationId);\n\t\t\tif (state === \"cancelled\") {\n\t\t\t\treturn c.json({ error: \"operation_superseded\" }, 409);\n\t\t\t}\n\t\t\treturn c.json({ error: code }, code === \"operation_not_found\" ? 404 : 409);\n\t\t}\n\t};\n\n\tapp.post(\"/api/sync/share-operations/:operationId/advance\", advanceProjectShare);\n\n\tapp.post(\"/api/sync/project-invites/:operationId/provision\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst operationId = String(c.req.param(\"operationId\") ?? \"\").trim();\n\t\tif (!/^share_[a-f0-9]{40}$/u.test(operationId)) {\n\t\t\treturn c.json({ error: \"operation_id_invalid\" }, 400);\n\t\t}\n\t\ttry {\n\t\t\tconst plan = await executeProjectShareProvisioning(store, operationId);\n\t\t\tif (plan.superseded) {\n\t\t\t\t// Consistent with /advance: a supersession race is a conflict, not a\n\t\t\t\t// success with a flag.\n\t\t\t\treturn c.json({ error: \"operation_superseded\" }, 409);\n\t\t\t}\n\t\t\treturn c.json({ ok: true, operation_id: operationId, state: \"active\", plan });\n\t\t} catch (error) {\n\t\t\tconst code = error instanceof Error ? error.message : \"provisioning_failed\";\n\t\t\tconst state = store.db\n\t\t\t\t.prepare(\"SELECT state FROM share_operations WHERE operation_id = ?\")\n\t\t\t\t.pluck()\n\t\t\t\t.get(operationId);\n\t\t\tif (state === \"cancelled\") {\n\t\t\t\treturn c.json({ error: \"operation_superseded\" }, 409);\n\t\t\t}\n\t\t\treturn c.json({ error: code }, code === \"operation_not_found\" ? 404 : 409);\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/legacy-shared-review/reassign\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst body = await parseViewerJsonBody(c);\n\t\tif (!body) return c.json({ error: \"invalid json\" }, 400);\n\t\ttry {\n\t\t\tconst workspaceIdentity = optionalViewerStrictString(body, \"workspace_identity\") ?? \"\";\n\t\t\tconst scopeId = optionalViewerStrictString(body, \"scope_id\") ?? \"\";\n\t\t\tconst confirmationToken = optionalViewerStrictString(body, \"confirmation_token\");\n\t\t\tconst confirmedOldCopies = body.confirmed_old_copies === true;\n\t\t\tconst preview = legacySharedReviewReassignmentPreview(store, {\n\t\t\t\tscopeId,\n\t\t\t\tworkspaceIdentity,\n\t\t\t});\n\t\t\tif (!confirmedOldCopies) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"legacy_review_confirmation_required\",\n\t\t\t\t\t\tmessage: preview.warning,\n\t\t\t\t\t\tpreview,\n\t\t\t\t\t},\n\t\t\t\t\t409,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn c.json(\n\t\t\t\treassignLegacySharedReviewGroup(store, {\n\t\t\t\t\tconfirmationToken,\n\t\t\t\t\tscopeId,\n\t\t\t\t\tworkspaceIdentity,\n\t\t\t\t}),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\treturn c.json({ error: message }, message.includes(\"not found\") ? 404 : 400);\n\t\t}\n\t});\n\n\tapp.put(\"/api/sync/sharing-domains/project-mappings\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst body = await parseViewerJsonBody(c);\n\t\tif (!body) return c.json({ error: \"invalid json\" }, 400);\n\t\tlet releasePublicationMutation: (() => void) | undefined;\n\t\ttry {\n\t\t\tconst confirmedGuardrailTokens = optionalViewerStringList(body, \"confirmed_guardrail_tokens\");\n\t\t\tconst mappingInput = parseViewerProjectMappingInput(body);\n\t\t\treleasePublicationMutation = await claimRecipientPolicyPublicationMutation(store.db);\n\t\t\tconst analysis = analyzeProjectScopeMappingChangeGuardrails(store.db, mappingInput);\n\t\t\tif (analysis.requested_workspace_identity?.startsWith(\"unmapped:\")) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"unmapped_project_local_only\",\n\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\"Unmapped projects need a stable path, git remote, or workspace id before assigning a Sharing domain.\",\n\t\t\t\t\t\tguardrail_warnings: analysis.warnings,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst missingConfirmations = missingGuardrailConfirmations(\n\t\t\t\tanalysis.warnings,\n\t\t\t\tconfirmedGuardrailTokens,\n\t\t\t);\n\t\t\tif (missingConfirmations.length > 0) {\n\t\t\t\tconst missingCodes = [...new Set(missingConfirmations.map((warning) => warning.code))];\n\t\t\t\tconst missingTokens = [\n\t\t\t\t\t...new Set(missingConfirmations.map((warning) => warning.confirmation_token)),\n\t\t\t\t].filter((token): token is string => typeof token === \"string\" && token.length > 0);\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"guardrail_confirmation_required\",\n\t\t\t\t\t\trequired_guardrails: missingCodes,\n\t\t\t\t\t\trequired_guardrail_tokens: missingTokens,\n\t\t\t\t\t\tguardrail_warnings: analysis.warnings,\n\t\t\t\t\t},\n\t\t\t\t\t409,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst [deviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });\n\t\t\tconst mapping = upsertProjectScopeSettingsMapping(store.db, {\n\t\t\t\tdeviceId,\n\t\t\t\t...mappingInput,\n\t\t\t});\n\t\t\treturn c.json({ ok: true, mapping, guardrail_warnings: analysis.warnings });\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error) }, 400);\n\t\t} finally {\n\t\t\treleasePublicationMutation?.();\n\t\t}\n\t});\n\n\tapp.put(\"/api/sync/sharing-domains/project-mappings/bulk\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst body = await parseViewerJsonBody(c);\n\t\tif (!body) return c.json({ error: \"invalid json\" }, 400);\n\t\tlet releasePublicationMutation: (() => void) | undefined;\n\t\ttry {\n\t\t\tconst rawMappings = body.mappings;\n\t\t\tif (!Array.isArray(rawMappings) || rawMappings.length === 0) {\n\t\t\t\treturn c.json({ error: \"mappings must be a non-empty array\" }, 400);\n\t\t\t}\n\t\t\tconst mappingInputs = rawMappings.map((raw) => {\n\t\t\t\tif (raw == null || typeof raw !== \"object\" || Array.isArray(raw)) {\n\t\t\t\t\tthrow new Error(\"each mapping must be an object\");\n\t\t\t\t}\n\t\t\t\treturn parseViewerProjectMappingInput(raw as Record<string, unknown>);\n\t\t\t});\n\t\t\treleasePublicationMutation = await claimRecipientPolicyPublicationMutation(store.db);\n\t\t\tconst analyses = mappingInputs.map((mappingInput) =>\n\t\t\t\tanalyzeProjectScopeMappingChangeGuardrails(store.db, mappingInput),\n\t\t\t);\n\t\t\tconst unmapped = analyses.find((analysis) =>\n\t\t\t\tanalysis.requested_workspace_identity?.startsWith(\"unmapped:\"),\n\t\t\t);\n\t\t\tif (unmapped) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"unmapped_project_local_only\",\n\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\"Unmapped projects need a stable path, git remote, or workspace id before assigning a Sharing domain.\",\n\t\t\t\t\t\tguardrail_warnings: unmapped.warnings,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst missingConfirmations = analyses.flatMap((analysis) =>\n\t\t\t\tmissingGuardrailConfirmations(analysis.warnings, []),\n\t\t\t);\n\t\t\tif (missingConfirmations.length > 0) {\n\t\t\t\tconst missingCodes = [...new Set(missingConfirmations.map((warning) => warning.code))];\n\t\t\t\tconst missingTokens = [\n\t\t\t\t\t...new Set(missingConfirmations.map((warning) => warning.confirmation_token)),\n\t\t\t\t].filter((token): token is string => typeof token === \"string\" && token.length > 0);\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"guardrail_confirmation_required\",\n\t\t\t\t\t\trequired_guardrails: missingCodes,\n\t\t\t\t\t\trequired_guardrail_tokens: missingTokens,\n\t\t\t\t\t\tguardrail_warnings: analyses.flatMap((analysis) => analysis.warnings),\n\t\t\t\t\t},\n\t\t\t\t\t409,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst [deviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });\n\t\t\tconst saveMappings = store.db.transaction(() =>\n\t\t\t\tmappingInputs.map((mappingInput) =>\n\t\t\t\t\tupsertProjectScopeSettingsMapping(store.db, { deviceId, ...mappingInput }),\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn c.json({\n\t\t\t\tok: true,\n\t\t\t\tmappings: saveMappings(),\n\t\t\t\tguardrail_warnings: analyses.flatMap((analysis) => analysis.warnings),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error) }, 400);\n\t\t} finally {\n\t\t\treleasePublicationMutation?.();\n\t\t}\n\t});\n\n\tapp.delete(\"/api/sync/sharing-domains/project-mappings/:id\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst id = Number(c.req.param(\"id\"));\n\t\tlet releasePublicationMutation: (() => void) | undefined;\n\t\ttry {\n\t\t\treleasePublicationMutation = await claimRecipientPolicyPublicationMutation(store.db);\n\t\t\tconst deleted = deleteProjectScopeSettingsMapping(store.db, id);\n\t\t\treturn c.json({ ok: true, deleted });\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error) }, 400);\n\t\t} finally {\n\t\t\treleasePublicationMutation?.();\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/peers/identity\", async (c) => {\n\t\tconst store = getStore();\n\t\tensureLocalActorRecord(store);\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\" }, 400);\n\t\t}\n\t\tconst peerDeviceId = String(body.peer_device_id ?? \"\").trim();\n\t\tif (!peerDeviceId) return c.json({ error: \"peer_device_id required\" }, 400);\n\t\tconst requestedActorId =\n\t\t\tbody.actor_id == null ? undefined : String(body.actor_id ?? \"\").trim() || null;\n\t\tconst claimedLocalActor =\n\t\t\ttypeof body.claimed_local_actor === \"boolean\" ? body.claimed_local_actor : undefined;\n\t\tconst d = drizzle(store.db, { schema });\n\t\tconst peer = d\n\t\t\t.select({\n\t\t\t\tpeer_device_id: schema.syncPeers.peer_device_id,\n\t\t\t\tactor_id: schema.syncPeers.actor_id,\n\t\t\t\tclaimed_local_actor: schema.syncPeers.claimed_local_actor,\n\t\t\t})\n\t\t\t.from(schema.syncPeers)\n\t\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t\t.get();\n\t\tif (!peer) return c.json({ error: \"peer not found\" }, 404);\n\n\t\tlet nextActorId = peer.actor_id ?? null;\n\t\tlet nextClaimedLocalActor = Boolean(peer.claimed_local_actor);\n\t\tif (requestedActorId !== undefined) {\n\t\t\tnextActorId = requestedActorId;\n\t\t\tif (requestedActorId) {\n\t\t\t\tconst actor = d\n\t\t\t\t\t.select({\n\t\t\t\t\t\tactor_id: schema.actors.actor_id,\n\t\t\t\t\t\tis_local: schema.actors.is_local,\n\t\t\t\t\t\tstatus: schema.actors.status,\n\t\t\t\t\t})\n\t\t\t\t\t.from(schema.actors)\n\t\t\t\t\t.where(eq(schema.actors.actor_id, requestedActorId))\n\t\t\t\t\t.get();\n\t\t\t\tif (!actor) return c.json({ error: \"actor not found\" }, 404);\n\t\t\t\tif (actor.status !== \"active\") return c.json({ error: \"actor not active\" }, 409);\n\t\t\t\tnextClaimedLocalActor = claimedLocalActor ?? Boolean(actor.is_local);\n\t\t\t} else {\n\t\t\t\tnextClaimedLocalActor = claimedLocalActor ?? false;\n\t\t\t}\n\t\t} else if (claimedLocalActor !== undefined) {\n\t\t\tnextClaimedLocalActor = claimedLocalActor;\n\t\t\tif (claimedLocalActor) {\n\t\t\t\tnextActorId = store.actorId;\n\t\t\t} else if (nextActorId === store.actorId) {\n\t\t\t\tnextActorId = null;\n\t\t\t}\n\t\t}\n\n\t\td.update(schema.syncPeers)\n\t\t\t.set({\n\t\t\t\tactor_id: nextActorId,\n\t\t\t\tclaimed_local_actor: nextClaimedLocalActor ? 1 : 0,\n\t\t\t})\n\t\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t\t.run();\n\t\treturn c.json({ ok: true, actor_id: nextActorId, claimed_local_actor: nextClaimedLocalActor });\n\t});\n\n\tapp.post(\"/api/sync/actors\", async (c) => {\n\t\tconst store = getStore();\n\t\tensureLocalActorRecord(store);\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\" }, 400);\n\t\t}\n\t\tconst rawDisplayName = String(body.display_name ?? \"\");\n\t\tif (!rawDisplayName.trim()) return c.json({ error: \"display_name required\" }, 400);\n\t\tlet displayName: string;\n\t\ttry {\n\t\t\tdisplayName = normalizeHumanPresentationName(rawDisplayName, \"display_name\");\n\t\t} catch (error) {\n\t\t\treturn c.json(\n\t\t\t\t{ error: error instanceof Error ? error.message : \"display_name_invalid\" },\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t\tconst d = drizzle(store.db, { schema });\n\t\tconst now = new Date().toISOString();\n\t\tconst actor = {\n\t\t\tactor_id: randomUUID(),\n\t\t\tdisplay_name: displayName,\n\t\t\tis_local: 0,\n\t\t\tstatus: \"active\",\n\t\t\tmerged_into_actor_id: null,\n\t\t\tcreated_at: now,\n\t\t\tupdated_at: now,\n\t\t};\n\t\td.insert(schema.actors).values(actor).run();\n\t\treturn c.json(actor);\n\t});\n\n\tapp.post(\"/api/sync/actors/rename\", async (c) => {\n\t\tconst store = getStore();\n\t\tensureLocalActorRecord(store);\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\" }, 400);\n\t\t}\n\t\tconst actorId = String(body.actor_id ?? \"\").trim();\n\t\tif (!actorId) return c.json({ error: \"actor_id required\" }, 400);\n\t\tlet displayName: string;\n\t\ttry {\n\t\t\tdisplayName = normalizeHumanPresentationName(String(body.display_name ?? \"\"), \"display_name\");\n\t\t} catch (error) {\n\t\t\treturn c.json(\n\t\t\t\t{ error: error instanceof Error ? error.message : \"display_name_invalid\" },\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t\tconst d = drizzle(store.db, { schema });\n\t\tconst actor = d.select().from(schema.actors).where(eq(schema.actors.actor_id, actorId)).get();\n\t\tif (!actor) return c.json({ error: \"actor not found\" }, 404);\n\t\tconst updatedAt = new Date().toISOString();\n\t\td.update(schema.actors)\n\t\t\t.set({ display_name: displayName, updated_at: updatedAt })\n\t\t\t.where(eq(schema.actors.actor_id, actorId))\n\t\t\t.run();\n\t\treturn c.json({ ...actor, display_name: displayName, updated_at: updatedAt });\n\t});\n\n\tapp.post(\"/api/sync/actors/merge\", async (c) => {\n\t\tconst store = getStore();\n\t\tensureLocalActorRecord(store);\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\" }, 400);\n\t\t}\n\t\tconst primaryActorId = String(body.primary_actor_id ?? \"\").trim();\n\t\tconst secondaryActorId = String(body.secondary_actor_id ?? \"\").trim();\n\t\tif (!primaryActorId) return c.json({ error: \"primary_actor_id required\" }, 400);\n\t\tif (!secondaryActorId) return c.json({ error: \"secondary_actor_id required\" }, 400);\n\t\tif (primaryActorId === secondaryActorId) return c.json({ error: \"actor ids must differ\" }, 400);\n\t\tconst d = drizzle(store.db, { schema });\n\t\tconst releaseActorMutations = await claimRecipientPolicyActorMutations(store.db, [\n\t\t\tprimaryActorId,\n\t\t\tsecondaryActorId,\n\t\t]);\n\t\t// This transaction is synchronous. Deferring release prevents a thrown transaction\n\t\t// from leaking the lock while keeping it held through every mutation below.\n\t\tqueueMicrotask(releaseActorMutations);\n\t\tconst now = new Date().toISOString();\n\t\tconst result = store.db\n\t\t\t.transaction(() => {\n\t\t\t\tconst primary = d\n\t\t\t\t\t.select()\n\t\t\t\t\t.from(schema.actors)\n\t\t\t\t\t.where(eq(schema.actors.actor_id, primaryActorId))\n\t\t\t\t\t.get();\n\t\t\t\tconst secondary = d\n\t\t\t\t\t.select()\n\t\t\t\t\t.from(schema.actors)\n\t\t\t\t\t.where(eq(schema.actors.actor_id, secondaryActorId))\n\t\t\t\t\t.get();\n\t\t\t\tif (!primary || !secondary) return { error: \"actor not found\", status: 404 as const };\n\t\t\t\tif (primary.status !== \"active\") {\n\t\t\t\t\treturn { error: \"primary actor not active\", status: 409 as const };\n\t\t\t\t}\n\t\t\t\tif (secondary.status !== \"active\") {\n\t\t\t\t\treturn { error: \"secondary actor not active\", status: 409 as const };\n\t\t\t\t}\n\t\t\t\tif (secondary.is_local && secondary.actor_id === store.actorId) {\n\t\t\t\t\treturn { error: \"cannot merge this device's own local actor\", status: 409 as const };\n\t\t\t\t}\n\t\t\t\tconst memberships = d\n\t\t\t\t\t.select()\n\t\t\t\t\t.from(schema.policyTeamMemberships)\n\t\t\t\t\t.where(eq(schema.policyTeamMemberships.identity_id, secondaryActorId))\n\t\t\t\t\t.all();\n\t\t\t\tconst primaryMemberships = new Map<string, (typeof memberships)[number] | undefined>();\n\t\t\t\tfor (const membership of memberships) {\n\t\t\t\t\tconst primaryMembership = d\n\t\t\t\t\t\t.select()\n\t\t\t\t\t\t.from(schema.policyTeamMemberships)\n\t\t\t\t\t\t.where(\n\t\t\t\t\t\t\tand(\n\t\t\t\t\t\t\t\teq(schema.policyTeamMemberships.team_id, membership.team_id),\n\t\t\t\t\t\t\t\teq(schema.policyTeamMemberships.identity_id, primaryActorId),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.get();\n\t\t\t\t\tif (\n\t\t\t\t\t\tprimaryMembership &&\n\t\t\t\t\t\t(primaryMembership.role !== membership.role ||\n\t\t\t\t\t\t\tprimaryMembership.status !== membership.status)\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn { error: \"actor team memberships conflict\", status: 409 as const };\n\t\t\t\t\t}\n\t\t\t\t\tprimaryMemberships.set(membership.team_id, primaryMembership);\n\t\t\t\t}\n\t\t\t\tconst directRecipients = d\n\t\t\t\t\t.select()\n\t\t\t\t\t.from(schema.projectRecipients)\n\t\t\t\t\t.where(\n\t\t\t\t\t\tand(\n\t\t\t\t\t\t\teq(schema.projectRecipients.recipient_kind, \"identity\"),\n\t\t\t\t\t\t\teq(schema.projectRecipients.recipient_id, secondaryActorId),\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t\t.all();\n\t\t\t\tconst primaryRecipients = new Map<string, (typeof directRecipients)[number] | undefined>();\n\t\t\t\tfor (const recipient of directRecipients) {\n\t\t\t\t\tconst primaryRecipient = d\n\t\t\t\t\t\t.select()\n\t\t\t\t\t\t.from(schema.projectRecipients)\n\t\t\t\t\t\t.where(\n\t\t\t\t\t\t\tand(\n\t\t\t\t\t\t\t\teq(\n\t\t\t\t\t\t\t\t\tschema.projectRecipients.canonical_project_identity,\n\t\t\t\t\t\t\t\t\trecipient.canonical_project_identity,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\teq(schema.projectRecipients.recipient_kind, \"identity\"),\n\t\t\t\t\t\t\t\teq(schema.projectRecipients.recipient_id, primaryActorId),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.get();\n\t\t\t\t\tif (primaryRecipient && primaryRecipient.status !== recipient.status) {\n\t\t\t\t\t\treturn { error: \"actor project recipients conflict\", status: 409 as const };\n\t\t\t\t\t}\n\t\t\t\t\tprimaryRecipients.set(recipient.canonical_project_identity, primaryRecipient);\n\t\t\t\t}\n\n\t\t\t\tconst mergeDigest = createHash(\"sha256\")\n\t\t\t\t\t.update(\n\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\tkind: \"identity-merge-v1\",\n\t\t\t\t\t\t\tprimaryActorId,\n\t\t\t\t\t\t\tsecondaryActorId,\n\t\t\t\t\t\t\tnonce: randomUUID(),\n\t\t\t\t\t\t}),\n\t\t\t\t\t)\n\t\t\t\t\t.digest(\"hex\");\n\t\t\t\tconst bindings = d\n\t\t\t\t\t.select({\n\t\t\t\t\t\tdeviceId: schema.identityDevices.device_id,\n\t\t\t\t\t\tassignmentVersion: schema.identityDevices.assignment_version,\n\t\t\t\t\t})\n\t\t\t\t\t.from(schema.identityDevices)\n\t\t\t\t\t.where(eq(schema.identityDevices.identity_id, secondaryActorId))\n\t\t\t\t\t.all();\n\t\t\t\tif (bindings.length > 0) {\n\t\t\t\t\tconst commitDigest = mergeDigest;\n\t\t\t\t\tconst outcomes = bindings.map((binding) => ({\n\t\t\t\t\t\tdeviceId: binding.deviceId,\n\t\t\t\t\t\tpreviousIdentityId: secondaryActorId,\n\t\t\t\t\t\ttargetIdentityId: primaryActorId,\n\t\t\t\t\t\taction: \"rebind\",\n\t\t\t\t\t}));\n\t\t\t\t\tstore.db\n\t\t\t\t\t\t.prepare(`INSERT INTO device_identity_binding_commits(\n\t\t\t\t\t\tcommit_digest, reviewed_inventory_digest, request_json, outcomes_json, write_count,\n\t\t\t\t\t\tdecided_by_identity_id, decided_by_device_id, created_at\n\t\t\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`)\n\t\t\t\t\t\t.run(\n\t\t\t\t\t\t\tcommitDigest,\n\t\t\t\t\t\t\t`identity-merge:${secondaryActorId}:${primaryActorId}`,\n\t\t\t\t\t\t\tJSON.stringify({ primaryActorId, secondaryActorId }),\n\t\t\t\t\t\t\tJSON.stringify(outcomes),\n\t\t\t\t\t\t\tbindings.length,\n\t\t\t\t\t\t\tstore.actorId,\n\t\t\t\t\t\t\tstore.deviceId,\n\t\t\t\t\t\t\tnow,\n\t\t\t\t\t\t);\n\n\t\t\t\t\tfor (const binding of bindings) {\n\t\t\t\t\t\tconst revision = createHash(\"sha256\")\n\t\t\t\t\t\t\t.update(`identity-merge-revision-v1\\0${commitDigest}\\0${binding.deviceId}`)\n\t\t\t\t\t\t\t.digest(\"hex\");\n\t\t\t\t\t\tconst idempotencyKey = createHash(\"sha256\")\n\t\t\t\t\t\t\t.update(`identity-merge-row-v1\\0${commitDigest}\\0${binding.deviceId}`)\n\t\t\t\t\t\t\t.digest(\"hex\");\n\t\t\t\t\t\tconst bindingUpdate = store.db\n\t\t\t\t\t\t\t.prepare(`UPDATE identity_devices SET\n\t\t\t\t\t\t\tidentity_id = ?, provenance = 'review_resolution', revision = ?,\n\t\t\t\t\t\t\tmigration_state = 'user_managed', source_fingerprint = ?,\n\t\t\t\t\t\t\tidempotency_key = ?, updated_at = ?\n\t\t\t\t\t\t WHERE device_id = ? AND identity_id = ?`)\n\t\t\t\t\t\t\t.run(\n\t\t\t\t\t\t\t\tprimaryActorId,\n\t\t\t\t\t\t\t\trevision,\n\t\t\t\t\t\t\t\tcommitDigest,\n\t\t\t\t\t\t\t\tidempotencyKey,\n\t\t\t\t\t\t\t\tnow,\n\t\t\t\t\t\t\t\tbinding.deviceId,\n\t\t\t\t\t\t\t\tsecondaryActorId,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\tif (bindingUpdate.changes !== 1)\n\t\t\t\t\t\t\tthrow new Error(\"identity_merge_binding_update_failed\");\n\t\t\t\t\t\tconst rebound = store.db\n\t\t\t\t\t\t\t.prepare(\"SELECT assignment_version FROM identity_devices WHERE device_id = ?\")\n\t\t\t\t\t\t\t.get(binding.deviceId) as { assignment_version: number } | undefined;\n\t\t\t\t\t\tif (!rebound || rebound.assignment_version !== binding.assignmentVersion + 1) {\n\t\t\t\t\t\t\tthrow new Error(\"identity_merge_assignment_version_unexpected\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tstore.db\n\t\t\t\t\t\t\t.prepare(\"DELETE FROM policy_team_device_decisions WHERE device_id = ?\")\n\t\t\t\t\t\t\t.run(binding.deviceId);\n\t\t\t\t\t\tstore.db\n\t\t\t\t\t\t\t.prepare(`INSERT INTO device_identity_binding_audit(\n\t\t\t\t\t\t\tevent_id, commit_digest, device_id, previous_identity_id, target_identity_id,\n\t\t\t\t\t\t\taction, previous_assignment_version, resulting_assignment_version,\n\t\t\t\t\t\t\tdecided_by_identity_id, decided_by_device_id, created_at\n\t\t\t\t\t\t) VALUES (?, ?, ?, ?, ?, 'rebind', ?, ?, ?, ?, ?)`)\n\t\t\t\t\t\t\t.run(\n\t\t\t\t\t\t\t\tcreateHash(\"sha256\")\n\t\t\t\t\t\t\t\t\t.update(`identity-merge-event-v1\\0${commitDigest}\\0${binding.deviceId}`)\n\t\t\t\t\t\t\t\t\t.digest(\"hex\"),\n\t\t\t\t\t\t\t\tcommitDigest,\n\t\t\t\t\t\t\t\tbinding.deviceId,\n\t\t\t\t\t\t\t\tsecondaryActorId,\n\t\t\t\t\t\t\t\tprimaryActorId,\n\t\t\t\t\t\t\t\tbinding.assignmentVersion,\n\t\t\t\t\t\t\t\trebound.assignment_version,\n\t\t\t\t\t\t\t\tstore.actorId,\n\t\t\t\t\t\t\t\tstore.deviceId,\n\t\t\t\t\t\t\t\tnow,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfor (const membership of memberships) {\n\t\t\t\t\tconst primaryMembership = primaryMemberships.get(membership.team_id);\n\t\t\t\t\tif (primaryMembership) {\n\t\t\t\t\t\td.delete(schema.policyTeamMemberships)\n\t\t\t\t\t\t\t.where(\n\t\t\t\t\t\t\t\tand(\n\t\t\t\t\t\t\t\t\teq(schema.policyTeamMemberships.team_id, membership.team_id),\n\t\t\t\t\t\t\t\t\teq(schema.policyTeamMemberships.identity_id, secondaryActorId),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.run();\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst revision = createHash(\"sha256\")\n\t\t\t\t\t\t.update(`identity-merge-membership-revision-v1\\0${mergeDigest}\\0${membership.team_id}`)\n\t\t\t\t\t\t.digest(\"hex\");\n\t\t\t\t\tconst idempotencyKey = createHash(\"sha256\")\n\t\t\t\t\t\t.update(`identity-merge-membership-row-v1\\0${mergeDigest}\\0${membership.team_id}`)\n\t\t\t\t\t\t.digest(\"hex\");\n\t\t\t\t\td.update(schema.policyTeamMemberships)\n\t\t\t\t\t\t.set({\n\t\t\t\t\t\t\tidentity_id: primaryActorId,\n\t\t\t\t\t\t\tprovenance: \"review_resolution\",\n\t\t\t\t\t\t\trevision,\n\t\t\t\t\t\t\tmigration_state: \"user_managed\",\n\t\t\t\t\t\t\tsource_fingerprint: mergeDigest,\n\t\t\t\t\t\t\tidempotency_key: idempotencyKey,\n\t\t\t\t\t\t\tupdated_at: now,\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.where(\n\t\t\t\t\t\t\tand(\n\t\t\t\t\t\t\t\teq(schema.policyTeamMemberships.team_id, membership.team_id),\n\t\t\t\t\t\t\t\teq(schema.policyTeamMemberships.identity_id, secondaryActorId),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.run();\n\t\t\t\t}\n\t\t\t\tfor (const recipient of directRecipients) {\n\t\t\t\t\tconst primaryRecipient = primaryRecipients.get(recipient.canonical_project_identity);\n\t\t\t\t\tif (primaryRecipient) {\n\t\t\t\t\t\td.delete(schema.projectRecipients)\n\t\t\t\t\t\t\t.where(\n\t\t\t\t\t\t\t\tand(\n\t\t\t\t\t\t\t\t\teq(\n\t\t\t\t\t\t\t\t\t\tschema.projectRecipients.canonical_project_identity,\n\t\t\t\t\t\t\t\t\t\trecipient.canonical_project_identity,\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\teq(schema.projectRecipients.recipient_kind, \"identity\"),\n\t\t\t\t\t\t\t\t\teq(schema.projectRecipients.recipient_id, secondaryActorId),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.run();\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst policyRevision = createHash(\"sha256\")\n\t\t\t\t\t\t.update(\n\t\t\t\t\t\t\t`identity-merge-recipient-revision-v1\\0${mergeDigest}\\0${recipient.canonical_project_identity}`,\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.digest(\"hex\");\n\t\t\t\t\tconst idempotencyKey = createHash(\"sha256\")\n\t\t\t\t\t\t.update(\n\t\t\t\t\t\t\t`identity-merge-recipient-row-v1\\0${mergeDigest}\\0${recipient.canonical_project_identity}`,\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.digest(\"hex\");\n\t\t\t\t\td.update(schema.projectRecipients)\n\t\t\t\t\t\t.set({\n\t\t\t\t\t\t\trecipient_id: primaryActorId,\n\t\t\t\t\t\t\tprovenance: \"review_resolution\",\n\t\t\t\t\t\t\tpolicy_revision: policyRevision,\n\t\t\t\t\t\t\tmigration_state: \"user_managed\",\n\t\t\t\t\t\t\tsource_fingerprint: mergeDigest,\n\t\t\t\t\t\t\tidempotency_key: idempotencyKey,\n\t\t\t\t\t\t\tupdated_at: now,\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.where(\n\t\t\t\t\t\t\tand(\n\t\t\t\t\t\t\t\teq(\n\t\t\t\t\t\t\t\t\tschema.projectRecipients.canonical_project_identity,\n\t\t\t\t\t\t\t\t\trecipient.canonical_project_identity,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\teq(schema.projectRecipients.recipient_kind, \"identity\"),\n\t\t\t\t\t\t\t\teq(schema.projectRecipients.recipient_id, secondaryActorId),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.run();\n\t\t\t\t}\n\t\t\t\td.update(schema.recipientManagedProjectProjections)\n\t\t\t\t\t.set({ recipient_identity_id: primaryActorId, updated_at: now })\n\t\t\t\t\t.where(\n\t\t\t\t\t\teq(schema.recipientManagedProjectProjections.recipient_identity_id, secondaryActorId),\n\t\t\t\t\t)\n\t\t\t\t\t.run();\n\t\t\t\tstore.db\n\t\t\t\t\t.prepare(`UPDATE share_operations SET\n\t\t\t\t\t\tinviter_actor_id = CASE WHEN inviter_actor_id = ? THEN ? ELSE inviter_actor_id END,\n\t\t\t\t\t\trecipient_actor_id = CASE WHEN recipient_actor_id = ? THEN ? ELSE recipient_actor_id END,\n\t\t\t\t\t\tperson_id = CASE WHEN person_id = ? THEN ? ELSE person_id END,\n\t\t\t\t\t\tupdated_at = ?\n\t\t\t\t\t WHERE inviter_actor_id = ? OR recipient_actor_id = ? OR person_id = ?`)\n\t\t\t\t\t.run(\n\t\t\t\t\t\tsecondaryActorId,\n\t\t\t\t\t\tprimaryActorId,\n\t\t\t\t\t\tsecondaryActorId,\n\t\t\t\t\t\tprimaryActorId,\n\t\t\t\t\t\tsecondaryActorId,\n\t\t\t\t\t\tprimaryActorId,\n\t\t\t\t\t\tnow,\n\t\t\t\t\t\tsecondaryActorId,\n\t\t\t\t\t\tsecondaryActorId,\n\t\t\t\t\t\tsecondaryActorId,\n\t\t\t\t\t);\n\n\t\t\t\tconst peerUpdate = d\n\t\t\t\t\t.update(schema.syncPeers)\n\t\t\t\t\t.set({ actor_id: primaryActorId })\n\t\t\t\t\t.where(eq(schema.syncPeers.actor_id, secondaryActorId))\n\t\t\t\t\t.run();\n\t\t\t\tif (primary.is_local) {\n\t\t\t\t\td.update(schema.syncPeers)\n\t\t\t\t\t\t.set({ claimed_local_actor: 1 })\n\t\t\t\t\t\t.where(eq(schema.syncPeers.actor_id, primaryActorId))\n\t\t\t\t\t\t.run();\n\t\t\t\t}\n\t\t\t\td.update(schema.actors)\n\t\t\t\t\t.set({ status: \"merged\", merged_into_actor_id: primaryActorId, updated_at: now })\n\t\t\t\t\t.where(eq(schema.actors.actor_id, secondaryActorId))\n\t\t\t\t\t.run();\n\t\t\t\treturn { mergedCount: Number(peerUpdate.changes ?? 0) };\n\t\t\t})\n\t\t\t.immediate();\n\t\tif (\"error\" in result) return c.json({ error: result.error }, result.status);\n\t\treturn c.json({ merged_count: result.mergedCount });\n\t});\n\n\tapp.post(\"/api/sync/actors/deactivate\", async (c) => {\n\t\tconst store = getStore();\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\" }, 400);\n\t\t}\n\t\tconst actorId = String(body.actor_id ?? \"\").trim();\n\t\tif (!actorId) return c.json({ error: \"actor_id required\" }, 400);\n\t\tif (actorId === store.actorId) {\n\t\t\treturn c.json({ error: \"cannot deactivate this device's own local actor\" }, 409);\n\t\t}\n\t\tconst releaseActorMutations = await claimRecipientPolicyActorMutations(store.db, [actorId]);\n\t\t// All following reads and writes are synchronous, so release after this turn.\n\t\tqueueMicrotask(releaseActorMutations);\n\t\tconst d = drizzle(store.db, { schema });\n\t\tconst actor = d.select().from(schema.actors).where(eq(schema.actors.actor_id, actorId)).get();\n\t\tif (!actor) return c.json({ error: \"actor not found\" }, 404);\n\t\tif (actor.status !== \"active\") return c.json({ error: \"actor not active\" }, 409);\n\t\tconst now = new Date().toISOString();\n\t\td.update(schema.actors)\n\t\t\t.set({ status: \"deactivated\", updated_at: now })\n\t\t\t.where(eq(schema.actors.actor_id, actorId))\n\t\t\t.run();\n\t\td.update(schema.syncPeers)\n\t\t\t.set({ actor_id: null })\n\t\t\t.where(eq(schema.syncPeers.actor_id, actorId))\n\t\t\t.run();\n\t\treturn c.json({ ok: true });\n\t});\n\n\tapp.post(\"/api/sync/legacy-devices/claim\", async (c) => {\n\t\tconst store = getStore();\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\" }, 400);\n\t\t}\n\t\tconst originDeviceId = String(body.origin_device_id ?? \"\").trim();\n\t\tif (!originDeviceId) return c.json({ error: \"origin_device_id required\" }, 400);\n\t\tconst updated = claimLegacyDeviceAsSelf(store, originDeviceId);\n\t\tif (updated <= 0) return c.json({ error: \"legacy device not found\" }, 404);\n\t\treturn c.json({ ok: true, origin_device_id: originDeviceId, updated });\n\t});\n\n\tapp.post(\"/api/sync/peers/accept-discovered\", async (c) => {\n\t\tconst store = getStore();\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\" }, 400);\n\t\t}\n\t\tconst peerDeviceId = String(body.peer_device_id ?? \"\").trim();\n\t\tconst fingerprint = String(body.fingerprint ?? \"\").trim();\n\t\tconst expectedGroupId = String(body.expected_group_id ?? \"\").trim();\n\t\tconst hasExpectedIncomingRequestId = Object.hasOwn(body, \"expected_incoming_request_id\");\n\t\tconst expectedIncomingRequestId = String(body.expected_incoming_request_id ?? \"\").trim();\n\t\tif (!peerDeviceId) return c.json({ error: \"peer_device_id required\" }, 400);\n\t\tif (hasExpectedIncomingRequestId && !expectedIncomingRequestId) {\n\t\t\treturn c.json({ error: \"expected_incoming_request_id must not be empty\" }, 400);\n\t\t}\n\t\tif (expectedIncomingRequestId && !expectedGroupId) {\n\t\t\treturn c.json({ error: \"expected_group_id required\" }, 400);\n\t\t}\n\t\ttry {\n\t\t\tconst result = await acceptDiscoveredPeer(store, {\n\t\t\t\tpeerDeviceId,\n\t\t\t\tfingerprint: fingerprint || undefined,\n\t\t\t\texpectedGroupId: expectedGroupId || undefined,\n\t\t\t\texpectedIncomingRequestId: expectedIncomingRequestId || undefined,\n\t\t\t});\n\t\t\tif (!result.ok) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: result.error,\n\t\t\t\t\t\tdetail: result.detail,\n\t\t\t\t\t\t...(result.reason ? { reason: result.reason } : {}),\n\t\t\t\t\t},\n\t\t\t\t\t{ status: result.status as 400 | 404 | 409 },\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn c.json({\n\t\t\t\tok: true,\n\t\t\t\tpeer_device_id: result.peer_device_id,\n\t\t\t\tcreated: result.created,\n\t\t\t\tupdated: result.updated,\n\t\t\t\tname: result.name,\n\t\t\t\tneeds_scope_review: true,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error instanceof CoordinatorReciprocalApprovalRequestChangedError) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: error.code,\n\t\t\t\t\t\tdetail:\n\t\t\t\t\t\t\t\"This approval request changed before it was submitted. Refresh sync status and review the current request.\",\n\t\t\t\t\t},\n\t\t\t\t\t{ status: 409 },\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn c.json(\n\t\t\t\t{\n\t\t\t\t\terror: \"coordinator_lookup_failed\",\n\t\t\t\t\tdetail: error instanceof Error ? error.message : String(error),\n\t\t\t\t},\n\t\t\t\t{ status: 502 },\n\t\t\t);\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/invites/create\", async (c) => {\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\" }, 400);\n\t\t}\n\t\tconst groupId = String(body.group_id ?? \"\").trim();\n\t\tconst coordinatorUrl = body.coordinator_url == null ? null : String(body.coordinator_url ?? \"\");\n\t\tconst policy = String(body.policy ?? \"auto_admit\").trim();\n\t\tconst ttlHours = parseInviteTtlHours(body.ttl_hours);\n\t\tif (!groupId) return c.json({ error: \"group_id required\" }, 400);\n\t\tif (body.coordinator_url != null && typeof body.coordinator_url !== \"string\") {\n\t\t\treturn c.json({ error: \"coordinator_url must be string\" }, 400);\n\t\t}\n\t\tif (![\"auto_admit\", \"approval_required\"].includes(policy)) {\n\t\t\treturn c.json({ error: \"policy must be auto_admit or approval_required\" }, 400);\n\t\t}\n\t\tif (ttlHours == null) return c.json({ error: \"ttl_hours must be an integer >= 1\" }, 400);\n\t\ttry {\n\t\t\tconst config = readCoordinatorSyncConfig();\n\t\t\tconst result = await coordinatorCreateInviteAction({\n\t\t\t\tgroupId,\n\t\t\t\tcoordinatorUrl,\n\t\t\t\tpolicy,\n\t\t\t\tttlHours,\n\t\t\t\tcreatedBy: null,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\treturn c.json(result);\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error) }, 400);\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/invites/inspect\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst body = await parseViewerJsonBody(c);\n\t\tif (!body || typeof body.invite !== \"string\") return c.json({ error: \"invite_invalid\" }, 400);\n\t\ttry {\n\t\t\tconst payload = decodeInvitePayload(extractInvitePayload(body.invite));\n\t\t\tconst recipientInvite = payload.kind === \"team_member\" || payload.kind === \"add_device\";\n\t\t\tif (recipientInvite) ensureStableStoreDeviceIdentity(store);\n\t\t\telse ensureStableStoreIdentity(store);\n\t\t\tif (!payload.operation_id && !recipientInvite) return c.json({ kind: \"legacy_team_invite\" });\n\t\t\tconst [status, inspected] = await requestJson(\n\t\t\t\t\"POST\",\n\t\t\t\t`${buildBaseUrl(payload.coordinator_url)}/v1/invites/inspect`,\n\t\t\t\t{ body: { token: payload.token }, timeoutS: 10 },\n\t\t\t);\n\t\t\tif (status < 200 || status >= 300) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: recipientInvite\n\t\t\t\t\t\t\t? safeRecipientInviteError(inspected?.error)\n\t\t\t\t\t\t\t: String(inspected?.error ?? \"invite_invalid\"),\n\t\t\t\t\t},\n\t\t\t\t\tstatus === 410 ? 410 : 400,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst config = readCodememConfigFile();\n\t\t\tconst identityId = recipientInvite\n\t\t\t\t? recipientInviteAuthoritativeIdentityId({\n\t\t\t\t\t\tkind: payload.kind as \"team_member\" | \"add_device\",\n\t\t\t\t\t\tassigned_identity_id: inspected?.assigned_identity_id,\n\t\t\t\t\t\ttarget_identity_id: inspected?.target_identity_id,\n\t\t\t\t\t})\n\t\t\t\t: store.actorId;\n\t\t\tconst expectedTarget =\n\t\t\t\tpayload.kind === \"team_member\"\n\t\t\t\t\t? String(inspected?.policy_team_id ?? \"\").trim()\n\t\t\t\t\t: String(inspected?.target_identity_id ?? \"\").trim();\n\t\t\tif (recipientInvite) {\n\t\t\t\tif (\n\t\t\t\t\tString(inspected?.kind ?? \"\").trim() !== payload.kind ||\n\t\t\t\t\t!expectedTarget ||\n\t\t\t\t\tString(inspected?.reviewed_preview_digest ?? \"\").trim() !==\n\t\t\t\t\t\tString(payload.reviewed_preview_digest ?? \"\").trim() ||\n\t\t\t\t\t(payload.kind === \"team_member\" && expectedTarget !== payload.policy_team_id) ||\n\t\t\t\t\t(payload.kind === \"team_member\" &&\n\t\t\t\t\t\t(identityId !== String(payload.assigned_identity_id ?? \"\").trim() || !identityId)) ||\n\t\t\t\t\t(payload.kind === \"add_device\" && expectedTarget !== payload.target_identity_id)\n\t\t\t\t) {\n\t\t\t\t\treturn c.json({ error: \"recipient_invite_intent_mismatch\" }, 409);\n\t\t\t\t}\n\t\t\t\tif (inspected?.reviewed_intent == null) {\n\t\t\t\t\treturn c.json({ error: \"recipient_invite_review_unavailable\" }, 409);\n\t\t\t\t}\n\t\t\t\tlet reviewedIntent: RecipientReviewedIntentV1;\n\t\t\t\ttry {\n\t\t\t\t\treviewedIntent = await verifyRecipientReviewedIntent(inspected.reviewed_intent, {\n\t\t\t\t\t\ttarget:\n\t\t\t\t\t\t\tpayload.kind === \"team_member\"\n\t\t\t\t\t\t\t\t? { kind: \"team_member\", policyTeamId: expectedTarget }\n\t\t\t\t\t\t\t\t: { kind: \"add_device\", targetIdentityId: expectedTarget },\n\t\t\t\t\t\tdigest: String(payload.reviewed_preview_digest ?? \"\").trim(),\n\t\t\t\t\t});\n\t\t\t\t} catch {\n\t\t\t\t\treturn c.json({ error: \"recipient_invite_intent_mismatch\" }, 409);\n\t\t\t\t}\n\t\t\t\tconst preview = recipientInviteOnboardingPreviewFromReviewedIntent(\n\t\t\t\t\tstore,\n\t\t\t\t\t{\n\t\t\t\t\t\tkind: payload.kind,\n\t\t\t\t\t\tpolicy_team_id: payload.kind === \"team_member\" ? expectedTarget : null,\n\t\t\t\t\t\tassigned_identity_id: payload.kind === \"team_member\" ? identityId : null,\n\t\t\t\t\t\ttarget_identity_id: payload.kind === \"add_device\" ? identityId : null,\n\t\t\t\t\t\tdevice_name: optionalViewerString(body, \"device_name\"),\n\t\t\t\t\t},\n\t\t\t\t\tString(payload.token),\n\t\t\t\t\treviewedIntent,\n\t\t\t\t);\n\t\t\t\treturn c.json({\n\t\t\t\t\t...inspected,\n\t\t\t\t\trecipient_name:\n\t\t\t\t\t\treviewedIntent.journey === \"add_device\"\n\t\t\t\t\t\t\t? reviewedIntent.targetIdentity.displayName\n\t\t\t\t\t\t\t: store.actorDisplayName,\n\t\t\t\t\tdevice_name: preview.binding.deviceDisplayName,\n\t\t\t\t\tonboarding: preview,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn c.json({\n\t\t\t\t...inspected,\n\t\t\t\trecipient_name: store.actorDisplayName,\n\t\t\t\tdevice_name: friendlyDeviceName({\n\t\t\t\t\texplicitName: String(config.sync_device_name ?? \"\"),\n\t\t\t\t\tosName: hostname(),\n\t\t\t\t\tfallbackSeed: store.deviceId,\n\t\t\t\t}),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: safeRecipientInviteError(error) }, 400);\n\t\t}\n\t});\n\n\t// POST /api/sync/invites/import accepts both team invites (coordinator\n\t// invite envelope or codemem:// link) and device-pairing payloads\n\t// (base64 JSON with { device_id, fingerprint, public_key, addresses }).\n\t// The server discriminates by decoding the pasted text — UI callers get\n\t// one textarea for all flows. Response type distinguishes legacy Team joins,\n\t// exact-Project pending setup, recipient onboarding, and direct pairing.\n\tapp.post(\"/api/sync/invites/import\", async (c) => {\n\t\tconst store = getStore();\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\" }, 400);\n\t\t}\n\t\tconst rawValue = String(body.invite ?? \"\").trim();\n\t\tif (!rawValue) return c.json({ error: \"invite required\" }, 400);\n\n\t\t// Users often paste the whole shell command emitted by the Pairing\n\t\t// diagnostics disclosure (`echo '<b64>' | base64 -d | codemem sync\n\t\t// pair --accept-file -`). Peel the base64 out if we see that shape.\n\t\tconst shellMatch = rawValue.match(\n\t\t\t/echo\\s+['\"]([A-Za-z0-9+/=]+)['\"]\\s*\\|\\s*base64\\s+-d\\s*\\|\\s*codemem/,\n\t\t);\n\t\tconst normalized = shellMatch?.[1]?.trim() || rawValue;\n\n\t\tconst pairingResult = tryParsePairingPayload(normalized);\n\t\tif (pairingResult?.kind === \"invalid-pair\") {\n\t\t\treturn c.json({ error: pairingResult.error }, 400);\n\t\t}\n\t\tif (pairingResult?.kind === \"pair\") {\n\t\t\ttry {\n\t\t\t\tconst d = drizzle(store.db, { schema });\n\t\t\t\tconst existing = d\n\t\t\t\t\t.select({ pinned_fingerprint: schema.syncPeers.pinned_fingerprint })\n\t\t\t\t\t.from(schema.syncPeers)\n\t\t\t\t\t.where(eq(schema.syncPeers.peer_device_id, pairingResult.device_id))\n\t\t\t\t\t.get();\n\t\t\t\tconst existingFingerprint = String(existing?.pinned_fingerprint ?? \"\").trim();\n\t\t\t\tif (existingFingerprint && existingFingerprint !== pairingResult.fingerprint) {\n\t\t\t\t\treturn c.json(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\terror: \"peer_conflict\",\n\t\t\t\t\t\t\tdetail:\n\t\t\t\t\t\t\t\t\"Pairing payload conflicts with the existing trusted fingerprint for this device. Remove or repair the old peer before accepting this pairing payload.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t409,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tupdatePeerAddresses(store.db, pairingResult.device_id, pairingResult.addresses, {\n\t\t\t\t\tpinnedFingerprint: pairingResult.fingerprint,\n\t\t\t\t\tpublicKey: pairingResult.public_key,\n\t\t\t\t\treplaceTrust: true,\n\t\t\t\t});\n\t\t\t\treturn c.json({\n\t\t\t\t\tok: true,\n\t\t\t\t\ttype: \"pair\",\n\t\t\t\t\tpeer_device_id: pairingResult.device_id,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error) }, 400);\n\t\t\t}\n\t\t}\n\n\t\tlet projectInvite = false;\n\t\tlet recipientInvite = false;\n\t\ttry {\n\t\t\tconst decoded = decodeInvitePayload(extractInvitePayload(rawValue));\n\t\t\tprojectInvite = Boolean(decoded.operation_id);\n\t\t\trecipientInvite = decoded.kind === \"team_member\" || decoded.kind === \"add_device\";\n\t\t\tif (recipientInvite) ensureStableStoreDeviceIdentity(store);\n\t\t\telse ensureStableStoreIdentity(store);\n\t\t\tconst reviewedOnboardingDigest =\n\t\t\t\ttypeof body.reviewed_onboarding_digest === \"string\"\n\t\t\t\t\t? body.reviewed_onboarding_digest.trim()\n\t\t\t\t\t: \"\";\n\t\t\tif (recipientInvite && !reviewedOnboardingDigest) {\n\t\t\t\treturn c.json({ error: \"reviewed_onboarding_digest_required\" }, 400);\n\t\t\t}\n\t\t\tconst result = await coordinatorImportInviteAction({\n\t\t\t\tinviteValue: rawValue,\n\t\t\t\tdbPath: store.dbPath,\n\t\t\t\trecipientActorId: recipientInvite ? null : store.actorId,\n\t\t\t\trecipientDisplayName:\n\t\t\t\t\tdecoded.kind === \"add_device\"\n\t\t\t\t\t\t? null\n\t\t\t\t\t\t: typeof body.recipient_name === \"string\"\n\t\t\t\t\t\t\t? body.recipient_name\n\t\t\t\t\t\t\t: store.actorDisplayName,\n\t\t\t\tdeviceDisplayName: typeof body.device_name === \"string\" ? body.device_name : null,\n\t\t\t\treviewedOnboardingDigest: reviewedOnboardingDigest || null,\n\t\t\t});\n\t\t\tconst type = recipientInvite\n\t\t\t\t? \"recipient_onboarding\"\n\t\t\t\t: projectInvite\n\t\t\t\t\t? \"project_share\"\n\t\t\t\t\t: \"team_join\";\n\t\t\tif (recipientInvite) {\n\t\t\t\tconst persistedIdentityId = String(result.identity_id ?? \"\").trim();\n\t\t\t\tif (!store.refreshPersistedLocalIdentity(persistedIdentityId)) {\n\t\t\t\t\treturn c.json(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t...result,\n\t\t\t\t\t\t\ttype,\n\t\t\t\t\t\t\tsetup_state: \"restart_required\",\n\t\t\t\t\t\t\trestart_required: true,\n\t\t\t\t\t\t\tdetail:\n\t\t\t\t\t\t\t\t\"The invitation was accepted and the reviewed Identity was persisted, but this process could not safely adopt it. Restart codemem before continuing.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t200,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ((projectInvite || recipientInvite) && getSyncRuntimeStatus?.()?.phase === \"disabled\") {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\t...result,\n\t\t\t\t\t\ttype,\n\t\t\t\t\t\tsetup_state: \"restart_required\",\n\t\t\t\t\t\trestart_required: true,\n\t\t\t\t\t\tdetail: projectInvite\n\t\t\t\t\t\t\t? \"The invitation was accepted and sync was enabled. Restart codemem to start the sync service; Project setup remains pending until the first sync finishes.\"\n\t\t\t\t\t\t\t: \"The invitation was accepted and sync was enabled. Restart codemem to start the sync service and receive the reviewed Projects.\",\n\t\t\t\t\t},\n\t\t\t\t\t200,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn c.json({\n\t\t\t\t...result,\n\t\t\t\ttype,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (projectInvite) return c.json(projectInviteAcceptanceFailure(error), 400);\n\t\t\tif (recipientInvite) return c.json({ error: safeRecipientInviteError(error) }, 400);\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error) }, 400);\n\t\t}\n\t});\n\n\tapp.get(\"/api/coordinator/admin/status\", async (c) => {\n\t\tconst status = coordinatorAdminStatusPayload();\n\t\treturn c.json(status);\n\t});\n\n\tapp.get(\"/api/coordinator/admin/groups\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tif (!status.has_admin_secret) {\n\t\t\treturn c.json({ error: \"coordinator_admin_secret_missing\", status }, 400);\n\t\t}\n\t\tconst includeArchived = queryBool(c.req.query(\"include_archived\"));\n\t\ttry {\n\t\t\tconst items = await coordinatorListGroupsAction({\n\t\t\t\tincludeArchived,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\treturn c.json({ items, status });\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"unknown\";\n\t\t\treturn c.json({ error: message, status }, coordinatorAdminMutationStatus(message));\n\t\t}\n\t});\n\n\tapp.post(\"/api/coordinator/admin/groups\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tif (!status.has_admin_secret) {\n\t\t\treturn c.json({ error: \"coordinator_admin_secret_missing\", status }, 400);\n\t\t}\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\", status }, 400);\n\t\t}\n\t\tconst groupId = String(body.group_id ?? \"\").trim();\n\t\tconst displayName = String(body.display_name ?? \"\").trim() || null;\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\ttry {\n\t\t\tconst group = await coordinatorCreateGroupAction({\n\t\t\t\tgroupId,\n\t\t\t\tdisplayName,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\ttry {\n\t\t\t\tconst defaultSpace = await ensureDefaultSpaceForTeam({\n\t\t\t\t\tstore: getStore(),\n\t\t\t\t\tconfig,\n\t\t\t\t\tgroupId,\n\t\t\t\t\tdisplayName: displayName || group.display_name || null,\n\t\t\t\t});\n\t\t\t\treturn c.json({ ok: true, group, default_space: defaultSpace, status });\n\t\t\t} catch (setupError) {\n\t\t\t\treturn c.json({\n\t\t\t\t\tok: true,\n\t\t\t\t\tgroup,\n\t\t\t\t\tdefault_space: null,\n\t\t\t\t\tsetup_warning: {\n\t\t\t\t\t\tstep: \"default_space\",\n\t\t\t\t\t\terror: setupError instanceof Error ? setupError.message : String(setupError),\n\t\t\t\t\t},\n\t\t\t\t\tstatus,\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error), status }, 400);\n\t\t}\n\t});\n\n\tapp.post(\"/api/coordinator/admin/groups/:group_id/rename\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tif (!status.has_admin_secret) {\n\t\t\treturn c.json({ error: \"coordinator_admin_secret_missing\", status }, 400);\n\t\t}\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\", status }, 400);\n\t\t}\n\t\tconst displayName = String(body.display_name ?? \"\").trim();\n\t\tif (!displayName) return c.json({ error: \"display_name required\", status }, 400);\n\t\ttry {\n\t\t\tconst group = await coordinatorRenameGroupAction({\n\t\t\t\tgroupId,\n\t\t\t\tdisplayName,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\tif (!group) return c.json({ error: \"group_not_found\", status }, 404);\n\t\t\treturn c.json({ ok: true, group, status });\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error), status }, 400);\n\t\t}\n\t});\n\n\tapp.post(\"/api/coordinator/admin/groups/:group_id/archive\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tif (!status.has_admin_secret) {\n\t\t\treturn c.json({ error: \"coordinator_admin_secret_missing\", status }, 400);\n\t\t}\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\ttry {\n\t\t\tconst group = await coordinatorArchiveGroupAction({\n\t\t\t\tgroupId,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\tif (!group) return c.json({ error: \"group_not_found_or_already_archived\", status }, 404);\n\t\t\tconst groups = removeConfiguredCoordinatorGroup(groupId);\n\t\t\treturn c.json({\n\t\t\t\tok: true,\n\t\t\t\tgroup,\n\t\t\t\tstatus: coordinatorAdminStatusPayload(),\n\t\t\t\tdisconnected_group_id: groupId,\n\t\t\t\tgroups,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error), status }, 400);\n\t\t}\n\t});\n\n\tapp.post(\"/api/coordinator/admin/groups/:group_id/unarchive\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tif (!status.has_admin_secret) {\n\t\t\treturn c.json({ error: \"coordinator_admin_secret_missing\", status }, 400);\n\t\t}\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\ttry {\n\t\t\tconst group = await coordinatorUnarchiveGroupAction({\n\t\t\t\tgroupId,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\tif (!group) return c.json({ error: \"group_not_found_or_not_archived\", status }, 404);\n\t\t\treturn c.json({ ok: true, group, status });\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error), status }, 400);\n\t\t}\n\t});\n\n\tapp.get(\"/api/coordinator/admin/groups/:group_id/scopes\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tconst unavailable = coordinatorAdminUnavailable(status);\n\t\tif (unavailable) return c.json(unavailable.body, unavailable.httpStatus);\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\ttry {\n\t\t\tconst items = await coordinatorListScopesAction({\n\t\t\t\tgroupId,\n\t\t\t\tincludeInactive: queryBool(c.req.query(\"include_inactive\")),\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\treturn c.json({ items, group_id: groupId, status });\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"unknown\";\n\t\t\treturn c.json({ error: message, status }, coordinatorAdminMutationStatus(message));\n\t\t}\n\t});\n\n\tapp.post(\"/api/coordinator/admin/groups/:group_id/scopes\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tconst unavailable = coordinatorAdminUnavailable(status);\n\t\tif (unavailable) return c.json(unavailable.body, unavailable.httpStatus);\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\tconst body = await parseViewerJsonBody(c);\n\t\tif (!body) return c.json({ error: \"invalid json\", status }, 400);\n\t\tconst scopeId = optionalViewerString(body, \"scope_id\");\n\t\tconst label = optionalViewerString(body, \"label\");\n\t\tconst membershipEpoch = optionalViewerNumber(body, \"membership_epoch\");\n\t\tif (!scopeId || !label) return c.json({ error: \"scope_id and label required\", status }, 400);\n\t\tif (Number.isNaN(membershipEpoch)) {\n\t\t\treturn c.json({ error: \"membership_epoch must be number\", status }, 400);\n\t\t}\n\t\ttry {\n\t\t\tconst scope = await coordinatorCreateScopeAction({\n\t\t\t\tgroupId,\n\t\t\t\tscopeId,\n\t\t\t\tlabel,\n\t\t\t\tkind: optionalViewerString(body, \"kind\"),\n\t\t\t\tauthorityType: optionalViewerString(body, \"authority_type\"),\n\t\t\t\tcoordinatorId: optionalViewerString(body, \"coordinator_id\"),\n\t\t\t\tmanifestIssuerDeviceId: optionalViewerString(body, \"manifest_issuer_device_id\"),\n\t\t\t\tmembershipEpoch,\n\t\t\t\tmanifestHash: optionalViewerString(body, \"manifest_hash\"),\n\t\t\t\tstatus: optionalViewerString(body, \"status\"),\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\treturn c.json({ ok: true, scope, group_id: groupId, status });\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\treturn c.json({ error: message, status }, coordinatorAdminMutationStatus(message));\n\t\t}\n\t});\n\n\tapp.patch(\"/api/coordinator/admin/groups/:group_id/scopes/:scope_id\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tconst unavailable = coordinatorAdminUnavailable(status);\n\t\tif (unavailable) return c.json(unavailable.body, unavailable.httpStatus);\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tconst scopeId = String(c.req.param(\"scope_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\tif (!scopeId) return c.json({ error: \"scope_id required\", status }, 400);\n\t\tconst body = await parseViewerJsonBody(c);\n\t\tif (!body) return c.json({ error: \"invalid json\", status }, 400);\n\t\tconst membershipEpoch = optionalViewerNumber(body, \"membership_epoch\");\n\t\tif (Number.isNaN(membershipEpoch)) {\n\t\t\treturn c.json({ error: \"membership_epoch must be number\", status }, 400);\n\t\t}\n\t\ttry {\n\t\t\tconst scope = await coordinatorUpdateScopeAction({\n\t\t\t\tgroupId,\n\t\t\t\tscopeId,\n\t\t\t\tlabel: body.label === undefined ? undefined : optionalViewerString(body, \"label\"),\n\t\t\t\tkind: body.kind === undefined ? undefined : optionalViewerString(body, \"kind\"),\n\t\t\t\tauthorityType:\n\t\t\t\t\tbody.authority_type === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: optionalViewerString(body, \"authority_type\"),\n\t\t\t\tcoordinatorId:\n\t\t\t\t\tbody.coordinator_id === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: optionalViewerString(body, \"coordinator_id\"),\n\t\t\t\tmanifestIssuerDeviceId:\n\t\t\t\t\tbody.manifest_issuer_device_id === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: optionalViewerString(body, \"manifest_issuer_device_id\"),\n\t\t\t\tmembershipEpoch,\n\t\t\t\tmanifestHash:\n\t\t\t\t\tbody.manifest_hash === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: optionalViewerString(body, \"manifest_hash\"),\n\t\t\t\tstatus: body.status === undefined ? undefined : optionalViewerString(body, \"status\"),\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\tif (!scope) return c.json({ error: \"scope_not_found\", status }, 404);\n\t\t\treturn c.json({ ok: true, scope, group_id: groupId, status });\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\treturn c.json({ error: message, status }, coordinatorAdminMutationStatus(message));\n\t\t}\n\t});\n\n\tapp.get(\"/api/coordinator/admin/groups/:group_id/scopes/:scope_id/members\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tconst unavailable = coordinatorAdminUnavailable(status);\n\t\tif (unavailable) return c.json(unavailable.body, unavailable.httpStatus);\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tconst scopeId = String(c.req.param(\"scope_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\tif (!scopeId) return c.json({ error: \"scope_id required\", status }, 400);\n\t\ttry {\n\t\t\tconst items = await coordinatorListScopeMembershipsAction({\n\t\t\t\tgroupId,\n\t\t\t\tscopeId,\n\t\t\t\tincludeRevoked: queryBool(c.req.query(\"include_revoked\")),\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\treturn c.json({ items, group_id: groupId, scope_id: scopeId, status });\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"unknown\";\n\t\t\treturn c.json({ error: message, status }, coordinatorAdminMutationStatus(message));\n\t\t}\n\t});\n\n\tapp.post(\"/api/coordinator/admin/groups/:group_id/scopes/:scope_id/members\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tconst unavailable = coordinatorAdminUnavailable(status);\n\t\tif (unavailable) return c.json(unavailable.body, unavailable.httpStatus);\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tconst scopeId = String(c.req.param(\"scope_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\tif (!scopeId) return c.json({ error: \"scope_id required\", status }, 400);\n\t\tconst body = await parseViewerJsonBody(c);\n\t\tif (!body) return c.json({ error: \"invalid json\", status }, 400);\n\t\tconst deviceId = optionalViewerString(body, \"device_id\");\n\t\tconst membershipEpoch = optionalViewerNumber(body, \"membership_epoch\");\n\t\tif (!deviceId) return c.json({ error: \"device_id required\", status }, 400);\n\t\tif (Number.isNaN(membershipEpoch)) {\n\t\t\treturn c.json({ error: \"membership_epoch must be number\", status }, 400);\n\t\t}\n\t\tconst role = optionalViewerString(body, \"role\");\n\t\tconst coordinatorId = optionalViewerString(body, \"coordinator_id\");\n\t\tconst manifestIssuerDeviceId = optionalViewerString(body, \"manifest_issuer_device_id\");\n\t\tconst manifestHash = optionalViewerString(body, \"manifest_hash\");\n\t\tconst signedManifestJson = optionalViewerString(body, \"signed_manifest_json\");\n\t\tconst effectId =\n\t\t\toptionalViewerString(body, \"effect_id\") ??\n\t\t\tcoordinatorAdminMembershipEffectId(\"grant\", randomUUID(), {\n\t\t\t\tgroupId,\n\t\t\t\tscopeId,\n\t\t\t\tdeviceId,\n\t\t\t\trole,\n\t\t\t\tmembershipEpoch,\n\t\t\t\tcoordinatorId,\n\t\t\t\tmanifestIssuerDeviceId,\n\t\t\t\tmanifestHash,\n\t\t\t\tsignedManifestJson,\n\t\t\t});\n\t\ttry {\n\t\t\tconst membership = await coordinatorGrantScopeMembershipAction({\n\t\t\t\teffectId,\n\t\t\t\tgroupId,\n\t\t\t\tscopeId,\n\t\t\t\tdeviceId,\n\t\t\t\trole,\n\t\t\t\tmembershipEpoch,\n\t\t\t\tcoordinatorId,\n\t\t\t\tmanifestIssuerDeviceId,\n\t\t\t\tmanifestHash,\n\t\t\t\tsignedManifestJson,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\treturn c.json({ ok: true, membership, group_id: groupId, scope_id: scopeId, status });\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\treturn c.json({ error: message, status }, coordinatorAdminMutationStatus(message));\n\t\t}\n\t});\n\n\tapp.post(\n\t\t\"/api/coordinator/admin/groups/:group_id/scopes/:scope_id/members/:device_id/revoke\",\n\t\tasync (c) => {\n\t\t\tconst config = readCoordinatorSyncConfig();\n\t\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\t\tconst unavailable = coordinatorAdminUnavailable(status);\n\t\t\tif (unavailable) return c.json(unavailable.body, unavailable.httpStatus);\n\t\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\t\tconst scopeId = String(c.req.param(\"scope_id\") ?? \"\").trim();\n\t\t\tconst deviceId = String(c.req.param(\"device_id\") ?? \"\").trim();\n\t\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\t\tif (!scopeId) return c.json({ error: \"scope_id required\", status }, 400);\n\t\t\tif (!deviceId) return c.json({ error: \"device_id required\", status }, 400);\n\t\t\tconst body = await parseViewerJsonBody(c, { allowEmpty: true });\n\t\t\tif (!body) return c.json({ error: \"invalid json\", status }, 400);\n\t\t\tconst membershipEpoch = optionalViewerNumber(body, \"membership_epoch\");\n\t\t\tif (Number.isNaN(membershipEpoch)) {\n\t\t\t\treturn c.json({ error: \"membership_epoch must be number\", status }, 400);\n\t\t\t}\n\t\t\tconst manifestHash = optionalViewerString(body, \"manifest_hash\");\n\t\t\tconst signedManifestJson = optionalViewerString(body, \"signed_manifest_json\");\n\t\t\tconst effectId =\n\t\t\t\toptionalViewerString(body, \"effect_id\") ??\n\t\t\t\tcoordinatorAdminMembershipEffectId(\"revoke\", randomUUID(), {\n\t\t\t\t\tgroupId,\n\t\t\t\t\tscopeId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tmembershipEpoch,\n\t\t\t\t\tmanifestHash,\n\t\t\t\t\tsignedManifestJson,\n\t\t\t\t});\n\t\t\ttry {\n\t\t\t\tconst ok = await coordinatorRevokeScopeMembershipAction({\n\t\t\t\t\teffectId,\n\t\t\t\t\tgroupId,\n\t\t\t\t\tscopeId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tmembershipEpoch,\n\t\t\t\t\tmanifestHash,\n\t\t\t\t\tsignedManifestJson,\n\t\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t\t});\n\t\t\t\tif (!ok) return c.json({ error: \"membership_not_found\", status }, 404);\n\t\t\t\treturn c.json({\n\t\t\t\t\tok: true,\n\t\t\t\t\tgroup_id: groupId,\n\t\t\t\t\tscope_id: scopeId,\n\t\t\t\t\tdevice_id: deviceId,\n\t\t\t\t\tstatus,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\treturn c.json({ error: message, status }, coordinatorAdminMutationStatus(message));\n\t\t\t}\n\t\t},\n\t);\n\n\tapp.post(\"/api/coordinator/admin/invites\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tif (!status.has_admin_secret) {\n\t\t\treturn c.json({ error: \"coordinator_admin_secret_missing\", status }, 400);\n\t\t}\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\", status }, 400);\n\t\t}\n\t\tconst groupId = resolveCoordinatorAdminGroup(String(body.group_id ?? \"\").trim(), status);\n\t\tconst coordinatorUrl = body.coordinator_url == null ? null : String(body.coordinator_url ?? \"\");\n\t\tconst policy = String(body.policy ?? \"auto_admit\").trim();\n\t\tconst ttlHours = parseInviteTtlHours(body.ttl_hours);\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\tif (body.coordinator_url != null && typeof body.coordinator_url !== \"string\") {\n\t\t\treturn c.json({ error: \"coordinator_url must be string\", status }, 400);\n\t\t}\n\t\tif (![\"auto_admit\", \"approval_required\"].includes(policy)) {\n\t\t\treturn c.json({ error: \"policy must be auto_admit or approval_required\", status }, 400);\n\t\t}\n\t\tif (ttlHours == null) {\n\t\t\treturn c.json({ error: \"ttl_hours must be an integer >= 1\", status }, 400);\n\t\t}\n\t\ttry {\n\t\t\tconst result = await coordinatorCreateInviteAction({\n\t\t\t\tgroupId,\n\t\t\t\tcoordinatorUrl,\n\t\t\t\tpolicy,\n\t\t\t\tttlHours,\n\t\t\t\tcreatedBy: null,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\treturn c.json({ ...result, status });\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error), status }, 400);\n\t\t}\n\t});\n\n\tapp.get(\"/api/coordinator/admin/join-requests\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tif (!status.has_admin_secret) {\n\t\t\treturn c.json({ error: \"coordinator_admin_secret_missing\", status }, 400);\n\t\t}\n\t\tconst groupId = resolveCoordinatorAdminGroup(c.req.query(\"group_id\"), status);\n\t\tif (!groupId) return c.json({ error: \"group_id_required\", status }, 400);\n\t\ttry {\n\t\t\tconst items = await coordinatorListJoinRequestsAction({\n\t\t\t\tgroupId,\n\t\t\t\tremoteUrl: status.coordinator_url,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\treturn c.json({ items, group_id: groupId, status });\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"unknown\";\n\t\t\treturn c.json({ error: message, status }, coordinatorAdminMutationStatus(message));\n\t\t}\n\t});\n\n\tapp.post(\"/api/coordinator/admin/join-requests/:request_id/approve\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tif (!status.has_admin_secret) {\n\t\t\treturn c.json({ error: \"coordinator_admin_secret_missing\", status }, 400);\n\t\t}\n\t\tconst requestId = String(c.req.param(\"request_id\") ?? \"\").trim();\n\t\tif (!requestId) return c.json({ error: \"request_id required\", status }, 400);\n\t\ttry {\n\t\t\tconst result = await coordinatorReviewJoinRequestAction({\n\t\t\t\trequestId,\n\t\t\t\tapprove: true,\n\t\t\t\treviewedBy: null,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\tif (!result) return c.json({ error: \"join request not found\", status }, 404);\n\t\t\tlet defaultSpaceMembership = null;\n\t\t\tlet setupWarning = null;\n\t\t\ttry {\n\t\t\t\tdefaultSpaceMembership = await maybeGrantDefaultSpaceOnJoin({\n\t\t\t\t\tstore: getStore(),\n\t\t\t\t\tconfig,\n\t\t\t\t\tgroupId: result.group_id,\n\t\t\t\t\trequestId,\n\t\t\t\t\tdeviceId: result.device_id,\n\t\t\t\t});\n\t\t\t} catch (grantError) {\n\t\t\t\tsetupWarning = {\n\t\t\t\t\tstep: \"default_space_grant\",\n\t\t\t\t\terror: grantError instanceof Error ? grantError.message : String(grantError),\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn c.json({\n\t\t\t\tok: true,\n\t\t\t\trequest: result,\n\t\t\t\tdefault_space_membership: defaultSpaceMembership,\n\t\t\t\tsetup_warning: setupWarning,\n\t\t\t\tstatus,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\treturn c.json(\n\t\t\t\t{ error: message, status },\n\t\t\t\tmessage.includes(\"request_not_found\") || message.includes(\"not found\") ? 404 : 400,\n\t\t\t);\n\t\t}\n\t});\n\n\tapp.post(\"/api/coordinator/admin/join-requests/:request_id/deny\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tif (!status.has_admin_secret) {\n\t\t\treturn c.json({ error: \"coordinator_admin_secret_missing\", status }, 400);\n\t\t}\n\t\tconst requestId = String(c.req.param(\"request_id\") ?? \"\").trim();\n\t\tif (!requestId) return c.json({ error: \"request_id required\", status }, 400);\n\t\ttry {\n\t\t\tconst result = await coordinatorReviewJoinRequestAction({\n\t\t\t\trequestId,\n\t\t\t\tapprove: false,\n\t\t\t\treviewedBy: null,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\tif (!result) return c.json({ error: \"join request not found\", status }, 404);\n\t\t\treturn c.json({ ok: true, request: result, status });\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\treturn c.json(\n\t\t\t\t{ error: message, status },\n\t\t\t\tmessage.includes(\"request_not_found\") || message.includes(\"not found\") ? 404 : 400,\n\t\t\t);\n\t\t}\n\t});\n\n\tapp.get(\"/api/coordinator/admin/devices\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tif (!status.has_admin_secret) {\n\t\t\treturn c.json({ error: \"coordinator_admin_secret_missing\", status }, 400);\n\t\t}\n\t\tconst groupId = resolveCoordinatorAdminGroup(c.req.query(\"group_id\"), status);\n\t\tif (!groupId) return c.json({ error: \"group_id_required\", status }, 400);\n\t\ttry {\n\t\t\tconst items = await coordinatorListDevicesAction({\n\t\t\t\tgroupId,\n\t\t\t\tincludeDisabled: queryBool(c.req.query(\"include_disabled\")),\n\t\t\t\tremoteUrl: status.coordinator_url,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\treturn c.json({ items, group_id: groupId, status });\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"unknown\";\n\t\t\treturn c.json({ error: message, status }, coordinatorAdminMutationStatus(message));\n\t\t}\n\t});\n\n\tapp.post(\"/api/coordinator/admin/devices/:device_id/rename\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tif (!status.has_admin_secret) {\n\t\t\treturn c.json({ error: \"coordinator_admin_secret_missing\", status }, 400);\n\t\t}\n\t\tconst deviceId = String(c.req.param(\"device_id\") ?? \"\").trim();\n\t\tif (!deviceId) return c.json({ error: \"device_id required\", status }, 400);\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\", status }, 400);\n\t\t}\n\t\tconst groupId = resolveCoordinatorAdminGroup(String(body.group_id ?? \"\").trim(), status);\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\tlet displayName: string;\n\t\ttry {\n\t\t\tdisplayName = normalizeHumanPresentationName(String(body.display_name ?? \"\"), \"display_name\");\n\t\t} catch (error) {\n\t\t\treturn c.json(\n\t\t\t\t{ error: error instanceof Error ? error.message : \"display_name_invalid\", status },\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t\ttry {\n\t\t\tconst device = await coordinatorRenameDeviceAction({\n\t\t\t\tgroupId,\n\t\t\t\tdeviceId,\n\t\t\t\tdisplayName,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\tif (!device) return c.json({ error: \"device_not_found\", status }, 404);\n\t\t\treturn c.json({ ok: true, device, status });\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error), status }, 400);\n\t\t}\n\t});\n\n\tapp.post(\"/api/coordinator/admin/devices/:device_id/disable\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tif (!status.has_admin_secret) {\n\t\t\treturn c.json({ error: \"coordinator_admin_secret_missing\", status }, 400);\n\t\t}\n\t\tconst deviceId = String(c.req.param(\"device_id\") ?? \"\").trim();\n\t\tif (!deviceId) return c.json({ error: \"device_id required\", status }, 400);\n\t\tconst groupId = resolveCoordinatorAdminGroup(c.req.query(\"group_id\"), status);\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\ttry {\n\t\t\tconst ok = await coordinatorDisableDeviceAction({\n\t\t\t\tgroupId,\n\t\t\t\tdeviceId,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\tif (!ok) return c.json({ error: \"device_not_found\", status }, 404);\n\t\t\treturn c.json({ ok: true, device_id: deviceId, status });\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error), status }, 400);\n\t\t}\n\t});\n\n\tapp.post(\"/api/coordinator/admin/devices/:device_id/enable\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tif (!status.has_admin_secret) {\n\t\t\treturn c.json({ error: \"coordinator_admin_secret_missing\", status }, 400);\n\t\t}\n\t\tconst deviceId = String(c.req.param(\"device_id\") ?? \"\").trim();\n\t\tif (!deviceId) return c.json({ error: \"device_id required\", status }, 400);\n\t\tconst groupId = resolveCoordinatorAdminGroup(c.req.query(\"group_id\"), status);\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\ttry {\n\t\t\tconst ok = await coordinatorEnableDeviceAction({\n\t\t\t\tgroupId,\n\t\t\t\tdeviceId,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\tif (!ok) return c.json({ error: \"device_not_found\", status }, 404);\n\t\t\treturn c.json({ ok: true, device_id: deviceId, status });\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error), status }, 400);\n\t\t}\n\t});\n\n\t// Unified peer-enrollment entry point. Mode is chosen by an explicit\n\t// body field so a legitimate coordinator group named (for example)\n\t// `none` cannot collide with the manual-pairing path:\n\t// - `mode: \"discovered\"` (default) → promote a coordinator-discovered\n\t// device, seed scope from the :group_id group's template when\n\t// auto_seed_scope is true and the caller didn't pass an override.\n\t// - `mode: \"manual\"` → manual pairing. Accepts peer_public_key +\n\t// optional name/fingerprint/addresses; :group_id path param is\n\t// ignored and both discovery columns are left null.\n\t// See docs/plans/2026-04-22-multi-team-coordinator-groups-design.md.\n\tapp.post(\"/api/coordinator/admin/groups/:group_id/enroll-peer\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\t// Admin-secret gating happens inside the discovered branch below —\n\t\t// manual pairing only writes a local sync_peers row and doesn't need\n\t\t// coordinator-admin privileges, matching the pre-existing /peers/accept\n\t\t// path.\n\t\tconst rawGroupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tif (!rawGroupId) return c.json({ error: \"group_id required\" }, 400);\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\t\tconst rawMode = String(body.mode ?? \"\")\n\t\t\t.trim()\n\t\t\t.toLowerCase();\n\t\tif (rawMode && rawMode !== \"manual\" && rawMode !== \"discovered\") {\n\t\t\treturn c.json(\n\t\t\t\t{ error: \"invalid_mode\", detail: `mode must be 'discovered' or 'manual', got ${rawMode}` },\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t\tconst mode: \"discovered\" | \"manual\" = rawMode === \"manual\" ? \"manual\" : \"discovered\";\n\t\t// Per-field normalization: distinguish \"caller did not specify\" from\n\t\t// \"caller set empty\". `undefined` = inherit (template); `null` or empty\n\t\t// array = explicit clear; non-empty array = use as-is.\n\t\tconst normalizeOverride = (value: unknown): string[] | null | undefined => {\n\t\t\tif (value === undefined) return undefined;\n\t\t\tif (value === null) return null;\n\t\t\tif (!Array.isArray(value)) return undefined;\n\t\t\tconst cleaned = value\n\t\t\t\t.map((item) => String(item ?? \"\").trim())\n\t\t\t\t.filter((item) => item.length > 0);\n\t\t\treturn cleaned.length === 0 ? null : cleaned;\n\t\t};\n\t\tconst overrideInclude = normalizeOverride(body.projects_include);\n\t\tconst overrideExclude = normalizeOverride(body.projects_exclude);\n\t\tconst scopeOverride =\n\t\t\toverrideInclude === undefined && overrideExclude === undefined\n\t\t\t\t? undefined\n\t\t\t\t: { projects_include: overrideInclude, projects_exclude: overrideExclude };\n\t\tconst store = getStore();\n\n\t\tif (mode === \"manual\") {\n\t\t\tconst peerDeviceId = String(body.peer_device_id ?? \"\").trim();\n\t\t\tconst publicKey = String(body.peer_public_key ?? \"\").trim();\n\t\t\tconst name = String(body.name ?? \"\").trim() || null;\n\t\t\tconst requestedFingerprint = String(body.fingerprint ?? \"\").trim();\n\t\t\tconst addressesInput = Array.isArray(body.peer_addresses) ? body.peer_addresses : [];\n\t\t\tconst addresses = mergeAddresses(\n\t\t\t\t[],\n\t\t\t\taddressesInput.map((item) => String(item ?? \"\").trim()).filter((item) => item.length > 0),\n\t\t\t);\n\t\t\tif (!peerDeviceId || !publicKey) {\n\t\t\t\treturn c.json({ error: \"peer_device_id_and_public_key_required\" }, 400);\n\t\t\t}\n\t\t\tconst fingerprint = requestedFingerprint || fingerprintPublicKey(publicKey);\n\t\t\tif (fingerprintPublicKey(publicKey) !== fingerprint) {\n\t\t\t\treturn c.json({ error: \"fingerprint_mismatch\" }, 400);\n\t\t\t}\n\t\t\tconst manualInclude =\n\t\t\t\toverrideInclude && overrideInclude.length > 0 ? JSON.stringify(overrideInclude) : null;\n\t\t\tconst manualExclude =\n\t\t\t\toverrideExclude && overrideExclude.length > 0 ? JSON.stringify(overrideExclude) : null;\n\t\t\tconst now = new Date().toISOString();\n\t\t\tconst d = drizzle(store.db, { schema });\n\t\t\t// Wrap the duplicate check + insert in a transaction so two concurrent\n\t\t\t// enrolls for the same peer cannot both clear the check. SQLite\n\t\t\t// serializes transactions on the write lock, so the second one sees\n\t\t\t// the committed row and returns 409 instead of racing past.\n\t\t\ttry {\n\t\t\t\tconst created = store.db.transaction(() => {\n\t\t\t\t\tconst existing = d\n\t\t\t\t\t\t.select({ peer_device_id: schema.syncPeers.peer_device_id })\n\t\t\t\t\t\t.from(schema.syncPeers)\n\t\t\t\t\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t\t\t\t\t.get();\n\t\t\t\t\tif (existing) return false;\n\t\t\t\t\td.insert(schema.syncPeers)\n\t\t\t\t\t\t.values({\n\t\t\t\t\t\t\tpeer_device_id: peerDeviceId,\n\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\tpinned_fingerprint: fingerprint,\n\t\t\t\t\t\t\tpublic_key: publicKey,\n\t\t\t\t\t\t\taddresses_json: JSON.stringify(addresses),\n\t\t\t\t\t\t\tprojects_include_json: manualInclude,\n\t\t\t\t\t\t\tprojects_exclude_json: manualExclude,\n\t\t\t\t\t\t\tcreated_at: now,\n\t\t\t\t\t\t\tlast_seen_at: now,\n\t\t\t\t\t\t\tdiscovered_via_coordinator_id: null,\n\t\t\t\t\t\t\tdiscovered_via_group_id: null,\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.run();\n\t\t\t\t\treturn true;\n\t\t\t\t})();\n\t\t\t\tif (!created) {\n\t\t\t\t\treturn c.json({ error: \"peer_exists\", detail: \"Peer is already enrolled.\" }, 409);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\t// Primary-key constraint collision is the expected race signal; the\n\t\t\t\t// first writer wins, the second gets \"peer_exists\".\n\t\t\t\tconst msg = error instanceof Error ? error.message.toLowerCase() : \"\";\n\t\t\t\tif (msg.includes(\"unique\") || msg.includes(\"primary key\")) {\n\t\t\t\t\treturn c.json({ error: \"peer_exists\", detail: \"Peer is already enrolled.\" }, 409);\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\treturn c.json({\n\t\t\t\tok: true,\n\t\t\t\tpeer_device_id: peerDeviceId,\n\t\t\t\tcreated: true,\n\t\t\t\tupdated: false,\n\t\t\t\tname,\n\t\t\t\tgroup_id: null,\n\t\t\t});\n\t\t}\n\n\t\t// Discovered mode calls out to the coordinator for reciprocal approval,\n\t\t// so it needs the admin secret. Manual mode never leaves this process.\n\t\tif (!status.has_admin_secret) {\n\t\t\treturn c.json({ error: \"coordinator_admin_secret_missing\", status }, 400);\n\t\t}\n\t\tconst peerDeviceId = String(body.peer_device_id ?? body.discovered_device_id ?? \"\").trim();\n\t\tconst fingerprint = String(body.fingerprint ?? \"\").trim();\n\t\tif (!peerDeviceId || !fingerprint) {\n\t\t\treturn c.json({ error: \"peer_device_id_and_fingerprint_required\" }, 400);\n\t\t}\n\t\ttry {\n\t\t\tconst result = await acceptDiscoveredPeer(store, {\n\t\t\t\tpeerDeviceId,\n\t\t\t\tfingerprint,\n\t\t\t\texpectedGroupId: rawGroupId,\n\t\t\t\tscopeOverride,\n\t\t\t});\n\t\t\tif (result.ok) {\n\t\t\t\treturn c.json(result);\n\t\t\t}\n\t\t\treturn c.json(\n\t\t\t\t{\n\t\t\t\t\terror: result.error,\n\t\t\t\t\tdetail: result.detail,\n\t\t\t\t\t...(result.reason ? { reason: result.reason } : {}),\n\t\t\t\t},\n\t\t\t\tresult.status as 400 | 404 | 409,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\t// acceptDiscoveredPeer shells out to the coordinator for reciprocal\n\t\t\t// approval and can throw on timeout / network / auth failures. Map\n\t\t\t// those to a structured 502 so clients get the same shape as the\n\t\t\t// legacy /api/sync/peers/accept-discovered path.\n\t\t\treturn c.json(\n\t\t\t\t{\n\t\t\t\t\terror: \"coordinator_lookup_failed\",\n\t\t\t\t\tdetail: error instanceof Error ? error.message : String(error),\n\t\t\t\t},\n\t\t\t\t502,\n\t\t\t);\n\t\t}\n\t});\n\n\t// Local-only preferences for a coordinator group — project-scope template\n\t// + auto-seed toggle applied when peers are enrolled through the group.\n\t// See docs/plans/2026-04-22-multi-team-coordinator-groups-design.md.\n\t// Local-only preferences — these rows live in the viewer's own DB and never\n\t// cross the wire to the coordinator. No admin-secret gate: the admin secret\n\t// authorizes remote coordinator mutations, not local settings.\n\tapp.get(\"/api/coordinator/admin/groups/:group_id/preferences\", (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\tconst coordinatorId = status.coordinator_url;\n\t\tif (!coordinatorId) return c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\tconst store = getStore();\n\t\tconst existing = getCoordinatorGroupPreference(store.db, coordinatorId, groupId);\n\t\tif (existing) return c.json({ preferences: existing, status });\n\t\treturn c.json({\n\t\t\tpreferences: {\n\t\t\t\tcoordinator_id: coordinatorId,\n\t\t\t\tgroup_id: groupId,\n\t\t\t\tprojects_include: null,\n\t\t\t\tprojects_exclude: null,\n\t\t\t\tauto_seed_scope: true,\n\t\t\t\tdefault_space_scope_id: null,\n\t\t\t\tauto_grant_default_space_on_join: false,\n\t\t\t\tupdated_at: null,\n\t\t\t},\n\t\t\tstatus,\n\t\t});\n\t});\n\n\tapp.put(\"/api/coordinator/admin/groups/:group_id/preferences\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\tconst coordinatorId = status.coordinator_url;\n\t\tif (!coordinatorId) return c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid_json\", status }, 400);\n\t\t}\n\t\tconst normalizeList = (value: unknown): string[] | null | undefined => {\n\t\t\tif (value === undefined) return undefined;\n\t\t\tif (value === null) return null;\n\t\t\tif (!Array.isArray(value)) return undefined;\n\t\t\tconst cleaned = value\n\t\t\t\t.map((item) => String(item ?? \"\").trim())\n\t\t\t\t.filter((item) => item.length > 0);\n\t\t\treturn cleaned.length === 0 ? null : cleaned;\n\t\t};\n\t\tconst autoSeed = typeof body.auto_seed_scope === \"boolean\" ? body.auto_seed_scope : undefined;\n\t\tconst autoGrantDefaultSpace =\n\t\t\ttypeof body.auto_grant_default_space_on_join === \"boolean\"\n\t\t\t\t? body.auto_grant_default_space_on_join\n\t\t\t\t: undefined;\n\t\tconst defaultSpaceScopeId =\n\t\t\tbody.default_space_scope_id === undefined\n\t\t\t\t? undefined\n\t\t\t\t: optionalViewerString(body, \"default_space_scope_id\");\n\t\tif (autoGrantDefaultSpace === true && !defaultSpaceScopeId) {\n\t\t\treturn c.json(\n\t\t\t\t{\n\t\t\t\t\terror: \"default_space_scope_id_required_for_auto_grant\",\n\t\t\t\t\tstatus,\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t\tconst store = getStore();\n\t\ttry {\n\t\t\tconst preferences = upsertCoordinatorGroupPreference(store.db, {\n\t\t\t\tcoordinator_id: coordinatorId,\n\t\t\t\tgroup_id: groupId,\n\t\t\t\tprojects_include: normalizeList(body.projects_include),\n\t\t\t\tprojects_exclude: normalizeList(body.projects_exclude),\n\t\t\t\tauto_seed_scope: autoSeed,\n\t\t\t\tdefault_space_scope_id: defaultSpaceScopeId,\n\t\t\t\tauto_grant_default_space_on_join: autoGrantDefaultSpace,\n\t\t\t});\n\t\t\treturn c.json({ preferences, status });\n\t\t} catch (error) {\n\t\t\tconst msg = error instanceof Error ? error.message : String(error);\n\t\t\treturn c.json({ error: msg, status }, 400);\n\t\t}\n\t});\n\n\tapp.post(\"/api/coordinator/admin/devices/:device_id/remove\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tif (!status.has_admin_secret) {\n\t\t\treturn c.json({ error: \"coordinator_admin_secret_missing\", status }, 400);\n\t\t}\n\t\tconst deviceId = String(c.req.param(\"device_id\") ?? \"\").trim();\n\t\tif (!deviceId) return c.json({ error: \"device_id required\", status }, 400);\n\t\tconst groupId = resolveCoordinatorAdminGroup(c.req.query(\"group_id\"), status);\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\ttry {\n\t\t\tconst ok = await coordinatorRemoveDeviceAction({\n\t\t\t\tgroupId,\n\t\t\t\tdeviceId,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\tif (!ok) return c.json({ error: \"device_not_found\", status }, 404);\n\t\t\treturn c.json({ ok: true, device_id: deviceId, status });\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error), status }, 400);\n\t\t}\n\t});\n\n\tapp.get(\"/api/sync/bootstrap-grants\", async (c) => {\n\t\tconst groupId = String(c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\t\tconst config = readCoordinatorSyncConfig();\n\t\ttry {\n\t\t\tconst items = await coordinatorListBootstrapGrantsAction({\n\t\t\t\tgroupId,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\treturn c.json({ items });\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"unknown\";\n\t\t\treturn c.json({ error: message }, 500);\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/bootstrap-grants/revoke\", async (c) => {\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\" }, 400);\n\t\t}\n\t\tconst grantId = String(body.grant_id ?? \"\").trim();\n\t\tif (!grantId) return c.json({ error: \"grant_id_required\" }, 400);\n\t\tconst config = readCoordinatorSyncConfig();\n\t\ttry {\n\t\t\tconst ok = await coordinatorRevokeBootstrapGrantAction({\n\t\t\t\tgrantId,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\tif (!ok) return c.json({ error: \"grant_not_found\" }, 404);\n\t\t\treturn c.json({ ok: true, grant_id: grantId });\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"unknown\";\n\t\t\treturn c.json({ error: message }, 500);\n\t\t}\n\t});\n\n\t// DELETE /api/sync/peers/:peer_device_id\n\tapp.delete(\"/api/sync/peers/:peer_device_id\", (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tconst d = drizzle(store.db, { schema });\n\t\t\tconst peerDeviceId = c.req.param(\"peer_device_id\")?.trim();\n\t\t\tif (!peerDeviceId) return c.json({ error: \"peer_device_id required\" }, 400);\n\t\t\tconst exists = d\n\t\t\t\t.select({ peer_device_id: schema.syncPeers.peer_device_id })\n\t\t\t\t.from(schema.syncPeers)\n\t\t\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t\t\t.get();\n\t\t\tif (!exists) return c.json({ error: \"peer not found\" }, 404);\n\t\t\td.delete(schema.replicationCursors)\n\t\t\t\t.where(eq(schema.replicationCursors.peer_device_id, peerDeviceId))\n\t\t\t\t.run();\n\t\t\td.delete(schema.syncPeers).where(eq(schema.syncPeers.peer_device_id, peerDeviceId)).run();\n\t\t\treturn c.json({ ok: true });\n\t\t}\n\t});\n\n\treturn app;\n}\n","import {\n\tgetUpdateStatus as defaultGetUpdateStatus,\n\tdetectInstallKind,\n\ttype GetUpdateStatusOptions,\n\ttype UpdateStatus,\n\tVERSION,\n} from \"@codemem/core\";\nimport { Hono } from \"hono\";\n\nexport interface UpdateStatusRoutesOptions {\n\tgetUpdateStatus?: (options: GetUpdateStatusOptions) => Promise<UpdateStatus>;\n}\n\nexport function updateStatusRoutes(options: UpdateStatusRoutesOptions = {}) {\n\tconst getUpdateStatus = options.getUpdateStatus ?? defaultGetUpdateStatus;\n\tconst app = new Hono();\n\n\tapp.get(\"/api/update-status\", async (c) => {\n\t\ttry {\n\t\t\tconst installKind = detectInstallKind({\n\t\t\t\tentryPath: process.argv[1] ?? \"\",\n\t\t\t\tenv: process.env,\n\t\t\t});\n\t\t\tconst status = await getUpdateStatus({\n\t\t\t\tcurrentVersion: VERSION,\n\t\t\t\tinstallKind,\n\t\t\t});\n\t\t\treturn c.json(status);\n\t\t} catch {\n\t\t\treturn c.json({ error: \"Update status unavailable.\" }, 503);\n\t\t}\n\t});\n\n\treturn app;\n}\n","/**\n * @codemem/server — HTTP server (viewer, sync, API).\n *\n * Single HTTP server handling viewer routes and sync daemon.\n * Shares one better-sqlite3 connection between viewer and sync.\n * Embedding inference runs in a worker_thread (lazy-started).\n *\n * Entry: `codemem serve`\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type {\n\tDeviceIdentityCoordinatorEvidence,\n\tGetUpdateStatusOptions,\n\tObserverClient,\n\tUpdateStatus,\n} from \"@codemem/core\";\nimport { MemoryStore, type RawEventSweeper, resolveDbPath, VERSION } from \"@codemem/core\";\nimport { serveStatic } from \"@hono/node-server/serve-static\";\nimport { Hono } from \"hono\";\nimport { originGuard, preflightHandler } from \"./middleware.js\";\nimport {\n\tcreateInMemoryRequestRateLimiter,\n\ttype InMemoryRequestRateLimiter,\n} from \"./request-rate-limit.js\";\nimport { configRoutes } from \"./routes/config.js\";\nimport { healthRoutes } from \"./routes/health.js\";\nimport { memoryRoutes } from \"./routes/memory.js\";\nimport { observerStatusRoutes } from \"./routes/observer-status.js\";\nimport { packTransportRoutes } from \"./routes/pack.js\";\nimport { rawEventsRoutes } from \"./routes/raw-events.js\";\nimport { statsRoutes } from \"./routes/stats.js\";\nimport { type SyncRoutesOptions, syncProtocolRoutes, syncRoutes } from \"./routes/sync.js\";\nimport {\n\ttype LegacyTeamCompletionDependencies,\n\ttype LegacyTeamConfiguredGroupSnapshotLoader,\n\tTEAM_SETUP_ROUTE_PREFIX,\n\tteamSetupRoutes,\n} from \"./routes/team-setup.js\";\nimport { updateStatusRoutes } from \"./routes/update-status.js\";\n\nexport type {\n\tAdvancePendingProjectSharesResult,\n\tAdvanceProjectShareOperationResult,\n\tRecipientPolicyReconciliationReadModel,\n\tRecipientPolicyReconciliationReadState,\n\tReconcileConfiguredCoordinatorEnrollmentResult,\n\tReconcileRecipientPolicyProjectsResult,\n} from \"./routes/sync.js\";\nexport {\n\tadvancePendingProjectShares,\n\tadvanceProjectShareOperation,\n\tcreateRecipientPolicyReconcilerEffects,\n\tlistRecipientPolicyReconciliationStatus,\n\trecipientPolicyCapabilityFromStatus,\n\treconcileConfiguredCoordinatorEnrollment,\n\treconcileRecipientPolicyProjects,\n} from \"./routes/sync.js\";\nexport type {\n\tLegacyTeamSetupActionBlockedReasonV1,\n\tLegacyTeamSetupActionGateV1,\n\tLegacyTeamSetupCandidateSummaryV1,\n\tLegacyTeamSetupDetailResponseV1,\n\tLegacyTeamSetupDeviceV1,\n\tLegacyTeamSetupErrorResponseV1,\n\tLegacyTeamSetupFinishResponseV1,\n\tLegacyTeamSetupIdentityChoiceV1,\n\tLegacyTeamSetupMutationResponseV1,\n\tLegacyTeamSetupPendingCandidateSummaryV1,\n\tLegacyTeamSetupProjectV1,\n\tLegacyTeamSetupSummaryResponseV1,\n\tLegacyTeamSetupViewerAccessDeltaV1,\n\tLegacyTeamSetupViewV1,\n} from \"./routes/team-setup.js\";\n\nexport { VERSION };\n\n/** Shared store instance — SQLite WAL mode handles concurrent reads safely. */\nlet sharedStore: MemoryStore | null = null;\n\n/** Get (or create) the shared store instance. Exported so the sweeper can share it. */\nexport function getStore(): MemoryStore {\n\tif (!sharedStore) {\n\t\tsharedStore = new MemoryStore(resolveDbPath());\n\t}\n\treturn sharedStore;\n}\n\n/** Close the shared store (called on shutdown). */\nexport function closeStore(): void {\n\tsharedStore?.close();\n\tsharedStore = null;\n}\n\n/**\n * Create the Hono app with all viewer routes.\n * Exported for testing — pass a custom store factory to inject test DBs.\n */\nexport interface AppOptions {\n\tstoreFactory?: () => MemoryStore;\n\tsweeper?: RawEventSweeper | null;\n\tobserver?: ObserverClient | null;\n\tgetUpdateStatus?: (options: GetUpdateStatusOptions) => Promise<UpdateStatus>;\n\tloadDeviceIdentityCoordinatorEvidence?: () => Promise<DeviceIdentityCoordinatorEvidence>;\n\tloadLegacyTeamConfiguredGroupSnapshots?: LegacyTeamConfiguredGroupSnapshotLoader;\n\tteamSetupCompletionDependencies?: LegacyTeamCompletionDependencies | null;\n\treadCoordinatorConfig?: SyncRoutesOptions[\"readCoordinatorConfig\"];\n\trenameCoordinatorGroup?: SyncRoutesOptions[\"renameCoordinatorGroup\"];\n\tsyncRequestRateLimit?: {\n\t\tlimiter?: InMemoryRequestRateLimiter;\n\t\treadLimit?: number;\n\t\tmutationLimit?: number;\n\t\tunauthenticatedReadLimit?: number;\n\t\tunauthenticatedMutationLimit?: number;\n\t};\n\tgetSyncRuntimeStatus?: () => {\n\t\tphase:\n\t\t\t| \"starting\"\n\t\t\t| \"running\"\n\t\t\t| \"stopping\"\n\t\t\t| \"error\"\n\t\t\t| \"disabled\"\n\t\t\t| \"rebootstrapping\"\n\t\t\t| \"needs_attention\"\n\t\t\t| null;\n\t\tdetail?: string | null;\n\t} | null;\n}\n\nexport function createApp(opts?: AppOptions) {\n\tconst storeFactory = opts?.storeFactory ?? getStore;\n\tconst sweeper = opts?.sweeper ?? null;\n\tconst observer = opts?.observer ?? null;\n\tconst getSyncRuntimeStatus = opts?.getSyncRuntimeStatus ?? (() => null);\n\tlet invalidateTeamSetupSummary = () => {};\n\tconst app = new Hono();\n\n\t// CORS / origin guard\n\tapp.use(\"*\", preflightHandler());\n\tapp.use(\"*\", originGuard({ unsafeGetPathPrefixes: [TEAM_SETUP_ROUTE_PREFIX] }));\n\n\t// API routes\n\tapp.route(\"/\", healthRoutes(storeFactory));\n\tapp.route(\"/\", statsRoutes(storeFactory));\n\tapp.route(\"/\", memoryRoutes(storeFactory));\n\tapp.route(\"/\", packTransportRoutes(storeFactory));\n\tapp.route(\n\t\t\"/\",\n\t\tobserverStatusRoutes({\n\t\t\tgetStore: storeFactory,\n\t\t\tgetSweeper: () => sweeper,\n\t\t\tgetObserver: () => observer,\n\t\t}),\n\t);\n\tapp.route(\"/\", configRoutes({ getSweeper: () => sweeper }));\n\tapp.route(\"/\", rawEventsRoutes(storeFactory, sweeper));\n\tapp.route(\n\t\t\"/\",\n\t\tsyncRoutes(storeFactory, getSyncRuntimeStatus, {\n\t\t\tloadDeviceIdentityCoordinatorEvidence: opts?.loadDeviceIdentityCoordinatorEvidence,\n\t\t\tonRecipientPolicyTeamRenamed: () => invalidateTeamSetupSummary(),\n\t\t\treadCoordinatorConfig: opts?.readCoordinatorConfig,\n\t\t\trenameCoordinatorGroup: opts?.renameCoordinatorGroup,\n\t\t}),\n\t);\n\tapp.route(\n\t\t\"/\",\n\t\tteamSetupRoutes({\n\t\t\tgetStore: storeFactory,\n\t\t\tloadLegacyTeamConfiguredGroupSnapshots: opts?.loadLegacyTeamConfiguredGroupSnapshots,\n\t\t\tcompletionDependencies: opts?.teamSetupCompletionDependencies,\n\t\t\treadCoordinatorConfig: opts?.readCoordinatorConfig,\n\t\t\tregisterSummaryInvalidator: (invalidate) => {\n\t\t\t\tinvalidateTeamSetupSummary = invalidate;\n\t\t\t},\n\t\t}),\n\t);\n\tapp.route(\"/\", updateStatusRoutes({ getUpdateStatus: opts?.getUpdateStatus }));\n\n\t// Static assets — serve under /assets/*\n\t// Resolves to packages/viewer-server/static/ both in dev and when installed from npm.\n\tconst staticRoot =\n\t\tprocess.env.CODEMEM_VIEWER_STATIC_DIR ?? join(import.meta.dirname ?? \".\", \"../static\");\n\n\tapp.use(\"/assets/*\", async (c, next) => {\n\t\tc.header(\"Cache-Control\", \"no-cache\");\n\t\tawait next();\n\t});\n\n\tapp.use(\n\t\t\"/assets/*\",\n\t\tserveStatic({\n\t\t\troot: staticRoot,\n\t\t\trewriteRequestPath: (path) => path.replace(/^\\/assets/, \"\"),\n\t\t\tprecompressed: true,\n\t\t}),\n\t);\n\n\t// SPA — serve index.html for root and all client-side routes\n\tconst indexPath = join(staticRoot, \"index.html\");\n\tif (!existsSync(indexPath)) {\n\t\tthrow new Error(\n\t\t\t`Viewer assets missing at ${indexPath}. Run \\`pnpm build\\` from the repo root before starting the viewer.`,\n\t\t);\n\t}\n\tconst indexHtml = readFileSync(indexPath, \"utf-8\");\n\tapp.get(\"*\", (c) => {\n\t\tif (c.req.path.startsWith(\"/api/\")) {\n\t\t\treturn c.json({ error: \"not found\" }, 404);\n\t\t}\n\t\tc.header(\"Cache-Control\", \"no-store\");\n\t\treturn c.html(indexHtml);\n\t});\n\n\treturn app;\n}\n\n/**\n * Create the Hono app for peer-to-peer sync protocol routes only.\n *\n * This app is bound to a separate network-accessible listener\n * (default 0.0.0.0:7337) so remote peers can reach the sync\n * endpoints without exposing the viewer UI or local API routes.\n *\n * No CORS/origin guard is applied — sync requests are authenticated\n * via cryptographic signature verification instead.\n */\nexport function createSyncApp(opts?: AppOptions) {\n\tconst storeFactory = opts?.storeFactory ?? getStore;\n\tconst requestRateLimit = opts?.syncRequestRateLimit ?? {};\n\tconst rateLimiter = requestRateLimit.limiter ?? createInMemoryRequestRateLimiter();\n\tconst readLimit = Math.max(1, Math.trunc(requestRateLimit.readLimit ?? 120));\n\tconst mutationLimit = Math.max(1, Math.trunc(requestRateLimit.mutationLimit ?? 30));\n\tconst app = new Hono();\n\tapp.route(\n\t\t\"/\",\n\t\tsyncProtocolRoutes(storeFactory, {\n\t\t\trouteRateLimit: {\n\t\t\t\tlimiter: rateLimiter,\n\t\t\t\treadLimit,\n\t\t\t\tmutationLimit,\n\t\t\t\tunauthenticatedReadLimit: Math.max(\n\t\t\t\t\t1,\n\t\t\t\t\tMath.trunc(requestRateLimit.unauthenticatedReadLimit ?? Math.min(20, readLimit)),\n\t\t\t\t),\n\t\t\t\tunauthenticatedMutationLimit: Math.max(\n\t\t\t\t\t1,\n\t\t\t\t\tMath.trunc(requestRateLimit.unauthenticatedMutationLimit ?? Math.min(10, mutationLimit)),\n\t\t\t\t),\n\t\t\t},\n\t\t}),\n\t);\n\n\t// Catch-all — return generic 404 to avoid fingerprinting the server.\n\tapp.all(\"*\", (c) => c.json({ error: \"not found\" }, 404));\n\n\treturn app;\n}\n\n// No auto-start — the CLI's `serve` command owns server startup.\n"],"mappings":";;;;;;;;;;;;AAaA,IAAM,iCAAiB,IAAI,IAAI;CAAC;CAAa;CAAa;AAAK,CAAC;;;;;AAMhE,SAAS,iBAAiB,QAAyB;CAClD,IAAI;CACJ,IAAI;EACH,MAAM,IAAI,IAAI,MAAM;CACrB,QAAQ;EACP,OAAO;CACR;CACA,IAAI,IAAI,aAAa,WAAW,IAAI,aAAa,UAAU,OAAO;CAClE,IAAI,IAAI,YAAY,IAAI,UAAU,OAAO;CACzC,MAAM,WAAW,IAAI,SAAS,WAAW,GAAG,IAAI,IAAI,SAAS,MAAM,GAAG,EAAE,IAAI,IAAI;CAChF,OAAO,eAAe,IAAI,QAAQ;AACnC;;AAGA,IAAM,iCAAiB,IAAI,IAAI;CAAC;CAAQ;CAAU;CAAS;AAAK,CAAC;;;;;;;;;AAUjE,SAAS,sBAAsB,GAAqB;CACnD,MAAM,gBAAgB,EAAE,IAAI,OAAO,gBAAg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AW,SAAS,GACxB,MAAM,IAAI,MACT,4BAA4B,UAAU,oEACvC;CAED,MAAM,YAAY,aAAa,WAAW,OAAO;CACjD,IAAI,IAAI,MAAM,MAAM;EACnB,IAAI,EAAE,IAAI,KAAK,WAAW,OAAO,GAChC,OAAO,EAAE,KAAK,EAAE,OAAO,YAAY,GAAG,GAAG;EAE1C,EAAE,OAAO,iBAAiB,UAAU;EACpC,OAAO,EAAE,KAAK,SAAS;CACxB,CAAC;CAED,OAAO;AACR;;;;;;;;;;;AAYA,SAAgB,cAAc,MAAmB;CAChD,MAAM,eAAe,MAAM,gBAAgB;CAC3C,MAAM,mBAAmB,MAAM,wBAAwB,CAAC;CACxD,MAAM,cAAc,iBAAiB,WAAW,iCAAiC;CACjF,MAAM,YAAY,KAAK,IAAI,GAAG,KAAK,MAAM,iBAAiB,aAAa,GAAG,CAAC;CAC3E,MAAM,gBAAgB,KAAK,IAAI,GAAG,KAAK,MAAM,iBAAiB,iBAAiB,EAAE,CAAC;CAClF,MAAM,MAAM,IAAI,KAAK;CACrB,IAAI,MACH,KACA,mBAAmB,cAAc,EAChC,gBAAgB;EACf,SAAS;EACT;EACA;EACA,0BAA0B,KAAK,IAC9B,GACA,KAAK,MAAM,iBAAiB,4BAA4B,KAAK,IAAI,IAAI,SAAS,CAAC,CAChF;EACA,8BAA8B,KAAK,IAClC,GACA,KAAK,MAAM,iBAAiB,gCAAgC,KAAK,IAAI,IAAI,aAAa,CAAC,CACxF;CACD,EACD,CAAC,CACF;CAGA,IAAI,IAAI,MAAM,MAAM,EAAE,KAAK,EAAE,OAAO,YAAY,GAAG,GAAG,CAAC;CAEvD,OAAO;AACR"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/middleware.ts","../src/request-rate-limit.ts","../src/routes/config.ts","../src/routes/diagnostics.ts","../src/routes/health.ts","../src/helpers.ts","../src/routes/memory.ts","../src/routes/observer-status.ts","../src/routes/target-validation.ts","../src/routes/pack.ts","../src/routes/raw-events.ts","../src/routes/stats.ts","../src/routes/team-setup-view.ts","../src/routes/team-setup.ts","../src/routes/sync.ts","../src/routes/update-status.ts","../src/index.ts"],"sourcesContent":["/**\n * CORS and cross-origin protection middleware.\n *\n * Ports Python's reject_cross_origin() logic from codemem/viewer_http.py.\n * GETs are allowed from any origin by default (viewer is local-only).\n * Callers can mark side-effecting GET path prefixes as unsafe.\n * Mutations (POST/DELETE/PATCH/PUT) require an Origin header matching a\n * loopback address, or are rejected with 403.\n */\n\nimport type { Context, Next } from \"hono\";\nimport { createMiddleware } from \"hono/factory\";\n\nconst LOOPBACK_HOSTS = new Set([\"127.0.0.1\", \"localhost\", \"::1\"]);\n\n/**\n * Check whether an Origin header value is a valid loopback URL.\n * Mirrors Python's _is_allowed_loopback_origin_url().\n */\nfunction isLoopbackOrigin(origin: string): boolean {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(origin);\n\t} catch {\n\t\treturn false;\n\t}\n\tif (url.protocol !== \"http:\" && url.protocol !== \"https:\") return false;\n\tif (url.username || url.password) return false;\n\tconst hostname = url.hostname.startsWith(\"[\") ? url.hostname.slice(1, -1) : url.hostname;\n\treturn LOOPBACK_HOSTS.has(hostname);\n}\n\n/** HTTP methods that mutate state and require origin validation. */\nconst UNSAFE_METHODS = new Set([\"POST\", \"DELETE\", \"PATCH\", \"PUT\"]);\n\n/**\n * Check whether a missing-Origin request looks like a cross-site browser\n * request. Matches Python's `_is_unsafe_missing_origin()`:\n *\n * - Sec-Fetch-Site present and NOT same-origin/same-site/none → unsafe\n * - Referer present and NOT loopback → unsafe\n * - Otherwise → safe (CLI / programmatic caller, no browser context)\n */\nfunction isUnsafeMissingOrigin(c: Context): boolean {\n\tconst secFetchSite = (c.req.header(\"Sec-Fetch-Site\") ?? \"\").trim().toLowerCase();\n\tif (secFetchSite && ![\"same-origin\", \"same-site\", \"none\"].includes(secFetchSite)) {\n\t\treturn true;\n\t}\n\tconst referer = c.req.header(\"Referer\");\n\tif (!referer) return false;\n\treturn !isLoopbackOrigin(referer);\n}\n\n/**\n * Cross-origin protection middleware.\n *\n * Ports Python's `reject_cross_origin(missing_origin_policy=\"reject_if_unsafe\")`:\n *\n * - GET/HEAD/OPTIONS: allowed from any origin unless the caller marks a\n * side-effecting GET path prefix as unsafe.\n * - POST/DELETE/PATCH/PUT:\n * - Origin present + loopback → allowed (browser on localhost)\n * - Origin present + non-loopback → rejected 403\n * - No Origin + no suspicious browser signals → allowed (CLI callers)\n * - No Origin + suspicious Sec-Fetch-Site/Referer → rejected 403\n *\n * For same-origin requests (no Origin header) on safe methods, no\n * Access-Control-Allow-Origin is set — the browser doesn't need it.\n * For valid loopback origins, ACAO is echoed back.\n */\nexport function originGuard(options?: { unsafeGetPathPrefixes?: readonly string[] }) {\n\treturn createMiddleware(async (c: Context, next: Next) => {\n\t\tconst origin = c.req.header(\"Origin\");\n\t\tconst method = c.req.method;\n\t\tconst unsafeGet =\n\t\t\t(method === \"GET\" || method === \"HEAD\") &&\n\t\t\toptions?.unsafeGetPathPrefixes?.some((prefix) => c.req.path.startsWith(prefix));\n\n\t\tif (UNSAFE_METHODS.has(method) || unsafeGet) {\n\t\t\tif (origin) {\n\t\t\t\t// Origin present — must be loopback\n\t\t\t\tif (!isLoopbackOrigin(origin)) {\n\t\t\t\t\treturn c.json({ error: \"forbidden\" }, 403);\n\t\t\t\t}\n\t\t\t\t// Valid loopback origin — echo it for CORS\n\t\t\t\tc.header(\"Access-Control-Allow-Origin\", origin);\n\t\t\t\tc.header(\"Access-Control-Allow-Methods\", \"GET, POST, PUT, DELETE, OPTIONS\");\n\t\t\t\tc.header(\"Access-Control-Allow-Headers\", \"Content-Type\");\n\t\t\t} else {\n\t\t\t\t// No Origin — reject only if browser signals indicate cross-site\n\t\t\t\t// (matches Python's reject_if_unsafe policy for API endpoints)\n\t\t\t\tif (isUnsafeMissingOrigin(c)) {\n\t\t\t\t\treturn c.json({ error: \"forbidden\" }, 403);\n\t\t\t\t}\n\t\t\t\t// CLI / programmatic caller — no CORS headers needed\n\t\t\t}\n\t\t} else if (origin && isLoopbackOrigin(origin)) {\n\t\t\t// Safe method with valid origin — echo for preflight\n\t\t\tc.header(\"Access-Control-Allow-Origin\", origin);\n\t\t\tc.header(\"Access-Control-Allow-Methods\", \"GET, POST, PUT, DELETE, OPTIONS\");\n\t\t\tc.header(\"Access-Control-Allow-Headers\", \"Content-Type\");\n\t\t}\n\t\t// No origin or non-loopback on safe method: no ACAO header set.\n\t\t// Browser enforces same-origin; we don't set permissive headers.\n\n\t\tawait next();\n\t});\n}\n\n/**\n * Handle OPTIONS preflight requests.\n * Returns 204 with appropriate CORS headers for loopback origins.\n */\nexport function preflightHandler() {\n\treturn createMiddleware(async (c: Context, next: Next) => {\n\t\tif (c.req.method !== \"OPTIONS\") {\n\t\t\tawait next();\n\t\t\treturn;\n\t\t}\n\t\tconst origin = c.req.header(\"Origin\");\n\t\tif (origin && isLoopbackOrigin(origin)) {\n\t\t\tc.header(\"Access-Control-Allow-Origin\", origin);\n\t\t\tc.header(\"Access-Control-Allow-Methods\", \"GET, POST, PUT, DELETE, OPTIONS\");\n\t\t\tc.header(\"Access-Control-Allow-Headers\", \"Content-Type\");\n\t\t\tc.header(\"Access-Control-Max-Age\", \"86400\");\n\t\t\treturn c.body(null, 204);\n\t\t}\n\t\treturn c.body(null, 204);\n\t});\n}\n","import { RateLimiter } from \"limiter\";\n\nexport interface InMemoryRequestRateLimiter {\n\tcheck(key: string, limit: number): { allowed: boolean; retryAfterS: number };\n}\n\nexport function createInMemoryRequestRateLimiter(windowMs = 60_000): InMemoryRequestRateLimiter {\n\tconst safeWindowMs = Math.max(1000, Math.trunc(windowMs));\n\tconst buckets = new Map<string, { limiter: RateLimiter; lastUsedAt: number }>();\n\tlet checks = 0;\n\n\tfunction estimatedRetryAfterS(limit: number): number {\n\t\treturn Math.max(1, Math.ceil(safeWindowMs / Math.max(1, limit) / 1000));\n\t}\n\n\tfunction cleanupExpiredBuckets(currentNow: number): void {\n\t\tif (buckets.size < 64 || checks % 64 !== 0) return;\n\t\tconst staleBefore = currentNow - safeWindowMs * 10;\n\t\tfor (const [key, bucket] of buckets) {\n\t\t\tif (bucket.lastUsedAt < staleBefore) buckets.delete(key);\n\t\t}\n\t}\n\n\treturn {\n\t\tcheck(key: string, limit: number) {\n\t\t\tchecks += 1;\n\t\t\tconst currentNow = Date.now();\n\t\t\tcleanupExpiredBuckets(currentNow);\n\t\t\tconst safeLimit = Math.max(1, Math.trunc(limit));\n\t\t\tconst bucketKey = `${safeLimit}:${key}`;\n\t\t\tlet bucket = buckets.get(bucketKey);\n\t\t\tif (!bucket) {\n\t\t\t\tbucket = {\n\t\t\t\t\tlimiter: new RateLimiter({\n\t\t\t\t\t\ttokensPerInterval: safeLimit,\n\t\t\t\t\t\tinterval: safeWindowMs,\n\t\t\t\t\t\tfireImmediately: true,\n\t\t\t\t\t}),\n\t\t\t\t\tlastUsedAt: currentNow,\n\t\t\t\t};\n\t\t\t\tbuckets.set(bucketKey, bucket);\n\t\t\t}\n\t\t\tbucket.lastUsedAt = currentNow;\n\t\t\tif (bucket.limiter.tryRemoveTokens(1)) {\n\t\t\t\treturn { allowed: true, retryAfterS: 0 };\n\t\t\t}\n\t\t\treturn { allowed: false, retryAfterS: estimatedRetryAfterS(safeLimit) };\n\t\t},\n\t};\n}\n","/**\n * Config routes — GET /api/config, POST /api/config.\n *\n * Ports the user-facing config read/write path from Python's\n * codemem/viewer_routes/config.py, scoped to the TS runtime's current needs.\n */\n\nimport {\n\tCODEMEM_CONFIG_ENV_OVERRIDES,\n\tcoerceObserverCommand,\n\tgetCodememConfigPath,\n\tgetCodememEnvOverrides,\n\tlistObserverProviderOptions,\n\ttype RawEventSweeper,\n\treadCodememConfigFile,\n\twriteCodememConfigFile,\n} from \"@codemem/core\";\nimport { Hono } from \"hono\";\n\ntype ConfigData = Record<string, unknown>;\n\nconst REDACTED_VALUE = \"[redacted]\";\n\nconst RUNTIMES = new Set([\"api_http\", \"claude_sidecar\", \"codex_sidecar\"]);\nconst AUTH_SOURCES = new Set([\"auto\", \"env\", \"file\", \"command\", \"none\"]);\nconst HOT_RELOAD_KEYS = new Set([\"raw_events_sweeper_interval_s\"]);\nconst PROTECTED_WRITE_KEYS = new Set<string>([\n\t\"claude_command\",\n\t\"codex_command\",\n\t\"observer_base_url\",\n\t\"observer_auth_file\",\n\t\"observer_auth_command\",\n\t\"observer_headers\",\n\t\"sync_coordinator_url\",\n] as const);\nconst SECRET_CONFIG_KEYS = new Set<string>([\n\t\"observer_auth_file\",\n\t\"observer_auth_command\",\n\t\"observer_headers\",\n\t\"sync_coordinator_admin_secret\",\n] as const);\nconst REMOVED_CONFIG_KEYS = new Set<string>([\"observer_rich_openai_use_responses\"]);\nconst ALLOWED_KEYS = [\n\t\"claude_command\",\n\t\"codex_command\",\n\t\"observer_base_url\",\n\t\"observer_provider\",\n\t\"observer_model\",\n\t\"observer_tier_routing_enabled\",\n\t\"observer_simple_model\",\n\t\"observer_simple_temperature\",\n\t\"observer_reasoning_effort\",\n\t\"observer_reasoning_summary\",\n\t\"observer_rich_model\",\n\t\"observer_rich_temperature\",\n\t\"observer_rich_reasoning_effort\",\n\t\"observer_rich_reasoning_summary\",\n\t\"observer_rich_max_output_tokens\",\n\t\"observer_runtime\",\n\t\"observer_auth_source\",\n\t\"observer_auth_file\",\n\t\"observer_auth_command\",\n\t\"observer_auth_timeout_ms\",\n\t\"observer_auth_cache_ttl_s\",\n\t\"observer_headers\",\n\t\"observer_max_chars\",\n\t\"pack_observation_limit\",\n\t\"pack_session_limit\",\n\t\"sync_enabled\",\n\t\"sync_retention_enabled\",\n\t\"sync_retention_max_age_days\",\n\t\"sync_retention_max_size_mb\",\n\t\"sync_host\",\n\t\"sync_port\",\n\t\"sync_interval_s\",\n\t\"sync_mdns\",\n\t\"sync_coordinator_url\",\n\t\"sync_coordinator_group\",\n\t\"sync_coordinator_timeout_s\",\n\t\"sync_coordinator_presence_ttl_s\",\n\t\"raw_events_sweeper_interval_s\",\n] as const;\n\nconst DEFAULTS: ConfigData = {\n\tclaude_command: [\"claude\"],\n\tcodex_command: [\"codex\"],\n\tobserver_runtime: \"api_http\",\n\tobserver_auth_source: \"auto\",\n\tobserver_tier_routing_enabled: false,\n\tobserver_auth_command: [],\n\tobserver_auth_timeout_ms: 1500,\n\tobserver_auth_cache_ttl_s: 300,\n\tobserver_headers: {},\n\tobserver_max_chars: 12000,\n\tpack_observation_limit: 50,\n\tpack_session_limit: 10,\n\tsync_enabled: false,\n\tsync_retention_enabled: false,\n\tsync_retention_max_age_days: 30,\n\tsync_retention_max_size_mb: 512,\n\tsync_host: \"0.0.0.0\",\n\tsync_port: 7337,\n\tsync_interval_s: 120,\n\tsync_mdns: true,\n\tsync_coordinator_timeout_s: 3,\n\tsync_coordinator_presence_ttl_s: 180,\n\traw_events_sweeper_interval_s: 30,\n};\n\nexport interface ConfigRouteOptions {\n\tgetSweeper?: () => RawEventSweeper | null;\n}\n\nfunction loadProviderOptions(): string[] {\n\treturn listObserverProviderOptions();\n}\n\nfunction withoutRemovedConfigKeys(configData: ConfigData): ConfigData {\n\tconst next = { ...configData };\n\tfor (const key of REMOVED_CONFIG_KEYS) {\n\t\tdelete next[key];\n\t}\n\treturn next;\n}\n\nfunction getEffectiveConfig(configData: ConfigData): ConfigData {\n\tconst effective: ConfigData = { ...DEFAULTS, ...configData };\n\tfor (const key of [\"claude_command\", \"codex_command\"] as const) {\n\t\teffective[key] = coerceObserverCommand(effective[key]) ?? DEFAULTS[key];\n\t}\n\tfor (const [key, envVar] of Object.entries(CODEMEM_CONFIG_ENV_OVERRIDES) as Array<\n\t\t[string, string]\n\t>) {\n\t\tconst val = process.env[envVar];\n\t\tif (val == null || val === \"\") continue;\n\t\tif (key === \"claude_command\" || key === \"codex_command\") {\n\t\t\teffective[key] = coerceObserverCommand(val) ?? effective[key];\n\t\t} else {\n\t\t\teffective[key] = val;\n\t\t}\n\t}\n\treturn effective;\n}\n\nfunction redactConfigValue(key: string, value: unknown): unknown {\n\tif (value == null || !SECRET_CONFIG_KEYS.has(key)) return value;\n\tif (Array.isArray(value)) return value.length > 0 ? REDACTED_VALUE : [];\n\tif (typeof value === \"object\") {\n\t\treturn Object.keys(value as Record<string, unknown>).length > 0 ? REDACTED_VALUE : {};\n\t}\n\tif (typeof value === \"string\") return value.trim() ? REDACTED_VALUE : \"\";\n\treturn REDACTED_VALUE;\n}\n\nfunction sanitizeConfigForResponse(configData: ConfigData): ConfigData {\n\tconst sanitized: ConfigData = {};\n\tfor (const [key, value] of Object.entries(configData)) {\n\t\tsanitized[key] = redactConfigValue(key, value);\n\t}\n\treturn sanitized;\n}\n\nfunction configValuesEqual(left: unknown, right: unknown): boolean {\n\tif (Object.is(left, right)) return true;\n\tif (left == null || right == null) return left == null && right == null;\n\tif (typeof left === \"object\" || typeof right === \"object\") {\n\t\treturn JSON.stringify(left) === JSON.stringify(right);\n\t}\n\treturn false;\n}\n\nfunction partitionViewerUpdates(\n\tupdates: ConfigData,\n\tbeforeConfig: ConfigData,\n): { allowedUpdates: ConfigData; error: string | null } {\n\tconst allowedUpdates: ConfigData = {};\n\tfor (const [key, value] of Object.entries(updates)) {\n\t\tif (!PROTECTED_WRITE_KEYS.has(key)) {\n\t\t\tallowedUpdates[key] = value;\n\t\t\tcontinue;\n\t\t}\n\t\tif (SECRET_CONFIG_KEYS.has(key) && value === REDACTED_VALUE) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (configValuesEqual(value, beforeConfig[key])) {\n\t\t\tcontinue;\n\t\t}\n\t\treturn {\n\t\t\tallowedUpdates: {},\n\t\t\terror: `${key} cannot be changed from the viewer API; edit the config file or environment instead`,\n\t\t};\n\t}\n\treturn { allowedUpdates, error: null };\n}\n\nfunction parsePositiveInt(value: unknown, allowZero = false): number | null {\n\tif (typeof value === \"boolean\") return null;\n\tconst parsed =\n\t\ttypeof value === \"number\"\n\t\t\t? value\n\t\t\t: typeof value === \"string\" && /^-?\\d+$/.test(value.trim())\n\t\t\t\t? Number(value.trim())\n\t\t\t\t: Number.NaN;\n\tif (!Number.isFinite(parsed) || !Number.isInteger(parsed)) return null;\n\tif (allowZero) return parsed >= 0 ? parsed : null;\n\treturn parsed > 0 ? parsed : null;\n}\n\nfunction parseFiniteNumber(value: unknown, allowZero = true): number | null {\n\tif (typeof value === \"boolean\") return null;\n\tconst parsed =\n\t\ttypeof value === \"number\"\n\t\t\t? value\n\t\t\t: typeof value === \"string\" && value.trim().length > 0\n\t\t\t\t? Number(value.trim())\n\t\t\t\t: Number.NaN;\n\tif (!Number.isFinite(parsed)) return null;\n\tif (allowZero) return parsed >= 0 ? parsed : null;\n\treturn parsed > 0 ? parsed : null;\n}\n\nfunction asStringMap(value: unknown): Record<string, string> | null {\n\tif (value == null || typeof value !== \"object\" || Array.isArray(value)) return null;\n\tconst parsed: Record<string, string> = {};\n\tfor (const [key, item] of Object.entries(value)) {\n\t\tif (typeof item !== \"string\") return null;\n\t\tconst stripped = key.trim();\n\t\tif (!stripped) return null;\n\t\tparsed[stripped] = item;\n\t}\n\treturn parsed;\n}\n\nfunction asExecutableArgv(value: unknown): string[] | null {\n\tif (!Array.isArray(value)) return null;\n\tconst argv: string[] = [];\n\tfor (const item of value) {\n\t\tif (typeof item !== \"string\") return null;\n\t\tconst token = item.trim();\n\t\tif (!token) return null;\n\t\targv.push(token);\n\t}\n\treturn argv;\n}\n\nfunction validateAndApplyUpdate(\n\tconfigData: ConfigData,\n\tkey: (typeof ALLOWED_KEYS)[number],\n\tvalue: unknown,\n\tproviders: Set<string>,\n): string | null {\n\tif (value == null || value === \"\") {\n\t\tdelete configData[key];\n\t\treturn null;\n\t}\n\tif (key === \"observer_provider\") {\n\t\tif (typeof value !== \"string\") return \"observer_provider must be string\";\n\t\tconst provider = value.trim().toLowerCase();\n\t\tconst savedBaseUrl = configData.observer_base_url;\n\t\tconst hasSavedBaseUrl = typeof savedBaseUrl === \"string\" && savedBaseUrl.trim().length > 0;\n\t\tif (!providers.has(provider) && !hasSavedBaseUrl) {\n\t\t\treturn \"observer_provider must match a configured provider\";\n\t\t}\n\t\tconfigData[key] = provider;\n\t\treturn null;\n\t}\n\tif (key === \"observer_runtime\") {\n\t\tif (typeof value !== \"string\") return \"observer_runtime must be string\";\n\t\tconst runtime = value.trim().toLowerCase();\n\t\tif (!RUNTIMES.has(runtime)) {\n\t\t\treturn \"observer_runtime must be one of: api_http, claude_sidecar, codex_sidecar\";\n\t\t}\n\t\tconfigData[key] = runtime;\n\t\treturn null;\n\t}\n\tif (key === \"observer_auth_source\") {\n\t\tif (typeof value !== \"string\") return \"observer_auth_source must be string\";\n\t\tconst source = value.trim().toLowerCase();\n\t\tif (!AUTH_SOURCES.has(source)) {\n\t\t\treturn \"observer_auth_source must be one of: auto, env, file, command, none\";\n\t\t}\n\t\tconfigData[key] = source;\n\t\treturn null;\n\t}\n\tif (key === \"claude_command\" || key === \"codex_command\" || key === \"observer_auth_command\") {\n\t\tconst argv = asExecutableArgv(value);\n\t\tif (argv == null) return `${key} must be string array`;\n\t\tif (argv.length > 0) configData[key] = argv;\n\t\telse delete configData[key];\n\t\treturn null;\n\t}\n\tif (key === \"observer_headers\") {\n\t\tconst headers = asStringMap(value);\n\t\tif (headers == null) return \"observer_headers must be object of string values\";\n\t\tif (Object.keys(headers).length > 0) configData[key] = headers;\n\t\telse delete configData[key];\n\t\treturn null;\n\t}\n\tif (key === \"sync_enabled\" || key === \"sync_retention_enabled\" || key === \"sync_mdns\") {\n\t\tif (typeof value !== \"boolean\") return `${key} must be boolean`;\n\t\tconfigData[key] = value;\n\t\treturn null;\n\t}\n\tif (key === \"observer_tier_routing_enabled\") {\n\t\tif (typeof value !== \"boolean\") return `${key} must be boolean`;\n\t\tconfigData[key] = value;\n\t\treturn null;\n\t}\n\tif (\n\t\tkey === \"observer_base_url\" ||\n\t\tkey === \"observer_model\" ||\n\t\tkey === \"observer_simple_model\" ||\n\t\tkey === \"observer_reasoning_effort\" ||\n\t\tkey === \"observer_reasoning_summary\" ||\n\t\tkey === \"observer_rich_model\" ||\n\t\tkey === \"observer_rich_reasoning_effort\" ||\n\t\tkey === \"observer_rich_reasoning_summary\" ||\n\t\tkey === \"observer_auth_file\" ||\n\t\tkey === \"sync_host\" ||\n\t\tkey === \"sync_coordinator_url\" ||\n\t\tkey === \"sync_coordinator_group\"\n\t) {\n\t\tif (typeof value !== \"string\") return `${key} must be string`;\n\t\tconst trimmed = value.trim();\n\t\tif (!trimmed) delete configData[key];\n\t\telse configData[key] = trimmed;\n\t\treturn null;\n\t}\n\tif (key === \"observer_simple_temperature\" || key === \"observer_rich_temperature\") {\n\t\tconst parsed = parseFiniteNumber(value, true);\n\t\tif (parsed == null) return `${key} must be non-negative number`;\n\t\tconfigData[key] = parsed;\n\t\treturn null;\n\t}\n\tconst allowZero = key === \"observer_auth_cache_ttl_s\";\n\tconst parsed = parsePositiveInt(value, allowZero);\n\tif (parsed == null) return `${key} must be ${allowZero ? \"non-negative int\" : \"int\"}`;\n\tconfigData[key] = parsed;\n\treturn null;\n}\n\nfunction applyRuntimeEffects(changedKeys: string[], opts: ConfigRouteOptions): string[] {\n\tconst applied: string[] = [];\n\tif (changedKeys.includes(\"raw_events_sweeper_interval_s\")) {\n\t\tconst configValue = readCodememConfigFile().raw_events_sweeper_interval_s;\n\t\tconst seconds =\n\t\t\ttypeof configValue === \"number\"\n\t\t\t\t? configValue\n\t\t\t\t: Number.parseInt(String(configValue ?? \"\"), 10);\n\t\tif (Number.isFinite(seconds) && seconds > 0) {\n\t\t\tprocess.env.CODEMEM_RAW_EVENTS_SWEEPER_INTERVAL_MS = String(seconds * 1000);\n\t\t} else {\n\t\t\tdelete process.env.CODEMEM_RAW_EVENTS_SWEEPER_INTERVAL_MS;\n\t\t}\n\t\topts.getSweeper?.()?.notifyConfigChanged();\n\t\tapplied.push(\"raw_events_sweeper_interval_s\");\n\t}\n\treturn applied;\n}\n\nexport function configRoutes(opts: ConfigRouteOptions = {}) {\n\tconst app = new Hono();\n\n\tapp.get(\"/api/config\", (c) => {\n\t\t// Resolve via the core resolver so GET reflects the same file POST\n\t\t// writes — including workspace-scoped overrides honored through\n\t\t// CODEMEM_RUNTIME_ROOT / CODEMEM_WORKSPACE_ID, which the legacy local\n\t\t// getConfigPath() ignored.\n\t\tconst configPath = getCodememConfigPath();\n\t\tconst configData = withoutRemovedConfigKeys(readCodememConfigFile());\n\t\tconst effective = getEffectiveConfig(configData);\n\t\treturn c.json({\n\t\t\tpath: configPath,\n\t\t\tconfig: sanitizeConfigForResponse(configData),\n\t\t\tdefaults: DEFAULTS,\n\t\t\teffective: sanitizeConfigForResponse(effective),\n\t\t\tenv_overrides: getCodememEnvOverrides(),\n\t\t\tprotected_keys: [...PROTECTED_WRITE_KEYS].sort(),\n\t\t\tproviders: loadProviderOptions(),\n\t\t});\n\t});\n\n\tapp.post(\"/api/config\", async (c) => {\n\t\tlet payload: unknown;\n\t\ttry {\n\t\t\tpayload = (await c.req.json()) as unknown;\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\" }, 400);\n\t\t}\n\t\tif (payload == null || typeof payload !== \"object\" || Array.isArray(payload)) {\n\t\t\treturn c.json({ error: \"payload must be an object\" }, 400);\n\t\t}\n\t\tif (\n\t\t\t\"config\" in payload &&\n\t\t\t(payload as ConfigData).config != null &&\n\t\t\t(typeof (payload as ConfigData).config !== \"object\" ||\n\t\t\t\tArray.isArray((payload as ConfigData).config))\n\t\t) {\n\t\t\treturn c.json({ error: \"config must be an object\" }, 400);\n\t\t}\n\t\tconst updates =\n\t\t\t\"config\" in payload &&\n\t\t\t(payload as ConfigData).config != null &&\n\t\t\ttypeof (payload as ConfigData).config === \"object\" &&\n\t\t\t!Array.isArray((payload as ConfigData).config)\n\t\t\t\t? ((payload as ConfigData).config as ConfigData)\n\t\t\t\t: (payload as ConfigData);\n\n\t\tconst configPath = getCodememConfigPath();\n\t\tconst beforeConfig = withoutRemovedConfigKeys(readCodememConfigFile());\n\t\tconst { allowedUpdates, error: protectedKeyError } = partitionViewerUpdates(\n\t\t\tupdates,\n\t\t\tbeforeConfig,\n\t\t);\n\t\tif (protectedKeyError) {\n\t\t\treturn c.json({ error: protectedKeyError }, 403);\n\t\t}\n\n\t\tconst beforeEffective = getEffectiveConfig(beforeConfig);\n\t\tconst nextConfig: ConfigData = { ...beforeConfig };\n\t\tconst providers = new Set(loadProviderOptions());\n\n\t\tconst touchedKeys = ALLOWED_KEYS.filter((key) => key in allowedUpdates);\n\t\tfor (const key of ALLOWED_KEYS) {\n\t\t\tif (!(key in allowedUpdates)) continue;\n\t\t\tconst error = validateAndApplyUpdate(nextConfig, key, allowedUpdates[key], providers);\n\t\t\tif (error) return c.json({ error }, 400);\n\t\t}\n\n\t\tlet savedPath: string;\n\t\ttry {\n\t\t\tsavedPath = writeCodememConfigFile(nextConfig, configPath);\n\t\t} catch {\n\t\t\treturn c.json({ error: \"failed to write config\" }, 500);\n\t\t}\n\n\t\tconst afterEffective = getEffectiveConfig(nextConfig);\n\t\tconst savedChangedKeys = ALLOWED_KEYS.filter((key) => beforeConfig[key] !== nextConfig[key]);\n\t\tconst effectiveChangedKeys = ALLOWED_KEYS.filter(\n\t\t\t(key) => !configValuesEqual(beforeEffective[key], afterEffective[key]),\n\t\t);\n\t\tconst envOverrides = getCodememEnvOverrides();\n\t\tconst ignoredByEnvKeys = savedChangedKeys.filter(\n\t\t\t(key) => !effectiveChangedKeys.includes(key) && key in envOverrides,\n\t\t);\n\t\tconst runtimeChangedKeys = [\n\t\t\t...new Set([...touchedKeys, ...savedChangedKeys, ...effectiveChangedKeys]),\n\t\t];\n\t\tconst hotReloadedKeys = applyRuntimeEffects(runtimeChangedKeys, opts);\n\t\tconst restartRequiredKeys = effectiveChangedKeys.filter(\n\t\t\t(key) => !HOT_RELOAD_KEYS.has(key) && !(key in envOverrides),\n\t\t);\n\n\t\treturn c.json({\n\t\t\tpath: savedPath,\n\t\t\tconfig: sanitizeConfigForResponse(nextConfig),\n\t\t\teffective: sanitizeConfigForResponse(afterEffective),\n\t\t\tprotected_keys: [...PROTECTED_WRITE_KEYS].sort(),\n\t\t\teffects: {\n\t\t\t\tsaved_keys: savedChangedKeys,\n\t\t\t\teffective_keys: effectiveChangedKeys,\n\t\t\t\thot_reloaded_keys: hotReloadedKeys,\n\t\t\t\trestart_required_keys: restartRequiredKeys,\n\t\t\t\tignored_by_env_keys: ignoredByEnvKeys,\n\t\t\t\twarnings: ignoredByEnvKeys.map(\n\t\t\t\t\t(key) =>\n\t\t\t\t\t\t`${key} is currently controlled by ${envOverrides[key]}; saved config will not take effect until that override is removed.`,\n\t\t\t\t),\n\t\t\t},\n\t\t});\n\t});\n\n\treturn app;\n}\n","import { createCipheriv, createDecipheriv, createHash, randomBytes } from \"node:crypto\";\nimport type { MemoryStore } from \"@codemem/core\";\nimport { Hono } from \"hono\";\n\nconst DEFAULT_LIMIT = 50;\nconst MAX_LIMIT = 100;\nconst CURSOR_KEY = randomBytes(32);\n\nexport const DIAGNOSTIC_SEVERITIES = [\"info\", \"warning\", \"error\"] as const;\nexport const DIAGNOSTIC_SUBSYSTEMS = [\n\t\"viewer\",\n\t\"observer\",\n\t\"capture\",\n\t\"sync\",\n\t\"storage\",\n\t\"maintenance\",\n] as const;\n\nexport type DiagnosticSeverity = (typeof DIAGNOSTIC_SEVERITIES)[number];\nexport type DiagnosticSubsystem = (typeof DIAGNOSTIC_SUBSYSTEMS)[number];\n\nexport type DiagnosticEvent = {\n\tid: string;\n\toccurred_at: string;\n\tseverity: DiagnosticSeverity;\n\tsubsystem: DiagnosticSubsystem;\n\tcode: string;\n\tmessage: string;\n\trecovery?: { label: string; href?: string; command?: string };\n\tcorrelation?: { kind: \"session\" | \"device\" | \"operation\"; label: string };\n\ttechnical_detail?: { available: boolean; text?: string };\n};\n\ntype Cursor = { occurredAt: string; orderKey: string };\ntype StoreFactory = () => MemoryStore;\ntype EventOptions = {\n\tcursor: Cursor | null;\n\tincludeTechnical: boolean;\n\tlimit: number;\n\tseverities: Set<DiagnosticSeverity>;\n\tsubsystems: Set<DiagnosticSubsystem>;\n};\n\ntype OrderedDiagnosticEvent = DiagnosticEvent & { orderKey: string };\n\nfunction opaqueId(kind: string, sourceId: unknown): string {\n\treturn createHash(\"sha256\")\n\t\t.update(`${kind}\\0${String(sourceId)}`)\n\t\t.digest(\"base64url\")\n\t\t.slice(0, 22);\n}\n\nfunction encodeCursor(event: OrderedDiagnosticEvent): string {\n\tconst iv = randomBytes(12);\n\tconst cipher = createCipheriv(\"aes-256-gcm\", CURSOR_KEY, iv);\n\tconst plaintext = JSON.stringify({ occurredAt: event.occurred_at, orderKey: event.orderKey });\n\tconst encrypted = Buffer.concat([cipher.update(plaintext, \"utf8\"), cipher.final()]);\n\treturn Buffer.concat([iv, cipher.getAuthTag(), encrypted]).toString(\"base64url\");\n}\n\nfunction parseCursor(raw: string | undefined): Cursor | null | \"invalid\" {\n\tif (!raw) return null;\n\ttry {\n\t\tconst encoded = Buffer.from(raw, \"base64url\");\n\t\tif (encoded.length < 29) return \"invalid\";\n\t\tconst decipher = createDecipheriv(\"aes-256-gcm\", CURSOR_KEY, encoded.subarray(0, 12));\n\t\tdecipher.setAuthTag(encoded.subarray(12, 28));\n\t\tconst plaintext = Buffer.concat([\n\t\t\tdecipher.update(encoded.subarray(28)),\n\t\t\tdecipher.final(),\n\t\t]).toString(\"utf8\");\n\t\tconst parsed = JSON.parse(plaintext) as Record<string, unknown>;\n\t\tif (\n\t\t\ttypeof parsed.occurredAt !== \"string\" ||\n\t\t\t!/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9:.+-]+Z$/.test(parsed.occurredAt) ||\n\t\t\t!Number.isFinite(Date.parse(parsed.occurredAt))\n\t\t) {\n\t\t\treturn \"invalid\";\n\t\t}\n\t\tif (\n\t\t\ttypeof parsed.orderKey !== \"string\" ||\n\t\t\tparsed.orderKey.length < 3 ||\n\t\t\tparsed.orderKey.length > 2_048\n\t\t) {\n\t\t\treturn \"invalid\";\n\t\t}\n\t\treturn { occurredAt: parsed.occurredAt, orderKey: parsed.orderKey };\n\t} catch {\n\t\treturn \"invalid\";\n\t}\n}\n\nfunction parseLimit(raw: string | undefined): number | \"invalid\" {\n\tif (raw == null || raw === \"\") return DEFAULT_LIMIT;\n\tif (!/^\\d+$/.test(raw)) return \"invalid\";\n\tconst parsed = Number(raw);\n\tif (!Number.isSafeInteger(parsed) || parsed <= 0) return \"invalid\";\n\treturn Math.min(parsed, MAX_LIMIT);\n}\n\nfunction parseFilter<T extends string>(\n\traw: string | undefined,\n\tallowed: readonly T[],\n): Set<T> | \"invalid\" {\n\tif (raw == null) return new Set(allowed);\n\tconst values = raw\n\t\t.split(\",\")\n\t\t.map((value) => value.trim())\n\t\t.filter(Boolean);\n\tif (!values.length || values.some((value) => !allowed.includes(value as T))) return \"invalid\";\n\treturn new Set(values as T[]);\n}\n\nfunction parseTechnical(raw: string | undefined): boolean | \"invalid\" {\n\tif (raw == null || raw === \"0\") return false;\n\tif (raw === \"1\") return true;\n\treturn \"invalid\";\n}\n\nfunction technicalDetail(available: boolean, text: string, include: boolean) {\n\tif (!available) return { available: false };\n\treturn include ? { available: true, text: text.slice(0, 2_000) } : { available: true };\n}\n\ntype DiagnosticSourceRow = {\n\tsource_type: \"sync\" | \"observer\" | \"capture_failure\" | \"backlog\" | \"maintenance\";\n\tsource_id: number | string;\n\torder_key: string;\n\toccurred_at: string;\n\tstatus: string;\n\tmetric_a: number | null;\n\tmetric_b: number | null;\n\tcategory: string | null;\n};\n\nconst SYNC_OCCURRED_AT_SQL = \"CASE WHEN finished_at IS NULL THEN started_at ELSE finished_at END\";\n\nfunction syncSelect(options: EventOptions): string | null {\n\tif (!options.subsystems.has(\"sync\")) return null;\n\tconst predicates: string[] = [];\n\tif (!options.severities.has(\"info\")) predicates.push(\"ok = 0\");\n\tif (!options.severities.has(\"error\")) predicates.push(\"ok <> 0\");\n\tif (!options.severities.has(\"info\") && !options.severities.has(\"error\")) return null;\n\tif (options.cursor) {\n\t\tpredicates.push(`(${SYNC_OCCURRED_AT_SQL} < @cursorOccurredAt OR\n\t\t\t(${SYNC_OCCURRED_AT_SQL} = @cursorOccurredAt AND\n\t\t\t's:' || printf('%020d', id) < @cursorOrderKey))`);\n\t}\n\tconst where = predicates.length ? `WHERE ${predicates.join(\" AND \")}` : \"\";\n\treturn `SELECT 'sync' AS source_type, id AS source_id,\n\t\t's:' || printf('%020d', id) AS order_key,\n\t\t${SYNC_OCCURRED_AT_SQL} AS occurred_at,\n\t\tCASE WHEN ok <> 0 THEN 'succeeded' ELSE 'failed' END AS status,\n\t\tops_in AS metric_a, ops_out AS metric_b,\n\t\tCASE\n\t\t\tWHEN lower(error) LIKE '%auth%' OR lower(error) LIKE '%unauthorized%' THEN 'authentication'\n\t\t\tWHEN lower(error) LIKE '%timeout%' OR lower(error) LIKE '%timed out%' THEN 'timeout'\n\t\t\tWHEN lower(error) LIKE '%version%' OR lower(error) LIKE '%capability%' THEN 'compatibility'\n\t\t\tWHEN lower(error) LIKE '%connect%' OR lower(error) LIKE '%network%'\n\t\t\t\tOR lower(error) LIKE '%dns%' THEN 'connectivity'\n\t\t\tELSE 'unspecified'\n\t\tEND AS category\n\t\tFROM sync_attempts ${where}\n\t\tORDER BY ${SYNC_OCCURRED_AT_SQL} DESC, id DESC\n\t\tLIMIT @sourceLimit`;\n}\n\nfunction observerSelect(options: EventOptions): string | null {\n\tif (!options.severities.has(\"error\")) return null;\n\tconst observer = options.subsystems.has(\"observer\");\n\tconst capture = options.subsystems.has(\"capture\");\n\tif (!observer && !capture) return null;\n\tlet providerFilter = \"\";\n\tif (observer && !capture) providerFilter = \"AND observer_provider IS NOT NULL\";\n\tif (capture && !observer) providerFilter = \"AND observer_provider IS NULL\";\n\tconst cursorFilter = options.cursor\n\t\t? `AND (updated_at < @cursorOccurredAt OR\n\t\t\t(updated_at = @cursorOccurredAt AND\n\t\t\t'o:' || printf('%020d', id) < @cursorOrderKey))`\n\t\t: \"\";\n\treturn [\"error\", \"failed\", \"gave_up\"]\n\t\t.map(\n\t\t\t(status) => `SELECT * FROM (\n\t\t\t\tSELECT\n\t\t\t\t\tCASE WHEN observer_provider IS NULL THEN 'capture_failure' ELSE 'observer' END AS source_type,\n\t\t\t\t\tid AS source_id, 'o:' || printf('%020d', id) AS order_key,\n\t\t\t\t\tupdated_at AS occurred_at, status, attempt_count AS metric_a,\n\t\t\t\t\tNULL AS metric_b,\n\t\t\t\t\tCASE\n\t\t\t\t\t\tWHEN lower(COALESCE(observer_error_code, error_type)) LIKE '%auth%' THEN 'authentication'\n\t\t\t\t\t\tWHEN lower(COALESCE(observer_error_code, error_type)) LIKE '%rate%'\n\t\t\t\t\t\t\tOR lower(COALESCE(observer_error_code, error_type)) LIKE '%limit%' THEN 'rate limit'\n\t\t\t\t\t\tWHEN lower(COALESCE(observer_error_code, error_type)) LIKE '%timeout%' THEN 'timeout'\n\t\t\t\t\t\tWHEN lower(COALESCE(observer_error_code, error_type)) LIKE '%schema%'\n\t\t\t\t\t\t\tOR lower(COALESCE(observer_error_code, error_type)) LIKE '%parse%' THEN 'response format'\n\t\t\t\t\t\tELSE 'unspecified'\n\t\t\t\t\tEND AS category\n\t\t\t\tFROM raw_event_flush_batches\n\t\t\t\tWHERE status = '${status}' ${providerFilter} ${cursorFilter}\n\t\t\t\tORDER BY updated_at DESC, id DESC\n\t\t\t\tLIMIT @sourceLimit\n\t\t\t)`,\n\t\t)\n\t\t.join(\" UNION ALL \");\n}\n\nfunction maintenanceSelect(options: EventOptions): string | null {\n\tif (!options.subsystems.has(\"maintenance\")) return null;\n\tconst statuses: string[] = [];\n\tif (options.severities.has(\"info\")) statuses.push(\"'pending'\", \"'running'\");\n\tif (options.severities.has(\"warning\")) statuses.push(\"'cancelled'\");\n\tif (options.severities.has(\"error\")) statuses.push(\"'failed'\");\n\tif (!statuses.length) return null;\n\treturn `SELECT 'maintenance' AS source_type, kind AS source_id,\n\t\t'm:' || hex(kind) AS order_key, updated_at AS occurred_at,\n\t\tstatus, progress_current AS metric_a, progress_total AS metric_b,\n\t\tNULL AS category\n\t\tFROM maintenance_jobs WHERE status IN (${statuses.join(\", \")})`;\n}\n\nfunction backlogSelect(options: EventOptions): string | null {\n\tif (!options.subsystems.has(\"capture\")) return null;\n\tconst warning = options.severities.has(\"warning\");\n\tconst error = options.severities.has(\"error\");\n\tif (!warning && !error) return null;\n\tlet having = \"pending >= 200\";\n\tif (!warning) having = \"pending >= 1000\";\n\tif (!error) having = \"pending >= 200 AND pending < 1000\";\n\treturn `WITH candidate_sessions AS MATERIALIZED (\n\t\t\tSELECT source, stream_id, last_flushed_event_seq, updated_at\n\t\t\tFROM raw_event_sessions\n\t\t\tWHERE last_received_event_seq > last_flushed_event_seq\n\t\t\tORDER BY updated_at DESC\n\t\t\tLIMIT 1001\n\t\t), bounded_sessions AS MATERIALIZED (\n\t\t\tSELECT source, stream_id, last_flushed_event_seq, updated_at\n\t\t\tFROM candidate_sessions\n\t\t\tORDER BY updated_at DESC\n\t\t\tLIMIT 1000\n\t\t), retained_sessions AS MATERIALIZED (\n\t\t\tSELECT updated_at,\n\t\t\t\t(SELECT COUNT(*) FROM raw_events AS events\n\t\t\t\t\tWHERE events.source = sessions.source\n\t\t\t\t\t\tAND events.stream_id = sessions.stream_id\n\t\t\t\t\t\tAND events.event_seq > sessions.last_flushed_event_seq) AS pending\n\t\t\tFROM bounded_sessions AS sessions\n\t\t)\n\t\tSELECT 'backlog' AS source_type, 0 AS source_id,\n\t\t'b:' || printf('%020d', 0) AS order_key, occurred_at,\n\t\tCASE WHEN pending >= 1000 THEN 'error' ELSE 'warning' END AS status,\n\t\tpending AS metric_a, sessions AS metric_b,\n\t\tCASE WHEN candidate_count > 1000 THEN 'capped' ELSE NULL END AS category\n\t\tFROM (\n\t\t\tSELECT MAX(updated_at) AS occurred_at,\n\t\t\t\tSUM(pending) AS pending,\n\t\t\t\tCOUNT(*) FILTER (WHERE pending > 0) AS sessions,\n\t\t\t\t(SELECT COUNT(*) FROM candidate_sessions) AS candidate_count\n\t\t\tFROM retained_sessions\n\t\t\tWHERE pending > 0\n\t\t) WHERE ${having}`;\n}\n\nfunction sourceSelects(options: EventOptions): string[] {\n\treturn [\n\t\tsyncSelect(options),\n\t\tobserverSelect(options),\n\t\tmaintenanceSelect(options),\n\t\tbacklogSelect(options),\n\t].filter((select): select is string => select != null);\n}\n\nfunction boundedSourceSelect(select: string, hasCursor: boolean): string {\n\tconst cursorWhere = hasCursor\n\t\t? \"WHERE occurred_at < @cursorOccurredAt OR (occurred_at = @cursorOccurredAt AND order_key < @cursorOrderKey)\"\n\t\t: \"\";\n\treturn `SELECT * FROM (\n\t\tSELECT * FROM (${select})\n\t\t${cursorWhere}\n\t\tORDER BY occurred_at DESC, order_key DESC\n\t\tLIMIT @sourceLimit\n\t)`;\n}\n\nfunction loadSourceRows(store: MemoryStore, options: EventOptions): DiagnosticSourceRow[] {\n\tconst selects = sourceSelects(options);\n\tif (!selects.length) return [];\n\tconst boundedSelects = selects.map((select) =>\n\t\tboundedSourceSelect(select, options.cursor != null),\n\t);\n\tconst params: Record<string, unknown> = {\n\t\tresultLimit: options.limit + 1,\n\t\tsourceLimit: options.limit + 1,\n\t};\n\tif (options.cursor) {\n\t\tparams.cursorOccurredAt = options.cursor.occurredAt;\n\t\tparams.cursorOrderKey = options.cursor.orderKey;\n\t}\n\treturn store.db\n\t\t.prepare(\n\t\t\t`SELECT * FROM (${boundedSelects.join(\" UNION ALL \")})\n\t\t\t ORDER BY occurred_at DESC, order_key DESC\n\t\t\t LIMIT @resultLimit`,\n\t\t)\n\t\t.all(params) as DiagnosticSourceRow[];\n}\n\nfunction syncEvent(row: DiagnosticSourceRow, includeTechnical: boolean): OrderedDiagnosticEvent {\n\tconst succeeded = row.status === \"succeeded\";\n\tconst opsIn = Number(row.metric_a ?? 0);\n\tconst opsOut = Number(row.metric_b ?? 0);\n\tconst category = row.category ?? \"unspecified\";\n\treturn {\n\t\tid: opaqueId(\"sync-attempt\", row.source_id),\n\t\torderKey: row.order_key,\n\t\toccurred_at: row.occurred_at,\n\t\tseverity: succeeded ? \"info\" : \"error\",\n\t\tsubsystem: \"sync\",\n\t\tcode: succeeded ? \"sync_attempt_succeeded\" : \"sync_attempt_failed\",\n\t\tmessage: succeeded\n\t\t\t? \"A sync attempt completed.\"\n\t\t\t: \"A sync attempt failed before all work completed.\",\n\t\trecovery: succeeded\n\t\t\t? undefined\n\t\t\t: { label: \"Open advanced sync diagnostics\", href: \"#advanced/sync/diagnostics\" },\n\t\ttechnical_detail: technicalDetail(\n\t\t\ttrue,\n\t\t\tsucceeded\n\t\t\t\t? `${opsIn} inbound and ${opsOut} outbound operations.`\n\t\t\t\t: `Failure category: ${category}. ${opsIn} inbound and ${opsOut} outbound operations.`,\n\t\t\tincludeTechnical,\n\t\t),\n\t};\n}\n\nfunction failureEvent(row: DiagnosticSourceRow, includeTechnical: boolean): OrderedDiagnosticEvent {\n\tconst subsystem = row.source_type === \"observer\" ? \"observer\" : \"capture\";\n\tconst attempts = Math.max(0, Number(row.metric_a ?? 0));\n\tconst gaveUp = row.status === \"gave_up\";\n\treturn {\n\t\tid: opaqueId(\"processing-failure\", row.source_id),\n\t\torderKey: row.order_key,\n\t\toccurred_at: row.occurred_at,\n\t\tseverity: \"error\",\n\t\tsubsystem,\n\t\tcode: `${subsystem}_flush_${gaveUp ? \"gave_up\" : \"failed\"}`,\n\t\tmessage: gaveUp\n\t\t\t? \"Processing stopped after all retry attempts were exhausted.\"\n\t\t\t: \"Processing failed and queued events are waiting for retry.\",\n\t\trecovery: { label: \"Open Health\", href: \"#health\" },\n\t\ttechnical_detail: technicalDetail(\n\t\t\ttrue,\n\t\t\t`Failure category: ${row.category ?? \"unspecified\"}. Attempts: ${attempts}.`,\n\t\t\tincludeTechnical,\n\t\t),\n\t};\n}\n\nfunction maintenanceEvent(\n\trow: DiagnosticSourceRow,\n\tincludeTechnical: boolean,\n): OrderedDiagnosticEvent {\n\tlet severity: DiagnosticSeverity = \"info\";\n\tlet code = \"maintenance_job_active\";\n\tlet message = \"A background maintenance task is active.\";\n\tif (row.status === \"failed\") {\n\t\tseverity = \"error\";\n\t\tcode = \"maintenance_job_failed\";\n\t\tmessage = \"A background maintenance task failed.\";\n\t} else if (row.status === \"cancelled\") {\n\t\tseverity = \"warning\";\n\t\tcode = \"maintenance_job_cancelled\";\n\t\tmessage = \"A background maintenance task was cancelled.\";\n\t}\n\tconst total = row.metric_b == null ? \"unknown\" : String(row.metric_b);\n\treturn {\n\t\tid: opaqueId(\"maintenance\", row.source_id),\n\t\torderKey: row.order_key,\n\t\toccurred_at: row.occurred_at,\n\t\tseverity,\n\t\tsubsystem: \"maintenance\",\n\t\tcode,\n\t\tmessage,\n\t\trecovery: severity === \"error\" ? { label: \"Open Health\", href: \"#health\" } : undefined,\n\t\ttechnical_detail: technicalDetail(\n\t\t\ttrue,\n\t\t\t`Progress: ${Number(row.metric_a ?? 0)} of ${total}.`,\n\t\t\tincludeTechnical,\n\t\t),\n\t};\n}\n\nfunction backlogEvent(row: DiagnosticSourceRow, includeTechnical: boolean): OrderedDiagnosticEvent {\n\tconst severity = row.status === \"error\" ? \"error\" : \"warning\";\n\tconst pending = Number(row.metric_a ?? 0);\n\tconst sessions = Number(row.metric_b ?? 0);\n\tconst countPrefix = row.category === \"capped\" ? \"At least \" : \"\";\n\tconst sessionLabel = sessions === 1 ? \"session\" : \"sessions\";\n\treturn {\n\t\tid: opaqueId(\"capture-backlog\", 0),\n\t\torderKey: row.order_key,\n\t\toccurred_at: row.occurred_at,\n\t\tseverity,\n\t\tsubsystem: \"capture\",\n\t\tcode: severity === \"error\" ? \"capture_backlog_high\" : \"capture_backlog_growing\",\n\t\tmessage:\n\t\t\tseverity === \"error\"\n\t\t\t\t? \"The capture queue has a high pending backlog.\"\n\t\t\t\t: \"The capture queue is growing and may need attention.\",\n\t\trecovery: { label: \"Open Health\", href: \"#health\" },\n\t\ttechnical_detail: technicalDetail(\n\t\t\ttrue,\n\t\t\t`${countPrefix}${pending} pending events across ${sessions} ${sessionLabel}.`,\n\t\t\tincludeTechnical,\n\t\t),\n\t};\n}\n\nfunction collectEvents(store: MemoryStore, options: EventOptions): OrderedDiagnosticEvent[] {\n\treturn loadSourceRows(store, options).map((row) => {\n\t\tif (row.source_type === \"sync\") return syncEvent(row, options.includeTechnical);\n\t\tif (row.source_type === \"maintenance\") {\n\t\t\treturn maintenanceEvent(row, options.includeTechnical);\n\t\t}\n\t\tif (row.source_type === \"backlog\") return backlogEvent(row, options.includeTechnical);\n\t\treturn failureEvent(row, options.includeTechnical);\n\t});\n}\n\nexport function diagnosticsRoutes(getStore: StoreFactory) {\n\tconst app = new Hono();\n\n\tapp.get(\"/api/diagnostics/events\", (c) => {\n\t\tconst limit = parseLimit(c.req.query(\"limit\"));\n\t\tconst cursor = parseCursor(c.req.query(\"cursor\"));\n\t\tconst severities = parseFilter(c.req.query(\"severity\"), DIAGNOSTIC_SEVERITIES);\n\t\tconst subsystems = parseFilter(c.req.query(\"subsystem\"), DIAGNOSTIC_SUBSYSTEMS);\n\t\tconst includeTechnical = parseTechnical(c.req.query(\"includeTechnical\"));\n\t\tif (\n\t\t\tlimit === \"invalid\" ||\n\t\t\tcursor === \"invalid\" ||\n\t\t\tseverities === \"invalid\" ||\n\t\t\tsubsystems === \"invalid\" ||\n\t\t\tincludeTechnical === \"invalid\"\n\t\t) {\n\t\t\treturn c.json({ error: \"invalid_diagnostics_query\" }, 400);\n\t\t}\n\n\t\tconst generatedAt = new Date().toISOString();\n\t\tconst events = collectEvents(getStore(), {\n\t\t\tcursor,\n\t\t\tincludeTechnical,\n\t\t\tlimit,\n\t\t\tseverities,\n\t\t\tsubsystems,\n\t\t});\n\t\tconst orderedItems = events.slice(0, limit);\n\t\tconst items = orderedItems.map(({ orderKey: _orderKey, ...event }) => event);\n\t\tconst lastItem = orderedItems.at(-1);\n\t\tconst nextCursor = events.length > limit && lastItem ? encodeCursor(lastItem) : null;\n\t\tc.header(\"Cache-Control\", \"no-store\");\n\t\treturn c.json({\n\t\t\tcontract_version: 1,\n\t\t\titems,\n\t\t\tnext_cursor: nextCursor,\n\t\t\tredacted: true,\n\t\t\tgenerated_at: generatedAt,\n\t\t});\n\t});\n\n\treturn app;\n}\n","import { type MemoryStore, VERSION, VIEWER_SERVICE_DISCRIMINATOR } from \"@codemem/core\";\nimport { Hono } from \"hono\";\n\ntype StoreFactory = () => MemoryStore;\n\nfunction databaseReachable(getStore: StoreFactory): boolean {\n\ttry {\n\t\tgetStore().db.pragma(\"schema_version\", { simple: true });\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport function healthRoutes(getStore: StoreFactory) {\n\tconst app = new Hono();\n\n\tapp.get(\"/api/health\", (c) => {\n\t\tconst reachable = databaseReachable(getStore);\n\t\tc.header(\"Cache-Control\", \"no-store\");\n\t\treturn c.json({\n\t\t\t// Bound to the shared probe contract so producer and clients\n\t\t\t// cannot drift independently.\n\t\t\tservice: VIEWER_SERVICE_DISCRIMINATOR,\n\t\t\tversion: VERSION,\n\t\t\tpid: process.pid,\n\t\t\tuptime_ms: Math.max(0, Math.floor(process.uptime() * 1_000)),\n\t\t\t// Database reachability is the only readiness dependency in this endpoint.\n\t\t\tready: reachable,\n\t\t\tdatabase: { reachable },\n\t\t});\n\t});\n\n\treturn app;\n}\n","import { parseStrictInteger } from \"@codemem/core\";\n\n/**\n * Shared helpers for viewer-server routes.\n */\n\n/**\n * Parse a JSON string that should be an array of strings.\n * Returns an empty array on null, invalid JSON, or non-array values.\n * Mirrors Python's store._safe_json_list().\n */\nexport function safeJsonList(raw: string | null | undefined): string[] {\n\tif (raw == null) return [];\n\ttry {\n\t\tconst parsed: unknown = JSON.parse(raw);\n\t\tif (!Array.isArray(parsed)) return [];\n\t\treturn parsed.filter((item): item is string => typeof item === \"string\");\n\t} catch {\n\t\treturn [];\n\t}\n}\n\n/**\n * Parse a query parameter as an integer, returning the default on failure.\n */\nexport function queryInt(value: string | undefined, defaultValue: number): number {\n\tif (value == null) return defaultValue;\n\tconst parsed = parseStrictInteger(value);\n\treturn parsed == null ? defaultValue : parsed;\n}\n\n/**\n * Parse a query parameter as a boolean flag.\n * Recognizes \"1\", \"true\", \"yes\" as truthy.\n */\nexport function queryBool(value: string | undefined): boolean {\n\tif (value == null) return false;\n\treturn value === \"1\" || value === \"true\" || value === \"yes\";\n}\n\n/**\n * Parse and validate a JSON object body, enforcing size limits.\n * Returns the parsed payload or a Hono Response on error.\n */\nexport async function parseJsonObjectBody(\n\tc: {\n\t\treq: { header: (name: string) => string | undefined; raw: Request };\n\t\tjson: (data: unknown, status?: number) => Response;\n\t},\n\tmaxBytes: number,\n): Promise<Record<string, unknown> | Response> {\n\tconst contentLength = Number.parseInt(c.req.header(\"content-length\") ?? \"0\", 10);\n\tif (Number.isNaN(contentLength) || contentLength < 0) {\n\t\treturn c.json({ error: \"invalid content-length\" }, 400);\n\t}\n\tif (contentLength > maxBytes) {\n\t\treturn c.json({ error: \"payload too large\", max_bytes: maxBytes }, 413);\n\t}\n\tlet raw = \"\";\n\ttry {\n\t\tconst body = c.req.raw.body;\n\t\tif (body !== null) {\n\t\t\tconst reader = body.getReader();\n\t\t\tconst chunks: Uint8Array[] = [];\n\t\t\tlet totalBytes = 0;\n\t\t\ttry {\n\t\t\t\twhile (true) {\n\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\tif (done) break;\n\t\t\t\t\ttotalBytes += value.byteLength;\n\t\t\t\t\tif (totalBytes > maxBytes) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait reader.cancel();\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t// The size rejection is authoritative even if cancellation fails.\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn c.json({ error: \"payload too large\", max_bytes: maxBytes }, 413);\n\t\t\t\t\t}\n\t\t\t\t\tchunks.push(value);\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\treader.releaseLock();\n\t\t\t}\n\n\t\t\tconst bytes = new Uint8Array(totalBytes);\n\t\t\tlet offset = 0;\n\t\t\tfor (const chunk of chunks) {\n\t\t\t\tbytes.set(chunk, offset);\n\t\t\t\toffset += chunk.byteLength;\n\t\t\t}\n\t\t\traw = new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n\t\t}\n\t} catch {\n\t\treturn c.json({ error: \"invalid json\" }, 400);\n\t}\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = raw ? JSON.parse(raw) : {};\n\t} catch {\n\t\treturn c.json({ error: \"invalid json\" }, 400);\n\t}\n\tif (parsed == null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n\t\treturn c.json({ error: \"payload must be an object\" }, 400);\n\t}\n\treturn parsed as Record<string, unknown>;\n}\n","/**\n * Memory routes — observations, summaries, sessions, projects, pack, artifacts.\n */\n\nimport type { MemoryFilters, MemoryStore } from \"@codemem/core\";\nimport {\n\tbuildFilterClausesWithContext,\n\tcanonicalMemoryKind,\n\tfromJson,\n\tnormalizeHumanPresentationName,\n\tparsePositiveMemoryId,\n\tparseStrictInteger,\n\tschema,\n\tsummaryLikeSqlPredicate,\n} from \"@codemem/core\";\nimport { eq, inArray } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport { Hono } from \"hono\";\nimport { queryInt } from \"../helpers.js\";\n\ntype StoreFactory = () => MemoryStore;\n\ntype OwnershipPredicate = (item: Record<string, unknown>) => boolean;\n\nconst MAX_FEED_QUERY_CODE_UNITS = 256;\nconst searchFunctionsRegisteredStores = new WeakSet<MemoryStore>();\n\nfunction casefold(value: unknown): string {\n\treturn String(value ?? \"\").toLowerCase();\n}\n\nfunction normalizeMemorySearchQuery(value: string | undefined): string | undefined {\n\tconst normalized = casefold(value?.trim()).slice(0, MAX_FEED_QUERY_CODE_UNITS);\n\treturn normalized || undefined;\n}\n\nfunction ensureMemorySearchFunctions(store: MemoryStore): void {\n\tif (searchFunctionsRegisteredStores.has(store)) return;\n\tstore.db.function(\"codemem_casefold\", { deterministic: true }, casefold);\n\tstore.db.function(\"codemem_project_basename\", { deterministic: true }, (value: unknown) =>\n\t\tprojectBasename(String(value ?? \"\").trim()),\n\t);\n\tsearchFunctionsRegisteredStores.add(store);\n}\n\ninterface ActorPresentationRow {\n\tactor_id: string;\n\tdisplay_name: string;\n\tstatus: string;\n\tmerged_into_actor_id: string | null;\n}\n\ninterface DevicePresentationRow {\n\tdevice_id: string;\n\tdisplay_name: string;\n}\n\ninterface PeerPresentationRow {\n\tpeer_device_id: string;\n\tname: string | null;\n\tactor_id: string | null;\n}\n\nconst IDENTITY_LOOKUP_BATCH_SIZE = 500;\n\nfunction identityValue(item: Record<string, unknown>, key: string): string {\n\tconst direct = String(item[key] ?? \"\").trim();\n\tif (direct) return direct;\n\tconst rawMetadata = item.metadata ?? item.metadata_json;\n\tconst metadata = typeof rawMetadata === \"string\" ? fromJson(rawMetadata) : rawMetadata;\n\tif (!metadata || typeof metadata !== \"object\" || Array.isArray(metadata)) return \"\";\n\treturn String((metadata as Record<string, unknown>)[key] ?? \"\").trim();\n}\n\nfunction uniqueStrings(items: Record<string, unknown>[], key: string): string[] {\n\treturn [...new Set(items.map((item) => identityValue(item, key)).filter(Boolean))];\n}\n\nfunction batchedLookup<T>(\n\tstore: MemoryStore,\n\tvalues: string[],\n\tquery: (placeholders: string) => string,\n): T[] {\n\tconst rows: T[] = [];\n\tfor (let offset = 0; offset < values.length; offset += IDENTITY_LOOKUP_BATCH_SIZE) {\n\t\tconst batch = values.slice(offset, offset + IDENTITY_LOOKUP_BATCH_SIZE);\n\t\tconst placeholders = batch.map(() => \"?\").join(\", \");\n\t\trows.push(...(store.db.prepare(query(placeholders)).all(...batch) as T[]));\n\t}\n\treturn rows;\n}\n\nfunction humanName(value: unknown): string | undefined {\n\tif (typeof value !== \"string\") return undefined;\n\ttry {\n\t\treturn normalizeHumanPresentationName(value, \"display_name\");\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Add presentation-only identity labels without changing persisted provenance.\n * Resolved names are display hints, not authority or ownership evidence; legacy\n * metadata receives the same top-level-first fallback as existing read paths.\n */\nfunction attachResolvedIdentityFieldsUnsafe(\n\tstore: MemoryStore,\n\titems: Record<string, unknown>[],\n): void {\n\tconst actorIds = uniqueStrings(items, \"actor_id\");\n\tconst deviceIds = uniqueStrings(items, \"origin_device_id\");\n\tconst peers = batchedLookup<PeerPresentationRow>(\n\t\tstore,\n\t\tdeviceIds,\n\t\t(placeholders) =>\n\t\t\t`SELECT peer_device_id, name, actor_id FROM sync_peers\n\t\t WHERE peer_device_id IN (${placeholders})\n\t\t AND TRIM(COALESCE(pinned_fingerprint, '')) <> ''`,\n\t);\n\tconst peerByDevice = new Map(peers.map((peer) => [peer.peer_device_id, peer]));\n\tconst peerActorIds = peers\n\t\t.map((peer) => String(peer.actor_id ?? \"\").trim())\n\t\t.filter((actorId) => actorId.length > 0);\n\tconst actorRows = batchedLookup<ActorPresentationRow>(\n\t\tstore,\n\t\t[...new Set([...actorIds, ...peerActorIds])],\n\t\t(placeholders) =>\n\t\t\t`SELECT actor_id, display_name, status, merged_into_actor_id FROM actors\n\t\t\t WHERE actor_id IN (${placeholders})`,\n\t);\n\tconst devices = batchedLookup<DevicePresentationRow>(\n\t\tstore,\n\t\tdeviceIds,\n\t\t(placeholders) =>\n\t\t\t`SELECT device_id, display_name FROM identity_devices\n\t\t WHERE device_id IN (${placeholders}) AND status = 'active'`,\n\t);\n\tconst actorById = new Map(actorRows.map((actor) => [actor.actor_id, actor] as const));\n\tlet pendingMergeTargets = [\n\t\t...new Set(\n\t\t\tactorRows\n\t\t\t\t.map((actor) => String(actor.merged_into_actor_id ?? \"\").trim())\n\t\t\t\t.filter((actorId) => actorId && !actorById.has(actorId)),\n\t\t),\n\t];\n\twhile (pendingMergeTargets.length > 0) {\n\t\tconst targetRows = batchedLookup<ActorPresentationRow>(\n\t\t\tstore,\n\t\t\tpendingMergeTargets,\n\t\t\t(placeholders) =>\n\t\t\t\t`SELECT actor_id, display_name, status, merged_into_actor_id FROM actors\n\t\t\t\t WHERE actor_id IN (${placeholders})`,\n\t\t);\n\t\tfor (const actor of targetRows) actorById.set(actor.actor_id, actor);\n\t\tpendingMergeTargets = [\n\t\t\t...new Set(\n\t\t\t\ttargetRows\n\t\t\t\t\t.map((actor) => String(actor.merged_into_actor_id ?? \"\").trim())\n\t\t\t\t\t.filter((actorId) => actorId && !actorById.has(actorId)),\n\t\t\t),\n\t\t];\n\t}\n\tconst resolvedActorName = (actorId: string): string | undefined => {\n\t\tconst seen = new Set<string>();\n\t\tlet currentActorId = actorId;\n\t\twhile (currentActorId && !seen.has(currentActorId)) {\n\t\t\tseen.add(currentActorId);\n\t\t\tconst actor = actorById.get(currentActorId);\n\t\t\tif (!actor) return undefined;\n\t\t\tif (actor.status === \"active\" && actor.merged_into_actor_id === null) {\n\t\t\t\treturn humanName(actor.display_name);\n\t\t\t}\n\t\t\tcurrentActorId = String(actor.merged_into_actor_id ?? \"\").trim();\n\t\t}\n\t\treturn undefined;\n\t};\n\tconst deviceNameById = new Map(\n\t\tdevices\n\t\t\t.map((device) => [device.device_id, humanName(device.display_name)] as const)\n\t\t\t.filter((entry): entry is readonly [string, string] => entry[1] !== undefined),\n\t);\n\n\tfor (const item of items) {\n\t\tconst actorId = identityValue(item, \"actor_id\");\n\t\tconst deviceId = identityValue(item, \"origin_device_id\");\n\t\tconst peer = peerByDevice.get(deviceId);\n\t\tconst peerActorId = String(peer?.actor_id ?? \"\").trim();\n\t\tconst knownMemoryActor = actorById.has(actorId);\n\t\tconst actorName = knownMemoryActor\n\t\t\t? (resolvedActorName(actorId) ?? humanName(item.actor_display_name))\n\t\t\t: (resolvedActorName(peerActorId) ?? humanName(item.actor_display_name));\n\t\tconst deviceName = deviceNameById.get(deviceId) ?? humanName(peer?.name);\n\t\tif (actorName) item.resolved_actor_display_name = actorName;\n\t\tif (deviceName) item.resolved_device_display_name = deviceName;\n\t}\n}\n\nfunction attachResolvedIdentityFields(store: MemoryStore, items: Record<string, unknown>[]): void {\n\ttry {\n\t\tattachResolvedIdentityFieldsUnsafe(store, items);\n\t} catch {\n\t\t// Presentation enrichment is optional; neutral Feed fallbacks must remain\n\t\t// available for legacy or partially initialized databases.\n\t}\n}\n\nfunction serializeMemoryRow(\n\townedBySelf: OwnershipPredicate,\n\trow: Record<string, unknown>,\n): Record<string, unknown> {\n\tconst metadata = fromJson((row.metadata_json as string) ?? null);\n\t// Evaluate ownership against the raw row (top-level columns + metadata_json\n\t// fallback) before we overwrite metadata_json with the parsed object.\n\tconst owned_by_self = ownedBySelf(row);\n\treturn {\n\t\t...row,\n\t\tkind: canonicalMemoryKind((row.kind as string | null | undefined) ?? null, row.metadata_json),\n\t\tmetadata_json: metadata,\n\t\towned_by_self,\n\t};\n}\n\n/**\n * Attach session project/cwd fields to memory items.\n */\nfunction attachSessionFields(store: MemoryStore, items: Record<string, unknown>[]): void {\n\tconst sessionIds: number[] = [];\n\tconst seen = new Set<number>();\n\tfor (const item of items) {\n\t\tconst value = item.session_id;\n\t\tif (value == null) continue;\n\t\tconst sid = Number(value);\n\t\tif (Number.isNaN(sid) || seen.has(sid)) continue;\n\t\tseen.add(sid);\n\t\tsessionIds.push(sid);\n\t}\n\tif (sessionIds.length === 0) return;\n\n\tconst d = drizzle(store.db, { schema });\n\tconst rows = d\n\t\t.select({\n\t\t\tid: schema.sessions.id,\n\t\t\tproject: schema.sessions.project,\n\t\t\tcwd: schema.sessions.cwd,\n\t\t})\n\t\t.from(schema.sessions)\n\t\t.where(inArray(schema.sessions.id, sessionIds))\n\t\t.all();\n\n\tconst bySession = new Map<number, { project: string; cwd: string }>();\n\tfor (const row of rows) {\n\t\tconst projectRaw = String(row.project ?? \"\").trim();\n\t\tconst project = projectRaw ? projectBasename(projectRaw) : \"\";\n\t\tconst cwd = String(row.cwd ?? \"\");\n\t\tbySession.set(row.id, { project, cwd });\n\t}\n\n\tfor (const item of items) {\n\t\tconst sid = Number(item.session_id);\n\t\tif (Number.isNaN(sid)) continue;\n\t\tconst fields = bySession.get(sid);\n\t\tif (!fields) continue;\n\t\titem.project ??= fields.project;\n\t\titem.cwd ??= fields.cwd;\n\t}\n}\n\n/**\n * Extract the basename of a project path.\n * Strips \"fatal:\" prefixed values.\n */\nfunction projectBasename(raw: string): string {\n\tif (raw.toLowerCase().startsWith(\"fatal:\")) return \"\";\n\tconst parts = raw.replace(/\\\\/g, \"/\").split(\"/\");\n\treturn parts[parts.length - 1] ?? raw;\n}\n\nfunction normalizeScope(raw: string | undefined): \"mine\" | \"theirs\" | undefined {\n\tconst value = String(raw ?? \"\")\n\t\t.trim()\n\t\t.toLowerCase();\n\tif (value === \"mine\" || value === \"theirs\") return value;\n\treturn undefined;\n}\n\nfunction buildViewerMemoryFilters(store: MemoryStore, filters?: MemoryFilters | null) {\n\treturn buildFilterClausesWithContext(filters, store.ownershipFilterContext());\n}\n\nfunction countVisibleMemoryRows(store: MemoryStore, filters?: MemoryFilters | null): number {\n\tconst filterResult = buildViewerMemoryFilters(store, filters);\n\tconst clauses = [\"memory_items.active = 1\", ...filterResult.clauses];\n\tconst from = filterResult.joinSessions\n\t\t? \"memory_items JOIN sessions ON sessions.id = memory_items.session_id\"\n\t\t: \"memory_items\";\n\tconst row = store.db\n\t\t.prepare(`SELECT COUNT(*) AS total FROM ${from} WHERE ${clauses.join(\" AND \")}`)\n\t\t.get(...filterResult.params) as Record<string, unknown> | undefined;\n\treturn Number(row?.total ?? 0);\n}\n\nfunction memorySearchSql(query: string): { clause: string; params: unknown[] } {\n\tconst textClause = `INSTR(codemem_casefold(\n\t\tCOALESCE(memory_items.title, '') || CHAR(10) ||\n\t\tCOALESCE(memory_items.body_text, '') || CHAR(10) ||\n\t\tCASE WHEN ${summaryLikeSqlPredicate()} THEN 'session_summary' ELSE\n\t\t\tCOALESCE(NULLIF(LOWER(TRIM(COALESCE(memory_items.kind, ''))), ''), 'change')\n\t\tEND || CHAR(10) ||\n\t\tCOALESCE(\n\t\t\tmemory_items.project,\n\t\t\tcodemem_project_basename(\n\t\t\t\t(SELECT sessions.project FROM sessions WHERE sessions.id = memory_items.session_id)\n\t\t\t),\n\t\t\t''\n\t\t) || CHAR(10) ||\n\t\tCOALESCE(memory_items.tags_text, '') || CHAR(10) ||\n\t\tCOALESCE(memory_items.facts, '') || CHAR(10) ||\n\t\tCOALESCE(memory_items.subtitle, '') || CHAR(10) ||\n\t\tCOALESCE(memory_items.narrative, '') || CHAR(10) ||\n\t\tCASE WHEN json_valid(COALESCE(memory_items.metadata_json, '')) THEN\n\t\t\tCOALESCE(json_extract(memory_items.metadata_json, '$.request'), '') || CHAR(10) ||\n\t\t\tCOALESCE(json_extract(memory_items.metadata_json, '$.subtitle'), '') || CHAR(10) ||\n\t\t\tCOALESCE(json_extract(memory_items.metadata_json, '$.narrative'), '') || CHAR(10) ||\n\t\t\tCOALESCE(json_extract(memory_items.metadata_json, '$.facts'), '') || CHAR(10) ||\n\t\t\tCOALESCE(json_extract(memory_items.metadata_json, '$.summary'), '')\n\t\tELSE '' END\n\t), codemem_casefold(?)) > 0`;\n\tconst parsedMemoryId = parsePositiveMemoryId(query);\n\tconst memoryId =\n\t\tparsedMemoryId != null && String(parsedMemoryId) === query ? parsedMemoryId : null;\n\tif (memoryId != null) {\n\t\treturn { clause: `(memory_items.id = ? OR ${textClause})`, params: [memoryId, query] };\n\t}\n\treturn { clause: textClause, params: [query] };\n}\n\nfunction countVisibleObservationRows(store: MemoryStore, filters?: MemoryFilters | null): number {\n\tconst filterResult = buildViewerMemoryFilters(store, filters);\n\tconst clauses = [\n\t\t\"memory_items.active = 1\",\n\t\t`NOT ${summaryLikeSqlPredicate()}`,\n\t\t...filterResult.clauses,\n\t];\n\tconst from = filterResult.joinSessions\n\t\t? \"memory_items JOIN sessions ON sessions.id = memory_items.session_id\"\n\t\t: \"memory_items\";\n\tconst row = store.db\n\t\t.prepare(`SELECT COUNT(*) AS total FROM ${from} WHERE ${clauses.join(\" AND \")}`)\n\t\t.get(...filterResult.params) as Record<string, unknown> | undefined;\n\treturn Number(row?.total ?? 0);\n}\n\nfunction sessionAllowsArtifactAccess(store: MemoryStore, sessionId: number): boolean {\n\tconst visibleCount = countVisibleMemoryRows(store, { session_id: sessionId });\n\tif (visibleCount === 0) return false;\n\tconst row = store.db\n\t\t.prepare(\n\t\t\t`SELECT COUNT(*) AS total FROM memory_items\n\t\t\t WHERE session_id = ? AND active = 1`,\n\t\t)\n\t\t.get(sessionId) as Record<string, unknown> | undefined;\n\treturn visibleCount === Number(row?.total ?? 0);\n}\n\nfunction countVisiblePromptRows(store: MemoryStore, project?: string | null): number {\n\tconst filterResult = buildViewerMemoryFilters(store, null);\n\tconst clauses = [\n\t\t\"user_prompts.session_id IS NOT NULL\",\n\t\t`EXISTS (\n\t\t\tSELECT 1 FROM memory_items\n\t\t\tWHERE memory_items.session_id = user_prompts.session_id\n\t\t\t AND memory_items.active = 1\n\t\t\t AND ${filterResult.clauses.join(\" AND \")}\n\t\t)`,\n\t];\n\tconst params: unknown[] = [...filterResult.params];\n\tif (project) {\n\t\tclauses.unshift(\"user_prompts.project = ?\");\n\t\tparams.unshift(project);\n\t}\n\tconst row = store.db\n\t\t.prepare(`SELECT COUNT(*) AS total FROM user_prompts WHERE ${clauses.join(\" AND \")}`)\n\t\t.get(...params) as Record<string, unknown> | undefined;\n\treturn Number(row?.total ?? 0);\n}\n\nfunction countVisibleArtifactRows(store: MemoryStore, project?: string | null): number {\n\tconst filterResult = buildViewerMemoryFilters(store, null);\n\tconst clauses = [\n\t\t`EXISTS (\n\t\t\tSELECT 1 FROM memory_items\n\t\t\tWHERE memory_items.session_id = artifacts.session_id\n\t\t\t AND memory_items.active = 1\n\t\t\t AND ${filterResult.clauses.join(\" AND \")}\n\t\t)`,\n\t];\n\tconst params: unknown[] = [...filterResult.params];\n\tconst from = project\n\t\t? \"artifacts JOIN sessions ON sessions.id = artifacts.session_id\"\n\t\t: \"artifacts\";\n\tif (project) {\n\t\tclauses.unshift(\"sessions.project = ?\");\n\t\tparams.unshift(project);\n\t}\n\tconst row = store.db\n\t\t.prepare(`SELECT COUNT(*) AS total FROM ${from} WHERE ${clauses.join(\" AND \")}`)\n\t\t.get(...params) as Record<string, unknown> | undefined;\n\treturn Number(row?.total ?? 0);\n}\n\nfunction queryMemoryPage(\n\tstore: MemoryStore,\n\toptions: {\n\t\tlimit: number;\n\t\toffset: number;\n\t\tproject?: string;\n\t\tscope?: \"mine\" | \"theirs\";\n\t\tq?: string;\n\t\tclassification: \"observation\" | \"summary\";\n\t},\n): Record<string, unknown>[] {\n\tensureMemorySearchFunctions(store);\n\tconst filters: MemoryFilters = {};\n\tif (options.project) filters.project = options.project;\n\tif (options.scope) filters.ownership_scope = options.scope;\n\n\tconst filterResult = buildViewerMemoryFilters(store, filters);\n\tconst summaryPredicate = summaryLikeSqlPredicate();\n\tconst clauses = [\n\t\t\"memory_items.active = 1\",\n\t\toptions.classification === \"summary\" ? summaryPredicate : `NOT ${summaryPredicate}`,\n\t\t...filterResult.clauses,\n\t];\n\tconst params: unknown[] = [...filterResult.params];\n\tif (options.q) {\n\t\tconst search = memorySearchSql(options.q);\n\t\tclauses.push(search.clause);\n\t\tparams.push(...search.params);\n\t}\n\tconst where = clauses.join(\" AND \");\n\tconst from = filterResult.joinSessions\n\t\t? \"memory_items JOIN sessions ON sessions.id = memory_items.session_id\"\n\t\t: \"memory_items\";\n\n\tconst rows = store.db\n\t\t.prepare(\n\t\t\t`SELECT memory_items.* FROM ${from}\n\t\t\t WHERE ${where}\n\t\t\t ORDER BY memory_items.created_at DESC, memory_items.id DESC\n\t\t\t LIMIT ? OFFSET ?`,\n\t\t)\n\t\t.all(...params, options.limit + 1, options.offset) as Record<string, unknown>[];\n\n\tconst ownedBySelf = store.buildOwnershipPredicate();\n\treturn rows.map((row) => serializeMemoryRow(ownedBySelf, row));\n}\n\nexport function memoryRoutes(getStore: StoreFactory) {\n\tconst app = new Hono();\n\n\t// GET /api/sessions\n\tapp.get(\"/api/sessions\", (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tconst limit = queryInt(c.req.query(\"limit\"), 20);\n\t\t\tconst filterResult = buildViewerMemoryFilters(store, null);\n\t\t\tconst clauses = [\n\t\t\t\t\"memory_items.session_id = sessions.id\",\n\t\t\t\t\"memory_items.active = 1\",\n\t\t\t\t...filterResult.clauses,\n\t\t\t];\n\t\t\tconst rows = store.db\n\t\t\t\t.prepare(\n\t\t\t\t\t`SELECT sessions.* FROM sessions\n\t\t\t\t\t WHERE EXISTS (SELECT 1 FROM memory_items WHERE ${clauses.join(\" AND \")})\n\t\t\t\t\t ORDER BY sessions.started_at DESC\n\t\t\t\t\t LIMIT ?`,\n\t\t\t\t)\n\t\t\t\t.all(...filterResult.params, limit) as Record<string, unknown>[];\n\t\t\tconst items = rows.map((row) => ({\n\t\t\t\t...row,\n\t\t\t\tmetadata_json: fromJson((row.metadata_json as string | null | undefined) ?? null),\n\t\t\t}));\n\t\t\treturn c.json({ items });\n\t\t}\n\t});\n\n\t// GET /api/projects\n\tapp.get(\"/api/projects\", (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tconst filterResult = buildViewerMemoryFilters(store, null);\n\t\t\tconst clauses = [\n\t\t\t\t\"memory_items.session_id = sessions.id\",\n\t\t\t\t\"memory_items.active = 1\",\n\t\t\t\t\"sessions.project IS NOT NULL\",\n\t\t\t\t...filterResult.clauses,\n\t\t\t];\n\t\t\tconst rows = store.db\n\t\t\t\t.prepare(\n\t\t\t\t\t`SELECT DISTINCT sessions.project AS project FROM sessions\n\t\t\t\t\t JOIN memory_items ON memory_items.session_id = sessions.id\n\t\t\t\t\t WHERE ${clauses.join(\" AND \")}`,\n\t\t\t\t)\n\t\t\t\t.all(...filterResult.params) as Record<string, unknown>[];\n\t\t\tconst projects = [\n\t\t\t\t...new Set(\n\t\t\t\t\trows\n\t\t\t\t\t\t.map((r) => String(r.project ?? \"\").trim())\n\t\t\t\t\t\t.filter((p) => p && !p.toLowerCase().startsWith(\"fatal:\"))\n\t\t\t\t\t\t.map((p) => projectBasename(p))\n\t\t\t\t\t\t.filter(Boolean),\n\t\t\t\t),\n\t\t\t].sort();\n\t\t\treturn c.json({ projects });\n\t\t}\n\t});\n\n\t// GET /api/observations (aliased from /api/memories)\n\tapp.get(\"/api/memories\", (c) => {\n\t\tconst search = new URL(c.req.url).search;\n\t\treturn c.redirect(`/api/observations${search}`, 301);\n\t});\n\n\tapp.get(\"/api/observations\", (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tconst limit = Math.max(1, queryInt(c.req.query(\"limit\"), 20));\n\t\t\tconst offset = Math.max(0, queryInt(c.req.query(\"offset\"), 0));\n\t\t\tconst project = c.req.query(\"project\") || undefined;\n\t\t\tconst scope = normalizeScope(c.req.query(\"scope\"));\n\t\t\tconst q = normalizeMemorySearchQuery(c.req.query(\"q\"));\n\t\t\tconst items = queryMemoryPage(store, {\n\t\t\t\tlimit,\n\t\t\t\toffset,\n\t\t\t\tproject,\n\t\t\t\tscope,\n\t\t\t\tq,\n\t\t\t\tclassification: \"observation\",\n\t\t\t});\n\t\t\tconst hasMore = items.length > limit;\n\t\t\tconst result = hasMore ? items.slice(0, limit) : items;\n\t\t\tconst asRecords = result as unknown as Record<string, unknown>[];\n\t\t\tattachSessionFields(store, asRecords);\n\t\t\tattachResolvedIdentityFields(store, asRecords);\n\t\t\treturn c.json({\n\t\t\t\titems: asRecords,\n\t\t\t\tpagination: {\n\t\t\t\t\tlimit,\n\t\t\t\t\toffset,\n\t\t\t\t\tnext_offset: hasMore ? offset + result.length : null,\n\t\t\t\t\thas_more: hasMore,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t});\n\n\t// GET /api/summaries\n\tapp.get(\"/api/summaries\", (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tconst limit = Math.max(1, queryInt(c.req.query(\"limit\"), 50));\n\t\t\tconst offset = Math.max(0, queryInt(c.req.query(\"offset\"), 0));\n\t\t\tconst project = c.req.query(\"project\") || undefined;\n\t\t\tconst scope = normalizeScope(c.req.query(\"scope\"));\n\t\t\tconst q = normalizeMemorySearchQuery(c.req.query(\"q\"));\n\t\t\tconst items = queryMemoryPage(store, {\n\t\t\t\tlimit,\n\t\t\t\toffset,\n\t\t\t\tproject,\n\t\t\t\tscope,\n\t\t\t\tq,\n\t\t\t\tclassification: \"summary\",\n\t\t\t});\n\t\t\tconst hasMore = items.length > limit;\n\t\t\tconst result = hasMore ? items.slice(0, limit) : items;\n\t\t\tconst asRecords = result as unknown as Record<string, unknown>[];\n\t\t\tattachSessionFields(store, asRecords);\n\t\t\tattachResolvedIdentityFields(store, asRecords);\n\t\t\treturn c.json({\n\t\t\t\titems: asRecords,\n\t\t\t\tpagination: {\n\t\t\t\t\tlimit,\n\t\t\t\t\toffset,\n\t\t\t\t\tnext_offset: hasMore ? offset + result.length : null,\n\t\t\t\t\thas_more: hasMore,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\t});\n\n\t// GET /api/session (aggregate counts)\n\tapp.get(\"/api/session\", (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tconst project = c.req.query(\"project\") || null;\n\t\t\tlet prompts: number;\n\t\t\tlet artifacts: number;\n\t\t\tlet memories: number;\n\t\t\tlet observations: number;\n\t\t\tif (project) {\n\t\t\t\tprompts = countVisiblePromptRows(store, project);\n\t\t\t\tartifacts = countVisibleArtifactRows(store, project);\n\t\t\t\tmemories = countVisibleMemoryRows(store, { project });\n\t\t\t\tobservations = countVisibleObservationRows(store, { project });\n\t\t\t} else {\n\t\t\t\tprompts = countVisiblePromptRows(store);\n\t\t\t\tartifacts = countVisibleArtifactRows(store);\n\t\t\t\tmemories = countVisibleMemoryRows(store);\n\t\t\t\tobservations = countVisibleObservationRows(store);\n\t\t\t}\n\t\t\tconst total = prompts + artifacts + memories;\n\t\t\treturn c.json({ total, memories, artifacts, prompts, observations });\n\t\t}\n\t});\n\n\t// GET /api/pack\n\tapp.get(\"/api/pack\", async (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tconst context = c.req.query(\"context\") || \"\";\n\t\t\tif (!context) {\n\t\t\t\treturn c.json({ error: \"context required\" }, 400);\n\t\t\t}\n\t\t\tconst limit = queryInt(c.req.query(\"limit\"), 10);\n\t\t\tconst tokenBudgetStr = c.req.query(\"token_budget\");\n\t\t\tlet tokenBudget: number | undefined;\n\t\t\tif (tokenBudgetStr) {\n\t\t\t\ttokenBudget = parseStrictInteger(tokenBudgetStr) ?? undefined;\n\t\t\t\tif (tokenBudget === undefined) {\n\t\t\t\t\treturn c.json({ error: \"token_budget must be int\" }, 400);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst project = c.req.query(\"project\") || undefined;\n\t\t\tconst filters: { project?: string } = {};\n\t\t\tif (project) filters.project = project;\n\t\t\tconst pack = await store.buildMemoryPackAsync(context, limit, tokenBudget ?? null, filters);\n\t\t\treturn c.json(pack);\n\t\t}\n\t});\n\n\tapp.post(\"/api/pack/trace\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst parsed = await c.req.json().catch(() => Symbol.for(\"invalid-json\"));\n\t\tif (parsed === Symbol.for(\"invalid-json\")) {\n\t\t\treturn c.json({ error: \"invalid json body\" }, 400);\n\t\t}\n\t\tconst body = parsed as {\n\t\t\tcontext?: unknown;\n\t\t\tlimit?: unknown;\n\t\t\ttoken_budget?: unknown;\n\t\t\tproject?: unknown;\n\t\t\tworking_set_files?: unknown;\n\t\t} | null;\n\t\tconst context = typeof body?.context === \"string\" ? body.context.trim() : \"\";\n\t\tif (!context) {\n\t\t\treturn c.json({ error: \"context required\" }, 400);\n\t\t}\n\t\tconst limit =\n\t\t\tbody?.limit == null\n\t\t\t\t? 10\n\t\t\t\t: typeof body.limit === \"number\" && Number.isInteger(body.limit) && body.limit >= 1\n\t\t\t\t\t? body.limit\n\t\t\t\t\t: null;\n\t\tif (limit == null) {\n\t\t\treturn c.json({ error: \"limit must be a positive int\" }, 400);\n\t\t}\n\t\tlet tokenBudget: number | null = null;\n\t\tif (body?.token_budget != null) {\n\t\t\tif (\n\t\t\t\ttypeof body.token_budget !== \"number\" ||\n\t\t\t\t!Number.isInteger(body.token_budget) ||\n\t\t\t\tbody.token_budget < 0\n\t\t\t) {\n\t\t\t\treturn c.json({ error: \"token_budget must be int\" }, 400);\n\t\t\t}\n\t\t\ttokenBudget = body.token_budget;\n\t\t}\n\t\tconst project = typeof body?.project === \"string\" && body.project.trim() ? body.project : null;\n\t\tif (body?.working_set_files != null && !Array.isArray(body.working_set_files)) {\n\t\t\treturn c.json({ error: \"working_set_files must be an array of strings\" }, 400);\n\t\t}\n\t\tif (\n\t\t\tArray.isArray(body?.working_set_files) &&\n\t\t\tbody.working_set_files.some((value) => typeof value !== \"string\")\n\t\t) {\n\t\t\treturn c.json({ error: \"working_set_files must be an array of strings\" }, 400);\n\t\t}\n\t\tconst workingSetFiles = Array.isArray(body?.working_set_files) ? body.working_set_files : [];\n\t\tconst filters: { project?: string; working_set_paths?: string[] } = {};\n\t\tif (project) filters.project = project;\n\t\tif (workingSetFiles.length > 0) filters.working_set_paths = workingSetFiles;\n\t\tconst trace = await store.buildMemoryPackTraceAsync(context, limit, tokenBudget, filters);\n\t\treturn c.json(trace);\n\t});\n\n\t// GET /api/memory\n\tapp.get(\"/api/memory\", (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tconst limit = queryInt(c.req.query(\"limit\"), 20);\n\t\t\tconst kind = c.req.query(\"kind\") || undefined;\n\t\t\tconst project = c.req.query(\"project\") || undefined;\n\t\t\tconst filters: MemoryFilters = {};\n\t\t\tif (kind) filters.kind = kind;\n\t\t\tif (project) filters.project = project;\n\t\t\tconst items = store.recent(limit, filters);\n\t\t\tconst asRecords = items as unknown as Record<string, unknown>[];\n\t\t\tattachSessionFields(store, asRecords);\n\t\t\tattachResolvedIdentityFields(store, asRecords);\n\t\t\treturn c.json({ items: asRecords });\n\t\t}\n\t});\n\n\t// GET /api/artifacts\n\tapp.get(\"/api/artifacts\", (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tconst sessionIdStr = c.req.query(\"session_id\");\n\t\t\tif (!sessionIdStr) {\n\t\t\t\treturn c.json({ error: \"session_id required\" }, 400);\n\t\t\t}\n\t\t\tconst sessionId = parseStrictInteger(sessionIdStr);\n\t\t\tif (sessionId == null) {\n\t\t\t\treturn c.json({ error: \"session_id must be int\" }, 400);\n\t\t\t}\n\t\t\tif (!sessionAllowsArtifactAccess(store, sessionId)) {\n\t\t\t\treturn c.json({ error: \"session not found\" }, 404);\n\t\t\t}\n\t\t\tconst d = drizzle(store.db, { schema });\n\t\t\tconst rows = d\n\t\t\t\t.select()\n\t\t\t\t.from(schema.artifacts)\n\t\t\t\t.where(eq(schema.artifacts.session_id, sessionId))\n\t\t\t\t.all();\n\t\t\treturn c.json({ items: rows });\n\t\t}\n\t});\n\n\t// POST /api/memories/visibility\n\tapp.post(\"/api/memories/visibility\", async (c) => {\n\t\tconst store = getStore();\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid JSON\" }, 400);\n\t\t}\n\t\tconst memoryId = parseStrictInteger(\n\t\t\ttypeof body.memory_id === \"string\" ? body.memory_id : String(body.memory_id ?? \"\"),\n\t\t);\n\t\tif (memoryId == null || memoryId <= 0) {\n\t\t\treturn c.json({ error: \"memory_id must be int\" }, 400);\n\t\t}\n\t\tif (!store.get(memoryId)) {\n\t\t\treturn c.json({ error: \"memory not found\" }, 404);\n\t\t}\n\t\tconst visibility = String(body.visibility ?? \"\").trim();\n\t\tif (visibility !== \"private\" && visibility !== \"shared\") {\n\t\t\treturn c.json({ error: \"visibility must be private or shared\" }, 400);\n\t\t}\n\t\ttry {\n\t\t\tconst item = store.updateMemoryVisibility(memoryId, visibility);\n\t\t\treturn c.json({ item });\n\t\t} catch (err) {\n\t\t\tconst msg = err instanceof Error ? err.message : String(err);\n\t\t\tif (msg.includes(\"not found\")) return c.json({ error: msg }, 404);\n\t\t\tif (msg.includes(\"not owned\")) return c.json({ error: msg }, 403);\n\t\t\treturn c.json({ error: msg }, 400);\n\t\t}\n\t});\n\n\t// POST /api/memories/project\n\tapp.post(\"/api/memories/project\", async (c) => {\n\t\tconst store = getStore();\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid JSON\" }, 400);\n\t\t}\n\t\tconst memoryId = parseStrictInteger(\n\t\t\ttypeof body.memory_id === \"string\" ? body.memory_id : String(body.memory_id ?? \"\"),\n\t\t);\n\t\tif (memoryId == null || memoryId <= 0) {\n\t\t\treturn c.json({ error: \"memory_id must be int\" }, 400);\n\t\t}\n\t\tconst project = String(body.project ?? \"\").trim();\n\t\tif (!project) {\n\t\t\treturn c.json({ error: \"project must be a non-empty string\" }, 400);\n\t\t}\n\t\tif (!store.get(memoryId)) {\n\t\t\treturn c.json({ error: \"memory not found\" }, 404);\n\t\t}\n\t\ttry {\n\t\t\tconst result = store.moveMemoryProject(memoryId, project);\n\t\t\treturn c.json(result);\n\t\t} catch (err) {\n\t\t\tconst msg = err instanceof Error ? err.message : String(err);\n\t\t\tif (msg.includes(\"not found\")) return c.json({ error: msg }, 404);\n\t\t\tif (msg.includes(\"not owned\")) return c.json({ error: msg }, 403);\n\t\t\treturn c.json({ error: msg }, 400);\n\t\t}\n\t});\n\n\t// POST /api/memories/forget\n\tapp.post(\"/api/memories/forget\", async (c) => {\n\t\tconst store = getStore();\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid JSON\" }, 400);\n\t\t}\n\t\tconst memoryId = parseStrictInteger(\n\t\t\ttypeof body.memory_id === \"string\" ? body.memory_id : String(body.memory_id ?? \"\"),\n\t\t);\n\t\tif (memoryId == null || memoryId <= 0) {\n\t\t\treturn c.json({ error: \"memory_id must be int\" }, 400);\n\t\t}\n\t\tif (!store.get(memoryId)) {\n\t\t\treturn c.json({ error: \"memory not found\" }, 404);\n\t\t}\n\n\t\tconst row = drizzle(store.db, { schema })\n\t\t\t.select()\n\t\t\t.from(schema.memoryItems)\n\t\t\t.where(eq(schema.memoryItems.id, memoryId))\n\t\t\t.get();\n\t\tif (!row) {\n\t\t\treturn c.json({ error: \"memory not found\" }, 404);\n\t\t}\n\t\tif (!store.memoryOwnedBySelf(row as Record<string, unknown>)) {\n\t\t\treturn c.json({ error: \"memory not owned by this device\" }, 403);\n\t\t}\n\t\tif (Number(row.active ?? 1) === 0 || row.deleted_at != null) {\n\t\t\treturn c.json({ status: \"ok\" });\n\t\t}\n\n\t\ttry {\n\t\t\tstore.forget(memoryId);\n\t\t\treturn c.json({ status: \"ok\" });\n\t\t} catch (err) {\n\t\t\tconst msg = err instanceof Error ? err.message : String(err);\n\t\t\tif (msg.includes(\"not found\")) return c.json({ error: msg }, 404);\n\t\t\tif (msg.includes(\"not owned\")) return c.json({ error: msg }, 403);\n\t\t\tif (msg.includes(\"sync_rebootstrap_in_progress\")) return c.json({ error: msg }, 409);\n\t\t\treturn c.json({ error: msg }, 400);\n\t\t}\n\t});\n\n\treturn app;\n}\n","/**\n * Observer status route — GET /api/observer-status.\n *\n * Ports Python's viewer_routes/observer_status.py.\n * Returns observer runtime info, credential availability, and queue status.\n */\n\nimport type { ObserverClient } from \"@codemem/core\";\nimport { type MemoryStore, probeAvailableCredentials, type RawEventSweeper } from \"@codemem/core\";\nimport { Hono } from \"hono\";\n\ntype StoreFactory = () => MemoryStore;\n\nexport interface ObserverStatusDeps {\n\tgetStore: StoreFactory;\n\tgetSweeper: () => RawEventSweeper | null;\n\tgetObserver?: () => ObserverClient | null;\n}\n\nfunction normalizeActiveObserver(active: ReturnType<ObserverClient[\"getStatus\"]> | null) {\n\tif (!active) return null;\n\treturn {\n\t\t...active,\n\t\tauth: {\n\t\t\t...active.auth,\n\t\t\tmethod: active.auth.type,\n\t\t\ttoken_present: active.auth.hasToken,\n\t\t},\n\t};\n}\n\nfunction buildFailureImpact(\n\tlatestFailure: Record<string, unknown> | null,\n\tqueueTotals: { pending: number; sessions: number },\n\tauthBackoff: { active: boolean; remainingS: number },\n): string | null {\n\tif (!latestFailure) return null;\n\tif (authBackoff.active) {\n\t\treturn `Queue retries paused for ~${authBackoff.remainingS}s after an observer auth failure.`;\n\t}\n\tif (queueTotals.pending > 0) {\n\t\treturn `${queueTotals.pending} queued raw events across ${queueTotals.sessions} session(s) are waiting on a successful flush.`;\n\t}\n\treturn \"Failed flush batches are pending retry.\";\n}\n\nexport function observerStatusRoutes(deps?: ObserverStatusDeps) {\n\tconst app = new Hono();\n\n\tapp.get(\"/api/observer-status\", (c) => {\n\t\tconst store = deps?.getStore();\n\t\tconst sweeper = deps?.getSweeper();\n\t\tconst observer = deps?.getObserver?.() ?? null;\n\n\t\t// Stub fallback when store doesn't have the required methods (e.g. tests with mock store)\n\t\tif (!store || typeof store.rawEventBacklogTotals !== \"function\") {\n\t\t\treturn c.json({\n\t\t\t\tactive: null,\n\t\t\t\tavailable_credentials: {},\n\t\t\t\tlatest_failure: null,\n\t\t\t\tqueue: {\n\t\t\t\t\tpending: 0,\n\t\t\t\t\tsessions: 0,\n\t\t\t\t\tauth_backoff_active: false,\n\t\t\t\t\tauth_backoff_remaining_s: 0,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\n\t\tconst queueTotals = store.rawEventBacklogTotals();\n\t\tconst authBackoff = sweeper?.authBackoffStatus() ?? { active: false, remainingS: 0 };\n\t\tconst latestFailure = store.latestRawEventFlushFailure();\n\t\tconst active = normalizeActiveObserver(observer?.getStatus() ?? null);\n\t\tconst availableCredentials = probeAvailableCredentials();\n\t\tconst shouldShowFailure =\n\t\t\tlatestFailure != null && (authBackoff.active || queueTotals.pending > 0);\n\n\t\tconst failureWithImpact =\n\t\t\tshouldShowFailure && latestFailure\n\t\t\t\t? { ...latestFailure, impact: buildFailureImpact(latestFailure, queueTotals, authBackoff) }\n\t\t\t\t: null;\n\n\t\treturn c.json({\n\t\t\tactive,\n\t\t\tavailable_credentials: availableCredentials,\n\t\t\tlatest_failure: failureWithImpact,\n\t\t\tqueue: {\n\t\t\t\t...queueTotals,\n\t\t\t\tauth_backoff_active: authBackoff.active,\n\t\t\t\tauth_backoff_remaining_s: authBackoff.remainingS,\n\t\t\t},\n\t\t});\n\t});\n\n\treturn app;\n}\n","import { resolve as resolvePath } from \"node:path\";\nimport type { MemoryStore, ViewerIdentityTarget } from \"@codemem/core\";\nimport {\n\tbuildViewerIdentityTarget,\n\tresolveDbPath,\n\tVIEWER_IDENTITY_TARGET_KEYS,\n} from \"@codemem/core\";\n\nconst IDENTITY_TARGET_KEYS = new Set<string>(VIEWER_IDENTITY_TARGET_KEYS);\nconst BOOLEAN_IDENTITY_TARGET_KEYS = new Set([\n\t\"actor_id_present\",\n\t\"embedding_disabled\",\n\t\"embedding_offline\",\n]);\n\nexport type ViewerTargetValidation =\n\t| { ok: true }\n\t| { ok: false; status: 400 | 409; body: { error: { code: string; message: string } } };\n\nfunction invalidRequest(message: string): ViewerTargetValidation {\n\treturn { ok: false, status: 400, body: { error: { code: \"invalid_request\", message } } };\n}\n\nfunction conflict(code: string, message: string): ViewerTargetValidation {\n\treturn { ok: false, status: 409, body: { error: { code, message } } };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn value != null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nexport function currentIdentityTarget(): ViewerIdentityTarget {\n\treturn buildViewerIdentityTarget();\n}\n\nfunction requestedDbMatches(store: MemoryStore, value: unknown): boolean | null {\n\tif (value == null) return true;\n\tif (typeof value !== \"string\" || !value.trim()) return null;\n\treturn resolvePath(resolveDbPath(value.trim())) === resolvePath(store.dbPath);\n}\n\nfunction requestedIdentityMatches(value: unknown): boolean | null | \"unsupported\" {\n\tif (value == null) return true;\n\tif (!isRecord(value)) return null;\n\tif (\n\t\tObject.keys(value).length !== IDENTITY_TARGET_KEYS.size ||\n\t\tObject.keys(value).some((key) => !IDENTITY_TARGET_KEYS.has(key))\n\t)\n\t\treturn \"unsupported\";\n\tconst expected = currentIdentityTarget();\n\tfor (const key of VIEWER_IDENTITY_TARGET_KEYS) {\n\t\tconst requested = value[key];\n\t\tif (BOOLEAN_IDENTITY_TARGET_KEYS.has(key)) {\n\t\t\tif (typeof requested !== \"boolean\") return null;\n\t\t} else if (requested !== null && typeof requested !== \"string\") {\n\t\t\treturn null;\n\t\t}\n\t\tif (requested !== expected[key]) return false;\n\t}\n\treturn true;\n}\n\nexport function validateViewerTarget(\n\tstore: MemoryStore,\n\tpayload: Record<string, unknown>,\n\toptions: { requireCurrentIdentity?: boolean; requirePairedTargets?: boolean } = {},\n): ViewerTargetValidation {\n\tif (options.requirePairedTargets) {\n\t\tconst hasDbPath = Object.hasOwn(payload, \"db_path\");\n\t\tconst hasIdentityTarget = Object.hasOwn(payload, \"identity_target\");\n\t\tif (hasDbPath !== hasIdentityTarget) {\n\t\t\treturn invalidRequest(\"db_path and identity_target must be provided together\");\n\t\t}\n\t\tif (hasDbPath && (payload.db_path == null || payload.identity_target == null)) {\n\t\t\treturn invalidRequest(\"db_path and identity_target must be valid when provided\");\n\t\t}\n\t}\n\tconst dbMatches = requestedDbMatches(store, payload.db_path);\n\tif (dbMatches == null) return invalidRequest(\"db_path must be a non-empty string\");\n\tif (!dbMatches) {\n\t\treturn conflict(\"viewer_db_mismatch\", \"viewer database does not match request\");\n\t}\n\n\tconst identityMatches = requestedIdentityMatches(payload.identity_target);\n\tif (identityMatches === \"unsupported\") {\n\t\treturn conflict(\"viewer_contract_unsupported\", \"viewer request contract is incompatible\");\n\t}\n\tif (identityMatches == null) return invalidRequest(\"identity_target is invalid\");\n\tif (!identityMatches) {\n\t\treturn conflict(\"viewer_identity_mismatch\", \"viewer identity does not match request\");\n\t}\n\tif (\n\t\t(options.requireCurrentIdentity || payload.identity_target != null) &&\n\t\t!store.hasCurrentIdentity()\n\t) {\n\t\treturn conflict(\"viewer_identity_mismatch\", \"viewer identity does not match request\");\n\t}\n\treturn { ok: true };\n}\n","import { isAbsolute, posix, resolve as resolvePath, win32 } from \"node:path\";\nimport type {\n\tAutomaticContext,\n\tAutomaticRecallWriteOutcome,\n\tMemoryFilters,\n\tMemoryStore,\n\tPackRenderOptions,\n\tPromptPackAttemptMetadata,\n\tRetrievalLedgerDeliveryOutcome,\n\tRetrievalLedgerFailureReason,\n\tRetrievalLedgerWriteOutcome,\n} from \"@codemem/core\";\nimport {\n\tclonePromptPackAttempt,\n\tisAutomaticRecallMeasurement,\n\tPROMPT_TRANSPORT_PROTOCOL_RANGE,\n\tpromptPackArtifactFingerprint,\n\trecordAutomaticRecall,\n\trecordPromptPackArtifacts,\n\trecordPromptPackTerminal,\n\tresolveProject,\n\ttryUpdateRetrievalDelivery,\n} from \"@codemem/core\";\nimport { Hono } from \"hono\";\nimport { currentIdentityTarget, validateViewerTarget } from \"./target-validation.js\";\n\ntype StoreFactory = () => MemoryStore;\ntype LedgerOutcome =\n\t| RetrievalLedgerWriteOutcome\n\t| RetrievalLedgerDeliveryOutcome\n\t| AutomaticRecallWriteOutcome;\n\nconst MAX_LEDGER_PAYLOAD_BYTES = 16 * 1024;\nconst MAX_METADATA_FIELD_CHARS = 512;\nconst MAX_WORKING_SET_FILES = 50;\nconst MAX_WORKING_SET_PATH_CHARS = 512;\nconst INVALID_JSON = Symbol(\"invalid-json\");\n\nconst PACK_KEYS = new Set([\n\t\"context\",\n\t\"limit\",\n\t\"token_budget\",\n\t\"project\",\n\t\"cwd\",\n\t\"all_projects\",\n\t\"working_set_files\",\n\t\"compact\",\n\t\"compact_detail_count\",\n\t\"db_path\",\n\t\"identity_target\",\n\t\"attempt\",\n\t\"automatic_context\",\n]);\nconst LEDGER_KEYS = new Set([\n\t\"automatic_recall\",\n\t\"evaluation_key\",\n\t\"action\",\n\t\"attempt_id\",\n\t\"started_at\",\n\t\"source\",\n\t\"stream_id\",\n\t\"source_session_id\",\n\t\"prompt_number\",\n\t\"request_id\",\n\t\"retrieval_status\",\n\t\"delivery_status\",\n\t\"failure_code\",\n\t\"failure_stage\",\n\t\"original_attempt_id\",\n\t\"db_path\",\n\t\"identity_target\",\n]);\nconst ATTEMPT_KEYS = new Set([\n\t\"attempt_id\",\n\t\"started_at\",\n\t\"source\",\n\t\"stream_id\",\n\t\"source_session_id\",\n\t\"prompt_number\",\n\t\"request_id\",\n]);\nconst FORBIDDEN_LEDGER_KEYS = new Set([\n\t\"body\",\n\t\"context\",\n\t\"pack\",\n\t\"pack_text\",\n\t\"path\",\n\t\"preview\",\n\t\"prompt\",\n\t\"query\",\n\t\"raw_prompt\",\n\t\"title\",\n]);\n\ntype ValidatedPackRequest = {\n\tcontext: string;\n\tlimit: number;\n\ttokenBudget: number | null;\n\tfilters: MemoryFilters;\n\trenderOptions?: PackRenderOptions;\n\tattempt?: Record<string, unknown>;\n\tautomaticContext?: AutomaticContext | null;\n};\n\nfunction invalidRequest(message: string) {\n\treturn { error: { code: \"invalid_request\", message } };\n}\n\nfunction viewerIdentityMismatch() {\n\treturn {\n\t\terror: {\n\t\t\tcode: \"viewer_identity_mismatch\",\n\t\t\tmessage: \"viewer identity does not match request\",\n\t\t},\n\t};\n}\n\nfunction viewerContractUnsupported() {\n\treturn {\n\t\terror: {\n\t\t\tcode: \"viewer_contract_unsupported\",\n\t\t\tmessage: \"viewer request contract is incompatible\",\n\t\t},\n\t};\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn value != null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction isAbsolutePath(value: string): boolean {\n\treturn posix.isAbsolute(value) || win32.isAbsolute(value);\n}\n\nfunction normalizeWorkingSetPath(value: string): string | null {\n\tconst trimmed = value.trim();\n\tif (!trimmed || trimmed.length > MAX_WORKING_SET_PATH_CHARS || isAbsolutePath(trimmed)) {\n\t\treturn null;\n\t}\n\tconst normalized = posix.normalize(trimmed.replaceAll(\"\\\\\", \"/\")).replace(/^\\.\\//, \"\");\n\tif (!normalized || normalized === \".\" || normalized === \"..\" || normalized.startsWith(\"../\")) {\n\t\treturn null;\n\t}\n\treturn normalized;\n}\n\nfunction validateMetadataFields(\n\tpayload: Record<string, unknown>,\n\tallowedKeys: ReadonlySet<string>,\n): string | null {\n\tif (Buffer.byteLength(JSON.stringify(payload), \"utf8\") > MAX_LEDGER_PAYLOAD_BYTES) {\n\t\treturn \"ledger metadata exceeds 16384 bytes\";\n\t}\n\tfor (const key of Object.keys(payload)) {\n\t\tif (FORBIDDEN_LEDGER_KEYS.has(key)) return `ledger metadata rejects sensitive field: ${key}`;\n\t\tif (!allowedKeys.has(key)) return `ledger metadata contains unsupported field: ${key}`;\n\t}\n\tif (typeof payload.attempt_id !== \"string\" || payload.attempt_id.length === 0) {\n\t\treturn \"ledger metadata requires attempt_id\";\n\t}\n\tif (\n\t\tpayload.prompt_number != null &&\n\t\t(typeof payload.prompt_number !== \"number\" ||\n\t\t\t!Number.isInteger(payload.prompt_number) ||\n\t\t\tpayload.prompt_number < 0)\n\t) {\n\t\treturn \"ledger metadata prompt_number must be a non-negative integer\";\n\t}\n\tfor (const key of [\n\t\t\"attempt_id\",\n\t\t\"started_at\",\n\t\t\"source\",\n\t\t\"stream_id\",\n\t\t\"source_session_id\",\n\t\t\"request_id\",\n\t\t\"failure_code\",\n\t\t\"failure_stage\",\n\t\t\"original_attempt_id\",\n\t] as const) {\n\t\tconst field = payload[key];\n\t\tif (field != null && (typeof field !== \"string\" || field.length > MAX_METADATA_FIELD_CHARS)) {\n\t\t\treturn `ledger metadata field ${key} is invalid`;\n\t\t}\n\t\tif (typeof field === \"string\" && isAbsolutePath(field)) {\n\t\t\treturn `ledger metadata rejects absolute paths in field: ${key}`;\n\t\t}\n\t}\n\treturn null;\n}\n\nfunction attemptMetadata(payload: Record<string, unknown>): PromptPackAttemptMetadata {\n\treturn {\n\t\tattemptId: payload.attempt_id as string,\n\t\tstartedAt: (payload.started_at as string | undefined) ?? new Date().toISOString(),\n\t\tcompletedAt: new Date().toISOString(),\n\t\tsource: (payload.source as string | undefined) ?? \"opencode\",\n\t\tstreamId: (payload.stream_id as string | undefined) ?? null,\n\t\tsourceSessionId: (payload.source_session_id as string | undefined) ?? null,\n\t\tpromptNumber: (payload.prompt_number as number | undefined) ?? null,\n\t\trequestId: (payload.request_id as string | undefined) ?? null,\n\t};\n}\n\nfunction validateAutomaticContext(value: unknown): AutomaticContext | null | string {\n\tif (value === null) return null;\n\tif (!isRecord(value)) return \"automatic_context must be an object or null\";\n\tfor (const key of Object.keys(value)) {\n\t\tif (key !== \"source\" && key !== \"host_session_id\") {\n\t\t\treturn `automatic_context contains unsupported field: ${key}`;\n\t\t}\n\t}\n\tconst source = value.source;\n\tconst hostSessionId = value.host_session_id;\n\tif (typeof source !== \"string\" || !source.trim() || source.length > 64) {\n\t\treturn \"automatic_context source is invalid\";\n\t}\n\tif (\n\t\ttypeof hostSessionId !== \"string\" ||\n\t\t!hostSessionId.trim() ||\n\t\thostSessionId.length > MAX_METADATA_FIELD_CHARS ||\n\t\tisAbsolutePath(hostSessionId)\n\t) {\n\t\treturn \"automatic_context host_session_id is invalid\";\n\t}\n\treturn { source: source.trim(), hostSessionId: hostSessionId.trim() };\n}\n\nfunction resolveRequestAutomaticContext(\n\tvalue: Record<string, unknown>,\n\tattempt: Record<string, unknown> | undefined,\n): AutomaticContext | null | undefined | string {\n\tif (Object.hasOwn(value, \"automatic_context\")) {\n\t\treturn validateAutomaticContext(value.automatic_context);\n\t}\n\tif (!attempt) return undefined;\n\t// Only the OpenCode plugin's older attempt metadata implies an automatic request.\n\t// Named non-OpenCode hook sources keep generic behavior so Viewer and their local\n\t// fallbacks agree; an attempt with no source is unknown origin and stays fail-closed.\n\tconst source = typeof attempt.source === \"string\" ? attempt.source.trim().toLowerCase() : \"\";\n\tif (source && source !== \"opencode\") return undefined;\n\tconst hostSessionId = attempt.source_session_id;\n\tif (source === \"opencode\" && typeof hostSessionId === \"string\" && hostSessionId.trim()) {\n\t\treturn { source, hostSessionId: hostSessionId.trim() };\n\t}\n\treturn null;\n}\n\nfunction packRenderOptions(value: Record<string, unknown>): PackRenderOptions | undefined {\n\tif (value.compact == null && value.compact_detail_count == null) return undefined;\n\treturn {\n\t\tcompact: value.compact === true || value.compact_detail_count != null,\n\t\t...(value.compact_detail_count != null\n\t\t\t? { compactDetailCount: value.compact_detail_count as number }\n\t\t\t: {}),\n\t};\n}\n\nfunction packRequestArgs(request: ValidatedPackRequest) {\n\treturn [\n\t\trequest.context,\n\t\trequest.limit,\n\t\trequest.tokenBudget,\n\t\trequest.filters,\n\t\trequest.renderOptions,\n\t\trequest.automaticContext,\n\t] as const;\n}\n\nfunction validatePackRequest(value: unknown): ValidatedPackRequest | string {\n\tif (!isRecord(value)) return \"request body must be an object\";\n\tfor (const key of Object.keys(value)) {\n\t\tif (!PACK_KEYS.has(key)) return `request body contains unsupported field: ${key}`;\n\t}\n\tconst context = typeof value.context === \"string\" ? value.context.trim() : \"\";\n\tif (!context) return \"context required\";\n\tconst limit = value.limit ?? 10;\n\tif (typeof limit !== \"number\" || !Number.isInteger(limit) || limit < 1) {\n\t\treturn \"limit must be a positive int\";\n\t}\n\tconst tokenBudget = value.token_budget ?? null;\n\tif (\n\t\ttokenBudget !== null &&\n\t\t(typeof tokenBudget !== \"number\" || !Number.isInteger(tokenBudget) || tokenBudget < 0)\n\t) {\n\t\treturn \"token_budget must be a non-negative int\";\n\t}\n\tif (value.all_projects != null && typeof value.all_projects !== \"boolean\") {\n\t\treturn \"all_projects must be a boolean\";\n\t}\n\tif (value.project != null && (typeof value.project !== \"string\" || !value.project.trim())) {\n\t\treturn \"project must be a non-empty string\";\n\t}\n\tif (\n\t\tvalue.cwd != null &&\n\t\t(typeof value.cwd !== \"string\" || !value.cwd.trim() || !isAbsolute(value.cwd))\n\t) {\n\t\treturn \"cwd must be an absolute path\";\n\t}\n\tif (value.working_set_files != null && !Array.isArray(value.working_set_files)) {\n\t\treturn \"working_set_files must be an array of repository-relative strings\";\n\t}\n\tconst workingSetValues = (value.working_set_files ?? []) as unknown[];\n\tif (workingSetValues.length > MAX_WORKING_SET_FILES) {\n\t\treturn `working_set_files must contain at most ${MAX_WORKING_SET_FILES} entries`;\n\t}\n\tconst workingSetFiles: string[] = [];\n\tfor (const entry of workingSetValues) {\n\t\tif (typeof entry !== \"string\") {\n\t\t\treturn \"working_set_files must be an array of repository-relative strings\";\n\t\t}\n\t\tconst normalized = normalizeWorkingSetPath(entry);\n\t\tif (!normalized) return \"working_set_files contains an invalid repository-relative path\";\n\t\tif (!workingSetFiles.includes(normalized)) workingSetFiles.push(normalized);\n\t}\n\tif (value.compact != null && typeof value.compact !== \"boolean\") {\n\t\treturn \"compact must be a boolean\";\n\t}\n\tif (\n\t\tvalue.compact_detail_count != null &&\n\t\t(typeof value.compact_detail_count !== \"number\" ||\n\t\t\t!Number.isInteger(value.compact_detail_count) ||\n\t\t\tvalue.compact_detail_count < 0)\n\t) {\n\t\treturn \"compact_detail_count must be a non-negative int\";\n\t}\n\tlet attempt: Record<string, unknown> | undefined;\n\tif (value.attempt != null) {\n\t\tif (!isRecord(value.attempt)) return \"attempt must be an object\";\n\t\tconst attemptError = validateMetadataFields(value.attempt, ATTEMPT_KEYS);\n\t\tif (attemptError) return attemptError;\n\t\tattempt = value.attempt;\n\t}\n\tconst automaticContext = resolveRequestAutomaticContext(value, attempt);\n\tif (typeof automaticContext === \"string\") return automaticContext;\n\n\tconst filters: MemoryFilters = {};\n\tif (value.all_projects !== true) {\n\t\tconst envProject = process.env.CODEMEM_PROJECT?.trim() || null;\n\t\tconst requestCwd = value.cwd as string | undefined;\n\t\tconst requestProject = value.project as string | undefined;\n\t\tconst project = resolveProject(\n\t\t\trequestCwd ?? process.cwd(),\n\t\t\trequestProject ?? (requestCwd == null ? envProject : undefined),\n\t\t);\n\t\tif (project) filters.project = project;\n\t}\n\tif (workingSetFiles.length > 0) filters.working_set_paths = workingSetFiles;\n\n\treturn {\n\t\tcontext,\n\t\tlimit,\n\t\ttokenBudget: tokenBudget as number | null,\n\t\tfilters,\n\t\trenderOptions: packRenderOptions(value),\n\t\tattempt,\n\t\tautomaticContext,\n\t};\n}\n\nfunction ledgerFailureStatus(reason: RetrievalLedgerFailureReason): 400 | 409 | 422 | 503 {\n\tif (reason === \"idempotency_conflict\") return 409;\n\tif (reason === \"attempt_not_found\") return 422;\n\tif (reason === \"storage_unavailable\") return 503;\n\treturn 400;\n}\n\nfunction dispatchRecallMeasurement(\n\tstore: MemoryStore,\n\tpayload: Record<string, unknown>,\n): AutomaticRecallWriteOutcome | string | null {\n\tconst action = payload.action;\n\tif (payload.automatic_recall === undefined && action !== \"recall\") return null;\n\tconst isValidMeasurement =\n\t\tisAutomaticRecallMeasurement(payload.automatic_recall) &&\n\t\ttypeof payload.evaluation_key === \"string\" &&\n\t\t/^[a-f0-9]{64}$/.test(payload.evaluation_key);\n\tif (action === \"delivery\") {\n\t\tif (!isValidMeasurement) return null;\n\t\ttry {\n\t\t\trecordAutomaticRecall(\n\t\t\t\tstore.db,\n\t\t\t\tpayload.attempt_id as string,\n\t\t\t\tpayload.evaluation_key,\n\t\t\t\tpayload.automatic_recall,\n\t\t\t);\n\t\t} catch {\n\t\t\t// Delivery diagnostics are best-effort after the receipt has been accepted.\n\t\t}\n\t\treturn null;\n\t}\n\tif (action !== \"recall\" || !isValidMeasurement) {\n\t\treturn \"invalid automatic recall measurement\";\n\t}\n\treturn recordAutomaticRecall(\n\t\tstore.db,\n\t\tpayload.attempt_id as string,\n\t\tpayload.evaluation_key,\n\t\tpayload.automatic_recall,\n\t);\n}\n\nfunction dispatchLedger(\n\tstore: MemoryStore,\n\tpayload: Record<string, unknown>,\n): LedgerOutcome | string {\n\tconst action = payload.action;\n\tconst metadata = attemptMetadata(payload);\n\tif (action === \"delivery\") {\n\t\tconst status = payload.delivery_status;\n\t\tif (status !== \"handed_off\" && status !== \"failed\" && status !== \"unknown\") {\n\t\t\treturn \"delivery action requires a valid delivery_status\";\n\t\t}\n\t\tconst outcome = tryUpdateRetrievalDelivery(store.db, metadata.attemptId, status);\n\t\tif (outcome.ok) dispatchRecallMeasurement(store, payload);\n\t\treturn outcome;\n\t}\n\tconst measurement = dispatchRecallMeasurement(store, payload);\n\tif (measurement !== null) return measurement;\n\tif (action === \"cache_reuse\") {\n\t\tif (typeof payload.original_attempt_id !== \"string\" || !payload.original_attempt_id) {\n\t\t\treturn \"cache_reuse action requires original_attempt_id\";\n\t\t}\n\t\treturn clonePromptPackAttempt(store.db, payload.original_attempt_id, metadata);\n\t}\n\tif (action !== \"record\") return \"ledger action is invalid\";\n\tif (\n\t\t(payload.retrieval_status !== \"skipped\" && payload.retrieval_status !== \"failed\") ||\n\t\ttypeof payload.failure_code !== \"string\" ||\n\t\t!payload.failure_code ||\n\t\ttypeof payload.failure_stage !== \"string\" ||\n\t\t!payload.failure_stage\n\t) {\n\t\treturn \"record action requires retrieval_status, failure_code, and failure_stage\";\n\t}\n\treturn recordPromptPackTerminal(\n\t\tstore.db,\n\t\tmetadata,\n\t\tpayload.retrieval_status,\n\t\tpayload.failure_code,\n\t\tpayload.failure_stage,\n\t);\n}\n\nexport function packTransportRoutes(getStore: StoreFactory) {\n\tconst app = new Hono();\n\n\tapp.get(\"/api/prompt-pack-profile\", (c) => {\n\t\ttry {\n\t\t\tconst store = getStore();\n\t\t\tif (!store.hasCurrentIdentity()) return c.json(viewerIdentityMismatch(), 409);\n\t\t\treturn c.json({\n\t\t\t\tservice: \"codemem-viewer\",\n\t\t\t\tprotocol_version: PROMPT_TRANSPORT_PROTOCOL_RANGE.protocolVersion,\n\t\t\t\tmin_supported_protocol_version: PROMPT_TRANSPORT_PROTOCOL_RANGE.minSupportedProtocolVersion,\n\t\t\t\tdb_path: resolvePath(store.dbPath),\n\t\t\t\tidentity_target: currentIdentityTarget(),\n\t\t\t});\n\t\t} catch {\n\t\t\treturn c.json(\n\t\t\t\t{ error: { code: \"profile_failed\", message: \"viewer profile could not be read\" } },\n\t\t\t\t500,\n\t\t\t);\n\t\t}\n\t});\n\n\tapp.post(\"/api/pack\", async (c) => {\n\t\tconst parsed = await c.req.json().catch(() => INVALID_JSON);\n\t\tif (parsed === INVALID_JSON) return c.json(invalidRequest(\"invalid json body\"), 400);\n\t\tconst request = validatePackRequest(parsed);\n\t\tif (typeof request === \"string\") {\n\t\t\tif (request.startsWith(\"request body contains unsupported field:\"))\n\t\t\t\treturn c.json(viewerContractUnsupported(), 409);\n\t\t\treturn c.json(invalidRequest(request), 400);\n\t\t}\n\t\ttry {\n\t\t\tconst store = getStore();\n\t\t\tconst target = validateViewerTarget(store, parsed, { requireCurrentIdentity: true });\n\t\t\tif (!target.ok) return c.json(target.body, target.status);\n\t\t\tif (!request.attempt) {\n\t\t\t\tconst pack = await store.buildMemoryPackAsync(...packRequestArgs(request));\n\t\t\t\treturn c.json(pack);\n\t\t\t}\n\t\t\tconst artifacts = await store.buildMemoryPackWithTraceAsync(...packRequestArgs(request));\n\t\t\tlet ledgerArtifactFingerprint: string | undefined;\n\t\t\ttry {\n\t\t\t\tledgerArtifactFingerprint = promptPackArtifactFingerprint(\n\t\t\t\t\tstore.db,\n\t\t\t\t\trequest.context,\n\t\t\t\t\trequest.filters,\n\t\t\t\t\tartifacts,\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\t// Fingerprinting is instrumentation and must not block pack delivery.\n\t\t\t}\n\t\t\tlet ledgerOutcome: RetrievalLedgerWriteOutcome | undefined;\n\t\t\ttry {\n\t\t\t\tledgerOutcome = recordPromptPackArtifacts(\n\t\t\t\t\tstore.db,\n\t\t\t\t\tattemptMetadata(request.attempt),\n\t\t\t\t\trequest.context,\n\t\t\t\t\trequest.filters,\n\t\t\t\t\tartifacts,\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\t// Ledger instrumentation is best-effort and must not block pack delivery.\n\t\t\t}\n\t\t\treturn c.json({\n\t\t\t\t...artifacts.response,\n\t\t\t\t...(ledgerArtifactFingerprint\n\t\t\t\t\t? { ledger_artifact_fingerprint: ledgerArtifactFingerprint }\n\t\t\t\t\t: {}),\n\t\t\t\t...(ledgerOutcome?.ok === false && ledgerOutcome.reason === \"idempotency_conflict\"\n\t\t\t\t\t? { ledger_outcome: ledgerOutcome }\n\t\t\t\t\t: {}),\n\t\t\t});\n\t\t} catch {\n\t\t\treturn c.json(\n\t\t\t\t{ error: { code: \"pack_failed\", message: \"memory pack could not be built\" } },\n\t\t\t\t500,\n\t\t\t);\n\t\t}\n\t});\n\n\tapp.post(\"/api/prompt-pack-ledger\", async (c) => {\n\t\tconst parsed = await c.req.json().catch(() => INVALID_JSON);\n\t\tif (parsed === INVALID_JSON) return c.json(invalidRequest(\"invalid json body\"), 400);\n\t\tif (!isRecord(parsed)) return c.json(invalidRequest(\"request body must be an object\"), 400);\n\t\tconst validationError = validateMetadataFields(parsed, LEDGER_KEYS);\n\t\tif (validationError) {\n\t\t\tif (validationError.startsWith(\"ledger metadata contains unsupported field:\"))\n\t\t\t\treturn c.json(viewerContractUnsupported(), 409);\n\t\t\treturn c.json(invalidRequest(validationError), 400);\n\t\t}\n\t\ttry {\n\t\t\tconst store = getStore();\n\t\t\tconst target = validateViewerTarget(store, parsed, { requireCurrentIdentity: true });\n\t\t\tif (!target.ok) return c.json(target.body, target.status);\n\t\t\tconst outcome = dispatchLedger(store, parsed);\n\t\t\tif (typeof outcome === \"string\") return c.json(invalidRequest(outcome), 400);\n\t\t\tif (outcome.ok) return c.json(outcome);\n\t\t\treturn c.json(outcome, ledgerFailureStatus(outcome.reason));\n\t\t} catch {\n\t\t\treturn c.json(\n\t\t\t\t{ error: { code: \"ledger_failed\", message: \"prompt-pack ledger operation failed\" } },\n\t\t\t\t500,\n\t\t\t);\n\t\t}\n\t});\n\n\treturn app;\n}\n","/**\n * Raw events routes — GET & POST /api/raw-events, GET /api/raw-events/status,\n * POST /api/claude-hooks, POST /api/codex-hooks.\n */\n\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { HookTranscriptOutcome, MemoryStore, RawEventSweeper } from \"@codemem/core\";\nimport {\n\tbuildRawEventEnvelopeFromCodexHook,\n\tbuildRawEventEnvelopeFromHook,\n\tingestRawEvents,\n\tRawEventIngestValidationError,\n\tschema,\n} from \"@codemem/core\";\nimport { desc } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport { Hono } from \"hono\";\nimport { parseJsonObjectBody, queryInt } from \"../helpers.js\";\nimport { validateViewerTarget } from \"./target-validation.js\";\n\ntype StoreFactory = () => MemoryStore;\ntype JsonResponder = {\n\tjson: (data: unknown, status?: number) => Response;\n};\n\nconst DEFAULT_MAX_RAW_EVENTS_BODY_BYTES = 1_048_576;\n\nfunction configuredMaxRawEventsBodyBytes(): number {\n\tconst parsed = Number(process.env.CODEMEM_RAW_EVENTS_MAX_BODY_BYTES?.trim() ?? \"\");\n\treturn Number.isSafeInteger(parsed) && parsed > 0 ? parsed : DEFAULT_MAX_RAW_EVENTS_BODY_BYTES;\n}\n\nconst MAX_RAW_EVENTS_BODY_BYTES = configuredMaxRawEventsBodyBytes();\ntype LegacyTranscriptSource = \"claude\" | \"codex\";\ntype TranscriptOutcomeCounts = Record<HookTranscriptOutcome, number>;\n\nfunction emptyTranscriptOutcomeCounts(): TranscriptOutcomeCounts {\n\treturn {\n\t\tok: 0,\n\t\tnot_provided: 0,\n\t\tpath_rejected: 0,\n\t\tunreadable: 0,\n\t\tno_complete_record: 0,\n\t\tno_assistant_record: 0,\n\t} satisfies TranscriptOutcomeCounts;\n}\n\nfunction createTranscriptDiagnostics() {\n\tconst counts: Record<LegacyTranscriptSource, TranscriptOutcomeCounts> = {\n\t\tclaude: emptyTranscriptOutcomeCounts(),\n\t\tcodex: emptyTranscriptOutcomeCounts(),\n\t};\n\treturn {\n\t\trecord(source: LegacyTranscriptSource, outcome: HookTranscriptOutcome): void {\n\t\t\tcounts[source][outcome] += 1;\n\t\t},\n\t\tsnapshot() {\n\t\t\treturn {\n\t\t\t\tscope: \"legacy_compatibility_routes\" as const,\n\t\t\t\tcounts: {\n\t\t\t\t\tclaude: { ...counts.claude },\n\t\t\t\t\tcodex: { ...counts.codex },\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t};\n}\n\nfunction transcriptSkipResponse(outcome: HookTranscriptOutcome | null) {\n\tif (outcome !== null && outcome !== \"ok\") {\n\t\treturn {\n\t\t\tinserted: 0,\n\t\t\tskipped: 1,\n\t\t\tskip_reason: \"transcript_unavailable\" as const,\n\t\t\tskip_detail: outcome,\n\t\t};\n\t}\n\treturn { inserted: 0, skipped: 1, skip_reason: \"unsupported_hook\" as const };\n}\n\nfunction claudeTranscriptRoot(): string {\n\treturn join(process.env.CLAUDE_CONFIG_DIR?.trim() || join(homedir(), \".claude\"), \"projects\");\n}\n\nfunction codexTranscriptRoot(): string {\n\treturn join(process.env.CODEX_HOME?.trim() || join(homedir(), \".codex\"), \"sessions\");\n}\n\n/** Nudge the sweeper safely — never crashes the caller. */\nfunction nudgeSweeper(\n\tsweeper: RawEventSweeper | null | undefined,\n\tsessions: Iterable<{ source: string; streamId: string }>,\n): void {\n\tfor (const session of sessions) {\n\t\ttry {\n\t\t\tsweeper?.nudge(session.streamId, session.source);\n\t\t} catch {\n\t\t\t// A failed nudge must not block later validated sessions.\n\t\t}\n\t}\n}\n\nasync function flushBoundarySessions(\n\tsweeper: RawEventSweeper | null | undefined,\n\tsessions: Iterable<{ source: string; streamId: string }>,\n): Promise<void> {\n\tfor (const session of sessions) {\n\t\ttry {\n\t\t\tawait sweeper?.flushBoundary(session.streamId, session.source);\n\t\t} catch {\n\t\t\t// Boundary extraction remains best-effort, matching the legacy CLI path.\n\t\t}\n\t}\n}\n\nfunction isClaudeBoundaryEnvelope(envelope: object): boolean {\n\tconst record = envelope as Record<string, unknown>;\n\tif (\n\t\tString(record.source ?? \"\")\n\t\t\t.trim()\n\t\t\t.toLowerCase() !== \"claude\"\n\t)\n\t\treturn false;\n\tconst payload = record.payload;\n\tif (payload == null || typeof payload !== \"object\" || Array.isArray(payload)) return false;\n\tconst adapter = (payload as Record<string, unknown>)._adapter;\n\tif (adapter == null || typeof adapter !== \"object\" || Array.isArray(adapter)) return false;\n\tconst meta = (adapter as Record<string, unknown>).meta;\n\tif (meta == null || typeof meta !== \"object\" || Array.isArray(meta)) return false;\n\tconst hookEventName = (meta as Record<string, unknown>).hook_event_name;\n\treturn hookEventName === \"SessionEnd\" || hookEventName === \"Stop\";\n}\n\nconst SAFE_INGEST_VALIDATION_ERRORS = new Set([\n\t\"source must be string\",\n\t\"source is required\",\n\t\"source must use 1-64 letters, digits, dots, underscores, or hyphens\",\n\t\"session_stream_id must be string\",\n\t\"session_id must be string\",\n\t\"stream_id must be string\",\n\t\"opencode_session_id must be string\",\n\t\"conflicting session id fields\",\n\t\"invalid session id\",\n\t\"event source conflicts with request source\",\n\t\"session id required\",\n\t\"event_type must be string\",\n\t\"event_type required\",\n\t\"event_type has invalid syntax\",\n\t\"event_id must be string\",\n\t\"event_id required\",\n\t\"event_id has invalid syntax\",\n\t\"event_seq must be int\",\n\t\"ts_wall_ms must be number\",\n\t\"ts_mono_ms must be number\",\n\t\"payload must be an object\",\n\t\"cwd must be string\",\n\t\"project must be string\",\n\t\"started_at must be string\",\n\t\"events must be a list\",\n\t\"event must be an object\",\n]);\n\nfunction boundedIngestValidationMessage(error: RawEventIngestValidationError): string {\n\treturn SAFE_INGEST_VALIDATION_ERRORS.has(error.message)\n\t\t? error.message\n\t\t: \"invalid raw event request\";\n}\n\nfunction boundedIngestErrorResponse(c: JsonResponder, error: unknown): Response {\n\tif (error instanceof RawEventIngestValidationError) {\n\t\treturn c.json({ error: boundedIngestValidationMessage(error) }, 400);\n\t}\n\tconst response: Record<string, unknown> = { error: \"internal server error\" };\n\tif (process.env.CODEMEM_VIEWER_DEBUG === \"1\") {\n\t\tresponse.detail = error instanceof Error ? error.message : String(error);\n\t}\n\treturn c.json(response, 500);\n}\n\nfunction untargetedPayload(payload: Record<string, unknown>): Record<string, unknown> {\n\tconst { db_path: _dbPath, identity_target: _identityTarget, ...body } = payload;\n\treturn body;\n}\n\nasync function ingestNormalizedEnvelope(\n\tstore: MemoryStore,\n\tsweeper: RawEventSweeper | null | undefined,\n\tenvelope: object,\n\tflushBoundary = false,\n) {\n\tconst result = ingestRawEvents(store, envelope);\n\tnudgeSweeper(sweeper, result.sessions);\n\tif (flushBoundary && isClaudeBoundaryEnvelope(envelope)) {\n\t\tawait flushBoundarySessions(sweeper, result.sessions);\n\t}\n\treturn result;\n}\n\nexport function rawEventsRoutes(getStore: StoreFactory, sweeper?: RawEventSweeper | null) {\n\tconst app = new Hono();\n\tconst transcriptDiagnostics = createTranscriptDiagnostics();\n\n\t// GET /api/raw-events (compat endpoint for stats panel)\n\tapp.get(\"/api/raw-events\", (c) => {\n\t\tconst store = getStore();\n\t\tconst totals = store.rawEventBacklogTotals();\n\t\treturn c.json(totals);\n\t});\n\n\t// GET /api/raw-events/status\n\tapp.get(\"/api/raw-events/status\", (c) => {\n\t\tconst store = getStore();\n\t\tconst limit = queryInt(c.req.query(\"limit\"), 25);\n\t\tconst d = drizzle(store.db, { schema });\n\t\tconst rows = d\n\t\t\t.select({\n\t\t\t\tsource: schema.rawEventSessions.source,\n\t\t\t\tstream_id: schema.rawEventSessions.stream_id,\n\t\t\t\topencode_session_id: schema.rawEventSessions.opencode_session_id,\n\t\t\t\tcwd: schema.rawEventSessions.cwd,\n\t\t\t\tproject: schema.rawEventSessions.project,\n\t\t\t\tstarted_at: schema.rawEventSessions.started_at,\n\t\t\t\tlast_seen_ts_wall_ms: schema.rawEventSessions.last_seen_ts_wall_ms,\n\t\t\t\tlast_received_event_seq: schema.rawEventSessions.last_received_event_seq,\n\t\t\t\tlast_flushed_event_seq: schema.rawEventSessions.last_flushed_event_seq,\n\t\t\t\tupdated_at: schema.rawEventSessions.updated_at,\n\t\t\t})\n\t\t\t.from(schema.rawEventSessions)\n\t\t\t.orderBy(desc(schema.rawEventSessions.updated_at))\n\t\t\t.limit(limit)\n\t\t\t.all();\n\t\tconst items = rows.map((row) => {\n\t\t\tconst streamId = String(row.stream_id ?? row.opencode_session_id ?? \"\");\n\t\t\treturn {\n\t\t\t\t...row,\n\t\t\t\tsession_stream_id: streamId,\n\t\t\t\tsession_id: streamId,\n\t\t\t};\n\t\t});\n\t\tconst totals = store.rawEventBacklogTotals();\n\t\treturn c.json({\n\t\t\titems,\n\t\t\ttotals,\n\t\t\tingest: {\n\t\t\t\tavailable: true,\n\t\t\t\tmode: \"stream_queue\",\n\t\t\t\tmax_body_bytes: MAX_RAW_EVENTS_BODY_BYTES,\n\t\t\t},\n\t\t\ttranscript_diagnostics: transcriptDiagnostics.snapshot(),\n\t\t});\n\t});\n\n\t// POST /api/raw-events — ingest raw events from plugin\n\tapp.post(\"/api/raw-events\", async (c) => {\n\t\tconst result = await parseJsonObjectBody(c, MAX_RAW_EVENTS_BODY_BYTES);\n\t\tif (result instanceof Response) return result;\n\t\ttry {\n\t\t\tconst store = getStore();\n\t\t\tconst target = validateViewerTarget(store, result, { requirePairedTargets: true });\n\t\t\tif (!target.ok) return c.json(target.body, target.status);\n\t\t\tconst ingestResult = await ingestNormalizedEnvelope(\n\t\t\t\tstore,\n\t\t\t\tsweeper,\n\t\t\t\tuntargetedPayload(result),\n\t\t\t\tc.req.header(\"x-codemem-boundary-flush\") === \"1\",\n\t\t\t);\n\t\t\treturn c.json({\n\t\t\t\tinserted: ingestResult.inserted,\n\t\t\t\tskipped: ingestResult.skipped,\n\t\t\t\treceived: ingestResult.received,\n\t\t\t});\n\t\t} catch (err) {\n\t\t\treturn boundedIngestErrorResponse(c, err);\n\t\t}\n\t});\n\n\t// POST /api/claude-hooks — ingest Claude Code hook events\n\tapp.post(\"/api/claude-hooks\", async (c) => {\n\t\tconst result = await parseJsonObjectBody(c, MAX_RAW_EVENTS_BODY_BYTES);\n\t\tif (result instanceof Response) return result;\n\t\tconst payload = result;\n\n\t\ttry {\n\t\t\tconst store = getStore();\n\t\t\tconst target = validateViewerTarget(store, payload, { requirePairedTargets: true });\n\t\t\tif (!target.ok) return c.json(target.body, target.status);\n\t\t\tlet transcriptOutcome: HookTranscriptOutcome | null = null;\n\t\t\tconst envelope = buildRawEventEnvelopeFromHook(untargetedPayload(payload), {\n\t\t\t\ttranscriptPolicy: { trust: \"restricted\", approvedRoots: [claudeTranscriptRoot()] },\n\t\t\t\tonTranscriptOutcome: (outcome) => {\n\t\t\t\t\ttranscriptOutcome = outcome;\n\t\t\t\t\ttranscriptDiagnostics.record(\"claude\", outcome);\n\t\t\t\t},\n\t\t\t});\n\t\t\tif (envelope === null) {\n\t\t\t\treturn c.json(transcriptSkipResponse(transcriptOutcome));\n\t\t\t}\n\t\t\tconst ingestResult = await ingestNormalizedEnvelope(\n\t\t\t\tstore,\n\t\t\t\tsweeper,\n\t\t\t\tenvelope,\n\t\t\t\tc.req.header(\"x-codemem-boundary-flush\") === \"1\",\n\t\t\t);\n\t\t\treturn c.json({ inserted: ingestResult.inserted, skipped: ingestResult.skipped });\n\t\t} catch (err) {\n\t\t\treturn boundedIngestErrorResponse(c, err);\n\t\t}\n\t});\n\n\t// POST /api/codex-hooks — ingest Codex hook events\n\tapp.post(\"/api/codex-hooks\", async (c) => {\n\t\tconst result = await parseJsonObjectBody(c, MAX_RAW_EVENTS_BODY_BYTES);\n\t\tif (result instanceof Response) return result;\n\t\tconst payload = result;\n\n\t\ttry {\n\t\t\tconst store = getStore();\n\t\t\tconst target = validateViewerTarget(store, payload, { requirePairedTargets: true });\n\t\t\tif (!target.ok) return c.json(target.body, target.status);\n\t\t\tlet transcriptOutcome: HookTranscriptOutcome | null = null;\n\t\t\tconst envelope = buildRawEventEnvelopeFromCodexHook(untargetedPayload(payload), {\n\t\t\t\ttranscriptPolicy: { trust: \"restricted\", approvedRoots: [codexTranscriptRoot()] },\n\t\t\t\tonTranscriptOutcome: (outcome) => {\n\t\t\t\t\ttranscriptOutcome = outcome;\n\t\t\t\t\ttranscriptDiagnostics.record(\"codex\", outcome);\n\t\t\t\t},\n\t\t\t});\n\t\t\tif (envelope === null) {\n\t\t\t\treturn c.json(transcriptSkipResponse(transcriptOutcome));\n\t\t\t}\n\t\t\tconst ingestResult = await ingestNormalizedEnvelope(store, sweeper, envelope);\n\t\t\treturn c.json({ inserted: ingestResult.inserted, skipped: ingestResult.skipped });\n\t\t} catch (err) {\n\t\t\treturn boundedIngestErrorResponse(c, err);\n\t\t}\n\t});\n\n\treturn app;\n}\n","/**\n * Stats routes — GET /api/stats, GET /api/usage.\n *\n * Ports Python's viewer_routes/stats.py.\n */\n\nimport {\n\tautomaticRecallHealth,\n\tbuildFilterClausesWithContext,\n\tlistMaintenanceJobs,\n\ttype MemoryStore,\n\tVERSION,\n} from \"@codemem/core\";\nimport { Hono } from \"hono\";\n\nfunction maintenanceJobSortKey(job: {\n\tstarted_at: string | null;\n\tupdated_at: string;\n\tkind: string;\n}): [string, string] {\n\treturn [job.started_at ?? job.updated_at, job.kind];\n}\n\nfunction sortActiveMaintenanceJobs<\n\tT extends { started_at: string | null; updated_at: string; kind: string },\n>(jobs: T[]): T[] {\n\treturn [...jobs].sort((a, b) => {\n\t\tconst [aTime, aKind] = maintenanceJobSortKey(a);\n\t\tconst [bTime, bKind] = maintenanceJobSortKey(b);\n\t\tif (aTime !== bTime) return aTime.localeCompare(bTime);\n\t\treturn aKind.localeCompare(bKind);\n\t});\n}\n\nconst MEMORY_ID_METADATA_KEYS = [\"pack_item_ids\", \"added_ids\", \"removed_ids\", \"retained_ids\"];\n\ntype UsageRow = {\n\tid: number;\n\tsession_id: number | null;\n\tevent: string;\n\ttokens_read: number;\n\ttokens_written: number;\n\ttokens_saved: number;\n\tcreated_at: string;\n\tmetadata_json: Record<string, unknown> | null;\n};\n\ntype UsageVisibility = {\n\tvisibleMemoryIds: Set<number>;\n\tvisibleSessionIds: Set<number>;\n};\n\nfunction toUsageRow(\n\trow: Record<string, unknown>,\n\tmetadata: Record<string, unknown> | null,\n): UsageRow {\n\treturn {\n\t\tid: Number(row.id ?? 0),\n\t\tsession_id: row.session_id == null ? null : Number(row.session_id),\n\t\tevent: String(row.event ?? \"pack\"),\n\t\ttokens_read: Number(row.tokens_read ?? 0),\n\t\ttokens_written: Number(row.tokens_written ?? 0),\n\t\ttokens_saved: Number(row.tokens_saved ?? 0),\n\t\tcreated_at: String(row.created_at ?? \"\"),\n\t\tmetadata_json: metadata,\n\t};\n}\n\nfunction metadataMemoryIds(value: unknown): number[] {\n\tif (!Array.isArray(value)) return [];\n\treturn value\n\t\t.map((item) => (typeof item === \"number\" ? item : Number(item)))\n\t\t.filter((item) => Number.isInteger(item) && item > 0);\n}\n\nfunction chunkNumbers(values: number[], chunkSize = 500): number[][] {\n\tconst chunks: number[][] = [];\n\tfor (let start = 0; start < values.length; start += chunkSize) {\n\t\tchunks.push(values.slice(start, start + chunkSize));\n\t}\n\treturn chunks;\n}\n\nfunction visibleMemoryIdSet(store: MemoryStore, memoryIds: Set<number>): Set<number> {\n\tif (memoryIds.size === 0) return new Set();\n\tconst filterResult = buildFilterClausesWithContext(null, {\n\t\tactorId: store.actorId,\n\t\tdeviceId: store.deviceId,\n\t\tenforceScopeVisibility: true,\n\t});\n\tconst visibleIds = new Set<number>();\n\tfor (const chunk of chunkNumbers([...memoryIds])) {\n\t\tconst placeholders = chunk.map(() => \"?\").join(\", \");\n\t\tconst clauses = [\n\t\t\t\"memory_items.active = 1\",\n\t\t\t`memory_items.id IN (${placeholders})`,\n\t\t\t...filterResult.clauses,\n\t\t];\n\t\tconst rows = store.db\n\t\t\t.prepare(`SELECT memory_items.id FROM memory_items WHERE ${clauses.join(\" AND \")}`)\n\t\t\t.all(...chunk, ...filterResult.params) as Array<{ id: number }>;\n\t\tfor (const row of rows) visibleIds.add(Number(row.id));\n\t}\n\treturn visibleIds;\n}\n\nfunction visibleSessionIdSet(store: MemoryStore, sessionIds: Set<number>): Set<number> {\n\tif (sessionIds.size === 0) return new Set();\n\tconst filterResult = buildFilterClausesWithContext(null, {\n\t\tactorId: store.actorId,\n\t\tdeviceId: store.deviceId,\n\t\tenforceScopeVisibility: true,\n\t});\n\tconst visibleIds = new Set<number>();\n\tfor (const chunk of chunkNumbers([...sessionIds])) {\n\t\tconst placeholders = chunk.map(() => \"?\").join(\", \");\n\t\tconst clauses = [\n\t\t\t\"memory_items.active = 1\",\n\t\t\t`memory_items.session_id IN (${placeholders})`,\n\t\t\t...filterResult.clauses,\n\t\t];\n\t\tconst rows = store.db\n\t\t\t.prepare(\n\t\t\t\t`SELECT DISTINCT memory_items.session_id AS session_id\n\t\t\t\t FROM memory_items\n\t\t\t\t WHERE ${clauses.join(\" AND \")}`,\n\t\t\t)\n\t\t\t.all(...chunk, ...filterResult.params) as Array<{ session_id: number | null }>;\n\t\tfor (const row of rows) {\n\t\t\tif (typeof row.session_id === \"number\") visibleIds.add(row.session_id);\n\t\t}\n\t}\n\treturn visibleIds;\n}\n\nfunction buildUsageVisibility(store: MemoryStore, rows: UsageRow[]): UsageVisibility {\n\tconst memoryIds = new Set<number>();\n\tconst sessionIds = new Set<number>();\n\tfor (const row of rows) {\n\t\tif (typeof row.session_id === \"number\") sessionIds.add(row.session_id);\n\t\tfor (const key of MEMORY_ID_METADATA_KEYS) {\n\t\t\tfor (const memoryId of metadataMemoryIds(row.metadata_json?.[key])) {\n\t\t\t\tmemoryIds.add(memoryId);\n\t\t\t}\n\t\t}\n\t}\n\treturn {\n\t\tvisibleMemoryIds: visibleMemoryIdSet(store, memoryIds),\n\t\tvisibleSessionIds: visibleSessionIdSet(store, sessionIds),\n\t};\n}\n\nfunction usageRowVisible(row: UsageRow, visibility: UsageVisibility): boolean {\n\tconst rowSessionVisible =\n\t\trow.session_id == null || visibility.visibleSessionIds.has(row.session_id);\n\tconst packItemIds = row.metadata_json?.pack_item_ids;\n\tif (Array.isArray(packItemIds)) {\n\t\tif (packItemIds.length === 0) {\n\t\t\treturn row.session_id != null && visibility.visibleSessionIds.has(row.session_id);\n\t\t}\n\t\treturn (\n\t\t\trowSessionVisible &&\n\t\t\tmetadataMemoryIds(packItemIds).some((memoryId) => visibility.visibleMemoryIds.has(memoryId))\n\t\t);\n\t}\n\treturn row.session_id != null && visibility.visibleSessionIds.has(row.session_id);\n}\n\nfunction sanitizePackUsageMetadata(\n\tmetadata: Record<string, unknown> | null,\n\tvisibility: UsageVisibility,\n): Record<string, unknown> | null {\n\tif (!metadata) return null;\n\tconst sanitized = { ...metadata };\n\tfor (const key of MEMORY_ID_METADATA_KEYS) {\n\t\tif (Array.isArray(sanitized[key])) {\n\t\t\tsanitized[key] = metadataMemoryIds(sanitized[key]).filter((memoryId) =>\n\t\t\t\tvisibility.visibleMemoryIds.has(memoryId),\n\t\t\t);\n\t\t}\n\t}\n\treturn sanitized;\n}\n\ntype UsageAggregateRow = {\n\tevent: string;\n\tcount: number;\n\ttokens_read: number;\n\ttokens_written: number;\n\ttokens_saved: number;\n};\n\n/**\n * Convert the neutral core aggregate rows into the wire shape for /api/usage\n * (ApiUsageEventSummary: total_tokens_* names), sorted by event name ASC to\n * match the route's historical ordering.\n */\nfunction mapAggregateEvents(rows: UsageAggregateRow[]): Record<string, unknown>[] {\n\treturn rows\n\t\t.map((row) => ({\n\t\t\tevent: row.event,\n\t\t\ttotal_tokens_read: row.tokens_read,\n\t\t\ttotal_tokens_written: row.tokens_written,\n\t\t\ttotal_tokens_saved: row.tokens_saved,\n\t\t\tcount: row.count,\n\t\t}))\n\t\t.sort((a, b) => a.event.localeCompare(b.event));\n}\n\n/**\n * Sum the neutral core aggregate rows into the ApiUsageTotals wire shape.\n */\nfunction totalsFromAggregate(rows: UsageAggregateRow[]): {\n\ttokens_read: number;\n\ttokens_written: number;\n\ttokens_saved: number;\n\tcount: number;\n} {\n\treturn rows.reduce(\n\t\t(acc, row) => ({\n\t\t\ttokens_read: acc.tokens_read + row.tokens_read,\n\t\t\ttokens_written: acc.tokens_written + row.tokens_written,\n\t\t\ttokens_saved: acc.tokens_saved + row.tokens_saved,\n\t\t\tcount: acc.count + row.count,\n\t\t}),\n\t\t{ tokens_read: 0, tokens_written: 0, tokens_saved: 0, count: 0 },\n\t);\n}\n\ntype UsagePayload = Record<string, unknown>;\n\ninterface UsageCacheEntry {\n\tpayload: UsagePayload;\n\texpiresAtMs: number;\n}\n\n/**\n * Short-lived cache for the computed /api/usage payload.\n *\n * The health dot polls /api/usage on every 5s refresh regardless of the\n * active tab. The token/event totals come from indexed SQL aggregates and the\n * recent-pack window runs scope-visibility resolution over its bounded set, so\n * each miss is cheap — but the totals are cumulative dashboard figures where a\n * few seconds of staleness is acceptable, so caching still collapses the\n * repeated recompute on the polling loop. Keyed by db path + scope identity +\n * project filter so distinct stores/projects never share an entry.\n */\nconst usagePayloadCache = new Map<string, UsageCacheEntry>();\nconst USAGE_PAYLOAD_CACHE_MS = 10_000;\n\n/**\n * Hard cap on cached usage payloads. The cache key folds in the arbitrary\n * `?project=` filter and a scope-visibility fingerprint that becomes\n * per-request-unique on the error/bypass path, so without a bound the map\n * would grow without limit in a long-running viewer. The cap is far above the\n * realistic working set (a handful of projects times one or two scope\n * generations), so legitimate hits are never evicted under normal load.\n */\nconst USAGE_PAYLOAD_CACHE_MAX_ENTRIES = 256;\n\n/**\n * Sweep expired entries and enforce the size cap before inserting a new one.\n *\n * Mirrors the lazy-sweep approach in request-rate-limit.ts: eviction is\n * piggybacked on writes rather than run on a timer, so an idle viewer does no\n * background work. Expired entries (those past `expiresAtMs`) are always\n * dropped; if the map is still at capacity afterward — e.g. a burst of\n * distinct, still-live bypass keys — the oldest-expiring entries are evicted\n * to make room. This never changes hit/miss semantics for a live entry: the\n * caller still re-checks `expiresAtMs` on read, and only already-expired or\n * over-cap entries are removed here.\n */\nfunction sweepUsagePayloadCache(cache: Map<string, UsageCacheEntry>, nowMs: number): void {\n\tfor (const [key, entry] of cache) {\n\t\tif (entry.expiresAtMs <= nowMs) cache.delete(key);\n\t}\n\tif (cache.size < USAGE_PAYLOAD_CACHE_MAX_ENTRIES) return;\n\t// Leave room for the entry about to be inserted by evicting down to one\n\t// below the cap. Drop the soonest-to-expire entries first.\n\tconst byExpiry = [...cache.entries()].sort((a, b) => a[1].expiresAtMs - b[1].expiresAtMs);\n\tlet overflow = cache.size - USAGE_PAYLOAD_CACHE_MAX_ENTRIES + 1;\n\tfor (const [key] of byExpiry) {\n\t\tif (overflow <= 0) break;\n\t\tcache.delete(key);\n\t\toverflow -= 1;\n\t}\n}\n\n/**\n * Cheap fingerprint of the state that drives scope visibility\n * (`scope_memberships` / `replication_scopes`). Folding this into the usage\n * cache key ensures a membership/scope status change — e.g. a revocation —\n * invalidates any cached payload immediately instead of letting a device keep\n * reading a scope it can no longer see for up to the TTL. These tables are\n * small, so the aggregate is negligible next to the usage_events scan the\n * cache exists to avoid. Fails safe: any error forces a unique value so the\n * request bypasses the cache and recomputes visibility from scratch.\n */\nfunction scopeVisibilityGeneration(store: MemoryStore): string {\n\ttry {\n\t\tconst row = store.db\n\t\t\t.prepare(\n\t\t\t\t`SELECT\n\t\t\t\t\t(SELECT COUNT(*) FROM scope_memberships) AS m_count,\n\t\t\t\t\t(SELECT COUNT(*) FROM scope_memberships WHERE status = 'active') AS m_active,\n\t\t\t\t\t(SELECT COALESCE(MAX(updated_at), '') FROM scope_memberships) AS m_updated,\n\t\t\t\t\t(SELECT COALESCE(MAX(membership_epoch), 0) FROM scope_memberships) AS m_epoch,\n\t\t\t\t\t(SELECT COUNT(*) FROM replication_scopes) AS s_count,\n\t\t\t\t\t(SELECT COUNT(*) FROM replication_scopes WHERE status = 'active') AS s_active,\n\t\t\t\t\t(SELECT COALESCE(MAX(updated_at), '') FROM replication_scopes) AS s_updated`,\n\t\t\t)\n\t\t\t.get() as Record<string, unknown> | undefined;\n\t\tif (!row) return \"no-scope-state\";\n\t\treturn [\n\t\t\trow.m_count,\n\t\t\trow.m_active,\n\t\t\trow.m_updated,\n\t\t\trow.m_epoch,\n\t\t\trow.s_count,\n\t\t\trow.s_active,\n\t\t\trow.s_updated,\n\t\t].join(\":\");\n\t} catch {\n\t\t// Fail safe: bypass the cache rather than risk serving a payload\n\t\t// computed under stale visibility rules.\n\t\treturn `bypass-${Date.now()}-${Math.random()}`;\n\t}\n}\n\nfunction usageCacheKey(store: MemoryStore, projectFilter: string | null): string {\n\tconst visibilityGeneration = scopeVisibilityGeneration(store);\n\treturn `${store.dbPath}|${store.actorId}|${store.deviceId}|${projectFilter ?? \"\"}|${visibilityGeneration}`;\n}\n\n/**\n * Create stats routes. The store factory is called per-request to get a\n * fresh connection (matching the Python viewer pattern).\n */\nexport function statsRoutes(getStore: () => MemoryStore) {\n\tconst app = new Hono();\n\n\tconst parseMetadataJson = (value: unknown): Record<string, unknown> | null => {\n\t\tif (typeof value !== \"string\" || !value.trim()) return null;\n\t\ttry {\n\t\t\treturn JSON.parse(value) as Record<string, unknown>;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t};\n\n\t// Keep completed jobs visible in /api/stats for a short window after\n\t// finished_at so the health UI has a chance to render success confirmation\n\t// for fast-completing backfills (often <1s). Failed jobs stay indefinitely.\n\tconst RECENTLY_COMPLETED_WINDOW_MS = 120_000;\n\n\tapp.get(\"/api/stats\", (c) => {\n\t\tconst store = getStore();\n\t\tconst jobs = listMaintenanceJobs(store.db);\n\t\tconst now = Date.now();\n\t\tconst surfacedJobs = sortActiveMaintenanceJobs(\n\t\t\tjobs.filter((job) => {\n\t\t\t\tif (job.status === \"pending\" || job.status === \"running\" || job.status === \"failed\") {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tif (job.status === \"completed\" && job.finished_at) {\n\t\t\t\t\tconst finished = Date.parse(job.finished_at);\n\t\t\t\t\tif (Number.isFinite(finished) && now - finished <= RECENTLY_COMPLETED_WINDOW_MS) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}),\n\t\t).map((job) => ({\n\t\t\tkind: job.kind,\n\t\t\ttitle: job.title,\n\t\t\tstatus: job.status,\n\t\t\tmessage: job.message,\n\t\t\tprogress: job.progress,\n\t\t\tfinished_at: job.finished_at,\n\t\t\terror: job.error,\n\t\t}));\n\t\treturn c.json({\n\t\t\t...healthStats(store),\n\t\t\tviewer_pid: process.pid,\n\t\t\tmaintenance_jobs: surfacedJobs,\n\t\t});\n\t});\n\n\tapp.get(\"/api/runtime\", (c) => {\n\t\treturn c.json({\n\t\t\tversion: VERSION,\n\t\t});\n\t});\n\n\tapp.get(\"/api/usage\", (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tconst projectFilter = c.req.query(\"project\") || null;\n\t\t\tconst cacheKey = usageCacheKey(store, projectFilter);\n\t\t\tconst nowMs = Date.now();\n\t\t\tconst cached = usagePayloadCache.get(cacheKey);\n\t\t\tif (cached && nowMs < cached.expiresAtMs) {\n\t\t\t\treturn c.json(cached.payload);\n\t\t\t}\n\n\t\t\t// Token/event aggregates are unfiltered SQL GROUP BYs (matching\n\t\t\t// store.stats()), so they never load the full usage_events table\n\t\t\t// into JS. Only the small surfaced recent_packs window below keeps\n\t\t\t// per-row scope visibility + metadata sanitization.\n\t\t\tconst globalAggregate = store.usageAggregate();\n\t\t\tconst eventsGlobal = mapAggregateEvents(globalAggregate);\n\t\t\tconst totalsGlobal = totalsFromAggregate(globalAggregate);\n\t\t\tconst filteredAggregate = projectFilter ? store.usageAggregate(projectFilter) : null;\n\t\t\tconst eventsFiltered = filteredAggregate ? mapAggregateEvents(filteredAggregate) : null;\n\t\t\tconst totalsFiltered = filteredAggregate ? totalsFromAggregate(filteredAggregate) : null;\n\n\t\t\t// recent_packs candidate window. Over-fetch the most-recent pack\n\t\t\t// events (20x the 10 we surface) so that, in the common case where a\n\t\t\t// device sees most of its own packs, 10 *visible* packs survive the\n\t\t\t// scope filter below without ever scanning the whole table.\n\t\t\t// Tradeoff vs. the old full-scan-then-slice: if MORE than\n\t\t\t// (LIMIT - 10) of the newest packs are non-visible, fewer than 10\n\t\t\t// surface, and a visible pack older than the newest 200 is not\n\t\t\t// shown at all. That only bites a heavily-shared DB whose recent\n\t\t\t// activity is dominated by other scopes; for an activity widget the\n\t\t\t// bounded recompute on a 5s poll is the right call.\n\t\t\tconst RECENT_PACK_SCAN_LIMIT = 200;\n\t\t\tconst loadRecentPackWindow = (project?: string | null): UsageRow[] => {\n\t\t\t\tconst rows = project\n\t\t\t\t\t? (store.db\n\t\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t\t`SELECT usage_events.id, usage_events.session_id, usage_events.event,\n\t\t\t\t\t\t\t\t\tusage_events.tokens_read, usage_events.tokens_written, usage_events.tokens_saved,\n\t\t\t\t\t\t\t\t\tusage_events.created_at, usage_events.metadata_json\n\t\t\t\t\t\t\t\t FROM usage_events\n\t\t\t\t\t\t\t\t JOIN sessions ON sessions.id = usage_events.session_id\n\t\t\t\t\t\t\t\t WHERE sessions.project = ? AND usage_events.event = 'pack'\n\t\t\t\t\t\t\t\t ORDER BY usage_events.created_at DESC\n\t\t\t\t\t\t\t\t LIMIT ?`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.all(project, RECENT_PACK_SCAN_LIMIT) as Record<string, unknown>[])\n\t\t\t\t\t: (store.db\n\t\t\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\t\t`SELECT id, session_id, event, tokens_read, tokens_written, tokens_saved,\n\t\t\t\t\t\t\t\t\tcreated_at, metadata_json\n\t\t\t\t\t\t\t\t FROM usage_events\n\t\t\t\t\t\t\t\t WHERE event = 'pack'\n\t\t\t\t\t\t\t\t ORDER BY created_at DESC\n\t\t\t\t\t\t\t\t LIMIT ?`,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.all(RECENT_PACK_SCAN_LIMIT) as Record<string, unknown>[]);\n\t\t\t\treturn rows.map((row) => toUsageRow(row, parseMetadataJson(row.metadata_json)));\n\t\t\t};\n\t\t\tconst recentWindow = loadRecentPackWindow(projectFilter);\n\t\t\tconst recentVisibility = buildUsageVisibility(store, recentWindow);\n\t\t\tconst recentPacks = recentWindow\n\t\t\t\t.filter((row) => usageRowVisible(row, recentVisibility))\n\t\t\t\t.slice(0, 10)\n\t\t\t\t.map((row) => ({\n\t\t\t\t\t...row,\n\t\t\t\t\tmetadata_json: sanitizePackUsageMetadata(row.metadata_json, recentVisibility),\n\t\t\t\t}));\n\n\t\t\tconst payload: UsagePayload = {\n\t\t\t\tproject: projectFilter,\n\t\t\t\tevents: projectFilter ? eventsFiltered : eventsGlobal,\n\t\t\t\ttotals: projectFilter ? totalsFiltered : totalsGlobal,\n\t\t\t\tevents_global: eventsGlobal,\n\t\t\t\ttotals_global: totalsGlobal,\n\t\t\t\tevents_filtered: eventsFiltered,\n\t\t\t\ttotals_filtered: totalsFiltered,\n\t\t\t\trecent_packs: recentPacks,\n\t\t\t};\n\t\t\tconst setAtMs = Date.now();\n\t\t\tsweepUsagePayloadCache(usagePayloadCache, setAtMs);\n\t\t\tusagePayloadCache.set(cacheKey, {\n\t\t\t\tpayload,\n\t\t\t\texpiresAtMs: setAtMs + USAGE_PAYLOAD_CACHE_MS,\n\t\t\t});\n\t\t\treturn c.json(payload);\n\t\t}\n\t});\n\n\treturn app;\n}\n\nfunction healthStats(store: MemoryStore) {\n\treturn {\n\t\t...store.stats(),\n\t\tautomatic_recall: automaticRecallHealth(store.db, {\n\t\t\tactorId: store.actorId,\n\t\t\tdeviceId: store.deviceId,\n\t\t}),\n\t};\n}\n\n/**\n * Internals exposed for unit tests of the usage-cache eviction. Not part of the\n * route's public surface; consumers should go through the HTTP handlers.\n */\nexport const __usageCacheTestHooks = {\n\tcache: usagePayloadCache,\n\tsweep: sweepUsagePayloadCache,\n\tmaxEntries: USAGE_PAYLOAD_CACHE_MAX_ENTRIES,\n\tttlMs: USAGE_PAYLOAD_CACHE_MS,\n};\n","import type {\n\tLegacyTeamSetupActivationErrorCode,\n\tLegacyTeamSetupDraftView,\n\tLegacyTeamSetupErrorReason,\n} from \"@codemem/core\";\n\nexport interface LegacyTeamSetupCandidateSummaryV1 {\n\tcandidateRef: string;\n\tdisplayName: string;\n\tstatus: \"needs_setup\" | \"in_progress\" | \"stale\" | \"ready\";\n\tdeviceCount: number;\n\tprojectCount: number;\n\tunresolvedDeviceCount: number;\n\tunresolvedProjectCount: number;\n}\n\nexport type LegacyTeamSetupPendingCandidateSummaryV1 = Omit<\n\tLegacyTeamSetupCandidateSummaryV1,\n\t\"status\"\n> & {\n\tstatus: Exclude<LegacyTeamSetupCandidateSummaryV1[\"status\"], \"ready\">;\n};\n\nexport interface LegacyTeamSetupSummaryResponseV1 {\n\tversion: 1;\n\tcandidates: LegacyTeamSetupPendingCandidateSummaryV1[];\n}\n\nexport type LegacyTeamSetupActionBlockedReasonV1 =\n\t| \"setup_incomplete\"\n\t| \"setup_unavailable\"\n\t| \"setup_completed\"\n\t| \"device_inactive\"\n\t| \"device_active\"\n\t| \"assignment_evidence_inactive\"\n\t| \"assignment_required\"\n\t| \"assignment_unavailable\"\n\t| \"decision_unresolved\"\n\t| \"mapping_unavailable\"\n\t| \"automatic_mapping\";\n\nexport type LegacyTeamSetupActionGateV1 =\n\t| { enabled: true; blockedReason: null }\n\t| { enabled: false; blockedReason: LegacyTeamSetupActionBlockedReasonV1 };\n\nexport type LegacyTeamSetupUnavailableReasonV1 = Exclude<\n\tLegacyTeamSetupActivationErrorCode,\n\t\"team_setup_projection_changed\"\n>;\n\nexport interface LegacyTeamSetupDeviceV1 {\n\tdeviceRef: string;\n\tdisplayName: string;\n\tenabled: boolean;\n\texistingIdentityRef: string | null;\n\tsuggestedIdentityRef: string | null;\n\tverifiedEvidenceKind: \"active_assignment\" | null;\n\tdecision: \"unresolved\" | \"included\" | \"excluded\" | \"removed\";\n\ttargetIdentityRef: string | null;\n\texpectation:\n\t\t| { kind: \"absent\" }\n\t\t| { kind: \"existing\"; assignmentVersion: number; identityRef: string };\n\tactions: {\n\t\tassignIdentity: LegacyTeamSetupActionGateV1;\n\t\tinclude: LegacyTeamSetupActionGateV1;\n\t\texclude: LegacyTeamSetupActionGateV1;\n\t\tremove: LegacyTeamSetupActionGateV1;\n\t\tclearDecision: LegacyTeamSetupActionGateV1;\n\t};\n}\n\nexport interface LegacyTeamSetupProjectV1 {\n\tprojectRef: string;\n\tdisplayName: string;\n\tresolution: \"unresolved\" | \"deterministic\" | \"explicit\";\n\tcanonicalProjectRef: string | null;\n\tresolvedProjectRef: string | null;\n\tmappingChoices: Array<{ resolvedProjectRef: string; displayName: string }>;\n\tactions: { map: LegacyTeamSetupActionGateV1 };\n}\n\nexport interface LegacyTeamSetupIdentityChoiceV1 {\n\tidentityRef: string;\n\tdisplayName: string;\n}\n\nexport interface LegacyTeamSetupViewerAccessDeltaV1 {\n\tteamChanges: Array<{\n\t\tteamRef: string;\n\t\tteamDisplayName: string;\n\t\tchange: \"add\" | \"update\" | \"remove\";\n\t\tfromDeviceEligibilityMode: \"person_all_devices\" | \"reviewed_allowlist\" | null;\n\t\ttoDeviceEligibilityMode: \"reviewed_allowlist\";\n\t}>;\n\tmembershipChanges: Array<{\n\t\tteamRef: string;\n\t\tteamDisplayName: string;\n\t\tidentityRef: string;\n\t\tidentityDisplayName: string;\n\t\tchange: \"add\" | \"update\" | \"remove\";\n\t}>;\n\tprojectChanges: Array<{\n\t\tprojectRef: string;\n\t\tprojectDisplayName: string;\n\t\tfromCanonicalProjectRef: string | null;\n\t\tfromResolvedProjectRef: string | null;\n\t\tfromResolvedProjectDisplayName: string | null;\n\t\ttoCanonicalProjectRef: string | null;\n\t\ttoResolvedProjectRef: string | null;\n\t\ttoResolvedProjectDisplayName: string | null;\n\t\tchange: \"add\" | \"update\" | \"remove\";\n\t}>;\n\trecipientChanges: Array<{\n\t\tcanonicalProjectRef: string;\n\t\tcanonicalProjectDisplayName: string;\n\t\tcanonicalProjectKind: \"project\" | \"legacy_default_sharing\";\n\t\trecipientKind: \"team\";\n\t\trecipientRef: string;\n\t\trecipientDisplayName: string;\n\t\tchange: \"add\" | \"update\" | \"remove\";\n\t}>;\n\tdeviceAccessChanges: Array<{\n\t\tcanonicalProjectRef: string;\n\t\tcanonicalProjectDisplayName: string;\n\t\tcanonicalProjectKind: \"project\" | \"legacy_default_sharing\";\n\t\tdeviceRef: string;\n\t\tdeviceDisplayName: string;\n\t\tchange: \"add\" | \"remove\";\n\t}>;\n}\n\ninterface LegacyTeamSetupViewBaseV1 {\n\tversion: 1;\n\tcandidate: LegacyTeamSetupCandidateSummaryV1;\n\tattemptId: string;\n\tunresolvedDeviceCount: number;\n\tunresolvedProjectCount: number;\n\tdevices: LegacyTeamSetupDeviceV1[];\n\tprojects: LegacyTeamSetupProjectV1[];\n\tidentityChoices: LegacyTeamSetupIdentityChoiceV1[];\n}\n\nexport type LegacyTeamSetupViewV1 =\n\t| (LegacyTeamSetupViewBaseV1 & {\n\t\t\tstate: \"reviewing\";\n\t\t\tactions: {\n\t\t\t\trefresh: { enabled: true; blockedReason: null };\n\t\t\t\tfinish: { enabled: false; blockedReason: \"setup_incomplete\" };\n\t\t\t};\n\t })\n\t| (LegacyTeamSetupViewBaseV1 & {\n\t\t\tstate: \"ready_to_finish\";\n\t\t\tactions: {\n\t\t\t\trefresh: { enabled: true; blockedReason: null };\n\t\t\t\tfinish: { enabled: true; blockedReason: null };\n\t\t\t};\n\t\t\tfinishDigest: string;\n\t\t\taccessDeltaDigest: string;\n\t\t\tviewerAccessDeltaDigest: string;\n\t\t\taccessDelta: LegacyTeamSetupViewerAccessDeltaV1;\n\t })\n\t| (LegacyTeamSetupViewBaseV1 & {\n\t\t\tstate: \"unavailable\";\n\t\t\tunavailableReason: LegacyTeamSetupUnavailableReasonV1;\n\t\t\tactions: {\n\t\t\t\trefresh: { enabled: true; blockedReason: null };\n\t\t\t\tfinish: { enabled: false; blockedReason: \"setup_unavailable\" };\n\t\t\t};\n\t })\n\t| (LegacyTeamSetupViewBaseV1 & {\n\t\t\tstate: \"completed\";\n\t\t\tactions: {\n\t\t\t\trefresh: { enabled: false; blockedReason: \"setup_completed\" };\n\t\t\t\tfinish: { enabled: false; blockedReason: \"setup_completed\" };\n\t\t\t};\n\t });\n\nexport type LegacyTeamSetupDetailResponseV1 = LegacyTeamSetupViewV1;\nexport type LegacyTeamSetupMutationResponseV1 = LegacyTeamSetupViewV1;\n\nexport interface LegacyTeamSetupErrorResponseV1 {\n\terror: LegacyTeamSetupActivationErrorCode;\n\treason?: LegacyTeamSetupErrorReason;\n}\n\nexport interface LegacyTeamSetupFinishResponseV1 {\n\tversion: 1;\n\tstatus: \"completed\";\n\tteamRef: string;\n\tattemptId: string;\n\taccessDeltaDigest: string;\n\tcompletedAt: string;\n}\n\ntype DeviceData = Omit<LegacyTeamSetupDeviceV1, \"actions\">;\ntype ProjectData = Omit<LegacyTeamSetupProjectV1, \"actions\">;\n\ninterface ProjectViewInput {\n\tversion: 1;\n\tcandidate: LegacyTeamSetupCandidateSummaryV1;\n\tdraftState: LegacyTeamSetupDraftView[\"state\"];\n\tattemptId: string;\n\tunresolvedDeviceCount: number;\n\tunresolvedProjectCount: number;\n\tdevices: DeviceData[];\n\tprojects: ProjectData[];\n\tidentityChoices: LegacyTeamSetupIdentityChoiceV1[];\n\tunavailableReason: LegacyTeamSetupUnavailableReasonV1 | null;\n\tpreview: null | {\n\t\tfinishDigest: string;\n\t\taccessDeltaDigest: string;\n\t\tviewerAccessDeltaDigest: string;\n\t\taccessDelta: LegacyTeamSetupViewerAccessDeltaV1;\n\t};\n}\n\nconst enabled = { enabled: true, blockedReason: null } as const;\n\nfunction blocked<const Reason extends LegacyTeamSetupActionBlockedReasonV1>(\n\treason: Reason,\n): { enabled: false; blockedReason: Reason } {\n\treturn { enabled: false, blockedReason: reason };\n}\n\nfunction deviceActions(\n\tdevice: DeviceData,\n\tidentityChoices: LegacyTeamSetupIdentityChoiceV1[],\n\tstate: LegacyTeamSetupViewV1[\"state\"],\n): LegacyTeamSetupDeviceV1[\"actions\"] {\n\tif (state === \"completed\") return disabledDeviceActions(\"setup_completed\");\n\tif (state === \"unavailable\") return disabledDeviceActions(\"setup_unavailable\");\n\tconst assignmentEvidenceInactive =\n\t\tdevice.expectation.kind === \"existing\" && device.verifiedEvidenceKind !== \"active_assignment\";\n\tconst targetAvailable = identityChoices.some(\n\t\t(identity) => identity.identityRef === device.targetIdentityRef,\n\t);\n\treturn {\n\t\tassignIdentity: !device.enabled\n\t\t\t? blocked(\"device_inactive\")\n\t\t\t: assignmentEvidenceInactive\n\t\t\t\t? blocked(\"assignment_evidence_inactive\")\n\t\t\t\t: identityChoices.length === 0\n\t\t\t\t\t? blocked(\"assignment_unavailable\")\n\t\t\t\t\t: enabled,\n\t\tinclude: !device.enabled\n\t\t\t? blocked(\"device_inactive\")\n\t\t\t: assignmentEvidenceInactive\n\t\t\t\t? blocked(\"assignment_evidence_inactive\")\n\t\t\t\t: !device.targetIdentityRef\n\t\t\t\t\t? blocked(\"assignment_required\")\n\t\t\t\t\t: !targetAvailable\n\t\t\t\t\t\t? blocked(\"assignment_unavailable\")\n\t\t\t\t\t\t: enabled,\n\t\texclude: device.enabled ? enabled : blocked(\"device_inactive\"),\n\t\tremove: device.enabled ? blocked(\"device_active\") : enabled,\n\t\tclearDecision: device.decision === \"unresolved\" ? blocked(\"decision_unresolved\") : enabled,\n\t};\n}\n\nfunction disabledDeviceActions(\n\treason: \"setup_completed\" | \"setup_unavailable\",\n): LegacyTeamSetupDeviceV1[\"actions\"] {\n\tconst gate = blocked(reason);\n\treturn {\n\t\tassignIdentity: gate,\n\t\tinclude: gate,\n\t\texclude: gate,\n\t\tremove: gate,\n\t\tclearDecision: gate,\n\t};\n}\n\nfunction projectActions(\n\tproject: ProjectData,\n\tstate: LegacyTeamSetupViewV1[\"state\"],\n): LegacyTeamSetupProjectV1[\"actions\"] {\n\tif (state === \"completed\") return { map: blocked(\"setup_completed\") };\n\tif (state === \"unavailable\") return { map: blocked(\"setup_unavailable\") };\n\treturn {\n\t\tmap:\n\t\t\tproject.resolution === \"deterministic\"\n\t\t\t\t? blocked(\"automatic_mapping\")\n\t\t\t\t: project.mappingChoices.length === 0\n\t\t\t\t\t? blocked(\"mapping_unavailable\")\n\t\t\t\t\t: enabled,\n\t};\n}\n\nfunction viewState(input: ProjectViewInput): LegacyTeamSetupViewV1[\"state\"] {\n\tif (input.draftState === \"completed\") return \"completed\";\n\tif (input.draftState === \"stale\" || input.unavailableReason) return \"unavailable\";\n\tif (input.preview) return \"ready_to_finish\";\n\treturn \"reviewing\";\n}\n\nexport function projectLegacyTeamSetupView(input: ProjectViewInput): LegacyTeamSetupViewV1 {\n\tconst state = viewState(input);\n\tconst base = {\n\t\tversion: input.version,\n\t\tcandidate: input.candidate,\n\t\tattemptId: input.attemptId,\n\t\tunresolvedDeviceCount: input.unresolvedDeviceCount,\n\t\tunresolvedProjectCount: input.unresolvedProjectCount,\n\t\tdevices: input.devices.map((device) => ({\n\t\t\t...device,\n\t\t\tactions: deviceActions(device, input.identityChoices, state),\n\t\t})),\n\t\tprojects: input.projects.map((project) => ({\n\t\t\t...project,\n\t\t\tactions: projectActions(project, state),\n\t\t})),\n\t\tidentityChoices: input.identityChoices,\n\t};\n\tif (state === \"completed\") {\n\t\treturn {\n\t\t\t...base,\n\t\t\tstate,\n\t\t\tactions: {\n\t\t\t\trefresh: blocked(\"setup_completed\"),\n\t\t\t\tfinish: blocked(\"setup_completed\"),\n\t\t\t},\n\t\t};\n\t}\n\tif (state === \"unavailable\") {\n\t\treturn {\n\t\t\t...base,\n\t\t\tstate,\n\t\t\tunavailableReason: input.unavailableReason ?? \"team_setup_confirmation_stale\",\n\t\t\tactions: { refresh: enabled, finish: blocked(\"setup_unavailable\") },\n\t\t};\n\t}\n\tif (state === \"ready_to_finish\" && input.preview) {\n\t\treturn {\n\t\t\t...base,\n\t\t\tstate,\n\t\t\tactions: { refresh: enabled, finish: enabled },\n\t\t\t...input.preview,\n\t\t};\n\t}\n\treturn {\n\t\t...base,\n\t\tstate: \"reviewing\",\n\t\tactions: { refresh: enabled, finish: blocked(\"setup_incomplete\") },\n\t};\n}\n","import type {\n\tCoordinatorLegacyTeamCompletionManifestV1,\n\tCoordinatorLegacyTeamCompletionRecord,\n\tLegacyTeamCandidateView,\n\tLegacyTeamConfiguredGroupSnapshot,\n\tLegacyTeamSetupAccessDeltaV1,\n\tLegacyTeamSetupActivationErrorCode,\n\tLegacyTeamSetupActivationResultV1,\n\tLegacyTeamSetupDraftView,\n\tLegacyTeamSetupErrorReason,\n\tMemoryStore,\n} from \"@codemem/core\";\nimport {\n\tapplyLegacyTeamSetupCompletionManifest,\n\tapplyLegacyTeamSetupCompletionManifestAndReturnActivation,\n\tareLegacyTeamSetupCompletionPolicyFactsAdditivelyCompatible,\n\tbuildBaseUrl,\n\tcanonicalCoordinatorLegacyTeamCompletionManifestJson,\n\tclaimRecipientPolicyActorMutations,\n\tclaimRecipientPolicyPublicationMutation,\n\tclearLegacyTeamSetupDeviceDecision,\n\tcontainLegacyTeamSetupCompletionConflict,\n\tcoordinatorCreateLegacyTeamCompletionAction,\n\tcoordinatorGetLegacyTeamCompletionAction,\n\tcoordinatorListDevicesAction,\n\tcoordinatorListGroupsAction,\n\tcoordinatorListLegacyTeamCompletionsAction,\n\tderiveLegacyTeamSetupCompletionManifest,\n\tdeterministicPolicyTeamId,\n\tdiscoverLegacyTeamCandidates,\n\tfingerprintPublicKey,\n\tgetLegacyTeamSetupDraft,\n\tinspectFreshLegacyTeamSetupActivation,\n\tinspectLegacyTeamSetupActivation,\n\tisLegacyTeamCandidateSelectable,\n\tisLegacyTeamSetupProjectMappingIdentity,\n\tLegacyTeamSetupAdditiveConvergenceError,\n\tLegacyTeamSetupRosterCapacityError,\n\tlegacyTeamCandidateId,\n\tlegacyTeamCandidateProjectInventory,\n\tlegacyTeamCanonicalProjectRef,\n\tlegacyTeamDeviceRef,\n\tlegacyTeamResolvedProjectRef,\n\tlegacyTeamSetupApiErrorCode,\n\tlistProjectScopeCandidates,\n\tpreviewLegacyTeamSetupActivation,\n\tRemoteCoordinatorRequestError,\n\treadCoordinatorSyncConfig,\n\trecipientPolicyDigest,\n\treconstructLegacyTeamSetupCompletionManifest,\n\trefreshLegacyTeamCandidate,\n\treplayLegacyTeamSetupActivation,\n\trequireLegacyTeamSetupAccessDeltaWithinLimit,\n\tserializeRecipientPolicyCoordinatorGroupMutation,\n\tserializeRecipientPolicyPublicationMutation,\n\tserializeRecipientPolicyTeamMutation,\n\tsetLegacyTeamSetupDeviceAssignment,\n\tsetLegacyTeamSetupDeviceDecision,\n\tsetLegacyTeamSetupProjectMapping,\n\tvalidateLegacyTeamSetupCompletionManifest,\n\tvalidateLegacyTeamSetupCompletionManifestBinding,\n} from \"@codemem/core\";\nimport { type Context, Hono } from \"hono\";\nimport {\n\ttype LegacyTeamSetupCandidateSummaryV1,\n\ttype LegacyTeamSetupDetailResponseV1,\n\ttype LegacyTeamSetupDeviceV1,\n\ttype LegacyTeamSetupFinishResponseV1,\n\ttype LegacyTeamSetupIdentityChoiceV1,\n\ttype LegacyTeamSetupPendingCandidateSummaryV1,\n\ttype LegacyTeamSetupProjectV1,\n\ttype LegacyTeamSetupSummaryResponseV1,\n\ttype LegacyTeamSetupUnavailableReasonV1,\n\ttype LegacyTeamSetupViewerAccessDeltaV1,\n\tprojectLegacyTeamSetupView,\n} from \"./team-setup-view.js\";\n\nexport type {\n\tLegacyTeamSetupActionBlockedReasonV1,\n\tLegacyTeamSetupActionGateV1,\n\tLegacyTeamSetupCandidateSummaryV1,\n\tLegacyTeamSetupDetailResponseV1,\n\tLegacyTeamSetupDeviceV1,\n\tLegacyTeamSetupErrorResponseV1,\n\tLegacyTeamSetupFinishResponseV1,\n\tLegacyTeamSetupIdentityChoiceV1,\n\tLegacyTeamSetupMutationResponseV1,\n\tLegacyTeamSetupPendingCandidateSummaryV1,\n\tLegacyTeamSetupProjectV1,\n\tLegacyTeamSetupSummaryResponseV1,\n\tLegacyTeamSetupUnavailableReasonV1,\n\tLegacyTeamSetupViewerAccessDeltaV1,\n\tLegacyTeamSetupViewV1,\n} from \"./team-setup-view.js\";\n\nconst TEAM_SETUP_VERSION = 1 as const;\nconst MAX_CONFIGURED_GROUPS = 25;\nconst MAX_SCOPE_EVIDENCE_COORDINATORS = 100;\nconst MAX_DEVICES = 500;\nconst MAX_PROJECTS = 500;\nconst MAX_IDENTITY_CHOICES = 500;\nconst MAX_COMPLETED_IDENTITY_CHOICES = MAX_DEVICES * 4;\nconst MAX_PROJECT_MAPPING_CHOICES = 500;\nconst MAX_TOTAL_PROJECT_MAPPING_CHOICES = 10_000;\nconst MAX_PROJECT_MAPPING_SCAN_ROWS = 10_000;\nconst MAX_PROJECT_MAPPING_METADATA_ROWS = 10_000;\nconst MAX_MUTATION_BODY_BYTES = 8_192;\nconst SUMMARY_SNAPSHOT_CACHE_TTL_MS = 30_000;\nconst COORDINATOR_ROSTER_READ_BUDGET_MS = 60_000;\nexport const TEAM_SETUP_ROUTE_PREFIX = \"/api/sync/team-setup/v1\";\nconst CANDIDATE_REF_PATTERN = /^legacy-team-candidate:[0-9a-f]{32}$/u;\nconst DEVICE_REF_PATTERN = /^legacy-team-device-ref-v1:[0-9a-f]{64}$/u;\nconst PROJECT_REF_PATTERN = /^legacy-team-project-ref-v1:[0-9a-f]{64}$/u;\nconst IDENTITY_REF_PATTERN = /^legacy-team-viewer-identity-ref-v1:[0-9a-f]{64}$/u;\nconst RESOLVED_PROJECT_REF_PATTERN = /^legacy-team-resolved-project-ref-v1:[0-9a-f]{64}$/u;\nconst ATTEMPT_ID_PATTERN = /^legacy-team-attempt:[0-9a-f-]{36}$/u;\nconst FINISH_DIGEST_PATTERN = /^legacy-team-activation-finish-v1:[0-9a-f]{64}$/u;\nconst ACCESS_DELTA_DIGEST_PATTERN = /^legacy-team-access-delta:[0-9a-f]{64}$/u;\nconst VIEWER_ACCESS_DELTA_DIGEST_PATTERN = /^legacy-team-viewer-access-delta-v1:[0-9a-f]{64}$/u;\nconst activeCandidateMutations = new WeakMap<MemoryStore[\"db\"], Map<string, Promise<void>>>();\n\nfunction claimCandidateMutation(db: MemoryStore[\"db\"], candidateRef: string): (() => void) | null {\n\tlet active = activeCandidateMutations.get(db);\n\tif (!active) {\n\t\tactive = new Map();\n\t\tactiveCandidateMutations.set(db, active);\n\t}\n\tif (active.has(candidateRef)) return null;\n\tlet settle: () => void = () => undefined;\n\tconst settled = new Promise<void>((resolve) => {\n\t\tsettle = resolve;\n\t});\n\tactive.set(candidateRef, settled);\n\tlet released = false;\n\treturn () => {\n\t\tif (released) return;\n\t\treleased = true;\n\t\tactive?.delete(candidateRef);\n\t\tsettle();\n\t};\n}\n\n/** Resolves once the current holder of the candidate claim (if any) releases it. */\nfunction candidateMutationSettled(db: MemoryStore[\"db\"], candidateRef: string): Promise<void> {\n\treturn activeCandidateMutations.get(db)?.get(candidateRef) ?? Promise.resolve();\n}\n\nasync function runCandidateMutation<T>(\n\tdb: MemoryStore[\"db\"],\n\tcandidateRef: string,\n\toperation: () => Promise<T>,\n): Promise<boolean> {\n\tconst release = claimCandidateMutation(db, candidateRef);\n\tif (!release) return false;\n\ttry {\n\t\tawait operation();\n\t\treturn true;\n\t} finally {\n\t\trelease();\n\t}\n}\n\ninterface LegacyTeamConfiguredGroupSnapshotLoadOptions {\n\tcandidateRef?: string;\n\tdeadlineMs?: number;\n}\n\nexport interface LegacyTeamCandidateGroupDescriptor {\n\tgroupId: string;\n\tcoordinatorId: string;\n}\n\nexport type LegacyTeamConfiguredGroupSnapshotLoader = (\n\toptions?: LegacyTeamConfiguredGroupSnapshotLoadOptions,\n) => Promise<LegacyTeamConfiguredGroupSnapshot[]>;\n\nexport interface TeamSetupRoutesOptions {\n\tgetStore: () => MemoryStore;\n\tloadLegacyTeamConfiguredGroupSnapshots?: LegacyTeamConfiguredGroupSnapshotLoader;\n\tsnapshotLoaderDependencies?: LegacyTeamSnapshotLoaderDependencies;\n\tcompletionDependencies?: LegacyTeamCompletionDependencies | null;\n\treadCoordinatorConfig?: typeof readCoordinatorSyncConfig;\n\tregisterSummaryInvalidator?: (invalidate: () => void) => void;\n}\n\nexport interface LegacyTeamCompletionDependencies {\n\tcreate: typeof coordinatorCreateLegacyTeamCompletionAction;\n\tget?: typeof coordinatorGetLegacyTeamCompletionAction;\n\tlist: typeof coordinatorListLegacyTeamCompletionsAction;\n}\n\nconst defaultCompletionDependencies: LegacyTeamCompletionDependencies = {\n\tcreate: coordinatorCreateLegacyTeamCompletionAction,\n\tget: coordinatorGetLegacyTeamCompletionAction,\n\tlist: coordinatorListLegacyTeamCompletionsAction,\n};\n\ninterface LegacyTeamSnapshotLoaderDependencies {\n\treadConfig: typeof readCoordinatorSyncConfig;\n\tlistGroups: typeof coordinatorListGroupsAction;\n\tlistDevices: typeof coordinatorListDevicesAction;\n}\n\nconst defaultSnapshotLoaderDependencies: LegacyTeamSnapshotLoaderDependencies = {\n\treadConfig: readCoordinatorSyncConfig,\n\tlistGroups: coordinatorListGroupsAction,\n\tlistDevices: coordinatorListDevicesAction,\n};\n\nfunction safeCoordinatorError(): Error {\n\treturn new Error(\"team_setup_roster_unavailable\");\n}\n\nfunction isCoordinatorRosterTooLargeError(error: unknown): boolean {\n\treturn error instanceof Error && error.message === \"coordinator_response_too_large\";\n}\n\nfunction remoteCoordinatorHttpStatus(error: unknown): number | null {\n\tif (!(error instanceof Error)) return null;\n\tconst status = /Remote coordinator request failed \\((\\d{3})\\):/u.exec(error.message)?.[1];\n\treturn status ? Number(status) : null;\n}\n\nfunction isTransientCoordinatorReadError(error: unknown): boolean {\n\tif (!(error instanceof Error)) return false;\n\tconst remoteStatus = remoteCoordinatorHttpStatus(error);\n\tif (remoteStatus) return [408, 429, 500, 502, 503, 504].includes(remoteStatus);\n\treturn (\n\t\terror.name === \"TimeoutError\" ||\n\t\terror.name === \"AbortError\" ||\n\t\t/request_timeout|fetch failed|timed out|timeout/iu.test(error.message)\n\t);\n}\n\nfunction isUnsupportedCompletionQuery(error: unknown): boolean {\n\tconst status = remoteCoordinatorHttpStatus(error);\n\treturn status === 404 || status === 405;\n}\n\n/**\n * Batch completion decoding rejects the whole payload when any one record is\n * malformed or misattributed, so the failure cannot be pinned to a group.\n */\nfunction isUnattributableCompletionBatchError(error: unknown): boolean {\n\treturn (\n\t\terror instanceof Error &&\n\t\t(error.message === \"coordinator_completion_response_malformed\" ||\n\t\t\terror.message === \"coordinator_completion_group_mismatch\")\n\t);\n}\n\nasync function listCompletionRecordsPerGroup(\n\tgroupIds: readonly string[],\n\tlist: (groupIds: string[]) => Promise<CoordinatorLegacyTeamCompletionRecord[]>,\n): Promise<CoordinatorLegacyTeamCompletionRecord[]> {\n\t// A single group re-query would repeat the same undecodable payload.\n\tif (groupIds.length < 2) return [];\n\tconst records: CoordinatorLegacyTeamCompletionRecord[] = [];\n\tfor (const groupId of groupIds) {\n\t\ttry {\n\t\t\trecords.push(...(await list([groupId])));\n\t\t} catch (error) {\n\t\t\tif (!isUnattributableCompletionBatchError(error)) throw error;\n\t\t}\n\t}\n\treturn records;\n}\n\nasync function retryTransientCoordinatorRead<T>(\n\tread: (timeoutS: number) => Promise<T>,\n\tconfiguredTimeoutS: number,\n\tdeadlineMs: number,\n): Promise<T> {\n\tlet lastError: unknown;\n\tfor (let attempt = 0; attempt < 8; attempt += 1) {\n\t\tconst remainingMs = deadlineMs - Date.now();\n\t\tif (remainingMs <= 0) throw lastError ?? safeCoordinatorError();\n\t\ttry {\n\t\t\treturn await read(Math.max(0.1, Math.min(configuredTimeoutS, remainingMs / 1_000)));\n\t\t} catch (error) {\n\t\t\tlastError = error;\n\t\t\tif (!isTransientCoordinatorReadError(error) || attempt === 7) throw error;\n\t\t\tconst delayMs = Math.min(100 * 2 ** attempt, 2_000, deadlineMs - Date.now());\n\t\t\tif (delayMs <= 0) throw error;\n\t\t\tawait new Promise((resolve) => setTimeout(resolve, delayMs));\n\t\t}\n\t}\n\tthrow lastError;\n}\n\nexport function remainingCoordinatorTimeoutS(\n\tconfiguredTimeoutS: number,\n\tdeadlineMs: number,\n\tnowMs = Date.now(),\n): number | null {\n\tconst remainingMs = deadlineMs - nowMs;\n\treturn remainingMs <= 0 ? null : Math.max(0.1, Math.min(configuredTimeoutS, remainingMs / 1_000));\n}\n\nfunction configuredGroupIds(groups: string[]): string[] {\n\tconst unique = [...new Set(groups.map((group) => group.trim()).filter(Boolean))];\n\tif (unique.length > MAX_CONFIGURED_GROUPS) throw safeCoordinatorError();\n\treturn unique;\n}\n\nexport function normalizedCoordinatorId(value: string): string | null {\n\ttry {\n\t\tconst normalized = buildBaseUrl(value);\n\t\tif (!normalized) return null;\n\t\tconst parsed = new URL(normalized);\n\t\tif (\n\t\t\t(parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") ||\n\t\t\t!parsed.host ||\n\t\t\tparsed.username ||\n\t\t\tparsed.password\n\t\t) {\n\t\t\treturn null;\n\t\t}\n\t\tconst path = parsed.pathname === \"/\" ? \"\" : parsed.pathname;\n\t\treturn `${parsed.protocol}//${parsed.host}${path}${parsed.search}`;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function legacyTeamCandidateGroupDescriptors(\n\tstore: MemoryStore | undefined,\n\tcoordinatorUrl: string,\n\tgroups: string[],\n): LegacyTeamCandidateGroupDescriptor[] {\n\tconst configuredIds = configuredGroupIds(groups);\n\tconst configuredCoordinatorId = buildBaseUrl(coordinatorUrl);\n\tconst normalizedConfiguredCoordinatorId = normalizedCoordinatorId(configuredCoordinatorId);\n\tif (!configuredCoordinatorId || !normalizedConfiguredCoordinatorId) throw safeCoordinatorError();\n\tlet scopeBackedDescriptors: LegacyTeamCandidateGroupDescriptor[] = [];\n\tif (store) {\n\t\ttry {\n\t\t\tscopeBackedDescriptors = scopeBackedGroupDescriptors(\n\t\t\t\tstore,\n\t\t\t\tnormalizedConfiguredCoordinatorId,\n\t\t\t\tMAX_CONFIGURED_GROUPS - configuredIds.length,\n\t\t\t\tconfiguredIds,\n\t\t\t);\n\t\t} catch {\n\t\t\t// Scope discovery is additive. Preserve configured coordinator candidates\n\t\t\t// when local evidence cannot be read.\n\t\t\tscopeBackedDescriptors = [];\n\t\t}\n\t}\n\treturn [\n\t\t...configuredIds.map((groupId) => ({ groupId, coordinatorId: configuredCoordinatorId })),\n\t\t...scopeBackedDescriptors,\n\t];\n}\n\nfunction scopeBackedGroupDescriptors(\n\tstore: MemoryStore,\n\tnormalizedConfiguredCoordinatorId: string,\n\tlimit: number,\n\texcludedGroupIds: string[],\n): LegacyTeamCandidateGroupDescriptor[] {\n\tif (limit <= 0) return [];\n\tconst textualCoordinatorIds = store.db\n\t\t.prepare(\n\t\t\t`SELECT DISTINCT coordinator_id FROM replication_scopes\n\t\t\t WHERE status = 'active' AND authority_type = 'coordinator'\n\t\t\t AND kind IN ('team', 'team_default', 'org', 'client')\n\t\t\t AND coordinator_id IS NOT NULL\n\t\t\t AND group_id IS NOT NULL AND TRIM(group_id) <> ''\n\t\t\t ORDER BY coordinator_id LIMIT ?`,\n\t\t)\n\t\t.pluck()\n\t\t.all(MAX_SCOPE_EVIDENCE_COORDINATORS + 1) as string[];\n\tif (textualCoordinatorIds.length > MAX_SCOPE_EVIDENCE_COORDINATORS) {\n\t\treturn [];\n\t}\n\tconst matchingTextualIds = textualCoordinatorIds.filter(\n\t\t(value) => normalizedCoordinatorId(value) === normalizedConfiguredCoordinatorId,\n\t);\n\tif (matchingTextualIds.length === 0) return [];\n\tconst coordinatorPlaceholders = matchingTextualIds.map(() => \"?\").join(\", \");\n\tconst excludedGroupClause =\n\t\texcludedGroupIds.length === 0\n\t\t\t? \"\"\n\t\t\t: `AND TRIM(group_id) NOT IN (${excludedGroupIds.map(() => \"?\").join(\", \")})`;\n\tconst groupIds = store.db\n\t\t.prepare(\n\t\t\t`SELECT DISTINCT TRIM(group_id) AS group_id FROM replication_scopes\n\t\t\t WHERE status = 'active' AND authority_type = 'coordinator'\n\t\t\t AND kind IN ('team', 'team_default', 'org', 'client')\n\t\t\t AND coordinator_id IN (${coordinatorPlaceholders})\n\t\t\t AND group_id IS NOT NULL AND TRIM(group_id) <> ''\n\t\t\t ${excludedGroupClause}\n\t\t\t ORDER BY TRIM(group_id) LIMIT ?`,\n\t\t)\n\t\t.pluck()\n\t\t.all(...matchingTextualIds, ...excludedGroupIds, limit) as string[];\n\tif (groupIds.length === 0) return [];\n\tconst groupPlaceholders = groupIds.map(() => \"?\").join(\", \");\n\tconst records = store.db\n\t\t.prepare(\n\t\t\t`SELECT DISTINCT TRIM(group_id) AS group_id, coordinator_id FROM replication_scopes\n\t\t\t WHERE status = 'active' AND authority_type = 'coordinator'\n\t\t\t AND kind IN ('team', 'team_default', 'org', 'client')\n\t\t\t AND coordinator_id IN (${coordinatorPlaceholders})\n\t\t\t AND TRIM(group_id) IN (${groupPlaceholders})\n\t\t\t ORDER BY TRIM(group_id), coordinator_id`,\n\t\t)\n\t\t.all(...matchingTextualIds, ...groupIds) as Array<{\n\t\tgroup_id: string;\n\t\tcoordinator_id: string;\n\t}>;\n\tconst coordinatorIdsByGroup = new Map<string, string[]>();\n\tfor (const record of records) {\n\t\tconst coordinatorIds = coordinatorIdsByGroup.get(record.group_id) ?? [];\n\t\tcoordinatorIds.push(record.coordinator_id);\n\t\tcoordinatorIdsByGroup.set(record.group_id, coordinatorIds);\n\t}\n\treturn groupIds.flatMap((groupId) => {\n\t\tconst coordinatorIds = coordinatorIdsByGroup.get(groupId) ?? [];\n\t\t// Equivalent textual coordinator IDs still represent distinct persisted\n\t\t// candidate identities. Never merge their authorization evidence by label.\n\t\tconst coordinatorId = coordinatorIds[0];\n\t\treturn coordinatorIds.length === 1 && coordinatorId ? [{ groupId, coordinatorId }] : [];\n\t});\n}\n\nasync function loadConfiguredLegacyTeamGroupSnapshotsWith(\n\tdependencies: LegacyTeamSnapshotLoaderDependencies,\n\toptions: LegacyTeamConfiguredGroupSnapshotLoadOptions = {},\n\tgetStore?: () => MemoryStore,\n): Promise<LegacyTeamConfiguredGroupSnapshot[]> {\n\tlet config: ReturnType<typeof readCoordinatorSyncConfig>;\n\ttry {\n\t\tconfig = dependencies.readConfig();\n\t} catch {\n\t\tthrow safeCoordinatorError();\n\t}\n\tconst hasUrl = Boolean(config.syncCoordinatorUrl);\n\tconst hasSecret = Boolean(config.syncCoordinatorAdminSecret);\n\tif (!hasUrl && !hasSecret && config.syncCoordinatorGroups.length === 0) return [];\n\tif (!hasUrl || !hasSecret) throw safeCoordinatorError();\n\n\ttry {\n\t\tconst configuredCoordinatorId = buildBaseUrl(config.syncCoordinatorUrl);\n\t\tif (!configuredCoordinatorId) throw safeCoordinatorError();\n\t\tconst remoteUrl = configuredCoordinatorId;\n\t\tlet store: MemoryStore | undefined;\n\t\ttry {\n\t\t\tstore = getStore?.();\n\t\t} catch {\n\t\t\t// Scope discovery is additive. Preserve configured coordinator candidates\n\t\t\t// when local evidence cannot be read.\n\t\t\tstore = undefined;\n\t\t}\n\t\tconst groupDescriptors = legacyTeamCandidateGroupDescriptors(\n\t\t\tstore,\n\t\t\tconfig.syncCoordinatorUrl,\n\t\t\tconfig.syncCoordinatorGroups,\n\t\t);\n\t\tif (groupDescriptors.length === 0) throw safeCoordinatorError();\n\t\tconst timeoutS = Math.max(1, config.syncCoordinatorTimeoutS);\n\t\tconst deadlineMs = options.deadlineMs ?? Date.now() + COORDINATOR_ROSTER_READ_BUDGET_MS;\n\t\tconst requestedGroupDescriptors = options.candidateRef\n\t\t\t? groupDescriptors.filter(\n\t\t\t\t\t({ coordinatorId, groupId }) =>\n\t\t\t\t\t\tlegacyTeamCandidateId(coordinatorId, groupId) === options.candidateRef,\n\t\t\t\t)\n\t\t\t: groupDescriptors;\n\t\tconst groups = await retryTransientCoordinatorRead(\n\t\t\t(attemptTimeoutS) =>\n\t\t\t\tdependencies.listGroups({\n\t\t\t\t\tremoteUrl,\n\t\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret,\n\t\t\t\t\tincludeArchived: false,\n\t\t\t\t\ttimeoutS: attemptTimeoutS,\n\t\t\t\t}),\n\t\t\ttimeoutS,\n\t\t\tdeadlineMs,\n\t\t);\n\t\tconst groupById = new Map(groups.map((group) => [group.group_id, group]));\n\t\tconst outcomes = await Promise.all(\n\t\t\trequestedGroupDescriptors.map(async ({ coordinatorId, groupId }) => {\n\t\t\t\t// Authoritative absence is stale state, while malformed or unavailable\n\t\t\t\t// evidence stays fail-closed. Summary mode may isolate the latter only\n\t\t\t\t// when another requested group remains healthy.\n\t\t\t\tconst group = groupById.get(groupId);\n\t\t\t\tif (!group || group.archived_at != null) {\n\t\t\t\t\treturn { kind: \"absent\" as const };\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\tgroup.group_id !== groupId ||\n\t\t\t\t\t(group.display_name !== null && typeof group.display_name !== \"string\")\n\t\t\t\t) {\n\t\t\t\t\tif (options.candidateRef) throw safeCoordinatorError();\n\t\t\t\t\treturn { kind: \"unavailable\" as const };\n\t\t\t\t}\n\t\t\t\tlet devices: Awaited<ReturnType<typeof coordinatorListDevicesAction>>;\n\t\t\t\ttry {\n\t\t\t\t\tdevices = await retryTransientCoordinatorRead(\n\t\t\t\t\t\t(attemptTimeoutS) =>\n\t\t\t\t\t\t\tdependencies.listDevices({\n\t\t\t\t\t\t\t\tgroupId,\n\t\t\t\t\t\t\t\tincludeDisabled: true,\n\t\t\t\t\t\t\t\tremoteUrl,\n\t\t\t\t\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret,\n\t\t\t\t\t\t\t\ttimeoutS: attemptTimeoutS,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\ttimeoutS,\n\t\t\t\t\t\tdeadlineMs,\n\t\t\t\t\t);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!options.candidateRef) return { kind: \"unavailable\" as const };\n\t\t\t\t\tif (isCoordinatorRosterTooLargeError(error)) {\n\t\t\t\t\t\tthrow new Error(\"legacy_team_setup_roster_too_large\");\n\t\t\t\t\t}\n\t\t\t\t\tthrow safeCoordinatorError();\n\t\t\t\t}\n\t\t\t\tif (devices.length > MAX_DEVICES) {\n\t\t\t\t\tif (options.candidateRef) throw new Error(\"legacy_team_setup_roster_too_large\");\n\t\t\t\t\treturn { kind: \"unavailable\" as const };\n\t\t\t\t}\n\t\t\t\tif (\n\t\t\t\t\tdevices.some(\n\t\t\t\t\t\t(device) =>\n\t\t\t\t\t\t\tfingerprintPublicKey(device.public_key) !== device.fingerprint ||\n\t\t\t\t\t\t\t(device.enabled !== 0 && device.enabled !== 1),\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\tif (options.candidateRef) throw safeCoordinatorError();\n\t\t\t\t\treturn { kind: \"unavailable\" as const };\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"snapshot\" as const,\n\t\t\t\t\tsnapshot: {\n\t\t\t\t\t\tcoordinatorId,\n\t\t\t\t\t\tgroupId,\n\t\t\t\t\t\tdisplayName: group.display_name ?? \"Legacy Team\",\n\t\t\t\t\t\tdevices: devices.map((device) => ({\n\t\t\t\t\t\t\tdeviceId: device.device_id,\n\t\t\t\t\t\t\tfingerprint: device.fingerprint,\n\t\t\t\t\t\t\tdisplayName: device.display_name ?? \"Device\",\n\t\t\t\t\t\t\tenabled: device.enabled === 1,\n\t\t\t\t\t\t\tlabelRedactionIds: [device.identity_id ?? \"\", device.public_key].filter(Boolean),\n\t\t\t\t\t\t})),\n\t\t\t\t\t},\n\t\t\t\t};\n\t\t\t}),\n\t\t);\n\t\tconst validSnapshots = outcomes.flatMap((outcome) =>\n\t\t\toutcome.kind === \"snapshot\" ? [outcome.snapshot] : [],\n\t\t);\n\t\tif (validSnapshots.length === 0 && outcomes.some((outcome) => outcome.kind === \"unavailable\")) {\n\t\t\tthrow safeCoordinatorError();\n\t\t}\n\t\treturn validSnapshots;\n\t} catch (error) {\n\t\tif (error instanceof Error && error.message === \"legacy_team_setup_roster_too_large\") {\n\t\t\tthrow error;\n\t\t}\n\t\tthrow safeCoordinatorError();\n\t}\n}\n\nfunction requireBoundedSnapshots(groups: LegacyTeamConfiguredGroupSnapshot[]): void {\n\tif (groups.length > MAX_CONFIGURED_GROUPS) {\n\t\tthrow new Error(\"legacy_team_setup_roster_too_large\");\n\t}\n}\n\nfunction projectionOptions(store: MemoryStore) {\n\treturn { localActorId: store.actorId, localDeviceId: store.deviceId };\n}\n\nfunction discoverCandidates(\n\tstore: MemoryStore,\n\tgroups: LegacyTeamConfiguredGroupSnapshot[],\n): LegacyTeamCandidateView[] {\n\trequireBoundedSnapshots(groups);\n\treturn discoverLegacyTeamCandidates(store.db, {\n\t\tprojection: projectionOptions(store),\n\t\tgroups,\n\t});\n}\n\nfunction candidateSummary(candidate: LegacyTeamCandidateView): LegacyTeamSetupCandidateSummaryV1 {\n\treturn {\n\t\tcandidateRef: candidate.candidateRef,\n\t\tdisplayName: candidate.displayName,\n\t\tstatus: candidate.status,\n\t\tdeviceCount: candidate.deviceCount,\n\t\tprojectCount: candidate.projectCount,\n\t\tunresolvedDeviceCount: candidate.unresolvedDeviceCount,\n\t\tunresolvedProjectCount: candidate.unresolvedProjectCount,\n\t};\n}\n\nfunction candidateSummaryForDraft(\n\tcandidate: LegacyTeamCandidateView,\n\tdraft: LegacyTeamSetupDraftView,\n): LegacyTeamSetupCandidateSummaryV1 {\n\treturn {\n\t\t...candidateSummary(candidate),\n\t\tstatus: draft.state === \"completed\" ? \"ready\" : draft.state,\n\t\tunresolvedDeviceCount: draft.unresolvedDeviceCount,\n\t\tunresolvedProjectCount: draft.unresolvedProjectCount,\n\t};\n}\n\nfunction candidateFromDraft(draft: LegacyTeamSetupDraftView): LegacyTeamCandidateView {\n\treturn {\n\t\tcandidateRef: draft.candidateRef,\n\t\tdisplayName: draft.displayName,\n\t\tstatus: draft.state === \"completed\" ? \"ready\" : draft.state,\n\t\tdeviceCount: draft.devices.length,\n\t\tprojectCount: draft.projects.length,\n\t\tunresolvedDeviceCount: draft.unresolvedDeviceCount,\n\t\tunresolvedProjectCount: draft.unresolvedProjectCount,\n\t};\n}\n\nfunction readPureCandidateViews(\n\tstore: MemoryStore,\n\tgroups: LegacyTeamConfiguredGroupSnapshot[],\n): LegacyTeamCandidateView[] {\n\tconst existing: LegacyTeamCandidateView[] = [];\n\tconst discoverable: LegacyTeamConfiguredGroupSnapshot[] = [];\n\tfor (const group of groups) {\n\t\tconst candidateRef = legacyTeamCandidateId(group.coordinatorId, group.groupId);\n\t\tconst draft = getLegacyTeamSetupDraft(store.db, candidateRef);\n\t\tif (hasCompletedLegacyTeamSetup(store, candidateRef)) {\n\t\t\t// Only canonical terminal completions pass through discovery: they can\n\t\t\t// reconcile missing setup recipient edges while preserving newer drafts.\n\t\t\tif (isLegacyTeamCandidateSelectable(store.db, candidateRef)) discoverable.push(group);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!draft || draft.state === \"completed\") {\n\t\t\tdiscoverable.push(group);\n\t\t\tcontinue;\n\t\t}\n\t\texisting.push(candidateFromDraft(draft));\n\t}\n\treturn [...existing, ...discoverCandidates(store, discoverable)]\n\t\t.filter((candidate) => !hasCompletedLegacyTeamSetup(store, candidate.candidateRef))\n\t\t.toSorted((left, right) =>\n\t\t\tleft.candidateRef < right.candidateRef ? -1 : left.candidateRef > right.candidateRef ? 1 : 0,\n\t\t);\n}\n\nfunction hasCompletedLegacyTeamSetup(store: MemoryStore, candidateRef: string): boolean {\n\treturn Boolean(\n\t\tstore.db\n\t\t\t.prepare(\n\t\t\t\t`SELECT 1 FROM policy_teams\n\t\t\t\t WHERE team_id = ? AND status = 'active'\n\t\t\t\t AND provenance = 'reviewed_team_candidate'\n\t\t\t\t AND migration_state = 'completed' LIMIT 1`,\n\t\t\t)\n\t\t\t.pluck()\n\t\t\t.get(deterministicPolicyTeamId(candidateRef)),\n\t);\n}\n\nfunction identityRef(candidateRef: string, identityId: string | null): string | null {\n\treturn identityId\n\t\t? recipientPolicyDigest(\"legacy-team-viewer-identity-ref-v1\", [candidateRef, identityId])\n\t\t: null;\n}\n\nfunction requiredIdentityRef(candidateRef: string, identityId: string): string {\n\treturn recipientPolicyDigest(\"legacy-team-viewer-identity-ref-v1\", [candidateRef, identityId]);\n}\n\nfunction teamRef(candidateRef: string, teamId: string): string {\n\treturn recipientPolicyDigest(\"legacy-team-viewer-team-ref-v1\", [candidateRef, teamId]);\n}\n\nfunction resolvedProjectRef(projectRef: string, projectIdentity: string | null): string | null {\n\treturn projectIdentity ? legacyTeamResolvedProjectRef(projectRef, projectIdentity) : null;\n}\n\nfunction viewerSafeAccessDelta(\n\tcandidateRef: string,\n\tdelta: LegacyTeamSetupAccessDeltaV1,\n\tlabels?: {\n\t\tteamDisplayName: string;\n\t\tdevices: Array<Omit<LegacyTeamSetupDeviceV1, \"actions\">>;\n\t\tprojects: Array<Omit<LegacyTeamSetupProjectV1, \"actions\">>;\n\t\tidentityChoices: LegacyTeamSetupIdentityChoiceV1[];\n\t},\n): LegacyTeamSetupViewerAccessDeltaV1 {\n\tconst fallbackLabels = new Map<string, string>();\n\tconst fallbackLabelCounts = new Map<string, number>();\n\tconst reservedLabels = new Set(\n\t\t[\n\t\t\tlabels?.teamDisplayName,\n\t\t\t...(labels?.devices.map((device) => device.displayName) ?? []),\n\t\t\t...(labels?.projects.flatMap((project) => [\n\t\t\t\tproject.displayName,\n\t\t\t\t...project.mappingChoices.map((choice) => choice.displayName),\n\t\t\t]) ?? []),\n\t\t\t...(labels?.identityChoices.map((identity) => identity.displayName) ?? []),\n\t\t]\n\t\t\t.filter((label): label is string => Boolean(label))\n\t\t\t.map((label) => normalizeChoiceLabelText(label).toLowerCase()),\n\t);\n\tconst fallbackLabel = (kind: string, ref: string) => {\n\t\tconst key = `${kind}:${ref}`;\n\t\tconst existing = fallbackLabels.get(key);\n\t\tif (existing) return existing;\n\t\tlet index = (fallbackLabelCounts.get(kind) ?? 0) + 1;\n\t\tlet label = `${kind} outside this setup (${index})`;\n\t\twhile (reservedLabels.has(normalizeChoiceLabelText(label).toLowerCase())) {\n\t\t\tindex += 1;\n\t\t\tlabel = `${kind} outside this setup (${index})`;\n\t\t}\n\t\tfallbackLabelCounts.set(kind, index);\n\t\treservedLabels.add(normalizeChoiceLabelText(label).toLowerCase());\n\t\tfallbackLabels.set(key, label);\n\t\treturn label;\n\t};\n\tconst projectsByRef = new Map(labels?.projects.map((project) => [project.projectRef, project]));\n\tconst projectsByCanonicalRef = new Map(\n\t\tlabels?.projects.flatMap((project) =>\n\t\t\tproject.canonicalProjectRef ? [[project.canonicalProjectRef, project] as const] : [],\n\t\t),\n\t);\n\tconst identitiesByRef = new Map(\n\t\tlabels?.identityChoices.map((identity) => [identity.identityRef, identity]),\n\t);\n\tconst devicesByRef = new Map(labels?.devices.map((device) => [device.deviceRef, device]));\n\tconst canonicalProjectPresentation = (identity: string, ref: string) => {\n\t\tif (identity === \"shared:default\") {\n\t\t\treturn { displayName: \"Legacy default sharing\", kind: \"legacy_default_sharing\" as const };\n\t\t}\n\t\treturn {\n\t\t\tdisplayName: projectsByCanonicalRef.get(ref)?.displayName ?? fallbackLabel(\"Project\", ref),\n\t\t\tkind: \"project\" as const,\n\t\t};\n\t};\n\tconst resolvedDisplayName = (projectRef: string, ref: string | null): string | null => {\n\t\tif (!ref) return null;\n\t\tconst project = projectsByRef.get(projectRef);\n\t\tconst choice = project?.mappingChoices.find((item) => item.resolvedProjectRef === ref);\n\t\tif (choice) return choice.displayName;\n\t\tif (project?.resolvedProjectRef === ref && project.resolution === \"deterministic\") {\n\t\t\treturn `${project.displayName} (automatic match)`;\n\t\t}\n\t\treturn fallbackLabel(\"Project\", ref);\n\t};\n\treturn {\n\t\tteamChanges: delta.teamChanges.map((change) => ({\n\t\t\tteamRef: teamRef(candidateRef, change.teamId),\n\t\t\tteamDisplayName:\n\t\t\t\tlabels?.teamDisplayName ?? fallbackLabel(\"Team\", teamRef(candidateRef, change.teamId)),\n\t\t\tchange: change.change,\n\t\t\tfromDeviceEligibilityMode: change.fromDeviceEligibilityMode,\n\t\t\ttoDeviceEligibilityMode: change.toDeviceEligibilityMode,\n\t\t})),\n\t\tmembershipChanges: delta.membershipChanges.map((change) => {\n\t\t\tconst identityRef = requiredIdentityRef(candidateRef, change.identityId);\n\t\t\tconst membershipTeamRef = teamRef(candidateRef, change.teamId);\n\t\t\treturn {\n\t\t\t\tteamRef: membershipTeamRef,\n\t\t\t\tteamDisplayName: labels?.teamDisplayName ?? fallbackLabel(\"Team\", membershipTeamRef),\n\t\t\t\tidentityRef,\n\t\t\t\tidentityDisplayName:\n\t\t\t\t\tidentitiesByRef.get(identityRef)?.displayName ?? fallbackLabel(\"Person\", identityRef),\n\t\t\t\tchange: change.change,\n\t\t\t};\n\t\t}),\n\t\tprojectChanges: delta.projectChanges.map((change) => {\n\t\t\tconst fromRef = resolvedProjectRef(change.projectRef, change.fromProjectIdentity);\n\t\t\tconst toRef = resolvedProjectRef(change.projectRef, change.toProjectIdentity);\n\t\t\treturn {\n\t\t\t\tprojectRef: change.projectRef,\n\t\t\t\tprojectDisplayName:\n\t\t\t\t\tprojectsByRef.get(change.projectRef)?.displayName ??\n\t\t\t\t\tfallbackLabel(\"Project\", change.projectRef),\n\t\t\t\tfromCanonicalProjectRef: change.fromProjectIdentity\n\t\t\t\t\t? legacyTeamCanonicalProjectRef(candidateRef, change.fromProjectIdentity)\n\t\t\t\t\t: null,\n\t\t\t\tfromResolvedProjectRef: fromRef,\n\t\t\t\tfromResolvedProjectDisplayName: resolvedDisplayName(change.projectRef, fromRef),\n\t\t\t\ttoCanonicalProjectRef: change.toProjectIdentity\n\t\t\t\t\t? legacyTeamCanonicalProjectRef(candidateRef, change.toProjectIdentity)\n\t\t\t\t\t: null,\n\t\t\t\ttoResolvedProjectRef: toRef,\n\t\t\t\ttoResolvedProjectDisplayName: resolvedDisplayName(change.projectRef, toRef),\n\t\t\t\tchange: change.change,\n\t\t\t};\n\t\t}),\n\t\trecipientChanges: delta.recipientChanges.map((change) => {\n\t\t\tconst canonicalProjectRef = legacyTeamCanonicalProjectRef(\n\t\t\t\tcandidateRef,\n\t\t\t\tchange.canonicalProjectIdentity,\n\t\t\t);\n\t\t\tconst recipientRef = teamRef(candidateRef, change.recipientId);\n\t\t\tconst projectPresentation = canonicalProjectPresentation(\n\t\t\t\tchange.canonicalProjectIdentity,\n\t\t\t\tcanonicalProjectRef,\n\t\t\t);\n\t\t\treturn {\n\t\t\t\tcanonicalProjectRef,\n\t\t\t\tcanonicalProjectDisplayName: projectPresentation.displayName,\n\t\t\t\tcanonicalProjectKind: projectPresentation.kind,\n\t\t\t\trecipientKind: change.recipientKind,\n\t\t\t\trecipientRef,\n\t\t\t\trecipientDisplayName: labels?.teamDisplayName ?? fallbackLabel(\"Team\", recipientRef),\n\t\t\t\tchange: change.change,\n\t\t\t};\n\t\t}),\n\t\tdeviceAccessChanges: delta.deviceAccessChanges.map((change) => {\n\t\t\tconst canonicalProjectRef = legacyTeamCanonicalProjectRef(\n\t\t\t\tcandidateRef,\n\t\t\t\tchange.canonicalProjectIdentity,\n\t\t\t);\n\t\t\tconst deviceRef = legacyTeamDeviceRef(candidateRef, change.deviceId);\n\t\t\tconst projectPresentation = canonicalProjectPresentation(\n\t\t\t\tchange.canonicalProjectIdentity,\n\t\t\t\tcanonicalProjectRef,\n\t\t\t);\n\t\t\treturn {\n\t\t\t\tcanonicalProjectRef,\n\t\t\t\tcanonicalProjectDisplayName: projectPresentation.displayName,\n\t\t\t\tcanonicalProjectKind: projectPresentation.kind,\n\t\t\t\tdeviceRef,\n\t\t\t\tdeviceDisplayName:\n\t\t\t\t\tdevicesByRef.get(deviceRef)?.displayName ?? fallbackLabel(\"Device\", deviceRef),\n\t\t\t\tchange: change.change,\n\t\t\t};\n\t\t}),\n\t};\n}\n\nfunction viewerAccessDeltaDigest(delta: LegacyTeamSetupViewerAccessDeltaV1): string {\n\treturn recipientPolicyDigest(\"legacy-team-viewer-access-delta-v1\", delta);\n}\n\nconst SAFE_CHOICE_LABEL_PATTERN = /^[\\p{L}\\p{N} '&,.()_-]*$/u;\n\n// Keep this byte-for-byte equivalent in behavior to the core setup-label\n// normalization without exporting a presentation-only core implementation.\nfunction normalizeChoiceLabelText(value: string): string {\n\treturn value\n\t\t.normalize(\"NFKC\")\n\t\t.replace(/\\p{Cf}/gu, \"\")\n\t\t.replace(/\\p{Cc}/gu, \" \")\n\t\t.replace(/\\s+/gu, \" \")\n\t\t.trim();\n}\n\nfunction safeChoiceLabel(\n\tvalue: string,\n\tfallback: string,\n\tforbiddenIds: readonly string[],\n\topaqueRef?: string,\n): string {\n\tconst normalized = normalizeChoiceLabelText(value.slice(0, 512));\n\tconst label = normalized.slice(0, 120).trim();\n\tconst forbiddenComparisons = forbiddenIds\n\t\t.map((forbiddenId) => normalizeChoiceLabelText(forbiddenId).toLowerCase())\n\t\t.filter(Boolean);\n\tconst comparable = normalized.toLowerCase();\n\tif (\n\t\t!label ||\n\t\t!SAFE_CHOICE_LABEL_PATTERN.test(label) ||\n\t\t/[\\p{L}\\p{N}]\\.[\\p{L}\\p{N}]/u.test(label) ||\n\t\t/-----|\\b(?:ssh|ecdsa|sk)-[\\p{L}\\p{N}-]+ /iu.test(label) ||\n\t\tforbiddenComparisons.some((forbiddenComparison) => comparable.includes(forbiddenComparison))\n\t) {\n\t\tconst suffix = opaqueRef?.slice(-6);\n\t\treturn suffix ? `${fallback} ${suffix}` : fallback;\n\t}\n\treturn label;\n}\n\nfunction disambiguateChoiceLabels<T extends { displayName: string }>(\n\tchoices: readonly T[],\n\tchoiceRef: (choice: T) => string,\n): T[] {\n\tconst counts = new Map<string, number>();\n\tconst originalLabels = new Set<string>();\n\tfor (const choice of choices) {\n\t\tconst comparable = normalizeChoiceLabelText(choice.displayName).toLowerCase();\n\t\tcounts.set(comparable, (counts.get(comparable) ?? 0) + 1);\n\t\toriginalLabels.add(comparable);\n\t}\n\tconst usedLabels = new Set<string>();\n\treturn choices.map((choice, index) => {\n\t\tconst comparable = normalizeChoiceLabelText(choice.displayName).toLowerCase();\n\t\tif ((counts.get(comparable) ?? 0) < 2 && !usedLabels.has(comparable)) {\n\t\t\tusedLabels.add(comparable);\n\t\t\treturn choice;\n\t\t}\n\t\tconst ref = choiceRef(choice);\n\t\tlet suffixLength = Math.min(6, ref.length);\n\t\tlet suffix = ref.slice(-suffixLength);\n\t\tconst maxAttempts = ref.length + originalLabels.size + usedLabels.size + 2;\n\t\tfor (let attempt = 0; attempt < maxAttempts; attempt += 1) {\n\t\t\tconst baseLength = Math.max(0, 119 - suffix.length);\n\t\t\tconst base = choice.displayName.slice(0, baseLength).trimEnd();\n\t\t\tconst displayName = base ? `${base} ${suffix}` : suffix.slice(-120);\n\t\t\tconst finalComparable = normalizeChoiceLabelText(displayName).toLowerCase();\n\t\t\tif (!usedLabels.has(finalComparable) && !originalLabels.has(finalComparable)) {\n\t\t\t\tusedLabels.add(finalComparable);\n\t\t\t\treturn { ...choice, displayName };\n\t\t\t}\n\t\t\tif (suffixLength < ref.length) {\n\t\t\t\tsuffixLength = Math.min(ref.length, suffixLength + 2);\n\t\t\t\tsuffix = ref.slice(-suffixLength);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tsuffix = `${ref.slice(-Math.min(96, ref.length))}-${index + 1}-${attempt + 1}`;\n\t\t}\n\t\tthrow new Error(\"legacy_team_setup_roster_too_large\");\n\t});\n}\n\nfunction requireCompleteMappingChoices(projectCount: number, choiceCount: number): void {\n\tif (projectCount * choiceCount > MAX_TOTAL_PROJECT_MAPPING_CHOICES) {\n\t\tthrow new Error(\"legacy_team_setup_roster_too_large\");\n\t}\n}\n\nfunction createCachedSnapshotLoader(\n\tload: () => Promise<LegacyTeamConfiguredGroupSnapshot[]>,\n\tttlMs: number,\n\tnow: () => number = Date.now,\n): (() => Promise<LegacyTeamConfiguredGroupSnapshot[]>) & {\n\tinvalidate: () => void;\n\tpeek: () => LegacyTeamConfiguredGroupSnapshot[] | null;\n} {\n\tlet cached: { expiresAt: number; snapshots: LegacyTeamConfiguredGroupSnapshot[] } | null = null;\n\tlet inFlight: Promise<LegacyTeamConfiguredGroupSnapshot[]> | null = null;\n\tlet generation = 0;\n\tconst cachedLoad = () => {\n\t\tif (cached && now() < cached.expiresAt) return Promise.resolve(cached.snapshots);\n\t\tif (inFlight) return inFlight;\n\t\tconst operationGeneration = generation;\n\t\tlet operation: Promise<LegacyTeamConfiguredGroupSnapshot[]>;\n\t\toperation = load()\n\t\t\t.then((snapshots) => {\n\t\t\t\tif (generation !== operationGeneration) return cachedLoad();\n\t\t\t\tcached = { expiresAt: now() + ttlMs, snapshots };\n\t\t\t\treturn snapshots;\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\tif (inFlight === operation) inFlight = null;\n\t\t\t});\n\t\tinFlight = operation;\n\t\treturn operation;\n\t};\n\tcachedLoad.invalidate = () => {\n\t\tgeneration += 1;\n\t\tcached = null;\n\t\tinFlight = null;\n\t};\n\tcachedLoad.peek = () => (cached && now() < cached.expiresAt ? cached.snapshots : null);\n\treturn cachedLoad;\n}\n\nasync function loadMutableCandidateSnapshots(\n\tstore: MemoryStore,\n\tcandidateRef: string,\n\tload: () => Promise<LegacyTeamConfiguredGroupSnapshot[]>,\n): Promise<LegacyTeamConfiguredGroupSnapshot[]> {\n\tif (getLegacyTeamSetupDraft(store.db, candidateRef)?.state === \"completed\") {\n\t\tthrow new Error(\"team_setup_confirmation_stale\");\n\t}\n\treturn load();\n}\n\nfunction projectMutationAtomically<Mutation, Projection>(\n\tstore: MemoryStore,\n\tmutate: () => Mutation,\n\tproject: (mutation: Mutation) => Projection,\n): Projection {\n\treturn store.db.transaction(() => project(mutate())).immediate();\n}\n\nexport const __teamSetupTestHooks = {\n\tcreateCachedSnapshotLoader,\n\tloadConfiguredLegacyTeamGroupSnapshotsWith,\n\tnormalizedCoordinatorId,\n\tprojectMutationAtomically,\n\trequireBoundedAccessDelta: requireLegacyTeamSetupAccessDeltaWithinLimit,\n\trequireCompleteMappingChoices,\n\tdisambiguateChoiceLabels,\n\tsafeChoiceLabel,\n\tviewerSafeAccessDelta,\n\t// Lazy: the classifier and its typed error are declared below this object.\n\tfinishFailureDetails: (error: unknown) => teamSetupFinishFailureDetails(error),\n\tlocalProjectScanBudgetError: (cause?: unknown) => new LocalProjectScanBudgetError(cause),\n};\n\ninterface IdentityChoiceInternal extends LegacyTeamSetupIdentityChoiceV1 {\n\tidentityId: string;\n}\n\ntype IdentityChoiceRow = { actor_id: string; display_name: string };\n\nfunction identityChoicesFromRows(\n\trows: IdentityChoiceRow[],\n\tcandidateRef: string,\n\tmaxChoices = MAX_IDENTITY_CHOICES,\n): IdentityChoiceInternal[] {\n\tif (rows.length > maxChoices) {\n\t\tthrow new Error(\"legacy_team_setup_roster_too_large\");\n\t}\n\tconst actorIds = rows.map((row) => row.actor_id);\n\treturn disambiguateChoiceLabels(\n\t\trows.map((row) => {\n\t\t\tconst opaqueIdentityRef = requiredIdentityRef(candidateRef, row.actor_id);\n\t\t\treturn {\n\t\t\t\tidentityId: row.actor_id,\n\t\t\t\tidentityRef: opaqueIdentityRef,\n\t\t\t\tdisplayName: safeChoiceLabel(row.display_name, \"Person\", actorIds, opaqueIdentityRef),\n\t\t\t};\n\t\t}),\n\t\t(choice) => choice.identityRef,\n\t);\n}\n\nfunction identityChoices(store: MemoryStore, candidateRef: string): IdentityChoiceInternal[] {\n\tconst rows = store.db\n\t\t.prepare(\n\t\t\t`SELECT actor_id, display_name FROM actors\n\t\t\t WHERE status = 'active' AND merged_into_actor_id IS NULL\n\t\t\t ORDER BY display_name, actor_id LIMIT ?`,\n\t\t)\n\t\t.all(MAX_IDENTITY_CHOICES + 1) as IdentityChoiceRow[];\n\treturn identityChoicesFromRows(rows, candidateRef);\n}\n\nfunction completedDraftIdentityChoices(\n\tstore: MemoryStore,\n\tdraft: LegacyTeamSetupDraftView,\n): IdentityChoiceInternal[] {\n\tconst actorIds = [\n\t\t...new Set(\n\t\t\tdraft.devices.flatMap((device) => [\n\t\t\t\tdevice.existingIdentityId,\n\t\t\t\tdevice.suggestedIdentityId,\n\t\t\t\tdevice.targetIdentityId,\n\t\t\t\tdevice.expectation.kind === \"existing\" ? device.expectation.identityId : null,\n\t\t\t]),\n\t\t),\n\t].filter((actorId): actorId is string => actorId !== null);\n\tif (actorIds.length === 0) return [];\n\tconst placeholders = actorIds.map(() => \"?\").join(\", \");\n\tconst rows = store.db\n\t\t.prepare(\n\t\t\t`SELECT actor_id, display_name FROM actors\n\t\t\t WHERE status = 'active' AND merged_into_actor_id IS NULL\n\t\t\t AND actor_id IN (${placeholders})\n\t\t\t ORDER BY display_name, actor_id`,\n\t\t)\n\t\t.all(...actorIds) as IdentityChoiceRow[];\n\treturn identityChoicesFromRows(rows, draft.candidateRef, MAX_COMPLETED_IDENTITY_CHOICES);\n}\n\ninterface ProjectMappingChoiceInternal {\n\tprojectIdentity: string;\n\tsourceDisplayName: string;\n}\n\nfunction projectMappingChoices(store: MemoryStore): ProjectMappingChoiceInternal[] {\n\tlet candidates: ReturnType<typeof listProjectScopeCandidates>;\n\ttry {\n\t\tcandidates = listProjectScopeCandidates(store.db, {\n\t\t\tlimit: null,\n\t\t\tmaxScannedRows: MAX_PROJECT_MAPPING_SCAN_ROWS,\n\t\t\tmaxMetadataRows: MAX_PROJECT_MAPPING_METADATA_ROWS,\n\t\t\texcludePeerReceived: true,\n\t\t}).filter(\n\t\t\t(candidate) =>\n\t\t\t\t!candidate.read_only &&\n\t\t\t\tisLegacyTeamSetupProjectMappingIdentity(candidate.workspace_identity, store.db),\n\t\t);\n\t} catch (error) {\n\t\tif (\n\t\t\terror instanceof Error &&\n\t\t\t(error.message === \"project_scope_candidate_scan_too_large\" ||\n\t\t\t\terror.message === \"project_scope_candidate_metadata_too_large\")\n\t\t) {\n\t\t\tthrow new LocalProjectScanBudgetError(error);\n\t\t}\n\t\tthrow error;\n\t}\n\tif (candidates.length > MAX_PROJECT_MAPPING_CHOICES) {\n\t\tthrow new LocalProjectScanBudgetError();\n\t}\n\treturn candidates.map((candidate) => ({\n\t\tprojectIdentity: candidate.workspace_identity,\n\t\tsourceDisplayName: candidate.display_project,\n\t}));\n}\n\ninterface ViewerSafeDraft {\n\tdevices: Array<Omit<LegacyTeamSetupDeviceV1, \"actions\">>;\n\tprojects: Array<Omit<LegacyTeamSetupProjectV1, \"actions\">>;\n\tidentityChoices: LegacyTeamSetupIdentityChoiceV1[];\n}\n\nfunction viewerSafeDraft(store: MemoryStore, draft: LegacyTeamSetupDraftView): ViewerSafeDraft {\n\tif (draft.devices.length > MAX_DEVICES || draft.projects.length > MAX_PROJECTS) {\n\t\tthrow new Error(\"legacy_team_setup_roster_too_large\");\n\t}\n\tconst completed = draft.state === \"completed\";\n\tconst identities = completed\n\t\t? completedDraftIdentityChoices(store, draft)\n\t\t: identityChoices(store, draft.candidateRef);\n\tconst mappableProjectCount = completed\n\t\t? 0\n\t\t: draft.projects.filter((project) => project.resolution !== \"deterministic\").length;\n\tconst mappingChoices = mappableProjectCount === 0 ? [] : projectMappingChoices(store);\n\trequireCompleteMappingChoices(mappableProjectCount, mappingChoices.length);\n\tconst mappingChoiceIdentities = mappingChoices.map((choice) => choice.projectIdentity);\n\treturn {\n\t\tdevices: draft.devices.map((device) => ({\n\t\t\tdeviceRef: device.deviceRef,\n\t\t\tdisplayName: device.displayName,\n\t\t\tenabled: device.enabled,\n\t\t\texistingIdentityRef: identityRef(draft.candidateRef, device.existingIdentityId),\n\t\t\tsuggestedIdentityRef: identityRef(draft.candidateRef, device.suggestedIdentityId),\n\t\t\tverifiedEvidenceKind: device.verifiedEvidenceKind,\n\t\t\tdecision: device.decision,\n\t\t\ttargetIdentityRef: identityRef(draft.candidateRef, device.targetIdentityId),\n\t\t\texpectation:\n\t\t\t\tdevice.expectation.kind === \"existing\"\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tkind: \"existing\" as const,\n\t\t\t\t\t\t\tassignmentVersion: device.expectation.assignmentVersion,\n\t\t\t\t\t\t\tidentityRef: requiredIdentityRef(draft.candidateRef, device.expectation.identityId),\n\t\t\t\t\t\t}\n\t\t\t\t\t: { kind: \"absent\" as const },\n\t\t})),\n\t\tprojects: draft.projects.map((project) => ({\n\t\t\tprojectRef: project.projectRef,\n\t\t\tdisplayName: project.displayName,\n\t\t\tresolution: project.resolution,\n\t\t\tcanonicalProjectRef: project.canonicalProjectRef,\n\t\t\tresolvedProjectRef: project.resolvedProjectRef,\n\t\t\tmappingChoices:\n\t\t\t\tproject.resolution === \"deterministic\"\n\t\t\t\t\t? []\n\t\t\t\t\t: disambiguateChoiceLabels(\n\t\t\t\t\t\t\tmappingChoices.map((choice) => {\n\t\t\t\t\t\t\t\tconst opaqueResolvedProjectRef = legacyTeamResolvedProjectRef(\n\t\t\t\t\t\t\t\t\tproject.projectRef,\n\t\t\t\t\t\t\t\t\tchoice.projectIdentity,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\tresolvedProjectRef: opaqueResolvedProjectRef,\n\t\t\t\t\t\t\t\t\tdisplayName: safeChoiceLabel(\n\t\t\t\t\t\t\t\t\t\tchoice.sourceDisplayName,\n\t\t\t\t\t\t\t\t\t\t\"Project\",\n\t\t\t\t\t\t\t\t\t\tmappingChoiceIdentities,\n\t\t\t\t\t\t\t\t\t\topaqueResolvedProjectRef,\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t(choice) => choice.resolvedProjectRef,\n\t\t\t\t\t\t),\n\t\t})),\n\t\tidentityChoices: identities.map(({ identityRef, displayName }) => ({\n\t\t\tidentityRef,\n\t\t\tdisplayName,\n\t\t})),\n\t};\n}\n\nfunction viewerSafePreview(\n\tdraft: LegacyTeamSetupDraftView,\n\tsafeDraft: ViewerSafeDraft,\n\tpreview: ReturnType<typeof inspectLegacyTeamSetupActivation>,\n) {\n\tconst accessDelta = viewerSafeAccessDelta(draft.candidateRef, preview.accessDelta, {\n\t\tteamDisplayName: draft.displayName,\n\t\t...safeDraft,\n\t});\n\treturn {\n\t\tfinishDigest: preview.finishDigest,\n\t\taccessDeltaDigest: preview.accessDeltaDigest,\n\t\tviewerAccessDeltaDigest: viewerAccessDeltaDigest(accessDelta),\n\t\taccessDelta,\n\t};\n}\n\nfunction errorStatus(code: LegacyTeamSetupActivationErrorCode): 400 | 409 | 503 {\n\tif (code === \"team_setup_roster_unavailable\" || code === \"team_setup_completion_unavailable\")\n\t\treturn 503;\n\tif (code === \"team_setup_failed\") return 503;\n\tif (code === \"team_setup_incomplete\") return 400;\n\treturn 409;\n}\n\nfunction apiErrorCode(error: unknown): LegacyTeamSetupActivationErrorCode {\n\tconst code = legacyTeamSetupApiErrorCode(error);\n\treturn code === \"team_setup_projection_changed\" ? \"team_setup_conflict\" : code;\n}\n\nfunction completionApiError(error: unknown): LegacyTeamSetupActivationErrorCode {\n\tconst code = legacyTeamSetupApiErrorCode(error);\n\treturn code === \"team_setup_failed\" ? \"team_setup_completion_unavailable\" : code;\n}\n\nclass TeamSetupFinishError extends Error {\n\tconstructor(\n\t\tcode: LegacyTeamSetupActivationErrorCode,\n\t\treadonly reason: LegacyTeamSetupErrorReason | undefined,\n\t\treadonly alreadyLogged: boolean,\n\t\tcause?: unknown,\n\t) {\n\t\tsuper(code, cause === undefined ? undefined : { cause });\n\t\tthis.name = \"TeamSetupFinishError\";\n\t}\n}\n\ninterface TeamSetupFinishFailureDetails {\n\treason?: LegacyTeamSetupErrorReason;\n\tcause: string;\n\tstatus?: number;\n\tcode?: string;\n}\n\n/**\n * The generic `legacy_team_setup_roster_too_large` string is thrown by ten\n * sites for unrelated limits (coordinator roster size, draft device count,\n * local project choices). Only the local project-candidate scan is a\n * \"this device's history is too large\" condition, so it carries a distinct\n * type. The message is kept identical so the frozen API-code mapping and every\n * existing caller that matches on it are unchanged.\n */\nclass LocalProjectScanBudgetError extends Error {\n\tconstructor(cause?: unknown) {\n\t\tsuper(\"legacy_team_setup_roster_too_large\", cause === undefined ? undefined : { cause });\n\t\tthis.name = \"LocalProjectScanBudgetError\";\n\t}\n}\n\n/**\n * Remote error codes the finish path can legitimately receive from the\n * coordinator. Anything else — including identifier-shaped values, which a\n * hostile or misconfigured upstream could use to smuggle a credential through\n * a JSON `error` field — is reduced to a fixed classification before logging.\n * A shape check is not an allowlist; only this set is echoed verbatim.\n */\nconst LOGGABLE_REMOTE_ERROR_CODES = new Set([\n\t\"body_too_large\",\n\t\"completion_manifest_invalid\",\n\t\"completion_manifest_unavailable\",\n\t\"completion_not_found\",\n\t\"completion_query_invalid\",\n\t\"group_archived\",\n\t\"group_id_and_candidate_ref_required\",\n\t\"group_not_found\",\n\t\"invalid_json\",\n\t\"missing_admin_header\",\n\t\"not_found\",\n\t\"rate_limited\",\n\t\"response_too_large\",\n\t\"unauthorized\",\n]);\n\nfunction loggableRemoteCode(code: string): string {\n\tif (LOGGABLE_REMOTE_ERROR_CODES.has(code)) return code;\n\tif (code.startsWith(\"non_json_response\")) return \"non_json_response\";\n\treturn \"unclassified_remote_error\";\n}\n\n/**\n * Local causes the finish path can produce. Same allowlist discipline as\n * remote codes: everything else, including transport messages that embed the\n * target URL, is classified rather than echoed.\n */\nconst LOGGABLE_LOCAL_CAUSES = new Set([\n\t\"completion_conflict\",\n\t\"legacy_team_setup_roster_too_large\",\n\t\"project_scope_candidate_metadata_too_large\",\n\t\"project_scope_candidate_scan_too_large\",\n\t\"team_setup_completion_conflict\",\n\t\"team_setup_completion_invalid\",\n\t\"team_setup_completion_unavailable\",\n\t\"team_setup_confirmation_stale\",\n\t\"team_setup_roster_unavailable\",\n]);\n\nfunction loggableLocalCause(error: Error): string {\n\tif (LOGGABLE_LOCAL_CAUSES.has(error.message)) return error.message;\n\tif (error.name === \"AbortError\" || error.name === \"TimeoutError\") return error.name;\n\tif (/fetch failed/iu.test(error.message)) return \"fetch_failed\";\n\tif (/timed out|timeout/iu.test(error.message)) return \"timed_out\";\n\treturn `unclassified_error:${error.name || \"Error\"}`;\n}\n\nfunction errorChain(error: unknown): unknown[] {\n\tconst chain: unknown[] = [];\n\tlet current = error;\n\twhile (current && !chain.includes(current)) {\n\t\tchain.push(current);\n\t\tcurrent = current instanceof Error ? current.cause : undefined;\n\t}\n\treturn chain;\n}\n\nfunction remoteFailureReason(\n\tremote: RemoteCoordinatorRequestError,\n\tfallback: LegacyTeamSetupErrorReason | undefined,\n): LegacyTeamSetupErrorReason | undefined {\n\tif (\n\t\tremote.status === 404 &&\n\t\t(remote.code === \"not_found\" || remote.code.startsWith(\"non_json\"))\n\t) {\n\t\treturn \"coordinator_route_missing\";\n\t}\n\tif (remote.status === 400 && remote.code === \"completion_manifest_invalid\") {\n\t\treturn \"coordinator_rejected_manifest\";\n\t}\n\treturn fallback;\n}\n\nfunction teamSetupFinishFailureDetails(error: unknown): TeamSetupFinishFailureDetails {\n\tconst chain = errorChain(error);\n\tconst wrapper = chain.find(\n\t\t(item): item is TeamSetupFinishError => item instanceof TeamSetupFinishError,\n\t);\n\tconst remote = chain.find(\n\t\t(item): item is RemoteCoordinatorRequestError => item instanceof RemoteCoordinatorRequestError,\n\t);\n\tif (remote) {\n\t\tconst reason = remoteFailureReason(remote, wrapper?.reason);\n\t\treturn {\n\t\t\t...(reason ? { reason } : {}),\n\t\t\tcause: \"remote coordinator request failed\",\n\t\t\tstatus: remote.status,\n\t\t\tcode: loggableRemoteCode(remote.code),\n\t\t};\n\t}\n\t// Only typed scan-budget errors mean \"this device's history is too large\".\n\t// The shared roster_too_large string also fires for coordinator roster size\n\t// and draft device count, which are not local conditions.\n\tif (\n\t\tchain.some(\n\t\t\t(item) =>\n\t\t\t\titem instanceof LegacyTeamSetupRosterCapacityError ||\n\t\t\t\titem instanceof LocalProjectScanBudgetError,\n\t\t)\n\t) {\n\t\treturn {\n\t\t\treason: \"local_candidate_scan_budget_exceeded\",\n\t\t\tcause: \"local project candidate scan exceeded budget\",\n\t\t};\n\t}\n\tconst errorCause = chain.find(\n\t\t(item): item is Error => item instanceof Error && !(item instanceof TeamSetupFinishError),\n\t);\n\tconst cause = errorCause ? loggableLocalCause(errorCause) : \"unclassified_non_error\";\n\tif (wrapper?.reason) return { reason: wrapper.reason, cause };\n\tif (\n\t\terrorCause &&\n\t\t(errorCause.name === \"AbortError\" ||\n\t\t\terrorCause.name === \"TimeoutError\" ||\n\t\t\t/fetch failed|timed out|timeout/iu.test(errorCause.message))\n\t) {\n\t\treturn { reason: \"coordinator_unreachable\", cause };\n\t}\n\treturn { cause };\n}\n\nfunction warnTeamSetupFinishFailure(\n\terror: unknown,\n\tdetails: TeamSetupFinishFailureDetails,\n\tcontext: {\n\t\tcandidateRef: string;\n\t\tattemptId: string;\n\t\tapiCode: LegacyTeamSetupActivationErrorCode;\n\t\tredactValues?: readonly string[];\n\t},\n): void {\n\tif (\n\t\terrorChain(error).some((item) => item instanceof TeamSetupFinishError && item.alreadyLogged)\n\t) {\n\t\treturn;\n\t}\n\tconst safe = (value: string | number): string => {\n\t\tlet sanitized = String(value).replace(/[\\r\\n\\t]+/gu, \" \");\n\t\tfor (const secret of context.redactValues ?? []) {\n\t\t\tif (secret) sanitized = sanitized.replaceAll(secret, \"[redacted]\");\n\t\t}\n\t\treturn sanitized.replace(/https?:\\/\\/[^\\s]+/giu, (value) => {\n\t\t\ttry {\n\t\t\t\tconst url = new URL(value);\n\t\t\t\treturn `${url.protocol}//${url.host}`;\n\t\t\t} catch {\n\t\t\t\treturn \"[redacted-url]\";\n\t\t\t}\n\t\t});\n\t};\n\tconst fields = [\n\t\t`candidateRef=${safe(context.candidateRef)}`,\n\t\t`attemptId=${safe(context.attemptId)}`,\n\t\t`apiCode=${safe(context.apiCode)}`,\n\t\t`cause=${safe(details.cause)}`,\n\t\t...(details.reason ? [`reason=${safe(details.reason)}`] : []),\n\t\t...(details.status == null ? [] : [`status=${safe(details.status)}`]),\n\t\t...(details.code == null ? [] : [`code=${safe(details.code)}`]),\n\t];\n\tconsole.warn(`[team-setup finish] ${fields.join(\" \")}`);\n}\n\nfunction finishErrorResponse(\n\tcode: LegacyTeamSetupActivationErrorCode,\n\tdetails: TeamSetupFinishFailureDetails,\n): { error: LegacyTeamSetupActivationErrorCode; reason?: LegacyTeamSetupErrorReason } {\n\tconst reason = details.reason;\n\treturn reason ? { error: code, reason } : { error: code };\n}\n\ntype BoundedJsonResult = { ok: true; value: Record<string, unknown> } | { ok: false };\n\nasync function parseBoundedJsonObject(c: Context): Promise<BoundedJsonResult> {\n\tconst contentType = c.req.header(\"content-type\")?.split(\";\", 1)[0]?.trim().toLowerCase();\n\tif (contentType !== \"application/json\") return { ok: false };\n\tconst lengthHeader = c.req.header(\"content-length\");\n\tif (lengthHeader != null && !/^\\d+$/u.test(lengthHeader.trim())) return { ok: false };\n\tconst contentLength = lengthHeader == null ? null : Number(lengthHeader);\n\tif (contentLength != null && contentLength > MAX_MUTATION_BODY_BYTES) return { ok: false };\n\tconst body = c.req.raw.body;\n\tif (!body) return { ok: false };\n\tconst reader = body.getReader();\n\tconst chunks: Uint8Array[] = [];\n\tlet total = 0;\n\ttry {\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) break;\n\t\t\tif (!value) continue;\n\t\t\ttotal += value.byteLength;\n\t\t\tif (total > MAX_MUTATION_BODY_BYTES) {\n\t\t\t\tawait reader.cancel().catch(() => undefined);\n\t\t\t\treturn { ok: false };\n\t\t\t}\n\t\t\tchunks.push(value);\n\t\t}\n\t} catch {\n\t\treturn { ok: false };\n\t} finally {\n\t\treader.releaseLock();\n\t}\n\ttry {\n\t\tconst bytes = new Uint8Array(total);\n\t\tlet offset = 0;\n\t\tfor (const chunk of chunks) {\n\t\t\tbytes.set(chunk, offset);\n\t\t\toffset += chunk.byteLength;\n\t\t}\n\t\tconst parsed = JSON.parse(new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes)) as unknown;\n\t\treturn parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n\t\t\t? { ok: true, value: parsed as Record<string, unknown> }\n\t\t\t: { ok: false };\n\t} catch {\n\t\treturn { ok: false };\n\t}\n}\n\nfunction hasExactKeys(value: Record<string, unknown>, keys: readonly string[]): boolean {\n\tconst actual = Object.keys(value).toSorted();\n\tconst expected = keys.toSorted();\n\treturn actual.length === expected.length && actual.every((key, index) => key === expected[index]);\n}\n\nfunction detailResponse(\n\tstore: MemoryStore,\n\tdraft: LegacyTeamSetupDraftView,\n\tcandidate: LegacyTeamCandidateView = candidateFromDraft(draft),\n): LegacyTeamSetupDetailResponseV1 {\n\tlet unavailableReason: LegacyTeamSetupUnavailableReasonV1 | null = null;\n\tlet preview: ReturnType<typeof inspectLegacyTeamSetupActivation> | null = null;\n\tif (draft.state !== \"completed\") {\n\t\ttry {\n\t\t\tpreview = inspectLegacyTeamSetupActivation(store.db, {\n\t\t\t\tcandidateRef: draft.candidateRef,\n\t\t\t\tattemptId: draft.attemptId,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst code = apiErrorCode(error);\n\t\t\tif (code === \"team_setup_failed\") throw error;\n\t\t\tif (code === \"team_setup_projection_changed\") unavailableReason = \"team_setup_conflict\";\n\t\t\telse if (code !== \"team_setup_incomplete\") unavailableReason = code;\n\t\t}\n\t}\n\tif (preview) requireLegacyTeamSetupAccessDeltaWithinLimit(preview.accessDelta);\n\tconst safeDraft = viewerSafeDraft(store, draft);\n\tconst safePreview = preview ? viewerSafePreview(draft, safeDraft, preview) : null;\n\treturn projectLegacyTeamSetupView({\n\t\tversion: TEAM_SETUP_VERSION,\n\t\tcandidate: candidateSummaryForDraft(candidate, draft),\n\t\tdraftState: draft.state,\n\t\tattemptId: draft.attemptId,\n\t\tunresolvedDeviceCount: draft.unresolvedDeviceCount,\n\t\tunresolvedProjectCount: draft.unresolvedProjectCount,\n\t\t...safeDraft,\n\t\tunavailableReason,\n\t\tpreview: safePreview,\n\t});\n}\n\nfunction finishResponse(\n\tcandidateRef: string,\n\tresult: LegacyTeamSetupActivationResultV1,\n): LegacyTeamSetupFinishResponseV1 {\n\treturn {\n\t\tversion: TEAM_SETUP_VERSION,\n\t\tstatus: result.status,\n\t\tteamRef: teamRef(candidateRef, result.teamId),\n\t\tattemptId: result.attemptId,\n\t\taccessDeltaDigest: result.accessDeltaDigest,\n\t\tcompletedAt: result.completedAt,\n\t};\n}\n\nexport function teamSetupRoutes(options: TeamSetupRoutesOptions): Hono {\n\tconst app = new Hono();\n\tconst loadSnapshots =\n\t\toptions.loadLegacyTeamConfiguredGroupSnapshots ??\n\t\t((loadOptions?: LegacyTeamConfiguredGroupSnapshotLoadOptions) =>\n\t\t\tloadConfiguredLegacyTeamGroupSnapshotsWith(\n\t\t\t\toptions.snapshotLoaderDependencies ?? defaultSnapshotLoaderDependencies,\n\t\t\t\tloadOptions,\n\t\t\t\toptions.getStore,\n\t\t\t));\n\n\tasync function loadedSnapshots(\n\t\tcandidateRef?: string,\n\t\tdeadlineMs?: number,\n\t): Promise<LegacyTeamConfiguredGroupSnapshot[]> {\n\t\ttry {\n\t\t\treturn await loadSnapshots(\n\t\t\t\tcandidateRef || deadlineMs != null ? { candidateRef, deadlineMs } : undefined,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message === \"legacy_team_setup_roster_too_large\") {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tthrow safeCoordinatorError();\n\t\t}\n\t}\n\tconst loadedSummarySnapshots = createCachedSnapshotLoader(\n\t\t() => loadedSnapshots(),\n\t\tSUMMARY_SNAPSHOT_CACHE_TTL_MS,\n\t);\n\toptions.registerSummaryInvalidator?.(() => loadedSummarySnapshots.invalidate());\n\tconst completionDependencies =\n\t\toptions.completionDependencies === undefined\n\t\t\t? defaultCompletionDependencies\n\t\t\t: options.completionDependencies;\n\n\tinterface CompletionAuthorization {\n\t\tconfig: ReturnType<typeof readCoordinatorSyncConfig>;\n\t\tremoteUrl: string;\n\t\tconfiguredCoordinatorId: string;\n\t\tcurrentGroupIds: Set<string>;\n\t}\n\n\t/**\n\t * Reads the live coordinator configuration and the groups it currently\n\t * authorizes. Returns null when completion I/O is not configured or current\n\t * authorization cannot be proven.\n\t */\n\tfunction currentCompletionAuthorization(): CompletionAuthorization | null {\n\t\tconst config = (\n\t\t\toptions.readCoordinatorConfig ??\n\t\t\toptions.snapshotLoaderDependencies?.readConfig ??\n\t\t\treadCoordinatorSyncConfig\n\t\t)();\n\t\tconst remoteUrl = buildBaseUrl(config.syncCoordinatorUrl);\n\t\tif (!remoteUrl || !config.syncCoordinatorAdminSecret) return null;\n\t\tconst configuredCoordinatorId = normalizedCoordinatorId(remoteUrl);\n\t\tif (!configuredCoordinatorId) return null;\n\t\tlet currentGroupIds: Set<string>;\n\t\ttry {\n\t\t\tcurrentGroupIds = new Set(configuredGroupIds(config.syncCoordinatorGroups));\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t\treturn { config, remoteUrl, configuredCoordinatorId, currentGroupIds };\n\t}\n\n\t// Endpoint equivalence only: candidate identity stays bound to the persisted\n\t// coordinator string and is never rewritten from configuration.\n\tfunction authorizesGroup(\n\t\tauthorization: CompletionAuthorization,\n\t\tgroup: LegacyTeamCandidateGroupDescriptor,\n\t): boolean {\n\t\treturn (\n\t\t\tauthorization.currentGroupIds.has(group.groupId) &&\n\t\t\tnormalizedCoordinatorId(group.coordinatorId) === authorization.configuredCoordinatorId\n\t\t);\n\t}\n\n\t/**\n\t * Configuration may change while completion-list or roster requests are in\n\t * flight. Re-prove authorization for the exact coordinator and group right\n\t * before applying canonical policy, as the finish publication path does.\n\t */\n\tfunction stillAuthorizesGroup(\n\t\tinitial: CompletionAuthorization,\n\t\tgroup: LegacyTeamCandidateGroupDescriptor,\n\t): boolean {\n\t\tlet current: CompletionAuthorization | null;\n\t\ttry {\n\t\t\tcurrent = currentCompletionAuthorization();\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t\treturn (\n\t\t\tcurrent !== null &&\n\t\t\tcurrent.configuredCoordinatorId === initial.configuredCoordinatorId &&\n\t\t\tcurrent.remoteUrl === initial.remoteUrl &&\n\t\t\tcurrent.config.syncCoordinatorAdminSecret === initial.config.syncCoordinatorAdminSecret &&\n\t\t\tauthorizesGroup(current, group)\n\t\t);\n\t}\n\n\tfunction matchesGroupSnapshot(\n\t\tsnapshot: LegacyTeamConfiguredGroupSnapshot,\n\t\tgroup: LegacyTeamCandidateGroupDescriptor,\n\t): boolean {\n\t\treturn (\n\t\t\tsnapshot.groupId === group.groupId &&\n\t\t\tnormalizedCoordinatorId(snapshot.coordinatorId) ===\n\t\t\t\tnormalizedCoordinatorId(group.coordinatorId)\n\t\t);\n\t}\n\n\tfunction freshGroupKey(group: { coordinatorId: string; groupId: string }): string {\n\t\treturn `${normalizedCoordinatorId(group.coordinatorId) ?? group.coordinatorId}\\0${group.groupId}`;\n\t}\n\n\t/**\n\t * The snapshot loader keys candidates by the configured coordinator spelling,\n\t * while a persisted group may carry an equivalent but different spelling.\n\t * Ask for the roster under each spelling and match on normalized identity,\n\t * preserving the persisted candidate identity for everything else.\n\t */\n\tasync function loadFreshGroupSnapshot(\n\t\tgroup: LegacyTeamCandidateGroupDescriptor,\n\t\tremoteUrl: string,\n\t\tdeadlineMs: number,\n\t): Promise<LegacyTeamConfiguredGroupSnapshot | undefined> {\n\t\tconst candidateRefs = [\n\t\t\t...new Set([\n\t\t\t\tlegacyTeamCandidateId(remoteUrl, group.groupId),\n\t\t\t\tlegacyTeamCandidateId(group.coordinatorId, group.groupId),\n\t\t\t]),\n\t\t];\n\t\tfor (const candidateRef of candidateRefs) {\n\t\t\tconst snapshots = await loadedSnapshots(candidateRef, deadlineMs);\n\t\t\tconst matches = snapshots.filter((snapshot) => matchesGroupSnapshot(snapshot, group));\n\t\t\tif (matches.length > 1) throw new Error(\"team_setup_completion_invalid\");\n\t\t\tif (matches[0]) return matches[0];\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tfunction completionRecordCandidateRef(record: { manifest: unknown }): string | null {\n\t\tconst manifest = record.manifest;\n\t\tif (!manifest || typeof manifest !== \"object\" || Array.isArray(manifest)) return null;\n\t\tconst candidateRef = (manifest as { candidate_ref?: unknown }).candidate_ref;\n\t\treturn typeof candidateRef === \"string\" ? candidateRef : null;\n\t}\n\n\t// The coordinator lists every candidate a group has ever completed. A record\n\t// for a different candidate identity (an earlier coordinator address) is\n\t// historical context, not evidence about this candidate.\n\tfunction belongsToGroupCandidate(\n\t\trecord: { manifest: unknown },\n\t\tgroup: LegacyTeamCandidateGroupDescriptor,\n\t): boolean {\n\t\tconst candidateRef = completionRecordCandidateRef(record);\n\t\treturn (\n\t\t\tcandidateRef === null ||\n\t\t\tcandidateRef === legacyTeamCandidateId(group.coordinatorId, group.groupId)\n\t\t);\n\t}\n\n\t/**\n\t * Applies a canonical manifest with authorization re-proven inside the same\n\t * serialized section that guards the apply. Checking before the locks would\n\t * let a group removed while reconciliation waited on another policy\n\t * mutation still be applied once the queues open.\n\t */\n\tasync function applyCanonicalManifestIfStillAuthorized(\n\t\tstore: MemoryStore,\n\t\tauthorization: CompletionAuthorization,\n\t\tgroup: LegacyTeamCandidateGroupDescriptor,\n\t\tmanifest: CoordinatorLegacyTeamCompletionManifestV1,\n\t\tfreshRoster: LegacyTeamConfiguredGroupSnapshot[\"devices\"],\n\t): Promise<\"applied\" | \"unauthorized\" | \"claimed\"> {\n\t\tlet outcome: \"applied\" | \"unauthorized\" = \"unauthorized\";\n\t\tconst ran = await runCandidateMutation(\n\t\t\tstore.db,\n\t\t\tlegacyTeamCandidateId(group.coordinatorId, group.groupId),\n\t\t\t() =>\n\t\t\t\tserializeRecipientPolicyPublicationMutation(store.db, () =>\n\t\t\t\t\tserializeRecipientPolicyTeamMutation(store.db, manifest.team_id, () =>\n\t\t\t\t\t\tserializeRecipientPolicyCoordinatorGroupMutation(store.db, group.groupId, async () => {\n\t\t\t\t\t\t\tif (!stillAuthorizesGroup(authorization, group)) return;\n\t\t\t\t\t\t\tawait applyLegacyTeamSetupCompletionManifest(store.db, {\n\t\t\t\t\t\t\t\tcoordinatorId: group.coordinatorId,\n\t\t\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\t\t\tmanifest,\n\t\t\t\t\t\t\t\tfreshRoster,\n\t\t\t\t\t\t\t\trecipientPolicyLocksHeld: { publication: true, team: true, coordinatorGroup: true },\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\toutcome = \"applied\";\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t);\n\t\treturn ran ? outcome : \"claimed\";\n\t}\n\n\tasync function reconcileCompletions(\n\t\tstore: MemoryStore,\n\t\tgroups: LegacyTeamCandidateGroupDescriptor[],\n\t\treconciliationOptions: { isolateApplyFailures?: boolean } = {},\n\t): Promise<void> {\n\t\tif (!completionDependencies || groups.length === 0) return;\n\t\tlet authorization: CompletionAuthorization | null;\n\t\ttry {\n\t\t\tauthorization = currentCompletionAuthorization();\n\t\t} catch (error) {\n\t\t\tthrow new Error(completionApiError(error));\n\t\t}\n\t\t// If current authorization cannot be proven, skip completion I/O without\n\t\t// failing an otherwise serviceable persisted detail read.\n\t\tif (!authorization) return;\n\t\tconst { config, remoteUrl } = authorization;\n\t\tconst scopedGroups = groups.filter((group) => authorizesGroup(authorization, group));\n\t\tif (scopedGroups.length === 0) return;\n\t\tconst timeoutS = Math.max(1, config.syncCoordinatorTimeoutS);\n\t\ttry {\n\t\t\tconst reconciliationDeadlineMs = Date.now() + COORDINATOR_ROSTER_READ_BUDGET_MS;\n\t\t\tconst groupById = new Map(scopedGroups.map((group) => [group.groupId, group]));\n\t\t\tconst listCompletionRecords = (groupIds: string[]) =>\n\t\t\t\tretryTransientCoordinatorRead(\n\t\t\t\t\t(attemptTimeoutS) =>\n\t\t\t\t\t\tcompletionDependencies.list({\n\t\t\t\t\t\t\tgroupIds,\n\t\t\t\t\t\t\tremoteUrl,\n\t\t\t\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret,\n\t\t\t\t\t\t\ttimeoutS: attemptTimeoutS,\n\t\t\t\t\t\t}),\n\t\t\t\t\ttimeoutS,\n\t\t\t\t\treconciliationDeadlineMs,\n\t\t\t\t);\n\t\t\tconst scopedGroupIds = [...new Set(scopedGroups.map((group) => group.groupId))];\n\t\t\tlet records: Awaited<ReturnType<LegacyTeamCompletionDependencies[\"list\"]>>;\n\t\t\ttry {\n\t\t\t\trecords = await listCompletionRecords(scopedGroupIds);\n\t\t\t} catch (error) {\n\t\t\t\t// Older coordinators do not expose completion reconciliation. Read routes\n\t\t\t\t// remain usable, and best-effort publication below still lets upgraded\n\t\t\t\t// peers observe a locally completed migration.\n\t\t\t\tif (isUnsupportedCompletionQuery(error)) {\n\t\t\t\t\trecords = [];\n\t\t\t\t} else if (\n\t\t\t\t\treconciliationOptions.isolateApplyFailures &&\n\t\t\t\t\tisUnattributableCompletionBatchError(error)\n\t\t\t\t) {\n\t\t\t\t\t// One corrupt or mixed-version record must not hide every healthy\n\t\t\t\t\t// group's setup state. Re-query per group so the decode failure\n\t\t\t\t\t// stays attributable; a group whose own record cannot be decoded is\n\t\t\t\t\t// skipped, matching the unprovable-binding path below.\n\t\t\t\t\trecords = await listCompletionRecordsPerGroup(scopedGroupIds, listCompletionRecords);\n\t\t\t\t} else {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst freshGroupByKey = new Map<string, LegacyTeamConfiguredGroupSnapshot>();\n\t\t\tif (records.length > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tconst onlyGroup = scopedGroups.length === 1 ? scopedGroups[0] : undefined;\n\t\t\t\t\tconst freshGroups = onlyGroup\n\t\t\t\t\t\t? [await loadFreshGroupSnapshot(onlyGroup, remoteUrl, reconciliationDeadlineMs)]\n\t\t\t\t\t\t: await loadedSnapshots(undefined, reconciliationDeadlineMs);\n\t\t\t\t\tfor (const freshGroup of freshGroups) {\n\t\t\t\t\t\tif (!freshGroup) continue;\n\t\t\t\t\t\tconst key = freshGroupKey(freshGroup);\n\t\t\t\t\t\tif (freshGroupByKey.has(key)) throw new Error(\"team_setup_completion_invalid\");\n\t\t\t\t\t\tfreshGroupByKey.set(key, freshGroup);\n\t\t\t\t\t}\n\t\t\t\t} catch (error) {\n\t\t\t\t\tfor (const record of records) {\n\t\t\t\t\t\tconst group = groupById.get(record.group_id);\n\t\t\t\t\t\tif (!group || !belongsToGroupCandidate(record, group)) continue;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tvalidateLegacyTeamSetupCompletionManifestBinding(record.manifest, {\n\t\t\t\t\t\t\t\tcoordinatorId: group.coordinatorId,\n\t\t\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} catch (bindingError) {\n\t\t\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) throw bindingError;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlet canonicalManifest: ReturnType<typeof validateLegacyTeamSetupCompletionManifest>;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tcanonicalManifest = validateLegacyTeamSetupCompletionManifest(record.manifest, {\n\t\t\t\t\t\t\t\tcoordinatorId: group.coordinatorId,\n\t\t\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} catch (validationError) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tconst contained = await runCandidateMutation(\n\t\t\t\t\t\t\t\t\tstore.db,\n\t\t\t\t\t\t\t\t\tlegacyTeamCandidateId(group.coordinatorId, group.groupId),\n\t\t\t\t\t\t\t\t\t() =>\n\t\t\t\t\t\t\t\t\t\tcontainLegacyTeamSetupCompletionConflict(store.db, {\n\t\t\t\t\t\t\t\t\t\t\tcoordinatorId: group.coordinatorId,\n\t\t\t\t\t\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tif (!contained) {\n\t\t\t\t\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) throw validationError;\n\t\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} catch (containmentError) {\n\t\t\t\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) throw containmentError;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) throw validationError;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst localManifest = reconstructLegacyTeamSetupCompletionManifest(store.db, {\n\t\t\t\t\t\t\t\tcandidateRef: canonicalManifest.candidate_ref,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\tcanonicalCoordinatorLegacyTeamCompletionManifestJson(localManifest) ===\n\t\t\t\t\t\t\t\tcanonicalCoordinatorLegacyTeamCompletionManifestJson(canonicalManifest)\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\tareLegacyTeamSetupCompletionPolicyFactsAdditivelyCompatible(\n\t\t\t\t\t\t\t\t\tlocalManifest,\n\t\t\t\t\t\t\t\t\tcanonicalManifest,\n\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t// Missing or invalid local completion state must not remain active when\n\t\t\t\t\t\t\t// a valid coordinator winner cannot be applied safely.\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tawait runCandidateMutation(store.db, canonicalManifest.candidate_ref, () =>\n\t\t\t\t\t\t\t\tcontainLegacyTeamSetupCompletionConflict(store.db, {\n\t\t\t\t\t\t\t\t\tcoordinatorId: group.coordinatorId,\n\t\t\t\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} catch (containmentError) {\n\t\t\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) throw containmentError;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) throw error;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst coordinatorCompletionGroupIds = new Set<string>();\n\t\t\tfor (const record of records) {\n\t\t\t\tconst group = groupById.get(record.group_id);\n\t\t\t\tif (!group) throw new Error(\"team_setup_completion_invalid\");\n\t\t\t\tif (!belongsToGroupCandidate(record, group)) continue;\n\t\t\t\ttry {\n\t\t\t\t\tvalidateLegacyTeamSetupCompletionManifestBinding(record.manifest, {\n\t\t\t\t\t\tcoordinatorId: group.coordinatorId,\n\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t});\n\t\t\t\t} catch (bindingError) {\n\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) throw bindingError;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tlet canonicalManifest: ReturnType<typeof validateLegacyTeamSetupCompletionManifest>;\n\t\t\t\ttry {\n\t\t\t\t\tcanonicalManifest = validateLegacyTeamSetupCompletionManifest(record.manifest, {\n\t\t\t\t\t\tcoordinatorId: group.coordinatorId,\n\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t});\n\t\t\t\t} catch (validationError) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait runCandidateMutation(\n\t\t\t\t\t\t\tstore.db,\n\t\t\t\t\t\t\tlegacyTeamCandidateId(group.coordinatorId, group.groupId),\n\t\t\t\t\t\t\t() =>\n\t\t\t\t\t\t\t\tcontainLegacyTeamSetupCompletionConflict(store.db, {\n\t\t\t\t\t\t\t\t\tcoordinatorId: group.coordinatorId,\n\t\t\t\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t} catch (containmentError) {\n\t\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) throw containmentError;\n\t\t\t\t\t}\n\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) throw validationError;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tcoordinatorCompletionGroupIds.add(record.group_id);\n\t\t\t\ttry {\n\t\t\t\t\tlet freshGroup = freshGroupByKey.get(freshGroupKey(group));\n\t\t\t\t\tif (!freshGroup && scopedGroups.length > 1) {\n\t\t\t\t\t\tif (remainingCoordinatorTimeoutS(timeoutS, reconciliationDeadlineMs) == null) {\n\t\t\t\t\t\t\tthrow new Error(\"team_setup_roster_unavailable\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfreshGroup = await loadFreshGroupSnapshot(group, remoteUrl, reconciliationDeadlineMs);\n\t\t\t\t\t}\n\t\t\t\t\tif (!freshGroup) {\n\t\t\t\t\t\tconst contained = await runCandidateMutation(\n\t\t\t\t\t\t\tstore.db,\n\t\t\t\t\t\t\tlegacyTeamCandidateId(group.coordinatorId, group.groupId),\n\t\t\t\t\t\t\t() =>\n\t\t\t\t\t\t\t\tcontainLegacyTeamSetupCompletionConflict(store.db, {\n\t\t\t\t\t\t\t\t\tcoordinatorId: group.coordinatorId,\n\t\t\t\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (!contained) {\n\t\t\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) {\n\t\t\t\t\t\t\t\tthrow new Error(\"team_setup_completion_invalid\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthrow new Error(\"team_setup_completion_invalid\");\n\t\t\t\t\t}\n\t\t\t\t\tconst applied = await applyCanonicalManifestIfStillAuthorized(\n\t\t\t\t\t\tstore,\n\t\t\t\t\t\tauthorization,\n\t\t\t\t\t\tgroup,\n\t\t\t\t\t\tcanonicalManifest,\n\t\t\t\t\t\tfreshGroup.devices,\n\t\t\t\t\t);\n\t\t\t\t\tif (applied !== \"applied\") continue;\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) throw error;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const group of scopedGroups) {\n\t\t\t\tif (coordinatorCompletionGroupIds.has(group.groupId)) continue;\n\t\t\t\tconst publicationTimeoutS = remainingCoordinatorTimeoutS(\n\t\t\t\t\ttimeoutS,\n\t\t\t\t\treconciliationDeadlineMs,\n\t\t\t\t);\n\t\t\t\tif (publicationTimeoutS == null) break;\n\t\t\t\tif (\n\t\t\t\t\t!hasCompletedLegacyTeamSetup(\n\t\t\t\t\t\tstore,\n\t\t\t\t\t\tlegacyTeamCandidateId(group.coordinatorId, group.groupId),\n\t\t\t\t\t)\n\t\t\t\t) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst candidateRef = legacyTeamCandidateId(group.coordinatorId, group.groupId);\n\t\t\t\tlet reconstructionFailed = false;\n\t\t\t\ttry {\n\t\t\t\t\tconst published = await runCandidateMutation(store.db, candidateRef, () =>\n\t\t\t\t\t\tserializeRecipientPolicyPublicationMutation(store.db, () =>\n\t\t\t\t\t\t\tserializeRecipientPolicyTeamMutation(\n\t\t\t\t\t\t\t\tstore.db,\n\t\t\t\t\t\t\t\tdeterministicPolicyTeamId(candidateRef),\n\t\t\t\t\t\t\t\tasync () => {\n\t\t\t\t\t\t\t\t\tlet manifest: ReturnType<typeof reconstructLegacyTeamSetupCompletionManifest>;\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tmanifest = reconstructLegacyTeamSetupCompletionManifest(store.db, {\n\t\t\t\t\t\t\t\t\t\t\tcandidateRef,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t\t\treconstructionFailed = true;\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t// Publication sends identity and policy data to the coordinator;\n\t\t\t\t\t\t\t\t\t// re-prove the destination is still the configured one.\n\t\t\t\t\t\t\t\t\tif (!stillAuthorizesGroup(authorization, group)) {\n\t\t\t\t\t\t\t\t\t\treconstructionFailed = true;\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tawait completionDependencies.create({\n\t\t\t\t\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\t\t\t\t\tmanifest,\n\t\t\t\t\t\t\t\t\t\tremoteUrl,\n\t\t\t\t\t\t\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret,\n\t\t\t\t\t\t\t\t\t\ttimeoutS: publicationTimeoutS,\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\tif (!published || reconstructionFailed) continue;\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Publishing an existing local completion is best-effort. The bounded\n\t\t\t\t\t// list/apply pass above remains authoritative and fail-closed.\n\t\t\t\t\tif (completionApiError(error) !== \"team_setup_completion_conflict\") continue;\n\t\t\t\t\tconst getCompletion = completionDependencies.get;\n\t\t\t\t\tlet canonicalManifest: Awaited<ReturnType<NonNullable<typeof getCompletion>>> = null;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tif (!getCompletion) throw new Error(\"team_setup_completion_conflict\");\n\t\t\t\t\t\tcanonicalManifest = await retryTransientCoordinatorRead(\n\t\t\t\t\t\t\t(attemptTimeoutS) =>\n\t\t\t\t\t\t\t\tgetCompletion({\n\t\t\t\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\t\t\t\tcandidateRef,\n\t\t\t\t\t\t\t\t\tremoteUrl,\n\t\t\t\t\t\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret,\n\t\t\t\t\t\t\t\t\ttimeoutS: attemptTimeoutS,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\ttimeoutS,\n\t\t\t\t\t\t\treconciliationDeadlineMs,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (!canonicalManifest) throw new Error(\"team_setup_completion_conflict\");\n\t\t\t\t\t} catch {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst contained = await runCandidateMutation(store.db, candidateRef, () =>\n\t\t\t\t\t\t\t\tcontainLegacyTeamSetupCompletionConflict(store.db, {\n\t\t\t\t\t\t\t\t\tcoordinatorId: group.coordinatorId,\n\t\t\t\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (!contained) {\n\t\t\t\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) {\n\t\t\t\t\t\t\t\t\tthrow new Error(\"team_setup_completion_conflict\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (containmentError) {\n\t\t\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) throw containmentError;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) {\n\t\t\t\t\t\t\tthrow new Error(\"team_setup_completion_conflict\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst freshGroup = await loadFreshGroupSnapshot(\n\t\t\t\t\t\t\tgroup,\n\t\t\t\t\t\t\tremoteUrl,\n\t\t\t\t\t\t\treconciliationDeadlineMs,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (!freshGroup) throw new Error(\"team_setup_roster_unavailable\");\n\t\t\t\t\t\tconst applied = await applyCanonicalManifestIfStillAuthorized(\n\t\t\t\t\t\t\tstore,\n\t\t\t\t\t\t\tauthorization,\n\t\t\t\t\t\t\tgroup,\n\t\t\t\t\t\t\tcanonicalManifest,\n\t\t\t\t\t\t\tfreshGroup.devices,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (applied !== \"applied\") continue;\n\t\t\t\t\t} catch (applyError) {\n\t\t\t\t\t\tif (applyError instanceof LegacyTeamSetupAdditiveConvergenceError) {\n\t\t\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) throw applyError;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst contained = await runCandidateMutation(store.db, candidateRef, () =>\n\t\t\t\t\t\t\t\tcontainLegacyTeamSetupCompletionConflict(store.db, {\n\t\t\t\t\t\t\t\t\tcoordinatorId: group.coordinatorId,\n\t\t\t\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (!contained) {\n\t\t\t\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) {\n\t\t\t\t\t\t\t\t\tthrow new Error(\"team_setup_completion_conflict\", { cause: applyError });\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (containmentError) {\n\t\t\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) throw containmentError;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!reconciliationOptions.isolateApplyFailures) {\n\t\t\t\t\t\t\tthrow new Error(\"team_setup_completion_conflict\", { cause: applyError });\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthrow new Error(completionApiError(error));\n\t\t}\n\t}\n\tasync function loadedCandidateSnapshots(\n\t\tcandidateRef: string,\n\t\tloadOptions: {\n\t\t\tallowCachedSummaryFallback?: boolean;\n\t\t\tdeadlineMs?: number;\n\t\t\tinvalidateSummaryCache?: boolean;\n\t\t} = {},\n\t): Promise<LegacyTeamConfiguredGroupSnapshot[]> {\n\t\tconst allowCachedSummaryFallback = loadOptions.allowCachedSummaryFallback ?? false;\n\t\tconst invalidateSummaryCache = loadOptions.invalidateSummaryCache ?? true;\n\t\tif (invalidateSummaryCache) loadedSummarySnapshots.invalidate();\n\t\ttry {\n\t\t\treturn await loadedSnapshots(candidateRef, loadOptions.deadlineMs);\n\t\t} catch (error) {\n\t\t\tif (!allowCachedSummaryFallback) throw error;\n\t\t\tconst cachedGroups = loadedSummarySnapshots.peek();\n\t\t\tif (!cachedGroups) throw error;\n\t\t\tconst matching = cachedGroups.filter(\n\t\t\t\t(group) => legacyTeamCandidateId(group.coordinatorId, group.groupId) === candidateRef,\n\t\t\t);\n\t\t\tif (matching.length !== 1) throw error;\n\t\t\treturn matching;\n\t\t} finally {\n\t\t\tif (invalidateSummaryCache) loadedSummarySnapshots.invalidate();\n\t\t}\n\t}\n\n\tfunction persistedCompletionGroup(\n\t\tstore: MemoryStore,\n\t\tcandidateRef: string,\n\t): LegacyTeamCandidateGroupDescriptor | null {\n\t\tconst row = store.db\n\t\t\t.prepare(\n\t\t\t\t`SELECT coordinator_id, group_id FROM legacy_team_setup_drafts\n\t\t\t\t WHERE candidate_id = ? ORDER BY rowid DESC LIMIT 1`,\n\t\t\t)\n\t\t\t.get(candidateRef) as { coordinator_id: string; group_id: string } | undefined;\n\t\tif (!row || legacyTeamCandidateId(row.coordinator_id, row.group_id) !== candidateRef)\n\t\t\treturn null;\n\t\treturn { coordinatorId: row.coordinator_id, groupId: row.group_id };\n\t}\n\n\tapp.get(\"/api/sync/team-setup/v1\", async (c) => {\n\t\tlet groups: LegacyTeamConfiguredGroupSnapshot[];\n\t\ttry {\n\t\t\tgroups = await loadedSummarySnapshots();\n\t\t} catch (error) {\n\t\t\tconst code = apiErrorCode(error);\n\t\t\treturn c.json({ error: code }, errorStatus(code));\n\t\t}\n\t\ttry {\n\t\t\tconst store = options.getStore();\n\t\t\treadPureCandidateViews(store, groups);\n\t\t\tawait reconcileCompletions(store, groups, { isolateApplyFailures: true });\n\t\t\tconst response = {\n\t\t\t\tversion: TEAM_SETUP_VERSION,\n\t\t\t\tcandidates: readPureCandidateViews(store, groups)\n\t\t\t\t\t.map(candidateSummary)\n\t\t\t\t\t.filter(\n\t\t\t\t\t\t(candidate): candidate is LegacyTeamSetupPendingCandidateSummaryV1 =>\n\t\t\t\t\t\t\tcandidate.status !== \"ready\",\n\t\t\t\t\t),\n\t\t\t} satisfies LegacyTeamSetupSummaryResponseV1;\n\t\t\treturn c.json(response);\n\t\t} catch (error) {\n\t\t\tconst code = apiErrorCode(error);\n\t\t\treturn c.json({ error: code }, errorStatus(code));\n\t\t}\n\t});\n\n\tapp.get(\"/api/sync/team-setup/v1/:candidateRef\", async (c) => {\n\t\tconst candidateRef = c.req.param(\"candidateRef\");\n\t\tif (!CANDIDATE_REF_PATTERN.test(candidateRef)) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\n\t\ttry {\n\t\t\tconst store = options.getStore();\n\t\t\tlet draft = getLegacyTeamSetupDraft(store.db, candidateRef);\n\t\t\tconst terminal = hasCompletedLegacyTeamSetup(store, candidateRef);\n\t\t\tlet candidateGroupsForCompletion: LegacyTeamConfiguredGroupSnapshot[] | null = null;\n\t\t\tif (terminal && draft?.state !== \"completed\") {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\t}\n\t\t\tlet candidate: LegacyTeamCandidateView;\n\t\t\tif (draft && (draft.state !== \"completed\" || terminal)) {\n\t\t\t\tcandidate = candidateFromDraft(draft);\n\t\t\t} else {\n\t\t\t\t// Revalidation may replace a completed draft, so it must never decide\n\t\t\t\t// against a stale summary-cache roster. Cache fallback remains safe for\n\t\t\t\t// candidates that have no persisted attempt yet.\n\t\t\t\tconst groups = await loadedCandidateSnapshots(candidateRef, {\n\t\t\t\t\tallowCachedSummaryFallback: draft == null,\n\t\t\t\t\tinvalidateSummaryCache: false,\n\t\t\t\t});\n\t\t\t\tconst candidateGroups = groups.filter(\n\t\t\t\t\t(group) => legacyTeamCandidateId(group.coordinatorId, group.groupId) === candidateRef,\n\t\t\t\t);\n\t\t\t\tcandidateGroupsForCompletion = candidateGroups;\n\t\t\t\tconst postLoadDraft = getLegacyTeamSetupDraft(store.db, candidateRef);\n\t\t\t\tif (hasCompletedLegacyTeamSetup(store, candidateRef)) {\n\t\t\t\t\tif (postLoadDraft?.state !== \"completed\") {\n\t\t\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\t\t\t}\n\t\t\t\t\tdraft = postLoadDraft;\n\t\t\t\t\tcandidate = candidateFromDraft(postLoadDraft);\n\t\t\t\t} else {\n\t\t\t\t\tconst discoveredCandidate = discoverCandidates(store, candidateGroups).find(\n\t\t\t\t\t\t(item) => item.candidateRef === candidateRef,\n\t\t\t\t\t);\n\t\t\t\t\tif (!discoveredCandidate) {\n\t\t\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\t\t\t}\n\t\t\t\t\tcandidate = discoveredCandidate;\n\t\t\t\t\tdraft = getLegacyTeamSetupDraft(store.db, candidateRef);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!draft) return c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\tconst cachedCandidateGroups = loadedSummarySnapshots\n\t\t\t\t.peek()\n\t\t\t\t?.filter(\n\t\t\t\t\t(group) => legacyTeamCandidateId(group.coordinatorId, group.groupId) === candidateRef,\n\t\t\t\t);\n\t\t\tlet completionGroups: LegacyTeamCandidateGroupDescriptor[] | null =\n\t\t\t\tcandidateGroupsForCompletion ??\n\t\t\t\t(cachedCandidateGroups?.length ? cachedCandidateGroups : null);\n\t\t\tif (!completionGroups) {\n\t\t\t\tconst persistedGroup = persistedCompletionGroup(store, candidateRef);\n\t\t\t\tcompletionGroups = persistedGroup ? [persistedGroup] : null;\n\t\t\t}\n\t\t\tconst terminalBeforeReconciliation = hasCompletedLegacyTeamSetup(store, candidateRef);\n\t\t\tif (completionGroups) await reconcileCompletions(store, completionGroups);\n\t\t\tdraft = getLegacyTeamSetupDraft(store.db, candidateRef);\n\t\t\tif (\n\t\t\t\t!draft ||\n\t\t\t\t(!terminalBeforeReconciliation && hasCompletedLegacyTeamSetup(store, candidateRef))\n\t\t\t) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\t}\n\t\t\tif (completionGroups) candidate = candidateFromDraft(draft);\n\n\t\t\treturn c.json(detailResponse(store, draft, candidate));\n\t\t} catch (error) {\n\t\t\tconst code = apiErrorCode(error);\n\t\t\treturn c.json({ error: code }, errorStatus(code));\n\t\t}\n\t});\n\n\tapp.put(\"/api/sync/team-setup/v1/:candidateRef/devices/:deviceRef/assignment\", async (c) => {\n\t\tconst candidateRef = c.req.param(\"candidateRef\");\n\t\tconst deviceRef = c.req.param(\"deviceRef\");\n\t\tif (!CANDIDATE_REF_PATTERN.test(candidateRef) || !DEVICE_REF_PATTERN.test(deviceRef)) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\tconst parsed = await parseBoundedJsonObject(c);\n\t\tif (\n\t\t\t!parsed.ok ||\n\t\t\t!hasExactKeys(parsed.value, [\"attemptId\", \"expectation\", \"targetIdentityRef\"])\n\t\t) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\tconst { attemptId, expectation, targetIdentityRef } = parsed.value;\n\t\tif (\n\t\t\ttypeof attemptId !== \"string\" ||\n\t\t\t!ATTEMPT_ID_PATTERN.test(attemptId) ||\n\t\t\ttypeof targetIdentityRef !== \"string\" ||\n\t\t\t!IDENTITY_REF_PATTERN.test(targetIdentityRef) ||\n\t\t\t!expectation ||\n\t\t\ttypeof expectation !== \"object\" ||\n\t\t\tArray.isArray(expectation)\n\t\t) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\ttry {\n\t\t\tconst store = options.getStore();\n\t\t\tconst draft = getLegacyTeamSetupDraft(store.db, candidateRef);\n\t\t\tif (!draft) return c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\tif (draft.state !== \"completed\" && hasCompletedLegacyTeamSetup(store, candidateRef)) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tif (draft.attemptId !== attemptId) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tif (draft.state === \"completed\") {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tconst device = draft.devices.find((item) => item.deviceRef === deviceRef);\n\t\t\tif (!device) return c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\tconst submittedExpectation = expectation as Record<string, unknown>;\n\t\t\tconst expectationMatches =\n\t\t\t\tdevice.expectation.kind === \"absent\"\n\t\t\t\t\t? hasExactKeys(submittedExpectation, [\"kind\"]) && submittedExpectation.kind === \"absent\"\n\t\t\t\t\t: hasExactKeys(submittedExpectation, [\"assignmentVersion\", \"identityRef\", \"kind\"]) &&\n\t\t\t\t\t\tsubmittedExpectation.kind === \"existing\" &&\n\t\t\t\t\t\tsubmittedExpectation.assignmentVersion === device.expectation.assignmentVersion &&\n\t\t\t\t\t\tsubmittedExpectation.identityRef ===\n\t\t\t\t\t\t\trequiredIdentityRef(candidateRef, device.expectation.identityId);\n\t\t\tif (!expectationMatches) {\n\t\t\t\treturn c.json({ error: \"team_setup_assignment_changed\" as const }, 409);\n\t\t\t}\n\t\t\tconst target = identityChoices(store, candidateRef).find(\n\t\t\t\t(choice) => choice.identityRef === targetIdentityRef,\n\t\t\t);\n\t\t\tif (!target) return c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\tconst releaseMutation = claimCandidateMutation(store.db, candidateRef);\n\t\t\tif (!releaseMutation) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn c.json(\n\t\t\t\t\tprojectMutationAtomically(\n\t\t\t\t\t\tstore,\n\t\t\t\t\t\t() =>\n\t\t\t\t\t\t\tsetLegacyTeamSetupDeviceAssignment(store.db, {\n\t\t\t\t\t\t\t\tattemptId,\n\t\t\t\t\t\t\t\tdeviceRef,\n\t\t\t\t\t\t\t\ttargetIdentityId: target.identityId,\n\t\t\t\t\t\t\t\texpectation: device.expectation,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t(draft) => detailResponse(store, draft),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} finally {\n\t\t\t\treleaseMutation();\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst code = apiErrorCode(error);\n\t\t\treturn c.json({ error: code }, errorStatus(code));\n\t\t}\n\t});\n\n\tapp.put(\"/api/sync/team-setup/v1/:candidateRef/devices/:deviceRef/decision\", async (c) => {\n\t\tconst candidateRef = c.req.param(\"candidateRef\");\n\t\tconst deviceRef = c.req.param(\"deviceRef\");\n\t\tif (!CANDIDATE_REF_PATTERN.test(candidateRef) || !DEVICE_REF_PATTERN.test(deviceRef)) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\tconst parsed = await parseBoundedJsonObject(c);\n\t\tif (!parsed.ok) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\tconst { attemptId, decision, expectedTargetIdentityRef } = parsed.value;\n\t\tif (\n\t\t\ttypeof attemptId !== \"string\" ||\n\t\t\t!ATTEMPT_ID_PATTERN.test(attemptId) ||\n\t\t\t!([\"included\", \"excluded\", \"removed\"] as unknown[]).includes(decision) ||\n\t\t\t(decision === \"included\"\n\t\t\t\t? !hasExactKeys(parsed.value, [\"attemptId\", \"decision\", \"expectedTargetIdentityRef\"]) ||\n\t\t\t\t\ttypeof expectedTargetIdentityRef !== \"string\" ||\n\t\t\t\t\t!IDENTITY_REF_PATTERN.test(expectedTargetIdentityRef)\n\t\t\t\t: !hasExactKeys(parsed.value, [\"attemptId\", \"decision\"]))\n\t\t) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\ttry {\n\t\t\tconst store = options.getStore();\n\t\t\tconst draft = getLegacyTeamSetupDraft(store.db, candidateRef);\n\t\t\tif (!draft) return c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\tif (draft.state !== \"completed\" && hasCompletedLegacyTeamSetup(store, candidateRef)) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tif (draft.attemptId !== attemptId) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tif (draft.state === \"completed\") {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tconst device = draft.devices.find((item) => item.deviceRef === deviceRef);\n\t\t\tif (!device) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\t}\n\t\t\tif (\n\t\t\t\tdecision === \"included\" &&\n\t\t\t\t(device.targetIdentityId === null ||\n\t\t\t\t\trequiredIdentityRef(candidateRef, device.targetIdentityId) !== expectedTargetIdentityRef)\n\t\t\t) {\n\t\t\t\treturn c.json({ error: \"team_setup_assignment_changed\" as const }, 409);\n\t\t\t}\n\t\t\tconst releaseMutation = claimCandidateMutation(store.db, candidateRef);\n\t\t\tif (!releaseMutation) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn c.json(\n\t\t\t\t\tprojectMutationAtomically(\n\t\t\t\t\t\tstore,\n\t\t\t\t\t\t() =>\n\t\t\t\t\t\t\tsetLegacyTeamSetupDeviceDecision(store.db, {\n\t\t\t\t\t\t\t\tattemptId,\n\t\t\t\t\t\t\t\tdeviceRef,\n\t\t\t\t\t\t\t\tdecision: decision as \"included\" | \"excluded\" | \"removed\",\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t(draft) => detailResponse(store, draft),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} finally {\n\t\t\t\treleaseMutation();\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst code = apiErrorCode(error);\n\t\t\treturn c.json({ error: code }, errorStatus(code));\n\t\t}\n\t});\n\n\tapp.delete(\"/api/sync/team-setup/v1/:candidateRef/devices/:deviceRef/decision\", async (c) => {\n\t\tconst candidateRef = c.req.param(\"candidateRef\");\n\t\tconst deviceRef = c.req.param(\"deviceRef\");\n\t\tif (!CANDIDATE_REF_PATTERN.test(candidateRef) || !DEVICE_REF_PATTERN.test(deviceRef)) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\tconst parsed = await parseBoundedJsonObject(c);\n\t\tif (!parsed.ok || !hasExactKeys(parsed.value, [\"attemptId\"])) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\tconst { attemptId } = parsed.value;\n\t\tif (typeof attemptId !== \"string\" || !ATTEMPT_ID_PATTERN.test(attemptId)) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\ttry {\n\t\t\tconst store = options.getStore();\n\t\t\tconst draft = getLegacyTeamSetupDraft(store.db, candidateRef);\n\t\t\tif (!draft) return c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\tif (draft.state !== \"completed\" && hasCompletedLegacyTeamSetup(store, candidateRef)) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tif (draft.attemptId !== attemptId) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tif (draft.state === \"completed\") {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tif (!draft.devices.some((item) => item.deviceRef === deviceRef)) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\t}\n\t\t\tconst releaseMutation = claimCandidateMutation(store.db, candidateRef);\n\t\t\tif (!releaseMutation) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn c.json(\n\t\t\t\t\tprojectMutationAtomically(\n\t\t\t\t\t\tstore,\n\t\t\t\t\t\t() => clearLegacyTeamSetupDeviceDecision(store.db, { attemptId, deviceRef }),\n\t\t\t\t\t\t(draft) => detailResponse(store, draft),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} finally {\n\t\t\t\treleaseMutation();\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst code = apiErrorCode(error);\n\t\t\treturn c.json({ error: code }, errorStatus(code));\n\t\t}\n\t});\n\n\tapp.put(\"/api/sync/team-setup/v1/:candidateRef/projects/:projectRef/mapping\", async (c) => {\n\t\tconst candidateRef = c.req.param(\"candidateRef\");\n\t\tconst projectRef = c.req.param(\"projectRef\");\n\t\tif (!CANDIDATE_REF_PATTERN.test(candidateRef) || !PROJECT_REF_PATTERN.test(projectRef)) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\tconst parsed = await parseBoundedJsonObject(c);\n\t\tif (!parsed.ok || !hasExactKeys(parsed.value, [\"attemptId\", \"resolvedProjectRef\"])) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\tconst { attemptId, resolvedProjectRef } = parsed.value;\n\t\tif (\n\t\t\ttypeof attemptId !== \"string\" ||\n\t\t\t!ATTEMPT_ID_PATTERN.test(attemptId) ||\n\t\t\ttypeof resolvedProjectRef !== \"string\" ||\n\t\t\t!RESOLVED_PROJECT_REF_PATTERN.test(resolvedProjectRef)\n\t\t) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\ttry {\n\t\t\tconst store = options.getStore();\n\t\t\tconst draft = getLegacyTeamSetupDraft(store.db, candidateRef);\n\t\t\tif (!draft) return c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\tif (draft.state !== \"completed\" && hasCompletedLegacyTeamSetup(store, candidateRef)) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tif (draft.attemptId !== attemptId) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tif (draft.state === \"completed\") {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tconst project = draft.projects.find((item) => item.projectRef === projectRef);\n\t\t\tif (!project) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\t}\n\t\t\tif (project.resolution === \"deterministic\") {\n\t\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t\t}\n\t\t\tconst target = projectMappingChoices(store).find(\n\t\t\t\t(choice) =>\n\t\t\t\t\tlegacyTeamResolvedProjectRef(projectRef, choice.projectIdentity) === resolvedProjectRef,\n\t\t\t);\n\t\t\tif (!target) return c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\tconst releaseMutation = claimCandidateMutation(store.db, candidateRef);\n\t\t\tif (!releaseMutation) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn c.json(\n\t\t\t\t\tprojectMutationAtomically(\n\t\t\t\t\t\tstore,\n\t\t\t\t\t\t() =>\n\t\t\t\t\t\t\tsetLegacyTeamSetupProjectMapping(store.db, {\n\t\t\t\t\t\t\t\tattemptId,\n\t\t\t\t\t\t\t\tprojectRef,\n\t\t\t\t\t\t\t\tresolvedProjectIdentity: target.projectIdentity,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t(draft) => detailResponse(store, draft),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} finally {\n\t\t\t\treleaseMutation();\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst code = apiErrorCode(error);\n\t\t\treturn c.json({ error: code }, errorStatus(code));\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/team-setup/v1/:candidateRef/refresh\", async (c) => {\n\t\tconst candidateRef = c.req.param(\"candidateRef\");\n\t\tif (!CANDIDATE_REF_PATTERN.test(candidateRef)) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\tconst parsed = await parseBoundedJsonObject(c);\n\t\tif (!parsed.ok || !hasExactKeys(parsed.value, [])) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\tlet store: MemoryStore;\n\t\ttry {\n\t\t\tstore = options.getStore();\n\t\t\tconst currentDraft = getLegacyTeamSetupDraft(store.db, candidateRef);\n\t\t\tif (currentDraft?.state === \"completed\" || hasCompletedLegacyTeamSetup(store, candidateRef)) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst code = apiErrorCode(error);\n\t\t\treturn c.json({ error: code }, errorStatus(code));\n\t\t}\n\t\tlet groups: LegacyTeamConfiguredGroupSnapshot[];\n\t\ttry {\n\t\t\tgroups = await loadMutableCandidateSnapshots(store, candidateRef, () =>\n\t\t\t\tloadedCandidateSnapshots(candidateRef),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconst code = apiErrorCode(error);\n\t\t\treturn c.json({ error: code }, errorStatus(code));\n\t\t}\n\t\tif (\n\t\t\tgroups.filter(\n\t\t\t\t(group) => legacyTeamCandidateId(group.coordinatorId, group.groupId) === candidateRef,\n\t\t\t).length === 0\n\t\t) {\n\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t}\n\t\ttry {\n\t\t\tconst releaseMutation = claimCandidateMutation(store.db, candidateRef);\n\t\t\tif (!releaseMutation) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\treturn c.json(\n\t\t\t\t\tprojectMutationAtomically(\n\t\t\t\t\t\tstore,\n\t\t\t\t\t\t() => {\n\t\t\t\t\t\t\tconst currentDraft = getLegacyTeamSetupDraft(store.db, candidateRef);\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\tcurrentDraft?.state === \"completed\" ||\n\t\t\t\t\t\t\t\thasCompletedLegacyTeamSetup(store, candidateRef)\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tthrow new Error(\"team_setup_confirmation_stale\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn refreshLegacyTeamCandidate(\n\t\t\t\t\t\t\t\tstore.db,\n\t\t\t\t\t\t\t\t{ projection: projectionOptions(store), groups },\n\t\t\t\t\t\t\t\tcandidateRef,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t},\n\t\t\t\t\t\t(draft) => detailResponse(store, draft),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} finally {\n\t\t\t\treleaseMutation();\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst code = apiErrorCode(error);\n\t\t\treturn c.json({ error: code }, errorStatus(code));\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/team-setup/v1/:candidateRef/finish\", async (c) => {\n\t\tconst candidateRef = c.req.param(\"candidateRef\");\n\t\tif (!CANDIDATE_REF_PATTERN.test(candidateRef)) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\tconst parsed = await parseBoundedJsonObject(c);\n\t\tif (!parsed.ok) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\tconst finishKeys = [\n\t\t\t\"attemptId\",\n\t\t\t\"confirmedAccessDeltaDigest\",\n\t\t\t\"confirmedViewerAccessDeltaDigest\",\n\t\t\t\"finishDigest\",\n\t\t] as const;\n\t\tif (!hasExactKeys(parsed.value, finishKeys)) {\n\t\t\treturn Object.keys(parsed.value).every((key) =>\n\t\t\t\tfinishKeys.includes(key as (typeof finishKeys)[number]),\n\t\t\t)\n\t\t\t\t? c.json({ error: \"team_setup_confirmation_stale\" as const }, 409)\n\t\t\t\t: c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\tconst {\n\t\t\tattemptId,\n\t\t\tconfirmedAccessDeltaDigest,\n\t\t\tconfirmedViewerAccessDeltaDigest,\n\t\t\tfinishDigest,\n\t\t} = parsed.value;\n\t\tif (\n\t\t\ttypeof attemptId !== \"string\" ||\n\t\t\t!ATTEMPT_ID_PATTERN.test(attemptId) ||\n\t\t\ttypeof finishDigest !== \"string\" ||\n\t\t\t!FINISH_DIGEST_PATTERN.test(finishDigest) ||\n\t\t\ttypeof confirmedAccessDeltaDigest !== \"string\" ||\n\t\t\t!ACCESS_DELTA_DIGEST_PATTERN.test(confirmedAccessDeltaDigest) ||\n\t\t\ttypeof confirmedViewerAccessDeltaDigest !== \"string\" ||\n\t\t\t!VIEWER_ACCESS_DELTA_DIGEST_PATTERN.test(confirmedViewerAccessDeltaDigest)\n\t\t) {\n\t\t\treturn c.json({ error: \"team_setup_incomplete\" as const }, 400);\n\t\t}\n\t\tlet releaseMutation: (() => void) | undefined;\n\t\tlet releasePublicationMutation: (() => void) | undefined;\n\t\tlet releaseActorMutations: (() => void) | undefined;\n\t\tlet finishLogRedactValues: readonly string[] = [];\n\t\ttry {\n\t\t\tconst store = options.getStore();\n\t\t\tconst draft = getLegacyTeamSetupDraft(store.db, candidateRef);\n\t\t\tif (!draft) return c.json({ error: \"team_setup_confirmation_stale\" as const }, 404);\n\t\t\tif (draft.state !== \"completed\" && hasCompletedLegacyTeamSetup(store, candidateRef)) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tif (draft.attemptId !== attemptId) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tconst replay = replayLegacyTeamSetupActivation(store.db, {\n\t\t\t\tcandidateRef,\n\t\t\t\tattemptId,\n\t\t\t\tfinishDigest,\n\t\t\t\tconfirmedAccessDeltaDigest,\n\t\t\t});\n\t\t\tif (replay) return c.json(finishResponse(candidateRef, replay));\n\t\t\tif (draft.state === \"completed\") {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tconst preview = previewLegacyTeamSetupActivation(store.db, {\n\t\t\t\tcandidateRef,\n\t\t\t\tattemptId: draft.attemptId,\n\t\t\t});\n\t\t\trequireLegacyTeamSetupAccessDeltaWithinLimit(preview.accessDelta);\n\t\t\tconst safeDraft = viewerSafeDraft(store, draft);\n\t\t\tconst currentViewerDigest = viewerAccessDeltaDigest(\n\t\t\t\tviewerSafeAccessDelta(candidateRef, preview.accessDelta, {\n\t\t\t\t\tteamDisplayName: draft.displayName,\n\t\t\t\t\t...safeDraft,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tif (currentViewerDigest !== confirmedViewerAccessDeltaDigest) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tconst freshGroups = await loadedCandidateSnapshots(candidateRef);\n\t\t\tconst matchingGroups = freshGroups.filter(\n\t\t\t\t(group) => legacyTeamCandidateId(group.coordinatorId, group.groupId) === candidateRef,\n\t\t\t);\n\t\t\tif (matchingGroups.length !== 1) throw safeCoordinatorError();\n\t\t\tconst group = matchingGroups[0];\n\t\t\tif (!group) throw safeCoordinatorError();\n\t\t\treleaseMutation = claimCandidateMutation(store.db, candidateRef) ?? undefined;\n\t\t\tif (!releaseMutation) {\n\t\t\t\t// An identical request may be committing right now. Wait for it and\n\t\t\t\t// return its immutable result instead of a stale-confirmation error.\n\t\t\t\tawait candidateMutationSettled(store.db, candidateRef);\n\t\t\t\tconst overlappingReplay = replayLegacyTeamSetupActivation(store.db, {\n\t\t\t\t\tcandidateRef,\n\t\t\t\t\tattemptId,\n\t\t\t\t\tfinishDigest,\n\t\t\t\t\tconfirmedAccessDeltaDigest,\n\t\t\t\t});\n\t\t\t\tif (overlappingReplay) return c.json(finishResponse(candidateRef, overlappingReplay));\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\t// The pre-claim replay lookup raced an in-flight commit; recheck under the claim.\n\t\t\tconst claimedReplay = replayLegacyTeamSetupActivation(store.db, {\n\t\t\t\tcandidateRef,\n\t\t\t\tattemptId,\n\t\t\t\tfinishDigest,\n\t\t\t\tconfirmedAccessDeltaDigest,\n\t\t\t});\n\t\t\tif (claimedReplay) return c.json(finishResponse(candidateRef, claimedReplay));\n\t\t\tconst claimedDraft = getLegacyTeamSetupDraft(store.db, candidateRef);\n\t\t\tif (!claimedDraft || claimedDraft.attemptId !== attemptId) {\n\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t}\n\t\t\tconst publicationDeadlineMs = Date.now() + COORDINATOR_ROSTER_READ_BUDGET_MS;\n\t\t\treleasePublicationMutation = await claimRecipientPolicyPublicationMutation(store.db);\n\t\t\t// Every identity the activation reads or writes is part of the immutable\n\t\t\t// publication winner: the target of each included device and the existing\n\t\t\t// assignment of every reviewed device (including excluded or removed ones,\n\t\t\t// whose current assignment the access delta depends on). These locks cover\n\t\t\t// coordinator creation, conflict recovery, and local application.\n\t\t\treleaseActorMutations = await claimRecipientPolicyActorMutations(\n\t\t\t\tstore.db,\n\t\t\t\tclaimedDraft.devices.flatMap((device) => [\n\t\t\t\t\t...(device.decision === \"included\" && device.targetIdentityId\n\t\t\t\t\t\t? [device.targetIdentityId]\n\t\t\t\t\t\t: []),\n\t\t\t\t\t...(device.existingIdentityId ? [device.existingIdentityId] : []),\n\t\t\t\t]),\n\t\t\t);\n\t\t\tconst response = await serializeRecipientPolicyTeamMutation(\n\t\t\t\tstore.db,\n\t\t\t\tdeterministicPolicyTeamId(candidateRef),\n\t\t\t\t() =>\n\t\t\t\t\tserializeRecipientPolicyCoordinatorGroupMutation(store.db, group.groupId, async () => {\n\t\t\t\t\t\tlet authorization: CompletionAuthorization | null;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tauthorization = currentCompletionAuthorization();\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tthrow new Error(completionApiError(error));\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!completionDependencies || !authorization) {\n\t\t\t\t\t\t\tthrow new Error(\"team_setup_completion_unavailable\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!authorizesGroup(authorization, group)) {\n\t\t\t\t\t\t\tthrow new Error(\"team_setup_completion_invalid\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst { config, remoteUrl } = authorization;\n\t\t\t\t\t\tfinishLogRedactValues = [config.syncCoordinatorAdminSecret];\n\t\t\t\t\t\tconst freshGroup = await loadFreshGroupSnapshot(\n\t\t\t\t\t\t\tgroup,\n\t\t\t\t\t\t\tremoteUrl,\n\t\t\t\t\t\t\tpublicationDeadlineMs,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (!freshGroup) {\n\t\t\t\t\t\t\tthrow new TeamSetupFinishError(\n\t\t\t\t\t\t\t\t\"team_setup_roster_unavailable\",\n\t\t\t\t\t\t\t\t\"coordinator_roster_unavailable\",\n\t\t\t\t\t\t\t\tfalse,\n\t\t\t\t\t\t\t\tnew Error(\"coordinator roster unavailable\"),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!stillAuthorizesGroup(authorization, group)) {\n\t\t\t\t\t\t\tthrow new Error(\"team_setup_completion_invalid\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst projectInventory = legacyTeamCandidateProjectInventory(\n\t\t\t\t\t\t\tstore.db,\n\t\t\t\t\t\t\tprojectionOptions(store),\n\t\t\t\t\t\t\tcandidateRef,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst freshPreview = inspectFreshLegacyTeamSetupActivation(store.db, {\n\t\t\t\t\t\t\tcandidateRef,\n\t\t\t\t\t\t\tattemptId,\n\t\t\t\t\t\t\tfreshRoster: freshGroup.devices,\n\t\t\t\t\t\t\tprojectInventory,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tfreshPreview.finishDigest !== finishDigest ||\n\t\t\t\t\t\t\tfreshPreview.accessDeltaDigest !== confirmedAccessDeltaDigest\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst freshDraft = getLegacyTeamSetupDraft(store.db, candidateRef);\n\t\t\t\t\t\tif (!freshDraft || freshDraft.attemptId !== attemptId) {\n\t\t\t\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst safeFreshDraft = viewerSafeDraft(store, freshDraft);\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tviewerAccessDeltaDigest(\n\t\t\t\t\t\t\t\tviewerSafeAccessDelta(candidateRef, freshPreview.accessDelta, {\n\t\t\t\t\t\t\t\t\tteamDisplayName: freshDraft.displayName,\n\t\t\t\t\t\t\t\t\t...safeFreshDraft,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t) !== confirmedViewerAccessDeltaDigest\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\treturn c.json({ error: \"team_setup_confirmation_stale\" as const }, 409);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst completedAt = new Date().toISOString();\n\t\t\t\t\t\tconst proposedManifest = deriveLegacyTeamSetupCompletionManifest(store.db, {\n\t\t\t\t\t\t\tcandidateRef,\n\t\t\t\t\t\t\tattemptId,\n\t\t\t\t\t\t\tcompletedAt,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst timeoutS = Math.max(1, config.syncCoordinatorTimeoutS);\n\t\t\t\t\t\tconst publicationTimeoutS = remainingCoordinatorTimeoutS(\n\t\t\t\t\t\t\ttimeoutS,\n\t\t\t\t\t\t\tpublicationDeadlineMs,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (publicationTimeoutS == null) {\n\t\t\t\t\t\t\tthrow new Error(\"team_setup_completion_unavailable\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tlet canonicalManifest: typeof proposedManifest;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tcanonicalManifest = validateLegacyTeamSetupCompletionManifest(\n\t\t\t\t\t\t\t\t(\n\t\t\t\t\t\t\t\t\tawait completionDependencies.create({\n\t\t\t\t\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\t\t\t\t\tmanifest: proposedManifest,\n\t\t\t\t\t\t\t\t\t\tremoteUrl,\n\t\t\t\t\t\t\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret,\n\t\t\t\t\t\t\t\t\t\ttimeoutS: publicationTimeoutS,\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t).manifest,\n\t\t\t\t\t\t\t\t{ coordinatorId: group.coordinatorId, groupId: group.groupId },\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\tcanonicalCoordinatorLegacyTeamCompletionManifestJson(canonicalManifest) !==\n\t\t\t\t\t\t\t\tcanonicalCoordinatorLegacyTeamCompletionManifestJson(proposedManifest)\n\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\tthrow new Error(\"team_setup_completion_conflict\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tconst code = completionApiError(error);\n\t\t\t\t\t\t\tconst details = teamSetupFinishFailureDetails(error);\n\t\t\t\t\t\t\tconst getCompletion = completionDependencies.get;\n\t\t\t\t\t\t\tif (code !== \"team_setup_completion_conflict\" || !getCompletion) {\n\t\t\t\t\t\t\t\twarnTeamSetupFinishFailure(error, details, {\n\t\t\t\t\t\t\t\t\tcandidateRef,\n\t\t\t\t\t\t\t\t\tattemptId,\n\t\t\t\t\t\t\t\t\tapiCode: code,\n\t\t\t\t\t\t\t\t\tredactValues: finishLogRedactValues,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tthrow new TeamSetupFinishError(code, details.reason, true, error);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tconst existing = await retryTransientCoordinatorRead(\n\t\t\t\t\t\t\t\t\t(attemptTimeoutS) =>\n\t\t\t\t\t\t\t\t\t\tgetCompletion({\n\t\t\t\t\t\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\t\t\t\t\t\tcandidateRef,\n\t\t\t\t\t\t\t\t\t\t\tremoteUrl,\n\t\t\t\t\t\t\t\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret,\n\t\t\t\t\t\t\t\t\t\t\ttimeoutS: attemptTimeoutS,\n\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\ttimeoutS,\n\t\t\t\t\t\t\t\t\tpublicationDeadlineMs,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tif (!existing) throw new Error(\"team_setup_completion_conflict\");\n\t\t\t\t\t\t\t\tcanonicalManifest = validateLegacyTeamSetupCompletionManifest(existing, {\n\t\t\t\t\t\t\t\t\tcoordinatorId: group.coordinatorId,\n\t\t\t\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t// A conflict can mean an earlier request committed before its response was lost.\n\t\t\t\t\t\t\t\t// The matching policy digest identifies that winner; its publication timestamp\n\t\t\t\t\t\t\t\t// is coordinator-owned metadata and must be applied unchanged.\n\t\t\t\t\t\t\t\tif (canonicalManifest.finish_digest !== proposedManifest.finish_digest) {\n\t\t\t\t\t\t\t\t\tthrow new Error(\"team_setup_completion_conflict\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} catch (recoveryError) {\n\t\t\t\t\t\t\t\tthrow new TeamSetupFinishError(\n\t\t\t\t\t\t\t\t\tcompletionApiError(recoveryError),\n\t\t\t\t\t\t\t\t\tteamSetupFinishFailureDetails(recoveryError).reason,\n\t\t\t\t\t\t\t\t\tfalse,\n\t\t\t\t\t\t\t\t\trecoveryError,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Publication is the commit point. Apply its immutable winner after binding\n\t\t\t\t\t\t// each included device to the current coordinator roster evidence.\n\t\t\t\t\t\t// If this reload fails, reconciliation can apply the published winner later.\n\t\t\t\t\t\tlet postPublicationGroup: LegacyTeamConfiguredGroupSnapshot | undefined;\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tpostPublicationGroup = await loadFreshGroupSnapshot(\n\t\t\t\t\t\t\t\tgroup,\n\t\t\t\t\t\t\t\tremoteUrl,\n\t\t\t\t\t\t\t\tpublicationDeadlineMs,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\tif (legacyTeamSetupApiErrorCode(error) === \"team_setup_completion_invalid\") {\n\t\t\t\t\t\t\t\tthrow new TeamSetupFinishError(\n\t\t\t\t\t\t\t\t\t\"team_setup_roster_unavailable\",\n\t\t\t\t\t\t\t\t\t\"coordinator_roster_unavailable\",\n\t\t\t\t\t\t\t\t\tfalse,\n\t\t\t\t\t\t\t\t\terror,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!postPublicationGroup) {\n\t\t\t\t\t\t\tthrow new TeamSetupFinishError(\n\t\t\t\t\t\t\t\t\"team_setup_roster_unavailable\",\n\t\t\t\t\t\t\t\t\"coordinator_roster_unavailable\",\n\t\t\t\t\t\t\t\tfalse,\n\t\t\t\t\t\t\t\tnew Error(\"coordinator roster unavailable\"),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst result = await applyLegacyTeamSetupCompletionManifestAndReturnActivation(\n\t\t\t\t\t\t\tstore.db,\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tcoordinatorId: group.coordinatorId,\n\t\t\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\t\t\tfreshRoster: postPublicationGroup.devices,\n\t\t\t\t\t\t\t\tmanifest: canonicalManifest,\n\t\t\t\t\t\t\t\texpectedDraftManifest: proposedManifest,\n\t\t\t\t\t\t\t\trecipientPolicyLocksHeld: {\n\t\t\t\t\t\t\t\t\tpublication: true,\n\t\t\t\t\t\t\t\t\tteam: true,\n\t\t\t\t\t\t\t\t\tcoordinatorGroup: true,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn c.json(finishResponse(candidateRef, result));\n\t\t\t\t\t}),\n\t\t\t);\n\t\t\treturn response;\n\t\t} catch (error) {\n\t\t\tconst code = apiErrorCode(error);\n\t\t\tconst details = teamSetupFinishFailureDetails(error);\n\t\t\twarnTeamSetupFinishFailure(error, details, {\n\t\t\t\tcandidateRef,\n\t\t\t\tattemptId,\n\t\t\t\tapiCode: code,\n\t\t\t\tredactValues: finishLogRedactValues,\n\t\t\t});\n\t\t\treturn c.json(finishErrorResponse(code, details), errorStatus(code));\n\t\t} finally {\n\t\t\treleaseActorMutations?.();\n\t\t\treleasePublicationMutation?.();\n\t\t\treleaseMutation?.();\n\t\t}\n\t});\n\n\treturn app;\n}\n","/**\n * Sync routes — status, peers, actors, attempts, pairing, mutations.\n */\n\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { readFileSync } from \"node:fs\";\nimport { hostname, networkInterfaces } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport type {\n\tCoordinatorBootstrapGrantVerification,\n\tCoordinatorConsumedTeamInvite,\n\tCoordinatorEnrollment,\n\tCoordinatorEnrollmentReconcileResult,\n\tCoordinatorScope,\n\tCoordinatorScopeMembership,\n\tDeviceIdentityBindingCommitRequestV1,\n\tDeviceIdentityBindingPreviewRequestV1,\n\tDeviceIdentityCoordinatorEvidence,\n\tMaintenanceJobSnapshot,\n\tMemoryStore,\n\tProjectScopeGuardrailWarning,\n\tReassignScopeCapability,\n\tRecipientPolicyCoordinatorEffectReceipt,\n\tRecipientPolicyOnboardingPreviewV1,\n\tRecipientPolicyPeerCapability,\n\tRecipientPolicyReconcileResult,\n\tRecipientPolicyReconcilerEffects,\n\tRecipientPolicyReviewDecisionV1,\n\tRecipientPolicyReviewResolveRequestV1,\n\tRecipientReviewedIntentV1,\n\tReplicationOp,\n\tSemanticIndexDiagnostics,\n\tShareOperationLifecycleStepInput,\n\tShareOperationPlan,\n\tSharePersonIntent,\n\tShareProjectIntent,\n} from \"@codemem/core\";\nimport {\n\tACCESS_CLEANUP_OP_TYPE,\n\taddSyncScopeToBoundary,\n\tanalyzeProjectScopeMappingChangeGuardrails,\n\tapplyReplicationOps,\n\tbuildAuthHeaders,\n\tbuildBaseUrl,\n\tbuildDirectPeerAuthHeaders,\n\tCoordinatorReciprocalApprovalRequestChangedError,\n\tcanonicalWorkspaceIdentity,\n\tclaimRecipientPolicyActorMutations,\n\tclaimRecipientPolicyPublicationMutation,\n\tcleanupNonces,\n\tcommitDeviceIdentityBindings,\n\tcommitRecipientPolicyEdges,\n\tcoordinatorArchiveGroupAction,\n\tcoordinatorCreateAddDeviceInviteAction,\n\tcoordinatorCreateGroupAction,\n\tcoordinatorCreateInviteAction,\n\tcoordinatorCreateScopeAction,\n\tcoordinatorDisableDeviceAction,\n\tcoordinatorEnableDeviceAction,\n\tcoordinatorGrantScopeMembershipAction,\n\tcoordinatorImportInviteAction,\n\tcoordinatorListBootstrapGrantsAction,\n\tcoordinatorListConsumedTeamInvitesAction,\n\tcoordinatorListDevicesAction,\n\tcoordinatorListGroupsAction,\n\tcoordinatorListJoinRequestsAction,\n\tcoordinatorListReviewedRecipientInviteEvidenceAction,\n\tcoordinatorListScopeMembershipsAction,\n\tcoordinatorListScopesAction,\n\tcoordinatorRemoveDeviceAction,\n\tcoordinatorRenameDeviceAction,\n\tcoordinatorRenameGroupAction,\n\tcoordinatorReviewJoinRequestAction,\n\tcoordinatorRevokeBootstrapGrantAction,\n\tcoordinatorRevokeScopeMembershipAction,\n\tcoordinatorStatusSnapshot,\n\tcoordinatorUnarchiveGroupAction,\n\tcoordinatorUpdateScopeAction,\n\tcountShareableProjectMemories,\n\tcreateCoordinatorReciprocalApproval,\n\tDEFAULT_TIME_WINDOW_S,\n\tdecodeInvitePayload,\n\tdefaultSpaceScopeIdForGroup,\n\tdeleteProjectScopeSettingsMapping,\n\tdiagnoseStalePeerReceivedRows,\n\tensureDeviceIdentity,\n\texecuteShareProvisioning,\n\textractInvitePayload,\n\textractReplicationOps,\n\ttype FilterReplicationSkipped,\n\tfilterReplicationOpsForSyncWithStatus,\n\tfingerprintPublicKey,\n\tformatHostPort,\n\tfriendlyDeviceName,\n\tgetCoordinatorEnrollmentReconciliationIssueSummary,\n\tgetCoordinatorGroupPreference,\n\tgetRecipientPolicyAuthorityState,\n\tgetSemanticIndexDiagnostics,\n\tgetSyncResetState,\n\ttype InboundScopeRejectionPeerSummary,\n\tinviteTokenDigest,\n\tisPeerTrustBindingCompatible,\n\tisProjectSyncEnablementError,\n\tisScopedSyncCapability,\n\tLEGACY_SHARED_REVIEW_SCOPE_ID,\n\tLOCAL_DEFAULT_SCOPE_ID,\n\tLOCAL_SYNC_CAPABILITY,\n\tLOCAL_SYNC_FEATURES,\n\tlistAuthorizedScopesForPeer,\n\tlistCoordinatorJoinRequests,\n\tlistDeviceIdentityInventory,\n\tlistInboundScopeRejections,\n\tlistLegacyRecipientPolicyProjections,\n\tlistMaintenanceJobs,\n\tlistPerPeerScopeSyncState,\n\tlistProjectScopeCandidates,\n\tlistProjectScopeInventory,\n\tlistProjectScopeSettingsMappings,\n\tlistRecipientPolicyIntent,\n\tlistRecipientPolicyReview,\n\tlistSharingDomainSettingsScopes,\n\tloadMemorySnapshotPageForPeer,\n\tloadReplicationOpsForPeer,\n\tlookupCoordinatorPeers,\n\tmergeAddresses,\n\tmigrateRecipientPolicyIntent,\n\tnegotiateSyncCapability,\n\tnormalizeAddress,\n\tnormalizeHumanPresentationName,\n\tnormalizeSyncCapability,\n\tnormalizeSyncFeatures,\n\tnormalizeTeammateName,\n\tparseAcceptedProjectIntent,\n\tparseReassignScopePayload,\n\tparseRecipientPolicyEdgeCommitRequest,\n\tparseSyncScopeRequest,\n\tpersistShareOperation,\n\tpersonalScopeGrantStatusForPeer,\n\tplanShareOperation,\n\tpreviewDeviceIdentityBindings,\n\tpreviewRecipientPolicyEdges,\n\tpreviewRecipientPolicyOnboarding,\n\tpreviewRecipientPolicyOnboardingFromReviewedIntent,\n\tprojectShareLifecycle,\n\tRecipientPolicyEdgeRequestError,\n\tRecipientPolicyTeamRenameError,\n\treadCodememConfigFile,\n\treadCoordinatorSyncConfig,\n\treassignProjectScopeInventoryProject,\n\trecipientInviteAuthoritativeIdentityId,\n\trecipientReviewedIntentDigest,\n\treconcileCoordinatorEnrollmentSnapshot,\n\treconcileRecipientPolicyProject,\n\treconcileShareOperationAcceptance,\n\trecordHighestObservedDirectSignatureVersion,\n\trecordNonce,\n\trefreshAuthorizedCoordinatorPeerTrust,\n\trefreshConfiguredScopeMembershipCache,\n\trejectInboundScopeFailures,\n\trenameRecipientPolicyTeam,\n\trequestJson,\n\tresolveRecipientPolicyReview,\n\tresolveRecipientPolicyReviewBulk,\n\trunSyncPass,\n\tSCOPE_MEMBERSHIP_REVOCATION_LIMITATION,\n\tSYNC_AUTHORIZATION_REFRESH_HEADER,\n\tSYNC_CAPABILITY_HEADER,\n\tSYNC_FEATURES_HEADER,\n\tSYNC_SCOPE_QUERY_PARAM,\n\tschema,\n\tserializeRecipientPolicyTeamMutation,\n\tsummarizeInboundScopeRejections,\n\tsupportsSyncFeature,\n\tsyncScopeResetRequiredPayload,\n\tupdatePeerAddresses,\n\tupsertCoordinatorGroupPreference,\n\tupsertProjectScopeSettingsMapping,\n\tVERSION,\n\tverifyDirectPeerSignature,\n\tverifyRecipientReviewedIntent,\n\tverifySignature,\n\twriteCodememConfigFile,\n} from \"@codemem/core\";\nimport { and, count, desc, eq, max, ne } from \"drizzle-orm\";\nimport { drizzle } from \"drizzle-orm/better-sqlite3\";\nimport { type Context, Hono } from \"hono\";\nimport { queryBool, queryInt, safeJsonList } from \"../helpers.js\";\nimport type { InMemoryRequestRateLimiter } from \"../request-rate-limit.js\";\nimport { legacyTeamCandidateGroupDescriptors, normalizedCoordinatorId } from \"./team-setup.js\";\n\ntype StoreFactory = () => MemoryStore;\nexport type DeviceIdentityCoordinatorEvidenceLoader =\n\t() => Promise<DeviceIdentityCoordinatorEvidence>;\nexport interface SyncRoutesOptions {\n\tloadDeviceIdentityCoordinatorEvidence?: DeviceIdentityCoordinatorEvidenceLoader;\n\tonRecipientPolicyTeamRenamed?: () => void;\n\treadCoordinatorConfig?: typeof readCoordinatorSyncConfig;\n\trenameCoordinatorGroup?: typeof coordinatorRenameGroupAction;\n}\ntype SyncRuntimeStatus = {\n\tphase:\n\t\t| \"starting\"\n\t\t| \"running\"\n\t\t| \"stopping\"\n\t\t| \"error\"\n\t\t| \"disabled\"\n\t\t| \"rebootstrapping\"\n\t\t| \"needs_attention\"\n\t\t| null;\n\tdetail?: string | null;\n};\n\ntype SafeSkippedSyncDetail = Pick<\n\tFilterReplicationSkipped,\n\t\"reason\" | \"skipped_count\" | \"scope_id\" | \"project\" | \"visibility\"\n>;\n\nfunction safeSkippedSyncDetail(\n\tdetail: FilterReplicationSkipped | null | undefined,\n): SafeSkippedSyncDetail | null {\n\tif (!detail) return null;\n\treturn {\n\t\treason: detail.reason,\n\t\tskipped_count: detail.skipped_count,\n\t\tscope_id: detail.scope_id ?? null,\n\t\tproject: detail.project ?? null,\n\t\tvisibility: detail.visibility ?? null,\n\t};\n}\n\ninterface SyncProtocolRouteOptions {\n\trouteRateLimit?: {\n\t\tlimiter: InMemoryRequestRateLimiter;\n\t\treadLimit: number;\n\t\tmutationLimit: number;\n\t\tunauthenticatedReadLimit: number;\n\t\tunauthenticatedMutationLimit: number;\n\t};\n}\n\nconst SYNC_STALE_AFTER_SECONDS = 10 * 60;\nconst SYNC_PROTOCOL_VERSION = \"2\";\nconst LEGACY_SYNC_ACTOR_DISPLAY_NAME = \"Legacy synced peer\";\nconst LEGACY_SHARED_WORKSPACE_ID = \"shared:legacy\";\n\n/**\n * Attempt to decode a pasted string as a device-pairing payload.\n *\n * Returns:\n * - `{ kind: \"pair\", ... }` when the payload base64-decodes to JSON with\n * the expected pairing shape AND the fingerprint matches the public\n * key.\n * - `{ kind: \"invalid-pair\", error }` when the payload looked like a\n * pairing payload but failed validation — the caller should 400 this\n * rather than falling back to coordinator-invite handling.\n * - `null` when the string is not a pairing payload at all.\n */\nfunction tryParsePairingPayload(value: string):\n\t| {\n\t\t\tkind: \"pair\";\n\t\t\tdevice_id: string;\n\t\t\tfingerprint: string;\n\t\t\tpublic_key: string;\n\t\t\taddresses: string[];\n\t }\n\t| { kind: \"invalid-pair\"; error: string }\n\t| null {\n\t// Accept both shapes the CLI can emit:\n\t// - raw JSON (`codemem sync pair --payload-only`)\n\t// - base64-encoded JSON (the inner blob inside the shell pipe wrapper)\n\tlet parsed: Record<string, unknown>;\n\tif (value.trimStart().startsWith(\"{\")) {\n\t\ttry {\n\t\t\tparsed = JSON.parse(value) as Record<string, unknown>;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t} else {\n\t\tlet decoded: string;\n\t\ttry {\n\t\t\tdecoded = Buffer.from(value, \"base64\").toString(\"utf8\");\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t\tif (!decoded?.trimStart().startsWith(\"{\")) return null;\n\t\ttry {\n\t\t\tparsed = JSON.parse(decoded) as Record<string, unknown>;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\tconst deviceId = String(parsed.device_id ?? \"\").trim();\n\tconst fingerprint = String(parsed.fingerprint ?? \"\").trim();\n\tconst publicKey = String(parsed.public_key ?? \"\").trim();\n\t// If the JSON doesn't carry any of the pairing discriminators, treat\n\t// it as a different kind of payload (e.g. a coordinator invite happened\n\t// to be JSON-encoded directly). Let the caller keep trying.\n\tif (!deviceId && !fingerprint && !publicKey) return null;\n\tconst rawAddresses = Array.isArray(parsed.addresses) ? parsed.addresses : [];\n\tconst addresses = rawAddresses\n\t\t.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0)\n\t\t.map((item) => item.trim());\n\tif (!deviceId || !fingerprint || !publicKey || addresses.length === 0) {\n\t\treturn {\n\t\t\tkind: \"invalid-pair\",\n\t\t\terror: \"Pairing payload missing device_id, fingerprint, public_key, or addresses\",\n\t\t};\n\t}\n\tif (fingerprintPublicKey(publicKey) !== fingerprint) {\n\t\treturn { kind: \"invalid-pair\", error: \"Pairing payload fingerprint mismatch\" };\n\t}\n\treturn {\n\t\tkind: \"pair\",\n\t\tdevice_id: deviceId,\n\t\tfingerprint,\n\t\tpublic_key: publicKey,\n\t\taddresses,\n\t};\n}\n\ntype CoordinatorAdminReadiness = \"not_configured\" | \"partial\" | \"ready\";\n\nfunction coordinatorAdminStatusPayload(config = readCoordinatorSyncConfig()) {\n\tconst groups = config.syncCoordinatorGroups;\n\tconst activeGroup = groups[0] ?? null;\n\tconst hasUrl = Boolean(config.syncCoordinatorUrl);\n\tconst hasGroups = groups.length > 0;\n\tconst hasAdminSecret = Boolean(config.syncCoordinatorAdminSecret);\n\tlet readiness: CoordinatorAdminReadiness = \"ready\";\n\tif (!hasUrl) readiness = \"not_configured\";\n\telse if (!hasGroups || !hasAdminSecret) readiness = \"partial\";\n\treturn {\n\t\treadiness,\n\t\tcoordinator_url: config.syncCoordinatorUrl || null,\n\t\tgroups,\n\t\tactive_group: activeGroup,\n\t\thas_admin_secret: hasAdminSecret,\n\t\thas_groups: hasGroups,\n\t};\n}\n\nasync function ensureDefaultSpaceForTeam(opts: {\n\tstore: MemoryStore;\n\tconfig: ReturnType<typeof readCoordinatorSyncConfig>;\n\tgroupId: string;\n\tdisplayName: string | null;\n}): Promise<{\n\tscope: CoordinatorScope | null;\n\tmembership: CoordinatorScopeMembership | null;\n\tpreferences: ReturnType<typeof upsertCoordinatorGroupPreference>;\n}> {\n\tconst coordinatorId = opts.config.syncCoordinatorUrl || null;\n\tif (!coordinatorId) throw new Error(\"coordinator_not_configured\");\n\tconst scopeId = defaultSpaceScopeIdForGroup(opts.groupId);\n\tconst label = opts.displayName || opts.groupId;\n\tconst existingScopes = await coordinatorListScopesAction({\n\t\tgroupId: opts.groupId,\n\t\tincludeInactive: false,\n\t\tremoteUrl: opts.config.syncCoordinatorUrl || null,\n\t\tadminSecret: opts.config.syncCoordinatorAdminSecret || null,\n\t});\n\tconst existingScope = existingScopes.find((scope) => scope.scope_id === scopeId) ?? null;\n\tconst scope =\n\t\texistingScope ??\n\t\t(await coordinatorCreateScopeAction({\n\t\t\tgroupId: opts.groupId,\n\t\t\tscopeId,\n\t\t\tlabel,\n\t\t\tkind: \"team_default\",\n\t\t\tauthorityType: \"coordinator\",\n\t\t\tcoordinatorId,\n\t\t\tmembershipEpoch: 1,\n\t\t\tstatus: \"active\",\n\t\t\tremoteUrl: opts.config.syncCoordinatorUrl || null,\n\t\t\tadminSecret: opts.config.syncCoordinatorAdminSecret || null,\n\t\t}));\n\tconst [deviceId] = ensureDeviceIdentity(opts.store.db, { keysDir: syncKeysDir() });\n\tconst membership = await coordinatorGrantScopeMembershipAction({\n\t\teffectId: `team-default-grant:${opts.groupId}:${scopeId}:${deviceId}:1`,\n\t\tgroupId: opts.groupId,\n\t\tscopeId,\n\t\tdeviceId,\n\t\trole: \"admin\",\n\t\tmembershipEpoch: 1,\n\t\tcoordinatorId,\n\t\tremoteUrl: opts.config.syncCoordinatorUrl || null,\n\t\tadminSecret: opts.config.syncCoordinatorAdminSecret || null,\n\t});\n\tconst preferences = upsertCoordinatorGroupPreference(opts.store.db, {\n\t\tcoordinator_id: coordinatorId,\n\t\tgroup_id: opts.groupId,\n\t\tdefault_space_scope_id: scopeId,\n\t\tauto_grant_default_space_on_join: true,\n\t});\n\treturn { scope, membership, preferences };\n}\n\nasync function maybeGrantDefaultSpaceOnJoin(opts: {\n\tstore: MemoryStore;\n\tconfig: ReturnType<typeof readCoordinatorSyncConfig>;\n\tgroupId: string;\n\trequestId: string;\n\tdeviceId: string;\n}): Promise<CoordinatorScopeMembership | null> {\n\tconst coordinatorId = opts.config.syncCoordinatorUrl || null;\n\tif (!coordinatorId) return null;\n\tconst preferences = getCoordinatorGroupPreference(opts.store.db, coordinatorId, opts.groupId);\n\tif (!preferences?.auto_grant_default_space_on_join) return null;\n\tconst scopeId = preferences.default_space_scope_id?.trim();\n\tif (!scopeId) return null;\n\tif (scopeId !== defaultSpaceScopeIdForGroup(opts.groupId)) return null;\n\tconst scopes = await coordinatorListScopesAction({\n\t\tgroupId: opts.groupId,\n\t\tincludeInactive: false,\n\t\tremoteUrl: opts.config.syncCoordinatorUrl || null,\n\t\tadminSecret: opts.config.syncCoordinatorAdminSecret || null,\n\t});\n\tconst defaultScope = scopes.find((scope) => scope.scope_id === scopeId) ?? null;\n\tif (defaultScope?.kind !== \"team_default\") return null;\n\treturn await coordinatorGrantScopeMembershipAction({\n\t\teffectId: `team-default-join:${opts.requestId}:${scopeId}:${opts.deviceId}:1`,\n\t\tgroupId: opts.groupId,\n\t\tscopeId,\n\t\tdeviceId: opts.deviceId,\n\t\trole: \"member\",\n\t\tmembershipEpoch: 1,\n\t\tcoordinatorId,\n\t\tremoteUrl: opts.config.syncCoordinatorUrl || null,\n\t\tadminSecret: opts.config.syncCoordinatorAdminSecret || null,\n\t});\n}\n\nfunction removeConfiguredCoordinatorGroup(groupId: string): string[] {\n\tconst targetGroup = groupId.trim();\n\tif (!targetGroup) return [];\n\tconst config = readCodememConfigFile();\n\tconst rawGroups = config.sync_coordinator_groups;\n\tconst groups = Array.isArray(rawGroups)\n\t\t? rawGroups.map((group) => String(group).trim()).filter(Boolean)\n\t\t: typeof rawGroups === \"string\"\n\t\t\t? rawGroups\n\t\t\t\t\t.split(\",\")\n\t\t\t\t\t.map((group) => group.trim())\n\t\t\t\t\t.filter(Boolean)\n\t\t\t: typeof config.sync_coordinator_group === \"string\" && config.sync_coordinator_group.trim()\n\t\t\t\t? [config.sync_coordinator_group.trim()]\n\t\t\t\t: [];\n\tconst nextGroups = groups.filter((group) => group !== targetGroup);\n\tif (nextGroups.length === groups.length) return groups;\n\tconfig.sync_coordinator_groups = nextGroups;\n\tif (nextGroups.length) config.sync_coordinator_group = nextGroups[0];\n\telse delete config.sync_coordinator_group;\n\twriteCodememConfigFile(config);\n\treturn nextGroups;\n}\n\nfunction coordinatorAdminUnavailable(status: ReturnType<typeof coordinatorAdminStatusPayload>): {\n\tbody: Record<string, unknown>;\n\thttpStatus: 400;\n} | null {\n\tif (status.readiness === \"not_configured\") {\n\t\treturn { body: { error: \"coordinator_not_configured\", status }, httpStatus: 400 };\n\t}\n\tif (!status.has_admin_secret) {\n\t\treturn { body: { error: \"coordinator_admin_secret_missing\", status }, httpStatus: 400 };\n\t}\n\treturn null;\n}\n\nfunction recipientInviteCreationUnavailable(\n\tstatus: ReturnType<typeof coordinatorAdminStatusPayload>,\n\tkind: RecipientInviteKind,\n): { body: Record<string, unknown>; httpStatus: 400 } | null {\n\tif (status.readiness === \"not_configured\") {\n\t\treturn { body: { error: \"coordinator_not_configured\", status }, httpStatus: 400 };\n\t}\n\tif (!status.has_groups) {\n\t\treturn { body: { error: \"coordinator_group_missing\", status }, httpStatus: 400 };\n\t}\n\tif (kind === \"team_member\" && !status.has_admin_secret) {\n\t\treturn { body: { error: \"coordinator_admin_secret_missing\", status }, httpStatus: 400 };\n\t}\n\treturn null;\n}\n\nasync function parseViewerJsonBody(\n\tc: Context,\n\toptions: { allowEmpty?: boolean } = {},\n): Promise<Record<string, unknown> | null> {\n\tconst raw = await c.req.text();\n\tif (!raw.trim()) return options.allowEmpty ? {} : null;\n\ttry {\n\t\tconst parsed = JSON.parse(raw) as unknown;\n\t\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) return null;\n\t\treturn parsed as Record<string, unknown>;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction optionalViewerString(body: Record<string, unknown>, key: string): string | null {\n\tconst value = body[key];\n\tif (value == null) return null;\n\treturn String(value).trim() || null;\n}\n\nfunction optionalViewerStrictString(body: Record<string, unknown>, key: string): string | null {\n\tconst value = body[key];\n\tif (value == null) return null;\n\tif (typeof value !== \"string\") throw new Error(`${key} must be string`);\n\treturn value.trim() || null;\n}\n\nfunction optionalViewerStringList(body: Record<string, unknown>, key: string): string[] {\n\tconst value = body[key];\n\tif (value == null) return [];\n\tif (!Array.isArray(value)) throw new Error(`${key} must be an array of strings`);\n\treturn [\n\t\t...new Set(\n\t\t\tvalue\n\t\t\t\t.map((item) => {\n\t\t\t\t\tif (typeof item !== \"string\") throw new Error(`${key} must be an array of strings`);\n\t\t\t\t\treturn item.trim();\n\t\t\t\t})\n\t\t\t\t.filter(Boolean),\n\t\t),\n\t];\n}\n\nfunction optionalViewerNumber(body: Record<string, unknown>, key: string): number | null {\n\tconst value = body[key];\n\tif (value == null || value === \"\") return null;\n\tconst number = typeof value === \"number\" ? value : Number(value);\n\treturn Number.isFinite(number) ? Math.trunc(number) : Number.NaN;\n}\n\nfunction coordinatorAdminMembershipEffectId(\n\taction: \"grant\" | \"revoke\",\n\tattemptId: string,\n\tinput: {\n\t\tgroupId: string;\n\t\tscopeId: string;\n\t\tdeviceId: string;\n\t\trole?: string | null;\n\t\tmembershipEpoch: number | null;\n\t\tcoordinatorId?: string | null;\n\t\tmanifestIssuerDeviceId?: string | null;\n\t\tmanifestHash: string | null;\n\t\tsignedManifestJson: string | null;\n\t},\n): string {\n\tconst fingerprint = createHash(\"sha256\")\n\t\t.update(\n\t\t\tJSON.stringify({\n\t\t\t\taction,\n\t\t\t\tattemptId,\n\t\t\t\tgroupId: input.groupId,\n\t\t\t\tscopeId: input.scopeId,\n\t\t\t\tdeviceId: input.deviceId,\n\t\t\t\trole: input.role ?? null,\n\t\t\t\tmembershipEpoch: input.membershipEpoch,\n\t\t\t\tcoordinatorId: input.coordinatorId ?? null,\n\t\t\t\tmanifestIssuerDeviceId: input.manifestIssuerDeviceId ?? null,\n\t\t\t\tmanifestHash: input.manifestHash,\n\t\t\t\tsignedManifestJson: input.signedManifestJson,\n\t\t\t}),\n\t\t)\n\t\t.digest(\"hex\");\n\treturn `viewer-admin-membership:${action}:${fingerprint}`;\n}\n\nfunction optionalViewerInteger(body: Record<string, unknown>, key: string): number | null {\n\tconst value = body[key];\n\tif (value == null || value === \"\") return null;\n\tconst number = typeof value === \"number\" ? value : Number(value);\n\treturn Number.isInteger(number) ? number : Number.NaN;\n}\n\nfunction missingGuardrailConfirmations(\n\twarnings: ProjectScopeGuardrailWarning[],\n\tconfirmedTokens: string[],\n): ProjectScopeGuardrailWarning[] {\n\tconst confirmed = new Set(confirmedTokens);\n\treturn warnings.filter(\n\t\t(warning) =>\n\t\t\twarning.requires_confirmation &&\n\t\t\t(!warning.confirmation_token || !confirmed.has(warning.confirmation_token)),\n\t);\n}\n\nfunction parseViewerProjectMappingInput(body: Record<string, unknown>) {\n\tconst id = optionalViewerInteger(body, \"id\");\n\tconst priority = optionalViewerInteger(body, \"priority\");\n\tif (Number.isNaN(id)) throw new Error(\"id must be an integer\");\n\tif (Number.isNaN(priority)) throw new Error(\"priority must be an integer\");\n\treturn {\n\t\tid,\n\t\tworkspace_identity: optionalViewerStrictString(body, \"workspace_identity\"),\n\t\tproject_pattern: optionalViewerStrictString(body, \"project_pattern\"),\n\t\tscope_id: optionalViewerStrictString(body, \"scope_id\") ?? \"\",\n\t\tpriority,\n\t\tsource: optionalViewerStrictString(body, \"source\") ?? \"user\",\n\t};\n}\n\nfunction coordinatorAdminMutationStatus(message: string): 400 | 404 | 409 | 502 {\n\tif (\n\t\tmessage.includes(\"scope_not_found\") ||\n\t\tmessage.includes(\"membership_not_found\") ||\n\t\tmessage.includes(\"group_not_found\") ||\n\t\tmessage.includes(\"Group not found\") ||\n\t\tmessage.includes(\"Scope not found\") ||\n\t\tmessage.includes(\"device_not_enrolled_for_scope_group\") ||\n\t\tmessage.includes(\"device must be enrolled\")\n\t) {\n\t\treturn 404;\n\t}\n\tif (\n\t\tmessage.includes(\"not active\") ||\n\t\tmessage.includes(\"scope_not_active\") ||\n\t\tmessage.includes(\"scope_membership_effect_conflict\") ||\n\t\tmessage.includes(\"group_archived\") ||\n\t\tmessage.includes(\"Group is archived\")\n\t) {\n\t\treturn 409;\n\t}\n\tif (\n\t\tmessage.includes(\"Remote coordinator request failed (5\") ||\n\t\tmessage.includes(\"fetch failed\") ||\n\t\tmessage.includes(\"network\") ||\n\t\tmessage.includes(\"timed out\")\n\t) {\n\t\treturn 502;\n\t}\n\treturn 400;\n}\n\nfunction pairingAdvertiseAddresses(config = readCoordinatorSyncConfig()): string[] {\n\tconst advertise = String(config.syncAdvertise || \"auto\")\n\t\t.trim()\n\t\t.toLowerCase();\n\tif (advertise && advertise !== \"auto\" && advertise !== \"default\") {\n\t\treturn mergeAddresses(\n\t\t\t[],\n\t\t\tString(config.syncAdvertise || \"\")\n\t\t\t\t.split(\",\")\n\t\t\t\t.map((item) => item.trim())\n\t\t\t\t.filter(Boolean),\n\t\t\t{ defaultHttpPort: config.syncPort },\n\t\t);\n\t}\n\tif (config.syncHost && config.syncHost !== \"0.0.0.0\") {\n\t\treturn [normalizeAddress(formatHostPort(config.syncHost, config.syncPort))].filter(Boolean);\n\t}\n\tconst addresses = Object.values(networkInterfaces())\n\t\t.flatMap((entries) => entries ?? [])\n\t\t.filter((entry) => !entry.internal)\n\t\t.map((entry) => entry.address)\n\t\t.filter((address) => address && address !== \"127.0.0.1\" && address !== \"::1\")\n\t\t.map((address) => normalizeAddress(formatHostPort(address, config.syncPort)))\n\t\t.filter(Boolean);\n\treturn [...new Set(addresses)];\n}\n\nfunction resolveCoordinatorAdminGroup(\n\trequestedGroup: string | null | undefined,\n\tstatus: ReturnType<typeof coordinatorAdminStatusPayload>,\n): string | null {\n\tconst explicit = String(requestedGroup ?? \"\").trim();\n\tif (explicit) return explicit;\n\treturn status.active_group;\n}\n\nfunction parseInviteTtlHours(value: unknown): number | null {\n\tconst ttlHours = Number(String(value ?? 24));\n\tif (!Number.isInteger(ttlHours) || ttlHours < 1) return null;\n\treturn ttlHours;\n}\n\nfunction projectInviteAcceptanceFailure(error: unknown): {\n\terror: string;\n\tdetail: string;\n} {\n\tif (isProjectSyncEnablementError(error)) {\n\t\treturn { error: error.code, detail: error.detail };\n\t}\n\tconst code = error instanceof Error ? error.message : \"project_invite_acceptance_failed\";\n\tconst detailByCode: Record<string, string> = {\n\t\tinvite_already_bound:\n\t\t\t\"This invitation was accepted by another device. Ask the owner to create a new invitation.\",\n\t\tinvite_expired: \"This invitation expired. Ask the owner to create a new invitation.\",\n\t\tinvite_identity_conflict:\n\t\t\t\"This invitation does not match this Identity. Ask the owner to create a new invitation for this recipient.\",\n\t\tinvite_invalid: \"This invitation is no longer valid. Ask the owner to create a new invitation.\",\n\t\tinviter_identity_invalid:\n\t\t\t\"The owner's device identity could not be verified. Ask the owner to review the share and create a new invitation.\",\n\t\tproject_invite_self_acceptance_forbidden:\n\t\t\t\"The owner cannot accept this recipient invitation on the owner's device.\",\n\t\tproject_invite_bootstrap_incomplete:\n\t\t\t\"The owner's device is not ready to establish trust yet. Retry once, then ask the owner to review the share.\",\n\t\tproject_invite_trust_state_invalid:\n\t\t\t\"The owner's trust setup could not be verified. Ask the owner to review the share.\",\n\t\trecipient_display_name_invalid:\n\t\t\t\"Enter a human-readable Identity name instead of an internal identifier.\",\n\t\trecipient_display_name_required: \"Enter an Identity display name.\",\n\t\trecipient_display_name_too_long: \"Use an Identity display name with 120 characters or fewer.\",\n\t\tdevice_display_name_invalid:\n\t\t\t\"Enter a human-readable device name instead of an internal identifier.\",\n\t\tdevice_display_name_required: \"Enter a device display name.\",\n\t\tdevice_display_name_too_long: \"Use a device display name with 120 characters or fewer.\",\n\t};\n\tconst safeCode = Object.hasOwn(detailByCode, code) ? code : \"project_invite_acceptance_failed\";\n\treturn {\n\t\terror: safeCode,\n\t\tdetail:\n\t\t\tdetailByCode[code] ??\n\t\t\t\"The invitation could not be accepted safely. Retry once, then ask the owner to review the share.\",\n\t};\n}\n\nconst PROJECT_INVITE_TTL_HOURS = 7 * 24;\nconst PROJECT_INVITE_OWNER_FALLBACK = \"Project owner\";\nconst PROJECT_INVITE_BODY_KEYS = new Set([\n\t\"teammate_name\",\n\t\"project_ids\",\n\t\"reviewed_project_set_digest\",\n]);\n\nfunction projectInviteInviterDisplayName(value: string): string {\n\ttry {\n\t\treturn normalizeHumanPresentationName(value, \"inviter_display_name\");\n\t} catch {\n\t\treturn PROJECT_INVITE_OWNER_FALLBACK;\n\t}\n}\n\nfunction projectInviteStringList(body: Record<string, unknown>, key: string): string[] {\n\tconst value = body[key];\n\tif (!Array.isArray(value)) throw new Error(`${key}_must_be_string_array`);\n\tif (value.length > 100) throw new Error(`${key}_too_large`);\n\tconst items = value.map((item) => {\n\t\tif (typeof item !== \"string\") throw new Error(`${key}_must_be_string_array`);\n\t\treturn item.trim();\n\t});\n\tif (items.some((item) => !item)) throw new Error(`${key}_contains_empty_value`);\n\tif (new Set(items).size !== items.length) throw new Error(`${key}_contains_duplicates`);\n\treturn items;\n}\n\nfunction assertProjectInviteBody(body: Record<string, unknown>, creating: boolean): void {\n\tconst allowed = creating ? PROJECT_INVITE_BODY_KEYS : new Set([\"teammate_name\", \"project_ids\"]);\n\tif (Object.keys(body).some((key) => !allowed.has(key))) {\n\t\tthrow new Error(\"unexpected_project_invite_fields\");\n\t}\n\tif (typeof body.teammate_name !== \"string\") throw new Error(\"teammate_name_must_be_string\");\n\tif (creating && typeof body.reviewed_project_set_digest !== \"string\") {\n\t\tthrow new Error(\"reviewed_project_set_digest_required\");\n\t}\n\tif (creating && !/^[a-f0-9]{64}$/u.test(String(body.reviewed_project_set_digest).trim())) {\n\t\tthrow new Error(\"reviewed_project_set_digest_invalid\");\n\t}\n}\n\nfunction projectInviteStatus(config = readCoordinatorSyncConfig()): {\n\tgroupId: string;\n\tconfig: ReturnType<typeof readCoordinatorSyncConfig>;\n} {\n\tconst status = coordinatorAdminStatusPayload(config);\n\tif (status.readiness !== \"ready\") throw new Error(\"team_sharing_not_configured\");\n\tif (status.groups.length !== 1) throw new Error(\"team_selection_ambiguous\");\n\tif (!status.active_group) throw new Error(\"team_sharing_not_configured\");\n\treturn { groupId: status.active_group, config };\n}\n\ntype RecipientInviteKind = \"team_member\" | \"add_device\";\n\nfunction recipientInviteKind(value: unknown): RecipientInviteKind {\n\tif (value === \"team_member\" || value === \"add_device\") return value;\n\tthrow new Error(\"recipient_invite_kind_invalid\");\n}\n\nfunction localOnboardingBinding(\n\tstore: MemoryStore,\n\tdeviceName: string | null,\n\toptions: { materializeActor?: boolean } = {},\n): {\n\tdeviceId: string;\n\tdevicePublicKey: string;\n\tdeviceDisplayName: string;\n} {\n\tconst deviceId =\n\t\toptions.materializeActor === false\n\t\t\t? ensureStableStoreDeviceIdentity(store)\n\t\t\t: ensureStableStoreIdentity(store);\n\tconst devicePublicKey = String(\n\t\tstore.db\n\t\t\t.prepare(\"SELECT public_key FROM sync_device WHERE device_id = ?\")\n\t\t\t.pluck()\n\t\t\t.get(deviceId) ?? \"\",\n\t).trim();\n\tif (!devicePublicKey) throw new Error(\"device_public_key_missing\");\n\tconst config = readCodememConfigFile();\n\treturn {\n\t\tdeviceId,\n\t\tdevicePublicKey,\n\t\tdeviceDisplayName: friendlyDeviceName({\n\t\t\texplicitName: deviceName ?? String(config.sync_device_name ?? \"\"),\n\t\t\tosName: hostname(),\n\t\t\tfallbackSeed: deviceId,\n\t\t}),\n\t};\n}\n\nfunction recipientInviteOnboardingPreview(\n\tstore: MemoryStore,\n\tbody: Record<string, unknown>,\n\tinvitationId: string,\n) {\n\tconst kind = recipientInviteKind(body.kind ?? body.invite_kind);\n\tconst binding = localOnboardingBinding(store, optionalViewerString(body, \"device_name\"));\n\tconst teamId = optionalViewerStrictString(body, \"policy_team_id\");\n\tconst targetIdentityId = optionalViewerStrictString(body, \"target_identity_id\");\n\tif (kind === \"team_member\") {\n\t\tif (!teamId || targetIdentityId) throw new Error(\"recipient_invite_metadata_invalid\");\n\t\treturn previewRecipientPolicyOnboarding(store.db, {\n\t\t\tversion: 1,\n\t\t\tjourney: \"team\",\n\t\t\tinvitationId,\n\t\t\tidentityId: store.actorId,\n\t\t\t...binding,\n\t\t\tteamId,\n\t\t});\n\t}\n\tif (!targetIdentityId || teamId) throw new Error(\"recipient_invite_metadata_invalid\");\n\treturn previewRecipientPolicyOnboarding(\n\t\tstore.db,\n\t\t{\n\t\t\tversion: 1,\n\t\t\tjourney: \"add_device\",\n\t\t\tinvitationId,\n\t\t\tidentityId: targetIdentityId,\n\t\t\t...binding,\n\t\t},\n\t\t{\n\t\t\taddDeviceTeamEligibility: \"prospective_device\",\n\t\t},\n\t);\n}\n\nfunction recipientInviteReviewedIntent(\n\tstore: MemoryStore,\n\tkind: RecipientInviteKind,\n\ttargetId: string,\n\tpreview: RecipientPolicyOnboardingPreviewV1,\n): RecipientReviewedIntentV1 {\n\tif (kind === \"team_member\") {\n\t\tif (preview.journey !== \"team\" || !preview.team || preview.team.teamId !== targetId) {\n\t\t\tthrow new Error(\"recipient_invite_intent_mismatch\");\n\t\t}\n\t\treturn {\n\t\t\tversion: 1,\n\t\t\tjourney: \"team\",\n\t\t\tteam: preview.team,\n\t\t\tprojects: preview.projects,\n\t\t\texcludedProjects: [],\n\t\t};\n\t}\n\tif (preview.journey !== \"add_device\" || preview.binding.identityId !== targetId) {\n\t\tthrow new Error(\"recipient_invite_intent_mismatch\");\n\t}\n\tconst targetIdentity = store.db\n\t\t.prepare(\n\t\t\t`SELECT display_name FROM actors\n\t\t\t WHERE actor_id = ? AND status = 'active' AND merged_into_actor_id IS NULL`,\n\t\t)\n\t\t.get(targetId) as { display_name: string } | undefined;\n\tif (!targetIdentity?.display_name) throw new Error(\"identity_not_found\");\n\treturn {\n\t\tversion: 1,\n\t\tjourney: \"add_device\",\n\t\ttargetIdentity: { identityId: targetId, displayName: targetIdentity.display_name },\n\t\tprojects: preview.projects,\n\t\texcludedProjects: preview.excludedProjects,\n\t};\n}\n\nfunction recipientInviteOnboardingPreviewFromReviewedIntent(\n\tstore: MemoryStore,\n\tbody: Record<string, unknown>,\n\tinvitationId: string,\n\treviewedIntent: RecipientReviewedIntentV1,\n) {\n\tconst kind = recipientInviteKind(body.kind ?? body.invite_kind);\n\tconst binding = localOnboardingBinding(store, optionalViewerString(body, \"device_name\"), {\n\t\tmaterializeActor: false,\n\t});\n\tconst teamId = optionalViewerStrictString(body, \"policy_team_id\");\n\tconst targetIdentityId = optionalViewerStrictString(body, \"target_identity_id\");\n\tconst assignedIdentityId = optionalViewerStrictString(body, \"assigned_identity_id\");\n\tif (kind === \"team_member\") {\n\t\tif (!teamId || !assignedIdentityId || targetIdentityId) {\n\t\t\tthrow new Error(\"recipient_invite_metadata_invalid\");\n\t\t}\n\t\treturn previewRecipientPolicyOnboardingFromReviewedIntent(reviewedIntent, {\n\t\t\tversion: 1,\n\t\t\tjourney: \"team\",\n\t\t\tinvitationId,\n\t\t\tidentityId: assignedIdentityId,\n\t\t\t...binding,\n\t\t\tteamId,\n\t\t});\n\t}\n\tif (!targetIdentityId || teamId || assignedIdentityId) {\n\t\tthrow new Error(\"recipient_invite_metadata_invalid\");\n\t}\n\treturn previewRecipientPolicyOnboardingFromReviewedIntent(reviewedIntent, {\n\t\tversion: 1,\n\t\tjourney: \"add_device\",\n\t\tinvitationId,\n\t\tidentityId: targetIdentityId,\n\t\t...binding,\n\t});\n}\n\nconst SAFE_RECIPIENT_INVITE_ERRORS = new Set([\n\t\"device_display_name_invalid\",\n\t\"device_display_name_required\",\n\t\"device_display_name_too_long\",\n\t\"invite_already_bound\",\n\t\"invite_expired\",\n\t\"invite_identity_conflict\",\n\t\"invite_invalid\",\n\t\"recipient_display_name_invalid\",\n\t\"recipient_display_name_required\",\n\t\"recipient_display_name_too_long\",\n\t\"recipient_invite_intent_mismatch\",\n\t\"recipient_invite_review_unavailable\",\n\t\"reviewed_onboarding_stale\",\n]);\n\nfunction safeRecipientInviteError(value: unknown, fallback = \"invite_invalid\"): string {\n\tconst code = value instanceof Error ? value.message : String(value ?? \"\").trim();\n\treturn SAFE_RECIPIENT_INVITE_ERRORS.has(code) ? code : fallback;\n}\n\nfunction recipientInvitePreviewId(kind: RecipientInviteKind, targetId: string): string {\n\treturn `recipient-invite-preview:${kind}:${targetId}`;\n}\n\nexport function recipientPolicyCapabilityFromStatus(payload: {\n\tsync_capability?: unknown;\n\tsync_features?: unknown;\n}): RecipientPolicyPeerCapability {\n\tif (!isScopedSyncCapability(normalizeSyncCapability(payload.sync_capability))) {\n\t\treturn \"unsupported\";\n\t}\n\treturn supportsSyncFeature(payload.sync_features, \"reassign_scope\") ? \"supported\" : \"unsupported\";\n}\n\nexport async function peerSupportsSyncRequirements(\n\tstore: MemoryStore,\n\tdeviceId: string,\n\trequirements: { scoped: boolean; reassignScope: boolean },\n): Promise<RecipientPolicyPeerCapability> {\n\tconst [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });\n\tif (deviceId === localDeviceId) return \"supported\";\n\tconst row = store.db\n\t\t.prepare(\n\t\t\t\"SELECT addresses_json, pinned_fingerprint, public_key FROM sync_peers WHERE peer_device_id = ?\",\n\t\t)\n\t\t.get(deviceId) as\n\t\t| {\n\t\t\t\taddresses_json: string | null;\n\t\t\t\tpinned_fingerprint: string | null;\n\t\t\t\tpublic_key: string | null;\n\t\t }\n\t\t| undefined;\n\tconst expectedFingerprint =\n\t\tString(row?.pinned_fingerprint ?? \"\").trim() ||\n\t\t(row?.public_key ? fingerprintPublicKey(row.public_key) : \"\");\n\tconst addresses = safeJsonList(row?.addresses_json ?? null);\n\tfor (const address of addresses) {\n\t\ttry {\n\t\t\tconst url = `${buildBaseUrl(address)}/v1/status`;\n\t\t\tconst headers = {\n\t\t\t\t...buildDirectPeerAuthHeaders({\n\t\t\t\t\tdeviceId: localDeviceId,\n\t\t\t\t\trecipientId: deviceId,\n\t\t\t\t\tdbPath: store.dbPath,\n\t\t\t\t\tmethod: \"GET\",\n\t\t\t\t\turl,\n\t\t\t\t\tbodyBytes: Buffer.alloc(0),\n\t\t\t\t\tkeysDir: syncKeysDir(),\n\t\t\t\t}),\n\t\t\t\t[SYNC_CAPABILITY_HEADER]: LOCAL_SYNC_CAPABILITY,\n\t\t\t\t[SYNC_FEATURES_HEADER]: LOCAL_SYNC_FEATURES.join(\",\"),\n\t\t\t};\n\t\t\tconst [status, payload] = await requestJson(\"GET\", url, { headers, timeoutS: 5 });\n\t\t\tif (status < 200 || status >= 300) continue;\n\t\t\tif (String(payload?.device_id ?? \"\").trim() !== deviceId) continue;\n\t\t\tif (\n\t\t\t\texpectedFingerprint &&\n\t\t\t\tString(payload?.fingerprint ?? \"\").trim() !== expectedFingerprint\n\t\t\t) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (\n\t\t\t\trequirements.scoped &&\n\t\t\t\trequirements.reassignScope &&\n\t\t\t\trecipientPolicyCapabilityFromStatus(payload ?? {}) !== \"supported\"\n\t\t\t) {\n\t\t\t\treturn \"unsupported\";\n\t\t\t}\n\t\t\tif (\n\t\t\t\trequirements.scoped &&\n\t\t\t\t!isScopedSyncCapability(normalizeSyncCapability(payload?.sync_capability))\n\t\t\t) {\n\t\t\t\treturn \"unsupported\";\n\t\t\t}\n\t\t\tif (\n\t\t\t\trequirements.reassignScope &&\n\t\t\t\t!supportsSyncFeature(payload?.sync_features, \"reassign_scope\")\n\t\t\t) {\n\t\t\t\treturn \"unsupported\";\n\t\t\t}\n\t\t\treturn \"supported\";\n\t\t} catch {\n\t\t\t// Try the next reviewed address. Ambiguous/unreachable capability fails closed.\n\t\t}\n\t}\n\treturn \"undetermined\";\n}\n\nasync function peerSupportsReassignScope(\n\tstore: MemoryStore,\n\tdeviceId: string,\n): Promise<ReassignScopeCapability> {\n\treturn peerSupportsSyncRequirements(store, deviceId, {\n\t\tscoped: false,\n\t\treassignScope: true,\n\t});\n}\n\nfunction resolveProjectInviteSelection(\n\tstore: MemoryStore,\n\trequestedIds: string[],\n\tinitiatingDeviceId: string,\n): ShareProjectIntent[] {\n\tif (requestedIds.length === 0) throw new Error(\"project_selection_empty\");\n\tconst requested = new Set(requestedIds);\n\tconst byIdentity = new Map<\n\t\tstring,\n\t\tReturnType<typeof listProjectScopeInventory>[\"projects\"][number]\n\t>();\n\tlet offset = 0;\n\twhile (byIdentity.size < requested.size) {\n\t\tconst page = listProjectScopeInventory(store.db, { limit: 250, offset });\n\t\tfor (const project of page.projects) {\n\t\t\tif (requested.has(project.workspace_identity)) {\n\t\t\t\tbyIdentity.set(project.workspace_identity, project);\n\t\t\t}\n\t\t}\n\t\tif (!page.has_more) break;\n\t\toffset += page.limit;\n\t}\n\treturn requestedIds.map((projectId) => {\n\t\tconst project = byIdentity.get(projectId);\n\t\tif (!project) throw new Error(\"project_selection_unknown\");\n\t\tconst ambiguous = project.guardrail_warnings.some(\n\t\t\t(warning) => warning.code === \"basename_collision_review\" && warning.requires_confirmation,\n\t\t);\n\t\tif (ambiguous) throw new Error(\"project_selection_ambiguous\");\n\t\tif (\n\t\t\tproject.read_only ||\n\t\t\tproject.identity_source === \"unmapped\" ||\n\t\t\tproject.memory_count == null ||\n\t\t\tproject.guardrail_warnings.some((warning) => warning.requires_confirmation)\n\t\t) {\n\t\t\tthrow new Error(\"project_selection_unsupported\");\n\t\t}\n\t\treturn {\n\t\t\tcanonicalIdentity: project.workspace_identity,\n\t\t\tdisplayName: project.display_project,\n\t\t\tidentitySource: project.identity_source,\n\t\t\texistingMemoryCount: countShareableProjectMemories(store.db, {\n\t\t\t\tcanonicalIdentity: project.workspace_identity,\n\t\t\t\tinitiatingDeviceId,\n\t\t\t}),\n\t\t};\n\t});\n}\n\nfunction resolveSharePerson(store: MemoryStore, teammateName: string): SharePersonIntent {\n\tconst matches = store.db\n\t\t.prepare(\n\t\t\t`SELECT actor_id, display_name, status\n\t\t\t FROM actors\n\t\t\t WHERE status IN ('active', 'pending') AND lower(trim(display_name)) = lower(?)\n\t\t\t ORDER BY actor_id`,\n\t\t)\n\t\t.all(teammateName) as Array<{ actor_id: string; display_name: string; status: string }>;\n\tif (matches.length > 1) throw new Error(\"teammate_match_ambiguous\");\n\tconst match = matches[0];\n\tif (match) {\n\t\treturn match.status === \"pending\"\n\t\t\t? { kind: \"pending\", personId: match.actor_id, displayName: match.display_name }\n\t\t\t: { kind: \"existing\", personId: match.actor_id, displayName: match.display_name };\n\t}\n\treturn { kind: \"pending\", displayName: teammateName };\n}\n\nfunction projectInvitePlan(\n\tstore: MemoryStore,\n\tbody: Record<string, unknown>,\n\tcreatedAt: string,\n\tinviteExpiresAt: string,\n): { plan: ShareOperationPlan; config: ReturnType<typeof readCoordinatorSyncConfig> } {\n\tconst teammateName = normalizeTeammateName(String(body.teammate_name));\n\tconst [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });\n\tstore.adoptEnsuredDeviceIdentity(localDeviceId);\n\tconst projects = resolveProjectInviteSelection(\n\t\tstore,\n\t\tprojectInviteStringList(body, \"project_ids\"),\n\t\tlocalDeviceId,\n\t);\n\tconst { groupId, config } = projectInviteStatus();\n\treturn {\n\t\tplan: planShareOperation({\n\t\t\tinviterActorId: store.actorId,\n\t\t\tinviterDeviceIds: [localDeviceId],\n\t\t\tperson: resolveSharePerson(store, teammateName),\n\t\t\tprojects,\n\t\t\tcoordinatorGroupId: groupId,\n\t\t\tcreatedAt,\n\t\t\tinviteExpiresAt,\n\t\t}),\n\t\tconfig,\n\t};\n}\n\nfunction projectInvitePreview(plan: ShareOperationPlan) {\n\treturn {\n\t\toperation_id: plan.operationId,\n\t\tteammate: {\n\t\t\tdisplay_name: plan.teammateName,\n\t\t\tmatch: plan.personKind,\n\t\t\t...(plan.personKind === \"existing\" ? { person_id: plan.personId } : {}),\n\t\t},\n\t\tprojects: plan.projects.map((project) => ({\n\t\t\tproject_id: project.canonicalIdentity,\n\t\t\tdisplay_name: project.displayName,\n\t\t\texisting_memory_count: project.existingMemoryCount,\n\t\t})),\n\t\texisting_memory_count: plan.projects.reduce(\n\t\t\t(total, project) => total + project.existingMemoryCount,\n\t\t\t0,\n\t\t),\n\t\tfuture_memories_shared: true as const,\n\t\thistory_policy: plan.historyPolicy,\n\t\treviewed_project_set_digest: plan.reviewedProjectSetDigest,\n\t};\n}\n\ntype CoordinatorProjectInvitePayload = Record<string, unknown> & {\n\toperation_id?: string;\n\tgroup_id?: string;\n\tstate?: string;\n};\n\nasync function coordinatorProjectInvitePayload(operationId: string): Promise<{\n\tgroupId: string;\n\tconfig: ReturnType<typeof readCoordinatorSyncConfig>;\n\tpayload: CoordinatorProjectInvitePayload;\n}> {\n\tconst { groupId, config } = projectInviteStatus();\n\tconst [status, payload] = await requestJson(\n\t\t\"GET\",\n\t\t`${buildBaseUrl(config.syncCoordinatorUrl)}/v1/admin/project-invites/${encodeURIComponent(operationId)}?group_id=${encodeURIComponent(groupId)}`,\n\t\t{\n\t\t\theaders: { \"X-Codemem-Coordinator-Admin\": config.syncCoordinatorAdminSecret },\n\t\t\ttimeoutS: 10,\n\t\t},\n\t).catch((cause: unknown) => {\n\t\tconst error = new Error(\"coordinator_unavailable\", { cause });\n\t\tObject.assign(error, { status: 503 });\n\t\tthrow error;\n\t});\n\tif (status < 200 || status >= 300) {\n\t\tconst error = new Error(String(payload?.error ?? \"operation_read_failed\"));\n\t\tObject.assign(error, { status });\n\t\tthrow error;\n\t}\n\tif (!payload || payload.operation_id !== operationId || payload.group_id !== groupId) {\n\t\tconst error = new Error(\"operation_scope_mismatch\");\n\t\tObject.assign(error, { status: 409 });\n\t\tthrow error;\n\t}\n\treturn { groupId, config, payload: payload as CoordinatorProjectInvitePayload };\n}\n\nasync function reconcileProjectInviteAcceptance(\n\tstore: MemoryStore,\n\toperationId: string,\n): Promise<{ accepted: boolean; payload: CoordinatorProjectInvitePayload }> {\n\tconst owner = store.db\n\t\t.prepare(\"SELECT inviter_actor_id FROM share_operations WHERE operation_id = ?\")\n\t\t.pluck()\n\t\t.get(operationId) as string | undefined;\n\tif (!owner) throw new Error(\"operation_not_found\");\n\tif (owner !== store.actorId) throw new Error(\"operation_scope_mismatch\");\n\tensureLocalActorRecord(store);\n\tconst { groupId, payload } = await coordinatorProjectInvitePayload(operationId);\n\tif (payload.state === \"waiting_for_acceptance\") return { accepted: false, payload };\n\tif (payload.state !== \"accepted\") {\n\t\tconst error = new Error(\"operation_state_invalid\");\n\t\tObject.assign(error, { status: 409 });\n\t\tthrow error;\n\t}\n\tconst required = [\n\t\t\"reviewed_project_set_digest\",\n\t\t\"recipient_actor_id\",\n\t\t\"recipient_display_name\",\n\t\t\"recipient_device_id\",\n\t\t\"recipient_device_display_name\",\n\t\t\"recipient_public_key\",\n\t\t\"recipient_fingerprint\",\n\t\t\"consumed_at\",\n\t\t\"trust_state\",\n\t] as const;\n\tif (required.some((key) => typeof payload[key] !== \"string\" || !String(payload[key]).trim())) {\n\t\tconst error = new Error(\"operation_acceptance_invalid\");\n\t\tObject.assign(error, { status: 409 });\n\t\tthrow error;\n\t}\n\tconst trustState = String(payload.trust_state);\n\tconst bootstrapGrantId =\n\t\ttypeof payload.bootstrap_grant_id === \"string\" && payload.bootstrap_grant_id.trim()\n\t\t\t? payload.bootstrap_grant_id\n\t\t\t: null;\n\tif (\n\t\t(trustState !== \"pending_inviter_device\" && trustState !== \"bootstrap_grant_created\") ||\n\t\t(trustState === \"bootstrap_grant_created\") !== Boolean(bootstrapGrantId)\n\t) {\n\t\tconst error = new Error(\"operation_trust_state_invalid\");\n\t\tObject.assign(error, { status: 409 });\n\t\tthrow error;\n\t}\n\tconst projects = parseAcceptedProjectIntent(payload.projects);\n\treconcileShareOperationAcceptance(store.db, {\n\t\toperationId,\n\t\tlocalInviterActorId: store.actorId,\n\t\tcoordinatorGroupId: groupId,\n\t\treviewedProjectSetDigest: String(payload.reviewed_project_set_digest),\n\t\trecipientActorId: String(payload.recipient_actor_id),\n\t\trecipientDisplayName: String(payload.recipient_display_name),\n\t\trecipientDeviceId: String(payload.recipient_device_id),\n\t\trecipientDeviceDisplayName: String(payload.recipient_device_display_name),\n\t\trecipientPublicKey: String(payload.recipient_public_key),\n\t\trecipientFingerprint: String(payload.recipient_fingerprint),\n\t\tconsumedAt: String(payload.consumed_at),\n\t\ttrustState,\n\t\tbootstrapGrantId,\n\t\tprojects,\n\t});\n\treturn { accepted: true, payload };\n}\n\ninterface ShareOperationReadRow {\n\toperation_id: string;\n\tstate: string;\n\tperson_id: string;\n\tteammate_name: string;\n\trecipient_actor_id: string | null;\n\trecipient_display_name: string | null;\n\trecipient_device_id: string | null;\n\trecipient_device_display_name: string | null;\n\tinvite_expires_at: string;\n\tacceptance_consumed_at: string | null;\n\tcreated_at: string;\n\tupdated_at: string;\n\tactor_display_name: string | null;\n\tpeer_display_name: string | null;\n\tdevice_last_seen_at: string | null;\n\tdevice_last_reached_at: string | null;\n}\n\nasync function shareOperationReadModels(\n\tstore: MemoryStore,\n\toperationId?: string,\n\tincludeInviteLinks = true,\n) {\n\tconst rows = store.db\n\t\t.prepare(`SELECT o.operation_id, o.state, o.person_id, o.teammate_name,\n\t\t\to.recipient_actor_id, o.recipient_display_name, o.recipient_device_id,\n\t\t\to.recipient_device_display_name, o.invite_expires_at, o.acceptance_consumed_at,\n\t\t\to.created_at, o.updated_at, a.display_name AS actor_display_name,\n\t\t\tp.name AS peer_display_name, p.last_seen_at AS device_last_seen_at,\n\t\t\tp.last_sync_at AS device_last_reached_at\n\t\t FROM share_operations o\n\t\t LEFT JOIN actors a ON a.actor_id = o.person_id\n\t\t LEFT JOIN sync_peers p ON p.peer_device_id = o.recipient_device_id\n\t\t WHERE o.inviter_actor_id = ? AND (? IS NULL OR o.operation_id = ?)\n\t\t ORDER BY o.created_at DESC, o.operation_id`)\n\t\t.all(store.actorId, operationId ?? null, operationId ?? null) as ShareOperationReadRow[];\n\tconst now = new Date().toISOString();\n\treturn Promise.all(\n\t\trows.map(async (row) => {\n\t\t\tconst projects = store.db\n\t\t\t\t.prepare(`SELECT canonical_project_identity AS project_id, display_name, existing_memory_count\n\t\t\t\t FROM share_operation_projects WHERE operation_id = ? ORDER BY ordinal`)\n\t\t\t\t.all(row.operation_id) as Array<{\n\t\t\t\tproject_id: string;\n\t\t\t\tdisplay_name: string;\n\t\t\t\texisting_memory_count: number;\n\t\t\t}>;\n\t\t\tconst steps = (\n\t\t\t\tstore.db\n\t\t\t\t\t.prepare(`SELECT step_key, status, attempt_count, started_at, last_attempt_at,\n\t\t\t\t\t\tsafe_error_code, updated_at FROM share_operation_steps WHERE operation_id = ?`)\n\t\t\t\t\t.all(row.operation_id) as Array<{\n\t\t\t\t\tstep_key: string;\n\t\t\t\t\tstatus: ShareOperationLifecycleStepInput[\"status\"];\n\t\t\t\t\tattempt_count: number;\n\t\t\t\t\tstarted_at: string | null;\n\t\t\t\t\tlast_attempt_at: string | null;\n\t\t\t\t\tsafe_error_code: string | null;\n\t\t\t\t\tupdated_at: string;\n\t\t\t\t}>\n\t\t\t).map(\n\t\t\t\t(step): ShareOperationLifecycleStepInput => ({\n\t\t\t\t\tattemptCount: step.attempt_count,\n\t\t\t\t\tlastAttemptAt: step.last_attempt_at,\n\t\t\t\t\tsafeErrorCode: step.safe_error_code,\n\t\t\t\t\tstartedAt: step.started_at,\n\t\t\t\t\tstatus: step.status,\n\t\t\t\t\tstepKey: step.step_key,\n\t\t\t\t\tupdatedAt: step.updated_at,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tlet inviteLink: string | null = null;\n\t\t\tlet projectedState = row.state;\n\t\t\tif (includeInviteLinks && row.state === \"waiting_for_acceptance\") {\n\t\t\t\ttry {\n\t\t\t\t\tconst remote = await coordinatorProjectInvitePayload(row.operation_id);\n\t\t\t\t\tif (remote.payload.state === \"accepted\") projectedState = \"accepted\";\n\t\t\t\t\tinviteLink =\n\t\t\t\t\t\ttypeof remote.payload.invite_link === \"string\" && remote.payload.invite_link.trim()\n\t\t\t\t\t\t\t? remote.payload.invite_link\n\t\t\t\t\t\t\t: null;\n\t\t\t\t} catch {\n\t\t\t\t\t// A read-model refresh remains useful when the coordinator is temporarily unavailable.\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst personId = row.recipient_actor_id || row.person_id;\n\t\t\tconst personName = row.recipient_display_name || row.actor_display_name || row.teammate_name;\n\t\t\tconst deviceName = row.recipient_device_display_name || row.peer_display_name;\n\t\t\tconst lifecycle = projectShareLifecycle({\n\t\t\t\tdeviceLastSeenAt: row.device_last_seen_at,\n\t\t\t\tdeviceLastReachedAt: row.device_last_reached_at,\n\t\t\t\tdeviceName,\n\t\t\t\tinviteLink,\n\t\t\t\tnow,\n\t\t\t\tpersonName,\n\t\t\t\tstate: projectedState,\n\t\t\t\tsteps,\n\t\t\t});\n\t\t\treturn {\n\t\t\t\toperation_id: row.operation_id,\n\t\t\t\tperson: { actor_id: personId, display_name: personName },\n\t\t\t\tdevices:\n\t\t\t\t\trow.recipient_device_id && deviceName\n\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tdevice_id: row.recipient_device_id,\n\t\t\t\t\t\t\t\t\tdisplay_name: deviceName,\n\t\t\t\t\t\t\t\t\tlast_seen_at: row.device_last_seen_at,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t: [],\n\t\t\t\tprojects,\n\t\t\t\tproject_count: projects.length,\n\t\t\t\tlifecycle: {\n\t\t\t\t\tstate: lifecycle.lifecycle,\n\t\t\t\t\tlabel: lifecycle.label,\n\t\t\t\t\texplanation: lifecycle.explanation,\n\t\t\t\t\tprimary_action:\n\t\t\t\t\t\tlifecycle.primaryAction?.kind === \"copy_invite\"\n\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\tkind: \"copy_invite\",\n\t\t\t\t\t\t\t\t\tlabel: lifecycle.primaryAction.label,\n\t\t\t\t\t\t\t\t\tinvite_link: lifecycle.primaryAction.inviteLink,\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t: !includeInviteLinks && lifecycle.lifecycle === \"waiting_for_acceptance\"\n\t\t\t\t\t\t\t\t? { kind: \"copy_invite\", label: \"Copy invite\" }\n\t\t\t\t\t\t\t\t: lifecycle.primaryAction,\n\t\t\t\t},\n\t\t\t\ttimestamps: {\n\t\t\t\t\tcreated_at: row.created_at,\n\t\t\t\t\tupdated_at: row.updated_at,\n\t\t\t\t\taccepted_at: row.acceptance_consumed_at,\n\t\t\t\t\tinvite_expires_at: row.invite_expires_at,\n\t\t\t\t},\n\t\t\t};\n\t\t}),\n\t);\n}\n\nasync function executeProjectShareProvisioning(store: MemoryStore, operationId: string) {\n\tconst { groupId, config } = projectInviteStatus();\n\tconst coordinatorId = config.syncCoordinatorUrl || null;\n\tif (!coordinatorId) throw new Error(\"coordinator_not_configured\");\n\tconst [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });\n\treturn executeShareProvisioning(\n\t\tstore.db,\n\t\t{ operationId, initiatingDeviceId: localDeviceId },\n\t\t{\n\t\t\tcreateOrGetBoundary: async (project, expectedGroupId) => {\n\t\t\t\tif (expectedGroupId !== groupId) throw new Error(\"operation_scope_mismatch\");\n\t\t\t\tconst readExisting = async () =>\n\t\t\t\t\t(\n\t\t\t\t\t\tawait coordinatorListScopesAction({\n\t\t\t\t\t\t\tgroupId,\n\t\t\t\t\t\t\tincludeInactive: true,\n\t\t\t\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t\t\t\t})\n\t\t\t\t\t).find((scope) => scope.scope_id === project.boundaryId) ?? null;\n\t\t\t\tconst existing = await readExisting();\n\t\t\t\tif (existing) return existing;\n\t\t\t\ttry {\n\t\t\t\t\treturn await coordinatorCreateScopeAction({\n\t\t\t\t\t\tgroupId,\n\t\t\t\t\t\tscopeId: project.boundaryId,\n\t\t\t\t\t\tlabel: project.displayName,\n\t\t\t\t\t\tkind: \"managed_project\",\n\t\t\t\t\t\tauthorityType: \"coordinator\",\n\t\t\t\t\t\tcoordinatorId,\n\t\t\t\t\t\tmembershipEpoch: 1,\n\t\t\t\t\t\tstatus: \"active\",\n\t\t\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst reread = await readExisting();\n\t\t\t\t\tif (reread) return reread;\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t},\n\t\t\tgrantMembership: ({ effectId, groupId: expectedGroupId, scopeId, deviceId, role }) => {\n\t\t\t\tif (expectedGroupId !== groupId) throw new Error(\"operation_scope_mismatch\");\n\t\t\t\treturn coordinatorGrantScopeMembershipAction({\n\t\t\t\t\teffectId,\n\t\t\t\t\tgroupId,\n\t\t\t\t\tscopeId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\trole,\n\t\t\t\t\tmembershipEpoch: 1,\n\t\t\t\t\tcoordinatorId,\n\t\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t\t});\n\t\t\t},\n\t\t\tsupportsReassignScope: (deviceId) => peerSupportsReassignScope(store, deviceId),\n\t\t\trefreshAuthorization: async (expectedGroupId) => {\n\t\t\t\tif (expectedGroupId !== groupId) throw new Error(\"operation_scope_mismatch\");\n\t\t\t\tconst refreshed = await refreshConfiguredScopeMembershipCache(store.db, config, {\n\t\t\t\t\tkeysDir: syncKeysDir(),\n\t\t\t\t\tdbPath: store.dbPath,\n\t\t\t\t});\n\t\t\t\tconst group = refreshed.groups.find((item) => item.groupId === groupId);\n\t\t\t\tif (group?.status !== \"refreshed\") throw new Error(\"authorization_refresh_failed\");\n\t\t\t},\n\t\t\trunInitialSync: (recipientDeviceId) =>\n\t\t\t\trunSyncPass(store.db, recipientDeviceId, {\n\t\t\t\t\tkeysDir: syncKeysDir(),\n\t\t\t\t\tdbPath: store.dbPath,\n\t\t\t\t\tscanner: store.scanner,\n\t\t\t\t\trefreshAuthorization: true,\n\t\t\t\t}),\n\t\t},\n\t);\n}\n\nexport interface AdvanceProjectShareOperationResult {\n\tadvanced: boolean;\n\tstate: \"active\" | \"waiting_for_acceptance\" | \"cancelled\";\n}\n\nexport async function advanceProjectShareOperation(\n\tstore: MemoryStore,\n\toperationId: string,\n): Promise<AdvanceProjectShareOperationResult> {\n\tconst operation = store.db\n\t\t.prepare(\n\t\t\t\"SELECT state, inviter_actor_id, recipient_device_id FROM share_operations WHERE operation_id = ?\",\n\t\t)\n\t\t.get(operationId) as\n\t\t| { state: string; inviter_actor_id: string; recipient_device_id: string | null }\n\t\t| undefined;\n\tif (!operation) throw new Error(\"operation_not_found\");\n\tif (operation.inviter_actor_id !== store.actorId) throw new Error(\"operation_scope_mismatch\");\n\tif (operation.state === \"cancelled\") {\n\t\t// Already superseded (possibly earlier in the same maintenance batch);\n\t\t// provisioning a cancelled operation would only produce a misleading\n\t\t// operation_not_accepted failure.\n\t\treturn { advanced: false, state: \"cancelled\" };\n\t}\n\tif (!operation.recipient_device_id) {\n\t\tconst reconciliation = await reconcileProjectInviteAcceptance(store, operationId);\n\t\tif (!reconciliation.accepted) {\n\t\t\treturn { advanced: false, state: \"waiting_for_acceptance\" };\n\t\t}\n\t}\n\tconst plan = await executeProjectShareProvisioning(store, operationId);\n\tif (plan.superseded) {\n\t\t// A duplicate operation won the race and cancelled this one mid-flight;\n\t\t// reporting it as active would contradict the stored state.\n\t\treturn { advanced: false, state: \"cancelled\" };\n\t}\n\treturn { advanced: true, state: \"active\" };\n}\n\nexport interface AdvancePendingProjectSharesResult {\n\tprocessed: number;\n\tadvanced: number;\n\twaiting: number;\n\tattention: number;\n\tfailed: number;\n\titems: Array<{\n\t\toperationId: string;\n\t\toutcome:\n\t\t\t| \"advanced\"\n\t\t\t| \"waiting_for_acceptance\"\n\t\t\t| \"waiting_for_device\"\n\t\t\t| \"retry_scheduled\"\n\t\t\t| \"needs_attention\"\n\t\t\t| \"superseded\"\n\t\t\t| \"failed\";\n\t\terror?: string;\n\t}>;\n}\n\nconst AUTOMATIC_SHARE_OPERATION_STATES = [\n\t\"waiting_for_acceptance\",\n\t\"accepted\",\n\t\"provisioning\",\n\t\"initial_sync\",\n\t\"waiting_for_device\",\n] as const;\n\nconst AUTOMATIC_WAITING_ACCEPTANCE_RETRY_COOLDOWN_MS = 30 * 1000;\nconst AUTOMATIC_WAITING_DEVICE_RETRY_COOLDOWN_MS = 5 * 60 * 1000;\nconst TERMINAL_SHARE_MAINTENANCE_ERRORS = new Set([\n\t\"coordinator_not_configured\",\n\t\"team_sharing_not_configured\",\n\t\"team_selection_ambiguous\",\n\t\"initiating_device_not_reviewed\",\n\t\"inviter_project_access_ambiguous\",\n\t\"managed_boundary_plan_missing\",\n\t\"operation_device_binding_missing\",\n\t\"operation_intent_invalid\",\n\t\"provisioning_membership_plan_invalid\",\n\t\"device_binding_conflict\",\n\t\"intent_conflict\",\n\t\"inviter_identity_conflict\",\n]);\nconst PROJECT_INVITE_OWNER_CONFLICT_ERRORS = new Set([\n\t\"operation_scope_mismatch\",\n\t\"operation_state_invalid\",\n\t\"operation_acceptance_invalid\",\n\t\"operation_trust_state_invalid\",\n\t\"operation_intent_invalid\",\n\t\"operation_intent_mismatch\",\n\t\"recipient_fingerprint_mismatch\",\n\t\"recipient_device_identity_conflict\",\n\t\"recipient_actor_conflict\",\n\t\"pending_person_identity_conflict\",\n\t\"device_binding_conflict\",\n\t\"intent_conflict\",\n\t\"inviter_identity_conflict\",\n]);\nconst TERMINAL_RECONCILIATION_ERRORS = new Set([\n\t\"coordinator_not_configured\",\n\t\"team_sharing_not_configured\",\n\t\"team_selection_ambiguous\",\n\t\"operation_not_found\",\n\t...PROJECT_INVITE_OWNER_CONFLICT_ERRORS,\n]);\n\nfunction errorStatus(error: unknown): number | null {\n\tconst value = error && typeof error === \"object\" ? (error as { status?: unknown }).status : null;\n\treturn typeof value === \"number\" && Number.isInteger(value) && value >= 400 && value <= 599\n\t\t? value\n\t\t: null;\n}\n\nfunction projectInviteOwnerErrorResponse(\n\terror: unknown,\n\tfallback: { code: \"operation_read_failed\" | \"operation_reconcile_failed\"; status: 400 | 409 },\n): {\n\tcode: string;\n\tstatus: 400 | 404 | 409 | 502 | 503;\n} {\n\tconst message = error instanceof Error ? error.message : \"\";\n\tconst status = errorStatus(error);\n\tif (message === \"operation_not_found\" && (status == null || status === 404)) {\n\t\treturn { code: message, status: 404 };\n\t}\n\tif (PROJECT_INVITE_OWNER_CONFLICT_ERRORS.has(message) && (status == null || status === 409)) {\n\t\treturn { code: message, status: 409 };\n\t}\n\tif (status != null && status >= 500 && message !== \"coordinator_unavailable\") {\n\t\treturn { code: \"coordinator_upstream_failed\", status: 502 };\n\t}\n\tif (message === \"coordinator_unavailable\" || status === 408 || status === 429 || status === 503) {\n\t\treturn { code: \"coordinator_unavailable\", status: 503 };\n\t}\n\treturn fallback;\n}\n\nfunction isRetryableReconciliationError(error: unknown): boolean {\n\tconst message = error instanceof Error ? error.message : String(error);\n\tif (TERMINAL_RECONCILIATION_ERRORS.has(message)) return false;\n\tconst status = errorStatus(error);\n\treturn status == null || status === 408 || status === 429 || status >= 500;\n}\n\nfunction safeReconciliationErrorCode(error: unknown): string {\n\tconst message = error instanceof Error ? error.message : String(error);\n\treturn TERMINAL_RECONCILIATION_ERRORS.has(message) ? message : \"operation_read_failed\";\n}\n\nfunction recordInviteReconciliationFailure(\n\tstore: MemoryStore,\n\toperationId: string,\n\terror: unknown,\n\tnow: string,\n): \"retry_scheduled\" | \"needs_attention\" {\n\tconst safeErrorCode = safeReconciliationErrorCode(error);\n\tconst retryable = isRetryableReconciliationError(error);\n\tstore.db\n\t\t.prepare(`UPDATE share_operation_steps SET\n\t\t\tstatus = CASE WHEN ? = 1 THEN 'pending' ELSE 'failed' END,\n\t\t\tattempt_count = attempt_count + 1, last_attempt_at = ?, safe_error_code = ?, updated_at = ?\n\t\t\tWHERE operation_id = ? AND step_key = 'invite_consumption'`)\n\t\t.run(retryable ? 1 : 0, now, safeErrorCode, now, operationId);\n\tconst outcome = retryable ? \"retry_scheduled\" : \"needs_attention\";\n\tstore.db\n\t\t.prepare(\"UPDATE share_operations SET state = ?, updated_at = ? WHERE operation_id = ?\")\n\t\t.run(\n\t\t\toutcome === \"needs_attention\" ? \"needs_attention\" : \"waiting_for_acceptance\",\n\t\t\tnow,\n\t\t\toperationId,\n\t\t);\n\treturn outcome;\n}\n\nexport async function advancePendingProjectShares(\n\tstore: MemoryStore,\n\toptions: {\n\t\tlimit?: number;\n\t\tnow?: Date;\n\t\tadvanceOperation?: (\n\t\t\tstore: MemoryStore,\n\t\t\toperationId: string,\n\t\t) => Promise<AdvanceProjectShareOperationResult>;\n\t} = {},\n): Promise<AdvancePendingProjectSharesResult> {\n\tconst limit = Math.max(1, Math.min(Math.trunc(options.limit ?? 3), 10));\n\tconst placeholders = AUTOMATIC_SHARE_OPERATION_STATES.map(() => \"?\").join(\", \");\n\tconst maintenanceNow = options.now ?? new Date();\n\tconst waitingAcceptanceRetryBefore = new Date(\n\t\tmaintenanceNow.getTime() - AUTOMATIC_WAITING_ACCEPTANCE_RETRY_COOLDOWN_MS,\n\t).toISOString();\n\tconst waitingRetryBefore = new Date(\n\t\tmaintenanceNow.getTime() - AUTOMATIC_WAITING_DEVICE_RETRY_COOLDOWN_MS,\n\t).toISOString();\n\t// A later failed attempt supersedes older reachability evidence and keeps the cooldown in force.\n\tconst rows = store.db\n\t\t.prepare(`SELECT operation.operation_id FROM share_operations AS operation\n\t\t WHERE operation.inviter_actor_id = ?\n\t\t AND operation.state IN (${placeholders})\n\t\t AND (operation.state <> 'waiting_for_acceptance' OR operation.updated_at <= ?)\n\t\t AND (\n\t\t\toperation.state <> 'waiting_for_device'\n\t\t\tOR operation.updated_at <= ?\n\t\t\tOR (\n\t\t\t\tNOT EXISTS (\n\t\t\t\t\tSELECT 1 FROM share_operation_steps AS step\n\t\t\t\t\tWHERE step.operation_id = operation.operation_id\n\t\t\t\t\tAND step.step_key = 'capability_preflight'\n\t\t\t\t\tAND step.status <> 'completed'\n\t\t\t\t\tAND (\n\t\t\t\t\t\tstep.status = 'running'\n\t\t\t\t\t\tOR step.safe_error_code IN (\n\t\t\t\t\t\t\t'waiting_for_device', 'device_offline', 'recipient_offline'\n\t\t\t\t\t\t)\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t\tAND EXISTS (\n\t\t\t\t\tSELECT 1 FROM sync_attempts AS attempt\n\t\t\t\t\tWHERE attempt.id = (\n\t\t\t\t\t\tSELECT latest.id FROM sync_attempts AS latest\n\t\t\t\t\t\tWHERE latest.peer_device_id = operation.recipient_device_id\n\t\t\t\t\t\tORDER BY latest.started_at DESC, latest.id DESC\n\t\t\t\t\t\tLIMIT 1\n\t\t\t\t\t)\n\t\t\t\t\tAND attempt.ok = 1\n\t\t\t\t\tAND julianday(COALESCE(attempt.finished_at, attempt.started_at)) >\n\t\t\t\t\t\tjulianday(operation.updated_at)\n\t\t\t\t)\n\t\t\t)\n\t\t )\n\t\t ORDER BY CASE WHEN operation.state IN ('accepted', 'provisioning', 'initial_sync') THEN 0 ELSE 1 END,\n\t\t\tCASE WHEN operation.state IN ('waiting_for_acceptance', 'waiting_for_device')\n\t\t\t\tTHEN operation.updated_at ELSE operation.created_at END ASC,\n\t\t\toperation.created_at ASC, operation.operation_id ASC\n\t\t LIMIT ?`)\n\t\t.all(\n\t\t\tstore.actorId,\n\t\t\t...AUTOMATIC_SHARE_OPERATION_STATES,\n\t\t\twaitingAcceptanceRetryBefore,\n\t\t\twaitingRetryBefore,\n\t\t\tlimit,\n\t\t) as Array<{\n\t\toperation_id: string;\n\t}>;\n\tconst advanceOperation = options.advanceOperation ?? advanceProjectShareOperation;\n\tconst result: AdvancePendingProjectSharesResult = {\n\t\tprocessed: 0,\n\t\tadvanced: 0,\n\t\twaiting: 0,\n\t\tattention: 0,\n\t\tfailed: 0,\n\t\titems: [],\n\t};\n\tfor (const row of rows) {\n\t\tresult.processed += 1;\n\t\ttry {\n\t\t\tconst advanced = await advanceOperation(store, row.operation_id);\n\t\t\tif (!advanced.advanced) {\n\t\t\t\tif (advanced.state === \"cancelled\") {\n\t\t\t\t\t// Superseded by a duplicate that reached active first; terminal.\n\t\t\t\t\tresult.items.push({ operationId: row.operation_id, outcome: \"superseded\" });\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tstore.db\n\t\t\t\t\t.prepare(\"UPDATE share_operations SET updated_at = ? WHERE operation_id = ?\")\n\t\t\t\t\t.run(maintenanceNow.toISOString(), row.operation_id);\n\t\t\t\tresult.waiting += 1;\n\t\t\t\tresult.items.push({\n\t\t\t\t\toperationId: row.operation_id,\n\t\t\t\t\toutcome: \"waiting_for_acceptance\",\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tresult.advanced += 1;\n\t\t\tresult.items.push({ operationId: row.operation_id, outcome: \"advanced\" });\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\tconst state = store.db\n\t\t\t\t.prepare(\"SELECT state FROM share_operations WHERE operation_id = ?\")\n\t\t\t\t.pluck()\n\t\t\t\t.get(row.operation_id);\n\t\t\tif (state === \"cancelled\") {\n\t\t\t\t// Superseded by a duplicate while a step was in flight; the stored\n\t\t\t\t// state is terminal and benign, so the step's rejection must not be\n\t\t\t\t// reported as a failure or push the daemon into an error phase.\n\t\t\t\tresult.items.push({ operationId: row.operation_id, outcome: \"superseded\" });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (message === \"waiting_for_device\" || state === \"waiting_for_device\") {\n\t\t\t\tresult.waiting += 1;\n\t\t\t\tresult.items.push({ operationId: row.operation_id, outcome: \"waiting_for_device\" });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (state === \"needs_attention\") {\n\t\t\t\tresult.attention += 1;\n\t\t\t\tresult.items.push({\n\t\t\t\t\toperationId: row.operation_id,\n\t\t\t\t\toutcome: \"needs_attention\",\n\t\t\t\t\terror: message,\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (state === \"waiting_for_acceptance\") {\n\t\t\t\tconst outcome = recordInviteReconciliationFailure(\n\t\t\t\t\tstore,\n\t\t\t\t\trow.operation_id,\n\t\t\t\t\terror,\n\t\t\t\t\tmaintenanceNow.toISOString(),\n\t\t\t\t);\n\t\t\t\tif (outcome === \"needs_attention\") result.attention += 1;\n\t\t\t\telse result.waiting += 1;\n\t\t\t\tresult.items.push({ operationId: row.operation_id, outcome, error: message });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (TERMINAL_SHARE_MAINTENANCE_ERRORS.has(message)) {\n\t\t\t\tstore.db\n\t\t\t\t\t.prepare(\n\t\t\t\t\t\t\"UPDATE share_operations SET state = 'needs_attention', updated_at = ? WHERE operation_id = ?\",\n\t\t\t\t\t)\n\t\t\t\t\t.run(maintenanceNow.toISOString(), row.operation_id);\n\t\t\t\tresult.attention += 1;\n\t\t\t\tresult.items.push({\n\t\t\t\t\toperationId: row.operation_id,\n\t\t\t\t\toutcome: \"needs_attention\",\n\t\t\t\t\terror: message,\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tresult.failed += 1;\n\t\t\tresult.items.push({\n\t\t\t\toperationId: row.operation_id,\n\t\t\t\toutcome: \"failed\",\n\t\t\t\terror: message,\n\t\t\t});\n\t\t}\n\t}\n\treturn result;\n}\n\nexport interface ReconcileConfiguredCoordinatorEnrollmentResult {\n\tskipped: boolean;\n\tgroupsProcessed: number;\n\tfailedGroups: number;\n\tfailures: CoordinatorEnrollmentMaintenanceFailure[];\n\tdevicesAdded: number;\n\tmembershipsAdded: number;\n\tidentitiesAdded: number;\n\tunchanged: number;\n\tissues: number;\n}\n\nexport type CoordinatorEnrollmentMaintenanceStage =\n\t| \"list_devices\"\n\t| \"list_consumed_team_invites\"\n\t| \"reconcile_snapshot\";\n\nexport interface CoordinatorEnrollmentMaintenanceFailure {\n\tgroupId: string;\n\tstage: CoordinatorEnrollmentMaintenanceStage;\n\tcode: string;\n}\n\nfunction coordinatorEnrollmentFailureCode(error: unknown): string {\n\tconst message = (error instanceof Error ? error.message : String(error)).trim();\n\tconst httpStatus = message.match(/\\((\\d{3})(?::|\\))/u)?.[1];\n\tif (httpStatus) return `http_${httpStatus}`;\n\tif (\n\t\tnew Set([\n\t\t\t\"coordinator_consumed_team_invite_invalid\",\n\t\t\t\"coordinator_device_list_malformed\",\n\t\t\t\"coordinator_group_id_invalid\",\n\t\t\t\"coordinator_id_invalid\",\n\t\t\t\"coordinator_invite_group_mismatch\",\n\t\t\t\"coordinator_invite_list_malformed\",\n\t\t\t\"reconciliation_time_invalid\",\n\t\t]).has(message)\n\t) {\n\t\treturn message;\n\t}\n\tif (/timeout|timed out|abort/iu.test(message)) return \"request_timeout\";\n\tif (/fetch failed|network|econn|enotfound/iu.test(message)) return \"network_error\";\n\treturn \"unexpected_error\";\n}\n\nfunction coordinatorEnrollmentFailure(\n\tgroupId: string,\n\tstage: CoordinatorEnrollmentMaintenanceStage,\n\terror: unknown,\n): CoordinatorEnrollmentMaintenanceFailure {\n\tconst safeGroupId = /^[A-Za-z0-9._-]{1,64}$/u.test(groupId)\n\t\t? groupId\n\t\t: `group_${createHash(\"sha256\").update(groupId).digest(\"hex\").slice(0, 12)}`;\n\treturn { groupId: safeGroupId, stage, code: coordinatorEnrollmentFailureCode(error) };\n}\n\nexport async function reconcileConfiguredCoordinatorEnrollment(\n\tstore: MemoryStore,\n\toptions: {\n\t\tconfig?: ReturnType<typeof readCoordinatorSyncConfig>;\n\t\tlistDevices?: (input: {\n\t\t\tgroupId: string;\n\t\t\tremoteUrl: string;\n\t\t\tadminSecret: string;\n\t\t}) => Promise<CoordinatorEnrollment[]>;\n\t\tlistConsumedTeamInvites?: (input: {\n\t\t\tgroupId: string;\n\t\t\tremoteUrl: string;\n\t\t\tadminSecret: string;\n\t\t}) => Promise<CoordinatorConsumedTeamInvite[]>;\n\t\treconcileSnapshot?: (\n\t\t\tinput: Parameters<typeof reconcileCoordinatorEnrollmentSnapshot>[1],\n\t\t) => CoordinatorEnrollmentReconcileResult | Promise<CoordinatorEnrollmentReconcileResult>;\n\t} = {},\n): Promise<ReconcileConfiguredCoordinatorEnrollmentResult> {\n\tconst config = options.config ?? readCoordinatorSyncConfig();\n\tconst remoteUrl = config.syncCoordinatorUrl.trim();\n\tconst adminSecret = config.syncCoordinatorAdminSecret.trim();\n\tif (!remoteUrl || !adminSecret || config.syncCoordinatorGroups.length === 0) {\n\t\treturn {\n\t\t\tskipped: true,\n\t\t\tgroupsProcessed: 0,\n\t\t\tfailedGroups: 0,\n\t\t\tfailures: [],\n\t\t\tdevicesAdded: 0,\n\t\t\tmembershipsAdded: 0,\n\t\t\tidentitiesAdded: 0,\n\t\t\tunchanged: 0,\n\t\t\tissues: 0,\n\t\t};\n\t}\n\tconst listDevices = options.listDevices ?? coordinatorListDevicesAction;\n\tconst listConsumedTeamInvites =\n\t\toptions.listConsumedTeamInvites ?? coordinatorListConsumedTeamInvitesAction;\n\tconst reconcileSnapshot =\n\t\toptions.reconcileSnapshot ??\n\t\t((input) => reconcileCoordinatorEnrollmentSnapshot(store.db, input));\n\tconst total: ReconcileConfiguredCoordinatorEnrollmentResult = {\n\t\tskipped: false,\n\t\tgroupsProcessed: 0,\n\t\tfailedGroups: 0,\n\t\tfailures: [],\n\t\tdevicesAdded: 0,\n\t\tmembershipsAdded: 0,\n\t\tidentitiesAdded: 0,\n\t\tunchanged: 0,\n\t\tissues: 0,\n\t};\n\tfor (const groupId of config.syncCoordinatorGroups) {\n\t\tconst [enrollmentsResult, consumedTeamInvitesResult] = await Promise.allSettled([\n\t\t\tlistDevices({ groupId, remoteUrl, adminSecret }),\n\t\t\tlistConsumedTeamInvites({ groupId, remoteUrl, adminSecret }),\n\t\t]);\n\t\tif (enrollmentsResult.status === \"rejected\") {\n\t\t\ttotal.failures.push(\n\t\t\t\tcoordinatorEnrollmentFailure(groupId, \"list_devices\", enrollmentsResult.reason),\n\t\t\t);\n\t\t}\n\t\tif (consumedTeamInvitesResult.status === \"rejected\") {\n\t\t\ttotal.failures.push(\n\t\t\t\tcoordinatorEnrollmentFailure(\n\t\t\t\t\tgroupId,\n\t\t\t\t\t\"list_consumed_team_invites\",\n\t\t\t\t\tconsumedTeamInvitesResult.reason,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\tenrollmentsResult.status === \"rejected\" ||\n\t\t\tconsumedTeamInvitesResult.status === \"rejected\"\n\t\t) {\n\t\t\ttotal.failedGroups += 1;\n\t\t\tcontinue;\n\t\t}\n\t\ttry {\n\t\t\tconst result = await reconcileSnapshot({\n\t\t\t\tcoordinatorId: buildBaseUrl(remoteUrl),\n\t\t\t\tgroupId,\n\t\t\t\tenrollments: enrollmentsResult.value,\n\t\t\t\tconsumedTeamInvites: consumedTeamInvitesResult.value,\n\t\t\t\tlocalDeviceId: store.deviceId,\n\t\t\t});\n\t\t\ttotal.groupsProcessed += 1;\n\t\t\ttotal.devicesAdded += result.devicesAdded;\n\t\t\ttotal.membershipsAdded += result.membershipsAdded;\n\t\t\ttotal.identitiesAdded += result.identitiesAdded;\n\t\t\ttotal.unchanged += result.unchanged;\n\t\t\ttotal.issues += result.issues.length;\n\t\t} catch (error) {\n\t\t\ttotal.failedGroups += 1;\n\t\t\ttotal.failures.push(coordinatorEnrollmentFailure(groupId, \"reconcile_snapshot\", error));\n\t\t}\n\t}\n\treturn total;\n}\n\nconst RECIPIENT_POLICY_MAINTENANCE_MAX_LIMIT = 10;\nconst RECIPIENT_POLICY_MAINTENANCE_DEFAULT_LIMIT = 3;\nconst RECIPIENT_POLICY_MAINTENANCE_BACKOFF_MS = 60_000;\nconst RECIPIENT_POLICY_WAITING_ERRORS = new Set([\n\t\"recipient_policy_capability_undetermined\",\n\t\"recipient_policy_parity_incomplete\",\n\t\"recipient_policy_snapshot_not_fresh\",\n]);\n\ninterface RecipientPolicyCoordinatorBoundary {\n\tcoordinatorId: string;\n\tgroupId: string;\n\tmembershipEpoch: number;\n}\n\nfunction recipientPolicyCoordinatorBoundary(\n\tstore: MemoryStore,\n\tscopeId: string,\n): RecipientPolicyCoordinatorBoundary {\n\tconst row = store.db\n\t\t.prepare(\n\t\t\t`SELECT coordinator_id, group_id, membership_epoch FROM replication_scopes\n\t\t\t WHERE scope_id = ? AND kind = 'managed_project' AND authority_type = 'coordinator'\n\t\t\t AND status = 'active'`,\n\t\t)\n\t\t.get(scopeId) as\n\t\t| {\n\t\t\t\tcoordinator_id: string | null;\n\t\t\t\tgroup_id: string | null;\n\t\t\t\tmembership_epoch: number;\n\t\t }\n\t\t| undefined;\n\tconst coordinatorId = String(row?.coordinator_id ?? \"\").trim();\n\tconst groupId = String(row?.group_id ?? \"\").trim();\n\tconst membershipEpoch = Number(row?.membership_epoch);\n\tif (!coordinatorId || !groupId || !Number.isSafeInteger(membershipEpoch) || membershipEpoch < 0) {\n\t\tthrow new Error(\"recipient_policy_active_managed_scope_required\");\n\t}\n\treturn { coordinatorId, groupId, membershipEpoch };\n}\n\nfunction recipientPolicySnapshotFingerprint(\n\tscopeId: string,\n\tscopeMembershipEpoch: number,\n\tmemberships: Array<{\n\t\tdeviceId: string;\n\t\tstatus: \"active\" | \"revoked\";\n\t\tmembershipEpoch: number;\n\t}>,\n): string {\n\tconst canonical = memberships\n\t\t.toSorted(\n\t\t\t(left, right) =>\n\t\t\t\tleft.deviceId.localeCompare(right.deviceId) ||\n\t\t\t\tleft.status.localeCompare(right.status) ||\n\t\t\t\tleft.membershipEpoch - right.membershipEpoch,\n\t\t)\n\t\t.map(\n\t\t\t(membership) =>\n\t\t\t\t`${membership.deviceId}\\u0000${membership.status}\\u0000${membership.membershipEpoch}`,\n\t\t)\n\t\t.join(\"\\u0001\");\n\treturn `recipient-policy-coordinator-snapshot-v2:${createHash(\"sha256\")\n\t\t.update(`${scopeId}\\u0000${scopeMembershipEpoch}\\u0000${canonical}`)\n\t\t.digest(\"hex\")}`;\n}\n\nfunction recipientPolicyPresenceCapabilityExpiresAt(\n\tenrollment: CoordinatorEnrollment,\n\tobservedAt: string,\n): number | null {\n\tconst expiresAt = enrollment.presence_expires_at;\n\tconst capabilities = enrollment.presence_capabilities;\n\tif (typeof expiresAt !== \"string\" || !capabilities) return null;\n\tconst expiresAtMs = Date.parse(expiresAt);\n\tconst observedAtMs = Date.parse(observedAt);\n\tif (\n\t\t!Number.isFinite(expiresAtMs) ||\n\t\t!Number.isFinite(observedAtMs) ||\n\t\tnew Date(expiresAtMs).toISOString() !== expiresAt ||\n\t\texpiresAtMs <= observedAtMs ||\n\t\tcapabilities.sync_capability !== \"scoped\" ||\n\t\t!Array.isArray(capabilities.sync_features) ||\n\t\t!capabilities.sync_features.every((feature) => typeof feature === \"string\") ||\n\t\t!capabilities.sync_features.includes(\"reassign_scope\")\n\t) {\n\t\treturn null;\n\t}\n\treturn expiresAtMs;\n}\n\nfunction recipientPolicyEnrollmentValueIsValid(value: unknown): value is string {\n\treturn typeof value === \"string\" && value.length > 0 && value === value.trim();\n}\n\nexport function createRecipientPolicyReconcilerEffects(\n\tstore: MemoryStore,\n\toptions: {\n\t\tconfig?: ReturnType<typeof readCoordinatorSyncConfig>;\n\t\tnow?: () => string;\n\t\tlistDevices?: typeof coordinatorListDevicesAction;\n\t\tlistReviewedRecipientInviteEvidence?: typeof coordinatorListReviewedRecipientInviteEvidenceAction;\n\t} = {},\n): RecipientPolicyReconcilerEffects {\n\tconst config = options.config ?? readCoordinatorSyncConfig();\n\tconst now = options.now ?? (() => new Date().toISOString());\n\tconst listDevices = options.listDevices ?? coordinatorListDevicesAction;\n\tconst listReviewedRecipientInviteEvidence =\n\t\toptions.listReviewedRecipientInviteEvidence ??\n\t\tcoordinatorListReviewedRecipientInviteEvidenceAction;\n\tconst reviewedRecipientInviteEvidence = new Map<\n\t\tstring,\n\t\tReturnType<typeof coordinatorListReviewedRecipientInviteEvidenceAction>\n\t>();\n\tconst loadReviewedRecipientInviteEvidence = (groupId: string) => {\n\t\tlet evidence = reviewedRecipientInviteEvidence.get(groupId);\n\t\tif (!evidence) {\n\t\t\tevidence = listReviewedRecipientInviteEvidence({\n\t\t\t\tgroupId,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\treviewedRecipientInviteEvidence.set(groupId, evidence);\n\t\t}\n\t\treturn evidence;\n\t};\n\tconst boundaryEnrollments = new Map<\n\t\tstring,\n\t\tMap<\n\t\t\tstring,\n\t\t\t{\n\t\t\t\tidentityId: string;\n\t\t\t\tpublicKey: string;\n\t\t\t\tfingerprint: string;\n\t\t\t\tpresenceCapabilityExpiresAtMs: number | null;\n\t\t\t}\n\t\t>\n\t>();\n\tconst target = (scopeId: string) => recipientPolicyCoordinatorBoundary(store, scopeId);\n\tconst coordinatorOptions = (scopeId: string) => {\n\t\tconst boundary = target(scopeId);\n\t\tconst remoteUrl = config.syncCoordinatorUrl?.trim();\n\t\tconst adminSecret = config.syncCoordinatorAdminSecret?.trim();\n\t\tif (!remoteUrl || !adminSecret) throw new Error(\"recipient_policy_effect_failed\");\n\t\tif (!config.syncCoordinatorGroups.includes(boundary.groupId)) {\n\t\t\tthrow new Error(\"recipient_policy_effect_failed\");\n\t\t}\n\t\ttry {\n\t\t\tif (buildBaseUrl(boundary.coordinatorId) !== buildBaseUrl(remoteUrl)) {\n\t\t\t\tthrow new Error(\"recipient_policy_effect_failed\");\n\t\t\t}\n\t\t} catch {\n\t\t\tthrow new Error(\"recipient_policy_effect_failed\");\n\t\t}\n\t\treturn {\n\t\t\t...boundary,\n\t\t\tremoteUrl,\n\t\t\tadminSecret,\n\t\t};\n\t};\n\treturn {\n\t\tnow,\n\t\tsnapshot: async ({ scopeId }) => {\n\t\t\tconst targetOptions = coordinatorOptions(scopeId);\n\t\t\tconst memberships = await coordinatorListScopeMembershipsAction({\n\t\t\t\tgroupId: targetOptions.groupId,\n\t\t\t\tscopeId,\n\t\t\t\tincludeRevoked: true,\n\t\t\t\tremoteUrl: targetOptions.remoteUrl,\n\t\t\t\tadminSecret: targetOptions.adminSecret,\n\t\t\t}).catch(() => {\n\t\t\t\tthrow new Error(\"recipient_policy_snapshot_not_fresh\");\n\t\t\t});\n\t\t\tconst snapshotMemberships = memberships.map((membership) => {\n\t\t\t\tif (\n\t\t\t\t\ttypeof membership.device_id !== \"string\" ||\n\t\t\t\t\t(membership.status !== \"active\" && membership.status !== \"revoked\")\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"recipient_policy_snapshot_invalid\");\n\t\t\t\t}\n\t\t\t\tconst status: \"active\" | \"revoked\" = membership.status;\n\t\t\t\treturn {\n\t\t\t\t\tdeviceId: membership.device_id,\n\t\t\t\t\tstatus,\n\t\t\t\t\tmembershipEpoch: membership.membership_epoch,\n\t\t\t\t};\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tauthoritative: true,\n\t\t\t\tscopeId,\n\t\t\t\tscopeMembershipEpoch: targetOptions.membershipEpoch,\n\t\t\t\tfingerprint: recipientPolicySnapshotFingerprint(\n\t\t\t\t\tscopeId,\n\t\t\t\t\ttargetOptions.membershipEpoch,\n\t\t\t\t\tsnapshotMemberships,\n\t\t\t\t),\n\t\t\t\tobservedAt: now(),\n\t\t\t\tmemberships: snapshotMemberships,\n\t\t\t};\n\t\t},\n\t\tlistBoundaryEnrollments: async ({ scopeId }) => {\n\t\t\tconst targetOptions = coordinatorOptions(scopeId);\n\t\t\tconst observedAt = now();\n\t\t\tconst enrollments = await listDevices({\n\t\t\t\tgroupId: targetOptions.groupId,\n\t\t\t\tincludeDisabled: true,\n\t\t\t\tremoteUrl: targetOptions.remoteUrl,\n\t\t\t\tadminSecret: targetOptions.adminSecret,\n\t\t\t}).catch(() => {\n\t\t\t\tthrow new Error(\"recipient_policy_snapshot_not_fresh\");\n\t\t\t});\n\t\t\tconst presenceCapabilityExpiries = new Map(\n\t\t\t\tenrollments.map((enrollment) => [\n\t\t\t\t\tenrollment.device_id,\n\t\t\t\t\trecipientPolicyPresenceCapabilityExpiresAt(enrollment, observedAt),\n\t\t\t\t]),\n\t\t\t);\n\t\t\tconst mapped = enrollments.map((enrollment) => {\n\t\t\t\tif (\n\t\t\t\t\tenrollment.group_id !== targetOptions.groupId ||\n\t\t\t\t\t!recipientPolicyEnrollmentValueIsValid(enrollment.device_id) ||\n\t\t\t\t\t!recipientPolicyEnrollmentValueIsValid(enrollment.public_key) ||\n\t\t\t\t\t!recipientPolicyEnrollmentValueIsValid(enrollment.fingerprint) ||\n\t\t\t\t\tfingerprintPublicKey(enrollment.public_key) !== enrollment.fingerprint ||\n\t\t\t\t\t(enrollment.enabled !== 0 && enrollment.enabled !== 1) ||\n\t\t\t\t\t(enrollment.identity_id !== null &&\n\t\t\t\t\t\t!recipientPolicyEnrollmentValueIsValid(enrollment.identity_id))\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(\"recipient_policy_snapshot_invalid\");\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tdeviceId: enrollment.device_id,\n\t\t\t\t\tidentityId: enrollment.identity_id,\n\t\t\t\t\tpublicKey: enrollment.public_key,\n\t\t\t\t\tfingerprint: enrollment.fingerprint,\n\t\t\t\t\tenabled: enrollment.enabled === 1,\n\t\t\t\t};\n\t\t\t});\n\t\t\tboundaryEnrollments.set(\n\t\t\t\tscopeId,\n\t\t\t\tnew Map(\n\t\t\t\t\tmapped.flatMap((enrollment) =>\n\t\t\t\t\t\tenrollment.enabled && enrollment.identityId !== null\n\t\t\t\t\t\t\t? [\n\t\t\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t\t\tenrollment.deviceId,\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tidentityId: enrollment.identityId,\n\t\t\t\t\t\t\t\t\t\t\tpublicKey: enrollment.publicKey,\n\t\t\t\t\t\t\t\t\t\t\tfingerprint: enrollment.fingerprint,\n\t\t\t\t\t\t\t\t\t\t\tpresenceCapabilityExpiresAtMs:\n\t\t\t\t\t\t\t\t\t\t\t\tpresenceCapabilityExpiries.get(enrollment.deviceId) ?? null,\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t] as const,\n\t\t\t\t\t\t\t\t]\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\treturn mapped;\n\t\t},\n\t\tprobeCapability: async ({ deviceId, scopeId }) => {\n\t\t\tif (deviceId === store.deviceId) return \"supported\";\n\t\t\t// Reconciliation always lists this scope's enrollments before capability\n\t\t\t// preflight. A missing binding still fails closed if that order changes.\n\t\t\tconst targetOptions = coordinatorOptions(scopeId);\n\t\t\tconst enrollment = boundaryEnrollments.get(scopeId)?.get(deviceId);\n\t\t\tif (!enrollment) return \"undetermined\";\n\t\t\tconst peer = store.db\n\t\t\t\t.prepare(\"SELECT pinned_fingerprint, public_key FROM sync_peers WHERE peer_device_id = ?\")\n\t\t\t\t.get(deviceId) as\n\t\t\t\t| { pinned_fingerprint: string | null; public_key: string | null }\n\t\t\t\t| undefined;\n\t\t\tif (peer) {\n\t\t\t\tconst peerPublicKey = String(peer.public_key ?? \"\").trim();\n\t\t\t\tconst peerFingerprint =\n\t\t\t\t\tString(peer.pinned_fingerprint ?? \"\").trim() ||\n\t\t\t\t\t(peerPublicKey ? fingerprintPublicKey(peerPublicKey) : \"\");\n\t\t\t\tif (\n\t\t\t\t\t(peerFingerprint || peerPublicKey) &&\n\t\t\t\t\t(peerFingerprint !== enrollment.fingerprint ||\n\t\t\t\t\t\t(peerPublicKey && peerPublicKey !== enrollment.publicKey))\n\t\t\t\t) {\n\t\t\t\t\treturn \"undetermined\";\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst observed = await peerSupportsSyncRequirements(store, deviceId, {\n\t\t\t\tscoped: true,\n\t\t\t\treassignScope: true,\n\t\t\t});\n\t\t\tif (observed !== \"undetermined\") return observed;\n\t\t\tconst observedAtMs = Date.parse(now());\n\t\t\tif (\n\t\t\t\tenrollment.presenceCapabilityExpiresAtMs == null ||\n\t\t\t\t!Number.isFinite(observedAtMs) ||\n\t\t\t\tenrollment.presenceCapabilityExpiresAtMs <= observedAtMs\n\t\t\t) {\n\t\t\t\treturn \"undetermined\";\n\t\t\t}\n\t\t\t// A consumed, still-reviewed Team/add-device invite is the only bootstrap\n\t\t\t// identity proof accepted before normal peer discovery can observe the new\n\t\t\t// device. Fresh authenticated presence separately proves capability.\n\t\t\tconst evidence = await loadReviewedRecipientInviteEvidence(targetOptions.groupId).catch(\n\t\t\t\t() => [],\n\t\t\t);\n\t\t\treturn evidence.some(\n\t\t\t\t(invite) =>\n\t\t\t\t\tinvite.group_id === targetOptions.groupId &&\n\t\t\t\t\tinvite.bound_device_id === deviceId &&\n\t\t\t\t\tinvite.recipient_actor_id === enrollment.identityId &&\n\t\t\t\t\tinvite.bound_public_key === enrollment.publicKey &&\n\t\t\t\t\tinvite.bound_fingerprint === enrollment.fingerprint,\n\t\t\t)\n\t\t\t\t? \"supported\"\n\t\t\t\t: \"undetermined\";\n\t\t},\n\t\trevoke: async (input): Promise<RecipientPolicyCoordinatorEffectReceipt> => {\n\t\t\tconst targetOptions = coordinatorOptions(input.scopeId);\n\t\t\tawait coordinatorRevokeScopeMembershipAction({\n\t\t\t\teffectId: input.effectId,\n\t\t\t\tgroupId: targetOptions.groupId,\n\t\t\t\tscopeId: input.scopeId,\n\t\t\t\tdeviceId: input.deviceId,\n\t\t\t\tremoteUrl: targetOptions.remoteUrl,\n\t\t\t\tadminSecret: targetOptions.adminSecret,\n\t\t\t});\n\t\t\treturn {\n\t\t\t\teffectId: input.effectId,\n\t\t\t\tscopeId: input.scopeId,\n\t\t\t\tdeviceId: input.deviceId,\n\t\t\t\tstatus: \"revoked\",\n\t\t\t};\n\t\t},\n\t\tgrant: async (input): Promise<RecipientPolicyCoordinatorEffectReceipt> => {\n\t\t\tconst targetOptions = coordinatorOptions(input.scopeId);\n\t\t\tconst membership = await coordinatorGrantScopeMembershipAction({\n\t\t\t\teffectId: input.effectId,\n\t\t\t\tgroupId: targetOptions.groupId,\n\t\t\t\tscopeId: input.scopeId,\n\t\t\t\tdeviceId: input.deviceId,\n\t\t\t\trole: input.role,\n\t\t\t\tcoordinatorId: targetOptions.coordinatorId,\n\t\t\t\tremoteUrl: targetOptions.remoteUrl,\n\t\t\t\tadminSecret: targetOptions.adminSecret,\n\t\t\t});\n\t\t\treturn {\n\t\t\t\teffectId: input.effectId,\n\t\t\t\tscopeId: membership.scope_id,\n\t\t\t\tdeviceId: membership.device_id,\n\t\t\t\tstatus: membership.status === \"active\" ? \"active\" : \"revoked\",\n\t\t\t};\n\t\t},\n\t\trefresh: async ({ scopeId }) => {\n\t\t\tconst boundary = target(scopeId);\n\t\t\tconst refreshed = await refreshConfiguredScopeMembershipCache(store.db, config, {\n\t\t\t\tkeysDir: syncKeysDir(),\n\t\t\t\tdbPath: store.dbPath,\n\t\t\t});\n\t\t\tconst group = refreshed.groups.find((item) => item.groupId === boundary.groupId);\n\t\t\tif (group?.status !== \"refreshed\") throw new Error(\"recipient_policy_effect_failed\");\n\t\t\tawait refreshAuthorizedCoordinatorPeerTrust(store, config);\n\t\t},\n\t};\n}\n\nexport interface ReconcileRecipientPolicyProjectsResult {\n\tprocessed: number;\n\tactive: number;\n\twaiting: number;\n\tattention: number;\n\tfailed: number;\n\titems: Array<{\n\t\tcanonicalProjectIdentity: string;\n\t\tstatus: RecipientPolicyReconcileResult[\"status\"] | \"failed\";\n\t\tsafeErrorCode: string | null;\n\t}>;\n}\n\nexport async function reconcileRecipientPolicyProjects(\n\tstore: MemoryStore,\n\toptions: {\n\t\tlimit?: number;\n\t\tnow?: Date;\n\t\tbackoffMs?: number;\n\t\tleaseOwner?: string;\n\t\teffects?: RecipientPolicyReconcilerEffects;\n\t\treconcileProject?: typeof reconcileRecipientPolicyProject;\n\t} = {},\n): Promise<ReconcileRecipientPolicyProjectsResult> {\n\tconst limit = Math.max(\n\t\t1,\n\t\tMath.min(\n\t\t\tMath.trunc(options.limit ?? RECIPIENT_POLICY_MAINTENANCE_DEFAULT_LIMIT),\n\t\t\tRECIPIENT_POLICY_MAINTENANCE_MAX_LIMIT,\n\t\t),\n\t);\n\tconst maintenanceNow = options.now ?? new Date();\n\tconst backoffMs = Math.max(\n\t\t0,\n\t\tMath.trunc(options.backoffMs ?? RECIPIENT_POLICY_MAINTENANCE_BACKOFF_MS),\n\t);\n\tconst retryBefore = new Date(maintenanceNow.getTime() - backoffMs).toISOString();\n\tconst rows = store.db\n\t\t.prepare(\n\t\t\t`WITH projects AS (\n\t\t\t\tSELECT DISTINCT canonical_project_identity FROM project_recipients\n\t\t\t\tUNION\n\t\t\t\tSELECT canonical_project_identity FROM recipient_policy_authority_states\n\t\t\t)\n\t\t\t SELECT projects.canonical_project_identity\n\t\t\t FROM projects\n\t\t\t LEFT JOIN recipient_policy_authority_states authority\n\t\t\t ON authority.canonical_project_identity = projects.canonical_project_identity\n\t\t\t WHERE authority.safe_error_code IS NULL OR authority.last_attempt_at IS NULL\n\t\t\t OR authority.last_attempt_at <= ?\n\t\t\t ORDER BY CASE WHEN authority.last_attempt_at IS NULL THEN 0 ELSE 1 END,\n\t\t\t authority.last_attempt_at, projects.canonical_project_identity\n\t\t\t LIMIT ?`,\n\t\t)\n\t\t.all(retryBefore, limit) as Array<{ canonical_project_identity: string }>;\n\tconst effects = options.effects ?? createRecipientPolicyReconcilerEffects(store);\n\tconst reconcileProject = options.reconcileProject ?? reconcileRecipientPolicyProject;\n\tconst result: ReconcileRecipientPolicyProjectsResult = {\n\t\tprocessed: 0,\n\t\tactive: 0,\n\t\twaiting: 0,\n\t\tattention: 0,\n\t\tfailed: 0,\n\t\titems: [],\n\t};\n\tfor (const row of rows) {\n\t\tresult.processed += 1;\n\t\ttry {\n\t\t\tconst outcome = await reconcileProject(\n\t\t\t\tstore.db,\n\t\t\t\t{\n\t\t\t\t\tcanonicalProjectIdentity: row.canonical_project_identity,\n\t\t\t\t\tleaseOwner:\n\t\t\t\t\t\toptions.leaseOwner ?? `recipient-policy-maintenance:${store.deviceId || process.pid}`,\n\t\t\t\t},\n\t\t\t\teffects,\n\t\t\t);\n\t\t\tif (outcome.status === \"active\") result.active += 1;\n\t\t\telse if (outcome.status === \"needs_attention\") result.attention += 1;\n\t\t\telse result.waiting += 1;\n\t\t\tresult.items.push({\n\t\t\t\tcanonicalProjectIdentity: row.canonical_project_identity,\n\t\t\t\tstatus: outcome.status,\n\t\t\t\tsafeErrorCode: outcome.safeErrorCode,\n\t\t\t});\n\t\t} catch {\n\t\t\tresult.failed += 1;\n\t\t\tresult.items.push({\n\t\t\t\tcanonicalProjectIdentity: row.canonical_project_identity,\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tsafeErrorCode: \"recipient_policy_reconciliation_failed\",\n\t\t\t});\n\t\t}\n\t}\n\treturn result;\n}\n\nexport type RecipientPolicyReconciliationReadState =\n\t| \"active\"\n\t| \"needs_attention\"\n\t| \"pending\"\n\t| \"verifying\"\n\t| \"waiting\";\n\nexport interface RecipientPolicyReconciliationReadModel {\n\tversion: 1;\n\titems: Array<{\n\t\tcanonicalProjectIdentity: string;\n\t\tstate: RecipientPolicyReconciliationReadState;\n\t\tlabel: string;\n\t\texplanation: string;\n\t\tdeliveredCopiesMayRemain: true;\n\t\trevocationWarning: string;\n\t}>;\n}\n\nfunction recipientPolicyReadState(\n\tauthority: ReturnType<typeof getRecipientPolicyAuthorityState>,\n): RecipientPolicyReconciliationReadState {\n\tif (!authority) return \"pending\";\n\tif (authority.safeErrorCode && RECIPIENT_POLICY_WAITING_ERRORS.has(authority.safeErrorCode)) {\n\t\treturn \"waiting\";\n\t}\n\tif (authority.safeErrorCode || authority.authorityState === \"rolled_back\") {\n\t\treturn \"needs_attention\";\n\t}\n\tif (authority.authorityState === \"active\") return \"active\";\n\tif (authority.authorityState === \"eligible\") return \"verifying\";\n\treturn \"pending\";\n}\n\nfunction recipientPolicyReadCopy(state: RecipientPolicyReconciliationReadState): {\n\tlabel: string;\n\texplanation: string;\n} {\n\tif (state === \"active\") {\n\t\treturn {\n\t\t\tlabel: \"Recipient policy active\",\n\t\t\texplanation: \"Recipient policy now controls future access for this Project.\",\n\t\t};\n\t}\n\tif (state === \"verifying\") {\n\t\treturn {\n\t\t\tlabel: \"Verifying recipient policy\",\n\t\t\texplanation: \"Current access matches recipient policy and needs one more stable check.\",\n\t\t};\n\t}\n\tif (state === \"waiting\") {\n\t\treturn {\n\t\t\tlabel: \"Waiting to reconcile\",\n\t\t\texplanation:\n\t\t\t\t\"Waiting for devices or a fresh coordinator snapshot. No partial grant is applied.\",\n\t\t};\n\t}\n\tif (state === \"needs_attention\") {\n\t\treturn {\n\t\t\tlabel: \"Reconciliation needs attention\",\n\t\t\texplanation:\n\t\t\t\t\"Legacy scope enforcement remains in control until this Project is safe to retry.\",\n\t\t};\n\t}\n\treturn {\n\t\tlabel: \"Recipient policy pending\",\n\t\texplanation: \"Legacy scope enforcement remains in control while reconciliation is pending.\",\n\t};\n}\n\nexport function listRecipientPolicyReconciliationStatus(\n\tstore: MemoryStore,\n): RecipientPolicyReconciliationReadModel {\n\tconst projectIds = (\n\t\tstore.db\n\t\t\t.prepare(\n\t\t\t\t`SELECT DISTINCT canonical_project_identity FROM project_recipients WHERE status = 'active'\n\t\t\t\t UNION SELECT canonical_project_identity FROM recipient_policy_authority_states\n\t\t\t\t ORDER BY canonical_project_identity`,\n\t\t\t)\n\t\t\t.all() as Array<{ canonical_project_identity: string }>\n\t).map((row) => row.canonical_project_identity);\n\treturn {\n\t\tversion: 1,\n\t\titems: projectIds.map((canonicalProjectIdentity) => {\n\t\t\tconst state = recipientPolicyReadState(\n\t\t\t\tgetRecipientPolicyAuthorityState(store.db, canonicalProjectIdentity),\n\t\t\t);\n\t\t\treturn {\n\t\t\t\tcanonicalProjectIdentity,\n\t\t\t\tstate,\n\t\t\t\t...recipientPolicyReadCopy(state),\n\t\t\t\tdeliveredCopiesMayRemain: true,\n\t\t\t\trevocationWarning: SCOPE_MEMBERSHIP_REVOCATION_LIMITATION,\n\t\t\t};\n\t\t}),\n\t};\n}\n\nfunction sortActiveMaintenanceJobs<\n\tT extends { started_at: string | null; updated_at: string; kind: string },\n>(jobs: T[]): T[] {\n\treturn [...jobs].sort((a, b) => {\n\t\tconst aTime = a.started_at ?? a.updated_at;\n\t\tconst bTime = b.started_at ?? b.updated_at;\n\t\tif (aTime !== bTime) return aTime.localeCompare(bTime);\n\t\treturn a.kind.localeCompare(b.kind);\n\t});\n}\n\nfunction summarizeMaintenanceJobs(\n\tjobs: MaintenanceJobSnapshot[],\n\tshowDiagnostics: boolean,\n): Array<Record<string, unknown>> {\n\treturn sortActiveMaintenanceJobs(\n\t\tjobs.filter((job) => [\"pending\", \"running\", \"failed\"].includes(String(job.status ?? \"\"))),\n\t).map((job) => ({\n\t\tkind: job.kind,\n\t\ttitle: job.title,\n\t\tstatus: job.status,\n\t\tprogress: job.progress,\n\t\t...(showDiagnostics\n\t\t\t? {\n\t\t\t\t\tmessage: job.message,\n\t\t\t\t\terror: job.error,\n\t\t\t\t\tmetadata: job.metadata,\n\t\t\t\t}\n\t\t\t: {}),\n\t}));\n}\n\nfunction redactSemanticIndexDiagnostics(\n\tdiagnostics: SemanticIndexDiagnostics,\n\tshowDiagnostics: boolean,\n): SemanticIndexDiagnostics {\n\tif (showDiagnostics || !diagnostics.maintenance_job) {\n\t\treturn diagnostics;\n\t}\n\tconst summary =\n\t\tdiagnostics.state === \"pending\"\n\t\t\t? \"Semantic-index catch-up is pending\"\n\t\t\t: diagnostics.state === \"failed\"\n\t\t\t\t? \"Semantic-index catch-up failed\"\n\t\t\t\t: diagnostics.state === \"degraded\"\n\t\t\t\t\t? \"Semantic index is running in degraded mode\"\n\t\t\t\t\t: diagnostics.summary;\n\treturn {\n\t\t...diagnostics,\n\t\tsummary,\n\t\tmaintenance_job: {\n\t\t\t...diagnostics.maintenance_job,\n\t\t\tmessage: null,\n\t\t\terror: null,\n\t\t},\n\t};\n}\n\nfunction syncKeysDir(): string | undefined {\n\treturn process.env.CODEMEM_KEYS_DIR?.trim() || undefined;\n}\n\n/** Strip control/format characters and cap length so attacker-controlled\n * headers cannot forge log lines when included in diagnostics. */\nfunction loggableHeaderValue(value: string | undefined): string {\n\tconst sanitized = (value ?? \"\")\n\t\t.replace(/[\\p{Cc}\\p{Cf}]/gu, \"\")\n\t\t.slice(0, 64)\n\t\t.trim();\n\treturn sanitized || \"unknown\";\n}\n\nfunction intEnvOr(name: string, fallback: number): number {\n\tconst value = Number.parseInt(process.env[name] ?? \"\", 10);\n\treturn Number.isFinite(value) ? value : fallback;\n}\n\nconst MAX_SYNC_BODY_BYTES = intEnvOr(\"CODEMEM_SYNC_MAX_BODY_BYTES\", 1_048_576);\nconst MAX_SYNC_OPS = intEnvOr(\"CODEMEM_SYNC_MAX_OPS\", 2000);\n\nasync function readBoundedRequestBytes(request: Request, maxBytes: number): Promise<Buffer | null> {\n\tconst contentLength = Number.parseInt(request.headers.get(\"content-length\") ?? \"\", 10);\n\tif (Number.isFinite(contentLength) && contentLength > maxBytes) {\n\t\treturn null;\n\t}\n\tconst stream = request.body;\n\tif (!stream) return Buffer.alloc(0);\n\tconst reader = stream.getReader();\n\tconst chunks: Uint8Array[] = [];\n\tlet total = 0;\n\ttry {\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) break;\n\t\t\tif (!value) continue;\n\t\t\ttotal += value.byteLength;\n\t\t\tif (total > maxBytes) {\n\t\t\t\tawait reader.cancel();\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tchunks.push(value);\n\t\t}\n\t} finally {\n\t\treader.releaseLock();\n\t}\n\treturn Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)));\n}\n\nconst PAIRING_FILTER_HINT =\n\t\"Run this on another device with codemem sync pair --accept '<payload>'. \" +\n\t\"On the accepting device, --include/--exclude control both what it sends and what it accepts from that peer.\";\n\nfunction pathWithQuery(url: string): string {\n\tconst parsed = new URL(url);\n\treturn parsed.search ? `${parsed.pathname}${parsed.search}` : parsed.pathname;\n}\n\nfunction unauthorizedPayload(): Record<string, string> {\n\treturn { error: \"unauthorized\" };\n}\n\nconst SYNC_AUTH_STORE_BUSY_REASON = \"sync_auth_store_busy\";\n\ntype SyncAuthResult = { ok: boolean; reason: string; deviceId: string };\ntype VerifiedDirectPeerSignature = { ok: true; version: 2 | 3 } | { ok: false; reason: string };\n\nconst DIRECT_PEER_SIGNATURE_VERSION_NUMBER = 3;\n\nfunction logDirectPeerAuthDiagnostic(...reasons: Array<string | null>): void {\n\tconst reason = reasons.find(\n\t\t(candidate) => candidate === \"recipient_mismatch\" || candidate === \"signature_downgrade\",\n\t);\n\tif (reason) console.warn(`[sync] peer auth failed: reason=${reason}`);\n}\n\nfunction isSqliteBusy(err: unknown): boolean {\n\tif (!err || typeof err !== \"object\") return false;\n\tconst code = \"code\" in err ? String((err as { code?: unknown }).code ?? \"\") : \"\";\n\tconst message = err instanceof Error ? err.message : \"\";\n\treturn code === \"SQLITE_BUSY\" || message.includes(\"database is locked\");\n}\n\nfunction recordSyncAuthNonce(\n\tstore: MemoryStore,\n\tdeviceId: string,\n\tnonce: string,\n\tcreatedAt: string,\n): SyncAuthResult | null {\n\ttry {\n\t\tif (!recordNonce(store.db, deviceId, nonce, createdAt)) {\n\t\t\treturn { ok: false, reason: \"nonce_replay\", deviceId };\n\t\t}\n\t} catch (err) {\n\t\tif (isSqliteBusy(err)) {\n\t\t\treturn { ok: false, reason: SYNC_AUTH_STORE_BUSY_REASON, deviceId };\n\t\t}\n\t\tthrow err;\n\t}\n\n\tconst cutoff = new Date(Date.now() - DEFAULT_TIME_WINDOW_S * 2 * 1000).toISOString();\n\ttry {\n\t\tcleanupNonces(store.db, cutoff);\n\t} catch (err) {\n\t\tif (!isSqliteBusy(err)) throw err;\n\t\t// Nonce cleanup is best-effort. A lock here should not fail a request\n\t\t// after its nonce was already recorded; the next request can prune.\n\t}\n\treturn null;\n}\n\nfunction isSyncAuthStoreBusy(auth: SyncAuthResult): boolean {\n\treturn !auth.ok && auth.reason === SYNC_AUTH_STORE_BUSY_REASON;\n}\n\nfunction syncAuthStoreBusyResponse(c: Context) {\n\tc.header(\"Retry-After\", \"1\");\n\treturn c.json({ error: SYNC_AUTH_STORE_BUSY_REASON }, 503);\n}\n\nfunction verifyDirectPeerRequestSignature(\n\trequest: { method: string; url: string; header(name: string): string | undefined },\n\tbody: Buffer,\n\toptions: {\n\t\tdeviceId: string;\n\t\tpublicKey: string;\n\t\texpectedRecipientId: string;\n\t\thighestObservedVersion: number | null;\n\t},\n): VerifiedDirectPeerSignature {\n\tconst timestamp = request.header(\"X-Opencode-Timestamp\") ?? \"\";\n\tconst nonce = request.header(\"X-Opencode-Nonce\") ?? \"\";\n\tconst legacySignature = request.header(\"X-Opencode-Signature\") ?? \"\";\n\tconst recipientHeader = request.header(\"X-Codemem-Recipient\");\n\tconst directSignatureHeader = request.header(\"X-Codemem-Signature\");\n\tconst hasDirectMaterial = recipientHeader !== undefined || directSignatureHeader !== undefined;\n\tconst direct = verifyDirectPeerSignature({\n\t\tmethod: request.method,\n\t\tpathWithQuery: pathWithQuery(request.url),\n\t\tbodyBytes: body,\n\t\ttimestamp,\n\t\tnonce,\n\t\trecipientId: recipientHeader,\n\t\texpectedRecipientId: options.expectedRecipientId,\n\t\tsignature: directSignatureHeader,\n\t\tpublicKey: options.publicKey,\n\t});\n\tif (hasDirectMaterial && direct.status === \"absent\") {\n\t\treturn { ok: false, reason: \"invalid_direct_signature\" };\n\t}\n\tif (direct.status === \"invalid\") {\n\t\treturn {\n\t\t\tok: false,\n\t\t\treason: direct.reason === \"recipient_mismatch\" ? direct.reason : \"invalid_direct_signature\",\n\t\t};\n\t}\n\n\tconst legacyValid = verifySignature({\n\t\tmethod: request.method,\n\t\tpathWithQuery: pathWithQuery(request.url),\n\t\tbodyBytes: body,\n\t\ttimestamp,\n\t\tnonce,\n\t\tsignature: legacySignature,\n\t\tpublicKey: options.publicKey,\n\t\tdeviceId: options.deviceId,\n\t});\n\tif (!legacyValid) return { ok: false, reason: \"invalid_signature\" };\n\tif (\n\t\tdirect.status === \"absent\" &&\n\t\t(options.highestObservedVersion ?? 0) >= DIRECT_PEER_SIGNATURE_VERSION_NUMBER\n\t) {\n\t\treturn { ok: false, reason: \"signature_downgrade\" };\n\t}\n\treturn { ok: true, version: direct.status === \"valid\" ? 3 : 2 };\n}\n\nfunction recordDirectPeerSignatureVersion(\n\tstore: MemoryStore,\n\tdeviceId: string,\n\tversion: 3,\n): SyncAuthResult | null {\n\ttry {\n\t\tconst advanced = recordHighestObservedDirectSignatureVersion(store.db, deviceId, version);\n\t\tif (!advanced) {\n\t\t\tconst observed = store.db\n\t\t\t\t.prepare(\n\t\t\t\t\t`SELECT sync_peer_signature_state.highest_observed_direct_signature_version\n\t\t\t\t\t FROM sync_peers\n\t\t\t\t\t LEFT JOIN sync_peer_signature_state USING (peer_device_id)\n\t\t\t\t\t WHERE sync_peers.peer_device_id = ? LIMIT 1`,\n\t\t\t\t)\n\t\t\t\t.pluck()\n\t\t\t\t.get(deviceId);\n\t\t\tif (observed === undefined) return { ok: false, reason: \"unknown_peer\", deviceId };\n\t\t}\n\t\treturn null;\n\t} catch (err) {\n\t\tif (isSqliteBusy(err)) {\n\t\t\treturn { ok: false, reason: SYNC_AUTH_STORE_BUSY_REASON, deviceId };\n\t\t}\n\t\tthrow err;\n\t}\n}\n\nfunction authorizeSyncRequest(\n\tstore: MemoryStore,\n\trequest: { method: string; url: string; header(name: string): string | undefined },\n\tbody: Buffer,\n): SyncAuthResult {\n\tconst deviceId = (request.header(\"X-Opencode-Device\") ?? \"\").trim();\n\tconst signature = request.header(\"X-Opencode-Signature\") ?? \"\";\n\tconst timestamp = request.header(\"X-Opencode-Timestamp\") ?? \"\";\n\tconst nonce = request.header(\"X-Opencode-Nonce\") ?? \"\";\n\tif (!deviceId || !signature || !timestamp || !nonce) {\n\t\treturn { ok: false, reason: \"missing_headers\", deviceId };\n\t}\n\n\tconst peerRow = store.db\n\t\t.prepare(\n\t\t\t`SELECT sync_peers.pinned_fingerprint, sync_peers.public_key,\n\t\t\t sync_peer_signature_state.highest_observed_direct_signature_version\n\t\t\t FROM sync_peers\n\t\t\t LEFT JOIN sync_peer_signature_state USING (peer_device_id)\n\t\t\t WHERE sync_peers.peer_device_id = ? LIMIT 1`,\n\t\t)\n\t\t.get(deviceId) as\n\t\t| {\n\t\t\t\tpinned_fingerprint: string | null;\n\t\t\t\tpublic_key: string | null;\n\t\t\t\thighest_observed_direct_signature_version: number | null;\n\t\t }\n\t\t| undefined;\n\tif (!peerRow) {\n\t\treturn { ok: false, reason: \"unknown_peer\", deviceId };\n\t}\n\n\tconst pinnedFingerprint = String(peerRow.pinned_fingerprint ?? \"\").trim();\n\tconst publicKey = String(peerRow.public_key ?? \"\").trim();\n\tif (!pinnedFingerprint || !publicKey) {\n\t\treturn { ok: false, reason: \"peer_record_incomplete\", deviceId };\n\t}\n\tif (fingerprintPublicKey(publicKey) !== pinnedFingerprint) {\n\t\treturn { ok: false, reason: \"fingerprint_mismatch\", deviceId };\n\t}\n\n\tlet verification: VerifiedDirectPeerSignature;\n\ttry {\n\t\tconst [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });\n\t\tverification = verifyDirectPeerRequestSignature(request, body, {\n\t\t\tdeviceId,\n\t\t\tpublicKey,\n\t\t\texpectedRecipientId: localDeviceId,\n\t\t\thighestObservedVersion: peerRow.highest_observed_direct_signature_version,\n\t\t});\n\t} catch {\n\t\treturn { ok: false, reason: \"signature_verification_error\", deviceId };\n\t}\n\tif (!verification.ok) {\n\t\treturn { ok: false, reason: verification.reason, deviceId };\n\t}\n\n\tconst createdAt = new Date().toISOString();\n\tconst nonceResult = recordSyncAuthNonce(store, deviceId, nonce, createdAt);\n\tif (nonceResult) return nonceResult;\n\tif (verification.version === DIRECT_PEER_SIGNATURE_VERSION_NUMBER) {\n\t\tconst versionResult = recordDirectPeerSignatureVersion(store, deviceId, verification.version);\n\t\tif (versionResult) return versionResult;\n\t}\n\treturn { ok: true, reason: \"ok\", deviceId };\n}\n\nasync function authorizeBootstrapGrantRequest(\n\tstore: MemoryStore,\n\trequest: { method: string; url: string; header(name: string): string | undefined },\n\tbody: Buffer,\n): Promise<SyncAuthResult> {\n\tconst grantId = (request.header(\"X-Codemem-Bootstrap-Grant\") ?? \"\").trim();\n\tconst deviceId = (request.header(\"X-Opencode-Device\") ?? \"\").trim();\n\tconst signature = request.header(\"X-Opencode-Signature\") ?? \"\";\n\tconst timestamp = request.header(\"X-Opencode-Timestamp\") ?? \"\";\n\tconst nonce = request.header(\"X-Opencode-Nonce\") ?? \"\";\n\tif (!grantId || !deviceId || !signature || !timestamp || !nonce) {\n\t\treturn { ok: false, reason: \"missing_bootstrap_grant_headers\", deviceId };\n\t}\n\n\tconst config = readCoordinatorSyncConfig();\n\tif (!config.syncCoordinatorUrl) {\n\t\treturn { ok: false, reason: \"bootstrap_grant_coordinator_not_configured\", deviceId };\n\t}\n\n\tconst [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });\n\tlet verification: CoordinatorBootstrapGrantVerification;\n\ttry {\n\t\tlet payload: Record<string, unknown> | null = null;\n\t\tif (config.syncCoordinatorAdminSecret) {\n\t\t\tconst [status, adminPayload] = await requestJson(\n\t\t\t\t\"GET\",\n\t\t\t\t`${buildBaseUrl(config.syncCoordinatorUrl)}/v1/admin/bootstrap-grants/${encodeURIComponent(grantId)}`,\n\t\t\t\t{\n\t\t\t\t\theaders: { \"X-Codemem-Coordinator-Admin\": config.syncCoordinatorAdminSecret },\n\t\t\t\t\ttimeoutS: Math.max(1, config.syncCoordinatorTimeoutS),\n\t\t\t\t},\n\t\t\t);\n\t\t\tif (status === 200) payload = adminPayload;\n\t\t} else {\n\t\t\tfor (const groupId of config.syncCoordinatorGroups) {\n\t\t\t\tconst lookupUrl = `${buildBaseUrl(config.syncCoordinatorUrl)}/v1/bootstrap-grants/${encodeURIComponent(grantId)}?group_id=${encodeURIComponent(groupId)}`;\n\t\t\t\tconst [status, signedPayload] = await requestJson(\"GET\", lookupUrl, {\n\t\t\t\t\theaders: buildAuthHeaders({\n\t\t\t\t\t\tdeviceId: localDeviceId,\n\t\t\t\t\t\tdbPath: store.dbPath,\n\t\t\t\t\t\tmethod: \"GET\",\n\t\t\t\t\t\turl: lookupUrl,\n\t\t\t\t\t\tbodyBytes: Buffer.alloc(0),\n\t\t\t\t\t\tkeysDir: syncKeysDir(),\n\t\t\t\t\t}),\n\t\t\t\t\ttimeoutS: Math.max(1, config.syncCoordinatorTimeoutS),\n\t\t\t\t});\n\t\t\t\tif (status === 200) {\n\t\t\t\t\tpayload = signedPayload;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (!payload) return { ok: false, reason: \"bootstrap_grant_lookup_failed\", deviceId };\n\t\tverification = payload as unknown as CoordinatorBootstrapGrantVerification;\n\t} catch {\n\t\treturn { ok: false, reason: \"bootstrap_grant_lookup_failed\", deviceId };\n\t}\n\n\tconst grant = verification.grant;\n\tconst workerEnrollment = verification.worker_enrollment;\n\tif (!grant || !workerEnrollment) {\n\t\treturn { ok: false, reason: \"bootstrap_grant_invalid_payload\", deviceId };\n\t}\n\tif (\n\t\tconfig.syncCoordinatorGroups.length > 0 &&\n\t\t!config.syncCoordinatorGroups.includes(String(grant.group_id))\n\t) {\n\t\treturn { ok: false, reason: \"bootstrap_grant_group_mismatch\", deviceId };\n\t}\n\tif (grant.revoked_at) return { ok: false, reason: \"bootstrap_grant_revoked\", deviceId };\n\tif (String(workerEnrollment.device_id) !== String(grant.worker_device_id)) {\n\t\treturn { ok: false, reason: \"bootstrap_grant_worker_enrollment_mismatch\", deviceId };\n\t}\n\tif (String(workerEnrollment.group_id) !== String(grant.group_id)) {\n\t\treturn { ok: false, reason: \"bootstrap_grant_group_mismatch\", deviceId };\n\t}\n\tif (Number(workerEnrollment.enabled) !== 1) {\n\t\treturn { ok: false, reason: \"bootstrap_grant_worker_disabled\", deviceId };\n\t}\n\tconst workerPublicKey = String(workerEnrollment.public_key ?? \"\").trim();\n\tconst workerFingerprint = String(workerEnrollment.fingerprint ?? \"\").trim();\n\tif (!workerPublicKey || fingerprintPublicKey(workerPublicKey) !== workerFingerprint) {\n\t\treturn { ok: false, reason: \"bootstrap_grant_worker_identity_invalid\", deviceId };\n\t}\n\tif (grant.worker_device_id !== deviceId) {\n\t\treturn { ok: false, reason: \"bootstrap_grant_worker_mismatch\", deviceId };\n\t}\n\tif (grant.seed_device_id !== localDeviceId) {\n\t\treturn { ok: false, reason: \"bootstrap_grant_seed_mismatch\", deviceId };\n\t}\n\tif (new Date(grant.expires_at) <= new Date()) {\n\t\treturn { ok: false, reason: \"bootstrap_grant_expired\", deviceId };\n\t}\n\n\tconst existingPeer = store.db\n\t\t.prepare(\n\t\t\t`SELECT highest_observed_direct_signature_version\n\t\t\t FROM sync_peer_signature_state WHERE peer_device_id = ? LIMIT 1`,\n\t\t)\n\t\t.get(deviceId) as { highest_observed_direct_signature_version: number | null } | undefined;\n\tlet signatureVerification: VerifiedDirectPeerSignature;\n\ttry {\n\t\tsignatureVerification = verifyDirectPeerRequestSignature(request, body, {\n\t\t\tdeviceId,\n\t\t\tpublicKey: workerPublicKey,\n\t\t\texpectedRecipientId: localDeviceId,\n\t\t\thighestObservedVersion: existingPeer?.highest_observed_direct_signature_version ?? null,\n\t\t});\n\t} catch {\n\t\treturn { ok: false, reason: \"bootstrap_grant_signature_verification_error\", deviceId };\n\t}\n\tif (!signatureVerification.ok) {\n\t\treturn { ok: false, reason: signatureVerification.reason, deviceId };\n\t}\n\tif (!isPeerTrustBindingCompatible(store.db, deviceId, workerPublicKey, workerFingerprint)) {\n\t\treturn { ok: false, reason: \"bootstrap_grant_peer_trust_conflict\", deviceId };\n\t}\n\n\tconst createdAt = new Date().toISOString();\n\tconst nonceResult = recordSyncAuthNonce(store, deviceId, nonce, createdAt);\n\tif (nonceResult) return nonceResult;\n\tupdatePeerAddresses(store.db, deviceId, [], {\n\t\tname: String(workerEnrollment.display_name ?? \"\").trim() || undefined,\n\t\tpinnedFingerprint: workerFingerprint,\n\t\tpublicKey: workerPublicKey,\n\t\treplaceTrust: true,\n\t});\n\tif (signatureVerification.version === DIRECT_PEER_SIGNATURE_VERSION_NUMBER) {\n\t\tconst versionResult = recordDirectPeerSignatureVersion(\n\t\t\tstore,\n\t\t\tdeviceId,\n\t\t\tsignatureVerification.version,\n\t\t);\n\t\tif (versionResult) return versionResult;\n\t}\n\treturn { ok: true, reason: \"ok\", deviceId };\n}\n\nfunction parseJsonList(value: unknown): string[] {\n\tif (value == null) return [];\n\tif (typeof value === \"string\") {\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(value) as unknown;\n\t\t\tif (!Array.isArray(parsed)) return [];\n\t\t\treturn parsed.map((entry) => String(entry ?? \"\").trim()).filter(Boolean);\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t}\n\tif (!Array.isArray(value)) return [];\n\treturn value.map((entry) => String(entry ?? \"\").trim()).filter(Boolean);\n}\n\nfunction readPeerProjectFilters(\n\tstore: MemoryStore,\n\tpeerDeviceId: string,\n): { include: string[]; exclude: string[] } {\n\tconst globalConfig = readCoordinatorSyncConfig();\n\tconst row = store.db\n\t\t.prepare(\n\t\t\t\"SELECT projects_include_json, projects_exclude_json FROM sync_peers WHERE peer_device_id = ? LIMIT 1\",\n\t\t)\n\t\t.get(peerDeviceId) as\n\t\t| { projects_include_json: string | null; projects_exclude_json: string | null }\n\t\t| undefined;\n\tif (!row) {\n\t\treturn {\n\t\t\tinclude: globalConfig.syncProjectsInclude,\n\t\t\texclude: globalConfig.syncProjectsExclude,\n\t\t};\n\t}\n\tconst hasOverride = row.projects_include_json != null || row.projects_exclude_json != null;\n\tif (!hasOverride) {\n\t\treturn {\n\t\t\tinclude: globalConfig.syncProjectsInclude,\n\t\t\texclude: globalConfig.syncProjectsExclude,\n\t\t};\n\t}\n\treturn {\n\t\tinclude: parseJsonList(row.projects_include_json),\n\t\texclude: parseJsonList(row.projects_exclude_json),\n\t};\n}\n\nfunction currentProjectScope(\n\trow: Record<string, unknown>,\n\teffective?: { include: string[]; exclude: string[] },\n): Record<string, unknown> {\n\treturn {\n\t\tinclude: safeJsonList(row.projects_include_json as string | null),\n\t\texclude: safeJsonList(row.projects_exclude_json as string | null),\n\t\teffective_include:\n\t\t\teffective?.include ?? safeJsonList(row.projects_include_json as string | null),\n\t\teffective_exclude:\n\t\t\teffective?.exclude ?? safeJsonList(row.projects_exclude_json as string | null),\n\t\tinherits_global: row.projects_include_json == null && row.projects_exclude_json == null,\n\t};\n}\n\nfunction cleanPeerScopeText(value: unknown): string | null {\n\tconst text = String(value ?? \"\").trim();\n\treturn text || null;\n}\n\nfunction peerAuthorizedScopes(store: MemoryStore, peerDeviceId: string): Record<string, unknown>[] {\n\tconst deviceId = peerDeviceId.trim();\n\tif (!deviceId) return [];\n\tconst rows = store.db\n\t\t.prepare(\n\t\t\t`SELECT\n\t\t\t\trs.scope_id,\n\t\t\t\trs.label,\n\t\t\t\trs.kind,\n\t\t\t\trs.authority_type,\n\t\t\t\trs.coordinator_id,\n\t\t\t\trs.group_id,\n\t\t\t\tsm.role,\n\t\t\t\tsm.membership_epoch,\n\t\t\t\tsm.updated_at\n\t\t\t FROM scope_memberships sm\n\t\t\t JOIN replication_scopes rs ON rs.scope_id = sm.scope_id\n\t\t\t WHERE sm.device_id = ?\n\t\t\t AND sm.status = 'active'\n\t\t\t AND rs.status = 'active'\n\t\t\t AND sm.membership_epoch >= rs.membership_epoch\n\t\t\t ORDER BY CASE WHEN rs.authority_type = 'local' THEN 1 ELSE 0 END,\n\t\t\t rs.label COLLATE NOCASE,\n\t\t\t rs.scope_id`,\n\t\t)\n\t\t.all(deviceId) as Array<Record<string, unknown>>;\n\treturn rows.map((row) => ({\n\t\tscope_id: String(row.scope_id ?? \"\"),\n\t\tlabel: String(row.label ?? row.scope_id ?? \"\"),\n\t\tkind: String(row.kind ?? \"user\"),\n\t\tauthority_type: String(row.authority_type ?? \"local\"),\n\t\tcoordinator_id: cleanPeerScopeText(row.coordinator_id),\n\t\tgroup_id: cleanPeerScopeText(row.group_id),\n\t\trole: String(row.role ?? \"member\"),\n\t\tmembership_epoch: Number(row.membership_epoch ?? 0),\n\t\tupdated_at: cleanPeerScopeText(row.updated_at),\n\t}));\n}\n\nfunction ensureLocalActorRecord(store: MemoryStore): void {\n\tconst d = drizzle(store.db, { schema });\n\tconst now = new Date().toISOString();\n\t// Invariant: exactly one row in `actors` has is_local=1, and it is the\n\t// row whose actor_id matches store.actorId. Stale is_local=1 rows can\n\t// appear when a device's actor_id changes (config edit, regenerated\n\t// device keys, DB copied from another machine). Demote any such rows\n\t// before ensuring the canonical local row exists.\n\td.update(schema.actors)\n\t\t.set({ is_local: 0, updated_at: now })\n\t\t.where(and(eq(schema.actors.is_local, 1), ne(schema.actors.actor_id, store.actorId)))\n\t\t.run();\n\tconst existing = d\n\t\t.select({ actor_id: schema.actors.actor_id, is_local: schema.actors.is_local })\n\t\t.from(schema.actors)\n\t\t.where(eq(schema.actors.actor_id, store.actorId))\n\t\t.get();\n\tif (existing) {\n\t\t// Row already exists for the canonical local actor id; the demotion\n\t\t// above guarantees it is the only is_local=1 row, but the row itself\n\t\t// may have been previously set to is_local=0 (e.g. via a stale demote\n\t\t// from an even earlier identity). Re-mark it as local idempotently.\n\t\tif (existing.is_local !== 1) {\n\t\t\td.update(schema.actors)\n\t\t\t\t.set({ is_local: 1, updated_at: now })\n\t\t\t\t.where(eq(schema.actors.actor_id, store.actorId))\n\t\t\t\t.run();\n\t\t}\n\t\treturn;\n\t}\n\td.insert(schema.actors)\n\t\t.values({\n\t\t\tactor_id: store.actorId,\n\t\t\tdisplay_name: store.actorDisplayName,\n\t\t\tis_local: 1,\n\t\t\tstatus: \"active\",\n\t\t\tmerged_into_actor_id: null,\n\t\t\tcreated_at: now,\n\t\t\tupdated_at: now,\n\t\t})\n\t\t.run();\n}\n\nfunction ensureStableStoreIdentity(store: MemoryStore): string {\n\tconst deviceId = ensureStableStoreDeviceIdentity(store);\n\tensureLocalActorRecord(store);\n\treturn deviceId;\n}\n\nfunction ensureStableStoreDeviceIdentity(store: MemoryStore): string {\n\tconst [deviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });\n\tstore.adoptEnsuredDeviceIdentity(deviceId);\n\treturn deviceId;\n}\n\nfunction findPeerDeviceIdForAddress(store: MemoryStore, address: string): string | null {\n\tconst rows = store.db\n\t\t.prepare(\"SELECT peer_device_id, addresses_json FROM sync_peers\")\n\t\t.all() as Array<{ peer_device_id: string; addresses_json: string | null }>;\n\tfor (const row of rows) {\n\t\tconst addresses = safeJsonList(row.addresses_json);\n\t\tif (addresses.includes(address)) return String(row.peer_device_id ?? \"\").trim() || null;\n\t}\n\treturn null;\n}\n\nfunction claimLegacyDeviceAsSelf(store: MemoryStore, originDeviceId: string): number {\n\tconst deviceId = String(originDeviceId || \"\").trim();\n\tif (!deviceId || deviceId === \"unknown\" || deviceId === store.deviceId) return 0;\n\tconst personalWorkspaceId = `personal:${store.actorId}`;\n\tconst result = store.db\n\t\t.prepare(\n\t\t\t`UPDATE memory_items\n\t\t\t SET actor_id = ?,\n\t\t\t actor_display_name = ?,\n\t\t\t visibility = 'private',\n\t\t\t workspace_id = ?,\n\t\t\t workspace_kind = 'personal',\n\t\t\t trust_state = 'trusted'\n\t\t\t WHERE origin_device_id = ?\n\t\t\t AND origin_device_id NOT IN (\n\t\t\t SELECT peer_device_id FROM sync_peers WHERE peer_device_id IS NOT NULL\n\t\t\t )\n\t\t\t AND (\n\t\t\t (\n\t\t\t actor_id IS NULL\n\t\t\t OR TRIM(actor_id) = ''\n\t\t\t OR actor_id LIKE 'legacy-sync:%'\n\t\t\t OR actor_id = ?\n\t\t\t )\n\t\t\t AND (\n\t\t\t actor_id IS NULL\n\t\t\t OR TRIM(actor_id) = ''\n\t\t\t OR actor_id LIKE 'legacy-sync:%'\n\t\t\t OR actor_display_name = ?\n\t\t\t OR workspace_id = ?\n\t\t\t OR trust_state = 'legacy_unknown'\n\t\t\t )\n\t\t\t )`,\n\t\t)\n\t\t.run(\n\t\t\tstore.actorId,\n\t\t\tstore.actorDisplayName,\n\t\t\tpersonalWorkspaceId,\n\t\t\tdeviceId,\n\t\t\tstore.actorId,\n\t\t\tLEGACY_SYNC_ACTOR_DISPLAY_NAME,\n\t\t\tLEGACY_SHARED_WORKSPACE_ID,\n\t\t);\n\treturn Number(result.changes ?? 0);\n}\n\nfunction redactCoordinatorStatus(\n\tcoordinator: Record<string, unknown>,\n\tshowDiag: boolean,\n): Record<string, unknown> {\n\tif (showDiag) return coordinator;\n\tconst discovered = Array.isArray(coordinator.discovered_devices)\n\t\t? coordinator.discovered_devices.map((item) => {\n\t\t\t\tif (!item || typeof item !== \"object\") return item;\n\t\t\t\tconst record = item as Record<string, unknown>;\n\t\t\t\tconst addressCount = Array.isArray(record.addresses) ? record.addresses.length : 0;\n\t\t\t\treturn {\n\t\t\t\t\tdevice_id: record.device_id,\n\t\t\t\t\tdisplay_name: record.display_name ?? null,\n\t\t\t\t\tgroups: Array.isArray(record.groups) ? record.groups : [],\n\t\t\t\t\tlast_seen_at: record.last_seen_at ?? null,\n\t\t\t\t\texpires_at: record.expires_at ?? null,\n\t\t\t\t\tstale: Boolean(record.stale),\n\t\t\t\t\tneeds_local_approval: Boolean(record.needs_local_approval),\n\t\t\t\t\twaiting_for_peer_approval: Boolean(record.waiting_for_peer_approval),\n\t\t\t\t\tincoming_reciprocal_request_id: record.incoming_reciprocal_request_id ?? null,\n\t\t\t\t\toutgoing_reciprocal_request_id: record.outgoing_reciprocal_request_id ?? null,\n\t\t\t\t\tfingerprint: null,\n\t\t\t\t\taddresses: [],\n\t\t\t\t\taddress_count: addressCount,\n\t\t\t\t};\n\t\t\t})\n\t\t: [];\n\treturn {\n\t\t...coordinator,\n\t\tdiscovered_devices: discovered,\n\t};\n}\n\ninterface AcceptDiscoveredPeerOptions {\n\tpeerDeviceId: string;\n\tfingerprint?: string;\n\t// Optional per-peer scope override. When undefined the group's scope\n\t// template is applied if auto_seed_scope is enabled; otherwise the peer\n\t// is enrolled with no scope filters.\n\t// Per-field: `undefined` = \"inherit from template\", `null` = \"explicit empty\",\n\t// `string[]` = \"use this list\". This avoids silently wiping the template's\n\t// exclude list when the caller only overrides include (or vice versa).\n\tscopeOverride?: {\n\t\tprojects_include?: string[] | null;\n\t\tprojects_exclude?: string[] | null;\n\t};\n\t// When provided and the caller is the admin-groups endpoint, this group\n\t// must be one of the match's coordinator groups. When undefined (legacy\n\t// /api/sync/peers/accept-discovered path) the match must belong to\n\t// exactly one group and that one is used.\n\texpectedGroupId?: string;\n\t// When provided, complete only the exact incoming reciprocal approval that\n\t// the caller reviewed instead of accepting a replacement request.\n\texpectedIncomingRequestId?: string;\n}\n\ntype AcceptDiscoveredPeerNotConfiguredReason =\n\t| \"coordinator_url_missing\"\n\t| \"coordinator_groups_empty\"\n\t| \"sync_disabled\";\n\nfunction detailForNotConfiguredReason(reason: AcceptDiscoveredPeerNotConfiguredReason): string {\n\tswitch (reason) {\n\t\tcase \"coordinator_url_missing\":\n\t\t\treturn \"Configure a coordinator URL before pairing with discovered peers.\";\n\t\tcase \"coordinator_groups_empty\":\n\t\t\treturn \"Join a coordinator team before pairing with discovered peers.\";\n\t\tcase \"sync_disabled\":\n\t\t\treturn \"Enable sync on this device before pairing with discovered peers.\";\n\t}\n}\n\nasync function acceptDiscoveredPeer(\n\tstore: MemoryStore,\n\tinput: AcceptDiscoveredPeerOptions,\n): Promise<\n\t| {\n\t\t\tok: true;\n\t\t\tpeer_device_id: string;\n\t\t\tcreated: boolean;\n\t\t\tupdated: boolean;\n\t\t\tname: string | null;\n\t\t\tgroup_id: string;\n\t }\n\t| {\n\t\t\tok: false;\n\t\t\tstatus: number;\n\t\t\terror: string;\n\t\t\tdetail: string;\n\t\t\treason?: AcceptDiscoveredPeerNotConfiguredReason;\n\t }\n> {\n\tconst config = readCoordinatorSyncConfig();\n\t// Order: address the most foundational gap first so the detail string\n\t// guides the user through setup in the correct sequence.\n\tlet notConfiguredReason: AcceptDiscoveredPeerNotConfiguredReason | null = null;\n\tif (!config.syncCoordinatorUrl) {\n\t\tnotConfiguredReason = \"coordinator_url_missing\";\n\t} else if (config.syncCoordinatorGroups.length === 0) {\n\t\tnotConfiguredReason = \"coordinator_groups_empty\";\n\t} else if (!config.syncEnabled) {\n\t\tnotConfiguredReason = \"sync_disabled\";\n\t}\n\tif (notConfiguredReason) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tstatus: 400,\n\t\t\terror: \"coordinator_not_configured\",\n\t\t\treason: notConfiguredReason,\n\t\t\tdetail: detailForNotConfiguredReason(notConfiguredReason),\n\t\t};\n\t}\n\tconst discovered = await lookupCoordinatorPeers(store, config);\n\tconst inputFingerprint = String(input.fingerprint ?? \"\").trim();\n\tconst candidates = discovered.filter(\n\t\t(peer) => String(peer.device_id ?? \"\").trim() === input.peerDeviceId,\n\t);\n\tconst matchingCandidates = inputFingerprint\n\t\t? candidates.filter((peer) => String(peer.fingerprint ?? \"\").trim() === inputFingerprint)\n\t\t: candidates;\n\tconst uniqueFingerprints = new Set(\n\t\tmatchingCandidates.map((peer) => String(peer.fingerprint ?? \"\").trim()).filter(Boolean),\n\t);\n\tif (!inputFingerprint && uniqueFingerprints.size > 1) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tstatus: 409,\n\t\t\terror: \"ambiguous_discovered_peer\",\n\t\t\tdetail:\n\t\t\t\t\"That discovered device has multiple coordinator fingerprints. Enable diagnostics, refresh sync status, and choose the intended device before trusting it.\",\n\t\t};\n\t}\n\tconst match = matchingCandidates[0];\n\tif (!match) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tstatus: 404,\n\t\t\terror: \"discovered_peer_not_found\",\n\t\t\tdetail: \"That discovered device is no longer available. Refresh sync status and try again.\",\n\t\t};\n\t}\n\tconst expiresAt = String(match.expires_at ?? \"\").trim();\n\tconst expired = expiresAt ? Date.parse(expiresAt) <= Date.now() : false;\n\tif (match.stale || expired) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tstatus: 409,\n\t\t\terror: \"discovered_peer_stale\",\n\t\t\tdetail:\n\t\t\t\t\"This discovered device's coordinator presence is stale. Wait for it to come online and refresh sync status before trusting it.\",\n\t\t};\n\t}\n\tconst nextFingerprint = String(match.fingerprint ?? \"\").trim();\n\tconst nextPublicKey = String(match.public_key ?? \"\").trim();\n\tconst nextName = String(match.display_name ?? \"\").trim() || null;\n\tconst nextAddresses = Array.isArray(match.addresses)\n\t\t? match.addresses.filter((value): value is string => typeof value === \"string\")\n\t\t: [];\n\tif (!nextPublicKey) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tstatus: 409,\n\t\t\terror: \"discovered_peer_missing_public_key\",\n\t\t\tdetail:\n\t\t\t\t\"This discovered device is missing its coordinator public key. Refresh sync status and try again.\",\n\t\t};\n\t}\n\tif (!nextFingerprint || fingerprintPublicKey(nextPublicKey) !== nextFingerprint) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tstatus: 409,\n\t\t\terror: \"discovered_peer_fingerprint_mismatch\",\n\t\t\tdetail:\n\t\t\t\t\"This discovered device's coordinator public key does not match its fingerprint. Refresh sync status or re-enroll the device before trusting it.\",\n\t\t};\n\t}\n\n\tconst groupIds = Array.isArray(match.groups)\n\t\t? match.groups.map((value) => String(value ?? \"\").trim()).filter(Boolean)\n\t\t: [];\n\tconst freshGroupIds = Array.isArray(match.fresh_groups)\n\t\t? match.fresh_groups.map((value) => String(value ?? \"\").trim()).filter(Boolean)\n\t\t: [];\n\tlet groupId: string;\n\tif (input.expectedGroupId) {\n\t\tif (!groupIds.includes(input.expectedGroupId)) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tstatus: 409,\n\t\t\t\terror: \"peer_not_in_group\",\n\t\t\t\tdetail:\n\t\t\t\t\t\"This discovered device is not visible through the specified coordinator group. Refresh sync status and try again.\",\n\t\t\t};\n\t\t}\n\t\tif (!freshGroupIds.includes(input.expectedGroupId)) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tstatus: 409,\n\t\t\t\terror: \"discovered_peer_stale\",\n\t\t\t\tdetail:\n\t\t\t\t\t\"This discovered device's coordinator presence is stale for the specified group. Wait for it to come online and refresh sync status before trusting it.\",\n\t\t\t};\n\t\t}\n\t\tgroupId = input.expectedGroupId;\n\t} else {\n\t\tif (groupIds.length !== 1) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tstatus: 409,\n\t\t\t\terror: \"ambiguous_coordinator_group\",\n\t\t\t\tdetail:\n\t\t\t\t\tgroupIds.length > 1\n\t\t\t\t\t\t? \"This device is visible through multiple coordinator groups. Review the team setup before approving it here.\"\n\t\t\t\t\t\t: \"This device is missing coordinator group context. Refresh sync status and try again.\",\n\t\t\t};\n\t\t}\n\t\tgroupId = groupIds[0] as string;\n\t}\n\tconst d = drizzle(store.db, { schema });\n\tconst existing = d\n\t\t.select({\n\t\t\tpeer_device_id: schema.syncPeers.peer_device_id,\n\t\t\tpinned_fingerprint: schema.syncPeers.pinned_fingerprint,\n\t\t\tpublic_key: schema.syncPeers.public_key,\n\t\t\taddresses_json: schema.syncPeers.addresses_json,\n\t\t\tdiscovered_via_group_id: schema.syncPeers.discovered_via_group_id,\n\t\t})\n\t\t.from(schema.syncPeers)\n\t\t.where(eq(schema.syncPeers.peer_device_id, input.peerDeviceId))\n\t\t.get();\n\tconst existingFingerprint = String(existing?.pinned_fingerprint ?? \"\").trim();\n\tif (existing && existingFingerprint && existingFingerprint !== nextFingerprint) {\n\t\treturn {\n\t\t\tok: false as const,\n\t\t\tstatus: 409,\n\t\t\terror: \"peer_conflict\",\n\t\t\tdetail:\n\t\t\t\t\"An existing peer with this device id is pinned to a different fingerprint. Remove or repair the old peer before accepting this discovered device.\",\n\t\t};\n\t}\n\tconst existingAddresses = (() => {\n\t\ttry {\n\t\t\tconst raw = JSON.parse(String(existing?.addresses_json ?? \"[]\"));\n\t\t\treturn Array.isArray(raw)\n\t\t\t\t? raw.filter((value): value is string => typeof value === \"string\")\n\t\t\t\t: [];\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t})();\n\tconst addressesJson = JSON.stringify(mergeAddresses(nextAddresses, existingAddresses));\n\tawait createCoordinatorReciprocalApproval(store, config, {\n\t\tgroupId,\n\t\trequestedDeviceId: input.peerDeviceId,\n\t\t...(input.expectedIncomingRequestId\n\t\t\t? { expectedIncomingRequestId: input.expectedIncomingRequestId }\n\t\t\t: {}),\n\t});\n\n\t// Resolve project-scope seed. On first enrollment (no existing row), apply\n\t// the group's scope template if auto_seed_scope is enabled. Per-field\n\t// overrides fall back to the template when undefined, so passing only\n\t// `projects_include` does not silently wipe the template's exclude list.\n\t// Existing peers are not re-scoped — the template is a seed, not a live link.\n\tconst coordinatorUrl = config.syncCoordinatorUrl || null;\n\tlet scopeInclude: string | null | undefined;\n\tlet scopeExclude: string | null | undefined;\n\tif (!existing) {\n\t\tlet templateInclude: string[] | null = null;\n\t\tlet templateExclude: string[] | null = null;\n\t\tif (coordinatorUrl) {\n\t\t\tconst prefs = getCoordinatorGroupPreference(store.db, coordinatorUrl, groupId);\n\t\t\tif (prefs?.auto_seed_scope) {\n\t\t\t\ttemplateInclude = prefs.projects_include ?? null;\n\t\t\t\ttemplateExclude = prefs.projects_exclude ?? null;\n\t\t\t}\n\t\t}\n\t\tconst overrideInclude = input.scopeOverride?.projects_include;\n\t\tconst overrideExclude = input.scopeOverride?.projects_exclude;\n\t\tconst resolvedInclude = overrideInclude === undefined ? templateInclude : overrideInclude;\n\t\tconst resolvedExclude = overrideExclude === undefined ? templateExclude : overrideExclude;\n\t\tscopeInclude = resolvedInclude ? JSON.stringify(resolvedInclude) : null;\n\t\tscopeExclude = resolvedExclude ? JSON.stringify(resolvedExclude) : null;\n\t}\n\n\tconst now = new Date().toISOString();\n\tconst result = store.db.transaction(() => {\n\t\tif (!existing) {\n\t\t\td.insert(schema.syncPeers)\n\t\t\t\t.values({\n\t\t\t\t\tpeer_device_id: input.peerDeviceId,\n\t\t\t\t\tname: nextName,\n\t\t\t\t\tpinned_fingerprint: nextFingerprint || null,\n\t\t\t\t\tpublic_key: nextPublicKey,\n\t\t\t\t\taddresses_json: addressesJson,\n\t\t\t\t\tprojects_include_json: scopeInclude ?? null,\n\t\t\t\t\tprojects_exclude_json: scopeExclude ?? null,\n\t\t\t\t\tcreated_at: now,\n\t\t\t\t\tlast_seen_at: now,\n\t\t\t\t\tdiscovered_via_coordinator_id: coordinatorUrl,\n\t\t\t\t\tdiscovered_via_group_id: groupId,\n\t\t\t\t})\n\t\t\t\t.run();\n\t\t\treturn {\n\t\t\t\tok: true as const,\n\t\t\t\tpeer_device_id: input.peerDeviceId,\n\t\t\t\tcreated: true,\n\t\t\t\tupdated: false,\n\t\t\t\tname: nextName,\n\t\t\t\tgroup_id: groupId,\n\t\t\t};\n\t\t}\n\t\td.update(schema.syncPeers)\n\t\t\t.set({\n\t\t\t\tname: nextName,\n\t\t\t\tpinned_fingerprint: nextFingerprint || existing.pinned_fingerprint || null,\n\t\t\t\tpublic_key: nextPublicKey || existing.public_key || null,\n\t\t\t\taddresses_json: addressesJson,\n\t\t\t\tlast_seen_at: now,\n\t\t\t\t// Backfill group-discovery attribution on existing rows if we know\n\t\t\t\t// it now and it wasn't stamped before. Don't overwrite a non-null\n\t\t\t\t// group reference — that would silently move the peer between\n\t\t\t\t// teams and invalidate any template-seeded scope.\n\t\t\t\t...((existing as { discovered_via_group_id?: string | null }).discovered_via_group_id\n\t\t\t\t\t? {}\n\t\t\t\t\t: { discovered_via_group_id: groupId, discovered_via_coordinator_id: coordinatorUrl }),\n\t\t\t})\n\t\t\t.where(eq(schema.syncPeers.peer_device_id, input.peerDeviceId))\n\t\t\t.run();\n\t\treturn {\n\t\t\tok: true as const,\n\t\t\tpeer_device_id: input.peerDeviceId,\n\t\t\tcreated: false,\n\t\t\tupdated: true,\n\t\t\tname: nextName,\n\t\t\tgroup_id: groupId,\n\t\t};\n\t})();\n\treturn result;\n}\n\nfunction filterOpsForPeer(\n\tstore: MemoryStore,\n\tpeerDeviceId: string,\n\tlocalDeviceId: string | null,\n\tops: ReplicationOp[],\n\toptions: { applyScopeFilter?: boolean; supportsReassignScope?: boolean } = {},\n): { allowed: ReplicationOp[]; skipped: number; skippedDetail: SafeSkippedSyncDetail | null } {\n\tconst [allowed, , skipped] = filterReplicationOpsForSyncWithStatus(store.db, ops, peerDeviceId, {\n\t\tlocalDeviceId,\n\t\tapplyScopeFilter: options.applyScopeFilter,\n\t\tsupportsReassignScope: options.supportsReassignScope,\n\t});\n\treturn {\n\t\tallowed,\n\t\tskipped: skipped?.skipped_count ?? 0,\n\t\tskippedDetail: skipped ? safeSkippedSyncDetail(skipped) : null,\n\t};\n}\n\n// ---------------------------------------------------------------------------\n// Peer row mapping — deduplicated helper (fix #4)\n// ---------------------------------------------------------------------------\n\nfunction claimedLocalActorScopeStatus(\n\tstore: MemoryStore,\n\trow: Record<string, unknown>,\n): Record<string, unknown> | null {\n\tif (!row.claimed_local_actor) return null;\n\tconst peerDeviceId = String(row.peer_device_id ?? \"\").trim();\n\tconst actorId = String(row.actor_id ?? store.actorId).trim() || store.actorId;\n\tconst grant = personalScopeGrantStatusForPeer(store.db, { peerDeviceId, actorId });\n\treturn {\n\t\tscope_id: grant.scope_id,\n\t\tauthorized: grant.authorized,\n\t\tstate: grant.state,\n\t\taction_required: !grant.authorized,\n\t};\n}\n\n/**\n * Map a raw sync_peers DB row to the API response shape.\n * When showDiag is false, sensitive fields (fingerprint, last_error, addresses)\n * are redacted.\n */\nfunction mapPeerRow(\n\tstore: MemoryStore,\n\trow: Record<string, unknown>,\n\tshowDiag: boolean,\n\trecentOpsByPeer?: Map<string, { in: number; out: number }>,\n\tscopeRejectionsByPeer?: Map<string, InboundScopeRejectionPeerSummary>,\n\tlocalDeviceId?: string | null,\n): Record<string, unknown> {\n\tconst peerId = String(row.peer_device_id ?? \"\");\n\tconst recentOps = recentOpsByPeer?.get(peerId) ?? { in: 0, out: 0 };\n\tconst scopeRejections = scopeRejectionsByPeer?.get(peerId);\n\tconst addresses = safeJsonList(row.addresses_json as string | null);\n\tconst perScopeSync = listPerPeerScopeSyncState(store.db, {\n\t\tlocalDeviceId: localDeviceId ?? null,\n\t\tpeerDeviceId: peerId,\n\t});\n\treturn {\n\t\tpeer_device_id: row.peer_device_id,\n\t\tname: row.name,\n\t\tfingerprint: showDiag ? row.pinned_fingerprint : null,\n\t\tpinned: Boolean(row.pinned_fingerprint),\n\t\taddresses: showDiag ? addresses : [],\n\t\taddress_count: addresses.length,\n\t\tlast_seen_at: row.last_seen_at,\n\t\tlast_sync_at: row.last_sync_at,\n\t\tlast_error: showDiag ? row.last_error : null,\n\t\truntime_version: row.runtime_version ?? null,\n\t\truntime_version_observed_at: row.runtime_version_observed_at ?? null,\n\t\thas_error: Boolean(row.last_error),\n\t\tclaimed_local_actor: Boolean(row.claimed_local_actor),\n\t\tclaimed_local_actor_scope: claimedLocalActorScopeStatus(store, row),\n\t\tactor_id: row.actor_id ?? null,\n\t\tactor_display_name: row.actor_display_name ?? null,\n\t\tauthorized_scopes: peerAuthorizedScopes(store, peerId),\n\t\t// Per-Space sync state intersecting local + peer membership and joining\n\t\t// per-scope replication cursor data. Use this surface to render\n\t\t// per-Space progress in CLI/UI without exposing the legacy `status=ok`\n\t\t// shorthand that hid scoped sync gaps in 0.32.x.\n\t\tper_scope_sync: perScopeSync,\n\t\tproject_scope: {\n\t\t\t...currentProjectScope(row, readPeerProjectFilters(store, String(row.peer_device_id ?? \"\"))),\n\t\t},\n\t\trecent_ops: { in: recentOps.in, out: recentOps.out },\n\t\tscope_rejections: {\n\t\t\ttotal: scopeRejections?.total ?? 0,\n\t\t\tby_reason: scopeRejections?.by_reason ?? {},\n\t\t\tlast_at: scopeRejections?.last_at ?? null,\n\t\t},\n\t\tdiscovered_via_coordinator_id:\n\t\t\ttypeof row.discovered_via_coordinator_id === \"string\"\n\t\t\t\t? row.discovered_via_coordinator_id\n\t\t\t\t: null,\n\t\tdiscovered_via_group_id:\n\t\t\ttypeof row.discovered_via_group_id === \"string\" ? row.discovered_via_group_id : null,\n\t};\n}\n\nfunction redactSyncAttemptError(error: unknown): string | null {\n\tconst text = String(error ?? \"\").trim();\n\tif (!text) return null;\n\treturn \"sync attempt failed; enable diagnostics for details\";\n}\n\nfunction mapSyncAttemptRow(\n\trow: Record<string, unknown>,\n\tshowDiag: boolean,\n\taddresses?: string[],\n): Record<string, unknown> {\n\tconst redactedError = redactSyncAttemptError(row.error);\n\treturn {\n\t\t...row,\n\t\terror: showDiag ? row.error : redactedError,\n\t\terror_redacted: !showDiag && redactedError != null,\n\t\tstatus: attemptStatus(row),\n\t\taddress: showDiag && addresses?.length ? addresses[0] : null,\n\t};\n}\n\nconst SYNC_SCOPE_REJECTION_WINDOW_SECONDS = 24 * 60 * 60;\nconst CLEANUP_DIAGNOSTICS_MAX_ROWS = 250;\n\nfunction recentScopeRejectionsByPeer(\n\tstore: MemoryStore,\n): Map<string, InboundScopeRejectionPeerSummary> {\n\tconst cutoff = new Date(Date.now() - SYNC_SCOPE_REJECTION_WINDOW_SECONDS * 1000).toISOString();\n\tconst summaries = summarizeInboundScopeRejections(store.db, { sinceIso: cutoff });\n\tconst map = new Map<string, InboundScopeRejectionPeerSummary>();\n\tfor (const summary of summaries) {\n\t\tconst id = String(summary.peer_device_id ?? \"\").trim();\n\t\tif (!id) continue;\n\t\tmap.set(id, summary);\n\t}\n\treturn map;\n}\n\nfunction cleanupDiagnostics(\n\tstore: MemoryStore,\n\tlocalDeviceId: string | null,\n\tshowDiag: boolean,\n): Record<string, unknown> {\n\tconst opRows = store.db\n\t\t.prepare(\n\t\t\t`SELECT\n\t\t\t\tSUM(CASE WHEN device_id = ? THEN 1 ELSE 0 END) AS source_authored,\n\t\t\t\tSUM(CASE WHEN device_id != ? THEN 1 ELSE 0 END) AS applied,\n\t\t\t\tMAX(created_at) AS latest_at\n\t\t\t FROM replication_ops\n\t\t\t WHERE op_type = ?`,\n\t\t)\n\t\t.get(localDeviceId ?? \"\", localDeviceId ?? \"\", ACCESS_CLEANUP_OP_TYPE) as\n\t\t| { applied: number | null; latest_at: string | null; source_authored: number | null }\n\t\t| undefined;\n\tconst stale =\n\t\tlocalDeviceId && showDiag\n\t\t\t? diagnoseStalePeerReceivedRows(store.db, {\n\t\t\t\t\tlocalDeviceId,\n\t\t\t\t\tmaxRows: CLEANUP_DIAGNOSTICS_MAX_ROWS,\n\t\t\t\t})\n\t\t\t: { ambiguous: [], checked: 0, retained: 0, would_delete: 0, would_delete_memory_ids: [] };\n\tconst ambiguousByReason: Record<string, number> = {};\n\tfor (const item of stale.ambiguous) {\n\t\tambiguousByReason[item.reason] = (ambiguousByReason[item.reason] ?? 0) + 1;\n\t}\n\tconst sourceAuthored = Number(opRows?.source_authored ?? 0);\n\tconst applied = Number(opRows?.applied ?? 0);\n\tconst ambiguous = stale.ambiguous.length;\n\tconst state = stale.would_delete\n\t\t? \"cleanup_pending\"\n\t\t: ambiguous\n\t\t\t? \"needs_review\"\n\t\t\t: applied\n\t\t\t\t? \"cleanup_applied\"\n\t\t\t\t: sourceAuthored\n\t\t\t\t\t? \"cleanup_announced\"\n\t\t\t\t\t: \"clear\";\n\treturn {\n\t\tstate,\n\t\taccess_cleanup_ops: {\n\t\t\tsource_authored: sourceAuthored,\n\t\t\tapplied,\n\t\t\tlatest_at: opRows?.latest_at ?? null,\n\t\t},\n\t\tstale_peer_rows: {\n\t\t\tchecked: stale.checked,\n\t\t\tdiagnostic_limit: showDiag ? CLEANUP_DIAGNOSTICS_MAX_ROWS : 0,\n\t\t\tscan_skipped: !showDiag || !localDeviceId,\n\t\t\twould_remove: stale.would_delete,\n\t\t\tambiguous,\n\t\t\tambiguous_by_reason: ambiguousByReason,\n\t\t\tretained: stale.retained,\n\t\t\titems: showDiag ? stale.ambiguous.slice(0, 25) : undefined,\n\t\t},\n\t\tredacted: !showDiag,\n\t};\n}\n\nfunction legacySharedReviewSummary(store: MemoryStore): Record<string, unknown> {\n\tconst rows = legacySharedReviewRows(store);\n\tconst memoryCount = rows.length;\n\tconst lastUpdatedAt = rows.reduce<string | null>(\n\t\t(current, row) =>\n\t\t\trow.updated_at && (!current || row.updated_at > current) ? row.updated_at : current,\n\t\tnull,\n\t);\n\tconst ownedBySelf = store.buildOwnershipPredicate();\n\tconst candidatesByIdentity = new Map(\n\t\tlistProjectScopeCandidates(store.db, { limit: null }).map((candidate) => [\n\t\t\tcandidate.workspace_identity,\n\t\t\tcandidate,\n\t\t]),\n\t);\n\tconst groupsByIdentity = new Map<\n\t\tstring,\n\t\t{\n\t\t\tworkspace_identity: string;\n\t\t\tidentity_source: string;\n\t\t\tdisplay_project: string;\n\t\t\tmemory_count: number;\n\t\t\treassignable_memory_count: number;\n\t\t\tpeer_owned_memory_count: number;\n\t\t\tlast_updated_at: string | null;\n\t\t\tmemory_samples: LegacySharedReviewMemorySample[];\n\t\t\tsuggested_scope_id: string | null;\n\t\t\tsuggestion_reason: string | null;\n\t\t}\n\t>();\n\tfor (const row of rows) {\n\t\tconst identity = canonicalWorkspaceIdentity({\n\t\t\tcwd: row.cwd,\n\t\t\tgitBranch: row.git_branch,\n\t\t\tgitRemote: row.git_remote,\n\t\t\tproject: row.project,\n\t\t\tworkspaceId: row.workspace_id,\n\t\t});\n\t\tconst candidate = candidatesByIdentity.get(identity.value);\n\t\tconst resolvedScope = candidate?.resolved_scope_id ?? null;\n\t\tconst suggestedScope =\n\t\t\tresolvedScope &&\n\t\t\tresolvedScope !== LOCAL_DEFAULT_SCOPE_ID &&\n\t\t\tresolvedScope !== LEGACY_SHARED_REVIEW_SCOPE_ID\n\t\t\t\t? resolvedScope\n\t\t\t\t: candidate?.suggested_scope_id;\n\t\tconst existing = groupsByIdentity.get(identity.value);\n\t\tconst isOwnedBySelf = ownedBySelf(row as unknown as Record<string, unknown>);\n\t\tconst rowUpdatedAt = row.updated_at ?? null;\n\t\tif (existing) {\n\t\t\texisting.memory_count += 1;\n\t\t\tif (isOwnedBySelf) existing.reassignable_memory_count += 1;\n\t\t\telse existing.peer_owned_memory_count += 1;\n\t\t\tif (rowUpdatedAt && (!existing.last_updated_at || rowUpdatedAt > existing.last_updated_at)) {\n\t\t\t\texisting.last_updated_at = rowUpdatedAt;\n\t\t\t}\n\t\t\tif (existing.memory_samples.length < LEGACY_SHARED_REVIEW_SAMPLE_LIMIT) {\n\t\t\t\texisting.memory_samples.push(legacySharedReviewMemorySample(row, isOwnedBySelf));\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tgroupsByIdentity.set(identity.value, {\n\t\t\tworkspace_identity: identity.value,\n\t\t\tidentity_source: identity.source,\n\t\t\tdisplay_project: identity.displayProject ?? row.project ?? row.cwd ?? identity.value,\n\t\t\tmemory_count: 1,\n\t\t\treassignable_memory_count: isOwnedBySelf ? 1 : 0,\n\t\t\tpeer_owned_memory_count: isOwnedBySelf ? 0 : 1,\n\t\t\tlast_updated_at: rowUpdatedAt,\n\t\t\tmemory_samples: [legacySharedReviewMemorySample(row, isOwnedBySelf)],\n\t\t\tsuggested_scope_id: suggestedScope ?? null,\n\t\t\tsuggestion_reason: suggestedScope\n\t\t\t\t? (candidate?.suggestion_reason ??\n\t\t\t\t\t\"Existing project mapping can be reviewed as a destination, but legacy data is not promoted automatically.\")\n\t\t\t\t: null,\n\t\t});\n\t}\n\tconst totalGroupCount = groupsByIdentity.size;\n\tconst groups = [...groupsByIdentity.values()].sort(\n\t\t(left, right) =>\n\t\t\tright.memory_count - left.memory_count ||\n\t\t\t(right.last_updated_at ?? \"\").localeCompare(left.last_updated_at ?? \"\") ||\n\t\t\tleft.workspace_identity.localeCompare(right.workspace_identity),\n\t);\n\tconst targetScopes = listSharingDomainSettingsScopes(store.db)\n\t\t.filter(\n\t\t\t(scope) =>\n\t\t\t\tscope.scope_id !== LOCAL_DEFAULT_SCOPE_ID &&\n\t\t\t\tscope.scope_id !== LEGACY_SHARED_REVIEW_SCOPE_ID,\n\t\t)\n\t\t.map((scope) => ({\n\t\t\tauthority_type: scope.authority_type,\n\t\t\tlabel: scope.label || scope.scope_id,\n\t\t\tscope_id: scope.scope_id,\n\t\t}));\n\treturn {\n\t\tscope_id: LEGACY_SHARED_REVIEW_SCOPE_ID,\n\t\tmemory_count: memoryCount,\n\t\thas_data: memoryCount > 0,\n\t\tlast_updated_at: lastUpdatedAt,\n\t\tgroups,\n\t\ttotal_group_count: totalGroupCount,\n\t\ttarget_scopes: targetScopes,\n\t};\n}\n\ninterface LegacySharedReviewReassignmentMemoryRow {\n\tid: number;\n\trev: number | null;\n\tactive: number | null;\n\tdeleted_at: string | null;\n\tcreated_at: string | null;\n\tupdated_at: string | null;\n\tscope_id: string | null;\n\tkind: string | null;\n\ttitle: string | null;\n\tbody_text: string | null;\n\tproject: string | null;\n\tcwd: string | null;\n\tgit_remote: string | null;\n\tgit_branch: string | null;\n\tworkspace_id: string | null;\n\tactor_id: string | null;\n\torigin_device_id: string | null;\n\tmetadata_json: string | null;\n}\n\nconst LEGACY_SHARED_REVIEW_SAMPLE_LIMIT = 3;\nconst LEGACY_SHARED_REVIEW_BODY_PREVIEW_SQL_LIMIT = 360;\n\ninterface LegacySharedReviewMemorySample {\n\tid: number;\n\tkind: string | null;\n\ttitle: string;\n\tbody_preview: string | null;\n\tcreated_at: string | null;\n\tupdated_at: string | null;\n\townership: \"local\" | \"peer\";\n\tproject: string | null;\n\tcwd: string | null;\n\tgit_remote: string | null;\n}\n\nfunction previewText(value: string | null | undefined, limit = 180): string | null {\n\tconst normalized = value?.replace(/\\s+/g, \" \").trim();\n\tif (!normalized) return null;\n\treturn normalized.length > limit ? `${normalized.slice(0, limit - 1)}…` : normalized;\n}\n\nfunction legacySharedReviewMemorySample(\n\trow: LegacySharedReviewReassignmentMemoryRow,\n\tisOwnedBySelf: boolean,\n): LegacySharedReviewMemorySample {\n\treturn {\n\t\tid: row.id,\n\t\tkind: row.kind,\n\t\ttitle: previewText(row.title, 120) ?? `Memory ${row.id}`,\n\t\tbody_preview: previewText(row.body_text),\n\t\tcreated_at: row.created_at ?? null,\n\t\tupdated_at: row.updated_at ?? null,\n\t\townership: isOwnedBySelf ? \"local\" : \"peer\",\n\t\tproject: row.project ?? null,\n\t\tcwd: row.cwd ?? null,\n\t\tgit_remote: row.git_remote ?? null,\n\t};\n}\n\nfunction legacySharedReviewRows(store: MemoryStore): LegacySharedReviewReassignmentMemoryRow[] {\n\treturn store.db\n\t\t.prepare(\n\t\t\t`SELECT m.id,\n\t\t\t m.rev,\n\t\t\t m.active,\n\t\t\t m.deleted_at,\n\t\t\t m.created_at,\n\t\t\t m.updated_at,\n\t\t\t m.scope_id,\n\t\t\t m.kind,\n\t\t\t m.title,\n\t\t\t\t substr(m.body_text, 1, ?) AS body_text,\n\t\t\t s.project,\n\t\t\t s.cwd,\n\t\t\t s.git_remote,\n\t\t\t s.git_branch,\n\t\t\t m.workspace_id,\n\t\t\t m.actor_id,\n\t\t\t m.origin_device_id,\n\t\t\t m.metadata_json\n\t\t\t FROM memory_items m\n\t\t\t LEFT JOIN sessions s ON s.id = m.session_id\n\t\t\t WHERE m.scope_id = ?\n\t\t\t AND m.active = 1\n\t\t\t AND m.deleted_at IS NULL\n\t\t\t ORDER BY COALESCE(m.updated_at, m.created_at, '') DESC, m.id DESC`,\n\t\t)\n\t\t.all(\n\t\t\tLEGACY_SHARED_REVIEW_BODY_PREVIEW_SQL_LIMIT,\n\t\t\tLEGACY_SHARED_REVIEW_SCOPE_ID,\n\t\t) as LegacySharedReviewReassignmentMemoryRow[];\n}\n\nfunction legacySharedReviewConfirmationToken(input: {\n\trows: LegacySharedReviewReassignmentMemoryRow[];\n\tscopeId: string;\n\tstore: MemoryStore;\n\tworkspaceIdentity: string;\n}): string {\n\tconst ownedBySelf = input.store.buildOwnershipPredicate();\n\tconst payload = input.rows\n\t\t.map((row) => {\n\t\t\tconst ownership = ownedBySelf(row as unknown as Record<string, unknown>) ? \"local\" : \"peer\";\n\t\t\treturn `${row.id}:${row.rev ?? 0}:${row.scope_id ?? \"\"}:${ownership}`;\n\t\t})\n\t\t.sort()\n\t\t.join(\",\");\n\treturn Buffer.from(`${input.workspaceIdentity}|${input.scopeId}|${payload}`, \"utf8\").toString(\n\t\t\"base64url\",\n\t);\n}\n\ninterface LegacySharedReviewReassignmentPreview {\n\tconfirmation_token: string;\n\tworkspace_identity: string;\n\tscope_id: string;\n\ttarget_scope_label: string;\n\tmemory_count: number;\n\treassignable_memory_count: number;\n\tskipped_memory_count: number;\n\taffected_peer_device_count: number;\n\taffected_peer_device_ids: string[];\n\twarning: string;\n}\n\ninterface ProjectInventoryMemoryRow {\n\tid: number;\n\trev: number | null;\n\tproject: string | null;\n\tcwd: string | null;\n\tgit_remote: string | null;\n\tgit_branch: string | null;\n\tworkspace_id: string | null;\n\tactor_id: string | null;\n\torigin_device_id: string | null;\n\tmetadata_json: string | null;\n}\n\nfunction projectInventoryRowsForWorkspace(\n\tstore: MemoryStore,\n\tworkspaceIdentity: string,\n): ProjectInventoryMemoryRow[] {\n\tconst rows = store.db\n\t\t.prepare(\n\t\t\t`SELECT m.id,\n\t\t\t m.rev,\n\t\t\t s.project,\n\t\t\t s.cwd,\n\t\t\t s.git_remote,\n\t\t\t s.git_branch,\n\t\t\t m.workspace_id,\n\t\t\t m.actor_id,\n\t\t\t m.origin_device_id,\n\t\t\t m.metadata_json\n\t\t\t FROM memory_items m\n\t\t\t LEFT JOIN sessions s ON s.id = m.session_id\n\t\t\t WHERE m.active = 1\n\t\t\t AND m.deleted_at IS NULL`,\n\t\t)\n\t\t.all() as ProjectInventoryMemoryRow[];\n\treturn rows.filter((row) => {\n\t\tconst identity = canonicalWorkspaceIdentity({\n\t\t\tcwd: row.cwd,\n\t\t\tgitBranch: row.git_branch,\n\t\t\tgitRemote: row.git_remote,\n\t\t\tproject: row.project,\n\t\t\tworkspaceId: row.workspace_id,\n\t\t});\n\t\treturn identity.value === workspaceIdentity;\n\t});\n}\n\nfunction projectForgetConfirmationToken(\n\tstore: MemoryStore,\n\trows: ProjectInventoryMemoryRow[],\n): string {\n\tconst ownedBySelf = store.buildOwnershipPredicate();\n\tconst payload = rows\n\t\t.map((row) => {\n\t\t\tconst ownership = ownedBySelf(row as unknown as Record<string, unknown>) ? \"local\" : \"peer\";\n\t\t\treturn `${row.id}:${row.rev ?? 0}:${ownership}`;\n\t\t})\n\t\t.sort()\n\t\t.join(\",\");\n\treturn Buffer.from(payload, \"utf8\").toString(\"base64url\");\n}\n\nfunction forgetProjectInventoryLocalMemories(\n\tstore: MemoryStore,\n\tinput: { confirmationToken?: string | null; confirmed: boolean; workspaceIdentity: string },\n): Record<string, unknown> {\n\tif (!input.workspaceIdentity.trim()) {\n\t\tthrow new Error(\"workspace_identity must be a non-empty string\");\n\t}\n\tconst rows = projectInventoryRowsForWorkspace(store, input.workspaceIdentity);\n\tif (rows.length === 0) throw new Error(\"project identity not found\");\n\tconst ownedBySelf = store.buildOwnershipPredicate();\n\tconst localRows = rows.filter((row) => ownedBySelf(row as unknown as Record<string, unknown>));\n\tconst confirmationToken = projectForgetConfirmationToken(store, rows);\n\tconst preview = {\n\t\tconfirmation_token: confirmationToken,\n\t\tlocal_owned_memory_count: localRows.length,\n\t\tpeer_owned_memory_count: rows.length - localRows.length,\n\t\tworkspace_identity: input.workspaceIdentity,\n\t};\n\tif (!input.confirmed) {\n\t\treturn { confirmed: false, ...preview };\n\t}\n\tif (input.confirmationToken !== confirmationToken) {\n\t\tthrow new Error(\"project memories changed before cleanup; refresh and try again\");\n\t}\n\tstore.db.transaction(() => {\n\t\tfor (const row of localRows) store.forget(row.id);\n\t})();\n\treturn { confirmed: true, forgotten_memory_count: localRows.length, ...preview };\n}\n\nfunction assertLocalDeviceScopeMembership(store: MemoryStore, scopeId: string): void {\n\tif (scopeId === LOCAL_DEFAULT_SCOPE_ID) return;\n\tconst row = store.db\n\t\t.prepare(\n\t\t\t`SELECT 1\n\t\t\t FROM scope_memberships sm\n\t\t\t JOIN replication_scopes rs ON rs.scope_id = sm.scope_id\n\t\t\t WHERE sm.scope_id = ?\n\t\t\t AND sm.device_id = ?\n\t\t\t AND sm.status = 'active'\n\t\t\t AND rs.status = 'active'\n\t\t\t AND sm.membership_epoch >= rs.membership_epoch\n\t\t\t LIMIT 1`,\n\t\t)\n\t\t.get(scopeId, store.deviceId);\n\tif (!row) throw new Error(`local device is not a member of Sharing domain ${scopeId}`);\n}\n\nfunction legacySharedReviewRowsForWorkspace(\n\tstore: MemoryStore,\n\tworkspaceIdentity: string,\n): LegacySharedReviewReassignmentMemoryRow[] {\n\treturn legacySharedReviewRows(store).filter((row) => {\n\t\tconst identity = canonicalWorkspaceIdentity({\n\t\t\tcwd: row.cwd,\n\t\t\tgitBranch: row.git_branch,\n\t\t\tgitRemote: row.git_remote,\n\t\t\tproject: row.project,\n\t\t\tworkspaceId: row.workspace_id,\n\t\t});\n\t\treturn identity.value === workspaceIdentity;\n\t});\n}\n\nfunction reassignableLegacySharedReviewRows(\n\tstore: MemoryStore,\n\trows: LegacySharedReviewReassignmentMemoryRow[],\n): LegacySharedReviewReassignmentMemoryRow[] {\n\tconst reassignableRows = rows.filter((row) =>\n\t\tstore.memoryOwnedBySelf(row as unknown as Record<string, unknown>),\n\t);\n\tif (reassignableRows.length === 0) {\n\t\tthrow new Error(\n\t\t\t\"This legacy review group contains only peer-owned memories; this device cannot reassign them to a Sharing domain.\",\n\t\t);\n\t}\n\tconst currentRows = store.db\n\t\t.prepare(\n\t\t\t`SELECT id, scope_id, active, deleted_at\n\t\t\t FROM memory_items\n\t\t\t WHERE id IN (${reassignableRows.map(() => \"?\").join(\",\")})`,\n\t\t)\n\t\t.all(...reassignableRows.map((row) => row.id)) as Array<{\n\t\tactive: number | null;\n\t\tdeleted_at: string | null;\n\t\tid: number;\n\t\tscope_id: string | null;\n\t}>;\n\tconst currentById = new Map(currentRows.map((row) => [Number(row.id), row]));\n\tfor (const row of reassignableRows) {\n\t\tconst current = currentById.get(row.id);\n\t\tif (\n\t\t\tcurrent?.scope_id !== LEGACY_SHARED_REVIEW_SCOPE_ID ||\n\t\t\tcurrent.active !== 1 ||\n\t\t\tcurrent.deleted_at\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t\"legacy shared review group changed before reassignment; refresh and try again\",\n\t\t\t);\n\t\t}\n\t}\n\treturn reassignableRows;\n}\n\nfunction legacySharedReviewReassignmentPreview(\n\tstore: MemoryStore,\n\tinput: { scopeId: string; workspaceIdentity: string },\n): LegacySharedReviewReassignmentPreview {\n\tif (!input.workspaceIdentity.trim())\n\t\tthrow new Error(\"workspace_identity must be a non-empty string\");\n\tif (!input.scopeId.trim()) throw new Error(\"scope_id must be a non-empty string\");\n\tif (input.scopeId === LOCAL_DEFAULT_SCOPE_ID) {\n\t\tthrow new Error(\"local-default is not a valid target for legacy shared review reassignment\");\n\t}\n\tif (input.scopeId === LEGACY_SHARED_REVIEW_SCOPE_ID) {\n\t\tthrow new Error(\"legacy-shared-review is a review bucket, not an assignable Sharing domain\");\n\t}\n\tconst targetScope = listSharingDomainSettingsScopes(store.db).find(\n\t\t(scope) => scope.scope_id === input.scopeId,\n\t);\n\tif (!targetScope) throw new Error(`scope_id ${input.scopeId} is not an active Sharing domain`);\n\tassertLocalDeviceScopeMembership(store, input.scopeId);\n\tconst rows = legacySharedReviewRowsForWorkspace(store, input.workspaceIdentity);\n\tif (rows.length === 0) throw new Error(\"legacy shared review group not found\");\n\tconst reassignableRows = reassignableLegacySharedReviewRows(store, rows);\n\tconst peerDeviceIds = [\n\t\t...new Set(\n\t\t\trows\n\t\t\t\t.map((row) => String(row.origin_device_id ?? \"\").trim())\n\t\t\t\t.filter((deviceId) => deviceId && deviceId !== store.deviceId),\n\t\t),\n\t].sort();\n\treturn {\n\t\taffected_peer_device_count: peerDeviceIds.length,\n\t\taffected_peer_device_ids: peerDeviceIds.slice(0, 5),\n\t\tconfirmation_token: legacySharedReviewConfirmationToken({\n\t\t\trows,\n\t\t\tscopeId: input.scopeId,\n\t\t\tstore,\n\t\t\tworkspaceIdentity: input.workspaceIdentity,\n\t\t}),\n\t\tmemory_count: rows.length,\n\t\treassignable_memory_count: reassignableRows.length,\n\t\tscope_id: input.scopeId,\n\t\tskipped_memory_count: rows.length - reassignableRows.length,\n\t\ttarget_scope_label: targetScope.label || targetScope.scope_id,\n\t\twarning:\n\t\t\t\"This device can reassign only locally owned memories. Peer-owned copies must be fixed on their source device. Online compatible peers should converge after syncing, but offline devices, backups, copied databases, malicious peers, or old versions may retain old copies.\",\n\t\tworkspace_identity: input.workspaceIdentity,\n\t};\n}\n\nfunction reassignLegacySharedReviewGroup(\n\tstore: MemoryStore,\n\tinput: { confirmationToken?: string | null; scopeId: string; workspaceIdentity: string },\n): Record<string, unknown> {\n\tconst preview = legacySharedReviewReassignmentPreview(store, input);\n\tif (input.confirmationToken !== preview.confirmation_token) {\n\t\tthrow new Error(\n\t\t\t\"legacy shared review group changed before reassignment; refresh and try again\",\n\t\t);\n\t}\n\tconst rows = reassignableLegacySharedReviewRows(\n\t\tstore,\n\t\tlegacySharedReviewRowsForWorkspace(store, input.workspaceIdentity),\n\t);\n\tstore.db.transaction(() => {\n\t\tfor (const row of rows) store.reassignMemoryScope(row.id, input.scopeId);\n\t})();\n\treturn {\n\t\tok: true,\n\t\t...preview,\n\t\treassigned_memory_count: rows.length,\n\t\tlegacy_shared_review: legacySharedReviewSummary(store),\n\t};\n}\n\n// Aggregate ops_in / ops_out across recent successful sync_attempts per peer.\n// Window: last 24 hours. Feeds the per-peer direction glyph on the Sync tab\n// (↕ bidirectional, ↑ publishing, ↓ subscribed) off real traffic instead of\n// an invented peer-role field.\nconst SYNC_DIRECTION_WINDOW_SECONDS = 24 * 60 * 60;\n\nfunction recentPeerOps(store: MemoryStore): Map<string, { in: number; out: number }> {\n\tconst cutoff = new Date(Date.now() - SYNC_DIRECTION_WINDOW_SECONDS * 1000).toISOString();\n\tconst rows = store.db\n\t\t.prepare(\n\t\t\t`SELECT peer_device_id,\n\t\t\t COALESCE(SUM(ops_in), 0) AS ops_in,\n\t\t\t COALESCE(SUM(ops_out), 0) AS ops_out\n\t\t\t FROM sync_attempts\n\t\t\t WHERE ok = 1 AND finished_at IS NOT NULL AND finished_at >= ?\n\t\t\t GROUP BY peer_device_id`,\n\t\t)\n\t\t.all(cutoff) as Array<{\n\t\tpeer_device_id: string | null;\n\t\tops_in: number | null;\n\t\tops_out: number | null;\n\t}>;\n\tconst map = new Map<string, { in: number; out: number }>();\n\tfor (const row of rows) {\n\t\tconst id = String(row.peer_device_id ?? \"\").trim();\n\t\tif (!id) continue;\n\t\tmap.set(id, { in: Number(row.ops_in ?? 0), out: Number(row.ops_out ?? 0) });\n\t}\n\treturn map;\n}\n\n// ---------------------------------------------------------------------------\n// Peer status helpers\n// ---------------------------------------------------------------------------\n\nfunction isRecentIso(value: unknown, windowS = SYNC_STALE_AFTER_SECONDS): boolean {\n\tconst raw = String(value ?? \"\").trim();\n\tif (!raw) return false;\n\tconst normalized = raw.replace(\"Z\", \"+00:00\");\n\tconst hasOffset = /(?:Z|[+-]\\d{2}:?\\d{2})$/i.test(raw);\n\tconst ts = new Date(hasOffset ? normalized : `${normalized}+00:00`);\n\tif (Number.isNaN(ts.getTime())) return false;\n\tconst ageS = (Date.now() - ts.getTime()) / 1000;\n\treturn ageS >= 0 && ageS <= windowS;\n}\n\nfunction peerStatus(peer: Record<string, unknown>): Record<string, unknown> {\n\tconst lastSyncAt = peer.last_sync_at;\n\tconst lastPingAt = peer.last_seen_at;\n\tconst hasError = Boolean(peer.has_error);\n\n\tconst syncFresh = isRecentIso(lastSyncAt);\n\tconst pingFresh = isRecentIso(lastPingAt);\n\n\tlet peerState: string;\n\tif (hasError && !(syncFresh || pingFresh)) peerState = \"offline\";\n\telse if (hasError) peerState = \"degraded\";\n\telse if (syncFresh || pingFresh) peerState = \"online\";\n\telse if (lastSyncAt || lastPingAt) peerState = \"stale\";\n\telse peerState = \"unknown\";\n\n\tconst syncStatus = hasError ? \"error\" : syncFresh ? \"ok\" : lastSyncAt ? \"stale\" : \"unknown\";\n\tconst pingStatus = pingFresh ? \"ok\" : lastPingAt ? \"stale\" : \"unknown\";\n\n\treturn {\n\t\tsync_status: syncStatus,\n\t\tping_status: pingStatus,\n\t\tpeer_state: peerState,\n\t\tfresh: syncFresh || pingFresh,\n\t\tlast_sync_at: lastSyncAt,\n\t\tlast_ping_at: lastPingAt,\n\t};\n}\n\nfunction attemptStatus(attempt: Record<string, unknown>): string {\n\tif (attempt.ok) return \"ok\";\n\tif (attempt.error) return \"error\";\n\treturn \"unknown\";\n}\n\nfunction readViewerBinding(dbPath: string): { host: string; port: number } | null {\n\ttry {\n\t\tconst raw = readFileSync(join(dirname(dbPath), \"viewer.pid\"), \"utf8\");\n\t\tconst parsed = JSON.parse(raw) as Partial<{ host: string; port: number }>;\n\t\tif (typeof parsed.host === \"string\" && typeof parsed.port === \"number\") {\n\t\t\treturn { host: parsed.host, port: parsed.port };\n\t\t}\n\t} catch {\n\t\t// ignore missing/malformed pidfile\n\t}\n\treturn null;\n}\n\nconst PEERS_QUERY = `\n\tSELECT p.peer_device_id, p.name, p.pinned_fingerprint, p.addresses_json,\n\t p.last_seen_at, p.last_sync_at, p.last_error,\n\t p.runtime_version, p.runtime_version_observed_at,\n\t p.projects_include_json, p.projects_exclude_json, p.claimed_local_actor,\n\t p.actor_id, p.discovered_via_coordinator_id, p.discovered_via_group_id,\n\t a.display_name AS actor_display_name\n\tFROM sync_peers AS p\n\tLEFT JOIN actors AS a ON a.actor_id = p.actor_id\n\tORDER BY name, peer_device_id\n`;\n\n// ---------------------------------------------------------------------------\n// Route factory\n// ---------------------------------------------------------------------------\n\n/**\n * Compute the negotiated sync capability for a request by combining the\n * server's local capability with the value the caller advertised in the\n * `X-Codemem-Sync-Capability` header. Routes use this to decide whether to\n * honor scoped-sync wire features such as explicit `scope_id` parameters\n * and `/v1/status` `authorized_scopes` enumeration.\n *\n * Threat model: this header is intentionally only a best-effort capability\n * advertisement. It is not signed, so an authenticated paired peer — or a\n * bootstrap worker presenting a valid grant on `/v1/status` — can claim\n * `scoped` support and cause status to enumerate the scopes that caller is\n * already authorized to see. That is metadata disclosure inside the paired-peer\n * or bootstrap-grant trust boundary, not data authorization. Every scoped data\n * path still requires signed requests and checks membership before returning\n * scope contents.\n */\nfunction negotiatedSyncCapability(c: Context) {\n\tconst header = c.req.header(SYNC_CAPABILITY_HEADER) ?? null;\n\treturn negotiateSyncCapability(LOCAL_SYNC_CAPABILITY, normalizeSyncCapability(header));\n}\n\n/**\n * Peer-to-peer sync protocol routes (/v1/*).\n *\n * These are mounted on the sync listener (0.0.0.0:7337) and are\n * network-accessible. All requests are auth-gated via signature\n * verification so unauthenticated callers are rejected.\n */\nexport function syncProtocolRoutes(getStore: StoreFactory, opts: SyncProtocolRouteOptions = {}) {\n\tconst app = new Hono();\n\tconst routeRateLimit = opts.routeRateLimit ?? null;\n\n\tfunction rateLimitedResponse(c: Context, key: string, authenticated: boolean) {\n\t\tif (!routeRateLimit) return null;\n\t\tconst isRead = c.req.method === \"GET\" || c.req.method === \"HEAD\" || c.req.method === \"OPTIONS\";\n\t\tconst result = routeRateLimit.limiter.check(\n\t\t\t`${c.req.method}:${authenticated ? \"auth\" : \"anon\"}:${key}`,\n\t\t\tauthenticated\n\t\t\t\t? isRead\n\t\t\t\t\t? routeRateLimit.readLimit\n\t\t\t\t\t: routeRateLimit.mutationLimit\n\t\t\t\t: isRead\n\t\t\t\t\t? routeRateLimit.unauthenticatedReadLimit\n\t\t\t\t\t: routeRateLimit.unauthenticatedMutationLimit,\n\t\t);\n\t\tif (result.allowed) return null;\n\t\tc.header(\"Retry-After\", String(result.retryAfterS));\n\t\treturn c.json({ error: \"rate_limited\", retry_after_s: result.retryAfterS }, 429);\n\t}\n\n\t// GET /v1/status (peer sync protocol)\n\tapp.get(\"/v1/status\", (c) => {\n\t\tconst store = getStore();\n\t\treturn (async () => {\n\t\t\tlet auth = authorizeSyncRequest(store, c.req, Buffer.alloc(0));\n\t\t\tif (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);\n\t\t\tlet preauthChecked = false;\n\t\t\tlet bootstrapAttempted = false;\n\t\t\tlet deviceAuthReason: string | null = null;\n\t\t\tif (!auth.ok) {\n\t\t\t\tconst bootstrapGrantId = (c.req.header(\"X-Codemem-Bootstrap-Grant\") ?? \"\").trim();\n\t\t\t\tif (bootstrapGrantId) {\n\t\t\t\t\tpreauthChecked = true;\n\t\t\t\t\t// Use unauthenticated bucket with stable key — grant is not yet verified,\n\t\t\t\t\t// so caller-controlled headers must not influence rate-limit identity.\n\t\t\t\t\tconst bootstrapLimited = rateLimitedResponse(c, c.req.path, false);\n\t\t\t\t\tif (bootstrapLimited) return bootstrapLimited;\n\t\t\t\t} else {\n\t\t\t\t\tpreauthChecked = true;\n\t\t\t\t\tconst unauthLimited = rateLimitedResponse(c, c.req.path, false);\n\t\t\t\t\tif (unauthLimited) return unauthLimited;\n\t\t\t\t}\n\t\t\t\tdeviceAuthReason = auth.reason;\n\t\t\t\tauth = await authorizeBootstrapGrantRequest(store, c.req, Buffer.alloc(0));\n\t\t\t\tbootstrapAttempted = true;\n\t\t\t}\n\t\t\tif (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);\n\t\t\tif (!auth.ok) {\n\t\t\t\t// Specific reasons stay server-side; wire responses remain generic.\n\t\t\t\tconst grantPresent = Boolean((c.req.header(\"X-Codemem-Bootstrap-Grant\") ?? \"\").trim());\n\t\t\t\t// Warn only when the caller actually attempted authentication (a\n\t\t\t\t// grant or signed device headers); bare probes and health checks\n\t\t\t\t// must not fill logs with attacker-controllable noise.\n\t\t\t\tconst authAttempted =\n\t\t\t\t\tgrantPresent || (deviceAuthReason != null && deviceAuthReason !== \"missing_headers\");\n\t\t\t\tif (bootstrapAttempted && authAttempted) {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`[sync] peer auth failed: reason=${auth.reason} device_auth_reason=${deviceAuthReason ?? \"none\"} grant_present=${grantPresent} path=${c.req.path} device=${loggableHeaderValue(c.req.header(\"X-Opencode-Device\"))}`,\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tlogDirectPeerAuthDiagnostic(deviceAuthReason, auth.reason);\n\t\t\t\t}\n\t\t\t\treturn (\n\t\t\t\t\t(preauthChecked ? null : rateLimitedResponse(c, c.req.path, false)) ??\n\t\t\t\t\tc.json(unauthorizedPayload(), 401)\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst limited = rateLimitedResponse(c, auth.deviceId, true);\n\t\t\tif (limited) return limited;\n\n\t\t\ttry {\n\t\t\t\tif (\n\t\t\t\t\tc.req.header(SYNC_AUTHORIZATION_REFRESH_HEADER) === \"1\" &&\n\t\t\t\t\tsupportsSyncFeature(c.req.header(SYNC_FEATURES_HEADER), \"reassign_scope\")\n\t\t\t\t) {\n\t\t\t\t\t// Project-first provisioning grants at the coordinator immediately before\n\t\t\t\t\t// this status probe. Refresh now so the managed scope can participate in\n\t\t\t\t\t// the same initial sync pass instead of waiting for the daemon interval.\n\t\t\t\t\tawait refreshConfiguredScopeMembershipCache(store.db, undefined, {\n\t\t\t\t\t\tkeysDir: syncKeysDir(),\n\t\t\t\t\t\tdbPath: store.dbPath,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tconst [deviceId, fingerprint] = ensureDeviceIdentity(store.db, {\n\t\t\t\t\tkeysDir: syncKeysDir(),\n\t\t\t\t});\n\t\t\t\tconst syncReset = getSyncResetState(store.db);\n\t\t\t\tconst negotiated = negotiatedSyncCapability(c);\n\t\t\t\tconst authorizedScopes = isScopedSyncCapability(negotiated)\n\t\t\t\t\t? listAuthorizedScopesForPeer(store.db, {\n\t\t\t\t\t\t\tlocalDeviceId: deviceId,\n\t\t\t\t\t\t\tpeerDeviceId: auth.deviceId,\n\t\t\t\t\t\t})\n\t\t\t\t\t: null;\n\t\t\t\tconst response: Record<string, unknown> = {\n\t\t\t\t\tdevice_id: deviceId,\n\t\t\t\t\tprotocol_version: SYNC_PROTOCOL_VERSION,\n\t\t\t\t\tfingerprint,\n\t\t\t\t\truntime_version: VERSION,\n\t\t\t\t\tsync_reset: addSyncScopeToBoundary(syncReset, null),\n\t\t\t\t\tsync_capability: LOCAL_SYNC_CAPABILITY,\n\t\t\t\t\tsync_features: LOCAL_SYNC_FEATURES,\n\t\t\t\t};\n\t\t\t\tif (authorizedScopes !== null) {\n\t\t\t\t\tresponse.authorized_scopes = authorizedScopes;\n\t\t\t\t}\n\t\t\t\treturn c.json(response);\n\t\t\t} catch {\n\t\t\t\treturn c.json({ error: \"internal_error\" }, 500);\n\t\t\t}\n\t\t})();\n\t});\n\n\t// GET /v1/ops (peer sync protocol)\n\tapp.get(\"/v1/ops\", (c) => {\n\t\tconst store = getStore();\n\t\tconst auth = authorizeSyncRequest(store, c.req, Buffer.alloc(0));\n\t\tif (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);\n\t\tif (!auth.ok) {\n\t\t\tlogDirectPeerAuthDiagnostic(auth.reason);\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json(unauthorizedPayload(), 401);\n\t\t}\n\t\tconst limited = rateLimitedResponse(c, auth.deviceId, true);\n\t\tif (limited) return limited;\n\t\tconst peerDeviceId = auth.deviceId;\n\n\t\ttry {\n\t\t\tconst rawScopeId = c.req.query(SYNC_SCOPE_QUERY_PARAM);\n\t\t\tconst negotiated = negotiatedSyncCapability(c);\n\t\t\tconst [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });\n\t\t\tconst scopeRequest = parseSyncScopeRequest(rawScopeId, rawScopeId !== undefined, {\n\t\t\t\tdb: store.db,\n\t\t\t\tlocalDeviceId,\n\t\t\t\tnegotiatedCapability: negotiated,\n\t\t\t\tpeerDeviceId,\n\t\t\t});\n\t\t\tif (!scopeRequest.ok) {\n\t\t\t\treturn c.json(\n\t\t\t\t\tsyncScopeResetRequiredPayload(\n\t\t\t\t\t\tgetSyncResetState(store.db),\n\t\t\t\t\t\tscopeRequest.reason,\n\t\t\t\t\t\tLOCAL_SYNC_CAPABILITY,\n\t\t\t\t\t\tnull,\n\t\t\t\t\t),\n\t\t\t\t\t409,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst since = c.req.query(\"since\") ?? null;\n\t\t\tconst rawLimit = Number.parseInt(c.req.query(\"limit\") ?? \"200\", 10);\n\t\t\tconst rawGeneration = c.req.query(\"generation\");\n\t\t\tconst generation =\n\t\t\t\trawGeneration != null && rawGeneration.trim().length > 0\n\t\t\t\t\t? Number.parseInt(rawGeneration, 10)\n\t\t\t\t\t: null;\n\t\t\tconst snapshotId = c.req.query(\"snapshot_id\") ?? null;\n\t\t\tconst baselineCursor = c.req.query(\"baseline_cursor\") ?? null;\n\t\t\tconst limit = Number.isFinite(rawLimit) ? Math.max(1, Math.min(rawLimit, 1000)) : 200;\n\t\t\tconst result = loadReplicationOpsForPeer(store.db, {\n\t\t\t\tsince,\n\t\t\t\tlimit,\n\t\t\t\tdeviceId: localDeviceId,\n\t\t\t\tgeneration: Number.isFinite(generation) ? generation : null,\n\t\t\t\tsnapshotId,\n\t\t\t\tbaselineCursor,\n\t\t\t\tscopeId: scopeRequest.mode === \"scoped\" ? scopeRequest.scope_id : undefined,\n\t\t\t});\n\t\t\tif (result.reset_required) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"reset_required\",\n\t\t\t\t\t\tsync_capability: LOCAL_SYNC_CAPABILITY,\n\t\t\t\t\t\t...addSyncScopeToBoundary(result.reset, scopeRequest.scope_id),\n\t\t\t\t\t},\n\t\t\t\t\t409,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst { ops, nextCursor, boundary } = result;\n\t\t\tconst filtered = filterOpsForPeer(store, peerDeviceId, localDeviceId, ops, {\n\t\t\t\tsupportsReassignScope: supportsSyncFeature(\n\t\t\t\t\tc.req.header(SYNC_FEATURES_HEADER),\n\t\t\t\t\t\"reassign_scope\",\n\t\t\t\t),\n\t\t\t});\n\t\t\treturn c.json({\n\t\t\t\treset_required: false,\n\t\t\t\tsync_capability: LOCAL_SYNC_CAPABILITY,\n\t\t\t\tscope_id: scopeRequest.scope_id,\n\t\t\t\tgeneration: boundary.generation,\n\t\t\t\tsnapshot_id: boundary.snapshot_id,\n\t\t\t\tbaseline_cursor: boundary.baseline_cursor,\n\t\t\t\tretained_floor_cursor: boundary.retained_floor_cursor,\n\t\t\t\tops: filtered.allowed,\n\t\t\t\tnext_cursor: nextCursor,\n\t\t\t\tskipped: filtered.skipped,\n\t\t\t\tskipped_detail: filtered.skippedDetail,\n\t\t\t});\n\t\t} catch {\n\t\t\treturn c.json({ error: \"internal_error\" }, 500);\n\t\t}\n\t});\n\n\t// GET /v1/snapshot (peer sync protocol — bootstrap snapshot pages)\n\tapp.get(\"/v1/snapshot\", (c) => {\n\t\tconst store = getStore();\n\t\treturn (async () => {\n\t\t\tlet auth = authorizeSyncRequest(store, c.req, Buffer.alloc(0));\n\t\t\tif (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);\n\t\t\tlet preauthChecked = false;\n\t\t\tlet bootstrapAttempted = false;\n\t\t\tlet deviceAuthReason: string | null = null;\n\t\t\tif (!auth.ok) {\n\t\t\t\tconst bootstrapGrantId = (c.req.header(\"X-Codemem-Bootstrap-Grant\") ?? \"\").trim();\n\t\t\t\tif (bootstrapGrantId) {\n\t\t\t\t\tpreauthChecked = true;\n\t\t\t\t\t// Use unauthenticated bucket with stable key — grant is not yet verified,\n\t\t\t\t\t// so caller-controlled headers must not influence rate-limit identity.\n\t\t\t\t\tconst bootstrapLimited = rateLimitedResponse(c, c.req.path, false);\n\t\t\t\t\tif (bootstrapLimited) return bootstrapLimited;\n\t\t\t\t} else {\n\t\t\t\t\tpreauthChecked = true;\n\t\t\t\t\tconst unauthLimited = rateLimitedResponse(c, c.req.path, false);\n\t\t\t\t\tif (unauthLimited) return unauthLimited;\n\t\t\t\t}\n\t\t\t\tdeviceAuthReason = auth.reason;\n\t\t\t\tauth = await authorizeBootstrapGrantRequest(store, c.req, Buffer.alloc(0));\n\t\t\t\tbootstrapAttempted = true;\n\t\t\t}\n\t\t\tif (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);\n\t\t\tif (!auth.ok) {\n\t\t\t\t// Specific reasons stay server-side; wire responses remain generic.\n\t\t\t\tconst grantPresent = Boolean((c.req.header(\"X-Codemem-Bootstrap-Grant\") ?? \"\").trim());\n\t\t\t\t// Warn only when the caller actually attempted authentication (a\n\t\t\t\t// grant or signed device headers); bare probes and health checks\n\t\t\t\t// must not fill logs with attacker-controllable noise.\n\t\t\t\tconst authAttempted =\n\t\t\t\t\tgrantPresent || (deviceAuthReason != null && deviceAuthReason !== \"missing_headers\");\n\t\t\t\tif (bootstrapAttempted && authAttempted) {\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`[sync] peer auth failed: reason=${auth.reason} device_auth_reason=${deviceAuthReason ?? \"none\"} grant_present=${grantPresent} path=${c.req.path} device=${loggableHeaderValue(c.req.header(\"X-Opencode-Device\"))}`,\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tlogDirectPeerAuthDiagnostic(deviceAuthReason, auth.reason);\n\t\t\t\t}\n\t\t\t\treturn (\n\t\t\t\t\t(preauthChecked ? null : rateLimitedResponse(c, c.req.path, false)) ??\n\t\t\t\t\tc.json(unauthorizedPayload(), 401)\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst limited = rateLimitedResponse(c, auth.deviceId, true);\n\t\t\tif (limited) return limited;\n\n\t\t\ttry {\n\t\t\t\tconst rawScopeId = c.req.query(SYNC_SCOPE_QUERY_PARAM);\n\t\t\t\tconst negotiated = negotiatedSyncCapability(c);\n\t\t\t\tconst [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });\n\t\t\t\tconst scopeRequest = parseSyncScopeRequest(rawScopeId, rawScopeId !== undefined, {\n\t\t\t\t\tdb: store.db,\n\t\t\t\t\tlocalDeviceId,\n\t\t\t\t\tnegotiatedCapability: negotiated,\n\t\t\t\t\tpeerDeviceId: auth.deviceId,\n\t\t\t\t});\n\t\t\t\tif (!scopeRequest.ok) {\n\t\t\t\t\treturn c.json(\n\t\t\t\t\t\tsyncScopeResetRequiredPayload(\n\t\t\t\t\t\t\tgetSyncResetState(store.db),\n\t\t\t\t\t\t\tscopeRequest.reason,\n\t\t\t\t\t\t\tLOCAL_SYNC_CAPABILITY,\n\t\t\t\t\t\t\tnull,\n\t\t\t\t\t\t),\n\t\t\t\t\t\t409,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst rawGeneration = c.req.query(\"generation\");\n\t\t\t\tconst generation =\n\t\t\t\t\trawGeneration != null && rawGeneration.trim().length > 0\n\t\t\t\t\t\t? Number.parseInt(rawGeneration, 10)\n\t\t\t\t\t\t: null;\n\t\t\t\tconst snapshotId = c.req.query(\"snapshot_id\") ?? null;\n\t\t\t\tconst baselineCursor = c.req.query(\"baseline_cursor\") ?? null;\n\t\t\t\tconst pageToken = c.req.query(\"page_token\") ?? null;\n\t\t\t\tconst rawLimit = Number.parseInt(c.req.query(\"limit\") ?? \"200\", 10);\n\t\t\t\t// Cap raised to 5000 to support elevated bootstrap page sizes (default 2000).\n\t\t\t\tconst limit = Number.isFinite(rawLimit) ? Math.max(1, Math.min(rawLimit, 5000)) : 200;\n\n\t\t\t\tif (generation == null || !Number.isFinite(generation)) {\n\t\t\t\t\treturn c.json({ error: \"missing_generation\" }, 400);\n\t\t\t\t}\n\t\t\t\tif (!snapshotId) {\n\t\t\t\t\treturn c.json({ error: \"missing_snapshot_id\" }, 400);\n\t\t\t\t}\n\n\t\t\t\tconst result = loadMemorySnapshotPageForPeer(store.db, {\n\t\t\t\t\tgeneration,\n\t\t\t\t\tsnapshotId,\n\t\t\t\t\tbaselineCursor,\n\t\t\t\t\tpageToken,\n\t\t\t\t\tlimit,\n\t\t\t\t\tpeerDeviceId: auth.deviceId,\n\t\t\t\t\tscopeId: scopeRequest.mode === \"scoped\" ? scopeRequest.scope_id : undefined,\n\t\t\t\t});\n\n\t\t\t\treturn c.json({\n\t\t\t\t\tscope_id: scopeRequest.scope_id,\n\t\t\t\t\tgeneration: result.boundary.generation,\n\t\t\t\t\tsnapshot_id: result.boundary.snapshot_id,\n\t\t\t\t\tbaseline_cursor: result.boundary.baseline_cursor,\n\t\t\t\t\tretained_floor_cursor: result.boundary.retained_floor_cursor,\n\t\t\t\t\tsync_capability: LOCAL_SYNC_CAPABILITY,\n\t\t\t\t\titems: result.items,\n\t\t\t\t\tnext_page_token: result.nextPageToken,\n\t\t\t\t\thas_more: result.hasMore,\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\tconst message = err instanceof Error ? err.message : \"\";\n\t\t\t\tif (message === \"generation_mismatch\" || message === \"boundary_mismatch\") {\n\t\t\t\t\treturn c.json({ error: message }, 409);\n\t\t\t\t}\n\t\t\t\treturn c.json({ error: \"internal_error\" }, 500);\n\t\t\t}\n\t\t})();\n\t});\n\n\t// POST /v1/ops (peer sync protocol)\n\tapp.post(\"/v1/ops\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst raw = await readBoundedRequestBytes(c.req.raw, MAX_SYNC_BODY_BYTES);\n\t\tif (raw == null) {\n\t\t\treturn c.json({ error: \"payload_too_large\" }, 413);\n\t\t}\n\n\t\tconst auth = authorizeSyncRequest(store, c.req, raw);\n\t\tif (isSyncAuthStoreBusy(auth)) return syncAuthStoreBusyResponse(c);\n\t\tif (!auth.ok) {\n\t\t\tlogDirectPeerAuthDiagnostic(auth.reason);\n\t\t\treturn rateLimitedResponse(c, c.req.path, false) ?? c.json(unauthorizedPayload(), 401);\n\t\t}\n\t\tconst limited = rateLimitedResponse(c, auth.deviceId, true);\n\t\tif (limited) return limited;\n\t\tconst peerDeviceId = auth.deviceId;\n\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(raw.toString(\"utf-8\")) as unknown;\n\t\t\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n\t\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t\t}\n\t\t\tbody = parsed as Record<string, unknown>;\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\n\t\tconst negotiated = negotiateSyncCapability(\n\t\t\tLOCAL_SYNC_CAPABILITY,\n\t\t\tnormalizeSyncCapability(body.sync_capability),\n\t\t);\n\t\tconst [localDeviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });\n\t\tconst scopeRequest = parseSyncScopeRequest(body.scope_id, Object.hasOwn(body, \"scope_id\"), {\n\t\t\tdb: store.db,\n\t\t\tlocalDeviceId,\n\t\t\tnegotiatedCapability: negotiated,\n\t\t\tpeerDeviceId,\n\t\t});\n\t\tif (!scopeRequest.ok) {\n\t\t\treturn c.json(\n\t\t\t\tsyncScopeResetRequiredPayload(\n\t\t\t\t\tgetSyncResetState(store.db),\n\t\t\t\t\tscopeRequest.reason,\n\t\t\t\t\tLOCAL_SYNC_CAPABILITY,\n\t\t\t\t\tnull,\n\t\t\t\t),\n\t\t\t\t409,\n\t\t\t);\n\t\t}\n\t\tif (!Array.isArray(body.ops)) {\n\t\t\treturn c.json({ error: \"invalid_ops\" }, 400);\n\t\t}\n\t\tif (body.ops.length > MAX_SYNC_OPS) {\n\t\t\treturn c.json({ error: \"too_many_ops\" }, 413);\n\t\t}\n\n\t\tconst normalizedOps = extractReplicationOps(body);\n\t\tconst peerFeatures = normalizeSyncFeatures(body.sync_features);\n\t\tconst reassignOps = normalizedOps.filter((op) => op.op_type === \"reassign_scope\");\n\t\tif (reassignOps.length > 0 && !peerFeatures.includes(\"reassign_scope\")) {\n\t\t\treturn c.json({ error: \"reassign_capability_required\" }, 409);\n\t\t}\n\t\ttry {\n\t\t\tfor (const op of reassignOps) parseReassignScopePayload(op);\n\t\t} catch {\n\t\t\treturn c.json({ error: \"reassign_payload_invalid\" }, 400);\n\t\t}\n\t\tfor (const op of normalizedOps) {\n\t\t\tif (op.device_id !== peerDeviceId || op.clock_device_id !== peerDeviceId) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"invalid_op_device\",\n\t\t\t\t\t\treason: \"device_id_mismatch\",\n\t\t\t\t\t\top_id: op.op_id,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\t// Inbound POSTs still use legacy visibility/project filters, but must not run\n\t\t// the outbound scope gate. Unsupported peers deliberately bypass strict inbound\n\t\t// scope rejection during rollout, so outbound filtering would silently drop data.\n\t\tconst filtered = filterOpsForPeer(store, peerDeviceId, localDeviceId, normalizedOps, {\n\t\t\tapplyScopeFilter: false,\n\t\t\tsupportsReassignScope: peerFeatures.includes(\"reassign_scope\"),\n\t\t});\n\t\t// Scope validation runs against the full signed batch so bad scoped ops cannot\n\t\t// evade fail-closed rejection by also tripping peer project filters.\n\t\tconst rejected = rejectInboundScopeFailures(store.db, normalizedOps, localDeviceId, {\n\t\t\tenabled: negotiated !== \"unsupported\",\n\t\t\tpeerDeviceId,\n\t\t});\n\t\tif (rejected) {\n\t\t\treturn c.json(\n\t\t\t\t{\n\t\t\t\t\terror: \"scope_rejected\",\n\t\t\t\t\treason: rejected.rejections[0]?.reason ?? \"scope_mismatch\",\n\t\t\t\t\trejections: rejected.rejections,\n\t\t\t\t\tsync_capability: LOCAL_SYNC_CAPABILITY,\n\t\t\t\t\tscope_id: scopeRequest.scope_id,\n\t\t\t\t},\n\t\t\t\t403,\n\t\t\t);\n\t\t}\n\n\t\tconst result = applyReplicationOps(store.db, filtered.allowed, localDeviceId, store.scanner);\n\t\tconst skipped = result.skipped + filtered.skipped;\n\t\treturn c.json({\n\t\t\t...result,\n\t\t\tskipped,\n\t\t\tskipped_detail: filtered.skippedDetail,\n\t\t\tsync_capability: LOCAL_SYNC_CAPABILITY,\n\t\t\tscope_id: scopeRequest.scope_id,\n\t\t});\n\t});\n\n\treturn app;\n}\n\nasync function loadConfiguredDeviceIdentityCoordinatorEvidence(): Promise<DeviceIdentityCoordinatorEvidence> {\n\tconst config = readCoordinatorSyncConfig();\n\tconst hasCoordinatorConfiguration =\n\t\tconfig.syncCoordinatorUrl.length > 0 || config.syncCoordinatorGroups.length > 0;\n\tconst remoteUrl = config.syncCoordinatorUrl.trim();\n\tconst adminSecret = config.syncCoordinatorAdminSecret.trim();\n\tconst groupIds = [\n\t\t...new Set(config.syncCoordinatorGroups.map((groupId) => groupId.trim())),\n\t].filter(Boolean);\n\tif (!hasCoordinatorConfiguration) {\n\t\treturn {\n\t\t\tavailability: \"unavailable\",\n\t\t\tsafeErrorCode: \"coordinator_not_configured\",\n\t\t\tenrollments: [],\n\t\t};\n\t}\n\tif (!remoteUrl || !adminSecret || groupIds.length === 0) {\n\t\treturn {\n\t\t\tavailability: \"unavailable\",\n\t\t\tsafeErrorCode: \"coordinator_unavailable\",\n\t\t\tenrollments: [],\n\t\t};\n\t}\n\tif (groupIds.length > 25) {\n\t\treturn {\n\t\t\tavailability: \"unavailable\",\n\t\t\tsafeErrorCode: \"coordinator_evidence_too_large\",\n\t\t\tenrollments: [],\n\t\t};\n\t}\n\ttry {\n\t\tconst enrollments = (\n\t\t\tawait Promise.all(\n\t\t\t\tgroupIds.map((groupId) =>\n\t\t\t\t\tcoordinatorListDevicesAction({\n\t\t\t\t\t\tgroupId,\n\t\t\t\t\t\tincludeDisabled: true,\n\t\t\t\t\t\tremoteUrl,\n\t\t\t\t\t\tadminSecret,\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t)\n\t\t).flat();\n\t\tif (enrollments.length > 500) {\n\t\t\treturn {\n\t\t\t\tavailability: \"unavailable\",\n\t\t\t\tsafeErrorCode: \"coordinator_evidence_too_large\",\n\t\t\t\tenrollments: [],\n\t\t\t};\n\t\t}\n\t\treturn { availability: \"available\", safeErrorCode: null, enrollments };\n\t} catch {\n\t\treturn {\n\t\t\tavailability: \"unavailable\",\n\t\t\tsafeErrorCode: \"coordinator_unavailable\",\n\t\t\tenrollments: [],\n\t\t};\n\t}\n}\n\n/**\n * Viewer-facing sync management routes (/api/sync/*).\n *\n * These are mounted on the viewer listener (127.0.0.1:38888) and\n * provide sync status, peer management, and coordinator UI for the\n * local viewer.\n */\nexport function syncRoutes(\n\tgetStore: StoreFactory,\n\tgetSyncRuntimeStatus?: () => SyncRuntimeStatus | null,\n\toptions: SyncRoutesOptions = {},\n) {\n\tconst app = new Hono();\n\tconst readCoordinatorConfig = options.readCoordinatorConfig ?? readCoordinatorSyncConfig;\n\tconst renameCoordinatorGroup = options.renameCoordinatorGroup ?? coordinatorRenameGroupAction;\n\tconst loadCoordinatorEvidence =\n\t\toptions.loadDeviceIdentityCoordinatorEvidence ??\n\t\tloadConfiguredDeviceIdentityCoordinatorEvidence;\n\tconst currentCoordinatorEvidence = async (): Promise<DeviceIdentityCoordinatorEvidence> => {\n\t\ttry {\n\t\t\treturn await loadCoordinatorEvidence();\n\t\t} catch {\n\t\t\treturn {\n\t\t\t\tavailability: \"unavailable\",\n\t\t\t\tsafeErrorCode: \"coordinator_unavailable\",\n\t\t\t\tenrollments: [],\n\t\t\t};\n\t\t}\n\t};\n\tconst localInventoryInput = async (store: MemoryStore) => {\n\t\tlet explicitDeviceName = \"\";\n\t\ttry {\n\t\t\texplicitDeviceName = String(readCodememConfigFile().sync_device_name ?? \"\");\n\t\t} catch {\n\t\t\texplicitDeviceName = \"\";\n\t\t}\n\t\treturn {\n\t\t\tlocalDeviceId: store.deviceId,\n\t\t\tlocalDisplayName: friendlyDeviceName({\n\t\t\t\texplicitName: explicitDeviceName,\n\t\t\t\tosName: hostname(),\n\t\t\t\tfallbackSeed: store.deviceId,\n\t\t\t}),\n\t\t\tcoordinator: await currentCoordinatorEvidence(),\n\t\t};\n\t};\n\n\tapp.get(\"/api/sync/recipient-policy/v1/device-inventory\", async (c) => {\n\t\tconst store = getStore();\n\t\tensureStableStoreIdentity(store);\n\t\treturn c.json(listDeviceIdentityInventory(store.db, await localInventoryInput(store)));\n\t});\n\n\tapp.patch(\"/api/sync/recipient-policy/v1/teams/:teamId\", async (c) => {\n\t\tconst raw = await readBoundedRequestBytes(c.req.raw, 8_192);\n\t\tif (!raw) return c.json({ error: \"team_name_invalid\" as const }, 400);\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(raw.toString(\"utf8\")) as unknown;\n\t\t\tif (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n\t\t\t\treturn c.json({ error: \"team_name_invalid\" as const }, 400);\n\t\t\t}\n\t\t\tbody = parsed as Record<string, unknown>;\n\t\t} catch {\n\t\t\treturn c.json({ error: \"team_name_invalid\" as const }, 400);\n\t\t}\n\t\tif (\n\t\t\tObject.keys(body).length !== 2 ||\n\t\t\t!Object.hasOwn(body, \"displayName\") ||\n\t\t\t!Object.hasOwn(body, \"expectedDisplayName\") ||\n\t\t\ttypeof body.displayName !== \"string\" ||\n\t\t\ttypeof body.expectedDisplayName !== \"string\"\n\t\t) {\n\t\t\treturn c.json({ error: \"team_name_invalid\" as const }, 400);\n\t\t}\n\t\ttry {\n\t\t\tconst store = getStore();\n\t\t\tconst config = readCoordinatorConfig();\n\t\t\tconst coordinatorId = config.syncCoordinatorUrl\n\t\t\t\t? buildBaseUrl(config.syncCoordinatorUrl)\n\t\t\t\t: null;\n\t\t\tconst normalizedConfiguredCoordinatorId = coordinatorId\n\t\t\t\t? normalizedCoordinatorId(coordinatorId)\n\t\t\t\t: null;\n\t\t\tlet configuredCoordinatorGroups: ReturnType<typeof legacyTeamCandidateGroupDescriptors> = [];\n\t\t\tif (coordinatorId) {\n\t\t\t\ttry {\n\t\t\t\t\t// Scope-backed descriptors widen rename eligibility only when\n\t\t\t\t\t// linkedGroup() also proves exact completed-setup history.\n\t\t\t\t\tconfiguredCoordinatorGroups = legacyTeamCandidateGroupDescriptors(\n\t\t\t\t\t\tstore,\n\t\t\t\t\t\tconfig.syncCoordinatorUrl,\n\t\t\t\t\t\tconfig.syncCoordinatorGroups,\n\t\t\t\t\t);\n\t\t\t\t} catch {\n\t\t\t\t\t// Bad coordinator evidence must not block a local-only rename.\n\t\t\t\t\t// Proven linked Teams still fail closed as team_link_stale.\n\t\t\t\t\tconfiguredCoordinatorGroups = [];\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst result = await renameRecipientPolicyTeam(store.db, {\n\t\t\t\tteamId: c.req.param(\"teamId\"),\n\t\t\t\tdisplayName: body.displayName,\n\t\t\t\texpectedDisplayName: body.expectedDisplayName,\n\t\t\t\tconfiguredCoordinatorGroups,\n\t\t\t\tcoordinatorIdsEquivalent: (left, right) => {\n\t\t\t\t\tconst normalizedLeft = normalizedCoordinatorId(left);\n\t\t\t\t\tconst normalizedRight = normalizedCoordinatorId(right);\n\t\t\t\t\treturn normalizedLeft !== null && normalizedLeft === normalizedRight;\n\t\t\t\t},\n\t\t\t\trenameCoordinatorGroup: async (group, normalizedDisplayName) => {\n\t\t\t\t\tconst normalizedLinkedCoordinatorId = normalizedCoordinatorId(group.coordinatorId);\n\t\t\t\t\tif (\n\t\t\t\t\t\t!config.syncCoordinatorUrl ||\n\t\t\t\t\t\t!config.syncCoordinatorAdminSecret ||\n\t\t\t\t\t\t!normalizedConfiguredCoordinatorId ||\n\t\t\t\t\t\t!normalizedLinkedCoordinatorId ||\n\t\t\t\t\t\tnormalizedLinkedCoordinatorId !== normalizedConfiguredCoordinatorId\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tconst renamed = await renameCoordinatorGroup({\n\t\t\t\t\t\tgroupId: group.groupId,\n\t\t\t\t\t\tdisplayName: normalizedDisplayName,\n\t\t\t\t\t\tremoteUrl: config.syncCoordinatorUrl,\n\t\t\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret,\n\t\t\t\t\t});\n\t\t\t\t\treturn (\n\t\t\t\t\t\trenamed?.group_id === group.groupId && renamed.display_name === normalizedDisplayName\n\t\t\t\t\t);\n\t\t\t\t},\n\t\t\t});\n\t\t\ttry {\n\t\t\t\toptions.onRecipientPolicyTeamRenamed?.();\n\t\t\t} catch {\n\t\t\t\t// Cache invalidation is best-effort after the authoritative rename commits.\n\t\t\t}\n\t\t\treturn c.json(result);\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof RecipientPolicyTeamRenameError)) {\n\t\t\t\treturn c.json({ error: \"team_rename_failed\" as const }, 503);\n\t\t\t}\n\t\t\tconst status =\n\t\t\t\terror.code === \"team_name_invalid\"\n\t\t\t\t\t? 400\n\t\t\t\t\t: error.code === \"team_not_found\"\n\t\t\t\t\t\t? 404\n\t\t\t\t\t\t: error.code === \"team_coordinator_rename_failed\" ||\n\t\t\t\t\t\t\t\terror.code === \"team_local_rename_pending\" ||\n\t\t\t\t\t\t\t\terror.code === \"team_rename_failed\"\n\t\t\t\t\t\t\t? 503\n\t\t\t\t\t\t\t: 409;\n\t\t\treturn c.json({ error: error.code }, status);\n\t\t}\n\t});\n\n\tconst parseDeviceBindingRequest = (\n\t\tvalue: unknown,\n\t\tcommit: boolean,\n\t): DeviceIdentityBindingPreviewRequestV1 | DeviceIdentityBindingCommitRequestV1 | null => {\n\t\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n\t\tconst body = value as Record<string, unknown>;\n\t\tconst allowed = new Set(commit ? [\"bindings\", \"reviewedInventoryDigest\"] : [\"bindings\"]);\n\t\tif (Object.keys(body).some((key) => !allowed.has(key)) || !Array.isArray(body.bindings)) {\n\t\t\treturn null;\n\t\t}\n\t\tconst bindings = body.bindings.map((value) => {\n\t\t\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n\t\t\tconst binding = value as Record<string, unknown>;\n\t\t\tconst bindingKeys = new Set([\"deviceId\", \"targetIdentityId\", \"confirmed\", \"allowRebind\"]);\n\t\t\tif (\n\t\t\t\tObject.keys(binding).some((key) => !bindingKeys.has(key)) ||\n\t\t\t\ttypeof binding.deviceId !== \"string\" ||\n\t\t\t\ttypeof binding.targetIdentityId !== \"string\" ||\n\t\t\t\ttypeof binding.confirmed !== \"boolean\" ||\n\t\t\t\t(Object.hasOwn(binding, \"allowRebind\") && typeof binding.allowRebind !== \"boolean\")\n\t\t\t) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tdeviceId: binding.deviceId,\n\t\t\t\ttargetIdentityId: binding.targetIdentityId,\n\t\t\t\tconfirmed: binding.confirmed,\n\t\t\t\t...(typeof binding.allowRebind === \"boolean\" ? { allowRebind: binding.allowRebind } : {}),\n\t\t\t};\n\t\t});\n\t\tif (bindings.some((binding) => binding == null)) return null;\n\t\tif (commit && typeof body.reviewedInventoryDigest !== \"string\") return null;\n\t\treturn {\n\t\t\tbindings: bindings as DeviceIdentityBindingPreviewRequestV1[\"bindings\"],\n\t\t\t...(commit ? { reviewedInventoryDigest: body.reviewedInventoryDigest as string } : {}),\n\t\t};\n\t};\n\n\tapp.post(\"/api/sync/recipient-policy/v1/device-bindings/preview\", async (c) => {\n\t\tconst body = parseDeviceBindingRequest(await parseViewerJsonBody(c), false);\n\t\tif (!body) return c.json({ error: \"binding_request_invalid\" }, 400);\n\t\tconst store = getStore();\n\t\ttry {\n\t\t\tensureStableStoreIdentity(store);\n\t\t\tconst result = previewDeviceIdentityBindings(\n\t\t\t\tstore.db,\n\t\t\t\tawait localInventoryInput(store),\n\t\t\t\tbody,\n\t\t\t);\n\t\t\tif (result.status === \"invalid\") return c.json(result, 400);\n\t\t\tif (result.status === \"not_found\") return c.json(result, 404);\n\t\t\tif (result.status === \"conflict\") return c.json(result, 409);\n\t\t\treturn c.json(result);\n\t\t} catch (error) {\n\t\t\tif (isSqliteBusy(error)) {\n\t\t\t\tc.header(\"Retry-After\", \"1\");\n\t\t\t\treturn c.json({ error: \"binding_preview_busy\" }, 503);\n\t\t\t}\n\t\t\treturn c.json({ error: \"binding_preview_failed\" }, 500);\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/recipient-policy/v1/device-bindings/commit\", async (c) => {\n\t\tconst body = parseDeviceBindingRequest(await parseViewerJsonBody(c), true);\n\t\tif (!body || !(\"reviewedInventoryDigest\" in body)) {\n\t\t\treturn c.json({ error: \"binding_request_invalid\" }, 400);\n\t\t}\n\t\tconst store = getStore();\n\t\tlet releasePublicationMutation: (() => void) | undefined;\n\t\ttry {\n\t\t\treleasePublicationMutation = await claimRecipientPolicyPublicationMutation(store.db);\n\t\t\tensureStableStoreIdentity(store);\n\t\t\tconst result = commitDeviceIdentityBindings(\n\t\t\t\tstore.db,\n\t\t\t\t{ localActorId: store.actorId, localDeviceId: store.deviceId },\n\t\t\t\tawait localInventoryInput(store),\n\t\t\t\tbody,\n\t\t\t);\n\t\t\tif (result.status === \"invalid\") return c.json(result, 400);\n\t\t\tif (result.status === \"not_found\") return c.json(result, 404);\n\t\t\tif (result.status === \"stale\" || result.status === \"conflict\") {\n\t\t\t\treturn c.json(result, 409);\n\t\t\t}\n\t\t\treturn c.json(result);\n\t\t} catch (error) {\n\t\t\tif (isSqliteBusy(error)) {\n\t\t\t\tc.header(\"Retry-After\", \"1\");\n\t\t\t\treturn c.json({ error: \"binding_commit_busy\" }, 503);\n\t\t\t}\n\t\t\treturn c.json({ error: \"binding_commit_failed\" }, 500);\n\t\t} finally {\n\t\t\treleasePublicationMutation?.();\n\t\t}\n\t});\n\n\t// GET /api/sync/status\n\tapp.get(\"/api/sync/status\", async (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tconst traceSync = <T>(label: string, fn: () => T): T => {\n\t\t\t\tif (process.env.CODEMEM_TRACE_SYNC_STATUS !== \"1\") return fn();\n\t\t\t\tconst startedAt = Date.now();\n\t\t\t\tconsole.warn(`[codemem sync-status] ${label} start`);\n\t\t\t\ttry {\n\t\t\t\t\treturn fn();\n\t\t\t\t} finally {\n\t\t\t\t\tconsole.warn(`[codemem sync-status] ${label} ${Date.now() - startedAt}ms`);\n\t\t\t\t}\n\t\t\t};\n\t\t\tconst showDiag = queryBool(c.req.query(\"includeDiagnostics\"));\n\t\t\tconst includeJoinRequests = queryBool(c.req.query(\"includeJoinRequests\"));\n\t\t\tconst project = c.req.query(\"project\") || null;\n\t\t\tconst config = traceSync(\"readCoordinatorSyncConfig\", () => readCoordinatorSyncConfig());\n\t\t\tconst syncReset = traceSync(\"getSyncResetState\", () => getSyncResetState(store.db));\n\n\t\t\tconst d = drizzle(store.db, { schema });\n\n\t\t\tconst deviceRow = traceSync(\"deviceRow\", () =>\n\t\t\t\td\n\t\t\t\t\t.select({\n\t\t\t\t\t\tdevice_id: schema.syncDevice.device_id,\n\t\t\t\t\t\tfingerprint: schema.syncDevice.fingerprint,\n\t\t\t\t\t})\n\t\t\t\t\t.from(schema.syncDevice)\n\t\t\t\t\t.limit(1)\n\t\t\t\t\t.get(),\n\t\t\t);\n\n\t\t\tconst daemonState = traceSync(\"daemonState\", () =>\n\t\t\t\td.select().from(schema.syncDaemonState).where(eq(schema.syncDaemonState.id, 1)).get(),\n\t\t\t);\n\n\t\t\tconst peerCountRow = traceSync(\"peerCountRow\", () =>\n\t\t\t\td.select({ total: count() }).from(schema.syncPeers).get(),\n\t\t\t);\n\t\t\tlet retentionState:\n\t\t\t\t| {\n\t\t\t\t\t\tlast_run_at?: string | null;\n\t\t\t\t\t\tlast_duration_ms?: number | null;\n\t\t\t\t\t\tlast_deleted_ops?: number | null;\n\t\t\t\t\t\tlast_estimated_bytes_before?: number | null;\n\t\t\t\t\t\tlast_estimated_bytes_after?: number | null;\n\t\t\t\t\t\tretained_floor_cursor?: string | null;\n\t\t\t\t\t\tlast_error?: string | null;\n\t\t\t\t\t\tlast_error_at?: string | null;\n\t\t\t\t }\n\t\t\t\t| undefined;\n\t\t\ttry {\n\t\t\t\tretentionState = traceSync(\"retentionState\", () =>\n\t\t\t\t\td\n\t\t\t\t\t\t.select()\n\t\t\t\t\t\t.from(schema.syncRetentionState)\n\t\t\t\t\t\t.where(eq(schema.syncRetentionState.id, 1))\n\t\t\t\t\t\t.get(),\n\t\t\t\t);\n\t\t\t} catch {\n\t\t\t\tretentionState = undefined;\n\t\t\t}\n\n\t\t\tconst lastSyncRow = traceSync(\"lastSyncRow\", () =>\n\t\t\t\td\n\t\t\t\t\t.select({ last_sync_at: max(schema.syncPeers.last_sync_at) })\n\t\t\t\t\t.from(schema.syncPeers)\n\t\t\t\t\t.get(),\n\t\t\t);\n\t\t\t// Always take the fast COUNT(DISTINCT) path. The slow\n\t\t\t// per-memory vec0 probe blocks the event loop for seconds on\n\t\t\t// larger DBs, which hangs every concurrent request — not\n\t\t\t// acceptable from a status endpoint. See codemem-00jn.\n\t\t\tconst semanticIndex = traceSync(\"semanticIndex\", () =>\n\t\t\t\tredactSemanticIndexDiagnostics(getSemanticIndexDiagnostics(store.db), showDiag),\n\t\t\t);\n\t\t\tconst enrollmentIssueSummary = traceSync(\"coordinatorEnrollmentIssues\", () =>\n\t\t\t\tgetCoordinatorEnrollmentReconciliationIssueSummary(store.db),\n\t\t\t);\n\t\t\tconst enrollmentIssueStatus = {\n\t\t\t\tcounts: enrollmentIssueSummary.counts,\n\t\t\t\t...(showDiag\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tissues: enrollmentIssueSummary.issues.map((issue) => ({\n\t\t\t\t\t\t\t\tcoordinator_id: issue.coordinatorId,\n\t\t\t\t\t\t\t\tgroup_id: issue.groupId,\n\t\t\t\t\t\t\t\tkind: issue.kind,\n\t\t\t\t\t\t\t\treference_id: issue.referenceId,\n\t\t\t\t\t\t\t\tcode: issue.code,\n\t\t\t\t\t\t\t\tstatus: issue.status,\n\t\t\t\t\t\t\t\tfirst_seen_at: issue.firstSeenAt,\n\t\t\t\t\t\t\t\tlast_seen_at: issue.lastSeenAt,\n\t\t\t\t\t\t\t\tresolved_at: issue.resolvedAt,\n\t\t\t\t\t\t\t\toccurrence_count: issue.occurrenceCount,\n\t\t\t\t\t\t\t\tupdated_at: issue.updatedAt,\n\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t};\n\n\t\t\tconst lastError = daemonState?.last_error as string | null;\n\t\t\tconst lastErrorAt = daemonState?.last_error_at as string | null;\n\t\t\tconst lastOkAt = daemonState?.last_ok_at as string | null;\n\t\t\tconst viewerBinding = traceSync(\"readViewerBinding\", () => readViewerBinding(store.dbPath));\n\t\t\t// The sync daemon runs inside the viewer-server process itself, so\n\t\t\t// if this request is being served, the daemon is by definition\n\t\t\t// running — the viewer is serving us right now. The prior\n\t\t\t// `portOpen` self-probe occasionally timed out under GC / socket\n\t\t\t// backlog pressure and mis-reported \"stopped · unreachable\" while\n\t\t\t// every other request kept succeeding. Trust the pidfile's\n\t\t\t// existence (a record was written at startup) and skip the loopback\n\t\t\t// probe.\n\t\t\tconst daemonRunning = Boolean(viewerBinding);\n\t\t\tconst daemonDetail = viewerBinding\n\t\t\t\t? `viewer pidfile at ${viewerBinding.host}:${viewerBinding.port}`\n\t\t\t\t: null;\n\n\t\t\tlet daemonStateValue = \"ok\";\n\t\t\tif (!config.syncEnabled) {\n\t\t\t\tdaemonStateValue = \"disabled\";\n\t\t\t} else if (lastError && (!lastOkAt || String(lastOkAt) < String(lastErrorAt ?? \"\"))) {\n\t\t\t\tdaemonStateValue = \"error\";\n\t\t\t} else if (!daemonRunning) {\n\t\t\t\tdaemonStateValue = \"stopped\";\n\t\t\t}\n\n\t\t\tconst statusPayload: Record<string, unknown> = {\n\t\t\t\tenabled: config.syncEnabled,\n\t\t\t\tinterval_s: config.syncIntervalS,\n\t\t\t\tretention: {\n\t\t\t\t\tenabled: config.syncRetentionEnabled,\n\t\t\t\t\tmax_age_days: config.syncRetentionMaxAgeDays,\n\t\t\t\t\tmax_size_mb: config.syncRetentionMaxSizeMb,\n\t\t\t\t\tretained_floor_cursor:\n\t\t\t\t\t\tsyncReset.retained_floor_cursor ??\n\t\t\t\t\t\t(retentionState?.retained_floor_cursor as string | null) ??\n\t\t\t\t\t\tnull,\n\t\t\t\t\tlast_run_at: (retentionState?.last_run_at as string | null) ?? null,\n\t\t\t\t\tlast_duration_ms:\n\t\t\t\t\t\ttypeof retentionState?.last_duration_ms === \"number\"\n\t\t\t\t\t\t\t? retentionState.last_duration_ms\n\t\t\t\t\t\t\t: null,\n\t\t\t\t\tlast_deleted_ops:\n\t\t\t\t\t\ttypeof retentionState?.last_deleted_ops === \"number\"\n\t\t\t\t\t\t\t? retentionState.last_deleted_ops\n\t\t\t\t\t\t\t: null,\n\t\t\t\t\tlast_estimated_bytes_before:\n\t\t\t\t\t\ttypeof retentionState?.last_estimated_bytes_before === \"number\"\n\t\t\t\t\t\t\t? retentionState.last_estimated_bytes_before\n\t\t\t\t\t\t\t: null,\n\t\t\t\t\tlast_estimated_bytes_after:\n\t\t\t\t\t\ttypeof retentionState?.last_estimated_bytes_after === \"number\"\n\t\t\t\t\t\t\t? retentionState.last_estimated_bytes_after\n\t\t\t\t\t\t\t: null,\n\t\t\t\t\tlast_error: (retentionState?.last_error as string | null) ?? null,\n\t\t\t\t\tlast_error_at: (retentionState?.last_error_at as string | null) ?? null,\n\t\t\t\t},\n\t\t\t\tsemantic_index: semanticIndex,\n\t\t\t\tcoordinator_enrollment_reconciliation_issues: enrollmentIssueStatus,\n\t\t\t\tpeer_count: Number(peerCountRow?.total ?? 0),\n\t\t\t\tlast_sync_at: lastSyncRow?.last_sync_at ?? null,\n\t\t\t\tdaemon_state: daemonStateValue,\n\t\t\t\tdaemon_running: daemonRunning,\n\t\t\t\tdaemon_detail: daemonDetail,\n\t\t\t\tproject_filter_active:\n\t\t\t\t\tconfig.syncProjectsInclude.length > 0 || config.syncProjectsExclude.length > 0,\n\t\t\t\tproject_filter: {\n\t\t\t\t\tinclude: config.syncProjectsInclude,\n\t\t\t\t\texclude: config.syncProjectsExclude,\n\t\t\t\t},\n\t\t\t\tcleanup_diagnostics: cleanupDiagnostics(\n\t\t\t\t\tstore,\n\t\t\t\t\t(deviceRow?.device_id as string | null | undefined) ?? null,\n\t\t\t\t\tshowDiag,\n\t\t\t\t),\n\t\t\t\tredacted: !showDiag,\n\t\t\t};\n\n\t\t\tif (showDiag) {\n\t\t\t\tstatusPayload.device_id = deviceRow?.device_id ?? null;\n\t\t\t\tstatusPayload.fingerprint = deviceRow?.fingerprint ?? null;\n\t\t\t\tstatusPayload.bind = `${config.syncHost}:${config.syncPort}`;\n\t\t\t\tstatusPayload.daemon_last_error = lastError;\n\t\t\t\tstatusPayload.daemon_last_error_at = lastErrorAt;\n\t\t\t\tstatusPayload.daemon_last_ok_at = lastOkAt;\n\t\t\t}\n\n\t\t\tconst runtimeStatus = getSyncRuntimeStatus?.() ?? null;\n\t\t\tif (runtimeStatus?.phase && runtimeStatus.phase !== \"running\") {\n\t\t\t\tdaemonStateValue = runtimeStatus.phase;\n\t\t\t\tstatusPayload.daemon_state = daemonStateValue;\n\t\t\t\tstatusPayload.daemon_running = runtimeStatus.phase === \"starting\" || daemonRunning;\n\t\t\t\tstatusPayload.daemon_detail = runtimeStatus.detail ?? daemonDetail;\n\t\t\t}\n\n\t\t\tconst coordinatorSnapshot = await coordinatorStatusSnapshot(store, config);\n\t\t\tconst coordinator = traceSync(\"coordinator\", () =>\n\t\t\t\tredactCoordinatorStatus(coordinatorSnapshot, showDiag),\n\t\t\t);\n\n\t\t\t// Build peers list using deduplicated mapPeerRow\n\t\t\tconst peerRows = traceSync(\n\t\t\t\t\"peerRows\",\n\t\t\t\t() => store.db.prepare(PEERS_QUERY).all() as Record<string, unknown>[],\n\t\t\t);\n\t\t\tconst recentOpsByPeer = traceSync(\"recentPeerOps\", () => recentPeerOps(store));\n\t\t\tconst scopeRejectionsByPeer = traceSync(\"recentScopeRejectionsByPeer\", () =>\n\t\t\t\trecentScopeRejectionsByPeer(store),\n\t\t\t);\n\t\t\tconst peersItems = peerRows.map((row) => {\n\t\t\t\tconst peer = mapPeerRow(\n\t\t\t\t\tstore,\n\t\t\t\t\trow,\n\t\t\t\t\tshowDiag,\n\t\t\t\t\trecentOpsByPeer,\n\t\t\t\t\tscopeRejectionsByPeer,\n\t\t\t\t\t(deviceRow?.device_id as string | null | undefined) ?? null,\n\t\t\t\t);\n\t\t\t\tpeer.status = peerStatus(peer);\n\t\t\t\treturn peer;\n\t\t\t});\n\n\t\t\tconst peersMap: Record<string, unknown> = {};\n\t\t\tfor (const peer of peersItems) {\n\t\t\t\tpeersMap[String(peer.peer_device_id)] = peer.status;\n\t\t\t}\n\n\t\t\t// Attempts\n\t\t\tconst attemptRows = traceSync(\"attemptRows\", () =>\n\t\t\t\td\n\t\t\t\t\t.select({\n\t\t\t\t\t\tpeer_device_id: schema.syncAttempts.peer_device_id,\n\t\t\t\t\t\tok: schema.syncAttempts.ok,\n\t\t\t\t\t\terror: schema.syncAttempts.error,\n\t\t\t\t\t\tstarted_at: schema.syncAttempts.started_at,\n\t\t\t\t\t\tfinished_at: schema.syncAttempts.finished_at,\n\t\t\t\t\t\tops_in: schema.syncAttempts.ops_in,\n\t\t\t\t\t\tops_out: schema.syncAttempts.ops_out,\n\t\t\t\t\t\tlocal_sync_capability: schema.syncAttempts.local_sync_capability,\n\t\t\t\t\t\tpeer_sync_capability: schema.syncAttempts.peer_sync_capability,\n\t\t\t\t\t\tnegotiated_sync_capability: schema.syncAttempts.negotiated_sync_capability,\n\t\t\t\t\t})\n\t\t\t\t\t.from(schema.syncAttempts)\n\t\t\t\t\t.orderBy(desc(schema.syncAttempts.finished_at))\n\t\t\t\t\t.limit(25)\n\t\t\t\t\t.all(),\n\t\t\t);\n\t\t\tconst peerAddressMap = new Map<string, string[]>();\n\t\t\tconst peerAddressRows = traceSync(\n\t\t\t\t\"peerAddressRows\",\n\t\t\t\t() =>\n\t\t\t\t\tstore.db.prepare(\"SELECT peer_device_id, addresses_json FROM sync_peers\").all() as Array<{\n\t\t\t\t\t\tpeer_device_id: string | null;\n\t\t\t\t\t\taddresses_json: string | null;\n\t\t\t\t\t}>,\n\t\t\t);\n\t\t\tpeerAddressRows.forEach((peerRow) => {\n\t\t\t\tconst addrs = safeJsonList(peerRow.addresses_json as string | null);\n\t\t\t\tif (addrs.length) peerAddressMap.set(String(peerRow.peer_device_id ?? \"\"), addrs);\n\t\t\t});\n\t\t\tconst attemptsItems = attemptRows.map((row) => {\n\t\t\t\tconst addrs = showDiag ? peerAddressMap.get(String(row.peer_device_id ?? \"\")) : undefined;\n\t\t\t\treturn mapSyncAttemptRow(row, showDiag, addrs);\n\t\t\t});\n\t\t\tconst latestAttemptError = String(attemptRows[0]?.error || \"\").trim();\n\n\t\t\tconst statusBlock: Record<string, unknown> = {\n\t\t\t\t...statusPayload,\n\t\t\t\tbackground_maintenance: summarizeMaintenanceJobs(listMaintenanceJobs(store.db), showDiag),\n\t\t\t\tpeers: peersMap,\n\t\t\t\tpending: 0,\n\t\t\t\tsync: {},\n\t\t\t\tping: {},\n\t\t\t};\n\t\t\tconst legacyDevices = traceSync(\"legacyDevices\", () => store.claimableLegacyDeviceIds());\n\t\t\tconst legacyReview = traceSync(\"legacySharedReview\", () => legacySharedReviewSummary(store));\n\t\t\tconst sharingReview = traceSync(\"sharingReview\", () => store.sharingReviewSummary(project));\n\t\t\tconst recipientPolicyReconciliation = traceSync(\"recipientPolicyReconciliation\", () =>\n\t\t\t\tlistRecipientPolicyReconciliationStatus(store),\n\t\t\t);\n\t\t\tlet joinRequests: Record<string, unknown>[] = [];\n\t\t\tif (includeJoinRequests && showDiag && config.syncCoordinatorAdminSecret) {\n\t\t\t\ttry {\n\t\t\t\t\tjoinRequests = await listCoordinatorJoinRequests(config);\n\t\t\t\t} catch {\n\t\t\t\t\tjoinRequests = [];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (daemonStateValue === \"ok\" && latestAttemptError.startsWith(\"needs_attention:\")) {\n\t\t\t\tdaemonStateValue = \"needs_attention\";\n\t\t\t\tstatusPayload.daemon_state = daemonStateValue;\n\t\t\t\tstatusPayload.daemon_detail = latestAttemptError.replace(/^needs_attention:/, \"\");\n\t\t\t\tstatusBlock.daemon_state = daemonStateValue;\n\t\t\t\tstatusBlock.daemon_detail = latestAttemptError.replace(/^needs_attention:/, \"\");\n\t\t\t}\n\n\t\t\tif (daemonStateValue === \"ok\") {\n\t\t\t\tconst peerStates = new Set(\n\t\t\t\t\tpeersItems.map((peer) =>\n\t\t\t\t\t\tString((peer.status as Record<string, unknown> | undefined)?.peer_state ?? \"\"),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tconst latestFailedRecently = Boolean(\n\t\t\t\t\tattemptsItems[0] &&\n\t\t\t\t\t\tattemptsItems[0].status === \"error\" &&\n\t\t\t\t\t\tisRecentIso(attemptsItems[0].finished_at),\n\t\t\t\t);\n\t\t\t\tconst allOffline =\n\t\t\t\t\tpeersItems.length > 0 &&\n\t\t\t\t\tpeersItems.every(\n\t\t\t\t\t\t(peer) =>\n\t\t\t\t\t\t\tString((peer.status as Record<string, unknown>)?.peer_state ?? \"\") === \"offline\",\n\t\t\t\t\t);\n\t\t\t\tif (latestFailedRecently) {\n\t\t\t\t\tconst hasLivePeer = peerStates.has(\"online\") || peerStates.has(\"degraded\");\n\t\t\t\t\tif (hasLivePeer) daemonStateValue = \"degraded\";\n\t\t\t\t\telse if (allOffline) daemonStateValue = \"offline-peers\";\n\t\t\t\t\telse if (peersItems.length > 0) daemonStateValue = \"stale\";\n\t\t\t\t} else if (peerStates.has(\"degraded\")) {\n\t\t\t\t\tdaemonStateValue = \"degraded\";\n\t\t\t\t} else if (allOffline) {\n\t\t\t\t\tdaemonStateValue = \"offline-peers\";\n\t\t\t\t} else if (peersItems.length > 0 && !peerStates.has(\"online\")) {\n\t\t\t\t\tdaemonStateValue = \"stale\";\n\t\t\t\t}\n\t\t\t\tstatusPayload.daemon_state = daemonStateValue;\n\t\t\t\tstatusBlock.daemon_state = daemonStateValue;\n\t\t\t}\n\n\t\t\tconst responsePayload: Record<string, unknown> = {\n\t\t\t\t...statusPayload,\n\t\t\t\tstatus: statusBlock,\n\t\t\t\tpeers: peersItems,\n\t\t\t\tattempts: attemptsItems.slice(0, 5),\n\t\t\t\tlegacy_devices: legacyDevices,\n\t\t\t\tlegacy_shared_review: legacyReview,\n\t\t\t\tsharing_review: sharingReview,\n\t\t\t\trecipient_policy_reconciliation: recipientPolicyReconciliation,\n\t\t\t\tcoordinator,\n\t\t\t};\n\t\t\tif (includeJoinRequests && showDiag) {\n\t\t\t\tresponsePayload.join_requests = joinRequests;\n\t\t\t}\n\t\t\treturn c.json(responsePayload);\n\t\t}\n\t});\n\n\t// GET /api/sync/peers\n\tapp.get(\"/api/sync/peers\", (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tconst showDiag = queryBool(c.req.query(\"includeDiagnostics\"));\n\t\t\tconst rows = store.db.prepare(PEERS_QUERY).all() as Record<string, unknown>[];\n\t\t\tconst recentOpsByPeer = recentPeerOps(store);\n\t\t\tconst scopeRejectionsByPeer = recentScopeRejectionsByPeer(store);\n\t\t\tconst d = drizzle(store.db, { schema });\n\t\t\tconst deviceRow = d\n\t\t\t\t.select({ device_id: schema.syncDevice.device_id })\n\t\t\t\t.from(schema.syncDevice)\n\t\t\t\t.limit(1)\n\t\t\t\t.get();\n\t\t\tconst localDeviceId = (deviceRow?.device_id as string | null | undefined) ?? null;\n\t\t\t// Use deduplicated mapPeerRow helper (fix #4)\n\t\t\tconst peers = rows.map((row) =>\n\t\t\t\tmapPeerRow(store, row, showDiag, recentOpsByPeer, scopeRejectionsByPeer, localDeviceId),\n\t\t\t);\n\t\t\treturn c.json({ items: peers, redacted: !showDiag });\n\t\t}\n\t});\n\n\t// GET /api/sync/peers/:peer_device_id/scope-rejections\n\t//\n\t// Recent scope-rejection records produced by the inbound fail-closed gate.\n\t// Each row is metadata only — op id, entity ref, scope id, reason code,\n\t// timestamp. The rejection log never stores op payloads, so this endpoint\n\t// can never leak inbound payload contents regardless of diagnostics state.\n\tapp.get(\"/api/sync/peers/:peer_device_id/scope-rejections\", (c) => {\n\t\tconst store = getStore();\n\t\tconst peerDeviceId = String(c.req.param(\"peer_device_id\") || \"\").trim();\n\t\tif (!peerDeviceId) return c.json({ error: \"missing_peer_device_id\" }, 400);\n\t\tconst limit = queryInt(c.req.query(\"limit\"), 100);\n\t\tif (limit <= 0) return c.json({ error: \"invalid_limit\" }, 400);\n\t\tconst sinceMinutesRaw = queryInt(c.req.query(\"sinceMinutes\"), 24 * 60);\n\t\t// Cap at ~10 years so a hostile or fat-fingered query cannot push the\n\t\t// computed timestamp past the Date range and turn toISOString() into\n\t\t// a 500. Anything older than 10 years is effectively \"all rejections\".\n\t\tconst SINCE_MINUTES_MAX = 10 * 365 * 24 * 60;\n\t\tconst sinceMinutes = Math.min(Math.max(sinceMinutesRaw, 0), SINCE_MINUTES_MAX);\n\t\tconst sinceIso =\n\t\t\tsinceMinutes > 0 ? new Date(Date.now() - sinceMinutes * 60_000).toISOString() : undefined;\n\t\tconst records = listInboundScopeRejections(store.db, {\n\t\t\tpeerDeviceId,\n\t\t\tsinceIso,\n\t\t\tlimit,\n\t\t});\n\t\tconst summaries = summarizeInboundScopeRejections(store.db, {\n\t\t\tpeerDeviceId,\n\t\t\tsinceIso,\n\t\t});\n\t\tconst summary = summaries[0] ?? {\n\t\t\tpeer_device_id: peerDeviceId,\n\t\t\ttotal: 0,\n\t\t\tby_reason: {},\n\t\t\tlast_at: null,\n\t\t};\n\t\treturn c.json({\n\t\t\tpeer_device_id: peerDeviceId,\n\t\t\tsummary,\n\t\t\titems: records,\n\t\t});\n\t});\n\n\t// GET /api/sync/actors\n\tapp.get(\"/api/sync/actors\", (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tensureLocalActorRecord(store);\n\t\t\tconst d = drizzle(store.db, { schema });\n\t\t\tconst includeMerged = queryBool(c.req.query(\"includeMerged\"));\n\t\t\tconst query = d.select().from(schema.actors);\n\t\t\tconst rows = includeMerged\n\t\t\t\t? query.orderBy(schema.actors.display_name).all()\n\t\t\t\t: query\n\t\t\t\t\t\t.where(and(ne(schema.actors.status, \"merged\"), ne(schema.actors.status, \"deactivated\")))\n\t\t\t\t\t\t.orderBy(schema.actors.display_name)\n\t\t\t\t\t\t.all();\n\t\t\treturn c.json({ items: rows });\n\t\t}\n\t});\n\n\t// GET /api/sync/attempts\n\tapp.get(\"/api/sync/attempts\", (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tconst d = drizzle(store.db, { schema });\n\t\t\tlet limit = queryInt(c.req.query(\"limit\"), 25);\n\t\t\tif (limit <= 0) return c.json({ error: \"invalid_limit\" }, 400);\n\t\t\tlimit = Math.min(limit, 500);\n\t\t\tconst rows = d\n\t\t\t\t.select({\n\t\t\t\t\tpeer_device_id: schema.syncAttempts.peer_device_id,\n\t\t\t\t\tok: schema.syncAttempts.ok,\n\t\t\t\t\terror: schema.syncAttempts.error,\n\t\t\t\t\tstarted_at: schema.syncAttempts.started_at,\n\t\t\t\t\tfinished_at: schema.syncAttempts.finished_at,\n\t\t\t\t\tops_in: schema.syncAttempts.ops_in,\n\t\t\t\t\tops_out: schema.syncAttempts.ops_out,\n\t\t\t\t\tlocal_sync_capability: schema.syncAttempts.local_sync_capability,\n\t\t\t\t\tpeer_sync_capability: schema.syncAttempts.peer_sync_capability,\n\t\t\t\t\tnegotiated_sync_capability: schema.syncAttempts.negotiated_sync_capability,\n\t\t\t\t})\n\t\t\t\t.from(schema.syncAttempts)\n\t\t\t\t.orderBy(desc(schema.syncAttempts.finished_at))\n\t\t\t\t.limit(limit)\n\t\t\t\t.all();\n\t\t\tconst showDiag = queryBool(c.req.query(\"includeDiagnostics\"));\n\t\t\tconst items = rows.map((row) => mapSyncAttemptRow(row, showDiag));\n\t\t\treturn c.json({ items, redacted: !showDiag });\n\t\t}\n\t});\n\n\t// GET /api/sync/pairing — uses ensureDeviceIdentity from core (fix #5 context)\n\t//\n\t// The pairing payload is not redacted by the generic diagnostics toggle:\n\t// it is the actual command the user shares with their own other devices,\n\t// and the UI already hides it inside a \"Show pairing command\" disclosure\n\t// that they explicitly open. Redacting the payload here broke the\n\t// happy-path pairing flow because the UI had nothing to render as the\n\t// command when diagnostics were off.\n\tapp.get(\"/api/sync/pairing\", (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tconst config = readCoordinatorSyncConfig();\n\t\t\tconst d = drizzle(store.db, { schema });\n\t\t\tlet deviceId: string | undefined;\n\t\t\tlet publicKey: string | undefined;\n\t\t\tlet fingerprint: string | undefined;\n\n\t\t\ttry {\n\t\t\t\tconst [id, fp] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });\n\t\t\t\tdeviceId = id;\n\t\t\t\tfingerprint = fp;\n\t\t\t\tconst row = d\n\t\t\t\t\t.select({ public_key: schema.syncDevice.public_key })\n\t\t\t\t\t.from(schema.syncDevice)\n\t\t\t\t\t.where(eq(schema.syncDevice.device_id, id))\n\t\t\t\t\t.get();\n\t\t\t\tpublicKey = row?.public_key ?? \"\";\n\t\t\t} catch {\n\t\t\t\treturn c.json({ error: \"device identity unavailable\" }, 500);\n\t\t\t}\n\n\t\t\tif (!deviceId || !fingerprint) {\n\t\t\t\treturn c.json({ error: \"public key missing\" }, 500);\n\t\t\t}\n\n\t\t\treturn c.json({\n\t\t\t\tdevice_id: deviceId,\n\t\t\t\tfingerprint,\n\t\t\t\tpublic_key: publicKey ?? null,\n\t\t\t\tpairing_filter_hint: PAIRING_FILTER_HINT,\n\t\t\t\taddresses: pairingAdvertiseAddresses(config),\n\t\t\t});\n\t\t}\n\t});\n\n\t// ------------------------------------------------------------------\n\t// POST mutations\n\t// ------------------------------------------------------------------\n\n\t// POST /api/sync/peers/rename\n\tapp.post(\"/api/sync/peers/rename\", async (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tconst d = drizzle(store.db, { schema });\n\t\t\tlet body: Record<string, unknown>;\n\t\t\ttry {\n\t\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t\t} catch {\n\t\t\t\treturn c.json({ error: \"invalid json\" }, 400);\n\t\t\t}\n\t\t\tconst peerDeviceId = String(body.peer_device_id ?? \"\").trim();\n\t\t\tconst rawName = String(body.name ?? \"\");\n\t\t\tif (!peerDeviceId) return c.json({ error: \"peer_device_id required\" }, 400);\n\t\t\tif (!rawName.trim()) return c.json({ error: \"name required\" }, 400);\n\t\t\tlet name: string;\n\t\t\ttry {\n\t\t\t\tname = normalizeHumanPresentationName(rawName, \"name\");\n\t\t\t} catch (error) {\n\t\t\t\treturn c.json({ error: error instanceof Error ? error.message : \"name_invalid\" }, 400);\n\t\t\t}\n\t\t\tconst exists = d\n\t\t\t\t.select({ peer_device_id: schema.syncPeers.peer_device_id })\n\t\t\t\t.from(schema.syncPeers)\n\t\t\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t\t\t.get();\n\t\t\tif (!exists) return c.json({ error: \"peer not found\" }, 404);\n\t\t\td.update(schema.syncPeers)\n\t\t\t\t.set({ name })\n\t\t\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t\t\t.run();\n\t\t\treturn c.json({ ok: true });\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/run\", async (c) => {\n\t\tconst store = getStore();\n\t\tlet body: Record<string, unknown> = {};\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\tbody = {};\n\t\t}\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tif (!config.syncEnabled) {\n\t\t\treturn c.json({ error: \"sync_disabled\" }, 403);\n\t\t}\n\t\tconst address =\n\t\t\ttypeof body.address === \"string\" && body.address.trim() ? body.address.trim() : null;\n\t\tconst requestedPeerId =\n\t\t\ttypeof body.peer_device_id === \"string\" && body.peer_device_id.trim()\n\t\t\t\t? body.peer_device_id.trim()\n\t\t\t\t: null;\n\t\tlet peerIds: string[];\n\t\tif (address) {\n\t\t\tconst peerId = findPeerDeviceIdForAddress(store, address);\n\t\t\tif (!peerId) return c.json({ error: \"unknown peer address\" }, 404);\n\t\t\tpeerIds = [peerId];\n\t\t} else if (requestedPeerId) {\n\t\t\tconst requestedPeerRows = store.db\n\t\t\t\t.prepare(\"SELECT peer_device_id FROM sync_peers WHERE peer_device_id = ?\")\n\t\t\t\t.all(requestedPeerId) as Array<{ peer_device_id: string | null }>;\n\t\t\tpeerIds = requestedPeerRows\n\t\t\t\t.map((row) => String(row.peer_device_id ?? \"\").trim())\n\t\t\t\t.filter(Boolean);\n\t\t} else {\n\t\t\tconst allPeerRows = store.db.prepare(\"SELECT peer_device_id FROM sync_peers\").all() as Array<{\n\t\t\t\tpeer_device_id: string | null;\n\t\t\t}>;\n\t\t\tpeerIds = allPeerRows.map((row) => String(row.peer_device_id ?? \"\").trim()).filter(Boolean);\n\t\t}\n\t\tconst items = [] as Array<Record<string, unknown>>;\n\t\tfor (const peerId of peerIds) {\n\t\t\t// keysDir must match the sync daemon's key material — omitting it made\n\t\t\t// this route sign with a different device key whenever CODEMEM_KEYS_DIR\n\t\t\t// was set, so manual sync runs failed peer auth while daemon syncs worked.\n\t\t\tconst result = await runSyncPass(store.db, peerId, {\n\t\t\t\tkeysDir: syncKeysDir(),\n\t\t\t\tdbPath: store.dbPath,\n\t\t\t\tscanner: store.scanner,\n\t\t\t});\n\t\t\titems.push({\n\t\t\t\tpeer_device_id: peerId,\n\t\t\t\t...result,\n\t\t\t\tskippedOut: undefined,\n\t\t\t\tskipped_out: safeSkippedSyncDetail(result.skippedOut),\n\t\t\t});\n\t\t}\n\t\treturn c.json({ items });\n\t});\n\n\tapp.post(\"/api/sync/peers/scope\", async (c) => {\n\t\tconst store = getStore();\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\" }, 400);\n\t\t}\n\t\tconst peerDeviceId = String(body.peer_device_id ?? \"\").trim();\n\t\tif (!peerDeviceId) return c.json({ error: \"peer_device_id required\" }, 400);\n\t\tconst include = Array.isArray(body.include)\n\t\t\t? body.include\n\t\t\t\t\t.filter((value): value is string => typeof value === \"string\")\n\t\t\t\t\t.map((value) => value.trim())\n\t\t\t\t\t.filter(Boolean)\n\t\t\t: null;\n\t\tconst exclude = Array.isArray(body.exclude)\n\t\t\t? body.exclude\n\t\t\t\t\t.filter((value): value is string => typeof value === \"string\")\n\t\t\t\t\t.map((value) => value.trim())\n\t\t\t\t\t.filter(Boolean)\n\t\t\t: null;\n\t\tconst inheritGlobal = Boolean(body.inherit_global);\n\t\tconst d = drizzle(store.db, { schema });\n\t\tconst exists = d\n\t\t\t.select({ peer_device_id: schema.syncPeers.peer_device_id })\n\t\t\t.from(schema.syncPeers)\n\t\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t\t.get();\n\t\tif (!exists) return c.json({ error: \"peer not found\" }, 404);\n\t\td.update(schema.syncPeers)\n\t\t\t.set({\n\t\t\t\tprojects_include_json: inheritGlobal ? null : JSON.stringify(include ?? []),\n\t\t\t\tprojects_exclude_json: inheritGlobal ? null : JSON.stringify(exclude ?? []),\n\t\t\t})\n\t\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t\t.run();\n\t\tconst row = d\n\t\t\t.select({\n\t\t\t\tprojects_include_json: schema.syncPeers.projects_include_json,\n\t\t\t\tprojects_exclude_json: schema.syncPeers.projects_exclude_json,\n\t\t\t})\n\t\t\t.from(schema.syncPeers)\n\t\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t\t.get() as Record<string, unknown> | undefined;\n\t\tif (!row) return c.json({ error: \"peer not found\" }, 404);\n\t\treturn c.json({\n\t\t\tok: true,\n\t\t\tproject_scope: currentProjectScope(row, readPeerProjectFilters(store, peerDeviceId)),\n\t\t});\n\t});\n\n\tapp.get(\"/api/sync/sharing-domains/settings\", (c) => {\n\t\tconst store = getStore();\n\t\tconst limit = Math.max(1, queryInt(c.req.query(\"limit\"), 250));\n\t\treturn c.json({\n\t\t\tscopes: listSharingDomainSettingsScopes(store.db),\n\t\t\tmappings: listProjectScopeSettingsMappings(store.db),\n\t\t\tprojects: listProjectScopeCandidates(store.db, { limit }),\n\t\t\tlocal_default_scope_id: LOCAL_DEFAULT_SCOPE_ID,\n\t\t});\n\t});\n\n\tapp.get(\"/api/sync/recipient-policy/v1/projection\", (c) => {\n\t\tconst store = getStore();\n\t\treturn c.json(\n\t\t\tlistLegacyRecipientPolicyProjections(store.db, {\n\t\t\t\tlocalActorId: store.actorId,\n\t\t\t\tlocalDeviceId: store.deviceId,\n\t\t\t}),\n\t\t);\n\t});\n\n\tapp.get(\"/api/sync/recipient-policy/v1/review\", (c) => {\n\t\tconst store = getStore();\n\t\tensureLocalActorRecord(store);\n\t\treturn c.json(\n\t\t\tlistRecipientPolicyReview(store.db, {\n\t\t\t\tlocalActorId: store.actorId,\n\t\t\t\tlocalDeviceId: store.deviceId,\n\t\t\t}),\n\t\t);\n\t});\n\n\tapp.get(\"/api/sync/recipient-policy/v1/intent\", (c) => {\n\t\tconst store = getStore();\n\t\treturn c.json(listRecipientPolicyIntent(store.db));\n\t});\n\n\tapp.get(\"/api/sync/recipient-policy/v1/reconciliation-status\", (c) => {\n\t\treturn c.json(listRecipientPolicyReconciliationStatus(getStore()));\n\t});\n\n\tapp.post(\"/api/sync/recipient-policy/v1/edges/preview\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst body = await parseViewerJsonBody(c);\n\t\ttry {\n\t\t\treturn c.json(previewRecipientPolicyEdges(store.db, body));\n\t\t} catch (error) {\n\t\t\tif (error instanceof RecipientPolicyEdgeRequestError) {\n\t\t\t\tif (error.status === \"not_found\") {\n\t\t\t\t\treturn c.json({ error: error.errorCode }, 404);\n\t\t\t\t}\n\t\t\t\treturn c.json({ error: error.errorCode }, 400);\n\t\t\t}\n\t\t\tif (isSqliteBusy(error)) {\n\t\t\t\tc.header(\"Retry-After\", \"1\");\n\t\t\t\treturn c.json({ error: \"edge_preview_busy\" }, 503);\n\t\t\t}\n\t\t\treturn c.json({ error: \"edge_preview_failed\" }, 500);\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/recipient-policy/v1/edges/commit\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst body = await parseViewerJsonBody(c);\n\t\ttry {\n\t\t\tconst request = parseRecipientPolicyEdgeCommitRequest(body);\n\t\t\t// Acquire every affected Team queue in one stable order. Finish publication\n\t\t\t// uses the same Team boundary, so its reviewed snapshot cannot race a\n\t\t\t// successful user recipient commit.\n\t\t\tconst teamIds = request\n\t\t\t\t? [\n\t\t\t\t\t\t...new Set(\n\t\t\t\t\t\t\trequest.changes.flatMap((change) =>\n\t\t\t\t\t\t\t\tchange.recipient.recipientKind === \"team\" ? [change.recipient.teamId] : [],\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t),\n\t\t\t\t\t].toSorted()\n\t\t\t\t: [];\n\t\t\tconst commit = async (\n\t\t\t\tindex: number,\n\t\t\t): Promise<ReturnType<typeof commitRecipientPolicyEdges>> => {\n\t\t\t\tconst teamId = teamIds[index];\n\t\t\t\tif (!teamId) return commitRecipientPolicyEdges(store.db, request ?? body);\n\t\t\t\treturn serializeRecipientPolicyTeamMutation(store.db, teamId, () => commit(index + 1));\n\t\t\t};\n\t\t\tconst result = await commit(0);\n\t\t\tif (result.status === \"invalid\") return c.json(result, 400);\n\t\t\tif (result.status === \"not_found\") return c.json(result, 404);\n\t\t\tif (result.status === \"stale\" || result.status === \"conflict\") {\n\t\t\t\treturn c.json(result, 409);\n\t\t\t}\n\t\t\treturn c.json(result);\n\t\t} catch (error) {\n\t\t\tif (isSqliteBusy(error)) {\n\t\t\t\tc.header(\"Retry-After\", \"1\");\n\t\t\t\treturn c.json({ error: \"edge_commit_busy\" }, 503);\n\t\t\t}\n\t\t\treturn c.json(\n\t\t\t\t{\n\t\t\t\t\tversion: 1,\n\t\t\t\t\tstatus: \"conflict\",\n\t\t\t\t\treviewedPolicyDigest: \"\",\n\t\t\t\t\terrorCode: \"edge_commit_conflict\",\n\t\t\t\t\toutcomes: [],\n\t\t\t\t\twriteCount: 0,\n\t\t\t\t\tidempotent: false,\n\t\t\t\t},\n\t\t\t\t409,\n\t\t\t);\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/recipient-policy/v1/invites/preview\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst body = await parseViewerJsonBody(c);\n\t\tif (!body) return c.json({ error: \"request_invalid\" }, 400);\n\t\ttry {\n\t\t\tconst kind = recipientInviteKind(body.kind ?? body.invite_kind);\n\t\t\tconst config = readCoordinatorSyncConfig();\n\t\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\t\tconst unavailable = recipientInviteCreationUnavailable(status, kind);\n\t\t\tif (unavailable) return c.json(unavailable.body, unavailable.httpStatus);\n\t\t\tconst targetId =\n\t\t\t\tkind === \"team_member\"\n\t\t\t\t\t? optionalViewerStrictString(body, \"policy_team_id\")\n\t\t\t\t\t: optionalViewerStrictString(body, \"target_identity_id\");\n\t\t\tif (!targetId) throw new Error(\"recipient_invite_metadata_invalid\");\n\t\t\tif (kind === \"add_device\" && targetId !== store.actorId) {\n\t\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t\t}\n\t\t\tconst preview = recipientInviteOnboardingPreview(\n\t\t\t\tstore,\n\t\t\t\tbody,\n\t\t\t\trecipientInvitePreviewId(kind, targetId),\n\t\t\t);\n\t\t\treturn c.json({ kind, preview });\n\t\t} catch (error) {\n\t\t\treturn c.json(\n\t\t\t\t{ error: error instanceof Error ? error.message : \"recipient_invite_invalid\" },\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/recipient-policy/v1/invites\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst body = await parseViewerJsonBody(c);\n\t\tif (!body) return c.json({ error: \"request_invalid\" }, 400);\n\t\ttry {\n\t\t\tconst kind = recipientInviteKind(body.kind ?? body.invite_kind);\n\t\t\tconst config = readCoordinatorSyncConfig();\n\t\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\t\tconst unavailable = recipientInviteCreationUnavailable(status, kind);\n\t\t\tif (unavailable) return c.json(unavailable.body, unavailable.httpStatus);\n\t\t\tconst targetId =\n\t\t\t\tkind === \"team_member\"\n\t\t\t\t\t? optionalViewerStrictString(body, \"policy_team_id\")\n\t\t\t\t\t: optionalViewerStrictString(body, \"target_identity_id\");\n\t\t\tif (!targetId) throw new Error(\"recipient_invite_metadata_invalid\");\n\t\t\tif (kind === \"add_device\" && targetId !== store.actorId) {\n\t\t\t\tthrow new Error(\"invite_identity_conflict\");\n\t\t\t}\n\t\t\tconst preview = recipientInviteOnboardingPreview(\n\t\t\t\tstore,\n\t\t\t\tbody,\n\t\t\t\trecipientInvitePreviewId(kind, targetId),\n\t\t\t);\n\t\t\tconst reviewedDigest = optionalViewerStrictString(body, \"reviewed_onboarding_digest\");\n\t\t\tif (!reviewedDigest) throw new Error(\"reviewed_onboarding_digest_required\");\n\t\t\tif (reviewedDigest !== preview.reviewedOnboardingDigest) {\n\t\t\t\treturn c.json({ error: \"reviewed_onboarding_stale\", preview }, 409);\n\t\t\t}\n\t\t\tconst reviewedIntent = recipientInviteReviewedIntent(store, kind, targetId, preview);\n\t\t\tconst reviewedPreviewDigest = await recipientReviewedIntentDigest(reviewedIntent);\n\t\t\tconst groupId = resolveCoordinatorAdminGroup(optionalViewerString(body, \"group_id\"), status);\n\t\t\tconst ttlHours = parseInviteTtlHours(body.ttl_hours);\n\t\t\tif (!groupId) throw new Error(\"group_id_required\");\n\t\t\tif (ttlHours == null) throw new Error(\"ttl_hours_invalid\");\n\t\t\t// Initial owner enrollments intentionally remain Identity-unbound, so an explicitly\n\t\t\t// admin-configured owner selects admin issuance up front. Non-admin devices use the\n\t\t\t// signed Identity-bound endpoint; failures never fall back across this boundary.\n\t\t\tconst useAdminIssuance = kind === \"team_member\" || status.has_admin_secret;\n\t\t\tconst result = useAdminIssuance\n\t\t\t\t? await coordinatorCreateInviteAction({\n\t\t\t\t\t\tgroupId,\n\t\t\t\t\t\tcoordinatorUrl: config.syncCoordinatorUrl || null,\n\t\t\t\t\t\tpolicy: \"auto_admit\",\n\t\t\t\t\t\tttlHours,\n\t\t\t\t\t\tcreatedBy: store.actorId,\n\t\t\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t\t\t\tinviteKind: kind,\n\t\t\t\t\t\tpolicyTeamId: kind === \"team_member\" ? targetId : null,\n\t\t\t\t\t\ttargetIdentityId: kind === \"add_device\" ? targetId : null,\n\t\t\t\t\t\tinviterDeviceId: kind === \"add_device\" ? preview.binding.deviceId : null,\n\t\t\t\t\t\treviewedPreviewDigest,\n\t\t\t\t\t\treviewedIntent,\n\t\t\t\t\t})\n\t\t\t\t: await coordinatorCreateAddDeviceInviteAction({\n\t\t\t\t\t\tgroupId,\n\t\t\t\t\t\tcoordinatorUrl: config.syncCoordinatorUrl || null,\n\t\t\t\t\t\tttlHours,\n\t\t\t\t\t\tdeviceId: preview.binding.deviceId,\n\t\t\t\t\t\tkeysDir: syncKeysDir(),\n\t\t\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\t\t\treviewedPreviewDigest,\n\t\t\t\t\t\treviewedIntent,\n\t\t\t\t\t});\n\t\t\treturn c.json({ ok: true, kind, preview, invite: result });\n\t\t} catch (error) {\n\t\t\treturn c.json(\n\t\t\t\t{ error: error instanceof Error ? error.message : \"recipient_invite_failed\" },\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/recipient-policy/v1/migrate\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst value = await parseViewerJsonBody(c);\n\t\tif (!value || typeof value !== \"object\" || Array.isArray(value)) {\n\t\t\treturn c.json({ error: \"request_invalid\" }, 400);\n\t\t}\n\t\tconst body = value as Record<string, unknown>;\n\t\tif (\n\t\t\tObject.keys(body).some((key) => key !== \"dryRun\") ||\n\t\t\t(Object.hasOwn(body, \"dryRun\") && typeof body.dryRun !== \"boolean\")\n\t\t) {\n\t\t\treturn c.json({ error: \"request_invalid\" }, 400);\n\t\t}\n\t\ttry {\n\t\t\treturn c.json(\n\t\t\t\tmigrateRecipientPolicyIntent(\n\t\t\t\t\tstore.db,\n\t\t\t\t\t{ localActorId: store.actorId, localDeviceId: store.deviceId },\n\t\t\t\t\t{ dryRun: body.dryRun === true },\n\t\t\t\t),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tif (isSqliteBusy(error)) {\n\t\t\t\tc.header(\"Retry-After\", \"1\");\n\t\t\t\treturn c.json({ error: \"migration_busy\" }, 503);\n\t\t\t}\n\t\t\treturn c.json({ error: \"migration_failed\" }, 500);\n\t\t}\n\t});\n\n\tconst parseReviewRequest = (value: unknown): RecipientPolicyReviewResolveRequestV1 | null => {\n\t\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n\t\tconst body = value as Record<string, unknown>;\n\t\tconst allowedKeys = new Set([\"reviewItemId\", \"sourceFingerprint\", \"decision\", \"decisionInput\"]);\n\t\tif (\n\t\t\tObject.keys(body).some((key) => !allowedKeys.has(key)) ||\n\t\t\ttypeof body.reviewItemId !== \"string\" ||\n\t\t\ttypeof body.sourceFingerprint !== \"string\" ||\n\t\t\ttypeof body.decision !== \"string\"\n\t\t) {\n\t\t\treturn null;\n\t\t}\n\t\treturn {\n\t\t\treviewItemId: body.reviewItemId,\n\t\t\tsourceFingerprint: body.sourceFingerprint,\n\t\t\tdecision: body.decision as RecipientPolicyReviewDecisionV1,\n\t\t\t...(Object.hasOwn(body, \"decisionInput\") ? { decisionInput: body.decisionInput } : {}),\n\t\t};\n\t};\n\n\tapp.post(\"/api/sync/recipient-policy/v1/review/resolve\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst body = await parseViewerJsonBody(c);\n\t\tconst request = parseReviewRequest(body);\n\t\tif (!request) return c.json({ error: \"request_invalid\" }, 400);\n\t\tensureLocalActorRecord(store);\n\t\tconst result = resolveRecipientPolicyReview(\n\t\t\tstore.db,\n\t\t\t{ localActorId: store.actorId, localDeviceId: store.deviceId },\n\t\t\trequest,\n\t\t);\n\t\tif (result.status === \"stale\" || result.status === \"conflict\") return c.json(result, 409);\n\t\tif (result.status === \"not_found\") return c.json(result, 404);\n\t\tif (result.status === \"invalid\") return c.json(result, 400);\n\t\treturn c.json(result);\n\t});\n\n\tapp.post(\"/api/sync/recipient-policy/v1/review/resolve-bulk\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst body = await parseViewerJsonBody(c);\n\t\tif (\n\t\t\t!body ||\n\t\t\t!Array.isArray(body.requests) ||\n\t\t\tbody.requests.length === 0 ||\n\t\t\tbody.requests.length > 100\n\t\t)\n\t\t\treturn c.json({ error: \"request_invalid\" }, 400);\n\t\tconst requests = body.requests.map(parseReviewRequest);\n\t\tif (requests.some((request) => request == null))\n\t\t\treturn c.json({ error: \"request_invalid\" }, 400);\n\t\tensureLocalActorRecord(store);\n\t\tconst result = resolveRecipientPolicyReviewBulk(\n\t\t\tstore.db,\n\t\t\t{ localActorId: store.actorId, localDeviceId: store.deviceId },\n\t\t\trequests as RecipientPolicyReviewResolveRequestV1[],\n\t\t);\n\t\treturn c.json(result, result.results.some((item) => item.status !== \"applied\") ? 207 : 200);\n\t});\n\n\tapp.get(\"/api/sync/projects\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst limit = Math.max(1, queryInt(c.req.query(\"limit\"), 50));\n\t\tconst offset = Math.max(0, queryInt(c.req.query(\"offset\"), 0));\n\t\tconst inventory = listProjectScopeInventory(store.db, {\n\t\t\tidentitySource: c.req.query(\"identity_source\"),\n\t\t\tlimit,\n\t\t\toffset,\n\t\t\tquery: c.req.query(\"q\"),\n\t\t\tscopeId: c.req.query(\"scope_id\"),\n\t\t\tstatus: c.req.query(\"status\"),\n\t\t});\n\t\tconst operations = await shareOperationReadModels(store, undefined, false);\n\t\tconst operationById = new Map(\n\t\t\toperations.map((operation) => [operation.operation_id, operation]),\n\t\t);\n\t\tconst sharingByProject = new Map<string, Array<Record<string, unknown>>>();\n\t\tconst reviewed = store.db\n\t\t\t.prepare(`SELECT p.operation_id, p.canonical_project_identity\n\t\t\t FROM share_operation_projects p\n\t\t\t JOIN share_operations o ON o.operation_id = p.operation_id\n\t\t\t WHERE o.inviter_actor_id = ? ORDER BY o.created_at, p.ordinal`)\n\t\t\t.all(store.actorId) as Array<{ operation_id: string; canonical_project_identity: string }>;\n\t\tfor (const item of reviewed) {\n\t\t\tconst operation = operationById.get(item.operation_id);\n\t\t\tif (!operation) continue;\n\t\t\tconst current = sharingByProject.get(item.canonical_project_identity) ?? [];\n\t\t\tcurrent.push({\n\t\t\t\tperson: operation.person,\n\t\t\t\tlifecycle: {\n\t\t\t\t\tstate: operation.lifecycle.state,\n\t\t\t\t\tlabel: operation.lifecycle.label,\n\t\t\t\t\texplanation: operation.lifecycle.explanation,\n\t\t\t\t},\n\t\t\t});\n\t\t\tsharingByProject.set(item.canonical_project_identity, current);\n\t\t}\n\t\treturn c.json({\n\t\t\t...inventory,\n\t\t\tprojects: inventory.projects.map((project) => ({\n\t\t\t\t...project,\n\t\t\t\tsharing: sharingByProject.get(project.workspace_identity) ?? [],\n\t\t\t})),\n\t\t});\n\t});\n\n\tapp.post(\"/api/sync/projects/reassign-project\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst body = await parseViewerJsonBody(c);\n\t\tif (!body) return c.json({ error: \"invalid json\" }, 400);\n\t\ttry {\n\t\t\tconst workspaceIdentity = optionalViewerStrictString(body, \"workspace_identity\") ?? \"\";\n\t\t\tconst project = optionalViewerStrictString(body, \"project\") ?? \"\";\n\t\t\tconst [deviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });\n\t\t\tconst result = reassignProjectScopeInventoryProject(store.db, {\n\t\t\t\tdeviceId,\n\t\t\t\tproject,\n\t\t\t\tworkspaceIdentity,\n\t\t\t});\n\t\t\treturn c.json({ ok: true, ...result });\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\treturn c.json({ error: message }, message.includes(\"not found\") ? 404 : 400);\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/projects/forget\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst body = await parseViewerJsonBody(c);\n\t\tif (!body) return c.json({ error: \"invalid json\" }, 400);\n\t\ttry {\n\t\t\tconst workspaceIdentity = optionalViewerStrictString(body, \"workspace_identity\") ?? \"\";\n\t\t\tconst confirmationToken = optionalViewerStrictString(body, \"confirmation_token\");\n\t\t\tconst confirmed = body.confirmed === true;\n\t\t\tconst result = forgetProjectInventoryLocalMemories(store, {\n\t\t\t\tconfirmationToken,\n\t\t\t\tconfirmed,\n\t\t\t\tworkspaceIdentity,\n\t\t\t});\n\t\t\tif (!confirmed) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"project_forget_confirmation_required\",\n\t\t\t\t\t\tpreview: result,\n\t\t\t\t\t},\n\t\t\t\t\t409,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn c.json({ ok: true, ...result });\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\treturn c.json({ error: message }, message.includes(\"not found\") ? 404 : 400);\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/project-invites/preview\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst body = await parseViewerJsonBody(c);\n\t\tif (!body) return c.json({ error: \"invalid_json\" }, 400);\n\t\ttry {\n\t\t\tassertProjectInviteBody(body, false);\n\t\t\tconst createdAt = new Date().toISOString();\n\t\t\tconst inviteExpiresAt = new Date(\n\t\t\t\tnew Date(createdAt).getTime() + PROJECT_INVITE_TTL_HOURS * 3600 * 1000,\n\t\t\t).toISOString();\n\t\t\tconst { plan } = projectInvitePlan(store, body, createdAt, inviteExpiresAt);\n\t\t\treturn c.json(projectInvitePreview(plan));\n\t\t} catch (error) {\n\t\t\treturn c.json(\n\t\t\t\t{ error: error instanceof Error ? error.message : \"project_invite_invalid\" },\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/project-invites\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst body = await parseViewerJsonBody(c);\n\t\tif (!body) return c.json({ error: \"invalid_json\" }, 400);\n\t\ttry {\n\t\t\tassertProjectInviteBody(body, true);\n\t\t\tconst createdAt = new Date().toISOString();\n\t\t\tconst inviteExpiresAt = new Date(\n\t\t\t\tnew Date(createdAt).getTime() + PROJECT_INVITE_TTL_HOURS * 3600 * 1000,\n\t\t\t).toISOString();\n\t\t\tconst { plan, config } = projectInvitePlan(store, body, createdAt, inviteExpiresAt);\n\t\t\tif (String(body.reviewed_project_set_digest).trim() !== plan.reviewedProjectSetDigest) {\n\t\t\t\treturn c.json({ error: \"reviewed_project_set_changed\" }, 409);\n\t\t\t}\n\t\t\tconst existingState = (() => {\n\t\t\t\ttry {\n\t\t\t\t\treturn store.db\n\t\t\t\t\t\t.prepare(\"SELECT state FROM share_operations WHERE operation_id = ?\")\n\t\t\t\t\t\t.pluck()\n\t\t\t\t\t\t.get(plan.operationId) as string | undefined;\n\t\t\t\t} catch {\n\t\t\t\t\t// Local persistence below remains authoritative. Keeping this precheck\n\t\t\t\t\t// best-effort preserves coordinator idempotency if local storage is unavailable.\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t})();\n\t\t\tif (existingState && existingState !== \"waiting_for_acceptance\") {\n\t\t\t\treturn c.json({ error: \"operation_state_invalid\" }, 409);\n\t\t\t}\n\t\t\t// The coordinator invite is minted before local persistence. If the local\n\t\t\t// transaction fails, operationId makes coordinator creation return the\n\t\t\t// current invite. Expired or revoked waiting invites are renewed in place.\n\t\t\tconst result = await coordinatorCreateInviteAction({\n\t\t\t\tgroupId: plan.coordinatorGroupId,\n\t\t\t\tcoordinatorUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tpolicy: \"auto_admit\",\n\t\t\t\tttlHours: PROJECT_INVITE_TTL_HOURS,\n\t\t\t\tcreatedBy: store.actorId,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t\toperationId: plan.operationId,\n\t\t\t\treviewedProjectSetDigest: plan.reviewedProjectSetDigest,\n\t\t\t\tinviterActorId: plan.inviterActorId,\n\t\t\t\tinviterDisplayName: projectInviteInviterDisplayName(store.actorDisplayName),\n\t\t\t\tinviterDeviceId: plan.inviterDeviceIds[0],\n\t\t\t\tpendingPersonId: plan.personId,\n\t\t\t\tprojectSummaries: plan.projects.map((project) => ({\n\t\t\t\t\tdisplay_name: project.displayName,\n\t\t\t\t\texisting_memory_count: project.existingMemoryCount,\n\t\t\t\t})),\n\t\t\t\tprojectIntent: plan.projects.map((project) => ({\n\t\t\t\t\tcanonical_identity: project.canonicalIdentity,\n\t\t\t\t\tdisplay_name: project.displayName,\n\t\t\t\t\texisting_memory_count: project.existingMemoryCount,\n\t\t\t\t})),\n\t\t\t});\n\t\t\tif (\n\t\t\t\tString(result.operation_id ?? \"\").trim() !== plan.operationId ||\n\t\t\t\tString(result.reviewed_project_set_digest ?? \"\").trim() !== plan.reviewedProjectSetDigest\n\t\t\t) {\n\t\t\t\tthrow new Error(\"coordinator_invite_intent_mismatch\");\n\t\t\t}\n\t\t\tconst payload = result.payload;\n\t\t\tif (!payload || typeof payload !== \"object\" || Array.isArray(payload)) {\n\t\t\t\tthrow new Error(\"coordinator_invite_payload_missing\");\n\t\t\t}\n\t\t\tconst token = String((payload as Record<string, unknown>).token ?? \"\").trim();\n\t\t\tconst expiresAt = String((payload as Record<string, unknown>).expires_at ?? \"\").trim();\n\t\t\tconst link = String(result.link ?? \"\").trim();\n\t\t\tconst encoded = String(result.encoded ?? \"\").trim();\n\t\t\tif (!token || !expiresAt || !link || !encoded) {\n\t\t\t\tthrow new Error(\"coordinator_invite_payload_invalid\");\n\t\t\t}\n\t\t\tconst persistedPlan = { ...plan, inviteExpiresAt: new Date(expiresAt).toISOString() };\n\t\t\tpersistShareOperation(store.db, persistedPlan, {\n\t\t\t\tinviteId: String(result.invite_id ?? \"\").trim() || null,\n\t\t\t\ttokenDigest: inviteTokenDigest(token),\n\t\t\t});\n\t\t\treturn c.json({\n\t\t\t\tok: true,\n\t\t\t\t...projectInvitePreview(persistedPlan),\n\t\t\t\tinvite: {\n\t\t\t\t\tlink,\n\t\t\t\t\tencoded,\n\t\t\t\t\texpires_at: persistedPlan.inviteExpiresAt,\n\t\t\t\t},\n\t\t\t});\n\t\t} catch (error) {\n\t\t\treturn c.json(\n\t\t\t\t{ error: error instanceof Error ? error.message : \"project_invite_failed\" },\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t});\n\n\tapp.get(\"/api/sync/project-invites/:operationId\", async (c) => {\n\t\tconst operationId = String(c.req.param(\"operationId\") ?? \"\").trim();\n\t\tif (!/^share_[a-f0-9]{40}$/u.test(operationId)) {\n\t\t\treturn c.json({ error: \"operation_id_invalid\" }, 400);\n\t\t}\n\t\ttry {\n\t\t\tconst { payload } = await coordinatorProjectInvitePayload(operationId);\n\t\t\treturn c.json(\n\t\t\t\tpayload.state === \"accepted\" ? { ...payload, state: \"pending_setup\" } : payload,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconst mapped = projectInviteOwnerErrorResponse(error, {\n\t\t\t\tcode: \"operation_read_failed\",\n\t\t\t\tstatus: 400,\n\t\t\t});\n\t\t\treturn c.json({ error: mapped.code }, mapped.status);\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/project-invites/:operationId/reconcile\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst operationId = String(c.req.param(\"operationId\") ?? \"\").trim();\n\t\tif (!/^share_[a-f0-9]{40}$/u.test(operationId)) {\n\t\t\treturn c.json({ error: \"operation_id_invalid\" }, 400);\n\t\t}\n\t\ttry {\n\t\t\tconst result = await reconcileProjectInviteAcceptance(store, operationId);\n\t\t\treturn c.json({\n\t\t\t\tok: true,\n\t\t\t\toperation_id: operationId,\n\t\t\t\treconciled: result.accepted,\n\t\t\t\tstate: result.accepted ? \"pending_setup\" : \"waiting_for_acceptance\",\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst mapped = projectInviteOwnerErrorResponse(error, {\n\t\t\t\tcode: \"operation_reconcile_failed\",\n\t\t\t\tstatus: 409,\n\t\t\t});\n\t\t\treturn c.json({ error: mapped.code }, mapped.status);\n\t\t}\n\t});\n\n\tapp.get(\"/api/sync/share-operations\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst items = await shareOperationReadModels(store, undefined, false);\n\t\treturn c.json({ items });\n\t});\n\n\tapp.get(\"/api/sync/share-operations/:operationId\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst operationId = String(c.req.param(\"operationId\") ?? \"\").trim();\n\t\tif (!/^share_[a-f0-9]{40}$/u.test(operationId)) {\n\t\t\treturn c.json({ error: \"operation_id_invalid\" }, 400);\n\t\t}\n\t\tconst [item] = await shareOperationReadModels(store, operationId);\n\t\treturn item ? c.json(item) : c.json({ error: \"operation_not_found\" }, 404);\n\t});\n\n\tconst advanceProjectShare = async (c: Context) => {\n\t\tconst store = getStore();\n\t\tconst operationId = String(c.req.param(\"operationId\") ?? \"\").trim();\n\t\tif (!/^share_[a-f0-9]{40}$/u.test(operationId)) {\n\t\t\treturn c.json({ error: \"operation_id_invalid\" }, 400);\n\t\t}\n\t\ttry {\n\t\t\tconst advanced = await advanceProjectShareOperation(store, operationId);\n\t\t\tif (!advanced.advanced) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror:\n\t\t\t\t\t\t\tadvanced.state === \"cancelled\" ? \"operation_superseded\" : \"invitation_not_accepted\",\n\t\t\t\t\t},\n\t\t\t\t\t409,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst [operation] = await shareOperationReadModels(store, operationId);\n\t\t\treturn c.json({ ok: true, operation });\n\t\t} catch (error) {\n\t\t\tconst code = error instanceof Error ? error.message : \"provisioning_failed\";\n\t\t\tconst state = store.db\n\t\t\t\t.prepare(\"SELECT state FROM share_operations WHERE operation_id = ?\")\n\t\t\t\t.pluck()\n\t\t\t\t.get(operationId);\n\t\t\tif (state === \"cancelled\") {\n\t\t\t\treturn c.json({ error: \"operation_superseded\" }, 409);\n\t\t\t}\n\t\t\treturn c.json({ error: code }, code === \"operation_not_found\" ? 404 : 409);\n\t\t}\n\t};\n\n\tapp.post(\"/api/sync/share-operations/:operationId/advance\", advanceProjectShare);\n\n\tapp.post(\"/api/sync/project-invites/:operationId/provision\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst operationId = String(c.req.param(\"operationId\") ?? \"\").trim();\n\t\tif (!/^share_[a-f0-9]{40}$/u.test(operationId)) {\n\t\t\treturn c.json({ error: \"operation_id_invalid\" }, 400);\n\t\t}\n\t\ttry {\n\t\t\tconst plan = await executeProjectShareProvisioning(store, operationId);\n\t\t\tif (plan.superseded) {\n\t\t\t\t// Consistent with /advance: a supersession race is a conflict, not a\n\t\t\t\t// success with a flag.\n\t\t\t\treturn c.json({ error: \"operation_superseded\" }, 409);\n\t\t\t}\n\t\t\treturn c.json({ ok: true, operation_id: operationId, state: \"active\", plan });\n\t\t} catch (error) {\n\t\t\tconst code = error instanceof Error ? error.message : \"provisioning_failed\";\n\t\t\tconst state = store.db\n\t\t\t\t.prepare(\"SELECT state FROM share_operations WHERE operation_id = ?\")\n\t\t\t\t.pluck()\n\t\t\t\t.get(operationId);\n\t\t\tif (state === \"cancelled\") {\n\t\t\t\treturn c.json({ error: \"operation_superseded\" }, 409);\n\t\t\t}\n\t\t\treturn c.json({ error: code }, code === \"operation_not_found\" ? 404 : 409);\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/legacy-shared-review/reassign\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst body = await parseViewerJsonBody(c);\n\t\tif (!body) return c.json({ error: \"invalid json\" }, 400);\n\t\ttry {\n\t\t\tconst workspaceIdentity = optionalViewerStrictString(body, \"workspace_identity\") ?? \"\";\n\t\t\tconst scopeId = optionalViewerStrictString(body, \"scope_id\") ?? \"\";\n\t\t\tconst confirmationToken = optionalViewerStrictString(body, \"confirmation_token\");\n\t\t\tconst confirmedOldCopies = body.confirmed_old_copies === true;\n\t\t\tconst preview = legacySharedReviewReassignmentPreview(store, {\n\t\t\t\tscopeId,\n\t\t\t\tworkspaceIdentity,\n\t\t\t});\n\t\t\tif (!confirmedOldCopies) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"legacy_review_confirmation_required\",\n\t\t\t\t\t\tmessage: preview.warning,\n\t\t\t\t\t\tpreview,\n\t\t\t\t\t},\n\t\t\t\t\t409,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn c.json(\n\t\t\t\treassignLegacySharedReviewGroup(store, {\n\t\t\t\t\tconfirmationToken,\n\t\t\t\t\tscopeId,\n\t\t\t\t\tworkspaceIdentity,\n\t\t\t\t}),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\treturn c.json({ error: message }, message.includes(\"not found\") ? 404 : 400);\n\t\t}\n\t});\n\n\tapp.put(\"/api/sync/sharing-domains/project-mappings\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst body = await parseViewerJsonBody(c);\n\t\tif (!body) return c.json({ error: \"invalid json\" }, 400);\n\t\tlet releasePublicationMutation: (() => void) | undefined;\n\t\ttry {\n\t\t\tconst confirmedGuardrailTokens = optionalViewerStringList(body, \"confirmed_guardrail_tokens\");\n\t\t\tconst mappingInput = parseViewerProjectMappingInput(body);\n\t\t\treleasePublicationMutation = await claimRecipientPolicyPublicationMutation(store.db);\n\t\t\tconst analysis = analyzeProjectScopeMappingChangeGuardrails(store.db, mappingInput);\n\t\t\tif (analysis.requested_workspace_identity?.startsWith(\"unmapped:\")) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"unmapped_project_local_only\",\n\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\"Unmapped projects need a stable path, git remote, or workspace id before assigning a Sharing domain.\",\n\t\t\t\t\t\tguardrail_warnings: analysis.warnings,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst missingConfirmations = missingGuardrailConfirmations(\n\t\t\t\tanalysis.warnings,\n\t\t\t\tconfirmedGuardrailTokens,\n\t\t\t);\n\t\t\tif (missingConfirmations.length > 0) {\n\t\t\t\tconst missingCodes = [...new Set(missingConfirmations.map((warning) => warning.code))];\n\t\t\t\tconst missingTokens = [\n\t\t\t\t\t...new Set(missingConfirmations.map((warning) => warning.confirmation_token)),\n\t\t\t\t].filter((token): token is string => typeof token === \"string\" && token.length > 0);\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"guardrail_confirmation_required\",\n\t\t\t\t\t\trequired_guardrails: missingCodes,\n\t\t\t\t\t\trequired_guardrail_tokens: missingTokens,\n\t\t\t\t\t\tguardrail_warnings: analysis.warnings,\n\t\t\t\t\t},\n\t\t\t\t\t409,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst [deviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });\n\t\t\tconst mapping = upsertProjectScopeSettingsMapping(store.db, {\n\t\t\t\tdeviceId,\n\t\t\t\t...mappingInput,\n\t\t\t});\n\t\t\treturn c.json({ ok: true, mapping, guardrail_warnings: analysis.warnings });\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error) }, 400);\n\t\t} finally {\n\t\t\treleasePublicationMutation?.();\n\t\t}\n\t});\n\n\tapp.put(\"/api/sync/sharing-domains/project-mappings/bulk\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst body = await parseViewerJsonBody(c);\n\t\tif (!body) return c.json({ error: \"invalid json\" }, 400);\n\t\tlet releasePublicationMutation: (() => void) | undefined;\n\t\ttry {\n\t\t\tconst rawMappings = body.mappings;\n\t\t\tif (!Array.isArray(rawMappings) || rawMappings.length === 0) {\n\t\t\t\treturn c.json({ error: \"mappings must be a non-empty array\" }, 400);\n\t\t\t}\n\t\t\tconst mappingInputs = rawMappings.map((raw) => {\n\t\t\t\tif (raw == null || typeof raw !== \"object\" || Array.isArray(raw)) {\n\t\t\t\t\tthrow new Error(\"each mapping must be an object\");\n\t\t\t\t}\n\t\t\t\treturn parseViewerProjectMappingInput(raw as Record<string, unknown>);\n\t\t\t});\n\t\t\treleasePublicationMutation = await claimRecipientPolicyPublicationMutation(store.db);\n\t\t\tconst analyses = mappingInputs.map((mappingInput) =>\n\t\t\t\tanalyzeProjectScopeMappingChangeGuardrails(store.db, mappingInput),\n\t\t\t);\n\t\t\tconst unmapped = analyses.find((analysis) =>\n\t\t\t\tanalysis.requested_workspace_identity?.startsWith(\"unmapped:\"),\n\t\t\t);\n\t\t\tif (unmapped) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"unmapped_project_local_only\",\n\t\t\t\t\t\tmessage:\n\t\t\t\t\t\t\t\"Unmapped projects need a stable path, git remote, or workspace id before assigning a Sharing domain.\",\n\t\t\t\t\t\tguardrail_warnings: unmapped.warnings,\n\t\t\t\t\t},\n\t\t\t\t\t400,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst missingConfirmations = analyses.flatMap((analysis) =>\n\t\t\t\tmissingGuardrailConfirmations(analysis.warnings, []),\n\t\t\t);\n\t\t\tif (missingConfirmations.length > 0) {\n\t\t\t\tconst missingCodes = [...new Set(missingConfirmations.map((warning) => warning.code))];\n\t\t\t\tconst missingTokens = [\n\t\t\t\t\t...new Set(missingConfirmations.map((warning) => warning.confirmation_token)),\n\t\t\t\t].filter((token): token is string => typeof token === \"string\" && token.length > 0);\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: \"guardrail_confirmation_required\",\n\t\t\t\t\t\trequired_guardrails: missingCodes,\n\t\t\t\t\t\trequired_guardrail_tokens: missingTokens,\n\t\t\t\t\t\tguardrail_warnings: analyses.flatMap((analysis) => analysis.warnings),\n\t\t\t\t\t},\n\t\t\t\t\t409,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst [deviceId] = ensureDeviceIdentity(store.db, { keysDir: syncKeysDir() });\n\t\t\tconst saveMappings = store.db.transaction(() =>\n\t\t\t\tmappingInputs.map((mappingInput) =>\n\t\t\t\t\tupsertProjectScopeSettingsMapping(store.db, { deviceId, ...mappingInput }),\n\t\t\t\t),\n\t\t\t);\n\t\t\treturn c.json({\n\t\t\t\tok: true,\n\t\t\t\tmappings: saveMappings(),\n\t\t\t\tguardrail_warnings: analyses.flatMap((analysis) => analysis.warnings),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error) }, 400);\n\t\t} finally {\n\t\t\treleasePublicationMutation?.();\n\t\t}\n\t});\n\n\tapp.delete(\"/api/sync/sharing-domains/project-mappings/:id\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst id = Number(c.req.param(\"id\"));\n\t\tlet releasePublicationMutation: (() => void) | undefined;\n\t\ttry {\n\t\t\treleasePublicationMutation = await claimRecipientPolicyPublicationMutation(store.db);\n\t\t\tconst deleted = deleteProjectScopeSettingsMapping(store.db, id);\n\t\t\treturn c.json({ ok: true, deleted });\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error) }, 400);\n\t\t} finally {\n\t\t\treleasePublicationMutation?.();\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/peers/identity\", async (c) => {\n\t\tconst store = getStore();\n\t\tensureLocalActorRecord(store);\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\" }, 400);\n\t\t}\n\t\tconst peerDeviceId = String(body.peer_device_id ?? \"\").trim();\n\t\tif (!peerDeviceId) return c.json({ error: \"peer_device_id required\" }, 400);\n\t\tconst requestedActorId =\n\t\t\tbody.actor_id == null ? undefined : String(body.actor_id ?? \"\").trim() || null;\n\t\tconst claimedLocalActor =\n\t\t\ttypeof body.claimed_local_actor === \"boolean\" ? body.claimed_local_actor : undefined;\n\t\tconst d = drizzle(store.db, { schema });\n\t\tconst peer = d\n\t\t\t.select({\n\t\t\t\tpeer_device_id: schema.syncPeers.peer_device_id,\n\t\t\t\tactor_id: schema.syncPeers.actor_id,\n\t\t\t\tclaimed_local_actor: schema.syncPeers.claimed_local_actor,\n\t\t\t})\n\t\t\t.from(schema.syncPeers)\n\t\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t\t.get();\n\t\tif (!peer) return c.json({ error: \"peer not found\" }, 404);\n\n\t\tlet nextActorId = peer.actor_id ?? null;\n\t\tlet nextClaimedLocalActor = Boolean(peer.claimed_local_actor);\n\t\tif (requestedActorId !== undefined) {\n\t\t\tnextActorId = requestedActorId;\n\t\t\tif (requestedActorId) {\n\t\t\t\tconst actor = d\n\t\t\t\t\t.select({\n\t\t\t\t\t\tactor_id: schema.actors.actor_id,\n\t\t\t\t\t\tis_local: schema.actors.is_local,\n\t\t\t\t\t\tstatus: schema.actors.status,\n\t\t\t\t\t})\n\t\t\t\t\t.from(schema.actors)\n\t\t\t\t\t.where(eq(schema.actors.actor_id, requestedActorId))\n\t\t\t\t\t.get();\n\t\t\t\tif (!actor) return c.json({ error: \"actor not found\" }, 404);\n\t\t\t\tif (actor.status !== \"active\") return c.json({ error: \"actor not active\" }, 409);\n\t\t\t\tnextClaimedLocalActor = claimedLocalActor ?? Boolean(actor.is_local);\n\t\t\t} else {\n\t\t\t\tnextClaimedLocalActor = claimedLocalActor ?? false;\n\t\t\t}\n\t\t} else if (claimedLocalActor !== undefined) {\n\t\t\tnextClaimedLocalActor = claimedLocalActor;\n\t\t\tif (claimedLocalActor) {\n\t\t\t\tnextActorId = store.actorId;\n\t\t\t} else if (nextActorId === store.actorId) {\n\t\t\t\tnextActorId = null;\n\t\t\t}\n\t\t}\n\n\t\td.update(schema.syncPeers)\n\t\t\t.set({\n\t\t\t\tactor_id: nextActorId,\n\t\t\t\tclaimed_local_actor: nextClaimedLocalActor ? 1 : 0,\n\t\t\t})\n\t\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t\t.run();\n\t\treturn c.json({ ok: true, actor_id: nextActorId, claimed_local_actor: nextClaimedLocalActor });\n\t});\n\n\tapp.post(\"/api/sync/actors\", async (c) => {\n\t\tconst store = getStore();\n\t\tensureLocalActorRecord(store);\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\" }, 400);\n\t\t}\n\t\tconst rawDisplayName = String(body.display_name ?? \"\");\n\t\tif (!rawDisplayName.trim()) return c.json({ error: \"display_name required\" }, 400);\n\t\tlet displayName: string;\n\t\ttry {\n\t\t\tdisplayName = normalizeHumanPresentationName(rawDisplayName, \"display_name\");\n\t\t} catch (error) {\n\t\t\treturn c.json(\n\t\t\t\t{ error: error instanceof Error ? error.message : \"display_name_invalid\" },\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t\tconst d = drizzle(store.db, { schema });\n\t\tconst now = new Date().toISOString();\n\t\tconst actor = {\n\t\t\tactor_id: randomUUID(),\n\t\t\tdisplay_name: displayName,\n\t\t\tis_local: 0,\n\t\t\tstatus: \"active\",\n\t\t\tmerged_into_actor_id: null,\n\t\t\tcreated_at: now,\n\t\t\tupdated_at: now,\n\t\t};\n\t\td.insert(schema.actors).values(actor).run();\n\t\treturn c.json(actor);\n\t});\n\n\tapp.post(\"/api/sync/actors/rename\", async (c) => {\n\t\tconst store = getStore();\n\t\tensureLocalActorRecord(store);\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\" }, 400);\n\t\t}\n\t\tconst actorId = String(body.actor_id ?? \"\").trim();\n\t\tif (!actorId) return c.json({ error: \"actor_id required\" }, 400);\n\t\tlet displayName: string;\n\t\ttry {\n\t\t\tdisplayName = normalizeHumanPresentationName(String(body.display_name ?? \"\"), \"display_name\");\n\t\t} catch (error) {\n\t\t\treturn c.json(\n\t\t\t\t{ error: error instanceof Error ? error.message : \"display_name_invalid\" },\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t\tconst d = drizzle(store.db, { schema });\n\t\tconst actor = d.select().from(schema.actors).where(eq(schema.actors.actor_id, actorId)).get();\n\t\tif (!actor) return c.json({ error: \"actor not found\" }, 404);\n\t\tconst updatedAt = new Date().toISOString();\n\t\td.update(schema.actors)\n\t\t\t.set({ display_name: displayName, updated_at: updatedAt })\n\t\t\t.where(eq(schema.actors.actor_id, actorId))\n\t\t\t.run();\n\t\treturn c.json({ ...actor, display_name: displayName, updated_at: updatedAt });\n\t});\n\n\tapp.post(\"/api/sync/actors/merge\", async (c) => {\n\t\tconst store = getStore();\n\t\tensureLocalActorRecord(store);\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\" }, 400);\n\t\t}\n\t\tconst primaryActorId = String(body.primary_actor_id ?? \"\").trim();\n\t\tconst secondaryActorId = String(body.secondary_actor_id ?? \"\").trim();\n\t\tif (!primaryActorId) return c.json({ error: \"primary_actor_id required\" }, 400);\n\t\tif (!secondaryActorId) return c.json({ error: \"secondary_actor_id required\" }, 400);\n\t\tif (primaryActorId === secondaryActorId) return c.json({ error: \"actor ids must differ\" }, 400);\n\t\tconst d = drizzle(store.db, { schema });\n\t\tconst releaseActorMutations = await claimRecipientPolicyActorMutations(store.db, [\n\t\t\tprimaryActorId,\n\t\t\tsecondaryActorId,\n\t\t]);\n\t\t// This transaction is synchronous. Deferring release prevents a thrown transaction\n\t\t// from leaking the lock while keeping it held through every mutation below.\n\t\tqueueMicrotask(releaseActorMutations);\n\t\tconst now = new Date().toISOString();\n\t\tconst result = store.db\n\t\t\t.transaction(() => {\n\t\t\t\tconst primary = d\n\t\t\t\t\t.select()\n\t\t\t\t\t.from(schema.actors)\n\t\t\t\t\t.where(eq(schema.actors.actor_id, primaryActorId))\n\t\t\t\t\t.get();\n\t\t\t\tconst secondary = d\n\t\t\t\t\t.select()\n\t\t\t\t\t.from(schema.actors)\n\t\t\t\t\t.where(eq(schema.actors.actor_id, secondaryActorId))\n\t\t\t\t\t.get();\n\t\t\t\tif (!primary || !secondary) return { error: \"actor not found\", status: 404 as const };\n\t\t\t\tif (primary.status !== \"active\") {\n\t\t\t\t\treturn { error: \"primary actor not active\", status: 409 as const };\n\t\t\t\t}\n\t\t\t\tif (secondary.status !== \"active\") {\n\t\t\t\t\treturn { error: \"secondary actor not active\", status: 409 as const };\n\t\t\t\t}\n\t\t\t\tif (secondary.is_local && secondary.actor_id === store.actorId) {\n\t\t\t\t\treturn { error: \"cannot merge this device's own local actor\", status: 409 as const };\n\t\t\t\t}\n\t\t\t\tconst memberships = d\n\t\t\t\t\t.select()\n\t\t\t\t\t.from(schema.policyTeamMemberships)\n\t\t\t\t\t.where(eq(schema.policyTeamMemberships.identity_id, secondaryActorId))\n\t\t\t\t\t.all();\n\t\t\t\tconst primaryMemberships = new Map<string, (typeof memberships)[number] | undefined>();\n\t\t\t\tfor (const membership of memberships) {\n\t\t\t\t\tconst primaryMembership = d\n\t\t\t\t\t\t.select()\n\t\t\t\t\t\t.from(schema.policyTeamMemberships)\n\t\t\t\t\t\t.where(\n\t\t\t\t\t\t\tand(\n\t\t\t\t\t\t\t\teq(schema.policyTeamMemberships.team_id, membership.team_id),\n\t\t\t\t\t\t\t\teq(schema.policyTeamMemberships.identity_id, primaryActorId),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.get();\n\t\t\t\t\tif (\n\t\t\t\t\t\tprimaryMembership &&\n\t\t\t\t\t\t(primaryMembership.role !== membership.role ||\n\t\t\t\t\t\t\tprimaryMembership.status !== membership.status)\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn { error: \"actor team memberships conflict\", status: 409 as const };\n\t\t\t\t\t}\n\t\t\t\t\tprimaryMemberships.set(membership.team_id, primaryMembership);\n\t\t\t\t}\n\t\t\t\tconst directRecipients = d\n\t\t\t\t\t.select()\n\t\t\t\t\t.from(schema.projectRecipients)\n\t\t\t\t\t.where(\n\t\t\t\t\t\tand(\n\t\t\t\t\t\t\teq(schema.projectRecipients.recipient_kind, \"identity\"),\n\t\t\t\t\t\t\teq(schema.projectRecipients.recipient_id, secondaryActorId),\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t\t.all();\n\t\t\t\tconst primaryRecipients = new Map<string, (typeof directRecipients)[number] | undefined>();\n\t\t\t\tfor (const recipient of directRecipients) {\n\t\t\t\t\tconst primaryRecipient = d\n\t\t\t\t\t\t.select()\n\t\t\t\t\t\t.from(schema.projectRecipients)\n\t\t\t\t\t\t.where(\n\t\t\t\t\t\t\tand(\n\t\t\t\t\t\t\t\teq(\n\t\t\t\t\t\t\t\t\tschema.projectRecipients.canonical_project_identity,\n\t\t\t\t\t\t\t\t\trecipient.canonical_project_identity,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\teq(schema.projectRecipients.recipient_kind, \"identity\"),\n\t\t\t\t\t\t\t\teq(schema.projectRecipients.recipient_id, primaryActorId),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.get();\n\t\t\t\t\tif (primaryRecipient && primaryRecipient.status !== recipient.status) {\n\t\t\t\t\t\treturn { error: \"actor project recipients conflict\", status: 409 as const };\n\t\t\t\t\t}\n\t\t\t\t\tprimaryRecipients.set(recipient.canonical_project_identity, primaryRecipient);\n\t\t\t\t}\n\n\t\t\t\tconst mergeDigest = createHash(\"sha256\")\n\t\t\t\t\t.update(\n\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\tkind: \"identity-merge-v1\",\n\t\t\t\t\t\t\tprimaryActorId,\n\t\t\t\t\t\t\tsecondaryActorId,\n\t\t\t\t\t\t\tnonce: randomUUID(),\n\t\t\t\t\t\t}),\n\t\t\t\t\t)\n\t\t\t\t\t.digest(\"hex\");\n\t\t\t\tconst bindings = d\n\t\t\t\t\t.select({\n\t\t\t\t\t\tdeviceId: schema.identityDevices.device_id,\n\t\t\t\t\t\tassignmentVersion: schema.identityDevices.assignment_version,\n\t\t\t\t\t})\n\t\t\t\t\t.from(schema.identityDevices)\n\t\t\t\t\t.where(eq(schema.identityDevices.identity_id, secondaryActorId))\n\t\t\t\t\t.all();\n\t\t\t\tif (bindings.length > 0) {\n\t\t\t\t\tconst commitDigest = mergeDigest;\n\t\t\t\t\tconst outcomes = bindings.map((binding) => ({\n\t\t\t\t\t\tdeviceId: binding.deviceId,\n\t\t\t\t\t\tpreviousIdentityId: secondaryActorId,\n\t\t\t\t\t\ttargetIdentityId: primaryActorId,\n\t\t\t\t\t\taction: \"rebind\",\n\t\t\t\t\t}));\n\t\t\t\t\tstore.db\n\t\t\t\t\t\t.prepare(`INSERT INTO device_identity_binding_commits(\n\t\t\t\t\t\tcommit_digest, reviewed_inventory_digest, request_json, outcomes_json, write_count,\n\t\t\t\t\t\tdecided_by_identity_id, decided_by_device_id, created_at\n\t\t\t\t\t) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`)\n\t\t\t\t\t\t.run(\n\t\t\t\t\t\t\tcommitDigest,\n\t\t\t\t\t\t\t`identity-merge:${secondaryActorId}:${primaryActorId}`,\n\t\t\t\t\t\t\tJSON.stringify({ primaryActorId, secondaryActorId }),\n\t\t\t\t\t\t\tJSON.stringify(outcomes),\n\t\t\t\t\t\t\tbindings.length,\n\t\t\t\t\t\t\tstore.actorId,\n\t\t\t\t\t\t\tstore.deviceId,\n\t\t\t\t\t\t\tnow,\n\t\t\t\t\t\t);\n\n\t\t\t\t\tfor (const binding of bindings) {\n\t\t\t\t\t\tconst revision = createHash(\"sha256\")\n\t\t\t\t\t\t\t.update(`identity-merge-revision-v1\\0${commitDigest}\\0${binding.deviceId}`)\n\t\t\t\t\t\t\t.digest(\"hex\");\n\t\t\t\t\t\tconst idempotencyKey = createHash(\"sha256\")\n\t\t\t\t\t\t\t.update(`identity-merge-row-v1\\0${commitDigest}\\0${binding.deviceId}`)\n\t\t\t\t\t\t\t.digest(\"hex\");\n\t\t\t\t\t\tconst bindingUpdate = store.db\n\t\t\t\t\t\t\t.prepare(`UPDATE identity_devices SET\n\t\t\t\t\t\t\tidentity_id = ?, provenance = 'review_resolution', revision = ?,\n\t\t\t\t\t\t\tmigration_state = 'user_managed', source_fingerprint = ?,\n\t\t\t\t\t\t\tidempotency_key = ?, updated_at = ?\n\t\t\t\t\t\t WHERE device_id = ? AND identity_id = ?`)\n\t\t\t\t\t\t\t.run(\n\t\t\t\t\t\t\t\tprimaryActorId,\n\t\t\t\t\t\t\t\trevision,\n\t\t\t\t\t\t\t\tcommitDigest,\n\t\t\t\t\t\t\t\tidempotencyKey,\n\t\t\t\t\t\t\t\tnow,\n\t\t\t\t\t\t\t\tbinding.deviceId,\n\t\t\t\t\t\t\t\tsecondaryActorId,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\tif (bindingUpdate.changes !== 1)\n\t\t\t\t\t\t\tthrow new Error(\"identity_merge_binding_update_failed\");\n\t\t\t\t\t\tconst rebound = store.db\n\t\t\t\t\t\t\t.prepare(\"SELECT assignment_version FROM identity_devices WHERE device_id = ?\")\n\t\t\t\t\t\t\t.get(binding.deviceId) as { assignment_version: number } | undefined;\n\t\t\t\t\t\tif (!rebound || rebound.assignment_version !== binding.assignmentVersion + 1) {\n\t\t\t\t\t\t\tthrow new Error(\"identity_merge_assignment_version_unexpected\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tstore.db\n\t\t\t\t\t\t\t.prepare(\"DELETE FROM policy_team_device_decisions WHERE device_id = ?\")\n\t\t\t\t\t\t\t.run(binding.deviceId);\n\t\t\t\t\t\tstore.db\n\t\t\t\t\t\t\t.prepare(`INSERT INTO device_identity_binding_audit(\n\t\t\t\t\t\t\tevent_id, commit_digest, device_id, previous_identity_id, target_identity_id,\n\t\t\t\t\t\t\taction, previous_assignment_version, resulting_assignment_version,\n\t\t\t\t\t\t\tdecided_by_identity_id, decided_by_device_id, created_at\n\t\t\t\t\t\t) VALUES (?, ?, ?, ?, ?, 'rebind', ?, ?, ?, ?, ?)`)\n\t\t\t\t\t\t\t.run(\n\t\t\t\t\t\t\t\tcreateHash(\"sha256\")\n\t\t\t\t\t\t\t\t\t.update(`identity-merge-event-v1\\0${commitDigest}\\0${binding.deviceId}`)\n\t\t\t\t\t\t\t\t\t.digest(\"hex\"),\n\t\t\t\t\t\t\t\tcommitDigest,\n\t\t\t\t\t\t\t\tbinding.deviceId,\n\t\t\t\t\t\t\t\tsecondaryActorId,\n\t\t\t\t\t\t\t\tprimaryActorId,\n\t\t\t\t\t\t\t\tbinding.assignmentVersion,\n\t\t\t\t\t\t\t\trebound.assignment_version,\n\t\t\t\t\t\t\t\tstore.actorId,\n\t\t\t\t\t\t\t\tstore.deviceId,\n\t\t\t\t\t\t\t\tnow,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfor (const membership of memberships) {\n\t\t\t\t\tconst primaryMembership = primaryMemberships.get(membership.team_id);\n\t\t\t\t\tif (primaryMembership) {\n\t\t\t\t\t\td.delete(schema.policyTeamMemberships)\n\t\t\t\t\t\t\t.where(\n\t\t\t\t\t\t\t\tand(\n\t\t\t\t\t\t\t\t\teq(schema.policyTeamMemberships.team_id, membership.team_id),\n\t\t\t\t\t\t\t\t\teq(schema.policyTeamMemberships.identity_id, secondaryActorId),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.run();\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst revision = createHash(\"sha256\")\n\t\t\t\t\t\t.update(`identity-merge-membership-revision-v1\\0${mergeDigest}\\0${membership.team_id}`)\n\t\t\t\t\t\t.digest(\"hex\");\n\t\t\t\t\tconst idempotencyKey = createHash(\"sha256\")\n\t\t\t\t\t\t.update(`identity-merge-membership-row-v1\\0${mergeDigest}\\0${membership.team_id}`)\n\t\t\t\t\t\t.digest(\"hex\");\n\t\t\t\t\td.update(schema.policyTeamMemberships)\n\t\t\t\t\t\t.set({\n\t\t\t\t\t\t\tidentity_id: primaryActorId,\n\t\t\t\t\t\t\tprovenance: \"review_resolution\",\n\t\t\t\t\t\t\trevision,\n\t\t\t\t\t\t\tmigration_state: \"user_managed\",\n\t\t\t\t\t\t\tsource_fingerprint: mergeDigest,\n\t\t\t\t\t\t\tidempotency_key: idempotencyKey,\n\t\t\t\t\t\t\tupdated_at: now,\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.where(\n\t\t\t\t\t\t\tand(\n\t\t\t\t\t\t\t\teq(schema.policyTeamMemberships.team_id, membership.team_id),\n\t\t\t\t\t\t\t\teq(schema.policyTeamMemberships.identity_id, secondaryActorId),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.run();\n\t\t\t\t}\n\t\t\t\tfor (const recipient of directRecipients) {\n\t\t\t\t\tconst primaryRecipient = primaryRecipients.get(recipient.canonical_project_identity);\n\t\t\t\t\tif (primaryRecipient) {\n\t\t\t\t\t\td.delete(schema.projectRecipients)\n\t\t\t\t\t\t\t.where(\n\t\t\t\t\t\t\t\tand(\n\t\t\t\t\t\t\t\t\teq(\n\t\t\t\t\t\t\t\t\t\tschema.projectRecipients.canonical_project_identity,\n\t\t\t\t\t\t\t\t\t\trecipient.canonical_project_identity,\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t\teq(schema.projectRecipients.recipient_kind, \"identity\"),\n\t\t\t\t\t\t\t\t\teq(schema.projectRecipients.recipient_id, secondaryActorId),\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.run();\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst policyRevision = createHash(\"sha256\")\n\t\t\t\t\t\t.update(\n\t\t\t\t\t\t\t`identity-merge-recipient-revision-v1\\0${mergeDigest}\\0${recipient.canonical_project_identity}`,\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.digest(\"hex\");\n\t\t\t\t\tconst idempotencyKey = createHash(\"sha256\")\n\t\t\t\t\t\t.update(\n\t\t\t\t\t\t\t`identity-merge-recipient-row-v1\\0${mergeDigest}\\0${recipient.canonical_project_identity}`,\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.digest(\"hex\");\n\t\t\t\t\td.update(schema.projectRecipients)\n\t\t\t\t\t\t.set({\n\t\t\t\t\t\t\trecipient_id: primaryActorId,\n\t\t\t\t\t\t\tprovenance: \"review_resolution\",\n\t\t\t\t\t\t\tpolicy_revision: policyRevision,\n\t\t\t\t\t\t\tmigration_state: \"user_managed\",\n\t\t\t\t\t\t\tsource_fingerprint: mergeDigest,\n\t\t\t\t\t\t\tidempotency_key: idempotencyKey,\n\t\t\t\t\t\t\tupdated_at: now,\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.where(\n\t\t\t\t\t\t\tand(\n\t\t\t\t\t\t\t\teq(\n\t\t\t\t\t\t\t\t\tschema.projectRecipients.canonical_project_identity,\n\t\t\t\t\t\t\t\t\trecipient.canonical_project_identity,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\teq(schema.projectRecipients.recipient_kind, \"identity\"),\n\t\t\t\t\t\t\t\teq(schema.projectRecipients.recipient_id, secondaryActorId),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.run();\n\t\t\t\t}\n\t\t\t\td.update(schema.recipientManagedProjectProjections)\n\t\t\t\t\t.set({ recipient_identity_id: primaryActorId, updated_at: now })\n\t\t\t\t\t.where(\n\t\t\t\t\t\teq(schema.recipientManagedProjectProjections.recipient_identity_id, secondaryActorId),\n\t\t\t\t\t)\n\t\t\t\t\t.run();\n\t\t\t\tstore.db\n\t\t\t\t\t.prepare(`UPDATE share_operations SET\n\t\t\t\t\t\tinviter_actor_id = CASE WHEN inviter_actor_id = ? THEN ? ELSE inviter_actor_id END,\n\t\t\t\t\t\trecipient_actor_id = CASE WHEN recipient_actor_id = ? THEN ? ELSE recipient_actor_id END,\n\t\t\t\t\t\tperson_id = CASE WHEN person_id = ? THEN ? ELSE person_id END,\n\t\t\t\t\t\tupdated_at = ?\n\t\t\t\t\t WHERE inviter_actor_id = ? OR recipient_actor_id = ? OR person_id = ?`)\n\t\t\t\t\t.run(\n\t\t\t\t\t\tsecondaryActorId,\n\t\t\t\t\t\tprimaryActorId,\n\t\t\t\t\t\tsecondaryActorId,\n\t\t\t\t\t\tprimaryActorId,\n\t\t\t\t\t\tsecondaryActorId,\n\t\t\t\t\t\tprimaryActorId,\n\t\t\t\t\t\tnow,\n\t\t\t\t\t\tsecondaryActorId,\n\t\t\t\t\t\tsecondaryActorId,\n\t\t\t\t\t\tsecondaryActorId,\n\t\t\t\t\t);\n\n\t\t\t\tconst peerUpdate = d\n\t\t\t\t\t.update(schema.syncPeers)\n\t\t\t\t\t.set({ actor_id: primaryActorId })\n\t\t\t\t\t.where(eq(schema.syncPeers.actor_id, secondaryActorId))\n\t\t\t\t\t.run();\n\t\t\t\tif (primary.is_local) {\n\t\t\t\t\td.update(schema.syncPeers)\n\t\t\t\t\t\t.set({ claimed_local_actor: 1 })\n\t\t\t\t\t\t.where(eq(schema.syncPeers.actor_id, primaryActorId))\n\t\t\t\t\t\t.run();\n\t\t\t\t}\n\t\t\t\td.update(schema.actors)\n\t\t\t\t\t.set({ status: \"merged\", merged_into_actor_id: primaryActorId, updated_at: now })\n\t\t\t\t\t.where(eq(schema.actors.actor_id, secondaryActorId))\n\t\t\t\t\t.run();\n\t\t\t\treturn { mergedCount: Number(peerUpdate.changes ?? 0) };\n\t\t\t})\n\t\t\t.immediate();\n\t\tif (\"error\" in result) return c.json({ error: result.error }, result.status);\n\t\treturn c.json({ merged_count: result.mergedCount });\n\t});\n\n\tapp.post(\"/api/sync/actors/deactivate\", async (c) => {\n\t\tconst store = getStore();\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\" }, 400);\n\t\t}\n\t\tconst actorId = String(body.actor_id ?? \"\").trim();\n\t\tif (!actorId) return c.json({ error: \"actor_id required\" }, 400);\n\t\tif (actorId === store.actorId) {\n\t\t\treturn c.json({ error: \"cannot deactivate this device's own local actor\" }, 409);\n\t\t}\n\t\tconst releaseActorMutations = await claimRecipientPolicyActorMutations(store.db, [actorId]);\n\t\t// All following reads and writes are synchronous, so release after this turn.\n\t\tqueueMicrotask(releaseActorMutations);\n\t\tconst d = drizzle(store.db, { schema });\n\t\tconst actor = d.select().from(schema.actors).where(eq(schema.actors.actor_id, actorId)).get();\n\t\tif (!actor) return c.json({ error: \"actor not found\" }, 404);\n\t\tif (actor.status !== \"active\") return c.json({ error: \"actor not active\" }, 409);\n\t\tconst now = new Date().toISOString();\n\t\td.update(schema.actors)\n\t\t\t.set({ status: \"deactivated\", updated_at: now })\n\t\t\t.where(eq(schema.actors.actor_id, actorId))\n\t\t\t.run();\n\t\td.update(schema.syncPeers)\n\t\t\t.set({ actor_id: null })\n\t\t\t.where(eq(schema.syncPeers.actor_id, actorId))\n\t\t\t.run();\n\t\treturn c.json({ ok: true });\n\t});\n\n\tapp.post(\"/api/sync/legacy-devices/claim\", async (c) => {\n\t\tconst store = getStore();\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\" }, 400);\n\t\t}\n\t\tconst originDeviceId = String(body.origin_device_id ?? \"\").trim();\n\t\tif (!originDeviceId) return c.json({ error: \"origin_device_id required\" }, 400);\n\t\tconst updated = claimLegacyDeviceAsSelf(store, originDeviceId);\n\t\tif (updated <= 0) return c.json({ error: \"legacy device not found\" }, 404);\n\t\treturn c.json({ ok: true, origin_device_id: originDeviceId, updated });\n\t});\n\n\tapp.post(\"/api/sync/peers/accept-discovered\", async (c) => {\n\t\tconst store = getStore();\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\" }, 400);\n\t\t}\n\t\tconst peerDeviceId = String(body.peer_device_id ?? \"\").trim();\n\t\tconst fingerprint = String(body.fingerprint ?? \"\").trim();\n\t\tconst expectedGroupId = String(body.expected_group_id ?? \"\").trim();\n\t\tconst hasExpectedIncomingRequestId = Object.hasOwn(body, \"expected_incoming_request_id\");\n\t\tconst expectedIncomingRequestId = String(body.expected_incoming_request_id ?? \"\").trim();\n\t\tif (!peerDeviceId) return c.json({ error: \"peer_device_id required\" }, 400);\n\t\tif (hasExpectedIncomingRequestId && !expectedIncomingRequestId) {\n\t\t\treturn c.json({ error: \"expected_incoming_request_id must not be empty\" }, 400);\n\t\t}\n\t\tif (expectedIncomingRequestId && !expectedGroupId) {\n\t\t\treturn c.json({ error: \"expected_group_id required\" }, 400);\n\t\t}\n\t\ttry {\n\t\t\tconst result = await acceptDiscoveredPeer(store, {\n\t\t\t\tpeerDeviceId,\n\t\t\t\tfingerprint: fingerprint || undefined,\n\t\t\t\texpectedGroupId: expectedGroupId || undefined,\n\t\t\t\texpectedIncomingRequestId: expectedIncomingRequestId || undefined,\n\t\t\t});\n\t\t\tif (!result.ok) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: result.error,\n\t\t\t\t\t\tdetail: result.detail,\n\t\t\t\t\t\t...(result.reason ? { reason: result.reason } : {}),\n\t\t\t\t\t},\n\t\t\t\t\t{ status: result.status as 400 | 404 | 409 },\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn c.json({\n\t\t\t\tok: true,\n\t\t\t\tpeer_device_id: result.peer_device_id,\n\t\t\t\tcreated: result.created,\n\t\t\t\tupdated: result.updated,\n\t\t\t\tname: result.name,\n\t\t\t\tneeds_scope_review: true,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error instanceof CoordinatorReciprocalApprovalRequestChangedError) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: error.code,\n\t\t\t\t\t\tdetail:\n\t\t\t\t\t\t\t\"This approval request changed before it was submitted. Refresh sync status and review the current request.\",\n\t\t\t\t\t},\n\t\t\t\t\t{ status: 409 },\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn c.json(\n\t\t\t\t{\n\t\t\t\t\terror: \"coordinator_lookup_failed\",\n\t\t\t\t\tdetail: error instanceof Error ? error.message : String(error),\n\t\t\t\t},\n\t\t\t\t{ status: 502 },\n\t\t\t);\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/invites/create\", async (c) => {\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\" }, 400);\n\t\t}\n\t\tconst groupId = String(body.group_id ?? \"\").trim();\n\t\tconst coordinatorUrl = body.coordinator_url == null ? null : String(body.coordinator_url ?? \"\");\n\t\tconst policy = String(body.policy ?? \"auto_admit\").trim();\n\t\tconst ttlHours = parseInviteTtlHours(body.ttl_hours);\n\t\tif (!groupId) return c.json({ error: \"group_id required\" }, 400);\n\t\tif (body.coordinator_url != null && typeof body.coordinator_url !== \"string\") {\n\t\t\treturn c.json({ error: \"coordinator_url must be string\" }, 400);\n\t\t}\n\t\tif (![\"auto_admit\", \"approval_required\"].includes(policy)) {\n\t\t\treturn c.json({ error: \"policy must be auto_admit or approval_required\" }, 400);\n\t\t}\n\t\tif (ttlHours == null) return c.json({ error: \"ttl_hours must be an integer >= 1\" }, 400);\n\t\ttry {\n\t\t\tconst config = readCoordinatorSyncConfig();\n\t\t\tconst result = await coordinatorCreateInviteAction({\n\t\t\t\tgroupId,\n\t\t\t\tcoordinatorUrl,\n\t\t\t\tpolicy,\n\t\t\t\tttlHours,\n\t\t\t\tcreatedBy: null,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\treturn c.json(result);\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error) }, 400);\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/invites/inspect\", async (c) => {\n\t\tconst store = getStore();\n\t\tconst body = await parseViewerJsonBody(c);\n\t\tif (!body || typeof body.invite !== \"string\") return c.json({ error: \"invite_invalid\" }, 400);\n\t\ttry {\n\t\t\tconst payload = decodeInvitePayload(extractInvitePayload(body.invite));\n\t\t\tconst recipientInvite = payload.kind === \"team_member\" || payload.kind === \"add_device\";\n\t\t\tif (recipientInvite) ensureStableStoreDeviceIdentity(store);\n\t\t\telse ensureStableStoreIdentity(store);\n\t\t\tif (!payload.operation_id && !recipientInvite) return c.json({ kind: \"legacy_team_invite\" });\n\t\t\tconst [status, inspected] = await requestJson(\n\t\t\t\t\"POST\",\n\t\t\t\t`${buildBaseUrl(payload.coordinator_url)}/v1/invites/inspect`,\n\t\t\t\t{ body: { token: payload.token }, timeoutS: 10 },\n\t\t\t);\n\t\t\tif (status < 200 || status >= 300) {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\terror: recipientInvite\n\t\t\t\t\t\t\t? safeRecipientInviteError(inspected?.error)\n\t\t\t\t\t\t\t: String(inspected?.error ?? \"invite_invalid\"),\n\t\t\t\t\t},\n\t\t\t\t\tstatus === 410 ? 410 : 400,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst config = readCodememConfigFile();\n\t\t\tconst identityId = recipientInvite\n\t\t\t\t? recipientInviteAuthoritativeIdentityId({\n\t\t\t\t\t\tkind: payload.kind as \"team_member\" | \"add_device\",\n\t\t\t\t\t\tassigned_identity_id: inspected?.assigned_identity_id,\n\t\t\t\t\t\ttarget_identity_id: inspected?.target_identity_id,\n\t\t\t\t\t})\n\t\t\t\t: store.actorId;\n\t\t\tconst expectedTarget =\n\t\t\t\tpayload.kind === \"team_member\"\n\t\t\t\t\t? String(inspected?.policy_team_id ?? \"\").trim()\n\t\t\t\t\t: String(inspected?.target_identity_id ?? \"\").trim();\n\t\t\tif (recipientInvite) {\n\t\t\t\tif (\n\t\t\t\t\tString(inspected?.kind ?? \"\").trim() !== payload.kind ||\n\t\t\t\t\t!expectedTarget ||\n\t\t\t\t\tString(inspected?.reviewed_preview_digest ?? \"\").trim() !==\n\t\t\t\t\t\tString(payload.reviewed_preview_digest ?? \"\").trim() ||\n\t\t\t\t\t(payload.kind === \"team_member\" && expectedTarget !== payload.policy_team_id) ||\n\t\t\t\t\t(payload.kind === \"team_member\" &&\n\t\t\t\t\t\t(identityId !== String(payload.assigned_identity_id ?? \"\").trim() || !identityId)) ||\n\t\t\t\t\t(payload.kind === \"add_device\" && expectedTarget !== payload.target_identity_id)\n\t\t\t\t) {\n\t\t\t\t\treturn c.json({ error: \"recipient_invite_intent_mismatch\" }, 409);\n\t\t\t\t}\n\t\t\t\tif (inspected?.reviewed_intent == null) {\n\t\t\t\t\treturn c.json({ error: \"recipient_invite_review_unavailable\" }, 409);\n\t\t\t\t}\n\t\t\t\tlet reviewedIntent: RecipientReviewedIntentV1;\n\t\t\t\ttry {\n\t\t\t\t\treviewedIntent = await verifyRecipientReviewedIntent(inspected.reviewed_intent, {\n\t\t\t\t\t\ttarget:\n\t\t\t\t\t\t\tpayload.kind === \"team_member\"\n\t\t\t\t\t\t\t\t? { kind: \"team_member\", policyTeamId: expectedTarget }\n\t\t\t\t\t\t\t\t: { kind: \"add_device\", targetIdentityId: expectedTarget },\n\t\t\t\t\t\tdigest: String(payload.reviewed_preview_digest ?? \"\").trim(),\n\t\t\t\t\t});\n\t\t\t\t} catch {\n\t\t\t\t\treturn c.json({ error: \"recipient_invite_intent_mismatch\" }, 409);\n\t\t\t\t}\n\t\t\t\tconst preview = recipientInviteOnboardingPreviewFromReviewedIntent(\n\t\t\t\t\tstore,\n\t\t\t\t\t{\n\t\t\t\t\t\tkind: payload.kind,\n\t\t\t\t\t\tpolicy_team_id: payload.kind === \"team_member\" ? expectedTarget : null,\n\t\t\t\t\t\tassigned_identity_id: payload.kind === \"team_member\" ? identityId : null,\n\t\t\t\t\t\ttarget_identity_id: payload.kind === \"add_device\" ? identityId : null,\n\t\t\t\t\t\tdevice_name: optionalViewerString(body, \"device_name\"),\n\t\t\t\t\t},\n\t\t\t\t\tString(payload.token),\n\t\t\t\t\treviewedIntent,\n\t\t\t\t);\n\t\t\t\treturn c.json({\n\t\t\t\t\t...inspected,\n\t\t\t\t\trecipient_name:\n\t\t\t\t\t\treviewedIntent.journey === \"add_device\"\n\t\t\t\t\t\t\t? reviewedIntent.targetIdentity.displayName\n\t\t\t\t\t\t\t: store.actorDisplayName,\n\t\t\t\t\tdevice_name: preview.binding.deviceDisplayName,\n\t\t\t\t\tonboarding: preview,\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn c.json({\n\t\t\t\t...inspected,\n\t\t\t\trecipient_name: store.actorDisplayName,\n\t\t\t\tdevice_name: friendlyDeviceName({\n\t\t\t\t\texplicitName: String(config.sync_device_name ?? \"\"),\n\t\t\t\t\tosName: hostname(),\n\t\t\t\t\tfallbackSeed: store.deviceId,\n\t\t\t\t}),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: safeRecipientInviteError(error) }, 400);\n\t\t}\n\t});\n\n\t// POST /api/sync/invites/import accepts both team invites (coordinator\n\t// invite envelope or codemem:// link) and device-pairing payloads\n\t// (base64 JSON with { device_id, fingerprint, public_key, addresses }).\n\t// The server discriminates by decoding the pasted text — UI callers get\n\t// one textarea for all flows. Response type distinguishes legacy Team joins,\n\t// exact-Project pending setup, recipient onboarding, and direct pairing.\n\tapp.post(\"/api/sync/invites/import\", async (c) => {\n\t\tconst store = getStore();\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\" }, 400);\n\t\t}\n\t\tconst rawValue = String(body.invite ?? \"\").trim();\n\t\tif (!rawValue) return c.json({ error: \"invite required\" }, 400);\n\n\t\t// Users often paste the whole shell command emitted by the Pairing\n\t\t// diagnostics disclosure (`echo '<b64>' | base64 -d | codemem sync\n\t\t// pair --accept-file -`). Peel the base64 out if we see that shape.\n\t\tconst shellMatch = rawValue.match(\n\t\t\t/echo\\s+['\"]([A-Za-z0-9+/=]+)['\"]\\s*\\|\\s*base64\\s+-d\\s*\\|\\s*codemem/,\n\t\t);\n\t\tconst normalized = shellMatch?.[1]?.trim() || rawValue;\n\n\t\tconst pairingResult = tryParsePairingPayload(normalized);\n\t\tif (pairingResult?.kind === \"invalid-pair\") {\n\t\t\treturn c.json({ error: pairingResult.error }, 400);\n\t\t}\n\t\tif (pairingResult?.kind === \"pair\") {\n\t\t\ttry {\n\t\t\t\tconst d = drizzle(store.db, { schema });\n\t\t\t\tconst existing = d\n\t\t\t\t\t.select({ pinned_fingerprint: schema.syncPeers.pinned_fingerprint })\n\t\t\t\t\t.from(schema.syncPeers)\n\t\t\t\t\t.where(eq(schema.syncPeers.peer_device_id, pairingResult.device_id))\n\t\t\t\t\t.get();\n\t\t\t\tconst existingFingerprint = String(existing?.pinned_fingerprint ?? \"\").trim();\n\t\t\t\tif (existingFingerprint && existingFingerprint !== pairingResult.fingerprint) {\n\t\t\t\t\treturn c.json(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\terror: \"peer_conflict\",\n\t\t\t\t\t\t\tdetail:\n\t\t\t\t\t\t\t\t\"Pairing payload conflicts with the existing trusted fingerprint for this device. Remove or repair the old peer before accepting this pairing payload.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t409,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tupdatePeerAddresses(store.db, pairingResult.device_id, pairingResult.addresses, {\n\t\t\t\t\tpinnedFingerprint: pairingResult.fingerprint,\n\t\t\t\t\tpublicKey: pairingResult.public_key,\n\t\t\t\t\treplaceTrust: true,\n\t\t\t\t});\n\t\t\t\treturn c.json({\n\t\t\t\t\tok: true,\n\t\t\t\t\ttype: \"pair\",\n\t\t\t\t\tpeer_device_id: pairingResult.device_id,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error) }, 400);\n\t\t\t}\n\t\t}\n\n\t\tlet projectInvite = false;\n\t\tlet recipientInvite = false;\n\t\ttry {\n\t\t\tconst decoded = decodeInvitePayload(extractInvitePayload(rawValue));\n\t\t\tprojectInvite = Boolean(decoded.operation_id);\n\t\t\trecipientInvite = decoded.kind === \"team_member\" || decoded.kind === \"add_device\";\n\t\t\tif (recipientInvite) ensureStableStoreDeviceIdentity(store);\n\t\t\telse ensureStableStoreIdentity(store);\n\t\t\tconst reviewedOnboardingDigest =\n\t\t\t\ttypeof body.reviewed_onboarding_digest === \"string\"\n\t\t\t\t\t? body.reviewed_onboarding_digest.trim()\n\t\t\t\t\t: \"\";\n\t\t\tif (recipientInvite && !reviewedOnboardingDigest) {\n\t\t\t\treturn c.json({ error: \"reviewed_onboarding_digest_required\" }, 400);\n\t\t\t}\n\t\t\tconst result = await coordinatorImportInviteAction({\n\t\t\t\tinviteValue: rawValue,\n\t\t\t\tdbPath: store.dbPath,\n\t\t\t\trecipientActorId: recipientInvite ? null : store.actorId,\n\t\t\t\trecipientDisplayName:\n\t\t\t\t\tdecoded.kind === \"add_device\"\n\t\t\t\t\t\t? null\n\t\t\t\t\t\t: typeof body.recipient_name === \"string\"\n\t\t\t\t\t\t\t? body.recipient_name\n\t\t\t\t\t\t\t: store.actorDisplayName,\n\t\t\t\tdeviceDisplayName: typeof body.device_name === \"string\" ? body.device_name : null,\n\t\t\t\treviewedOnboardingDigest: reviewedOnboardingDigest || null,\n\t\t\t});\n\t\t\tconst type = recipientInvite\n\t\t\t\t? \"recipient_onboarding\"\n\t\t\t\t: projectInvite\n\t\t\t\t\t? \"project_share\"\n\t\t\t\t\t: \"team_join\";\n\t\t\tif (recipientInvite) {\n\t\t\t\tconst persistedIdentityId = String(result.identity_id ?? \"\").trim();\n\t\t\t\tif (!store.refreshPersistedLocalIdentity(persistedIdentityId)) {\n\t\t\t\t\treturn c.json(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t...result,\n\t\t\t\t\t\t\ttype,\n\t\t\t\t\t\t\tsetup_state: \"restart_required\",\n\t\t\t\t\t\t\trestart_required: true,\n\t\t\t\t\t\t\tdetail:\n\t\t\t\t\t\t\t\t\"The invitation was accepted and the reviewed Identity was persisted, but this process could not safely adopt it. Restart codemem before continuing.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t200,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif ((projectInvite || recipientInvite) && getSyncRuntimeStatus?.()?.phase === \"disabled\") {\n\t\t\t\treturn c.json(\n\t\t\t\t\t{\n\t\t\t\t\t\t...result,\n\t\t\t\t\t\ttype,\n\t\t\t\t\t\tsetup_state: \"restart_required\",\n\t\t\t\t\t\trestart_required: true,\n\t\t\t\t\t\tdetail: projectInvite\n\t\t\t\t\t\t\t? \"The invitation was accepted and sync was enabled. Restart codemem to start the sync service; Project setup remains pending until the first sync finishes.\"\n\t\t\t\t\t\t\t: \"The invitation was accepted and sync was enabled. Restart codemem to start the sync service and receive the reviewed Projects.\",\n\t\t\t\t\t},\n\t\t\t\t\t200,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn c.json({\n\t\t\t\t...result,\n\t\t\t\ttype,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (projectInvite) return c.json(projectInviteAcceptanceFailure(error), 400);\n\t\t\tif (recipientInvite) return c.json({ error: safeRecipientInviteError(error) }, 400);\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error) }, 400);\n\t\t}\n\t});\n\n\tapp.get(\"/api/coordinator/admin/status\", async (c) => {\n\t\tconst status = coordinatorAdminStatusPayload();\n\t\treturn c.json(status);\n\t});\n\n\tapp.get(\"/api/coordinator/admin/groups\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tif (!status.has_admin_secret) {\n\t\t\treturn c.json({ error: \"coordinator_admin_secret_missing\", status }, 400);\n\t\t}\n\t\tconst includeArchived = queryBool(c.req.query(\"include_archived\"));\n\t\ttry {\n\t\t\tconst items = await coordinatorListGroupsAction({\n\t\t\t\tincludeArchived,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\treturn c.json({ items, status });\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"unknown\";\n\t\t\treturn c.json({ error: message, status }, coordinatorAdminMutationStatus(message));\n\t\t}\n\t});\n\n\tapp.post(\"/api/coordinator/admin/groups\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tif (!status.has_admin_secret) {\n\t\t\treturn c.json({ error: \"coordinator_admin_secret_missing\", status }, 400);\n\t\t}\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\", status }, 400);\n\t\t}\n\t\tconst groupId = String(body.group_id ?? \"\").trim();\n\t\tconst displayName = String(body.display_name ?? \"\").trim() || null;\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\ttry {\n\t\t\tconst group = await coordinatorCreateGroupAction({\n\t\t\t\tgroupId,\n\t\t\t\tdisplayName,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\ttry {\n\t\t\t\tconst defaultSpace = await ensureDefaultSpaceForTeam({\n\t\t\t\t\tstore: getStore(),\n\t\t\t\t\tconfig,\n\t\t\t\t\tgroupId,\n\t\t\t\t\tdisplayName: displayName || group.display_name || null,\n\t\t\t\t});\n\t\t\t\treturn c.json({ ok: true, group, default_space: defaultSpace, status });\n\t\t\t} catch (setupError) {\n\t\t\t\treturn c.json({\n\t\t\t\t\tok: true,\n\t\t\t\t\tgroup,\n\t\t\t\t\tdefault_space: null,\n\t\t\t\t\tsetup_warning: {\n\t\t\t\t\t\tstep: \"default_space\",\n\t\t\t\t\t\terror: setupError instanceof Error ? setupError.message : String(setupError),\n\t\t\t\t\t},\n\t\t\t\t\tstatus,\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error), status }, 400);\n\t\t}\n\t});\n\n\tapp.post(\"/api/coordinator/admin/groups/:group_id/rename\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tif (!status.has_admin_secret) {\n\t\t\treturn c.json({ error: \"coordinator_admin_secret_missing\", status }, 400);\n\t\t}\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\", status }, 400);\n\t\t}\n\t\tconst displayName = String(body.display_name ?? \"\").trim();\n\t\tif (!displayName) return c.json({ error: \"display_name required\", status }, 400);\n\t\ttry {\n\t\t\tconst group = await coordinatorRenameGroupAction({\n\t\t\t\tgroupId,\n\t\t\t\tdisplayName,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\tif (!group) return c.json({ error: \"group_not_found\", status }, 404);\n\t\t\treturn c.json({ ok: true, group, status });\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error), status }, 400);\n\t\t}\n\t});\n\n\tapp.post(\"/api/coordinator/admin/groups/:group_id/archive\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tif (!status.has_admin_secret) {\n\t\t\treturn c.json({ error: \"coordinator_admin_secret_missing\", status }, 400);\n\t\t}\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\ttry {\n\t\t\tconst group = await coordinatorArchiveGroupAction({\n\t\t\t\tgroupId,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\tif (!group) return c.json({ error: \"group_not_found_or_already_archived\", status }, 404);\n\t\t\tconst groups = removeConfiguredCoordinatorGroup(groupId);\n\t\t\treturn c.json({\n\t\t\t\tok: true,\n\t\t\t\tgroup,\n\t\t\t\tstatus: coordinatorAdminStatusPayload(),\n\t\t\t\tdisconnected_group_id: groupId,\n\t\t\t\tgroups,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error), status }, 400);\n\t\t}\n\t});\n\n\tapp.post(\"/api/coordinator/admin/groups/:group_id/unarchive\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tif (!status.has_admin_secret) {\n\t\t\treturn c.json({ error: \"coordinator_admin_secret_missing\", status }, 400);\n\t\t}\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\ttry {\n\t\t\tconst group = await coordinatorUnarchiveGroupAction({\n\t\t\t\tgroupId,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\tif (!group) return c.json({ error: \"group_not_found_or_not_archived\", status }, 404);\n\t\t\treturn c.json({ ok: true, group, status });\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error), status }, 400);\n\t\t}\n\t});\n\n\tapp.get(\"/api/coordinator/admin/groups/:group_id/scopes\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tconst unavailable = coordinatorAdminUnavailable(status);\n\t\tif (unavailable) return c.json(unavailable.body, unavailable.httpStatus);\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\ttry {\n\t\t\tconst items = await coordinatorListScopesAction({\n\t\t\t\tgroupId,\n\t\t\t\tincludeInactive: queryBool(c.req.query(\"include_inactive\")),\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\treturn c.json({ items, group_id: groupId, status });\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"unknown\";\n\t\t\treturn c.json({ error: message, status }, coordinatorAdminMutationStatus(message));\n\t\t}\n\t});\n\n\tapp.post(\"/api/coordinator/admin/groups/:group_id/scopes\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tconst unavailable = coordinatorAdminUnavailable(status);\n\t\tif (unavailable) return c.json(unavailable.body, unavailable.httpStatus);\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\tconst body = await parseViewerJsonBody(c);\n\t\tif (!body) return c.json({ error: \"invalid json\", status }, 400);\n\t\tconst scopeId = optionalViewerString(body, \"scope_id\");\n\t\tconst label = optionalViewerString(body, \"label\");\n\t\tconst membershipEpoch = optionalViewerNumber(body, \"membership_epoch\");\n\t\tif (!scopeId || !label) return c.json({ error: \"scope_id and label required\", status }, 400);\n\t\tif (Number.isNaN(membershipEpoch)) {\n\t\t\treturn c.json({ error: \"membership_epoch must be number\", status }, 400);\n\t\t}\n\t\ttry {\n\t\t\tconst scope = await coordinatorCreateScopeAction({\n\t\t\t\tgroupId,\n\t\t\t\tscopeId,\n\t\t\t\tlabel,\n\t\t\t\tkind: optionalViewerString(body, \"kind\"),\n\t\t\t\tauthorityType: optionalViewerString(body, \"authority_type\"),\n\t\t\t\tcoordinatorId: optionalViewerString(body, \"coordinator_id\"),\n\t\t\t\tmanifestIssuerDeviceId: optionalViewerString(body, \"manifest_issuer_device_id\"),\n\t\t\t\tmembershipEpoch,\n\t\t\t\tmanifestHash: optionalViewerString(body, \"manifest_hash\"),\n\t\t\t\tstatus: optionalViewerString(body, \"status\"),\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\treturn c.json({ ok: true, scope, group_id: groupId, status });\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\treturn c.json({ error: message, status }, coordinatorAdminMutationStatus(message));\n\t\t}\n\t});\n\n\tapp.patch(\"/api/coordinator/admin/groups/:group_id/scopes/:scope_id\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tconst unavailable = coordinatorAdminUnavailable(status);\n\t\tif (unavailable) return c.json(unavailable.body, unavailable.httpStatus);\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tconst scopeId = String(c.req.param(\"scope_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\tif (!scopeId) return c.json({ error: \"scope_id required\", status }, 400);\n\t\tconst body = await parseViewerJsonBody(c);\n\t\tif (!body) return c.json({ error: \"invalid json\", status }, 400);\n\t\tconst membershipEpoch = optionalViewerNumber(body, \"membership_epoch\");\n\t\tif (Number.isNaN(membershipEpoch)) {\n\t\t\treturn c.json({ error: \"membership_epoch must be number\", status }, 400);\n\t\t}\n\t\ttry {\n\t\t\tconst scope = await coordinatorUpdateScopeAction({\n\t\t\t\tgroupId,\n\t\t\t\tscopeId,\n\t\t\t\tlabel: body.label === undefined ? undefined : optionalViewerString(body, \"label\"),\n\t\t\t\tkind: body.kind === undefined ? undefined : optionalViewerString(body, \"kind\"),\n\t\t\t\tauthorityType:\n\t\t\t\t\tbody.authority_type === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: optionalViewerString(body, \"authority_type\"),\n\t\t\t\tcoordinatorId:\n\t\t\t\t\tbody.coordinator_id === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: optionalViewerString(body, \"coordinator_id\"),\n\t\t\t\tmanifestIssuerDeviceId:\n\t\t\t\t\tbody.manifest_issuer_device_id === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: optionalViewerString(body, \"manifest_issuer_device_id\"),\n\t\t\t\tmembershipEpoch,\n\t\t\t\tmanifestHash:\n\t\t\t\t\tbody.manifest_hash === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: optionalViewerString(body, \"manifest_hash\"),\n\t\t\t\tstatus: body.status === undefined ? undefined : optionalViewerString(body, \"status\"),\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\tif (!scope) return c.json({ error: \"scope_not_found\", status }, 404);\n\t\t\treturn c.json({ ok: true, scope, group_id: groupId, status });\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\treturn c.json({ error: message, status }, coordinatorAdminMutationStatus(message));\n\t\t}\n\t});\n\n\tapp.get(\"/api/coordinator/admin/groups/:group_id/scopes/:scope_id/members\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tconst unavailable = coordinatorAdminUnavailable(status);\n\t\tif (unavailable) return c.json(unavailable.body, unavailable.httpStatus);\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tconst scopeId = String(c.req.param(\"scope_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\tif (!scopeId) return c.json({ error: \"scope_id required\", status }, 400);\n\t\ttry {\n\t\t\tconst items = await coordinatorListScopeMembershipsAction({\n\t\t\t\tgroupId,\n\t\t\t\tscopeId,\n\t\t\t\tincludeRevoked: queryBool(c.req.query(\"include_revoked\")),\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\treturn c.json({ items, group_id: groupId, scope_id: scopeId, status });\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"unknown\";\n\t\t\treturn c.json({ error: message, status }, coordinatorAdminMutationStatus(message));\n\t\t}\n\t});\n\n\tapp.post(\"/api/coordinator/admin/groups/:group_id/scopes/:scope_id/members\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tconst unavailable = coordinatorAdminUnavailable(status);\n\t\tif (unavailable) return c.json(unavailable.body, unavailable.httpStatus);\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tconst scopeId = String(c.req.param(\"scope_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\tif (!scopeId) return c.json({ error: \"scope_id required\", status }, 400);\n\t\tconst body = await parseViewerJsonBody(c);\n\t\tif (!body) return c.json({ error: \"invalid json\", status }, 400);\n\t\tconst deviceId = optionalViewerString(body, \"device_id\");\n\t\tconst membershipEpoch = optionalViewerNumber(body, \"membership_epoch\");\n\t\tif (!deviceId) return c.json({ error: \"device_id required\", status }, 400);\n\t\tif (Number.isNaN(membershipEpoch)) {\n\t\t\treturn c.json({ error: \"membership_epoch must be number\", status }, 400);\n\t\t}\n\t\tconst role = optionalViewerString(body, \"role\");\n\t\tconst coordinatorId = optionalViewerString(body, \"coordinator_id\");\n\t\tconst manifestIssuerDeviceId = optionalViewerString(body, \"manifest_issuer_device_id\");\n\t\tconst manifestHash = optionalViewerString(body, \"manifest_hash\");\n\t\tconst signedManifestJson = optionalViewerString(body, \"signed_manifest_json\");\n\t\tconst effectId =\n\t\t\toptionalViewerString(body, \"effect_id\") ??\n\t\t\tcoordinatorAdminMembershipEffectId(\"grant\", randomUUID(), {\n\t\t\t\tgroupId,\n\t\t\t\tscopeId,\n\t\t\t\tdeviceId,\n\t\t\t\trole,\n\t\t\t\tmembershipEpoch,\n\t\t\t\tcoordinatorId,\n\t\t\t\tmanifestIssuerDeviceId,\n\t\t\t\tmanifestHash,\n\t\t\t\tsignedManifestJson,\n\t\t\t});\n\t\ttry {\n\t\t\tconst membership = await coordinatorGrantScopeMembershipAction({\n\t\t\t\teffectId,\n\t\t\t\tgroupId,\n\t\t\t\tscopeId,\n\t\t\t\tdeviceId,\n\t\t\t\trole,\n\t\t\t\tmembershipEpoch,\n\t\t\t\tcoordinatorId,\n\t\t\t\tmanifestIssuerDeviceId,\n\t\t\t\tmanifestHash,\n\t\t\t\tsignedManifestJson,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\treturn c.json({ ok: true, membership, group_id: groupId, scope_id: scopeId, status });\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\treturn c.json({ error: message, status }, coordinatorAdminMutationStatus(message));\n\t\t}\n\t});\n\n\tapp.post(\n\t\t\"/api/coordinator/admin/groups/:group_id/scopes/:scope_id/members/:device_id/revoke\",\n\t\tasync (c) => {\n\t\t\tconst config = readCoordinatorSyncConfig();\n\t\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\t\tconst unavailable = coordinatorAdminUnavailable(status);\n\t\t\tif (unavailable) return c.json(unavailable.body, unavailable.httpStatus);\n\t\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\t\tconst scopeId = String(c.req.param(\"scope_id\") ?? \"\").trim();\n\t\t\tconst deviceId = String(c.req.param(\"device_id\") ?? \"\").trim();\n\t\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\t\tif (!scopeId) return c.json({ error: \"scope_id required\", status }, 400);\n\t\t\tif (!deviceId) return c.json({ error: \"device_id required\", status }, 400);\n\t\t\tconst body = await parseViewerJsonBody(c, { allowEmpty: true });\n\t\t\tif (!body) return c.json({ error: \"invalid json\", status }, 400);\n\t\t\tconst membershipEpoch = optionalViewerNumber(body, \"membership_epoch\");\n\t\t\tif (Number.isNaN(membershipEpoch)) {\n\t\t\t\treturn c.json({ error: \"membership_epoch must be number\", status }, 400);\n\t\t\t}\n\t\t\tconst manifestHash = optionalViewerString(body, \"manifest_hash\");\n\t\t\tconst signedManifestJson = optionalViewerString(body, \"signed_manifest_json\");\n\t\t\tconst effectId =\n\t\t\t\toptionalViewerString(body, \"effect_id\") ??\n\t\t\t\tcoordinatorAdminMembershipEffectId(\"revoke\", randomUUID(), {\n\t\t\t\t\tgroupId,\n\t\t\t\t\tscopeId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tmembershipEpoch,\n\t\t\t\t\tmanifestHash,\n\t\t\t\t\tsignedManifestJson,\n\t\t\t\t});\n\t\t\ttry {\n\t\t\t\tconst ok = await coordinatorRevokeScopeMembershipAction({\n\t\t\t\t\teffectId,\n\t\t\t\t\tgroupId,\n\t\t\t\t\tscopeId,\n\t\t\t\t\tdeviceId,\n\t\t\t\t\tmembershipEpoch,\n\t\t\t\t\tmanifestHash,\n\t\t\t\t\tsignedManifestJson,\n\t\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t\t});\n\t\t\t\tif (!ok) return c.json({ error: \"membership_not_found\", status }, 404);\n\t\t\t\treturn c.json({\n\t\t\t\t\tok: true,\n\t\t\t\t\tgroup_id: groupId,\n\t\t\t\t\tscope_id: scopeId,\n\t\t\t\t\tdevice_id: deviceId,\n\t\t\t\t\tstatus,\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\treturn c.json({ error: message, status }, coordinatorAdminMutationStatus(message));\n\t\t\t}\n\t\t},\n\t);\n\n\tapp.post(\"/api/coordinator/admin/invites\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tif (!status.has_admin_secret) {\n\t\t\treturn c.json({ error: \"coordinator_admin_secret_missing\", status }, 400);\n\t\t}\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\", status }, 400);\n\t\t}\n\t\tconst groupId = resolveCoordinatorAdminGroup(String(body.group_id ?? \"\").trim(), status);\n\t\tconst coordinatorUrl = body.coordinator_url == null ? null : String(body.coordinator_url ?? \"\");\n\t\tconst policy = String(body.policy ?? \"auto_admit\").trim();\n\t\tconst ttlHours = parseInviteTtlHours(body.ttl_hours);\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\tif (body.coordinator_url != null && typeof body.coordinator_url !== \"string\") {\n\t\t\treturn c.json({ error: \"coordinator_url must be string\", status }, 400);\n\t\t}\n\t\tif (![\"auto_admit\", \"approval_required\"].includes(policy)) {\n\t\t\treturn c.json({ error: \"policy must be auto_admit or approval_required\", status }, 400);\n\t\t}\n\t\tif (ttlHours == null) {\n\t\t\treturn c.json({ error: \"ttl_hours must be an integer >= 1\", status }, 400);\n\t\t}\n\t\ttry {\n\t\t\tconst result = await coordinatorCreateInviteAction({\n\t\t\t\tgroupId,\n\t\t\t\tcoordinatorUrl,\n\t\t\t\tpolicy,\n\t\t\t\tttlHours,\n\t\t\t\tcreatedBy: null,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\treturn c.json({ ...result, status });\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error), status }, 400);\n\t\t}\n\t});\n\n\tapp.get(\"/api/coordinator/admin/join-requests\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tif (!status.has_admin_secret) {\n\t\t\treturn c.json({ error: \"coordinator_admin_secret_missing\", status }, 400);\n\t\t}\n\t\tconst groupId = resolveCoordinatorAdminGroup(c.req.query(\"group_id\"), status);\n\t\tif (!groupId) return c.json({ error: \"group_id_required\", status }, 400);\n\t\ttry {\n\t\t\tconst items = await coordinatorListJoinRequestsAction({\n\t\t\t\tgroupId,\n\t\t\t\tremoteUrl: status.coordinator_url,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\treturn c.json({ items, group_id: groupId, status });\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"unknown\";\n\t\t\treturn c.json({ error: message, status }, coordinatorAdminMutationStatus(message));\n\t\t}\n\t});\n\n\tapp.post(\"/api/coordinator/admin/join-requests/:request_id/approve\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tif (!status.has_admin_secret) {\n\t\t\treturn c.json({ error: \"coordinator_admin_secret_missing\", status }, 400);\n\t\t}\n\t\tconst requestId = String(c.req.param(\"request_id\") ?? \"\").trim();\n\t\tif (!requestId) return c.json({ error: \"request_id required\", status }, 400);\n\t\ttry {\n\t\t\tconst result = await coordinatorReviewJoinRequestAction({\n\t\t\t\trequestId,\n\t\t\t\tapprove: true,\n\t\t\t\treviewedBy: null,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\tif (!result) return c.json({ error: \"join request not found\", status }, 404);\n\t\t\tlet defaultSpaceMembership = null;\n\t\t\tlet setupWarning = null;\n\t\t\ttry {\n\t\t\t\tdefaultSpaceMembership = await maybeGrantDefaultSpaceOnJoin({\n\t\t\t\t\tstore: getStore(),\n\t\t\t\t\tconfig,\n\t\t\t\t\tgroupId: result.group_id,\n\t\t\t\t\trequestId,\n\t\t\t\t\tdeviceId: result.device_id,\n\t\t\t\t});\n\t\t\t} catch (grantError) {\n\t\t\t\tsetupWarning = {\n\t\t\t\t\tstep: \"default_space_grant\",\n\t\t\t\t\terror: grantError instanceof Error ? grantError.message : String(grantError),\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn c.json({\n\t\t\t\tok: true,\n\t\t\t\trequest: result,\n\t\t\t\tdefault_space_membership: defaultSpaceMembership,\n\t\t\t\tsetup_warning: setupWarning,\n\t\t\t\tstatus,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\treturn c.json(\n\t\t\t\t{ error: message, status },\n\t\t\t\tmessage.includes(\"request_not_found\") || message.includes(\"not found\") ? 404 : 400,\n\t\t\t);\n\t\t}\n\t});\n\n\tapp.post(\"/api/coordinator/admin/join-requests/:request_id/deny\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tif (!status.has_admin_secret) {\n\t\t\treturn c.json({ error: \"coordinator_admin_secret_missing\", status }, 400);\n\t\t}\n\t\tconst requestId = String(c.req.param(\"request_id\") ?? \"\").trim();\n\t\tif (!requestId) return c.json({ error: \"request_id required\", status }, 400);\n\t\ttry {\n\t\t\tconst result = await coordinatorReviewJoinRequestAction({\n\t\t\t\trequestId,\n\t\t\t\tapprove: false,\n\t\t\t\treviewedBy: null,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\tif (!result) return c.json({ error: \"join request not found\", status }, 404);\n\t\t\treturn c.json({ ok: true, request: result, status });\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\treturn c.json(\n\t\t\t\t{ error: message, status },\n\t\t\t\tmessage.includes(\"request_not_found\") || message.includes(\"not found\") ? 404 : 400,\n\t\t\t);\n\t\t}\n\t});\n\n\tapp.get(\"/api/coordinator/admin/devices\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tif (!status.has_admin_secret) {\n\t\t\treturn c.json({ error: \"coordinator_admin_secret_missing\", status }, 400);\n\t\t}\n\t\tconst groupId = resolveCoordinatorAdminGroup(c.req.query(\"group_id\"), status);\n\t\tif (!groupId) return c.json({ error: \"group_id_required\", status }, 400);\n\t\ttry {\n\t\t\tconst items = await coordinatorListDevicesAction({\n\t\t\t\tgroupId,\n\t\t\t\tincludeDisabled: queryBool(c.req.query(\"include_disabled\")),\n\t\t\t\tremoteUrl: status.coordinator_url,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\treturn c.json({ items, group_id: groupId, status });\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"unknown\";\n\t\t\treturn c.json({ error: message, status }, coordinatorAdminMutationStatus(message));\n\t\t}\n\t});\n\n\tapp.post(\"/api/coordinator/admin/devices/:device_id/rename\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tif (!status.has_admin_secret) {\n\t\t\treturn c.json({ error: \"coordinator_admin_secret_missing\", status }, 400);\n\t\t}\n\t\tconst deviceId = String(c.req.param(\"device_id\") ?? \"\").trim();\n\t\tif (!deviceId) return c.json({ error: \"device_id required\", status }, 400);\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\", status }, 400);\n\t\t}\n\t\tconst groupId = resolveCoordinatorAdminGroup(String(body.group_id ?? \"\").trim(), status);\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\tlet displayName: string;\n\t\ttry {\n\t\t\tdisplayName = normalizeHumanPresentationName(String(body.display_name ?? \"\"), \"display_name\");\n\t\t} catch (error) {\n\t\t\treturn c.json(\n\t\t\t\t{ error: error instanceof Error ? error.message : \"display_name_invalid\", status },\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t\ttry {\n\t\t\tconst device = await coordinatorRenameDeviceAction({\n\t\t\t\tgroupId,\n\t\t\t\tdeviceId,\n\t\t\t\tdisplayName,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\tif (!device) return c.json({ error: \"device_not_found\", status }, 404);\n\t\t\treturn c.json({ ok: true, device, status });\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error), status }, 400);\n\t\t}\n\t});\n\n\tapp.post(\"/api/coordinator/admin/devices/:device_id/disable\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tif (!status.has_admin_secret) {\n\t\t\treturn c.json({ error: \"coordinator_admin_secret_missing\", status }, 400);\n\t\t}\n\t\tconst deviceId = String(c.req.param(\"device_id\") ?? \"\").trim();\n\t\tif (!deviceId) return c.json({ error: \"device_id required\", status }, 400);\n\t\tconst groupId = resolveCoordinatorAdminGroup(c.req.query(\"group_id\"), status);\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\ttry {\n\t\t\tconst ok = await coordinatorDisableDeviceAction({\n\t\t\t\tgroupId,\n\t\t\t\tdeviceId,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\tif (!ok) return c.json({ error: \"device_not_found\", status }, 404);\n\t\t\treturn c.json({ ok: true, device_id: deviceId, status });\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error), status }, 400);\n\t\t}\n\t});\n\n\tapp.post(\"/api/coordinator/admin/devices/:device_id/enable\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tif (!status.has_admin_secret) {\n\t\t\treturn c.json({ error: \"coordinator_admin_secret_missing\", status }, 400);\n\t\t}\n\t\tconst deviceId = String(c.req.param(\"device_id\") ?? \"\").trim();\n\t\tif (!deviceId) return c.json({ error: \"device_id required\", status }, 400);\n\t\tconst groupId = resolveCoordinatorAdminGroup(c.req.query(\"group_id\"), status);\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\ttry {\n\t\t\tconst ok = await coordinatorEnableDeviceAction({\n\t\t\t\tgroupId,\n\t\t\t\tdeviceId,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\tif (!ok) return c.json({ error: \"device_not_found\", status }, 404);\n\t\t\treturn c.json({ ok: true, device_id: deviceId, status });\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error), status }, 400);\n\t\t}\n\t});\n\n\t// Unified peer-enrollment entry point. Mode is chosen by an explicit\n\t// body field so a legitimate coordinator group named (for example)\n\t// `none` cannot collide with the manual-pairing path:\n\t// - `mode: \"discovered\"` (default) → promote a coordinator-discovered\n\t// device, seed scope from the :group_id group's template when\n\t// auto_seed_scope is true and the caller didn't pass an override.\n\t// - `mode: \"manual\"` → manual pairing. Accepts peer_public_key +\n\t// optional name/fingerprint/addresses; :group_id path param is\n\t// ignored and both discovery columns are left null.\n\t// See docs/plans/2026-04-22-multi-team-coordinator-groups-design.md.\n\tapp.post(\"/api/coordinator/admin/groups/:group_id/enroll-peer\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\t// Admin-secret gating happens inside the discovered branch below —\n\t\t// manual pairing only writes a local sync_peers row and doesn't need\n\t\t// coordinator-admin privileges, matching the pre-existing /peers/accept\n\t\t// path.\n\t\tconst rawGroupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tif (!rawGroupId) return c.json({ error: \"group_id required\" }, 400);\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid_json\" }, 400);\n\t\t}\n\t\tconst rawMode = String(body.mode ?? \"\")\n\t\t\t.trim()\n\t\t\t.toLowerCase();\n\t\tif (rawMode && rawMode !== \"manual\" && rawMode !== \"discovered\") {\n\t\t\treturn c.json(\n\t\t\t\t{ error: \"invalid_mode\", detail: `mode must be 'discovered' or 'manual', got ${rawMode}` },\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t\tconst mode: \"discovered\" | \"manual\" = rawMode === \"manual\" ? \"manual\" : \"discovered\";\n\t\t// Per-field normalization: distinguish \"caller did not specify\" from\n\t\t// \"caller set empty\". `undefined` = inherit (template); `null` or empty\n\t\t// array = explicit clear; non-empty array = use as-is.\n\t\tconst normalizeOverride = (value: unknown): string[] | null | undefined => {\n\t\t\tif (value === undefined) return undefined;\n\t\t\tif (value === null) return null;\n\t\t\tif (!Array.isArray(value)) return undefined;\n\t\t\tconst cleaned = value\n\t\t\t\t.map((item) => String(item ?? \"\").trim())\n\t\t\t\t.filter((item) => item.length > 0);\n\t\t\treturn cleaned.length === 0 ? null : cleaned;\n\t\t};\n\t\tconst overrideInclude = normalizeOverride(body.projects_include);\n\t\tconst overrideExclude = normalizeOverride(body.projects_exclude);\n\t\tconst scopeOverride =\n\t\t\toverrideInclude === undefined && overrideExclude === undefined\n\t\t\t\t? undefined\n\t\t\t\t: { projects_include: overrideInclude, projects_exclude: overrideExclude };\n\t\tconst store = getStore();\n\n\t\tif (mode === \"manual\") {\n\t\t\tconst peerDeviceId = String(body.peer_device_id ?? \"\").trim();\n\t\t\tconst publicKey = String(body.peer_public_key ?? \"\").trim();\n\t\t\tconst name = String(body.name ?? \"\").trim() || null;\n\t\t\tconst requestedFingerprint = String(body.fingerprint ?? \"\").trim();\n\t\t\tconst addressesInput = Array.isArray(body.peer_addresses) ? body.peer_addresses : [];\n\t\t\tconst addresses = mergeAddresses(\n\t\t\t\t[],\n\t\t\t\taddressesInput.map((item) => String(item ?? \"\").trim()).filter((item) => item.length > 0),\n\t\t\t);\n\t\t\tif (!peerDeviceId || !publicKey) {\n\t\t\t\treturn c.json({ error: \"peer_device_id_and_public_key_required\" }, 400);\n\t\t\t}\n\t\t\tconst fingerprint = requestedFingerprint || fingerprintPublicKey(publicKey);\n\t\t\tif (fingerprintPublicKey(publicKey) !== fingerprint) {\n\t\t\t\treturn c.json({ error: \"fingerprint_mismatch\" }, 400);\n\t\t\t}\n\t\t\tconst manualInclude =\n\t\t\t\toverrideInclude && overrideInclude.length > 0 ? JSON.stringify(overrideInclude) : null;\n\t\t\tconst manualExclude =\n\t\t\t\toverrideExclude && overrideExclude.length > 0 ? JSON.stringify(overrideExclude) : null;\n\t\t\tconst now = new Date().toISOString();\n\t\t\tconst d = drizzle(store.db, { schema });\n\t\t\t// Wrap the duplicate check + insert in a transaction so two concurrent\n\t\t\t// enrolls for the same peer cannot both clear the check. SQLite\n\t\t\t// serializes transactions on the write lock, so the second one sees\n\t\t\t// the committed row and returns 409 instead of racing past.\n\t\t\ttry {\n\t\t\t\tconst created = store.db.transaction(() => {\n\t\t\t\t\tconst existing = d\n\t\t\t\t\t\t.select({ peer_device_id: schema.syncPeers.peer_device_id })\n\t\t\t\t\t\t.from(schema.syncPeers)\n\t\t\t\t\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t\t\t\t\t.get();\n\t\t\t\t\tif (existing) return false;\n\t\t\t\t\td.insert(schema.syncPeers)\n\t\t\t\t\t\t.values({\n\t\t\t\t\t\t\tpeer_device_id: peerDeviceId,\n\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\tpinned_fingerprint: fingerprint,\n\t\t\t\t\t\t\tpublic_key: publicKey,\n\t\t\t\t\t\t\taddresses_json: JSON.stringify(addresses),\n\t\t\t\t\t\t\tprojects_include_json: manualInclude,\n\t\t\t\t\t\t\tprojects_exclude_json: manualExclude,\n\t\t\t\t\t\t\tcreated_at: now,\n\t\t\t\t\t\t\tlast_seen_at: now,\n\t\t\t\t\t\t\tdiscovered_via_coordinator_id: null,\n\t\t\t\t\t\t\tdiscovered_via_group_id: null,\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.run();\n\t\t\t\t\treturn true;\n\t\t\t\t})();\n\t\t\t\tif (!created) {\n\t\t\t\t\treturn c.json({ error: \"peer_exists\", detail: \"Peer is already enrolled.\" }, 409);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\t// Primary-key constraint collision is the expected race signal; the\n\t\t\t\t// first writer wins, the second gets \"peer_exists\".\n\t\t\t\tconst msg = error instanceof Error ? error.message.toLowerCase() : \"\";\n\t\t\t\tif (msg.includes(\"unique\") || msg.includes(\"primary key\")) {\n\t\t\t\t\treturn c.json({ error: \"peer_exists\", detail: \"Peer is already enrolled.\" }, 409);\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\treturn c.json({\n\t\t\t\tok: true,\n\t\t\t\tpeer_device_id: peerDeviceId,\n\t\t\t\tcreated: true,\n\t\t\t\tupdated: false,\n\t\t\t\tname,\n\t\t\t\tgroup_id: null,\n\t\t\t});\n\t\t}\n\n\t\t// Discovered mode calls out to the coordinator for reciprocal approval,\n\t\t// so it needs the admin secret. Manual mode never leaves this process.\n\t\tif (!status.has_admin_secret) {\n\t\t\treturn c.json({ error: \"coordinator_admin_secret_missing\", status }, 400);\n\t\t}\n\t\tconst peerDeviceId = String(body.peer_device_id ?? body.discovered_device_id ?? \"\").trim();\n\t\tconst fingerprint = String(body.fingerprint ?? \"\").trim();\n\t\tif (!peerDeviceId || !fingerprint) {\n\t\t\treturn c.json({ error: \"peer_device_id_and_fingerprint_required\" }, 400);\n\t\t}\n\t\ttry {\n\t\t\tconst result = await acceptDiscoveredPeer(store, {\n\t\t\t\tpeerDeviceId,\n\t\t\t\tfingerprint,\n\t\t\t\texpectedGroupId: rawGroupId,\n\t\t\t\tscopeOverride,\n\t\t\t});\n\t\t\tif (result.ok) {\n\t\t\t\treturn c.json(result);\n\t\t\t}\n\t\t\treturn c.json(\n\t\t\t\t{\n\t\t\t\t\terror: result.error,\n\t\t\t\t\tdetail: result.detail,\n\t\t\t\t\t...(result.reason ? { reason: result.reason } : {}),\n\t\t\t\t},\n\t\t\t\tresult.status as 400 | 404 | 409,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\t// acceptDiscoveredPeer shells out to the coordinator for reciprocal\n\t\t\t// approval and can throw on timeout / network / auth failures. Map\n\t\t\t// those to a structured 502 so clients get the same shape as the\n\t\t\t// legacy /api/sync/peers/accept-discovered path.\n\t\t\treturn c.json(\n\t\t\t\t{\n\t\t\t\t\terror: \"coordinator_lookup_failed\",\n\t\t\t\t\tdetail: error instanceof Error ? error.message : String(error),\n\t\t\t\t},\n\t\t\t\t502,\n\t\t\t);\n\t\t}\n\t});\n\n\t// Local-only preferences for a coordinator group — project-scope template\n\t// + auto-seed toggle applied when peers are enrolled through the group.\n\t// See docs/plans/2026-04-22-multi-team-coordinator-groups-design.md.\n\t// Local-only preferences — these rows live in the viewer's own DB and never\n\t// cross the wire to the coordinator. No admin-secret gate: the admin secret\n\t// authorizes remote coordinator mutations, not local settings.\n\tapp.get(\"/api/coordinator/admin/groups/:group_id/preferences\", (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\tconst coordinatorId = status.coordinator_url;\n\t\tif (!coordinatorId) return c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\tconst store = getStore();\n\t\tconst existing = getCoordinatorGroupPreference(store.db, coordinatorId, groupId);\n\t\tif (existing) return c.json({ preferences: existing, status });\n\t\treturn c.json({\n\t\t\tpreferences: {\n\t\t\t\tcoordinator_id: coordinatorId,\n\t\t\t\tgroup_id: groupId,\n\t\t\t\tprojects_include: null,\n\t\t\t\tprojects_exclude: null,\n\t\t\t\tauto_seed_scope: true,\n\t\t\t\tdefault_space_scope_id: null,\n\t\t\t\tauto_grant_default_space_on_join: false,\n\t\t\t\tupdated_at: null,\n\t\t\t},\n\t\t\tstatus,\n\t\t});\n\t});\n\n\tapp.put(\"/api/coordinator/admin/groups/:group_id/preferences\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tconst groupId = String(c.req.param(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\tconst coordinatorId = status.coordinator_url;\n\t\tif (!coordinatorId) return c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid_json\", status }, 400);\n\t\t}\n\t\tconst normalizeList = (value: unknown): string[] | null | undefined => {\n\t\t\tif (value === undefined) return undefined;\n\t\t\tif (value === null) return null;\n\t\t\tif (!Array.isArray(value)) return undefined;\n\t\t\tconst cleaned = value\n\t\t\t\t.map((item) => String(item ?? \"\").trim())\n\t\t\t\t.filter((item) => item.length > 0);\n\t\t\treturn cleaned.length === 0 ? null : cleaned;\n\t\t};\n\t\tconst autoSeed = typeof body.auto_seed_scope === \"boolean\" ? body.auto_seed_scope : undefined;\n\t\tconst autoGrantDefaultSpace =\n\t\t\ttypeof body.auto_grant_default_space_on_join === \"boolean\"\n\t\t\t\t? body.auto_grant_default_space_on_join\n\t\t\t\t: undefined;\n\t\tconst defaultSpaceScopeId =\n\t\t\tbody.default_space_scope_id === undefined\n\t\t\t\t? undefined\n\t\t\t\t: optionalViewerString(body, \"default_space_scope_id\");\n\t\tif (autoGrantDefaultSpace === true && !defaultSpaceScopeId) {\n\t\t\treturn c.json(\n\t\t\t\t{\n\t\t\t\t\terror: \"default_space_scope_id_required_for_auto_grant\",\n\t\t\t\t\tstatus,\n\t\t\t\t},\n\t\t\t\t400,\n\t\t\t);\n\t\t}\n\t\tconst store = getStore();\n\t\ttry {\n\t\t\tconst preferences = upsertCoordinatorGroupPreference(store.db, {\n\t\t\t\tcoordinator_id: coordinatorId,\n\t\t\t\tgroup_id: groupId,\n\t\t\t\tprojects_include: normalizeList(body.projects_include),\n\t\t\t\tprojects_exclude: normalizeList(body.projects_exclude),\n\t\t\t\tauto_seed_scope: autoSeed,\n\t\t\t\tdefault_space_scope_id: defaultSpaceScopeId,\n\t\t\t\tauto_grant_default_space_on_join: autoGrantDefaultSpace,\n\t\t\t});\n\t\t\treturn c.json({ preferences, status });\n\t\t} catch (error) {\n\t\t\tconst msg = error instanceof Error ? error.message : String(error);\n\t\t\treturn c.json({ error: msg, status }, 400);\n\t\t}\n\t});\n\n\tapp.post(\"/api/coordinator/admin/devices/:device_id/remove\", async (c) => {\n\t\tconst config = readCoordinatorSyncConfig();\n\t\tconst status = coordinatorAdminStatusPayload(config);\n\t\tif (status.readiness === \"not_configured\") {\n\t\t\treturn c.json({ error: \"coordinator_not_configured\", status }, 400);\n\t\t}\n\t\tif (!status.has_admin_secret) {\n\t\t\treturn c.json({ error: \"coordinator_admin_secret_missing\", status }, 400);\n\t\t}\n\t\tconst deviceId = String(c.req.param(\"device_id\") ?? \"\").trim();\n\t\tif (!deviceId) return c.json({ error: \"device_id required\", status }, 400);\n\t\tconst groupId = resolveCoordinatorAdminGroup(c.req.query(\"group_id\"), status);\n\t\tif (!groupId) return c.json({ error: \"group_id required\", status }, 400);\n\t\ttry {\n\t\t\tconst ok = await coordinatorRemoveDeviceAction({\n\t\t\t\tgroupId,\n\t\t\t\tdeviceId,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\tif (!ok) return c.json({ error: \"device_not_found\", status }, 404);\n\t\t\treturn c.json({ ok: true, device_id: deviceId, status });\n\t\t} catch (error) {\n\t\t\treturn c.json({ error: error instanceof Error ? error.message : String(error), status }, 400);\n\t\t}\n\t});\n\n\tapp.get(\"/api/sync/bootstrap-grants\", async (c) => {\n\t\tconst groupId = String(c.req.query(\"group_id\") ?? \"\").trim();\n\t\tif (!groupId) return c.json({ error: \"group_id_required\" }, 400);\n\t\tconst config = readCoordinatorSyncConfig();\n\t\ttry {\n\t\t\tconst items = await coordinatorListBootstrapGrantsAction({\n\t\t\t\tgroupId,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\treturn c.json({ items });\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"unknown\";\n\t\t\treturn c.json({ error: message }, 500);\n\t\t}\n\t});\n\n\tapp.post(\"/api/sync/bootstrap-grants/revoke\", async (c) => {\n\t\tlet body: Record<string, unknown>;\n\t\ttry {\n\t\t\tbody = await c.req.json<Record<string, unknown>>();\n\t\t} catch {\n\t\t\treturn c.json({ error: \"invalid json\" }, 400);\n\t\t}\n\t\tconst grantId = String(body.grant_id ?? \"\").trim();\n\t\tif (!grantId) return c.json({ error: \"grant_id_required\" }, 400);\n\t\tconst config = readCoordinatorSyncConfig();\n\t\ttry {\n\t\t\tconst ok = await coordinatorRevokeBootstrapGrantAction({\n\t\t\t\tgrantId,\n\t\t\t\tremoteUrl: config.syncCoordinatorUrl || null,\n\t\t\t\tadminSecret: config.syncCoordinatorAdminSecret || null,\n\t\t\t});\n\t\t\tif (!ok) return c.json({ error: \"grant_not_found\" }, 404);\n\t\t\treturn c.json({ ok: true, grant_id: grantId });\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"unknown\";\n\t\t\treturn c.json({ error: message }, 500);\n\t\t}\n\t});\n\n\t// DELETE /api/sync/peers/:peer_device_id\n\tapp.delete(\"/api/sync/peers/:peer_device_id\", (c) => {\n\t\tconst store = getStore();\n\t\t{\n\t\t\tconst d = drizzle(store.db, { schema });\n\t\t\tconst peerDeviceId = c.req.param(\"peer_device_id\")?.trim();\n\t\t\tif (!peerDeviceId) return c.json({ error: \"peer_device_id required\" }, 400);\n\t\t\tconst exists = d\n\t\t\t\t.select({ peer_device_id: schema.syncPeers.peer_device_id })\n\t\t\t\t.from(schema.syncPeers)\n\t\t\t\t.where(eq(schema.syncPeers.peer_device_id, peerDeviceId))\n\t\t\t\t.get();\n\t\t\tif (!exists) return c.json({ error: \"peer not found\" }, 404);\n\t\t\td.delete(schema.replicationCursors)\n\t\t\t\t.where(eq(schema.replicationCursors.peer_device_id, peerDeviceId))\n\t\t\t\t.run();\n\t\t\td.delete(schema.syncPeers).where(eq(schema.syncPeers.peer_device_id, peerDeviceId)).run();\n\t\t\treturn c.json({ ok: true });\n\t\t}\n\t});\n\n\treturn app;\n}\n","import {\n\tgetUpdateStatus as defaultGetUpdateStatus,\n\tdetectInstallKind,\n\ttype GetUpdateStatusOptions,\n\ttype UpdateStatus,\n\tVERSION,\n} from \"@codemem/core\";\nimport { Hono } from \"hono\";\n\nexport interface UpdateStatusRoutesOptions {\n\tgetUpdateStatus?: (options: GetUpdateStatusOptions) => Promise<UpdateStatus>;\n}\n\nexport function updateStatusRoutes(options: UpdateStatusRoutesOptions = {}) {\n\tconst getUpdateStatus = options.getUpdateStatus ?? defaultGetUpdateStatus;\n\tconst app = new Hono();\n\n\tapp.get(\"/api/update-status\", async (c) => {\n\t\ttry {\n\t\t\tconst installKind = detectInstallKind({\n\t\t\t\tentryPath: process.argv[1] ?? \"\",\n\t\t\t\tenv: process.env,\n\t\t\t});\n\t\t\tconst status = await getUpdateStatus({\n\t\t\t\tcurrentVersion: VERSION,\n\t\t\t\tinstallKind,\n\t\t\t});\n\t\t\treturn c.json(status);\n\t\t} catch {\n\t\t\treturn c.json({ error: \"Update status unavailable.\" }, 503);\n\t\t}\n\t});\n\n\treturn app;\n}\n","/**\n * @codemem/server — HTTP server (viewer, sync, API).\n *\n * Single HTTP server handling viewer routes and sync daemon.\n * Shares one better-sqlite3 connection between viewer and sync.\n * Embedding inference runs in a worker_thread (lazy-started).\n *\n * Entry: `codemem serve`\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type {\n\tDeviceIdentityCoordinatorEvidence,\n\tGetUpdateStatusOptions,\n\tObserverClient,\n\tUpdateStatus,\n} from \"@codemem/core\";\nimport { MemoryStore, type RawEventSweeper, resolveDbPath, VERSION } from \"@codemem/core\";\nimport { serveStatic } from \"@hono/node-server/serve-static\";\nimport { Hono } from \"hono\";\nimport { originGuard, preflightHandler } from \"./middleware.js\";\nimport {\n\tcreateInMemoryRequestRateLimiter,\n\ttype InMemoryRequestRateLimiter,\n} from \"./request-rate-limit.js\";\nimport { configRoutes } from \"./routes/config.js\";\nimport { diagnosticsRoutes } from \"./routes/diagnostics.js\";\nimport { healthRoutes } from \"./routes/health.js\";\nimport { memoryRoutes } from \"./routes/memory.js\";\nimport { observerStatusRoutes } from \"./routes/observer-status.js\";\nimport { packTransportRoutes } from \"./routes/pack.js\";\nimport { rawEventsRoutes } from \"./routes/raw-events.js\";\nimport { statsRoutes } from \"./routes/stats.js\";\nimport { type SyncRoutesOptions, syncProtocolRoutes, syncRoutes } from \"./routes/sync.js\";\nimport {\n\ttype LegacyTeamCompletionDependencies,\n\ttype LegacyTeamConfiguredGroupSnapshotLoader,\n\tTEAM_SETUP_ROUTE_PREFIX,\n\tteamSetupRoutes,\n} from \"./routes/team-setup.js\";\nimport { updateStatusRoutes } from \"./routes/update-status.js\";\n\nexport type {\n\tAdvancePendingProjectSharesResult,\n\tAdvanceProjectShareOperationResult,\n\tRecipientPolicyReconciliationReadModel,\n\tRecipientPolicyReconciliationReadState,\n\tReconcileConfiguredCoordinatorEnrollmentResult,\n\tReconcileRecipientPolicyProjectsResult,\n} from \"./routes/sync.js\";\nexport {\n\tadvancePendingProjectShares,\n\tadvanceProjectShareOperation,\n\tcreateRecipientPolicyReconcilerEffects,\n\tlistRecipientPolicyReconciliationStatus,\n\trecipientPolicyCapabilityFromStatus,\n\treconcileConfiguredCoordinatorEnrollment,\n\treconcileRecipientPolicyProjects,\n} from \"./routes/sync.js\";\nexport type {\n\tLegacyTeamSetupActionBlockedReasonV1,\n\tLegacyTeamSetupActionGateV1,\n\tLegacyTeamSetupCandidateSummaryV1,\n\tLegacyTeamSetupDetailResponseV1,\n\tLegacyTeamSetupDeviceV1,\n\tLegacyTeamSetupErrorResponseV1,\n\tLegacyTeamSetupFinishResponseV1,\n\tLegacyTeamSetupIdentityChoiceV1,\n\tLegacyTeamSetupMutationResponseV1,\n\tLegacyTeamSetupPendingCandidateSummaryV1,\n\tLegacyTeamSetupProjectV1,\n\tLegacyTeamSetupSummaryResponseV1,\n\tLegacyTeamSetupViewerAccessDeltaV1,\n\tLegacyTeamSetupViewV1,\n} from \"./routes/team-setup.js\";\n\nexport { VERSION };\n\n/** Shared store instance — SQLite WAL mode handles concurrent reads safely. */\nlet sharedStore: MemoryStore | null = null;\n\n/** Get (or create) the shared store instance. Exported so the sweeper can share it. */\nexport function getStore(): MemoryStore {\n\tif (!sharedStore) {\n\t\tsharedStore = new MemoryStore(resolveDbPath());\n\t}\n\treturn sharedStore;\n}\n\n/** Close the shared store (called on shutdown). */\nexport function closeStore(): void {\n\tsharedStore?.close();\n\tsharedStore = null;\n}\n\n/**\n * Create the Hono app with all viewer routes.\n * Exported for testing — pass a custom store factory to inject test DBs.\n */\nexport interface AppOptions {\n\tstoreFactory?: () => MemoryStore;\n\tsweeper?: RawEventSweeper | null;\n\tobserver?: ObserverClient | null;\n\tgetUpdateStatus?: (options: GetUpdateStatusOptions) => Promise<UpdateStatus>;\n\tloadDeviceIdentityCoordinatorEvidence?: () => Promise<DeviceIdentityCoordinatorEvidence>;\n\tloadLegacyTeamConfiguredGroupSnapshots?: LegacyTeamConfiguredGroupSnapshotLoader;\n\tteamSetupCompletionDependencies?: LegacyTeamCompletionDependencies | null;\n\treadCoordinatorConfig?: SyncRoutesOptions[\"readCoordinatorConfig\"];\n\trenameCoordinatorGroup?: SyncRoutesOptions[\"renameCoordinatorGroup\"];\n\tsyncRequestRateLimit?: {\n\t\tlimiter?: InMemoryRequestRateLimiter;\n\t\treadLimit?: number;\n\t\tmutationLimit?: number;\n\t\tunauthenticatedReadLimit?: number;\n\t\tunauthenticatedMutationLimit?: number;\n\t};\n\tgetSyncRuntimeStatus?: () => {\n\t\tphase:\n\t\t\t| \"starting\"\n\t\t\t| \"running\"\n\t\t\t| \"stopping\"\n\t\t\t| \"error\"\n\t\t\t| \"disabled\"\n\t\t\t| \"rebootstrapping\"\n\t\t\t| \"needs_attention\"\n\t\t\t| null;\n\t\tdetail?: string | null;\n\t} | null;\n}\n\nfunction registerStaticRoutes(app: Hono): void {\n\tconst staticRoot =\n\t\tprocess.env.CODEMEM_VIEWER_STATIC_DIR ?? join(import.meta.dirname ?? \".\", \"../static\");\n\n\tapp.use(\"/assets/*\", async (c, next) => {\n\t\tc.header(\"Cache-Control\", \"no-cache\");\n\t\tawait next();\n\t});\n\tapp.use(\n\t\t\"/assets/*\",\n\t\tserveStatic({\n\t\t\troot: staticRoot,\n\t\t\trewriteRequestPath: (path) => path.replace(/^\\/assets/, \"\"),\n\t\t\tprecompressed: true,\n\t\t}),\n\t);\n\n\tconst indexPath = join(staticRoot, \"index.html\");\n\tif (!existsSync(indexPath)) {\n\t\tthrow new Error(\n\t\t\t`Viewer assets missing at ${indexPath}. Run \\`pnpm build\\` from the repo root before starting the viewer.`,\n\t\t);\n\t}\n\tconst indexHtml = readFileSync(indexPath, \"utf-8\");\n\tapp.get(\"*\", (c) => {\n\t\tif (c.req.path.startsWith(\"/api/\")) {\n\t\t\treturn c.json({ error: \"not found\" }, 404);\n\t\t}\n\t\tc.header(\"Cache-Control\", \"no-store\");\n\t\treturn c.html(indexHtml);\n\t});\n}\n\nexport function createApp(opts?: AppOptions) {\n\tconst storeFactory = opts?.storeFactory ?? getStore;\n\tconst sweeper = opts?.sweeper ?? null;\n\tconst observer = opts?.observer ?? null;\n\tconst getSyncRuntimeStatus = opts?.getSyncRuntimeStatus ?? (() => null);\n\tlet invalidateTeamSetupSummary = () => {};\n\tconst app = new Hono();\n\n\t// CORS / origin guard\n\tapp.use(\"*\", preflightHandler());\n\tapp.use(\"*\", originGuard({ unsafeGetPathPrefixes: [TEAM_SETUP_ROUTE_PREFIX] }));\n\n\t// API routes\n\tapp.route(\"/\", healthRoutes(storeFactory));\n\tapp.route(\"/\", diagnosticsRoutes(storeFactory));\n\tapp.route(\"/\", statsRoutes(storeFactory));\n\tapp.route(\"/\", memoryRoutes(storeFactory));\n\tapp.route(\"/\", packTransportRoutes(storeFactory));\n\tapp.route(\n\t\t\"/\",\n\t\tobserverStatusRoutes({\n\t\t\tgetStore: storeFactory,\n\t\t\tgetSweeper: () => sweeper,\n\t\t\tgetObserver: () => observer,\n\t\t}),\n\t);\n\tapp.route(\"/\", configRoutes({ getSweeper: () => sweeper }));\n\tapp.route(\"/\", rawEventsRoutes(storeFactory, sweeper));\n\tapp.route(\n\t\t\"/\",\n\t\tsyncRoutes(storeFactory, getSyncRuntimeStatus, {\n\t\t\tloadDeviceIdentityCoordinatorEvidence: opts?.loadDeviceIdentityCoordinatorEvidence,\n\t\t\tonRecipientPolicyTeamRenamed: () => invalidateTeamSetupSummary(),\n\t\t\treadCoordinatorConfig: opts?.readCoordinatorConfig,\n\t\t\trenameCoordinatorGroup: opts?.renameCoordinatorGroup,\n\t\t}),\n\t);\n\tapp.route(\n\t\t\"/\",\n\t\tteamSetupRoutes({\n\t\t\tgetStore: storeFactory,\n\t\t\tloadLegacyTeamConfiguredGroupSnapshots: opts?.loadLegacyTeamConfiguredGroupSnapshots,\n\t\t\tcompletionDependencies: opts?.teamSetupCompletionDependencies,\n\t\t\treadCoordinatorConfig: opts?.readCoordinatorConfig,\n\t\t\tregisterSummaryInvalidator: (invalidate) => {\n\t\t\t\tinvalidateTeamSetupSummary = invalidate;\n\t\t\t},\n\t\t}),\n\t);\n\tapp.route(\"/\", updateStatusRoutes({ getUpdateStatus: opts?.getUpdateStatus }));\n\n\tregisterStaticRoutes(app);\n\n\treturn app;\n}\n\n/**\n * Create the Hono app for peer-to-peer sync protocol routes only.\n *\n * This app is bound to a separate network-accessible listener\n * (default 0.0.0.0:7337) so remote peers can reach the sync\n * endpoints without exposing the viewer UI or local API routes.\n *\n * No CORS/origin guard is applied — sync requests are authenticated\n * via cryptographic signature verification instead.\n */\nexport function createSyncApp(opts?: AppOptions) {\n\tconst storeFactory = opts?.storeFactory ?? getStore;\n\tconst requestRateLimit = opts?.syncRequestRateLimit ?? {};\n\tconst rateLimiter = requestRateLimit.limiter ?? createInMemoryRequestRateLimiter();\n\tconst readLimit = Math.max(1, Math.trunc(requestRateLimit.readLimit ?? 120));\n\tconst mutationLimit = Math.max(1, Math.trunc(requestRateLimit.mutationLimit ?? 30));\n\tconst app = new Hono();\n\tapp.route(\n\t\t\"/\",\n\t\tsyncProtocolRoutes(storeFactory, {\n\t\t\trouteRateLimit: {\n\t\t\t\tlimiter: rateLimiter,\n\t\t\t\treadLimit,\n\t\t\t\tmutationLimit,\n\t\t\t\tunauthenticatedReadLimit: Math.max(\n\t\t\t\t\t1,\n\t\t\t\t\tMath.trunc(requestRateLimit.unauthenticatedReadLimit ?? Math.min(20, readLimit)),\n\t\t\t\t),\n\t\t\t\tunauthenticatedMutationLimit: Math.max(\n\t\t\t\t\t1,\n\t\t\t\t\tMath.trunc(requestRateLimit.unauthenticatedMutationLimit ?? Math.min(10, mutationLimit)),\n\t\t\t\t),\n\t\t\t},\n\t\t}),\n\t);\n\n\t// Catch-all — return generic 404 to avoid fingerprinting the server.\n\tapp.all(\"*\", (c) => c.json({ error: \"not found\" }, 404));\n\n\treturn app;\n}\n\n// No auto-start — the CLI's `serve` command owns server startup.\n"],"mappings":";;;;;;;;;;;;AAaA,IAAM,iCAAiB,IAAI,IAAI;CAAC;CAAa;CAAa;AAAK,CAAC;;;;;AAMhE,SAAS,iBAAiB,QAAyB;CAClD,IAAI;CACJ,IAAI;EACH,MAAM,IAAI,IAAI,MAAM;CACrB,QAAQ;EACP,OAAO;CACR;CACA,IAAI,IAAI,aAAa,WAAW,IAAI,aAAa,UAAU,OAAO;CAClE,IAAI,IAAI,YAAY,IAAI,UAAU,OAAO;CACzC,MAAM,WAAW,IAAI,SAAS,WAAW,GAAG,IAAI,IAAI,SAAS,MAAM,GAAG,EAAE,IAAI,IAAI;CAChF,OAAO,eAAe,IAAI,QAAQ;AACnC;;AAGA,IAAM,iCAAiB,IAAI,IAAI;CAAC;CAAQ;CAAU;CAAS;AAAK,CAAC;;;;;;;;;AAUjE,SAAS,sBAAsB,GAAqB;CACnD,MAAM,gBAAgB,EAAE,IAAI,OAAO,gBAAgB,KAAK,GAAA,CAAI,KAAK,CAAC,CAAC,YAAY;CAC/E,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