Repository architecture#
Rehearsal separates shipped product code, repository automation, tests, fixtures, and documentation so each file has one obvious home. This guide is for contributors; ordinary setup and runtime use start in Getting started.
The source layout is the authoritative map of source folders and their responsibilities. This guide owns the contracts between those domains.
rehearsal-db/
├── src/ TypeScript product source; folder map in src/README.md
├── scripts/
│ ├── build/ clean TypeScript compilation helpers
│ ├── install/ TypeScript install-hook source
│ ├── runtime/ TypeScript runtime-launcher source
│ └── verification/ repository-only package and fixture proofs
├── dist/ generated ESM and declaration output; never edit directly
├── types/ compatibility entry point for generated declarations
├── tests/
│ ├── unit/ mirrors the `src/` domains
│ ├── integration/ multi-module and terminal behavior
│ ├── contracts/ public documentation and package promises
│ └── fixtures/ disposable example projects
└── docs/ user and maintainer documentationBoundaries#
src/must never import from tests or repository-only verification scripts.dist/is rebuilt from TypeScript before tests and packaging; never hand-edit it.- Database-specific lifecycle behavior belongs in
src/targets/. scripts/verification/is never included in the npm package.- Public consumers use only the paths declared in
package.json#exports. - Existing public
runtime/migration_history,container_retirement,service_environmentandmanaged_prototypemodule paths remain small export facades. Their implementations live in the domain folders above; private imports use those owners directly. The publicbaseline/privacy_enginefacade likewise keeps its path while the privacy stages live together underbaseline/privacy/. - Unit tests mirror their source domain. Cross-domain workflows belong in
tests/integration/; durable public promises belong intests/contracts/. tests/helpers/public_cli.mjsandscenarios/process.mjsshare a closed test-failure projection: fixed categories, phase labels and bounded exit/signal metadata. Test reports must not retain raw child errors, argv, provider output or SQL. Unknown failures stay unclassified; later passing checks do not establish their cause.
Command capability inspection#
project/command_capabilities.mts owns the bounded command-requirement projection;
project/receipt_provenance.mts owns explicit recorded-receipt parsing and stable,
private, confined POSIX reads. The thin capability CLI handler consumes these
owners through a separate advertised version-1 contract. It does not load project
configuration, probe tools/engines, select a backend or replace live readiness.
Receipt observations never establish current input matches, time or live state.
Held ancestry and before/after file identity checks detect observed drift; they
are not atomic openat resolution or a sandbox against privileged concurrent work.
Documentation audiences#
Site navigation separates Getting started, User reference and Maintainers. Installation, rehearsal, results and failure recovery belong in the first journey; configuration, supported environments, troubleshooting and data safety belong in reference. Keep deletion, production-access and unsupported-behavior warnings visible to users.
docs/capabilities.md owns the released Core and Starter capability catalog and their
independently verified release snapshots. READMEs provide short outcome summaries and
link to that catalog. docs/roadmap.md owns intended and paused directions; linked
subject guides retain their technical contracts. Review these summaries and owners
with every release. A development manifest or passing candidate check does not establish
publication or promote an intention to a released capability.
docs/updating.md answers release changes, compatibility, updating, breaking changes
and origin verification with links to deeper owners. Build, test and publishing details
belong in maintainer guidance, not installation prerequisites. docs/releasing.md owns
current publishing controls; historical incidents stay in release and issue history.
CLI modules#
The executable is split by responsibility so no command file becomes a second application layer. Scripted commands and the interactive guide resolve through the same typed registry and produce the same result contract:
rehearsal.mtsowns process lifecycle, project locking, guided-loop coordination, and top-level error handling. It does not implement commands.arguments.mtsowns the command-line contract and mutation classification.command_contract.mts,command_registry.mts, andcommand_output.mtsdefine command context, handler selection, stable JSON envelopes, human rendering, and exit codes.*_command_handlers.mtsandruntime_action_handlers.mtsgroup handlers by project, source, identity, inspection, application, or runtime responsibility.cli_commands.mtscomposes those focused families in precedence order without implementing their behavior.guided.mtsowns the interactive home screen and first-run questions.guided_updates.mtsowns optional update consent and reminders in that guide;update_advisory.mtsbounds public release metadata, private preferences and installation-origin checks.updates/startup_updates.mtspresents a bounded, best-effort notice for ordinary human-terminal commands. Update checks never participate in passive JSON inspection.runtime_commands.mtscoordinates local runtimes and project proofs.cli/presentation/cleanup_rendering.mtsowns human cleanup previews and outcomes; it never performs cleanup. The existingrenderers.mtsentry retains its exports.cli/presentation/failure_output.mtsowns CLI failure normalization and human/JSON formatting. The executable retains output-stream selection and the process exit code.runtime_readiness_rendering.mtspresents shared engine choices and doctor readiness.engine_discovery.mtsowns bounded host/engine observations;local_docker_context.mtsowns explicit selection and local endpoint binding. Support reports reuse those observations without exposing private context or endpoint identities.runtime_stack_runner.mtsselects configured targets, binds their reviewed engine and configuration identities, executes the serial stack and retains receipt-bound cleanup.runtime_workload_admission.mtsapplies optional lifecycle admission before that work; application proofs and interactive sessions are deliberately outside it.workload_command_handlers.mtsexposes local queue inspection and exact dead-holder metadata recovery without a project lock or Docker.runtime/resources/workload_queue.mtsowns cooperative lifecycle admission; its store owns bounded private atomic tickets, and its location helper binds the local user, boot and PID namespace independently of per-command temporary directories. No background scheduler is installed.engine_command_handlers.mtsexposes configuration-independent engine status and reviewed VM shutdown.runtime/engines/engine_lifecycle.mtsowns the closed result, shared-workload review and coordination;engine_colima_backend.mtsowns the qualified profile, disk, boot and process proofs. Explicit shutdown uses the sharedengine-stopworkload ticket instead of creating a project lock. Its signal scope preserves typed uncertainty after dispatch, and installed-package fingerprint checks still surround the mutation. Automatic owned-idle shutdown remains a separate receipt-bound policy.runtime_planning.mtsowns read-only stack plans and exact candidate summaries.editor_command_handlers.mtsexposes bounded migration and configuration review contracts plus digest-bound, non-destructive stale-environment stop review. It also keeps impact preview/measurement dispatch thin; aggregate policy stays in runtime.source_commands.mtscoordinates approved source access and refresh.renderers.mtsformats human-readable results without changing state.terminal.mtsowns prompts, colors, and terminal exit behavior.
Command handlers receive an explicit context containing parsed flags, selected config,
guided state, and session-local caches. They return a rendered, text, or silent result;
only the shared output boundary creates JSON envelopes or writes final human output.
runtime/migrations/migration_failure.mts owns bounded provider-envelope SQLSTATE recognition,
fixed classification/remediation and closed safe diagnostic validation. Target drivers
never forward SQL or provider error details. The manager summary reconstructs that
fixed diagnostic across the child-process boundary; CLI JSON and private operation
history expose the same projection. Activity adds a separate recentFailures list,
leaving existing strict progress/recent receipt shapes unchanged for old clients.
The optional source projection is owned by runtime/migrations/migration_failure_source.mts.
For individually dispatched PostgreSQL files, it identifies the attempted execution
input by its reviewed filename, exact SHA-256 and baseline/candidate kind. The driver
hashes the bytes it loads before dispatch; changed reviewed bytes refuse execution.
Only a safe project-relative candidate path may be included, never an absolute path;
baseline inputs keep that path null. This is not attribution of the failing SQL's actual
origin: included scripts, functions and triggers can fail elsewhere. SQL line and column
remain null. Supabase batch execution currently supplies no file attribution, and
ambiguous or unavailable evidence is not inferred from candidate count or provider text.
cli/presentation/failure_output.mts preserves the outer category and cleanup warning when a
stack failure wraps the original migration error. It projects only a validated fixed
diagnosis from at most four original-error wrappers, never cleanup siblings or causes.
Session caches never appear in the public parsed-flags type.
Owned child output is decoded as UTF-8 independently for stdout and stderr, preserving
characters split across pipe chunks. Byte counts and per-stream limits use the original
bytes; an incomplete trailing sequence becomes a replacement character when the process
closes. If a process floods its byte boundary, Rehearsal sends TERM and forcibly reaps
only that owned process group after one second; a child ignoring TERM cannot leave the
operation hanging indefinitely.
Application sessions retain no diagnostic text; each stream reports total observed raw
bytes, saturated at Number.MAX_SAFE_INTEGER.
Repository contracts keep the process entry point at 300 lines or fewer and every handler-family module at 350 lines or fewer. A new command belongs in the narrowest existing family, or in a new focused family when it represents a genuinely separate responsibility.
Static Migration Insights has a separate additive contract from migration-plan v1 and
post-failure SQLSTATE diagnosis. runtime/migrations/inspection/migration_insights_input.mts owns bounded
regular-file reads and private exact-input text; the existing inventory, baseline-prefix
and topology owners still calculate the candidate digest. Repeated shared-directory
inputs must keep the same raw hash; findings retrieve text only by its expected hash.
shared/held_path_ancestry.mts retains canonical directory identities and timestamps
to refuse detected concurrent ancestry changes. This is not atomic openat resolution
or a filesystem sandbox; leaf checks and existing workspace trust remain necessary.
migration_sql_lexer.mts and
migration_sql_scan.mts own bounded lexical positions and fixed review hints, not SQL
validation. migration_insights.mts alone projects redacted public findings and explicit
coverage/unknown states. The editor consumes that contract; it must not reimplement SQL
analysis or infer runtime measurements from static warnings.
Migration impact is a separate optional contract, not a new rehearsal gate.
runtime/migrations/impact/migration_impact_plan.mts recognizes only bounded simple SQL forms and retains
private relation/column specifications; it does not execute migrations or claim SQL
validity. migration_impact_queries.mts validates those specifications and generates
fixed, identifier-quoted aggregate queries. migration_impact_catalog.mts owns the
closed native index, statistics and operator-family predicates. Metadata checks refuse unsupported
table, type and operator semantics; public output contains count strings or explicit
unknowns, never those private specifications, SQL, object names or row contents.
migration_impact.mts binds preview and measurement reports to the whole candidate
digest, selected target, immutable baseline and exact input bytes. It rechecks the
binding after measurement and never interprets current counts as sequential migration
simulation or a production prediction.
targets/migration_impact_runtime.mts owns access to an already-running, verified,
ownership-proven local sandbox and its unchanged identity. It does not start/repair
an engine, reset data or apply migrations. Measurement uses one read-only repeatable
read count transaction with bounded locks, statements, output and total duration.
The environment-scrubbed client connects only through the proven owned container's
fixed local socket. PostgreSQL uses its configured local owner; Supabase uses its
built-in supabase_admin, not the restricted application-facing postgres role.
The fixed temporary-file bound and namespace-catalog lock require that local
administrator. No grants, role promotion, password access, network connection or
caller-selected SQL is added; the same read-only compiler and metadata refusals apply.
A separate read-only catalog preflight retains relation OIDs; globally ordered
SHARE ROW EXCLUSIVE locks precede the first repeatable-read snapshot, preventing
index/statistics DDL from outrunning its metadata checks. Counts recheck the retained
OIDs and supported semantics after locking. A concurrent name-to-view swap can
transiently lock view dependencies within the selected sandbox, but cannot make the
compiler execute that view query or return its counts. This is not atomic name/OID
resolution or a sandbox for a compromised database server. The private transport
also takes a bounded database-local namespace-catalog SHARE lock before relation
name resolution, preventing schema rename/swap during checks and aggregates.
This can temporarily block schema-catalog changes anywhere in that selected
disposable database; it does not change another database or acquire a cluster-wide lock.
The transport invokes the script compiler after final identity preflight so a slow check cannot
leave an earlier, larger server deadline embedded in the submitted script. The CLI
classifies measure impact for the existing project-operation lock and cancellation
owner despite the SQL being read-only; operation metadata/history may be written.
inspect impact is an offline preview. Both require one explicit configured target;
measurement additionally requires the exact whole-plan confirmation. Neither command
is a prerequisite for ordinary run or migrate, and both remain free CLI features.
Configuration pipeline#
The stable project/configuration.mts facade keeps existing imports compatible while
configuration work moves through explicit phases under project/configuration/:
configuration_discovery.mtsselects one supported project-owned config path.configuration_schema.mtsvalidates the raw object shape and rejects unknown keys.configuration_normalization.mtsapplies defaults and semantic safety constraints.configuration_resolution.mtsresolves owned paths from the project root and checks destructive-operation boundaries.
The project_discovery.mts facade orchestrates the separate read-only Project Profile.
Its versioned contract, bounded metadata access, and application inference live in
focused modules under project/discovery/. They never import project modules and classify
output as detected, suggested, or requiring a human decision. Discovery may report
proposed configuration fields, but setup and configuration rendering remain the only
owners that can prepare writes. Editor clients consume rehearsal discover --json;
they do not reproduce comprehensive discovery rules.
project_discovery_migration_tool.mts owns migration-format classification and
directory-selection decisions, including the existing Prisma 7 and Drizzle paths
and separate Prisma 8 metadata. The project-profile facade delegates those choices.
The public contract/defaults, primitive validators, project detection, and starter
rendering have their own focused modules. NormalizedRehearsalConfig is inferred from
the normalizer, while the package's public declarations are emitted from the same
TypeScript implementation. Repository contracts keep the facade at 50 lines or fewer
and each configuration phase at 700 lines or fewer.
Installed-consumer verification#
Repository verification installs the package tarball into disposable projects; it must
not import unpublished product source by accident. One scenario catalog drives both the
individual fixture commands and npm run release:verify.
scenarios/artifact.mjsselects or packs one tarball, reads its package identity, and records its SHA-256 before installation.scenarios/workspace.mjscreates and removes only scenario-owned scratch roots.scenarios/process.mjsstarts commands with inherited credentials removed unless a scenario explicitly supplies a safe value.scenarios/application_session.mjsowns persistent application and terminal-session checks.scenarios/fixture_container.mjsowns only the standalone source fixture: a unique creation ID and nonce, pinned local engine, and image-created anonymous volumes. Cleanup refuses ownership or mount drift, verifies removal, and cannot hide the original failure or report success early. This is not persistent-runtime cleanup.scenarios/catalog.mjsis the sole ordered list of installed-consumer scenarios.- Fixture files contain only the target setup and assertions unique to that scenario.
Each scenario remains independently runnable through its test:fixture:* script. The
complete release gate runs every catalog entry against the same immutable tarball and
writes its version, SHA-256, tool environment, commands, timings, and results under
test-results/release-gate/.
The existing Supabase scenario includes native syntax and populated-row constraint
failures, fixed public error/history diagnostics, reviewed corrections and independent
data/Storage preservation checks. It does not infer a rollback from a failed migration.
Runtime lifecycle#
The separate runtime/migrations/native/prisma8/prisma8_artifacts.mts owner provides
bounded, pure compiled-JSON integrity review through the advanced migrations export.
It validates the pinned Prisma 8 migration hash, shallow operation structure and
invariant consistency, returning only redacted counts and history hashes. It does
not execute operations, validate contract snapshots or replace the Prisma 7 adapter
and baseline format. Project discovery identifies conventional metadata separately
from this artifact review; neither establishes Prisma 8 runtime qualification.
Core 2.4.0's separate executable Prisma 8 path uses prisma8_inventory.mts for
compiled-file and graph receipts, prisma8_toolchain.mts for the exact installed
SDK closure, and targets/native/prisma8_migration_process.mts for replay through
the shared owned-process boundary. Format 7 retains semantic edge identities and
exact snapshot/file receipts independently of Prisma 7's format 3. Core-owned
Prisma 8 children preserve explicitly enabled Electron Node mode without inheriting
ambient Node overrides. The worker loads the pinned SDK and compiled JSON, never
project prisma.config.ts or author migration TypeScript. The
configuration profile owns the exact
rc.25/linear-graph limits and independently qualified native host scope.
Prisma 8 retains at most one process-local toolchain evidence record. Reuse requires fresh dependency resolution and checks of every original file and directory identity; drift refuses the call rather than silently replacing the reviewed digest. No persistent cache or held file handles survive the operation. Cancellation is cooperative between bounded filesystem operations; it does not claim to interrupt an operating-system filesystem call atomically.
Explicit Prisma Migrate 7 configuration selects runtime/migrations/native/prisma/prisma_history.mts for
bounded raw-byte history and native-ledger validation. The toolchain owner binds
the installed execution dependencies; native_migration_contract.mts distinguishes
portable baseline history from the current execution binding. Read-only active
baseline/resume checks validate fresh native inventory against the portable baseline
prefix and lock without hashing executable dependencies or creating a candidate digest.
Candidate review still binds the full current toolchain. A single plan inspection reuses
its exact per-target inventory, and deploy hashes the complete toolchain, then rechecks fresh source/private-copy
and generated-config bytes immediately before dispatch, and hashes again after execution;
no persistent hash cache or reduced dependency closure is used. Late native dispatch
and completion assert the active pointer and an unchanged regular manifest (at most
8 MiB) against the already fully verified baseline; this metadata assertion does not
rehash or newly verify row payloads and is not applied to SQL formats 1/2. Prepared
native schema/config bytes are checked again after execution. Same-owner mutation
races are not an atomic-openat or filesystem-sandbox guarantee. Baseline format 3
preserves native paths and lock bytes; existing SQL formats remain unchanged.
targets/postgresql/postgresql_migrations.mts owns SQL/native dispatch, while
prisma_migration_process.mts owns only private-config, bounded native execution
against the exact target proven by prisma_target_binding.mts. A native migration
failure preserves its data volume and requires explicit recovery; the extension
consumes the public review contract and never runs a second migration engine.
targets/sqlite/sqlite_inspection.mts owns the current engine-scoped capability
report. Engine identity, execution backend, observed availability and supported
features remain separate: an available backend does not prove feature support or
a successful rehearsal, and missing observations stay unknown. The
SQLite guide owns its binding and file-lifecycle limits; the
command reference owns database capabilities --json usage.
runtime/lifecycle/lifecycle_engine.mts owns the target-neutral lifecycle contract. Both
PostgreSQL and Supabase use it to dispatch commands, verify active baseline inputs,
calculate and confirm the exact migration set, write target-bound receipts, validate
runtime markers, and attempt owned failure cleanup without hiding the original error.
That cleanup can remove the disposable runtime; a failure message does not establish a
SQL transaction rollback, restoration of sandbox edits, or successful resource removal.
The files in src/targets/ remain drivers. They prove ownership before deleting local
resources and implement only the behavior that genuinely differs: Docker PostgreSQL
containers and SQL setup on one side; Supabase CLI, Auth, Storage, and generated config
on the other. An ordinary stop never enters rollback or discard, so later start
preserves the sandbox database and Storage contents.
SQLite boundary in Core 2.3.0#
SQLite in Core 2.3.0 uses the same lifecycle dispatch without
Docker admission. targets/sqlite/sqlite_manager.mts owns private runtime receipts
and exact file transitions; sqlite_files.mts owns canonical identity guards.
baseline/producers/sqlite_baseline.mts creates separate format-6 generations.
sqlite_worker_process.mts supervises bounded private jobs, and sqlite_worker.mts
alone executes native SQL, typed sanitization and journal verification.
Before migration, the manager exclusively preclaims the DELETE journal and records its identity in a dirty receipt. Only confirmed worker closure permits guarded recovery of that original journal; a replacement or unconfirmed worker never gains cleanup authority. Fixed transport failures preserve cleanup uncertainty through inspection and CLI boundaries. Worker memory uses supervised sampled RSS, not a hard native-memory or OS quota; the guide owns the exact limits. SQLite has its own runtime qualification and does not inherit PostgreSQL/Supabase platform support. The capability catalog records verified release availability.
Within targets/postgresql/, postgresql_resume_protocol.mts owns retained-container
contracts, binding checks and reconstruction sequencing through an injected adapter.
postgresql_container_resume.mts owns private recovery receipts and real Docker
lifecycle probes, reusing those checks and retaining its existing exports. The protocol
keeps cancellation, deadlines and startup-ownership capture with reconstruction;
the adapter remains responsible for its actual engine and filesystem observations.
postgresql_process.mts owns finite asynchronous command/SQL budgets and the bounded
synchronous custom-adapter callback; postgresql_resources.mts requires successful
exact listings before recovery deletion. Built-in ledgers and native target guards
await that transport. Container retirement shares one validation/command sequence
between its existing synchronous public API and the driver's asynchronous variant.
runtime/recovery/restore_process.mts shares bounded COPY transport between PostgreSQL
and Supabase while each driver retains its provider-specific SQL/cache input.
The shared owned-process runner streams restore input with backpressure; interrupted
or exited-leader pipe uncertainty is bounded locally and never proves backend cleanup.
CLI command completion and database lifecycle are separate. A successful run can finish
and release its project lock while the configured keep-until-stop database remains
running. The project-owned CLI proof has its own primary application-proof stage;
HTTP readiness is optional and is not a prerequisite for a database-only proof. Public
operation receipts record those past stages, not fresh proof of subsequently changed
configuration, baseline or migration bytes. Editor presentation consumes that evidence
without interpreting database liveness as an active command or successful proof.
Repository contracts keep each target driver at 900 lines or fewer and the shared lifecycle engine at 300 lines or fewer. A new database target must use this lifecycle boundary rather than copying an existing driver's orchestration.
Native migration producers#
Explicit configuration selects native producers; metadata discovery never imports
project migration configuration, schema or environment files. Prisma and the
separate Drizzle integration share runtime/migrations/native/native_toolchain* for complete bounded
resolved package fingerprints and targets/native/native_migration_process.mts for the
private process/cancellation/target/source/baseline boundary. Producer recipes own
their exact file inventory, generated closed configuration and actual CLI argv.
No recipe generates or repairs source history. Format 3 remains Prisma-specific;
format 4 records Drizzle's ordered native journal identities and raw receipt.
The baseline owner and
configuration contract
explain the qualified scope and unsupported cases.
Identity claim pipeline#
The stable identity/claim.mts facade exposes policy validation, deterministic planning,
and confirmed execution while keeping those responsibilities separate in identity/claims/:
claim_contract.mtsdefines the normalized policy, plan, database, and receipt types.claim_policy.mtsvalidates and normalizes the reviewed declaration.claim_plan.mtsbinds the local matcher value to an immutable redacted review and digest without opening a database or Storage connection.claim_sql.mtsgenerates identifier-safe relational, JSON, signup-default, and path SQL without executing it.claim_identity_lookup.mtsperforms read-only local Auth and reference discovery.claim_verification.mtschecks signup defaults and token-hook claim shapes.claim_executor.mtsalone owns the database transaction, Storage staging, rollback, commit, old-object cleanup, and final receipt.connect.mtsperforms read-only, provider-neutral sign-in discovery and produces the redacted preview used by the interactive copied-account connection.
Repository contracts keep the facade at 50 lines or fewer and every identity-claim stage at 600 lines or fewer. Provider callbacks and consumer application behavior stay outside this pipeline.
Privacy rule pipeline#
The stable baseline/privacy_engine.mts facade preserves the documented privacy import
path while policy work is divided into fail-closed typed stages:
privacy_contract.mtsdefines normalized policy and execution types.privacy_recipe_validation.mtsnormalizes only reviewed rule shapes;privacy_policy.mtsvalidates complete policy structure.privacy_dependency_graph.mtschecks owner bindings, path mappings, sanitized digest inputs, cycles, and shared date groups.privacy_transforms.mtsimplements deterministic pseudonyms and bounded paths.privacy_rule_registry.mtsexplicitly registers every action and derivation kind; unknown kinds have no fallback execution path.privacy_structured_json.mtsowns bounded object, array, union, and dictionary rules.privacy_pipeline.mtsresolves reviewed bindings and executes rows, whileprivacy_key.mtsowns the local secret-file boundary.
Repository contracts keep the facade at 50 lines or fewer and every privacy stage at 700 lines or fewer. Adding a rule requires its normalized type, validator, registered handler, focused boundary tests, and documentation—without widening policy version 2.
Adding something new#
- Put policy and reusable behavior in the domain that owns it.
- Put target-specific implementation behind the target boundary.
- Add its focused test under the matching
tests/unit/domain. - Add an integration or contract test only when behavior crosses domains or becomes a public promise.
- Update the documentation map when adding a new guide.
Run npm run build after changing TypeScript source. Tests import the generated package
code so the same JavaScript boundary consumers install is exercised locally.