Skip to content
Open
28 changes: 23 additions & 5 deletions docs/contracts/coordinator-project-moves.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,10 +157,28 @@ nobody at the switch:

`GET /v1/project-moves?group_id=<group>`, signed by an enrolled device of the
group, answers `{ "moves": [ … ] }` with every logged move of the group, oldest
first. A device maps a Project to a boundary only when a logged move names a
scope that holds the Project's memories as `source_scope_id`, the boundary ID
it derives for that Project equals `boundary_scope_id`, and its membership cache
shows it authorized in the boundary. It then moves only the memories it wrote
itself. A device that was offline during the move moves when it next refreshes.
first. A device records moves for boundaries it can access, even when it has
no Project mapping. Snapshots and incremental updates in either scope use the
same rule: when the device holds one non-private copy with the same memory key
and stored origin, it keeps the newest revision under the boundary. A recorded
author that conflicts with the stored origin prevents this reconciliation.
An empty origin or the legacy `local` value cannot identify an author.
If the device pulled both copies before seeing the move, it compares them when
it records the move. An older-scope arrival can identify its boundary only
when the boundary already holds that memory. Ambiguous arrivals update only
their own scope.
`codemem sync duplicates` lists copies that still share a memory key.

A device remaps a Project only when it still maps to the move's source scope
and the derived boundary ID matches. It then restamps only memories it wrote
itself. A device that was offline during the move learns of it when it next
refreshes.

Before restamping, a device saves one private SQLite backup beside its store
as `<store>.before-project-moves.sqlite` and syncs the file and its parent
directory to disk. A backup failure leaves all source memories in place.
codemem keeps this backup until you remove it. Run
`codemem sync migration status` to see the backup path and size, and how many
rows still carry each older scope on this device.

The TypeScript types are in `packages/core/src/coordinator-project-moves.ts`.
9 changes: 6 additions & 3 deletions docs/coordinator-discovery.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,16 @@ Backward compatibility:

### Boundary migration rollout setting

`sync_boundary_migration` has the environment override
`CODEMEM_SYNC_BOUNDARY_MIGRATION` and defaults to `off`.
`sync_boundary_migration=on` enables Project moves and advertises support for
them in coordinator presence. It defaults to `off` and can be overridden with
`CODEMEM_SYNC_BOUNDARY_MIGRATION`. With migration off, the device still records
moves so it can reconcile received copies, but it does not remap Projects or
restamp memories it authored.

| Value | `codemem sync migration status` behavior |
| --- | --- |
| `off` | Report that the migration is off. |
| `report`, `on` | Read the local database and report Project candidates and filter evidence. Neither setting starts a migration. |
| `report`, `on` | Read the local database and report Project candidates and filter evidence. The report itself never starts a move. |

Use `--json` for counts or `--db-path` and `--config` to inspect a particular install.
The report sends no requests and does not change sharing or advertise readiness. A
Expand Down
21 changes: 21 additions & 0 deletions packages/cli/src/commands/sync-migration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ it("distinguishes a fresh peer install from a configured coordinator that cannot
maintenance_window: expect.stringContaining("stop every client"),
storage_fence: expect.stringContaining("does not erase data from disk"),
projects: null,
adopted_sources: [],
});
expect(fetch).not.toHaveBeenCalled();
});
Expand All @@ -73,6 +74,26 @@ it("does not create a missing database or classify a damaged config as peer-only
expect(process.exitCode).toBe(1);
});

it("reports the local backup path and byte size even when migration reporting is off", async () => {
connect(dbPath).close();
vi.stubEnv("CODEMEM_SYNC_BOUNDARY_MIGRATION", "off");
const backup = `${dbPath}.before-project-moves.sqlite`;
writeFileSync(backup, "fixture", { mode: 0o600 });
const output = vi.spyOn(process.stdout, "write").mockReturnValue(true);

await status();
expect(JSON.parse(String(output.mock.calls.at(-1)?.[0]))).toMatchObject({
backup: { path: backup, size_bytes: 7 },
});
await buildSyncMigrationCommand().parseAsync(
["status", "--db-path", dbPath, "--config", configPath],
{ from: "user" },
);
expect(output.mock.calls.map(([chunk]) => String(chunk)).join("")).toContain(
`${backup} (7 bytes)`,
);
});

it("tells the person in text what the storage fence does not erase and how to recover", async () => {
connect(dbPath).close();
writeFileSync(
Expand Down
32 changes: 29 additions & 3 deletions packages/cli/src/commands/sync-migration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,19 @@ import {
resolveDbOpt,
} from "../shared-options.js";

function sourceRowsText(rows: Array<{ source_scope_id: string; remaining_rows: number }> = []) {
return rows
.map(
({ source_scope_id, remaining_rows }) =>
`${source_scope_id}: ${remaining_rows} rows still in the older scope.`,
)
.join("\n");
}

function reportText(report: ReturnType<typeof readLocalProjectMigrationReport>): string {
switch (report.state) {
case "off":
return "Project migration reporting is off.";
return sourceRowsText(report.adopted_sources) || "Project migration reporting is off.";
case "not_applicable":
return "This device uses basic peer sync. No Project migration is needed.";
case "waiting_for_coordinator":
Expand All @@ -32,7 +41,15 @@ function reportText(report: ReturnType<typeof readLocalProjectMigrationReport>):
const observed = counts
? `Project candidates: ${counts.candidate_projects}. Projects in multiple setups: ${counts.multiple_sources}. Locally authored rows in those setups: ${counts.own_source_rows}.`
: "The local Project inventory is unavailable.";
return `${observed}\nLocal filter evidence: ${report.local_filters}. Other devices have not been checked.\n${report.maintenance_window}\n${report.storage_fence}`;
return [
observed,
sourceRowsText(report.adopted_sources),
`Local filter evidence: ${report.local_filters}. Other devices have not been checked.`,
report.maintenance_window,
report.storage_fence,
]
.filter(Boolean)
.join("\n");
}
}
}
Expand All @@ -55,7 +72,16 @@ function migrationStatus(opts: DbOpts & ConfigOpts & JsonOpts) {
config.status === "valid" ? config.data : {},
);
if (opts.json) process.stdout.write(`${JSON.stringify(report)}\n`);
else p.log.info(reportText(report));
else
p.log.info(
[
reportText(report),
report.backup &&
`Project migration backup: ${report.backup.path} (${report.backup.size_bytes} bytes).`,
]
.filter(Boolean)
.join("\n"),
);
} finally {
db.close();
}
Expand Down
17 changes: 11 additions & 6 deletions packages/core/src/boundary-migration-config.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { readBoundaryMigrationMode } from "./coordinator-sync-config.js";
import { coordinatorPresenceSyncFeatures } from "./coordinator-runtime.js";
import { readBoundaryMigrationMode, readCoordinatorSyncConfig } from "./coordinator-sync-config.js";
import { getCodememEnvOverrides } from "./observer-config.js";
import { LOCAL_SYNC_FEATURES, supportsSyncFeature } from "./sync-capability.js";

Expand Down Expand Up @@ -44,13 +45,17 @@ describe("the boundary migration rollout mode", () => {
expect(getCodememEnvOverrides().sync_boundary_migration).toBeUndefined();
});

it("recognizes the move feature without advertising it before the mover exists", () => {
vi.stubEnv("CODEMEM_SYNC_BOUNDARY_MIGRATION", "on");

expect(readBoundaryMigrationMode({})).toBe("on");
it("recognizes Project move capability advertised by a peer", () => {
expect(
supportsSyncFeature(["project_boundary_migration_v1"], "project_boundary_migration_v1"),
).toBe(true);
expect(LOCAL_SYNC_FEATURES).not.toContain("project_boundary_migration_v1");
});

it("advertises supported Project moves in coordinator presence only when enabled", () => {
const feature = "project_boundary_migration_v1";
const enabled = readCoordinatorSyncConfig({ sync_boundary_migration: "on" });
expect(coordinatorPresenceSyncFeatures(readCoordinatorSyncConfig({}), [feature])).toEqual([]);
expect(coordinatorPresenceSyncFeatures(enabled, [])).toEqual([]);
expect(coordinatorPresenceSyncFeatures(enabled, LOCAL_SYNC_FEATURES)).toContain(feature);
});
});
34 changes: 34 additions & 0 deletions packages/core/src/coordinator-runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
readCoordinatorSyncConfig,
refreshAuthorizedCoordinatorPeerTrust,
refreshStoredCoordinatorPeerAddresses,
registerCoordinatorPresence,
revokeUnauthorizedCoordinatorPeerTrust,
trustCoordinatorPeersWithSharedManagedScopes,
} from "./coordinator-runtime.js";
Expand All @@ -50,6 +51,39 @@ const EXPECTED_PRESENCE_CAPABILITIES = {
transport_statement: { payload: expect.any(String), signature: expect.any(String) },
};

it.each(["off", "on"] as const)(
"posts the Project move feature correctly when migration is %s",
async (mode) => {
const keysDir = mkdtempSync(join(tmpdir(), "project-move-presence-"));
const db = new Database(":memory:");
vi.stubEnv("CODEMEM_SYNC_BOUNDARY_MIGRATION", undefined);
const post = vi.spyOn(globalThis, "fetch").mockResolvedValue(Response.json({}));
try {
initTestSchema(db);
await registerCoordinatorPresence(
{ db, dbPath: ":memory:" },
readCoordinatorSyncConfig({
sync_coordinator_url: "https://coord.example.test",
sync_coordinator_group: "team-a",
sync_boundary_migration: mode,
}),
{ keysDir },
);
const request = post.mock.calls.find(([url]) => String(url).endsWith("/v1/presence"));
expect(request).toBeDefined();
const body = JSON.parse(Buffer.from(request?.[1]?.body as Uint8Array).toString("utf8"));
expect(body.capabilities.sync_features.includes("project_boundary_migration_v1")).toBe(
mode === "on",
);
} finally {
post.mockRestore();
vi.unstubAllEnvs();
db.close();
rmSync(keysDir, { recursive: true, force: true });
}
},
);

describe("readCoordinatorSyncConfig.syncOpsLimit", () => {
afterEach(() => {
delete process.env.CODEMEM_SYNC_OPS_LIMIT;
Expand Down
15 changes: 13 additions & 2 deletions packages/core/src/coordinator-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
type PeerRemovalLookup,
type PeerRevocationCheckStatus,
} from "./coordinator-peer-revocation.js";
import { PROJECT_MOVE_SYNC_FEATURE } from "./coordinator-project-moves.js";
import {
clearCoordinatorDeviceRemoved,
recordCoordinatorDeviceRemoved,
Expand All @@ -41,7 +42,7 @@ import {
import { getEffectiveCachedScopeAuthorization } from "./scope-membership-cache.js";
import type { MemoryStore } from "./store.js";
import { buildAuthHeaders } from "./sync-auth.js";
import { LOCAL_SYNC_CAPABILITY, LOCAL_SYNC_FEATURES } from "./sync-capability.js";
import { LOCAL_SYNC_CAPABILITY, LOCAL_SYNC_FEATURES, type SyncFeature } from "./sync-capability.js";
import { fingerprintPublicKey } from "./sync-fingerprint.js";
import { buildBaseUrl, requestJson } from "./sync-http-client.js";
import { ensureDeviceIdentity, loadPrivateKey, loadPublicKey } from "./sync-identity.js";
Expand Down Expand Up @@ -142,6 +143,7 @@ function presenceCacheKey(store: PresenceStoreLike, config: CoordinatorSyncConfi
config.syncPort,
config.syncAdvertise,
config.syncCoordinatorPresenceTtlS,
config.syncBoundaryMigrationEnabled === true,
].join("|");
}

Expand Down Expand Up @@ -263,6 +265,15 @@ export function advertisedSyncAddresses(config: CoordinatorSyncConfig): string[]
return [...new Set(addresses)];
}

export function coordinatorPresenceSyncFeatures(
config: Pick<CoordinatorSyncConfig, "syncBoundaryMigrationEnabled">,
features: readonly SyncFeature[] = LOCAL_SYNC_FEATURES,
): readonly SyncFeature[] {
return config.syncBoundaryMigrationEnabled
? features
: features.filter((feature) => feature !== PROJECT_MOVE_SYNC_FEATURE);
}

export async function registerCoordinatorPresence(
store: PresenceStoreLike,
config: CoordinatorSyncConfig,
Expand All @@ -285,7 +296,7 @@ export async function registerCoordinatorPresence(
ttl_s: Math.max(1, config.syncCoordinatorPresenceTtlS),
capabilities: {
sync_capability: LOCAL_SYNC_CAPABILITY,
sync_features: LOCAL_SYNC_FEATURES,
sync_features: coordinatorPresenceSyncFeatures(config),
// 0 until a complete lookup has covered every pairing and binding this device has now.
applied_removal_seq: readAppliedRemovalSeq(store.db),
...localTransportStatementCapability({
Expand Down
11 changes: 8 additions & 3 deletions packages/core/src/coordinator-sync-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export interface CoordinatorSyncConfig {
syncAllowLegacyPlaintext: boolean;
syncProjectsInclude: string[];
syncProjectsExclude: string[];
syncBoundaryMigrationEnabled?: boolean;
syncOpsLimit: number;
syncCoordinatorUrl: string;
syncCoordinatorGroup: string;
Expand Down Expand Up @@ -102,11 +103,14 @@ export function readRelayClientSettings(config?: ConfigRecord): RelayClientSetti
}

/**
* Selects the rollout mode without activating the migration or advertising
* readiness. Invalid nonempty settings disable migration.
* Only `on` enables Project moves. Invalid settings disable migration.
*/
export function readBoundaryMigrationMode(config?: ConfigRecord): BoundaryMigrationMode {
const mode = clean(readRawSyncConfig(config).sync_boundary_migration).toLowerCase();
return parseBoundaryMigrationMode(readRawSyncConfig(config).sync_boundary_migration);
}

function parseBoundaryMigrationMode(value: unknown): BoundaryMigrationMode {
const mode = clean(value).toLowerCase();
if (mode === "report" || mode === "on") return mode;
return "off";
}
Expand Down Expand Up @@ -140,6 +144,7 @@ export function readCoordinatorSyncConfig(config?: ConfigRecord): CoordinatorSyn
syncAllowLegacyPlaintext: parseBoolOr(raw.sync_allow_legacy_plaintext, false),
syncProjectsInclude: parseStringList(raw.sync_projects_include),
syncProjectsExclude: parseStringList(raw.sync_projects_exclude),
syncBoundaryMigrationEnabled: parseBoundaryMigrationMode(raw.sync_boundary_migration) === "on",
syncOpsLimit: Math.max(1, Math.min(1000, parseIntOr(raw.sync_ops_limit, 500))),
syncCoordinatorUrl: clean(raw.sync_coordinator_url),
syncCoordinatorGroup,
Expand Down
26 changes: 22 additions & 4 deletions packages/core/src/memory-creation-provenance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,18 @@ import { tableExists as hasTable } from "./schema-lookups.js";

// Actor/workspace aliases and replication clocks may change during local adoption.
// Scope and user-facing content must still match the immutable creation snapshot.
const CREATION_CONTENT_SQL = `json_array(memory_items.kind, memory_items.title,
const creationContentSql = (
extraMetadataPaths = "",
) => `json_array(memory_items.kind, memory_items.title,
memory_items.subtitle, memory_items.body_text, memory_items.confidence,
memory_items.tags_text, memory_items.visibility, memory_items.workspace_kind,
memory_items.origin_source, memory_items.trust_state, memory_items.narrative,
memory_items.facts, memory_items.concepts, memory_items.files_read,
memory_items.files_modified, memory_items.user_prompt_id, memory_items.prompt_number,
memory_items.project, memory_items.active, memory_items.deleted_at,
json_remove(CASE WHEN json_valid(memory_items.metadata_json)
THEN memory_items.metadata_json ELSE '{}' END, '$.clock_device_id', '$.import_key'))`;
THEN memory_items.metadata_json ELSE '{}' END, '$.clock_device_id', '$.import_key'${extraMetadataPaths}))`;
const CREATION_CONTENT_SQL = creationContentSql();

function ensureCreationProvenanceSchema(db: Database): void {
db.exec(`CREATE TABLE IF NOT EXISTS memory_local_creation_snapshots (
Expand Down Expand Up @@ -114,10 +117,25 @@ export function matchingLocalCreationClause(db: Database): string | null {
WHERE creation_device.device_id = (SELECT source_device_id FROM memory_source_bindings WHERE entity_id = creation.entity_id)
AND creation_device.public_key = creation.source_public_key
AND creation_device.fingerprint = creation.source_fingerprint))`;
const contentMatch =
hasTable(db, "project_boundary_migrations") &&
hasTable(db, "memory_copy_identities") &&
hasTable(db, "memory_copy_creations")
? `(creation.scope_id IS memory_items.scope_id AND creation.content_json = ${CREATION_CONTENT_SQL}
OR (EXISTS (SELECT 1 FROM project_boundary_migrations move
WHERE move.state = 'committed' AND move.source_scope_id = creation.scope_id
AND move.boundary_scope_id = memory_items.scope_id)
AND EXISTS (SELECT 1 FROM memory_copy_identities copy JOIN memory_copy_creations born USING (copy_id)
WHERE copy.memory_id = memory_items.id)
AND json_extract(CASE WHEN json_valid(memory_items.metadata_json) THEN memory_items.metadata_json END,
'$.last_scope_reassignment.old_scope_id') = creation.scope_id
AND json_extract(CASE WHEN json_valid(memory_items.metadata_json) THEN memory_items.metadata_json END,
'$.last_scope_reassignment.new_scope_id') = memory_items.scope_id
AND creation.content_json = ${creationContentSql(", '$.last_scope_reassignment'")}))`
: `creation.scope_id IS memory_items.scope_id AND creation.content_json = ${CREATION_CONTENT_SQL}`;
return `EXISTS (SELECT 1 FROM memory_local_creation_snapshots creation
WHERE creation.entity_id = memory_items.import_key
AND creation.scope_id IS memory_items.scope_id
AND creation.content_json = ${CREATION_CONTENT_SQL}
AND (${contentMatch})
AND ${keyMatchSql}
AND NOT EXISTS (SELECT 1 FROM memory_foreign_revisions foreign_revision
WHERE foreign_revision.entity_id = creation.entity_id))`;
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/project-migration-report.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ it("counts one split candidate without exporting names, content, or any readines
expect(readLocalProjectMigrationReport(db, CONFIG)).toEqual({
mode: "report",
state: "local_report",
adopted_sources: [],
local_filters: "none",
maintenance_window: expect.stringMatching(/including current versions.*already read/),
storage_fence: expect.stringMatching(
Expand Down
Loading
Loading