{"version":3,"file":"index.mjs","names":["__dxlog_file","__dxlog_file","__dxlog_file","isValidDocumentId","Array","__dxlog_file","__dxlog_file","_decorate","MIGRATIONS","init","MIGRATIONS_TABLE","__dxlog_file","MIGRATIONS","MIGRATIONS_TABLE","__dxlog_file","__dxlog_file","__dxlog_file","MIGRATIONS","__dxlog_file","headsEquals","_decorate","__dxlog_file","__dxlog_file","__dxlog_file","A","__dxlog_file","__dxlog_file","A","__dxlog_file","isIndexingDisabled","__dxlog_file","__dxlog_file","__dxlog_file","A","A","__dxlog_file","__dxlog_file","MAX_DEPTH_FOR_DELETION_TRACING","MAX_DEPTH_FOR_CHILD_OF_TRACING","MAX_DEPTH_FOR_STRONG_DEP_TRACING","extractQueueRefs","extractQueueWindow","BEFORE_FIRST_POSITION","parseCursor","__dxlog_file","__dxlog_file","_decorate","init","spaceRoot","directorySnapshots","__dxlog_file","__dxlog_file","A","__dxlog_file","__dxlog_file","A","_decorate","__dxlog_file","_decorate","RouterMessageSchema"],"sources":["../../src/query/object-state.ts","../../src/db-host/change-record.ts","../../src/db-host/automerge-data-source.ts","../../src/util.ts","../../src/automerge/errors.ts","../../src/automerge/space-collection.ts","../../src/automerge/collection-synchronizer.ts","../../src/automerge/handle-state.ts","../../src/automerge/document-lease.ts","../../src/automerge/network-protocol.ts","../../src/automerge/echo-network-adapter.ts","../../src/automerge/quarantine.ts","../../src/migrations/heads/index.ts","../../src/automerge/sqlite-heads-store.ts","../../src/automerge/subduction-migrations/0002_self_checkpointed_fragments.ts","../../src/automerge/subduction-migrations/0001_delete_remote_heads.ts","../../src/automerge/subduction-migrations/index.ts","../../src/automerge/automerge-host.ts","../../src/automerge/mesh-echo-replicator-connection.ts","../../src/automerge/mesh-echo-replicator.ts","../../src/automerge/echo-replicator.ts","../../src/automerge/echo-data-monitor.ts","../../src/db-host/documents-synchronizer.ts","../../src/db-host/data-service.ts","../../src/db-host/merge-core.ts","../../src/db-host/convergence-key-merge.ts","../../src/db-host/deletion.ts","../../src/db-host/feed-data-source.ts","../../src/db-host/index-scheduler.ts","../../src/db-host/index-status.ts","../../src/db-host/retirement.ts","../../src/db-host/inline-objects.ts","../../src/db-host/invalidation-hint.ts","../../src/db-host/local-feed-service.ts","../../src/query/changes-executor.ts","../../src/query/sql/compile.ts","../../src/query/query-executor.ts","../../src/db-host/query-service.ts","../../src/migrations/space-state/index.ts","../../src/db-host/automerge-metrics.ts","../../src/db-host/database-root.ts","../../src/db-host/space-state-manager.ts","../../src/db-host/echo-host.ts","../../src/db-host/sqlite-health-check.ts","../../src/edge/echo-edge-subduction-replicator.ts"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\nexport const isSaved = (storedHeads: readonly string[] | undefined, heads: readonly string[]): boolean =>\n  storedHeads !== undefined && sameHeads(storedHeads, heads);\n\nexport const sameHeads = (left: readonly string[], right: readonly string[]): boolean =>\n  left.length === right.length && left.every((head) => right.includes(head));\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport type * as A from '@automerge/automerge';\nimport type * as Schema from 'effect/Schema';\n\nimport { type Change } from '@dxos/echo';\n\nexport type ChangeRecord = Schema.Schema.Type<typeof Change.Change>;\n\n/** A document change as `Filter.changes` reports it, or `null` for one made without a clock (time 0). */\nexport const toChangeRecord = (meta: A.ChangeMetadata): ChangeRecord | null =>\n  meta.time > 0\n    ? {\n        key: meta.hash,\n        source: 'document',\n        time: meta.time * 1000,\n        actor: meta.actor,\n        seq: meta.seq,\n        ops: meta.maxOp - meta.startOp + 1,\n      }\n    : null;\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport * as A from '@automerge/automerge';\nimport { type DocumentId, interpretAsDocumentId, isValidAutomergeUrl } from '@automerge/automerge-repo';\nimport * as Effect from 'effect/Effect';\n\nimport { type Context } from '@dxos/context';\nimport { DatabaseDirectory, SpaceDocVersion, backingJson, directoryJson } from '@dxos/echo-protocol';\nimport { objectStructureToJson } from '@dxos/echo/internal';\nimport {\n  type DataSourceCursor,\n  type DocumentActivity,\n  type IndexDataSource,\n  type IndexerObject,\n} from '@dxos/index-core';\nimport { type SpaceId } from '@dxos/keys';\nimport { log } from '@dxos/log';\n\nimport { type AutomergeHost } from '../automerge/index.ts';\nimport { isSaved } from '../query/object-state.ts';\nimport { toChangeRecord } from './change-record.ts';\n\nconst HEADS_DELIMITER = '|';\n\n/**\n * Codec for serializing/deserializing Automerge heads to cursor strings.\n */\nexport const headsCodec = {\n  /**\n   * Serialize automerge heads to a cursor string.\n   * Heads are sorted to ensure consistent comparison.\n   */\n  encode: (heads: A.Heads): string => [...heads].sort().join(HEADS_DELIMITER),\n\n  /**\n   * Deserialize a cursor string back to heads array.\n   */\n  decode: (cursor: string): string[] => (cursor ? cursor.split(HEADS_DELIMITER) : []),\n};\n\n/**\n * Check if document has changed by comparing cursor with current heads.\n */\nconst hasChanged = (cursor: string | undefined, currentHeads: A.Heads): boolean => {\n  if (!cursor) {\n    return true; // New document.\n  }\n  return cursor !== headsCodec.encode(currentHeads);\n};\n\nexport type AutomergeDataSourceOptions = {\n  isBranchDocument?: (documentId: DocumentId) => boolean;\n  /**\n   * Stores a space root's directory JSON at heads its document is saved at, so the root can be opened from it\n   * without loading Automerge. Called for each changed document `isSpaceRoot` names.\n   */\n  directories?: {\n    isSpaceRoot: (documentId: DocumentId) => boolean;\n    store: (documentId: DocumentId, snapshot: { heads: A.Heads; json: string }) => Promise<void>;\n  };\n};\n\n/**\n * Data source that fetches objects from AutomergeHost.\n * Iterates all documents from SqliteHeadsStore and tracks document heads as cursors to detect changes.\n */\nexport class AutomergeDataSource implements IndexDataSource {\n  readonly sourceName = 'automerge';\n\n  readonly #automergeHost: AutomergeHost;\n  readonly #isBranchDocument: ((documentId: DocumentId) => boolean) | undefined;\n  readonly #directories: AutomergeDataSourceOptions['directories'];\n\n  /**\n   * Heads for every document, captured once per `IndexEngine.update` pass. `listDocumentHeads()` is\n   * an unbounded scan of `automerge_heads` and is cursor-independent, so re-reading it for each\n   * index in a pass doubles the cost for an identical result. Held only for the pass — a document\n   * saved mid-pass is still picked up next pass, since `documentsSaved` schedules one.\n   */\n  #passHeads: Promise<{ documentId: DocumentId; heads: A.Heads }[]> | null = null;\n  #passActive = false;\n\n  /**\n   * Branch documents seen as a space root's registry, across every pass. A merge lands a branch's\n   * changes in the main document under the same hashes, so counting the branch document too would\n   * double-count every merged change.\n   */\n  readonly #branchDocumentIds = new Set<DocumentId>();\n\n  constructor(automergeHost: AutomergeHost, options?: AutomergeDataSourceOptions) {\n    this.#automergeHost = automergeHost;\n    this.#isBranchDocument = options?.isBranchDocument;\n    this.#directories = options?.directories;\n  }\n\n  beginPass(): void {\n    this.#passActive = true;\n    this.#passHeads = null;\n  }\n\n  endPass(): void {\n    this.#passActive = false;\n    this.#passHeads = null;\n  }\n\n  /** Caches the promise, not the result, so concurrent callers in one pass share a single scan. */\n  #listAllDocumentHeads(): Promise<{ documentId: DocumentId; heads: A.Heads }[]> {\n    if (this.#passHeads) {\n      return this.#passHeads;\n    }\n    const scan = (async () => {\n      const entries: { documentId: DocumentId; heads: A.Heads }[] = [];\n      for await (const entry of this.#automergeHost.listDocumentHeads()) {\n        entries.push(entry);\n      }\n      return entries;\n    })();\n    if (this.#passActive) {\n      this.#passHeads = scan;\n    }\n    return scan;\n  }\n\n  getChangedObjects(\n    ctx: Context,\n    cursors: DataSourceCursor[],\n    opts?: { limit?: number; activity?: boolean; objects?: boolean; countCatchUp?: boolean },\n  ): Effect.Effect<{\n    objects: IndexerObject[];\n    cursors: DataSourceCursor[];\n    activity?: DocumentActivity[];\n    more: boolean;\n    catchUp?: number;\n  }> {\n    return Effect.gen({ self: this }, function* () {\n      // Build a map of documentId -> cursor for quick lookup.\n      const cursorMap = new Map<string, string>();\n      for (const cursor of cursors) {\n        if (cursor.resourceId) {\n          cursorMap.set(cursor.resourceId, String(cursor.cursor));\n        }\n      }\n\n      // Find changed documents by diffing every document's heads against this index's cursors. The\n      // scan is shared across the pass; the diff is not, since cursors are per-index.\n      const allDocumentHeads = yield* Effect.promise(() => this.#listAllDocumentHeads());\n      const changedDocuments: { documentId: DocumentId; heads: A.Heads }[] = [];\n      const limit = opts?.limit ?? Infinity;\n      let more = false;\n      let catchUp = opts?.countCatchUp ? 0 : undefined;\n      for (const { documentId, heads } of allDocumentHeads) {\n        const cursor = cursorMap.get(documentId);\n        if (hasChanged(cursor, heads)) {\n          if (changedDocuments.length >= limit) {\n            more = true;\n            if (catchUp === undefined) {\n              break;\n            }\n            if (cursor) {\n              catchUp++;\n            }\n            continue;\n          }\n          changedDocuments.push({ documentId, heads });\n        }\n      }\n\n      // Load changed documents and extract objects.\n      const objects: IndexerObject[] = [];\n      const updatedCursors: DataSourceCursor[] = [];\n      const pendingActivity = new Map<DocumentId, DocumentActivity>();\n      const branchDiscards = new Map<DocumentId, DocumentActivity>();\n      const extractObjects = opts?.objects !== false;\n\n      for (const { documentId, heads: docHeads } of changedDocuments) {\n        const firstObject = objects.length;\n        let docSpaceId: SpaceId | null = null;\n        const markRead = (spaceId: SpaceId | null) =>\n          updatedCursors.push({ spaceId, resourceId: documentId, cursor: headsCodec.encode(docHeads) });\n        try {\n          using lease = yield* Effect.promise(() => this.#automergeHost.loadDoc<DatabaseDirectory>(ctx, documentId));\n          if (!lease) {\n            continue;\n          }\n          const doc: DatabaseDirectory = lease.doc();\n\n          const spaceId = yield* Effect.promise(() =>\n            DatabaseDirectory.getSpaceId(doc).catch((err) => {\n              log.warn('document space id could not be derived', { documentId, err });\n              return null;\n            }),\n          );\n          docSpaceId = spaceId;\n\n          if (doc.version !== SpaceDocVersion.CURRENT || !spaceId) {\n            markRead(spaceId);\n            continue;\n          }\n\n          if (doc.branches) {\n            for (const url of DatabaseDirectory.getAllBranchDocUrls(doc)) {\n              if (!isValidAutomergeUrl(url)) {\n                continue;\n              }\n              const branchId = interpretAsDocumentId(url);\n              this.#branchDocumentIds.add(branchId);\n              branchDiscards.set(branchId, { spaceId, documentId: branchId, full: true, changes: [] });\n            }\n          }\n\n          const existingCursor = cursorMap.get(documentId);\n          const { changedObjectIds, updatedAt, changesMeta } = inspectDocChanges(doc, existingCursor, {\n            changes: !!opts?.activity,\n            objects: extractObjects,\n          });\n\n          const docObjects = extractObjects ? (doc.objects ?? {}) : {};\n          const readHeads = A.getHeads(doc);\n          const atSavedHeads = !this.#branchDocumentIds.has(documentId) && isSaved(docHeads, readHeads);\n          for (const [objectId, structure] of Object.entries(docObjects)) {\n            if (changedObjectIds && !changedObjectIds.has(objectId)) {\n              continue;\n            }\n            const storedCreatedAt = structure.system?.createdAt;\n            const data = objectStructureToJson(objectId, structure);\n            objects.push({\n              spaceId,\n              documentId,\n              queueId: null,\n              queueNamespace: null,\n              queuePosition: null,\n              recordId: null,\n              data,\n              createdAt: typeof storedCreatedAt === 'number' ? storedCreatedAt : null,\n              updatedAt,\n              heads: atSavedHeads && backingJson(doc, structure, data) !== undefined ? docHeads : undefined,\n              version: readHeads,\n            });\n          }\n\n          const directories = this.#directories;\n          const json = atSavedHeads && directories?.isSpaceRoot(documentId) ? directoryJson(doc) : undefined;\n          if (directories && json !== undefined) {\n            yield* Effect.promise(() =>\n              directories\n                .store(documentId, { heads: readHeads, json })\n                .catch((err) => log.warn('directory snapshot not stored', { documentId, err })),\n            );\n          }\n\n          markRead(spaceId);\n          if (opts?.activity) {\n            pendingActivity.set(documentId, {\n              spaceId,\n              documentId,\n              full: existingCursor === undefined,\n              changes: changesMeta.flatMap((meta) => {\n                const change = toChangeRecord(meta);\n                return change ? [{ time: change.time, ops: change.ops }] : [];\n              }),\n            });\n          }\n        } catch (error) {\n          log.error('Error loading document for indexing', { documentId, error });\n          objects.length = firstObject;\n          markRead(docSpaceId);\n        }\n      }\n\n      if (!opts?.activity) {\n        return { objects, cursors: updatedCursors, more, catchUp };\n      }\n      const activity: DocumentActivity[] = [...branchDiscards.values()];\n      for (const [documentId, entry] of pendingActivity) {\n        if (branchDiscards.has(documentId)) {\n          continue;\n        }\n        const isBranch = this.#branchDocumentIds.has(documentId) || this.#isBranchDocument?.(documentId);\n        activity.push(isBranch ? { ...entry, full: true, changes: [] } : entry);\n      }\n      return { objects, cursors: updatedCursors, activity, more, catchUp };\n    });\n  }\n}\n\n/**\n * Determines which ECHO objects changed, the document-level max change timestamp, and (when\n * `opts.changes` is set) the Automerge changes behind them.\n *\n * Uses `A.diff` to extract changed objectIds from patch paths (`[\"objects\", objectId, ...]`),\n * and `A.getChangesMetaSince` for both the max timestamp (second-level precision) and the change\n * metadata.\n * Returns `changedObjectIds: null` when all objects should be indexed (new document).\n */\nconst inspectDocChanges = (\n  doc: DatabaseDirectory,\n  existingCursor: string | undefined,\n  opts: { changes: boolean; objects: boolean },\n): { changedObjectIds: Set<string> | null; updatedAt: number; changesMeta: A.ChangeMetadata[] } => {\n  if (!existingCursor) {\n    // On first indexing we don't have a prior cursor so we can't isolate per-object\n    // change timestamps.  Fall back to the current wall-clock time so that freshly\n    // indexed objects sort \"recent\" in `Order.updated` queries.\n    const changesMeta = opts.changes ? A.getChangesMetaSince(doc, []) : [];\n    return { changedObjectIds: null, updatedAt: Date.now(), changesMeta };\n  }\n\n  const oldHeads = headsCodec.decode(existingCursor);\n\n  const changedObjectIds = new Set<string>();\n  if (opts.objects) {\n    for (const patch of A.diff(doc, oldHeads, A.getHeads(doc))) {\n      if (patch.path.length >= 2 && patch.path[0] === 'objects') {\n        changedObjectIds.add(String(patch.path[1]));\n      }\n    }\n  }\n\n  const changesMeta = A.getChangesMetaSince(doc, oldHeads);\n  let maxTime = 0;\n  for (const change of changesMeta) {\n    if (change.time > maxTime) {\n      maxTime = change.time;\n    }\n  }\n  const updatedAt = maxTime > 0 ? maxTime * 1000 : Date.now();\n\n  return { changedObjectIds, updatedAt, changesMeta };\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport { type DatabaseDirectory, EncodedReference, EntityStructure } from '@dxos/echo-protocol';\nimport { DXN } from '@dxos/keys';\n\n/** Worker work this long holds every query queued behind it, so it is logged above the worker's log filter. */\nexport const SLOW_WORK_MS = 1_000;\n\n/**\n * Finds an object of `typename` inlined in a space directory.\n *\n * @deprecated Inline directory objects are migrated into linked documents on space open; this only finds ones that\n *   have not been migrated yet.\n */\n// TODO(dmaretskyi): Remove once every space has run the inline object migration.\nexport const findInlineObjectOfType = (\n  spaceDoc: DatabaseDirectory,\n  typename: string,\n): [string, EntityStructure] | undefined => {\n  for (const [id, obj] of Object.entries(spaceDoc.objects ?? {})) {\n    const objType = EntityStructure.getTypeReference(obj);\n    if (objType) {\n      const uri = EncodedReference.toURI(objType);\n      // Parse the DXN to extract the typename.\n      const parsed = DXN.tryMake(uri);\n      if (parsed !== undefined && DXN.getName(parsed) === typename) {\n        return [id, obj];\n      }\n    }\n  }\n\n  return undefined;\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport { BaseError } from '@dxos/errors';\n\n/**\n * Thrown when attempting to send a message to a peer that is not connected.\n */\nexport class PeerNotFoundError extends BaseError.extend('PeerNotFoundError', 'Peer not found') {}\n\n/**\n * Raised to a caller waiting on, or leasing, a document the host has quarantined.\n */\nexport class DocumentQuarantinedError extends BaseError.extend('DocumentQuarantinedError', 'Document is quarantined') {}\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport { type DocumentId } from '@automerge/automerge-repo';\n\nimport type { CollectionId } from '@dxos/echo-protocol';\nimport { invariant } from '@dxos/invariant';\nimport { SpaceId } from '@dxos/keys';\n\nexport const deriveCollectionIdFromSpaceId = (spaceId: SpaceId, rootDocumentId?: DocumentId): CollectionId =>\n  (rootDocumentId ? `space:${spaceId}:${rootDocumentId}` : `space:${spaceId}`) as CollectionId;\n\n/**\n * Non-throwing variant of {@link getSpaceIdFromCollectionId}: returns the owning space id for a\n * space collection id (`space:<spaceId>[:<root>]`), or null for any collection id that does not\n * embed a valid space id. Used on the share-policy path, where the parse must not throw.\n */\nexport const tryGetSpaceIdFromCollectionId = (collectionId: string): SpaceId | null => {\n  const spaceId = collectionId.split(':')[1];\n  return SpaceId.isValid(spaceId) ? spaceId : null;\n};\n\nexport const getSpaceIdFromCollectionId = (collectionId: CollectionId): SpaceId => {\n  const spaceId = tryGetSpaceIdFromCollectionId(collectionId);\n  invariant(spaceId);\n  return spaceId;\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport { type Heads } from '@automerge/automerge';\nimport type { DocumentId, PeerId } from '@automerge/automerge-repo';\nimport * as Array from 'effect/Array';\nimport * as Record from 'effect/Record';\n\nimport { Event, asyncReturn, scheduleTask, scheduleTaskInterval } from '@dxos/async';\nimport { type Context, Resource } from '@dxos/context';\nimport { isEdgePeerId } from '@dxos/echo-protocol';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { trace } from '@dxos/tracing';\nimport { defaultMap } from '@dxos/util';\n\nimport { PeerNotFoundError } from './errors.ts';\nimport { tryGetSpaceIdFromCollectionId } from './space-collection.ts';\n\nconst MIN_QUERY_INTERVAL = 5_000;\n\nconst POLL_INTERVAL = 10_000;\n\n/** Whether the local replica of a document contains the change with the given hash; `false` marks it `advertised`. */\nexport type HasLocalChange = (documentId: DocumentId, changeHash: string) => boolean;\n\nexport type CollectionSynchronizerProps = {\n  sendCollectionState: (collectionId: string, peerId: PeerId, state: CollectionState) => void;\n  queryCollectionState: (collectionId: string, peerId: PeerId) => void;\n  shouldSyncCollection: (collectionId: string, peerId: PeerId) => boolean;\n  /** Tells an ancestor head from a change worth a sync round. */\n  hasLocalChange?: HasLocalChange;\n};\n\n/**\n * Implements collection sync protocol.\n */\nexport class CollectionSynchronizer extends Resource {\n  private readonly _sendCollectionState: CollectionSynchronizerProps['sendCollectionState'];\n  private readonly _queryCollectionState: CollectionSynchronizerProps['queryCollectionState'];\n  private readonly _shouldSyncCollection: CollectionSynchronizerProps['shouldSyncCollection'];\n  private readonly _hasLocalChange: CollectionSynchronizerProps['hasLocalChange'];\n\n  /**\n   * CollectionId -> State.\n   */\n  private readonly _perCollectionStates = new Map<string, PerCollectionState>();\n  private readonly _activeCollections = new Set<string>();\n\n  private readonly _connectedPeers = new Set<PeerId>();\n\n  /** Open sync span ids, by collection then peer. */\n  private readonly _syncSpans = new Map<string, Map<PeerId, string>>();\n\n  /** Open sync spans with EDGE, by collection alone: each reconnect reaches EDGE under a new peer id. */\n  private readonly _edgeSyncSpans = new Map<string, EdgeSyncSpan>();\n\n  /** The manual span registry is global, so ids must differ across synchronizers and across a pair's spans. */\n  private readonly _spanIdPrefix = `collection-sync-${PublicKey.random().toHex()}`;\n  private _syncSpanCount = 0;\n\n  public readonly peerCollectionStateUpdated = new Event<{\n    collectionId: string;\n    peerId: PeerId;\n    newDocsAppeared: boolean;\n  }>();\n\n  constructor(params: CollectionSynchronizerProps) {\n    super();\n    this._sendCollectionState = params.sendCollectionState;\n    this._queryCollectionState = params.queryCollectionState;\n    this._shouldSyncCollection = params.shouldSyncCollection;\n    this._hasLocalChange = params.hasLocalChange;\n  }\n\n  protected override async _open(ctx: Context): Promise<void> {\n    scheduleTaskInterval(\n      this._ctx,\n      async () => {\n        for (const collectionId of this._perCollectionStates.keys()) {\n          if (this._activeCollections.has(collectionId)) {\n            this.refreshCollection(collectionId);\n            await asyncReturn();\n          }\n        }\n      },\n      POLL_INTERVAL,\n    );\n  }\n\n  protected override async _close(_ctx: Context): Promise<void> {\n    this._endSyncSpans('closed', () => true);\n    this._endEdgeSyncSpans('closed', () => true);\n  }\n\n  getRegisteredCollectionIds(): string[] {\n    return [...this._activeCollections];\n  }\n\n  getLocalCollectionState(collectionId: string): CollectionState | undefined {\n    return this._perCollectionStates.get(collectionId)?.localState;\n  }\n\n  setLocalCollectionState(collectionId: string, state: CollectionState): void {\n    this._activeCollections.add(collectionId);\n\n    log('setLocalCollectionState', { collectionId, state });\n    const perCollectionState = this._getOrCreatePerCollectionState(collectionId);\n    const trigger = perCollectionState.localState ? 'local' : 'initial';\n    perCollectionState.localState = state;\n\n    for (const peerId of this._connectedPeers) {\n      this._diffCollectionState(collectionId, peerId, trigger);\n    }\n\n    this._scheduleBroadcast(collectionId);\n  }\n\n  /**\n   * Coalesce bursts of `setLocalCollectionState` (e.g. from `_onHeadsChanged` during an\n   * import) into one broadcast microtask per collection. If another call arrives while\n   * the microtask is pending, we just flag the collection dirty — the in-flight run\n   * already reads the latest `localState`. If it arrives during the run itself, we\n   * schedule exactly one follow-up.\n   */\n  private _scheduleBroadcast(collectionId: string): void {\n    const perCollectionState = this._getOrCreatePerCollectionState(collectionId);\n    queueMicrotask(() => {\n      this._refreshInterestedPeers(collectionId);\n      this._broadcastLocalState(collectionId);\n      this.refreshCollection(collectionId);\n    });\n  }\n\n  clearLocalCollectionState(collectionId: string): void {\n    this._endSyncSpans('closed', (spanCollectionId) => spanCollectionId === collectionId);\n    this._endEdgeSyncSpans('closed', (spanCollectionId) => spanCollectionId === collectionId);\n    this._activeCollections.delete(collectionId);\n    this._perCollectionStates.delete(collectionId);\n    log('clearLocalCollectionState', { collectionId });\n  }\n\n  getRemoteCollectionStates(collectionId: string): ReadonlyMap<PeerId, CollectionState> {\n    return this._getOrCreatePerCollectionState(collectionId).remoteStates;\n  }\n\n  refreshCollection(collectionId: string): void {\n    let scheduleAnotherRefresh = false;\n    const state = this._getOrCreatePerCollectionState(collectionId);\n    for (const peerId of this._connectedPeers) {\n      if (state.interestedPeers.has(peerId)) {\n        const lastQueried = state.lastQueried.get(peerId) ?? 0;\n        if (Date.now() - lastQueried > MIN_QUERY_INTERVAL) {\n          state.lastQueried.set(peerId, Date.now());\n          this._queryCollectionState(collectionId, peerId);\n        } else {\n          scheduleAnotherRefresh = true;\n        }\n      }\n    }\n    if (scheduleAnotherRefresh) {\n      scheduleTask(this._ctx, () => this.refreshCollection(collectionId), MIN_QUERY_INTERVAL);\n    }\n  }\n\n  /**\n   * Callback when a connection to a peer is established.\n   */\n  onConnectionOpen(peerId: PeerId): void {\n    log('onConnectionOpen', { peerId });\n    this._connectedPeers.add(peerId);\n\n    queueMicrotask(async () => {\n      if (this._ctx.disposed) {\n        return;\n      }\n      for (const [collectionId, state] of this._perCollectionStates.entries()) {\n        if (this._activeCollections.has(collectionId) && this._shouldSyncCollection(collectionId, peerId)) {\n          state.interestedPeers.add(peerId);\n          state.lastQueried.set(peerId, Date.now());\n          this._queryCollectionState(collectionId, peerId);\n        }\n      }\n    });\n  }\n\n  /**\n   * Callback when a connection to a peer is closed.\n   */\n  onConnectionClosed(peerId: PeerId): void {\n    log('onConnectionClosed', { peerId });\n\n    // An EDGE span outlives the connection: the next one resumes it, so it only counts the drop.\n    for (const span of this._edgeSyncSpans.values()) {\n      if (span.connectedPeers.delete(peerId)) {\n        span.disconnects++;\n      }\n    }\n    this._endSyncSpans('disconnected', (_, spanPeerId) => spanPeerId === peerId);\n    this._connectedPeers.delete(peerId);\n\n    for (const perCollectionState of this._perCollectionStates.values()) {\n      perCollectionState.remoteStates.delete(peerId);\n      perCollectionState.interestedPeers.delete(peerId);\n      perCollectionState.lastQueried.delete(peerId);\n      perCollectionState.lastBroadcast.delete(peerId);\n      perCollectionState.syncedVerdicts.delete(peerId);\n    }\n  }\n\n  /**\n   * Callback when a peer queries the state of a collection.\n   *\n   * If we have no local state yet we silently drop the query; the peer will receive our\n   * state via {@link _broadcastLocalState} once `setLocalCollectionState` is called.\n   */\n  onCollectionStateQueried(collectionId: string, peerId: PeerId): void {\n    const perCollectionState = this._getOrCreatePerCollectionState(collectionId);\n\n    if (perCollectionState.localState) {\n      try {\n        this._sendCollectionState(collectionId, peerId, withoutEmptyHeads(perCollectionState.localState));\n      } catch (error) {\n        if (PeerNotFoundError.is(error)) {\n          log('peer not found when sending collection state callback', { error });\n          return;\n        }\n        throw error;\n      }\n    }\n  }\n\n  /**\n   * Callback when a peer sends the state of a collection.\n   */\n  onRemoteStateReceived(collectionId: string, peerId: PeerId, state: CollectionState): void {\n    log('onRemoteStateReceived', { collectionId, peerId, state });\n    validateCollectionState(state);\n    const perCollectionState = this._getOrCreatePerCollectionState(collectionId);\n    const previousRemoteState = perCollectionState.remoteStates.get(peerId);\n    // Dedupe an unchanged remote state only while that peer is fully caught up. A peer whose\n    // state is unchanged AND still diverges from ours is a stalled sync: skipping the diff\n    // would suppress `peerCollectionStateUpdated`, and with it the `_handleCollectionSync`\n    // replication retry, for as long as the remote keeps repeating itself — i.e. forever.\n    // The poll below can then only ever act on change, never on a stall, and the sole escape\n    // is a reconnect.\n    if (\n      previousRemoteState &&\n      isCollectionStateEqual(previousRemoteState, state) &&\n      this._isSyncedWithPeer(collectionId, peerId)\n    ) {\n      return;\n    }\n    perCollectionState.remoteStates.set(peerId, state);\n    this._diffCollectionState(collectionId, peerId, previousRemoteState ? 'remote' : 'initial');\n  }\n\n  /** True when the last recorded state for `peerId` has no outstanding work against our local state. */\n  private _isSyncedWithPeer(collectionId: string, peerId: PeerId): boolean {\n    const perCollectionState = this._getOrCreatePerCollectionState(collectionId);\n    const remoteState = perCollectionState.remoteStates.get(peerId);\n    if (!remoteState) {\n      return false;\n    }\n    const verdict = perCollectionState.syncedVerdicts.get(peerId);\n    if (verdict && verdict.local === perCollectionState.localState && verdict.remote === remoteState) {\n      return verdict.synced;\n    }\n\n    const localState = perCollectionState.localState ?? { documents: {} };\n    const synced = isDiffEmpty(\n      diffCollectionStateForPeer(localState, remoteState, {\n        isEdgePeer: isEdgePeerId(peerId),\n        hasLocalChange: this._hasLocalChange,\n      }),\n    );\n    perCollectionState.syncedVerdicts.set(peerId, {\n      local: perCollectionState.localState,\n      remote: remoteState,\n      synced,\n    });\n    return synced;\n  }\n\n  private _diffCollectionState(collectionId: string, peerId: PeerId, trigger: SyncSpanTrigger) {\n    const perCollectionState = this._getOrCreatePerCollectionState(collectionId);\n    const remoteState = perCollectionState.remoteStates.get(peerId);\n    if (!remoteState) {\n      return;\n    }\n\n    log('diffCollectionState', { collectionId, peerId });\n    const localState = perCollectionState.localState ?? { documents: {} };\n    const diff = diffCollectionStateForPeer(localState, remoteState, {\n      isEdgePeer: isEdgePeerId(peerId),\n      hasLocalChange: this._hasLocalChange,\n    });\n    if (isDiffEmpty(diff)) {\n      if (isEdgePeerId(peerId)) {\n        this._endEdgeSyncSpan(collectionId, 'synced');\n      } else {\n        this._endSyncSpan(collectionId, peerId, 'synced');\n      }\n    } else {\n      this._startSyncSpan(collectionId, peerId, trigger, diff);\n    }\n    log('diff', {\n      localState: localState.documents,\n      remoteState: remoteState.documents,\n      missingOnLocal: diff.missingOnLocal,\n      missingOnRemote: diff.missingOnRemote,\n      different: diff.different,\n      advertised: diff.advertised,\n    });\n    log('emit peer collection state update');\n    this.peerCollectionStateUpdated.emit({\n      peerId,\n      collectionId,\n      newDocsAppeared: diff.missingOnLocal.length > 0,\n    });\n  }\n\n  /**\n   * Opens a span when a collection diverges from a peer; see {@link SYNC_SPAN_METHOD} for its dashboard.\n   * Spans with EDGE are keyed by the collection, so one span covers a catch-up however many connections\n   * it takes; spans with other peers, whose ids survive a reconnect, are keyed by the peer as well.\n   */\n  private _startSyncSpan(\n    collectionId: string,\n    peerId: PeerId,\n    trigger: SyncSpanTrigger,\n    diff: CollectionStateDiff,\n  ): void {\n    // Nothing would end a span for a closed synchronizer, a gone peer or an inactive collection.\n    if (!this.isOpen || !this._connectedPeers.has(peerId) || !this._activeCollections.has(collectionId)) {\n      return;\n    }\n\n    const edgeSpan = isEdgePeerId(peerId) ? this._edgeSyncSpans.get(collectionId) : undefined;\n    if (edgeSpan) {\n      if (!edgeSpan.connectedPeers.has(peerId)) {\n        edgeSpan.connectedPeers.add(peerId);\n        edgeSpan.connections++;\n      }\n      return;\n    }\n    if (this._syncSpans.get(collectionId)?.has(peerId)) {\n      return;\n    }\n\n    const spanId = `${this._spanIdPrefix}-${collectionId}-${peerId}-${++this._syncSpanCount}`;\n    if (isEdgePeerId(peerId)) {\n      this._edgeSyncSpans.set(collectionId, {\n        spanId,\n        connections: 1,\n        disconnects: 0,\n        connectedPeers: new Set([peerId]),\n      });\n    } else {\n      defaultMap(this._syncSpans, collectionId, () => new Map<PeerId, string>()).set(peerId, spanId);\n    }\n    const spaceId = tryGetSpaceIdFromCollectionId(collectionId);\n    // The derived ctx is discarded: the downstream `_queryCollectionState` hop is a user-supplied callback with no ctx.\n    void trace.spanStart({\n      id: spanId,\n      methodName: SYNC_SPAN_METHOD,\n      instance: this,\n      parentCtx: this._ctx,\n      showInBrowserTimeline: true,\n      attributes: {\n        peerId,\n        collectionId,\n        ...(spaceId ? { spaceId } : {}),\n        trigger,\n        missingOnLocal: diff.missingOnLocal.length,\n        missingOnRemote: diff.missingOnRemote.length,\n        different: diff.different.length,\n      },\n    });\n  }\n\n  private _endEdgeSyncSpan(collectionId: string, outcome: SyncSpanOutcome): void {\n    const span = this._edgeSyncSpans.get(collectionId);\n    if (!span) {\n      return;\n    }\n\n    this._edgeSyncSpans.delete(collectionId);\n    trace.spanEnd(span.spanId, {\n      attributes: { outcome, connections: span.connections, disconnects: span.disconnects },\n    });\n  }\n\n  private _endEdgeSyncSpans(outcome: SyncSpanOutcome, matches: (collectionId: string) => boolean): void {\n    for (const collectionId of [...this._edgeSyncSpans.keys()]) {\n      if (matches(collectionId)) {\n        this._endEdgeSyncSpan(collectionId, outcome);\n      }\n    }\n  }\n\n  private _endSyncSpan(collectionId: string, peerId: PeerId, outcome: SyncSpanOutcome): void {\n    const spans = this._syncSpans.get(collectionId);\n    const spanId = spans?.get(peerId);\n    if (!spans || spanId === undefined) {\n      return;\n    }\n\n    spans.delete(peerId);\n    if (spans.size === 0) {\n      this._syncSpans.delete(collectionId);\n    }\n    trace.spanEnd(spanId, { attributes: { outcome } });\n  }\n\n  private _endSyncSpans(outcome: SyncSpanOutcome, matches: (collectionId: string, peerId: PeerId) => boolean): void {\n    for (const [collectionId, spans] of this._syncSpans) {\n      for (const peerId of spans.keys()) {\n        if (matches(collectionId, peerId)) {\n          this._endSyncSpan(collectionId, peerId, outcome);\n        }\n      }\n    }\n  }\n\n  private _getOrCreatePerCollectionState(collectionId: string): PerCollectionState {\n    return defaultMap(this._perCollectionStates, collectionId, () => ({\n      localState: undefined,\n      remoteStates: new Map(),\n      interestedPeers: new Set(),\n      lastQueried: new Map(),\n      lastBroadcast: new Map(),\n      syncedVerdicts: new Map(),\n    }));\n  }\n\n  /**\n   * Push local state to interested peers whose last-known remote state differs from local\n   * (or is unknown), then pull from peers via {@link refreshCollection}.\n   *\n   * Diff-gating avoids spamming peers that are already in sync; this matters because\n   * {@link setLocalCollectionState} is called on every local heads change.\n   */\n  private _broadcastLocalState(collectionId: string): void {\n    if (this._ctx.disposed || !this._activeCollections.has(collectionId)) {\n      return;\n    }\n    const perCollectionState = this._getOrCreatePerCollectionState(collectionId);\n    const localState = perCollectionState.localState;\n    if (!localState) {\n      return;\n    }\n    // Edge replicators are pull-only from our perspective: the edge is the source of truth and\n    // already holds every doc in the space, so proactively pushing our heads on every local\n    // change is wasted work. The edge can still pull our state via `onCollectionStateQueried`.\n    for (const peerId of perCollectionState.interestedPeers) {\n      if (isEdgePeerId(peerId)) {\n        continue;\n      }\n      const lastBroadcast = perCollectionState.lastBroadcast.get(peerId) ?? 0;\n      if (Date.now() - lastBroadcast > MIN_QUERY_INTERVAL) {\n        perCollectionState.lastBroadcast.set(peerId, Date.now());\n        try {\n          this._sendCollectionState(collectionId, peerId, withoutEmptyHeads(localState));\n        } catch (error) {\n          if (PeerNotFoundError.is(error)) {\n            log('peer not found when broadcasting collection state', { error });\n            return;\n          }\n          throw error;\n        }\n      }\n    }\n  }\n\n  private _refreshInterestedPeers(collectionId: string): void {\n    for (const peerId of this._connectedPeers) {\n      if (this._shouldSyncCollection(collectionId, peerId)) {\n        this._getOrCreatePerCollectionState(collectionId).interestedPeers.add(peerId);\n      } else {\n        this._getOrCreatePerCollectionState(collectionId).interestedPeers.delete(peerId);\n      }\n    }\n  }\n}\n\ntype PerCollectionState = {\n  localState?: CollectionState;\n  remoteStates: Map<PeerId, CollectionState>;\n  interestedPeers: Set<PeerId>;\n  lastQueried: Map<PeerId, number>;\n  lastBroadcast: Map<PeerId, number>;\n  syncedVerdicts: Map<PeerId, { local: CollectionState | undefined; remote: CollectionState; synced: boolean }>;\n};\n\nexport type CollectionState = {\n  /**\n   * DocumentId -> Heads.\n   */\n  readonly documents: Readonly<Record<DocumentId, Heads>>;\n};\n\nexport type CollectionStateDiff = {\n  missingOnRemote: DocumentId[];\n  missingOnLocal: DocumentId[];\n  different: DocumentId[];\n  /**\n   * In sync, since the heads overlap, but the remote advertises a change the local replica lacks: worth one sync\n   * round in case it is new, never a divergence.\n   */\n  advertised: DocumentId[];\n};\n\n/** One collection's sync span with EDGE, across however many connections the catch-up takes. */\ntype EdgeSyncSpan = {\n  spanId: string;\n  /** Connections to EDGE that diverged while the span was open. */\n  connections: number;\n  /** Connections to EDGE that dropped while the span was open. */\n  disconnects: number;\n  /** EDGE peers of this span still connected; a drop counts once per peer. */\n  connectedPeers: Set<PeerId>;\n};\n\n/** What exposed a divergence: the pair's first comparison, a peer change, or a local change. */\ntype SyncSpanTrigger = 'initial' | 'remote' | 'local';\n\n/**\n * `closed` covers both a cleared collection and a closed synchronizer; `disconnected` ends only a\n * span with a non-EDGE peer, since one with EDGE carries on over the next connection.\n */\ntype SyncSpanOutcome = 'synced' | 'disconnected' | 'closed';\n\n/** In sync: a document that is only {@link CollectionStateDiff.advertised} does not count. */\nconst isDiffEmpty = (diff: CollectionStateDiff): boolean =>\n  diff.different.length === 0 && diff.missingOnLocal.length === 0 && diff.missingOnRemote.length === 0;\n\nexport const isCollectionStateEqual = (left: CollectionState, right: CollectionState): boolean => {\n  let unmatched = 0;\n  for (const documentId in left.documents) {\n    const heads = left.documents[documentId as DocumentId];\n    if (heads.length === 0) {\n      continue;\n    }\n    const other = right.documents[documentId as DocumentId];\n    if (!other || !headsEqual(heads, other)) {\n      return false;\n    }\n    unmatched++;\n  }\n  for (const documentId in right.documents) {\n    if (right.documents[documentId as DocumentId].length > 0) {\n      unmatched--;\n    }\n  }\n  return unmatched === 0;\n};\n\n/**\n * Strip entries whose heads array is empty before sending a CollectionState\n * over the wire. Empty-heads entries are inert (they don't participate in the\n * diff thanks to `Record.filter` in {@link diffCollectionState}) but they\n * inflate the on-wire payload AND end up advertised as \"I know about this\n * document with no commits\" to the receiver — leaking sedimentree ids that\n * leaked into the local store from other spaces via the subduction\n * fingerprint exchange. Filtering at the send site is the cheapest place to\n * keep collection-state semantics aligned with `diffCollectionState`.\n */\nexport const withoutEmptyHeads = (state: CollectionState): CollectionState => ({\n  documents: Record.filter(state.documents, (heads) => heads.length > 0),\n});\n\n/**\n * Restrict a remote {@link CollectionState} to the document keys present in `local`.\n *\n * Used when diffing against an edge peer: edge subduction storage retains every\n * sedimentree id it has ever seen (old roots, partial creations, cross-space\n * fingerprint leaks), so a raw symmetric diff would surface those as\n * `missingOnLocal` forever. The local root's `links` are authoritative for\n * \"what docs are in this space\"; intersecting the remote view with the local\n * key set drops the noise without changing wire format.\n */\nexport const subsetRemoteToLocal = (local: CollectionState, remote: CollectionState): CollectionState => ({\n  documents: Record.filter(remote.documents, (_heads, documentId) => documentId in local.documents),\n});\n\n/**\n * Peer-aware wrapper around {@link diffCollectionState}.\n *\n * For mesh peers the diff is symmetric (every doc on either side participates).\n * For edge peers we first intersect the remote state with the local key set —\n * see {@link subsetRemoteToLocal} for why.\n */\nexport const diffCollectionStateForPeer = (\n  local: CollectionState,\n  remote: CollectionState,\n  { isEdgePeer, hasLocalChange }: { isEdgePeer: boolean; hasLocalChange?: HasLocalChange },\n): CollectionStateDiff => {\n  const effectiveRemote = isEdgePeer ? subsetRemoteToLocal(local, remote) : remote;\n  return diffCollectionState(local, effectiveRemote, { hasLocalChange });\n};\n\nexport type DiffCollectionStateOptions = {\n  hasLocalChange?: HasLocalChange;\n  /** Compares head sets exactly instead of applying the overlap rule. */\n  exact?: boolean;\n};\n\nexport const diffCollectionState = (\n  local: CollectionState,\n  remote: CollectionState,\n  { hasLocalChange, exact = false }: DiffCollectionStateOptions = {},\n): CollectionStateDiff => {\n  const localDocuments = Record.filter(local.documents, (heads) => heads.length > 0);\n  const remoteDocuments = Record.filter(remote.documents, (heads) => heads.length > 0);\n  // NOTE: Using `Array.union` is slow.\n  const allDocuments = [...new Set([...Record.keys(localDocuments), ...Record.keys(remoteDocuments)])] as DocumentId[];\n\n  const missingOnRemote: DocumentId[] = [];\n  const missingOnLocal: DocumentId[] = [];\n  const different: DocumentId[] = [];\n  const advertised: DocumentId[] = [];\n  for (const documentId of allDocuments) {\n    if (!localDocuments[documentId]) {\n      missingOnLocal.push(documentId);\n    } else if (!remoteDocuments[documentId]) {\n      missingOnRemote.push(documentId);\n    } else if (exact) {\n      if (!headsEqual(local.documents[documentId], remote.documents[documentId])) {\n        different.push(documentId);\n      }\n    } else if (!headsOverlap(local.documents[documentId], remote.documents[documentId])) {\n      // Subduction's `getAllHeads()` on the edge mixes raw `LooseCommit` tips with\n      // fragment heads (commit IDs promoted to depth >= 1 by leading-zero count of the\n      // hash). The host's `automerge.getHeads(doc)` only ever sees raw change tips —\n      // it has no notion of fragments — so the two views can disagree on a doc's\n      // head set even when every change byte is replicated. We treat the doc as in\n      // sync as long as both sides agree on at least one head.\n      different.push(documentId);\n    } else if (\n      advertisesMissingChange(documentId, local.documents[documentId], remote.documents[documentId], hasLocalChange)\n    ) {\n      advertised.push(documentId);\n    }\n  }\n\n  return {\n    missingOnRemote,\n    missingOnLocal,\n    different,\n    advertised,\n  };\n};\n\n/**\n * Returns true when two head-sets share at least one element. Used by the collection-state\n * diff so transient fragment-vs-commit-ID mismatches between subduction peers don't get\n * reported as `differentDocuments` while the underlying change bytes are fully replicated.\n */\nconst headsOverlap = (a: readonly string[], b: readonly string[]): boolean => {\n  if (a.length === 0 || b.length === 0) {\n    return false;\n  }\n  const aset = new Set(a);\n  for (const h of b) {\n    if (aset.has(h)) {\n      return true;\n    }\n  }\n  return false;\n};\n\nconst headsEqual = (a: readonly string[], b: readonly string[]): boolean => {\n  if (a.length === b.length && a.every((head, index) => head === b[index])) {\n    return true;\n  }\n  const aset = new Set(a);\n  const bset = new Set(b);\n  return aset.size === bset.size && [...bset].every((head) => aset.has(head));\n};\n\nconst advertisesMissingChange = (\n  documentId: DocumentId,\n  local: readonly string[],\n  remote: readonly string[],\n  hasLocalChange: HasLocalChange | undefined,\n): boolean => {\n  if (!hasLocalChange) {\n    return false;\n  }\n  const localSet = new Set(local);\n  return remote.some((head) => !localSet.has(head) && !hasLocalChange(documentId, head));\n};\n\nconst validateCollectionState = (state: CollectionState) => {\n  for (const documentId in state.documents) {\n    if (!isValidDocumentId(documentId as DocumentId)) {\n      throw new Error(`Invalid documentId: ${documentId}`);\n    }\n    const heads = state.documents[documentId as DocumentId];\n    if (Array.isArray(heads)) {\n      for (const head of heads) {\n        if (typeof head !== 'string') {\n          throw new Error(`Invalid heads: ${heads}`);\n        }\n      }\n    }\n  }\n};\n\nconst isValidDocumentId = (documentId: DocumentId) => {\n  return typeof documentId === 'string' && !documentId.includes(':');\n};\n\n/**\n * The PostHog dashboard \"EDGE replication latency\" (https://eu.posthog.com/project/126171/dashboard/973334) queries\n * this name, the attributes set in `_startSyncSpan` and the trigger and outcome values: update it when changing them.\n * A span with EDGE also ends with `connections` and `disconnects`: how many connections diverged and dropped under it.\n */\nconst SYNC_SPAN_METHOD = 'syncPeer';\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport { type DocumentId, type QueryState, type Repo } from '@automerge/automerge-repo';\n\n/**\n * Variants reported by {@link QueryState}: `'loading' | 'ready' | 'unavailable' | 'failed'`.\n */\nexport type HandleQueryState = QueryState<unknown>['state'];\n\n/**\n * Returns the {@link QueryState} variant for a document already known to the\n * repo (i.e. one for which a handle has been registered via `Repo.find` /\n * `Repo.findWithProgress` / `Repo.create`), or `undefined` if no handle/query\n * exists for this document yet.\n *\n * Use this anywhere you need to ask \"is this document loaded?\" / \"did sync\n * give up?\" — read the result against the {@link HandleQueryState} variants\n * (e.g. `=== 'ready'`).\n *\n * # Why we can't just call `DocHandle.isReady()` / read `DocHandle.state`\n *\n * The current subduction fork of `@automerge/automerge-repo`\n * (`2.6.0-subduction.10`) **gutted** the per-handle state machine. Inside the\n * fork, every `DocHandle` state predicate is a constant placeholder:\n *\n * ```\n * isReady       = () => true\n * isUnloaded    = () => false\n * isDeleted     = () => false\n * isUnavailable = () => false\n * inState       = (states) => states.includes('ready')\n * get state     = () => 'ready'\n * whenReady     = async () => {}     // resolves immediately, ignores argument\n * ```\n *\n * That means `handle.isReady()` always lies \"yes\", `handle.state` always reads\n * `'ready'`, and `await handle.whenReady()` never blocks — even for handles\n * whose document has never been loaded from storage or synced from a peer.\n * Reading `handle.doc()` on such a \"ready\" handle returns the empty initial\n * doc (`A.init()` or `A.emptyChange(A.init())`) rather than throwing or\n * returning undefined, which can silently corrupt downstream logic that\n * trusted the handle's `isReady()` signal.\n *\n * Real liveness moved to the {@link DocumentQuery} returned by\n * `Repo.findWithProgress`, whose state goes through\n * `'loading' → 'ready' | 'unavailable' | 'failed'`. Production code that\n * needs to know whether a document is actually loaded must consult the query\n * state through this helper instead of any `DocHandle.*` predicate.\n *\n * TODO(mykola): Remove this helper once the fork either (a) restores the\n * `DocHandle` state machine, or (b) every caller is migrated to query\n * `DocumentProgress` directly with a richer API surface (await on state\n * transitions, etc.).\n */\nexport const getHandleState = (repo: Repo, documentId: DocumentId): HandleQueryState | undefined => {\n  if (!repo.getHandle(documentId)) {\n    return undefined;\n  }\n  return repo.findWithProgress(documentId).peek().state;\n};\n\n/**\n * Whether a query holds the document as stored. `'ready'` fires on the first source to put data in\n * the handle, and the subduction source rehydrates from its own commit store before the storage\n * source has merged the current snapshot, so a reader that stops at `'ready'` can see a document\n * behind disk.\n */\nexport const isLoaded = <T>(state: QueryState<T>): boolean =>\n  state.state === 'ready' && state.sources.storage !== 'pending';\n\n/** {@link isLoaded} for a document the repo may not hold; never faults one in. */\nexport const isDocumentLoaded = (repo: Repo, documentId: DocumentId): boolean =>\n  repo.getHandle(documentId) ? isLoaded(repo.findWithProgress(documentId).peek()) : false;\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport type * as A from '@automerge/automerge';\nimport {\n  type AutomergeUrl,\n  type DocHandle,\n  type DocHandleChangePayload,\n  type DocumentId,\n  type DocumentProgress,\n  type Heads,\n  type QueryState,\n  type UrlHeads,\n} from '@automerge/automerge-repo';\n\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\n\nimport { type HandleQueryState, isLoaded } from './handle-state.ts';\n\n/** One loaded document as the repo holds it now. */\nexport type DocumentPair<T> = { query: DocumentProgress<T>; handle: DocHandle<T> };\n\n/**\n * How a lease reaches its document: `open` faults it in if it is not loaded, `peek` never does —\n * teardown has to be able to detach a listener without resurrecting an evicted document.\n */\nexport type DocumentResolver<T> = {\n  open: () => DocumentPair<T>;\n  peek: () => DocumentPair<T> | undefined;\n};\n\n/** What a subscriber learns about a leased document — never the handle. */\nexport type DocumentLeaseState = {\n  state: HandleQueryState;\n};\n\n/**\n * Events a holder can observe on the leased document.\n */\nexport type DocumentLeaseEvents<T> = {\n  'change': DocHandleChangePayload<T>;\n  'heads-changed': { doc: A.Doc<T>; heads: Heads };\n};\n\n/**\n * A borrowed reference to one loaded document, held for as long as the holder needs it.\n *\n * The repo caches a document forever once anything faults it in, so residency has to be decided by\n * the host rather than by the repo: a lease records that decision. The underlying `DocHandle` is\n * never handed out — a holder that captured one would keep reading (and writing) a document the host\n * has since evicted, and no reference count could see it — so every operation goes through the lease\n * and stops working the moment it is disposed.\n *\n * Disposal is idempotent and, being `Symbol.dispose`, is usually written as `using lease = ...`.\n * A holder that outlives its scope (a subscription, a space root) keeps the lease in a field and\n * disposes it in its own teardown.\n */\nexport class DocumentLease<T = any> implements Disposable {\n  #release: (() => void) | undefined;\n\n  /**\n   * `#private` rather than a TypeScript `private`, which survives compilation: the resolver is a\n   * route to the raw `DocHandle`, and a holder that reached it could use one the host has evicted.\n   */\n  readonly #resolve: DocumentResolver<T>;\n\n  /** The handle each listener was registered on, so it is detached from that one — see {@link off}. */\n  readonly #listeners = new Map<(payload: any) => void, DocHandle<T>>();\n\n  /**\n   * The pair is resolved through the registry rather than captured, because an eviction of the same\n   * document may still be draining: a lease taken during that window must operate on the pair the\n   * repo holds after it, not the pair being torn down.\n   */\n  constructor(\n    private readonly _documentId: DocumentId,\n    resolve: DocumentResolver<T>,\n    release: () => void,\n  ) {\n    this.#resolve = resolve;\n    this.#release = release;\n  }\n\n  /** Readable after disposal: an id is not a claim on the document. */\n  get documentId(): DocumentId {\n    return this._documentId;\n  }\n\n  /** Derived from the id, so it reads the same whether or not the document is loaded. */\n  get url(): AutomergeUrl {\n    return `automerge:${this._documentId}` as AutomergeUrl;\n  }\n\n  /** Readiness of the document — the `DocHandle`'s own predicates lie, see `getHandleState`. */\n  get state(): HandleQueryState {\n    return this.#query.peek().state;\n  }\n\n  /** Ready with the stored copy merged in — see {@link isLoaded}; what {@link waitUntilReady} waits for. */\n  get loaded(): boolean {\n    return isLoaded(this.#query.peek());\n  }\n\n  get disposed(): boolean {\n    return this.#release === undefined;\n  }\n\n  /**\n   * The document, or the empty initial document while it is still loading — check {@link state}\n   * (or await {@link waitUntilReady}) when the difference matters.\n   */\n  doc(): A.Doc<T> {\n    return this.#handle.doc();\n  }\n\n  /** Heads of the document as loaded now — an empty document while it is still loading. */\n  heads(): UrlHeads {\n    return this.#handle.heads();\n  }\n\n  /** Mutates the document; the change is saved and synced by the repo's own listeners. */\n  change(callback: A.ChangeFn<T>, options?: A.ChangeOptions<T>): void {\n    this.#handle.change(callback, options);\n  }\n\n  /** Mutates the document as of `heads`, returning the resulting heads, or undefined if none applied. */\n  changeAt(heads: UrlHeads, callback: A.ChangeFn<T>, options?: A.ChangeOptions<T>): UrlHeads | undefined {\n    return this.#handle.changeAt(heads, callback, options);\n  }\n\n  /**\n   * Resolves once the document is loaded, rejects if the query fails.\n   *\n   * `'unavailable'` is transient rather than terminal — the query routinely reports it while no peer\n   * serves the document yet — so this waits through it, unlike `DocumentQuery.whenReady`.\n   */\n  async waitUntilReady(): Promise<void> {\n    await new Promise<void>((resolve, reject) => {\n      let unsubscribe: (() => void) | undefined;\n      let settled = false;\n      const settle = (state: QueryState<T>) => {\n        if (settled) {\n          return;\n        }\n        if (isLoaded(state)) {\n          settled = true;\n          unsubscribe?.();\n          resolve();\n        } else if (state.state === 'failed') {\n          settled = true;\n          unsubscribe?.();\n          reject(state.error);\n        }\n      };\n      const query = this.#query;\n      unsubscribe = query.subscribe(settle);\n      // Re-read after subscribing: the document may have become ready between the two, and the\n      // subscription only reports transitions.\n      settle(query.peek());\n      if (settled) {\n        unsubscribe();\n      }\n    });\n  }\n\n  /** Registers a listener on the document as loaded now; a later eviction detaches it. */\n  on<K extends keyof DocumentLeaseEvents<T>>(event: K, listener: (payload: DocumentLeaseEvents<T>[K]) => void): void {\n    const handle = this.#handle;\n    this.#listeners.set(listener as (payload: any) => void, handle);\n    handle.on(event as any, listener as any);\n  }\n\n  /**\n   * Removes a listener from the handle it was registered on, not from whatever the document resolves\n   * to now: an eviction and re-acquisition swaps the handle, so detaching from the current one would\n   * strip a listener another lease registered. It also never faults a document in, so teardown after\n   * an eviction (or after the repo closed) cannot resurrect one.\n   */\n  off<K extends keyof DocumentLeaseEvents<T>>(event: K, listener: (payload: DocumentLeaseEvents<T>[K]) => void): void {\n    const registered = this.#listeners.get(listener as (payload: any) => void);\n    this.#listeners.delete(listener as (payload: any) => void);\n    (registered ?? this.#resolve.peek()?.handle)?.off(event as any, listener as any);\n  }\n\n  /** Registers a one-shot listener; see {@link on} for what an eviction does to it. */\n  once<K extends keyof DocumentLeaseEvents<T>>(event: K, listener: (payload: DocumentLeaseEvents<T>[K]) => void): void {\n    this.#handle.once(event as any, listener as any);\n  }\n\n  /**\n   * Observes readiness and sync transitions. Returns an unsubscribe function.\n   *\n   * Only the state is handed out: the query's own payload carries the `DocHandle`, which a\n   * subscriber could keep past disposal.\n   */\n  subscribe(callback: (state: DocumentLeaseState) => void): () => void {\n    return this.#query.subscribe(({ state }) => callback({ state }));\n  }\n\n  [Symbol.dispose](): void {\n    const release = this.#release;\n    this.#release = undefined;\n    release?.();\n  }\n\n  get #handle(): DocHandle<T> {\n    this.#assertLive();\n    return this.#resolve.open().handle;\n  }\n\n  get #query(): DocumentProgress<T> {\n    this.#assertLive();\n    return this.#resolve.open().query;\n  }\n\n  #assertLive(): void {\n    invariant(this.#release !== undefined, 'Document lease has been disposed.');\n  }\n}\n\nexport type DocumentLeaseRegistryParams = {\n  /**\n   * Opens (or returns the cached) query and its attached handle for a document — the one place the\n   * repo is consulted.\n   */\n  open: (documentId: DocumentId) => DocumentPair<any>;\n\n  /**\n   * Drops the document from the repo cache once nothing holds it. Runs after the last lease is\n   * disposed. Eviction is asynchronous, so a lease can be taken while it runs: `isCancelled` must be\n   * consulted after every await, and the document left alone once it reads true.\n   *\n   * Resolves `false` when the document was left resident (still loading, or the drop failed), which\n   * puts it back in the queue for a later attempt.\n   */\n  evict: (documentId: DocumentId, isCancelled: () => boolean) => Promise<boolean>;\n\n  /**\n   * How long a document stays resident after its last lease is disposed. Faulting a document back in\n   * costs a load from storage, so a document released between two passes of the same workload has to\n   * survive the gap rather than be evicted into it.\n   */\n  evictionDelay?: number;\n\n  /**\n   * How many released documents stay resident regardless of age — the most recently released ones.\n   * A floor keeps the hot working set loaded on a host whose whole workload is shorter than the\n   * delay, and bounds nothing else: leased documents are never counted against it.\n   */\n  minResidentDocuments?: number;\n\n  /** How many released documents may wait out the delay. Past it the oldest are evicted at once. */\n  maxIdleDocuments?: number;\n};\n\nconst DEFAULT_EVICTION_DELAY = 0;\nconst DEFAULT_MIN_RESIDENT_DOCUMENTS = 0;\nconst DEFAULT_MAX_IDLE_DOCUMENTS = Infinity;\n\n/**\n * Reference counts the documents the host holds loaded, and evicts each one once its last lease has\n * been disposed for {@link DocumentLeaseRegistryParams.evictionDelay}, oldest release first, keeping\n * the {@link DocumentLeaseRegistryParams.minResidentDocuments} most recently released.\n *\n * Eviction is never immediate: it has to drain the document's pending save, which is asynchronous\n * while disposal is not, and evicting on the last dispose would thrash a workload that releases and\n * re-reads the same document across passes.\n */\nexport class DocumentLeaseRegistry {\n  readonly #counts = new Map<DocumentId, number>();\n\n  /**\n   * The pair each document currently resolves to. Cached so a lease can detach a listener from the\n   * handle it attached to, and dropped whenever the document leaves the repo.\n   */\n  readonly #resolved = new Map<DocumentId, DocumentPair<any>>();\n\n  /** Released documents by release time, in release order — the eviction queue. */\n  readonly #idle = new Map<DocumentId, number>();\n\n  /** Idle documents whose eviction was deferred: each retries once the delay passes, whatever the ceiling. */\n  readonly #deferred = new Set<DocumentId>();\n\n  readonly #params: DocumentLeaseRegistryParams;\n  readonly #evictionDelay: number;\n  readonly #minResidentDocuments: number;\n  readonly #maxIdleDocuments: number;\n\n  #timer: ReturnType<typeof setTimeout> | undefined = undefined;\n  #timerDue = 0;\n  #draining: Promise<void> | undefined = undefined;\n  #closed = false;\n\n  constructor(params: DocumentLeaseRegistryParams) {\n    this.#params = params;\n    this.#evictionDelay = params.evictionDelay ?? DEFAULT_EVICTION_DELAY;\n    this.#minResidentDocuments = params.minResidentDocuments ?? DEFAULT_MIN_RESIDENT_DOCUMENTS;\n    this.#maxIdleDocuments = params.maxIdleDocuments ?? DEFAULT_MAX_IDLE_DOCUMENTS;\n  }\n\n  /** Documents currently leased — the host's document residency. */\n  get size(): number {\n    return this.#counts.size;\n  }\n\n  get leasedDocumentIds(): DocumentId[] {\n    return [...this.#counts.keys()];\n  }\n\n  /** Released documents still resident, waiting out the delay or held by the floor. */\n  get idleCount(): number {\n    return this.#idle.size;\n  }\n\n  /** Whether a lease is outstanding — an idle-but-resident document reads `false`, see {@link idleCount}. */\n  isLeased(documentId: DocumentId): boolean {\n    return this.#counts.has(documentId);\n  }\n\n  acquire<T>(documentId: DocumentId): DocumentLease<T> {\n    invariant(!this.#closed, 'Document lease registry is closed.');\n    this.#idle.delete(documentId);\n    this.#deferred.delete(documentId);\n    this.#counts.set(documentId, (this.#counts.get(documentId) ?? 0) + 1);\n    // Faulted in now so the document starts loading, and re-resolved on each access — see the\n    // lease's constructor for why the pair cannot be captured here.\n    this.#open(documentId);\n    return new DocumentLease<T>(\n      documentId,\n      {\n        open: () => this.#open(documentId),\n        peek: () => this.#resolved.get(documentId),\n      },\n      () => this.#release(documentId),\n    );\n  }\n\n  /**\n   * Drops all bookkeeping for a document without evicting it — for a caller that removed the\n   * document itself, where a later eviction would re-create the query it just deleted.\n   */\n  forget(documentId: DocumentId): void {\n    this.#counts.delete(documentId);\n    this.#idle.delete(documentId);\n    this.#deferred.delete(documentId);\n    this.#resolved.delete(documentId);\n  }\n\n  /**\n   * Stops evicting and forgets every count, without disposing the outstanding leases: the repo is\n   * being shut down, so unloading one document at a time would be wasted work.\n   */\n  close(): void {\n    this.#closed = true;\n    this.#counts.clear();\n    this.#idle.clear();\n    this.#deferred.clear();\n    this.#resolved.clear();\n    this.#clearTimer();\n  }\n\n  /**\n   * Closes, then waits for an eviction that is already draining — it holds the repo's storage and\n   * would otherwise flush into an adapter the caller is about to shut down.\n   */\n  async closeAndSettle(): Promise<void> {\n    this.close();\n    // Not swallowed: `#drain` already logs a failed eviction and carries on, so anything reaching\n    // here is a registry fault the caller needs to see.\n    await this.#draining;\n  }\n\n  #open(documentId: DocumentId): DocumentPair<any> {\n    const pair = this.#params.open(documentId);\n    this.#resolved.set(documentId, pair);\n    return pair;\n  }\n\n  /**\n   * Evicts every released document now, ignoring the delay and the floor — for a caller that needs\n   * residency settled before it measures it.\n   */\n  async drain(): Promise<void> {\n    this.#clearTimer();\n    await this.#draining;\n    await this.#run(true);\n  }\n\n  #release(documentId: DocumentId): void {\n    const count = this.#counts.get(documentId);\n    if (count === undefined) {\n      // The registry was closed under the holder, which is not the holder's fault to report.\n      return;\n    }\n    if (count > 1) {\n      this.#counts.set(documentId, count - 1);\n      return;\n    }\n\n    this.#counts.delete(documentId);\n    this.#idle.set(documentId, Date.now());\n    this.#scheduleDrain();\n  }\n\n  /** Documents due for eviction now, oldest release first, skipping those `attempted` this drain. */\n  #evictable(force: boolean, attempted: ReadonlySet<DocumentId>): DocumentId[] {\n    const excess = force ? this.#idle.size : this.#idle.size - this.#minResidentDocuments;\n    if (excess <= 0) {\n      return [];\n    }\n\n    const now = Date.now();\n    let overCeiling = this.#idle.size - this.#maxIdleDocuments;\n    const evictable: DocumentId[] = [];\n    for (const [documentId, releasedAt] of this.#idle) {\n      if (evictable.length >= excess) {\n        break;\n      }\n      if (attempted.has(documentId)) {\n        continue;\n      }\n      if (!force && now - releasedAt < this.#evictionDelay) {\n        if (overCeiling <= 0) {\n          // Release order, so nothing after this one has waited longer.\n          break;\n        }\n        if (this.#deferred.has(documentId)) {\n          continue;\n        }\n      }\n      overCeiling--;\n      evictable.push(documentId);\n    }\n    return evictable;\n  }\n\n  #scheduleDrain(): void {\n    if (this.#closed) {\n      return;\n    }\n\n    const excess = this.#idle.size - this.#minResidentDocuments;\n    if (excess <= 0) {\n      return;\n    }\n    const now = Date.now();\n    const oldest = this.#idle.values().next();\n    const wait =\n      oldest.done || (this.#idle.size > this.#maxIdleDocuments && this.#idle.size > this.#deferred.size)\n        ? 0\n        : Math.max(0, this.#evictionDelay - (now - oldest.value));\n    if (this.#timer !== undefined) {\n      if (this.#timerDue <= now + wait) {\n        return;\n      }\n      this.#clearTimer();\n    }\n    this.#timerDue = now + wait;\n    this.#timer = setTimeout(() => {\n      this.#timer = undefined;\n      void this.#run(false);\n    }, wait);\n  }\n\n  #clearTimer(): void {\n    if (this.#timer !== undefined) {\n      clearTimeout(this.#timer);\n      this.#timer = undefined;\n    }\n  }\n\n  /** Serializes drains: a forced drain must not interleave with a scheduled one. */\n  #run(force: boolean): Promise<void> {\n    const running = (this.#draining ?? Promise.resolve()).then(() => this.#drain(force));\n    this.#draining = running;\n    const settled = running.finally(() => {\n      if (this.#draining === settled) {\n        this.#draining = undefined;\n      }\n    });\n    this.#draining = settled;\n    return settled;\n  }\n\n  async #drain(force: boolean): Promise<void> {\n    // Each document is attempted once per drain, so one that stays resident cannot spin the loop.\n    const attempted = new Set<DocumentId>();\n    // Drained in a loop: an eviction awaits a flush, and a document released during that await would\n    // otherwise wait for the next release to schedule a drain of its own.\n    while (!this.#closed) {\n      const documentIds = this.#evictable(force, attempted);\n      if (documentIds.length === 0) {\n        break;\n      }\n      for (const documentId of documentIds) {\n        attempted.add(documentId);\n        this.#idle.delete(documentId);\n        this.#deferred.delete(documentId);\n        if (this.#counts.has(documentId)) {\n          continue;\n        }\n\n        let evicted = false;\n        try {\n          evicted = await this.#params.evict(documentId, () => this.#closed || this.#counts.has(documentId));\n          if (evicted) {\n            // The pair a lease resolves to left the repo with the document.\n            this.#resolved.delete(documentId);\n          }\n          if (!this.#closed && this.#counts.has(documentId)) {\n            // Re-leased while the eviction was draining, so the document is faulted back in here\n            // rather than on the holder's next access, which may be its first.\n            this.#open(documentId);\n          }\n        } catch (err) {\n          // Inside the try with the eviction: a throw from either leaves the document resident, and\n          // an unhandled one would reject the drain chain and stop every later eviction.\n          log.warn('failed to evict document', { documentId, err });\n        }\n\n        if (this.#closed) {\n          return;\n        }\n        if (this.#counts.has(documentId)) {\n          continue;\n        }\n        if (!evicted) {\n          // Still resident, so it goes back in the queue rather than being forgotten — re-stamped,\n          // which spaces the retry out by the idle delay instead of retrying in a tight loop.\n          this.#idle.set(documentId, Date.now());\n          this.#deferred.add(documentId);\n        }\n      }\n    }\n\n    if (!this.#closed) {\n      // Whatever the delay, the floor, or a deferred eviction still holds needs a timer of its own.\n      this.#scheduleDrain();\n    }\n  }\n}\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport type { Message } from '@automerge/automerge-repo';\n\nimport {\n  type CollectionQueryMessage,\n  type CollectionStateMessage,\n  MESSAGE_TYPE_COLLECTION_QUERY,\n  MESSAGE_TYPE_COLLECTION_STATE,\n} from '@dxos/protocols';\n\nexport { type CollectionQueryMessage, type CollectionStateMessage };\n\nexport const isCollectionQueryMessage = (message: Message): message is CollectionQueryMessage =>\n  message.type === MESSAGE_TYPE_COLLECTION_QUERY;\n\nexport const isCollectionStateMessage = (message: Message): message is CollectionStateMessage =>\n  message.type === MESSAGE_TYPE_COLLECTION_STATE;\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport {\n  type DocumentId,\n  type Message,\n  NetworkAdapter,\n  type PeerId,\n  type PeerMetadata,\n} from '@automerge/automerge-repo';\n\nimport { Event, Trigger, synchronized } from '@dxos/async';\nimport { type Context, LifecycleState } from '@dxos/context';\nimport { invariant } from '@dxos/invariant';\nimport { type PublicKey, type SpaceId } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { isNonNullable } from '@dxos/util';\n\nimport {\n  type AutomergeReplicator,\n  type AutomergeReplicatorConnection,\n  type RemoteDocumentExistenceCheckProps,\n  type ReplicatorConnectionMessage,\n  type ShouldAdvertiseProps,\n  type ShouldSyncCollectionProps,\n} from './echo-replicator.ts';\nimport { PeerNotFoundError } from './errors.ts';\nimport {\n  type CollectionQueryMessage,\n  type CollectionStateMessage,\n  isCollectionQueryMessage,\n  isCollectionStateMessage,\n} from './network-protocol.ts';\n\nexport interface NetworkDataMonitor {\n  recordPeerConnected(peerId: string): void;\n  recordPeerDisconnected(peerId: string): void;\n  recordMessageSent(message: Message, duration: number): void;\n  recordMessageReceived(message: Message): void;\n  recordMessageSendingFailed(message: Message): void;\n}\n\nexport type EchoNetworkAdapterProps = {\n  getContainingSpaceForDocument: (documentId: string) => Promise<PublicKey | null>;\n  getContainingSpaceIdForDocument: (documentId: string) => Promise<SpaceId | null>;\n  isDocumentInRemoteCollection: (params: RemoteDocumentExistenceCheckProps) => Promise<boolean>;\n  onCollectionStateQueried: (collectionId: string, peerId: PeerId) => void;\n  onCollectionStateReceived: (collectionId: string, peerId: PeerId, state: unknown) => void;\n  /** Invoked when a replicator connection opens (including after reconnect). */\n  onConnectionOpen?: () => void;\n  /** What a connected peer gaining access to more spaces does: re-announce it, or run this handler instead. */\n  onConnectionAuthScopeChanged: 'reannounce-peer' | ((peerId: PeerId) => void);\n  monitor?: NetworkDataMonitor;\n};\n\ntype ConnectionEntry = {\n  isOpen: boolean;\n  connection: AutomergeReplicatorConnection;\n  reader: ReadableStreamDefaultReader<ReplicatorConnectionMessage>;\n  writer: WritableStreamDefaultWriter<ReplicatorConnectionMessage>;\n  requestedDocuments: Set<DocumentId>;\n};\n\n/**\n * Manages a set of {@link AutomergeReplicator} instances.\n */\nexport class EchoNetworkAdapter extends NetworkAdapter {\n  private readonly _replicators = new Set<AutomergeReplicator>();\n  /**\n   * Remote peer id -> connection.\n   */\n  private readonly _connections = new Map<PeerId, ConnectionEntry>();\n  /** Peers mid-reset, whose event pair must not read as a peer leaving and rejoining (DX-1277). */\n  private readonly _resettingTransports = new Set<PeerId>();\n  private _lifecycleState: LifecycleState = LifecycleState.CLOSED;\n  private readonly _connected = new Trigger();\n  private readonly _ready = new Trigger();\n\n  public readonly documentRequested = new Event<{ documentId: DocumentId; peerId: PeerId }>();\n\n  constructor(private readonly _params: EchoNetworkAdapterProps) {\n    super();\n  }\n\n  override isReady(): boolean {\n    return this._lifecycleState === LifecycleState.OPEN;\n  }\n\n  override whenReady(): Promise<void> {\n    return this._ready.wait();\n  }\n\n  override connect(peerId: PeerId, peerMetadata?: PeerMetadata | undefined): void {\n    this.peerId = peerId;\n    this.peerMetadata = peerMetadata;\n    this._connected.wake();\n  }\n\n  override send(message: Message): void {\n    this._send(message);\n  }\n\n  override disconnect(): void {\n    // No-op\n  }\n\n  @synchronized\n  async open(): Promise<void> {\n    if (this._lifecycleState === LifecycleState.OPEN) {\n      return;\n    }\n    this._lifecycleState = LifecycleState.OPEN;\n    this._ready.wake();\n  }\n\n  @synchronized\n  async close(): Promise<this | undefined> {\n    if (this._lifecycleState === LifecycleState.CLOSED) {\n      return this;\n    }\n\n    for (const replicator of this._replicators) {\n      await replicator.disconnect();\n    }\n    this._replicators.clear();\n\n    this._ready.reset();\n    this._lifecycleState = LifecycleState.CLOSED;\n  }\n\n  async whenConnected(): Promise<void> {\n    await this._connected.wait({ timeout: 10_000 });\n  }\n\n  /** True while {@link _onConnectionTransportReset} is emitting for `peerId`; see that method. */\n  public isTransportResetting(peerId: PeerId): boolean {\n    return this._resettingTransports.has(peerId);\n  }\n\n  public onConnectionAuthScopeChanged(peer: PeerId): void {\n    const entry = this._connections.get(peer);\n    if (entry) {\n      this._onConnectionAuthScopeChanged(entry.connection);\n    }\n  }\n\n  @synchronized\n  async addReplicator(ctx: Context, replicator: AutomergeReplicator): Promise<void> {\n    invariant(this._lifecycleState === LifecycleState.OPEN);\n    invariant(this.peerId);\n    invariant(!this._replicators.has(replicator));\n\n    this._replicators.add(replicator);\n    await replicator.connect(ctx, {\n      peerId: this.peerId,\n      onConnectionOpen: this._onConnectionOpen.bind(this),\n      onConnectionClosed: this._onConnectionClosed.bind(this),\n      onConnectionAuthScopeChanged: this._onConnectionAuthScopeChanged.bind(this),\n      onConnectionTransportReset: this._onConnectionTransportReset.bind(this),\n      isDocumentInRemoteCollection: this._params.isDocumentInRemoteCollection,\n      getContainingSpaceForDocument: this._params.getContainingSpaceForDocument,\n      getContainingSpaceIdForDocument: this._params.getContainingSpaceIdForDocument,\n    });\n  }\n\n  @synchronized\n  async removeReplicator(replicator: AutomergeReplicator): Promise<void> {\n    invariant(this._lifecycleState === LifecycleState.OPEN);\n    invariant(this._replicators.has(replicator));\n    await replicator.disconnect();\n    this._replicators.delete(replicator);\n  }\n\n  async shouldAdvertise(peerId: PeerId, params: ShouldAdvertiseProps): Promise<boolean> {\n    const connection = this._connections.get(peerId);\n    if (!connection) {\n      // Denies every document for the peer, so a stale peerId reads as a share-policy refusal.\n      log.verbose('share policy probe: no connection for peer', { peerId, documentId: params.documentId });\n      return false;\n    }\n\n    return connection.connection.shouldAdvertise(params);\n  }\n\n  shouldSyncCollection(peerId: PeerId, params: ShouldSyncCollectionProps): boolean {\n    const connection = this._connections.get(peerId);\n    if (!connection) {\n      return false;\n    }\n\n    return connection.connection.shouldSyncCollection(params);\n  }\n\n  queryCollectionState(collectionId: string, targetId: PeerId): void {\n    const message: CollectionQueryMessage = {\n      type: 'collection-query',\n      senderId: this.peerId as PeerId,\n      targetId,\n      collectionId,\n    };\n    this._send(message);\n  }\n\n  sendCollectionState(collectionId: string, targetId: PeerId, state: unknown): void {\n    const message: CollectionStateMessage = {\n      type: 'collection-state',\n      senderId: this.peerId as PeerId,\n      targetId,\n      collectionId,\n      state,\n    };\n    this._send(message);\n  }\n\n  // TODO(dmaretskyi): Remove.\n  getPeersInterestedInCollection(collectionId: string): PeerId[] {\n    return Array.from(this._connections.values())\n      .map((connection) => {\n        return connection.connection.shouldSyncCollection({ collectionId })\n          ? (connection.connection.peerId as PeerId)\n          : null;\n      })\n      .filter(isNonNullable);\n  }\n\n  private _send(message: Message): void {\n    const connectionEntry = this._connections.get(message.targetId);\n    if (!connectionEntry) {\n      throw new PeerNotFoundError({ context: { peerId: message.targetId } });\n    }\n\n    // TODO(dmaretskyi): Find a way to enforce backpressure on AM-repo.\n    const start = Date.now();\n    connectionEntry.writer\n      .write(message as ReplicatorConnectionMessage)\n      .then(() => {\n        this._params.monitor?.recordMessageSent(message, Date.now() - start);\n      })\n      .catch((err) => {\n        if (connectionEntry.isOpen) {\n          log.catch(err);\n        }\n\n        this._params.monitor?.recordMessageSendingFailed(message);\n      });\n  }\n\n  private _onConnectionOpen(connection: AutomergeReplicatorConnection): void {\n    log('connection opened', { peerId: connection.peerId });\n    invariant(!this._connections.has(connection.peerId as PeerId));\n    const connectionEntry: ConnectionEntry = {\n      isOpen: true,\n      connection,\n      reader: connection.readable.getReader(),\n      writer: connection.writable.getWriter(),\n      requestedDocuments: new Set(),\n    };\n\n    this._connections.set(connection.peerId as PeerId, connectionEntry);\n\n    // Read inbound messages.\n    queueMicrotask(async () => {\n      try {\n        while (true) {\n          // TODO(dmaretskyi): Find a way to enforce backpressure on AM-repo.\n          const { done, value } = await connectionEntry.reader.read();\n          if (done) {\n            break;\n          }\n\n          this._onMessage(connectionEntry, value as Message);\n        }\n      } catch (err) {\n        if (connectionEntry.isOpen) {\n          log.catch(err);\n        }\n      }\n    });\n\n    log('emit peer-candidate', { peerId: connection.peerId });\n    this._emitPeerCandidate(connection);\n    this._params.monitor?.recordPeerConnected(connection.peerId);\n    this._params.onConnectionOpen?.();\n  }\n\n  private _onMessage(connectionEntry: ConnectionEntry, message: Message): void {\n    const amMessage = message as ReplicatorConnectionMessage;\n    if (amMessage.type === 'request') {\n      this.documentRequested.emit({\n        documentId: amMessage.documentId as DocumentId,\n        peerId: connectionEntry.connection.peerId as PeerId,\n      });\n    }\n\n    if (isCollectionQueryMessage(message)) {\n      this._params.onCollectionStateQueried(message.collectionId, message.senderId);\n    } else if (isCollectionStateMessage(message)) {\n      this._params.onCollectionStateReceived(message.collectionId, message.senderId, message.state);\n    } else {\n      this.emit('message', message);\n    }\n    this._params.monitor?.recordMessageReceived(message);\n  }\n\n  private _onConnectionClosed(connection: AutomergeReplicatorConnection): void {\n    log('connection closed', { peerId: connection.peerId });\n    const entry = this._connections.get(connection.peerId as PeerId);\n    invariant(entry);\n\n    entry.isOpen = false;\n    this.emit('peer-disconnected', { peerId: connection.peerId as PeerId });\n    this._params.monitor?.recordPeerDisconnected(connection.peerId);\n\n    void entry.writer.abort().catch((err) => log.catch(err));\n    void entry.reader.cancel().catch((err) => log.catch(err));\n\n    this._connections.delete(connection.peerId as PeerId);\n  }\n\n  /**\n   * Trigger doc-synchronizer shared documents set recalculation. Happens on peer-candidate.\n   * TODO(y): replace with a proper API call when sharePolicy update becomes supported by automerge-repo\n   */\n  private _onConnectionAuthScopeChanged(connection: AutomergeReplicatorConnection): void {\n    log('Connection auth scope changed', { peerId: connection.peerId });\n    const entry = this._connections.get(connection.peerId as PeerId);\n    invariant(entry);\n    if (this._params.onConnectionAuthScopeChanged !== 'reannounce-peer') {\n      this._params.onConnectionAuthScopeChanged(connection.peerId as PeerId);\n      return;\n    }\n    this.emit('peer-disconnected', { peerId: connection.peerId as PeerId });\n    this._emitPeerCandidate(connection);\n  }\n\n  /**\n   * Re-run the peer's transport handshake without closing the connection (DX-1275). The event pair\n   * is the only thing that drives `AdapterConnections` to rebuild a subduction transport; the mark\n   * covers exactly this pair, since both emissions are synchronous.\n   */\n  private _onConnectionTransportReset(connection: AutomergeReplicatorConnection): boolean {\n    const peerId = connection.peerId as PeerId;\n    const entry = this._connections.get(peerId);\n    if (!entry?.isOpen) {\n      log('no open connection to reset', { peerId });\n      return false;\n    }\n\n    log('resetting connection transport', { peerId });\n    this._resettingTransports.add(peerId);\n    try {\n      this.emit('peer-disconnected', { peerId });\n      this._emitPeerCandidate(connection);\n    } finally {\n      this._resettingTransports.delete(peerId);\n    }\n    return true;\n  }\n\n  private _emitPeerCandidate(connection: AutomergeReplicatorConnection): void {\n    this.emit('peer-candidate', {\n      peerId: connection.peerId as PeerId,\n      peerMetadata: createEchoPeerMetadata(),\n    });\n  }\n}\n\nexport const createEchoPeerMetadata = (): PeerMetadata =>\n  ({\n    // TODO(dmaretskyi): Refactor this.\n    dxos_peerSource: 'EchoNetworkAdapter',\n  }) as any;\n\nexport const isEchoPeerMetadata = (metadata: PeerMetadata): boolean =>\n  (metadata as any)?.dxos_peerSource === 'EchoNetworkAdapter';\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport { type DocumentId } from '@automerge/automerge-repo';\n\n/**\n * Why a document is quarantined: its bytes could not be loaded, or a space directory retired it.\n */\nexport type QuarantineReason = 'load-failed' | 'retired';\n\nexport type QuarantineRecord = {\n  documentId: DocumentId;\n  reason: QuarantineReason;\n  /** The load error, for a document quarantined because it could not be loaded. */\n  error?: string;\n  quarantinedAt: number;\n};\n\n/**\n * Whether a load failed because the document cannot fit in Automerge's WASM heap — `error inflating document chunk\n * ops: out of memory` from `loadIncremental`, or the heap refusing to grow. Every load of such a document fails the\n * same way, while any other error (a storage read, malformed bytes) may not repeat.\n */\nexport const isOutOfMemoryError = (error: unknown): boolean =>\n  error instanceof Error &&\n  /out of memory|maximum memory size exceeded|could not allocate memory|allocation failed/i.test(error.message);\n\n/** Changes (commits) past which a document is reported as oversized. */\nexport const OVERSIZED_DOCUMENT_CHANGES = 1_000_000;\n\n/**\n * Ops past which a document is reported as oversized. Checked alongside changes because a few huge changes\n * bloat a document as surely as many small ones: the 45.7M-op cursor that ran out of memory had 156 changes.\n */\nexport const OVERSIZED_DOCUMENT_OPS = 1_000_000;\n\nexport type DocumentSize = { changes: number; ops: number };\n\n/**\n * How many times over the limits a document is, as a doubling level: 0 at the limit, 1 at twice it, and so on;\n * -1 while it is within both limits. Reporting only when the level rises keeps the warning to one per doubling.\n */\nexport const oversizeLevel = ({ changes, ops }: DocumentSize): number => {\n  const ratio = Math.max(changes / OVERSIZED_DOCUMENT_CHANGES, ops / OVERSIZED_DOCUMENT_OPS);\n  return ratio < 1 ? -1 : Math.floor(Math.log2(ratio));\n};\n\n/**\n * Ops a document whose load ran out of memory must hold to be quarantined. Once the heap is full every load fails,\n * so a smaller document is a bystander rather than the cause.\n */\nexport const QUARANTINE_MIN_OPS = 100_000;\n\n//\n// Counting ops from stored bytes; see https://automerge.org/automerge-binary-format-spec.\n//\n\nconst CHUNK_MAGIC = [0x85, 0x6f, 0x4a, 0x83];\nconst ChunkType = { DOCUMENT: 0, CHANGE: 1, COMPRESSED_CHANGE: 2, BUNDLE: 3 } as const;\nconst ACTION_COLUMN_ID = 4;\nconst COLUMN_DEFLATED = 0x08;\nconst HASH_BYTES = 32;\n\ntype Column = { spec: number; length: number };\n\nconst createReader = (bytes: Uint8Array) => {\n  let offset = 0;\n  const take = (length: number): Uint8Array => {\n    if (offset + length > bytes.length) {\n      throw new RangeError('truncated chunk');\n    }\n    offset += length;\n    return bytes.subarray(offset - length, offset);\n  };\n  const leb = (signed: boolean): number => {\n    let value = 0;\n    for (let shift = 0; ; shift += 7) {\n      const byte = take(1)[0];\n      value += (byte & 0x7f) * 2 ** shift;\n      if (byte < 0x80) {\n        return signed && byte & 0x40 ? value - 2 ** (shift + 7) : value;\n      }\n    }\n  };\n  const uleb = () => leb(false);\n  const skipBytes = () => take(uleb());\n  return {\n    done: () => offset >= bytes.length,\n    take,\n    uleb,\n    sleb: () => leb(true),\n    skipBytes,\n    skipHashes: () => take(uleb() * HASH_BYTES),\n    skipActors: () => {\n      for (let count = uleb(); count > 0; count--) {\n        skipBytes();\n      }\n    },\n    columns: (): Column[] => Array.from({ length: uleb() }, () => ({ spec: uleb(), length: uleb() })),\n  };\n};\n\ntype Reader = ReturnType<typeof createReader>;\n\nconst inflate = async (bytes: Uint8Array): Promise<Uint8Array> =>\n  new Uint8Array(\n    await new Response(\n      // Copied: a subarray may sit on a shared buffer, which `Blob` does not take.\n      new Blob([new Uint8Array(bytes)]).stream().pipeThrough(new DecompressionStream('deflate-raw')),\n    ).arrayBuffer(),\n  );\n\n/** Every op has exactly one action, so the rows of the run-length-encoded action column are the chunk's ops. */\nconst countActionRows = async (reader: Reader, columns: Column[]): Promise<number> => {\n  let rows = 0;\n  for (const { spec, length } of columns) {\n    const data = reader.take(length);\n    if (spec >> 4 !== ACTION_COLUMN_ID) {\n      continue;\n    }\n    const runs = createReader(spec & COLUMN_DEFLATED ? await inflate(data) : data);\n    while (!runs.done()) {\n      const run = runs.sleb();\n      if (run > 0) {\n        // One value repeated.\n        runs.uleb();\n        rows += run;\n      } else if (run < 0) {\n        // Literal values.\n        for (let index = 0; index < -run; index++) {\n          runs.uleb();\n        }\n        rows -= run;\n      } else {\n        // Nulls.\n        rows += runs.uleb();\n      }\n    }\n  }\n  return rows;\n};\n\nconst countChunkOps = async (type: number, body: Uint8Array): Promise<number> => {\n  const reader = createReader(body);\n  const skipColumnData = (columns: Column[]) => reader.take(columns.reduce((total, { length }) => total + length, 0));\n  switch (type) {\n    case ChunkType.DOCUMENT: {\n      reader.skipActors();\n      reader.skipHashes(); // Heads.\n      const changeColumns = reader.columns();\n      const opColumns = reader.columns();\n      skipColumnData(changeColumns);\n      return countActionRows(reader, opColumns);\n    }\n    case ChunkType.CHANGE:\n      reader.skipHashes(); // Dependencies.\n      reader.skipBytes(); // Actor.\n      reader.uleb(); // Sequence number.\n      reader.uleb(); // Start op.\n      reader.sleb(); // Time.\n      reader.skipBytes(); // Message.\n      reader.skipActors(); // Other actors.\n      return countActionRows(reader, reader.columns());\n    case ChunkType.COMPRESSED_CHANGE:\n      return countChunkOps(ChunkType.CHANGE, await inflate(body));\n    case ChunkType.BUNDLE:\n      reader.skipHashes(); // Dependencies.\n      reader.skipActors();\n      skipColumnData(reader.columns());\n      return countActionRows(reader, reader.columns());\n    default:\n      return 0;\n  }\n};\n\n/**\n * A lower bound on the ops in a document's stored Automerge chunks, read without loading the document, since loading\n * is what runs out of memory. Distinct changes never overlap, but a snapshot or bundle may repeat them, so the bound\n * is the larger of the changes' sum and the biggest snapshot or bundle. Bytes it cannot read count as no ops.\n */\nexport const countStoredOps = async (records: Iterable<Uint8Array>): Promise<number> => {\n  let changeOps = 0;\n  let largestOps = 0;\n  // A snapshot record can carry changes after its document chunk that an incremental record also holds.\n  const seenChanges = new Set<string>();\n  for (const record of records) {\n    const reader = createReader(record);\n    try {\n      while (!reader.done()) {\n        const magic = reader.take(CHUNK_MAGIC.length);\n        // Sync states and Subduction metadata share the documents' key ranges.\n        if (!CHUNK_MAGIC.every((value, index) => magic[index] === value)) {\n          break;\n        }\n        const checksum = reader.take(4).join();\n        const type = reader.take(1)[0];\n        const body = reader.take(reader.uleb());\n        if (type === ChunkType.CHANGE || type === ChunkType.COMPRESSED_CHANGE) {\n          const key = `${type}:${checksum}:${body.length}`;\n          if (!seenChanges.has(key)) {\n            seenChanges.add(key);\n            changeOps += await countChunkOps(type, body);\n          }\n        } else {\n          largestOps = Math.max(largestOps, await countChunkOps(type, body));\n        }\n      }\n    } catch {\n      // A truncated or corrupt record adds nothing, which keeps the count a lower bound.\n    }\n  }\n  return Math.max(changeOps, largestOps);\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport * as SqlMigrations from '@dxos/sql-sqlite/SqlMigrations';\n\nimport init from './0001_init.sql?raw';\n\n/**\n * Automerge heads migrations, keyed `<id>_<name>` as `Migrator.fromRecord` expects. Ids must only ever increase,\n * and an applied migration must never be edited — nothing verifies its contents.\n */\nexport const MIGRATIONS = {\n  '0001_init': SqlMigrations.apply(init),\n};\n\n/** Own history table per store, since many stores share the client database. */\nexport const MIGRATIONS_TABLE = 'automerge_heads_migrations';\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport type { Heads } from '@automerge/automerge';\nimport type { DocumentId } from '@automerge/automerge-repo';\nimport { create, fromBinary, toBinary } from '@bufbuild/protobuf';\nimport * as Effect from 'effect/Effect';\nimport * as Migrator from 'effect/sql/Migrator';\nimport * as SqlClient from 'effect/sql/SqlClient';\nimport type * as SqlError from 'effect/sql/SqlError';\n\nimport * as RuntimeProvider from '@dxos/effect/RuntimeProvider';\nimport { SQL_MAX_BOUND_VARIABLES } from '@dxos/index-core';\nimport { log } from '@dxos/log';\nimport { HeadsSchema } from '@dxos/protocols/buf/dxos/echo/query_pb';\nimport { chunkArray } from '@dxos/util';\n\nimport { MIGRATIONS, MIGRATIONS_TABLE } from '../migrations/heads/index.ts';\n\nconst encodeHeads = (heads: Heads): Uint8Array => toBinary(HeadsSchema, create(HeadsSchema, { hashes: heads }));\n\nconst decodeHeads = (data: Uint8Array): Heads => {\n  try {\n    return fromBinary(HeadsSchema, data).hashes ?? [];\n  } catch {\n    // Legacy encoding migration path for heads persisted before protobuf encoding.\n    log.warn('Detected legacy encoding of heads in SQLite storage.');\n    const concatenated = Buffer.from(data).toString('utf8').replace(/\"/g, '');\n    const heads: string[] = [];\n    for (let i = 0; i < concatenated.length; i += 64) {\n      heads.push(concatenated.slice(i, i + 64));\n    }\n    return heads;\n  }\n};\n\nexport type SqliteHeadsStoreProps = {\n  runtime: RuntimeProvider.RuntimeProvider<SqlClient.SqlClient>;\n};\n\n/**\n * SQLite-backed store for automerge document heads.\n */\nexport class SqliteHeadsStore {\n  readonly #runtime: RuntimeProvider.RuntimeProvider<SqlClient.SqlClient>;\n\n  constructor({ runtime }: SqliteHeadsStoreProps) {\n    this.#runtime = runtime;\n  }\n\n  /**\n   * Applies any migrations this database has not recorded yet.\n   */\n  readonly migrate: Effect.Effect<void, SqlError.SqlError, SqlClient.SqlClient> = Migrator.make({})({\n    loader: Migrator.fromRecord(MIGRATIONS),\n    table: MIGRATIONS_TABLE,\n  }).pipe(\n    // A malformed bundled manifest is a defect, not something a caller can recover from.\n    Effect.catchTag('MigrationError', (error) => Effect.die(error)),\n    Effect.asVoid,\n    Effect.withSpan('SqliteHeadsStore.migrate'),\n  );\n\n  /**\n   * Returns an Effect that sets heads for a document.\n   * Use RuntimeProvider.runPromise to execute.\n   */\n  setHeads(documentId: DocumentId, heads: Heads): Effect.Effect<void, SqlError.SqlError, SqlClient.SqlClient> {\n    const encoded = encodeHeads(heads);\n    return Effect.gen(function* () {\n      const sql = yield* SqlClient.SqlClient;\n      yield* sql`INSERT OR REPLACE INTO automerge_heads (document_id, heads) VALUES (${documentId}, ${encoded})`;\n    }).pipe(Effect.withSpan('SqliteHeadsStore.setHeads'));\n  }\n\n  /**\n   * Retrieves heads for multiple documents.\n   * Returns undefined for documents not found.\n   */\n  async getHeads(documentIds: DocumentId[]): Promise<Array<Heads | undefined>> {\n    if (documentIds.length === 0) {\n      return [];\n    }\n    return RuntimeProvider.runPromise(this.#runtime)(\n      Effect.gen(function* () {\n        const sql = yield* SqlClient.SqlClient;\n        const headsMap = new Map<string, Heads>();\n        for (const chunk of chunkArray(documentIds, SQL_MAX_BOUND_VARIABLES)) {\n          const rows = yield* sql<{ document_id: string; heads: Uint8Array }>`\n            SELECT document_id, heads FROM automerge_heads\n            WHERE document_id IN ${sql.in(chunk)}\n          `;\n          for (const row of rows) {\n            headsMap.set(row.document_id, decodeHeads(row.heads));\n          }\n        }\n        return documentIds.map((id) => headsMap.get(id));\n      }),\n    );\n  }\n\n  /**\n   * Deletes the heads row for a document. Paired with wiping the document's chunks during\n   * garbage collection — leaving the row behind would orphan it.\n   */\n  remove(documentId: DocumentId): Effect.Effect<void, SqlError.SqlError, SqlClient.SqlClient> {\n    return Effect.gen(function* () {\n      const sql = yield* SqlClient.SqlClient;\n      yield* sql`DELETE FROM automerge_heads WHERE document_id = ${documentId}`;\n    }).pipe(Effect.withSpan('SqliteHeadsStore.remove'));\n  }\n\n  /**\n   * Iterates over all stored document heads.\n   */\n  async *iterateAll(): AsyncGenerator<{ documentId: DocumentId; heads: Heads }> {\n    const rows = await RuntimeProvider.runPromise(this.#runtime)(\n      Effect.gen(function* () {\n        const sql = yield* SqlClient.SqlClient;\n        return yield* sql<{ document_id: string; heads: Uint8Array }>`\n          SELECT document_id, heads FROM automerge_heads ORDER BY document_id ASC\n        `;\n      }),\n    );\n    for (const row of rows) {\n      yield { documentId: row.document_id as DocumentId, heads: decodeHeads(row.heads) };\n    }\n  }\n}\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport {\n  BlobMeta,\n  CommitId,\n  Fragment,\n  FragmentInput,\n  SedimentreeId,\n  type Subduction,\n} from '@automerge/automerge-subduction';\n\nimport { log } from '@dxos/log';\n\nimport { type SqliteStorageAdapter, SUBDUCTION_PREFIX } from '../sqlite-storage-adapter.ts';\nimport { type Migration } from './index.ts';\n\nconst FRAGMENTS_FAMILY = 'fragments';\nconst FRAGMENT_BLOBS_FAMILY = 'fragment-blobs';\n\nexport type FragmentRepairResult = {\n  /** Fragment records inspected. */\n  scanned: number;\n  /** Self-checkpointed records rewritten into the valid shape. */\n  rewritten: number;\n  /** Self-checkpointed records that can never be rewritten: blob missing or not matching its digest. */\n  skipped: number;\n  /** Self-checkpointed records whose rewrite threw; the stored rows are untouched and a later run retries. */\n  failed: number;\n};\n\n/**\n * Rewrites every self-checkpointed fragment in `storage` — what every client on\n * `@automerge/automerge` < 3.5 wrote, and a shape the engine reports no head for — into the valid\n * one: same head, boundary and blob; checkpoints without the head and the boundary ids. Goes\n * through `subduction.storeBuiltBatch`, which signs the new record with the Repo's signer and\n * replaces the two chunks (`[subduction, fragments, <sid>, <head>]` and its `fragment-blobs`\n * twin) under their existing keys. See {@link selfCheckpointRepair} for why.\n *\n * Never deletes and never edits stored bytes: a chunk that does not parse is not a fragment of ours\n * to touch, and one whose blob is missing or mismatched, or whose rewrite throws, is left exactly\n * as it was. Idempotent — a rewritten record no longer matches. One `storeBuiltBatch` per\n * sedimentree.\n *\n * Runs before the engine loads any tree: a loaded tree keeps one in-memory fragment per head (the\n * lower digest wins), so rewriting under it would fix storage while the live view kept the old\n * copy until the tree was next loaded.\n */\nexport const repairSelfCheckpointedFragments = async (\n  subduction: Subduction,\n  storage: SqliteStorageAdapter,\n): Promise<FragmentRepairResult> => {\n  const result: FragmentRepairResult = { scanned: 0, rewritten: 0, skipped: 0, failed: 0 };\n  const chunks = await storage.loadRange([SUBDUCTION_PREFIX, FRAGMENTS_FAMILY]);\n  const bySedimentree = new Map<string, Array<{ headHex: string; repair: SelfCheckpointRepair }>>();\n  for (const { key, data } of chunks) {\n    if (key.length !== 4 || !data) {\n      continue;\n    }\n    result.scanned++;\n    const repair = selfCheckpointRepair(data);\n    if (!repair) {\n      continue;\n    }\n    const [, , sedimentreeHex, headHex] = key;\n    const group = bySedimentree.get(sedimentreeHex) ?? [];\n    group.push({ headHex, repair });\n    bySedimentree.set(sedimentreeHex, group);\n  }\n\n  for (const [sedimentreeHex, group] of bySedimentree) {\n    const sedimentreeId = SedimentreeId.fromBytes(hexToBytes(sedimentreeHex));\n    const inputs: FragmentInput[] = [];\n    for (const { headHex, repair } of group) {\n      const blob = await storage.load([SUBDUCTION_PREFIX, FRAGMENT_BLOBS_FAMILY, sedimentreeHex, headHex]);\n      if (!blob) {\n        result.skipped++;\n        continue;\n      }\n      const blobMeta = new BlobMeta(blob);\n      if (!bytesEqual(blobMeta.digest().toBytes(), repair.blobDigest)) {\n        log.warn('subduction fragment migration: stored blob does not match its record; leaving it', {\n          sedimentreeId: sedimentreeHex,\n          head: headHex,\n        });\n        result.skipped++;\n        continue;\n      }\n      const fragment = new Fragment(\n        sedimentreeId,\n        CommitId.fromBytes(repair.head),\n        repair.boundary.map((id) => CommitId.fromBytes(id)),\n        repair.checkpoints.map((id) => CommitId.fromBytes(id)),\n        blobMeta,\n      );\n      inputs.push(new FragmentInput(fragment, blob));\n    }\n    if (inputs.length === 0) {\n      continue;\n    }\n    try {\n      await subduction.storeBuiltBatch(sedimentreeId, [], inputs);\n      result.rewritten += inputs.length;\n    } catch (err) {\n      result.failed += inputs.length;\n      log.warn('subduction fragment migration: rewrite failed; leaving the stored records', {\n        sedimentreeId: sedimentreeHex,\n        fragments: inputs.length,\n        err,\n      });\n    }\n  }\n  return result;\n};\n\n/**\n * Store-wide {@link repairSelfCheckpointedFragments}. Done — and so recorded — once no rewrite\n * failed; a permanently skipped record does not hold it open, since nothing later can change it.\n */\nexport const selfCheckpointedFragments: Migration = {\n  name: '0002_self_checkpointed_fragments',\n  run: async ({ subduction, storage }) => {\n    const result = await repairSelfCheckpointedFragments(subduction, storage);\n    log.info('subduction fragment migration', result);\n    return result.failed === 0;\n  },\n};\n\nconst bytesEqual = (left: Uint8Array, right: Uint8Array): boolean =>\n  left.length === right.length && left.every((byte, index) => right[index] === byte);\n\nconst hexToBytes = (hex: string): Uint8Array =>\n  Uint8Array.from({ length: hex.length / 2 }, (_, index) => parseInt(hex.slice(index * 2, index * 2 + 2), 16));\n\n/**\n * Reads the checkpoint list out of a stored, signed sedimentree fragment record.\n *\n * `@automerge/automerge-subduction` 0.17.x does not expose a fragment's checkpoints to JS, so a\n * fragment that lists its own head as a checkpoint (the shape every client on `@automerge/automerge`\n * < 3.5 wrote, automerge/automerge#1559) can only be recognized from the record bytes. Such a\n * fragment never contributes a head to `getAllHeads()` (inkandswitch/subduction#306), which is\n * what makes a document look unsynced forever.\n *\n * Record layout, as produced by `SignedFragment.encode()`:\n *\n * ```\n * \"STF\\0\"[4] issuer[32] sedimentreeId[32] head[32] blobDigest[32]\n * boundaryCount:u8 checkpointCount:u16be blobSize:bijou64\n * boundary[32]×boundaryCount checkpoints[12]×checkpointCount signature[64]\n * ```\n *\n * Nothing here verifies the signature: the bytes are only inspected, never trusted as a fragment.\n * The rewrite that follows a positive match goes through the engine, which re-signs the record.\n */\n\nconst MAGIC = [0x53, 0x54, 0x46, 0x00];\nconst ID_LENGTH = 32;\nconst CHECKPOINT_PREFIX_LENGTH = 12;\nconst SIGNATURE_LENGTH = 64;\nconst HEADER_LENGTH = MAGIC.length + ID_LENGTH * 4 + 1 + 2;\n\nexport type SignedFragmentRecord = {\n  issuer: Uint8Array;\n  sedimentreeId: Uint8Array;\n  head: Uint8Array;\n  blobDigest: Uint8Array;\n  boundary: Uint8Array[];\n  /** Checkpoints as stored: {@link CHECKPOINT_PREFIX_LENGTH}-byte id prefixes. */\n  checkpoints: Uint8Array[];\n};\n\n/**\n * Byte width of a bijou64 varint from its first byte: one byte below `0xf8`, otherwise the first\n * byte names the total width.\n */\nconst bijou64Width = (firstByte: number): number => (firstByte < 0xf8 ? 1 : firstByte - 0xf6);\n\n/**\n * Parses a signed fragment record. Returns `undefined` for anything that is not exactly one\n * well-formed record (wrong magic, truncated, or trailing bytes), so a caller can skip it.\n */\nexport const parseSignedFragmentRecord = (bytes: Uint8Array): SignedFragmentRecord | undefined => {\n  if (bytes.length < HEADER_LENGTH + 1 + SIGNATURE_LENGTH) {\n    return undefined;\n  }\n  if (!MAGIC.every((byte, index) => bytes[index] === byte)) {\n    return undefined;\n  }\n  let offset = MAGIC.length;\n  const readId = (): Uint8Array => {\n    const id = bytes.subarray(offset, offset + ID_LENGTH);\n    offset += ID_LENGTH;\n    return id;\n  };\n  const issuer = readId();\n  const sedimentreeId = readId();\n  const head = readId();\n  const blobDigest = readId();\n  const boundaryCount = bytes[offset];\n  offset += 1;\n  const checkpointCount = (bytes[offset] << 8) | bytes[offset + 1];\n  offset += 2;\n  offset += bijou64Width(bytes[offset]);\n  const expectedLength =\n    offset + boundaryCount * ID_LENGTH + checkpointCount * CHECKPOINT_PREFIX_LENGTH + SIGNATURE_LENGTH;\n  if (bytes.length !== expectedLength) {\n    return undefined;\n  }\n  const boundary: Uint8Array[] = [];\n  for (let index = 0; index < boundaryCount; index++) {\n    boundary.push(readId());\n  }\n  const checkpoints: Uint8Array[] = [];\n  for (let index = 0; index < checkpointCount; index++) {\n    checkpoints.push(bytes.subarray(offset, offset + CHECKPOINT_PREFIX_LENGTH));\n    offset += CHECKPOINT_PREFIX_LENGTH;\n  }\n  return { issuer, sedimentreeId, head, blobDigest, boundary, checkpoints };\n};\n\nexport type SelfCheckpointRepair = {\n  head: Uint8Array;\n  boundary: Uint8Array[];\n  /** Digest of the stored blob, for a caller to check the blob it reuses against. */\n  blobDigest: Uint8Array;\n  /**\n   * The checkpoints to store instead: every stored prefix that is neither the head nor a boundary\n   * id, zero-padded to a full id. The engine truncates ids back to the stored prefix width, so the\n   * padding round-trips losslessly.\n   */\n  checkpoints: Uint8Array[];\n};\n\nconst prefixMatches = (prefix: Uint8Array, id: Uint8Array): boolean =>\n  prefix.every((byte, index) => id[index] === byte);\n\n/**\n * Detects a self-checkpointed fragment record and computes the valid shape to rewrite it into:\n * same head and boundary, checkpoints without the head and without the boundary ids. Returns\n * `undefined` when the record does not parse or does not list its own head as a checkpoint.\n */\nexport const selfCheckpointRepair = (bytes: Uint8Array): SelfCheckpointRepair | undefined => {\n  const record = parseSignedFragmentRecord(bytes);\n  if (!record) {\n    return undefined;\n  }\n  const isHead = (prefix: Uint8Array) => prefixMatches(prefix, record.head);\n  if (!record.checkpoints.some(isHead)) {\n    return undefined;\n  }\n  const isBoundary = (prefix: Uint8Array) => record.boundary.some((id) => prefixMatches(prefix, id));\n  const checkpoints = record.checkpoints\n    .filter((prefix) => !isHead(prefix) && !isBoundary(prefix))\n    .map((prefix) => {\n      const id = new Uint8Array(ID_LENGTH);\n      id.set(prefix);\n      return id;\n    });\n  return { head: record.head, boundary: record.boundary, blobDigest: record.blobDigest, checkpoints };\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport * as SqlClient from 'effect/sql/SqlClient';\nimport type * as SqlError from 'effect/sql/SqlError';\n\nimport * as RuntimeProvider from '@dxos/effect/RuntimeProvider';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\n\nimport { SUBDUCTION_PREFIX, descendantRange, encodeKey } from '../sqlite-storage-adapter.ts';\nimport { type Migration } from './index.ts';\n\n/**\n * Run once on every profile: deletes the stored remote-heads records, which a long-lived profile\n * collected one per document per edge restart, and vacuums the file so the space comes back. See\n * {@link deleteSubductionRemoteHeads} for why nothing is lost.\n */\nexport const deleteRemoteHeads: Migration = {\n  name: '0001_delete_remote_heads',\n  run: async ({ storage }) => {\n    const { deleted, reclaimedBytes } = await RuntimeProvider.runPromise(storage.runtime)(\n      deleteSubductionRemoteHeads(),\n    );\n    log.info('subduction remote heads deleted', { deleted, reclaimedBytes });\n    return true;\n  },\n};\n\nexport type DeleteSubductionRemoteHeadsOptions = {\n  /**\n   * Rows per statement when deleting in place. Bounds each transaction (and so the WAL) and sets how often progress\n   * is reported.\n   */\n  batchSize?: number;\n  /**\n   * Whether to `VACUUM` after deleting, if the file has free pages. A delete only moves pages to SQLite's freelist;\n   * the file keeps its size (700 MB on a bloated profile) until a vacuum rewrites it, which needs about that much\n   * free space. Default `true`; a caller that vacuums on its own schedule passes `false`.\n   */\n  vacuum?: boolean;\n  /**\n   * Called once the total is known (`deleted: 0`), then after every batch, or once when a rebuild commits. Not called\n   * when there is nothing to delete.\n   */\n  onProgress?: (progress: { deleted: number; total: number }) => void;\n};\n\nexport type DeleteSubductionRemoteHeadsResult = {\n  /** Records deleted. */\n  deleted: number;\n  /** Bytes the database shrank by in the vacuum that followed; `0` when no vacuum ran. */\n  reclaimedBytes: number;\n};\n\n/**\n * Deletes every stored Subduction remote-heads record — `[SUBDUCTION_PREFIX, 'remote-heads', <sedimentreeId>,\n * <peerId>]`, one per document per remote peer it has synced with. A repair for profiles those records have bloated.\n *\n * The records cache what a peer last reported having. `SubductionSource` replays them when a document attaches (into\n * `getSyncInfo` and the handle's `remote-heads` event) and persists one again when a peer next reports heads.\n * The heads Subduction exchanges while syncing are computed from the local sedimentree, never read from here, so\n * deleting the records loses no document data and changes nothing about what gets synced. Edge used to come back\n * under a new Subduction identity after every restart, which is how a long-lived profile collects one record per\n * document per restart — the bulk of the table.\n *\n * Deleting only moves pages to SQLite's freelist, so the file is then vacuumed (see `vacuum`) — gated on the\n * freelist, not on this run's count, so a run interrupted between the delete and the vacuum finishes the job when\n * rerun. A vacuum that fails propagates: the caller must not record the repair as done.\n */\nexport const deleteSubductionRemoteHeads = ({\n  batchSize = 100_000,\n  vacuum = true,\n  onProgress,\n}: DeleteSubductionRemoteHeadsOptions = {}): Effect.Effect<\n  DeleteSubductionRemoteHeadsResult,\n  SqlError.SqlError,\n  SqlClient.SqlClient\n> =>\n  Effect.gen(function* () {\n    const deleted = yield* deleteRecords({ batchSize, onProgress });\n    const reclaimedBytes = vacuum ? yield* vacuumFreePages : 0;\n    return { deleted, reclaimedBytes };\n  }).pipe(Effect.withSpan('deleteSubductionRemoteHeads'));\n\n/**\n * Rewrites the database without its free pages, when it has any, and reports how much it shrank. Not inside a\n * transaction: SQLite refuses `VACUUM` there. The WAL checkpoint after it is what shrinks the main file on disk in\n * WAL mode (the app's OPFS default); it is a no-op under a rollback journal.\n */\nconst vacuumFreePages: Effect.Effect<number, SqlError.SqlError, SqlClient.SqlClient> = Effect.gen(function* () {\n  const sql = yield* SqlClient.SqlClient;\n  const [{ freelist }] = yield* sql<{\n    freelist: number;\n  }>`SELECT freelist_count AS freelist FROM pragma_freelist_count()`;\n  if (freelist === 0) {\n    return 0;\n  }\n  const fileBytes = Effect.map(\n    sql<{ bytes: number }>`SELECT page_count * page_size AS bytes FROM pragma_page_count(), pragma_page_size()`,\n    ([row]) => row.bytes,\n  );\n  const before = yield* fileBytes;\n  yield* sql`VACUUM`;\n  yield* sql`PRAGMA wal_checkpoint(TRUNCATE)`;\n  const after = yield* fileBytes;\n  return Math.max(0, before - after);\n}).pipe(Effect.withSpan('deleteSubductionRemoteHeads.vacuum'));\n\n/**\n * Two strategies, picked by which side of the table is bigger:\n * - The records outnumber everything else (a bloated profile): the other rows are set aside, the table is emptied\n *   with an unqualified `DELETE`, and they are put back, in one transaction. SQLite's truncate optimization frees an\n *   unqualified delete's pages without visiting its rows, so the cost is one read of each page plus two copies of the\n *   kept rows. Deleting the records in place would rewrite nearly every table page per batch, because they are\n *   scattered across the table in insertion order: minutes of OPFS I/O on a 700 MB profile.\n * - Otherwise: deletes in key order, `batchSize` rows per statement, so an interrupted run keeps what it deleted and\n *   a rerun resumes. Each batch is cut at an existing key rather than selected with `IN (SELECT … LIMIT)`, which\n *   would materialize the batch in a temp B-tree.\n */\nconst deleteRecords = ({\n  batchSize,\n  onProgress,\n}: {\n  batchSize: number;\n  onProgress?: DeleteSubductionRemoteHeadsOptions['onProgress'];\n}): Effect.Effect<number, SqlError.SqlError, SqlClient.SqlClient> =>\n  Effect.gen(function* () {\n    invariant(Number.isInteger(batchSize) && batchSize > 0, 'batchSize must be a positive integer');\n    const sql = yield* SqlClient.SqlClient;\n    const { lower, upper } = descendantRange(encodeKey([SUBDUCTION_PREFIX, 'remote-heads']));\n    const count = (rows: Effect.Effect<ReadonlyArray<{ n: number }>, SqlError.SqlError>) =>\n      Effect.map(rows, ([row]) => row.n);\n    const countRemaining = count(\n      sql<{ n: number }>`SELECT count(*) AS n FROM automerge_chunks WHERE key >= ${lower} AND key < ${upper}`,\n    );\n\n    const total = yield* countRemaining;\n    if (total === 0) {\n      return 0;\n    }\n    onProgress?.({ deleted: 0, total });\n\n    // Everything outside the range, as index range scans: an `OR` of the ranges would plan as a full table scan.\n    // `key` can hold NULL (SQLite allows it in a non-INTEGER PRIMARY KEY), and a NULL key is outside the range too.\n    const kept =\n      (yield* count(sql<{ n: number }>`SELECT count(*) AS n FROM automerge_chunks WHERE key IS NULL`)) +\n      (yield* count(sql<{ n: number }>`SELECT count(*) AS n FROM automerge_chunks WHERE key < ${lower}`)) +\n      (yield* count(sql<{ n: number }>`SELECT count(*) AS n FROM automerge_chunks WHERE key >= ${upper}`));\n    if (total >= kept) {\n      yield* sql.withTransaction(\n        Effect.gen(function* () {\n          yield* sql`DROP TABLE IF EXISTS automerge_chunks_repair`;\n          yield* sql`CREATE TABLE automerge_chunks_repair AS SELECT key, data FROM automerge_chunks WHERE key IS NULL`;\n          yield* sql`INSERT INTO automerge_chunks_repair SELECT key, data FROM automerge_chunks WHERE key < ${lower}`;\n          yield* sql`INSERT INTO automerge_chunks_repair SELECT key, data FROM automerge_chunks WHERE key >= ${upper}`;\n          // Unqualified, so SQLite frees whole pages instead of deleting row by row.\n          yield* sql`DELETE FROM automerge_chunks`;\n          yield* sql`INSERT INTO automerge_chunks (key, data) SELECT key, data FROM automerge_chunks_repair`;\n          yield* sql`DROP TABLE automerge_chunks_repair`;\n        }),\n      );\n      onProgress?.({ deleted: total, total });\n      return total;\n    }\n\n    let deleted = 0;\n    while (true) {\n      // The `batchSize`-th remaining key: everything from the start of the range up to it is exactly one batch.\n      const [last] = yield* sql<{ key: string }>`\n        SELECT key FROM automerge_chunks WHERE key >= ${lower} AND key < ${upper}\n        ORDER BY key LIMIT 1 OFFSET ${batchSize - 1}\n      `;\n      if (last === undefined) {\n        break;\n      }\n      yield* sql`DELETE FROM automerge_chunks WHERE key >= ${lower} AND key <= ${last.key}`;\n      deleted += batchSize;\n      onProgress?.({ deleted, total });\n    }\n\n    const remaining = yield* countRemaining;\n    if (remaining > 0) {\n      yield* sql`DELETE FROM automerge_chunks WHERE key >= ${lower} AND key < ${upper}`;\n      deleted += remaining;\n      onProgress?.({ deleted, total });\n    }\n    return deleted;\n  });\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport { type Subduction } from '@automerge/automerge-subduction';\nimport * as Effect from 'effect/Effect';\nimport * as SqlClient from 'effect/sql/SqlClient';\n\nimport * as RuntimeProvider from '@dxos/effect/RuntimeProvider';\nimport { log } from '@dxos/log';\n\nimport { type SqliteStorageAdapter } from '../sqlite-storage-adapter.ts';\nimport { deleteRemoteHeads } from './0001_delete_remote_heads.ts';\nimport { selfCheckpointedFragments } from './0002_self_checkpointed_fragments.ts';\n\n/**\n * Data migrations over the Subduction records in `automerge_chunks` — rewrites that need the\n * engine or a sweep, unlike the schema DDL in `migrations/chunks`. Each lives in its own numbered\n * file and is recorded in `automerge_subduction_migrations` when it reports itself done; a later\n * open skips it. Order is the order here, and a migration that throws stops the run so the ones\n * after it still see the store they were written against.\n *\n * EVERY MIGRATION MUST BE IDEMPOTENT. Applying and recording are separate commits, and an open can\n * die between them, so a migration reruns against a database it already changed and must change\n * nothing the second time. The ledger is a performance optimization only — it saves the rerun's\n * sweep of every stored record on every open — never what makes a migration safe: a database must\n * be correct with the migration applied any number of times, with or without its ledger row.\n */\nexport const MIGRATIONS: readonly Migration[] = [deleteRemoteHeads, selfCheckpointedFragments];\n\nexport type MigrationContext = {\n  /** The Repo's engine, before any document attached or any sync round ran: no tree is loaded yet. */\n  subduction: Subduction;\n  storage: SqliteStorageAdapter;\n};\n\nexport type Migration = {\n  /** Ledger key: stable for the migration's lifetime, never reused. */\n  name: string;\n  /**\n   * Resolves `true` once nothing is left to do, so the run is recorded; `false` runs it again next\n   * open. Must be idempotent (see {@link MIGRATIONS}): it can run again after a crash, recorded or not.\n   */\n  run: (context: MigrationContext) => Promise<boolean>;\n};\n\n/**\n * Runs every migration in `migrations` that the ledger does not list yet. Errors propagate: the\n * caller decides what a failed migration means for the host.\n */\nexport const runMigrations = async (\n  context: MigrationContext,\n  migrations: readonly Migration[] = MIGRATIONS,\n): Promise<void> => {\n  const run = RuntimeProvider.runPromise(context.storage.runtime);\n  for (const migration of migrations) {\n    if (await run(hasMigration(migration.name))) {\n      continue;\n    }\n    const startedAt = Date.now();\n    const done = await migration.run(context);\n    if (done) {\n      await run(recordMigration(migration.name));\n    }\n    log.info('subduction migration ran', {\n      migration: migration.name,\n      recorded: done,\n      durationMs: Date.now() - startedAt,\n    });\n  }\n};\n\nconst hasMigration = (name: string) =>\n  Effect.gen(function* () {\n    const sql = yield* SqlClient.SqlClient;\n    const rows = yield* sql<{\n      n: number;\n    }>`SELECT count(*) AS n FROM automerge_subduction_migrations WHERE name = ${name}`;\n    return rows[0].n > 0;\n  });\n\nconst recordMigration = (name: string) =>\n  Effect.gen(function* () {\n    const sql = yield* SqlClient.SqlClient;\n    const appliedAt = Date.now();\n    yield* sql`INSERT OR IGNORE INTO automerge_subduction_migrations (name, applied_at) VALUES (${name}, ${appliedAt})`;\n  });\n","//\n// Copyright 2023 DXOS.org\n//\n\nimport {\n  type Doc,\n  type Heads,\n  getBackend,\n  getHeads,\n  equals as headsEquals,\n  isAutomerge,\n  save,\n  stats,\n} from '@automerge/automerge';\nimport {\n  type AnyDocumentId,\n  type DocHandle,\n  type DocumentId,\n  type DocumentProgress,\n  type PeerCandidatePayload,\n  type PeerDisconnectedPayload,\n  type PeerId,\n  Repo,\n  type StorageKey,\n  type SubductionPeerBinding,\n  type SubductionPeerId,\n  type SubductionPolicy,\n  initSubduction,\n  interpretAsDocumentId,\n} from '@automerge/automerge-repo';\nimport {\n  type CommitId,\n  type MemorySigner,\n  type SedimentreeId,\n  SignedFragment,\n  SignedLooseCommit,\n  type Subduction,\n} from '@automerge/automerge-subduction';\nimport bs58check from 'bs58check';\nimport * as Effect from 'effect/Effect';\nimport * as SqlClient from 'effect/sql/SqlClient';\nimport type * as SqlError from 'effect/sql/SqlError';\n\nimport { DeferredTask, Event, asyncTimeout, scheduleTask } from '@dxos/async';\nimport { Context, LifecycleState, Resource, cancelWithContext } from '@dxos/context';\nimport { type CollectionId, DatabaseDirectory, createIdFromSpaceKey, isEdgePeerId } from '@dxos/echo-protocol';\nimport * as RuntimeProvider from '@dxos/effect/RuntimeProvider';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey, type SpaceId } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { type DataService } from '@dxos/protocols/rpc';\nimport { trace } from '@dxos/tracing';\nimport { ComplexSet, bufferToArray, countWork, defaultMap } from '@dxos/util';\n\nimport { SLOW_WORK_MS } from '../util.ts';\nimport {\n  type CollectionState,\n  type CollectionStateDiff,\n  CollectionSynchronizer,\n  diffCollectionStateForPeer,\n  subsetRemoteToLocal,\n} from './collection-synchronizer.ts';\nimport { type DocumentLease, DocumentLeaseRegistry } from './document-lease.ts';\nimport { type EchoDataMonitor } from './echo-data-monitor.ts';\nimport { EchoNetworkAdapter, isEchoPeerMetadata } from './echo-network-adapter.ts';\nimport { type AutomergeReplicator, type RemoteDocumentExistenceCheckProps } from './echo-replicator.ts';\nimport { DocumentQuarantinedError } from './errors.ts';\nimport { type HandleQueryState, getHandleState, isDocumentLoaded, isLoaded } from './handle-state.ts';\nimport {\n  type DocumentSize,\n  OVERSIZED_DOCUMENT_CHANGES,\n  OVERSIZED_DOCUMENT_OPS,\n  QUARANTINE_MIN_OPS,\n  type QuarantineReason,\n  type QuarantineRecord,\n  countStoredOps,\n  isOutOfMemoryError,\n  oversizeLevel,\n} from './quarantine.ts';\nimport { tryGetSpaceIdFromCollectionId } from './space-collection.ts';\nimport { SqliteHeadsStore } from './sqlite-heads-store.ts';\nimport { SqliteStorageAdapter, SUBDUCTION_KEY_FAMILIES, SUBDUCTION_PREFIX } from './sqlite-storage-adapter.ts';\nimport { repairSelfCheckpointedFragments } from './subduction-migrations/0002_self_checkpointed_fragments.ts';\nimport { runMigrations } from './subduction-migrations/index.ts';\n\nexport type PeerIdProvider = () => string | undefined;\n\nexport type RootDocumentSpaceKeyProvider = (documentId: string) => PublicKey | undefined;\n\nconst SUBDUCTION_SERVICE_NAME = 'dxos-subduction';\n\nexport type AutomergeHostProps = {\n  runtime: RuntimeProvider.RuntimeProvider<SqlClient.SqlClient>;\n  dataMonitor?: EchoDataMonitor;\n\n  /**\n   * Used for creating stable ids. A random key is generated on open, if no value is provided.\n   */\n  peerIdProvider?: PeerIdProvider;\n  getSpaceKeyByRootDocumentId?: RootDocumentSpaceKeyProvider;\n\n  /**\n   * Enable Subduction sedimentree transport.\n   *\n   * When `false` (default), the host wires {@link EchoNetworkAdapter} as a classical\n   * automerge-repo network adapter and skips all Subduction-specific initialization\n   * (WASM init, signer generation, subduction policy / adapters). When `true`, the\n   * host runs Subduction as the document byte transport.\n   */\n  useSubduction?: boolean;\n\n  /**\n   * Residency policy for loaded documents. The default evicts a released document after\n   * {@link EVICT_IDLE_DELAY} and keeps no floor; a host whose invocations are shorter than the delay\n   * (a Worker) should set its own.\n   */\n  residency?: {\n    /** How long a document stays resident after its last lease is disposed. */\n    evictionDelay?: number;\n    /** How many released documents stay resident regardless of age. */\n    minResidentDocuments?: number;\n    /** How many released documents may wait out the delay before the oldest are evicted at once. */\n    maxIdleDocuments?: number;\n  };\n};\n\nexport type LoadDocOptions = {\n  timeout?: number;\n\n  /** Internal: set on the one retry `_loadLeasedDoc` takes after an eviction raced its wait. */\n  retried?: boolean;\n\n  /**\n   * Controls whether `loadDoc` is allowed to wait on the network.\n   *\n   * - `true` / unset (default): announce that we want the doc and wait\n   *   until any source (storage OR network) delivers it.\n   * - `false`: probe local storage only. If chunks for the doc exist\n   *   on disk, wait for storage to populate the handle; otherwise\n   *   throw `'unavailable'` immediately without ever consulting the\n   *   network. Note that this does not guarantee that the document\n   *   will not be fetched from the network — an inbound peer announce\n   *   can still deliver bytes — but the host will never request it.\n   */\n  fetchFromNetwork?: boolean;\n};\n\nexport type CreateDocOptions = {\n  /**\n   * Import the document together with its history.\n   */\n  preserveHistory?: boolean;\n\n  documentId?: DocumentId;\n};\n\n/**\n * Only announce documents that are known to require sync.\n */\nconst OPTIMIZED_SHARE_POLICY = true;\n\n/**\n * Consecutive non-converging collection-sync passes before warning, at a ~10s poll — ~1min, so\n * in-flight replication of a large document does not trip it.\n */\nconst NON_CONVERGENCE_WARN_THRESHOLD = 6;\n\n/**\n * Passes between repeat non-convergence warnings, so a permanently stuck pair stays visible in a\n * short log-buffer window without emitting the diagnostic on every poll.\n */\nconst NON_CONVERGENCE_WARN_INTERVAL = 30;\n\n/**\n * Passes after which non-convergence is reported at `error` rather than `warn`: at a ~10s poll this\n * is ~15min of a pair making no progress, which no in-flight replication explains.\n */\nconst NON_CONVERGENCE_ERROR_THRESHOLD = 90;\n\n/**\n * Throttle for the repo-wide share-policy kick, as a per-resident-document cost.\n *\n * `Repo.shareConfigChanged()` takes no document argument — it walks every entry and re-probes each\n * against every connection — so its cost scales with the corpus, and there is no cheaper scoped\n * variant to reach for ({@link resyncDocument} is the per-document lever). Measured in a browser\n * trace of a ~800-document profile: one kick fanned out to ~7.6k probes over ~12s of worker time,\n * i.e. ~15ms per resident document once the per-connection fan-out is amortised in.\n *\n * Used as the *minimum interval between kicks*, so a new fan-out does not start before the previous\n * one has plausibly drained. The kick walks only resident entries, so its cost shrinks with the\n * interval when residency is capped below the corpus. Deliberately not a larger\n * multiple: the kick is also the recovery path for a denied-then-allowed share policy, and delaying\n * it past the fan-out itself would trade a real stall for a bound nobody is hitting.\n */\nconst SHARE_POLICY_KICK_MS_PER_DOCUMENT = 15;\n\n/**\n * Floor for the share-policy throttle. Below this the kick is cheap enough that throttling only\n * adds recovery latency — a small repo should stay as responsive as it was before the throttle.\n */\nconst SHARE_POLICY_KICK_MIN_INTERVAL_MS = 1_000;\n\n/**\n * Ceiling for the share-policy throttle. A corpus large enough to exceed this is past the point\n * where the repo-wide kick is a sensible recovery mechanism at all; capping keeps a pathological\n * profile from stalling recovery outright.\n */\nconst SHARE_POLICY_KICK_MAX_INTERVAL_MS = 30_000;\n\n/**\n * Wall-clock cap for `_repo.shutdown()` during host teardown. Healthy\n * shutdowns finish in single-digit ms; see the comment in\n * {@link AutomergeHost._close} for why the cap is still here.\n */\nconst CLOSE_TIMEOUT = 2_000;\n\n/**\n * How long an eviction waits for a document that is still loading. A document only reaches disk once\n * it settles, so dropping one mid-load would discard memory-only data; one that never arrives costs\n * an empty handle and is left resident.\n */\nconst EVICT_SETTLE_TIMEOUT = 2_000;\n\n/**\n * How long a document being replicated after a collection-sync diff stays leased. A peer can\n * advertise a document it never delivers, so the wait cannot be unbounded.\n */\nconst REPLICATION_LEASE_TIMEOUT = 30_000;\n\n/** Bounds a re-index load, so one document no peer serves cannot stall the whole pass. */\nconst REINDEX_LOAD_TIMEOUT = 10_000;\n\n/**\n * How long a document stays resident after its last lease is disposed. Long enough to span the gap\n * between two passes over the same working set (indexing then querying it), which would otherwise\n * load each document twice. Nothing stays past it: an evicted document's Automerge memory is reused by\n * the next one loaded.\n */\nconst EVICT_IDLE_DELAY = 30_000;\n\nconst MAX_IDLE_DOCUMENTS = 50;\n\n/**\n * Abstracts over the AutomergeRepo.\n *\n * Runs Subduction as the document byte transport ({@link Repo.subductionAdapters}), while\n * the DXOS-specific {@link CollectionSynchronizer} rides on the same {@link EchoNetworkAdapter}\n * via `sync-request` / `sync-state` control messages that are intercepted at the adapter\n * level and never reach the Subduction sedimentree layer.\n */\nexport class AutomergeHost extends Resource {\n  private readonly _runtime: RuntimeProvider.RuntimeProvider<SqlClient.SqlClient>;\n  private readonly _echoNetworkAdapter: EchoNetworkAdapter;\n\n  private readonly _collectionSynchronizer = new CollectionSynchronizer({\n    queryCollectionState: (collectionId, peerId) => this._queryCollectionState(collectionId, peerId),\n    sendCollectionState: (collectionId, peerId, state) => this._sendCollectionState(collectionId, peerId, state),\n    shouldSyncCollection: (collectionId, peerId) => this._shouldSyncCollection(collectionId, peerId),\n    hasLocalChange: (documentId, changeHash) => this._hasLocalChange(documentId, changeHash),\n  });\n\n  private _repo!: Repo;\n  /** Changes confirmed while resident, so an evicted document answers without a load; forgetting costs one load. */\n  private readonly _confirmedChanges = new Map<DocumentId, Set<string>>();\n\n  private _storage!: SqliteStorageAdapter;\n  private readonly _headsStore: SqliteHeadsStore;\n\n  /**\n   * Documents this host never loads, replicates or serves; see {@link quarantineDocument}. Held in memory only: the\n   * space directories' `retired` maps are the durable record, and re-quarantine their documents on every open.\n   */\n  readonly #quarantined = new Map<DocumentId, QuarantineRecord>();\n\n  /** Fired when a document is quarantined, so waits on it end and the space that links it can retire it. */\n  public readonly documentQuarantined = new Event<QuarantineRecord>();\n\n  /** The oversize level last reported per document, so a growing document warns once per doubling. */\n  readonly #oversizeReported = new Map<DocumentId, number>();\n\n  /** Fired for every document loaded from disk, with its size, so the space can retire one whose history bloated. */\n  public readonly documentLoaded = new Event<{ documentId: DocumentId } & DocumentSize>();\n\n  private _syncTask: DeferredTask | undefined = undefined;\n  /**\n   * Cache of collections that would be synced on next sync task run.\n   */\n  private readonly _collectionsToSync = new ComplexSet<{ collectionId: string; peerId: PeerId }>(\n    ({ collectionId, peerId }) => `${collectionId}|${peerId}`,\n  );\n\n  private _peerId!: PeerId;\n\n  private readonly _peerIdProvider?: PeerIdProvider;\n  private readonly _getSpaceKeyByRootDocumentId?: RootDocumentSpaceKeyProvider;\n\n  public readonly collectionStateUpdated = new Event<{ collectionId: CollectionId }>();\n\n  /**\n   * Fired after a batch of documents was saved to disk.\n   */\n  public readonly documentsSaved = new Event();\n\n  /** Fired per document whose heads a save advanced — what a reader of that document must catch up on. */\n  public readonly documentHeadsChanged = new Event<{ documentId: DocumentId; heads: Heads }>();\n\n  private readonly _headsUpdates = new Map<DocumentId, Heads>();\n  private _onHeadsChangedTask?: DeferredTask;\n\n  /**\n   * Documents created in this session.\n   */\n  private _createdDocuments = new Set<DocumentId>();\n\n  /**\n   * Documents that need to be synced based on the result of collection-sync.\n   */\n  private _documentsToSync = new Set<DocumentId>();\n\n  /**\n   * Documents that are not available locally that should be requested.\n   */\n  private _documentsToRequest = new Set<DocumentId>();\n\n  /**\n   * Consecutive non-converging collection-sync passes, keyed by `<collectionId>:<peerId>` — a pair\n   * making no progress is otherwise indistinguishable from idle polling in the logs.\n   */\n  private _nonConvergingSyncPasses = new Map<string, number>();\n\n  /**\n   * The heads each classical sync peer last reported for a document, kept across evictions. Evicting a document drops\n   * the sync round that would deliver its latest change, so one stays resident until every connected peer that synced\n   * it holds its heads.\n   */\n  private readonly _peerHeads = new Map<DocumentId, Map<PeerId, Heads>>();\n\n  /**\n   * Heads a diverged document was last re-synced at, keyed by `<collectionId>:<peerId>:<documentId>`.\n   *\n   * {@link resyncDocument} re-arms the Subduction heal loop, which then retries with its own\n   * backoff — so one call per observed head pair is the whole retry budget, and calling it again\n   * on the next diff pass would reset that backoff to zero and pin it there. Keyed by the heads\n   * rather than a plain \"already tried\" flag so that a genuine change on either side (the peer\n   * advanced, or we committed again) re-opens the retry. An evicted document spends it on the load that\n   * faults it in.\n   *\n   * The map key is only for lookup: collection and peer ids both contain `:`, so no joined string is\n   * unambiguous, and cleanup compares the ids stored on each entry instead.\n   */\n  private _divergedResyncHeads = new Map<\n    string,\n    { collectionId: string; peerId: PeerId; documentId: DocumentId; heads: string }\n  >();\n\n  /** Earliest time the repo-wide share-policy kick may fan out again. See {@link SHARE_POLICY_KICK_MS_PER_DOCUMENT}. */\n  private _sharePolicyKickNextAllowedAt = 0;\n\n  /** Whether a trailing share-policy kick is parked at {@link _sharePolicyKickNextAllowedAt}. */\n  private _sharePolicyKickParked = false;\n\n  /**\n   * Documents requested by remote peers.\n   */\n  private _documentsRequested = new Map<PeerId, Set<DocumentId>>();\n\n  /**\n   * Reference counts the documents held loaded. The repo caches a document forever once anything\n   * faults it in, so residency is decided here instead — see {@link DocumentLeaseRegistry}.\n   */\n  private readonly _leases: DocumentLeaseRegistry;\n\n  /**\n   * Leases held for documents being replicated after a collection-sync diff, released when the\n   * document settles: the trigger is fire-and-forget, so nothing else holds the document while its\n   * bytes are in flight.\n   */\n  private readonly _replicationLeases = new Map<DocumentId, DocumentLease>();\n\n  private _sharePolicyChangedTask?: DeferredTask;\n\n  private _signer: MemorySigner | undefined = undefined;\n  private readonly _useSubduction: boolean;\n\n  /** Subduction Ed25519 PeerId hex → automerge-repo PeerId, populated from `subduction-peer-bound`. */\n  private readonly _subductionPeerIdHexToRepoPeerId = new Map<string, PeerId>();\n\n  constructor({\n    runtime,\n    dataMonitor,\n    peerIdProvider,\n    getSpaceKeyByRootDocumentId,\n    useSubduction = false,\n    residency,\n  }: AutomergeHostProps) {\n    super();\n    this._leases = new DocumentLeaseRegistry({\n      open: (documentId) => {\n        countWork('automerge.docLoads');\n        const query = this._repo.findWithProgress(documentId);\n        const handle = this._repo.getHandle(documentId);\n        invariant(handle, 'Document query has no attached handle.');\n        return { query, handle };\n      },\n      evict: (documentId, isCancelled) => this._evictDocument(documentId, isCancelled),\n      evictionDelay: residency?.evictionDelay ?? EVICT_IDLE_DELAY,\n      minResidentDocuments: residency?.minResidentDocuments,\n      maxIdleDocuments: residency?.maxIdleDocuments ?? MAX_IDLE_DOCUMENTS,\n    });\n    this._runtime = runtime;\n    this._useSubduction = useSubduction;\n    this._storage = new SqliteStorageAdapter({\n      runtime,\n      callbacks: {\n        afterSave: async (key) => this._afterSave(key),\n      },\n      monitor: dataMonitor,\n    });\n    this._echoNetworkAdapter = new EchoNetworkAdapter({\n      getContainingSpaceForDocument: this._getContainingSpaceForDocument.bind(this),\n      getContainingSpaceIdForDocument: this.getContainingSpaceIdForDocument.bind(this),\n      isDocumentInRemoteCollection: this._isDocumentInRemoteCollection.bind(this),\n      onCollectionStateQueried: this._onCollectionStateQueried.bind(this),\n      onCollectionStateReceived: this._onCollectionStateReceived.bind(this),\n      onConnectionOpen: () => this._sharePolicyChangedTask?.schedule(),\n      // Re-announcing under Subduction binds a second connection to the peer, stranding the rounds pending on the first.\n      onConnectionAuthScopeChanged: useSubduction ? () => this._sharePolicyChangedTask?.schedule() : 'reannounce-peer',\n      monitor: dataMonitor,\n    });\n    this._echoNetworkAdapter.documentRequested.on(({ peerId, documentId }) => {\n      defaultMap(this._documentsRequested, peerId, () => new Set()).add(documentId);\n      // Recovery hatch for both classical sharePolicy and subduction `authorizeFetch` denials.\n      this._sharePolicyChangedTask!.schedule();\n    });\n    this._headsStore = new SqliteHeadsStore({ runtime });\n    this._peerIdProvider = peerIdProvider;\n    this._getSpaceKeyByRootDocumentId = getSpaceKeyByRootDocumentId;\n  }\n\n  protected override async _open(ctx: Context): Promise<void> {\n    this._peerId = `host-${this._peerIdProvider?.() ?? PublicKey.random().toHex()}` as PeerId;\n\n    this._onHeadsChangedTask = new DeferredTask(this._ctx, async () => {\n      const docHeads = Array.from(this._headsUpdates.entries());\n      this._headsUpdates.clear();\n      this._onHeadsChanged(docHeads);\n    });\n\n    await this._storage.open?.();\n\n    // Tables must exist before the Repo constructor calls loadRange() on the storage adapter.\n    await RuntimeProvider.runPromise(this._runtime)(this.migrate);\n\n    // Storage and Subduction each inflate a document independently, so the second must see the quarantine the\n    // first one's failure raised rather than spend another minute failing the same way.\n    const isLoadBlocked = (documentId: DocumentId) => this.#quarantined.has(documentId);\n\n    // `Repo` unconditionally constructs a Subduction `SubductionSource` (with a fresh\n    // `MemorySigner` when none is injected) regardless of whether we register any\n    // `subductionAdapters`. That source's signer needs the Subduction WASM module\n    // initialized first — `Repo` imports from `@automerge/automerge-subduction/slim`,\n    // which does not auto-init. So WASM init runs in both modes.\n    await initSubduction();\n\n    if (this._useSubduction) {\n      const { MemorySigner, setSubductionLogLevel } = await import('@automerge/automerge-subduction');\n      this._signer ??= MemorySigner.generate();\n\n      this._repo = new Repo({\n        peerId: this._peerId as PeerId,\n        shareConfig: this._shareConfig,\n        subductionPolicy: this._subductionPolicy,\n        storage: this._storage,\n        isLoadBlocked,\n        network: [],\n        signer: this._signer,\n        subductionAdapters: [\n          {\n            adapter: this._echoNetworkAdapter,\n            serviceName: SUBDUCTION_SERVICE_NAME,\n            // DXOS hosts are always clients — the edge DO is the single `accept` peer in\n            // the DXOS-client <-> edge topology. `connect` uses Subduction's discovery mode,\n            // so peer-to-peer connections (e.g., mesh replicator, test networks) also work\n            // with `connect` on both sides.\n            role: 'connect',\n          },\n        ],\n      });\n\n      // Capture the subduction ↔ repo PeerId binding (websocket arm has no repoPeerId; unused).\n      Event.wrap<SubductionPeerBinding>(this._repo, 'subduction-peer-bound').on(this._ctx, (binding) => {\n        if ('repoPeerId' in binding) {\n          this._subductionPeerIdHexToRepoPeerId.set(binding.subductionPeerId.toString(), binding.repoPeerId);\n        }\n      });\n\n      // Subduction stores a push for an evicted document without applying it; loading it applies it.\n      Event.wrap<{ documentId: DocumentId }>(this._repo, 'subduction-detached-data').on(this._ctx, ({ documentId }) => {\n        // Opening applies migration writes itself, and garbage-collected documents are in no collection.\n        if (this.isOpen && this._isInLocalCollection(documentId)) {\n          this._leaseUntilSettled(documentId);\n        }\n      });\n\n      // Quiet subduction_core's console WARNs: every per-sedimentree sync round fans out to all\n      // space-scoped edge peers, and each correct cross-space `authorizeFetch` denial is logged by\n      // the WASM at WARN (\"not authorized to access sedimentree\"), flooding the console. Must run\n      // after `new Repo(...)` — the SubductionSource constructor resets the level to 'warn' on\n      // every startup. Skipped when subduction debugging is requested, mirroring the constructor's\n      // own escape hatch (`localStorage.debug` / `__SUBDUCTION_DEBUG`).\n      const subductionDebugRequested =\n        (typeof localStorage !== 'undefined' &&\n          typeof localStorage.getItem === 'function' &&\n          /subduction/i.test(localStorage.getItem('debug') ?? '')) ||\n        Boolean(Reflect.get(globalThis, '__SUBDUCTION_DEBUG'));\n      if (!subductionDebugRequested) {\n        setSubductionLogLevel('error');\n      }\n      // Recorded so a log bundle states whether sedimentree-level warnings were being dropped.\n      log('subduction log level', {\n        level: subductionDebugRequested ? 'warn' : 'error',\n        suppressed: !subductionDebugRequested,\n        enableWith: \"localStorage.debug='subduction'\",\n      });\n    } else {\n      // Classical automerge-repo wiring: the EchoNetworkAdapter is registered as a\n      // network adapter and document bytes flow through the standard sync protocol.\n      // `Repo` will internally construct an unused `MemorySigner` for its always-on\n      // `SubductionSource`; with no `subductionAdapters` passed in that source has no\n      // peers to talk to, so it's effectively dormant.\n      this._repo = new Repo({\n        peerId: this._peerId as PeerId,\n        shareConfig: this._shareConfig,\n        storage: this._storage,\n        isLoadBlocked,\n        network: [this._echoNetworkAdapter],\n      });\n      this._repo.synchronizer.on('sync-state', ({ documentId, peerId, syncState }) => {\n        // A reloaded document starts from a persisted sync state, which does not carry the peer's heads.\n        if (syncState.theirHeads) {\n          defaultMap(this._peerHeads, documentId, () => new Map<PeerId, Heads>()).set(peerId, syncState.theirHeads);\n        }\n      });\n    }\n\n    // A source that cannot apply a document only marks itself unavailable, so a load waiting on the document would\n    // wait forever while every retry fails the same way; out of memory is the failure that always repeats.\n    Event.wrap<{ documentId: DocumentId; error: unknown; source: string }>(this._repo, 'document-load-failed').on(\n      this._ctx,\n      ({ documentId, error, source }) => {\n        if (!isOutOfMemoryError(error)) {\n          log.warn('document load failed', { documentId, source, error });\n          return;\n        }\n        if (this.#quarantined.has(documentId)) {\n          return;\n        }\n        // Once the heap is full every load fails, so only a document big enough to be the cause is quarantined.\n        this.#countStoredOps(documentId)\n          .then((ops) => {\n            if (ops < QUARANTINE_MIN_OPS) {\n              log.warn('document ran out of memory but holds too few ops to be the cause', { documentId, ops, error });\n              return;\n            }\n            log.warn('quarantining a document that ran out of memory', { documentId, source, ops, error });\n            return this.quarantineDocument(documentId, { reason: 'load-failed', error });\n          })\n          .catch((err) => log.error('failed to quarantine document', { documentId, err }));\n      },\n    );\n\n    // Every load from disk, whoever asked for it (the indexer leases documents rather than calling `loadDoc`).\n    if (this._repo.storageSubsystem) {\n      Event.wrap<{ documentId: DocumentId; numOps: number; numChanges: number }>(\n        this._repo.storageSubsystem,\n        'document-loaded',\n      ).on(this._ctx, ({ documentId, numOps, numChanges }) => {\n        this.#reportOversizedDocument(documentId, { changes: numChanges, ops: numOps });\n        this.documentLoaded.emit({ documentId, changes: numChanges, ops: numOps });\n      });\n    }\n\n    // Here, and awaited: the Repo constructs its engine without loading any tree, and nothing can\n    // attach a document or start a sync round until `open()` returns, so a rewrite the migrations\n    // make lands before the engine's in-memory view of that tree exists.\n    await this._runSubductionMigrations();\n\n    // A transport reset re-announces a peer that never left, and dropping its collection state costs\n    // a diff over every document in the collection (DX-1275).\n    const peerLifecycleSuppressed = (peerId: PeerId): boolean => this._echoNetworkAdapter.isTransportResetting(peerId);\n    Event.wrap(this._echoNetworkAdapter, 'peer-candidate').on(\n      this._ctx,\n      ((e: PeerCandidatePayload) => !peerLifecycleSuppressed(e.peerId) && this._onPeerConnected(e.peerId)) as any,\n    );\n    Event.wrap(this._echoNetworkAdapter, 'peer-disconnected').on(\n      this._ctx,\n      ((e: PeerDisconnectedPayload) => !peerLifecycleSuppressed(e.peerId) && this._onPeerDisconnected(e.peerId)) as any,\n    );\n\n    this._collectionSynchronizer.peerCollectionStateUpdated.on(this._ctx, ({ collectionId, peerId }) => {\n      // The sync pass this schedules re-runs the share policy for the documents that appeared; re-announcing the\n      // peer instead would restart every sync round in flight with it.\n      this._onRemoteCollectionStateUpdated(collectionId, peerId);\n      this.collectionStateUpdated.emit({ collectionId: collectionId as CollectionId });\n    });\n\n    this._syncTask = new DeferredTask(this._ctx, async () => {\n      const collectionToSync = Array.from(this._collectionsToSync.values());\n      this._collectionsToSync.clear();\n      if (collectionToSync.length === 0) {\n        return;\n      }\n      await Promise.all(\n        collectionToSync.map(async ({ collectionId, peerId }) => {\n          try {\n            await this._handleCollectionSync(this._ctx, collectionId, peerId);\n          } catch (err) {\n            log.error('failed to sync collection', { collectionId, peerId, err });\n          }\n        }),\n      );\n    });\n\n    this._sharePolicyChangedTask = new DeferredTask(this._ctx, async () => {\n      // Throttled by parking one trailing run at the deadline rather than waiting in here:\n      // `DeferredTask` clears its scheduled flag before running this callback, so a `schedule()`\n      // landing during a wait here queues a second run, which would fan out again for requests the\n      // first run already covered. While the trailing run is parked every schedule returns through\n      // this branch, so a burst costs one fan-out. Leading edge is immediate — a kick after a quiet\n      // period pays nothing, which keeps the deny→allow recovery path prompt.\n      const waitMs = this._sharePolicyKickNextAllowedAt - Date.now();\n      if (waitMs > 0) {\n        if (!this._sharePolicyKickParked) {\n          this._sharePolicyKickParked = true;\n          log('share policy kick throttled', { waitMs, loadedDocs: this.loadedDocsCount });\n          scheduleTask(\n            this._ctx,\n            () => {\n              this._sharePolicyKickParked = false;\n              this._sharePolicyChangedTask?.schedule();\n            },\n            waitMs,\n          );\n        }\n        return;\n      }\n      this._sharePolicyKickNextAllowedAt =\n        Date.now() +\n        Math.min(\n          SHARE_POLICY_KICK_MAX_INTERVAL_MS,\n          Math.max(SHARE_POLICY_KICK_MIN_INTERVAL_MS, this.loadedDocsCount * SHARE_POLICY_KICK_MS_PER_DOCUMENT),\n        );\n      log('share policy changed');\n      this._repo.shareConfigChanged();\n    });\n\n    await this._echoNetworkAdapter.open();\n    await this._collectionSynchronizer.open(ctx);\n    await this._echoNetworkAdapter.whenConnected();\n  }\n\n  protected override async _close(ctx: Context): Promise<void> {\n    // Closed before the repo shuts down: unloading one document at a time on the way out is wasted\n    // work, and an eviction racing the shutdown would flush into a closed storage adapter.\n    for (const lease of this._replicationLeases.values()) {\n      lease[Symbol.dispose]();\n    }\n    this._replicationLeases.clear();\n    await this._leases.closeAndSettle();\n\n    // Drain any in-flight `_onHeadsChangedTask` before the `Resource` base\n    // disposes `this._ctx`.\n    await this._onHeadsChangedTask?.join();\n\n    await this._collectionSynchronizer.close(ctx);\n\n    // In subduction mode `_repo.shutdown()` can stall for ~30s on a\n    // Rust-side bug: `subduction_core` doesn't reject pending\n    // `RequestId`s on disconnect, so an in-flight `addBatch(...)` to a\n    // now-gone peer waits the full per-request timeout. Capping drops\n    // only never-going-to-be-delivered pushes; local commits are\n    // already durable in the subduction storage bridge. Reproducer:\n    // `collection synchronization is bidirectional` in\n    // `automerge-host-subduction.test.ts`.\n    //\n    // Classical mode doesn't hit that bug. It does need the explicit\n    // `flush()` (saves docs to local storage) and the full\n    // `shutdown()` to drain pending sync messages, otherwise a peer\n    // about to forward our last writes to a third party can miss the\n    // space-root doc (reproducer: `delegated > single-use` in\n    // `spaces-invitations.test.ts`).\n    if (this._useSubduction) {\n      await asyncTimeout(this._repo.shutdown(), CLOSE_TIMEOUT).catch((err) =>\n        log.warn('failed to shutdown repo', { err }),\n      );\n    } else {\n      await this._repo.flush().catch((err) => log.warn('failed to flush repo before shutdown', { err }));\n      await this._repo.shutdown().catch((err) => log.warn('failed to shutdown repo', { err }));\n    }\n    await this._storage.close?.();\n    await this._echoNetworkAdapter.close();\n    this._syncTask = undefined;\n    this._onHeadsChangedTask = undefined;\n    this._sharePolicyChangedTask = undefined;\n  }\n\n  /**\n   * Runs the data migrations in `./subduction-migrations` over the stored Subduction records, then\n   * repairs the self-checkpointed fragments stored since the last open. Contained: a failed\n   * migration is logged and the host opens on the records as stored, since every migration is a\n   * repair of data the host can already read.\n   *\n   * The repair runs on every open, not once: a peer forwards a fragment with the signature it\n   * received it with and clients on `@automerge/automerge` < 3.5 still write the shape, so one\n   * kept as received would be uploaded to the next empty EDGE store and hide the document's head.\n   */\n  private async _runSubductionMigrations(): Promise<void> {\n    try {\n      const subduction = await this._repo.subduction;\n      await runMigrations({ storage: this._storage, subduction });\n      // TODO(mykola): Delete this every-open repair in the next release, once EDGE refuses the SDKs that write the old\n      //   fragment shape (`MIN_CLIENT_SDK_VERSION`) and repairs any that still reach it.\n      const repaired = await repairSelfCheckpointedFragments(subduction, this._storage);\n      if (repaired.rewritten + repaired.skipped + repaired.failed > 0) {\n        log.info('repaired self-checkpointed fragments stored since the last open', repaired);\n      }\n    } catch (err) {\n      log.error('subduction migrations failed; continuing on the stored records', { err });\n    }\n  }\n\n  /**\n   * Creates automerge_chunks and automerge_heads tables if they do not exist.\n   * Must be called (via RuntimeProvider.runPromise) before opening the host.\n   */\n  get migrate(): Effect.Effect<void, SqlError.SqlError, SqlClient.SqlClient> {\n    return this._storage.migrate.pipe(Effect.andThen(this._headsStore.migrate));\n  }\n\n  get peerId(): PeerId {\n    return this._peerId;\n  }\n\n  get loadedDocsCount(): number {\n    return Object.keys(this._repo.handles).length;\n  }\n\n  /** Ids of the documents resident in the repo cache — ids only, so no caller can bypass a lease. */\n  get loadedDocumentIds(): DocumentId[] {\n    return Object.keys(this._repo.handles) as DocumentId[];\n  }\n\n  /**\n   * Cached handles owned by one space — residency, not the space's document count.\n   *\n   * Counted by testing the space's collection state (which survives handle eviction, and is the\n   * same mapping `getContainingSpaceIdForDocument` trusts first) against the repo's cache, rather\n   * than by asking each cached handle which space it belongs to: that lookup can await a load, and\n   * a stats call must not fault documents in.\n   */\n  loadedDocsCountForSpace(spaceId: SpaceId): number {\n    const counted = new Set<string>();\n    for (const collectionId of this._collectionSynchronizer.getRegisteredCollectionIds()) {\n      if (tryGetSpaceIdFromCollectionId(collectionId) !== spaceId) {\n        continue;\n      }\n      const state = this._collectionSynchronizer.getLocalCollectionState(collectionId);\n      if (!state) {\n        continue;\n      }\n      // A space registers a collection per root, so the same document can appear more than once.\n      for (const documentId of Object.keys(state.documents)) {\n        if (!counted.has(documentId) && this._repo.getHandle(documentId as DocumentId) !== undefined) {\n          counted.add(documentId);\n        }\n      }\n    }\n    return counted.size;\n  }\n\n  /** The Repo's Subduction engine, for storage-level inspection (tests, devtools). */\n  get subduction(): Promise<Subduction> {\n    return this._repo.subduction;\n  }\n\n  get storage(): SqliteStorageAdapter {\n    return this._storage;\n  }\n\n  async addReplicator(ctx: Context, replicator: AutomergeReplicator): Promise<void> {\n    invariant(this.isOpen, 'AutomergeHost is not open');\n    await this._echoNetworkAdapter.addReplicator(ctx, replicator);\n  }\n\n  async removeReplicator(replicator: AutomergeReplicator): Promise<void> {\n    invariant(this.isOpen, 'AutomergeHost is not open');\n    await this._echoNetworkAdapter.removeReplicator(replicator);\n  }\n\n  /**\n   * automerge-repo's `findWithProgress` does not re-issue a parked DocumentQuery; repo-wide,\n   * `shareConfigChanged` clears `all-failed` entries and the heal backoff, then re-syncs.\n   */\n  kickStalledSync(): void {\n    this._repo.shareConfigChanged();\n  }\n\n  /**\n   * Re-drives one document's Subduction sync round, re-arming its heal loop.\n   *\n   * {@link kickStalledSync} only revives `all-failed`/`no-peers` entries, so it cannot move a\n   * sedimentree Subduction already considers settled — which is the state a document sits in when\n   * its heads stay behind the sync server with no round in flight.\n   */\n  resyncDocument(documentId: DocumentId): void {\n    this._repo.resyncSubduction(documentId);\n  }\n\n  /**\n   * Leases a document, waiting until it is loaded. The lease is the only route to a `DocHandle`;\n   * dispose it (`using`, or in the holder's teardown) so the document can be evicted.\n   *\n   * Returns null when `fetchFromNetwork: false` and the document is not on disk, and when the document is\n   * quarantined — including one quarantined while this call waits on it.\n   */\n  async loadDoc<T>(ctx: Context, documentId: AnyDocumentId, opts?: LoadDocOptions): Promise<DocumentLease<T> | null> {\n    invariant(this.isOpen, 'AutomergeHost is not open');\n    if (this.isQuarantined(documentId)) {\n      return null;\n    }\n    // Leased before the wait, so the document cannot be evicted between becoming ready and the\n    // caller receiving it.\n    const lease = this.acquireDoc<T>(documentId);\n    let settled = false;\n    try {\n      const result = await this._loadLeasedDoc(ctx, lease, opts);\n      settled = result !== null;\n      return result;\n    } catch (err) {\n      if (err instanceof DocumentQuarantinedError) {\n        return null;\n      }\n      throw err;\n    } finally {\n      if (!settled) {\n        lease[Symbol.dispose]();\n      }\n    }\n  }\n\n  /**\n   * Leases a document without waiting for it to load — the lease's query carries the readiness\n   * state. Faults the document in, so a caller that only wants to know whether it is already\n   * resident must not use this.\n   */\n  acquireDoc<T>(documentId: AnyDocumentId): DocumentLease<T> {\n    invariant(this.isOpen, 'AutomergeHost is not open');\n    // A lease is over the whole live document, so a heads pin or a path scope in the URL would be\n    // silently dropped rather than honoured.\n    invariant(\n      typeof documentId !== 'string' || !(documentId.includes('#') || documentId.includes('/')),\n      'A lease cannot be taken on a heads-pinned or path-scoped URL.',\n    );\n    const id = interpretAsDocumentId(documentId);\n    // Leasing faults the document in, which is the load the quarantine exists to prevent.\n    if (this.#quarantined.has(id)) {\n      throw new DocumentQuarantinedError({ context: { documentId: id } });\n    }\n    return this._leases.acquire<T>(id);\n  }\n\n  /** Whether the host refuses to load the document; see {@link quarantineDocument}. */\n  isQuarantined(documentId: AnyDocumentId): boolean {\n    return this.#quarantined.has(interpretAsDocumentId(documentId));\n  }\n\n  /** Documents the host refuses to load, with why. */\n  get quarantinedDocuments(): ReadonlyMap<DocumentId, QuarantineRecord> {\n    return this.#quarantined;\n  }\n\n  /** A lower bound on a document's ops, read from its stored bytes since loading it is what ran out of memory. */\n  async #countStoredOps(documentId: DocumentId): Promise<number> {\n    // Settled apart so one failed read does not hide the ops in the others.\n    const recordsUnder = async (...prefixes: string[][]): Promise<Uint8Array[]> =>\n      (await Promise.allSettled(prefixes.map((prefix) => this._storage.loadRange(prefix))))\n        .flatMap((result) => (result.status === 'fulfilled' ? result.value : []))\n        .flatMap(({ data }) => (data ? [data] : []));\n    const sedimentreeId = documentIdToSedimentreeIdHex(documentId);\n    // Either store may hold the whole document, so each is counted on its own rather than summed.\n    return Math.max(\n      await countStoredOps(await recordsUnder([documentId])),\n      await countStoredOps(\n        await recordsUnder(\n          [SUBDUCTION_PREFIX, 'blobs', sedimentreeId],\n          [SUBDUCTION_PREFIX, 'fragment-blobs', sedimentreeId],\n        ),\n      ),\n    );\n  }\n\n  /**\n   * Stops loading, replicating and serving a document for the life of this host: one that cannot be loaded would\n   * otherwise stall the start that reaches it. Waits on it resolve as unavailable. Its bytes stay on disk until\n   * {@link removeDocument}.\n   */\n  async quarantineDocument(\n    documentId: DocumentId,\n    { reason, error }: { reason: QuarantineReason; error?: unknown },\n  ): Promise<void> {\n    const existing = this.#quarantined.get(documentId);\n    if (existing) {\n      // Retirement is terminal, so it supersedes the load failure that led to it.\n      if (reason === 'retired') {\n        this.#quarantined.set(documentId, { ...existing, reason });\n      }\n      return;\n    }\n    const record: QuarantineRecord = {\n      documentId,\n      reason,\n      error: error === undefined ? undefined : String(error),\n      quarantinedAt: Date.now(),\n    };\n    this.#quarantined.set(documentId, record);\n\n    this._replicationLeases.get(documentId)?.[Symbol.dispose]();\n    this._replicationLeases.delete(documentId);\n    this._leases.forget(documentId);\n    this._documentsToSync.delete(documentId);\n    this._documentsToRequest.delete(documentId);\n    this._headsUpdates.delete(documentId);\n    // Detaches every source, so none retries the load.\n    await this._repo.removeFromCache(documentId);\n\n    // Debug level: every open re-applies the `retired` entries, and a load failure already warned where it was caught.\n    log('quarantined document', { documentId, reason });\n    this.documentQuarantined.emit(record);\n  }\n\n  /** Documents currently leased — what the host holds because something is using it. */\n  get leasedDocsCount(): number {\n    return this._leases.size;\n  }\n\n  /** Settles pending evictions, for a caller measuring residency. */\n  async drainEvictions(): Promise<void> {\n    await this._leases.drain();\n  }\n\n  /**\n   * Drops a document from the repo cache, draining its pending save so it cannot re-persist.\n   * Resolves `false` when the document was left resident, so the registry retries it later.\n   */\n  private async _evictDocument(documentId: DocumentId, isCancelled: () => boolean): Promise<boolean> {\n    if (!this.isOpen) {\n      return false;\n    }\n    // Only a loaded document is evicted: `_repo.flush` persists ready handles, so dropping one that\n    // is still loading would discard data that is only in memory.\n    if (getHandleState(this._repo, documentId) !== 'ready') {\n      const abort = new AbortController();\n      await asyncTimeout(\n        this._waitForReady(this._repo.findWithProgress(documentId), abort.signal),\n        EVICT_SETTLE_TIMEOUT,\n      )\n        .catch((err) => log('document did not settle before eviction', { documentId, err }))\n        .finally(() => abort.abort());\n      if (getHandleState(this._repo, documentId) !== 'ready') {\n        log('deferred eviction of a document that is not loaded', { documentId });\n        return false;\n      }\n    }\n    await this._repo.flush([documentId]);\n    // Re-leased while this was draining: dropping the handle now would hand its holder an empty\n    // document to read.\n    if (isCancelled()) {\n      log('cancelled eviction of a re-leased document', { documentId });\n      return false;\n    }\n    // A document faulted in to catch up is ready from its older local copy, so dropping it before its\n    // sync round lands would discard the round and leave it behind for good.\n    if (this._useSubduction && this._repo.hasPendingSubductionSync(documentId)) {\n      log('deferred eviction of a document with a sync round pending', { documentId });\n      return false;\n    }\n    if (!this._useSubduction && this._hasPeerBehind(documentId)) {\n      log('deferred eviction of a document a peer has not caught up on', { documentId });\n      return false;\n    }\n    if (this._repo.handles[documentId]) {\n      await this._repo.removeFromCache(documentId);\n      countWork('automerge.evictions');\n    }\n    log('evicted document', { documentId });\n    return true;\n  }\n\n  /** Whether a connected peer that synced the document last reported heads other than ours. */\n  private _hasPeerBehind(documentId: DocumentId): boolean {\n    const peerHeads = this._peerHeads.get(documentId);\n    const handle = this._repo.getHandle(documentId);\n    if (!peerHeads || !handle) {\n      return false;\n    }\n    const heads = [...getHeads(handle.doc())].sort();\n    const connected = new Set(this._repo.peers);\n    for (const [peerId, theirHeads] of peerHeads) {\n      if (connected.has(peerId) && !headsEquals([...theirHeads].sort(), heads)) {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  private async _loadLeasedDoc<T>(\n    ctx: Context,\n    lease: DocumentLease<T>,\n    opts?: LoadDocOptions,\n  ): Promise<DocumentLease<T> | null> {\n    if (lease.loaded) {\n      return lease;\n    }\n    const startedAt = performance.now();\n    // Readiness lives on the `DocumentQuery`, not the `DocHandle` — see {@link getHandleState}. The\n    // query is read from the repo rather than through the lease, which does not hand it out.\n    const progress = this._repo.findWithProgress<T>(lease.documentId);\n\n    // Default: when `fetchFromNetwork` is unset, behave as if it were\n    // `true` — wait on any source. Only an explicit `false` activates\n    // the storage-only branch.\n    if (opts?.fetchFromNetwork !== false) {\n      // Network branch: announce that we want the doc, then fall through\n      // to the wait below; any source may deliver it. `_documentsToRequest`\n      // is a classical-sync announce optimization (subduction's fingerprint\n      // exchange doesn't need it); `shareConfigChanged()` is useful in both\n      // modes.\n      if (!this._useSubduction) {\n        this._documentsToRequest.add(progress.documentId);\n      }\n      this._sharePolicyChangedTask!.schedule();\n    } else {\n      // Note: This is a Hack.\n      // Storage-only branch. The subduction fork's `DocumentQuery` merged\n      // storage/network into a single `'loading'` state, so we can't tell\n      // them apart via `progress.peek()`. Workaround: probe storage\n      // directly and throw `'unavailable'` if nothing is on disk, without\n      // ever scheduling a network announce. See `fetchFromNetwork` JSDoc\n      // for the residual inbound-announce race.\n      // TODO(mykola): replace with per-source state inspection once the\n      // patched fork exposes it on `DocumentProgress`.\n      const chunks = await this._storage.loadRange([progress.documentId]);\n      const onDisk = chunks.some((chunk) => chunk.data && chunk.data.length > 0);\n      if (!onDisk) {\n        return null;\n      }\n    }\n\n    // `_waitForReady` (vs `progress.whenReady()`) treats `'unavailable'` as transient — the query routinely transits through it when classical sync sees `peers.size === 0` before the next peer arrives.\n    if (opts?.timeout) {\n      const abort = new AbortController();\n      try {\n        await cancelWithContext(ctx, asyncTimeout(this._waitForReady(progress, abort.signal), opts.timeout));\n      } finally {\n        abort.abort();\n      }\n    } else {\n      const abort = new AbortController();\n      try {\n        await cancelWithContext(ctx, this._waitForReady(progress, abort.signal));\n      } finally {\n        abort.abort();\n      }\n    }\n    // Re-read through the lease: an eviction of the same document may have completed during the wait,\n    // in which case the query that just reported ready is not the one the lease now resolves. Bounded\n    // to one retry, so an evict/re-fault oscillation cannot re-arm the caller's timeout forever.\n    if (getHandleState(this._repo, lease.documentId) !== 'ready' && !opts?.retried) {\n      return await this._loadLeasedDoc(ctx, lease, { ...opts, retried: true });\n    }\n    // A network load may legitimately wait on replication; a storage-only one should not.\n    const durationMs = performance.now() - startedAt;\n    if (opts?.fetchFromNetwork === false && durationMs >= SLOW_WORK_MS) {\n      log.warn('slow document load from storage', { documentId: lease.documentId, durationMs });\n    }\n    return lease;\n  }\n\n  /**\n   * Resolve on `'ready'`, reject on `'failed'`, treat `'unavailable'` as transient; caller bounds via\n   * `opts.timeout` / `ctx`.\n   *\n   * `signal` unsubscribes an abandoned wait: a bounded caller stops awaiting but the query lives on,\n   * so without it a document that never settles gains a subscriber per attempt.\n   */\n  private _waitForReady<T>(progress: DocumentProgress<T>, signal?: AbortSignal): Promise<DocHandle<T>> {\n    const peeked = progress.peek();\n    if (peeked.state === 'ready' && isLoaded(peeked)) {\n      return Promise.resolve(peeked.handle);\n    }\n    if (peeked.state === 'failed') {\n      return Promise.reject(peeked.error);\n    }\n    if (this.#quarantined.has(progress.documentId)) {\n      return Promise.reject(new DocumentQuarantinedError({ context: { documentId: progress.documentId } }));\n    }\n    return new Promise<DocHandle<T>>((resolve, reject) => {\n      const unsubscribeQuarantine = this.documentQuarantined.on(({ documentId }) => {\n        // A failed load leaves the query `'unavailable'`, which this wait would otherwise sit through forever.\n        if (documentId === progress.documentId) {\n          unsubscribe();\n          reject(new DocumentQuarantinedError({ context: { documentId } }));\n        }\n      });\n      const unsubscribeProgress = progress.subscribe((state) => {\n        if (state.state === 'ready' && isLoaded(state)) {\n          unsubscribe();\n          resolve(state.handle);\n        } else if (state.state === 'failed') {\n          unsubscribe();\n          reject(state.error);\n        }\n        // `'unavailable'` and `'loading'` are non-terminal — keep waiting.\n      });\n      const unsubscribe = () => {\n        unsubscribeQuarantine();\n        unsubscribeProgress();\n      };\n      signal?.addEventListener('abort', () => {\n        unsubscribe();\n        reject(signal.reason instanceof Error ? signal.reason : new Error('Wait for document aborted.'));\n      });\n    });\n  }\n\n  async exportDoc(id: AnyDocumentId): Promise<Uint8Array> {\n    invariant(this.isOpen, 'AutomergeHost is not open');\n    const documentId = interpretAsDocumentId(id);\n\n    const chunks = await this._storage.loadRange([documentId]);\n    return bufferToArray(Buffer.concat(chunks.map((c) => c.data!)));\n  }\n\n  /**\n   * The document's saved changes as storage holds them, without loading the document: its snapshot and\n   * incremental chunks, concatenated in the form `A.loadIncremental` reads. Undefined when storage holds\n   * none, or more than `limit` bytes.\n   */\n  async readStoredChanges(id: DocumentId, { limit }: { limit?: number } = {}): Promise<Uint8Array | undefined> {\n    invariant(this.isOpen, 'AutomergeHost is not open');\n    const chunks = await this._storage.loadRange([id]);\n    const changes = chunks.flatMap(({ key, data }) =>\n      (key[1] === 'snapshot' || key[1] === 'incremental') && data != null && data.length > 0 ? [data] : [],\n    );\n    const size = changes.reduce((sum, data) => sum + data.length, 0);\n    if (size === 0 || (limit !== undefined && size > limit)) {\n      return undefined;\n    }\n    return bufferToArray(Buffer.concat(changes));\n  }\n\n  /**\n   * Probe local storage to determine whether the document has any persisted\n   * chunks. Does not request the document from the network and does not\n   * touch the in-memory `Repo`. Returns `true` iff at least one non-empty\n   * chunk exists on disk for the document.\n   *\n   * Intended for query-driven (disk-only) loads that need to know quickly\n   * whether a document is locally available without waiting on network\n   * latency. See `DocumentsSynchronizer.addDocuments` and the `requesting`\n   * transition in `DocHandleProxy`.\n   */\n  async hasDocOnDisk(id: AnyDocumentId): Promise<boolean> {\n    invariant(this.isOpen, 'AutomergeHost is not open');\n    const documentId = interpretAsDocumentId(id);\n    const chunks = await this._storage.loadRange([documentId]);\n    return chunks.some((chunk) => chunk.data != null && chunk.data.length > 0);\n  }\n\n  /**\n   * Wipe a document from local storage: its automerge chunks and its heads-store row (both, or the\n   * heads row is orphaned). Used by garbage collection for documents that are no longer reachable\n   * from any space directory.\n   */\n  async removeDocument(id: AnyDocumentId): Promise<void> {\n    invariant(this.isOpen, 'AutomergeHost is not open');\n    const documentId = interpretAsDocumentId(id);\n    // Flushed, then evicted, so the handle cannot re-persist what is deleted below — collection loads\n    // the document to check ownership, so one is usually live here. Eviction only detaches the save\n    // listener; a throttled save already scheduled still runs, and the flush is what makes it a\n    // no-op, since its heads then match the last save.\n    if (this._repo.handles[documentId]) {\n      // A quarantined document's handle holds at most a partial load, which must not be saved over its bytes.\n      if (!this.#quarantined.has(documentId)) {\n        await this._repo.flush([documentId]);\n      }\n      await this._repo.removeFromCache(documentId);\n    }\n    // Dropped from the registry too: the document is about to stop existing, so a later eviction of\n    // it would re-create — and re-announce — the query this call deletes.\n    this._leases.forget(documentId);\n    this._confirmedChanges.delete(documentId);\n\n    // One write: the orphan scan enumerates the heads table, so chunks outliving their heads row could\n    // never be found again. Through the chunk write queue, so a save queued before it cannot land after.\n    const sedimentreeId = documentIdToSedimentreeIdHex(documentId);\n    await this._storage.enqueue(\n      Effect.gen({ self: this }, function* () {\n        yield* this._headsStore.remove(documentId);\n        yield* this._storage.removeRangeEffect([documentId]);\n        for (const family of SUBDUCTION_KEY_FAMILIES) {\n          yield* this._storage.removeRangeEffect([SUBDUCTION_PREFIX, family, sedimentreeId]);\n        }\n      }),\n    );\n\n    // The classical share policy answers from these, so an id left behind keeps being announced.\n    this._peerHeads.delete(documentId);\n    this._createdDocuments.delete(documentId);\n    this._documentsToSync.delete(documentId);\n    this._documentsToRequest.delete(documentId);\n    this._headsUpdates.delete(documentId);\n    for (const requested of this._documentsRequested.values()) {\n      requested.delete(documentId);\n    }\n    // A removed document never converges, so neither of the other cleanups (convergence of its\n    // collection, or its peer disconnecting) is guaranteed to reach its entry.\n    for (const [resyncKey, entry] of this._divergedResyncHeads) {\n      if (entry.documentId === documentId) {\n        this._divergedResyncHeads.delete(resyncKey);\n      }\n    }\n  }\n\n  /**\n   * Create new persisted document.\n   */\n  async createDoc<T>(initialValue?: T | Doc<T> | Uint8Array, opts?: CreateDocOptions): Promise<DocumentLease<T>> {\n    invariant(this.isOpen, 'AutomergeHost is not open');\n    if (opts?.preserveHistory) {\n      if (initialValue instanceof Uint8Array) {\n        const handle = this._repo.import<T>(initialValue, { docId: opts?.documentId });\n        return this._afterCreate<T>(handle.documentId);\n      }\n\n      if (!isAutomerge(initialValue)) {\n        throw new TypeError('Initial value must be an Automerge document');\n      }\n\n      // TODO(dmaretskyi): There's a more efficient way.\n      const handle = this._repo.import<T>(save(initialValue as Doc<T>), { docId: opts?.documentId });\n      return this._afterCreate<T>(handle.documentId);\n    } else {\n      if (initialValue instanceof Uint8Array) {\n        throw new Error('Cannot create document from Uint8Array without preserving history');\n      }\n\n      if (opts?.documentId) {\n        throw new Error('Cannot prefil document id when not importing an existing doc');\n      }\n      const handle = await this._repo.create2<T>(initialValue);\n      return this._afterCreate<T>(handle.documentId);\n    }\n  }\n\n  /** Leases a freshly created document and announces it, so the creator holds it until it lets go. */\n  private _afterCreate<T>(documentId: DocumentId): DocumentLease<T> {\n    this._createdDocuments.add(documentId);\n    this._sharePolicyChangedTask!.schedule();\n    return this._leases.acquire<T>(documentId);\n  }\n\n  async waitUntilHeadsReplicated(ctx: Context, heads: DataService.DocHeadsList): Promise<void> {\n    invariant(this.isOpen, 'AutomergeHost is not open');\n    const entries = heads.entries;\n    if (!entries?.length) {\n      return;\n    }\n    const documentIds = entries.map((entry) => entry.documentId as DocumentId);\n    const documentHeads = await this.getHeads(documentIds);\n    const headsToWait = entries.filter((entry, index) => {\n      const targetHeads = entry.heads;\n      if (!targetHeads || targetHeads.length === 0) {\n        return false;\n      }\n      const currentHeads = documentHeads[index];\n      return !(currentHeads !== null && currentHeads !== undefined && headsEquals(currentHeads, targetHeads));\n    });\n    if (headsToWait.length > 0) {\n      await Promise.all(\n        headsToWait.map(async (entry) => {\n          using lease = await this.loadDoc<DatabaseDirectory>(ctx, entry.documentId as DocumentId);\n          invariant(lease, 'Document handle must be available when waiting for heads replication.');\n          await waitForHeads(lease, entry.heads!);\n        }),\n      );\n    }\n\n    // Flush to disk handles loaded to memory also so that the indexer can pick up the changes.\n    await this._repo.flush(documentIds.filter((documentId) => getHandleState(this._repo, documentId) === 'ready'));\n  }\n\n  async reIndexHeads(documentIds: DocumentId[]): Promise<void> {\n    invariant(this.isOpen, 'AutomergeHost is not open');\n    for (const documentId of documentIds) {\n      log('re-indexing heads for document', { documentId });\n      // Bounded: `loadDoc` treats `'unavailable'` as transient, so a document no peer serves would\n      // otherwise block every document after it.\n      let lease: DocumentLease<any> | null;\n      try {\n        lease = await this.loadDoc(Context.default(), documentId, { timeout: REINDEX_LOAD_TIMEOUT });\n      } catch (err) {\n        log.error('failed to find document', { documentId, err });\n        continue;\n      }\n      if (!lease) {\n        continue;\n      }\n      using _lease = lease;\n\n      const heads = lease.heads();\n      if (!heads) {\n        continue;\n      }\n      await RuntimeProvider.runPromise(this._runtime)(this._headsStore.setHeads(documentId, heads));\n    }\n    log('done re-indexing heads');\n  }\n\n  /**\n   * Share policy for the Repo's classical automerge-repo sync path (CollectionSynchronizer /\n   * DocSynchronizer — see `src/synchronizer/DocSynchronizer.ts#resolveSharePolicy`).\n   *\n   * NOTE: Subduction replication does NOT consult `shareConfig`.\n   * {@link AutomergeReplicator}s via {@link EchoNetworkAdapter}.\n   */\n  private readonly _shareConfig = {\n    access: async (_peerId: PeerId, _documentId?: DocumentId): Promise<boolean> => {\n      // Access-on-request is always allowed; per-doc authorization happens in the replicator.\n      return true;\n    },\n\n    // TODO(dmaretskyi): Share based on HALO permissions and space affinity.\n    // Hosts, running in the worker, don't share documents unless requested by other peers.\n    // NOTE: If both peers return sharePolicy=false the replication will not happen\n    // https://github.com/automerge/automerge-repo/pull/292\n    // Called for all loaded documents so they could be advertised to the sync server.\n    announce: async (peerId: PeerId, documentId?: DocumentId): Promise<boolean> => {\n      if (!documentId) {\n        return false;\n      }\n\n      if (OPTIMIZED_SHARE_POLICY) {\n        if (\n          !this._createdDocuments.has(documentId) &&\n          !this._documentsToSync.has(documentId) &&\n          !this._documentsToRequest.has(documentId)\n        ) {\n          // Skip advertising documents that don't need to be synced.\n          return false;\n        }\n      }\n\n      const peerMetadata = this._repo.peerMetadataByPeerId[peerId];\n      if (isEchoPeerMetadata(peerMetadata)) {\n        return this._echoNetworkAdapter.shouldAdvertise(peerId, { documentId });\n      }\n\n      return false;\n    },\n  };\n\n  /**\n   * Subduction sedimentree authorization policy. Mirrors {@link _shareConfig.announce}\n   * on the OUTBOUND side (`authorizeFetch`, `filterAuthorizedFetch`) via the same\n   * per-connection `shouldAdvertise` predicate on `_echoNetworkAdapter`.\n   *\n   * `authorizePut` is intentionally allow-all to mirror classical sync (`useSubduction:\n   * false`), which has no inbound gate. Gating inbound here creates a bootstrapping\n   * deadlock during invitations: the joining peer's `_getContainingSpaceForDocument`\n   * cannot resolve the space-root doc until it's loaded, which can't happen if the\n   * inbound write is denied — and subduction `authorizePut` denials are sticky on the\n   * receiver (see .claude/skills/subduction/SKILL.md), so the entry never recovers.\n   * Inbound trust here is bounded by `authorizeFetch` on the sender side (peers can't\n   * push docs we wouldn't have served them) and by the sedimentree's internal\n   * cryptographic structure.\n   */\n  private readonly _subductionPolicy: SubductionPolicy = {\n    authorizeConnect: async (_subductionPeerId) => {\n      // Per-document gating below; no per-peer kill-switch.\n    },\n    authorizeFetch: async (subductionPeerId, sedimentreeId) => {\n      const allow = await this._shouldShareDocumentWithSubductionPeer(subductionPeerId, sedimentreeId);\n      // The throw below is the only record of a denial, and the peer's matching WASM warning is\n      // suppressed (see `_open`), so a refused document is otherwise invisible on both sides.\n      log.verbose('subduction authorizeFetch', {\n        documentId: sedimentreeIdToDocumentId(sedimentreeId),\n        subductionPeerId: subductionPeerId.toString(),\n        allow,\n      });\n      if (!allow) {\n        throw new Error('authorizeFetch denied by client share policy');\n      }\n    },\n    authorizePut: async (_requestor, _author, sedimentreeId) => {\n      // Intentionally permissive — see class-level comment above. Logged because this is the\n      // only signal that a peer actually delivered changes for a document.\n      const documentId = sedimentreeIdToDocumentId(sedimentreeId);\n      log.verbose('subduction authorizePut', { documentId });\n      // Sticky, which is what a quarantine wants: the pushed bytes would only be loaded again.\n      if (this.#quarantined.has(documentId)) {\n        throw new DocumentQuarantinedError({ context: { documentId } });\n      }\n    },\n    filterAuthorizedFetch: async (subductionPeerId, sedimentreeIds) => {\n      const allowed: SedimentreeId[] = [];\n      const denied: string[] = [];\n      for (const sid of sedimentreeIds) {\n        if (await this._shouldShareDocumentWithSubductionPeer(subductionPeerId, sid)) {\n          allowed.push(sid);\n        } else {\n          denied.push(sedimentreeIdToDocumentId(sid));\n        }\n      }\n      // Silently dropping ids from the response would otherwise leave no trace of the omission.\n      log.verbose('subduction filterAuthorizedFetch', {\n        subductionPeerId: subductionPeerId.toString(),\n        requested: sedimentreeIds.length,\n        allowed: allowed.length,\n        denied,\n      });\n      return allowed;\n    },\n  };\n\n  /**\n   * Translates subduction PeerId → repo PeerId and delegates to the per-connection\n   * `shouldAdvertise`. Default-allow when the binding hasn't arrived yet (narrow race\n   * window: the handshake event fires before any sedimentree sync round).\n   */\n  private async _shouldShareDocumentWithSubductionPeer(\n    subductionPeerId: SubductionPeerId,\n    sedimentreeId: SedimentreeId,\n  ): Promise<boolean> {\n    const subductionPeerIdHex = subductionPeerId.toString();\n    const repoPeerId = this._subductionPeerIdHexToRepoPeerId.get(subductionPeerIdHex);\n    const documentId = sedimentreeIdToDocumentId(sedimentreeId);\n    if (this.#quarantined.has(documentId)) {\n      return false;\n    }\n    if (!repoPeerId) {\n      // Default-allow on the unbound-peer race; logged because it bypasses the share policy.\n      log.verbose('subduction share probe: peer not bound, allowing', { documentId, subductionPeerIdHex });\n      return true;\n    }\n    const allow = await this._echoNetworkAdapter.shouldAdvertise(repoPeerId, { documentId });\n    log.verbose('subduction share probe', { documentId, peerId: repoPeerId, allow });\n    return allow;\n  }\n\n  private _shouldSyncCollection(collectionId: string, peerId: PeerId): boolean {\n    // Under Subduction the Repo's `peerMetadataByPeerId` is not populated for peers that only\n    // speak Subduction (no classical peer message). Query the adapter directly — it maps\n    // peerId -> connection and the per-connection `shouldSyncCollection` gates the answer.\n    return this._echoNetworkAdapter.shouldSyncCollection(peerId, { collectionId });\n  }\n\n  /**\n   * Called by SqliteStorageAdapter after a chunk is committed to SQLite.\n   * Updates heads store and schedules collection sync notification.\n   */\n  private async _afterSave(path: StorageKey): Promise<void> {\n    // The flush on close saves too, and its heads must still reach the store: a space root opened from its\n    // directory snapshot trusts them as the heads its stored changes are at.\n    if (this._lifecycleState === LifecycleState.CLOSED) {\n      return undefined;\n    }\n\n    if (path[0] === SUBDUCTION_PREFIX) {\n      // Subduction keys are `[prefix, family, sedimentreeId, ...]`, so they carry no documentId and\n      // fall through the handle lookup below unnoticed. A `remote-heads` write is the only\n      // persisted evidence that a head exchange with a peer completed for a document.\n      const [, family, sedimentreeId] = path;\n      if (family === 'remote-heads' && sedimentreeId) {\n        log.verbose('subduction remote-heads persisted', {\n          documentId: sedimentreeHexToDocumentId(sedimentreeId),\n          sedimentreeId,\n        });\n      }\n      return;\n    }\n\n    const documentId = path[0] as DocumentId;\n    const handle = this._repo.getHandle(documentId);\n    if (!handle) {\n      return;\n    }\n    const document = handle.doc();\n    if (!document) {\n      return;\n    }\n\n    const heads = getHeads(document);\n    const { numChanges, numOps } = stats(document);\n    this.#reportOversizedDocument(documentId, { changes: numChanges, ops: numOps });\n\n    // Persist heads to SQLite. Non-atomic with the chunk save but recoverable:\n    // heads can be reconstructed from chunks via reIndexHeads on restart.\n    await RuntimeProvider.runPromise(this._runtime)(this._headsStore.setHeads(documentId, heads));\n    if (!this.isOpen) {\n      return;\n    }\n\n    this._headsUpdates.set(documentId, heads);\n    invariant(this._onHeadsChangedTask, 'onHeadsChangedTask is not initialized');\n    this._onHeadsChangedTask.schedule();\n    this.documentsSaved.emit();\n  }\n\n  /**\n   * Warns when a document passes {@link OVERSIZED_DOCUMENT_CHANGES} changes or {@link OVERSIZED_DOCUMENT_OPS} ops,\n   * and again at every doubling: a document that keeps growing eventually cannot be loaded at all.\n   */\n  #reportOversizedDocument(documentId: DocumentId, { changes, ops }: DocumentSize): void {\n    const level = oversizeLevel({ changes, ops });\n    if (level <= (this.#oversizeReported.get(documentId) ?? -1)) {\n      return;\n    }\n    this.#oversizeReported.set(documentId, level);\n    log.warn('oversized automerge document', {\n      documentId,\n      changes,\n      ops,\n      changesLimit: OVERSIZED_DOCUMENT_CHANGES,\n      opsLimit: OVERSIZED_DOCUMENT_OPS,\n    });\n  }\n\n  private async _isDocumentInRemoteCollection(params: RemoteDocumentExistenceCheckProps): Promise<boolean> {\n    for (const collectionId of this._collectionSynchronizer.getRegisteredCollectionIds()) {\n      const remoteCollections = this._collectionSynchronizer.getRemoteCollectionStates(collectionId);\n      const remotePeerDocs = remoteCollections.get(params.peerId as PeerId)?.documents;\n      if (remotePeerDocs && params.documentId in remotePeerDocs) {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  private async _getContainingSpaceForDocument(documentId: string): Promise<PublicKey | null> {\n    // This runs inside share-policy resolution (see `MeshEchoReplicator.shouldAdvertise` ->\n    // `_shareConfig.announce` -> `DocSynchronizer.#resolveSharePolicy`). It must NOT block\n    // on the document becoming ready: under classical sync the network source's availability\n    // is itself gated on share policy returning, so awaiting `progress.whenReady()` here\n    // deadlocks the load (the document never transitions out of `'loading'`).\n    //\n    // Read the spaceKey iff the document is already loaded; otherwise let the share policy\n    // fall through to the `_getSpaceKeyByRootDocumentId` lookup or the\n    // `isDocumentInRemoteCollection` check on the caller.\n    const handle = this._repo.getHandle(documentId as DocumentId);\n    if (handle && getHandleState(this._repo, documentId as DocumentId) === 'ready') {\n      const doc = handle.doc();\n      if (doc) {\n        const spaceKeyHex = DatabaseDirectory.getSpaceKey(doc);\n        if (spaceKeyHex) {\n          return PublicKey.from(spaceKeyHex);\n        }\n      }\n    }\n\n    // Edge case on initial space setup: a peer may be sharing the space root document\n    // with us after a successful invitation, before our local handle has any data.\n    const rootDocSpaceKey = this._getSpaceKeyByRootDocumentId?.(documentId);\n    if (rootDocSpaceKey) {\n      return rootDocSpaceKey;\n    }\n\n    return null;\n  }\n\n  private _isInLocalCollection(documentId: DocumentId): boolean {\n    return this._collectionSynchronizer\n      .getRegisteredCollectionIds()\n      .some(\n        (collectionId) =>\n          documentId in (this._collectionSynchronizer.getLocalCollectionState(collectionId)?.documents ?? {}),\n      );\n  }\n\n  /**\n   * Resolve the space id owning a document for the share policy.\n   *\n   * Membership is answered first from the local collection state — the space root's document\n   * list (root + linked docs), maintained by `updateLocalCollectionState`. That mapping survives\n   * handle eviction and never blocks on the document loading, so a doc the node owns but whose\n   * handle is evicted or still `'loading'` resolves to its space instead of reading as \"not in any\n   * space\" and producing a spurious `authorizeFetch`/share-policy denial (logged by the peer as\n   * `not authorized to access sedimentree`). This must stay synchronous for the same reason\n   * `_getContainingSpaceForDocument` refuses to await the load: the network source's availability\n   * is itself gated on the share policy returning, so awaiting the document here would deadlock.\n   *\n   * Falls back to the document's own embedded space key (loaded handle) / the root-doc lookup for\n   * a doc not yet linked into any local collection (e.g. inbound during initial sync).\n   */\n  async getContainingSpaceIdForDocument(documentId: string): Promise<SpaceId | null> {\n    for (const collectionId of this._collectionSynchronizer.getRegisteredCollectionIds()) {\n      const state = this._collectionSynchronizer.getLocalCollectionState(collectionId);\n      if (!state || !(documentId in state.documents)) {\n        continue;\n      }\n      // Only space collections (`space:<spaceId>[:<root>]`) carry a resolvable owner; a non-space\n      // collection id yields null (rather than throwing on the share-policy path) and the scan\n      // continues to the next registered collection.\n      const spaceId = tryGetSpaceIdFromCollectionId(collectionId);\n      if (spaceId) {\n        return spaceId;\n      }\n    }\n\n    const spaceKey = await this._getContainingSpaceForDocument(documentId);\n    return spaceKey ? createIdFromSpaceKey(spaceKey) : null;\n  }\n\n  /**\n   * Flush documents to disk.\n   *\n   * Persists ready handles via `_repo.flush`. Head updates are published into\n   * the collection synchronizer asynchronously by {@link _onHeadsChangedTask};\n   * callers needing an up-to-date sync-state view should subscribe to\n   * {@link collectionStateUpdated} rather than sampling immediately after flush.\n   */\n  @trace.span({ showInBrowserTimeline: true, showInRemoteTracing: false })\n  async flush(ctx: Context, { documentIds }: DataService.FlushRequest = {}): Promise<void> {\n    if (!this.isOpen) {\n      return;\n    }\n    const loadedDocuments = (documentIds ?? Object.keys(this._repo.handles)).filter(\n      (documentId): documentId is DocumentId => getHandleState(this._repo, documentId as DocumentId) === 'ready',\n    );\n    await this._repo.flush(loadedDocuments);\n  }\n\n  /**\n   * Returns current heads of each requested document.\n   *\n   * Loaded handles are read directly; unloaded documents fall back to the {@link SqliteHeadsStore},\n   * then to reconstruction from the automerge storage chunks (for docs persisted before\n   * the SqliteHeadsStore was populated).\n   */\n  async getHeads(documentIds: DocumentId[]): Promise<(Heads | undefined)[]> {\n    const result: (Heads | undefined)[] = [];\n    const storeRequestIds: DocumentId[] = [];\n    const storeResultIndices: number[] = [];\n    for (const documentId of documentIds) {\n      const handle = this._repo.getHandle(documentId);\n      if (handle && getHandleState(this._repo, documentId) === 'ready' && handle.doc()) {\n        result.push(getHeads(handle.doc()!));\n      } else {\n        storeRequestIds.push(documentId);\n        storeResultIndices.push(result.length);\n        result.push(undefined);\n      }\n    }\n    if (storeRequestIds.length > 0) {\n      const storedHeads = await this._headsStore.getHeads(storeRequestIds);\n      for (let i = 0; i < storedHeads.length; i++) {\n        result[storeResultIndices[i]] = storedHeads[i];\n      }\n    }\n    return result;\n  }\n\n  /** The heads each document's saved changes reach, from the heads store, whatever is loaded and unsaved. */\n  async getStoredHeads(documentIds: DocumentId[]): Promise<(Heads | undefined)[]> {\n    return this._headsStore.getHeads(documentIds);\n  }\n\n  /**\n   * Iterate over all document heads stored on disk.\n   */\n  listDocumentHeads(): AsyncGenerator<{ documentId: DocumentId; heads: Heads }> {\n    return this._headsStore.iterateAll();\n  }\n\n  //\n  // Collection sync.\n  //\n\n  getLocalCollectionState(collectionId: string): CollectionState | undefined {\n    return this._collectionSynchronizer.getLocalCollectionState(collectionId);\n  }\n\n  getRemoteCollectionStates(collectionId: string): ReadonlyMap<PeerId, CollectionState> {\n    return this._collectionSynchronizer.getRemoteCollectionStates(collectionId);\n  }\n\n  refreshCollection(collectionId: string): void {\n    this._collectionSynchronizer.refreshCollection(collectionId);\n  }\n\n  /**\n   * Snapshot of local-vs-remote collection state for the given collectionId.\n   *\n   * Eventually consistent. A single emission via `collectionStateUpdated` may\n   * reflect stale local heads if a local save is mid-propagation through\n   * `_onHeadsChangedTask` (the deferred task that publishes `_afterSave` head\n   * updates into `_collectionSynchronizer`). The follow-up emission from\n   * `_onHeadsChanged` will reflect the up-to-date heads. Consumers must not\n   * treat any single emission as authoritative; subscribe to the stream and\n   * converge.\n   *\n   */\n  async getCollectionSyncState(collectionId: string): Promise<DataService.SpaceSyncState> {\n    const result: DataService.SpaceSyncState = {\n      peers: [],\n    };\n\n    const localState = this.getLocalCollectionState(collectionId);\n    const remoteState = this.getRemoteCollectionStates(collectionId);\n\n    if (!localState) {\n      return result;\n    }\n\n    for (const [peerId, state] of remoteState) {\n      const isEdgePeer = isEdgePeerId(peerId);\n      // For edge peers, intersect the remote view with the local key set so\n      // edge orphans (sedimentrees the edge still knows about but the local\n      // root no longer references) don't inflate counts or appear unsynced.\n      const effectiveRemote = isEdgePeer ? subsetRemoteToLocal(localState, state) : state;\n      const diff = diffCollectionStateForPeer(localState, state, {\n        isEdgePeer,\n        hasLocalChange: (documentId, changeHash) => this._hasLocalChange(documentId, changeHash),\n      });\n      result.peers!.push({\n        peerId,\n        missingOnRemote: diff.missingOnRemote.length,\n        missingOnLocal: diff.missingOnLocal.length,\n        differentDocuments: diff.different.length,\n        localDocumentCount: Object.entries(localState.documents).filter(([_, heads]) => heads.length > 0).length,\n        remoteDocumentCount: Object.entries(effectiveRemote.documents).filter(([_, heads]) => heads.length > 0).length,\n        totalDocumentCount: new Set([...Object.keys(localState.documents), ...Object.keys(effectiveRemote.documents)])\n          .size,\n        unsyncedDocumentCount: new Set([...diff.missingOnLocal, ...diff.missingOnRemote, ...diff.different]).size,\n      });\n    }\n\n    return result;\n  }\n\n  /**\n   * Update the local collection state based on the locally stored document heads.\n   */\n  async updateLocalCollectionState(collectionId: string, allDocumentIds: DocumentId[]): Promise<void> {\n    // Never advertised: a peer would replicate the document to us or ask us to serve it.\n    const documentIds = allDocumentIds.filter((documentId) => !this.#quarantined.has(documentId));\n    const heads = await this.getHeads(documentIds);\n    const documents: Record<DocumentId, Heads> = Object.fromEntries(\n      heads.map((heads, index) => [documentIds[index], heads ?? []]),\n    );\n    this._collectionSynchronizer.setLocalCollectionState(collectionId, { documents });\n    // Notify subscribers (e.g. data-service `subscribeSpaceSyncState`) that local state changed.\n    // `setLocalCollectionState` only emits `peerCollectionStateUpdated` for peers that already\n    // have a recorded remote state; on a fresh space (no remote yet) the membership refresh\n    // would otherwise be silent and subscribers would never wake up. The sibling local-write\n    // path in `_onHeadsChanged` follows the same \"mutate, then emit\" pattern.\n    this.collectionStateUpdated.emit({ collectionId: collectionId as CollectionId });\n\n    // Proactively push our updated local state to peers that are interested in this collection.\n    // This reduces reliance on the next periodic query and prevents replication stalls in fast\n    // paths where the remote queries before our local state is ready.\n    const interestedPeers = this._echoNetworkAdapter.getPeersInterestedInCollection(collectionId);\n    if (interestedPeers.length > 0) {\n      for (const peerId of interestedPeers) {\n        this._sendCollectionState(collectionId, peerId, { documents });\n      }\n    }\n  }\n\n  async clearLocalCollectionState(collectionId: string): Promise<void> {\n    this._collectionSynchronizer.clearLocalCollectionState(collectionId);\n    // With no local state `_handleCollectionSync` returns before its convergence cleanup, so a\n    // cleared collection's entries would otherwise outlive it and suppress the first resync if it\n    // is registered again.\n    for (const [resyncKey, entry] of this._divergedResyncHeads) {\n      if (entry.collectionId === collectionId) {\n        this._divergedResyncHeads.delete(resyncKey);\n      }\n    }\n  }\n\n  /** For the collection diff: an evicted document holds only the changes confirmed while it was resident. */\n  private _hasLocalChange(documentId: DocumentId, changeHash: string): boolean {\n    // A malformed head is unanswerable, and calling it missing would keep the document `different` forever.\n    if (!CHANGE_HASH_PATTERN.test(changeHash)) {\n      return true;\n    }\n    const doc =\n      this._repo && getHandleState(this._repo, documentId) === 'ready'\n        ? this._repo.getHandle(documentId)?.doc()\n        : undefined;\n    if (!doc) {\n      return this._confirmedChanges.get(documentId)?.has(changeHash) ?? false;\n    }\n    if (!changeIsPresentInDoc(doc, changeHash)) {\n      return false;\n    }\n    this._confirmChange(documentId, changeHash);\n    return true;\n  }\n\n  private async _confirmFromStorage(\n    documentIds: DocumentId[],\n    localState: CollectionState,\n    remoteState: CollectionState,\n  ): Promise<DocumentId[]> {\n    const unconfirmed: DocumentId[] = [];\n    for (const documentId of documentIds) {\n      const local = localState.documents[documentId] ?? [];\n      const beyond = (remoteState.documents[documentId] ?? []).filter(\n        (head) => !local.includes(head) && !this._hasLocalChange(documentId, head),\n      );\n      if (beyond.length === 0) {\n        continue;\n      }\n      const isStored = await this._storedHistoryCheck(documentId, local);\n      if (beyond.every(isStored)) {\n        for (const head of beyond) {\n          this._confirmChange(documentId, head);\n        }\n      } else {\n        unconfirmed.push(documentId);\n      }\n    }\n    return unconfirmed;\n  }\n\n  private async _storedHistoryCheck(\n    documentId: DocumentId,\n    heads: readonly string[],\n  ): Promise<(hash: string) => boolean> {\n    const sedimentreeId = documentIdToSedimentreeIdHex(documentId);\n    const families = ['commits', 'fragments'] as const;\n    const records = await Promise.all(\n      families.map((family) => this._storage.loadRange([SUBDUCTION_PREFIX, family, sedimentreeId])),\n    );\n    const beneath = new Map<string, string[]>();\n    families.forEach((family, index) => {\n      for (const { key, data } of records[index]) {\n        if (key.length === 4 && data) {\n          try {\n            beneath.set(key[3], recordDependencies(family, data));\n          } catch (err) {\n            log.warn('unreadable subduction record', { documentId, family, err });\n          }\n        }\n      }\n    });\n\n    const known = new Map<string, boolean>(heads.map((head) => [head, true]));\n    return (hash) => {\n      const stack = [hash];\n      const visiting = new Set<string>();\n      while (stack.length > 0) {\n        const current = stack[stack.length - 1];\n        if (known.has(current)) {\n          stack.pop();\n          continue;\n        }\n        const dependencies = this._hasLocalChange(documentId, current) ? [] : beneath.get(current);\n        if (dependencies === undefined) {\n          known.set(current, false);\n          stack.pop();\n          continue;\n        }\n        const pending = dependencies.filter((dependency) => !known.has(dependency));\n        if (pending.length > 0 && !visiting.has(current)) {\n          visiting.add(current);\n          stack.push(...pending);\n          continue;\n        }\n        known.set(\n          current,\n          dependencies.every((dependency) => known.get(dependency) === true),\n        );\n        stack.pop();\n      }\n      return known.get(hash) === true;\n    };\n  }\n\n  private _confirmChange(documentId: DocumentId, changeHash: string): void {\n    const confirmed = this._confirmedChanges.get(documentId) ?? new Set<string>();\n    if (!confirmed.has(changeHash) && confirmed.size >= MAX_CONFIRMED_PER_DOCUMENT) {\n      confirmed.clear();\n    }\n    confirmed.add(changeHash);\n    // Re-inserted so iteration starts at the least recently confirmed document, which the cap drops.\n    this._confirmedChanges.delete(documentId);\n    this._confirmedChanges.set(documentId, confirmed);\n    if (this._confirmedChanges.size > MAX_CONFIRMED_DOCUMENTS) {\n      const [leastRecent] = this._confirmedChanges.keys();\n      this._confirmedChanges.delete(leastRecent);\n    }\n  }\n\n  private _onCollectionStateQueried(collectionId: string, peerId: PeerId): void {\n    this._collectionSynchronizer.onCollectionStateQueried(collectionId, peerId);\n  }\n\n  private _onCollectionStateReceived(collectionId: string, peerId: PeerId, state: unknown): void {\n    this._collectionSynchronizer.onRemoteStateReceived(collectionId, peerId, decodeCollectionState(state));\n  }\n\n  private _queryCollectionState(collectionId: string, peerId: PeerId): void {\n    this._echoNetworkAdapter.queryCollectionState(collectionId, peerId);\n  }\n\n  private _sendCollectionState(collectionId: string, peerId: PeerId, state: CollectionState): void {\n    this._echoNetworkAdapter.sendCollectionState(collectionId, peerId, encodeCollectionState(state));\n  }\n\n  private _onPeerConnected(peerId: PeerId): void {\n    this._collectionSynchronizer.onConnectionOpen(peerId);\n  }\n\n  private _onPeerDisconnected(peerId: PeerId): void {\n    // Passes are only consecutive within one connection.\n    for (const syncKey of this._nonConvergingSyncPasses.keys()) {\n      if (syncKey.endsWith(`:${peerId}`)) {\n        this._nonConvergingSyncPasses.delete(syncKey);\n      }\n    }\n    // A reconnect is a fresh chance for the push that did not land, so the resync budget resets\n    // with the connection.\n    for (const [resyncKey, entry] of this._divergedResyncHeads) {\n      if (entry.peerId === peerId) {\n        this._divergedResyncHeads.delete(resyncKey);\n      }\n    }\n    for (const peerHeads of this._peerHeads.values()) {\n      peerHeads.delete(peerId);\n    }\n    this._collectionSynchronizer.onConnectionClosed(peerId);\n  }\n\n  private _onRemoteCollectionStateUpdated(collectionId: string, peerId: PeerId): void {\n    this._collectionsToSync.add({ collectionId, peerId });\n    this._syncTask?.schedule();\n  }\n\n  private async _handleCollectionSync(ctx: Context, collectionId: string, peerId: PeerId) {\n    const localState = this._collectionSynchronizer.getLocalCollectionState(collectionId);\n    const remoteState = this._collectionSynchronizer.getRemoteCollectionStates(collectionId).get(peerId);\n\n    if (!localState || !remoteState) {\n      return;\n    }\n\n    const diff = diffCollectionStateForPeer(localState, remoteState, {\n      isEdgePeer: isEdgePeerId(peerId),\n      hasLocalChange: (documentId, changeHash) => this._hasLocalChange(documentId, changeHash),\n    });\n    const { different, missingOnLocal, missingOnRemote } = diff;\n    const advertised = this._useSubduction\n      ? await this._confirmFromStorage(diff.advertised, localState, remoteState)\n      : diff.advertised;\n    if (ctx.disposed) {\n      return;\n    }\n\n    const syncKey = `${collectionId}:${peerId}`;\n    if (different.length === 0 && missingOnLocal.length === 0 && missingOnRemote.length === 0) {\n      this._nonConvergingSyncPasses.delete(syncKey);\n      // An advertised document keeps its entry, so the same heads kick one sync round, not one per pass.\n      const kicked = new Set<string>(advertised);\n      for (const [resyncKey, entry] of this._divergedResyncHeads) {\n        if (entry.collectionId === collectionId && entry.peerId === peerId && !kicked.has(entry.documentId)) {\n          this._divergedResyncHeads.delete(resyncKey);\n        }\n      }\n    } else {\n      this._reportNonConvergence(collectionId, peerId, localState, remoteState, {\n        different,\n        missingOnLocal,\n        missingOnRemote,\n      });\n    }\n\n    // An advertised document is in sync, but a sync round costs little and delivers the change if it is new.\n    // A mesh peer's diff is symmetric, so it can still offer a document this host quarantined.\n    const toReplicate = [...different, ...advertised, ...missingOnRemote, ...missingOnLocal].filter(\n      (documentId) => !this.#quarantined.has(documentId),\n    );\n    const differentSet = new Set([...different, ...advertised]);\n\n    if (toReplicate.length === 0) {\n      return;\n    }\n\n    // Per-handle state included: a document stuck in `unavailable`/`loading` here on every diff\n    // pass is the signature of a subduction DocumentQuery parked without retry —\n    // `findWithProgress` will not re-issue the query, so the doc never arrives.\n    log('replicating documents after collection sync', {\n      collectionId,\n      peerId,\n      count: toReplicate.length,\n      handleStates: Object.fromEntries(\n        toReplicate.map((documentId) => [documentId, getHandleState(this._repo, documentId)]),\n      ),\n    });\n\n    // Trigger replication of the missing documents. `findWithProgress` is the\n    // fire-and-forget trigger — it creates a DocHandle and attaches sources. Under classical\n    // sync this triggers automerge-repo's doc-synchronizer; under Subduction it registers a\n    // query for the sedimentreeId. Either way, once bytes arrive `_afterSave` populates\n    // `SqliteHeadsStore` so collection sync sees the updated heads on the next diff.\n\n    // Whether this pass has anything left for the classical share policy to act on. Only a pass\n    // consisting entirely of diverged documents whose resync is already spent has nothing: for\n    // those the policy is provably a no-op (`shareConfigChanged` revives only `all-failed` /\n    // `no-peers` entries, and a diverged-but-settled entry is neither), while re-arming it\n    // re-probes every document against every connection. The answering peer reports heads for\n    // each, and Subduction persists a `remote-heads` record the first time it hears a document's\n    // heads from a peer; with edge coming back under a new Subduction identity after every restart,\n    // each restart turned the next probe into one fresh row per document. That is the storage\n    // growth this branch used to drive.\n    //\n    // A pass that *issues* a resync still schedules it, so first-pass behaviour is unchanged and\n    // only the repeating tail is dropped.\n    let sharePolicyCanHelp = false;\n\n    for (const documentId of toReplicate) {\n      // `findWithProgress` resolves from the existing query for an already-`ready` document and\n      // `_documentsToSync` feeds a share policy Subduction does not consult, so neither moves a\n      // diverged document, resident or not. `resyncDocument` is the lever for a resident one: it\n      // clears the heal state and marks the entry never-synced, so Subduction opens a fresh\n      // bidirectional round (`syncWithAllPeers` reports both `commitsSent` and `commitsReceived`) —\n      // which is what delivers a local commit the peer never received. An evicted one needs no\n      // lever: `_leaseUntilSettled` below faults it in and `SubductionSource.attach` gives it a\n      // fresh never-synced entry.\n      if (this._useSubduction && differentSet.has(documentId)) {\n        const resyncKey = JSON.stringify([collectionId, peerId, documentId]);\n        // Both sides' heads: a round already spent against this exact pair cannot do better, but\n        // either side advancing means the situation changed and is worth another.\n        const heads = `${(localState.documents[documentId] ?? []).join(',')}|${(remoteState.documents[documentId] ?? []).join(',')}`;\n        if (this._divergedResyncHeads.get(resyncKey)?.heads === heads) {\n          // Verbose: this fires on every diff pass for docs that are in practice fully synced,\n          // so at warn level it floods the console without indicating a real fault.\n          log.verbose('diverged document already resynced at these heads', {\n            collectionId,\n            peerId,\n            documentId,\n            sedimentreeId: documentIdToSedimentreeIdHex(documentId),\n          });\n          continue;\n        }\n        this._divergedResyncHeads.set(resyncKey, { collectionId, peerId, documentId, heads });\n        if (isDocumentLoaded(this._repo, documentId)) {\n          log('resyncing diverged document', {\n            collectionId,\n            peerId,\n            documentId,\n            sedimentreeId: documentIdToSedimentreeIdHex(documentId),\n            localHeads: localState.documents[documentId],\n            remoteHeads: remoteState.documents[documentId],\n          });\n          this.resyncDocument(documentId);\n          sharePolicyCanHelp = true;\n        }\n      } else {\n        sharePolicyCanHelp = true;\n      }\n      this._documentsToSync.add(documentId);\n      this._leaseUntilSettled(documentId as DocumentId);\n    }\n\n    if (sharePolicyCanHelp) {\n      this._sharePolicyChangedTask!.schedule();\n    }\n  }\n\n  /** Counts a pass that left the pair diverged, with both sides' heads so a stuck document is diagnosable from logs. */\n  private _reportNonConvergence(\n    collectionId: string,\n    peerId: PeerId,\n    localState: CollectionState,\n    remoteState: CollectionState,\n    { different, missingOnLocal, missingOnRemote }: Omit<CollectionStateDiff, 'advertised'>,\n  ): void {\n    const syncKey = `${collectionId}:${peerId}`;\n    const passes = (this._nonConvergingSyncPasses.get(syncKey) ?? 0) + 1;\n    this._nonConvergingSyncPasses.set(syncKey, passes);\n    const overThreshold = passes - NON_CONVERGENCE_WARN_THRESHOLD;\n    if (overThreshold >= 0 && overThreshold % NON_CONVERGENCE_WARN_INTERVAL === 0) {\n      // Reported for the undelivered documents as well as the diverged ones: a pair stuck on a\n      // permanent `missingOnRemote` otherwise logs every detail field empty, which reads as \"never\n      // got a handle\" when the document is resident and the remote holds a headless fragment for it.\n      const stuck = [...different, ...missingOnRemote];\n      const context = {\n        collectionId,\n        peerId,\n        passes,\n        missingOnLocal,\n        missingOnRemote,\n        different,\n        localHeads: Object.fromEntries(stuck.map((documentId) => [documentId, localState.documents[documentId]])),\n        remoteHeads: Object.fromEntries(stuck.map((documentId) => [documentId, remoteState.documents[documentId]])),\n        // Subduction addresses documents by sedimentree id, so without this a log bundle cannot be\n        // searched for the stuck document's storage or policy activity.\n        sedimentreeIds: Object.fromEntries(\n          stuck.map((documentId) => [documentId, documentIdToSedimentreeIdHex(documentId)]),\n        ),\n        handleStates: Object.fromEntries(\n          stuck.map((documentId) => [documentId, getHandleState(this._repo, documentId)]),\n        ),\n      };\n      // Two call sites rather than an aliased log function: `@dxos/log` injects call metadata at\n      // the call site, so an alias loses its file and line.\n      if (passes >= NON_CONVERGENCE_ERROR_THRESHOLD) {\n        log.error('collection sync not converging', context);\n      } else {\n        log.warn('collection sync not converging', context);\n      }\n    }\n  }\n\n  /**\n   * Leases a document until its query settles, which both triggers replication and keeps the\n   * document resident while its bytes are in flight — nothing else holds it until they land.\n   *\n   * Bounded by {@link REPLICATION_LEASE_TIMEOUT} rather than waiting for `'ready'` forever: a peer\n   * can advertise a document it never delivers, and `'unavailable'` is transient here (the query\n   * reports it whenever no source can serve the document *yet*), so it cannot be the release signal.\n   */\n  private _leaseUntilSettled(documentId: DocumentId): void {\n    if (this._replicationLeases.has(documentId) || this.#quarantined.has(documentId)) {\n      return;\n    }\n    const lease = this.acquireDoc(documentId);\n    this._replicationLeases.set(documentId, lease);\n    let timer: ReturnType<typeof setTimeout> | undefined;\n    const release = () => {\n      clearTimeout(timer);\n      if (this._replicationLeases.delete(documentId)) {\n        lease[Symbol.dispose]();\n      }\n    };\n    const settled = (state: HandleQueryState) => state === 'ready' || state === 'failed';\n    if (settled(lease.state)) {\n      release();\n      return;\n    }\n    const unsubscribe = lease.subscribe(({ state }) => {\n      if (settled(state)) {\n        unsubscribe();\n        release();\n      }\n    });\n    timer = setTimeout(() => {\n      log('replication lease expired before the document settled', { documentId });\n      unsubscribe();\n      release();\n    }, REPLICATION_LEASE_TIMEOUT);\n  }\n\n  private _onHeadsChanged(docHeads: [DocumentId, Heads][]): void {\n    for (const [documentId, heads] of docHeads) {\n      this.documentHeadsChanged.emit({ documentId, heads });\n    }\n\n    const collectionsChanged = new Set<CollectionId>();\n\n    for (const collectionId of this._collectionSynchronizer.getRegisteredCollectionIds()) {\n      const state = this._collectionSynchronizer.getLocalCollectionState(collectionId);\n      if (!state) {\n        continue;\n      }\n      let documents: Record<DocumentId, Heads> | undefined;\n\n      for (const [documentId, heads] of docHeads) {\n        const current = state.documents[documentId];\n        // Collection membership is owned by `updateLocalCollectionState` (driven by\n        // `SpaceStateManager.spaceDocumentListUpdated`). `_afterSave` fires for every\n        // chunk written — including the space root, system docs, and transiently-fetched\n        // docs that haven't been admitted to any collection — so we only refresh heads\n        // for documents the membership path has already registered. Adding new keys\n        // here would leak non-collection docs into the broadcast state and race with\n        // the authoritative rebuild in `updateLocalCollectionState`.\n        if (current === undefined) {\n          continue;\n        }\n        if (headsEquals(current, heads)) {\n          continue;\n        }\n        documents ??= { ...state.documents };\n        documents[documentId] = heads;\n      }\n\n      if (documents) {\n        this._collectionSynchronizer.setLocalCollectionState(collectionId, { documents });\n        collectionsChanged.add(collectionId as CollectionId);\n      }\n    }\n\n    for (const collectionId of collectionsChanged) {\n      this.collectionStateUpdated.emit({ collectionId });\n    }\n  }\n}\n\nconst waitForHeads = async (lease: DocumentLease<DatabaseDirectory>, heads: Heads) => {\n  const unavailableHeads = new Set(heads);\n\n  // Check the current doc first, then subscribe to `change` to catch later\n  // updates. (We can't use the handle's readiness to gate the subscription —\n  // see {@link getHandleState} for why `DocHandle.*` state is unusable in\n  // this fork.)\n  const checkPresentHeads = () => {\n    const doc = lease.doc();\n    if (!doc) {\n      return;\n    }\n    for (const changeHash of unavailableHeads.values()) {\n      if (changeIsPresentInDoc(doc, changeHash)) {\n        unavailableHeads.delete(changeHash);\n      }\n    }\n  };\n\n  checkPresentHeads();\n  if (unavailableHeads.size === 0) {\n    return;\n  }\n\n  await new Promise<void>((resolve) => {\n    const onChange = () => {\n      checkPresentHeads();\n      if (unavailableHeads.size === 0) {\n        lease.off('change', onChange);\n        resolve();\n      }\n    };\n    lease.on('change', onChange);\n  });\n};\n\nconst recordDependencies = (family: 'commits' | 'fragments', data: Uint8Array): string[] => {\n  const toHex = (ids: CommitId[]) =>\n    ids.map((id) => {\n      try {\n        return id.toHexString();\n      } finally {\n        id.free();\n      }\n    });\n  if (family === 'commits') {\n    const signed = SignedLooseCommit.tryDecode(data);\n    const commit = signed.payload;\n    try {\n      return toHex(commit.parents);\n    } finally {\n      commit.free();\n      signed.free();\n    }\n  }\n  const signed = SignedFragment.tryDecode(data);\n  const fragment = signed.payload;\n  try {\n    return toHex(fragment.boundary);\n  } finally {\n    fragment.free();\n    signed.free();\n  }\n};\n\n/** A hex-encoded change hash, the only form `getChangeByHash` accepts. */\nconst CHANGE_HASH_PATTERN = /^[0-9a-f]{64}$/;\n\nconst MAX_CONFIRMED_PER_DOCUMENT = 64;\n\nconst MAX_CONFIRMED_DOCUMENTS = 1_000;\n\nconst changeIsPresentInDoc = (doc: Doc<any>, changeHash: string): boolean => {\n  return !!getBackend(doc).getChangeByHash(changeHash);\n};\n\nconst decodeCollectionState = (state: unknown): CollectionState => {\n  invariant(typeof state === 'object' && state !== null, 'Invalid state');\n\n  return state as CollectionState;\n};\n\nconst encodeCollectionState = (state: CollectionState): unknown => {\n  return state;\n};\n\n/**\n * Inverse of `toSedimentreeId` in `@automerge/automerge-repo/src/subduction/helpers.ts`:\n * truncate the 32-byte SedimentreeId to its first 16 bytes and base58check-encode.\n */\nconst sedimentreeIdToDocumentId = (sedimentreeId: SedimentreeId): DocumentId =>\n  bs58check.encode(sedimentreeId.toBytes().slice(0, 16)) as DocumentId;\n\n/**\n * The sedimentree id `SubductionStorageBridge` embeds in its storage keys: the 16-byte DocumentId\n * zero-padded to 32, lowercase hex. Derived arithmetically so sweeping never requires the\n * subduction WASM module to be initialized; `sqlite-storage-adapter.test.ts` pins the two against\n * each other.\n */\n/**\n * Inverse of {@link documentIdToSedimentreeIdHex}, for naming the document behind a storage key.\n * Decodes the leading 16 bytes by hand — `Buffer` is not available in the browser worker.\n */\nconst sedimentreeHexToDocumentId = (sedimentreeIdHex: string): DocumentId => {\n  const bytes = new Uint8Array(16);\n  for (let index = 0; index < 16; index++) {\n    bytes[index] = Number.parseInt(sedimentreeIdHex.slice(index * 2, index * 2 + 2), 16);\n  }\n  return bs58check.encode(bytes) as DocumentId;\n};\n\nexport const documentIdToSedimentreeIdHex = (documentId: DocumentId): string => {\n  const bytes = new Uint8Array(32);\n  bytes.set(bs58check.decode(documentId).subarray(0, 16));\n  return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as A from '@automerge/automerge';\nimport { cbor } from '@automerge/automerge-repo';\nimport { create } from '@bufbuild/protobuf';\n\nimport { Resource } from '@dxos/context';\nimport { invariant } from '@dxos/invariant';\nimport { type PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport type { AutomergeProtocolMessage } from '@dxos/protocols';\nimport { SyncMessageSchema } from '@dxos/protocols/buf/dxos/mesh/teleport/automerge_pb';\nimport { AutomergeReplicator, type AutomergeReplicatorFactory } from '@dxos/teleport-extension-automerge-replicator';\n\nimport type {\n  AutomergeReplicatorConnection,\n  ShouldAdvertiseProps,\n  ShouldSyncCollectionProps,\n} from './echo-replicator.ts';\n\nconst DEFAULT_FACTORY: AutomergeReplicatorFactory = (params) => new AutomergeReplicator(...params);\n\nexport type MeshReplicatorConnectionProps = {\n  ownPeerId: string;\n  onRemoteConnected: () => void;\n  onRemoteDisconnected: () => void;\n  shouldAdvertise: (params: ShouldAdvertiseProps) => Promise<boolean>;\n  shouldSyncCollection: (params: ShouldSyncCollectionProps) => boolean;\n  replicatorFactory?: AutomergeReplicatorFactory;\n};\n\nexport class MeshReplicatorConnection extends Resource implements AutomergeReplicatorConnection {\n  public readable: ReadableStream<AutomergeProtocolMessage>;\n  public writable: WritableStream<AutomergeProtocolMessage>;\n  public remoteDeviceKey: PublicKey | null = null;\n\n  public readonly replicatorExtension: AutomergeReplicator;\n\n  private _remotePeerId: string | null = null;\n  private _isEnabled = false;\n  /** Set once the teleport extension is destroyed, after which no write can reach the remote. */\n  #closed = false;\n\n  constructor(private readonly _params: MeshReplicatorConnectionProps) {\n    super();\n\n    let readableStreamController!: ReadableStreamDefaultController<AutomergeProtocolMessage>;\n    this.readable = new ReadableStream<AutomergeProtocolMessage>({\n      start: (controller) => {\n        readableStreamController = controller;\n        this._ctx.onDispose(() => controller.close());\n      },\n    });\n\n    this.writable = new WritableStream<AutomergeProtocolMessage>({\n      write: async (message: AutomergeProtocolMessage, controller) => {\n        // A closed or disabled connection has no live extension behind it, so the message is dropped\n        // rather than thrown at a fire-and-forget caller.\n        if (this.#closed || !this._isEnabled) {\n          log('dropping message for an inactive connection', { peerId: this._remotePeerId, type: message.type });\n          return;\n        }\n\n        try {\n          logSendSync(message);\n          await this.replicatorExtension.sendSyncMessage(create(SyncMessageSchema, { payload: cbor.encode(message) }));\n        } catch (err) {\n          controller.error(err);\n          this._disconnectIfEnabled();\n        }\n      },\n    });\n\n    const createAutomergeReplicator = this._params.replicatorFactory ?? DEFAULT_FACTORY;\n    this.replicatorExtension = createAutomergeReplicator([\n      {\n        peerId: this._params.ownPeerId,\n      },\n      {\n        onStartReplication: async (info, remotePeerId /** Teleport ID */) => {\n          // Note: We store only one enabled extension per peer.\n          //       There can be a case where two connected peers have more than one teleport connection between them\n          //       and each of them uses different teleport connections to send messages.\n          //       It works because we receive messages from all teleport connections and Automerge Repo dedup them.\n          // TODO(mykola): Use only one teleport connection per peer.\n\n          this.remoteDeviceKey = remotePeerId;\n\n          // Set automerge id.\n          this._remotePeerId = info.id;\n\n          log('onStartReplication', { id: info.id, thisPeerId: this.peerId, remotePeerId: remotePeerId.toHex() });\n\n          this._params.onRemoteConnected();\n        },\n        onSyncMessage: async ({ payload }) => {\n          if (!this._isEnabled) {\n            return;\n          }\n          const message = cbor.decode(payload) as AutomergeProtocolMessage;\n          // Note: automerge Repo dedup messages.\n          readableStreamController.enqueue(message);\n        },\n        onClose: async () => {\n          this.#closed = true;\n          // A disabled connection must be retired too, or it stays queued for promotion and the\n          // network adapter later writes to its destroyed extension (DX-1279).\n          if (this._remotePeerId != null) {\n            this._params.onRemoteDisconnected();\n          }\n        },\n      },\n    ]);\n  }\n\n  private _disconnectIfEnabled(): void {\n    if (this._isEnabled) {\n      this._params.onRemoteDisconnected();\n    }\n  }\n\n  get peerId(): string {\n    invariant(this._remotePeerId != null, 'Remote peer has not connected yet.');\n    return this._remotePeerId;\n  }\n\n  get isEnabled() {\n    return this._isEnabled;\n  }\n\n  get isClosed(): boolean {\n    return this.#closed;\n  }\n\n  async shouldAdvertise(params: ShouldAdvertiseProps): Promise<boolean> {\n    return this._params.shouldAdvertise(params);\n  }\n\n  shouldSyncCollection(params: ShouldSyncCollectionProps): boolean {\n    return this._params.shouldSyncCollection(params);\n  }\n\n  /**\n   * Start exchanging messages with the remote peer.\n   * Call after the remote peer has connected.\n   */\n  enable(): void {\n    invariant(this._remotePeerId != null, 'Remote peer has not connected yet.');\n    this._isEnabled = true;\n  }\n\n  /**\n   * Stop exchanging messages with the remote peer.\n   */\n  disable(): void {\n    this._isEnabled = false;\n  }\n}\n\nconst logSendSync = (message: AutomergeProtocolMessage) => {\n  log('sendSyncMessage', () => {\n    let decodedSyncMessage: ReturnType<typeof A.decodeSyncMessage> | undefined;\n    if (message.type === 'sync' && message.data) {\n      try {\n        decodedSyncMessage = A.decodeSyncMessage(message.data);\n      } catch {\n        // Ignore malformed sync message data for logging purposes.\n      }\n    }\n    return {\n      sync: decodedSyncMessage && {\n        headsLength: decodedSyncMessage.heads.length,\n        requesting: decodedSyncMessage.need.length > 0,\n        sendingChanges: decodedSyncMessage.changes.length > 0,\n      },\n      type: message.type,\n      from: message.senderId,\n      to: message.targetId,\n    };\n  });\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as EffectContext from 'effect/Context';\nimport * as Layer from 'effect/Layer';\n\nimport { type Context } from '@dxos/context';\nimport { type CollectionId } from '@dxos/echo-protocol';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey, type SpaceId } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport type * as TeleportAutomergeReplicator from '@dxos/teleport-extension-automerge-replicator';\nimport { ComplexSet, defaultMap } from '@dxos/util';\n\nimport {\n  type AutomergeReplicator,\n  type AutomergeReplicatorContext,\n  type ShouldAdvertiseProps,\n} from './echo-replicator.ts';\nimport { MeshReplicatorConnection } from './mesh-echo-replicator-connection.ts';\nimport { getSpaceIdFromCollectionId } from './space-collection.ts';\n\n// TODO(dmaretskyi): Move out of @dxos/echo-host.\n\n/**\n * Used to replicate with other peers over the network.\n */\nexport class MeshEchoReplicator implements AutomergeReplicator {\n  /**\n   * We might have multiple connections open with a peer (one per space), but there'll be only one enabled\n   * connection at any given moment, because there's a single repo for all the spaces.\n   * When a connection closes (space was closed) it gets removed from the list and the next connection\n   * in the line gets enabled.\n   */\n  private readonly _connectionsPerPeer = new Map<string, MeshReplicatorConnection[]>();\n  /**\n   * A set of all connections (enabled and disabled).\n   */\n  private readonly _connections = new Set<MeshReplicatorConnection>();\n\n  /**\n   * spaceId -> deviceKey[]\n   */\n  private readonly _authorizedDevices = new Map<SpaceId, ComplexSet<PublicKey>>();\n\n  private _context: AutomergeReplicatorContext | null = null;\n\n  async connect(_ctx: Context, context: AutomergeReplicatorContext): Promise<void> {\n    this._context = context;\n  }\n\n  async disconnect(): Promise<void> {\n    for (const connection of this._connections) {\n      if (connection.isEnabled) {\n        this._context?.onConnectionClosed(connection);\n      }\n    }\n\n    for (const connection of this._connections) {\n      await connection.close();\n    }\n\n    this._connections.clear();\n    this._connectionsPerPeer.clear();\n\n    this._context = null;\n  }\n\n  createExtension(\n    extensionFactory?: TeleportAutomergeReplicator.AutomergeReplicatorFactory,\n  ): TeleportAutomergeReplicator.AutomergeReplicator {\n    invariant(this._context);\n\n    const connection: MeshReplicatorConnection = new MeshReplicatorConnection({\n      ownPeerId: this._context.peerId,\n      replicatorFactory: extensionFactory,\n      onRemoteConnected: async () => {\n        log('onRemoteConnected', { peerId: connection.peerId });\n        invariant(this._context);\n\n        const existingConnections = this._connectionsPerPeer.get(connection.peerId);\n        if (existingConnections?.length) {\n          const enabledConnection = existingConnections[0];\n          this._context.onConnectionAuthScopeChanged(enabledConnection);\n          existingConnections.push(connection);\n        } else {\n          this._connectionsPerPeer.set(connection.peerId, [connection]);\n          this._context.onConnectionOpen(connection);\n          connection.enable();\n        }\n      },\n      onRemoteDisconnected: async () => {\n        log('onRemoteDisconnected', { peerId: connection.peerId });\n\n        this._connections.delete(connection);\n\n        const existingConnections = this._connectionsPerPeer.get(connection.peerId) ?? [];\n\n        const index = existingConnections.indexOf(connection);\n        if (index < 0) {\n          log.warn('disconnected connection not found', { peerId: connection.peerId });\n          return;\n        }\n\n        existingConnections.splice(index, 1);\n\n        // A closed connection's extension is destroyed, so promoting it would hand the adapter a peer\n        // it can never write to (DX-1279).\n        const liveConnections = existingConnections.filter((candidate) => !candidate.isClosed);\n        this._connectionsPerPeer.set(connection.peerId, liveConnections);\n\n        if (connection.isEnabled) {\n          this._context?.onConnectionClosed(connection);\n          connection.disable();\n\n          // Promote the next connection to enabled\n          if (liveConnections.length > 0) {\n            this._context?.onConnectionOpen(liveConnections[0]);\n            liveConnections[0].enable();\n          }\n        }\n      },\n      shouldAdvertise: async (params: ShouldAdvertiseProps) => {\n        log('shouldAdvertise', { peerId: connection.peerId, documentId: params.documentId });\n        invariant(this._context);\n        try {\n          // Resolve space membership via `getContainingSpaceIdForDocument`, which answers from the\n          // local collection state (the space root's document list) and so still identifies a doc\n          // the node owns whose handle is evicted or still loading.\n          const spaceId = await this._context.getContainingSpaceIdForDocument(params.documentId);\n          if (!spaceId) {\n            const remoteDocumentExists = await this._context.isDocumentInRemoteCollection({\n              documentId: params.documentId,\n              peerId: connection.peerId,\n            });\n            log('document not found locally for share policy check', {\n              peerId: connection.peerId,\n              documentId: params.documentId,\n              acceptDocument: remoteDocumentExists,\n            });\n\n            // If a document is not present locally return true if another peer claims to have it.\n            // Simply returning true will add the peer to \"generous peers list\" for this document which will\n            // start replication of the document after we receive, even if the peer is not in the corresponding space.\n            return remoteDocumentExists;\n          }\n\n          const authorizedDevices = this._authorizedDevices.get(spaceId);\n\n          if (!connection.remoteDeviceKey) {\n            log('device key not found for share policy check', {\n              peerId: connection.peerId,\n              documentId: params.documentId,\n            });\n            return false;\n          }\n\n          const isAuthorized = authorizedDevices?.has(connection.remoteDeviceKey) ?? false;\n          log('share policy check', {\n            localPeer: this._context.peerId,\n            remotePeer: connection.peerId,\n            documentId: params.documentId,\n            deviceKey: connection.remoteDeviceKey,\n            spaceId,\n            isAuthorized,\n          });\n          return isAuthorized;\n        } catch (err) {\n          log.catch(err);\n          return false;\n        }\n      },\n      shouldSyncCollection: ({ collectionId }) => {\n        const spaceId = getSpaceIdFromCollectionId(collectionId as CollectionId);\n\n        const authorizedDevices = this._authorizedDevices.get(spaceId);\n\n        if (!connection.remoteDeviceKey) {\n          log('device key not found for collection sync check', {\n            peerId: connection.peerId,\n            collectionId,\n          });\n          return false;\n        }\n\n        const isAuthorized = authorizedDevices?.has(connection.remoteDeviceKey) ?? false;\n        return isAuthorized;\n      },\n    });\n    this._connections.add(connection);\n\n    return connection.replicatorExtension;\n  }\n\n  /**\n   * Takes a space id rather than a key: a root-anchored space's id is not derivable from its key, so\n   * deriving here would record the authorization under an id no document belongs to.\n   */\n  async authorizeDevice(spaceId: SpaceId, deviceKey: PublicKey): Promise<void> {\n    log('authorizeDevice', { spaceId, deviceKey });\n    defaultMap(this._authorizedDevices, spaceId, () => new ComplexSet(PublicKey.hash)).add(deviceKey);\n    for (const connection of this._connections) {\n      if (connection.isEnabled && connection.remoteDeviceKey && connection.remoteDeviceKey.equals(deviceKey)) {\n        if (this._connectionsPerPeer.has(connection.peerId)) {\n          this._context?.onConnectionAuthScopeChanged(connection);\n        }\n      }\n    }\n  }\n}\n\n/**\n * Effect service tag for {@link MeshEchoReplicator}.\n *\n * Distinct from the generic {@link AutomergeReplicatorService} because `DataSpaceManager` drives\n * mesh-specific hooks (`authorizeDevice`, `createExtension`) not present on the base interface.\n */\nexport class MeshEchoReplicatorService extends EffectContext.Service<MeshEchoReplicatorService, MeshEchoReplicator>()(\n  '@dxos/echo-host/MeshEchoReplicator',\n) {}\n\n/**\n * Effect Layer constructing a {@link MeshEchoReplicator}.\n */\nexport const MeshEchoReplicatorLayer = (): Layer.Layer<MeshEchoReplicatorService> =>\n  Layer.succeed(MeshEchoReplicatorService, new MeshEchoReplicator());\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as EffectContext from 'effect/Context';\n\nimport { type Context } from '@dxos/context';\nimport { type PublicKey, type SpaceId } from '@dxos/keys';\nimport { type AutomergeProtocolMessage, type SubductionProtocolMessage } from '@dxos/protocols';\n\n/**\n * Union of every shape the read/write streams below can carry.\n *\n * @remarks\n * - {@link AutomergeProtocolMessage}: the classical automerge-repo sync frames\n *   (carried by mesh replication and the in-memory `TestAdapter`).\n * - {@link SubductionProtocolMessage}: the in-process subduction shape\n *   (carried by `EchoEdgeSubductionReplicator` — envelopes are unwrapped to\n *   raw `SubductionConnectionMessage` before they reach the stream).\n *\n * The interface uses the union so a single `EchoNetworkAdapter` instance can\n * be wired behind either replicator without resorting to type casts at the\n * boundary.\n */\nexport type ReplicatorConnectionMessage = AutomergeProtocolMessage | SubductionProtocolMessage;\n\n// TODO(burdon): Rename AutomergeReplicator?\nexport interface AutomergeReplicator {\n  /**\n   * Called on when replicator is added to EchoHost.\n   */\n  connect(ctx: Context, context: AutomergeReplicatorContext): Promise<void>;\n\n  /**\n   * Called on when replicator is removed from EchoHost.\n   */\n  disconnect(): Promise<void>;\n}\n\n/**\n * Effect service tag for {@link AutomergeReplicator}.\n */\nexport class AutomergeReplicatorService extends EffectContext.Service<\n  AutomergeReplicatorService,\n  AutomergeReplicator\n>()('@dxos/echo-host/AutomergeReplicator') {}\n\n/**\n * Replicator with explicit per-space wiring (used by edge replicators that maintain one logical\n * connection per `SpaceId`). `DataSpaceManager` drives these lifecycle hooks on space open/close.\n */\nexport interface EdgeAutomergeReplicator extends AutomergeReplicator {\n  connectToSpace(ctx: Context, spaceId: SpaceId): Promise<void>;\n  disconnectFromSpace(spaceId: SpaceId): Promise<void>;\n}\n\n/**\n * Effect service tag for {@link EdgeAutomergeReplicator}.\n */\nexport class EdgeAutomergeReplicatorService extends EffectContext.Service<\n  EdgeAutomergeReplicatorService,\n  EdgeAutomergeReplicator\n>()('@dxos/echo-host/EdgeAutomergeReplicator') {}\n\nexport interface AutomergeReplicatorContext {\n  /**\n   * Our own peer id.\n   */\n  get peerId(): string;\n\n  /**\n   * @deprecated Use `getContainingSpaceIdForDocument`.\n   */\n  getContainingSpaceForDocument(documentId: string): Promise<PublicKey | null>;\n  getContainingSpaceIdForDocument(documentId: string): Promise<SpaceId | null>;\n\n  /**\n   * Returns false if collection sync hasn't happened yet.\n   */\n  isDocumentInRemoteCollection(params: RemoteDocumentExistenceCheckProps): Promise<boolean>;\n\n  onConnectionOpen(connection: AutomergeReplicatorConnection): void;\n  onConnectionClosed(connection: AutomergeReplicatorConnection): void;\n  onConnectionAuthScopeChanged(connection: AutomergeReplicatorConnection): void;\n\n  /**\n   * Re-run the peer's transport handshake on a connection that stays open, so the peer id and the\n   * sync state keyed by it survive a remote that lost its session but not the link (DX-1275).\n   *\n   * @returns `false` when the peer has no open connection, so the caller can fall back to a restart.\n   */\n  onConnectionTransportReset(connection: AutomergeReplicatorConnection): boolean;\n}\n\nexport interface AutomergeReplicatorConnection {\n  /**\n   * Remote peer id.\n   */\n  get peerId(): string;\n\n  /**\n   * Stream to read messages coming from the remote peer.\n   */\n  readable: ReadableStream<ReplicatorConnectionMessage>;\n\n  /**\n   * Stream to write messages to the remote peer.\n   */\n  writable: WritableStream<ReplicatorConnectionMessage>;\n\n  /**\n   * @returns true if the document should be advertised to this peer.\n   * The remote peer can still request the document by its id bypassing this check.\n   */\n  shouldAdvertise(params: ShouldAdvertiseProps): Promise<boolean>;\n\n  /**\n   * @returns true if the collection should be synced to this peer.\n   */\n  shouldSyncCollection(params: ShouldSyncCollectionProps): boolean;\n}\n\nexport type ShouldAdvertiseProps = {\n  documentId: string;\n};\n\nexport type ShouldSyncCollectionProps = {\n  collectionId: string;\n};\n\nexport type RemoteDocumentExistenceCheckProps = {\n  peerId: string;\n  documentId: string;\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport { type Message } from '@automerge/automerge-repo';\n\nimport { trace } from '@dxos/tracing';\nimport { CircularBuffer, SlidingWindowSummary, type SlidingWindowSummaryConfig, mapValues } from '@dxos/util';\n\nimport { type NetworkDataMonitor } from './echo-network-adapter.ts';\nimport { isCollectionQueryMessage, isCollectionStateMessage } from './network-protocol.ts';\nimport { type StorageAdapterDataMonitor } from './sqlite-storage-adapter.ts';\n\nconst PER_SECOND_RATE_AVG_WINDOW_SIZE = 5;\nconst DEFAULT_AVG_WINDOW_SIZE = 25;\n\nexport type EchoDataMonitorOptions = {\n  timeSeriesLength: number;\n};\n\nexport class EchoDataMonitor implements StorageAdapterDataMonitor, NetworkDataMonitor {\n  private _lastTick = 0;\n\n  private _activeCounters = createLocalCounters();\n  private _lastCompleteCounters: LocalCounters | undefined;\n  private readonly _localTimeSeries = createLocalTimeSeries();\n  private readonly _storageAverages = createStorageAverages();\n  private readonly _replicationAverages = createNetworkAverages();\n  private readonly _sizeByMessage: { [type: string]: SlidingWindowSummary } = {};\n  private readonly _lastReceivedMessages = new CircularBuffer<StoredMessage>(100);\n  private readonly _lastSentMessages = new CircularBuffer<StoredMessage>(100);\n\n  private _connectionsCount = 0;\n\n  constructor(private readonly _params: EchoDataMonitorOptions = { timeSeriesLength: 30 }) {}\n\n  public tick(timeMs: number): void {\n    this._advanceTimeWindow(timeMs - this._lastTick);\n    this._lastTick = timeMs;\n  }\n\n  public computeStats(): EchoDataStats {\n    return {\n      meta: {\n        rateAverageOverSeconds: PER_SECOND_RATE_AVG_WINDOW_SIZE,\n      },\n      storage: {\n        reads: {\n          payloadSize: this._storageAverages.loadedChunkSize.average(),\n          opDuration: this._storageAverages.loadDuration.average(),\n          countPerSecond: this._storageAverages.loadsPerSecond.average(),\n        },\n        writes: {\n          payloadSize: this._storageAverages.storedChunkSize.average(),\n          opDuration: this._storageAverages.storeDuration.average(),\n          countPerSecond: this._storageAverages.storesPerSecond.average(),\n        },\n      },\n      replicator: {\n        connections: this._connectionsCount,\n        receivedMessages: {\n          payloadSize: this._replicationAverages.receivedMessageSize.average(),\n          countPerSecond: this._replicationAverages.receivedPerSecond.average(),\n        },\n        sentMessages: {\n          payloadSize: this._replicationAverages.sentMessageSize.average(),\n          opDuration: this._replicationAverages.sendDuration.average(),\n          countPerSecond: this._replicationAverages.sentPerSecond.average(),\n          failedPerSecond: this._replicationAverages.sendsFailedPerSecond.average(),\n        },\n        countByMessage: this._computeMessageHistogram('type'),\n        avgSizeByMessage: mapValues(this._sizeByMessage, (summary) => summary.average()),\n      },\n    };\n  }\n\n  public get connectionsCount() {\n    return this._connectionsCount;\n  }\n\n  /**\n   * @internal\n   */\n  get lastPerSecondStats() {\n    return this._lastCompleteCounters;\n  }\n\n  /**\n   * @internal\n   */\n  get timeSeries() {\n    return { ...this._localTimeSeries.storage, ...this._localTimeSeries.replication };\n  }\n\n  /**\n   * @internal\n   */\n  get messagesByPeerId() {\n    return this._computeMessageHistogram('peerId');\n  }\n\n  private _advanceTimeWindow(millisPassed: number): void {\n    const oldMetrics = Object.freeze(this._activeCounters);\n    this._activeCounters = createLocalCounters();\n    this._lastCompleteCounters = oldMetrics;\n    for (const peerId of Object.keys(oldMetrics.byPeerId)) {\n      this._activeCounters.byPeerId[peerId] = createMessageCounter();\n    }\n    this._addToTimeSeries(oldMetrics.replication, this._localTimeSeries.replication);\n    this._addToTimeSeries(oldMetrics.storage, this._localTimeSeries.storage);\n    // Prevent skewed measurements of incomplete buckets / after CPU freezes.\n    if (Math.abs(millisPassed - 1000) < 100) {\n      this._reportPerSecondRate(oldMetrics);\n    }\n  }\n\n  private _addToTimeSeries<T extends object>(values: T, timeSeries: TimeSeries<T>): void {\n    for (const [key, value] of Object.entries(values)) {\n      const values: (typeof value)[] = (timeSeries as any)[key];\n      values.push(value);\n      if (values.length > this._params.timeSeriesLength) {\n        values.shift();\n      }\n    }\n  }\n\n  private _reportPerSecondRate(metrics: LocalCounters): void {\n    const toReport: [string, number, SlidingWindowSummary][] = [\n      ['storage.load', metrics.storage.loadedChunks, this._storageAverages.loadsPerSecond],\n      ['storage.store', metrics.storage.storedChunks, this._storageAverages.storesPerSecond],\n      ['network.receive', metrics.replication.received, this._replicationAverages.receivedPerSecond],\n      ['network.send', metrics.replication.sent, this._replicationAverages.sentPerSecond],\n    ];\n    for (const [metricName, metric, summary] of toReport) {\n      summary.record(metric);\n      if (metric > 0) {\n        trace.metrics.distribution(`dxos.echo.${metricName}-rate`, metric);\n        trace.metrics.increment(`dxos.echo.${metricName}`, 1, { tags: { status: 'busy' } });\n      } else {\n        trace.metrics.increment(`dxos.echo.${metricName}`, 1, { tags: { status: 'idle' } });\n      }\n    }\n    this._replicationAverages.sendsFailedPerSecond.record(metrics.replication.failed);\n  }\n\n  public recordPeerConnected(peerId: string): void {\n    this._activeCounters.byPeerId[peerId] = createMessageCounter();\n    this._connectionsCount++;\n  }\n\n  public recordPeerDisconnected(peerId: string): void {\n    this._connectionsCount--;\n    delete this._activeCounters.byPeerId[peerId];\n  }\n\n  public recordBytesStored(count: number): void {\n    this._activeCounters.storage.storedChunks++;\n    this._activeCounters.storage.storedBytes += count;\n    this._storageAverages.storedChunkSize.record(count);\n    trace.metrics.distribution('dxos.echo.storage.bytes-stored', count, { unit: 'bytes' });\n  }\n\n  public recordLoadDuration(durationMs: number): void {\n    this._storageAverages.loadDuration.record(durationMs);\n  }\n\n  public recordStoreDuration(durationMs: number): void {\n    this._storageAverages.storeDuration.record(durationMs);\n  }\n\n  public recordBytesLoaded(count: number): void {\n    this._activeCounters.storage.loadedChunks++;\n    this._activeCounters.storage.loadedBytes += count;\n    this._storageAverages.loadedChunkSize.record(count);\n    trace.metrics.distribution('dxos.echo.storage.bytes-loaded', count, { unit: 'bytes' });\n  }\n\n  public recordMessageSent(message: Message, duration: number): void {\n    let metricsGroupName;\n    const bytes = getByteCount(message);\n    const tags = { type: message.type };\n    if (isAutomergeProtocolMessage(message)) {\n      this._activeCounters.replication.sent++;\n      this._replicationAverages.sendDuration.record(duration);\n      this._replicationAverages.sentMessageSize.record(bytes);\n      metricsGroupName = 'replication';\n    } else {\n      metricsGroupName = 'collection-sync';\n    }\n    trace.metrics.distribution(`dxos.echo.${metricsGroupName}.bytes-sent`, bytes, { unit: 'bytes', tags });\n    trace.metrics.distribution(`dxos.echo.${metricsGroupName}.send-duration`, duration, { unit: 'millisecond', tags });\n    trace.metrics.increment(`dxos.echo.${metricsGroupName}.send-status`, 1, { tags: { ...tags, success: true } });\n    const { messageSize, messageCounts } = this._getStatsForType(message);\n    messageSize.record(bytes);\n    messageCounts.sent++;\n    this._lastSentMessages.push({ type: message.type, peerId: message.targetId });\n  }\n\n  public recordMessageReceived(message: Message): void {\n    const bytes = getByteCount(message);\n    const tags = { type: message.type };\n    if (isAutomergeProtocolMessage(message)) {\n      this._activeCounters.replication.received++;\n      this._replicationAverages.receivedMessageSize.record(bytes);\n      trace.metrics.distribution('dxos.echo.replication.bytes-received', bytes, { unit: 'bytes', tags });\n    } else {\n      trace.metrics.distribution('dxos.echo.collection-sync.bytes-received', bytes, { unit: 'bytes', tags });\n    }\n    const { messageSize, messageCounts } = this._getStatsForType(message);\n    messageSize.record(bytes);\n    messageCounts.received++;\n    this._lastReceivedMessages.push({ type: message.type, peerId: message.senderId });\n  }\n\n  public recordMessageSendingFailed(message: Message): void {\n    const tags = { type: message.type, success: false };\n    if (isAutomergeProtocolMessage(message)) {\n      this._activeCounters.replication.failed++;\n      trace.metrics.increment('dxos.echo.replication.send-status', 1, { unit: 'bytes', tags });\n    } else {\n      trace.metrics.increment('dxos.echo.collection-sync.send-status', 1, { unit: 'bytes', tags });\n    }\n    const { messageCounts } = this._getStatsForType(message);\n    messageCounts.failed++;\n  }\n\n  private _getStatsForType(message: Message): { messageCounts: MessageCounts; messageSize: SlidingWindowSummary } {\n    const messageSize = (this._sizeByMessage[message.type] ??= createSlidingWindow());\n    const messageCounts = (this._activeCounters.byType[message.type] ??= createMessageCounter());\n    return { messageCounts, messageSize };\n  }\n\n  private _computeMessageHistogram(groupKey: keyof StoredMessage): MessageAttributeHistogram {\n    const result: MessageAttributeHistogram = {};\n    for (const receivedMessage of this._lastReceivedMessages) {\n      const counters = (result[receivedMessage[groupKey]] ??= { received: 0, sent: 0 });\n      counters.received++;\n    }\n    for (const receivedMessage of this._lastSentMessages) {\n      const counters = (result[receivedMessage[groupKey]] ??= { received: 0, sent: 0 });\n      counters.sent++;\n    }\n    return result;\n  }\n}\n\ntype BaseDataOpStats = {\n  payloadSize: number;\n  countPerSecond: number;\n};\n\nexport type TimedDataOpStats = BaseDataOpStats & { opDuration: number };\n\ntype TimeSeries<T extends object> = { [key in keyof T]: T[key][] };\n\ntype StorageCounts = {\n  storedChunks: number;\n  storedBytes: number;\n  loadedChunks: number;\n  loadedBytes: number;\n};\ntype StorageCountTimeSeries = TimeSeries<StorageCounts>;\n\ntype MessageCounts = {\n  sent: number;\n  received: number;\n  failed: number;\n};\ntype MessageCountTimeSeries = TimeSeries<MessageCounts>;\n\ntype MessageAttributeHistogram = {\n  [Message: string]: {\n    received: number;\n    sent: number;\n  };\n};\n\nexport type EchoDataStats = {\n  meta: {\n    rateAverageOverSeconds: number;\n  };\n  storage: {\n    reads: TimedDataOpStats;\n    writes: TimedDataOpStats;\n  };\n  replicator: {\n    connections: number;\n    receivedMessages: BaseDataOpStats;\n    sentMessages: TimedDataOpStats & { failedPerSecond: number };\n    avgSizeByMessage: { [Message: string]: number };\n    countByMessage: MessageAttributeHistogram;\n  };\n};\n\ntype StoredMessage = { type: string; peerId: string };\n\ntype StorageAverages = {\n  storedChunkSize: SlidingWindowSummary;\n  storesPerSecond: SlidingWindowSummary;\n  loadedChunkSize: SlidingWindowSummary;\n  loadsPerSecond: SlidingWindowSummary;\n  loadDuration: SlidingWindowSummary;\n  storeDuration: SlidingWindowSummary;\n};\n\n// TODO(burdon): Standardize: `sent`/`recv`.\ntype NetworkAverages = {\n  receivedMessageSize: SlidingWindowSummary;\n  receivedPerSecond: SlidingWindowSummary;\n  sentMessageSize: SlidingWindowSummary;\n  sentPerSecond: SlidingWindowSummary;\n  sendDuration: SlidingWindowSummary;\n  sendsFailedPerSecond: SlidingWindowSummary;\n};\n\ntype LocalCounters = {\n  storage: StorageCounts;\n  replication: MessageCounts;\n  byPeerId: { [peerId: string]: MessageCounts };\n  byType: { [type: string]: MessageCounts };\n};\n\ntype LocalTimeSeries = {\n  storage: StorageCountTimeSeries;\n  replication: MessageCountTimeSeries;\n};\n\nconst isAutomergeProtocolMessage = (message: Message) => {\n  return !(isCollectionQueryMessage(message) || isCollectionStateMessage(message));\n};\n\nconst createSlidingWindow = (overrides?: SlidingWindowSummaryConfig) =>\n  new SlidingWindowSummary({ dataPoints: DEFAULT_AVG_WINDOW_SIZE, precision: 2, ...overrides });\n\nconst createLocalCounters = (): LocalCounters => ({\n  storage: { loadedBytes: 0, storedBytes: 0, storedChunks: 0, loadedChunks: 0 },\n  replication: createMessageCounter(),\n  byPeerId: {},\n  byType: {},\n});\n\nconst createLocalTimeSeries = (): LocalTimeSeries => ({\n  storage: { loadedBytes: [], storedBytes: [], storedChunks: [], loadedChunks: [] },\n  replication: { sent: [], failed: [], received: [] },\n});\n\nconst createMessageCounter = (): MessageCounts => ({ sent: 0, received: 0, failed: 0 });\n\nconst createNetworkAverages = (): NetworkAverages => ({\n  receivedMessageSize: createSlidingWindow(),\n  sentMessageSize: createSlidingWindow(),\n  sendDuration: createSlidingWindow(),\n  receivedPerSecond: createSlidingWindow({ dataPoints: PER_SECOND_RATE_AVG_WINDOW_SIZE }),\n  sentPerSecond: createSlidingWindow({ dataPoints: PER_SECOND_RATE_AVG_WINDOW_SIZE }),\n  sendsFailedPerSecond: createSlidingWindow({ dataPoints: PER_SECOND_RATE_AVG_WINDOW_SIZE }),\n});\n\nconst createStorageAverages = (): StorageAverages => ({\n  storedChunkSize: createSlidingWindow(),\n  loadedChunkSize: createSlidingWindow(),\n  loadDuration: createSlidingWindow(),\n  storeDuration: createSlidingWindow(),\n  loadsPerSecond: createSlidingWindow({ dataPoints: PER_SECOND_RATE_AVG_WINDOW_SIZE }),\n  storesPerSecond: createSlidingWindow({ dataPoints: PER_SECOND_RATE_AVG_WINDOW_SIZE }),\n});\n\nconst getByteCount = (message: Message): number => {\n  return (\n    message.type.length +\n    message.senderId.length +\n    message.targetId.length +\n    (message.data?.byteLength ?? 0) +\n    (message.documentId?.length ?? 0)\n  );\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport { next as A, type Heads } from '@automerge/automerge';\nimport { type DocumentId } from '@automerge/automerge-repo';\n\nimport { UpdateScheduler, asyncTimeout } from '@dxos/async';\nimport { Context, LifecycleState, Resource } from '@dxos/context';\nimport { BACKED_DIRECTORY_LIMIT, type DatabaseDirectory, backingJson, directoryJson } from '@dxos/echo-protocol';\nimport { objectStructureToJson } from '@dxos/echo/internal';\nimport { invariant } from '@dxos/invariant';\nimport { type EntityId } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { type DataService } from '@dxos/protocols/rpc';\nimport { countWork } from '@dxos/util';\n\nimport { type AutomergeHost, type DocumentLease } from '../automerge/index.ts';\nimport { sameHeads } from '../query/object-state.ts';\n\nconst MAX_UPDATE_FREQ = 10; // [updates/sec]\n\n/**\n * Ceilings on one batch. A first sync can make thousands of documents pending inside one tick, and\n * the client decodes and integrates a batch as one message, so the remainder waits for the next tick.\n * The byte ceiling is soft: a batch closes after the document that crosses it.\n */\nconst MAX_BATCH_BYTES = 1024 * 1024;\nconst MAX_BATCH_DOCUMENTS = 500;\n\n/**\n * Bound on loading a document to read or write it. A document a client subscribes to is on disk or\n * was just created, so a load that takes longer than this is a document that is gone.\n */\nconst RELOAD_TIMEOUT = 10_000;\n\nexport type DocumentsSynchronizerProps = {\n  automergeHost: AutomergeHost;\n  sendUpdates: (updates: DataService.BatchedDocumentUpdates) => void;\n  /** Override of {@link MAX_BATCH_BYTES}. */\n  maxBatchBytes?: number;\n  /** Override of {@link MAX_BATCH_DOCUMENTS}. */\n  maxBatchDocuments?: number;\n  /**\n   * A space directory's JSON at the heads its document is stored at, for answering a passive subscription that\n   * holds nothing with the stored changes and that JSON, without loading the document.\n   */\n  readDirectorySnapshot?: (documentId: DocumentId) => Promise<{ heads: Heads; json: string } | undefined>;\n};\n\n/** A document a client subscribes to, with the heads it already holds and whether it holds it unloaded. */\nexport type SubscribedDocument = { documentId: DocumentId; heads?: Heads; passive?: boolean };\n\ninterface DocSyncState {\n  passive: boolean;\n  lastSentHead?: Heads;\n  confirm?: boolean;\n  /**\n   * Held only until the document is loaded for its initial send. Nothing pins the document after\n   * that: the host's residency policy decides, and each send re-leases it for the duration of a read.\n   */\n  initialLease?: DocumentLease<DatabaseDirectory>;\n}\n\n/**\n * Manages a connection and replication between worker's Automerge Repo and the client's Repo.\n */\nexport class DocumentsSynchronizer extends Resource {\n  private readonly _syncStates = new Map<DocumentId, DocSyncState>();\n  /**\n   * Documents that have pending updates.\n   * Used to batch updates.\n   */\n  private readonly _pendingUpdates = new Set<DocumentId>();\n\n  /** First sends read from storage rather than from a loaded document; see `readDirectorySnapshot`. */\n  readonly #storedSends = new Map<DocumentId, DataService.DocumentUpdate>();\n\n  /**\n   * Documents whose on-disk probe completed negative and that need a\n   * mutation-less `requesting: true` transition update sent to the client.\n   * Cleared per-flush in `_checkAndSendUpdates`.\n   */\n  private readonly _pendingRequesting = new Set<DocumentId>();\n\n  /**\n   * Job that schedules if there are pending updates.\n   */\n  private _sendUpdatesJob?: UpdateScheduler = undefined;\n\n  /**\n   * Test affordance: when true, `_checkAndSendUpdates` is a no-op so no\n   * document state is flushed to the client. `addDocuments` still loads\n   * documents on the worker side and accumulates `_pendingUpdates`, which\n   * flush automatically on resume. From the client's perspective every\n   * `RepoProxy.find()` made while paused returns a handle that stays\n   * `pending` until resume — used to deterministically reproduce\n   * worker-side hangs in query-pipeline tests.\n   */\n  #sendUpdatesPaused = false;\n\n  constructor(private readonly _params: DocumentsSynchronizerProps) {\n    super();\n  }\n\n  /**\n   * Test affordance: pause/resume flushing of document updates to the client.\n   * See `#sendUpdatesPaused` for details. Idempotent.\n   */\n  setSendUpdatesPaused(paused: boolean): void {\n    if (this.#sendUpdatesPaused === paused) {\n      return;\n    }\n    this.#sendUpdatesPaused = paused;\n    if (!paused) {\n      this._sendUpdatesJob?.trigger();\n    }\n  }\n\n  /**\n   * Subscribes the client to each document, from the heads it names so the first send is only what came\n   * after. A document already subscribed switches to the given mode, and is sent from the heads it names,\n   * or whole when it names none. A passive document is not loaded until storage moves past its heads.\n   */\n  async addDocuments(documents: readonly SubscribedDocument[]): Promise<void> {\n    const waiting: { documentId: DocumentId; heads: Heads; syncState: DocSyncState }[] = [];\n    for (const { documentId, heads, passive = false } of documents) {\n      if (this._lifecycleState === LifecycleState.CLOSED) {\n        continue;\n      }\n      const existing = this._syncStates.get(documentId);\n      if (existing) {\n        existing.passive = passive;\n        existing.lastSentHead = heads;\n        existing.confirm = heads !== undefined && !passive;\n        if (passive && heads !== undefined) {\n          waiting.push({ documentId, heads, syncState: existing });\n        } else {\n          this._pendingUpdates.add(documentId);\n          this._sendUpdatesJob?.trigger();\n        }\n        continue;\n      }\n      if (passive && heads !== undefined) {\n        const syncState: DocSyncState = { passive, lastSentHead: heads };\n        this._syncStates.set(documentId, syncState);\n        waiting.push({ documentId, heads, syncState });\n        continue;\n      }\n      if (passive && (await this.#sendFromStorage(documentId))) {\n        continue;\n      }\n      log('loading document', { documentId });\n      const lease = this._params.automergeHost.acquireDoc<DatabaseDirectory>(documentId);\n      const syncState: DocSyncState = {\n        passive,\n        initialLease: lease,\n        lastSentHead: heads,\n        confirm: heads !== undefined,\n      };\n      this._syncStates.set(documentId, syncState);\n      // Background disk probe so the client can distinguish\n      // \"not on disk, waiting for network\" from \"still loading\".\n      // Fire-and-forget; the result feeds `_pendingRequesting`.\n      this._scheduleDiskProbe(documentId);\n      void this._sendWhenLoaded(documentId, syncState);\n    }\n\n    if (waiting.length > 0) {\n      const stored = await this._params.automergeHost.getStoredHeads(waiting.map(({ documentId }) => documentId));\n      waiting.forEach(({ documentId, heads, syncState }, index) => {\n        const storedHeads = stored[index];\n        if (this._syncStates.get(documentId) === syncState && (!storedHeads || !sameHeads(storedHeads, heads))) {\n          this._pendingUpdates.add(documentId);\n          this._sendUpdatesJob?.trigger();\n        }\n      });\n    }\n  }\n\n  /**\n   * Queues the first send of a passive directory from its stored changes and snapshot, which the client shows it\n   * from; nothing loads the document until it changes. Later sends take the usual path.\n   */\n  async #sendFromStorage(documentId: DocumentId): Promise<boolean> {\n    const snapshot = await this._params.readDirectorySnapshot?.(documentId);\n    if (!snapshot) {\n      return false;\n    }\n    const bytes = await this._params.automergeHost.readStoredChanges(documentId, { limit: BACKED_DIRECTORY_LIMIT });\n    if (!bytes || this._lifecycleState === LifecycleState.CLOSED || this._syncStates.has(documentId)) {\n      return false;\n    }\n    // The stored changes may be ahead of the snapshot's heads, never behind; the next change sends what follows them.\n    const syncState: DocSyncState = { passive: true, lastSentHead: snapshot.heads };\n    this._syncStates.set(documentId, syncState);\n    this.#storedSends.set(documentId, {\n      documentId,\n      mutation: bytes,\n      passive: { heads: [...snapshot.heads], json: snapshot.json },\n    });\n    // The snapshot matched the stored heads when read, so heads that moved since mean a save the stored changes may\n    // lack, made before this sync state existed for the heads-changed handler to queue it.\n    const [storedHeads] = await this._params.automergeHost.getStoredHeads([documentId]);\n    if (this._syncStates.get(documentId) === syncState && (!storedHeads || !sameHeads(storedHeads, snapshot.heads))) {\n      this._pendingUpdates.add(documentId);\n    }\n    this._sendUpdatesJob?.trigger();\n    return true;\n  }\n\n  /** Queues the initial send once the document is loaded, then lets go of it. */\n  private async _sendWhenLoaded(documentId: DocumentId, syncState: DocSyncState): Promise<void> {\n    const lease = syncState.initialLease;\n    invariant(lease);\n    try {\n      if (!lease.loaded) {\n        await lease.waitUntilReady();\n      }\n    } catch (err) {\n      log.warn('failed to load document', { documentId, err });\n    } finally {\n      // Unsubscribed while loading: the state is gone and `removeDocuments` released the lease.\n      if (this._syncStates.get(documentId) === syncState && syncState.initialLease === lease) {\n        syncState.initialLease = undefined;\n        lease[Symbol.dispose]();\n        // Queued whether or not the load succeeded: a failed one is retried by the send loop, which\n        // gives up on a document this host does not store rather than retrying it forever.\n        this._pendingUpdates.add(documentId);\n        this._sendUpdatesJob?.trigger();\n      }\n    }\n  }\n\n  /**\n   * Probe local storage for the document; if not present, enqueue a\n   * `requesting: true` transition update so the client moves the handle\n   * from `'pending'` to `'requesting'` and disk-only callers can give up\n   * without waiting on the network. If the doc became `ready` before the\n   * probe completes (e.g. delivered concurrently by network/peer), no\n   * transition update is sent.\n   */\n  private _scheduleDiskProbe(documentId: DocumentId): void {\n    void Promise.resolve().then(async () => {\n      try {\n        const onDisk = await this._params.automergeHost.hasDocOnDisk(documentId);\n        if (onDisk) {\n          // Doc is on disk; the initial send follows once the load completes.\n          return;\n        }\n        // Skip the transition signal if the doc has since become `ready`\n        // via the network/peer race.\n        const syncState = this._syncStates.get(documentId);\n        if (!syncState || !syncState.initialLease || syncState.initialLease.loaded) {\n          return;\n        }\n        this._pendingRequesting.add(documentId);\n        this._sendUpdatesJob?.trigger();\n      } catch (err) {\n        log.warn('disk probe failed', { documentId, err });\n      }\n    });\n  }\n\n  holds(documentId: DocumentId): boolean {\n    return this._syncStates.has(documentId);\n  }\n\n  /** Drops the documents the client no longer subscribes to. */\n  removeDocuments(documentIds: DocumentId[]): void {\n    for (const documentId of documentIds) {\n      const syncState = this._syncStates.get(documentId);\n      syncState?.initialLease?.[Symbol.dispose]();\n      this._syncStates.delete(documentId);\n      this._pendingUpdates.delete(documentId);\n      this.#storedSends.delete(documentId);\n      this._pendingRequesting.delete(documentId);\n    }\n  }\n\n  protected override async _open(): Promise<void> {\n    this._sendUpdatesJob = new UpdateScheduler(this._ctx, this._checkAndSendUpdates.bind(this), {\n      maxFrequency: MAX_UPDATE_FREQ,\n    });\n    // Every save the host makes, whatever wrote it: this client's own mutation, another client's,\n    // or a peer's replicated change.\n    this._params.automergeHost.documentHeadsChanged.on(this._ctx, ({ documentId }) => {\n      if (!this._syncStates.has(documentId)) {\n        return;\n      }\n      this._pendingUpdates.add(documentId);\n      this._sendUpdatesJob?.trigger();\n    });\n  }\n\n  protected override async _close(): Promise<void> {\n    await this._sendUpdatesJob!.join();\n    for (const syncState of this._syncStates.values()) {\n      syncState.initialLease?.[Symbol.dispose]();\n    }\n    this._syncStates.clear();\n  }\n\n  async update(ctx: Context, updates: DataService.DocumentUpdate[]): Promise<void> {\n    for (const { documentId, mutation } of updates) {\n      // Inbound (client -> worker) updates are always mutation-bearing; the\n      // `mutation`-less variant is only used for worker -> client transition\n      // signals (e.g. `requesting`). Defensive skip here to satisfy the\n      // optional proto field.\n      if (!mutation) {\n        continue;\n      }\n      await this._writeMutation(ctx, documentId as DocumentId, mutation);\n    }\n    // TODO(mykola): This should not be required.\n    await this._params.automergeHost.flush(ctx, {\n      documentIds: updates.map(({ documentId }) => documentId as DocumentId),\n    });\n  }\n\n  private async _checkAndSendUpdates(): Promise<void> {\n    if (this.#sendUpdatesPaused) {\n      return;\n    }\n    const updates: DataService.DocumentUpdate[] = [];\n    const maxBytes = this._params.maxBatchBytes ?? MAX_BATCH_BYTES;\n    const maxDocuments = this._params.maxBatchDocuments ?? MAX_BATCH_DOCUMENTS;\n    let bytes = 0;\n    for (const [documentId, update] of this.#storedSends) {\n      updates.push(update);\n      bytes += (update.mutation?.byteLength ?? 0) + (update.passive?.json?.length ?? 0);\n      this.#storedSends.delete(documentId);\n    }\n\n    // Consumed one at a time so whatever does not fit stays pending for the next tick.\n    for (const documentId of this._pendingUpdates) {\n      if (updates.length >= maxDocuments || bytes >= maxBytes) {\n        break;\n      }\n      this._pendingUpdates.delete(documentId);\n      const update = await this._getPendingChanges(documentId);\n      if (update) {\n        updates.push(update);\n        bytes += (update.mutation?.byteLength ?? 0) + (update.passive?.json?.length ?? 0);\n      }\n    }\n    if (this._pendingUpdates.size > 0) {\n      this._sendUpdatesJob!.trigger();\n    }\n\n    // Mutation-less transition updates: tell the client `requesting: true`\n    // for any documents whose disk probe completed negative. Skip docs that\n    // are already being delivered as a real mutation in this same batch\n    // (those go directly to `ready` on the client and a subsequent\n    // `requesting` would be ignored anyway).\n    const docsRequesting = Array.from(this._pendingRequesting);\n    this._pendingRequesting.clear();\n    if (docsRequesting.length > 0) {\n      const docsBeingFlushed = new Set(updates.map((update) => update.documentId));\n      for (const documentId of docsRequesting) {\n        if (docsBeingFlushed.has(documentId)) {\n          continue;\n        }\n        updates.push({ documentId, requesting: true });\n      }\n    }\n\n    if (updates.length > 0) {\n      this._params.sendUpdates({ updates });\n    }\n  }\n\n  private async _getPendingChanges(documentId: DocumentId): Promise<DataService.DocumentUpdate | undefined> {\n    const syncState = this._syncStates.get(documentId);\n    // Still loading for its initial send, which queues the document again once it is ready.\n    if (!syncState || syncState.initialLease) {\n      return;\n    }\n    using lease = this._params.automergeHost.acquireDoc<DatabaseDirectory>(documentId);\n    if (!lease.loaded) {\n      // Gone from this host (e.g. wiped by garbage collection); its next save, if any, queues it again.\n      const [storedHeads] = await this._params.automergeHost.getHeads([documentId]);\n      if (storedHeads === undefined) {\n        return;\n      }\n      try {\n        await asyncTimeout(lease.waitUntilReady(), RELOAD_TIMEOUT);\n      } catch (err) {\n        log.warn('document could not be reloaded for an update, retrying', { documentId, err });\n        this._pendingUpdates.add(documentId);\n        this._sendUpdatesJob?.trigger();\n        return;\n      }\n    }\n    // Unsubscribed or closed while reloading.\n    if (this._syncStates.get(documentId) !== syncState) {\n      return;\n    }\n    const doc = lease.doc();\n    const since =\n      syncState.lastSentHead && A.hasHeads(doc, syncState.lastSentHead) ? syncState.lastSentHead : undefined;\n    const mutation = since ? A.saveSince(doc, since) : A.save(doc);\n    if (mutation.length === 0 && !syncState.confirm) {\n      return;\n    }\n    syncState.confirm = false;\n    syncState.lastSentHead = A.getHeads(doc);\n    countWork('automerge.mutationsSent');\n    countWork('automerge.mutationSentBytes', mutation.length);\n    return { documentId, mutation, passive: syncState.passive ? passiveObject(doc, since) : undefined };\n  }\n\n  private async _writeMutation(ctx: Context, documentId: DocumentId, mutation: Uint8Array): Promise<void> {\n    if (this._lifecycleState === LifecycleState.CLOSED) {\n      return;\n    }\n    log('write mutation', { documentId });\n    countWork('automerge.mutationsApplied');\n    countWork('automerge.mutationAppliedBytes', mutation.length);\n\n    const syncState = this._syncStates.get(documentId);\n    invariant(syncState, 'Sync state for document not found');\n    // Resident before the import, so the mutation merges into the document's stored history rather\n    // than into an empty document that would leave it parked as a change without its dependencies.\n    // A load that fails rejects the whole update, and the client re-sends the batch.\n    using lease = await this._params.automergeHost.loadDoc<DatabaseDirectory>(ctx, documentId, {\n      timeout: RELOAD_TIMEOUT,\n    });\n    invariant(lease, 'Document not found');\n    const headsBefore = A.getHeads(lease.doc());\n    const imported = this._params.automergeHost.createDoc(mutation, { documentId, preserveHistory: true });\n    // Read before awaiting: another client's write imported meanwhile is not something this client holds.\n    const headsAfter = A.getHeads(lease.doc());\n    using _imported = await imported;\n\n    if (A.equals(headsBefore, syncState.lastSentHead)) {\n      // No new mutations were discovered on network, so we do not need to send updates from worker to client.\n      syncState.lastSentHead = headsAfter;\n    }\n  }\n}\n\n/**\n * What a passive client shows the document from: its one object, or, on the first send only, the directory it reads\n * as. A later change to a directory is the client's cue to load it, so only the bytes follow.\n */\nconst passiveObject = (\n  doc: A.Doc<DatabaseDirectory>,\n  since: Heads | undefined,\n): DataService.DocumentUpdate['passive'] => {\n  const heads = A.getHeads(doc);\n  const [entry] = Object.entries(doc.objects ?? {});\n  return {\n    heads,\n    json: entry\n      ? backingJson(doc, entry[1], objectStructureToJson(entry[0] as EntityId, entry[1]))\n      : since === undefined\n        ? directoryJson(doc)\n        : undefined,\n    updatedAt: lastChangeTime(doc, heads),\n  };\n};\n\nconst lastChangeTime = (doc: A.Doc<unknown>, heads: A.Heads): number | undefined => {\n  const backend = A.getBackend(doc);\n  const time = Math.max(0, ...heads.map((hash) => backend.getChangeMetaByHash(hash)?.time ?? 0));\n  return time > 0 ? time * 1000 : undefined;\n};\n","//\n// Copyright 2021 DXOS.org\n//\n\nimport { type DocumentId } from '@automerge/automerge-repo';\nimport * as Effect from 'effect/Effect';\nimport * as EffectStream from 'effect/Stream';\n\nimport { UpdateScheduler } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport * as EffectEx from '@dxos/effect/EffectEx';\nimport { invariant } from '@dxos/invariant';\nimport { SpaceId } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { toServiceError } from '@dxos/protocols';\nimport { type DataService } from '@dxos/protocols/rpc';\n\nimport { type AutomergeHost, type DocumentLease, deriveCollectionIdFromSpaceId } from '../automerge/index.ts';\nimport { DocumentsSynchronizer, type DocumentsSynchronizerProps } from './documents-synchronizer.ts';\nimport { type IndexStatusTracker } from './index-status.ts';\nimport { type SpaceStateManager } from './space-state-manager.ts';\n\n/** Space sync-state recomputations per second; the scheduler still runs a trailing pass, so the last state lands. */\nconst SYNC_STATE_MAX_FREQ = 2;\n\nexport type DataServiceProps = {\n  automergeHost: AutomergeHost;\n  spaceStateManager: SpaceStateManager;\n  updateIndexes: (request: DataService.UpdateIndexesRequest) => Promise<void>;\n  getSpaceStats: (spaceId: SpaceId) => Promise<DataService.DatabaseStats>;\n  runGarbageCollection: (\n    spaceId: SpaceId,\n    options: DataService.RunGarbageCollectionRequest,\n  ) => Promise<DataService.GarbageCollectionReport>;\n  indexStatus: IndexStatusTracker;\n  /** See {@link DocumentsSynchronizerProps.readDirectorySnapshot}. */\n  readDirectorySnapshot?: DocumentsSynchronizerProps['readDirectorySnapshot'];\n};\n\n/**\n * Data sync between client and services.\n */\n// TODO(burdon): Move to client-services.\nexport class DataServiceImpl implements DataService.Handlers {\n  /**\n   * Map of subscriptions.\n   * subscriptionId -> DocumentsSynchronizer\n   */\n  private readonly '_subscriptions' = new Map<string, DocumentsSynchronizer>();\n\n  /**\n   * Leases on documents created for a client that has not subscribed to them yet. A created document\n   * lives only in memory until it is saved, and its creator subscribes in a later call, so releasing\n   * it at creation lets the host evict it out from under the write that follows.\n   */\n  private readonly '_pendingCreations' = new Map<DocumentId, DocumentLease>();\n\n  private readonly '_automergeHost': AutomergeHost;\n  private readonly '_spaceStateManager': SpaceStateManager;\n  private readonly '_indexStatus': IndexStatusTracker;\n  readonly #readDirectorySnapshot: DataServiceProps['readDirectorySnapshot'];\n  private readonly '_updateIndexes': (request: DataService.UpdateIndexesRequest) => Promise<void>;\n  private readonly '_getSpaceStats': (spaceId: SpaceId) => Promise<DataService.DatabaseStats>;\n  private readonly '_runGarbageCollection': (\n    spaceId: SpaceId,\n    options: DataService.RunGarbageCollectionRequest,\n  ) => Promise<DataService.GarbageCollectionReport>;\n\n  'constructor'(params: DataServiceProps) {\n    this._automergeHost = params.automergeHost;\n    this._spaceStateManager = params.spaceStateManager;\n    this._updateIndexes = params.updateIndexes;\n    this._getSpaceStats = params.getSpaceStats;\n    this._runGarbageCollection = params.runGarbageCollection;\n    this._indexStatus = params.indexStatus;\n    this.#readDirectorySnapshot = params.readDirectorySnapshot;\n  }\n\n  ['DataService.subscribe'](\n    request: DataService.SubscribeRequest,\n  ): EffectStream.Stream<DataService.BatchedDocumentUpdates, Error> {\n    return EffectEx.streamFromEmitter<DataService.BatchedDocumentUpdates, Error>((emit) => {\n      const synchronizer = new DocumentsSynchronizer({\n        automergeHost: this._automergeHost,\n        sendUpdates: (updates) => void emit.single(updates),\n        readDirectorySnapshot: this.#readDirectorySnapshot,\n      });\n      synchronizer\n        .open()\n        .then(() => {\n          this._subscriptions.set(request.subscriptionId, synchronizer);\n          // Ready beacon: an empty update batch signals that the subscription is registered, so the\n          // client can safely issue `updateSubscription` (see RepoProxy reconnect). A real update\n          // never carries an empty batch, so this is unambiguous and a no-op on the client.\n          void emit.single({ updates: [] });\n        })\n        .catch((err) => {\n          log.catch(err);\n          void emit.fail(err);\n        });\n      return Effect.sync(() => {\n        // Guarded by identity: a reconnect re-subscribes under the same id before this finalizer\n        // runs, and an unconditional delete would drop the replacement.\n        if (this._subscriptions.get(request.subscriptionId) === synchronizer) {\n          this._subscriptions.delete(request.subscriptionId);\n        }\n        // Nothing is left to subscribe to a created document once the last client is gone, so its\n        // creation lease would otherwise outlive every reader.\n        if (this._subscriptions.size === 0) {\n          for (const lease of this._pendingCreations.values()) {\n            lease[Symbol.dispose]();\n          }\n          this._pendingCreations.clear();\n        }\n        void synchronizer.close();\n      });\n    });\n  }\n\n  ['DataService.updateSubscription'](request: DataService.UpdateSubscriptionRequest): Effect.Effect<void, Error> {\n    return Effect.tryPromise({\n      try: async () => {\n        const synchronizer = this._subscriptions.get(request.subscriptionId);\n        invariant(synchronizer, 'Subscription not found');\n\n        if (request.add?.length) {\n          await synchronizer.addDocuments(\n            request.add.map(({ id, heads, passive }) => ({ documentId: id as DocumentId, heads, passive })),\n          );\n          // The subscription now holds each document, so the creation lease has nothing left to guard.\n          for (const { id } of request.add) {\n            const documentId = id as DocumentId;\n            this._pendingCreations.get(documentId)?.[Symbol.dispose]();\n            this._pendingCreations.delete(documentId);\n          }\n        }\n        if (request.removeIds?.length) {\n          await synchronizer.removeDocuments(request.removeIds as DocumentId[]);\n        }\n      },\n      catch: toServiceError,\n    });\n  }\n\n  ['DataService.createDocument'](\n    request: DataService.CreateDocumentRequest,\n  ): Effect.Effect<DataService.CreateDocumentResponse, Error> {\n    return Effect.tryPromise({\n      try: async () => {\n        if (request.initialValue && !request.initialDocument) {\n          log.warn('document created from deprecated `initialValue`; send `initialDocument` bytes', {\n            spaceId: request.spaceId,\n          });\n        }\n        const created = request.initialDocument\n          ? await this._automergeHost.createDoc(request.initialDocument, { preserveHistory: true })\n          : await this._automergeHost.createDoc(request.initialValue);\n        this._pendingCreations.set(created.documentId, created);\n        return { documentId: created.documentId };\n      },\n      catch: toServiceError,\n    });\n  }\n\n  ['DataService.update'](request: DataService.UpdateRequest): Effect.Effect<void, Error> {\n    return Effect.tryPromise({\n      try: async () => {\n        if (!request.updates) {\n          return;\n        }\n        const synchronizer = this._subscriptions.get(request.subscriptionId);\n        invariant(synchronizer, 'Subscription not found');\n\n        await synchronizer.update(Context.default(), request.updates);\n      },\n      catch: toServiceError,\n    });\n  }\n\n  ['DataService.flush'](request: DataService.FlushRequest): Effect.Effect<void, Error> {\n    return Effect.tryPromise({\n      try: async () => {\n        await this._automergeHost.flush(Context.default(), request);\n      },\n      catch: toServiceError,\n    });\n  }\n\n  ['DataService.getDocumentHeads'](\n    request: DataService.GetDocumentHeadsRequest,\n  ): Effect.Effect<DataService.GetDocumentHeadsResponse, Error> {\n    return Effect.tryPromise({\n      try: async () => {\n        const documentIds = request.documentIds;\n        if (!documentIds) {\n          return { heads: { entries: [] } };\n        }\n        const heads = await this._automergeHost.getHeads(documentIds as DocumentId[]);\n        return {\n          heads: {\n            entries: heads.map((heads, idx) => ({ documentId: documentIds[idx], heads })),\n          },\n        };\n      },\n      catch: toServiceError,\n    });\n  }\n\n  ['DataService.waitUntilHeadsReplicated'](\n    request: DataService.WaitUntilHeadsReplicatedRequest,\n  ): Effect.Effect<void, Error> {\n    return Effect.tryPromise({\n      try: async () => {\n        await this._automergeHost.waitUntilHeadsReplicated(Context.default(), request.heads);\n      },\n      catch: toServiceError,\n    });\n  }\n\n  ['DataService.reIndexHeads'](request: DataService.ReIndexHeadsRequest): Effect.Effect<void, Error> {\n    return Effect.tryPromise({\n      try: async () => {\n        await this._automergeHost.reIndexHeads((request.documentIds ?? []) as DocumentId[]);\n      },\n      catch: toServiceError,\n    });\n  }\n\n  ['DataService.updateIndexes'](request: DataService.UpdateIndexesRequest): Effect.Effect<void, Error> {\n    return Effect.tryPromise({\n      try: async () => {\n        await this._updateIndexes(request);\n      },\n      catch: toServiceError,\n    });\n  }\n\n  ['DataService.stats'](request: DataService.DatabaseStatsRequest): Effect.Effect<DataService.DatabaseStats, Error> {\n    return Effect.tryPromise({\n      try: async () => {\n        invariant(SpaceId.isValid(request.spaceId), 'Invalid space id');\n        return this._getSpaceStats(request.spaceId);\n      },\n      catch: toServiceError,\n    });\n  }\n\n  ['DataService.runGarbageCollection'](\n    request: DataService.RunGarbageCollectionRequest,\n  ): Effect.Effect<DataService.GarbageCollectionReport, Error> {\n    return Effect.tryPromise({\n      try: async () => {\n        invariant(SpaceId.isValid(request.spaceId), 'Invalid space id');\n        return this._runGarbageCollection(request.spaceId, request);\n      },\n      catch: toServiceError,\n    });\n  }\n\n  /** Whether any of the given subscriptions holds the document, passive or loaded. */\n  'holds'(subscriptionIds: readonly string[], documentId: DocumentId): boolean {\n    return subscriptionIds.some((subscriptionId) => this._subscriptions.get(subscriptionId)?.holds(documentId));\n  }\n\n  /**\n   * Test affordance: pause/resume flushing of document updates on every\n   * active subscription. See `DocumentsSynchronizer.setSendUpdatesPaused`.\n   */\n  'setAllSubscriptionsSendUpdatesPaused'(paused: boolean): void {\n    for (const synchronizer of this._subscriptions.values()) {\n      synchronizer.setSendUpdatesPaused(paused);\n    }\n  }\n\n  ['DataService.subscribeIndexStatus'](): EffectStream.Stream<DataService.IndexStatus, Error> {\n    return EffectEx.streamFromEmitter<DataService.IndexStatus, Error>((emit) => {\n      const ctx = Context.default();\n      this._indexStatus.updated.on(ctx, (status) => void emit.single(status));\n      void emit.single(this._indexStatus.current);\n      return Effect.promise(() => ctx.dispose());\n    });\n  }\n\n  ['DataService.subscribeIndexActivity'](): EffectStream.Stream<DataService.IndexActivity, Error> {\n    return EffectEx.streamFromEmitter<DataService.IndexActivity, Error>((emit) => {\n      const ctx = Context.default();\n      this._indexStatus.activityUpdated.on(ctx, (activity) => void emit.single(activity));\n      void emit.single(this._indexStatus.activity);\n      return Effect.promise(() => ctx.dispose());\n    });\n  }\n\n  ['DataService.subscribeSpaceSyncState'](\n    request: DataService.GetSpaceSyncStateRequest,\n  ): EffectStream.Stream<DataService.SpaceSyncState, Error> {\n    return EffectEx.streamFromEmitter<DataService.SpaceSyncState, Error>((emit) => {\n      const ctx = Context.default();\n      const spaceId = request.spaceId;\n      invariant(SpaceId.isValid(spaceId));\n\n      const rootDocumentId = this._spaceStateManager.getSpaceRootDocumentId(spaceId);\n      let collectionId = rootDocumentId && deriveCollectionIdFromSpaceId(spaceId, rootDocumentId);\n      this._spaceStateManager.spaceDocumentListUpdated.on(ctx, (event) => {\n        // Filter by spaceId — without this, an update for any other space rewrites our\n        // collectionId to `space:<our-spaceId>:<other-space-root>`, which never has any\n        // recorded peers and so the subscriber's sync-state stalls at peerCount: 0.\n        if (event.spaceId !== spaceId) {\n          return;\n        }\n        const newId = deriveCollectionIdFromSpaceId(spaceId, event.spaceRootId);\n        if (newId !== collectionId) {\n          collectionId = newId;\n          scheduler.trigger();\n        }\n      });\n\n      // Every local save fires `collectionStateUpdated`, and each run diffs every document against every\n      // peer, so an unthrottled stream re-diffs the whole space per keystroke for a status indicator.\n      const scheduler = new UpdateScheduler(\n        ctx,\n        async () => {\n          const state = collectionId ? await this._automergeHost.getCollectionSyncState(collectionId) : { peers: [] };\n\n          void emit.single({ peers: state.peers });\n        },\n        { maxFrequency: SYNC_STATE_MAX_FREQ },\n      );\n\n      this._automergeHost.collectionStateUpdated.on(ctx, (e) => {\n        if (e.collectionId === collectionId) {\n          scheduler.trigger();\n        }\n      });\n      scheduler.trigger();\n\n      return Effect.promise(() => ctx.dispose());\n    });\n  }\n}\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport { type ForeignKey } from '@dxos/echo-protocol';\nimport { type EntityId } from '@dxos/keys';\n\n/**\n * Storage-independent view of one entity participating in a merge.\n *\n * The merge core is defined over these rather than over live objects so that winner selection\n * and the merge function stay pure and testable without a database.\n */\nexport type MergeCandidate = {\n  readonly id: EntityId;\n\n  /** The declared convergence key; candidates in one merge group all share it. */\n  readonly convergenceKey?: string;\n\n  /** User-defined data. A property present with value `undefined` counts as undefined. */\n  readonly data: Readonly<Record<string, unknown>>;\n\n  /** Foreign keys, unioned across the group by {@link mergeCandidates}. */\n  readonly keys?: readonly ForeignKey[];\n};\n\nexport type MergeResult = {\n  /** The surviving entity. */\n  readonly winner: EntityId;\n\n  /** Entities to redirect at the winner and tombstone, ascending by id. */\n  readonly losers: readonly EntityId[];\n\n  /** Field-wise merged data, to be written to the winner as per-field writes. */\n  readonly data: Record<string, unknown>;\n\n  /** Union of every candidate's foreign keys, deduplicated and deterministically ordered. */\n  readonly keys: ForeignKey[];\n};\n\nconst compareForeignKeys = (a: ForeignKey, b: ForeignKey): number =>\n  a.source === b.source ? (a.id < b.id ? -1 : a.id > b.id ? 1 : 0) : a.source < b.source ? -1 : 1;\n\n/**\n * Merge a group of duplicates into a single deterministic result.\n *\n * The winner is the minimum id. Ids are ULIDs, so this is also the earliest-created entity —\n * and, being a pure function of the id set, it is agreed on by every peer that sees the same\n * set. Because it is a minimum, a peer seeing a superset picks an id no larger than a peer\n * seeing a subset, which is what makes redirect chains terminate (see `resolveMergeRedirect`\n * in `@dxos/echo/internal`).\n *\n * The result is a pure function of the candidate **set**: for each field, the value comes from\n * the smallest-id candidate that defines it. This is deliberately not a pairwise fold —\n * pairwise winner-preference is not associative, so different application orders would diverge\n * (for ids `Z < X < Y` where `Z` lacks field `a`, merging `X` then `Y` into `Z` yields a\n * different `a` than `Y` then `X`). Computing over the whole set at once is\n * permutation-independent by construction.\n *\n * Peers holding different candidate sets can still transiently compute different results. They\n * reconverge because losers are retained as redirects: a later pass follows a tombstoned loser's\n * chain to the live end and folds its remaining state there. That guarantees *agreement* — every\n * peer ends at the same winner with the same fields — but not that the final value of every field\n * equals what this function would return over the union: once an entity is tombstoned it never\n * re-enters the field-wise merge, so a fold can carry a field onto a winner that had defined it.\n * Likewise, folds run by different peers race as ordinary register writes on the winner —\n * resolved deterministically, so agreement still holds, but sequential straggler edits observed\n * by different folders can resolve to the earlier value.\n *\n * @throws If given no candidates.\n */\nexport const mergeCandidates = (candidates: readonly MergeCandidate[]): MergeResult => {\n  if (candidates.length === 0) {\n    throw new TypeError('Cannot merge an empty candidate set.');\n  }\n\n  // Deduplicate by id first: a caller may pass the same entity twice (query results are not unique\n  // until presentation), and without this the repeat becomes a loser pointing at itself, which\n  // would tombstone the winner.\n  const byId = new Map<EntityId, MergeCandidate>();\n  for (const candidate of candidates) {\n    if (!byId.has(candidate.id)) {\n      byId.set(candidate.id, candidate);\n    }\n  }\n\n  // Ascending by id, so the first candidate defining a field is the smallest-id one that does.\n  const ordered = [...byId.values()].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));\n  const [winner, ...losers] = ordered;\n\n  // Accumulate in a Map: on a plain object, `field in data` would see `Object.prototype`\n  // members (`toString`, `__proto__`, ...) as already present and silently drop those fields.\n  const data = new Map<string, unknown>();\n  for (const candidate of ordered) {\n    for (const [field, value] of Object.entries(candidate.data)) {\n      if (value !== undefined && !data.has(field)) {\n        data.set(field, value);\n      }\n    }\n  }\n\n  const keys: ForeignKey[] = [];\n  for (const candidate of ordered) {\n    for (const key of candidate.keys ?? []) {\n      if (!keys.some((existing) => existing.source === key.source && existing.id === key.id)) {\n        keys.push(key);\n      }\n    }\n  }\n  keys.sort(compareForeignKeys);\n\n  return { winner: winner.id, losers: losers.map(({ id }) => id), data: Object.fromEntries(data), keys };\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport { next as A } from '@automerge/automerge';\nimport { type DocumentId } from '@automerge/automerge-repo';\n\nimport { type Context } from '@dxos/context';\nimport {\n  type DatabaseDirectory,\n  EncodedReference,\n  type EntityStructure,\n  PROPERTY_ID,\n  isEncodedReference,\n} from '@dxos/echo-protocol';\nimport { resolveMergeRedirect } from '@dxos/echo/internal';\nimport { type EntityMeta, type Referrer } from '@dxos/index-core';\nimport { EID, type EntityId, type SpaceId } from '@dxos/keys';\nimport { log } from '@dxos/log';\n\nimport { mergeCandidates } from './merge-core.ts';\n\n/**\n * The document surface a merge needs — structurally satisfied by the host's `DocumentLease`\n * (whose disposal the merge honors) and by a bare `DocHandle` in tests.\n */\nexport type MergeDocumentRef = {\n  readonly documentId: DocumentId;\n  doc(): A.Doc<DatabaseDirectory>;\n  change(callback: A.ChangeFn<DatabaseDirectory>): void;\n  [Symbol.dispose]?: () => void;\n};\n\n/**\n * A referrer document is loaded on the index's say-so alone, so the rewrite path never waits on\n * the network: a document that is not locally available has no local references to rewrite, and a\n * best-effort optimization must not stall the indexing loop. The timeout is a backstop for the\n * local load itself.\n */\nconst REFERRER_LOAD_OPTIONS = { fetchFromNetwork: false, timeout: 10_000 };\n\nexport type ConvergenceKeyMergerDeps = {\n  loadDoc: (\n    ctx: Context,\n    documentId: DocumentId,\n    opts?: { timeout?: number; fetchFromNetwork?: boolean },\n  ) => Promise<MergeDocumentRef | null>;\n\n  /**\n   * Persist a document's pending changes durably. Winner and loser live in different documents\n   * with no cross-document write ordering, so the merge flushes the winner's folded data before\n   * writing any tombstone whose watermark claims that fold happened.\n   */\n  flushDoc: (ctx: Context, documentId: DocumentId) => Promise<void>;\n\n  /**\n   * Detection point lookup (`IndexEngine.queryByConvergenceKeys`), already bound to the host\n   * runtime. Promise-typed so tests can supply rows without a database.\n   */\n  queryByConvergenceKeys: (spaceId: SpaceId, convergenceKeys: readonly string[]) => Promise<readonly EntityMeta[]>;\n\n  /**\n   * Referrers of one entity (`IndexEngine.queryReferrers`) — the point lookup behind reference\n   * rewriting. Index rows are derived state; every hit is re-verified against the document before\n   * anything is written.\n   */\n  queryReferrers: (spaceId: SpaceId, targetId: EntityId) => Promise<readonly Referrer[]>;\n};\n\nexport type ConvergenceKeyMergeResult = {\n  /** Duplicate groups that required writes (a merge or a late-edit fold). */\n  mergedGroups: number;\n\n  /** Keys serviced to completion, per space — safe to clear from the durable intent log. */\n  serviced: Map<SpaceId, Set<string>>;\n};\n\n/**\n * Merges convergence-key duplicates surfaced by the indexing intent log — the worker-side trigger.\n *\n * The merge operates on the raw document structures via the storage-independent core in\n * `@dxos/echo/internal`; the writes replicate to clients like any other change, and the\n * `documentsSaved` event re-indexes the tombstones, which is what removes the losers from query\n * results everywhere.\n */\nexport class ConvergenceKeyMerger {\n  readonly #deps: ConvergenceKeyMergerDeps;\n\n  constructor(deps: ConvergenceKeyMergerDeps) {\n    this.#deps = deps;\n  }\n\n  /**\n   * Merge every duplicate group among the given pending keys.\n   *\n   * Runs after the index engine processes changed documents, which is the earliest a duplicate\n   * can exist on this device: duplicates are born from replication, and a replicated write is\n   * exactly what lands here. Detection is a point lookup on only the pending keys, so the cost\n   * is proportional to writes that carry one — nil for everything else — and no client, query,\n   * or full scan is involved.\n   *\n   * Already-redirected entities that re-index — a straggler peer's late edits replicating onto a\n   * tombstone, or a loser resurrected by `db.add` — are serviced too: their post-merge edits are\n   * folded into the winner and the tombstone is re-asserted, which is what makes `mergedInto`\n   * sticky and the convergence argument hold without any client-side pass.\n   *\n   * Failure containment: a key whose group throws is reported un-serviced (it stays in the intent\n   * log and the next pass retries it) without blocking the rest of the batch. A group member whose\n   * document cannot be loaded is merged around — the merge over the loadable subset is safe, and\n   * the missing document's eventual arrival is itself an indexed write that re-presents the key.\n   */\n  async mergeDuplicates(\n    ctx: Context,\n    convergenceKeys: ReadonlyMap<SpaceId, ReadonlySet<string>>,\n  ): Promise<ConvergenceKeyMergeResult> {\n    let mergedGroups = 0;\n    const serviced = new Map<SpaceId, Set<string>>();\n    for (const [spaceId, keys] of convergenceKeys) {\n      if (keys.size === 0) {\n        continue;\n      }\n\n      let rows;\n      try {\n        rows = await this.#deps.queryByConvergenceKeys(spaceId, [...keys]);\n      } catch (err) {\n        log.warn('convergence-key detection failed; keys stay pending', { spaceId, keys: keys.size, err });\n        continue;\n      }\n\n      const groups = new Map<string, { objectId: EntityId; documentId: string }[]>();\n      for (const row of rows) {\n        if (!row.convergenceKey || !row.documentId) {\n          continue;\n        }\n        const group = groups.get(row.convergenceKey) ?? [];\n        if (!group.some(({ objectId }) => objectId === row.objectId)) {\n          group.push({ objectId: row.objectId, documentId: row.documentId });\n        }\n        groups.set(row.convergenceKey, group);\n      }\n\n      const servicedKeys = new Set<string>();\n      serviced.set(spaceId, servicedKeys);\n      for (const convergenceKey of keys) {\n        const group = groups.get(convergenceKey);\n        if (group === undefined || group.length < 2) {\n          // A lone row, or rows that no longer carry the key — nothing to merge.\n          servicedKeys.add(convergenceKey);\n          continue;\n        }\n        try {\n          if (await this.mergeGroup(ctx, spaceId, convergenceKey, group)) {\n            mergedGroups++;\n          }\n          servicedKeys.add(convergenceKey);\n        } catch (err) {\n          log.warn('convergence-key merge group failed; will retry', { spaceId, convergenceKey, err });\n        }\n      }\n    }\n\n    if (mergedGroups > 0) {\n      log('merged convergence-key duplicates', { groups: mergedGroups });\n    }\n    return { mergedGroups, serviced };\n  }\n\n  /**\n   * Merge one convergence-key group: the live candidates fold into the minimum-id winner, and\n   * already-redirected members get their late edits folded and their tombstones re-asserted.\n   *\n   * Public as the unit under test — `mergeDuplicates` adds detection and failure containment\n   * around it.\n   */\n  async mergeGroup(\n    ctx: Context,\n    spaceId: SpaceId,\n    convergenceKey: string,\n    group: readonly { objectId: EntityId; documentId: string }[],\n  ): Promise<boolean> {\n    // Load phase: awaited doc loads, during which replicated changes are free to land — nothing\n    // has been read yet. The index row is derived state and can trail the truth, so everything is\n    // re-verified against the documents below.\n    const handles = new Map<EntityId, MergeDocumentRef>();\n    try {\n      for (const { objectId, documentId } of group) {\n        const handle = await this.#deps.loadDoc(ctx, documentId as DocumentId);\n        if (!handle) {\n          continue;\n        }\n        if (handles.has(objectId)) {\n          handle[Symbol.dispose]?.();\n          continue;\n        }\n        handles.set(objectId, handle);\n      }\n\n      // Classification reads current state, and `#mergeCandidates` computes the merge from these\n      // same reads synchronously — replicated changes apply through the event loop, so nothing can\n      // land between a read and the write derived from it. `#foldRedirected` re-reads on its own:\n      // by the time it runs, awaits inside `#mergeCandidates` may have let changes land — including\n      // the redirects the merge itself just wrote, which a fold must follow to their live end.\n      const candidates: GroupMember[] = [];\n      const redirectedIds: EntityId[] = [];\n      for (const [objectId, handle] of handles) {\n        const entity = _readEntity(handle, objectId, convergenceKey);\n        if (!entity) {\n          continue;\n        }\n        if (entity.system?.mergedInto !== undefined) {\n          redirectedIds.push(objectId);\n        } else if (!entity.system?.deleted) {\n          // A user-deleted entity without a redirect is neither: deletion is respected, not merged.\n          candidates.push({ objectId, handle, entity });\n        }\n      }\n\n      let changed = candidates.length >= 2 && (await this.#mergeCandidates(ctx, spaceId, convergenceKey, candidates));\n      for (const objectId of redirectedIds) {\n        changed = (await this.#foldRedirected(ctx, spaceId, objectId, handles, convergenceKey)) || changed;\n      }\n      return changed;\n    } finally {\n      // Leased documents must be returned or the host keeps them resident forever.\n      for (const handle of handles.values()) {\n        handle[Symbol.dispose]?.();\n      }\n    }\n  }\n\n  /**\n   * Merge live duplicates: fold every loser's state into the minimum-id winner, flush the winner\n   * durably, then redirect and tombstone the losers.\n   *\n   * The member reads, the merge computation, the losers' watermark heads, and the winner write all\n   * belong to one synchronous block, so the tombstones' `mergedAtHeads` cover exactly the state\n   * the merge folded — an edit landing later is above the watermark and reachable by a later fold.\n   * The only await is the durability flush between the winner write and the loser tombstones; the\n   * loser callbacks re-verify eligibility after it.\n   */\n  async #mergeCandidates(\n    ctx: Context,\n    spaceId: SpaceId,\n    convergenceKey: string,\n    candidates: readonly GroupMember[],\n  ): Promise<boolean> {\n    const result = mergeCandidates(\n      candidates.map(({ objectId, entity }) => ({\n        id: objectId,\n        convergenceKey,\n        data: (entity.data ?? {}) as Record<string, unknown>,\n        keys: entity.meta?.keys,\n      })),\n    );\n\n    const byId = new Map(candidates.map((member) => [member.objectId, member]));\n    const winner = byId.get(result.winner);\n    if (!winner) {\n      return false;\n    }\n\n    // Transitively closed: a loser that already absorbed others hands those on.\n    const absorbed = new Set<EntityId>(winner.entity.system?.mergedFrom ?? []);\n    for (const loserId of result.losers) {\n      absorbed.add(loserId);\n      for (const inherited of byId.get(loserId)?.entity.system?.mergedFrom ?? []) {\n        absorbed.add(inherited);\n      }\n    }\n\n    // Watermark heads, captured from the same doc states the merge was computed over.\n    const loserHeads = new Map<EntityId, string[]>();\n    for (const loserId of result.losers) {\n      const loser = byId.get(loserId);\n      if (loser) {\n        loserHeads.set(loserId, A.getHeads(loser.handle.doc()));\n      }\n    }\n\n    // The change callback runs in the same tick as the reads the merge was computed from, so the\n    // re-checks are a backstop against out-of-band mutation, not the concurrency mechanism.\n    let applied = false;\n    winner.handle.change((doc: DatabaseDirectory) => {\n      const entity = doc.objects?.[winner.objectId];\n      if (\n        !entity ||\n        entity.system?.mergedInto !== undefined ||\n        entity.system?.deleted ||\n        entity.meta?.convergenceKey !== convergenceKey\n      ) {\n        return;\n      }\n      // `x ??= y` evaluates to the plain right-hand value, not the proxy the document wraps it in,\n      // so every container is re-read through the entity after assignment — mutations on the alias\n      // of the right-hand value would go nowhere.\n      if (entity.data === undefined) {\n        entity.data = {};\n      }\n      for (const [field, value] of Object.entries(result.data)) {\n        // Per-field writes, and only where the value differs, so a concurrent edit to a field the\n        // merge never touched keeps its last-write-wins outcome.\n        if (!_jsonEqual(entity.data[field], value)) {\n          entity.data[field] = _clone(value);\n        }\n      }\n      // Stored meta can predate the `keys` array (the client backfills it on read); the raw document\n      // does not.\n      if (entity.meta.keys === undefined) {\n        entity.meta.keys = [];\n      }\n      const keys = entity.meta.keys;\n      for (const key of result.keys) {\n        if (!keys.some((existing) => existing.source === key.source && existing.id === key.id)) {\n          keys.push(_clone(key));\n        }\n      }\n      if (entity.system === undefined) {\n        entity.system = {};\n      }\n      // Append to the existing list rather than assigning a new one: concurrent assignments are\n      // whole-list conflicts and LWW would drop one peer's ids; concurrent inserts both survive,\n      // and reads deduplicate.\n      if (entity.system.mergedFrom === undefined) {\n        entity.system.mergedFrom = [];\n      }\n      const mergedFrom = entity.system.mergedFrom;\n      for (const id of [...absorbed].sort()) {\n        if (!mergedFrom.includes(id)) {\n          mergedFrom.push(id);\n        }\n      }\n      applied = true;\n    });\n    if (!applied) {\n      // Tombstoning the losers without having folded their state would strand it.\n      return false;\n    }\n\n    // Make the fold durable before any tombstone can be: a crash that persists a loser's\n    // watermark without the winner's folded data would strand the loser's state below a\n    // watermark nothing re-reads.\n    await this.#deps.flushDoc(ctx, winner.handle.documentId);\n\n    // The flush is an await — re-read the winner before tombstoning against it. A deletion that\n    // replicated in during it is respected: tombstoning the losers under a deleted winner would\n    // make every copy invisible. The losers stay live and a later pass re-merges them.\n    if (winner.handle.doc()?.objects?.[winner.objectId]?.system?.deleted) {\n      return true;\n    }\n\n    // Only losers whose redirect was actually written may have their referrers repointed: a loser\n    // whose callback declines (re-keyed, deleted, concurrently redirected) carries no redirect of\n    // ours, and rewriting refs to a live independent entity would sever them with no way back.\n    const redirected = new Map<EntityId, EntityId>();\n    for (const loserId of result.losers) {\n      const loser = byId.get(loserId);\n      const heads = loserHeads.get(loserId);\n      if (!loser || !heads) {\n        continue;\n      }\n      loser.handle.change((doc: DatabaseDirectory) => {\n        const entity = doc.objects?.[loserId];\n        // Changes that landed during the flush win: an existing redirect owns the watermark its\n        // fold depends on; a changed key means this is no longer the entity that was merged; a\n        // deletion is respected, not converted into a redirect.\n        if (\n          !entity ||\n          entity.system?.mergedInto !== undefined ||\n          entity.system?.deleted ||\n          entity.meta?.convergenceKey !== convergenceKey\n        ) {\n          return;\n        }\n        if (entity.system === undefined) {\n          entity.system = {};\n        }\n        entity.system.mergedInto = result.winner;\n        entity.system.mergedAtHeads = [...heads];\n        entity.system.deleted = true;\n        redirected.set(loserId, result.winner);\n      });\n    }\n\n    // The durability rule's dual: returning marks the key serviced and lets the orchestrator clear\n    // its durable intent, so the tombstones must be on disk first — an intent must never die before\n    // the tombstone it claims exists.\n    const flushedDocs = new Set([winner.handle.documentId]);\n    for (const loserId of result.losers) {\n      const loser = byId.get(loserId);\n      if (loser && !flushedDocs.has(loser.handle.documentId)) {\n        flushedDocs.add(loser.handle.documentId);\n        await this.#deps.flushDoc(ctx, loser.handle.documentId);\n      }\n    }\n\n    log('merged group', { convergenceKey, winner: result.winner, losers: result.losers });\n\n    // References to the losers repoint at the winner now that the tombstones exist. Outside the\n    // durability guarantee by design: resolution follows the redirect regardless, so this is an\n    // optimization plus the compat path for clients too old to follow `mergedInto`.\n    if (redirected.size > 0) {\n      const groupHandles = new Map([...byId].map(([objectId, member]) => [objectId, member.handle]));\n      await this.#rewriteReferences(ctx, spaceId, redirected, groupHandles);\n    }\n    return true;\n  }\n\n  /**\n   * Service an already-redirected entity: fold data edits made since its recorded watermark into\n   * the surviving entity, and re-assert the tombstone.\n   *\n   * This is what makes the redirect durable. A peer offline during the merge keeps editing its\n   * copy; those edits replicate onto the tombstone, re-index it, and land here — re-running the\n   * field-wise merge could not rescue them (it prefers the smallest-id candidate, the winner).\n   * And `db.add` un-deletes, so a restored loser would otherwise be a live duplicate that\n   * detection ignores forever; re-tombstoning makes `mergedInto` sticky, with the restore's edits\n   * carried to the winner by the same fold.\n   *\n   * Redirect resolution, the diff, the folded values, and the watermark all read the documents'\n   * current state in one synchronous block: the fold can never write a value older than the heads\n   * it advances the watermark to, and a redirect chain that collapsed earlier in this same pass is\n   * followed to its live end. The watermark advances only when the fold write actually applied —\n   * otherwise the edits stay above it for a later pass.\n   */\n  async #foldRedirected(\n    ctx: Context,\n    spaceId: SpaceId,\n    loserId: EntityId,\n    handles: ReadonlyMap<EntityId, MergeDocumentRef>,\n    convergenceKey: string,\n  ): Promise<boolean> {\n    const handle = handles.get(loserId);\n    const doc = handle?.doc();\n    const entity = doc?.objects?.[loserId];\n    const mergedInto = entity?.system?.mergedInto;\n    if (!handle || !doc || !entity || mergedInto === undefined || entity.meta?.convergenceKey !== convergenceKey) {\n      return false;\n    }\n    const mergedAtHeads = _watermarkUnion(entity);\n\n    const winnerId = resolveMergeRedirect(loserId, (id) => handles.get(id)?.doc()?.objects?.[id]?.system?.mergedInto);\n    const winnerHandle = winnerId !== loserId ? handles.get(winnerId) : undefined;\n    const winnerEntity = winnerHandle?.doc()?.objects?.[winnerId];\n    // The chain's end must be live to fold into. Deleted → the edits wait above the watermark\n    // until the winner is restored; still redirected (a non-decreasing edge stopped the walk) →\n    // corrupt data, leave it alone.\n    const winnerLive =\n      winnerEntity !== undefined && winnerEntity.system?.mergedInto === undefined && !winnerEntity.system?.deleted;\n\n    const currentHeads = A.getHeads(doc);\n    let changedFields: string[] = [];\n    if (mergedAtHeads !== undefined && winnerLive) {\n      const prefix = ['objects', loserId, 'data'];\n      const changed = new Set<string>();\n      for (const patch of A.diff(doc, mergedAtHeads, currentHeads)) {\n        if (patch.path.length > prefix.length && prefix.every((key, index) => patch.path[index] === key)) {\n          changed.add(String(patch.path[prefix.length]));\n        }\n      }\n      changedFields = [...changed].filter((field) => field !== PROPERTY_ID);\n    }\n\n    let applied = false;\n    if (changedFields.length > 0 && winnerHandle !== undefined) {\n      const loserData = (entity.data ?? {}) as Record<string, unknown>;\n      winnerHandle.change((target: DatabaseDirectory) => {\n        const targetEntity = target.objects?.[winnerId];\n        if (!targetEntity || targetEntity.system?.mergedInto !== undefined || targetEntity.system?.deleted) {\n          return;\n        }\n        if (targetEntity.data === undefined) {\n          targetEntity.data = {};\n        }\n        for (const field of changedFields) {\n          const value = loserData[field];\n          if (value === undefined) {\n            delete targetEntity.data[field];\n          } else if (!_jsonEqual(targetEntity.data[field], value)) {\n            targetEntity.data[field] = _clone(value);\n          }\n        }\n        applied = true;\n      });\n    }\n\n    if (applied && winnerHandle !== undefined) {\n      // Durability order, as in `#mergeCandidates`: a watermark must never outlive the fold it\n      // claims happened.\n      await this.#deps.flushDoc(ctx, winnerHandle.documentId);\n    }\n\n    const needsTombstone = entity.system?.deleted !== true;\n    if (applied || needsTombstone) {\n      handle.change((target: DatabaseDirectory) => {\n        const targetEntity = target.objects?.[loserId];\n        // A concurrent redirect elsewhere owns the watermark now; leave it to that merge's fold.\n        if (!targetEntity || targetEntity.system === undefined || targetEntity.system.mergedInto !== mergedInto) {\n          return;\n        }\n        if (applied) {\n          // Advance the watermark so the same edit is never folded twice.\n          targetEntity.system.mergedAtHeads = [...currentHeads];\n        }\n        targetEntity.system.deleted = true;\n      });\n      // The durability rule's dual, as in `#mergeCandidates`: the watermark advance and re-asserted\n      // tombstone must be on disk before the intent that claims this fold happened can be cleared.\n      await this.#deps.flushDoc(ctx, handle.documentId);\n      log('serviced redirected entity', {\n        loserId,\n        winnerId,\n        foldedFields: applied ? changedFields : [],\n        tombstoneReasserted: needsTombstone,\n      });\n    }\n\n    // Even a pass with nothing to fold re-covers referrers: a loser re-indexing is the only signal\n    // that re-presents the key, so this is where late referrers (§4.11's freshness residual) catch\n    // up. Idempotent — a rewritten referrer re-indexes with rows naming the winner, so the loser's\n    // steady-state lookup is empty and no documents are loaded.\n    if (winnerLive) {\n      await this.#rewriteReferences(ctx, spaceId, new Map([[loserId, winnerId]]), handles);\n    }\n    return applied || needsTombstone;\n  }\n\n  /**\n   * Repoint references at merged-away losers to their winners, index-driven: the reverse-reference\n   * index names each referrer and the property holding the ref, so every rewrite is a point load —\n   * no scan, no client, no hydration. A referrer holding refs to several losers is loaded and\n   * written once, covering all of them.\n   *\n   * Best-effort by design (see §4.11): a ref that stays behind still resolves through the redirect,\n   * and the loser's next re-index re-presents the work — so every failure surface here, the write\n   * included, is logged and swallowed, and no flush is ordered. A throw escaping this method would\n   * mark the key un-serviced and wedge the intent on permanent retry, which a non-load-bearing\n   * optimization must never do. The reference's own spelling (local or space-qualified) is\n   * preserved; the index restricts rows to same-space referrers with a document.\n   */\n  async #rewriteReferences(\n    ctx: Context,\n    spaceId: SpaceId,\n    redirects: ReadonlyMap<EntityId, EntityId>,\n    handles: ReadonlyMap<EntityId, MergeDocumentRef>,\n  ): Promise<void> {\n    // One batch entry per referrer object, accumulating the rewrites every loser asks of it.\n    type ReferrerBatch = {\n      referrer: Referrer;\n      rewrites: { loserId: EntityId; winnerId: EntityId; propPaths: Referrer['propPaths'] }[];\n    };\n    const batches = new Map<string, ReferrerBatch>();\n    for (const [loserId, winnerId] of redirects) {\n      let referrers: readonly Referrer[];\n      try {\n        referrers = await this.#deps.queryReferrers(spaceId, loserId);\n      } catch (err) {\n        log.warn('referrer lookup failed; references stay on the redirect', { spaceId, loserId, err });\n        continue;\n      }\n      for (const referrer of referrers) {\n        if (referrer.propPaths.length === 0) {\n          continue;\n        }\n        const key = `${referrer.documentId}/${referrer.objectId}`;\n        const batch = batches.get(key) ?? { referrer, rewrites: [] };\n        batch.rewrites.push({ loserId, winnerId, propPaths: referrer.propPaths });\n        batches.set(key, batch);\n      }\n    }\n\n    for (const { referrer, rewrites } of batches.values()) {\n      try {\n        // A group member (the winner included) is already loaded; reuse its lease rather than\n        // taking a second one — but only when the lease holds the document the index row names.\n        const shared = handles.get(referrer.objectId);\n        const reusable = shared !== undefined && shared.documentId === referrer.documentId;\n        const handle = reusable\n          ? shared\n          : ((await this.#deps.loadDoc(ctx, referrer.documentId as DocumentId, REFERRER_LOAD_OPTIONS)) ?? undefined);\n        if (!handle) {\n          continue;\n        }\n        try {\n          const rewritten: string[] = [];\n          handle.change((doc: DatabaseDirectory) => {\n            const entity = doc.objects?.[referrer.objectId];\n            // A merged-away referrer is left alone: a write would land above its own fold\n            // watermark and be carried into its winner as if it were a straggler's edit. A\n            // plain-deleted referrer is also left alone — if it is restored, the loser's next\n            // re-index re-covers it.\n            if (!entity || entity.system?.mergedInto !== undefined || entity.system?.deleted || !entity.data) {\n              return;\n            }\n            for (const { loserId, winnerId, propPaths } of rewrites) {\n              for (const path of propPaths) {\n                if (_rewriteReferenceAt(entity.data as Record<string, unknown>, path, loserId, winnerId)) {\n                  rewritten.push(path.join('.'));\n                }\n              }\n            }\n          });\n          if (rewritten.length > 0) {\n            log('rewrote references', { referrer: referrer.objectId, paths: rewritten });\n          }\n        } finally {\n          if (!reusable) {\n            handle[Symbol.dispose]?.();\n          }\n        }\n      } catch (err) {\n        log.warn('referrer rewrite failed; references stay on the redirect', { referrer: referrer.objectId, err });\n      }\n    }\n  }\n}\n\ntype GroupMember = {\n  objectId: EntityId;\n  handle: MergeDocumentRef;\n\n  /** Current entity state, read in the same synchronous block as the merge computed from it. */\n  entity: EntityStructure;\n};\n\n/**\n * Read an entity's current state, or `undefined` when it is not a merge subject for this key.\n *\n * Objects only: relations and types index as document entities too, but merging a relation would\n * tombstone it without reconciling its endpoints, and merging a type would break schema\n * resolution for its instances. The kind is read leniently — throwing here would wedge the\n * indexing loop on one corrupt entity.\n */\nconst _readEntity = (\n  handle: MergeDocumentRef,\n  objectId: EntityId,\n  convergenceKey: string,\n): EntityStructure | undefined => {\n  const entity = handle.doc()?.objects?.[objectId];\n  if (!entity || (entity.system?.kind ?? 'object') !== 'object' || entity.meta?.convergenceKey !== convergenceKey) {\n    return undefined;\n  }\n  return entity;\n};\n\n/**\n * The effective fold watermark: the stored `mergedAtHeads` unioned with every conflicting value\n * of that register.\n *\n * Peers merging the same group concurrently each record their own watermark; automerge keeps one\n * as the register value and the rest as conflicts. Diffing from the union means an edit *any*\n * peer already folded is never re-presented — a re-fold from a stale surviving watermark would\n * write the loser's old value over a newer edit made on the winner since.\n */\nconst _watermarkUnion = (entity: EntityStructure): string[] | undefined => {\n  const system = entity.system;\n  const stored = system?.mergedAtHeads;\n  if (system === undefined || stored === undefined) {\n    return undefined;\n  }\n  const hashes = new Set<string>();\n  const collect = (value: unknown): void => {\n    if (Array.isArray(value)) {\n      for (const hash of value) {\n        if (typeof hash === 'string') {\n          hashes.add(hash);\n        }\n      }\n    }\n  };\n  collect(stored);\n  for (const conflicting of Object.values(A.getConflicts(system, 'mergedAtHeads') ?? {})) {\n    collect(conflicting);\n  }\n  return [...hashes];\n};\n\n/**\n * Rewrite the reference at one indexed property path from `loserId` to `winnerId`, preserving the\n * reference's own spelling (a space-qualified ref stays qualified). Returns whether a write\n * happened. The index row can trail the document, so a path that no longer holds a ref to the\n * loser — moved, deleted, already rewritten — is a silent no-op.\n */\nconst _rewriteReferenceAt = (\n  data: Record<string, unknown>,\n  path: readonly string[],\n  loserId: EntityId,\n  winnerId: EntityId,\n): boolean => {\n  if (path.length === 0) {\n    return false;\n  }\n  let container: unknown = data;\n  for (const segment of path.slice(0, -1)) {\n    if (typeof container !== 'object' || container === null) {\n      return false;\n    }\n    container = (container as Record<string, unknown>)[segment];\n  }\n  if (typeof container !== 'object' || container === null) {\n    return false;\n  }\n  const leafKey = path[path.length - 1];\n  const value = (container as Record<string, unknown>)[leafKey];\n  if (!isEncodedReference(value)) {\n    return false;\n  }\n  const uri = EID.tryParse(EncodedReference.toURI(value));\n  if (uri === undefined || EID.getEntityId(uri) !== loserId) {\n    return false;\n  }\n  (container as Record<string, unknown>)[leafKey] = EncodedReference.fromURI(\n    EID.make({ spaceId: EID.getSpaceId(uri), entityId: winnerId }),\n  );\n  return true;\n};\n\n/**\n * Deep-copies a value read from one automerge document so it can be inserted into another —\n * materialized automerge values may be proxied, and a document must not hold another's nodes.\n */\nconst _clone = <T>(value: T): T => {\n  if (value === null || typeof value !== 'object') {\n    return value;\n  }\n  if (value instanceof Uint8Array) {\n    return new Uint8Array(value) as T;\n  }\n  // Long strings are stored as unmergeable raw strings; the generic branch would flatten one\n  // into a `{ val }` map — silent corruption of the field.\n  if (value instanceof A.RawString) {\n    return new A.RawString(value.val) as T;\n  }\n  if (Array.isArray(value)) {\n    return value.map(_clone) as T;\n  }\n  return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, _clone(entry)])) as T;\n};\n\n/**\n * Structural equality good enough for the write-only-if-different guard: a false negative costs\n * one redundant (idempotent) write, never a wrong value.\n */\nconst _jsonEqual = (a: unknown, b: unknown): boolean => {\n  if (a === b) {\n    return true;\n  }\n  try {\n    return JSON.stringify(a) === JSON.stringify(b);\n  } catch {\n    return false;\n  }\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport { EncodedReference, type EntityStructure } from '@dxos/echo-protocol';\nimport { EID, type EntityId, type SpaceId } from '@dxos/keys';\n\n/**\n * Depth bound for the transitive walk. Mirrors `ObjectCore.isDeleted`, which caps the same\n * traversal — the two must agree, or an object queries as deleted yet survives collection.\n */\nconst MAX_DELETION_DEPTH = 10;\n\n/**\n * Resolves whether entities are deleted, including the transitive rule.\n *\n * Deletion cascades are computed at read time, never written: a child of a deleted parent, and a\n * relation with a deleted endpoint, carry no `deleted` flag of their own yet query as deleted\n * (`ObjectCore.isDeleted`). Garbage collection has to apply the same rule, or those entities are\n * invisible to every query while their documents are retained forever.\n *\n * Memoized per (entity, remaining depth) across the pass: the walk revisits shared parents\n * constantly.\n */\nexport class DeletionResolver {\n  readonly #structures = new Map<EntityId, EntityStructure>();\n  readonly #memo = new Map<string, boolean>();\n  readonly #spaceId: SpaceId;\n\n  constructor(spaceId: SpaceId) {\n    this.#spaceId = spaceId;\n  }\n\n  /** Registers the entities of one document so the walk can resolve references into it. */\n  add(objects: Record<string, EntityStructure> | undefined): void {\n    for (const [objectId, structure] of Object.entries(objects ?? {})) {\n      this.#structures.set(objectId as EntityId, structure);\n    }\n    this.#memo.clear();\n  }\n\n  has(objectId: string): boolean {\n    return this.#structures.has(objectId as EntityId);\n  }\n\n  isDeleted(objectId: string): boolean {\n    return this.#isDeleted(objectId as EntityId, MAX_DELETION_DEPTH);\n  }\n\n  #isDeleted(objectId: EntityId, remainingDepth: number): boolean {\n    // Keyed by the remaining budget as well as the id: a `false` that came from exhausting the\n    // budget is not the answer a deeper budget gives, so sharing it across budgets would make the\n    // verdict depend on visit order. The budget also bounds the recursion, so cycles terminate.\n    const key = `${objectId}:${remainingDepth}`;\n    const cached = this.#memo.get(key);\n    if (cached !== undefined) {\n      return cached;\n    }\n\n    const structure = this.#structures.get(objectId);\n    if (!structure) {\n      return false;\n    }\n\n    let deleted = structure.system?.deleted ?? false;\n    if (!deleted && remainingDepth > 0) {\n      const dependencies = [structure.system?.parent];\n      if (structure.system?.kind === 'relation') {\n        dependencies.push(structure.system?.source, structure.system?.target);\n      }\n      deleted = dependencies.some((reference) => {\n        const dependencyId = reference && this.#resolveLocal(reference);\n        return dependencyId ? this.#isDeleted(dependencyId, remainingDepth - 1) : false;\n      });\n    }\n\n    this.#memo.set(key, deleted);\n    return deleted;\n  }\n\n  /** References leaving this space, or resolving to nothing, count as not deleted. */\n  #resolveLocal(reference: EncodedReference): EntityId | undefined {\n    const uri = EncodedReference.toURI(reference);\n    if (!EID.isEID(uri)) {\n      return undefined;\n    }\n    const referencedSpaceId = EID.getSpaceId(uri);\n    if (referencedSpaceId !== undefined && referencedSpaceId !== this.#spaceId) {\n      return undefined;\n    }\n    return EID.getEntityId(uri);\n  }\n}\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport type * as SqlClient from 'effect/sql/SqlClient';\n\nimport { type Context } from '@dxos/context';\nimport { EchoFeedCodec } from '@dxos/echo-protocol';\nimport { type ObjectJSON } from '@dxos/echo/internal';\nimport * as RuntimeProvider from '@dxos/effect/RuntimeProvider';\nimport { type FeedOptions, type FeedStore } from '@dxos/feed';\nimport { type DataSourceCursor, type IndexDataSource, type IndexerObject } from '@dxos/index-core';\nimport { failedInvariant } from '@dxos/invariant';\nimport type { SpaceId } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { FeedProtocol } from '@dxos/protocols';\n\nexport type FeedDataSourceOptions = {\n  feedStore: FeedStore;\n  runtime: RuntimeProvider.RuntimeProvider<SqlClient.SqlClient>;\n  /**\n   * Callback to get the list of space IDs that should be indexed.\n   */\n  getSpaceIds: () => SpaceId[];\n\n  /**\n   * Feed namespaces to index.\n   * @default [WellKnownNamespaces.data, WellKnownNamespaces.trace]\n   */\n  feedNamespaces?: string[];\n};\n\n/** Prefix of a backfill cursor's resource id, `backfill/<namespace>/<feedId>`. */\nconst BACKFILL_PREFIX = 'backfill/';\n\n/** The value a backfill cursor takes once it has read its feed to the end; the host then deletes it. */\nexport const BACKFILL_FINISHED = 'done';\n\n/**\n * Resource id of the cursor that backfills one feed, read by {@link FeedDataSource} beside the\n * namespace cursors; a host seeds it (`IndexEngine.seedCursor`) when a feed's indexing is re-enabled.\n */\nexport const backfillResourceId = (feedNamespace: string, feedId: string): string =>\n  `${BACKFILL_PREFIX}${feedNamespace}/${feedId}`;\n\nconst parseBackfillResourceId = (resourceId: string): { feedNamespace: string; feedId: string } | undefined => {\n  if (!resourceId.startsWith(BACKFILL_PREFIX)) {\n    return undefined;\n  }\n  const rest = resourceId.slice(BACKFILL_PREFIX.length);\n  const separator = rest.indexOf('/');\n  return separator > 0 ? { feedNamespace: rest.slice(0, separator), feedId: rest.slice(separator + 1) } : undefined;\n};\n\nconst isIndexingDisabled = (options: FeedOptions | undefined): boolean => options?.indexing?.enabled === false;\n\n/** Whether the feed's index holds every branch; absent, it holds only the main branch. */\nexport const indexesAllBranches = (options: FeedOptions | undefined): boolean => options?.indexing?.mode === 'all';\n\n/** What one pass read beyond the objects it returned, for the host to act on once the pass ends. */\nexport type FeedPassReport = {\n  /** Spaces whose feeds returned blocks, indexed or skipped; retention may have more to trim there. */\n  spaces: Set<SpaceId>;\n  /**\n   * Feeds whose blocks were skipped because indexing is disabled or the block is on a branch the index\n   * does not hold, keyed by space; their readers still need invalidating.\n   */\n  skippedFeeds: Map<SpaceId, Set<string>>;\n  /** Backfill cursors that reached {@link BACKFILL_FINISHED}, for the host to delete. */\n  finishedBackfills: Map<SpaceId, Set<string>>;\n};\n\nconst makeEmptyReport = (): FeedPassReport => ({\n  spaces: new Set(),\n  skippedFeeds: new Map(),\n  finishedBackfills: new Map(),\n});\n\nconst addTo = (map: Map<SpaceId, Set<string>>, spaceId: SpaceId, value: string) => {\n  const values = map.get(spaceId) ?? new Set();\n  values.add(value);\n  map.set(spaceId, values);\n};\n\nexport class FeedDataSource implements IndexDataSource {\n  // TODO(queue-to-feed-migration): retains \"queue\" naming — persisted as a column value in the\n  // local `indexCursor`/`objectMeta` SQLite tables (see index-tracker.ts, indexes/entity-meta-index.ts);\n  // renaming it requires a local index-store migration.\n  readonly sourceName = 'queue';\n\n  /**\n   * Feed namespaces to index.\n   */\n  private readonly _feedNamespaces: string[];\n  private readonly _feedStore: FeedStore;\n  private readonly _runtime: RuntimeProvider.RuntimeProvider<SqlClient.SqlClient>;\n  private readonly _getSpaceIds: () => SpaceId[];\n\n  /**\n   * Reads made during the current pass, keyed by their request. The snapshot and reverse-ref legs of\n   * one pass usually hold the same cursors, and a trace block can be over 100 KB, so the second leg\n   * reuses the first leg's read instead of fetching the same blocks again.\n   */\n  #passReads: Map<string, FeedProtocol.QueryResponse> | undefined;\n\n  /** Feeds already reported as re-read: an empty feed's cursor is never rewritten, so every pass meets it again. */\n  readonly #restartedFeeds = new Set<string>();\n\n  /** Each space's stored feed options, read once per pass. */\n  #passOptions: Map<SpaceId, Map<string, FeedOptions>> | undefined;\n\n  #report: FeedPassReport = makeEmptyReport();\n\n  constructor(options: FeedDataSourceOptions) {\n    this._feedStore = options.feedStore;\n    this._runtime = options.runtime;\n    this._getSpaceIds = options.getSpaceIds;\n    this._feedNamespaces = options.feedNamespaces ?? [\n      FeedProtocol.WellKnownNamespaces.data,\n      FeedProtocol.WellKnownNamespaces.trace,\n    ];\n  }\n\n  beginPass(): void {\n    this.#passReads = new Map();\n    this.#passOptions = new Map();\n  }\n\n  endPass(): void {\n    this.#passReads = undefined;\n    this.#passOptions = undefined;\n  }\n\n  /** What the passes since the last call read beyond their objects; resets the report. */\n  takeReport(): FeedPassReport {\n    const report = this.#report;\n    this.#report = makeEmptyReport();\n    return report;\n  }\n\n  #feedOptions(spaceId: SpaceId): Effect.Effect<Map<string, FeedOptions>, never, SqlClient.SqlClient> {\n    return Effect.gen({ self: this }, function* () {\n      const cached = this.#passOptions?.get(spaceId);\n      if (cached) {\n        return cached;\n      }\n      const options = yield* this._feedStore.listFeedOptions(spaceId).pipe(\n        Effect.catch((error) => {\n          // Indexing a disabled feed is recoverable (the rows go when its options next apply); failing every pass is not.\n          log.warn('feed options could not be read, indexing every feed', { spaceId, error });\n          return Effect.succeed(new Map<string, FeedOptions>());\n        }),\n      );\n      this.#passOptions?.set(spaceId, options);\n      return options;\n    });\n  }\n\n  getChangedObjects(\n    _ctx: Context,\n    cursors: DataSourceCursor[],\n    opts?: { limit?: number; objects?: boolean },\n  ): Effect.Effect<{ objects: IndexerObject[]; cursors: DataSourceCursor[]; more: boolean }> {\n    // Feed blocks carry no document activity, so an activity-only read would fetch every new block\n    // just to discard it; returning no cursors also spares the activity leg its cursor write.\n    if (opts?.objects === false) {\n      return Effect.succeed({ objects: [], cursors: [], more: false });\n    }\n\n    // For queue, the cursor is assumed to have:\n    // spaceId = set\n    // resourceId = null\n    // cursor = feed cursor\n\n    // We also add new cursors from all previously unindexed spaces.\n\n    return Effect.gen({ self: this }, function* () {\n      const objects: IndexerObject[] = [];\n      const updatedCursors: DataSourceCursor[] = [];\n\n      // Delete old cursors that did not have feed namespace set. Backfills go first, so a block a\n      // namespace cursor reads in the same batch is written after an older one of the same object.\n      const isBackfill = (cursor: DataSourceCursor) =>\n        cursor.resourceId !== null && parseBackfillResourceId(cursor.resourceId) !== undefined;\n      let augmentedCursors = [\n        ...cursors.filter((c) => c.resourceId !== null && isBackfill(c)),\n        ...cursors.filter((c) => c.resourceId !== null && !isBackfill(c)),\n      ];\n      // Only its backfill reads a feed being backfilled, or the backfill's older blocks would overwrite newer ones.\n      const backfilling = new Set(\n        augmentedCursors.flatMap((cursor) => {\n          const backfill = cursor.resourceId !== null ? parseBackfillResourceId(cursor.resourceId) : undefined;\n          return backfill && cursor.cursor !== BACKFILL_FINISHED ? [`${cursor.spaceId}|${backfill.feedId}`] : [];\n        }),\n      );\n      for (const spaceId of this._getSpaceIds()) {\n        for (const feedNamespace of this._feedNamespaces) {\n          if (!augmentedCursors.some((c) => c.spaceId === spaceId && c.resourceId === feedNamespace)) {\n            // Add a new cursor for this space starting from the beginning.\n            // Empty string cursor means \"start from beginning\".\n            augmentedCursors.push({\n              spaceId,\n              resourceId: feedNamespace,\n              cursor: '',\n            });\n          }\n        }\n      }\n\n      // Limit per call, but we might have multiple spaces.\n      // We should distribute limit or just fill up to limit.\n      let remainingLimit = opts?.limit ?? Infinity;\n\n      for (const cursor of augmentedCursors) {\n        if (remainingLimit <= 0) {\n          // Remaining cursors are not processed in this call.\n          updatedCursors.push(cursor);\n          continue;\n        }\n        if (!cursor.spaceId) {\n          // Ignore cursors without spaceId.\n          updatedCursors.push(cursor);\n          continue;\n        }\n        const backfill = cursor.resourceId !== null ? parseBackfillResourceId(cursor.resourceId) : undefined;\n        const feedNamespace = backfill?.feedNamespace ?? cursor.resourceId;\n        if (backfill && cursor.cursor === BACKFILL_FINISHED) {\n          addTo(this.#report.finishedBackfills, cursor.spaceId, cursor.resourceId ?? failedInvariant());\n          updatedCursors.push(cursor);\n          continue;\n        }\n        if (\n          FeedProtocol.WellKnownNamespaces.data !== feedNamespace &&\n          FeedProtocol.WellKnownNamespaces.trace !== feedNamespace\n        ) {\n          // TODO(dmaretskyi): Update/remove this check when adding new feed namespaces.\n          log.warn('Ignoring cursor with invaliding feed namespace', { namespace: cursor.resourceId });\n          // Ignore cursors with unknown resourceId.\n          updatedCursors.push(cursor);\n          continue;\n        }\n\n        const storedCursor =\n          typeof cursor.cursor === 'string' && cursor.cursor !== ''\n            ? FeedProtocol.FeedCursor.make(cursor.cursor)\n            : undefined;\n        // The store fails a read from a cursor it did not issue, which would fail every pass; the index is\n        // derived, so reading the feed again from the start is safe.\n        const storedIsCurrent =\n          storedCursor !== undefined && (yield* this._feedStore.isCursorCurrent(cursor.spaceId, storedCursor));\n        const feedKey = `${cursor.spaceId}|${cursor.resourceId}`;\n        const spaceId = cursor.spaceId;\n        const feedOptions = yield* this.#feedOptions(spaceId);\n        if (storedCursor && !storedIsCurrent && !this.#restartedFeeds.has(feedKey)) {\n          this.#restartedFeeds.add(feedKey);\n          log.warn('feed index cursor was issued by another store, reading the feed again', {\n            spaceId: cursor.spaceId,\n            feedNamespace: cursor.resourceId,\n          });\n        }\n        const currentCursor =\n          storedCursor && storedIsCurrent\n            ? storedCursor\n            : FeedProtocol.encodeFeedCursor(\n                yield* this._feedStore.getServerToken(cursor.spaceId),\n                FeedProtocol.FEED_START,\n              );\n\n        try {\n          const readKey = JSON.stringify([cursor.spaceId, cursor.resourceId, currentCursor, remainingLimit]);\n          const result =\n            this.#passReads?.get(readKey) ??\n            (yield* this._feedStore.query({\n              spaceId,\n              feedNamespace: feedNamespace ?? failedInvariant(),\n              ...(backfill ? { query: { feedIds: [backfill.feedId] } } : {}),\n              cursor: currentCursor,\n              limit: remainingLimit,\n            }));\n          this.#passReads?.set(readKey, result);\n          if (result.blocks.length > 0) {\n            this.#report.spaces.add(spaceId);\n          }\n\n          // A backfill that read nothing is done; one whose feed was disabled again stops, its rows already removed.\n          if (backfill && (result.blocks.length === 0 || isIndexingDisabled(feedOptions.get(backfill.feedId)))) {\n            addTo(this.#report.finishedBackfills, spaceId, cursor.resourceId ?? failedInvariant());\n            updatedCursors.push({ spaceId, resourceId: cursor.resourceId, cursor: BACKFILL_FINISHED });\n            continue;\n          }\n\n          // Process blocks\n          for (const block of result.blocks) {\n            const feedId = block.feedId ?? failedInvariant();\n            if (isIndexingDisabled(feedOptions.get(feedId))) {\n              addTo(this.#report.skippedFeeds, spaceId, feedId);\n              continue;\n            }\n            if (!backfill && backfilling.has(`${spaceId}|${feedId}`)) {\n              continue;\n            }\n            try {\n              // Stamp the block's id and position (mirrors the local feed-service read path); the index\n              // snapshot persists them, which is how a reader recognises a block it already applied.\n              const data = EchoFeedCodec.decodeBlock(block) as ObjectJSON;\n              if (EchoFeedCodec.branchOf(data) !== undefined && !indexesAllBranches(feedOptions.get(feedId))) {\n                addTo(this.#report.skippedFeeds, spaceId, feedId);\n                continue;\n              }\n\n              objects.push({\n                spaceId,\n                queueId: feedId,\n                queueNamespace: feedNamespace,\n                documentId: null,\n                recordId: null,\n                queuePosition: block.position ?? null,\n                queueInsertionId: block.insertionId ?? null,\n                data,\n                createdAt: null,\n                updatedAt: block.timestamp,\n              });\n            } catch (err) {\n              log.warn('Failed to parse block data for indexing', { spaceId: cursor.spaceId, err });\n            }\n          }\n\n          remainingLimit -= result.blocks.length;\n          updatedCursors.push({\n            spaceId: cursor.spaceId,\n            resourceId: cursor.resourceId,\n            cursor: result.nextCursor,\n          });\n        } catch (error) {\n          log.error('Error querying queue for indexing', { spaceId: cursor.spaceId, error });\n        }\n      }\n\n      // A spent limit may have stopped mid-feed or skipped feeds; the store cannot say which, so the\n      // next pass finds out, and reads empty if there was nothing left.\n      return { objects, cursors: updatedCursors, more: remainingLimit <= 0 };\n    }).pipe(RuntimeProvider.provide(this._runtime), Effect.withSpan('FeedDataSource.getChangedObjects'), Effect.orDie);\n  }\n}\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport { DeferredTask, type ReadOnlyEvent, scheduleTask } from '@dxos/async';\nimport { type Context, Resource } from '@dxos/context';\nimport { BaseError } from '@dxos/errors';\nimport { log } from '@dxos/log';\nimport { FeedProtocol } from '@dxos/protocols';\n\n/**\n * Longest a trace append waits for the background pass that indexes it. An agent turn appends trace\n * messages continuously, and starting a pass per append kept the worker saturated for the whole turn;\n * a reader that needs them sooner (a feed-scoped query, `flush`) drives the pass itself.\n */\nexport const TRACE_INDEX_DELAY_MS = 1_000;\n\n/** Wait before retrying after a failed pass, doubled on each further failure up to {@link INDEX_RETRY_MAX_DELAY_MS}. */\nexport const INDEX_RETRY_DELAY_MS = 1_000;\n\nexport const INDEX_RETRY_MAX_DELAY_MS = 60_000;\n\n/** A pass failed before the changes a caller waited for were indexed; the cause is the pass's error. */\nexport class IndexPassFailedError extends BaseError.extend('IndexPassFailedError', 'Index pass failed.') {}\n\n/**\n * Every path that can start an indexing run. Logged on each run so an idle-churn loop is\n * attributable from `app.log` alone — the counts are otherwise indistinguishable between a\n * data-driven pass and a self-sustaining invalidation cycle.\n */\nexport type IndexRunReason =\n  | 'open'\n  | 'feed-blocks'\n  | 'trace-blocks'\n  | 'documents-saved'\n  | 'batch-continuation'\n  | 'retry'\n  | 'rpc-update-indexes'\n  | 'feed-scoped-query'\n  | 'epoch';\n\n/** Requests that drive the indexer directly, as opposed to the events that schedule it. */\nexport type IndexRequestReason = Extract<IndexRunReason, 'rpc-update-indexes' | 'feed-scoped-query' | 'epoch'>;\n\n/** What the scheduler needs to know about a finished pass; `undefined` means the host is closing. */\nexport type IndexPassResult = {\n  /** The pass found nothing more to index. */\n  done: boolean;\n  /** Every input that existed when the pass started is indexed. */\n  drained: boolean;\n};\n\nexport type IndexSchedulerProps = {\n  /** `FeedStore.onNewBlocks`. */\n  feedBlocks: ReadOnlyEvent<{ spaceId: string; feedNamespace?: string }>;\n  /** `AutomergeHost.documentsSaved`. */\n  documentsSaved: ReadOnlyEvent;\n  /** Runs one pass over every data source, given the reasons that accumulated since the last one. */\n  runPass: (ctx: Context, reasons: Record<string, number>) => Promise<IndexPassResult | undefined>;\n};\n\n/**\n * Decides when the index runs: subscribes to the writes that need indexing, coalesces them into\n * passes, and lets callers wait for the inputs that existed when they asked.\n */\nexport class IndexScheduler extends Resource {\n  readonly #feedBlocks: IndexSchedulerProps['feedBlocks'];\n  readonly #documentsSaved: IndexSchedulerProps['documentsSaved'];\n  readonly #runPass: IndexSchedulerProps['runPass'];\n\n  #task: DeferredTask | undefined;\n\n  /**\n   * Why the pending run was scheduled, counted per reason. `DeferredTask` coalesces overlapping\n   * `schedule()` calls into one run, so attributing a run needs the full multiset of reasons that\n   * accumulated before it started — a single \"last caller\" field would misattribute every coalesced run.\n   */\n  readonly #pendingReasons = new Map<IndexRunReason, number>();\n\n  /**\n   * Bumped by every change that needs indexing (not by a pass continuing its own backlog), so a\n   * caller can wait for the inputs that existed when it asked rather than for the index to go idle.\n   */\n  #inputGeneration = 0;\n\n  /** The newest input generation a drained pass has fully indexed. */\n  #indexedGeneration = 0;\n\n  /** Whether the last pass found nothing to index. */\n  #lastPassIdle = false;\n\n  /** Whether a throttled trace-triggered run is already waiting to start. */\n  #traceRunPending = false;\n\n  /** Wait before the next retry; reset by a pass that succeeds. */\n  #retryDelay = INDEX_RETRY_DELAY_MS;\n\n  /** Whether a retry after a failed pass is already waiting to start. */\n  #retryPending = false;\n\n  /** Passes failed so far, so a waiter can tell that one failed while it waited, and the newest failure. */\n  #failures = 0;\n  #lastFailure: unknown;\n\n  constructor({ feedBlocks, documentsSaved, runPass }: IndexSchedulerProps) {\n    super();\n    this.#feedBlocks = feedBlocks;\n    this.#documentsSaved = documentsSaved;\n    this.#runPass = runPass;\n  }\n\n  protected override async _open(): Promise<void> {\n    this.#task = new DeferredTask(this._ctx, this.#run);\n    this.#feedBlocks.on(this._ctx, ({ feedNamespace }) => {\n      if (feedNamespace === FeedProtocol.WellKnownNamespaces.trace) {\n        this.#scheduleTraceRun();\n      } else {\n        this.schedule('feed-blocks');\n      }\n    });\n    this.#documentsSaved.on(this._ctx, () => this.schedule('documents-saved'));\n    this.schedule('open');\n  }\n\n  /**\n   * Drains an in-flight pass, so a waiter's `runBlocking` loop is not left to hit the disposed\n   * context on its next iteration and escape as an unhandled rejection.\n   */\n  protected override async _close(): Promise<void> {\n    await this.#task?.join();\n    this.#releaseWaiters();\n    this.#task = undefined;\n    // The disposed context cancelled the timers that would clear these, and a reopened scheduler reuses them.\n    this.#traceRunPending = false;\n    this.#retryPending = false;\n    this.#retryDelay = INDEX_RETRY_DELAY_MS;\n  }\n\n  /** Starts a pass soon, coalesced with any other request made before it starts. */\n  schedule(reason: IndexRunReason): void {\n    if (reason !== 'batch-continuation') {\n      this.#inputGeneration++;\n    }\n    this.#noteReason(reason);\n    this.#task?.schedule();\n  }\n\n  /**\n   * Waits until every change made before the call is indexed. Changes made during the wait are left\n   * to later passes, so a stream of writes cannot hold the caller. A no-op once closed: a late\n   * caller has nothing to wait for, and `runBlocking` would throw on the disposed context.\n   *\n   * @throws {IndexPassFailedError} when a pass fails before those changes are indexed.\n   */\n  async waitForIndexed(reason?: IndexRequestReason): Promise<void> {\n    const task = this.#task;\n    if (!task || this._ctx.disposed) {\n      return;\n    }\n    // Waits for the inputs that existed on entry, not for the index to go idle: writes arriving faster\n    // than a pass completes never leave the empty batch that idleness needs.\n    const target = this.#inputGeneration;\n    const failures = this.#failures;\n    while (this.#indexedGeneration < target) {\n      if (reason) {\n        this.#noteReason(reason);\n      }\n      await task.runBlocking();\n      if (this._ctx.disposed) {\n        return;\n      }\n      // Rerunning the pass at once would fail again; the retry is already scheduled.\n      if (this.#failures > failures) {\n        throw new IndexPassFailedError({ cause: this.#lastFailure });\n      }\n    }\n    // One more pass when the last still found work, as the old wait-for-idle ended: under a quiet\n    // index it is empty and gives the results the last pass invalidated time to reach their clients,\n    // which callers that flush then read depend on. One, so a stream still cannot hold the caller.\n    if (!this.#lastPassIdle) {\n      await task.runBlocking();\n    }\n  }\n\n  /**\n   * Starts at most one trace-triggered run per {@link TRACE_INDEX_DELAY_MS}. The input generation is\n   * bumped at once, so {@link waitForIndexed} callers still wait for these blocks; only the\n   * background trigger is coalesced.\n   */\n  #scheduleTraceRun(): void {\n    this.#inputGeneration++;\n    this.#noteReason('trace-blocks');\n    if (this.#traceRunPending) {\n      return;\n    }\n    this.#traceRunPending = true;\n    scheduleTask(\n      this._ctx,\n      () => {\n        this.#traceRunPending = false;\n        this.#task?.schedule();\n      },\n      TRACE_INDEX_DELAY_MS,\n    );\n  }\n\n  /** Records why a run is wanted without scheduling it — for callers that drive the task directly. */\n  #noteReason(reason: IndexRunReason): void {\n    this.#pendingReasons.set(reason, (this.#pendingReasons.get(reason) ?? 0) + 1);\n  }\n\n  /** Drains the pending reasons so each run reports only the requests that produced it. */\n  #takeReasons(): Record<string, number> {\n    const reasons = Object.fromEntries(this.#pendingReasons);\n    this.#pendingReasons.clear();\n    return reasons;\n  }\n\n  /** Lets every waiter return: a closing host indexes nothing more. */\n  #releaseWaiters(): void {\n    this.#indexedGeneration = this.#inputGeneration;\n  }\n\n  /** Fails the waiters through {@link waitForIndexed} and retries with backoff. */\n  #retryAfterFailure(error: unknown): void {\n    const delayMs = this.#retryDelay;\n    log.error('index pass failed, retrying', { delayMs, error });\n    this.#failures++;\n    this.#lastFailure = error;\n    this.#retryDelay = Math.min(delayMs * 2, INDEX_RETRY_MAX_DELAY_MS);\n    if (this.#retryPending) {\n      return;\n    }\n    this.#retryPending = true;\n    scheduleTask(\n      this._ctx,\n      () => {\n        this.#retryPending = false;\n        this.schedule('retry');\n      },\n      delayMs,\n    );\n  }\n\n  #run = async (): Promise<void> => {\n    if (this._ctx.disposed) {\n      this.#releaseWaiters();\n      return;\n    }\n\n    // Derived and disposed per pass: `@trace.span` derives a child of whatever ctx it is handed,\n    // and a child stays on its parent's dispose list until disposed -- at three passes a second,\n    // parenting those on `this._ctx` is an unbounded leak.\n    const passCtx = this._ctx.derive();\n    try {\n      // Read before the pass reads its sources, so an input landing mid-pass is left to the next one.\n      const generation = this.#inputGeneration;\n      // Drained here rather than inside the pass so the span can report what triggered it.\n      let result: IndexPassResult | undefined;\n      try {\n        result = await this.#runPass(passCtx, this.#takeReasons());\n      } catch (error) {\n        // Raising would put this resource, and the host whose context it was opened on, into ERROR for good.\n        this.#retryAfterFailure(error);\n        return;\n      }\n      if (!result) {\n        this.#releaseWaiters();\n        return;\n      }\n      this.#retryDelay = INDEX_RETRY_DELAY_MS;\n      this.#lastPassIdle = result.done;\n      if (result.drained) {\n        this.#indexedGeneration = Math.max(this.#indexedGeneration, generation);\n      }\n      if (!result.done) {\n        this.schedule('batch-continuation');\n      }\n    } finally {\n      await passCtx.dispose();\n    }\n  };\n}\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport * as SqlClient from 'effect/sql/SqlClient';\nimport type * as SqlError from 'effect/sql/SqlError';\n\nimport { Event } from '@dxos/async';\nimport { IndexEngine } from '@dxos/index-core';\nimport { log } from '@dxos/log';\nimport { FeedProtocol } from '@dxos/protocols';\nimport { type DataService } from '@dxos/protocols/rpc';\n\nconst IDLE: DataService.IndexStatus = { phase: 'idle', done: 0, total: 0 };\n\nconst advance = (\n  progress: DataService.IndexProgress | undefined,\n  remaining: number,\n): DataService.IndexProgress | undefined => {\n  if (remaining <= 0) {\n    return undefined;\n  }\n  const total = Math.max(progress?.total ?? 0, (progress?.done ?? 0) + remaining);\n  return { done: total - remaining, total };\n};\n\nconst sameProgress = (a: DataService.IndexProgress | undefined, b: DataService.IndexProgress | undefined): boolean =>\n  a?.done === b?.done && a?.total === b?.total;\n\nconst withRebuild = (status: DataService.IndexStatus, remaining: number): DataService.IndexStatus => {\n  const rebuild = advance(\n    status.phase === 'indexing' ? { done: status.done, total: status.total } : undefined,\n    remaining,\n  );\n  return rebuild ? { phase: 'indexing', ...rebuild } : IDLE;\n};\n\nconst withLane = (\n  activity: DataService.IndexActivity,\n  lane: keyof DataService.IndexActivity,\n  remaining: number,\n): DataService.IndexActivity => {\n  const { [lane]: progress, ...rest } = activity;\n  const next = advance(progress, remaining);\n  return next ? { ...rest, [lane]: next } : rest;\n};\n\nconst rebuildOf = ({ documents, blocks }: IndexBacklog): number => documents + blocks;\n\n/** How often the tracker reads a count while work goes on. */\nexport const BACKLOG_RECOUNT_INTERVAL = 1_000;\n\n/**\n * The host's {@link DataService.IndexStatus} and {@link DataService.IndexActivity}, each with an event\n * on change. The one place index counts become progress: it decides when each count is taken (at most\n * once per {@link BACKLOG_RECOUNT_INTERVAL}), a count that fails leaves progress as it was, and each\n * kind of work ends when it does.\n */\nexport class IndexStatusTracker {\n  /** Each change of the status, so each is progress of a migration or rebuild. */\n  readonly updated = new Event<DataService.IndexStatus>();\n\n  readonly activityUpdated = new Event<DataService.IndexActivity>();\n\n  #status = IDLE;\n\n  #activity: DataService.IndexActivity = {};\n\n  #documentCatchUp = 0;\n\n  #feedCatchUp = 0;\n\n  readonly #recountInterval: number;\n\n  #countBacklog: () => Promise<IndexBacklog> = () => Promise.reject(new Error('index status not opened'));\n\n  #counting = false;\n\n  #countedAt = Number.NEGATIVE_INFINITY;\n\n  #fullTextCountedAt = Number.NEGATIVE_INFINITY;\n\n  /** `recountInterval` overrides {@link BACKLOG_RECOUNT_INTERVAL}. */\n  constructor({ recountInterval = BACKLOG_RECOUNT_INTERVAL }: { recountInterval?: number } = {}) {\n    this.#recountInterval = recountInterval;\n  }\n\n  get current(): DataService.IndexStatus {\n    return this.#status;\n  }\n\n  get activity(): DataService.IndexActivity {\n    return this.#activity;\n  }\n\n  setMigrating(done: number, total: number): void {\n    this.#setStatus({ phase: 'migrating', done, total });\n  }\n\n  /** Counts the rebuild once the stores open, which ends any migration; `count` is the backlog count from then on. */\n  async opened(count: () => Promise<IndexBacklog>): Promise<void> {\n    this.#countBacklog = count;\n    this.#countedAt = performance.now();\n    const backlog = await this.#count(count);\n    this.#setStatus(withRebuild(this.#status, backlog ? rebuildOf(backlog) : 0));\n  }\n\n  /** Whether the pass about to run counts its documents' catch-up, and the backlog after it. */\n  beginPass(): boolean {\n    this.#counting = performance.now() - this.#countedAt >= this.#recountInterval;\n    if (this.#counting) {\n      this.#countedAt = performance.now();\n    }\n    return this.#counting;\n  }\n\n  /**\n   * Moves the status and catch-up on after a pass, and after a counting one (see {@link beginPass})\n   * takes its documents' `catchUp` and recounts the backlog. A drained pass read every document it had\n   * to, so it ends the rebuild and catch-up.\n   */\n  async afterPass({ drained, catchUp }: { drained: boolean; catchUp?: number }): Promise<void> {\n    const counting = this.#counting;\n    this.#counting = false;\n    if (drained) {\n      this.#documentCatchUp = 0;\n      this.#feedCatchUp = 0;\n      this.#setStatus(IDLE);\n      this.#setActivity(withLane(this.#activity, 'catchUp', 0));\n      return;\n    }\n    if (counting) {\n      this.#documentCatchUp = catchUp ?? 0;\n      const backlog = await this.#count(this.#countBacklog);\n      if (backlog) {\n        this.#feedCatchUp = backlog.catchUp;\n        this.#setStatus(withRebuild(this.#status, rebuildOf(backlog)));\n      }\n    }\n    this.#setActivity(withLane(this.#activity, 'catchUp', this.#documentCatchUp + this.#feedCatchUp));\n  }\n\n  /** After a full-text batch that leaves more, recounts what is left with `count` when due. */\n  async afterFullTextBatch(count: () => Promise<number>): Promise<void> {\n    if (performance.now() - this.#fullTextCountedAt < this.#recountInterval) {\n      return;\n    }\n    this.#fullTextCountedAt = performance.now();\n    const remaining = await this.#count(count);\n    if (remaining !== undefined) {\n      this.#setActivity(withLane(this.#activity, 'fullText', remaining));\n    }\n  }\n\n  /** A full-text flush ended, done or failed, and its lane with it. */\n  fullTextEnded(): void {\n    this.#setActivity(withLane(this.#activity, 'fullText', 0));\n  }\n\n  async #count<T>(count: () => Promise<T>): Promise<T | undefined> {\n    try {\n      return await count();\n    } catch (err) {\n      log.warn('index progress count failed', { err });\n      return undefined;\n    }\n  }\n\n  #setStatus(status: DataService.IndexStatus): void {\n    const current = this.#status;\n    if (status.phase === current.phase && status.done === current.done && status.total === current.total) {\n      return;\n    }\n    this.#status = status;\n    this.updated.emit(status);\n  }\n\n  #setActivity(activity: DataService.IndexActivity): void {\n    const current = this.#activity;\n    if (sameProgress(activity.catchUp, current.catchUp) && sameProgress(activity.fullText, current.fullText)) {\n      return;\n    }\n    this.#activity = activity;\n    this.activityUpdated.emit(activity);\n  }\n}\n\nconst SOURCE_AUTOMERGE = 'automerge';\nconst SOURCE_FEED = 'queue';\nconst FEED_NAMESPACES = [FeedProtocol.WellKnownNamespaces.data, FeedProtocol.WellKnownNamespaces.trace];\n\n/** What {@link countIndexBacklog} found the primary indexes have not reached. */\nexport type IndexBacklog = {\n  /** Documents with no cursor: the rebuild, with {@link blocks}. */\n  documents: number;\n  /** Feed blocks stored before the host opened: the rebuild, with {@link documents}. */\n  blocks: number;\n  /** Feed blocks stored after the host opened, as after time offline. */\n  catchUp: number;\n};\n\n/**\n * The newest feed block when the host opens. Feed blocks share one insertion counter, so the blocks the\n * index has not read up to it stay a rebuild until it reads them, and blocks stored later are catch-up;\n * a feed cursor covers a whole namespace, so whether one exists cannot tell the two apart.\n */\nexport const readFeedPin = (): Effect.Effect<number, SqlError.SqlError, SqlClient.SqlClient> =>\n  Effect.gen(function* () {\n    const sql = yield* SqlClient.SqlClient;\n    const [row] = yield* sql<{ pin: number | null }>`SELECT MAX(insertionId) AS pin FROM blocks`;\n    return row?.pin ?? FeedProtocol.FEED_START;\n  });\n\n/**\n * What the primary indexes have not reached, under whichever primary index is furthest behind:\n * documents with no cursor, and the blocks of the feeds of `spaceIds` (the spaces the host has loaded,\n * which the indexer reads), split at `pin` (see {@link readFeedPin}).\n *\n * A document with a cursor but newer heads is not counted (heads are stored as a blob that SQL cannot\n * compare with a cursor); the indexing pass counts that catch-up as it reads.\n */\nexport const countIndexBacklog = ({\n  pin,\n  spaceIds,\n}: {\n  pin: number;\n  spaceIds: readonly string[];\n}): Effect.Effect<IndexBacklog, SqlError.SqlError, SqlClient.SqlClient> =>\n  Effect.gen(function* () {\n    const sql = yield* SqlClient.SqlClient;\n\n    let documents = 0;\n    for (const indexName of IndexEngine.primaryIndexNames) {\n      const [row] = yield* sql<{ count: number }>`\n        SELECT COUNT(*) AS count FROM automerge_heads WHERE document_id NOT IN (\n          SELECT resourceId FROM indexCursor WHERE indexName = ${indexName} AND sourceName = ${SOURCE_AUTOMERGE}\n        )`;\n      documents = Math.max(documents, row?.count ?? 0);\n    }\n\n    let blocks = 0;\n    let catchUp = 0;\n    if (spaceIds.length === 0) {\n      return { documents, blocks, catchUp };\n    }\n    const feeds = yield* sql<{ spaceId: string; feedNamespace: string }>`\n      SELECT DISTINCT spaceId, feedNamespace FROM feeds\n      WHERE feedNamespace IN ${sql.in(FEED_NAMESPACES)} AND spaceId IN ${sql.in([...spaceIds])}`;\n    for (const { spaceId, feedNamespace } of feeds) {\n      const cursors = yield* sql<{ cursor: string | null }>`\n        SELECT cursor FROM indexCursor\n        WHERE sourceName = ${SOURCE_FEED} AND spaceId = ${spaceId} AND resourceId = ${feedNamespace}\n          AND indexName IN ${sql.in([...IndexEngine.primaryIndexNames])}`;\n      const positions = cursors.map(({ cursor }) =>\n        cursor ? FeedProtocol.decodeFeedCursor(FeedProtocol.FeedCursor.make(cursor)).insertionId : Number.NaN,\n      );\n      const after =\n        positions.length === IndexEngine.primaryIndexNames.length && positions.every(Number.isFinite)\n          ? Math.min(...positions)\n          : FeedProtocol.FEED_START;\n      const [row] = yield* sql<{ rebuild: number | null; catchUp: number | null }>`\n        SELECT SUM(b.insertionId <= ${pin}) AS rebuild, SUM(b.insertionId > ${pin}) AS catchUp\n        FROM blocks b JOIN feeds f ON f.feedPrivateId = b.feedPrivateId\n        WHERE f.spaceId = ${spaceId} AND f.feedNamespace = ${feedNamespace} AND b.insertionId > ${after}`;\n      blocks += row?.rebuild ?? 0;\n      catchUp += row?.catchUp ?? 0;\n    }\n\n    return { documents, blocks, catchUp };\n  });\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport { next as A } from '@automerge/automerge';\nimport { type DocumentId, isValidDocumentId } from '@automerge/automerge-repo';\nimport bs58check from 'bs58check';\n\nimport { type Obj } from '@dxos/echo';\nimport {\n  type DatabaseDirectory,\n  type EntityStructure,\n  type RetirementReason,\n  SpaceDocVersion,\n} from '@dxos/echo-protocol';\nimport { objectStructureFromJson } from '@dxos/echo/internal';\nimport { invariant } from '@dxos/invariant';\nimport { type SpaceId } from '@dxos/keys';\n\n/** Ops below which a document is never retired for its history, however it grew. */\nexport const HISTORY_BLOAT_MIN_OPS = 100_000;\n\n/** How many times its current state's size a document's ops must reach before its history counts as bloated. */\nconst HISTORY_BLOAT_RATIO = 4;\n\n/**\n * Object types whose documents are retired when their history bloats. Sync cursors hold only machine-written\n * state, so rebuilding them from their current state loses nothing a user wrote.\n */\nconst HISTORY_RETIREMENT_TYPES: readonly string[] = ['dxn:org.dxos.type.cursor:'];\n\n/** A `retired` entry of a space directory, read back; see {@link DatabaseDirectory.retired}. */\nexport type Retirement = { documentId: string; replacedBy: string; reason: RetirementReason };\n\n/** One object of a retired document, as the index last saw it. */\nexport type IndexedObject = {\n  objectId: string;\n  json: Obj.JSON;\n  createdAt: number | null;\n};\n\n/**\n * Id of a document derived from `seed` rather than random, so peers that create the document for the same reason\n * concurrently write into one document instead of linking several.\n */\nexport const deriveDocumentId = async (seed: string): Promise<DocumentId> => {\n  const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(seed));\n  const id = bs58check.encode(new Uint8Array(digest).subarray(0, 16));\n  invariant(isValidDocumentId(id), 'Derived document id is invalid.');\n  return id;\n};\n\n/**\n * A document as one deterministic change: its actor is derived from `seed` and the content exactly as inserted,\n * and its timestamp is fixed. Peers that build the same state produce byte-identical changes that merge into one;\n * any difference yields a distinct actor, which Automerge merges as a conflict.\n */\nexport const buildDeterministicDocument = async (\n  seed: string,\n  directory: DatabaseDirectory,\n): Promise<A.Doc<DatabaseDirectory>> => {\n  const digest = await crypto.subtle.digest(\n    'SHA-256',\n    new TextEncoder().encode(`${seed}:${JSON.stringify(directory)}`),\n  );\n  const actor = Array.from(new Uint8Array(digest).subarray(0, 16), (byte) => byte.toString(16).padStart(2, '0')).join(\n    '',\n  );\n  return A.change(A.init<DatabaseDirectory>({ actor }), { time: 0 }, (draft) => Object.assign(draft, directory));\n};\n\n/** Id of the document that replaces `documentId` when it is retired. */\nexport const replacementDocumentId = (documentId: DocumentId): Promise<DocumentId> =>\n  deriveDocumentId(`dxos:retired:${documentId}`);\n\n/** The replacement document of `documentId`; see {@link buildDeterministicDocument}. */\nexport const buildReplacementDocument = (\n  documentId: DocumentId,\n  directory: DatabaseDirectory,\n): Promise<A.Doc<DatabaseDirectory>> => buildDeterministicDocument(`dxos:retired:${documentId}`, directory);\n\n/** The directory that replaces an unloadable document: its objects rebuilt from the index, with no history. */\nexport const makeReplacementDirectory = ({\n  spaceId,\n  spaceKey,\n  objects,\n}: {\n  spaceId: SpaceId;\n  /** Written alongside `spaceId` for clients that still read it, as every new document is. */\n  spaceKey: string | null;\n  objects: readonly IndexedObject[];\n}): DatabaseDirectory => ({\n  version: SpaceDocVersion.CURRENT,\n  access: spaceKey ? { spaceId, spaceKey } : { spaceId },\n  objects: Object.fromEntries(\n    objects.map(({ objectId, json, createdAt }): [string, EntityStructure] => [\n      objectId,\n      objectStructureFromJson(json, { createdAt: createdAt ?? undefined }),\n    ]),\n  ),\n});\n\n/** Whether a document's history has outgrown its current state, which a rebuild without history would fix. */\nexport const isHistoryBloated = ({ ops, stateBytes }: { ops: number; stateBytes: number }): boolean =>\n  ops >= HISTORY_BLOAT_MIN_OPS && ops >= HISTORY_BLOAT_RATIO * stateBytes;\n\n/** Whether every object's type is one {@link HISTORY_RETIREMENT_TYPES} allows to be rebuilt. */\nexport const isRetirableForHistory = (typeDXNs: readonly (string | null | undefined)[]): boolean =>\n  typeDXNs.length > 0 &&\n  typeDXNs.every((typeDXN) => HISTORY_RETIREMENT_TYPES.some((prefix) => typeDXN?.startsWith(prefix) ?? false));\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport { next as A } from '@automerge/automerge';\nimport { type DocumentId } from '@automerge/automerge-repo';\n\nimport { type DatabaseDirectory, type EntityStructure, SpaceDocVersion } from '@dxos/echo-protocol';\nimport { type SpaceId } from '@dxos/keys';\n\nimport { buildDeterministicDocument, deriveDocumentId } from './retirement.ts';\n\n/** One seed per directory and object, so peers that migrate the same object concurrently write one document. */\nconst inlineObjectSeed = (directoryId: DocumentId, objectId: string): string =>\n  `dxos:inline:${directoryId}:${objectId}`;\n\n/** Id of the document an object inlined in the space directory `directoryId` moves to. */\nexport const inlineObjectDocumentId = (directoryId: DocumentId, objectId: string): Promise<DocumentId> =>\n  deriveDocumentId(inlineObjectSeed(directoryId, objectId));\n\n/**\n * The document an inlined object moves to, holding only that object, as one deterministic change; see\n * {@link buildDeterministicDocument}.\n */\nexport const buildInlineObjectDocument = ({\n  directoryId,\n  spaceId,\n  spaceKey,\n  objectId,\n  structure,\n}: {\n  directoryId: DocumentId;\n  spaceId: SpaceId;\n  /** Written alongside `spaceId` for clients that still read it, as every new document is. */\n  spaceKey: string | null;\n  objectId: string;\n  structure: EntityStructure;\n}): Promise<A.Doc<DatabaseDirectory>> =>\n  buildDeterministicDocument(inlineObjectSeed(directoryId, objectId), {\n    version: SpaceDocVersion.CURRENT,\n    access: spaceKey ? { spaceId, spaceKey } : { spaceId },\n    objects: { [objectId]: structure },\n  });\n\n/**\n * Whether a document holds only creation changes — the deterministic ones migrating peers write, which depend on\n * nothing. Its object is then still the inline copy as some peer saw it, and no one has edited it through a link.\n */\nexport const isUntouchedSinceCreation = (doc: A.Doc<DatabaseDirectory>): boolean =>\n  A.getAllChanges(doc).every((change) => A.decodeChange(change).deps.length === 0);\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport type { IndexingResult } from '@dxos/index-core';\nimport { DXN, type EntityId, type SpaceId } from '@dxos/keys';\n\nexport type InvalidationHint = {\n  spaceIds?: ReadonlySet<SpaceId>;\n  queueIds?: ReadonlySet<EntityId>;\n  /**\n   * Canonical typenames (version-less) — see {@link canonicalTypename}.\n   * A type filter matches every version of a typename, so invalidation keys on the bare typename.\n   * Query scopes are canonicalized the same way, so hints and scopes compare with a plain set overlap.\n   */\n  typenames?: ReadonlySet<string>;\n  objectIds?: ReadonlySet<EntityId>;\n};\n\n/**\n * Reduces a type URI to the version-less typename used as the canonical key for invalidation\n * matching. Stored objects record a versioned `@type` (e.g. `dxn:foo:0.1.0`) while type filters\n * reference a typename without a version; both collapse to the same key here. Non-DXN URIs\n * (EchoURI schema references) have no version and pass through unchanged.\n */\nexport const canonicalTypename = (uri: string): string => {\n  const dxn = DXN.tryMake(uri);\n  return dxn != null ? DXN.getName(dxn) : uri;\n};\n\n/**\n * Converts an IndexingResult to an InvalidationHint.\n * Returns undefined when nothing was indexed (no need to invalidate).\n */\nexport const hintFromIndexingResult = (r: IndexingResult): InvalidationHint | undefined => {\n  if (r.updated === 0) {\n    return undefined;\n  }\n  return {\n    spaceIds: r.spaces.size > 0 ? r.spaces : undefined,\n    queueIds: r.queues.size > 0 ? r.queues : undefined,\n    typenames: r.types.size > 0 ? new Set(Array.from(r.types, canonicalTypename)) : undefined,\n    objectIds: r.objects.size > 0 ? r.objects : undefined,\n  };\n};\n\n/**\n * Merges two hints for the same tick.\n * If either side leaves a dimension unconstrained (undefined), the merged result is also unconstrained on that dimension.\n */\nexport const mergeHints = (a: InvalidationHint, b: InvalidationHint): InvalidationHint => ({\n  spaceIds: unionOrUndefined(a.spaceIds, b.spaceIds),\n  queueIds: unionOrUndefined(a.queueIds, b.queueIds),\n  typenames: unionOrUndefined(a.typenames, b.typenames),\n  objectIds: unionOrUndefined(a.objectIds, b.objectIds),\n});\n\nconst unionOrUndefined = <T>(\n  a: ReadonlySet<T> | undefined,\n  b: ReadonlySet<T> | undefined,\n): ReadonlySet<T> | undefined => {\n  if (a === undefined || b === undefined) {\n    return undefined;\n  }\n  return new Set<T>([...a, ...b]);\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport * as Function from 'effect/Function';\nimport type * as SqlClient from 'effect/sql/SqlClient';\nimport * as EffectStream from 'effect/Stream';\n\nimport { type Event } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { EchoFeedCodec } from '@dxos/echo-protocol';\nimport { type ObjectJSON } from '@dxos/echo/internal';\nimport * as EffectEx from '@dxos/effect/EffectEx';\nimport * as RuntimeProvider from '@dxos/effect/RuntimeProvider';\nimport { BaseError } from '@dxos/errors';\nimport { type FeedStore } from '@dxos/feed';\nimport { assertArgument, invariant } from '@dxos/invariant';\nimport { SpaceId } from '@dxos/keys';\nimport { FeedProtocol, toServiceError } from '@dxos/protocols';\nimport { type FeedService } from '@dxos/protocols/rpc';\n\n/**\n * Writes feed data to a local FeedStore.\n */\nexport class LocalFeedServiceImpl implements FeedService.Handlers {\n  #runtime: RuntimeProvider.RuntimeProvider<SqlClient.SqlClient>;\n  #feedStore: FeedStore;\n  #syncFeed?: (ctx: Context, request: FeedService.SyncFeedRequest) => Promise<void>;\n\n  'constructor'(\n    runtime: RuntimeProvider.RuntimeProvider<SqlClient.SqlClient>,\n    feedStore: FeedStore,\n    options?: {\n      syncFeed?: (ctx: Context, request: FeedService.SyncFeedRequest) => Promise<void>;\n    },\n  ) {\n    this.#runtime = runtime;\n    this.#feedStore = feedStore;\n    this.#syncFeed = options?.syncFeed;\n  }\n\n  ['FeedService.queryFeed'](\n    request: FeedService.QueryFeedRequest,\n  ): Effect.Effect<FeedService.FeedQueryResult, BaseError> {\n    return Effect.tryPromise({\n      try: () => this.#queryFeedImpl(request),\n      catch: toServiceError,\n    });\n  }\n\n  /**\n   * Pushes the feed's full contents on subscribe, then on every {@link FeedStore.onNewBlocks} signal\n   * a delta: the blocks written since, and position changes and removals of blocks sent before. Each\n   * push costs a scan of block heads plus the new payloads, not a re-read of the whole feed.\n   *\n   * `after`, `limit` and `reverse` are ignored: a subscriber is sent every block of its feeds.\n   */\n  ['FeedService.subscribeFeed'](\n    request: FeedService.QueryFeedRequest,\n  ): EffectStream.Stream<FeedService.FeedQueryResult, Error> {\n    const { query } = request;\n    invariant(query, 'query is required');\n    const spaceId = query.spaceId;\n    const feedNamespace = query.feedNamespace || FeedProtocol.WellKnownNamespaces.data;\n    const feedStore = this.#feedStore;\n    let dataAfter = -1;\n    let sent: Map<string, number | null> | undefined;\n    return this.#recomputeOn(\n      this.#feedStore.onNewBlocks,\n      spaceId,\n      () =>\n        RuntimeProvider.runPromise(this.#runtime)(\n          Effect.gen(function* () {\n            const { heads, blocks } = yield* feedStore.queryHeads({\n              spaceId,\n              feedNamespace,\n              feedIds: query.feedIds,\n              dataAfter,\n            });\n            const current = new Map<string, number | null>();\n            for (const head of [...heads, ...blocks]) {\n              current.set(EchoFeedCodec.blockId(head.actorId, head.sequence), head.position);\n              dataAfter = Math.max(dataAfter, head.insertionId ?? -1);\n            }\n            const objects = blocks.map((block) => JSON.stringify(EchoFeedCodec.decodeBlock(block)));\n            const previous = sent;\n            sent = current;\n            if (previous === undefined) {\n              return Function.identity<FeedService.FeedQueryResult>({ objects, nextCursor: '', prevCursor: '' });\n            }\n            return Function.identity<FeedService.FeedQueryResult>({\n              objects,\n              nextCursor: '',\n              prevCursor: '',\n              delta: true,\n              positions: [...current]\n                .filter(([block, position]) => previous.has(block) && previous.get(block) !== position)\n                .map(([block, position]) => ({ block, position })),\n              removed: [...previous.keys()].filter((block) => !current.has(block)),\n            });\n          }),\n        ),\n      (_, next) =>\n        next.delta !== true ||\n        (next.objects?.length ?? 0) + (next.positions?.length ?? 0) + (next.removed?.length ?? 0) > 0,\n    );\n  }\n\n  async #queryFeedImpl(request: FeedService.QueryFeedRequest): Promise<FeedService.FeedQueryResult> {\n    const { query } = request;\n    invariant(query, 'query is required');\n    const { spaceId, feedIds } = query;\n    return RuntimeProvider.runPromise(this.#runtime)(\n      Effect.gen({ self: this }, function* () {\n        const result = yield* this.#feedStore.query({\n          requestId: crypto.randomUUID(),\n          feedNamespace: request.query.feedNamespace || FeedProtocol.WellKnownNamespaces.data,\n          spaceId: spaceId! as SpaceId,\n          query: { feedIds: feedIds ?? [] },\n          cursor: query.after ? FeedProtocol.FeedCursor.make(query.after) : undefined,\n          limit: query.limit,\n        });\n\n        const objects = result.blocks.map((block: FeedProtocol.Block) =>\n          JSON.stringify(EchoFeedCodec.decodeBlock(block)),\n        );\n\n        return Function.identity<FeedService.FeedQueryResult>({\n          objects,\n          nextCursor: result.nextCursor,\n          prevCursor: '',\n        });\n      }),\n    );\n  }\n\n  ['FeedService.insertIntoFeed'](\n    request: FeedService.InsertIntoFeedRequest,\n  ): Effect.Effect<FeedService.InsertIntoFeedResponse, BaseError> {\n    return Effect.tryPromise({\n      try: async () => {\n        const { subspaceTag, spaceId, feedId, objects } = request;\n        const feedNamespace = subspaceTag ?? FeedProtocol.WellKnownNamespaces.data;\n        assertArgument(\n          FeedProtocol.isWellKnownNamespace(feedNamespace),\n          'request.subspaceTag',\n          'expected a well-known feed namespace',\n        );\n        return RuntimeProvider.runPromise(this.#runtime)(\n          Effect.gen({ self: this }, function* () {\n            const messages = (objects ?? []).map((encoded) => {\n              const object: ObjectJSON = JSON.parse(encoded);\n              return {\n                spaceId: spaceId,\n                feedId,\n                feedNamespace,\n                ...EchoFeedCodec.writeIntentOf(object),\n                data: EchoFeedCodec.encode(object),\n              };\n            });\n\n            const blocks = yield* this.#feedStore.appendLocal(messages);\n            return {\n              blocks: blocks.map((block) => EchoFeedCodec.blockId(block.actorId, block.sequence)),\n              predecessors: blocks.map((block) =>\n                block.prevActorId !== null && block.prevSequence !== null\n                  ? EchoFeedCodec.blockId(block.prevActorId, block.prevSequence)\n                  : null,\n              ),\n            };\n          }),\n        );\n      },\n      catch: toServiceError,\n    });\n  }\n\n  ['FeedService.deleteFromFeed'](request: FeedService.DeleteFromFeedRequest): Effect.Effect<void, BaseError> {\n    return Effect.tryPromise({\n      try: async () => {\n        const { subspaceTag, spaceId, feedId, objectIds, branches } = request;\n        const feedNamespace = subspaceTag ?? FeedProtocol.WellKnownNamespaces.data;\n        assertArgument(objectIds !== undefined, 'request.objectIds', 'expected the ids to remove');\n        assertArgument(\n          FeedProtocol.isWellKnownNamespace(feedNamespace),\n          'request.subspaceTag',\n          'expected a well-known feed namespace',\n        );\n        await RuntimeProvider.runPromise(this.#runtime)(\n          Effect.gen({ self: this }, function* () {\n            const messages = objectIds.map((id, index) => ({\n              spaceId: spaceId,\n              feedId,\n              feedNamespace,\n              branch: branches?.[index] ?? null,\n              data: EchoFeedCodec.encode({ id, '@deleted': true }),\n            }));\n\n            yield* this.#feedStore.appendLocal(messages);\n          }),\n        );\n      },\n      catch: toServiceError,\n    });\n  }\n\n  ['FeedService.syncFeed'](request: FeedService.SyncFeedRequest): Effect.Effect<void, BaseError> {\n    return Effect.tryPromise({\n      try: async () => {\n        await this.#syncFeed?.(Context.default(), request);\n      },\n      catch: toServiceError,\n    });\n  }\n\n  ['FeedService.getSyncState'](\n    request: FeedService.GetSyncStateRequest,\n  ): Effect.Effect<FeedService.GetSyncStateResponse, BaseError> {\n    return Effect.tryPromise({\n      try: () => this.#getSyncStateImpl(request),\n      catch: toServiceError,\n    });\n  }\n\n  ['FeedService.subscribeSyncState'](\n    request: FeedService.GetSyncStateRequest,\n  ): EffectStream.Stream<FeedService.GetSyncStateResponse, Error> {\n    return this.#recomputeOn(\n      this.#feedStore.onSyncStateChanged,\n      request.spaceId,\n      () => this.#getSyncStateImpl(request),\n      syncStateResponseChanged,\n    );\n  }\n\n  /**\n   * Shared by every `subscribeX` RPC: pushes `compute()`'s result on subscribe, then again whenever\n   * `event` fires for `spaceId` and `changed` says the recomputed value\n   * actually differs from the last one sent. Coalesced, not concurrent -- a signal that arrives\n   * mid-recomputation only marks `dirty` rather than starting a second overlapping read, so a slow\n   * recomputation can never finish after (and thus emit over) a faster, later one.\n   */\n  #recomputeOn<T>(\n    event: Event<{ spaceId: string }>,\n    spaceId: string,\n    compute: () => Promise<T>,\n    changed: (before: T, after: T) => boolean,\n  ): EffectStream.Stream<T, Error> {\n    return EffectEx.streamFromEmitter<T, Error>((emit) => {\n      const ctx = Context.default();\n      let last: T | undefined;\n      let running = false;\n      let dirty = false;\n      const recompute = async () => {\n        if (running) {\n          dirty = true;\n          return;\n        }\n        running = true;\n        try {\n          do {\n            dirty = false;\n            const next = await compute();\n            if (!last || changed(last, next)) {\n              last = next;\n              emit.single(next);\n            }\n          } while (dirty);\n        } catch (err) {\n          emit.fail(err as Error);\n        } finally {\n          running = false;\n        }\n      };\n      void recompute();\n      event.on(ctx, (signal) => {\n        if (signal.spaceId === spaceId) {\n          void recompute();\n        }\n      });\n      return Effect.promise(() => ctx.dispose());\n    });\n  }\n\n  #getSyncStateImpl(request: FeedService.GetSyncStateRequest): Promise<FeedService.GetSyncStateResponse> {\n    const { spaceId } = request;\n    assertArgument(SpaceId.isValid(spaceId), 'request.spaceId', 'expected a space id');\n    const namespaces =\n      request.namespaces != null && request.namespaces.length > 0\n        ? request.namespaces\n        : Object.values(FeedProtocol.WellKnownNamespaces);\n    for (const feedNamespace of namespaces) {\n      assertArgument(\n        FeedProtocol.isWellKnownNamespace(feedNamespace),\n        'request.namespaces',\n        'expected well-known feed namespaces',\n      );\n    }\n\n    return RuntimeProvider.runPromise(this.#runtime)(\n      Effect.gen({ self: this }, function* () {\n        const namespaceStates = yield* Effect.forEach(\n          namespaces,\n          (feedNamespace) =>\n            Effect.gen({ self: this }, function* () {\n              const blocksToPush = yield* this.#feedStore.countUnpositionedBlocks({\n                spaceId,\n                feedNamespace,\n              });\n              const totalBlocks = yield* this.#feedStore.countNamespaceBlocks({\n                spaceId,\n                feedNamespace,\n              });\n              const { blocksToPull } = yield* this.#feedStore.getSyncState({ spaceId, feedNamespace });\n              return {\n                namespace: feedNamespace,\n                blocksToPull: String(blocksToPull),\n                blocksToPush: String(blocksToPush),\n                totalBlocks: String(totalBlocks),\n              };\n            }),\n          { concurrency: 'unbounded' },\n        );\n        return { namespaces: namespaceStates };\n      }),\n    );\n  }\n}\n\n/**\n * Assumes both responses enumerate namespaces in the same order -- true because `#getSyncStateImpl`\n * always iterates the same fixed `namespaces` list for a given request.\n */\nconst syncStateResponseChanged = (\n  before: FeedService.GetSyncStateResponse,\n  after: FeedService.GetSyncStateResponse,\n): boolean => {\n  const beforeNamespaces = before.namespaces ?? [];\n  const afterNamespaces = after.namespaces ?? [];\n  if (beforeNamespaces.length !== afterNamespaces.length) {\n    return true;\n  }\n  return beforeNamespaces.some((namespaceState, index) => {\n    const other = afterNamespaces[index];\n    return (\n      namespaceState.namespace !== other.namespace ||\n      namespaceState.blocksToPull !== other.blocksToPull ||\n      namespaceState.blocksToPush !== other.blocksToPush ||\n      namespaceState.totalBlocks !== other.totalBlocks\n    );\n  });\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport * as A from '@automerge/automerge';\nimport { type DocumentId } from '@automerge/automerge-repo';\nimport type * as Effect from 'effect/Effect';\nimport type * as SqlClient from 'effect/sql/SqlClient';\n\nimport { type Context } from '@dxos/context';\nimport { type QueryAST } from '@dxos/echo-protocol';\nimport { type IndexEngine } from '@dxos/index-core';\nimport { invariant } from '@dxos/invariant';\nimport { EID, type SpaceId } from '@dxos/keys';\nimport { type QueryService } from '@dxos/protocols/rpc';\n\nimport type { AutomergeHost } from '../automerge/index.ts';\nimport { type ChangeRecord, toChangeRecord } from '../db-host/change-record.ts';\nimport type { SpaceStateManager } from '../db-host/index.ts';\nimport { type GroupAggregates, GroupBy, type GroupKeyValue } from './group-by.ts';\nimport { type QueryPlan } from './plan.ts';\n\n/** A replayed change, or an hourly activity bucket standing for its `changes`. */\ntype ChangeRow =\n  | { kind: 'change'; change: ChangeRecord }\n  | { kind: 'bucket'; hour: number; changes: number; ops: number };\n\nexport type ChangeItem = {\n  spaceId: SpaceId;\n  row: ChangeRow;\n  weight: number;\n  groupKey?: GroupKeyValue;\n  aggregates?: GroupAggregates;\n  collapsed?: { size: number };\n};\n\nexport type ChangesExecutorDeps = {\n  indexEngine: IndexEngine;\n  automergeHost: AutomergeHost;\n  spaceStateManager: SpaceStateManager;\n  runInRuntime: <T>(effect: Effect.Effect<T, unknown, SqlClient.SqlClient>) => Promise<T>;\n};\n\nexport const executeChangesPlan = async (\n  ctx: Context,\n  plan: QueryPlan.Plan,\n  deps: ChangesExecutorDeps,\n): Promise<ChangeItem[]> => {\n  const [select, ...rest] = plan.steps;\n  if (select._tag !== 'SelectStep' || select.selector._tag !== 'ChangesSelector') {\n    throw new Error('Expected a changes select step.');\n  }\n  const spaceIds = select.scope.flatMap((scope) => (scope._tag === 'space' ? [scope.spaceId as SpaceId] : []));\n  let workingSet = await selectChanges(ctx, select.selector, spaceIds, deps);\n  for (const step of rest) {\n    workingSet = execStep(step, workingSet);\n  }\n  return workingSet;\n};\n\nexport const changeResults = (items: readonly ChangeItem[]): QueryService.QueryResult[] =>\n  items.map((item): QueryService.QueryResult => {\n    if (item.collapsed !== undefined && item.groupKey !== undefined) {\n      const groupKey = GroupBy.serializeGroupKey(item.groupKey);\n      return {\n        id: groupKey,\n        spaceId: item.spaceId,\n        rank: 1,\n        groupKey,\n        groupCount: item.collapsed.size,\n        aggregates: JSON.stringify(item.aggregates ?? {}),\n      };\n    }\n    invariant(item.row.kind === 'change', 'Only a replayed change ships as a record.');\n    const { change } = item.row;\n    return { id: change.key, spaceId: item.spaceId, rank: 1, recordJson: JSON.stringify(change) };\n  });\n\nexport const serializeChangeResults = (items: readonly ChangeItem[]): string =>\n  JSON.stringify(changeResults(items).map(({ id, groupCount, aggregates }) => [id, groupCount, aggregates]));\n\nconst selectChanges = async (\n  ctx: Context,\n  selector: QueryPlan.ChangesSelector,\n  spaceIds: readonly SpaceId[],\n  deps: ChangesExecutorDeps,\n): Promise<ChangeItem[]> => {\n  const documents = selector.targets && (await resolveDocuments(selector.targets, spaceIds, deps));\n  const items: ChangeItem[] = [];\n\n  if (selector.source === 'index') {\n    for (const spaceId of spaceIds) {\n      const documentIds = documents?.filter((document) => document.spaceId === spaceId).map((doc) => doc.documentId);\n      const rows = await deps.runInRuntime(deps.indexEngine.queryActivity({ spaceId, documentIds }));\n      for (const { hour, changes, ops } of rows) {\n        items.push({ spaceId, row: { kind: 'bucket', hour, changes, ops }, weight: changes });\n      }\n    }\n    return items;\n  }\n\n  for (const { spaceId, documentId } of documents ?? []) {\n    if (deps.spaceStateManager.isBranchDocument(documentId)) {\n      continue;\n    }\n    using lease = await deps.automergeHost.loadDoc<Record<string, unknown>>(ctx, documentId, {\n      fetchFromNetwork: false,\n    });\n    if (!lease) {\n      continue;\n    }\n    for (const meta of A.getChangesMetaSince(lease.doc(), [])) {\n      const change = toChangeRecord(meta);\n      if (change) {\n        items.push({ spaceId, row: { kind: 'change', change }, weight: 1 });\n      }\n    }\n  }\n  return items.sort(compareNatural);\n};\n\nconst resolveDocuments = async (\n  targets: readonly EID.EID[],\n  spaceIds: readonly SpaceId[],\n  deps: ChangesExecutorDeps,\n): Promise<{ spaceId: SpaceId; documentId: DocumentId }[]> => {\n  const objectIds = targets.flatMap((target) => {\n    const entityId = EID.getEntityId(target);\n    return entityId ? [entityId] : [];\n  });\n  if (objectIds.length === 0 || spaceIds.length === 0) {\n    return [];\n  }\n  const metas = await deps.runInRuntime(deps.indexEngine.queryObjectIds({ spaceIds, objectIds }));\n  const documents = new Map<string, { spaceId: SpaceId; documentId: DocumentId }>();\n  for (const meta of metas) {\n    if (meta.documentId) {\n      documents.set(`${meta.spaceId}/${meta.documentId}`, {\n        spaceId: meta.spaceId as SpaceId,\n        documentId: meta.documentId as DocumentId,\n      });\n    }\n  }\n  return [...documents.values()];\n};\n\nconst execStep = (step: QueryPlan.Step, workingSet: ChangeItem[]): ChangeItem[] => {\n  const grouped = workingSet.length > 0 && workingSet[0].groupKey !== undefined;\n  switch (step._tag) {\n    case 'OrderStep': {\n      const compare = (a: ChangeItem, b: ChangeItem) => compareMultiOrder(a, b, step.order);\n      const sorted = grouped ? GroupBy.orderGroups(workingSet, getGroupKey, compare) : [...workingSet].sort(compare);\n      if (step.limit === undefined) {\n        return sorted;\n      }\n      return grouped ? GroupBy.takeGroups(sorted, step.limit, getGroupKey) : sorted.slice(0, step.limit);\n    }\n    case 'LimitStep':\n      return grouped ? GroupBy.takeGroups(workingSet, step.limit, getGroupKey) : workingSet.slice(0, step.limit);\n    case 'SkipStep':\n      return grouped ? GroupBy.dropGroups(workingSet, step.skip, getGroupKey) : workingSet.slice(step.skip);\n    case 'AggregateStep': {\n      const withKeys = workingSet.map((item) => ({ ...item, groupKey: groupKeyOf(item, step.aggregates) }));\n      const partitioned = GroupBy.partitionByGroupKey(withKeys, getGroupKey);\n      const stamped = GroupBy.withGroupAggregates(partitioned, getGroupKey, step.aggregates, (item, property) =>\n        fieldOf(item.row, property),\n      );\n      return GroupBy.collapseGroups(stamped, getGroupKey);\n    }\n    default:\n      throw new Error(`Unexpected step after a changes select: ${step._tag}`);\n  }\n};\n\nconst getGroupKey = (item: ChangeItem): string => {\n  invariant(item.groupKey, 'Grouped steps run only after an aggregate keyed every item.');\n  return GroupBy.serializeGroupKey(item.groupKey);\n};\n\n/** The row's `Change.Change` fields; a bucket has only `source`, `time` and `ops`, all the planner lets it read. */\nconst fieldsOf = (row: ChangeRow): Readonly<Record<string, unknown>> =>\n  row.kind === 'change' ? row.change : { source: 'document', time: row.hour, ops: row.ops };\n\nconst fieldOf = (row: ChangeRow, property: string): unknown => fieldsOf(row)[property];\n\nconst groupKeyOf = (item: ChangeItem, aggregates: readonly QueryAST.GroupAggregate[]): GroupKeyValue => {\n  const key: GroupKeyValue = {};\n  for (const aggregate of aggregates) {\n    if (aggregate.kind === 'group') {\n      key[aggregate.name] = GroupBy.resolveKeyComponent(aggregate.properties, (property) =>\n        fieldOf(item.row, property),\n      );\n    } else if (aggregate.kind === 'time') {\n      key[aggregate.name] = GroupBy.truncateTime(fieldOf(item.row, aggregate.property), aggregate.unit);\n    }\n  }\n  return key;\n};\n\nconst compareNatural = (a: ChangeItem, b: ChangeItem): number =>\n  Number(fieldOf(a.row, 'time')) - Number(fieldOf(b.row, 'time')) ||\n  String(fieldOf(a.row, 'key') ?? '').localeCompare(String(fieldOf(b.row, 'key') ?? ''));\n\nconst compareMultiOrder = (a: ChangeItem, b: ChangeItem, orders: readonly QueryAST.Order[]): number => {\n  for (const order of orders) {\n    const comparison =\n      order.kind === 'natural'\n        ? compareNatural(a, b)\n        : order.kind === 'property'\n          ? GroupBy.compareScalar(propertyOf(a, order.property), propertyOf(b, order.property))\n          : 0;\n    if (comparison !== 0) {\n      return order.direction === 'desc' ? -comparison : comparison;\n    }\n  }\n  return 0;\n};\n\nconst propertyOf = (item: ChangeItem, property: string) =>\n  item.aggregates && property in item.aggregates\n    ? item.aggregates[property]\n    : GroupBy.coerceKeyComponent(fieldOf(item.row, property));\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport * as SqlClient from 'effect/sql/SqlClient';\nimport type * as Statement from 'effect/sql/Statement';\n\nimport {\n  EncodedReference,\n  EscapedPropPath,\n  QueryAST,\n  isEncodedReference,\n  referenceIndexKey,\n} from '@dxos/echo-protocol';\nimport { ATTR_META } from '@dxos/echo/internal';\nimport {\n  type QueueRef,\n  type QueueWindow,\n  buildFtsCondition,\n  buildQueueWindow,\n  buildSourceCondition,\n  buildTypeDxnCondition,\n  normalizePropPath,\n  queueBranchesOf,\n} from '@dxos/index-core';\nimport { DXN, EID, EntityId, type SpaceId } from '@dxos/keys';\n\nimport { QueryError } from '../errors.ts';\nimport { QueryPlan } from '../plan.ts';\n\n/**\n * Depth bounds shared with the in-memory executor and `DeletionResolver`, so a query and garbage\n * collection agree on what counts as deleted or reachable.\n */\nconst MAX_DEPTH_FOR_DELETION_TRACING = 10;\nconst MAX_DEPTH_FOR_CHILD_OF_TRACING = 10;\nconst MAX_DEPTH_FOR_STRONG_DEP_TRACING = 10;\n\n/** Keeps union branches ordered after one another without renumbering their rows. */\nconst UNION_BRANCH_STRIDE = 1_000_000_000;\n\n/**\n * A working-set row's own metadata is a rowid lookup. `NOT INDEXED` keeps it one: given a `WHERE`\n * on `queueId` the planner would otherwise drive from `objectMeta` through the queue-position index\n * and probe the working set, a scan of every document instead of one seek per row.\n *\n * `objectMeta` indexes the joins below name explicitly. Without `ANALYZE` statistics SQLite rates an\n * equality on `queueId` (the leading column of the queue-position index, true of every document\n * row) as cheap as a seek on `(spaceId, objectId)`, and picks it; the traversal then scans every\n * document per reference. The names are fixed by the entity-meta migrations.\n */\nconst INDEX_SPACE_OBJECT = 'idx_object_index_objectId';\nconst INDEX_SPACE_TYPE = 'idx_object_index_typeDXN';\nconst INDEX_SPACE_QUEUE_OBJECT = 'idx_object_index_queueObjectId';\nconst INDEX_SPACE_QUEUE_BRANCH = 'idx_object_index_queueBranch';\nconst INDEX_SPACE_PARENT = 'idx_object_index_parentId';\nconst INDEX_SPACE_SOURCE = 'idx_object_index_sourceId';\nconst INDEX_SPACE_TARGET = 'idx_object_index_targetId';\n\n/** One row of a compiled query's final projection. */\nexport type CompiledRow = {\n  recordId: number;\n  objectId: EntityId;\n  spaceId: SpaceId;\n  documentId: string;\n  queueId: string;\n  queueNamespace: string;\n  rank: number;\n  createdAt: number | null;\n  updatedAt: number | null;\n  documentJson: string | null;\n  /** JSON text of the group key; present iff the plan aggregates. */\n  groupKey: string | null;\n  groupCount: number | null;\n  /**\n   * JSON text of the scalar aggregate values, present iff the row stands for a whole group: the\n   * query declared no `items` aggregate, so one member represents its group and `objectId` is the\n   * serialized key rather than an object.\n   */\n  aggregates: string | null;\n  /** JSON heads of the backing the row ships, present iff the index copy is at the document's saved heads. */\n  heads: string | null;\n  /** JSON heads the index copy was read at: the row's version, whether or not it backs the row. */\n  versionHeads: string | null;\n  /** A feed item's block position: the row's version. */\n  queuePosition: number | null;\n  /**\n   * JSON array of the traversal edges that reached the row, one `{hop, from, to, kind, property, holder,\n   * holderHeads}` per edge; present iff the plan is a linear traversal chain.\n   */\n  edges: string | null;\n  /** JSON array of a collapsed group's members, each `{id, documentId, heads, position, contribution}`. */\n  manifest: string | null;\n};\n\n/** Edges one row may carry: past it the row's derivation is left unknown, as a fan-in hub would overflow it. */\nexport const MAX_EDGES_PER_ROW = 512;\n\n/**\n * Builds the plan of an `in-query` subquery. Injected rather than imported, because the planner\n * owns plan building and calls this compiler — importing it back would make the two modules cyclic.\n */\nexport type PlanSubquery = (query: QueryAST.Query) => QueryPlan.Plan;\n\nexport type CompiledQuery = {\n  statement: Statement.Statement<CompiledRow>;\n  /** The statement's SQL text with placeholders, for traces. */\n  sql: string;\n  /** The compiled plan: one `SqlStep` standing for every step the statement absorbed. */\n  plan: QueryPlan.Plan;\n};\n\n/**\n * A working set as one CTE. Every relation carries the same columns so steps compose:\n * `recordId`, `objectId`, `spaceId`, `rank`, `ord` (position), and after an `AggregateStep` also\n * `groupKey`, `groupOrd`, `groupCount` plus one `agg_<name>` column per scalar aggregate.\n */\ntype Relation = {\n  name: string;\n  grouped?: GroupedShape;\n};\n\ntype GroupedShape = {\n  /** Result field names of every non-`items` aggregate, orderable as group columns. */\n  aggregateNames: readonly string[];\n  /** One row per group, carrying its aggregates, because the query asked for no members. */\n  collapsed: boolean;\n  /**\n   * The keyed members of a collapsed group and each one's share of its scalar aggregates, over the `k`\n   * (member), `m` (meta) and `d` (body) aliases, from which the final projection lists the group's manifest.\n   */\n  manifest?: { keyed: Relation; contribution: Fragment };\n};\n\nconst HOUR_MS = 3_600_000;\nconst DAY_MS = 86_400_000;\nconst UNTYPED_INDEX_TYPE = 'type';\n\ntype Fragment = Statement.Fragment;\n\n/**\n * Compiles a {@link QueryPlan.Plan} into one SQLite statement over the index tables.\n *\n * The compiler is a single pass over the plan's steps; each step becomes a CTE over the previous\n * one, and the final `SELECT` projects the identity of each row. It holds no state beyond the\n * CTE counter and the parameter-free fragments it builds, so one instance compiles one plan.\n */\nexport class SqlPlanCompiler {\n  readonly #sql: SqlClient.SqlClient;\n  readonly #ctes: Fragment[] = [];\n  #counter = 0;\n  /** Distinct `in-query` subqueries already compiled this plan, keyed as the executor caches them. */\n  readonly #subqueries = new Map<string, string>();\n  /** Whether any select in the plan scopes a space with its feeds, which lets a traversal reach feed items. */\n  #includeAllFeeds = false;\n  readonly #planSubquery: PlanSubquery;\n  /** Depth of `#compilePlan` calls; 1 is the query's own chain, deeper is a union branch or a subquery. */\n  #nesting = 0;\n  /** The edge relation of each traversal on the query's own chain, by hop. */\n  readonly #hops: Relation[] = [];\n  /** Whether a traversal ran inside a union branch or subquery, whose derivations the chain cannot state. */\n  #nestedTraversal = false;\n  #feedCutoffs: ReadonlyMap<string, number> = new Map();\n\n  constructor(sql: SqlClient.SqlClient, planSubquery: PlanSubquery) {\n    this.#sql = sql;\n    this.#planSubquery = planSubquery;\n  }\n\n  compile(plan: QueryPlan.Plan, options: CompileOptions = {}): CompiledQuery {\n    const sql = this.#sql;\n    this.#feedCutoffs = options.feedCutoffs ?? new Map();\n    this.#includeAllFeeds = planIncludesAllFeeds(plan);\n    let root = this.#compilePlan(plan, undefined);\n    if (options.strongDependencyFilter !== false) {\n      root = this.#compileStrongDependencyFilter(root);\n    }\n    const final = this.#final(root);\n    const withClause = sql.join(', ', false)(this.#ctes);\n    const statement = sql<CompiledRow>`WITH RECURSIVE ${withClause} ${final}`;\n    const [text, params] = statement.compile();\n    return {\n      statement,\n      sql: text,\n      plan: QueryPlan.Plan.make([{ _tag: 'SqlStep', sql: text, params, steps: plan.steps }]),\n    };\n  }\n\n  #fresh(prefix: string): string {\n    return `${prefix}${this.#counter++}`;\n  }\n\n  #define(prefix: string, body: Fragment, grouped?: GroupedShape): Relation {\n    const name = this.#fresh(prefix);\n    this.#ctes.push(this.#sql`${this.#sql.literal(name)} AS (${body})`);\n    return { name, grouped };\n  }\n\n  #ref(relation: Relation): Fragment {\n    return this.#sql.literal(relation.name);\n  }\n\n  #compilePlan(plan: QueryPlan.Plan, input: Relation | undefined): Relation {\n    const sql = this.#sql;\n    this.#nesting++;\n    try {\n      let current: Relation =\n        input ??\n        this.#define(\n          'empty',\n          sql`SELECT NULL AS recordId, NULL AS objectId, NULL AS spaceId, 1.0 AS rank, 0 AS ord WHERE 0`,\n        );\n      for (const step of plan.steps) {\n        current = this.#compileStep(step, current);\n      }\n      return current;\n    } finally {\n      this.#nesting--;\n    }\n  }\n\n  #compileStep(step: QueryPlan.Step, ws: Relation): Relation {\n    switch (step._tag) {\n      case 'ClearWorkingSetStep':\n        return this.#define('empty', this.#sql`SELECT * FROM ${this.#ref(ws)} WHERE 0`, ws.grouped);\n      case 'SelectStep':\n        return this.#compileSelect(step, ws);\n      case 'FilterStep':\n        return this.#compileFilter(step, ws);\n      case 'FilterDeletedStep':\n        return this.#compileFilterDeleted(step, ws);\n      case 'TraverseStep':\n        return this.#compileTraverse(step, ws);\n      case 'UnionStep':\n        return this.#compileUnion(step, ws);\n      case 'SetDifferenceStep':\n        return this.#compileSetDifference(step, ws);\n      case 'OrderStep':\n        return this.#compileOrder(step, ws);\n      case 'LimitStep':\n        return this.#compileLimitSkip(ws, { limit: step.limit });\n      case 'SkipStep':\n        return this.#compileLimitSkip(ws, { skip: step.skip });\n      case 'AggregateStep':\n        return this.#compileAggregate(step, ws);\n      default:\n        throw new QueryError({ message: `Unknown step type: ${(step as { _tag: string })._tag}`, context: {} });\n    }\n  }\n\n  //\n  // Select.\n  //\n\n  #compileSelect(step: QueryPlan.SelectStep, ws: Relation): Relation {\n    const sql = this.#sql;\n    const spaceScopes = step.scope.filter((scope): scope is QueryAST.SpaceScope => scope._tag === 'space');\n    const spaces = spaceScopes.map((scope) => scope.spaceId as SpaceId);\n    const queues = step.scope.filter((scope): scope is QueryAST.FeedScope => scope._tag === 'feed');\n    const includeAllQueues = spaceScopes.some((scope) => scope.includeAllFeeds === true);\n    const queueRefs = withFeedCutoffs(extractQueueRefs(queues), this.#feedCutoffs);\n    const scope = buildSourceCondition(sql, spaces, includeAllQueues, queueRefs);\n    const window = buildQueueWindow(sql, extractQueueWindow(step));\n\n    let base: Fragment;\n    switch (step.selector._tag) {\n      case 'WildcardSelector':\n        base = sql`SELECT m.recordId, m.objectId, m.spaceId, 1.0 AS rank FROM objectMeta m WHERE ${scope}${window}`;\n        break;\n      case 'TypeSelector': {\n        if (step.selector.typename.length === 0) {\n          base = step.selector.inverted\n            ? sql`SELECT m.recordId, m.objectId, m.spaceId, 1.0 AS rank FROM objectMeta m WHERE ${scope}${window}`\n            : sql`SELECT m.recordId, m.objectId, m.spaceId, 1.0 AS rank FROM objectMeta m WHERE 0`;\n          break;\n        }\n        const typeCondition = buildTypeDxnCondition(sql, step.selector.typename);\n        // Pinned: over a space the planner otherwise seeks `(spaceId, queueId)` and scans the space's\n        // documents for the type. One feed is the exception: the type index would read that type in\n        // every feed of the space (a chat's messages among every chat's), where the feed seek reads\n        // only its rows, and one branch of one feed seeks that branch. An inverted select cannot seek\n        // the type index, so it is left free.\n        const singleQueue =\n          spaces.length === 0 && queueRefs?.length === 1 && queueRefs[0].spaceId !== undefined\n            ? queueRefs[0]\n            : undefined;\n        const index =\n          singleQueue === undefined\n            ? INDEX_SPACE_TYPE\n            : singleQueue.branches?.length === 1\n              ? INDEX_SPACE_QUEUE_BRANCH\n              : INDEX_SPACE_QUEUE_OBJECT;\n        base = step.selector.inverted\n          ? sql`SELECT m.recordId, m.objectId, m.spaceId, 1.0 AS rank FROM objectMeta m WHERE ${scope} AND NOT (${typeCondition})${window}`\n          : sql`SELECT m.recordId, m.objectId, m.spaceId, 1.0 AS rank FROM objectMeta m INDEXED BY ${sql.literal(index)} WHERE ${scope} AND (${typeCondition})${window}`;\n        break;\n      }\n      case 'IdSelector': {\n        const ids = step.selector.objectIds.filter((id) => EntityId.isValid(id));\n        base = sql`SELECT m.recordId, m.objectId, m.spaceId, 1.0 AS rank FROM objectMeta m WHERE ${scope} AND m.objectId IN (SELECT value FROM json_each(${JSON.stringify(ids)}))`;\n        break;\n      }\n      case 'TimestampSelector': {\n        const { updatedAfter, updatedBefore, createdAfter, createdBefore } = step.selector;\n        const conditions: Fragment[] = [scope];\n        if (updatedAfter != null) {\n          conditions.push(sql`m.updatedAt >= ${updatedAfter}`);\n        }\n        if (updatedBefore != null) {\n          conditions.push(sql`m.updatedAt <= ${updatedBefore}`);\n        }\n        if (createdAfter != null) {\n          conditions.push(sql`m.createdAt >= ${createdAfter}`);\n        }\n        if (createdBefore != null) {\n          conditions.push(sql`m.createdAt <= ${createdBefore}`);\n        }\n        base = sql`SELECT m.recordId, m.objectId, m.spaceId, 1.0 AS rank FROM objectMeta m WHERE ${sql.and(conditions)}`;\n        break;\n      }\n      case 'IncomingReferenceSelector': {\n        const target = referenceIndexKey(step.selector.targetDXN);\n        if (target === undefined) {\n          base = sql`SELECT m.recordId, m.objectId, m.spaceId, 1.0 AS rank FROM objectMeta m WHERE 0`;\n          break;\n        }\n        const pathCondition = this.#propPathCondition(step.selector.property);\n        // The index is not scoped by space; the select's scope narrows the referrers, as the\n        // executor filtered them after the lookup.\n        const spaceCondition =\n          spaces.length > 0 ? sql`m.spaceId IN (SELECT value FROM json_each(${JSON.stringify(spaces)}))` : sql`1 = 1`;\n        base = sql`SELECT DISTINCT m.recordId, m.objectId, m.spaceId, 1.0 AS rank FROM reverseRef r JOIN objectMeta m ON m.recordId = r.recordId WHERE r.targetDXN = ${target} AND ${pathCondition} AND ${spaceCondition}`;\n        break;\n      }\n      case 'TextSelector': {\n        if (step.selector.searchKind === 'vector') {\n          base = sql`SELECT m.recordId, m.objectId, m.spaceId, 1.0 AS rank FROM objectMeta m WHERE 0`;\n          break;\n        }\n        const fts = buildFtsCondition(sql, step.selector.text);\n        if (fts === undefined) {\n          base = sql`SELECT m.recordId, m.objectId, m.spaceId, 1.0 AS rank FROM objectMeta m WHERE 0`;\n          break;\n        }\n        const conditions: Fragment[] = [fts.condition, scope];\n        if (step.selector.typename !== null) {\n          conditions.push(\n            step.selector.typename.length > 0 ? sql`(${buildTypeDxnCondition(sql, step.selector.typename)})` : sql`0`,\n          );\n        }\n        // Both branches read `ftsIndex`, as `FtsIndex.query` does: the index stores the extracted\n        // text, so a term below the trigram minimum scans that column rather than another store.\n        const rank = fts.ranked ? sql`-bm25(ftsIndex)` : sql`1.0`;\n        base = sql`SELECT m.recordId, m.objectId, m.spaceId, ${rank} AS rank FROM ftsIndex f JOIN objectMeta m ON m.recordId = f.rowid WHERE ${sql.and(conditions)}`;\n        break;\n      }\n      default:\n        throw new QueryError({\n          message: `Unknown selector type: ${(step.selector as { _tag: string })._tag}`,\n          context: {},\n        });\n    }\n\n    // A select appends to the incoming working set. Every plan orders after its last set changer\n    // (`QueryPlanner._ensureOrderStep`), so the scan's own order only matters when the planner\n    // pushed a limit into this step: then the first rows in natural order (rank for a text search,\n    // id otherwise) are the ones kept, and numbering them costs a sort of the candidates.\n    const selected = this.#define('sel', base);\n    const orderNew = step.selector._tag === 'TextSelector' ? sql`s.rank DESC, s.objectId` : sql`s.objectId`;\n    const ord =\n      step.limit !== undefined ? sql`${UNION_BRANCH_STRIDE} + ROW_NUMBER() OVER (ORDER BY ${orderNew})` : sql`0`;\n    const appended = sql`\n      SELECT recordId, objectId, spaceId, rank, ord FROM ${this.#ref(ws)}\n      UNION ALL\n      SELECT s.recordId, s.objectId, s.spaceId, s.rank, ${ord} AS ord\n      FROM ${this.#ref(selected)} s`;\n    const union = this.#define('ws', appended);\n    if (step.limit === undefined) {\n      return union;\n    }\n    return this.#define('ws', sql`SELECT * FROM ${this.#ref(union)} ORDER BY ord LIMIT ${step.limit}`);\n  }\n\n  /** Reverse-reference rows at a property, matching the executor's index-vs-query path rule. */\n  #propPathCondition(property: string | null): Fragment {\n    const sql = this.#sql;\n    if (property === null) {\n      return sql`1 = 1`;\n    }\n    const normalized = EscapedPropPath.escape(normalizePropPath(EscapedPropPath.unescape(property)));\n    return sql`(r.propPathNormalized = ${normalized} OR r.propPath = ${property})`;\n  }\n\n  //\n  // Filter.\n  //\n\n  #compileFilter(step: QueryPlan.FilterStep, ws: Relation): Relation {\n    const sql = this.#sql;\n    if (step.filter.type === 'child-of') {\n      return this.#compileChildOf(step.filter, ws);\n    }\n    const predicate = this.#compileRootPredicate(step.filter);\n    return this.#define(\n      'ws',\n      sql`SELECT w.* FROM ${this.#ref(ws)} w JOIN objectMeta m NOT INDEXED ON m.recordId = w.recordId JOIN objectSnapshot d ON d.recordId = w.recordId WHERE ${predicate}`,\n      ws.grouped,\n    );\n  }\n\n  /**\n   * A filter at the root of a `FilterStep`, evaluated against the row `m`/`d`. Mirrors\n   * `makeFilterMatcher`: `object` checks type, id, props and meta; the rest are boolean\n   * composition or local predicates.\n   */\n  #compileRootPredicate(filter: QueryAST.Filter): Fragment {\n    const sql = this.#sql;\n    switch (filter.type) {\n      case 'object': {\n        const conditions: Fragment[] = [];\n        if (filter.typename !== null) {\n          conditions.push(sql`(${this.#typenameCondition(filter.typename)})`);\n        }\n        if (filter.id && filter.id.length > 0) {\n          conditions.push(sql`m.objectId IN (SELECT value FROM json_each(${JSON.stringify(filter.id)}))`);\n        }\n        for (const [key, valueFilter] of Object.entries(filter.props)) {\n          // `@`-prefixed keys address annotations, never data.\n          if (key.startsWith('@')) {\n            continue;\n          }\n          conditions.push(this.#compileValuePredicate(valueFilter, [key]));\n        }\n        if (filter.foreignKeys && filter.foreignKeys.length > 0) {\n          conditions.push(sql`EXISTS (\n            SELECT 1 FROM json_each(d.snapshot, ${jsonPathLiteral(sql, [ATTR_META, 'keys'])}) k, json_each(${JSON.stringify(filter.foreignKeys)}) f\n            WHERE json_extract(k.value, '$.source') = json_extract(f.value, '$.source') AND json_extract(k.value, '$.id') = json_extract(f.value, '$.id'))`);\n        }\n        if (filter.metaKey !== undefined) {\n          const keyPath = jsonPathLiteral(sql, [ATTR_META, 'key']);\n          conditions.push(sql`json_extract(d.snapshot, ${keyPath}) = ${filter.metaKey}`);\n          if (filter.metaVersion !== undefined) {\n            // Resolving a semver range needs the versions present in the store, so `planDeclinedByCompiler`\n            // sends these plans to the in-memory executor before compilation starts.\n            throw new QueryError({\n              message: 'metaVersion filter is not compilable',\n              context: { key: filter.metaKey },\n            });\n          }\n        }\n        return conditions.length === 0 ? sql`1 = 1` : sql`(${sql.and(conditions)})`;\n      }\n      case 'tag': {\n        const tagsPath = jsonPathLiteral(sql, [ATTR_META, 'tags']);\n        const target = canonicalTag(filter.tag);\n        // A tag is an encoded reference or (legacy) a bare URI; both sides compare by entity id.\n        return sql`EXISTS (SELECT 1 FROM json_each(d.snapshot, ${tagsPath}) t\n          WHERE ${localIdOfUri(sql, tagUriOf(sql, sql`t`))} = ${target})`;\n      }\n      case 'annotation': {\n        // Keys are matched with `json_each` rather than a JSON path, which cannot address every key\n        // (e.g. a legacy id containing `\"`); a NULL column or absent key is a definite non-match, so\n        // `not` keeps entities that never carried the annotation.\n        const annotations = sql`json_each(COALESCE(m.annotations, '{}'))`;\n        return filter.value === undefined\n          ? sql`EXISTS (SELECT 1 FROM ${annotations} a WHERE a.key = ${filter.key})`\n          : sql`EXISTS (SELECT 1 FROM ${annotations} a WHERE a.key = ${filter.key} AND ${scalarEquals(sql, sql`a.value`, sql`a.type`, filter.value)})`;\n      }\n      case 'text-search':\n        // The executors behind an index resolve text search in the select; a residual node\n        // matches nothing, as the in-memory matcher's `noTextSearch` does.\n        return sql`0`;\n      case 'timestamp':\n        return this.#timestampCondition(filter);\n      case 'has-parent':\n        return filter.value ? sql`m.parent IS NOT NULL` : sql`m.parent IS NULL`;\n      case 'mnemonic':\n        return sql`upper(substr(m.objectId, -${EntityId.mnemonicLength})) = ${EntityId.normalizeMnemonic(filter.mnemonic)}`;\n      case 'not':\n        return sql`NOT (${this.#compileRootPredicate(filter.filter)})`;\n      case 'and':\n        return filter.filters.length === 0\n          ? sql`1 = 1`\n          : sql`(${sql.and(filter.filters.map((inner) => this.#compileRootPredicate(inner)))})`;\n      case 'or':\n        return filter.filters.length === 0\n          ? sql`0`\n          : sql`(${sql.or(filter.filters.map((inner) => this.#compileRootPredicate(inner)))})`;\n      case 'child-of':\n        throw new QueryError({ message: 'child-of must be the root of its filter step', context: {} });\n      case 'in-query':\n        throw new QueryError({ message: 'in-query is valid only inside an object filter', context: {} });\n      case 'feed-cursor':\n        throw new QueryError({ message: 'feed-cursor filters are lifted onto the select step', context: {} });\n      default:\n        // Property-level predicates at the root are rejected by the planner; matching nothing\n        // mirrors `makeFilterMatcher`'s default arm.\n        return sql`0`;\n    }\n  }\n\n  #timestampCondition(filter: QueryAST.FilterTimestamp): Fragment {\n    const sql = this.#sql;\n    const column = filter.field === 'updatedAt' ? sql`m.updatedAt` : sql`m.createdAt`;\n    // The index treats both bounds as inclusive, whichever operator the filter carries.\n    return filter.operator === 'gt' || filter.operator === 'gte'\n      ? sql`${column} >= ${filter.value}`\n      : sql`${column} <= ${filter.value}`;\n  }\n\n  /** `compareTypenameStrings` over the stored `typeDXN`: exact when versioned, every version otherwise. */\n  #typenameCondition(typename: string): Fragment {\n    const sql = this.#sql;\n    const forms: string[] = [typename];\n    const dxn = DXN.tryMake(typename);\n    if (dxn && DXN.getVersion(dxn) !== undefined) {\n      // A stored versionless type matches any expected version.\n      forms.push(DXN.make<string>(DXN.getName(dxn)));\n    }\n    return sql.or(forms.map((form) => sql`(${buildTypeDxnCondition(sql, [form])})`));\n  }\n\n  /**\n   * A predicate on one property value, mirroring `filterMatchValue`. Comparisons are typed: a\n   * value matches a string operand only when it is a string, a number operand only when a number.\n   */\n  #compileValuePredicate(filter: QueryAST.Filter, path: readonly string[]): Fragment {\n    const sql = this.#sql;\n    const at = jsonPathLiteral(sql, path);\n    const value = sql`json_extract(d.snapshot, ${at})`;\n    // Coalesced so a missing property yields a definite `false`, never SQL's NULL: `NOT` over a\n    // NULL is NULL, which would drop rows the matcher's `!==` keeps.\n    const type = sql`COALESCE(json_type(d.snapshot, ${at}), 'missing')`;\n    switch (filter.type) {\n      case 'compare': {\n        const operand = filter.value;\n        switch (filter.operator) {\n          case 'eq':\n            return this.#equalsOperand(path, operand);\n          case 'neq':\n            return sql`NOT ${this.#equalsOperand(path, operand)}`;\n          case 'gt':\n          case 'gte':\n          case 'lt':\n          case 'lte': {\n            const op = { gt: '>', gte: '>=', lt: '<', lte: '<=' }[filter.operator];\n            if (typeof operand === 'number') {\n              return sql`(${type} IN ('integer', 'real') AND ${value} ${sql.literal(op)} ${operand})`;\n            }\n            if (typeof operand === 'string') {\n              return sql`(${type} = 'text' AND ${value} ${sql.literal(op)} ${operand})`;\n            }\n            return sql`0`;\n          }\n          default:\n            return sql`0`;\n        }\n      }\n      case 'object': {\n        const nested: Fragment[] = [sql`${type} = 'object'`];\n        for (const [key, valueFilter] of Object.entries(filter.props ?? {})) {\n          nested.push(this.#compileValuePredicate(valueFilter, [...path, key]));\n        }\n        return sql`(${sql.and(nested)})`;\n      }\n      case 'in': {\n        const values = filter.values.map(normalizeInValue);\n        const strings = values.filter((candidate): candidate is string => typeof candidate === 'string');\n        const numbers = values.filter((candidate): candidate is number => typeof candidate === 'number');\n        const booleans = values.filter((candidate): candidate is boolean => typeof candidate === 'boolean');\n        const branches: Fragment[] = [];\n        const refOrValue = sql`COALESCE(json_extract(d.snapshot, ${jsonPathLiteral(sql, [...path, '/'])}), ${value})`;\n        if (strings.length > 0) {\n          branches.push(\n            sql`(${type} IN ('text', 'object') AND ${refOrValue} IN (SELECT value FROM json_each(${JSON.stringify(strings)})))`,\n          );\n        }\n        if (numbers.length > 0) {\n          branches.push(\n            sql`(${type} IN ('integer', 'real') AND ${value} IN (SELECT value FROM json_each(${JSON.stringify(numbers)})))`,\n          );\n        }\n        if (booleans.includes(true)) {\n          branches.push(sql`${type} = 'true'`);\n        }\n        if (booleans.includes(false)) {\n          branches.push(sql`${type} = 'false'`);\n        }\n        if (values.includes(null)) {\n          branches.push(sql`${type} = 'null'`);\n        }\n        return branches.length === 0 ? sql`0` : sql`(${sql.or(branches)})`;\n      }\n      case 'in-query': {\n        const subquery = this.#compileInQuery(filter);\n        const refOrValue = sql`COALESCE(json_extract(d.snapshot, ${jsonPathLiteral(sql, [...path, '/'])}), ${value})`;\n        return sql`COALESCE(${refOrValue} IN (SELECT v FROM ${sql.literal(subquery)}), 0)`;\n      }\n      case 'contains': {\n        const element = filter.value;\n        if (typeof element === 'object' && element !== null && !Array.isArray(element)) {\n          return sql`(${type} = 'array' AND EXISTS (SELECT 1 FROM json_each(d.snapshot, ${at}) e WHERE ${structuralMatch(sql, sql`e.value`, element)}))`;\n        }\n        return sql`(${type} = 'array' AND EXISTS (SELECT 1 FROM json_each(d.snapshot, ${at}) e WHERE ${scalarEquals(sql, sql`e.value`, sql`e.type`, element)}))`;\n      }\n      case 'range': {\n        if (typeof filter.from === 'number' && typeof filter.to === 'number') {\n          return sql`(${type} IN ('integer', 'real') AND ${value} >= ${filter.from} AND ${value} <= ${filter.to})`;\n        }\n        if (typeof filter.from === 'string' && typeof filter.to === 'string') {\n          return sql`(${type} = 'text' AND ${value} >= ${filter.from} AND ${value} <= ${filter.to})`;\n        }\n        return sql`0`;\n      }\n      case 'not':\n        return sql`NOT ${this.#compileValuePredicate(filter.filter, path)}`;\n      case 'and':\n        return filter.filters.length === 0\n          ? sql`1 = 1`\n          : sql`(${sql.and(filter.filters.map((inner) => this.#compileValuePredicate(inner, path)))})`;\n      case 'or':\n        return filter.filters.length === 0\n          ? sql`0`\n          : sql`(${sql.or(filter.filters.map((inner) => this.#compileValuePredicate(inner, path)))})`;\n      default:\n        return sql`0`;\n    }\n  }\n\n  /** Strict equality of a property against an operand, `undefined` meaning \"absent\". */\n  #equalsOperand(path: readonly string[], operand: unknown): Fragment {\n    const sql = this.#sql;\n    const at = jsonPathLiteral(sql, path);\n    const value = sql`json_extract(d.snapshot, ${at})`;\n    const type = sql`COALESCE(json_type(d.snapshot, ${at}), 'missing')`;\n    if (operand === undefined) {\n      return sql`(${type} = 'missing')`;\n    }\n    if (isEncodedReference(operand)) {\n      return sql`(COALESCE(json_extract(d.snapshot, ${jsonPathLiteral(sql, [...path, '/'])}) = ${EncodedReference.toURI(operand)}, 0))`;\n    }\n    return scalarEquals(sql, value, type, operand);\n  }\n\n  /** Compiles the subquery of an `in-query` node once and returns the CTE holding its projection. */\n  #compileInQuery(filter: QueryAST.FilterInQuery): string {\n    const sql = this.#sql;\n    const key = `${JSON.stringify(filter.subquery)}\\0${filter.property}`;\n    const existing = this.#subqueries.get(key);\n    if (existing !== undefined) {\n      return existing;\n    }\n    const subPlan = this.#planSubquery(filter.subquery);\n    const result = this.#compilePlan(subPlan, undefined);\n    const at = jsonPathLiteral(sql, [filter.property]);\n    const refAt = jsonPathLiteral(sql, [filter.property, '/']);\n    // Missing and null projected values never broaden the membership set.\n    const projection = this.#define(\n      'sub',\n      sql`SELECT COALESCE(json_extract(d.snapshot, ${refAt}), json_extract(d.snapshot, ${at})) AS v FROM ${this.#ref(result)} w JOIN objectSnapshot d ON d.recordId = w.recordId WHERE json_type(d.snapshot, ${at}) IS NOT NULL AND json_type(d.snapshot, ${at}) != 'null'`,\n    );\n    this.#subqueries.set(key, projection.name);\n    return projection.name;\n  }\n\n  //\n  // Deleted, child-of, strong deps: recursive walks over the dependency columns.\n  //\n\n  #compileFilterDeleted(step: QueryPlan.FilterDeletedStep, ws: Relation): Relation {\n    const sql = this.#sql;\n    const wsRef = this.#ref(ws);\n    // Dependencies whose deletion cascades: the parent chain, plus a relation's endpoints. Each\n    // row's direct dependencies are the walk's seeds; rows share them (a collection's items, one\n    // parent), so the chain is walked once per distinct seed, not once per row.\n    const seedId = sql`CASE f.k WHEN 0 THEN m.parentId WHEN 1 THEN m.sourceId ELSE m.targetId END`;\n    const seeds = this.#define(\n      'seed',\n      // `CAST` gives the column TEXT affinity, without which the probes below cannot seek on it.\n      sql`SELECT DISTINCT m.spaceId, CAST(${seedId} AS TEXT) AS seedId\n        FROM ${wsRef} w CROSS JOIN objectMeta m NOT INDEXED ON m.recordId = w.recordId CROSS JOIN ${fanOut(sql, 3)} f\n        WHERE (f.k = 0 OR m.entityKind = 'relation') AND ${seedId} IS NOT NULL`,\n    );\n    // Each seed's chain to the executor's depth; the seed itself sits at depth 1.\n    const chain = this.#define(\n      'chain',\n      sql`\n      SELECT spaceId, seedId, seedId AS depId, 1 AS depth FROM ${this.#ref(seeds)}\n      UNION\n      SELECT x.spaceId, x.seedId, p.parentId, x.depth + 1\n        FROM ${sql.literal(this.#peekName('chain'))} x JOIN ${docRow(sql, 'p')} ON p.spaceId = x.spaceId AND p.queueId = '' AND p.objectId = x.depId\n        WHERE x.depth < ${MAX_DEPTH_FOR_DELETION_TRACING} AND p.deleted = 0 AND p.parentId IS NOT NULL`,\n    );\n    // `CROSS JOIN` keeps the chain outer: the planner otherwise scans every document row and probes the chain.\n    const deadSeeds = this.#define(\n      'dead',\n      sql`SELECT DISTINCT x.spaceId, x.seedId FROM ${this.#ref(chain)} x\n        CROSS JOIN ${docRow(sql, 'p')} ON p.spaceId = x.spaceId AND p.queueId = '' AND p.objectId = x.depId\n        WHERE p.deleted = 1`,\n    );\n    // One probe per column: an `OR` inside one `EXISTS` cannot seek the dead seeds.\n    const dead = (column: Fragment) =>\n      sql`EXISTS (SELECT 1 FROM ${this.#ref(deadSeeds)} s WHERE s.spaceId = m.spaceId AND s.seedId = ${column})`;\n    const isDeleted = sql`(m.deleted = 1 OR ${dead(sql`m.parentId`)}\n      OR (m.entityKind = 'relation' AND (${dead(sql`m.sourceId`)} OR ${dead(sql`m.targetId`)})))`;\n    const condition = step.mode === 'only-deleted' ? isDeleted : sql`NOT ${isDeleted}`;\n    return this.#define(\n      'ws',\n      sql`SELECT w.* FROM ${wsRef} w JOIN objectMeta m NOT INDEXED ON m.recordId = w.recordId WHERE ${condition}`,\n      ws.grouped,\n    );\n  }\n\n  /** The name the next `#define` with this prefix will receive, for a recursive CTE's self-reference. */\n  #peekName(prefix: string): string {\n    return `${prefix}${this.#counter}`;\n  }\n\n  #compileChildOf(filter: QueryAST.FilterChildOf, ws: Relation): Relation {\n    const sql = this.#sql;\n    const parentIds: string[] = [];\n    for (const parent of filter.parents) {\n      const eid = EID.tryParse(parent);\n      const objectId = eid ? EID.getEntityId(eid) : undefined;\n      if (objectId) {\n        parentIds.push(objectId);\n      }\n    }\n    const maxDepth = filter.transitive ? MAX_DEPTH_FOR_CHILD_OF_TRACING : 1;\n    const wsRef = this.#ref(ws);\n    // Walked down from the parents, so the cost follows the subtree rather than the working set: the\n    // owners a row's direct owner must be among are the parents and their documents `maxDepth - 1` levels down.\n    const owners = this.#define(\n      'own',\n      sql`\n      SELECT s.spaceId, p.value AS ownerId, 1 AS depth\n        FROM (SELECT DISTINCT spaceId FROM ${wsRef}) s CROSS JOIN json_each(${JSON.stringify(parentIds)}) p\n      UNION ALL\n      SELECT o.spaceId, c.objectId, o.depth + 1\n        FROM ${sql.literal(this.#peekName('own'))} o\n        JOIN objectMeta c INDEXED BY ${sql.literal(INDEX_SPACE_PARENT)} ON c.spaceId = o.spaceId AND c.parentId = o.ownerId\n        WHERE o.depth < ${maxDepth} AND c.queueId = ''`,\n    );\n    // A feed item's owner is its feed when it carries no parent of its own.\n    return this.#define(\n      'ws',\n      sql`SELECT w.* FROM ${wsRef} w JOIN objectMeta m NOT INDEXED ON m.recordId = w.recordId\n        WHERE EXISTS (\n          SELECT 1 FROM ${this.#ref(owners)} o WHERE o.spaceId = m.spaceId\n            AND o.ownerId = COALESCE(m.parentId, CASE WHEN m.parent IS NULL AND m.queueId != '' THEN m.queueId END))`,\n      ws.grouped,\n    );\n  }\n\n  /**\n   * Drops document rows whose strong dependencies (schema object, relation endpoints, parent, tags) are\n   * absent from the space's indexed documents, transitively, so they never reach a client that\n   * could not hydrate them. Cross-space dependencies are not gated, as `ObjectCore` does not gate them.\n   */\n  #compileStrongDependencyFilter(ws: Relation): Relation {\n    const sql = this.#sql;\n    const wsRef = this.#ref(ws);\n    // One row's direct strong dependencies: its schema object, parent and a relation's endpoints\n    // (one per `f.k`), and the tags in its snapshot's meta.\n    const columnDep = (row: string) => {\n      const table = sql.literal(row);\n      return sql`CASE f.k WHEN 0 THEN ${localIdOfLocalUri(sql, sql`${table}.typeDXN`)} WHEN 1 THEN ${table}.parentId\n        WHEN 2 THEN CASE WHEN ${table}.entityKind = 'relation' THEN ${table}.sourceId END\n        ELSE CASE WHEN ${table}.entityKind = 'relation' THEN ${table}.targetId END END`;\n    };\n    const tagsPath = jsonPathLiteral(sql, [ATTR_META, 'tags']);\n    const tagId = localIdOfLocalUri(sql, tagUriOf(sql, sql`t`));\n    // Materialized: read once for the distinct seeds and once for the rows they condemn.\n    const seedsName = this.#fresh('sseed');\n    this.#ctes.push(\n      sql`${sql.literal(seedsName)} AS MATERIALIZED (\n        SELECT w.recordId, m.spaceId, CAST(${columnDep('m')} AS TEXT) AS depId\n          FROM ${wsRef} w CROSS JOIN objectMeta m NOT INDEXED ON m.recordId = w.recordId CROSS JOIN ${fanOut(sql, 4)} f\n          WHERE m.queueId = '' AND ${columnDep('m')} IS NOT NULL\n        UNION ALL\n        SELECT w.recordId, m.spaceId, ${tagId}\n          FROM ${wsRef} w JOIN objectMeta m NOT INDEXED ON m.recordId = w.recordId JOIN objectSnapshot d ON d.recordId = w.recordId, json_each(d.snapshot, ${tagsPath}) t\n          WHERE m.queueId = '' AND ${tagId} IS NOT NULL)`,\n    );\n    const seeds = sql.literal(seedsName);\n    // A dependency's verdict does not depend on the row that reached it, so each distinct seed's\n    // closure is walked once, to the executor's depth; the seed itself sits at depth 1. Each\n    // level seeks the dependency row once and fans out to its own dependencies.\n    const closure = this.#peekName('sclosure');\n    this.#define(\n      'sclosure',\n      sql`\n      SELECT DISTINCT spaceId, depId AS seedId, depId, 1 AS depth FROM ${seeds}\n      UNION\n      SELECT x.spaceId, x.seedId, ${columnDep('p')}, x.depth + 1\n        FROM ${sql.literal(closure)} x JOIN ${docRow(sql, 'p')} ON p.spaceId = x.spaceId AND p.queueId = '' AND p.objectId = x.depId\n        CROSS JOIN ${fanOut(sql, 4)} f\n        WHERE x.depth < ${MAX_DEPTH_FOR_STRONG_DEP_TRACING} AND ${columnDep('p')} IS NOT NULL\n      UNION\n      SELECT x.spaceId, x.seedId, ${tagId}, x.depth + 1\n        FROM ${sql.literal(closure)} x JOIN ${docRow(sql, 'p')} ON p.spaceId = x.spaceId AND p.queueId = '' AND p.objectId = x.depId\n        JOIN objectSnapshot pd ON pd.recordId = p.recordId, json_each(pd.snapshot, ${tagsPath}) t\n        WHERE x.depth < ${MAX_DEPTH_FOR_STRONG_DEP_TRACING} AND ${tagId} IS NOT NULL`,\n    );\n    const brokenSeeds = this.#define(\n      'bseed',\n      sql`SELECT DISTINCT x.spaceId, x.seedId FROM ${sql.literal(closure)} x\n        WHERE NOT EXISTS (SELECT 1 FROM ${docRow(sql, 'p')} WHERE p.spaceId = x.spaceId AND p.queueId = '' AND p.objectId = x.depId)`,\n    );\n    const broken = this.#define(\n      'broken',\n      sql`SELECT s.recordId FROM ${seeds} s JOIN ${this.#ref(brokenSeeds)} b ON b.spaceId = s.spaceId AND b.seedId = s.depId`,\n    );\n    return this.#define(\n      'ws',\n      sql`SELECT w.* FROM ${wsRef} w WHERE w.recordId NOT IN (SELECT recordId FROM ${this.#ref(broken)})`,\n      ws.grouped,\n    );\n  }\n\n  //\n  // Traversal.\n  //\n\n  #compileTraverse(step: QueryPlan.TraverseStep, ws: Relation): Relation {\n    const sql = this.#sql;\n    const edges = this.#compileTraverseEdges(step, ws);\n    if (this.#nesting === 1) {\n      this.#hops.push(edges);\n    } else {\n      this.#nestedTraversal = true;\n    }\n    // One row per object reached, at the best rank and first position of the anchors reaching it.\n    return this.#define(\n      'ws',\n      sql`SELECT recordId, objectId, spaceId, MIN(rank) AS rank, MIN(ord) AS ord FROM ${this.#ref(edges)} GROUP BY recordId`,\n    );\n  }\n\n  /**\n   * Every edge a traversal crosses, one row per (anchor, object reached, way it was reached): the reached\n   * object's identity, the anchor's rank and position, and the edge's kind, property and holder (the object\n   * whose document records it), which the final projection ships as the row's derivations.\n   */\n  #compileTraverseEdges(step: QueryPlan.TraverseStep, ws: Relation): Relation {\n    const sql = this.#sql;\n    const wsRef = this.#ref(ws);\n    const project = (kind: string, property: Fragment, holder: Fragment) =>\n      sql`SELECT w.recordId AS fromRecordId, w.objectId AS fromObjectId, t.recordId, t.objectId, t.spaceId, w.rank, w.ord,\n        ${kind} AS kind, ${property} AS property, ${holder}.recordId AS holderRecordId, ${holder}.objectId AS holderObjectId`;\n    switch (step.traversal._tag) {\n      case 'ReferenceTraversal': {\n        if (step.traversal.direction === 'outgoing') {\n          if (step.traversal.property === null) {\n            throw new QueryError({ message: 'Outgoing reference traversal requires a property', context: {} });\n          }\n          const path = EscapedPropPath.unescape(step.traversal.property);\n          const at = jsonPathLiteral(sql, path);\n          // The property holds one reference or an array of them; either way each is `{\"/\": uri}`.\n          const refs = sql`json_each(CASE json_type(d.snapshot, ${at}) WHEN 'array' THEN json_extract(d.snapshot, ${at}) ELSE json_array(json_extract(d.snapshot, ${at})) END)`;\n          const uri = sql`json_extract(ref.value, '$.\"/\"')`;\n          // A target in a feed is reachable only when the plan scopes the space with its feeds.\n          const target = this.#includeAllFeeds\n            ? sql`objectMeta t INDEXED BY ${sql.literal(INDEX_SPACE_OBJECT)}`\n            : docRow(sql, 't');\n          const targetKind = this.#includeAllFeeds ? sql`1 = 1` : sql`t.queueId = ''`;\n          return this.#define(\n            'edges',\n            sql`${project('ref', sql`${step.traversal.property}`, sql`w`)} FROM ${wsRef} w\n              JOIN objectMeta m NOT INDEXED ON m.recordId = w.recordId\n              JOIN objectSnapshot d ON d.recordId = w.recordId\n              JOIN ${refs} ref\n              JOIN ${target} ON t.spaceId = COALESCE(${spaceIdOfUri(sql, uri)}, m.spaceId) AND t.objectId = ${localIdOfUri(sql, uri)} AND ${targetKind}\n              WHERE ${uri} LIKE 'echo:%'`,\n          );\n        }\n        // Incoming: the reverse index keys targets by their local form; the property narrows the\n        // referrer's path.\n        const pathCondition = this.#propPathCondition(step.traversal.property);\n        return this.#define(\n          'edges',\n          sql`${project('incoming-ref', sql`r.propPath`, sql`t`)} FROM ${wsRef} w\n            JOIN reverseRef r ON r.targetDXN = 'echo:///' || w.objectId\n            JOIN objectMeta t ON t.recordId = r.recordId\n            WHERE ${pathCondition}`,\n        );\n      }\n      case 'RelationTraversal': {\n        switch (step.traversal.direction) {\n          case 'relation-to-source':\n          case 'relation-to-target': {\n            const toSource = step.traversal.direction === 'relation-to-source';\n            const column = toSource ? sql`m.source` : sql`m.target`;\n            return this.#define(\n              'edges',\n              sql`${project(toSource ? 'relation-source' : 'relation-target', sql`NULL`, sql`w`)} FROM ${wsRef} w\n                JOIN objectMeta m NOT INDEXED ON m.recordId = w.recordId\n                JOIN ${docRow(sql, 't')} ON t.spaceId = COALESCE(${spaceIdOfUri(sql, column)}, m.spaceId) AND t.objectId = ${localIdOfUri(sql, column)} AND t.queueId = ''\n                WHERE ${column} IS NOT NULL`,\n            );\n          }\n          case 'source-to-relation':\n          case 'target-to-relation': {\n            const bySource = step.traversal.direction === 'source-to-relation';\n            const column = bySource ? sql`t.sourceId` : sql`t.targetId`;\n            const index = sql.literal(bySource ? INDEX_SPACE_SOURCE : INDEX_SPACE_TARGET);\n            return this.#define(\n              'edges',\n              sql`${project(bySource ? 'relation-source' : 'relation-target', sql`NULL`, sql`t`)} FROM ${wsRef} w\n                JOIN objectMeta t INDEXED BY ${index} ON t.spaceId = w.spaceId AND ${column} = w.objectId AND t.entityKind = 'relation'`,\n            );\n          }\n        }\n        break;\n      }\n      case 'HierarchyTraversal': {\n        if (step.traversal.direction === 'to-parent') {\n          return this.#define(\n            'edges',\n            sql`${project('parent', sql`NULL`, sql`w`)} FROM ${wsRef} w\n              JOIN objectMeta m NOT INDEXED ON m.recordId = w.recordId\n              JOIN ${docRow(sql, 't')} ON t.spaceId = COALESCE(${spaceIdOfUri(sql, sql`m.parent`)}, m.spaceId) AND t.objectId = ${localIdOfUri(sql, sql`m.parent`)} AND t.queueId = ''\n              WHERE m.queueId = '' AND m.parent IS NOT NULL`,\n          );\n        }\n        // Children by parent, and a feed's items by queue id (a feed's queue id is its object id).\n        // Two seeks rather than one `OR`, which SQLite answers by scanning the space.\n        return this.#define(\n          'edges',\n          sql`${project('child', sql`NULL`, sql`t`)} FROM ${wsRef} w\n              JOIN objectMeta t INDEXED BY ${sql.literal(INDEX_SPACE_PARENT)} ON t.spaceId = w.spaceId AND t.parentId = w.objectId\n            UNION ALL\n            ${project('child', sql`NULL`, sql`t`)} FROM ${wsRef} w\n              JOIN objectMeta t INDEXED BY ${sql.literal(INDEX_SPACE_QUEUE_OBJECT)} ON t.spaceId = w.spaceId AND t.queueId = w.objectId`,\n        );\n      }\n    }\n    throw new QueryError({\n      message: `Unknown traversal type: ${(step.traversal as { _tag: string })._tag}`,\n      context: {},\n    });\n  }\n\n  //\n  // Set operations.\n  //\n\n  #compileUnion(step: QueryPlan.UnionStep, ws: Relation): Relation {\n    const sql = this.#sql;\n    const branches = step.plans.map((plan, index) => {\n      const result = this.#compilePlan(plan, ws);\n      return sql`SELECT recordId, objectId, spaceId, rank, ${index * UNION_BRANCH_STRIDE} + ord AS ord FROM ${this.#ref(result)}`;\n    });\n    // First occurrence keeps its position, the last occurrence its rank, as the executor's\n    // insertion into a `Map` keyed by (space, document, object) did.\n    const all = this.#define('all', sql.join(' UNION ALL ', false)(branches));\n    return this.#define(\n      'ws',\n      sql`SELECT recordId, objectId, spaceId, MAX(rank) AS rank, MIN(ord) AS ord FROM ${this.#ref(all)} GROUP BY recordId`,\n    );\n  }\n\n  #compileSetDifference(step: QueryPlan.SetDifferenceStep, ws: Relation): Relation {\n    const sql = this.#sql;\n    const source = this.#compilePlan(step.source, ws);\n    const exclude = this.#compilePlan(step.exclude, ws);\n    return this.#define(\n      'ws',\n      sql`SELECT s.* FROM ${this.#ref(source)} s WHERE s.objectId NOT IN (SELECT objectId FROM ${this.#ref(exclude)})`,\n    );\n  }\n\n  //\n  // Order, limit, skip, aggregate.\n  //\n\n  #compileOrder(step: QueryPlan.OrderStep, ws: Relation): Relation {\n    const sql = this.#sql;\n    const wsRef = this.#ref(ws);\n    const terms = step.order.map((order) => this.#orderTerm(order, ws.grouped));\n    const orderBy = terms.length > 0 ? sql.csv(terms) : sql`w.ord`;\n    if (ws.grouped) {\n      // Groups reorder as wholes by their first member; members keep their order within the group.\n      const regrouped = this.#define(\n        'grp',\n        sql`SELECT w.*, DENSE_RANK() OVER (ORDER BY ${orderBy}, w.groupOrd) AS newGroupOrd\n          FROM ${wsRef} w JOIN objectMeta m NOT INDEXED ON m.recordId = w.recordId JOIN objectSnapshot d ON d.recordId = w.recordId\n          WHERE w.ord = (SELECT MIN(ord) FROM ${wsRef} f WHERE f.groupKey = w.groupKey)`,\n      );\n      const reordered = this.#define(\n        'ws',\n        sql`SELECT ${this.#groupedColumns(ws.grouped, sql`w`, sql`g.newGroupOrd`)}\n          FROM ${wsRef} w JOIN ${this.#ref(regrouped)} g ON g.groupKey = w.groupKey`,\n        ws.grouped,\n      );\n      const withOrd = this.#define(\n        'ws',\n        sql`SELECT ${this.#groupedColumns(ws.grouped, sql`w`, sql`w.groupOrd`, sql`ROW_NUMBER() OVER (ORDER BY w.groupOrd, w.ord)`)} FROM ${this.#ref(reordered)} w`,\n        ws.grouped,\n      );\n      return step.limit === undefined ? withOrd : this.#compileLimitSkip(withOrd, { limit: step.limit });\n    }\n    const ordered = this.#define(\n      'ws',\n      sql`SELECT w.recordId, w.objectId, w.spaceId, w.rank, ROW_NUMBER() OVER (ORDER BY ${orderBy}) AS ord\n        FROM ${wsRef} w JOIN objectMeta m NOT INDEXED ON m.recordId = w.recordId JOIN objectSnapshot d ON d.recordId = w.recordId`,\n    );\n    return step.limit === undefined ? ordered : this.#compileLimitSkip(ordered, { limit: step.limit });\n  }\n\n  /** One `ORDER BY` term over the joined row `w`/`m`/`d`, with nulls last as the executor sorts. */\n  #orderTerm(order: QueryAST.Order, grouped: GroupedShape | undefined): Fragment {\n    const sql = this.#sql;\n    const direction = order.direction === 'desc' ? sql`DESC` : sql`ASC`;\n    switch (order.kind) {\n      case 'natural':\n        return sql`w.objectId ${direction}`;\n      case 'rank':\n        return sql`w.rank ${direction}`;\n      case 'timestamp': {\n        const column = order.field === 'updatedAt' ? sql`m.updatedAt` : sql`m.createdAt`;\n        return sql`COALESCE(${column}, 0) ${direction}`;\n      }\n      case 'property': {\n        if (grouped && grouped.aggregateNames.includes(order.property)) {\n          return sql`${sql.literal(aggregateColumn(order.property))} ${direction} NULLS LAST`;\n        }\n        const at = jsonPathLiteral(sql, [order.property]);\n        // Only scalars order; anything else sorts with the nulls, last.\n        return sql`CASE WHEN json_type(d.snapshot, ${at}) IN ('text', 'integer', 'real', 'true', 'false') THEN json_extract(d.snapshot, ${at}) END ${direction} NULLS LAST`;\n      }\n      case 'annotation': {\n        // The key and each path segment are matched with `json_each`, as the annotation filter does,\n        // since a JSON path cannot address every key; a non-object level yields no row, so NULL.\n        const objectOrEmpty = (level: string) =>\n          sql`json_each(CASE WHEN ${sql.literal(level)}.type = 'object' THEN ${sql.literal(level)}.value ELSE '{}' END)`;\n        const path = order.path ?? [];\n        const joins = path.map(\n          (segment, index) =>\n            sql`JOIN ${objectOrEmpty(index === 0 ? 'a' : `p${index - 1}`)} ${sql.literal(`p${index}`)} ON ${sql.literal(`p${index}`)}.key = ${segment}`,\n        );\n        const leaf = sql.literal(path.length === 0 ? 'a' : `p${path.length - 1}`);\n        // Only scalars order; anything else sorts with the nulls, last.\n        return sql`(SELECT CASE WHEN ${leaf}.type IN ('text', 'integer', 'real', 'true', 'false') THEN ${leaf}.value END\n          FROM json_each(COALESCE(m.annotations, '{}')) a ${sql.join(' ', false)(joins)}\n          WHERE a.key = ${order.key}) ${direction} NULLS LAST`;\n      }\n      default:\n        return sql`w.ord`;\n    }\n  }\n\n  #compileLimitSkip(ws: Relation, { limit, skip }: { limit?: number; skip?: number }): Relation {\n    const sql = this.#sql;\n    const wsRef = this.#ref(ws);\n    if (ws.grouped) {\n      // Group-level paging: whole groups by their ordinal.\n      const conditions: Fragment[] = [];\n      if (skip !== undefined) {\n        conditions.push(sql`w.groupOrd > ${skip}`);\n      }\n      if (limit !== undefined) {\n        conditions.push(sql`w.groupOrd <= ${(skip ?? 0) + limit}`);\n      }\n      const paged = this.#define('ws', sql`SELECT w.* FROM ${wsRef} w WHERE ${sql.and(conditions)}`, ws.grouped);\n      return skip === undefined\n        ? paged\n        : this.#define(\n            'ws',\n            sql`SELECT ${this.#groupedColumns(ws.grouped, sql`w`, sql`w.groupOrd - ${skip}`)} FROM ${this.#ref(paged)} w`,\n            ws.grouped,\n          );\n    }\n    const limitClause = limit !== undefined ? sql`LIMIT ${limit}` : sql`LIMIT -1`;\n    const offsetClause = skip !== undefined ? sql`OFFSET ${skip}` : sql``;\n    return this.#define(\n      'ws',\n      sql`SELECT w.recordId, w.objectId, w.spaceId, w.rank, ROW_NUMBER() OVER (ORDER BY w.ord) AS ord\n        FROM (SELECT * FROM ${wsRef} ORDER BY ord ${limitClause} ${offsetClause}) w`,\n    );\n  }\n\n  #compileAggregate(step: QueryPlan.AggregateStep, ws: Relation): Relation {\n    const sql = this.#sql;\n    const wsRef = this.#ref(ws);\n    const groups = step.aggregates.filter(QueryAST.isGroupKeyAggregate);\n    const scalarAggregates = step.aggregates.filter((aggregate) => aggregate.kind !== 'items');\n    const collapsed = !step.aggregates.some((aggregate) => aggregate.kind === 'items');\n    const itemsOrders = step.aggregates.flatMap((aggregate) =>\n      aggregate.kind === 'items' && aggregate.order?.length ? [aggregate.order] : [],\n    );\n    if (new Set(itemsOrders.map((order) => JSON.stringify(order))).size > 1) {\n      throw new QueryError({\n        message: 'Multiple `items` aggregates with different `order`s are not supported.',\n        context: {},\n      });\n    }\n    const itemsOrder = itemsOrders[0];\n\n    // Group key: one coerced scalar per key entry; a `group` entry falls through its property chain.\n    const keyColumns = groups.map(\n      (group) => sql`${this.#keyComponent(group)} AS ${sql.literal(keyColumn(group.name))}`,\n    );\n    const keyJson =\n      groups.length === 0\n        ? sql`'{}'`\n        : sql`json_object(${sql.join(', ', false)(groups.map((group) => sql`${group.name}, ${this.#jsonKeyComponent(group)}`))})`;\n    const keyed = this.#define(\n      'keyed',\n      sql`SELECT w.*, ${keyJson} AS groupKey${keyColumns.length > 0 ? sql`, ${sql.csv(keyColumns)}` : sql``}\n        FROM ${wsRef} w JOIN objectMeta m NOT INDEXED ON m.recordId = w.recordId JOIN objectSnapshot d ON d.recordId = w.recordId`,\n    );\n\n    const aggregateColumns = scalarAggregates.map((aggregate) => {\n      const name = sql.literal(aggregateColumn(aggregate.name));\n      switch (aggregate.kind) {\n        case 'group':\n        case 'type':\n        case 'timestamp':\n        case 'time':\n          return sql`k.${sql.literal(keyColumn(aggregate.name))} AS ${name}`;\n        case 'sum':\n          return sql`TOTAL(${this.#numericProperty(aggregate.property)}) OVER (PARTITION BY k.groupKey) AS ${name}`;\n        case 'count':\n          return sql`COUNT(*) OVER (PARTITION BY k.groupKey) AS ${name}`;\n        case 'max':\n          return sql`MAX(${this.#coercedProperty(aggregate.property, sql`k`)}) OVER (PARTITION BY k.groupKey) AS ${name}`;\n        case 'min':\n          return sql`MIN(${this.#coercedProperty(aggregate.property, sql`k`)}) OVER (PARTITION BY k.groupKey) AS ${name}`;\n        default:\n          throw new QueryError({ message: 'Unknown aggregate kind', context: {} });\n      }\n    });\n    const stamped = this.#define(\n      'agg',\n      sql`SELECT k.recordId, k.objectId, k.spaceId, k.rank, k.ord, k.groupKey,\n        MIN(k.ord) OVER (PARTITION BY k.groupKey) AS firstOrd,\n        COUNT(*) OVER (PARTITION BY k.groupKey) AS groupCount${aggregateColumns.length > 0 ? sql`, ${sql.csv(aggregateColumns)}` : sql``}\n        FROM ${this.#ref(keyed)} k JOIN objectMeta m NOT INDEXED ON m.recordId = k.recordId JOIN objectSnapshot d ON d.recordId = k.recordId`,\n    );\n    const shape: GroupedShape = {\n      aggregateNames: scalarAggregates.map((aggregate) => aggregate.name),\n      collapsed,\n      manifest: collapsed ? this.#manifestShape(keyed, scalarAggregates) : undefined,\n    };\n    // Groups take the order of their first member; members keep their order, or the `items`\n    // aggregate's own order when it declares one. A collapsed set keeps only the first member,\n    // which already carries the group's key, count and aggregates.\n    const memberOrder = itemsOrder ? sql.csv(itemsOrder.map((order) => this.#orderTerm(order, undefined))) : sql`w.ord`;\n    const members = collapsed ? sql`WHERE w.ord = w.firstOrd` : sql``;\n    return this.#define(\n      'ws',\n      sql`SELECT ${this.#groupedColumns(shape, sql`w`, sql`DENSE_RANK() OVER (ORDER BY w.firstOrd)`, sql`ROW_NUMBER() OVER (ORDER BY w.firstOrd, ${memberOrder})`)}\n        FROM ${this.#ref(stamped)} w JOIN objectMeta m NOT INDEXED ON m.recordId = w.recordId JOIN objectSnapshot d ON d.recordId = w.recordId ${members}`,\n      shape,\n    );\n  }\n\n  /**\n   * Each member's share of the count, sum, min and max aggregates, as the client subtracts it when it holds\n   * the member; undefined when the query asks for none.\n   */\n  #manifestShape(keyed: Relation, aggregates: readonly QueryAST.GroupAggregate[]): GroupedShape['manifest'] {\n    const sql = this.#sql;\n    const shares = aggregates.flatMap((aggregate) => {\n      switch (aggregate.kind) {\n        case 'count':\n          return [sql`${aggregate.name}, 1`];\n        case 'sum':\n          return [sql`${aggregate.name}, ${this.#numericProperty(aggregate.property)}`];\n        case 'min':\n        case 'max':\n          return [sql`${aggregate.name}, ${this.#coercedProperty(aggregate.property, sql`k`)}`];\n        default:\n          return [];\n      }\n    });\n    return shares.length > 0 ? { keyed, contribution: sql`json_object(${sql.join(', ', false)(shares)})` } : undefined;\n  }\n\n  /** A group key component in the scalar domain, from the joined `m` (meta) and `d` (body) rows. */\n  #keyComponent(aggregate: QueryAST.GroupAggregate): Fragment {\n    const sql = this.#sql;\n    switch (aggregate.kind) {\n      case 'group': {\n        const coerced = aggregate.properties.map((property) => this.#coercedProperty(property));\n        // `COALESCE` needs two arguments; a single-property chain is the property itself.\n        return coerced.length === 1 ? coerced[0] : sql`COALESCE(${sql.join(', ', false)(coerced)})`;\n      }\n      case 'type':\n        return sql`CASE WHEN m.typeDXN = ${UNTYPED_INDEX_TYPE} THEN NULL ELSE m.typeDXN END`;\n      case 'timestamp':\n        return this.#truncatedTimestamp(aggregate);\n      case 'time':\n        return this.#truncatedProperty(aggregate);\n      default:\n        throw new QueryError({ message: 'Not a group key aggregate', context: { kind: aggregate.kind } });\n    }\n  }\n\n  #truncatedTimestamp(aggregate: QueryAST.GroupAggregate & { kind: 'timestamp' }): Fragment {\n    const sql = this.#sql;\n    const column = aggregate.field === 'updatedAt' ? sql`m.updatedAt` : sql`m.createdAt`;\n    return this.#floorTo(column, aggregate.unit === 'hour' ? HOUR_MS : DAY_MS);\n  }\n\n  /** The grouped working-set columns, with `groupOrd` (and optionally `ord`) replaced. */\n  #groupedColumns(shape: GroupedShape, row: Fragment, groupOrd: Fragment, ord?: Fragment): Fragment {\n    const sql = this.#sql;\n    const columns: Fragment[] = [\n      sql`${row}.recordId`,\n      sql`${row}.objectId`,\n      sql`${row}.spaceId`,\n      sql`${row}.rank`,\n      ord ? sql`${ord} AS ord` : sql`${row}.ord`,\n      sql`${row}.groupKey`,\n      sql`${groupOrd} AS groupOrd`,\n      sql`${row}.groupCount`,\n      ...shape.aggregateNames.map((name) => sql`${row}.${sql.literal(aggregateColumn(name))}`),\n    ];\n    return sql.csv(columns);\n  }\n\n  #truncatedProperty(aggregate: QueryAST.GroupAggregate & { kind: 'time' }): Fragment {\n    return this.#floorTo(this.#numericProperty(aggregate.property), aggregate.unit === 'hour' ? HOUR_MS : DAY_MS);\n  }\n\n  #floorTo(value: Fragment, size: number): Fragment {\n    const sql = this.#sql;\n    // `CAST` truncates toward zero; stepping back one below a negative fraction makes it a floor.\n    const floored = sql`(CAST(${value} AS INTEGER) - (${value} < CAST(${value} AS INTEGER)))`;\n    return sql`(${floored} - ((${floored} % ${size}) + ${size}) % ${size})`;\n  }\n\n  #numericProperty(property: string): Fragment {\n    const sql = this.#sql;\n    if (property === 'id') {\n      return sql`NULL`;\n    }\n    const at = jsonPathLiteral(sql, [property]);\n    return sql`CASE WHEN json_type(d.snapshot, ${at}) IN ('integer', 'real') THEN json_extract(d.snapshot, ${at}) END`;\n  }\n\n  /** A property coerced to the scalar domain (`null` for anything else); `id` is the entity id. */\n  #coercedProperty(property: string, row: Fragment = this.#sql`m`): Fragment {\n    const sql = this.#sql;\n    if (property === 'id') {\n      return sql`${row}.objectId`;\n    }\n    const at = jsonPathLiteral(sql, [property]);\n    return sql`CASE WHEN json_type(d.snapshot, ${at}) IN ('text', 'integer', 'real', 'true', 'false') THEN json_extract(d.snapshot, ${at}) END`;\n  }\n\n  /** The group key component as JSON, so booleans serialize as `true`/`false` like `JSON.stringify`. */\n  #jsonKeyComponent(group: QueryAST.GroupAggregate): Fragment {\n    const sql = this.#sql;\n    if (group.kind !== 'group') {\n      return this.#keyComponent(group);\n    }\n    const branches = group.properties.map((property) => {\n      if (property === 'id') {\n        return sql`WHEN m.objectId IS NOT NULL THEN m.objectId`;\n      }\n      const at = jsonPathLiteral(sql, [property]);\n      return sql`WHEN json_type(d.snapshot, ${at}) IN ('true', 'false') THEN json(json_type(d.snapshot, ${at})) WHEN json_type(d.snapshot, ${at}) IN ('text', 'integer', 'real') THEN json_extract(d.snapshot, ${at})`;\n    });\n    return sql`CASE ${sql.join(' ', false)(branches)} ELSE NULL END`;\n  }\n\n  //\n  // Final projection.\n  //\n\n  #final(ws: Relation): Fragment {\n    const sql = this.#sql;\n    const aggregates =\n      ws.grouped?.collapsed && ws.grouped.aggregateNames.length > 0\n        ? sql`json_object(${sql.join(', ', false)(ws.grouped.aggregateNames.map((name) => sql`${name}, w.${sql.literal(aggregateColumn(name))}`))})`\n        : ws.grouped?.collapsed\n          ? sql`'{}'`\n          : sql`NULL`;\n    const groupColumns = ws.grouped\n      ? sql`w.groupKey AS groupKey, w.groupCount AS groupCount, ${aggregates} AS aggregates`\n      : sql`NULL AS groupKey, NULL AS groupCount, NULL AS aggregates`;\n    // Grouped once over the members, not per final row, so a set of many groups costs one pass.\n    const manifests = ws.grouped?.manifest\n      ? this.#define(\n          'manifests',\n          sql`SELECT k.groupKey, json_group_array(json_object('id', k.objectId, 'documentId', m.documentId, 'heads', json(COALESCE(d.version, d.heads)), 'position', m.queuePosition, 'contribution', ${ws.grouped.manifest.contribution})) AS manifest\n            FROM ${this.#ref(ws.grouped.manifest.keyed)} k JOIN objectMeta m NOT INDEXED ON m.recordId = k.recordId JOIN objectSnapshot d ON d.recordId = k.recordId\n            GROUP BY k.groupKey`,\n        )\n      : undefined;\n    const rowEdges = this.#rowEdges(ws);\n    return sql`SELECT w.recordId, w.objectId, w.spaceId, m.documentId, m.queueId, m.queueNamespace, w.rank AS rank,\n      m.createdAt, m.updatedAt, d.heads AS heads, COALESCE(d.version, d.heads) AS versionHeads, m.queuePosition AS queuePosition,\n      CASE WHEN m.queueId != '' THEN d.snapshot END AS documentJson,\n      ${groupColumns}, ${rowEdges ? sql`re.edges` : sql`NULL`} AS edges, ${manifests ? sql`mf.manifest` : sql`NULL`} AS manifest\n      FROM ${this.#ref(ws)} w JOIN objectMeta m NOT INDEXED ON m.recordId = w.recordId LEFT JOIN objectSnapshot d ON d.recordId = w.recordId\n      ${rowEdges ? sql`LEFT JOIN ${this.#ref(rowEdges)} re ON re.root = w.recordId` : sql``}\n      ${manifests ? sql`LEFT JOIN ${this.#ref(manifests)} mf ON mf.groupKey = w.groupKey` : sql``}\n      ORDER BY w.ord`;\n  }\n\n  /**\n   * The edges that derive each final row of a linear traversal chain, as one JSON array per row: a recursive walk\n   * back from the row through each hop's edges into the objects that reached it, grouped in one pass. A row past\n   * {@link MAX_EDGES_PER_ROW} edges gets JSON `null`, which the executor reads as an unknown derivation.\n   */\n  #rowEdges(ws: Relation): Relation | undefined {\n    const sql = this.#sql;\n    if (this.#hops.length === 0 || this.#nestedTraversal || ws.grouped) {\n      return undefined;\n    }\n    // Materialized: inlined, every recursive step and the final join recompute each hop's edges.\n    const allName = this.#fresh('alledges');\n    this.#ctes.push(\n      sql`${sql.literal(allName)} AS MATERIALIZED (${sql.join(\n        ' UNION ALL ',\n        false,\n      )(this.#hops.map((hop, index) => sql`SELECT ${index + 1} AS hop, e.* FROM ${this.#ref(hop)} e`))})`,\n    );\n    const all: Relation = { name: allName };\n    // `CROSS JOIN` below keeps `reach` outer: probing it instead keys on `hop` alone (its `recordId` has no\n    // affinity), which matches every edge of a hop, so each row would scan them all.\n    const reach = this.#fresh('reach');\n    this.#ctes.push(\n      sql`${sql.literal(reach)}(root, hop, recordId) AS (\n        SELECT recordId, ${this.#hops.length}, recordId FROM ${this.#ref(ws)}\n        UNION\n        SELECT r.root, r.hop - 1, e.fromRecordId FROM ${sql.literal(reach)} r JOIN ${this.#ref(all)} e ON e.hop = r.hop AND e.recordId = r.recordId WHERE r.hop > 1\n      )`,\n    );\n    return this.#define(\n      'rowedges',\n      sql`SELECT r.root, CASE WHEN COUNT(*) > ${MAX_EDGES_PER_ROW} THEN 'null' ELSE json_group_array(json_object('hop', e.hop, 'from', e.fromObjectId, 'to', e.objectId, 'kind', e.kind, 'property', e.property,\n          'holder', e.holderObjectId, 'holderHeads', json(COALESCE(hd.version, hd.heads)))) END AS edges\n        FROM ${sql.literal(reach)} r CROSS JOIN ${this.#ref(all)} e ON e.hop = r.hop AND e.recordId = r.recordId\n        LEFT JOIN objectSnapshot hd ON hd.recordId = e.holderRecordId\n        GROUP BY r.root`,\n    );\n  }\n}\n\nexport type CompileOptions = {\n  /**\n   * Drop document rows whose strong dependencies are absent from the index (default true); the\n   * executor mirrors the client-side gate so dependency-broken objects never reach it.\n   */\n  strongDependencyFilter?: boolean;\n  /** Per feed (keyed `<spaceId>/<feedId>`), the time (unix ms) before which its rows have expired. */\n  feedCutoffs?: ReadonlyMap<string, number>;\n};\n\n/**\n * Compiles a plan, first resolving every `metaVersion` filter to the literal versions present\n * under its key: semver ranges are not expressible in SQL, and the distinct versions under one\n * registry key are few.\n */\nexport const compilePlan = (\n  sql: SqlClient.SqlClient,\n  plan: QueryPlan.Plan,\n  planSubquery: PlanSubquery,\n  options: CompileOptions = {},\n): CompiledQuery => new SqlPlanCompiler(sql, planSubquery).compile(plan, options);\n\n//\n// Helpers.\n//\n\nconst metaVersionKey = (key: string, range: string): string => `${key}\\0${range}`;\n\n/** True when any select step, sub-plans included, scopes a space with `includeAllFeeds`. */\nconst planIncludesAllFeeds = (plan: QueryPlan.Plan): boolean =>\n  plan.steps.some((step) => {\n    switch (step._tag) {\n      case 'SelectStep':\n        return step.scope.some((scope) => scope._tag === 'space' && scope.includeAllFeeds === true);\n      case 'UnionStep':\n        return step.plans.some(planIncludesAllFeeds);\n      case 'SetDifferenceStep':\n        return planIncludesAllFeeds(step.source) || planIncludesAllFeeds(step.exclude);\n      default:\n        return false;\n    }\n  });\n\nexport const planDeclinedByCompiler = (plan: QueryPlan.Plan, planSubquery: PlanSubquery): boolean =>\n  planSelectsChanges(plan) ||\n  planReadsObjectMeta(plan, planSubquery) ||\n  collectMetaVersionFilters(plan, planSubquery).length > 0;\n\nconst planSelectsChanges = (plan: QueryPlan.Plan): boolean =>\n  plan.steps.some((step) => step._tag === 'SelectStep' && step.selector._tag === 'ChangesSelector');\n\nconst planReadsObjectMeta = (plan: QueryPlan.Plan, planSubquery: PlanSubquery): boolean => {\n  const readsMeta = (filter: QueryAST.Filter): boolean => {\n    if (filter.type === 'object') {\n      if (filter.foreignKeys !== undefined || filter.metaKey !== undefined) {\n        return true;\n      }\n      if (Object.values(filter.props ?? {}).some(readsMeta)) {\n        return true;\n      }\n    }\n    if (filter.type === 'tag') {\n      return true;\n    }\n    if (filter.type === 'and' || filter.type === 'or') {\n      return filter.filters.some(readsMeta);\n    }\n    if (filter.type === 'not') {\n      return readsMeta(filter.filter);\n    }\n    if (filter.type === 'in-query') {\n      // The subquery carries no scope of its own, so it cannot be planned here; walk its AST.\n      let found = false;\n      QueryAST.visit(filter.subquery, (node) => {\n        if ((node.type === 'select' || node.type === 'filter') && readsMeta(node.filter)) {\n          found = true;\n        }\n      });\n      return found;\n    }\n    return false;\n  };\n  return plan.steps.some((step) => {\n    switch (step._tag) {\n      case 'FilterStep':\n        return readsMeta(step.filter);\n      case 'UnionStep':\n        return step.plans.some((nested) => planReadsObjectMeta(nested, planSubquery));\n      case 'SetDifferenceStep':\n        return planReadsObjectMeta(step.source, planSubquery) || planReadsObjectMeta(step.exclude, planSubquery);\n      default:\n        return false;\n    }\n  });\n};\n\n/** Every `(metaKey, metaVersion)` pair in the plan, sub-plans and subqueries included. */\nconst collectMetaVersionFilters = (\n  plan: QueryPlan.Plan,\n  planSubquery: PlanSubquery,\n): [key: string, range: string][] => {\n  const found: [string, string][] = [];\n  const visitFilter = (filter: QueryAST.Filter): void => {\n    switch (filter.type) {\n      case 'object':\n        if (filter.metaKey !== undefined && filter.metaVersion !== undefined) {\n          found.push([filter.metaKey, filter.metaVersion]);\n        }\n        for (const nested of Object.values(filter.props)) {\n          visitFilter(nested);\n        }\n        break;\n      case 'in-query':\n        visitPlan(planSubquery(filter.subquery));\n        break;\n      case 'not':\n        visitFilter(filter.filter);\n        break;\n      case 'and':\n      case 'or':\n        filter.filters.forEach(visitFilter);\n        break;\n      default:\n        break;\n    }\n  };\n  const visitPlan = (visited: QueryPlan.Plan): void => {\n    for (const step of visited.steps) {\n      switch (step._tag) {\n        case 'FilterStep':\n          visitFilter(step.filter);\n          break;\n        case 'UnionStep':\n          step.plans.forEach(visitPlan);\n          break;\n        case 'SetDifferenceStep':\n          visitPlan(step.source);\n          visitPlan(step.exclude);\n          break;\n        default:\n          break;\n      }\n    }\n  };\n  visitPlan(plan);\n  return found;\n};\n\n/**\n * A JSON path literal for SQLite's JSON functions, every key quoted so a dot or bracket in a key\n * cannot change the path. Emitted as a literal, not a parameter, so an expression index on the\n * same spelling can serve the predicate.\n */\nconst jsonPathLiteral = (sql: SqlClient.SqlClient, path: readonly string[]): Fragment => {\n  const escaped = path.map((key) => `.\"${key.replaceAll('\\\\', '\\\\\\\\').replaceAll('\"', '\\\\\"')}\"`).join('');\n  return sql.literal(`'$${escaped.replaceAll(\"'\", \"''\")}'`);\n};\n\nconst keyColumn = (name: string): string => `key_${columnSuffix(name)}`;\nconst aggregateColumn = (name: string): string => `agg_${columnSuffix(name)}`;\n\n/**\n * A result field name as a column identifier. Names come from the query author and only have to be\n * unique within the statement, so one that is already identifier-safe is kept for readability and\n * anything else is hex-encoded; the distinct prefixes keep the two classes from colliding. Encoding\n * rather than rejecting is what keeps `aggregate({ 'last-at': … })` working on both executors.\n */\nconst columnSuffix = (name: string): string =>\n  /^[A-Za-z0-9_]+$/.test(name)\n    ? `s_${name}`\n    : `u_${name\n        .split('')\n        .map((unit) => unit.charCodeAt(0).toString(16).padStart(4, '0'))\n        .join('')}`;\n\n/** `filterMatchValue`'s `in` normalization: a reference compares by its URI. */\nconst normalizeInValue = (value: unknown): unknown =>\n  isEncodedReference(value) ? EncodedReference.toURI(value) : value;\n\n/** `matchesTag`'s canonical form: the entity id of an `echo:` URI, the URI itself otherwise. */\nconst canonicalTag = (tag: string): string => {\n  const eid = EID.tryParse(tag);\n  return (eid && EID.getEntityId(eid)) || tag;\n};\n\n/**\n * Strict equality of a JSON value (`value`/`type` are `json_extract`/`json_type` over it) with a\n * literal, typed as JS `===` is: a number never equals a string, `true` never equals `1`.\n */\nconst scalarEquals = (sql: SqlClient.SqlClient, value: Fragment, type: Fragment, operand: unknown): Fragment => {\n  if (operand === null) {\n    return sql`(${type} = 'null')`;\n  }\n  if (typeof operand === 'boolean') {\n    return sql`(${type} = ${operand ? 'true' : 'false'})`;\n  }\n  if (typeof operand === 'number') {\n    return sql`(${type} IN ('integer', 'real') AND ${value} = ${operand})`;\n  }\n  if (typeof operand === 'string') {\n    return sql`(${type} = 'text' AND ${value} = ${operand})`;\n  }\n  return sql`0`;\n};\n\n/**\n * `structuralMatch` with `strict` on: the element has exactly the operand's keys, each equal.\n * Nested objects recurse; arrays and other non-scalars never match, as in the matcher.\n */\nconst structuralMatch = (sql: SqlClient.SqlClient, element: Fragment, operand: Record<string, unknown>): Fragment => {\n  const keys = Object.keys(operand);\n  const conditions: Fragment[] = [\n    sql`json_type(${element}) = 'object'`,\n    sql`(SELECT count(*) FROM json_each(${element})) = ${keys.length}`,\n  ];\n  for (const key of keys) {\n    const at = jsonPathLiteral(sql, [key]);\n    const nested = operand[key];\n    if (typeof nested === 'object' && nested !== null && !Array.isArray(nested)) {\n      conditions.push(structuralMatch(sql, sql`json_extract(${element}, ${at})`, nested as Record<string, unknown>));\n    } else {\n      conditions.push(\n        scalarEquals(\n          sql,\n          sql`json_extract(${element}, ${at})`,\n          sql`COALESCE(json_type(${element}, ${at}), 'missing')`,\n          nested,\n        ),\n      );\n    }\n  }\n  return sql`(${sql.and(conditions)})`;\n};\n\n/** `k` = 0..count-1, joined to a row to emit one output per dependency column after a single seek. */\nconst fanOut = (sql: SqlClient.SqlClient, count: number): Fragment =>\n  sql`(${sql.literal(Array.from({ length: count }, (_, index) => `SELECT ${index} AS k`).join(' UNION ALL '))})`;\n\n/** `objectMeta` aliased for a document-row point lookup by (space, queue, object), with the index pinned. */\nconst docRow = (sql: SqlClient.SqlClient, alias: string): Fragment =>\n  sql`objectMeta ${sql.literal(alias)} INDEXED BY ${sql.literal(INDEX_SPACE_QUEUE_OBJECT)}`;\n\n/**\n * The URI of one `json_each` element of `meta.tags`: an encoded reference, or (legacy) a bare URI, whose\n * text `json_extract` would reject as malformed JSON — so the element's type picks the read.\n */\nconst tagUriOf = (sql: SqlClient.SqlClient, element: Fragment): Fragment =>\n  sql`CASE ${element}.type WHEN 'object' THEN json_extract(${element}.value, '$.\"/\"') WHEN 'text' THEN ${element}.value END`;\n\n/** The entity id of an `echo:` URI (the text after its last slash), `NULL` for any other text. */\nconst localIdOfUri = (sql: SqlClient.SqlClient, uri: Fragment): Fragment =>\n  sql`CASE WHEN ${uri} LIKE 'echo:%' THEN substr(${uri}, length(rtrim(${uri}, replace(${uri}, '/', ''))) + 1) ELSE ${uri} END`;\n\n/** The entity id of a space-less `echo:` URI (canonical `echo:///<id>` or legacy `echo:/<id>`), else `NULL`. */\nconst localIdOfLocalUri = (sql: SqlClient.SqlClient, uri: Fragment): Fragment =>\n  sql`CASE WHEN ${uri} LIKE 'echo:///%' THEN substr(${uri}, 9) WHEN ${uri} LIKE 'echo:/%' AND ${uri} NOT LIKE 'echo://%' THEN substr(${uri}, 7) END`;\n\n/** The space id of a space-qualified `echo://<space>/<id>` URI, `NULL` for a local one. */\nconst spaceIdOfUri = (sql: SqlClient.SqlClient, uri: Fragment): Fragment =>\n  sql`CASE WHEN ${uri} LIKE 'echo://%' AND ${uri} NOT LIKE 'echo:///%' AND instr(substr(${uri}, 8), '/') > 0 THEN substr(${uri}, 8, instr(substr(${uri}, 8), '/') - 1) END`;\n\n/**\n * The queues a feed scope names, each carrying the space its URI qualifies it with, so the index\n * seek cannot cross spaces, and the branches it is restricted to. An unqualified URI matches on its\n * id alone.\n */\nconst extractQueueRefs = (queues: readonly QueryAST.FeedScope[]): QueueRef[] | null => {\n  if (queues.length === 0) {\n    return null;\n  }\n  const refs: QueueRef[] = [];\n  for (const scope of queues) {\n    const eid = EID.tryParse(String(scope.feedUri));\n    const queueId = eid ? EID.getEntityId(eid) : undefined;\n    if (!eid || !queueId) {\n      continue;\n    }\n    const spaceId = EID.getSpaceId(eid);\n    refs.push({\n      queueId,\n      ...(spaceId !== undefined ? { spaceId } : {}),\n      ...queueBranchesOf(scope.branches),\n    });\n  }\n  return refs;\n};\n\n/**\n * Bounds each space-qualified queue by its feed's retention cutoff, so the read (and the page limit\n * after it) never counts an expired row. An unqualified queue names no space whose options apply.\n */\nexport const withFeedCutoffs = (refs: QueueRef[] | null, feedCutoffs: ReadonlyMap<string, number>): QueueRef[] | null =>\n  refs?.map((ref) => {\n    const updatedSince = ref.spaceId !== undefined ? feedCutoffs.get(`${ref.spaceId}/${ref.queueId}`) : undefined;\n    return updatedSince !== undefined ? { ...ref, updatedSince } : ref;\n  }) ?? null;\n\n/** Bound below every assigned position, which start at 0. */\nconst BEFORE_FIRST_POSITION = -1;\n\n/**\n * The index-level window for a select the storage layer can bound itself: a cursor range resumes\n * by position, a `feedScan` reads a capped page in natural order. Mirrors the executor's rule,\n * including treating a non-numeric cursor as unsatisfiable rather than absent.\n */\nconst extractQueueWindow = (step: QueryPlan.SelectStep): QueueWindow | undefined => {\n  const range = step.feedCursorRange;\n  if (range === undefined) {\n    if (step.feedScan === undefined || step.limit === undefined) {\n      return undefined;\n    }\n    return {\n      kind: 'natural',\n      direction: step.feedScan.direction,\n      limit: step.limit,\n      ...(step.feedScan.skip !== undefined ? { skip: step.feedScan.skip } : {}),\n      ...(step.feedScan.deleted !== undefined ? { deleted: step.feedScan.deleted } : {}),\n    };\n  }\n  if (!step.scope.every((scope) => scope._tag === 'feed')) {\n    throw new QueryError({ message: 'A feed cursor filter can only be used with a feed scope.', context: {} });\n  }\n  return {\n    kind: 'cursor',\n    after: range.begin ? parseCursor(range.begin, Number.MAX_SAFE_INTEGER) : BEFORE_FIRST_POSITION,\n    ...(range.end ? { before: parseCursor(range.end, BEFORE_FIRST_POSITION) } : {}),\n    ...(step.limit !== undefined ? { limit: step.limit } : {}),\n  };\n};\n\nconst parseCursor = (cursor: string, unsatisfiable: number): number => {\n  const position = /^\\d+$/.test(cursor) ? Number(cursor) : Number.NaN;\n  return Number.isSafeInteger(position) ? position : unsatisfiable;\n};\n","//\n// Copyright 2025 DXOS.org\n//\n\nimport * as A from '@automerge/automerge';\nimport {\n  type DocumentId,\n  interpretAsDocumentId,\n  isValidAutomergeUrl,\n  isValidDocumentId,\n} from '@automerge/automerge-repo';\nimport * as Effect from 'effect/Effect';\nimport * as SqlClient from 'effect/sql/SqlClient';\n\nimport { ContextDisposedError, LifecycleState, Resource } from '@dxos/context';\nimport { type Obj, Query } from '@dxos/echo';\nimport {\n  BACKED_OBJECT_LIMIT,\n  DatabaseDirectory,\n  EchoFeedCodec,\n  EncodedReference,\n  type EntityPropPath,\n  EntityStructure,\n  EscapedPropPath,\n  PROPERTY_ID,\n  QueryAST,\n  backingJson,\n  isEncodedReference,\n} from '@dxos/echo-protocol';\nimport {\n  ATTR_DELETED,\n  ATTR_META,\n  ATTR_PARENT,\n  ATTR_RELATION_SOURCE,\n  ATTR_RELATION_TARGET,\n  ATTR_TYPE,\n  objectStructureFromJson,\n  objectStructureToJson,\n} from '@dxos/echo/internal';\nimport * as RuntimeProvider from '@dxos/effect/RuntimeProvider';\nimport { type FeedOptions, type FeedStore } from '@dxos/feed';\nimport {\n  type EntityMeta,\n  type IndexEngine,\n  type ObjectSnapshot,\n  type QueueRef,\n  type QueueWindow,\n  type ReverseRef,\n  queueBranchesOf,\n} from '@dxos/index-core';\nimport { invariant } from '@dxos/invariant';\nimport { EID, EntityId, SpaceId, URI } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { type FeedProtocol } from '@dxos/protocols';\nimport { type QueryReactivity } from '@dxos/protocols/buf/dxos/echo/query_pb';\nimport { type QueryService } from '@dxos/protocols/rpc';\nimport { chunkArray, compositeKey, countWork, getDeep, isNonNullable } from '@dxos/util';\n\nimport type { AutomergeHost } from '../automerge/index.ts';\nimport type { SpaceStateManager } from '../db-host/index.ts';\nimport { type InvalidationHint, canonicalTypename } from '../db-host/invalidation-hint.ts';\nimport { filterMatchDoc, filterMatchEntityMeta, filterMatchObjectJSON, getEntityMetaTypeURI } from '../filter/index.ts';\nimport { type ChangeItem, changeResults, executeChangesPlan, serializeChangeResults } from './changes-executor.ts';\nimport { QueryError } from './errors.ts';\nimport { type GroupAggregates, GroupBy, type GroupKeyValue, compareCodeUnits } from './group-by.ts';\nimport { isSaved } from './object-state.ts';\nimport { QueryPlan } from './plan.ts';\nimport { QueryPlanner, filterContainsInQuery } from './query-planner.ts';\nimport {\n  type CompiledRow,\n  MAX_EDGES_PER_ROW,\n  compilePlan,\n  planDeclinedByCompiler,\n  withFeedCutoffs,\n} from './sql/index.ts';\n\n/**\n * Which evaluation path a plan targets: `memory` leaves every step for the executor to evaluate in\n * JS over loaded objects; `sql` compiles the steps into a single {@link QueryPlan.SqlStep} over the\n * index tables. `memory` is the default; the host resolves where the choice comes from.\n */\nexport type QueryExecutorMode = 'sql' | 'memory';\n\ntype QueryExecutorOptions = {\n  indexEngine: IndexEngine;\n  runtime: RuntimeProvider.RuntimeProvider<SqlClient.SqlClient>;\n  automergeHost: AutomergeHost;\n  spaceStateManager: SpaceStateManager;\n\n  queryId: string;\n  query: QueryAST.Query;\n  reactivity: QueryReactivity;\n  executor?: QueryExecutorMode;\n  /** Builds compiled statements; needed only under the `sql` executor. */\n  sql?: SqlClient.SqlClient;\n  /** Whether the client already holds a document; its rows ship without JSON and stored changes. */\n  holds?: (documentId: DocumentId) => boolean;\n  /**\n   * The feed store, read for the feeds whose indexing is disabled (they have no index rows) and for\n   * the `maxAge` an index row of a feed item is checked against. Absent, every feed is read from the index.\n   */\n  feedStore?: FeedStore;\n};\n\n/** A feed whose indexing is disabled, which a run reads from the feed store instead of the index. */\ntype StoreFeed = { spaceId: SpaceId; feedNamespace: string };\n\ntype QueryExecutionResult = {\n  /**\n   * Whether the query results have changed since the last execution.\n   */\n  changed: boolean;\n};\n\n/**\n * Represents an item in the query working set during execution.\n */\ntype QueryItem = {\n  objectId: EntityId;\n\n  spaceId: SpaceId;\n  queueId: EntityId | null;\n  queueNamespace: string | null;\n\n  // For objects from automerge documents.\n  documentId: DocumentId | null;\n\n  // For objects from automerge documents.\n  doc: EntityStructure | null;\n\n  // For objects from queues.\n  data: Obj.JSON | null;\n\n  /** For objects selected from the index without loading, when both `doc` and `data` are null. */\n  meta?: EntityMeta;\n\n  /**\n   * Relevance rank for this item.\n   * Higher values indicate better matches for FTS/vector searches.\n   * Defaults to 1 for non-ranked queries (predicate matches).\n   */\n  rank: number;\n\n  /**\n   * System timestamps from the object meta index (unix ms), used for `timestamp` ordering.\n   * Null when the index has not recorded a timestamp for the item.\n   */\n  createdAt: number | null;\n  updatedAt: number | null;\n\n  /**\n   * Group key, set by `AggregateStep`. Undefined for queries without an `aggregate` clause; `{}` for\n   * an aggregate clause with no `group` entries (a single group over the whole input).\n   */\n  groupKey?: GroupKeyValue;\n\n  /**\n   * Named group aggregates, stamped by `AggregateStep` when the query declares non-`items` aggregates;\n   * shared by every member of a group and read by a following group-level `OrderStep`.\n   */\n  aggregates?: GroupAggregates;\n\n  /**\n   * Set when this item stands for its whole group: the query declared no `items` aggregate, so\n   * `AggregateStep` kept one member per group and the result ships only `groupKey`/`aggregates`.\n   */\n  collapsed?: { size: number };\n\n  /**\n   * The shipped form, already built by a `SqlStep` from the row SQLite returned. Such an item\n   * carries no document, data or meta, so it is only ever produced by the plan's last step.\n   */\n  result?: QueryService.QueryResult;\n\n  recordId?: number;\n\n  /**\n   * The place of the item on a walk, which the natural order of a walk scope sorts by: the index of its\n   * first block on the path read forward, so a descending order gives the backward walk.\n   */\n  walkIndex?: number;\n\n  backing?: { heads: readonly string[]; json: string };\n\n  /** Heads of the document the item was read at, which the row ships as its version. */\n  heads?: readonly string[];\n\n  /** A feed item's global block position, which the row ships as its version. */\n  position?: number | null;\n\n  /** How a traversal reached the item, one path per derivation; absent outside traversals. */\n  paths?: readonly (readonly QueryService.PathEdge[])[];\n\n  /** Set when some derivation of the item could not be stated, so its paths are not shipped. */\n  derivationUnknown?: boolean;\n\n  /** Each member of a collapsed group with its share of the scalar aggregates; set by `AggregateStep`. */\n  manifest?: readonly QueryService.ManifestEntry[];\n};\n\n/** Parsed once per index row: an order step reads it on every comparison. */\nconst indexedAnnotations = new WeakMap<EntityMeta, Readonly<Record<string, unknown>> | undefined>();\n\nconst parseIndexedAnnotations = (meta: EntityMeta): Readonly<Record<string, unknown>> | undefined => {\n  if (!indexedAnnotations.has(meta)) {\n    indexedAnnotations.set(meta, meta.annotations === null ? undefined : JSON.parse(meta.annotations));\n  }\n  return indexedAnnotations.get(meta);\n};\n\nconst QueryItem = Object.freeze({\n  /** An item for an index row, carrying no document; `null` for a row that is not document-backed. */\n  fromIndexRow: (meta: EntityMeta): QueryItem | null =>\n    meta.documentId\n      ? {\n          objectId: meta.objectId,\n          documentId: meta.documentId as DocumentId,\n          spaceId: meta.spaceId,\n          queueId: null,\n          queueNamespace: null,\n          doc: null,\n          data: null,\n          meta,\n          rank: 1,\n          createdAt: meta.createdAt,\n          updatedAt: meta.updatedAt,\n        }\n      : null,\n\n  /** The state the item was read at, as a row ships it; undefined when the item does not know it. */\n  getVersion: (item: QueryItem): QueryService.RowVersion | undefined => {\n    if (item.documentId && item.heads) {\n      return { kind: 'automerge', documentId: item.documentId, heads: [...item.heads] };\n    }\n    if (item.queueId && typeof item.position === 'number') {\n      return { kind: 'feed', insertionId: item.position };\n    }\n    return undefined;\n  },\n\n  /** An item for a document object read from the index's copy, which carries its version and backing. */\n  fromSnapshot: (meta: EntityMeta, documentId: DocumentId, snapshot: ObjectSnapshot): QueryItem => ({\n    objectId: meta.objectId,\n    documentId,\n    spaceId: meta.spaceId,\n    queueId: null,\n    queueNamespace: null,\n    doc: objectStructureFromJson(JSON.parse(snapshot.json), { createdAt: meta.createdAt ?? undefined }),\n    data: null,\n    rank: 1,\n    createdAt: meta.createdAt,\n    updatedAt: meta.updatedAt,\n    recordId: meta.recordId,\n    backing: snapshot.heads ? { heads: snapshot.heads, json: snapshot.json } : undefined,\n    heads: snapshot.version,\n  }),\n\n  /**\n   * Checks if the item is deleted.\n   * Only applies to this item, not its parents.\n   */\n  isDeleted: (item: QueryItem) => {\n    if (item.doc) {\n      return EntityStructure.isDeleted(item.doc);\n    } else if (item.data) {\n      return item.data['@deleted'] === true;\n    } else if (item.meta) {\n      return item.meta.deleted;\n    } else {\n      throw new Error('Invalid query item');\n    }\n  },\n\n  /** The entity's `meta.annotations`, from whichever representation the item carries. */\n  getAnnotations: (item: QueryItem): Readonly<Record<string, unknown>> | undefined => {\n    if (item.doc) {\n      return item.doc.meta?.annotations;\n    } else if (item.data) {\n      return item.data[ATTR_META]?.annotations;\n    } else if (item.meta) {\n      return parseIndexedAnnotations(item.meta);\n    } else {\n      return undefined;\n    }\n  },\n\n  getProperty: (item: QueryItem, property: EntityPropPath) => {\n    if (item.doc) {\n      return getDeep(item.doc.data, property);\n    } else if (item.data) {\n      return getDeep(item.data, property);\n    } else {\n      throw new Error('Invalid query item');\n    }\n  },\n\n  /**\n   * Reads a top-level property for the `aggregate` clause, resolving `id` to the entity id — every\n   * object exposes `id` through the API, but documents don't store it in their data (see\n   * `PROPERTY_ID` handling in the echo handler), so a group key falling back to `id` would otherwise\n   * collapse every keyless member into the shared `null` group.\n   */\n  getAggregateProperty: (item: QueryItem, property: string): unknown =>\n    property === PROPERTY_ID ? item.objectId : QueryItem.getProperty(item, [property]),\n\n  /**\n   * Computes the composite group key for this item from the aggregate's `group`-kind entries, keyed\n   * by result field name. No `group` entries yields `{}` — a single group over the whole input.\n   */\n  getGroupKey: (item: QueryItem, aggregates: readonly QueryAST.GroupAggregate[]): GroupKeyValue => {\n    const key: GroupKeyValue = {};\n    for (const aggregate of aggregates) {\n      switch (aggregate.kind) {\n        case 'group':\n          key[aggregate.name] = GroupBy.resolveKeyComponent(aggregate.properties, (property) =>\n            QueryItem.getAggregateProperty(item, property),\n          );\n          break;\n        case 'type':\n          key[aggregate.name] = QueryItem.getTypeUri(item);\n          break;\n        case 'timestamp':\n          key[aggregate.name] = GroupBy.truncateTime(item[aggregate.field], aggregate.unit);\n          break;\n        case 'time':\n          key[aggregate.name] = GroupBy.truncateTime(\n            QueryItem.getAggregateProperty(item, aggregate.property),\n            aggregate.unit,\n          );\n          break;\n      }\n    }\n    return key;\n  },\n\n  /** The stored type reference as a URI string, or `null` for an untyped object. */\n  getTypeUri: (item: QueryItem): string | null => {\n    if (item.doc) {\n      return EntityStructure.getTypeReference(item.doc)?.['/'] ?? null;\n    } else if (item.data) {\n      const type = item.data[ATTR_TYPE];\n      return typeof type === 'string' ? type : null;\n    } else if (item.meta) {\n      return getEntityMetaTypeURI(item.meta) ?? null;\n    } else {\n      throw new Error('Invalid query item');\n    }\n  },\n\n  getParent: (item: QueryItem): EID.EID | undefined => {\n    let raw: string | undefined;\n    if (item.doc) {\n      raw = EntityStructure.getParent(item.doc)?.['/'];\n    } else if (item.data) {\n      raw = item.data[ATTR_PARENT];\n    } else if (item.meta) {\n      raw = item.meta.parent ?? undefined;\n    } else {\n      throw new Error('Invalid query item');\n    }\n    return raw !== undefined ? EID.tryParse(raw) : undefined;\n  },\n\n  getRelationSource: (item: QueryItem): EID.EID | undefined => {\n    let raw: string | undefined;\n    if (item.doc) {\n      raw = EntityStructure.getRelationSource(item.doc)?.['/'];\n    } else if (item.data) {\n      raw = item.data[ATTR_RELATION_SOURCE];\n    } else if (item.meta) {\n      raw = item.meta.source ?? undefined;\n    } else {\n      throw new Error('Invalid query item');\n    }\n    return raw !== undefined ? EID.tryParse(raw) : undefined;\n  },\n\n  getRelationTarget: (item: QueryItem): EID.EID | undefined => {\n    let raw: string | undefined;\n    if (item.doc) {\n      raw = EntityStructure.getRelationTarget(item.doc)?.['/'];\n    } else if (item.data) {\n      raw = item.data[ATTR_RELATION_TARGET];\n    } else if (item.meta) {\n      raw = item.meta.target ?? undefined;\n    } else {\n      throw new Error('Invalid query item');\n    }\n    return raw !== undefined ? EID.tryParse(raw) : undefined;\n  },\n\n  /**\n   * EIDs of objects this item strongly depends on: the schema object (when the type is an\n   * ECHO object reference), relation source/target, the parent, and the tags (read from the\n   * document only: an index row carries no meta). Mirrors\n   * `ObjectCore.getStrongDependencies` on the client. Queue items hydrate from indexed\n   * snapshots and don't gate on dependency loads, so they report no strong deps.\n   */\n  getStrongDependencies: (item: QueryItem): EID.EID[] => {\n    if (!item.doc && item.meta) {\n      const { typeDXN, entityKind, source, target, parent } = item.meta;\n      const endpoints = entityKind === 'relation' ? [source, target] : [];\n      return [typeDXN, ...endpoints, parent].flatMap((raw) => {\n        const uri = raw ? EID.tryParse(raw) : undefined;\n        return uri ? [uri] : [];\n      });\n    }\n    if (!item.doc) {\n      return [];\n    }\n    const res: EID.EID[] = [];\n    const push = (ref: EncodedReference | undefined) => {\n      if (!ref) {\n        return;\n      }\n      try {\n        const uri = EID.tryParse(EncodedReference.toURI(ref));\n        if (uri) {\n          res.push(uri);\n        }\n      } catch {\n        log.warn('invalid reference', { ref: ref['/'] });\n      }\n    };\n    push(EntityStructure.getTypeReference(item.doc));\n    if (EntityStructure.getEntityKind(item.doc) === 'relation') {\n      push(EntityStructure.getRelationSource(item.doc));\n      push(EntityStructure.getRelationTarget(item.doc));\n    }\n    push(EntityStructure.getParent(item.doc));\n    for (const tag of EntityStructure.getTags(item.doc)) {\n      // A legacy tag is a bare URI rather than an encoded reference.\n      push(typeof tag === 'string' ? EncodedReference.fromURI(URI.make(tag)) : tag);\n    }\n    return res;\n  },\n});\n\n/**\n * Recursive data structure that represents the execution trace of a query.\n */\nexport type ExecutionTrace = {\n  name: string;\n  details: string;\n\n  objectCount: number;\n  documentsLoaded: number;\n  indexHits: number;\n\n  beginTs: number;\n  endTs: number;\n\n  executionTime: number;\n  indexQueryTime: number;\n  documentLoadTime: number;\n\n  children: ExecutionTrace[];\n\n  /** The compiled statement, on the `sql` path. */\n  sql?: string;\n  /** `EXPLAIN QUERY PLAN` of that statement, when execution tracing is on. */\n  explain?: string[];\n};\n\nexport const ExecutionTrace = Object.freeze({\n  makeEmpty: (): ExecutionTrace => ({\n    name: 'Empty',\n    details: '',\n    objectCount: 0,\n    documentsLoaded: 0,\n    indexHits: 0,\n    beginTs: 0,\n    endTs: 0,\n    indexQueryTime: 0,\n    documentLoadTime: 0,\n    executionTime: 0,\n    children: [],\n  }),\n  markEnd: (trace: ExecutionTrace) => {\n    trace.endTs = performance.now();\n    trace.executionTime = trace.endTs - trace.beginTs;\n  },\n  putOnPerformanceTimeline: (trace: ExecutionTrace) => {\n    performance.measure(trace.name, {\n      start: trace.beginTs,\n      end: trace.endTs,\n      detail: {\n        devtools: {\n          dataType: 'track-entry',\n          track: 'Query Execution',\n          trackGroup: 'ECHO', // Group related tracks together\n          color: 'tertiary-dark',\n          properties: [\n            ['objectCount', trace.objectCount],\n            ['documentsLoaded', trace.documentsLoaded],\n            ['index hits', trace.indexHits],\n            ['indexQueryTime', trace.indexQueryTime],\n            ['documentLoadTime', trace.documentLoadTime],\n          ],\n          tooltipText: trace.details,\n        },\n      },\n    });\n    for (const child of trace.children) {\n      ExecutionTrace.putOnPerformanceTimeline(child);\n    }\n  },\n  format: (trace: ExecutionTrace): string => {\n    const go = (trace: ExecutionTrace, indent: number): string => {\n      return [\n        `${' '.repeat(indent)} - ${trace.name}(${trace.details})`,\n        `${' '.repeat(indent)}   objects: ${trace.objectCount}  docs: ${trace.documentsLoaded}  index hits: ${trace.indexHits} | total: ${trace.executionTime.toFixed(0)}ms  index: ${trace.indexQueryTime.toFixed(0)}ms  load: ${trace.documentLoadTime.toFixed(0)}ms`,\n        '',\n        ...trace.children.map((child) => go(child, indent + 2)),\n      ].join('\\n');\n    };\n    return go(trace, 0);\n  },\n});\n\ntype StepExecutionResult = {\n  workingSet: QueryItem[];\n  trace: ExecutionTrace;\n};\n\ndeclare global {\n  interface ImportMeta {\n    env: ImportMetaEnv;\n  }\n\n  interface ImportMetaEnv {\n    DX_TRACE_QUERY_EXECUTION: string;\n    DX_ECHO_QUERY_EXECUTOR: string;\n  }\n}\n\nconst TRACE_QUERY_EXECUTION = !!import.meta.env?.DX_TRACE_QUERY_EXECUTION;\n\nconst MAX_DEPTH_FOR_DELETION_TRACING = 10;\nconst MAX_DEPTH_FOR_CHILD_OF_TRACING = 10;\nconst MAX_DEPTH_FOR_STRONG_DEP_TRACING = 10;\n\n/**\n * Cached scope constraints extracted from a query plan.\n * Used to quickly determine whether an invalidation hint can affect this query.\n *\n * A null dimension means the query is unconstrained on that dimension (matches any value).\n */\ntype QueryScopes = {\n  /**\n   * False for text-search, traversal, union, set-difference, or child-of queries.\n   * When false, matchesHint always returns true (conservative: always re-execute).\n   */\n  isSimple: boolean;\n  spaceIds: Set<SpaceId> | null;\n  queueIds: Set<EntityId> | null;\n  typenames: Set<string> | null;\n  objectIds: Set<EntityId> | null;\n  readsFeeds: boolean;\n  /**\n   * Typenames of the relations a plan ending in a typed relation traversal (`targetOf` / `sourceOf`) selects.\n   * Such a plan also re-runs when a relation of one of these types changes, since that never touches its\n   * anchors, or when an endpoint of a relation it returned changes. Null for every other plan.\n   */\n  relationTypenames: Set<string> | null;\n};\n\n/**\n * Replaces each compiled {@link QueryPlan.SqlStep} with the steps it stands for: scope analysis must\n * see the original selects and filters, or every compiled query reads as unconstrained and re-runs on\n * every write.\n */\nconst flattenSqlSteps = (steps: readonly QueryPlan.Step[]): QueryPlan.Step[] =>\n  steps.flatMap((step) => (step._tag === 'SqlStep' ? flattenSqlSteps(step.steps) : [step]));\n\nconst extractScopes = (plan: QueryPlan.Plan): QueryScopes => {\n  const scopes: QueryScopes = {\n    isSimple: true,\n    spaceIds: null,\n    queueIds: null,\n    typenames: null,\n    objectIds: null,\n    readsFeeds: false,\n    relationTypenames: null,\n  };\n  // Set by a relation traversal until the typed filter after it names the relations it selects.\n  let untypedRelationTraversal = false;\n\n  for (const step of flattenSqlSteps(plan.steps)) {\n    switch (step._tag) {\n      case 'SelectStep': {\n        // Extract spaceIds from space-scoped entries.\n        const spaceScopes = step.scope.filter((scope): scope is QueryAST.SpaceScope => scope._tag === 'space');\n        if (spaceScopes.length > 0) {\n          if (!scopes.spaceIds) {\n            scopes.spaceIds = new Set();\n          }\n          for (const spaceScope of spaceScopes) {\n            scopes.spaceIds.add(spaceScope.spaceId as SpaceId);\n          }\n        }\n\n        // Extract queueIds from feed-scoped entries and derive spaceIds from them.\n        const feedScopesForExtract = step.scope.filter((scope): scope is QueryAST.FeedScope => scope._tag === 'feed');\n        const hasIncludeAllFeeds = spaceScopes.some((s) => s.includeAllFeeds === true);\n        if (feedScopesForExtract.length > 0 || hasIncludeAllFeeds) {\n          scopes.readsFeeds = true;\n        }\n        if (feedScopesForExtract.length > 0 && !hasIncludeAllFeeds) {\n          let parseFailed = false;\n          const derivedQueueIds = new Set<EntityId>();\n          const derivedSpaceIds = new Set<SpaceId>();\n          for (const feedEntry of feedScopesForExtract) {\n            const echoUri = EID.tryParse(String(feedEntry.feedUri));\n            if (echoUri) {\n              const queueId = EID.getEntityId(echoUri);\n              const spaceId = EID.getSpaceId(echoUri);\n              if (queueId) {\n                derivedQueueIds.add(queueId);\n              }\n              if (spaceId) {\n                derivedSpaceIds.add(spaceId);\n              }\n            } else {\n              parseFailed = true;\n            }\n          }\n\n          if (!parseFailed) {\n            if (derivedQueueIds.size > 0) {\n              scopes.queueIds ??= new Set<EntityId>();\n              for (const id of derivedQueueIds) {\n                scopes.queueIds.add(id);\n              }\n            }\n            if (derivedSpaceIds.size > 0) {\n              scopes.spaceIds ??= new Set<SpaceId>();\n              for (const id of derivedSpaceIds) {\n                // Derive spaceId from the queue DXN so space-scoped hints can skip this query.\n                scopes.spaceIds.add(id);\n              }\n            }\n          }\n          // On any parse error, leave queue-derived dimensions unconstrained.\n        }\n\n        // Extract typename / objectId constraints from selector.\n        switch (step.selector._tag) {\n          case 'TypeSelector': {\n            if (step.selector.inverted) {\n              // Inverted type selectors come from Filter.not — mark as non-simple.\n              scopes.isSimple = false;\n            } else {\n              if (!scopes.typenames) {\n                scopes.typenames = new Set();\n              }\n              for (const typename of step.selector.typename) {\n                scopes.typenames.add(canonicalTypename(typename as string));\n              }\n            }\n            break;\n          }\n          case 'IdSelector': {\n            if (!scopes.objectIds) {\n              scopes.objectIds = new Set();\n            }\n            for (const id of step.selector.objectIds) {\n              scopes.objectIds.add(id);\n            }\n            break;\n          }\n          case 'TextSelector': {\n            scopes.isSimple = false;\n            break;\n          }\n          default:\n            // WildcardSelector, TimestampSelector — no type/id constraint.\n            break;\n        }\n        break;\n      }\n      case 'FilterStep': {\n        if (untypedRelationTraversal) {\n          if (step.filter.type === 'object' && typeof step.filter.typename === 'string') {\n            scopes.relationTypenames ??= new Set();\n            scopes.relationTypenames.add(canonicalTypename(step.filter.typename));\n            untypedRelationTraversal = false;\n          } else {\n            scopes.isSimple = false;\n          }\n        }\n        // child-of filters require transitive parent traversal which can't be hinted.\n        if (step.filter.type === 'child-of') {\n          scopes.isSimple = false;\n        }\n        // A nested in-query (subquery-membership) predicate's result depends on the subquery's\n        // own scope/typenames — which may differ entirely from this query's — so a hint scoped\n        // to this query's dimensions could miss a change that alters the subquery's result set.\n        // `filterContainsInQuery` (not a bare `step.filter.type` check) is required: the residual\n        // filter here is always `type: 'object'` with the in-query nested in `props`.\n        if (filterContainsInQuery(step.filter)) {\n          scopes.isSimple = false;\n        }\n        break;\n      }\n      case 'TraverseStep': {\n        // One step from the anchors to the relations on them can be bounded by the relations' type; any other\n        // traversal reaches objects the hint cannot name.\n        const { traversal } = step;\n        const toRelations =\n          traversal._tag === 'RelationTraversal' &&\n          (traversal.direction === 'source-to-relation' || traversal.direction === 'target-to-relation');\n        if (toRelations && scopes.relationTypenames === null && !untypedRelationTraversal) {\n          untypedRelationTraversal = true;\n        } else {\n          scopes.isSimple = false;\n        }\n        break;\n      }\n      case 'UnionStep':\n      case 'SetDifferenceStep':\n        scopes.isSimple = false;\n        break;\n      default:\n        // ClearWorkingSetStep, FilterDeletedStep, OrderStep, LimitStep are fine.\n        break;\n    }\n  }\n\n  if (untypedRelationTraversal) {\n    scopes.isSimple = false;\n  }\n  return scopes;\n};\n\n/** The spaces any select step (including those nested in UnionStep/SetDifferenceStep subplans) scopes with {@link QueryAST.SpaceScope.includeAllFeeds}. */\nconst extractAllFeedsSpaces = (plan: QueryPlan.Plan): Set<SpaceId> =>\n  new Set(\n    plan.steps.flatMap((step): SpaceId[] => {\n      switch (step._tag) {\n        case 'SelectStep':\n          return step.scope.flatMap((scope) =>\n            scope._tag === 'space' && scope.includeAllFeeds === true ? [scope.spaceId as SpaceId] : [],\n          );\n        case 'UnionStep':\n          return step.plans.flatMap((subplan) => [...extractAllFeedsSpaces(subplan)]);\n        case 'SetDifferenceStep':\n          return [...extractAllFeedsSpaces(step.source), ...extractAllFeedsSpaces(step.exclude)];\n        default:\n          return [];\n      }\n    }),\n  );\n\nconst setsOverlap = <T>(a: ReadonlySet<T>, b: ReadonlySet<T>): boolean => {\n  const [smaller, larger]: [ReadonlySet<T>, ReadonlySet<T>] = a.size <= b.size ? [a, b] : [b, a];\n  for (const item of smaller) {\n    if (larger.has(item)) {\n      return true;\n    }\n  }\n  return false;\n};\n\n/** The id of the object that directly owns `item`: its parent, else the feed it was appended to. */\nconst childOfOwnerId = (item: QueryItem): EntityId | undefined => {\n  const parent = QueryItem.getParent(item);\n  if (parent) {\n    return EID.getEntityId(parent);\n  }\n  return item.queueId ?? undefined;\n};\n\n/** The ids of the objects the relations in `items` connect, read from whichever form each item carries. */\nconst relationEndpoints = (items: readonly QueryItem[]): Set<EntityId> => {\n  const endpoints = new Set<EntityId>();\n  const add = (uri: string | null | undefined) => {\n    const eid = uri ? EID.tryParse(uri) : undefined;\n    const entityId = eid && EID.getEntityId(eid);\n    if (entityId) {\n      endpoints.add(entityId);\n    }\n  };\n  for (const item of items) {\n    if (item.meta) {\n      add(item.meta.source);\n      add(item.meta.target);\n    }\n    const source = item.doc && EntityStructure.getRelationSource(item.doc);\n    const target = item.doc && EntityStructure.getRelationTarget(item.doc);\n    add(source && EncodedReference.toURI(source));\n    add(target && EncodedReference.toURI(target));\n  }\n  return endpoints;\n};\n\nconst overlapsOrUnconstrained = <T>(hintSet: ReadonlySet<T> | undefined, scopeSet: Set<T> | null): boolean =>\n  hintSet === undefined || scopeSet === null || setsOverlap(hintSet, scopeSet);\n\n/**\n * Serializes a possibly-absent group key for `changed` diffing. `undefined` (non-grouped\n * queries) serializes to a distinct sentinel so it never collides with a real (empty) group key.\n */\nconst _serializeOptionalGroupKey = (key: GroupKeyValue | undefined): string =>\n  key === undefined ? '\\0' : GroupBy.serializeGroupKey(key);\n\nconst _serializeCollapsed = (item: QueryItem): string =>\n  item.collapsed === undefined ? '' : JSON.stringify([item.collapsed.size, item.aggregates ?? null]);\n\n/** True once the working set has been partitioned by an AggregateStep (every item carries a group key). */\nconst isGrouped = (workingSet: QueryItem[]): boolean => workingSet.length > 0 && workingSet[0].groupKey !== undefined;\n\n// Non-null assertion is sound: only called from group-aware limit/skip, which run exclusively on a\n// working set already partitioned by AggregateStep (guarded by `isGrouped`), where every item has a key.\nconst serializeItemGroupKey = (item: QueryItem): string => GroupBy.serializeGroupKey(item.groupKey!);\n\n/**\n * Executes query plans against the IndexEngine and AutomergeHost.\n *\n * The QueryExecutor is responsible for:\n * - Executing query plans step by step\n * - Managing the working set of query results\n * - Loading documents from the database\n * - Tracking execution performance metrics\n * - Handling different types of query operations (select, filter, traverse, etc.)\n */\nexport class QueryExecutor extends Resource {\n  private readonly _indexEngine: IndexEngine;\n  private readonly _runtime: RuntimeProvider.RuntimeProvider<SqlClient.SqlClient>;\n  private readonly _automergeHost: AutomergeHost;\n  private readonly _spaceStateManager: SpaceStateManager;\n  /**\n   * Id of this query.\n   */\n  private readonly _id: string;\n  private readonly _query: QueryAST.Query;\n  // TODO(dmaretskyi): Might be used in the future.\n  private readonly _reactivity: QueryReactivity;\n\n  /** The uncompiled steps until the first execution, which swaps in the compiled plan. */\n  private _plan: QueryPlan.Plan;\n  /** The steps before compilation, run instead of a compiled plan when a feed in scope has no index rows. */\n  readonly #uncompiledPlan: QueryPlan.Plan;\n  readonly #feedStore: FeedStore | undefined;\n  /** Feeds the current run reads from the feed store, keyed by feed id; set at the top of every run. */\n  #storeFeeds = new Map<string, StoreFeed>();\n  /** Per feed in scope with a `maxAge` (keyed `<spaceId>/<feedId>`), the time its rows expire before; set every run. */\n  #feedCutoffs = new Map<string, number>();\n  /** Recompiles the plan with this run's feed cutoffs; absent when the plan was not compiled. */\n  readonly #compile: ((feedCutoffs: ReadonlyMap<string, number>) => QueryPlan.Plan) | undefined;\n  #scopes: QueryScopes;\n  /** Endpoints of the relations in the last result, for a plan bounded by {@link QueryScopes.relationTypenames}. */\n  #relationEndpoints = new Set<EntityId>();\n  readonly #allFeedsSpaces: ReadonlySet<SpaceId>;\n  private _trace: ExecutionTrace = ExecutionTrace.makeEmpty();\n  private _lastResultSet: QueryItem[] = [];\n  #truncated: 'paths' | 'manifest' | undefined = undefined;\n  #changeResultSet: ChangeItem[] | undefined;\n  readonly #planner: QueryPlanner;\n  readonly #mode: QueryExecutorMode;\n  readonly #holds: (documentId: DocumentId) => boolean;\n\n  /**\n   * Resolved `in-query` (subquery-membership) sets for the current `execQuery` run, keyed by\n   * `JSON.stringify(subquery) + '\\0' + property`. Two FilterSteps embedding the same subquery\n   * (e.g. both branches of a `Query.all` union) share one resolution instead of re-running it;\n   * the `Promise` (rather than the resolved value) is cached so concurrent lookups — `UnionStep`\n   * branches execute via `Promise.all` — await the same in-flight resolution instead of racing.\n   * Cleared at the top of every `execQuery()` since subquery results can change between runs.\n   */\n  #inQuerySetCache = new Map<string, Promise<{ values: ReadonlySet<unknown>; trace: ExecutionTrace }>>();\n  /** Subquery-resolution traces already attached to a FilterStep's trace this `execQuery` run. */\n  #inQueryTracesAttached = new Set<string>();\n\n  /**\n   * Strong dependencies loaded during the current `execQuery` run, keyed by how they resolve (see\n   * {@link QueryExecutor._loadDependency}). Siblings share their parents, and each load is a lookup.\n   */\n  #dependencyCache = new Map<string, Promise<QueryItem | null>>();\n\n  constructor(options: QueryExecutorOptions) {\n    super();\n\n    this._indexEngine = options.indexEngine;\n    this._runtime = options.runtime;\n    this._automergeHost = options.automergeHost;\n    this._spaceStateManager = options.spaceStateManager;\n\n    this._id = options.queryId;\n    this._query = options.query;\n    this._reactivity = options.reactivity;\n\n    this.#holds = options.holds ?? (() => false);\n    this.#mode = options.executor ?? 'memory';\n    this.#feedStore = options.feedStore;\n    this.#planner = new QueryPlanner();\n    const plan = this.#planner.createPlan(this._query);\n    this.#uncompiledPlan = plan;\n    const planSubquery = (query: QueryAST.Query) => this.#planner.createPlan(query);\n    const sql = options.sql;\n    this.#compile =\n      this.#mode === 'sql' && sql !== undefined && !planDeclinedByCompiler(plan, planSubquery)\n        ? (feedCutoffs) => compilePlan(sql, plan, planSubquery, { feedCutoffs }).plan\n        : undefined;\n    this._plan = this.#compile?.(new Map()) ?? plan;\n    this.#scopes = extractScopes(this._plan);\n    this.#allFeedsSpaces = extractAllFeedsSpaces(plan);\n  }\n\n  get queryId(): string {\n    return this._id;\n  }\n\n  get query(): QueryAST.Query {\n    return this._query;\n  }\n\n  get plan(): QueryPlan.Plan {\n    return this._plan;\n  }\n\n  get trace(): ExecutionTrace {\n    return this._trace;\n  }\n\n  get compiled(): boolean {\n    return this._plan.steps.some((step) => step._tag === 'SqlStep');\n  }\n\n  get selectsById(): boolean {\n    return this.#scopes.isSimple && this.#scopes.objectIds !== null && this.#scopes.relationTypenames === null;\n  }\n\n  /** Spaces the query reads; null when unconstrained or when the plan is too complex to bound. */\n  get spaceIds(): ReadonlySet<SpaceId> | null {\n    return this.#scopes.isSimple ? this.#scopes.spaceIds : null;\n  }\n\n  /** Whether the query can read feed rows; assumed for a plan too complex to bound. */\n  get readsFeeds(): boolean {\n    return !this.#scopes.isSimple || this.#scopes.readsFeeds;\n  }\n\n  /** What the last {@link getResults} left out to stay within its byte budget. */\n  get truncated(): 'paths' | 'manifest' | undefined {\n    return this.#truncated;\n  }\n\n  async getResults(): Promise<QueryService.QueryResult[]> {\n    this.#truncated = undefined;\n    if (this.#changeResultSet) {\n      return changeResults(this.#changeResultSet);\n    }\n    const shipPaths = withinBudget(this._lastResultSet.map((item) => item.paths));\n    const shipManifests = withinBudget(this._lastResultSet.map((item) => item.manifest));\n    if (!shipPaths) {\n      this.#truncated = 'paths';\n    } else if (!shipManifests) {\n      this.#truncated = 'manifest';\n    }\n    // Computed over the final (post-filter) result set so counts always match shipped records.\n    const groupCounts = new Map<string, number>();\n    for (const item of this._lastResultSet) {\n      if (item.groupKey === undefined) {\n        continue;\n      }\n      const serialized = GroupBy.serializeGroupKey(item.groupKey);\n      groupCounts.set(serialized, (groupCounts.get(serialized) ?? 0) + 1);\n    }\n\n    const results = this._lastResultSet.map((item): QueryService.QueryResult => {\n      if (item.result !== undefined) {\n        return {\n          ...item.result,\n          ...(shipPaths && item.paths && !item.derivationUnknown && { paths: item.paths.map((path) => [...path]) }),\n          ...(shipManifests && item.manifest && { manifest: [...item.manifest] }),\n        };\n      }\n      const serializedGroupKey = item.groupKey !== undefined ? GroupBy.serializeGroupKey(item.groupKey) : undefined;\n      if (item.collapsed !== undefined && serializedGroupKey !== undefined) {\n        return {\n          id: serializedGroupKey,\n          spaceId: item.spaceId,\n          rank: item.rank,\n          groupKey: serializedGroupKey,\n          groupCount: item.collapsed.size,\n          aggregates: JSON.stringify(item.aggregates ?? {}),\n          manifest: shipManifests && item.manifest ? [...item.manifest] : undefined,\n        };\n      }\n      return {\n        id: item.objectId,\n        documentId: item.documentId ?? undefined,\n        queueId: item.queueId ?? undefined,\n        queueNamespace: item.queueNamespace ?? undefined,\n        spaceId: item.spaceId,\n\n        rank: item.rank,\n\n        documentJson: item.backing?.json ?? (item.data ? JSON.stringify(item.data) : undefined),\n\n        groupKey: serializedGroupKey,\n        groupCount: serializedGroupKey !== undefined ? groupCounts.get(serializedGroupKey) : undefined,\n\n        heads: item.backing ? [...item.backing.heads] : undefined,\n        createdAt: item.backing ? (item.createdAt ?? undefined) : undefined,\n        updatedAt: item.backing ? (item.updatedAt ?? undefined) : undefined,\n        version: QueryItem.getVersion(item),\n        paths: shipPaths && item.paths && !item.derivationUnknown ? item.paths.map((path) => [...path]) : undefined,\n      };\n    });\n    return this.#withBacking(results, this._lastResultSet);\n  }\n\n  /**\n   * Backs each document row the client does not hold with its JSON, heads and stored changes. A row\n   * that cannot be backed ships bare, and is tried again on the next emission while the client lacks it.\n   */\n  async #withBacking(\n    results: QueryService.QueryResult[],\n    items: readonly QueryItem[],\n  ): Promise<QueryService.QueryResult[]> {\n    const unheld = results.flatMap((result, index) =>\n      result.heads !== undefined && result.documentId !== undefined && !this.#holds(result.documentId as DocumentId)\n        ? [index]\n        : [],\n    );\n    const sources = await this.#readBackingSources(results, items, unheld);\n    const backings = await this.#readStoredChanges(results, sources);\n    return results.map((result, index) => {\n      if (result.heads === undefined) {\n        return result;\n      }\n      const backing = backings.get(index);\n      return backing\n        ? { ...result, documentJson: backing.json, heads: backing.heads, bytes: backing.bytes }\n        : withoutBacking(result);\n    });\n  }\n\n  /**\n   * The JSON each row is backed with and the heads it was read at: the row's own, or for a compiled row\n   * the index's, both from one read so a pass between the plan and this read cannot pair them wrongly.\n   */\n  async #readBackingSources(\n    results: readonly QueryService.QueryResult[],\n    items: readonly QueryItem[],\n    indices: readonly number[],\n  ): Promise<Map<number, BackingSource>> {\n    const fromIndex = indices.filter(\n      (index) => results[index].documentJson === undefined && items[index]?.recordId !== undefined,\n    );\n    const indexed =\n      fromIndex.length > 0\n        ? await this._runInRuntime(\n            this._indexEngine.queryBackings(fromIndex.map((index) => items[index].recordId!)),\n          ).catch((err) => {\n            log.warn('index JSON could not be read for rows', { err });\n            return [];\n          })\n        : [];\n    const byRecord = new Map(indexed.map((row) => [row.recordId, row]));\n    const sources = new Map<number, BackingSource>();\n    for (const index of indices) {\n      const row = byRecord.get(items[index]?.recordId ?? -1);\n      const json = results[index].documentJson ?? row?.json;\n      if (json !== undefined) {\n        sources.set(index, { json, heads: row?.heads ?? results[index].heads! });\n      }\n    }\n    return sources;\n  }\n\n  /** Stored changes for each row with a source, {@link STORED_CHANGES_CONCURRENCY} reads at a time. */\n  async #readStoredChanges(\n    results: readonly QueryService.QueryResult[],\n    sources: ReadonlyMap<number, BackingSource>,\n  ): Promise<Map<number, BackingSource & { bytes: Uint8Array }>> {\n    const backings = new Map<number, BackingSource & { bytes: Uint8Array }>();\n    for (const chunk of chunkArray([...sources], STORED_CHANGES_CONCURRENCY)) {\n      await Promise.all(\n        chunk.map(async ([index, source]) => {\n          const documentId = results[index].documentId as DocumentId;\n          const bytes = await this._automergeHost\n            .readStoredChanges(documentId, { limit: BACKED_OBJECT_LIMIT })\n            .catch((err) => {\n              log.warn('stored changes could not be read for a row', { documentId, err });\n              return undefined;\n            });\n          if (bytes !== undefined) {\n            backings.set(index, { ...source, bytes });\n          }\n        }),\n      );\n    }\n    return backings;\n  }\n\n  /**\n   * Returns true if the given invalidation hint could affect this query's result set.\n   * When false, the query can safely be skipped for this invalidation cycle.\n   *\n   * Conservative: returns true for complex queries (traversals, text-search, unions) and\n   * for any dimension where either the hint or the query is unconstrained.\n   */\n  matchesHint(hint: InvalidationHint): boolean {\n    if (!this.#scopes.isSimple) {\n      return true;\n    }\n    if (\n      !overlapsOrUnconstrained(hint.spaceIds, this.#scopes.spaceIds) ||\n      !overlapsOrUnconstrained(hint.queueIds, this.#scopes.queueIds)\n    ) {\n      return false;\n    }\n    if (\n      overlapsOrUnconstrained(hint.typenames, this.#scopes.typenames) &&\n      overlapsOrUnconstrained(hint.objectIds, this.#scopes.objectIds)\n    ) {\n      return true;\n    }\n    const { relationTypenames } = this.#scopes;\n    return (\n      relationTypenames !== null &&\n      (overlapsOrUnconstrained(hint.typenames, relationTypenames) ||\n        (hint.objectIds !== undefined && setsOverlap(hint.objectIds, this.#relationEndpoints)))\n    );\n  }\n\n  async execQuery(): Promise<QueryExecutionResult> {\n    invariant(this._lifecycleState === LifecycleState.OPEN);\n\n    log('exec query', {\n      queryId: this._id,\n      query: Query.pretty(Query.fromAst(this._query)),\n      mode: this.#mode,\n    });\n\n    // Subquery results can change between reactive runs, so resolved `in-query` sets must not\n    // survive across `execQuery` calls.\n    this.#inQuerySetCache = new Map();\n    this.#inQueryTracesAttached = new Set();\n\n    const [select] = this._plan.steps;\n    if (select?._tag === 'SelectStep' && select.selector._tag === 'ChangesSelector') {\n      const previous = this.#changeResultSet;\n      const next = await executeChangesPlan(this._ctx, this._plan, {\n        indexEngine: this._indexEngine,\n        automergeHost: this._automergeHost,\n        spaceStateManager: this._spaceStateManager,\n        runInRuntime: (effect) => this._runInRuntime(effect),\n      });\n      this.#changeResultSet = next;\n      return { changed: serializeChangeResults(previous ?? []) !== serializeChangeResults(next) };\n    }\n\n    const previous = this._lastResultSet;\n    const { workingSet, trace } = await this._resolveWorkingSet();\n    this._lastResultSet = workingSet;\n    if (this.#scopes.relationTypenames !== null) {\n      this.#relationEndpoints = relationEndpoints(workingSet);\n    }\n    trace.name = 'Root';\n    trace.details = JSON.stringify({ id: this._id, query: Query.pretty(Query.fromAst(this._query)) });\n    // A `SqlStep` ran the statement one level down; surface it on the root the trace prints.\n    trace.sql = trace.children.find((child) => child.sql !== undefined)?.sql;\n    trace.explain = trace.children.find((child) => child.explain !== undefined)?.explain;\n    this._trace = trace;\n\n    const changed =\n      previous.length !== workingSet.length || previous.some((item, index) => !_sameResult(workingSet[index], item));\n\n    // Disabled because concurrent queries don't print hierarchies correctly.\n    // ExecutionTrace.putOnPerformanceTimeline(trace);\n\n    if (TRACE_QUERY_EXECUTION) {\n      // eslint-disable-next-line no-console\n      console.log(ExecutionTrace.format(trace), trace.sql, trace.explain);\n    }\n\n    return { changed };\n  }\n\n  /** Runs the plan, then drops items whose strong dependencies cannot be resolved from local state. */\n  private async _resolveWorkingSet(): Promise<{ workingSet: QueryItem[]; trace: ExecutionTrace }> {\n    try {\n      const now = Date.now();\n      ({ storeFeeds: this.#storeFeeds, feedCutoffs: this.#feedCutoffs } = await this.#readScopedFeeds(now));\n      // A compiled statement reads only the index, which holds nothing of a disabled feed; the cutoffs are\n      // bound into the statement, so a run with any recompiles it.\n      const plan =\n        this.#storeFeeds.size > 0\n          ? this.#uncompiledPlan\n          : this.#feedCutoffs.size > 0\n            ? (this.#compile?.(this.#feedCutoffs) ?? this._plan)\n            : this._plan;\n      const { workingSet: planned, trace } = await this._execPlan(plan, []);\n      const workingSet = await this.#withoutExpired(planned, now);\n      // A compiled plan resolved these in SQL. Keyed on the plan rather than the mode, because a plan\n      // the compiler declined runs step by step even under `sql` and needs the filter.\n      if (plan.steps.some((step) => step._tag === 'SqlStep')) {\n        return { workingSet, trace };\n      }\n      // Unresolvable items never reach the client, where hydration would fail or stall on them.\n      return { workingSet: await this._filterUnresolvableStrongDeps(workingSet), trace };\n    } finally {\n      // An idle reactive query keeps its executor, which would otherwise hold these items until its next run.\n      this.#dependencyCache.clear();\n    }\n  }\n\n  /** Each space's stored feed options, or none when the store cannot say; a read failure answers from the index. */\n  async #listFeedOptions(spaceId: SpaceId): Promise<Map<string, FeedOptions>> {\n    const feedStore = this.#feedStore;\n    if (!feedStore) {\n      return new Map();\n    }\n    return this._runInRuntime(feedStore.listFeedOptions(spaceId)).catch((err) => {\n      log.warn('feed options could not be read; answering feeds from the index', { spaceId, err });\n      return new Map<string, FeedOptions>();\n    });\n  }\n\n  /**\n   * Of the feeds the plan scopes to — by name, or as every feed of a space — those read from the store,\n   * keyed by feed id: indexing disabled, or named with a branch other than main while the index holds\n   * only the main branch. Also the retention cutoff of the named ones with a `maxAge`, keyed\n   * `<spaceId>/<feedId>`.\n   */\n  async #readScopedFeeds(\n    now: number,\n  ): Promise<{ storeFeeds: Map<string, StoreFeed>; feedCutoffs: Map<string, number> }> {\n    const storeFeeds = new Map<string, StoreFeed>();\n    const feedCutoffs = new Map<string, number>();\n    const feedStore = this.#feedStore;\n    const feedRefs = extractQueueRefs(extractFeedScopes(this.#uncompiledPlan)) ?? [];\n    if (!feedStore || (feedRefs.length === 0 && this.#allFeedsSpaces.size === 0)) {\n      return { storeFeeds, feedCutoffs };\n    }\n    const spaceIds = new Set([\n      ...this.#allFeedsSpaces,\n      ...feedRefs.flatMap((ref) => (ref.spaceId !== undefined && SpaceId.isValid(ref.spaceId) ? [ref.spaceId] : [])),\n    ]);\n    const addStoreFeed = async (spaceId: SpaceId, feedId: string) => {\n      const feedNamespace = await this._runInRuntime(feedStore.getFeedNamespace({ spaceId, feedId }));\n      if (feedNamespace !== undefined) {\n        storeFeeds.set(feedId, { spaceId, feedNamespace });\n      }\n    };\n    // A walk reads the branch tree of the store, which the index does not hold.\n    const walkRefs = extractQueueRefs(extractFeedScopes(this.#uncompiledPlan).filter((scope) => scope.walk)) ?? [];\n    for (const spaceId of spaceIds) {\n      for (const ref of walkRefs) {\n        if (ref.spaceId === spaceId && !storeFeeds.has(ref.queueId)) {\n          await addStoreFeed(spaceId, ref.queueId);\n        }\n      }\n      const options = await this.#listFeedOptions(spaceId);\n      if (this.#allFeedsSpaces.has(spaceId)) {\n        for (const [feedId, feedOptions] of options) {\n          if (feedOptions.indexing?.enabled === false) {\n            await addStoreFeed(spaceId, feedId);\n          }\n        }\n      }\n      for (const ref of feedRefs) {\n        const maxAge = ref.spaceId === spaceId ? options.get(ref.queueId)?.retention?.maxAge : undefined;\n        if (maxAge !== undefined) {\n          feedCutoffs.set(`${spaceId}/${ref.queueId}`, now - maxAge);\n        }\n        // A feed indexing only its main branch has no rows for any other, so reading one is a store read.\n        const feedOptions = options.get(ref.queueId);\n        if (\n          ref.spaceId === spaceId &&\n          !storeFeeds.has(ref.queueId) &&\n          (feedOptions?.indexing?.enabled === false ||\n            (feedOptions?.indexing?.mode !== 'all' &&\n              (ref.branches === undefined || ref.branches.some((branch) => branch !== null))))\n        ) {\n          await addStoreFeed(spaceId, ref.queueId);\n        }\n      }\n    }\n    return { storeFeeds, feedCutoffs };\n  }\n\n  /**\n   * Drops feed items whose block is past its feed's `maxAge`: the store hides them at once but deletes\n   * them, and so their index rows, only at its next trim. A feed scope's read already excludes them;\n   * this catches the rows no read could bound — reached by a traversal, a space's all-feeds scope, or\n   * an unqualified feed URI.\n   */\n  async #withoutExpired(workingSet: QueryItem[], now: number): Promise<QueryItem[]> {\n    const spaceIds = new Set(workingSet.flatMap((item) => (item.queueId !== null ? [item.spaceId] : [])));\n    if (!this.#feedStore || spaceIds.size === 0) {\n      return workingSet;\n    }\n    const maxAges = new Map<string, number>();\n    for (const spaceId of spaceIds) {\n      for (const [feedId, options] of await this.#listFeedOptions(spaceId)) {\n        if (options.retention?.maxAge !== undefined) {\n          maxAges.set(`${spaceId}/${feedId}`, options.retention.maxAge);\n        }\n      }\n    }\n    if (maxAges.size === 0) {\n      return workingSet;\n    }\n    return workingSet.filter((item) => {\n      // A collapsed group stands for members the row does not list, so it cannot drop one of them.\n      const maxAge =\n        item.queueId !== null && item.groupKey === undefined\n          ? maxAges.get(`${item.spaceId}/${item.queueId}`)\n          : undefined;\n      return maxAge === undefined || item.updatedAt === null || item.updatedAt >= now - maxAge;\n    });\n  }\n\n  /**\n   * The current items of the store-read feeds `refs` names, one per object id at its latest block.\n   * A partial block (a removal tombstone) keeps the body of the block before it, as the index does.\n   */\n  async #readStoreFeedItems(refs: readonly QueueRef[]): Promise<QueryItem[]> {\n    const feedStore = this.#feedStore;\n    if (!feedStore) {\n      return [];\n    }\n    const items: QueryItem[] = [];\n    for (const ref of refs) {\n      const feed = this.#storeFeeds.get(ref.queueId);\n      if (!feed || (ref.spaceId !== undefined && ref.spaceId !== feed.spaceId) || !EntityId.isValid(ref.queueId)) {\n        continue;\n      }\n      const { blocks } = await this._runInRuntime(\n        feedStore.query({\n          spaceId: feed.spaceId,\n          feedNamespace: feed.feedNamespace,\n          query: { feedIds: [ref.queueId] },\n        }),\n      );\n      const byId = new Map<string, QueryItem>();\n      for (const block of [...blocks].sort((left, right) => (left.insertionId ?? 0) - (right.insertionId ?? 0))) {\n        const data = EchoFeedCodec.decodeBlock(block);\n        const previous = typeof data.id === 'string' ? byId.get(data.id)?.data : undefined;\n        const merged = data[ATTR_TYPE] === undefined && previous ? { ...previous, ...data } : data;\n        if (!isObjectJSON(merged)) {\n          continue;\n        }\n        const objectId = merged.id;\n        byId.set(objectId, {\n          objectId,\n          spaceId: feed.spaceId,\n          queueId: ref.queueId,\n          queueNamespace: feed.feedNamespace,\n          documentId: null,\n          doc: null,\n          data: merged,\n          rank: 1,\n          createdAt: block.timestamp,\n          updatedAt: block.timestamp,\n          position: block.position,\n        });\n      }\n      items.push(...[...byId.values()].filter((item) => item.data !== null && isOnBranches(item.data, ref.branches)));\n    }\n    return items;\n  }\n\n  /**\n   * The items of a walk of one feed after the cursor of `range`, in walk order, each once at the place of its\n   * first block on the walk and with the content of its latest one [D-69]. The direction is the natural order\n   * the query asks for.\n   */\n  /**\n   * A walk of every branch: the store's blocks after the cursor (before it, walking backward), in local order, so a\n   * page costs the blocks it reads rather than the feed. Each item comes once, at the first of its blocks the page\n   * holds, with the content of its latest; an item changed after the cursor comes again, since whether it started\n   * before the cursor is only known by reading the blocks there [D-75]. A backward walk with a limit reads pages from\n   * the end until the selector keeps enough.\n   */\n  async #walkAll(\n    scope: QueryAST.FeedScope,\n    range: QueryPlan.SelectStep['feedCursorRange'],\n    select: (items: QueryItem[]) => Promise<QueryItem[]>,\n    limit: number | undefined,\n  ): Promise<{ selected: QueryItem[]; read: number }> {\n    const feedStore = this.#feedStore;\n    const ref = extractQueueRefs([scope])?.[0];\n    const feed = ref === undefined ? undefined : this.#storeFeeds.get(ref.queueId);\n    if (!feedStore || ref === undefined || feed === undefined) {\n      return { selected: [], read: 0 };\n    }\n    if (range?.end !== undefined || range?.positions === 'edge') {\n      throw new QueryError({\n        message: 'A walk starts after a local cursor and has no end cursor.',\n        context: { query: null },\n      });\n    }\n    const direction = walkDirection(this.#uncompiledPlan);\n    const after = range?.begin ? parseLocalCursor(range.begin)?.block : undefined;\n    const read = (pageLimit: number | undefined) =>\n      this._runInRuntime(\n        feedStore.walk({\n          spaceId: feed.spaceId,\n          feedNamespace: feed.feedNamespace,\n          feedId: ref.queueId,\n          branch: 'all',\n          direction,\n          ...(after !== undefined ? { after } : {}),\n          ...(pageLimit !== undefined ? { limit: pageLimit } : {}),\n        }),\n      );\n    const toItems = (blocks: readonly FeedProtocol.Block[]): QueryItem[] => {\n      const items = new Map<string, { first: FeedProtocol.Block; last: FeedProtocol.Block; data: Obj.JSON | null }>();\n      for (const block of direction === 'desc' ? [...blocks].reverse() : blocks) {\n        const data = EchoFeedCodec.decodeBlock(block);\n        const id = typeof data.id === 'string' ? data.id : undefined;\n        if (id === undefined) {\n          continue;\n        }\n        const previous = items.get(id);\n        // A partial block (a removal tombstone) keeps the body of the block before it, as the index does.\n        const merged = data[ATTR_TYPE] === undefined && previous?.data ? { ...previous.data, ...data } : data;\n        items.set(id, { first: previous?.first ?? block, last: block, data: isObjectJSON(merged) ? merged : null });\n      }\n      // In the walk's direction: the step cuts its limit before any ordering, so the first items must be the ones\n      // the walk reaches first.\n      const ordered = [...items.entries()].sort(\n        ([, left], [, right]) =>\n          (direction === 'desc' ? -1 : 1) * ((left.first.insertionId ?? 0) - (right.first.insertionId ?? 0)),\n      );\n      return ordered.flatMap(([objectId, { first, last, data }]): QueryItem[] =>\n        data === null || !EntityId.isValid(objectId)\n          ? []\n          : [\n              {\n                objectId: EntityId.make(objectId),\n                spaceId: feed.spaceId,\n                queueId: ref.queueId,\n                queueNamespace: feed.feedNamespace,\n                documentId: null,\n                doc: null,\n                data,\n                rank: 1,\n                createdAt: first.timestamp,\n                updatedAt: last.timestamp,\n                position: last.position,\n                walkIndex: first.insertionId ?? 0,\n              },\n            ],\n      );\n    };\n\n    if (direction === 'asc' || limit === undefined) {\n      const blocks = await read(undefined);\n      return { selected: await select(toItems(blocks)), read: blocks.length };\n    }\n    // Pages grow fourfold, so a selector that keeps few of the blocks still ends in a handful of reads.\n    for (let pageLimit = Math.max(limit * 4, 8); ; pageLimit *= 4) {\n      const blocks = await read(pageLimit);\n      const selected = await select(toItems(blocks));\n      if (selected.length >= limit || blocks.length < pageLimit) {\n        return { selected, read: blocks.length };\n      }\n    }\n  }\n\n  async #walkFeed(scope: QueryAST.FeedScope, range: QueryPlan.SelectStep['feedCursorRange']): Promise<QueryItem[]> {\n    const feedStore = this.#feedStore;\n    const ref = extractQueueRefs([scope])?.[0];\n    const feed = ref === undefined ? undefined : this.#storeFeeds.get(ref.queueId);\n    if (!feedStore || ref === undefined || feed === undefined) {\n      return [];\n    }\n    if (range?.end !== undefined || range?.positions === 'edge') {\n      throw new QueryError({\n        message: 'A walk starts after a local cursor and has no end cursor.',\n        context: { query: null },\n      });\n    }\n    const direction = walkDirection(this.#uncompiledPlan);\n    const cursor = range?.begin ? parseLocalCursor(range.begin) : undefined;\n    // The whole path, read forward: an item's place is its first block, which may lie before the cursor.\n    const branch = scope.walk?.branch !== undefined ? scope.walk.branch : direction === 'desc' ? cursor?.branch : null;\n    const blocks = await this._runInRuntime(\n      feedStore.walk({\n        spaceId: feed.spaceId,\n        feedNamespace: feed.feedNamespace,\n        feedId: ref.queueId,\n        ...(branch !== undefined ? { branch } : {}),\n        direction: 'asc',\n        forks: scope.walk?.forks === true,\n      }),\n    );\n\n    // Each item once: placed at its first block, with the content of its latest one.\n    const items = new Map<string, { first: number; last: number; data: Obj.JSON | null }>();\n    const blockItems: (string | undefined)[] = [];\n    blocks.forEach((block, index) => {\n      const data = EchoFeedCodec.decodeBlock(block);\n      const id = typeof data.id === 'string' ? data.id : undefined;\n      blockItems.push(id);\n      if (id === undefined) {\n        return;\n      }\n      const previous = items.get(id);\n      // A partial block (a removal tombstone) keeps the body of the block before it, as the index does.\n      const merged = data[ATTR_TYPE] === undefined && previous?.data ? { ...previous.data, ...data } : data;\n      items.set(id, { first: previous?.first ?? index, last: index, data: isObjectJSON(merged) ? merged : null });\n    });\n\n    // A cursor names the latest block of an item, so the walk resumes after the place of that item.\n    let after: number | undefined;\n    if (cursor !== undefined) {\n      const cursorIndex = blocks.findIndex(\n        (block) => EchoFeedCodec.blockId(block.actorId, block.sequence) === cursor.block,\n      );\n      const cursorItem = cursorIndex === -1 ? undefined : blockItems[cursorIndex];\n      after = cursorItem === undefined ? undefined : items.get(cursorItem)?.first;\n      if (after === undefined) {\n        return [];\n      }\n    }\n\n    const sign = direction === 'desc' ? -1 : 1;\n    return [...items.entries()]\n      .filter(([, { first }]) => after === undefined || sign * (first - after) > 0)\n      .sort(([, left], [, right]) => sign * (left.first - right.first))\n      .flatMap(([objectId, { first, last, data }]): QueryItem[] => {\n        if (data === null || !EntityId.isValid(objectId)) {\n          return [];\n        }\n        const block = blocks[last];\n        return [\n          {\n            objectId: EntityId.make(objectId),\n            spaceId: feed.spaceId,\n            queueId: ref.queueId,\n            queueNamespace: feed.feedNamespace,\n            documentId: null,\n            doc: null,\n            data,\n            rank: 1,\n            createdAt: blocks[first].timestamp,\n            updatedAt: block.timestamp,\n            position: block.position,\n            walkIndex: first,\n          },\n        ];\n      });\n  }\n\n  private async _execPlan(plan: QueryPlan.Plan, workingSet: QueryItem[]): Promise<StepExecutionResult> {\n    const trace = ExecutionTrace.makeEmpty();\n    for (const step of plan.steps) {\n      if (this._ctx.disposed) {\n        throw new ContextDisposedError();\n      }\n\n      const result = await this._execStep(step, workingSet);\n      workingSet = result.workingSet;\n      trace.children.push(result.trace);\n    }\n    trace.objectCount = workingSet.length;\n    ExecutionTrace.markEnd(trace);\n    return { workingSet, trace };\n  }\n\n  private async _execStep(step: QueryPlan.Step, workingSet: QueryItem[]): Promise<StepExecutionResult> {\n    if (this._ctx.disposed) {\n      return { workingSet, trace: ExecutionTrace.makeEmpty() };\n    }\n    let newWorkingSet: QueryItem[], trace: ExecutionTrace;\n\n    const begin = performance.now();\n    switch (step._tag) {\n      case 'ClearWorkingSetStep':\n        newWorkingSet = [];\n        trace = ExecutionTrace.makeEmpty();\n        break;\n      case 'SelectStep':\n        ({ workingSet: newWorkingSet, trace } = await this._execSelectStep(step, workingSet));\n        break;\n      case 'FilterStep':\n        ({ workingSet: newWorkingSet, trace } = await this._execFilterStep(step, workingSet));\n        break;\n      case 'FilterDeletedStep':\n        ({ workingSet: newWorkingSet, trace } = await this._execFilterDeletedStep(step, workingSet));\n        break;\n      case 'UnionStep':\n        ({ workingSet: newWorkingSet, trace } = await this._execUnionStep(step, workingSet));\n        break;\n      case 'SetDifferenceStep':\n        ({ workingSet: newWorkingSet, trace } = await this._execSetDifferenceStep(step, workingSet));\n        break;\n      case 'TraverseStep':\n        ({ workingSet: newWorkingSet, trace } = await this._execTraverseStep(step, workingSet));\n        break;\n      case 'OrderStep':\n        ({ workingSet: newWorkingSet, trace } = await this._execOrderStep(step, workingSet));\n        break;\n      case 'LimitStep':\n        ({ workingSet: newWorkingSet, trace } = await this._execLimitStep(step, workingSet));\n        break;\n      case 'SkipStep':\n        ({ workingSet: newWorkingSet, trace } = await this._execSkipStep(step, workingSet));\n        break;\n      case 'AggregateStep':\n        ({ workingSet: newWorkingSet, trace } = await this._execAggregateStep(step, workingSet));\n        break;\n      case 'SqlStep':\n        ({ workingSet: newWorkingSet, trace } = await this._execSqlStep(step));\n        break;\n      default:\n        throw new Error(`Unknown step type: ${(step as any)._tag}`);\n    }\n    trace.beginTs = begin;\n    ExecutionTrace.markEnd(trace);\n\n    return { workingSet: newWorkingSet, trace };\n  }\n\n  private async _execSelectStep(step: QueryPlan.SelectStep, workingSet: QueryItem[]): Promise<StepExecutionResult> {\n    workingSet = [...workingSet];\n\n    const execSpaceScopes = step.scope.filter((s): s is QueryAST.SpaceScope => s._tag === 'space');\n    const spaces = execSpaceScopes.map((s) => s.spaceId as SpaceId);\n    const scopedQueues = step.scope.filter((s): s is QueryAST.FeedScope => s._tag === 'feed');\n    const allQueuesFromSpaces = execSpaceScopes.some((s) => s.includeAllFeeds === true);\n\n    const trace: ExecutionTrace = {\n      ...ExecutionTrace.makeEmpty(),\n      name: 'Select',\n      details: JSON.stringify(step.selector),\n      beginTs: performance.now(),\n    };\n\n    const walkScopes = scopedQueues.filter((scope) => scope.walk !== undefined);\n    if (walkScopes.length > 0) {\n      if (scopedQueues.length > 1 || execSpaceScopes.length > 0) {\n        throw new QueryError({ message: 'A walk reads one feed scope alone.', context: { query: null } });\n      }\n      // The walk itself is the window, so the selector applies without the cursor range the walk consumed.\n      const select = (items: QueryItem[]) =>\n        selectStoreItems({ ...step, feedCursorRange: undefined, feedScan: undefined }, items);\n      // A page of a walk counts what the plan keeps of it; the filter steps run again on the result, unchanged.\n      const narrowing = this.#uncompiledPlan.steps.filter(\n        (planStep): planStep is QueryPlan.FilterStep | QueryPlan.FilterDeletedStep =>\n          planStep._tag === 'FilterStep' || planStep._tag === 'FilterDeletedStep',\n      );\n      const keep = async (items: QueryItem[]) => {\n        let kept = select(items);\n        for (const planStep of narrowing) {\n          kept = (\n            planStep._tag === 'FilterStep'\n              ? await this._execFilterStep(planStep, kept)\n              : await this._execFilterDeletedStep(planStep, kept)\n          ).workingSet;\n        }\n        return kept;\n      };\n      const { selected, read } =\n        walkScopes[0].walk?.branch === 'all'\n          ? await this.#walkAll(\n              walkScopes[0],\n              step.feedCursorRange,\n              keep,\n              step.limit ?? walkLimit(this.#uncompiledPlan),\n            )\n          : await this.#walkFeed(walkScopes[0], step.feedCursorRange).then((walked) => ({\n              selected: select(walked),\n              read: walked.length,\n            }));\n      workingSet.push(...(step.limit === undefined ? selected : selected.slice(0, step.limit)));\n      trace.documentsLoaded += read;\n      trace.objectCount = workingSet.length;\n      return { workingSet, trace };\n    }\n\n    // A feed with indexing disabled has no index rows, so its items come from the store, selected here.\n    const isStoreFeed = (scope: QueryAST.FeedScope) => {\n      const ref = extractQueueRefs([scope])?.[0];\n      return ref !== undefined && this.#storeFeeds.has(ref.queueId);\n    };\n    const allFeedsSpaces = new Set(execSpaceScopes.flatMap((s) => (s.includeAllFeeds === true ? [s.spaceId] : [])));\n    const storeRefs = new Map<string, QueueRef>([\n      ...[...this.#storeFeeds]\n        .filter(([, feed]) => allFeedsSpaces.has(feed.spaceId))\n        // A read of every feed is a default read, so it covers only the main branch.\n        .map(([queueId, feed]): [string, QueueRef] => [queueId, { queueId, spaceId: feed.spaceId, branches: [null] }]),\n    ]);\n    // Several scopes of one feed read it once, over the union of their branches.\n    for (const ref of extractQueueRefs(scopedQueues.filter(isStoreFeed)) ?? []) {\n      const previous = storeRefs.get(ref.queueId);\n      storeRefs.set(ref.queueId, previous === undefined ? ref : { ...ref, branches: unionBranches(previous, ref) });\n    }\n    const queues = scopedQueues.filter((scope) => !isStoreFeed(scope));\n    if (storeRefs.size > 0) {\n      const storeItems = selectStoreItems(step, await this.#readStoreFeedItems([...storeRefs.values()]));\n      workingSet.push(...storeItems);\n      trace.documentsLoaded += storeItems.length;\n      if (queues.length === 0 && spaces.length === 0) {\n        if (step.limit !== undefined && workingSet.length > step.limit) {\n          workingSet = workingSet.slice(0, step.limit);\n        }\n        trace.objectCount = workingSet.length;\n        return { workingSet, trace };\n      }\n    }\n\n    switch (step.selector._tag) {\n      case 'WildcardSelector': {\n        const beginIndexQuery = performance.now();\n        const queueRefs = withFeedCutoffs(extractQueueRefs(queues), this.#feedCutoffs);\n        const metas = await this._queryAllFromSqlIndex(\n          spaces,\n          allQueuesFromSpaces,\n          queueRefs,\n          extractQueueWindow(step),\n        );\n        trace.indexHits = metas.length;\n        trace.indexQueryTime += performance.now() - beginIndexQuery;\n\n        if (this._ctx.disposed) {\n          return { workingSet, trace };\n        }\n\n        const documentLoadStart = performance.now();\n        const results = step.bare ? metas.map(QueryItem.fromIndexRow) : await this._loadDocumentsAfterSqlQuery(metas);\n        trace.documentsLoaded += step.bare ? 0 : results.length;\n        trace.documentLoadTime += performance.now() - documentLoadStart;\n\n        workingSet.push(...results.filter(isNonNullable));\n        trace.objectCount = workingSet.length;\n\n        break;\n      }\n\n      case 'IdSelector': {\n        const beginLoad = performance.now();\n\n        if (allQueuesFromSpaces && spaces.length > 0) {\n          const objectIds = step.selector.objectIds.filter((id) => EntityId.isValid(id));\n          if (objectIds.length > 0) {\n            const metas = await this._runInRuntime(this._indexEngine.queryObjectIds({ spaceIds: spaces, objectIds }));\n            const results = await this._loadDocumentsAfterSqlQuery(metas);\n            trace.documentLoadTime += performance.now() - beginLoad;\n            workingSet.push(...results.filter(isNonNullable));\n            trace.objectCount = workingSet.length;\n            break;\n          }\n        }\n\n        const items = await Promise.all(\n          step.selector.objectIds.map(async (id) => {\n            if (!EntityId.isValid(id)) {\n              return null;\n            }\n            if (queues.length > 0) {\n              const ref = extractQueueRefs([queues[0]])?.[0];\n              if (ref?.spaceId !== undefined && SpaceId.isValid(ref.spaceId) && EntityId.isValid(ref.queueId)) {\n                const item = await this._loadQueueItemById(ref.spaceId, ref.queueId, id);\n                return item?.data && isOnBranches(item.data, ref.branches) ? item : null;\n              }\n              return null;\n            } else if (spaces.length > 0) {\n              return this._loadFromDXN(EID.make({ entityId: id }), { sourceSpaceId: spaces[0] });\n            } else {\n              return null; // Unknown scope.\n            }\n          }),\n        );\n        trace.documentLoadTime += performance.now() - beginLoad;\n\n        workingSet.push(...items.filter(isNonNullable));\n        trace.objectCount = workingSet.length;\n        break;\n      }\n\n      case 'TypeSelector': {\n        const beginIndexQuery = performance.now();\n        const queueRefs = withFeedCutoffs(extractQueueRefs(queues), this.#feedCutoffs);\n        const metas = await this._queryTypesFromSqlIndex(\n          spaces,\n          step.selector.typename,\n          step.selector.inverted,\n          allQueuesFromSpaces,\n          queueRefs,\n          extractQueueWindow(step),\n        );\n        trace.indexHits = metas.length;\n        trace.indexQueryTime += performance.now() - beginIndexQuery;\n\n        if (this._ctx.disposed) {\n          return { workingSet, trace };\n        }\n\n        const documentLoadStart = performance.now();\n        const results = step.bare ? metas.map(QueryItem.fromIndexRow) : await this._loadDocumentsAfterSqlQuery(metas);\n        trace.documentsLoaded += step.bare ? 0 : results.length;\n        trace.documentLoadTime += performance.now() - documentLoadStart;\n\n        workingSet.push(...results.filter(isNonNullable));\n        trace.objectCount = workingSet.length;\n\n        break;\n      }\n\n      case 'TimestampSelector': {\n        const beginIndexQuery = performance.now();\n        const queueRefs = withFeedCutoffs(extractQueueRefs(queues), this.#feedCutoffs);\n        const metas = await this._runInRuntime(\n          this._indexEngine.queryByTimeRange({\n            spaceIds: spaces,\n            updatedAfter: step.selector.updatedAfter,\n            updatedBefore: step.selector.updatedBefore,\n            createdAfter: step.selector.createdAfter,\n            createdBefore: step.selector.createdBefore,\n            includeAllQueues: allQueuesFromSpaces,\n            queues: queueRefs,\n          }),\n        );\n        trace.indexHits = metas.length;\n        trace.indexQueryTime += performance.now() - beginIndexQuery;\n\n        if (this._ctx.disposed) {\n          return { workingSet, trace };\n        }\n\n        const documentLoadStart = performance.now();\n        const results = step.bare ? metas.map(QueryItem.fromIndexRow) : await this._loadDocumentsAfterSqlQuery(metas);\n        trace.documentsLoaded += step.bare ? 0 : results.length;\n        trace.documentLoadTime += performance.now() - documentLoadStart;\n\n        workingSet.push(...results.filter(isNonNullable));\n        trace.objectCount = workingSet.length;\n\n        break;\n      }\n\n      case 'ChangesSelector':\n        throw new Error('A changes plan runs through executeChangesPlan.');\n\n      case 'IncomingReferenceSelector': {\n        const beginIndexQuery = performance.now();\n        const metas = await this._queryIncomingReferencesByTarget([step.selector.targetDXN], step.selector.property);\n        trace.indexHits = metas.length;\n        trace.indexQueryTime += performance.now() - beginIndexQuery;\n\n        if (this._ctx.disposed) {\n          return { workingSet, trace };\n        }\n\n        const documentLoadStart = performance.now();\n        // The index is per-space, but the scope may name a subset of the queried spaces.\n        const scoped = spaces.length > 0 ? metas.filter((meta) => spaces.includes(meta.spaceId)) : metas;\n        const results = await this._loadDocumentsAfterSqlQuery(scoped);\n        trace.documentsLoaded += results.length;\n        trace.documentLoadTime += performance.now() - documentLoadStart;\n\n        workingSet.push(...results.filter(isNonNullable));\n        trace.objectCount = workingSet.length;\n\n        break;\n      }\n\n      case 'TextSelector': {\n        // TODO(dmaretskyi): nice to have matched text snippets/highlighting.\n        if (step.selector.searchKind === 'vector') {\n          // Vector search is not currently supported.\n          log.warn('Vector search is not supported');\n          break;\n        }\n\n        // Full-text search using SQLite FTS5, optionally scoped by type.\n        const beginIndexQuery = performance.now();\n        invariant(spaces.length <= 1, 'Multiple spaces are not supported for full-text search');\n        const queueRefs = withFeedCutoffs(extractQueueRefs(queues), this.#feedCutoffs);\n        const textResults = await this._runInRuntime(\n          this._indexEngine.queryText({\n            query: step.selector.text,\n            spaceId: spaces,\n            includeAllQueues: allQueuesFromSpaces,\n            queues: queueRefs,\n            typeDxns: step.selector.typename,\n          }),\n        );\n        trace.indexHits = textResults.length;\n        trace.indexQueryTime += performance.now() - beginIndexQuery;\n\n        if (this._ctx.disposed) {\n          return { workingSet, trace };\n        }\n\n        // Load documents from the results.\n        const documentLoadStart = performance.now();\n\n        // Separate queue items from space items.\n        const queueResults = textResults.filter((r) => r.queueId);\n        const spaceResults = textResults.filter((r) => !r.queueId);\n\n        // Build a map from recordId to rank for all FTS results.\n        const rankMap = new Map(textResults.map((r) => [r.recordId, r.rank]));\n\n        // Load queue items from indexed snapshots.\n        let queueItems: QueryItem[] = [];\n        if (queueResults.length > 0) {\n          const snapshots = await this._runInRuntime(\n            this._indexEngine.querySnapshotsJSON(queueResults.map((r) => r.recordId)),\n          );\n          const snapshotMap = new Map(snapshots.map((s) => [s.recordId, s.snapshot]));\n          queueItems = queueResults\n            .map((result): QueryItem | null => {\n              const snapshot = snapshotMap.get(result.recordId);\n              if (!snapshot || typeof snapshot !== 'object') {\n                return null;\n              }\n              if (!EntityId.isValid(result.queueId)) {\n                return null;\n              }\n              return {\n                objectId: result.objectId,\n                spaceId: result.spaceId,\n                queueId: result.queueId,\n                queueNamespace: result.queueNamespace || null,\n                documentId: null,\n                doc: null,\n                data: snapshot as Obj.JSON,\n                rank: rankMap.get(result.recordId) ?? 1,\n                createdAt: result.createdAt,\n                updatedAt: result.updatedAt,\n              };\n            })\n            .filter(isNonNullable);\n        }\n\n        // Load space items from documents.\n        const spaceItems = await Promise.all(\n          spaceResults.map(async (result): Promise<QueryItem | null> => {\n            const dxn = EID.make({ entityId: result.objectId });\n            const item = await this._loadFromDXN(dxn, { sourceSpaceId: result.spaceId });\n            if (item) {\n              // Override the default rank with the FTS rank.\n              item.rank = rankMap.get(result.recordId) ?? 1;\n            }\n            return item;\n          }),\n        );\n\n        const items = [...queueItems, ...spaceItems.filter(isNonNullable)];\n        trace.documentsLoaded += items.length;\n        trace.documentLoadTime += performance.now() - documentLoadStart;\n\n        workingSet.push(\n          ...items.filter((item) => {\n            if (spaces.includes(item.spaceId)) {\n              return true;\n            }\n            if (item.queueId) {\n              return queues.some((scope) => {\n                const queueId = extractQueueRefs([scope])?.[0]?.queueId;\n                const spaceId = extractSpaceIdFromQueue(String(scope.feedUri));\n                return queueId === item.queueId && spaceId === item.spaceId;\n              });\n            }\n            return false;\n          }),\n        );\n        trace.objectCount = workingSet.length;\n        break;\n      }\n\n      default:\n        throw new Error(`Unknown selector type: ${(step.selector as any)._tag}`);\n    }\n\n    // Apply limit if specified on the select step.\n    if (step.limit !== undefined && workingSet.length > step.limit) {\n      workingSet = workingSet.slice(0, step.limit);\n      trace.objectCount = workingSet.length;\n    }\n\n    return { workingSet, trace };\n  }\n\n  private async _execFilterStep(step: QueryPlan.FilterStep, workingSet: QueryItem[]): Promise<StepExecutionResult> {\n    if (step.filter.type === 'child-of') {\n      return this._execChildOfFilterStep(step.filter, workingSet);\n    }\n\n    const timestampParams = extractTimestampParams(step.filter);\n    if (timestampParams !== null) {\n      return this._execTimestampFilterStep(step, workingSet, timestampParams);\n    }\n\n    if (filterContainsTimestamp(step.filter)) {\n      throw new QueryError({\n        message:\n          'Timestamp filter in unsupported composition (not, or). Use Filter.updated/Filter.created with explicit range instead.',\n        context: {},\n      });\n    }\n\n    // A nested `in-query` (subquery-membership) predicate is not a matcher-level concept — resolve\n    // each one to a concrete literal `in` before falling through to the normal in-memory matchers,\n    // which only know how to test a value against a static set.\n    const subqueryTraces: ExecutionTrace[] = [];\n    const filter = filterContainsInQuery(step.filter)\n      ? await this._resolveInQueryFilter(step.filter, subqueryTraces)\n      : step.filter;\n\n    const result = workingSet.filter((item) => {\n      if (item.doc) {\n        return filterMatchDoc(filter, {\n          id: item.objectId,\n          spaceId: item.spaceId,\n          doc: item.doc,\n        });\n      } else if (item.data) {\n        return filterMatchObjectJSON(filter, item.data);\n      } else if (item.meta) {\n        return filterMatchEntityMeta(filter, item.meta);\n      } else {\n        return false;\n      }\n    });\n\n    return {\n      workingSet: result,\n      trace: {\n        ...ExecutionTrace.makeEmpty(),\n        name: 'Filter',\n        details: JSON.stringify(step.filter),\n        objectCount: result.length,\n        children: subqueryTraces,\n      },\n    };\n  }\n\n  /**\n   * Recursively rewrites every `in-query` node in `filter` to a literal `in` node, resolving each\n   * subquery's projected value set at most once per `execQuery` run (see `#inQuerySetCache`).\n   * `subqueryTraces` collects the resolution's `ExecutionTrace` the first time each subquery is\n   * resolved this run, so its cost is visible under the FilterStep that triggered it.\n   */\n  private async _resolveInQueryFilter(\n    filter: QueryAST.Filter,\n    subqueryTraces: ExecutionTrace[],\n  ): Promise<QueryAST.Filter> {\n    switch (filter.type) {\n      case 'in-query': {\n        const { values, trace } = await this._resolveInQuerySet(filter);\n        const cacheKey = _inQueryCacheKey(filter);\n        if (!this.#inQueryTracesAttached.has(cacheKey)) {\n          this.#inQueryTracesAttached.add(cacheKey);\n          subqueryTraces.push(trace);\n        }\n        return { type: 'in', values: [...values] };\n      }\n      case 'object': {\n        if (Object.keys(filter.props).length === 0) {\n          return filter;\n        }\n        const props: Record<string, QueryAST.Filter> = {};\n        for (const [key, propFilter] of Object.entries(filter.props)) {\n          props[key] = await this._resolveInQueryFilter(propFilter, subqueryTraces);\n        }\n        return { ...filter, props };\n      }\n      case 'not':\n        return { ...filter, filter: await this._resolveInQueryFilter(filter.filter, subqueryTraces) };\n      case 'and':\n        return {\n          ...filter,\n          filters: await Promise.all(filter.filters.map((f) => this._resolveInQueryFilter(f, subqueryTraces))),\n        };\n      case 'or':\n        return {\n          ...filter,\n          filters: await Promise.all(filter.filters.map((f) => this._resolveInQueryFilter(f, subqueryTraces))),\n        };\n      default:\n        return filter;\n    }\n  }\n\n  /**\n   * Resolves a single `in-query` node's projected value set, sharing one resolution across every\n   * occurrence of the same subquery+property within this `execQuery` run (e.g. both branches of a\n   * `Query.all` union embedding the same subquery). The `Promise` is cached (not just the value) so\n   * concurrent callers — `UnionStep` branches run under `Promise.all` — await the same in-flight\n   * resolution instead of each starting their own.\n   */\n  private _resolveInQuerySet(\n    node: QueryAST.FilterInQuery,\n  ): Promise<{ values: ReadonlySet<unknown>; trace: ExecutionTrace }> {\n    const cacheKey = _inQueryCacheKey(node);\n    let cached = this.#inQuerySetCache.get(cacheKey);\n    if (!cached) {\n      cached = this._computeInQuerySet(node);\n      this.#inQuerySetCache.set(cacheKey, cached);\n    }\n    return cached;\n  }\n\n  private async _computeInQuerySet(\n    node: QueryAST.FilterInQuery,\n  ): Promise<{ values: ReadonlySet<unknown>; trace: ExecutionTrace }> {\n    // TODO(dmaretskyi): Push membership into the SQL index once custom property indexes are\n    // supported, instead of a full in-memory scan of the subquery's candidates.\n    const subPlan = new QueryPlanner().createPlan(node.subquery);\n    const { workingSet: subResults, trace } = await this._execPlan(subPlan, []);\n    trace.name = 'Subquery';\n    trace.details = Query.pretty(Query.fromAst(node.subquery));\n\n    const values = new Set<unknown>();\n    for (const item of subResults) {\n      const rawValue = QueryItem.getProperty(item, [node.property]);\n      // Omit missing/null projected values so a subquery object lacking the property never\n      // broadens the membership set (it must not make parents that also lack the property match).\n      if (rawValue === undefined || rawValue === null) {\n        continue;\n      }\n      values.add(isEncodedReference(rawValue) ? EncodedReference.toURI(rawValue) : rawValue);\n    }\n    return { values, trace };\n  }\n\n  private async _execTimestampFilterStep(\n    step: QueryPlan.FilterStep,\n    workingSet: QueryItem[],\n    params: { updatedAfter?: number; updatedBefore?: number; createdAfter?: number; createdBefore?: number },\n  ): Promise<StepExecutionResult> {\n    const spaces = [...new Set(workingSet.map((item) => item.spaceId).filter(isNonNullable))];\n    const metas = await this._runInRuntime(\n      this._indexEngine.queryByTimeRange({\n        spaceIds: spaces,\n        ...params,\n        includeAllQueues: false,\n        queues: [],\n      }),\n    );\n    const matchingIds = new Set(metas.map((m) => m.objectId));\n    const result = workingSet.filter((item) => matchingIds.has(item.objectId));\n    return {\n      workingSet: result,\n      trace: {\n        ...ExecutionTrace.makeEmpty(),\n        name: 'Filter(timestamp)',\n        details: JSON.stringify(params),\n        objectCount: result.length,\n      },\n    };\n  }\n\n  private async _execFilterDeletedStep(\n    step: QueryPlan.FilterDeletedStep,\n    workingSet: QueryItem[],\n  ): Promise<StepExecutionResult> {\n    const expected = step.mode === 'only-deleted';\n\n    const deletedState = workingSet.map((item) => QueryItem.isDeleted(item));\n    await Promise.all(\n      workingSet.map(async (item, index) => {\n        if (deletedState[index]) {\n          return;\n        }\n        deletedState[index] ||= await this._getTransitiveDeletionState(item, MAX_DEPTH_FOR_DELETION_TRACING);\n      }),\n    );\n\n    const result = workingSet.filter((item, index) => deletedState[index] === expected);\n\n    // TODO(dmaretskyi): How do we handle items with parents and cascade deletions? -- perhaps we forbid queue items from having parents -- i.e. queue is their parent.\n    return {\n      workingSet: result,\n      trace: {\n        ...ExecutionTrace.makeEmpty(),\n        name: 'FilterDeleted',\n        details: step.mode,\n        objectCount: result.length,\n      },\n    };\n  }\n\n  private async _execChildOfFilterStep(\n    filter: QueryAST.FilterChildOf,\n    workingSet: QueryItem[],\n  ): Promise<StepExecutionResult> {\n    const parentObjectIds = new Set<EntityId>();\n    for (const parentDxnStr of filter.parents) {\n      const echoUri = EID.tryParse(parentDxnStr);\n      if (echoUri) {\n        const objectId = EID.getEntityId(echoUri);\n        if (objectId) {\n          parentObjectIds.add(objectId);\n        }\n      }\n    }\n    const maxDepth = filter.transitive ? MAX_DEPTH_FOR_CHILD_OF_TRACING : 1;\n\n    const trace = ExecutionTrace.makeEmpty();\n    const beginIndexQuery = performance.now();\n    const ownerIds = await this._collectChildOfOwners(parentObjectIds, maxDepth, workingSet, trace);\n    trace.indexQueryTime += performance.now() - beginIndexQuery;\n\n    const result = workingSet.filter((item) => {\n      const ownerId = childOfOwnerId(item);\n      return ownerId !== undefined && ownerIds.has(ownerId);\n    });\n\n    return {\n      workingSet: result,\n      trace: {\n        ...trace,\n        name: 'Filter(child-of)',\n        details: JSON.stringify({ parents: filter.parents, transitive: filter.transitive }),\n        objectCount: result.length,\n      },\n    };\n  }\n\n  /**\n   * The ids an item's direct owner must be among to sit within `maxDepth` levels of a parent: the parents\n   * and their descendants down to `maxDepth - 1` levels, walked down the children index so that no\n   * ancestor document of any working-set item is loaded.\n   */\n  private async _collectChildOfOwners(\n    parentObjectIds: ReadonlySet<EntityId>,\n    maxDepth: number,\n    workingSet: readonly QueryItem[],\n    trace: ExecutionTrace,\n  ): Promise<Set<EntityId>> {\n    const ownerIds = new Set(parentObjectIds);\n    if (maxDepth <= 1 || ownerIds.size === 0 || workingSet.length === 0) {\n      return ownerIds;\n    }\n\n    const spaceIds = [...new Set(workingSet.map((item) => item.spaceId))];\n    let frontier = [...ownerIds];\n    for (let depth = 1; depth < maxDepth && frontier.length > 0; depth++) {\n      const children = await this._runInRuntime(\n        this._indexEngine.queryChildren({ spaceId: spaceIds, parentIds: frontier }),\n      );\n      trace.indexHits += children.length;\n      frontier = [];\n      for (const child of children) {\n        // Only a document owns further objects; a feed item is a leaf.\n        if (child.queueId === '' && !ownerIds.has(child.objectId)) {\n          ownerIds.add(child.objectId);\n          frontier.push(child.objectId);\n        }\n      }\n    }\n    return ownerIds;\n  }\n\n  // TODO(dmaretskyi): This needs to be completed.\n  private async _execTraverseStep(step: QueryPlan.TraverseStep, workingSet: QueryItem[]): Promise<StepExecutionResult> {\n    const trace: ExecutionTrace = {\n      ...ExecutionTrace.makeEmpty(),\n      name: 'Traverse',\n      details: JSON.stringify(step.traversal),\n    };\n\n    // Every item reached, with the edge that reached it; items reached more than once are merged below.\n    const reached: { item: QueryItem; from: QueryItem; edge: TraversalEdge | undefined }[] = [];\n\n    switch (step.traversal._tag) {\n      case 'ReferenceTraversal': {\n        switch (step.traversal.direction) {\n          case 'outgoing': {\n            invariant(step.traversal.property !== null, 'Outgoing reference traversal requires a property');\n            const escapedProperty = step.traversal.property;\n            const property = EscapedPropPath.unescape(escapedProperty);\n\n            const refs = workingSet.flatMap((item) => {\n              const ref = QueryItem.getProperty(item, property);\n              const refs = Array.isArray(ref) ? ref : [ref];\n              return refs.flatMap((ref) => {\n                try {\n                  return isEncodedReference(ref) ? [{ ref: EncodedReference.toURI(ref), from: item }] : [];\n                } catch {\n                  log.warn('invalid reference', { ref: ref['/'] });\n                  return [];\n                }\n              });\n            });\n\n            const beginLoad = performance.now();\n            const items = await Promise.all(\n              refs.map(({ ref, from }) => this._loadReferencedTarget(ref, { sourceSpaceId: from.spaceId })),\n            );\n            trace.documentLoadTime += performance.now() - beginLoad;\n            items.forEach((item, index) => {\n              const { from } = refs[index];\n              if (item) {\n                reached.push({ item, from, edge: { kind: 'ref', property: escapedProperty, holder: from } });\n              }\n            });\n            break;\n          }\n          case 'incoming': {\n            const beginIndexQuery = performance.now();\n            const { metas, referrers } = await this.#queryIncomingReferences(workingSet, step.traversal.property);\n            trace.indexHits += metas.length;\n            trace.indexQueryTime += performance.now() - beginIndexQuery;\n\n            const documentLoadStart = performance.now();\n            const results = await this._loadDocumentsAfterSqlQuery(metas);\n            trace.documentsLoaded += results.length;\n            trace.documentLoadTime += performance.now() - documentLoadStart;\n\n            results.forEach((item, index) => {\n              if (!item) {\n                return;\n              }\n              for (const { anchor, propPath } of referrers.get(metas[index].recordId) ?? []) {\n                reached.push({ item, from: anchor, edge: { kind: 'incoming-ref', property: propPath, holder: item } });\n              }\n            });\n            break;\n          }\n        }\n        break;\n      }\n      case 'RelationTraversal': {\n        switch (step.traversal.direction) {\n          case 'relation-to-source':\n          case 'relation-to-target': {\n            const toSource = step.traversal.direction === 'relation-to-source';\n            const refs = workingSet.flatMap((item) => {\n              const dxn = toSource ? QueryItem.getRelationSource(item) : QueryItem.getRelationTarget(item);\n              return dxn ? [{ ref: dxn, from: item }] : [];\n            });\n\n            const beginLoad = performance.now();\n            const items = await Promise.all(\n              refs.map(({ ref, from }) => this._loadFromDXN(ref, { sourceSpaceId: from.spaceId })),\n            );\n            trace.documentLoadTime += performance.now() - beginLoad;\n            items.forEach((item, index) => {\n              const { from } = refs[index];\n              if (item) {\n                reached.push({\n                  item,\n                  from,\n                  edge: { kind: toSource ? 'relation-source' : 'relation-target', holder: from },\n                });\n              }\n            });\n            break;\n          }\n\n          case 'source-to-relation':\n          case 'target-to-relation': {\n            const endpoint = step.traversal.direction === 'source-to-relation' ? 'source' : 'target';\n            const beginIndexQuery = performance.now();\n            const metas = await this._queryRelationsFromSqlIndex(workingSet, endpoint);\n            trace.indexHits += metas.length;\n            trace.indexQueryTime += performance.now() - beginIndexQuery;\n\n            const documentLoadStart = performance.now();\n            const results = await this._loadDocumentsAfterSqlQuery(metas);\n            trace.documentsLoaded += results.length;\n            trace.documentLoadTime += performance.now() - documentLoadStart;\n\n            const anchors = itemsById(workingSet);\n            results.forEach((item, index) => {\n              const anchorId = entityIdOf(endpoint === 'source' ? metas[index].source : metas[index].target);\n              const from = anchorId !== undefined ? anchors.get(anchorId) : undefined;\n              if (item && from) {\n                reached.push({\n                  item,\n                  from,\n                  edge: { kind: endpoint === 'source' ? 'relation-source' : 'relation-target', holder: item },\n                });\n              }\n            });\n            break;\n          }\n        }\n        break;\n      }\n      case 'HierarchyTraversal': {\n        switch (step.traversal.direction) {\n          case 'to-parent': {\n            // Traverse from child to parent using the parent reference in the document.\n            const refs = workingSet.flatMap((item) => {\n              if (!item.doc) {\n                return []; // TODO(dmaretskyi): Queue items not supported here.\n              }\n              const ref = EntityStructure.getParent(item.doc);\n              return EncodedReference.isEncodedReference(ref) ? [{ ref: EncodedReference.toURI(ref), from: item }] : [];\n            });\n\n            const beginLoad = performance.now();\n            const items = await Promise.all(\n              refs.map(({ ref, from }) => this._loadFromDXN(ref, { sourceSpaceId: from.spaceId })),\n            );\n            trace.documentLoadTime += performance.now() - beginLoad;\n            items.forEach((item, index) => {\n              const { from } = refs[index];\n              if (item) {\n                reached.push({ item, from, edge: { kind: 'parent', holder: from } });\n              }\n            });\n            break;\n          }\n\n          case 'to-children': {\n            // Traverse from parent to children using the SQL index.\n            // Covers both standard parent/child hierarchy (via the `parent` field) and\n            // feed -> queue items (via the `queueId` field — a feed's queue id matches the feed's object id).\n            // Group working set by spaceId.\n            const bySpace = new Map<SpaceId, EntityId[]>();\n            for (const item of workingSet) {\n              const existing = bySpace.get(item.spaceId);\n              if (existing) {\n                existing.push(item.objectId);\n              } else {\n                bySpace.set(item.spaceId, [item.objectId]);\n              }\n            }\n\n            const beginIndexQuery = performance.now();\n            const allMetas: EntityMeta[] = [];\n            for (const [spaceId, parentIds] of bySpace) {\n              const children = await this._runInRuntime(\n                this._indexEngine.queryChildren({ spaceId: [spaceId], parentIds }),\n              );\n              allMetas.push(...children);\n            }\n            trace.indexHits += allMetas.length;\n            trace.indexQueryTime += performance.now() - beginIndexQuery;\n\n            const documentLoadStart = performance.now();\n            const results = await this._loadDocumentsAfterSqlQuery(allMetas);\n            trace.documentsLoaded += results.filter(isNonNullable).length;\n            trace.documentLoadTime += performance.now() - documentLoadStart;\n\n            const anchors = itemsById(workingSet);\n            results.forEach((item, index) => {\n              const meta = allMetas[index];\n              // A feed's items name it by queue id; a document child names its parent.\n              const parentId = entityIdOf(meta.parent) ?? (meta.queueId ? meta.queueId : undefined);\n              const from = parentId !== undefined ? anchors.get(parentId) : undefined;\n              if (item && from) {\n                reached.push({ item, from, edge: { kind: 'child', holder: item } });\n              } else if (item) {\n                reached.push({ item, from: item, edge: undefined });\n              }\n            });\n            break;\n          }\n        }\n        break;\n      }\n      default:\n        throw new Error(`Unknown traversal type: ${(step.traversal as any)._tag}`);\n    }\n\n    const newWorkingSet = mergeReached(reached);\n    trace.objectCount = newWorkingSet.length;\n    return { workingSet: newWorkingSet, trace };\n  }\n\n  private async _execUnionStep(step: QueryPlan.UnionStep, workingSet: QueryItem[]): Promise<StepExecutionResult> {\n    const results = new Map<EntityId, QueryItem>();\n\n    const resultSets = await Promise.all(step.plans.map((plan) => this._execPlan(plan, [...workingSet])));\n\n    const trace: ExecutionTrace = {\n      ...ExecutionTrace.makeEmpty(),\n      name: 'Union',\n    };\n\n    // NOTE: Doing insertion after execution to ensure deterministic results. Probably not needed.\n    for (const resultSet of resultSets) {\n      for (const item of resultSet.workingSet) {\n        // Could be duplicate object ids in different spaces or in different epochs of the same space.\n        results.set(compositeKey(item.spaceId, String(item.documentId), item.objectId), item);\n      }\n      trace.children.push(resultSet.trace);\n    }\n\n    return {\n      workingSet: [...results.values()],\n      trace,\n    };\n  }\n\n  private async _execSetDifferenceStep(\n    step: QueryPlan.SetDifferenceStep,\n    workingSet: QueryItem[],\n  ): Promise<StepExecutionResult> {\n    const trace: ExecutionTrace = {\n      ...ExecutionTrace.makeEmpty(),\n      name: 'SetDifference',\n    };\n\n    const sourceResult = await this._execPlan(step.source, [...workingSet]);\n    const excludeResult = await this._execPlan(step.exclude, [...workingSet]);\n    trace.children.push(sourceResult.trace, excludeResult.trace);\n\n    return {\n      workingSet: sourceResult.workingSet.filter((item) => {\n        const index = excludeResult.workingSet.findIndex((i) => i.objectId === item.objectId);\n        return index === -1;\n      }),\n      trace,\n    };\n  }\n\n  private async _execOrderStep(step: QueryPlan.OrderStep, workingSet: QueryItem[]): Promise<StepExecutionResult> {\n    // After an AggregateStep the working set is partitioned into contiguous groups; a post-group order\n    // reorders whole groups (by their aggregates), and a pushed-down limit pages over whole groups.\n    // Otherwise it sorts and slices the flat object stream.\n    let sortedWorkingSet = isGrouped(workingSet)\n      ? GroupBy.orderGroups(workingSet, serializeItemGroupKey, (a, b) => this._compareMultiOrder(a, b, step.order))\n      : [...workingSet].sort((a, b) => this._compareMultiOrder(a, b, step.order));\n\n    // Apply limit if specified on the order step.\n    if (step.limit !== undefined && sortedWorkingSet.length > step.limit) {\n      sortedWorkingSet = isGrouped(sortedWorkingSet)\n        ? GroupBy.takeGroups(sortedWorkingSet, step.limit, serializeItemGroupKey)\n        : sortedWorkingSet.slice(0, step.limit);\n    }\n\n    return {\n      workingSet: sortedWorkingSet,\n      trace: {\n        ...ExecutionTrace.makeEmpty(),\n        name: 'Order',\n        details: JSON.stringify({ order: step.order, limit: step.limit }),\n        objectCount: sortedWorkingSet.length,\n      },\n    };\n  }\n\n  private async _execLimitStep(step: QueryPlan.LimitStep, workingSet: QueryItem[]): Promise<StepExecutionResult> {\n    // After an AggregateStep the working set is partitioned into contiguous groups; limit then pages\n    // over whole groups. Otherwise it slices the flat object stream.\n    const limitedWorkingSet = isGrouped(workingSet)\n      ? GroupBy.takeGroups(workingSet, step.limit, serializeItemGroupKey)\n      : workingSet.slice(0, step.limit);\n\n    return {\n      workingSet: limitedWorkingSet,\n      trace: {\n        ...ExecutionTrace.makeEmpty(),\n        name: 'Limit',\n        details: JSON.stringify({ limit: step.limit }),\n        objectCount: limitedWorkingSet.length,\n      },\n    };\n  }\n\n  private async _execSkipStep(step: QueryPlan.SkipStep, workingSet: QueryItem[]): Promise<StepExecutionResult> {\n    const skippedWorkingSet = isGrouped(workingSet)\n      ? GroupBy.dropGroups(workingSet, step.skip, serializeItemGroupKey)\n      : workingSet.slice(step.skip);\n\n    return {\n      workingSet: skippedWorkingSet,\n      trace: {\n        ...ExecutionTrace.makeEmpty(),\n        name: 'Skip',\n        details: JSON.stringify({ skip: step.skip }),\n        objectCount: skippedWorkingSet.length,\n      },\n    };\n  }\n\n  /**\n   * Runs a compiled statement. A source step: it ignores the incoming working set, because the\n   * statement already stands for every step that produced one.\n   */\n  private async _execSqlStep(step: QueryPlan.SqlStep): Promise<StepExecutionResult> {\n    const trace = ExecutionTrace.makeEmpty();\n    const begin = performance.now();\n    const { rows, explain } = await this._runInRuntime(\n      Effect.gen(function* () {\n        const sql = yield* SqlClient.SqlClient;\n        const rows = yield* sql.unsafe<CompiledRow>(step.sql, step.params);\n        const explain = TRACE_QUERY_EXECUTION\n          ? (yield* sql.unsafe<{ detail: string }>(`EXPLAIN QUERY PLAN ${step.sql}`, step.params)).map(\n              (row) => row.detail,\n            )\n          : undefined;\n        return { rows, explain };\n      }),\n    );\n    trace.indexQueryTime = performance.now() - begin;\n    trace.indexHits = rows.length;\n    trace.objectCount = rows.length;\n    trace.sql = step.sql;\n    trace.explain = explain;\n    return { workingSet: rows.map(compiledRowToItem), trace };\n  }\n\n  private async _execAggregateStep(\n    step: QueryPlan.AggregateStep,\n    workingSet: QueryItem[],\n  ): Promise<StepExecutionResult> {\n    const withKeys = workingSet.map((item) => ({ ...item, groupKey: QueryItem.getGroupKey(item, step.aggregates) }));\n    const partitioned = GroupBy.partitionByGroupKey(withKeys, (item) => GroupBy.serializeGroupKey(item.groupKey!));\n    const stamped = GroupBy.withGroupAggregates(\n      partitioned,\n      (item) => GroupBy.serializeGroupKey(item.groupKey!),\n      step.aggregates,\n      (item, property) => QueryItem.getAggregateProperty(item, property),\n      (a, b, order) => this._compareByOrder(a, b, order),\n    );\n    const groupedWorkingSet = step.aggregates.some((aggregate) => aggregate.kind === 'items')\n      ? stamped\n      : withManifests(GroupBy.collapseGroups(stamped, serializeItemGroupKey), stamped, step.aggregates);\n\n    return {\n      workingSet: groupedWorkingSet,\n      trace: {\n        ...ExecutionTrace.makeEmpty(),\n        name: 'Aggregate',\n        details: JSON.stringify({ aggregates: step.aggregates }),\n        objectCount: groupedWorkingSet.length,\n      },\n    };\n  }\n\n  private _compareMultiOrder(a: QueryItem, b: QueryItem, orders: readonly QueryAST.Order[]): number {\n    // Short circuit for common cases.\n    if (orders.length === 0) {\n      return 0;\n    } else if (orders.length === 1) {\n      return this._compareByOrder(a, b, orders[0]);\n    }\n\n    for (const order of orders) {\n      const comparison = this._compareByOrder(a, b, order);\n      if (comparison !== 0) {\n        return comparison;\n      }\n    }\n    return 0;\n  }\n\n  private _compareByOrder(a: QueryItem, b: QueryItem, order: QueryAST.Order): number {\n    switch (order.kind) {\n      case 'natural': {\n        if (a.walkIndex !== undefined && b.walkIndex !== undefined) {\n          const comparison = a.walkIndex - b.walkIndex;\n          return order.direction === 'desc' ? -comparison : comparison;\n        }\n        // Code-unit order, not `localeCompare`: the feed scan pushes this ordering into SQLite's\n        // `ORDER BY objectId`, which collates BINARY, and an entity id may be lower-case (the\n        // format check is case-insensitive). Under a locale collation the two would disagree on a\n        // mixed-case pair, and the scan's capped page would not be the page this sort produces.\n        const comparison = a.objectId < b.objectId ? -1 : a.objectId > b.objectId ? 1 : 0;\n        return order.direction === 'desc' ? -comparison : comparison;\n      }\n      case 'property': {\n        const comparison = this._compareByProperty(a, b, order.property);\n        return order.direction === 'desc' ? -comparison : comparison;\n      }\n      case 'rank': {\n        // Higher rank = better match. By default, descending order (best first).\n        const comparison = a.rank - b.rank;\n        return order.direction === 'desc' ? -comparison : comparison;\n      }\n      case 'annotation':\n        return QueryAST.compareAnnotationOrderValues(\n          QueryAST.getAnnotationOrderValue(QueryItem.getAnnotations(a), order),\n          QueryAST.getAnnotationOrderValue(QueryItem.getAnnotations(b), order),\n          order.direction,\n        );\n      case 'timestamp': {\n        // Order by the system createdAt/updatedAt timestamp from the meta index.\n        // Missing timestamps sort as oldest (0).\n        const aValue = (order.field === 'updatedAt' ? a.updatedAt : a.createdAt) ?? 0;\n        const bValue = (order.field === 'updatedAt' ? b.updatedAt : b.createdAt) ?? 0;\n        const comparison = aValue - bValue;\n        return order.direction === 'desc' ? -comparison : comparison;\n      }\n      default:\n        // Should never reach here with proper TypeScript types.\n        return 0;\n    }\n  }\n\n  private _compareByProperty(a: QueryItem, b: QueryItem, property: string): number {\n    // On a grouped working set, a property order names a group field: prefer a stamped scalar\n    // aggregate (max/min/count) when present, else fall through to the member/row property (which\n    // also covers ordering by a group-key component, shared by every member).\n    const aValue =\n      a.aggregates && property in a.aggregates ? a.aggregates[property] : QueryItem.getProperty(a, [property]);\n    const bValue =\n      b.aggregates && property in b.aggregates ? b.aggregates[property] : QueryItem.getProperty(b, [property]);\n\n    // Both null or undefined\n    if (aValue == null && bValue == null) {\n      return 0;\n    }\n\n    // Only a is null/undefined\n    if (aValue == null) {\n      return 1;\n    }\n\n    // Only b is null/undefined\n    if (bValue == null) {\n      return -1;\n    }\n\n    // Both strings, in the collation SQLite sorts by.\n    if (typeof aValue === 'string' && typeof bValue === 'string') {\n      return compareCodeUnits(aValue, bValue);\n    }\n\n    // Both numbers\n    if (typeof aValue === 'number' && typeof bValue === 'number') {\n      return aValue - bValue;\n    }\n\n    // Both booleans\n    if (typeof aValue === 'boolean' && typeof bValue === 'boolean') {\n      return aValue === bValue ? 0 : aValue ? 1 : -1;\n    }\n\n    // Fallback: convert to strings and compare\n    return compareCodeUnits(String(aValue), String(bValue));\n  }\n\n  private async _runInRuntime<T>(effect: Effect.Effect<T, unknown, SqlClient.SqlClient>): Promise<T> {\n    const runtimeProvider = this._runtime;\n    invariant(runtimeProvider, 'SQL runtime is required.');\n    return await RuntimeProvider.runPromise(runtimeProvider)(effect);\n  }\n\n  private async _queryAllFromSqlIndex(\n    spaceIds: readonly SpaceId[],\n    includeAllQueues: boolean,\n    queues: readonly QueueRef[] | null,\n    window?: QueueWindow,\n  ): Promise<readonly EntityMeta[]> {\n    return await this._runInRuntime(this._indexEngine.queryAll({ spaceIds, includeAllQueues, queues, window }));\n  }\n\n  private async _queryTypesFromSqlIndex(\n    spaceIds: readonly SpaceId[],\n    typeDxns: readonly URI.URI[],\n    inverted: boolean,\n    includeAllQueues: boolean,\n    queues: readonly QueueRef[] | null,\n    window?: QueueWindow,\n  ): Promise<readonly EntityMeta[]> {\n    return await this._runInRuntime(\n      this._indexEngine.queryTypes({ spaceIds, typeDxns, inverted, includeAllQueues, queues, window }),\n    );\n  }\n\n  /** The objects referencing each anchor through `property`, with the anchors and property paths each references them by. */\n  async #queryIncomingReferences(\n    workingSet: readonly QueryItem[],\n    property: EscapedPropPath | null,\n  ): Promise<{ metas: readonly EntityMeta[]; referrers: Map<number, { anchor: QueryItem; propPath: string }[]> }> {\n    const queryPath = property === null ? null : EscapedPropPath.unescape(property);\n    const rowsByAnchor = await Promise.all(\n      workingSet.map(async (anchor) => ({\n        anchor,\n        rows: await this._runInRuntime(\n          this._indexEngine.queryReverseRef({ targetDXN: QueryExecutor._anchorTargetDxn(anchor) }),\n        ),\n      })),\n    );\n    const referrers = new Map<number, { anchor: QueryItem; propPath: string }[]>();\n    for (const { anchor, rows } of rowsByAnchor) {\n      for (const row of rows) {\n        if (\n          queryPath !== null &&\n          !QueryExecutor._matchesReferencePropertyPath(EscapedPropPath.unescape(row.propPath), queryPath)\n        ) {\n          continue;\n        }\n        const list = referrers.get(row.recordId) ?? [];\n        list.push({ anchor, propPath: row.propPath });\n        referrers.set(row.recordId, list);\n      }\n    }\n    const metas = await this._runInRuntime(this._indexEngine.lookupByRecordIds([...referrers.keys()]));\n    return { metas, referrers };\n  }\n\n  private static _anchorTargetDxn(item: QueryItem): EID.EID {\n    // Queue items are indexed with fully-qualified DXNs; local `echo:/<id>` anchors miss them.\n    if (item.queueId != null) {\n      return EID.make({ spaceId: item.spaceId, entityId: item.objectId });\n    }\n    return EID.make({ entityId: item.objectId });\n  }\n\n  /**\n   * Reverse-reference lookup by target URI. Anchors that are not entities (a named entity's `dxn:`)\n   * reach this directly, without a working set.\n   */\n  private async _queryIncomingReferencesByTarget(\n    anchorDxns: readonly URI.URI[],\n    property: EscapedPropPath | null,\n  ): Promise<readonly EntityMeta[]> {\n    const rows: readonly ReverseRef[] = (\n      await Promise.all(\n        anchorDxns.map((targetDXN) => this._runInRuntime(this._indexEngine.queryReverseRef({ targetDXN }))),\n      )\n    ).flat();\n\n    const recordIds = rows\n      .filter((row) => {\n        if (property === null) {\n          return true;\n        }\n\n        const queryPath = EscapedPropPath.unescape(property);\n        const rowPath = EscapedPropPath.unescape(row.propPath);\n        return QueryExecutor._matchesReferencePropertyPath(rowPath, queryPath);\n      })\n      .map((row) => row.recordId);\n\n    const uniqueRecordIds = Array.from(new Set<number>(recordIds));\n    return await this._runInRuntime(this._indexEngine.lookupByRecordIds(uniqueRecordIds));\n  }\n\n  /**\n   * Matches a reverse-reference row path against a query property path.\n   * Allows numeric segments in the row path (array indices) that are not present in the query.\n   *\n   * Examples:\n   * - query: ['assignee'] matches row: ['assignee'] and ['assignee', '0'].\n   * - query: ['items', 'assignee'] matches row: ['items', '0', 'assignee'].\n   * - query: ['a', 'b'] does NOT match row: ['a'].\n   * - query: ['a'] does NOT match row: ['a', 'b'].\n   */\n  private static _matchesReferencePropertyPath(rowPath: readonly string[], queryPath: readonly string[]): boolean {\n    const isNumericSegment = (segment: string) => /^[0-9]+$/.test(segment);\n\n    let i = 0; // queryPath index.\n    let j = 0; // rowPath index.\n\n    while (i < queryPath.length && j < rowPath.length) {\n      if (rowPath[j] === queryPath[i]) {\n        i++;\n        j++;\n        continue;\n      }\n\n      // Row may contain array indices that aren't present in the query path.\n      if (isNumericSegment(rowPath[j])) {\n        j++;\n        continue;\n      }\n\n      return false;\n    }\n\n    // Must consume full query path.\n    if (i !== queryPath.length) {\n      return false;\n    }\n\n    // Any remaining row segments must be numeric (array indices).\n    for (; j < rowPath.length; j++) {\n      if (!isNumericSegment(rowPath[j])) {\n        return false;\n      }\n    }\n\n    return true;\n  }\n\n  private async _queryRelationsFromSqlIndex(\n    workingSet: QueryItem[],\n    endpoint: 'source' | 'target',\n  ): Promise<readonly EntityMeta[]> {\n    const anchorDxns = workingSet.map((item) => EID.make({ entityId: item.objectId }));\n    return await this._runInRuntime(this._indexEngine.queryRelations({ endpoint, anchorDxns }));\n  }\n\n  private async _loadDocumentsAfterSqlQuery(metas: readonly EntityMeta[]): Promise<(QueryItem | null)[]> {\n    const snapshotMap = await this._loadQueueSnapshotMap(metas);\n    const documentIds = [...new Set(metas.flatMap((meta) => (meta.documentId ? [meta.documentId as DocumentId] : [])))];\n    const storedHeads =\n      documentIds.length > 0\n        ? new Map(\n            (await this._automergeHost.getStoredHeads(documentIds)).map((heads, index) => [documentIds[index], heads]),\n          )\n        : new Map<DocumentId, A.Heads | undefined>();\n    const snapshots = await this.#readCurrentSnapshots(metas, documentIds);\n    return await Promise.all(\n      metas.map(async (meta) => {\n        // Branch 1: Document-backed object, from the index's copy when it was read at the stored heads.\n        if (meta.documentId) {\n          const snapshot = snapshots.get(meta.recordId);\n          return snapshot && isValidDocumentId(meta.documentId)\n            ? QueryItem.fromSnapshot(meta, meta.documentId, snapshot)\n            : this._loadFromAutomerge(meta, storedHeads.get(meta.documentId as DocumentId));\n        }\n\n        // Branch 2: Queue-backed object.\n        if (meta.queueId) {\n          return this._loadFromQueue(meta, snapshotMap);\n        }\n\n        return null;\n      }),\n    );\n  }\n\n  /**\n   * The index's copies of the document objects among `metas` that were read at their document's current heads,\n   * keyed by record id: the heads in memory when the document is loaded, its stored heads otherwise. Such a copy\n   * is the document's own state, so it stands in for loading the document.\n   */\n  async #readCurrentSnapshots(\n    metas: readonly EntityMeta[],\n    documentIds: readonly DocumentId[],\n  ): Promise<Map<number, ObjectSnapshot>> {\n    const documentMetas = new Map(metas.filter((meta) => meta.documentId).map((meta) => [meta.recordId, meta]));\n    if (documentMetas.size === 0) {\n      return new Map();\n    }\n    const [snapshots, heads] = await Promise.all([\n      this._runInRuntime(this._indexEngine.querySnapshots([...documentMetas.keys()])).catch((err) => {\n        log.warn('index snapshots could not be read; loading the documents', { err });\n        return [];\n      }),\n      this._automergeHost.getHeads([...documentIds]),\n    ]);\n    const currentHeads = new Map<string, A.Heads | undefined>(\n      documentIds.map((documentId, index) => [documentId, heads[index]]),\n    );\n    const current = new Map<number, ObjectSnapshot>();\n    for (const snapshot of snapshots) {\n      const meta = documentMetas.get(snapshot.recordId);\n      if (meta?.documentId && isSaved(currentHeads.get(meta.documentId), snapshot.version)) {\n        current.set(snapshot.recordId, snapshot);\n      }\n    }\n    countWork('echo.querySnapshotHits', current.size);\n    return current;\n  }\n\n  private async _loadQueueSnapshotMap(metas: readonly EntityMeta[]): Promise<Map<number, unknown>> {\n    const queueMetas = metas.filter((meta) => !meta.documentId && !!meta.queueId);\n    if (queueMetas.length === 0) {\n      return new Map();\n    }\n\n    const snapshots = await this._runInRuntime(\n      this._indexEngine.querySnapshotsJSON(queueMetas.map((meta) => meta.recordId)),\n    );\n    return new Map(snapshots.map((s) => [s.recordId, s.snapshot]));\n  }\n\n  /**\n   * Loads a queue-backed object from an indexed snapshot (by `recordId`).\n   * Returns `null` when the snapshot is missing or is not a JSON object.\n   */\n  private _loadFromQueue(meta: EntityMeta, snapshotMap: Map<number, unknown>): QueryItem | null {\n    const snapshot = snapshotMap.get(meta.recordId);\n    if (!snapshot || typeof snapshot !== 'object') {\n      return null;\n    }\n    if (!EntityId.isValid(meta.queueId)) {\n      return null;\n    }\n\n    return {\n      objectId: meta.objectId,\n      spaceId: meta.spaceId,\n      queueId: meta.queueId,\n      queueNamespace: meta.queueNamespace || null,\n      documentId: null,\n      doc: null,\n      data: snapshot as Obj.JSON,\n      rank: 1,\n      createdAt: meta.createdAt,\n      updatedAt: meta.updatedAt,\n      position: meta.queuePosition,\n    };\n  }\n\n  /**\n   * Loads a document-backed object from an Automerge `DatabaseDirectory`.\n   * Returns `null` if the document can't be loaded, the inline object isn't present, or if the meta does not have a\n   * document id (e.g. queue-backed objects).\n   */\n  private async _loadFromAutomerge(meta: EntityMeta, storedHeads: A.Heads | undefined): Promise<QueryItem | null> {\n    if (!meta.documentId) {\n      return null;\n    }\n    using lease = await this._automergeHost.loadDoc<DatabaseDirectory>(this._ctx, meta.documentId as DocumentId, {\n      fetchFromNetwork: false,\n    });\n    if (!lease) {\n      return null;\n    }\n    const doc = lease.doc();\n    const object = DatabaseDirectory.getInlineObject(doc, meta.objectId);\n    if (!object) {\n      return null;\n    }\n    countWork('echo.queryDocumentLoads');\n    const json = objectStructureToJson(meta.objectId, object);\n    const heads = A.getHeads(doc);\n    const text = isSaved(storedHeads, heads) ? backingJson(doc, object, json) : undefined;\n    return {\n      objectId: meta.objectId,\n      documentId: meta.documentId as DocumentId,\n      spaceId: meta.spaceId,\n      queueId: null,\n      queueNamespace: null,\n      doc: object,\n      data: null,\n      rank: 1,\n      createdAt: meta.createdAt,\n      updatedAt: meta.updatedAt,\n      backing: text !== undefined ? { heads, json: text } : undefined,\n      heads,\n      recordId: meta.recordId,\n    };\n  }\n\n  /**\n   * Loads the target of an outgoing reference traversal.\n   * Space-db objects load from Automerge; with `includeAllFeeds` scope, queue items resolve via the SQL index.\n   */\n  private async _loadReferencedTarget(\n    dxn: URI.URI,\n    { sourceSpaceId }: { sourceSpaceId: SpaceId },\n  ): Promise<QueryItem | null> {\n    const fromSpace = await this._loadFromDXN(dxn, { sourceSpaceId });\n    if (fromSpace) {\n      return fromSpace;\n    }\n    if (this.#allFeedsSpaces.size === 0) {\n      return null;\n    }\n\n    const parsedEchoUri = EID.tryParse(dxn);\n    const objectId = parsedEchoUri ? EID.getEntityId(parsedEchoUri) : undefined;\n    const spaceId = (parsedEchoUri ? EID.getSpaceId(parsedEchoUri) : undefined) ?? sourceSpaceId;\n    if (!objectId || !spaceId) {\n      return null;\n    }\n\n    const metas = await this._runInRuntime(\n      this._indexEngine.queryObjectIds({ spaceIds: [spaceId], objectIds: [objectId] }),\n    );\n    if (metas.length === 0) {\n      return null;\n    }\n\n    const [item] = await this._loadDocumentsAfterSqlQuery(metas);\n    return item ?? null;\n  }\n\n  private async _loadFromDXN(dxn: URI.URI, { sourceSpaceId }: { sourceSpaceId: SpaceId }): Promise<QueryItem | null> {\n    const echoUri = EID.tryParse(dxn);\n    if (!echoUri) {\n      log.warn('unable to resolve DXN', { dxn });\n      return null;\n    }\n\n    const objectId = EID.getEntityId(echoUri);\n    if (!objectId) {\n      log.warn('unable to resolve DXN', { dxn });\n      return null;\n    }\n\n    const spaceId = EID.getSpaceId(echoUri) ?? sourceSpaceId;\n\n    const spaceRoot = this._spaceStateManager.getRootBySpaceId(spaceId);\n    if (!spaceRoot) {\n      log.warn('no space state found for', { spaceId });\n      return null;\n    }\n    const dbDirectory = spaceRoot.directory();\n    const directoryHeads = spaceRoot.heads();\n    if (!dbDirectory || !directoryHeads) {\n      log.warn('no space state found for', { spaceId });\n      return null;\n    }\n\n    // Deprecated inline directory object, read until the inline object migration moves it.\n    // TODO(dmaretskyi): Drop once every space has run the inline object migration.\n    const inlineObject = DatabaseDirectory.getInlineObject(dbDirectory, objectId);\n    if (inlineObject) {\n      return {\n        objectId,\n        documentId: spaceRoot.documentId,\n        spaceId,\n        queueId: null,\n        queueNamespace: null,\n        data: null,\n        doc: inlineObject,\n        rank: 1,\n        // DXN traversal results are not sourced from the meta index; timestamps are unavailable.\n        createdAt: null,\n        updatedAt: null,\n        heads: directoryHeads,\n      };\n    }\n\n    const link = DatabaseDirectory.getLink(dbDirectory, objectId);\n    if (!link || !isValidAutomergeUrl(link)) {\n      return null;\n    }\n\n    const fromIndex = await this.#loadFromIndexCopy(spaceId, objectId, interpretAsDocumentId(link));\n    if (fromIndex) {\n      return fromIndex;\n    }\n\n    using lease = await this._automergeHost.loadDoc<DatabaseDirectory>(this._ctx, link, {\n      fetchFromNetwork: false,\n    });\n    if (!lease) {\n      return null;\n    }\n\n    const object = DatabaseDirectory.getInlineObject(lease.doc(), objectId);\n    if (!object) {\n      return null;\n    }\n\n    countWork('echo.queryDocumentLoads');\n    return {\n      objectId,\n      documentId: lease.documentId,\n      spaceId,\n      queueId: null,\n      queueNamespace: null,\n      data: null,\n      doc: object,\n      rank: 1,\n      // DXN traversal results are not sourced from the meta index; timestamps are unavailable.\n      createdAt: null,\n      updatedAt: null,\n      heads: A.getHeads(lease.doc()),\n    };\n  }\n\n  /**\n   * The index's copy of an object in the document the space directory places it in, when the index read it\n   * at that document's stored heads; null when the document has to be loaded.\n   */\n  async #loadFromIndexCopy(spaceId: SpaceId, objectId: EntityId, documentId: DocumentId): Promise<QueryItem | null> {\n    const meta = await this._runInRuntime(this._indexEngine.lookupByObjectId({ objectId, spaceId, queueId: '' })).catch(\n      (err) => {\n        log.warn('index row could not be read; loading the document', { objectId, err });\n        return null;\n      },\n    );\n    if (!meta || meta.documentId !== documentId) {\n      return null;\n    }\n    const snapshot = (await this.#readCurrentSnapshots([meta], [documentId])).get(meta.recordId);\n    return snapshot ? QueryItem.fromSnapshot(meta, documentId, snapshot) : null;\n  }\n\n  /**\n   * Loads a queue item by its object ID from the SQL index.\n   * Used by the IdSelector path when querying within a queue scope.\n   */\n  private async _loadQueueItemById(spaceId: SpaceId, queueId: EntityId, objectId: EntityId): Promise<QueryItem | null> {\n    const meta = await this._runInRuntime(this._indexEngine.lookupByObjectId({ objectId, spaceId, queueId }));\n    if (!meta) {\n      return null;\n    }\n    const snapshotMap = await this._loadQueueSnapshotMap([meta]);\n    return this._loadFromQueue(meta, snapshotMap);\n  }\n\n  /**\n   * Filters out items whose strong dependencies (schema object, relation endpoints,\n   * parent) are not resolvable from local state — dangling references or docs that are\n   * not on disk. Mirrors the client-side working-set filter so dep-broken objects are\n   * excluded consistently on both sides of the query pipeline.\n   */\n  private async _filterUnresolvableStrongDeps(workingSet: QueryItem[]): Promise<QueryItem[]> {\n    // Resolved dep verdicts shared across items (e.g. a common schema object).\n    const verdicts = new Map<string, boolean>();\n    const resolvable = await Promise.all(\n      workingSet.map((item) =>\n        this._areStrongDepsResolvable(item, MAX_DEPTH_FOR_STRONG_DEP_TRACING, verdicts, new Set()),\n      ),\n    );\n    const result = workingSet.filter((_item, index) => resolvable[index]);\n    if (result.length !== workingSet.length) {\n      log('omitted items with unresolvable strong deps', {\n        queryId: this._id,\n        omitted: workingSet.filter((_item, index) => !resolvable[index]).map((item) => item.objectId),\n      });\n    }\n    return result;\n  }\n\n  private async _areStrongDepsResolvable(\n    item: QueryItem,\n    remainingDepth: number,\n    verdicts: Map<string, boolean>,\n    seen: Set<string>,\n  ): Promise<boolean> {\n    if (remainingDepth <= 0) {\n      // Depth cap reached — give the item the benefit of the doubt rather than excluding it.\n      return true;\n    }\n\n    const results = await Promise.all(\n      QueryItem.getStrongDependencies(item).map(async (dep) => {\n        if (!EID.isLocal(dep)) {\n          // Cross-space references are not gated (mirrors `ObjectCore.getStrongDependencies` usage).\n          return true;\n        }\n        const key = compositeKey(item.spaceId, dep);\n        const cached = verdicts.get(key);\n        if (cached !== undefined) {\n          return cached;\n        }\n        if (seen.has(key)) {\n          // Reference cycle — treat as resolvable (mirrors the client's seen-set behavior).\n          return true;\n        }\n        seen.add(key);\n\n        const depItem = await this._loadDependency(item, dep);\n        const verdict =\n          depItem != null && (await this._areStrongDepsResolvable(depItem, remainingDepth - 1, verdicts, seen));\n        verdicts.set(key, verdict);\n        return verdict;\n      }),\n    );\n    return results.every(Boolean);\n  }\n\n  /**\n   * Resolves an object `item` depends on, in the same form as `item`: an item selected from the index\n   * resolves its dependencies from the index too, so checking them loads no documents either. Each\n   * dependency loads once per `execQuery` run.\n   */\n  private _loadDependency(item: QueryItem, dxn: URI.URI): Promise<QueryItem | null> {\n    const fromDocument = Boolean(item.doc || item.data || !item.meta);\n    const key = compositeKey(item.spaceId, dxn, fromDocument ? 'document' : 'index');\n    let loaded = this.#dependencyCache.get(key);\n    if (!loaded) {\n      loaded = fromDocument\n        ? this._loadFromDXN(dxn, { sourceSpaceId: item.spaceId })\n        : this._loadDependencyFromIndex(item.spaceId, dxn);\n      this.#dependencyCache.set(key, loaded);\n    }\n    return loaded;\n  }\n\n  private async _loadDependencyFromIndex(sourceSpaceId: SpaceId, dxn: URI.URI): Promise<QueryItem | null> {\n    const echoUri = EID.tryParse(dxn);\n    const objectId = echoUri ? EID.getEntityId(echoUri) : undefined;\n    if (!echoUri || !objectId) {\n      return null;\n    }\n    const spaceId = EID.getSpaceId(echoUri) ?? sourceSpaceId;\n    const metas = await this._runInRuntime(\n      this._indexEngine.queryObjectIds({ spaceIds: [spaceId], objectIds: [objectId] }),\n    );\n    const meta = metas.find((candidate) => candidate.documentId);\n    return meta ? QueryItem.fromIndexRow(meta) : null;\n  }\n\n  private async _getTransitiveDeletionState(item: QueryItem, remainingDepth: number): Promise<boolean> {\n    const strongDeps = [\n      QueryItem.getParent(item),\n      QueryItem.getRelationSource(item),\n      QueryItem.getRelationTarget(item),\n    ].filter((x) => x !== undefined);\n\n    if (strongDeps.length === 0) {\n      return false;\n    }\n\n    // TODO(dmaretskyi): This could be optimized to bail early if any of the dependencies are deleted.\n    const strongDepStates = await Promise.all(\n      strongDeps.map(async (dxn) => {\n        const dep = await this._loadDependency(item, dxn);\n        if (!dep) {\n          return false;\n        }\n        if (QueryItem.isDeleted(dep)) {\n          return true;\n        }\n        if (remainingDepth > 0) {\n          return this._getTransitiveDeletionState(dep, remainingDepth - 1);\n        }\n        return false;\n      }),\n    );\n\n    return strongDepStates.some((x) => x);\n  }\n}\n\nconst extractSpaceIdFromQueue = (feedUri: string): SpaceId | undefined => {\n  const echoUri = EID.tryParse(feedUri);\n  return echoUri ? EID.getSpaceId(echoUri) : undefined;\n};\n\n/** A decoded feed block carrying a valid object id, which is all a feed item's JSON is checked for. */\nconst isObjectJSON = (value: Record<string, unknown>): value is Obj.JSON =>\n  typeof value.id === 'string' && EntityId.isValid(value.id);\n\n/** Every feed scope any select step of the plan (subplans included) names. */\nconst extractFeedScopes = (plan: QueryPlan.Plan): QueryAST.FeedScope[] =>\n  plan.steps.flatMap((step) => {\n    switch (step._tag) {\n      case 'SelectStep':\n        return step.scope.filter((scope): scope is QueryAST.FeedScope => scope._tag === 'feed');\n      case 'UnionStep':\n        return step.plans.flatMap(extractFeedScopes);\n      case 'SetDifferenceStep':\n        return [...extractFeedScopes(step.source), ...extractFeedScopes(step.exclude)];\n      default:\n        return [];\n    }\n  });\n\n/** Whether a feed item is a member of one of `branches` (`null` is main); absent admits every branch. */\nconst isOnBranches = (data: Record<string, unknown>, branches: QueueRef['branches']): boolean =>\n  branches === undefined || branches.includes(EchoFeedCodec.branchOf(data) ?? null);\n\n/** The branches two scopes of one feed read together; either reading every branch reads them all. */\nconst unionBranches = (left: QueueRef, right: QueueRef): QueueRef['branches'] =>\n  left.branches === undefined || right.branches === undefined\n    ? undefined\n    : [...new Set([...left.branches, ...right.branches])];\n\n/**\n * The store-read feed items a select step picks, as the index would have answered it: by selector,\n * then the step's feed window. Text and reference selectors match nothing, since they are answered\n * from indexes a disabled feed is not in.\n */\nconst selectStoreItems = (step: QueryPlan.SelectStep, items: readonly QueryItem[]): QueryItem[] => {\n  const { selector } = step;\n  const selected = items.filter((item) => {\n    const data = item.data;\n    if (!data) {\n      return false;\n    }\n    switch (selector._tag) {\n      case 'WildcardSelector':\n        return true;\n      case 'IdSelector':\n        return selector.objectIds.includes(item.objectId);\n      case 'TypeSelector': {\n        const matches = selector.typename.some((typename) =>\n          filterMatchObjectJSON({ type: 'object', typename, props: {} }, data),\n        );\n        return matches !== selector.inverted;\n      }\n      case 'TimestampSelector': {\n        const updatedAt = item.updatedAt ?? 0;\n        const createdAt = item.createdAt ?? 0;\n        return (\n          (selector.updatedAfter === undefined || updatedAt > selector.updatedAfter) &&\n          (selector.updatedBefore === undefined || updatedAt < selector.updatedBefore) &&\n          (selector.createdAfter === undefined || createdAt > selector.createdAfter) &&\n          (selector.createdBefore === undefined || createdAt < selector.createdBefore)\n        );\n      }\n      default:\n        return false;\n    }\n  });\n\n  const window = extractQueueWindow(step);\n  if (window === undefined) {\n    return selected;\n  }\n  if (window.kind === 'cursor') {\n    return selected\n      .filter(\n        (item) =>\n          typeof item.position === 'number' &&\n          item.position > window.after &&\n          (window.before === undefined || item.position < window.before),\n      )\n      .sort((left, right) => (left.position ?? 0) - (right.position ?? 0))\n      .slice(0, window.limit);\n  }\n  const sorted = selected\n    .filter((item) => window.deleted === undefined || (item.data?.[ATTR_DELETED] === true) === window.deleted)\n    .sort((left, right) => compareCodeUnits(left.objectId, right.objectId));\n  const ordered = window.direction === 'desc' ? sorted.reverse() : sorted;\n  const skip = window.skip ?? 0;\n  return ordered.slice(skip, skip + window.limit);\n};\n\n/** Bound below every assigned position, which start at 0. */\nconst BEFORE_FIRST_POSITION = -1;\n\n/**\n * The index-level window for a select the storage layer can bound itself, so a bounded query costs\n * what it asks for rather than the whole feed: a cursor range resumes by position, and a\n * `feedScan` (set by the planner only where it proved the cap sound) reads in natural order.\n *\n * Every cursor range windows the scan, an empty one included — it bounds nothing but still asks for\n * a cursor read, which is over positioned blocks in position order. A reader that paged the\n * unpositioned blocks in first would stop at a page of items it cannot act on while positioned ones\n * waited behind them.\n *\n * A bound that is not a decimal position is treated as unsatisfiable rather than as absent:\n * resuming a corrupted checkpoint from the beginning would re-dispatch the whole feed.\n */\nconst extractQueueWindow = (step: QueryPlan.SelectStep): QueueWindow | undefined => {\n  const range = step.feedCursorRange;\n  if (range === undefined) {\n    if (step.feedScan === undefined || step.limit === undefined) {\n      return undefined;\n    }\n    return {\n      kind: 'natural',\n      direction: step.feedScan.direction,\n      limit: step.limit,\n      ...(step.feedScan.skip !== undefined ? { skip: step.feedScan.skip } : {}),\n      ...(step.feedScan.deleted !== undefined ? { deleted: step.feedScan.deleted } : {}),\n    };\n  }\n\n  // Backstop for the planner's check, which is where a cursor over a space's documents is refused.\n  if (!step.scope.every((scope) => scope._tag === 'feed')) {\n    throw new QueryError({\n      message: 'A feed cursor filter can only be used with a feed scope.',\n      context: { query: null },\n    });\n  }\n\n  return {\n    kind: 'cursor',\n    // The empty string is the start sentinel (`Feed.START`), which bounds nothing.\n    after: range.begin ? parseCursor(range.begin, Number.MAX_SAFE_INTEGER) : BEFORE_FIRST_POSITION,\n    ...(range.end ? { before: parseCursor(range.end, BEFORE_FIRST_POSITION) } : {}),\n    ...(step.limit !== undefined ? { limit: step.limit } : {}),\n  };\n};\n\n/** The block id a local cursor (`<branch>|<block>`) resumes after; the start sentinel `''` names none. */\n/** A local cursor is `<branch>|<block id>`, with an empty branch for the root. */\nconst parseLocalCursor = (cursor: string): { branch: string | null; block: string } => {\n  const separator = cursor.indexOf('|');\n  const branch = cursor.slice(0, separator);\n  return { branch: branch === '' ? null : branch, block: cursor.slice(separator + 1) };\n};\n\n/**\n * The direction of a walk: the natural order the plan asks for, ascending when it asks for none. A\n * walk has no other order, since its natural order is the walk itself.\n */\nconst walkDirection = (plan: QueryPlan.Plan): 'asc' | 'desc' => {\n  const orders = plan.steps.flatMap((step) => (step._tag === 'OrderStep' ? step.order : []));\n  const unsupported = orders.find((order) => order.kind !== 'natural');\n  if (unsupported !== undefined) {\n    throw new QueryError({\n      message: `A walk accepts only the natural order, not the ${unsupported.kind} order.`,\n      context: { query: null, order: unsupported.kind },\n    });\n  }\n  return orders[0]?.kind === 'natural' ? orders[0].direction : 'asc';\n};\n\n/**\n * The page a walk is cut to: the plan's limit, when it only selects, filters and orders before it. A walk counts what\n * the filters keep of each page, so reading pages until that many remain is enough.\n */\nconst walkLimit = (plan: QueryPlan.Plan): number | undefined => {\n  // The planner moves a trailing limit onto the order step, removing the limit step.\n  const ordered = plan.steps.find((step) => step._tag === 'OrderStep');\n  const limit = plan.steps.find((step) => step._tag === 'LimitStep');\n  const passing = new Set([\n    'SelectStep',\n    'OrderStep',\n    'ClearWorkingSetStep',\n    'FilterDeletedStep',\n    'FilterStep',\n    'LimitStep',\n  ]);\n  const narrowing = plan.steps.some((step) => !passing.has(step._tag));\n  return narrowing\n    ? undefined\n    : limit?._tag === 'LimitStep'\n      ? limit.limit\n      : ordered?._tag === 'OrderStep'\n        ? ordered.limit\n        : undefined;\n};\n\n/** A cursor's position, or `unsatisfiable` when it does not name one. */\nconst parseCursor = (cursor: string, unsatisfiable: number): number => {\n  const position = /^\\d+$/.test(cursor) ? Number(cursor) : Number.NaN;\n  return Number.isSafeInteger(position) ? position : unsatisfiable;\n};\n\n/**\n * The queues a feed scope names, each carrying the space its URI qualifies it with so the index\n * seek cannot cross spaces — a queue id is unique only within its own. An unqualified URI\n * (`echo:///<id>`) names no space, and matches on its id alone.\n */\nconst extractQueueRefs = (queues: readonly QueryAST.FeedScope[]): QueueRef[] | null => {\n  if (queues.length === 0) {\n    return null;\n  }\n  return queues\n    .map((scope): QueueRef | undefined => {\n      const echoUri = EID.tryParse(String(scope.feedUri));\n      if (!echoUri) {\n        return undefined;\n      }\n      const queueId = EID.getEntityId(echoUri);\n      if (!queueId) {\n        return undefined;\n      }\n      const spaceId = EID.getSpaceId(echoUri);\n      return {\n        queueId,\n        ...(spaceId !== undefined ? { spaceId } : {}),\n        ...queueBranchesOf(scope.branches),\n      };\n    })\n    .filter(isNonNullable);\n};\n\n/**\n * Extract timestamp parameters from a filter AST node.\n * Returns null if the filter doesn't contain timestamp nodes.\n */\nconst extractTimestampParams = (\n  filter: QueryAST.Filter,\n): { updatedAfter?: number; updatedBefore?: number; createdAfter?: number; createdBefore?: number } | null => {\n  const collect = (f: QueryAST.Filter): QueryAST.FilterTimestamp[] => {\n    if (f.type === 'timestamp') {\n      return [f];\n    }\n    if (f.type === 'and') {\n      return f.filters.flatMap(collect);\n    }\n    return [];\n  };\n\n  const timestamps = collect(filter);\n  if (timestamps.length === 0) {\n    return null;\n  }\n\n  const params: { updatedAfter?: number; updatedBefore?: number; createdAfter?: number; createdBefore?: number } = {};\n  for (const ts of timestamps) {\n    if (ts.field === 'updatedAt' && (ts.operator === 'gt' || ts.operator === 'gte')) {\n      params.updatedAfter = ts.value;\n    } else if (ts.field === 'updatedAt' && (ts.operator === 'lt' || ts.operator === 'lte')) {\n      params.updatedBefore = ts.value;\n    } else if (ts.field === 'createdAt' && (ts.operator === 'gt' || ts.operator === 'gte')) {\n      params.createdAfter = ts.value;\n    } else if (ts.field === 'createdAt' && (ts.operator === 'lt' || ts.operator === 'lte')) {\n      params.createdBefore = ts.value;\n    }\n  }\n  return params;\n};\n\nfunction filterContainsTimestamp(filter: QueryAST.Filter): boolean {\n  if (filter.type === 'timestamp') {\n    return true;\n  }\n  if (filter.type === 'and' || filter.type === 'or') {\n    return filter.filters.some(filterContainsTimestamp);\n  }\n  if (filter.type === 'not') {\n    return filterContainsTimestamp(filter.filter);\n  }\n  return false;\n}\n\n/**\n * Cache key identifying an `in-query` node's subquery + projected property, used to share one\n * resolution across every occurrence of the same subquery within an `execQuery` run.\n */\nconst _inQueryCacheKey = (node: QueryAST.FilterInQuery): string => `${JSON.stringify(node.subquery)}\\0${node.property}`;\n\n/**\n * A compiled row as a working-set item. The shipped form is built here rather than in\n * `getResults`, since the row already carries everything the client needs and the item carries no\n * document to derive it from. A collapsed group stands for its members, so it ships no object\n * fields and its id is the serialized group key.\n */\nconst compiledRowToItem = (row: CompiledRow): QueryItem => {\n  const result: QueryService.QueryResult =\n    row.aggregates !== null && row.groupKey !== null\n      ? {\n          id: row.groupKey,\n          spaceId: row.spaceId,\n          rank: row.rank,\n          groupKey: row.groupKey,\n          groupCount: row.groupCount ?? undefined,\n          aggregates: row.aggregates,\n        }\n      : {\n          id: row.objectId,\n          spaceId: row.spaceId,\n          documentId: row.documentId !== '' ? row.documentId : undefined,\n          queueId: row.queueId !== '' ? row.queueId : undefined,\n          queueNamespace: row.queueNamespace !== '' ? row.queueNamespace : undefined,\n          rank: row.rank,\n          documentJson: row.documentJson ?? undefined,\n          groupKey: row.groupKey ?? undefined,\n          groupCount: row.groupCount ?? undefined,\n          heads: row.heads !== null ? JSON.parse(row.heads) : undefined,\n          createdAt: row.heads !== null ? (row.createdAt ?? undefined) : undefined,\n          updatedAt: row.heads !== null ? (row.updatedAt ?? undefined) : undefined,\n          version: compiledRowVersion(row),\n        };\n  const paths = row.edges !== null ? pathsFromEdges(row.objectId, parseEdges(row.edges)) : undefined;\n  return {\n    objectId: row.objectId,\n    spaceId: row.spaceId,\n    documentId: row.documentId !== '' ? (row.documentId as DocumentId) : null,\n    queueId: row.queueId !== '' ? (row.queueId as EntityId) : null,\n    queueNamespace: row.queueNamespace !== '' ? row.queueNamespace : null,\n    doc: null,\n    data: null,\n    rank: row.rank,\n    createdAt: row.createdAt,\n    updatedAt: row.updatedAt,\n    recordId: row.recordId,\n    result,\n    ...(paths === null ? { derivationUnknown: true } : paths && { paths }),\n    ...(row.manifest !== null && { manifest: parseCompiledManifest(row.manifest) }),\n  };\n};\n\n/** The state a compiled row was read at: its document's index heads, or its feed block's position. */\nconst compiledRowVersion = (row: {\n  documentId: string;\n  queueId: string;\n  versionHeads: string | null;\n  queuePosition: number | null;\n}): QueryService.RowVersion | undefined => {\n  if (row.queueId !== '') {\n    return row.queuePosition !== null ? { kind: 'feed', insertionId: row.queuePosition } : undefined;\n  }\n  if (row.documentId !== '' && row.versionHeads !== null) {\n    return { kind: 'automerge', documentId: row.documentId, heads: parseStringArray(JSON.parse(row.versionHeads)) };\n  }\n  return undefined;\n};\n\nconst parseStringArray = (value: unknown): string[] =>\n  Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === 'string') : [];\n\nconst PATH_EDGE_KINDS: readonly QueryService.PathEdge['kind'][] = [\n  'ref',\n  'incoming-ref',\n  'relation-source',\n  'relation-target',\n  'parent',\n  'child',\n];\n\nconst isPathEdgeKind = (value: unknown): value is QueryService.PathEdge['kind'] =>\n  PATH_EDGE_KINDS.some((kind) => kind === value);\n\ntype HopEdge = QueryService.PathEdge & { hop: number };\n\n/** A compiled row's edges, or undefined past {@link MAX_EDGES_PER_ROW}, where the row's derivation is unknown. */\nconst parseEdges = (text: string): HopEdge[] | undefined => {\n  const parsed: unknown = JSON.parse(text);\n  if (!Array.isArray(parsed) || parsed.length > MAX_EDGES_PER_ROW) {\n    return undefined;\n  }\n  return parsed.flatMap((raw: unknown): HopEdge[] => {\n    if (typeof raw !== 'object' || raw === null) {\n      return [];\n    }\n    const { hop, from, to, kind, property, holder, holderHeads } = Object.fromEntries(Object.entries(raw));\n    if (\n      typeof hop !== 'number' ||\n      typeof from !== 'string' ||\n      typeof to !== 'string' ||\n      typeof holder !== 'string' ||\n      !isPathEdgeKind(kind)\n    ) {\n      return [];\n    }\n    return [\n      {\n        hop,\n        from,\n        to,\n        kind,\n        ...(typeof property === 'string' && { property }),\n        holder,\n        ...(Array.isArray(holderHeads) && { holderHeads: parseStringArray(holderHeads) }),\n      },\n    ];\n  });\n};\n\n/**\n * The derivations of a row reached by a traversal chain, rebuilt from its edges by walking back from the\n * last hop to the first. Null when the edges were cut off or the derivations exceed\n * {@link MAX_PATHS_PER_ITEM}, as the in-memory traversal leaves such a derivation unknown.\n */\nconst pathsFromEdges = (\n  objectId: string,\n  edges: readonly HopEdge[] | undefined,\n): QueryService.PathEdge[][] | null | undefined => {\n  if (edges === undefined) {\n    return null;\n  }\n  const last = edges.reduce((max, edge) => Math.max(max, edge.hop), 0);\n  if (last === 0) {\n    return undefined;\n  }\n  const into = new Map<string, HopEdge[]>();\n  for (const edge of edges) {\n    const key = `${edge.hop}:${edge.to}`;\n    into.set(key, [...(into.get(key) ?? []), edge]);\n  }\n  const paths = new Map<string, QueryService.PathEdge[]>();\n  let overflow = false;\n  const walk = (hop: number, to: string, suffix: readonly QueryService.PathEdge[]): void => {\n    for (const { hop: _hop, ...edge } of into.get(`${hop}:${to}`) ?? []) {\n      if (overflow) {\n        return;\n      }\n      const path = [edge, ...suffix];\n      if (hop > 1) {\n        walk(hop - 1, edge.from, path);\n        continue;\n      }\n      const key = path.map(({ from, to, kind, property }) => `${from}>${to}:${kind}:${property ?? ''}`).join('|');\n      if (!paths.has(key) && paths.size >= MAX_PATHS_PER_ITEM) {\n        overflow = true;\n        return;\n      }\n      paths.set(key, path);\n    }\n  };\n  walk(last, objectId, []);\n  return overflow ? null : paths.size > 0 ? [...paths.values()] : undefined;\n};\n\n/** A compiled collapsed group's members, each with its version and share of the scalar aggregates. */\nconst parseCompiledManifest = (text: string): QueryService.ManifestEntry[] => {\n  const parsed: unknown = JSON.parse(text);\n  if (!Array.isArray(parsed)) {\n    return [];\n  }\n  return parsed.flatMap((raw: unknown): QueryService.ManifestEntry[] => {\n    if (typeof raw !== 'object' || raw === null) {\n      return [];\n    }\n    const { id, documentId, heads, position, contribution } = Object.fromEntries(Object.entries(raw));\n    if (typeof id !== 'string') {\n      return [];\n    }\n    const version: QueryService.RowVersion | undefined =\n      typeof documentId === 'string' && documentId !== '' && Array.isArray(heads)\n        ? { kind: 'automerge', documentId, heads: parseStringArray(heads) }\n        : typeof position === 'number'\n          ? { kind: 'feed', insertionId: position }\n          : undefined;\n    return [{ id, ...(version && { version }), contribution: JSON.stringify(contribution ?? {}) }];\n  });\n};\n\n/**\n * Whether two working-set items would ship the same record, for reactive change detection. A\n * `SqlStep` item already carries its shipped form, so comparing that is comparing the record; an\n * item the steps built is compared on the fields `getResults` derives the record from.\n */\nconst _sameResult = (a: QueryItem, b: QueryItem): boolean => {\n  // A client drops a hit by its paths and adjusts a group by its manifest, so stale evidence must be resent.\n  if (evidenceKey(a) !== evidenceKey(b)) {\n    return false;\n  }\n  if (a.result !== undefined || b.result !== undefined) {\n    return (\n      a.result?.id === b.result?.id &&\n      a.result?.spaceId === b.result?.spaceId &&\n      a.result?.documentId === b.result?.documentId &&\n      a.result?.queueId === b.result?.queueId &&\n      a.result?.queueNamespace === b.result?.queueNamespace &&\n      a.result?.groupKey === b.result?.groupKey &&\n      a.result?.groupCount === b.result?.groupCount &&\n      a.result?.aggregates === b.result?.aggregates &&\n      a.result?.rank === b.result?.rank &&\n      // A feed row ships its indexed body, so an edit to it changes the record without moving the row.\n      a.result?.documentJson === b.result?.documentJson\n    );\n  }\n  return (\n    a.objectId === b.objectId &&\n    a.spaceId === b.spaceId &&\n    a.documentId === b.documentId &&\n    a.queueId === b.queueId &&\n    a.queueNamespace === b.queueNamespace &&\n    // A feed item read from the store has no record yet; a new block for it moves its version.\n    (a.queueId === null || (a.position === b.position && a.updatedAt === b.updatedAt)) &&\n    // A property edit can move an item between groups without changing its flat position\n    // (e.g. the last item of group A becomes the first item of group B at the same index).\n    _serializeOptionalGroupKey(a.groupKey) === _serializeOptionalGroupKey(b.groupKey) &&\n    // A collapsed group ships only its size and aggregates, so those are what can change.\n    _serializeCollapsed(a) === _serializeCollapsed(b)\n  );\n};\n\nconst evidenceKey = (item: QueryItem): string =>\n  item.paths === undefined && item.manifest === undefined && !item.derivationUnknown\n    ? ''\n    : JSON.stringify([item.derivationUnknown ?? false, item.paths ?? null, item.manifest ?? null]);\n\nconst STORED_CHANGES_CONCURRENCY = 16;\n\ntype BackingSource = { json: string; heads: string[] };\n\nconst withoutBacking = ({\n  documentJson: _documentJson,\n  heads: _heads,\n  bytes: _bytes,\n  createdAt: _createdAt,\n  updatedAt: _updatedAt,\n  ...row\n}: QueryService.QueryResult): QueryService.QueryResult => row;\n\n/**\n * Bytes of paths, or of manifests, one answer may carry: a mailbox-scale traversal would otherwise ship a\n * derivation DAG per hit, and the client retains every answer for the life of its subscription.\n */\nconst DERIVATION_BUDGET_BYTES = 256 * 1024;\n\n/** Whether the derivations of one answer fit {@link DERIVATION_BUDGET_BYTES}, measured as they encode. */\nconst withinBudget = (derivations: readonly (readonly unknown[] | undefined)[]): boolean => {\n  let bytes = 0;\n  for (const derivation of derivations) {\n    if (derivation === undefined) {\n      continue;\n    }\n    bytes += JSON.stringify(derivation).length;\n    if (bytes > DERIVATION_BUDGET_BYTES) {\n      return false;\n    }\n  }\n  return true;\n};\n\n/** One traversal hop, before it is attributed to the two items it joins. */\ntype TraversalEdge = { kind: QueryService.PathEdge['kind']; property?: string; holder: QueryItem };\n\n/** Derivations kept per item: enough to revalidate a hit, bounded for a hub that every anchor reaches. */\nconst MAX_PATHS_PER_ITEM = 16;\n\nconst itemKey = (item: QueryItem): string => `${item.spaceId}:${item.queueId ?? ''}:${item.objectId}`;\n\nconst itemsById = (items: readonly QueryItem[]): Map<string, QueryItem> =>\n  new Map(items.map((item) => [item.objectId, item]));\n\nconst entityIdOf = (raw: string | null): EntityId | undefined => {\n  const eid = raw ? EID.tryParse(raw) : undefined;\n  return eid ? EID.getEntityId(eid) : undefined;\n};\n\n/**\n * One item per object reached, carrying every derivation that reached it: each path of the item it was\n * reached from, extended by the hop. A derivation that cannot be stated, or one past the per-item bound,\n * leaves the item's derivation unknown, since a client that saw only some paths could drop a hit an\n * unlisted path still reaches.\n */\nconst mergeReached = (\n  reached: readonly { item: QueryItem; from: QueryItem; edge: TraversalEdge | undefined }[],\n): QueryItem[] => {\n  const merged = new Map<string, { item: QueryItem; paths: Map<string, QueryService.PathEdge[]>; unknown: boolean }>();\n  for (const { item, from, edge } of reached) {\n    const key = itemKey(item);\n    let entry = merged.get(key);\n    if (!entry) {\n      entry = { item, paths: new Map(), unknown: false };\n      merged.set(key, entry);\n    }\n    if (!edge || from.derivationUnknown) {\n      entry.unknown = true;\n      continue;\n    }\n    const hop: QueryService.PathEdge = {\n      from: from.objectId,\n      to: item.objectId,\n      kind: edge.kind,\n      ...(edge.property !== undefined && { property: edge.property }),\n      holder: edge.holder.objectId,\n      ...(edge.holder.heads && { holderHeads: [...edge.holder.heads] }),\n    };\n    for (const prefix of from.paths ?? [[]]) {\n      const path = [...prefix, hop];\n      const pathKey = path.map(({ from, to, kind, property }) => `${from}>${to}:${kind}:${property ?? ''}`).join('|');\n      if (!entry.paths.has(pathKey) && entry.paths.size >= MAX_PATHS_PER_ITEM) {\n        entry.unknown = true;\n        break;\n      }\n      entry.paths.set(pathKey, path);\n    }\n  }\n  return [...merged.values()].map(({ item, paths, unknown }) =>\n    unknown ? { ...item, paths: undefined, derivationUnknown: true } : { ...item, paths: [...paths.values()] },\n  );\n};\n\n/**\n * Attaches to each collapsed group the members it stands for, each with its share of the group's scalar\n * aggregates, so a client holding a member can swap the share for its local value. A group built from bare\n * index rows, whose values were never read, ships without one.\n */\nconst withManifests = (\n  collapsed: readonly QueryItem[],\n  members: readonly QueryItem[],\n  aggregates: readonly QueryAST.GroupAggregate[],\n): QueryItem[] => {\n  const scalar = aggregates.filter(\n    (aggregate): aggregate is Extract<QueryAST.GroupAggregate, { kind: 'count' | 'sum' | 'min' | 'max' }> =>\n      aggregate.kind === 'count' || aggregate.kind === 'sum' || aggregate.kind === 'min' || aggregate.kind === 'max',\n  );\n  // A count needs no member values, so a group of bare index rows can still list its members.\n  const readsValues = scalar.some((aggregate) => aggregate.kind !== 'count');\n  if (scalar.length === 0 || (readsValues && members.some((member) => !member.doc && !member.data))) {\n    return [...collapsed];\n  }\n  const byGroup = new Map<string, QueryService.ManifestEntry[]>();\n  for (const member of members) {\n    const key = serializeItemGroupKey(member);\n    const contribution: Record<string, unknown> = {};\n    for (const aggregate of scalar) {\n      contribution[aggregate.name] =\n        aggregate.kind === 'count'\n          ? 1\n          : GroupBy.coerceKeyComponent(QueryItem.getAggregateProperty(member, aggregate.property));\n    }\n    const version = QueryItem.getVersion(member);\n    const list = byGroup.get(key) ?? [];\n    list.push({ id: member.objectId, ...(version && { version }), contribution: JSON.stringify(contribution) });\n    byGroup.set(key, list);\n  }\n  return collapsed.map((item) => ({ ...item, manifest: byGroup.get(serializeItemGroupKey(item)) }));\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport { type DocumentId } from '@automerge/automerge-repo';\nimport * as Effect from 'effect/Effect';\nimport * as Schema from 'effect/Schema';\nimport type * as SqlClient from 'effect/sql/SqlClient';\nimport * as EffectStream from 'effect/Stream';\n\nimport { DeferredTask, scheduleMicroTask, scheduleTask, synchronized, yieldBehindQueuedTasks } from '@dxos/async';\nimport { Context, Resource } from '@dxos/context';\nimport { raise } from '@dxos/debug';\nimport { Query } from '@dxos/echo';\nimport { QueryAST } from '@dxos/echo-protocol';\nimport * as EffectEx from '@dxos/effect/EffectEx';\nimport type * as RuntimeProvider from '@dxos/effect/RuntimeProvider';\nimport { type FeedStore } from '@dxos/feed';\nimport { type IndexEngine } from '@dxos/index-core';\nimport { type SpaceId } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { QueryReactivity } from '@dxos/protocols/buf/dxos/echo/query_pb';\nimport { QueryService } from '@dxos/protocols/rpc';\nimport { trace } from '@dxos/tracing';\nimport { countWork } from '@dxos/util';\n\nimport { type AutomergeHost } from '../automerge/index.ts';\nimport { type ExecutionTrace, QueryExecutor, type QueryExecutorMode } from '../query/index.ts';\nimport { SLOW_WORK_MS } from '../util.ts';\nimport { IndexPassFailedError } from './index-scheduler.ts';\nimport { type InvalidationHint, mergeHints } from './invalidation-hint.ts';\nimport type { SpaceStateManager } from './space-state-manager.ts';\n\nexport type QueryServiceProps = {\n  /** Read on each query: the host builds its engine when it opens, after this service is constructed. */\n  indexEngine: () => IndexEngine;\n  runtime: RuntimeProvider.RuntimeProvider<SqlClient.SqlClient>;\n  automergeHost: AutomergeHost;\n  spaceStateManager: SpaceStateManager;\n  /**\n   * Brings the index up to date and resolves once done. Awaited before a feed-scoped query's first\n   * execution so that a query issued right after a feed append reads the just-written items instead\n   * of racing the host's deferred indexing task. Feed reads have no client-side working-set\n   * fallback, so the index is their only source of truth.\n   */\n  updateIndexes: () => Promise<void>;\n\n  /**\n   * True once every indexed object in scope has a snapshot (see `IndexEngine.hasCompleteSnapshots`).\n   * The compiled executor reads that store rather than loading documents, so while it is still\n   * filling after upgrade a query awaits indexing before its first execution. Ignored on the\n   * in-memory path, which loads documents itself.\n   */\n  hasCompleteSnapshots?: (scope: { spaceIds?: readonly SpaceId[]; feeds: boolean }) => Promise<boolean>;\n\n  /** Evaluation path for every query this service creates; see {@link QueryExecutorMode}. */\n  executor?: QueryExecutorMode;\n  /** Resolved lazily, like `indexEngine`: the client exists only once the host is open. */\n  sql: () => SqlClient.SqlClient;\n\n  /** Overrides {@link DEFAULT_QUERY_DEBOUNCE}. */\n  debounce?: Partial<QueryDebounceOptions>;\n\n  /** Whether any of a client's data subscriptions holds a document. */\n  holdsDocument?: (subscriptionIds: readonly string[], documentId: DocumentId) => boolean;\n\n  /** Read for feeds with indexing disabled and for feed retention; see the query executor's `feedStore`. */\n  feedStore?: FeedStore;\n};\n\n/**\n * How long a live query waits before re-running, in proportion to what its last run cost, so one\n * heavy query re-executing on every write cannot starve the cheap queries and writes sharing its worker.\n */\nexport type QueryDebounceOptions = {\n  /** Debounce window per millisecond of the last run: at 4 a query spends at most a fifth of the time running. */\n  factor: number;\n  /** Queries whose last run was cheaper than this (ms) re-run as soon as they are invalidated. */\n  minCost: number;\n  /** Ceiling on a debounce window (ms), so a very slow query still refreshes. */\n  maxDelay: number;\n  /** Cost (ms) charged for a run; defaults to its wall-clock time, which tests replace to be deterministic. */\n  cost?: (query: QueryAST.Query, measured: number) => number;\n};\n\n/** Longest stretch (ms) a batch runs queries before yielding, so answers and incoming requests are not held for the whole batch. */\nconst QUERY_SLICE_MS = 16;\n\nexport const DEFAULT_QUERY_DEBOUNCE: QueryDebounceOptions = {\n  factor: 4,\n  minCost: 16,\n  maxDelay: 5_000,\n};\n\n/**\n * Represents an active query (stream and query state connected to that stream).\n */\ntype ActiveQuery = {\n  executor: QueryExecutor;\n  /**\n   * Schedule re-execution of the query if true.\n   */\n  dirty: boolean;\n\n  open: boolean;\n\n  firstResult: boolean;\n\n  /** Query reads from at least one feed scope, so its first result must await indexing. */\n  feedScoped: boolean;\n\n  /** Answered once and never re-run; its stream ends after the first response. */\n  oneShot: boolean;\n\n  /** Cost (ms) of the last run; 0 until the query has run. */\n  cost: number;\n\n  /** `performance.now()` before which an invalidated query is left dirty rather than re-run. */\n  debouncedUntil: number;\n\n  sendResults: (results: QueryService.QueryResult[], executionTime: number, truncated?: 'paths' | 'manifest') => void;\n  /** Reports a re-run whose result matched the last one sent. */\n  sendUnchanged: (executionTime: number) => void;\n  onError: (err: Error) => void;\n\n  close: () => Promise<void>;\n};\n\ntype QueryInvalidationStats = {\n  totalInvalidations: number;\n  catchAllInvalidations: number;\n  hintedInvalidations: number;\n  totalDirtyQueriesExecuted: number;\n  totalExecutionBatches: number;\n  averageDirtyPerBatch: number;\n  averageQueriesActive: number;\n  /** Times a dirty query was left for a later batch because its debounce window was still open. */\n  totalDebounced: number;\n};\n\nexport class QueryServiceImpl extends Resource implements QueryService.Handlers {\n  // TODO(dmaretskyi): We need to implement query deduping. Idle composer has 80 queries with only 10 being unique.\n  private readonly '_queries' = new Set<ActiveQuery>();\n\n  private '_updateQueries'!: DeferredTask;\n\n  /** Reactive queries currently registered, across every space. */\n  get 'activeQueryCount'(): number {\n    return this._queries.size;\n  }\n\n  'getQueryTraces'(): ExecutionTrace[] {\n    return Array.from(this._queries, (query) => query.executor.trace);\n  }\n\n  readonly #snapshotsKnownComplete = new Set<string>();\n\n  readonly #snapshotsChecks = new Map<string, Promise<boolean>>();\n\n  async #snapshotsComplete(executor: QueryExecutor): Promise<boolean> {\n    const hasCompleteSnapshots = this._params.hasCompleteSnapshots;\n    if (!hasCompleteSnapshots) {\n      return true;\n    }\n    const spaceIds = executor.spaceIds ? [...executor.spaceIds].sort() : undefined;\n    const feeds = executor.readsFeeds;\n    const key = `${spaceIds?.join(',') ?? '*'}:${feeds}`;\n    if (this.#snapshotsKnownComplete.has(key)) {\n      return true;\n    }\n    let check = this.#snapshotsChecks.get(key);\n    if (!check) {\n      check = hasCompleteSnapshots({ spaceIds, feeds }).finally(() => this.#snapshotsChecks.delete(key));\n      this.#snapshotsChecks.set(key, check);\n    }\n    if (await check) {\n      this.#snapshotsKnownComplete.add(key);\n      return true;\n    }\n    return false;\n  }\n\n  // 'all' = catch-all; null = no pending hint.\n  #pendingHint: InvalidationHint | 'all' | null = null;\n\n  // Diagnostic counters.\n  #stats: QueryInvalidationStats = {\n    totalInvalidations: 0,\n    catchAllInvalidations: 0,\n    hintedInvalidations: 0,\n    totalDirtyQueriesExecuted: 0,\n    totalExecutionBatches: 0,\n    averageDirtyPerBatch: 0,\n    averageQueriesActive: 0,\n    totalDebounced: 0,\n  };\n\n  readonly #debounce: QueryDebounceOptions;\n\n  /** Set by {@link awaitQueryUpdates}: the next batch runs debounced queries too. */\n  #flushDebounced = false;\n\n  /** Owns the wake-up for the earliest debounce window; disposed to cancel it. */\n  #wakeCtx: Context | undefined;\n  #wakeAt = Infinity;\n\n  // TODO(burdon): OK for options, but not params. Pass separately and type readonly here.\n  'constructor'(private readonly _params: QueryServiceProps) {\n    super();\n    this.#debounce = { ...DEFAULT_QUERY_DEBOUNCE, ..._params.debounce };\n\n    trace.diagnostic({\n      id: 'active-queries',\n      name: 'Active Queries',\n      fetch: () => {\n        return Array.from(this._queries).map((query) => {\n          return {\n            query: JSON.stringify(query.executor.query),\n            plan: JSON.stringify(query.executor.plan),\n            trace: JSON.stringify(query.executor.trace),\n          };\n        });\n      },\n    });\n\n    trace.diagnostic<QueryInvalidationStats>({\n      id: 'query-invalidation',\n      name: 'Query Invalidation',\n      fetch: async () => ({ ...this.#stats }),\n    });\n  }\n\n  override async '_open'(): Promise<void> {\n    this._updateQueries = new DeferredTask(this._ctx, () => this._executeQueries(this._ctx));\n  }\n\n  @synchronized\n  override async '_close'(): Promise<void> {\n    this.#clearWake();\n    await this._updateQueries.join();\n    await Promise.all(Array.from(this._queries).map((query) => query.close()));\n  }\n\n  /**\n   * @deprecated No longer needed with SQL-based indexing.\n   */\n  ['QueryService.setConfig'](_request: QueryService.IndexConfig): Effect.Effect<void, Error> {\n    // No-op: SQL indexer doesn't need explicit configuration.\n    return Effect.void;\n  }\n\n  /**\n   * @deprecated No longer needed with SQL-based indexing.\n   */\n  ['QueryService.reindex'](): Effect.Effect<void, Error> {\n    // No-op: SQL indexer handles re-indexing automatically.\n    return Effect.sync(() => log.warn('reindex() is deprecated and no longer has any effect'));\n  }\n\n  ['QueryService.execQuery'](\n    request: QueryService.QueryRequest,\n  ): EffectStream.Stream<QueryService.QueryResponse, Error> {\n    const stream = EffectEx.streamFromEmitter<QueryService.QueryResponse, Error>((emit) => {\n      const ctx = Context.default();\n      const queryEntry = this._createQuery(\n        ctx,\n        request,\n        (response) => void emit.single(response),\n        (err) => void emit.fail(err),\n        () => void emit.end(),\n      );\n      scheduleMicroTask(ctx, async () => {\n        await queryEntry.executor.open();\n        const readsSnapshotStore = queryEntry.executor.compiled;\n        if (queryEntry.feedScoped || (readsSnapshotStore && !(await this.#snapshotsComplete(queryEntry.executor)))) {\n          // A failed pass is logged and retried by the scheduler; the query answers from the index as it stands.\n          await this._params.updateIndexes().catch((error) => {\n            if (!(error instanceof IndexPassFailedError)) {\n              throw error;\n            }\n          });\n        }\n        if (!this._queries.has(queryEntry)) {\n          return;\n        }\n        if (queryEntry.oneShot && queryEntry.executor.selectsById) {\n          await this.#runQuery(queryEntry);\n          return;\n        }\n        queryEntry.open = true;\n        this._updateQueries.schedule();\n      });\n      return Effect.promise(async () => {\n        await queryEntry.close();\n        await ctx.dispose();\n      });\n    });\n    // The client settles on the first response; ending the stream there runs the finalizer above.\n    return request.reactivity === QueryReactivity.ONE_SHOT ? stream.pipe(EffectStream.take(1)) : stream;\n  }\n\n  /**\n   * Schedule re-execution of queries, optionally guided by a targeted hint.\n   * When called without a hint, all queries are marked dirty (catch-all invalidation).\n   */\n  'invalidateQueries'(hint?: InvalidationHint): void {\n    this.#stats.totalInvalidations++;\n    if (!hint) {\n      this.#pendingHint = 'all';\n      this.#stats.catchAllInvalidations++;\n    } else {\n      this.#stats.hintedInvalidations++;\n      if (this.#pendingHint !== 'all') {\n        this.#pendingHint = this.#pendingHint ? mergeHints(this.#pendingHint, hint) : hint;\n      }\n    }\n    this._updateQueries.schedule();\n  }\n\n  /**\n   * Resolves once every query invalidated so far has re-run and sent its results, so a caller that\n   * waited for the index also sees the queries it changed. Debounced queries run now rather than\n   * when their window closes.\n   */\n  async 'awaitQueryUpdates'(): Promise<void> {\n    await this._updateQueries.join();\n    const pending =\n      this._updateQueries.scheduled ||\n      this.#pendingHint !== null ||\n      Array.from(this._queries).some((query) => query.open && query.dirty);\n    if (pending) {\n      this.#flushDebounced = true;\n      await this._updateQueries.runBlocking();\n    }\n  }\n\n  private '_createQuery'(\n    ctx: Context,\n    request: QueryService.QueryRequest,\n    onResults: (respose: QueryService.QueryResponse) => void,\n    onError: (err: Error) => void,\n    onClose: () => void,\n  ): ActiveQuery {\n    const parsedQuery = QueryAST.Query.pipe(Schema.decodeUnknownSync)(JSON.parse(request.query));\n    const subscriptionIds = request.subscriptionIds ?? [];\n    const queryEntry: ActiveQuery = {\n      executor: new QueryExecutor({\n        indexEngine: this._params.indexEngine(),\n        runtime: this._params.runtime,\n        automergeHost: this._params.automergeHost,\n        queryId: request.queryId ?? raise(new Error('query id required')),\n        query: parsedQuery,\n        reactivity: request.reactivity,\n        executor: this._params.executor,\n        sql: this._params.sql(),\n        spaceStateManager: this._params.spaceStateManager,\n        holds: (documentId) => this._params.holdsDocument?.(subscriptionIds, documentId) ?? false,\n        feedStore: this._params.feedStore,\n      }),\n      dirty: true,\n      open: false,\n      firstResult: true,\n      feedScoped: queryHasFeedScope(parsedQuery),\n      oneShot: request.reactivity === QueryReactivity.ONE_SHOT,\n      cost: 0,\n      debouncedUntil: 0,\n      sendResults: (results, executionTime, truncated) => {\n        if (ctx.disposed) {\n          return;\n        }\n        onResults({ queryId: request.queryId, results, executionTime, ...(truncated && { truncated }) });\n      },\n      sendUnchanged: (executionTime) => {\n        if (ctx.disposed) {\n          return;\n        }\n        onResults({ queryId: request.queryId, unchanged: true, executionTime });\n      },\n      onError,\n      close: async () => {\n        // Cleared first so a batch that has not reached this query yet skips it instead of running a closed executor.\n        queryEntry.open = false;\n        onClose();\n        await queryEntry.executor.close();\n        this._queries.delete(queryEntry);\n      },\n    };\n    this._queries.add(queryEntry);\n    return queryEntry;\n  }\n\n  @trace.span({ showInBrowserTimeline: true, showInRemoteTracing: false })\n  private async '_executeQueries'(_ctx: Context) {\n    const hint = this.#pendingHint;\n    this.#pendingHint = null;\n\n    // Apply hint to determine which queries need re-execution.\n    for (const query of this._queries) {\n      if (!query.open) {\n        continue;\n      }\n      if (query.firstResult) {\n        // First run is always executed regardless of hint.\n        query.dirty = true;\n        continue;\n      }\n      if (query.oneShot) {\n        continue;\n      }\n      if (hint === 'all') {\n        query.dirty = true;\n        continue;\n      }\n      if (hint && query.executor.matchesHint(hint)) {\n        query.dirty = true;\n      }\n    }\n\n    const flush = this.#flushDebounced;\n    this.#flushDebounced = false;\n\n    const begin = performance.now();\n    const activeCount = this._queries.size;\n    const ready: ActiveQuery[] = [];\n    const deferred: ActiveQuery[] = [];\n    for (const query of this._queries) {\n      if (!query.dirty || !query.open) {\n        continue;\n      }\n      if (!flush && !query.firstResult && query.debouncedUntil > begin) {\n        deferred.push(query);\n      } else {\n        ready.push(query);\n      }\n    }\n    this.#stats.totalDebounced += deferred.length;\n\n    // One at a time, cheapest first: SQLite runs synchronously, so interleaved queries would all finish with the\n    // slowest and each run's measured time would include the others' statements.\n    ready.sort((left, right) => left.cost - right.cost);\n    let sliceStart = performance.now();\n    let executing = 0;\n    for (const query of ready) {\n      if (!query.open) {\n        continue;\n      }\n      const queryStart = performance.now();\n      await this.#runQuery(query);\n      executing += performance.now() - queryStart;\n      // Without a turn the whole batch is one task, and its answers and the requests queued behind it wait for the last query.\n      if (performance.now() - sliceStart >= QUERY_SLICE_MS) {\n        await yieldBehindQueuedTasks();\n        sliceStart = performance.now();\n      }\n    }\n    const dirtyCount = ready.length;\n\n    this.#scheduleWake(deferred);\n\n    this.#stats.totalExecutionBatches++;\n    this.#stats.totalDirtyQueriesExecuted += dirtyCount;\n    this.#stats.averageDirtyPerBatch = this.#stats.totalDirtyQueriesExecuted / this.#stats.totalExecutionBatches;\n    this.#stats.averageQueriesActive =\n      (this.#stats.averageQueriesActive * (this.#stats.totalExecutionBatches - 1) + activeCount) /\n      this.#stats.totalExecutionBatches;\n\n    // Judged on time spent in queries: the wall-clock `duration` also counts the slice yields, which wait behind\n    // whatever else the worker is doing (indexing at boot) and make a batch of fast queries look slow.\n    const duration = performance.now() - begin;\n    if (executing >= SLOW_WORK_MS) {\n      const slowest = ready.reduce<ActiveQuery | undefined>(\n        (max, query) => (max && max.cost >= query.cost ? max : query),\n        undefined,\n      );\n      log.warn('slow query batch', {\n        dirty: dirtyCount,\n        active: activeCount,\n        executing,\n        duration,\n        slowest: slowest && Query.pretty(Query.fromAst(slowest.executor.query)),\n        slowestCost: slowest?.cost,\n      });\n    } else {\n      log.verbose('executed queries', { dirty: dirtyCount, active: activeCount, executing, duration });\n    }\n  }\n\n  async #runQuery(query: ActiveQuery): Promise<void> {\n    try {\n      const begin = performance.now();\n      const { changed } = await query.executor.execQuery();\n      const finishedAt = performance.now();\n      countWork('echo.queryExecutions');\n      query.cost = this.#debounce.cost?.(query.executor.query, finishedAt - begin) ?? finishedAt - begin;\n      query.debouncedUntil =\n        query.cost < this.#debounce.minCost\n          ? 0\n          : finishedAt + Math.min(this.#debounce.factor * query.cost, this.#debounce.maxDelay);\n      query.dirty = false;\n      if (changed || query.firstResult) {\n        query.firstResult = false;\n        const results = await query.executor.getResults();\n        countWork('echo.queryResultsSent');\n        countWork('echo.queryResultRows', results.length);\n        query.sendResults(results, performance.now() - begin, query.executor.truncated);\n      } else if (!query.oneShot) {\n        // A client that holds local writes against this query waits for a re-run to know its answer is current.\n        query.sendUnchanged(finishedAt - begin);\n      }\n    } catch (err) {\n      log.catch(err, {\n        queryId: query.executor.queryId,\n        query: JSON.stringify(query.executor.query),\n      });\n      query.onError(err as Error);\n    }\n  }\n\n  /** Arms a wake-up for the earliest deferred query, so its pending invalidation is not lost. */\n  #scheduleWake(deferred: ActiveQuery[]): void {\n    let wakeAt = Infinity;\n    for (const query of deferred) {\n      if (query.open && query.dirty) {\n        wakeAt = Math.min(wakeAt, query.debouncedUntil);\n      }\n    }\n    if (wakeAt === Infinity || wakeAt >= this.#wakeAt || this._ctx.disposed) {\n      return;\n    }\n    this.#clearWake();\n    this.#wakeAt = wakeAt;\n    const wakeCtx = this._ctx.derive();\n    this.#wakeCtx = wakeCtx;\n    scheduleTask(\n      wakeCtx,\n      () => {\n        this.#clearWake();\n        this._updateQueries.schedule();\n      },\n      Math.max(0, wakeAt - performance.now()),\n    );\n  }\n\n  #clearWake(): void {\n    void this.#wakeCtx?.dispose();\n    this.#wakeCtx = undefined;\n    this.#wakeAt = Infinity;\n  }\n}\n\n/**\n * True when the query's `from` clause carries at least one feed scope (`Scope.feed(...)`).\n */\nconst queryHasFeedScope = (query: QueryAST.Query): boolean => {\n  let found = false;\n  QueryAST.visit(query, (node) => {\n    if (node.type === 'from' && node.from._tag === 'scope' && node.from.scopes.some((scope) => scope._tag === 'feed')) {\n      found = true;\n    }\n  });\n  return found;\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport * as SqlMigrations from '@dxos/sql-sqlite/SqlMigrations';\n\nimport init from './0001_init.sql?raw';\nimport spaceRoot from './0002_space_root.sql?raw';\nimport directorySnapshots from './0003_directory_snapshots.sql?raw';\n\n/** An applied migration must never be edited — nothing verifies its contents. */\nexport const MIGRATIONS = {\n  '0001_init': SqlMigrations.apply(init),\n  '0002_space_root': SqlMigrations.apply(spaceRoot),\n  '0003_directory_snapshots': SqlMigrations.apply(directorySnapshots),\n};\n\n/** Own history table per store, since many stores share the client database. */\nexport const MIGRATIONS_TABLE = 'space_state_migrations';\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport * as A from '@automerge/automerge';\n\nimport { log } from '@dxos/log';\n\nexport type DocMetrics = {\n  compressedByteSize: number;\n  loadTime: number;\n  mutationCount: number;\n};\n\n/**\n * WARN: Slow to run on large docs.\n */\nexport const measureDocMetrics = (doc: A.Doc<any>): DocMetrics => {\n  const snapshot = A.save(doc);\n\n  const start = Date.now();\n  const temp = A.load(snapshot);\n  const end = Date.now();\n  A.free(temp);\n\n  const getAllChangesStart = Date.now();\n  const mutationCount = A.getAllChanges(doc).length;\n  const getAllChangesEnd = Date.now();\n\n  if (getAllChangesEnd - getAllChangesStart > 300) {\n    log.warn('getAllChanges took too long', { elapsed: getAllChangesEnd - getAllChangesStart });\n  }\n\n  return {\n    compressedByteSize: snapshot.byteLength,\n    loadTime: end - start,\n    mutationCount,\n  };\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport { next as A } from '@automerge/automerge';\nimport {\n  type AutomergeUrl,\n  type DocumentId,\n  interpretAsDocumentId,\n  isValidAutomergeUrl,\n} from '@automerge/automerge-repo';\n\nimport { Event } from '@dxos/async';\nimport { DatabaseDirectory, type DirectoryJson, SpaceDocVersion } from '@dxos/echo-protocol';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\n\nimport { type DocumentLease } from '../automerge/document-lease.ts';\nimport { type DocMetrics, measureDocMetrics } from './automerge-metrics.ts';\n\n/** A space directory's JSON and the stored heads it was read at; see `directoryJson` in `@dxos/echo-protocol`. */\nexport type DirectorySnapshot = { heads: A.Heads; json: DirectoryJson };\n\nexport type DatabaseRootSource =\n  | { lease: DocumentLease<DatabaseDirectory> }\n  | {\n      documentId: DocumentId;\n      snapshot: DirectorySnapshot;\n      /** Leases the root's document once it is loaded. */\n      load: () => Promise<DocumentLease<DatabaseDirectory>>;\n      /** Each save on the host; one for this root means the snapshot no longer shows it. */\n      headsChanged: Event<{ documentId: DocumentId }>;\n    };\n\nexport class DatabaseRoot implements Disposable {\n  static mapLinks(document: DocumentLease<DatabaseDirectory>, mapping: Record<DocumentId, DocumentId>): void {\n    const remap = (url: string): string | undefined => {\n      if (!isValidAutomergeUrl(url)) {\n        return undefined;\n      }\n      const documentId = interpretAsDocumentId(url);\n      return mapping[documentId] ? `automerge:${mapping[documentId]}` : undefined;\n    };\n    document.change((draft) => {\n      for (const [key, value] of Object.entries(draft.links ?? {})) {\n        const mapped = remap(value.toString());\n        if (mapped && draft.links) {\n          draft.links[key] = mapped;\n        }\n      }\n      // Branch documents live in the `branches` registry, not `links`, so they must be remapped here\n      // too — otherwise an imported/copied space's branches point at the source space's documents.\n      for (const byName of Object.values(draft.branches ?? {})) {\n        for (const record of Object.values(byName)) {\n          for (const [objectId, value] of Object.entries(record.members ?? {})) {\n            const mapped = remap(value.toString());\n            if (mapped) {\n              record.members[objectId] = mapped;\n            }\n          }\n        }\n      }\n    });\n  }\n\n  readonly #documentId: DocumentId;\n\n  /** Held once the root is loaded; a root opened from a snapshot takes it on its first write or change. */\n  #lease: DocumentLease<DatabaseDirectory> | undefined;\n\n  /** What the root shows until it is loaded: its directory JSON at the heads the host stores it at. */\n  #snapshot: DirectorySnapshot | undefined;\n\n  readonly #source: DatabaseRootSource;\n  #loading: Promise<void> | undefined;\n  #disposed = false;\n  readonly #unsubscribe: () => void;\n\n  /** Emitted when the directory changes: each change of the loaded root, and the load that ends a snapshot. */\n  readonly changed = new Event<void>();\n\n  /**\n   * A root from a lease is loaded for as long as the space is open. A root from a snapshot is read from it without\n   * loading, until something writes to the root or its stored heads move; then it loads and stays loaded.\n   */\n  constructor(source: DatabaseRootSource) {\n    this.#source = source;\n    if ('lease' in source) {\n      this.#documentId = source.lease.documentId;\n      this.#attach(source.lease);\n      this.#unsubscribe = () => {};\n    } else {\n      this.#documentId = source.documentId;\n      this.#snapshot = source.snapshot;\n      this.#unsubscribe = source.headsChanged.on(({ documentId }) => {\n        if (documentId === this.#documentId && !this.#lease) {\n          void this.load().catch((err) => log.warn('space root failed to load after a change', { documentId, err }));\n        }\n      });\n    }\n  }\n\n  get documentId(): DocumentId {\n    return this.#documentId;\n  }\n\n  /** Derived from the id, so a root whose lease was released still reports which document it was. */\n  get url(): AutomergeUrl {\n    return `automerge:${this.#documentId}` as AutomergeUrl;\n  }\n\n  /** Whether the root's Automerge document is loaded. */\n  get isLoaded(): boolean {\n    const lease = this.#lease;\n    return lease !== undefined && !lease.disposed && lease.state === 'ready';\n  }\n\n  /** Whether the root can be read: loaded, or shown from its snapshot. */\n  get isAvailable(): boolean {\n    return this.isLoaded || this.#snapshot !== undefined;\n  }\n\n  /** Loads the root's document if it was opened from a snapshot; writers await it before {@link change}. */\n  async load(): Promise<void> {\n    if (this.#lease || this.#disposed) {\n      return;\n    }\n    const source = this.#source;\n    invariant(!('lease' in source));\n    this.#loading ??= source.load().then((lease) => {\n      if (this.#disposed) {\n        lease[Symbol.dispose]();\n        return;\n      }\n      this.#attach(lease);\n      this.#snapshot = undefined;\n      this.changed.emit();\n    });\n    try {\n      await this.#loading;\n    } finally {\n      this.#loading = undefined;\n    }\n  }\n\n  /**\n   * The `DocHandle` stays inside the lease — a caller holding one would read and write a document the\n   * host had evicted, so the operations the root needs are proxied instead.\n   */\n  change(callback: Parameters<DocumentLease<DatabaseDirectory>['change']>[0]): void {\n    invariant(this.#lease, 'A space root opened from its snapshot must load before it is written.');\n    this.#lease.change(callback);\n  }\n\n  /** Releases the root document, which is the last thing keeping the space's directory resident. */\n  [Symbol.dispose](): void {\n    this.#disposed = true;\n    this.#unsubscribe();\n    if (this.#lease) {\n      this.#lease.off('change', this.#onChange);\n      this.#lease[Symbol.dispose]();\n    }\n  }\n\n  /** The root's directory as it reads now: the loaded document, or the snapshot it was opened from. */\n  directory(): DatabaseDirectory | null {\n    return this.doc() ?? this.#snapshot?.json ?? null;\n  }\n\n  /** The heads {@link directory} is read at. */\n  heads(): A.Heads | null {\n    const doc = this.doc();\n    return doc ? A.getHeads(doc) : (this.#snapshot?.heads ?? null);\n  }\n\n  #attach(lease: DocumentLease<DatabaseDirectory>): void {\n    this.#lease = lease;\n    lease.on('change', this.#onChange);\n  }\n\n  readonly #onChange = (): void => this.changed.emit();\n\n  /** The loaded Automerge document; null for a root shown from its snapshot. */\n  doc(): A.Doc<DatabaseDirectory> | null {\n    return this.isLoaded && this.#lease ? this.#lease.doc() : null;\n  }\n\n  getVersion(): SpaceDocVersion | null {\n    const doc = this.directory();\n    if (!doc) {\n      return null;\n    }\n\n    return doc.version ?? SpaceDocVersion.LEGACY;\n  }\n\n  getSpaceKey(): string | null {\n    const doc = this.directory();\n    if (!doc) {\n      return null;\n    }\n\n    return DatabaseDirectory.getSpaceKey(doc);\n  }\n\n  /** @deprecated Inline directory objects are migrated into linked documents; this counts the ones left. */\n  getInlineObjectCount(): number | null {\n    const doc = this.directory();\n    if (!doc) {\n      return null;\n    }\n\n    return Object.keys(doc.objects ?? {}).length;\n  }\n\n  getLinkedObjectCount(): number | null {\n    const doc = this.directory();\n    if (!doc) {\n      return null;\n    }\n\n    return Object.keys(doc.links ?? {}).length;\n  }\n\n  getAllLinkedDocuments(): AutomergeUrl[] {\n    const doc = this.directory();\n    invariant(doc);\n\n    // .toString() to handle RawString. Branch documents are referenced via the `branches` registry\n    // (not `links`), so they must be collected here too in order to replicate.\n    return [\n      ...Object.values(doc.links ?? {}).map((s) => s.toString()),\n      ...DatabaseDirectory.getAllBranchDocUrls(doc),\n    ] as AutomergeUrl[];\n  }\n\n  measureMetrics(): DocMetrics | null {\n    const doc = this.doc();\n    if (!doc) {\n      return null;\n    }\n    return measureDocMetrics(doc);\n  }\n}\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport {\n  type AutomergeUrl,\n  type DocumentId,\n  interpretAsDocumentId,\n  isValidAutomergeUrl,\n} from '@automerge/automerge-repo';\nimport * as Effect from 'effect/Effect';\nimport * as Migrator from 'effect/sql/Migrator';\nimport * as SqlClient from 'effect/sql/SqlClient';\nimport type * as SqlError from 'effect/sql/SqlError';\nimport isEqual from 'fast-deep-equal';\n\nimport { Event, UpdateScheduler } from '@dxos/async';\nimport { Context, LifecycleState, Resource } from '@dxos/context';\nimport { DatabaseDirectory } from '@dxos/echo-protocol';\nimport * as RuntimeProvider from '@dxos/effect/RuntimeProvider';\nimport { invariant } from '@dxos/invariant';\nimport { type SpaceId } from '@dxos/keys';\nimport { log } from '@dxos/log';\n\nimport { MIGRATIONS, MIGRATIONS_TABLE } from '../migrations/space-state/index.ts';\nimport { DatabaseRoot, type DatabaseRootSource } from './database-root.ts';\n\nexport type SpaceStateManagerProps = {\n  runtime: RuntimeProvider.RuntimeProvider<SqlClient.SqlClient>;\n};\n\nexport class SpaceStateManager extends Resource {\n  private readonly _runtime: RuntimeProvider.RuntimeProvider<SqlClient.SqlClient>;\n\n  private readonly _roots = new Map<DocumentId, DatabaseRoot>();\n  private readonly _rootBySpace = new Map<SpaceId, DocumentId>();\n  /** Keyed by space, not by root document: two spaces can share one root and must tear down apart. */\n  private readonly _perSpaceContext = new Map<SpaceId, Context>();\n  private readonly _lastSpaceDocumentList = new Map<SpaceId, DocumentId[]>();\n  private readonly _spaceRootRefs = new Map<SpaceId, SpaceRootRefs>();\n  /** Re-runs a space's document-list check; the anchor documents enter the list only once refs exist. */\n  private readonly _documentListCheck = new Map<SpaceId, () => void>();\n\n  public readonly spaceDocumentListUpdated = new Event<SpaceDocumentListUpdatedEvent>();\n\n  constructor({ runtime }: SpaceStateManagerProps) {\n    super();\n    this._runtime = runtime;\n  }\n\n  /**\n   * Applies any migrations this database has not recorded yet.\n   */\n  readonly migrate: Effect.Effect<void, SqlError.SqlError, SqlClient.SqlClient> = Migrator.make({})({\n    loader: Migrator.fromRecord(MIGRATIONS),\n    table: MIGRATIONS_TABLE,\n  }).pipe(\n    // A malformed bundled manifest is a defect, not something a caller can recover from.\n    Effect.catchTag('MigrationError', (error) => Effect.die(error)),\n    Effect.asVoid,\n    Effect.withSpan('SpaceStateManager.migrate'),\n  );\n\n  protected override async _open(ctx: Context): Promise<void> {\n    log('SpaceStateManager: running migration...');\n    await RuntimeProvider.runPromise(this._runtime)(this.migrate);\n    log('SpaceStateManager: loading spaces...');\n    await this._loadSpaces();\n  }\n\n  protected override async _close(ctx: Context): Promise<void> {\n    for (const [_, spaceCtx] of this._perSpaceContext) {\n      await spaceCtx.dispose();\n    }\n    for (const root of this._roots.values()) {\n      root[Symbol.dispose]();\n    }\n    this._roots.clear();\n    this._rootBySpace.clear();\n    this._perSpaceContext.clear();\n    this._lastSpaceDocumentList.clear();\n    this._spaceRootRefs.clear();\n  }\n\n  get roots(): ReadonlyMap<DocumentId, DatabaseRoot> {\n    return this._roots;\n  }\n\n  get spaceIds(): SpaceId[] {\n    return Array.from(this._rootBySpace.keys());\n  }\n\n  getRootByDocumentId(documentId: DocumentId): DatabaseRoot | undefined {\n    return this._roots.get(documentId);\n  }\n\n  /** Whether the document is the directory of a space this host stores, opened this session or not. */\n  isSpaceRootDocument(documentId: DocumentId): boolean {\n    for (const rootId of this._rootBySpace.values()) {\n      if (rootId === documentId) {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  getSpaceRootDocumentId(spaceId: SpaceId): DocumentId | undefined {\n    return this._rootBySpace.get(spaceId);\n  }\n\n  getRootBySpaceId(spaceId: SpaceId): DatabaseRoot | undefined {\n    invariant(this._lifecycleState === LifecycleState.OPEN);\n    const documentId = this._rootBySpace.get(spaceId);\n    if (!documentId) {\n      return undefined;\n    }\n    return this._roots.get(documentId);\n  }\n\n  isBranchDocument(documentId: DocumentId): boolean {\n    for (const root of this._roots.values()) {\n      const doc = root.directory();\n      if (!doc) {\n        continue;\n      }\n      for (const url of DatabaseDirectory.getAllBranchDocUrls(doc)) {\n        if (isValidAutomergeUrl(url) && interpretAsDocumentId(url) === documentId) {\n          return true;\n        }\n      }\n    }\n    return false;\n  }\n\n  /**\n   * References carried by the space root document, or undefined for a space that has none yet\n   * (every space created before the root document existed).\n   */\n  getSpaceRootRefs(spaceId: SpaceId): SpaceRootRefs | undefined {\n    return this._spaceRootRefs.get(spaceId);\n  }\n\n  /** The root is immutable, so this is written once per space — at creation, or when a legacy space gains one. */\n  async setSpaceRootRefs(spaceId: SpaceId, refs: SpaceRootRefs): Promise<void> {\n    // The refs are stored as columns on the space's row, so without one the UPDATE below matches\n    // nothing and the refs would survive only in memory — lost on the next open.\n    invariant(this._rootBySpace.has(spaceId), 'Space has no directory assigned.');\n    await this._saveSpaceRootRefs(spaceId, refs);\n    // Normalized so a caller sees the same shape here as after a reload, where SQL yields every column.\n    this._spaceRootRefs.set(spaceId, {\n      spaceRootDocUrl: refs.spaceRootDocUrl,\n      credentialsDocUrl: refs.credentialsDocUrl,\n    });\n    // The list was computed before these existed, and nothing else changes to trigger a recheck.\n    this._documentListCheck.get(spaceId)?.();\n  }\n\n  /**\n   * Get all persisted spaces.\n   */\n  getPersistedSpaces(): Array<{ spaceId: SpaceId; rootDocUrl: AutomergeUrl }> {\n    const spaces: Array<{ spaceId: SpaceId; rootDocUrl: AutomergeUrl }> = [];\n    for (const [spaceId, documentId] of this._rootBySpace.entries()) {\n      const root = this._roots.get(documentId);\n      const url = root ? root.url : (`automerge:${documentId}` as AutomergeUrl);\n      spaces.push({ spaceId, rootDocUrl: url });\n    }\n    return spaces;\n  }\n\n  /**\n   * Remove a space from the persistent store and close its resources.\n   */\n  async removeSpace(spaceId: SpaceId): Promise<void> {\n    const documentId = this._rootBySpace.get(spaceId);\n    if (!documentId) {\n      return;\n    }\n    await this._deleteSpace(spaceId);\n    this._rootBySpace.delete(spaceId);\n    this._lastSpaceDocumentList.delete(spaceId);\n    this._spaceRootRefs.delete(spaceId);\n\n    const spaceCtx = this._perSpaceContext.get(spaceId);\n    if (spaceCtx) {\n      await spaceCtx.dispose();\n      this._perSpaceContext.delete(spaceId);\n    }\n    // Kept while another space still reads through the same root, whose lease it shares.\n    if (!this._isRootReferenced(documentId)) {\n      this._roots.get(documentId)?.[Symbol.dispose]();\n      this._roots.delete(documentId);\n    }\n  }\n\n  /** Whether any space still reads through this root document. */\n  private _isRootReferenced(documentId: DocumentId): boolean {\n    for (const rootId of this._rootBySpace.values()) {\n      if (rootId === documentId) {\n        return true;\n      }\n    }\n    return false;\n  }\n\n  /** Takes ownership of a lease in `source`: the root holds it until the space is removed or the manager closes. */\n  async assignRootToSpace(spaceId: SpaceId, source: DatabaseRootSource): Promise<DatabaseRoot> {\n    let root: DatabaseRoot;\n    const documentId = 'lease' in source ? source.lease.documentId : source.documentId;\n    const existing = this._roots.get(documentId);\n    if (existing) {\n      root = existing;\n      // The root already holds this document, so the caller's lease is surplus.\n      if ('lease' in source) {\n        source.lease[Symbol.dispose]();\n      }\n    } else {\n      root = new DatabaseRoot(source);\n      this._roots.set(documentId, root);\n    }\n\n    if (this._rootBySpace.get(spaceId) === root.documentId && this._perSpaceContext.has(spaceId)) {\n      return root;\n    }\n\n    const prevRootId = this._rootBySpace.get(spaceId);\n    if (prevRootId) {\n      // Awaited: the context detaches the root's `change` listener, which needs the lease disposed\n      // below to still be live.\n      await this._perSpaceContext.get(spaceId)?.dispose();\n      this._perSpaceContext.delete(spaceId);\n    }\n\n    this._rootBySpace.set(spaceId, root.documentId);\n\n    // The replaced root is released here rather than at `removeSpace`, which only ever sees the\n    // current one — its lease would otherwise keep the retired directory resident for the session.\n    // A root shared with another space stays, since that space still reads through it.\n    if (prevRootId && prevRootId !== root.documentId && !this._isRootReferenced(prevRootId)) {\n      this._roots.get(prevRootId)?.[Symbol.dispose]();\n      this._roots.delete(prevRootId);\n    }\n\n    // A space restored from storage is re-assigned the directory it was saved with, which retires nothing\n    // and has nothing new to persist.\n    let retiredRootId = prevRootId !== root.documentId ? prevRootId : undefined;\n    if (prevRootId !== root.documentId) {\n      await this._saveSpace(spaceId, root.url);\n    }\n\n    const ctx = new Context();\n\n    this._perSpaceContext.set(spaceId, ctx);\n\n    // Each check runs on every directory change, and decoding a url costs a base58check SHA-256; the\n    // ids of links seen by the previous check are reused, so the cache holds only the current links.\n    let linkedIds = new Map<AutomergeUrl, DocumentId>();\n    const documentListCheckScheduler = new UpdateScheduler(\n      ctx,\n      async () => {\n        // The space root and its credentials document hang off the space, not off the directory's\n        // links, so they replicate only if named here — without them a peer (edge included) can\n        // never read the credentials the space was anchored on.\n        const anchorIds = Object.values(this._spaceRootRefs.get(spaceId) ?? {})\n          .filter((url): url is AutomergeUrl => typeof url === 'string')\n          .map((url) => interpretAsDocumentId(url));\n        const documentIds = [root.documentId, ...anchorIds];\n        const nextLinkedIds = new Map<AutomergeUrl, DocumentId>();\n        for (const url of root.getAllLinkedDocuments()) {\n          const documentId = linkedIds.get(url) ?? interpretAsDocumentId(url);\n          nextLinkedIds.set(url, documentId);\n          documentIds.push(documentId);\n        }\n        linkedIds = nextLinkedIds;\n        if (!isEqual(documentIds, this._lastSpaceDocumentList.get(spaceId))) {\n          this._lastSpaceDocumentList.set(spaceId, documentIds);\n          const event = new SpaceDocumentListUpdatedEvent(spaceId, root.documentId, retiredRootId, documentIds);\n          // Reported once: listeners tear down the retired root's sync state, which must not repeat per list change.\n          retiredRootId = undefined;\n          this.spaceDocumentListUpdated.emit(event);\n        }\n      },\n      { maxFrequency: 50 },\n    );\n    this._documentListCheck.set(spaceId, () => documentListCheckScheduler.trigger());\n    ctx.onDispose(() => this._documentListCheck.delete(spaceId));\n\n    const triggerCheckOnChange = () => documentListCheckScheduler.trigger();\n    ctx.onDispose(root.changed.on(triggerCheckOnChange));\n\n    documentListCheckScheduler.trigger();\n\n    return root;\n  }\n\n  private async _loadSpaces(): Promise<void> {\n    const rows = await RuntimeProvider.runPromise(this._runtime)(\n      Effect.gen(function* () {\n        const sql = yield* SqlClient.SqlClient;\n        return yield* sql<{\n          space_id: string;\n          root_doc_url: string;\n          space_root_doc_url: string | null;\n          credentials_doc_url: string | null;\n        }>`SELECT space_id, root_doc_url, space_root_doc_url, credentials_doc_url FROM echo_spaces`;\n      }),\n    );\n    for (const row of rows) {\n      const spaceId = row.space_id as SpaceId;\n      const rootDocUrl = row.root_doc_url as AutomergeUrl;\n      const documentId = interpretAsDocumentId(rootDocUrl);\n      this._rootBySpace.set(spaceId, documentId);\n      if (row.space_root_doc_url) {\n        this._spaceRootRefs.set(spaceId, {\n          spaceRootDocUrl: row.space_root_doc_url as AutomergeUrl,\n          credentialsDocUrl: (row.credentials_doc_url ?? undefined) as AutomergeUrl | undefined,\n        });\n      }\n    }\n  }\n\n  private async _saveSpace(spaceId: SpaceId, rootDocUrl: AutomergeUrl): Promise<void> {\n    await RuntimeProvider.runPromise(this._runtime)(\n      Effect.gen(function* () {\n        const sql = yield* SqlClient.SqlClient;\n        // Upsert rather than INSERT OR REPLACE: the latter deletes the row, discarding the space-root columns.\n        yield* sql`INSERT INTO echo_spaces (space_id, root_doc_url) VALUES (${spaceId}, ${rootDocUrl})\n          ON CONFLICT(space_id) DO UPDATE SET root_doc_url = excluded.root_doc_url`;\n      }),\n    );\n  }\n\n  private async _saveSpaceRootRefs(spaceId: SpaceId, refs: SpaceRootRefs): Promise<void> {\n    await RuntimeProvider.runPromise(this._runtime)(\n      Effect.gen(function* () {\n        const sql = yield* SqlClient.SqlClient;\n        yield* sql`UPDATE echo_spaces SET space_root_doc_url = ${refs.spaceRootDocUrl},\n          credentials_doc_url = ${refs.credentialsDocUrl ?? null}\n          WHERE space_id = ${spaceId}`;\n      }),\n    );\n  }\n\n  private async _deleteSpace(spaceId: SpaceId): Promise<void> {\n    const rootId = this._rootBySpace.get(spaceId);\n    const shared =\n      rootId !== undefined && [...this._rootBySpace].some(([id, root]) => id !== spaceId && root === rootId);\n    await RuntimeProvider.runPromise(this._runtime)(\n      Effect.gen(function* () {\n        const sql = yield* SqlClient.SqlClient;\n        yield* sql`DELETE FROM echo_spaces WHERE space_id = ${spaceId}`;\n        if (rootId !== undefined && !shared) {\n          yield* sql`DELETE FROM echo_directory_snapshots WHERE document_id = ${rootId}`;\n        }\n      }),\n    );\n  }\n\n  /** The directory JSON last stored for a space root, with the heads it was read at. */\n  async readDirectorySnapshot(documentId: DocumentId): Promise<DirectorySnapshotRow | undefined> {\n    const rows = await RuntimeProvider.runPromise(this._runtime)(\n      Effect.gen(function* () {\n        const sql = yield* SqlClient.SqlClient;\n        return yield* sql<{\n          heads: string;\n          json: string;\n        }>`SELECT heads, json FROM echo_directory_snapshots WHERE document_id = ${documentId}`;\n      }),\n    );\n    const [row] = rows;\n    return row ? { heads: JSON.parse(row.heads), json: row.json } : undefined;\n  }\n\n  async writeDirectorySnapshot(documentId: DocumentId, { heads, json }: DirectorySnapshotRow): Promise<void> {\n    const encodedHeads = JSON.stringify(heads);\n    await RuntimeProvider.runPromise(this._runtime)(\n      Effect.gen(function* () {\n        const sql = yield* SqlClient.SqlClient;\n        yield* sql`INSERT INTO echo_directory_snapshots (document_id, heads, json) VALUES (${documentId}, ${encodedHeads}, ${json})\n          ON CONFLICT(document_id) DO UPDATE SET heads = excluded.heads, json = excluded.json`;\n      }),\n    );\n  }\n}\n\n/**\n * The references a space root document carries, as persisted beside the space. The directory lives in\n * `root_doc_url` and is reached through {@link SpaceStateManager.getRootBySpaceId}.\n */\nexport type SpaceRootRefs = {\n  spaceRootDocUrl: AutomergeUrl;\n  credentialsDocUrl?: AutomergeUrl;\n};\n\n/** A space directory's JSON and the heads it was read at; see `directoryJson` in `@dxos/echo-protocol`. */\nexport type DirectorySnapshotRow = { heads: readonly string[]; json: string };\n\nexport class SpaceDocumentListUpdatedEvent {\n  constructor(\n    public readonly spaceId: SpaceId,\n    public readonly spaceRootId: DocumentId,\n    /** The directory `spaceRootId` replaced; set only on the first update after the swap. */\n    public readonly previousRootId: DocumentId | undefined,\n    public readonly documentIds: DocumentId[],\n  ) {}\n}\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport { next as A, type Heads } from '@automerge/automerge';\nimport {\n  type AnyDocumentId,\n  type AutomergeUrl,\n  type DocumentId,\n  interpretAsDocumentId,\n  isValidAutomergeUrl,\n  isValidDocumentId,\n  stringifyAutomergeUrl,\n} from '@automerge/automerge-repo';\nimport * as Clock from 'effect/Clock';\nimport * as EffectContext from 'effect/Context';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\nimport * as SqlClient from 'effect/sql/SqlClient';\nimport isEqual from 'fast-deep-equal';\n\nimport { Mutex, scheduleTask, sleep, yieldBehindQueuedTasks } from '@dxos/async';\nimport { Context, LifecycleState, Resource } from '@dxos/context';\nimport { todo } from '@dxos/debug';\nimport {\n  DatabaseDirectory,\n  EntityStructure,\n  type RetirementReason,\n  SPACE_ROOT_TYPE,\n  SpaceDocVersion,\n  type SpaceRoot,\n  createIdFromSpaceKey,\n  directoryJson,\n  isSpaceRoot,\n} from '@dxos/echo-protocol';\nimport * as EffectEx from '@dxos/effect/EffectEx';\nimport * as RuntimeProvider from '@dxos/effect/RuntimeProvider';\nimport { type FeedKey, type FeedOptions, FeedStore, type TrimResult } from '@dxos/feed';\nimport { IndexEngine, type IndexingResult, type IndexTransactionLimits } from '@dxos/index-core';\nimport { invariant } from '@dxos/invariant';\nimport { EID, EntityId, type PublicKey, SpaceId } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { FeedProtocol } from '@dxos/protocols';\nimport { type DataService, type FeedService } from '@dxos/protocols/rpc';\nimport { trace } from '@dxos/tracing';\nimport { countWork, defaultMap, markMilestone } from '@dxos/util';\n\nimport {\n  AutomergeHost,\n  type AutomergeReplicator,\n  type CreateDocOptions,\n  type DocumentLease,\n  EchoDataMonitor,\n  type EchoDataStats,\n  type LoadDocOptions,\n  type PeerIdProvider,\n  type RootDocumentSpaceKeyProvider,\n  deriveCollectionIdFromSpaceId,\n} from '../automerge/index.ts';\nimport { sameHeads } from '../query/object-state.ts';\nimport { SLOW_WORK_MS } from '../util.ts';\nimport { AutomergeDataSource } from './automerge-data-source.ts';\nimport { ConvergenceKeyMerger } from './convergence-key-merge.ts';\nimport { DataServiceImpl } from './data-service.ts';\nimport { type DatabaseRoot } from './database-root.ts';\nimport { DeletionResolver } from './deletion.ts';\nimport { BACKFILL_FINISHED, FeedDataSource, backfillResourceId, indexesAllBranches } from './feed-data-source.ts';\nimport { type IndexRequestReason, IndexScheduler } from './index-scheduler.ts';\nimport { IndexStatusTracker, countIndexBacklog, readFeedPin } from './index-status.ts';\nimport { buildInlineObjectDocument, inlineObjectDocumentId, isUntouchedSinceCreation } from './inline-objects.ts';\nimport { type InvalidationHint, hintFromIndexingResult, mergeHints } from './invalidation-hint.ts';\nimport { LocalFeedServiceImpl } from './local-feed-service.ts';\nimport { type QueryDebounceOptions, QueryServiceImpl } from './query-service.ts';\nimport {\n  HISTORY_BLOAT_MIN_OPS,\n  type IndexedObject,\n  type Retirement,\n  buildReplacementDocument,\n  isHistoryBloated,\n  isRetirableForHistory,\n  makeReplacementDirectory,\n  replacementDocumentId,\n} from './retirement.ts';\nimport { type SpaceDocumentListUpdatedEvent, type SpaceRootRefs, SpaceStateManager } from './space-state-manager.ts';\n\n/**\n * Documents walked between event-loop yields during a reachability traversal. Bounds how long one\n * pass can hold the worker thread; the walk is best-effort maintenance and never latency-critical.\n */\nconst CLOSURE_YIELD_INTERVAL = 32;\n\nconst AUTOMATIC_GARBAGE_COLLECTION = false;\n\nconst AUTOMERGE_URL_PREFIX = 'automerge:';\n\n/**\n * The document id a link spells, without validating it: for matching against ids already known to be\n * valid, where a `parseAutomergeUrl` checksum per link would cost more than the lookup it guards.\n */\nconst linkedDocumentIdText = (url: string): string => {\n  if (!url.startsWith(AUTOMERGE_URL_PREFIX)) {\n    return '';\n  }\n  // `parseAutomergeUrl` takes the id verbatim up to a sub-document path (`/`) or heads (`#`).\n  let end = AUTOMERGE_URL_PREFIX.length;\n  while (end < url.length && url[end] !== '/' && url[end] !== '#') {\n    end++;\n  }\n  return url.slice(AUTOMERGE_URL_PREFIX.length, end);\n};\n\n/**\n * Idle window before the second indexing step re-tokenizes what the first one wrote, and the\n * ceiling an unbroken write stream cannot push it past. A typing burst then costs one rebuild\n * rather than one per save; nothing a query reads depends on either number, since text search\n * flushes for itself and every other read comes from the snapshot store.\n */\nconst FTS_FLUSH_IDLE_MS = 1_000;\nconst FTS_FLUSH_MAX_DELAY_MS = 10_000;\n\n/** Trimmed blocks one take of the trimmed log reads, and the takes one index pass makes before it yields to the next. */\nconst PURGE_BATCH = 1_000;\nconst PURGE_BATCHES_PER_PASS = 10;\n\nconst isIndexingDisabled = (options: FeedOptions | undefined): boolean => options?.indexing?.enabled === false;\n\n/** Repeats a bounded trim until it reports nothing left past a limit. */\nconst trimUntilDone = Effect.fnUntraced(function* <E, R>(\n  trim: Effect.Effect<TrimResult, E, R>,\n  first: TrimResult = { deleted: 0, more: true },\n) {\n  let result = first;\n  let deleted = result.deleted;\n  while (result.more) {\n    result = yield* trim;\n    deleted += result.deleted;\n  }\n  return deleted;\n});\n\n/** Feeds whose index rows a pass changed outside the index legs, as a hint unconstrained by type or object. */\ntype FeedChanges = { spaceIds: Set<SpaceId>; queueIds: Set<EntityId> };\n\nconst makeFeedChanges = (): FeedChanges => ({ spaceIds: new Set(), queueIds: new Set() });\n\nconst hintFromFeedChanges = (changes: FeedChanges): InvalidationHint | undefined =>\n  changes.queueIds.size === 0 ? undefined : { spaceIds: changes.spaceIds, queueIds: changes.queueIds };\n\nimport { type QueryExecutorMode } from '../query/index.ts';\n\n/**\n * Query evaluation path for this host: the explicit option, else `DX_ECHO_QUERY_EXECUTOR`, else the\n * compiled SQL executor. Resolved here, where the option enters, so nothing below reads the\n * environment — the planner and executor take the mode they are given.\n *\n * `memory` remains reachable so a regression can be bisected against the old path without a rebuild,\n * and the planner still falls back to it per query for the shapes the compiler declines.\n */\nconst resolveQueryExecutorMode = (explicit?: QueryExecutorMode): QueryExecutorMode => {\n  if (explicit) {\n    return explicit;\n  }\n  const fromEnv =\n    import.meta.env?.DX_ECHO_QUERY_EXECUTOR ??\n    (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env?.DX_ECHO_QUERY_EXECUTOR;\n  return fromEnv === 'memory' ? 'memory' : 'sql';\n};\n\nexport type EchoHostProps = {\n  /** Query evaluation path; defaults to `DX_ECHO_QUERY_EXECUTOR`, else the compiled SQL executor. */\n  queryExecutor?: QueryExecutorMode;\n\n  /** Overrides how live queries are debounced in proportion to their cost; see {@link QueryDebounceOptions}. */\n  queryDebounce?: Partial<QueryDebounceOptions>;\n\n  /** Overrides the bounds on one index write transaction; see {@link IndexTransactionLimits}. */\n  indexTransactionLimits?: Partial<IndexTransactionLimits>;\n\n  /** Overrides how often index progress is counted, once a second by default. */\n  indexRecountInterval?: number;\n\n  peerIdProvider?: PeerIdProvider;\n  getSpaceKeyByRootDocumentId?: RootDocumentSpaceKeyProvider;\n\n  runtime: RuntimeProvider.RuntimeProvider<SqlClient.SqlClient>;\n\n  /**\n   * This peer is allowed to assign positions (global-order) to items appended to the queue.\n   * @default false\n   */\n  assignQueuePositions?: boolean;\n\n  /**\n   * Enable Subduction sedimentree transport for Automerge document replication.\n   * @default false\n   */\n  useSubduction?: boolean;\n};\n\n/**\n * Feed sync handlers wired after construction to break the EchoHost <-> FeedSyncer cycle.\n */\nexport type FeedSyncHandlers = {\n  /**\n   * Callback to run blocking feed sync.\n   */\n  syncFeed: (ctx: Context, request: FeedService.SyncFeedRequest) => Promise<void>;\n};\n\n/**\n * The automerge documents that make up a space directory. Used by storage metrics and garbage\n * collection to enumerate and attribute a space's documents.\n */\ntype SpaceDocumentSet = {\n  /** The space root document id. */\n  rootDocumentId: DocumentId;\n  /** Document ids that embed objects (root inlined objects live in the root document itself). */\n  linkedDocumentIds: DocumentId[];\n  /** Branch member document ids (occupy storage but are not object-link targets). */\n  branchDocumentIds: DocumentId[];\n};\n\n/**\n * Effect service tag for {@link EchoHost}.\n */\nexport class EchoHostService extends EffectContext.Service<EchoHostService, EchoHost>()('@dxos/echo-host/EchoHost') {}\n\n/**\n * Host for the Echo database.\n * Manages multiple spaces.\n * Stores data to disk.\n * Can sync with pluggable data replicators.\n */\nexport class EchoHost extends Resource {\n  private readonly _automergeHost: AutomergeHost;\n  private readonly _queryService: QueryServiceImpl;\n  private readonly _dataService: DataServiceImpl;\n  private readonly _spaceStateManager: SpaceStateManager;\n  private readonly _echoDataMonitor: EchoDataMonitor;\n\n  private readonly _automergeDataSource: AutomergeDataSource;\n  /** Built in `_open`: resolving the SQL client is asynchronous on some platforms. */\n  private _indexEngine: IndexEngine | undefined;\n  /** Resolved when the host opens; the query planner builds compiled statements with it. */\n  private _sql: SqlClient.SqlClient | undefined;\n  private readonly _convergenceKeyMerger: ConvergenceKeyMerger;\n  private readonly _runtime: RuntimeProvider.RuntimeProvider<SqlClient.SqlClient>;\n  private readonly _feedStore: FeedStore;\n  private readonly _feedDataSource: FeedDataSource;\n\n  private readonly _indexScheduler: IndexScheduler;\n\n  /** What the index is doing, for boot screens and progress indicators; see {@link DataService.IndexStatus}. */\n  readonly indexStatus: IndexStatusTracker;\n\n  private _feedService: FeedService.Handlers;\n\n  readonly #indexTransactionLimits: Partial<IndexTransactionLimits> | undefined;\n\n  /** Invalidates a pending full-text flush that a later write has superseded. */\n  #ftsFlushGeneration = 0;\n\n  /** Whether the first index pass, and the first pass that left nothing behind, are marked on the timeline. */\n  #indexingMarked = false;\n  /** The last document leg read every saved document, so until one is saved again a pass need not rescan them. */\n  #documentsDrained = false;\n  #caughtUpMarked = false;\n\n  readonly #secondaryIndexLock = new Mutex();\n\n  /** When the oldest unflushed write stops being allowed to wait for an idle moment. */\n  #ftsFlushDeadline: number | undefined;\n\n  /** Last known document set per space, to detect what left the directory. */\n  private readonly _spaceDocumentIds = new Map<SpaceId, Set<DocumentId>>();\n\n  /** The latest retirement pass per space; passes are chained so two never write one space's directory at once. */\n  readonly #retirements = new Map<SpaceId, Promise<void>>();\n\n  /** Retired documents wiped this session, since every later directory change still lists them. */\n  readonly #wipedDocuments = new Set<DocumentId>();\n\n  /** Retirements this host wrote or saw this session, to write back an entry a concurrent change dropped. */\n  readonly #knownRetirements = new Map<DocumentId, Retirement & { spaceId: SpaceId }>();\n\n  /** Op counts of loaded documents big enough to be retired for their history. */\n  readonly #historyCandidates = new Map<DocumentId, number>();\n\n  // Feed sync handlers are wired lazily via `setFeedSyncHandlers` to break the construction-time\n  // cycle with the FeedSyncer, which itself depends on `this.feedStore`.\n  #syncFeed?: (ctx: Context, request: FeedService.SyncFeedRequest) => Promise<void>;\n\n  constructor({\n    peerIdProvider,\n    getSpaceKeyByRootDocumentId,\n    runtime,\n    queryExecutor,\n    queryDebounce,\n    indexTransactionLimits,\n    indexRecountInterval,\n    assignQueuePositions = false,\n    useSubduction,\n  }: EchoHostProps) {\n    super();\n    this.#indexTransactionLimits = indexTransactionLimits;\n    this.indexStatus = new IndexStatusTracker({ recountInterval: indexRecountInterval });\n\n    this._echoDataMonitor = new EchoDataMonitor();\n    this._automergeHost = new AutomergeHost({\n      runtime,\n      dataMonitor: this._echoDataMonitor,\n      peerIdProvider,\n      getSpaceKeyByRootDocumentId,\n      useSubduction,\n    });\n\n    this._runtime = runtime;\n    this._spaceStateManager = new SpaceStateManager({ runtime });\n    this._automergeDataSource = new AutomergeDataSource(this._automergeHost, {\n      isBranchDocument: (documentId) => this._spaceStateManager.isBranchDocument(documentId),\n      directories: {\n        isSpaceRoot: (documentId) => this._spaceStateManager.isSpaceRootDocument(documentId),\n        store: (documentId, snapshot) => this._spaceStateManager.writeDirectorySnapshot(documentId, snapshot),\n      },\n    });\n\n    this._feedStore = new FeedStore({ assignPositions: assignQueuePositions, localActorId: crypto.randomUUID() });\n    this._feedDataSource = new FeedDataSource({\n      feedStore: this._feedStore,\n      runtime: this._runtime,\n      getSpaceIds: () => this._spaceStateManager.spaceIds,\n    });\n    this._indexScheduler = new IndexScheduler({\n      feedBlocks: this._feedStore.onNewBlocks,\n      documentsSaved: this._automergeHost.documentsSaved,\n      runPass: (ctx, reasons) => this._runIndexPass(ctx, reasons),\n    });\n    this._feedService = new LocalFeedServiceImpl(runtime, this._feedStore, {\n      // Read the mutable slot lazily so a handler wired after construction takes effect;\n      // fall back to a no-op before it is set.\n      syncFeed: (ctx, request) => this.#syncFeed?.(ctx, request) ?? Promise.resolve(),\n    });\n\n    this._convergenceKeyMerger = new ConvergenceKeyMerger({\n      queryByConvergenceKeys: (spaceId, keys) =>\n        this.indexEngine.queryByConvergenceKeys(spaceId, keys).pipe(RuntimeProvider.runPromise(this._runtime)),\n      queryReferrers: (spaceId, targetId) =>\n        this.indexEngine\n          .queryReferrers(spaceId, EID.make({ entityId: targetId }))\n          .pipe(RuntimeProvider.runPromise(this._runtime)),\n      loadDoc: (ctx, documentId, opts) => this._automergeHost.loadDoc<DatabaseDirectory>(ctx, documentId, opts),\n      flushDoc: (ctx, documentId) => this._automergeHost.flush(ctx, { documentIds: [documentId] }),\n    });\n\n    this._queryService = new QueryServiceImpl({\n      indexEngine: () => this.indexEngine,\n      runtime: this._runtime,\n      automergeHost: this._automergeHost,\n      spaceStateManager: this._spaceStateManager,\n      // Delegate to the public method so the closed-host early-out and cooperative loop apply.\n      // `QueryEntry.feedScoped`, or a compiled query whose snapshot store is still filling, is what\n      // decides a query must await indexing before its first result.\n      updateIndexes: () => this.updateIndexes({ reason: 'feed-scoped-query' }),\n      executor: resolveQueryExecutorMode(queryExecutor),\n      feedStore: this._feedStore,\n      debounce: queryDebounce,\n      sql: () => {\n        invariant(this._sql, 'EchoHost is not open.');\n        return this._sql;\n      },\n      hasCompleteSnapshots: (scope) =>\n        RuntimeProvider.runPromise(this._runtime)(this.indexEngine.hasCompleteSnapshots(scope)),\n      holdsDocument: (subscriptionIds, documentId) => this._dataService.holds(subscriptionIds, documentId),\n    });\n\n    this._dataService = new DataServiceImpl({\n      automergeHost: this._automergeHost,\n      spaceStateManager: this._spaceStateManager,\n      // Delegate to the public method so the closed-host early-out and\n      // cooperative loop apply uniformly to the RPC handler path.\n      updateIndexes: (request) => this.updateIndexes({ ...request, reason: 'rpc-update-indexes' }),\n      getSpaceStats: (spaceId) => this.getSpaceStats(spaceId),\n      indexStatus: this.indexStatus,\n      runGarbageCollection: (spaceId, options) => this.runGarbageCollection(spaceId, options),\n      readDirectorySnapshot: (documentId) => this.readDirectorySnapshot(documentId),\n    });\n\n    trace.diagnostic<EchoStatsDiagnostic>({\n      id: 'echo-stats',\n      name: 'Echo Stats',\n      fetch: async () => {\n        return {\n          dataStats: this._echoDataMonitor.computeStats(),\n          loadedDocsCount: this._automergeHost.loadedDocsCount,\n        };\n      },\n    });\n\n    trace.diagnostic({\n      id: 'database-roots',\n      name: 'Database Roots',\n      fetch: async () => {\n        return Array.from(this._spaceStateManager.roots.values()).map((root) => ({\n          url: root.url,\n          isLoaded: root.isLoaded,\n          spaceKey: root.getSpaceKey(),\n          inlineObjects: root.getInlineObjectCount(),\n          linkedObjects: root.getLinkedObjectCount(),\n        }));\n      },\n    });\n\n    trace.diagnostic({\n      id: 'database-root-metrics',\n      name: 'Database Roots (with metrics)',\n      fetch: async () => {\n        return Array.from(this._spaceStateManager.roots.values()).map((root) => ({\n          url: root.url,\n          isLoaded: root.isLoaded,\n          spaceKey: root.getSpaceKey(),\n          inlineObjects: root.getInlineObjectCount(),\n          linkedObjects: root.getLinkedObjectCount(),\n          ...(root.measureMetrics() ?? {}),\n        }));\n      },\n    });\n  }\n\n  get spaceIds(): SpaceId[] {\n    return this._spaceStateManager.spaceIds;\n  }\n\n  get queryService(): QueryServiceImpl {\n    return this._queryService;\n  }\n\n  get dataService(): DataServiceImpl {\n    return this._dataService;\n  }\n\n  get feedService(): FeedService.Handlers {\n    return this._feedService;\n  }\n\n  get roots(): ReadonlyMap<DocumentId, DatabaseRoot> {\n    return this._spaceStateManager.roots;\n  }\n\n  get feedStore(): FeedStore {\n    return this._feedStore;\n  }\n\n  /**\n   * Automerge document store backing every space.\n   */\n  get automergeHost(): AutomergeHost {\n    return this._automergeHost;\n  }\n\n  /**\n   * Wires the feed sync handlers after the composing stack is fully constructed.\n   */\n  setFeedSyncHandlers(handlers: FeedSyncHandlers): void {\n    this.#syncFeed = handlers.syncFeed;\n  }\n\n  /**\n   * Index engine for queries.\n   */\n  get indexEngine(): IndexEngine {\n    invariant(this._indexEngine, 'EchoHost is not open.');\n    return this._indexEngine;\n  }\n\n  protected override async _open(ctx: Context): Promise<void> {\n    // The index engine holds its SQL client, and resolving one out of the runtime may suspend --\n    // the browser's SQLite layer builds asynchronously -- so it cannot be built in the constructor.\n    this._sql = await RuntimeProvider.runPromise(this._runtime)(SqlClient.SqlClient);\n    this._indexEngine = new IndexEngine(this._sql, {\n      transactionLimits: this.#indexTransactionLimits,\n      yieldBetweenTransactions: yieldBehindQueuedTasks,\n    });\n\n    const pendingMigrations = await RuntimeProvider.runPromise(this._runtime)(this.indexEngine.pendingMigrations());\n    log('echo-host: running index engine migration...', { pending: pendingMigrations });\n    if (pendingMigrations > 0) {\n      this.indexStatus.setMigrating(0, pendingMigrations);\n    }\n    await RuntimeProvider.runPromise(this._runtime)(\n      this.indexEngine.migrate({\n        onProgress: (applied) => this.indexStatus.setMigrating(applied, pendingMigrations),\n      }),\n    );\n    log('echo-host: index engine migration done');\n\n    log('echo-host: running feed store migration...');\n    await RuntimeProvider.runPromise(this._runtime)(this._feedStore.migrate());\n    log('echo-host: feed store migration done');\n\n    // Age expires with no write to trigger a trim, so open is when expired blocks of an idle feed go.\n    await RuntimeProvider.runPromise(this._runtime)(\n      Effect.gen({ self: this }, function* () {\n        yield* this.#trimSpaces(yield* this._feedStore.listSpacesWithOptions());\n      }),\n    );\n\n    // AutomergeHost._open() runs its own migrations (automerge_chunks, heads) before\n    // constructing the Repo, so table creation is handled there.\n    log('echo-host: opening automerge host...');\n    await this._automergeHost.open(ctx);\n    log('echo-host: automerge host opened');\n\n    log('echo-host: opening query service...');\n    await this._queryService.open(ctx);\n    log('echo-host: query service opened');\n\n    log('echo-host: opening space state manager...');\n    await this._spaceStateManager.open(ctx);\n    log('echo-host: space state manager opened');\n\n    const pin = await RuntimeProvider.runPromise(this._runtime)(readFeedPin()).catch((err) => {\n      log.warn('index feed pin read failed', { err });\n      return FeedProtocol.FEED_START;\n    });\n    await this.indexStatus.opened(() =>\n      RuntimeProvider.runPromise(this._runtime)(countIndexBacklog({ pin, spaceIds: this._spaceStateManager.spaceIds })),\n    );\n    this._spaceStateManager.spaceDocumentListUpdated.on(this._ctx, (e) => {\n      const previous = this._spaceDocumentIds.get(e.spaceId);\n      this._spaceDocumentIds.set(e.spaceId, new Set(e.documentIds));\n\n      if (e.previousRootId) {\n        void this._automergeHost.clearLocalCollectionState(deriveCollectionIdFromSpaceId(e.spaceId, e.previousRootId));\n      }\n      void this._automergeHost.updateLocalCollectionState(\n        deriveCollectionIdFromSpaceId(e.spaceId, e.spaceRootId),\n        e.documentIds,\n      );\n\n      // TODO(dmaretskyi): Current algortithm is too expensive.\n      if (AUTOMATIC_GARBAGE_COLLECTION) {\n        // Documents that left the directory are this peer's share of a garbage-collection pass some\n        // peer explicitly ran: the unlink replicates as an ordinary change, and its arrival here is\n        // the evidence. Reclaiming them locally is what makes one invocation free disk everywhere,\n        // rather than requiring every peer to run collection itself.\n        //\n        // Safe because a departed document id never comes back: automerge delivers causally, so a\n        // link removal is never observed before the create it depends on, and the sole writer of a\n        // `links` key (object creation) always writes a freshly created document url. Registering\n        // the new collection state first also means no fetch can race the wipe.\n        const departed = previous ? this.#departedDocuments(previous, e) : [];\n        if (departed.length > 0 || e.previousRootId) {\n          this.#scheduleReclaim(e.spaceId, departed, e.previousRootId);\n        }\n      }\n\n      // A directory change can carry another peer's retirement, and a newly opened space can link a document\n      // quarantined on an earlier start.\n      this.#scheduleDirectoryMaintenance(e.spaceId);\n    });\n    this._automergeHost.documentQuarantined.on(this._ctx, ({ reason }) => {\n      if (reason === 'load-failed') {\n        for (const spaceId of this._spaceStateManager.spaceIds) {\n          this.#scheduleDirectoryMaintenance(spaceId);\n        }\n      }\n    });\n    this._automergeHost.documentLoaded.on(this._ctx, ({ documentId, ops }) => {\n      if (ops >= HISTORY_BLOAT_MIN_OPS) {\n        this.#historyCandidates.set(documentId, ops);\n        // The index may already be current, in which case no index pass will bring the document up again.\n        for (const spaceId of this._spaceStateManager.spaceIds) {\n          this.#scheduleDirectoryMaintenance(spaceId);\n        }\n      }\n    });\n    // Opened on the host's context, so the scheduler stops subscribing the moment the host starts closing.\n    await this._indexScheduler.open(this._ctx);\n    log('echo-host: open complete');\n  }\n\n  protected override async _close(ctx: Context): Promise<void> {\n    await this._indexScheduler.close();\n\n    await this._queryService.close(ctx);\n    await this._spaceStateManager.close(ctx);\n    await this._automergeHost.close();\n  }\n\n  /**\n   * Flush all pending writes to the underlying storage.\n   */\n  async flush(ctx: Context): Promise<void> {\n    await this._automergeHost.flush(ctx);\n  }\n\n  /**\n   * Waits until every change made before the call is indexed. Changes made during the wait are left\n   * to later passes, so a stream of writes cannot hold the caller.\n   *\n   * Bails as a no-op when the host has been closed: a late `db.flush()` RPC\n   * (client still has an open service ref while the host is in/post-teardown)\n   * has nothing to update against. The pre-loop and post-iteration\n   * `_ctx.disposed` checks prevent `runBlocking` from being entered against a\n   * disposed context — which would throw `ContextDisposedError` and escape as\n   * an unhandled rejection at the fire-and-forget originating caller. Other\n   * `Resource` methods in this codebase (e.g. `SqliteStorageAdapter.load`)\n   * follow the same closed-host early-out pattern.\n   */\n  async updateIndexes({\n    secondaryIndexes = false,\n    reason,\n  }: { secondaryIndexes?: boolean; reason?: IndexRequestReason } = {}): Promise<void> {\n    if (this._ctx.disposed) {\n      return;\n    }\n    await this._indexScheduler.waitForIndexed(reason);\n    if (this._ctx.disposed) {\n      return;\n    }\n    // A pass invalidates queries as it ends and they re-run on their own task; callers flushing the\n    // index expect those results too.\n    await this._queryService.awaitQueryUpdates();\n\n    if (secondaryIndexes) {\n      await this.updateSecondaryIndexes();\n    }\n  }\n\n  /**\n   * Indexes the secondary-index backlog to completion, which the debounced flush otherwise gets to\n   * on its own schedule (see {@link IndexEngine.updateSecondaryIndexes}). Runs one at a time: a call\n   * made during a run waits for it, then runs on its own to cover what the run may have missed.\n   *\n   * @returns Number of records indexed.\n   */\n  async updateSecondaryIndexes(): Promise<number> {\n    return this.#secondaryIndexLock.executeSynchronized(() => this.#indexSecondary());\n  }\n\n  async #indexSecondary(): Promise<number> {\n    const ctx = this._ctx;\n    const startedAt = performance.now();\n    let records = 0;\n    let batches = 0;\n    let hint: InvalidationHint | undefined;\n    try {\n      while (!ctx.disposed && this.isOpen) {\n        if (batches > 0) {\n          await yieldBehindQueuedTasks();\n          if (ctx.disposed) {\n            break;\n          }\n        }\n        const result = await this.indexEngine\n          .updateSecondaryIndexes(ctx)\n          .pipe(RuntimeProvider.runPromise(this._runtime));\n        records += result.updated;\n        batches++;\n        const batch = hintFromIndexingResult(result);\n        if (batch) {\n          hint = hint ? mergeHints(hint, batch) : batch;\n        }\n        if (result.done || ctx.disposed || !this.isOpen) {\n          break;\n        }\n        await this.indexStatus.afterFullTextBatch(() =>\n          this.indexEngine.countSecondaryBacklog().pipe(RuntimeProvider.runPromise(this._runtime)),\n        );\n      }\n    } finally {\n      this.indexStatus.fullTextEnded();\n    }\n\n    // A text query issued before this catch-up matched nothing and would never re-run on its own:\n    // the indexer is the sole invalidation source, and this pass is the only writer of the rows.\n    if (hint) {\n      this._queryService.invalidateQueries(hint);\n    }\n\n    const durationMs = performance.now() - startedAt;\n    if (durationMs >= SLOW_WORK_MS) {\n      log.warn('slow full-text catch-up', { durationMs, records, batches });\n    }\n    return records;\n  }\n\n  /**\n   * Leases the document and waits for it to be ready. Dispose the lease when done with it.\n   *\n   * @returns `null` when the document is not available yet (e.g. storage-only load with no local chunks).\n   */\n  async loadDoc<T>(ctx: Context, documentId: AnyDocumentId, opts?: LoadDocOptions): Promise<DocumentLease<T> | null> {\n    return await this._automergeHost.loadDoc<T>(ctx, documentId, opts);\n  }\n\n  /** Leases the document without waiting for it to load. Dispose the lease when done with it. */\n  acquireDoc<T>(documentId: AnyDocumentId): DocumentLease<T> {\n    return this._automergeHost.acquireDoc<T>(documentId);\n  }\n\n  async exportDoc(id: AnyDocumentId): Promise<Uint8Array> {\n    return await this._automergeHost.exportDoc(id);\n  }\n\n  /**\n   * Create new persisted document.\n   */\n  async createDoc<T>(initialValue?: T, opts?: CreateDocOptions): Promise<DocumentLease<T>> {\n    return this._automergeHost.createDoc<T>(initialValue, opts);\n  }\n\n  /**\n   * Create new space root.\n   */\n  async createSpaceRoot(ctx: Context, spaceKey: PublicKey): Promise<DatabaseRoot> {\n    invariant(this._lifecycleState === LifecycleState.OPEN);\n    const spaceId = await createIdFromSpaceKey(spaceKey);\n\n    // Released once the root is assigned: `updateSpaceRoot` takes the lease the space keeps.\n    using automergeRoot = await this._automergeHost.createDoc<DatabaseDirectory>({\n      version: SpaceDocVersion.CURRENT,\n      // spaceKey is deprecated but still written so older clients can resolve the owning space.\n      access: { spaceId, spaceKey: spaceKey.toHex() },\n\n      // Better to initialize them right away to avoid merge conflicts and data loss that can occur if those maps get created on the fly.\n      objects: {},\n      links: {},\n    });\n\n    await this._automergeHost.flush(ctx, { documentIds: [automergeRoot.documentId] });\n\n    return await this.updateSpaceRoot(ctx, spaceId, automergeRoot.url);\n  }\n\n  /**\n   * Creates a space anchored on an immutable space root document, which carries the credentials\n   * document. The id still derives from the space genesis key, exactly as a feed-backed space's\n   * does — the root changes where credentials live, not how the space is identified.\n   *\n   * NOTE: `createSpaceRoot` above creates the DIRECTORY, which predates this naming.\n   */\n  async createSpaceWithRootDocument(ctx: Context, spaceKey: PublicKey): Promise<CreatedSpace> {\n    invariant(this._lifecycleState === LifecycleState.OPEN);\n\n    const spaceId = await createIdFromSpaceKey(spaceKey);\n    // Both released here: the directory's lease is retaken by `updateSpaceRoot`, and the space root\n    // document is only written once.\n    using rootHandle = await this._automergeHost.createDoc<Partial<SpaceRoot>>({});\n\n    using directoryHandle = await this._automergeHost.createDoc<DatabaseDirectory>({\n      version: SpaceDocVersion.CURRENT,\n      // spaceKey is deprecated but still written so older clients can resolve the owning space.\n      access: { spaceId, spaceKey: spaceKey.toHex() },\n      objects: {},\n      links: {},\n    });\n\n    rootHandle.change((doc: Partial<SpaceRoot>) => {\n      doc.type = SPACE_ROOT_TYPE;\n      doc.spaceId = spaceId;\n      doc.directory = directoryHandle.url;\n    });\n\n    await this._automergeHost.flush(ctx, { documentIds: [rootHandle.documentId, directoryHandle.documentId] });\n\n    const directory = await this.updateSpaceRoot(ctx, spaceId, directoryHandle.url);\n    await this._spaceStateManager.setSpaceRootRefs(spaceId, {\n      spaceRootDocUrl: rootHandle.url,\n    });\n\n    return { spaceId, spaceRootUrl: rootHandle.url, directory };\n  }\n\n  /**\n   * Mints a space root over a legacy space's existing directory, keeping the space id: it was derived\n   * from the space key and cannot be reproduced from a document, which is what `spaceKey` derivation\n   * records. Idempotent — a space that already has a root keeps it, so a re-run cannot fork the anchor.\n   */\n  async migrateSpaceToRootDocument(ctx: Context, spaceId: SpaceId): Promise<SpaceRootRefs | undefined> {\n    invariant(this._lifecycleState === LifecycleState.OPEN);\n\n    const existing = this._spaceStateManager.getSpaceRootRefs(spaceId);\n    if (existing) {\n      return existing;\n    }\n\n    // A space whose directory is not assigned yet (an accepted space still catching up) has nothing to\n    // anchor; it migrates on a later load rather than failing here.\n    const directory = this._spaceStateManager.getRootBySpaceId(spaceId);\n    if (!directory) {\n      return undefined;\n    }\n\n    using rootHandle = await this._automergeHost.createDoc<Partial<SpaceRoot>>({});\n    rootHandle.change((doc: Partial<SpaceRoot>) => {\n      doc.type = SPACE_ROOT_TYPE;\n      doc.spaceId = spaceId;\n      doc.directory = directory.url;\n    });\n\n    await this._automergeHost.flush(ctx, { documentIds: [rootHandle.documentId] });\n\n    const refs: SpaceRootRefs = { spaceRootDocUrl: rootHandle.url };\n    await this._spaceStateManager.setSpaceRootRefs(spaceId, refs);\n    return refs;\n  }\n\n  /**\n   * Links an already-created credentials document from the space root, once. Idempotent — the link is\n   * what the per-space source flip keys off, so a second document would fork the chain. The document\n   * itself is built a layer up, where credential encoding lives.\n   */\n  /**\n   * Adopts a space root minted elsewhere, so a joining peer records the root the space already has\n   * rather than minting a second one over it. Idempotent; the root must name this space.\n   */\n  async adoptSpaceRoot(\n    ctx: Context,\n    spaceId: SpaceId,\n    spaceRootUrl: AutomergeUrl,\n    { fetchFromNetwork = false, timeout }: { fetchFromNetwork?: boolean; timeout?: number } = {},\n  ): Promise<SpaceRootRefs> {\n    invariant(this._lifecycleState === LifecycleState.OPEN);\n\n    const existing = this._spaceStateManager.getSpaceRootRefs(spaceId);\n    if (existing) {\n      invariant(existing.spaceRootDocUrl === spaceRootUrl, `Space already anchored on another root: ${spaceId}`);\n      return existing;\n    }\n\n    // Local-only by default: a caller adopting a root it was merely told about must not block on the\n    // network. A root edge minted exists nowhere else, so that caller opts in to fetching it.\n    using rootHandle = await this._automergeHost.loadDoc<SpaceRoot>(ctx, spaceRootUrl, { fetchFromNetwork, timeout });\n    const root = rootHandle?.doc();\n    invariant(root && isSpaceRoot(root), 'Space root document must load.');\n    invariant(root.spaceId === spaceId, `Space root names another space: ${root.spaceId}`);\n\n    // The directory travels with the root, so a peer that has never opened the space gets one here.\n    if (!this._spaceStateManager.getRootBySpaceId(spaceId)) {\n      await this.updateSpaceRoot(ctx, spaceId, root.directory);\n    }\n\n    const refs: SpaceRootRefs = {\n      spaceRootDocUrl: spaceRootUrl,\n      credentialsDocUrl: root.credentials,\n    };\n    await this._spaceStateManager.setSpaceRootRefs(spaceId, refs);\n    return refs;\n  }\n\n  async setCredentialsDocument(ctx: Context, spaceId: SpaceId, credentialsDocUrl: AutomergeUrl): Promise<AutomergeUrl> {\n    invariant(this._lifecycleState === LifecycleState.OPEN);\n\n    const refs = this._spaceStateManager.getSpaceRootRefs(spaceId);\n    invariant(refs, `Space has no root document: ${spaceId}`);\n    if (refs.credentialsDocUrl) {\n      return refs.credentialsDocUrl;\n    }\n\n    using rootHandle = await this._automergeHost.loadDoc<SpaceRoot>(ctx, refs.spaceRootDocUrl);\n    invariant(rootHandle, 'Space root document must load before linking credentials.');\n    rootHandle.change((doc: SpaceRoot) => {\n      doc.credentials = credentialsDocUrl;\n    });\n\n    await this._automergeHost.flush(ctx, { documentIds: [rootHandle.documentId] });\n    await this._spaceStateManager.setSpaceRootRefs(spaceId, { ...refs, credentialsDocUrl });\n    return credentialsDocUrl;\n  }\n\n  /** References carried by the space root document, or undefined for a space that predates it. */\n  getSpaceRootRefs(spaceId: SpaceId): SpaceRootRefs | undefined {\n    return this._spaceStateManager.getSpaceRootRefs(spaceId);\n  }\n\n  get spaces(): ReadonlyArray<{ spaceId: SpaceId; rootDocUrl: AutomergeUrl }> {\n    return this._spaceStateManager.getPersistedSpaces();\n  }\n\n  async openSpaceRoot(ctx: Context, spaceId: SpaceId): Promise<DatabaseRoot> {\n    invariant(this._lifecycleState === LifecycleState.OPEN);\n    const documentId = this._spaceStateManager.getSpaceRootDocumentId(spaceId);\n    invariant(documentId, `Space root document not found for space: ${spaceId}`);\n    return this.#assignRoot(ctx, spaceId, `automerge:${documentId}` as AutomergeUrl);\n  }\n\n  async updateSpaceRoot(ctx: Context, spaceId: SpaceId, automergeUrl: AutomergeUrl): Promise<DatabaseRoot> {\n    invariant(this._lifecycleState === LifecycleState.OPEN);\n    const currentRoot = this._spaceStateManager.getRootBySpaceId(spaceId);\n    if (currentRoot && currentRoot.url === automergeUrl) {\n      return currentRoot;\n    }\n    return this.#assignRoot(ctx, spaceId, automergeUrl);\n  }\n\n  /**\n   * Assigns a space its root from the directory snapshot the index holds, when that is current, so a space nothing\n   * writes this session never loads its root; otherwise loads the root, which the space then keeps resident.\n   */\n  async #assignRoot(ctx: Context, spaceId: SpaceId, url: AutomergeUrl): Promise<DatabaseRoot> {\n    const documentId = interpretAsDocumentId(url);\n    const snapshot = this._spaceStateManager.getRootByDocumentId(documentId)\n      ? undefined\n      : await this.readDirectorySnapshot(documentId);\n    if (snapshot) {\n      const root = await this._spaceStateManager.assignRootToSpace(spaceId, {\n        documentId,\n        snapshot: { heads: snapshot.heads, json: JSON.parse(snapshot.json) },\n        load: async () => {\n          const lease = await this._automergeHost.loadDoc<DatabaseDirectory>(this._ctx, url, {\n            fetchFromNetwork: true,\n          });\n          invariant(lease, 'Space root document must load before it is written.');\n          return lease;\n        },\n        headsChanged: this._automergeHost.documentHeadsChanged,\n      });\n      // A save between reading the snapshot and the root's subscription would otherwise go unseen.\n      const [storedHeads] = await this._automergeHost.getStoredHeads([documentId]);\n      if (!storedHeads || !sameHeads(storedHeads, snapshot.heads)) {\n        await root.load();\n      }\n      return root;\n    }\n    const lease = await this._automergeHost.loadDoc<DatabaseDirectory>(ctx, url, {\n      fetchFromNetwork: true,\n    });\n    invariant(lease, 'Space root document must load before assignment.');\n    // Written here as well as by the index: a root indexed before snapshots existed is never re-read by it.\n    await this.#writeDirectorySnapshot(documentId, lease.doc());\n    // The lease is handed over: the space's root stays resident for as long as the space is open.\n    return this._spaceStateManager.assignRootToSpace(spaceId, { lease });\n  }\n\n  /**\n   * The directory JSON the index holds for a space root, when it was read at the heads the root is stored at: what\n   * a client or this host can show the root from without loading it.\n   */\n  async readDirectorySnapshot(documentId: DocumentId): Promise<{ heads: Heads; json: string } | undefined> {\n    const [stored, [storedHeads]] = await Promise.all([\n      this._spaceStateManager.readDirectorySnapshot(documentId),\n      this._automergeHost.getStoredHeads([documentId]),\n    ]);\n    return stored && storedHeads && sameHeads(stored.heads, storedHeads)\n      ? { heads: storedHeads, json: stored.json }\n      : undefined;\n  }\n\n  /** Stores a loaded root's directory JSON, when the root is saved at the heads it is read at. */\n  async #writeDirectorySnapshot(documentId: DocumentId, doc: A.Doc<DatabaseDirectory>): Promise<void> {\n    const json = directoryJson(doc);\n    if (json === undefined) {\n      return;\n    }\n    const heads = A.getHeads(doc);\n    const [storedHeads] = await this._automergeHost.getStoredHeads([documentId]);\n    if (storedHeads && sameHeads(storedHeads, heads)) {\n      await this._spaceStateManager.writeDirectorySnapshot(documentId, { heads, json });\n    }\n  }\n\n  async closeSpace(spaceId: SpaceId): Promise<void> {\n    todo();\n  }\n\n  /**\n   * Runs `wipe`, which deletes this host's rows while it stays open, with indexing stopped and the feed\n   * store's caches dropped after it: either would otherwise write cursors under tokens the wipe deleted.\n   */\n  async wipeStorage(wipe: () => Promise<void>): Promise<void> {\n    // Closing drains the pass under way.\n    await this._indexScheduler.close();\n    try {\n      await wipe();\n    } finally {\n      this._feedStore.resetCaches();\n      await this._indexScheduler.open(this._ctx);\n    }\n  }\n\n  async removeSpace(spaceId: SpaceId): Promise<void> {\n    this._spaceDocumentIds.delete(spaceId);\n    const root = this._spaceStateManager.getRootBySpaceId(spaceId);\n    if (root) {\n      void this._automergeHost.clearLocalCollectionState(deriveCollectionIdFromSpaceId(spaceId, root.documentId));\n    }\n    await this._spaceStateManager.removeSpace(spaceId);\n  }\n\n  /**\n   * Install data replicator.\n   */\n  async addReplicator(ctx: Context, replicator: AutomergeReplicator): Promise<void> {\n    await this._automergeHost.addReplicator(ctx, replicator);\n  }\n\n  /**\n   * Remove data replicator.\n   */\n  async removeReplicator(replicator: AutomergeReplicator): Promise<void> {\n    await this._automergeHost.removeReplicator(replicator);\n  }\n\n  /**\n   * Run collection sync for the given space.\n   * Does not wait for the sync to complete.\n   */\n  async runCollectionSync(spaceId: SpaceId) {\n    const root = this._spaceStateManager.getRootBySpaceId(spaceId);\n    if (!root) {\n      throw new Error(`Space not found: ${spaceId}`);\n    }\n    this._automergeHost.refreshCollection(deriveCollectionIdFromSpaceId(spaceId, root.documentId));\n  }\n\n  /**\n   * Get all feeds and their blocks for a space.\n   * Used for space archive export.\n   */\n  async getAllFeedsForSpace(\n    spaceId: SpaceId,\n  ): Promise<Array<{ feedId: string; feedNamespace: string; blocks: FeedProtocol.Block[] }>> {\n    return RuntimeProvider.runPromise(this._runtime)(this._feedStore.getAllFeedsForSpace({ spaceId }));\n  }\n\n  /**\n   * Per-space storage metrics: objects (alive/deleted), automerge documents, feeds, feed blocks,\n   * plus what the host is holding in memory. See `docs/GARBAGE_COLLECTION.md`.\n   */\n  async getSpaceStats(spaceId: SpaceId): Promise<DataService.DatabaseStats> {\n    const root = await this.#ensureSpaceRootLoaded(spaceId);\n    const documents = this.#collectSpaceDocuments(root);\n    const objects = await this.#countSpaceObjects(root, documents);\n    const feeds = await this.getAllFeedsForSpace(spaceId);\n    const feedBlocks = feeds.reduce((sum, feed) => sum + feed.blocks.length, 0);\n\n    return {\n      objects,\n      documents: this.#allSpaceDocumentIds(documents).size,\n      feeds: feeds.length,\n      feedBlocks,\n      // Sampled after the walk above, which loads the space root: reading it first would report a\n      // residency the call itself then changes.\n      loaded: {\n        documents: this._automergeHost.loadedDocsCountForSpace(spaceId),\n        documentsTotal: this._automergeHost.loadedDocsCount,\n        queriesTotal: this._queryService.activeQueryCount,\n        leases: this._automergeHost.leasedDocsCount,\n      },\n    };\n  }\n\n  /**\n   * Reclaim storage held by soft-deleted objects and unreachable documents for a space.\n   * See `docs/GARBAGE_COLLECTION.md` for the full algorithm and its safety invariants: unlink\n   * soft-deleted objects from the space directory (step 1), wipe every document owned by the space\n   * that is no longer reachable from the post-unlink directory (step 2), then drop the reclaimed\n   * documents' index rows (step 5).\n   */\n  async runGarbageCollection(\n    spaceId: SpaceId,\n    options: DataService.RunGarbageCollectionRequest = { spaceId },\n  ): Promise<DataService.GarbageCollectionReport> {\n    const root = await this.#ensureSpaceRootLoaded(spaceId);\n    const { unlinkedObjects, removedInlineObjects } = await this.#unlinkDeletedObjects(spaceId, root);\n    const wipedDocumentIds = await this.#wipeUnreachableDocuments(spaceId, root);\n\n    let removedIndexEntries = 0;\n    if (options.index !== false && (wipedDocumentIds.length > 0 || removedInlineObjects.length > 0)) {\n      removedIndexEntries = await RuntimeProvider.runPromise(this._runtime)(\n        this.indexEngine.deleteObjects({ spaceId, documentIds: wipedDocumentIds, objects: removedInlineObjects }),\n      );\n    }\n\n    return {\n      unlinkedObjects,\n      removedDocuments: wipedDocumentIds.length,\n      removedIndexEntries,\n      purgedFeedBlocks: 0,\n    };\n  }\n\n  /**\n   * Writes each object into a new document of its own and links it from the space directory in one change, which is\n   * the shape every object takes: the directory itself holds no objects.\n   */\n  async addObjects(ctx: Context, spaceId: SpaceId, objects: Readonly<Record<string, EntityStructure>>): Promise<void> {\n    const root = this._spaceStateManager.getRootBySpaceId(spaceId);\n    invariant(root, `Space root not found: ${spaceId}`);\n    const spaceKey = root.getSpaceKey();\n    const links: { objectId: string; url: AutomergeUrl; documentId: DocumentId }[] = [];\n    for (const [objectId, structure] of Object.entries(objects)) {\n      using lease = await this._automergeHost.createDoc<DatabaseDirectory>({\n        version: SpaceDocVersion.CURRENT,\n        // spaceKey is deprecated but still written so older clients can resolve the owning space.\n        access: spaceKey ? { spaceId, spaceKey } : { spaceId },\n        objects: { [objectId]: structure },\n      });\n      links.push({ objectId, url: lease.url, documentId: lease.documentId });\n    }\n    if (links.length === 0) {\n      return;\n    }\n    await root.load();\n    root.change((draft: DatabaseDirectory) => {\n      draft.links ??= {};\n      for (const { objectId, url } of links) {\n        draft.links[objectId] = new A.RawString(url);\n      }\n    });\n    await this._automergeHost.flush(ctx, {\n      documentIds: [root.documentId, ...links.map(({ documentId }) => documentId)],\n    });\n  }\n\n  /**\n   * Moves every object inlined in a space directory into a document of its own, linked from the directory, and\n   * waits for the pass. Runs on its own whenever a space opens or its document list changes; exposed so callers\n   * that must observe the result (tests, tooling) need not wait for that.\n   */\n  async migrateInlineObjects(spaceId: SpaceId): Promise<void> {\n    this.#scheduleDirectoryMaintenance(spaceId);\n    await this.#retirements.get(spaceId);\n  }\n\n  /**\n   * Queues a directory maintenance pass for a space behind the one already running: inline objects are migrated\n   * out first, then documents are retired. Failures are logged, not propagated.\n   */\n  #scheduleDirectoryMaintenance(spaceId: SpaceId): void {\n    const previous = this.#retirements.get(spaceId) ?? Promise.resolve();\n    const next = previous\n      .then(() => this.#migrateInlineObjectsPass(spaceId))\n      .catch((err) => {\n        if (!this._ctx.disposed) {\n          log.warn('inline object migration failed', { spaceId, err });\n        }\n      })\n      .then(() => this.#retireDocuments(spaceId))\n      .catch((err) => {\n        if (!this._ctx.disposed) {\n          log.warn('document retirement failed', { spaceId, err });\n        }\n      });\n    this.#retirements.set(spaceId, next);\n  }\n\n  /**\n   * Moves each object inlined in the space directory (`DatabaseDirectory.objects`) into a document of its own and\n   * replaces it with a link, keeping its id and its current state. The documents are derived from the directory and\n   * the object (see {@link inlineObjectDocumentId}), so peers that migrate the same directory concurrently converge\n   * on one document per object instead of duplicating it. Idempotent: a directory with no inline objects is left as\n   * it is.\n   */\n  async #migrateInlineObjectsPass(spaceId: SpaceId): Promise<void> {\n    if (this._ctx.disposed || !this.isOpen) {\n      return;\n    }\n    const root = this._spaceStateManager.getRootBySpaceId(spaceId);\n    const directory = root?.doc();\n    if (!root || !directory || Object.keys(directory.objects ?? {}).length === 0) {\n      return;\n    }\n\n    const spaceKey = root.getSpaceKey();\n    const leases = new Map<string, DocumentLease<DatabaseDirectory>>();\n    try {\n      for (const [objectId, structure] of Object.entries(A.toJS(directory).objects ?? {})) {\n        const documentId = await inlineObjectDocumentId(root.documentId, objectId);\n        // Another peer's migration may have delivered the document already; importing over it would start a\n        // second history for the same object.\n        const [existingHeads] = await this._automergeHost.getHeads([documentId]);\n        const lease =\n          existingHeads && existingHeads.length > 0\n            ? await this._automergeHost.loadDoc<DatabaseDirectory>(this._ctx, documentId)\n            : await this._automergeHost.createDoc<DatabaseDirectory>(\n                await buildInlineObjectDocument({\n                  directoryId: root.documentId,\n                  spaceId,\n                  spaceKey,\n                  objectId,\n                  structure,\n                }),\n                { preserveHistory: true, documentId },\n              );\n        if (lease) {\n          leases.set(objectId, lease);\n        }\n      }\n      if (this._ctx.disposed) {\n        return;\n      }\n\n      // No await from here to the directory change, so an edit made to an inline object while its document was\n      // being created is carried over rather than lost.\n      const currentDirectory = root.doc();\n      const current = currentDirectory ? (A.toJS(currentDirectory).objects ?? {}) : {};\n      const migrated: { objectId: string; lease: DocumentLease<DatabaseDirectory> }[] = [];\n      for (const [objectId, lease] of leases) {\n        const state = current[objectId];\n        if (state === undefined) {\n          continue;\n        }\n        if (isUntouchedSinceCreation(lease.doc()) && !isEqual(A.toJS(lease.doc()).objects?.[objectId], state)) {\n          lease.change((draft: DatabaseDirectory) => {\n            draft.objects ??= {};\n            draft.objects[objectId] = state;\n          });\n        }\n        migrated.push({ objectId, lease });\n      }\n      if (migrated.length === 0) {\n        return;\n      }\n      root.change((draft: DatabaseDirectory) => {\n        draft.links ??= {};\n        for (const { objectId, lease } of migrated) {\n          draft.links[objectId] = new A.RawString(lease.url);\n          if (draft.objects) {\n            delete draft.objects[objectId];\n          }\n        }\n      });\n      await this._automergeHost.flush(this._ctx, {\n        documentIds: [root.documentId, ...migrated.map(({ lease }) => lease.documentId)],\n      });\n      // The directory's rows would otherwise outlive the move: the indexer adds rows for the objects it finds.\n      await RuntimeProvider.runPromise(this._runtime)(\n        this.indexEngine.deleteObjects({\n          spaceId,\n          documentIds: [],\n          objects: migrated.map(({ objectId }) => ({ documentId: root.documentId, objectId })),\n        }),\n      );\n      log.info('migrated inline objects out of the space directory', { spaceId, objects: migrated.length });\n    } finally {\n      for (const lease of leases.values()) {\n        lease[Symbol.dispose]();\n      }\n    }\n  }\n\n  /**\n   * Retirement, in every direction. Documents the space directory has retired are wiped without being read —\n   * the share of every peer. Linked documents this host could not load, or whose history outgrew their state,\n   * are rebuilt from the index and retired in the directory — the share of the peer that found them.\n   */\n  async #retireDocuments(spaceId: SpaceId): Promise<void> {\n    if (this._ctx.disposed || !this.isOpen) {\n      return;\n    }\n    const root = this._spaceStateManager.getRootBySpaceId(spaceId);\n    const directory = root?.directory();\n    if (!root || !directory) {\n      return;\n    }\n\n    await this.#wipeRetiredDocuments(spaceId, DatabaseDirectory.getRetiredDocuments(directory));\n    await this.#restoreLostRetirements(spaceId, root);\n\n    // Keyed by the id as it is spelled in a link, so the scan below compares strings: decoding every link\n    // (a base58check checksum each) on every directory change saturated the worker on large spaces.\n    const candidates = new Map<string, DocumentId>();\n    for (const [documentId, record] of this._automergeHost.quarantinedDocuments) {\n      if (record.reason === 'load-failed') {\n        candidates.set(documentId, documentId);\n      }\n    }\n    for (const documentId of this.#historyCandidates.keys()) {\n      candidates.set(documentId, documentId);\n    }\n    if (candidates.size === 0) {\n      return;\n    }\n\n    const unloadable = new Map<DocumentId, string[]>();\n    const bloated = new Map<DocumentId, string[]>();\n    for (const [objectId, link] of Object.entries(directory.links ?? {})) {\n      const documentId = candidates.get(linkedDocumentIdText(link.toString()));\n      if (documentId === undefined || directory.retired?.[documentId] !== undefined) {\n        continue;\n      }\n      if (this._automergeHost.quarantinedDocuments.get(documentId)?.reason === 'load-failed') {\n        defaultMap(unloadable, documentId, () => []).push(objectId);\n      } else if (this.#historyCandidates.has(documentId)) {\n        defaultMap(bloated, documentId, () => []).push(objectId);\n      }\n    }\n    for (const [documentId, objectIds] of unloadable) {\n      await this.#retireUnloadableDocument(spaceId, root, documentId, objectIds);\n    }\n    for (const [documentId, objectIds] of bloated) {\n      await this.#retireBloatedDocument(spaceId, root, documentId, objectIds);\n    }\n  }\n\n  /**\n   * Writes back `retired` entries this host knows of but the directory lacks. Two peers that each create the\n   * map concurrently leave only one of them in the merge, so an entry can vanish after it was written.\n   */\n  async #restoreLostRetirements(spaceId: SpaceId, root: DatabaseRoot): Promise<void> {\n    const directory = root.directory();\n    const lost = [...this.#knownRetirements.values()].filter(\n      (retirement) => retirement.spaceId === spaceId && directory?.retired?.[retirement.documentId] === undefined,\n    );\n    if (lost.length === 0) {\n      return;\n    }\n    await root.load();\n    root.change((draft) => {\n      draft.retired ??= {};\n      for (const { documentId, replacedBy, reason } of lost) {\n        draft.retired[documentId] = { replacedBy: new A.RawString(replacedBy), reason: new A.RawString(reason) };\n      }\n    });\n    log.info('restored retirements lost to a concurrent change', { spaceId, documents: lost.length });\n  }\n\n  /**\n   * Retires a document that cannot be loaded, rebuilt from the state the index last saw. Left quarantined, and\n   * not retired, while the index lacks any of the document's objects.\n   */\n  async #retireUnloadableDocument(\n    spaceId: SpaceId,\n    root: DatabaseRoot,\n    documentId: DocumentId,\n    objectIds: string[],\n  ): Promise<void> {\n    const indexed = await RuntimeProvider.runPromise(this._runtime)(\n      Effect.gen({ self: this }, function* () {\n        const metas = (yield* this.indexEngine.queryObjectIds({ spaceIds: [spaceId], objectIds })).filter(\n          (meta) => meta.documentId === documentId,\n        );\n        const snapshots = new Map(\n          (yield* this.indexEngine.querySnapshotsJSON(metas.map((meta) => meta.recordId))).map(\n            ({ recordId, snapshot }) => [recordId, snapshot],\n          ),\n        );\n        return metas.flatMap((meta): IndexedObject[] => {\n          const json = snapshots.get(meta.recordId);\n          return json ? [{ objectId: meta.objectId, json, createdAt: meta.createdAt }] : [];\n        });\n      }),\n    );\n    const missing = objectIds.filter((objectId) => !indexed.some((object) => object.objectId === objectId));\n    if (missing.length > 0) {\n      log.warn('unloadable document kept quarantined: the index has no state for some of its objects', {\n        spaceId,\n        documentId,\n        missing,\n      });\n      return;\n    }\n\n    await this.#replaceDocument(\n      spaceId,\n      root,\n      documentId,\n      objectIds,\n      makeReplacementDirectory({ spaceId, spaceKey: root.getSpaceKey(), objects: indexed }),\n      'load-failed',\n    );\n    log.info('retired a document that could not be loaded', { spaceId, documentId, objects: objectIds.length });\n  }\n\n  /**\n   * Retires a loaded document whose history has outgrown its state, if it holds only the objects linked to it and\n   * all are of a type that may be rebuilt (see `HISTORY_RETIREMENT_TYPES`). Rebuilt from the document's own current\n   * state, so it keeps every change, including any the index has not caught up with.\n   */\n  async #retireBloatedDocument(\n    spaceId: SpaceId,\n    root: DatabaseRoot,\n    documentId: DocumentId,\n    objectIds: string[],\n  ): Promise<void> {\n    const ops = this.#historyCandidates.get(documentId) ?? 0;\n    this.#historyCandidates.delete(documentId);\n    using lease = await this._automergeHost.loadDoc<DatabaseDirectory>(this._ctx, documentId);\n    const state = lease ? A.toJS(lease.doc()) : undefined;\n    const objects = state?.objects ?? {};\n    if (\n      !state ||\n      Object.keys(objects).length !== objectIds.length ||\n      !isRetirableForHistory(objectIds.map((objectId) => objects[objectId]?.system?.type?.['/']))\n    ) {\n      return;\n    }\n    const stateBytes = JSON.stringify(objects).length;\n    if (!isHistoryBloated({ ops, stateBytes })) {\n      return;\n    }\n\n    await this.#replaceDocument(\n      spaceId,\n      root,\n      documentId,\n      objectIds,\n      { version: state.version, access: state.access, objects },\n      'history',\n    );\n    log.info('retired a document whose history outgrew its state', {\n      spaceId,\n      documentId,\n      ops,\n      stateBytes,\n      objects: objectIds.length,\n    });\n  }\n\n  /**\n   * Replaces a document with `directory`, which carries no history, then records the retirement in the space\n   * directory, which every peer acts on, and wipes the original here.\n   */\n  async #replaceDocument(\n    spaceId: SpaceId,\n    root: DatabaseRoot,\n    documentId: DocumentId,\n    objectIds: string[],\n    directory: DatabaseDirectory,\n    reason: RetirementReason,\n  ): Promise<void> {\n    const replacementId = await replacementDocumentId(documentId);\n    const replacementUrl = stringifyAutomergeUrl(replacementId);\n    // Another peer's retirement may have delivered the replacement already; importing over it would start a\n    // second history for the same objects.\n    const [existingHeads] = await this._automergeHost.getHeads([replacementId]);\n    const lease =\n      existingHeads && existingHeads.length > 0\n        ? undefined\n        : await this._automergeHost.createDoc<DatabaseDirectory>(\n            await buildReplacementDocument(documentId, directory),\n            { preserveHistory: true, documentId: replacementId },\n          );\n    try {\n      await root.load();\n      root.change((draft) => {\n        draft.links ??= {};\n        for (const objectId of objectIds) {\n          draft.links[objectId] = new A.RawString(replacementUrl);\n        }\n        draft.retired ??= {};\n        draft.retired[documentId] = { replacedBy: new A.RawString(replacementUrl), reason: new A.RawString(reason) };\n      });\n      await this._automergeHost.flush(this._ctx, { documentIds: [root.documentId, replacementId] });\n    } finally {\n      lease?.[Symbol.dispose]();\n    }\n\n    await this.#wipeRetiredDocuments(spaceId, [{ documentId, replacedBy: replacementUrl, reason }]);\n  }\n\n  /**\n   * Wipes documents the space directory retired, without reading them: the directory naming them is the\n   * attribution, since loading one is what retirement exists to avoid. Idempotent, and run on every open, since the\n   * directory is the only durable record of a retirement.\n   */\n  async #wipeRetiredDocuments(spaceId: SpaceId, entries: readonly Retirement[]): Promise<void> {\n    const candidates = entries.filter(\n      (entry): entry is Retirement & { documentId: DocumentId } =>\n        isValidDocumentId(entry.documentId) && !this.#wipedDocuments.has(entry.documentId),\n    );\n    if (candidates.length === 0) {\n      return;\n    }\n    const referenced = this.#referencedDocuments();\n    const indexedElsewhere = await RuntimeProvider.runPromise(this._runtime)(\n      this.indexEngine.queryDocumentsIndexedElsewhere({\n        spaceId,\n        documentIds: candidates.map((entry) => entry.documentId),\n      }),\n    );\n    const isProtected = (documentId: DocumentId) => referenced.has(documentId) || indexedElsewhere.has(documentId);\n    const retired = candidates.filter((entry) => !isProtected(entry.documentId));\n    if (retired.length < candidates.length) {\n      log.warn('ignored retirements naming documents another space or a live link still uses', {\n        spaceId,\n        documentIds: candidates.filter((entry) => isProtected(entry.documentId)).map((entry) => entry.documentId),\n      });\n    }\n    if (retired.length === 0) {\n      return;\n    }\n    for (const retirement of retired) {\n      this.#knownRetirements.set(retirement.documentId, { ...retirement, spaceId });\n      await this._automergeHost.quarantineDocument(retirement.documentId, { reason: 'retired' });\n    }\n    const documentIds = retired.map(({ documentId }) => documentId);\n    // Index rows first: the indexer finds documents through them, so one outliving its bytes would be read again.\n    await RuntimeProvider.runPromise(this._runtime)(\n      this.indexEngine.deleteObjects({ spaceId, documentIds, objects: [] }),\n    );\n    for (const documentId of documentIds) {\n      await this._automergeHost.removeDocument(documentId);\n      this.#wipedDocuments.add(documentId);\n      this.#historyCandidates.delete(documentId);\n    }\n    log('wiped retired documents', { spaceId, documents: documentIds.length });\n  }\n\n  /**\n   * Documents a space on this host still references: the directory, space root and credentials of every persisted\n   * space, opened or not, and every link and branch of an open directory. A `retired` entry naming one is never acted\n   * on, since any member can write a directory and a document id may belong to another space; a genuine retirement\n   * re-points the links in the same change. Links of an unopened directory are covered by the index instead.\n   */\n  #referencedDocuments(): Set<DocumentId> {\n    const urls: string[] = [];\n    const referenced = new Set<DocumentId>();\n    for (const spaceId of this._spaceStateManager.spaceIds) {\n      const directoryId = this._spaceStateManager.getSpaceRootDocumentId(spaceId);\n      if (directoryId) {\n        referenced.add(directoryId);\n      }\n      const refs = this._spaceStateManager.getSpaceRootRefs(spaceId);\n      urls.push(...[refs?.spaceRootDocUrl, refs?.credentialsDocUrl].filter((url) => url !== undefined));\n    }\n    for (const [documentId, root] of this._spaceStateManager.roots) {\n      referenced.add(documentId);\n      if (root.directory()) {\n        urls.push(...root.getAllLinkedDocuments().map((url) => url.toString()));\n      }\n    }\n    for (const url of urls) {\n      if (isValidAutomergeUrl(url)) {\n        referenced.add(interpretAsDocumentId(url));\n      }\n    }\n    return referenced;\n  }\n\n  /** Document ids present in the space's previous directory listing but not the current one. */\n  #departedDocuments(previous: ReadonlySet<DocumentId>, event: SpaceDocumentListUpdatedEvent): DocumentId[] {\n    const current = new Set(event.documentIds);\n    return [...previous].filter((documentId) => !current.has(documentId));\n  }\n\n  /**\n   * Wipes documents that left a space's directory, off the critical path of applying the change\n   * that removed them. Failures are logged rather than propagated: reclamation is best-effort\n   * maintenance, and a space that fails to reclaim is only still holding disk.\n   *\n   * A retired root is expanded to its whole closure rather than trusting the departed set. The\n   * diff only knows what this peer observed, and the directory listing is debounced — a document\n   * linked and then orphaned in quick succession may never have appeared in a listing at all.\n   * Walking the retired root makes an epoch deterministic regardless of what was seen.\n   *\n   * The unlink case has no equivalent anchor and so relies on the diff, which is exact for the\n   * case it exists to serve: an unlink replicating in from a peer arrives long after the link it\n   * removes, so the document was certainly observed. A document that was never observed is left\n   * for the next explicit collection pass, whose orphan scan finds it by reachability.\n   */\n  #scheduleReclaim(spaceId: SpaceId, departed: DocumentId[], retiredRoot?: DocumentId): void {\n    scheduleTask(this._ctx, async () => {\n      try {\n        const candidates = new Set(departed);\n        if (retiredRoot) {\n          for (const documentId of await this.#collectClosure(retiredRoot)) {\n            candidates.add(documentId);\n          }\n        }\n        // Nothing to reclaim: return before touching the live directory. Walking it to build a\n        // reachable set no candidate would be tested against costs one storage load per document in\n        // the space, which on a large space is seconds of thread time for no possible outcome.\n        if (candidates.size === 0) {\n          return;\n        }\n\n        // Re-checked against the live directory: between the event and this task the documents\n        // could have been re-linked (a concurrent write merging in), and reachable data is never\n        // a collection candidate.\n        // An unreadable live directory is unknown reachability, not empty reachability: taking it\n        // as empty would make every candidate — including documents a new root carried forward —\n        // read as collectable. Skipping only defers, since the explicit pass scans for orphans.\n        const root = this._spaceStateManager.getRootBySpaceId(spaceId);\n        if (!root || !(await this.#loadFromStorage(root.documentId))) {\n          log('reclamation skipped, live space directory unavailable', { spaceId });\n          return;\n        }\n        // Only the candidates' reachability is in question, so the walk stops as soon as every one\n        // has been found rather than enumerating the whole space. Proving a candidate *unreachable*\n        // still costs a full traversal — that is inherent to reachability — but the common\n        // re-link case now exits after a few loads instead of thousands.\n        const reachable = await this.#collectClosure(root.documentId, candidates);\n\n        const stale: DocumentId[] = [];\n        for (const documentId of candidates) {\n          if (reachable.has(documentId)) {\n            continue;\n          }\n          // Same attribution boundary as the explicit pass: never wipe a document that does not\n          // positively identify as this space's.\n          if (await this.#isOwnedBySpace(spaceId, documentId)) {\n            stale.push(documentId);\n          }\n        }\n        if (stale.length === 0) {\n          return;\n        }\n\n        // Index state first: the indexer enumerates documents from their heads rows and cursors,\n        // and a pass landing between the wipe and this cleanup would re-load a document whose\n        // bytes are gone — which re-creates it as an empty document and persists it again.\n        await RuntimeProvider.runPromise(this._runtime)(\n          this.indexEngine.deleteObjects({ spaceId, documentIds: stale, objects: [] }),\n        );\n        for (const documentId of stale) {\n          await this._automergeHost.removeDocument(documentId);\n        }\n        log.info('reclaimed documents that left the space directory', { spaceId, documents: stale.length });\n      } catch (err) {\n        if (this._ctx.disposed) {\n          return;\n        }\n        log.warn('automatic reclamation failed', { spaceId, err });\n      }\n    });\n  }\n\n  /**\n   * Transitive closure of documents reachable from a document, over object links and branch\n   * members. Storage-only: fetching from the network here would re-materialize the very documents\n   * being collected. A document that is not on disk terminates the walk.\n   */\n  async #collectClosure(documentId: DocumentId, stopWhenFound?: ReadonlySet<DocumentId>): Promise<Set<DocumentId>> {\n    const visited = new Set<DocumentId>();\n    const queue: DocumentId[] = [documentId];\n    // When the caller only needs a membership answer, track what is still outstanding so the walk\n    // can stop early. An empty set means the caller wants the full closure.\n    const outstanding = stopWhenFound ? new Set(stopWhenFound) : undefined;\n    let sinceYield = 0;\n    while (queue.length > 0) {\n      const next = queue.shift()!;\n      if (visited.has(next)) {\n        continue;\n      }\n      visited.add(next);\n      outstanding?.delete(next);\n      if (outstanding?.size === 0) {\n        break;\n      }\n      // Every load parses an automerge document on the single worker thread, so a large space would\n      // otherwise hold it for seconds and stall the RPCs a booting tab is waiting on.\n      if (++sinceYield >= CLOSURE_YIELD_INTERVAL) {\n        sinceYield = 0;\n        await sleep(0);\n        // Throw rather than return what has been walked so far: a truncated traversal is not a\n        // closure, and returning it would read as \"these documents are unreachable\" and wipe live\n        // data. `#scheduleReclaim` swallows this once the context is disposed.\n        if (this._ctx.disposed) {\n          throw new Error('closure traversal aborted: context disposed');\n        }\n      }\n      const doc = await this.#loadFromStorage(next);\n      if (!doc) {\n        continue;\n      }\n      for (const url of [\n        ...Object.values(doc.links ?? {}).map((link) => link.toString()),\n        ...DatabaseDirectory.getAllBranchDocUrls(doc),\n      ]) {\n        if (isValidAutomergeUrl(url)) {\n          queue.push(interpretAsDocumentId(url as AutomergeUrl));\n        }\n      }\n    }\n    return visited;\n  }\n\n  async #isOwnedBySpace(spaceId: SpaceId, documentId: DocumentId): Promise<boolean> {\n    const doc = await this.#loadFromStorage(documentId);\n    return doc ? (await DatabaseDirectory.getSpaceId(doc)) === spaceId : false;\n  }\n\n  async #loadFromStorage(documentId: DocumentId): Promise<DatabaseDirectory | null> {\n    try {\n      using lease = await this._automergeHost.loadDoc<DatabaseDirectory>(this._ctx, documentId, {\n        fetchFromNetwork: false,\n      });\n      return lease?.doc() ?? null;\n    } catch (err) {\n      log.warn('reclamation: document failed to load, treating as opaque', { documentId, err });\n      return null;\n    }\n  }\n\n  /** Enumerate the documents reachable from a space root (root + object links + branch members). */\n  #collectSpaceDocuments(root: DatabaseRoot): SpaceDocumentSet {\n    const doc = root.directory();\n    if (!doc) {\n      return { rootDocumentId: root.documentId, linkedDocumentIds: [], branchDocumentIds: [] };\n    }\n\n    const linkedDocumentIds = Object.values(doc.links ?? {}).map((url) =>\n      interpretAsDocumentId(url.toString() as AutomergeUrl),\n    );\n    const branchDocumentIds = DatabaseDirectory.getAllBranchDocUrls(doc).map((url) =>\n      interpretAsDocumentId(url as AutomergeUrl),\n    );\n\n    return { rootDocumentId: root.documentId, linkedDocumentIds, branchDocumentIds };\n  }\n\n  /** Distinct set of every document id owned by the space directory. */\n  #allSpaceDocumentIds(docs: SpaceDocumentSet): Set<DocumentId> {\n    return new Set<DocumentId>([docs.rootDocumentId, ...docs.linkedDocumentIds, ...docs.branchDocumentIds]);\n  }\n\n  /**\n   * Count live/soft-deleted objects across the root and every object-bearing linked document.\n   * Branch documents are skipped to avoid double-counting an object across its branches.\n   */\n  async #countSpaceObjects(root: DatabaseRoot, docs: SpaceDocumentSet): Promise<{ alive: number; deleted: number }> {\n    const counts = { alive: 0, deleted: 0 };\n    const addCounts = (doc: DatabaseDirectory) => {\n      for (const object of Object.values(doc.objects ?? {}) as EntityStructure[]) {\n        if (EntityStructure.isDeleted(object)) {\n          counts.deleted += 1;\n        } else {\n          counts.alive += 1;\n        }\n      }\n    };\n\n    const rootDoc = root.directory();\n    if (rootDoc) {\n      addCounts(rootDoc);\n    }\n\n    for (const documentId of docs.linkedDocumentIds) {\n      // Storage-only: `stats()` is a local metric and must always resolve. A default load would\n      // wait on the network for a linked document that is not on disk, hanging `stats()` for an\n      // offline space; an unavailable document is simply not counted.\n      using lease = await this._automergeHost.loadDoc<DatabaseDirectory>(this._ctx, documentId, {\n        fetchFromNetwork: false,\n      });\n      const doc = lease?.doc();\n      if (doc) {\n        addCounts(doc);\n      }\n    }\n\n    return counts;\n  }\n\n  /**\n   * GC step 1: remove soft-deleted objects from the space directory — deleted inlined objects are\n   * dropped from the root document; deleted linked objects (and links dangling to a missing\n   * document) have their `links` entry removed, orphaning the document for step 2.\n   */\n  async #unlinkDeletedObjects(\n    spaceId: SpaceId,\n    root: DatabaseRoot,\n  ): Promise<{ unlinkedObjects: number; removedInlineObjects: { documentId: string; objectId: string }[] }> {\n    const rootDoc = root.directory();\n    if (!rootDoc) {\n      return { unlinkedObjects: 0, removedInlineObjects: [] };\n    }\n\n    // Every entity in the directory is registered before anything is judged: deletion cascades\n    // through parents and relation endpoints, which routinely live in a different document than\n    // the object they condemn.\n    const deletion = new DeletionResolver(spaceId);\n    deletion.add(rootDoc.objects);\n    const linkedDocs = new Map<string, DatabaseDirectory>();\n    for (const [objectId, url] of Object.entries(rootDoc.links ?? {})) {\n      const documentId = interpretAsDocumentId(url.toString() as AutomergeUrl);\n      using lease = await this._automergeHost.loadDoc<DatabaseDirectory>(this._ctx, documentId, {\n        fetchFromNetwork: false,\n      });\n      const doc = lease?.doc();\n      if (!doc) {\n        // A storage-only miss is ambiguous: the document may be genuinely gone, or it may be live\n        // data this host has not replicated yet. Retain the link — unlinking here would sync the\n        // removal and make a live object unreachable. Only a loaded, confirmed-deleted object is\n        // unlinked below.\n        continue;\n      }\n      linkedDocs.set(objectId, doc);\n      deletion.add(doc.objects);\n    }\n\n    const deletedInlineIds = Object.keys(rootDoc.objects ?? {}).filter((id) => deletion.isDeleted(id));\n\n    const deletedLinkIds: string[] = [];\n    for (const [objectId] of linkedDocs) {\n      if (deletion.has(objectId) && deletion.isDeleted(objectId)) {\n        deletedLinkIds.push(objectId);\n      }\n    }\n\n    if (deletedInlineIds.length === 0 && deletedLinkIds.length === 0) {\n      return { unlinkedObjects: 0, removedInlineObjects: [] };\n    }\n\n    await root.load();\n    root.change((draft: DatabaseDirectory) => {\n      for (const id of deletedInlineIds) {\n        if (draft.objects) {\n          delete draft.objects[id];\n        }\n      }\n      for (const id of deletedLinkIds) {\n        if (draft.links) {\n          delete draft.links[id];\n        }\n      }\n    });\n\n    return {\n      unlinkedObjects: deletedInlineIds.length + deletedLinkIds.length,\n      removedInlineObjects: deletedInlineIds.map((objectId) => ({ documentId: root.documentId, objectId })),\n    };\n  }\n\n  /**\n   * GC step 2: wipe every document owned by the space that is no longer reachable from the (post\n   * step-1) directory. Reachability is recomputed here so just-unlinked documents fall out of the\n   * set. Attribution is the safety boundary — a document is wiped only when its `access.spaceId`\n   * matches; a document that cannot be loaded (offline) or carries no owner is left untouched.\n   */\n  async #wipeUnreachableDocuments(spaceId: SpaceId, root: DatabaseRoot): Promise<DocumentId[]> {\n    const reachable = this.#allSpaceDocumentIds(this.#collectSpaceDocuments(root));\n    const wipedDocumentIds: DocumentId[] = [];\n    for await (const { documentId } of this._automergeHost.listDocumentHeads()) {\n      if (reachable.has(documentId)) {\n        continue;\n      }\n      using lease = await this._automergeHost.loadDoc<DatabaseDirectory>(this._ctx, documentId, {\n        fetchFromNetwork: false,\n      });\n      const doc = lease?.doc();\n      if (!doc) {\n        continue;\n      }\n      const owner = await DatabaseDirectory.getSpaceId(doc);\n      if (owner !== spaceId) {\n        continue;\n      }\n      await this._automergeHost.removeDocument(documentId);\n      wipedDocumentIds.push(documentId);\n      log('gc: wiped orphaned document', { spaceId, documentId });\n    }\n    return wipedDocumentIds;\n  }\n\n  /** Resolve the space root, opening it if this host does not hold it yet. */\n  async #ensureSpaceRootLoaded(spaceId: SpaceId): Promise<DatabaseRoot> {\n    const existing = this._spaceStateManager.getRootBySpaceId(spaceId);\n    if (existing?.isAvailable) {\n      return existing;\n    }\n    return this.openSpaceRoot(this._ctx, spaceId);\n  }\n\n  /**\n   * Debounces the deferred full-text re-tokenization, bounded by {@link FTS_FLUSH_MAX_DELAY_MS} so\n   * a stream of writes that never pauses still makes progress.\n   */\n  #scheduleFtsFlush(): void {\n    const now = performance.now();\n    const deadline = (this.#ftsFlushDeadline ??= now + FTS_FLUSH_MAX_DELAY_MS);\n    const generation = ++this.#ftsFlushGeneration;\n\n    scheduleTask(\n      this._ctx,\n      async () => {\n        // A later write re-armed the timer, so its run covers this one too — unless the ceiling\n        // has passed, where waiting again is the thing being prevented.\n        if (generation !== this.#ftsFlushGeneration && performance.now() < deadline) {\n          return;\n        }\n        this.#ftsFlushDeadline = undefined;\n        if (this._ctx.disposed || !this.isOpen) {\n          return;\n        }\n\n        const records = await this.updateSecondaryIndexes();\n        if (records > 0) {\n          log.verbose('flushed deferred full-text index', { records });\n        }\n      },\n      Math.max(0, Math.min(FTS_FLUSH_IDLE_MS, deadline - now)),\n    );\n  }\n\n  /**\n   * Applies each pending feed-options intent to the feed store and clears it. The index side runs\n   * before the store write, so a crash in between redoes it: a disable removes the feed's rows on\n   * every apply, and a re-enable seeds the backfill while the store still holds the disabled options.\n   * The index mode is handled the same way: widening to all branches seeds a backfill, and narrowing\n   * to the main branch removes the other branches' rows. A failed apply leaves its intent pending for\n   * the next pass.\n   */\n  #applyFeedOptionsIntents(changes: FeedChanges): Effect.Effect<void, never, SqlClient.SqlClient> {\n    return Effect.gen({ self: this }, function* () {\n      const { maxId, intents } = yield* this.indexEngine.takeFeedOptionsIntents();\n      for (const { spaceId, feedId, namespace, options } of intents) {\n        const feed: FeedKey = { spaceId, feedId, feedNamespace: namespace };\n        yield* Effect.gen({ self: this }, function* () {\n          const previous = yield* this._feedStore.getFeedOptions(feed);\n          if (isIndexingDisabled(options)) {\n            const deleted = yield* this.indexEngine.deleteFeedObjects({ spaceId, queueId: feedId });\n            if (deleted > 0 && EntityId.isValid(feedId)) {\n              changes.spaceIds.add(spaceId);\n              changes.queueIds.add(feedId);\n            }\n          } else if (isIndexingDisabled(previous) || (indexesAllBranches(options) && !indexesAllBranches(previous))) {\n            yield* this.indexEngine.seedCursor({\n              sourceName: this._feedDataSource.sourceName,\n              spaceId,\n              resourceId: backfillResourceId(namespace, feedId),\n              cursor: '',\n            });\n          } else if (!indexesAllBranches(options) && indexesAllBranches(previous)) {\n            const deleted = yield* this.indexEngine.deleteFeedBranchObjects({ spaceId, queueId: feedId });\n            if (deleted > 0 && EntityId.isValid(feedId)) {\n              changes.spaceIds.add(spaceId);\n              changes.queueIds.add(feedId);\n            }\n          }\n          const { trim } = yield* this._feedStore.setFeedOptions({ ...feed, options });\n          const now = yield* Clock.currentTimeMillis;\n          yield* trimUntilDone(this._feedStore.trim(feed, now), trim);\n          yield* this.indexEngine.clearFeedOptionsIntents(spaceId, feedId, maxId);\n        }).pipe(\n          Effect.catch((error) =>\n            Effect.sync(() =>\n              log.warn('feed options could not be applied; retrying next pass', { spaceId, feedId, error }),\n            ),\n          ),\n        );\n      }\n    }).pipe(\n      Effect.catch((error) => Effect.sync(() => log.warn('feed-options intents could not be read', { error }))),\n      Effect.withSpan('EchoHost.applyFeedOptionsIntents'),\n    );\n  }\n\n  /** Trims every feed of each space until retention leaves nothing past a limit. */\n  #trimSpaces(spaceIds: Iterable<string>): Effect.Effect<void, never, SqlClient.SqlClient> {\n    return Effect.gen({ self: this }, function* () {\n      for (const spaceId of spaceIds) {\n        const now = yield* Clock.currentTimeMillis;\n        yield* trimUntilDone(this._feedStore.trimAll(spaceId, now)).pipe(\n          Effect.catch((error) => Effect.sync(() => log.warn('feed retention trim failed', { spaceId, error }))),\n        );\n      }\n    });\n  }\n\n  /** Deletes the backfill cursors the feed source reported finished. */\n  #deleteFinishedBackfills(finished: ReadonlyMap<SpaceId, ReadonlySet<string>>): Effect.Effect<void, never, never> {\n    return Effect.gen({ self: this }, function* () {\n      for (const [spaceId, resourceIds] of finished) {\n        yield* this.indexEngine.deleteFinishedCursors({\n          sourceName: this._feedDataSource.sourceName,\n          spaceId,\n          resourceIds: [...resourceIds],\n          cursor: BACKFILL_FINISHED,\n        });\n      }\n    }).pipe(Effect.catch((error) => Effect.sync(() => log.warn('finished backfill cursors not deleted', { error }))));\n  }\n\n  /**\n   * Removes the index rows of blocks retention deleted, a bounded number per pass, and forgets each\n   * batch once its rows are gone. Returns whether logged blocks remain for a later pass.\n   */\n  #purgeTrimmedBlocks(changes: FeedChanges): Effect.Effect<boolean, never, SqlClient.SqlClient> {\n    return Effect.gen({ self: this }, function* () {\n      for (let batch = 0; batch < PURGE_BATCHES_PER_PASS; batch++) {\n        const { maxId, blocks } = yield* this._feedStore.takeTrimmed({ limit: PURGE_BATCH });\n        if (blocks.length === 0) {\n          return false;\n        }\n        const byFeed = new Map<string, { spaceId: SpaceId; queueId: string; blocks: typeof blocks }>();\n        for (const block of blocks) {\n          if (!SpaceId.isValid(block.spaceId)) {\n            continue;\n          }\n          const key = `${block.spaceId}/${block.feedId}`;\n          const entry = byFeed.get(key) ?? { spaceId: block.spaceId, queueId: block.feedId, blocks: [] };\n          entry.blocks.push(block);\n          byFeed.set(key, entry);\n        }\n        for (const feed of byFeed.values()) {\n          const deleted = yield* this.indexEngine.purgeFeedBlocks(feed);\n          if (deleted > 0 && EntityId.isValid(feed.queueId)) {\n            changes.spaceIds.add(feed.spaceId);\n            changes.queueIds.add(feed.queueId);\n          }\n        }\n        yield* this._feedStore.clearTrimmed(maxId);\n        if (blocks.length < PURGE_BATCH) {\n          return false;\n        }\n      }\n      return true;\n    }).pipe(\n      Effect.catch((error) =>\n        Effect.sync(() => {\n          log.warn('trimmed blocks could not be purged from the index; retrying next pass', { error });\n          return true;\n        }),\n      ),\n      Effect.withSpan('EchoHost.purgeTrimmedBlocks'),\n    );\n  }\n\n  /**\n   * One indexing pass over both data sources.\n   *\n   * Spanned so that a pass is a single trace naming the requests that caused it, instead of one\n   * parentless `IndexEngine.update` root per data source with nothing to attribute it to. The\n   * `ctx` the decorator hands back carries the pass span, and `EffectEx.withContext` is what\n   * carries it across into the Effect world.\n   */\n  @trace.span({\n    op: 'indexer',\n    // Flattened to strings/numbers: OTel attribute values are primitives, so a histogram object\n    // would be dropped by the exporter rather than reaching PostHog.\n    attributes: (_ctx: Context, reasons: Record<string, number>) => ({\n      reasons: Object.entries(reasons)\n        .map(([reason, count]) => `${reason}:${count}`)\n        .join(','),\n    }),\n    // The outcome rides on the span rather than a log line: the only level the OTLP log sink\n    // exports (INFO) is also one the browser console shows, and at three passes a second that\n    // buries the console it is meant to help.\n    resultAttributes: (outcome: IndexPassOutcome | undefined) => ({\n      updated: outcome?.updated ?? 0,\n      done: outcome?.done ?? false,\n      drained: outcome?.drained ?? false,\n      // A pass that indexed nothing yet still invalidates queries is the signature of a\n      // self-sustaining invalidation loop, so record whether this run re-armed its own trigger.\n      invalidates: outcome?.invalidates ?? false,\n      spaces: outcome?.spaces ?? 0,\n      documents: outcome?.documents ?? 0,\n    }),\n  })\n  private async _runIndexPass(ctx: Context, reasons: Record<string, number>): Promise<IndexPassOutcome | undefined> {\n    if (this._ctx.disposed || !this.isOpen) {\n      return undefined;\n    }\n    const startedAt = performance.now();\n    if (!this.#indexingMarked) {\n      this.#indexingMarked = true;\n      markMilestone('indexing.started');\n    }\n\n    try {\n      const combinedResult = _makeEmptyMergedResult();\n      const feedChanges = makeFeedChanges();\n      const countCatchUp = this.indexStatus.beginPass();\n\n      {\n        performance.mark('indexEngine.update.automerge:start');\n        // A feed append changes no document, yet the document leg reads the heads of every document and\n        // every cursor to find that out; an agent turn appends many times a second.\n        const scanDocuments = !this.#documentsDrained || !_onlyFeedReasons(reasons);\n        const result = scanDocuments\n          ? await this.indexEngine\n              .update(ctx, this._automergeDataSource, { spaceId: null, limit: 50, countCatchUp })\n              .pipe(EffectEx.withContext(ctx), RuntimeProvider.runPromise(this._runtime))\n          : undefined;\n        if (result) {\n          _mergeInto(combinedResult, result);\n          this.#documentsDrained = result.done && result.drained;\n        }\n\n        // Convergence-key duplicates are born from replication, and a replicated write is exactly what\n        // was just indexed — so this is the earliest a duplicate can be detected on this device.\n        // The trigger is the durable intent log, committed no later than the index cursors: a crash\n        // or a faulted merge pass leaves the intents in place, and this pass —\n        // which also runs once at every startup — retries them, so no detected duplicate is ever\n        // silently dropped. The merge's own writes land back here via `documentsSaved`, which\n        // re-indexes the tombstones; idempotence is what makes that follow-up pass a no-op.\n        const { maxId, intents } = await this.indexEngine\n          .takeConvergenceKeyIntents()\n          .pipe(RuntimeProvider.runPromise(this._runtime));\n        if (intents.size > 0) {\n          log('servicing convergence-key intents', {\n            spaces: intents.size,\n            keys: [...intents.values()].reduce((count, keys) => count + keys.size, 0),\n            upToId: maxId,\n          });\n          const { serviced } = await this._convergenceKeyMerger.mergeDuplicates(this._ctx, intents);\n          let cleared = 0;\n          for (const [spaceId, keys] of serviced) {\n            for (const key of keys) {\n              await this.indexEngine\n                .clearConvergenceKeyIntents(spaceId, key, maxId)\n                .pipe(RuntimeProvider.runPromise(this._runtime));\n              cleared++;\n            }\n          }\n          log('cleared serviced convergence-key intents', { cleared, upToId: maxId });\n        }\n\n        // After the object leg, which recorded them, and before the feed leg, so it reads under the new options.\n        await this.#applyFeedOptionsIntents(feedChanges).pipe(RuntimeProvider.runPromise(this._runtime));\n        performance.measure('Index Automerge', {\n          start: 'indexEngine.update.automerge:start',\n          detail: {\n            devtools: {\n              dataType: 'track-entry',\n              track: 'Indexing',\n              trackGroup: 'ECHO', // Group related tracks together\n              color: 'tertiary-dark',\n              properties: [['count', result?.updated ?? 0]],\n            },\n          },\n        });\n      }\n      if (this._ctx.disposed || !this.isOpen) {\n        return undefined;\n      }\n\n      {\n        performance.mark('indexEngine.update.queue:start');\n        const result = await this.indexEngine\n          .update(ctx, this._feedDataSource, { spaceId: null, limit: 50 })\n          .pipe(EffectEx.withContext(ctx), RuntimeProvider.runPromise(this._runtime));\n        _mergeInto(combinedResult, result);\n\n        const report = this._feedDataSource.takeReport();\n        for (const [spaceId, feedIds] of report.skippedFeeds) {\n          feedChanges.spaceIds.add(spaceId);\n          for (const feedId of feedIds) {\n            if (EntityId.isValid(feedId)) {\n              feedChanges.queueIds.add(feedId);\n            }\n          }\n        }\n        const purgeIncomplete = await Effect.gen({ self: this }, function* () {\n          // An append trims in its own transaction, but at most TRIM_LIMIT blocks; the rest goes here.\n          yield* this.#trimSpaces([...report.spaces]);\n          yield* this.#deleteFinishedBackfills(report.finishedBackfills);\n          return yield* this.#purgeTrimmedBlocks(feedChanges);\n        }).pipe(RuntimeProvider.runPromise(this._runtime));\n        if (purgeIncomplete) {\n          combinedResult.done = false;\n        }\n        performance.measure('Index Queues', {\n          start: 'indexEngine.update.queue:start',\n          detail: {\n            devtools: {\n              dataType: 'track-entry',\n              track: 'Indexing',\n              trackGroup: 'ECHO',\n              color: 'tertiary-dark',\n              properties: [['count', result.updated]],\n            },\n          },\n        });\n      }\n\n      countWork('echo.indexPasses');\n      countWork('echo.indexedObjects', combinedResult.updated);\n      // A document is only rebuilt for its history from index state that has caught up with it.\n      if (this.#historyCandidates.size > 0) {\n        for (const spaceId of combinedResult.spaces) {\n          this.#scheduleDirectoryMaintenance(spaceId);\n        }\n      }\n      if (combinedResult.updated > 0) {\n        this.#scheduleFtsFlush();\n      }\n\n      const indexHint = hintFromIndexingResult(combinedResult);\n      const feedHint = hintFromFeedChanges(feedChanges);\n      const hint = indexHint && feedHint ? mergeHints(indexHint, feedHint) : (indexHint ?? feedHint);\n      const durationMs = performance.now() - startedAt;\n      const summary = {\n        reasons,\n        durationMs,\n        // A run that indexed nothing yet still invalidates queries is the signature of a\n        // self-sustaining invalidation loop, so record whether this run re-armed its own trigger.\n        invalidates: !!hint,\n        updated: combinedResult.updated,\n        done: combinedResult.done,\n        drained: combinedResult.drained,\n        spaces: combinedResult.spaces.size,\n        queues: combinedResult.queues.size,\n        documents: combinedResult.documents.size,\n        types: combinedResult.types.size,\n        objects: combinedResult.objects.size,\n      };\n      if (durationMs >= SLOW_WORK_MS) {\n        log.warn('slow index pass', summary);\n      } else {\n        log.verbose('indexEngine update completed', summary);\n      }\n      await sleep(1);\n      // Invalidate queries after index update — the indexer is the sole invalidation source.\n      if (hint) {\n        this._queryService.invalidateQueries(hint);\n      }\n\n      if (!this._ctx.disposed && this.isOpen) {\n        await this.indexStatus.afterPass(combinedResult);\n      }\n      if (combinedResult.drained && !this.#caughtUpMarked) {\n        this.#caughtUpMarked = true;\n        markMilestone('indexing.caught-up');\n      }\n\n      return {\n        updated: combinedResult.updated,\n        done: combinedResult.done,\n        drained: combinedResult.drained,\n        invalidates: !!hint,\n        spaces: combinedResult.spaces.size,\n        documents: combinedResult.documents.size,\n      };\n    } catch (err) {\n      if (this._ctx.disposed || !this.isOpen) {\n        return undefined;\n      }\n      // Failsafe: prevent queries from freezing if the indexer faults.\n      this._queryService.invalidateQueries();\n      throw err;\n    }\n  }\n}\n\nexport type { EchoDataStats };\n\n/** What one indexing pass did, as the span reports it. */\ntype IndexPassOutcome = {\n  updated: number;\n  done: boolean;\n  drained: boolean;\n  invalidates: boolean;\n  spaces: number;\n  documents: number;\n};\n\ntype MutableIndexingAccumulator = {\n  updated: number;\n  done: boolean;\n  drained: boolean;\n  catchUp?: number;\n  spaces: Set<SpaceId>;\n  queues: Set<EntityId>;\n  documents: Set<string>;\n  types: Set<string>;\n  objects: Set<EntityId>;\n};\n\n/** Index runs a feed append starts; every other reason may follow a document save. */\nconst FEED_ONLY_REASONS: ReadonlySet<string> = new Set(['feed-blocks', 'trace-blocks']);\n\nconst _onlyFeedReasons = (reasons: Record<string, number>): boolean => {\n  const triggers = Object.keys(reasons);\n  return triggers.length > 0 && triggers.every((reason) => FEED_ONLY_REASONS.has(reason));\n};\n\nconst _makeEmptyMergedResult = (): MutableIndexingAccumulator => ({\n  updated: 0,\n  done: true,\n  drained: true,\n  spaces: new Set(),\n  queues: new Set(),\n  documents: new Set(),\n  types: new Set(),\n  objects: new Set(),\n});\n\nconst _mergeInto = (acc: MutableIndexingAccumulator, r: IndexingResult): void => {\n  acc.updated += r.updated;\n  acc.done = acc.done && r.done;\n  acc.drained = acc.drained && r.drained;\n  if (r.catchUp !== undefined) {\n    acc.catchUp = (acc.catchUp ?? 0) + r.catchUp;\n  }\n  for (const s of r.spaces) {\n    acc.spaces.add(s);\n  }\n  for (const q of r.queues) {\n    acc.queues.add(q);\n  }\n  for (const d of r.documents) {\n    acc.documents.add(d);\n  }\n  for (const t of r.types) {\n    acc.types.add(t);\n  }\n  for (const o of r.objects) {\n    acc.objects.add(o);\n  }\n};\n\nexport type EchoStatsDiagnostic = {\n  loadedDocsCount: number;\n  dataStats: EchoDataStats;\n};\n\n/** A space created from a space root document, before any credentials exist for it. */\nexport type CreatedSpace = {\n  spaceId: SpaceId;\n\n  /** Automerge URL of the immutable root; goes into the `SpaceMember` credential as `spaceRootUrl`. */\n  spaceRootUrl: AutomergeUrl;\n\n  directory: DatabaseRoot;\n};\n\nexport type EchoHostLayerOptions = Pick<\n  EchoHostProps,\n  | 'peerIdProvider'\n  | 'getSpaceKeyByRootDocumentId'\n  | 'assignQueuePositions'\n  | 'useSubduction'\n  | 'queryExecutor'\n  | 'queryDebounce'\n>;\n\n/**\n * Effect Layer constructing a dormant {@link EchoHost}.\n */\nexport const EchoHostLayer = (\n  options: EchoHostLayerOptions = {},\n): Layer.Layer<EchoHostService, never, SqlClient.SqlClient> =>\n  Layer.effect(\n    EchoHostService,\n    Effect.gen(function* () {\n      const runtime = yield* RuntimeProvider.currentRuntime<SqlClient.SqlClient>();\n      return new EchoHost({ runtime, ...options });\n    }),\n  );\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport * as Effect from 'effect/Effect';\nimport * as SqlClient from 'effect/sql/SqlClient';\n\nimport { asyncTimeout } from '@dxos/async';\nimport * as RuntimeProvider from '@dxos/effect/RuntimeProvider';\nimport { log } from '@dxos/log';\n\n/**\n * Executes \"PRAGMA quick_check;\" on SQLite database on startup.\n *\n * NOTE: Keep DISABLED in production, \"quick\" check is O(dbSize) which took 6 seconds for my relatively-small profile.\n */\nexport const RUN_SQLITE_QUICK_CHECK_ON_STARTUP = false;\n\n/** Timeout for the startup sqlite health check (schema probe + optional quick_check). */\nexport const SQLITE_HEALTH_CHECK_TIMEOUT_MS = 15_000;\n\n/**\n * Sqlite health check on startup.\n *\n * Always runs a cheap schema-level probe (`PRAGMA schema_version` + a read from\n * `sqlite_schema`). These do not walk user data, but they fail fast if the DB\n * file header or schema root page is unreadable.\n *\n * Additionally runs `PRAGMA quick_check` when {@link RUN_SQLITE_QUICK_CHECK_ON_STARTUP}\n * is enabled. That walks every page and is O(dbSize) — slow on OPFS.\n */\nexport const testSqlite = (): Effect.Effect<void, unknown, SqlClient.SqlClient> =>\n  Effect.gen(function* () {\n    log('begin sqlite health check');\n    const sql = yield* SqlClient.SqlClient;\n    const databases = yield* sql<{ seq: number; name: string; file: string }>`PRAGMA database_list`;\n    log('SQLite databases', { databases });\n\n    // Cheap header/schema probe: forces SQLite to read the file header and\n    // schema root page. Catches catastrophic corruption (bad header,\n    // unreadable schema) without walking user data.\n    const [schemaVersion] = yield* sql<{ schema_version: number }>`PRAGMA schema_version`;\n    const [schemaCount] = yield* sql<{ n: number }>`SELECT count(*) AS n FROM sqlite_schema`;\n    log('sqlite schema probe passed', {\n      schemaVersion: schemaVersion.schema_version,\n      objectCount: schemaCount.n,\n    });\n\n    if (RUN_SQLITE_QUICK_CHECK_ON_STARTUP) {\n      // NOTE: This is slow on non-trivial databases: O(dbSize).\n      log('starting sqlite quick_check');\n      const [result] = yield* sql<{ quick_check: string }>`PRAGMA quick_check`;\n      if (result.quick_check !== 'ok') {\n        throw new Error('SQLite quick check failed');\n      }\n      log('sqlite quick_check passed');\n    } else {\n      log('sqlite quick_check skipped');\n    }\n    log('sqlite health check complete');\n  });\n\n/**\n * Run {@link testSqlite} via the service runtime before hypercore feed storage opens.\n * Timeout is outside the Effect runtime to catch the layer hanging on startup.\n */\nexport const runSqliteHealthCheck = async (\n  runtime: RuntimeProvider.RuntimeProvider<SqlClient.SqlClient>,\n  options?: { timeoutMs?: number },\n): Promise<void> => {\n  const timeoutMs = options?.timeoutMs ?? SQLITE_HEALTH_CHECK_TIMEOUT_MS;\n  await asyncTimeout(\n    RuntimeProvider.runPromise(runtime)(testSqlite()),\n    timeoutMs,\n    new Error('SQLite health check timed out'),\n  );\n};\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport { cbor } from '@automerge/automerge-repo';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\n\nimport { Mutex, scheduleMicroTask, scheduleTask } from '@dxos/async';\nimport { Context, Resource } from '@dxos/context';\nimport { randomUUID } from '@dxos/crypto';\nimport type { CollectionId } from '@dxos/echo-protocol';\nimport {\n  type EdgeConnection,\n  EdgeConnectionService,\n  type EdgeHttpClient,\n  EdgeHttpClientService,\n} from '@dxos/edge-client';\nimport { invariant } from '@dxos/invariant';\nimport type { SpaceId } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport {\n  EdgeService,\n  MESSAGE_TYPE_COLLECTION_QUERY,\n  MESSAGE_TYPE_COLLECTION_STATE,\n  MESSAGE_TYPE_ERROR,\n  MESSAGE_TYPE_SUBDUCTION_BATCH,\n  MESSAGE_TYPE_SUBDUCTION_CONNECTION,\n  MESSAGE_TYPE_SUBDUCTION_FRAME,\n  type PeerId,\n  type SubductionBatchEnvelope,\n  type SubductionConnectionMessage,\n  type SubductionProtocolMessage,\n  type SubductionProtocolMessageEnveloped,\n} from '@dxos/protocols';\nimport { buf } from '@dxos/protocols/buf';\nimport { EdgeStatus_ConnectionState } from '@dxos/protocols/buf/dxos/client/services_pb';\nimport {\n  type Message as RouterMessage,\n  MessageSchema as RouterMessageSchema,\n} from '@dxos/protocols/buf/dxos/edge/messenger_pb';\nimport { trace } from '@dxos/tracing';\nimport { bufferToArray, compositeKey, markMilestone } from '@dxos/util';\n\nimport {\n  type AutomergeReplicatorConnection,\n  type AutomergeReplicatorContext,\n  type EdgeAutomergeReplicator,\n  EdgeAutomergeReplicatorService,\n  type ShouldAdvertiseProps,\n  type ShouldSyncCollectionProps,\n  getSpaceIdFromCollectionId,\n} from '../automerge/index.ts';\n\n/**\n * Delay before restarting the connection after the edge requests it.\n */\nconst INITIAL_RESTART_DELAY = 500;\nconst RESTART_DELAY_JITTER = 250;\nconst MAX_RESTART_DELAY = 5000;\n\n/**\n * Consecutive error signals answered by an in-place re-handshake before the connection is restarted\n * instead (DX-1275). Bounded so an edge that keeps refusing the rebound session cannot loop here.\n */\nexport const MAX_IN_PLACE_REHANDSHAKES = 3;\n\n/**\n * Outbound frame batching bounds (see `frame-batching-spec.md`). Subduction transport frames are\n * coalesced into one {@link SubductionBatchEnvelope}, flushed on whichever bound trips first:\n * {@link SUBDUCTION_BATCH_MAX_FRAMES} frames, {@link SUBDUCTION_BATCH_MAX_BYTES} accumulated, or\n * {@link SUBDUCTION_BATCH_MAX_DELAY_MS} elapsed. The byte cap is a hard safety bound well under\n * the 1 MB Cloudflare WebSocket message limit; count and delay tune coalescing vs latency.\n */\nconst SUBDUCTION_BATCH_MAX_FRAMES = 32;\nconst SUBDUCTION_BATCH_MAX_BYTES = 256 * 1024;\nconst SUBDUCTION_BATCH_MAX_DELAY_MS = 200;\n\nexport type EchoEdgeSubductionReplicatorProps = {\n  edgeConnection: EdgeConnection;\n  edgeHttpClient: EdgeHttpClient;\n  disableSharePolicy?: boolean;\n  /**\n   * Coalesce outbound subduction transport frames into batches (default enabled). Both peers\n   * accept single and batched frames; a mixed-version fleet can flip this off until the edge is\n   * deployed. See `frame-batching-spec.md`.\n   */\n  frameBatching?: boolean;\n};\n\n/**\n * Edge replicator for the Subduction transport.\n *\n * Subduction byte tunnel over the Edge router WebSocket. Every inbound router message\n * targeting the subduction service is forwarded verbatim to the local Repo via an\n * {@link AutomergeReplicatorConnection}. Outbound repo messages are wrapped in a router\n * frame and sent to the edge.\n *\n * No automerge-repo sync, collection-query/state, or rate-limiting runs through this class —\n * Subduction's sedimentree protocol replaces those responsibilities.\n */\nexport class EchoEdgeSubductionReplicator implements EdgeAutomergeReplicator {\n  private readonly _edgeConnection: EdgeConnection;\n  private readonly _edgeHttpClient: EdgeHttpClient;\n  /**\n   * Coordinates cross-space lifecycle (`connect`/`disconnect`/`_handleReconnect`)\n   * — operations that touch the entire `_connections` map atomically. Per-space\n   * operations use {@link _spaceMutex} instead, so a slow restart on space A\n   * cannot serialize behind / block `connectToSpace(B)`.\n   */\n  private readonly _mutex = new Mutex();\n  /**\n   * Per-space serialization for `connectToSpace`/`disconnectFromSpace` and the\n   * restart task fired from `onRestartRequested`. Restart tears down the WS\n   * subscription and runs a fresh SUH handshake against the edge (seconds of\n   * I/O), and under a single global mutex this blocked every other space's\n   * `host.spaces.create` → `connectToSpace` call, producing O(N) create-latency\n   * growth at space-creation boundaries. Per-space mutexes preserve the same-\n   * space serialization invariant (`_openConnection`'s `invariant(!_connections.has)`,\n   * single in-flight restart per space) without cross-space contention.\n   */\n  private readonly _spaceMutexes = new Map<SpaceId, Mutex>();\n  private readonly _disableSharePolicy: boolean;\n  private readonly _frameBatching: boolean;\n\n  private _ctx?: Context = undefined;\n  private _context: AutomergeReplicatorContext | null = null;\n  private _connectedSpaces = new Set<SpaceId>();\n  private _connections = new Map<SpaceId, EdgeSubductionReplicatorConnection>();\n  /** Whether the first space connection has been marked on the timeline. */\n  #replicationMarked = false;\n  /** Replaced connections whose async close is still settling; force-closed on disconnect. */\n  private readonly _closingConnections = new Set<EdgeSubductionReplicatorConnection>();\n\n  private _spaceMutex(spaceId: SpaceId): Mutex {\n    let mutex = this._spaceMutexes.get(spaceId);\n    if (!mutex) {\n      mutex = new Mutex();\n      this._spaceMutexes.set(spaceId, mutex);\n    }\n    return mutex;\n  }\n\n  constructor({\n    edgeConnection,\n    edgeHttpClient,\n    disableSharePolicy,\n    frameBatching,\n  }: EchoEdgeSubductionReplicatorProps) {\n    this._edgeConnection = edgeConnection;\n    this._edgeHttpClient = edgeHttpClient;\n    this._disableSharePolicy = disableSharePolicy ?? false;\n    this._frameBatching = frameBatching ?? true;\n  }\n\n  async connect(ctx: Context, context: AutomergeReplicatorContext): Promise<void> {\n    log('connecting...', { peerId: context.peerId, connectedSpaces: this._connectedSpaces.size });\n    this._context = context;\n    this._ctx = ctx.derive();\n    this._ctx.onDispose(\n      this._edgeConnection.onReconnected(\n        () => {\n          this._ctx && scheduleMicroTask(this._ctx, () => this._handleReconnect());\n        },\n        // Reconnect-reaction logic: reacting to the subscribe-time current-state firing would\n        // tear down and reopen connections that are already on the fresh WS.\n        { emitCurrentState: false },\n      ),\n    );\n  }\n\n  private async _handleReconnect(): Promise<void> {\n    using _guard = await this._mutex.acquire();\n\n    // Snapshot + tear down all existing connections in one pass. Per-space\n    // operations no longer share `_mutex` with us, so we acquire each\n    // `_spaceMutex` before touching its slot to avoid racing with a concurrent\n    // `connectToSpace`/`disconnectFromSpace`/restart-task for the same space.\n    const spaces = [...this._connectedSpaces];\n    for (const spaceId of spaces) {\n      using _spaceGuard = await this._spaceMutex(spaceId).acquire();\n      const connection = this._connections.get(spaceId);\n      if (connection) {\n        this._connections.delete(spaceId);\n        this._closeReplacedConnection(spaceId, connection);\n      }\n      if (this._context !== null && this._connectedSpaces.has(spaceId)) {\n        await this._openConnection(spaceId);\n      }\n    }\n  }\n\n  /**\n   * Close a replaced connection immediately. Closing before the successor binds lets\n   * `subduction_core` fail the connection's pending requests promptly (no sibling exists at\n   * removal), so in-flight rounds settle and re-drive on the fresh connection within\n   * milliseconds instead of riding the sync-round timeout.\n   */\n  private _closeReplacedConnection(spaceId: SpaceId, connection: EdgeSubductionReplicatorConnection): void {\n    this._closingConnections.add(connection);\n    const close = async () => {\n      if (this._closingConnections.delete(connection)) {\n        log('replaced connection closed', { spaceId });\n        await connection.close();\n      }\n    };\n    close().catch((err) => {\n      log.warn('replaced-connection close failed', { spaceId, err });\n      if (this._closingConnections.delete(connection)) {\n        void connection.close();\n      }\n    });\n  }\n\n  async disconnect(): Promise<void> {\n    using _guard = await this._mutex.acquire();\n    await this._ctx?.dispose();\n\n    for (const connection of this._connections.values()) {\n      await connection.close();\n    }\n    this._connections.clear();\n    for (const connection of this._closingConnections) {\n      await connection.close();\n    }\n    this._closingConnections.clear();\n  }\n\n  @trace.span({ showInBrowserTimeline: true })\n  async connectToSpace(ctx: Context, spaceId: SpaceId): Promise<void> {\n    log('connectToSpace', { spaceId });\n    using _guard = await this._spaceMutex(spaceId).acquire();\n\n    if (this._connectedSpaces.has(spaceId)) {\n      return;\n    }\n    this._connectedSpaces.add(spaceId);\n\n    if (this._context !== null) {\n      await this._openConnection(spaceId);\n    }\n  }\n\n  async disconnectFromSpace(spaceId: SpaceId): Promise<void> {\n    using _guard = await this._spaceMutex(spaceId).acquire();\n\n    this._connectedSpaces.delete(spaceId);\n\n    const connection = this._connections.get(spaceId);\n    if (connection) {\n      await connection.close();\n      this._connections.delete(spaceId);\n    }\n    // NOTE: do not delete from `_spaceMutexes`. A concurrent `connectToSpace`\n    // that arrived while we held the mutex is parked on this exact instance\n    // and would otherwise race against a fresh mutex created by a later\n    // caller. The map entries are bounded by the live space set, so the\n    // residual cost is one Mutex per ever-connected space.\n  }\n\n  private async _openConnection(spaceId: SpaceId, reconnects: number = 0): Promise<void> {\n    invariant(this._context);\n    invariant(!this._connections.has(spaceId));\n\n    // Opening while the edge WS is down (or mid-restart, e.g. right after an identity change)\n    // would handshake a connection that the reconnect handler immediately restarts. The edge\n    // then supersedes that session the moment the replacement handshake arrives, and sync\n    // requests racing the supersede are silently swallowed inside `subduction_core`\n    // (`remove_connection` detaches the peer's muxes with no notification to the requester),\n    // costing a full sync-round timeout. The space is already registered in `_connectedSpaces`,\n    // so `_handleReconnect` opens this connection once the socket is actually ready.\n    if (this._edgeConnection.status.state !== EdgeStatus_ConnectionState.CONNECTED) {\n      log('deferring subduction connection until edge ws is ready', { spaceId });\n      return;\n    }\n\n    let restartScheduled = false;\n\n    const connection = new EdgeSubductionReplicatorConnection({\n      edgeConnection: this._edgeConnection,\n      spaceId,\n      context: this._context,\n      sharedPolicyEnabled: !this._disableSharePolicy,\n      frameBatching: this._frameBatching,\n      onRemoteConnected: async () => {\n        log.trace('dxos.echo.edge.subduction-replicator.onRemoteConnected', { spaceId });\n        if (!this.#replicationMarked) {\n          this.#replicationMarked = true;\n          markMilestone('replication.connected', spaceId);\n        }\n        this._context?.onConnectionOpen(connection);\n      },\n      onRemoteDisconnected: async () => {\n        log.trace('dxos.echo.edge.subduction-replicator.onRemoteDisconnected', { spaceId });\n        this._context?.onConnectionClosed(connection);\n      },\n      onRestartRequested: async () => {\n        if (!this._ctx || restartScheduled) {\n          return;\n        }\n\n        const restartDelay =\n          Math.min(MAX_RESTART_DELAY, INITIAL_RESTART_DELAY * reconnects) + Math.random() * RESTART_DELAY_JITTER;\n\n        log('connection restart scheduled', { spaceId, reconnects, restartDelay });\n\n        restartScheduled = true;\n        scheduleTask(\n          this._ctx!,\n          async () => {\n            // Per-space mutex (not the global `_mutex`) — the restart's heavy\n            // I/O (`close()` + fresh SUH handshake on `open()`) must not block\n            // `connectToSpace`/`disconnectFromSpace` for other spaces, which\n            // was the O(N) create-latency cliff at space-creation boundaries.\n            using _guard = await this._spaceMutex(spaceId).acquire();\n            if (this._connections.get(spaceId) !== connection) {\n              return;\n            }\n\n            const ctx = this._ctx;\n            this._connections.delete(spaceId);\n            this._closeReplacedConnection(spaceId, connection);\n            if (ctx?.disposed) {\n              return;\n            }\n            log.trace('dxos.echo.edge.subduction-replicator.restart', { spaceId, reconnects, restartDelay });\n            await this._openConnection(spaceId, reconnects + 1);\n          },\n          restartDelay,\n        );\n      },\n    });\n    this._connections.set(spaceId, connection);\n\n    await connection.open();\n  }\n}\n\ntype EdgeSubductionReplicatorConnectionProps = {\n  edgeConnection: EdgeConnection;\n  spaceId: SpaceId;\n  context: AutomergeReplicatorContext;\n  sharedPolicyEnabled: boolean;\n  frameBatching: boolean;\n  onRemoteConnected: () => Promise<void>;\n  onRemoteDisconnected: () => Promise<void>;\n  onRestartRequested: () => Promise<void>;\n};\n\nclass EdgeSubductionReplicatorConnection extends Resource implements AutomergeReplicatorConnection {\n  private readonly _connectionId = randomUUID();\n\n  /** Timestamp of the last inbound frame consumed by this connection. Diagnostic only. */\n  lastInboundAt = Date.now();\n  private readonly _edgeConnection: EdgeConnection;\n  private readonly _remotePeerId: string;\n  private readonly _subductionServiceId: string;\n  private readonly _spaceId: SpaceId;\n  private readonly _context: AutomergeReplicatorContext;\n  private readonly _sharedPolicyEnabled: boolean;\n  private readonly _onRemoteConnected: () => Promise<void>;\n  private readonly _onRemoteDisconnected: () => Promise<void>;\n  private readonly _onRestartRequested: () => void;\n  private readonly _frameBatching: boolean;\n\n  // Outbound batching state. `#pending` holds encoded-size-tracked inner frames awaiting a\n  // flush; `#firstFrameSent` sends the handshake (first frame) alone, see `_sendMessage`;\n  // `#inFlightFlush` bounds buffering to one flush at a time so a slow socket cannot grow the\n  // buffer without applying write backpressure.\n  #pendingFrames: SubductionConnectionMessage[] = [];\n  #pendingBytes = 0;\n  #flushTimer?: ReturnType<typeof setTimeout>;\n  #firstFrameSent = false;\n  #inFlightFlush?: Promise<void>;\n\n  /** Error signals answered in place since the last inbound frame; see {@link MAX_IN_PLACE_REHANDSHAKES}. */\n  #inPlaceRehandshakes = 0;\n\n  private _readableStreamController!: ReadableStreamDefaultController<SubductionProtocolMessage>;\n\n  public readable: ReadableStream<SubductionProtocolMessage>;\n  public writable: WritableStream<SubductionProtocolMessage>;\n\n  constructor({\n    edgeConnection,\n    spaceId,\n    context,\n    sharedPolicyEnabled,\n    frameBatching,\n    onRemoteConnected,\n    onRemoteDisconnected,\n    onRestartRequested,\n  }: EdgeSubductionReplicatorConnectionProps) {\n    super();\n    this._edgeConnection = edgeConnection;\n    this._spaceId = spaceId;\n    this._context = context;\n    this._sharedPolicyEnabled = sharedPolicyEnabled;\n    this._frameBatching = frameBatching;\n    // Generate a unique peer id for every connection so sync-state is fresh on reconnect.\n    this._subductionServiceId = compositeKey(EdgeService.SUBDUCTION_REPLICATOR, spaceId);\n    this._remotePeerId = `${this._subductionServiceId}-${this._connectionId}`;\n    this._onRemoteConnected = onRemoteConnected;\n    this._onRemoteDisconnected = onRemoteDisconnected;\n    this._onRestartRequested = onRestartRequested;\n\n    this.readable = new ReadableStream<SubductionProtocolMessage>({\n      start: (controller) => {\n        this._readableStreamController = controller;\n      },\n    });\n\n    this.writable = new WritableStream<SubductionProtocolMessage>({\n      write: async (message: SubductionProtocolMessage) => {\n        await this._sendMessage(this._ctx, message);\n      },\n    });\n  }\n\n  protected override async _open(ctx: Context): Promise<void> {\n    log('opening...');\n\n    this._ctx.onDispose(\n      this._edgeConnection.onMessage((msg: RouterMessage) => {\n        this._onMessage(msg);\n      }),\n    );\n\n    this._ctx.onDispose(\n      this._edgeConnection.onReconnected(\n        async () => {\n          // Every WS (re-)establishment after this session started runs the full restart cycle:\n          // close this connection (emitting peer-disconnected for its peer id) and open a fresh\n          // one under a new connectionId. `emitCurrentState: false` is essential: the default\n          // subscribe-time firing would restart the connection that was just created, and each\n          // restart re-subscribes — an unbounded restart loop.\n          this._onRestartRequested();\n        },\n        { emitCurrentState: false },\n      ),\n    );\n\n    await this._onRemoteConnected();\n  }\n\n  protected override async _close(ctx: Context): Promise<void> {\n    log('closing...');\n    // Flush buffered frames before teardown so nothing is lost on a close mid-batch.\n    await this.#flushPendingFrames();\n    this._readableStreamController.close();\n    await this._onRemoteDisconnected();\n  }\n\n  get peerId(): string {\n    return this._remotePeerId;\n  }\n\n  async shouldAdvertise(params: ShouldAdvertiseProps): Promise<boolean> {\n    if (!this._sharedPolicyEnabled) {\n      log.verbose('share policy probe', { documentId: params.documentId, allow: true, reason: 'policy-disabled' });\n      return true;\n    }\n    const spaceId = await this._context.getContainingSpaceIdForDocument(params.documentId);\n    if (!spaceId) {\n      const remoteDocumentExists = await this._context.isDocumentInRemoteCollection({\n        documentId: params.documentId,\n        peerId: this._remotePeerId as PeerId,\n      });\n      log.verbose('document not found locally for share policy check', {\n        documentId: params.documentId,\n        acceptDocument: remoteDocumentExists,\n        remoteId: this._remotePeerId,\n      });\n      // If a document is not present locally return true only if it already exists on edge.\n      return remoteDocumentExists;\n    }\n    // `reason` separates the expected cross-space denial — which fans out across every\n    // space-scoped peer each sync round — from a same-space document being wrongly refused.\n    const allow = spaceId === this._spaceId;\n    log.verbose('share policy probe', {\n      documentId: params.documentId,\n      allow,\n      reason: allow ? 'same-space' : 'cross-space',\n      documentSpaceId: spaceId,\n      connectionSpaceId: this._spaceId,\n    });\n    return allow;\n  }\n\n  shouldSyncCollection(params: ShouldSyncCollectionProps): boolean {\n    if (!this._sharedPolicyEnabled) {\n      return true;\n    }\n    const spaceId = getSpaceIdFromCollectionId(params.collectionId as CollectionId);\n    // Only sync collections of form `space:id:rootDoc`; edge ignores legacy `space:id` collections.\n    return spaceId === this._spaceId && params.collectionId.split(':').length === 3;\n  }\n\n  private _onMessage(message: RouterMessage): void {\n    if (message.serviceId !== this._subductionServiceId) {\n      return;\n    }\n\n    let payload: SubductionProtocolMessageEnveloped;\n    try {\n      payload = cbor.decode(message.payload!.value) as SubductionProtocolMessageEnveloped;\n    } catch (err) {\n      log.warn('failed to decode subduction envelope', { err });\n      return;\n    }\n    // Defensive validation: cbor.decode returns untrusted bytes. Drop malformed\n    // envelopes before touching `payload.type` / `payload.subductionFrame`.\n    if (payload === null || typeof payload !== 'object' || typeof (payload as { type?: unknown }).type !== 'string') {\n      log.warn('dropping malformed subduction envelope', { payload });\n      return;\n    }\n\n    switch (payload.type) {\n      case MESSAGE_TYPE_ERROR: {\n        // Edge → client restart signal for a specific connection lifetime.\n        // Match the edge-supplied `connectionId` against our local\n        // `_connectionId` and tear down only on an exact match; mismatches\n        // (or absent ids) refer to a sibling/prior connection and must be\n        // ignored.\n        if (payload.connectionId === undefined) {\n          log.verbose('dropping error without connectionId', { message: payload.message });\n          return;\n        }\n        if (payload.connectionId !== this._connectionId) {\n          log.verbose('dropping error for different connection', {\n            expected: this._connectionId,\n            got: payload.connectionId,\n          });\n          return;\n        }\n        // The edge lost the session, not the link: re-running the handshake here keeps the peer id\n        // and every piece of sync state keyed by it. Verbose because the edge recycles an active\n        // space's instance every 15-25 s (DX-1275); the restart fallback below stays at info.\n        if (this.#inPlaceRehandshakes < MAX_IN_PLACE_REHANDSHAKES && this._context.onConnectionTransportReset(this)) {\n          this.#discardPendingFrames();\n          this.#inPlaceRehandshakes++;\n          log.verbose('received subduction error; re-handshaking in place', {\n            message: payload.message,\n            attempt: this.#inPlaceRehandshakes,\n          });\n          return;\n        }\n        log.info('received subduction error; restarting', {\n          message: payload.message,\n          inPlaceRehandshakes: this.#inPlaceRehandshakes,\n        });\n        this._onRestartRequested();\n        return;\n      }\n      case MESSAGE_TYPE_SUBDUCTION_FRAME: {\n        // The edge echoes the client-supplied connectionId. Frames carrying a\n        // different id are leftovers from a previous connection lifetime\n        // (rotated by `_onRestartRequested`) and must be dropped.\n        if (payload.connectionId !== this._connectionId) {\n          log.verbose('dropping subduction-frame for different connection', {\n            expected: this._connectionId,\n            got: payload.connectionId,\n          });\n          return;\n        }\n        const inner = payload.subductionFrame;\n        if (inner === null || typeof inner !== 'object') {\n          log.warn('dropping subduction-frame with missing inner frame', { payload });\n          return;\n        }\n        log.verbose('received subduction frame', { remoteId: this._remotePeerId });\n        this.#onInboundFrame();\n        // Fix the peer id so subduction routing inside the Repo accepts the frame.\n        inner.senderId = this._remotePeerId as PeerId;\n        this._readableStreamController.enqueue(inner);\n        return;\n      }\n      case MESSAGE_TYPE_SUBDUCTION_BATCH: {\n        // Batched counterpart of MESSAGE_TYPE_SUBDUCTION_FRAME: same connectionId gate, then\n        // enqueue every inner frame in array order so the subduction byte stream stays FIFO.\n        if (payload.connectionId !== this._connectionId) {\n          log.verbose('dropping subduction-batch for different connection', {\n            expected: this._connectionId,\n            got: payload.connectionId,\n          });\n          return;\n        }\n        if (!Array.isArray(payload.frames)) {\n          log.warn('dropping subduction-batch with missing frames', { payload });\n          return;\n        }\n        log.verbose('received subduction batch', { frames: payload.frames.length, remoteId: this._remotePeerId });\n        let enqueued = 0;\n        for (const inner of payload.frames) {\n          if (inner === null || typeof inner !== 'object') {\n            continue;\n          }\n          inner.senderId = this._remotePeerId as PeerId;\n          this._readableStreamController.enqueue(inner);\n          enqueued++;\n        }\n        // Counted, not assumed: an empty or malformed batch must not refill the budget.\n        if (enqueued > 0) {\n          this.#onInboundFrame();\n        }\n        return;\n      }\n      case MESSAGE_TYPE_COLLECTION_STATE: {\n        // The state shape is implementation-defined and arrives from remote CBOR; every level must\n        // be validated so a malformed frame degrades the diagnostic instead of throwing mid-dispatch.\n        const state = payload.state;\n        const documents =\n          state !== null && typeof state === 'object' && 'documents' in state ? state.documents : undefined;\n        const documentCount =\n          documents !== null && typeof documents === 'object' ? Object.keys(documents).length : undefined;\n        log.verbose('received collection-state', {\n          collectionId: payload.collectionId,\n          documentCount,\n          remoteId: this._remotePeerId,\n        });\n        payload.senderId = this._remotePeerId as PeerId;\n        this._readableStreamController.enqueue(payload);\n        return;\n      }\n      case MESSAGE_TYPE_COLLECTION_QUERY:\n        // Invariant (not expressed in the protocol union): collection state flows edge → client\n        // only; the edge never queries the client's collection state. An inbound query means a\n        // protocol violation or a misbehaving peer, so surface it loudly instead of answering.\n        throw new Error(\n          `collection-query from edge is not supported (collectionId: ${payload.collectionId}, remoteId: ${this._remotePeerId})`,\n        );\n      default: {\n        const _exhaustive: never = payload;\n        log.warn('unknown subduction protocol message', { payload: _exhaustive });\n      }\n    }\n  }\n\n  private async _sendMessage(ctx: Context, message: SubductionProtocolMessage): Promise<void> {\n    switch (message.type) {\n      case MESSAGE_TYPE_SUBDUCTION_CONNECTION: {\n        message.targetId = this._subductionServiceId as PeerId;\n        if (!this._frameBatching) {\n          await this.#sendEnveloped({\n            type: MESSAGE_TYPE_SUBDUCTION_FRAME,\n            connectionId: this._connectionId,\n            subductionFrame: message,\n          });\n          return;\n        }\n        // The handshake goes alone, so the edge starts the session from it, and in a batch envelope,\n        // because the edge relays its replies one router message per frame until this connection has\n        // sent it a batch.\n        if (!this.#firstFrameSent) {\n          this.#firstFrameSent = true;\n          await this.#sendEnveloped({\n            type: MESSAGE_TYPE_SUBDUCTION_BATCH,\n            connectionId: this._connectionId,\n            frames: [message],\n          });\n          return;\n        }\n        this.#enqueueFrame(message);\n        // If a flush is already in flight and another full batch is queued behind it, apply\n        // write backpressure so a slow socket cannot grow the buffer without bound.\n        if (this.#inFlightFlush && this.#pendingFrames.length >= SUBDUCTION_BATCH_MAX_FRAMES) {\n          await this.#inFlightFlush;\n        }\n        return;\n      }\n      case MESSAGE_TYPE_COLLECTION_QUERY:\n      case MESSAGE_TYPE_COLLECTION_STATE:\n        message.targetId = this._subductionServiceId as PeerId;\n        // Preserve send order: any buffered transport frames must reach the edge before this\n        // control-plane message.\n        await this.#flushPendingFrames();\n        await this.#sendEnveloped(message);\n        return;\n      case MESSAGE_TYPE_ERROR:\n        // Edge → client only; the client never originates an error on the subduction channel.\n        log.warn('dropping unexpected error outbound', { message: message.message });\n        return;\n      default: {\n        const _exhaustive: never = message;\n        log.warn('dropping unexpected message type on subduction channel', {\n          type: (_exhaustive as { type: string }).type,\n        });\n        return;\n      }\n    }\n  }\n\n  /** A frame arrived, so the session behind this connection works: clear the re-handshake budget. */\n  #onInboundFrame(): void {\n    this.lastInboundAt = Date.now();\n    this.#inPlaceRehandshakes = 0;\n  }\n\n  /**\n   * Drop what is buffered for a session that no longer exists, and let the next frame ship alone:\n   * flushing stale `SUM` bytes after a rebind would reach the fresh transport mid-handshake.\n   */\n  #discardPendingFrames(): void {\n    if (this.#flushTimer !== undefined) {\n      clearTimeout(this.#flushTimer);\n      this.#flushTimer = undefined;\n    }\n    this.#pendingFrames = [];\n    this.#pendingBytes = 0;\n    this.#firstFrameSent = false;\n  }\n\n  /** Buffer an inner frame for the next batch flush, arming the delay timer / tripping bounds. */\n  #enqueueFrame(frame: SubductionConnectionMessage): void {\n    this.#pendingFrames.push(frame);\n    this.#pendingBytes += frame.data.byteLength;\n    if (this.#pendingFrames.length >= SUBDUCTION_BATCH_MAX_FRAMES || this.#pendingBytes >= SUBDUCTION_BATCH_MAX_BYTES) {\n      void this.#flushPendingFrames();\n    } else if (this.#flushTimer === undefined) {\n      this.#flushTimer = setTimeout(() => {\n        this.#flushTimer = undefined;\n        void this.#flushPendingFrames();\n      }, SUBDUCTION_BATCH_MAX_DELAY_MS);\n    }\n  }\n\n  /** Send all buffered frames as one batch (or a single-frame envelope for the degenerate case). */\n  async #flushPendingFrames(): Promise<void> {\n    if (this.#flushTimer !== undefined) {\n      clearTimeout(this.#flushTimer);\n      this.#flushTimer = undefined;\n    }\n    if (this.#pendingFrames.length === 0) {\n      return;\n    }\n    const frames = this.#pendingFrames;\n    this.#pendingFrames = [];\n    this.#pendingBytes = 0;\n    const wire: SubductionProtocolMessageEnveloped =\n      frames.length === 1\n        ? { type: MESSAGE_TYPE_SUBDUCTION_FRAME, connectionId: this._connectionId, subductionFrame: frames[0] }\n        : { type: MESSAGE_TYPE_SUBDUCTION_BATCH, connectionId: this._connectionId, frames };\n    const flush = this.#sendEnveloped(wire, frames.length);\n    // Track a single in-flight flush; chain a follow-up if frames accumulated during this send.\n    this.#inFlightFlush = flush.finally(() => {\n      this.#inFlightFlush = undefined;\n      if (this.#pendingFrames.length > 0) {\n        void this.#flushPendingFrames();\n      }\n    });\n    await flush;\n  }\n\n  /** Encode one wire envelope and send it as a single router message. */\n  async #sendEnveloped(wire: SubductionProtocolMessageEnveloped, frameCount = 1): Promise<void> {\n    if (wire.type === MESSAGE_TYPE_COLLECTION_QUERY || wire.type === MESSAGE_TYPE_COLLECTION_STATE) {\n      log.verbose(`sending ${wire.type}`, {\n        collectionId: wire.collectionId,\n        serviceId: this._subductionServiceId,\n        remoteId: this._remotePeerId,\n      });\n    } else {\n      log.verbose('sending...', { type: wire.type, frameCount, remoteId: this._remotePeerId });\n    }\n\n    const encoded = cbor.encode(wire);\n    try {\n      await this._edgeConnection.send(\n        this._ctx,\n        buf.create(RouterMessageSchema, {\n          serviceId: this._subductionServiceId,\n          source: {\n            identityDid: this._edgeConnection.identityDid,\n            peerKey: this._edgeConnection.peerKey,\n          },\n          payload: { value: bufferToArray(encoded) },\n        }),\n      );\n    } catch (err) {\n      log.error('failed to send message', { err });\n    }\n  }\n}\n\nexport type EchoEdgeSubductionReplicatorLayerOptions = Pick<EchoEdgeSubductionReplicatorProps, 'disableSharePolicy'>;\n\n/**\n * Effect Layer constructing an {@link EchoEdgeSubductionReplicator}.\n */\nexport const EchoEdgeSubductionReplicatorLayer = (\n  options: EchoEdgeSubductionReplicatorLayerOptions = {},\n): Layer.Layer<EdgeAutomergeReplicatorService, never, EdgeConnectionService | EdgeHttpClientService> =>\n  Layer.effect(\n    EdgeAutomergeReplicatorService,\n    Effect.gen(function* () {\n      const edgeConnection = yield* EdgeConnectionService;\n      const edgeHttpClient = yield* EdgeHttpClientService;\n      return new EchoEdgeSubductionReplicator({\n        edgeConnection,\n        edgeHttpClient,\n        disableSharePolicy: options.disableSharePolicy,\n      });\n    }),\n  );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,IAAa,WAAW,aAA4C,UAClE,gBAAgB,KAAA,KAAa,UAAU,aAAa,KAAK;AAE3D,IAAa,aAAa,MAAyB,UACjD,KAAK,WAAW,MAAM,UAAU,KAAK,OAAO,SAAS,MAAM,SAAS,IAAI,CAAC;;;;ACI3E,IAAa,kBAAkB,SAC7B,KAAK,OAAO,IACR;CACE,KAAK,KAAK;CACV,QAAQ;CACR,MAAM,KAAK,OAAO;CAClB,OAAO,KAAK;CACZ,KAAK,KAAK;CACV,KAAK,KAAK,QAAQ,KAAK,UAAU;AACnC,IACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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