diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,9 @@
+# Changelog
+
+## [Unreleased]
+
+## [0.1.0.0] - 2026-12-03
+
+### Added
+
+- Initial release.
diff --git a/LICENSE b/LICENSE
new file mode 100644
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Kris Nuttycombe
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/dag-migrations.cabal b/dag-migrations.cabal
new file mode 100644
--- /dev/null
+++ b/dag-migrations.cabal
@@ -0,0 +1,78 @@
+cabal-version: 3.0
+name:          dag-migrations
+version:       0.1.0.0
+synopsis:      Database migrations that form a directed acyclic graph
+description:
+  Migrations declare their dependencies, and run in a monad that each
+  project chooses. The library validates the dependency graph, plans runs
+  purely, and runs each migration in its own transaction through a
+  database adapter. The package includes the guide
+  <https://github.com/nuttycom/dag-migrations/blob/canon/dag-migrations/docs/writing-haskell-migrations.md docs/writing-haskell-migrations.md>,
+  on writing and running migrations.
+
+category:      Database
+license:       MIT
+license-file:  LICENSE
+author:        Kris Nuttycombe
+maintainer:    Kris Nuttycombe <kris@nutty.land>
+homepage:      https://github.com/nuttycom/dag-migrations
+bug-reports:   https://github.com/nuttycom/dag-migrations/issues
+build-type:    Simple
+extra-doc-files:
+  CHANGELOG.md
+  docs/writing-haskell-migrations.md
+tested-with:   GHC ==9.6.* || ==9.8.* || ==9.10.* || ==9.12.*
+
+source-repository head
+  type:     git
+  location: https://github.com/nuttycom/dag-migrations.git
+  subdir:   dag-migrations
+
+common language
+  default-language:   GHC2021
+  default-extensions: OverloadedStrings
+  ghc-options:
+    -Wall -Wcompat -Widentities -Wincomplete-record-updates
+    -Wincomplete-uni-patterns -Wmissing-export-lists -Wpartial-fields
+    -Wredundant-constraints -Wunused-packages
+
+library
+  import:          language
+  hs-source-dirs:  src
+  exposed-modules:
+    Database.DagMigrations
+    Database.DagMigrations.Adapter
+    Database.DagMigrations.Error
+    Database.DagMigrations.Graph
+    Database.DagMigrations.Migration
+    Database.DagMigrations.Plan
+    Database.DagMigrations.Progress
+    Database.DagMigrations.Run
+
+  build-depends:
+    , base          >=4.18 && <5
+    , containers    >=0.6  && <0.9
+    , text          >=2.0  && <2.2
+    , transformers  >=0.6  && <0.7
+
+test-suite dag-migrations-test
+  import:         language
+  type:           exitcode-stdio-1.0
+  hs-source-dirs: test
+  main-is:        Main.hs
+  other-modules:
+    Database.DagMigrations.FakeAdapter
+    Database.DagMigrations.Gen
+    Database.DagMigrations.GraphSpec
+    Database.DagMigrations.PlanSpec
+    Database.DagMigrations.RunSpec
+
+  build-depends:
+    , base
+    , containers
+    , dag-migrations
+    , hedgehog        >=1.4  && <1.8
+    , hspec           >=2.11 && <2.12
+    , hspec-hedgehog  >=0.3  && <0.4
+    , text
+    , transformers
diff --git a/docs/writing-haskell-migrations.md b/docs/writing-haskell-migrations.md
new file mode 100644
--- /dev/null
+++ b/docs/writing-haskell-migrations.md
@@ -0,0 +1,488 @@
+# Writing Haskell migrations
+
+In `dag-migrations`, a migration is a Haskell value. This guide is for the
+authors of a project's migrations: how to define them, how to run them, and
+how to keep them correct while the rest of the project's code changes.
+
+The code in this guide comes from two modules of an example project, in the
+`dag-migrations` repository:
+
+- `Database.DagMigrations.PostgreSQL.Example.Migration`, in
+  [`dag-migrations-postgresql-simple/test/Database/DagMigrations/PostgreSQL/Example/Migration.hs`](https://github.com/nuttycom/dag-migrations/blob/canon/dag-migrations-postgresql-simple/test/Database/DagMigrations/PostgreSQL/Example/Migration.hs),
+  holds the monad of the migrations and its operations;
+- `Database.DagMigrations.PostgreSQL.Example`, in
+  [`dag-migrations-postgresql-simple/test/Database/DagMigrations/PostgreSQL/Example.hs`](https://github.com/nuttycom/dag-migrations/blob/canon/dag-migrations-postgresql-simple/test/Database/DagMigrations/PostgreSQL/Example.hs),
+  holds the migrations and the functions that run them.
+
+The test suite of `dag-migrations-postgresql-simple` compiles both modules,
+and runs the migrations against PostgreSQL. Both modules enable the
+language extensions `GHC2021` and `OverloadedStrings` with `LANGUAGE`
+pragmas, so a project that copies them needs no extensions of its own. The
+first module imports:
+
+```haskell
+import Control.Monad (void)
+import Control.Monad.Trans.Class (lift)
+import Control.Monad.Trans.Except (ExceptT, runExceptT, throwE)
+import Control.Monad.Trans.Reader (ReaderT (..), runReaderT)
+import Data.Text (Text)
+import Database.DagMigrations (Interpreter (..))
+import Database.DagMigrations.PostgreSQL.Simple (Transaction, executeSqlIn, transactionConnection)
+import Database.PostgreSQL.Simple (FromRow, Query, ToRow, execute, query)
+```
+
+The second module imports:
+
+```haskell
+import Control.Monad (unless)
+import Data.Bifunctor (first)
+import Data.Foldable (traverse_)
+import Data.List (sort)
+import Data.List.NonEmpty (NonEmpty)
+import Data.Map.Strict qualified as Map
+import Data.Set qualified as Set
+import Data.Text (Text)
+import Data.Text qualified as Text
+import Database.DagMigrations
+  ( Direction,
+    Fingerprint (..),
+    Inspection,
+    Migration (..),
+    MigrationGraph,
+    Migrator (..),
+    RunError,
+    Target,
+    ValidationError,
+    defaultRunSettings,
+    inspect,
+    migrate,
+    silentProgress,
+    textIdentifiers,
+    validate,
+  )
+import Database.DagMigrations.PostgreSQL.Example.Migration (ProjectMigration, executeRow, failMigration, projectInterpreter, queryRows, runSql)
+import Database.DagMigrations.PostgreSQL.Simple (PgError, Transaction, defaultAdapterSettings, postgresAdapter)
+import Database.PostgreSQL.Simple (Connection, Only (..))
+```
+
+## Terms
+
+- The **registry** is the list of every migration of a project.
+- The **tracking table** is the table in which the adapter records the
+  identifier of each migration that the runner has applied to the
+  database.
+- An **adapter** gives the library access to one kind of database. The
+  PostgreSQL adapter is `postgresAdapter`, from
+  `dag-migrations-postgresql-simple`.
+- The **runner** is the code behind `migrate`, which applies and reverts
+  migrations through an adapter.
+- The **run lock** is a lock that the adapter holds while a run lasts, so
+  that two runs against the same database never happen at the same time.
+  The PostgreSQL adapter uses an advisory lock.
+
+## A migration
+
+A value of type `Migration i m` describes one migration. Its identifier
+has type `i`, and its actions run in the monad `m`:
+
+```haskell
+-- | A migration that only changes the schema.
+addViewFilters :: Migration Text ProjectMigration
+addViewFilters =
+  Migration
+    { migrationId = "2026-03-08_00-00-00_add-view-filters",
+      migrationDependencies = Set.fromList ["2022-11-27_22-28-18_create-views"],
+      migrationDescription = "Add a filter column to saved views",
+      migrationFingerprint = Just (Fingerprint "1"),
+      migrationUp = runSql "ALTER TABLE saved_views ADD COLUMN filter text;",
+      migrationDown = Just (runSql "ALTER TABLE saved_views DROP COLUMN filter;")
+    }
+```
+
+- `migrationId :: i` names the migration. No two migrations of the registry
+  have the same identifier.
+- `migrationDependencies :: Set i` holds the identifiers of the migrations
+  that the runner must apply before this one. The migrations and their
+  dependencies form a directed acyclic graph.
+- `migrationDescription :: Text` is text for people to read.
+- `migrationFingerprint :: Maybe Fingerprint` is a value that the
+  migration's author changes whenever the migration's effect changes. See
+  [Fingerprints](#fingerprints).
+- `migrationUp :: m ()` is the action that applies the migration.
+- `migrationDown :: Maybe (m ())` is the action that reverts the migration,
+  or `Nothing` when the migration cannot be reverted.
+
+For SQL that spans several lines, `dag-migrations-postgresql-simple` has
+the quasiquoter `sqlText`, in the module
+`Database.DagMigrations.PostgreSQL.SqlText`. A quotation
+`[sqlText| ... |]` holds the SQL one line to a line of the source file,
+without escapes, and stands for the SQL's text. The documentation of the
+module describes the layout of a quotation.
+
+The example project's registry is:
+
+```haskell
+-- | Every migration of the project.
+registry :: [Migration Text ProjectMigration]
+registry = [createViews, addViewFilters, splitViewFilters, normalizeViewNames]
+```
+
+`validate` takes the registry. It returns a `MigrationGraph` when the
+registry is valid. Otherwise it returns every problem that it found:
+repeated identifiers, dependencies on identifiers that no migration has,
+and cycles.
+
+## The monad of the migrations
+
+The library does not constrain the monad in which migrations run. A project
+chooses a monad that gives its migrations exactly the operations that they
+need. The example project defines the monad `ProjectMigration`, with three
+operations, `runSql`, `queryRows` and `executeRow`, and one way to fail,
+`failMigration`. The monad, the operation `runSql`, and `failMigration` are:
+
+```haskell
+-- | The monad in which the project's migrations run.
+newtype ProjectMigration a = ProjectMigration (ReaderT Transaction (ExceptT Text IO) a)
+  deriving (Functor, Applicative, Monad)
+```
+
+```haskell
+-- | Runs SQL text in the migration's transaction. The text may hold several
+-- statements, and its last statement may be a query, whose rows 'runSql'
+-- discards. The text must not hold @COMMIT@, @ROLLBACK@,
+-- @COPY ... FROM STDIN@ or @COPY ... TO STDOUT@. When PostgreSQL rejects a
+-- statement, the migration fails with the adapter's error, and the adapter
+-- rolls back its transaction.
+runSql :: Text -> ProjectMigration ()
+runSql sql = ProjectMigration (ReaderT (lift . (`executeSqlIn` sql)))
+```
+
+```haskell
+-- | Ends the migration with this message. The adapter rolls back the
+-- migration's transaction, and the run reports the message in
+-- 'Database.DagMigrations.MigrationFailed'.
+failMigration :: Text -> ProjectMigration a
+failMigration = ProjectMigration . lift . throwE
+```
+
+`ProjectMigration` has no `MonadIO` instance, and its module does not export
+its constructor. So a migration in another module reaches the database only
+through the three operations. The type does not stop every escape:
+
+- code that imports `Database.PostgreSQL.Simple.Internal` or
+  `System.IO.Unsafe` can run other `IO`;
+- a `FromRow` instance of a row type that a migration reads can run `IO`,
+  and so can an application function that the migration calls;
+- the database runs the migration's SQL with the privileges of the
+  database role, which may include reading files on the server.
+
+A reviewer of a migration therefore checks its imports, the instances of
+the row types that it reads and writes, the application functions that it
+calls, and its SQL.
+
+An author must not run `COMMIT` or `ROLLBACK` through any of the three
+operations. After such a statement, the adapter can no longer roll back the
+migration's changes, and some of them may stay committed without a row in
+the tracking table. The PostgreSQL adapter detects this in most cases, and
+reports `TransactionEnded`.
+
+To give migrations another operation, a project adds a function of type
+`... -> ProjectMigration a` to the monad's module. A project never changes
+what an existing operation does, because every old migration uses the
+operations, and a new database runs the old migrations with the operations
+of the day.
+
+An `Interpreter tx m e` runs an action of the monad `m` in a transaction of
+type `tx`. It returns `Left` with an error of type `e` when the action
+fails, and the adapter then rolls the transaction back. The example
+project's interpreter is:
+
+```haskell
+-- | Runs a 'ProjectMigration' in a transaction of the PostgreSQL adapter.
+projectInterpreter :: Interpreter Transaction ProjectMigration Text
+projectInterpreter = Interpreter (\tx (ProjectMigration action) -> runExceptT (runReaderT action tx))
+```
+
+## Running migrations
+
+`migrate` takes a `Migrator`, a direction, and a target. A `Migrator` holds:
+
+- the adapter;
+- the identifier codec, which converts identifiers to the text values in
+  the tracking table and back. `textIdentifiers` is the codec for `Text`
+  identifiers;
+- the interpreter;
+- a `Progress` value, which receives an event for each thing that the
+  runner does. `silentProgress` ignores the events;
+- the `RunSettings`;
+- the graph that `validate` returned.
+
+The example project builds its `Migrator`, and runs its migrations, with
+these definitions:
+
+```haskell
+-- | The project's migrator over the connection, with
+-- 'defaultAdapterSettings' and 'defaultRunSettings'.
+projectMigrator ::
+  Connection ->
+  MigrationGraph Text ProjectMigration ->
+  Migrator Text ProjectMigration Transaction Text PgError
+projectMigrator connection graph =
+  Migrator
+    { migratorAdapter = postgresAdapter defaultAdapterSettings connection,
+      migratorCodec = textIdentifiers,
+      migratorInterpreter = projectInterpreter,
+      migratorProgress = silentProgress,
+      migratorSettings = defaultRunSettings,
+      migratorGraph = graph
+    }
+```
+
+```haskell
+-- | Why a run or an inspection of the project's migrations failed.
+data ProjectError
+  = -- | The registry is not valid, for these reasons.
+    InvalidRegistry (NonEmpty (ValidationError Text))
+  | -- | The run or the inspection failed with this error.
+    RunFailed (RunError Text Text PgError)
+  deriving (Eq, Show)
+```
+
+```haskell
+-- | Validates the registry, and moves the database to the target, with
+-- 'defaultAdapterSettings' and 'defaultRunSettings'. The connection must be
+-- open and idle, and no other code may use it during the run. Returns
+-- 'Left' when the registry is not valid or the run fails; the steps before
+-- a failed step stay committed. After an asynchronous exception, the
+-- caller closes the connection.
+migrateProject :: Connection -> Direction -> Target Text -> IO (Either ProjectError ())
+migrateProject connection direction target = case validate registry of
+  Left errors -> pure (Left (InvalidRegistry errors))
+  Right graph -> first RunFailed <$> migrate (projectMigrator connection graph) direction target
+```
+
+The runner takes the run lock, and holds it while it takes these steps:
+
+1. It reads the applied migrations from the tracking table, through the
+   adapter. When the table does not exist, the adapter reads no migrations.
+   The PostgreSQL adapter also reads the table that `dbmigrations` created,
+   without its row `root`, and with no fingerprints.
+2. It compares the recorded fingerprints with the registered ones, and
+   plans the run. When the comparison or the plan fails, the run writes
+   nothing.
+3. It creates the tracking table, or upgrades it to the current version.
+4. In one transaction, it records the registered fingerprints of applied
+   migrations that have none recorded (see [Fingerprints](#fingerprints)).
+5. It runs each step of the plan in its own transaction. A step applies or
+   reverts one migration, and records the change in the tracking table in
+   the same transaction.
+
+The first failed step ends the run. What the run did before it stays
+committed: the table's creation or upgrade, the recorded fingerprints, and
+the steps before the failed one.
+
+The runner builds the plan from the direction and the target:
+
+- `Up` with `AllMigrations` applies every registered migration that the
+  database has not applied.
+- `Up` with `TargetMigration t` applies `t` and the migrations that `t`
+  depends on, directly or indirectly. It skips each of them that the
+  database has applied.
+- `Down` with `TargetMigration t` reverts every applied migration that
+  depends on `t`, directly or indirectly. It keeps `t` applied.
+- `Down` with `AllMigrations` reverts every applied migration.
+
+An `Up` plan applies migrations in one fixed order: the lexicographically
+least order, by the identifiers' `Ord` instance, in which every migration
+comes after its dependencies. A `Down` plan reverts migrations in the
+reverse of that order. When a `Down` plan would revert a migration
+whose `migrationDown` is `Nothing`, the runner reverts nothing. It then
+reports every such migration.
+
+`inspect` reads the state of the database without the run lock, and writes
+nothing. Its result, an `Inspection`, has these fields:
+
+- `inspectedStatus`: each registered migration, in the order of the `Up`
+  plans, with whether the database has applied it;
+- `inspectedUnregistered`: the applied identifiers that no registered
+  migration has;
+- `inspectedMismatches`: the fingerprint mismatches;
+- `inspectedToRecord`: the fingerprints that a run would record on first
+  use.
+
+The example project calls it in `inspectProject`:
+
+```haskell
+-- | Validates the registry, and reads the state of the database without the
+-- run lock. Writes nothing. The connection must be open and idle. Returns
+-- 'Left' when the registry is not valid or the adapter cannot read the
+-- tracking table.
+inspectProject :: Connection -> IO (Either ProjectError (Inspection Text))
+inspectProject connection = case validate registry of
+  Left errors -> pure (Left (InvalidRegistry errors))
+  Right graph -> first RunFailed <$> inspect (projectMigrator connection graph)
+```
+
+## Fingerprints
+
+The runner uses fingerprints to detect that someone changed a migration
+after the runner applied it to a database.
+
+- When the runner applies a migration, the runner records the migration's
+  fingerprint in the tracking table.
+- When the tracking table holds no fingerprint for an applied migration,
+  and the migration's registered fingerprint is `Just f`, the runner
+  records `f`. The same rule covers a migration that the runner applied
+  before the migration had a fingerprint.
+- When the tracking table holds a fingerprint for an applied migration, and
+  the migration's registered fingerprint differs or is `Nothing`, the run
+  fails and writes nothing. Failing is the default policy, `MismatchIsError`.
+  Under `MismatchIsWarning`, the runner reports the mismatch through the
+  `Progress` value, and continues; with `silentProgress`, nobody sees the
+  report. The field `runFingerprintPolicy` of `RunSettings` holds the
+  policy.
+- When neither the tracking table nor the registry holds a fingerprint for
+  a migration, the runner compares nothing.
+- After a person checks that a changed migration is still correct for the
+  databases that applied it, `acceptFingerprints` records the registered
+  fingerprints of the migrations that the person names.
+
+When an author changes what a migration does, the author changes its
+fingerprint too. A migration converted from `dbmigrations` has the
+fingerprint `1`, which the first run records in each database. A project
+must not edit those migrations, because `dbmigrations` applied them to the
+project's databases in their current form. If someone edits one and changes
+its fingerprint, each run fails with `FingerprintsMismatched` on every
+database that has recorded `1`. A database on which no run has recorded `1` yet records the
+new fingerprint without a report; the guide
+[Converting from `dbmigrations`](https://github.com/nuttycom/dag-migrations/blob/canon/dag-migrations-postgresql-simple/docs/converting-from-dbmigrations.md)
+has the procedure that records `1` everywhere.
+
+## Migrations and code that changes
+
+A migration must give an acceptable result whatever later changes the
+project makes to the code that it calls.
+
+When someone creates a new database, the runner applies every migration to
+it. The actions of each migration then call the application's code as that
+code exists at that time, not as it was when someone wrote the migration.
+So a migration whose actions call application code meets the rule in one
+of two ways.
+
+The same holds for code outside the application. A project never changes
+what an existing operation of its migration monad does. A frozen type has
+an encoder and a decoder that its migration writes by hand, not instances
+that a library derives, because a new release of the library can change a
+derived instance.
+
+### Frozen types
+
+The migration keeps its own copy of every application type and function
+that it uses. This migration reads each saved view's definition with its
+own type, `SavedViewV1`:
+
+```haskell
+-- | A data migration with a frozen type: it reads each saved view's
+-- definition as 'SavedViewV1', and writes the filter part to the new
+-- column. Every definition must be of version 1; when one is not, the
+-- migration fails, names every such view, and changes nothing. Its
+-- 'migrationDown' is 'Nothing', so no run can revert it.
+splitViewFilters :: Migration Text ProjectMigration
+splitViewFilters =
+  Migration
+    { migrationId = "2026-03-09_00-00-00_split-view-filters",
+      migrationDependencies = Set.fromList ["2026-03-08_00-00-00_add-view-filters"],
+      migrationDescription = "Move each view's filter to its own column",
+      migrationFingerprint = Just (Fingerprint "1"),
+      migrationUp = do
+        rows <- queryRows "SELECT name, definition FROM saved_views ORDER BY name" ()
+        let decoded = [(name, decodeSavedViewV1 definition) | (name, definition) <- rows]
+            invalid = sort [name | (name, Nothing) <- decoded]
+        unless (null invalid) $
+          failMigration ("saved views whose definition is not of version 1: " <> Text.intercalate ", " (map quoted invalid))
+        traverse_
+          ( \(name, view) ->
+              executeRow
+                "UPDATE saved_views SET definition = ?, filter = ? WHERE name = ?"
+                (savedViewColumns view, savedViewFilter view, name)
+          )
+          [(name, view) | (name, Just view) <- decoded],
+      migrationDown = Nothing
+    }
+```
+
+```haskell
+-- | A saved view's definition as @2026-03-09_00-00-00_split-view-filters@
+-- reads it: the columns, a @|@, and the filter, which may be empty. The
+-- migration keeps this copy of the type and its decoder. So when someone
+-- changes the application's own type, the migration still does the same
+-- thing.
+data SavedViewV1 = SavedViewV1
+  { savedViewColumns :: Text,
+    savedViewFilter :: Text
+  }
+```
+
+```haskell
+-- | Reads a definition of version 1, or returns 'Nothing' when the text
+-- holds no @|@.
+decodeSavedViewV1 :: Text -> Maybe SavedViewV1
+decodeSavedViewV1 definition = case Text.breakOn "|" definition of
+  (columns, rest) | not (Text.null rest) -> Just (SavedViewV1 columns (Text.drop 1 rest))
+  _ -> Nothing
+```
+
+When the application's own type for a saved view changes, this migration
+still reads definitions of version 1, because the migration does not refer
+to the application's type.
+
+### Current code on an empty table
+
+The migration changes existing rows with the application's current code.
+On a new database, the table is empty when the migration runs, as long as
+every other migration that fills the table depends on this one, directly or
+indirectly. The migration then changes nothing there. Here,
+`normalizeViewName` stands for application code, and `quoted` only shapes
+the error message. Before it renames any view, the migration checks that no
+two names normalize to the same name, so that it fails with a message that
+names the views, not with the primary key's error. The renames assume that
+a normalized name normalizes to itself:
+
+```haskell
+-- | A data migration that uses the application's current code,
+-- 'normalizeViewName'. On a new database, @saved_views@ is empty when this
+-- migration runs, so the migration changes nothing there, whatever
+-- 'normalizeViewName' does by then. A later migration that fills
+-- @saved_views@ must depend on this one. When two names normalize to the
+-- same name, the migration fails, names them, and changes nothing. The
+-- renames assume that a normalized name normalizes to itself.
+normalizeViewNames :: Migration Text ProjectMigration
+normalizeViewNames =
+  Migration
+    { migrationId = "2026-03-10_00-00-00_normalize-view-names",
+      migrationDependencies = Set.fromList ["2022-11-27_22-28-18_create-views"],
+      migrationDescription = "Normalize the names of saved views",
+      migrationFingerprint = Just (Fingerprint "1"),
+      migrationUp = do
+        names <- map fromOnly <$> queryRows "SELECT name FROM saved_views ORDER BY name" ()
+        let groups = Map.fromListWith (flip (<>)) [(normalizeViewName name, [name]) | name <- names]
+            clashes = [sort group | group <- Map.elems groups, length group > 1]
+        unless (null clashes) $
+          failMigration ("saved views whose names normalize to the same name: " <> Text.intercalate "; " (map (Text.intercalate ", " . map quoted) clashes))
+        traverse_
+          (\name -> executeRow "UPDATE saved_views SET name = ? WHERE name = ?" (normalizeViewName name, name))
+          [name | name <- names, normalizeViewName name /= name],
+      migrationDown = Nothing
+    }
+```
+
+When someone changes the type of `normalizeViewName`, this migration stops
+compiling. Its author then copies the code that the migration uses, as in
+the first pattern, or updates the migration. The compiler reports a change
+of type, but cannot report a change of behavior. A database that has rows
+in the table, and has not yet applied the migration, gets the current
+behavior of `normalizeViewName`. Use this pattern only when the current
+behavior is acceptable for such a database.
+
+A migration that uses application code to create or fill rows, even on an
+empty database, needs the first pattern.
diff --git a/src/Database/DagMigrations.hs b/src/Database/DagMigrations.hs
new file mode 100644
--- /dev/null
+++ b/src/Database/DagMigrations.hs
@@ -0,0 +1,78 @@
+-- | Database migrations that form a directed acyclic graph, and that run
+-- in a monad that each project chooses.
+--
+-- A project registers its migrations, validates them with 'validate',
+-- and runs them with 'migrate', through a t'Migrator' that holds an adapter
+-- for its database and an interpreter for its monad.
+--
+-- A migration must give an acceptable result whatever later changes the
+-- project makes to the code that it calls, because the runner applies
+-- every migration to a new database with the code of the day of that run.
+-- So a migration either keeps its own copies of the application types and
+-- functions that it uses, or changes only existing rows, which a new
+-- database does not have, with a behavior of the current code that is
+-- acceptable for the databases that have them. The
+-- guide
+-- <https://github.com/nuttycom/dag-migrations/blob/canon/dag-migrations/docs/writing-haskell-migrations.md Writing Haskell migrations>
+-- has both patterns, and the choice of a monad for a project's migrations.
+module Database.DagMigrations
+  ( -- * Migrations
+    Migration (..),
+    hoistMigration,
+    Interpreter (..),
+    IdentifierCodec (..),
+    textIdentifiers,
+    Fingerprint (..),
+
+    -- * Validation
+    MigrationGraph,
+    validate,
+    registeredIdentifiers,
+    linearOrder,
+
+    -- * Planning
+    Target (..),
+    PlanOptions (..),
+    defaultPlanOptions,
+    Step (..),
+    Plan (..),
+    planIdentifiers,
+    plan,
+    checkFingerprints,
+    status,
+
+    -- * Running
+    Adapter,
+    Migrator (..),
+    RunSettings (..),
+    defaultRunSettings,
+    FingerprintPolicy (..),
+    migrate,
+    Inspection (..),
+    appliedSet,
+    inspect,
+    acceptFingerprints,
+
+    -- * Progress
+    Progress (..),
+    ProgressEvent (..),
+    TrackingVersion (..),
+    silentProgress,
+
+    -- * Errors
+    ValidationError (..),
+    PlanError (..),
+    FingerprintMismatch (..),
+    AcceptError (..),
+    Direction (..),
+    RunError (..),
+  )
+where
+
+import Database.DagMigrations.Adapter (Adapter)
+import Database.DagMigrations.Error
+import Database.DagMigrations.Graph
+import Database.DagMigrations.Migration
+import Database.DagMigrations.Plan
+import Database.DagMigrations.Progress
+import Database.DagMigrations.Run
diff --git a/src/Database/DagMigrations/Adapter.hs b/src/Database/DagMigrations/Adapter.hs
new file mode 100644
--- /dev/null
+++ b/src/Database/DagMigrations/Adapter.hs
@@ -0,0 +1,105 @@
+-- | The capability that a database adapter provides. This module is for
+-- the authors of adapters: a project passes an t'Adapter' to the runner,
+-- and never calls its fields. The module re-exports t'Fingerprint' and
+-- t'TrackingVersion', so that an adapter author needs only this import. A
+-- project imports "Database.DagMigrations" instead.
+module Database.DagMigrations.Adapter
+  ( Adapter (..),
+    BootstrapOutcome (..),
+    AppliedRow (..),
+    Fingerprint (..),
+    TrackingVersion (..),
+  )
+where
+
+import Data.Map.Strict (Map)
+import Data.Text (Text)
+import Database.DagMigrations.Migration (Fingerprint (..))
+import Database.DagMigrations.Progress (TrackingVersion (..))
+
+-- | What 'bootstrap' did to the tracking table.
+data BootstrapOutcome
+  = -- | The table was current, and the adapter changed nothing.
+    AlreadyCurrent
+  | -- | The adapter created the table, at this version.
+    Created TrackingVersion
+  | -- | The adapter upgraded the table from the first version to the
+    -- second.
+    Upgraded TrackingVersion TrackingVersion
+  deriving (Eq, Show)
+
+-- | The row with which the runner records an applied migration.
+data AppliedRow = AppliedRow
+  { appliedIdentifier :: Text,
+    appliedDescription :: Text,
+    appliedFingerprint :: Maybe Fingerprint
+  }
+  deriving (Eq, Show)
+
+-- | The operations of one database connection. @tx@ is the adapter's
+-- transaction value, which only 'withTransaction' produces. @ae@ is the
+-- adapter's error type. Each operation returns the adapter's own errors
+-- as 'Left', and propagates any other exception. The one exception to this
+-- rule is 'withRunLock', which throws a failure to release the lock, as its
+-- documentation states.
+--
+-- When an asynchronous exception, such as the one that
+-- 'System.Timeout.timeout' throws, interrupts an operation, the operation
+-- rethrows it, and leaves the session in an unknown state: a statement may
+-- still be running, a transaction may be open, and the session may later
+-- hold the run lock. The caller then closes the session, which ends the
+-- transaction and releases the lock.
+data Adapter tx ae = Adapter
+  { -- | Runs the action while holding the lock that keeps two runs apart,
+    -- and releases the lock when the action returns or throws. When another
+    -- session holds the lock, waits until that session releases it. An
+    -- asynchronous exception, such as the one that
+    -- 'System.Timeout.timeout' throws, interrupts the wait, and leaves the
+    -- session in an unknown state, in which it may later hold the lock.
+    -- After an interrupted wait, the caller closes the session. The lock
+    -- belongs to the session, so closing the session releases it. Returns
+    -- 'Left', and does not run the action, when the adapter cannot take the
+    -- lock: for example, when the connection fails, or when a limit on the
+    -- wait that the connection sets, such as PostgreSQL's @lock_timeout@,
+    -- expires. When the action has run and the adapter then fails to
+    -- release the lock, the adapter throws the failure as an exception, and
+    -- does not return 'Left'.
+    withRunLock :: forall a. IO a -> IO (Either ae a),
+    -- | Reads the applied identifiers and their recorded fingerprints, from
+    -- every version of the tracking table that the adapter recognizes.
+    -- Writes nothing. Returns an empty map when the tracking table does not
+    -- exist. From a @dbmigrations@ table (version 0), leaves out the row
+    -- @root@, which @dbmigrations@ writes for its own bootstrap migration,
+    -- reads an identifier that appears in several rows as one entry, and
+    -- reads no fingerprints.
+    readApplied :: IO (Either ae (Map Text (Maybe Fingerprint))),
+    -- | Creates or upgrades the tracking table, in one transaction. Does
+    -- nothing, and returns 'AlreadyCurrent', when the table is current, so
+    -- that a repeated call does no harm. An adapter that recognizes the
+    -- @dbmigrations@ table upgrades it without its row @root@, and returns
+    -- 'Upgraded' with version 0 as the first version. When that table holds
+    -- an identifier in several rows, the upgraded table holds one row for
+    -- the identifier. A row of that table holds nothing but the
+    -- identifier, so the upgrade loses no information.
+    bootstrap :: IO (Either ae BootstrapOutcome),
+    -- | Runs the action in a transaction. Commits when the action returns
+    -- 'Right', and rolls back when it returns 'Left'. When the action throws
+    -- an exception of the adapter's database library, rolls back and returns
+    -- the adapter's error as 'Left' ('Left' @ae@). When it throws any other
+    -- exception, rolls back and rethrows; an asynchronous exception that
+    -- interrupts a statement leaves the session to the caller to close, as
+    -- the documentation of t'Adapter' states.
+    withTransaction :: forall e a. (tx -> IO (Either e a)) -> IO (Either (Either ae e) a),
+    -- | Records an applied migration inside the transaction, with the
+    -- database's current time. Fails with the adapter's error when a row
+    -- for the identifier already exists.
+    recordApplied :: tx -> AppliedRow -> IO (Either ae ()),
+    -- | Removes the row of a reverted migration inside the transaction.
+    -- Fails with the adapter's error when no row for the identifier exists.
+    -- The runner removes only rows that it read while it held the run lock,
+    -- so when the row is missing, another process has changed the table.
+    removeApplied :: tx -> Text -> IO (Either ae ()),
+    -- | Sets the recorded fingerprints of the given applied migrations
+    -- inside the transaction. Ignores identifiers that have no row.
+    recordFingerprints :: tx -> Map Text (Maybe Fingerprint) -> IO (Either ae ())
+  }
diff --git a/src/Database/DagMigrations/Error.hs b/src/Database/DagMigrations/Error.hs
new file mode 100644
--- /dev/null
+++ b/src/Database/DagMigrations/Error.hs
@@ -0,0 +1,94 @@
+-- | The errors that validation, planning, and running report. A project
+-- imports "Database.DagMigrations", which re-exports everything that this
+-- module exports.
+module Database.DagMigrations.Error
+  ( ValidationError (..),
+    PlanError (..),
+    FingerprintMismatch (..),
+    AcceptError (..),
+    Direction (..),
+    RunError (..),
+  )
+where
+
+import Data.List.NonEmpty (NonEmpty)
+import Data.Text (Text)
+import Database.DagMigrations.Migration (Fingerprint)
+
+-- | A problem in a registry of migrations.
+data ValidationError i
+  = -- | More than one migration has this identifier.
+    DuplicateIdentifier i
+  | -- | The first migration depends on the second identifier, which no
+    -- migration has.
+    UnknownDependency i i
+  | -- | A cycle of dependencies: each identifier depends on the next, and
+    -- the last depends on the first.
+    DependencyCycle (NonEmpty i)
+  deriving (Eq, Ord, Show)
+
+-- | A reason why no plan exists for a database and a target.
+data PlanError i
+  = -- | No registered migration has the target identifier.
+    UnknownTarget i
+  | -- | A run applied this identifier to the database, and no registered
+    -- migration has it: the database is newer than the code.
+    UnregisteredApplied i
+  | -- | The applied set holds the first migration and not the second,
+    -- which the first depends on.
+    InconsistentApplied i i
+  | -- | Reaching the target requires reverting this migration, and it has
+    -- no down action.
+    Irreversible i
+  deriving (Eq, Ord, Show)
+
+-- | An applied migration whose recorded fingerprint differs from its
+-- registered one. The fields are the identifier, the recorded fingerprint,
+-- and the registered fingerprint.
+data FingerprintMismatch i
+  = FingerprintMismatch i (Maybe Fingerprint) (Maybe Fingerprint)
+  deriving (Eq, Ord, Show)
+
+-- | A reason why 'Database.DagMigrations.Run.acceptFingerprints' cannot
+-- accept the registered fingerprint of a named migration.
+data AcceptError i
+  = -- | No registered migration has this identifier.
+    NotRegistered i
+  | -- | The migration is registered, and the adapter does not report it as
+    -- applied.
+    NotApplied i
+  deriving (Eq, Ord, Show)
+
+-- | Whether a run applies migrations or reverts them.
+data Direction
+  = -- | The run applies migrations.
+    Up
+  | -- | The run reverts migrations.
+    Down
+  deriving (Eq, Ord, Show, Bounded, Enum)
+
+-- | A failed run. @e@ is the type of the errors that the project's
+-- interpreter reports, and @ae@ the type of the adapter's errors.
+data RunError i e ae
+  = -- | No plan exists, for the reasons listed.
+    PlanFailed (NonEmpty (PlanError i))
+  | -- | Under 'Database.DagMigrations.Run.MismatchIsError', the run found
+    -- these mismatches, and changed nothing.
+    FingerprintsMismatched (NonEmpty (FingerprintMismatch i))
+  | -- | The adapter read this text from the tracking table, and the
+    -- identifier codec does not decode it.
+    UndecodableIdentifier Text
+  | -- | The adapter read this text from the tracking table, and the
+    -- identifier codec decodes it to this identifier, whose encoding is
+    -- different text. The run writes rows by the encoding, so it could not
+    -- update or remove this row.
+    NonCanonicalIdentifier Text i
+  | -- | 'Database.DagMigrations.Run.acceptFingerprints' cannot accept these
+    -- names, and changed nothing.
+    CannotAccept (NonEmpty (AcceptError i))
+  | -- | The migration failed in the given direction, with the adapter's
+    -- error or the interpreter's.
+    MigrationFailed i Direction (Either ae e)
+  | -- | The adapter failed outside any migration.
+    AdapterFailed ae
+  deriving (Eq, Show)
diff --git a/src/Database/DagMigrations/Graph.hs b/src/Database/DagMigrations/Graph.hs
new file mode 100644
--- /dev/null
+++ b/src/Database/DagMigrations/Graph.hs
@@ -0,0 +1,196 @@
+-- | Validation of a registry of migrations, and the dependency graph that
+-- it produces. A project imports "Database.DagMigrations", which re-exports
+-- t'MigrationGraph', 'validate', 'registeredIdentifiers', and 'linearOrder'
+-- from this module.
+module Database.DagMigrations.Graph
+  ( MigrationGraph,
+    validate,
+    registeredIdentifiers,
+    lookupMigration,
+    linearOrder,
+    inLinearOrder,
+    downSet,
+    upSet,
+  )
+where
+
+import Data.Graph (SCC (..), stronglyConnComp)
+import Data.Graph qualified as Graph
+import Data.List qualified as List
+import Data.List.NonEmpty (NonEmpty (..))
+import Data.List.NonEmpty qualified as NonEmpty
+import Data.Map.Strict (Map)
+import Data.Map.Strict qualified as Map
+import Data.Maybe (fromMaybe)
+import Data.Set (Set)
+import Data.Set qualified as Set
+import Database.DagMigrations.Error (ValidationError (..))
+import Database.DagMigrations.Migration (Migration (..))
+
+-- | A registry of migrations that has passed validation: identifiers are
+-- unique, every dependency is registered, and the dependencies are
+-- acyclic. Only 'validate' builds one.
+data MigrationGraph i m = MigrationGraph
+  { graphMigrations :: Map i (Migration i m),
+    -- | The lexicographically least linear extension of the dependency
+    -- order, by @Ord i@.
+    graphOrder :: [i],
+    graphDependencies :: Graph.Graph,
+    graphVertexKey :: Graph.Vertex -> i,
+    graphKeyVertex :: i -> Maybe Graph.Vertex
+  }
+
+-- | Checks a registry, and returns either every problem that it finds, in
+-- ascending order, or the validated graph. It is pure.
+validate :: (Ord i) => [Migration i m] -> Either (NonEmpty (ValidationError i)) (MigrationGraph i m)
+validate migrations =
+  case NonEmpty.nonEmpty (Set.toAscList problems) of
+    Just errors -> Left errors
+    Nothing -> Right (buildGraph migrations knownDependencies order)
+  where
+    occurrences = Map.fromListWith (+) [(migrationId m, 1 :: Int) | m <- migrations]
+    isRegistered i = Map.member i occurrences
+    knownDependencies =
+      Map.fromListWith
+        Set.union
+        [(migrationId m, Set.filter isRegistered (migrationDependencies m)) | m <- migrations]
+    order = leastLinearExtension knownDependencies
+    unplaced = Map.keysSet knownDependencies `Set.difference` Set.fromList order
+    duplicates = [DuplicateIdentifier i | (i, n) <- Map.toList occurrences, n > 1]
+    unknowns =
+      [ UnknownDependency (migrationId m) d
+      | m <- migrations,
+        d <- Set.toList (migrationDependencies m),
+        not (isRegistered d)
+      ]
+    cycles =
+      [ cycleError knownDependencies component
+      | CyclicSCC members <- stronglyConnComp (unplacedEdges knownDependencies unplaced),
+        Just component <- [NonEmpty.nonEmpty members]
+      ]
+    problems = Set.fromList (duplicates <> unknowns <> cycles)
+
+-- | The edges among the nodes that Kahn's algorithm could not place, in the
+-- form that 'stronglyConnComp' takes.
+unplacedEdges :: (Ord i) => Map i (Set i) -> Set i -> [(i, i, [i])]
+unplacedEdges dependencies unplaced =
+  [ (n, n, Set.toList (Set.intersection unplaced ds))
+  | (n, ds) <- Map.toList (Map.restrictKeys dependencies unplaced)
+  ]
+
+-- | The error for one cyclic strongly connected component: a cycle through
+-- its least member. Every member of a cyclic component lies on a cycle, so
+-- the fallback to the whole component is unreachable.
+cycleError :: (Ord i) => Map i (Set i) -> NonEmpty i -> ValidationError i
+cycleError dependencies component =
+  DependencyCycle (fromMaybe sorted (cycleThrough dependencies (Set.fromList (NonEmpty.toList component)) start))
+  where
+    sorted = NonEmpty.sort component
+    start = NonEmpty.head sorted
+
+-- | A shortest cycle through @start@ that stays inside @component@. Each
+-- element of the result depends on the next, and the last depends on
+-- @start@, which comes first. 'Nothing' when no such cycle exists.
+cycleThrough :: (Ord i) => Map i (Set i) -> Set i -> i -> Maybe (NonEmpty i)
+cycleThrough dependencies component start =
+  fmap (\closer -> start :| pathFrom closer) (List.find closesCycle finalFrontier)
+  where
+    successors x = Set.intersection component (Map.findWithDefault Set.empty x dependencies)
+    closesCycle x = Set.member start (successors x)
+    (finalFrontier, parents) = until finished expand ([start], Map.singleton start start)
+    finished (frontier, _) = null frontier || any closesCycle frontier
+    expand (frontier, visited) =
+      let fresh =
+            -- 'Map.fromListWith' passes the new value first; keep the old one,
+            -- the parent that the search reached first.
+            Map.fromListWith
+              (\_ first -> first)
+              [ (y, x)
+              | x <- frontier,
+                y <- Set.toAscList (successors x),
+                not (Map.member y visited)
+              ]
+       in (Map.keys fresh, Map.union visited fresh)
+    -- The nodes from the child of start down to the given node.
+    pathFrom closer =
+      reverse
+        ( List.unfoldr
+            (\y -> if y == start then Nothing else fmap (\p -> (y, p)) (Map.lookup y parents))
+            closer
+        )
+
+-- | Kahn's algorithm with a min-priority queue. Returns the
+-- lexicographically least linear extension of the order generated by the
+-- map's dependency relation, restricted to the nodes that it can place. A
+-- node on a cycle, or above one, is never placed. Every dependency must
+-- be a key of the map.
+leastLinearExtension :: (Ord i) => Map i (Set i) -> [i]
+leastLinearExtension dependencies = List.unfoldr step (initialReady, initialCounts)
+  where
+    dependents =
+      Map.fromListWith
+        Set.union
+        [(d, Set.singleton n) | (n, ds) <- Map.toList dependencies, d <- Set.toList ds]
+    initialCounts = Map.map Set.size dependencies
+    initialReady = Map.keysSet (Map.filter (== 0) initialCounts)
+    step (ready, counts) = do
+      (next, rest) <- Set.minView ready
+      let released = Map.findWithDefault Set.empty next dependents
+          counts' = foldr (Map.adjust (subtract 1)) counts (Set.toList released)
+          newlyReady = Set.filter (\d -> Map.lookup d counts' == Just 0) released
+      pure (next, (Set.union rest newlyReady, counts'))
+
+-- | Builds the validated graph. The dependencies must be acyclic, and every
+-- dependency must be a key of the map.
+buildGraph :: (Ord i) => [Migration i m] -> Map i (Set i) -> [i] -> MigrationGraph i m
+buildGraph migrations dependencies order =
+  MigrationGraph
+    { graphMigrations = Map.fromList [(migrationId m, m) | m <- migrations],
+      graphOrder = order,
+      graphDependencies = graph,
+      -- 'nodeFromVertex' fails on a vertex outside the graph. The graph's
+      -- functions apply it only to vertices that 'Graph.reachable' returns
+      -- for the same graph.
+      graphVertexKey = \v -> let (_, key, _) = nodeFromVertex v in key,
+      graphKeyVertex = vertexFromKey
+    }
+  where
+    (graph, nodeFromVertex, vertexFromKey) =
+      Graph.graphFromEdges [((), n, Set.toList ds) | (n, ds) <- Map.toList dependencies]
+
+-- | The identifiers of every registered migration.
+registeredIdentifiers :: MigrationGraph i m -> Set i
+registeredIdentifiers = Map.keysSet . graphMigrations
+
+-- | The registered migration with this identifier.
+lookupMigration :: (Ord i) => i -> MigrationGraph i m -> Maybe (Migration i m)
+lookupMigration i = Map.lookup i . graphMigrations
+
+-- | Every registered identifier, in the lexicographically least linear
+-- extension of the dependency order.
+linearOrder :: MigrationGraph i m -> [i]
+linearOrder = graphOrder
+
+-- | The given identifiers that are registered, in the order of
+-- 'linearOrder'.
+inLinearOrder :: (Ord i) => MigrationGraph i m -> Set i -> [i]
+inLinearOrder graph ids = filter (`Set.member` ids) (graphOrder graph)
+
+-- | The identifier and everything that it depends on, directly or
+-- indirectly. Empty when the identifier is not registered.
+downSet :: (Ord i) => MigrationGraph i m -> i -> Set i
+downSet graph = reachableFrom graph (graphDependencies graph)
+
+-- | The identifier and everything that depends on it, directly or
+-- indirectly. Empty when the identifier is not registered.
+upSet :: (Ord i) => MigrationGraph i m -> i -> Set i
+upSet graph = reachableFrom graph (Graph.transposeG (graphDependencies graph))
+
+-- | The identifiers reachable from this one along the given edges,
+-- including itself. Empty when the identifier is not registered.
+reachableFrom :: (Ord i) => MigrationGraph i m -> Graph.Graph -> i -> Set i
+reachableFrom graph edges i =
+  maybe
+    Set.empty
+    (Set.fromList . map (graphVertexKey graph) . Graph.reachable edges)
+    (graphKeyVertex graph i)
diff --git a/src/Database/DagMigrations/Migration.hs b/src/Database/DagMigrations/Migration.hs
new file mode 100644
--- /dev/null
+++ b/src/Database/DagMigrations/Migration.hs
@@ -0,0 +1,81 @@
+-- | Migrations, the interpreter that runs them, identifier codecs, and
+-- fingerprints. A project imports "Database.DagMigrations", which re-exports
+-- everything that this module exports.
+module Database.DagMigrations.Migration
+  ( Migration (..),
+    hoistMigration,
+    Interpreter (..),
+    IdentifierCodec (..),
+    textIdentifiers,
+    Fingerprint (..),
+  )
+where
+
+import Data.Set (Set)
+import Data.Text (Text)
+
+-- | A value that the author of a migration sets, and changes when the
+-- migration changes after a run has applied it to some database. A run
+-- records it when it applies the migration, and later runs compare it.
+newtype Fingerprint = Fingerprint Text
+  deriving (Eq, Ord, Show)
+
+-- | A migration with identifier type @i@, whose actions run in the monad
+-- @m@ that the project chooses.
+data Migration i m = Migration
+  { -- | The identifier, unique in a registry.
+    migrationId :: i,
+    -- | The identifiers of the migrations that this one depends on directly.
+    migrationDependencies :: Set i,
+    -- | A description, which the run records in the tracking table when it
+    -- applies the migration.
+    migrationDescription :: Text,
+    -- | The fingerprint, if the author gives one.
+    migrationFingerprint :: Maybe Fingerprint,
+    -- | The action that applies the migration.
+    migrationUp :: m (),
+    -- | The action that reverts the migration, or 'Nothing' when the
+    -- migration cannot be reverted.
+    migrationDown :: Maybe (m ())
+  }
+
+-- | Moves a migration's actions into another monad, through a natural
+-- transformation. Every other field stays the same.
+hoistMigration :: (forall a. m a -> n a) -> Migration i m -> Migration i n
+hoistMigration nat migration =
+  migration
+    { migrationUp = nat (migrationUp migration),
+      migrationDown = fmap nat (migrationDown migration)
+    }
+
+-- | Runs an action of the project's monad @m@ inside an open transaction,
+-- and returns 'Left' when the action fails with an error of the project's
+-- type @e@.
+--
+-- * The adapter opens the transaction, and passes its value @tx@. The
+--   interpreter must neither commit nor roll back the transaction; the
+--   adapter does both.
+-- * The interpreter's side effects are those of the action, and the action
+--   performs them inside the transaction.
+-- * When the action throws an exception of the adapter's database library,
+--   the adapter rolls back and the run reports the adapter's error. When it
+--   throws any other exception, the adapter rolls back and releases its
+--   lock, and the exception propagates out of the run.
+newtype Interpreter tx m e = Interpreter
+  { runInterpreter :: forall a. tx -> m a -> IO (Either e a)
+  }
+
+-- | Converts identifiers to and from the text that the adapter stores in
+-- the tracking table. The codec must satisfy
+-- @decodeIdentifier (encodeIdentifier i) == Just i@ for every @i@. The
+-- planner orders identifiers by @Ord i@, not by their encoded text. A run
+-- accepts a row of the tracking table only when its text is the encoding of
+-- the identifier that it decodes to.
+data IdentifierCodec i = IdentifierCodec
+  { encodeIdentifier :: i -> Text,
+    decodeIdentifier :: Text -> Maybe i
+  }
+
+-- | The codec for identifiers that are already text.
+textIdentifiers :: IdentifierCodec Text
+textIdentifiers = IdentifierCodec {encodeIdentifier = id, decodeIdentifier = Just}
diff --git a/src/Database/DagMigrations/Plan.hs b/src/Database/DagMigrations/Plan.hs
new file mode 100644
--- /dev/null
+++ b/src/Database/DagMigrations/Plan.hs
@@ -0,0 +1,159 @@
+-- | Pure planning: which migrations a run applies or reverts, and in what
+-- order; which fingerprints it records or rejects; and the status of each
+-- migration. A project imports "Database.DagMigrations", which re-exports
+-- everything that this module exports.
+module Database.DagMigrations.Plan
+  ( Target (..),
+    PlanOptions (..),
+    defaultPlanOptions,
+    Step (..),
+    Plan (..),
+    planIdentifiers,
+    plan,
+    checkFingerprints,
+    status,
+  )
+where
+
+import Data.Either (partitionEithers)
+import Data.List.NonEmpty (NonEmpty)
+import Data.List.NonEmpty qualified as NonEmpty
+import Data.Map.Strict (Map)
+import Data.Map.Strict qualified as Map
+import Data.Set (Set)
+import Data.Set qualified as Set
+import Database.DagMigrations.Error (Direction (..), FingerprintMismatch (..), PlanError (..))
+import Database.DagMigrations.Graph
+  ( MigrationGraph,
+    downSet,
+    inLinearOrder,
+    linearOrder,
+    lookupMigration,
+    registeredIdentifiers,
+    upSet,
+  )
+import Database.DagMigrations.Migration (Fingerprint, Migration (..))
+
+-- | What a run moves the database towards.
+data Target i
+  = -- | Every registered migration under 'Up'; no migration under 'Down'.
+    AllMigrations
+  | -- | Under 'Up', this migration and everything that it depends on. Under
+    -- 'Down', the state in which nothing that depends on this migration is
+    -- applied; the migration itself stays applied.
+    TargetMigration i
+  deriving (Eq, Show)
+
+-- | The caller's choices about what 'plan' accepts.
+newtype PlanOptions = PlanOptions
+  { -- | Whether 'plan' accepts an applied identifier that no registered
+    -- migration has. When it does, 'plan' leaves such identifiers out.
+    -- Their dependencies are unknown, so 'plan' cannot check them: a 'Down'
+    -- plan may revert a migration that an unregistered applied migration
+    -- depends on, and 'Down' to 'AllMigrations' leaves every unregistered
+    -- applied identifier applied.
+    allowUnregisteredApplied :: Bool
+  }
+  deriving (Eq, Show)
+
+-- | The default options, under which 'plan' rejects unregistered applied
+-- identifiers.
+defaultPlanOptions :: PlanOptions
+defaultPlanOptions = PlanOptions {allowUnregisteredApplied = False}
+
+-- | One migration of a plan, and the action that the run performs for it.
+data Step i m = Step (Migration i m) (m ())
+
+-- | The steps of a run, in the order in which they run.
+data Plan i m = Plan Direction [Step i m]
+
+-- | The identifiers of a plan's steps, in order.
+planIdentifiers :: Plan i m -> [i]
+planIdentifiers (Plan _ steps) = [migrationId m | Step m _ <- steps]
+
+-- | Computes the plan that moves a database with the given applied set
+-- towards the target. It is pure. The steps of an 'Up' plan follow
+-- 'linearOrder'; the steps of a 'Down' plan follow its reverse.
+--
+-- It reports errors in two phases. First, in this order, every unregistered
+-- applied identifier (unless the options allow them), every inconsistency,
+-- and an unknown target. Only when it finds none of these, and only for
+-- 'Down', it reports every migration to revert that has no down action, in
+-- the order of reversion.
+plan ::
+  (Ord i) =>
+  PlanOptions ->
+  MigrationGraph i m ->
+  Set i ->
+  Direction ->
+  Target i ->
+  Either (NonEmpty (PlanError i)) (Plan i m)
+plan options graph applied direction target = do
+  failWith (unregisteredErrors <> inconsistencyErrors <> targetErrors)
+  case direction of
+    Up -> pure (Plan Up [Step m (migrationUp m) | m <- migrationsOf (inLinearOrder graph toApply)])
+    Down -> do
+      let (irreversible, steps) =
+            partitionEithers (map revertStep (migrationsOf (reverse (inLinearOrder graph toRevert))))
+      failWith irreversible
+      pure (Plan Down steps)
+  where
+    registered = registeredIdentifiers graph
+    registeredApplied = Set.intersection applied registered
+    unregisteredErrors
+      | allowUnregisteredApplied options = []
+      | otherwise = map UnregisteredApplied (Set.toAscList (Set.difference applied registered))
+    inconsistencyErrors =
+      [ InconsistentApplied i d
+      | i <- Set.toAscList registeredApplied,
+        Just m <- [lookupMigration i graph],
+        d <- Set.toAscList (migrationDependencies m),
+        not (Set.member d applied)
+      ]
+    targetErrors = case target of
+      TargetMigration t | not (Set.member t registered) -> [UnknownTarget t]
+      _ -> []
+    toApply = case target of
+      AllMigrations -> Set.difference registered applied
+      TargetMigration t -> Set.difference (downSet graph t) applied
+    toRevert = case target of
+      AllMigrations -> registeredApplied
+      TargetMigration t -> Set.intersection registeredApplied (Set.delete t (upSet graph t))
+    migrationsOf ids = [m | i <- ids, Just m <- [lookupMigration i graph]]
+    revertStep m = maybe (Left (Irreversible (migrationId m))) (Right . Step m) (migrationDown m)
+
+-- | Succeeds on an empty list, and fails with the errors otherwise.
+failWith :: [e] -> Either (NonEmpty e) ()
+failWith = maybe (Right ()) Left . NonEmpty.nonEmpty
+
+-- | Compares the recorded fingerprints of applied migrations with the
+-- registered ones. Returns the fingerprints to record under trust on first
+-- use (recorded none, registered one), and every mismatch (recorded one,
+-- registered a different one or none). Unregistered identifiers are left
+-- out.
+checkFingerprints ::
+  (Ord i) =>
+  MigrationGraph i m ->
+  Map i (Maybe Fingerprint) ->
+  (Map i Fingerprint, [FingerprintMismatch i])
+checkFingerprints graph recorded = (toRecord, mismatches)
+  where
+    pairs =
+      [ (i, stored, migrationFingerprint m)
+      | (i, stored) <- Map.toAscList recorded,
+        Just m <- [lookupMigration i graph]
+      ]
+    toRecord = Map.fromList [(i, f) | (i, Nothing, Just f) <- pairs]
+    mismatches =
+      [ FingerprintMismatch i (Just stored) registeredFingerprint
+      | (i, Just stored, registeredFingerprint) <- pairs,
+        registeredFingerprint /= Just stored
+      ]
+
+-- | Every registered identifier in the order of 'linearOrder', with whether
+-- it is applied, and the applied identifiers that are not registered.
+status :: (Ord i) => MigrationGraph i m -> Set i -> ([(i, Bool)], Set i)
+status graph applied =
+  ( [(i, Set.member i applied) | i <- linearOrder graph],
+    Set.difference applied (registeredIdentifiers graph)
+  )
diff --git a/src/Database/DagMigrations/Progress.hs b/src/Database/DagMigrations/Progress.hs
new file mode 100644
--- /dev/null
+++ b/src/Database/DagMigrations/Progress.hs
@@ -0,0 +1,47 @@
+-- | The capability through which a run reports its progress. A project
+-- imports "Database.DagMigrations", which re-exports everything that this
+-- module exports.
+module Database.DagMigrations.Progress
+  ( Progress (..),
+    ProgressEvent (..),
+    TrackingVersion (..),
+    silentProgress,
+  )
+where
+
+import Database.DagMigrations.Error (Direction, FingerprintMismatch)
+
+-- | The version of the tracking table's schema. Version 0 is the table of
+-- @dbmigrations@.
+newtype TrackingVersion = TrackingVersion Int
+  deriving (Eq, Ord, Show)
+
+-- | An event of a run.
+data ProgressEvent i
+  = -- | The run created the tracking table, at this version.
+    TrackingTableCreated TrackingVersion
+  | -- | The run upgraded the tracking table from the first version to the
+    -- second.
+    TrackingTableUpgraded TrackingVersion TrackingVersion
+  | -- | The run recorded the fingerprint of this applied migration, which
+    -- had none (trust on first use).
+    FingerprintRecorded i
+  | -- | The run found this mismatch, and continued under the warning
+    -- policy.
+    FingerprintMismatchIgnored (FingerprintMismatch i)
+  | -- | The run is about to apply or revert this migration, in its own
+    -- transaction.
+    MigrationStarted Direction i
+  | -- | The run committed the migration's transaction.
+    MigrationFinished Direction i
+  deriving (Eq, Show)
+
+-- | Receives each event of a run. The runner reports events only through
+-- this capability; the library prints and logs nothing itself.
+newtype Progress i = Progress
+  { reportProgress :: ProgressEvent i -> IO ()
+  }
+
+-- | Ignores every event.
+silentProgress :: Progress i
+silentProgress = Progress (const (pure ()))
diff --git a/src/Database/DagMigrations/Run.hs b/src/Database/DagMigrations/Run.hs
new file mode 100644
--- /dev/null
+++ b/src/Database/DagMigrations/Run.hs
@@ -0,0 +1,260 @@
+-- | Running migrations against a database through an adapter. A project
+-- imports "Database.DagMigrations", which re-exports everything that this
+-- module exports.
+module Database.DagMigrations.Run
+  ( Migrator (..),
+    RunSettings (..),
+    defaultRunSettings,
+    FingerprintPolicy (..),
+    migrate,
+    Inspection (..),
+    appliedSet,
+    inspect,
+    acceptFingerprints,
+  )
+where
+
+import Control.Monad (unless)
+import Control.Monad.IO.Class (liftIO)
+import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT, throwE, withExceptT)
+import Data.Bifunctor (first)
+import Data.Foldable (for_, traverse_)
+import Data.List.NonEmpty qualified as NonEmpty
+import Data.Map.Strict (Map)
+import Data.Map.Strict qualified as Map
+import Data.Maybe (isNothing)
+import Data.Set (Set)
+import Data.Set qualified as Set
+import Data.Traversable (for)
+import Database.DagMigrations.Adapter (Adapter (..), AppliedRow (..), BootstrapOutcome (..))
+import Database.DagMigrations.Error
+  ( AcceptError (..),
+    Direction (..),
+    FingerprintMismatch,
+    RunError (..),
+  )
+import Database.DagMigrations.Graph (MigrationGraph, lookupMigration)
+import Database.DagMigrations.Migration
+  ( Fingerprint,
+    IdentifierCodec (..),
+    Interpreter (..),
+    Migration (..),
+  )
+import Database.DagMigrations.Plan
+  ( Plan (..),
+    PlanOptions,
+    Step (..),
+    Target,
+    checkFingerprints,
+    defaultPlanOptions,
+    plan,
+    status,
+  )
+import Database.DagMigrations.Progress (Progress (..), ProgressEvent (..))
+
+-- | What a run does when a recorded fingerprint differs from a registered
+-- one.
+data FingerprintPolicy
+  = -- | The run fails, and changes nothing.
+    MismatchIsError
+  | -- | The run reports each mismatch through t'Progress', and continues.
+    MismatchIsWarning
+  deriving (Eq, Show)
+
+-- | The choices of a run.
+data RunSettings = RunSettings
+  { runPlanOptions :: PlanOptions,
+    runFingerprintPolicy :: FingerprintPolicy
+  }
+  deriving (Eq, Show)
+
+-- | The default settings, under which a run rejects unregistered applied
+-- identifiers and fingerprint mismatches.
+defaultRunSettings :: RunSettings
+defaultRunSettings =
+  RunSettings {runPlanOptions = defaultPlanOptions, runFingerprintPolicy = MismatchIsError}
+
+-- | Everything that a run needs. A project builds one, and passes it to
+-- 'migrate', 'inspect', or 'acceptFingerprints'.
+data Migrator i m tx e ae = Migrator
+  { migratorAdapter :: Adapter tx ae,
+    migratorCodec :: IdentifierCodec i,
+    migratorInterpreter :: Interpreter tx m e,
+    migratorProgress :: Progress i,
+    migratorSettings :: RunSettings,
+    migratorGraph :: MigrationGraph i m
+  }
+
+-- | Moves the database towards the target. While it holds the adapter's
+-- run lock, it reads the applied migrations, checks fingerprints and plans
+-- (writing nothing if either fails), bootstraps the tracking table, records
+-- fingerprints on first use, and runs each step in its own transaction.
+-- The first failed step ends the run; the steps before it stay committed.
+-- Under 'MismatchIsWarning', it reports each mismatch after it bootstraps
+-- the table. An exception that a migration throws, other than one of the
+-- adapter's database library, propagates after the adapter rolls back the
+-- step's transaction and releases the lock. An asynchronous exception,
+-- such as the one that 'System.Timeout.timeout' throws, propagates too, but
+-- may leave the session with a statement running or a transaction open;
+-- the caller then closes the session.
+migrate :: (Ord i) => Migrator i m tx e ae -> Direction -> Target i -> IO (Either (RunError i e ae) ())
+migrate migrator direction target =
+  underRunLock migrator $ do
+    recorded <- readDecoded migrator
+    let (toRecord, mismatches) = checkFingerprints graph recorded
+    case (runFingerprintPolicy settings, NonEmpty.nonEmpty mismatches) of
+      (MismatchIsError, Just found) -> throwE (FingerprintsMismatched found)
+      _ -> pure ()
+    Plan _ steps <-
+      except (first PlanFailed (plan (runPlanOptions settings) graph (Map.keysSet recorded) direction target))
+    bootstrapAndReport migrator
+    liftIO (traverse_ (report . FingerprintMismatchIgnored) mismatches)
+    unless (Map.null toRecord) $ do
+      writeFingerprints migrator (Map.map Just toRecord)
+      liftIO (traverse_ (report . FingerprintRecorded) (Map.keys toRecord))
+    for_ steps (runStep migrator direction)
+  where
+    graph = migratorGraph migrator
+    settings = migratorSettings migrator
+    report = reportProgress (migratorProgress migrator)
+
+-- | What 'inspect' found.
+data Inspection i = Inspection
+  { -- | Every registered migration in the order of the linear extension,
+    -- with whether it is applied.
+    inspectedStatus :: [(i, Bool)],
+    -- | Applied identifiers that no registered migration has.
+    inspectedUnregistered :: Set i,
+    -- | Applied migrations whose recorded fingerprint differs from the
+    -- registered one.
+    inspectedMismatches :: [FingerprintMismatch i],
+    -- | The fingerprints that a run would record on first use.
+    inspectedToRecord :: Map i Fingerprint
+  }
+  deriving (Eq, Show)
+
+-- | The applied set that 'inspect' found: the applied registered
+-- migrations and the unregistered applied identifiers.
+appliedSet :: (Ord i) => Inspection i -> Set i
+appliedSet inspection =
+  Set.union
+    (inspectedUnregistered inspection)
+    (Set.fromList [i | (i, True) <- inspectedStatus inspection])
+
+-- | Reads the database's state without the run lock, and writes nothing.
+-- Without the lock, its result may reflect a run in progress.
+inspect :: (Ord i) => Migrator i m tx e ae -> IO (Either (RunError i e ae) (Inspection i))
+inspect migrator = runExceptT $ do
+  recorded <- readDecoded migrator
+  let graph = migratorGraph migrator
+      (toRecord, mismatches) = checkFingerprints graph recorded
+      (statuses, unregistered) = status graph (Map.keysSet recorded)
+  pure (Inspection statuses unregistered mismatches toRecord)
+
+-- | Records the registered fingerprint of each named migration, which must
+-- be registered and applied. While it holds the run lock, it reads the
+-- applied migrations, checks every name (writing nothing if any fails),
+-- bootstraps the tracking table, and records the fingerprints in one
+-- transaction. When the registered fingerprint is 'Nothing', it records
+-- null. Given an empty set, it returns 'Right' at once: it takes no lock,
+-- and reads and writes nothing.
+acceptFingerprints :: (Ord i) => Migrator i m tx e ae -> Set i -> IO (Either (RunError i e ae) ())
+acceptFingerprints migrator names
+  | Set.null names = pure (Right ())
+  | otherwise = underRunLock migrator $ do
+      recorded <- readDecoded migrator
+      let problems =
+            [ problem
+            | name <- Set.toAscList names,
+              Just problem <- [acceptProblem recorded name]
+            ]
+      traverse_ (throwE . CannotAccept) (NonEmpty.nonEmpty problems)
+      bootstrapAndReport migrator
+      writeFingerprints
+        migrator
+        ( Map.fromList
+            [ (name, migrationFingerprint m)
+            | name <- Set.toList names,
+              Just m <- [lookupMigration name graph]
+            ]
+        )
+  where
+    graph = migratorGraph migrator
+    acceptProblem recorded name
+      | isNothing (lookupMigration name graph) = Just (NotRegistered name)
+      | not (Map.member name recorded) = Just (NotApplied name)
+      | otherwise = Nothing
+
+-- Steps shared by the operations above.
+
+-- | Runs the action under the adapter's run lock, and reports a failure of
+-- the lock as 'AdapterFailed'.
+underRunLock ::
+  Migrator i m tx e ae ->
+  ExceptT (RunError i e ae) IO () ->
+  IO (Either (RunError i e ae) ())
+underRunLock migrator action =
+  either (Left . AdapterFailed) id <$> withRunLock (migratorAdapter migrator) (runExceptT action)
+
+-- | Reads the applied rows through the adapter, and decodes their
+-- identifiers with the codec. Returns each decoded identifier with its
+-- recorded fingerprint. Fails with 'UndecodableIdentifier' on the first row
+-- whose text the codec does not decode, and with 'NonCanonicalIdentifier'
+-- on the first row whose text the codec decodes to an identifier whose
+-- encoding is different text: the run later writes rows by the encoding,
+-- so the two must match. Writes nothing.
+readDecoded :: (Ord i) => Migrator i m tx e ae -> ExceptT (RunError i e ae) IO (Map i (Maybe Fingerprint))
+readDecoded migrator = do
+  rows <- withExceptT AdapterFailed (ExceptT (readApplied (migratorAdapter migrator)))
+  decoded <- for (Map.toList rows) $ \(raw, fingerprint) ->
+    case decodeIdentifier codec raw of
+      Nothing -> throwE (UndecodableIdentifier raw)
+      Just i
+        | encodeIdentifier codec i /= raw -> throwE (NonCanonicalIdentifier raw i)
+        | otherwise -> pure (i, fingerprint)
+  pure (Map.fromList decoded)
+  where
+    codec = migratorCodec migrator
+
+-- | Bootstraps the tracking table, and reports a creation or an upgrade.
+bootstrapAndReport :: Migrator i m tx e ae -> ExceptT (RunError i e ae) IO ()
+bootstrapAndReport migrator = do
+  outcome <- withExceptT AdapterFailed (ExceptT (bootstrap (migratorAdapter migrator)))
+  liftIO $ case outcome of
+    AlreadyCurrent -> pure ()
+    Created version -> report (TrackingTableCreated version)
+    Upgraded from to -> report (TrackingTableUpgraded from to)
+  where
+    report = reportProgress (migratorProgress migrator)
+
+-- | Records the given fingerprints in one transaction.
+writeFingerprints :: Migrator i m tx e ae -> Map i (Maybe Fingerprint) -> ExceptT (RunError i e ae) IO ()
+writeFingerprints migrator fingerprints =
+  withExceptT (AdapterFailed . either id id) . ExceptT $
+    withTransaction adapter (\tx -> recordFingerprints adapter tx encoded)
+  where
+    adapter = migratorAdapter migrator
+    encoded = Map.mapKeys (encodeIdentifier (migratorCodec migrator)) fingerprints
+
+-- | Runs one step and its bookkeeping in one transaction, and reports its
+-- start and its end.
+runStep :: Migrator i m tx e ae -> Direction -> Step i m -> ExceptT (RunError i e ae) IO ()
+runStep migrator direction (Step migration action) = do
+  liftIO (report (MigrationStarted direction identifier))
+  result <- liftIO . withTransaction adapter $ \tx -> do
+    outcome <- runInterpreter (migratorInterpreter migrator) tx action
+    case outcome of
+      Left err -> pure (Left (Right err))
+      Right () -> first Left <$> bookkeeping tx
+  case result of
+    Left (Left adapterError) -> throwE (MigrationFailed identifier direction (Left adapterError))
+    Left (Right failure) -> throwE (MigrationFailed identifier direction failure)
+    Right () -> liftIO (report (MigrationFinished direction identifier))
+  where
+    adapter = migratorAdapter migrator
+    report = reportProgress (migratorProgress migrator)
+    identifier = migrationId migration
+    encoded = encodeIdentifier (migratorCodec migrator) identifier
+    bookkeeping tx = case direction of
+      Up -> recordApplied adapter tx (AppliedRow encoded (migrationDescription migration) (migrationFingerprint migration))
+      Down -> removeApplied adapter tx encoded
diff --git a/test/Database/DagMigrations/FakeAdapter.hs b/test/Database/DagMigrations/FakeAdapter.hs
new file mode 100644
--- /dev/null
+++ b/test/Database/DagMigrations/FakeAdapter.hs
@@ -0,0 +1,164 @@
+-- | An adapter that keeps its database in an 'IORef', for testing the
+-- runner without a database server.
+module Database.DagMigrations.FakeAdapter
+  ( FakeDatabase (..),
+    emptyDatabase,
+    FakeTx,
+    FakeError (..),
+    FakeFaults (..),
+    noFaults,
+    fakeAdapter,
+    fakeAdapterWith,
+    FakeM,
+    fakeInterpreter,
+    createTable,
+    dropTable,
+    failWith,
+    tableMigration,
+  )
+where
+
+import Control.Exception (Exception, try)
+import Control.Monad.IO.Class (liftIO)
+import Control.Monad.Trans.Class (lift)
+import Control.Monad.Trans.Except (ExceptT, runExceptT, throwE)
+import Control.Monad.Trans.Reader (ReaderT, ask, runReaderT)
+import Data.IORef (IORef, atomicModifyIORef', modifyIORef', newIORef, readIORef, writeIORef)
+import Data.Map.Strict (Map)
+import Data.Map.Strict qualified as Map
+import Data.Set (Set)
+import Data.Set qualified as Set
+import Data.Text (Text)
+import Database.DagMigrations.Adapter (Adapter (..), AppliedRow (..), BootstrapOutcome (..))
+import Database.DagMigrations.Migration (Fingerprint, Interpreter (..), Migration (..))
+import Database.DagMigrations.Progress (TrackingVersion (..))
+
+-- | The state of a fake database.
+data FakeDatabase = FakeDatabase
+  { -- | The tracking table, or 'Nothing' when it does not exist.
+    fakeTrackingTable :: Maybe (Map Text (Maybe Fingerprint)),
+    -- | The tables that test migrations created.
+    fakeTables :: Set Text
+  }
+  deriving (Eq, Show)
+
+emptyDatabase :: FakeDatabase
+emptyDatabase = FakeDatabase {fakeTrackingTable = Nothing, fakeTables = Set.empty}
+
+-- | A transaction: a working copy of the database, which the adapter
+-- writes back on commit.
+newtype FakeTx = FakeTx (IORef FakeDatabase)
+
+-- | The error of the fake database. Test migrations throw it to stand for a
+-- failure of a database library, such as rejected SQL.
+newtype FakeError = FakeError Text
+  deriving (Eq, Show)
+
+instance Exception FakeError
+
+-- | Failures and outcomes that a test switches on.
+data FakeFaults = FakeFaults
+  { -- | 'withRunLock' fails with this error, and runs nothing.
+    faultLock :: Maybe FakeError,
+    -- | 'recordApplied' fails with this error.
+    faultRecordApplied :: Maybe FakeError,
+    -- | 'bootstrap' reports an upgrade from this version, when the table
+    -- exists.
+    faultUpgradeFrom :: Maybe TrackingVersion
+  }
+
+-- | No faults: every operation succeeds.
+noFaults :: FakeFaults
+noFaults = FakeFaults {faultLock = Nothing, faultRecordApplied = Nothing, faultUpgradeFrom = Nothing}
+
+-- | An adapter over the given database, with no faults. Its lock does
+-- nothing.
+fakeAdapter :: IORef FakeDatabase -> Adapter FakeTx FakeError
+fakeAdapter = fakeAdapterWith noFaults
+
+-- | An adapter over the given database, with the given faults. Like a real
+-- adapter, its 'withTransaction' turns a 'FakeError' that the action throws
+-- into the adapter's error, after it discards the transaction's changes.
+fakeAdapterWith :: FakeFaults -> IORef FakeDatabase -> Adapter FakeTx FakeError
+fakeAdapterWith faults database =
+  Adapter
+    { withRunLock = \action -> maybe (Right <$> action) (pure . Left) (faultLock faults),
+      readApplied = Right . maybe Map.empty id . fakeTrackingTable <$> readIORef database,
+      bootstrap =
+        atomicModifyIORef' database $ \db -> case fakeTrackingTable db of
+          Nothing -> (db {fakeTrackingTable = Just Map.empty}, Right (Created (TrackingVersion 1)))
+          Just _ -> (db, Right (maybe AlreadyCurrent (\from -> Upgraded from (TrackingVersion 1)) (faultUpgradeFrom faults))),
+      withTransaction = \action -> do
+        working <- newIORef =<< readIORef database
+        result <- try (action (FakeTx working))
+        case result of
+          Left err -> pure (Left (Left err))
+          Right (Left err) -> pure (Left (Right err))
+          Right (Right a) -> do
+            writeIORef database =<< readIORef working
+            pure (Right a),
+      recordApplied = \(FakeTx working) row -> case faultRecordApplied faults of
+        Just err -> pure (Left err)
+        Nothing ->
+          -- Like an SQL INSERT into a table keyed by identifier, this fails
+          -- when the row exists.
+          modifyTrackingTable working $ \table ->
+            if Map.member (appliedIdentifier row) table
+              then Left (FakeError ("row exists: " <> appliedIdentifier row))
+              else Right (Map.insert (appliedIdentifier row) (appliedFingerprint row) table),
+      removeApplied = \(FakeTx working) identifier ->
+        modifyTrackingTable working $ \table ->
+          if Map.member identifier table
+            then Right (Map.delete identifier table)
+            else Left (FakeError ("no row: " <> identifier)),
+      recordFingerprints = \(FakeTx working) fingerprints ->
+        -- Like an SQL UPDATE, this changes only rows that exist.
+        modifyTrackingTable working (\table -> Right (Map.union (Map.intersection fingerprints table) table))
+    }
+
+-- | Applies the change to the tracking table of the transaction's working
+-- copy. Fails, and writes nothing, when the table does not exist or the
+-- change fails.
+modifyTrackingTable ::
+  IORef FakeDatabase ->
+  (Map Text (Maybe Fingerprint) -> Either FakeError (Map Text (Maybe Fingerprint))) ->
+  IO (Either FakeError ())
+modifyTrackingTable working change = do
+  db <- readIORef working
+  case change =<< maybe (Left (FakeError "no tracking table")) Right (fakeTrackingTable db) of
+    Left err -> pure (Left err)
+    Right table -> Right <$> writeIORef working db {fakeTrackingTable = Just table}
+
+-- | The monad of test migrations: they read the transaction, and fail
+-- with text.
+type FakeM = ReaderT FakeTx (ExceptT Text IO)
+
+fakeInterpreter :: Interpreter FakeTx FakeM Text
+fakeInterpreter = Interpreter (\tx action -> runExceptT (runReaderT action tx))
+
+createTable :: Text -> FakeM ()
+createTable name = changeTables (Set.insert name)
+
+dropTable :: Text -> FakeM ()
+dropTable name = changeTables (Set.delete name)
+
+failWith :: Text -> FakeM a
+failWith = lift . throwE
+
+changeTables :: (Set Text -> Set Text) -> FakeM ()
+changeTables change = do
+  FakeTx working <- ask
+  liftIO (modifyIORef' working (\db -> db {fakeTables = change (fakeTables db)}))
+
+-- | A migration that creates the table with its own name, and drops it
+-- when reverted.
+tableMigration :: Text -> [Text] -> Migration Text FakeM
+tableMigration name dependencies =
+  Migration
+    { migrationId = name,
+      migrationDependencies = Set.fromList dependencies,
+      migrationDescription = "create " <> name,
+      migrationFingerprint = Nothing,
+      migrationUp = createTable name,
+      migrationDown = Just (dropTable name)
+    }
diff --git a/test/Database/DagMigrations/Gen.hs b/test/Database/DagMigrations/Gen.hs
new file mode 100644
--- /dev/null
+++ b/test/Database/DagMigrations/Gen.hs
@@ -0,0 +1,84 @@
+-- | Generators of registries, applied sets, and targets for property tests.
+module Database.DagMigrations.Gen
+  ( TestMigration,
+    testMigration,
+    RegistrySpec,
+    toRegistry,
+    genRegistry,
+    genDownSet,
+    validated,
+    isDownSet,
+    dependencyMap,
+  )
+where
+
+import Data.Functor.Identity (Identity (..))
+import Data.Map.Strict (Map)
+import Data.Map.Strict qualified as Map
+import Data.Set (Set)
+import Data.Set qualified as Set
+import Data.Text (Text)
+import Data.Text qualified as Text
+import Database.DagMigrations.Graph (MigrationGraph, downSet, linearOrder, lookupMigration, validate)
+import Database.DagMigrations.Migration (Migration (..))
+import Hedgehog (Gen, MonadTest, annotateShow, failure)
+import Hedgehog.Gen qualified as Gen
+import Hedgehog.Range qualified as Range
+
+-- | A migration whose actions do nothing.
+type TestMigration = Migration Text Identity
+
+-- | A reversible migration with the given name and dependencies.
+testMigration :: Text -> [Text] -> TestMigration
+testMigration name dependencies =
+  Migration
+    { migrationId = name,
+      migrationDependencies = Set.fromList dependencies,
+      migrationDescription = "",
+      migrationFingerprint = Nothing,
+      migrationUp = Identity (),
+      migrationDown = Just (Identity ())
+    }
+
+-- | The name and the dependencies of each migration of a registry.
+-- Migrations hold actions and cannot be shown, so generators produce
+-- this, and 'toRegistry' builds the migrations.
+type RegistrySpec = [(Text, [Text])]
+
+-- | The migrations named in the spec, with their dependencies.
+toRegistry :: RegistrySpec -> [TestMigration]
+toRegistry = map (uncurry testMigration)
+
+-- | An acyclic registry of up to 12 migrations. The k-th migration depends
+-- on a random subset of the ones before it. The names are a random
+-- permutation of @m10@, @m11@, ..., so the order of the names differs from
+-- the order of construction.
+genRegistry :: Gen RegistrySpec
+genRegistry = do
+  size <- Gen.int (Range.linear 0 12)
+  names <- Gen.shuffle [Text.pack ('m' : show k) | k <- [10 .. 9 + size]]
+  dependencies <- traverse (\k -> Gen.subsequence (take k names)) [0 .. size - 1]
+  pure (zip names dependencies)
+
+-- | A down-set of the graph: the union of the down-sets of a random subset.
+genDownSet :: MigrationGraph Text m -> Gen (Set Text)
+genDownSet graph = do
+  chosen <- Gen.subsequence (linearOrder graph)
+  pure (Set.unions (map (downSet graph) chosen))
+
+-- | The validated graph, or a test failure that shows the errors.
+validated :: (MonadTest t, Ord i, Show i) => [Migration i m] -> t (MigrationGraph i m)
+validated migrations = either (\errors -> annotateShow errors >> failure) pure (validate migrations)
+
+-- | Whether every dependency of every member of the set is in the set.
+isDownSet :: (Ord i) => MigrationGraph i m -> Set i -> Bool
+isDownSet graph ids =
+  and
+    [ migrationDependencies m `Set.isSubsetOf` ids
+    | i <- Set.toList ids,
+      Just m <- [lookupMigration i graph]
+    ]
+
+-- | The direct dependencies of each migration of the spec.
+dependencyMap :: RegistrySpec -> Map Text (Set Text)
+dependencyMap specs = Map.fromList [(name, Set.fromList dependencies) | (name, dependencies) <- specs]
diff --git a/test/Database/DagMigrations/GraphSpec.hs b/test/Database/DagMigrations/GraphSpec.hs
new file mode 100644
--- /dev/null
+++ b/test/Database/DagMigrations/GraphSpec.hs
@@ -0,0 +1,143 @@
+module Database.DagMigrations.GraphSpec (spec) where
+
+import Data.Either (isRight)
+import Data.List qualified as List
+import Data.List.NonEmpty (NonEmpty (..))
+import Data.List.NonEmpty qualified as NonEmpty
+import Data.Map.Strict qualified as Map
+import Data.Maybe (listToMaybe)
+import Data.Set qualified as Set
+import Data.Text (Text)
+import Database.DagMigrations.Error (ValidationError (..))
+import Database.DagMigrations.Gen
+import Database.DagMigrations.Graph
+import Hedgehog.Gen qualified as Gen
+import Test.Hspec
+import Test.Hspec.Hedgehog (assert, forAll, hedgehog, (===))
+
+spec :: Spec
+spec = do
+  describe "validate" $ do
+    it "accepts an empty registry" $
+      fmap linearOrder (validate ([] :: [TestMigration])) `shouldBe` Right []
+
+    it "reports a duplicate identifier" $
+      errorsOf [testMigration "a" [], testMigration "a" []]
+        `shouldBe` Just (DuplicateIdentifier "a" :| [])
+
+    it "reports an unknown dependency" $
+      errorsOf [testMigration "a" ["missing"]]
+        `shouldBe` Just (UnknownDependency "a" "missing" :| [])
+
+    it "reports a migration that depends on itself as a cycle of length 1" $
+      errorsOf [testMigration "a" ["a"]]
+        `shouldBe` Just (DependencyCycle ("a" :| []) :| [])
+
+    it "reports a cycle starting from its least member, in dependency order" $
+      errorsOf [testMigration "a" ["b"], testMigration "b" ["c"], testMigration "c" ["a"]]
+        `shouldBe` Just (DependencyCycle ("a" :| ["b", "c"]) :| [])
+
+    it "reports each of several disjoint cycles" $
+      errorsOf [testMigration "a" ["b"], testMigration "b" ["a"], testMigration "c" ["d"], testMigration "d" ["c"]]
+        `shouldBe` Just (DependencyCycle ("a" :| ["b"]) :| [DependencyCycle ("c" :| ["d"])])
+
+    it "reports a shortest cycle through the least member" $
+      errorsOf [testMigration "a" ["b", "c"], testMigration "b" ["d"], testMigration "d" ["a"], testMigration "c" ["a"]]
+        `shouldBe` Just (DependencyCycle ("a" :| ["c"]) :| [])
+
+    it "reports a cycle that only one of two duplicate registrations closes" $
+      errorsOf [testMigration "a" ["b"], testMigration "a" [], testMigration "b" ["a"]]
+        `shouldBe` Just (DuplicateIdentifier "a" :| [DependencyCycle ("a" :| ["b"])])
+
+    it "does not report a migration that only depends on a cycle" $
+      errorsOf [testMigration "a" ["b"], testMigration "b" ["a"], testMigration "c" ["a"]]
+        `shouldBe` Just (DependencyCycle ("a" :| ["b"]) :| [])
+
+    it "reports every problem at once, in ascending order" $
+      errorsOf
+        [ testMigration "a" ["x"],
+          testMigration "a" [],
+          testMigration "b" ["c"],
+          testMigration "c" ["b"]
+        ]
+        `shouldBe` Just
+          ( DuplicateIdentifier "a"
+              :| [UnknownDependency "a" "x", DependencyCycle ("b" :| ["c"])]
+          )
+
+    it "accepts every generated acyclic registry" $ hedgehog $ do
+      specs <- forAll genRegistry
+      assert (isRight (validate (toRegistry specs)))
+
+    it "reports only real cycles after an edge closes one" $ hedgehog $ do
+      specs <- forAll genRegistry
+      graph <- validated (toRegistry specs)
+      case linearOrder graph of
+        [] -> pure ()
+        ids -> do
+          from <- forAll (Gen.element ids)
+          -- Every member of upSet depends on 'from', so a dependency of
+          -- 'from' on any of them closes a cycle.
+          to <- forAll (Gen.element (Set.toList (upSet graph from)))
+          let mutated =
+                [ (name, if name == from then to : dependencies else dependencies)
+                | (name, dependencies) <- specs
+                ]
+              edges = dependencyMap mutated
+              isEdge (a, b) = maybe False (Set.member b) (Map.lookup a edges)
+              cyclesOf errors = [c | DependencyCycle c <- NonEmpty.toList errors]
+          case validate (toRegistry mutated) of
+            Right _ -> fail "expected a cycle"
+            Left errors -> do
+              assert (not (null (cyclesOf errors)))
+              let consecutive (c :| rest) = zip (c : rest) (rest <> [c])
+              assert (all (all isEdge . consecutive) (cyclesOf errors))
+              -- Each cycle is simple, and starts with its least member.
+              assert (all (\c -> length c == Set.size (Set.fromList (NonEmpty.toList c))) (cyclesOf errors))
+              assert (all (\c -> NonEmpty.head c == minimum c) (cyclesOf errors))
+
+  describe "linearOrder" $ do
+    it "is the lexicographically least linear extension" $
+      fmap linearOrder (validate [testMigration "1" ["3"], testMigration "2" [], testMigration "3" []])
+        `shouldBe` Right ["2", "3", "1"]
+
+    it "places, at each position, the least migration whose dependencies are all placed" $ hedgehog $ do
+      specs <- forAll genRegistry
+      graph <- validated (toRegistry specs)
+      let edges = dependencyMap specs
+          order = linearOrder graph
+          available placed =
+            [ name
+            | (name, dependencies) <- Map.toAscList edges,
+              not (Set.member name placed),
+              dependencies `Set.isSubsetOf` placed
+            ]
+          expected = List.unfoldr (\placed -> fmap (\next -> (next, Set.insert next placed)) (listToMaybe (available placed))) Set.empty
+      order === expected
+
+    it "does not depend on the order of registration" $ hedgehog $ do
+      specs <- forAll genRegistry
+      shuffled <- forAll (Gen.shuffle specs)
+      graph <- validated (toRegistry specs)
+      graph' <- validated (toRegistry shuffled)
+      linearOrder graph === linearOrder graph'
+
+    it "keeps the old order when a maximal migration is added" $ hedgehog $ do
+      specs <- forAll genRegistry
+      graph <- validated (toRegistry specs)
+      dependencies <- forAll (Gen.subsequence (linearOrder graph))
+      -- "m00" sorts before every generated name.
+      graph' <- validated (toRegistry (("m00", dependencies) : specs))
+      filter (/= "m00") (linearOrder graph') === linearOrder graph
+
+  describe "downSet and upSet" $ do
+    it "contain the identifier and its transitive dependencies or dependents" $
+      case validate [testMigration "a" [], testMigration "b" ["a"], testMigration "c" ["b"]] of
+        Left errors -> expectationFailure (show errors)
+        Right graph -> do
+          downSet graph "b" `shouldBe` Set.fromList ["a", "b"]
+          upSet graph "b" `shouldBe` Set.fromList ["b", "c"]
+          downSet graph "missing" `shouldBe` Set.empty
+  where
+    errorsOf :: [TestMigration] -> Maybe (NonEmpty (ValidationError Text))
+    errorsOf = either Just (const Nothing) . validate
diff --git a/test/Database/DagMigrations/PlanSpec.hs b/test/Database/DagMigrations/PlanSpec.hs
new file mode 100644
--- /dev/null
+++ b/test/Database/DagMigrations/PlanSpec.hs
@@ -0,0 +1,255 @@
+module Database.DagMigrations.PlanSpec (spec) where
+
+import Control.Monad (forM_)
+import Data.Functor.Identity (Identity)
+import Data.List qualified as List
+import Data.List.NonEmpty (NonEmpty (..))
+import Data.List.NonEmpty qualified as NonEmpty
+import Data.Map.Strict qualified as Map
+import Data.Set (Set)
+import Data.Set qualified as Set
+import Data.Text (Text)
+import Database.DagMigrations.Error (Direction (..), FingerprintMismatch (..), PlanError (..))
+import Database.DagMigrations.Gen
+import Database.DagMigrations.Graph
+import Database.DagMigrations.Migration (Fingerprint (..), Migration (..))
+import Database.DagMigrations.Plan
+import Hedgehog (Gen, PropertyT, annotateShow, failure)
+import Hedgehog.Gen qualified as Gen
+import Test.Hspec
+import Test.Hspec.Hedgehog (assert, forAll, hedgehog, (===))
+
+spec :: Spec
+spec = do
+  describe "plan Up" $ do
+    it "orders steps by the linear extension of the whole registry" $
+      case validate [testMigration "1" ["3"], testMigration "2" [], testMigration "3" []] of
+        Left errors -> expectationFailure (show errors)
+        Right graph ->
+          fmap planIdentifiers (plan defaultPlanOptions graph (Set.fromList ["3"]) Up AllMigrations)
+            `shouldBe` Right ["2", "1"]
+
+    it "applies the target's down-set minus the applied set: the join S ∪ ↓t" $ hedgehog $ do
+      (graph, applied, target) <- genCase
+      steps <- planned graph applied Up target
+      Set.fromList steps === Set.difference (upTargetSet graph target) applied
+      Set.union applied (Set.fromList steps) === Set.union applied (upTargetSet graph target)
+
+    it "puts every step after its dependencies" $ hedgehog $ do
+      (graph, applied, target) <- genCase
+      steps <- planned graph applied Up target
+      let prefixes = List.inits steps
+      forM_ (zip steps prefixes) $ \(step, earlier) ->
+        assert (dependenciesOf graph step `Set.isSubsetOf` Set.union applied (Set.fromList earlier))
+
+    it "keeps the applied set a down-set after every prefix" $ hedgehog $ do
+      (graph, applied, target) <- genCase
+      steps <- planned graph applied Up target
+      assert (all (isDownSet graph . Set.union applied . Set.fromList) (List.inits steps))
+
+    it "plans nothing after the plan is applied" $ hedgehog $ do
+      (graph, applied, target) <- genCase
+      steps <- planned graph applied Up target
+      again <- planned graph (Set.union applied (Set.fromList steps)) Up target
+      again === []
+
+    it "lists steps in the order of linearOrder" $ hedgehog $ do
+      (graph, applied, target) <- genCase
+      steps <- planned graph applied Up target
+      steps === filter (`elem` steps) (linearOrder graph)
+
+    it "does not depend on the order of registration" $ hedgehog $ do
+      specs <- forAll genRegistry
+      shuffled <- forAll (Gen.shuffle specs)
+      graph <- validated (toRegistry specs)
+      graph' <- validated (toRegistry shuffled)
+      applied <- forAll (genDownSet graph)
+      target <- forAll (genTarget graph)
+      steps <- planned graph applied Up target
+      steps' <- planned graph' applied Up target
+      steps === steps'
+
+  describe "plan Down" $ do
+    it "reverts the meet S ∩ (P ∖ (↑t ∖ {t})), keeping the target applied" $ hedgehog $ do
+      (graph, applied, target) <- genCase
+      steps <- planned graph applied Down target
+      Set.difference applied (Set.fromList steps) === Set.intersection applied (downTargetSet graph target)
+
+    it "keeps the applied set a down-set after every prefix, and the target applied" $ hedgehog $ do
+      (graph, applied, target) <- genCase
+      steps <- planned graph applied Down target
+      assert (all (isDownSet graph . Set.difference applied . Set.fromList) (List.inits steps))
+      case target of
+        TargetMigration t -> assert (t `notElem` steps)
+        AllMigrations -> pure ()
+
+    it "plans nothing after the plan is applied" $ hedgehog $ do
+      (graph, applied, target) <- genCase
+      steps <- planned graph applied Down target
+      again <- planned graph (Set.difference applied (Set.fromList steps)) Down target
+      again === []
+
+    it "does not depend on the order of registration" $ hedgehog $ do
+      specs <- forAll genRegistry
+      shuffled <- forAll (Gen.shuffle specs)
+      graph <- validated (toRegistry specs)
+      graph' <- validated (toRegistry shuffled)
+      applied <- forAll (genDownSet graph)
+      target <- forAll (genTarget graph)
+      steps <- planned graph applied Down target
+      steps' <- planned graph' applied Down target
+      steps === steps'
+
+    it "lists steps in the reverse order of linearOrder" $ hedgehog $ do
+      (graph, applied, target) <- genCase
+      steps <- planned graph applied Down target
+      steps === reverse (filter (`elem` steps) (linearOrder graph))
+
+    it "is undone by applying every migration" $ hedgehog $ do
+      (graph, applied, target) <- genCase
+      reverted <- planned graph applied Down target
+      let afterDown = Set.difference applied (Set.fromList reverted)
+      restored <- planned graph afterDown Up AllMigrations
+      Set.union afterDown (Set.fromList restored) === registeredIdentifiers graph
+
+    it "reports every irreversible migration, and reverts nothing" $ hedgehog $ do
+      specs <- forAll genRegistry
+      irreversible <- forAll (Set.fromList <$> Gen.subsequence (map fst specs))
+      let marked =
+            [ if Set.member (migrationId m) irreversible then m {migrationDown = Nothing} else m
+            | m <- toRegistry specs
+            ]
+      graph <- validated marked
+      applied <- forAll (genDownSet graph)
+      target <- forAll (genTarget graph)
+      let reverting = Set.difference applied (downTargetSet graph target)
+          blocked = Set.intersection reverting irreversible
+      case plan defaultPlanOptions graph applied Down target of
+        Right (Plan _ steps) -> do
+          assert (Set.null blocked)
+          length steps === Set.size reverting
+        Left errors -> NonEmpty.toList errors === map Irreversible (reverse (filter (`Set.member` blocked) (linearOrder graph)))
+
+  describe "plan errors" $ do
+    it "reports an unknown target" $
+      planErrors [testMigration "a" []] Set.empty (TargetMigration "zz")
+        `shouldBe` Just (UnknownTarget "zz" :| [])
+
+    it "reports an applied identifier that is not registered, unless allowed" $ do
+      planErrors [testMigration "a" []] (Set.fromList ["old"]) AllMigrations
+        `shouldBe` Just (UnregisteredApplied "old" :| [])
+      case validate [testMigration "a" []] of
+        Left errors -> expectationFailure (show errors)
+        Right graph ->
+          fmap planIdentifiers (plan (PlanOptions True) graph (Set.fromList ["old"]) Up AllMigrations)
+            `shouldBe` Right ["a"]
+
+    it "reports every error of the first phase at once, in check order" $
+      planErrors [testMigration "a" [], testMigration "b" ["a"]] (Set.fromList ["old", "b"]) (TargetMigration "zz")
+        `shouldBe` Just (UnregisteredApplied "old" :| [InconsistentApplied "b" "a", UnknownTarget "zz"])
+
+    it "leaves allowed unregistered identifiers applied under Down" $
+      case validate [testMigration "a" [], testMigration "b" ["a"]] of
+        Left errors -> expectationFailure (show errors)
+        Right graph ->
+          fmap planIdentifiers (plan (PlanOptions True) graph (Set.fromList ["old", "a", "b"]) Down AllMigrations)
+            `shouldBe` Right ["b", "a"]
+
+    it "reports an applied set that is not a down-set" $
+      planErrors [testMigration "a" [], testMigration "b" ["a"]] (Set.fromList ["b"]) AllMigrations
+        `shouldBe` Just (InconsistentApplied "b" "a" :| [])
+
+    it "reports an inconsistency exactly when the applied set is not a down-set" $ hedgehog $ do
+      specs <- forAll genRegistry
+      graph <- validated (toRegistry specs)
+      applied <- forAll (Set.fromList <$> Gen.subsequence (map fst specs))
+      let inconsistent = case plan defaultPlanOptions graph applied Up AllMigrations of
+            Left errors -> any isInconsistentApplied errors
+            Right _ -> False
+      inconsistent === not (isDownSet graph applied)
+
+  describe "status" $
+    it "lists registered migrations in order, with flags, and the unregistered applied ones" $
+      case validate [testMigration "a" [], testMigration "b" ["a"]] of
+        Left errors -> expectationFailure (show errors)
+        Right graph ->
+          status graph (Set.fromList ["a", "old"])
+            `shouldBe` ([("a", True), ("b", False)], Set.fromList ["old"])
+
+  describe "checkFingerprints" $ do
+    it "records on first use, and reports both kinds of mismatch" $ do
+      let withFingerprint name fingerprint = (testMigration name []) {migrationFingerprint = fingerprint}
+          v1 = Fingerprint "v1"
+          v2 = Fingerprint "v2"
+      case validate
+        [ withFingerprint "first-use" (Just v1),
+          withFingerprint "changed" (Just v2),
+          withFingerprint "removed" Nothing,
+          withFingerprint "same" (Just v1),
+          withFingerprint "none" Nothing
+        ] of
+        Left errors -> expectationFailure (show errors)
+        Right graph ->
+          checkFingerprints
+            graph
+            ( Map.fromList
+                [ ("first-use", Nothing),
+                  ("changed", Just v1),
+                  ("removed", Just v1),
+                  ("same", Just v1),
+                  ("none", Nothing),
+                  ("unregistered", Just v1)
+                ]
+            )
+            `shouldBe` ( Map.fromList [("first-use", v1)],
+                         [ FingerprintMismatch "changed" (Just v1) (Just v2),
+                           FingerprintMismatch "removed" (Just v1) Nothing
+                         ]
+                       )
+  where
+    planErrors :: [TestMigration] -> Set Text -> Target Text -> Maybe (NonEmpty (PlanError Text))
+    planErrors registry applied target = case validate registry of
+      Left _ -> Nothing
+      Right graph -> either Just (const Nothing) (plan defaultPlanOptions graph applied Up target)
+
+-- | 'AllMigrations', or a registered migration when the graph has one.
+genTarget :: MigrationGraph Text m -> Gen (Target Text)
+genTarget graph = case linearOrder graph of
+  [] -> pure AllMigrations
+  ids -> Gen.choice [pure AllMigrations, TargetMigration <$> Gen.element ids]
+
+-- | A valid graph, a down-set of it, and a target.
+genCase :: PropertyT IO (MigrationGraph Text Identity, Set Text, Target Text)
+genCase = do
+  specs <- forAll genRegistry
+  graph <- validated (toRegistry specs)
+  applied <- forAll (genDownSet graph)
+  target <- forAll (genTarget graph)
+  pure (graph, applied, target)
+
+-- | The identifiers of the plan, or a test failure that shows the errors.
+planned :: MigrationGraph Text m -> Set Text -> Direction -> Target Text -> PropertyT IO [Text]
+planned graph applied direction target =
+  case plan defaultPlanOptions graph applied direction target of
+    Left errors -> annotateShow errors >> failure
+    Right p -> pure (planIdentifiers p)
+
+-- | The set that 'Up' brings in: every registered migration, or the
+-- target's down-set.
+upTargetSet :: MigrationGraph Text m -> Target Text -> Set Text
+upTargetSet graph AllMigrations = registeredIdentifiers graph
+upTargetSet graph (TargetMigration t) = downSet graph t
+
+-- | The largest down-set that a 'Down' plan leaves applied: nothing, or
+-- everything except what depends on the target.
+downTargetSet :: MigrationGraph Text m -> Target Text -> Set Text
+downTargetSet _ AllMigrations = Set.empty
+downTargetSet graph (TargetMigration t) =
+  Set.difference (registeredIdentifiers graph) (Set.delete t (upSet graph t))
+
+isInconsistentApplied :: PlanError i -> Bool
+isInconsistentApplied (InconsistentApplied _ _) = True
+isInconsistentApplied _ = False
+
+dependenciesOf :: MigrationGraph Text m -> Text -> Set Text
+dependenciesOf graph i = maybe Set.empty migrationDependencies (lookupMigration i graph)
diff --git a/test/Database/DagMigrations/RunSpec.hs b/test/Database/DagMigrations/RunSpec.hs
new file mode 100644
--- /dev/null
+++ b/test/Database/DagMigrations/RunSpec.hs
@@ -0,0 +1,385 @@
+module Database.DagMigrations.RunSpec (spec) where
+
+import Control.Exception (ErrorCall (..), throwIO)
+import Control.Monad.IO.Class (liftIO)
+import Data.IORef (IORef, modifyIORef', newIORef, readIORef)
+import Data.List.NonEmpty (NonEmpty (..))
+import Data.List.NonEmpty qualified as NonEmpty
+import Data.Map.Strict qualified as Map
+import Data.Set (Set)
+import Data.Set qualified as Set
+import Data.Text (Text)
+import Data.Text qualified as Text
+import Database.DagMigrations.Adapter (Adapter (..), AppliedRow (..))
+import Database.DagMigrations.Error
+import Database.DagMigrations.FakeAdapter
+import Database.DagMigrations.Gen (RegistrySpec, genDownSet, genRegistry, isDownSet, validated)
+import Database.DagMigrations.Graph (MigrationGraph, downSet, linearOrder, registeredIdentifiers, upSet, validate)
+import Database.DagMigrations.Migration
+import Database.DagMigrations.Plan (PlanOptions (..), Target (..), defaultPlanOptions, plan, planIdentifiers)
+import Database.DagMigrations.Progress
+import Database.DagMigrations.Run
+import Hedgehog (Gen, PropertyT, annotateShow, evalIO, failure)
+import Hedgehog.Gen qualified as Gen
+import Test.Hspec
+import Test.Hspec.Hedgehog (assert, forAll, hedgehog, (===))
+
+-- | A fake database in the given state, a migrator over it with the given
+-- settings and registry, and the events that runs report.
+data Harness = Harness
+  { harnessDatabase :: IORef FakeDatabase,
+    harnessEvents :: IORef [ProgressEvent Text],
+    harnessMigrator :: Migrator Text FakeM FakeTx Text FakeError
+  }
+
+harness :: FakeDatabase -> RunSettings -> IdentifierCodec Text -> [Migration Text FakeM] -> IO Harness
+harness = harnessWith noFaults
+
+-- | Like 'harness', with the given faults in the fake adapter.
+harnessWith :: FakeFaults -> FakeDatabase -> RunSettings -> IdentifierCodec Text -> [Migration Text FakeM] -> IO Harness
+harnessWith faults initial settings codec registry = do
+  databaseRef <- newIORef initial
+  eventsRef <- newIORef []
+  graph <- either (fail . show) pure (validate registry)
+  pure
+    Harness
+      { harnessDatabase = databaseRef,
+        harnessEvents = eventsRef,
+        harnessMigrator =
+          Migrator
+            { migratorAdapter = fakeAdapterWith faults databaseRef,
+              migratorCodec = codec,
+              migratorInterpreter = fakeInterpreter,
+              migratorProgress = Progress (\event -> modifyIORef' eventsRef (event :)),
+              migratorSettings = settings,
+              migratorGraph = graph
+            }
+      }
+
+events :: Harness -> IO [ProgressEvent Text]
+events h = reverse <$> readIORef (harnessEvents h)
+
+database :: Harness -> IO FakeDatabase
+database = readIORef . harnessDatabase
+
+-- | A tracking table that holds the given rows, and no other tables.
+withRows :: [(Text, Maybe Fingerprint)] -> FakeDatabase
+withRows rows = emptyDatabase {fakeTrackingTable = Just (Map.fromList rows)}
+
+fingerprinted :: Fingerprint -> Migration Text FakeM -> Migration Text FakeM
+fingerprinted fingerprint m = m {migrationFingerprint = Just fingerprint}
+
+v1, v2 :: Fingerprint
+v1 = Fingerprint "v1"
+v2 = Fingerprint "v2"
+
+abc :: [Migration Text FakeM]
+abc = [tableMigration "a" [], tableMigration "b" ["a"], tableMigration "c" ["a"]]
+
+spec :: Spec
+spec = do
+  describe "migrate" $ do
+    it "creates the tracking table and applies every migration in order" $ do
+      h <- harness emptyDatabase defaultRunSettings textIdentifiers abc
+      migrate (harnessMigrator h) Up AllMigrations `shouldReturn` Right ()
+      database h
+        `shouldReturn` FakeDatabase
+          { fakeTrackingTable = Just (Map.fromList [("a", Nothing), ("b", Nothing), ("c", Nothing)]),
+            fakeTables = Set.fromList ["a", "b", "c"]
+          }
+      events h
+        `shouldReturn` [ TrackingTableCreated (TrackingVersion 1),
+                         MigrationStarted Up "a",
+                         MigrationFinished Up "a",
+                         MigrationStarted Up "b",
+                         MigrationFinished Up "b",
+                         MigrationStarted Up "c",
+                         MigrationFinished Up "c"
+                       ]
+
+    it "does nothing when every migration is applied" $ do
+      h <- harness emptyDatabase defaultRunSettings textIdentifiers abc
+      _ <- migrate (harnessMigrator h) Up AllMigrations
+      settled <- database h
+      h' <- harness settled defaultRunSettings textIdentifiers abc
+      migrate (harnessMigrator h') Up AllMigrations `shouldReturn` Right ()
+      database h' `shouldReturn` settled
+      events h' `shouldReturn` []
+
+    it "stops at a failed migration and keeps the steps before it" $ do
+      let failing = (tableMigration "b" ["a"]) {migrationUp = createTable "b" >> failWith "boom"}
+      h <- harness emptyDatabase defaultRunSettings textIdentifiers [tableMigration "a" [], failing]
+      migrate (harnessMigrator h) Up AllMigrations
+        `shouldReturn` Left (MigrationFailed "b" Up (Right "boom"))
+      database h `shouldReturn` (withRows [("a", Nothing)]) {fakeTables = Set.fromList ["a"]}
+
+    it "rolls back a migration that throws, and rethrows" $ do
+      let throwing = (tableMigration "b" ["a"]) {migrationUp = createTable "b" >> liftIO (throwIO (ErrorCall "thrown"))}
+      h <- harness emptyDatabase defaultRunSettings textIdentifiers [tableMigration "a" [], throwing]
+      migrate (harnessMigrator h) Up AllMigrations `shouldThrow` (== ErrorCall "thrown")
+      database h `shouldReturn` (withRows [("a", Nothing)]) {fakeTables = Set.fromList ["a"]}
+
+    it "reports a failure of the database library as the adapter's error, and rolls back" $ do
+      let failing = (tableMigration "b" ["a"]) {migrationUp = createTable "b" >> liftIO (throwIO (FakeError "sql"))}
+      h <- harness emptyDatabase defaultRunSettings textIdentifiers [tableMigration "a" [], failing]
+      migrate (harnessMigrator h) Up AllMigrations
+        `shouldReturn` Left (MigrationFailed "b" Up (Left (FakeError "sql")))
+      database h `shouldReturn` (withRows [("a", Nothing)]) {fakeTables = Set.fromList ["a"]}
+
+    it "rolls back a migration whose row the adapter cannot record" $ do
+      let faults = noFaults {faultRecordApplied = Just (FakeError "record")}
+      h <- harnessWith faults emptyDatabase defaultRunSettings textIdentifiers [tableMigration "a" []]
+      migrate (harnessMigrator h) Up AllMigrations
+        `shouldReturn` Left (MigrationFailed "a" Up (Left (FakeError "record")))
+      database h `shouldReturn` withRows []
+
+    it "reports a failure of the run lock, and writes nothing" $ do
+      let faults = noFaults {faultLock = Just (FakeError "locked")}
+      h <- harnessWith faults emptyDatabase defaultRunSettings textIdentifiers abc
+      migrate (harnessMigrator h) Up AllMigrations `shouldReturn` Left (AdapterFailed (FakeError "locked"))
+      database h `shouldReturn` emptyDatabase
+
+    it "reports an upgrade of the tracking table" $ do
+      let faults = noFaults {faultUpgradeFrom = Just (TrackingVersion 0)}
+      h <- harnessWith faults (withRows []) defaultRunSettings textIdentifiers [tableMigration "a" []]
+      migrate (harnessMigrator h) Up AllMigrations `shouldReturn` Right ()
+      events h
+        `shouldReturn` [ TrackingTableUpgraded (TrackingVersion 0) (TrackingVersion 1),
+                         MigrationStarted Up "a",
+                         MigrationFinished Up "a"
+                       ]
+
+    it "reverts what depends on the target, and keeps the target" $ do
+      h <- harness emptyDatabase defaultRunSettings textIdentifiers abc
+      _ <- migrate (harnessMigrator h) Up AllMigrations
+      migrate (harnessMigrator h) Down (TargetMigration "a") `shouldReturn` Right ()
+      database h `shouldReturn` (withRows [("a", Nothing)]) {fakeTables = Set.fromList ["a"]}
+
+    it "writes nothing when planning fails" $ do
+      h <- harness emptyDatabase defaultRunSettings textIdentifiers abc
+      migrate (harnessMigrator h) Up (TargetMigration "zz")
+        `shouldReturn` Left (PlanFailed (UnknownTarget "zz" :| []))
+      database h `shouldReturn` emptyDatabase
+
+    it "records no first-use fingerprint when planning fails" $ do
+      let initial = withRows [("a", Nothing)]
+      h <- harness initial defaultRunSettings textIdentifiers [fingerprinted v1 (tableMigration "a" [])]
+      migrate (harnessMigrator h) Up (TargetMigration "zz")
+        `shouldReturn` Left (PlanFailed (UnknownTarget "zz" :| []))
+      database h `shouldReturn` initial
+
+    it "rejects a fingerprint mismatch by default, and writes nothing" $ do
+      let initial = withRows [("a", Just v1)]
+      h <- harness initial defaultRunSettings textIdentifiers [fingerprinted v2 (tableMigration "a" []), tableMigration "b" ["a"]]
+      migrate (harnessMigrator h) Up AllMigrations
+        `shouldReturn` Left (FingerprintsMismatched (FingerprintMismatch "a" (Just v1) (Just v2) :| []))
+      database h `shouldReturn` initial
+
+    it "reports a mismatch and continues under the warning policy" $ do
+      let settings = defaultRunSettings {runFingerprintPolicy = MismatchIsWarning}
+      h <- harness (withRows [("a", Just v1)]) settings textIdentifiers [fingerprinted v2 (tableMigration "a" []), tableMigration "b" ["a"]]
+      migrate (harnessMigrator h) Up AllMigrations `shouldReturn` Right ()
+      events h
+        `shouldReturn` [ FingerprintMismatchIgnored (FingerprintMismatch "a" (Just v1) (Just v2)),
+                         MigrationStarted Up "b",
+                         MigrationFinished Up "b"
+                       ]
+
+    it "records a fingerprint on first use" $ do
+      h <- harness (withRows [("a", Nothing)]) defaultRunSettings textIdentifiers [fingerprinted v1 (tableMigration "a" [])]
+      migrate (harnessMigrator h) Up AllMigrations `shouldReturn` Right ()
+      fakeTrackingTable <$> database h `shouldReturn` Just (Map.fromList [("a", Just v1)])
+      events h `shouldReturn` [FingerprintRecorded "a"]
+
+    it "fails on an identifier that the codec does not decode" $ do
+      let rejecting = textIdentifiers {decodeIdentifier = \raw -> if raw == "bad" then Nothing else Just raw}
+      h <- harness (withRows [("bad", Nothing)]) defaultRunSettings rejecting abc
+      migrate (harnessMigrator h) Up AllMigrations `shouldReturn` Left (UndecodableIdentifier "bad")
+
+    it "fails on text that decodes to an identifier with a different encoding" $ do
+      -- Rows are written by encoding, so a row named "A" could never be
+      -- removed or updated through the identifier "a". This codec breaks the
+      -- codec law for upper-case identifiers on purpose; the registry has
+      -- none, and no project should copy it.
+      let lowering = textIdentifiers {decodeIdentifier = Just . Text.toLower}
+          initial = withRows [("A", Nothing)]
+      h <- harness initial defaultRunSettings lowering abc
+      migrate (harnessMigrator h) Down AllMigrations `shouldReturn` Left (NonCanonicalIdentifier "A" "a")
+      database h `shouldReturn` initial
+
+    it "leaves an allowed unregistered row in place" $ do
+      let settings = defaultRunSettings {runPlanOptions = defaultPlanOptions {allowUnregisteredApplied = True}}
+      h <- harness (withRows [("old", Nothing)]) settings textIdentifiers abc
+      migrate (harnessMigrator h) Up AllMigrations `shouldReturn` Right ()
+      database h
+        `shouldReturn` (withRows [("old", Nothing), ("a", Nothing), ("b", Nothing), ("c", Nothing)])
+          { fakeTables = Set.fromList ["a", "b", "c"]
+          }
+
+  describe "migrate, as a property" $ do
+    it "reaches S ∪ ↓t under Up, and S ∩ (P ∖ (↑t ∖ {t})) under Down" $ hedgehog $ do
+      RunCase specs graph applied direction target <- genRunCase
+      h <- evalIO (harness (seeded applied) defaultRunSettings textIdentifiers (tableRegistry specs))
+      result <- evalIO (migrate (harnessMigrator h) direction target)
+      result === Right ()
+      db <- evalIO (database h)
+      let expected = reachedSet graph applied direction target
+      fmap Map.keysSet (fakeTrackingTable db) === Just expected
+      fakeTables db === expected
+
+    it "keeps the steps before a failed step, and leaves a down-set" $ hedgehog $ do
+      RunCase specs graph applied direction target <- genRunCase
+      steps <- case plan defaultPlanOptions graph applied direction target of
+        Left errors -> annotateShow errors >> failure
+        Right p -> pure (planIdentifiers p)
+      case NonEmpty.nonEmpty (zip [0 :: Int ..] steps) of
+        Nothing -> pure ()
+        Just indexed -> do
+          (k, failing) <- forAll (Gen.element indexed)
+          let registry = map (failingIn direction failing) (tableRegistry specs)
+          h <- evalIO (harness (seeded applied) defaultRunSettings textIdentifiers registry)
+          result <- evalIO (migrate (harnessMigrator h) direction target)
+          result === Left (MigrationFailed failing direction (Right "boom"))
+          db <- evalIO (database h)
+          let done = Set.fromList (take k steps)
+              expected = case direction of
+                Up -> Set.union applied done
+                Down -> Set.difference applied done
+          fmap Map.keysSet (fakeTrackingTable db) === Just expected
+          fakeTables db === expected
+          assert (isDownSet graph (fakeTables db))
+
+  describe "acceptFingerprints" $ do
+    it "records the registered fingerprint, so that the next run succeeds" $ do
+      h <- harness (withRows [("a", Just v1)]) defaultRunSettings textIdentifiers [fingerprinted v2 (tableMigration "a" [])]
+      acceptFingerprints (harnessMigrator h) (Set.fromList ["a"]) `shouldReturn` Right ()
+      fakeTrackingTable <$> database h `shouldReturn` Just (Map.fromList [("a", Just v2)])
+      migrate (harnessMigrator h) Up AllMigrations `shouldReturn` Right ()
+
+    it "records null for a migration whose registered fingerprint is Nothing" $ do
+      h <- harness (withRows [("a", Just v1)]) defaultRunSettings textIdentifiers [tableMigration "a" []]
+      acceptFingerprints (harnessMigrator h) (Set.fromList ["a"]) `shouldReturn` Right ()
+      fakeTrackingTable <$> database h `shouldReturn` Just (Map.fromList [("a", Nothing)])
+
+    it "returns at once for an empty set: it takes no lock and writes nothing" $ do
+      let faults = noFaults {faultLock = Just (FakeError "locked")}
+      h <- harnessWith faults emptyDatabase defaultRunSettings textIdentifiers abc
+      acceptFingerprints (harnessMigrator h) Set.empty `shouldReturn` Right ()
+      database h `shouldReturn` emptyDatabase
+
+    it "rejects every name that is not registered or not applied" $ do
+      h <- harness (withRows []) defaultRunSettings textIdentifiers abc
+      acceptFingerprints (harnessMigrator h) (Set.fromList ["a", "zz"])
+        `shouldReturn` Left (CannotAccept (NotApplied "a" :| [NotRegistered "zz"]))
+      database h `shouldReturn` withRows []
+
+  describe "inspect" $ do
+    it "reports status and fingerprints, and writes nothing" $ do
+      let initial = withRows [("a", Nothing)]
+      h <- harness initial defaultRunSettings textIdentifiers [fingerprinted v1 (tableMigration "a" []), tableMigration "b" ["a"]]
+      inspect (harnessMigrator h)
+        `shouldReturn` Right
+          Inspection
+            { inspectedStatus = [("a", True), ("b", False)],
+              inspectedUnregistered = Set.empty,
+              inspectedMismatches = [],
+              inspectedToRecord = Map.fromList [("a", v1)]
+            }
+      database h `shouldReturn` initial
+
+    it "does not create the tracking table" $ do
+      h <- harness emptyDatabase defaultRunSettings textIdentifiers abc
+      _ <- inspect (harnessMigrator h)
+      database h `shouldReturn` emptyDatabase
+
+    it "reports applied identifiers that no registered migration has" $ do
+      h <- harness (withRows [("a", Nothing), ("old", Nothing)]) defaultRunSettings textIdentifiers abc
+      inspect (harnessMigrator h)
+        `shouldReturn` Right
+          Inspection
+            { inspectedStatus = [("a", True), ("b", False), ("c", False)],
+              inspectedUnregistered = Set.fromList ["old"],
+              inspectedMismatches = [],
+              inspectedToRecord = Map.empty
+            }
+
+    it "fails on an identifier that the codec does not decode" $ do
+      let rejecting = textIdentifiers {decodeIdentifier = \raw -> if raw == "bad" then Nothing else Just raw}
+      h <- harness (withRows [("bad", Nothing)]) defaultRunSettings rejecting abc
+      inspect (harnessMigrator h) `shouldReturn` Left (UndecodableIdentifier "bad")
+
+  describe "the fake adapter" $ do
+    it "fails to record a row that exists, and changes nothing" $ do
+      let initial = withRows [("a", Just v1)]
+      ref <- newIORef initial
+      let adapter = fakeAdapter ref
+      committing adapter (\tx -> recordApplied adapter tx (AppliedRow "a" "" Nothing))
+        `shouldReturn` Right (Left (FakeError "row exists: a"))
+      readIORef ref `shouldReturn` initial
+
+    it "fails to remove a row that does not exist, and changes nothing" $ do
+      let initial = withRows [("a", Nothing)]
+      ref <- newIORef initial
+      let adapter = fakeAdapter ref
+      committing adapter (\tx -> removeApplied adapter tx "b")
+        `shouldReturn` Right (Left (FakeError "no row: b"))
+      readIORef ref `shouldReturn` initial
+
+-- | Runs the operation in a transaction of the fake adapter, and commits
+-- whatever the operation returns, so that a test sees both the operation's
+-- result and every change that the operation made.
+committing ::
+  Adapter FakeTx FakeError ->
+  (FakeTx -> IO (Either FakeError ())) ->
+  IO (Either (Either FakeError ()) (Either FakeError ()))
+committing adapter operation = withTransaction adapter (fmap Right . operation)
+
+-- | A generated registry, a down-set of it, a direction, and a target.
+data RunCase = RunCase RegistrySpec (MigrationGraph Text FakeM) (Set Text) Direction (Target Text)
+
+genRunCase :: PropertyT IO RunCase
+genRunCase = do
+  specs <- forAll genRegistry
+  graph <- validated (tableRegistry specs)
+  applied <- forAll (genDownSet graph)
+  direction <- forAll Gen.enumBounded
+  target <- forAll (genTarget graph)
+  pure (RunCase specs graph applied direction target)
+
+-- | 'AllMigrations', or a registered migration when the graph has one.
+genTarget :: MigrationGraph Text m -> Gen (Target Text)
+genTarget graph = case linearOrder graph of
+  [] -> pure AllMigrations
+  ids -> Gen.choice [pure AllMigrations, TargetMigration <$> Gen.element ids]
+
+-- | The migrations of the spec, each of which creates the table with its
+-- own name, and drops it when reverted.
+tableRegistry :: RegistrySpec -> [Migration Text FakeM]
+tableRegistry = map (uncurry tableMigration)
+
+-- | A database to which runs applied exactly the given migrations: it has
+-- a tracking row with no fingerprint for each, and the table that each
+-- created.
+seeded :: Set Text -> FakeDatabase
+seeded applied =
+  FakeDatabase {fakeTrackingTable = Just (Map.fromSet (const Nothing) applied), fakeTables = applied}
+
+-- | The migration with its action for the direction replaced by one that
+-- changes its table and then fails with @"boom"@, when it has the given
+-- identifier. Any other migration is unchanged.
+failingIn :: Direction -> Text -> Migration Text FakeM -> Migration Text FakeM
+failingIn direction name m
+  | migrationId m /= name = m
+  | otherwise = case direction of
+      Up -> m {migrationUp = createTable name >> failWith "boom"}
+      Down -> m {migrationDown = Just (dropTable name >> failWith "boom")}
+
+-- | The applied set after a successful run from the applied set S in the
+-- direction, towards the target t: S ∪ ↓t under 'Up', and
+-- S ∩ (P ∖ (↑t ∖ {t})) under 'Down'.
+reachedSet :: MigrationGraph Text m -> Set Text -> Direction -> Target Text -> Set Text
+reachedSet graph applied Up AllMigrations = Set.union applied (registeredIdentifiers graph)
+reachedSet graph applied Up (TargetMigration t) = Set.union applied (downSet graph t)
+reachedSet _ _ Down AllMigrations = Set.empty
+reachedSet graph applied Down (TargetMigration t) =
+  Set.intersection applied (Set.difference (registeredIdentifiers graph) (Set.delete t (upSet graph t)))
diff --git a/test/Main.hs b/test/Main.hs
new file mode 100644
--- /dev/null
+++ b/test/Main.hs
@@ -0,0 +1,12 @@
+module Main (main) where
+
+import Database.DagMigrations.GraphSpec qualified as GraphSpec
+import Database.DagMigrations.PlanSpec qualified as PlanSpec
+import Database.DagMigrations.RunSpec qualified as RunSpec
+import Test.Hspec (describe, hspec)
+
+main :: IO ()
+main = hspec $ do
+  describe "Graph" GraphSpec.spec
+  describe "Plan" PlanSpec.spec
+  describe "Run" RunSpec.spec
