# Develop a card provider locally

This path is for implementing a new interaction or grader through reviewed code
integration. To create a course using existing cards, start with the
[course-author workflow](../authoring/api.md). Course proposal tokens do not authorize code installation.

SDK v1 kit. This is the current interface generation, not a guarantee that providers built against any earlier v1 checkout remain compatible. Validate against the target host checkout before publication; the independent provider API is not yet frozen. Start with the [one-page card developer guide](../authoring/implementing-card-types.md). The independent provider-author trial remains incomplete.
The [web getting-started guide](../authoring/provider-playground.html) summarizes this workflow.

This kit runs trusted provider code through the app's actual content, draft and
result boundaries. It requires an app checkout, Node 22 or later, Gleam 1.18.1 or later,
and the app's npm dependencies. Run `npm ci` in the app checkout on the same
machine/OS that will run the kit: esbuild has a native executable, so copying
macOS `node_modules` into Linux does not work. Dependency installation may use
the network; an offline machine needs its compiler and dependencies provisioned
in advance. Node 22.14.0 and 24.10.0 have been tested on macOS. The running playground has no account or cloud sync.

## First run

In the app checkout, install dependencies and prepare the host once:

```sh
npm ci
npm run providers:prepare
```

Preparation requires Gleam and writes host compiler output and generated schemas
inside the app checkout. Re-run it after changing host contracts/build inputs or
cleaning build artifacts. Provider checks and previews only read that prepared
host; a missing or stale preparation produces a command to run, not an automatic
host rebuild.

From the app checkout, choose a new directory outside it:

```sh
npm run providers:init -- /absolute/path/my-provider
(cd /absolute/path/my-provider && npm run build)
npm run providers:check -- --config /absolute/path/my-provider/playground.json
npm run dev:providers -- --config /absolute/path/my-provider/playground.json
```

Open http://localhost:3022/. The generated provider is an exact-text echo card using the optional SDK standard shell.
The checker builds only the provider's Gleam project, imports its view, admits every sample,
and runs the declared positive and negative contract cases. A provider exception
fails the check; it does not count as an expected JSON rejection.

For browser automation use `dev:providers:test-state`, port 4022, and confirm the
**BROWSER TEST STATE** banner. Never automate the learner's preview on 3022.

## Built-in isolation checks

To exercise the five built-in providers, run `npm run build:static` once for their
fonts and math assets, then start `npm run dev:providers` without `--config`.
External providers do not require that asset build. Each sample receives an empty
root and its own storage key. The [provider contract](../providers/README.md#view-ownership-and-lifetime)
describes slot ownership, synchronous capabilities, appearance and optional
history consumers. These are reviewed modules sharing runtime/CSS utilities,
not a browser security sandbox.

## Files to change

| File | Purpose |
| --- | --- |
| `manifest.js` | Type ID, schema name and view entry; rebuild after changes |
| `src/providers_echo_test.gleam` | Content and result definitions and semantic requirements |
| `provider.js` | Connect those contracts to the host and declare provider behavior |
| `view.js` | Mount the UI; use the supplied lifecycle context |
| `playground.json` | Samples, contract checks, module path and project storage identity |
| `build.mjs`, `environment.mjs` | Check compiler prerequisites and run the provider build |
| `export-schemas.mjs` | Export the contracts' structural JSON schemas |

The generated `README.md` describes the starter's data. Keep the provider's prose
and generated schemas up to date as you change its contracts. Run `npm run build`
in the provider directory to regenerate schemas; `providers:check` compiles code
but does not regenerate those exported files.

For SDK-v1 saved work, see `experiments/provider-contract-test/saved-provider.js`
and `saved-view.js`. They extend the minimal echo with a work boundary and saved
input; the generated starter itself deliberately saves no drafts.

Use the saved echo fixture for Run-only drafts. Start new types with `providers:init`.

## Edit and check

1. Edit contracts and/or view in your provider directory.
2. Run `npm run build` there, then `providers:check` from the app checkout.
3. Restart `dev:providers` and reload the preview. There is no hot reload yet.
4. Use **Start fresh** after changing content. For types declaring saved work,
   use **Restore saved draft** to exercise compatibility with the stored draft.
   The minimal starter restores fresh state and does not recover transient input.
5. Use the boundary inspector to submit malformed payloads and inspect errors.

Add reproducible contract cases to `playground.json`. This work-channel example
applies after adding the saved echo work contract; the minimal starter only
registers content and result channels:

```json
{
  "checks": [
    {
      "name": "reject stale draft",
      "sample": "hello",
      "channel": "work",
      "payload": {"text": "hel", "answerKey": "old"},
      "accept": false
    }
  ]
}
```

`sample` names an entry in `samples`; its admitted content is the context for
work/result checks. Channels are `content`, `work`, or `result`. Include
both accepted and rejected cases. These checks do not exercise UI interactions,
prove schema equivalence, or replace lifecycle tests.

## Working with Gleam from JavaScript

Import host adapters from `@flashcards/provider-sdk/v1`. This name is resolved by the
kit's bundler, not a published npm package. Import provider contracts
from the generated `.generated/contracts.js` facade. Do not prebundle a separate Gargamelle runtime.

Ordinary JSON crosses a boundary unchanged in representation. Arguments supplied
directly to a compiled Gleam function instead need Gleam representations: use
a small Gleam wrapper to accept ordinary JS-facing values. The legacy
`@flashcards/provider-dev` helpers remain available for the ordering example;
new cards should not import compiler representations.

The starter copies the host's shared dependency declarations and lock entries.
Hex dependencies retain archive checksums; local path dependencies are relocated
relative to the new project and must remain available.
A mismatch fails before bundling. Do not remove that guard; coordinate dependency
updates with the host. A replaced Hex release can change a checksum without
changing the version number.

## Current contract baseline

The current checkout pins **published Gargamelle 1.0.0**. The host
`boundaries/gleam.toml` and generated starter manifests are authoritative.
No sibling Gargamelle checkout is required. The provider kit still requires
the app checkout.

The starter registers content and result channels; saved work is optional:

- **Content:** `jsonBoundary` wraps a Gargamelle receiving boundary. It decodes
  authored JSON and checks the JSON produced by the content encoder.
- **Optional saved work:** `jsonOutputBoundary` registers a contract parameterized by
  the current card's answer key. Saving and restoration both use that contract.
- **Result:** `jsonOutputBoundary` checks submitted evidence against current
  content. Historical interpretation uses the evidence's own saved answer instead
  of today's card, while retaining its internal consistency checks.

Define structural constraints and semantic requirements in Gleam contracts.
Keep schema exports and prose alongside them; schema files alone do not describe
arbitrary semantic checks. Preserve structured rejection diagnostics from the SDK.
These host adapters compose receiving and output boundaries. Gargamelle 1.0.0
also supplies `PairedBoundary` for typed loading/saving through one contract;
using it is not required by the provider kit.

## Current scope

The host supports drafts, completion, continuation, skipping and diagnostics.
It simulates one mounted card with a selectable Continue or Finish receipt. It does not simulate scheduling,
history digests, authentication, xAPI persistence or cloud sync. Provider code
runs as trusted local code, not inside a security sandbox. The application checkout
is still required; this is a source-based kit rather than an independently
installed SDK.

For the full provider interface, see ../providers/README.md and the generated
provider reference. Report any need to import app internals as a kit limitation.

## Setup failures

The commands check the Node version, Gleam availability/version (when needed),
and whether esbuild can execute before building. They report all detected
prerequisite problems together. These checks do not install anything or grant
permissions. A compiler/network/OS restriction still needs to be resolved in the
execution environment.

The standard starter build checks Node and Gleam; it does not require esbuild in
the provider directory. Only the host tools bundle JavaScript. Pure JavaScript
providers can use a prepared host without a Gleam compiler at check/preview time.

## Historical interpretation and diagnostic assertions

Use `interpretations` separately from current-content `checks`. Each entry has
`name`, `sample` (the current content), `attempt` (the original historical try),
and `outcome` (a provider outcome string, or `null` for unsupported evidence).
The checker admits the current sample, then calls `resultPolicy.interpret(attempt)`
synchronously, just as production does. Promises are rejected. Sample progress queries are checked against the runtime limits: history depth 1–100 and a positive safe-integer Try weight (no upper limit of 4). It does **not** pass current content into that interpreter
or require old evidence to pass today's content-specific result boundary. The
starter includes an old “hello” result paired with the current “bonjour” card.

Run `providers:check -- --config … --verbose` to see named successes and actual
rejection diagnostics. Negative `checks` may set `rejectionIncludes` to a
substring expected in the error message or structured issues (for example a
JSON Pointer). An exception is still a failure, never an expected rejection.
`--help` prints the command's usage.

## Independent Node tests

After building your provider and preparing the host, import `provider.js` directly
from a test using the supplied Node loader:

```sh
PROVIDER_CONFIG=/absolute/path/my-provider/playground.json \
  node --import /absolute/path/equation-flashcards/provider-dev/register.mjs \
  --test /absolute/path/my-provider/example.test.mjs
```

This resolves `@flashcards/provider-sdk/v1` (and the legacy `@flashcards/provider-dev`) and shares the checked host Gargamelle and
Gleam runtime identities, without bundling your test. Plain Node without the
loader still cannot resolve that development alias. The loader checks dependency
versions/checksums and host preparation; it does not compile either project.

## Multiple playgrounds and browser automation

Pass `--port 4023` together with `--test-state` for a second automation server.
Choose an unused origin that has never been used for learner previews. Each
process has its own temporary build directory; a port collision cannot overwrite
another process's bundle. Clean shutdown removes that directory. A hard process
kill can leave temporary files for the operating system to clean up.

Select a sample with `?provider=SAMPLE_ID`. Stable controls include `#content`,
`#mount` (fresh), `#restore`, `#continuation`, `#snapshot`, `#continue`, `#skip`,
`#end`, `#channel`, `#payload`, and `#submit`. Inspect `#status`, `#events` and
`#data` for results. Set continuation **before mounting**; completion freezes the
receipt. Continue leaves the card, simulating a next-card destination; it does not
run a scheduler or automatically choose another sample.

`#snapshot` saves the current provider record through the real work boundary,
with completed status stored separately in the host envelope. Restore it with `#restore` to test completed-card
UI without recording another try. The host tracks the latest successfully saved state; `saveWork(newState)` may
replace the previous object. Unsaved edits still require an explicit save. Providers declaring no saved work can be snapshotted, but restore
fresh rather than recovering transient input.
This explicit test snapshot is separate from production's completion-clears-draft
policy. The minimal starter restores no draft. Redo creates fresh state through the same
factory as a fresh mount, and exposes `context.redoOfAttemptId`. The saved echo fixture exercises disabled controls and continuation.

`cardView.mount` receives `root`, admitted `card`, `state`, lifecycle `context`,
`onError`, `onChange`, `onControlsChange`, and `onAppearanceChange`. The last two
are currently no-op hooks in the playground. Render only beneath `root`, and
release listeners/resources in the returned controller's `dispose()`.

## Contract authoring references

See the [Gargamelle API](https://hexdocs.pm/gargamelle/1.0.0/) for definitions, constraints,
contracts, and boundary functions. The generated starter pins the prepared host's
exact dependency versions and checksums; use its manifest rather than a version
number copied from a guide.

`npm ci` replaces `node_modules`. It is safe for source files but stop running
builds and development servers before reinstalling dependencies in an active checkout.

## SDK declaration and normalization

`defineCardType(manifest, declaration)` is the only raw-declaration reader.
The app registry and playground reject declarations not passed through it.
The [quickstart](../authoring/implementing-card-types.md) lists the small core and
optional capabilities. `providers/card-type-contract.js` and `card-api.d.ts`
describe the **normalized consumer interface**, not mandatory developer boilerplate.
Omitted math/review/offline hooks remain absent; consumers handle that absence.
Never supply fake success checks or empty math stubs to satisfy registration.

One `freshState(card)` factory creates new state, including restore fallbacks.
Work defaults to `mode: "run"`: drafts survive remounts within the active Run
only. Custom restore receives saved/current Run and Occurrence identities; the
host withholds foreign-Run work. Returning
`kind: 'fresh'` delegates to that factory. Default restore requires matching work
workVersion and successful work-codec validation. No work declaration means
no persisted payload, regardless of what the view keeps in memory.

The frozen default snapshot is `{schemaVersion:1, snapshotFormat:'card-sdk-v1',
cardId, type, learningVersion, weight, content}`. `content` is the canonical export;
weight is resolved before snapshotting. Custom snapshots preserve existing hashes.
Do not change this rule in place once a type has used it.

Registration is build-time. Manifest entry points generate facades and the registry;
package-local imports determine shipped modules. Course authors cannot install
executable types. The SDK is a small versioned source interface, not a separate
published package or a browser security boundary.

## History consumer lab

Open `/history` on the running playground (for example
`http://localhost:3022/history`; automated interaction belongs on the separate
`--test-state` origin). The **History consumer lab** link is also in the header.
It is available with built-in fixtures and with an external provider configuration.
This page runs a separate example consumer, not the selected card provider.

The example in `provider-dev/history-example.mjs` counts tries for one card,
either within a course or across courses. It declares both supported key schemes;
the host supplies the concrete `historyScope`. Its `detail` input selects a total
or counts by course. Changing detail deliberately requests originals, showing why
a digest's usefulness can depend on more than the history alone.

The lab starts with 1,600 synthetic tries, including the same card in two courses
and unrelated cards. Nothing is saved to disk, synced, or sent to a server. Reload
or **Reset synthetic history and digests** starts over. Evaluate twice to see
original blocks become cached digests. Choose a different scope to see independent
caches, then switch back to reuse the earlier one.

Fault controls exercise these cases:

- **Omit first block entry:** the consumer requests it. Even if that fetch succeeds,
  the initial delivery was incomplete, so the host cannot submit a digest update.
- **Fail original-block fetch:** the lab first caches the opposite detail to ensure
  a request is needed. The forced second call returns an incomplete output and no
  replacements; the host withholds the proposal.
- **History changes before commit:** an early try is inserted into the selected
  scope. Changed block hashes discard affected digests, and the old proposal fails.
- **Competing digest commit:** the lab first caches opposite detail, then runs two
  evaluations. One changes the cached digests; the other proposal is stale.

Both displayed outputs refer to the same opening snapshot. A race may change the
current history afterward; a matching output does not make a stale write valid.
The report shows block kinds, requests, call count, input certification, and commit
status. Stable automation IDs are `#scope`, `#detail`, `#fault`, `#evaluate`,
`#reset-history`, `#history-status`, `#history-report`, `#history-comparison`, and
`#history-replacements`.

### Testing another consumer

`provider-dev/history-lab.mjs` exports `createHistoryLab(consumer, records)` for
browser or Node tests. It accepts the app's existing consumer interface:
`id`, `version`, `keyScheme`, optional `supportedKeySchemes`, `acceptsDigest`, and
`evaluate(input, {blockCount, entries, force})`. Entries contain original blocks
or cached digests (including explicit null). Evaluation returns either
`{kind: 'needs-originals', blocks}` or `{kind: 'ready', output, replacements}`.
A forced call must return ready, possibly with a degraded output and no replacements.

```js
const lab = createHistoryLab(myConsumer, syntheticTries);
const snapshot = await lab.open(input);
const evaluated = await lab.evaluate(input, snapshot);
assert.deepEqual(evaluated.output, await lab.direct(input));
const receipt = await lab.commit(input, evaluated.proposal);
```

The records are the host's interpreted try views consumed by existing history
components, not a new persisted student-record format. The harness reuses production
snapshot preparation, hashing, host evaluation, and full-history evaluation.
Its serialized in-memory commits model compare-and-swap, but **do not test** D1,
SQL transactions, authentication, HTTP, receipt replay, or production retention.
Use the existing history-digest server/D1 tests for those guarantees.

See `tests/provider-history-lab.test.mjs` for scope isolation, rehydration, rejected
writes, out-of-order insertion, and growth-partition comparisons. Run with
`node --test tests/provider-history-lab.test.mjs` after host preparation. These
finite comparisons are regression tests, not proof of path independence.

### Registration contract

`providers/card-type-contract.js` declares the required and optional card-type,
view and instance capabilities. `providers:check` validates registration and view
shape before checking samples, reporting all missing members together. The host's
registered-type tests use the same declaration. A standalone practice view may
omit catalog previews; the adapter supplies a plain title/prompt preview. See the
"Registration vocabulary and executable contract" section of `providers/README.md`
for the boundaries and conditional requirements. These shape checks do not replace
content/work/result validation or behavioral tests.

## Standard card shell

Import `standardCardView` from `@flashcards/provider-sdk/v1/view` and export
`standardCardView({mount})`. The inner mount receives an empty child root. The
shell renders the prompt and navigation controls, applies appearance, forwards
history, and supplies generic previews and restart behavior. The host renders
the page title; do not repeat it inside the shell. No `borderTarget`, prompt CSS
selector, preview footprint, or custom restart is required. History decoration
is opt-in via the second argument `{history:{interpret, style:'candy'}}` and
requires the card type to declare a history consumer separately.

Bare views remain supported: mount options include `actions.previous`,
`actions.redo`, `actions.canRedo`, and `context.advance`. They own the controls
that invoke these capabilities. The adapter's restart implementation alone does
not create a button. Previews may return a `footprint` of `{columns, rows,
compact:{columns, rows}}`; omit previews to use the SDK default.

When registering a generated provider, preserve its source files and SDK imports.
Add its manifest to `providers/catalog.js` with its repository-relative
`directory`. `contractsEntry` names its Gleam source (default `contracts.gleam`),
and `gleamModule` names the compiled module. Renaming that module requires updating
its source filename and manifest, then rebuilding; generated facades are not hand-edited.
Schema functions receive the manifest type ID in both the kit and app builds.
The shared `src/card_header.gleam` copy is pinned SDK source: checks reject drift.

Run `npm run test:sdk-registration` in the app checkout to create a clean temporary
app, scaffold and register a provider without editing its sources, build from
scratch, import a course, and exercise its visible controls in Chromium. It uses
test port 4031 and removes the temporary app afterward.

### Generated sources and Gargamelle 1.0.0 migration

Host builds reconcile their generated Gleam source list before compilation, removing obsolete owned copies and ignoring copies regardless of module name. Do not clean authored sources to repair a generated-file error.

The earlier published Gargamelle 0.10.0 artifact was replaced during development. The current checkout uses the published 1.0.0 release. Older kits may use `text`, `boundary_definition` or other pre-rename APIs. Regenerate a starter against the current prepared host and migrate to `string`, `definition` (or the boundary-specific accessor), `DefinitionError`, `ValidationError`, and `JsonLayout`. The host lockfile pins the 1.0.0 release checksum. Future API changes require a new immutable dependency release; the SDK does not publish Gargamelle.

`freshState(card)` may use randomness. It is called for genuinely new work, Redo and restore fallbacks, not to reconstruct valid saved work or repaint the card. Save randomized choices as part of the work payload if they must survive reload.


### Current card progress queries

Ask the normalized card type for `historyDepth(card, environment)` and
`tryWeight(card, environment)` after supplying the environment. Both are
synchronous. SDK defaults are depth 10 and the card's authored weight (or 1).
Custom answers must be integers: depth 1–100, weight 1–4. All built-in card types
currently use depth 10. The host serializes the resolved numbers for catalog and
history counting; it does not infer depth from rendered border geometry.
Historical Try weights remain unchanged. Completion policy uses one unweighted
slot per card independently of its depth. These queries do not change stored
provider results or introduce outcome vectors.
