import test from "node:test"; import assert from "node:assert/strict"; import { registerResource, resolveOwner, listResources, type SessionLike } from "../registry.js"; function fakeSession(records: Array<{ get(key: string): unknown }>) { const calls: Array<{ cypher: string; params?: Record }> = []; const session: SessionLike = { async run(cypher, params) { calls.push({ cypher, params }); return { records }; }, }; return { session, calls }; } test("registerResource MERGEs on (kind, name) and sets accountId only on create", async () => { const { session, calls } = fakeSession([]); await registerResource(session, { accountId: "acc-a", kind: "d1", name: "gls-leads", cfResourceId: "db-123", }); // Ownership key is (kind, name): a name maps to exactly one owner on the // shared account, so resolveOwner's lookup key and the write key must agree. assert.match( calls[0].cypher, /MERGE \(r:StorageResource \{kind: \$kind, name: \$name\}\)/, ); // accountId is set ON CREATE and never overwritten ON MATCH (no silent takeover). assert.match(calls[0].cypher, /ON CREATE SET r\.accountId = \$accountId/); assert.doesNotMatch(calls[0].cypher, /ON MATCH SET[\s\S]*accountId/); assert.match(calls[0].cypher, /r\.createdByAgent = 'system'/); assert.match(calls[0].cypher, /r\.createdBySource = 'storage-broker'/); assert.deepEqual(calls[0].params, { accountId: "acc-a", kind: "d1", name: "gls-leads", cfResourceId: "db-123", }); }); test("resolveOwner returns the owning accountId, or null when absent", async () => { const found = fakeSession([{ get: () => "acc-b" }]); assert.equal(await resolveOwner(found.session, "d1", "beagle-investors"), "acc-b"); const missing = fakeSession([]); assert.equal(await resolveOwner(missing.session, "d1", "no-such"), null); }); test("listResources returns only the account's resources of a kind", async () => { const { session, calls } = fakeSession([ { get: (k: string) => ({ name: "gls-leads", cfResourceId: "db-1" } as Record)[k] }, ]); const rows = await listResources(session, "acc-a", "d1"); assert.deepEqual(rows, [ { accountId: "acc-a", kind: "d1", name: "gls-leads", cfResourceId: "db-1" }, ]); assert.match( calls[0].cypher, /MATCH \(r:StorageResource \{accountId: \$accountId, kind: \$kind\}\)/, ); assert.deepEqual(calls[0].params, { accountId: "acc-a", kind: "d1" }); });