From 7850fb9017160f159ceef0cd8e2197993bb4696e Mon Sep 17 00:00:00 2001 From: Andrew Lee <5784515+andyrewlee@users.noreply.github.com> Date: Mon, 30 Nov 2026 12:53:58 -0800 Subject: [PATCH] Reconcile reference updates before catalog writes --- README.md | 2 + scripts/import-reference.mjs | 51 +++------- scripts/reference-import.mjs | 143 ++++++++++++++++++++++++++++ test/reference-import.test.mjs | 13 +-- test/reference-update.test.mjs | 169 +++++++++++++++++++++++++++++++++ 5 files changed, 336 insertions(+), 42 deletions(-) create mode 100644 test/reference-update.test.mjs diff --git a/README.md b/README.md index ba2e03d..f8b3db2 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,8 @@ Edit one YAML file per service or provider. Start with [Linear](catalog/services Run `bun run import:reference /path/to/reference-checkout` to reproduce the import from the pinned revision. Supply a full commit SHA as a second argument to update the source revision, then review the changed definitions and regenerate the exports. +The importer checks every candidate before writing. A removed upstream entry or a collision with a local ID stops the import. Resolve the affected entries in a separate catalog change. An upstream display-name change follows the source when the local name matches its old source name. Local name overrides are preserved. Keep the old Git objects available when names differ so the importer can tell the two cases apart. + Reference settings describe per-connection values such as a region, tenant host, or account identifier. Related caveats describe limits in the reference definition. Hosts supply the values and implement the corresponding setup. Generation and import check credential fields, HTTPS endpoint templates, and event verifier definitions. An invalid definition reports the field that needs attention. These checks establish structure. Vendor compatibility and credential permissions require separate verification. diff --git a/scripts/import-reference.mjs b/scripts/import-reference.mjs index 8d4ea11..507ee15 100644 --- a/scripts/import-reference.mjs +++ b/scripts/import-reference.mjs @@ -1,8 +1,5 @@ -import { execFileSync } from "node:child_process" -import { readFile, writeFile } from "node:fs/promises" -import { Document, parseDocument } from "yaml" -import { readDefinition, validateReference } from "./catalog-yaml.mjs" -import { projectReference } from "./reference-import.mjs" +import { writeFile } from "node:fs/promises" +import { planReferenceUpdate, readReferenceInputs } from "./reference-import.mjs" const checkout = process.argv[2] const revision = process.argv[3] ?? "0621be370cd4d86c32c310390df03f5a64b1a105" @@ -10,37 +7,19 @@ if (!checkout || !/^[a-f0-9]{40}$/u.test(revision)) { throw new Error("Usage: bun run import:reference [full commit SHA]") } -const git = (...args) => execFileSync("git", ["-C", checkout, ...args], { encoding: "utf8" }) -const tree = git("ls-tree", "-r", "--name-only", revision, "catalog/checked", "catalog/providers") -const files = tree.trim().split("\n").sort() +const catalog = new URL("../catalog/", import.meta.url) +const { changes, conflicts, notices } = planReferenceUpdate(await readReferenceInputs({ + checkout, revision, catalog, +})) -for (const sourceFolder of ["checked", "providers"]) { - if (!files.some(path => path.startsWith(`catalog/${sourceFolder}/`) && path.endsWith(".yaml"))) { - throw new Error(`No reference YAML found in catalog/${sourceFolder} at ${revision}`) +if (conflicts.length > 0) { + for (const { folder, file, code, runtime } of conflicts) { + console.error(`catalog/${folder}/${file} ${code}${runtime ? " (runtime overlay)" : ""}`) } + console.error("Resolve the reference conflicts in a reviewed catalog change before rerunning the import.") + process.exitCode = 1 +} else { + await Promise.all(changes.map(({ folder, file, contents }) => + writeFile(new URL(`${folder}/${file}`, catalog), contents))) + console.log(`Imported ${changes.length} changed definitions from ${revision}. Preserved ${notices.length} local names.`) } - -const imports = [] -for (const path of files) { - const [, sourceFolder, file] = path.split("/") - if (!path.endsWith(".yaml") || file === undefined) continue - const input = readDefinition(file, git("show", `${revision}:${path}`)) - const folder = sourceFolder === "checked" ? "services" : "providers" - const reference = projectReference(input, { revision, path, folder, file }) - validateReference(reference, folder, file) - - const target = new URL(`../catalog/${folder}/${file}`, import.meta.url) - const current = await readFile(target, "utf8").catch(error => { - if (error.code === "ENOENT") return null - throw error - }) - const document = current === null - ? new Document({ format: 1, id: input.id, name: input.name }) - : parseDocument(current) - if (current !== null) readDefinition(file, current) - document.set("reference", reference) - imports.push([target, document.toString({ lineWidth: 100 })]) -} - -await Promise.all(imports.map(([target, contents]) => writeFile(target, contents))) -console.log(`Imported ${imports.length} definitions from ${revision}`) diff --git a/scripts/reference-import.mjs b/scripts/reference-import.mjs index 5eb4860..a6461e1 100644 --- a/scripts/reference-import.mjs +++ b/scripts/reference-import.mjs @@ -22,3 +22,146 @@ export function projectReference(input, { revision, path, folder }) { sources, } } +import { execFileSync, spawnSync } from "node:child_process" +import { readdir, readFile } from "node:fs/promises" +import { Document, parseDocument } from "yaml" +import { readDefinition, validateReference } from "./catalog-yaml.mjs" + +const folders = ["providers", "services"] +const fileName = /^[a-z][a-z0-9-]*\.yaml$/u +const fullRevision = /^[0-9a-f]{40}$/u +const keyFor = ({ folder, file }) => `${folder}/${file}` + + +function indexRecords(records, label) { + const paths = new Map() + const files = new Map() + for (const record of records) { + const { folder, file, input } = record + if (!folders.includes(folder) || !fileName.test(file) || + (input !== undefined && file !== `${input.id}.yaml`)) { + throw new Error(`Invalid ${label} catalog record`) + } + const key = keyFor(record) + if (files.has(file)) throw new Error(`Duplicate ${label} catalog id or path at ${key}`) + paths.set(key, record) + files.set(file, record) + } + return { paths, files } +} + +function parseDefinition(record, source) { + try { + return readDefinition(record.file, source) + } catch { + throw new Error(`${keyFor(record)}: expected a valid YAML definition matching its filename`) + } +} + +function checkReference(reference, record) { + try { + validateReference(reference, record.folder, record.file) + } catch (error) { + throw new Error(`${keyFor(record)}: ${error.message}`, { cause: error }) + } +} + +export function planReferenceUpdate({ upstream, current, previous }) { + const incoming = indexRecords(upstream, "upstream").paths + const local = indexRecords(current, "local") + const old = indexRecords(previous, "previous").paths + const changes = [] + const conflicts = [] + const notices = [] + + const inventory = [...new Set([...incoming.keys(), ...local.paths.keys()])].sort() + for (const key of inventory) { + const next = incoming.get(key) + const existing = local.paths.get(key) + const definition = existing === undefined ? undefined : parseDefinition(existing, existing.source) + if (definition?.reference !== undefined) checkReference(definition.reference, existing) + + if (next === undefined) { + if (definition.reference !== undefined) { + const { folder, file } = existing + const runtime = folder === "services" + ? Object.hasOwn(definition, "surfaces") + : Object.hasOwn(definition, "endpoints") || Object.hasOwn(definition, "auth") + conflicts.push({ code: "removed-reference", folder, file, runtime }) + } + continue + } + + const { folder, file, input } = next + const reference = projectReference(input, next) + checkReference(reference, next) + const sameId = local.files.get(file) + if ((definition !== undefined && definition.reference === undefined) || + (existing === undefined && sameId !== undefined && sameId.folder !== folder)) { + conflicts.push({ code: "local-id-collision", folder, file, existingFolder: sameId.folder }) + continue + } + + const document = existing === undefined + ? new Document({ format: 1, id: input.id, name: input.name }) + : parseDocument(existing.source) + if (definition !== undefined && definition.name !== input.name) { + const previousName = old.get(key)?.input.name + if (previousName === undefined) { + conflicts.push({ code: "previous-name-unavailable", folder, file }) + continue + } + if (definition.name === previousName) document.set("name", input.name) + else notices.push({ code: "local-name-preserved", folder, file }) + } + document.set("reference", reference) + const contents = document.toString({ lineWidth: 100 }) + if (contents !== existing?.source) { + changes.push({ folder, file, action: existing === undefined ? "add" : "update", contents }) + } + } + return { changes, conflicts, notices } +} + +/** Read the committed upstream and local snapshots without changing either checkout. */ +export async function readReferenceInputs({ checkout, revision, catalog }) { + if (!checkout || !fullRevision.test(revision)) throw new Error("Expected a reference checkout and full commit SHA") + const git = (...args) => execFileSync("git", ["-C", checkout, ...args], { encoding: "utf8" }) + const sourceFolders = { checked: "services", providers: "providers" } + const tree = git("ls-tree", "-rz", "--name-only", revision, "catalog/checked", "catalog/providers") + const upstream = tree.split("\0").filter(path => path.endsWith(".yaml")).sort().map(path => { + const [, source, file, extra] = path.split("/") + const folder = sourceFolders[source] + if (extra !== undefined || folder === undefined || !fileName.test(file)) { + throw new Error("Upstream YAML must have a catalog folder and an ID filename") + } + return { folder, file, path, revision, input: parseDefinition({ folder, file }, git("show", `${revision}:${path}`)) } + }) + for (const folder of folders) { + if (!upstream.some(record => record.folder === folder)) throw new Error(`No upstream YAML for ${folder} at ${revision}`) + } + const current = (await Promise.all(folders.map(async folder => { + const directory = new URL(`${folder}/`, catalog) + const files = (await readdir(directory)).filter(file => file.endsWith(".yaml")).sort() + return Promise.all(files.map(async file => ({ + folder, file, source: await readFile(new URL(file, directory), "utf8"), + }))) + }))).flat() + const incoming = indexRecords(upstream, "upstream").paths + const previous = [] + for (const record of current) { + const candidate = incoming.get(keyFor(record)) + if (candidate === undefined) continue + const definition = parseDefinition(record, record.source) + const { reference } = definition + if (reference === undefined || definition.name === candidate.input.name) continue + checkReference(reference, record) + const result = spawnSync("git", ["-C", checkout, "show", `${reference.revision}:${reference.path}`], + { encoding: "utf8" }) + if (result.error !== undefined) throw result.error + if (result.status === 0) { + previous.push({ folder: record.folder, file: record.file, input: parseDefinition(record, result.stdout) }) + } + } + return { upstream, current, previous } +} diff --git a/test/reference-import.test.mjs b/test/reference-import.test.mjs index 31714ee..87704f9 100644 --- a/test/reference-import.test.mjs +++ b/test/reference-import.test.mjs @@ -70,15 +70,16 @@ test("the CLI preserves the runtime overlay and emits deterministic YAML", async "catalog/providers/model.yaml": provider("model"), }) const revision = commit() - await writeFiles(destination, { - "catalog/services/regional.yaml": [ - "format: 1", "id: regional", "name: Regional service", - "# Keep the runtime endpoint.", "surfaces:", " mcp:", " url: https://runtime.example.com/mcp", "", - ].join("\n"), - }) const first = runImport(revision) assert.equal(first.status, 0, first.stderr) const catalog = join(destination, "catalog") + const initial = (await snapshot(catalog))["services/regional.yaml"] + await writeFiles(catalog, { + "services/regional.yaml": initial.replace(/^reference:/mu, [ + "# Keep the runtime endpoint.", "surfaces:", " mcp:", " url: https://runtime.example.com/mcp", "reference:", + ].join("\n")), + }) + assert.equal(runImport(revision).status, 0) const contents = await snapshot(catalog) const yaml = contents["services/regional.yaml"] assert.match(yaml, /^# Keep the runtime endpoint\.$/mu) diff --git a/test/reference-update.test.mjs b/test/reference-update.test.mjs new file mode 100644 index 0000000..2227892 --- /dev/null +++ b/test/reference-update.test.mjs @@ -0,0 +1,169 @@ +import assert from "node:assert/strict" +import { rm } from "node:fs/promises" +import { join } from "node:path" +import { test } from "node:test" +import { parse, stringify } from "yaml" +import { planReferenceUpdate, projectReference } from "../scripts/reference-import.mjs" +import { + inputRecord, provider, service, snapshot, withReferenceFixture, writeFiles, +} from "./fixtures/reference-import/fixture.mjs" + +const revision = "b".repeat(40) +const managed = (record, overlay = {}) => ({ + folder: record.folder, + file: record.file, + source: stringify({ + format: 1, id: record.input.id, name: record.input.name, ...overlay, + reference: projectReference(record.input, record), + }, { lineWidth: 100 }), +}) +const change = (id, name) => inputRecord(service(id, name), revision) + +test("plans sorted additions and metadata updates, skips identical files, and does not mutate inputs", () => { + const unchanged = inputRecord(service("unchanged")) + const before = inputRecord(service("updated")) + const update = change("updated") + update.input.surfaces.mcp.url = "https://example.com/mcp/v2" + const inputs = { + upstream: [unchanged, update, change("added")], + current: [managed(unchanged), managed(before)], + previous: [], + } + const original = structuredClone(inputs) + const { changes, conflicts, notices } = planReferenceUpdate(inputs) + assert.deepEqual(changes.map(({ folder, file, action }) => [folder, file, action]), [ + ["services", "added.yaml", "add"], ["services", "updated.yaml", "update"], + ]) + assert.equal(parse(changes[1].contents).reference.surfaces.mcp.url, update.input.surfaces.mcp.url) + assert.deepEqual(conflicts, []) + assert.deepEqual(notices, []) + assert.deepEqual(inputs, original) +}) + +test("rejects duplicate paths and IDs before planning", () => { + const duplicate = inputRecord(service("one")) + const providerCollision = inputRecord(provider("one"), revision, "providers") + for (const upstream of [[duplicate, duplicate], [duplicate, providerCollision]]) { + assert.throws(() => planReferenceUpdate({ upstream, current: [], previous: [] }), /Duplicate upstream/u) + } + assert.throws(() => planReferenceUpdate({ + upstream: [], current: [managed(duplicate), managed(duplicate)], previous: [], + }), /Duplicate local/u) +}) + +test("reports removals, possible renames, and local ID collisions", () => { + const old = inputRecord(service("old", "Same name")) + const collision = inputRecord(service("collision")) + const localOnly = { folder: "services", file: collision.file, source: stringify(collision.input) } + const independent = inputRecord(service("independent")) + const current = [ + localOnly, + { folder: independent.folder, file: independent.file, source: stringify(independent.input) }, + managed(old, { surfaces: { mcp: { url: "https://local.example.com/mcp" } } }), + managed(inputRecord(provider("gone"), revision, "providers")), + ] + const plan = planReferenceUpdate({ upstream: [change("replacement", "Same name"), collision], current, previous: [] }) + assert.deepEqual(plan.conflicts, [ + { code: "removed-reference", folder: "providers", file: "gone.yaml", runtime: false }, + { code: "local-id-collision", folder: "services", file: "collision.yaml", existingFolder: "services" }, + { code: "removed-reference", folder: "services", file: "old.yaml", runtime: true }, + ]) + assert.deepEqual(plan.changes.map(({ action, file }) => [action, file]), [["add", "replacement.yaml"]]) +}) + +test("uses previous names to follow the source or preserve an override", () => { + const before = inputRecord(service("renamed", "Old upstream")) + const next = change("renamed", "New upstream") + const update = current => planReferenceUpdate({ upstream: [next], current: [current], previous: [before] }) + assert.equal(parse(update(managed(before)).changes[0].contents).name, "New upstream") + const override = update(managed(before, { name: "Local name" })) + assert.equal(parse(override.changes[0].contents).name, "Local name") + assert.deepEqual(override.notices, [{ code: "local-name-preserved", folder: "services", file: "renamed.yaml" }]) + const unavailable = planReferenceUpdate({ upstream: [next], current: [managed(before)], previous: [] }) + assert.deepEqual(unavailable.changes, []) + assert.deepEqual(unavailable.conflicts, [{ code: "previous-name-unavailable", folder: "services", file: "renamed.yaml" }]) + const matching = planReferenceUpdate({ upstream: [next], current: [managed(before, { name: next.input.name })], previous: [] }) + assert.deepEqual(matching.conflicts, []) +}) + +const checkedPath = id => `catalog/checked/${id}.yaml` +const providerPath = "catalog/providers/model.yaml" +const localPath = id => `services/${id}.yaml` + +test("the writing CLI follows upstream names, preserves local overlays and comments, and is byte-stable", async () => { + await withReferenceFixture(async ({ checkout, destination, commit, runImport }) => { + await writeFiles(checkout, { + [checkedPath("tracked")]: service("tracked", "Original name"), + [checkedPath("override")]: service("override", "Upstream label"), + [providerPath]: provider("model"), + }) + const first = runImport(commit()) + assert.equal(first.status, 0, first.stderr) + const catalog = join(destination, "catalog") + const initial = await snapshot(catalog) + await writeFiles(catalog, { + [localPath("tracked")]: initial[localPath("tracked")].replace(/^reference:/mu, [ + "# Runtime definition stays here.", "surfaces:", " mcp:", " url: https://runtime.example.com/mcp", "reference:", + ].join("\n")), + [localPath("override")]: initial[localPath("override")].replace("name: Upstream label", "name: Local label # Keep this label."), + [localPath("independent")]: service("independent"), + }) + await writeFiles(checkout, { + [checkedPath("tracked")]: service("tracked", "Updated name"), + [checkedPath("override")]: service("override", "Updated upstream"), + [checkedPath("added")]: service("added"), + }) + const next = commit() + const imported = runImport(next) + assert.equal(imported.status, 0, imported.stderr) + assert.match(imported.stdout, /Preserved 1 local names/u) + const output = await snapshot(catalog) + const tracked = output[localPath("tracked")] + assert.match(tracked, /^# Runtime definition stays here\.$/mu) + assert.equal(parse(tracked).name, "Updated name") + assert.equal(parse(tracked).surfaces.mcp.url, "https://runtime.example.com/mcp") + assert.match(output[localPath("override")], /name: Local label # Keep this label\./u) + assert.equal(parse(output[localPath("added")]).reference.revision, next) + assert.equal(parse(output[localPath("independent")]).reference, undefined) + const repeat = runImport(next) + assert.equal(repeat.status, 0, repeat.stderr) + assert.match(repeat.stdout, /Imported 0 changed definitions/u) + assert.deepEqual(await snapshot(catalog), output) + }) +}) + +test("the writing CLI performs zero writes on removals, local collisions, and invalid later records", async () => { + await withReferenceFixture(async ({ checkout, destination, commit, runImport }) => { + await writeFiles(checkout, { + [checkedPath("alpha")]: service("alpha"), + [checkedPath("removed")]: service("removed"), + [providerPath]: provider("model"), + }) + assert.equal(runImport(commit()).status, 0) + const catalog = join(destination, "catalog") + await writeFiles(catalog, { [localPath("collision")]: service("collision") }) + const before = await snapshot(catalog) + await rm(join(checkout, checkedPath("removed"))) + await writeFiles(checkout, { + [checkedPath("alpha")]: service("alpha", "Changed"), + [checkedPath("collision")]: service("collision"), + }) + const conflict = runImport(commit()) + assert.notEqual(conflict.status, 0) + assert.match(conflict.stderr, /services\/removed\.yaml removed-reference/u) + assert.match(conflict.stderr, /services\/collision\.yaml local-id-collision/u) + assert.deepEqual(await snapshot(catalog), before) + + await rm(join(checkout, checkedPath("collision"))) + const malformed = service("z-last") + malformed.surfaces.mcp.url = "http://example.com" + await writeFiles(checkout, { + [checkedPath("removed")]: service("removed"), + [checkedPath("z-last")]: malformed, + }) + const invalid = runImport(commit()) + assert.notEqual(invalid.status, 0) + assert.match(invalid.stderr, /services\/z-last\.yaml: reference\.surfaces\.mcp\.url/u) + assert.deepEqual(await snapshot(catalog), before) + }) +})