import assert from "node:assert/strict"; import { mkdtempSync, renameSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { test } from "node:test"; import { createProjectInventoryReader, createProjectReaders, MemoryStore } from "../packages/core/dist/index.js"; import { createApp } from "../packages/viewer-server/dist/index.js"; const PROJECTS = "/api/sync/projects"; const MIGRATION_DETAILS = `${PROJECTS}/migration-details`; const REVIEW = "/api/sync/recipient-policy/v1/review"; const REVIEW_UNAVAILABLE = { error: "recipient_policy_review_unavailable" }; const REPOSITORY = "https://example.test/acme/api.git"; const CWD = "/fixture/api-worktree"; const DATE = "2026-11-02T00:00:00.000Z"; const RECEIVER_NOTICE = { projectIdentity: REPOSITORY, projectName: "api", reason: "removed_from_assumed_team", devices: [], }; function openStore(t, file) { const store = new MemoryStore(file); t.after(() => store.closeAsync()); return store; } function databasePath(t) { const directory = mkdtempSync(join(tmpdir(), "codemem-project-inventory-")); t.after(() => rmSync(directory, { recursive: true, force: true })); return join(directory, "db.sqlite"); } function seedStore(store) { const insert = store.db.prepare( "INSERT INTO sessions(started_at, cwd, project, git_remote) VALUES (?, ?, ?, ?)", ); const api = Number(insert.run(DATE, CWD, "api", REPOSITORY).lastInsertRowid); const web = Number(insert.run(DATE, "/fixture/web", "web", null).lastInsertRowid); const insertMemory = store.db.prepare(`INSERT INTO memory_items( session_id, kind, title, body_text, created_at, updated_at ) VALUES (?, 'discovery', ?, 'fixture', ?, ?)`); insertMemory.run(api, "Test API memory", DATE, DATE); insertMemory.run(web, "Test web memory", DATE, DATE); store.db.exec(`CREATE TABLE project_move_receiver_notices ( boundary_scope_id TEXT PRIMARY KEY, notice_json TEXT NOT NULL )`); store.db.prepare("INSERT INTO project_move_receiver_notices VALUES (?, ?)").run( "fixture-boundary", JSON.stringify(RECEIVER_NOTICE), ); store.db.prepare(`INSERT INTO share_operations( operation_id, state, inviter_actor_id, inviter_device_ids_json, person_id, person_kind, teammate_name, history_policy, reviewed_project_set_digest, coordinator_group_id, invite_token_digest, invite_expires_at, recipient_actor_id, recipient_device_id, acceptance_consumed_at, created_at, updated_at ) VALUES ('fixture-share', 'active', ?, ?, 'fixture-person', 'existing', 'Fixture person', 'existing_and_future', 'digest', 'team', 'invite-digest', '2099-01-01T00:00:00.000Z', 'fixture-person', 'fixture-device', ?, ?, ?)`) .run(store.actorId, JSON.stringify([store.deviceId]), DATE, DATE, DATE); store.db.prepare(`INSERT INTO share_operation_projects( operation_id, canonical_project_identity, display_name, identity_source, existing_memory_count, ordinal ) VALUES ('fixture-share', ?, 'api', 'cwd', 1, 0)`).run(CWD); seedUnmatchedReceivedMemory(store); } function seedUnmatchedReceivedMemory(store) { store.db.prepare(`INSERT INTO replication_scopes( scope_id, label, kind, authority_type, coordinator_id, group_id, created_at, updated_at ) VALUES ('fixture-older-scope', 'Older scope', 'team', 'coordinator', 'https://example.test', 'fixture-group', ?, ?)`).run(DATE, DATE); const { lastInsertRowid } = store.db.prepare(`INSERT INTO sessions(started_at, project, tool_version) VALUES (?, 'received', 'sync_replication')`).run(DATE); store.db.prepare(`INSERT INTO memory_items( session_id, kind, title, body_text, created_at, updated_at, scope_id, project ) VALUES (?, 'discovery', 'Received memory', 'fixture', ?, ?, 'fixture-older-scope', 'received')`) .run(lastInsertRowid, DATE, DATE); } function forbidInventoryQueriesOnParent(store) { const prepare = store.db.prepare.bind(store.db); const forbidden = []; store.db.prepare = (sql) => { const normalized = sql.replace(/\s+/g, " ").trim(); if (/^SELECT (?:DISTINCT )?cwd\b|'local' AS inventory_source|kind NOT IN \('managed_project', 'personal'\)|SELECT notice_json FROM project_move_receiver_notices|WITH session_counts|recipient_policy_review_resolutions/i.test(normalized)) { forbidden.push(normalized); throw new Error("Project inventory queried the Viewer's SQLite connection"); } return prepare(sql); }; return forbidden; } async function readProjects(app, query = "") { const response = await app.request(`${PROJECTS}${query}`); assert.equal(response.status, 200, await response.clone().text()); return response.json(); } test("the built Viewer runs file-backed Projects inventory and migration reads off its connection", async (t) => { const inMemory = openStore(t, ":memory:"); const store = openStore(t, databasePath(t)); seedStore(inMemory); seedStore(store); const inline = createApp({ storeFactory: () => inMemory }); const fileBacked = createApp({ storeFactory: () => store }); const forbidden = forbidInventoryQueriesOnParent(store); const full = await readProjects(fileBacked, "?q=api&status=local_only&limit=1"); assert.deepEqual(full, await readProjects(inline, "?q=api&status=local_only&limit=1")); assert.equal(full.total, 1); assert.equal(full.projects[0].memory_count, 1); assert.equal(full.projects[0].sharing.length, 1); assert.deepEqual(full.migration_issues, [RECEIVER_NOTICE]); assert.deepEqual(full.migration_unmatched_received, [{ sourceScopeId: "fixture-older-scope", label: "Older scope", memoryCount: 1, }]); const page = "?status=local_only&offset=1&limit=1&include_migration_details=false"; const paged = await readProjects(fileBacked, page); assert.deepEqual(paged, await readProjects(inline, page)); assert.equal(paged.total, 2); assert.equal(paged.offset, 1); assert.equal(paged.migration_issues, undefined); assert.equal(paged.migration_unmatched_received, undefined); const migration = await fileBacked.request(MIGRATION_DETAILS); assert.equal(migration.status, 200); assert.deepEqual(await migration.json(), { migration_issues: full.migration_issues, migration_unmatched_received: full.migration_unmatched_received, }); const fileReview = await fileBacked.request(REVIEW); const inlineReview = await inline.request(REVIEW); assert.equal(fileReview.status, 200); assert.equal(inlineReview.status, 200); assert.deepEqual(await fileReview.json(), await inlineReview.json()); assert.deepEqual(forbidden, []); }); test("the built Sharing Review uses the same two slots as Projects and sequenced migration notices", async (t) => { const store = openStore(t, databasePath(t)); const app = createApp({ storeFactory: () => store }); const firstReview = app.request(REVIEW); const projects = app.request(`${PROJECTS}?include_migration_details=false`); const excess = await app.request(REVIEW); assert.equal(excess.status, 503); assert.deepEqual(await excess.json(), REVIEW_UNAVAILABLE); assert.equal((await projects).status, 200); const migration = app.request(MIGRATION_DETAILS); assert.equal((await firstReview).status, 200); assert.equal((await migration).status, 200); }); test("the built Viewer discards an aborted Sharing Review and serves the next request", async (t) => { const store = openStore(t, databasePath(t)); const app = createApp({ storeFactory: () => store }); const forbidden = forbidInventoryQueriesOnParent(store); const abort = new AbortController(); const response = app.request(REVIEW, { signal: abort.signal }); abort.abort(); const cancelled = await response; assert.equal(cancelled.status, 503); assert.deepEqual(await cancelled.json(), REVIEW_UNAVAILABLE); assert.equal((await app.request(REVIEW)).status, 200); assert.deepEqual(forbidden, []); }); test("the built reader refuses excess requests and cancels an admitted worker", async (t) => { const store = openStore(t, databasePath(t)); const read = createProjectInventoryReader(); const request = { filters: {}, includeMigrationDetails: false }; const abort = new AbortController(); const keep = new AbortController(); const first = read(store, request, abort.signal); const second = read(store, request, keep.signal); const excess = read(store, request, keep.signal); abort.abort(); assert.equal(await excess, null); assert.equal(await first, null); assert.ok(await second); }); test("the built Sharing Review reader stops waiting at the existing deadline", async (t) => { const store = openStore(t, databasePath(t)); const { readRecipientPolicyReview } = createProjectReaders(); t.mock.timers.enable({ apis: ["setTimeout"] }); const result = readRecipientPolicyReview(store, new AbortController().signal); t.mock.timers.tick(15_000); assert.equal(await result, null); }); test("the built Viewer refuses a changed file without reading inventory on the main thread", async (t) => { const path = databasePath(t); const store = openStore(t, path); const app = createApp({ storeFactory: () => store }); const forbidden = forbidInventoryQueriesOnParent(store); const replacement = openStore(t, `${path}.replacement`); await replacement.closeAsync(); renameSync(`${path}.replacement`, path); for (const [endpoint, expected] of [ [PROJECTS, { error: "project_inventory_unavailable" }], [MIGRATION_DETAILS, { error: "project_inventory_unavailable" }], [REVIEW, REVIEW_UNAVAILABLE], ]) { const response = await app.request(endpoint); assert.equal(response.status, 503); assert.deepEqual(await response.json(), expected); } assert.deepEqual(forbidden, []); }); test("the built Sharing Review reader refuses the result when the local Identity generation changes", async (t) => { const store = openStore(t, databasePath(t)); store.db.exec(`CREATE TABLE IF NOT EXISTS local_identity_generation ( id INTEGER PRIMARY KEY, generation INTEGER NOT NULL, actor_id TEXT NOT NULL )`); store.db.prepare("INSERT INTO local_identity_generation VALUES (1, 1, ?)").run(store.actorId); const { readRecipientPolicyReview } = createProjectReaders(); const result = readRecipientPolicyReview(store, new AbortController().signal); store.db.prepare("UPDATE local_identity_generation SET generation = 2 WHERE id = 1").run(); assert.equal(await result, null); });