diff --git a/prototypes/reference-preview/DESIGN.md b/prototypes/reference-preview/DESIGN.md new file mode 100644 index 0000000..e2428f1 --- /dev/null +++ b/prototypes/reference-preview/DESIGN.md @@ -0,0 +1,40 @@ +# Read-only reference import preview + +## Review workflow + +Run the preview against an existing checkout and a full reference commit SHA. Review endpoint, credential-schema, and capability changes. Resolve conflicts in a separate catalog change, then rerun the preview against the same SHA. + +## Output contract + +JSON contains the revision, sorted changes, conflicts, and notices. A change includes its folder, ID, action, and sorted structural fields grouped by purpose. Text shows the same information. Exit status 0 means the comparison succeeded, 2 means it found unresolved conflicts, and 1 means it could not compare the inputs. + +## Examples + +```text +update services/example + endpoints: reference.surfaces.mcp.url + credential-schema: reference.credentials.token.fields.0.label +services/retired removed-reference +``` + +Run a no-op fixture with `node prototypes/reference-preview/prototype.mjs --fixture prototypes/reference-preview/fixtures/noop.json --json`. For a local review, use `--checkout /path/to/reference --revision --json`. + +## Read-only guarantee + +The preview reads local catalog files and committed Git objects. It uses the same comparison as the writing importer. It has no writer, network step, or generator. Tests compare recursive file hashes before and after both a no-op and a conflicting review. + +## Privacy + +The report contains identifiers, field paths, structural conflict details, and opt-in review dates. Candidate YAML, template values, endpoint values, and payloads stay out of output. Invalid input produces a short error so parser excerpts stay private. + +## Source-age semantics + +Provide both `--as-of YYYY-MM-DD` and `--max-age-days N`. Age is the difference between UTC calendar days. Equality with the threshold is recent. A date after the given day is future-dated. These dates document source review and carry no live health claim. + +## Integration proposal + +A production dry-run mode could share the importer's arguments and comparison, then stop before the writer. A standalone review command leaves the writer's interface smaller. Either approach can preserve the same conflict exit status for both text and JSON. + +## Recommendation + +Try the prototype on a real catalog review, then design a production entrypoint around the existing plan object. Keep output limited to structural paths and leave conflict resolution to the reviewer. diff --git a/prototypes/reference-preview/decision.json b/prototypes/reference-preview/decision.json new file mode 100644 index 0000000..eee5bfd --- /dev/null +++ b/prototypes/reference-preview/decision.json @@ -0,0 +1,8 @@ +{ + "outcome": "propose-production-plan", + "reason": "A deterministic structural preview can surface changes and conflicts before the writing importer runs.", + "openQuestions": [ + "Which structural field groups are most useful in day-to-day catalog review?", + "Should the production interface keep text and JSON output in the importer or expose a standalone command?" + ] +} diff --git a/prototypes/reference-preview/fixtures/noop.json b/prototypes/reference-preview/fixtures/noop.json new file mode 100644 index 0000000..7e6c19c --- /dev/null +++ b/prototypes/reference-preview/fixtures/noop.json @@ -0,0 +1,6 @@ +{ + "revision": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "upstream": [], + "current": [], + "previous": [] +} diff --git a/prototypes/reference-preview/prototype.mjs b/prototypes/reference-preview/prototype.mjs new file mode 100644 index 0000000..372199e --- /dev/null +++ b/prototypes/reference-preview/prototype.mjs @@ -0,0 +1,181 @@ +import { readFile } from "node:fs/promises" +import { realpathSync } from "node:fs" +import { resolve, sep } from "node:path" +import { pathToFileURL } from "node:url" +import { parseArgs } from "node:util" +import { parse } from "yaml" +import { planReferenceUpdate, readReferenceInputs } from "../../scripts/reference-import.mjs" + +const groups = ["endpoints", "credential-schema", "capabilities", "settings", "provenance", "other"] +const keyFor = ({ folder, file }) => `${folder}/${file}` +const valuesOf = value => value !== null && typeof value === "object" +const pathLabel = key => /^(?:[a-zA-Z][a-zA-Z0-9_-]{0,63}|[0-9]{1,6})$/u.test(key) ? key : "[field]" + +function pathsOf(before, after, prefix = "") { + if (Object.is(before, after)) return [] + if (prefix === "reference" && before === undefined) before = {} + if (valuesOf(before) && valuesOf(after) && Array.isArray(before) === Array.isArray(after)) { + const keys = [...new Set([...Object.keys(before), ...Object.keys(after)])].sort() + return keys.flatMap(key => pathsOf( + Object.hasOwn(before, key) ? before[key] : undefined, + Object.hasOwn(after, key) ? after[key] : undefined, + prefix === "" ? pathLabel(key) : `${prefix}.${pathLabel(key)}`, + )) + } + return [prefix] +} + +function groupFor(path) { + if (/^reference\.(?:revision|path|sources)(?:\.|$)/u.test(path)) return "provenance" + if (/^reference\.(?:settings|gaps)(?:\.|$)/u.test(path)) return "settings" + if (/^reference\.credentials(?:\.|$)|\.(?:accepts|send)(?:\.|$)/u.test(path)) return "credential-schema" + if (/\.(?:url|base|base_url|discover|authorization_url|token_url|description)$/u.test(path) && + path !== "description") return "endpoints" + if (/^(?:reference\.)?(?:surfaces|speaks|models|endpoints|auth)(?:\.|$)/u.test(path)) return "capabilities" + return "other" +} + +function summarizeFields(before, after) { + const fields = Object.fromEntries(groups.map(group => [group, []])) + for (const path of [...new Set(pathsOf(before, after))].sort()) fields[groupFor(path)].push(path) + return fields +} + +const millisecondsPerDay = 86_400_000 +function utcDay(value) { + if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/u.test(value)) { + throw new Error("Expected a UTC calendar date") + } + const parsed = new Date(`${value}T00:00:00.000Z`) + if (!Number.isFinite(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== value) { + throw new Error("Expected a valid UTC calendar date") + } + return parsed.getTime() / millisecondsPerDay +} + +function sourceAgeFor(upstream, { asOf, maxAgeDays }) { + const day = utcDay(asOf) + if (!Number.isFinite(maxAgeDays) || maxAgeDays < 0) throw new Error("Expected a nonnegative review-age threshold") + const sources = [...upstream].sort((left, right) => { + const a = keyFor(left) + const b = keyFor(right) + return a < b ? -1 : a > b ? 1 : 0 + }).flatMap(({ folder, file, input }) => + Object.keys(input.sources).sort().map(section => { + const { read } = input.sources[section] + const ageDays = day - utcDay(read) + const status = ageDays < 0 ? "future-dated" : ageDays > maxAgeDays ? "older-than-threshold" : "recent" + return { folder, file, section: pathLabel(section), read, ageDays, status } + })) + return { asOf, maxAgeDays, sources } +} + +export function previewReferenceUpdate(inputs, { revision, age } = {}) { + if (typeof revision !== "string" || !/^[a-f0-9]{40}$/u.test(revision)) { + throw new Error("Expected a full reference revision") + } + if (inputs.upstream.some(record => record.revision !== revision)) { + throw new Error("Upstream records must match the reviewed revision") + } + const plan = planReferenceUpdate(inputs) + const local = new Map(inputs.current.map(record => [keyFor(record), record.source])) + const changes = plan.changes.map(({ folder, file, action, contents }) => { + const source = local.get(keyFor({ folder, file })) + return { + folder, + id: file.slice(0, -5), + action, + fields: summarizeFields(source === undefined ? {} : parse(source), parse(contents)), + } + }) + const conflicts = plan.conflicts.map(({ folder, file, code, runtime, existingFolder }) => ({ + folder, + id: file.slice(0, -5), + code, + ...(runtime === undefined ? {} : { runtime }), + ...(existingFolder === undefined ? {} : { existingFolder }), + })) + const notices = plan.notices.map(({ folder, file, code }) => ({ folder, id: file.slice(0, -5), code })) + return { + revision, + changes, + conflicts, + notices, + ...(age === undefined ? {} : { sourceAge: sourceAgeFor(inputs.upstream, age) }), + } +} + +function renderText(report) { + const lines = [ + `Reference ${report.revision}`, + `${report.changes.length} changes, ${report.conflicts.length} conflicts, ${report.notices.length} notices`, + ] + for (const { folder, id, action, fields } of report.changes) { + lines.push(`${action} ${folder}/${id}`) + for (const group of groups) { + if (fields[group].length > 0) lines.push(` ${group}: ${fields[group].join(", ")}`) + } + } + for (const { folder, id, code } of [...report.conflicts, ...report.notices]) { + lines.push(`${folder}/${id} ${code}`) + } + if (report.sourceAge !== undefined) { + const { asOf, maxAgeDays, sources } = report.sourceAge + lines.push(`Source review age as of ${asOf} with a ${maxAgeDays}-day threshold`) + for (const { folder, file, section, read, ageDays, status } of sources) { + lines.push(`${folder}/${file} ${section} ${read} ${ageDays} days ${status}`) + } + } + return lines.join("\n") +} + +async function main() { + const { values } = parseArgs({ options: { + fixture: { type: "string" }, + checkout: { type: "string" }, + revision: { type: "string" }, + catalog: { type: "string" }, + json: { type: "boolean" }, + "as-of": { type: "string" }, + "max-age-days": { type: "string" }, + } }) + const asOf = values["as-of"] + const threshold = values["max-age-days"] + let age + if (asOf !== undefined || threshold !== undefined) { + if (asOf === undefined || threshold === undefined || threshold.trim() === "") { + throw new Error("Both review-age options are required") + } + age = { asOf, maxAgeDays: Number(threshold) } + } + + let inputs + let revision + if (values.fixture !== undefined) { + if (values.checkout !== undefined || values.revision !== undefined || values.catalog !== undefined) { + throw new Error("Choose either a fixture or the local checkout") + } + const { revision: fixtureRevision, ...records } = JSON.parse(await readFile(values.fixture, "utf8")) + inputs = records + revision = fixtureRevision + } else { + const catalog = values.catalog === undefined + ? new URL("../../catalog/", import.meta.url) + : pathToFileURL(resolve(values.catalog) + sep) + revision = values.revision + inputs = await readReferenceInputs({ checkout: values.checkout, revision, catalog }) + } + const report = previewReferenceUpdate(inputs, { revision, age }) + console.log(values.json ? JSON.stringify(report, null, 2) : renderText(report)) + return report.conflicts.length === 0 ? 0 : 2 +} + +if (process.argv[1] && pathToFileURL(realpathSync(process.argv[1])).href === import.meta.url) { + try { + process.exitCode = await main() + } catch { + // YAML/parser failures can contain raw input. Keep diagnostics private. + console.error("Preview failed. Check the arguments, catalog structure, and available Git objects.") + process.exitCode = 1 + } +} diff --git a/prototypes/reference-preview/prototype.test.mjs b/prototypes/reference-preview/prototype.test.mjs new file mode 100644 index 0000000..b22af7d --- /dev/null +++ b/prototypes/reference-preview/prototype.test.mjs @@ -0,0 +1,166 @@ +import assert from "node:assert/strict" +import { spawnSync } from "node:child_process" +import { createHash, randomUUID } from "node:crypto" +import { readdir, readFile, readlink, rm } from "node:fs/promises" +import { join, relative } from "node:path" +import { test } from "node:test" +import { fileURLToPath } from "node:url" +import { stringify } from "yaml" +import { projectReference } from "../../scripts/reference-import.mjs" +import { inputRecord, provider, service, withReferenceFixture, writeFiles } from "../../test/fixtures/reference-import/fixture.mjs" +import { previewReferenceUpdate } from "./prototype.mjs" + +const earlier = "a".repeat(40) +const revision = "b".repeat(40) +const script = fileURLToPath(new URL("./prototype.mjs", import.meta.url)) +const fixture = fileURLToPath(new URL("./fixtures/noop.json", import.meta.url)) +const run = (...args) => spawnSync(process.execPath, [script, ...args], { encoding: "utf8" }) + +function local(record, name = record.input.name) { + return { + folder: record.folder, + file: record.file, + source: stringify({ + format: 1, id: record.input.id, name, reference: projectReference(record.input, record), + }, { lineWidth: 100 }), + } +} + +function example(sentinel) { + const old = inputRecord(service("example", "Previous name"), earlier) + const next = inputRecord(service("example", "New upstream name"), revision) + next.input.surfaces.mcp.url = "https://example.com/new-endpoint" + next.input.surfaces.mcp.accepts[0].send = { header: "Authorization", value: sentinel } + next.input.credentials.secret.fields[0].label = "New token label" + const removed = inputRecord(service("removed"), earlier) + const unresolved = inputRecord(service("unresolved", "Original"), earlier) + const colliding = inputRecord(service("collision"), revision) + return { + upstream: [next, inputRecord(service("added"), revision), inputRecord(service("unresolved", "Renamed"), revision), colliding], + current: [ + local(old, "Local name"), local(removed), local(unresolved), + { folder: colliding.folder, file: colliding.file, source: stringify(colliding.input) }, + ], + previous: [old], + } +} + +test("reports structural fields and every conflict without candidate values", () => { + const sentinel = "fixture-value-" + randomUUID() + const inputs = example(sentinel) + const report = previewReferenceUpdate(inputs, { revision }) + assert.deepEqual(report.changes.map(({ id, action }) => [id, action]), [["added", "add"], ["example", "update"]]) + const fields = report.changes[1].fields + assert.deepEqual(fields.endpoints, ["reference.surfaces.mcp.url"]) + assert.deepEqual(fields["credential-schema"], [ + "reference.credentials.secret.fields.0.label", "reference.surfaces.mcp.accepts.0.send", + ]) + assert.deepEqual(report.conflicts.map(({ id, code }) => [id, code]), [ + ["collision", "local-id-collision"], ["removed", "removed-reference"], ["unresolved", "previous-name-unavailable"], + ]) + assert.deepEqual(report.notices, [{ folder: "services", id: "example", code: "local-name-preserved" }]) + assert.equal(Object.hasOwn(report, "sourceAge"), false) + const serialized = JSON.stringify(report) + for (const value of [sentinel, "https://example.com/new-endpoint", "Local name", "contents"]) { + assert.equal(serialized.includes(value), false) + } +}) + +test("source review age uses validated whole UTC calendar dates and an explicit threshold", () => { + const input = service("dates") + const section = read => ({ read, from: ["https://docs.example.com"] }) + input.sources = { + older: section("2024-02-28"), recent: section("2024-02-29"), future: section("2024-03-02"), + } + const inputs = { upstream: [inputRecord(input, revision)], current: [], previous: [] } + const age = { asOf: "2024-03-01", maxAgeDays: 1 } + const report = previewReferenceUpdate(inputs, { revision, age }) + assert.deepEqual(report.sourceAge.sources.map(({ section, ageDays, status }) => [section, ageDays, status]), [ + ["future", -1, "future-dated"], ["older", 2, "older-than-threshold"], ["recent", 1, "recent"], + ]) + for (const invalid of [ + { ...age, asOf: "2023-02-29" }, { ...age, asOf: "2024-3-01" }, { ...age, asOf: undefined }, + { ...age, maxAgeDays: -1 }, { ...age, maxAgeDays: Infinity }, { ...age, maxAgeDays: undefined }, + ]) assert.throws(() => previewReferenceUpdate(inputs, { revision, age: invalid }), /UTC|threshold/u) + input.sources.older.read = "2024-02-30" + assert.throws(() => previewReferenceUpdate(inputs, { revision, age }), /valid UTC calendar date/u) +}) + +async function hashes(directory) { + const entries = await readdir(directory, { recursive: true, withFileTypes: true }) + const files = await Promise.all(entries.map(async entry => { + const path = join(entry.parentPath, entry.name) + const name = relative(directory, path) + if (entry.isSymbolicLink()) return [name, "link:" + await readlink(path)] + if (entry.isFile()) return [name, createHash("sha256").update(await readFile(path)).digest("hex")] + return [name, "directory"] + })) + return Object.fromEntries(files) +} + +test("CLI fixture mode has deterministic safe output and explicit exit statuses", async () => { + const noop = run("--fixture", fixture, "--json") + assert.equal(noop.status, 0, noop.stderr) + assert.deepEqual(JSON.parse(noop.stdout), { revision: earlier, changes: [], conflicts: [], notices: [] }) + assert.equal(run("--fixture", fixture, "--as-of", "2024-03-01", "--json").status, 1) + assert.equal(run("--fixture", fixture, "--max-age-days", "1").status, 1) + const dated = run("--fixture", fixture, "--as-of", "2024-03-01", "--max-age-days", "1", "--json") + assert.equal(dated.status, 0, dated.stderr) + assert.deepEqual(JSON.parse(dated.stdout).sourceAge, { asOf: "2024-03-01", maxAgeDays: 1, sources: [] }) + await withReferenceFixture(async ({ destination }) => { + const sentinel = "fixture-value-" + randomUUID() + await writeFiles(destination, { "input.json": JSON.stringify({ revision, ...example(sentinel) }) }) + const path = join(destination, "input.json") + const json = run("--fixture", path, "--json") + const text = run("--fixture", path) + assert.equal(json.status, 2, json.stderr) + assert.equal(text.status, 2, text.stderr) + assert.ok(JSON.parse(json.stdout).conflicts.length > 0) + assert.match(text.stdout, /services\/removed removed-reference/u) + assert.equal(run("--fixture", path, "--json").stdout, json.stdout) + for (const output of [json.stdout, json.stderr, text.stdout, text.stderr]) assert.equal(output.includes(sentinel), false) + assert.equal(run("--fixture", join(destination, "missing.json")).status, 1) + await writeFiles(destination, { "invalid.json": `invalid input ${sentinel}` }) + const invalid = run("--fixture", join(destination, "invalid.json")) + assert.equal(invalid.status, 1) + assert.equal((invalid.stdout + invalid.stderr).includes(sentinel), false) + }) +}) + +test("local mode leaves both repository trees byte-identical", async () => { + await withReferenceFixture(async ({ checkout, destination, commit, runImport }) => { + await writeFiles(checkout, { + "catalog/checked/keep.yaml": service("keep"), + "catalog/checked/removed.yaml": service("removed"), + "catalog/providers/model.yaml": provider("model"), + }) + const first = commit() + assert.equal(runImport(first).status, 0) + const args = ["--checkout", checkout, "--catalog", join(destination, "catalog"), "--json", "--revision"] + const beforeDestination = await hashes(destination) + const beforeCheckout = await hashes(checkout) + const noop = run(...args, first) + assert.equal(noop.status, 0, noop.stderr) + assert.deepEqual(JSON.parse(noop.stdout).changes, []) + assert.deepEqual(await hashes(destination), beforeDestination) + assert.deepEqual(await hashes(checkout), beforeCheckout) + + await rm(join(checkout, "catalog/checked/removed.yaml")) + const next = commit() + const conflictCheckout = await hashes(checkout) + const conflict = run(...args, next) + assert.equal(conflict.status, 2, conflict.stderr) + assert.deepEqual(JSON.parse(conflict.stdout).conflicts, [ + { folder: "services", id: "removed", code: "removed-reference", runtime: false }, + ]) + assert.deepEqual(await hashes(destination), beforeDestination) + assert.deepEqual(await hashes(checkout), conflictCheckout) + }) +}) + +test("records the design decision", async () => { + const data = JSON.parse(await readFile(new URL("./decision.json", import.meta.url), "utf8")) + assert.ok(["propose-production-plan", "defer"].includes(data.outcome)) + assert.ok(data.reason.trim()) + assert.ok(Array.isArray(data.openQuestions) && data.openQuestions.every(question => typeof question === "string")) +})