From 64a0f0724f55abc7f1d1a8c67a6741c8b2e6d915 Mon Sep 17 00:00:00 2001 From: Adam Kunicki Date: Sat, 28 Nov 2026 18:28:28 -0800 Subject: [PATCH 1/4] feat(sync): migrate older Project sharing on the admin device --- docs/coordinator-discovery.md | 17 +- packages/cli/src/commands/serve.ts | 9 +- .../cli/src/commands/sync-migration.test.ts | 40 +- packages/cli/src/commands/sync-migration.ts | 36 +- .../coordinator-project-move-commit.test.ts | 80 ++- packages/core/src/index.ts | 5 + .../src/project-boundary-migration-hold.ts | 16 +- .../core/src/project-migration-report.test.ts | 14 +- packages/core/src/project-migration-report.ts | 116 ++-- packages/core/src/project-move-admin.test.ts | 648 ++++++++++++++++++ packages/core/src/project-move-admin.ts | 494 +++++++++++++ packages/core/src/project-move-plan.ts | 385 +++++++++++ .../core/src/recipient-policy-reconciler.ts | 12 + .../src/recipient-policy-reconciliation.ts | 50 +- packages/ui/src/lib/api/sync.ts | 2 + packages/ui/src/tabs/projects-controller.ts | 6 + .../ui/src/tabs/projects-inventory-model.ts | 2 + packages/ui/src/tabs/projects.test.ts | 54 ++ .../ui/src/tabs/projects/ProjectInventory.tsx | 13 + .../tabs/projects/ProjectMigrationNotices.tsx | 34 + packages/viewer-server/src/routes/sync.ts | 7 +- 21 files changed, 1954 insertions(+), 86 deletions(-) create mode 100644 packages/core/src/project-move-admin.test.ts create mode 100644 packages/core/src/project-move-admin.ts create mode 100644 packages/core/src/project-move-plan.ts create mode 100644 packages/ui/src/tabs/projects/ProjectMigrationNotices.tsx diff --git a/docs/coordinator-discovery.md b/docs/coordinator-discovery.md index b4839ba43..c795c7076 100644 --- a/docs/coordinator-discovery.md +++ b/docs/coordinator-discovery.md @@ -74,23 +74,20 @@ Backward compatibility: - when `sync_coordinator_groups` is set, the first entry becomes the legacy single-group value for compatibility with older surfaces -### Boundary migration rollout setting +### Project migration report `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. The report itself never starts a move. | +restamp memories it authored. The `codemem sync migration status` command works +at either setting and lists the planned recipients and devices that would start +or stop receiving each Project. 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 -candidate is a Project found locally. It does not imply that every device would keep -the same access. `projects: null` means the inventory is unavailable. `local_filters` +The report sends no requests and does not change sharing. It uses the membership +information on this device, which may be older than the coordinator's records. +`projects: null` means the inventory is unavailable. `local_filters` includes restrictions on pairings, retained pairing settings, active group templates and effective config settings. `unknown` means the report could not classify them. diff --git a/packages/cli/src/commands/serve.ts b/packages/cli/src/commands/serve.ts index fa4707f01..c62109649 100644 --- a/packages/cli/src/commands/serve.ts +++ b/packages/cli/src/commands/serve.ts @@ -20,6 +20,7 @@ import { resolveCodememConfigPath, resolveDbPath, resolveKeyPaths, + runProjectMoves, runSyncDaemon, type SyncDaemonTickCallback, VERSION, @@ -781,11 +782,13 @@ function createServeCoordinatorMaintenanceDependencies( }), reconcileConfiguredCoordinatorEnrollment: server.reconcileConfiguredCoordinatorEnrollment, convertLegacyPairingAssignments: server.convertLegacyPairingAssignmentsOperation, - reconcileRecipientPolicyProjects: (store, options) => - server.reconcileRecipientPolicyProjectsOperation(store, { + reconcileRecipientPolicyProjects: async (store, options) => { + await runProjectMoves(store.db, readCoordinatorSyncConfig(), store.deviceId); + return server.reconcileRecipientPolicyProjectsOperation(store, { ...options, effects: server.createRecipientPolicyReconcilerEffects(store), - }), + }); + }, }; } diff --git a/packages/cli/src/commands/sync-migration.test.ts b/packages/cli/src/commands/sync-migration.test.ts index ae904d036..861317bcd 100644 --- a/packages/cli/src/commands/sync-migration.test.ts +++ b/packages/cli/src/commands/sync-migration.test.ts @@ -57,6 +57,7 @@ it("distinguishes a fresh peer install from a configured coordinator that cannot storage_fence: expect.stringContaining("does not erase data from disk"), projects: null, adopted_sources: [], + project_moves: [], }); expect(fetch).not.toHaveBeenCalled(); }); @@ -74,7 +75,7 @@ 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 () => { +it("reports the local backup path and byte size even when migration is off", async () => { connect(dbPath).close(); vi.stubEnv("CODEMEM_SYNC_BOUNDARY_MIGRATION", "off"); const backup = `${dbPath}.before-project-moves.sqlite`; @@ -112,3 +113,40 @@ it("tells the person in text what the storage fence does not erase and how to re expect(text).toContain("does not erase data from disk"); expect(text).toContain("leave the project_* tables unchanged"); }); + +it("prints one line each for the devices that would start and stop receiving a Project", async () => { + const db = connect(dbPath); + db.exec(`INSERT INTO replication_scopes(scope_id,label,kind,authority_type,coordinator_id,group_id,created_at,updated_at) + VALUES ('old','Older setup','team','coordinator','https://coordinator.example','test','now','now'); + INSERT INTO project_scope_mappings(workspace_identity,project_pattern,scope_id,created_at,updated_at) + VALUES ('repo:journal','repo:journal','old','now','now'); + INSERT INTO scope_memberships(scope_id,device_id,updated_at) VALUES ('old','desktop','now'), ('old','tablet','now'); + INSERT INTO actors(actor_id,display_name,status,created_at,updated_at) + VALUES ('pat','Pat','active','now','now'), ('lee','Lee','deactivated','now','now'); + INSERT INTO identity_devices(device_id,identity_id,display_name,status,provenance,revision,migration_state,idempotency_key,created_at,updated_at) + VALUES ('desktop','pat','Desktop','active','test','1','native','desktop','now','now'), + ('laptop','pat','Laptop','active','test','1','native','laptop','now','now'), + ('tablet','lee','Tablet','active','test','1','native','tablet','now','now');`); + db.close(); + writeFileSync( + configPath, + JSON.stringify({ + sync_coordinator_url: "https://coordinator.example", + sync_coordinator_group: "test", + }), + ); + const output = vi.spyOn(process.stdout, "write").mockReturnValue(true); + await buildSyncMigrationCommand().parseAsync( + ["status", "--db-path", dbPath, "--config", configPath], + { from: "user" }, + ); + const text = output.mock.calls.map(([chunk]) => String(chunk)).join(""); + expect(text).toContain("repo:journal: Pat"); + expect(text.match(/\w+ will start receiving this Project\./g)).toEqual([ + "Laptop will start receiving this Project.", + ]); + expect(text.match(/\w+ will stop receiving this Project\./g)).toEqual([ + "Tablet will stop receiving this Project.", + ]); + expect(fetch).not.toHaveBeenCalled(); +}); diff --git a/packages/cli/src/commands/sync-migration.ts b/packages/cli/src/commands/sync-migration.ts index 578dc00bc..4687e6109 100644 --- a/packages/cli/src/commands/sync-migration.ts +++ b/packages/cli/src/commands/sync-migration.ts @@ -23,28 +23,56 @@ function sourceRowsText(rows: Array<{ source_scope_id: string; remaining_rows: n return rows .map( ({ source_scope_id, remaining_rows }) => - `${source_scope_id}: ${remaining_rows} rows still in the older scope.`, + `${source_scope_id}: ${remaining_rows} rows still in the older sharing setup.`, ) .join("\n"); } function reportText(report: ReturnType): string { switch (report.state) { - case "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": return "Coordinator settings are missing. Existing sharing stays in effect."; case "local_report": { const counts = report.projects; + const moves = report.project_moves; 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}.` + ? `Locally authored rows in older setups: ${counts.own_source_rows}.` : "The local Project inventory is unavailable."; return [ + ...(moves + ? [ + `Project candidates: ${moves.length}. Projects in multiple setups: ${moves.filter((project) => project.multipleSources).length}.`, + ] + : []), observed, sourceRowsText(report.adopted_sources), `Local filter evidence: ${report.local_filters}. Other devices have not been checked.`, + ...(moves ?? []).flatMap(({ projectName, plan, multipleSources }) => { + if (multipleSources) + return [`${projectName}: Needs attention. Found in more than one older sharing setup.`]; + if (!plan) + return [`${projectName}: Needs attention. The Project could not be identified.`]; + if (plan.teamInAnotherGroup) + return [ + `${projectName}: Needs attention. The Project and its Team use different sharing setups.`, + ]; + return [ + `${projectName}: ${plan.recipients.map(({ name }) => name).join(", ") || "No recipients found"}`, + ...plan.unlinkedDevices.map( + ({ name }) => + ` Waiting for ${name}. Link this device to a person in Devices, or remove it.`, + ), + ...(plan.needsAttention + ? [" Needs attention. Current access could not be verified."] + : []), + ...plan.newReceivers.map(({ name }) => ` ${name} will start receiving this Project.`), + ...plan.excludedDevices.map( + ({ name }) => ` ${name} will stop receiving this Project.`, + ), + ]; + }), report.maintenance_window, report.storage_fence, ] diff --git a/packages/core/src/coordinator-project-move-commit.test.ts b/packages/core/src/coordinator-project-move-commit.test.ts index 32cf0ff18..aacda7a2c 100644 --- a/packages/core/src/coordinator-project-move-commit.test.ts +++ b/packages/core/src/coordinator-project-move-commit.test.ts @@ -1,5 +1,9 @@ +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import type Database from "better-sqlite3"; -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; +import { createBetterSqliteCoordinatorApp } from "./better-sqlite-coordinator-runtime.js"; import { setupStore } from "./coordinator-auth-store-test-fixtures.js"; import type { DeviceRemovalBackend } from "./coordinator-device-removal.js"; import { @@ -7,6 +11,11 @@ import { projectMoveHarness, registerProjectMoveContract, } from "./coordinator-project-move-test-harness.js"; +import { registerCoordinatorPresence } from "./coordinator-runtime.js"; +import { readCoordinatorSyncConfig } from "./coordinator-sync-config.js"; +import { connect } from "./db.js"; +import { projectMoveAdminEffects } from "./project-move-admin.js"; +import { ensureDeviceIdentity, loadPublicKey } from "./sync-identity.js"; /** The atomic batch the stores use, over the fixture's database. */ function sqliteBackend(db: Database.Database): DeviceRemovalBackend { @@ -68,3 +77,72 @@ describe.each(["SQLite", "D1"] as const)("%s coordinator without move storage", } }); }); + +it.each(["off", "on"] as const)( + "gates a Project move on production presence with migration %s", + async (mode) => { + const directory = mkdtempSync(join(tmpdir(), "project-move-gate-")); + const db = connect(":memory:"); + const coordinatorPath = join(directory, "coordinator.sqlite"); + const { store } = setupStore("SQLite", { databasePath: coordinatorPath }); + const keysDir = join(directory, "keys"); + vi.stubEnv("CODEMEM_SYNC_BOUNDARY_MIGRATION", undefined); + const config = readCoordinatorSyncConfig({ + sync_coordinator_url: "https://coordinator.example", + sync_coordinator_group: "g", + sync_coordinator_admin_secret: "test-admin", + sync_boundary_migration: mode, + }); + const app = createBetterSqliteCoordinatorApp({ + dbPath: coordinatorPath, + runtime: { + adminSecret: () => config.syncCoordinatorAdminSecret, + now: () => new Date().toISOString(), + }, + }); + const fetch = vi + .spyOn(globalThis, "fetch") + .mockImplementation(async (url, init) => app.request(new Request(url, init))); + try { + const [deviceId, fingerprint] = ensureDeviceIdentity(db, { keysDir }); + await store.createGroup("g"); + await store.enrollDevice("g", { + deviceId, + publicKey: loadPublicKey(keysDir) ?? "", + fingerprint, + }); + await store.createScope({ + scopeId: "older", + groupId: "g", + label: "Older setup", + kind: "team", + authorityType: "coordinator", + membershipEpoch: 1, + }); + await store.grantScopeMembership({ + scopeId: "older", + deviceId, + membershipEpoch: 1, + effectId: "fixture-grant", + }); + + await registerCoordinatorPresence({ db, dbPath: ":memory:" }, config, { keysDir }); + const move = await projectMoveAdminEffects(config).move({ + groupId: "g", + sourceScopeId: "older", + boundaryScopeId: `managed-project:${"a".repeat(64)}`, + deviceId, + excludedDeviceIds: [], + teamRemovalSeq: 0, + }); + if (mode === "on") expect(move).toMatchObject({ kind: "moved", deviceIds: [deviceId] }); + else expect(move).toEqual({ kind: "devices_not_updated", deviceIds: [deviceId] }); + } finally { + fetch.mockRestore(); + vi.unstubAllEnvs(); + db.close(); + await store.close(); + rmSync(directory, { recursive: true, force: true }); + } + }, +); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index a35989ffb..b0d2e07ad 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1155,6 +1155,11 @@ export { } from "./project-invite-identity.js"; export { normalizeProjectLabel } from "./project-label.js"; export { readLocalProjectMigrationReport } from "./project-migration-report.js"; +export { + listProjectMoveIssues, + type ProjectMoveIssue, + runProjectMoves, +} from "./project-move-admin.js"; export type { ResumeProjectScopeSyncResult } from "./project-scope-resume.js"; export { resumeProjectScopeSync } from "./project-scope-resume.js"; export type { diff --git a/packages/core/src/project-boundary-migration-hold.ts b/packages/core/src/project-boundary-migration-hold.ts index ffddad670..ab848945f 100644 --- a/packages/core/src/project-boundary-migration-hold.ts +++ b/packages/core/src/project-boundary-migration-hold.ts @@ -5,10 +5,9 @@ import { } from "./project-boundary-migration-records.js"; /* - * The hold on a migrated Project. While it is set, the recipient reconciler - * works out what it would change and changes nothing, so a Project keeps the - * devices the migration copied until a pass finds nothing to change or the - * admin confirms the summary. + * While a Project is held, reconciliation leaves the copied devices alone. + * The admin device clears the hold automatically when its saved recipients + * derive exactly the devices planned for the Project. * * The hold is not a stored flag. A Project with a migration record is held * unless the hold was cleared at the record's current generation. A newer @@ -32,13 +31,18 @@ const HOLD_COLUMNS = [ "hold_withdrawn_device_ids_json", ]; -/** Why a hold was cleared: nothing to change, the admin's answer, or a recipient change in Projects. */ -export type MigrationHoldClearReason = "empty_plan" | "summary_confirmed" | "recipients_changed"; +/** The reason stored when the hold was cleared. */ +export type MigrationHoldClearReason = + | "empty_plan" + | "summary_confirmed" + | "recipients_changed" + | "migration_recipients_recorded"; const CLEAR_REASONS: readonly MigrationHoldClearReason[] = [ "empty_plan", "summary_confirmed", "recipients_changed", + "migration_recipients_recorded", ]; export interface ProjectBoundaryMigrationHold { diff --git a/packages/core/src/project-migration-report.test.ts b/packages/core/src/project-migration-report.test.ts index 377d65686..4f981c228 100644 --- a/packages/core/src/project-migration-report.test.ts +++ b/packages/core/src/project-migration-report.test.ts @@ -90,7 +90,7 @@ function currentStore() { return db; } -it("counts one split candidate without exporting names, content, or any readiness assertion", () => { +it("lists and counts one split candidate without exporting memory content", () => { const db = currentStore(); try { expect(readLocalProjectMigrationReport(db, CONFIG)).toEqual({ @@ -103,8 +103,18 @@ it("counts one split candidate without exporting names, content, or any readines /does not erase data.*planner statistics.*project_\* tables unchanged/, ), projects: { candidate_projects: 1, multiple_sources: 1, own_source_rows: 1 }, + project_moves: [ + expect.objectContaining({ + projectIdentity: "repository:example", + multipleSources: true, + plan: null, + }), + ], + }); + expect(readLocalProjectMigrationReport(db, {})).toEqual({ + mode: "off", + state: "waiting_for_coordinator", }); - expect(readLocalProjectMigrationReport(db, {})).toEqual({ mode: "off", state: "off" }); expect(readLocalProjectMigrationReport(db, PEER_ONLY).state).toBe("waiting_for_coordinator"); } finally { db.close(); diff --git a/packages/core/src/project-migration-report.ts b/packages/core/src/project-migration-report.ts index cc8b2c586..b74851816 100644 --- a/packages/core/src/project-migration-report.ts +++ b/packages/core/src/project-migration-report.ts @@ -2,11 +2,17 @@ import { type BoundaryFilterEvidence, readBoundaryFilterEvidence, } from "./boundary-filter-evidence.js"; -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 { + cachedProjectMoveMembers, + listProjectMoveCandidates, + olderProjectScopes, + planProjectMove, +} from "./project-move-plan.js"; import { columnExists } from "./schema-lookups.js"; +import { SYNC_BOOTSTRAP_CWD_PREFIX } from "./sync-bootstrap-constants.js"; /** These are observations on one store, never permission to migrate a Project. */ type LocalInventory = { @@ -22,37 +28,46 @@ function hasHistory(db: Database, table: string, predicate = "1"): boolean { ); } -function groupsInStore(db: Database) { - if (!tableExists(db, "replication_scopes")) return []; - return db - .prepare(`SELECT DISTINCT coordinator_id, group_id FROM replication_scopes - WHERE authority_type = 'coordinator'`) - .all() as { - coordinator_id: string | null; - group_id: string | null; - }[]; +function hasCoordinatorHistory(db: Database): boolean { + return ( + hasHistory(db, "replication_scopes", "authority_type = 'coordinator'") || + hasHistory(db, "peer_project_filter_management") || + hasHistory(db, "scope_membership_cache_state") || + hasHistory(db, "coordinator_group_preferences") || + hasHistory(db, "project_boundary_migrations") || + hasHistory(db, "policy_team_coordinator_links") || + (columnExists(db, "sync_peers", "discovered_via_coordinator_id") && + hasHistory(db, "sync_peers", "discovered_via_coordinator_id IS NOT NULL")) + ); } -function inventory(db: Database, groups: ReturnType): LocalInventory | null { +function inventory( + db: Database, + moves: NonNullable>, +): LocalInventory | null { const device = db.prepare("SELECT device_id FROM sync_device LIMIT 1").pluck().get(); - if (typeof device !== "string" || !device.trim() || !groups.length) return null; - const counts: LocalInventory = { candidate_projects: 0, multiple_sources: 0, own_source_rows: 0 }; - for (const group of groups) { - if (!group.coordinator_id || !group.group_id) return null; - const result = buildBoundaryReadinessInventory(db, { - deviceId: device, - coordinatorId: group.coordinator_id, - groupId: group.group_id, - }); - const sources = new Map(); - for (const entry of result.projects) { - sources.set(entry.boundary_scope_id, (sources.get(entry.boundary_scope_id) ?? 0) + 1); - counts.own_source_rows += entry.own_rows_in_source; - } - counts.candidate_projects += sources.size; - counts.multiple_sources += [...sources.values()].filter((n) => n > 1).length; - } - return counts; + const sources = olderProjectScopes(db); + if (typeof device !== "string" || !device.trim() || !sources.length) return null; + const ownRows = db + .prepare( + `SELECT COUNT(*) FROM memory_items mi JOIN sessions s ON mi.session_id = s.id + WHERE mi.scope_id IN (SELECT value FROM json_each(?)) + AND mi.active = 1 AND mi.deleted_at IS NULL AND COALESCE(mi.origin_device_id, '') IN ('', 'local', ?) + AND COALESCE(s.user, '') <> 'sync' AND COALESCE(s.tool_version, '') <> 'sync_replication' + AND substr(COALESCE(s.cwd, ''), 1, ?) <> ?`, + ) + .pluck() + .get( + JSON.stringify(sources.map(({ scope_id }) => scope_id)), + device, + SYNC_BOOTSTRAP_CWD_PREFIX.length, + SYNC_BOOTSTRAP_CWD_PREFIX, + ); + return { + candidate_projects: moves.length, + multiple_sources: moves.filter(({ multipleSources }) => multipleSources).length, + own_source_rows: Number(ownRows), + }; } export function readLocalProjectMigrationReport(db: Database, config: Record) { @@ -63,40 +78,31 @@ export function readLocalProjectMigrationReport(db: Database, config: Record) { const mode = readBoundaryMigrationMode(config); - 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 = - settings.syncCoordinatorGroups.length > 0 || - groups.length > 0 || - hasHistory(db, "peer_project_filter_management") || - hasHistory(db, "scope_membership_cache_state") || - hasHistory(db, "coordinator_group_preferences") || - hasHistory(db, "project_boundary_migrations") || - hasHistory(db, "policy_team_coordinator_links") || - (columnExists(db, "sync_peers", "discovered_via_coordinator_id") && - hasHistory(db, "sync_peers", "discovered_via_coordinator_id IS NOT NULL")); - if (!managed) return { mode, state: "not_applicable" } as const; - return { mode, state: "waiting_for_coordinator" } as const; + const managed = settings.syncCoordinatorGroups.length > 0 || hasCoordinatorHistory(db); + return { + mode, + state: managed ? "waiting_for_coordinator" : "not_applicable", + ...(adoptedSources.length ? { adopted_sources: adoptedSources } : {}), + } as const; } let filters: BoundaryFilterEvidence = "unknown"; let projects: LocalInventory | null = null; + let projectMoves: ReturnType | null = null; try { filters = readBoundaryFilterEvidence(db, config); } catch { // A historical table can predate the columns read by current code. } try { - projects = inventory(db, groups); + projectMoves = reportProjectMoves(db); + if (projectMoves) projects = inventory(db, projectMoves); } catch { - // An unidentified Project or an older schema is not an empty inventory. + // The report can read historical stores that do not have recipient policy. } return { mode, @@ -104,6 +110,7 @@ function migrationReport(db: Database, config: Record) { local_filters: filters, projects, adopted_sources: adoptedSources, + project_moves: projectMoves, maintenance_window: "Before transitioning this store, drain transfers and proof refreshes and stop every client that uses it, including current versions. Neither the exclusive lock nor the format change can recall bytes a process has already read.", storage_fence: @@ -112,3 +119,16 @@ function migrationReport(db: Database, config: Record) { }) .deferred(); } + +function reportProjectMoves(db: Database) { + if (!tableExists(db, "project_recipients")) return null; + return listProjectMoveCandidates(db).map((project) => { + const { projectIdentity, projectName, sources, identityUnavailable } = project; + const source = sources[0]; + const plan = + source && sources.length === 1 && !identityUnavailable + ? planProjectMove(db, projectIdentity, source, cachedProjectMoveMembers(db, source)) + : null; + return { projectIdentity, projectName, multipleSources: sources.length > 1, plan }; + }); +} diff --git a/packages/core/src/project-move-admin.test.ts b/packages/core/src/project-move-admin.test.ts new file mode 100644 index 000000000..512f1f1fd --- /dev/null +++ b/packages/core/src/project-move-admin.test.ts @@ -0,0 +1,648 @@ +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { unassignedProjectIdentity } from "./coordinator-project-moves.js"; +import { readCoordinatorSyncConfig } from "./coordinator-sync-config.js"; +import { connect, type Database } from "./db.js"; +import { managedProjectScopeId } from "./managed-project-scope.js"; +import { getProjectBoundaryMigrationHold } from "./project-boundary-migration-hold.js"; +import { recordProjectBoundaryMigration } from "./project-boundary-migration-records.js"; +import { readLocalProjectMigrationReport } from "./project-migration-report.js"; +import { + listProjectMoveIssues, + type ProjectMoveAdminEffects, + projectMoveAdminEffects, + runProjectMoves, +} from "./project-move-admin.js"; +import { + type RecipientPolicyReconcilerEffects, + reconcileRecipientPolicyProject, +} from "./recipient-policy-reconciler.js"; +import { teamMemberRemovalRefusesScope } from "./team-member-removal-admission.js"; +import { applyTeamMemberRemovals } from "./team-member-removal-policy.js"; + +const NOW = "2026-11-28T10:00:00.000Z"; +const URL = "https://coordinator.example"; +const SOURCE = "team:test:default"; +const PROJECTS = ["repo:one", "repo:three", "repo:two"]; +const TEAM_DEVICES = ["a", "b", "c"]; +const ADMIN = TEAM_DEVICES[0]; +const RAW_CONFIG = { + sync_coordinator_url: URL, + sync_coordinator_group: "test", + sync_coordinator_admin_secret: "test-admin", + sync_boundary_migration: "on", +}; +const config = readCoordinatorSyncConfig(RAW_CONFIG); +let db: Database; + +function scope(id: string, kind = "team_default") { + db.prepare(`INSERT INTO replication_scopes(scope_id,label,kind,authority_type, + coordinator_id,group_id,membership_epoch,created_at,updated_at) + VALUES (?,?,?,'coordinator',?,'test',1,?,?)`).run(id, id, kind, URL, NOW, NOW); +} + +function mapProject(project: string, source = SOURCE) { + db.prepare(`INSERT INTO project_scope_mappings(workspace_identity,project_pattern,scope_id,created_at,updated_at) + VALUES (?,?,?,?,?)`).run(project, project, source, NOW, NOW); +} + +function member(id: string, source = SOURCE) { + db.prepare(`INSERT INTO scope_memberships(scope_id,device_id,membership_epoch,updated_at) + VALUES (?,?,1,?)`).run(source, id, NOW); +} + +function bind(device: string, person = `person-${device}`, inTeam = false) { + db.prepare(`INSERT OR IGNORE INTO actors(actor_id,display_name,is_local,status,created_at,updated_at) + VALUES (?,?,0,'active',?,?)`).run(person, person, NOW, NOW); + db.prepare(`INSERT INTO identity_devices(device_id,identity_id,display_name,status,provenance,revision, + migration_state,idempotency_key,created_at,updated_at) + VALUES (?,?,?,'active','test','1','native',?,?,?)`).run( + device, + person, + `Device ${device}`, + device, + NOW, + NOW, + ); + if (inTeam) + db.prepare(`INSERT INTO policy_team_memberships(team_id,identity_id,role,status,provenance, + revision,migration_state,idempotency_key,created_at,updated_at) + VALUES ('team',?,'member','active','test','1','native',?,?,?)`).run(person, person, NOW, NOW); +} + +beforeEach(() => { + db = connect(":memory:"); + scope(SOURCE); + db.prepare(`INSERT INTO policy_teams(team_id,display_name,status,provenance,revision,migration_state, + idempotency_key,created_at,updated_at) VALUES ('team','Example Team','active','test','1','native','team',?,?)`).run( + NOW, + NOW, + ); + db.prepare(`INSERT INTO policy_team_coordinator_links(team_id,coordinator_id,group_id,source,recorded_at) + VALUES ('team',?,'test','team_create',?)`).run(URL, NOW); + for (const device of TEAM_DEVICES) { + bind(device, `person-${device}`, true); + member(device); + } +}); + +afterEach(() => { + vi.restoreAllMocks(); + db.close(); +}); + +function enrollments() { + const bindings = db + .prepare("SELECT device_id AS deviceId, identity_id AS identityId FROM identity_devices") + .all() as Array<{ deviceId: string; identityId: string }>; + return new Map( + bindings.map(({ deviceId, identityId }) => [deviceId, { enabled: true, identityId }]), + ); +} + +function coordinator(authorized = TEAM_DEVICES) { + const memberships = new Map>(); + const move = vi.fn( + async ({ boundaryScopeId, excludedDeviceIds }) => { + const excluded = authorized.filter((id) => excludedDeviceIds.includes(id)); + const deviceIds = authorized.filter((id) => !excluded.includes(id)); + memberships.set(boundaryScopeId, new Set(deviceIds)); + return { kind: "moved", deviceIds, excludedDeviceIds: excluded, createdAt: NOW }; + }, + ); + const effects = { + readTeamRemovals: vi.fn(async () => []), + readAccess: vi.fn(async (source) => ({ + authorized: + source.scope_id === SOURCE ? authorized : [...(memberships.get(source.scope_id) ?? [])], + enrollments: new Map([ + ...authorized.map((id) => [id, { enabled: true, identityId: null }] as const), + ...enrollments(), + ]), + })), + move, + }; + return { effects, memberships, move }; +} + +function boundary(project: string) { + return managedProjectScopeId("test", project); +} + +function adoptBoundary(project: string) { + const id = boundary(project); + scope(id, "managed_project"); + db.prepare("DELETE FROM project_scope_mappings WHERE workspace_identity = ?").run(project); + mapProject(project, id); +} + +function reconcile(project: string, memberships: Map>) { + const revoke = vi.fn( + async ({ effectId, scopeId, deviceId }) => { + memberships.get(scopeId)?.delete(deviceId); + return { effectId, scopeId, deviceId, status: "revoked" }; + }, + ); + const effects: RecipientPolicyReconcilerEffects = { + now: () => NOW, + async snapshot({ scopeId }) { + const devices = [...(memberships.get(scopeId) ?? [])].sort(); + return { + scopeId, + authoritative: true, + observedAt: NOW, + fingerprint: devices.join(","), + memberships: devices.map((deviceId) => ({ deviceId, status: "active" })), + }; + }, + async listBoundaryEnrollments() { + return [...enrollments()].map(([deviceId, enrollment]) => ({ + ...enrollment, + deviceId, + publicKey: `key-${deviceId}`, + fingerprint: `fp-${deviceId}`, + })); + }, + probeCapability: async () => "supported", + revoke, + async grant({ effectId, deviceId, scopeId }) { + memberships.get(scopeId)?.add(deviceId); + return { effectId, deviceId, scopeId, status: "active" }; + }, + refresh: async () => {}, + }; + return { + revoke, + result: reconcileRecipientPolicyProject( + db, + { + canonicalProjectIdentity: project, + leaseOwner: "test-worker", + }, + effects, + ), + }; +} + +async function expectReconciled( + project: string, + remote: ReturnType, + devices: string[], +) { + adoptBoundary(project); + const pass = reconcile(project, remote.memberships); + expect((await pass.result).safeErrorCode).toBeNull(); + expect(pass.revoke).not.toHaveBeenCalled(); + expect(remote.memberships.get(boundary(project))).toEqual(new Set(devices)); +} + +function recipients() { + return db + .prepare(`SELECT canonical_project_identity AS project, recipient_kind AS kind, recipient_id AS recipient + FROM project_recipients ORDER BY project, kind, recipient`) + .all(); +} + +function report() { + const result = readLocalProjectMigrationReport(db, RAW_CONFIG); + if (result.state !== "local_report") throw new Error("expected migration report"); + return result.project_moves; +} + +it("moves three Projects to their own boundaries without changing the Team's devices", async () => { + for (const project of PROJECTS) mapProject(project); + const remote = coordinator(); + await runProjectMoves(db, config, ADMIN, remote.effects); + expect(remote.move.mock.calls.map(([input]) => input.boundaryScopeId)).toEqual( + PROJECTS.map(boundary), + ); + expect(recipients()).toEqual( + PROJECTS.map((project) => ({ project, kind: "team", recipient: "team" })), + ); + for (const project of PROJECTS) await expectReconciled(project, remote, TEAM_DEVICES); + await runProjectMoves(db, config, ADMIN, remote.effects); + expect(remote.move).toHaveBeenCalledTimes(3); +}); + +it("keeps the device outside the Team and adds only the new devices of the mapped people", async () => { + const project = PROJECTS[0]; + mapProject(project); + bind("outside"); + bind("outside-laptop", "person-outside"); + bind("team-laptop", "person-a"); + bind("unrelated"); + member("outside"); + const original = [...TEAM_DEVICES, "outside"]; + const remote = coordinator(original); + expect(report()?.[0]?.plan?.newReceivers.map(({ deviceId }) => deviceId)).toEqual([ + "outside-laptop", + "team-laptop", + ]); + expect(recipients()).toEqual([]); + await runProjectMoves(db, config, ADMIN, remote.effects); + expect(recipients()).toEqual([ + { project, kind: "identity", recipient: "person-outside" }, + { project, kind: "team", recipient: "team" }, + ]); + await expectReconciled(project, remote, [...original, "outside-laptop", "team-laptop"]); +}); + +function shareTeam(project: string) { + db.prepare(`INSERT INTO project_recipients(canonical_project_identity,recipient_kind,recipient_id,status, + provenance,policy_revision,migration_state,idempotency_key,created_at,updated_at) + VALUES (?,'team','team','active','test','1','native','share',?,?)`).run(project, NOW, NOW); +} + +const teamRemoval = { + removal_seq: 1, + group_id: "test", + team_id: "team", + identity_id: "person-c", + removed_at: NOW, + removed_by_device_id: ADMIN, +}; + +function removeTeamMember() { + applyTeamMemberRemovals(db, { + coordinatorId: URL, + groupId: "test", + now: NOW, + removals: [teamRemoval], + }); +} + +it.each([ + ["removed Team member", removeTeamMember, true], + ["removed Team member without a recipient row", removeTeamMember, false], + [ + "deactivated person", + () => db.prepare("UPDATE actors SET status = 'deactivated' WHERE actor_id = 'person-c'").run(), + false, + ], +])("excludes a %s who still has an active source membership", async (_, withdraw, share) => { + const [project] = PROJECTS; + mapProject(project); + if (share) shareTeam(project); + withdraw(); + expect(teamMemberRemovalRefusesScope(db, { scopeId: SOURCE, deviceId: "c" })).toBe(share); + expect( + db + .prepare("SELECT status FROM scope_memberships WHERE scope_id = ? AND device_id = 'c'") + .pluck() + .get(SOURCE), + ).toBe("active"); + expect(report()?.[0]?.plan?.excludedDevices).toEqual([{ deviceId: "c", name: "Device c" }]); + const remote = coordinator(); + await runProjectMoves(db, config, ADMIN, remote.effects); + expect(remote.move.mock.calls[0]?.[0].excludedDeviceIds).toEqual(["c"]); + expect(recipients()).toEqual([{ project, kind: "team", recipient: "team" }]); + await expectReconciled(project, remote, ["a", "b"]); +}); + +it.each([ + ["keeps a direct share after a Team removal", "direct-share"], + ["applies a coordinator Team removal missing from the local roster", "remote-removal"], + ["revokes a copied membership after deactivation", "deactivated"], +] as const)("%s during a move", async (_, change) => { + const [project] = PROJECTS; + mapProject(project); + if (change === "direct-share") { + db.prepare(`INSERT INTO project_recipients(canonical_project_identity,recipient_kind,recipient_id,status, + provenance,policy_revision,migration_state,idempotency_key,created_at,updated_at) + VALUES (?,'identity','person-c','active','user','1','native','direct',?,?)`).run( + project, + NOW, + NOW, + ); + } + const remote = coordinator(); + const committed = Promise.withResolvers(); + const respond = Promise.withResolvers(); + const move = remote.move.getMockImplementation(); + if (!move) throw new Error("missing test coordinator move"); + remote.move.mockImplementationOnce(async (input) => { + const result = await move(input); + committed.resolve(); + await respond.promise; + return result; + }); + const moving = runProjectMoves(db, config, ADMIN, remote.effects); + await committed.promise; + if (change === "direct-share") removeTeamMember(); + if (change === "remote-removal") remote.effects.readTeamRemovals.mockResolvedValue([teamRemoval]); + if (change === "deactivated") + db.prepare("UPDATE actors SET status = 'deactivated' WHERE actor_id = 'person-c'").run(); + respond.resolve(); + await moving; + + expect(getProjectBoundaryMigrationHold(db, boundary(project))?.held).toBe(false); + expect(remote.memberships.get(boundary(project))).toEqual(new Set(TEAM_DEVICES)); + adoptBoundary(project); + const pass = reconcile(project, remote.memberships); + expect((await pass.result).safeErrorCode).toBeNull(); + if (change === "direct-share") { + expect(pass.revoke).not.toHaveBeenCalled(); + expect(remote.memberships.get(boundary(project))).toEqual(new Set(TEAM_DEVICES)); + return; + } + expect(pass.revoke).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ scopeId: boundary(project), deviceId: "c" }), + ); + expect(remote.memberships.get(boundary(project))).toEqual(new Set(["a", "b"])); +}); + +it("reports Projects with migration off without requesting a move", async () => { + mapProject(PROJECTS[0]); + const off = { ...RAW_CONFIG, sync_boundary_migration: "off" }; + const remote = coordinator(); + await runProjectMoves(db, readCoordinatorSyncConfig(off), ADMIN, remote.effects); + expect.soft(remote.move).not.toHaveBeenCalled(); + expect(readLocalProjectMigrationReport(db, off)).toMatchObject({ + mode: "off", + state: "local_report", + project_moves: [{ projectIdentity: PROJECTS[0] }], + }); +}); + +it("names an unlinked device without moving any Project in its sharing setup", async () => { + for (const project of PROJECTS) mapProject(project); + member("unlinked"); + db.prepare( + "INSERT INTO sync_peers(peer_device_id,name,created_at) VALUES ('unlinked','Office Mac',?)", + ).run(NOW); + const remote = coordinator([...TEAM_DEVICES, "unlinked"]); + await runProjectMoves(db, config, ADMIN, remote.effects); + expect(remote.move).not.toHaveBeenCalled(); + expect(recipients()).toEqual([]); + expect(report()?.[0]?.plan?.unlinkedDevices).toEqual([ + { deviceId: "unlinked", name: "Office Mac" }, + ]); + expect(listProjectMoveIssues(db)).toEqual( + PROJECTS.map((projectIdentity) => ({ + projectIdentity, + projectName: projectIdentity, + reason: "unlinked_devices", + devices: [{ deviceId: "unlinked", name: "Office Mac" }], + })), + ); +}); + +it("lists a Project in two older sharing setups and leaves its sharing unchanged", async () => { + scope("other", "client"); + mapProject(PROJECTS[0]); + mapProject(PROJECTS[0], "other"); + const remote = coordinator(); + await runProjectMoves(db, config, ADMIN, remote.effects); + expect(remote.move).not.toHaveBeenCalled(); + expect(report()).toEqual([ + expect.objectContaining({ projectIdentity: PROJECTS[0], multipleSources: true, plan: null }), + ]); + expect(listProjectMoveIssues(db)[0]?.reason).toBe("multiple_sources"); +}); + +it("holds a Project whose Team is linked to a different coordinator group", async () => { + const [project] = PROJECTS; + mapProject(project); + shareTeam(project); + db.prepare( + "UPDATE policy_team_coordinator_links SET group_id = 'other' WHERE team_id = 'team'", + ).run(); + const remote = coordinator(); + await runProjectMoves(db, config, ADMIN, remote.effects); + expect(remote.move).not.toHaveBeenCalled(); + expect(report()?.[0]?.plan).toMatchObject({ teamInAnotherGroup: true }); + expect(listProjectMoveIssues(db)[0]?.reason).toBe("team_in_another_group"); +}); + +it("uses the reserved Unassigned identity for a memory without a Project", async () => { + db.exec(`INSERT INTO sessions(id,started_at) VALUES (1,'now'); + INSERT INTO memory_items(session_id,kind,title,body_text,created_at,updated_at,scope_id,workspace_id) + VALUES (1,'note','title','body','now','now','${SOURCE}','shared:default');`); + const remote = coordinator(); + const project = unassignedProjectIdentity(SOURCE); + expect(report()).toEqual([ + expect.objectContaining({ projectIdentity: project, projectName: "Unassigned" }), + ]); + await runProjectMoves(db, config, ADMIN, remote.effects); + expect(remote.move.mock.calls[0]?.[0].boundaryScopeId).toBe(boundary(project)); + expect(recipients()).toEqual([{ project, kind: "team", recipient: "team" }]); +}); + +it.each(["devices_not_updated", "device_keys_missing"] as const)( + "names the device when the coordinator refuses a move with %s", + async (reason) => { + mapProject(PROJECTS[0]); + const fetch = vi.spyOn(globalThis, "fetch").mockResolvedValue( + Response.json( + { + error: "project_move_refused", + reason, + device_ids: ["b"], + }, + { status: 409 }, + ), + ); + await runProjectMoves(db, config, ADMIN, { + ...coordinator().effects, + move: projectMoveAdminEffects(config).move, + }); + expect(fetch).toHaveBeenCalledWith( + `${URL}/v1/admin/groups/test/project-moves`, + expect.objectContaining({ method: "POST", redirect: "error" }), + ); + expect(await new Response(fetch.mock.calls[0]?.[1]?.body).json()).toEqual({ + source_scope_id: SOURCE, + boundary_scope_id: boundary(PROJECTS[0]), + device_id: ADMIN, + excluded_device_ids: [], + team_removal_seq: 0, + }); + expect(listProjectMoveIssues(db)).toEqual([ + expect.objectContaining({ + reason, + devices: [{ deviceId: "b", name: "Device b" }], + }), + ]); + expect(recipients()).toEqual([]); + }, +); + +it("rebuilds the exclusion list and sends the applied sequence after Team removals change", async () => { + const [project] = PROJECTS; + mapProject(project); + const removal = { + removal_seq: 12, + group_id: "test", + team_id: "team", + identity_id: "person-c", + removed_at: NOW, + removed_by_device_id: ADMIN, + }; + applyTeamMemberRemovals(db, { + coordinatorId: URL, + groupId: "other", + now: NOW, + removals: [{ ...removal, group_id: "other", removal_seq: 99 }], + }); + const fetch = vi + .spyOn(globalThis, "fetch") + .mockResolvedValueOnce(removalsChanged()) + .mockResolvedValueOnce(loggedMoveResponse(project, ["c"])); + const readTeamRemovals = vi.fn(async () => [removal]); + const remote = coordinator(); + remote.memberships.set(boundary(project), new Set(["a", "b"])); + const effects = { + ...remote.effects, + move: projectMoveAdminEffects(config).move, + readTeamRemovals, + }; + await runProjectMoves(db, config, ADMIN, effects); + const requests = await Promise.all( + fetch.mock.calls.map(([, init]) => new Response(init?.body).json()), + ); + expect(requests).toEqual([ + expect.objectContaining({ team_removal_seq: 0, excluded_device_ids: [] }), + expect.objectContaining({ team_removal_seq: 12, excluded_device_ids: ["c"] }), + ]); + expect(readTeamRemovals).toHaveBeenCalledTimes(2); + expect(recipients()).toEqual([{ project, kind: "team", recipient: "team" }]); +}); + +function removalsChanged() { + return Response.json( + { error: "project_move_refused", reason: "team_removals_changed", device_ids: [] }, + { status: 409 }, + ); +} + +it("leaves the Project in place when Team removals change on every retry", async () => { + mapProject(PROJECTS[0]); + const fetch = vi.spyOn(globalThis, "fetch").mockImplementation(async () => removalsChanged()); + const readTeamRemovals = vi.fn(async () => []); + await runProjectMoves(db, config, ADMIN, { + ...coordinator().effects, + move: projectMoveAdminEffects(config).move, + readTeamRemovals, + }); + expect(fetch).toHaveBeenCalledTimes(3); + expect(readTeamRemovals).toHaveBeenCalledTimes(2); + expect(recipients()).toEqual([]); +}); + +it.each([ + { conflict: false, name: "automatically releases the hold after recording matching intent" }, + { conflict: true, name: "rolls back mismatched intent and keeps reconciliation on hold" }, +])("$name", async ({ conflict }) => { + const project = PROJECTS[0]; + const id = boundary(project); + const remote = coordinator(); + if (conflict) { + bind("unrelated"); + db.prepare(`INSERT INTO project_recipients(canonical_project_identity,recipient_kind,recipient_id,status, + provenance,policy_revision,migration_state,idempotency_key,created_at,updated_at) + VALUES (?,'identity','person-unrelated','active','user','1','native','conflict',?,?)`).run( + project, + NOW, + NOW, + ); + } + remote.move.mockImplementation(async () => { + adoptBoundary(project); + recordProjectBoundaryMigration(db, { + boundaryScopeId: id, + sourceScopeId: SOURCE, + state: "committed", + generation: 1, + now: NOW, + }); + remote.memberships.set(id, new Set(TEAM_DEVICES)); + const pass = reconcile(project, remote.memberships); + expect(await pass.result).toMatchObject({ + status: "waiting", + safeErrorCode: "project_move_recipients_pending", + }); + expect(pass.revoke).not.toHaveBeenCalled(); + return { kind: "moved", deviceIds: TEAM_DEVICES, excludedDeviceIds: [], createdAt: NOW }; + }); + mapProject(project); + await runProjectMoves(db, config, ADMIN, remote.effects); + expect(getProjectBoundaryMigrationHold(db, id)?.held).toBe(conflict); + expect(recipients()).toEqual([ + conflict + ? { project, kind: "identity", recipient: "person-unrelated" } + : { project, kind: "team", recipient: "team" }, + ]); + expect(listProjectMoveIssues(db).map(({ reason }) => reason)).toEqual( + conflict ? ["access_needs_attention"] : [], + ); +}); + +it("keeps the hold when the coordinator copied a device missing from the earlier read", async () => { + const project = PROJECTS[0]; + mapProject(project); + const remote = coordinator(); + remote.move.mockResolvedValue({ + kind: "moved", + createdAt: NOW, + deviceIds: [...TEAM_DEVICES, "new-unlinked"], + excludedDeviceIds: [], + }); + await runProjectMoves(db, config, ADMIN, remote.effects); + expect(listProjectMoveIssues(db)[0]).toMatchObject({ + reason: "unlinked_devices", + devices: [{ deviceId: "new-unlinked" }], + }); + expect(recipients()).toEqual([]); + expect(getProjectBoundaryMigrationHold(db, boundary(project))?.held).toBe(true); +}); + +function loggedMoveResponse(project: string, excluded_devices: string[] = []) { + return Response.json({ + repeated: true, + move: { + version: 1, + group_id: "test", + source_scope_id: SOURCE, + boundary_scope_id: boundary(project), + committed_by_device_id: ADMIN, + created_at: NOW, + granted_devices: TEAM_DEVICES.filter((id) => !excluded_devices.includes(id)).map( + (device_id) => ({ device_id, role: "member" }), + ), + excluded_devices, + }, + }); +} + +it("finishes a logged move from another admin after its response was lost", async () => { + const project = PROJECTS[0]; + mapProject(project); + vi.spyOn(globalThis, "fetch") + .mockRejectedValueOnce(new Error("response lost")) + .mockResolvedValueOnce(loggedMoveResponse(project)); + const remote = coordinator(); + remote.memberships.set(boundary(project), new Set(TEAM_DEVICES)); + const effects = { ...remote.effects, move: projectMoveAdminEffects(config).move }; + await runProjectMoves(db, config, ADMIN, effects); + expect(recipients()).toEqual([]); + remote.effects.readTeamRemovals.mockResolvedValue([teamRemoval]); + await runProjectMoves(db, config, "b", effects); + expect(recipients()).toEqual([{ project, kind: "team", recipient: "team" }]); + expect(getProjectBoundaryMigrationHold(db, boundary(project))?.held).toBe(false); + adoptBoundary(project); + const pass = reconcile(project, remote.memberships); + expect((await pass.result).safeErrorCode).toBeNull(); + expect(remote.memberships.get(boundary(project))).toEqual(new Set(["a", "b"])); +}); + +it("does not let a repeat re-add a device that the move log excluded", async () => { + const project = PROJECTS[0]; + mapProject(project); + bind("a-laptop", "person-a"); + vi.spyOn(globalThis, "fetch").mockResolvedValue(loggedMoveResponse(project, ["a-laptop"])); + await runProjectMoves(db, config, ADMIN, { + ...coordinator().effects, + move: projectMoveAdminEffects(config).move, + }); + expect(recipients()).toEqual([]); + expect(getProjectBoundaryMigrationHold(db, boundary(project))?.held).toBe(true); +}); diff --git a/packages/core/src/project-move-admin.ts b/packages/core/src/project-move-admin.ts new file mode 100644 index 000000000..6ed1761bf --- /dev/null +++ b/packages/core/src/project-move-admin.ts @@ -0,0 +1,494 @@ +import { createHash } from "node:crypto"; +import { + coordinatorListDevicesAction, + coordinatorListScopeMembershipsAction, +} from "./coordinator-actions.js"; +import { + type CommitProjectMoveInput, + MAX_PROJECT_MOVE_EXCLUSIONS, + PROJECT_MOVE_COMMIT_PATH, + type ProjectMove, +} from "./coordinator-project-moves.js"; +import { type CoordinatorSyncConfig, isCoordinatorAdminDevice } from "./coordinator-sync-config.js"; +import { coordinatorListTeamMemberRemovalsAction } from "./coordinator-team-member-removal-client.js"; +import type { CoordinatorTeamMemberRemoval } from "./coordinator-team-member-removals.js"; +import type { Database } from "./db.js"; +import { managedProjectScopeId } from "./managed-project-scope.js"; +import { clearProjectBoundaryMigrationHold } from "./project-boundary-migration-hold.js"; +import { recordProjectBoundaryMigration } from "./project-boundary-migration-records.js"; +import { + cachedProjectMoveMembers, + listProjectMoveCandidates, + type ProjectMoveCandidate, + type ProjectMoveDevice, + type ProjectMovePlan, + type ProjectMoveSource, + planProjectMove, + projectMoveDevices, +} from "./project-move-plan.js"; +import { deriveRecipientPolicyEffectiveDevicesFromDatabase } from "./recipient-policy-reconciliation.js"; +import { buildBaseUrl, normalizedCoordinatorId, requestJson } from "./sync-http-client.js"; +import { applyTeamMemberRemovals } from "./team-member-removal-policy.js"; + +export interface ProjectMoveIssue { + projectIdentity: string; + projectName: string; + reason: + | "multiple_sources" + | "team_in_another_group" + | "unlinked_devices" + | "devices_not_updated" + | "device_keys_missing" + | "access_needs_attention"; + devices: ProjectMoveDevice[]; +} + +const lastIssues = new WeakMap(); + +function issue( + { projectIdentity, projectName }: ProjectMoveCandidate, + reason: ProjectMoveIssue["reason"], + devices: ProjectMoveDevice[] = [], +): ProjectMoveIssue { + return { projectIdentity, projectName, reason, devices }; +} + +export function listProjectMoveIssues(db: Database): ProjectMoveIssue[] { + return lastIssues.get(db) ?? []; +} + +interface SourceAccess { + authorized: string[]; + enrollments: ReadonlyMap< + string, + { enabled: boolean; identityId: string | null; name?: string | null } + >; +} + +type MoveResult = + | { kind: "moved"; deviceIds: string[]; excludedDeviceIds: string[]; createdAt: string } + | { kind: "devices_not_updated" | "device_keys_missing"; deviceIds: string[] } + | { kind: "team_removals_changed" } + | { kind: "unavailable" } + | { kind: "refused" }; + +export interface ProjectMoveAdminEffects { + readAccess(source: ProjectMoveSource): Promise; + readTeamRemovals(source: ProjectMoveSource): Promise; + move(input: CommitProjectMoveInput): Promise; +} + +function projectMoveRequestBody({ + sourceScopeId, + boundaryScopeId, + deviceId, + excludedDeviceIds, + teamRemovalSeq, +}: CommitProjectMoveInput) { + return { + source_scope_id: sourceScopeId, + boundary_scope_id: boundaryScopeId, + device_id: deviceId, + excluded_device_ids: excludedDeviceIds, + team_removal_seq: teamRemovalSeq, + }; +} + +function asDeviceIds(value: unknown): string[] | null { + if (!Array.isArray(value) || !value.every((id) => typeof id === "string" && id.length > 0)) + return null; + return [...new Set(value)]; +} + +function readMoveResult( + status: number, + body: Record | null, + expected: CommitProjectMoveInput, +): MoveResult { + if (status === 404 || (status === 503 && body?.error === "project_moves_unavailable")) + return { kind: "unavailable" }; + if (status === 409 && body?.error === "project_move_refused") return readMoveRefusal(body); + const move = body?.move as Partial | undefined; + if ( + status === 200 && + move?.version === 1 && + move.group_id === expected.groupId && + move.source_scope_id === expected.sourceScopeId && + move.boundary_scope_id === expected.boundaryScopeId && + (body?.repeated === true || move.committed_by_device_id === expected.deviceId) && + typeof move.created_at === "string" && + Array.isArray(move.granted_devices) + ) { + const deviceIds = asDeviceIds(move.granted_devices.map((device) => device?.device_id)); + const excludedDeviceIds = asDeviceIds(move.excluded_devices); + if (deviceIds?.length && excludedDeviceIds) + return { kind: "moved", deviceIds, excludedDeviceIds, createdAt: move.created_at }; + } + return { kind: "refused" }; +} + +function readMoveRefusal(body: Record): MoveResult { + const reason = body.reason; + if (reason === "team_removals_changed") return { kind: reason }; + if (reason === "devices_not_updated" || reason === "device_keys_missing") { + const deviceIds = asDeviceIds(body.device_ids); + if (deviceIds?.length) return { kind: reason, deviceIds }; + } + return { kind: "refused" }; +} + +export function projectMoveAdminEffects(config: CoordinatorSyncConfig): ProjectMoveAdminEffects { + const remoteUrl = buildBaseUrl(config.syncCoordinatorUrl); + const adminSecret = config.syncCoordinatorAdminSecret; + const readAccess = createSourceAccessReader(config, remoteUrl); + return { + readAccess, + readTeamRemovals: (source) => + coordinatorListTeamMemberRemovalsAction({ + groupId: source.group_id, + remoteUrl, + adminSecret, + timeoutS: config.syncCoordinatorTimeoutS, + }), + async move(input) { + const path = PROJECT_MOVE_COMMIT_PATH.replace(":group_id", encodeURIComponent(input.groupId)); + const [status, response] = await requestJson("POST", `${remoteUrl}${path}`, { + headers: { "X-Codemem-Coordinator-Admin": adminSecret }, + body: projectMoveRequestBody(input), + timeoutS: config.syncCoordinatorTimeoutS, + maxResponseBytes: 256 * 1024, + }); + return readMoveResult(status, response, input); + }, + }; +} + +function createSourceAccessReader( + config: CoordinatorSyncConfig, + remoteUrl: string, +): ProjectMoveAdminEffects["readAccess"] { + return async (source) => { + const target = { + groupId: source.group_id, + remoteUrl, + adminSecret: config.syncCoordinatorAdminSecret, + }; + const [devices, members] = await Promise.all([ + coordinatorListDevicesAction({ + ...target, + includeDisabled: true, + timeoutS: config.syncCoordinatorTimeoutS, + }), + coordinatorListScopeMembershipsAction({ ...target, scopeId: source.scope_id }), + ]); + const enrollments = new Map( + devices.map((device) => [ + device.device_id, + { + enabled: device.enabled === 1 && !device.revoked, + identityId: device.identity_id, + name: device.display_name, + }, + ]), + ); + return { + enrollments, + authorized: members + .filter( + (member) => + member.scope_id === source.scope_id && + member.status === "active" && + member.membership_epoch >= source.membership_epoch && + enrollments.get(member.device_id)?.enabled, + ) + .map((member) => member.device_id), + }; + }; +} + +function recordRecipients( + db: Database, + project: ProjectMoveCandidate, + plan: ProjectMovePlan, + boundaryScopeId: string, + now: string, +): void { + db.transaction(() => { + const insert = db.prepare( + `INSERT INTO project_recipients(canonical_project_identity, recipient_kind, recipient_id, status, + provenance, policy_revision, migration_state, idempotency_key, created_at, updated_at) + VALUES (?, ?, ?, 'active', 'project_boundary_migration', ?, 'applied', ?, ?, ?) + ON CONFLICT(canonical_project_identity, recipient_kind, recipient_id) DO NOTHING`, + ); + for (const { recipientKind, recipientId } of plan.recipients) { + const key = createHash("sha256") + .update(JSON.stringify([boundaryScopeId, recipientKind, recipientId])) + .digest("hex"); + insert.run( + project.projectIdentity, + recipientKind, + recipientId, + key, + `project-move:${key}`, + now, + now, + ); + } + const actual = deriveRecipientPolicyEffectiveDevicesFromDatabase(db, project.projectIdentity); + const expected = new Set(plan.receivingDevices.map(({ deviceId }) => deviceId)); + if ( + actual.status !== "eligible" || + actual.devices.length !== expected.size || + actual.devices.some(({ deviceId }) => !expected.has(deviceId)) + ) { + throw new Error("project_move_recipient_intent_conflict"); + } + // Device adoption installs the migration record before exposing the mapping. + // Only this transaction releases the reconciler to use the saved recipients. + if ( + !clearProjectBoundaryMigrationHold(db, { + boundaryScopeId, + generation: 1, + reason: "migration_recipients_recorded", + now, + }) + ) { + throw new Error("project_move_hold_not_cleared"); + } + }).immediate(); +} + +function planIssue(project: ProjectMoveCandidate, plan: ProjectMovePlan): ProjectMoveIssue | null { + if (plan.teamInAnotherGroup) return issue(project, "team_in_another_group"); + if (plan.unlinkedDevices.length) return issue(project, "unlinked_devices", plan.unlinkedDevices); + if (plan.needsAttention) return issue(project, "access_needs_attention"); + return null; +} + +function sourceBindingsMatch( + db: Database, + deviceIds: readonly string[], + access: SourceAccess, +): boolean { + const lookup = db + .prepare("SELECT identity_id FROM identity_devices WHERE device_id = ? AND status = 'active'") + .pluck(); + return deviceIds.every((id) => { + const enrollment = access.enrollments.get(id); + return ( + enrollment && (enrollment.identityId === null || enrollment.identityId === lookup.get(id)) + ); + }); +} + +function highestAppliedTeamRemoval(db: Database, source: ProjectMoveSource): number { + const coordinator = normalizedCoordinatorId(source.coordinator_id); + const rows = db + .prepare( + `SELECT coordinator_id, MAX(removal_seq) AS seq FROM policy_team_member_removals + WHERE group_id = ? GROUP BY coordinator_id`, + ) + .all(source.group_id) as Array<{ coordinator_id: string; seq: number }>; + return rows.reduce( + (seq, row) => + normalizedCoordinatorId(row.coordinator_id) === coordinator ? Math.max(seq, row.seq) : seq, + 0, + ); +} + +async function refreshTeamRemovals( + db: Database, + source: ProjectMoveSource, + effects: ProjectMoveAdminEffects, +): Promise { + const removals = await effects.readTeamRemovals(source); + applyTeamMemberRemovals(db, { + coordinatorId: buildBaseUrl(source.coordinator_id), + groupId: source.group_id, + removals, + now: new Date().toISOString(), + }); +} + +async function requestProjectMove( + db: Database, + project: ProjectMoveCandidate, + source: ProjectMoveSource, + access: SourceAccess, + deviceId: string, + effects: ProjectMoveAdminEffects, +): Promise< + | { problem: ProjectMoveIssue } + | { result: MoveResult; boundaryScopeId: string; excluded: Set } +> { + const boundaryScopeId = managedProjectScopeId(source.group_id, project.projectIdentity); + const fallbackName = (id: string) => access.enrollments.get(id)?.name; + for (let attempt = 1; attempt <= 3; attempt++) { + const { plan, teamRemovalSeq } = db + .transaction(() => ({ + plan: planProjectMove(db, project.projectIdentity, source, access.authorized, fallbackName), + teamRemovalSeq: highestAppliedTeamRemoval(db, source), + })) + .deferred(); + const problem = planIssue(project, plan); + if (problem) return { problem }; + const excluded = new Set(plan.excludedDevices.map(({ deviceId }) => deviceId)); + if ( + excluded.size > MAX_PROJECT_MOVE_EXCLUSIONS || + excluded.has(deviceId) || + !sourceBindingsMatch( + db, + access.authorized.filter((id) => !excluded.has(id)), + access, + ) + ) + break; + const result = await effects.move({ + groupId: source.group_id, + sourceScopeId: source.scope_id, + boundaryScopeId, + deviceId, + excludedDeviceIds: [...excluded], + teamRemovalSeq, + }); + if (result.kind !== "team_removals_changed") return { result, boundaryScopeId, excluded }; + if (attempt === 3) break; + await refreshTeamRemovals(db, source, effects); + } + return { problem: issue(project, "access_needs_attention") }; +} + +async function moveCandidate( + db: Database, + project: ProjectMoveCandidate, + source: ProjectMoveSource, + access: SourceAccess, + deviceId: string, + effects: ProjectMoveAdminEffects, +): Promise { + const request = await requestProjectMove(db, project, source, access, deviceId, effects); + if ("problem" in request) return request.problem; + const { result, boundaryScopeId, excluded } = request; + const fallbackName = (id: string) => access.enrollments.get(id)?.name; + if (result.kind === "unavailable") return null; + if (result.kind !== "moved") { + if ("deviceIds" in result) + return issue(project, result.kind, projectMoveDevices(db, result.deviceIds, fallbackName)); + return issue(project, "access_needs_attention"); + } + + recordProjectBoundaryMigration(db, { + boundaryScopeId, + sourceScopeId: source.scope_id, + state: "committed", + generation: 1, + now: result.createdAt, + }); + const boundary = await effects.readAccess({ + ...source, + scope_id: boundaryScopeId, + kind: "managed_project", + membership_epoch: 1, + }); + await refreshTeamRemovals(db, source, effects); + const copied = result.deviceIds.filter((id) => boundary.enrollments.get(id)?.enabled !== false); + const committedPlan = planProjectMove(db, project.projectIdentity, source, copied, fallbackName); + const committedProblem = planIssue(project, committedPlan); + if (committedProblem) return committedProblem; + for (const id of result.excludedDeviceIds) excluded.add(id); + if ( + result.excludedDeviceIds.some((id) => boundary.authorized.includes(id)) || + committedPlan.receivingDevices.some(({ deviceId }) => excluded.has(deviceId)) + ) + return issue(project, "access_needs_attention"); + if (!boundaryMatchesPlan(db, boundary, copied, committedPlan)) + return issue(project, "access_needs_attention"); + recordRecipients(db, project, committedPlan, boundaryScopeId, result.createdAt); + return null; +} + +function boundaryMatchesPlan( + db: Database, + boundary: SourceAccess, + copied: string[], + plan: ProjectMovePlan, +): boolean { + // Only the ordinary reconciler removes copied devices that have since lost access. + const withdrawn = new Set(plan.excludedDevices.map(({ deviceId }) => deviceId)); + const continuing = copied.filter((id) => !withdrawn.has(id)); + const current = new Set(boundary.authorized); + const desired = new Set(plan.receivingDevices.map(({ deviceId }) => deviceId)); + return ( + boundary.authorized.every((id) => desired.has(id) || withdrawn.has(id)) && + continuing.every((id) => current.has(id) && desired.has(id)) && + sourceBindingsMatch(db, continuing, boundary) + ); +} + +export async function runProjectMoves( + db: Database, + config: CoordinatorSyncConfig, + deviceId: string, + effects = projectMoveAdminEffects(config), +): Promise { + if (config.syncBoundaryMigrationEnabled !== true) { + lastIssues.delete(db); + return; + } + const results: ProjectMoveIssue[] = []; + const coordinator = normalizedCoordinatorId(config.syncCoordinatorUrl); + const canMove = isCoordinatorAdminDevice(config) && coordinator !== null; + const forSource = createSourceMover(db, deviceId, effects); + for (const project of listProjectMoveCandidates(db)) { + const source = project.sources[0]; + if (!source) continue; + if (project.sources.length > 1) { + results.push(issue(project, "multiple_sources")); + continue; + } + if (project.identityUnavailable) { + results.push(issue(project, "access_needs_attention")); + continue; + } + const matchesConfig = + canMove && + normalizedCoordinatorId(source.coordinator_id) === coordinator && + config.syncCoordinatorGroups.includes(source.group_id); + const problem = matchesConfig + ? await forSource(project, source) + : planIssue( + project, + planProjectMove( + db, + project.projectIdentity, + source, + cachedProjectMoveMembers(db, source), + ), + ); + if (problem) results.push(problem); + } + lastIssues.set(db, results); +} + +function createSourceMover(db: Database, deviceId: string, effects: ProjectMoveAdminEffects) { + const accessBySource = new Map(); + return async ( + project: ProjectMoveCandidate, + source: ProjectMoveSource, + ): Promise => { + try { + let access = accessBySource.get(source.scope_id); + if (!access) { + access = await effects.readAccess(source); + accessBySource.set(source.scope_id, access); + } + if (!access.authorized.length) return null; + // The existing reconciler needs the local managed mapping, and only a + // member can read the copied boundary from the coordinator. + if (!access.authorized.includes(deviceId)) return issue(project, "access_needs_attention"); + return await moveCandidate(db, project, source, access, deviceId, effects); + } catch { + return issue(project, "access_needs_attention"); + } + }; +} diff --git a/packages/core/src/project-move-plan.ts b/packages/core/src/project-move-plan.ts new file mode 100644 index 000000000..39de04d3a --- /dev/null +++ b/packages/core/src/project-move-plan.ts @@ -0,0 +1,385 @@ +import { unassignedProjectIdentity } from "./coordinator-project-moves.js"; +import type { Database } from "./db.js"; +import { managedProjectScopeId } from "./managed-project-scope.js"; +import { getProjectBoundaryMigrationHold } from "./project-boundary-migration-hold.js"; +import { listProjectBoundaryMigrationRecords } from "./project-boundary-migration-records.js"; +import { + activeProjectRecipientIds, + deriveRecipientPolicyEffectiveDevicesFromDatabase, +} from "./recipient-policy-reconciliation.js"; +import { + canonicalRepositoryProjectIdentity, + readRepositoryIdentitySnapshot, + repositoryIdentitiesByWorkspace, + repositoryIdentityForWorkspace, +} from "./repository-mapping-aliases.js"; +import { isScopeDeviceAdmissionRefused } from "./scope-device-admission.js"; +import { SYNC_BOOTSTRAP_CWD_PREFIX } from "./sync-bootstrap-constants.js"; +import { normalizedCoordinatorId } from "./sync-http-client.js"; +import { teamMemberRemovalRefusesScope } from "./team-member-removal-admission.js"; +import { + removedTeamMemberIdentityIds, + teamCoordinatorLinkState, +} from "./team-member-removal-lookup.js"; +import { canonicalWorkspaceIdentity } from "./workspace-identity.js"; + +export interface ProjectMoveSource { + scope_id: string; + group_id: string; + coordinator_id: string; + membership_epoch: number; + kind: string; +} + +export interface ProjectMoveCandidate { + projectIdentity: string; + projectName: string; + sources: ProjectMoveSource[]; + identityUnavailable?: boolean; +} + +export interface ProjectMoveDevice { + deviceId: string; + name: string; +} + +interface MoveRecipient { + recipientKind: "identity" | "team"; + recipientId: string; + name: string; +} + +export interface ProjectMovePlan { + recipients: MoveRecipient[]; + receivingDevices: ProjectMoveDevice[]; + newReceivers: ProjectMoveDevice[]; + excludedDevices: ProjectMoveDevice[]; + unlinkedDevices: ProjectMoveDevice[]; + needsAttention: boolean; + teamInAnotherGroup: boolean; +} + +interface ProjectMemoryEvidence { + scope_id: string; + cwd: string | null; + project: string | null; + git_remote: string | null; + metadata_json: string | null; + workspace_id: string | null; +} + +export function olderProjectScopes(db: Database): ProjectMoveSource[] { + return db + .prepare( + `SELECT scope_id, coordinator_id, group_id, membership_epoch, kind FROM replication_scopes + WHERE authority_type = 'coordinator' AND coordinator_id IS NOT NULL AND group_id IS NOT NULL + AND status = 'active' AND kind NOT IN ('managed_project', 'personal') + AND scope_id NOT LIKE 'personal:%' AND scope_id NOT LIKE 'managed-project:%' + ORDER BY scope_id`, + ) + .all() as ProjectMoveSource[]; +} + +function readMoveProgress(db: Database) { + const pendingSources = new Map(); + const finished = new Set(); + for (const { boundaryScopeId, sourceScopeId, state } of listProjectBoundaryMigrationRecords(db)) { + if (state !== "committed") continue; + const hold = getProjectBoundaryMigrationHold(db, boundaryScopeId); + if (hold?.held) pendingSources.set(boundaryScopeId, sourceScopeId); + if (hold?.clearedReason === "migration_recipients_recorded") finished.add(boundaryScopeId); + } + return { pendingSources, finished }; +} + +/** Read the mappings and stored copies, including copies received from other devices. */ +export function listProjectMoveCandidates(db: Database): ProjectMoveCandidate[] { + return db.transaction(() => readProjectMoveCandidates(db)).deferred(); +} + +function readProjectMoveCandidates(db: Database): ProjectMoveCandidate[] { + const scopes = new Map(olderProjectScopes(db).map((scope) => [scope.scope_id, scope])); + if (!scopes.size) return []; + const { pendingSources, finished } = readMoveProgress(db); + const snapshot = readRepositoryIdentitySnapshot(db); + const repositories = repositoryIdentitiesByWorkspace(db, { + repositoryIdentitySnapshot: { ...snapshot, workspaces: [] }, + }); + const canonical = (value: string) => canonicalRepositoryProjectIdentity(repositories, value); + const candidates = new Map(); + const add = ( + identity: string, + scopeId: string, + name?: string | null, + identityUnavailable = false, + ) => { + const source = scopes.get(pendingSources.get(scopeId) ?? scopeId); + if (!source || finished.has(managedProjectScopeId(source.group_id, identity))) return; + const existing = candidates.get(identity) ?? { + projectIdentity: identity, + projectName: name || identity, + sources: [], + ...(identityUnavailable ? { identityUnavailable } : {}), + }; + if (name && existing.projectName === identity) existing.projectName = name; + if (!existing.sources.includes(source)) existing.sources.push(source); + candidates.set(identity, existing); + }; + const mappings = db + .prepare( + `SELECT workspace_identity, scope_id FROM project_scope_mappings + WHERE workspace_identity IS NOT NULL AND workspace_identity <> '' ORDER BY id`, + ) + .all() as Array<{ workspace_identity: string; scope_id: string }>; + for (const mapping of mappings) add(canonical(mapping.workspace_identity), mapping.scope_id); + for (const row of projectMoveMemoryEvidence(db, [...scopes.keys(), ...pendingSources.keys()])) { + const scopeId = pendingSources.get(row.scope_id) ?? row.scope_id; + const identity = projectMoveMemoryIdentity(row, repositories); + if (identity.source === "unmapped" && !row.project?.trim()) { + add(unassignedProjectIdentity(scopeId), scopeId, "Unassigned"); + continue; + } + add( + canonical(identity.value), + scopeId, + identity.displayProject, + identity.source === "unmapped", + ); + } + return [...candidates.values()].sort((a, b) => + a.projectIdentity.localeCompare(b.projectIdentity), + ); +} + +function projectMoveMemoryEvidence(db: Database, scopeIds: string[]): ProjectMemoryEvidence[] { + return db + .prepare( + `SELECT DISTINCT mi.scope_id, s.cwd, COALESCE(mi.project, s.project) AS project, + s.git_remote, s.metadata_json, mi.workspace_id + FROM memory_items mi LEFT JOIN sessions s ON mi.session_id = s.id + WHERE mi.scope_id IN (SELECT value FROM json_each(?)) + AND mi.active = 1 AND mi.deleted_at IS NULL`, + ) + .all(JSON.stringify(scopeIds)) as ProjectMemoryEvidence[]; +} + +function projectMoveMemoryIdentity( + row: ProjectMemoryEvidence, + repositories: ReadonlyMap, +) { + const cwd = row.cwd?.startsWith(SYNC_BOOTSTRAP_CWD_PREFIX) ? null : row.cwd; + return canonicalWorkspaceIdentity({ + cwd, + project: row.project, + gitRemote: row.git_remote, + repositoryIdentity: repositoryIdentityForWorkspace(repositories, { + cwd, + gitRemote: row.git_remote, + metadataJson: row.metadata_json, + }), + workspaceId: row.workspace_id === "shared:default" ? null : row.workspace_id, + }); +} + +export function cachedProjectMoveMembers(db: Database, source: ProjectMoveSource): string[] { + return db + .prepare( + `SELECT device_id FROM scope_memberships WHERE scope_id = ? AND status = 'active' + AND membership_epoch >= ? ORDER BY device_id`, + ) + .pluck() + .all(source.scope_id, source.membership_epoch) as string[]; +} + +export function projectMoveDevices( + db: Database, + ids: Iterable, + fallbackName?: (deviceId: string) => string | null | undefined, +): ProjectMoveDevice[] { + const rows = db + .prepare( + `SELECT + COALESCE(NULLIF(peer.name, ''), NULLIF(binding.display_name, '')) AS name, + wanted.value AS deviceId + FROM json_each(?) AS wanted + LEFT JOIN sync_peers AS peer ON peer.peer_device_id = wanted.value + LEFT JOIN identity_devices AS binding ON binding.device_id = wanted.value + ORDER BY wanted.value`, + ) + .all(JSON.stringify([...new Set(ids)])) as Array<{ deviceId: string; name: string | null }>; + return rows.map(({ deviceId, name }) => ({ + deviceId, + name: name || fallbackName?.(deviceId) || deviceId, + })); +} + +/** A withdrawal can explain a missing grant, but doesn't override another recipient edge. */ +function withdrawnProjectMoveDevices( + db: Database, + scopeId: string, + authorized: readonly string[], + teamIds: string[], +): Set { + const removed = new Set(teamIds.flatMap((id) => [...removedTeamMemberIdentityIds(db, id)])); + const binding = db.prepare( + `SELECT person.actor_id, person.status FROM identity_devices AS binding + JOIN actors AS person ON person.actor_id = binding.identity_id + WHERE binding.device_id = ? AND binding.status = 'active'`, + ); + return new Set( + authorized.filter((deviceId) => { + const person = binding.get(deviceId) as { actor_id: string; status: string } | undefined; + // The planned Team might not have a Project recipient row for scope admission to read yet. + if (person && (person.status === "deactivated" || removed.has(person.actor_id))) return true; + return teamMemberRemovalRefusesScope(db, { scopeId, deviceId }); + }), + ); +} + +function linkedProjectMoveTeams(db: Database, source: ProjectMoveSource, projectIdentity: string) { + const targeted = db + .prepare( + `SELECT DISTINCT team.team_id, team.display_name FROM policy_teams AS team + JOIN legacy_team_setup_drafts AS draft ON draft.completed_team_id = team.team_id + JOIN legacy_team_setup_draft_projects AS project ON project.attempt_id = draft.attempt_id + WHERE project.target_scope_id = ? AND draft.state = 'completed'`, + ) + .all(source.scope_id) as Array<{ team_id: string; display_name: string }>; + const coordinator = normalizedCoordinatorId(source.coordinator_id); + const location = (teamId: string) => { + const link = teamCoordinatorLinkState(db, teamId); + if (link.state !== "linked" || coordinator === null) return "unknown"; + return link.groupId === source.group_id && + normalizedCoordinatorId(link.coordinatorId) === coordinator + ? "source" + : "other"; + }; + const teamInAnotherGroup = [ + ...targeted.map(({ team_id }) => team_id), + ...activeProjectRecipientIds(db, projectIdentity, "team"), + ].some((id) => location(id) === "other"); + const matchesGroup = (team: { team_id: string }) => location(team.team_id) === "source"; + if (targeted.length > 0) + return { + teams: targeted.filter(matchesGroup), + conflict: !targeted.every(matchesGroup), + teamInAnotherGroup, + }; + if (source.kind !== "team" && source.kind !== "team_default") + return { teams: [], conflict: false, teamInAnotherGroup }; + const teams = db + .prepare("SELECT team_id, display_name FROM policy_teams ORDER BY team_id") + .all() as typeof targeted; + return { teams: teams.filter(matchesGroup), conflict: false, teamInAnotherGroup }; +} + +/** Derive the exact policy the reconciler will enforce, before writing any recipient. */ +export function planProjectMove( + db: Database, + projectIdentity: string, + source: ProjectMoveSource, + authorizedDeviceIds: readonly string[], + fallbackName?: (deviceId: string) => string | null | undefined, +): ProjectMovePlan { + const { teams, conflict, teamInAnotherGroup } = linkedProjectMoveTeams( + db, + source, + projectIdentity, + ); + const recipients: MoveRecipient[] = teams.map((team) => ({ + recipientKind: "team", + recipientId: team.team_id, + name: team.display_name, + })); + const teamDevices = deriveRecipientPolicyEffectiveDevicesFromDatabase(db, projectIdentity, { + proposedRecipients: recipients, + }); + const withdrawn = withdrawnProjectMoveDevices( + db, + source.scope_id, + authorizedDeviceIds, + teams.map(({ team_id }) => team_id), + ); + const covered = new Set(teamDevices.devices.map(({ deviceId }) => deviceId)); + const existing = new Set(activeProjectRecipientIds(db, projectIdentity, "identity")); + const { people, unlinked } = directProjectMoveRecipients(db, authorizedDeviceIds, { + covered, + withdrawn, + existing, + }); + recipients.push(...people); + const desired = people.length + ? deriveRecipientPolicyEffectiveDevicesFromDatabase(db, projectIdentity, { + proposedRecipients: recipients, + }) + : teamDevices; + const authorized = new Set(authorizedDeviceIds); + const desiredIds = desired.devices.map((device) => device.deviceId); + const planned = new Set(desiredIds); + const excluded = new Set([...withdrawn].filter((id) => !planned.has(id))); + const receivingDevices = projectMoveDevices(db, desiredIds, fallbackName); + return { + recipients, + receivingDevices, + newReceivers: receivingDevices.filter(({ deviceId }) => !authorized.has(deviceId)), + excludedDevices: projectMoveDevices(db, excluded, fallbackName), + unlinkedDevices: projectMoveDevices(db, unlinked, fallbackName), + teamInAnotherGroup, + needsAttention: + conflict || + teams.length > 1 || + desired.status !== "eligible" || + unexplainedMoveAccess(db, source.scope_id, authorizedDeviceIds, excluded, [ + ...desiredIds, + ...unlinked, + ]), + }; +} + +function directProjectMoveRecipients( + db: Database, + deviceIds: readonly string[], + { + covered, + withdrawn, + existing, + }: Record<"covered" | "withdrawn" | "existing", ReadonlySet>, +) { + const binding = db.prepare( + `SELECT person.actor_id, person.display_name FROM identity_devices AS device + JOIN actors AS person ON person.actor_id = device.identity_id AND person.status = 'active' + WHERE device.device_id = ? AND device.status = 'active'`, + ); + const people = new Map(); + const unlinked: string[] = []; + for (const deviceId of deviceIds) { + const person = binding.get(deviceId) as { actor_id: string; display_name: string } | undefined; + if (!person) { + if (!withdrawn.has(deviceId) && !covered.has(deviceId)) unlinked.push(deviceId); + continue; + } + if (!existing.has(person.actor_id) && (covered.has(deviceId) || withdrawn.has(deviceId))) + continue; + people.set(person.actor_id, { + recipientKind: "identity", + recipientId: person.actor_id, + name: person.display_name, + }); + } + return { people: [...people.values()], unlinked }; +} + +function unexplainedMoveAccess( + db: Database, + scopeId: string, + authorized: readonly string[], + excluded: ReadonlySet, + accountedFor: string[], +): boolean { + const known = new Set(accountedFor); + return authorized.some( + (deviceId) => + !excluded.has(deviceId) && + (!known.has(deviceId) || isScopeDeviceAdmissionRefused(db, { scopeId, deviceId })), + ); +} diff --git a/packages/core/src/recipient-policy-reconciler.ts b/packages/core/src/recipient-policy-reconciler.ts index 6a93e821d..9282b73a6 100644 --- a/packages/core/src/recipient-policy-reconciler.ts +++ b/packages/core/src/recipient-policy-reconciler.ts @@ -1,6 +1,7 @@ import { createHash } from "node:crypto"; import type { Database } from "./db.js"; import { isWithdrawnPolicyIdentity } from "./policy-team-device-eligibility.js"; +import { getProjectBoundaryMigrationHold } from "./project-boundary-migration-hold.js"; import { isStrictRecipientPolicyId } from "./recipient-policy-identifiers.js"; import { clearRecipientPolicyDenyOverlay, @@ -1706,6 +1707,17 @@ async function prepareInitialReconciliation( canonicalProjectIdentity: run.projectId, }); const managedBoundary = boundary(run.db, run.projectId); + if (getProjectBoundaryMigrationHold(run.db, managedBoundary.scopeId)?.held) { + return { + kind: "complete", + result: result( + run.projectId, + "waiting", + run.activeGeneration, + "project_move_recipients_pending", + ), + }; + } const desired = deriveRecipientPolicyEffectiveDevicesFromDatabase(run.db, run.projectId); if (desired.status !== "eligible") { return { diff --git a/packages/core/src/recipient-policy-reconciliation.ts b/packages/core/src/recipient-policy-reconciliation.ts index 7c9a0d485..cf1e29225 100644 --- a/packages/core/src/recipient-policy-reconciliation.ts +++ b/packages/core/src/recipient-policy-reconciliation.ts @@ -595,16 +595,53 @@ function canonicalProjectRecipientRows( })); } +export function activeProjectRecipientIds( + db: Database, + projectIdentity: string, + kind: "team" | "identity", +): string[] { + return canonicalProjectRecipientRows(db, projectIdentity) + .filter((row) => row.recipient_kind === kind && row.status === "active") + .map((row) => row.recipient_id); +} + export function deriveRecipientPolicyEffectiveDevicesFromDatabase( db: Database, canonicalProjectIdentity: string, + options: { + proposedRecipients?: ReadonlyArray<{ recipientKind: string; recipientId: string }>; + } = {}, ): StrictRecipientPolicyEffectiveDeviceDerivation { const repositoryIdentities = repositoryIdentitiesByWorkspace(db); const canonicalIdentity = canonicalRepositoryProjectIdentity( repositoryIdentities, canonicalProjectIdentity, ); - const projectRecipients = canonicalProjectRecipientRows(db, canonicalIdentity); + const projectRecipients = + options.proposedRecipients?.map((recipient) => ({ + ...recipient, + canonicalProjectIdentity: canonicalIdentity, + status: "active", + })) ?? + canonicalProjectRecipientRows(db, canonicalIdentity).map((row) => ({ + canonicalProjectIdentity: row.canonical_project_identity, + recipientKind: row.recipient_kind, + recipientId: row.recipient_id, + status: row.status, + })); + return deriveRecipientPolicyEffectiveDevices({ + canonicalProjectIdentity: canonicalIdentity, + projectRecipients, + ...readRecipientPolicyBindings(db), + }); +} + +function readRecipientPolicyBindings( + db: Database, +): Omit< + DeriveRecipientPolicyEffectiveDevicesInput, + "canonicalProjectIdentity" | "projectRecipients" +> { const identities = db .prepare("SELECT actor_id, status, merged_into_actor_id FROM actors ORDER BY actor_id") .all() as Array<{ actor_id: string; status: string; merged_into_actor_id: string | null }>; @@ -625,14 +662,7 @@ export function deriveRecipientPolicyEffectiveDevicesFromDatabase( assignment_version: number; }>; const teamDeviceDecisions = readEffectiveTeamDeviceDecisions(db); - return deriveRecipientPolicyEffectiveDevices({ - canonicalProjectIdentity: canonicalIdentity, - projectRecipients: projectRecipients.map((row) => ({ - canonicalProjectIdentity: row.canonical_project_identity, - recipientKind: row.recipient_kind, - recipientId: row.recipient_id, - status: row.status, - })), + return { identities: identities.map((row) => ({ identityId: row.actor_id, status: row.status, @@ -660,7 +690,7 @@ export function deriveRecipientPolicyEffectiveDevicesFromDatabase( status: row.status, assignmentVersion: row.assignment_version, })), - }); + }; } function authorityRow(row: Record): RecipientPolicyAuthorityStateRecord { diff --git a/packages/ui/src/lib/api/sync.ts b/packages/ui/src/lib/api/sync.ts index 3aa605a4f..ea13f6a14 100644 --- a/packages/ui/src/lib/api/sync.ts +++ b/packages/ui/src/lib/api/sync.ts @@ -3,6 +3,7 @@ * the manual sync-now trigger. Every request in this file hits * /api/sync/* or /api/sync/run/* on the viewer. */ +import type { ProjectMoveIssue } from "@codemem/core"; import { RECIPIENT_POLICY_TEAM_CREATE_ERROR_CODES, RECIPIENT_POLICY_TEAM_RENAME_ERROR_CODES, @@ -635,6 +636,7 @@ export interface ShareOperationList { export interface ProjectScopeInventoryResult { projects: ProjectScopeInventoryProject[]; + migration_issues?: ProjectMoveIssue[]; total: number; limit: number; offset: number; diff --git a/packages/ui/src/tabs/projects-controller.ts b/packages/ui/src/tabs/projects-controller.ts index 4c30dc632..a5db2a0c3 100644 --- a/packages/ui/src/tabs/projects-controller.ts +++ b/packages/ui/src/tabs/projects-controller.ts @@ -3,6 +3,7 @@ import type { LegacyTeamSetupSummaryResponseV1, ProjectScopeGuardrailWarning, ProjectScopeInventoryProject, + ProjectScopeInventoryResult, RecipientPolicyBlockedItemV1, RecipientPolicyIntentGraphV1, RecipientPolicyReviewListV1, @@ -117,6 +118,7 @@ let latestInventoryResult: { total: number; offset: number; has_more: boolean; + migration_issues?: ProjectScopeInventoryResult["migration_issues"]; } = { projects: [], total: 0, offset: 0, has_more: false }; const projectInventoryListeners = new Set<(viewModel: ProjectsInventoryViewModel) => void>(); @@ -948,6 +950,7 @@ function projectsInventoryViewModel(): ProjectsInventoryViewModel { const selectedIds = [...selectedProjectIds].sort(); return { rows: projectClusters(latestInventoryResult.projects).map(inventoryRowViewModel), + migrationIssues: latestInventoryResult.migration_issues, recipientPolicyReady: recipientPolicyIntentDisplayReady, shareInventoryReady: projectShareInventoryReady, scopeLabels: Object.fromEntries( @@ -1046,6 +1049,7 @@ function renderProjectInventory(result: { has_more: boolean; hidden_empty_count?: number; hidden_unnamed_count?: number; + migration_issues?: ProjectScopeInventoryResult["migration_issues"]; }) { hasProjectInventoryResult = true; latestInventoryResult = { @@ -1053,6 +1057,7 @@ function renderProjectInventory(result: { total: result.total, offset: result.offset, has_more: result.has_more, + migration_issues: result.migration_issues, }; const meta = el("projectsInventoryMeta"); const list = el("projectsInventoryList"); @@ -1078,6 +1083,7 @@ function refreshProjectCoordinatorGroupNamesInBackground( projects: ProjectScopeInventoryProject[]; total: number; offset: number; + migration_issues?: ProjectScopeInventoryResult["migration_issues"]; has_more: boolean; }, loadGeneration: number, diff --git a/packages/ui/src/tabs/projects-inventory-model.ts b/packages/ui/src/tabs/projects-inventory-model.ts index 9ea337a4c..82bb2d571 100644 --- a/packages/ui/src/tabs/projects-inventory-model.ts +++ b/packages/ui/src/tabs/projects-inventory-model.ts @@ -1,6 +1,7 @@ import type { ProjectScopeGuardrailWarning, ProjectScopeInventoryProject, + ProjectScopeInventoryResult, SharingDomainScope, } from "../lib/api/sync"; @@ -59,6 +60,7 @@ export type ClusterMappingCheckState = "accepted" | "checking" | "failed" | "rev export interface ProjectsInventoryViewModel { rows: Array; + migrationIssues?: ProjectScopeInventoryResult["migration_issues"]; recipientPolicyReady: boolean; shareInventoryReady: boolean; scopeLabels: Record; diff --git a/packages/ui/src/tabs/projects.test.ts b/packages/ui/src/tabs/projects.test.ts index e630f6f6f..c1af85c0d 100644 --- a/packages/ui/src/tabs/projects.test.ts +++ b/packages/ui/src/tabs/projects.test.ts @@ -443,6 +443,60 @@ describe("Projects tab", () => { expect(document.getElementById("projectsInventorySkeleton")).toBeNull(); }); + it("shows which Projects need a device update, a linked person, or attention", async () => { + vi.mocked(api.loadProjectScopeInventory).mockResolvedValue({ + ...inventoryPage(), + migration_issues: [ + { + projectIdentity: "repo:docs", + projectName: "Docs", + reason: "devices_not_updated", + devices: [{ deviceId: "a", name: "Office Mac" }], + }, + { + projectIdentity: "repo:site", + projectName: "Site", + reason: "unlinked_devices", + devices: [{ deviceId: "b", name: "Laptop" }], + }, + { + projectIdentity: "repo:web", + projectName: "Web", + reason: "multiple_sources", + devices: [], + }, + { + projectIdentity: "repo:notes", + projectName: "Notes", + reason: "device_keys_missing", + devices: [{ deviceId: "c", name: "Studio Mac" }], + }, + { + projectIdentity: "repo:archive", + projectName: "Archive", + reason: "team_in_another_group", + devices: [], + }, + ], + }); + initProjectsTab(() => {}); + await loadProjectsData(); + + const text = document.querySelector('[aria-label="Project sharing migration"]')?.textContent; + expect(text).toContain("Docs: Waiting for Codemem updates on Office Mac."); + expect(text).toContain( + "Site: Waiting for Laptop. Link each device to a person in Devices, or remove it.", + ); + expect(text).toContain( + "Web: Needs attention. This Project belongs to more than one older sharing setup.", + ); + expect(text).toContain("Notes: Waiting for device setup on Studio Mac."); + expect(text).toContain( + "Archive: Needs attention. This Project and its Team use different sharing setups, so the Project can’t move automatically. Sharing stays unchanged.", + ); + expect(text).not.toMatch(/\b(space|scope)\b/i); + }); + it("keeps Advanced recovery snapshots untouched when Project Team-name refresh fails", async () => { state.lastCoordinatorAdminStatus = { active_group: "retained-group", diff --git a/packages/ui/src/tabs/projects/ProjectInventory.tsx b/packages/ui/src/tabs/projects/ProjectInventory.tsx index 1bc19e4d9..fed0848e7 100644 --- a/packages/ui/src/tabs/projects/ProjectInventory.tsx +++ b/packages/ui/src/tabs/projects/ProjectInventory.tsx @@ -4,6 +4,7 @@ import type { ProjectsInventoryViewModel, } from "../projects-inventory-model"; import { ProjectClusterRow } from "./ProjectClusterRow"; +import { ProjectMigrationNotices } from "./ProjectMigrationNotices"; import { ProjectRow } from "./ProjectRow"; interface ProjectInventoryProps { @@ -19,6 +20,18 @@ export function ProjectInventory({ callbacks, error, view }: ProjectInventoryPro {error} ); + return ( + <> + + + + ); +} + +function ProjectInventoryTable({ + callbacks, + view, +}: Pick) { if (view.rows.length === 0) return
No matching projects
; return ( diff --git a/packages/ui/src/tabs/projects/ProjectMigrationNotices.tsx b/packages/ui/src/tabs/projects/ProjectMigrationNotices.tsx new file mode 100644 index 000000000..0028b8f6d --- /dev/null +++ b/packages/ui/src/tabs/projects/ProjectMigrationNotices.tsx @@ -0,0 +1,34 @@ +import type { ProjectMoveIssue } from "@codemem/core"; + +function notice(issue: ProjectMoveIssue): string { + const names = issue.devices.map(({ name }) => name).join(", "); + switch (issue.reason) { + case "devices_not_updated": + return `Waiting for Codemem updates on ${names}.`; + case "device_keys_missing": + return `Waiting for device setup on ${names}.`; + case "unlinked_devices": + return `Waiting for ${names}. Link each device to a person in Devices, or remove it.`; + case "multiple_sources": + return "Needs attention. This Project belongs to more than one older sharing setup. Sharing stays unchanged."; + case "team_in_another_group": + return "Needs attention. This Project and its Team use different sharing setups, so the Project can’t move automatically. Sharing stays unchanged."; + case "access_needs_attention": + return "Needs attention. Current access could not be verified."; + } +} + +export function ProjectMigrationNotices({ issues }: { issues?: readonly ProjectMoveIssue[] }) { + if (!issues?.length) return null; + return ( +
+
    + {issues.map((issue) => ( +
  • + {issue.projectName}: {notice(issue)} +
  • + ))} +
+
+ ); +} diff --git a/packages/viewer-server/src/routes/sync.ts b/packages/viewer-server/src/routes/sync.ts index f200f0719..5617786df 100644 --- a/packages/viewer-server/src/routes/sync.ts +++ b/packages/viewer-server/src/routes/sync.ts @@ -138,6 +138,7 @@ import { listInboundScopeRejections, listLegacyRecipientPolicyProjections, listPerPeerScopeSyncState, + listProjectMoveIssues, listProjectScopeCandidates, listProjectScopeInventory, listProjectScopeSettingsMappings, @@ -7155,7 +7156,11 @@ async function projectScopeInventoryRoute(c: Context, store: MemoryStore) { operations, repositoryIdentitySnapshot, ); - return c.json(serializeProjectScopeInventory(store, inventory, sharingByProject)); + const migrationIssues = listProjectMoveIssues(store.db); + return c.json({ + ...serializeProjectScopeInventory(store, inventory, sharingByProject), + ...(migrationIssues.length > 0 ? { migration_issues: migrationIssues } : {}), + }); } /** From b65193278e18a0a89f05a156b5c0a7d14970e5ed Mon Sep 17 00:00:00 2001 From: Adam Kunicki Date: Sat, 28 Nov 2026 19:59:17 -0800 Subject: [PATCH 2/4] fix(sync): persist devices waiting for Project moves --- docs/coordinator-discovery.md | 2 + .../cli/src/commands/sync-migration.test.ts | 80 ++++++++++++++++++- packages/cli/src/commands/sync-migration.ts | 6 ++ packages/core/src/project-migration-report.ts | 8 +- packages/core/src/project-move-admin.ts | 15 +++- packages/core/src/project-move-waits.ts | 74 +++++++++++++++++ .../src/transitioned-store-inventory.test.ts | 1 + .../tabs/projects/ProjectMigrationNotices.tsx | 2 +- 8 files changed, 178 insertions(+), 10 deletions(-) create mode 100644 packages/core/src/project-move-waits.ts diff --git a/docs/coordinator-discovery.md b/docs/coordinator-discovery.md index c795c7076..53bfe94b5 100644 --- a/docs/coordinator-discovery.md +++ b/docs/coordinator-discovery.md @@ -83,6 +83,8 @@ moves so it can reconcile received copies, but it does not remap Projects or restamp memories it authored. The `codemem sync migration status` command works at either setting and lists the planned recipients and devices that would start or stop receiving each Project. +The report and Projects show which devices need an update or still need setup. +The last answer from the coordinator survives a restart. Use `--json` for counts or `--db-path` and `--config` to inspect a particular install. The report sends no requests and does not change sharing. It uses the membership diff --git a/packages/cli/src/commands/sync-migration.test.ts b/packages/cli/src/commands/sync-migration.test.ts index 861317bcd..29946f252 100644 --- a/packages/cli/src/commands/sync-migration.test.ts +++ b/packages/cli/src/commands/sync-migration.test.ts @@ -1,7 +1,13 @@ import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { connect } from "@codemem/core"; +import { + connect, + connectReadOnly, + listProjectMoveIssues, + readCoordinatorSyncConfig, + runProjectMoves, +} from "@codemem/core"; import { afterEach, beforeEach, expect, it, vi } from "vitest"; import { buildSyncMigrationCommand } from "./sync-migration.js"; @@ -90,9 +96,9 @@ it("reports the local backup path and byte size even when migration is off", asy ["status", "--db-path", dbPath, "--config", configPath], { from: "user" }, ); - expect(output.mock.calls.map(([chunk]) => String(chunk)).join("")).toContain( - `${backup} (7 bytes)`, - ); + const text = output.mock.calls.map(([chunk]) => String(chunk)).join(""); + expect(text).toContain(`${backup} (7 bytes)`); + expect(text).toContain("Project migration is off on this device. No move request was sent."); }); it("tells the person in text what the storage fence does not erase and how to recover", async () => { @@ -150,3 +156,69 @@ it("prints one line each for the devices that would start and stop receiving a P ]); expect(fetch).not.toHaveBeenCalled(); }); + +it("reports the latest waiting device after reopening the store and drops it after the move", async () => { + vi.stubEnv("CODEMEM_SYNC_BOUNDARY_MIGRATION", "on"); + const raw = { + sync_coordinator_url: "https://coordinator.example", + sync_coordinator_group: "test", + sync_coordinator_admin_secret: "test-admin", + }; + writeFileSync(configPath, JSON.stringify(raw)); + const db = connect(dbPath); + try { + db.exec(`INSERT INTO replication_scopes(scope_id,label,kind,authority_type,coordinator_id,group_id,created_at,updated_at) + VALUES ('old','Older setup','team','coordinator','https://coordinator.example','test','now','now'); + INSERT INTO project_scope_mappings(workspace_identity,project_pattern,scope_id,created_at,updated_at) + VALUES ('repo:journal','repo:journal','old','now','now'); + INSERT INTO actors(actor_id,display_name,status,created_at,updated_at) VALUES ('pat','Pat','active','now','now'); + INSERT INTO identity_devices(device_id,identity_id,display_name,status,provenance,revision,migration_state,idempotency_key,created_at,updated_at) + VALUES ('desktop','pat','Desktop','active','test','1','native','desktop','now','now'), + ('laptop','pat','Office Laptop','active','test','1','native','laptop','now','now');`); + const config = readCoordinatorSyncConfig(raw); + const access = { + authorized: ["desktop", "laptop"], + enrollments: new Map( + ["desktop", "laptop"].map((id) => [id, { enabled: true, identityId: "pat" }]), + ), + }; + const pass = (move: NonNullable[3]>["move"]) => + runProjectMoves(db, config, "desktop", { + readAccess: async () => access, + readTeamRemovals: async () => [], + move, + }); + await pass(async () => ({ kind: "devices_not_updated", deviceIds: ["desktop"] })); + await pass(async () => ({ kind: "device_keys_missing", deviceIds: ["laptop"] })); + + const reopened = connectReadOnly(dbPath); + try { + expect(listProjectMoveIssues(reopened)).toMatchObject([ + { reason: "device_keys_missing", devices: [{ deviceId: "laptop", name: "Office Laptop" }] }, + ]); + } finally { + reopened.close(); + } + const output = vi.spyOn(process.stdout, "write").mockReturnValue(true); + const textReport = async () => { + output.mockClear(); + await buildSyncMigrationCommand().parseAsync( + ["status", "--db-path", dbPath, "--config", configPath], + { from: "user" }, + ); + return output.mock.calls.map(([chunk]) => String(chunk)).join(""); + }; + expect(await textReport()).toContain("Waiting for device setup on Office Laptop."); + await pass(async () => ({ + kind: "moved", + deviceIds: access.authorized, + excludedDeviceIds: [], + createdAt: "2026-11-28T00:00:00Z", + })); + expect(await textReport()).not.toContain("Office Laptop"); + expect(db.prepare("SELECT COUNT(*) FROM project_move_waits").pluck().get()).toBe(0); + expect(fetch).not.toHaveBeenCalled(); + } finally { + db.close(); + } +}); diff --git a/packages/cli/src/commands/sync-migration.ts b/packages/cli/src/commands/sync-migration.ts index 4687e6109..ef73959f4 100644 --- a/packages/cli/src/commands/sync-migration.ts +++ b/packages/cli/src/commands/sync-migration.ts @@ -104,6 +104,12 @@ function migrationStatus(opts: DbOpts & ConfigOpts & JsonOpts) { p.log.info( [ reportText(report), + report.mode === "off" && + "Project migration is off on this device. No move request was sent.", + ...(report.waiting_for_devices ?? []).map(({ projectName, reason, devices }) => { + const action = reason === "devices_not_updated" ? "Codemem updates" : "device setup"; + return `${projectName}: Waiting for ${action} on ${devices.map(({ name }) => name).join(", ")}.`; + }), report.backup && `Project migration backup: ${report.backup.path} (${report.backup.size_bytes} bytes).`, ] diff --git a/packages/core/src/project-migration-report.ts b/packages/core/src/project-migration-report.ts index b74851816..3b0a1b6cb 100644 --- a/packages/core/src/project-migration-report.ts +++ b/packages/core/src/project-migration-report.ts @@ -11,6 +11,7 @@ import { olderProjectScopes, planProjectMove, } from "./project-move-plan.js"; +import { listProjectMoveWaitIssues } from "./project-move-waits.js"; import { columnExists } from "./schema-lookups.js"; import { SYNC_BOOTSTRAP_CWD_PREFIX } from "./sync-bootstrap-constants.js"; @@ -73,7 +74,12 @@ function inventory( export function readLocalProjectMigrationReport(db: Database, config: Record) { const report = migrationReport(db, config); const backup = projectMoveBackupInfo(db); - return { ...report, ...(backup ? { backup } : {}) }; + const waiting = listProjectMoveWaitIssues(db); + return { + ...report, + ...(backup ? { backup } : {}), + ...(waiting.length ? { waiting_for_devices: waiting } : {}), + }; } function migrationReport(db: Database, config: Record) { diff --git a/packages/core/src/project-move-admin.ts b/packages/core/src/project-move-admin.ts index 6ed1761bf..534d631bb 100644 --- a/packages/core/src/project-move-admin.ts +++ b/packages/core/src/project-move-admin.ts @@ -24,8 +24,12 @@ import { type ProjectMovePlan, type ProjectMoveSource, planProjectMove, - projectMoveDevices, } from "./project-move-plan.js"; +import { + clearCompletedProjectMoveWaits, + listProjectMoveWaitIssues, + recordProjectMoveWait, +} from "./project-move-waits.js"; import { deriveRecipientPolicyEffectiveDevicesFromDatabase } from "./recipient-policy-reconciliation.js"; import { buildBaseUrl, normalizedCoordinatorId, requestJson } from "./sync-http-client.js"; import { applyTeamMemberRemovals } from "./team-member-removal-policy.js"; @@ -54,7 +58,7 @@ function issue( } export function listProjectMoveIssues(db: Database): ProjectMoveIssue[] { - return lastIssues.get(db) ?? []; + return [...(lastIssues.get(db) ?? []), ...listProjectMoveWaitIssues(db)]; } interface SourceAccess { @@ -372,8 +376,10 @@ async function moveCandidate( const fallbackName = (id: string) => access.enrollments.get(id)?.name; if (result.kind === "unavailable") return null; if (result.kind !== "moved") { - if ("deviceIds" in result) - return issue(project, result.kind, projectMoveDevices(db, result.deviceIds, fallbackName)); + if ("deviceIds" in result) { + recordProjectMoveWait(db, source.scope_id, result.kind, result.deviceIds); + return null; + } return issue(project, "access_needs_attention"); } @@ -468,6 +474,7 @@ export async function runProjectMoves( if (problem) results.push(problem); } lastIssues.set(db, results); + if (canMove) clearCompletedProjectMoveWaits(db); } function createSourceMover(db: Database, deviceId: string, effects: ProjectMoveAdminEffects) { diff --git a/packages/core/src/project-move-waits.ts b/packages/core/src/project-move-waits.ts new file mode 100644 index 000000000..b26750ff6 --- /dev/null +++ b/packages/core/src/project-move-waits.ts @@ -0,0 +1,74 @@ +import { type Database, tableExists } from "./db.js"; +import { listProjectMoveCandidates, projectMoveDevices } from "./project-move-plan.js"; + +type WaitReason = "devices_not_updated" | "device_keys_missing"; +const TABLE = "project_move_waits"; + +export function recordProjectMoveWait( + db: Database, + sourceScopeId: string, + reason: WaitReason, + deviceIds: string[], +): void { + db.exec(`CREATE TABLE IF NOT EXISTS project_move_waits ( + source_scope_id TEXT PRIMARY KEY NOT NULL, + reason TEXT NOT NULL, + device_ids_json TEXT NOT NULL, + observed_at TEXT NOT NULL + )`); + db.prepare( + `INSERT INTO project_move_waits(source_scope_id, reason, device_ids_json, observed_at) VALUES (?, ?, ?, ?) + ON CONFLICT(source_scope_id) DO UPDATE SET reason = excluded.reason, + device_ids_json = excluded.device_ids_json, observed_at = excluded.observed_at`, + ).run(sourceScopeId, reason, JSON.stringify(deviceIds), new Date().toISOString()); +} + +function waitRows(db: Database) { + if (!tableExists(db, TABLE)) return []; + return db + .prepare( + `SELECT source_scope_id, reason, device_ids_json, observed_at FROM project_move_waits + WHERE reason IN ('devices_not_updated', 'device_keys_missing') AND json_valid(device_ids_json) + ORDER BY source_scope_id`, + ) + .all() as Array<{ + source_scope_id: string; + reason: WaitReason; + device_ids_json: string; + observed_at: string; + }>; +} + +export function listProjectMoveWaitIssues(db: Database) { + const rows = waitRows(db); + if (!rows.length) return []; + const waits = new Map(rows.map((row) => [row.source_scope_id, row])); + return listProjectMoveCandidates(db).flatMap(({ projectIdentity, projectName, sources }) => { + const [source] = sources; + const row = source && sources.length === 1 ? waits.get(source.scope_id) : undefined; + if (!row) return []; + const deviceIds: unknown = JSON.parse(row.device_ids_json); + if (!Array.isArray(deviceIds) || !deviceIds.every((id) => typeof id === "string")) return []; + return [ + { + projectIdentity, + projectName, + reason: row.reason, + devices: projectMoveDevices(db, deviceIds), + observedAt: row.observed_at, + }, + ]; + }); +} + +export function clearCompletedProjectMoveWaits(db: Database): void { + const rows = waitRows(db); + if (!rows.length) return; + const pending = new Set( + listProjectMoveCandidates(db).flatMap(({ sources }) => sources.map(({ scope_id }) => scope_id)), + ); + const clear = db.prepare("DELETE FROM project_move_waits WHERE source_scope_id = ?"); + for (const row of rows) { + if (!pending.has(row.source_scope_id)) clear.run(row.source_scope_id); + } +} diff --git a/packages/core/src/transitioned-store-inventory.test.ts b/packages/core/src/transitioned-store-inventory.test.ts index 1ce899688..3ea2c34fc 100644 --- a/packages/core/src/transitioned-store-inventory.test.ts +++ b/packages/core/src/transitioned-store-inventory.test.ts @@ -64,6 +64,7 @@ const reviewedMetadata: Record = { policy_team_recovery_skipped_projects: "Project identities a recovery skipped.", policy_teams: "Team names and state.", project_boundary_migrations: "Per-Project migration state.", + project_move_waits: "Devices an older sharing setup is waiting for.", project_recipients: "Project recipients.", project_scope_mappings: "Workspace patterns to scope IDs.", project_scope_withdrawals: "Withdrawn Project scopes.", diff --git a/packages/ui/src/tabs/projects/ProjectMigrationNotices.tsx b/packages/ui/src/tabs/projects/ProjectMigrationNotices.tsx index 0028b8f6d..49042c6df 100644 --- a/packages/ui/src/tabs/projects/ProjectMigrationNotices.tsx +++ b/packages/ui/src/tabs/projects/ProjectMigrationNotices.tsx @@ -24,7 +24,7 @@ export function ProjectMigrationNotices({ issues }: { issues?: readonly ProjectM
    {issues.map((issue) => ( -
  • +
  • {issue.projectName}: {notice(issue)}
  • ))} From 1ae0cca32c6fbf90070b1761fd356d54a52820c4 Mon Sep 17 00:00:00 2001 From: Adam Kunicki Date: Sun, 29 Nov 2026 08:03:43 -0800 Subject: [PATCH 3/4] fix(sync): preserve Team exclusions and progress past held moves --- packages/core/src/project-move-admin.test.ts | 38 ++++++++++ packages/core/src/project-move-plan.ts | 10 +++ .../core/src/recipient-policy-reconciler.ts | 5 +- .../coordinator-maintenance.test.ts | 75 +++++++++++++++++++ 4 files changed, 127 insertions(+), 1 deletion(-) diff --git a/packages/core/src/project-move-admin.test.ts b/packages/core/src/project-move-admin.test.ts index 512f1f1fd..cb586c977 100644 --- a/packages/core/src/project-move-admin.test.ts +++ b/packages/core/src/project-move-admin.test.ts @@ -208,6 +208,44 @@ function report() { return result.project_moves; } +it.each([false, true])( + "preserves a Team device exclusion unless the Project is shared directly (%s)", + async (direct) => { + const [project] = PROJECTS; + const extra = "a-laptop"; + const authorized = [...TEAM_DEVICES, extra]; + mapProject(project); + bind(extra, "person-a"); + member(extra); + db.prepare(`INSERT INTO policy_team_device_decisions( + team_id, device_id, decision, assignment_version, provenance, revision, created_at, updated_at + ) VALUES ('team', ?, 'excluded', 0, 'test', '1', ?, ?)`).run(extra, NOW, NOW); + if (direct) + db.prepare(`INSERT INTO project_recipients(canonical_project_identity, recipient_kind, recipient_id, status, + provenance, policy_revision, migration_state, idempotency_key, created_at, updated_at) + VALUES (?,'identity','person-a','active','user','1','native','direct',?,?)`).run( + project, + NOW, + NOW, + ); + + const remote = coordinator(authorized); + expect(report()?.[0]?.plan?.excludedDevices.map(({ deviceId }) => deviceId)).toEqual( + direct ? [] : [extra], + ); + await runProjectMoves(db, config, ADMIN, remote.effects); + expect(remote.move).toHaveBeenCalledWith( + expect.objectContaining({ + excludedDeviceIds: direct ? [] : [extra], + }), + ); + expect(recipients().filter((row) => (row as { kind: string }).kind === "identity")).toEqual( + direct ? [{ project, kind: "identity", recipient: "person-a" }] : [], + ); + await expectReconciled(project, remote, direct ? authorized : TEAM_DEVICES); + }, +); + it("moves three Projects to their own boundaries without changing the Team's devices", async () => { for (const project of PROJECTS) mapProject(project); const remote = coordinator(); diff --git a/packages/core/src/project-move-plan.ts b/packages/core/src/project-move-plan.ts index 39de04d3a..78c2bf046 100644 --- a/packages/core/src/project-move-plan.ts +++ b/packages/core/src/project-move-plan.ts @@ -21,6 +21,7 @@ import { removedTeamMemberIdentityIds, teamCoordinatorLinkState, } from "./team-member-removal-lookup.js"; +import { readEffectiveTeamDeviceDecisions } from "./team-recovery-exclusions.js"; import { canonicalWorkspaceIdentity } from "./workspace-identity.js"; export interface ProjectMoveSource { @@ -219,8 +220,16 @@ function withdrawnProjectMoveDevices( scopeId: string, authorized: readonly string[], teamIds: string[], + exclusionTeamIds = teamIds, ): Set { const removed = new Set(teamIds.flatMap((id) => [...removedTeamMemberIdentityIds(db, id)])); + const excluded = new Set( + readEffectiveTeamDeviceDecisions(db) + .filter( + ({ team_id, decision }) => decision === "excluded" && exclusionTeamIds.includes(team_id), + ) + .map(({ device_id }) => device_id), + ); const binding = db.prepare( `SELECT person.actor_id, person.status FROM identity_devices AS binding JOIN actors AS person ON person.actor_id = binding.identity_id @@ -228,6 +237,7 @@ function withdrawnProjectMoveDevices( ); return new Set( authorized.filter((deviceId) => { + if (excluded.has(deviceId)) return true; const person = binding.get(deviceId) as { actor_id: string; status: string } | undefined; // The planned Team might not have a Project recipient row for scope admission to read yet. if (person && (person.status === "deactivated" || removed.has(person.actor_id))) return true; diff --git a/packages/core/src/recipient-policy-reconciler.ts b/packages/core/src/recipient-policy-reconciler.ts index 9282b73a6..7236de240 100644 --- a/packages/core/src/recipient-policy-reconciler.ts +++ b/packages/core/src/recipient-policy-reconciler.ts @@ -125,7 +125,9 @@ interface Lease { const DEFAULT_LEASE_DURATION_MS = 60_000; const DELIVERED_COPY_WARNING = true as const; const CONTROL_CHARACTER = /\p{Cc}/u; +const PROJECT_MOVE_RECIPIENTS_PENDING = "project_move_recipients_pending"; const RETRYABLE_ACTIVE_AUTHORITY_ERRORS = new Set([ + PROJECT_MOVE_RECIPIENTS_PENDING, "recipient_policy_capability_undetermined", "recipient_policy_parity_incomplete", "recipient_policy_snapshot_not_fresh", @@ -1708,13 +1710,14 @@ async function prepareInitialReconciliation( }); const managedBoundary = boundary(run.db, run.projectId); if (getProjectBoundaryMigrationHold(run.db, managedBoundary.scopeId)?.held) { + authority(run, { safeErrorCode: PROJECT_MOVE_RECIPIENTS_PENDING, now: startedAt }); return { kind: "complete", result: result( run.projectId, "waiting", run.activeGeneration, - "project_move_recipients_pending", + PROJECT_MOVE_RECIPIENTS_PENDING, ), }; } diff --git a/packages/viewer-server/src/application/coordinator-maintenance.test.ts b/packages/viewer-server/src/application/coordinator-maintenance.test.ts index 95721c383..ae6b24952 100644 --- a/packages/viewer-server/src/application/coordinator-maintenance.test.ts +++ b/packages/viewer-server/src/application/coordinator-maintenance.test.ts @@ -1,6 +1,7 @@ import { initTestSchema, type RecipientPolicyReconcilerEffects } from "@codemem/core"; import Database from "better-sqlite3"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { recordProjectBoundaryMigration } from "../../../core/src/project-boundary-migration-records.js"; import type { MemoryStore } from "../store.js"; import { advancePendingProjectSharesOperation, @@ -41,6 +42,80 @@ describe("recipient-policy maintenance pacing", () => { afterEach(() => db.close()); + it("reaches unrelated Project work within two passes when held moves exceed the limit", async () => { + const insertScope = db.prepare(`INSERT INTO replication_scopes + (scope_id,label,kind,authority_type,coordinator_id,group_id,status,created_at,updated_at) + VALUES (?, ?, 'managed_project','coordinator','coordinator-a','group-a','active',?,?)`); + const map = db.prepare(`INSERT INTO project_scope_mappings + (workspace_identity,project_pattern,scope_id,created_at,updated_at) VALUES (?,?,?,?,?)`); + const insertAuthority = db.prepare(`INSERT INTO recipient_policy_authority_states + (canonical_project_identity,authority_state,generation,state_changed_at,created_at,updated_at) + VALUES (?, 'eligible', 1, ?, ?, ?)`); + for (const project of ["git:a", "git:b", "git:c", "git:unrelated"]) { + const scopeId = `managed-project:${project}`; + map.run(project, project, scopeId, NOW, NOW); + insertScope.run(scopeId, scopeId, NOW, NOW); + if (project !== "git:unrelated") { + insertAuthority.run(project, NOW, NOW, NOW); + recordProjectBoundaryMigration(db, { + sourceScopeId: "older", + boundaryScopeId: scopeId, + state: "committed", + generation: 1, + }); + } + } + db.prepare(`INSERT INTO project_recipients( + canonical_project_identity, recipient_kind, recipient_id, status, provenance, + policy_revision, migration_state, idempotency_key, created_at, updated_at) + VALUES ('git:unrelated','identity','person-unrelated','revoked','test','1','native','unrelated',?,?)`).run( + NOW, + NOW, + ); + const effects = unusedEffects(); + const maintain = () => + reconcileRecipientPolicyProjectsOperation(store, { + now: new Date(NOW), + limit: 2, + effects: { + ...effects, + snapshot: async ({ scopeId }) => ({ + authoritative: true, + scopeId, + memberships: [], + observedAt: NOW, + fingerprint: "empty", + }), + listBoundaryEnrollments: async () => [], + }, + }); + + const first = await maintain(); + expect(first.items).toEqual( + ["git:a", "git:b"].map((canonicalProjectIdentity) => ({ + canonicalProjectIdentity, + status: "waiting", + safeErrorCode: "project_move_recipients_pending", + })), + ); + expect( + db + .prepare(`SELECT attempt_count, last_attempt_at, safe_error_code + FROM recipient_policy_authority_states WHERE canonical_project_identity = 'git:a'`) + .get(), + ).toEqual({ + attempt_count: 1, + last_attempt_at: NOW, + safe_error_code: "project_move_recipients_pending", + }); + const second = await maintain(); + expect(second.items).toContainEqual({ + canonicalProjectIdentity: "git:unrelated", + status: "parity_pending", + safeErrorCode: null, + }); + }); + it("paces active policy checks to preserve coordinator read capacity", async () => { db.prepare( `INSERT INTO recipient_policy_authority_states( From a72bab73fdb65d18f98d98aa3fcd501936aadc13 Mon Sep 17 00:00:00 2001 From: Adam Kunicki Date: Sun, 29 Nov 2026 08:34:41 -0800 Subject: [PATCH 4/4] fix(sync): revoke newly deactivated devices during Project holds --- docs/contracts/coordinator-project-moves.md | 5 + .../src/project-boundary-migration-hold.ts | 27 +++- packages/core/src/project-move-admin.test.ts | 85 +++++++++++ packages/core/src/project-move-admin.ts | 8 +- packages/core/src/project-move-device.test.ts | 5 +- packages/core/src/project-move-device.ts | 8 +- .../core/src/recipient-policy-reconciler.ts | 144 ++++++++++-------- .../src/recipient-policy-reconciliation.ts | 18 +++ 8 files changed, 229 insertions(+), 71 deletions(-) diff --git a/docs/contracts/coordinator-project-moves.md b/docs/contracts/coordinator-project-moves.md index b0e47dcb5..57f6145c7 100644 --- a/docs/contracts/coordinator-project-moves.md +++ b/docs/contracts/coordinator-project-moves.md @@ -71,6 +71,11 @@ roster it enforces, and the coordinator does not check it. An ID that is not an authorized member is ignored. Anything else answers 400 `excluded_device_ids_invalid`. +While recipient setup is on hold after a move, reconciliation makes no grants +and leaves copied access unchanged except for people deactivated or merged +after the hold began. It revokes those devices on the next pass. Devices of +people already deactivated or merged when the hold began wait for it to clear. + `team_removal_seq` is required: the group's highest Team removal sequence (`removal_seq`) the admin device had applied when it built `excluded_device_ids`, or 0 when the group has none. Team removals don't revoke diff --git a/packages/core/src/project-boundary-migration-hold.ts b/packages/core/src/project-boundary-migration-hold.ts index ab848945f..9e4d1e9f0 100644 --- a/packages/core/src/project-boundary-migration-hold.ts +++ b/packages/core/src/project-boundary-migration-hold.ts @@ -2,10 +2,14 @@ import { type Database, tableExists } from "./db.js"; import { type ProjectBoundaryMigrationRecordRow, projectBoundaryMigrationRecordFromRow, + type RecordProjectBoundaryMigrationInput, + recordProjectBoundaryMigration, } from "./project-boundary-migration-records.js"; +import { withdrawnIdentityDeviceIds } from "./recipient-policy-reconciliation.js"; /* - * While a Project is held, reconciliation leaves the copied devices alone. + * While a Project is held, reconciliation leaves copied devices alone unless + * their person was withdrawn after the hold began. * The admin device clears the hold automatically when its saved recipients * derive exactly the devices planned for the Project. * @@ -54,7 +58,7 @@ export interface ProjectBoundaryMigrationHold { clearedAt: string | null; /** * Devices that belonged to a deactivated or merged person when this hold was - * first seen at the current generation. Null until a pass has stored them. + * recorded at the current generation. An older hold can lack this list. */ withdrawnAtFirstPassDeviceIds: string[] | null; } @@ -164,6 +168,25 @@ export function getProjectBoundaryMigrationHold( return row ? holdFromRow(row) : null; } +/** Place the hold and capture its exceptions in the same write transaction. */ +export function recordProjectMoveHold( + db: Database, + input: RecordProjectBoundaryMigrationInput & { state: "committed" }, +): boolean { + return db + .transaction(() => { + const changed = recordProjectBoundaryMigration(db, input); + if (changed) + recordHoldWithdrawnDevices(db, { + boundaryScopeId: input.boundaryScopeId, + generation: input.generation, + deviceIds: withdrawnIdentityDeviceIds(db), + }); + return changed; + }) + .immediate(); +} + /** * Clears the hold for the generation the caller read. Returns whether the hold * is clear at that generation afterwards. A newer record, an unreadable row, or diff --git a/packages/core/src/project-move-admin.test.ts b/packages/core/src/project-move-admin.test.ts index cb586c977..f2caacb22 100644 --- a/packages/core/src/project-move-admin.test.ts +++ b/packages/core/src/project-move-admin.test.ts @@ -1,4 +1,5 @@ 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 { readCoordinatorSyncConfig } from "./coordinator-sync-config.js"; import { connect, type Database } from "./db.js"; @@ -16,6 +17,15 @@ import { type RecipientPolicyReconcilerEffects, reconcileRecipientPolicyProject, } from "./recipient-policy-reconciler.js"; +import { + getEffectiveCachedScopeAuthorization, + refreshScopeMembershipCache, +} from "./scope-membership-cache.js"; +import { + cacheMember, + cacheScope, + cacheWireSnapshot, +} from "./scope-membership-cache-test-fixtures.js"; import { teamMemberRemovalRefusesScope } from "./team-member-removal-admission.js"; import { applyTeamMemberRemovals } from "./team-member-removal-policy.js"; @@ -308,6 +318,81 @@ function removeTeamMember() { }); } +async function refreshReplicaBoundary(replica: Database, id: string, revoked: boolean) { + const scope = cacheScope({ + scope_id: id, + kind: "managed_project", + group_id: "test", + coordinator_id: URL, + membership_epoch: revoked ? 2 : 1, + }); + const memberships = TEAM_DEVICES.filter((deviceId) => !revoked || deviceId !== "b").map( + (deviceId) => cacheMember(scope, deviceId), + ); + const refreshed = await refreshScopeMembershipCache(replica, { + coordinatorId: URL, + groupIds: ["test"], + fetchers: { + listScopes: async () => ({ version: 1, items: [scope] }), + getScopeSnapshot: async () => cacheWireSnapshot(scope, memberships), + }, + }); + expect(refreshed.status, JSON.stringify(refreshed)).toBe("refreshed"); + return getEffectiveCachedScopeAuthorization(replica, { + deviceId: "b", + scopeId: id, + expectedPublicKey: CANONICAL_PUBLIC_KEY, + }).authorized; +} + +it("revokes only a newly deactivated device during a held Project move", async () => { + const [project] = PROJECTS; + const id = boundary(project); + mapProject(project); + const copied = [...TEAM_DEVICES, "unlinked"]; + const remote = coordinator(); + const deactivate = (person: string) => + db.prepare("UPDATE actors SET status = 'deactivated' WHERE actor_id = ?").run(person); + deactivate("person-a"); + remote.move.mockImplementation(async () => { + remote.memberships.set(id, new Set(copied)); + return { kind: "moved", deviceIds: copied, excludedDeviceIds: [], createdAt: NOW }; + }); + const readAccess = remote.effects.readAccess.getMockImplementation(); + if (!readAccess) throw new Error("Expected a coordinator access fixture"); + remote.effects.readAccess.mockImplementation(async (source) => { + if (source.scope_id === id) deactivate("person-b"); + return readAccess(source); + }); + await runProjectMoves(db, config, "c", remote.effects); + expect(getProjectBoundaryMigrationHold(db, id)?.held).toBe(true); + adoptBoundary(project); + removeTeamMember(); + + const replica = connect(":memory:"); + try { + expect(await refreshReplicaBoundary(replica, id, false)).toBe(true); + const pass = reconcile(project, remote.memberships); + expect(await pass.result).toMatchObject({ + status: "waiting", + safeErrorCode: "project_move_recipients_pending", + revokedDeviceIds: ["b"], + grantedDeviceIds: [], + }); + expect(pass.revoke).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ scopeId: id, deviceId: "b" }), + ); + expect(remote.memberships.get(id)).toEqual(new Set(["a", "c", "unlinked"])); + expect(getProjectBoundaryMigrationHold(db, id)?.withdrawnAtFirstPassDeviceIds).toEqual(["a"]); + expect(recipients()).toEqual([]); + expect(await refreshReplicaBoundary(replica, id, !remote.memberships.get(id)?.has("b"))).toBe( + false, + ); + } finally { + replica.close(); + } +}); + it.each([ ["removed Team member", removeTeamMember, true], ["removed Team member without a recipient row", removeTeamMember, false], diff --git a/packages/core/src/project-move-admin.ts b/packages/core/src/project-move-admin.ts index 534d631bb..441120b3b 100644 --- a/packages/core/src/project-move-admin.ts +++ b/packages/core/src/project-move-admin.ts @@ -14,8 +14,10 @@ import { coordinatorListTeamMemberRemovalsAction } from "./coordinator-team-memb import type { CoordinatorTeamMemberRemoval } from "./coordinator-team-member-removals.js"; import type { Database } from "./db.js"; import { managedProjectScopeId } from "./managed-project-scope.js"; -import { clearProjectBoundaryMigrationHold } from "./project-boundary-migration-hold.js"; -import { recordProjectBoundaryMigration } from "./project-boundary-migration-records.js"; +import { + clearProjectBoundaryMigrationHold, + recordProjectMoveHold, +} from "./project-boundary-migration-hold.js"; import { cachedProjectMoveMembers, listProjectMoveCandidates, @@ -383,7 +385,7 @@ async function moveCandidate( return issue(project, "access_needs_attention"); } - recordProjectBoundaryMigration(db, { + recordProjectMoveHold(db, { boundaryScopeId, sourceScopeId: source.scope_id, state: "committed", diff --git a/packages/core/src/project-move-device.test.ts b/packages/core/src/project-move-device.test.ts index a60325c9e..c74324d68 100644 --- a/packages/core/src/project-move-device.test.ts +++ b/packages/core/src/project-move-device.test.ts @@ -185,7 +185,10 @@ it("commits the move record and hold before exposing the remapped Project or new expect((await announce()).status).toBe("refreshed"); expect(mappedScope()).toBe(boundary); - expect(getProjectBoundaryMigrationHold(db(), boundary)).toMatchObject({ held: true }); + expect(getProjectBoundaryMigrationHold(db(), boundary)).toMatchObject({ + held: true, + withdrawnAtFirstPassDeviceIds: [], + }); }); it("does not publish the new proof or leave a hold when the remap fails", async () => { diff --git a/packages/core/src/project-move-device.ts b/packages/core/src/project-move-device.ts index fdc695ed3..08ff28aee 100644 --- a/packages/core/src/project-move-device.ts +++ b/packages/core/src/project-move-device.ts @@ -15,10 +15,8 @@ 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 { recordProjectMoveHold } from "./project-boundary-migration-hold.js"; +import { listProjectBoundaryMigrationRecords } from "./project-boundary-migration-records.js"; import { reconcilePreviouslyPulledProjectMove } from "./project-move-arrival.js"; import { canonicalRepositoryProjectIdentity, @@ -239,7 +237,7 @@ function recordLocalMove(db: Database, source: string, boundary: string) { generation: 1, additionalSourceScopeIds: [], }; - if (!recordProjectBoundaryMigration(db, record)) + if (!recordProjectMoveHold(db, record)) throw new Error("Local Project move conflicts with an existing record."); return record; } diff --git a/packages/core/src/recipient-policy-reconciler.ts b/packages/core/src/recipient-policy-reconciler.ts index 7236de240..ea43c98ba 100644 --- a/packages/core/src/recipient-policy-reconciler.ts +++ b/packages/core/src/recipient-policy-reconciler.ts @@ -1,7 +1,10 @@ import { createHash } from "node:crypto"; import type { Database } from "./db.js"; -import { isWithdrawnPolicyIdentity } from "./policy-team-device-eligibility.js"; -import { getProjectBoundaryMigrationHold } from "./project-boundary-migration-hold.js"; +import { + getProjectBoundaryMigrationHold, + type ProjectBoundaryMigrationHold, + recordHoldWithdrawnDevices, +} from "./project-boundary-migration-hold.js"; import { isStrictRecipientPolicyId } from "./recipient-policy-identifiers.js"; import { clearRecipientPolicyDenyOverlay, @@ -18,6 +21,7 @@ import { recordRecipientPolicyReconciliationStepState, recordRecipientPolicyStableParityPass, upsertRecipientPolicyAuthorityObservation, + withdrawnIdentityDeviceIds, } from "./recipient-policy-reconciliation.js"; import { canonicalRepositoryProjectIdentity, @@ -1567,40 +1571,6 @@ function stagePolicyRevocations( } } -/** - * Whether a device is bound to a deactivated or merged Identity. Such a device - * never receives a Project, whatever else the policy says, so revoking it is safe - * even while another problem blocks the rest of the Project's recipients. Devices - * with no binding, or bound to an Identity that is merely pending or missing, are - * left for full derivation to decide. - */ -const WITHDRAWN_BINDING_SQL = `SELECT d.device_id, a.status, a.merged_into_actor_id - FROM identity_devices d JOIN actors a ON a.actor_id = d.identity_id`; - -type BindingRow = { device_id: string; status: string; merged_into_actor_id: string | null }; - -function bindingWithdrawn(row: BindingRow | undefined): boolean { - return ( - row !== undefined && - isWithdrawnPolicyIdentity({ - status: row.status, - mergedIntoIdentityId: row.merged_into_actor_id, - }) - ); -} - -function hasWithdrawnBinding(db: Database): boolean { - const rows = db.prepare(WITHDRAWN_BINDING_SQL).all() as BindingRow[]; - return rows.some(bindingWithdrawn); -} - -function deviceBindingWithdrawn(db: Database, deviceId: string): boolean { - const row = db.prepare(`${WITHDRAWN_BINDING_SQL} WHERE d.device_id = ?`).get(deviceId) as - | BindingRow - | undefined; - return bindingWithdrawn(row); -} - /** * Stages a deny overlay for a device only if this worker still holds the lease and * the device is still bound to a withdrawn Identity, all in one transaction, so a @@ -1610,17 +1580,34 @@ function denyIfStillWithdrawn( run: RecipientPolicyReconciliationRun, scopeId: string, deviceId: string, + holdGeneration?: number, ): boolean { return run.db .transaction(() => { assertLease(run.db, run.projectId, run.leaseOwner, run.effects.now()); - if (!deviceBindingWithdrawn(run.db, deviceId)) return false; + if (withdrawnIdentityDeviceIds(run.db, deviceId).length === 0) return false; + if ( + holdGeneration !== undefined && + !holdAllowsWithdrawal(run.db, scopeId, holdGeneration, deviceId) + ) + return false; stagePolicyRevocations(run, scopeId, [deviceId]); return true; }) .immediate(); } +/** Recheck after the coordinator read in case the hold was replaced or cleared. */ +function holdAllowsWithdrawal(db: Database, scopeId: string, generation: number, deviceId: string) { + const hold = getProjectBoundaryMigrationHold(db, scopeId); + return ( + hold?.held && + hold.generation === generation && + hold.withdrawnAtFirstPassDeviceIds !== null && + !hold.withdrawnAtFirstPassDeviceIds.includes(deviceId) + ); +} + function isLeaseLost(error: unknown): boolean { return error instanceof Error && error.message === "recipient_policy_lease_lost"; } @@ -1635,12 +1622,18 @@ function isLeaseLost(error: unknown): boolean { */ async function revokeWithdrawnDevices( run: RecipientPolicyReconciliationRun, - input: { scopeId: string; snapshotStateKey: string; candidateDeviceIds: string[] }, + input: { + scopeId: string; + snapshotStateKey: string; + candidateDeviceIds: string[]; + holdGeneration?: number; + }, ): Promise { let revokeError: unknown = null; let refreshError: unknown = null; for (const deviceId of input.candidateDeviceIds) { - if (!denyIfStillWithdrawn(run, input.scopeId, deviceId) || revokeError) continue; + if (!denyIfStillWithdrawn(run, input.scopeId, deviceId, input.holdGeneration) || revokeError) + continue; try { const error = await applyPolicyRevocation(run, { scopeId: input.scopeId, @@ -1665,6 +1658,38 @@ async function revokeWithdrawnDevices( }); } +async function revokeWithdrawnBoundaryMembers( + run: RecipientPolicyReconciliationRun, + scopeId: string, + startedAt: string, + hold?: ProjectBoundaryMigrationHold, +): Promise { + const withdrawn = withdrawnIdentityDeviceIds(run.db); + let exempt = new Set(); + if (hold) { + if (hold.generation === null) return; + const atStart = + hold.withdrawnAtFirstPassDeviceIds ?? + recordHoldWithdrawnDevices(run.db, { + boundaryScopeId: scopeId, + generation: hold.generation, + deviceIds: withdrawn, + }); + if (!atStart) return; + exempt = new Set(atStart); + } + if (!withdrawn.some((deviceId) => !exempt.has(deviceId))) return; + const snapshot = await run.effects.snapshot({ canonicalProjectIdentity: run.projectId, scopeId }); + await revokeWithdrawnDevices(run, { + scopeId, + snapshotStateKey: digest("recipient-policy-snapshot-state-v1", { + fingerprint: snapshot.fingerprint, + }), + candidateDeviceIds: activeSnapshotDevices(snapshot, scopeId, startedAt), + holdGeneration: hold?.generation ?? undefined, + }); +} + /** * Full derivation is blocked, so nothing is granted and the blocker is reported. * Deactivating or merging a person still revokes their devices here (ADR 0007 @@ -1679,19 +1704,7 @@ async function blockedDerivationResult( safeErrorCode: "recipient_policy_desired_state_invalid", now: run.effects.now(), }); - if (hasWithdrawnBinding(run.db)) { - const snapshot = await run.effects.snapshot({ - canonicalProjectIdentity: run.projectId, - scopeId: managedBoundary.scopeId, - }); - await revokeWithdrawnDevices(run, { - scopeId: managedBoundary.scopeId, - snapshotStateKey: digest("recipient-policy-snapshot-state-v1", { - fingerprint: snapshot.fingerprint, - }), - candidateDeviceIds: activeSnapshotDevices(snapshot, managedBoundary.scopeId, startedAt), - }); - } + await revokeWithdrawnBoundaryMembers(run, managedBoundary.scopeId, startedAt); return result( run.projectId, "needs_attention", @@ -1701,6 +1714,22 @@ async function blockedDerivationResult( ); } +async function reconcileHeldProjectMove( + run: RecipientPolicyReconciliationRun, + hold: ProjectBoundaryMigrationHold, + startedAt: string, +): Promise { + authority(run, { safeErrorCode: PROJECT_MOVE_RECIPIENTS_PENDING, now: startedAt }); + await revokeWithdrawnBoundaryMembers(run, hold.boundaryScopeId, startedAt, hold); + return result( + run.projectId, + "waiting", + run.activeGeneration, + PROJECT_MOVE_RECIPIENTS_PENDING, + run.revokedDeviceIds, + ); +} + async function prepareInitialReconciliation( run: RecipientPolicyReconciliationRun, startedAt: string, @@ -1709,16 +1738,11 @@ async function prepareInitialReconciliation( canonicalProjectIdentity: run.projectId, }); const managedBoundary = boundary(run.db, run.projectId); - if (getProjectBoundaryMigrationHold(run.db, managedBoundary.scopeId)?.held) { - authority(run, { safeErrorCode: PROJECT_MOVE_RECIPIENTS_PENDING, now: startedAt }); + const hold = getProjectBoundaryMigrationHold(run.db, managedBoundary.scopeId); + if (hold?.held) { return { kind: "complete", - result: result( - run.projectId, - "waiting", - run.activeGeneration, - PROJECT_MOVE_RECIPIENTS_PENDING, - ), + result: await reconcileHeldProjectMove(run, hold, startedAt), }; } const desired = deriveRecipientPolicyEffectiveDevicesFromDatabase(run.db, run.projectId); diff --git a/packages/core/src/recipient-policy-reconciliation.ts b/packages/core/src/recipient-policy-reconciliation.ts index cf1e29225..3c67f1f7d 100644 --- a/packages/core/src/recipient-policy-reconciliation.ts +++ b/packages/core/src/recipient-policy-reconciliation.ts @@ -23,6 +23,24 @@ export { isStrictRecipientPolicyId }; export type RecipientPolicyAuthorityState = "legacy" | "eligible" | "active" | "rolled_back"; +/** Device bindings that belong to a deactivated or merged person. */ +export function withdrawnIdentityDeviceIds(db: Database, deviceId?: string): string[] { + const rows = db + .prepare(`SELECT d.device_id, a.status, a.merged_into_actor_id + FROM identity_devices d JOIN actors a ON a.actor_id = d.identity_id + ${deviceId === undefined ? "" : "WHERE d.device_id = ?"}`) + .all(...(deviceId === undefined ? [] : [deviceId])) as Array<{ + device_id: string; + status: string; + merged_into_actor_id: string | null; + }>; + return rows.flatMap(({ device_id, status, merged_into_actor_id }) => + isWithdrawnPolicyIdentity({ status, mergedIntoIdentityId: merged_into_actor_id }) + ? [device_id] + : [], + ); +} + export type RecipientPolicyDerivationBlockCode = | "canonical_project_identity_invalid" | "project_recipient_invalid"