diff --git a/docs/contracts/coordinator-project-moves.md b/docs/contracts/coordinator-project-moves.md index 8b7f98faa..b0e47dcb5 100644 --- a/docs/contracts/coordinator-project-moves.md +++ b/docs/contracts/coordinator-project-moves.md @@ -157,10 +157,36 @@ nobody at the switch: `GET /v1/project-moves?group_id=`, signed by an enrolled device of the group, answers `{ "moves": [ … ] }` with every logged move of the group, oldest -first. A device maps a Project to a boundary only when a logged move names a -scope that holds the Project's memories as `source_scope_id`, the boundary ID -it derives for that Project equals `boundary_scope_id`, and its membership cache -shows it authorized in the boundary. It then moves only the memories it wrote -itself. A device that was offline during the move moves when it next refreshes. +first. A device records moves for boundaries it can access, even when it has +no Project mapping. Snapshots and incremental updates in either scope use the +same rule: when the device holds one non-private copy with the same memory key +and stored origin, it keeps the newest revision under the boundary. A recorded +author that conflicts with the stored origin prevents this reconciliation. +An empty origin or the legacy `local` value cannot identify an author. +If a legacy snapshot omits the origin, the serving device can stand in for +the creator only when the receiver already verified that device created the +memory. The older scope's snapshot rules otherwise apply. +If the device pulled both copies before seeing the move, it compares them when +it records the move. An older-scope arrival can identify its boundary only +when the boundary already holds that memory. Ambiguous arrivals update only +their own scope. +`codemem sync duplicates` lists copies that still share a memory key. + +A delete targets an attributed copy only when the authenticated sender created +it or the coordinator's retained proofs bind both devices to the same identity +in the copy's scope. The ordinary delete rules still apply to unattributed +copies. + +A device remaps a Project only when it still maps to the move's source scope +and the derived boundary ID matches. It then restamps only memories it wrote +itself. A device that was offline during the move learns of it when it next +refreshes. + +Before restamping, a device saves one private SQLite backup beside its store +as `.before-project-moves.sqlite` and syncs the file and its parent +directory to disk. A backup failure leaves all source memories in place. +codemem keeps this backup until you remove it. Run +`codemem sync migration status` to see the backup path and size, and how many +rows still carry each older scope on this device. The TypeScript types are in `packages/core/src/coordinator-project-moves.ts`. diff --git a/docs/coordinator-discovery.md b/docs/coordinator-discovery.md index 5777383df..b4839ba43 100644 --- a/docs/coordinator-discovery.md +++ b/docs/coordinator-discovery.md @@ -76,13 +76,16 @@ Backward compatibility: ### Boundary migration rollout setting -`sync_boundary_migration` has the environment override -`CODEMEM_SYNC_BOUNDARY_MIGRATION` and defaults to `off`. +`sync_boundary_migration=on` enables Project moves and advertises support for +them in coordinator presence. It defaults to `off` and can be overridden with +`CODEMEM_SYNC_BOUNDARY_MIGRATION`. With migration off, the device still records +moves so it can reconcile received copies, but it does not remap Projects or +restamp memories it authored. | Value | `codemem sync migration status` behavior | | --- | --- | | `off` | Report that the migration is off. | -| `report`, `on` | Read the local database and report Project candidates and filter evidence. Neither setting starts a migration. | +| `report`, `on` | Read the local database and report Project candidates and filter evidence. The report itself never starts a move. | Use `--json` for counts or `--db-path` and `--config` to inspect a particular install. The report sends no requests and does not change sharing or advertise readiness. A diff --git a/packages/cli/src/commands/sync-migration.test.ts b/packages/cli/src/commands/sync-migration.test.ts index 15d97fdd1..ae904d036 100644 --- a/packages/cli/src/commands/sync-migration.test.ts +++ b/packages/cli/src/commands/sync-migration.test.ts @@ -56,6 +56,7 @@ it("distinguishes a fresh peer install from a configured coordinator that cannot maintenance_window: expect.stringContaining("stop every client"), storage_fence: expect.stringContaining("does not erase data from disk"), projects: null, + adopted_sources: [], }); expect(fetch).not.toHaveBeenCalled(); }); @@ -73,6 +74,26 @@ it("does not create a missing database or classify a damaged config as peer-only expect(process.exitCode).toBe(1); }); +it("reports the local backup path and byte size even when migration reporting is off", async () => { + connect(dbPath).close(); + vi.stubEnv("CODEMEM_SYNC_BOUNDARY_MIGRATION", "off"); + const backup = `${dbPath}.before-project-moves.sqlite`; + writeFileSync(backup, "fixture", { mode: 0o600 }); + const output = vi.spyOn(process.stdout, "write").mockReturnValue(true); + + await status(); + expect(JSON.parse(String(output.mock.calls.at(-1)?.[0]))).toMatchObject({ + backup: { path: backup, size_bytes: 7 }, + }); + await buildSyncMigrationCommand().parseAsync( + ["status", "--db-path", dbPath, "--config", configPath], + { from: "user" }, + ); + expect(output.mock.calls.map(([chunk]) => String(chunk)).join("")).toContain( + `${backup} (7 bytes)`, + ); +}); + it("tells the person in text what the storage fence does not erase and how to recover", async () => { connect(dbPath).close(); writeFileSync( diff --git a/packages/cli/src/commands/sync-migration.ts b/packages/cli/src/commands/sync-migration.ts index 9837d72d9..578dc00bc 100644 --- a/packages/cli/src/commands/sync-migration.ts +++ b/packages/cli/src/commands/sync-migration.ts @@ -19,10 +19,19 @@ import { resolveDbOpt, } from "../shared-options.js"; +function sourceRowsText(rows: Array<{ source_scope_id: string; remaining_rows: number }> = []) { + return rows + .map( + ({ source_scope_id, remaining_rows }) => + `${source_scope_id}: ${remaining_rows} rows still in the older scope.`, + ) + .join("\n"); +} + function reportText(report: ReturnType): string { switch (report.state) { case "off": - return "Project migration reporting is off."; + return sourceRowsText(report.adopted_sources) || "Project migration reporting is off."; case "not_applicable": return "This device uses basic peer sync. No Project migration is needed."; case "waiting_for_coordinator": @@ -32,7 +41,15 @@ function reportText(report: ReturnType): const observed = counts ? `Project candidates: ${counts.candidate_projects}. Projects in multiple setups: ${counts.multiple_sources}. Locally authored rows in those setups: ${counts.own_source_rows}.` : "The local Project inventory is unavailable."; - return `${observed}\nLocal filter evidence: ${report.local_filters}. Other devices have not been checked.\n${report.maintenance_window}\n${report.storage_fence}`; + return [ + observed, + sourceRowsText(report.adopted_sources), + `Local filter evidence: ${report.local_filters}. Other devices have not been checked.`, + report.maintenance_window, + report.storage_fence, + ] + .filter(Boolean) + .join("\n"); } } } @@ -55,7 +72,16 @@ function migrationStatus(opts: DbOpts & ConfigOpts & JsonOpts) { config.status === "valid" ? config.data : {}, ); if (opts.json) process.stdout.write(`${JSON.stringify(report)}\n`); - else p.log.info(reportText(report)); + else + p.log.info( + [ + reportText(report), + report.backup && + `Project migration backup: ${report.backup.path} (${report.backup.size_bytes} bytes).`, + ] + .filter(Boolean) + .join("\n"), + ); } finally { db.close(); } diff --git a/packages/core/src/boundary-migration-config.test.ts b/packages/core/src/boundary-migration-config.test.ts index c1ad5ca90..392f48d6f 100644 --- a/packages/core/src/boundary-migration-config.test.ts +++ b/packages/core/src/boundary-migration-config.test.ts @@ -1,5 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { readBoundaryMigrationMode } from "./coordinator-sync-config.js"; +import { coordinatorPresenceSyncFeatures } from "./coordinator-runtime.js"; +import { readBoundaryMigrationMode, readCoordinatorSyncConfig } from "./coordinator-sync-config.js"; import { getCodememEnvOverrides } from "./observer-config.js"; import { LOCAL_SYNC_FEATURES, supportsSyncFeature } from "./sync-capability.js"; @@ -44,13 +45,17 @@ describe("the boundary migration rollout mode", () => { expect(getCodememEnvOverrides().sync_boundary_migration).toBeUndefined(); }); - it("recognizes the move feature without advertising it before the mover exists", () => { - vi.stubEnv("CODEMEM_SYNC_BOUNDARY_MIGRATION", "on"); - - expect(readBoundaryMigrationMode({})).toBe("on"); + it("recognizes Project move capability advertised by a peer", () => { expect( supportsSyncFeature(["project_boundary_migration_v1"], "project_boundary_migration_v1"), ).toBe(true); - expect(LOCAL_SYNC_FEATURES).not.toContain("project_boundary_migration_v1"); + }); + + it("advertises supported Project moves in coordinator presence only when enabled", () => { + const feature = "project_boundary_migration_v1"; + const enabled = readCoordinatorSyncConfig({ sync_boundary_migration: "on" }); + expect(coordinatorPresenceSyncFeatures(readCoordinatorSyncConfig({}), [feature])).toEqual([]); + expect(coordinatorPresenceSyncFeatures(enabled, [])).toEqual([]); + expect(coordinatorPresenceSyncFeatures(enabled, LOCAL_SYNC_FEATURES)).toContain(feature); }); }); diff --git a/packages/core/src/coordinator-runtime.test.ts b/packages/core/src/coordinator-runtime.test.ts index 7a024812e..9dcc56f38 100644 --- a/packages/core/src/coordinator-runtime.test.ts +++ b/packages/core/src/coordinator-runtime.test.ts @@ -25,6 +25,7 @@ import { readCoordinatorSyncConfig, refreshAuthorizedCoordinatorPeerTrust, refreshStoredCoordinatorPeerAddresses, + registerCoordinatorPresence, revokeUnauthorizedCoordinatorPeerTrust, trustCoordinatorPeersWithSharedManagedScopes, } from "./coordinator-runtime.js"; @@ -50,6 +51,39 @@ const EXPECTED_PRESENCE_CAPABILITIES = { transport_statement: { payload: expect.any(String), signature: expect.any(String) }, }; +it.each(["off", "on"] as const)( + "posts the Project move feature correctly when migration is %s", + async (mode) => { + const keysDir = mkdtempSync(join(tmpdir(), "project-move-presence-")); + const db = new Database(":memory:"); + vi.stubEnv("CODEMEM_SYNC_BOUNDARY_MIGRATION", undefined); + const post = vi.spyOn(globalThis, "fetch").mockResolvedValue(Response.json({})); + try { + initTestSchema(db); + await registerCoordinatorPresence( + { db, dbPath: ":memory:" }, + readCoordinatorSyncConfig({ + sync_coordinator_url: "https://coord.example.test", + sync_coordinator_group: "team-a", + sync_boundary_migration: mode, + }), + { keysDir }, + ); + const request = post.mock.calls.find(([url]) => String(url).endsWith("/v1/presence")); + expect(request).toBeDefined(); + const body = JSON.parse(Buffer.from(request?.[1]?.body as Uint8Array).toString("utf8")); + expect(body.capabilities.sync_features.includes("project_boundary_migration_v1")).toBe( + mode === "on", + ); + } finally { + post.mockRestore(); + vi.unstubAllEnvs(); + db.close(); + rmSync(keysDir, { recursive: true, force: true }); + } + }, +); + describe("readCoordinatorSyncConfig.syncOpsLimit", () => { afterEach(() => { delete process.env.CODEMEM_SYNC_OPS_LIMIT; diff --git a/packages/core/src/coordinator-runtime.ts b/packages/core/src/coordinator-runtime.ts index e77b04307..743320e3c 100644 --- a/packages/core/src/coordinator-runtime.ts +++ b/packages/core/src/coordinator-runtime.ts @@ -16,6 +16,7 @@ import { type PeerRemovalLookup, type PeerRevocationCheckStatus, } from "./coordinator-peer-revocation.js"; +import { PROJECT_MOVE_SYNC_FEATURE } from "./coordinator-project-moves.js"; import { clearCoordinatorDeviceRemoved, recordCoordinatorDeviceRemoved, @@ -41,7 +42,7 @@ import { import { getEffectiveCachedScopeAuthorization } from "./scope-membership-cache.js"; import type { MemoryStore } from "./store.js"; import { buildAuthHeaders } from "./sync-auth.js"; -import { LOCAL_SYNC_CAPABILITY, LOCAL_SYNC_FEATURES } from "./sync-capability.js"; +import { LOCAL_SYNC_CAPABILITY, LOCAL_SYNC_FEATURES, type SyncFeature } from "./sync-capability.js"; import { fingerprintPublicKey } from "./sync-fingerprint.js"; import { buildBaseUrl, requestJson } from "./sync-http-client.js"; import { ensureDeviceIdentity, loadPrivateKey, loadPublicKey } from "./sync-identity.js"; @@ -142,6 +143,7 @@ function presenceCacheKey(store: PresenceStoreLike, config: CoordinatorSyncConfi config.syncPort, config.syncAdvertise, config.syncCoordinatorPresenceTtlS, + config.syncBoundaryMigrationEnabled === true, ].join("|"); } @@ -263,6 +265,15 @@ export function advertisedSyncAddresses(config: CoordinatorSyncConfig): string[] return [...new Set(addresses)]; } +export function coordinatorPresenceSyncFeatures( + config: Pick, + features: readonly SyncFeature[] = LOCAL_SYNC_FEATURES, +): readonly SyncFeature[] { + return config.syncBoundaryMigrationEnabled + ? features + : features.filter((feature) => feature !== PROJECT_MOVE_SYNC_FEATURE); +} + export async function registerCoordinatorPresence( store: PresenceStoreLike, config: CoordinatorSyncConfig, @@ -285,7 +296,7 @@ export async function registerCoordinatorPresence( ttl_s: Math.max(1, config.syncCoordinatorPresenceTtlS), capabilities: { sync_capability: LOCAL_SYNC_CAPABILITY, - sync_features: LOCAL_SYNC_FEATURES, + sync_features: coordinatorPresenceSyncFeatures(config), // 0 until a complete lookup has covered every pairing and binding this device has now. applied_removal_seq: readAppliedRemovalSeq(store.db), ...localTransportStatementCapability({ diff --git a/packages/core/src/coordinator-sync-config.ts b/packages/core/src/coordinator-sync-config.ts index 2ff12c4b5..961dc3d63 100644 --- a/packages/core/src/coordinator-sync-config.ts +++ b/packages/core/src/coordinator-sync-config.ts @@ -66,6 +66,7 @@ export interface CoordinatorSyncConfig { syncAllowLegacyPlaintext: boolean; syncProjectsInclude: string[]; syncProjectsExclude: string[]; + syncBoundaryMigrationEnabled?: boolean; syncOpsLimit: number; syncCoordinatorUrl: string; syncCoordinatorGroup: string; @@ -102,11 +103,14 @@ export function readRelayClientSettings(config?: ConfigRecord): RelayClientSetti } /** - * Selects the rollout mode without activating the migration or advertising - * readiness. Invalid nonempty settings disable migration. + * Only `on` enables Project moves. Invalid settings disable migration. */ export function readBoundaryMigrationMode(config?: ConfigRecord): BoundaryMigrationMode { - const mode = clean(readRawSyncConfig(config).sync_boundary_migration).toLowerCase(); + return parseBoundaryMigrationMode(readRawSyncConfig(config).sync_boundary_migration); +} + +function parseBoundaryMigrationMode(value: unknown): BoundaryMigrationMode { + const mode = clean(value).toLowerCase(); if (mode === "report" || mode === "on") return mode; return "off"; } @@ -140,6 +144,7 @@ export function readCoordinatorSyncConfig(config?: ConfigRecord): CoordinatorSyn syncAllowLegacyPlaintext: parseBoolOr(raw.sync_allow_legacy_plaintext, false), syncProjectsInclude: parseStringList(raw.sync_projects_include), syncProjectsExclude: parseStringList(raw.sync_projects_exclude), + syncBoundaryMigrationEnabled: parseBoundaryMigrationMode(raw.sync_boundary_migration) === "on", syncOpsLimit: Math.max(1, Math.min(1000, parseIntOr(raw.sync_ops_limit, 500))), syncCoordinatorUrl: clean(raw.sync_coordinator_url), syncCoordinatorGroup, diff --git a/packages/core/src/memory-creation-provenance.ts b/packages/core/src/memory-creation-provenance.ts index 784a4f4df..0c981b2de 100644 --- a/packages/core/src/memory-creation-provenance.ts +++ b/packages/core/src/memory-creation-provenance.ts @@ -5,7 +5,9 @@ import { tableExists as hasTable } from "./schema-lookups.js"; // Actor/workspace aliases and replication clocks may change during local adoption. // Scope and user-facing content must still match the immutable creation snapshot. -const CREATION_CONTENT_SQL = `json_array(memory_items.kind, memory_items.title, +const creationContentSql = ( + extraMetadataPaths = "", +) => `json_array(memory_items.kind, memory_items.title, memory_items.subtitle, memory_items.body_text, memory_items.confidence, memory_items.tags_text, memory_items.visibility, memory_items.workspace_kind, memory_items.origin_source, memory_items.trust_state, memory_items.narrative, @@ -13,7 +15,8 @@ const CREATION_CONTENT_SQL = `json_array(memory_items.kind, memory_items.title, memory_items.files_modified, memory_items.user_prompt_id, memory_items.prompt_number, memory_items.project, memory_items.active, memory_items.deleted_at, json_remove(CASE WHEN json_valid(memory_items.metadata_json) - THEN memory_items.metadata_json ELSE '{}' END, '$.clock_device_id', '$.import_key'))`; + THEN memory_items.metadata_json ELSE '{}' END, '$.clock_device_id', '$.import_key'${extraMetadataPaths}))`; +const CREATION_CONTENT_SQL = creationContentSql(); function ensureCreationProvenanceSchema(db: Database): void { db.exec(`CREATE TABLE IF NOT EXISTS memory_local_creation_snapshots ( @@ -114,10 +117,25 @@ export function matchingLocalCreationClause(db: Database): string | null { WHERE creation_device.device_id = (SELECT source_device_id FROM memory_source_bindings WHERE entity_id = creation.entity_id) AND creation_device.public_key = creation.source_public_key AND creation_device.fingerprint = creation.source_fingerprint))`; + const contentMatch = + hasTable(db, "project_boundary_migrations") && + hasTable(db, "memory_copy_identities") && + hasTable(db, "memory_copy_creations") + ? `(creation.scope_id IS memory_items.scope_id AND creation.content_json = ${CREATION_CONTENT_SQL} + OR (EXISTS (SELECT 1 FROM project_boundary_migrations move + WHERE move.state = 'committed' AND move.source_scope_id = creation.scope_id + AND move.boundary_scope_id = memory_items.scope_id) + AND EXISTS (SELECT 1 FROM memory_copy_identities copy JOIN memory_copy_creations born USING (copy_id) + WHERE copy.memory_id = memory_items.id) + AND json_extract(CASE WHEN json_valid(memory_items.metadata_json) THEN memory_items.metadata_json END, + '$.last_scope_reassignment.old_scope_id') = creation.scope_id + AND json_extract(CASE WHEN json_valid(memory_items.metadata_json) THEN memory_items.metadata_json END, + '$.last_scope_reassignment.new_scope_id') = memory_items.scope_id + AND creation.content_json = ${creationContentSql(", '$.last_scope_reassignment'")}))` + : `creation.scope_id IS memory_items.scope_id AND creation.content_json = ${CREATION_CONTENT_SQL}`; return `EXISTS (SELECT 1 FROM memory_local_creation_snapshots creation WHERE creation.entity_id = memory_items.import_key - AND creation.scope_id IS memory_items.scope_id - AND creation.content_json = ${CREATION_CONTENT_SQL} + AND (${contentMatch}) AND ${keyMatchSql} AND NOT EXISTS (SELECT 1 FROM memory_foreign_revisions foreign_revision WHERE foreign_revision.entity_id = creation.entity_id))`; diff --git a/packages/core/src/memory-revision-writes.test.ts b/packages/core/src/memory-revision-writes.test.ts index 8ef0ae219..e39ab0dd9 100644 --- a/packages/core/src/memory-revision-writes.test.ts +++ b/packages/core/src/memory-revision-writes.test.ts @@ -373,6 +373,12 @@ const EXEMPT_WRITERS: Array<{ file: string; snippet: string; reason: string }> = snippet: "SET scope_id = ?", reason: "Stamps a scope on a row without one, inside the transaction recording its op.", }, + { + file: "core/src/project-move-arrival.ts", + snippet: "SET scope_id = ?,", + reason: + "Reconciles copies of an existing revision under a recorded boundary. The winning clock stays unchanged, and receivers do not author a new revision or op for it.", + }, { file: "core/src/local-origin-claim.ts", snippet: "SET origin_device_id = ?", diff --git a/packages/core/src/project-migration-report.test.ts b/packages/core/src/project-migration-report.test.ts index 329698b14..377d65686 100644 --- a/packages/core/src/project-migration-report.test.ts +++ b/packages/core/src/project-migration-report.test.ts @@ -96,6 +96,7 @@ it("counts one split candidate without exporting names, content, or any readines expect(readLocalProjectMigrationReport(db, CONFIG)).toEqual({ mode: "report", state: "local_report", + adopted_sources: [], local_filters: "none", maintenance_window: expect.stringMatching(/including current versions.*already read/), storage_fence: expect.stringMatching( diff --git a/packages/core/src/project-migration-report.ts b/packages/core/src/project-migration-report.ts index 3dce6ae1d..cc8b2c586 100644 --- a/packages/core/src/project-migration-report.ts +++ b/packages/core/src/project-migration-report.ts @@ -5,6 +5,7 @@ import { import { buildBoundaryReadinessInventory } from "./boundary-readiness-inventory.js"; import { readBoundaryMigrationMode, readCoordinatorSyncConfig } from "./coordinator-sync-config.js"; import { type Database, tableExists } from "./db.js"; +import { projectMoveBackupInfo, projectMoveSourceCounts } from "./project-move-device.js"; import { columnExists } from "./schema-lookups.js"; /** These are observations on one store, never permission to migrate a Project. */ @@ -55,11 +56,21 @@ function inventory(db: Database, groups: ReturnType): Loca } export function readLocalProjectMigrationReport(db: Database, config: Record) { + const report = migrationReport(db, config); + const backup = projectMoveBackupInfo(db); + return { ...report, ...(backup ? { backup } : {}) }; +} + +function migrationReport(db: Database, config: Record) { const mode = readBoundaryMigrationMode(config); - if (mode === "off") return { mode, state: "off" } as const; + if (mode === "off") { + const sources = projectMoveSourceCounts(db); + return { mode, state: "off", ...(sources.length ? { adopted_sources: sources } : {}) } as const; + } const settings = readCoordinatorSyncConfig(config); return db .transaction(() => { + const adoptedSources = projectMoveSourceCounts(db); const groups = groupsInStore(db); if (!settings.syncCoordinatorUrl) { const managed = @@ -92,6 +103,7 @@ export function readLocalProjectMigrationReport(db: Database, config: Record[number]; + +export interface MoveArrival { + key: string; + scopeId: string; + origin: string | null; + shared: boolean; + clock: Clock; + storedId?: number; +} + +export interface MoveArrivalPlan { + scopeId: string; + copyId: number | null; + copyScopeId: string | null; + keep: boolean; + equalClock?: boolean; + deny?: true; +} + +export function projectMovePairs(db: Database) { + return listProjectBoundaryMigrationRecords(db).flatMap((record) => + record.state === "committed" && record.additionalSourceScopeIds.length === 0 + ? [{ source: record.sourceScopeId, boundary: record.boundaryScopeId }] + : [], + ); +} + +interface MoveDelete { + key: string; + scopeId: string; + sender: { deviceId: string; binding: PinnedKeyBinding } | null; +} + +/** A delete's sender may be another device of the creator's person. */ +export function decideProjectMoveDelete(db: Database, item: MoveDelete): MoveArrivalPlan | null { + const scopes = new Set( + projectMovePairs(db) + .filter(({ source, boundary }) => source === item.scopeId || boundary === item.scopeId) + .flatMap(({ source, boundary }) => [source, boundary]), + ); + if (!scopes.size) return null; + const scoped = { scopeId: item.scopeId, copyId: null, copyScopeId: null, keep: false }; + const rows = db + .prepare(`SELECT id, scope_id, origin_device_id, visibility, metadata_json FROM memory_items + WHERE import_key = ?`) + .all(item.key) as Array< + Pick + >; + const copies = rows.filter((row) => row.scope_id !== null && scopes.has(row.scope_id)); + if (!copies.length) return scoped; + if ( + copies.every( + (row) => storedSyncVisibilityAllowed(row) && hasUnattributedOrigin(row.origin_device_id), + ) + ) + return null; + const verified = + tableExists(db, "memory_source_bindings") && getVerifiedMemorySource(db, item.key); + const matches = copies.filter((row) => + canDeleteMoveCopy(db, item.sender, row, verified ? verified.sourceDeviceId : null), + ); + const [copy] = matches; + if (matches.length > 1) return null; + if (!copy?.scope_id) return { ...scoped, deny: true }; + return { scopeId: copy.scope_id, copyId: copy.id, copyScopeId: copy.scope_id, keep: false }; +} + +function canDeleteMoveCopy( + db: Database, + sender: MoveDelete["sender"], + row: Pick, + verifiedOrigin: string | null, +): boolean { + const { scope_id: scopeId, origin_device_id: origin } = row; + if (!sender || !scopeId || !origin || hasUnattributedOrigin(origin)) return false; + if (!storedSyncVisibilityAllowed(row) || isProjectScopeWithdrawn(db, scopeId)) return false; + if (verifiedOrigin && verifiedOrigin !== origin) return false; + if (origin === sender.deviceId) return true; + const senderIdentity = getVerifiedScopeEnrollmentIdentity(db, { + scopeId, + deviceId: sender.deviceId, + ...sender.binding, + }); + return ( + senderIdentity !== null && + senderIdentity === getVerifiedScopeEnrollmentIdentity(db, { scopeId, deviceId: origin }) + ); +} + +/** Null delegates to the ordinary path. A scoped plan must never use a key-only lookup. */ +export function decideProjectMoveArrival( + db: Database, + item: MoveArrival, + pairs = projectMovePairs(db), +): MoveArrivalPlan | null { + const related = pairs.filter( + ({ source, boundary }) => item.scopeId === source || item.scopeId === boundary, + ); + if (!related.length) return null; + const scoped = { scopeId: item.scopeId, copyId: null, copyScopeId: null, keep: false }; + if (!item.shared) return scoped; + const crossed = crossScopeMoveCopy(db, item, related); + if (crossed) return crossed; + if (item.storedId !== undefined) return scoped; + return sameScopeMovePlan(db, item, scoped); +} + +function crossScopeMoveCopy( + db: Database, + item: MoveArrival, + pairs: ReturnType, +): MoveArrivalPlan | null { + if (hasUnattributedOrigin(item.origin)) return null; + const verified = + tableExists(db, "memory_source_bindings") && getVerifiedMemorySource(db, item.key); + if (verified && verified.sourceDeviceId !== item.origin) return null; + const copies = db + .prepare(`SELECT id, scope_id, origin_device_id, visibility, + COALESCE(rev, 0) AS rev, updated_at, metadata_json FROM memory_items + WHERE import_key = ? AND origin_device_id = ? AND id IS NOT ?`) + .all(item.key, item.origin, item.storedId ?? null) as Copy[]; + return chooseMoveCopy(db, item, pairs, copies); +} + +function sameScopeMovePlan( + db: Database, + item: MoveArrival, + scoped: MoveArrivalPlan, +): MoveArrivalPlan | null { + const rows = copiesInSyncScope( + drizzle(db), + item.key, + eq(memoryItems.scope_id, item.scopeId), + ).filter(storedSyncVisibilityAllowed); + const unattributed = hasUnattributedOrigin(item.origin); + const attributed = unattributed ? [] : rows.filter((row) => row.origin_device_id === item.origin); + if (attributed.length > 1) return null; + const [copy] = attributed; + if (copy) return planForCopy(item, item.scopeId, copy); + + const candidates = unattributed + ? rows + : rows.filter((row) => hasUnattributedOrigin(row.origin_device_id)); + if (!candidates.length) return scoped; + // The ordinary path sees a copy in this scope and can use its normal ambiguity check. + // A newer clock alone cannot link two copies when either origin is unknown. + const replay = candidates.some((row) => compareIncomingClock(item.clock, row) === 0); + return replay ? { ...scoped, keep: true } : null; +} + +function chooseMoveCopy( + db: Database, + item: MoveArrival, + pairs: ReturnType, + copies: Copy[], +): MoveArrivalPlan | null { + // A source can hold several Projects. An S arrival identifies a particular + // destination only if this key and origin already exist in that boundary. + const destinations = new Set( + pairs + .filter( + ({ boundary }) => + boundary === item.scopeId || copies.some((copy) => copy.scope_id === boundary), + ) + .map(({ boundary }) => boundary), + ); + if (destinations.size !== 1) return null; + const [boundary] = destinations; + if (!boundary) return null; + const relevant = new Set([ + item.scopeId, + boundary, + ...pairs.filter((pair) => pair.boundary === boundary).map((pair) => pair.source), + ]); + const copy = singleSharedCopy( + copies.filter(({ scope_id }) => scope_id !== null && relevant.has(scope_id)), + ); + if (!copy || isProjectScopeWithdrawn(db, boundary)) return null; + if (boundary !== item.scopeId && !canReceiveBoundary(db, item.key, boundary)) return null; + return planForCopy(item, boundary, copy); +} + +function singleSharedCopy(copies: Copy[]): Copy | undefined { + const [copy] = copies; + if (copies.length === 1 && copy && storedSyncVisibilityAllowed(copy)) return copy; +} + +function planForCopy(item: MoveArrival, scopeId: string, copy: Copy): MoveArrivalPlan { + const order = compareIncomingClock(item.clock, copy); + return { + scopeId, + copyId: copy.id, + copyScopeId: copy.scope_id, + keep: order <= 0, + equalClock: order === 0, + }; +} + +function canReceiveBoundary(db: Database, key: string, scopeId: string): boolean { + if (isMemoryScopeRetired(db, key, scopeId)) return false; + const self = db.prepare("SELECT device_id, public_key FROM sync_device").get() as + | { device_id: string; public_key: string } + | undefined; + return ( + self !== undefined && + getEffectiveCachedScopeAuthorization(db, { + scopeId, + deviceId: self.device_id, + expectedPublicKey: self.public_key, + }).authorized + ); +} + +export function stampMoveMetadata( + metadata: Record, + fromScope: string | null | undefined, + toScope: string | null, +): Record { + if (toScope && toScope !== fromScope && typeof metadata.scope_id === "string") + metadata.scope_id = toScope; + return metadata; +} + +function compareIncomingClock([rev, timestamp, device]: Clock, copy: Copy): number { + const existingRev = copy.rev ?? 0; + if (rev !== existingRev) return rev > existingRev ? 1 : -1; + if (timestamp !== copy.updated_at) return timestamp > copy.updated_at ? 1 : -1; + const existingDevice = storedClockDevice(copy); + if (device === existingDevice) return 0; + return device > existingDevice ? 1 : -1; +} + +function storedClockDevice(copy: Copy): string { + const clockDevice = fromJson(copy.metadata_json).clock_device_id; + return typeof clockDevice === "string" ? clockDevice : ""; +} + +export function keepMoveCopy(db: Database, plan: MoveArrivalPlan | null): void { + if (!plan?.keep || plan.copyId === null) return; + db.prepare(`UPDATE memory_items SET scope_id = ?, + metadata_json = CASE WHEN json_type(CASE WHEN json_valid(metadata_json) THEN metadata_json END, '$.scope_id') = 'text' + THEN json_set(metadata_json, '$.scope_id', ?) ELSE metadata_json END + WHERE id = ? AND scope_id <> ?`).run(plan.scopeId, plan.scopeId, plan.copyId, plan.scopeId); +} + +export function deleteMoveCopy(db: Database, id: number): void { + snapshotSessionExportKeysForMemoryIds(db, [id]); + clearMemoryRefs(db, id); + db.prepare("DELETE FROM memory_items WHERE id = ?").run(id); +} + +/** Treat each already-received boundary row as the arrival, without matching it to itself. */ +export function reconcilePreviouslyPulledProjectMove( + db: Database, + source: string, + boundary: string, +) { + const current = db + .prepare(`SELECT id, import_key, scope_id, origin_device_id, visibility, + COALESCE(rev, 0) AS rev, updated_at, metadata_json FROM memory_items b + WHERE scope_id = ? AND import_key IS NOT NULL AND EXISTS (SELECT 1 FROM memory_items s + WHERE s.scope_id = ? AND s.import_key = b.import_key AND s.origin_device_id = b.origin_device_id)`) + .all(boundary, source) as Array; + for (const row of current) { + const clock = fromJson(row.metadata_json).clock_device_id; + const plan = decideProjectMoveArrival( + db, + { + key: row.import_key, + origin: row.origin_device_id, + shared: storedSyncVisibilityAllowed(row), + scopeId: boundary, + storedId: row.id, + clock: [row.rev ?? 0, row.updated_at, typeof clock === "string" ? clock : ""], + }, + [{ source, boundary }], + ); + if (plan?.copyId == null) continue; + if (plan.keep) { + keepMoveCopy(db, plan); + deleteMoveCopy(db, row.id); + } else { + deleteMoveCopy(db, plan.copyId); + } + } +} diff --git a/packages/core/src/project-move-device.test.ts b/packages/core/src/project-move-device.test.ts new file mode 100644 index 000000000..a60325c9e --- /dev/null +++ b/packages/core/src/project-move-device.test.ts @@ -0,0 +1,1099 @@ +import { fsyncSync, lstatSync, openSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { CANONICAL_PUBLIC_KEY } from "./coordinator-ed25519-key-id-test-fixtures.js"; +import { unassignedProjectIdentity } from "./coordinator-project-moves.js"; +import { connectReadOnly } from "./db.js"; +import { managedProjectScopeId } from "./managed-project-scope.js"; +import { getProjectBoundaryMigrationHold } from "./project-boundary-migration-hold.js"; +import { projectMoveSourceCounts, restampLocalProjectMoves } from "./project-move-device.js"; +import { + getEffectiveCachedScopeAuthorization, + refreshScopeMembershipCache, +} from "./scope-membership-cache.js"; +import { + cacheMember, + cacheScope, + cacheWireSnapshot, + recordTestLocalIdentity, +} from "./scope-membership-cache-test-fixtures.js"; +import { MemoryStore } from "./store.js"; +import { applyBootstrapSnapshot, mergeBootstrapSnapshot } from "./sync-bootstrap.js"; +import { fingerprintPublicKey } from "./sync-fingerprint.js"; +import { + applyReplicationOps, + filterReplicationOpsForSync, + getSyncResetState, + loadMemorySnapshotPageForPeer, + recordScopeReassignment, +} from "./sync-replication.js"; +import type { ReplicationOp } from "./types.js"; + +vi.mock("node:fs", async (original) => { + const fs = await original(); + return { ...fs, fsyncSync: vi.fn(fs.fsyncSync), openSync: vi.fn(fs.openSync) }; +}); + +const self = "device-local"; +const peer = "device-peer"; +const groupId = "group-a"; +const coordinatorId = "https://coordinator.example.test"; +const source = "team:group-a:default"; +const project = "https://git.example.test/org/project.git"; +const boundary = managedProjectScopeId(groupId, project); +const unassigned = managedProjectScopeId(groupId, unassignedProjectIdentity(source)); +const now = "2026-11-28T00:00:00.000Z"; +let store: MemoryStore; +let sequence = 0; +let dbPath: string; +const db = () => store.db; +const options = { groupIds: [groupId], coordinatorId }; +const signingKey = { runtimeSigningKey: { deviceId: self, publicKey: CANONICAL_PUBLIC_KEY } }; + +beforeEach(() => { + vi.stubEnv("CODEMEM_SYNC_BOUNDARY_MIGRATION", "on"); + dbPath = join(String(process.env.CODEMEM_KEYS_DIR), `project-moves-${++sequence}.sqlite`); + store = new MemoryStore(dbPath, signingKey); + recordTestLocalIdentity(db(), self); + store.close(); + store = new MemoryStore(dbPath, signingKey); + db() + .prepare(`INSERT INTO sync_peers(peer_device_id, public_key, pinned_fingerprint, created_at) + VALUES (?, ?, ?, ?)`) + .run(peer, CANONICAL_PUBLIC_KEY, fingerprintPublicKey(CANONICAL_PUBLIC_KEY), now); +}); + +afterEach(() => { + store.close(); + vi.restoreAllMocks(); + vi.unstubAllEnvs(); +}); + +function mapping(identity = project, scope = source) { + db() + .prepare(`INSERT INTO project_scope_mappings(workspace_identity, project_pattern, scope_id, created_at, updated_at) + VALUES (?, ?, ?, ?, ?)`) + .run(identity, identity, scope, now, now); +} + +function memory( + input: { + id?: string; + scope?: string; + origin?: string; + project?: string | null; + visibility?: string; + } = {}, +) { + const remote = input.project === undefined ? project : input.project; + const session = db() + .prepare("INSERT INTO sessions(git_remote, started_at) VALUES (?, ?)") + .run(remote, now); + return Number( + db() + .prepare(`INSERT INTO memory_items(session_id, kind, title, body_text, active, created_at, + updated_at, rev, scope_id, import_key, origin_device_id, visibility) + VALUES (?, 'discovery', 'Test', 'Test body', 1, ?, ?, 1, ?, ?, ?, ?)`) + .run( + session.lastInsertRowid, + now, + now, + input.scope ?? source, + input.id ?? `memory-${session.lastInsertRowid}`, + input.origin ?? self, + input.visibility ?? "shared", + ).lastInsertRowid, + ); +} + +function announce( + overrides: { + group?: string; + source?: string; + boundary?: string; + proof?: boolean; + listMoves?: () => Promise; + onlyBoundary?: boolean; + remapProjects?: boolean; + enrolledPeople?: Record; + } = {}, +) { + const scope = cacheScope({ + scope_id: source, + group_id: groupId, + coordinator_id: coordinatorId, + membership_epoch: 1, + }); + const target = cacheScope({ + ...scope, + scope_id: overrides.boundary ?? boundary, + kind: "managed_project", + }); + return refreshScopeMembershipCache(db(), { + ...options, + syncBoundaryMigrationEnabled: overrides.remapProjects ?? true, + fetchers: { + async listScopes() { + return { version: 1, items: overrides.onlyBoundary ? [target] : [scope, target] }; + }, + async getScopeSnapshot(_group, id) { + const selected = id === source ? scope : target; + const members = [cacheMember(selected, peer)]; + if (id === source || overrides.proof !== false) members.push(cacheMember(selected, self)); + for (const device of Object.keys(overrides.enrolledPeople ?? {})) { + if (device !== peer && device !== self) members.push(cacheMember(selected, device)); + } + const snapshot = cacheWireSnapshot(selected, members); + for (const item of snapshot.items) + item.enrollment.identity_id = + overrides.enrolledPeople?.[item.membership.device_id] ?? null; + return snapshot; + }, + async listProjectMoves() { + if (overrides.listMoves) return overrides.listMoves(); + return { + moves: [ + { + version: 1, + group_id: overrides.group ?? groupId, + source_scope_id: overrides.source ?? source, + boundary_scope_id: target.scope_id, + unknown_field: [null], + }, + ], + }; + }, + }, + }); +} + +const scopeOf = (id: number) => + db().prepare("SELECT scope_id FROM memory_items WHERE id = ?").pluck().get(id); +const mappedScope = () => + db() + .prepare("SELECT scope_id FROM project_scope_mappings WHERE workspace_identity = ?") + .pluck() + .get(project); + +it("commits the move record and hold before exposing the remapped Project or new proof", async () => { + mapping(); + db().exec(`CREATE TRIGGER expect_move_record BEFORE INSERT ON project_scope_mappings + WHEN NEW.scope_id = '${boundary}' AND NOT EXISTS (SELECT 1 FROM project_boundary_migrations + WHERE boundary_scope_id = NEW.scope_id AND source_scope_id = '${source}') + BEGIN SELECT RAISE(ABORT, 'missing move record'); END;`); + + expect((await announce()).status).toBe("refreshed"); + + expect(mappedScope()).toBe(boundary); + expect(getProjectBoundaryMigrationHold(db(), boundary)).toMatchObject({ held: true }); +}); + +it("does not publish the new proof or leave a hold when the remap fails", async () => { + mapping(); + db().exec(`CREATE TRIGGER reject_remap BEFORE INSERT ON project_scope_mappings + WHEN NEW.scope_id = '${boundary}' BEGIN SELECT RAISE(ABORT, 'remap failed'); END;`); + + expect((await announce()).status).toBe("stale"); + expect(mappedScope()).toBe(source); + expect(getProjectBoundaryMigrationHold(db(), boundary)).toBeNull(); + expect( + getEffectiveCachedScopeAuthorization(db(), { + deviceId: self, + scopeId: boundary, + expectedPublicKey: CANONICAL_PUBLIC_KEY, + }).authorized, + ).toBe(false); +}); + +it.each([ + [{ source: "elsewhere" }, true], + [{ boundary: managedProjectScopeId(groupId, "other-project") }, true], + [{ group: "other-group" }, false], + [{ proof: false }, false], +] as const)( + "keeps the existing mapping unless the log and retained proof match: %j", + async (overrides, records) => { + mapping(); + expect((await announce(overrides)).status).toBe("refreshed"); + expect(mappedScope()).toBe(source); + const hold = getProjectBoundaryMigrationHold( + db(), + "boundary" in overrides ? overrides.boundary : boundary, + ); + expect(Boolean(hold)).toBe(records); + }, +); + +it("does not change a named Project without a matching current mapping", async () => { + memory(); + await announce(); + expect(mappedScope()).toBeUndefined(); + expect(getProjectBoundaryMigrationHold(db(), boundary)).toMatchObject({ held: true }); +}); + +it("records the move while disabled but does not remap or continue restamping", async () => { + mapping(); + const id = memory(); + vi.stubEnv("CODEMEM_SYNC_BOUNDARY_MIGRATION", "off"); + await announce({ remapProjects: false }); + expect(getProjectBoundaryMigrationHold(db(), boundary)).toMatchObject({ held: true }); + expect(mappedScope()).toBe(source); + + await announce(); + expect(mappedScope()).toBe(boundary); + const backup = vi.spyOn(db(), "backup"); + await restampLocalProjectMoves(store); + expect(scopeOf(id)).toBe(source); + expect(backup).not.toHaveBeenCalled(); +}); + +it("does not restamp if it cannot publish a private backup", async () => { + mapping(); + const id = memory(); + await announce(); + vi.spyOn(db(), "backup").mockRejectedValue(new Error("backup write failed")); + + await expect(restampLocalProjectMoves(store)).rejects.toThrow("backup"); + expect(scopeOf(id)).toBe(source); +}); + +it("moves only own rows of the matching Project and source, with a private backup", async () => { + mapping(); + const own = memory(); + const received = memory({ origin: peer }); + const other = memory({ project: `${project}-other` }); + const unmapped = memory({ scope: "local-default" }); + const privateRow = memory({ visibility: "private" }); + await announce(); + + await restampLocalProjectMoves(store); + + expect([own, received, other, unmapped, privateRow].map(scopeOf)).toEqual([ + boundary, + source, + source, + "local-default", + boundary, + ]); + expect( + db().prepare("SELECT visibility FROM memory_items WHERE id = ?").pluck().get(privateRow), + ).toBe("private"); + const backupPath = `${dbPath}.before-project-moves.sqlite`; + expect(lstatSync(backupPath).mode & 0o777).toBe(0o600); + const backup = connectReadOnly(backupPath); + try { + expect(backup.prepare("SELECT scope_id FROM memory_items WHERE id = ?").pluck().get(own)).toBe( + source, + ); + } finally { + backup.close(); + } + expect(projectMoveSourceCounts(db())).toEqual([{ source_scope_id: source, remaining_rows: 2 }]); + const ops = db().prepare("SELECT * FROM replication_ops").all() as ReplicationOp[]; + const [sent] = filterReplicationOpsForSync(db(), ops, peer, { + localDeviceId: self, + scopeId: boundary, + }); + expect(sent.map(({ entity_id, op_type }) => [entity_id, op_type])).toHaveLength(1); + expect(sent[0]).toMatchObject({ op_type: "upsert", scope_id: boundary }); + const [oldOps] = filterReplicationOpsForSync( + db(), + ops.filter((op) => op.scope_id === source), + peer, + { localDeviceId: self, scopeId: source }, + ); + expect(oldOps).toEqual([]); + const reset = getSyncResetState(db(), boundary); + const snapshot = loadMemorySnapshotPageForPeer(db(), { + peerDeviceId: peer, + scopeId: boundary, + generation: reset.generation, + snapshotId: reset.snapshot_id, + baselineCursor: reset.baseline_cursor, + }); + expect(snapshot.items).toHaveLength(1); +}); + +it("waits for attention to clear and can resume after a crash between batches", async () => { + mapping(); + db().transaction(() => { + for (let index = 0; index < 201; index++) memory(); + })(); + await announce(); + db().exec("INSERT INTO sync_daemon_state(id, phase) VALUES (1, 'needs_attention')"); + await restampLocalProjectMoves(store); + expect(projectMoveSourceCounts(db())[0]?.remaining_rows).toBe(201); + db().exec("UPDATE sync_daemon_state SET phase = NULL"); + + await expect( + restampLocalProjectMoves(store, async () => { + throw new Error("interrupted"); + }), + ).rejects.toThrow("interrupted"); + expect(projectMoveSourceCounts(db())[0]?.remaining_rows).toBe(1); + const backup = `${dbPath}.before-project-moves.sqlite`; + const inode = lstatSync(backup).ino; + store.close(); + store = new MemoryStore(dbPath, signingKey); + await restampLocalProjectMoves(store); + expect(projectMoveSourceCounts(db())[0]?.remaining_rows).toBe(0); + expect(lstatSync(backup).ino).toBe(inode); +}); + +it("moves only Unassigned rows of the older scope without a named mapping", async () => { + const unnamed = memory({ project: null }); + const named = memory(); + await announce({ boundary: unassigned }); + await restampLocalProjectMoves(store); + expect([scopeOf(unnamed), scopeOf(named)]).toEqual([unassigned, source]); +}); + +function pullBoundary() { + const reset = { + ...getSyncResetState(db(), boundary), + scope_id: boundary, + reset_required: true as const, + reason: "generation_mismatch" as const, + }; + applyBootstrapSnapshot( + db(), + peer, + [ + { + entity_id: "received-copy", + op_type: "upsert", + clock_rev: 3, + clock_updated_at: "2026-11-28T00:01:00.000Z", + clock_device_id: peer, + payload_json: JSON.stringify({ + scope_id: boundary, + kind: "discovery", + title: "Moved", + body_text: "Same memory", + visibility: "shared", + origin_device_id: peer, + created_at: now, + }), + }, + ], + reset, + ); +} + +it("reconciles a received copy on the first boundary snapshot without a mapping", async () => { + memory({ id: "received-copy", origin: peer }); + await announce(); + pullBoundary(); + expect( + db() + .prepare("SELECT scope_id FROM memory_items WHERE import_key = 'received-copy'") + .pluck() + .all(), + ).toEqual([boundary]); + expect(mappedScope()).toBeUndefined(); + expect(store.get(onlyCopyId())?.body_text).toBe("Same memory"); +}); + +function onlyCopyId(): number { + const ids = db() + .prepare("SELECT id FROM memory_items WHERE import_key = 'received-copy'") + .pluck() + .all(); + expect(ids).toHaveLength(1); + return Number(ids[0]); +} + +const arrivalCases = [ + { + label: "newer timestamp", + origin: peer, + rev: 1, + time: "2026-11-28T00:00:01.000Z", + matches: true, + keeps: false, + }, + { label: "older clock", origin: peer, rev: 0, time: now, matches: true, keeps: true }, + { + label: "newer device tiebreak", + origin: peer, + rev: 1, + time: now, + clockDevice: `${peer}-later`, + matches: true, + keeps: false, + }, + { label: "equal clock", origin: peer, rev: 1, time: now, matches: true, keeps: true }, + { label: "different author", origin: "other-author", rev: 3, time: now, matches: false }, + { label: "private copy", origin: peer, visibility: "private", rev: 3, time: now, matches: false }, + { label: "empty origin", origin: "", rev: 3, time: now, matches: false }, + { label: "two candidates", origin: peer, ambiguous: true, rev: 3, time: now, matches: false }, + { + label: "conflicting author proof", + origin: peer, + conflictingProof: true, + rev: 3, + time: now, + matches: false, + }, +]; + +function arrivals() { + return (["snapshot", "snapshot merge", "ops"] as const).flatMap((path) => + [source, boundary].map((scope) => ({ path, scope, cases: arrivalCases })), + ); +} + +type ArrivalPath = ReturnType[number]["path"]; + +function applyTestArrival( + path: ArrivalPath, + scope: string, + rev: number, + time: string, + { + clock = peer, + origin = peer, + metadataPrivate = false, + opId = `arrived:${rev}`, + validateScope = false, + }: { + clock?: string; + origin?: string; + metadataPrivate?: boolean; + opId?: string; + validateScope?: boolean; + } = {}, +) { + const item = { + entity_id: "received-copy", + op_type: "upsert" as const, + clock_rev: rev, + clock_updated_at: time, + clock_device_id: clock, + payload_json: JSON.stringify({ + scope_id: scope, + kind: "discovery", + title: "Moved", + body_text: "incoming", + visibility: metadataPrivate ? null : "shared", + origin_device_id: origin, + metadata_json: { scope_id: scope, ...(metadataPrivate ? { visibility: "private" } : {}) }, + }), + }; + if (path !== "ops") { + const apply = path === "snapshot" ? applyBootstrapSnapshot : mergeBootstrapSnapshot; + const result = apply(db(), peer, [item], { + ...getSyncResetState(db(), scope), + scope_id: scope, + reset_required: true, + reason: "generation_mismatch", + }); + expect(result.ok).toBe(true); + return result; + } + const result = applyReplicationOps( + db(), + [ + { + ...item, + op_id: opId, + entity_type: "memory_item", + device_id: peer, + scope_id: scope, + created_at: time, + }, + ], + self, + undefined, + { + activityPeerDeviceId: peer, + inboundScopeValidation: validateScope ? { peerDeviceId: peer } : undefined, + }, + ); + expect(result.errors).toEqual([]); + expect(result.rejections).toEqual([]); + return result; +} + +it.each([ + ["ops", 3, ""], + ["ops", 1, ""], + ["ops", 3, peer], + ["snapshot", 3, ""], + ["snapshot merge", 3, ""], +] as const)( + "%s handles a non-replay of an unattributed copy as it does without a recorded move (rev %i, origin %j)", + async (path, rev, origin) => { + await announce({ listMoves: async () => ({ moves: [] }) }); + const held = memory({ id: "received-copy", scope: source, origin: "local" }); + memory({ id: "received-copy", scope: boundary, origin: "another-author" }); + db() + .prepare(`UPDATE memory_items SET metadata_json = '{"clock_device_id":"before-peer"}' + WHERE id = ?`) + .run(held); + if (path !== "ops") { + // Merge considers this newer same-key row too. A reset replaces both source rows. + const newer = memory({ id: "received-copy", scope: source, origin: "third-author" }); + db().prepare("UPDATE memory_items SET rev = 4 WHERE id = ?").run(newer); + } + const before = receivedCopies(); + const heldRow = db().prepare("SELECT * FROM memory_items WHERE id = ?"); + const original = heldRow.get(held); + const receive = () => { + applyTestArrival(path, source, rev, now, { origin, validateScope: true }); + return { + rows: receivedCopies(), + opRecorded: + db().prepare("SELECT 1 FROM replication_ops WHERE op_id = ?").get(`arrived:${rev}`) !== + undefined, + }; + }; + + db().exec("SAVEPOINT without_move"); + const ordinary = receive(); + db().exec("ROLLBACK TO without_move; RELEASE without_move"); + await announce(); + + if (path !== "snapshot") expect(ordinary.rows).toEqual(before); + expect(ordinary.opRecorded).toBe(false); + expect(receive()).toEqual(ordinary); + if (path !== "snapshot") expect(heldRow.get(held)).toEqual(original); + }, +); + +it.each([ + ["ops", 3, 2], + ["ops", 5, 2], + ["snapshot merge", 3, 2], + ["snapshot merge", 5, 1], +] as const)( + "%s handles already-duplicated attributed copies like ordinary sync (rev %i, %i rows)", + async (path, rev, count) => { + await announce({ listMoves: async () => ({ moves: [] }) }); + memory({ id: "received-copy", origin: peer }); + const newer = memory({ id: "received-copy", origin: peer }); + db().prepare("UPDATE memory_items SET rev = 4 WHERE id = ?").run(newer); + const receive = () => + ["first-update", "second-update"].map((opId) => { + applyTestArrival(path, source, rev, now, { opId, validateScope: true }); + return receivedCopies(); + }); + + db().exec("SAVEPOINT without_move"); + const ordinary = receive(); + db().exec("ROLLBACK TO without_move; RELEASE without_move"); + await announce(); + + for (const rows of ordinary) expect(rows).toHaveLength(count); + expect(receive()).toEqual(ordinary); + }, +); + +function peerReassignment(id: number): { oldSide: ReplicationOp; newSide: ReplicationOp } { + // Build the author's wire operations, then restore the receiver's original row. + db().exec("SAVEPOINT author"); + const { oldOpId, newOpId } = recordScopeReassignment(db(), { + operationId: "paired-reassignment", + memoryId: id, + oldScopeId: source, + newScopeId: boundary, + deviceId: peer, + createdAt: now, + }); + const byId = db().prepare("SELECT * FROM replication_ops WHERE op_id = ?"); + const oldSide = byId.get(oldOpId) as ReplicationOp; + const newSide = byId.get(newOpId) as ReplicationOp; + db().exec("ROLLBACK TO author; RELEASE author"); + return { oldSide, newSide }; +} + +it.each([false, true])( + "keeps a paired reassignment readable after both sides arrive (old side first: %s)", + async (oldFirst) => { + await announce(); + const id = memory({ id: "received-copy", origin: peer }); + const { oldSide, newSide } = peerReassignment(id); + + const row = db().prepare("SELECT scope_id, active, deleted_at FROM memory_items WHERE id = ?"); + for (const op of oldFirst ? [oldSide, newSide] : [newSide, oldSide]) { + const result = applyReplicationOps(db(), [op], self, undefined, { + activityPeerDeviceId: peer, + inboundScopeValidation: { peerDeviceId: peer }, + }); + expect(result.errors).toEqual([]); + expect(result.rejections).toEqual([]); + if (op === oldSide && oldFirst) + expect(row.get(id)).toEqual({ scope_id: source, active: 0, deleted_at: now }); + } + expect(onlyCopyId()).toBe(id); + expect(row.get(id)).toEqual({ scope_id: boundary, active: 1, deleted_at: null }); + expect(store.get(id)).toMatchObject({ scope_id: boundary, body_text: "Test body" }); + }, +); + +for (const path of ["ops", "snapshot"] as const) { + it.each([ + { label: "newer revision", rev: 3, time: now, clock: peer, newer: true }, + { + label: "newer timestamp", + rev: 2, + time: "2026-11-28T00:00:01.000Z", + clock: peer, + newer: true, + }, + { label: "newer clock device", rev: 2, time: now, clock: `${peer}-later`, newer: true }, + { label: "equal clock", rev: 2, time: now, clock: peer, newer: false }, + { label: "older revision", rev: 1, time: now, clock: peer, newer: false }, + ])( + `${path} reconciles a reassignment against a held copy with $label`, + async ({ rev, time, clock, newer }) => { + await announce(); + const id = memory({ id: "received-copy", origin: peer }); + const { newSide } = peerReassignment(id); + db() + .prepare(`UPDATE memory_items SET rev = ?, updated_at = ?, metadata_json = ?, + body_text = 'Held content' WHERE id = ?`) + .run(rev, time, JSON.stringify({ clock_device_id: clock }), id); + + if (path === "ops") { + expect( + applyReplicationOps(db(), [newSide], self, undefined, { + activityPeerDeviceId: peer, + inboundScopeValidation: { peerDeviceId: peer }, + }), + ).toMatchObject({ errors: [], rejections: [] }); + } else { + applyTestArrival(path, boundary, newSide.clock_rev, now, { clock: peer }); + } + + const keepsHeld = newer || (path === "snapshot" && rev === newSide.clock_rev); + const incomingContent = path === "ops" ? "Test body" : "incoming"; + expect( + db() + .prepare(`SELECT scope_id, body_text, rev, updated_at, + json_extract(metadata_json, '$.clock_device_id') AS clock_device_id + FROM memory_items WHERE id = ?`) + .get(onlyCopyId()), + ).toEqual({ + scope_id: boundary, + body_text: keepsHeld ? "Held content" : incomingContent, + rev: keepsHeld ? rev : newSide.clock_rev, + updated_at: keepsHeld ? time : now, + clock_device_id: keepsHeld ? clock : peer, + }); + }, + ); +} + +it.each([ + { held: source, sent: boundary, origin: "creator-device", samePerson: true, active: 0 }, + { held: boundary, sent: source, origin: "creator-device", samePerson: true, active: 0 }, + { held: boundary, sent: boundary, origin: "creator-device", samePerson: false, active: 1 }, + { held: source, sent: source, origin: "local", samePerson: false, active: 0 }, +])( + "applies a Project move delete by verified ownership: $origin, $samePerson, $held", + async ({ held, sent, origin, samePerson, active }) => { + await announce({ + enrolledPeople: { + [peer]: "sending-person", + "creator-device": samePerson ? "sending-person" : "different-person", + }, + }); + const id = memory({ id: "received-copy", scope: held, origin }); + const op: ReplicationOp = { + op_id: "same-person-delete", + entity_type: "memory_item", + entity_id: "received-copy", + op_type: "delete", + payload_json: null, + clock_rev: 3, + clock_updated_at: now, + clock_device_id: peer, + device_id: peer, + created_at: now, + scope_id: sent, + }; + const result = applyReplicationOps(db(), [op], self, undefined, { + activityPeerDeviceId: peer, + inboundScopeValidation: { peerDeviceId: peer }, + }); + expect(result.errors).toEqual([]); + expect(result.rejections).toEqual([]); + expect(db().prepare("SELECT active, scope_id FROM memory_items WHERE id = ?").get(id)).toEqual({ + active, + scope_id: held, + }); + }, +); + +function receivedCopies() { + return db() + .prepare(`SELECT scope_id, origin_device_id, body_text + FROM memory_items WHERE import_key = 'received-copy' ORDER BY id`) + .all(); +} + +function markLegacyPrivate(id: number) { + db() + .prepare(`UPDATE memory_items SET visibility = NULL, metadata_json = '{"visibility":"private"}' + WHERE id = ?`) + .run(id); +} + +for (const { path, scope, cases } of arrivals()) { + const otherScope = scope === source ? boundary : source; + const lane = `${path} in ${scope === source ? "the source" : "the boundary"}`; + it.each([ + { label: "metadata-only private origin", origin: peer, heldPrivate: true }, + { label: "legacy local origin", origin: "local", heldPrivate: false }, + { label: "incoming metadata-only private copy", origin: peer, metadataPrivate: true }, + ])(`${lane} keeps both copies with $label`, async ({ origin, heldPrivate, metadataPrivate }) => { + await announce(); + const id = memory({ id: "received-copy", scope: otherScope, origin }); + if (heldPrivate) markLegacyPrivate(id); + const row = db().prepare("SELECT * FROM memory_items WHERE id = ?"); + const before = row.get(id); + applyTestArrival(path, scope, 3, now, { origin, metadataPrivate }); + expect(row.get(id)).toEqual(before); + expect(receivedCopies()).toEqual([ + { scope_id: otherScope, origin_device_id: origin, body_text: "Test body" }, + { scope_id: scope, origin_device_id: origin, body_text: "incoming" }, + ]); + if (metadataPrivate && path !== "ops") + expect( + db().prepare("SELECT visibility FROM memory_items WHERE id <> ?").pluck().get(id), + ).toBe("private"); + }); + + it.each([peer, "", "local"])(`${lane} replays origin %j in place`, async (origin) => { + await announce(); + expect(applyTestArrival(path, scope, 1, now, { origin }).applied).toBe(1); + for (let repeat = 0; repeat < 2; repeat++) + expect(applyTestArrival(path, scope, 1, now, { origin }).applied).toBe(0); + // The same op ID is acknowledged only once. A new ID with the same clock + // also has to find the copy already held in this scope. + if (path === "ops") + expect(applyTestArrival(path, scope, 1, now, { origin, opId: "same-clock" }).applied).toBe(0); + expect(receivedCopies()).toEqual([ + { scope_id: scope, origin_device_id: origin, body_text: "incoming" }, + ]); + }); + + it(`${lane} replays without touching a private sibling in the same scope`, async () => { + await announce(); + const id = memory({ id: "received-copy", scope, origin: peer }); + markLegacyPrivate(id); + const row = db().prepare("SELECT * FROM memory_items WHERE id = ?"); + const before = row.get(id); + applyTestArrival(path, scope, 3, now); + applyTestArrival(path, scope, 3, now, { opId: "sibling-replay" }); + expect(row.get(id)).toEqual(before); + expect(receivedCopies()).toEqual([ + { scope_id: scope, origin_device_id: peer, body_text: "Test body" }, + { scope_id: scope, origin_device_id: peer, body_text: "incoming" }, + ]); + }); + + it.each(cases)( + `${path} in ${scope === source ? "the source" : "the boundary"} handles $label`, + async (test) => { + await announce(); + const held = scope === source ? boundary : source; + const id = memory({ + id: "received-copy", + scope: held, + origin: test.origin, + visibility: test.visibility, + }); + db() + .prepare("UPDATE memory_items SET metadata_json = ? WHERE id = ?") + .run(JSON.stringify({ clock_device_id: peer }), id); + if (test.ambiguous) memory({ id: "received-copy", scope: held, origin: peer }); + if (test.conflictingProof) + db() + .prepare(`INSERT INTO memory_source_bindings + (entity_id, source_device_id, evidence, created_at) VALUES ('received-copy', 'other-author', + 'authenticated_namespace', ?)`) + .run(now); + const rows = () => + db() + .prepare(`SELECT scope_id, origin_device_id, visibility, body_text + FROM memory_items WHERE import_key = 'received-copy' ORDER BY scope_id, body_text`) + .all(); + const before = rows(); + applyTestArrival(path, scope, test.rev, test.time, { clock: test.clockDevice }); + const incoming = { + scope_id: scope, + origin_device_id: peer, + visibility: "shared", + body_text: "incoming", + }; + if (test.matches) { + expect(rows()).toEqual([ + { ...incoming, scope_id: boundary, body_text: test.keeps ? "Test body" : "incoming" }, + ]); + if (!test.keeps) + expect( + db() + .prepare("SELECT json_extract(metadata_json, '$.scope_id') FROM memory_items") + .pluck() + .get(), + ).toBe(boundary); + if (test.keeps && scope === source && path === "snapshot") { + applyTestArrival("ops", boundary, 5, now); + expect(rows()).toEqual([{ ...incoming, scope_id: boundary }]); + } + } else { + expect(rows()).toHaveLength(before.length + 1); + expect(rows()).toEqual(expect.arrayContaining([...before, incoming])); + } + }, + ); + it(`${path} updates only its own copy if both move scopes already hold the same origin (${scope === source ? "source" : "boundary"})`, async () => { + await announce(); + const held = scope === source ? boundary : source; + const untouched = memory({ id: "received-copy", scope: held, origin: peer }); + const row = db().prepare("SELECT * FROM memory_items WHERE id = ?"); + const before = row.get(untouched); + memory({ id: "received-copy", scope, origin: peer }); + applyTestArrival(path, scope, 3, now); + expect(row.get(untouched)).toEqual(before); + expect( + db() + .prepare(`SELECT scope_id, origin_device_id, visibility, body_text + FROM memory_items WHERE id <> ?`) + .all(untouched), + ).toEqual([ + { scope_id: scope, origin_device_id: peer, visibility: "shared", body_text: "incoming" }, + ]); + }); +} + +it.each(["private-source", "private-boundary", "local"])( + "preserves both early copies while recording the move: %s", + async (kind) => { + const origin = kind === "local" ? "local" : peer; + const old = memory({ id: "received-copy", scope: source, origin }); + const moved = memory({ id: "received-copy", scope: boundary, origin }); + db().prepare("UPDATE memory_items SET rev = 3 WHERE id = ?").run(moved); + if (kind === "private-source") markLegacyPrivate(old); + if (kind === "private-boundary") markLegacyPrivate(moved); + const before = receivedCopies(); + await announce(); + expect(receivedCopies()).toEqual(before); + }, +); + +it("keeps metadata-only private rows absent from a reset of a recorded scope", async () => { + await announce(); + const id = memory({ scope: boundary, origin: self }); + markLegacyPrivate(id); + const row = db().prepare("SELECT * FROM memory_items WHERE id = ?"); + const before = row.get(id); + applyTestArrival("snapshot", boundary, 3, now); + expect(row.get(id)).toEqual(before); +}); + +it("keeps the author's restamped memory readable after the boundary proof is lost", async () => { + mapping(); + await announce({ listMoves: async () => ({ moves: [] }) }); + const session = store.startSession({ cwd: "/tmp/fixture", gitRemote: project }); + const id = store.remember(session, "discovery", "Author's memory", "Local creation"); + expect(scopeOf(id)).toBe(source); + await announce(); + await restampLocalProjectMoves(store); + expect(scopeOf(id)).toBe(boundary); + db() + .prepare("DELETE FROM scope_membership_authorization_evidence WHERE scope_id = ?") + .run(boundary); + expect( + getEffectiveCachedScopeAuthorization(db(), { deviceId: self, scopeId: boundary }).authorized, + ).toBe(false); + expect(store.get(id)?.body_text).toBe("Local creation"); +}); + +it("does not change the ordinary key-only op path before recording a move", async () => { + await announce({ listMoves: async () => ({ moves: [] }) }); + const id = memory({ id: "received-copy", scope: source, origin: peer }); + applyTestArrival("ops", boundary, 3, now); + expect(scopeOf(id)).toBe(boundary); + expect(onlyCopyId()).toBe(id); +}); + +it("applies a boundary op without changing a same-key row in a local-only scope", async () => { + await announce(); + const id = memory({ id: "received-copy", scope: "local-default", origin: self }); + const row = db().prepare("SELECT * FROM memory_items WHERE id = ?"); + const before = row.get(id); + applyTestArrival("ops", boundary, 3, now); + expect(row.get(id)).toEqual(before); + expect( + db().prepare("SELECT scope_id, body_text FROM memory_items WHERE id <> ?").all(id), + ).toEqual([{ scope_id: boundary, body_text: "incoming" }]); +}); + +it("does not reconcile two originless copies of the same key", async () => { + await announce(); + const id = memory({ id: "received-copy", scope: source, origin: "" }); + applyTestArrival("snapshot", boundary, 3, now, { origin: "" }); + expect(scopeOf(id)).toBe(source); + expect(db().prepare("SELECT scope_id FROM memory_items ORDER BY id").pluck().all()).toEqual([ + source, + boundary, + ]); +}); + +it("does not update a boundary copy from a source arrival after losing the boundary proof", async () => { + await announce(); + const id = memory({ id: "received-copy", scope: boundary, origin: peer }); + const row = db().prepare("SELECT * FROM memory_items WHERE id = ?"); + const before = row.get(id); + db() + .prepare("DELETE FROM scope_membership_authorization_evidence WHERE scope_id = ?") + .run(boundary); + applyTestArrival("snapshot", source, 3, now); + expect(row.get(id)).toEqual(before); + expect( + db().prepare("SELECT scope_id, body_text FROM memory_items WHERE id <> ?").all(id), + ).toEqual([{ scope_id: source, body_text: "incoming" }]); +}); + +it("syncs the backup directory before restamping a memory", async () => { + mapping(); + memory(); + await announce(); + const opened = vi.mocked(openSync); + const synced = vi.mocked(fsyncSync); + opened.mockClear(); + synced.mockClear(); + const restamp = vi.spyOn(store, "reassignMemoryScope"); + + await restampLocalProjectMoves(store); + + const directory = opened.mock.calls.findIndex(([path]) => path === dirname(dbPath)); + expect(directory).toBeGreaterThanOrEqual(0); + const fd = opened.mock.results[directory]?.value; + const directoryOpen = opened.mock.invocationCallOrder[directory] ?? Infinity; + const directorySync = synced.mock.calls.findIndex( + ([value], index) => + value === fd && (synced.mock.invocationCallOrder[index] ?? 0) > directoryOpen, + ); + expect(directorySync).toBeGreaterThanOrEqual(0); + expect(synced.mock.invocationCallOrder[directorySync]).toBeLessThan( + restamp.mock.invocationCallOrder[0] ?? 0, + ); +}); + +it.each([false, true])( + "applies the author's restamp to one readable boundary copy (early pull: %s)", + async (earlyPull) => { + memory({ id: "received-copy", origin: peer }); + if (earlyPull) { + await announce({ listMoves: async () => ({ moves: [] }) }); + pullBoundary(); + expect( + db() + .prepare("SELECT COUNT(*) FROM memory_items WHERE import_key = 'received-copy'") + .pluck() + .get(), + ).toBe(2); + } + await announce(); + if (earlyPull) expect(store.get(onlyCopyId())?.body_text).toBe("Same memory"); + + const op: ReplicationOp = { + op_id: "restamp-op", + entity_type: "memory_item", + entity_id: "received-copy", + op_type: "upsert", + scope_id: boundary, + clock_rev: 4, + clock_updated_at: "2026-11-28T00:01:00.000Z", + clock_device_id: peer, + device_id: peer, + created_at: "2026-11-28T00:01:00.000Z", + payload_json: JSON.stringify({ + scope_id: boundary, + kind: "discovery", + title: "Moved", + body_text: "Restamped", + visibility: "shared", + origin_device_id: peer, + }), + }; + expect( + applyReplicationOps(db(), [op], self, undefined, { + activityPeerDeviceId: peer, + }), + ).toMatchObject({ applied: 1, errors: [] }); + expect(store.get(onlyCopyId())).toMatchObject({ scope_id: boundary, body_text: "Restamped" }); + expect(mappedScope()).toBeUndefined(); + }, +); + +it("withholds a new boundary proof until the move log arrives, even without the source in the catalogue", async () => { + memory({ id: "received-copy", origin: peer }); + const entered = Promise.withResolvers(); + const release = Promise.withResolvers(); + const refreshing = announce({ + onlyBoundary: true, + listMoves: () => { + entered.resolve(); + return release.promise; + }, + }); + const ready = await Promise.race([ + entered.promise.then(() => false), + refreshing.then(() => true), + ]); + expect(ready).toBe(false); + try { + expect( + getEffectiveCachedScopeAuthorization(db(), { + deviceId: self, + scopeId: boundary, + expectedPublicKey: CANONICAL_PUBLIC_KEY, + }).authorized, + ).toBe(false); + } finally { + release.resolve({ + moves: [ + { version: 1, group_id: groupId, source_scope_id: source, boundary_scope_id: boundary }, + ], + }); + await refreshing; + } + expect(getProjectBoundaryMigrationHold(db(), boundary)).toMatchObject({ held: true }); +}); + +it.each([{ origin: self }, { visibility: "private" }])( + "keeps an older-scope copy that the boundary copy cannot replace: %j", + async (options) => { + const old = memory({ id: "received-copy", origin: peer, ...options }); + await announce({ listMoves: async () => ({ moves: [] }) }); + pullBoundary(); + + await announce(); + + expect(scopeOf(old)).toBe(source); + }, +); + +it("keeps the newer source contents under the boundary when recording a move after a pull", async () => { + const id = memory({ id: "received-copy", origin: peer }); + db() + .prepare("UPDATE memory_items SET rev = 4, metadata_json = ? WHERE id = ?") + .run(JSON.stringify({ clock_device_id: peer, scope_id: source }), id); + await announce({ listMoves: async () => ({ moves: [] }) }); + pullBoundary(); + await announce(); + expect(store.get(onlyCopyId())).toMatchObject({ scope_id: boundary, body_text: "Test body" }); + expect( + db() + .prepare(`SELECT rev, updated_at, + json_extract(metadata_json, '$.clock_device_id') AS clock_device_id + FROM memory_items WHERE id = ?`) + .get(id), + ).toEqual({ rev: 4, updated_at: now, clock_device_id: peer }); + expect(db().prepare("SELECT COUNT(*) FROM replication_ops").pluck().get()).toBe(0); +}); diff --git a/packages/core/src/project-move-device.ts b/packages/core/src/project-move-device.ts new file mode 100644 index 000000000..fdc695ed3 --- /dev/null +++ b/packages/core/src/project-move-device.ts @@ -0,0 +1,430 @@ +import { + closeSync, + constants, + fsyncSync, + linkSync, + lstatSync, + mkdtempSync, + openSync, + rmSync, +} from "node:fs"; +import { dirname, join } from "node:path"; +import { setImmediate } from "node:timers/promises"; +import { unassignedProjectIdentity } from "./coordinator-project-moves.js"; +import { readCoordinatorSyncConfig } from "./coordinator-sync-config.js"; +import { type Database, tableExists } from "./db.js"; +import { claimLocalOrigin, hasUnattributedOrigin } from "./local-origin-claim.js"; +import { managedProjectScopeId } from "./managed-project-scope.js"; +import { + listProjectBoundaryMigrationRecords, + recordProjectBoundaryMigration, +} from "./project-boundary-migration-records.js"; +import { reconcilePreviouslyPulledProjectMove } from "./project-move-arrival.js"; +import { + canonicalRepositoryProjectIdentity, + readRepositoryIdentitySnapshot, + repositoryIdentitiesByWorkspace, + repositoryIdentityForWorkspace, + withRepositoryMappingAliasesFromIdentities, +} from "./repository-mapping-aliases.js"; +import { getEffectiveCachedScopeAuthorization } from "./scope-membership-cache-read.js"; +import { resolveProjectScope } from "./scope-resolution.js"; +import type { MemoryStore } from "./store.js"; +import { SYNC_BOOTSTRAP_CWD_PREFIX } from "./sync-bootstrap-constants.js"; +import { canonicalWorkspaceIdentity } from "./workspace-identity.js"; + +type Move = { source_scope_id: string; boundary_scope_id: string }; +type Authority = { groupId: string; coordinatorId: string }; +type ProjectMapping = { + id: number; + workspace_identity: string | null; + project_pattern: string; + scope_id: string; + source: string; + priority: number; + updated_at: string; +}; +type MemoryEvidence = { + id: number; + cwd: string | null; + project: string | null; + git_remote: string | null; + metadata_json: string | null; + workspace_id: string | null; + origin_device_id: string | null; +}; +const MOVE_MAPPING = "project_boundary_migration"; +const BATCH_SIZE = 200; + +export function parseProjectMoves(body: unknown, groupId: string): Move[] { + const moves = (body as { moves?: unknown } | null)?.moves; + if (!Array.isArray(moves)) throw new Error("Coordinator Project moves response invalid."); + return moves.flatMap((move) => { + if (move?.version !== 1 || move.group_id !== groupId) return []; + const { source_scope_id, boundary_scope_id } = move; + if ( + typeof source_scope_id !== "string" || + !source_scope_id || + source_scope_id.trim() !== source_scope_id || + typeof boundary_scope_id !== "string" || + !/^managed-project:[a-f0-9]{64}$/u.test(boundary_scope_id) + ) + return []; + return [{ source_scope_id, boundary_scope_id }]; + }); +} + +function recordedRepositories(db: Database) { + return repositoryIdentitiesByWorkspace(db, { + repositoryIdentitySnapshot: { ...readRepositoryIdentitySnapshot(db), workspaces: [] }, + }); +} + +const MEMORY_EVIDENCE = `SELECT m.id, s.cwd, COALESCE(m.project, s.project) AS project, s.git_remote, + s.metadata_json, m.workspace_id, m.origin_device_id + FROM memory_items m LEFT JOIN sessions s ON m.session_id = s.id + WHERE m.scope_id = ? AND m.active = 1 AND m.deleted_at IS NULL`; + +function localProject(row: MemoryEvidence, repos: ReadonlyMap, source: string) { + const cwd = row.cwd?.startsWith(SYNC_BOOTSTRAP_CWD_PREFIX) ? null : row.cwd; + const identity = canonicalWorkspaceIdentity({ + cwd, + project: row.project, + gitRemote: row.git_remote, + repositoryIdentity: repositoryIdentityForWorkspace(repos, { + cwd, + gitRemote: row.git_remote, + metadataJson: row.metadata_json, + }), + workspaceId: row.workspace_id === "shared:default" ? null : row.workspace_id, + }); + if (identity.source !== "unmapped") + return canonicalRepositoryProjectIdentity(repos, identity.value); + return row.project?.trim() ? null : unassignedProjectIdentity(source); +} + +function authorizedBoundary(db: Database, scopeId: string, authority?: Authority) { + const self = db.prepare("SELECT device_id, public_key FROM sync_device").get() as + | { device_id: string; public_key: string } + | undefined; + if (!self) return null; + const proof = getEffectiveCachedScopeAuthorization(db, { + scopeId, + deviceId: self.device_id, + expectedPublicKey: self.public_key, + authority, + }); + if ( + !proof.authorized || + proof.scope?.kind !== "managed_project" || + proof.scope.authority_type !== "coordinator" + ) + return null; + if ( + authority && + (proof.scope.group_id !== authority.groupId || + proof.scope.coordinator_id !== authority.coordinatorId) + ) + return null; + return self.device_id; +} + +function isOlderScope(db: Database, source: string, authority: Authority) { + return ( + db + .prepare(`SELECT 1 FROM replication_scopes WHERE scope_id = ? AND coordinator_id = ? + AND group_id = ? AND authority_type = 'coordinator' AND status = 'active' + AND kind NOT IN ('managed_project', 'personal') + AND scope_id NOT IN ('local-default', 'legacy-shared-review') + AND scope_id NOT LIKE 'personal:%' AND scope_id NOT LIKE 'managed-project:%'`) + .get(source, authority.coordinatorId, authority.groupId) !== undefined + ); +} + +function matchingProject( + db: Database, + move: Move, + groupId: string, + mappings: ProjectMapping[], + repos: ReadonlyMap, +) { + const source = move.source_scope_id; + const matches = (project: string) => + managedProjectScopeId(groupId, project) === move.boundary_scope_id; + const projects = new Set( + mappings.flatMap(({ workspace_identity }) => + workspace_identity ? canonicalRepositoryProjectIdentity(repos, workspace_identity) : [], + ), + ); + const project = [...projects].find(matches); + if (project) return project; + for (const row of db.prepare(MEMORY_EVIDENCE).iterate(source) as Iterable) { + const identity = localProject(row, repos, source); + if (identity && matches(identity)) return identity; + } + // An empty older scope can have an Unassigned boundary, but has no local history to move. + return null; +} + +/** Called in the cache write transaction before peers can use a newly issued boundary proof. */ +export function adoptProjectMoves( + db: Database, + authority: Authority, + moves: readonly Move[], + { remapProjects }: { remapProjects: boolean }, +) { + if (!moves.length) return; + const previous = new Map( + listProjectBoundaryMigrationRecords(db).map((row) => [row.boundaryScopeId, row]), + ); + const eligible = moves.filter(({ boundary_scope_id: id }) => + authorizedBoundary(db, id, authority), + ); + if (!eligible.length) return; + const repos = remapProjects ? recordedRepositories(db) : null; + const allMappings = () => + db + .prepare( + `SELECT id, workspace_identity, project_pattern, scope_id, source, priority, updated_at + FROM project_scope_mappings ORDER BY id`, + ) + .all() as ProjectMapping[]; + for (const move of eligible) { + const { source_scope_id: source, boundary_scope_id: boundary } = move; + const existing = previous.get(boundary); + if (existing && (existing.state !== "committed" || existing.sourceScopeId !== source)) + throw new Error("Local Project move conflicts with an existing record."); + // Record receive-only moves too. The cache transaction also publishes the + // proof, so a peer cannot pull a new boundary before this record is visible. + if (!existing) { + previous.set(boundary, recordLocalMove(db, source, boundary)); + reconcilePreviouslyPulledProjectMove(db, source, boundary); + } + if (!repos || !isOlderScope(db, source, authority)) continue; + remapProject(db, move, authority.groupId, allMappings(), repos); + } +} + +function remapProject( + db: Database, + move: Move, + groupId: string, + mappings: ProjectMapping[], + repos: ReadonlyMap, +) { + const source = move.source_scope_id; + const project = matchingProject(db, move, groupId, mappings, repos); + if (!project) return; + const aliases = mappings.filter( + (row) => + row.workspace_identity && + canonicalRepositoryProjectIdentity(repos, row.workspace_identity) === project, + ); + if (aliases.some((row) => row.scope_id !== source)) return; + const current = resolveProjectScope({ + repositoryIdentity: project, + mappings: withRepositoryMappingAliasesFromIdentities(mappings, repos), + }); + if (project !== unassignedProjectIdentity(source) && current.scopeId !== source) return; + replaceProjectMapping(db, move.boundary_scope_id, project, aliases); +} + +function recordLocalMove(db: Database, source: string, boundary: string) { + // This committed local record is also the recipient reconciler hold until + // the admin's recipient transaction clears it. + const record = { + sourceScopeId: source, + boundaryScopeId: boundary, + state: "committed" as const, + generation: 1, + additionalSourceScopeIds: [], + }; + if (!recordProjectBoundaryMigration(db, record)) + throw new Error("Local Project move conflicts with an existing record."); + return record; +} + +function replaceProjectMapping( + db: Database, + boundary: string, + project: string, + replaced: ProjectMapping[], +) { + const remove = db.prepare("DELETE FROM project_scope_mappings WHERE id = ?"); + for (const row of replaced) remove.run(row.id); + const now = new Date().toISOString(); + db.prepare(`INSERT INTO project_scope_mappings + (workspace_identity, project_pattern, scope_id, priority, source, created_at, updated_at) + VALUES (?, ?, ?, 0, ?, ?, ?)`).run(project, project, boundary, MOVE_MAPPING, now, now); +} + +export function projectMoveSourceCounts(db: Database) { + const sources = new Set( + listProjectBoundaryMigrationRecords(db) + .filter((move) => move.state === "committed") + .map((move) => move.sourceScopeId), + ); + if (!sources.size) return []; + const count = db.prepare("SELECT count(*) FROM memory_items WHERE scope_id = ?").pluck(); + return [...sources].sort().map((source_scope_id) => ({ + source_scope_id, + remaining_rows: Number(count.get(source_scope_id)), + })); +} + +export function projectMoveBackupInfo(db: Database) { + if (db.memory || !db.name) return null; + const path = `${db.name}.before-project-moves.sqlite`; + const info = lstatSync(path, { throwIfNoEntry: false }); + return info?.isFile() ? { path, size_bytes: info.size } : null; +} + +function safeExistingBackup(path: string): boolean { + const info = lstatSync(path, { throwIfNoEntry: false }); + if (!info) return false; + if (!info.isFile() || (info.mode & 0o777) !== 0o600 || info.size === 0) + throw new Error("Project move backup is not a private, regular file."); + return true; +} + +async function ensureBackup(db: Database) { + if (db.memory || !db.name) throw new Error("Project moves require a file-backed database."); + const backup = `${db.name}.before-project-moves.sqlite`; + if (safeExistingBackup(backup)) { + syncBackupPath(dirname(backup)); + return; + } + const directory = mkdtempSync(join(dirname(db.name), ".project-move-backup-")); + const temporary = join(directory, "store.sqlite"); + try { + closeSync(openSync(temporary, "wx", 0o600)); + await db.backup(temporary); + syncBackupPath(temporary); + try { + linkSync(temporary, backup); + } catch (error) { + if ( + !( + error instanceof Error && + "code" in error && + error.code === "EEXIST" && + safeExistingBackup(backup) + ) + ) + throw error; + } + syncBackupPath(dirname(backup)); + } finally { + rmSync(directory, { recursive: true }); + } +} + +function syncBackupPath(path: string): void { + const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW); + try { + fsyncSync(fd); + } finally { + closeSync(fd); + } +} + +function pendingMoves(db: Database) { + return listProjectBoundaryMigrationRecords(db).flatMap((move) => { + if (move.state !== "committed") return []; + const project = db + .prepare(`SELECT workspace_identity FROM project_scope_mappings + WHERE scope_id = ? AND source = ? LIMIT 1`) + .pluck() + .get(move.boundaryScopeId, MOVE_MAPPING); + return typeof project === "string" ? [{ ...move, project }] : []; + }); +} + +export function hasLocalProjectMoves(db: Database): boolean { + return ( + tableExists(db, "project_boundary_migrations") && + pendingMoves(db).some((move) => + db + .prepare(`SELECT 1 FROM memory_items WHERE scope_id = ? AND active = 1 AND deleted_at IS NULL + AND (origin_device_id = (SELECT device_id FROM sync_device LIMIT 1) + OR COALESCE(TRIM(origin_device_id), '') IN ('', 'local')) LIMIT 1`) + .get(move.sourceScopeId), + ) + ); +} + +type PendingMove = ReturnType[number]; + +function needsAttention(db: Database): boolean { + return ( + db.prepare("SELECT phase FROM sync_daemon_state WHERE id = 1").pluck().get() === + "needs_attention" + ); +} + +function authoredBy(store: MemoryStore, row: MemoryEvidence): boolean { + return ( + row.origin_device_id === store.deviceId || + (hasUnattributedOrigin(row.origin_device_id) && + claimLocalOrigin(store.db, row.id, store.deviceId)) + ); +} + +function canContinue(store: MemoryStore, move: PendingMove) { + const { db } = store; + if (needsAttention(db) || authorizedBoundary(db, move.boundaryScopeId) !== store.deviceId) + return false; + return ( + db + .prepare(`SELECT 1 FROM project_scope_mappings + WHERE workspace_identity = ? AND scope_id = ? AND source = ?`) + .get(move.project, move.boundaryScopeId, MOVE_MAPPING) !== undefined + ); +} + +function moveBatch( + store: MemoryStore, + move: PendingMove, + repos: ReadonlyMap, + after: number, +) { + const { db } = store; + return db + .transaction(() => { + if (!canContinue(store, move)) return null; + const rows = db + .prepare(`${MEMORY_EVIDENCE} + AND m.id > ? AND (m.origin_device_id = ? OR COALESCE(TRIM(m.origin_device_id), '') IN ('', 'local')) + ORDER BY m.id LIMIT ?`) + .all(move.sourceScopeId, after, store.deviceId, BATCH_SIZE) as MemoryEvidence[]; + for (const row of rows) { + if (localProject(row, repos, move.sourceScopeId) !== move.project) continue; + if (!authoredBy(store, row)) continue; + store.reassignMemoryScope(row.id, move.boundaryScopeId); + } + return rows.length === BATCH_SIZE ? (rows.at(-1)?.id ?? null) : null; + }) + .immediate(); +} + +/** Restarting scans what still carries the source; a completed row needs no progress cursor. */ +export async function restampLocalProjectMoves( + store: MemoryStore, + yieldBatch: () => Promise = setImmediate, +) { + if (!readCoordinatorSyncConfig().syncBoundaryMigrationEnabled) return; + const { db } = store; + const moves = pendingMoves(db); + if (!moves.length || needsAttention(db)) return; + await ensureBackup(db); + if (!readCoordinatorSyncConfig().syncBoundaryMigrationEnabled) return; + const repos = recordedRepositories(db); + for (const move of moves) { + let after = moveBatch(store, move, repos, 0); + while (after !== null) { + await yieldBatch(); + if (!readCoordinatorSyncConfig().syncBoundaryMigrationEnabled) return; + after = moveBatch(store, move, repos, after); + } + } +} diff --git a/packages/core/src/scope-membership-cache-on-demand.test.ts b/packages/core/src/scope-membership-cache-on-demand.test.ts index a01470243..9b5cb6839 100644 --- a/packages/core/src/scope-membership-cache-on-demand.test.ts +++ b/packages/core/src/scope-membership-cache-on-demand.test.ts @@ -86,7 +86,7 @@ beforeEach(async () => { }; request.mockImplementation( async (_method, url) => - [200, url.includes("/members?") ? snapshot : { version: 1, items: [scope] }] as Awaited< + [200, url.includes("/members?") ? snapshot : catalogueOrMoves(url)] as Awaited< ReturnType >, ); @@ -95,6 +95,11 @@ beforeEach(async () => { request.mockClear(); }); +function catalogueOrMoves(url: string) { + if (url.includes("/project-moves?")) return { moves: [] }; + return { version: 1, items: [scope] }; +} + afterEach(() => { db.close(); rmSync(directory, { recursive: true, force: true }); @@ -104,11 +109,48 @@ afterEach(() => { }); describe("on-demand scope authorization", () => { + it("reads the group's move log with the current device's signature", async () => { + const older = { ...scope, scope_id: "team:group-a:default", kind: "team_default" }; + const sourceSnapshot = { + ...snapshot, + scope: older, + items: snapshot.items.map((item) => ({ + ...item, + membership: { + ...item.membership, + scope_id: older.scope_id, + }, + })), + }; + request.mockImplementation(async (_method, url) => { + if (url.includes("/v1/project-moves?")) return [200, { moves: [] }]; + if (url.includes("/members?")) + return [200, url.includes(encodeURIComponent(older.scope_id)) ? sourceSnapshot : snapshot]; + return [200, { version: 1, items: [scope, older] }]; + }); + + expect( + (await refreshConfiguredScopeMembershipCache(db, config, { keysDir, dbPath })).status, + ).toBe("refreshed"); + + expect(request).toHaveBeenCalledWith( + "GET", + `${coordinatorId}/v1/project-moves?group_id=group-a`, + expect.objectContaining({ + redirect: "error", + headers: expect.objectContaining({ + "X-Opencode-Device": db.prepare("SELECT device_id FROM sync_device").pluck().get(), + "X-Opencode-Signature": expect.stringMatching(/^v2:/u), + }), + }), + ); + }); + it("revalidates the 61-second stale cache before the next 120-second daemon tick", async () => { vi.setSystemTime(new Date(Date.parse(cacheTime) + 61_000)); expect(relayPeerScopes(db, "peer-a", coordinatorId)).toHaveLength(0); await refreshConfiguredScopeMembershipCache(db, config, { keysDir, dbPath, onlyIfStale: true }); - expect(request).toHaveBeenCalledTimes(2); + expect(request).toHaveBeenCalledTimes(3); expect(relayPeerScopes(db, "peer-a", coordinatorId)).toHaveLength(1); }); @@ -121,7 +163,7 @@ describe("on-demand scope authorization", () => { it("preserves the daemon's unconditional refresh behavior", async () => { await refreshConfiguredScopeMembershipCache(db, config, { keysDir, dbPath }); - expect(request).toHaveBeenCalledTimes(2); + expect(request).toHaveBeenCalledTimes(3); }); it("ignores stale cache records for authorities that are not configured", async () => { @@ -160,7 +202,7 @@ describe("on-demand scope authorization", () => { items: snapshot.items.filter((item) => item.membership.device_id !== "peer-a"), }; await refreshConfiguredScopeMembershipCache(db, config, { keysDir, dbPath, onlyIfStale: true }); - expect(request).toHaveBeenCalledTimes(2); + expect(request).toHaveBeenCalledTimes(3); expect(relayPeerScopes(db, "peer-a", coordinatorId)).toHaveLength(0); }); @@ -185,7 +227,7 @@ describe("on-demand refresh of a transitioned group", () => { function echoingCoordinator() { request.mockImplementation(async (_method, url, options) => { const nonce = (options?.headers as Record | undefined)?.["X-Opencode-Nonce"]; - const body = url.includes("/members?") ? snapshot : { version: 1, items: [scope] }; + const body = url.includes("/members?") ? snapshot : catalogueOrMoves(url); return [200, { ...body, request_nonce: nonce }] as Awaited>; }); } @@ -209,7 +251,7 @@ describe("on-demand refresh of a transitioned group", () => { onlyIfStale: true, }); expect(result.status).toBe("refreshed"); - expect(request).toHaveBeenCalledTimes(2); + expect(request).toHaveBeenCalledTimes(3); expect(relayPeerScopes(db, "peer-a", coordinatorId)).toHaveLength(1); request.mockClear(); await refreshConfiguredScopeMembershipCache(db, config, { keysDir, dbPath, onlyIfStale: true }); @@ -244,7 +286,7 @@ describe("a transitioned group's refresh over plain HTTP", () => { // Anyone on the path can copy the request's nonce into an earlier answer. request.mockImplementation(async (_method, url, options) => { const nonce = (options?.headers as Record | undefined)?.["X-Opencode-Nonce"]; - const body = url.includes("/members?") ? snapshot : { version: 1, items: [scope] }; + const body = url.includes("/members?") ? snapshot : catalogueOrMoves(url); return [200, { ...body, request_nonce: nonce }] as Awaited>; }); const result = await refreshScopeMembershipCache(db, { @@ -282,7 +324,7 @@ describe("a transitioned group under a coordinator URL override", () => { // Every answer names the scope's original authority and echoes the request's nonce. request.mockImplementation(async (_method, url, options) => { const nonce = (options?.headers as Record | undefined)?.["X-Opencode-Nonce"]; - const body = url.includes("/members?") ? snapshot : { version: 1, items: [scope] }; + const body = url.includes("/members?") ? snapshot : catalogueOrMoves(url); return [200, { ...body, request_nonce: nonce }] as Awaited>; }); }); diff --git a/packages/core/src/scope-membership-cache-read.ts b/packages/core/src/scope-membership-cache-read.ts index 896acd1c5..bd9f88461 100644 --- a/packages/core/src/scope-membership-cache-read.ts +++ b/packages/core/src/scope-membership-cache-read.ts @@ -3,7 +3,10 @@ import type { CoordinatorScope, CoordinatorScopeMembership } from "./coordinator-store-contract.js"; import type { Database } from "./db.js"; import { isScopeDeviceAdmissionRefused } from "./scope-device-admission.js"; -import { getRetainedScopeAuthorizationKey } from "./scope-membership-evidence.js"; +import { + getRetainedScopeAuthorizationKey, + getRetainedScopeAuthorizationMember, +} from "./scope-membership-evidence.js"; import { explainScopeMembershipRevocation, type ScopeMembershipEpochStatus, @@ -346,6 +349,24 @@ export function getEffectiveCachedScopeAuthorization( return { ...cached, keyId }; } +/** The identity bound to this scope member by the coordinator's retained proof. */ +export function getVerifiedScopeEnrollmentIdentity( + db: Database, + input: { deviceId: string; scopeId: string } & Partial, +): string | null { + const cached = readCachedScopeAuthorization(db, input); + if (!cached.authorized || cached.scope?.authority_type !== "coordinator" || !cached.membership) + return null; + const proof = getRetainedScopeAuthorizationMember( + db, + cached.scope, + cached.membership, + "expectedPublicKey" in input ? input.expectedPublicKey : undefined, + "expectedFingerprint" in input ? input.expectedFingerprint : undefined, + ); + return proof?.enrollment.identity_id ?? null; +} + function readCachedScopeAuthorization( db: Database, input: { deviceId: string; scopeId: string } & ScopeMembershipCacheLookupOptions, diff --git a/packages/core/src/scope-membership-cache.ts b/packages/core/src/scope-membership-cache.ts index 5f8db0e57..d763ef84f 100644 --- a/packages/core/src/scope-membership-cache.ts +++ b/packages/core/src/scope-membership-cache.ts @@ -1,6 +1,7 @@ import { randomBytes } from "node:crypto"; import { markCoordinatorManaged } from "./coordinator-free-attestation.js"; import { ensureCoordinatorHistorySchema } from "./coordinator-history.js"; +import { PROJECT_MOVES_PATH } from "./coordinator-project-moves.js"; import { BetterSqliteCoordinatorStore, DEFAULT_COORDINATOR_DB_PATH } from "./coordinator-store.js"; import type { CoordinatorScope, CoordinatorScopeMembership } from "./coordinator-store-contract.js"; import { @@ -9,6 +10,7 @@ import { readCoordinatorSyncConfig, } from "./coordinator-sync-config.js"; import type { Database } from "./db.js"; +import { adoptProjectMoves, parseProjectMoves } from "./project-move-device.js"; import { columnExists, schemaObjectExists } from "./schema-lookups.js"; import { listCachedScopesForDevice, @@ -66,6 +68,7 @@ export interface ScopeMembershipRequest { export interface ScopeMembershipCacheFetchers { listScopes(groupId: string, request: ScopeMembershipRequest): Promise; + listProjectMoves?(groupId: string): Promise; getScopeSnapshot( groupId: string, scopeId: string, @@ -75,6 +78,7 @@ export interface ScopeMembershipCacheFetchers { export interface RefreshScopeMembershipCacheOptions { groupIds: string[]; + syncBoundaryMigrationEnabled?: boolean; coordinatorId?: string | null; remoteUrl?: string | null; adminSecret?: string | null; @@ -185,6 +189,7 @@ function signedCoordinatorGet( request: ScopeMembershipRequest, keysDir?: string | null, dbPath?: string, + options?: { allowUnavailable: boolean }, ): Promise | null> { const [deviceId] = ensureDeviceIdentity(db, { keysDir: keysDir ?? undefined }); const bodyBytes = Buffer.alloc(0); @@ -201,6 +206,7 @@ function signedCoordinatorGet( headers, redirect: "error", }).then(([status, payload]) => { + if (options?.allowUnavailable && (status === 404 || status === 503)) return { moves: [] }; if (status < 200 || status >= 300) { throw new Error(`Coordinator membership snapshot failed (${status})`); } @@ -216,6 +222,15 @@ function authenticatedFetchers( const get = (url: string, request: ScopeMembershipRequest) => signedCoordinatorGet(db, url, request, opts.keysDir, opts.dbPath); return { + listProjectMoves: (groupId) => + signedCoordinatorGet( + db, + `${baseUrl}${PROJECT_MOVES_PATH}?group_id=${encodeURIComponent(groupId)}`, + newRequest(), + opts.keysDir, + opts.dbPath, + { allowUnavailable: true }, + ), listScopes: async (groupId, request) => (await get( `${baseUrl}/v1/scopes?group_id=${encodeURIComponent(groupId)}`, @@ -236,6 +251,10 @@ function defaultFetchers( if (clean(opts.remoteUrl)) return authenticatedFetchers(db, opts); // A coordinator file read in this process has no transport, so its answers are this request's. return { + listProjectMoves: (groupId) => + withLocalCoordinator(opts, async (store) => ({ + moves: (await store.listProjectMoves(groupId)) ?? [], + })), listScopes: (groupId, request) => withLocalCoordinator(opts, async (store) => ({ version: 1, @@ -507,6 +526,7 @@ export async function refreshScopeMembershipCache( const expected = { revision: expectedRevision, removalGeneration: readScopeAuthorizationRemovalGeneration(db), + remapProjects: opts.syncBoundaryMigrationEnabled === true, }; requireTransitionedTransport(db, authority, opts); const snapshot = await gatherCurrentSnapshots(fetchers, authority); @@ -609,7 +629,18 @@ async function gatherCurrentSnapshots( normalizeScopeSnapshot(snapshot, scope, authority.groupId, authority.coordinatorId), ); } - return { batches, bound }; + const moves = await readMovesForSnapshot(fetchers, authority.groupId, batches); + return { batches, bound, moves }; +} + +async function readMovesForSnapshot( + fetchers: ScopeMembershipCacheFetchers, + groupId: string, + batches: CurrentScopeBatch[], +) { + if (!fetchers.listProjectMoves || !batches.some(({ scope }) => scope.kind === "managed_project")) + return []; + return parseProjectMoves(await fetchers.listProjectMoves(groupId), groupId); } /** @@ -690,10 +721,10 @@ function migrateSnapshotMembershipAuthority(db: Database, batch: CurrentScopeBat function persistCurrentSnapshots( db: Database, - { batches }: { batches: CurrentScopeBatch[] }, + { batches, moves }: Awaited>, authority: ScopeMembershipCacheAuthority, timestamp: string, - expected: { revision: number; removalGeneration: number }, + expected: { revision: number; removalGeneration: number; remapProjects: boolean }, ): string | null { return db .transaction(() => { @@ -728,6 +759,8 @@ function persistCurrentSnapshots( } catch { throw new Error("Scope authorization evidence unavailable."); } + if (!error) + adoptProjectMoves(db, authority, moves, { remapProjects: expected.remapProjects }); recordRefreshState(db, { ...authority, ok: error === null, error, now: timestamp }); return error; }) @@ -767,6 +800,7 @@ export async function refreshConfiguredScopeMembershipCache( } return refreshScopeMembershipCache(db, { groupIds: syncConfig.syncCoordinatorGroups, + syncBoundaryMigrationEnabled: syncConfig.syncBoundaryMigrationEnabled, coordinatorId: authorityId(syncConfig.syncCoordinatorUrl), remoteUrl: syncConfig.syncCoordinatorUrl, adminSecret: syncConfig.syncCoordinatorAdminSecret, diff --git a/packages/core/src/scope-membership-evidence.ts b/packages/core/src/scope-membership-evidence.ts index b6a562aea..f150d0bd2 100644 --- a/packages/core/src/scope-membership-evidence.ts +++ b/packages/core/src/scope-membership-evidence.ts @@ -134,6 +134,7 @@ function sameProof(previous: Batch, current: Batch): boolean { "group_id", "device_id", "fingerprint", + "identity_id", "enabled", ]) ); @@ -222,6 +223,19 @@ export function getRetainedScopeAuthorizationKey( expectedPublicKey?: string, expectedFingerprint?: string, ): string | null { + return ( + getRetainedScopeAuthorizationMember(db, scope, member, expectedPublicKey, expectedFingerprint) + ?.key_id ?? null + ); +} + +export function getRetainedScopeAuthorizationMember( + db: Database, + scope: CoordinatorScope, + member: CoordinatorScopeMembership, + expectedPublicKey?: string, + expectedFingerprint?: string, +): ScopeMembershipSnapshot["items"][number] | null { try { if (!scope.coordinator_id || !scope.group_id || !scopeEvidenceTableExists(db)) return null; const authority = { coordinatorId: scope.coordinator_id, groupId: scope.group_id }; @@ -233,7 +247,8 @@ export function getRetainedScopeAuthorizationKey( | undefined; const proof = row && parseEvidence(row.evidence_json, authority); if (!proof || !matchesRows(proof, scope, member)) return null; - const keyId = proof.evidence.items[0]?.key_id; + const captured = proof.evidence.items[0]; + const keyId = captured?.key_id; if (!keyId) return null; if (expectedPublicKey !== undefined) { const parsed = parseSshEd25519PublicKeyForRevocation(expectedPublicKey); @@ -245,14 +260,14 @@ export function getRetainedScopeAuthorizationKey( } // A pin with no stored key binds the proof through the fingerprint of the enrolled key. if (expectedFingerprint !== undefined) { - const enrolledKey = proof.evidence.items[0]?.enrollment.public_key; + const enrolledKey = captured.enrollment.public_key; if ( typeof enrolledKey !== "string" || fingerprintPublicKey(enrolledKey) !== expectedFingerprint ) return null; } - return keyId; + return captured; } catch { return null; } diff --git a/packages/core/src/snapshot-cross-scope-reconcile.ts b/packages/core/src/snapshot-cross-scope-reconcile.ts index 6199e8f54..efeee0f5e 100644 --- a/packages/core/src/snapshot-cross-scope-reconcile.ts +++ b/packages/core/src/snapshot-cross-scope-reconcile.ts @@ -10,6 +10,7 @@ import { getEffectiveCachedScopeAuthorization, } from "./scope-membership-cache-read.js"; import { clockDeviceIdFromMetadataJson, isNewerClock } from "./sync-replication.js"; +import { storedSyncVisibilityAllowed } from "./sync-visibility.js"; import type { SyncMemorySnapshotItem } from "./types.js"; /* @@ -37,8 +38,11 @@ export interface CrossScopeSnapshotContext { /** False when this device holds no migration record, so no item is ever held back. */ readonly hasRecords: boolean; decide(item: SyncMemorySnapshotItem, itemScopeId: string): CrossScopeDecision; + omittedOrigin(item: SyncMemorySnapshotItem, itemScopeId: string): SnapshotMoveOrigin; } +export type SnapshotMoveOrigin = { kind: "hold" } | { kind: "apply"; origin: string | null }; + interface HeldCopy { id: number; scope_id: string | null; @@ -46,6 +50,7 @@ interface HeldCopy { updated_at: string; metadata_json: string | null; origin_device_id: string | null; + visibility: string | null; } interface Party { @@ -54,7 +59,12 @@ interface Party { } const APPLY: CrossScopeDecision = { kind: "apply" }; -const NO_RECORDS: CrossScopeSnapshotContext = { hasRecords: false, decide: () => APPLY }; +const UNKNOWN_ORIGIN: SnapshotMoveOrigin = { kind: "apply", origin: null }; +const NO_RECORDS: CrossScopeSnapshotContext = { + hasRecords: false, + decide: () => APPLY, + omittedOrigin: () => UNKNOWN_ORIGIN, +}; /** The states in which stale-row cleanup removes what a peer sent into a scope. */ const LEFT_SCOPE_STATES = new Set(["revoked", "scope_inactive", "stale_epoch"]); @@ -120,7 +130,7 @@ class RecordedMoves implements CrossScopeSnapshotContext { private coveredCopies(importKey: string, itemScopeId: string): HeldCopy[] { const held = this.db .prepare( - `SELECT id, scope_id, rev, updated_at, metadata_json, origin_device_id + `SELECT id, scope_id, rev, updated_at, metadata_json, origin_device_id, visibility FROM memory_items WHERE import_key = ? AND COALESCE(scope_id, '') != ? AND COALESCE(visibility, '') != 'private' @@ -162,6 +172,18 @@ class RecordedMoves implements CrossScopeSnapshotContext { return getVerifiedMemorySource(this.db, importKey)?.sourceDeviceId === this.serving.deviceId; } + omittedOrigin(item: SyncMemorySnapshotItem, itemScopeId: string): SnapshotMoveOrigin { + if (!tableExists(this.db, "memory_source_bindings")) return UNKNOWN_ORIGIN; + const creator = getVerifiedMemorySource(this.db, item.entity_id)?.sourceDeviceId; + if (!creator) return UNKNOWN_ORIGIN; + if (creator === this.serving.deviceId) return { kind: "apply", origin: creator }; + // A legacy item that omits its origin cannot bypass the source's snapshot policy. + const held = this.coveredCopies(item.entity_id, itemScopeId).some( + (copy) => storedSyncVisibilityAllowed(copy) && this.settle(item, copy) === "hold_back", + ); + return held ? { kind: "hold" } : UNKNOWN_ORIGIN; + } + /** * What happens to one held copy when the item is applied. * - `replace`: the item is newer, and the serving peer could have rewritten the @@ -197,7 +219,12 @@ class RecordedMoves implements CrossScopeSnapshotContext { export function crossScopeSnapshotContext( db: Database, peerDeviceId: string, + mode: "legacy" | "one-way" = "legacy", ): CrossScopeSnapshotContext { - const records = listProjectBoundaryMigrationRecords(db); + // Keep the old snapshot behavior for records left by the rollback and multi-source paths. + const records = listProjectBoundaryMigrationRecords(db).filter((record) => { + const oneWay = record.state === "committed" && record.additionalSourceScopeIds.length === 0; + return mode === "one-way" ? oneWay : !oneWay; + }); return records.length === 0 ? NO_RECORDS : new RecordedMoves(db, records, peerDeviceId); } diff --git a/packages/core/src/sync-bootstrap.ts b/packages/core/src/sync-bootstrap.ts index 79625e22c..9ea8f2d5b 100644 --- a/packages/core/src/sync-bootstrap.ts +++ b/packages/core/src/sync-bootstrap.ts @@ -18,6 +18,13 @@ import type { Database } from "./db.js"; import { toJson } from "./db.js"; import { recordForeignMemoryRevision } from "./memory-creation-provenance.js"; import { retirementAllowsSnapshot } from "./memory-retirement-snapshot-guard.js"; +import { + decideProjectMoveArrival, + deleteMoveCopy, + keepMoveCopy, + projectMovePairs, + stampMoveMetadata, +} from "./project-move-arrival.js"; import { isProjectScopeWithdrawn } from "./project-scope-withdrawal.js"; import * as schema from "./schema.js"; import { redactMemoryFields, SecretScanner } from "./secret-scanner.js"; @@ -25,12 +32,14 @@ import { snapshotSessionExportKeysForMemoryIds } from "./session-export-identity import { type CrossScopeSnapshotContext, crossScopeSnapshotContext, + type SnapshotMoveOrigin, } from "./snapshot-cross-scope-reconcile.js"; import { buildAuthHeaders, buildDirectPeerAuthHeaders } from "./sync-auth.js"; import { SYNC_BOOTSTRAP_CWD_PREFIX } from "./sync-bootstrap-constants.js"; import { LOCAL_SYNC_CAPABILITY, SYNC_CAPABILITY_HEADER } from "./sync-capability.js"; import { parseSyncEntryTooLarge, SyncEntryTooLargeReply } from "./sync-entry-size.js"; import { type RequestJsonExecutor, requestJson } from "./sync-http-client.js"; +import { copiesInSyncScope, storedSyncVisibilityFields } from "./sync-memory-copies.js"; import { clearReplicationCursorLastApplied, clockDeviceIdFromMetadataJson, @@ -46,6 +55,7 @@ import { recordSyncTransferReceipts, } from "./sync-transfer-activity.js"; import { DIRECT_NOISE_ACTIVE } from "./sync-transport-policy.js"; +import { storedSyncVisibilityAllowed, syncVisibilityAllowed } from "./sync-visibility.js"; import { TransferPausedError } from "./transitioned-transfer-window.js"; import type { SyncMemorySnapshotItem, SyncResetRequired } from "./types.js"; import { queueVectorBackfillForSyncBootstrap } from "./vector-migration.js"; @@ -485,30 +495,6 @@ function insertSnapshotItem( return { applied: true, embeddable: !isDeleted && isEmbeddableSnapshotPayload(payload) }; } -/** Copies of the item's memory that this device holds in the scope being merged. */ -function copiesInSnapshotScope( - d: ReturnType, - item: SyncMemorySnapshotItem, - scopePredicate: SQL | undefined, -): ExistingSnapshotRow[] { - return d - .select({ - id: schema.memoryItems.id, - rev: schema.memoryItems.rev, - updated_at: schema.memoryItems.updated_at, - metadata_json: schema.memoryItems.metadata_json, - }) - .from(schema.memoryItems) - .where( - and( - eq(schema.memoryItems.import_key, item.entity_id), - scopePredicate, - ne(sql`COALESCE(${schema.memoryItems.visibility}, '')`, "private"), - ), - ) - .all(); -} - interface SnapshotTarget { db: Database; d: ReturnType; @@ -516,7 +502,9 @@ interface SnapshotTarget { scopeId: string | null; scanner: SecretScanner; result: BootstrapResult; - crossScope: CrossScopeSnapshotContext; + moves: ReturnType; + legacyMoves: CrossScopeSnapshotContext; + omittedMoveOrigins: CrossScopeSnapshotContext; } function snapshotTarget( @@ -533,7 +521,9 @@ function snapshotTarget( scopeId, scanner, result, - crossScope: crossScopeSnapshotContext(db, peerDeviceId), + moves: projectMovePairs(db), + legacyMoves: crossScopeSnapshotContext(db, peerDeviceId), + omittedMoveOrigins: crossScopeSnapshotContext(db, peerDeviceId, "one-way"), }; } @@ -541,16 +531,37 @@ function snapshotTarget( * The memories a scope holds before a first pull clears it. Read only when this * device has a migration record, the one case in which an item can be held back. */ -function keysHeldInScope(target: SnapshotTarget): Set { - if (!target.scopeId || !target.crossScope.hasRecords) return new Set(); - const keys = target.db - .prepare( - `SELECT DISTINCT import_key FROM memory_items - WHERE scope_id = ? AND import_key IS NOT NULL AND COALESCE(visibility, '') != 'private'`, - ) - .pluck() - .all(target.scopeId) as string[]; - return new Set(keys); +function hasSnapshotMoves(target: SnapshotTarget): boolean { + return target.moves.some( + ({ source, boundary }) => source === target.scopeId || boundary === target.scopeId, + ); +} + +function legacyHeldKeys(target: SnapshotTarget): Set { + if (!target.scopeId || !target.legacyMoves.hasRecords) return new Set(); + return new Set( + target.db + .prepare(`SELECT DISTINCT import_key FROM memory_items + WHERE scope_id = ? AND import_key IS NOT NULL AND COALESCE(visibility, '') != 'private'`) + .pluck() + .all(target.scopeId) as string[], + ); +} + +function applyLegacySnapshotItem( + target: SnapshotTarget, + item: SyncMemorySnapshotItem, + hadCopy: boolean, + existingIds: number[] = [], +): number { + const plan = + target.scopeId && !hasSnapshotMoves(target) + ? target.legacyMoves.decide(item, target.scopeId) + : null; + if (plan?.kind === "keep_existing" && !hadCopy) return 0; + const replaced = plan?.kind === "replace" ? plan.memoryIds : []; + target.result.deleted += deleteReplacedRows(target.db, [...replaced, ...existingIds]); + return addSnapshotItem(target, item, plan?.kind === "replace" ? plan.originDeviceId : null); } /** Keeps the creating device of a copy the item replaces, when the item does not name one. */ @@ -571,11 +582,12 @@ function addSnapshotItem( target: SnapshotTarget, item: SyncMemorySnapshotItem, replacedOriginDeviceId: string | null, + scopeId = target.scopeId, ): number { const inserted = insertSnapshotItem( target.d, withReplacedOrigin(item, replacedOriginDeviceId), - target.scopeId, + scopeId, target.scanner, ); if (!inserted.applied) return 0; @@ -585,32 +597,55 @@ function addSnapshotItem( return inserted.embeddable ? 1 : 0; } -interface CopiesInOtherScopes { - /** The copy this device holds stays, and the item is not added. */ - keepExisting: boolean; - deleted: number; - originDeviceId: string | null; +function snapshotMoveOrigin( + target: SnapshotTarget, + item: SyncMemorySnapshotItem, + origin: unknown, + shared: boolean, +): SnapshotMoveOrigin { + if (shared && origin === undefined && target.scopeId) + return target.omittedMoveOrigins.omittedOrigin(item, target.scopeId); + return { kind: "apply", origin: typeof origin === "string" ? origin : null }; } -/** - * Settles copies of the item's memory that this device holds under another - * scope. Only a migration record makes this do anything. See - * `snapshot-cross-scope-reconcile.ts`. - */ -function settleCopiesInOtherScopes( +/** Null leaves a snapshot item on the ordinary snapshot path. */ +function applyMoveSnapshotItem( target: SnapshotTarget, item: SyncMemorySnapshotItem, -): CopiesInOtherScopes { - const untouched = { keepExisting: false, deleted: 0, originDeviceId: null }; - if (!target.scopeId) return untouched; - const decision = target.crossScope.decide(item, target.scopeId); - if (decision.kind === "apply") return untouched; - if (decision.kind === "keep_existing") return { ...untouched, keepExisting: true }; - return { - keepExisting: false, - deleted: deleteReplacedRows(target.db, decision.memoryIds), - originDeviceId: decision.originDeviceId, - }; +): number | null { + if (!target.scopeId || !hasSnapshotMoves(target)) return null; + const payload = parseSnapshotPayload(item); + if (!payload) return 0; + const shared = syncVisibilityAllowed(payload); + const attribution = snapshotMoveOrigin(target, item, payload.origin_device_id, shared); + if (attribution.kind === "hold") return 0; + const { origin } = attribution; + const plan = decideProjectMoveArrival( + target.db, + { + key: item.entity_id, + scopeId: target.scopeId, + origin, + shared, + clock: [item.clock_rev, item.clock_updated_at, item.clock_device_id], + }, + target.moves, + ); + if (!plan) return null; + if (plan.keep) { + keepMoveCopy(target.db, plan); + return 0; + } + if (plan.copyId !== null) { + deleteMoveCopy(target.db, plan.copyId); + target.result.deleted++; + } + const metadata = payload.metadata_json; + if (metadata && typeof metadata === "object" && !Array.isArray(metadata)) + stampMoveMetadata(metadata as Record, target.scopeId, plan.scopeId); + if (!shared && typeof payload.visibility !== "string") payload.visibility = "private"; + payload.origin_device_id = origin ?? ""; + return addSnapshotItem(target, { ...item, payload_json: toJson(payload) }, null, plan.scopeId); } /** Removes rows a snapshot item is about to replace. Returns how many were removed. */ @@ -640,20 +675,41 @@ function clearScopedAckedCursor(db: Database, peerDeviceId: string, scopeId: str function replaceSnapshotItems( target: SnapshotTarget, items: Iterable, - heldInScope: Set, - result: BootstrapResult, + held: Set, ): number { let embeddableApplied = 0; for (const item of items) { - const heldElsewhere = settleCopiesInOtherScopes(target, item); - // A copy this scope held before it was cleared is put back. Only a first copy is held back. - if (heldElsewhere.keepExisting && !heldInScope.has(item.entity_id)) continue; - result.deleted += heldElsewhere.deleted; - embeddableApplied += addSnapshotItem(target, item, heldElsewhere.originDeviceId); + const moved = applyMoveSnapshotItem(target, item); + if (moved !== null) { + embeddableApplied += moved; + continue; + } + // The reset held back keys covered by a move so we could check for a replay. + const existingIds = resetHeldSnapshotCopies(target, item).map((row) => row.id); + embeddableApplied += applyLegacySnapshotItem( + target, + item, + held.has(item.entity_id), + existingIds, + ); } return embeddableApplied; } +function resetHeldSnapshotCopies(target: SnapshotTarget, item: SyncMemorySnapshotItem) { + if (!target.scopeId || !hasSnapshotMoves(target)) return []; + return ordinarySnapshotCopies(target, item, eq(schema.memoryItems.scope_id, target.scopeId)); +} + +function ordinarySnapshotCopies( + target: SnapshotTarget, + item: SyncMemorySnapshotItem, + scope: SQL | undefined, +): ExistingSnapshotRow[] { + const rows = copiesInSyncScope(target.d, item.entity_id, scope); + return hasSnapshotMoves(target) ? rows.filter(storedSyncVisibilityAllowed) : rows; +} + /** * Moves the replication cursor to a replacing snapshot's baseline. For scoped * null-baseline snapshots, baseline_cursor can be null; a hidden marker in the @@ -722,23 +778,24 @@ export function applyBootstrapSnapshot( // - Only explicitly private memories are preserved; NULL visibility is // treated as sync-eligible (matching syncVisibilityAllowed semantics) // to avoid leaving stale rows that could create duplicate import_keys. + // A recorded move also protects rows marked private in legacy metadata. // - The dirty-local gate in sync-pass ensures we only reach here when // no unsynced shared changes exist. const target = snapshotTarget(db, peerDeviceId, bootstrapScopeId, activeScanner, result); - const heldInScope = keysHeldInScope(target); + const eligible = retirementSnapshotItems(db, items, bootstrapScopeId); + const held = legacyHeldKeys(target); if (bootstrapScopeId) { - result.deleted = deleteSyncedMemoriesInScope(db, bootstrapScopeId); + result.deleted = deleteSyncedMemoriesInScope( + db, + bootstrapScopeId, + hasSnapshotMoves(target) ? eligible.map(({ entity_id }) => entity_id) : undefined, + ); } // 2. Insert snapshot items, grouping by project. bootstrapSessionCache.clear(); - const embeddableApplied = replaceSnapshotItems( - target, - retirementSnapshotItems(db, items, bootstrapScopeId), - heldInScope, - result, - ); + const embeddableApplied = replaceSnapshotItems(target, eligible, held); // 3. Update replication cursor to baseline_cursor. advanceReplacedSnapshotBoundary(db, peerDeviceId, resetInfo); @@ -762,22 +819,34 @@ export function applyBootstrapSnapshot( return result; } -function deleteSyncedMemoriesInScope(db: Database, scopeId: string): number { +function deleteSyncedMemoriesInScope( + db: Database, + scopeId: string, + held: string[] | undefined, +): number { const d = drizzle(db, { schema }); - const deletePredicate = and( + const candidates = and( isNotNull(schema.memoryItems.import_key), eq(schema.memoryItems.scope_id, scopeId), ne(sql`COALESCE(${schema.memoryItems.visibility}, '')`, "private"), + held?.length + ? sql`${schema.memoryItems.import_key} NOT IN (SELECT value FROM json_each(${JSON.stringify(held)}))` + : undefined, ); - const affectedRows = d - .select({ id: schema.memoryItems.id }) - .from(schema.memoryItems) - .where(deletePredicate) - .all(); - snapshotSessionExportKeysForMemoryIds( - db, - affectedRows.map((row) => row.id), - ); + const affectedRows = held + ? d + .select({ id: schema.memoryItems.id, ...storedSyncVisibilityFields }) + .from(schema.memoryItems) + .where(candidates) + .all() + .filter(storedSyncVisibilityAllowed) + : d.select({ id: schema.memoryItems.id }).from(schema.memoryItems).where(candidates).all(); + const ids = affectedRows.map(({ id }) => id); + if (!ids.length) return 0; + const deletePredicate = held + ? sql`${schema.memoryItems.id} IN (SELECT value FROM json_each(${JSON.stringify(ids)}))` + : candidates; + snapshotSessionExportKeysForMemoryIds(db, ids); return d.delete(schema.memoryItems).where(deletePredicate).run().changes; } @@ -857,19 +926,21 @@ export function mergeBootstrapSnapshot( const target = snapshotTarget(db, peerDeviceId, bootstrapScopeId, activeScanner, result); for (const item of retirementSnapshotItems(db, items, bootstrapScopeId)) { if (!parseSnapshotPayload(item)) continue; - const existingRows = copiesInSnapshotScope(target.d, item, mergeScopePredicate); + const moved = applyMoveSnapshotItem(target, item); + if (moved !== null) { + embeddableApplied += moved; + continue; + } + const existingRows = ordinarySnapshotCopies(target, item, mergeScopePredicate); if (!shouldReplaceExistingSnapshotRows(existingRows, item)) continue; - const heldElsewhere = settleCopiesInOtherScopes(target, item); - // A copy already in this scope is still brought up to date. Only a first copy is held back. - if (heldElsewhere.keepExisting && existingRows.length === 0) continue; - result.deleted += heldElsewhere.deleted; - result.deleted += deleteReplacedRows( - db, + embeddableApplied += applyLegacySnapshotItem( + target, + item, + existingRows.length > 0, existingRows.map((row) => row.id), ); - embeddableApplied += addSnapshotItem(target, item, heldElsewhere.originDeviceId); } advanceMergedSnapshotBoundary(db, peerDeviceId, resetInfo, options); diff --git a/packages/core/src/sync-capability.test.ts b/packages/core/src/sync-capability.test.ts index 7a03a7f22..d74693ade 100644 --- a/packages/core/src/sync-capability.test.ts +++ b/packages/core/src/sync-capability.test.ts @@ -21,12 +21,14 @@ describe("additive sync features", () => { describe("peer_removal_check feature", () => { it("is advertised locally and stays advertised, in sorted order, when another feature is toggled", () => { expect(LOCAL_SYNC_FEATURES).toContain("peer_removal_check"); + expect(LOCAL_SYNC_FEATURES).toContain("project_boundary_migration_v1"); expect(LOCAL_SYNC_FEATURES).toEqual([...LOCAL_SYNC_FEATURES].sort()); setLocalSyncFeature("relay", true); try { expect(LOCAL_SYNC_FEATURES).toEqual([ "peer_removal_check", + "project_boundary_migration_v1", "reassign_scope", "relay", "relay_aware", @@ -34,7 +36,12 @@ describe("peer_removal_check feature", () => { } finally { setLocalSyncFeature("relay", false); } - expect(LOCAL_SYNC_FEATURES).toEqual(["peer_removal_check", "reassign_scope", "relay_aware"]); + expect(LOCAL_SYNC_FEATURES).toEqual([ + "peer_removal_check", + "project_boundary_migration_v1", + "reassign_scope", + "relay_aware", + ]); }); it("is recognized from a peer, while a feature from a newer peer is dropped without affecting the rest", () => { diff --git a/packages/core/src/sync-capability.ts b/packages/core/src/sync-capability.ts index 991990f02..6a612a9d2 100644 --- a/packages/core/src/sync-capability.ts +++ b/packages/core/src/sync-capability.ts @@ -21,8 +21,6 @@ export const SYNC_FEATURES = [ "project_boundary_migration_v1", ] as const; // Retirement is recognized but not advertised until snapshot and admission gates are complete. -// `project_boundary_migration_v1` is recognized so a coordinator can read it from presence. No -// build advertises it until the device side of the per-Project boundary migration exists. // `relay_aware` marks a build that reports `relay` truthfully, so a peer can tell "this device // runs no relay client" from "this device predates the `relay` feature". `relay` itself is // advertised only by a viewer that runs a relay client; see `setLocalSyncFeature`. @@ -31,6 +29,7 @@ export const SYNC_FEATURES = [ // removed peer's pairing. The list stays sorted, as `setLocalSyncFeature` keeps it. export const LOCAL_SYNC_FEATURES: SyncFeature[] = [ "peer_removal_check", + "project_boundary_migration_v1", "reassign_scope", "relay_aware", ]; diff --git a/packages/core/src/sync-daemon.ts b/packages/core/src/sync-daemon.ts index 564c66ef2..3599d13ab 100644 --- a/packages/core/src/sync-daemon.ts +++ b/packages/core/src/sync-daemon.ts @@ -22,6 +22,7 @@ import { } from "./coordinator-runtime.js"; import type { Database } from "./db.js"; import { connect as connectDb, ensureAdditiveSchemaCompatibility, resolveDbPath } from "./db.js"; +import { hasLocalProjectMoves, restampLocalProjectMoves } from "./project-move-device.js"; import type { RelayPeerClient } from "./relay-peer-client.js"; import { listRetiredDeviceAliases, retiredAliasApplies } from "./retired-device-aliases.js"; import * as schema from "./schema.js"; @@ -556,6 +557,7 @@ async function runCoordinatorPhase( // Leave the peer snapshot empty so the stale-peer preflight can read it itself. } try { + await restampDeviceProjects(context); await onAfterCoordinatorRefresh?.(context); return { peers, callbackFailed: false }; } catch (error) { @@ -564,6 +566,18 @@ async function runCoordinatorPhase( } } +async function restampDeviceProjects({ db, dbPath, keysDir }: SyncDaemonTickContext) { + if (!readCoordinatorSyncConfig().syncBoundaryMigrationEnabled) return; + if (getSyncDaemonPhase(db) === "needs_attention" || !hasLocalProjectMoves(db)) return; + const { MemoryStore } = await import("./store.js"); + const store = new MemoryStore(dbPath, { keysDir }); + try { + await restampLocalProjectMoves(store); + } finally { + store.close(); + } +} + /** * Run a single tick, opening and closing a DB connection. * diff --git a/packages/core/src/sync-memory-copies.ts b/packages/core/src/sync-memory-copies.ts new file mode 100644 index 000000000..c0c9809fc --- /dev/null +++ b/packages/core/src/sync-memory-copies.ts @@ -0,0 +1,34 @@ +import { and, eq, ne, type SQL, sql } from "drizzle-orm"; +import type { drizzle } from "drizzle-orm/better-sqlite3"; +import { memoryItems } from "./schema.js"; + +export const storedSyncVisibilityFields = { + visibility: memoryItems.visibility, + metadata_json: memoryItems.metadata_json, +}; + +/** Copies of one key in the scope being applied. */ +export function copiesInSyncScope( + d: ReturnType, + key: string, + scopePredicate: SQL | undefined, +) { + return d + .select({ + id: memoryItems.id, + scope_id: memoryItems.scope_id, + rev: memoryItems.rev, + updated_at: memoryItems.updated_at, + origin_device_id: memoryItems.origin_device_id, + ...storedSyncVisibilityFields, + }) + .from(memoryItems) + .where( + and( + eq(memoryItems.import_key, key), + scopePredicate, + ne(sql`COALESCE(${memoryItems.visibility}, '')`, "private"), + ), + ) + .all(); +} diff --git a/packages/core/src/sync-replication.ts b/packages/core/src/sync-replication.ts index 6a897ce59..6a36b3386 100644 --- a/packages/core/src/sync-replication.ts +++ b/packages/core/src/sync-replication.ts @@ -34,6 +34,13 @@ import { readCodememConfigFile } from "./observer-config.js"; import { pairingStillExists } from "./pairing-instance.js"; import { readRetainedPeerProjectFilters } from "./peer-project-filter-retention.js"; import { projectBasename } from "./project.js"; +import { + decideProjectMoveArrival, + decideProjectMoveDelete, + keepMoveCopy, + type MoveArrivalPlan, + stampMoveMetadata, +} from "./project-move-arrival.js"; import { isProjectScopeWithdrawn } from "./project-scope-withdrawal.js"; import { clearMemoryRefs, populateMemoryRefs } from "./ref-populate.js"; import { requestReplicationBackfillRecheck } from "./replication-backfill-state.js"; @@ -59,6 +66,7 @@ import { recordSyncTransferReceipts, type SyncTransferObservationSource, } from "./sync-transfer-activity.js"; +import { syncVisibilityAllowed } from "./sync-visibility.js"; import { deriveTags } from "./tags.js"; import { hasTransitionedGroup, @@ -74,6 +82,8 @@ import type { SyncMemorySnapshotItem, } from "./types.js"; +export { syncVisibilityAllowed } from "./sync-visibility.js"; + export const DEFAULT_SYNC_SCOPE_ID = "local-default"; export const ACCESS_CLEANUP_OP_TYPE = "access_cleanup"; export const REASSIGN_SCOPE_OP_TYPE = "reassign_scope"; @@ -2420,49 +2430,6 @@ export function syncProjectAllowedByFilters( return false; } -export function syncVisibilityAllowed(payload: Record | null): boolean { - if (!payload) return false; - let visibility = String(payload.visibility ?? "") - .trim() - .toLowerCase(); - const metadata = - payload.metadata_json && - typeof payload.metadata_json === "object" && - !Array.isArray(payload.metadata_json) - ? (payload.metadata_json as Record) - : {}; - const metadataVisibility = String(metadata.visibility ?? "") - .trim() - .toLowerCase(); - if (!visibility && metadataVisibility) { - visibility = metadataVisibility; - } - - if (!visibility) { - let workspaceKind = String(payload.workspace_kind ?? "") - .trim() - .toLowerCase(); - let workspaceId = String(payload.workspace_id ?? "") - .trim() - .toLowerCase(); - if (!workspaceKind) - workspaceKind = String(metadata.workspace_kind ?? "") - .trim() - .toLowerCase(); - if (!workspaceId) - workspaceId = String(metadata.workspace_id ?? "") - .trim() - .toLowerCase(); - if (workspaceKind === "shared" || workspaceId.startsWith("shared:")) { - visibility = "shared"; - } else { - return true; - } - } - - return visibility === "shared"; -} - function cleanText(value: unknown): string | null { const trimmed = typeof value === "string" ? value.trim() : ""; return trimmed.length > 0 ? trimmed : null; @@ -4681,12 +4648,14 @@ function skipOwnRetiredOrAppliedOp( op: ReplicationOp, localDeviceId: string, options: ApplyReplicationOpsOptions, + move: MoveArrivalPlan | null, ): boolean { if (skipOwnOrRetiredMemoryOp(db, op, localDeviceId)) return true; // Not recorded as applied, so a re-pull after the withdrawal ends applies it. if (opInWithdrawnScope(db, op)) return true; + if (move?.deny) return true; // Not recorded either: which copy the op would change is unclear until repaired. - if (opTargetsAmbiguousCopies(db, op)) return true; + if (!move && opTargetsAmbiguousCopies(db, op)) return true; if (opCreatesContent(op) && newerTombstoneSuppresses(db, op)) return true; const applied = d @@ -4695,10 +4664,98 @@ function skipOwnRetiredOrAppliedOp( .where(eq(schema.replicationOps.op_id, op.op_id)) .get() !== undefined; // Inside the op's savepoint, so a delete that then fails to apply records nothing. - if (!applied && op.op_type === "delete") recordAuthorizedTombstone(db, op, options); + if (!applied && op.op_type === "delete") recordAuthorizedTombstone(db, op, options, move); return applied; } +function projectMoveOpPlan( + db: Database, + op: ReplicationOp, + senderId: string | null, +): MoveArrivalPlan | null { + const scopeId = cleanText(op.scope_id); + if ( + op.entity_type !== "memory_item" || + !scopeId || + !MEMORY_WRITE_OP_TYPES.has(op.op_type) || + op.op_type === ACCESS_CLEANUP_OP_TYPE + ) + return null; + if (op.op_type === "delete") + return decideProjectMoveDelete(db, { + key: op.entity_id, + scopeId, + sender: moveDeleteSender(db, op, senderId), + }); + const payload = parsePayload(op.payload_json); + const origin = typeof payload?.origin_device_id === "string" ? payload.origin_device_id : null; + return decideProjectMoveArrival(db, { + key: op.entity_id, + scopeId, + origin: moveOpOrigin(op, payload, origin), + shared: syncVisibilityAllowed(payload), + clock: [op.clock_rev, op.clock_updated_at, op.clock_device_id], + }); +} + +function moveDeleteSender(db: Database, op: ReplicationOp, deviceId: string | null) { + if ( + !deviceId || + cleanText(op.device_id) !== deviceId || + cleanText(op.clock_device_id) !== deviceId + ) + return null; + const binding = admittedSenderKey(db, deviceId, undefined); + return binding ? { deviceId, binding } : null; +} + +function inboundMoveSender(options: ApplyReplicationOpsOptions): string | null { + return cleanText(options.inboundScopeValidation?.peerDeviceId ?? options.activityPeerDeviceId); +} + +function moveOpOrigin( + op: ReplicationOp, + payload: Record | null, + origin: string | null, +): string | null { + if (payload?.side === "old") return cleanText(op.device_id); + return origin; +} + +function inboundMemoryMetadata( + db: Database, + op: ReplicationOp, + payload: MemoryPayload, + move: MoveArrivalPlan | null, + replaced?: { metadata_json: string | null }, +): Record { + const metadata = foreignRevisionMetadata(db, op, payload.metadata_json, replaced); + return move ? stampMoveMetadata(metadata, cleanText(op.scope_id), move.scopeId) : metadata; +} + +function inboundCopyPredicate(op: ReplicationOp, move: MoveArrivalPlan | null) { + if (!move) return eq(schema.memoryItems.import_key, op.entity_id); + return move.copyId === null ? sql`0 = 1` : eq(schema.memoryItems.id, move.copyId); +} + +function keepInboundMove( + db: Database, + d: ReturnType, + op: ReplicationOp, + move: MoveArrivalPlan | null, +) { + if (!move?.keep) return false; + // Both sides share a clock. The upsert path can restore the source row + // when the new side follows the old side's tombstone. + if (move.equalClock && op.op_type === REASSIGN_SCOPE_OP_TYPE) { + const reassignment = parseReassignScopePayload(op); + if (reassignment.side === "new" && move.copyScopeId === reassignment.old_scope_id) return false; + } + keepMoveCopy(db, move); + insertReplicationOpRow(d, op); + return true; +} + /** * Whether an incremental op can create a memory's row, which is what a tombstone * stops: an upsert, or the new side of a scope move. @@ -4760,6 +4817,7 @@ function recordAuthorizedTombstone( db: Database, op: ReplicationOp, options: ApplyReplicationOpsOptions, + move: MoveArrivalPlan | null, ): void { if (op.entity_type !== "memory_item") return; const author = cleanText(op.clock_device_id); @@ -4769,9 +4827,13 @@ function recordAuthorizedTombstone( options.inboundScopeValidation?.peerDeviceId ?? options.activityPeerDeviceId, ); if (sender !== author) return; - const stored = db - .prepare("SELECT origin_device_id FROM memory_items WHERE import_key = ? LIMIT 1") - .get(op.entity_id) as { origin_device_id: string | null } | undefined; + const stored = ( + move + ? db.prepare("SELECT origin_device_id FROM memory_items WHERE id = ?").get(move.copyId) + : db + .prepare("SELECT origin_device_id FROM memory_items WHERE import_key = ? LIMIT 1") + .get(op.entity_id) + ) as { origin_device_id: string | null } | undefined; const creator = stored && (verifiedMemoryCreator(db, op.entity_id) ?? cleanText(stored.origin_device_id)); if (stored && creator !== author) return; @@ -4998,7 +5060,11 @@ function applyReplicationOpsInternal( db.exec("SAVEPOINT codemem_replication_op"); try { // Skip own, retired, and already-applied ops. - if (skipOwnRetiredOrAppliedOp(db, d, op, localDeviceId, options)) { + const move = projectMoveOpPlan(db, op, inboundMoveSender(options)); + if ( + skipOwnRetiredOrAppliedOp(db, d, op, localDeviceId, options, move) || + keepInboundMove(db, d, op, move) + ) { result.skipped++; continue; } @@ -5016,7 +5082,7 @@ function applyReplicationOpsInternal( scope_id: schema.memoryItems.scope_id, }) .from(schema.memoryItems) - .where(eq(schema.memoryItems.import_key, op.entity_id)) + .where(inboundCopyPredicate(op, move)) .get(); if ( !current || @@ -5078,10 +5144,7 @@ function applyReplicationOpsInternal( if (op.op_type === "upsert" || reassignment?.side === "new") { const importKey = op.entity_id; - const opScopeId = - typeof op.scope_id === "string" && op.scope_id.trim().length > 0 - ? op.scope_id.trim() - : null; + const opScopeId = move?.scopeId ?? cleanText(op.scope_id); const memRow = d .select({ id: schema.memoryItems.id, @@ -5095,7 +5158,7 @@ function applyReplicationOpsInternal( scope_id: schema.memoryItems.scope_id, }) .from(schema.memoryItems) - .where(eq(schema.memoryItems.import_key, importKey)) + .where(inboundCopyPredicate(op, move)) .get(); if (memRow) { @@ -5140,7 +5203,7 @@ function applyReplicationOpsInternal( continue; } redactMemoryFields(payload, activeScanner); - const metaObj = foreignRevisionMetadata(db, op, payload.metadata_json, memRow); + const metaObj = inboundMemoryMetadata(db, op, payload, move, memRow); const nextTitle = resolveReplicatedTextUpdate(payload.title, memRow.title); const nextBodyText = resolveReplicatedTextUpdate(payload.body_text, memRow.body_text); const contentChanged = @@ -5245,7 +5308,7 @@ function applyReplicationOpsInternal( op.clock_updated_at, replicatedProject, ); - const metaObj = foreignRevisionMetadata(db, op, payload.metadata_json); + const metaObj = inboundMemoryMetadata(db, op, payload, move); const insertedRows = d .insert(schema.memoryItems) .values({ @@ -5302,11 +5365,7 @@ function applyReplicationOpsInternal( } } } else if (op.op_type === "delete") { - const importKey = op.entity_id; - const opScopeId = - typeof op.scope_id === "string" && op.scope_id.trim().length > 0 - ? op.scope_id.trim() - : null; + const opScopeId = move?.scopeId ?? cleanText(op.scope_id); const existingForDelete = d .select({ id: schema.memoryItems.id, @@ -5315,7 +5374,7 @@ function applyReplicationOpsInternal( metadata_json: schema.memoryItems.metadata_json, }) .from(schema.memoryItems) - .where(eq(schema.memoryItems.import_key, importKey)) + .where(inboundCopyPredicate(op, move)) .limit(1) .get(); @@ -5477,7 +5536,8 @@ function localOnlyRowRejections( sender: string, ): InboundScopeRejection[] { const stored = db.prepare( - "SELECT scope_id, origin_device_id FROM memory_items WHERE import_key = ?", + `SELECT scope_id, origin_device_id FROM memory_items + WHERE import_key = ? AND (? OR id = ?)`, ); const applied = db.prepare("SELECT 1 FROM replication_ops WHERE op_id = ?"); const rejections: InboundScopeRejection[] = []; @@ -5487,7 +5547,8 @@ function localOnlyRowRejections( if (op.device_id === localDeviceId || applied.get(op.op_id)) continue; if (retirementBlocksMemoryOp(db, op) || opInWithdrawnScope(db, op)) continue; const deviceId = sender; - const rows = stored.all(op.entity_id) as Array<{ + const move = projectMoveOpPlan(db, op, sender); + const rows = stored.all(op.entity_id, Number(move === null), move?.copyId ?? null) as Array<{ scope_id: string | null; origin_device_id: string | null; }>; @@ -5531,6 +5592,12 @@ export function scopesWrittenByInboundOp( // The other scope counts only through a copy stored there, below: a device in the // destination may not know the older scope, and the old side writes nothing new. const scopes = new Set([cleanText(op.scope_id) ?? ""]); + const move = projectMoveOpPlan(db, op, senderId); + if (move) { + scopes.add(move.scopeId); + if (move.copyScopeId !== null) scopes.add(move.copyScopeId); + return [...scopes]; + } const existing = db .prepare("SELECT DISTINCT scope_id FROM memory_items WHERE import_key = ?") .pluck() diff --git a/packages/core/src/sync-visibility.ts b/packages/core/src/sync-visibility.ts new file mode 100644 index 000000000..e63883ee2 --- /dev/null +++ b/packages/core/src/sync-visibility.ts @@ -0,0 +1,27 @@ +import { fromJson } from "./db.js"; + +export function syncVisibilityAllowed(payload: Record | null): boolean { + if (!payload) return false; + const visibility = String(payload.visibility ?? "") + .trim() + .toLowerCase(); + const metadata = + payload.metadata_json && + typeof payload.metadata_json === "object" && + !Array.isArray(payload.metadata_json) + ? (payload.metadata_json as Record) + : {}; + const metadataVisibility = String(metadata.visibility ?? "") + .trim() + .toLowerCase(); + // Legacy payloads without a visibility in either field are sync-eligible. + const effectiveVisibility = visibility || metadataVisibility; + return !effectiveVisibility || effectiveVisibility === "shared"; +} + +export function storedSyncVisibilityAllowed(row: { + visibility: string | null; + metadata_json: string | null; +}): boolean { + return syncVisibilityAllowed({ ...row, metadata_json: fromJson(row.metadata_json) }); +} diff --git a/packages/core/src/transitioned-transfer-sync.test.ts b/packages/core/src/transitioned-transfer-sync.test.ts index 1d5455c2f..b2db68328 100644 --- a/packages/core/src/transitioned-transfer-sync.test.ts +++ b/packages/core/src/transitioned-transfer-sync.test.ts @@ -530,6 +530,7 @@ describe("a snapshot of a scope whose group has not transitioned", () => { updated_at: "2026-01-03T00:00:00Z", scope_id: NEW, visibility: "shared", + origin_device_id: PEER, }), clock_rev: 2, clock_updated_at: "2026-01-03T00:00:00Z", diff --git a/packages/viewer-server/src/index.test.ts b/packages/viewer-server/src/index.test.ts index 40ca446a0..42b0f8f8e 100644 --- a/packages/viewer-server/src/index.test.ts +++ b/packages/viewer-server/src/index.test.ts @@ -10432,7 +10432,7 @@ describe("viewer-server", () => { // Assert expect(ordinary.status).toBe(200); expect((await ordinary.json()) as Record).toMatchObject({ - sync_features: ["peer_removal_check", "reassign_scope", "relay_aware"], + sync_features: core.LOCAL_SYNC_FEATURES, }); expect(refreshOnly.status).toBe(200); expect(featureOnly.status).toBe(200);