diff --git a/prototypes/reference-preview/DESIGN.md b/prototypes/reference-preview/DESIGN.md deleted file mode 100644 index e2428f1..0000000 --- a/prototypes/reference-preview/DESIGN.md +++ /dev/null @@ -1,40 +0,0 @@ -# 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 deleted file mode 100644 index eee5bfd..0000000 --- a/prototypes/reference-preview/decision.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "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 deleted file mode 100644 index 7e6c19c..0000000 --- a/prototypes/reference-preview/fixtures/noop.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "revision": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "upstream": [], - "current": [], - "previous": [] -} diff --git a/prototypes/reference-preview/prototype.mjs b/prototypes/reference-preview/prototype.mjs deleted file mode 100644 index 372199e..0000000 --- a/prototypes/reference-preview/prototype.mjs +++ /dev/null @@ -1,181 +0,0 @@ -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 deleted file mode 100644 index b22af7d..0000000 --- a/prototypes/reference-preview/prototype.test.mjs +++ /dev/null @@ -1,166 +0,0 @@ -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")) -}) diff --git a/prototypes/runtime-availability/DESIGN.md b/prototypes/runtime-availability/DESIGN.md deleted file mode 100644 index e34c1f0..0000000 --- a/prototypes/runtime-availability/DESIGN.md +++ /dev/null @@ -1,37 +0,0 @@ -# Per-capability runtime availability - -## User problem - -A host picker currently joins several exports to label the capabilities it can use. A service can have several capabilities, each with different library support. - -## Contract - -Each entry retains its ID and discovery capability order. A capability carries a descriptor for a reference-only entry, a runtime definition, or protocol helpers. Definitions identify the relevant export and key. Helper descriptors identify helper names and include the native webhook event subset when available. - -Library availability describes static implementation coverage. The host owns configuration, credential validation, account permissions, routing, scheduling, and health checks. - -## Examples - -| Capability | Runtime | -| --- | --- | -| Linear MCP | Definition in `connectors` | -| Linear webhook | Native verification for the events in `webhooks.linear.events` | -| Linear API and GitHub CLI | Reference only | -| Generic signed webhook | Verification in `triggers` | -| Schedule | Host-owned scheduling | -| Discord channel | Interaction verification and reply helpers | -| Discord webhook listing | Reference only | - -Discord's interaction implementation belongs to its channel. A host may cross-link that channel when it displays the webhook listing. - -## Compatibility - -The prototype preserves every discovery tuple, including unrecognized future capabilities. Consumers can handle such descriptors as reference only. Existing runtime maps keep their declarations and package subpaths. Native event subsets track the public definitions, so behavior changes remain reviewable in the export that owns them. - -## Alternatives - -A separate export keeps the discovery entry compact and lets hosts opt into the additional import cost. Embedding descriptors in generated entries makes lookups simpler but adds bytes and declaration changes to every catalog consumer. A pure helper with supplied maps keeps imports explicit at the cost of extra host wiring. A generated companion can avoid loading runtime modules while deriving membership from the same projections. - -## Recommendation - -Prototype a separate lightweight export against a real host picker and measure its bundle cost. A production follow-up should derive descriptors from generation, cover the public declaration and event-subset behavior, and handle unknown capabilities conservatively. diff --git a/prototypes/runtime-availability/contract.ts b/prototypes/runtime-availability/contract.ts deleted file mode 100644 index 77aba83..0000000 --- a/prototypes/runtime-availability/contract.ts +++ /dev/null @@ -1,37 +0,0 @@ -type ReferenceOnly = { readonly type: "reference-only" } -type Definition = { - readonly type: "definition" - readonly export: Name - readonly key: string -} -type ProtocolHelper = { - readonly type: "protocol-helper" - readonly export: Name - readonly key: string - readonly helpers: readonly string[] -} & (Name extends "webhooks" ? { readonly events: readonly string[] } : { readonly events?: never }) - -export type CapabilityRuntime = - | { readonly kind: "provider"; readonly surface: "inference"; readonly runtime: ReferenceOnly | Definition<"providers"> } - | { readonly kind: "connector"; readonly surface: "mcp"; readonly runtime: ReferenceOnly | Definition<"connectors"> } - | { readonly kind: "connector"; readonly surface: "api" | "cli"; readonly runtime: ReferenceOnly } - | { readonly kind: "trigger"; readonly surface: "schedule"; readonly runtime: ReferenceOnly } - | { readonly kind: "trigger"; readonly surface: "webhook"; readonly runtime: ReferenceOnly | ProtocolHelper<"triggers"> | ProtocolHelper<"webhooks"> } - | { readonly kind: "channel"; readonly surface: "channel"; readonly runtime: ReferenceOnly | ProtocolHelper<"channels"> } - -export type EntryRuntime = { - readonly id: string - readonly capabilities: readonly CapabilityRuntime[] -} - -export const examples = { - id: "linear", - capabilities: [ - { kind: "connector", surface: "mcp", runtime: { type: "definition", export: "connectors", key: "linear" } }, - { kind: "connector", surface: "api", runtime: { type: "reference-only" } }, - { kind: "trigger", surface: "webhook", runtime: { - type: "protocol-helper", export: "webhooks", key: "linear", helpers: ["verifyNativeWebhook"], - events: ["Issue.create", "Issue.update"], - } }, - ], -} as const satisfies EntryRuntime diff --git a/prototypes/runtime-availability/decision.json b/prototypes/runtime-availability/decision.json deleted file mode 100644 index 597803f..0000000 --- a/prototypes/runtime-availability/decision.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "outcome": "propose-production-plan", - "reason": "A host picker can label definition and helper coverage without repeating the mapping between discovery capabilities and runtime exports.", - "openQuestions": [ - "Should runtime membership be generated in a separate lightweight export?", - "How should a future channel advertise helper names for its own protocol?", - "Should hosts request a single descriptor by ID to limit bundle costs?" - ] -} diff --git a/prototypes/runtime-availability/prototype.mjs b/prototypes/runtime-availability/prototype.mjs deleted file mode 100644 index 106f7fb..0000000 --- a/prototypes/runtime-availability/prototype.mjs +++ /dev/null @@ -1,56 +0,0 @@ -import { realpathSync } from "node:fs" -import { pathToFileURL } from "node:url" -import { catalog } from "@checkfu/integrations/catalog" -import { channels } from "@checkfu/integrations/channels" -import { connectors } from "@checkfu/integrations/connectors" -import { providers } from "@checkfu/integrations/providers" -import { triggers } from "@checkfu/integrations/triggers" -import { webhooks } from "@checkfu/integrations/webhooks" - -export const publicMaps = { channels, connectors, providers, triggers, webhooks } - -const own = (map, key) => Object.hasOwn(map, key) ? map[key] : undefined -const definition = (name, key) => ({ type: "definition", export: name, key }) -const helpers = (name, key, names) => ({ type: "protocol-helper", export: name, key, helpers: names }) -const channelHelpers = { - "discord-interactions": ["verifyDiscordInteraction", "discordReplyRequest"], -} - -function runtimeFor(id, { kind, surface }, maps) { - if (kind === "provider" && surface === "inference" && own(maps.providers, id)) { - return definition("providers", id) - } - if (kind === "connector" && surface === "mcp" && own(maps.connectors, id)) { - return definition("connectors", id) - } - if (kind === "trigger" && surface === "webhook") { - const native = own(maps.webhooks, id) - if (native !== undefined) { - const names = native.setup === "challenge" - ? ["verifyNativeWebhook", "readNotionChallenge"] - : ["verifyNativeWebhook"] - return { ...helpers("webhooks", id, names), events: [...native.events] } - } - if (own(maps.triggers, id)) return helpers("triggers", id, ["verifyWebhookDelivery"]) - } - if (kind === "channel" && surface === "channel") { - const configured = own(maps.channels, id) - const names = own(channelHelpers, configured?.channel.protocol) - if (names !== undefined) return helpers("channels", id, [...names]) - } - return { type: "reference-only" } -} - -export function availabilityFor(entry, runtimeMaps) { - return { - id: entry.id, - capabilities: entry.capabilities.map(capability => ({ - ...capability, - runtime: runtimeFor(entry.id, capability, runtimeMaps), - })), - } -} - -if (process.argv[1] && pathToFileURL(realpathSync(process.argv[1])).href === import.meta.url) { - console.log(JSON.stringify(catalog.map(entry => availabilityFor(entry, publicMaps)), null, 2)) -} diff --git a/prototypes/runtime-availability/prototype.test.mjs b/prototypes/runtime-availability/prototype.test.mjs deleted file mode 100644 index eff465a..0000000 --- a/prototypes/runtime-availability/prototype.test.mjs +++ /dev/null @@ -1,66 +0,0 @@ -import assert from "node:assert/strict" -import { readFileSync } from "node:fs" -import { test } from "node:test" -import { catalog } from "@checkfu/integrations/catalog" -import { availabilityFor, publicMaps } from "./prototype.mjs" - -const reference = { type: "reference-only" } -const runtime = (id, kind, surface) => { - const entry = catalog.find(candidate => candidate.id === id) - const capability = availabilityFor(entry, publicMaps).capabilities.find(candidate => - candidate.kind === kind && candidate.surface === surface) - assert.ok(capability, `${id} ${kind}/${surface}`) - return capability.runtime -} - -test("matches discovery capabilities against actual definitions and protocol helpers", () => { - assert.deepEqual(runtime("openai", "provider", "inference"), - { type: "definition", export: "providers", key: "openai" }) - assert.deepEqual(runtime("google-gemini", "provider", "inference"), reference) - assert.deepEqual(runtime("linear", "connector", "mcp"), - { type: "definition", export: "connectors", key: "linear" }) - assert.deepEqual(runtime("linear", "connector", "api"), reference) - assert.deepEqual(runtime("linear", "trigger", "webhook"), { - type: "protocol-helper", export: "webhooks", key: "linear", helpers: ["verifyNativeWebhook"], - events: publicMaps.webhooks.linear.events, - }) - assert.deepEqual(runtime("github", "connector", "cli"), reference) - assert.deepEqual(runtime("discord", "trigger", "webhook"), reference) - assert.deepEqual(runtime("discord", "channel", "channel"), { - type: "protocol-helper", export: "channels", key: "discord", - helpers: ["verifyDiscordInteraction", "discordReplyRequest"], - }) - assert.deepEqual(runtime("webhook", "trigger", "webhook"), { - type: "protocol-helper", export: "triggers", key: "webhook", helpers: ["verifyWebhookDelivery"], - }) - assert.deepEqual(runtime("schedule", "trigger", "schedule"), reference) -}) - -test("extends map membership without a vendor registry and ignores inherited keys", () => { - const capabilities = [{ kind: "connector", surface: "mcp" }] - const future = { id: "future", capabilities } - const maps = { ...publicMaps, connectors: { ...publicMaps.connectors, future: { name: "Future connector" } } } - assert.deepEqual(availabilityFor(future, publicMaps).capabilities[0].runtime, reference) - assert.deepEqual(availabilityFor(future, maps).capabilities[0].runtime, - { type: "definition", export: "connectors", key: "future" }) - assert.deepEqual(availabilityFor({ id: "toString", capabilities }, maps).capabilities[0].runtime, reference) -}) - -test("preserves every discovery tuple without mutating catalog or runtime definitions", () => { - const original = structuredClone({ catalog, publicMaps }) - const descriptors = catalog.map(entry => availabilityFor(entry, publicMaps)) - assert.deepEqual(descriptors.map(({ id, capabilities }) => ({ - id, capabilities: capabilities.map(({ kind, surface }) => ({ kind, surface })), - })), catalog.map(({ id, capabilities }) => ({ id, capabilities }))) - const copy = descriptors.find(entry => entry.id === "linear").capabilities - .find(({ kind }) => kind === "trigger").runtime.events - assert.notStrictEqual(copy, publicMaps.webhooks.linear.events) - assert.deepEqual({ catalog, publicMaps }, original) -}) - -test("records the prototype decision", () => { - const decision = JSON.parse(readFileSync(new URL("./decision.json", import.meta.url), "utf8")) - assert.ok(["propose-production-plan", "defer"].includes(decision.outcome)) - assert.ok(decision.reason.trim()) - assert.ok(Array.isArray(decision.openQuestions) && decision.openQuestions.every(question => typeof question === "string")) -}) diff --git a/research/github-webhook-rotation/REPORT.md b/research/github-webhook-rotation/REPORT.md deleted file mode 100644 index 090db73..0000000 --- a/research/github-webhook-rotation/REPORT.md +++ /dev/null @@ -1,21 +0,0 @@ -# GitHub webhook receipt identity during signing-secret rotation - -## Observed code behavior - -The verifier authenticates the raw body and returns its verified MAC as the receipt ID. The synthetic probe authenticates the same body with two generated keys. Reusing a key produces the same receipt ID. Changing the signing key produces a different receipt ID. Changing unsigned delivery and event headers leaves the authenticated result unchanged. - -## Provider evidence - -GitHub documents how the signing secret and payload determine the MAC. Its redelivery guidance says the delivery header is retained. The REST reference describes editing webhook settings and redelivering a delivery. These sources leave the signing key for historical redeliveries after rotation unspecified. [Validating deliveries](https://docs.github.com/en/webhooks/using-webhooks/validating-webhook-deliveries) · [Redelivery header](https://docs.github.com/en/webhooks/using-webhooks/best-practices-for-using-webhooks#use-the-x-github-delivery-header) · [Webhook REST reference](https://docs.github.com/en/rest/repos/webhooks) - -## Decision - -Provider behavior is inconclusive. Keep the existing receipt ID. The offline result establishes how this verifier would behave if an identical payload arrived under a different signing key. - -## Compatibility - -Hosts can persist the current signature-derived ID under a binding and provider namespace. A later identity migration would need to account for both legacy and new IDs over the host's replay-store retention window. A body-only digest could merge distinct deliveries with identical bytes. A design for different IDs should establish that behavior explicitly and calculate any candidate ID after authentication. The unsigned delivery header can help correlate observations. - -## Next experiment - -With separate authorization, use a disposable repository and webhook. Observe the same historical delivery before and after changing the test signing secret. Compare raw body equality and which key authenticates each attempt, then record whether the verified receipt remains the same. Record outcomes and provider scope without keeping secrets, signatures, or payloads in the report. diff --git a/research/github-webhook-rotation/evidence.json b/research/github-webhook-rotation/evidence.json deleted file mode 100644 index a91e39a..0000000 --- a/research/github-webhook-rotation/evidence.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "plannedAt": "19a98ac", - "providerStatus": "inconclusive", - "codeFacts": { - "sameSecretSameId": true, - "differentSecretDifferentId": true, - "unsignedHeadersDoNotChangeId": true - }, - "sources": [ - { - "url": "https://docs.github.com/en/webhooks/using-webhooks/validating-webhook-deliveries", - "retrievedAt": "2026-11-30", - "supports": "GitHub computes its signature from the payload and the signing secret." - }, - { - "url": "https://docs.github.com/en/webhooks/using-webhooks/best-practices-for-using-webhooks#use-the-x-github-delivery-header", - "retrievedAt": "2026-11-30", - "supports": "GitHub documents reuse of the delivery header on a redelivery." - }, - { - "url": "https://docs.github.com/en/rest/repos/webhooks#redeliver-a-delivery-for-a-repository-webhook", - "retrievedAt": "2026-11-30", - "supports": "GitHub exposes a redelivery operation and a separate operation for editing the webhook configuration." - } - ], - "providerEvidence": "The sources describe signing, configuration, and redelivery independently. They leave the key used for historical redelivery after a secret change unspecified.", - "recommendation": "Retain authenticated receipt IDs and qualify the redelivery assumption until a disposable, authorized observation resolves the provider behavior.", - "liveExperimentPerformed": false -} diff --git a/research/github-webhook-rotation/reproduce.mjs b/research/github-webhook-rotation/reproduce.mjs deleted file mode 100644 index cf9ba5d..0000000 --- a/research/github-webhook-rotation/reproduce.mjs +++ /dev/null @@ -1,36 +0,0 @@ -import { createHmac, randomBytes } from "node:crypto" -import { realpathSync } from "node:fs" -import { pathToFileURL } from "node:url" -import { verifyNativeWebhook } from "@checkfu/integrations/webhooks" - -export async function characterizeRotation() { - const firstKey = randomBytes(32).toString("base64url") - const secondKey = randomBytes(32).toString("base64url") - const body = Buffer.from(JSON.stringify({ - action: "opened", issue: { number: 1 }, repository: { id: 42 }, - })) - const sign = key => new Headers({ - "x-hub-signature-256": "sha256=" + createHmac("sha256", key).update(body).digest("hex"), - "x-github-delivery": "synthetic-delivery", - "x-github-event": "issues", - }) - const verify = (key, headers) => verifyNativeWebhook("github", body, headers, key) - const before = await verify(firstKey, sign(firstKey)) - const repeated = await verify(firstKey, sign(firstKey)) - const rekeyed = await verify(secondKey, sign(secondKey)) - const changedHeaders = sign(firstKey) - changedHeaders.set("x-github-delivery", "different-synthetic-delivery") - changedHeaders.set("x-github-event", "pull_request") - const changed = await verify(firstKey, changedHeaders) - const allAuthenticated = [before, repeated, rekeyed, changed].every(receipt => receipt.type === "event") - return { - allAuthenticated, - sameSecretSameId: allAuthenticated && before.id === repeated.id, - differentSecretDifferentId: allAuthenticated && before.id !== rekeyed.id, - unsignedHeadersDoNotChangeId: allAuthenticated && before.id === changed.id && before.event === changed.event, - } -} - -if (process.argv[1] && pathToFileURL(realpathSync(process.argv[1])).href === import.meta.url) { - console.log(JSON.stringify(await characterizeRotation())) -} diff --git a/research/github-webhook-rotation/reproduce.test.mjs b/research/github-webhook-rotation/reproduce.test.mjs deleted file mode 100644 index c691d45..0000000 --- a/research/github-webhook-rotation/reproduce.test.mjs +++ /dev/null @@ -1,34 +0,0 @@ -import assert from "node:assert/strict" -import { readFileSync } from "node:fs" -import { test } from "node:test" -import { characterizeRotation } from "./reproduce.mjs" - -test("authenticated GitHub receipt identity depends on the signing key", async () => { - assert.deepEqual(await characterizeRotation(), { - allAuthenticated: true, - sameSecretSameId: true, - differentSecretDifferentId: true, - unsignedHeadersDoNotChangeId: true, - }) -}) - -test("the evidence packet separates provider observations from offline code facts", async () => { - const packet = JSON.parse(readFileSync(new URL("./evidence.json", import.meta.url), "utf8")) - const { allAuthenticated, ...facts } = await characterizeRotation() - assert.equal(allAuthenticated, true) - assert.deepEqual(packet.codeFacts, facts) - assert.match(packet.plannedAt, /^[a-f0-9]{7,40}$/u) - assert.ok(["inconclusive", "confirmed-rekeys", "confirmed-preserves"].includes(packet.providerStatus)) - assert.equal(packet.liveExperimentPerformed, false) - assert.ok(packet.providerEvidence.trim()) - assert.ok(packet.recommendation.trim()) - assert.ok(packet.sources.length > 0) - for (const { url, retrievedAt, supports } of packet.sources) { - assert.equal(new URL(url).origin, "https://docs.github.com") - assert.match(retrievedAt, /^\d{4}-\d{2}-\d{2}$/u) - assert.ok(supports.trim()) - } - if (packet.providerStatus !== "inconclusive") { - assert.ok(packet.sources.some(({ supports }) => supports.startsWith("Direct evidence of historical redelivery after a secret change:"))) - } -})