Documentation menu
Documentation / CRM & Marketing engine / deals
Deals
npm install @wabbit/tome-dealsFirst install from our registry?
Get a registry token from your credentials page. You need a purchase that includes this package, or a Craft Library membership.
Add the registry and your token to the
.npmrcat the root of your project, with your token in place ofYOUR_TOKEN:@wabbit:registry=https://npm.wabbit.com/ //npm.wabbit.com/:_authToken=YOUR_TOKEN
Tome Deals layer — deal lifecycle engine with artifact-type registry (quotes, proposals, SOWs, retainer agreements) and CRM cascade integration.
Overview
Tome Deals layer — deal lifecycle engine with an artifact-type registry (quotes, proposals, SOWs, retainer agreements) and CRM cascade integration. Description copied verbatim from package.json.
Layer: domain (per the repo's ARCHITECTURE.md § The Layer Model). Optionally integrates with @wabbit/tome-crm (customer/opportunity cascade), @wabbit/tome-catalog (line items), and @wabbit/tome-print (document rendering) — all three are optional peers, none is required to use deals standalone. @wabbit/tome-core and @wabbit/tome-workflow (which owns the status-transition check) are required.
Peer dependencies
Peer ranges, copied from package.json:
| Peer | Range | Optional? |
|---|---|---|
payload | >=3.67.0 | no |
typescript | >=5.7.0 | no |
@wabbit/tome-core | >=1.14.0 <2.0.0 | no |
@wabbit/tome-crm | >=0.2.0 <1.0.0 | yes |
@wabbit/tome-catalog | >=1.1.0 <2.0.0 | yes |
@wabbit/tome-print | >=0.1.0 <1.0.0 | yes |
@wabbit/tome-workflow | >=0.1.1 <1.0.0 | no |
dependencies: server-only@^0.0.1. Note: no `lucide-react` peer — deals passes a string iconName: 'Handshake' to the admin-nav manifest rather than importing an actual lucide icon component the way crm/catalog/org/economy/lms do, so it has no icon-package dependency at all (verified: zero lucide-react references anywhere in src/).
60-second quickstart
The current API is createDealsLayer(config), returning [dealsCollection, dealCounterCollection] (initDeals is a deprecated pure alias, kept for back-compat only):
import { buildConfig } from 'payload'
import { createDealsLayer } from '@wabbit/tome-deals'
export default buildConfig({
collections: [
...createDealsLayer({ slug: 'deals', currency: 'USD' }),
// ...your other collections
],
})The gotcha that bites: the deals collection carries relationships to collections it does not create, and Payload refuses to start if any target slug is missing. Line-item product relates to productCollection (default 'catalog-products', @wabbit/tome-catalog's products slug — pass your own slug when line items point at a products collection you own), and the rep and createdBy fields relate to users (repCollection; createdBy is always users). Other defaults: counterSlug: 'deal-number-counters', numberStrategy: 'count-query' with yearly reset, adminGroup: 'Sales Operations'.
createDealsLayer({ productCollection: 'catalog-products' }) // with @wabbit/tome-catalogcreateDealsLayer pre-registers the default quote artifact type and five built-in side-effect handlers (sendDealEmail, stampInvoiceNumber, cascadeOpportunityWon/Lost/Paid), then freezes the artifact registry — defineDealArtifactType calls after createDealsLayer runs will throw. customerRelation auto-defaults to 'crm-contacts' when @wabbit/tome-crm is already registered in the layer registry at the moment createDealsLayer runs — so call createCrmLayer first; pass customerRelation: undefined explicitly to opt out. To advance CRM opportunities when a deal changes status, pass onStatusChange: buildDealsCrmBridge(crmConfig) (from @wabbit/tome-crm's server subpath) — onStatusChange(deal, prevStatus, req) is called exactly once for every status transition (draft → sent, sent → accepted, sent → rejected, sent → expired, accepted → invoiced, invoiced → paid and the admin-only backward edges in the default workflow; every edge of a custom workflow), whichever path wrote the change (admin edit, payload.update or advanceDealStatus), after the transition's side effect has run. A save that leaves the status unchanged does not call it, and failures are logged, not thrown. Without onStatusChange, the same transitions go to @wabbit/tome-crm's cascade automatically when CRM is installed and the deal has a linked opportunity. resolveRepByAddress and printAdapter are the other two integration seams on TomeDealsConfig. printAdapter(deal, templateSlug, req) is the only print path: deals has no fallback into @wabbit/tome-print (that package registers no layer and exposes no job-dispatch function), so a site that prints deal documents calls its print setup from inside its own adapter. No built-in side-effect handler invokes printAdapter today; call it from a side effect you register, for example by replacing the stampInvoiceNumber handler with @wabbit/tome-workflow's replaceWorkflowSideEffect.
A transition's side effect fires once per status change, whichever way the change is made: advanceDealStatus fires it itself, and a direct payload.update or admin-panel edit fires it from the collection's afterChange hook after the write persists. The deal-number-counters collection is readable by any signed-in user, but create/update/delete are admin-only (deals:admin, or the legacy admin role); deal-number generation writes with overrideAccess, so reps creating deals are unaffected.
API surface
Four subpaths: ., @wabbit/tome-deals/server, ./test, @wabbit/tome-deals/legacy/quote-types.
`.`:
| Group | Exports |
|---|---|
| Layer entry | createDealsLayer |
| Artifact-type registry | defineDealArtifactType, replaceDealArtifactType, getDealArtifactType, getRegisteredDealArtifactTypes (registry-registration verbs, not deprecated create* aliases — deals has no createDealArtifactType) |
| Side-effect registry | defineDealSideEffect (deprecated — use @wabbit/tome-workflow side effects), replaceDealSideEffect, getDealSideEffect, getRegisteredSideEffectKeys |
| Default registrations | DEFAULT_QUOTE_ARTIFACT, DEFAULT_DEAL_WORKFLOW, resolveWorkflow, findTransition (deprecated — delegates to @wabbit/tome-workflow), validateWorkflow |
| Pure helper | computeDealTotals — the one export explicitly documented "safe for client import" (no server-only guard) |
| Access | dealsAccess, deals, dealCountersAccess, DEALS_CAPABILITIES, DealsCapability |
| Test escape hatch | _resetArtifactRegistry — contradiction found in source: the artifact-registry module's own comment says _freezeArtifactRegistry/_resetArtifactRegistry are "intentionally not re-exported from the public barrel," but the last line of src/index.ts re-exports _resetArtifactRegistry anyway (for test teardown). Verified by direct read, not the module's own comment. |
| Types | TomeDealStatus, TomeDealTransition, TomeDealStatusWorkflow, TomeDealArtifactTypeDefinition, TomeDealsConfig, TomeDealAddress, TomeDealCustomer, TomeDiscountType, TomePaymentTerms, TomeDealDiscount, TomeDealLineItem, TomeDealScheduleEntry, TomeDeal, TomeHydratedDeal, TomeDealTotalsInput, TomeDealTotals, TomeDealSideEffectHandler, TomeDealSideEffectDefinition, TomeDealEmailContext, TomeDealEmailResult |
Deprecated alias (pure rename, @deprecated-tagged, removal at this package's next major): initDeals → createDealsLayer.
`@wabbit/tome-deals/server` — behind import 'server-only': getDeal, getDealByNumber, advanceDealStatus, createDealFromIntake (+DealIntakeSubmission), sendDealEmailMessage, resolveOpportunityForDeal, resolveOpportunityForNewDeal, attachOpportunityToExistingDeal, isCrmRegistered, resolveCustomerRelationDefault, requiresRepOrAdmin, requiresDealsAdmin, dealsRepWhereClause, dealsRepOrAdminWhereClause.
`./test` — explicitly a stub per its own docblock ("Wave 2 integration will flesh this out"): re-exports DEFAULT_QUOTE_ARTIFACT/DEFAULT_DEAL_WORKFLOW plus two bare fixtures, mockQuoteDeal and mockProposalDeal.
`@wabbit/tome-deals/legacy/quote-types` — deprecated backward-compat type aliases (TomeQuote → TomeDeal, TomeQuoteStatus → TomeDealStatus, etc.) for pre-rename @wabbit/tome-quotes consumers. The module's own comment states it "will be removed at v0.2.0" — the package is now past that stated removal point without the subpath having been removed. Don't build new code against it; migrate to the canonical TomeDeal* names.
Server / client posture
Server-only package: Payload collection factories + import 'server-only'-guarded @wabbit/tome-deals/server helpers. The single exception is computeDealTotals, explicitly called out in the barrel's own comment as safe for client-side import (a pure totals calculator with no I/O).
Links
- CRM cascade ownership:
@wabbit/tome-crm'sintegration/deals.tsonDealStatusChange()is the authoritative owner of the won/lost stage cascade and the sent/paid activity records. This package reaches it only throughconfig.onStatusChange(or the automatic CRM bridge when that is unset), called once per status transition by the deals collection's afterChange hook and byadvanceDealStatus. The built-incascadeOpportunityWon/cascadeOpportunityLosthandlers are no-ops andcascadeOpportunityPaidonly stampspaidAt; a side effect you register must not callonStatusChangeoradvanceOpportunityStageitself, or the cascade double-fires. CHANGELOG.md
Testing
pnpm --filter @wabbit/tome-deals test runs the Vitest suite. The artifact registry freezes on the first createDealsLayer call and is module-level, so call _resetArtifactRegistry() in afterEach before a test registers artifact types or builds the layer again. @wabbit/tome-deals/test exports mockQuoteDeal / mockProposalDeal fixtures.
Extending this package
New artifact types register via defineDealArtifactType before createDealsLayer runs (or a consumer can pre-register 'quote' itself — createDealsLayer catches the duplicate-key throw for that one sanctioned override case only). New side-effect handlers register the same way via defineDealSideEffect (deprecated — use @wabbit/tome-workflow side effects); each of the five built-in handlers is registered inside a try/catch so a consumer pre-registering the same key wins.
Exports
| Import path |
|---|
@wabbit/tome-deals |
@wabbit/tome-deals/server |
@wabbit/tome-deals/test |
@wabbit/tome-deals/legacy/quote-types |
Changelog
0.8.xMinor
BREAKING: Deals now record how often and when a recipient viewed them, through new fields that need a database migration on SQL adapters.
Migration: On SQL adapters generate and run a migration for the new deal fields; MongoDB needs none. Otherwise the change is additive.
- New read-only
viewCount,firstViewedAtandlastViewedAtdeal fields, and arecordDealViewhelper on./server. - Recipient opens increment the counter and stamp the dates; staff opens change nothing.
- When the CRM bridge is wired, a
proposal-viewedactivity is logged oncustomerContact, folded per deal per day.
- New read-only
4 fixes (0.8.1 – 0.8.4)
- 0.8.4
The changelog, README and license text now use American spellings.
No code or behavior changes.
- 0.8.3
README: subpath and file mentions are written package-qualified (for example
@wabbit/tome-x/render) or as code text, so crawlers no longer resolve them as site URLs. - 0.8.2
Deals' optional CRM integration (deal-view logging, opportunity resolution, status cascade) no longer crashes the process: it loads
@wabbit/tome-crm/server-apiinstead of./server.The unbundled
./serverimport hitserver-only's throwing module under Node's native loader, and the error escaped the try/catch. The tome-starter demo seed died at "seeding deals" because of it.With a tome-crm that predates
./server-api, the import fails as an ordinary error and the CRM side is skipped. - 0.8.1
Proposal views read "Opened proposal PROP-2026-0001" on the contact timeline instead of the raw key
proposal-viewed.recordCrmActivityWithDeduptakes an optionalsubjectfor a new row; without it the subject is still derived from the eventType.- tome-deals passes the proposal number as the subject when it logs a recipient view.
0.7.xMinor
BREAKING:
onStatusChangenow fires once on every deal status transition, including draft → sent and accepted → invoiced, not only on accepted, rejected and paid.Migration: a callback written for won/lost/paid outcomes only should branch on
deal.statusandprevStatusand ignore the rest.buildDealsCrmBridgefrom@wabbit/tome-crmneeds no change, but it now receivessenttransitions and records an email activity on the linked contact when a deal is sent; the automatic CRM bridge used whenonStatusChangeis unset does the same.The listener is called after the transition's side effect, on every write path (admin edit,
payload.update,advanceDealStatus), and never on a save that leaves the status unchanged. The built-incascadeOpportunityWonandcascadeOpportunityLostside effects are now no-ops andcascadeOpportunityPaidonly stampspaidAt: the listener is no longer called from side effects, so a transition cannot reach it twice.The keys stay registered, so workflows that reference them keep validating.
2 fixes (0.7.1 – 0.7.2)
- 0.7.2
Published packages now contain compiled JavaScript and type declarations under a one-line license banner, and no longer include source maps.
What you install: one compiled
.js(ESM) and.cjs(CommonJS) file per source module, its.d.ts/.d.ctsdeclarations, and the stylesheets, fonts and other assets a package already shipped. Every JavaScript module opens with a comment naming the package and its license:/*! @wabbit/<package> — © Wabbit, LLC. Wabbit Tome Commercial License (see LICENSE.md). Not for redistribution. */.The
.mapfiles and thesourceMappingURLcomments that pointed at them are gone, which roughly halves the size of each tarball.Debugging: the code is still unbundled and unminified, one readable file per module, so a stack trace points at real code with real names. Line numbers in a stack trace are one higher than before, because of the banner line.
A
'use client'directive stays the first statement of its module (the banner is a comment above it), so React Server Component boundaries are unchanged.No API change, no runtime behavior change, and nothing to do on upgrade.
In
@wabbit/tome-blocks-gallery, the source snapshotsextractGallerySourcewrites from an installed pack leave out the license banner line, so a component or config snapshot starts at the code and a paid block's preview shows its first 15 lines of real code. - 0.7.1
createDealsLayer({ productCollection: false })omits the line-itemproductrelationship, so Deals runs on a site with no catalog.Before this, the relationship to a missing product collection failed Payload's config validation at startup. Line items keep their name, price and quantity. The default (
'catalog-products') and custom slugs are unchanged.
0.6.xMinor
BREAKING: a default changed — see the Migration note below.
Status changes made by a direct update or an admin-panel edit now fire their transition side effect, and deal-number counters are admin-only to write.
- A status change through
payload.updateor the admin panel validated the transition but never ran its side effect (customer email, invoice number, CRM cascade). The deals collection now fires it once from anafterChangehook after the write persists;advanceDealStatusstill fires it itself and no longer risks a second run. deal-number-counterscreate/update/delete are now admin-only (deals:admin, or the legacy admin role); reads stay open to signed-in users. Deal-number generation writes withoverrideAccess, so reps creating deals are unaffected.- The line-item
productrelation now defaults tocatalog-products,@wabbit/tome-catalog's products slug, instead ofproducts. Migration: a site whose line items point at a collection namedproductswithout passingproductCollectionsetsproductCollection: 'products'. - Removed the unreachable
@wabbit/tome-printfallback from print dispatch;printAdapteris the only print path.
- A status change through
Deal and invoice numbering now counts existing numbers with
payload.count()instead of reading every matching deal.No API or behavior change.
customer-facing wording: internal references removed from admin descriptions, error messages and block metadata.
0.5.xMinor
Artifact types can opt into a block layout:
hasLayout: trueon aTomeDealArtifactTypeDefinitionadds alayoutblocks field (Layout tab) to deals of that type, fed by the newTomeDealsConfig.layoutBlocks.Configuring
hasLayoutwithoutlayoutBlocksthrows at config time.narrativeBodyis unchanged; existing artifact types are unaffected.
0.4.xMinor
Naming convergence (all additive; every old name keeps working as a
@deprecatedalias until that package's next major).create*is canonical for collection/layer factories (define*stays reserved for the blocks descriptor system): crm/deals/marketing/intake/forms gaincreate*Collectionnames for their formerdefine*Collectionfactories. Layer entries converge oncreateXLayer(config?) → bundle:createCrmLayer/createDealsLayer/createMarketingLayer/createCatalogLayer/createEconomyLayer/createChromeLayer/createLmsLayer/createAiLayer(+createFormsLayer/createIntakeLayer), returning bareCollectionConfig[]where the layer contributes only collections or an honest named bundle where it hands back more (chrome:{ globals }; lms/ai:{ collections, hooks }); void-returninginitCatalog/initEconomystay as the single registration call sites, delegated to internally.Naming note for forms consumers:
createFormsCollection(singular factory) vscreateFormsCollections(plural composer) vscreateFormsLayer(layer entry) — each docblock states the distinction.Email lookup paths adopt core's
normalizeEmailinstead of hand-rolled lowercasing: crm'sfind-contact-by-email/match-or-create-contact, and deals'create-from-intake— the latter was missing.trim(), so a padded intake email could fork a duplicate CRM contact.registerLayeris now statically imported (forms/intake pattern) instead of lazilyrequire()d in ten layer packages' init/register paths.The lazy pattern silently no-ops under Payload's native-ESM CLI (
generate:types/generate:importmap), so layer registration could vanish without error. Packages whose tome-core peer is genuinely optional (economy, ai, gamification) deliberately keep the guarded lazy path; tome-core'sadmin-nav/self-register.tsdeliberately keeps its subpathrequire()(documented ESM/CJS dual-cache fix — do not convert).Every package now declares an explicit
sideEffectsfield (38 added; motion/engine/forms already correct).Registration-bearing modules (render files'
registerRenderer,blocks/*/index.tsdefineBlockself-registration, widgetregister.tsfiles, productHooks, permission self-registrations, print templates, chrome built-in variants) are listed so bundlers can tree-shake everything else WITHOUT dropping import-time registrations — previously the field was unset, which blocked cross-module tree-shaking through the barrels entirely. Never blanketfalseon a package with registration or CSS.DRY adoption sweep (the audit's "adoption, not extraction" rule): crm/deals capability presets delegate to core's
sessionHasCapabilityOrLegacyAdmin; new corebuildOwnershipWhere/ownershipOrBypass(via./access) adopted by core's vendorScoped, catalog's vendor-scoping, and org's ownOrScoped (public APIs unchanged);slugField()adopted at 7 sites where semantics matched exactly (core lms collections + createMemberCollection — replacing a third independent slugify), with ~25 sites honestly skipped for named semantic divergences (auto-regenerate-on-clear vs allow-empty, collection-level hook pattern) now listed as core-enhancement candidates; newformatDisplayDatein blocks-core utilities (UTC-pinned, hydration-safe) adopted at 5 verified-identical sites; lms-ui consolidates its two certificate date formatters locally;useMediaQuery/useIsMobilepublished from tome-ui and adopted by AppShell + admin's SidebarProvider; gamification'sawardPointsnow uses the authoritativegetPointsBalance(fixes a divergent 1000-row scan cap vs the correct 10000).
7 fixes (0.4.1 – 0.4.3)
- 0.4.3
The bootstrap read fallback (any authenticated session passes
deals:read/deals:read:ownwhen the capability registry holds no grant) is now OFF in production by default, matching@wabbit/tome-crm0.6.0.A site mid-migration opts back in explicitly with
TOME_DEALS_BOOTSTRAP_READ_FALLBACK=1; any other value is not an opt-in. Non-production keeps the bridge open.Production logs one warning per process when access runs on the fallback. Found live on a public demo consumer where self-registered visitors could read deal pricing and embedded customer PII.
- 0.4.2
Adopt
@wabbit/tome-core/fields/addressand@wabbit/tome-core/utilities/relationIdat the sites the audit counted (2026-09-01 sale-readiness audit §5.1, T3(g)).No stored field name, and no emitted field array, changes anywhere in this changeset — each adopter passes the vocabulary it already stores, and each ships a characterization test that was written from the pre-change source, run green against the untouched factory, and run green again after.
Address group — five sites, one implementation.
@wabbit/tome-crm—accountsandcontactseach carried a byte-identical seven-fieldaddressgroup. Both now spreadpostalAddressFields({ vocabulary: 'legacy-crm' })after their ownnameline (nameis the company/contact line, not a postal line).tests/address-characterisation.test.tspins both groups whole.@wabbit/tome-deals—billingAddressandshippingAddressinside the frozen Customer Snapshot were copies three and four. They now come from onebuildSnapshotAddressGrouphelper:name+companyprepended locally, the six postal lines from core, and the eight per-field labels plus the'US'country default passed through core'sfieldOverridesseam. The snapshot is a legal-offer record frozen after send, so a field-name change would orphan the address on every deal already sent;tests/address-characterisation.test.tspins both groups and the fact that they differ only in the group label and the recipient line's label.@wabbit/tome-fulfillment— the fifth copy, and the only one that validatedcountry. Its postal lines stay FLAT at collection top level (they are stored columns with PII rows and a GDPR registration behind them), now viapostalAddressFields({ vocabulary: 'postal', required: true, validateCountry: true }). The ISO-3166 validator and its uppercase-normalizing hook moved into core verbatim; because a moved function is a new object,tests/address-characterisation.test.tspins the whole top-level field ORDER plus the validator's and hook's BEHAVIOR (acceptsUS, rejectsusa, rewrites' us 'to'US'), not their identity.
`relationId` — the four-return-types problem.
@wabbit/tome-lms— twelve modules undersrc/server(academy,catalog,certificates,course,dashboard,enrollment,grades,leaderboard,learnerShell,notes,profile,reviews) carried a byte-identicalstring | nullcopy. They importrelationIdfrom core now. One behavioral difference, strictly an improvement: on a malformed populated doc ({ id: null },{ id: {} }) the old copy returned the STRING'null'/'[object Object]'as an id; core returnsnull.tests/relation-id-adoption.test.tspins the adoption itself, because adoption is the thing that decays — the July 2026 audit's finding, repeated verbatim in September, was "extraction keeps happening, adoption does not."
Not migrated, deliberately:
src/guards,src/utilities/{grading,prerequisites,progress}.ts,src/hooks/**,src/server/mutations/helpers.tsandsrc/server/awardGate.tsreturnstring | numberorundefined. Migrating those is a semantic change, not an import change, and belongs in a pass that owns their call sites.The new test names them as out of scope so the next reader does not have to re-derive why.
@wabbit/tome-sc— the registry sub-cluster's copy is gone;collections/registry/shared.tsre-exports core'srelationId, keepingextractIdas a local alias (the module is private to that sub-cluster). This one WIDENS: the sc copy returnedstring | number, so a populated doc's numeric id came through unstringified. It is now stringified, which makes===between two resolved ids agree — the behavior every call site in the cluster already assumed. Ids handed back topayload.find/updateare unaffected, since Payload accepts either form in awhereclause. sc's 179 tests stay green.@wabbit/tome-crm— the inline ternary inintegration/deals.ts(typeof oppRaw === 'object' ? oppRaw.id : oppRaw) was the fifth shape and had the same numeric-id asymmetry; it is onerelationId(deal.opportunity)call now.
`fetchMemberId` ×4 — one implementation (sc).
asset-availability,fleet-logsandfleeteach carried a verbatim copy of the auth-user → Member-row lookup, andresource-requestscarried its projecting twin. All four now import fromsrc/access/fetchMemberId.ts, which documents why each query knob is load-bearing:overrideAccess: true(the member collection's own read access may itself depend on membership, so without the bypass this is a circular check that denies the owner their own row),depth: 0,pagination: false.The id is returned in its STORED type here rather than through
relationId— this is an identity read fed straight back into awhereclause, not a relationship read.tests/fleet-shared-helpers.test.tspins the adoption, the three knobs, and the null-for-anonymous contract. - 0.4.2
createKeyedRegistryin core, and the gate that keeps the next registry anchored.Tome had eleven keyed registries and two implementations of one idea: five anchored their state on
globalThisviaSymbol.for, six held a module-localMap(2026-09-01 sale-readiness audit §5.1, "same mechanism, half correct").The half that is wrong is wrong silently. A published package ships separate ESM and CJS builds — distinct module instances with distinct module-local state — so the moment one consumer static-imports one build and another
require()s the other, or a bundler splits an RSC/SSR/client graph, a module-localMapexists twice and a registration made through one is invisible through the other.Nothing throws; the handler just never fires.
layerRegistryshipped that bug in 2026-05 and moved ontoglobalThisin tome-core 1.0.10, both it and the render registry explain the mechanism at length in their headers, and six registries were written afterwards without it.A comment cannot make the next author read it.
New in core:
@wabbit/tome-core/registry/createKeyedRegistry(a NEW exports-map subpath — hence the minor).createKeyedRegistry<T>(symbolKey, { onDuplicate, validate })returns{ register, replace, get, has, list, clear }over a store anchored atglobalThis[Symbol.for(symbolKey)].onDuplicateis'throw'(default) /'replace'/'ignore', chosen to match each migrating registry's CURRENT behavior rather than a preferred one.replace()is the explicit override path every throw-on-duplicate registry in the repo already exposed for tests and consumer shadowing.The module's JSDoc carries the full migration recipe for the registries not migrated here. 14 unit tests, including the dual-instantiation proof: two separately-created registries on one key share a store, and the state survives a
vi.resetModules()re-evaluation of the defining module — a module-localMapfails both.Migrated in core:
gdpr/registry.ts. This one had BOTH halves of the defect — a module-localMapinsideGdprRegistryImpl, and absence from core's ownsideEffectsarray — while four layers (fulfillment, org, sc, plus consumer sites) register into it by import side effect.Split state meant
runErasure/exportUserDatareporting zero rows for collections registered into the other copy; a missingsideEffectsentry meant a bundler was free to drop the registering module outright. The store is now anchored (onDuplicate: 'replace', matchingregisterCollection's documented overwrite) and./dist/gdpr/registry.*is insideEffects, with asideEffectsRationaleblock in the manifest recording why each entry is there.The class API is unchanged — same names, arguments, semantics, and
getAll()'s registration-order guarantee.unregisterCollectionrebuilds the store minus one key (the helper exposes no per-key delete because nothing else needs one), preserving that order.Migrated in deals: both registries.
registry/side-effect-registry.tsis now a delegation shim over@wabbit/tome-workflow's registry (see the workflow-adoption changeset) — anchored by that route.registry/artifact-registry.tsmoves ontocreateKeyedRegistry, INCLUDING itsfrozenflag: a freeze applied to one module instance while another still accepted registrations would have enforced the config-time contract in exactly half the process. Public API, throws and messages are unchanged.This registry is populated in
payload.config.tsand read during collection construction, and under the Payload CLI those are separate module instances — the observable failure was anartifactTypeselect with no options and a thrown "Unknown artifact type".Forcing function:
scripts/assert-registry-anchoring.mjs+pnpm assert:registry-anchoring, wired intoplatform-discipline.ymlimmediately afterassert:no-forked-primitives(source + manifest reading only, so it runs pre-build and fails fast). Any module-scope mutableMap/Set/instance singleton whose name — or whose FILE name — announces a registry must importcreateKeyedRegistry, containSymbol.for(, or have its built path listed in the package'ssideEffectsarray; otherwise it fails with the migration recipe.Before this change it reported 3 violations (core's gdpr registry and both deals registries) and now reports 0.
Eight registries are ALLOWLISTED with a written architectural reason each, not a schedule: forms ×3, intake and print are owned by the forms+intake access wave and their file sets are off-limits to this one;
blocks-core/src/registry/index.tsis the deliberately explicit-instance DESCRIPTOR registry (ARCHITECTURE.md § Three Registry Mechanisms #2 — the registry that genuinely must be one store, the render registry, is separatelySymbol.for-anchored and passes), and changing it is a twelve-package linked-family decision; blocks-gallery's two are import-side-effect registries its own header already calls "the outlier, not the template", in a package with zero tests, so they migrate in the wave that gives it tests. - 0.4.2
One
LayerFactoryConfigevery layer factory's config extends, and one factory verb.Fourteen layer packages end in the same one call a consumer writes into
payload.config.ts, and no two agreed on whatconfigmay contain: full seam vocabulary in three (org, lms, ledger), partial in six, NONE in six (2026-09-01 sale-readiness audit §5.3). A site that learnedadminGroupfrom org andhooksfrom sc discovered, package by package, that six factories accept neither — not because the seam had been rejected, but because nothing said it existed.New in core (a NEW exports-map subpath, hence the minor):
@wabbit/tome-core/utilities/layerFactoryConfigexports theLayerFactoryConfiginterface —adminGroup,access(per-collection override map),hooks(appended viamergeHooks, never replacing),extraFields,fieldOverrides,omitFields,fieldOrder,slugs— andapplyLayerFactoryConfig(collections, config), which honors the whole vocabulary in one call and one fixed order (adminGroup → access → hooks → field shape, the last delegated tofields/fieldShape'sapplyFieldShapeso the order cannot drift between layers). Pure: new array, new objects, identity return on an empty config.It is a separate subpath from
./utilities/layerRegistrydeliberately — that module is in core'ssideEffectsarray, and a pure type/vocabulary module should not drag a declared side-effecting module into every factory's type graph.The slug convention is documented rather than forced, because both live shapes are right for what they do: a typed
slugs?: Partial<XSlugs>map for the slugs a layer OWNS (org, sc, accounts — the typed key set makes a typo a compile error, and a homomorphic mapped type satisfies the base'sRecord<string, string | undefined>), and named<name>Slug?: stringscalars for relationship targets in OTHER layers (memberSlug,mediaSlug,eventSlug,rolesSlug) — those are pointers out of a layer, not entries in its key set.*Every `createLayer
config now extends it.** Twelve extendLayerFactoryConfigdirectly and APPLY it throughapplyLayerFactoryConfig(accounts, catalog, crm, crowdfund, deals, fulfillment, lms, marketing, org, sc) or through a targeted application (chrome). Additive in every case: for the six that accepted none of the seams (deals, economy, gamification, marketing, plus forms/intake, see below), the fields are new; for the rest,adminGroup` and friends keep their existing meaning and the applier is a no-op when they are omitted.Two packages accept the vocabulary but do NOT yet apply it, and say so in their type's JSDoc in the required form ("accepted, not yet applied — trigger: …"). economy and gamification both declare
@wabbit/tome-coreas an OPTIONAL peer and hold zero runtime imports of it — gamification reachesregisterLayerthrough a lazyrequire()in a try/catch for exactly this reason.applyLayerFactoryConfigis a runtime VALUE, so importing it at module scope would convert an optional peer into a required one and break every site that installs those packages without core; copying the applier locally is barred byassert:no-forked-primitives. The trigger is stated: the day core becomes a required peer, delete the note and add one line.Both take the type via
import type, which is erased at runtime.Two packages drop seams EXPLICITLY rather than accept-and-ignore. chrome extends
Omit<LayerFactoryConfig, 'access' | 'hooks' | 'extraFields' | 'fieldOverrides' | 'omitFields' | 'fieldOrder' | 'slugs'>because it returns Payload GLOBALS, not collections — those seven are keyed by collection slug and typed againstCollectionConfig, and chrome's slugs already have direct per-surface knobs (header.slug,footer.slug) a parallel map could contradict.The one seam it keeps,
adminGroup, IS applied: globals carryadmin.groupexactly as collections do. rpg extendsOmit<LayerFactoryConfig, 'access'>becauseCharacterSheetsConfigis a single collection's config that doubles as the layer factory's config, and its ownaccessalready means "this collection's access object" — one level shallower than the base's slug-keyed map.Two meanings under one name is the confusion this interface exists to end.
Factory-verb convergence. Three verbs were live.
createWorkflowLayer(config?)is new in@wabbit/tome-workflow(a new export — hence the minor) and returns a spreadable, deliberately EMPTYCollectionConfig[]: this layer is an engine, not a collection set, so the empty array is the honest answer and lets...createWorkflowLayer()compose exactly like every sibling.Its
WorkflowLayerConfigomits every seam for the same reason, and exists as the stable place a real option will land.createGamificationLayerandcreateRpgLayerare pure aliases ofregisterGamificationLayer/registerRpgLayer.initWorkflow,registerGamificationLayerandregisterRpgLayerare all@deprecatedwith sunset at each package's next major; none is removed.Forcing function:
scripts/assert-layer-factory-contract.mjs+pnpm assert:layer-factory-contract, wired intoplatform-discipline.ymlafterassert:layer-version(source reading only, pre-build). Every exportedcreate*Layermust take a config parameter whose type resolves toLayerFactoryConfig— throughextends, an intersection, or an explicitOmit<…>— with verb aliases followed to theirregister*/init*target.Before this change it reported 12 violations and 0 conforming; it now reports 15 conforming, 0 violations. Deliberately NOT checked: whether a factory actually applies what it accepts, because a machine cannot tell a documented deferral from an accident, and a gate that forced silent application would be worse than one that forces a stated deferral.
docs/guides/create-a-new-layer-package.mdgains a "The factory contract" section stating the rule and the three permitted responses.Three factories are ALLOWLISTED with a reason each:
createAiLayerreturns credential wiring and owns no collections, so every seam is meaningless to it;createFormsLayerandcreateIntakeLayerare owned by the forms+intake access wave running in parallel, whose changes rewrite the same files.Peer floors: accounts, catalog, chrome, crm, deals, economy, fulfillment, gamification, marketing and rpg raise
@wabbit/tome-coreto>=1.14.0 <2.0.0. The new subpaths do not exist below that, and a too-low floor is howERR_PACKAGE_PATH_NOT_EXPORTEDreached crowdfund's consumers once already.These are marked
patchbecause the config widening is purely additive; the raised required-peer floor is the reason a release manager may prefer to cut them as minors instead. - 0.4.2
Manifest metadata:
homepage,bugs,engines.All 46 publishable manifests were missing the three fields a consumer sees before any code (2026-09-01 sale-readiness audit §6). Metadata only — no source, no build, no runtime change.
homepagedeep-links to that package README on GitHub (.../tree/main/packages/<dir>#readme). Without it a registry page links to the monorepo root and the reader has to guess which of 46 folders they want.bugs.urlpoints at the repo issue tracker, so a paying customer has a place to report a defect that is not email.engines.nodeis>=22, matching the rootenginesand.nvmrcset the same day. This is a real floor, not decoration: CI on Node 20 could not expand the glob the block packs use fornode --test, and a package installed on Node 20 fails at a runtime the installer cannot connect back to the version.
The forcing function ships with the change:
scripts/assert-manifest-metadata.mjs(rootpnpm assert:manifest-metadata, wired intoplatform-discipline.ymlbesideassert:license-metadata) fails when any publishable manifest lacksdescription,repository.directorymatching its own folder,homepage,bugs,engines.nodeequal to the repo floor,license,filesorsideEffects. It reported 138 violations before this change and 0 after. - 0.4.2
Delegates to
@wabbit/tome-workflow; local guards deprecated.@wabbit/tome-workflowis the extracted canonical home for the status-transition table and the keyed side-effect registry — its own module headers say so, naming deals as the source it was ported from — and none of the three packages that still shipped a copy depended on it (2026-09-01 sale-readiness audit §5.1). All three now declare@wabbit/tome-workflowas a required, explicitly non-optional peer (>=0.1.1 <1.0.0) with aworkspace:*devDependency twin, and all three raise their@wabbit/tome-corepeer floor to>=1.14.0 <2.0.0(see the LayerFactoryConfig changeset — the new core subpaths do not exist below it).deals — full delegation, five functions deprecated.
defineDealSideEffect,replaceDealSideEffect,getDealSideEffect,getRegisteredSideEffectKeysand_resetSideEffectRegistryare now thin wrappers overdefineWorkflowSideEffect/replaceWorkflowSideEffect/getWorkflowSideEffect/getRegisteredWorkflowSideEffectKeys/_resetWorkflowSideEffectRegistry, each@deprecatedwith sunset at the next major.findTransitionandvalidateWorkflowlikewise wrap workflow'sfindTransition/validateTransitionTable.resolveWorkflowandDEFAULT_DEAL_WORKFLOWare NOT deprecated: the default quote lifecycle is deals' own domain data, andresolveWorkflowresolves an artifact type's optional workflow override, a deals concept with no workflow-layer equivalent.Two consequences of the deals delegation are invisible at a call site and are stated in the module headers. First, the side-effect store moves from a module-local
MaptoglobalThiskeyed bySymbol.for— a FIX, not a byproduct: deals ships separate ESM and CJS builds, so a handler registered through one instance was invisible through the other, and the transition then advanced with its side effect silently skipped.Workflow's own header names deals' local
Mapas the hazard it deliberately did not repeat. Second, the key namespace is now shared with every other workflow consumer, so a duplicate key across two layers throws at registration instead of quietly shadowing — the intended duplicate policy in both packages.One behavior change to note:
validateWorkflow's returned message prefix is now[tome-workflow]rather than[tome-deals], because the validator is workflow's; that function shipped with zero call sites and zero tests.marketing — lookup delegated, three semantics kept local. The §9 campaign lifecycle is now published (module-scope, not from the barrel) as
MARKETING_CAMPAIGN_TRANSITION_TABLE, derived from the existing adjacency map so the two cannot disagree, and the allow decision plus the "allowed from here" list come from workflow'sfindTransition/allowedTransitionsFrom. The adjacency map is kept as the source it is derived from because a flat table cannot distinguish a deliberately terminal status (archived, empty list) from a status absent from the map entirely (data corruption) — this hook has always reported those as two different errors, and collapsing them would turn "your database has an unknown status" into "that transition is not permitted".buildStageTransitionGuardis NOT deprecated: it is a PayloadbeforeChangehook factory and workflow ships no hook;guardedTransitionis a server-side call that owns the write, and adopting it moves the transition out of the collection hook entirely. That is marketing's 1.0 question.crm — lookup delegated, three semantics kept local, and this is the one that could not be forced.
buildStageTransitionTable(stageConfig)projects aTomeCrmOpportunityStageConfigonto aWorkflowTransitionTable, and the allow decision comes from workflow. Three semantics stay local, each because delegating them would change behavior: (1) a stage that declares NOallowedTransitionsis UNCONSTRAINED in crm, and a transition table cannot distinguish "no edges declared" from "no edges permitted" — feeding those stages tofindTransitionwould turn crm's open-by-default pipeline into a closed one for every consumer whose config declares transitions on some stages and not others; (2) an unknown stage key is a misconfiguration reported as one, ahead of any transition check; (3) the lost-categorylossCategoryrequirement is a field-level data rule keyed off a stage'scategory, and hanging it onWorkflowTransition.guardwould make every consumer of the exported table inherit a crm write-validation rule.The rejection message now also names the legal moves from the previous stage, sourced from
allowedTransitionsFrom— strictly more diagnostic, same throw conditions.The deals↔CRM cascade re-entrancy handshake is untouched:
skipDealCascadeHooks(dealsstatus-transition-guard.ts) andtomeCrmSuppressStageDispatch(crmadvance-opportunity-stage.ts→stage-change-dispatch.ts) behave exactly as the 2026-06-11 cascade-semantics amendment D2 documents. Neither guard's participation in that handshake changed; crm's stage guard never participated in it at all.New suites pinning the delegation, one per package (
tests/workflow-delegation.test.ts, 12 + 9 + 8 assertions), each spying on the workflow module itself so a future edit that quietly restores a local copy fails a test rather than passing silently — which is exactly how the original fork survived four months of green CI. - 0.4.1
Wave 4 I0 hygiene: dist ships extensioned specifiers (fix-dist-extensions --strict + assert-node-loadable preflight — both dists now raw-Node loadable), registerLayer versions corrected and test-pinned to package.json, accounts' full @wabbit/tome-core/auth barrel import replaced by the auth/guards leaf (the barrel drags the BetterAuth plugin factory).
0.3.x
1 fix (0.3.1)
- 0.3.1
Core runtime-floor sweep: each package's
@wabbit/tome-corepeer floor now matches the newest core runtime export it actually imports, instead of the platform-wide>=1.0.0baseline from the original peer-range sweep.The stale floors let npm silently install a package next to a core version missing a module it runtime-imports, producing a hard
next buildfailure at import time (reproduced 2026-07-11: tome-starter locked core 1.0.12 + admin 0.6.3 —isAdminNavDomaindoes not exist in core 1.0.x, whereregistry/adminNavwas type-only).@wabbit/tome-admin→>=1.3.0 <2.0.0—nav/manifestResolverruntime-importsisAdminNavDomainfromregistry/adminNav, first shipped as a runtime export in core 1.3.0 (Sidebar v2 Wave 0, d8ff1b2).@wabbit/tome-deals→>=1.1.0 <2.0.0— runtime-importsauth/repScoping(buildRepWhereClauseet al.) andutilities/normalize(normalizeEmail), both introduced in core 1.1.0 (consolidation pass, a9801fe).@wabbit/tome-accounts→>=1.2.0 <2.0.0— runtime-importsauth/permissions(roleSatisfiesPermission, permission registration), introduced in core 1.2.0 (platform permission engine, 9238072).@wabbit/tome-org→>=1.2.0 <2.0.0— runtime-importsauth/permissions(checkPermissionHierarchicalet al.).@wabbit/tome-sc→>=1.2.0 <2.0.0— runtime-importsauth/permissionsacross access helpers and military collections.
Same defect class as the
tome-crmfloor raise to>=1.1.0(b027075);tome-crmis already correct and unchanged here.
0.2.xMinor
Add
hasFlatAmountartifact-type flag for priced-but-not-itemized deals.Artifact types with
hasFlatAmount: true(e.g. proposals, retainer agreements) now expose an editable `total` field that the human sets directly, instead of the line-items-computed total. This fills the gap where ahasLineItems: falseartifact had no price field at all —totalis the field downstream charge/email flows read.- Mutually exclusive with
hasLineItems(a type is either itemized or flat-priced). - Editability is enforced via field-level
access.update(Payload v3admin.readOnlyis boolean-only): editable for flat-amount types, read-only for itemized types wherecomputeDealTotalsHookremains the source of truth. - No change to
computeDealTotalsHook— it already skips any artifact type withhasLineItems !== true, so a flat-amount total is never clobbered.
- Mutually exclusive with
3 fixes (0.2.1 – 0.2.3)
- 0.2.3
Docs-manifest emitter pipeline (W3 ship-readiness).
@wabbit/tome-blocks-corenow ships a standalone Node ESM CLI atscripts/emit-docs-manifests.mjsthat emits per-package documentation manifests (index.json, packages/<slug>.json, changelog.json) by reading what packages already carry — READMEs, the payload-free<pkg>/metablock-usage barrels, package.json exports maps, and CHANGELOG.md. It is the docs-pipeline sibling of the gallery source extractor and is consumed by host sites at prebuild:node node_modules/@wabbit/tome-blocks-core/scripts/emit-docs-manifests.mjs --output-dir <dir> --scope <scope.json>.To let the emitter import block metadata uniformly without dragging Payload config into a build script, the
./metapayload-free subpath (BlockMetaEntry[]) is extended to the remaining offered blocks packs — agency-essentials, catalog-pack, lms-pack, org-pack, and signal-theme — mirroring the existing editorial-pack / marketing-starter / content-writer / extras barrels. Each block'sBlockMetawas relocated verbatim into a payload-free sibling meta module and re-imported by its block config; no meta values changed.Every supported-core package additionally adds
CHANGELOG.mdto its publishedfilesarray so the next publish cascade ships changelogs the emitter can read from installed tarballs at prebuild. - 0.2.2
Revert the 0.2.1
access.creategating ontotal— it broke the create form.0.2.1 added
access.createto make the itemizedtotalread-only on the create form, but Payload evaluates field access once at form-init with empty data and does NOT re-evaluate it reactively as the artifact type is selected (unlikeadmin.condition). The result wastotaldisabled for ALL types on the create form — including flat-amount proposals, breaking proposal entry.This restores 0.2.0 behavior:
totaleditable on the create form for every shown type, correctly gated read-only on the edit form viaaccess.update. For itemized types the create-form editability is cosmetic —computeDealTotalsHookoverwrites the value on save, so no incorrect total can persist.A code comment documents why create is intentionally ungated (fully-correct reactive gating would need a custom client Field component).
- 0.2.1
Fix flat-amount
totaleditability on the create form.hasFlatAmountgatedtotaleditability via fieldaccess.updateonly, but the create form is governed byaccess.create— so an itemized type'stotalrendered editable on create (cosmetic: the compute-totals hook overwrites it on save, but incorrect). Now gates bothcreateandupdatesymmetrically:totalis editable iff the artifact type ishasFlatAmount, on both forms.
0.1.xMinor
Initial release of the Tome Deals layer — a deal-lifecycle engine with a config-time artifact-type registry (quotes, proposals, SOWs, retainer agreements), per-artifact-type field gating, a default
draft → sent → accepted → invoiced → paidworkflow, and CRM cascade integration.- Artifact-type registry:
defineDealArtifactTyperegisters types beforeinitDeals(...); the defaultquoteartifact is preregistered.artifactTypeis aselectfrozen from the registry at config time, driving per-type field visibility via Payloadconditionclauses. - Two collections:
deals(the lifecycle collection with per-artifact-type field gating) anddeal-number-counters(independent per-artifact-type numbering, e.g.PROP-2026-0001,SOW-2026-0001). - Side-effect engine: five built-in side-effect handlers (
send-deal-email,stamp-invoice-number,cascade-opportunity-won/lost/paid); the CRM cascade firesadvanceOpportunityStagevia the deals→crm integration adapter only when@wabbit/tome-crmis registered (deals firesonStatusChange; crm ownsonDealStatusChange, no double-fire). - Server helpers + libs generalized from a shipped consumer's
Quotes.ts:computeDealTotals,generateDealNumber,advanceDealStatus,getDeal,createDealFromIntake, Resend-or-log email send. - Optional integrations (
crm,territory,print) lazy-loaded vialayerRegistry;@wabbit/tome-crmand@wabbit/tome-catalogare optional peers. - Legacy compat:
./legacy/quote-typessubpath re-exportsTomeQuote*aliases for one minor version to ease the migration from that consumer.
- Artifact-type registry:
4 fixes (0.1.1 – 0.1.3)
- 0.1.3
Consolidation pass (2026-06-10 audit dialect-drift findings) — the platform stops forking its own conventions.
tome-core (minor — new public APIs):
./auth/repScoping—buildRepWhereClause({ adminCapability, repField })+buildCapabilityScopedRead({ readCapability, adminCapability, repField })+sessionHasCapabilityOrLegacyAdmin+DENY_ALL_WHERE. The canonical "rows I own" access primitive, promoted from crm/deals' ~90%-identical copies (266 LOC → one parameterized implementation)../utilities/normalize—normalizeEmail(trim + lowercase). Email is the cross-layer join key; one normalizer, everywhere../fields/slug—formatSlugupgraded to the canonical algorithm (promoted from catalog's strictly-more-robust slugify: collapses whitespace/hyphen runs, trims edge hyphens); newbuildAutoSlugHook(sourceField, slugField)collection-level variant. Stored slugs untouched; only future generations on irregular-whitespace inputs differ.
catalog / org / crm / deals (patch): local copies replaced with delegations to the core primitives. Public names and signatures unchanged (
slugify,autoSlugHook,buildNormalizeEmailHook,normalizeDealEmail,repWhereClause,accountRepWhereClause,dealsRepWhereClause,dealsRepOrAdminWhereClause).Notably, org's auto-slug header had _claimed_ to wrap core's slugifier while carrying a divergent local copy — now it actually does.
- 0.1.3
Platform-wide peer-range sweep: every
workspace:*/workspace:^entry inpeerDependenciesreplaced with an explicit semver range (@wabbit/tome-core >=1.0.0 <2.0.0,tome-ui >=0.9.0 <1.0.0,tome-motion >=0.2.0 <1.0.0,tome-catalog >=1.1.0 <2.0.0,tome-admin >=0.5.0 <1.0.0;tome-crmranges standardized to>=0.2.0 <1.0.0).The workspace protocol publishes as an exact-version pin, so every substrate bump stranded installed dependents — the breakage class proven by marketing@0.1.0/deals@0.1.1 requiring
tome-crm@0.2.0exactly. devDependencies keepworkspace:*for the local link. (@wabbit/tome-admin-progot the same source fix but is rc-versioned; it carries the change on its next intentional release.)tome-crm additionally gains a once-per-process production warning when the capability-registry fallback grants access — the bootstrap heuristic (any authenticated user passes
crm:read) now announces itself instead of running silently on sites that forgot to seed capability grants (2026-06-10 audit hardening item).Graph-truth additions (same hygiene wave): tome-deals declares its lazy print integration as an optional peer (
@wabbit/tome-print >=0.1.0 <1.0.0); tome-intake declares its lazy catalog routing strategy (@wabbit/tome-catalog >=1.1.0 <2.0.0, optional). These were undeclared dynamic imports — invisible to consumers and to pnpm's build topology. - 0.1.2
Peer ranges widened —
@wabbit/tome-core,@wabbit/tome-crm, and@wabbit/tome-catalogpeers are now explicit semver ranges instead ofworkspace:*(which published as exact-version pins, breaking installs whenever a substrate package bumped, e.g. tome-crm 0.2.0 → 0.3.0). - 0.1.1
Auto-bridge the deal→CRM opportunity cascade.
The
cascadeOpportunityWon/Lost/Paidside-effects previously only forwarded toconfig.onStatusChange; when a consumer registered@wabbit/tome-crmbut didn't wireonStatusChange, the cascade was a silent no-op (accepting/rejecting/paying a deal never advanced the linked opportunity). They now fall back to a newdispatchDealStatusChangeToCrm(integration/crm.ts) that lazy-imports CRM'sonDealStatusChangeand runs the cascade whenever CRM is registered.A consumer-provided
onStatusChangestill takes precedence (no double-fire); CRM-absent stays a clean no-op. Consumers with a custom opportunity stage pipeline should still wireonStatusChangeexplicitly.No API/schema change — purely additive defensive wiring.