source: .forge/design/archive/core-reuse-feasibility.md · generated — edit the markdown, not this file

Reusable CRM Core — Feasibility Analysis

Status: analysis — adopted in full 2026-08-06 by developer decision (an earlier same-day reduced-scope adoption was withdrawn). See the adoption note below. Date: 2026-08-06 (Rev 1 same-day: recommendation revised after team size and timeline were confirmed) Author: Dinil (with Claude) Related: .forge/design/architecture.md § Core / Domain Separation, .forge/project-prd.md, .claude/CLAUDE.md Decision owner: engagement lead. This document proposes; it does not decide.

⚠️ Superseded — AD #29 (2026-09-07) then AD #31 (2026-09-09, FS-14). This analysis recommended, and (per the adoption note) drove, the reusable-core investment. Its premise — reuse of the generic layer on future projects (OQ-50) — is no longer expected, so the split was first stopped (AD #29) and then collapsed outright (AD #31 / FS-14): one Gradle module, one public schema, feature-first packages. Read this as the historical case for a decision since reversed. Current record: architecture.md § Core / Domain Separation (historical) and .claude/CLAUDE.md AD #17 / #29 / #31.


✅ Adoption note — read before §2

Adopted in full on 2026-08-06 by developer decision. architecture.md § Core / Domain Separation (Rev 5) implements this document’s Level 1 recommendation completely: the crm-core / domain-tea module layout (§5.1), typed 1:1 extension tables (§5.2), all ten extension points (§5.4), the four-layer enforcement stack (§6.1), the primitives in §6.3, and the frontend package split with a FieldRenderer registry. The Foundation Backlog grew 11 → 13 slices to carry it.

The acceptance test is explicit: deleting domain-tea must leave a clean, working generic CRM.

Cost accepted: the +8–15% in §9, which moves the estimate band to roughly 63–85 cycle-days against a ~55–65 working-day budget on a 2-developer team. §10 risk D (“compounds R-ARCH-001”) was raised and the decision reaffirmed; it proceeds as a deliberate investment and R-ARCH-001 tightens accordingly. (Basis superseded 2026-08-18: team of 3 full-stack developers, ~68–92 cycle-days against a 64-working-day dated window — see R-ARCH-001 in tracker.yaml.)

What this changes about §8 (distribution) and §11 (IP):

  • §8’s progression is unchanged — this is still not a published crm-core artifact. Fork at project two; extract a shared library only at project three.
  • §11 (IP) — assumed yes. Advice reported 2026-08-06 that there is no obstacle to reuse; full adoption proceeds on that basis. Tracked as OQ-50, not a blocker. §11 is retained as background only.

An earlier same-day note here proposed a reduced adoption (module split, ChecklistEngine and swappable tokens only, skipping extension tables and the SPI). That is withdrawn — it failed the acceptance test above by leaving tea columns on core tables. Where this document and architecture.md disagree, architecture.md is what is being built.

Superseded reduced-scope reasoning (retained for the record)

The recommendation in §2 was made while team size and delivery window were unknown. Both were confirmed hours later:

  • Team: 2 developers.
  • Timeline: committed. project-proposal.md § 7 — already issued — commits ~11–13 weeks to feature-complete with a day-for-day slippage clause. /forge-estimate puts the build at 58–74 cycle-days against a ~55–65 working-day budget.

§9 costed the recommended Level 1 at +8–15% of V1. Against two developers and that budget, there is nowhere for that to land — and it would be spent serving a second client who does not exist. §10 risk D (“compounds R-ARCH-001 — adding platform overhead to a team whose capacity is unconfirmed”) turned out to be the operative risk, and the mitigation it names — “resolve R-ARCH-001 first” — has now happened, with an unfavourable answer.

What was actually adopted (architecture.md § Core / Domain Separation) is the subset that pays for itself on this engagement regardless of any reuse ambition:

Adopted From this document
Module separation with a build-enforced one-way dependency §5.1 + §6.1 — but the placement discipline only, not the abstraction
A single ChecklistEngine + GateRule primitive, built with its first consumer in P1a §6.3 — the “pays for itself immediately” argument, which survives the cost pressure intact
A swappable design-token layer §6.2 — the one time-critical item

Explicitly not adopted: the typed extension tables (§5.2) and the ten extension points (§5.4) — the expensive half, and the half that would be guesswork against one known consumer. Tea attributes stay as ordinary typed columns. No published crm-core artifact (§8.6). No multi-tenancy (§7).

Net effect: this engagement buys the cheap half of the reuse option and defers the expensive half. The adopted items make a later extraction cheaper; they do not produce a reusable core. Deleting domain-tea after V1 would leave generic entities still carrying tea columns.

§11 (IP and contract) is unchanged and still governs the reuse claim — now tracked as OQ-50.

Everything below is the original analysis, preserved in full.


1. The question

Can the Empire Teas CRM be built so that its general-purpose CRM parts are separated from its tea-industry parts — such that a future CRM project for a different client can reuse the general-purpose parts instead of starting from scratch?

The client-facing framing is “reuse.” The engineering framing is: can a domain layer add first-class behaviour and typed fields to generic CRM entities without the generic layer ever referring to that domain?


2. Verdict

Feasible, and worth doing — at the lower of two ambition levels.

Recommendation
Do Separate generic and tea code into distinct modules inside the same repositories and the same deployable, with the separation enforced by the build system rather than by convention.
Do not (yet) Extract the generic part into a separately versioned, published library that client projects consume as a dependency.
Cost of the recommended option Approximately +8–15% on V1 effort. Unvalidated estimate — see §9.
Runtime impact None. Same deployment topology, same infrastructure, same hosting cost, same performance. This is a source-organisation change only.
Hard prerequisite The intellectual-property question in §11 must be resolved first. It can invalidate the entire exercise.

Three qualifiers, all material:

  1. The separation must be enforced by the build, not documented. A documented boundary erodes within weeks under delivery pressure.
  2. It must be treated as code placement, not as designing a generic product. Designing a reusable API against a single known client is how reusable APIs get built wrong.
  3. It is not multi-tenancy and must not be allowed to become multi-tenancy. See §7.4.

3. Why the starting position is favourable

Most attempts to extract a reusable core fail because the domain is woven through everything. That is not the case here, for a reason specific to this engagement.

The PRD is already around two-thirds generic CRM by feature count. The scope explicitly includes replicating the Pipedrive feature set so that migration loses nothing (project-prd.md §Problem Statement, and the P-01→P-34 Reference-System Classification table). Pipedrive is a generic CRM. A large block of V1 is therefore, by definition, general-purpose B2B CRM behaviour with no tea content.

3.1 Feature classification

Layer Features Count
Generic CRM F1 Accounts/Contacts · F2 Pipeline/Deals · F3 Activities · F5 Auth/Roles/Ownership · F17 Dashboard framework · F20 Email-in-CRM · F21 Calendar sync · F22 Contact sync · F23 Import/export · F24 Configurable pipelines · F25 Sequences · F26 Products catalog (base) · F31 Global search · F32 List views/filters/bulk actions · F33 Attachments · F34 Custom fields 16
Generic mechanism, tea-specific data F7 Quote readiness gate · F9 Certification mismatch · F10 Export-doc rules · F18 Stale/rotting alerts · F19 Handoff-on-Won · F11–F16 AI layer 11
Irreducibly tea F6 Sample rounds (partly) · F8 Product briefs · Buying Standard + weekly bulk pricing · the certification / grade / Incoterm taxonomies · all AI prompts ~5
Disposable adapter F4 Pipedrive field mapping (the import engine is generic; the Pipedrive column map is throwaway) 1

The middle row is where the leverage is — see §6.3.

3.2 Three existing decisions already point this way

The architecture locked at Gate 2 already contains the necessary instinct:

Decision What it establishes
AD #6 — AI isolated behind an AIProvider interface Vendor-specific code behind a named seam. Half of the AI-layer separation is already conceptually done.
AD #10 — ErpHandoffService seam for the ERP handoff Outbound integration behind a named seam as an established pattern.
AD #11 — stage_type held separately from a stage’s display name Stable semantic identity separated from mutable presentation — precisely the discipline this separation needs.

This is not a green-field proposal. It is a formalisation of a separation the architecture already half-implements.


4. Where the entanglement actually is

The intuitive reading — “F6/F8/F9/F10 are the tea features, isolate those” — is wrong, and planning around it would surface the real problem months into delivery.

The entanglement is at the field level, inside otherwise generic entities. From project-prd.md §Domain Model:

Entity Generic attributes Tea attributes embedded in it
Account name, country, region, owner, contacts required certifications, preferred packaging, default Incoterm
Deal title, value, currency, stage, owner, expected close volume (kg/MT), held certifications, brand
Product name, code, price, cost, tax, category grade, origin, held certifications, brand, 1:N Buying Standards with weekly market-differentiated pricing
Quote line items, status, aging, revisions Incoterm, destination port, payment terms, gross-profit floor, the 8-item tea readiness checklist
Contact, Activity, Email, Sequence, Saved View, Custom Field — none — genuinely clean

So the question is not “can the features be separated.” It is:

Can the tea layer add first-class typed fields to a generic entity without the generic entity knowing tea exists?

4.1 Why the existing custom-fields mechanism cannot solve this

The natural instinct is to use the JSONB custom_fields column already decided in AD #8. That path is closed, and deliberately so.

project-prd.md P-09 states that tea-domain attributes — grade, certifications, packaging, Incoterm, volume units — are first-class typed fields, with F34’s JSONB reserved for admin-defined fields layered on top. Pushing the tea domain into JSONB would:

  • lose type safety and database-level validation,
  • degrade query and filter performance on fields that are filtered constantly,
  • and contradict a Gate-1 decision.

The correct mechanism is extension tables. See §5.2.


5. Proposed design

5.1 Module layout

Backend — one deployable, Gradle multi-module (Groovy DSL — AD #18):

crm-core/                    ← must NEVER depend on any domain module
  core-platform/             User, Role, Permission, Session, Audit log, correlation IDs
  core-crm/                  Account, Contact, Deal, Pipeline, Stage, Activity, Note, Timeline
  core-commerce/             Product (base), LineItem, Quote (base), price + validity primitives
  core-comms/                Email sync/send/templates/tracking, Calendar sync, Contact sync, Sequences
  core-datamgmt/             Import/export engine, CustomFieldDefinition, SavedView, Global search, Attachments
  core-workflow/             ChecklistEngine, GateRule, TagSetCompatibility, RoundLifecycle, StaleClock (rotting)
  core-ai/                   AIProvider, prompt-catalog registry, schema validation, provenance, human-approval queue, batch dispatch
  core-integration/          HandoffService seam, webhook/poll ingestion substrate, per-mailbox rate limiter

domain-tea/                  ← depends on crm-core; the reverse is a compile error
  tea-catalog/               grade, origin, held certifications, brand, BuyingStandard, weekly pricing
  tea-compliance/            certification taxonomy, mismatch rule, export document-rule catalog
  tea-samples/               sample rounds on core RoundLifecycle, taster ownership, courier/tracking
  tea-privatelabel/          ProductBrief and its blocking open questions
  tea-quoting/               8-item readiness checklist definition, gross-profit floor gate, Incoterm/destination
  tea-ai/                    prompts and extraction schemas (inquiry, triage, briefing, quote flags)
  tea-erp/                   ErpHandoffService implementation (manual document, later IFS)

app/                         Spring Boot bootstrap; wires core + domain; ONE ECS task, unchanged

Frontend — npm/pnpm workspace:

packages/core-ui/            Swappable design tokens, atoms, ListView, KanbanBoard, DetailShell,
                             FilterBar, SearchPalette, CalendarView, admin-config shells,
                             field-renderer registry
packages/core-crm-ui/        Generic screens: accounts, deals, activities, quotes, products, admin
packages/domain-tea-ui/      Tea field renderers, sample board, brief form, certification-mismatch
                             panel, export-document checklist, weekly-pricing screens —
                             registered into the core shells
apps/web/                    React SPA (Vite — AD #21); theme = Empire tokens; composes the above

Dependency direction, in both stacks:

flowchart LR
  app[app / apps-web] --> domain[domain-tea]
  app --> core[crm-core]
  domain --> core
  core -.->|"never"| domain

The deployment topology in architecture.md does not change. Same single ECS Fargate service, same worker, same RDS instance, same SQS queue. Nothing about hosting, cost, or performance moves.

Database:

  • Separate Postgres schemas — core.* and tea.* — or table prefixes.
  • Flyway migration folders per module: db/migration/core/, db/migration/tea/.
  • Foreign keys may point tea → core. Never core → tea. This is the database-level statement of the same rule, and it is mechanically checkable in CI.

5.2 The extension mechanism — how the tea layer adds typed fields

Rather than one table carrying both generic and tea columns, use two tables in a one-to-one relationship, with the second owned entirely by the domain module.

Instead of:

-- generic and tea mixed: the separation is already lost
customers (id, name, country, owner_id, required_certs, packaging, incoterm)

use:

core.account              (id, name, country, owner_id, region, custom_fields jsonb)
tea.account_profile       (account_id  PK/FK → core.account,
                           required_certifications  text[],
                           preferred_packaging      text,
                           default_incoterm         text)

core.account contains no tea column. tea.account_profile is additive and can be dropped without touching the generic table.

The domain module registers its extension with the core at startup, so that generic machinery — list views, filters, global search, the detail drawer, import/export — can surface domain fields without knowing what they are:

registry.register(EntityExtension.of(Account.class, TeaAccountProfile.class)
    .withFields(...)      // makes them appear in list views, filters, search
    .withValidation(...)  // typed validation, not a JSONB free-for-all
    .withRenderer("tea/account-profile"));   // frontend renderer key

The core knows there is an extension. It never knows the word “tea.”

Trade-off, stated plainly: one additional join per entity fetch. At the PRD’s stated scale — 10–20 concurrent users, thousands of records (§NFR Performance) — this is immaterial. At millions of rows it would deserve revisiting. It is the correct call at this scale.

5.3 How generic code calls domain code without importing it

This is the mechanism that makes the boundary possible, and it is the same regardless of which reuse approach is eventually chosen.

The core defines an interface. It contains no domain reference:

// crm-core
public interface EntityExtension<T> {
    Class<T> entityType();
    List<FieldDefinition> extraFields();
}

The core service asks the framework for every implementation that happens to exist:

// crm-core
@Service
public class AccountService {
    private final List<EntityExtension<?>> extensions;

    // Spring injects every EntityExtension found on the classpath at startup.
    // Core has no idea how many exist, or what domain they belong to.
    public AccountService(List<EntityExtension<?>> extensions) {
        this.extensions = extensions;
    }
}

The domain module supplies one:

// domain-tea — this module imports crm-core. Never the reverse.
@Component
public class TeaAccountExtension implements EntityExtension<Account> {
    public Class<Account> entityType() { return Account.class; }
    public List<FieldDefinition> extraFields() {
        return List.of(
            field("requiredCertifications", MULTI_SELECT),
            field("preferredPackaging",     TEXT),
            field("defaultIncoterm",        ENUM));
    }
}

At startup Spring scans for implementations and hands them to AccountService as a list. The compile-time dependency arrow points one way only — domain-tea → crm-core — while the runtime call flows the other way.

This is dependency inversion: the core owns the interface, the domain owns the implementation. Substituting domain-spice for domain-tea requires no change to core; it simply finds different implementations in the list.

5.4 The full set of extension points

The complete surface area the core must expose. Ten seams — a bounded, enumerable list, which is itself evidence that the separation is tractable.

# Extension point What the domain supplies Serves
1 EntityExtension<T> Typed one-to-one extension tables plus field metadata Account / Deal / Product / Quote tea fields
2 StageTypeProvider Additional stage_type values beyond core’s NEW / WON / LOST F24, AD #11
3 ChecklistDefinition + GateRule Named checklists and blocking rules on a state transition F7, F8, F10, F19
4 TagSetRequirement The taxonomy to compare (certifications) F9
5 RoundLifecycle config State names, vocabulary, “where it’s stuck” rules F6
6 PromptCatalog + ExtractionSchema Prompts and JSON output schemas F11–F16
7 MetricProvider KPI and widget definitions F17
8 PriceModel Buying Standard, weekly cadence, destination-market dimension F26 bulk pricing
9 HandoffTarget ERP payload shape and generator F19
10 FieldRenderer (frontend) React components for domain field types All domain UI inside core shells

6. Enforcement, and the primitives worth building

6.1 The boundary must be enforced by the machine

A documented rule will not hold. Under delivery pressure someone will reference a tea type inside generic code, no one will notice in review, and within a month the separation is fiction. It has to fail the build.

Mechanism What it does Effort
Build-graph separation crm-core modules simply do not declare a dependency on domain-tea. Java can only see what is on its classpath, so referencing a tea class from core is a compile error — not a review comment. This alone does most of the work. Near zero
ArchUnit tests A test library that asserts rules about code structure. Add package-dependency rules, plus a banned-vocabulary rule: no identifier matching tea|grade|certification|incoterm|auction|sample|brand|buying.?standard may appear anywhere in crm-core. Catches leakage by name before it becomes structural. Low
Frontend import rules ESLint no-restricted-imports denying *domain-* inside core-ui, plus separate workspace packages. dependency-cruiser for the whole-graph rule. Low
Database check in CI Assert that no core.* table holds a foreign key into tea.*. Low
Process — spec-template change Add a ## Layer Classification section to _TEMPLATE-spec.md: every spec states core / domain / both, and if both, names which extension point carries the split. Trivial

Example ArchUnit rule — an ordinary unit test that fails the build like any other:

@Test
void coreMustNotDependOnAnyDomain() {
    noClasses().that().resideInAPackage("..crm.core..")
        .should().dependOnClassesThat().resideInAPackage("..crm.domain..")
        .check(new ClassFileImporter().importPackages("com.yourco"));
}

The spec-template change is the highest-leverage item on the list relative to its cost. It moves the “core or domain?” question to spec time, when answering it is free, rather than to review time, when it is not. This is the compounding-engineering pattern already established in .claude/CLAUDE.md.

6.2 One item is time-critical

Almost everything in this document can wait for a decision. One item cannot.

Foundation Backlog slice 3 currently produces “Design tokens (warm tea palette, Fraunces/Inter per the client-approved prototype)”. If those values are baked into components rather than consumed as swappable semantic tokens, the generic UI layer becomes permanently Empire-branded, and re-theming it later means editing hundreds of components.

Making the token layer swappable — components consume semantic tokens, the application supplies the palette — costs almost nothing during Foundation and is expensive to retrofit. This decision happens at the very start of frontend work, so it is worth settling early even if everything else is parked.

6.3 Primitives that pay for themselves on this project alone

This is the argument that moves the proposal from “a cost accepted for future benefit” to “something worth doing regardless.”

Five features in the PRD are the same pattern:

Feature Behaviour
F7 The 8-item readiness checklist blocks quote submission
F8 Blocking open questions prevent a product brief reaching “complete”
F9 Required-vs-held certification mismatch blocks quoting
F10 Export document set — base + country + certification — toggled as assembled
F19 Handoff readiness (quote approved / certs verified / brief complete) blocks ERP handoff

All five are instances of one thing: a data-driven set of rules, evaluated against a record, that blocks a state transition and reports which items failed and why.

Built independently, that is five implementations and five sets of defects. Built once as a core ChecklistEngine plus GateRule primitive with domain-supplied rule definitions, it is one implementation and five configurations — and it is simultaneously among the most reusable assets in the core, because approval gates are universal in B2B software.

The same argument applies, more weakly, to:

  • RoundLifecycle (F6) — a multi-round prepare → dispatch → deliver → await feedback → outcome cycle with per-round owner, due date, days-in-state, and a computed “where it’s stuck” reason. Generic to sample and proof cycles in many industries. Generalise the shape; keep the vocabulary in tea-samples.
  • StaleClock (F18/F24) — the rotting mechanism is already fully generic. Nothing about it is tea-specific.
  • core-ai (F11–F16) — the orchestration is generic and non-trivial: assemble context, call the provider, validate the JSON response against a schema, persist with source and confidence and an “edited by you” flag, route to the human-approval queue, write the audit entry, batch through SQS, and route by model tier (Haiku vs Sonnet). The domain supplies only prompts and schemas.

Guardrail on that last point. The PRD’s entire justification for building custom software rather than configuring a SaaS product is tea-domain AI (§Problem Statement, P-21). The core takes the orchestration only. The prompts stay in tea-ai and stay rich. If “make the AI layer generic” is ever allowed to become “make the prompts generic,” the product’s differentiator has been traded away to serve a hypothetical second client. This is a line to state explicitly and defend.


7. What not to abstract

Equally important, and usually omitted from proposals like this.

Do not abstract Reason
Multi-tenancy Unrelated to reuse. A reusable codebase is a source-code property; multi-tenancy is a runtime data-partitioning property with very large cost. project-prd.md §Multi-Tenancy explicitly specifies single-tenant, single-organization. Project #2 gets its own single-tenant deployment from the same core. If these two ideas are conflated, the estimate triples and a PRD decision is violated.
Buying Standard / weekly bulk pricing Irreducibly tea. A pricing engine flexible enough to express it generically would be flexible enough to express nothing well.
Certification / grade / Incoterm taxonomies Reference data, not structure. The core provides TagSet; the tags are domain.
F4 Pipedrive field mapping Disposable adapter. The import engine is core; the Pipedrive column map is throwaway.
Dashboard metrics The widget framework is core. Every actual KPI — “samples overdue for feedback”, “quotes aging beyond 7 days” — is domain.
Export document catalog The rules engine (base + country + attribute-derived set) is semi-generic for any export business. The document list itself is tea.
The AI prompts See §6.3. This is the product.

8. How reuse would actually work

Separating the code is necessary but not sufficient — “we will reuse it” is meaningless until the distribution mechanism is named. There are three, and they form a progression rather than a set of alternatives.

8.1 The three options

Option A — Fork the project Option B — Starter template Option C — Shared library
Mechanism Copy the Empire repo, delete domain-tea, write domain-<next> Maintain a separate clean generic repo with no client content; copy that for each new project The generic part is published as a versioned package; client projects declare it as a dependency
Generic code physically present in the new project? Yes, all of it Yes, all of it No — one dependency line
Can a developer edit generic code for one client? Yes, freely Yes, freely No
Do fixes reach existing projects? No No Yes
Can you break a live client? No No Yes
Infrastructure required None A template repository A private package registry plus a publish pipeline
Ongoing burden None Maintaining the starter Versioning, releases, changelogs, backward compatibility, support
Scales with client count? Poorly — fix N times Poorly — fix N times Well

Options A and B are the same strategy. B is a tidier front door: a clean starter avoids the risk of leaving stray tea code behind. But the moment a project is created from the template, it is an independent copy and stops receiving improvements. B does not solve the duplication problem. It also adds a third artefact to maintain, and starters go stale quickly when no real project uses them.

8.2 The central trade-off

Copying gives freedom but improvements do not spread. Sharing spreads improvements but you can break existing clients.

Concretely — a defect is found in email sync six months after the second project starts:

Option A/B Option C
Fix the generic code ✅ ✅
Empire receives the fix ❌ — fix separately ✅ — bump the version
Spice receives the fix ❌ — fix separately ✅ — bump the version
Total fixes 3 1

At two projects, fixing twice is mildly annoying, and the ability to freely modify generic code for an unusual client is genuinely useful. At five projects, fixing five times is untenable.

When Do Why
Now (1 project) Build the module boundary only. Choose no distribution mechanism. There is no second project to design against.
Project 2 Fork (Option A) You will learn which parts are actually generic versus which merely looked generic. This is almost always surprising.
Project 3 Extract the shared library (Option C) Three real examples make it possible to see what genuinely recurs, rather than guessing.

The reasoning is standard and worth stating explicitly: do not build the shared version until the thing has been built two or three times. A first attempt at “generic” is shaped by the single client that existed. The second client wants it differently, and the abstraction is found to be wrong — at which point it is expensive to change, because a live client depends on it.

8.4 What is identical across all three options

  • The module split (crm-core / domain-tea)
  • The extension-point pattern of §5.4
  • Dependency inversion — core defines interfaces, domain implements them (§5.3)
  • The extension tables (§5.2)
  • ArchUnit and ESLint enforcement rules (§6.1)
  • Every line of application code

All of the engineering is the same. Option C adds packaging, publishing and versioning on top. The difference is distribution machinery, not design — which is precisely why the work can be done now and the distribution decision deferred without rework.

8.5 Technical mechanics — Option A/B (fork or template)

Repositories

crm-starter-backend      clean generic backend, no domain. Never deployed.
crm-starter-frontend     clean generic frontend, no domain. Never deployed.
empire-teas-crm          a real client project

The starter repos are marked as template repositories (a GitHub setting that adds a “Use this template” action).

Creating a project. gh repo create spice-crm --template crm-starter-backend produces a new repository whose files are identical to the starter’s. The technically significant detail: it copies files but not git history. The new repository begins with a single commit and has no git relationship to the starter — no shared ancestor, no remote link. That is precisely why fixes do not flow: git does not know the repositories are related.

Bootstrap script. The copy still carries starter naming, so a one-time setup script (./init.sh --client spice --package com.yourco.spicecrm --db spice_crm) handles the mechanical work:

  • Rewrite the Java package name across every file and physically move directories, because in Java the package name must match the directory structure.
  • Rewrite artifactId / name in pom.xml or build.gradle, and name in package.json.
  • Set the database name in application.yml.
  • Create an empty domain-spice/ module and register it in the build file.
  • Replace the README; git init; first commit.

Tools that formalise this: Cookiecutter, Yeoman, or JHipster (Spring-specific and close to this use case). A shell script is adequate.

Database. Everything is in one project, so Flyway simply reads from both folders:

spring:
  flyway:
    locations:
      - classpath:db/migration/core
      - classpath:db/migration/tea

Migrations run in version order; Flyway records what it has applied in flyway_schema_history. No complication.

8.6 Technical mechanics — Option C (shared library)

What a package is. A package (npm) or artifact (Java) is compiled code, zipped, stamped with a name and version. The project already consumes dozens: a pom.xml entry for spring-boot-starter-web does not copy Spring’s source — Maven downloads a .jar, caches it in ~/.m2/repository, and places it on the classpath. Option C does exactly this with crm-core.

Where it is stored. Public packages live on Maven Central and npmjs.com. A private registry is required here: GitHub Packages (simplest to start), AWS CodeArtifact (fits the existing AWS account structure), or Sonatype Nexus / JFrog Artifactory (self-hosted). Functionally it is an authenticated HTTP server storing versioned zip files.

Repository layout

crm-core                 its own repo. Builds and publishes a .jar. Never deployed.
empire-teas-crm          small repo: tea code plus a dependency declaration
spice-crm                small repo: spice code plus a dependency declaration
<dependency>
  <groupId>com.yourco</groupId>
  <artifactId>crm-core</artifactId>
  <version>2.4.0</version>
</dependency>

That single declaration replaces the entire generic codebase that Option A/B would have copied into the folder.

Versioning becomes a contract. Semantic versioning — MAJOR.MINOR.PATCH:

Change Meaning
2.4.0 → 2.4.1 Bug fix only. Safe upgrade.
2.4.0 → 2.5.0 New capability added; existing code still works. Safe.
2.4.0 → 3.0.0 Something was renamed or changed incompatibly. Client projects must be edited.

This is a real discipline, not a formality: it is what tells a client project’s team whether upgrading is a one-line change or a week of work. Getting it wrong breaks a production system.

How the library wires itself in. A genuine wrinkle. In Option A/B, Spring’s component scan starts at the application’s package root and finds everything, because it is all under one root. In Option C, crm-core classes live under com.yourco.crmcore.* while the application lives under com.yourco.empireteas.* — the default scan will not look inside the library.

The correct mechanism is Spring Boot auto-configuration, the same one every Spring Boot starter uses. Add to crm-core:

src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports

containing one line naming a configuration class:

@AutoConfiguration
@ComponentScan("com.yourco.crmcore")
@EnableJpaRepositories("com.yourco.crmcore")
@EntityScan("com.yourco.crmcore")
public class CrmCoreAutoConfiguration { }

Any Spring Boot application that merely has crm-core on its classpath then receives all its services, entities and repositories automatically — the same mechanism by which adding spring-boot-starter-web provides an embedded web server. In effect you would be building your own Spring Boot starter. Well-trodden, but a thing to know and maintain.

Database migrations — the genuinely awkward part. This is the largest hidden cost of Option C and the strongest reason to defer it.

crm-core ships migrations inside its jar; domain-tea ships its own. Flyway orders migrations by version and keeps a single history table. If core ships V5__add_column.sql and tea also has a V5, they collide. Worse, if core releases a new V4 after a client has already applied its own V6, Flyway sees a migration arriving out of order and — by default — refuses to run, failing startup.

Available fixes, none free:

Approach Trade-off
Version-space partitioning — core owns V1–V999, domain starts at V1000 Crude but effective and easy to explain
Separate Flyway instances with separate history tables and Postgres schemas Cleanest; more configuration
outOfOrder: true Convenient, but forfeits the guarantee that every environment applied migrations in the same sequence — exactly the guarantee wanted in production

Frontend. Same idea, different ecosystem. packages/core-ui is published (npm publish --registry=...), and client projects install it:

"dependencies": { "@yourco/crm-core-ui": "^2.4.0" }

The ^ means “2.4.0 or any later 2.x”, so patches and minor versions arrive on npm install while a 3.x never does without an explicit change. Two extra requirements Java does not have: the package must be compiled and bundled before publishing (TypeScript to JavaScript, plus .d.ts type-definition files so consumers get type checking and autocomplete — via tsup or vite build --lib), and react must be declared a peer dependency, meaning the consuming application supplies React rather than the library bundling its own copy. Two copies of React in one application break hooks in hard-to-diagnose ways.

The release process becomes an owned responsibility.

edit → test → decide the version bump → build → publish to registry → update changelog
     → notify client projects → each project bumps its version → runs its tests → deploys

This can be automated in CI, but somebody owns it. This — not the technology — is the real cost of Option C. It is an ongoing job that does not currently exist.


9. Cost

These are unvalidated engineering estimates, not commitments. They cannot be converted into dates: architecture.md §Resource & Timeline Reality records that no delivery window has been supplied, and R-ARCH-001 (team capacity, composition and skills-fit unconfirmed) remains open. /forge-estimate is the harness mechanism once Gate 3 phases exist.

Area Delta Reasoning
Foundation +25–40% Grows from 8 slices to roughly 11: module skeleton and CI enforcement, extension-point substrate, swappable token layer plus field-renderer registry. Slices 1, 2 and 3 each get modestly heavier.
Generic features (F1–F5, F17, F20–F26, F31–F34) +10–20% Designing an extension seam rather than simply adding a column.
Domain features (F6–F10, F19, bulk pricing) ~0%, plausibly negative If ChecklistEngine lands first, F7/F8/F10/F19 become rule definitions rather than four bespoke implementations.
AI layer (F11–F16) +5% AIProvider already exists per AD #6; a prompt-catalog registry is incremental.
V1 overall +8–15% Weighted across the above.

Why this lands near 10% rather than near 100%: roughly two-thirds of the feature set is already generic in shape, and the tea features largely attach to core entities rather than interleave with them. The work is formalising a seam the PRD’s own structure already implies. That is the central feasibility finding.

Return. On a second CRM project, Foundation and roughly 16 of ~30 features’ worth of substrate are already built — accounts, contacts, deals, pipelines, activities, email, calendar, import, search, list views, attachments, custom fields, sequences, auth, audit and AI orchestration — and already hardened by a real production deployment.


10. Risks

ID Risk Severity Mitigation
A Speculative generality — abstractions designed for one consumer are usually wrong for the second, and the cost is paid twice: once to build, once to unpick High Apply the rule of two. Commit only to code placement and dependency direction; defer every genuine abstraction except the §6.3 primitives that pay for themselves on this project alone.
B Boundary erosion under delivery pressure High Enforce in CI from day one (§6.1). Build-graph separation plus ArchUnit plus the spec-template question — not a review convention.
C Client funds a platform they did not commission — Empire Teas is paying for a tea CRM; the +8–15% is time not spent on their features High An explicit commercial decision. Either Empire funds it knowingly, or it is absorbed as internal investment. It must not be done silently.
D Compounds R-ARCH-001 — adding structural overhead to a team whose capacity and skills-fit are unconfirmed Medium Resolve R-ARCH-001 first. This proposal should not be committed to before team capacity is known.
E AI differentiator diluted if “generic AI layer” is allowed to become “generic prompts” Medium The hard line in §6.3. Prompts remain in tea-ai permanently.
F Gate 2 reopening — this modifies locked architectural decisions Low / procedural Requires a Gate 2 Run 2 entry or a documented addendum plus new AD rows, per .claude/rules/tracker.md § Gate Audit Protocol. Not a silent edit to architecture.md.
G Theme baked into components during Foundation slice 3 Medium, time-boxed Cheap now, expensive later. Decide before frontend work begins (§6.2).

11. Prerequisite: intellectual property and contract

This is not a technical question, and it outranks everything above.

Does the Empire Teas engagement contract assign ownership of the delivered software to Empire Teas? Many custom-build agreements do, and some add exclusivity or non-compete terms covering derived works.

If so, then however cleanly crm-core is separated, there may be no contractual right to deploy it for another client — in which case the exercise delivers no commercial value while costing 8–15% of V1.

Usual resolutions, in order of preference:

  1. The contract carves out background / reusable IP: Empire owns the tea-domain modules and holds a perpetual licence to the core; the supplier retains ownership of crm-core. Standard, and usually uncontroversial when raised openly at the right time.
  2. Empire owns everything, with a non-exclusive reuse licence back to the supplier for non-domain-specific components.
  3. Empire owns everything outright with no carve-out → do not build the separation for reuse. The Level-1 module boundary may still be worth doing for maintainability reasons — the ChecklistEngine and the module structure improve this codebase regardless — but the reuse justification disappears and the business case must stand on internal quality alone.

Recommended action: raise as a new engagement-level open question in project-prd-signals.md (Blocks: —, since it blocks no specific feature), with this analysis blocked on its resolution. It is a client and legal conversation, not an engineering one.


12. Proposed changes if adopted

None of the following has been applied. This is the change-set for the engagement lead’s decision.

Prerequisites, before any code

  1. Resolve the IP and contract question (§11) — new open question in project-prd-signals.md.
  2. Resolve R-ARCH-001 (team capacity, composition, skills-fit) — the §9 estimate is meaningless without it.
  3. Reach an explicit commercial decision on who funds the +8–15% (§10, risk C).

Architecture artefacts

  1. New rows in .claude/CLAUDE.md § Architecture Decisions (DO NOT REVERSE):
    • #12 — Core/domain module split; crm-core may never depend on domain-tea; enforced at build-graph and ArchUnit level.
    • #13 — Domain extends core entities via typed one-to-one extension tables registered through an extension-point registry — not via the F34 JSONB mechanism, which remains reserved for admin-defined fields, preserving P-09.
    • #14 — Frontend design tokens are a swappable theme layer; core UI components carry no client-specific brand values.
  2. New ## Core / Domain Layering section in .forge/design/architecture.md — the module map (§5.1), the extension-point table (§5.4) and the enforcement mechanisms (§6.1).
  3. Foundation Backlog grows from 8 slices to approximately 11:
    • (new) Module skeleton and dependency enforcement — build-graph rules, ArchUnit, dependency-cruiser, the foreign-key check.
    • (new) Extension-point substrate and entity-extension registry.
    • (new) core-workflow primitives — ChecklistEngine, GateRule, TagSetCompatibility, RoundLifecycle, StaleClock.
    • (revised) Slice 3 — design tokens become a swappable theme plus a field-renderer registry.
    • (revised) Slice 2 — Flyway split into per-module migration paths; core / tea schema separation.
  4. New risks: R-ARCH-002 (boundary erosion), R-ARCH-003 (speculative generality).
  5. _TEMPLATE-spec.md gains a ## Layer Classification section (§6.1).

Process

  1. This constitutes a Gate 2 reopening. It requires a ## Gate 2 Run 2 entry in .forge/engagement-gate-runs.md with the developer’s verdict, plus the corresponding setup.architecture update in .forge/tracker.yaml. Per .claude/rules/tracker.md, the gate verdict is the developer’s, not Claude’s.

13. Summary

The separation is architecturally feasible at low-to-moderate cost, for reasons specific to this engagement rather than generic optimism: the PRD is already roughly two-thirds Pipedrive-parity generic CRM; the tea domain attaches to core entities rather than permeating them; and three Gate-2 decisions (AIProvider, ErpHandoffService, stage_type) already establish the necessary seam discipline. The entanglement is real but bounded — it lives at the field level within about six entities, and ten extension points cover it.

Recommended course:

  • Build the enforced module boundary (not a published library).
  • Build the ChecklistEngine and the swappable token layer regardless of the reuse question, because both improve this project on their own merits.
  • Enforce the boundary in CI from day one, or do not claim to have one.
  • Defer the choice of reuse mechanism until a second project exists; fork for project 2, extract a shared library at project 3.

And resolve the IP question first — it is the only finding here capable of rendering the other twelve sections moot.


Appendix — terms used

Term Meaning
Artifact / package Compiled code, zipped, stamped with a name and version. A .jar (Java) or a published npm package.
Classpath The set of compiled code available to a running or compiling Java program. Code not on the classpath does not exist as far as the compiler is concerned.
Dependency inversion The generic layer defines an interface; the specific layer implements it. Lets generic code invoke specific code at runtime without referencing it at compile time.
Extension table A second table in one-to-one relationship with a main table, holding additional typed columns, owned by a different module.
Semantic versioning MAJOR.MINOR.PATCH. Patch = fix, minor = compatible addition, major = breaking change.
Package / artifact registry An authenticated server storing versioned packages. Public: Maven Central, npmjs.com. Private: GitHub Packages, AWS CodeArtifact, Nexus, Artifactory.
Auto-configuration Spring Boot’s mechanism by which a library on the classpath registers its own components automatically, with no configuration in the consuming application.
Component scan Spring’s startup process of finding annotated classes and wiring them together. By default it starts at the application’s own package root.
Peer dependency An npm declaration meaning “the consuming application must provide this library” — used for React so a library does not bundle a second copy.
ArchUnit A Java test library for asserting rules about code structure (which packages may reference which). Failures fail the build like any other test.
Multi-tenancy One running system serving multiple separate customer organisations with partitioned data. Unrelated to code reuse, and explicitly out of scope in this PRD.
Template repository A GitHub setting allowing a repository to be copied into a new one. Copies files but not git history — the copies are permanently unrelated.
Rule of two Wait until a second real consumer exists before generalising an abstraction.

Generated from .forge/design/archive/core-reuse-feasibility.md by .claude/lib/render-docs-html.js. Markdown is canonical.