Skip to content

Add active contract checks for dynamic package invocation - #435

Merged
kentcdodds merged 7 commits into
mainfrom
cursor/package-invoke-contract-checks
May 11, 2026
Merged

kentcdodds merged 7 commits into
mainfrom
cursor/package-invoke-contract-checks

Conversation

@kentcdodds

@kentcdodds kentcdodds commented May 10, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • rebased on latest main
  • add packages.check and packages.invokeChecked runtime helpers plus codemode.package_invoke_check / codemode.package_invoke_checked
  • return normalized invoke input and current package/export contract metadata with weak-validation warnings
  • document when agents should use static imports, direct packages.invoke, and checked dynamic invocation
  • address AI-review feedback by reusing shared helpers, deduplicating and caching package-app bridge setup, reusing manifest resolution during package checks, clarifying check.contract.warnings, and preserving invokeChecked operation labels in preflight validation errors

Testing

  • npx vitest run packages/worker/src/package-invocations/service.node.test.ts (20 passed)
  • npx vitest run packages/worker/src/package-invocations/service.node.test.ts packages/worker/src/mcp/run-codemode-registry.node.test.ts packages/worker/src/package-runtime/module-graph.workers.test.ts packages/worker/src/repo/checks.node.test.ts (67 passed)
  • PR CI passed after the latest push: Validate, Preview deploy, CodeRabbit, and Bugbot
Open in Web Open in Cursor 

Summary by CodeRabbit

  • New Features

    • Added packages.check() method to validate package contracts before invocation
    • Added packages.invokeChecked() method for safer dynamic package calls with built-in validation
  • Documentation

    • Updated guidance on dynamic package invocation patterns and best practices
  • Tests

    • Expanded test coverage for new package invocation validation and checked invocation flows

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 10, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

The PR extends package runtime invocations with a pre-invocation checking capability. packages.check validates existence and parameters of a target package export, returning current contract metadata and warnings. packages.invokeChecked combines check and invocation into a single operation that fails before invoking if validation fails. The feature is wired through the service layer, runtime bridge, codemode helpers, and documented across user-facing guides.

Changes

Pre-invocation checking for package invocations

Layer / File(s) Summary
Type Definitions
packages/worker/src/mcp/run-codemode-registry.ts, packages/worker/src/repo/checks.ts
New types PackageInvokeNormalizedInput, PackageInvokeContract, and PackageInvokeCheckResult define the structure of check results and contract metadata; PackageInvokeTools updated to include check and invokeChecked methods; KodyPackagesRuntime type prelude expands to declare check(...) and invokeChecked(...) in addition to invoke(...).
Core Service: Input Parsing
packages/worker/src/package-invocations/service.ts
readSinglePackageIdentifier and input parsing helpers accept operationName parameter to produce operation-specific error messages; parsePackageInvokeInput returns normalized { packageIdOrKodyId, exportName, params } structure.
Core Service: Check Path
packages/worker/src/package-invocations/service.ts
New checkPackageInvokeForRuntime function parses invocation input, resolves saved package and manifest, determines runtime target, ensures module artifacts are available, optionally loads package source for metadata extraction, and returns either { ok: true, invoke, contract, warnings } or { ok: false, message, problems }. Helper functions construct failure results, normalize inputs, and build warning lists based on missing schemas/sources.
Core Service: Invocation Refactoring
packages/worker/src/package-invocations/service.ts
createPackageRuntimeInvokeTools refactored to centralize runtime-context validation via requireRuntimeCaller guard; invoke reuses shared parsing and idempotency flow; invokeChecked runs checkPackageInvokeForRuntime and throws if check fails, otherwise invokes using returned normalized input.
Service Tests: Setup and Helpers
packages/worker/src/package-invocations/service.node.test.ts
Test fixtures expanded with per-source sourceFiles map including concrete package.json and handler modules; new createRuntimeDispatchTools helper constructs invocation tools with caller context and gateway package context.
Service Tests: Check Validation
packages/worker/src/package-invocations/service.node.test.ts
Tests verify tools.check returns ok: true with invoke payload and detailed contract metadata (published commit, export mapping, runtime target, type definition); warnings emitted when params schema unavailable; check reflects metadata changes without republishing caller.
Service Tests: Check Failures
packages/worker/src/package-invocations/service.node.test.ts
Tests verify tools.check returns structured failures for missing saved package, missing export, and invalid params (non-object); tools.invokeChecked fails fast with composed message when check fails, avoiding bundled module invocation.
Runtime Bridge: Proxy and Tools
packages/worker/src/package-runtime/package-app.ts
createPackagesProxy forwards check and invokeChecked to runtime-bridge methods; PackageAppRuntimeBridge gains createPackageRuntimeInvokeTools() method that lazily imports service and constructs tools configured with baseUrl, caller context, package context, and runtime debug/depth.
Runtime Bridge: Check and Checked Methods
packages/worker/src/package-runtime/package-app.ts
New packageInvokeCheck and packageInvokeChecked methods added to PackageAppRuntimeBridge; packageInvoke refactored to use shared tools helper; all three methods delegate to corresponding tools functions.
Runtime Tests
packages/worker/src/package-runtime/module-graph.workers.test.ts
Bundled test entry module detects packages.check and packages.invokeChecked capability flags; packageInvokeTools test mock extended with check and invokeChecked implementations; test assertions verify hasCheck: true and hasInvokeChecked: true flags.
Codemode Prelude and Registry
packages/worker/src/mcp/run-codemode-registry.ts
Codemode helper prelude updated to expose packages.check and packages.invokeChecked mapped to codemode tools; buildCodemodeFns extended to register package_invoke_check and package_invoke_checked tool wrappers delegating to packageInvokeTools.check and packageInvokeTools.invokeChecked.
Codemode Tests
packages/worker/src/mcp/run-codemode-registry.node.test.ts
Test fixture includes packageInvokeTools.check implementation returning contract-shaped invoke payload; assertions verify providerFns.package_invoke_check integration and providerFns.package_invoke_checked invocation path.
User Documentation
docs/use/packages.md
Section revised to document packages.invokeChecked for fan-out scenarios requiring pre-invocation validation and packages.check as standalone inspect helper; details success shape (contract, warnings) and failure shape (ok: false, message, problems); clarifies pre-invocation rejection for invokeChecked versus runtime rejection for invoke; notes packages is null in ad hoc execute contexts; documents codemode equivalents.
Contributing Guide
docs/contributing/packages-and-manifests.md
"Dynamic current-version invocation" section expanded with packages.invokeChecked and packages.check as recommended validation step; includes TypeScript example showing check followed by invoke via returned check.invoke; documents behavioral differences and params validation constraints.
Execute Documentation
docs/use/execute.md
Clarification added to prefer packages.invokeChecked(...) for dynamic current-version calls; documents relationship between check and invoke via check.invoke; reiterates packages is null outside saved-package contexts.
Server Instructions
packages/worker/src/mcp/server-instructions.ts
execute tool instructions updated with guidance preferring packages.invokeChecked or packages.check(...)+packages.invoke(...) for dynamic current-version calls inside package runtime code versus static imports for bundled snapshots.
Tool Description
packages/worker/src/mcp/tools/execute.ts
execute tool description expanded to document packages.check, packages.invoke, and packages.invokeChecked availability in saved package runtime contexts only; advises using invokeChecked for dynamic current-version calls unless check is already performed.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • kentcdodds/kody#429: Directly extended by this PR with pre-invocation packages.check path and packages.invokeChecked helper built on top of the dynamic invocation work introduced there.
  • kentcdodds/kody#275: Modifies the same packages/worker/src/package-invocations/service.ts file to extend invocation-related APIs; both PRs affect the core package invocation service layer.
  • kentcdodds/kody#306: Both PRs modify package invocation paths and the ensureModuleArtifact flow; this PR refactors that function to support the new check validation path.

Poem

🐰 A check before you leap, dear friend,
invokeChecked calls to the very end—
Contract promises peek through the door,
Before the bundled runtime roars!
Thump thump, validation complete at last. 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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
Title check ✅ Passed The title 'Add active contract checks for dynamic package invocation' directly and accurately summarizes the main feature being added—new contract checking capabilities for package invocation. It aligns with the primary objectives and changes throughout the pull request.
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch cursor/package-invoke-contract-checks

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 and usage tips.

@github-actions

github-actions Bot commented May 10, 2026 •

Copy link
Copy Markdown
Contributor

🔎 Preview deployed: https://kody-pr-435.kentcdodds.workers.dev

Worker: kody-pr-435
D1: kody-pr-435-db
KV: kody-pr-435-oauth-kv

Mocks:

Comment thread packages/worker/src/package-invocations/service.ts Outdated
Comment thread packages/worker/src/package-runtime/package-app.ts
cursoragent and others added 4 commits May 11, 2026 17:28
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
@cursor
cursor Bot force-pushed the cursor/package-invoke-contract-checks branch from 4ff9c2b to 841211c Compare May 11, 2026 17:29
Comment thread packages/worker/src/package-invocations/service.ts

@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: 2

🤖 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 `@docs/use/packages.md`:
- Around line 158-164: The docs paragraph implies a top-level warnings field but
in code warnings live under the returned contract; update the text to explicitly
state that package checks return warnings on check.contract.warnings (e.g.,
"warnings are available on check.contract.warnings") and adjust the surrounding
sentence so consumers don't expect a top-level warnings property when using
packages.check or destructuring the result.

In `@packages/worker/src/package-invocations/service.ts`:
- Around line 389-404: The preflight validation in checkPackageInvokeForRuntime
hard-codes the caller operation name to "packages.check" when calling
parsePackageInvokeInput, which causes validation errors to be labeled
incorrectly for invokeChecked callers; change the function signature of
checkPackageInvokeForRuntime to accept an operationName string (e.g.,
"packages.invokeChecked" or the caller-provided name) and pass that
operationName into parsePackageInvokeInput instead of the hard-coded
"packages.check"; also update the other parsePackageInvokeInput call-site(s) in
this file (the similar block around the later invocation) to thread the
appropriate operation name through so validation errors retain the correct
operation label.
🪄 Autofix (Beta)

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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: c6564635-356b-44a9-9cfd-655ed0d5f492

📥 Commits

Reviewing files that changed from the base of the PR and between 26462ea and 841211c.

📒 Files selected for processing (12)
  • docs/contributing/packages-and-manifests.md
  • docs/use/execute.md
  • docs/use/packages.md
  • packages/worker/src/mcp/run-codemode-registry.node.test.ts
  • packages/worker/src/mcp/run-codemode-registry.ts
  • packages/worker/src/mcp/server-instructions.ts
  • packages/worker/src/mcp/tools/execute.ts
  • packages/worker/src/package-invocations/service.node.test.ts
  • packages/worker/src/package-invocations/service.ts
  • packages/worker/src/package-runtime/module-graph.workers.test.ts
  • packages/worker/src/package-runtime/package-app.ts
  • packages/worker/src/repo/checks.ts

Comment thread docs/use/packages.md Outdated
Comment thread packages/worker/src/package-invocations/service.ts
cursoragent and others added 2 commits May 11, 2026 17:44
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit ebc556b. Configure here.

Comment thread packages/worker/src/package-runtime/package-app.ts
Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>
@coderabbitai

coderabbitai Bot commented May 11, 2026

Copy link
Copy Markdown

Caution

Failed to replace (edit) comment. This is likely due to insufficient permissions or the comment being deleted.

Error details
{}

@kentcdodds
kentcdodds merged commit a1b36d8 into main May 11, 2026
5 checks passed
@kody-bot
kody-bot deleted the cursor/package-invoke-contract-checks branch July 21, 2026 18:59
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.

2 participants