Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
25ded9f
Plan native JSON Schema comparisons and shared-reference collections
daveshanley Nov 25, 2026
6c4aa65
Render native schema comparisons in full and lite HTML reports
daveshanley Nov 25, 2026
c8957b5
Embed the JSON Schema icon in offline reports
daveshanley Nov 25, 2026
c631939
Compare standalone JSON Schemas across commands and revision history
daveshanley Nov 25, 2026
4b58ac2
Document standalone JSON Schema inputs, policies and report identity
daveshanley Nov 25, 2026
0d77339
Pin the native JSON Schema report components
daveshanley Nov 25, 2026
9f8b59a
Follow schema collection references to their authored edits
daveshanley Nov 25, 2026
27d0ed4
Keep the legacy history API explicit about its supported formats
daveshanley Nov 25, 2026
62fbe14
Compare schema directory snapshots and resolve shared definitions acr…
daveshanley Nov 25, 2026
bd302e7
Document shared-reference collection comparisons and source navigation
daveshanley Nov 25, 2026
0ead3a2
Bundle the schema-aware reference renderer from its pinned revision
daveshanley Nov 25, 2026
90b0207
Keep every target of a shared schema reference site
daveshanley Nov 25, 2026
f0ee521
Pin and verify the one-sided schema source contract
daveshanley Nov 25, 2026
97326b7
Build the CLI against the public native schema modules
daveshanley Nov 25, 2026
8520324
Show the schema or collection root in the console tree
daveshanley Nov 25, 2026
ae265e3
Exercise collection base overrides through the report command
daveshanley Nov 25, 2026
2ba1a84
Identify the selected schema file and side in console source views
daveshanley Nov 25, 2026
01e7928
Disambiguate collection members by their source filename in the tree
daveshanley Nov 25, 2026
5599392
Verify both file panes for moved and one-sided schema changes
daveshanley Nov 25, 2026
c11f4cb
Select marked schemas without building a second syntax tree
daveshanley Nov 25, 2026
b61b857
Show local and referenced edits together in schema reports
daveshanley Nov 25, 2026
c92cf51
Pin schema comparisons with bounded validation allocations
daveshanley Nov 25, 2026
134f7bd
Keep distinct native schema dependency edits in CLI reports
daveshanley Nov 26, 2026
3a1d731
Explain unrecognized inputs and stray collection files in schema comp…
daveshanley Nov 26, 2026
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
53 changes: 50 additions & 3 deletions .ai-docs/bilingual-comparison.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# OpenAPI and AsyncAPI comparisons
# Document and schema comparisons

One command family supports OpenAPI and AsyncAPI 3.x. `model.ParseSpecification`
One command family supports OpenAPI, AsyncAPI 3.x, and standalone JSON Schema Draft 2020-12. `model.ParseSpecification`
uses libopenapi's strict YAML/JSON parser once, checks the root version marker,
and transfers the parsed AsyncAPI tree to libasyncapi. Mixed formats, ambiguous
markers, unsupported AsyncAPI versions and partial AsyncAPI models fail clearly.
Expand All @@ -19,7 +19,7 @@ available; `Commit.AllChanges` selects the additive neutral report when present.

Existing unscoped rule files remain OpenAPI-only. A combined file has optional
`openapiRules`, `asyncapiRules`, and `schemaRules` sections. The last section
configures JSON Schemas embedded in AsyncAPI; it does not change OpenAPI policy.
configures standalone JSON Schemas and schemas embedded in AsyncAPI; it does not change OpenAPI policy.
Unknown sections are rejected. Rules are merged into fresh defaults. The CLI's
shared breakingrules lock covers the entire delegated comparison and restores
defaults afterwards, including comparisons without a custom policy.
Expand Down Expand Up @@ -102,3 +102,50 @@ on dispatch/policy/history, and command smoke checks. Compare
`BenchmarkOpenAPIReport` against the base branch with the same Go toolchain and
hardware; use `-benchmem` and multiple samples. The model-window test verifies
that 30 adjacent revisions parse once each and retain at most two idle models.

## Standalone JSON Schema

All five commands accept Draft 2020-12 JSON Schemas. A root with the supported `$schema` declaration selects
this engine automatically. `--schema` also accepts unmarked JSON and YAML objects, `true`, and `false`.
Both sides must have the same native format. Unsupported dialects, unresolved references, duplicate resource IDs,
and unsupported dynamic references return errors with source details.

`model.ParseInput` and `HistoryWindow.AcquireInput` carry a single native model through direct comparisons and history.
The Git and GitHub loaders give each schema its revision filesystem. Equal root bytes can still have different
referenced content. The global `schemaRules` policy lock covers the native comparison. Explicit property rules
override the default widening and narrowing classification. `libasyncapi` continues to compare embedded payloads.

A schema change has a defining `schemaResource`, a resource-relative JSONPath, and available source locations in
`context.originalDocument` and `context.modifiedDocument`. Matched resources carry both filenames, including when a file moves.
Line and column coordinates identify only the sides where the edited value exists. The console and HTML views
use the filenames for source lookup. The schema hash uses semantic fields, including the resource, so line movement alone
does not change it. The root source is stored once per side. Additional files use the optional `originalSources`
and `modifiedSources` report maps. Renderers request those source views while the result is pinned. Flat reports
retain change values and copied coordinates. The console keeps per-file line tables in its bounded result cache.

For the Customer fixture, the required-list addition has `path = $.required`, `property = required`, and `new = id`.
The human reports show the Customer title, and the flat report groups by its canonical resource ID.
`markdown-report --include-diff` includes the physical file pair that owns the edit.

## JSON Schema collections

`cmd.comparisonMode` selects a direct comparison when both arguments are local directories and `--schema` is set.
The existing repository and file path form selects local Git history. The one-URL GitHub history form is unchanged.

The directory loader enumerates regular `.json`, `.yaml`, and `.yml` files, including uppercase extensions,
using slash-separated relative names. It skips symlinks, `node_modules`, and dot-directories such as `.git`. Every
other member is read as a schema, so a directory should hold schemas only. The library registers every member before
resolving references and matching resources by ID, then by relative file and embedded pointer. Either directory may
be empty. A malformed member aborts that direct comparison with its side and filename. When that member has no
Draft 2020-12 `$schema` declaration, the error also says it does not look like a JSON Schema.

Two directories without `--schema` still select local Git history. That loader reports both arguments as
directories and suggests `--schema`.

A collection produces one report item. The graph has a `Schemas` root. Source lookup keys are the physical member
names, and change paths are local to the resource in `schemaResource`. The summary, compact counts, and Markdown
use the same resource-aware identity as the console and the HTML views. `--include-diff` includes one unified
diff per changed file pair. A moved resource can have different original and modified filenames.

Selecting a reference site in either HTML report shows edits authored at the site and in the definitions reached
through its unchanged references. A changed `$ref` or `$dynamicRef` shows the edit to that keyword at its source.
3 changes: 2 additions & 1 deletion .ai-docs/compact-report.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# Compact Markdown reports

`markdown-report --compact` compares two direct inputs and writes a short report.
Inputs can be files, URLs, or git revision paths. Repository history is not
Inputs can be files, URLs, or git revision paths for OpenAPI, AsyncAPI, or JSON Schema.
Use `--schema` for unmarked Draft 2020-12 inputs or a pair of local schema directories. Repository history is not
supported in this mode. `--include-diff` cannot be used with `--compact`.

Example:
Expand Down
14 changes: 13 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Public documentation:

## What This Repo Is

`openapi-changes` is a Go CLI for comparing OpenAPI specifications across:
`openapi-changes` is a Go CLI for comparing OpenAPI, AsyncAPI 3.x, and JSON Schema Draft 2020-12 documents across:

- direct left/right file, URL, or git-revision comparison
- local git history for a file in a repository
Expand Down Expand Up @@ -62,6 +62,7 @@ All `cmd/` implementation files use their canonical names (e.g., `cmd/summary.go

### Machine-readable JSON

- Standalone schema edits carry a resource-relative `path` and a `schemaResource`. Include both in count and hash identity.
- `report` should emit semantic `path` values whenever possible.
- If semantic normalization rewrites an engine path, preserve the original path in `rawPath`.
- Parameter identity must not depend on array index positions when a stable semantic name exists.
Expand Down Expand Up @@ -124,6 +125,17 @@ All `cmd/` implementation files use their canonical names (e.g., `cmd/summary.go
- The residual `tui/` package still exists in-repo, but it is not the canonical console implementation. The canonical console is `tui/v2/` (Bubbletea).
- **Dependency version sensitivity**: `doctor` and `libopenapi` version bumps can silently change comparison output, count semantics, or tree structure. After upgrading either dependency, always re-run the petstore regression fixtures and verify counts match expectations.

## JSON Schema inputs

`model.ParseInput` dispatches the parsed document by its native format. The shared `--schema` flag enables
unmarked schemas, including booleans. `libopenapi/jsonschema` owns schema resources and reference resolution.
Doctor attaches edits to its native schema graph. The CLI uses the same report and console paths as the API formats.
Use `sample-specs/json-schema/{before,after}/customer.json` to check one breaking addition at `$.required`.

With `--schema`, two local directories select a direct collection comparison. A repository and a file path still select file history.
Use `sample-specs/json-schema/collections/{before,after}` to verify one edit at `$.properties.currency.minLength` in `money.json`,
two incoming references, and source selection in both the console and the offline HTML report.

## Regression Fixtures

Use these files whenever you change semantics, counts, report rendering, or UI payload shape:
Expand Down
33 changes: 32 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

## The world's **_most powerful and complete_** OpenAPI diff tool.

`openapi-changes` lets you inspect what changed in an OpenAPI or AsyncAPI 3.x specification between two files,
`openapi-changes` lets you inspect what changed in an OpenAPI, AsyncAPI 3.x, or JSON Schema Draft 2020-12 document between two files,
between git revisions of the same file, across local git history, or directly from a GitHub-hosted file URL.

It can render the same semantic change model as:
Expand All @@ -24,6 +24,37 @@ It works well for local exploration, CI/CD checks, release notes, and API review

---

## Compare JSON Schemas

Supply a pair of schemas to any of the five commands. A Draft 2020-12 `$schema` declaration selects the schema engine.
Pass `--schema` for an unmarked object or boolean.

```sh
openapi-changes summary sample-specs/json-schema/before/customer.json sample-specs/json-schema/after/customer.json
openapi-changes report --schema HEAD~1:schemas/customer.yaml HEAD:schemas/customer.yaml
```

The Customer example adds `id` to `required`. The report records one breaking change at `$.required`.
The `schemaResource` field identifies the defining schema. The console and the offline HTML report open the source
that owns the change, including referenced files. Use the `schemaRules` configuration section for schema policy.

### Compare schema collections

Pass two local directories with `--schema`. The CLI reads JSON and YAML files recursively and registers each
resource before resolving references. It skips symbolic links, `node_modules`, and any directory whose name starts
with a dot. Every other JSON or YAML file is read as a schema, so keep the directory to schemas only. An empty
directory is a valid snapshot.

```sh
openapi-changes html-report --schema --report-file changes.html \
sample-specs/json-schema/collections/before sample-specs/json-schema/collections/after
```

Order and Invoice both reference Money in this example. Raising the minimum currency length from 2 to 3 produces
one breaking change at `$.properties.currency.minLength`. The graph shows both references. The source view
opens line 9 of `money.json`. Run the same pair with `report` for JSON or `markdown-report --include-diff`
for the file diff.

## AsyncAPI has landed

Event-driven APIs break too. They just do it quietly, in a consumer nobody remembers subscribing to that topic.
Expand Down
8 changes: 4 additions & 4 deletions cmd/asyncapi_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -173,11 +173,11 @@ func TestAsyncAPIAllReports(t *testing.T) {
require.Len(t, items, 1)
require.Contains(t, items[0].HtmlReport, `icon="channel"`)
require.Contains(t, items[0].HtmlReport, `id="channels"`)
ctr, root, release, err := bridgeRunChangerator(commits[0], nil)
comparison, err := bridgeRunChangerator(commits[0], nil)
require.NoError(t, err)
require.NotNil(t, root)
defer release()
require.Len(t, ctr.DeduplicateChanges(), 2)
require.NotNil(t, comparison.Root)
defer comparison.Release()
require.Len(t, comparison.Changerator.DeduplicateChanges(), 2)
}

func TestAsyncAPIUnchangedHistoryWithMalformedRevision(t *testing.T) {
Expand Down
51 changes: 35 additions & 16 deletions cmd/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const (

// summaryOpts holds the flags shared by the current doctor-based command family.
type summaryOpts struct {
schema bool
rules *model.ComparisonRules
noColor bool
tektronix bool
Expand Down Expand Up @@ -111,6 +112,7 @@ func readCommonFlags(cmd *cobra.Command) (opts summaryOpts, configFlag string, e
opts.limitTime, _ = cmd.Flags().GetInt("limit-time")
opts.base, _ = cmd.Flags().GetString("base")
opts.baseCommit, _ = cmd.Flags().GetString("base-commit")
opts.schema, _ = cmd.Flags().GetBool("schema")
opts.remote, _ = cmd.Flags().GetBool("remote")
opts.extRefs, _ = cmd.Flags().GetBool("ext-refs")
opts.globalRevisions, _ = cmd.Flags().GetBool("global-revisions")
Expand Down Expand Up @@ -222,27 +224,42 @@ func prepareCommandRun(
}, nil
}

// loadCommitsFromArgs dispatches to the appropriate commit loader based on argument types.
// Expects len(args) to be 1 or 2 (caller must validate arg count).
func loadCommitsFromArgs(args []string, opts summaryOpts, breakingConfig *whatChangedModel.BreakingRulesConfig) ([]*model.Commit, error) {
type inputMode uint8

const (
directInputs inputMode = iota
schemaDirectories
localHistory
githubHistory
)

// comparisonMode distinguishes a directory pair from the repository/file form used by history.
func comparisonMode(args []string, schema bool) inputMode {
if len(args) == 1 {
return loadGitHubCommits(args[0], opts, breakingConfig)
}
if isHTTPURL(args[0]) {
return loadLeftRightCommits(args[0], args[1], opts)
return githubHistory
}
if _, _, ok := parseGitRef(args[0]); ok {
return loadLeftRightCommits(args[0], args[1], opts)
if len(args) != 2 || isHTTPURL(args[0]) {
return directInputs
}
f, statErr := os.Stat(args[0])
if statErr == nil && f.IsDir() {
return loadGitHistoryCommits(args[0], args[1], opts, breakingConfig)
first, err := os.Stat(args[0])
if err != nil || !first.IsDir() {
return directInputs
}
if _, _, ok := parseGitRef(args[1]); ok {
return loadLeftRightCommits(args[0], args[1], opts)
if schema {
Comment thread
daveshanley marked this conversation as resolved.
Resolved
second, err := os.Stat(args[1])
if err == nil && second.IsDir() {
return schemaDirectories
}
}
if statErr != nil {
return nil, fmt.Errorf("cannot open file/repository: '%s'", args[0])
return localHistory
}

func loadCommitsFromArgs(args []string, opts summaryOpts, breakingConfig *whatChangedModel.BreakingRulesConfig) ([]*model.Commit, error) {
switch comparisonMode(args, opts.schema) {
case githubHistory:
return loadGitHubCommits(args[0], opts, breakingConfig)
case localHistory:
return loadGitHistoryCommits(args[0], args[1], opts, breakingConfig)
}
return loadLeftRightCommits(args[0], args[1], opts)
}
Expand All @@ -263,6 +280,8 @@ func printCommandUsage(commandName, description string, palette terminal.Palette
fmt.Println()
fmt.Println("Examples:")
fmt.Printf(" %s\n", cmdStyle.Render("openapi-changes "+commandName+" ./specs/old.yaml ./specs/new.yaml"))
fmt.Printf(" %s\n", cmdStyle.Render("openapi-changes "+commandName+" --schema before/customer.json after/customer.json"))
fmt.Printf(" %s\n", cmdStyle.Render("openapi-changes "+commandName+" --schema before/schemas after/schemas"))
fmt.Printf(" %s\n", cmdStyle.Render("openapi-changes "+commandName+" HEAD~1:openapi.yaml ./openapi.yaml"))
fmt.Printf(" %s\n", cmdStyle.Render("openapi-changes "+commandName+" https://github.com/user/repo/blob/main/openapi.yaml"))
fmt.Printf(" %s\n", cmdStyle.Render("openapi-changes "+commandName+" /path/to/git/repo path/to/openapi.yaml"))
Expand Down
3 changes: 2 additions & 1 deletion cmd/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,15 @@ import (
"testing"

"github.com/pb33f/doctor/terminal"
"github.com/spf13/cobra"
"github.com/pb33f/testify/assert"
"github.com/pb33f/testify/require"
"github.com/spf13/cobra"
)

// testRootCmd creates a root command with standard persistent flags and a subcommand for testing.
func testRootCmd(sub *cobra.Command, args ...string) *cobra.Command {
root := &cobra.Command{Use: "openapi-changes"}
root.PersistentFlags().Bool("schema", false, "")
root.PersistentFlags().BoolP("no-logo", "b", false, "")
root.PersistentFlags().BoolP("top", "t", false, "")
root.PersistentFlags().IntP("limit", "l", 5, "")
Expand Down
16 changes: 11 additions & 5 deletions cmd/compact_report.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import (
// compactOutcome is written only after a complete direct comparison.
// Counts use the same semantic identity as the human summary.
type compactOutcome struct {
async bool
label string
Total int `json:"total"`
Breaking int `json:"breaking"`
}
Expand All @@ -31,7 +31,9 @@ func generateCompactMarkdown(commits []*model.Commit, config *whatChangedModel.B
return nil, outcome, errors.New("compact report requires one complete direct comparison")
}
result, err := runChangerator(commits[0], config)
outcome.async = commits[0].APILabel() == "AsyncAPI"
if label := commits[0].APILabel(); label != "OpenAPI" {
outcome.label = label
}
if err != nil {
return nil, outcome, err
}
Expand Down Expand Up @@ -75,8 +77,8 @@ func generateCompactMarkdown(commits []*model.Commit, config *whatChangedModel.B
func renderCompactMarkdown(outcome compactOutcome, highlights []string) []byte {
var sb strings.Builder
label := "OpenAPI"
if outcome.async {
label = "AsyncAPI"
if outcome.label != "" {
label = outcome.label
}
sb.WriteString("## " + label + " changes\n\n")
switch {
Expand All @@ -97,7 +99,11 @@ func renderCompactMarkdown(outcome compactOutcome, highlights []string) []byte {
}
sb.WriteString("\nUp to 8 highlights are shown. See the full report for all changes.\n\n")
}
sb.WriteString("Use [OpenAPI Doctor](https://pb33f.io/doctor/) for workspace history, diagnostics, and pipeline controls.\n")
product := "OpenAPI Doctor"
if outcome.label == "JSON Schema" {
product = "Doctor"
}
sb.WriteString("Use [" + product + "](https://pb33f.io/doctor/) for workspace history, diagnostics, and pipeline controls.\n")
return []byte(sb.String())
}

Expand Down
2 changes: 1 addition & 1 deletion cmd/compact_report_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ func TestCompactReportRejectsAliasedOutputs(t *testing.T) {
report, result := filepath.Join(dir, "report"), filepath.Join(dir, "result")
require.NoError(t, os.WriteFile(report, []byte("existing"), 0600))
require.NoError(t, os.Link(report, result))
require.Error(t, validateCompactOptions([]string{"a", "b"}, true, false, report, result))
require.Error(t, validateCompactOptions([]string{"a", "b"}, true, false, false, report, result))
}

func TestCompactReportHighlightsRemovedPath(t *testing.T) {
Expand Down
2 changes: 1 addition & 1 deletion cmd/component_report_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func TestComponentReports_PreserveEachComponent(t *testing.T) {
assert.Contains(t, item.HtmlReport, "<strong>8</strong> changes detected")
assert.Contains(t, string(item.Graph.NodeChangeTree), "$.components")

markdown, err := renderCommitMarkdown(commits[0], nil)
markdown, err := renderCommitMarkdown(commits[0], nil, false)
require.NoError(t, err)
assert.Contains(t, markdown, "**8** changes detected")
assert.Contains(t, markdown, "| Component | 8 |")
Expand Down
Loading
Loading