diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml
index 7b5acdb..4623ba1 100644
--- a/.github/workflows/docs.yml
+++ b/.github/workflows/docs.yml
@@ -1,7 +1,6 @@
name: Docs
-# Checks the documentation on every pull request. GitHub Pages publishing remains enabled during the
-# Read the Docs transition; see docs/index.md for the cutover and old-URL redirect steps.
+# Read the Docs hosts the site. This workflow only validates documentation changes.
on:
pull_request:
@@ -18,26 +17,13 @@ jobs:
- uses: actions/checkout@v4
- uses: astral-sh/setup-uv@v6
- run: uv sync --locked --group docs
+ - uses: actions/setup-node@v4
+ with:
+ node-version: "24"
+ - run: npm ci --ignore-scripts
+ - run: npm test
- run: uv run --group docs pytest -q docs/tests
- run: uv run --group docs python docs/catalogue.py
- run: uv run ruff check docs
- run: uv run ruff format --check docs
- run: uv run --group docs mkdocs build --strict
- - if: github.event_name == 'push'
- uses: actions/upload-pages-artifact@v3
- with:
- path: site
-
- deploy:
- if: github.event_name == 'push'
- needs: build
- runs-on: ubuntu-latest
- permissions:
- pages: write
- id-token: write
- environment:
- name: github-pages
- url: ${{ steps.deployment.outputs.page_url }}
- steps:
- - id: deployment
- uses: actions/deploy-pages@v4
diff --git a/.gitignore b/.gitignore
index b17017b..d51a596 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,3 +7,6 @@ __pycache__/
build/
dist/
site/
+
+.cache/
+node_modules/
diff --git a/README.md b/README.md
index 4b0dafe..b0753cc 100644
--- a/README.md
+++ b/README.md
@@ -22,7 +22,11 @@ Browse the [algorithm catalogue](https://meds-algorithm.readthedocs.io/en/latest
for implementations, reviewed installation commands and validation evidence. Register or update an
entry through `catalogue/algorithms.yaml`; documentation builds and release observations are independent
of the runtime package and never query private source repositories. See
-[site maintenance](https://github.com/McDermottHealthAI/meds-algorithm/blob/main/docs/index.md).
+[site maintenance](https://meds-algorithm.readthedocs.io/en/latest/documentation/).
+
+The [unified documentation](https://meds-algorithm.readthedocs.io/en/latest/) also contains the
+template workflow, [implementation prompt builder](https://meds-algorithm.readthedocs.io/en/latest/prompt-builder/),
+manual tutorial, publishing guides and API/UML references.
## Package layout
@@ -142,8 +146,10 @@ training. Keep each algorithm's data-access and cluster approval rules in its ow
### Unreleased
+- Consolidate the template guides, implementation prompt and interactive builder on Read the Docs;
+ use Read the Docs as the only documentation host.
- Configure Read the Docs hosting with the existing MkDocs theme and docs dependency group; update
- documentation links and document the transition from GitHub Pages.
+ documentation links and document Read the Docs hosting.
- Host the algorithm catalogue and its release-observation workflow in this ecosystem repository.
- Add independently built documentation; catalogue metadata and tooling are excluded from Python distributions.
diff --git a/docs/assets/prompt-builder.css b/docs/assets/prompt-builder.css
new file mode 100644
index 0000000..c7da175
--- /dev/null
+++ b/docs/assets/prompt-builder.css
@@ -0,0 +1,19 @@
+.prompt-builder { --pb-line: var(--md-default-fg-color--lightest, #dce5eb); --pb-bg: var(--md-default-bg-color, #fff); --pb-ink: var(--md-default-fg-color, #182b3d); color: var(--pb-ink); }
+.prompt-builder fieldset { min-width: 0; border: 1px solid var(--pb-line); border-radius: 8px; margin: 1.6em 0; padding: 1em 1.25em; }
+.prompt-builder legend { padding: 0 .4em; font-weight: 700; }
+.prompt-builder label { display: block; margin: .8em 0; font-weight: 600; }
+.prompt-builder .pb-hint { display: block; font-size: .86em; font-weight: 400; opacity: .8; margin: .3em 0; }
+.prompt-builder input:not([type="checkbox"]), .prompt-builder select, .prompt-builder textarea { display: block; width: 100%; min-width: 0; margin-top: .4em; padding: .65em .75em; border: 1px solid var(--pb-line); border-radius: 5px; color: var(--pb-ink); background: var(--pb-bg); font: inherit; font-weight: 400; }
+.prompt-builder input:not([type="checkbox"]) { line-height: 1.4; }
+.prompt-builder textarea { resize: vertical; line-height: 1.5; }
+.prompt-builder [data-prompt-output] { font: .85em/1.6 Consolas, monospace; white-space: pre-wrap; }
+.prompt-builder .pb-check { display: flex; align-items: baseline; gap: .6em; font-weight: 400; }
+.prompt-builder input[type="checkbox"] { flex: 0 0 auto; width: 1em; height: 1em; }
+.prompt-builder .pb-actions { display: flex; flex-wrap: wrap; gap: .7em; margin: 1em 0; }
+.prompt-builder button { padding: .6em 1em; border: 1px solid var(--pb-line); border-radius: 5px; color: var(--pb-ink); background: var(--pb-bg); cursor: pointer; font: inherit; }
+.prompt-builder [data-generate] { background: #116b7b; color: #fff; border-color: #116b7b; }
+.prompt-builder button:disabled { opacity: .45; cursor: not-allowed; }
+.prompt-builder :focus-visible { outline: 3px solid #208bba; outline-offset: 3px; }
+.prompt-builder .pb-status { min-height: 1.6em; }
+.prompt-builder [hidden] { display: none !important; }
+@media (max-width: 600px) { .prompt-builder fieldset { padding: .75em; } }
diff --git a/docs/assets/prompt-builder.js b/docs/assets/prompt-builder.js
new file mode 100644
index 0000000..57ba30f
--- /dev/null
+++ b/docs/assets/prompt-builder.js
@@ -0,0 +1,173 @@
+/* No network calls or persisted inputs: the documentation embeds the canonical implementation prompt. */
+(function () {
+ "use strict";
+ const profiles = ["supervised", "finetune", "probe", "zero_shot_direct", "zero_shot_materialized", "predict_only"];
+ const scopes = {
+ local: "Implementation and local tests only.",
+ integration: "Implementation, local tests and MEDS-DEV integration; stop before the demo.",
+ full: "Implementation, local tests, MEDS-DEV integration and preparation for demo/full-data evaluation; wait for the existing execution approvals."
+ };
+ const clean = (value) => String(value ?? "").trim();
+ function required(value, label) {
+ const result = clean(value);
+ if (!result) throw new Error(`Supply ${label}.`);
+ return result;
+ }
+ function choice(value, allowed, label) {
+ if (!allowed.includes(value)) throw new Error(`Choose a valid ${label}.`);
+ return value;
+ }
+ function renderPrompt(template, values) {
+ const source = choice(values.source_kind, ["paper", "code", "both"], "source type");
+ const destination = choice(values.destination_kind, ["local", "github"], "destination");
+ const mode = choice(values.profile_mode, ["automatic", "manual"], "profile selection");
+ const tasks = choice(values.tasks_mode, ["none", "ready"], "task-input option");
+ const scope = choice(values.scope, Object.keys(scopes), "work scope");
+ if (values.exploratory_mode !== undefined && typeof values.exploratory_mode !== "boolean") {
+ throw new Error("Exploratory mode must be an explicit checkbox selection.");
+ }
+ let repository = "New local Git repository only; do not create a GitHub repository.";
+ if (destination === "github") {
+ const name = required(values.github_repo, "the new GitHub repository")
+ .replace(/^https:\/\/github\.com\//, "").replace(/\/$/, "");
+ if (!/^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\/[A-Za-z0-9_.-]+$/.test(name)
+ || [".", ".."].includes(name.split("/")[1])) {
+ throw new Error("Use owner/name or https://github.com/owner/name for the new repository.");
+ }
+ const visibility = choice(values.visibility, ["private", "public"], "repository visibility");
+ repository = `New GitHub repository: https://github.com/${name}; visibility: ${visibility}.`;
+ }
+ let selection = "automatic";
+ if (mode === "manual") {
+ const selected = Array.isArray(values.profiles) ? [...new Set(values.profiles)] : [];
+ if (!selected.length || selected.some((name) => !profiles.includes(name))) {
+ throw new Error("Select at least one supported profile.");
+ }
+ selection = `Explicit profiles: ${selected.join(", ")}.`;
+ }
+ let bundle = "Not supplied. Continue implementation and synthetic tests; defer evaluation on external task bundles.";
+ if (tasks === "ready") {
+ required(values.dataset, "the dataset name, revision and MEDS path for these tasks");
+ bundle = [
+ `Prepared labels: ${required(values.labels_path, "the prepared labels location")}`,
+ `Prepared task configs: ${required(values.configs_path, "the prepared task-config location")}`,
+ `Bundle revision/identifier: ${required(values.bundle_revision, "the bundle revision or identifier")}`,
+ `Task subset: ${clean(values.task_subset) || "All tasks already present in this bundle."}`
+ ].join("\n");
+ }
+ const replacements = {
+ PAPER_REFERENCES_OR_NOT_SUPPLIED: source === "code" ? "Not supplied." : required(values.papers, "at least one paper reference"),
+ CODE_REFERENCES_OR_NOT_SUPPLIED: source === "paper" ? "Not supplied." : required(values.code, "at least one code/repository reference"),
+ NEW_REPOSITORY_DESTINATION: repository,
+ NEW_LOCAL_REPOSITORY_PATH: required(values.local_path, "a new local repository path"),
+ PROFILE_SELECTION: selection,
+ DATASET_CONTEXT_OR_NOT_SUPPLIED: clean(values.dataset) || "Not supplied; use synthetic data for local implementation tests.",
+ PREPARED_TASK_BUNDLE_OR_NOT_SUPPLIED: bundle,
+ WORK_SCOPE: scopes[scope],
+ SCIENTIFIC_AMBIGUITY_MODE: values.exploratory_mode === true
+ ? "Exploratory mode explicitly enabled: provisional algorithm-design assumptions are permitted under the policy below."
+ : "Confirmation required (default): ask before implementing material unresolved scientific choices.",
+ ADDITIONAL_CONSTRAINTS_OR_NONE: clean(values.constraints) || "None."
+ };
+ return template.replace(/<([A-Z][A-Z0-9_]*)>/g, (token, key) => {
+ if (!Object.hasOwn(replacements, key)) throw new Error(`Unknown prompt field: ${token}`);
+ return replacements[key];
+ });
+ }
+ function init(root) {
+ if (root.dataset.initialized) return;
+ const source = root.querySelector("[data-prompt-template]");
+ if (!source) return;
+ const template = JSON.parse(source.textContent);
+ const form = root.querySelector("[data-builder-form]");
+ const output = root.querySelector("[data-prompt-output]");
+ const status = root.querySelector("[data-status]");
+ const copy = root.querySelector("[data-copy]");
+ const download = root.querySelector("[data-download]");
+ const generate = root.querySelector("[data-generate]");
+ const reset = root.querySelector("[data-reset]");
+ root.dataset.initialized = "true";
+ let stale = true;
+ const field = (name) => form.elements.namedItem(name);
+ function section(name, visible, requiredNames = []) {
+ const block = root.querySelector(`[data-section="${name}"]`);
+ block.hidden = !visible;
+ block.querySelectorAll("input, textarea, select").forEach((input) => {
+ input.disabled = !visible;
+ input.required = visible && requiredNames.includes(input.name);
+ });
+ }
+ function update() {
+ section("papers", field("source_kind").value !== "code", ["papers"]);
+ section("code", field("source_kind").value !== "paper", ["code"]);
+ section("github", field("destination_kind").value === "github", ["github_repo"]);
+ section("profiles", field("profile_mode").value === "manual");
+ const ready = field("tasks_mode").value === "ready";
+ section("tasks", ready, ["labels_path", "configs_path", "bundle_revision"]);
+ field("dataset").required = ready;
+ }
+ form.addEventListener("input", () => {
+ update();
+ stale = true;
+ copy.disabled = download.disabled = true;
+ status.textContent = output.value ? "Inputs changed. Generate again to update the prompt; existing edits remain below." : "Fill in the inputs, then generate your prompt.";
+ });
+ form.addEventListener("submit", (event) => {
+ event.preventDefault();
+ if (!form.reportValidity()) return;
+ const data = new FormData(form);
+ const values = Object.fromEntries(data.entries());
+ values.profiles = data.getAll("profiles");
+ values.exploratory_mode = field("exploratory_mode").checked;
+ try {
+ output.value = renderPrompt(template, values);
+ output.readOnly = false;
+ stale = false;
+ copy.disabled = download.disabled = false;
+ status.textContent = "Prompt ready. Review or edit it, then copy or download.";
+ } catch (error) {
+ copy.disabled = download.disabled = true;
+ status.textContent = error.message;
+ }
+ });
+ output.addEventListener("input", () => {
+ download.disabled = copy.disabled = stale || !output.value.trim();
+ });
+ copy.addEventListener("click", async () => {
+ try {
+ await navigator.clipboard.writeText(output.value);
+ status.textContent = "Prompt copied.";
+ } catch (_) {
+ output.focus();
+ output.select();
+ status.textContent = "Clipboard access is unavailable. The prompt is selected; use Ctrl+C or Command+C.";
+ }
+ });
+ download.addEventListener("click", () => {
+ const url = URL.createObjectURL(new Blob([output.value], {type: "text/plain;charset=utf-8"}));
+ const anchor = document.createElement("a");
+ anchor.href = url;
+ anchor.download = "meds-algorithm-implementation.txt";
+ anchor.click();
+ setTimeout(() => URL.revokeObjectURL(url), 0);
+ });
+ reset.addEventListener("click", () => {
+ form.reset();
+ stale = true;
+ update();
+ output.value = "";
+ output.readOnly = true;
+ copy.disabled = download.disabled = true;
+ status.textContent = "Reset. Fill in the inputs, then generate your prompt.";
+ });
+ update();
+ generate.disabled = reset.disabled = false;
+ }
+ if (typeof module !== "undefined" && module.exports) module.exports = {renderPrompt, init};
+ if (typeof document !== "undefined") {
+ const start = () => document.querySelectorAll("[data-prompt-builder]").forEach(init);
+ if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", start);
+ else start();
+ if (typeof document$ !== "undefined") document$.subscribe(start);
+ }
+})();
diff --git a/docs/concepts.md b/docs/concepts.md
new file mode 100644
index 0000000..efbe2db
--- /dev/null
+++ b/docs/concepts.md
@@ -0,0 +1,207 @@
+# Concepts
+
+This page walks through the objects the contract talks about, in the order data flows through an algorithm:
+the dataset, the task, the predicates, the task specification (zero-shot only), the artifacts each
+command publishes, the final predictions, and the measurements attached to all of them.
+
+## The MEDS dataset and its splits
+
+The input data is a split-sharded [MEDS](https://medical-event-data-standard.github.io/) dataset, passed
+as `external_meds_dir`. MEDS fixes what `subject_id`, `time`, `code`, the value columns, static events
+(`time = null`) and code metadata mean; an algorithm may not reinterpret them.
+
+The dataset comes with three splits: `train`, `tuning` and `held_out`. They are a **boundary**:
+
+!!! warning "Fit population statistics on `train` only"
+ Anything fitted over a population — vocabularies, code frequencies, quantile bins, normalization
+ constants, feature selections — must be fitted on the training split alone. Fitting over all splits is
+ *transductive leakage*. It is easy to miss because it is not label leakage: code frequencies do not
+ depend on labels, so an algorithm can pass every label-leakage check and still carry it. If preprocessing
+ is delegated upstream and the scope is not yours to control, declare which quantity was fitted over
+ which population.
+
+The generated end-to-end test checks this: it plants a canary code in every tuning and held-out subject of
+its fixture, and none may appear among the codes the algorithm fitted statistics for (see the
+[FAQ](faq.md#how-do-the-tests-catch-label-leakage-and-transductive-fitting)).
+
+The MIMIC-IV demo in MEDS form is the canonical real-data example used by the tests; it is not a separate
+schema.
+
+## The task index (built upstream)
+
+An upstream task extraction can store both keys and outcomes. Inference/scoring receives its key-only
+view as `external_index_dir`; training receives permitted targets through `external_labels_dir`:
+
+- **keys**: `(subject_id, prediction_time)`, the rows to predict, in every split;
+- **labels**: a value column such as `boolean_value`.
+
+### Who reads which labels
+
+Keys identify where to predict; ground-truth values describe what happened. They are not interchangeable.
+The [canonical argument table](reference/spec.md#step-arguments-and-artifacts) defines each step's access.
+Inference and ordinary scoring read only keys. The core index reader projects those columns at Parquet
+read time, even when MEDS-DEV supplies a directory whose files also contain outcomes.
+
+The index is never built in the algorithm repository. One ACES extraction, run upstream, applies the task's
+trigger, inclusion/exclusion criteria and splits, so every algorithm scores exactly the same rows:
+
+| Run | Who builds the index |
+|---|---|
+| MIMIC-IV demo (smoke test) | MEDS-DEV's `meds-dev-task`, task `mortality/in_icu/first_24h` |
+| Full-data evaluation | a shared, reviewed task bundle for the target dataset, built once upstream: clinical tasks defined and extracted with [ACES](https://eventstreamaces.readthedocs.io/), or randomly sampled code-by-horizon tasks (generated with [meds-random-task-sampler](https://github.com/florian6973/meds-random-task-sampler) and selected with [meds-task-selection](https://github.com/florian6973/meds-task-selection)), containing each task's definition and its per-task index and labels |
+
+Every algorithm compared on a dataset uses the same bundle. Zero-shot runs additionally need each task's ACES
+criteria file.
+
+An algorithm repository must not re-extract, filter or extend the index. If an algorithm rebuilt the cohort itself,
+two algorithms could silently be evaluated on different patients, and a zero-shot algorithm would read the labels
+it is supposed to be blind to.
+
+### Reading labels: the one rule
+
+The contract rule is: evaluated-split labels are never read, and only `train_supervised` / `train_finetune` / `train_probe`
+and a `predict_only` in-context learner read train/tuning labels. There is exactly one sanctioned exception: once every probability is final, `predict` may join the label column onto the predictions by
+key (`attach_ground_truth`), because meds-evaluation reads ground truth from the predictions file. Nothing
+computed from that join may feed back into a prediction.
+
+## Dataset predicates
+
+Tasks are written against named *predicates* (for example `icu_admission`, `death`, or
+`abnormally_low_sodium` with a value threshold). A dataset's predicates file binds those names to that
+dataset's codes. It is passed as `external_predicates_file` (MEDS-DEV's `{predicates_path}`).
+
+- When MEDS-DEV provides predicates for a dataset, reuse them; the MIMIC-IV demo must use MEDS-DEV's
+ MIMIC-IV predicates.
+- The algorithm decides whether and how to use them: selecting tokens, building SQL or columns, matching
+ events directly, or not at all.
+- Any command that consumes the file records its digest and origin in its manifest.
+- An algorithm that relies on particular predicate names declares and validates them in its own configuration.
+ The contract deliberately has no generic "predicate features" format.
+
+### Additional feature predicates per dataset
+
+Every generated configuration inherits optional `additional_predicates_file` from `AlgorithmConfig`.
+Select the dataset configuration explicitly, for example `config_file=/repo/dataset_configs/mimic_iv.yaml`:
+
+```yaml
+additional_predicates_file: ../predicates/mimic_iv_additional.yaml
+```
+
+Paths resolve relative to the configuration file. The additional file has the same predicate-only
+shape as MEDS-DEV's dataset file:
+
+```yaml
+predicates:
+ algorithm_specific_event:
+ code: YOUR_DATASET_EVENT_CODE
+```
+
+During `preprocess_data`, core combines this file with `external_predicates_file`, or uses it alone if
+no base was supplied. Duplicate names are errors even if their definitions agree; duplicate YAML keys
+and task/cohort sections are also rejected. Expression semantics and dataset compatibility remain the
+algorithm's responsibility. The runner passes the resolved path as `request.predicates_file` to both
+the compatibility hook and preprocessing. Implementations must read that path rather than merge files.
+
+Core saves `resolved_feature_predicates.yaml` in the prepared-data artifact, records both source paths
+and content digests plus the resolved digest, and includes them in the configuration digest. The source
+additions file can be temporary: later steps use persisted features and do not reopen or merge it.
+Keep the same configuration across the lifecycle; use a separate config file for each dataset.
+
+These are feature additions only. They never modify `TaskSpec`, evaluated labels, or the cohort. Task
+predicates continue to reach only the task-conditioned commands through the original task binding.
+Preprocessing must not include outcome-dependent definitions or read events beyond each permitted cutoff.
+For a changed target or cohort, update the shared upstream task bundle instead.
+
+## The task specification (zero-shot only)
+
+A supervised algorithm learns *what* to predict from labels. A zero-shot algorithm never sees labels, so the task
+itself must be an input. The task language is [ACES](https://eventstreamaces.readthedocs.io/): a criteria
+file passed as `external_task_criteria_file`, bound to the dataset predicates. The pair is the **task
+specification** (`TaskSpec`).
+
+```mermaid
+flowchart LR
+ crit[ACES criteria file e.g. mortality/in_icu/first_24h.yaml] --> spec[TaskSpec]
+ pred[Dataset predicates e.g. MIMIC-IV predicates.yaml] --> spec
+ spec --> digest["semantics_digest sha256 of criteria + predicates"]
+```
+
+The **semantics digest** hashes the criteria bytes together with the predicates bytes. MEDS-DEV task files
+leave dataset codes as `???`, so the same criteria bound to MIMIC-IV and to eICU predicates are different
+tasks with different digests. Every task-conditioned artifact records this digest, so an artifact can never
+be silently reused for another task. See [Zero-shot in practice](zero-shot.md).
+
+## Artifacts and the manifest envelope
+
+Every command publishes one **artifact**: a directory containing whatever payload the algorithm wants plus a
+`manifest.yaml` that follows a fixed envelope.
+
+```mermaid
+flowchart LR
+ p[preprocess_data] -->|patients| pt[pretrain]
+ pt -->|pretrained_algorithm| i[infer_embeddings]
+ i -->|embeddings| st[train_probe]
+ st -->|probe_algorithm| pr[predict_probe]
+ pr -->|predictions| out[(final output)]
+```
+
+*(The `probe` profile shown; other profiles skip some commands. See [Choosing a profile](profiles.md).)*
+
+| Artifact type | Produced by | Meaning |
+|---|---|---|
+| `patients` | `preprocess_data` | the algorithm's own representation of the dataset |
+| `pretrained_algorithm` | `pretrain` | a task-independent algorithm |
+| `embeddings` / `trajectories` | `infer_embeddings` / `infer_trajectories` | separate task-independent representations and generated futures |
+| `supervised_algorithm` / `finetuned_algorithm` / `probe_algorithm` | `train_supervised` / `train_finetune` / `train_probe` | a complete task-specific inference bundle |
+| `predictions` | `predict` | the normative final output |
+
+Four properties hold for every artifact:
+
+- **The payload format is the algorithm's.** The manifest declares it (`payload_format: name/version`), and
+ consumers reject an incompatible type, contract version or payload format *before* doing expensive work.
+- **Publication preserves complete artifacts.** The command writes its manifest last in unique staging.
+ New outputs appear by one rename. Overwrite retains the old output until replacement succeeds and
+ restores it on failure; readers may briefly see no destination during the two renames. Process crashes
+ can leave recovery files. See [publication behavior](reference/manifest.md).
+- **Inputs and configuration are traceable.** The manifest records stable identifiers or digests of its
+ inputs (including the predicates digest and, for task-conditioned artifacts, the task's provenance and
+ digest), a `config_digest` over the command's arguments and resolved settings, and the git commit and
+ dirty state of the code that produced it.
+- **Artifacts are never nested.** Each artifact is its own directory; `infer_embeddings`, for example, writes a
+ sibling of the data artifact rather than a subdirectory of it, so runs over different indexes cannot
+ overwrite each other.
+
+Core's `StepRunner` owns this work through `measured_artifact(...)`; algorithm methods write payloads into
+the supplied staging directory. See the [manifest reference](reference/manifest.md).
+
+## Final predictions
+
+`predict` writes `predictions.parquet` in the
+[meds-evaluation](https://github.com/kamilest/meds-evaluation) prediction schema of the version MEDS-DEV
+evaluates with (currently `meds-evaluation==0.0.3`, checked with `validate_binary_classification_schema`):
+
+- exactly **one row per requested key**, with **unique keys**;
+- row order means nothing and must never be used to match outputs to keys;
+- conformance tests compare the written keys directly with the requested index — a self-reported count is
+ not proof of coverage;
+- rows may be left out only under an explicitly declared exclusion policy that lists the excluded keys;
+- every parquet file in the predictions artifact is read as predictions (MEDS-DEV evaluates
+ `**/*.parquet`), so supporting tables use another format.
+
+For zero-shot algorithms, predictions are always evaluated against the labels of the *requested* task, and the
+predictions artifact carries or references the `relaxations.yaml` describing what the algorithm actually
+answered.
+
+## Measurements
+
+Every command invocation records its resource use in the manifest, wherever it runs (tests, MEDS-DEV,
+SLURM):
+
+- **wall time** on a monotonic clock;
+- **memory** sampled over the whole process tree; on Linux, PSS (which apportions shared pages) is the
+ comparison value and RSS is kept as a diagnostic;
+- **GPU** peak allocated/reserved memory when measured;
+- optional work units (subjects, events, rows, optimizer steps).
+
+`null` means *not measured*; `0` means *measured, nothing used*. Measurements are observations for
+comparing algorithms, never pass/fail thresholds.
diff --git a/docs/core-package.md b/docs/core-package.md
new file mode 100644
index 0000000..1034c77
--- /dev/null
+++ b/docs/core-package.md
@@ -0,0 +1,25 @@
+# Shared core package
+
+The core lives in its own [repository](https://github.com/McDermottHealthAI/meds-algorithm), pinned by the template to PyPI version `0.4.0a5`.
+See its [layout and usage](https://github.com/McDermottHealthAI/meds-algorithm/blob/v0.4.0a5/README.md) for its artifact, runtime, task, evaluation, integration and conformance APIs.
+The [specification](reference/spec.md) and [architecture and UML](reference/architecture.md) are
+rendered directly from this core checkout, the same sources included in its distributions.
+The `latest` documentation follows core `main`; generated algorithms use their pinned installed release.
+
+`AlgorithmConfig` is the shared configuration parent. Neural implementations can extend `NNConfig`;
+the [neural configuration and scaling guide](reference/architecture.md#neural-network-configuration-and-scaling-experiments)
+shows a concrete subclass, YAML settings and a capacity sweep. It also explains why data-subset selection
+belongs upstream and which measurements an algorithm must report for a later scaling-law analysis.
+The template keeps this example in the core guide rather than maintaining a second specification.
+
+Family-specific sharing belongs in one algorithm-family repository with multiple profiles and shared internal
+modules. Tokenizers, neural architectures, objectives and algorithm-specific task translators stay there.
+
+Generated repositories import `meds_algorithm` directly. Their package contains a typed algorithm
+implementation and an algorithm-owned immutable configuration. `tests/e2e.py` invokes the same shared runner
+as the CLI and supplies fitted-feature inspection hooks.
+Reusable assertions, fixtures and MEDS-DEV provisioning live in core. No compatibility package is copied.
+
+Publication uses exclusive writers and overwrite rollback. Algorithm provenance must be supplied explicitly;
+the installed package cannot infer an algorithm checkout. See the core README for crash recovery, reader
+visibility during overwrite, optional dependencies, and measurement limits.
diff --git a/docs/documentation-tests.md b/docs/documentation-tests.md
new file mode 100644
index 0000000..2b8956f
--- /dev/null
+++ b/docs/documentation-tests.md
@@ -0,0 +1,40 @@
+# Documentation tests
+
+Documentation tests run separately from the installed runtime suite. They do not train algorithms,
+access clinical data, or establish scientific validity.
+
+Run `uv run --group docs pytest -q docs/tests` and, with Node 24, `npm ci --ignore-scripts && npm test`.
+The strict MkDocs build additionally validates page links, anchors, snippets, template-source hashes
+and rendered reference pages. See [site maintenance](documentation.md) for the full commands.
+
+## Python source and rendering tests
+
+| Test | What it checks | Why |
+|---|---|---|
+| Canonical prompt embedding | Decodes embedded JSON and compares it with the static prompt's text block | Keep the copyable and interactive prompts identical |
+| Release guide rendering | Renders the template source with example package names | Avoid showing unresolved Jinja placeholders |
+| Script boundary escaping | Embeds prompt text containing a script closer | Keep source text inert inside HTML |
+| Core reference sources | Compares contract, UML, test catalogue and orchestration with this checkout | Prevent stale installed-wheel docs from masking code changes |
+| Immutable source and cache | Checks the requested commit URL and verifies a cache hit avoids another fetch | Make template-owned guides reproducible and support offline rebuilds |
+| Corrupt downloaded/cached sources | Rejects content whose SHA-256 differs from the manifest | Never silently publish changed source content |
+| Mutable revision rejection | Rejects a branch name instead of a full commit SHA | Keep builds independent of moving template branches |
+| Download failure | Propagates unavailable-source errors | Fail instead of substituting stale or unrelated guidance |
+
+The [catalogue test inventory](catalogue-testing.md) documents its separate registry checks.
+
+## Browser tests
+
+The prompt builder uses plain JavaScript with no runtime dependencies, network requests or persisted
+form inputs. jsdom is used only in tests.
+
+| Test | What it checks | Why |
+|---|---|---|
+| All 144 input combinations | Source, destination, profiles, task bundle, scope and ambiguity mode | Preserve the user's choices and scientific/execution gates |
+| Ambiguity defaults | Missing/false mode requires confirmation; non-booleans fail | Prevent accidental exploratory opt-in |
+| Checkbox lifecycle | Unchecked initial state, explicit toggle, stale output and reset | Keep exploratory mode intentional |
+| Invalid plans | Missing sources, destination, profiles and prepared-task metadata | Avoid apparently executable incomplete prompts |
+| Task subsets and literal text | Existing task identifiers and non-recursive substitutions | Preserve supplied scope and constraints |
+| Conditional fields | Visibility, required fields and several selected profiles | Prevent hidden inputs from overriding user choices |
+| Edits, copy, download, reset | Exact edited text and stale-output invalidation | Prevent copying outdated instructions |
+| Clipboard fallback | Selection after denied clipboard access | Support local previews and restricted browser contexts |
+| Inert HTML and repeated initialization | HTML-like user text and repeated page initialization | Prevent injection and lost edits |
diff --git a/docs/documentation.md b/docs/documentation.md
new file mode 100644
index 0000000..e6a4c69
--- /dev/null
+++ b/docs/documentation.md
@@ -0,0 +1,60 @@
+# Maintaining documentation
+
+The full MEDS algorithms site is maintained in `McDermottHealthAI/meds-algorithm` and hosted at
+. `latest` follows core `main`; it may describe changes
+newer than the released core version pinned by an algorithm. Use its installed contract for that version.
+
+## One maintained source per document
+
+| Content | Canonical source |
+|---|---|
+| Concepts, profiles, workflow, tutorials, prompt builder and static prompt | This repository's `docs/` |
+| Contract, architecture/UML, shared tests and orchestration | Core's `src/meds_algorithm/*.md` and `ARCHITECTURE.md`, rendered directly from this checkout |
+| Catalogue | `catalogue/algorithms.yaml` and `catalogue/updates.json` |
+| Template contributor release/test guides | `RELEASING.md` and `TESTING.md` in the template repository |
+| Generated algorithm release/test guides | `template/RELEASING.md.jinja` and `template/docs/TESTING.md` in the template repository |
+
+The last two rows are included at build time from the immutable template commit recorded in
+`docs/template-source.json`. Each file is SHA-256 checked and cached under `.cache/template-docs/`.
+Only these public documentation files are fetched; the build does not clone private algorithms or run
+template code. A missing source or checksum mismatch fails the build. The cached files permit offline
+rebuilds, but a clean checkout needs network access for its first build.
+
+When template-owned guides change, update the revision and four hashes in `docs/template-source.json`
+in a core PR, then run the strict build. Keep their content in the template so generated projects and
+the documentation use the same instructions. Do not copy those files into this repository.
+
+The static implementation prompt lives in `docs/implementation-prompt.md`; the interactive builder embeds
+its text block. Edit that single source to update both. Template README links point here.
+
+## Local checks and preview
+
+From the root of this core checkout:
+
+```bash
+uv sync --locked --group docs
+uv run --group docs pytest -q docs/tests
+uv run ruff check docs
+uv run ruff format --check docs
+npm ci --ignore-scripts
+npm test
+uv run --group docs mkdocs build --strict
+uv run --group docs mkdocs serve
+```
+
+Node 24 is needed only for browser tests, not for building or serving the site. See
+[documentation tests](documentation-tests.md) and [catalogue tests](catalogue-testing.md) for what each checks.
+Runtime tests remain under `tests/`; their inventory is [Shared-package tests](reference/tests.md).
+
+## Hosting
+
+Read the Docs builds with `.readthedocs.yaml`, Python 3.12, uv's `docs` dependency group and MkDocs Material.
+`READTHEDOCS_CANONICAL_URL` supplies the version-specific canonical URL, with a `latest` fallback locally.
+GitHub Actions runs documentation checks independently. Enable Read the Docs pull request builds in the
+project settings for hosted previews. Older release tags without this configuration cannot build this site.
+
+Read the Docs is the only documentation host. The template repository has no documentation deployment
+workflow; all MkDocs and prompt-builder checks run here.
+
+The catalogue update workflow still needs permission for Actions to create pull requests; see
+[catalogue maintenance](implemented-algorithms.md#register-or-update-an-algorithm) for its report fallback.
diff --git a/docs/examples/manual-supervised.sh b/docs/examples/manual-supervised.sh
new file mode 100644
index 0000000..3c6255e
--- /dev/null
+++ b/docs/examples/manual-supervised.sh
@@ -0,0 +1,216 @@
+#!/usr/bin/env bash
+# --8<-- [start:setup]
+# A complete local tutorial. Prerequisites: Bash, Git, uv, and network access for dependencies.
+set -euo pipefail
+command -v git >/dev/null
+command -v uv >/dev/null
+
+# Use a NEW directory. Nothing is deleted or overwritten outside this tutorial.
+WORKSPACE="${1:-$PWD/manual-meds-example}"
+if [[ -e "$WORKSPACE" ]]; then
+ echo "Choose a new directory: $WORKSPACE already exists" >&2
+ exit 1
+fi
+mkdir -p "$WORKSPACE"
+cd "$WORKSPACE"
+WORKSPACE="$PWD"
+
+# 1. Render a named, single-profile repository from a reproducible template revision.
+cat > answers.yaml <<'YAML'
+algorithm_name: Manual baseline
+algorithm_slug: manual_baseline
+algorithm_class: ManualBaseline
+algorithm_description: Synthetic tutorial estimating training-label prevalence.
+profiles: [supervised]
+uses_predicates: true
+implementation_source: This tutorial; not a reproduction of a published clinical algorithm.
+YAML
+uvx --from 'copier==9.17.1' copier copy --defaults --trust \
+ --vcs-ref=55ddd290d20a39dd19954321580c616cc11a74ae \
+ --data-file answers.yaml \
+ https://github.com/McDermottHealthAI/MEDS_algorithm_template.git manual-baseline
+cd manual-baseline
+# --8<-- [end:setup]
+
+# --8<-- [start:environment]
+# 2. Create the Python environment and install the generated package and test dependencies.
+uv python install 3.11
+uv sync --python 3.11 --extra test
+uv run manual-baseline profiles
+uv run manual-baseline commands --profile supervised
+uv run meds-algorithm-spec > installed-contract.txt
+# --8<-- [end:environment]
+
+# 3. Implement the generated stubs manually. No agent or MEDS-DEV runner is involved.
+# --8<-- [start:configuration]
+cat > src/manual_baseline/config.py <<'PY'
+from dataclasses import dataclass
+from meds_algorithm import AlgorithmConfig
+
+
+@dataclass(frozen=True)
+class ManualBaselineConfig(AlgorithmConfig):
+ smoothing: float = 1.0
+
+ def validate(self):
+ if self.smoothing <= 0:
+ raise ValueError("smoothing must be positive")
+PY
+# --8<-- [end:configuration]
+
+# --8<-- [start:algorithm]
+cat > src/manual_baseline/manual_baseline.py <<'PY'
+import json
+from pathlib import Path
+
+import polars as pl
+import yaml
+
+from meds_algorithm import AlgorithmRepository, PayloadMetadata, SupervisedAlgorithm
+from meds_algorithm.requests import (
+ PreprocessDataRequest, TrainSupervisedRequest, PredictSupervisedRequest,
+)
+from .config import ManualBaselineConfig
+
+
+class ManualBaseline(SupervisedAlgorithm):
+ name = "manual_baseline"
+ config_type = ManualBaselineConfig
+
+ def preprocess_data(self, request: PreprocessDataRequest) -> PayloadMetadata:
+ events = pl.read_parquet(str(request.meds_dir / "data" / "*.parquet"))
+ events.write_parquet(request.output.directory / "events.parquet")
+ # Core supplies the composed feature predicates; keep its reserved file unchanged.
+ predicates = yaml.safe_load(request.predicates_file.read_text())["predicates"]
+ (request.output.directory / "summary.json").write_text(json.dumps({
+ "events": events.height, "predicate_names": sorted(predicates),
+ }))
+ return PayloadMetadata("tutorial-events")
+
+ def train_supervised(self, request: TrainSupervisedRequest) -> PayloadMetadata:
+ outcomes = request.labels.read("train")["boolean_value"]
+ if len(outcomes) == 0:
+ raise ValueError("Training labels must not be empty")
+ alpha = self.config.smoothing
+ probability = (outcomes.sum() + alpha) / (len(outcomes) + 2 * alpha)
+ (request.output.directory / "probability.json").write_text(json.dumps(probability))
+ return PayloadMetadata("tutorial-prevalence")
+
+ def predict_supervised(self, request: PredictSupervisedRequest) -> PayloadMetadata:
+ probability = json.loads((request.fitted_algorithm.directory / "probability.json").read_text())
+ request.index.read().with_columns(
+ pl.lit(probability).alias("predicted_boolean_probability")
+ ).write_parquet(request.output.directory / "predictions.parquet")
+ return PayloadMetadata("tutorial-predictions")
+
+
+IMPLEMENTATIONS = {"supervised": ManualBaseline}
+PROFILES = tuple(IMPLEMENTATIONS)
+# Keep the completion gate: this tutorial does not implement the full conformance adapters/report.
+STUB_PROFILES = set(PROFILES)
+
+
+def create_repository():
+ return AlgorithmRepository(IMPLEMENTATIONS, repo=Path(__file__).resolve().parents[2])
+PY
+# --8<-- [end:algorithm]
+
+# --8<-- [start:inputs]
+# 4. Create tiny synthetic MEDS events and an upstream label/index bundle.
+# Real work should reuse a reviewed task bundle, not derive labels inside the algorithm.
+mkdir -p inputs/meds/data inputs/labels dataset_configs predicates
+uv run python - <<'PY'
+from datetime import datetime
+import polars as pl
+
+pl.DataFrame({
+ "subject_id": [1, 2, 3, 4, 5],
+ "time": [datetime(2020, 1, 1)] * 5,
+ "code": ["DEMO//encounter"] * 5,
+ "numeric_value": [None] * 5,
+}, schema_overrides={"numeric_value": pl.Float64}).write_parquet("inputs/meds/data/events.parquet")
+for split, ids, outcomes in (
+ ("train", [1, 2, 3], [True, True, False]),
+ ("held_out", [4, 5], [True, False]),
+):
+ pl.DataFrame({
+ "subject_id": ids,
+ "prediction_time": [datetime(2020, 1, 2)] * len(ids),
+ "boolean_value": outcomes,
+ }).write_parquet(f"inputs/labels/{split}.parquet")
+PY
+cat > predicates/base.yaml <<'YAML'
+predicates:
+ encounter:
+ code: DEMO//encounter
+YAML
+cat > predicates/demo_additional.yaml <<'YAML'
+predicates:
+ demo_measurement:
+ code: DEMO//measurement
+YAML
+cat > dataset_configs/demo.yaml <<'YAML'
+smoothing: 1.0
+additional_predicates_file: ../predicates/demo_additional.yaml
+YAML
+# --8<-- [end:inputs]
+
+# --8<-- [start:paths]
+# 5. Run the complete supervised lifecycle, one independent process per step.
+CONFIG="$PWD/dataset_configs/demo.yaml"
+MEDS="$PWD/inputs/meds"
+LABELS="$PWD/inputs/labels"
+BASE_PREDICATES="$PWD/predicates/base.yaml"
+ARTIFACTS="$PWD/runs/manual/supervised/artifacts"
+# --8<-- [end:paths]
+
+# --8<-- [start:preprocess]
+uv run manual-baseline preprocess_data --profile supervised \
+ "config_file=$CONFIG" "external_meds_dir=$MEDS" \
+ "external_predicates_file=$BASE_PREDICATES" "output_data_dir=$ARTIFACTS/data"
+# --8<-- [end:preprocess]
+
+# --8<-- [start:train]
+uv run manual-baseline train_supervised --profile supervised \
+ "config_file=$CONFIG" "input_data_dir=$ARTIFACTS/data" \
+ "external_labels_dir=$LABELS" "output_supervised_algorithm_dir=$ARTIFACTS/algorithm"
+# --8<-- [end:train]
+
+# --8<-- [start:predict]
+uv run manual-baseline predict_supervised --profile supervised \
+ "config_file=$CONFIG" "input_data_dir=$ARTIFACTS/data" \
+ "input_supervised_algorithm_dir=$ARTIFACTS/algorithm" "external_index_dir=$LABELS" \
+ 'splits=[held_out]' "output_predictions_dir=$ARTIFACTS/predictions" \
+ "external_evaluation_labels_dir=$LABELS"
+# --8<-- [end:predict]
+
+# --8<-- [start:verify]
+# 6. Inspect and verify the outputs. Only the runner attaches the held-out truth after scoring.
+uv run python - <<'PY'
+from pathlib import Path
+import polars as pl
+import yaml
+from meds_algorithm import read_manifest
+from meds_algorithm.conformance.assertions import assert_prediction_schema
+from manual_baseline import ManualBaseline, ManualBaselineConfig
+
+root = Path("runs/manual/supervised/artifacts")
+predictions = pl.read_parquet(root / "predictions/predictions.parquet")
+assert predictions["subject_id"].to_list() == [4, 5]
+assert predictions["predicted_boolean_probability"].to_list() == [0.6, 0.6]
+assert predictions["boolean_value"].to_list() == [True, False]
+assert_prediction_schema(predictions)
+print(predictions)
+for stage in ("data", "algorithm", "predictions"):
+ manifest = read_manifest(root / stage)
+ assert (root / stage / "config.json").is_file()
+ assert (root / stage / "request.json").is_file()
+ print(stage, manifest["command"]["name"], manifest["resources"]["wall_seconds"])
+resolved = yaml.safe_load((root / "data/resolved_feature_predicates.yaml").read_text())
+assert set(resolved["predicates"]) == {"encounter", "demo_measurement"}
+config = ManualBaselineConfig.load(root / "algorithm/config.json")
+assert ManualBaseline(config).name == "manual_baseline"
+PY
+uv run pytest -q tests/test_contract.py tests/test_operations.py
+printf 'Tutorial completed in %s\n' "$PWD"
+# --8<-- [end:verify]
diff --git a/docs/faq.md b/docs/faq.md
new file mode 100644
index 0000000..d221e32
--- /dev/null
+++ b/docs/faq.md
@@ -0,0 +1,88 @@
+# FAQ
+
+## Why can't my algorithm build or filter its own cohort?
+
+Because then two algorithms could be evaluated on different patients and nobody would notice. The index and
+its labels come from one extraction run upstream (MEDS-DEV's `meds-dev-task` for the demo, a shared,
+reviewed task bundle for full data). An algorithm predicts every requested row; rows can be left out
+only under a declared exclusion policy that lists them.
+
+## My algorithm needs a statistic over the whole dataset. Can I compute it on all splits?
+
+No. Fit vocabularies, frequencies, bins and normalizers on `train` only. Computing them over all splits is
+transductive leakage: it uses held-out patients' data even though it never touches a label.
+
+## Why do some algorithms run in two Python environments?
+
+Because their dependencies cannot coexist. An algorithm's training stack may pin an older `meds` (for example
+femr 0.2.4 requires `meds==0.3.3`), while the ACES tooling a zero-shot adapter uses for task translation
+(aces-relaxations, es-aces ≥ 0.7.3) requires `meds ≥ 0.4`. The two sides can run in separate environments
+and exchange only files. The contract does not care how a command
+is executed, so this is allowed; document it in the repository.
+
+## What does it mean that a task is "refused"?
+
+A zero-shot algorithm must raise rather than answer a task it cannot pose; the command fails and writes no
+predictions. The common case is a direct algorithm given a task whose label is not *future-only* in
+aces-relaxations' structural sense — for example MEDS-DEV's `mortality/in_icu/first_24h`, whose `gap`
+window is anchored at the trigger and straddles the prediction time. A re-anchoring step makes it
+posable; see [Zero-shot in practice](zero-shot.md#windows-that-straddle-the-prediction-time).
+Materialized algorithms are not affected.
+
+## Why is the AUROC on the MIMIC-IV demo undefined (or meaningless)?
+
+The demo has 100 patients. For `mortality/in_icu/first_24h` the held-out split has a handful of rows and
+may have no positive label at all, in which case AUROC is undefined. Training rows cannot stand in for a
+pretrained algorithm: pretraining saw those patients' futures. The demo gate validates that the pipeline runs
+on real data — formats, scale transitions, coverage, resources — not how good the algorithm is. Performance
+comes from the full-data run.
+
+## My algorithm writes several files next to `predictions.parquet`. Is that allowed?
+
+Yes, with one rule: every parquet file in the predictions artifact must be a predictions file. MEDS-DEV
+evaluates every `**/*.parquet` under the predictions directory, and the key check does the same. Store
+supporting tables — a zero-shot query bundle, a coverage table — in another format such as Arrow IPC;
+`relaxations.yaml` and JSON files are fine.
+
+## How do the tests catch label leakage and transductive fitting?
+
+The end-to-end check validates the original run and a fresh full-lifecycle rerun:
+
+- **Label leakage:** every stage runs again with evaluated outcome columns removed (all outcomes for
+ zero-shot). Separate input roots remain separate; permitted training/context labels are retained.
+ Both runs use the recorded fixture seed and deterministic settings. They must produce the same keyed
+ scores within the contract's tolerance. Original and rerun probabilities are checked across every shard.
+- **Transductive fitting:** `meds_algorithm.conformance.signal.add_split_canaries` gives every tuning and held-out subject a
+ canary code that no training subject has. Your `fitted_codes(artifacts)` hook reports every code the
+ algorithm fitted a statistic for (vocabulary, frequencies, bins); no canary may appear in it.
+
+## Can a non-zero-shot algorithm use the ACES task?
+
+Only `predict_only` may accept optional `external_task_criteria_file` as provenance, with
+`semantics_digest: null`. Other non-zero-shot commands reject it. Supervised, finetune and probe algorithms
+learn the task from its labels.
+
+## What does `scripts/github-sync.sh` push?
+
+Only `runs//spec.yaml` (dataset name and counts, task, predicates digest), `runs//result.yaml`
+(status, git commit and dirty state, environment, SLURM job id, per-command resource summary) and
+`runs//manifests/*.yaml`, on a `runs//` branch with a draft PR. It never pushes
+predictions, labels, data, checkpoints, raw logs or metrics. The template computes no metrics at all:
+MEDS-DEV's evaluation step (meds-evaluation) does.
+
+## How do I bring template changes into an existing repository?
+
+Review your working tree, then run in the generated repository:
+
+```bash
+copier update --trust
+```
+
+The repository's `.copier-answers.yml` records the template source, revision and answers, so Copier can
+apply the template's changes as a three-way merge. Render from the Git URL rather than a local checkout so
+updates work on every machine.
+
+## Where is the authoritative rule for X?
+
+In the [specification](reference/spec.md), which this site renders from core's `src/meds_algorithm/CONTRACT.md`.
+Generated repositories' `SPEC.md` points to the contract in their installed core version.
diff --git a/docs/hooks.py b/docs/hooks.py
new file mode 100644
index 0000000..8a7ac61
--- /dev/null
+++ b/docs/hooks.py
@@ -0,0 +1,94 @@
+"""Render canonical core documents and immutable template-owned guides in one site."""
+
+import hashlib
+import json
+import re
+from pathlib import Path
+from urllib.request import urlopen
+
+from jinja2 import Environment, StrictUndefined
+
+
+class _TemplateGuides:
+ """Read hash-verified guide sources from a pinned public template commit."""
+
+ def __init__(self, root: Path):
+ self.root = root
+ self.manifest = json.loads((root / "docs/template-source.json").read_text(encoding="utf-8"))
+ if not re.fullmatch(r"[0-9a-f]{40}", self.manifest["revision"]):
+ raise ValueError("Template documentation source must pin a full commit SHA")
+
+ def read(self, name: str) -> str:
+ digest = self.manifest["files"][name]
+ revision = self.manifest["revision"]
+ cache = self.root / ".cache/template-docs" / revision / name
+ if not cache.resolve().is_relative_to((self.root / ".cache/template-docs").resolve()):
+ raise ValueError("Guide source must stay inside the documentation cache")
+ if cache.is_file():
+ content = cache.read_bytes()
+ else:
+ url = f"https://raw.githubusercontent.com/McDermottHealthAI/MEDS_algorithm_template/{revision}/{name}"
+ with urlopen(url, timeout=30) as response:
+ content = response.read()
+ if hashlib.sha256(content).hexdigest() != digest:
+ raise ValueError(f"Template guide checksum mismatch: {name}")
+ cache.parent.mkdir(parents=True, exist_ok=True)
+ cache.write_bytes(content)
+ return content.decode("utf-8")
+
+ def provenance(self) -> str:
+ revision = self.manifest["revision"]
+ return (
+ '!!! note "Template source version"\n'
+ f" Template-owned guides below come from [revision `{revision[:12]}`]"
+ f"(https://github.com/McDermottHealthAI/MEDS_algorithm_template/tree/{revision}). "
+ "Use your generated repository's guides for its exact version.\n\n"
+ )
+
+
+def on_page_markdown(markdown, page, **kwargs):
+ root = Path(__file__).resolve().parents[1]
+ source = page.file.src_uri
+ if source in {"publishing-algorithms.md", "releasing.md", "testing.md"}:
+ guides = _TemplateGuides(root)
+ if source == "publishing-algorithms.md":
+ guide = (
+ Environment(undefined=StrictUndefined)
+ .from_string(guides.read("template/RELEASING.md.jinja"))
+ .render(
+ algorithm_name="My Algorithm", algorithm_slug="my_algorithm", package_name="my-algorithm"
+ )
+ )
+ return markdown.replace("", guides.provenance() + guide)
+ if source == "releasing.md":
+ return markdown.replace(
+ "", guides.provenance() + guides.read("RELEASING.md")
+ )
+ return markdown.replace(
+ "", guides.provenance() + guides.read("TESTING.md")
+ ).replace("", guides.read("template/docs/TESTING.md"))
+ if source == "running.md":
+ return markdown.replace(
+ "",
+ (root / "src/meds_algorithm/ORCHESTRATION.md").read_text(encoding="utf-8"),
+ )
+ if source == "reference/spec.md":
+ return markdown + "\n\n" + (root / "src/meds_algorithm/CONTRACT.md").read_text(encoding="utf-8")
+ if source == "reference/architecture.md":
+ return (
+ (root / "ARCHITECTURE.md")
+ .read_text(encoding="utf-8")
+ .replace("(src/meds_algorithm/CONTRACT.md)", "(spec.md)")
+ )
+ if source == "reference/tests.md":
+ return (root / "src/meds_algorithm/TESTING.md").read_text(encoding="utf-8")
+ if source == "prompt-builder.md":
+ document = (root / "docs/implementation-prompt.md").read_text(encoding="utf-8")
+ prompt = re.search(r"```text\n(.*?)\n```", document, re.DOTALL).group(1)
+ # JSON lives inside an HTML script element: source text must not close it.
+ payload = json.dumps(prompt).replace("<", "\\u003c")
+ return markdown.replace(
+ "",
+ f'',
+ )
+ return markdown
diff --git a/docs/implementation-prompt.md b/docs/implementation-prompt.md
new file mode 100644
index 0000000..dc7a713
--- /dev/null
+++ b/docs/implementation-prompt.md
@@ -0,0 +1,235 @@
+# Copyable algorithm-implementation prompt
+
+Use the [interactive prompt builder](https://meds-algorithm.readthedocs.io/en/latest/prompt-builder/)
+or fill in the fields below. The agent inspects sources and selects profiles before generating a new
+local or GitHub repository. The builder runs locally in your browser; it does not launch an agent.
+The provided `real_data` test remains the MIMIC-IV demo smoke test, independent of supplied evaluation tasks.
+
+The prompt adapts [Ponytail's implementation principles](https://github.com/DietrichGebert/ponytail/blob/main/skills/ponytail/SKILL.md)
+to scientific algorithm development. It works with Claude and other coding agents without installing a plugin.
+
+```text
+Implement a MEDS algorithm from the following inputs.
+
+Paper(s), supplementary material and versions:
+
+
+Code/repository source(s), revisions, configurations and checkpoints:
+
+
+Destination (a NEW local repository or a NEW GitHub repository, including visibility):
+
+
+Local working directory for the new repository:
+
+
+Profile selection (automatic, or an explicit list of one or more profiles):
+
+
+Dataset context (name, revision and MEDS path, if available):
+
+
+Already prepared evaluation tasks (labels location, task-config location, bundle revision and
+optional task subset; or explicitly not supplied):
+
+
+Work scope (implementation/local tests, also MEDS-DEV integration, or preparation for full evaluation):
+
+
+Scientific ambiguity mode (confirmation required by default; exploratory only if explicitly enabled):
+
+
+Additional implementation constraints:
+
+
+Inspect the supplied sources before generating the repository. If both paper and code are provided,
+compare them, record discrepancies and identify which behavior is implemented; do not silently assume
+one always overrides the other. If only a paper is provided, distinguish source-backed choices from
+necessary assumptions. If only code is provided, inspect its revision, configuration and checkpoint
+requirements; do not claim fidelity to an unavailable paper.
+
+Resolve scientific ambiguities before implementing the affected behavior. Check the paper, supplements,
+official code and available configurations first; record sources and material conflicts. Ask whether two
+reasonable interpretations could produce materially different algorithms or change what evaluation measures.
+A missing learning rate or batch size can usually use a plausible, configurable default with its rationale
+recorded, unless that choice is central to the scientific claim. Missing feature construction, temporal
+aggregation, architecture components or training objectives are material ambiguities, not routine defaults.
+
+In confirmation-required mode (also the default if no mode is supplied), pause dependent implementation
+and request confirmation for a material unresolved ambiguity. Explain what is missing, the evidence
+consulted, plausible interpretations and their consequences; recommend an option when justified. Continue
+independent work while waiting. An earlier explicit decision covering the same choice is sufficient unless
+new evidence or a scope change invalidates it; silence is not confirmation.
+
+Only when exploratory mode is explicitly enabled may you implement provisional interpretations of material
+algorithm-design ambiguities without first obtaining a decision. Record each as provisional before using
+it, expose the choice in configuration where appropriate, and label affected code, tests and results as an
+exploratory adaptation. Require review of these decisions before claiming faithful reproduction. Do not
+present an assumption as source-backed behavior or silently substitute a familiar method for a missing one.
+
+In BOTH modes, ambiguities about leakage, permitted label access, cohort/target definitions or evaluation
+validity remain blocking for dependent work until explicitly resolved. Exploratory mode does not authorize
+changing supplied tasks, weakening acceptance tests, accessing data or running demo/full-data/cluster jobs
+without the existing approvals. Record the mode, routine defaults, unresolved questions, provisional choices
+and explicit decisions in IMPLEMENTATION_REPORT.md under "Scientific assumptions and decisions"; update the
+existing report rather than creating another specification file.
+
+For automatic profile selection, choose one or more profiles supported by documented source behavior:
+supervised, finetune, probe, zero_shot_direct, zero_shot_materialized or predict_only. Record evidence for
+each choice and proceed when the evidence is clear. Do not add speculative capabilities merely because
+a profile exists. For an explicit list, implement that scope; report material incompatibilities before
+implementing unsupported behavior, and do not silently replace or expand it. Shared methods may be
+implemented once through multiple profile inheritance when their semantics match, or through separate
+classes with shared components. Each selected profile gets its own MEDS-DEV YAML and acceptance tests.
+
+Generate the new repository with the MEDS algorithm template at
+https://github.com/McDermottHealthAI/MEDS_algorithm_template using a reviewed immutable revision, and
+record it in .copier-answers.yml. Pass the selected profiles explicitly; do not accidentally accept the
+single-profile default. Never overwrite an existing local directory or GitHub repository. For a local
+destination, initialize Git without creating a remote. For a GitHub destination, create the specified
+repository with the specified visibility and connect the local checkout; report missing access without
+changing the destination or visibility. Respect any more specific workspace repository-routing rules.
+
+Supplied evaluation tasks are already prepared: use their labels and task configs as fixed inputs.
+Verify their dataset/revision, task identities, splits, prediction times and consistency before use.
+An optional task subset selects only tasks already present in that bundle. Do not generate new tasks,
+extract new labels, relabel examples or silently modify the task definitions. Use supplied indices or
+read only the supplied prediction keys through the core index reader; evaluation outcomes must never
+enter scoring. Zero-shot profiles additionally require executable task criteria and matching predicates.
+If the bundle is not supplied, continue implementation and synthetic tests; report evaluation as
+pending. An incomplete bundle blocks only the dependent evaluation, not unrelated implementation.
+
+Read AGENTS.md, SPEC.md, README.md, and docs/IMPLEMENTATION_GUIDE.md in the generated repository
+completely before writing code. Inspect the paper, supplementary material, source repository,
+configuration files, checkpoints, preprocessing code, and evaluation code available from the supplied
+source.
+
+Apply the Ponytail principle of the smallest complete change: implement the complete source-defined
+algorithm with the least additional infrastructure. Check meds-algorithm, existing algorithm-family code,
+standard libraries and installed dependencies before creating helpers. If the source ships an installable
+package or executable, depend on it pinned to the exact reviewed revision and call it; write only contract
+glue (label-free preprocessing, cohort/key adaptation, explicit key association, coverage). Install it in the
+algorithm environment; if it breaks meds-algorithm within core's declared dependency ranges, fix core. For a
+genuine conflict with core, run the source as an external executable from a separate environment that the
+algorithm package creates and manages (committed lockfile, built at install or first use, digest recorded in
+manifests; MEDS-DEV installs only requirements.txt). Reimplement only when the source cannot run even in
+isolation or its code cannot meet the contract even with glue, and record why in IMPLEMENTATION_REPORT.md;
+local hardware alone is not a reason, since CPU or other hardware is acceptable.
+Choose an algorithm_slug that does not shadow the source's distribution or import name (for example
+genhpf_meds, not genhpf), so both can be installed together. Keep shared fixes in their
+owning package; do not copy core utilities into the algorithm repository. Avoid speculative wrappers,
+configuration options and compatibility layers. Trace affected commands, callers, fixtures and
+documentation, and finish all required changes. Simplicity must preserve scientific fidelity, temporal
+and label isolation, artifact validation, reproducibility, required evaluation evidence and human
+review gates. Write focused tests for new behavior and failure cases. Report deviations and checks
+that were not run.
+
+Write minimalist, auditable, object-oriented algorithm code. Put source-defined hyperparameters and defaults
+in the algorithm-owned frozen Config class in config.py; validate values and prove
+serialization round trips. Keep the implementation in .py and expose the named algorithm
+and configuration classes from the package, so callers can import them meaningfully.
+Keep the public API intentional and small. Classes, functions and modules used only inside the implementation
+should use a single leading underscore (for example _FeatureEncoder or _features.py) and should not be
+re-exported from the package __init__.py. List only intended public exports in __all__. Keep contract-required
+methods and integration hooks publicly named where required. A leading underscore signals an internal,
+unstable interface in Python; it does not enforce access control. Prefer it over double-underscore name
+mangling unless avoiding a specific inheritance collision. Do not create extra classes just to organize
+private helpers, and do not hide the algorithm/configuration classes callers are expected to import.
+For neural algorithms with matching semantics, extend core NNConfig rather than
+duplicating shared capacity, learning_rate, batch_size, weight_decay and dropout settings. Define
+source-backed defaults and the capacity-multiplier mapping (reference architecture, dimensions, rounding
+and minimums); call super().validate() for inherited
+constraints. Test that the settings actually control construction/training. See the installed architecture
+guide for units, extension examples and scaling ownership. Keep cohort selection upstream; record actual
+parameter counts and consumed data separately rather than inferring them from capacity or a data fraction.
+Use inherited additional_predicates_file for dataset-specific feature additions when needed. Read the
+runner-resolved request.predicates_file in preprocessing; do not override base definitions, merge again,
+or change task predicates. Preserve temporal isolation and use the same configuration across steps.
+Implement the selected Algorithm profile methods with their typed request classes. Prefer small cohesive
+components and explicit constructor dependencies; use inheritance for the profile contract and composition
+for algorithm internals. Do not add unnecessary classes, wrappers, mutable module-level runtime state, hidden
+singletons, import-time work, broad exception swallowing, or duplicated contract tables. Declarative
+constants and the profile-to-implementation association are appropriate; fitted state belongs in artifacts.
+Use core's runner for both CLI execution and tests. Algorithm methods write only to its staging destination
+and return PayloadMetadata; do not reimplement publication, measurements or manifest/config/request writing.
+Implement explicit payload compatibility checks. Prediction outputs contain keys and probabilities;
+only the runner attaches evaluation truth after scoring. Demonstrate that saved configuration and requests
+can be reloaded in a fresh process and executed without an earlier call on the same algorithm instance.
+
+Preserve all selected algorithm profiles and standardized command arguments, MEDS input boundary, artifact
+manifest envelopes, MEDS-DEV model.yaml interface, and final MEDS prediction output. Intermediate payload
+formats and execution mechanisms are algorithm-owned: choose whatever preprocessing, featurization, framework,
+batching or non-batching strategy, external executable, storage format, and algorithm architecture most
+faithfully reproduce the source.
+
+When predicates are needed, reuse MEDS-DEV predicates for the selected dataset if available; otherwise,
+use reviewed external predicates for that dataset and record their provenance. Decide within the algorithm
+how those predicates become inputs. Validate dataset-specific codes, units, task definitions, and label mappings;
+do not assume MIMIC mappings apply to another dataset. Keep such mappings in dataset-specific
+configuration or algorithm-owned code. Do not introduce a generic predicate-derived feature representation
+into the contract package. Keep the provided MIMIC-IV demo code, task, and MEDS-DEV predicates as the
+canonical smoke test, regardless of the full-data target.
+
+For a zero_shot_direct algorithm (answers queries directly, e.g. MOTOR, EveryQuery) or a zero_shot_materialized
+algorithm (generates futures and evaluates the task on them; infer is task-independent and only predict
+receives the task): the algorithm receives the original ACES task through
+external_task_criteria_file (with the dataset predicates) and the upstream-built index through
+external_index_dir. Never build, filter, or extend the cohort, and read the index only through
+meds_algorithm.read_index. Reuse an existing aces-to- adapter for this algorithm if one exists;
+otherwise write one on aces-relaxations, pinned to an exact version: reject tasks that are not future-only
+or are degenerate, normalize, then apply only the approximations and assumptions the algorithm's query
+language forces. Publish relaxations.yaml with each zero-shot prediction artifact, and report per task whether
+the answer is exact.
+A materialized algorithm evaluates the task on generated futures instead and needs no relaxation beyond
+sampling. Follow the shape for the selected profile in docs/IMPLEMENTATION_GUIDE.md.
+Do not omit source behavior because it is inconvenient for a fixture; adapt the implementation or fixture
+instead.
+
+Record every material source element as ported, adapted, or omitted, with evidence and justification, in
+IMPLEMENTATION_REPORT.md. Implement every selected typed algorithm method, finalize the implementation-specific
+command strings in model.yaml, and implement tests/e2e.py. Configure representative config instances
+in tests/conftest.py. Keep TestConformance inheriting the shared meds-algorithm acceptance suite;
+do not copy its test bodies or override its checks to suppress failures. Remove each profile from STUB_PROFILES only
+after that profile completes and produces standards-conformant predictions; complete every selected profile.
+
+Always run:
+
+ uv run pytest -rs
+
+Also run `bash scripts/check_distribution.sh` to verify installed imports, CLI commands and bundled
+defaults outside the checkout. Extend `tests/wheel_smoke.py` for required algorithm configuration or
+resources. Follow RELEASING.md for publication readiness; package publication itself requires an explicit
+user request. Do not choose a license on the user's behalf or bundle datasets, credentials or fitted weights.
+
+If the selected scope includes MEDS-DEV integration or full-evaluation preparation, also run:
+
+ uv run pytest -m meds_dev -rs
+
+For implementation/local-tests scope, finish with implementation and local validation evidence. For
+MEDS-DEV integration scope, finish after its integration evidence. Report unavailable dependencies or
+adapters explicitly; do not weaken tests. The following demo and full-data stages apply only when the
+selected scope is preparation for full evaluation; selecting that scope is not execution approval.
+
+Complete the pre-demo sections of IMPLEMENTATION_REPORT.md and ask for human review of source fidelity,
+predicate interpretation, and the proposed MIMIC-IV demo execution. Only after approval, run:
+
+ uv run pytest -m real_data -rs
+
+There must be zero algorithm_stub skips. Report exact pass/skip counts and account for every remaining skip.
+Update IMPLEMENTATION_REPORT.md with the demo cohort, final-output coverage, predicate provenance,
+environment, wall time, peak process-tree PSS/RSS, GPU measurements when available, failures, and fixes.
+Ask for a second human review before launching the selected full dataset through the repository's SLURM
+interface. Review target-dataset compatibility, access, and resources separately from the MIMIC-IV demo.
+Use the supplied, already prepared task bundle for the selected dataset. It must contain task configs,
+per-task labels/keys and split assignments; zero-shot runs additionally require the original ACES criteria
+and matching predicates. Do not generate or extract replacement evaluation tasks. Canonical synthetic
+fixtures and the built-in MIMIC-IV demo smoke task remain separate from this supplied evaluation bundle. If the bundle is absent
+or inconsistent, report the evaluation blocker and the exact missing inputs.
+Record the dataset name/revision, predicate provenance, bundle location, supplied bundle revision and
+available upstream build provenance, and a digest of its task definitions. Keep the bundle external to Git.
+Commit the implementation, configuration and report-so-far; push when a remote is configured. Run the
+cluster job from that exact clean commit. After the authorized run, complete the report with full-data evidence, scientific deviations, and known limitations, then
+synchronize structured results through the GitHub workflow when the destination has a GitHub remote.
+For a local-only repository, retain the committed report and run evidence locally. Treat
+docs/IMPLEMENTATION_GUIDE.md as the authority for the ordered gates and their evidence.
+```
diff --git a/docs/index.md b/docs/index.md
index 32d709f..1dca57a 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -1,66 +1,81 @@
# MEDS algorithms
-`meds-algorithm` provides shared contracts and infrastructure for algorithms consuming MEDS data:
-profile interfaces, typed step requests, artifact provenance, prediction validation and conformance tests.
+This site documents the `meds-algorithm` shared package and the
+[MEDS algorithm template](https://github.com/McDermottHealthAI/MEDS_algorithm_template), a
+[Copier](https://copier.readthedocs.io) template for packaging a clinical
+prediction algorithm as a repository that anyone can run, compare, and audit the same way. You render a new
+repository from it, implement your algorithm inside a fixed set of commands, and get, for free, the parts
+that make algorithms comparable: a standard input and output, artifact manifests with measurements, MEDS-DEV
+registration, a SLURM interface, and a staged test workflow ending in a full-data run.
-- Browse [implemented algorithms](implemented-algorithms.md), their declared profiles, reviewed PyPI
- versions and validation evidence.
-- Read the [package README](https://github.com/McDermottHealthAI/meds-algorithm#readme),
- [architecture and UML](https://github.com/McDermottHealthAI/meds-algorithm/blob/main/ARCHITECTURE.md),
- and [canonical contract](https://github.com/McDermottHealthAI/meds-algorithm/blob/main/src/meds_algorithm/CONTRACT.md).
-- Build an implementation using the
- [algorithm template and its workflow documentation](https://mcdermotthealthai.github.io/MEDS_algorithm_template/).
+!!! note "Who this site is for"
+ Generated repositories' `README.md`, `AGENTS.md` and `SPEC.md` are written as instructions for coding
+ agents that port algorithms. This site explains the same contract to people: algorithm implementers,
+ reviewers, and benchmark organizers. The [specification](reference/spec.md) remains the normative
+ source; where this site and the spec differ, the spec wins.
-The catalogue belongs to this ecosystem repository and is maintained independently of Python package
-releases. Its registry, renderer and tests are excluded from both wheel and source distributions.
-Updating a listing rebuilds this site; it does not require publishing another `meds-algorithm` version.
+## The picture in one diagram
-## Maintaining this documentation
-
-```bash
-uv sync --locked --group docs
-uv run --group docs pytest docs/tests -q
-uv run --group docs mkdocs serve
+```mermaid
+flowchart LR
+ subgraph upstream["Upstream (shared by every algorithm)"]
+ meds[(MEDS dataset train / tuning / held_out)]
+ task[ACES task criteria + predicates]
+ aces[[ACES extraction]]
+ index[(Task index subject_id, prediction_time, boolean_value)]
+ meds --> aces
+ task --> aces
+ aces --> index
+ end
+ subgraph repo["Algorithm repository (rendered from the template)"]
+ cmds["Commands of the selected profile preprocess_data → … → predict"]
+ end
+ meds --> cmds
+ index --> cmds
+ task -. zero-shot only .-> cmds
+ cmds --> preds[(predictions.parquet one row per requested key)]
+ preds --> eval[[meds-evaluation / MEDS-DEV]]
```
-See [catalogue registration and updates](implemented-algorithms.md#register-or-update-an-algorithm) and
-the [catalogue test inventory](catalogue-testing.md). Runtime tests remain under `tests/` and their
-inventory remains in the packaged
-[TESTING.md](https://github.com/McDermottHealthAI/meds-algorithm/blob/main/src/meds_algorithm/TESTING.md).
-
-### Read the Docs hosting
+Everything left of the algorithm repository is built **once, upstream**: the dataset, the task definition,
+and the cohort (which patients, at which prediction times, with which labels). Every algorithm receives the
+same inputs and must return one prediction for every requested `(subject_id, prediction_time)`. That is
+what makes results comparable.
-The repository-root `.readthedocs.yaml` builds this site with Python 3.12, the existing `docs`
-dependency group and MkDocs Material. It uses uv to install dependencies from `pyproject.toml` and
-`uv.lock`, and fails on documentation warnings. GitHub Actions continues running catalogue tests,
-validation, lint and the strict documentation build independently of the hosting service.
+## Fixed by the contract, owned by the algorithm
-To enable hosting:
+| Fixed by the contract | Owned by the algorithm |
+|---|---|
+| Inputs: a split-sharded MEDS dataset, a task index, optional dataset predicates, and (zero-shot) an ACES task | Preprocessing, featurization, tokenization |
+| Six **algorithm profiles**, each a fixed sequence of commands | Architecture, framework, batching, hardware |
+| Standard command arguments (`external_meds_dir`, `output_predictions_dir`, …) | Intermediate payload formats (checkpoints, embeddings, caches) |
+| A `manifest.yaml` envelope on every artifact, written last and published with rollback | How the payload inside an artifact is laid out |
+| Wall time and memory measurements on every command | How fast the algorithm is |
+| Final predictions in the meds-evaluation schema, keyed and complete | How probabilities are computed |
+| `algorithms//model.yaml` for MEDS-DEV, SLURM scripts, GitHub result sync | The command strings inside them, once finalized |
-1. Import `McDermottHealthAI/meds-algorithm` into Read the Docs and use `meds-algorithm` as the project
- slug. If a different slug is needed, update the README badge and links, `pyproject.toml` documentation
- URL and the fallback `site_url` in `mkdocs.yml` together.
-2. Set the default branch to `main`, build its `latest` version, and use `latest` as the default
- documentation version initially. Older release tags do not contain this hosting configuration.
-3. Verify the build and the catalogue at
- , and enable pull request builds if desired.
+The contract fixes **boundaries**, not methods. An algorithm can be a PyTorch transformer, a gradient-boosted
+tree, an external executable or a call to a service; the template only cares that each command consumes
+the right artifacts and publishes the right one.
-MkDocs reads `READTHEDOCS_CANONICAL_URL` during hosted builds so canonical links use the appropriate
-version URL. Local builds fall back to the `latest` URL. The source pages, navigation and theme are
-shared between local builds and hosting; no second copy of the documentation is needed.
+## Where to go next
-### GitHub Pages transition
+- **Find an implementation:** browse the [algorithm catalogue](implemented-algorithms.md).
+- **Getting started:** read [Concepts](concepts.md), [Choosing a profile](profiles.md), then the
+ [Workflow](workflow.md) from implementation to validation.
+- **Building an algorithm:** prepare instructions with the [prompt builder](prompt-builder.md),
+ learn the [run commands](running.md), or follow the [fully manual example](manual-example.md).
+- **Development:** explore the [core package](core-package.md) and
+ [what belongs in the template or shared package](shared-package-assessment.md). Use the
+ [migration guide](migration-v4.md) and [publishing guide](releasing.md) when maintaining packages.
+- **Reference:** consult the [specification](reference/spec.md),
+ [tests and acceptance](testing.md), or [zero-shot guide](zero-shot.md) for the details.
-The existing GitHub Pages deployment remains active until Read the Docs has built successfully.
-After verifying the new site, replace the Pages publication with a small redirect site that preserves
-the old page paths and fragments at . Keep those
-redirects hosted on Pages so existing links continue working; Read the Docs cannot redirect requests
-made to the old GitHub Pages domain. Retain the GitHub Actions documentation checks when replacing
-the old full-site deployment.
+## Preview this site locally
-This change only moves hosting for this repository. The algorithm template's documentation remains
-at its existing GitHub Pages URL.
+From a checkout of `McDermottHealthAI/meds-algorithm`:
-The weekly catalogue workflow additionally needs permission for Actions to create pull requests; its
-registration guide documents the setting and the report-artifact fallback. No private-repository
-credentials are required.
+```bash
+uv sync --locked --group docs
+uv run --group docs mkdocs serve
+```
diff --git a/docs/manual-example.md b/docs/manual-example.md
new file mode 100644
index 0000000..cb0ac16
--- /dev/null
+++ b/docs/manual-example.md
@@ -0,0 +1,177 @@
+# Fully manual example: setup to predictions
+
+This walkthrough generates a repository, implements its three supervised methods by hand, creates
+synthetic inputs, and runs **preprocessing → training → prediction** locally. No coding agent, MEDS-DEV
+installation, clinical dataset, GPU or cluster is needed. All commands appear in execution order below.
+
+The example is a **constant-prevalence baseline**, not a clinical algorithm reproduction. It learns one
+smoothed probability from the training labels and emits it for every requested held-out key. It copies
+events during preprocessing but does not use event features to predict. Additional predicates are
+included to demonstrate composition and provenance, not to claim feature-dependent behavior.
+
+## Setup and expected result
+
+Use Bash on Linux/macOS or inside WSL on Windows, with **Git and uv installed** and network access for
+Python/packages. Run the commands in a new workspace; the script refuses an existing directory.
+`uv python install 3.11` installs the tutorial's Python, and `uv sync --extra test` installs the generated
+package, core, Polars and the conformance dependencies into its `.venv`. No global Python environment
+is modified. Copier and the template revision are pinned so the tutorial can be reproduced.
+
+Run the numbered sections below **in order, in the same Bash session**. Alternatively, expand
+[All commands](#all-commands) at the end to copy the complete script, or download the
+[same script](examples/manual-supervised.sh) and run
+`bash manual-supervised.sh /absolute/path/to/a/new/tutorial-directory`.
+
+The generated package is `manual_baseline`, its class is `ManualBaseline`, and its named command is
+`manual-baseline`. Each lifecycle command starts a fresh
+process, using the same `config_file`. There are three training outcomes (`true, true, false`) and a
+smoothing value of 1, so the resulting probability is `(2 + 1) / (3 + 2) = 0.6` for both held-out rows.
+
+---
+
+## 1. Create the workspace and generate the repository
+
+Choose a new directory and render the supervised profile. These commands create `manual-baseline/`
+and change into it; all subsequent paths are relative to that generated repository.
+
+```bash
+--8<-- "docs/examples/manual-supervised.sh:setup"
+```
+
+---
+
+## 2. Install the environment
+
+Install Python and the generated package, then inspect its profiles, commands and installed contract.
+
+```bash
+--8<-- "docs/examples/manual-supervised.sh:environment"
+```
+
+---
+
+## 3. Implement the algorithm
+
+The code-writing commands below intentionally replace the generated tutorial stubs. The template alone
+does not contain an implemented algorithm. Leave its completion gate in place: this short tutorial does
+not implement `tests/e2e.py`, the full implementation report, or the MEDS-DEV/demo acceptance tiers.
+The final pytest command runs only the generated contract and operations checks; its success does not
+mean a production port has passed the [complete workflow](workflow.md).
+
+### Typed configuration
+
+Define the smoothing parameter and validate it when configuration is loaded.
+
+```bash
+--8<-- "docs/examples/manual-supervised.sh:configuration"
+```
+
+### Algorithm class
+
+Implement preprocessing, supervised training and prediction. The learned probability is saved to disk
+so prediction can run in a separate process.
+
+```bash
+--8<-- "docs/examples/manual-supervised.sh:algorithm"
+```
+
+---
+
+## 4. Prepare synthetic inputs and dataset settings
+
+Create the event table, separate training and held-out label/index files, base and additional
+predicates, and the dataset configuration that refers to those additions.
+
+```bash
+--8<-- "docs/examples/manual-supervised.sh:inputs"
+```
+
+---
+
+## 5. Run each lifecycle step
+
+Set the shared paths once. Each command below then starts its own process.
+
+```bash
+--8<-- "docs/examples/manual-supervised.sh:paths"
+```
+
+### Preprocess the data
+
+Compose the feature predicates and write the prepared data artifact.
+
+```bash
+--8<-- "docs/examples/manual-supervised.sh:preprocess"
+```
+
+### Train the algorithm
+
+Estimate the smoothed probability from the training outcomes and persist it in the algorithm artifact.
+
+```bash
+--8<-- "docs/examples/manual-supervised.sh:train"
+```
+
+### Predict on the held-out index
+
+Load the saved probability and emit one prediction per requested key. The runner attaches evaluation
+labels after scoring.
+
+```bash
+--8<-- "docs/examples/manual-supervised.sh:predict"
+```
+
+---
+
+## 6. Inspect and verify the outputs
+
+Check the two expected probabilities, the prediction schema, artifact metadata and composed predicates.
+Then run the generated contract and operations checks.
+
+```bash
+--8<-- "docs/examples/manual-supervised.sh:verify"
+```
+
+---
+
+## What was produced
+
+Under `manual-meds-example/manual-baseline/` (or your chosen workspace):
+
+| Path | Contents |
+|---|---|
+| `src/manual_baseline/manual_baseline.py` | Concrete algorithm methods and profile association |
+| `src/manual_baseline/config.py` | Named, typed configuration with positive smoothing validation |
+| `dataset_configs/demo.yaml` | Dataset-specific settings and relative additional-predicates path |
+| `inputs/meds/data/`, `inputs/labels/` | Synthetic events and the separate label/index bundle |
+| `runs/manual/supervised/artifacts/data/` | Prepared events, summary, resolved feature predicates and core metadata |
+| `runs/manual/supervised/artifacts/algorithm/` | Persisted learned probability and core metadata |
+| `runs/manual/supervised/artifacts/predictions/` | Held-out probabilities, post-score truth and core metadata |
+
+Each artifact has `manifest.yaml`, `config.json` and `request.json`. The manifest records measurements,
+input identities and the configuration. Because this example does not create a Git commit for the
+generated implementation, its commit provenance may be unavailable; commit reviewed implementation
+code before reproducible production runs. Keep input data and artifact payloads out of source control.
+
+The index and evaluation labels happen to share a directory in this example. Prediction reads only
+keys through `request.index.read()`; the runner attaches `boolean_value` afterward. In real work,
+reuse the upstream reviewed task bundle, respect all temporal cutoffs, and do not create labels inside
+the algorithm. Additional feature predicates must not redefine the evaluated task.
+
+To rerun, choose fresh output paths. Explicit `do_overwrite=true` opts into replacing an artifact with
+rollback; do not add it automatically to every command. Other profiles have different intermediate
+steps: use the [profile lifecycle table](reference/spec.md#3-commands-and-algorithm-profiles) and
+[per-step arguments](reference/spec.md#9-software-interfaces) when adapting this example.
+
+---
+
+## All commands
+
+This is the complete script used by the sections above. Run it from a fresh workspace instead of
+running it again in the directory you just created.
+
+??? example "All commands — complete runnable script"
+
+ ```bash
+ --8<-- "docs/examples/manual-supervised.sh"
+ ```
diff --git a/docs/migration-v4.md b/docs/migration-v4.md
new file mode 100644
index 0000000..602671d
--- /dev/null
+++ b/docs/migration-v4.md
@@ -0,0 +1,103 @@
+# Migrating to algorithm terminology and typed profiles
+
+Version 4 changes command names, artifact types, descriptor locations and repository dispatch. Do not
+reuse version 2 or 3 artifacts by editing their manifest version: validate or rebuild their payloads against
+the new contract. The template emits and reads version 4 envelopes.
+
+## From version 3
+
+This is an intentional naming change, with no old-name aliases:
+
+| Previous name | Current name |
+|---|---|
+| `meds-model-core`, `meds_model_core` | `meds-algorithm`, `meds_algorithm` |
+| `ModelConfig`, `MODEL_PROFILES` | `AlgorithmConfig`, `ALGORITHM_PROFILES` |
+| `ModelRepository` (mapping-based adapter) | Replace with typed `AlgorithmRepository` |
+| `SupervisedModelArtifact` (and pretrained/finetuned/probe equivalents) | `SupervisedAlgorithmArtifact` (and corresponding equivalents) |
+| Request field `model` or `algorithm` for fitted prediction state | `fitted_algorithm` |
+| `meds-model`, `meds-model-*` helper commands | `meds-algorithm`, `meds-algorithm-*` |
+| `input_*_model_dir`, `output_*_model_dir`, `*_model` artifact types | `input_*_algorithm_dir`, `output_*_algorithm_dir`, `*_algorithm` |
+| Copier `model_name`, `model_slug`, `model_description` | `algorithm_name`, `algorithm_slug`, `algorithm_description` |
+| `commands.py` with `ModelAlgorithm` and generic `Config` | `.py` with `` and `Config` |
+| `models//model.yaml` | `algorithms//model.yaml` |
+
+Set the new `algorithm_class` answer explicitly for acronyms, such as `RETAIN`. Update imports, scripts,
+SLURM environment variables (`MEDS_ALGORITHM_*`), lockfiles and persisted invocation descriptions together.
+Serialization records concrete class identifiers; old JSON envelopes require an explicit migration.
+MEDS-DEV still owns `model.yaml`, its `models/` directory, `meds-dev-model`, `model=`, and
+`{model_initialization_dir}`. Those upstream names are intentionally unchanged.
+
+## From older single-profile repositories
+
+1. Replace the Copier `profile` answer with `profiles: [, ...]`. Rename `packaged` to `predict_only`.
+ Keep the original source/revision metadata in `.copier-answers.yml` and review the Copier update diff.
+2. Implement the selected profile ABCs and associate profiles with concrete classes in `IMPLEMENTATIONS`.
+ Shared methods appear once where their semantics match.
+3. Rename commands according to the table below. Split previously conditional implementations into
+ distinct profile methods, sharing cohesive components where their semantics really match.
+4. Update every invocation, manifest producer, output argument, test adapter and SLURM stage selection.
+5. Move the MEDS-DEV descriptor to `algorithms//model.yaml`; add one for each declared profile.
+ Register them independently using `--profile`; the registered name is `__`.
+6. Supply explicit split lists for inference and prediction. Supervised/fine-tuned prediction receives `input_data_dir`; probe prediction receives
+ `input_embeddings_dir`. Scoring and inference use `external_index_dir`, not the training-label argument.
+7. Replace the global `IS_STUB` boolean with `STUB_PROFILES`. Run the acceptance suite for every profile.
+ Record the profile in `write_run_result(..., profile=...)`.
+
+| Profile | Old command | New command |
+|---|---|---|
+| All | `preprocess_data`, `pretrain` where present | Unchanged |
+| supervised | `supervised_train`, `predict` | `train_supervised`, `predict_supervised` |
+| finetune | `supervised_train`, `predict` | `train_finetune`, `predict_finetune` |
+| probe | `infer`, `supervised_train`, `predict` | `infer_embeddings`, `train_probe`, `predict_probe` |
+| zero_shot_direct | `predict` | `predict_zero_shot_direct` |
+| zero_shot_materialized | `infer`, `predict` | `infer_trajectories`, `predict_zero_shot_materialized` |
+| predict_only (formerly packaged) | `predict` | `predict_only` |
+
+`inference` splits into `embeddings` and `trajectories`, with matching
+`input_embeddings_dir`/`output_embeddings_dir` and `input_trajectories_dir`/`output_trajectories_dir`.
+Task-algorithm artifacts split into `supervised_algorithm`, `finetuned_algorithm`, and `probe_algorithm`, with matching
+input/output argument names. Prediction output remains `output_predictions_dir`.
+
+Use Copier 9.17.1 or newer; the template uses its yield extension to generate a directory for each
+selected profile. A single-profile repository may omit CLI `--profile`; a repository with multiple
+profiles must select one. There is no ambiguous compatibility alias for the old generic command names.
+
+This revision supplies the interfaces and tests. It does not automatically migrate downstream algorithm
+implementations or publish a shared runtime package. See the [package assessment](shared-package-assessment.md).
+
+The core package now owns the single normative `CONTRACT.md`. Generated `SPEC.md` is a pointer to the
+installed package version, readable with `meds-algorithm-spec`. The template and generated projects
+install the alpha from an immutable Git commit in the separate core repository; no PyPI release is required.
+
+Replace imports from `meds_model_contract` with `meds_algorithm` and remove the generated compatibility
+package. Core supplies the registration/input-resolution CLI entry points; keep only the algorithm's own
+CLI in its project configuration. Import shared fixtures and checks from `meds_algorithm.conformance`.
+For the typed API, pass algorithm provenance explicitly to `AlgorithmRepository(..., repo=algorithm_root)`.
+Return `E2EResult` from core's `conformance.types`, recording all external inputs;
+the lifecycle checker now reruns every step with forbidden outcomes absent and fresh output paths.
+Existing algorithm repositories are not migrated by this template change.
+
+## From mapping-based commands to typed algorithms
+
+Core 0.4.0a5 removes `Command` and `LegacyAlgorithmRepository`. The supported execution path is
+`AlgorithmRepository` with typed requests and `StepRunner`. Migrate deliberately:
+
+1. Move command bodies to the selected `Algorithm` profile methods. Use their typed request fields.
+2. Put algorithm settings/defaults in a frozen `AlgorithmConfig` subclass; test validation and JSON round trips.
+3. Replace internal publication contexts with writes to `request.output.directory` and a returned
+ `PayloadMetadata`. Remove algorithm-written manifests and truth attachment; the runner owns those.
+4. Extend `validate_inputs` for payload compatibility. Document any override of its default same-algorithm,
+ same-config rule, especially for external pretrained artifacts or legacy manifests without config.
+5. Route the CLI and end-to-end adapters through `AlgorithmRepository`/`StepRunner`. Verify saved
+ requests/configuration and fitted artifacts work in a fresh process.
+
+See [architecture and UML](reference/architecture.md). No private algorithm migration is included here.
+
+
+## Fitted prediction requests in core 0.4.0a5
+
+`PredictSupervisedRequest`, `PredictFinetuneRequest` and `PredictProbeRequest` now name their saved fitted
+artifact `fitted_algorithm`, distinguishing it from the executing Python algorithm instance. Their JSON
+schema version is 2; version 1 envelopes are rejected. Reconstruct requests with the current typed API
+rather than editing version numbers. External `input_*_algorithm_dir` names are unchanged. Fitted input
+manifests must contain the complete resolved config; missing historical fields are no longer filled in.
diff --git a/docs/profiles.md b/docs/profiles.md
new file mode 100644
index 0000000..e8662a2
--- /dev/null
+++ b/docs/profiles.md
@@ -0,0 +1,67 @@
+# Choosing profiles
+
+A profile describes an algorithm's lifecycle. A repository may declare several profiles and implement them
+in one package. Choose them with Copier's `profiles` multiselect, or supply a data file:
+
+```yaml
+profiles: [finetune, probe, zero_shot_direct]
+```
+
+The [prompt builder](prompt-builder.md) supports automatic selection from paper/code evidence or an
+explicit selection of several profiles before repository generation.
+
+The [canonical lifecycle table](reference/spec.md#3-commands-and-algorithm-profiles) lists the exact steps.
+
+Only preprocessing and pretraining share command names. They may share artifacts when input identities,
+configuration, payload format and training scope match. Selecting two profiles does not automatically
+make their artifacts compatible.
+
+| Profile | Use when |
+|---|---|
+| `supervised` | Learning a task-specific algorithm directly from the dataset's training labels. |
+| `finetune` | Updating a pretrained encoder together with a task-specific head. |
+| `probe` | Fitting a task-specific head on frozen encoder representations. |
+| `zero_shot_direct` | Translating an ACES task into direct algorithm queries and decoding probabilities without labels. |
+| `zero_shot_materialized` | Generating task-independent futures, then evaluating the task on history plus those futures. |
+| `predict_only` | Preprocessing then applying a supplied fixed algorithm or an in-context learner, without a training command. |
+
+`predict_only` is the renamed packaged profile. It does not mean probe training. In-context learners may
+read explicitly selected train/tuning examples; fixed scores need no labels. Neither may read evaluated
+labels before its probabilities are final.
+
+## Select a profile when running commands
+
+Each invocation selects one of the repository's declared profiles. The executable is named after your
+algorithm's slug, with underscores replaced by hyphens: `algorithm_slug: my_algorithm` creates the
+command `my-algorithm`. Substitute your own command name below.
+
+From the generated repository's root, with the `probe` profile declared:
+
+```bash
+uv sync --extra test
+
+# List the profiles implemented by this repository.
+uv run my-algorithm profiles
+
+# List the commands in the probe lifecycle.
+uv run my-algorithm commands --profile probe
+
+# Register its descriptor in an existing MEDS-DEV checkout.
+uv run meds-algorithm-add-to-meds-dev \
+ --meds-dev /path/to/MEDS-DEV --name my-algorithm --profile probe
+```
+
+Replace `/path/to/MEDS-DEV` with your checkout. Registration copies
+`algorithms/probe/model.yaml` into MEDS-DEV under `my-algorithm__probe`.
+Here `--name my-algorithm` chooses the registration name; it does not rename the executable.
+For SLURM, select the profile with `PROFILE=probe`; see [Running an algorithm](running.md)
+for input paths, dry runs and execution settings.
+
+The probe's `infer_embeddings` stage materializes keyed representations without labels. `train_probe`
+fits a head on training representations, and `predict_probe` applies it to explicit evaluated embeddings.
+Supervised/fine-tuned prediction instead takes `input_data_dir` and the fitted algorithm. Neither dependency
+is assumed to disappear just because training recorded its path.
+
+The [software contract](reference/spec.md#9-software-interfaces) gives every command's arguments, artifact type, label
+access, class responsibilities, compatibility checks, and acceptance requirements. See
+[migration](migration-v4.md) for an existing repository.
diff --git a/docs/prompt-builder.md b/docs/prompt-builder.md
new file mode 100644
index 0000000..9f302ee
--- /dev/null
+++ b/docs/prompt-builder.md
@@ -0,0 +1,88 @@
+# Implementation prompt builder
+
+Prepare instructions for Claude or another coding agent. Choose paper/code sources, a **new local or
+GitHub repository**, and automatic or explicit profile selection. Evaluation tasks, if supplied, must
+already have **labels and task configs**. This form assembles text locally; it does not read your files,
+contact GitHub, upload inputs or run an agent.
+
+The generated prompt uses the same maintained instructions as the [static workflow prompt](implementation-prompt.md).
+You can edit the result before copying. Demo and full-data execution retain their human review gates.
+
+