# Testing and validation (https://docs.neuralisapp.com/package-system/testing)

Two layers keep a package honest: load-time validation (a failing package does
not load), and `@neuralis/package-system/testing`, the helpers every native
suite runs against the contract shapes the runtime dispatches.

## Load-time validation [#load-time-validation]

| Validator | What it enforces |
| --- | --- |
| `validateManifest` | Identity present, package id not in the reserved host-route set, runtime/trust consistency (in-process `node` is native-only; untrusted packages cannot declare exec, full network, or full filesystem permissions; skill-script execution above `'none'` requires at least trusted), [URI policy](https://docs.neuralisapp.com/package-system/uri-policies.md) namespace rejection, `requires.*` shape checks |
| `validateContribution` | Per-tool schema checks, duplicate tool/widget/dock/card/command/connector ids, the renderer-by-trust matrix for [App surfaces](https://docs.neuralisapp.com/package-system/app-surfaces.md), the full source-connector contract (`kind`, `configSchema`, mandatory `list`+`read` capabilities, factory format, scope rules), `requires` shape on files and commands |
| `validateToolSchema` | MCP root shape (`$schema`, `title`, `type: "object"`, root `additionalProperties: false`), reserved session-context keys rejected as top-level input properties (root-only), legacy extensions rejected, open-bag normalisation — see [Tools](https://docs.neuralisapp.com/package-system/tools.md) |
| `validateXNeuralis` | The canonical `x-neuralis` extension: dotted `operation`, fixed `transport` enum, annotations shape, mandatory risk category for native tools |
| `validateWorkflowTemplate` | Every `workflows/*.json` template, strictly (`additionalProperties: false` throughout): the trigger and execution-policy shapes, engine-owned input keys rejected, `choice` inputs and their defaults — see [Workflows](https://docs.neuralisapp.com/package-system/workflows.md) |
| `validateRequiresShape` | The one `requires` shape check the tool, file, command and workflow validators share, so a gate is spelled identically everywhere |

Results are `{ valid, errors, warnings }`: errors block registration,
warnings go to the logs.

## The testing toolkit [#the-testing-toolkit]

Everything below imports from `@neuralis/package-system/testing` and runs
under vitest.

### Session factories [#session-factories]

| Helper | Returns |
| --- | --- |
| `createMockSession(overrides?)` | Full-access `SessionContext` — owner role, `['*']` features |
| `createDeniedSession(overrides?)` | Zero feature grants — every gate denies |
| `createTrustedSession(overrides?)` | Member role with a specific (non-wildcard) feature list |
| `createViewerSession(overrides?)` | Viewer role, read-only agent access, no grants |

All four take partial overrides ([shape](https://docs.neuralisapp.com/package-system/sessions.md)).

### Request and context builders [#request-and-context-builders]

`routeGet(path, query?, session?)`, `routePost`, `routePatch`, `routeDelete`
and `createMockRouteRequest(overrides?)` build a `PackageRouteRequest` (path =
the segments after `/api/packages/<id>/`); call the handler directly:

```ts
import { describe, it, expect } from 'vitest';
import { routeGet, createDeniedSession } from '@neuralis/package-system/testing';
import { GET } from '../src/routes/items';

describe('items route', () => {
  const state = { db: { listItems: async () => [{ id: '1' }] } };

  it('returns items for an authorized caller', async () => {
    const res = await GET(routeGet(['items'], undefined, { grantedFeatures: ['my-pkg.read'] }), state);
    expect(res.status).toBe(200);
  });

  it('denies a caller without the feature', async () => {
    const res = await GET(routeGet(['items'], undefined, createDeniedSession()), state);
    expect(res.status).toBe(403);
  });
});
```

For tools and lifecycle code:

- `createMockToolCallContext()` / `createDeniedToolCallContext()` — a tool
  handler's context (`sessionOverrides` / `ctxOverrides`).
- `createMockInitContext({ packageSlug?, dataDir?, globalDir?, ... })` — a
  native `PackageInitContext` (`globalDir: null` = project-installed) with a
  real `FileStore`/`JsonlAppender` and `dataPath` in a temp directory, so the
  real scoping runs.
- `createMockPackagesAccessor({ '@scope/pkg': api })` — `getPackageApi()` stubs.
- `createDiscoveredRoute` / `createDiscoveredToolHandler` — dispatcher subjects.
- `createPackageDefinition` / `createToolDefinition` and the hosted-entry
  builders — minimal valid shapes.

### Filesystem and async helpers [#filesystem-and-async-helpers]

- `createTempDir(prefix)` / `cleanupTempDirs()` / `withTempDir(prefix, fn)` —
  auto-cleaned scratch directories.
- `waitFor(predicate, { timeoutMs?, intervalMs?, message? })` — condition
  polling; throws on timeout (default 5 s).

### Connector compliance [#connector-compliance]

```ts
import { assertConnectorCompliance } from '@neuralis/package-system/testing';

await assertConnectorCompliance(connector, {
  rootUri: `${connector.source}://`,
  sampleFilePath: `${connector.source}://README.md`,
  packageTrust: 'trusted',
});
```

It exercises every declared capability (declared versus actual, round-trips
only when advertised, the typed error taxonomy), throws a
`ConnectorComplianceFailure` listing every violation, and never writes outside
`rootUri`. Run it for every [source connector](https://docs.neuralisapp.com/package-system/connectors.md).

### Cross-package mirror drift [#cross-package-mirror-drift]

A structural shape declared where a dependency edge must not exist
([why](https://docs.neuralisapp.com/package-system/routes.md#typed-cross-package-api)) is pinned by
`assertApiMirror`, compiled against the provider type's declaring file by
absolute path, so no edge is created:

```ts
import { assertApiMirror } from '@neuralis/package-system/testing';

expect(assertApiMirror({
  mirrorFile: `${repo}/packages/your-package/src/theirApi.ts`,
  mirrorType: 'TheirApiLike',
  providerDts: `${repo}/packages/their-package/dist/src/lifecycle.d.ts`,
  providerType: 'TheirApi',
})).toEqual([]);
```

It reports drift both ways (an extra key, a changed argument or return shape)
and treats vacuity as failure: a missing declaration or unresolved module
would collapse to `any`, so it is reported. It reads the last-emitted
declaration — build the provider first. `providerType: '*'` targets a dynamic
`import('<pkg>')` module shape; `exclude` skips a key the call site owns.

### Feature audit [#feature-audit]

`auditFeatures({ provided, references })` reports ids referenced (by a tool,
route, skill or role grant) that no package provides, and provided ids nothing
references; `formatFeatureAudit(result)` renders them.

## What to cover [#what-to-cover]

Test the contract, not just the happy path:

- **Authorization** — every route and tool against a denied session (403 or an
  error result, not an exception); each feature with and without the grant and
  `'*'` ([Features](https://docs.neuralisapp.com/package-system/features.md)).
- **Cross-project isolation** — data from another project never leaks.
- **Schema strictness** — `validateToolSchema` over your `tools/*.json` in a test.
- **Failure paths** — malformed input, oversized payloads, missing state,
  connector errors, each a structured error.
- **Result envelopes** — runtime-only accounting in `_meta`, never in `content`.

## App surface pre-flight [#app-surface-pre-flight]

An [app surface](https://docs.neuralisapp.com/package-system/app-surfaces.md) almost always fails silently: it
validates, loads, is listed, and the panel is blank or unstyled. Load-time
validation sees only the manifest, so the rest is a pre-flight plus a look at
the rendered surface.

| Check | Where it is caught |
| --- | --- |
| Removed renderer (`inline-html`, `wasm-ui`), or a legacy `fallback` key | load-time validation — a migration error, and it fails the whole package |
| Entry outside its own `app/surfaces/{kind}/{surfaceId}/` root, under `app/shared/`, traversal-capable, or a root that collides after case-folding | load-time validation |
| Absolute iframe URL from an untrusted package; `bridge.enabled` below trusted; `direct` below native | load-time validation |
| A self-contained entry (the default) references an external stylesheet, script, image, or `url(…)` that is not a `data:` URI | **packaging pre-flight only** |
| An `assetMode: "bundle"` entry references something resolving outside its own surface root and `app/shared/`, or links to a second document | **packaging pre-flight only** (the serving lane also refuses it at request time) |
| `assetMode: "bundle"` declared on a `direct` renderer, an absolute URL, or a non-HTML entry | load-time validation — a warning; the declaration is ignored and the surface is served self-contained |
| `app.module` with an unknown key, an `entry`/`css` that is not a package-relative `.js`/`.mjs`/`.css` path under `dist/`, or a `provides` id that is not a subpath of the package's own name (or is duplicated, or more than 16); or declared by a package that is not host-assigned native | load-time validation — an error; for the trust case a warning, and the field is dropped |
| A native UI module whose bundle carries its own React or platform client copy, imports a module no other UI package lists in `app.module.provides`, reads React with no resolvable `react` package, or whose output mismatches its `app.module` | **build time** — `neuralis-build ui` fails (`BUNDLED_SHARED_MODULE` / `UNDECLARED_SHARED_MODULE` / `NO_REACT` / `MANIFEST_MISMATCH`) |
| A UI module built for another host API version or React major, or a React-reading build whose record names no React major (built before an upgrade) | **attach time** — refused, its surfaces show the placeholder; rebuild with `neuralis-build ui` |
| Entry is root-absolute, carries a `projectId`, or points at a package-id-bearing asset path | **packaging pre-flight only** |
| Entry over the 2 MiB asset cap | packaging pre-flight; the serving route also refuses it |
| A tool's `ui.cardType` matching no declared card surface | packaging pre-flight — a warning; the result falls back to the generic default card |
| One card `type` declared twice with different renderer/URL profiles | packaging pre-flight — the later one wins; at runtime the host only logs a duplicate-type warning |
| A widget with no `kind: "dock"` companion, no `defaultOpen` and no `dock: { "show": false }` opt-out | packaging pre-flight |
| The surface renders **styled** in all three tool states for the least-privileged role that should see it, and is absent for one that should not | live, as the real role |

Subresource rules depend on the asset mode and cannot be checked at load time
(the validator has no filesystem): a self-contained entry's linked stylesheet
is never served; a `bundle` entry's siblings come from a lane refusing anything
outside the surface root and `app/shared/`. The pre-flight script ships with
the package-creation skill; run it before every publish.