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
40 changes: 40 additions & 0 deletions prototypes/reference-preview/DESIGN.md
Original file line number Diff line number Diff line change
@@ -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 <full-commit-sha> --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.
8 changes: 8 additions & 0 deletions prototypes/reference-preview/decision.json
Original file line number Diff line number Diff line change
@@ -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?"
]
}
6 changes: 6 additions & 0 deletions prototypes/reference-preview/fixtures/noop.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"revision": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"upstream": [],
"current": [],
"previous": []
}
181 changes: 181 additions & 0 deletions prototypes/reference-preview/prototype.mjs
Original file line number Diff line number Diff line change
@@ -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
}
}
Loading