Migrate one service
Prepare a small, behavior-preserving migration of one existing service. This is
an execution workflow, not permission to redesign a service's lifecycle. The
services guide is the authoring
guide; read it rather than copying an earlier migration blindly.
For a new service, use add-service to generate and
complete the root instead.
1. Establish the starting point
- Read the root and nearest
AGENTS.md, the
testing guide and
- Inspect status, existing branches/worktrees and related PRs. Preserve unrelated
work. Fetch origin and start from current origin/main; refresh dependencies
with pnpm bootstrap in a fresh checkout or after dependency changes.
- Read this service's entry under
servicesin
ghost/core/server/services/legacy-service-inventory.yaml and any existing
migration plan. If a plan-registry skill is available, use it to find/update that plan;
do not create a competing plan in the repository.
- Verify prerequisites are merged. An open tests or enforcement PR is not main.
Preparation can proceed against a proposed policy, but record its exact head
and repeat validation against the policy that actually merges.
2. Audit the whole service and its callers
Use rg across production and tests. Include deep imports, nested helpers,
separate actions, job handlers, CLI use and CommonJS consumers. Also inspect
shared boot harnesses and tests that construct routers or renderers indirectly;
a search for the service name alone misses those fixtures. Record:
- Existing runtime/type exports and the intended instance and extras surfaces.
- Who constructs each instance and whether consumers capture it during import.
- Dependencies acquired at import, boot, request, dispatch and job execution.
- Configuration captured once versus read again for each operation.
- Shared identity, caches, pending/rejected promises and invalidation semantics.
- Resource ownership, partial-startup cleanup, normal shutdown and failure policy.
Confirm the capability belongs in services. A reusable constructor or helper
without an application-owned instance belongs elsewhere; do not add an empty
initializer merely to keep its directory.
Read .dependency-cruiser.cjs and .oxlintrc.json on the actual base. The
service-dependencies rule covers every implementation file in the directory,
not just the main class. Only the top-level wiring index.ts is exempt in lint.
pnpm gx services audit also exempts a legacy index.js root, so its output
omits that root's imports.
Implementations must not retrieve collaborators through their own root.
Wire application instances, models, logging, DomainEvents and configured
adapters in the root. The guide's dependency boundaries cover fs, lodash,
deferred lookups and live configuration reads.
Keep approved libraries imported where used and use explicit type-only imports.
Type injected logging as GhostLogger (or a Pick of it) from
@tryghost/logging, never a hand-written shape; class tests inject
createLoggingFake() from ghost/test/utils/logging-utils rather than stubbing
the global logger.
Do not inject stateless utilities to evade the policy or duplicate shared helpers.
Inspect the source before adding a library allowance. Justify why the dependency
is a library rather than an application-owned instance, and allow only its exact
entry or file. Include the reason and a boundary regression in the migration PR
that needs the allowance. Write out each file the allowance admits in full, as
dependency-cruiser resolves it from source and from built output, in a boundary
regression; gx services verify looks for the literal path, not one built from
variables. Assert each rejected target as well as its rule and source. Keep
allowances out of standalone skill/tooling PRs.
Seek review when that distinction is unclear or a broader policy change is
needed; do not widen the rule merely to make lint pass. Deleting the service's
legacy entry still belongs in each migration.
Preserve late acquisition with getters/factories when dependencies are unavailable
at boot. Inspect pnpm gx services report <name> and the full
pnpm gx services audit output: a summary may omit unresolved/own-root imports.
3. Establish coverage before changing production
Map each proposed change to an existing behavioral assertion. Run the relevant
unchanged root/implementation tests and real consumer checks on the base.
Use the testing guide's focused Nx commands: they prepare workspace builds and
Core assets before running the selected files. Direct Vitest or test:single
commands skip those prerequisites; pnpm bootstrap alone does not supply them.
Treat missing package outputs or card manifests as setup failures. Do not compile
Core merely to supply workspace outputs: adjacent emitted JavaScript can shadow
TypeScript edits in CommonJS consumers.
Initialization complexity, an audited inventory entry or an old green result
is not proof of coverage. If a test reloads CommonJS modules, restore the loaded
consumer chain too: cached consumers can retain a discarded root or collaborator.
Run those suites with their neighboring consumers in one worker to check isolation.
Cover the real risk: retained consumers, configuration timing, transaction or
cache behavior, boot ordering and resource cleanup. Use existing cold-boot
HTTP/job coverage where it already proves readiness. Do not copy a boot harness
for every service or duplicate generic kernel concurrency/retry tests.
For async ordering tests, verify both a missing required await and a harmless
extra await: the first must fail and the second must pass. Avoid checks that
count microtask turns; follow the testing guide's async-ordering advice.
If a needed assertion is absent, prepare passing characterization against the
old implementation in a tests-only PR and merge it first. Keep one commit per
service in preparatory batches. If a test exposes a production bug, isolate the
fix ahead of initializer adoption; do not change expectations to hide it.
Update each prepared service's inventory evidence in that tests-only change,
citing the new tests and narrowing only the blockers they cover. Preserve
historical audit revisions; do not defer this evidence to initializer adoption.
Substantial dependency refactors, fixture rewrites and business changes are also
preparation work, separate from the minimal initializer PR. Preserve the old
public API during preparation. Small dependency wiring can accompany migration
when existing tests protect it.
4. Make the smallest initializer change
- Create a TypeScript top-level
index.tsdefault-exportingdefineService
from the kernel. Return one fully ready instance from its factory, or one
typed object when several objects are built together.
- Expose normal operations on
.service. Keep classes and implementation
contracts in implementation files; root named exports are type-only.
- Use optional
extrasonly for justified transitional concerns. Catalogue each
helper's purpose, callers, timing, dependencies, failure policy and destination.
Extras are not automatic lifecycle hooks or a substitute for readiness.
- Boot calls and awaits
init()in the appropriate phase, even for a
synchronous factory. Initialize before eager consumers read .service.
Importing a root early is fine; evaluating its guarded getter early is not.
- Adapt every production consumer. Retain CommonJS
.defaultat existing
boundaries; do not convert boot wholesale or add a wrapper solely for it.
- Preserve receivers when forwarding methods. Keep validation at the same public
boundary and preserve synchronous throws versus promise rejections where
callers depend on that distinction.
- Keep config reads, external operations, jobs and per-operation resources at
their established times. Do not make the first request initialize the service.
- If startup acquires resources, clean up that attempt before rejecting. Do not
dispose borrowed shared resources or change normal shutdown ownership.
If the service requires new kernel features, a restart/replacement policy, an API
redesign or broad boot orchestration, record the concrete mismatch and separate
that decision from the small migration. Do not silently expand its scope.
Migration tests may receive mechanical import/type/stub and initializer-await
adaptations. New assertions about behavior the old implementation already has,
and substantial harness changes, return to preparation. The migration commit
adds new cases only for what cannot be tested before the root exists:
- Boundary regressions for new exact dependency allowances.
- Boot order, where another root reads this one: boot finishes this root's
init() before it starts theirs.
- Readiness: a consumer's
init()fails until this root is ready, and a
consumer loaded before init() reads the instance on use.
Each must fail under a change you can name. Never weaken assertions,
coverage gates, lint or types to make the refactor pass.
5. Update the inventory and verify
A migrated service is no longer legacy:
- Delete its entry under
servicesin the legacy service inventory. Git
history keeps the audit record.
- Delete all its entries from
.dependency-cruiser-known-violations.json. A
service that is not legacy cannot have any.
- If the root declares extras, move their catalogue to the service's entry in
the inventory's followUps section. A suggested future home, and
notes on what defineService does not do for the service yet, go there too.
That entry holds nothing else; leave it out when nothing is open.
- Move any bug the entry's
blockersdescribe to the inventory'sknownBugs
section, so deleting the entry does not lose it.
- Repair affected file references and startup-order descriptions in other
legacy entries mechanically, without changing their unrelated assessments.
An audit SHA you add must be a commit on main: a branch commit disappears on
squash merge.
There is no lint list to update. Deleting the entry applies
ghost/service-root-shape to the root and full boundary enforcement to the
implementation. It also applies ghost/boot-awaits-service-init and the
standard services boot test: boot must bind the root with .default and await
its init(), as
shows. Never add a legacy entry or defer a service's dependency
checks: CI rejects both. Do not claim enforcement passed if that policy was
only checked in a temporary integration or is still awaiting merge.
Run focused tests before/after, relevant real consumer/DB checks and the default
pnpm check, then pnpm gx services verify <name> on the committed result. Repeat
gx services verify after every rebase or fix: hooks do not run during a rebase.
Before a PR is opened or marked ready, an agent that did not write the change runs
the verify-service-change skill. Run one full
local validation at a time. Investigate failures from fresh output; a passing
retry or an unchanged file alone does not establish that a failure belongs to
main. Keep unrelated fixes out of the migration.
Review the final diff: one service, unchanged operation behavior, no hidden
composition, and only justified metadata/enforcement changes. New test cases
are limited to those step 4 allows.
Use the repository commit skill and make one commit for this service.
Keep unrelated tooling/skill changes on their own branch. Report the branch,
commit, validation and unresolved prerequisites. Push/open a PR only within the
user's authorization, rebase on fetched main before opening, and report current
CI/review state accurately. Do not merge or enable auto-merge implicitly.