Skip to content

SDK output envelopes, format-aware budgets, and stable error contracts - #895

Merged
unbraind merged 4 commits into
mainfrom
agent/sdk-output-envelope-contracts
Aug 4, 2026
Merged

unbraind merged 4 commits into
mainfrom
agent/sdk-output-envelope-contracts

Conversation

@unbraind

@unbraind unbraind commented Aug 4, 2026 •

Copy link
Copy Markdown
Owner

Outcome

Delivers a cohesive SDK/CLI context-contract tranche: typed output envelopes and mutation receipts, format-aware command budgets, classified/stability-gated error metadata, typed workspace snapshot failures, and deterministic offline reindex coverage. This directly resolves the undocumented mutation/query envelope defect reported in #888 while retaining broader follow-on scopes as open PM features.

Closes #888.

PM lineage

What changed

  • Added public SDK envelope definitions, built-in/package fallback resolution, flat CLI mutation receipt typing, validation, and camelCase normalization.
  • Paired every active runtime command with an output envelope and format-specific TOON/JSON budget; full consumer discovery currently reports 117 command contracts.
  • Added semantic exit classes, emitting-command ownership, and a stable/provisional ledger whose generator fails closed on malformed state, unsupported exits, stable removals, and drift.
  • Reclassified workspace snapshot grammar/not-found/conflict paths into typed errors with real CLI negative controls.
  • Added SDK/scripting documentation and an executable package-consumer receipt example.
  • Prevented mutation-triggered semantic refresh from escaping the residual reindex test mock boundary.
  • Regenerated contracts, SDK surface, error catalog, token baseline, and CHANGELOG through pm-changelog 2026.8.4.

Verification

  • Full repository coverage: 433 files, 6,850 tests, 100% statements / branches / functions / lines.
  • ESLint: zero warnings; jscpd: zero clones; static quality: 100% docstrings.
  • Typecheck, contract snapshot, SDK surface, docs/skills, secrets, token-budget, context-calibration, tracker measurement, CLI transport, and package-boundary gates pass.
  • Packed artifact installed in unrelated temporary npm and Bun projects; npx and bunx initialized trackers and created receipts parsed through the public SDK. Offline npm install audited 70 packages with zero vulnerabilities.
  • GitHub open security inventory: zero Dependabot, code-scanning, and secret-scanning alerts.

Explicit limitations

  • The npm advisory endpoint timed out through all pnpm audit retries; the cached/offline artifact audit and GitHub alert surfaces are clean.
  • The pre-existing pm-ay3l0p defect makes a broad coverage command direct-green but linked-schema-red; focused linked tests pass and direct coverage is the authoritative 100% result.
  • Local import-cost timing was noisy under sustained host load after passing earlier on the same code; hosted exact-head gates remain authoritative.

Summary by Sourcery

Introduce typed output envelope and mutation receipt contracts across the SDK/CLI, enrich error metadata with semantic classes, stability gating, and emitting command ownership, and harden workspace snapshot flows and offline reindex behavior.

New Features:

  • Expose SDK output envelope contracts, including generated budgets and envelopes for core and package commands, plus a public mutation receipt parser for scripting and package consumers.
  • Add format-aware command output budgets with TOON/JSON-specific token ceilings and fallback generation for extension-owned commands.
  • Publish command output and error-code contracts through the contracts command, including envelope families, budgets, semantic exit classes, stability, and emitting command roots.

Bug Fixes:

  • Fix workspace snapshot CLI errors by replacing generic exceptions with structured, typed PmCliError failures for invalid targets, missing snapshots, manifest mismatches, and unsafe restores.
  • Prevent reindex coverage tests from leaking mutation-triggered semantic refresh HTTP calls past their intended mock boundaries.

Enhancements:

  • Extend the error-code catalog generator and runtime contracts to track stability over time, infer emitting commands, classify exit codes into semantic classes, and reject unsupported or malformed catalog entries.
  • Tighten SDK and CLI contracts around output formats, including documenting mutation-versus-read envelope differences, enriching scripting docs, and enforcing non-empty, normalized command paths in budget and envelope helpers.
  • Broaden tests and type coverage for error catalogs, output budgets, output envelopes, SDK subpath entrypoints, and scripting examples to keep the public surface deterministic and safely consumable.

Documentation:

  • Update scripting and SDK documentation and examples to describe mutation receipts versus read envelopes, command output budget/envelope contracts, and how machine clients should consume these structured results.

Tests:

  • Add unit and integration tests for the error-code catalog generator stability ledger, output envelope contracts, mutation receipt parsing, workspace snapshot CLI error behavior, SDK subpath entrypoints, and the contract-consumer example receipt script.

Chores:

  • Regenerate public SDK surface, contracts fixtures, token baselines, and changelog entries to reflect the new output and error-code contracts.

Summary by cubic

Adds typed output envelopes and flat mutation receipts to the SDK/CLI, plus format-aware TOON/JSON budgets and a stability-gated error catalog with exit classes. Hardens contract discovery (normalized subcommand paths, explicit single/bulk mutations), clarifies --json, validates normalized error provenance, and makes reindex coverage deterministic. Closes #888.

  • New Features

    • SDK: PM_COMMAND_OUTPUT_ENVELOPE_CONTRACTS; parseMutationReceipt/isPmMutationReceipt with unambiguous overloads.
    • Budgets: TOON/JSON ceilings in PM_COMMAND_OUTPUT_BUDGET_CONTRACTS; helpers createPmCommandOutputBudget and inferPmOutputBudgetClass.
    • Errors: catalog includes PM_ERROR_CODE_EXIT_CLASS_CONTRACTS, emitting commands, and a reviewed stability ledger.
  • Bug Fixes

    • Discovery: preserve normalized subcommand/alias paths for envelope and budget lookups; classify single vs bulk mutation shapes.
    • Catalog: generator fails closed on unreadable/drifting ledgers; trims/normalizes sources and emitting commands and rejects empty provenance; unknown_error maps to exit 1; adds tests that lock resolution semantics and usage-class exits.
    • CLI/Tests: --json help clarifies receipts vs envelopes; workspace snapshot emits typed usage errors; reindex coverage is deterministic and under 30s.

Written for commit 37b55c6. Summary will update on new commits.

Review in cubic

Expose typed mutation receipts and per-command envelope contracts through the SDK and runtime discovery surface. Add format-aware token ceilings, package fallbacks, semantic error classes, and a stable/provisional compatibility ledger. Harden workspace snapshot failures, document executable consumer flows, preserve 100 percent coverage, and make reindex coverage deterministic.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry @unbraind, your pull request is larger than the review limit of 150000 diff characters

@gemini-code-assist

Copy link
Copy Markdown

Caution

The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased.

@unbraind

unbraind commented Aug 4, 2026

Copy link
Copy Markdown
Owner Author

@greptileai please review this cohesive SDK/CLI output-contract tranche at the exact current head.

@sourcery-ai

sourcery-ai Bot commented Aug 4, 2026

Copy link
Copy Markdown

Reviewer's Guide

Introduces format-aware output budgets and envelope contracts for all commands, adds semantic error exit classes with a stability ledger, makes workspace snapshot failures typed CLI errors, provides a public mutation receipt parser and example script, fixes reindex semantic refresh leakage, and updates contracts/docs/tests to reflect the new SDK/CLI context contract surface.

File-Level Changes

Change Details Files
Make command output budgets format-aware and expose envelope contracts for all core and package commands.
  • Extend PmCommandOutputBudgetContract with per-format token ceilings and helper to infer workload class and generate budgets for arbitrary command strings.
  • Add resolvePmCommandOutputBudget overload that can generate deterministic package fallback budgets.
  • Introduce PM_OUTPUT_ENVELOPE_KINDS and PmCommandOutputEnvelopeContract plus helpers to declare/resolve default result envelopes for each command.
  • Wire command_output_contracts (budget + envelope pairs) into the contracts command runtime and fixtures.
  • Export new budget and envelope helpers through SDK index and cli-contracts surfaces.
src/sdk/cli-contracts/agent-output-contracts.ts
src/sdk/output-contracts.ts
src/sdk/cli-contracts/runtime-contracts.ts
src/sdk/index.ts
src/sdk/cli-contracts.ts
tests/unit/sdk/agent-output-contracts.spec.ts
tests/unit/sdk/output-contracts.spec.ts
tests/fixtures/contracts/full.json
sdk/public-surface.json
docs/SDK.md
docs/SCRIPTING.md
docs/README.md
docs/SELF_DESCRIBING_CONTEXT_CONTRACTS.md
Strengthen error-code catalog with semantic classes, emitting-command ownership, and a stability ledger enforced by the generator.
  • Extend error-code contracts with class and emitting_commands fields and validate them against a stable exit-code taxonomy.
  • Regenerate generated-error-code-catalog entries to include semantic classes, provisional stability for new codes, and inferred emitting_commands.
  • Teach generate-error-code-catalog.mjs to assign error classes from exit codes, infer emitting commands from source paths, read/write an error-code-stability ledger, and refuse unsupported exits or removal of stable codes.
  • Add unit tests covering ledger creation, provisional codes, removal protection, malformed ledgers, and unsupported exit codes.
  • Update docs to describe exit-code classes, emitting command roots, and stability ledger behavior.
src/sdk/error-code-catalog.ts
src/sdk/generated-error-code-catalog.ts
scripts/generate-error-code-catalog.mjs
scripts/error-code-stability.json
tests/unit/scripts/generate-error-code-catalog.spec.ts
tests/unit/sdk/error-code-catalog.spec.ts
docs/SELF_DESCRIBING_CONTEXT_CONTRACTS.md
Convert workspace snapshot paths into structured CLI errors with stable codes and recovery contracts.
  • Introduce new provisional workspace snapshot error codes in the generated catalog.
  • Replace generic Error throws in workspace-snapshot.ts with PmCliError instances carrying structured metadata for invalid targets, reserved fingerprint names, not-found cases, manifest mismatches, and force-required restores.
  • Use shared EXIT_CODE constants for snapshot errors and add helper to build a not-found error reused across read/remove operations.
  • Extend workspace snapshot CLI integration tests to cover invalid target handling and JSON stderr structure.
src/sdk/workspace-snapshot.ts
src/sdk/generated-error-code-catalog.ts
tests/integration/workspace-snapshot-cli.integration.spec.ts
Expose a typed mutation receipt parser and example script for package and shell consumers.
  • Define PmMutationReceipt and PmCliMutationReceipt types plus isPmMutationReceipt and parseMutationReceipt helpers that enforce flat receipt shape and normalize field names.
  • Export parseMutationReceipt via SDK contracts and index surfaces and assert its availability in SDK subpath entrypoint tests and dts type tests.
  • Add docs example parse-receipt.mjs script that runs pm create, checks subprocess errors/exit status, and parses stdout via parseMutationReceipt.
  • Extend sdk-contract-consumer tests and example README/package.json to cover receipt parsing and subprocess failure modes.
src/sdk/output-contracts.ts
src/sdk/contracts.ts
src/sdk/index.ts
tests/unit/sdk/sdk-subpath-entrypoints.spec.ts
tests/types/sdk-subpath-entrypoints.test-d.ts
docs/examples/sdk-contract-consumer/parse-receipt.mjs
docs/examples/sdk-contract-consumer/package.json
docs/examples/sdk-contract-consumer/README.md
tests/unit/docs-examples/sdk-contract-consumer.spec.ts
Adjust CLI help and reindex behavior to align with new contracts and fix semantic refresh leakage in tests.
  • Clarify global --json help text to distinguish flat mutation receipts from read envelopes.
  • Set mutation_refresh_policy to cache_only in reindex-command tests to prevent semantic refresh HTTP from escaping the mock boundary.
  • Document the reindex coverage leak fix in CHANGELOG and add PM issue artifacts for deterministic reindex coverage.
src/sdk/cli-program.ts
tests/unit/commands/reindex-command.spec.ts
CHANGELOG.md
.agents/pm/issues/pm-cflhoj.toon
.agents/pm/history/pm-cflhoj.jsonl

Assessment against linked issues

Issue Objective Addressed Explanation
#888 Document the JSON envelope contract: mutations emit flat receipts with top-level id/status/changed_field_count while reads use wrapped entity/collection envelopes, in both CLI help (e.g. --json) and scripting/docs. ✅
#888 Provide a typed SDK helper (e.g. parseMutationReceipt in @unbrained/pm-cli/sdk) so extensions can safely parse mutation receipts instead of hand-parsing stdout. ✅
#888 Expose a machine-readable discriminant for output envelopes so consumers can assert whether a command returns a receipt, single entity, or collection instead of guessing. ✅

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@unbraind

unbraind commented Aug 4, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Summary by CodeRabbit

  • New Features
    • Added structured output envelopes and typed mutation-receipt parsing.
    • Added format-specific TOON and JSON output limits with safe fallbacks.
    • Expanded error details and workspace snapshot diagnostics.
  • Bug Fixes
    • Prevented unintended external refresh requests during reindex coverage.
  • Documentation
    • Updated scripting, SDK, error handling, and contract documentation with examples and discovery guidance.

Walkthrough

The PR adds format-aware command output budgets, output-envelope and mutation-receipt contracts, classified error metadata with stability validation, and structured workspace-snapshot errors. It also updates SDK exports, documentation, generated fixtures, tests, and PM tracking records.

Changes

SDK output contracts

Layer / File(s) Summary
Format-aware output budgets and runtime contracts
src/sdk/cli-contracts/..., src/sdk/cli-contracts/runtime-contracts.ts, tests/unit/sdk/agent-output-contracts.spec.ts, tests/fixtures/contracts/full.json
Budgets now define TOON and JSON ceilings. Undeclared package commands can receive generated fallback contracts. Runtime contract output includes budgets and envelopes.
Output envelopes and mutation receipts
src/sdk/output-contracts.ts, src/sdk/contracts.ts, src/sdk/index.ts, docs/SDK.md, docs/SCRIPTING.md, docs/examples/sdk-contract-consumer/*, tests/unit/sdk/output-contracts.spec.ts
The SDK defines command envelopes, validates flat mutation receipts, parses JSON receipts, and normalizes snake_case fields to camelCase.
Public surface and contract validation
sdk/public-surface.json, tests/types/sdk-subpath-entrypoints.test-d.ts, tests/unit/sdk/sdk-subpath-entrypoints.spec.ts, src/sdk/cli-program.ts
New budget, envelope, receipt, and error-contract APIs are published and type-tested. CLI JSON help describes mutation and read envelopes.

Error catalog and workspace errors

Layer / File(s) Summary
Error classification and stability ledger
src/sdk/error-code-catalog.ts, src/sdk/generated-error-code-catalog.ts, scripts/error-code-stability.json, scripts/generate-error-code-catalog.mjs, tests/unit/scripts/generate-error-code-catalog.spec.ts, docs/SELF_DESCRIBING_CONTEXT_CONTRACTS.md
Error entries now include semantic classes and emitting commands. Generation validates exit mappings, ledger compatibility, provisional codes, and stable-code removal.
Structured workspace-snapshot failures
src/sdk/workspace-snapshot.ts, tests/integration/workspace-snapshot-cli.integration.spec.ts, sdk/public-surface.json, tests/fixtures/contracts/full.json
Snapshot validation, lookup, creation, manifest checks, and restore confirmation now use typed CLI errors with diagnostic and recovery metadata.

Supporting records and documentation

Layer / File(s) Summary
Tracking and verification records
.agents/pm/features/*, .agents/pm/history/*, .agents/pm/issues/*, CHANGELOG.md
PM records document implementation tranches, dependencies, test runs, reproductions, and the reindex mock-lifetime fix.
Documentation and measured surfaces
docs/README.md, docs/examples/sdk-contract-consumer/*, scripts/agent-token-surface-baseline.json
Documentation maps, SDK examples, receipt parsing instructions, and token-surface baselines are updated.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 51.61% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the main SDK and CLI changes: output envelopes, format-aware budgets, and stable error contracts.
Description check ✅ Passed The description directly explains the SDK, CLI, error-contract, documentation, testing, and deterministic reindex changes.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
✅ Action performed

Full review finished.


Your included review limit is currently reached under our Fair Usage Limits Policy. This review may still proceed through usage-based billing if eligible. Your next included review will be available in 59 minutes.

@codspeed

codspeed Bot commented Aug 4, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 11 untouched benchmarks


Comparing agent/sdk-output-envelope-contracts (37b55c6) with main (478c522)

Open in CodSpeed

@codecov

codecov Bot commented Aug 4, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ All tests successful. No failed tests found.

📢 Thoughts on this report? Let us know!

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 12

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/sdk/error-code-catalog.ts (1)

77-99: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Validate sources and emitting_commands after normalization.

Lines 77-78 check the raw array lengths. Lines 88-99 then trim each value and drop empty strings. An input of [" "] passes validation and normalizes to []. The published contract then carries an empty sources or emitting_commands list, which the new nonempty invariant is meant to prevent.

Normalize first, then validate the normalized lists.

🔧 Proposed fix to validate normalized lists
     seen.add(code);
+    const normalizeList = (values: readonly string[]): string[] => [
+      ...new Set(values.map((value) => value.trim()).filter(Boolean)),
+    ].sort();
+    const sources = normalizeList(declaration.sources);
+    const emittingCommands = normalizeList(declaration.emitting_commands);
     if (
       ![1, 2, 3, 4, 5].includes(declaration.exit_code) ||
       declaration.meaning.trim().length === 0 ||
       declaration.recovery.trim().length === 0 ||
-      declaration.sources.length === 0 ||
-      declaration.emitting_commands.length === 0 ||
+      sources.length === 0 ||
+      emittingCommands.length === 0 ||
       ERROR_CLASS_BY_EXIT_CODE.get(declaration.exit_code) !== declaration.class
     ) {
       throw new TypeError(`Invalid pm error code contract: ${code}`);
     }
     return Object.freeze({
       ...declaration,
       code,
       meaning: declaration.meaning.trim(),
       recovery: declaration.recovery.trim(),
-      sources: [
-        ...new Set(
-          declaration.sources.map((source) => source.trim()).filter(Boolean),
-        ),
-      ].sort(),
-      emitting_commands: [
-        ...new Set(
-          declaration.emitting_commands
-            .map((command) => command.trim())
-            .filter(Boolean),
-        ),
-      ].sort(),
+      sources,
+      emitting_commands: emittingCommands,
     });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/sdk/error-code-catalog.ts` around lines 77 - 99, Update the contract
validation flow around the declaration normalization to validate the normalized
sources and emitting_commands lists, not their raw input lengths. Trim, filter
empty values, deduplicate, and sort both lists first, then reject the
declaration if either resulting list is empty; preserve the existing TypeError
and frozen return behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.agents/pm/features/pm-x4nn3z.toon:
- Around line 82-86: Add a focused PM test entry for
tests/integration/workspace-snapshot-cli.integration.spec.ts alongside the
existing tests in the tests block, using the project’s PM CLI test command, and
record its result. Keep the change scoped to this PM item and preserve the
existing verification entries.

In `@scripts/generate-error-code-catalog.mjs`:
- Around line 149-159: Update inferEmittingCommands to track sources that do not
match command, lifecycle, or query paths and include "*" alongside resolved
command roots when any such source exists; retain ["*"] for sources with no
resolved roots. Regenerate src/sdk/generated-error-code-catalog.ts using pnpm
contracts:errors:update so invalid_argument_value and missing_required_option
reflect the wildcard origin.
- Around line 231-256: In main, defer bootstrapped stability-ledger creation
until after the rows mapping with renderCatalogRow completes successfully.
Preserve the missing-ledger --check error and stability validation, but move the
mkdir/writeFile block out of the stableCodes initialization path so render
failures cannot persist discovered codes; retain the generated ledger contents
and subsequent catalog behavior.
- Around line 161-173: Update readStabilityLedger to treat only an ENOENT read
error as a missing ledger, returning null in that case; rethrow all other
filesystem errors so main cannot overwrite the stability record after an
unreadable ledger failure.

In `@src/sdk/output-contracts.ts`:
- Around line 214-216: Update the parseMutationReceipt function signature to
remove the redundant string | unknown union. Use overloads to explicitly expose
the string JSON-parsing form alongside the unknown-value form, while preserving
the existing PmMutationReceipt return type and implementation behavior.
- Around line 71-102: Update the command classification in MUTATION_COMMANDS to
include all remaining single-item mutation commands, including start-task,
close-task, pause-task, and focus, so they receive mutation_receipt envelopes
with their top-level id and status. Add explicit envelope handling for bulk
mutations such as close-many and update-many instead of allowing them to use the
diagnostic fallback in the default branch around the contract generation logic.
Preserve the existing diagnostic and collection classifications for commands
that are not mutations.

In `@tests/fixtures/contracts/full.json`:
- Around line 8471-8524: Update the runtime contract generator around
resolvePmCommandOutputBudget and resolvePmCommandOutputEnvelope so each
generated subcommand row preserves its full command path, such as “extension
install”, instead of the root token. Ensure command_output_contracts emits
distinct command identifiers for every subcommand while retaining the declared
budget and envelope values, then regenerate the fixture.
- Around line 14892-14949: Update the error catalog generation/source mappings
so unknown_error uses generic_failure with class generic_failure and exit code 1
instead of usage/2. Then standardize unknown_field, unknown_item_type,
unknown_status, unknown_field_projection, unknown_option, and unknown_subcommand
under one consistent class and exit-code pair, updating their source definitions
and regenerated full.json entries together.
- Around line 12601-12613: Restore meaningful, authored contract metadata for
the affected entries in the generated full.json fixture: update each meaning to
describe the actual error condition, preferably deriving it from the
corresponding source error message such as core/item/parse.ts, and provide
actionable recovery guidance specific to each class or code instead of the
shared generic sentence. Regenerate the fixture using the project’s existing
contract-generation workflow so runtime consumers receive the corrected values.

In `@tests/unit/docs-examples/sdk-contract-consumer.spec.ts`:
- Around line 28-34: Update all four node:child_process mock factories in this
spec to include an execFile vi.fn alongside the existing spawnSync mock. Keep
each factory’s current spawnSync behavior unchanged so imports that promisify
execFile do not receive undefined.

In `@tests/unit/scripts/generate-error-code-catalog.spec.ts`:
- Around line 66-81: Extend the test around main(root, []) with a second
declaration of new_create_failure in a non-command source, such as a
cross-cutting module. Update the assertions for emitting_commands to verify both
the create command root and the * root, covering multi-source inference while
preserving the existing stability and code assertions.

In `@tests/unit/sdk/agent-output-contracts.spec.ts`:
- Around line 92-107: Add a separate assertion in the “rejects invalid format
budgets and empty generated command paths” test that passes an invalid value for
the json entry of default_max_estimated_tokens_by_format to
definePmCommandOutputBudget and verifies the expected validation error
references that entry, while preserving the existing toon and
createPmCommandOutputBudget coverage.

---

Outside diff comments:
In `@src/sdk/error-code-catalog.ts`:
- Around line 77-99: Update the contract validation flow around the declaration
normalization to validate the normalized sources and emitting_commands lists,
not their raw input lengths. Trim, filter empty values, deduplicate, and sort
both lists first, then reject the declaration if either resulting list is empty;
preserve the existing TypeError and frozen return behavior.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI (base), Organization UI (inherited)

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: d0cf7a32-0a60-441f-913b-2d090f4be11c

📥 Commits

Reviewing files that changed from the base of the PR and between 478c522 and acbd3f6.

📒 Files selected for processing (42)
  • .agents/pm/features/pm-5t33or.toon
  • .agents/pm/features/pm-x4nn3z.toon
  • .agents/pm/history/pm-5t33or.jsonl
  • .agents/pm/history/pm-ay3l0p.jsonl
  • .agents/pm/history/pm-cflhoj.jsonl
  • .agents/pm/history/pm-srns.jsonl
  • .agents/pm/history/pm-x4nn3z.jsonl
  • .agents/pm/issues/pm-ay3l0p.toon
  • .agents/pm/issues/pm-cflhoj.toon
  • .agents/pm/issues/pm-srns.toon
  • CHANGELOG.md
  • docs/README.md
  • docs/SCRIPTING.md
  • docs/SDK.md
  • docs/SELF_DESCRIBING_CONTEXT_CONTRACTS.md
  • docs/examples/sdk-contract-consumer/README.md
  • docs/examples/sdk-contract-consumer/package.json
  • docs/examples/sdk-contract-consumer/parse-receipt.mjs
  • scripts/agent-token-surface-baseline.json
  • scripts/error-code-stability.json
  • scripts/generate-error-code-catalog.mjs
  • sdk/public-surface.json
  • src/sdk/cli-contracts.ts
  • src/sdk/cli-contracts/agent-output-contracts.ts
  • src/sdk/cli-contracts/runtime-contracts.ts
  • src/sdk/cli-program.ts
  • src/sdk/contracts.ts
  • src/sdk/error-code-catalog.ts
  • src/sdk/generated-error-code-catalog.ts
  • src/sdk/index.ts
  • src/sdk/output-contracts.ts
  • src/sdk/workspace-snapshot.ts
  • tests/fixtures/contracts/full.json
  • tests/integration/workspace-snapshot-cli.integration.spec.ts
  • tests/types/sdk-subpath-entrypoints.test-d.ts
  • tests/unit/commands/reindex-command.spec.ts
  • tests/unit/docs-examples/sdk-contract-consumer.spec.ts
  • tests/unit/scripts/generate-error-code-catalog.spec.ts
  • tests/unit/sdk/agent-output-contracts.spec.ts
  • tests/unit/sdk/error-code-catalog.spec.ts
  • tests/unit/sdk/output-contracts.spec.ts
  • tests/unit/sdk/sdk-subpath-entrypoints.spec.ts

Comment thread .agents/pm/features/pm-x4nn3z.toon Resolved
Comment thread scripts/generate-error-code-catalog.mjs Resolved
Comment thread scripts/generate-error-code-catalog.mjs Resolved
Comment thread scripts/generate-error-code-catalog.mjs Resolved
Comment thread src/sdk/output-contracts.ts Resolved
Comment thread tests/fixtures/contracts/full.json Resolved
Comment thread tests/fixtures/contracts/full.json Resolved
Preserve normalized subcommand paths in envelope and token-budget lookup, classify single and bulk mutation shapes explicitly, and expose unambiguous mutation receipt overloads.

Make error-catalog generation fail closed for unreadable ledgers, publish the ledger only after successful rendering, retain cross-cutting emitter provenance, and align unknown_error with generic failure exit semantics.

Add review-driven regressions, refresh generated SDK/contracts/token surfaces, clarify scripting guidance, and record exact 100/100/100/100 plus npm/Bun consumer evidence in pm-srns, pm-5t33or, and pm-x4nn3z.
@unbraind

unbraind commented Aug 4, 2026

Copy link
Copy Markdown
Owner Author

Review revision pushed at 3e90d2d8524ad71ebbe819b830262a81c270c2c9.

@coderabbitai full review
@greptileai please review the new exact head
@sourcery-ai review

@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown

@unbraind I will perform a full review of the current PR head at 3e90d2d8524ad71ebbe819b830262a81c270c2c9.

✅ Action performed

Full review finished.


Your included review limit is currently reached under our Fair Usage Limits Policy. This review may still proceed through usage-based billing if eligible. Your next included review will be available in 3 minutes.

@unbraind

unbraind commented Aug 4, 2026

Copy link
Copy Markdown
Owner Author

Gemini notice acknowledged: the consumer reviewer is sunset, so it supplied no code-review evidence for this PR.

@unbraind

unbraind commented Aug 4, 2026

Copy link
Copy Markdown
Owner Author

Sourcery guide acknowledged; its file-level and issue mapping was useful for review orientation.

@unbraind

unbraind commented Aug 4, 2026

Copy link
Copy Markdown
Owner Author

CodeRabbit summary acknowledged. All 12 actionable findings received an inline disposition, reaction, regression evidence, and review-fix commit where applicable.

@unbraind

unbraind commented Aug 4, 2026

Copy link
Copy Markdown
Owner Author

CodeRabbit command acknowledgement noted; the resulting full first-head review was processed completely.

@unbraind

unbraind commented Aug 4, 2026

Copy link
Copy Markdown
Owner Author

CodSpeed report acknowledged. Its own report flags differing runtime environments; the exact-head hosted benchmark job passed, so no baseline was weakened.

@unbraind

unbraind commented Aug 4, 2026

Copy link
Copy Markdown
Owner Author

Codecov report acknowledged: patch coverage and the four-shard aggregate coverage gate pass on exact head.

@unbraind

unbraind commented Aug 4, 2026

Copy link
Copy Markdown
Owner Author

CodeRabbit second-review acknowledgement noted. The provider subsequently reported the new-head review as rate limited; this is recorded as a provider limitation, while all first-round findings were resolved and exact-head gates are green.

@unbraind

unbraind commented Aug 4, 2026

Copy link
Copy Markdown
Owner Author

Sourcery review-limit response acknowledged. It supplied no actionable review because the cohesive PR exceeds the provider limit; the separate Sourcery guide was still useful.

@unbraind

unbraind commented Aug 4, 2026

Copy link
Copy Markdown
Owner Author

CodeRabbit review acknowledged. All 12 findings were inspected, voted, answered inline, and either implemented with regression proof or dispositioned with the preserved semantic boundary.

Normalize error sources and emitting command roots before enforcing non-empty catalog invariants, so whitespace-only declarations cannot publish empty provenance.

Add regression coverage and record exact full-suite coverage evidence on pm-x4nn3z.
@unbraind

unbraind commented Aug 4, 2026

Copy link
Copy Markdown
Owner Author

Outside-diff CodeRabbit finding implemented in fd84261f0: sources and emitting_commands are normalized before the non-empty invariant is checked, with whitespace-only regressions for both arrays. Direct full coverage remains 100/100/100/100 (6,850 tests).

@coderabbitai full review
@greptileai please review the new exact head
@sourcery-ai review

@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown

@unbraind I will perform a full review of the current PR head. I will verify the normalization change and its regression coverage.

✅ Action performed

Full review finished.


Your included review limit is currently reached under our Fair Usage Limits Policy. This review may still proceed through usage-based billing if eligible. Your next included review will be available in 59 minutes.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
tests/unit/sdk/error-code-catalog.spec.ts (1)

36-41: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Assert the new error metadata in resolvePmErrorCodeContract.

The fixture includes class and emitting_commands, but the assertion checks only exit_code and stability. A resolver regression that drops either field would pass this test.

Suggested assertion
     ).toMatchObject({
       exit_code: 2,
       stability: "stable",
+      class: "usage",
+      emitting_commands: ["help"],
     });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/unit/sdk/error-code-catalog.spec.ts` around lines 36 - 41, Extend the
assertion for resolvePmErrorCodeContract("unknown_command", catalog) to also
verify the fixture’s class and emitting_commands metadata, preserving the
existing exit_code and stability checks.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.agents/pm/features/pm-x4nn3z.toon:
- Around line 87-90: Remove the duplicate generate-error-code-catalog test
command from the PM metadata while retaining one canonical entry. Apply the
change through the PM CLI, then regenerate the derived projection; do not edit
the .toon or append-only history file directly.

---

Outside diff comments:
In `@tests/unit/sdk/error-code-catalog.spec.ts`:
- Around line 36-41: Extend the assertion for
resolvePmErrorCodeContract("unknown_command", catalog) to also verify the
fixture’s class and emitting_commands metadata, preserving the existing
exit_code and stability checks.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI (base), Organization UI (inherited)

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 7003fa3a-7be1-419e-9cb4-576d63008253

📥 Commits

Reviewing files that changed from the base of the PR and between acbd3f6 and fd84261.

📒 Files selected for processing (20)
  • .agents/pm/features/pm-5t33or.toon
  • .agents/pm/features/pm-x4nn3z.toon
  • .agents/pm/history/pm-5t33or.jsonl
  • .agents/pm/history/pm-srns.jsonl
  • .agents/pm/history/pm-x4nn3z.jsonl
  • .agents/pm/issues/pm-srns.toon
  • docs/SCRIPTING.md
  • scripts/agent-token-surface-baseline.json
  • scripts/generate-error-code-catalog.mjs
  • sdk/public-surface.json
  • src/sdk/cli-contracts/agent-output-contracts.ts
  • src/sdk/error-code-catalog.ts
  • src/sdk/generated-error-code-catalog.ts
  • src/sdk/output-contracts.ts
  • tests/fixtures/contracts/full.json
  • tests/unit/docs-examples/sdk-contract-consumer.spec.ts
  • tests/unit/scripts/generate-error-code-catalog.spec.ts
  • tests/unit/sdk/agent-output-contracts.spec.ts
  • tests/unit/sdk/error-code-catalog.spec.ts
  • tests/unit/sdk/output-contracts.spec.ts

Comment thread .agents/pm/features/pm-x4nn3z.toon Resolved
Assert the complete stable usage contract for resolved error codes and normalize the canonical PM evidence to three non-overlapping linked test gates.
@unbraind

unbraind commented Aug 4, 2026

Copy link
Copy Markdown
Owner Author

@greptileai please review the exact final head 37b55c6 after the review corrections.\n\n@coderabbitai full review\n\n@sourcery-ai review

@unbraind

unbraind commented Aug 4, 2026

Copy link
Copy Markdown
Owner Author

Acknowledged CodeRabbit completion/rate-limit artifact IC_kwDORSgRDc8AAAABNQoCzw. Its two actionable findings were useful and are implemented at exact head 37b55c6; the provider limit is recorded as a review-availability limitation, not approval.

@unbraind

unbraind commented Aug 4, 2026

Copy link
Copy Markdown
Owner Author

Acknowledged CodeRabbit review PRR_kwDORSgRDc8AAAABIaEGDA. Both findings are implemented at exact head 37b55c6: catalog resolution now asserts class and emitting command ownership, and redundant PM-linked test commands were removed through pm.

@coderabbitai

coderabbitai Bot commented Aug 4, 2026

Copy link
Copy Markdown

Rate Limit Exceeded

@unbraind have exceeded the limit for the number of chat messages per hour. Please wait 26 minutes and 22 seconds before sending another message.

@unbraind

unbraind commented Aug 4, 2026

Copy link
Copy Markdown
Owner Author

Acknowledged and up-voted all 12 CodeRabbit confirmation replies and their associated review containers. Each confirmation maps to an individually answered, resolved finding on the reviewed source head; no additional action was requested by those confirmation artifacts.

@unbraind

unbraind commented Aug 4, 2026

Copy link
Copy Markdown
Owner Author

Acknowledged empty CodeRabbit review container PRR_kwDORSgRDc8AAAABIaF3qQ associated with the exact-head rate-limit response. No finding was supplied; no approval is inferred.

@unbraind

unbraind commented Aug 4, 2026

Copy link
Copy Markdown
Owner Author

Acknowledged CodeRabbit exact-head rate-limit artifact IC_kwDORSgRDc8AAAABNQvN6w. It supplies no review finding; the provider limit is a documented availability limitation, while exact-head repository checks and the earlier substantive review remain separate evidence.

@unbraind

unbraind commented Aug 4, 2026

Copy link
Copy Markdown
Owner Author

Final artifact acknowledgement: down-voted CodeRabbit rate-limit reply PRRC_kwDORSgRDc7dg7yx and its empty review container PRR_kwDORSgRDc8AAAABIaHn0Q. They contain no findings; their parent thread is resolved because the underlying PM test duplication is fixed and verified. No additional inline reply is being sent because it would only generate another provider rate-limit artifact.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

JSON envelope shape differs between mutations and queries with no documented contract, and it silently cost us a production bug

1 participant