Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/contracts/coordinator-project-moves.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
19 changes: 9 additions & 10 deletions docs/coordinator-discovery.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,23 +74,22 @@ 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.
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 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.

Expand Down
9 changes: 6 additions & 3 deletions packages/cli/src/commands/serve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
resolveCodememConfigPath,
resolveDbPath,
resolveKeyPaths,
runProjectMoves,
runSyncDaemon,
type SyncDaemonTickCallback,
VERSION,
Expand Down Expand Up @@ -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),
}),
});
},
};
}

Expand Down
120 changes: 115 additions & 5 deletions packages/cli/src/commands/sync-migration.test.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -57,6 +63,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();
});
Expand All @@ -74,7 +81,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`;
Expand All @@ -89,9 +96,9 @@ it("reports the local backup path and byte size even when migration reporting is
["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 () => {
Expand All @@ -112,3 +119,106 @@ 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();
});

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<Parameters<typeof runProjectMoves>[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();
}
});
42 changes: 38 additions & 4 deletions packages/cli/src/commands/sync-migration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof readLocalProjectMigrationReport>): 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,
]
Expand Down Expand Up @@ -76,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).`,
]
Expand Down
80 changes: 79 additions & 1 deletion packages/core/src/coordinator-project-move-commit.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
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 {
PROJECT_MOVE_CLOCK_MS,
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 {
Expand Down Expand Up @@ -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 });
}
},
);
Loading