Skip to contents

Use the same loop for new and existing clients: update inputs -> plan -> review -> apply -> check -> test -> commit. Schemas, service policy, callbacks, fixed fixtures, output, .specmill/helpers/, and .specmill/manifest.json form one reviewed change. For a toolkit upgrade, follow the existing-client upgrade workflow. Normal generation does not update client-owned request helpers or session controls. After a toolkit upgrade, a client that uses the load and attach stubs runs specmill::configure_lifecycle(root) to see whether R/client_lifecycle.R changed and mode = 'apply' to update it; R/zzz.R is never touched.

1. Review schema changes

Keep the old schema snapshot while downloading the new one using your client’s own acquisition process. Use the same filename and selection policy for both versions. For example, place catalogue.json in schema-before/ and schema-after/:

selection <- list(methods = c('GET', 'POST'), exclude = '^/internal/')
diff <- specmill::schema_diff(
  '/path/to/schema-before', '/path/to/schema-after',
  policies = list('catalogue.json' = selection)
)
cat(specmill::format_diff_markdown(diff))
specmill::count_diff_changes(diff)

schema_diff() compares method/path identities and canonical data including reachable local references and response shapes. Changed contracts enter the breaking-change report lane conservatively for review. Parsing failures stop comparison. These labels do not prove runtime compatibility.

For parsed operation records, compare_operations(old, new) gives a smaller report of additions, removals, changed parameters/bodies, and unknown response compatibility. Unsupported operations remain parser diagnostics, so review them alongside any comparison.

Compare schema revisions under a fixed policy, then review policy changes separately. Otherwise, changing an exclusion can look like an upstream deletion. Generation does not automatically delete an implementation merely because an operation disappears from an unsupported or changed schema. Eligible removal comes from explicit exclusions or reconciled renames and requires verified ownership.

Naming conventions are proposal-time settings. generate_client() uses the explicit service YAML names and does not reapply name_case. To propose names for new endpoints, run configure_client(..., name_case = 'snake_case'), review its changes, and copy the accepted mappings into the existing YAML.

2. Generate and verify

root <- normalizePath('/path/to/client', winslash = '/', mustWork = TRUE)
plan <- specmill::generate_client(root, config = 'specmill.yml', mode = 'plan')
plan$files
plan$drift
plan$diagnostics
plan$validation
# After reviewing the change:
specmill::generate_client(root, config = 'specmill.yml', mode = 'apply')
specmill::generate_client(root, config = 'specmill.yml', mode = 'check')
testthat::test_local(root, stop_on_failure = TRUE)

Generation validates each schema locally against its official OpenAPI JSON Schema before translating operations. Invalid documents and unsupported coverage block apply and check; inspect plan$validation for the full findings. References outside the document must be bundled first or, for remote ones, mapped to reviewed local copies.

Check mode warns when a current schema’s hash differs from the last applied manifest, showing its path and previous/current SHA-256 hashes. The warning appears before schema translation, including when the changed schema cannot be translated. A schema newly referenced by existing configuration reports its previous hash as not recorded. Initial generation and legacy manifests without input hashes have no comparison baseline. Check writes no client files; use plan mode to review file changes, then apply reviewed output to record the new baseline. A hash change alone does not mean a function needs rebuilding.

When the manifest has an endpoint inventory, the warning also lists added and removed method/path pairs, identifies additions outside current selection policy, and names previously configured functions affected by removals. It appears even when a removed endpoint makes a function mapping invalid. For a parseable plan, the same information is in plan$schema_changes and its printed summary. This compares endpoint presence; it does not classify parameter or response changes as compatible or breaking. Removed endpoints never authorize deleting client functions automatically.

An upgrade from a manifest containing only hashes needs one reviewed apply to record the endpoint inventory. Plan/check report that comparison is unavailable until the inventory exists. Schema files removed from configuration or renamed are not automatically matched to their previous versions. Commit the updated manifest with the reviewed policy and generated output.

This warning runs only when the generation check is called. It does not download schemas or automatically attach to devtools::build() or devtools::check(). Include the generation check in your project’s development command or CI as shown below.

Supply the same explicit callbacks environment on each call when your policy uses callbacks. Run the relevant manual/helper tests too. Reapplying unchanged inputs should produce only unchanged/retained file actions. Review output diffs before committing; do not hand-edit generated files to fix a policy error.

Defer a changed contract that does not validate yet

By default every selected operation must validate, and one failing operation blocks apply and check. When an upstream revision breaks one operation, you can defer that single contract revision instead of excluding the operation or forgetting its inventory. Enrollment is explicit and is recorded on apply only. For a worked example with real output, see Defer or skip an operation:

enroll <- list(enroll = c('demo GET /bad' = 'Response lacks a description'))
specmill::generate_client(root, config = 'specmill.yml', mode = 'plan', deferrals = enroll)
specmill::generate_client(root, config = 'specmill.yml', mode = 'apply', deferrals = enroll)

The key is <service id> <METHOD> <path>; the reason is one line. The manifest stores the reason, source, operation key, and a v1: SHA-256 fingerprint of the operation, its path-level parameters and servers, security, host/base path, and every transitively referenced local definition (sorted keys, normalized line endings). Healthy operations generate normally.

State Meaning
deferred Fingerprint unchanged. Skipped; apply and check are no-ops.
retry_blocked Contract changed but still fails. Needs a fix, a new enrollment, or an opt-in policy.
retry_recovered Contract changed and now passes. Plan shows the wrapper; apply writes it through the normal gates and drops the enrollment.
uncertain Enrollment metadata, source, or operation cannot be read or matched. The record is kept untouched and the operation stays withheld; check fails until you clear or re-enroll it. A record that is not an object cannot be matched, so apply stays strict for it.

Clearing is an explicit retry: deferrals = list(clear = 'demo GET /bad'). A toolkit update alone, key order, whitespace, and edits to unrelated operations or definitions do not wake an enrollment; prose changes inside the contract do. Fingerprints are scoped per source, so equal paths in other APIs are unaffected.

To enroll failures of listed diagnostic codes without a manual step, add deferral: {automatic: [schema_validation_invalid]} to the service. Other codes, document-level findings, and shared blockers (an unreadable schema, a bad policy) still stop the run. Validation is never disabled.

Plan and check are read-only. Deferral never deletes code: an existing wrapper, its documentation, tests and ownership are preserved, including a function inside a grouped file that a healthy sibling rewrites. A never-generated deferred operation gets no placeholder. A project whose operations are all deferred still persists the enrollment, and repeating an empty apply is a no-op.

Prune retired output

Preserving output is the default; removal is opt-in. To retire an operation, defer or exclude it so it is no longer generated, then name it:

specmill::generate_client(root, config = 'specmill.yml', mode = 'plan', prune = 'demo GET /bad')
specmill::generate_client(root, config = 'specmill.yml', mode = 'apply', prune = 'demo GET /bad')

Apply removes the operation’s R file, tests and help page, regenerates NAMESPACE (when documentation is generated) and drops the ownership records. The ID is matched against manifest ownership, so it may name a service that was since removed from specmill.yml; an enrolled deferral ID also matches the retired owner of the same METHOD /path. Otherwise the service in the ID must be the owner the manifest records, which can differ from the service you remember generating the file from: copy the ID from files[<path>].operations in .specmill/manifest.json. Pruning refuses an operation that is still generated, an ID that owns nothing, and a file shared with other operations. A hand-edited file is retained, as with any removal. Without prune, outputs of a removed service stay in place with their old ownership record.

Named prune covers the selected artifacts.

A manifest file path also works, e.g. prune = 'R/helper_preflight.R'. It drops that file and its ownership record whole, which is the way to clear a stale entry that owns no operations (a helper whose file is already gone). It refuses a still-generated R/ or tests/ file and NAMESPACE; an edited file is retained.

Run the configuration against an older or staging schema

names, operations, selection.include and routes keys must name operations the schema contains, so a configuration written for one schema revision stops on another that dropped routes (Unknown operation override). For a one-off or preview build, pass absent_overrides = 'warn':

specmill::generate_client(root, config = 'specmill.yml', mode = 'plan', absent_overrides = 'warn')

Keys for absent operations then raise a warning that lists them and are otherwise ignored, while the YAML itself stays strict. If every selection.include key of a service is absent, that service selects nothing. Wrappers already generated for dropped operations stay in place until you prune them.

Review a clean regeneration

Before pruning, regeneration_report() shows what a full rebuild would add, change or remove, and what Specmill leaves alone. It writes nothing:

specmill::regeneration_report(root, config = 'specmill.yml')

Each file gets a category: added, changed, unchanged, edited_conflict and unowned_collision (a hand-written file at a generated path), kept (lifecycle badge, existing implementation, deferral or NAMESPACE), would_remove (owned but no longer generated; prune_eligible is FALSE when an edit makes prune refuse it, and reason notes a removed service), unowned_generated (generated-looking, no ownership record) and hand_written (left alone, so the remainder is your hand-built inventory). It compares the in-memory plan with the current tree rather than purging and rebuilding: deferrals, existing implementations and lifecycle badges keep their placement.

prune = 'all' plans removal of every manifest-owned, unmodified output so a project can be regenerated from scratch; unowned and edited files are untouched. It ignores spec, config, validation, artifacts, adopt and deferrals. Apply asks Are you sure? [y/N] (default no). Non-interactive sessions never prompt: pass confirm = TRUE, or the call aborts without writing. R/client_lifecycle.R is kept while your R/zzz.R exists, because that file may call it; delete R/zzz.R first to remove both.

Limitations: a contract that stays broken needs a human decision; fingerprints cover local references only; a renamed source or removed operation is reported as uncertain rather than matched.

3. Add a thin sourceable command

New clients receive dev/generate.R during initialization. Source it and call generate_main(args = '--plan'), or use the shell commands below. Add callback loading to this client-owned script when your policy needs it. Regeneration preserves its contents.

For clients created before development scripts were emitted, save the following as dev/generate.R if no command exists:

.client_root <- specmill::script_root('generate.R')
generate_main <- function(root = .client_root, args = commandArgs(trailingOnly = TRUE)) {
  specmill::generation_command(root, args = args, kind = 'stubs')
}
if (sys.nframe() == 0L) generate_main()

script_root() locates the package from the source frame or Rscript invocation, so the command works from another working directory. Add explicit callback loading inside generate_main() if needed, as in the existing-client guide. Source it in R and call generate_main(args = '--plan'), or run:

Rscript dev/generate.R --plan
Rscript dev/generate.R --check
Rscript dev/generate.R

The final command applies. Compatibility commands intentionally have a different default from the core generate_client(), which defaults to check.

Command kind Preview Check Apply
stubs (wrappers and documentation) --plan --check No mode flag
tests (fixed contract tests) --dry-run --check --generate or no mode flag

--help describes accepted flags. Any other flag stops the command, including the former --rebuild=<prefix> and --force, which were ignored before: YAML controls selection, and ownership is never overridden. Check/apply test commands fail if any selected operation lacks a fixed contract. Plan can report the gaps.

For custom orchestration, use generate_client(artifacts = ...) to limit reconciliation to wrappers, tests, or documentation. Shared ownership and manifest checks still apply.

4. Inspect implementation and test gaps

inspection <- specmill::inspect_client(root)
inspection$coverage
inspection$manual_exports
inspection$diagnostics
inspection$helpers
inspection$protected_sources

Coverage counts files and declarations, not passing tests or working endpoints. Selected unsupported operations remain in totals. Manual exported wrappers are separate from the schema denominator and still need their own tests.

For badges and baseline comparisons, create a separate client report policy:

# dev/coverage.yml
baseline: dev/coverage-baseline.json
groups:
  catalogue:
    services: '^catalogue$'
    label: Catalogue wrappers
    badge: man/figures/catalogue-coverage.json

Every configured service must belong to a group. To leave one out, such as a reviewed overlay with no production source, list a regex for it under exclude_services. Matching services get no badge, and the plan names them. A service cannot be both excluded and in a group.

exclude_services: ['^pubchem$']

By default a group counts only the operations your policy selected, so a client that wraps everything it selected reads 100% however much of the API that is. To measure coverage of the API itself, opt a group in to the schema as its denominator:

groups:
  catalogue:
    services: '^catalogue$'
    label: Catalogue wrappers
    badge: man/figures/catalogue-coverage.json
    denominator: schema          # default: selected
    exclude: ['^GET /health']    # optional: operations you skip on purpose

With denominator: schema the total is every operation in the schemas the matched services reference, including those your selection policy excludes, minus any operation whose METHOD /path matches an exclude regex (the same regex engine as selection.exclude). An operation counts once per METHOD /path in the group, however many schema files or services describe it, so -full and -rebuild services, or a route that two schema files both document, do not double count. Keep one API surface in a group: two APIs on different servers that share a route would count as one, so put them in separate groups. An operation is covered when any service of the group wraps it. A path item that cannot be parsed counts as one operation named PATH /path. The badge, baseline and GitHub outputs keep their format; endpoints is the schema total and functions the wrapped count.

Each schema-mode group prints how many schema operations have no wrapper and how many of those are not selected. coverage_report() returns the full list as gaps, one data frame per group with key, schema, status (excluded, unsupported, selected, …) and services, so the gap can be acted on:

report <- specmill::coverage_report(root, file.path(root, 'dev/coverage.yml'))
report$gaps$catalogue

Group services values are regex strings matching service IDs. Groups must partition every configured service exactly once. Create the baseline’s parent directory before apply. Report-policy filenames passed as strings are resolved by R against the working directory; make them explicit with file.path(root, ...):

specmill::coverage_report(root, file.path(root, 'dev/coverage.yml'))
specmill::coverage_report(root, file.path(root, 'dev/coverage.yml'), mode = 'apply')
specmill::test_gap_report(root, list(
  helpers = list('api_request'), report_dir = 'dev/test-gaps',
  readiness_report = 'dev/readiness-report.json'
))

Reports default to read-only plans. Coverage apply writes badges and its baseline; gap-report apply writes a dated JSON report. Gap reasons distinguish missing contracts, absent/empty test files, and unsupported operations. readiness_report is a pointer to your canonical audit, not an audit created by this call.

Maintain recorded tests

Clients with cassette scenarios need one extra pass after a schema, policy, helper or hook change. See the testing guide for the details.

  1. Run specmill::testing_report(root) and read review and changed for each scenario. Regenerate first if test_current is FALSE.
  2. For each recording that needs review, decide whether its behavior should change. Re-record only intended changes: delete the cassette and list the scenario in <PACKAGE>_RECORD, locally, with real credentials.
  3. Run specmill::review_recordings(root) to compare the new responses with the response schema, and read the cassette, .credentials and signature diffs before committing.
  4. Run the tests with credentials unset. Replay must pass offline.

Never re-record to make a failing expectation pass, and never record in CI.

5. Add client-specific checks to CI

CI should install the project’s reviewed toolkit and formatter, then run generation checks before tests. For a client with no callbacks, an R CI step can be:

checked <- specmill::generate_client('.', config = 'specmill.yml', mode = 'check')
stopifnot(length(checked$diagnostics) == 0L)
testthat::test_local('.', stop_on_failure = TRUE)

If you intentionally retain unsupported operations, use an explicit reviewed diagnostic allowance instead of removing the diagnostics gate. Do not use continue-on-error for invalid configuration or schema parsing before publishing generated output. Generation commands write existing summary keys to GITHUB_OUTPUT when that environment variable is set; core functions return structured results and errors instead of choosing a process exit code.

check_public_boundary() accepts your forbidden host/file/export/schema regexes and approved manual-export list. check_client_hooks() validates supplied runtime hook declarations against parsed client definitions. Their reference pages explain arguments and return values. Keep these policies client-specific.

credential_status() and credential_preflight() detect absent/placeholder credentials without logging values or making requests. They cannot prove a key is authorized. Offline generation and fixed contract tests need no live key.

Scan the manifest for secrets

.specmill/manifest.json records inputs and outputs as 64-character lowercase SHA-256 digests keyed by file path. Gitleaks’ default generic-api-key rule can report these digests as credentials. Allow only the manifest’s digest lines, and only for that rule, in the client’s .gitleaks.toml:

[extend]
useDefault = true

# SHA-256 digests in the specmill manifest are not credentials. Allow only
# whole "key": "<sha256>" lines in that file, for generic-api-key alone.
[[rules]]
id = "generic-api-key"
[[rules.allowlists]]
description = "specmill manifest SHA-256 digests"
condition = "AND"
paths = ['''^\.specmill/manifest\.json$''']
regexTarget = "line"
regexes = ['''^\s*"[^"]+": "[0-9a-f]{64}",?\s*$''']

Keep the allowlist on the rule. A top-level [allowlist] path entry skips the whole file before any rule runs, which also hides provider-specific tokens. Do not exclude generated files, the whole manifest, or historical fingerprints. With this rule, a generated manifest scans clean, while a non-hex token in the manifest and a digest-shaped value in any other file are still reported.

Gate an upstream schema publication

A publisher can use read_operations() directly on the candidate local schema, without a client project or generated files. Save this as an R script and invoke it with Rscript validate-schema.R candidate.json using a reviewed specmill pin:

files <- commandArgs(trailingOnly = TRUE)
stopifnot(length(files) > 0L)
for (file in files) {
  parsed <- specmill::read_operations(file)
  for (d in parsed$diagnostics) cat(file, d$code, d$key, '\n')
  stopifnot(length(parsed$diagnostics) == 0L)
}

Parsing errors and failed assertions exit unsuccessfully. Publish only after this step succeeds. Do not apply client selection filters to a whole-schema gate: excluded operations are inventoried but not validated. This gate rejects both detected schema defects and specmill capability gaps. It is not a complete OpenAPI conformance validator or proof of a working service. Fixture and server diagnostics are separate results and need separate gates if required.

For the AMOS GET /api/amos/get_similar_structures/{identifier_type}/{identifier} declaration containing only a dtxsid path parameter, the reader reports three schema defects: unmatched dtxsid, missing identifier_type, and missing identifier. Each diagnostic has the same stable method/path key, a source file, and a source_location JSON Pointer. The unmatched declaration points to its parameter object; missing declarations point to the path item, since their parameter objects do not exist. Use the full diagnostics list for all findings; inventory keeps one row per operation and its first diagnostic for compatibility. Earlier parsing errors can still prevent the path-name checks from running.

Generation plans expose these diagnostics too. Check and apply reject a mixed selection containing this route before writing output. After reviewing the findings, explicitly select independently supported routes to generate those. A generated client mapping cannot repair malformed path metadata. Existing implementation: existing support can retain a reviewed handwritten function with a complete client contract, but does not certify or correct the schema.

6. Build documentation for your generated client

Set documentation: true and write useful docs policy before building the client site. Generation stages roxygen and reconciles man/ and NAMESPACE; the help pages then become pkgdown reference pages. Add human-written vignettes for authentication, common workflows, result interpretation, and errors.

From the client package root, install the documentation tools and initialize pkgdown once:

install.packages(c('pkgdown', 'usethis', 'rmarkdown', 'knitr'))
usethis::use_pkgdown()
pkgdown::build_site(preview = FALSE)

For a GitHub-hosted client, usethis::use_pkgdown_github_pages() configures the publishing workflow and Pages settings. Review the generated workflow for your default branch. See usethis’s pkgdown setup.

Keep its README short: purpose, installation, one example, and links to guides. Put sequential workflows in vignettes and per-function detail in reference docs. Render examples offline; mark real API calls eval=FALSE or use fixed examples that do not contact services.

For specmill’s own site, _pkgdown.yml defines navigation and .github/workflows/pkgdown.yaml builds on pull requests and publishes through GitHub Actions Pages after default-branch pushes or manual dispatch. Local build command:

pkgdown::build_site(preview = FALSE)

Open docs/index.html after building. Site output is ignored by Git and package builds; source articles and help pages are tracked. The workflow follows the r-lib pkgdown example.