Skip to content
Merged
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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
51 changes: 15 additions & 36 deletions scripts/import-reference.mjs
Original file line number Diff line number Diff line change
@@ -1,46 +1,25 @@
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"
if (!checkout || !/^[a-f0-9]{40}$/u.test(revision)) {
throw new Error("Usage: bun run import:reference <reference checkout> [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}`)
143 changes: 143 additions & 0 deletions scripts/reference-import.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
}
13 changes: 7 additions & 6 deletions test/reference-import.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading