Skip to content
This repository was archived by the owner on Nov 25, 2026. It is now read-only.

feat(mongo-family): port contract spaces - #494

Merged
wmadden merged 44 commits into
mainfrom
tml-2408-port-contract-spaces-to-the-mongo-family
May 13, 2026
Merged

wmadden merged 44 commits into
mainfrom
tml-2408-port-contract-spaces-to-the-mongo-family

Conversation

@wmadden

@wmadden wmadden commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

closes TML-2408

After this lands, a Mongo extension can declare a contract space the same way an SQL one does:

export const auditPack: MongoControlExtensionDescriptor = {
  id: 'audit',
  targetId: 'mongo',
  contractSpace: {
    contractJson: auditContract,
    headRef: { hash: 'sha256:…', invariants: [] },
    migrations: auditMigrations,
  },
};

The framework plans, applies, verifies, and pins each space's contract through the same per-space machinery ADR 212 specifies and the SQL family already implements. The marker collection (_prisma_migrations) gains a space axis: one document per loaded space keyed by _id: <spaceId>, with space carried as a stamped field for partitioned reads.

The decision

One architectural call separates Mongo from SQL: cross-space apply is resumable per-space, not transactional all-or-nothing. Mongo cannot wrap a multi-space apply in a single session transaction — most DDL operations bypass session transactions entirely — so cross-space rollback is not architecturally available. Instead, each space's marker advance is the commit point: per-space verify must pass before the marker advances, and a failure leaves earlier-advanced markers in place. Re-running converges (each at-head space is a no-op skip; the failed space retries; later spaces follow). The atomicity model is documented at subsystem 10 § Contract spaces, with a one-line cross-reference in subsystem 7.

What changed

  • Per-space marker collection. marker-ledger.ts takes a space parameter on every read/write/CAS. Ledger entries gain space so the same edgeId can recur across spaces (e.g. the synthetic ∅→head edge on first apply). readMarker is single-path; readAllMarkers returns the full multi-space map and defensively filters docs that lack a space field.

  • Multi-space runner with per-space verify projection. mongo-target-descriptor.ts iterates perSpaceOptions in caller order; per-space runner.execute is followed by a strict verify against the projected slice of the live database (sibling-space collections are pruned before verify runs). The runner exposes an optional projectSchema callback so the descriptor can wire the slice in without verifyMongoSchema knowing about contract spaces. Failure short-circuits with failingSpace and a MultiSpaceRunnerFailure shape that surfaces which space stopped the apply.

  • Descriptor surface. MongoControlExtensionDescriptor.contractSpace? carries (contractJson, migrations, headRef). createMongoFamilyInstance runs assertDescriptorSelfConsistency over each extension, so a stale headRef.hash fails fast at construction with the existing MIGRATION.DESCRIPTOR_HEAD_HASH_MISMATCH rather than corrupting an apply.

  • Schema-prune lift to a family-agnostic helper. projectSchemaToSpace and the loader's storage-element extractor previously knew only about SQL's storage.tables. They now duck-type Mongo's storage.collections (record and array forms) too, with the actual walk consolidated into extract-storage-element-names.ts. No MongoSchemaIR import lands in migration-tools; an unrecognised storage shape falls through unchanged.

  • Codec-rehydration guardrail. Migration ops, once serialised to disk, must execute with no codec runtime instances loaded. A new integration test plans an app + extension aggregate, JSON-roundtrips the ops through serializeMongoOps, and runs executeAcrossSpaces with an empty controlStack against mongodb-memory-server. A future regression that re-introduces a codec lookup at apply time turns this test red.

How a multi-space apply runs

For a fresh DB with one app space and one extension space:

  1. Plan + apply each space's migrations against the live MongoDB instance, in caller order.
  2. Introspect the live schema, project to the space's slice via projectSchemaToSpace, run strict verifyMongoSchema against that slice.
  3. If verify passes, advance that space's marker ({_id: <spaceId>, space: <spaceId>, storageHash, …}) and write a ledger entry.
  4. Move to the next space.

If step 2 fails for space N: spaces 1..N−1 keep their advanced markers, space N's marker stays at its prior hash, and the runner returns immediately with failingSpace: N. Re-running finds 1..N−1 already at-head (the runner's idempotency optimisation skips them) and retries N onward.

Why this shape, not the alternatives

  • Why not transactional cross-space apply? That's the SQL model. Mongo session transactions don't cover most DDL operations (createCollection, createIndex, collMod, …), so wrapping a multi-space apply in withTransaction would silently fail to roll back the DDL ops on abort. Resumable + idempotent ops give the same end-state property — eventual convergence to the destination contract — without claiming an atomicity Mongo cannot deliver. Subsystem 10 names the trade-off explicitly so a reader landing on the migration-system doc knows where to look.

  • Why duck-type the storage shape in framework code, instead of registering an extractor per family? A family-registered extractor callback (the cleaner architectural answer) would touch every SQL family call site for no near-term gain; the duck-typed walk lives in one ~30-line helper with an explicit fall-through guarantee for unrecognised shapes. Worth a focused follow-up if the team wants to invert the dependency, but not part of this port.

  • Why no typed .d.ts renderer for extension contracts? The framework's contract-space-seed-phase emits a placeholder .d.ts (export {};) for every family's extension spaces today — not just Mongo. Byte-equivalent re-emission is satisfied by the placeholder's by-construction stability. A typed renderer is a framework-wide concern, separately tracked.

Compatibility & risk

  • Existing single-space deployments: no semantic change. The single-space code paths are preserved; runner.execute(options) leaves the per-space projection callback unset; markers keep their existing shape on first apply ({_id: 'app', space: 'app', …}).
  • Pre-port marker shape: the prior {_id: 'marker', …} legacy doc shape is not auto-upgraded — by design (no production Mongo users on that shape; the no-backward-compat-shims rule applies). If such a doc exists it is filtered out by readAllMarkers and the next apply against _id: 'app' proceeds unaffected.
  • Cross-space rollback is not available on Mongo, by design. Documented at subsystem 10.

Follow-ups

  • Per-space data-op session transactions on replica sets (could provide intra-space atomicity for operationClass: 'data' ops; no consumer requesting it; recorded in subsystem 10).
  • Typed .d.ts renderer for extension contracts — framework-wide, not Mongo-specific.
  • TML-2506 (mongoQuery().updateMany(…) not in the runner's deserializer) and TML-2507 (Mongo collMod postcheck too lenient on validator content) — surfaced while regenerating the retail-store example chain; both filed.

Summary by CodeRabbit

  • New Features

    • Multi-space migrations: per‑space execution with verify‑gated, resumable markers and optional Mongo contract‑space support; retail-store adds product‑category index and backfill migration.
  • Documentation

    • Streamlined reviewer workflow to a single durable code‑review artifact, multitasking guidance for Cursor IDE, tightened anti‑patterns and reviewer/implementer responsibilities.
  • Tests

    • Expanded unit and E2E coverage for multi‑space flows, per‑space markers, projection/pruning, and rehydration guardrails.
  • Chores

    • Added rule banning transient project IDs and regenerated example contracts/fixtures.

Review Change Stack

@wmadden
wmadden requested a review from a team as a code owner May 12, 2026 18:47
@coderabbitai

coderabbitai Bot commented May 12, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Centralizes reviewer output to a single per-round artifact (projects/{project}/reviews/code-review.md), adds a transient-ID detection rule, and implements MongoDB contract-space multi-space migrations: space-keyed markers, per-space schema projection/verification, a multi-space runner, type/docs/tooling changes, and many tests and example updates.

Changes

Agent skills & iteration contract

Layer / File(s) Summary
Single-artifact orchestration contract & loop
.agents/skills/drive-orchestrate-plan/SKILL.md
Bumped version to 2026.5.13. Rewrote loop to require a single per-round durable artifact projects/{project}/reviews/code-review.md; removed per-round system-design-review.md/walkthrough.md refresh; added Multitask (Cursor IDE) rules; removed post-SATISFIED narrative-refresh step.
Implementer discipline & templates
.agents/skills/drive-orchestrate-plan/agents/implementer.md, .agents/skills/drive-orchestrate-plan/templates/delegate-implement.md
Mandated selective per-iteration validation (typecheck, tests for changed paths, lint), single end-of-round full validation gate with targeted reruns, added required diff-scan to prevent transient project IDs, and generalized read-only constraint forbidding edits under projects/{project}/reviews/.
Reviewer contract, heartbeat, templates
.agents/skills/drive-orchestrate-plan/agents/reviewer.md, .agents/skills/drive-orchestrate-plan/templates/delegate-review.md
Made reviewer verdict-first; durable writes limited to projects/{project}/reviews/code-review.md and wip/heartbeats/reviewer.txt; tightened SATISFIED acceptance (all severities block); simplified return shape to list only code-review.md; updated heartbeat cadence/payload guidance.
Rule: no transient project IDs
.agents/rules/no-transient-project-ids-in-code.mdc
New rule forbidding transient plan/project IDs in source/comments/tests/fixtures and providing a pre-commit git diff --cached grep quick-check.

Contract-space & migration multi-space

Layer / File(s) Summary
Contract-space types, ADRs, docs
docs/architecture/docs/adrs/ADR 212 - Contract spaces.md, docs/architecture/docs/subsystems/6. Ecosystem Extensions & Packs.md, docs/architecture/docs/subsystems/7. Migration System.md, packages/1-framework/1-core/framework-components/src/control/control-migration-types.ts
Introduced/used shared ContractSpace<TContract> and ContractSpaceHeadRef types; renamed helper to emitContractSpaceArtefacts; documented family-specific atomicity semantics (SQL all-or-nothing vs Mongo per-space marker atomicity) in JSDoc and ADRs.
Storage element extraction & disjointness
packages/1-framework/3-tooling/migration/src/aggregate/extract-storage-element-names.ts, packages/1-framework/3-tooling/migration/src/aggregate/loader.ts, tests
Added extractStorageElementNames() and switched loader disjointness checks to element-name semantics (tables/collections unified); updated conflict reporting and removed old helper.
Project schema projection (per-space pruning)
packages/1-framework/3-tooling/migration/src/aggregate/project-schema-to-space.ts, tests
Expanded projectSchemaToSpace to prune SQL tables and Mongo collections (array- or record-shaped) using extractStorageElementNames; added helpers collectOwnedNames, pruneRecord, pruneCollectionsArray and unit tests for Mongo-shaped schemas.
Contract-space seeding tests
packages/1-framework/3-tooling/cli/test/utils/contract-space-seed-phase.mongo.test.ts
New Vitest tests validating Mongo-shaped contract seeding, deterministic storage hashing, on-disk artifact round-trip, and idempotent seed behavior.

Mongo marker/runner/adapter/family

Layer / File(s) Summary
Marker ledger: space-partitioned API & semantics
packages/3-mongo-target/1-mongo-target/src/core/marker-ledger.ts, packages/3-mongo-target/1-mongo-target/test/marker-ledger.test.ts, packages/3-mongo-target/1-mongo-target/src/exports/control.ts
Partitioned markers by space (documents keyed _id: <space> and include space); added readMarker(db, space), readAllMarkers(db), initMarker(db, space, ...), updateMarker(db, space, ...), writeLedgerEntry(db, space, ...); implemented server-side invariant merge semantics and updated tests for per-space isolation and ledger behavior.
Mongo runner: per-space execution and projection hook
packages/3-mongo-target/1-mongo-target/src/core/mongo-runner.ts, packages/3-mongo-target/2-mongo-adapter/src/core/runner-deps.ts
Runner computes space = plan.spaceId ?? APP_SPACE_ID, threads space into marker/ledger calls, and added optional projectSchema callback to transform introspected schema before verification; adapter bindings updated to forward space.
Mongo family: multi-space execution & descriptor checks
packages/2-mongo-family/9-family/src/core/control-types.ts, packages/2-mongo-family/9-family/src/core/control-instance.ts, packages/2-mongo-family/9-family/src/core/mongo-target-descriptor.ts, packages/2-mongo-family/9-family/src/exports/control.ts, tests, vitest.config.ts, package.json
Added exported MongoControlExtensionDescriptor with optional contractSpace; createMongoFamilyInstance validates extension headRef.hash self-consistency; verify/sign use APP-space-scoped marker ops; replaced single-space executeAcrossSpaces shim with full multi-space iteration that projects per-space schema, runs each per-space runner, returns failingSpace on first failure, or aggregates perSpaceResults; added descriptor self-consistency tests and package test wiring.
Exports & adapter wiring
packages/3-mongo-target/1-mongo-target/src/exports/control.ts, packages/3-mongo-target/2-mongo-adapter/src/core/runner-deps.ts
Re-exported readAllMarkers and MongoMigrationRunnerExecuteOptions; adapter wrappers changed to require explicit space parameter and forward it into target-mongo control calls.

Integration tests, examples, and artifacts

Layer / File(s) Summary
Aggregate & multi-space integration tests
test/integration/test/mongo/*, test/integration/test/contract-space-fixture-mongo/*, packages/3-mongo-target/2-mongo-adapter/test/*, packages/1-framework/3-tooling/migration/test/*
Added broad integration and unit tests exercising multi-space planning/execution/verify/resume semantics: per-space ordering, failure isolation with failingSpace, resume-and-skip-if-at-head, codec-free rehydration guardrail, readAllMarkers coverage, disjointness violations, and explicit 'app' marker assertions.
Retail-store example: regenerated contracts & migrations
examples/retail-store/migrations/app/*, examples/retail-store/src/contract.*, examples/retail-store/src/seed.ts, examples/retail-store/test/*, examples/retail-store/app/products/[id]/page.tsx
Regenerated retail-store contracts and migrations: removed/added migration artifacts (including a new product-category compound-index migration and a backfill-product-status migration that refreshes validator + backfills data), updated generated JSON/TS contract files and types, and adapted example code/tests/seed data to use primaryCategory instead of masterCategory. Some older migration files were removed.
Migration ops/ops.json changes
examples/retail-store/migrations/app/**/ops.json, *.migration.ts
Updated or added migration ops and migration scripts for new/changed migrations (index creation, validator refresh, data backfill); removed some prior ops files for deleted migrations.
Test fixtures & helpers
test/integration/test/contract-space-fixture-mongo/*, test/integration/test/mongo/*
New contract-space fixture for Mongo used in multiple integration tests, constants, control descriptor, baseline migration, and end-to-end aggregate tests validating per-space semantics.

Sequence Diagram

sequenceDiagram
    participant Orch as Orchestrator
    participant Runner as MongoRunner
    participant Marker as MarkerOps
    participant DB as MongoDB

    Orch->>Runner: executeAcrossSpaces([app, ext])

    rect rgba(100, 150, 200, 0.5)
    note right of Runner: App space iteration
    Runner->>Runner: space = 'app'
    Runner->>Runner: projectSchemaToSpace(schema, 'app')
    Runner->>DB: apply per-space ops
    Runner->>Marker: readMarker(db, 'app')
    Marker->>DB: query _id:'app'
    DB-->>Marker: doc
    Marker-->>Runner: marker
    Runner->>Marker: updateMarker(db, 'app', ...)
    Marker->>DB: CAS update on _id:'app'
    DB-->>Marker: ok
    Marker-->>Runner: success
    end

    rect rgba(150, 100, 200, 0.5)
    note right of Runner: Extension space iteration
    Runner->>Runner: space = 'cipherstash'
    Runner->>Runner: projectSchemaToSpace(schema, 'cipherstash')
    Runner->>DB: apply per-space ops
    Runner->>Marker: readMarker(db, 'cipherstash')
    Marker->>DB: query _id:'cipherstash'
    DB-->>Marker: doc/null
    Marker-->>Runner: marker
    Runner->>Marker: updateMarker(db, 'cipherstash', ...)
    Marker->>DB: CAS update on _id:'cipherstash'
    DB-->>Marker: ok
    Marker-->>Runner: success
    end

    Runner-->>Orch: ok(perSpaceResults)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

"I nibble diffs and plant small marks,
One rabbit, many migration arcs,
Space-keyed markers, tidy and bright,
Skip what's done, resume what's right.
Hops of hashes, tests that gleam — code, run! 🐇"

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch tml-2408-port-contract-spaces-to-the-mongo-family

@pkg-pr-new

pkg-pr-new Bot commented May 12, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/mongo-runtime

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-runtime@494

@prisma-next/family-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/family-mongo@494

@prisma-next/sql-runtime

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-runtime@494

@prisma-next/family-sql

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/family-sql@494

@prisma-next/extension-arktype-json

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-arktype-json@494

@prisma-next/extension-cipherstash

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-cipherstash@494

@prisma-next/middleware-telemetry

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/middleware-telemetry@494

@prisma-next/mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo@494

@prisma-next/extension-paradedb

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-paradedb@494

@prisma-next/extension-pgvector

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-pgvector@494

@prisma-next/extension-postgis

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-postgis@494

@prisma-next/postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/postgres@494

@prisma-next/sql-orm-client

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-orm-client@494

@prisma-next/sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sqlite@494

@prisma-next/target-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/target-mongo@494

@prisma-next/adapter-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/adapter-mongo@494

@prisma-next/driver-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/driver-mongo@494

@prisma-next/contract

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/contract@494

@prisma-next/utils

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/utils@494

@prisma-next/config

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/config@494

@prisma-next/errors

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/errors@494

@prisma-next/framework-components

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/framework-components@494

@prisma-next/operations

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/operations@494

@prisma-next/ts-render

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/ts-render@494

@prisma-next/contract-authoring

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/contract-authoring@494

@prisma-next/ids

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/ids@494

@prisma-next/psl-parser

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/psl-parser@494

@prisma-next/psl-printer

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/psl-printer@494

@prisma-next/cli

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/cli@494

@prisma-next/emitter

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/emitter@494

@prisma-next/migration-tools

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/migration-tools@494

prisma-next

npm i https://pkg.pr.new/prisma/prisma-next@494

@prisma-next/vite-plugin-contract-emit

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/vite-plugin-contract-emit@494

@prisma-next/mongo-codec

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-codec@494

@prisma-next/mongo-contract

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-contract@494

@prisma-next/mongo-value

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-value@494

@prisma-next/mongo-contract-psl

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-contract-psl@494

@prisma-next/mongo-contract-ts

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-contract-ts@494

@prisma-next/mongo-emitter

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-emitter@494

@prisma-next/mongo-schema-ir

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-schema-ir@494

@prisma-next/mongo-query-ast

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-query-ast@494

@prisma-next/mongo-orm

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-orm@494

@prisma-next/mongo-query-builder

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-query-builder@494

@prisma-next/mongo-lowering

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-lowering@494

@prisma-next/mongo-wire

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-wire@494

@prisma-next/sql-contract

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract@494

@prisma-next/sql-errors

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-errors@494

@prisma-next/sql-operations

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-operations@494

@prisma-next/sql-schema-ir

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-schema-ir@494

@prisma-next/sql-contract-psl

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract-psl@494

@prisma-next/sql-contract-ts

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract-ts@494

@prisma-next/sql-contract-emitter

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract-emitter@494

@prisma-next/sql-lane-query-builder

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-lane-query-builder@494

@prisma-next/sql-relational-core

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-relational-core@494

@prisma-next/sql-builder

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-builder@494

@prisma-next/target-postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/target-postgres@494

@prisma-next/target-sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/target-sqlite@494

@prisma-next/adapter-postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/adapter-postgres@494

@prisma-next/adapter-sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/adapter-sqlite@494

@prisma-next/driver-postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/driver-postgres@494

@prisma-next/driver-sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/driver-sqlite@494

commit: cbae5b0

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
packages/2-mongo-family/9-family/src/core/control-instance.ts (1)

148-174: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

schemaVerify() is still contract-space blind.

This path always verifies against the full introspected schema. After a multi-space apply, any direct verify of a non-app space has to drop to strict: false to suppress sibling collections, so strict extension-space verification is still unavailable outside executeAcrossSpaces. Please thread a space/projection through this API, or route callers through the aggregate verifier instead.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/2-mongo-family/9-family/src/core/control-instance.ts` around lines
148 - 174, schemaVerify currently always verifies against the full introspected
schema, which breaks strict/extension-space checks for non-app spaces; update
schemaVerify(options) to accept an optional space (or projection) and apply that
projection to the introspected IR before calling verifyMongoSchema, or
alternatively route callers to the aggregate verifier used by
executeAcrossSpaces. Concretely: add an optional space?: string (or projection)
field to the schemaVerify options, after const liveIR = await
introspectSchema(db) compute a projectedIR by filtering/mapping liveIR to only
include collections/entities in the requested space, then pass projectedIR (not
liveIR) into verifyMongoSchema; keep existing behavior when space is undefined
by passing the full liveIR, and ensure callers that need multi-space aggregation
use the executeAcrossSpaces/aggregate verifier path instead.
packages/3-mongo-target/1-mongo-target/src/core/mongo-runner.ts (1)

241-295: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Multi-space apply still leaks partial progress.

execute() persists the marker and ledger as soon as one space verifies. When executeAcrossSpaces() composes these executions sequentially, a later failure leaves earlier spaces committed — which is exactly the resume path the new tests lock in. That breaks the all-or-nothing contract-space apply semantics described in ADR 212 and makes partial advancement part of the observable API. Either defer marker/ledger writes until the aggregate completes, or give Mongo an explicit weaker contract instead of silently diverging.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/3-mongo-target/1-mongo-target/src/core/mongo-runner.ts` around lines
241 - 295, The per-space execute() is writing markers and ledger entries
immediately (see markerOps.updateMarker, markerOps.initMarker and
markerOps.writeLedgerEntry in mongo-runner.ts), which leaks partial progress for
multi-space aggregates; change the implementation so marker/ledger writes are
deferred when called from executeAcrossSpaces(): add an option/flag (e.g.,
deferMarkerWrites or commitMarkers) to execute()/verify flow and, when true,
skip calling markerOps.updateMarker/initMarker/writeLedgerEntry and instead
return the intended marker/ledger payloads to the caller; then modify
executeAcrossSpaces() to collect those payloads across all spaces and only call
markerOps.* once the entire aggregate succeeds (or perform a CAS-style commit
for all), preserving the existing immediate-write behavior when
deferMarkerWrites is false so single-space callers are unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.agents/skills/drive-orchestrate-plan/agents/reviewer.md:
- Around line 7-9: Update the top-level role description to match the Heartbeats
section by making the writable files consistent: either add
wip/heartbeats/reviewer.txt to the list of writable files alongside
reviews/code-review.md in the opening description, or remove the heartbeat write
requirement from the Heartbeats section; ensure the terms "only file it writes"
and the Heartbeats requirement reference the same set of writable artifacts
(check the header block and the Heartbeats paragraph in reviewer.md) and keep
the wording verdict-first, terse, single-artifact if you choose to retain the
original intent.
- Around line 210-213: Update the "Files modified" requirement in reviewer.md to
resolve the contradiction: change the rule that currently mandates listing only
`code-review.md` to explicitly exempt operational heartbeat files like
`wip/heartbeats/reviewer.txt` or alter the rule to require two categories
(durable writes and operational writes) so both `code-review.md` and heartbeat
files can be reported separately; ensure you update the wording around "Files
modified" and the `## Round notes` guidance so it references the new exemption
or the two-list format and include the exact filenames `code-review.md` and
`wip/heartbeats/reviewer.txt` in the new text for clarity.

In `@docs/architecture` docs/adrs/ADR 212 - Contract spaces.md:
- Around line 214-215: Update the documentation text to reference the canonical
package export path '@prisma-next/migration-tools/spaces' instead of the
non-canonical '@prisma-next/migration-tools/exports/spaces'; keep the listed
producer-side helper names (planAllSpaces, concatenateSpaceApplyInputs,
verifyContractSpaces, emitContractSpaceArtefacts, gatherDiskContractSpaceState,
detectSpaceContractDrift) intact and just change the package path so readers
import the helpers from the correct shared-plane package name.

In
`@packages/1-framework/3-tooling/cli/test/utils/contract-space-seed-phase.mongo.test.ts`:
- Around line 13-38: Remove all transient planning artefact identifiers from the
file header comment (the tokens "T4.1", "T4.2", "T4.3", "TC-12", "TC-13", and
"AC6") and replace them with plain-language descriptions of the test assertions:
state that the seed phase for a Mongo-shaped contract should produce the three
on-disk artefacts, that the read helpers (readContractSpaceContract,
readContractSpaceHeadRef, listContractSpaceDirectories) round-trip the written
values, and that re-running the seed phase with no contract changes yields
byte-identical artefacts; keep the rest of the contextual explanation about
Mongo-shaped input and canonicalisation unchanged.

In `@packages/1-framework/3-tooling/migration/src/aggregate/loader.ts`:
- Around line 340-345: The loop that records claimers pushes the same
member.spaceId multiple times if extractStorageElementNames(member.contract)
returns duplicate names; update the logic in the block using
extractStorageElementNames and elementClaimedBy so you first deduplicate the
extracted element names (e.g., convert elements to a Set or otherwise remove
duplicates) before iterating and adding member.spaceId, thereby preventing false
self-collisions in disjointnessViolation; apply the same deduplication change to
the analogous block handling lines 380-391.

In `@packages/2-mongo-family/9-family/src/core/mongo-target-descriptor.ts`:
- Around line 102-104: The inline comment in mongo-target-descriptor.ts
references a transient project artifact path
`projects/contract-spaces-mongo-port/spec.md`; remove that projects/...
reference and replace it with a durable doc link or package README (for example
point only to the existing durable doc `docs/architecture/.../10. MongoDB
Family.md` or an ADR/package README). Update the comment in
mongo-target-descriptor.ts (the comment block that currently mentions
`projects/contract-spaces-mongo-port/spec.md`) so it no longer references
transient project artifacts, keeping any remaining explanatory text but linking
exclusively to durable documentation.

In `@packages/3-mongo-target/1-mongo-target/src/core/marker-ledger.ts`:
- Around line 41-45: The comment in marker-ledger.ts that documents canonical
post-port shape references a transient milestone ID "T1.2"; remove that artifact
and replace it with a neutral description of the upgrade step (e.g., "see
readMarker's caller-side upgrade pass") so durable source comments do not
include milestone/task IDs—locate the comment near the readMarker reference and
update the text accordingly.

In `@test/integration/test/mongo/codec-rehydration-guardrail.test.ts`:
- Around line 26-49: The block comment for TC-18 (the "codec-rehydration
guardrail" test) contains transient milestone/acceptance codes ("NFR5 / AC11");
remove those references and rewrite the comment to describe the constraint
directly (e.g., explain the intent that rehydrated ops must carry all
codec-related bytes so apply-time never requires codec runtime lookup), keeping
the rest of the explanation about serializeMongoOps, re-parsing JSON, and
running against MongoFamilyInstance unchanged; ensure the revised comment
mentions the observable behavior (what the test verifies) rather than project
artifact codes.

---

Outside diff comments:
In `@packages/2-mongo-family/9-family/src/core/control-instance.ts`:
- Around line 148-174: schemaVerify currently always verifies against the full
introspected schema, which breaks strict/extension-space checks for non-app
spaces; update schemaVerify(options) to accept an optional space (or projection)
and apply that projection to the introspected IR before calling
verifyMongoSchema, or alternatively route callers to the aggregate verifier used
by executeAcrossSpaces. Concretely: add an optional space?: string (or
projection) field to the schemaVerify options, after const liveIR = await
introspectSchema(db) compute a projectedIR by filtering/mapping liveIR to only
include collections/entities in the requested space, then pass projectedIR (not
liveIR) into verifyMongoSchema; keep existing behavior when space is undefined
by passing the full liveIR, and ensure callers that need multi-space aggregation
use the executeAcrossSpaces/aggregate verifier path instead.

In `@packages/3-mongo-target/1-mongo-target/src/core/mongo-runner.ts`:
- Around line 241-295: The per-space execute() is writing markers and ledger
entries immediately (see markerOps.updateMarker, markerOps.initMarker and
markerOps.writeLedgerEntry in mongo-runner.ts), which leaks partial progress for
multi-space aggregates; change the implementation so marker/ledger writes are
deferred when called from executeAcrossSpaces(): add an option/flag (e.g.,
deferMarkerWrites or commitMarkers) to execute()/verify flow and, when true,
skip calling markerOps.updateMarker/initMarker/writeLedgerEntry and instead
return the intended marker/ledger payloads to the caller; then modify
executeAcrossSpaces() to collect those payloads across all spaces and only call
markerOps.* once the entire aggregate succeeds (or perform a CAS-style commit
for all), preserving the existing immediate-write behavior when
deferMarkerWrites is false so single-space callers are unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 932eb652-a48d-4d59-8cea-2b101d40ccc0

📥 Commits

Reviewing files that changed from the base of the PR and between 2c26553 and 68ae172.

⛔ Files ignored due to path filters (3)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • projects/contract-spaces-mongo-port/plan.md is excluded by !projects/**
  • projects/contract-spaces-mongo-port/spec.md is excluded by !projects/**
📒 Files selected for processing (43)
  • .agents/skills/drive-orchestrate-plan/SKILL.md
  • .agents/skills/drive-orchestrate-plan/agents/implementer.md
  • .agents/skills/drive-orchestrate-plan/agents/reviewer.md
  • .agents/skills/drive-orchestrate-plan/templates/delegate-implement.md
  • .agents/skills/drive-orchestrate-plan/templates/delegate-review.md
  • docs/architecture docs/adrs/ADR 212 - Contract spaces.md
  • docs/architecture docs/subsystems/10. MongoDB Family.md
  • docs/architecture docs/subsystems/6. Ecosystem Extensions & Packs.md
  • docs/architecture docs/subsystems/7. Migration System.md
  • packages/1-framework/1-core/framework-components/src/control/control-migration-types.ts
  • packages/1-framework/3-tooling/cli/test/utils/contract-space-seed-phase.mongo.test.ts
  • packages/1-framework/3-tooling/migration/src/aggregate/loader.ts
  • packages/1-framework/3-tooling/migration/src/aggregate/project-schema-to-space.ts
  • packages/1-framework/3-tooling/migration/test/aggregate/loader.test.ts
  • packages/1-framework/3-tooling/migration/test/aggregate/project-schema-to-space.test.ts
  • packages/2-mongo-family/9-family/package.json
  • packages/2-mongo-family/9-family/src/core/control-instance.ts
  • packages/2-mongo-family/9-family/src/core/control-types.ts
  • packages/2-mongo-family/9-family/src/core/mongo-target-descriptor.ts
  • packages/2-mongo-family/9-family/src/exports/control.ts
  • packages/2-mongo-family/9-family/test/control-instance.descriptor-self-consistency.test.ts
  • packages/2-mongo-family/9-family/vitest.config.ts
  • packages/3-mongo-target/1-mongo-target/src/core/marker-ledger.ts
  • packages/3-mongo-target/1-mongo-target/src/core/mongo-runner.ts
  • packages/3-mongo-target/1-mongo-target/src/exports/control.ts
  • packages/3-mongo-target/1-mongo-target/test/marker-ledger.test.ts
  • packages/3-mongo-target/2-mongo-adapter/src/core/runner-deps.ts
  • packages/3-mongo-target/2-mongo-adapter/test/mongo-runner.schema-verify.integration.test.ts
  • packages/3-mongo-target/2-mongo-adapter/test/mongo-runner.test.ts
  • test/integration/test/cli.mongo-db-sign.e2e.test.ts
  • test/integration/test/cli.mongo-db-verify.e2e.test.ts
  • test/integration/test/contract-space-fixture-mongo/README.md
  • test/integration/test/contract-space-fixture-mongo/constants.ts
  • test/integration/test/contract-space-fixture-mongo/contract.ts
  • test/integration/test/contract-space-fixture-mongo/control.ts
  • test/integration/test/contract-space-fixture-mongo/descriptor.test.ts
  • test/integration/test/contract-space-fixture-mongo/migrations.ts
  • test/integration/test/mongo/aggregate-e2e.test.ts
  • test/integration/test/mongo/codec-rehydration-guardrail.test.ts
  • test/integration/test/mongo/db-verify-sign.test.ts
  • test/integration/test/mongo/family-read-marker-per-space.test.ts
  • test/integration/test/mongo/migration-e2e.test.ts
  • test/integration/test/mongo/multi-space-runner.test.ts

@wmadden
wmadden force-pushed the tml-2408-port-contract-spaces-to-the-mongo-family branch from 68ae172 to 65f5fff Compare May 12, 2026 20:04

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (3)
.agents/skills/drive-orchestrate-plan/agents/reviewer.md (2)

210-211: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

“Files modified” rule still conflicts with mandatory heartbeat writes.

The return shape mandates listing only code-review.md, while the protocol requires writing wip/heartbeats/reviewer.txt. Please explicitly exclude heartbeat files from this list (or split durable vs operational writes) to avoid an impossible reporting rule.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.agents/skills/drive-orchestrate-plan/agents/reviewer.md around lines 210 -
211, Update the rule text that requires listing "code-review.md" so it
explicitly excludes ephemeral heartbeat files (e.g.,
"wip/heartbeats/reviewer.txt") or split the return into two lists (durable files
and operational/heartbeat files); locate the rule wording around the "Files
modified" bullet in reviewer.md and change it to either: "must list
code-review.md (and only durable files; exclude wip/heartbeats/*)" or add a
separate "Operational writes" section that allows heartbeat entries, ensuring
the rule no longer forces an impossible single-list return that would include
heartbeat files.

7-8: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Writable-file contract is internally inconsistent.

Line 7-Line 8 says the agent writes only reviews/code-review.md, but Line 15 also requires heartbeat writes to wip/heartbeats/reviewer.txt. Please make the opening constraint explicitly match the heartbeat exception so the protocol is not self-contradictory.

Also applies to: 15-15

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.agents/skills/drive-orchestrate-plan/agents/reviewer.md around lines 7 - 8,
Update the writable-file contract in
.agents/skills/drive-orchestrate-plan/agents/reviewer.md so the opening
constraint explicitly permits the heartbeat exception: change the sentence that
currently states the agent writes only `reviews/code-review.md` to state it
writes only `reviews/code-review.md` (and, as an exception, heartbeat files
under `wip/heartbeats/`, e.g. `wip/heartbeats/reviewer.txt`); ensure the same
clarification appears where the contract is referenced near the line that
mentions `wip/heartbeats/reviewer.txt` so the two statements are consistent.
packages/1-framework/3-tooling/cli/test/utils/contract-space-seed-phase.mongo.test.ts (1)

13-38: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Remove transient planning IDs from the file header comment.

Line 14 and Line 32-37 still include milestone/task/AC tokens (T4.*, TC-*, AC6). Please replace them with plain-language test intent.

As per coding guidelines, "Source-code comments must not reference transient project artifacts including ... milestone-task IDs ... [and] milestone-named acceptance criteria."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@packages/1-framework/3-tooling/cli/test/utils/contract-space-seed-phase.mongo.test.ts`
around lines 13 - 38, Remove the transient planning IDs from the file header
comment: delete tokens like "T4.*", "TC-*", and "AC6" and replace them with
plain-language descriptions of the test intent (e.g., describe that the file
verifies the Mongo-shaped contract is accepted, artifact generation,
read/round-trip helpers, and idempotent re-seeding) so the top comment in this
test file is free of milestone/task/acceptance IDs; update the sentences that
currently read "T4.1 (TC-12): ...", "T4.2: ...", and "T4.3 (TC-13 / AC6): ..."
to equivalent human-readable intent statements within the same header comment
block.
🧹 Nitpick comments (2)
packages/1-framework/3-tooling/cli/test/utils/contract-space-seed-phase.mongo.test.ts (1)

117-118: ⚡ Quick win

Prefer direct assertions over defensive/optional access in test invariants.

Since these values are expected to exist after setup, avoid if (!record) throw ... and ?. access; assert presence, then use non-null access for clearer failures.

Suggested cleanup
-    const [record] = out.seeded;
-    if (!record) throw new Error('unreachable');
+    const record = out.seeded[0]!;
@@
-    expect(headRef?.hash).toBe(headHash);
-    expect(headRef?.invariants).toEqual(['inv:a', 'inv:b']);
+    expect(headRef).toBeDefined();
+    expect(headRef!.hash).toBe(headHash);
+    expect(headRef!.invariants).toEqual(['inv:a', 'inv:b']);
@@
-    expect(second.seeded[0]?.action).toBe('unchanged');
+    expect(second.seeded[0]!.action).toBe('unchanged');

As per coding guidelines, "Prefer assertions over defensive checks when data is guaranteed to be valid ... Remove optional chaining ... for properties that are guaranteed to exist."

Also applies to: 146-147, 176-176

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@packages/1-framework/3-tooling/cli/test/utils/contract-space-seed-phase.mongo.test.ts`
around lines 117 - 118, Replace defensive runtime checks with direct test
assertions: instead of guarding extraction with "if (!record) throw ..." and
using optional chaining on guaranteed values (e.g., the destructured const
[record] = out.seeded and subsequent property access), assert presence using the
test assertion utility (e.g., expect(record).toBeDefined() or equivalent) and
then access properties directly (remove ?.). Apply the same change for the other
occurrences mentioned (the checks around lines handling out.seeded at the second
and third locations), updating the tests that reference record and other
guaranteed values to assert existence first and then use non-null property
access.
packages/3-mongo-target/1-mongo-target/test/marker-ledger.test.ts (1)

575-590: 💤 Low value

Test is misplaced in the readAllMarkers describe block.

This test exercises readMarker(db, 'marker') behavior, not readAllMarkers. The test logic is correct (verifying that a legacy doc without space field is not interpreted as the marker for a space named 'marker'), but it belongs in the readMarker describe block or the legacy upgrade suite for clarity.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/3-mongo-target/1-mongo-target/test/marker-ledger.test.ts` around
lines 575 - 590, The test titled "a non-app `readMarker(space)` for a space id
colliding with the legacy `_id: \"marker\"` returns null..." is in the
`readAllMarkers` describe block but exercises `readMarker(db, 'marker')`; move
this it(...) block out of the `readAllMarkers` describe and into the
`readMarker` describe (or the legacy upgrade suite) so the test context matches
the exercised function (`readMarker`) and keep the existing assertion logic
unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@packages/1-framework/3-tooling/migration/src/aggregate/project-schema-to-space.ts`:
- Around line 57-67: The checks that branch to pruneRecord for
tables/collections use typeof === 'object' which also matches arrays, so update
the conditions in project-schema-to-space.ts to exclude arrays (e.g. change
"typeof schemaObj.tables === 'object' && schemaObj.tables !== null" to also
require "!Array.isArray(schemaObj.tables)"); do the same for the collections
record branch and the analogous block around lines 88-95. This preserves the
fallback behavior by ensuring arrays hit the Array.isArray branches
(pruneCollectionsArray) or fall through unchanged instead of being treated as
records by pruneRecord.

---

Duplicate comments:
In @.agents/skills/drive-orchestrate-plan/agents/reviewer.md:
- Around line 210-211: Update the rule text that requires listing
"code-review.md" so it explicitly excludes ephemeral heartbeat files (e.g.,
"wip/heartbeats/reviewer.txt") or split the return into two lists (durable files
and operational/heartbeat files); locate the rule wording around the "Files
modified" bullet in reviewer.md and change it to either: "must list
code-review.md (and only durable files; exclude wip/heartbeats/*)" or add a
separate "Operational writes" section that allows heartbeat entries, ensuring
the rule no longer forces an impossible single-list return that would include
heartbeat files.
- Around line 7-8: Update the writable-file contract in
.agents/skills/drive-orchestrate-plan/agents/reviewer.md so the opening
constraint explicitly permits the heartbeat exception: change the sentence that
currently states the agent writes only `reviews/code-review.md` to state it
writes only `reviews/code-review.md` (and, as an exception, heartbeat files
under `wip/heartbeats/`, e.g. `wip/heartbeats/reviewer.txt`); ensure the same
clarification appears where the contract is referenced near the line that
mentions `wip/heartbeats/reviewer.txt` so the two statements are consistent.

In
`@packages/1-framework/3-tooling/cli/test/utils/contract-space-seed-phase.mongo.test.ts`:
- Around line 13-38: Remove the transient planning IDs from the file header
comment: delete tokens like "T4.*", "TC-*", and "AC6" and replace them with
plain-language descriptions of the test intent (e.g., describe that the file
verifies the Mongo-shaped contract is accepted, artifact generation,
read/round-trip helpers, and idempotent re-seeding) so the top comment in this
test file is free of milestone/task/acceptance IDs; update the sentences that
currently read "T4.1 (TC-12): ...", "T4.2: ...", and "T4.3 (TC-13 / AC6): ..."
to equivalent human-readable intent statements within the same header comment
block.

---

Nitpick comments:
In
`@packages/1-framework/3-tooling/cli/test/utils/contract-space-seed-phase.mongo.test.ts`:
- Around line 117-118: Replace defensive runtime checks with direct test
assertions: instead of guarding extraction with "if (!record) throw ..." and
using optional chaining on guaranteed values (e.g., the destructured const
[record] = out.seeded and subsequent property access), assert presence using the
test assertion utility (e.g., expect(record).toBeDefined() or equivalent) and
then access properties directly (remove ?.). Apply the same change for the other
occurrences mentioned (the checks around lines handling out.seeded at the second
and third locations), updating the tests that reference record and other
guaranteed values to assert existence first and then use non-null property
access.

In `@packages/3-mongo-target/1-mongo-target/test/marker-ledger.test.ts`:
- Around line 575-590: The test titled "a non-app `readMarker(space)` for a
space id colliding with the legacy `_id: \"marker\"` returns null..." is in the
`readAllMarkers` describe block but exercises `readMarker(db, 'marker')`; move
this it(...) block out of the `readAllMarkers` describe and into the
`readMarker` describe (or the legacy upgrade suite) so the test context matches
the exercised function (`readMarker`) and keep the existing assertion logic
unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 269ad31d-acd4-4ba6-9e9a-a1f411b4a2ad

📥 Commits

Reviewing files that changed from the base of the PR and between 68ae172 and 65f5fff.

⛔ Files ignored due to path filters (2)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • projects/contract-spaces-mongo-port/plan.md is excluded by !projects/**
📒 Files selected for processing (29)
  • .agents/skills/drive-orchestrate-plan/SKILL.md
  • .agents/skills/drive-orchestrate-plan/agents/implementer.md
  • .agents/skills/drive-orchestrate-plan/agents/reviewer.md
  • .agents/skills/drive-orchestrate-plan/templates/delegate-implement.md
  • .agents/skills/drive-orchestrate-plan/templates/delegate-review.md
  • docs/architecture docs/adrs/ADR 212 - Contract spaces.md
  • docs/architecture docs/subsystems/10. MongoDB Family.md
  • docs/architecture docs/subsystems/6. Ecosystem Extensions & Packs.md
  • docs/architecture docs/subsystems/7. Migration System.md
  • packages/1-framework/1-core/framework-components/src/control/control-migration-types.ts
  • packages/1-framework/3-tooling/cli/test/utils/contract-space-seed-phase.mongo.test.ts
  • packages/1-framework/3-tooling/migration/src/aggregate/loader.ts
  • packages/1-framework/3-tooling/migration/src/aggregate/project-schema-to-space.ts
  • packages/1-framework/3-tooling/migration/test/aggregate/loader.test.ts
  • packages/1-framework/3-tooling/migration/test/aggregate/project-schema-to-space.test.ts
  • packages/2-mongo-family/9-family/package.json
  • packages/2-mongo-family/9-family/src/core/control-instance.ts
  • packages/2-mongo-family/9-family/src/core/control-types.ts
  • packages/2-mongo-family/9-family/src/core/mongo-target-descriptor.ts
  • packages/2-mongo-family/9-family/src/exports/control.ts
  • packages/2-mongo-family/9-family/test/control-instance.descriptor-self-consistency.test.ts
  • packages/2-mongo-family/9-family/vitest.config.ts
  • packages/3-mongo-target/1-mongo-target/src/core/marker-ledger.ts
  • packages/3-mongo-target/1-mongo-target/src/core/mongo-runner.ts
  • packages/3-mongo-target/1-mongo-target/src/exports/control.ts
  • packages/3-mongo-target/1-mongo-target/test/marker-ledger.test.ts
  • packages/3-mongo-target/2-mongo-adapter/src/core/runner-deps.ts
  • packages/3-mongo-target/2-mongo-adapter/test/mongo-runner.schema-verify.integration.test.ts
  • packages/3-mongo-target/2-mongo-adapter/test/mongo-runner.test.ts
✅ Files skipped from review due to trivial changes (6)
  • packages/2-mongo-family/9-family/package.json
  • packages/2-mongo-family/9-family/src/exports/control.ts
  • docs/architecture docs/subsystems/6. Ecosystem Extensions & Packs.md
  • .agents/skills/drive-orchestrate-plan/templates/delegate-implement.md
  • docs/architecture docs/subsystems/7. Migration System.md
  • packages/2-mongo-family/9-family/vitest.config.ts
🚧 Files skipped from review as they are similar to previous changes (15)
  • packages/3-mongo-target/1-mongo-target/src/exports/control.ts
  • packages/3-mongo-target/2-mongo-adapter/src/core/runner-deps.ts
  • .agents/skills/drive-orchestrate-plan/agents/implementer.md
  • packages/1-framework/3-tooling/migration/src/aggregate/loader.ts
  • packages/2-mongo-family/9-family/src/core/control-types.ts
  • packages/3-mongo-target/2-mongo-adapter/test/mongo-runner.schema-verify.integration.test.ts
  • packages/1-framework/3-tooling/migration/test/aggregate/project-schema-to-space.test.ts
  • packages/2-mongo-family/9-family/test/control-instance.descriptor-self-consistency.test.ts
  • packages/1-framework/3-tooling/migration/test/aggregate/loader.test.ts
  • .agents/skills/drive-orchestrate-plan/templates/delegate-review.md
  • packages/3-mongo-target/1-mongo-target/src/core/mongo-runner.ts
  • packages/2-mongo-family/9-family/src/core/mongo-target-descriptor.ts
  • .agents/skills/drive-orchestrate-plan/SKILL.md
  • docs/architecture docs/adrs/ADR 212 - Contract spaces.md
  • packages/3-mongo-target/1-mongo-target/src/core/marker-ledger.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@examples/retail-store/migrations/app/20260513T0508_backfill_product_status/migration.ts`:
- Around line 85-88: The current dataTransform call uses check: { source:
existingProductsWithoutStatus } which treats zero matching rows as a precheck
failure; change the check to a custom precheck function that queries
existingProductsWithoutStatus and returns success when the query yields zero
rows (so “nothing left to backfill” is treated as success) and otherwise returns
the list to process; specifically update the dataTransform invocation for
'backfill-product-status' to replace the simple check.source with a function or
check object that inspects existingProductsWithoutStatus and returns an
empty-result-success rather than failing, keeping backfillRun unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: abbbb79c-d53f-471a-8ea6-649e905fa16a

📥 Commits

Reviewing files that changed from the base of the PR and between effc3b1 and bf26ef4.

📒 Files selected for processing (21)
  • examples/retail-store/migrations/app/20260513T0505_initial/end-contract.d.ts
  • examples/retail-store/migrations/app/20260513T0505_initial/end-contract.json
  • examples/retail-store/migrations/app/20260513T0505_initial/migration.json
  • examples/retail-store/migrations/app/20260513T0505_initial/migration.ts
  • examples/retail-store/migrations/app/20260513T0505_initial/ops.json
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/end-contract.d.ts
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/end-contract.json
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/migration.json
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/migration.ts
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/ops.json
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/start-contract.d.ts
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/start-contract.json
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/end-contract.d.ts
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/end-contract.json
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/migration.json
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/migration.ts
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/ops.json
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/start-contract.d.ts
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/start-contract.json
  • examples/retail-store/test/manual-migration.test.ts
  • examples/retail-store/test/migration-chain.test.ts
✅ Files skipped from review due to trivial changes (11)
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/ops.json
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/migration.ts
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/migration.json
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/end-contract.d.ts
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/start-contract.json
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/end-contract.json
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/migration.json
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/start-contract.d.ts
  • examples/retail-store/migrations/app/20260513T0505_initial/end-contract.d.ts
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/end-contract.d.ts
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/start-contract.d.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • examples/retail-store/test/manual-migration.test.ts

wmadden added a commit that referenced this pull request May 13, 2026
…viewer to scan for them; document Cursor Multitask Mode

Three connected changes pulled into one commit because they describe one
policy: transient project planning IDs (T1.1, TC-7, AC4, P3 R2,
CKPT-2, etc.) must not leak into source code, comments, test names, or
hash fixtures, and the iteration loop must catch them at review time
rather than after merge.

1. New rule `.agents/rules/no-transient-project-ids-in-code.mdc`. A
   focused, always-applied companion to `doc-maintenance.mdc`. Names
   the specific token classes that are forbidden in code (task IDs,
   test-case IDs, AC/FR/NFR IDs, phase/round/checkpoint IDs,
   `projects/<x>/...` paths, prose attributions to the plan,
   ID-named hash fixtures), explains the failure mode (transient IDs
   rot silently — once the plan is renumbered or deleted at close-out,
   the comment is dangling), and lists the stable references that
   stay allowed (Linear ticket IDs, ADR numbers, durable docs paths).
   Includes a paste-ready scan command the implementer can run on
   their `+` diff before declaring a task done.

2. Reviewer protocol update in
   `.agents/skills/drive-orchestrate-plan/agents/reviewer.md`. Adds
   step 7 to the round workflow ("Scan for transient project IDs
   leaking into code") and a dedicated `## Transient ID scan` section
   with the procedure: extract the round plan IDs from `plan.md` and
   `spec.md`, scan the round `+` diff for them and the structural
   patterns that catch IDs missed in step 1, file every hit as a
   `must-fix` finding. Adds a zero-hits clause to the
   `SATISFIED` acceptance bar so the scan is enforced rather than
   advisory. Adds an anti-pattern entry naming the protocol breach
   (skipping the scan).

3. Implementer protocol update in
   `.agents/skills/drive-orchestrate-plan/agents/implementer.md`.
   Adds a `## No transient project IDs in code` section with the
   high-frequency leakage shapes (test names, JSDoc, hash fixtures,
   `projects/<this-project>/...` paths, prose attributions) and the
   self-scan command to run before declaring a task done. Clarifies
   that commit messages and PR descriptions are out-of-band of the
   source-tree ban — task IDs are useful there for traceability but
   forbidden inside source files.

4. Multitasking guidance in
   `.agents/skills/drive-orchestrate-plan/SKILL.md`. New `##
   Multitasking the loop (Cursor IDE)` section: when the user is in
   Multitask Mode, both implementer and reviewer round delegations
   set `run_in_background: true`, and the orchestrator uses the
   wait window for productive prep (pre-stage the next delegation
   prompt, prepare R<N+1> implementer scoping, drain unrelated user
   questions). Explicitly forbids polling the backgrounded subagent,
   forbids running two persistent subagents of the same role in
   parallel (the loop is sequential per role even when each call
   is backgrounded), and reaffirms heartbeats as the canonical
   "stuck?" signal — backgrounding makes them more important, not
   less. Wires the multitasking hook into loop steps 2 and 5 and
   adds a behavioural rule to the cross-cutting invariants list.

Refs: TML-2408
Refs: PR #494
Signed-off-by: Will Madden <[email protected]>
wmadden added a commit that referenced this pull request May 13, 2026
The Mongo family is being shipped with multi-space markers as part of
this PR; we have no production users on the prior single-doc shape, and
the no-backward-compat-shims rule says we should not pre-pay maintenance
for hypothetical legacy state.

Removes the LEGACY_MARKER_ID constant, the duplicate-key error code, the
upgrade/sweep helpers, the markerCollection type widener, and the entire
legacy-upgrade test describe block. readMarker collapses to a single
non-branching aggregate. readAllMarkers keeps the defensive `space`
filter as a guard against malformed/manually-inserted docs (now framed
as exactly that, not as legacy handling).

Surfaced by review feedback on PR #494.

Signed-off-by: Will Madden <[email protected]>
wmadden added a commit that referenced this pull request May 13, 2026
… docs

Two narrow corrections surfaced in PR #494 review:

- mongo-target-descriptor.ts had a comment block pointing at
  `projects/contract-spaces-mongo-port/spec.md`, which the no-transient-
  project-ids-in-code rule (the rule introduced in 7c915a2) explicitly
  forbids. Replaced with the durable equivalents: subsystem 10 (MongoDB
  Family § Contract spaces) and ADR 212.

- ADR 212 listed the producer-side helpers as imported from
  `@prisma-next/migration-tools/exports/spaces`. The codebase imports
  them from `@prisma-next/migration-tools/spaces` per the no-`/exports/`-
  in-imports convention; documenting the canonical name avoids leading
  readers to a non-canonical path.

Signed-off-by: Will Madden <[email protected]>
@wmadden

wmadden commented May 13, 2026

Copy link
Copy Markdown
Contributor Author

Triage of CodeRabbit's review-body items (the ones that don't have inline threads):

Will-address items posted as commits

  • reviewer.md writable-file contract internally inconsistent (review #4275826286 dupes A07-2 / A07-3): fixed in f9784c4. The frontmatter, body, and return-shape rule are aligned around two named surfaces: durable (code-review.md) and operational (wip/heartbeats/reviewer.txt). The Files modified rule now says "durable writes only", so the heartbeat doesn't have to appear there.
  • contract-space-seed-phase.mongo.test.ts defensive checks (review #4275826286 nitpick): fixed in b52a0d6. if (!record) throw 'unreachable' and the ?. patterns at lines 117-118, 146-147, and 176 are gone — replaced with non-null extraction + explicit expect(...).not.toBeNull() per the project's coding-conventions rule.

Already-resolved by deletion

  • marker-ledger.test.ts misplaced test in readAllMarkers describe block (review #4275826286 nitpick): superseded by 84863f3. The legacy upgrade path was removed wholesale, including this test — placement nit moot.

Not addressing in this PR

  • schemaVerify() is contract-space blind (review #4275290971 outside-diff). Per ADR 212 + subsystem 10, per-space strict verify is a property of executeAcrossSpaces. The single-contract schemaVerify is intentionally whole-DB. Threading an optional space / projection through that API is real new surface — worthwhile, but a focused refactor that should land as its own change rather than tacked onto this port. Happy to file a Linear follow-up if the team wants the feature.
  • Multi-space apply leaks partial progress (review #4275290971 outside-diff). By design. ADR 212 § "Apply-time atomicity and ordering" + subsystem 10 § "Contract spaces" explicitly document Mongo's atomicity model as resumable, per-space, marker-level — not transactional all-or-nothing. The "leak" CodeRabbit identifies is exactly the documented contract: failure on a later space leaves earlier-advanced markers in place, and rerun finds spaces 1..N−1 at-head (no-op skip) and retries N onward. The new tests in multi-space-runner.test.ts and aggregate-e2e.test.ts pin this property as a correctness requirement, not as a bug to fix. The transactional model would require session transactions across DDL ops, which Mongo does not support.
  • Backfill migration unresumable on rerun (review #4278589367 inline; replied on PRRT_kwDOQM0QJc6BpGQv). Verified incorrect: the runner's idempotency optimization (mongo-runner.ts:310-318) evaluates the postcheck before precheck/run and skips the operation when the postcheck is already satisfied. So the backfill is convergent on rerun under default CLI invocation. Full trace on the inline thread.

wmadden added a commit that referenced this pull request May 13, 2026
…viewer to scan for them; document Cursor Multitask Mode

Three connected changes pulled into one commit because they describe one
policy: transient project planning IDs (T1.1, TC-7, AC4, P3 R2,
CKPT-2, etc.) must not leak into source code, comments, test names, or
hash fixtures, and the iteration loop must catch them at review time
rather than after merge.

1. New rule `.agents/rules/no-transient-project-ids-in-code.mdc`. A
   focused, always-applied companion to `doc-maintenance.mdc`. Names
   the specific token classes that are forbidden in code (task IDs,
   test-case IDs, AC/FR/NFR IDs, phase/round/checkpoint IDs,
   `projects/<x>/...` paths, prose attributions to the plan,
   ID-named hash fixtures), explains the failure mode (transient IDs
   rot silently — once the plan is renumbered or deleted at close-out,
   the comment is dangling), and lists the stable references that
   stay allowed (Linear ticket IDs, ADR numbers, durable docs paths).
   Includes a paste-ready scan command the implementer can run on
   their `+` diff before declaring a task done.

2. Reviewer protocol update in
   `.agents/skills/drive-orchestrate-plan/agents/reviewer.md`. Adds
   step 7 to the round workflow ("Scan for transient project IDs
   leaking into code") and a dedicated `## Transient ID scan` section
   with the procedure: extract the round plan IDs from `plan.md` and
   `spec.md`, scan the round `+` diff for them and the structural
   patterns that catch IDs missed in step 1, file every hit as a
   `must-fix` finding. Adds a zero-hits clause to the
   `SATISFIED` acceptance bar so the scan is enforced rather than
   advisory. Adds an anti-pattern entry naming the protocol breach
   (skipping the scan).

3. Implementer protocol update in
   `.agents/skills/drive-orchestrate-plan/agents/implementer.md`.
   Adds a `## No transient project IDs in code` section with the
   high-frequency leakage shapes (test names, JSDoc, hash fixtures,
   `projects/<this-project>/...` paths, prose attributions) and the
   self-scan command to run before declaring a task done. Clarifies
   that commit messages and PR descriptions are out-of-band of the
   source-tree ban — task IDs are useful there for traceability but
   forbidden inside source files.

4. Multitasking guidance in
   `.agents/skills/drive-orchestrate-plan/SKILL.md`. New `##
   Multitasking the loop (Cursor IDE)` section: when the user is in
   Multitask Mode, both implementer and reviewer round delegations
   set `run_in_background: true`, and the orchestrator uses the
   wait window for productive prep (pre-stage the next delegation
   prompt, prepare R<N+1> implementer scoping, drain unrelated user
   questions). Explicitly forbids polling the backgrounded subagent,
   forbids running two persistent subagents of the same role in
   parallel (the loop is sequential per role even when each call
   is backgrounded), and reaffirms heartbeats as the canonical
   "stuck?" signal — backgrounding makes them more important, not
   less. Wires the multitasking hook into loop steps 2 and 5 and
   adds a behavioural rule to the cross-cutting invariants list.

Refs: TML-2408
Refs: PR #494
Signed-off-by: Will Madden <[email protected]>
wmadden added a commit that referenced this pull request May 13, 2026
The Mongo family is being shipped with multi-space markers as part of
this PR; we have no production users on the prior single-doc shape, and
the no-backward-compat-shims rule says we should not pre-pay maintenance
for hypothetical legacy state.

Removes the LEGACY_MARKER_ID constant, the duplicate-key error code, the
upgrade/sweep helpers, the markerCollection type widener, and the entire
legacy-upgrade test describe block. readMarker collapses to a single
non-branching aggregate. readAllMarkers keeps the defensive `space`
filter as a guard against malformed/manually-inserted docs (now framed
as exactly that, not as legacy handling).

Surfaced by review feedback on PR #494.

Signed-off-by: Will Madden <[email protected]>
wmadden added a commit that referenced this pull request May 13, 2026
… docs

Two narrow corrections surfaced in PR #494 review:

- mongo-target-descriptor.ts had a comment block pointing at
  `projects/contract-spaces-mongo-port/spec.md`, which the no-transient-
  project-ids-in-code rule (the rule introduced in 7c915a2) explicitly
  forbids. Replaced with the durable equivalents: subsystem 10 (MongoDB
  Family § Contract spaces) and ADR 212.

- ADR 212 listed the producer-side helpers as imported from
  `@prisma-next/migration-tools/exports/spaces`. The codebase imports
  them from `@prisma-next/migration-tools/spaces` per the no-`/exports/`-
  in-imports convention; documenting the canonical name avoids leading
  readers to a non-canonical path.

Signed-off-by: Will Madden <[email protected]>
@wmadden
wmadden force-pushed the tml-2408-port-contract-spaces-to-the-mongo-family branch from b52a0d6 to 79b3d26 Compare May 13, 2026 10:05
@wmadden

wmadden commented May 13, 2026

Copy link
Copy Markdown
Contributor Author

Returning to correct the framing of my earlier reply — it was incomplete and undersold what's actually planned.

The accurate framing: this isn't an option-A-vs-B trade-off the spaces port chose to defer. The framework lacks a typed primitive for storage topology — the structural backbone of "what named things does this contract claim?" independent of family — and that primitive is being introduced as interface Storage { readonly namespaces: Record<string, Namespace> } in TML-2459 (target-extensible-ir)'s M1 foundation. TML-2459's M2 R2 plan explicitly names this PR's extractStorageElementNames / projectSchemaToSpace duck-typed walks as consumers it will rebase onto and clean up:

framework projectSchemaToSpace / extractStorageElementNames generalisation to duck-type collections alongside tables

TML-2459 also lists TML-2408 as a strict-precedence prerequisite (so this PR lands first, with the duck-typed helper, and the IR class flip absorbs it). Landing an interim typed shape here would introduce a third on-disk shape — neither today's flat tables/collections nor TML-2459's namespaces: Record<string, Namespace> — that TML-2459 would then have to migrate away from a second time, violating its NFR1 ("no dual-shape transition window").

So: stopgap, known layering violation, deliberate sequencing. JSDoc updated to record this and point at TML-2459 so the next reader doesn't reach the same conclusion and rewrite it under their own initiative. No follow-up Linear issue needed — TML-2459 already covers it.

@wmadden
wmadden force-pushed the tml-2408-port-contract-spaces-to-the-mongo-family branch from 24a90fa to c03dfe9 Compare May 13, 2026 12:32
wmadden added a commit that referenced this pull request May 13, 2026
All acceptance criteria for the Mongo contract-spaces port are
satisfied on this branch (PR #494) and verified end-to-end against
the live test suite:

- AC1  MongoControlExtensionDescriptor.contractSpace + descriptor
       self-consistency wired in createMongoFamilyInstance
- AC2  Marker docs keyed by {_id: <spaceId>, space: <spaceId>}
       (legacy upgrade clause from FR4 deliberately dropped during
       execution; no production users on the legacy single-doc shape,
       upgrade path was unnecessary scope)
- AC3  readMarker / readAllMarkers per-space; executeAcrossSpaces
       accepts >= 2 perSpaceOptions
- AC4  Resumable per-space failure semantics (multi-space-runner test)
- AC5  Disjointness + sibling-pruning generalised for collections
- AC6  Pinned per-space contract.json / contract.d.ts / refs/head.json
- AC7  Aggregate apply + per-space verify drift isolation (e2e)
- AC8  Existing Mongo baseline preserved
- AC9  Subsystem 10 § Contract spaces + Subsystem 7 cross-reference
- AC10 All validation gates green at PR merge time
- AC11 Codec-rehydration guardrail test (NFR5)

Close-out actions:

- Refresh ADR 021 (Contract Marker Storage) to reflect Mongo per-space
  marker shape now in place; remove the stale "out of scope for Mongo
  today" caveat, point to Subsystem 10 § Contract spaces.
- Delete the transient projects/contract-spaces-mongo-port/ directory
  (spec, plan, specs/, reviews/) per the drive-project-workflow rule;
  durable docs already migrated to Subsystem 10 + ADR 212.

No code changes; mechanism + docs already shipped earlier on the branch.

Refs: TML-2408
Signed-off-by: Will Madden <[email protected]>
wmadden added a commit that referenced this pull request May 13, 2026
…viewer to scan for them; document Cursor Multitask Mode

Three connected changes pulled into one commit because they describe one
policy: transient project planning IDs (T1.1, TC-7, AC4, P3 R2,
CKPT-2, etc.) must not leak into source code, comments, test names, or
hash fixtures, and the iteration loop must catch them at review time
rather than after merge.

1. New rule `.agents/rules/no-transient-project-ids-in-code.mdc`. A
   focused, always-applied companion to `doc-maintenance.mdc`. Names
   the specific token classes that are forbidden in code (task IDs,
   test-case IDs, AC/FR/NFR IDs, phase/round/checkpoint IDs,
   `projects/<x>/...` paths, prose attributions to the plan,
   ID-named hash fixtures), explains the failure mode (transient IDs
   rot silently — once the plan is renumbered or deleted at close-out,
   the comment is dangling), and lists the stable references that
   stay allowed (Linear ticket IDs, ADR numbers, durable docs paths).
   Includes a paste-ready scan command the implementer can run on
   their `+` diff before declaring a task done.

2. Reviewer protocol update in
   `.agents/skills/drive-orchestrate-plan/agents/reviewer.md`. Adds
   step 7 to the round workflow ("Scan for transient project IDs
   leaking into code") and a dedicated `## Transient ID scan` section
   with the procedure: extract the round plan IDs from `plan.md` and
   `spec.md`, scan the round `+` diff for them and the structural
   patterns that catch IDs missed in step 1, file every hit as a
   `must-fix` finding. Adds a zero-hits clause to the
   `SATISFIED` acceptance bar so the scan is enforced rather than
   advisory. Adds an anti-pattern entry naming the protocol breach
   (skipping the scan).

3. Implementer protocol update in
   `.agents/skills/drive-orchestrate-plan/agents/implementer.md`.
   Adds a `## No transient project IDs in code` section with the
   high-frequency leakage shapes (test names, JSDoc, hash fixtures,
   `projects/<this-project>/...` paths, prose attributions) and the
   self-scan command to run before declaring a task done. Clarifies
   that commit messages and PR descriptions are out-of-band of the
   source-tree ban — task IDs are useful there for traceability but
   forbidden inside source files.

4. Multitasking guidance in
   `.agents/skills/drive-orchestrate-plan/SKILL.md`. New `##
   Multitasking the loop (Cursor IDE)` section: when the user is in
   Multitask Mode, both implementer and reviewer round delegations
   set `run_in_background: true`, and the orchestrator uses the
   wait window for productive prep (pre-stage the next delegation
   prompt, prepare R<N+1> implementer scoping, drain unrelated user
   questions). Explicitly forbids polling the backgrounded subagent,
   forbids running two persistent subagents of the same role in
   parallel (the loop is sequential per role even when each call
   is backgrounded), and reaffirms heartbeats as the canonical
   "stuck?" signal — backgrounding makes them more important, not
   less. Wires the multitasking hook into loop steps 2 and 5 and
   adds a behavioural rule to the cross-cutting invariants list.

Refs: TML-2408
Refs: PR #494
Signed-off-by: Will Madden <[email protected]>
wmadden added a commit that referenced this pull request May 13, 2026
The Mongo family is being shipped with multi-space markers as part of
this PR; we have no production users on the prior single-doc shape, and
the no-backward-compat-shims rule says we should not pre-pay maintenance
for hypothetical legacy state.

Removes the LEGACY_MARKER_ID constant, the duplicate-key error code, the
upgrade/sweep helpers, the markerCollection type widener, and the entire
legacy-upgrade test describe block. readMarker collapses to a single
non-branching aggregate. readAllMarkers keeps the defensive `space`
filter as a guard against malformed/manually-inserted docs (now framed
as exactly that, not as legacy handling).

Surfaced by review feedback on PR #494.

Signed-off-by: Will Madden <[email protected]>
wmadden added a commit that referenced this pull request May 13, 2026
… docs

Two narrow corrections surfaced in PR #494 review:

- mongo-target-descriptor.ts had a comment block pointing at
  `projects/contract-spaces-mongo-port/spec.md`, which the no-transient-
  project-ids-in-code rule (the rule introduced in 7c915a2) explicitly
  forbids. Replaced with the durable equivalents: subsystem 10 (MongoDB
  Family § Contract spaces) and ADR 212.

- ADR 212 listed the producer-side helpers as imported from
  `@prisma-next/migration-tools/exports/spaces`. The codebase imports
  them from `@prisma-next/migration-tools/spaces` per the no-`/exports/`-
  in-imports convention; documenting the canonical name avoids leading
  readers to a non-canonical path.

Signed-off-by: Will Madden <[email protected]>
@wmadden
wmadden force-pushed the tml-2408-port-contract-spaces-to-the-mongo-family branch from c1fdf59 to 8c9edf3 Compare May 13, 2026 12:54
wmadden added a commit that referenced this pull request May 13, 2026
All acceptance criteria for the Mongo contract-spaces port are
satisfied on this branch (PR #494) and verified end-to-end against
the live test suite:

- AC1  MongoControlExtensionDescriptor.contractSpace + descriptor
       self-consistency wired in createMongoFamilyInstance
- AC2  Marker docs keyed by {_id: <spaceId>, space: <spaceId>}
       (legacy upgrade clause from FR4 deliberately dropped during
       execution; no production users on the legacy single-doc shape,
       upgrade path was unnecessary scope)
- AC3  readMarker / readAllMarkers per-space; executeAcrossSpaces
       accepts >= 2 perSpaceOptions
- AC4  Resumable per-space failure semantics (multi-space-runner test)
- AC5  Disjointness + sibling-pruning generalised for collections
- AC6  Pinned per-space contract.json / contract.d.ts / refs/head.json
- AC7  Aggregate apply + per-space verify drift isolation (e2e)
- AC8  Existing Mongo baseline preserved
- AC9  Subsystem 10 § Contract spaces + Subsystem 7 cross-reference
- AC10 All validation gates green at PR merge time
- AC11 Codec-rehydration guardrail test (NFR5)

Close-out actions:

- Refresh ADR 021 (Contract Marker Storage) to reflect Mongo per-space
  marker shape now in place; remove the stale "out of scope for Mongo
  today" caveat, point to Subsystem 10 § Contract spaces.
- Delete the transient projects/contract-spaces-mongo-port/ directory
  (spec, plan, specs/, reviews/) per the drive-project-workflow rule;
  durable docs already migrated to Subsystem 10 + ADR 212.

No code changes; mechanism + docs already shipped earlier on the branch.

Refs: TML-2408
Signed-off-by: Will Madden <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

♻️ Duplicate comments (1)
.agents/skills/drive-orchestrate-plan/agents/implementer.md (1)

137-141: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Align the scan pattern with the rule file and the reviewer script.

This script has the same incompleteness as the patterns in .agents/rules/no-transient-project-ids-in-code.mdc and reviewer.md:

  • Missing D[0-9]+ (for D7)
  • Missing M[0-9]+\.[0-9]+ (for M3.2)
  • AC[0-9]+ should be AC-?[0-9]+ (to match AC-13)

All three scripts must use the same complete pattern. See the review comments on the rule file and reviewer.md for the proposed unified pattern.

🔧 Proposed fix (same as rule file and reviewer.md)
 git diff --cached -- '*.ts' '*.tsx' '*.js' '*.mjs' '*.py' '*.rs' '*.go' \
   | grep -E '^\+' \
-  | grep -oE '\b(T[0-9]+\.[0-9]+|TC-?[0-9]+|AC[0-9]+|FR[0-9]+|NFR[0-9]+|CKPT-[0-9]+|AM[0-9]+|P[0-9]+ R[0-9]+|M[0-9]+ review)\b' \
+  | grep -oE '\b(T[0-9]+\.[0-9]+|D[0-9]+|M[0-9]+\.[0-9]+|TC-?[0-9]+|AC-?[0-9]+|AM[0-9]+|FR[0-9]+|NFR[0-9]+|CKPT-[0-9]+|P[0-9]+ R[0-9]+|M[0-9]+ review)\b' \
   | sort -u
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.agents/skills/drive-orchestrate-plan/agents/implementer.md around lines 137
- 141, Update the grep regex in the staged-files scan inside implementer.md to
match the unified pattern used by the rule file and reviewer script: add the
D[0-9]+ token, add M[0-9]+\.[0-9]+ to cover versions like M3.2, and change
AC[0-9]+ to AC-?[0-9]+ so AC-13 matches; ensure the final alternation list
includes T[0-9]+\.[0-9]+, TC-?[0-9]+, D[0-9]+, M[0-9]+\.[0-9]+, AC-?[0-9]+,
FR[0-9]+, NFR[0-9]+, CKPT-[0-9]+, AM[0-9]+, P[0-9]+ R[0-9]+, and M[0-9]+ review
to keep it consistent with the other rule files.
🧹 Nitpick comments (2)
packages/1-framework/3-tooling/cli/test/utils/contract-space-seed-phase.mongo.test.ts (1)

116-121: ⚡ Quick win

Prefer object matchers for grouped record/headRef assertions.

Use toMatchObject for related fields to align with the test assertion style guideline and keep the expectation blocks tighter.

Proposed refactor
     expect(out.seeded).toHaveLength(1);
     const record = out.seeded[0]!;
-    expect(record.spaceId).toBe(EXT_SPACE);
-    expect(record.action).toBe('updated');
-    expect(record.priorHash).toBeNull();
-    expect(record.newHash).toBe(headHash);
+    expect(record).toMatchObject({
+      spaceId: EXT_SPACE,
+      action: 'updated',
+      priorHash: null,
+      newHash: headHash,
+    });
@@
     const headRef = await readContractSpaceHeadRef(migrationsDir, EXT_SPACE);
     expect(headRef).not.toBeNull();
-    expect(headRef!.hash).toBe(headHash);
-    expect(headRef!.invariants).toEqual(['inv:a', 'inv:b']);
+    expect(headRef).toMatchObject({
+      hash: headHash,
+      invariants: ['inv:a', 'inv:b'],
+    });

As per coding guidelines: "**/*.test.ts: Prefer object matchers (toMatchObject) over multiple individual expect().toBe() calls when checking 2 or more related values in tests."

Also applies to: 145-147

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@packages/1-framework/3-tooling/cli/test/utils/contract-space-seed-phase.mongo.test.ts`
around lines 116 - 121, Replace the multiple individual assertions on the seeded
record with an object matcher: use expect(out.seeded).toHaveLength(1); then
expect(out.seeded[0]).toMatchObject({ spaceId: EXT_SPACE, action: 'updated',
priorHash: null, newHash: headHash }); do the same refactor for the similar
block around the other assertion group (lines referenced in the comment) so
related fields are asserted with toMatchObject instead of separate
expect(...).toBe() calls.
test/integration/test/mongo/db-verify-sign.test.ts (1)

333-334: ⚡ Quick win

Include _id: string in the collection type shape to eliminate the blind cast.

The _id field is standard in MongoDB collections. Adding it to the type parameter lets .findOne({ _id: 'app' }) type correctly without the as unknown as never escape hatch.

Suggested fix
-        const markerDoc = await db
-          .collection<{ invariants?: readonly string[] }>('_prisma_migrations')
-          .findOne({ _id: 'app' as unknown as never });
+        const markerDoc = await db
+          .collection<{ _id: string; invariants?: readonly string[] }>('_prisma_migrations')
+          .findOne({ _id: 'app' });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/integration/test/mongo/db-verify-sign.test.ts` around lines 333 - 334,
The test uses .collection<{ invariants?: readonly string[]
}>('_prisma_migrations') then calls .findOne({ _id: 'app' as unknown as never
}); update the collection generic to include the _id field (e.g., { _id: string;
invariants?: readonly string[] }) so that .findOne({ _id: 'app' }) types
correctly without the blind cast; modify the generic on the collection call (the
type passed to .collection<...>) and remove the as unknown as never on the
.findOne call.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.agents/rules/no-transient-project-ids-in-code.mdc:
- Around line 54-59: Update the grep regex in the
.agents/rules/no-transient-project-ids-in-code.mdc script (the pattern used in
the pipeline that currently reads
'\b(T[0-9]+\.[0-9]+|TC-?[0-9]+|AC[0-9]+|FR[0-9]+|NFR[0-9]+|CKPT-[0-9]+|AM[0-9]+|P[0-9]+
R[0-9]+)\b') to also match D[0-9]+, M[0-9]+\.[0-9]+, AC-?[0-9]+ (to accept
hyphenated AC-13), and the milestone prose form M[0-9]+ review so it aligns with
the examples and the reviewer/implementer scripts; additionally add a short note
in the rule file documenting that freeform prose (e.g., "sub-spec § 4",
"deferred per project plan") cannot be reliably tokenized and suggest a
secondary heuristic grep (e.g., search for "spec §", "per project plan", "per
the spec") or manual review for those cases.

In @.agents/skills/drive-orchestrate-plan/agents/reviewer.md:
- Around line 100-115: The reviewer regex patterns that extract transient IDs
must be aligned with the canonical pattern used by the rule and implementer
scripts: update the token regex to include D[0-9]+ and M[0-9]+\.[0-9]+, change
AC[0-9]+ to AC-?[0-9]+ to allow hyphenated AC-13 forms, and remove or normalize
the ad‑hoc "M[0-9]+ review" variant so all three places use the exact same
complete pattern (the union of tokens:
T[0-9]+\.[0-9]+|TC-?[0-9]+|AC-?[0-9]+|FR[0-9]+|NFR[0-9]+|CKPT-[0-9]+|AM[0-9]+|D[0-9]+|M[0-9]+\.[0-9]+|P[0-9]+
R[0-9]+|M[0-9]+ review if you choose to keep it); apply this single canonical
regex to reviewer.md, implementer.md, and the
no-transient-project-ids-in-code.mdc rule script so the pre-commit check and
review scan are identical.

In
`@packages/1-framework/3-tooling/migration/src/aggregate/extract-storage-element-names.ts`:
- Around line 1-36: In the leading JSDoc of extract-storage-element-names.ts
remove transient planning/spec labels ("M1", "M2 R2", "NFR1") and any other
milestone shorthand, and reflow the prose to avoid hard-wrapped ~80-column
lines; keep durable context only (e.g., replace transient labels with canonical
ticket/ADR links or omit them) while preserving the behavioral notes and intent
of the comment.

In `@packages/3-mongo-target/1-mongo-target/src/core/marker-ledger.ts`:
- Line 87: The marker read and CAS filter must enforce the invariant that
document _id equals the provided space; update the RawAggregateCommand match
(where you currently use { _id: space }) to require both _id: space and space:
space (or use an $expr checking $_id == $space) so a row like { _id: "app",
space: "ext" } cannot be returned, and apply the same strict match to all
compare-and-swap/update filters used for markers (the places using
RawAggregateCommand(COLLECTION, ...) and the CAS update filters) so every
read/update uses { _id: space, space: space } (or equivalent $expr) to guarantee
_id === space.

---

Duplicate comments:
In @.agents/skills/drive-orchestrate-plan/agents/implementer.md:
- Around line 137-141: Update the grep regex in the staged-files scan inside
implementer.md to match the unified pattern used by the rule file and reviewer
script: add the D[0-9]+ token, add M[0-9]+\.[0-9]+ to cover versions like M3.2,
and change AC[0-9]+ to AC-?[0-9]+ so AC-13 matches; ensure the final alternation
list includes T[0-9]+\.[0-9]+, TC-?[0-9]+, D[0-9]+, M[0-9]+\.[0-9]+, AC-?[0-9]+,
FR[0-9]+, NFR[0-9]+, CKPT-[0-9]+, AM[0-9]+, P[0-9]+ R[0-9]+, and M[0-9]+ review
to keep it consistent with the other rule files.

---

Nitpick comments:
In
`@packages/1-framework/3-tooling/cli/test/utils/contract-space-seed-phase.mongo.test.ts`:
- Around line 116-121: Replace the multiple individual assertions on the seeded
record with an object matcher: use expect(out.seeded).toHaveLength(1); then
expect(out.seeded[0]).toMatchObject({ spaceId: EXT_SPACE, action: 'updated',
priorHash: null, newHash: headHash }); do the same refactor for the similar
block around the other assertion group (lines referenced in the comment) so
related fields are asserted with toMatchObject instead of separate
expect(...).toBe() calls.

In `@test/integration/test/mongo/db-verify-sign.test.ts`:
- Around line 333-334: The test uses .collection<{ invariants?: readonly
string[] }>('_prisma_migrations') then calls .findOne({ _id: 'app' as unknown as
never }); update the collection generic to include the _id field (e.g., { _id:
string; invariants?: readonly string[] }) so that .findOne({ _id: 'app' }) types
correctly without the blind cast; modify the generic on the collection call (the
type passed to .collection<...>) and remove the as unknown as never on the
.findOne call.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 409eb91c-4c98-4f12-a83c-8deaf3a03d6e

📥 Commits

Reviewing files that changed from the base of the PR and between bf26ef4 and 8c9edf3.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (82)
  • .agents/rules/no-transient-project-ids-in-code.mdc
  • .agents/skills/drive-orchestrate-plan/SKILL.md
  • .agents/skills/drive-orchestrate-plan/agents/implementer.md
  • .agents/skills/drive-orchestrate-plan/agents/reviewer.md
  • .agents/skills/drive-orchestrate-plan/templates/delegate-implement.md
  • .agents/skills/drive-orchestrate-plan/templates/delegate-review.md
  • docs/architecture docs/adrs/ADR 021 - Contract Marker Storage.md
  • docs/architecture docs/adrs/ADR 212 - Contract spaces.md
  • docs/architecture docs/subsystems/10. MongoDB Family.md
  • docs/architecture docs/subsystems/6. Ecosystem Extensions & Packs.md
  • docs/architecture docs/subsystems/7. Migration System.md
  • examples/retail-store/app/products/[id]/page.tsx
  • examples/retail-store/migrations/app/20260415_add-product-validation/migration.json
  • examples/retail-store/migrations/app/20260415_add-product-validation/migration.ts
  • examples/retail-store/migrations/app/20260415_add-product-validation/ops.json
  • examples/retail-store/migrations/app/20260416_backfill-product-status/migration.json
  • examples/retail-store/migrations/app/20260416_backfill-product-status/migration.ts
  • examples/retail-store/migrations/app/20260416_backfill-product-status/ops.json
  • examples/retail-store/migrations/app/20260513T0505_initial/end-contract.d.ts
  • examples/retail-store/migrations/app/20260513T0505_initial/end-contract.json
  • examples/retail-store/migrations/app/20260513T0505_initial/migration.json
  • examples/retail-store/migrations/app/20260513T0505_initial/migration.ts
  • examples/retail-store/migrations/app/20260513T0505_initial/ops.json
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/end-contract.d.ts
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/end-contract.json
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/migration.json
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/migration.ts
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/ops.json
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/start-contract.d.ts
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/start-contract.json
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/end-contract.d.ts
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/end-contract.json
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/migration.json
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/migration.ts
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/ops.json
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/start-contract.d.ts
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/start-contract.json
  • examples/retail-store/prisma/contract.prisma
  • examples/retail-store/src/contract.d.ts
  • examples/retail-store/src/contract.json
  • examples/retail-store/src/seed.ts
  • examples/retail-store/test/aggregation.test.ts
  • examples/retail-store/test/crud-lifecycle.test.ts
  • examples/retail-store/test/manual-migration.test.ts
  • examples/retail-store/test/migration-chain.test.ts
  • examples/retail-store/test/migration.test.ts
  • examples/retail-store/test/search.test.ts
  • packages/1-framework/1-core/framework-components/src/control/control-migration-types.ts
  • packages/1-framework/3-tooling/cli/test/utils/contract-space-seed-phase.mongo.test.ts
  • packages/1-framework/3-tooling/migration/src/aggregate/extract-storage-element-names.ts
  • packages/1-framework/3-tooling/migration/src/aggregate/loader.ts
  • packages/1-framework/3-tooling/migration/src/aggregate/project-schema-to-space.ts
  • packages/1-framework/3-tooling/migration/test/aggregate/loader.test.ts
  • packages/1-framework/3-tooling/migration/test/aggregate/project-schema-to-space.test.ts
  • packages/2-mongo-family/9-family/package.json
  • packages/2-mongo-family/9-family/src/core/control-instance.ts
  • packages/2-mongo-family/9-family/src/core/control-types.ts
  • packages/2-mongo-family/9-family/src/core/mongo-target-descriptor.ts
  • packages/2-mongo-family/9-family/src/exports/control.ts
  • packages/2-mongo-family/9-family/test/control-instance.descriptor-self-consistency.test.ts
  • packages/2-mongo-family/9-family/vitest.config.ts
  • packages/3-mongo-target/1-mongo-target/src/core/marker-ledger.ts
  • packages/3-mongo-target/1-mongo-target/src/core/mongo-runner.ts
  • packages/3-mongo-target/1-mongo-target/src/exports/control.ts
  • packages/3-mongo-target/1-mongo-target/test/marker-ledger.test.ts
  • packages/3-mongo-target/2-mongo-adapter/src/core/runner-deps.ts
  • packages/3-mongo-target/2-mongo-adapter/test/mongo-runner.schema-verify.integration.test.ts
  • packages/3-mongo-target/2-mongo-adapter/test/mongo-runner.test.ts
  • test/integration/test/cli.mongo-db-sign.e2e.test.ts
  • test/integration/test/cli.mongo-db-verify.e2e.test.ts
  • test/integration/test/contract-space-fixture-mongo/README.md
  • test/integration/test/contract-space-fixture-mongo/constants.ts
  • test/integration/test/contract-space-fixture-mongo/contract.ts
  • test/integration/test/contract-space-fixture-mongo/control.ts
  • test/integration/test/contract-space-fixture-mongo/descriptor.test.ts
  • test/integration/test/contract-space-fixture-mongo/migrations.ts
  • test/integration/test/mongo/aggregate-e2e.test.ts
  • test/integration/test/mongo/codec-rehydration-guardrail.test.ts
  • test/integration/test/mongo/db-verify-sign.test.ts
  • test/integration/test/mongo/family-read-marker-per-space.test.ts
  • test/integration/test/mongo/migration-e2e.test.ts
  • test/integration/test/mongo/multi-space-runner.test.ts
💤 Files with no reviewable changes (6)
  • examples/retail-store/migrations/app/20260416_backfill-product-status/migration.json
  • examples/retail-store/migrations/app/20260415_add-product-validation/migration.json
  • examples/retail-store/migrations/app/20260416_backfill-product-status/ops.json
  • examples/retail-store/migrations/app/20260415_add-product-validation/migration.ts
  • examples/retail-store/migrations/app/20260415_add-product-validation/ops.json
  • examples/retail-store/migrations/app/20260416_backfill-product-status/migration.ts
✅ Files skipped from review due to trivial changes (17)
  • test/integration/test/contract-space-fixture-mongo/README.md
  • docs/architecture docs/adrs/ADR 021 - Contract Marker Storage.md
  • examples/retail-store/test/search.test.ts
  • examples/retail-store/test/aggregation.test.ts
  • examples/retail-store/test/crud-lifecycle.test.ts
  • docs/architecture docs/subsystems/7. Migration System.md
  • docs/architecture docs/subsystems/6. Ecosystem Extensions & Packs.md
  • packages/1-framework/1-core/framework-components/src/control/control-migration-types.ts
  • packages/3-mongo-target/2-mongo-adapter/test/mongo-runner.test.ts
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/migration.json
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/end-contract.json
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/migration.json
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/start-contract.json
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/end-contract.d.ts
  • docs/architecture docs/adrs/ADR 212 - Contract spaces.md
  • examples/retail-store/migrations/app/20260513T0505_initial/end-contract.d.ts
  • examples/retail-store/migrations/app/20260513T0505_initial/end-contract.json
🚧 Files skipped from review as they are similar to previous changes (41)
  • examples/retail-store/prisma/contract.prisma
  • packages/2-mongo-family/9-family/src/exports/control.ts
  • packages/2-mongo-family/9-family/src/core/control-types.ts
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/ops.json
  • test/integration/test/cli.mongo-db-sign.e2e.test.ts
  • test/integration/test/contract-space-fixture-mongo/descriptor.test.ts
  • packages/2-mongo-family/9-family/package.json
  • packages/3-mongo-target/2-mongo-adapter/test/mongo-runner.schema-verify.integration.test.ts
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/migration.ts
  • test/integration/test/contract-space-fixture-mongo/control.ts
  • packages/3-mongo-target/2-mongo-adapter/src/core/runner-deps.ts
  • examples/retail-store/test/migration.test.ts
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/ops.json
  • packages/2-mongo-family/9-family/vitest.config.ts
  • test/integration/test/mongo/family-read-marker-per-space.test.ts
  • packages/3-mongo-target/1-mongo-target/src/exports/control.ts
  • packages/1-framework/3-tooling/migration/test/aggregate/loader.test.ts
  • .agents/skills/drive-orchestrate-plan/templates/delegate-implement.md
  • test/integration/test/contract-space-fixture-mongo/migrations.ts
  • packages/2-mongo-family/9-family/test/control-instance.descriptor-self-consistency.test.ts
  • test/integration/test/contract-space-fixture-mongo/constants.ts
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/start-contract.d.ts
  • packages/2-mongo-family/9-family/src/core/mongo-target-descriptor.ts
  • test/integration/test/contract-space-fixture-mongo/contract.ts
  • test/integration/test/mongo/codec-rehydration-guardrail.test.ts
  • packages/2-mongo-family/9-family/src/core/control-instance.ts
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/end-contract.d.ts
  • examples/retail-store/test/manual-migration.test.ts
  • .agents/skills/drive-orchestrate-plan/templates/delegate-review.md
  • test/integration/test/cli.mongo-db-verify.e2e.test.ts
  • test/integration/test/mongo/migration-e2e.test.ts
  • test/integration/test/mongo/aggregate-e2e.test.ts
  • packages/3-mongo-target/1-mongo-target/src/core/mongo-runner.ts
  • packages/1-framework/3-tooling/migration/src/aggregate/project-schema-to-space.ts
  • packages/1-framework/3-tooling/migration/test/aggregate/project-schema-to-space.test.ts
  • examples/retail-store/test/migration-chain.test.ts
  • .agents/skills/drive-orchestrate-plan/SKILL.md
  • examples/retail-store/migrations/app/20260513T0505_initial/ops.json
  • examples/retail-store/migrations/app/20260513T0505_initial/migration.ts
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/start-contract.json
  • examples/retail-store/migrations/app/20260513T0505_initial/migration.json

@wmadden

wmadden commented May 13, 2026

Copy link
Copy Markdown
Contributor Author

On it 👍 — addressing the PR-body sub-findings from review 4281865043 in separate commits: implementer.md grep alignment, the toMatchObject tidy in contract-space-seed-phase.mongo.test.ts, and the db-verify-sign _id typing.

@wmadden

wmadden commented May 13, 2026

Copy link
Copy Markdown
Contributor Author

PR-body sub-findings from review 4281865043:

  • implementer.md grep alignment → 98b9161
  • contract-space-seed-phase.mongo.test.ts toMatchObject tidy → ba79db2
  • db-verify-sign _id typing (drops the as unknown as never cast) → 79be933

wmadden added 3 commits May 13, 2026 16:11
Capture the spec and plan for porting contract spaces to the Mongo family.
Documents the cross-space atomicity choice (per-space marker-level, gated
on post-apply verify, resumable not transactional), the marker-doc shape
change, the descriptor surface, the multi-space runner contract, and the
schema-prune generalisation. Plan is a single PR structured as five
commit-clusters with reasoning-effort checkpoints at the design-call
moments and a final pre-PR self-review.

Refs: TML-2408
Signed-off-by: Will Madden <[email protected]>
Replace ExtensionContractSpace / ExtensionContractRef with the canonical
ContractSpace<TContract> / ContractSpaceHeadRef types from
framework-components/control. The descriptor blocks now show the SQL
family specialising the family-agnostic generic, which is what lets a
second family (Mongo, TML-2408) adopt the same shape without a parallel
type. Also rename stale emitPinnedSpaceArtefacts references to the
shipped emitContractSpaceArtefacts.

Signed-off-by: Will Madden <[email protected]>
….T1.1)

Mongo marker/ledger ops are now keyed by contract space. Each marker
doc lives at `_id: <space>` with `space: <space>` carried alongside;
ledger entries gain a `space` field so the same edgeId can recur
across spaces without colliding. The runner derives the space from
`plan.spaceId ?? APP_SPACE_ID`, so single-space callers that pre-date
contract spaces still write the application's well-known marker.

Legacy `{_id: "marker", ...}` docs remain unsupported here — pre-port
upgrade is the next slice (T1.2). After T1.1, fresh databases write
`{_id: "app", space: "app", ...}` directly.

BREAKING CHANGE: `readMarker` / `initMarker` / `updateMarker` /
`writeLedgerEntry` exported from `@prisma-next/target-mongo/control`
take a `space` parameter as their first positional argument after `db`.
Callers that previously addressed the implicit single marker doc must
pass APP_SPACE_ID explicitly.

Refs: TML-2408
Signed-off-by: Will Madden <[email protected]>
wmadden added 16 commits May 13, 2026 16:11
…ts and test names

Apply the new `no-transient-project-ids-in-code` rule to the code
this branch added in earlier rounds. The leaks were exactly the shape
the new rule names — test names tagged with TC-numbers, JSDoc blocks
attributing comments to phase/task IDs (P5 T5.2, T1.2, T3.4),
hash-fixture constants named after test-case IDs (`sha256:tc12-...`),
and a `describe` block parenthesising round labels.

Six files affected:

- `packages/3-mongo-target/1-mongo-target/src/core/marker-ledger.ts`:
  drop the `(T1.2)` attribution from the JSDoc on `MongoMarkerDocSchema`.
  Rephrase "post-port shape" / "pre-port docs" to "canonical shape" /
  "pre-canonical docs" so the comment describes the schema property in
  its own terms rather than referencing the migration that introduced it.

- `packages/3-mongo-target/1-mongo-target/test/marker-ledger.test.ts`:
  drop `(TC-3)`, `(TC-4, TC-5)` from `it` and `describe` strings.

- `packages/1-framework/3-tooling/cli/test/utils/contract-space-seed-phase.mongo.test.ts`:
  drop the `Phase 4 smoke tests (T4.1 / T4.2 / T4.3)` doc-comment
  preamble; rewrite as a property-focused summary. Drop `(T4.1, T4.2)`
  and `(T4.3 / AC6)` from `it` strings. Rename
  `sha256:tc12-ext-contract` / `sha256:tc12-ext-profile` to
  `sha256:mongo-ext-contract` / `sha256:mongo-ext-profile` so the
  fixture is named after its role, not the test case that introduced
  it.

- `test/integration/test/mongo/aggregate-e2e.test.ts`: drop
  `P5 T5.2 / T5.3` from the file-level JSDoc and `describe` label.
  Drop `(T5.2 / TC-14)` and `(T5.3 / TC-15)` from `it` labels. Drop
  `(AC4 property)` and `(AC4)` from JSDoc bullets and inline
  comments — the boundary they describe is intrinsic to the test, not
  a reference to a spec entry.

- `test/integration/test/mongo/codec-rehydration-guardrail.test.ts`:
  drop `TC-18 — codec-rehydration guardrail (NFR5 / AC11)` from the
  file JSDoc heading and the `describe` label.

- `test/integration/test/mongo/multi-space-runner.test.ts`: drop
  `(TC-7)`, `(TC-8)`, `(TC-9)` from `it` labels and `TC-8` /
  `T3.4` / `TC-9` references from JSDoc and inline comments.
  Tighten the `buildAppContractMissingPosts` JSDoc preamble.

In every case the rewrite preserves the property the comment / test
name was describing — what changed is that the property is now named
in its own right, not by reference to the plan row that introduced it.
Behaviour is unchanged; affected unit + integration suites remain
green (cli + target-mongo unit tests, multi-space-runner +
aggregate-e2e + codec-rehydration-guardrail integration tests).

Refs: TML-2408
Signed-off-by: Will Madden <[email protected]>
The Mongo family is being shipped with multi-space markers as part of
this PR; we have no production users on the prior single-doc shape, and
the no-backward-compat-shims rule says we should not pre-pay maintenance
for hypothetical legacy state.

Removes the LEGACY_MARKER_ID constant, the duplicate-key error code, the
upgrade/sweep helpers, the markerCollection type widener, and the entire
legacy-upgrade test describe block. readMarker collapses to a single
non-branching aggregate. readAllMarkers keeps the defensive `space`
filter as a guard against malformed/manually-inserted docs (now framed
as exactly that, not as legacy handling).

Surfaced by review feedback on PR #494.

Signed-off-by: Will Madden <[email protected]>
… walk

The aggregate loader and projectSchemaToSpace were each doing their own
typeof / Object.keys walk over a contract storage object to extract the
top-level table/collection names. Two consequences review surfaced:

- The loader walk push-pushed names into an array, so a contract that
  exposed the same name in both `tables` and `collections` (a
  hypothetical cross-family shape) registered the space twice and could
  trip a false self-collision in the disjointness check.

- The record-shape guards (`typeof === "object" && !== null`) also matched
  arrays, so an unrecognised array-shaped value entered the record-prune
  path via numeric keys instead of falling through unchanged.

Lifts the walk into a single `extractStorageElementNames(contract)`
helper that returns a Set (dedupes by construction) and excludes arrays
from the record branch (so the unrecognised-shape-passes-through
guarantee is preserved). Both call sites switch to the helper, and
projectSchemaToSpace gets the same `!Array.isArray` guard on its own
prune-record branches.

Also clarifies the projectSchemaToSpace JSDoc: "schema" here means the
live introspected DB state (MongoSchemaIR / SqlSchemaIR), not a
contract-space namespace nor a SQL CREATE-SCHEMA schema. The function
filters that introspected state down to the slice claimed by one space.

Signed-off-by: Will Madden <[email protected]>
… docs

Two narrow corrections surfaced in PR #494 review:

- mongo-target-descriptor.ts had a comment block pointing at
  `projects/contract-spaces-mongo-port/spec.md`, which the no-transient-
  project-ids-in-code rule (the rule introduced in 7c915a2) explicitly
  forbids. Replaced with the durable equivalents: subsystem 10 (MongoDB
  Family § Contract spaces) and ADR 212.

- ADR 212 listed the producer-side helpers as imported from
  `@prisma-next/migration-tools/exports/spaces`. The codebase imports
  them from `@prisma-next/migration-tools/spaces` per the no-`/exports/`-
  in-imports convention; documenting the canonical name avoids leading
  readers to a non-canonical path.

Signed-off-by: Will Madden <[email protected]>
The reviewer skill says (frontmatter) the agent is "the only file it
writes is reviews/code-review.md" but the Heartbeats section requires
writing wip/heartbeats/reviewer.txt every round. Two readers flagged
this as an impossible reporting rule: any honest "Files modified" return
list would have to include the heartbeat, contradicting the constraint.

Splits the writable-file contract into two surfaces, named explicitly:

- Durable: reviews/code-review.md (the round artifact).
- Operational: wip/heartbeats/reviewer.txt (overwrite-in-place liveness
  ping; not a deliverable).

The "Files modified" return-shape rule now says "durable writes only"
and explicitly tells the reviewer not to list the heartbeat there. The
frontmatter description and the body opening paragraph are aligned to
the same split so the writable contract reads consistently end-to-end.

Signed-off-by: Will Madden <[email protected]>
These values are guaranteed to exist after setup; the project's
coding-conventions rule prefers asserting presence and using non-null
property access over `if (!x) throw "unreachable"` and optional
chaining. Three sites in this file followed the older defensive shape
left over from when the API returned narrower types; tightening them up.

Signed-off-by: Will Madden <[email protected]>
Avoid politically loaded "master" terminology in the example schema.
"primaryCategory" reads naturally alongside the sibling `subCategory`
field on `Product`.

Signed-off-by: Will Madden <[email protected]>
…ML-2459

The framework lacks a typed primitive for storage topology — the
structural backbone of "what named things does this contract claim?"
independent of family. Today the helper duck-types `tables` /
`collections` from framework-domain code that has no business naming
family-specific storage idioms.

The correct fix is `interface Storage { namespaces: Record<string,
Namespace> }` at the framework level, which is scoped in TML-2459
(target-extensible-ir) M1; TML-2459 M2 R2 explicitly schedules removal
of this duck-typed walk when the IR class flip rebases onto this PR.
Landing an interim typed shape here would introduce a third on-disk
shape that TML-2459 would have to migrate away from again — violating
its NFR1 (no dual-shape transition window).

Update the JSDoc to record this so the next reader does not reach the
same conclusion and rewrite the helper under their own initiative.

Signed-off-by: Will Madden <[email protected]>
All acceptance criteria for the Mongo contract-spaces port are
satisfied on this branch (PR #494) and verified end-to-end against
the live test suite:

- AC1  MongoControlExtensionDescriptor.contractSpace + descriptor
       self-consistency wired in createMongoFamilyInstance
- AC2  Marker docs keyed by {_id: <spaceId>, space: <spaceId>}
       (legacy upgrade clause from FR4 deliberately dropped during
       execution; no production users on the legacy single-doc shape,
       upgrade path was unnecessary scope)
- AC3  readMarker / readAllMarkers per-space; executeAcrossSpaces
       accepts >= 2 perSpaceOptions
- AC4  Resumable per-space failure semantics (multi-space-runner test)
- AC5  Disjointness + sibling-pruning generalised for collections
- AC6  Pinned per-space contract.json / contract.d.ts / refs/head.json
- AC7  Aggregate apply + per-space verify drift isolation (e2e)
- AC8  Existing Mongo baseline preserved
- AC9  Subsystem 10 § Contract spaces + Subsystem 7 cross-reference
- AC10 All validation gates green at PR merge time
- AC11 Codec-rehydration guardrail test (NFR5)

Close-out actions:

- Refresh ADR 021 (Contract Marker Storage) to reflect Mongo per-space
  marker shape now in place; remove the stale "out of scope for Mongo
  today" caveat, point to Subsystem 10 § Contract spaces.
- Delete the transient projects/contract-spaces-mongo-port/ directory
  (spec, plan, specs/, reviews/) per the drive-project-workflow rule;
  durable docs already migrated to Subsystem 10 + ADR 212.

No code changes; mechanism + docs already shipped earlier on the branch.

Refs: TML-2408
Signed-off-by: Will Madden <[email protected]>
The pre-commit grep in the rule file lagged the canonical alternation used
by reviewer.md/implementer.md. Add the missing token shapes (D[0-9]+,
M[0-9]+\.[0-9]+, M[0-9]+ review) and accept hyphenated AC-?[0-9]+ so the
three scans cover the same surface. Also note that the regex only catches
token-shaped IDs — freeform prose attributions need a separate manual
scan.

Signed-off-by: Will Madden <[email protected]>
Both grep snippets in reviewer.md now use the same alternation as the rule
file and the implementer pre-commit check, so a token caught by one scan
is caught by all three.

Signed-off-by: Will Madden <[email protected]>
… regex

The implementer pre-commit scan now uses the same alternation as the rule
file and reviewer.md, so a token caught by one scan is caught by all
three.

Signed-off-by: Will Madden <[email protected]>
…eElementNames JSDoc

The JSDoc encoded TML-2459-internal milestone and spec-decision IDs
(M1, M2 R2, NFR1) that the no-transient-project-ids-in-code rule
forbids. Reword to describe the constraint itself: TML-2459 will
remove the duck-typed walk via the typed Storage primitive, and an
interim shape here would create a dual-shape transition window
TML-2459 explicitly rules out. TML-2459 ticket reference and the
behavioural notes are preserved.

Signed-off-by: Will Madden <[email protected]>
…ad and CAS

Marker docs are written with `_id` and `space` set to the same string
(see initMarker), so the two fields should always agree at read time.
Previously the read and CAS sites only matched on one of them, which
meant a corrupted or non-Prisma-written row whose `_id` and `space`
disagreed could masquerade as a marker for the wrong space. Add
defence-in-depth so:

- readMarker's $match requires both `_id: <space>` and `space: <space>`
- readAllMarkers adds `$expr: { $eq: ['$_id', '$space'] }` so
  any row where the two diverge is excluded by construction
- updateMarker's CAS filter includes `space` alongside `_id` and
  `storageHash`, so a mismatched row never satisfies the precondition

Regression tests cover all three sites against an inserted
`{ _id: APP, space: EXT, ... }` row.

Signed-off-by: Will Madden <[email protected]>
The first-seed assertions on `record` and `headRef` were each split into
four sequential single-field expectations. Collapse each group into one
`toMatchObject` per logical object so a future structural change shows
up as a single failure rather than four interleaved ones.

Signed-off-by: Will Madden <[email protected]>
…p the cast

The previous generic on the marker-doc lookup omitted `_id`, so the
filter `{ _id: 'app' }` only typechecked via `as unknown as never`.
The repo's typesafety rules call out that cast as a last-resort escape
hatch. Including `_id: string` in the collection generic lets the filter
typecheck cleanly.

Signed-off-by: Will Madden <[email protected]>
@wmadden
wmadden force-pushed the tml-2408-port-contract-spaces-to-the-mongo-family branch from 79be933 to cbae5b0 Compare May 13, 2026 14:11

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
docs/architecture docs/subsystems/10. MongoDB Family.md (1)

464-464: 💤 Low value

Consider American spelling for consistency.

The document uses "behavior" (American spelling) consistently elsewhere (lines 5, 92, 462), but "behaviour" (British spelling) appears here. Consider changing to "behavior" to maintain internal consistency.

Proposed spelling fix
-Descriptors without a `contractSpace` remain valid — they are codec-only or query-ops-only extensions, the existing pre-spaces behaviour preserved.
+Descriptors without a `contractSpace` remain valid — they are codec-only or query-ops-only extensions, the existing pre-spaces behavior preserved.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/architecture` docs/subsystems/10. MongoDB Family.md at line 464, Change
the British spelling "behaviour" to the American "behavior" in the described
paragraph; specifically update the sentence that reads "codec-only or
query-ops-only extensions, the existing pre-spaces behaviour preserved" so it
uses "behavior" to match the rest of the document, leaving references like
contractSpace, MongoControlExtensionDescriptor, createMongoFamilyInstance,
assertDescriptorSelfConsistency, and MIGRATION.DESCRIPTOR_HEAD_HASH_MISMATCH
unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.agents/skills/drive-orchestrate-plan/agents/reviewer.md:
- Line 30: Update the non-standard phrase "wants triaged" to the correct
phrasing "wants to be triaged" in the reviewer documentation; search for the
exact string "wants triaged" (e.g., in the reviewer.md content) and replace it
with "wants to be triaged" to fix grammar while preserving surrounding context
and punctuation.

---

Nitpick comments:
In `@docs/architecture` docs/subsystems/10. MongoDB Family.md:
- Line 464: Change the British spelling "behaviour" to the American "behavior"
in the described paragraph; specifically update the sentence that reads
"codec-only or query-ops-only extensions, the existing pre-spaces behaviour
preserved" so it uses "behavior" to match the rest of the document, leaving
references like contractSpace, MongoControlExtensionDescriptor,
createMongoFamilyInstance, assertDescriptorSelfConsistency, and
MIGRATION.DESCRIPTOR_HEAD_HASH_MISMATCH unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: fe02c963-550f-4e65-905d-ece4ffaf5dd1

📥 Commits

Reviewing files that changed from the base of the PR and between 79be933 and cbae5b0.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (82)
  • .agents/rules/no-transient-project-ids-in-code.mdc
  • .agents/skills/drive-orchestrate-plan/SKILL.md
  • .agents/skills/drive-orchestrate-plan/agents/implementer.md
  • .agents/skills/drive-orchestrate-plan/agents/reviewer.md
  • .agents/skills/drive-orchestrate-plan/templates/delegate-implement.md
  • .agents/skills/drive-orchestrate-plan/templates/delegate-review.md
  • docs/architecture docs/adrs/ADR 021 - Contract Marker Storage.md
  • docs/architecture docs/adrs/ADR 212 - Contract spaces.md
  • docs/architecture docs/subsystems/10. MongoDB Family.md
  • docs/architecture docs/subsystems/6. Ecosystem Extensions & Packs.md
  • docs/architecture docs/subsystems/7. Migration System.md
  • examples/retail-store/app/products/[id]/page.tsx
  • examples/retail-store/migrations/app/20260415_add-product-validation/migration.json
  • examples/retail-store/migrations/app/20260415_add-product-validation/migration.ts
  • examples/retail-store/migrations/app/20260415_add-product-validation/ops.json
  • examples/retail-store/migrations/app/20260416_backfill-product-status/migration.json
  • examples/retail-store/migrations/app/20260416_backfill-product-status/migration.ts
  • examples/retail-store/migrations/app/20260416_backfill-product-status/ops.json
  • examples/retail-store/migrations/app/20260513T0505_initial/end-contract.d.ts
  • examples/retail-store/migrations/app/20260513T0505_initial/end-contract.json
  • examples/retail-store/migrations/app/20260513T0505_initial/migration.json
  • examples/retail-store/migrations/app/20260513T0505_initial/migration.ts
  • examples/retail-store/migrations/app/20260513T0505_initial/ops.json
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/end-contract.d.ts
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/end-contract.json
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/migration.json
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/migration.ts
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/ops.json
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/start-contract.d.ts
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/start-contract.json
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/end-contract.d.ts
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/end-contract.json
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/migration.json
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/migration.ts
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/ops.json
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/start-contract.d.ts
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/start-contract.json
  • examples/retail-store/prisma/contract.prisma
  • examples/retail-store/src/contract.d.ts
  • examples/retail-store/src/contract.json
  • examples/retail-store/src/seed.ts
  • examples/retail-store/test/aggregation.test.ts
  • examples/retail-store/test/crud-lifecycle.test.ts
  • examples/retail-store/test/manual-migration.test.ts
  • examples/retail-store/test/migration-chain.test.ts
  • examples/retail-store/test/migration.test.ts
  • examples/retail-store/test/search.test.ts
  • packages/1-framework/1-core/framework-components/src/control/control-migration-types.ts
  • packages/1-framework/3-tooling/cli/test/utils/contract-space-seed-phase.mongo.test.ts
  • packages/1-framework/3-tooling/migration/src/aggregate/extract-storage-element-names.ts
  • packages/1-framework/3-tooling/migration/src/aggregate/loader.ts
  • packages/1-framework/3-tooling/migration/src/aggregate/project-schema-to-space.ts
  • packages/1-framework/3-tooling/migration/test/aggregate/loader.test.ts
  • packages/1-framework/3-tooling/migration/test/aggregate/project-schema-to-space.test.ts
  • packages/2-mongo-family/9-family/package.json
  • packages/2-mongo-family/9-family/src/core/control-instance.ts
  • packages/2-mongo-family/9-family/src/core/control-types.ts
  • packages/2-mongo-family/9-family/src/core/mongo-target-descriptor.ts
  • packages/2-mongo-family/9-family/src/exports/control.ts
  • packages/2-mongo-family/9-family/test/control-instance.descriptor-self-consistency.test.ts
  • packages/2-mongo-family/9-family/vitest.config.ts
  • packages/3-mongo-target/1-mongo-target/src/core/marker-ledger.ts
  • packages/3-mongo-target/1-mongo-target/src/core/mongo-runner.ts
  • packages/3-mongo-target/1-mongo-target/src/exports/control.ts
  • packages/3-mongo-target/1-mongo-target/test/marker-ledger.test.ts
  • packages/3-mongo-target/2-mongo-adapter/src/core/runner-deps.ts
  • packages/3-mongo-target/2-mongo-adapter/test/mongo-runner.schema-verify.integration.test.ts
  • packages/3-mongo-target/2-mongo-adapter/test/mongo-runner.test.ts
  • test/integration/test/cli.mongo-db-sign.e2e.test.ts
  • test/integration/test/cli.mongo-db-verify.e2e.test.ts
  • test/integration/test/contract-space-fixture-mongo/README.md
  • test/integration/test/contract-space-fixture-mongo/constants.ts
  • test/integration/test/contract-space-fixture-mongo/contract.ts
  • test/integration/test/contract-space-fixture-mongo/control.ts
  • test/integration/test/contract-space-fixture-mongo/descriptor.test.ts
  • test/integration/test/contract-space-fixture-mongo/migrations.ts
  • test/integration/test/mongo/aggregate-e2e.test.ts
  • test/integration/test/mongo/codec-rehydration-guardrail.test.ts
  • test/integration/test/mongo/db-verify-sign.test.ts
  • test/integration/test/mongo/family-read-marker-per-space.test.ts
  • test/integration/test/mongo/migration-e2e.test.ts
  • test/integration/test/mongo/multi-space-runner.test.ts
💤 Files with no reviewable changes (6)
  • examples/retail-store/migrations/app/20260415_add-product-validation/migration.json
  • examples/retail-store/migrations/app/20260416_backfill-product-status/migration.ts
  • examples/retail-store/migrations/app/20260415_add-product-validation/migration.ts
  • examples/retail-store/migrations/app/20260416_backfill-product-status/migration.json
  • examples/retail-store/migrations/app/20260416_backfill-product-status/ops.json
  • examples/retail-store/migrations/app/20260415_add-product-validation/ops.json
✅ Files skipped from review due to trivial changes (17)
  • packages/2-mongo-family/9-family/src/exports/control.ts
  • examples/retail-store/test/aggregation.test.ts
  • packages/1-framework/3-tooling/migration/src/aggregate/extract-storage-element-names.ts
  • test/integration/test/contract-space-fixture-mongo/README.md
  • docs/architecture docs/adrs/ADR 021 - Contract Marker Storage.md
  • packages/1-framework/1-core/framework-components/src/control/control-migration-types.ts
  • packages/2-mongo-family/9-family/package.json
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/end-contract.json
  • test/integration/test/contract-space-fixture-mongo/constants.ts
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/start-contract.d.ts
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/migration.json
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/end-contract.d.ts
  • .agents/rules/no-transient-project-ids-in-code.mdc
  • examples/retail-store/migrations/app/20260513T0505_initial/end-contract.d.ts
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/end-contract.d.ts
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/start-contract.json
  • docs/architecture docs/adrs/ADR 212 - Contract spaces.md
🚧 Files skipped from review as they are similar to previous changes (48)
  • examples/retail-store/test/migration.test.ts
  • examples/retail-store/app/products/[id]/page.tsx
  • packages/3-mongo-target/2-mongo-adapter/src/core/runner-deps.ts
  • test/integration/test/contract-space-fixture-mongo/descriptor.test.ts
  • examples/retail-store/prisma/contract.prisma
  • test/integration/test/contract-space-fixture-mongo/control.ts
  • .agents/skills/drive-orchestrate-plan/templates/delegate-implement.md
  • packages/3-mongo-target/2-mongo-adapter/test/mongo-runner.schema-verify.integration.test.ts
  • .agents/skills/drive-orchestrate-plan/agents/implementer.md
  • docs/architecture docs/subsystems/7. Migration System.md
  • packages/1-framework/3-tooling/migration/test/aggregate/loader.test.ts
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/migration.ts
  • packages/2-mongo-family/9-family/test/control-instance.descriptor-self-consistency.test.ts
  • examples/retail-store/test/crud-lifecycle.test.ts
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/ops.json
  • packages/3-mongo-target/1-mongo-target/src/exports/control.ts
  • packages/3-mongo-target/2-mongo-adapter/test/mongo-runner.test.ts
  • packages/1-framework/3-tooling/cli/test/utils/contract-space-seed-phase.mongo.test.ts
  • packages/2-mongo-family/9-family/src/core/control-types.ts
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/migration.ts
  • examples/retail-store/test/manual-migration.test.ts
  • docs/architecture docs/subsystems/6. Ecosystem Extensions & Packs.md
  • test/integration/test/mongo/family-read-marker-per-space.test.ts
  • examples/retail-store/src/contract.json
  • examples/retail-store/test/migration-chain.test.ts
  • examples/retail-store/migrations/app/20260513T0508_backfill_product_status/migration.json
  • test/integration/test/mongo/codec-rehydration-guardrail.test.ts
  • packages/1-framework/3-tooling/migration/src/aggregate/project-schema-to-space.ts
  • packages/2-mongo-family/9-family/vitest.config.ts
  • packages/2-mongo-family/9-family/src/core/mongo-target-descriptor.ts
  • test/integration/test/cli.mongo-db-sign.e2e.test.ts
  • test/integration/test/contract-space-fixture-mongo/contract.ts
  • packages/1-framework/3-tooling/migration/test/aggregate/project-schema-to-space.test.ts
  • .agents/skills/drive-orchestrate-plan/templates/delegate-review.md
  • .agents/skills/drive-orchestrate-plan/SKILL.md
  • test/integration/test/contract-space-fixture-mongo/migrations.ts
  • test/integration/test/mongo/aggregate-e2e.test.ts
  • examples/retail-store/migrations/app/20260513T0505_initial/end-contract.json
  • test/integration/test/mongo/db-verify-sign.test.ts
  • packages/1-framework/3-tooling/migration/src/aggregate/loader.ts
  • examples/retail-store/src/contract.d.ts
  • test/integration/test/cli.mongo-db-verify.e2e.test.ts
  • packages/3-mongo-target/1-mongo-target/test/marker-ledger.test.ts
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/end-contract.json
  • packages/2-mongo-family/9-family/src/core/control-instance.ts
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/start-contract.json
  • examples/retail-store/migrations/app/20260513T0507_add_product_category_index/start-contract.d.ts
  • packages/3-mongo-target/1-mongo-target/src/core/marker-ledger.ts

@wmadden
wmadden merged commit 72ef04c into main May 13, 2026
16 checks passed
wmadden added a commit that referenced this pull request May 13, 2026
…viewer to scan for them; document Cursor Multitask Mode

Three connected changes pulled into one commit because they describe one
policy: transient project planning IDs (T1.1, TC-7, AC4, P3 R2,
CKPT-2, etc.) must not leak into source code, comments, test names, or
hash fixtures, and the iteration loop must catch them at review time
rather than after merge.

1. New rule `.agents/rules/no-transient-project-ids-in-code.mdc`. A
   focused, always-applied companion to `doc-maintenance.mdc`. Names
   the specific token classes that are forbidden in code (task IDs,
   test-case IDs, AC/FR/NFR IDs, phase/round/checkpoint IDs,
   `projects/<x>/...` paths, prose attributions to the plan,
   ID-named hash fixtures), explains the failure mode (transient IDs
   rot silently — once the plan is renumbered or deleted at close-out,
   the comment is dangling), and lists the stable references that
   stay allowed (Linear ticket IDs, ADR numbers, durable docs paths).
   Includes a paste-ready scan command the implementer can run on
   their `+` diff before declaring a task done.

2. Reviewer protocol update in
   `.agents/skills/drive-orchestrate-plan/agents/reviewer.md`. Adds
   step 7 to the round workflow ("Scan for transient project IDs
   leaking into code") and a dedicated `## Transient ID scan` section
   with the procedure: extract the round plan IDs from `plan.md` and
   `spec.md`, scan the round `+` diff for them and the structural
   patterns that catch IDs missed in step 1, file every hit as a
   `must-fix` finding. Adds a zero-hits clause to the
   `SATISFIED` acceptance bar so the scan is enforced rather than
   advisory. Adds an anti-pattern entry naming the protocol breach
   (skipping the scan).

3. Implementer protocol update in
   `.agents/skills/drive-orchestrate-plan/agents/implementer.md`.
   Adds a `## No transient project IDs in code` section with the
   high-frequency leakage shapes (test names, JSDoc, hash fixtures,
   `projects/<this-project>/...` paths, prose attributions) and the
   self-scan command to run before declaring a task done. Clarifies
   that commit messages and PR descriptions are out-of-band of the
   source-tree ban — task IDs are useful there for traceability but
   forbidden inside source files.

4. Multitasking guidance in
   `.agents/skills/drive-orchestrate-plan/SKILL.md`. New `##
   Multitasking the loop (Cursor IDE)` section: when the user is in
   Multitask Mode, both implementer and reviewer round delegations
   set `run_in_background: true`, and the orchestrator uses the
   wait window for productive prep (pre-stage the next delegation
   prompt, prepare R<N+1> implementer scoping, drain unrelated user
   questions). Explicitly forbids polling the backgrounded subagent,
   forbids running two persistent subagents of the same role in
   parallel (the loop is sequential per role even when each call
   is backgrounded), and reaffirms heartbeats as the canonical
   "stuck?" signal — backgrounding makes them more important, not
   less. Wires the multitasking hook into loop steps 2 and 5 and
   adds a behavioural rule to the cross-cutting invariants list.

Refs: TML-2408
Refs: PR #494
Signed-off-by: Will Madden <[email protected]>
wmadden added a commit that referenced this pull request May 13, 2026
The Mongo family is being shipped with multi-space markers as part of
this PR; we have no production users on the prior single-doc shape, and
the no-backward-compat-shims rule says we should not pre-pay maintenance
for hypothetical legacy state.

Removes the LEGACY_MARKER_ID constant, the duplicate-key error code, the
upgrade/sweep helpers, the markerCollection type widener, and the entire
legacy-upgrade test describe block. readMarker collapses to a single
non-branching aggregate. readAllMarkers keeps the defensive `space`
filter as a guard against malformed/manually-inserted docs (now framed
as exactly that, not as legacy handling).

Surfaced by review feedback on PR #494.

Signed-off-by: Will Madden <[email protected]>
wmadden added a commit that referenced this pull request May 13, 2026
… docs

Two narrow corrections surfaced in PR #494 review:

- mongo-target-descriptor.ts had a comment block pointing at
  `projects/contract-spaces-mongo-port/spec.md`, which the no-transient-
  project-ids-in-code rule (the rule introduced in 7c915a2) explicitly
  forbids. Replaced with the durable equivalents: subsystem 10 (MongoDB
  Family § Contract spaces) and ADR 212.

- ADR 212 listed the producer-side helpers as imported from
  `@prisma-next/migration-tools/exports/spaces`. The codebase imports
  them from `@prisma-next/migration-tools/spaces` per the no-`/exports/`-
  in-imports convention; documenting the canonical name avoids leading
  readers to a non-canonical path.

Signed-off-by: Will Madden <[email protected]>
wmadden added a commit that referenced this pull request May 13, 2026
All acceptance criteria for the Mongo contract-spaces port are
satisfied on this branch (PR #494) and verified end-to-end against
the live test suite:

- AC1  MongoControlExtensionDescriptor.contractSpace + descriptor
       self-consistency wired in createMongoFamilyInstance
- AC2  Marker docs keyed by {_id: <spaceId>, space: <spaceId>}
       (legacy upgrade clause from FR4 deliberately dropped during
       execution; no production users on the legacy single-doc shape,
       upgrade path was unnecessary scope)
- AC3  readMarker / readAllMarkers per-space; executeAcrossSpaces
       accepts >= 2 perSpaceOptions
- AC4  Resumable per-space failure semantics (multi-space-runner test)
- AC5  Disjointness + sibling-pruning generalised for collections
- AC6  Pinned per-space contract.json / contract.d.ts / refs/head.json
- AC7  Aggregate apply + per-space verify drift isolation (e2e)
- AC8  Existing Mongo baseline preserved
- AC9  Subsystem 10 § Contract spaces + Subsystem 7 cross-reference
- AC10 All validation gates green at PR merge time
- AC11 Codec-rehydration guardrail test (NFR5)

Close-out actions:

- Refresh ADR 021 (Contract Marker Storage) to reflect Mongo per-space
  marker shape now in place; remove the stale "out of scope for Mongo
  today" caveat, point to Subsystem 10 § Contract spaces.
- Delete the transient projects/contract-spaces-mongo-port/ directory
  (spec, plan, specs/, reviews/) per the drive-project-workflow rule;
  durable docs already migrated to Subsystem 10 + ADR 212.

No code changes; mechanism + docs already shipped earlier on the branch.

Refs: TML-2408
Signed-off-by: Will Madden <[email protected]>
@wmadden
wmadden deleted the tml-2408-port-contract-spaces-to-the-mongo-family branch May 13, 2026 14:25
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant